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
main.rs
// Copyright (C) 2015, Alberto Corona <ac@albertocorona.com> // All rights reserved. This file is part of core-utils, distributed under the // GPL v3 license. For full terms please see the LICENSE file. #![crate_type = "bin"] #![crate_name = "nproc"] static UTIL: Prog = Prog { name: "nproc", vers: "0.1.0", yr: "2015"...
(opts: Options) { print!("{}: {} {}", UTIL.name.bold(), "Usage".bold(), "[OPTION]".underline()); println!("{}", opts.options()); } fn main() { let args: Vec<String> = env::args().collect(); let mut opts = Options::new(); opts.optflag("h", "help", "Print help information"); opts.optflag("", "ve...
print_usage
identifier_name
main.rs
// Copyright (C) 2015, Alberto Corona <ac@albertocorona.com> // All rights reserved. This file is part of core-utils, distributed under the // GPL v3 license. For full terms please see the LICENSE file. #![crate_type = "bin"] #![crate_name = "nproc"] static UTIL: Prog = Prog { name: "nproc", vers: "0.1.0", yr: "2015"...
else { println!("{}", num - ignore); } } else { println!("{}", num); } }
{ println!("0"); }
conditional_block
main.rs
// Copyright (C) 2015, Alberto Corona <ac@albertocorona.com> // All rights reserved. This file is part of core-utils, distributed under the // GPL v3 license. For full terms please see the LICENSE file. #![crate_type = "bin"] #![crate_name = "nproc"] static UTIL: Prog = Prog { name: "nproc", vers: "0.1.0", yr: "2015"...
}; if ignore > num { println!("0"); } else { println!("{}", num - ignore); } } else { println!("{}", num); } }
&["Alberto Corona"]); } else if matches.opt_present("i") { let ignore = match matches.opts_str(&[String::from("i")]) { Some(s) => { s.parse::<u32>().unwrap_or(0) }, None => { panic!() },
random_line_split
main.rs
// Copyright (C) 2015, Alberto Corona <ac@albertocorona.com> // All rights reserved. This file is part of core-utils, distributed under the // GPL v3 license. For full terms please see the LICENSE file. #![crate_type = "bin"] #![crate_name = "nproc"] static UTIL: Prog = Prog { name: "nproc", vers: "0.1.0", yr: "2015"...
UTIL.copyright("Copyright (C) 2015 core-utils developers\n\ License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n\ This is free software: you are free to change and redistribute it.\n\ There is NO WARRANTY, to the ex...
{ let args: Vec<String> = env::args().collect(); let mut opts = Options::new(); opts.optflag("h", "help", "Print help information"); opts.optflag("", "version", "Print version information"); opts.optopt("i", "ignore", "Number of processing units to ignore", "NUM"); let matches = match opts.par...
identifier_body
song_map.rs
use radio::song::Song; use serde_json; use std::collections::HashMap; use std::fs::File; use std::fs; use std::io::prelude::*; use std::io::{BufReader, BufWriter}; use util::logger::log; /// A map containing songs and their times played, /// Inserting a song already known will increase its counter #[derive(Debug)] pub...
// Write json to file match serde_json::to_writer_pretty(&mut to, &string_vec) { Err(_) => { save_error(dir, name); return } _ => {}, } // Add a newline, otherwise the json might be invalid let _ = to.write(b"\n"...
random_line_split
song_map.rs
use radio::song::Song; use serde_json; use std::collections::HashMap; use std::fs::File; use std::fs; use std::io::prelude::*; use std::io::{BufReader, BufWriter}; use util::logger::log; /// A map containing songs and their times played, /// Inserting a song already known will increase its counter #[derive(Debug)] pub...
(dir: &str, name: &'static str) -> Self { /// Logs possible errors fn load_error(dir: &str, name: &'static str) { log(&format!("ERROR: Could not load {}\\{}.json",dir, name)); } // Create an empty map let mut song_map = SongMap::new(); // Try to open ...
load_from_file
identifier_name
song_map.rs
use radio::song::Song; use serde_json; use std::collections::HashMap; use std::fs::File; use std::fs; use std::io::prelude::*; use std::io::{BufReader, BufWriter}; use util::logger::log; /// A map containing songs and their times played, /// Inserting a song already known will increase its counter #[derive(Debug)] pub...
/// Inserts a song into the map fn insert(&mut self, key: Song, value: u16) { self.0.insert(key, value); } /// Inserts a song into the map /// If known increases its counter instead pub fn insert_song(&mut self, song: Song) { let counter = self.0.entry(song).or_insert(0); ...
{ SongMap(HashMap::new()) }
identifier_body
lib.rs
pub extern crate piston_window; mod printer; pub use printer::*; pub mod colors; #[cfg(test)] extern crate float_cmp; #[cfg(test)] use float_cmp::ApproxEqUlps; #[cfg(test)] /// Check if two floats are approximately equal macro_rules! assert_float_eq { ($left: expr, $right: expr, $precision: expr) => { ...
assert_color_eq!([0.15, 0.3, 0.45, 1.0], lighter(color, 0.5, false)); }
random_line_split
lib.rs
pub extern crate piston_window; mod printer; pub use printer::*; pub mod colors; #[cfg(test)] extern crate float_cmp; #[cfg(test)] use float_cmp::ApproxEqUlps; #[cfg(test)] /// Check if two floats are approximately equal macro_rules! assert_float_eq { ($left: expr, $right: expr, $precision: expr) => { ...
#[test] fn test_lighter() { use colors::lighter; let color = [0.3, 0.6, 0.9, 1.0]; assert_color_eq!([0.15, 0.3, 0.45, 0.5], lighter(color, 0.5, true)); assert_color_eq!([0.15, 0.3, 0.45, 1.0], lighter(color, 0.5, false)); }
{ use colors::darker; let color = [0.3, 0.6, 0.9, 1.0]; assert_color_eq!([0.45, 0.9, 1.0, 1.0], darker(color, 0.5, true)); assert_color_eq!([0.45, 0.9, 1.0, 1.0], darker(color, 0.5, false)); }
identifier_body
lib.rs
pub extern crate piston_window; mod printer; pub use printer::*; pub mod colors; #[cfg(test)] extern crate float_cmp; #[cfg(test)] use float_cmp::ApproxEqUlps; #[cfg(test)] /// Check if two floats are approximately equal macro_rules! assert_float_eq { ($left: expr, $right: expr, $precision: expr) => { ...
() { use colors::lighter; let color = [0.3, 0.6, 0.9, 1.0]; assert_color_eq!([0.15, 0.3, 0.45, 0.5], lighter(color, 0.5, true)); assert_color_eq!([0.15, 0.3, 0.45, 1.0], lighter(color, 0.5, false)); }
test_lighter
identifier_name
lib.rs
//! This crate provides an interface, `Shifter` that makes it trivially easy to //! manipulate [shift registers][4] with a Raspberry Pi (thanks to [CuPi][1]). //! Internally it keeps track of each shift register's state, allowing you to //! manipulate each pin individually as if it were a regular GPIO pin! //! //! Why ...
self.clock.high().unwrap(); } } self.latch.high().unwrap(); } } #[cfg(test)] mod tests { #[test] fn it_works() { } }
{ match sr.data >> n & 1 { 0 => self.data.low().unwrap(), 1 => self.data.high().unwrap(), _ => unreachable!(), } }
conditional_block
lib.rs
//! This crate provides an interface, `Shifter` that makes it trivially easy to //! manipulate [shift registers][4] with a Raspberry Pi (thanks to [CuPi][1]). //! Internally it keeps track of each shift register's state, allowing you to //! manipulate each pin individually as if it were a regular GPIO pin! //! //! Why ...
() { } }
it_works
identifier_name
lib.rs
//! This crate provides an interface, `Shifter` that makes it trivially easy to //! manipulate [shift registers][4] with a Raspberry Pi (thanks to [CuPi][1]). //! Internally it keeps track of each shift register's state, allowing you to //! manipulate each pin individually as if it were a regular GPIO pin! //! //! Why ...
#![allow(dead_code, unused_variables)] extern crate cupi; // Using a singly-linked list to represent the chain of shift registers since // it accurately represents how they're physically linked together. use std::collections::LinkedList; use std::cell::RefCell; use cupi::{CuPi, PinOutput, DigitalWrite}; struct Shif...
//! [2]: https://www.adafruit.com/product/732 //! [3]: https://www.sparkfun.com/datasheets/IC/SN74HC595.pdf //! [4]: https://en.wikipedia.org/wiki/Shift_register
random_line_split
lib.rs
//! This crate provides an interface, `Shifter` that makes it trivially easy to //! manipulate [shift registers][4] with a Raspberry Pi (thanks to [CuPi][1]). //! Internally it keeps track of each shift register's state, allowing you to //! manipulate each pin individually as if it were a regular GPIO pin! //! //! Why ...
} self.latch.high().unwrap(); } } #[cfg(test)] mod tests { #[test] fn it_works() { } }
{ self.latch.low().unwrap(); for sr in self.shift_registers.iter() { for n in 0..sr.pins { self.clock.low().unwrap(); if self.invert { match sr.data >> n & 1 { 1 => self.data.low().unwrap(), 0...
identifier_body
coherence-tuple-conflict.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 ...
(&self) -> usize { self.dummy } } fn main() { }
get
identifier_name
coherence-tuple-conflict.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
use std::fmt::Debug; use std::default::Default; // Test that a blank impl for all T conflicts with an impl for some // specific T. trait MyTrait { fn get(&self) -> usize; } impl<T> MyTrait for (T,T) { //~ ERROR E0119 fn get(&self) -> usize { 0 } } impl<A,B> MyTrait for (A,B) { fn get(&self) -> usize { s...
// 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.
random_line_split
coherence-tuple-conflict.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 ...
{ }
identifier_body
main.rs
extern crate curl; extern crate tokio_core; extern crate tokio_curl; extern crate fibers; extern crate futures; extern crate futures_cpupool; use std::io::{self, Write, BufWriter}; use curl::easy::Easy; use futures::future::*; use std::fs::File; use futures_cpupool::CpuPool; use std::sync::{Mutex, Arc}; use futures::{...
fn collect_request(x: i32, url: &str, sess: &Session) -> FutureResult<Perform, ()> { let mut data = Vec::new(); let mut easy = Easy::new(); easy.get(true).unwrap(); easy.url("https://www.rust-lang.org").unwrap(); easy.write_function(|data| Ok(data.len())).unwrap(); make_file(x, &mut data); ...
{ let f = File::create(format!("./data/{}.txt", x)).expect("Unable to open file"); let mut writer = BufWriter::new(&f); writer.write_all(data.as_mut_slice()).unwrap(); data.len() }
identifier_body
main.rs
extern crate curl; extern crate tokio_core; extern crate tokio_curl; extern crate fibers; extern crate futures; extern crate futures_cpupool; use std::io::{self, Write, BufWriter}; use curl::easy::Easy; use futures::future::*; use std::fs::File; use futures_cpupool::CpuPool; use std::sync::{Mutex, Arc}; use futures::{...
let session = Session::new(handle); let requests = (0..20).into_iter().map(|x| { pool.spawn(collect_request(x, url, &session)) }); let performed = futures_unordered(requests).into_future(); } // let out = requests.into_stream().wait();
let url = "https://en.wikipedia.org/wiki/Immanuel_Kant"; let mut core = Core::new().unwrap(); let handle = core.handle(); let pool = CpuPool::new_num_cpus();
random_line_split
main.rs
extern crate curl; extern crate tokio_core; extern crate tokio_curl; extern crate fibers; extern crate futures; extern crate futures_cpupool; use std::io::{self, Write, BufWriter}; use curl::easy::Easy; use futures::future::*; use std::fs::File; use futures_cpupool::CpuPool; use std::sync::{Mutex, Arc}; use futures::{...
() { let url = "https://en.wikipedia.org/wiki/Immanuel_Kant"; let mut core = Core::new().unwrap(); let handle = core.handle(); let pool = CpuPool::new_num_cpus(); let session = Session::new(handle); let requests = (0..20).into_iter().map(|x| { pool.spawn(collect_request(x, url, &sessio...
main
identifier_name
mod.rs
// Copyright (c) 2015 Daniel Grunwald // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publis...
fn type_object(py: ::python::Python) -> ::objects::typeobject::PyType { unsafe { ::objects::typeobject::PyType::from_type_ptr(py, &mut ::ffi::$typeobject) } } } ); ); macro_rules! extract( ($obj:ident to $t:ty; $py:ident => $body: block) => { impl <'sourc...
($name: ident, $checkfunction: ident, $typeobject: ident) => ( pyobject_newtype!($name, $checkfunction); impl ::python::PythonObjectWithTypeObject for $name { #[inline]
random_line_split
simple.rs
extern crate readline as rl; extern crate libc; use std::io::{BufRead,BufReader}; use std::fs::File; use std::path::Path; use std::ffi::CStr; use std::str; fn
(text: String) -> Vec<String> { let path = Path::new("/usr/share/dict/words"); let file = BufReader::new(File::open(&path).unwrap()); let mut entries: Vec<String> = Vec::new(); for line in file.lines() { let word = line.unwrap(); if (&word).starts_with(&text) { entries.push(w...
complete
identifier_name
simple.rs
extern crate readline as rl; extern crate libc; use std::io::{BufRead,BufReader}; use std::fs::File; use std::path::Path; use std::ffi::CStr; use std::str; fn complete(text: String) -> Vec<String> { let path = Path::new("/usr/share/dict/words"); let file = BufReader::new(File::open(&path).unwrap()); let m...
println!(""); break } } } }
println!("{}", l); //println!("{}", rl::history_get(-2)); }, _ => {
random_line_split
simple.rs
extern crate readline as rl; extern crate libc; use std::io::{BufRead,BufReader}; use std::fs::File; use std::path::Path; use std::ffi::CStr; use std::str; fn complete(text: String) -> Vec<String> { let path = Path::new("/usr/share/dict/words"); let file = BufReader::new(File::open(&path).unwrap()); let m...
} return entries; } extern fn rl_compentry_func(text: *const i8, state: i32) -> *const i8 { if state == 0 { let txt = unsafe { CStr::from_ptr(text).to_bytes() }; let entries = complete(str::from_utf8(txt).unwrap().to_string()); rl::set_compentries(entries); } rl::get_compen...
{ entries.push(word); }
conditional_block
simple.rs
extern crate readline as rl; extern crate libc; use std::io::{BufRead,BufReader}; use std::fs::File; use std::path::Path; use std::ffi::CStr; use std::str; fn complete(text: String) -> Vec<String> { let path = Path::new("/usr/share/dict/words"); let file = BufReader::new(File::open(&path).unwrap()); let m...
} }
{ rl::rl_initialize().unwrap(); //println!("{}", rl::rl_readline_version()) println!("{}", rl::rl_library_version()); rl::set_rl_attempted_completion_function(Some(my_attempted_completion_function)); loop { match rl::readline("> ") { Some(line) => { let l = line...
identifier_body
template.rs
use handlebars::Handlebars; use std::path::{Path, PathBuf}; use glob::glob; use std::sync::Mutex; use itertools::Itertools; use std::error::Error; use std::borrow::Cow; use serde_json::{Value, to_value}; use rocket::response::{Responder, Response}; use rocket::request::Request; use rocket::http::ContentType; use rocket...
} impl Responder<'static> for Template { fn respond_to(self, _: &Request) -> Result<Response<'static>, Status> { let hb = HANDLEBARS.lock().unwrap(); let render = hb.render(&self.name, &self.value).unwrap_or_else(|e| e.to_string()); Response::build() .header(ContentType::HTML) ...
{ Template { name: name.into(), value: to_value(context).ok(), } }
identifier_body
template.rs
use handlebars::Handlebars; use std::path::{Path, PathBuf}; use glob::glob; use std::sync::Mutex; use itertools::Itertools; use std::error::Error; use std::borrow::Cow; use serde_json::{Value, to_value}; use rocket::response::{Responder, Response}; use rocket::request::Request; use rocket::http::ContentType; use rocket...
else { c })) .collect(); println!("{}", &name); if let Err(e) = hb.register_template_file(&name, &entry) { // TODO: make correct error loagging println!("{} {}", &name, &e); error!("Error in Handlebars template {}", &name); info!("{}", e); ...
{ '/' }
conditional_block
template.rs
use handlebars::Handlebars; use std::path::{Path, PathBuf}; use glob::glob; use std::sync::Mutex; use itertools::Itertools; use std::error::Error; use std::borrow::Cow; use serde_json::{Value, to_value}; use rocket::response::{Responder, Response}; use rocket::request::Request; use rocket::http::ContentType; use rocket...
(self, _: &Request) -> Result<Response<'static>, Status> { let hb = HANDLEBARS.lock().unwrap(); let render = hb.render(&self.name, &self.value).unwrap_or_else(|e| e.to_string()); Response::build() .header(ContentType::HTML) .sized_body(Cursor::new(render)) .ok() ...
respond_to
identifier_name
template.rs
use handlebars::Handlebars; use std::path::{Path, PathBuf}; use glob::glob; use std::sync::Mutex;
use itertools::Itertools; use std::error::Error; use std::borrow::Cow; use serde_json::{Value, to_value}; use rocket::response::{Responder, Response}; use rocket::request::Request; use rocket::http::ContentType; use rocket::http::Status; use serde::ser::Serialize; use std::io::Cursor; #[derive(Debug)] pub struct Templ...
random_line_split
handler.rs
use Rpc; use std::{fmt, mem, str}; use std::sync::Arc; use hyper::{self, mime, server, Method}; use hyper::header::{self, Headers}; use unicase::Ascii; use jsonrpc::{self as core, FutureResult, Metadata, Middleware, NoopMiddleware}; use jsonrpc::futures::{Future, Poll, Async, Stream, future}; use jsonrpc::serde_json...
( &self, request: server::Request, continue_on_invalid_cors: bool, ) -> RpcHandlerState<M, S::Future> { if self.cors_header == cors::CorsHeader::Invalid &&!continue_on_invalid_cors { return RpcHandlerState::Writing(Response::invalid_cors()); } // Read metadata let metadata = self.jsonrpc_handler.extra...
read_headers
identifier_name
handler.rs
use Rpc; use std::{fmt, mem, str}; use std::sync::Arc; use hyper::{self, mime, server, Method}; use hyper::header::{self, Headers}; use unicase::Ascii; use jsonrpc::{self as core, FutureResult, Metadata, Middleware, NoopMiddleware}; use jsonrpc::futures::{Future, Poll, Async, Stream, future}; use jsonrpc::serde_json...
self.process_rest(uri, metadata)? }, RpcHandlerState::Waiting(mut waiting) => { match waiting.poll() { Ok(Async::Ready(response)) => { RpcPollState::Ready(RpcHandlerState::Writing(match response { // Notification, just return empty response. None => Response::ok(String::new()), ...
}, RpcHandlerState::ProcessRest { uri, metadata } => {
random_line_split
custom_error_handler.rs
#[macro_use] extern crate nickel; use std::io::Write; use nickel::{Nickel, NickelError, Request, HttpRouter, Action}; use nickel::status::StatusCode; fn main()
match res.status() { StatusCode::ImATeapot => { // Pass the internal message to the client let _ = res.write_all(err.message.as_bytes()); return Action::Halt(()) } StatusCode::NotFound => { ...
{ let mut server = Nickel::new(); // go to http://localhost:6767/user/4711 to see this route in action server.get("/user/:userid", middleware! { |request| if let Some("42") = request.param("userid") { (StatusCode::Ok, "User 42 was found!") } else { (StatusCode::ImATe...
identifier_body
custom_error_handler.rs
#[macro_use] extern crate nickel; use std::io::Write; use nickel::{Nickel, NickelError, Request, HttpRouter, Action}; use nickel::status::StatusCode; fn main() { let mut server = Nickel::new(); // go to http://localhost:6767/user/4711 to see this route in action server.get("/user/:userid", middleware! { ...
_ => {} } } // Fall through to next error handler Action::Continue(()) } // issue #20178 let custom_handler: fn(&mut NickelError<()>, &mut Request<()>) -> Action = custom_handler; server.handle_error(custom_handler); server.listen("127.0.0.1:6...
{ let _ = res.write_all(b"<h1>404 - Not Found</h1>"); return Action::Halt(()) }
conditional_block
custom_error_handler.rs
#[macro_use] extern crate nickel; use std::io::Write; use nickel::{Nickel, NickelError, Request, HttpRouter, Action}; use nickel::status::StatusCode; fn main() { let mut server = Nickel::new(); // go to http://localhost:6767/user/4711 to see this route in action server.get("/user/:userid", middleware! { ...
<D>(err: &mut NickelError<D>, req: &mut Request<D>) -> Action { // Print the internal error message and path to the console println!("[{}] ERROR: {}", req.path_without_query().unwrap(), err.message); if let Some(ref mut res) = err.stream { match res...
custom_handler
identifier_name
custom_error_handler.rs
#[macro_use] extern crate nickel; use std::io::Write; use nickel::{Nickel, NickelError, Request, HttpRouter, Action}; use nickel::status::StatusCode; fn main() { let mut server = Nickel::new(); // go to http://localhost:6767/user/4711 to see this route in action server.get("/user/:userid", middleware! { ...
match res.status() { StatusCode::ImATeapot => { // Pass the internal message to the client let _ = res.write_all(err.message.as_bytes()); return Action::Halt(()) } StatusCode::NotFound => { ...
req.path_without_query().unwrap(), err.message); if let Some(ref mut res) = err.stream {
random_line_split
mod.rs
//! Provides the fundamental units of computation for the [Network][1]. //! [1]:../network/index.html //! //! These layers provide different type of operations to the data Blobs #[allow(unused_import_braces)] pub use blocks::neural::neuron::*; pub use core::*; pub mod neural; pub mod fullmesh; pub mod mesh;
pub mod function; #[cfg(test)] mod block_tst; #[derive(Default, Clone)] pub struct BlockData { pub id: BlockId, pub name: String, pub connections: Vec<Connection>, pub next_run_sequence: Vec<BlockId>, pub neuron_count: u32, /// includes bias per neuron pub synapse_count: u32 } impl Blo...
random_line_split
mod.rs
//! Provides the fundamental units of computation for the [Network][1]. //! [1]:../network/index.html //! //! These layers provide different type of operations to the data Blobs #[allow(unused_import_braces)] pub use blocks::neural::neuron::*; pub use core::*; pub mod neural; pub mod fullmesh; pub mod mesh; pub mod f...
(newid: BlockId, ncount: u32, scount: u32) -> BlockData { BlockData { id : newid, neuron_count: ncount, synapse_count: scount,..Default::default() } } } pub fn add_three(a: i32) -> i32 { a + 3 } // revist names pub type LinearByteMutBlock = ::blocks::fullmesh::FullMeshBlock<i8,u8,LinearByteB>; pub type Logistic...
new
identifier_name
tty.rs
use std::{fs, io}; use std::os::unix::io::AsRawFd; /// Is this stream an TTY? #[cfg(not(target_os = "redox"))] pub fn is_tty<T: AsRawFd>(stream: &T) -> bool { use libc; unsafe { libc::isatty(stream.as_raw_fd()) == 1 } } /// This will panic. #[cfg(target_os = "redox")] pub fn is_tty<T: AsRawFd>(_stream: &T) -...
/// Get the TTY device. /// /// This allows for getting stdio representing _only_ the TTY, and not other streams. #[cfg(target_os = "redox")] pub fn get_tty() -> io::Result<fs::File> { use std::env; let tty = try!(env::var("TTY").map_err(|x| io::Error::new(io::ErrorKind::NotFound, x))); fs::OpenOptions::n...
{ unimplemented!(); }
identifier_body
tty.rs
use std::{fs, io}; use std::os::unix::io::AsRawFd; /// Is this stream an TTY? #[cfg(not(target_os = "redox"))] pub fn is_tty<T: AsRawFd>(stream: &T) -> bool { use libc; unsafe { libc::isatty(stream.as_raw_fd()) == 1 } } /// This will panic. #[cfg(target_os = "redox")] pub fn is_tty<T: AsRawFd>(_stream: &T) -...
() -> io::Result<fs::File> { use std::env; let tty = try!(env::var("TTY").map_err(|x| io::Error::new(io::ErrorKind::NotFound, x))); fs::OpenOptions::new().read(true).write(true).open(tty) } /// Get the TTY device. /// /// This allows for getting stdio representing _only_ the TTY, and not other streams. #[c...
get_tty
identifier_name
tty.rs
use std::{fs, io}; use std::os::unix::io::AsRawFd; /// Is this stream an TTY? #[cfg(not(target_os = "redox"))] pub fn is_tty<T: AsRawFd>(stream: &T) -> bool { use libc; unsafe { libc::isatty(stream.as_raw_fd()) == 1 } } /// This will panic. #[cfg(target_os = "redox")] pub fn is_tty<T: AsRawFd>(_stream: &T) -...
#[cfg(target_os = "redox")] pub fn get_tty() -> io::Result<fs::File> { use std::env; let tty = try!(env::var("TTY").map_err(|x| io::Error::new(io::ErrorKind::NotFound, x))); fs::OpenOptions::new().read(true).write(true).open(tty) } /// Get the TTY device. /// /// This allows for getting stdio representing ...
/// This allows for getting stdio representing _only_ the TTY, and not other streams.
random_line_split
lib.rs
//! A TIS-100 emulator. //! //! # Example //! //! ``` //! use tis_100::save::parse_save; //! use tis_100::machine::Sandbox; //! //! // This program reads the value from the console and simply passes it to the console output. //! let src = "@1\nMOV UP DOWN\n@5\nMOV UP DOWN\n@9\nMOV UP RIGHT\n@10\nMOV LEFT DOWN\n"; //! /...
pub mod lex; pub mod parse; pub mod io; pub mod node; pub mod image; pub mod save; pub mod spec; pub mod machine;
extern crate vec_map; pub mod core;
random_line_split
lazy_cell.rs
//! A lazily fill Cell, but with frozen contents. //! //! With a `RefCell`, the inner contents cannot be borrowed for the lifetime of //! the entire object, but only of the borrows returned. A `LazyCell` is a //! variation on `RefCell` which allows borrows tied to the lifetime of the //! outer object. //! //! The limit...
() -> LazyCell<T> { LazyCell { inner: RefCell::new(None) } } /// Put a value into this cell. /// /// This function will fail if the cell has already been filled. pub fn fill(&self, t: T) { let mut slot = self.inner.borrow_mut(); if slot.is_some() { panic!("lazy c...
new
identifier_name
lazy_cell.rs
//! A lazily fill Cell, but with frozen contents. //! //! With a `RefCell`, the inner contents cannot be borrowed for the lifetime of //! the entire object, but only of the borrows returned. A `LazyCell` is a //! variation on `RefCell` which allows borrows tied to the lifetime of the //! outer object. //! //! The limit...
/// /// This function will fail if the cell has already been filled. pub fn fill(&self, t: T) { let mut slot = self.inner.borrow_mut(); if slot.is_some() { panic!("lazy cell is already filled") } *slot = Some(t); } /// Test whether this cell has been prev...
LazyCell { inner: RefCell::new(None) } } /// Put a value into this cell.
random_line_split
murmurhash.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. *
const C1: u32 = 0xcc9e_2d51; const C2: u32 = 0x1b87_3593; const R1: u32 = 15; const R2: u32 = 13; const M: u32 = 5; const N: u32 = 0xe654_6b64; const CHARSET: [char; 62] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l','m', 'n', 'o', 'p', 'q', 'r'...
* This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::ptr::copy_nonoverlapping;
random_line_split
murmurhash.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::ptr::copy_nonoverlapping; const C1: u32 = 0xcc9e_2d51; const C2: u32 = 0x1b87_3593; const R1: u32 = 15; const R2: u32 =...
3 => { hash ^= calculate_k( (bytes[i] as u32) | ((bytes[i + 1] as u32) << 8) | ((bytes[i + 2] as u32) << 16), ); } _ => {} } hash ^= nbytes as u32; hash ^= hash.wrapping_shr(16); hash = hash.wrapping_mul(0x85eb_ca6b); hash ^= hash.wra...
{ hash ^= calculate_k((bytes[i] as u32) | ((bytes[i + 1] as u32) << 8)); }
conditional_block
murmurhash.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::ptr::copy_nonoverlapping; const C1: u32 = 0xcc9e_2d51; const C2: u32 = 0x1b87_3593; const R1: u32 = 15; const R2: u32 =...
{ assert_eq!(murmurhash("{count: 20, start: 0, end: 5}"), "31sjku"); assert_eq!( murmurhash("{arg: \"{arg: {count: 20, start: 0, end: 5}}\"}"), "3RGiWM" ); assert_eq!( murmurhash(&str::repeat( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", ...
identifier_body
murmurhash.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use std::ptr::copy_nonoverlapping; const C1: u32 = 0xcc9e_2d51; const C2: u32 = 0x1b87_3593; const R1: u32 = 15; const R2: u32 =...
(src: &[u8]) -> u32 { let mut data: u32 = 0; unsafe { copy_nonoverlapping(src.as_ptr(), &mut data as *mut u32 as *mut u8, 4); } data.to_le() } fn calculate_k(k: u32) -> u32 { k.wrapping_mul(C1).rotate_left(R1).wrapping_mul(C2) } #[test] fn test_murmurhash() { assert_eq!(murmurhash("{co...
read_u32
identifier_name
test_fixture.rs
use crate::cpu::Cpu; use crate::cpu::{Interconnect, Interrupt, ADDRESSABLE_MEMORY}; pub struct TestInterconnect { addr: [u8; ADDRESSABLE_MEMORY], elapsed_cycles: usize, } impl TestInterconnect { pub fn new() -> Self { TestInterconnect { addr: [0; ADDRESSABLE_MEMORY], elaps...
fn default() -> Self { Self::new() } } impl Interconnect for TestInterconnect { fn read(&self, addr: u16) -> u8 { let addr = addr as usize; self.addr[addr] } fn write(&mut self, addr: u16, data: u8) { let addr = addr as usize; self.addr[addr] = data; } ...
impl Default for TestInterconnect {
random_line_split
test_fixture.rs
use crate::cpu::Cpu; use crate::cpu::{Interconnect, Interrupt, ADDRESSABLE_MEMORY}; pub struct TestInterconnect { addr: [u8; ADDRESSABLE_MEMORY], elapsed_cycles: usize, } impl TestInterconnect { pub fn new() -> Self
pub fn store_many(&mut self, addr: u16, data: &[u8]) { for (i, byte) in data.iter().enumerate() { self.write(addr + i as u16, *byte); } } } impl Default for TestInterconnect { fn default() -> Self { Self::new() } } impl Interconnect for TestInterconnect { fn r...
{ TestInterconnect { addr: [0; ADDRESSABLE_MEMORY], elapsed_cycles: 0, } }
identifier_body
test_fixture.rs
use crate::cpu::Cpu; use crate::cpu::{Interconnect, Interrupt, ADDRESSABLE_MEMORY}; pub struct
{ addr: [u8; ADDRESSABLE_MEMORY], elapsed_cycles: usize, } impl TestInterconnect { pub fn new() -> Self { TestInterconnect { addr: [0; ADDRESSABLE_MEMORY], elapsed_cycles: 0, } } pub fn store_many(&mut self, addr: u16, data: &[u8]) { for (i, byte) i...
TestInterconnect
identifier_name
hud.rs
// HUD window extern crate piston_window; extern crate engine; use piston_window::{Context, Transformed, text, Event}; use super::{WindowBase, PostAction, States}; use super::Resources; use engine::Engine; use opengl_graphics::GlGraphics; use std::rc::Rc; use std::cell::{RefCell, Cell}; pub struct HUDWindow { ...
(resources: Rc<RefCell<Resources>>, engine: Rc<RefCell<Engine>>) -> HUDWindow { HUDWindow { resources: resources, engine: engine } } } impl WindowBase for HUDWindow { fn paint(&mut self, c: Context, g: &mut GlGraphics) { text(super::GREEN, 15, &f...
new
identifier_name
hud.rs
// HUD window extern crate piston_window; extern crate engine; use piston_window::{Context, Transformed, text, Event}; use super::{WindowBase, PostAction, States}; use super::Resources; use engine::Engine; use opengl_graphics::GlGraphics; use std::rc::Rc; use std::cell::{RefCell, Cell}; pub struct HUDWindow { ...
text(super::GREEN, 15, &format!("population {}", self.engine.borrow().get_board().get_population()), &mut self.resources.borrow_mut().font, c.trans(150.0, 20.0).transform, g); text(super::GREEN, 15, &format!("update time {:.*}", 5, self.engine.borrow(...
random_line_split
hud.rs
// HUD window extern crate piston_window; extern crate engine; use piston_window::{Context, Transformed, text, Event}; use super::{WindowBase, PostAction, States}; use super::Resources; use engine::Engine; use opengl_graphics::GlGraphics; use std::rc::Rc; use std::cell::{RefCell, Cell}; pub struct HUDWindow { ...
} impl WindowBase for HUDWindow { fn paint(&mut self, c: Context, g: &mut GlGraphics) { text(super::GREEN, 15, &format!("generation {}", self.engine.borrow().cur_iteration()), &mut self.resources.borrow_mut().font, c.trans(10.0, 20.0).transform, g); text(s...
{ HUDWindow { resources: resources, engine: engine } }
identifier_body
urlsearchparams.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::cell::DOMRefCell; use dom::bindings::codegen::Bindings::URLSearchParamsBinding; use dom::bindin...
impl URLSearchParams { fn new_inherited() -> URLSearchParams { URLSearchParams { reflector_: Reflector::new(), data: DOMRefCell::new(HashMap::new()), } } pub fn new(global: GlobalRef) -> Temporary<URLSearchParams> { reflect_dom_object(box URLSearchParams::new...
reflector_: Reflector, data: DOMRefCell<HashMap<DOMString, Vec<DOMString>>>, }
random_line_split
urlsearchparams.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::cell::DOMRefCell; use dom::bindings::codegen::Bindings::URLSearchParamsBinding; use dom::bindin...
, None => {} } Ok(Temporary::from_rooted(usp.r())) } } impl<'a> URLSearchParamsMethods for JSRef<'a, URLSearchParams> { fn Append(self, name: DOMString, value: DOMString) { let mut data = self.data.borrow_mut(); match data.entry(name) { Occupied(entry) =...
{ let u = u.root(); let usp = usp.r(); let mut map = usp.data.borrow_mut(); // FIXME(https://github.com/rust-lang/rust/issues/23338) let r = u.r(); let data = r.data.borrow(); *map = data.clone(); ...
conditional_block
urlsearchparams.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::cell::DOMRefCell; use dom::bindings::codegen::Bindings::URLSearchParamsBinding; use dom::bindin...
(self, name: DOMString, value: DOMString) { let mut data = self.data.borrow_mut(); match data.entry(name) { Occupied(entry) => entry.into_mut().push(value), Vacant(entry) => { entry.insert(vec!(value)); } } self.update_steps(); } ...
Append
identifier_name
urlsearchparams.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::cell::DOMRefCell; use dom::bindings::codegen::Bindings::URLSearchParamsBinding; use dom::bindin...
}
{ // XXXManishearth Implement this when the URL interface is implemented // http://url.spec.whatwg.org/#concept-uq-update }
identifier_body
window_run_return.rs
// Limit this example to only compatible platforms. #[cfg(any( target_os = "windows", target_os = "macos", target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] fn
() { use std::{thread::sleep, time::Duration}; use simple_logger::SimpleLogger; use winit::{ event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, platform::run_return::EventLoopExtRunReturn, window::WindowBuilder, }; let mut event_loop = EventLoop::new(...
main
identifier_name
window_run_return.rs
// Limit this example to only compatible platforms. #[cfg(any( target_os = "windows", target_os = "macos", target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] fn main()
while!quit { event_loop.run_return(|event, _, control_flow| { *control_flow = ControlFlow::Wait; if let Event::WindowEvent { event,.. } = &event { // Print only Window events to reduce noise println!("{:?}", event); } match ev...
{ use std::{thread::sleep, time::Duration}; use simple_logger::SimpleLogger; use winit::{ event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, platform::run_return::EventLoopExtRunReturn, window::WindowBuilder, }; let mut event_loop = EventLoop::new(); ...
identifier_body
window_run_return.rs
// Limit this example to only compatible platforms. #[cfg(any( target_os = "windows", target_os = "macos", target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] fn main() { use std::{thread::sleep, time::Duration}; use s...
event::{Event, WindowEvent}, event_loop::{ControlFlow, EventLoop}, platform::run_return::EventLoopExtRunReturn, window::WindowBuilder, }; let mut event_loop = EventLoop::new(); SimpleLogger::new().init().unwrap(); let _window = WindowBuilder::new() .with_title("A ...
random_line_split
window_run_return.rs
// Limit this example to only compatible platforms. #[cfg(any( target_os = "windows", target_os = "macos", target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "netbsd", target_os = "openbsd" ))] fn main() { use std::{thread::sleep, time::Duration}; use s...
Event::MainEventsCleared => { *control_flow = ControlFlow::Exit; } _ => (), } }); // Sleep for 1/60 second to simulate rendering println!("rendering"); sleep(Duration::from_millis(16)); } } #[cfg(any(t...
{ quit = true; }
conditional_block
router.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crate::fsm::{Fsm, FsmScheduler, FsmState}; use crate::mailbox::{BasicMailbox, Mailbox}; use crate::metrics::CHANNEL_FULL_COUNTER_VEC; use collections::HashMap; use crossbeam::channel::{SendError, TrySendError}; use std::cell::Cell; use std::mem; us...
.inc(); r } r => r, } } /// Try to notify all normal fsm a message. pub fn broadcast_normal(&self, mut msg_gen: impl FnMut() -> N::Message) { let mailboxes = self.normals.lock().unwrap(); for mailbox in mailboxes.map.values(...
match self.control_box.try_send(msg, &self.control_scheduler) { Ok(()) => Ok(()), r @ Err(TrySendError::Full(_)) => { CHANNEL_FULL_COUNTER_VEC .with_label_values(&["control"])
random_line_split
router.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crate::fsm::{Fsm, FsmScheduler, FsmState}; use crate::mailbox::{BasicMailbox, Mailbox}; use crate::metrics::CHANNEL_FULL_COUNTER_VEC; use collections::HashMap; use crossbeam::channel::{SendError, TrySendError}; use std::cell::Cell; use std::mem; us...
CheckDoResult::Invalid => Either::Left(Err(TrySendError::Disconnected(msg.unwrap()))), CheckDoResult::NotExist => Either::Right(msg.unwrap()), } } /// Send the message to specified address. #[inline] pub fn send(&self, addr: u64, msg: N::Message) -> Result<(), TrySendEr...
{ let mut msg = Some(msg); let res = self.check_do(addr, |mailbox| { let m = msg.take().unwrap(); match mailbox.try_send(m, &self.normal_scheduler) { Ok(()) => Some(Ok(())), r @ Err(TrySendError::Full(_)) => { CHANNEL_FULL_COUNT...
identifier_body
router.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. use crate::fsm::{Fsm, FsmScheduler, FsmState}; use crate::mailbox::{BasicMailbox, Mailbox}; use crate::metrics::CHANNEL_FULL_COUNTER_VEC; use collections::HashMap; use crossbeam::channel::{SendError, TrySendError}; use std::cell::Cell; use std::mem; us...
(&self, addr: u64) -> Option<Mailbox<N, Ns>> { let res = self.check_do(addr, |mailbox| { if mailbox.is_connected() { Some(Mailbox::new(mailbox.clone(), self.normal_scheduler.clone())) } else { None } }); match res { ...
mailbox
identifier_name
env.rs
#![crate_id(name="env", vers="1.0.0", author="LeoTestard")] /* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: ...
// print name=value env pairs on screen // if null is true, separate pairs with a \0, \n otherwise fn print_env(null: bool) { let env = std::os::env(); for &(ref n, ref v) in env.iter() { print!("{:s}={:s}{:c}", n.as_slice(), v.as_slice(), if null { '\0' } else { '...
{ println!("env 1.0.0"); }
identifier_body
env.rs
#![crate_id(name="env", vers="1.0.0", author="LeoTestard")] /* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: ...
() { println!("env 1.0.0"); } // print name=value env pairs on screen // if null is true, separate pairs with a \0, \n otherwise fn print_env(null: bool) { let env = std::os::env(); for &(ref n, ref v) in env.iter() { print!("{:s}={:s}{:c}", n.as_slice(), v.as_slice(), ...
version
identifier_name
env.rs
#![crate_id(name="env", vers="1.0.0", author="LeoTestard")] /* * This file is part of the uutils coreutils package. * * (c) Jordi Boggiano <j.boggiano@seld.be> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* last synced with: ...
for &(ref n, ref v) in env.iter() { print!("{:s}={:s}{:c}", n.as_slice(), v.as_slice(), if null { '\0' } else { '\n' } ); } } #[allow(dead_code)] fn main() { uumain(os::args()); } pub fn uumain(args: Vec<String>) { let prog = args.get(0).as_slice(); ...
// print name=value env pairs on screen // if null is true, separate pairs with a \0, \n otherwise fn print_env(null: bool) { let env = std::os::env();
random_line_split
dst-bad-deep.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 ...
let g: &Fat<[int]> = &f; let h: &Fat<Fat<[int]>> = &Fat { ptr: *g }; //~^ ERROR the trait `core::kinds::Sized` is not implemented }
} pub fn main() { let f: Fat<[int, ..3]> = Fat { ptr: [5i, 6, 7] };
random_line_split
dst-bad-deep.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 ...
<Sized? T> { ptr: T } pub fn main() { let f: Fat<[int,..3]> = Fat { ptr: [5i, 6, 7] }; let g: &Fat<[int]> = &f; let h: &Fat<Fat<[int]>> = &Fat { ptr: *g }; //~^ ERROR the trait `core::kinds::Sized` is not implemented }
Fat
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 ...
use hyper::http::RawStatus; use hyper::method::Method; use ipc_channel::ipc::IpcSender; use time::Duration; use std::net::TcpStream; use std::sync::mpsc::{Receiver, Sender}; pub type DevtoolsControlChan = Sender<DevtoolsControlMsg>; pub type DevtoolsControlPort = Receiver<DevtoolScriptControlMsg>; // Information wou...
use hyper::header::Headers;
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 ...
(&self, later: PreciseTime) -> Duration { Duration::nanoseconds((later.0 - self.0) as i64) } }
to
identifier_name
package_id.rs
use std::cmp::Ordering; use std::fmt::{self, Formatter}; use std::hash::Hash; use std::hash; use std::path::Path; use std::sync::Arc; use semver; use serde::de; use serde::ser; use util::{CargoResult, ToSemver}; use core::source::SourceId; use core::interning::InternedString; /// Identifier for a specific version of...
(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{} v{}", self.inner.name, self.inner.version)?; if!self.inner.source_id.is_default_registry() { write!(f, " ({})", self.inner.source_id)?; } Ok(()) } } impl fmt::Debug for PackageId { fn fmt(&self, f: &mut Form...
fmt
identifier_name
package_id.rs
use std::cmp::Ordering; use std::fmt::{self, Formatter}; use std::hash::Hash; use std::hash; use std::path::Path; use std::sync::Arc; use semver; use serde::de; use serde::ser; use util::{CargoResult, ToSemver}; use core::source::SourceId; use core::interning::InternedString; /// Identifier for a specific version of...
version: v, source_id: sid.clone(), }), }) } pub fn name(&self) -> InternedString { self.inner.name } pub fn version(&self) -> &semver::Version { &self.inner.version } pub fn source_id(&self) -> &SourceId { &self.inner....
let v = version.to_semver()?; Ok(PackageId { inner: Arc::new(PackageIdInner { name: InternedString::new(name),
random_line_split
package_id.rs
use std::cmp::Ordering; use std::fmt::{self, Formatter}; use std::hash::Hash; use std::hash; use std::path::Path; use std::sync::Arc; use semver; use serde::de; use serde::ser; use util::{CargoResult, ToSemver}; use core::source::SourceId; use core::interning::InternedString; /// Identifier for a specific version of...
} #[cfg(test)] mod tests { use super::PackageId; use core::source::SourceId; use sources::CRATES_IO; use util::ToUrl; #[test] fn invalid_version_handled_nicely() { let loc = CRATES_IO.to_url().unwrap(); let repo = SourceId::for_registry(&loc).unwrap(); assert!(Package...
{ f.debug_struct("PackageId") .field("name", &self.inner.name) .field("version", &self.inner.version.to_string()) .field("source", &self.inner.source_id.to_string()) .finish() }
identifier_body
wasm.rs
use crate::*; use std::alloc::Layout; pub static mut APPS2: Vec<Application> = Vec::new(); static LOGGER: WebConsoleLogger = WebConsoleLogger {}; struct WebConsoleLogger {} impl log::Log for WebConsoleLogger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= log::max_level() ...
{ ptr: *mut u8, } impl AllocBuffer { pub fn header_size() -> usize { std::mem::size_of::<usize>() } pub fn from_data_ptr(ptr: usize) -> Self { let ptr_start = ptr - Self::header_size(); let block = Self { ptr: ptr_start as *mut u8, }; block } ...
AllocBuffer
identifier_name
wasm.rs
use crate::*; use std::alloc::Layout; pub static mut APPS2: Vec<Application> = Vec::new(); static LOGGER: WebConsoleLogger = WebConsoleLogger {}; struct WebConsoleLogger {} impl log::Log for WebConsoleLogger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= log::max_level() ...
#[cfg(target_arch = "x86_64")] pub unsafe fn apply_to(_size: u32, _ptr: u32) {} #[cfg(target_arch = "x86_64")] pub unsafe fn console(_category: u32, _size: u32, _ptr: u32) {} #[no_mangle] pub fn init() { std::panic::set_hook(Box::new(|panic_info| { let msg = format!("{}", panic_info); unsafe { con...
}
random_line_split
wasm.rs
use crate::*; use std::alloc::Layout; pub static mut APPS2: Vec<Application> = Vec::new(); static LOGGER: WebConsoleLogger = WebConsoleLogger {}; struct WebConsoleLogger {} impl log::Log for WebConsoleLogger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= log::max_level() ...
#[no_mangle] pub fn application_new() -> usize { unsafe { let app = Application::new(APPS2.len()); APPS2.push(app); APPS2.len() - 1 } } #[macro_export] macro_rules! mount { ( $($id:expr => $type:ty),*) => { $(impl runtime::ApplicationFacade for $type { fn send_...
{ std::panic::set_hook(Box::new(|panic_info| { let msg = format!("{}", panic_info); unsafe { console(0, msg.len() as u32, msg.as_ptr() as u32) }; })); let _ = log::set_logger(&LOGGER); log::set_max_level(log::LevelFilter::Trace); }
identifier_body
entry.rs
//! # Page table entry //! Some code borrowed from [Phil Opp's Blog](http://os.phil-opp.com/modifying-page-tables.html) use memory::Frame; use super::PhysicalAddress; /// A page table entry pub struct Entry(u64); bitflags! { pub flags EntryFlags: u64 { const PRESENT = 1 << 0, const WRITA...
(&self) -> EntryFlags { EntryFlags::from_bits_truncate(self.0) } /// Get the associated frame, if available pub fn pointed_frame(&self) -> Option<Frame> { if self.flags().contains(PRESENT) { Some(Frame::containing_address(self.address())) } else { None ...
flags
identifier_name
entry.rs
//! # Page table entry
//! Some code borrowed from [Phil Opp's Blog](http://os.phil-opp.com/modifying-page-tables.html) use memory::Frame; use super::PhysicalAddress; /// A page table entry pub struct Entry(u64); bitflags! { pub flags EntryFlags: u64 { const PRESENT = 1 << 0, const WRITABLE = 1 << 1, ...
random_line_split
entry.rs
//! # Page table entry //! Some code borrowed from [Phil Opp's Blog](http://os.phil-opp.com/modifying-page-tables.html) use memory::Frame; use super::PhysicalAddress; /// A page table entry pub struct Entry(u64); bitflags! { pub flags EntryFlags: u64 { const PRESENT = 1 << 0, const WRITA...
/// Get the associated frame, if available pub fn pointed_frame(&self) -> Option<Frame> { if self.flags().contains(PRESENT) { Some(Frame::containing_address(self.address())) } else { None } } pub fn set(&mut self, frame: Frame, flags: EntryFlags) { ...
{ EntryFlags::from_bits_truncate(self.0) }
identifier_body
entry.rs
//! # Page table entry //! Some code borrowed from [Phil Opp's Blog](http://os.phil-opp.com/modifying-page-tables.html) use memory::Frame; use super::PhysicalAddress; /// A page table entry pub struct Entry(u64); bitflags! { pub flags EntryFlags: u64 { const PRESENT = 1 << 0, const WRITA...
else { None } } pub fn set(&mut self, frame: Frame, flags: EntryFlags) { debug_assert!(frame.start_address().get() &!ADDRESS_MASK == 0); self.0 = (frame.start_address().get() as u64) | flags.bits(); } }
{ Some(Frame::containing_address(self.address())) }
conditional_block
test.rs
#![feature(phase)] extern crate debug; extern crate time; extern crate stomp; #[phase(plugin, link)] extern crate log; use stomp::Client; use stomp::{CONNECTED, RECEIPT}; // Test CONNECT #[test] fn test_connect() { let mut client = Client::with_uri("localhost:61613"); let response = client.connect("user", "pw")...
{ let mut client = Client::with_uri("localhost:61613"); let _ = client.connect("user", "pw").unwrap(); let _ = client.send("/queue/test", "auto").unwrap(); }
identifier_body
test.rs
#![feature(phase)] extern crate debug; extern crate time; extern crate stomp; #[phase(plugin, link)] extern crate log; use stomp::Client; use stomp::{CONNECTED, RECEIPT}; // Test CONNECT #[test] fn test_connect() { let mut client = Client::with_uri("localhost:61613"); let response = client.connect("user", "pw")...
() { let mut client = Client::with_uri("localhost:61613"); let _ = client.connect("user", "pw").unwrap(); let _ = client.send("/queue/test", "auto").unwrap(); }
test_subscribe
identifier_name
test.rs
#![feature(phase)] extern crate debug; extern crate time; extern crate stomp; #[phase(plugin, link)] extern crate log; use stomp::Client; use stomp::{CONNECTED, RECEIPT};
let response = client.connect("user", "pw").unwrap(); assert_eq!(response.command, CONNECTED); drop(client.stream); } // Test SEND #[test] fn test_send() { let mut client = Client::with_uri("localhost:61613"); let _ = client.connect("user", "pw").unwrap(); let mut buf = [0,..128]; // Temp hack to disting...
// Test CONNECT #[test] fn test_connect() { let mut client = Client::with_uri("localhost:61613");
random_line_split
header.rs
use std::convert::From; use std::ascii::AsciiExt; /// Headers that may be used by an HTTP request or response. #[derive(Clone, Debug, PartialEq)] pub enum
{ Host, Connection, KeepAlive, ContentLength, TransferEncoding, Raw(String), } impl<'a> From<&'a str> for Header { fn from(s: &'a str) -> Header { if s.eq_ignore_ascii_case("Host") { Header::Host } else if s.eq_ignore_ascii_case("Connection") { Heade...
Header
identifier_name
magics.rs
use rand::{Rng, thread_rng}; use types::{BISHOP, ROOK}; use util::*; static mut KING_MAP: [u64; 64] = [0; 64]; static mut KNIGHT_MAP: [u64; 64] = [0; 64]; static mut BISHOP_MAP: [SMagic; 64] = [SMagic { offset: 0, mask: 0, magic: 0, shift: 0 }; 64]; static mut ROOK_MAP: [SMagic; 64] = [SMagic { offset: 0, mask: 0, mag...
pub fn queen_moves(from: u32, occ: u64) -> u64 { unsafe { BISHOP_MAP[from as usize].att(occ) | ROOK_MAP[from as usize].att(occ) } } pub unsafe fn init() { king_map_init(); knight_map_init(); let size = get_piece_map(BISHOP, &mut BISHOP_MAP, 0, false); let total = get_piece_map(RO...
{ unsafe { ROOK_MAP[from as usize].att(occ) } }
identifier_body
magics.rs
use rand::{Rng, thread_rng}; use types::{BISHOP, ROOK}; use util::*; static mut KING_MAP: [u64; 64] = [0; 64]; static mut KNIGHT_MAP: [u64; 64] = [0; 64]; static mut BISHOP_MAP: [SMagic; 64] = [SMagic { offset: 0, mask: 0, magic: 0, shift: 0 }; 64]; static mut ROOK_MAP: [SMagic; 64] = [SMagic { offset: 0, mask: 0, mag...
} } } pub unsafe fn king_map_init() { let offsets = vec![ (1, -1), (1, 0), (1, 1), (0, -1), (0, 1), (-1,-1), (-1, 0), (-1, 1)]; for (i, attacks) in KING_MAP.iter_mut().enumerate() { let (r, c) = ((i / 8) as isize, (i % 8) as isize); for &(dr, dc) in &offsets...
{ *attacks |= 1 << ((r + dr)*8 + c + dc); }
conditional_block
magics.rs
use rand::{Rng, thread_rng}; use types::{BISHOP, ROOK}; use util::*; static mut KING_MAP: [u64; 64] = [0; 64]; static mut KNIGHT_MAP: [u64; 64] = [0; 64]; static mut BISHOP_MAP: [SMagic; 64] = [SMagic { offset: 0, mask: 0, magic: 0, shift: 0 }; 64]; static mut ROOK_MAP: [SMagic; 64] = [SMagic { offset: 0, mask: 0, mag...
{ pub offset: usize, pub mask: u64, pub magic: u64, pub shift: u32 } impl SMagic { pub unsafe fn att(&self, occ: u64) -> u64 { let ind = (self.magic * (occ & self.mask)) >> self.shift; MAP[self.offset + ind as usize] } } pub unsafe fn get_piece_map(piece: u8, piece_map: &mut [...
SMagic
identifier_name
magics.rs
use rand::{Rng, thread_rng}; use types::{BISHOP, ROOK}; use util::*; static mut KING_MAP: [u64; 64] = [0; 64]; static mut KNIGHT_MAP: [u64; 64] = [0; 64]; static mut BISHOP_MAP: [SMagic; 64] = [SMagic { offset: 0, mask: 0, magic: 0, shift: 0 }; 64]; static mut ROOK_MAP: [SMagic; 64] = [SMagic { offset: 0, mask: 0, mag...
pub fn rook_moves(from: u32, occ: u64) -> u64 { unsafe { ROOK_MAP[from as usize].att(occ) } } pub fn queen_moves(from: u32, occ: u64) -> u64 { unsafe { BISHOP_MAP[from as usize].att(occ) | ROOK_MAP[from as usize].att(occ) } } pub unsafe fn init() { king_map_init(); knight_map_init(); ...
pub fn bishop_moves(from: u32, occ: u64) -> u64 { unsafe { BISHOP_MAP[from as usize].att(occ) } }
random_line_split
main.rs
extern crate clap; use clap::{App, SubCommand}; fn main()
// + Used by "$ myapp test" with the following arguments // > A list flag // = Uses "-l" (usage is "$ myapp test -l" // > A help flag (automatically generated by clap // = Uses "-h" or "--help" (full usage "$ myapp test -h" or "$ myapp test ...
{ // This example shows how to create an application with several arguments using usage strings, which can be // far less verbose that shown in 01b_QuickExample.rs, but is more readable. The downside is you cannot set // the more advanced configuration options using this method (well...actually you can, you...
identifier_body
main.rs
extern crate clap; use clap::{App, SubCommand}; fn
() { // This example shows how to create an application with several arguments using usage strings, which can be // far less verbose that shown in 01b_QuickExample.rs, but is more readable. The downside is you cannot set // the more advanced configuration options using this method (well...actually you can, ...
main
identifier_name
main.rs
extern crate clap; use clap::{App, SubCommand}; fn main() { // This example shows how to create an application with several arguments using usage strings, which can be // far less verbose that shown in 01b_QuickExample.rs, but is more readable. The downside is you cannot set // the more advanced configura...
if let Some(c) = matches.value_of("config") { println!("Value for config: {}", c); } // You can see how many times a particular flag or argument occurred // Note, only flags can have multiple occurrences match matches.occurrences_of("d") { 0 => println!("Debug mode is off"), ...
{ println!("Value for output: {}", o); }
conditional_block
main.rs
extern crate clap; use clap::{App, SubCommand}; fn main() { // This example shows how to create an application with several arguments using usage strings, which can be // far less verbose that shown in 01b_QuickExample.rs, but is more readable. The downside is you cannot set // the more advanced configura...
// You can see how many times a particular flag or argument occurred // Note, only flags can have multiple occurrences match matches.occurrences_of("d") { 0 => println!("Debug mode is off"), 1 => println!("Debug mode is kind of on"), 2 => println!("Debug mode is on"), _ => p...
if let Some(c) = matches.value_of("config") { println!("Value for config: {}", c); }
random_line_split
cache.rs
use std::env; use std::ffi::OsStr; use std::fs; use std::io::Read; use std::iter; use std::path::{Path, PathBuf}; use app_dirs::{get_app_root, AppDataType}; use flate2::read::GzDecoder; use log::debug; use reqwest::{blocking::Client, Proxy}; use std::time::{Duration, SystemTime}; use tar::Archive; use walkdir::{DirEnt...
let patch_path = Self::find_patch(&patch_filename, custom_pages_dir.as_deref()); // Try to find a platform specific path next, append custom patch to it. if let Some(pf) = self.get_platform_dir() { if let Some(page) = Self::find_page_for_platform(&page_filename, &ca...
} }
random_line_split
cache.rs
use std::env; use std::ffi::OsStr; use std::fs; use std::io::Read; use std::iter; use std::path::{Path, PathBuf}; use app_dirs::{get_app_root, AppDataType}; use flate2::read::GzDecoder; use log::debug; use reqwest::{blocking::Client, Proxy}; use std::time::{Duration, SystemTime}; use tar::Archive; use walkdir::{DirEnt...
pub fn paths(&self) -> impl Iterator<Item = &Path> { iter::once(self.page_path.as_path()).chain(self.patch_path.as_deref().into_iter()) } } impl Cache { pub fn new<S>(url: S, os: OsType) -> Self where S: Into<String>, { Self { url: url.into(), os, ...
{ self.patch_path = patch_path; self }
identifier_body
cache.rs
use std::env; use std::ffi::OsStr; use std::fs; use std::io::Read; use std::iter; use std::path::{Path, PathBuf}; use app_dirs::{get_app_root, AppDataType}; use flate2::read::GzDecoder; use log::debug; use reqwest::{blocking::Client, Proxy}; use std::time::{Duration, SystemTime}; use tar::Archive; use walkdir::{DirEnt...
else { None } }) .collect::<Vec<String>>(); pages.sort(); pages.dedup(); Ok(pages) } /// Delete the cache directory. pub fn clear() -> Result<(), TealdeerError> { let (path, _) = Self::get_cache_dir()?; if p...
{ path.file_stem() .and_then(|stem| stem.to_str().map(|s| s.into())) }
conditional_block
cache.rs
use std::env; use std::ffi::OsStr; use std::fs; use std::io::Read; use std::iter; use std::path::{Path, PathBuf}; use app_dirs::{get_app_root, AppDataType}; use flate2::read::GzDecoder; use log::debug; use reqwest::{blocking::Client, Proxy}; use std::time::{Duration, SystemTime}; use tar::Archive; use walkdir::{DirEnt...
<R: Read>(reader: R) -> Archive<GzDecoder<R>> { Archive::new(GzDecoder::new(reader)) } /// Update the pages cache. pub fn update(&self) -> Result<(), TealdeerError> { // First, download the compressed data let bytes: Vec<u8> = self.download()?; // Decompress the response bo...
decompress
identifier_name
atom.rs
use crate::syntax::Type; use proc_macro2::Ident; use std::fmt::{self, Display}; #[derive(Copy, Clone, PartialEq)] pub enum Atom { Bool, Char, // C char, not Rust char U8, U16, U32, U64, Usize, I8, I16, I32, I64, Isize, F32, F64, CxxString, RustString, } ...
impl AsRef<str> for Atom { fn as_ref(&self) -> &str { use self::Atom::*; match self { Bool => "bool", Char => "c_char", U8 => "u8", U16 => "u16", U32 => "u32", U64 => "u64", Usize => "usize", I8 => "i8",...
random_line_split
atom.rs
use crate::syntax::Type; use proc_macro2::Ident; use std::fmt::{self, Display}; #[derive(Copy, Clone, PartialEq)] pub enum Atom { Bool, Char, // C char, not Rust char U8, U16, U32, U64, Usize, I8, I16, I32, I64, Isize, F32, F64, CxxString, RustString, } ...
(&self) -> &str { use self::Atom::*; match self { Bool => "bool", Char => "c_char", U8 => "u8", U16 => "u16", U32 => "u32", U64 => "u64", Usize => "usize", I8 => "i8", I16 => "i16", I3...
as_ref
identifier_name
atom.rs
use crate::syntax::Type; use proc_macro2::Ident; use std::fmt::{self, Display}; #[derive(Copy, Clone, PartialEq)] pub enum Atom { Bool, Char, // C char, not Rust char U8, U16, U32, U64, Usize, I8, I16, I32, I64, Isize, F32, F64, CxxString, RustString, } ...
} impl PartialEq<Atom> for &Ident { fn eq(&self, atom: &Atom) -> bool { *self == atom } } impl PartialEq<Atom> for &Type { fn eq(&self, atom: &Atom) -> bool { *self == atom } }
{ match self { Type::Ident(ident) => ident.rust == atom, _ => false, } }
identifier_body