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
fetch.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::RequestBinding::RequestInfo; use dom::bindings::codegen::Bindings::RequestBinding::RequestInit; use dom::bindings::codegen::Bindings::ResponseBinding::ResponseBinding::ResponseMethods; use dom::bindings::codegen::Bindings::ResponseBinding::ResponseType as DOMResponseType; use dom::bindings::error::Error; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::{Trusted, TrustedPromise}; use dom::bindings::reflector::DomObject; use dom::bindings::root::DomRoot; use dom::bindings::trace::RootedTraceableBox; use dom::globalscope::GlobalScope; use dom::headers::Guard; use dom::promise::Promise; use dom::request::Request; use dom::response::Response; use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use js::jsapi::JSAutoCompartment; use net_traits::{FetchChannels, FetchResponseListener, NetworkError}; use net_traits::{FilteredMetadata, FetchMetadata, Metadata}; use net_traits::CoreResourceMsg::Fetch as NetTraitsFetch; use net_traits::request::{Request as NetTraitsRequest, ServiceWorkersMode}; use net_traits::request::RequestInit as NetTraitsRequestInit; use network_listener::{NetworkListener, PreInvoke}; use servo_url::ServoUrl; use std::mem; use std::rc::Rc; use std::sync::{Arc, Mutex}; use task_source::TaskSourceName; struct FetchContext { fetch_promise: Option<TrustedPromise>, response_object: Trusted<Response>, body: Vec<u8>, } /// RAII fetch canceller object. By default initialized to not having a canceller /// in it, however you can ask it for a cancellation receiver to send to Fetch /// in which case it will store the sender. You can manually cancel it /// or let it cancel on Drop in that case. #[derive(Default, JSTraceable, MallocSizeOf)] pub struct FetchCanceller { #[ignore_malloc_size_of = "channels are hard"] cancel_chan: Option<ipc::IpcSender<()>> } impl FetchCanceller { /// Create an empty FetchCanceller pub fn new() -> Self { Default::default() } /// Obtain an IpcReceiver to send over to Fetch, and initialize /// the internal sender pub fn initialize(&mut self) -> ipc::IpcReceiver<()> { // cancel previous fetch self.cancel(); let (rx, tx) = ipc::channel().unwrap(); self.cancel_chan = Some(rx); tx } /// Cancel a fetch if it is ongoing pub fn cancel(&mut self) { if let Some(chan) = self.cancel_chan.take()
} /// Use this if you don't want it to send a cancellation request /// on drop (e.g. if the fetch completes) pub fn ignore(&mut self) { let _ = self.cancel_chan.take(); } } impl Drop for FetchCanceller { fn drop(&mut self) { self.cancel() } } fn from_referrer_to_referrer_url(request: &NetTraitsRequest) -> Option<ServoUrl> { request.referrer.to_url().map(|url| url.clone()) } fn request_init_from_request(request: NetTraitsRequest) -> NetTraitsRequestInit { NetTraitsRequestInit { method: request.method.clone(), url: request.url(), headers: request.headers.clone(), unsafe_request: request.unsafe_request, body: request.body.clone(), destination: request.destination, synchronous: request.synchronous, mode: request.mode.clone(), use_cors_preflight: request.use_cors_preflight, credentials_mode: request.credentials_mode, use_url_credentials: request.use_url_credentials, origin: GlobalScope::current().expect("No current global object").origin().immutable().clone(), referrer_url: from_referrer_to_referrer_url(&request), referrer_policy: request.referrer_policy, pipeline_id: request.pipeline_id, redirect_mode: request.redirect_mode, cache_mode: request.cache_mode, ..NetTraitsRequestInit::default() } } // https://fetch.spec.whatwg.org/#fetch-method #[allow(unrooted_must_root)] pub fn Fetch(global: &GlobalScope, input: RequestInfo, init: RootedTraceableBox<RequestInit>) -> Rc<Promise> { let core_resource_thread = global.core_resource_thread(); // Step 1 let promise = Promise::new(global); let response = Response::new(global); // Step 2 let request = match Request::Constructor(global, input, init) { Err(e) => { promise.reject_error(e); return promise; }, Ok(r) => r.get_request(), }; let mut request_init = request_init_from_request(request); // Step 3 if global.downcast::<ServiceWorkerGlobalScope>().is_some() { request_init.service_workers_mode = ServiceWorkersMode::Foreign; } // Step 4 response.Headers().set_guard(Guard::Immutable); // Step 5 let (action_sender, action_receiver) = ipc::channel().unwrap(); let fetch_context = Arc::new(Mutex::new(FetchContext { fetch_promise: Some(TrustedPromise::new(promise.clone())), response_object: Trusted::new(&*response), body: vec![], })); let listener = NetworkListener { context: fetch_context, task_source: global.networking_task_source(), canceller: Some(global.task_canceller(TaskSourceName::Networking)) }; ROUTER.add_route(action_receiver.to_opaque(), Box::new(move |message| { listener.notify_fetch(message.to().unwrap()); })); core_resource_thread.send( NetTraitsFetch(request_init, FetchChannels::ResponseMsg(action_sender, None))).unwrap(); promise } impl PreInvoke for FetchContext {} impl FetchResponseListener for FetchContext { fn process_request_body(&mut self) { // TODO } fn process_request_eof(&mut self) { // TODO } #[allow(unrooted_must_root)] fn process_response(&mut self, fetch_metadata: Result<FetchMetadata, NetworkError>) { let promise = self.fetch_promise.take().expect("fetch promise is missing").root(); // JSAutoCompartment needs to be manually made. // Otherwise, Servo will crash. let promise_cx = promise.global().get_cx(); let _ac = JSAutoCompartment::new(promise_cx, promise.reflector().get_jsobject().get()); match fetch_metadata { // Step 4.1 Err(_) => { promise.reject_error(Error::Type("Network error occurred".to_string())); self.fetch_promise = Some(TrustedPromise::new(promise)); self.response_object.root().set_type(DOMResponseType::Error); return; }, // Step 4.2 Ok(metadata) => { match metadata { FetchMetadata::Unfiltered(m) => { fill_headers_with_metadata(self.response_object.root(), m); self.response_object.root().set_type(DOMResponseType::Default); }, FetchMetadata::Filtered { filtered,.. } => match filtered { FilteredMetadata::Basic(m) => { fill_headers_with_metadata(self.response_object.root(), m); self.response_object.root().set_type(DOMResponseType::Basic); }, FilteredMetadata::Cors(m) => { fill_headers_with_metadata(self.response_object.root(), m); self.response_object.root().set_type(DOMResponseType::Cors); }, FilteredMetadata::Opaque => self.response_object.root().set_type(DOMResponseType::Opaque), FilteredMetadata::OpaqueRedirect => self.response_object.root().set_type(DOMResponseType::Opaqueredirect) } } } } // Step 4.3 promise.resolve_native(&self.response_object.root()); self.fetch_promise = Some(TrustedPromise::new(promise)); } fn process_response_chunk(&mut self, mut chunk: Vec<u8>) { self.body.append(&mut chunk); } fn process_response_eof(&mut self, _response: Result<(), NetworkError>) { let response = self.response_object.root(); let global = response.global(); let cx = global.get_cx(); let _ac = JSAutoCompartment::new(cx, global.reflector().get_jsobject().get()); response.finish(mem::replace(&mut self.body, vec![])); // TODO //... trailerObject is not supported in Servo yet. } } fn fill_headers_with_metadata(r: DomRoot<Response>, m: Metadata) { r.set_headers(m.headers); r.set_raw_status(m.status); r.set_final_url(m.final_url); }
{ // stop trying to make fetch happen // it's not going to happen // The receiver will be destroyed if the request has already completed; // so we throw away the error. Cancellation is a courtesy call, // we don't actually care if the other side heard. let _ = chan.send(()); }
conditional_block
suspicious_splitn.rs
#![warn(clippy::suspicious_splitn)] fn main() { let _ = "a,b,c".splitn(3, ','); let _ = [0, 1, 2, 1, 3].splitn(3, |&x| x == 1); let _ = "".splitn(0, ','); let _ = [].splitn(0, |&x: &u32| x == 1); let _ = "a,b".splitn(0, ',');
let _ = "a,b".rsplitn(0, ','); let _ = "a,b".splitn(1, ','); let _ = [0, 1, 2].splitn(0, |&x| x == 1); let _ = [0, 1, 2].splitn_mut(0, |&x| x == 1); let _ = [0, 1, 2].splitn(1, |&x| x == 1); let _ = [0, 1, 2].rsplitn_mut(1, |&x| x == 1); const X: usize = 0; let _ = "a,b".splitn(X + 1, ','); let _ = "a,b".splitn(X, ','); }
random_line_split
suspicious_splitn.rs
#![warn(clippy::suspicious_splitn)] fn main()
{ let _ = "a,b,c".splitn(3, ','); let _ = [0, 1, 2, 1, 3].splitn(3, |&x| x == 1); let _ = "".splitn(0, ','); let _ = [].splitn(0, |&x: &u32| x == 1); let _ = "a,b".splitn(0, ','); let _ = "a,b".rsplitn(0, ','); let _ = "a,b".splitn(1, ','); let _ = [0, 1, 2].splitn(0, |&x| x == 1); let _ = [0, 1, 2].splitn_mut(0, |&x| x == 1); let _ = [0, 1, 2].splitn(1, |&x| x == 1); let _ = [0, 1, 2].rsplitn_mut(1, |&x| x == 1); const X: usize = 0; let _ = "a,b".splitn(X + 1, ','); let _ = "a,b".splitn(X, ','); }
identifier_body
suspicious_splitn.rs
#![warn(clippy::suspicious_splitn)] fn
() { let _ = "a,b,c".splitn(3, ','); let _ = [0, 1, 2, 1, 3].splitn(3, |&x| x == 1); let _ = "".splitn(0, ','); let _ = [].splitn(0, |&x: &u32| x == 1); let _ = "a,b".splitn(0, ','); let _ = "a,b".rsplitn(0, ','); let _ = "a,b".splitn(1, ','); let _ = [0, 1, 2].splitn(0, |&x| x == 1); let _ = [0, 1, 2].splitn_mut(0, |&x| x == 1); let _ = [0, 1, 2].splitn(1, |&x| x == 1); let _ = [0, 1, 2].rsplitn_mut(1, |&x| x == 1); const X: usize = 0; let _ = "a,b".splitn(X + 1, ','); let _ = "a,b".splitn(X, ','); }
main
identifier_name
lib.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/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of in script so that the devtools crate can be //! modified independently of the rest of Servo. #![crate_name = "style_traits"] #![crate_type = "rlib"] #![deny(unsafe_code, missing_docs)] #![cfg_attr(feature = "servo", feature(plugin))] extern crate app_units; #[macro_use] extern crate cssparser; extern crate euclid; #[cfg(feature = "servo")] extern crate heapsize; #[cfg(feature = "servo")] #[macro_use] extern crate heapsize_derive; extern crate rustc_serialize; #[cfg(feature = "servo")] #[macro_use] extern crate serde_derive; /// Opaque type stored in type-unsafe work queues for parallel layout. /// Must be transmutable to and from `TNode`. pub type UnsafeNode = (usize, usize); /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport
/// `ViewportPx` is equal to `DeviceIndependentPixel` times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one `PagePx` is equal to one `DeviceIndependentPixel`. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(Clone, Copy, Debug)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. /// /// `PagePx` is equal to `ViewportPx` multiplied by a "viewport zoom" factor controlled by the user. /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. #[derive(Clone, Copy, Debug)] pub enum PagePx {} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => DeviceIndependentPixel // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx pub mod cursor; #[macro_use] pub mod values; pub mod viewport; pub use values::{ToCss, OneOrMoreCommaSeparated};
///
random_line_split
lib.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/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of in script so that the devtools crate can be //! modified independently of the rest of Servo. #![crate_name = "style_traits"] #![crate_type = "rlib"] #![deny(unsafe_code, missing_docs)] #![cfg_attr(feature = "servo", feature(plugin))] extern crate app_units; #[macro_use] extern crate cssparser; extern crate euclid; #[cfg(feature = "servo")] extern crate heapsize; #[cfg(feature = "servo")] #[macro_use] extern crate heapsize_derive; extern crate rustc_serialize; #[cfg(feature = "servo")] #[macro_use] extern crate serde_derive; /// Opaque type stored in type-unsafe work queues for parallel layout. /// Must be transmutable to and from `TNode`. pub type UnsafeNode = (usize, usize); /// One CSS "px" in the coordinate system of the "initial viewport": /// http://www.w3.org/TR/css-device-adapt/#initial-viewport /// /// `ViewportPx` is equal to `DeviceIndependentPixel` times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one `PagePx` is equal to one `DeviceIndependentPixel`. However, if the /// document is zoomed in or out then this scale may be larger or smaller. #[derive(Clone, Copy, Debug)] pub enum ViewportPx {} /// One CSS "px" in the root coordinate system for the content document. /// /// `PagePx` is equal to `ViewportPx` multiplied by a "viewport zoom" factor controlled by the user. /// This is the mobile-style "pinch zoom" that enlarges content without reflowing it. When the /// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size /// as the viewable area. #[derive(Clone, Copy, Debug)] pub enum
{} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => DeviceIndependentPixel // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx pub mod cursor; #[macro_use] pub mod values; pub mod viewport; pub use values::{ToCss, OneOrMoreCommaSeparated};
PagePx
identifier_name
main.rs
// Copyright 2015-2017 Intecture Developers. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate futures; extern crate intecture_api; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate tokio_core; extern crate tokio_proto; extern crate tokio_service; extern crate toml; mod errors; use error_chain::ChainedError; use errors::*; use futures::{future, Future}; use intecture_api::host::local::Local; use intecture_api::host::remote::JsonLineProto; use intecture_api::{FromMessage, InMessage, Request}; use std::fs::File; use std::io::{self, Read}; use std::net::SocketAddr; use std::result; use std::sync::Arc; use tokio_core::reactor::Remote; use tokio_proto::streaming::Message; use tokio_proto::TcpServer; use tokio_service::{NewService, Service}; pub struct Api { host: Local, } pub struct
{ remote: Remote, } impl Service for Api { type Request = InMessage; type Response = InMessage; type Error = Error; type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; fn call(&self, req: Self::Request) -> Self::Future { let request = match Request::from_msg(req) .chain_err(|| "Malformed Request") { Ok(r) => r, Err(e) => return Box::new(future::ok(error_to_msg(e))), }; Box::new(request.exec(&self.host) .chain_err(|| "Failed to execute Request") .then(|mut result| match result { Ok(mut msg) => { let mut reply = msg.get_mut(); reply = format!("{\"Ok\":\"{}\"}", reply); future::ok(msg) }, Err(e) => future::ok(error_to_msg(e)) })) } } impl NewService for NewApi { type Request = InMessage; type Response = InMessage; type Error = Error; type Instance = Api; fn new_service(&self) -> io::Result<Self::Instance> { // XXX Danger zone! If we're running multiple threads, this `unwrap()` // will explode. The API requires a `Handle`, but we can only send a // `Remote` to this Service. Currently we force the `Handle`, which is // only safe for the current thread. // See https://github.com/alexcrichton/tokio-process/issues/23 let handle = self.remote.handle().unwrap(); Ok(Api { host: Local::new(&handle).wait().unwrap(), }) } } #[derive(Deserialize)] struct Config { address: SocketAddr, } quick_main!(|| -> Result<()> { env_logger::init().chain_err(|| "Could not start logging")?; let matches = clap::App::new("Intecture Agent") .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(env!("CARGO_PKG_DESCRIPTION")) .arg(clap::Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .help("Path to the agent configuration file") .takes_value(true)) .arg(clap::Arg::with_name("addr") .short("a") .long("address") .value_name("ADDR") .help("Set the socket address this server will listen on (e.g. 0.0.0.0:7101)") .takes_value(true)) .group(clap::ArgGroup::with_name("config_or_else") .args(&["config", "addr"]) .required(true)) .get_matches(); let config = if let Some(c) = matches.value_of("config") { let mut fh = File::open(c).chain_err(|| "Could not open config file")?; let mut buf = Vec::new(); fh.read_to_end(&mut buf).chain_err(|| "Could not read config file")?; toml::from_slice(&buf).chain_err(|| "Config file contained invalid TOML")? } else { let address = matches.value_of("addr").unwrap().parse().chain_err(|| "Invalid server address")?; Config { address } }; // XXX We can only run a single thread here, or big boom!! // The API requires a `Handle`, but we can only send a `Remote`. // Currently we force the issue (`unwrap()`), which is only safe // for the current thread. // See https://github.com/alexcrichton/tokio-process/issues/23 let server = TcpServer::new(JsonLineProto, config.address); server.with_handle(move |handle| { Arc::new(NewApi { remote: handle.remote().clone(), }) }); Ok(()) }); fn error_to_msg(e: Error) -> InMessage { let response: result::Result<(), String> = Err(format!("{}", e.display_chain())); // If we can't serialize this, we can't serialize anything, so // panicking is appropriate. let value = serde_json::to_value(response) .expect("Cannot serialize ResponseResult::Err. This is bad..."); Message::WithoutBody(value) }
NewApi
identifier_name
main.rs
// Copyright 2015-2017 Intecture Developers. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate futures; extern crate intecture_api; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate tokio_core; extern crate tokio_proto; extern crate tokio_service; extern crate toml; mod errors; use error_chain::ChainedError; use errors::*; use futures::{future, Future}; use intecture_api::host::local::Local; use intecture_api::host::remote::JsonLineProto; use intecture_api::{FromMessage, InMessage, Request}; use std::fs::File; use std::io::{self, Read}; use std::net::SocketAddr; use std::result; use std::sync::Arc; use tokio_core::reactor::Remote; use tokio_proto::streaming::Message; use tokio_proto::TcpServer; use tokio_service::{NewService, Service}; pub struct Api { host: Local, } pub struct NewApi { remote: Remote, } impl Service for Api { type Request = InMessage; type Response = InMessage; type Error = Error; type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; fn call(&self, req: Self::Request) -> Self::Future
} impl NewService for NewApi { type Request = InMessage; type Response = InMessage; type Error = Error; type Instance = Api; fn new_service(&self) -> io::Result<Self::Instance> { // XXX Danger zone! If we're running multiple threads, this `unwrap()` // will explode. The API requires a `Handle`, but we can only send a // `Remote` to this Service. Currently we force the `Handle`, which is // only safe for the current thread. // See https://github.com/alexcrichton/tokio-process/issues/23 let handle = self.remote.handle().unwrap(); Ok(Api { host: Local::new(&handle).wait().unwrap(), }) } } #[derive(Deserialize)] struct Config { address: SocketAddr, } quick_main!(|| -> Result<()> { env_logger::init().chain_err(|| "Could not start logging")?; let matches = clap::App::new("Intecture Agent") .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(env!("CARGO_PKG_DESCRIPTION")) .arg(clap::Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .help("Path to the agent configuration file") .takes_value(true)) .arg(clap::Arg::with_name("addr") .short("a") .long("address") .value_name("ADDR") .help("Set the socket address this server will listen on (e.g. 0.0.0.0:7101)") .takes_value(true)) .group(clap::ArgGroup::with_name("config_or_else") .args(&["config", "addr"]) .required(true)) .get_matches(); let config = if let Some(c) = matches.value_of("config") { let mut fh = File::open(c).chain_err(|| "Could not open config file")?; let mut buf = Vec::new(); fh.read_to_end(&mut buf).chain_err(|| "Could not read config file")?; toml::from_slice(&buf).chain_err(|| "Config file contained invalid TOML")? } else { let address = matches.value_of("addr").unwrap().parse().chain_err(|| "Invalid server address")?; Config { address } }; // XXX We can only run a single thread here, or big boom!! // The API requires a `Handle`, but we can only send a `Remote`. // Currently we force the issue (`unwrap()`), which is only safe // for the current thread. // See https://github.com/alexcrichton/tokio-process/issues/23 let server = TcpServer::new(JsonLineProto, config.address); server.with_handle(move |handle| { Arc::new(NewApi { remote: handle.remote().clone(), }) }); Ok(()) }); fn error_to_msg(e: Error) -> InMessage { let response: result::Result<(), String> = Err(format!("{}", e.display_chain())); // If we can't serialize this, we can't serialize anything, so // panicking is appropriate. let value = serde_json::to_value(response) .expect("Cannot serialize ResponseResult::Err. This is bad..."); Message::WithoutBody(value) }
{ let request = match Request::from_msg(req) .chain_err(|| "Malformed Request") { Ok(r) => r, Err(e) => return Box::new(future::ok(error_to_msg(e))), }; Box::new(request.exec(&self.host) .chain_err(|| "Failed to execute Request") .then(|mut result| match result { Ok(mut msg) => { let mut reply = msg.get_mut(); reply = format!("{\"Ok\":\"{}\"}", reply); future::ok(msg) }, Err(e) => future::ok(error_to_msg(e)) })) }
identifier_body
main.rs
// Copyright 2015-2017 Intecture Developers. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. extern crate clap; extern crate env_logger; #[macro_use] extern crate error_chain; extern crate futures; extern crate intecture_api; #[macro_use] extern crate serde_derive; extern crate serde_json; extern crate tokio_core; extern crate tokio_proto; extern crate tokio_service; extern crate toml; mod errors; use error_chain::ChainedError; use errors::*; use futures::{future, Future}; use intecture_api::host::local::Local; use intecture_api::host::remote::JsonLineProto; use intecture_api::{FromMessage, InMessage, Request}; use std::fs::File; use std::io::{self, Read}; use std::net::SocketAddr; use std::result; use std::sync::Arc; use tokio_core::reactor::Remote; use tokio_proto::streaming::Message; use tokio_proto::TcpServer; use tokio_service::{NewService, Service}; pub struct Api { host: Local, } pub struct NewApi { remote: Remote, } impl Service for Api { type Request = InMessage; type Response = InMessage; type Error = Error; type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; fn call(&self, req: Self::Request) -> Self::Future { let request = match Request::from_msg(req) .chain_err(|| "Malformed Request") { Ok(r) => r, Err(e) => return Box::new(future::ok(error_to_msg(e))), }; Box::new(request.exec(&self.host) .chain_err(|| "Failed to execute Request") .then(|mut result| match result { Ok(mut msg) => { let mut reply = msg.get_mut(); reply = format!("{\"Ok\":\"{}\"}", reply); future::ok(msg) }, Err(e) => future::ok(error_to_msg(e)) })) } } impl NewService for NewApi { type Request = InMessage; type Response = InMessage; type Error = Error; type Instance = Api; fn new_service(&self) -> io::Result<Self::Instance> { // XXX Danger zone! If we're running multiple threads, this `unwrap()` // will explode. The API requires a `Handle`, but we can only send a // `Remote` to this Service. Currently we force the `Handle`, which is // only safe for the current thread. // See https://github.com/alexcrichton/tokio-process/issues/23 let handle = self.remote.handle().unwrap(); Ok(Api { host: Local::new(&handle).wait().unwrap(), }) } } #[derive(Deserialize)] struct Config { address: SocketAddr, }
quick_main!(|| -> Result<()> { env_logger::init().chain_err(|| "Could not start logging")?; let matches = clap::App::new("Intecture Agent") .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(env!("CARGO_PKG_DESCRIPTION")) .arg(clap::Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .help("Path to the agent configuration file") .takes_value(true)) .arg(clap::Arg::with_name("addr") .short("a") .long("address") .value_name("ADDR") .help("Set the socket address this server will listen on (e.g. 0.0.0.0:7101)") .takes_value(true)) .group(clap::ArgGroup::with_name("config_or_else") .args(&["config", "addr"]) .required(true)) .get_matches(); let config = if let Some(c) = matches.value_of("config") { let mut fh = File::open(c).chain_err(|| "Could not open config file")?; let mut buf = Vec::new(); fh.read_to_end(&mut buf).chain_err(|| "Could not read config file")?; toml::from_slice(&buf).chain_err(|| "Config file contained invalid TOML")? } else { let address = matches.value_of("addr").unwrap().parse().chain_err(|| "Invalid server address")?; Config { address } }; // XXX We can only run a single thread here, or big boom!! // The API requires a `Handle`, but we can only send a `Remote`. // Currently we force the issue (`unwrap()`), which is only safe // for the current thread. // See https://github.com/alexcrichton/tokio-process/issues/23 let server = TcpServer::new(JsonLineProto, config.address); server.with_handle(move |handle| { Arc::new(NewApi { remote: handle.remote().clone(), }) }); Ok(()) }); fn error_to_msg(e: Error) -> InMessage { let response: result::Result<(), String> = Err(format!("{}", e.display_chain())); // If we can't serialize this, we can't serialize anything, so // panicking is appropriate. let value = serde_json::to_value(response) .expect("Cannot serialize ResponseResult::Err. This is bad..."); Message::WithoutBody(value) }
random_line_split
array.rs
//! Array with SIMD alignment use crate::types::*; use ffi; use num_traits::Zero; use std::ops::{Deref, DerefMut}; use std::os::raw::c_void; use std::slice::{from_raw_parts, from_raw_parts_mut}; /// A RAII-wrapper of `fftw_alloc` and `fftw_free` with the [SIMD alignment]. /// /// [SIMD alignment]: http://www.fftw.org/fftw3_doc/SIMD-alignment-and-fftw_005fmalloc.html #[derive(Debug)] pub struct AlignedVec<T> { n: usize, data: *mut T, } /// Allocate SIMD-aligned memory of Real/Complex type pub trait AlignedAllocable: Zero + Clone + Copy + Sized { /// Allocate SIMD-aligned memory unsafe fn alloc(n: usize) -> *mut Self; } impl AlignedAllocable for f64 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftw_alloc_real(n) } } impl AlignedAllocable for f32 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftwf_alloc_real(n) } } impl AlignedAllocable for c64 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftw_alloc_complex(n) } } impl AlignedAllocable for c32 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftwf_alloc_complex(n) } } impl<T> AlignedVec<T> { pub fn as_slice(&self) -> &[T] { unsafe { from_raw_parts(self.data, self.n) } } pub fn as_slice_mut(&mut self) -> &mut [T] { unsafe { from_raw_parts_mut(self.data, self.n) } } } impl<T> Deref for AlignedVec<T> { type Target = [T]; fn deref(&self) -> &[T] { self.as_slice() } } impl<T> DerefMut for AlignedVec<T> { fn deref_mut(&mut self) -> &mut [T] { self.as_slice_mut() } } impl<T> AlignedVec<T> where T: AlignedAllocable, { /// Create array with `fftw_malloc` (`fftw_free` will be automatically called by `Drop` trait) pub fn
(n: usize) -> Self { let ptr = excall! { T::alloc(n) }; let mut vec = AlignedVec { n: n, data: ptr }; for v in vec.iter_mut() { *v = T::zero(); } vec } } impl<T> Drop for AlignedVec<T> { fn drop(&mut self) { excall! { ffi::fftw_free(self.data as *mut c_void) }; } } impl<T> Clone for AlignedVec<T> where T: AlignedAllocable, { fn clone(&self) -> Self { let mut new_vec = Self::new(self.n); new_vec.copy_from_slice(self); new_vec } } pub type Alignment = i32; /// Check the alignment of slice /// /// ``` /// # use fftw::array::*; /// let a = AlignedVec::<f32>::new(123); /// assert_eq!(alignment_of(&a), 0); // aligned /// ``` pub fn alignment_of<T>(a: &[T]) -> Alignment { unsafe { ffi::fftw_alignment_of(a.as_ptr() as *mut _) } }
new
identifier_name
array.rs
//! Array with SIMD alignment use crate::types::*; use ffi; use num_traits::Zero; use std::ops::{Deref, DerefMut}; use std::os::raw::c_void; use std::slice::{from_raw_parts, from_raw_parts_mut}; /// A RAII-wrapper of `fftw_alloc` and `fftw_free` with the [SIMD alignment]. /// /// [SIMD alignment]: http://www.fftw.org/fftw3_doc/SIMD-alignment-and-fftw_005fmalloc.html #[derive(Debug)] pub struct AlignedVec<T> { n: usize, data: *mut T, } /// Allocate SIMD-aligned memory of Real/Complex type pub trait AlignedAllocable: Zero + Clone + Copy + Sized { /// Allocate SIMD-aligned memory unsafe fn alloc(n: usize) -> *mut Self; } impl AlignedAllocable for f64 { unsafe fn alloc(n: usize) -> *mut Self
} impl AlignedAllocable for f32 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftwf_alloc_real(n) } } impl AlignedAllocable for c64 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftw_alloc_complex(n) } } impl AlignedAllocable for c32 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftwf_alloc_complex(n) } } impl<T> AlignedVec<T> { pub fn as_slice(&self) -> &[T] { unsafe { from_raw_parts(self.data, self.n) } } pub fn as_slice_mut(&mut self) -> &mut [T] { unsafe { from_raw_parts_mut(self.data, self.n) } } } impl<T> Deref for AlignedVec<T> { type Target = [T]; fn deref(&self) -> &[T] { self.as_slice() } } impl<T> DerefMut for AlignedVec<T> { fn deref_mut(&mut self) -> &mut [T] { self.as_slice_mut() } } impl<T> AlignedVec<T> where T: AlignedAllocable, { /// Create array with `fftw_malloc` (`fftw_free` will be automatically called by `Drop` trait) pub fn new(n: usize) -> Self { let ptr = excall! { T::alloc(n) }; let mut vec = AlignedVec { n: n, data: ptr }; for v in vec.iter_mut() { *v = T::zero(); } vec } } impl<T> Drop for AlignedVec<T> { fn drop(&mut self) { excall! { ffi::fftw_free(self.data as *mut c_void) }; } } impl<T> Clone for AlignedVec<T> where T: AlignedAllocable, { fn clone(&self) -> Self { let mut new_vec = Self::new(self.n); new_vec.copy_from_slice(self); new_vec } } pub type Alignment = i32; /// Check the alignment of slice /// /// ``` /// # use fftw::array::*; /// let a = AlignedVec::<f32>::new(123); /// assert_eq!(alignment_of(&a), 0); // aligned /// ``` pub fn alignment_of<T>(a: &[T]) -> Alignment { unsafe { ffi::fftw_alignment_of(a.as_ptr() as *mut _) } }
{ ffi::fftw_alloc_real(n) }
identifier_body
array.rs
//! Array with SIMD alignment use crate::types::*; use ffi; use num_traits::Zero; use std::ops::{Deref, DerefMut}; use std::os::raw::c_void; use std::slice::{from_raw_parts, from_raw_parts_mut}; /// A RAII-wrapper of `fftw_alloc` and `fftw_free` with the [SIMD alignment]. /// /// [SIMD alignment]: http://www.fftw.org/fftw3_doc/SIMD-alignment-and-fftw_005fmalloc.html #[derive(Debug)] pub struct AlignedVec<T> { n: usize, data: *mut T, } /// Allocate SIMD-aligned memory of Real/Complex type pub trait AlignedAllocable: Zero + Clone + Copy + Sized { /// Allocate SIMD-aligned memory unsafe fn alloc(n: usize) -> *mut Self; } impl AlignedAllocable for f64 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftw_alloc_real(n) } } impl AlignedAllocable for f32 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftwf_alloc_real(n) } }
ffi::fftw_alloc_complex(n) } } impl AlignedAllocable for c32 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftwf_alloc_complex(n) } } impl<T> AlignedVec<T> { pub fn as_slice(&self) -> &[T] { unsafe { from_raw_parts(self.data, self.n) } } pub fn as_slice_mut(&mut self) -> &mut [T] { unsafe { from_raw_parts_mut(self.data, self.n) } } } impl<T> Deref for AlignedVec<T> { type Target = [T]; fn deref(&self) -> &[T] { self.as_slice() } } impl<T> DerefMut for AlignedVec<T> { fn deref_mut(&mut self) -> &mut [T] { self.as_slice_mut() } } impl<T> AlignedVec<T> where T: AlignedAllocable, { /// Create array with `fftw_malloc` (`fftw_free` will be automatically called by `Drop` trait) pub fn new(n: usize) -> Self { let ptr = excall! { T::alloc(n) }; let mut vec = AlignedVec { n: n, data: ptr }; for v in vec.iter_mut() { *v = T::zero(); } vec } } impl<T> Drop for AlignedVec<T> { fn drop(&mut self) { excall! { ffi::fftw_free(self.data as *mut c_void) }; } } impl<T> Clone for AlignedVec<T> where T: AlignedAllocable, { fn clone(&self) -> Self { let mut new_vec = Self::new(self.n); new_vec.copy_from_slice(self); new_vec } } pub type Alignment = i32; /// Check the alignment of slice /// /// ``` /// # use fftw::array::*; /// let a = AlignedVec::<f32>::new(123); /// assert_eq!(alignment_of(&a), 0); // aligned /// ``` pub fn alignment_of<T>(a: &[T]) -> Alignment { unsafe { ffi::fftw_alignment_of(a.as_ptr() as *mut _) } }
impl AlignedAllocable for c64 { unsafe fn alloc(n: usize) -> *mut Self {
random_line_split
mod.rs
mod api; use gcrypt; use hyper; use rustc_serialize::base64; use rustc_serialize::hex; use rustc_serialize::json; use crypto; use std::fmt; use std::io; use rustc_serialize::base64::FromBase64; use rustc_serialize::hex::FromHex; use rustc_serialize::hex::ToHex; #[derive(Debug)] pub enum KeybaseError { Http(String), Api(api::Status), FromBase64(base64::FromBase64Error), FromHex(hex::FromHexError), Gcrypt(gcrypt::error::Error), Hyper(hyper::Error), Io(io::Error), Json(json::DecoderError), } impl From<api::Status> for KeybaseError { fn from(err: api::Status) -> KeybaseError { KeybaseError::Api(err) } } impl From<base64::FromBase64Error> for KeybaseError { fn from(err: base64::FromBase64Error) -> KeybaseError { KeybaseError::FromBase64(err) } } impl From<hex::FromHexError> for KeybaseError { fn from(err: hex::FromHexError) -> KeybaseError { KeybaseError::FromHex(err) } } impl From<gcrypt::error::Error> for KeybaseError { fn
(err: gcrypt::error::Error) -> KeybaseError { KeybaseError::Gcrypt(err) } } impl From<hyper::Error> for KeybaseError { fn from(err: hyper::Error) -> KeybaseError { KeybaseError::Hyper(err) } } impl From<io::Error> for KeybaseError { fn from(err: io::Error) -> KeybaseError { KeybaseError::Io(err) } } impl From<json::DecoderError> for KeybaseError { fn from(err: json::DecoderError) -> KeybaseError { KeybaseError::Json(err) } } impl fmt::Display for KeybaseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { KeybaseError::Http(ref msg) => write!(f, "Keybase API Error: {}", msg), KeybaseError::Api(ref err) => match err.desc.as_ref() { Some(ref desc) => write!(f, "Keybase API error: {} ({})", desc, err.name), None => write!(f, "Keybase API error: {}", err.name), }, KeybaseError::FromBase64(ref err) => err.fmt(f), KeybaseError::FromHex(ref err) => err.fmt(f), KeybaseError::Gcrypt(ref err) => err.fmt(f), KeybaseError::Hyper(ref err) => err.fmt(f), KeybaseError::Io(ref err) => err.fmt(f), KeybaseError::Json(ref err) => err.fmt(f), } } } pub type KeybaseResult<T> = Result<T, KeybaseError>; #[allow(dead_code)] pub struct Keybase { session: String, csrf_token: String, } impl Keybase { pub fn login(user: &str, password: &str, token: gcrypt::Token) -> KeybaseResult<Keybase> { let getsalt = try!(api::getsalt(user)); let salt = &getsalt.salt.unwrap(); let login_session = &getsalt.login_session.unwrap(); let salt_bytes = try!(salt.from_hex()); let mut pwh = vec![0; 224]; try!(crypto::scrypt(password, &salt_bytes, &mut pwh, token)); let session = try!(login_session.from_base64()); let hmac_pwh = try!(crypto::hmac_sha512(&session, &pwh[192..224], token)); let key = hmac_pwh.to_hex(); let login = try!(api::login(user, &key, login_session)); Ok(Keybase{session : login.session.unwrap(), csrf_token: login.csrf_token.unwrap()}) } } #[cfg(test)] mod tests { use gcrypt; use super::*; use std::env; #[test] #[allow(unused_variables)] fn can_login() { let token = gcrypt::init(|mut gcry| { gcry.enable_secmem(16384).unwrap(); }); let username = &env::var("HEDWIG_TEST_KEYBASE_USERNAME").unwrap(); let password = &env::var("HEDWIG_TEST_KEYBASE_PASSWORD").unwrap(); let keybase_session = Keybase::login(&username, &password, token).unwrap(); } }
from
identifier_name
mod.rs
mod api; use gcrypt; use hyper; use rustc_serialize::base64; use rustc_serialize::hex; use rustc_serialize::json; use crypto; use std::fmt; use std::io; use rustc_serialize::base64::FromBase64; use rustc_serialize::hex::FromHex; use rustc_serialize::hex::ToHex; #[derive(Debug)] pub enum KeybaseError { Http(String), Api(api::Status), FromBase64(base64::FromBase64Error), FromHex(hex::FromHexError), Gcrypt(gcrypt::error::Error), Hyper(hyper::Error), Io(io::Error), Json(json::DecoderError), } impl From<api::Status> for KeybaseError { fn from(err: api::Status) -> KeybaseError { KeybaseError::Api(err) } } impl From<base64::FromBase64Error> for KeybaseError { fn from(err: base64::FromBase64Error) -> KeybaseError { KeybaseError::FromBase64(err) } } impl From<hex::FromHexError> for KeybaseError { fn from(err: hex::FromHexError) -> KeybaseError { KeybaseError::FromHex(err) } } impl From<gcrypt::error::Error> for KeybaseError { fn from(err: gcrypt::error::Error) -> KeybaseError { KeybaseError::Gcrypt(err) } } impl From<hyper::Error> for KeybaseError { fn from(err: hyper::Error) -> KeybaseError { KeybaseError::Hyper(err) } }
} } impl From<json::DecoderError> for KeybaseError { fn from(err: json::DecoderError) -> KeybaseError { KeybaseError::Json(err) } } impl fmt::Display for KeybaseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { KeybaseError::Http(ref msg) => write!(f, "Keybase API Error: {}", msg), KeybaseError::Api(ref err) => match err.desc.as_ref() { Some(ref desc) => write!(f, "Keybase API error: {} ({})", desc, err.name), None => write!(f, "Keybase API error: {}", err.name), }, KeybaseError::FromBase64(ref err) => err.fmt(f), KeybaseError::FromHex(ref err) => err.fmt(f), KeybaseError::Gcrypt(ref err) => err.fmt(f), KeybaseError::Hyper(ref err) => err.fmt(f), KeybaseError::Io(ref err) => err.fmt(f), KeybaseError::Json(ref err) => err.fmt(f), } } } pub type KeybaseResult<T> = Result<T, KeybaseError>; #[allow(dead_code)] pub struct Keybase { session: String, csrf_token: String, } impl Keybase { pub fn login(user: &str, password: &str, token: gcrypt::Token) -> KeybaseResult<Keybase> { let getsalt = try!(api::getsalt(user)); let salt = &getsalt.salt.unwrap(); let login_session = &getsalt.login_session.unwrap(); let salt_bytes = try!(salt.from_hex()); let mut pwh = vec![0; 224]; try!(crypto::scrypt(password, &salt_bytes, &mut pwh, token)); let session = try!(login_session.from_base64()); let hmac_pwh = try!(crypto::hmac_sha512(&session, &pwh[192..224], token)); let key = hmac_pwh.to_hex(); let login = try!(api::login(user, &key, login_session)); Ok(Keybase{session : login.session.unwrap(), csrf_token: login.csrf_token.unwrap()}) } } #[cfg(test)] mod tests { use gcrypt; use super::*; use std::env; #[test] #[allow(unused_variables)] fn can_login() { let token = gcrypt::init(|mut gcry| { gcry.enable_secmem(16384).unwrap(); }); let username = &env::var("HEDWIG_TEST_KEYBASE_USERNAME").unwrap(); let password = &env::var("HEDWIG_TEST_KEYBASE_PASSWORD").unwrap(); let keybase_session = Keybase::login(&username, &password, token).unwrap(); } }
impl From<io::Error> for KeybaseError { fn from(err: io::Error) -> KeybaseError { KeybaseError::Io(err)
random_line_split
borrowck-lend-flow-if.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. // Note: the borrowck analysis is currently flow-insensitive. // Therefore, some of these errors are marked as spurious and could be // corrected by a simple change to the analysis. The others are // either genuine or would require more advanced changes. The latter // cases are noted. fn borrow(_v: &int) {} fn borrow_mut(_v: &mut int) {} fn cond() -> bool { fail!() } fn for_func(_f: || -> bool) { fail!() } fn produce<T>() -> T { fail!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn pre_freeze_cond() { // In this instance, the freeze is conditional and starts before // the mut borrow. let mut v = ~3; let _w; if cond() { _w = &v; } borrow_mut(v); //~ ERROR cannot borrow } fn pre_freeze_else() { // In this instance, the freeze and mut borrow are on separate sides // of the if. let mut v = ~3;
} } fn main() {}
let _w; if cond() { _w = &v; } else { borrow_mut(v);
random_line_split
borrowck-lend-flow-if.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. // Note: the borrowck analysis is currently flow-insensitive. // Therefore, some of these errors are marked as spurious and could be // corrected by a simple change to the analysis. The others are // either genuine or would require more advanced changes. The latter // cases are noted. fn borrow(_v: &int) {} fn borrow_mut(_v: &mut int) {} fn cond() -> bool { fail!() } fn for_func(_f: || -> bool) { fail!() } fn produce<T>() -> T { fail!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn pre_freeze_cond() { // In this instance, the freeze is conditional and starts before // the mut borrow. let mut v = ~3; let _w; if cond()
borrow_mut(v); //~ ERROR cannot borrow } fn pre_freeze_else() { // In this instance, the freeze and mut borrow are on separate sides // of the if. let mut v = ~3; let _w; if cond() { _w = &v; } else { borrow_mut(v); } } fn main() {}
{ _w = &v; }
conditional_block
borrowck-lend-flow-if.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. // Note: the borrowck analysis is currently flow-insensitive. // Therefore, some of these errors are marked as spurious and could be // corrected by a simple change to the analysis. The others are // either genuine or would require more advanced changes. The latter // cases are noted. fn borrow(_v: &int) {} fn borrow_mut(_v: &mut int) {} fn cond() -> bool { fail!() } fn for_func(_f: || -> bool)
fn produce<T>() -> T { fail!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn pre_freeze_cond() { // In this instance, the freeze is conditional and starts before // the mut borrow. let mut v = ~3; let _w; if cond() { _w = &v; } borrow_mut(v); //~ ERROR cannot borrow } fn pre_freeze_else() { // In this instance, the freeze and mut borrow are on separate sides // of the if. let mut v = ~3; let _w; if cond() { _w = &v; } else { borrow_mut(v); } } fn main() {}
{ fail!() }
identifier_body
borrowck-lend-flow-if.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. // Note: the borrowck analysis is currently flow-insensitive. // Therefore, some of these errors are marked as spurious and could be // corrected by a simple change to the analysis. The others are // either genuine or would require more advanced changes. The latter // cases are noted. fn borrow(_v: &int) {} fn
(_v: &mut int) {} fn cond() -> bool { fail!() } fn for_func(_f: || -> bool) { fail!() } fn produce<T>() -> T { fail!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn pre_freeze_cond() { // In this instance, the freeze is conditional and starts before // the mut borrow. let mut v = ~3; let _w; if cond() { _w = &v; } borrow_mut(v); //~ ERROR cannot borrow } fn pre_freeze_else() { // In this instance, the freeze and mut borrow are on separate sides // of the if. let mut v = ~3; let _w; if cond() { _w = &v; } else { borrow_mut(v); } } fn main() {}
borrow_mut
identifier_name
mod.rs
mod version; mod init; mod config; mod ignore; mod sweep; mod burn; mod start; mod end; mod destroy; mod patrol; use self::version::Version; use self::init::Init; use self::config::Config; use self::ignore::Ignore; use self::sweep::Sweep; use self::burn::Burn; use self::start::Start; use self::end::End; use self::destroy::Destroy; use self::patrol::Patrol; use constant::BANNED_DIRS; use error::{CliError, EssentialLack, EssentialKind, RunningPlaceError, Usage, UsageKind}; use lib::io::*; use lib::setting; use std::env; use std::fmt::Display; trait Command { fn allow_to_check_current_dir(&self) -> bool { true } fn check_current_dir(&self) -> Result<(), CliError> { let current_dir = try!(env::current_dir()); match BANNED_DIRS.iter().find(|d| current_dir.ends_with(d)) { Some(d) => Err(From::from(RunningPlaceError::new(d.to_string()))), None => Ok(()), } } fn
(&self) -> bool { true } fn check_settings(&self) -> Result<(), EssentialLack> { if!setting::working_dir_exists() { return Err(EssentialLack::new(EssentialKind::WorkingDir)); } if!setting::Storage::exist() { return Err(EssentialLack::new(EssentialKind::StorageDir)); } if!setting::Config::exist() { return Err(EssentialLack::new(EssentialKind::ConfigFile)); } if!setting::Ignore::exist() { return Err(EssentialLack::new(EssentialKind::IgnoreFile)); } Ok(()) } fn usage(&self) -> Usage; fn main(&self) -> Result<(), CliError>; fn exec(&self, need_help: bool) -> Result<(), CliError> { if need_help { return Err(From::from(self.usage())); } if self.allow_to_check_current_dir() { try!(self.check_current_dir()); } if self.allow_to_check_settings() { try!(self.check_settings()); } self.main() } fn run_after_confirmation<D: Display, F>(message: D, danger_exec: F) -> Result<(), CliError> where Self: Sized, F: FnOnce() -> Result<(), CliError> { echo(format_with_tag(Tag::Caution, format!("{} [yes/no]: ", message))); let input = try!(read_line_from_stdin()).to_lowercase(); match input.as_ref() { "y" | "yes" => try!(danger_exec()), _ => print_with_tag(Tag::Notice, "Interrupted by user"), }; Ok(()) } } pub fn execute(args: Vec<String>) -> Result<(), CliError> { let mut args = args.into_iter(); let command = try!(args.next().ok_or(Usage::new(UsageKind::Nothing))); let (command, need_help) = if &command == "help" { (try!(args.next().ok_or(Usage::new(UsageKind::Help))), true) } else { (command, false) }; match command.as_ref() { "version" => Version .exec(need_help), "init" => Init .exec(need_help), "config" => Config::new(args.next(), args.next(), args.next()).exec(need_help), "ignore" => Ignore::new(args.next(), args.collect()) .exec(need_help), "sweep" => Sweep::new(args.next(), args.next()) .exec(need_help), "burn" => Burn::new(args.next()) .exec(need_help), "start" => Start .exec(need_help), "end" => End .exec(need_help), "destroy" => Destroy .exec(need_help), "patrol" => Patrol .exec(need_help), _ => Err(From::from(Usage::new(UsageKind::Nothing))), } } pub fn clean_up() -> Result<(), CliError> { // This is temporary "if" for avoiding the error except for "unix". if cfg!(unix) { End.main() } else { Ok(()) } }
allow_to_check_settings
identifier_name
mod.rs
mod version; mod init; mod config; mod ignore; mod sweep; mod burn; mod start; mod end; mod destroy; mod patrol; use self::version::Version; use self::init::Init; use self::config::Config; use self::ignore::Ignore; use self::sweep::Sweep; use self::burn::Burn; use self::start::Start; use self::end::End; use self::destroy::Destroy; use self::patrol::Patrol; use constant::BANNED_DIRS; use error::{CliError, EssentialLack, EssentialKind, RunningPlaceError, Usage, UsageKind}; use lib::io::*; use lib::setting; use std::env; use std::fmt::Display; trait Command { fn allow_to_check_current_dir(&self) -> bool { true } fn check_current_dir(&self) -> Result<(), CliError>
fn allow_to_check_settings(&self) -> bool { true } fn check_settings(&self) -> Result<(), EssentialLack> { if!setting::working_dir_exists() { return Err(EssentialLack::new(EssentialKind::WorkingDir)); } if!setting::Storage::exist() { return Err(EssentialLack::new(EssentialKind::StorageDir)); } if!setting::Config::exist() { return Err(EssentialLack::new(EssentialKind::ConfigFile)); } if!setting::Ignore::exist() { return Err(EssentialLack::new(EssentialKind::IgnoreFile)); } Ok(()) } fn usage(&self) -> Usage; fn main(&self) -> Result<(), CliError>; fn exec(&self, need_help: bool) -> Result<(), CliError> { if need_help { return Err(From::from(self.usage())); } if self.allow_to_check_current_dir() { try!(self.check_current_dir()); } if self.allow_to_check_settings() { try!(self.check_settings()); } self.main() } fn run_after_confirmation<D: Display, F>(message: D, danger_exec: F) -> Result<(), CliError> where Self: Sized, F: FnOnce() -> Result<(), CliError> { echo(format_with_tag(Tag::Caution, format!("{} [yes/no]: ", message))); let input = try!(read_line_from_stdin()).to_lowercase(); match input.as_ref() { "y" | "yes" => try!(danger_exec()), _ => print_with_tag(Tag::Notice, "Interrupted by user"), }; Ok(()) } } pub fn execute(args: Vec<String>) -> Result<(), CliError> { let mut args = args.into_iter(); let command = try!(args.next().ok_or(Usage::new(UsageKind::Nothing))); let (command, need_help) = if &command == "help" { (try!(args.next().ok_or(Usage::new(UsageKind::Help))), true) } else { (command, false) }; match command.as_ref() { "version" => Version .exec(need_help), "init" => Init .exec(need_help), "config" => Config::new(args.next(), args.next(), args.next()).exec(need_help), "ignore" => Ignore::new(args.next(), args.collect()) .exec(need_help), "sweep" => Sweep::new(args.next(), args.next()) .exec(need_help), "burn" => Burn::new(args.next()) .exec(need_help), "start" => Start .exec(need_help), "end" => End .exec(need_help), "destroy" => Destroy .exec(need_help), "patrol" => Patrol .exec(need_help), _ => Err(From::from(Usage::new(UsageKind::Nothing))), } } pub fn clean_up() -> Result<(), CliError> { // This is temporary "if" for avoiding the error except for "unix". if cfg!(unix) { End.main() } else { Ok(()) } }
{ let current_dir = try!(env::current_dir()); match BANNED_DIRS.iter().find(|d| current_dir.ends_with(d)) { Some(d) => Err(From::from(RunningPlaceError::new(d.to_string()))), None => Ok(()), } }
identifier_body
mod.rs
mod version; mod init; mod config; mod ignore; mod sweep; mod burn; mod start; mod end; mod destroy; mod patrol; use self::version::Version; use self::init::Init; use self::config::Config; use self::ignore::Ignore; use self::sweep::Sweep; use self::burn::Burn; use self::start::Start; use self::end::End; use self::destroy::Destroy; use self::patrol::Patrol; use constant::BANNED_DIRS; use error::{CliError, EssentialLack, EssentialKind, RunningPlaceError, Usage, UsageKind}; use lib::io::*; use lib::setting; use std::env; use std::fmt::Display; trait Command { fn allow_to_check_current_dir(&self) -> bool { true } fn check_current_dir(&self) -> Result<(), CliError> { let current_dir = try!(env::current_dir()); match BANNED_DIRS.iter().find(|d| current_dir.ends_with(d)) { Some(d) => Err(From::from(RunningPlaceError::new(d.to_string()))), None => Ok(()), } } fn allow_to_check_settings(&self) -> bool { true } fn check_settings(&self) -> Result<(), EssentialLack> { if!setting::working_dir_exists() { return Err(EssentialLack::new(EssentialKind::WorkingDir)); } if!setting::Storage::exist() { return Err(EssentialLack::new(EssentialKind::StorageDir)); } if!setting::Config::exist() { return Err(EssentialLack::new(EssentialKind::ConfigFile)); } if!setting::Ignore::exist() { return Err(EssentialLack::new(EssentialKind::IgnoreFile)); } Ok(()) } fn usage(&self) -> Usage; fn main(&self) -> Result<(), CliError>; fn exec(&self, need_help: bool) -> Result<(), CliError> { if need_help { return Err(From::from(self.usage())); } if self.allow_to_check_current_dir() { try!(self.check_current_dir()); } if self.allow_to_check_settings() { try!(self.check_settings()); } self.main() } fn run_after_confirmation<D: Display, F>(message: D, danger_exec: F) -> Result<(), CliError> where Self: Sized, F: FnOnce() -> Result<(), CliError> { echo(format_with_tag(Tag::Caution, format!("{} [yes/no]: ", message))); let input = try!(read_line_from_stdin()).to_lowercase(); match input.as_ref() { "y" | "yes" => try!(danger_exec()), _ => print_with_tag(Tag::Notice, "Interrupted by user"), }; Ok(()) } } pub fn execute(args: Vec<String>) -> Result<(), CliError> { let mut args = args.into_iter(); let command = try!(args.next().ok_or(Usage::new(UsageKind::Nothing))); let (command, need_help) = if &command == "help" { (try!(args.next().ok_or(Usage::new(UsageKind::Help))), true)
}; match command.as_ref() { "version" => Version .exec(need_help), "init" => Init .exec(need_help), "config" => Config::new(args.next(), args.next(), args.next()).exec(need_help), "ignore" => Ignore::new(args.next(), args.collect()) .exec(need_help), "sweep" => Sweep::new(args.next(), args.next()) .exec(need_help), "burn" => Burn::new(args.next()) .exec(need_help), "start" => Start .exec(need_help), "end" => End .exec(need_help), "destroy" => Destroy .exec(need_help), "patrol" => Patrol .exec(need_help), _ => Err(From::from(Usage::new(UsageKind::Nothing))), } } pub fn clean_up() -> Result<(), CliError> { // This is temporary "if" for avoiding the error except for "unix". if cfg!(unix) { End.main() } else { Ok(()) } }
} else { (command, false)
random_line_split
error.rs
use crate::{constants::MAX_PRECISION_U32, Decimal}; use alloc::string::String; use core::fmt; /// Error type for the library. #[derive(Clone, Debug, PartialEq)] pub enum Error { ErrorString(String), ExceedsMaximumPossibleValue, LessThanMinimumPossibleValue, Underflow, ScaleExceedsMaximumPrecision(u32), } impl<S> From<S> for Error where S: Into<String>, { #[inline] fn from(from: S) -> Self { Self::ErrorString(from.into()) } } #[cold] pub(crate) fn tail_error(from: &'static str) -> Result<Decimal, Error> { Err(from.into()) } #[cfg(feature = "std")] impl std::error::Error for Error {} impl fmt::Display for Error { fn
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::ErrorString(ref err) => f.pad(err), Self::ExceedsMaximumPossibleValue => { write!(f, "Number exceeds maximum value that can be represented.") } Self::LessThanMinimumPossibleValue => { write!(f, "Number less than minimum value that can be represented.") } Self::Underflow => { write!(f, "Number has a high precision that can not be represented.") } Self::ScaleExceedsMaximumPrecision(ref scale) => { write!( f, "Scale exceeds the maximum precision allowed: {} > {}", scale, MAX_PRECISION_U32 ) } } } }
fmt
identifier_name
error.rs
use crate::{constants::MAX_PRECISION_U32, Decimal}; use alloc::string::String; use core::fmt; /// Error type for the library. #[derive(Clone, Debug, PartialEq)] pub enum Error { ErrorString(String),
} impl<S> From<S> for Error where S: Into<String>, { #[inline] fn from(from: S) -> Self { Self::ErrorString(from.into()) } } #[cold] pub(crate) fn tail_error(from: &'static str) -> Result<Decimal, Error> { Err(from.into()) } #[cfg(feature = "std")] impl std::error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::ErrorString(ref err) => f.pad(err), Self::ExceedsMaximumPossibleValue => { write!(f, "Number exceeds maximum value that can be represented.") } Self::LessThanMinimumPossibleValue => { write!(f, "Number less than minimum value that can be represented.") } Self::Underflow => { write!(f, "Number has a high precision that can not be represented.") } Self::ScaleExceedsMaximumPrecision(ref scale) => { write!( f, "Scale exceeds the maximum precision allowed: {} > {}", scale, MAX_PRECISION_U32 ) } } } }
ExceedsMaximumPossibleValue, LessThanMinimumPossibleValue, Underflow, ScaleExceedsMaximumPrecision(u32),
random_line_split
error.rs
use crate::{constants::MAX_PRECISION_U32, Decimal}; use alloc::string::String; use core::fmt; /// Error type for the library. #[derive(Clone, Debug, PartialEq)] pub enum Error { ErrorString(String), ExceedsMaximumPossibleValue, LessThanMinimumPossibleValue, Underflow, ScaleExceedsMaximumPrecision(u32), } impl<S> From<S> for Error where S: Into<String>, { #[inline] fn from(from: S) -> Self { Self::ErrorString(from.into()) } } #[cold] pub(crate) fn tail_error(from: &'static str) -> Result<Decimal, Error> { Err(from.into()) } #[cfg(feature = "std")] impl std::error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::ErrorString(ref err) => f.pad(err), Self::ExceedsMaximumPossibleValue => { write!(f, "Number exceeds maximum value that can be represented.") } Self::LessThanMinimumPossibleValue => { write!(f, "Number less than minimum value that can be represented.") } Self::Underflow =>
Self::ScaleExceedsMaximumPrecision(ref scale) => { write!( f, "Scale exceeds the maximum precision allowed: {} > {}", scale, MAX_PRECISION_U32 ) } } } }
{ write!(f, "Number has a high precision that can not be represented.") }
conditional_block
error.rs
use crate::{constants::MAX_PRECISION_U32, Decimal}; use alloc::string::String; use core::fmt; /// Error type for the library. #[derive(Clone, Debug, PartialEq)] pub enum Error { ErrorString(String), ExceedsMaximumPossibleValue, LessThanMinimumPossibleValue, Underflow, ScaleExceedsMaximumPrecision(u32), } impl<S> From<S> for Error where S: Into<String>, { #[inline] fn from(from: S) -> Self { Self::ErrorString(from.into()) } } #[cold] pub(crate) fn tail_error(from: &'static str) -> Result<Decimal, Error> { Err(from.into()) } #[cfg(feature = "std")] impl std::error::Error for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
} }
{ match *self { Self::ErrorString(ref err) => f.pad(err), Self::ExceedsMaximumPossibleValue => { write!(f, "Number exceeds maximum value that can be represented.") } Self::LessThanMinimumPossibleValue => { write!(f, "Number less than minimum value that can be represented.") } Self::Underflow => { write!(f, "Number has a high precision that can not be represented.") } Self::ScaleExceedsMaximumPrecision(ref scale) => { write!( f, "Scale exceeds the maximum precision allowed: {} > {}", scale, MAX_PRECISION_U32 ) } }
identifier_body
bitflags.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 `bitflags!` macro generates a `struct` that holds a set of C-style //! bitmask flags. It is useful for creating typesafe wrappers for C APIs. //! //! The flags should only be defined for integer types, otherwise unexpected //! type errors may occur at compile time. //! //! # Example //! //! ~~~rust //! bitflags!( //! flags Flags: u32 { //! static FlagA = 0x00000001, //! static FlagB = 0x00000010, //! static FlagC = 0x00000100, //! static FlagABC = FlagA.bits //! | FlagB.bits //! | FlagC.bits //! } //! ) //! //! fn main() { //! let e1 = FlagA | FlagC; //! let e2 = FlagB | FlagC; //! assert!((e1 | e2) == FlagABC); // union //! assert!((e1 & e2) == FlagC); // intersection //! assert!((e1 - e2) == FlagA); // set difference //! } //! ~~~ //! //! The generated `struct`s can also be extended with type and trait implementations: //! //! ~~~rust //! use std::fmt; //! //! bitflags!( //! flags Flags: u32 { //! static FlagA = 0x00000001, //! static FlagB = 0x00000010 //! } //! ) //! //! impl Flags { //! pub fn clear(&mut self) { //! self.bits = 0; // The `bits` field can be accessed from within the //! // same module where the `bitflags!` macro was invoked. //! } //! } //! //! impl fmt::Show for Flags { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! write!(f.buf, "hi!") //! } //! } //! //! fn main() { //! let mut flags = FlagA | FlagB; //! flags.clear(); //! assert!(flags.is_empty()); //! assert_eq!(format!("{}", flags).as_slice(), "hi!"); //! } //! ~~~ //! //! # Attributes //! //! Attributes can be attached to the generated `struct` by placing them //! before the `flags` keyword. //! //! # Derived traits //! //! The `Eq` and `Clone` traits are automatically derived for the `struct` using //! the `deriving` attribute. Additional traits can be derived by providing an //! explicit `deriving` attribute on `flags`. //! //! # Operators //! //! The following operator traits are implemented for the generated `struct`: //! //! - `BitOr`: union //! - `BitAnd`: intersection //! - `Sub`: set difference //! //! # Methods //! //! The following methods are defined for the generated `struct`: //! //! - `empty`: an empty set of flags //! - `bits`: the raw value of the flags currently stored //! - `is_empty`: `true` if no flags are currently stored //! - `intersects`: `true` if there are flags common to both `self` and `other` //! - `contains`: `true` all of the flags in `other` are contained within `self` //! - `insert`: inserts the specified flags in-place //! - `remove`: removes the specified flags in-place #![macro_escape] #[macro_export] macro_rules! bitflags( ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty { $($(#[$Flag_attr:meta])* static $Flag:ident = $value:expr),+ }) => ( #[deriving(Eq, TotalEq, Clone)] $(#[$attr])* pub struct $BitFlags { bits: $T, } $($(#[$Flag_attr])* pub static $Flag: $BitFlags = $BitFlags { bits: $value };)+ impl $BitFlags { /// Returns an empty set of flags. pub fn empty() -> $BitFlags { $BitFlags { bits: 0 } } /// Returns the raw value of the flags currently stored. pub fn bits(&self) -> $T { self.bits } /// Convert from underlying bit representation. Unsafe because the /// bits are not guaranteed to represent valid flags. pub unsafe fn from_bits(bits: $T) -> $BitFlags { $BitFlags { bits: bits } } /// Returns `true` if no flags are currently stored. pub fn is_empty(&self) -> bool { *self == $BitFlags::empty() } /// Returns `true` if there are flags common to both `self` and `other`. pub fn intersects(&self, other: $BitFlags) -> bool { !(self & other).is_empty() } /// Returns `true` all of the flags in `other` are contained within `self`. pub fn contains(&self, other: $BitFlags) -> bool { (self & other) == other } /// Inserts the specified flags in-place. pub fn insert(&mut self, other: $BitFlags) { self.bits |= other.bits; } /// Removes the specified flags in-place. pub fn remove(&mut self, other: $BitFlags) { self.bits &=!other.bits; } } impl BitOr<$BitFlags, $BitFlags> for $BitFlags { /// Returns the union of the two sets of flags. #[inline] fn bitor(&self, other: &$BitFlags) -> $BitFlags { $BitFlags { bits: self.bits | other.bits } } } impl BitAnd<$BitFlags, $BitFlags> for $BitFlags { /// Returns the intersection between the two sets of flags. #[inline] fn bitand(&self, other: &$BitFlags) -> $BitFlags { $BitFlags { bits: self.bits & other.bits } } } impl Sub<$BitFlags, $BitFlags> for $BitFlags { /// Returns the set difference of the two sets of flags. #[inline] fn sub(&self, other: &$BitFlags) -> $BitFlags { $BitFlags { bits: self.bits &!other.bits } } } ) ) #[cfg(test)] mod tests { use ops::{BitOr, BitAnd, Sub}; bitflags!( flags Flags: u32 { static FlagA = 0x00000001, static FlagB = 0x00000010, static FlagC = 0x00000100, static FlagABC = FlagA.bits | FlagB.bits | FlagC.bits } ) #[test] fn test_bits(){ assert_eq!(Flags::empty().bits(), 0x00000000); assert_eq!(FlagA.bits(), 0x00000001); assert_eq!(FlagABC.bits(), 0x00000111); } #[test] fn test_is_empty(){ assert!(Flags::empty().is_empty()); assert!(!FlagA.is_empty()); assert!(!FlagABC.is_empty()); } #[test] fn test_two_empties_do_not_intersect() { let e1 = Flags::empty(); let e2 = Flags::empty(); assert!(!e1.intersects(e2)); } #[test] fn test_empty_does_not_intersect_with_full() { let e1 = Flags::empty(); let e2 = FlagABC; assert!(!e1.intersects(e2)); } #[test] fn test_disjoint_intersects() { let e1 = FlagA; let e2 = FlagB; assert!(!e1.intersects(e2)); } #[test] fn test_overlapping_intersects() { let e1 = FlagA; let e2 = FlagA | FlagB; assert!(e1.intersects(e2)); } #[test] fn test_contains() { let e1 = FlagA; let e2 = FlagA | FlagB; assert!(!e1.contains(e2)); assert!(e2.contains(e1)); assert!(FlagABC.contains(e2)); } #[test] fn test_insert()
#[test] fn test_remove(){ let mut e1 = FlagA | FlagB; let e2 = FlagA | FlagC; e1.remove(e2); assert!(e1 == FlagB); } #[test] fn test_operators() { let e1 = FlagA | FlagC; let e2 = FlagB | FlagC; assert!((e1 | e2) == FlagABC); // union assert!((e1 & e2) == FlagC); // intersection assert!((e1 - e2) == FlagA); // set difference } }
{ let mut e1 = FlagA; let e2 = FlagA | FlagB; e1.insert(e2); assert!(e1 == e2); }
identifier_body
bitflags.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 `bitflags!` macro generates a `struct` that holds a set of C-style //! bitmask flags. It is useful for creating typesafe wrappers for C APIs. //! //! The flags should only be defined for integer types, otherwise unexpected //! type errors may occur at compile time. //! //! # Example //! //! ~~~rust //! bitflags!( //! flags Flags: u32 { //! static FlagA = 0x00000001, //! static FlagB = 0x00000010, //! static FlagC = 0x00000100, //! static FlagABC = FlagA.bits //! | FlagB.bits //! | FlagC.bits //! } //! ) //! //! fn main() { //! let e1 = FlagA | FlagC; //! let e2 = FlagB | FlagC; //! assert!((e1 | e2) == FlagABC); // union //! assert!((e1 & e2) == FlagC); // intersection //! assert!((e1 - e2) == FlagA); // set difference //! } //! ~~~ //! //! The generated `struct`s can also be extended with type and trait implementations: //! //! ~~~rust //! use std::fmt; //! //! bitflags!( //! flags Flags: u32 { //! static FlagA = 0x00000001, //! static FlagB = 0x00000010 //! } //! ) //! //! impl Flags { //! pub fn clear(&mut self) { //! self.bits = 0; // The `bits` field can be accessed from within the //! // same module where the `bitflags!` macro was invoked. //! } //! } //! //! impl fmt::Show for Flags { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! write!(f.buf, "hi!") //! } //! } //! //! fn main() { //! let mut flags = FlagA | FlagB; //! flags.clear(); //! assert!(flags.is_empty()); //! assert_eq!(format!("{}", flags).as_slice(), "hi!"); //! } //! ~~~ //! //! # Attributes //! //! Attributes can be attached to the generated `struct` by placing them //! before the `flags` keyword. //! //! # Derived traits //! //! The `Eq` and `Clone` traits are automatically derived for the `struct` using //! the `deriving` attribute. Additional traits can be derived by providing an //! explicit `deriving` attribute on `flags`. //! //! # Operators //! //! The following operator traits are implemented for the generated `struct`: //! //! - `BitOr`: union //! - `BitAnd`: intersection //! - `Sub`: set difference //! //! # Methods //! //! The following methods are defined for the generated `struct`: //! //! - `empty`: an empty set of flags //! - `bits`: the raw value of the flags currently stored //! - `is_empty`: `true` if no flags are currently stored //! - `intersects`: `true` if there are flags common to both `self` and `other` //! - `contains`: `true` all of the flags in `other` are contained within `self`
//! - `insert`: inserts the specified flags in-place //! - `remove`: removes the specified flags in-place #![macro_escape] #[macro_export] macro_rules! bitflags( ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty { $($(#[$Flag_attr:meta])* static $Flag:ident = $value:expr),+ }) => ( #[deriving(Eq, TotalEq, Clone)] $(#[$attr])* pub struct $BitFlags { bits: $T, } $($(#[$Flag_attr])* pub static $Flag: $BitFlags = $BitFlags { bits: $value };)+ impl $BitFlags { /// Returns an empty set of flags. pub fn empty() -> $BitFlags { $BitFlags { bits: 0 } } /// Returns the raw value of the flags currently stored. pub fn bits(&self) -> $T { self.bits } /// Convert from underlying bit representation. Unsafe because the /// bits are not guaranteed to represent valid flags. pub unsafe fn from_bits(bits: $T) -> $BitFlags { $BitFlags { bits: bits } } /// Returns `true` if no flags are currently stored. pub fn is_empty(&self) -> bool { *self == $BitFlags::empty() } /// Returns `true` if there are flags common to both `self` and `other`. pub fn intersects(&self, other: $BitFlags) -> bool { !(self & other).is_empty() } /// Returns `true` all of the flags in `other` are contained within `self`. pub fn contains(&self, other: $BitFlags) -> bool { (self & other) == other } /// Inserts the specified flags in-place. pub fn insert(&mut self, other: $BitFlags) { self.bits |= other.bits; } /// Removes the specified flags in-place. pub fn remove(&mut self, other: $BitFlags) { self.bits &=!other.bits; } } impl BitOr<$BitFlags, $BitFlags> for $BitFlags { /// Returns the union of the two sets of flags. #[inline] fn bitor(&self, other: &$BitFlags) -> $BitFlags { $BitFlags { bits: self.bits | other.bits } } } impl BitAnd<$BitFlags, $BitFlags> for $BitFlags { /// Returns the intersection between the two sets of flags. #[inline] fn bitand(&self, other: &$BitFlags) -> $BitFlags { $BitFlags { bits: self.bits & other.bits } } } impl Sub<$BitFlags, $BitFlags> for $BitFlags { /// Returns the set difference of the two sets of flags. #[inline] fn sub(&self, other: &$BitFlags) -> $BitFlags { $BitFlags { bits: self.bits &!other.bits } } } ) ) #[cfg(test)] mod tests { use ops::{BitOr, BitAnd, Sub}; bitflags!( flags Flags: u32 { static FlagA = 0x00000001, static FlagB = 0x00000010, static FlagC = 0x00000100, static FlagABC = FlagA.bits | FlagB.bits | FlagC.bits } ) #[test] fn test_bits(){ assert_eq!(Flags::empty().bits(), 0x00000000); assert_eq!(FlagA.bits(), 0x00000001); assert_eq!(FlagABC.bits(), 0x00000111); } #[test] fn test_is_empty(){ assert!(Flags::empty().is_empty()); assert!(!FlagA.is_empty()); assert!(!FlagABC.is_empty()); } #[test] fn test_two_empties_do_not_intersect() { let e1 = Flags::empty(); let e2 = Flags::empty(); assert!(!e1.intersects(e2)); } #[test] fn test_empty_does_not_intersect_with_full() { let e1 = Flags::empty(); let e2 = FlagABC; assert!(!e1.intersects(e2)); } #[test] fn test_disjoint_intersects() { let e1 = FlagA; let e2 = FlagB; assert!(!e1.intersects(e2)); } #[test] fn test_overlapping_intersects() { let e1 = FlagA; let e2 = FlagA | FlagB; assert!(e1.intersects(e2)); } #[test] fn test_contains() { let e1 = FlagA; let e2 = FlagA | FlagB; assert!(!e1.contains(e2)); assert!(e2.contains(e1)); assert!(FlagABC.contains(e2)); } #[test] fn test_insert(){ let mut e1 = FlagA; let e2 = FlagA | FlagB; e1.insert(e2); assert!(e1 == e2); } #[test] fn test_remove(){ let mut e1 = FlagA | FlagB; let e2 = FlagA | FlagC; e1.remove(e2); assert!(e1 == FlagB); } #[test] fn test_operators() { let e1 = FlagA | FlagC; let e2 = FlagB | FlagC; assert!((e1 | e2) == FlagABC); // union assert!((e1 & e2) == FlagC); // intersection assert!((e1 - e2) == FlagA); // set difference } }
random_line_split
bitflags.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 `bitflags!` macro generates a `struct` that holds a set of C-style //! bitmask flags. It is useful for creating typesafe wrappers for C APIs. //! //! The flags should only be defined for integer types, otherwise unexpected //! type errors may occur at compile time. //! //! # Example //! //! ~~~rust //! bitflags!( //! flags Flags: u32 { //! static FlagA = 0x00000001, //! static FlagB = 0x00000010, //! static FlagC = 0x00000100, //! static FlagABC = FlagA.bits //! | FlagB.bits //! | FlagC.bits //! } //! ) //! //! fn main() { //! let e1 = FlagA | FlagC; //! let e2 = FlagB | FlagC; //! assert!((e1 | e2) == FlagABC); // union //! assert!((e1 & e2) == FlagC); // intersection //! assert!((e1 - e2) == FlagA); // set difference //! } //! ~~~ //! //! The generated `struct`s can also be extended with type and trait implementations: //! //! ~~~rust //! use std::fmt; //! //! bitflags!( //! flags Flags: u32 { //! static FlagA = 0x00000001, //! static FlagB = 0x00000010 //! } //! ) //! //! impl Flags { //! pub fn clear(&mut self) { //! self.bits = 0; // The `bits` field can be accessed from within the //! // same module where the `bitflags!` macro was invoked. //! } //! } //! //! impl fmt::Show for Flags { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! write!(f.buf, "hi!") //! } //! } //! //! fn main() { //! let mut flags = FlagA | FlagB; //! flags.clear(); //! assert!(flags.is_empty()); //! assert_eq!(format!("{}", flags).as_slice(), "hi!"); //! } //! ~~~ //! //! # Attributes //! //! Attributes can be attached to the generated `struct` by placing them //! before the `flags` keyword. //! //! # Derived traits //! //! The `Eq` and `Clone` traits are automatically derived for the `struct` using //! the `deriving` attribute. Additional traits can be derived by providing an //! explicit `deriving` attribute on `flags`. //! //! # Operators //! //! The following operator traits are implemented for the generated `struct`: //! //! - `BitOr`: union //! - `BitAnd`: intersection //! - `Sub`: set difference //! //! # Methods //! //! The following methods are defined for the generated `struct`: //! //! - `empty`: an empty set of flags //! - `bits`: the raw value of the flags currently stored //! - `is_empty`: `true` if no flags are currently stored //! - `intersects`: `true` if there are flags common to both `self` and `other` //! - `contains`: `true` all of the flags in `other` are contained within `self` //! - `insert`: inserts the specified flags in-place //! - `remove`: removes the specified flags in-place #![macro_escape] #[macro_export] macro_rules! bitflags( ($(#[$attr:meta])* flags $BitFlags:ident: $T:ty { $($(#[$Flag_attr:meta])* static $Flag:ident = $value:expr),+ }) => ( #[deriving(Eq, TotalEq, Clone)] $(#[$attr])* pub struct $BitFlags { bits: $T, } $($(#[$Flag_attr])* pub static $Flag: $BitFlags = $BitFlags { bits: $value };)+ impl $BitFlags { /// Returns an empty set of flags. pub fn empty() -> $BitFlags { $BitFlags { bits: 0 } } /// Returns the raw value of the flags currently stored. pub fn bits(&self) -> $T { self.bits } /// Convert from underlying bit representation. Unsafe because the /// bits are not guaranteed to represent valid flags. pub unsafe fn from_bits(bits: $T) -> $BitFlags { $BitFlags { bits: bits } } /// Returns `true` if no flags are currently stored. pub fn is_empty(&self) -> bool { *self == $BitFlags::empty() } /// Returns `true` if there are flags common to both `self` and `other`. pub fn intersects(&self, other: $BitFlags) -> bool { !(self & other).is_empty() } /// Returns `true` all of the flags in `other` are contained within `self`. pub fn contains(&self, other: $BitFlags) -> bool { (self & other) == other } /// Inserts the specified flags in-place. pub fn insert(&mut self, other: $BitFlags) { self.bits |= other.bits; } /// Removes the specified flags in-place. pub fn remove(&mut self, other: $BitFlags) { self.bits &=!other.bits; } } impl BitOr<$BitFlags, $BitFlags> for $BitFlags { /// Returns the union of the two sets of flags. #[inline] fn bitor(&self, other: &$BitFlags) -> $BitFlags { $BitFlags { bits: self.bits | other.bits } } } impl BitAnd<$BitFlags, $BitFlags> for $BitFlags { /// Returns the intersection between the two sets of flags. #[inline] fn bitand(&self, other: &$BitFlags) -> $BitFlags { $BitFlags { bits: self.bits & other.bits } } } impl Sub<$BitFlags, $BitFlags> for $BitFlags { /// Returns the set difference of the two sets of flags. #[inline] fn sub(&self, other: &$BitFlags) -> $BitFlags { $BitFlags { bits: self.bits &!other.bits } } } ) ) #[cfg(test)] mod tests { use ops::{BitOr, BitAnd, Sub}; bitflags!( flags Flags: u32 { static FlagA = 0x00000001, static FlagB = 0x00000010, static FlagC = 0x00000100, static FlagABC = FlagA.bits | FlagB.bits | FlagC.bits } ) #[test] fn
(){ assert_eq!(Flags::empty().bits(), 0x00000000); assert_eq!(FlagA.bits(), 0x00000001); assert_eq!(FlagABC.bits(), 0x00000111); } #[test] fn test_is_empty(){ assert!(Flags::empty().is_empty()); assert!(!FlagA.is_empty()); assert!(!FlagABC.is_empty()); } #[test] fn test_two_empties_do_not_intersect() { let e1 = Flags::empty(); let e2 = Flags::empty(); assert!(!e1.intersects(e2)); } #[test] fn test_empty_does_not_intersect_with_full() { let e1 = Flags::empty(); let e2 = FlagABC; assert!(!e1.intersects(e2)); } #[test] fn test_disjoint_intersects() { let e1 = FlagA; let e2 = FlagB; assert!(!e1.intersects(e2)); } #[test] fn test_overlapping_intersects() { let e1 = FlagA; let e2 = FlagA | FlagB; assert!(e1.intersects(e2)); } #[test] fn test_contains() { let e1 = FlagA; let e2 = FlagA | FlagB; assert!(!e1.contains(e2)); assert!(e2.contains(e1)); assert!(FlagABC.contains(e2)); } #[test] fn test_insert(){ let mut e1 = FlagA; let e2 = FlagA | FlagB; e1.insert(e2); assert!(e1 == e2); } #[test] fn test_remove(){ let mut e1 = FlagA | FlagB; let e2 = FlagA | FlagC; e1.remove(e2); assert!(e1 == FlagB); } #[test] fn test_operators() { let e1 = FlagA | FlagC; let e2 = FlagB | FlagC; assert!((e1 | e2) == FlagABC); // union assert!((e1 & e2) == FlagC); // intersection assert!((e1 - e2) == FlagA); // set difference } }
test_bits
identifier_name
tokenizer.rs
//! A whitespace and comment preserving lexer designed for use in both the compiler frontend //! and IDEs. //! //! The output of the tokenizer is lightweight, and only contains information about the //! type of a [Token] and where it occurred in the source. use std::ops::Range; use itertools::Itertools; use logos::Lexer; use logos::Logos; use secsp_parser::syntax::TokenKind; use crate::token::Token; struct Tokenizer<'a> { lexer: Lexer<TokenKind, &'a str>, seen_eof: bool, } impl<'a> Tokenizer<'a> { fn new(text: &'a str) -> Self { Tokenizer { lexer: TokenKind::lexer(text), seen_eof: false, } }
} impl<'a> Iterator for Tokenizer<'a> { type Item = (TokenKind, Range<usize>); fn next(&mut self) -> Option<Self::Item> { if self.seen_eof { return None; } let ty = self.lexer.token; let range = self.lexer.range(); self.lexer.advance(); if ty == TokenKind::Eof { self.seen_eof = true; } Some((ty, range)) } } /// Runs the tokenizer on an input string and collects all of the output tokens /// into a list, continuing past lex errors. pub fn tokenize<S: AsRef<str>>(str: S) -> Vec<Token> { let tokenizer = Tokenizer::new(str.as_ref()); let mut tokens: Vec<Token> = vec![]; let mut iter = tokenizer.peekable(); while let Some((token, range)) = iter.next() { match token { TokenKind::Illegal | TokenKind::Whitespace | TokenKind::LineComment => { let range = iter .peeking_take_while(|(ty, _)| *ty == token) .map(|(_, range)| range) .last() .map_or(range.clone(), |to| range.start..to.end); tokens.push(Token::new(token, range)) } _ => tokens.push(Token::new(token, range)), } } tokens } #[test] fn preserves_whitespace() { let types: Vec<TokenKind> = tokenize("test abc 123") .into_iter() .map(|t| t.into()) .collect(); assert_eq!( vec![ TokenKind::Name, TokenKind::Whitespace, TokenKind::Name, TokenKind::Whitespace, TokenKind::Integer, TokenKind::Eof, ], types ); }
random_line_split
tokenizer.rs
//! A whitespace and comment preserving lexer designed for use in both the compiler frontend //! and IDEs. //! //! The output of the tokenizer is lightweight, and only contains information about the //! type of a [Token] and where it occurred in the source. use std::ops::Range; use itertools::Itertools; use logos::Lexer; use logos::Logos; use secsp_parser::syntax::TokenKind; use crate::token::Token; struct Tokenizer<'a> { lexer: Lexer<TokenKind, &'a str>, seen_eof: bool, } impl<'a> Tokenizer<'a> { fn new(text: &'a str) -> Self { Tokenizer { lexer: TokenKind::lexer(text), seen_eof: false, } } } impl<'a> Iterator for Tokenizer<'a> { type Item = (TokenKind, Range<usize>); fn next(&mut self) -> Option<Self::Item> { if self.seen_eof { return None; } let ty = self.lexer.token; let range = self.lexer.range(); self.lexer.advance(); if ty == TokenKind::Eof { self.seen_eof = true; } Some((ty, range)) } } /// Runs the tokenizer on an input string and collects all of the output tokens /// into a list, continuing past lex errors. pub fn tokenize<S: AsRef<str>>(str: S) -> Vec<Token> { let tokenizer = Tokenizer::new(str.as_ref()); let mut tokens: Vec<Token> = vec![]; let mut iter = tokenizer.peekable(); while let Some((token, range)) = iter.next() { match token { TokenKind::Illegal | TokenKind::Whitespace | TokenKind::LineComment => { let range = iter .peeking_take_while(|(ty, _)| *ty == token) .map(|(_, range)| range) .last() .map_or(range.clone(), |to| range.start..to.end); tokens.push(Token::new(token, range)) } _ => tokens.push(Token::new(token, range)), } } tokens } #[test] fn preserves_whitespace()
{ let types: Vec<TokenKind> = tokenize("test abc 123") .into_iter() .map(|t| t.into()) .collect(); assert_eq!( vec![ TokenKind::Name, TokenKind::Whitespace, TokenKind::Name, TokenKind::Whitespace, TokenKind::Integer, TokenKind::Eof, ], types ); }
identifier_body
tokenizer.rs
//! A whitespace and comment preserving lexer designed for use in both the compiler frontend //! and IDEs. //! //! The output of the tokenizer is lightweight, and only contains information about the //! type of a [Token] and where it occurred in the source. use std::ops::Range; use itertools::Itertools; use logos::Lexer; use logos::Logos; use secsp_parser::syntax::TokenKind; use crate::token::Token; struct
<'a> { lexer: Lexer<TokenKind, &'a str>, seen_eof: bool, } impl<'a> Tokenizer<'a> { fn new(text: &'a str) -> Self { Tokenizer { lexer: TokenKind::lexer(text), seen_eof: false, } } } impl<'a> Iterator for Tokenizer<'a> { type Item = (TokenKind, Range<usize>); fn next(&mut self) -> Option<Self::Item> { if self.seen_eof { return None; } let ty = self.lexer.token; let range = self.lexer.range(); self.lexer.advance(); if ty == TokenKind::Eof { self.seen_eof = true; } Some((ty, range)) } } /// Runs the tokenizer on an input string and collects all of the output tokens /// into a list, continuing past lex errors. pub fn tokenize<S: AsRef<str>>(str: S) -> Vec<Token> { let tokenizer = Tokenizer::new(str.as_ref()); let mut tokens: Vec<Token> = vec![]; let mut iter = tokenizer.peekable(); while let Some((token, range)) = iter.next() { match token { TokenKind::Illegal | TokenKind::Whitespace | TokenKind::LineComment => { let range = iter .peeking_take_while(|(ty, _)| *ty == token) .map(|(_, range)| range) .last() .map_or(range.clone(), |to| range.start..to.end); tokens.push(Token::new(token, range)) } _ => tokens.push(Token::new(token, range)), } } tokens } #[test] fn preserves_whitespace() { let types: Vec<TokenKind> = tokenize("test abc 123") .into_iter() .map(|t| t.into()) .collect(); assert_eq!( vec![ TokenKind::Name, TokenKind::Whitespace, TokenKind::Name, TokenKind::Whitespace, TokenKind::Integer, TokenKind::Eof, ], types ); }
Tokenizer
identifier_name
main.rs
extern crate rustbox; extern crate memmap; extern crate clap; use std::error::Error; // use std::default::Default; // use std::cmp; // use std::char; use std::env; use memmap::{Mmap, Protection}; use rustbox::{Color, RustBox, Key, Event}; use clap::{App, Arg}; fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize { a.chars().zip(b.chars()).take_while(|&(c1, c2)| c1 == c2).count() } fn header(width: usize) -> String { format!("{:1$}0 1 2 3 4 5 6 7 8 9 A B C D E F", "", width + 3) } fn string_repeat(s: &str, n: usize) -> String { std::iter::repeat(s).take(n).collect::<String>() } fn offset(offset: usize, width: usize, trimming_offset: Option<String>) -> String { match trimming_offset { None => { format!("{:01$x}: ", offset, width) } Some(trimming_string) => { let new_fmt = format!("{:01$x}: ", offset, width); let n_chars_to_remove = longest_prefix(&new_fmt, &trimming_string); let padding = string_repeat(" ", n_chars_to_remove); padding + &new_fmt[n_chars_to_remove..] } } } fn offset_width(num_bytes: usize) -> usize { // +1 byte for the final EOF symbol // +1 for the base-16 computation (((num_bytes + 1) as f64).log(16.0) as usize) + 1 } fn try_open_file(file_path: &str) -> Result<(Mmap, bool), std::io::Error> { let mut is_read_only = false; let mut file_mmap_try = Mmap::open_path(file_path, Protection::ReadWrite); if file_mmap_try.is_err() { file_mmap_try = Mmap::open_path(file_path, Protection::Read); is_read_only = true; } file_mmap_try.map(|x| (x, is_read_only)) } fn standard_output(file_path: &str) { let file_mmap = Mmap::open_path(file_path, Protection::Read).unwrap(); let bytes: &[u8] = unsafe { file_mmap.as_slice() }; let offset_width = offset_width(bytes.len()); println!("{}\n", header(offset_width)); let mut prev_offset: String = offset(0, offset_width, None); let mut should_trim = true; print!("{}", prev_offset); for (idx, chunk) in bytes.chunks(16).enumerate() { if chunk.iter().all(|&x| x == 0) { should_trim = false; continue; } for b in chunk { match *b { // ASCII printable 0x20u8...0x7e => { print!(".{} ", *b as char) } 0x00 => { print!(" ") } 0xFF => { print!("## ") } _ => { print!("{:02X} ", b) } } } let trimming_offset = if should_trim { Some(prev_offset.clone()) } else { None }; let new_offset = offset((idx + 1) * 16, offset_width, trimming_offset); // TODO: idx + 1 is wrong print!("\n{}", new_offset); prev_offset = new_offset; should_trim = true; } if should_trim { // that means just skipped a bunch of zeroes at the end } println!("Ω⸫"); } struct EditorState { open_file: Option<Mmap>, read_only: bool, } fn rustbox_output(file_path: &str) { let rustbox = match RustBox::init(Default::default()) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; let mut state = EditorState { open_file: None, read_only: false }; // rustbox.print(1, 1, rustbox::RB_BOLD, Color::White, Color::Black, "Hello, world!"); // rustbox.print(1, 3, rustbox::RB_BOLD, Color::White, Color::Black, // "Press 'q' to quit."); // let mut file_mmap_try = try_open_file(file_path); // let offset_width = offset_width(bytes.len()); loop { rustbox.print(rustbox.width() - 10, 0, rustbox::RB_BOLD, Color::White, Color::Black, "HexRS"); rustbox.present(); match rustbox.poll_event(false).unwrap() { Event::KeyEvent(key) => { match key { Key::Char('q') => { return; } Key::Esc => { return; } _ => { } } } _ => { } } } } fn main() { let matches = App::new("HexRS").version("0.1").args_from_usage(
"-i, --interactive 'Use the interactive version instead of outputting to stdout' [INPUT] 'Specifies the input file to use'").get_matches(); if let Some(file_path) = matches.value_of("INPUT") { if matches.is_present("interactive") { rustbox_output(&file_path); } else { standard_output(&file_path); } } }
random_line_split
main.rs
extern crate rustbox; extern crate memmap; extern crate clap; use std::error::Error; // use std::default::Default; // use std::cmp; // use std::char; use std::env; use memmap::{Mmap, Protection}; use rustbox::{Color, RustBox, Key, Event}; use clap::{App, Arg}; fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize { a.chars().zip(b.chars()).take_while(|&(c1, c2)| c1 == c2).count() } fn header(width: usize) -> String
fn string_repeat(s: &str, n: usize) -> String { std::iter::repeat(s).take(n).collect::<String>() } fn offset(offset: usize, width: usize, trimming_offset: Option<String>) -> String { match trimming_offset { None => { format!("{:01$x}: ", offset, width) } Some(trimming_string) => { let new_fmt = format!("{:01$x}: ", offset, width); let n_chars_to_remove = longest_prefix(&new_fmt, &trimming_string); let padding = string_repeat(" ", n_chars_to_remove); padding + &new_fmt[n_chars_to_remove..] } } } fn offset_width(num_bytes: usize) -> usize { // +1 byte for the final EOF symbol // +1 for the base-16 computation (((num_bytes + 1) as f64).log(16.0) as usize) + 1 } fn try_open_file(file_path: &str) -> Result<(Mmap, bool), std::io::Error> { let mut is_read_only = false; let mut file_mmap_try = Mmap::open_path(file_path, Protection::ReadWrite); if file_mmap_try.is_err() { file_mmap_try = Mmap::open_path(file_path, Protection::Read); is_read_only = true; } file_mmap_try.map(|x| (x, is_read_only)) } fn standard_output(file_path: &str) { let file_mmap = Mmap::open_path(file_path, Protection::Read).unwrap(); let bytes: &[u8] = unsafe { file_mmap.as_slice() }; let offset_width = offset_width(bytes.len()); println!("{}\n", header(offset_width)); let mut prev_offset: String = offset(0, offset_width, None); let mut should_trim = true; print!("{}", prev_offset); for (idx, chunk) in bytes.chunks(16).enumerate() { if chunk.iter().all(|&x| x == 0) { should_trim = false; continue; } for b in chunk { match *b { // ASCII printable 0x20u8...0x7e => { print!(".{} ", *b as char) } 0x00 => { print!(" ") } 0xFF => { print!("## ") } _ => { print!("{:02X} ", b) } } } let trimming_offset = if should_trim { Some(prev_offset.clone()) } else { None }; let new_offset = offset((idx + 1) * 16, offset_width, trimming_offset); // TODO: idx + 1 is wrong print!("\n{}", new_offset); prev_offset = new_offset; should_trim = true; } if should_trim { // that means just skipped a bunch of zeroes at the end } println!("Ω⸫"); } struct EditorState { open_file: Option<Mmap>, read_only: bool, } fn rustbox_output(file_path: &str) { let rustbox = match RustBox::init(Default::default()) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; let mut state = EditorState { open_file: None, read_only: false }; // rustbox.print(1, 1, rustbox::RB_BOLD, Color::White, Color::Black, "Hello, world!"); // rustbox.print(1, 3, rustbox::RB_BOLD, Color::White, Color::Black, // "Press 'q' to quit."); // let mut file_mmap_try = try_open_file(file_path); // let offset_width = offset_width(bytes.len()); loop { rustbox.print(rustbox.width() - 10, 0, rustbox::RB_BOLD, Color::White, Color::Black, "HexRS"); rustbox.present(); match rustbox.poll_event(false).unwrap() { Event::KeyEvent(key) => { match key { Key::Char('q') => { return; } Key::Esc => { return; } _ => { } } } _ => { } } } } fn main() { let matches = App::new("HexRS").version("0.1").args_from_usage( "-i, --interactive 'Use the interactive version instead of outputting to stdout' [INPUT] 'Specifies the input file to use'").get_matches(); if let Some(file_path) = matches.value_of("INPUT") { if matches.is_present("interactive") { rustbox_output(&file_path); } else { standard_output(&file_path); } } }
{ format!("{:1$}0 1 2 3 4 5 6 7 8 9 A B C D E F", "", width + 3) }
identifier_body
main.rs
extern crate rustbox; extern crate memmap; extern crate clap; use std::error::Error; // use std::default::Default; // use std::cmp; // use std::char; use std::env; use memmap::{Mmap, Protection}; use rustbox::{Color, RustBox, Key, Event}; use clap::{App, Arg}; fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize { a.chars().zip(b.chars()).take_while(|&(c1, c2)| c1 == c2).count() } fn header(width: usize) -> String { format!("{:1$}0 1 2 3 4 5 6 7 8 9 A B C D E F", "", width + 3) } fn string_repeat(s: &str, n: usize) -> String { std::iter::repeat(s).take(n).collect::<String>() } fn offset(offset: usize, width: usize, trimming_offset: Option<String>) -> String { match trimming_offset { None => { format!("{:01$x}: ", offset, width) } Some(trimming_string) => { let new_fmt = format!("{:01$x}: ", offset, width); let n_chars_to_remove = longest_prefix(&new_fmt, &trimming_string); let padding = string_repeat(" ", n_chars_to_remove); padding + &new_fmt[n_chars_to_remove..] } } } fn offset_width(num_bytes: usize) -> usize { // +1 byte for the final EOF symbol // +1 for the base-16 computation (((num_bytes + 1) as f64).log(16.0) as usize) + 1 } fn try_open_file(file_path: &str) -> Result<(Mmap, bool), std::io::Error> { let mut is_read_only = false; let mut file_mmap_try = Mmap::open_path(file_path, Protection::ReadWrite); if file_mmap_try.is_err() { file_mmap_try = Mmap::open_path(file_path, Protection::Read); is_read_only = true; } file_mmap_try.map(|x| (x, is_read_only)) } fn standard_output(file_path: &str) { let file_mmap = Mmap::open_path(file_path, Protection::Read).unwrap(); let bytes: &[u8] = unsafe { file_mmap.as_slice() }; let offset_width = offset_width(bytes.len()); println!("{}\n", header(offset_width)); let mut prev_offset: String = offset(0, offset_width, None); let mut should_trim = true; print!("{}", prev_offset); for (idx, chunk) in bytes.chunks(16).enumerate() { if chunk.iter().all(|&x| x == 0) { should_trim = false; continue; } for b in chunk { match *b { // ASCII printable 0x20u8...0x7e => { print!(".{} ", *b as char) } 0x00 =>
0xFF => { print!("## ") } _ => { print!("{:02X} ", b) } } } let trimming_offset = if should_trim { Some(prev_offset.clone()) } else { None }; let new_offset = offset((idx + 1) * 16, offset_width, trimming_offset); // TODO: idx + 1 is wrong print!("\n{}", new_offset); prev_offset = new_offset; should_trim = true; } if should_trim { // that means just skipped a bunch of zeroes at the end } println!("Ω⸫"); } struct EditorState { open_file: Option<Mmap>, read_only: bool, } fn rustbox_output(file_path: &str) { let rustbox = match RustBox::init(Default::default()) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; let mut state = EditorState { open_file: None, read_only: false }; // rustbox.print(1, 1, rustbox::RB_BOLD, Color::White, Color::Black, "Hello, world!"); // rustbox.print(1, 3, rustbox::RB_BOLD, Color::White, Color::Black, // "Press 'q' to quit."); // let mut file_mmap_try = try_open_file(file_path); // let offset_width = offset_width(bytes.len()); loop { rustbox.print(rustbox.width() - 10, 0, rustbox::RB_BOLD, Color::White, Color::Black, "HexRS"); rustbox.present(); match rustbox.poll_event(false).unwrap() { Event::KeyEvent(key) => { match key { Key::Char('q') => { return; } Key::Esc => { return; } _ => { } } } _ => { } } } } fn main() { let matches = App::new("HexRS").version("0.1").args_from_usage( "-i, --interactive 'Use the interactive version instead of outputting to stdout' [INPUT] 'Specifies the input file to use'").get_matches(); if let Some(file_path) = matches.value_of("INPUT") { if matches.is_present("interactive") { rustbox_output(&file_path); } else { standard_output(&file_path); } } }
{ print!(" ") }
conditional_block
main.rs
extern crate rustbox; extern crate memmap; extern crate clap; use std::error::Error; // use std::default::Default; // use std::cmp; // use std::char; use std::env; use memmap::{Mmap, Protection}; use rustbox::{Color, RustBox, Key, Event}; use clap::{App, Arg}; fn longest_prefix<'a>(a: &'a str, b: &'a str) -> usize { a.chars().zip(b.chars()).take_while(|&(c1, c2)| c1 == c2).count() } fn header(width: usize) -> String { format!("{:1$}0 1 2 3 4 5 6 7 8 9 A B C D E F", "", width + 3) } fn string_repeat(s: &str, n: usize) -> String { std::iter::repeat(s).take(n).collect::<String>() } fn offset(offset: usize, width: usize, trimming_offset: Option<String>) -> String { match trimming_offset { None => { format!("{:01$x}: ", offset, width) } Some(trimming_string) => { let new_fmt = format!("{:01$x}: ", offset, width); let n_chars_to_remove = longest_prefix(&new_fmt, &trimming_string); let padding = string_repeat(" ", n_chars_to_remove); padding + &new_fmt[n_chars_to_remove..] } } } fn offset_width(num_bytes: usize) -> usize { // +1 byte for the final EOF symbol // +1 for the base-16 computation (((num_bytes + 1) as f64).log(16.0) as usize) + 1 } fn try_open_file(file_path: &str) -> Result<(Mmap, bool), std::io::Error> { let mut is_read_only = false; let mut file_mmap_try = Mmap::open_path(file_path, Protection::ReadWrite); if file_mmap_try.is_err() { file_mmap_try = Mmap::open_path(file_path, Protection::Read); is_read_only = true; } file_mmap_try.map(|x| (x, is_read_only)) } fn standard_output(file_path: &str) { let file_mmap = Mmap::open_path(file_path, Protection::Read).unwrap(); let bytes: &[u8] = unsafe { file_mmap.as_slice() }; let offset_width = offset_width(bytes.len()); println!("{}\n", header(offset_width)); let mut prev_offset: String = offset(0, offset_width, None); let mut should_trim = true; print!("{}", prev_offset); for (idx, chunk) in bytes.chunks(16).enumerate() { if chunk.iter().all(|&x| x == 0) { should_trim = false; continue; } for b in chunk { match *b { // ASCII printable 0x20u8...0x7e => { print!(".{} ", *b as char) } 0x00 => { print!(" ") } 0xFF => { print!("## ") } _ => { print!("{:02X} ", b) } } } let trimming_offset = if should_trim { Some(prev_offset.clone()) } else { None }; let new_offset = offset((idx + 1) * 16, offset_width, trimming_offset); // TODO: idx + 1 is wrong print!("\n{}", new_offset); prev_offset = new_offset; should_trim = true; } if should_trim { // that means just skipped a bunch of zeroes at the end } println!("Ω⸫"); } struct EditorState { open_file: Option<Mmap>, read_only: bool, } fn rus
le_path: &str) { let rustbox = match RustBox::init(Default::default()) { Result::Ok(v) => v, Result::Err(e) => panic!("{}", e), }; let mut state = EditorState { open_file: None, read_only: false }; // rustbox.print(1, 1, rustbox::RB_BOLD, Color::White, Color::Black, "Hello, world!"); // rustbox.print(1, 3, rustbox::RB_BOLD, Color::White, Color::Black, // "Press 'q' to quit."); // let mut file_mmap_try = try_open_file(file_path); // let offset_width = offset_width(bytes.len()); loop { rustbox.print(rustbox.width() - 10, 0, rustbox::RB_BOLD, Color::White, Color::Black, "HexRS"); rustbox.present(); match rustbox.poll_event(false).unwrap() { Event::KeyEvent(key) => { match key { Key::Char('q') => { return; } Key::Esc => { return; } _ => { } } } _ => { } } } } fn main() { let matches = App::new("HexRS").version("0.1").args_from_usage( "-i, --interactive 'Use the interactive version instead of outputting to stdout' [INPUT] 'Specifies the input file to use'").get_matches(); if let Some(file_path) = matches.value_of("INPUT") { if matches.is_present("interactive") { rustbox_output(&file_path); } else { standard_output(&file_path); } } }
tbox_output(fi
identifier_name
history.rs
use std::io::prelude::*; use std::path::Path; use curl::http; use yaml_rust::Yaml; use super::file; use super::yaml_util; use super::request::SpagRequest; use super::remember; const HISTORY_DIR: &'static str = ".spag"; const HISTORY_FILE: &'static str = ".spag/history.yml"; const HISTORY_LIMIT: usize = 100; pub fn ensure_history_exists() { if!Path::new(HISTORY_FILE).exists() { file::ensure_dir_exists(HISTORY_DIR); file::write_file(HISTORY_FILE, "[]"); } } pub fn append(req: &SpagRequest, resp: &http::Response) -> Result<(), String> { ensure_history_exists(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { // Trim the history, -1 so that our request fits under the limit if arr.len() > HISTORY_LIMIT - 1 { while arr.len() > HISTORY_LIMIT - 1 { arr.remove(0); } }
Ok(try!(yaml_util::dump_yaml_file(HISTORY_FILE, &y))) } pub fn list() -> Result<Vec<String>, String> { ensure_history_exists(); let mut result = Vec::new(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { for y in arr.iter() { let method = try!(yaml_util::get_value_as_string(&y, &["request", "method"])); let endpoint = try!(yaml_util::get_value_as_string(&y, &["request", "endpoint"])); let uri = try!(yaml_util::get_value_as_string(&y, &["request", "uri"])); let s = format!("{} {}{}", method, endpoint, uri); result.push(s); } } Ok(result) } pub fn get(raw_index: &String) -> Result<String, String> { ensure_history_exists(); let index = raw_index.parse().unwrap(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { let target = match arr.get(index) { Some(yaml) => yaml, None => return Err(format!("No request at #{}", index)), }; // Request data let mut output = "-------------------- Request ---------------------\n".to_string(); let method = try!(yaml_util::get_value_as_string(&target, &["request", "method"])); let endpoint = try!(yaml_util::get_value_as_string(&target, &["request", "endpoint"])); let uri = try!(yaml_util::get_value_as_string(&target, &["request", "uri"])); let body = try!(yaml_util::get_value_as_string(&target, &["request", "body"])); output.push_str(format!("{} {}{}\n", method, endpoint, uri).as_str()); match yaml_util::get_nested_value(&target, &["request", "headers"]) { Some(&Yaml::Hash(ref headers)) => { for (key, value) in headers.iter() { output.push_str(format!("{}: {}\n", key.as_str().unwrap(), value.as_str().unwrap()).as_str()); } }, None => {}, _ => { return Err(format!("Invalid headers in request history #{}.", index))}, }; output.push_str(format!("Body:\n{}\n", body).as_str()); // Response Data output.push_str("-------------------- Response ---------------------\n"); let body = try!(yaml_util::get_value_as_string(&target, &["response", "body"])); let status = try!(yaml_util::get_value_as_string(&target, &["response", "status"])); output.push_str(format!("Status code {}\n", status).as_str()); match yaml_util::get_nested_value(&target, &["response", "headers"]) { Some(&Yaml::Hash(ref headers)) => { for (key, value) in headers.iter() { output.push_str(format!("{}: {}\n", key.as_str().unwrap(), value.as_str().unwrap()).as_str()); } }, None => {}, _ => { return Err(format!("Invalid headers in request history #{}.", index))}, }; output.push_str(format!("Body:\n{}\n", body).as_str()); Ok(output.to_string()) } else { Err(format!("Failed to load history file {}", HISTORY_FILE)) } }
let new_entry = remember::serialize(req, resp); arr.insert(0, new_entry); }
random_line_split
history.rs
use std::io::prelude::*; use std::path::Path; use curl::http; use yaml_rust::Yaml; use super::file; use super::yaml_util; use super::request::SpagRequest; use super::remember; const HISTORY_DIR: &'static str = ".spag"; const HISTORY_FILE: &'static str = ".spag/history.yml"; const HISTORY_LIMIT: usize = 100; pub fn ensure_history_exists() { if!Path::new(HISTORY_FILE).exists() { file::ensure_dir_exists(HISTORY_DIR); file::write_file(HISTORY_FILE, "[]"); } } pub fn append(req: &SpagRequest, resp: &http::Response) -> Result<(), String> { ensure_history_exists(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { // Trim the history, -1 so that our request fits under the limit if arr.len() > HISTORY_LIMIT - 1 { while arr.len() > HISTORY_LIMIT - 1 { arr.remove(0); } } let new_entry = remember::serialize(req, resp); arr.insert(0, new_entry); } Ok(try!(yaml_util::dump_yaml_file(HISTORY_FILE, &y))) } pub fn list() -> Result<Vec<String>, String> { ensure_history_exists(); let mut result = Vec::new(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { for y in arr.iter() { let method = try!(yaml_util::get_value_as_string(&y, &["request", "method"])); let endpoint = try!(yaml_util::get_value_as_string(&y, &["request", "endpoint"])); let uri = try!(yaml_util::get_value_as_string(&y, &["request", "uri"])); let s = format!("{} {}{}", method, endpoint, uri); result.push(s); } } Ok(result) } pub fn get(raw_index: &String) -> Result<String, String> { ensure_history_exists(); let index = raw_index.parse().unwrap(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { let target = match arr.get(index) { Some(yaml) => yaml, None => return Err(format!("No request at #{}", index)), }; // Request data let mut output = "-------------------- Request ---------------------\n".to_string(); let method = try!(yaml_util::get_value_as_string(&target, &["request", "method"])); let endpoint = try!(yaml_util::get_value_as_string(&target, &["request", "endpoint"])); let uri = try!(yaml_util::get_value_as_string(&target, &["request", "uri"])); let body = try!(yaml_util::get_value_as_string(&target, &["request", "body"])); output.push_str(format!("{} {}{}\n", method, endpoint, uri).as_str()); match yaml_util::get_nested_value(&target, &["request", "headers"]) { Some(&Yaml::Hash(ref headers)) => { for (key, value) in headers.iter() { output.push_str(format!("{}: {}\n", key.as_str().unwrap(), value.as_str().unwrap()).as_str()); } }, None => {}, _ => { return Err(format!("Invalid headers in request history #{}.", index))}, }; output.push_str(format!("Body:\n{}\n", body).as_str()); // Response Data output.push_str("-------------------- Response ---------------------\n"); let body = try!(yaml_util::get_value_as_string(&target, &["response", "body"])); let status = try!(yaml_util::get_value_as_string(&target, &["response", "status"])); output.push_str(format!("Status code {}\n", status).as_str()); match yaml_util::get_nested_value(&target, &["response", "headers"]) { Some(&Yaml::Hash(ref headers)) => { for (key, value) in headers.iter() { output.push_str(format!("{}: {}\n", key.as_str().unwrap(), value.as_str().unwrap()).as_str()); } }, None =>
, _ => { return Err(format!("Invalid headers in request history #{}.", index))}, }; output.push_str(format!("Body:\n{}\n", body).as_str()); Ok(output.to_string()) } else { Err(format!("Failed to load history file {}", HISTORY_FILE)) } }
{}
conditional_block
history.rs
use std::io::prelude::*; use std::path::Path; use curl::http; use yaml_rust::Yaml; use super::file; use super::yaml_util; use super::request::SpagRequest; use super::remember; const HISTORY_DIR: &'static str = ".spag"; const HISTORY_FILE: &'static str = ".spag/history.yml"; const HISTORY_LIMIT: usize = 100; pub fn ensure_history_exists() { if!Path::new(HISTORY_FILE).exists() { file::ensure_dir_exists(HISTORY_DIR); file::write_file(HISTORY_FILE, "[]"); } } pub fn append(req: &SpagRequest, resp: &http::Response) -> Result<(), String>
} pub fn list() -> Result<Vec<String>, String> { ensure_history_exists(); let mut result = Vec::new(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { for y in arr.iter() { let method = try!(yaml_util::get_value_as_string(&y, &["request", "method"])); let endpoint = try!(yaml_util::get_value_as_string(&y, &["request", "endpoint"])); let uri = try!(yaml_util::get_value_as_string(&y, &["request", "uri"])); let s = format!("{} {}{}", method, endpoint, uri); result.push(s); } } Ok(result) } pub fn get(raw_index: &String) -> Result<String, String> { ensure_history_exists(); let index = raw_index.parse().unwrap(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { let target = match arr.get(index) { Some(yaml) => yaml, None => return Err(format!("No request at #{}", index)), }; // Request data let mut output = "-------------------- Request ---------------------\n".to_string(); let method = try!(yaml_util::get_value_as_string(&target, &["request", "method"])); let endpoint = try!(yaml_util::get_value_as_string(&target, &["request", "endpoint"])); let uri = try!(yaml_util::get_value_as_string(&target, &["request", "uri"])); let body = try!(yaml_util::get_value_as_string(&target, &["request", "body"])); output.push_str(format!("{} {}{}\n", method, endpoint, uri).as_str()); match yaml_util::get_nested_value(&target, &["request", "headers"]) { Some(&Yaml::Hash(ref headers)) => { for (key, value) in headers.iter() { output.push_str(format!("{}: {}\n", key.as_str().unwrap(), value.as_str().unwrap()).as_str()); } }, None => {}, _ => { return Err(format!("Invalid headers in request history #{}.", index))}, }; output.push_str(format!("Body:\n{}\n", body).as_str()); // Response Data output.push_str("-------------------- Response ---------------------\n"); let body = try!(yaml_util::get_value_as_string(&target, &["response", "body"])); let status = try!(yaml_util::get_value_as_string(&target, &["response", "status"])); output.push_str(format!("Status code {}\n", status).as_str()); match yaml_util::get_nested_value(&target, &["response", "headers"]) { Some(&Yaml::Hash(ref headers)) => { for (key, value) in headers.iter() { output.push_str(format!("{}: {}\n", key.as_str().unwrap(), value.as_str().unwrap()).as_str()); } }, None => {}, _ => { return Err(format!("Invalid headers in request history #{}.", index))}, }; output.push_str(format!("Body:\n{}\n", body).as_str()); Ok(output.to_string()) } else { Err(format!("Failed to load history file {}", HISTORY_FILE)) } }
{ ensure_history_exists(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { // Trim the history, -1 so that our request fits under the limit if arr.len() > HISTORY_LIMIT - 1 { while arr.len() > HISTORY_LIMIT - 1 { arr.remove(0); } } let new_entry = remember::serialize(req, resp); arr.insert(0, new_entry); } Ok(try!(yaml_util::dump_yaml_file(HISTORY_FILE, &y)))
identifier_body
history.rs
use std::io::prelude::*; use std::path::Path; use curl::http; use yaml_rust::Yaml; use super::file; use super::yaml_util; use super::request::SpagRequest; use super::remember; const HISTORY_DIR: &'static str = ".spag"; const HISTORY_FILE: &'static str = ".spag/history.yml"; const HISTORY_LIMIT: usize = 100; pub fn
() { if!Path::new(HISTORY_FILE).exists() { file::ensure_dir_exists(HISTORY_DIR); file::write_file(HISTORY_FILE, "[]"); } } pub fn append(req: &SpagRequest, resp: &http::Response) -> Result<(), String> { ensure_history_exists(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { // Trim the history, -1 so that our request fits under the limit if arr.len() > HISTORY_LIMIT - 1 { while arr.len() > HISTORY_LIMIT - 1 { arr.remove(0); } } let new_entry = remember::serialize(req, resp); arr.insert(0, new_entry); } Ok(try!(yaml_util::dump_yaml_file(HISTORY_FILE, &y))) } pub fn list() -> Result<Vec<String>, String> { ensure_history_exists(); let mut result = Vec::new(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { for y in arr.iter() { let method = try!(yaml_util::get_value_as_string(&y, &["request", "method"])); let endpoint = try!(yaml_util::get_value_as_string(&y, &["request", "endpoint"])); let uri = try!(yaml_util::get_value_as_string(&y, &["request", "uri"])); let s = format!("{} {}{}", method, endpoint, uri); result.push(s); } } Ok(result) } pub fn get(raw_index: &String) -> Result<String, String> { ensure_history_exists(); let index = raw_index.parse().unwrap(); let mut y = &mut try!(yaml_util::load_yaml_file(&HISTORY_FILE)); if let Yaml::Array(ref mut arr) = *y { let target = match arr.get(index) { Some(yaml) => yaml, None => return Err(format!("No request at #{}", index)), }; // Request data let mut output = "-------------------- Request ---------------------\n".to_string(); let method = try!(yaml_util::get_value_as_string(&target, &["request", "method"])); let endpoint = try!(yaml_util::get_value_as_string(&target, &["request", "endpoint"])); let uri = try!(yaml_util::get_value_as_string(&target, &["request", "uri"])); let body = try!(yaml_util::get_value_as_string(&target, &["request", "body"])); output.push_str(format!("{} {}{}\n", method, endpoint, uri).as_str()); match yaml_util::get_nested_value(&target, &["request", "headers"]) { Some(&Yaml::Hash(ref headers)) => { for (key, value) in headers.iter() { output.push_str(format!("{}: {}\n", key.as_str().unwrap(), value.as_str().unwrap()).as_str()); } }, None => {}, _ => { return Err(format!("Invalid headers in request history #{}.", index))}, }; output.push_str(format!("Body:\n{}\n", body).as_str()); // Response Data output.push_str("-------------------- Response ---------------------\n"); let body = try!(yaml_util::get_value_as_string(&target, &["response", "body"])); let status = try!(yaml_util::get_value_as_string(&target, &["response", "status"])); output.push_str(format!("Status code {}\n", status).as_str()); match yaml_util::get_nested_value(&target, &["response", "headers"]) { Some(&Yaml::Hash(ref headers)) => { for (key, value) in headers.iter() { output.push_str(format!("{}: {}\n", key.as_str().unwrap(), value.as_str().unwrap()).as_str()); } }, None => {}, _ => { return Err(format!("Invalid headers in request history #{}.", index))}, }; output.push_str(format!("Body:\n{}\n", body).as_str()); Ok(output.to_string()) } else { Err(format!("Failed to load history file {}", HISTORY_FILE)) } }
ensure_history_exists
identifier_name
extern-return-TwoU32s.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. // pretty-expanded FIXME #23616 pub struct TwoU32s { one: u32, two: u32 } #[link(name = "rust_test_helpers")] extern {
} pub fn main() { unsafe { let y = rust_dbg_extern_return_TwoU32s(); assert_eq!(y.one, 10); assert_eq!(y.two, 20); } }
pub fn rust_dbg_extern_return_TwoU32s() -> TwoU32s;
random_line_split
extern-return-TwoU32s.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. // pretty-expanded FIXME #23616 pub struct
{ one: u32, two: u32 } #[link(name = "rust_test_helpers")] extern { pub fn rust_dbg_extern_return_TwoU32s() -> TwoU32s; } pub fn main() { unsafe { let y = rust_dbg_extern_return_TwoU32s(); assert_eq!(y.one, 10); assert_eq!(y.two, 20); } }
TwoU32s
identifier_name
htmlselectelement.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::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement}; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, UnbindContext, window_from_node}; use dom::nodelist::NodeList; use dom::validation::Validatable; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; use style::element_state::*; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } static DEFAULT_SELECT_SIZE: u32 = 0; impl HTMLSelectElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } // https://html.spec.whatwg.org/multipage/#ask-for-a-reset pub fn ask_for_reset(&self) { if self.Multiple() { return; } let mut first_enabled: Option<Root<HTMLOptionElement>> = None; let mut last_selected: Option<Root<HTMLOptionElement>> = None; let node = self.upcast::<Node>(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.Selected() { opt.set_selectedness(false); last_selected = Some(Root::from_ref(opt.r())); } let element = opt.upcast::<Element>(); if first_enabled.is_none() &&!element.disabled_state() { first_enabled = Some(Root::from_ref(opt.r())); } } if let Some(last_selected) = last_selected { last_selected.set_selectedness(true); } else { if self.display_size() == 1 { if let Some(first_enabled) = first_enabled { first_enabled.set_selectedness(true); } } } } pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) { let node = self.upcast::<Node>(); if self.Name().is_empty() { return; } for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { let element = opt.upcast::<Element>(); if opt.Selected() && element.enabled_state() { data_set.push(FormDatum { ty: self.Type(), name: self.Name(), value: FormDatumValue::String(opt.Value()) }); } } } // https://html.spec.whatwg.org/multipage/#concept-select-pick pub fn pick_option(&self, picked: &HTMLOptionElement) { if!self.Multiple() { let node = self.upcast::<Node>(); let picked = picked.upcast(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.upcast::<HTMLElement>()!= picked { opt.set_selectedness(false); } } } } // https://html.spec.whatwg.org/multipage/#concept-select-size fn display_size(&self) -> u32 { if self.Size() == 0 { if self.Multiple() { 4 } else { 1 } } else { self.Size() } } } impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState>
// Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_getter!(Multiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_setter!(SetMultiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(&self) -> DOMString { DOMString::from(if self.Multiple() { "select-multiple" } else { "select-one" }) } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels fn Labels(&self) -> Root<NodeList> { self.upcast::<HTMLElement>().labels() } } impl VirtualMethods for HTMLSelectElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &atom!("disabled") { let el = self.upcast::<Element>(); match mutation { AttributeMutation::Set(_) => { el.set_disabled_state(true); el.set_enabled_state(false); }, AttributeMutation::Removed => { el.set_disabled_state(false); el.set_enabled_state(true); el.check_ancestors_disabled_state_for_form_control(); } } } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue { match *local_name { atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } } impl FormControl for HTMLSelectElement {} impl Validatable for HTMLSelectElement {}
{ let window = window_from_node(self); ValidityState::new(window.r(), self.upcast()) }
identifier_body
htmlselectelement.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::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement}; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, UnbindContext, window_from_node}; use dom::nodelist::NodeList; use dom::validation::Validatable; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; use style::element_state::*; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } static DEFAULT_SELECT_SIZE: u32 = 0; impl HTMLSelectElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } // https://html.spec.whatwg.org/multipage/#ask-for-a-reset pub fn ask_for_reset(&self) { if self.Multiple() { return; } let mut first_enabled: Option<Root<HTMLOptionElement>> = None; let mut last_selected: Option<Root<HTMLOptionElement>> = None; let node = self.upcast::<Node>(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.Selected() { opt.set_selectedness(false); last_selected = Some(Root::from_ref(opt.r())); } let element = opt.upcast::<Element>(); if first_enabled.is_none() &&!element.disabled_state() { first_enabled = Some(Root::from_ref(opt.r())); } } if let Some(last_selected) = last_selected { last_selected.set_selectedness(true); } else { if self.display_size() == 1 { if let Some(first_enabled) = first_enabled { first_enabled.set_selectedness(true); } } } } pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) { let node = self.upcast::<Node>(); if self.Name().is_empty() { return; } for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { let element = opt.upcast::<Element>(); if opt.Selected() && element.enabled_state() { data_set.push(FormDatum { ty: self.Type(), name: self.Name(), value: FormDatumValue::String(opt.Value()) }); } } } // https://html.spec.whatwg.org/multipage/#concept-select-pick pub fn pick_option(&self, picked: &HTMLOptionElement) { if!self.Multiple() { let node = self.upcast::<Node>(); let picked = picked.upcast(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.upcast::<HTMLElement>()!= picked { opt.set_selectedness(false); } } } } // https://html.spec.whatwg.org/multipage/#concept-select-size fn display_size(&self) -> u32 { if self.Size() == 0 { if self.Multiple() { 4 } else { 1 } } else { self.Size() } } } impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r(), self.upcast()) } // Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_getter!(Multiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_setter!(SetMultiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(&self) -> DOMString { DOMString::from(if self.Multiple() { "select-multiple" } else { "select-one" }) } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels fn Labels(&self) -> Root<NodeList> { self.upcast::<HTMLElement>().labels() } } impl VirtualMethods for HTMLSelectElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &atom!("disabled") { let el = self.upcast::<Element>(); match mutation { AttributeMutation::Set(_) => { el.set_disabled_state(true); el.set_enabled_state(false); }, AttributeMutation::Removed => { el.set_disabled_state(false); el.set_enabled_state(true); el.check_ancestors_disabled_state_for_form_control(); } } } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>())
else { el.check_disabled_attribute(); } } fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue { match *local_name { atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } } impl FormControl for HTMLSelectElement {} impl Validatable for HTMLSelectElement {}
{ el.check_ancestors_disabled_state_for_form_control(); }
conditional_block
htmlselectelement.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::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement}; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, UnbindContext, window_from_node}; use dom::nodelist::NodeList; use dom::validation::Validatable; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; use style::element_state::*; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } static DEFAULT_SELECT_SIZE: u32 = 0; impl HTMLSelectElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } // https://html.spec.whatwg.org/multipage/#ask-for-a-reset pub fn ask_for_reset(&self) { if self.Multiple() { return; } let mut first_enabled: Option<Root<HTMLOptionElement>> = None; let mut last_selected: Option<Root<HTMLOptionElement>> = None; let node = self.upcast::<Node>(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.Selected() { opt.set_selectedness(false); last_selected = Some(Root::from_ref(opt.r())); } let element = opt.upcast::<Element>(); if first_enabled.is_none() &&!element.disabled_state() { first_enabled = Some(Root::from_ref(opt.r())); } } if let Some(last_selected) = last_selected { last_selected.set_selectedness(true); } else { if self.display_size() == 1 { if let Some(first_enabled) = first_enabled { first_enabled.set_selectedness(true); } } } } pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) { let node = self.upcast::<Node>(); if self.Name().is_empty() { return; } for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { let element = opt.upcast::<Element>(); if opt.Selected() && element.enabled_state() { data_set.push(FormDatum { ty: self.Type(), name: self.Name(), value: FormDatumValue::String(opt.Value()) }); } } } // https://html.spec.whatwg.org/multipage/#concept-select-pick pub fn pick_option(&self, picked: &HTMLOptionElement) { if!self.Multiple() { let node = self.upcast::<Node>(); let picked = picked.upcast(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.upcast::<HTMLElement>()!= picked { opt.set_selectedness(false); } } } } // https://html.spec.whatwg.org/multipage/#concept-select-size fn display_size(&self) -> u32 { if self.Size() == 0 { if self.Multiple() { 4 } else { 1 } } else { self.Size() } } } impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r(), self.upcast()) }
fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_getter!(Multiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_setter!(SetMultiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(&self) -> DOMString { DOMString::from(if self.Multiple() { "select-multiple" } else { "select-one" }) } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels fn Labels(&self) -> Root<NodeList> { self.upcast::<HTMLElement>().labels() } } impl VirtualMethods for HTMLSelectElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &atom!("disabled") { let el = self.upcast::<Element>(); match mutation { AttributeMutation::Set(_) => { el.set_disabled_state(true); el.set_enabled_state(false); }, AttributeMutation::Removed => { el.set_disabled_state(false); el.set_enabled_state(true); el.check_ancestors_disabled_state_for_form_control(); } } } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue { match *local_name { atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } } impl FormControl for HTMLSelectElement {} impl Validatable for HTMLSelectElement {}
// Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add
random_line_split
htmlselectelement.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::Attr; use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods; use dom::bindings::codegen::UnionTypes::HTMLElementOrLong; use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element}; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement}; use dom::htmloptionelement::HTMLOptionElement; use dom::node::{Node, UnbindContext, window_from_node}; use dom::nodelist::NodeList; use dom::validation::Validatable; use dom::validitystate::ValidityState; use dom::virtualmethods::VirtualMethods; use string_cache::Atom; use style::attr::AttrValue; use style::element_state::*; #[dom_struct] pub struct HTMLSelectElement { htmlelement: HTMLElement } static DEFAULT_SELECT_SIZE: u32 = 0; impl HTMLSelectElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLSelectElement { HTMLSelectElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLSelectElement> { let element = HTMLSelectElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap) } // https://html.spec.whatwg.org/multipage/#ask-for-a-reset pub fn ask_for_reset(&self) { if self.Multiple() { return; } let mut first_enabled: Option<Root<HTMLOptionElement>> = None; let mut last_selected: Option<Root<HTMLOptionElement>> = None; let node = self.upcast::<Node>(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.Selected() { opt.set_selectedness(false); last_selected = Some(Root::from_ref(opt.r())); } let element = opt.upcast::<Element>(); if first_enabled.is_none() &&!element.disabled_state() { first_enabled = Some(Root::from_ref(opt.r())); } } if let Some(last_selected) = last_selected { last_selected.set_selectedness(true); } else { if self.display_size() == 1 { if let Some(first_enabled) = first_enabled { first_enabled.set_selectedness(true); } } } } pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) { let node = self.upcast::<Node>(); if self.Name().is_empty() { return; } for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { let element = opt.upcast::<Element>(); if opt.Selected() && element.enabled_state() { data_set.push(FormDatum { ty: self.Type(), name: self.Name(), value: FormDatumValue::String(opt.Value()) }); } } } // https://html.spec.whatwg.org/multipage/#concept-select-pick pub fn pick_option(&self, picked: &HTMLOptionElement) { if!self.Multiple() { let node = self.upcast::<Node>(); let picked = picked.upcast(); for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { if opt.upcast::<HTMLElement>()!= picked { opt.set_selectedness(false); } } } } // https://html.spec.whatwg.org/multipage/#concept-select-size fn display_size(&self) -> u32 { if self.Size() == 0 { if self.Multiple() { 4 } else { 1 } } else { self.Size() } } } impl HTMLSelectElementMethods for HTMLSelectElement { // https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r(), self.upcast()) } // Note: this function currently only exists for union.html. // https://html.spec.whatwg.org/multipage/#dom-select-add fn
(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) { } // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_getter!(Multiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-select-multiple make_bool_setter!(SetMultiple, "multiple"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#dom-fe-name make_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-size make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-select-type fn Type(&self) -> DOMString { DOMString::from(if self.Multiple() { "select-multiple" } else { "select-one" }) } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels fn Labels(&self) -> Root<NodeList> { self.upcast::<HTMLElement>().labels() } } impl VirtualMethods for HTMLSelectElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); if attr.local_name() == &atom!("disabled") { let el = self.upcast::<Element>(); match mutation { AttributeMutation::Set(_) => { el.set_disabled_state(true); el.set_enabled_state(false); }, AttributeMutation::Removed => { el.set_disabled_state(false); el.set_enabled_state(true); el.check_ancestors_disabled_state_for_form_control(); } } } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue { match *local_name { atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE), _ => self.super_type().unwrap().parse_plain_attribute(local_name, value), } } } impl FormControl for HTMLSelectElement {} impl Validatable for HTMLSelectElement {}
Add
identifier_name
close_on_drop.rs
#![cfg(all(feature = "os-poll", feature = "net"))] use std::io::Read; use log::debug; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interest, Poll, Token}; mod util; use util::{any_local_address, init}; use self::TestState::{AfterRead, Initial}; const SERVER: Token = Token(0); const CLIENT: Token = Token(1); #[derive(Debug, PartialEq)] enum TestState { Initial, AfterRead, } struct TestHandler { srv: TcpListener, cli: TcpStream, state: TestState, shutdown: bool, } impl TestHandler { fn new(srv: TcpListener, cli: TcpStream) -> TestHandler { TestHandler { srv, cli, state: Initial, shutdown: false, } } fn handle_read(&mut self, poll: &mut Poll, tok: Token) { debug!("readable; tok={:?}", tok); match tok { SERVER => { debug!("server connection ready for accept"); let _ = self.srv.accept().unwrap(); } CLIENT => { debug!("client readable"); match self.state { Initial => { let mut buf = [0; 4096]; debug!("GOT={:?}", self.cli.read(&mut buf[..])); self.state = AfterRead; } AfterRead => {} } let mut buf = Vec::with_capacity(1024); match self.cli.read(&mut buf) { Ok(0) => self.shutdown = true, Ok(_) => panic!("the client socket should not be readable"), Err(e) => panic!("Unexpected error {:?}", e), } } _ => panic!("received unknown token {:?}", tok), } poll.registry() .reregister(&mut self.cli, CLIENT, Interest::READABLE) .unwrap(); } fn handle_write(&mut self, poll: &mut Poll, tok: Token) { match tok { SERVER => panic!("received writable for token 0"), CLIENT => { debug!("client connected"); poll.registry() .reregister(&mut self.cli, CLIENT, Interest::READABLE) .unwrap(); } _ => panic!("received unknown token {:?}", tok), } } } #[test] pub fn
() { init(); debug!("Starting TEST_CLOSE_ON_DROP"); let mut poll = Poll::new().unwrap(); // == Create & setup server socket let mut srv = TcpListener::bind(any_local_address()).unwrap(); let addr = srv.local_addr().unwrap(); poll.registry() .register(&mut srv, SERVER, Interest::READABLE) .unwrap(); // == Create & setup client socket let mut sock = TcpStream::connect(addr).unwrap(); poll.registry() .register(&mut sock, CLIENT, Interest::WRITABLE) .unwrap(); // == Create storage for events let mut events = Events::with_capacity(1024); // == Setup test handler let mut handler = TestHandler::new(srv, sock); // == Run test while!handler.shutdown { poll.poll(&mut events, None).unwrap(); for event in &events { if event.is_readable() { handler.handle_read(&mut poll, event.token()); } if event.is_writable() { handler.handle_write(&mut poll, event.token()); } } } assert!(handler.state == AfterRead, "actual={:?}", handler.state); }
close_on_drop
identifier_name
close_on_drop.rs
#![cfg(all(feature = "os-poll", feature = "net"))] use std::io::Read; use log::debug; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interest, Poll, Token}; mod util; use util::{any_local_address, init}; use self::TestState::{AfterRead, Initial}; const SERVER: Token = Token(0); const CLIENT: Token = Token(1); #[derive(Debug, PartialEq)] enum TestState { Initial, AfterRead, } struct TestHandler { srv: TcpListener, cli: TcpStream, state: TestState, shutdown: bool, } impl TestHandler { fn new(srv: TcpListener, cli: TcpStream) -> TestHandler { TestHandler { srv, cli, state: Initial, shutdown: false, } } fn handle_read(&mut self, poll: &mut Poll, tok: Token) { debug!("readable; tok={:?}", tok); match tok { SERVER => { debug!("server connection ready for accept"); let _ = self.srv.accept().unwrap(); } CLIENT => { debug!("client readable"); match self.state { Initial => { let mut buf = [0; 4096]; debug!("GOT={:?}", self.cli.read(&mut buf[..])); self.state = AfterRead; } AfterRead => {} } let mut buf = Vec::with_capacity(1024); match self.cli.read(&mut buf) { Ok(0) => self.shutdown = true, Ok(_) => panic!("the client socket should not be readable"), Err(e) => panic!("Unexpected error {:?}", e), } } _ => panic!("received unknown token {:?}", tok), } poll.registry() .reregister(&mut self.cli, CLIENT, Interest::READABLE) .unwrap(); } fn handle_write(&mut self, poll: &mut Poll, tok: Token) { match tok { SERVER => panic!("received writable for token 0"), CLIENT => { debug!("client connected"); poll.registry() .reregister(&mut self.cli, CLIENT, Interest::READABLE) .unwrap(); } _ => panic!("received unknown token {:?}", tok), } } } #[test] pub fn close_on_drop() { init(); debug!("Starting TEST_CLOSE_ON_DROP"); let mut poll = Poll::new().unwrap(); // == Create & setup server socket let mut srv = TcpListener::bind(any_local_address()).unwrap(); let addr = srv.local_addr().unwrap(); poll.registry() .register(&mut srv, SERVER, Interest::READABLE) .unwrap(); // == Create & setup client socket let mut sock = TcpStream::connect(addr).unwrap(); poll.registry() .register(&mut sock, CLIENT, Interest::WRITABLE) .unwrap(); // == Create storage for events let mut events = Events::with_capacity(1024); // == Setup test handler let mut handler = TestHandler::new(srv, sock); // == Run test while!handler.shutdown { poll.poll(&mut events, None).unwrap(); for event in &events { if event.is_readable() { handler.handle_read(&mut poll, event.token()); } if event.is_writable()
} } assert!(handler.state == AfterRead, "actual={:?}", handler.state); }
{ handler.handle_write(&mut poll, event.token()); }
conditional_block
close_on_drop.rs
#![cfg(all(feature = "os-poll", feature = "net"))] use std::io::Read; use log::debug; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interest, Poll, Token}; mod util; use util::{any_local_address, init}; use self::TestState::{AfterRead, Initial}; const SERVER: Token = Token(0); const CLIENT: Token = Token(1); #[derive(Debug, PartialEq)] enum TestState { Initial, AfterRead, } struct TestHandler { srv: TcpListener, cli: TcpStream, state: TestState, shutdown: bool, } impl TestHandler { fn new(srv: TcpListener, cli: TcpStream) -> TestHandler { TestHandler { srv, cli, state: Initial, shutdown: false, } } fn handle_read(&mut self, poll: &mut Poll, tok: Token) { debug!("readable; tok={:?}", tok); match tok { SERVER => { debug!("server connection ready for accept"); let _ = self.srv.accept().unwrap(); } CLIENT => { debug!("client readable"); match self.state { Initial => { let mut buf = [0; 4096]; debug!("GOT={:?}", self.cli.read(&mut buf[..])); self.state = AfterRead; } AfterRead => {} } let mut buf = Vec::with_capacity(1024); match self.cli.read(&mut buf) { Ok(0) => self.shutdown = true, Ok(_) => panic!("the client socket should not be readable"), Err(e) => panic!("Unexpected error {:?}", e), } } _ => panic!("received unknown token {:?}", tok), } poll.registry() .reregister(&mut self.cli, CLIENT, Interest::READABLE) .unwrap(); } fn handle_write(&mut self, poll: &mut Poll, tok: Token)
} #[test] pub fn close_on_drop() { init(); debug!("Starting TEST_CLOSE_ON_DROP"); let mut poll = Poll::new().unwrap(); // == Create & setup server socket let mut srv = TcpListener::bind(any_local_address()).unwrap(); let addr = srv.local_addr().unwrap(); poll.registry() .register(&mut srv, SERVER, Interest::READABLE) .unwrap(); // == Create & setup client socket let mut sock = TcpStream::connect(addr).unwrap(); poll.registry() .register(&mut sock, CLIENT, Interest::WRITABLE) .unwrap(); // == Create storage for events let mut events = Events::with_capacity(1024); // == Setup test handler let mut handler = TestHandler::new(srv, sock); // == Run test while!handler.shutdown { poll.poll(&mut events, None).unwrap(); for event in &events { if event.is_readable() { handler.handle_read(&mut poll, event.token()); } if event.is_writable() { handler.handle_write(&mut poll, event.token()); } } } assert!(handler.state == AfterRead, "actual={:?}", handler.state); }
{ match tok { SERVER => panic!("received writable for token 0"), CLIENT => { debug!("client connected"); poll.registry() .reregister(&mut self.cli, CLIENT, Interest::READABLE) .unwrap(); } _ => panic!("received unknown token {:?}", tok), } }
identifier_body
close_on_drop.rs
#![cfg(all(feature = "os-poll", feature = "net"))] use std::io::Read; use log::debug; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interest, Poll, Token}; mod util; use util::{any_local_address, init}; use self::TestState::{AfterRead, Initial}; const SERVER: Token = Token(0); const CLIENT: Token = Token(1); #[derive(Debug, PartialEq)] enum TestState { Initial, AfterRead, } struct TestHandler { srv: TcpListener, cli: TcpStream, state: TestState, shutdown: bool, } impl TestHandler { fn new(srv: TcpListener, cli: TcpStream) -> TestHandler { TestHandler { srv, cli, state: Initial, shutdown: false, } } fn handle_read(&mut self, poll: &mut Poll, tok: Token) { debug!("readable; tok={:?}", tok); match tok { SERVER => { debug!("server connection ready for accept"); let _ = self.srv.accept().unwrap(); } CLIENT => { debug!("client readable"); match self.state { Initial => { let mut buf = [0; 4096]; debug!("GOT={:?}", self.cli.read(&mut buf[..])); self.state = AfterRead; } AfterRead => {} } let mut buf = Vec::with_capacity(1024); match self.cli.read(&mut buf) { Ok(0) => self.shutdown = true, Ok(_) => panic!("the client socket should not be readable"), Err(e) => panic!("Unexpected error {:?}", e), } } _ => panic!("received unknown token {:?}", tok), } poll.registry() .reregister(&mut self.cli, CLIENT, Interest::READABLE) .unwrap(); } fn handle_write(&mut self, poll: &mut Poll, tok: Token) { match tok { SERVER => panic!("received writable for token 0"), CLIENT => { debug!("client connected"); poll.registry() .reregister(&mut self.cli, CLIENT, Interest::READABLE) .unwrap(); } _ => panic!("received unknown token {:?}", tok), } } } #[test] pub fn close_on_drop() { init(); debug!("Starting TEST_CLOSE_ON_DROP"); let mut poll = Poll::new().unwrap(); // == Create & setup server socket let mut srv = TcpListener::bind(any_local_address()).unwrap(); let addr = srv.local_addr().unwrap();
// == Create & setup client socket let mut sock = TcpStream::connect(addr).unwrap(); poll.registry() .register(&mut sock, CLIENT, Interest::WRITABLE) .unwrap(); // == Create storage for events let mut events = Events::with_capacity(1024); // == Setup test handler let mut handler = TestHandler::new(srv, sock); // == Run test while!handler.shutdown { poll.poll(&mut events, None).unwrap(); for event in &events { if event.is_readable() { handler.handle_read(&mut poll, event.token()); } if event.is_writable() { handler.handle_write(&mut poll, event.token()); } } } assert!(handler.state == AfterRead, "actual={:?}", handler.state); }
poll.registry() .register(&mut srv, SERVER, Interest::READABLE) .unwrap();
random_line_split
lib.rs
// Copyright (C) 2020 Natanael Mojica <[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 gst::gst_plugin_define; mod filter; fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { filter::register(plugin)?; Ok(()) } gst_plugin_define!( csound, env!("CARGO_PKG_DESCRIPTION"), plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), "MIT/X11", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), env!("CARGO_PKG_REPOSITORY"),
env!("BUILD_REL_DATE") );
random_line_split
lib.rs
// Copyright (C) 2020 Natanael Mojica <[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 gst::gst_plugin_define; mod filter; fn
(plugin: &gst::Plugin) -> Result<(), glib::BoolError> { filter::register(plugin)?; Ok(()) } gst_plugin_define!( csound, env!("CARGO_PKG_DESCRIPTION"), plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), "MIT/X11", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), env!("CARGO_PKG_REPOSITORY"), env!("BUILD_REL_DATE") );
plugin_init
identifier_name
lib.rs
// Copyright (C) 2020 Natanael Mojica <[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 gst::gst_plugin_define; mod filter; fn plugin_init(plugin: &gst::Plugin) -> Result<(), glib::BoolError>
gst_plugin_define!( csound, env!("CARGO_PKG_DESCRIPTION"), plugin_init, concat!(env!("CARGO_PKG_VERSION"), "-", env!("COMMIT_ID")), "MIT/X11", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_NAME"), env!("CARGO_PKG_REPOSITORY"), env!("BUILD_REL_DATE") );
{ filter::register(plugin)?; Ok(()) }
identifier_body
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! partial_eq_impl { // ($($t:ty)*) => ($( // #[stable(feature = "rust1", since = "1.0.0")] // impl PartialEq for $t { // #[inline] // fn eq(&self, other: &$t) -> bool { (*self) == (*other) } // #[inline] // fn ne(&self, other: &$t) -> bool { (*self)!= (*other) } // } // )*) // } // partial_eq_impl! { // bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 // } macro_rules! ne_test { ($($t:ty)*) => ($({ let v1: $t = 68 as $t; { let result: bool = v1.ne(&v1); assert_eq!(result, false); } let v2: $t = 100 as $t; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } })*) } #[test] fn
() { let v1: bool = false; { let result: bool = v1.ne(&v1); assert_eq!(result, false); } let v2: bool = true; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } } #[test] fn ne_test2() { ne_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }; } }
ne_test1
identifier_name
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! partial_eq_impl { // ($($t:ty)*) => ($( // #[stable(feature = "rust1", since = "1.0.0")] // impl PartialEq for $t { // #[inline] // fn eq(&self, other: &$t) -> bool { (*self) == (*other) } // #[inline] // fn ne(&self, other: &$t) -> bool { (*self)!= (*other) } // } // )*) // } // partial_eq_impl! { // bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 // } macro_rules! ne_test { ($($t:ty)*) => ($({ let v1: $t = 68 as $t;
let v2: $t = 100 as $t; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } })*) } #[test] fn ne_test1() { let v1: bool = false; { let result: bool = v1.ne(&v1); assert_eq!(result, false); } let v2: bool = true; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } } #[test] fn ne_test2() { ne_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }; } }
{ let result: bool = v1.ne(&v1); assert_eq!(result, false); }
random_line_split
ne.rs
#![feature(core)] extern crate core; #[cfg(test)] mod tests { // macro_rules! partial_eq_impl { // ($($t:ty)*) => ($( // #[stable(feature = "rust1", since = "1.0.0")] // impl PartialEq for $t { // #[inline] // fn eq(&self, other: &$t) -> bool { (*self) == (*other) } // #[inline] // fn ne(&self, other: &$t) -> bool { (*self)!= (*other) } // } // )*) // } // partial_eq_impl! { // bool char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 // } macro_rules! ne_test { ($($t:ty)*) => ($({ let v1: $t = 68 as $t; { let result: bool = v1.ne(&v1); assert_eq!(result, false); } let v2: $t = 100 as $t; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } })*) } #[test] fn ne_test1() { let v1: bool = false; { let result: bool = v1.ne(&v1); assert_eq!(result, false); } let v2: bool = true; { let result: bool = v1.ne(&v2); assert_eq!(result, true); } } #[test] fn ne_test2()
}
{ ne_test! { char usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }; }
identifier_body
mod.rs
extern crate rmp; use std; quick_error! { #[derive(Debug)] pub enum DBError { Protocol(err: String) { description("Protocol error") display("Protocol error: {}", err) } FileFormat(err: String) { description("File fromat error") display("File format error: {}", err) } ParseString(err: String) { description("Parse string error") display("Parse string error") from(rmp::decode::DecodeStringError) } ParseValue(err: rmp::decode::ValueReadError){ description("Parse value error") display("Parse value error: {}", err) from() cause(err) } SendValue(err: rmp::encode::ValueWriteError){ description("Send value error") display("Send value error: {}", err) from() cause(err) } UTF8(err: std::string::FromUtf8Error){ description("UTF decoding error") display("UTF encoding error: {}", err) from() cause(err) } IO(err: std::io::Error){
description("IO error") display("IO error: {}", err) from() cause(err) } } }
random_line_split
if-check-panic.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. // error-pattern:Number is odd fn even(x: usize) -> bool { if x < 2 { return false; } else if x == 2
else { return even(x - 2); } } fn foo(x: usize) { if even(x) { println!("{}", x); } else { panic!("Number is odd"); } } fn main() { foo(3); }
{ return true; }
conditional_block
if-check-panic.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. // error-pattern:Number is odd fn even(x: usize) -> bool { if x < 2 { return false; } else if x == 2 { return true; } else { return even(x - 2); } }
println!("{}", x); } else { panic!("Number is odd"); } } fn main() { foo(3); }
fn foo(x: usize) { if even(x) {
random_line_split
if-check-panic.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. // error-pattern:Number is odd fn even(x: usize) -> bool { if x < 2 { return false; } else if x == 2 { return true; } else { return even(x - 2); } } fn
(x: usize) { if even(x) { println!("{}", x); } else { panic!("Number is odd"); } } fn main() { foo(3); }
foo
identifier_name
if-check-panic.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. // error-pattern:Number is odd fn even(x: usize) -> bool
fn foo(x: usize) { if even(x) { println!("{}", x); } else { panic!("Number is odd"); } } fn main() { foo(3); }
{ if x < 2 { return false; } else if x == 2 { return true; } else { return even(x - 2); } }
identifier_body
password_based_encryption.rs
extern crate rustc_serialize; extern crate rncryptor; use rustc_serialize::hex::FromHex; use rncryptor::v3::types::{IV, Salt}; use rncryptor::v3::encryptor::Encryptor; struct TestVector { password: &'static str, encryption_salt: &'static str, hmac_salt: &'static str, iv: &'static str, plain_text: &'static str, cipher_text: &'static str, } fn test_vector(vector: TestVector) { let encryption_salt = Salt(vector.encryption_salt.from_hex().unwrap()); let hmac_salt = Salt(vector.hmac_salt.from_hex().unwrap()); let iv = IV::from(vector.iv.from_hex().unwrap()); let plain_text = vector.plain_text.from_hex().unwrap(); let ciphertext = vector.cipher_text.from_hex().unwrap(); let result = Encryptor::from_password(vector.password, encryption_salt, hmac_salt, iv) .and_then(|e| e.encrypt(&plain_text)); match result { Err(e) => panic!(e), Ok(encrypted) => assert_eq!(*encrypted.as_slice(), *ciphertext.as_slice()), } } #[test] fn all_fields_empty_or_zero() { test_vector(TestVector { password: "a", encryption_salt: "0000000000000000", hmac_salt: "0000000000000000", iv: "00000000000000000000000000000000", plain_text: "", cipher_text: "03010000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 \ 0000b303 9be31cd7 ece5e754 f5c8da17 00366631 3ae8a89d dcf8e3cb 41fdc130 \ b2329dbe 07d6f4d3 2c34e050 c8bd7e93 3b12", }) } #[test] fn one_byte() { test_vector(TestVector { password: "thepassword", encryption_salt: "0001020304050607", hmac_salt: "0102030405060708", iv: "02030405060708090a0b0c0d0e0f0001", plain_text: "01", cipher_text: "03010001 02030405 06070102 03040506 07080203 04050607 08090a0b 0c0d0e0f \ 0001a1f8 730e0bf4 80eb7b70 f690abf2 1e029514 164ad3c4 74a51b30 c7eaa1ca \ 545b7de3 de5b010a cbad0a9a 13857df6 96a8", }) } #[test] fn exactly_one_block() { test_vector(TestVector { password: "thepassword", encryption_salt: "0102030405060700", hmac_salt: "0203040506070801", iv: "030405060708090a0b0c0d0e0f000102", plain_text: "0123456789abcdef", cipher_text: "03010102 03040506 07000203 04050607 08010304 05060708 090a0b0c 0d0e0f00 \ 01020e43 7fe80930 9c03fd53 a475131e 9a1978b8 eaef576f 60adb8ce 2320849b \ a32d7429 00438ba8 97d22210 c76c35c8 49df", }) }
encryption_salt: "0203040506070001", hmac_salt: "0304050607080102", iv: "0405060708090a0b0c0d0e0f00010203", plain_text: "0123456789abcdef 01234567", cipher_text: "03010203 04050607 00010304 05060708 01020405 06070809 0a0b0c0d 0e0f0001 \ 0203e01b bda5df2c a8adace3 8f6c588d 291e03f9 51b78d34 17bc2816 581dc6b7 \ 67f1a2e5 7597512b 18e1638f 21235fa5 928c", }) } #[test] fn multibyte_password() { test_vector(TestVector { password: "中文密码", encryption_salt: "0304050607000102", hmac_salt: "0405060708010203", iv: "05060708090a0b0c0d0e0f0001020304", plain_text: "23456789abcdef 0123456701", cipher_text: "03010304 05060700 01020405 06070801 02030506 0708090a 0b0c0d0e 0f000102 \ 03048a9e 08bdec1c 4bfe13e8 1fb85f00 9ab3ddb9 1387e809 c4ad86d9 e8a60145 \ 57716657 bd317d4b b6a76446 15b3de40 2341", }) } #[test] fn longer_text_and_password() { test_vector(TestVector { password: "It was the best of times, it was the worst of times; it was the age of wisdom, \ it was the age of foolishness;", encryption_salt: "0405060700010203", hmac_salt: "0506070801020304", iv: "060708090a0b0c0d0e0f000102030405", plain_text: "69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 62 65 6c 69 65 \ 66 2c 20 69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 69 6e \ 63 72 65 64 75 6c 69 74 79 3b 20 69 74 20 77 61 73 20 74 68 65 20 73 65 61 \ 73 6f 6e 20 6f 66 20 4c 69 67 68 74 2c 20 69 74 20 77 61 73 20 74 68 65 20 \ 73 65 61 73 6f 6e 20 6f 66 20 44 61 72 6b 6e 65 73 73 3b 20 69 74 20 77 61 \ 73 20 74 68 65 20 73 70 72 69 6e 67 20 6f 66 20 68 6f 70 65 2c 20 69 74 20 \ 77 61 73 20 74 68 65 20 77 69 6e 74 65 72 20 6f 66 20 64 65 73 70 61 69 72 \ 3b 20 77 65 20 68 61 64 20 65 76 65 72 79 74 68 69 6e 67 20 62 65 66 6f 72 \ 65 20 75 73 2c 20 77 65 20 68 61 64 20 6e 6f 74 68 69 6e 67 20 62 65 66 6f \ 72 65 20 75 73 3b 20 77 65 20 77 65 72 65 20 61 6c 6c 20 67 6f 69 6e 67 20 \ 64 69 72 65 63 74 6c 79 20 74 6f 20 48 65 61 76 65 6e 2c 20 77 65 20 77 65 \ 72 65 20 61 6c 6c 20 67 6f 69 6e 67 20 74 68 65 20 6f 74 68 65 72 20 77 61 \ 79 2e 0a 0a", cipher_text: "03010405 06070001 02030506 07080102 03040607 08090a0b 0c0d0e0f 00010203 \ 0405d564 c7a99da9 21a6e7c4 078a8264 1d954795 51283167 a2c81f31 ab80c9d7 \ d8beb770 111decd3 e3d29bbd f7ebbfc5 f10ac87e 7e55bfb5 a7f487bc d3983570 \ 5e83b9c0 49c6d695 2be011f8 ddb1a14f c0c92573 8de017e6 2b1d621c cdb75f29 \ 37d0a1a7 0e44d843 b9c61037 dee2998b 2bbd740b 910232ee a7196116 8838f699 \ 5b996417 3b34c0bc d311a2c8 7e271630 928bae30 1a8f4703 ac2ae469 9f3c285a \ bf1c55ac 324b073a 958ae52e e8c3bd68 f919c09e b1cd2814 2a1996a9 e6cbff5f \ 4f4e1dba 07d29ff6 6860db98 95a48233 140ca249 419d6304 6448db1b 0f4252a6 \ e4edb947 fd0071d1 e52bc156 00622fa5 48a67739 63618150 797a8a80 e592446d \ f5926d0b fd32b544 b796f335 9567394f 77e7b171 b2f9bc5f 2caf7a0f ac0da7d0 \ 4d6a8674 4d6e06d0 2fbe15d0 f580a1d5 bd16ad91 34800361 1358dcb4 ac999095 \ 5f6cbbbf b185941d 4b4b71ce 7f9ba6ef c1270b78 08838b6c 7b7ef17e 8db919b3 4fac", }) }
#[test] fn more_than_one_block() { test_vector(TestVector { password: "thepassword",
random_line_split
password_based_encryption.rs
extern crate rustc_serialize; extern crate rncryptor; use rustc_serialize::hex::FromHex; use rncryptor::v3::types::{IV, Salt}; use rncryptor::v3::encryptor::Encryptor; struct
{ password: &'static str, encryption_salt: &'static str, hmac_salt: &'static str, iv: &'static str, plain_text: &'static str, cipher_text: &'static str, } fn test_vector(vector: TestVector) { let encryption_salt = Salt(vector.encryption_salt.from_hex().unwrap()); let hmac_salt = Salt(vector.hmac_salt.from_hex().unwrap()); let iv = IV::from(vector.iv.from_hex().unwrap()); let plain_text = vector.plain_text.from_hex().unwrap(); let ciphertext = vector.cipher_text.from_hex().unwrap(); let result = Encryptor::from_password(vector.password, encryption_salt, hmac_salt, iv) .and_then(|e| e.encrypt(&plain_text)); match result { Err(e) => panic!(e), Ok(encrypted) => assert_eq!(*encrypted.as_slice(), *ciphertext.as_slice()), } } #[test] fn all_fields_empty_or_zero() { test_vector(TestVector { password: "a", encryption_salt: "0000000000000000", hmac_salt: "0000000000000000", iv: "00000000000000000000000000000000", plain_text: "", cipher_text: "03010000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 \ 0000b303 9be31cd7 ece5e754 f5c8da17 00366631 3ae8a89d dcf8e3cb 41fdc130 \ b2329dbe 07d6f4d3 2c34e050 c8bd7e93 3b12", }) } #[test] fn one_byte() { test_vector(TestVector { password: "thepassword", encryption_salt: "0001020304050607", hmac_salt: "0102030405060708", iv: "02030405060708090a0b0c0d0e0f0001", plain_text: "01", cipher_text: "03010001 02030405 06070102 03040506 07080203 04050607 08090a0b 0c0d0e0f \ 0001a1f8 730e0bf4 80eb7b70 f690abf2 1e029514 164ad3c4 74a51b30 c7eaa1ca \ 545b7de3 de5b010a cbad0a9a 13857df6 96a8", }) } #[test] fn exactly_one_block() { test_vector(TestVector { password: "thepassword", encryption_salt: "0102030405060700", hmac_salt: "0203040506070801", iv: "030405060708090a0b0c0d0e0f000102", plain_text: "0123456789abcdef", cipher_text: "03010102 03040506 07000203 04050607 08010304 05060708 090a0b0c 0d0e0f00 \ 01020e43 7fe80930 9c03fd53 a475131e 9a1978b8 eaef576f 60adb8ce 2320849b \ a32d7429 00438ba8 97d22210 c76c35c8 49df", }) } #[test] fn more_than_one_block() { test_vector(TestVector { password: "thepassword", encryption_salt: "0203040506070001", hmac_salt: "0304050607080102", iv: "0405060708090a0b0c0d0e0f00010203", plain_text: "0123456789abcdef 01234567", cipher_text: "03010203 04050607 00010304 05060708 01020405 06070809 0a0b0c0d 0e0f0001 \ 0203e01b bda5df2c a8adace3 8f6c588d 291e03f9 51b78d34 17bc2816 581dc6b7 \ 67f1a2e5 7597512b 18e1638f 21235fa5 928c", }) } #[test] fn multibyte_password() { test_vector(TestVector { password: "中文密码", encryption_salt: "0304050607000102", hmac_salt: "0405060708010203", iv: "05060708090a0b0c0d0e0f0001020304", plain_text: "23456789abcdef 0123456701", cipher_text: "03010304 05060700 01020405 06070801 02030506 0708090a 0b0c0d0e 0f000102 \ 03048a9e 08bdec1c 4bfe13e8 1fb85f00 9ab3ddb9 1387e809 c4ad86d9 e8a60145 \ 57716657 bd317d4b b6a76446 15b3de40 2341", }) } #[test] fn longer_text_and_password() { test_vector(TestVector { password: "It was the best of times, it was the worst of times; it was the age of wisdom, \ it was the age of foolishness;", encryption_salt: "0405060700010203", hmac_salt: "0506070801020304", iv: "060708090a0b0c0d0e0f000102030405", plain_text: "69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 62 65 6c 69 65 \ 66 2c 20 69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 69 6e \ 63 72 65 64 75 6c 69 74 79 3b 20 69 74 20 77 61 73 20 74 68 65 20 73 65 61 \ 73 6f 6e 20 6f 66 20 4c 69 67 68 74 2c 20 69 74 20 77 61 73 20 74 68 65 20 \ 73 65 61 73 6f 6e 20 6f 66 20 44 61 72 6b 6e 65 73 73 3b 20 69 74 20 77 61 \ 73 20 74 68 65 20 73 70 72 69 6e 67 20 6f 66 20 68 6f 70 65 2c 20 69 74 20 \ 77 61 73 20 74 68 65 20 77 69 6e 74 65 72 20 6f 66 20 64 65 73 70 61 69 72 \ 3b 20 77 65 20 68 61 64 20 65 76 65 72 79 74 68 69 6e 67 20 62 65 66 6f 72 \ 65 20 75 73 2c 20 77 65 20 68 61 64 20 6e 6f 74 68 69 6e 67 20 62 65 66 6f \ 72 65 20 75 73 3b 20 77 65 20 77 65 72 65 20 61 6c 6c 20 67 6f 69 6e 67 20 \ 64 69 72 65 63 74 6c 79 20 74 6f 20 48 65 61 76 65 6e 2c 20 77 65 20 77 65 \ 72 65 20 61 6c 6c 20 67 6f 69 6e 67 20 74 68 65 20 6f 74 68 65 72 20 77 61 \ 79 2e 0a 0a", cipher_text: "03010405 06070001 02030506 07080102 03040607 08090a0b 0c0d0e0f 00010203 \ 0405d564 c7a99da9 21a6e7c4 078a8264 1d954795 51283167 a2c81f31 ab80c9d7 \ d8beb770 111decd3 e3d29bbd f7ebbfc5 f10ac87e 7e55bfb5 a7f487bc d3983570 \ 5e83b9c0 49c6d695 2be011f8 ddb1a14f c0c92573 8de017e6 2b1d621c cdb75f29 \ 37d0a1a7 0e44d843 b9c61037 dee2998b 2bbd740b 910232ee a7196116 8838f699 \ 5b996417 3b34c0bc d311a2c8 7e271630 928bae30 1a8f4703 ac2ae469 9f3c285a \ bf1c55ac 324b073a 958ae52e e8c3bd68 f919c09e b1cd2814 2a1996a9 e6cbff5f \ 4f4e1dba 07d29ff6 6860db98 95a48233 140ca249 419d6304 6448db1b 0f4252a6 \ e4edb947 fd0071d1 e52bc156 00622fa5 48a67739 63618150 797a8a80 e592446d \ f5926d0b fd32b544 b796f335 9567394f 77e7b171 b2f9bc5f 2caf7a0f ac0da7d0 \ 4d6a8674 4d6e06d0 2fbe15d0 f580a1d5 bd16ad91 34800361 1358dcb4 ac999095 \ 5f6cbbbf b185941d 4b4b71ce 7f9ba6ef c1270b78 08838b6c 7b7ef17e 8db919b3 4fac", }) }
TestVector
identifier_name
password_based_encryption.rs
extern crate rustc_serialize; extern crate rncryptor; use rustc_serialize::hex::FromHex; use rncryptor::v3::types::{IV, Salt}; use rncryptor::v3::encryptor::Encryptor; struct TestVector { password: &'static str, encryption_salt: &'static str, hmac_salt: &'static str, iv: &'static str, plain_text: &'static str, cipher_text: &'static str, } fn test_vector(vector: TestVector) { let encryption_salt = Salt(vector.encryption_salt.from_hex().unwrap()); let hmac_salt = Salt(vector.hmac_salt.from_hex().unwrap()); let iv = IV::from(vector.iv.from_hex().unwrap()); let plain_text = vector.plain_text.from_hex().unwrap(); let ciphertext = vector.cipher_text.from_hex().unwrap(); let result = Encryptor::from_password(vector.password, encryption_salt, hmac_salt, iv) .and_then(|e| e.encrypt(&plain_text)); match result { Err(e) => panic!(e), Ok(encrypted) => assert_eq!(*encrypted.as_slice(), *ciphertext.as_slice()), } } #[test] fn all_fields_empty_or_zero() { test_vector(TestVector { password: "a", encryption_salt: "0000000000000000", hmac_salt: "0000000000000000", iv: "00000000000000000000000000000000", plain_text: "", cipher_text: "03010000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 \ 0000b303 9be31cd7 ece5e754 f5c8da17 00366631 3ae8a89d dcf8e3cb 41fdc130 \ b2329dbe 07d6f4d3 2c34e050 c8bd7e93 3b12", }) } #[test] fn one_byte() { test_vector(TestVector { password: "thepassword", encryption_salt: "0001020304050607", hmac_salt: "0102030405060708", iv: "02030405060708090a0b0c0d0e0f0001", plain_text: "01", cipher_text: "03010001 02030405 06070102 03040506 07080203 04050607 08090a0b 0c0d0e0f \ 0001a1f8 730e0bf4 80eb7b70 f690abf2 1e029514 164ad3c4 74a51b30 c7eaa1ca \ 545b7de3 de5b010a cbad0a9a 13857df6 96a8", }) } #[test] fn exactly_one_block() { test_vector(TestVector { password: "thepassword", encryption_salt: "0102030405060700", hmac_salt: "0203040506070801", iv: "030405060708090a0b0c0d0e0f000102", plain_text: "0123456789abcdef", cipher_text: "03010102 03040506 07000203 04050607 08010304 05060708 090a0b0c 0d0e0f00 \ 01020e43 7fe80930 9c03fd53 a475131e 9a1978b8 eaef576f 60adb8ce 2320849b \ a32d7429 00438ba8 97d22210 c76c35c8 49df", }) } #[test] fn more_than_one_block()
#[test] fn multibyte_password() { test_vector(TestVector { password: "中文密码", encryption_salt: "0304050607000102", hmac_salt: "0405060708010203", iv: "05060708090a0b0c0d0e0f0001020304", plain_text: "23456789abcdef 0123456701", cipher_text: "03010304 05060700 01020405 06070801 02030506 0708090a 0b0c0d0e 0f000102 \ 03048a9e 08bdec1c 4bfe13e8 1fb85f00 9ab3ddb9 1387e809 c4ad86d9 e8a60145 \ 57716657 bd317d4b b6a76446 15b3de40 2341", }) } #[test] fn longer_text_and_password() { test_vector(TestVector { password: "It was the best of times, it was the worst of times; it was the age of wisdom, \ it was the age of foolishness;", encryption_salt: "0405060700010203", hmac_salt: "0506070801020304", iv: "060708090a0b0c0d0e0f000102030405", plain_text: "69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 62 65 6c 69 65 \ 66 2c 20 69 74 20 77 61 73 20 74 68 65 20 65 70 6f 63 68 20 6f 66 20 69 6e \ 63 72 65 64 75 6c 69 74 79 3b 20 69 74 20 77 61 73 20 74 68 65 20 73 65 61 \ 73 6f 6e 20 6f 66 20 4c 69 67 68 74 2c 20 69 74 20 77 61 73 20 74 68 65 20 \ 73 65 61 73 6f 6e 20 6f 66 20 44 61 72 6b 6e 65 73 73 3b 20 69 74 20 77 61 \ 73 20 74 68 65 20 73 70 72 69 6e 67 20 6f 66 20 68 6f 70 65 2c 20 69 74 20 \ 77 61 73 20 74 68 65 20 77 69 6e 74 65 72 20 6f 66 20 64 65 73 70 61 69 72 \ 3b 20 77 65 20 68 61 64 20 65 76 65 72 79 74 68 69 6e 67 20 62 65 66 6f 72 \ 65 20 75 73 2c 20 77 65 20 68 61 64 20 6e 6f 74 68 69 6e 67 20 62 65 66 6f \ 72 65 20 75 73 3b 20 77 65 20 77 65 72 65 20 61 6c 6c 20 67 6f 69 6e 67 20 \ 64 69 72 65 63 74 6c 79 20 74 6f 20 48 65 61 76 65 6e 2c 20 77 65 20 77 65 \ 72 65 20 61 6c 6c 20 67 6f 69 6e 67 20 74 68 65 20 6f 74 68 65 72 20 77 61 \ 79 2e 0a 0a", cipher_text: "03010405 06070001 02030506 07080102 03040607 08090a0b 0c0d0e0f 00010203 \ 0405d564 c7a99da9 21a6e7c4 078a8264 1d954795 51283167 a2c81f31 ab80c9d7 \ d8beb770 111decd3 e3d29bbd f7ebbfc5 f10ac87e 7e55bfb5 a7f487bc d3983570 \ 5e83b9c0 49c6d695 2be011f8 ddb1a14f c0c92573 8de017e6 2b1d621c cdb75f29 \ 37d0a1a7 0e44d843 b9c61037 dee2998b 2bbd740b 910232ee a7196116 8838f699 \ 5b996417 3b34c0bc d311a2c8 7e271630 928bae30 1a8f4703 ac2ae469 9f3c285a \ bf1c55ac 324b073a 958ae52e e8c3bd68 f919c09e b1cd2814 2a1996a9 e6cbff5f \ 4f4e1dba 07d29ff6 6860db98 95a48233 140ca249 419d6304 6448db1b 0f4252a6 \ e4edb947 fd0071d1 e52bc156 00622fa5 48a67739 63618150 797a8a80 e592446d \ f5926d0b fd32b544 b796f335 9567394f 77e7b171 b2f9bc5f 2caf7a0f ac0da7d0 \ 4d6a8674 4d6e06d0 2fbe15d0 f580a1d5 bd16ad91 34800361 1358dcb4 ac999095 \ 5f6cbbbf b185941d 4b4b71ce 7f9ba6ef c1270b78 08838b6c 7b7ef17e 8db919b3 4fac", }) }
{ test_vector(TestVector { password: "thepassword", encryption_salt: "0203040506070001", hmac_salt: "0304050607080102", iv: "0405060708090a0b0c0d0e0f00010203", plain_text: "0123456789abcdef 01234567", cipher_text: "03010203 04050607 00010304 05060708 01020405 06070809 0a0b0c0d 0e0f0001 \ 0203e01b bda5df2c a8adace3 8f6c588d 291e03f9 51b78d34 17bc2816 581dc6b7 \ 67f1a2e5 7597512b 18e1638f 21235fa5 928c", }) }
identifier_body
trait-bounds-sugar.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. // Tests for "default" bounds inferred for traits with no bounds list. trait Foo {} fn
(_x: Box<Foo+Send>) { } fn b(_x: &'static Foo) { // should be same as &'static Foo+'static } fn c(x: Box<Foo+Share>) { a(x); //~ ERROR expected bounds `Send` } fn d(x: &'static Foo+Share) { b(x); //~ ERROR expected bounds `'static` } fn main() {}
a
identifier_name
trait-bounds-sugar.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. // Tests for "default" bounds inferred for traits with no bounds list.
fn b(_x: &'static Foo) { // should be same as &'static Foo+'static } fn c(x: Box<Foo+Share>) { a(x); //~ ERROR expected bounds `Send` } fn d(x: &'static Foo+Share) { b(x); //~ ERROR expected bounds `'static` } fn main() {}
trait Foo {} fn a(_x: Box<Foo+Send>) { }
random_line_split
trait-bounds-sugar.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. // Tests for "default" bounds inferred for traits with no bounds list. trait Foo {} fn a(_x: Box<Foo+Send>) { } fn b(_x: &'static Foo) { // should be same as &'static Foo+'static } fn c(x: Box<Foo+Share>)
fn d(x: &'static Foo+Share) { b(x); //~ ERROR expected bounds `'static` } fn main() {}
{ a(x); //~ ERROR expected bounds `Send` }
identifier_body
const-int-saturating-arith.rs
// run-pass const INT_U32_NO: u32 = (42 as u32).saturating_add(2); const INT_U32: u32 = u32::MAX.saturating_add(1); const INT_U128: u128 = u128::MAX.saturating_add(1);
const INT_I128: i128 = i128::MAX.saturating_add(1); const INT_I128_NEG: i128 = i128::MIN.saturating_add(-1); const INT_U32_NO_SUB: u32 = (42 as u32).saturating_sub(2); const INT_U32_SUB: u32 = (1 as u32).saturating_sub(2); const INT_I32_NO_SUB: i32 = (-42 as i32).saturating_sub(2); const INT_I32_NEG_SUB: i32 = i32::MIN.saturating_sub(1); const INT_I32_POS_SUB: i32 = i32::MAX.saturating_sub(-1); const INT_U128_SUB: u128 = (0 as u128).saturating_sub(1); const INT_I128_NEG_SUB: i128 = i128::MIN.saturating_sub(1); const INT_I128_POS_SUB: i128 = i128::MAX.saturating_sub(-1); fn main() { assert_eq!(INT_U32_NO, 44); assert_eq!(INT_U32, u32::MAX); assert_eq!(INT_U128, u128::MAX); assert_eq!(INT_I128, i128::MAX); assert_eq!(INT_I128_NEG, i128::MIN); assert_eq!(INT_U32_NO_SUB, 40); assert_eq!(INT_U32_SUB, 0); assert_eq!(INT_I32_NO_SUB, -44); assert_eq!(INT_I32_NEG_SUB, i32::MIN); assert_eq!(INT_I32_POS_SUB, i32::MAX); assert_eq!(INT_U128_SUB, 0); assert_eq!(INT_I128_NEG_SUB, i128::MIN); assert_eq!(INT_I128_POS_SUB, i128::MAX); }
random_line_split
const-int-saturating-arith.rs
// run-pass const INT_U32_NO: u32 = (42 as u32).saturating_add(2); const INT_U32: u32 = u32::MAX.saturating_add(1); const INT_U128: u128 = u128::MAX.saturating_add(1); const INT_I128: i128 = i128::MAX.saturating_add(1); const INT_I128_NEG: i128 = i128::MIN.saturating_add(-1); const INT_U32_NO_SUB: u32 = (42 as u32).saturating_sub(2); const INT_U32_SUB: u32 = (1 as u32).saturating_sub(2); const INT_I32_NO_SUB: i32 = (-42 as i32).saturating_sub(2); const INT_I32_NEG_SUB: i32 = i32::MIN.saturating_sub(1); const INT_I32_POS_SUB: i32 = i32::MAX.saturating_sub(-1); const INT_U128_SUB: u128 = (0 as u128).saturating_sub(1); const INT_I128_NEG_SUB: i128 = i128::MIN.saturating_sub(1); const INT_I128_POS_SUB: i128 = i128::MAX.saturating_sub(-1); fn main()
{ assert_eq!(INT_U32_NO, 44); assert_eq!(INT_U32, u32::MAX); assert_eq!(INT_U128, u128::MAX); assert_eq!(INT_I128, i128::MAX); assert_eq!(INT_I128_NEG, i128::MIN); assert_eq!(INT_U32_NO_SUB, 40); assert_eq!(INT_U32_SUB, 0); assert_eq!(INT_I32_NO_SUB, -44); assert_eq!(INT_I32_NEG_SUB, i32::MIN); assert_eq!(INT_I32_POS_SUB, i32::MAX); assert_eq!(INT_U128_SUB, 0); assert_eq!(INT_I128_NEG_SUB, i128::MIN); assert_eq!(INT_I128_POS_SUB, i128::MAX); }
identifier_body
const-int-saturating-arith.rs
// run-pass const INT_U32_NO: u32 = (42 as u32).saturating_add(2); const INT_U32: u32 = u32::MAX.saturating_add(1); const INT_U128: u128 = u128::MAX.saturating_add(1); const INT_I128: i128 = i128::MAX.saturating_add(1); const INT_I128_NEG: i128 = i128::MIN.saturating_add(-1); const INT_U32_NO_SUB: u32 = (42 as u32).saturating_sub(2); const INT_U32_SUB: u32 = (1 as u32).saturating_sub(2); const INT_I32_NO_SUB: i32 = (-42 as i32).saturating_sub(2); const INT_I32_NEG_SUB: i32 = i32::MIN.saturating_sub(1); const INT_I32_POS_SUB: i32 = i32::MAX.saturating_sub(-1); const INT_U128_SUB: u128 = (0 as u128).saturating_sub(1); const INT_I128_NEG_SUB: i128 = i128::MIN.saturating_sub(1); const INT_I128_POS_SUB: i128 = i128::MAX.saturating_sub(-1); fn
() { assert_eq!(INT_U32_NO, 44); assert_eq!(INT_U32, u32::MAX); assert_eq!(INT_U128, u128::MAX); assert_eq!(INT_I128, i128::MAX); assert_eq!(INT_I128_NEG, i128::MIN); assert_eq!(INT_U32_NO_SUB, 40); assert_eq!(INT_U32_SUB, 0); assert_eq!(INT_I32_NO_SUB, -44); assert_eq!(INT_I32_NEG_SUB, i32::MIN); assert_eq!(INT_I32_POS_SUB, i32::MAX); assert_eq!(INT_U128_SUB, 0); assert_eq!(INT_I128_NEG_SUB, i128::MIN); assert_eq!(INT_I128_POS_SUB, i128::MAX); }
main
identifier_name
mod.rs
//! Seat handling and managing. use std::cell::RefCell; use std::rc::Rc; use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1; use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPointerConstraintsV1; use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3; use sctk::reexports::client::protocol::wl_seat::WlSeat; use sctk::reexports::client::Attached; use sctk::environment::Environment; use sctk::reexports::calloop::LoopHandle; use sctk::seat::pointer::ThemeManager; use sctk::seat::{SeatData, SeatListener}; use super::env::WinitEnv; use super::event_loop::WinitState; use crate::event::ModifiersState; mod keyboard; pub mod pointer; pub mod text_input; mod touch; use keyboard::Keyboard; use pointer::Pointers; use text_input::TextInput; use touch::Touch; pub struct SeatManager { /// Listener for seats. _seat_listener: SeatListener, } impl SeatManager { pub fn new( env: &Environment<WinitEnv>, loop_handle: LoopHandle<WinitState>, theme_manager: ThemeManager, ) -> Self { let relative_pointer_manager = env.get_global::<ZwpRelativePointerManagerV1>(); let pointer_constraints = env.get_global::<ZwpPointerConstraintsV1>(); let text_input_manager = env.get_global::<ZwpTextInputManagerV3>(); let mut inner = SeatManagerInner::new( theme_manager, relative_pointer_manager, pointer_constraints, text_input_manager, loop_handle, ); // Handle existing seats. for seat in env.get_all_seats() { let seat_data = match sctk::seat::clone_seat_data(&seat) { Some(seat_data) => seat_data, None => continue, }; inner.process_seat_update(&seat, &seat_data); } let seat_listener = env.listen_for_seats(move |seat, seat_data, _| { inner.process_seat_update(&seat, &seat_data); }); Self { _seat_listener: seat_listener, } } } /// Inner state of the seat manager. struct SeatManagerInner { /// Currently observed seats. seats: Vec<SeatInfo>, /// Loop handle. loop_handle: LoopHandle<WinitState>, /// Relative pointer manager. relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, /// Pointer constraints. pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, /// Text input manager. text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, /// A theme manager. theme_manager: ThemeManager, } impl SeatManagerInner { fn new( theme_manager: ThemeManager, relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, loop_handle: LoopHandle<WinitState>, ) -> Self { Self { seats: Vec::new(), loop_handle, relative_pointer_manager, pointer_constraints, text_input_manager, theme_manager, } } /// Handle seats update from the `SeatListener`. pub fn process_seat_update(&mut self, seat: &Attached<WlSeat>, seat_data: &SeatData) { let detached_seat = seat.detach(); let position = self.seats.iter().position(|si| si.seat == detached_seat); let index = position.unwrap_or_else(|| { self.seats.push(SeatInfo::new(detached_seat)); self.seats.len() - 1 }); let seat_info = &mut self.seats[index]; // Pointer handling. if seat_data.has_pointer &&!seat_data.defunct { if seat_info.pointer.is_none() { seat_info.pointer = Some(Pointers::new( &seat, &self.theme_manager, &self.relative_pointer_manager, &self.pointer_constraints, seat_info.modifiers_state.clone(), )); } } else { seat_info.pointer = None; } // Handle keyboard. if seat_data.has_keyboard &&!seat_data.defunct { if seat_info.keyboard.is_none() { seat_info.keyboard = Keyboard::new( &seat, self.loop_handle.clone(), seat_info.modifiers_state.clone(), ); } } else { seat_info.keyboard = None; } // Handle touch. if seat_data.has_touch &&!seat_data.defunct { if seat_info.touch.is_none() { seat_info.touch = Some(Touch::new(&seat)); } } else { seat_info.touch = None; }
if let Some(text_input_manager) = self.text_input_manager.as_ref() { if seat_data.defunct { seat_info.text_input = None; } else if seat_info.text_input.is_none() { seat_info.text_input = Some(TextInput::new(&seat, &text_input_manager)); } } } } /// Resources associtated with a given seat. struct SeatInfo { /// Seat to which this `SeatInfo` belongs. seat: WlSeat, /// A keyboard handle with its repeat rate handling. keyboard: Option<Keyboard>, /// All pointers we're using on a seat. pointer: Option<Pointers>, /// Touch handling. touch: Option<Touch>, /// Text input handling aka IME. text_input: Option<TextInput>, /// The current state of modifiers observed in keyboard handler. /// /// We keep modifiers state on a seat, since it's being used by pointer events as well. modifiers_state: Rc<RefCell<ModifiersState>>, } impl SeatInfo { pub fn new(seat: WlSeat) -> Self { Self { seat, keyboard: None, pointer: None, touch: None, text_input: None, modifiers_state: Rc::new(RefCell::new(ModifiersState::default())), } } }
// Handle text input.
random_line_split
mod.rs
//! Seat handling and managing. use std::cell::RefCell; use std::rc::Rc; use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1; use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPointerConstraintsV1; use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3; use sctk::reexports::client::protocol::wl_seat::WlSeat; use sctk::reexports::client::Attached; use sctk::environment::Environment; use sctk::reexports::calloop::LoopHandle; use sctk::seat::pointer::ThemeManager; use sctk::seat::{SeatData, SeatListener}; use super::env::WinitEnv; use super::event_loop::WinitState; use crate::event::ModifiersState; mod keyboard; pub mod pointer; pub mod text_input; mod touch; use keyboard::Keyboard; use pointer::Pointers; use text_input::TextInput; use touch::Touch; pub struct SeatManager { /// Listener for seats. _seat_listener: SeatListener, } impl SeatManager { pub fn new( env: &Environment<WinitEnv>, loop_handle: LoopHandle<WinitState>, theme_manager: ThemeManager, ) -> Self { let relative_pointer_manager = env.get_global::<ZwpRelativePointerManagerV1>(); let pointer_constraints = env.get_global::<ZwpPointerConstraintsV1>(); let text_input_manager = env.get_global::<ZwpTextInputManagerV3>(); let mut inner = SeatManagerInner::new( theme_manager, relative_pointer_manager, pointer_constraints, text_input_manager, loop_handle, ); // Handle existing seats. for seat in env.get_all_seats() { let seat_data = match sctk::seat::clone_seat_data(&seat) { Some(seat_data) => seat_data, None => continue, }; inner.process_seat_update(&seat, &seat_data); } let seat_listener = env.listen_for_seats(move |seat, seat_data, _| { inner.process_seat_update(&seat, &seat_data); }); Self { _seat_listener: seat_listener, } } } /// Inner state of the seat manager. struct SeatManagerInner { /// Currently observed seats. seats: Vec<SeatInfo>, /// Loop handle. loop_handle: LoopHandle<WinitState>, /// Relative pointer manager. relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, /// Pointer constraints. pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, /// Text input manager. text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, /// A theme manager. theme_manager: ThemeManager, } impl SeatManagerInner { fn new( theme_manager: ThemeManager, relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, loop_handle: LoopHandle<WinitState>, ) -> Self { Self { seats: Vec::new(), loop_handle, relative_pointer_manager, pointer_constraints, text_input_manager, theme_manager, } } /// Handle seats update from the `SeatListener`. pub fn process_seat_update(&mut self, seat: &Attached<WlSeat>, seat_data: &SeatData) { let detached_seat = seat.detach(); let position = self.seats.iter().position(|si| si.seat == detached_seat); let index = position.unwrap_or_else(|| { self.seats.push(SeatInfo::new(detached_seat)); self.seats.len() - 1 }); let seat_info = &mut self.seats[index]; // Pointer handling. if seat_data.has_pointer &&!seat_data.defunct { if seat_info.pointer.is_none() { seat_info.pointer = Some(Pointers::new( &seat, &self.theme_manager, &self.relative_pointer_manager, &self.pointer_constraints, seat_info.modifiers_state.clone(), )); } } else { seat_info.pointer = None; } // Handle keyboard. if seat_data.has_keyboard &&!seat_data.defunct
else { seat_info.keyboard = None; } // Handle touch. if seat_data.has_touch &&!seat_data.defunct { if seat_info.touch.is_none() { seat_info.touch = Some(Touch::new(&seat)); } } else { seat_info.touch = None; } // Handle text input. if let Some(text_input_manager) = self.text_input_manager.as_ref() { if seat_data.defunct { seat_info.text_input = None; } else if seat_info.text_input.is_none() { seat_info.text_input = Some(TextInput::new(&seat, &text_input_manager)); } } } } /// Resources associtated with a given seat. struct SeatInfo { /// Seat to which this `SeatInfo` belongs. seat: WlSeat, /// A keyboard handle with its repeat rate handling. keyboard: Option<Keyboard>, /// All pointers we're using on a seat. pointer: Option<Pointers>, /// Touch handling. touch: Option<Touch>, /// Text input handling aka IME. text_input: Option<TextInput>, /// The current state of modifiers observed in keyboard handler. /// /// We keep modifiers state on a seat, since it's being used by pointer events as well. modifiers_state: Rc<RefCell<ModifiersState>>, } impl SeatInfo { pub fn new(seat: WlSeat) -> Self { Self { seat, keyboard: None, pointer: None, touch: None, text_input: None, modifiers_state: Rc::new(RefCell::new(ModifiersState::default())), } } }
{ if seat_info.keyboard.is_none() { seat_info.keyboard = Keyboard::new( &seat, self.loop_handle.clone(), seat_info.modifiers_state.clone(), ); } }
conditional_block
mod.rs
//! Seat handling and managing. use std::cell::RefCell; use std::rc::Rc; use sctk::reexports::protocols::unstable::relative_pointer::v1::client::zwp_relative_pointer_manager_v1::ZwpRelativePointerManagerV1; use sctk::reexports::protocols::unstable::pointer_constraints::v1::client::zwp_pointer_constraints_v1::ZwpPointerConstraintsV1; use sctk::reexports::protocols::unstable::text_input::v3::client::zwp_text_input_manager_v3::ZwpTextInputManagerV3; use sctk::reexports::client::protocol::wl_seat::WlSeat; use sctk::reexports::client::Attached; use sctk::environment::Environment; use sctk::reexports::calloop::LoopHandle; use sctk::seat::pointer::ThemeManager; use sctk::seat::{SeatData, SeatListener}; use super::env::WinitEnv; use super::event_loop::WinitState; use crate::event::ModifiersState; mod keyboard; pub mod pointer; pub mod text_input; mod touch; use keyboard::Keyboard; use pointer::Pointers; use text_input::TextInput; use touch::Touch; pub struct SeatManager { /// Listener for seats. _seat_listener: SeatListener, } impl SeatManager { pub fn new( env: &Environment<WinitEnv>, loop_handle: LoopHandle<WinitState>, theme_manager: ThemeManager, ) -> Self { let relative_pointer_manager = env.get_global::<ZwpRelativePointerManagerV1>(); let pointer_constraints = env.get_global::<ZwpPointerConstraintsV1>(); let text_input_manager = env.get_global::<ZwpTextInputManagerV3>(); let mut inner = SeatManagerInner::new( theme_manager, relative_pointer_manager, pointer_constraints, text_input_manager, loop_handle, ); // Handle existing seats. for seat in env.get_all_seats() { let seat_data = match sctk::seat::clone_seat_data(&seat) { Some(seat_data) => seat_data, None => continue, }; inner.process_seat_update(&seat, &seat_data); } let seat_listener = env.listen_for_seats(move |seat, seat_data, _| { inner.process_seat_update(&seat, &seat_data); }); Self { _seat_listener: seat_listener, } } } /// Inner state of the seat manager. struct SeatManagerInner { /// Currently observed seats. seats: Vec<SeatInfo>, /// Loop handle. loop_handle: LoopHandle<WinitState>, /// Relative pointer manager. relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, /// Pointer constraints. pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, /// Text input manager. text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, /// A theme manager. theme_manager: ThemeManager, } impl SeatManagerInner { fn new( theme_manager: ThemeManager, relative_pointer_manager: Option<Attached<ZwpRelativePointerManagerV1>>, pointer_constraints: Option<Attached<ZwpPointerConstraintsV1>>, text_input_manager: Option<Attached<ZwpTextInputManagerV3>>, loop_handle: LoopHandle<WinitState>, ) -> Self { Self { seats: Vec::new(), loop_handle, relative_pointer_manager, pointer_constraints, text_input_manager, theme_manager, } } /// Handle seats update from the `SeatListener`. pub fn
(&mut self, seat: &Attached<WlSeat>, seat_data: &SeatData) { let detached_seat = seat.detach(); let position = self.seats.iter().position(|si| si.seat == detached_seat); let index = position.unwrap_or_else(|| { self.seats.push(SeatInfo::new(detached_seat)); self.seats.len() - 1 }); let seat_info = &mut self.seats[index]; // Pointer handling. if seat_data.has_pointer &&!seat_data.defunct { if seat_info.pointer.is_none() { seat_info.pointer = Some(Pointers::new( &seat, &self.theme_manager, &self.relative_pointer_manager, &self.pointer_constraints, seat_info.modifiers_state.clone(), )); } } else { seat_info.pointer = None; } // Handle keyboard. if seat_data.has_keyboard &&!seat_data.defunct { if seat_info.keyboard.is_none() { seat_info.keyboard = Keyboard::new( &seat, self.loop_handle.clone(), seat_info.modifiers_state.clone(), ); } } else { seat_info.keyboard = None; } // Handle touch. if seat_data.has_touch &&!seat_data.defunct { if seat_info.touch.is_none() { seat_info.touch = Some(Touch::new(&seat)); } } else { seat_info.touch = None; } // Handle text input. if let Some(text_input_manager) = self.text_input_manager.as_ref() { if seat_data.defunct { seat_info.text_input = None; } else if seat_info.text_input.is_none() { seat_info.text_input = Some(TextInput::new(&seat, &text_input_manager)); } } } } /// Resources associtated with a given seat. struct SeatInfo { /// Seat to which this `SeatInfo` belongs. seat: WlSeat, /// A keyboard handle with its repeat rate handling. keyboard: Option<Keyboard>, /// All pointers we're using on a seat. pointer: Option<Pointers>, /// Touch handling. touch: Option<Touch>, /// Text input handling aka IME. text_input: Option<TextInput>, /// The current state of modifiers observed in keyboard handler. /// /// We keep modifiers state on a seat, since it's being used by pointer events as well. modifiers_state: Rc<RefCell<ModifiersState>>, } impl SeatInfo { pub fn new(seat: WlSeat) -> Self { Self { seat, keyboard: None, pointer: None, touch: None, text_input: None, modifiers_state: Rc::new(RefCell::new(ModifiersState::default())), } } }
process_seat_update
identifier_name
use-keyword.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Check that imports with nakes super and self don't fail during parsing
mod a { mod b { use self as A; //~^ ERROR `self` imports are only allowed within a { } list use super as B; //~^ ERROR unresolved import `super` [E0432] //~| no `super` in the root use super::{self as C}; //~^ ERROR unresolved import `super` [E0432] //~| no `super` in the root } } fn main() {}
// FIXME: this shouldn't fail during name resolution either
random_line_split
use-keyword.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Check that imports with nakes super and self don't fail during parsing // FIXME: this shouldn't fail during name resolution either mod a { mod b { use self as A; //~^ ERROR `self` imports are only allowed within a { } list use super as B; //~^ ERROR unresolved import `super` [E0432] //~| no `super` in the root use super::{self as C}; //~^ ERROR unresolved import `super` [E0432] //~| no `super` in the root } } fn
() {}
main
identifier_name
use-keyword.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Check that imports with nakes super and self don't fail during parsing // FIXME: this shouldn't fail during name resolution either mod a { mod b { use self as A; //~^ ERROR `self` imports are only allowed within a { } list use super as B; //~^ ERROR unresolved import `super` [E0432] //~| no `super` in the root use super::{self as C}; //~^ ERROR unresolved import `super` [E0432] //~| no `super` in the root } } fn main()
{}
identifier_body
demand.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty; use middle::typeck::check::FnCtxt; use middle::typeck::infer; use middle::typeck::infer::resolve_type; use middle::typeck::infer::resolve::try_resolve_tvar_shallow; use std::result::{Err, Ok}; use std::result; use syntax::ast; use syntax::codemap::Span; use util::ppaux::Repr; // Requires that the two types unify, and prints an error message if they // don't. pub fn suptype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { suptype_with_fn(fcx, sp, false, expected, actual, |sp, e, a, s| { fcx.report_mismatched_types(sp, e, a, s) }) } pub fn
(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { suptype_with_fn(fcx, sp, true, actual, expected, |sp, a, e, s| { fcx.report_mismatched_types(sp, e, a, s) }) } pub fn suptype_with_fn(fcx: &FnCtxt, sp: Span, b_is_expected: bool, ty_a: ty::t, ty_b: ty::t, handle_err: |Span, ty::t, ty::t, &ty::type_err|) { // n.b.: order of actual, expected is reversed match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp), ty_b, ty_a) { result::Ok(()) => { /* ok */ } result::Err(ref err) => { handle_err(sp, ty_a, ty_b, err); } } } pub fn eqtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { match infer::mk_eqty(fcx.infcx(), false, infer::Misc(sp), actual, expected) { Ok(()) => { /* ok */ } Err(ref err) => { fcx.report_mismatched_types(sp, expected, actual, err); } } } // Checks that the type `actual` can be coerced to `expected`. pub fn coerce(fcx: &FnCtxt, sp: Span, expected: ty::t, expr: &ast::Expr) { let expr_ty = fcx.expr_ty(expr); debug!("demand::coerce(expected = {}, expr_ty = {})", expected.repr(fcx.ccx.tcx), expr_ty.repr(fcx.ccx.tcx)); let expected = if ty::type_needs_infer(expected) { resolve_type(fcx.infcx(), expected, try_resolve_tvar_shallow).unwrap_or(expected) } else { expected }; match fcx.mk_assignty(expr, expr_ty, expected) { result::Ok(()) => { /* ok */ } result::Err(ref err) => { fcx.report_mismatched_types(sp, expected, expr_ty, err); } } }
subtype
identifier_name
demand.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty; use middle::typeck::check::FnCtxt; use middle::typeck::infer; use middle::typeck::infer::resolve_type; use middle::typeck::infer::resolve::try_resolve_tvar_shallow; use std::result::{Err, Ok}; use std::result; use syntax::ast; use syntax::codemap::Span; use util::ppaux::Repr; // Requires that the two types unify, and prints an error message if they // don't. pub fn suptype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { suptype_with_fn(fcx, sp, false, expected, actual, |sp, e, a, s| { fcx.report_mismatched_types(sp, e, a, s) }) } pub fn subtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { suptype_with_fn(fcx, sp, true, actual, expected, |sp, a, e, s| { fcx.report_mismatched_types(sp, e, a, s) }) } pub fn suptype_with_fn(fcx: &FnCtxt, sp: Span, b_is_expected: bool, ty_a: ty::t, ty_b: ty::t, handle_err: |Span, ty::t, ty::t, &ty::type_err|) { // n.b.: order of actual, expected is reversed match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp), ty_b, ty_a) { result::Ok(()) => { /* ok */ } result::Err(ref err) => { handle_err(sp, ty_a, ty_b, err); } } } pub fn eqtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { match infer::mk_eqty(fcx.infcx(), false, infer::Misc(sp), actual, expected) { Ok(()) => { /* ok */ } Err(ref err) => { fcx.report_mismatched_types(sp, expected, actual, err); } } } // Checks that the type `actual` can be coerced to `expected`. pub fn coerce(fcx: &FnCtxt, sp: Span, expected: ty::t, expr: &ast::Expr) { let expr_ty = fcx.expr_ty(expr); debug!("demand::coerce(expected = {}, expr_ty = {})", expected.repr(fcx.ccx.tcx), expr_ty.repr(fcx.ccx.tcx)); let expected = if ty::type_needs_infer(expected)
else { expected }; match fcx.mk_assignty(expr, expr_ty, expected) { result::Ok(()) => { /* ok */ } result::Err(ref err) => { fcx.report_mismatched_types(sp, expected, expr_ty, err); } } }
{ resolve_type(fcx.infcx(), expected, try_resolve_tvar_shallow).unwrap_or(expected) }
conditional_block
demand.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty; use middle::typeck::check::FnCtxt; use middle::typeck::infer; use middle::typeck::infer::resolve_type; use middle::typeck::infer::resolve::try_resolve_tvar_shallow; use std::result::{Err, Ok}; use std::result; use syntax::ast; use syntax::codemap::Span; use util::ppaux::Repr; // Requires that the two types unify, and prints an error message if they // don't. pub fn suptype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { suptype_with_fn(fcx, sp, false, expected, actual, |sp, e, a, s| { fcx.report_mismatched_types(sp, e, a, s) }) } pub fn subtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t)
pub fn suptype_with_fn(fcx: &FnCtxt, sp: Span, b_is_expected: bool, ty_a: ty::t, ty_b: ty::t, handle_err: |Span, ty::t, ty::t, &ty::type_err|) { // n.b.: order of actual, expected is reversed match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp), ty_b, ty_a) { result::Ok(()) => { /* ok */ } result::Err(ref err) => { handle_err(sp, ty_a, ty_b, err); } } } pub fn eqtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { match infer::mk_eqty(fcx.infcx(), false, infer::Misc(sp), actual, expected) { Ok(()) => { /* ok */ } Err(ref err) => { fcx.report_mismatched_types(sp, expected, actual, err); } } } // Checks that the type `actual` can be coerced to `expected`. pub fn coerce(fcx: &FnCtxt, sp: Span, expected: ty::t, expr: &ast::Expr) { let expr_ty = fcx.expr_ty(expr); debug!("demand::coerce(expected = {}, expr_ty = {})", expected.repr(fcx.ccx.tcx), expr_ty.repr(fcx.ccx.tcx)); let expected = if ty::type_needs_infer(expected) { resolve_type(fcx.infcx(), expected, try_resolve_tvar_shallow).unwrap_or(expected) } else { expected }; match fcx.mk_assignty(expr, expr_ty, expected) { result::Ok(()) => { /* ok */ } result::Err(ref err) => { fcx.report_mismatched_types(sp, expected, expr_ty, err); } } }
{ suptype_with_fn(fcx, sp, true, actual, expected, |sp, a, e, s| { fcx.report_mismatched_types(sp, e, a, s) }) }
identifier_body
demand.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty; use middle::typeck::check::FnCtxt; use middle::typeck::infer; use middle::typeck::infer::resolve_type; use middle::typeck::infer::resolve::try_resolve_tvar_shallow; use std::result::{Err, Ok}; use std::result; use syntax::ast; use syntax::codemap::Span; use util::ppaux::Repr; // Requires that the two types unify, and prints an error message if they // don't. pub fn suptype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) {
pub fn subtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { suptype_with_fn(fcx, sp, true, actual, expected, |sp, a, e, s| { fcx.report_mismatched_types(sp, e, a, s) }) } pub fn suptype_with_fn(fcx: &FnCtxt, sp: Span, b_is_expected: bool, ty_a: ty::t, ty_b: ty::t, handle_err: |Span, ty::t, ty::t, &ty::type_err|) { // n.b.: order of actual, expected is reversed match infer::mk_subty(fcx.infcx(), b_is_expected, infer::Misc(sp), ty_b, ty_a) { result::Ok(()) => { /* ok */ } result::Err(ref err) => { handle_err(sp, ty_a, ty_b, err); } } } pub fn eqtype(fcx: &FnCtxt, sp: Span, expected: ty::t, actual: ty::t) { match infer::mk_eqty(fcx.infcx(), false, infer::Misc(sp), actual, expected) { Ok(()) => { /* ok */ } Err(ref err) => { fcx.report_mismatched_types(sp, expected, actual, err); } } } // Checks that the type `actual` can be coerced to `expected`. pub fn coerce(fcx: &FnCtxt, sp: Span, expected: ty::t, expr: &ast::Expr) { let expr_ty = fcx.expr_ty(expr); debug!("demand::coerce(expected = {}, expr_ty = {})", expected.repr(fcx.ccx.tcx), expr_ty.repr(fcx.ccx.tcx)); let expected = if ty::type_needs_infer(expected) { resolve_type(fcx.infcx(), expected, try_resolve_tvar_shallow).unwrap_or(expected) } else { expected }; match fcx.mk_assignty(expr, expr_ty, expected) { result::Ok(()) => { /* ok */ } result::Err(ref err) => { fcx.report_mismatched_types(sp, expected, expr_ty, err); } } }
suptype_with_fn(fcx, sp, false, expected, actual, |sp, e, a, s| { fcx.report_mismatched_types(sp, e, a, s) }) }
random_line_split
lifetime-update.rs
#![feature(type_changing_struct_update)] #![allow(incomplete_features)] #[derive(Clone)] struct Machine<'a, S> {
} #[derive(Clone)] struct State1; #[derive(Clone)] struct State2; fn update_to_state2() { let s = String::from("hello"); let m1: Machine<State1> = Machine { state: State1, lt_str: &s, //~^ ERROR `s` does not live long enough [E0597] // FIXME: The error here actually comes from line 34. The // span of the error message should be corrected to line 34 common_field: 2, }; // update lifetime let m3: Machine<'static, State1> = Machine { lt_str: "hello, too", ..m1.clone() }; // update lifetime and type let m4: Machine<'static, State2> = Machine { state: State2, lt_str: "hello, again", ..m1.clone() }; // updating to `static should fail. let m2: Machine<'static, State1> = Machine { ..m1 }; } fn main() {}
state: S, lt_str: &'a str, common_field: i32,
random_line_split
lifetime-update.rs
#![feature(type_changing_struct_update)] #![allow(incomplete_features)] #[derive(Clone)] struct Machine<'a, S> { state: S, lt_str: &'a str, common_field: i32, } #[derive(Clone)] struct
; #[derive(Clone)] struct State2; fn update_to_state2() { let s = String::from("hello"); let m1: Machine<State1> = Machine { state: State1, lt_str: &s, //~^ ERROR `s` does not live long enough [E0597] // FIXME: The error here actually comes from line 34. The // span of the error message should be corrected to line 34 common_field: 2, }; // update lifetime let m3: Machine<'static, State1> = Machine { lt_str: "hello, too", ..m1.clone() }; // update lifetime and type let m4: Machine<'static, State2> = Machine { state: State2, lt_str: "hello, again", ..m1.clone() }; // updating to `static should fail. let m2: Machine<'static, State1> = Machine { ..m1 }; } fn main() {}
State1
identifier_name
lib.rs
#![doc(html_root_url = "http://cpjreynolds.github.io/rustty/rustty/index.html")] //! # Rustty //! //! Rustty is a terminal UI library that provides a simple, concise abstraction over an //! underlying terminal device. //! //! Rustty is based on the concepts of cells and events. A terminal display is an array of cells, //! each holding a character and a set of foreground and background styles. Events are how a //! terminal communicates changes in its state; events are received from a terminal, processed, and //! pushed onto an input stream to be read and responded to. //! //! Futher reading on the concepts behind Rustty can be found in the //! [README](https://github.com/cpjreynolds/rustty/blob/master/README.md) extern crate term; extern crate nix; extern crate libc; extern crate gag; #[macro_use] extern crate lazy_static; mod core; mod util; pub mod ui; pub use core::terminal::Terminal; pub use core::cellbuffer::{ Cell,
pub use core::position::{Pos, Size, HasSize, HasPosition}; pub use core::input::Event; pub use util::errors::Error;
Color, Attr, CellAccessor, };
random_line_split
expressionset.rs
use ordered_float::NotNaN; use bio::stats::probs; use crate::model; pub type MeanExpression = NotNaN<f64>; pub type CDF = probs::cdf::CDF<MeanExpression>; pub fn cdf(expression_cdfs: &[model::expression::NormalizedCDF], pseudocounts: f64) -> CDF
// #[cfg(test)] // mod tests { // #![allow(non_upper_case_globals)] // // use bio::stats::{Prob, LogProb}; // // use super::*; // use model; // use io; // // // const GENE: &'static str = "COL5A1"; // // fn setup() -> Box<model::readout::Model> { // model::readout::new_model( // &[Prob(0.04); 16], // &[Prob(0.1); 16], // io::codebook::Codebook::from_file("tests/codebook/140genesData.1.txt").unwrap() // ) // } // // #[test] // fn test_cdf() { // let readout = setup(); // let cdfs = [ // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0 // ]; // println!("{:?}", cdfs[0]); // let cdf = cdf(&cdfs, 0.0000001); // println!("{:?}", cdf); // // let total = cdf.total_prob(); // // assert_relative_eq!(*total, *LogProb::ln_one(), epsilon = 0.002); // } // }
{ let pseudocounts = NotNaN::new(pseudocounts).unwrap(); if expression_cdfs.len() == 1 { let mut cdf = expression_cdfs[0].clone(); for e in cdf.iter_mut() { e.value += pseudocounts; } return cdf; } let cdf = model::meanvar::cdf(expression_cdfs, |mean, _| mean + pseudocounts); assert_relative_eq!(cdf.total_prob().exp(), 1.0, epsilon = 0.001); cdf.reduce().sample(1000) }
identifier_body
expressionset.rs
use ordered_float::NotNaN; use bio::stats::probs; use crate::model; pub type MeanExpression = NotNaN<f64>; pub type CDF = probs::cdf::CDF<MeanExpression>; pub fn cdf(expression_cdfs: &[model::expression::NormalizedCDF], pseudocounts: f64) -> CDF { let pseudocounts = NotNaN::new(pseudocounts).unwrap(); if expression_cdfs.len() == 1 { let mut cdf = expression_cdfs[0].clone(); for e in cdf.iter_mut() { e.value += pseudocounts; } return cdf; } let cdf = model::meanvar::cdf(expression_cdfs, |mean, _| mean + pseudocounts); assert_relative_eq!(cdf.total_prob().exp(), 1.0, epsilon = 0.001); cdf.reduce().sample(1000) } // #[cfg(test)] // mod tests { // #![allow(non_upper_case_globals)] // // use bio::stats::{Prob, LogProb}; // // use super::*; // use model; // use io; // // // const GENE: &'static str = "COL5A1"; // // fn setup() -> Box<model::readout::Model> { // model::readout::new_model( // &[Prob(0.04); 16], // &[Prob(0.1); 16],
// io::codebook::Codebook::from_file("tests/codebook/140genesData.1.txt").unwrap() // ) // } // // #[test] // fn test_cdf() { // let readout = setup(); // let cdfs = [ // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0 // ]; // println!("{:?}", cdfs[0]); // let cdf = cdf(&cdfs, 0.0000001); // println!("{:?}", cdf); // // let total = cdf.total_prob(); // // assert_relative_eq!(*total, *LogProb::ln_one(), epsilon = 0.002); // } // }
random_line_split
expressionset.rs
use ordered_float::NotNaN; use bio::stats::probs; use crate::model; pub type MeanExpression = NotNaN<f64>; pub type CDF = probs::cdf::CDF<MeanExpression>; pub fn
(expression_cdfs: &[model::expression::NormalizedCDF], pseudocounts: f64) -> CDF { let pseudocounts = NotNaN::new(pseudocounts).unwrap(); if expression_cdfs.len() == 1 { let mut cdf = expression_cdfs[0].clone(); for e in cdf.iter_mut() { e.value += pseudocounts; } return cdf; } let cdf = model::meanvar::cdf(expression_cdfs, |mean, _| mean + pseudocounts); assert_relative_eq!(cdf.total_prob().exp(), 1.0, epsilon = 0.001); cdf.reduce().sample(1000) } // #[cfg(test)] // mod tests { // #![allow(non_upper_case_globals)] // // use bio::stats::{Prob, LogProb}; // // use super::*; // use model; // use io; // // // const GENE: &'static str = "COL5A1"; // // fn setup() -> Box<model::readout::Model> { // model::readout::new_model( // &[Prob(0.04); 16], // &[Prob(0.1); 16], // io::codebook::Codebook::from_file("tests/codebook/140genesData.1.txt").unwrap() // ) // } // // #[test] // fn test_cdf() { // let readout = setup(); // let cdfs = [ // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0 // ]; // println!("{:?}", cdfs[0]); // let cdf = cdf(&cdfs, 0.0000001); // println!("{:?}", cdf); // // let total = cdf.total_prob(); // // assert_relative_eq!(*total, *LogProb::ln_one(), epsilon = 0.002); // } // }
cdf
identifier_name
expressionset.rs
use ordered_float::NotNaN; use bio::stats::probs; use crate::model; pub type MeanExpression = NotNaN<f64>; pub type CDF = probs::cdf::CDF<MeanExpression>; pub fn cdf(expression_cdfs: &[model::expression::NormalizedCDF], pseudocounts: f64) -> CDF { let pseudocounts = NotNaN::new(pseudocounts).unwrap(); if expression_cdfs.len() == 1
let cdf = model::meanvar::cdf(expression_cdfs, |mean, _| mean + pseudocounts); assert_relative_eq!(cdf.total_prob().exp(), 1.0, epsilon = 0.001); cdf.reduce().sample(1000) } // #[cfg(test)] // mod tests { // #![allow(non_upper_case_globals)] // // use bio::stats::{Prob, LogProb}; // // use super::*; // use model; // use io; // // // const GENE: &'static str = "COL5A1"; // // fn setup() -> Box<model::readout::Model> { // model::readout::new_model( // &[Prob(0.04); 16], // &[Prob(0.1); 16], // io::codebook::Codebook::from_file("tests/codebook/140genesData.1.txt").unwrap() // ) // } // // #[test] // fn test_cdf() { // let readout = setup(); // let cdfs = [ // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0, // model::expression::cdf(GENE, 5, 5, &readout, 100).0 // ]; // println!("{:?}", cdfs[0]); // let cdf = cdf(&cdfs, 0.0000001); // println!("{:?}", cdf); // // let total = cdf.total_prob(); // // assert_relative_eq!(*total, *LogProb::ln_one(), epsilon = 0.002); // } // }
{ let mut cdf = expression_cdfs[0].clone(); for e in cdf.iter_mut() { e.value += pseudocounts; } return cdf; }
conditional_block
load.rs
/*! # Reading and loading hyphenation dictionaries To hyphenate words in a given language, it is first necessary to load the relevant hyphenation dictionary into memory. This module offers convenience methods for common retrieval patterns, courtesy of the [`Load`] trait. ``` use hyphenation::Load; use hyphenation::{Standard, Language}; ``` The primary function of [`Load`] is to deserialize dictionaries from buffers – usually, file buffers. ```ignore use std::io; use std::fs::File; let path_to_dict = "/path/to/english-dictionary.bincode"; let dict_file = File::open(path_to_dict)?; let mut reader = io::BufReader::new(dict_file); let english_us = Standard::from_reader(Language::EnglishUS, &mut reader)?; ``` Dictionaries can be loaded from the file system rather more succintly with the [`from_path`] shorthand: ```ignore let path_to_dict = "/path/to/english-dictionary.bincode"; let english_us = Standard::from_path(Language::EnglishUS, path_to_dict)?; ``` Dictionaries bundled with the `hyphenation` library are copied to Cargo's output directory at build time. To locate them, look for a `dictionaries` folder under `target`: ```text $ find target -name "dictionaries" target/debug/build/hyphenation-33034db3e3b5f3ce/out/dictionaries ``` ## Embedding Optionally, hyphenation dictionaries can be embedded in the compiled artifact by enabling the `embed_all` feature. Embedded dictionaries can be accessed directly from memory. ```ignore use hyphenation::{Standard, Language, Load}; let english_us = Standard::from_embedded(Language::EnglishUS)?; ``` Note that embedding significantly increases the size of the compiled artifact. [`Load`]: trait.Load.html [`from_path`]: trait.Load.html#method.from_path */ #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] use resources::ResourceId; use bincode as bin; use std::error; use std::fmt; use std::io; use std::fs::File; use std::path::Path; use std::result; use hyphenation_commons::Language; use hyphenation_commons::dictionary::{Standard, extended::Extended}; /// Convenience methods for the retrieval of hyphenation dictionaries. pub trait Load : Sized { /// Read and deserialize the dictionary at the given path, verifying that it /// belongs to the expected language. fn from_path<P>(lang : Language, path : P) -> Result<Self> where P : AsRef<Path> {
/// Deserialize a dictionary from the provided reader, verifying that it /// belongs to the expected language. fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self> where R : io::Read; /// Deserialize a dictionary from the provided reader. fn any_from_reader<R>(reader : &mut R) -> Result<Self> where R : io::Read; #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] /// Deserialize the embedded dictionary for the given language. fn from_embedded(lang : Language) -> Result<Self>; } macro_rules! impl_load { ($dict:ty, $suffix:expr) => { impl Load for $dict { fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self> where R : io::Read { let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader)?; let (found, expected) = (dict.language(), lang); if found!= expected { Err(Error::LanguageMismatch { expected, found }) } else { Ok(dict) } } fn any_from_reader<R>(reader : &mut R) -> Result<Self> where R : io::Read { let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader)?; Ok(dict) } #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] fn from_embedded(lang : Language) -> Result<Self> { let dict_bytes = retrieve_resource(lang.code(), $suffix)?; let dict = bin::deserialize(dict_bytes)?; Ok(dict) } } } } impl_load! { Standard, "standard" } impl_load! { Extended, "extended" } #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] fn retrieve_resource<'a>(code : &str, suffix : &str) -> Result<&'a [u8]> { let name = format!("{}.{}.bincode", code, suffix); let res : Option<ResourceId> = ResourceId::from_name(&name); match res { Some(data) => Ok(data.load()), None => Err(Error::Resource) } } pub type Result<T> = result::Result<T, Error>; /// Failure modes of dictionary loading. #[derive(Debug)] pub enum Error { /// The dictionary could not be deserialized. Deserialization(bin::Error), /// The dictionary could not be read. IO(io::Error), /// The loaded dictionary is for the wrong language. LanguageMismatch { expected : Language, found : Language }, /// The embedded dictionary could not be retrieved. Resource } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error +'static)> { match *self { Error::Deserialization(ref e) => Some(e), Error::IO(ref e) => Some(e), _ => None } } } impl fmt::Display for Error { fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result { match *self { Error::Deserialization(ref e) => e.fmt(f), Error::IO(ref e) => e.fmt(f), Error::LanguageMismatch { expected, found } => write!(f, "\ Language mismatch: attempted to load a dictionary for `{}`, but found a dictionary for `{}` instead.", expected, found), Error::Resource => f.write_str("the embedded dictionary could not be retrieved") } } } impl From<io::Error> for Error { fn from(err : io::Error) -> Error { Error::IO(err) } } impl From<bin::Error> for Error { fn from(err : bin::Error) -> Error { Error::Deserialization(err) } }
let file = File::open(path) ?; Self::from_reader(lang, &mut io::BufReader::new(file)) }
identifier_body
load.rs
/*! # Reading and loading hyphenation dictionaries To hyphenate words in a given language, it is first necessary to load the relevant hyphenation dictionary into memory. This module offers convenience methods for common retrieval patterns, courtesy of the [`Load`] trait. ``` use hyphenation::Load; use hyphenation::{Standard, Language}; ``` The primary function of [`Load`] is to deserialize dictionaries from buffers – usually, file buffers. ```ignore use std::io; use std::fs::File; let path_to_dict = "/path/to/english-dictionary.bincode"; let dict_file = File::open(path_to_dict)?; let mut reader = io::BufReader::new(dict_file); let english_us = Standard::from_reader(Language::EnglishUS, &mut reader)?; ``` Dictionaries can be loaded from the file system rather more succintly with the [`from_path`] shorthand: ```ignore let path_to_dict = "/path/to/english-dictionary.bincode"; let english_us = Standard::from_path(Language::EnglishUS, path_to_dict)?; ``` Dictionaries bundled with the `hyphenation` library are copied to Cargo's output directory at build time. To locate them, look for a `dictionaries` folder under `target`: ```text $ find target -name "dictionaries" target/debug/build/hyphenation-33034db3e3b5f3ce/out/dictionaries ``` ## Embedding Optionally, hyphenation dictionaries can be embedded in the compiled artifact by enabling the `embed_all` feature. Embedded dictionaries can be accessed directly from memory. ```ignore use hyphenation::{Standard, Language, Load}; let english_us = Standard::from_embedded(Language::EnglishUS)?; ``` Note that embedding significantly increases the size of the compiled artifact. [`Load`]: trait.Load.html [`from_path`]: trait.Load.html#method.from_path */ #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] use resources::ResourceId; use bincode as bin; use std::error; use std::fmt; use std::io; use std::fs::File; use std::path::Path; use std::result; use hyphenation_commons::Language; use hyphenation_commons::dictionary::{Standard, extended::Extended}; /// Convenience methods for the retrieval of hyphenation dictionaries. pub trait Load : Sized { /// Read and deserialize the dictionary at the given path, verifying that it /// belongs to the expected language. fn from_path<P>(lang : Language, path : P) -> Result<Self> where P : AsRef<Path> { let file = File::open(path)?; Self::from_reader(lang, &mut io::BufReader::new(file)) } /// Deserialize a dictionary from the provided reader, verifying that it /// belongs to the expected language. fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self> where R : io::Read; /// Deserialize a dictionary from the provided reader. fn any_from_reader<R>(reader : &mut R) -> Result<Self> where R : io::Read; #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] /// Deserialize the embedded dictionary for the given language. fn from_embedded(lang : Language) -> Result<Self>; } macro_rules! impl_load { ($dict:ty, $suffix:expr) => { impl Load for $dict { fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self> where R : io::Read { let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader)?; let (found, expected) = (dict.language(), lang); if found!= expected { Err(Error::LanguageMismatch { expected, found }) } else { Ok(dict) } } fn any_from_reader<R>(reader : &mut R) -> Result<Self> where R : io::Read { let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader)?; Ok(dict) } #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] fn from_embedded(lang : Language) -> Result<Self> { let dict_bytes = retrieve_resource(lang.code(), $suffix)?; let dict = bin::deserialize(dict_bytes)?; Ok(dict) } } } } impl_load! { Standard, "standard" } impl_load! { Extended, "extended" } #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] fn re
a>(code : &str, suffix : &str) -> Result<&'a [u8]> { let name = format!("{}.{}.bincode", code, suffix); let res : Option<ResourceId> = ResourceId::from_name(&name); match res { Some(data) => Ok(data.load()), None => Err(Error::Resource) } } pub type Result<T> = result::Result<T, Error>; /// Failure modes of dictionary loading. #[derive(Debug)] pub enum Error { /// The dictionary could not be deserialized. Deserialization(bin::Error), /// The dictionary could not be read. IO(io::Error), /// The loaded dictionary is for the wrong language. LanguageMismatch { expected : Language, found : Language }, /// The embedded dictionary could not be retrieved. Resource } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error +'static)> { match *self { Error::Deserialization(ref e) => Some(e), Error::IO(ref e) => Some(e), _ => None } } } impl fmt::Display for Error { fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result { match *self { Error::Deserialization(ref e) => e.fmt(f), Error::IO(ref e) => e.fmt(f), Error::LanguageMismatch { expected, found } => write!(f, "\ Language mismatch: attempted to load a dictionary for `{}`, but found a dictionary for `{}` instead.", expected, found), Error::Resource => f.write_str("the embedded dictionary could not be retrieved") } } } impl From<io::Error> for Error { fn from(err : io::Error) -> Error { Error::IO(err) } } impl From<bin::Error> for Error { fn from(err : bin::Error) -> Error { Error::Deserialization(err) } }
trieve_resource<'
identifier_name
load.rs
/*! # Reading and loading hyphenation dictionaries To hyphenate words in a given language, it is first necessary to load the relevant hyphenation dictionary into memory. This module offers convenience methods for common retrieval patterns, courtesy of the [`Load`] trait. ``` use hyphenation::Load; use hyphenation::{Standard, Language}; ``` The primary function of [`Load`] is to deserialize dictionaries from buffers – usually, file buffers. ```ignore use std::io; use std::fs::File; let path_to_dict = "/path/to/english-dictionary.bincode"; let dict_file = File::open(path_to_dict)?; let mut reader = io::BufReader::new(dict_file); let english_us = Standard::from_reader(Language::EnglishUS, &mut reader)?; ``` Dictionaries can be loaded from the file system rather more succintly with the [`from_path`] shorthand: ```ignore let path_to_dict = "/path/to/english-dictionary.bincode"; let english_us = Standard::from_path(Language::EnglishUS, path_to_dict)?; ``` Dictionaries bundled with the `hyphenation` library are copied to Cargo's output directory at build time. To locate them, look for a `dictionaries` folder under `target`: ```text $ find target -name "dictionaries" target/debug/build/hyphenation-33034db3e3b5f3ce/out/dictionaries ``` ## Embedding Optionally, hyphenation dictionaries can be embedded in the compiled artifact by enabling the `embed_all` feature. Embedded dictionaries can be accessed directly from memory. ```ignore use hyphenation::{Standard, Language, Load}; let english_us = Standard::from_embedded(Language::EnglishUS)?; ``` Note that embedding significantly increases the size of the compiled artifact. [`Load`]: trait.Load.html [`from_path`]: trait.Load.html#method.from_path */ #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] use resources::ResourceId; use bincode as bin; use std::error; use std::fmt; use std::io; use std::fs::File; use std::path::Path; use std::result; use hyphenation_commons::Language; use hyphenation_commons::dictionary::{Standard, extended::Extended}; /// Convenience methods for the retrieval of hyphenation dictionaries. pub trait Load : Sized { /// Read and deserialize the dictionary at the given path, verifying that it /// belongs to the expected language. fn from_path<P>(lang : Language, path : P) -> Result<Self> where P : AsRef<Path> { let file = File::open(path)?; Self::from_reader(lang, &mut io::BufReader::new(file)) } /// Deserialize a dictionary from the provided reader, verifying that it /// belongs to the expected language. fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self> where R : io::Read; /// Deserialize a dictionary from the provided reader. fn any_from_reader<R>(reader : &mut R) -> Result<Self> where R : io::Read; #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] /// Deserialize the embedded dictionary for the given language. fn from_embedded(lang : Language) -> Result<Self>; } macro_rules! impl_load {
where R : io::Read { let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader)?; let (found, expected) = (dict.language(), lang); if found!= expected { Err(Error::LanguageMismatch { expected, found }) } else { Ok(dict) } } fn any_from_reader<R>(reader : &mut R) -> Result<Self> where R : io::Read { let dict : Self = bin::config().limit(5_000_000).deserialize_from(reader)?; Ok(dict) } #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] fn from_embedded(lang : Language) -> Result<Self> { let dict_bytes = retrieve_resource(lang.code(), $suffix)?; let dict = bin::deserialize(dict_bytes)?; Ok(dict) } } } } impl_load! { Standard, "standard" } impl_load! { Extended, "extended" } #[cfg(any(feature = "embed_all", feature = "embed_en-us"))] fn retrieve_resource<'a>(code : &str, suffix : &str) -> Result<&'a [u8]> { let name = format!("{}.{}.bincode", code, suffix); let res : Option<ResourceId> = ResourceId::from_name(&name); match res { Some(data) => Ok(data.load()), None => Err(Error::Resource) } } pub type Result<T> = result::Result<T, Error>; /// Failure modes of dictionary loading. #[derive(Debug)] pub enum Error { /// The dictionary could not be deserialized. Deserialization(bin::Error), /// The dictionary could not be read. IO(io::Error), /// The loaded dictionary is for the wrong language. LanguageMismatch { expected : Language, found : Language }, /// The embedded dictionary could not be retrieved. Resource } impl error::Error for Error { fn source(&self) -> Option<&(dyn error::Error +'static)> { match *self { Error::Deserialization(ref e) => Some(e), Error::IO(ref e) => Some(e), _ => None } } } impl fmt::Display for Error { fn fmt(&self, f : &mut fmt::Formatter) -> fmt::Result { match *self { Error::Deserialization(ref e) => e.fmt(f), Error::IO(ref e) => e.fmt(f), Error::LanguageMismatch { expected, found } => write!(f, "\ Language mismatch: attempted to load a dictionary for `{}`, but found a dictionary for `{}` instead.", expected, found), Error::Resource => f.write_str("the embedded dictionary could not be retrieved") } } } impl From<io::Error> for Error { fn from(err : io::Error) -> Error { Error::IO(err) } } impl From<bin::Error> for Error { fn from(err : bin::Error) -> Error { Error::Deserialization(err) } }
($dict:ty, $suffix:expr) => { impl Load for $dict { fn from_reader<R>(lang : Language, reader : &mut R) -> Result<Self>
random_line_split
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::{ContentType, Status}; fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T) where T: Into<Option<&'static str>> { let client = Client::new(rocket()).unwrap(); let query = format!("username={}&password={}&age={}", user, pass, age); let mut response = client.post("/login") .header(ContentType::Form) .body(&query) .dispatch(); assert_eq!(response.status(), status); if let Some(expected_str) = body.into() { let body_str = response.body_string(); assert!(body_str.map_or(false, |s| s.contains(expected_str))); } } #[test] fn test_good_login()
#[test] fn test_invalid_user() { test_login("-1", "password", "30", Status::Ok, "Unrecognized user"); test_login("Mike", "password", "30", Status::Ok, "Unrecognized user"); } #[test] fn test_invalid_password() { test_login("Sergio", "password1", "30", Status::Ok, "Wrong password!"); test_login("Sergio", "ok", "30", Status::Ok, "Password is invalid: too short!"); } #[test] fn test_invalid_age() { test_login("Sergio", "password", "20", Status::Ok, "must be at least 21."); test_login("Sergio", "password", "-100", Status::Ok, "must be at least 21."); test_login("Sergio", "password", "hi", Status::Ok, "value is not a number"); } fn check_bad_form(form_str: &str, status: Status) { let client = Client::new(rocket()).unwrap(); let response = client.post("/login") .header(ContentType::Form) .body(form_str) .dispatch(); assert_eq!(response.status(), status); } #[test] fn test_bad_form_abnromal_inputs() { check_bad_form("&", Status::BadRequest); check_bad_form("=", Status::BadRequest); check_bad_form("&&&===&", Status::BadRequest); } #[test] fn test_bad_form_missing_fields() { let bad_inputs: [&str; 6] = [ "username=Sergio", "password=pass", "age=30", "username=Sergio&password=pass", "username=Sergio&age=30", "password=pass&age=30" ]; for bad_input in bad_inputs.into_iter() { check_bad_form(bad_input, Status::UnprocessableEntity); } } #[test] fn test_bad_form_additional_fields() { check_bad_form("username=Sergio&password=pass&age=30&addition=1", Status::UnprocessableEntity); }
{ test_login("Sergio", "password", "30", Status::SeeOther, None); }
identifier_body
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::{ContentType, Status}; fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T) where T: Into<Option<&'static str>> { let client = Client::new(rocket()).unwrap(); let query = format!("username={}&password={}&age={}", user, pass, age); let mut response = client.post("/login") .header(ContentType::Form) .body(&query) .dispatch(); assert_eq!(response.status(), status); if let Some(expected_str) = body.into()
} #[test] fn test_good_login() { test_login("Sergio", "password", "30", Status::SeeOther, None); } #[test] fn test_invalid_user() { test_login("-1", "password", "30", Status::Ok, "Unrecognized user"); test_login("Mike", "password", "30", Status::Ok, "Unrecognized user"); } #[test] fn test_invalid_password() { test_login("Sergio", "password1", "30", Status::Ok, "Wrong password!"); test_login("Sergio", "ok", "30", Status::Ok, "Password is invalid: too short!"); } #[test] fn test_invalid_age() { test_login("Sergio", "password", "20", Status::Ok, "must be at least 21."); test_login("Sergio", "password", "-100", Status::Ok, "must be at least 21."); test_login("Sergio", "password", "hi", Status::Ok, "value is not a number"); } fn check_bad_form(form_str: &str, status: Status) { let client = Client::new(rocket()).unwrap(); let response = client.post("/login") .header(ContentType::Form) .body(form_str) .dispatch(); assert_eq!(response.status(), status); } #[test] fn test_bad_form_abnromal_inputs() { check_bad_form("&", Status::BadRequest); check_bad_form("=", Status::BadRequest); check_bad_form("&&&===&", Status::BadRequest); } #[test] fn test_bad_form_missing_fields() { let bad_inputs: [&str; 6] = [ "username=Sergio", "password=pass", "age=30", "username=Sergio&password=pass", "username=Sergio&age=30", "password=pass&age=30" ]; for bad_input in bad_inputs.into_iter() { check_bad_form(bad_input, Status::UnprocessableEntity); } } #[test] fn test_bad_form_additional_fields() { check_bad_form("username=Sergio&password=pass&age=30&addition=1", Status::UnprocessableEntity); }
{ let body_str = response.body_string(); assert!(body_str.map_or(false, |s| s.contains(expected_str))); }
conditional_block
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::{ContentType, Status}; fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T) where T: Into<Option<&'static str>> { let client = Client::new(rocket()).unwrap(); let query = format!("username={}&password={}&age={}", user, pass, age); let mut response = client.post("/login") .header(ContentType::Form) .body(&query) .dispatch(); assert_eq!(response.status(), status); if let Some(expected_str) = body.into() { let body_str = response.body_string(); assert!(body_str.map_or(false, |s| s.contains(expected_str))); } } #[test] fn test_good_login() { test_login("Sergio", "password", "30", Status::SeeOther, None); } #[test] fn test_invalid_user() { test_login("-1", "password", "30", Status::Ok, "Unrecognized user"); test_login("Mike", "password", "30", Status::Ok, "Unrecognized user"); } #[test] fn test_invalid_password() { test_login("Sergio", "password1", "30", Status::Ok, "Wrong password!"); test_login("Sergio", "ok", "30", Status::Ok, "Password is invalid: too short!"); } #[test] fn test_invalid_age() { test_login("Sergio", "password", "20", Status::Ok, "must be at least 21."); test_login("Sergio", "password", "-100", Status::Ok, "must be at least 21."); test_login("Sergio", "password", "hi", Status::Ok, "value is not a number"); } fn check_bad_form(form_str: &str, status: Status) { let client = Client::new(rocket()).unwrap(); let response = client.post("/login") .header(ContentType::Form) .body(form_str) .dispatch(); assert_eq!(response.status(), status); } #[test] fn
() { check_bad_form("&", Status::BadRequest); check_bad_form("=", Status::BadRequest); check_bad_form("&&&===&", Status::BadRequest); } #[test] fn test_bad_form_missing_fields() { let bad_inputs: [&str; 6] = [ "username=Sergio", "password=pass", "age=30", "username=Sergio&password=pass", "username=Sergio&age=30", "password=pass&age=30" ]; for bad_input in bad_inputs.into_iter() { check_bad_form(bad_input, Status::UnprocessableEntity); } } #[test] fn test_bad_form_additional_fields() { check_bad_form("username=Sergio&password=pass&age=30&addition=1", Status::UnprocessableEntity); }
test_bad_form_abnromal_inputs
identifier_name
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::{ContentType, Status}; fn test_login<T>(user: &str, pass: &str, age: &str, status: Status, body: T) where T: Into<Option<&'static str>> { let client = Client::new(rocket()).unwrap(); let query = format!("username={}&password={}&age={}", user, pass, age); let mut response = client.post("/login") .header(ContentType::Form) .body(&query) .dispatch(); assert_eq!(response.status(), status); if let Some(expected_str) = body.into() { let body_str = response.body_string(); assert!(body_str.map_or(false, |s| s.contains(expected_str))); } } #[test] fn test_good_login() { test_login("Sergio", "password", "30", Status::SeeOther, None); } #[test] fn test_invalid_user() { test_login("-1", "password", "30", Status::Ok, "Unrecognized user"); test_login("Mike", "password", "30", Status::Ok, "Unrecognized user"); } #[test] fn test_invalid_password() { test_login("Sergio", "password1", "30", Status::Ok, "Wrong password!"); test_login("Sergio", "ok", "30", Status::Ok, "Password is invalid: too short!"); } #[test] fn test_invalid_age() { test_login("Sergio", "password", "20", Status::Ok, "must be at least 21."); test_login("Sergio", "password", "-100", Status::Ok, "must be at least 21."); test_login("Sergio", "password", "hi", Status::Ok, "value is not a number"); } fn check_bad_form(form_str: &str, status: Status) { let client = Client::new(rocket()).unwrap(); let response = client.post("/login") .header(ContentType::Form) .body(form_str) .dispatch();
#[test] fn test_bad_form_abnromal_inputs() { check_bad_form("&", Status::BadRequest); check_bad_form("=", Status::BadRequest); check_bad_form("&&&===&", Status::BadRequest); } #[test] fn test_bad_form_missing_fields() { let bad_inputs: [&str; 6] = [ "username=Sergio", "password=pass", "age=30", "username=Sergio&password=pass", "username=Sergio&age=30", "password=pass&age=30" ]; for bad_input in bad_inputs.into_iter() { check_bad_form(bad_input, Status::UnprocessableEntity); } } #[test] fn test_bad_form_additional_fields() { check_bad_form("username=Sergio&password=pass&age=30&addition=1", Status::UnprocessableEntity); }
assert_eq!(response.status(), status); }
random_line_split
class-cast-to-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; trait noisy { fn speak(&self); } struct cat { priv meows : uint, how_hungry : int, name : ~str, } impl cat { pub fn eat(&self) -> bool { if self.how_hungry > 0
else { error!("Not hungry!"); return false; } } } impl noisy for cat { fn speak(&self) { self.meow(); } } impl cat { fn meow(&self) { error!("Meow"); self.meows += 1; if self.meows % 5 == 0 { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } fn main() { let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy; nyan.eat(); //~ ERROR does not implement any method in scope named `eat` }
{ error!("OM NOM NOM"); self.how_hungry -= 2; return true; }
conditional_block
class-cast-to-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; trait noisy { fn speak(&self); } struct cat { priv meows : uint, how_hungry : int, name : ~str, } impl cat { pub fn eat(&self) -> bool { if self.how_hungry > 0 { error!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { error!("Not hungry!"); return false; } } } impl noisy for cat { fn speak(&self) { self.meow(); } } impl cat { fn meow(&self)
} fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } fn main() { let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy; nyan.eat(); //~ ERROR does not implement any method in scope named `eat` }
{ error!("Meow"); self.meows += 1; if self.meows % 5 == 0 { self.how_hungry += 1; } }
identifier_body
class-cast-to-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; trait noisy { fn speak(&self); } struct cat { priv meows : uint, how_hungry : int, name : ~str, } impl cat { pub fn eat(&self) -> bool { if self.how_hungry > 0 { error!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { error!("Not hungry!"); return false; } } } impl noisy for cat { fn speak(&self) { self.meow(); } } impl cat { fn meow(&self) { error!("Meow"); self.meows += 1; if self.meows % 5 == 0 { self.how_hungry += 1; } } } fn
(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } fn main() { let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy; nyan.eat(); //~ ERROR does not implement any method in scope named `eat` }
cat
identifier_name
class-cast-to-trait.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #[feature(managed_boxes)]; trait noisy { fn speak(&self); } struct cat { priv meows : uint, how_hungry : int, name : ~str, } impl cat { pub fn eat(&self) -> bool { if self.how_hungry > 0 { error!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { error!("Not hungry!");
impl noisy for cat { fn speak(&self) { self.meow(); } } impl cat { fn meow(&self) { error!("Meow"); self.meows += 1; if self.meows % 5 == 0 { self.how_hungry += 1; } } } fn cat(in_x : uint, in_y : int, in_name: ~str) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } fn main() { let nyan : @noisy = @cat(0, 2, ~"nyan") as @noisy; nyan.eat(); //~ ERROR does not implement any method in scope named `eat` }
return false; } } }
random_line_split
cfg-macros-notfoo.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. // xfail-fast compile-flags directive doesn't work for check-fast // compile-flags: // check that cfg correctly chooses between the macro impls (see also // cfg-macros-foo.rs) #[cfg(foo)] #[macro_escape] mod foo { macro_rules! bar { () => { true } } } #[cfg(not(foo))] #[macro_escape] mod foo { macro_rules! bar { () => { false } } } fn main()
{ assert!(!bar!()) }
identifier_body
cfg-macros-notfoo.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. // xfail-fast compile-flags directive doesn't work for check-fast // compile-flags: // check that cfg correctly chooses between the macro impls (see also // cfg-macros-foo.rs) #[cfg(foo)] #[macro_escape] mod foo { macro_rules! bar { () => { true } } } #[cfg(not(foo))] #[macro_escape] mod foo { macro_rules! bar { () => { false } } } fn
() { assert!(!bar!()) }
main
identifier_name
cfg-macros-notfoo.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. // xfail-fast compile-flags directive doesn't work for check-fast // compile-flags: // check that cfg correctly chooses between the macro impls (see also // cfg-macros-foo.rs)
macro_rules! bar { () => { true } } } #[cfg(not(foo))] #[macro_escape] mod foo { macro_rules! bar { () => { false } } } fn main() { assert!(!bar!()) }
#[cfg(foo)] #[macro_escape] mod foo {
random_line_split