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
extern crate chrono; extern crate iron; extern crate persistent; extern crate r2d2; extern crate r2d2_sqlite; extern crate router; extern crate rusqlite; extern crate rustc_serialize; extern crate sha2; use chrono::*; use iron::prelude::*; use iron::Url; use iron::modifiers::Redirect; use iron::status::Status; use ir...
(req: &mut Request) -> IronResult<Response> { let pool = req.get::<Read<YausDb>>().unwrap().clone(); let db = pool.get().unwrap(); let locator = req.url.path()[0]; let mut stmt = db.prepare("SELECT url FROM urls WHERE locator = (?)").unwrap(); let mut row = stmt.query_map::<String, _>(&[&locator], |...
redirect_handler
identifier_name
sampler_linux.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] use crate::sampler::{NativeStack, Sampler}; use libc; use nix::sys::signal::{sigaction, S...
-> Box<dyn Sampler> { let thread_id = unsafe { libc::syscall(libc::SYS_gettid) as libc::pid_t }; let handler = SigHandler::SigAction(sigprof_handler); let action = SigAction::new( handler, SaFlags::SA_RESTART | SaFlags::SA_SIGINFO, SigSet::empty(), );...
w()
identifier_name
sampler_linux.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] use crate::sampler::{NativeStack, Sampler}; use libc; use nix::sys::signal::{sigaction, S...
unsafe { libc::sem_destroy(self.sem.get()) }; } } #[allow(dead_code)] pub struct LinuxSampler { thread_id: MonitoredThreadId, old_handler: SigAction, } impl LinuxSampler { #[allow(unsafe_code, dead_code)] pub fn new() -> Box<dyn Sampler> { let thread_id = unsafe { libc::syscall(lib...
/// Destroys the semaphore. fn drop(&mut self) {
random_line_split
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult}, server::LSPState, }; use common::PerfLogger; use lsp_t...
} Ok(ResolvedTypesAtLocationResponse { path_and_schema_name: None, }) }
{ // If type_path is empty, type_path.resolve_current_field() will panic. if !node_resolution_info.type_path.0.is_empty() { let type_and_field = node_resolution_info .type_path .resolve_current_field(&schema); if let Some((_...
conditional_block
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult}, server::LSPState, }; use common::PerfLogger; use lsp_t...
} } Ok(ResolvedTypesAtLocationResponse { path_and_schema_name: None, }) }
{ if let Ok(node_resolution_info) = state.resolve_node(params.to_text_document_position_params()?) { if let Some(schema) = state.get_schemas().get(&node_resolution_info.project_name) { // If type_path is empty, type_path.resolve_current_field() will panic. if !node_resolution_inf...
identifier_body
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult}, server::LSPState, }; use common::PerfLogger; use lsp_t...
path_and_schema_name: None, }) }
} } Ok(ResolvedTypesAtLocationResponse {
random_line_split
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::{ lsp_runtime_error::{LSPRuntimeError, LSPRuntimeResult}, server::LSPState, }; use common::PerfLogger; use lsp_t...
(&self) -> LSPRuntimeResult<TextDocumentPositionParams> { Ok(TextDocumentPositionParams { text_document: TextDocumentIdentifier { uri: Url::parse(&self.file_name).map_err(|_| LSPRuntimeError::ExpectedError)?, }, position: Position { character: ...
to_text_document_position_params
identifier_name
lib.rs
//! A blazingly fast chess library. //! //! This package is separated into two parts. Firstly, the board representation & associated functions //! (the current crate, `pleco`), and secondly, the AI implementations using these chess foundations, //! [pleco_engine](https://crates.io/crates/pleco_engine). //! //! The gene...
//! board.apply_move(*mov); //! println!("{}",board.get_fen()); //! board.undo_move(); //! } //! ``` //! //! Using fen strings is also supported: //! //! ```ignore //! let start_position = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; //! let board = Board::from_fen(start_position).unwrap(); /...
//! //! for mov in list.iter() {
random_line_split
test_utils.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![doc(hidden)] #[cfg(test)] use std::thread; #[cfg(test)] use std::time::Duration; use crate::virtio::block::device::FileEngineType; #[cfg(test)] use crate::virtio::block::io::FileEngine; #[cfg(test)] u...
} /// Create a default Block instance using file at the specified path to be used in tests. pub fn default_block_with_path(path: String, file_engine_type: FileEngineType) -> Block { // Rate limiting is enabled but with a high operation rate (10 million ops/s). let rate_limiter = RateLimiter::new(0, 0, 0, 100_...
{ FileEngineType::Sync }
conditional_block
test_utils.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![doc(hidden)] #[cfg(test)] use std::thread; #[cfg(test)] use std::time::Duration; use crate::virtio::block::device::FileEngineType; #[cfg(test)] use crate::virtio::block::io::FileEngine; #[cfg(test)] u...
id, None, CacheType::Unsafe, path, false, false, rate_limiter, file_engine_type, ) .unwrap() } pub fn set_queue(blk: &mut Block, idx: usize, q: Queue) { blk.queues[idx] = q; } pub fn set_rate_limiter(blk: &mut Block, rl: RateLimiter) { blk...
let rate_limiter = RateLimiter::new(0, 0, 0, 100_000, 0, 10).unwrap(); let id = "test".to_string(); // The default block device is read-write and non-root. Block::new(
random_line_split
test_utils.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![doc(hidden)] #[cfg(test)] use std::thread; #[cfg(test)] use std::time::Duration; use crate::virtio::block::device::FileEngineType; #[cfg(test)] use crate::virtio::block::io::FileEngine; #[cfg(test)] u...
(b: &mut Block, maybe_expected_irq: Option<bool>) { // Trigger the queue event. b.queue_evts[0].write(1).unwrap(); // Handle event. b.process_queue_event(); // Validate the queue operation finished successfully. if let Some(expected_irq) = maybe_expected_irq { assert_eq!(b.irq_trigger.ha...
simulate_queue_event
identifier_name
test_utils.rs
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 #![doc(hidden)] #[cfg(test)] use std::thread; #[cfg(test)] use std::time::Duration; use crate::virtio::block::device::FileEngineType; #[cfg(test)] use crate::virtio::block::io::FileEngine; #[cfg(test)] u...
pub fn set_rate_limiter(blk: &mut Block, rl: RateLimiter) { blk.rate_limiter = rl; } pub fn rate_limiter(blk: &mut Block) -> &RateLimiter { &blk.rate_limiter } #[cfg(test)] pub fn simulate_queue_event(b: &mut Block, maybe_expected_irq: Option<bool>) { // Trigger the queue event. b.queue_evts[0].writ...
{ blk.queues[idx] = q; }
identifier_body
mod.rs
//! Items related to the **Frame** type, describing a single frame of graphics for a single window. use crate::color::IntoLinSrgba; use crate::wgpu; use std::ops; use std::path::PathBuf; use std::sync::Mutex; use std::time::Duration; pub mod raw; pub use self::raw::RawFrame; /// A **Frame** to which the user can dr...
(&self) -> wgpu::RenderPassColorAttachmentDescriptor { let load = wgpu::LoadOp::Load; let store = true; let attachment = match self.render_data.intermediary_lin_srgba.msaa_texture { None => &self.render_data.intermediary_lin_srgba.texture_view, Some((_, ref msaa_texture_v...
color_attachment_descriptor
identifier_name
mod.rs
//! Items related to the **Frame** type, describing a single frame of graphics for a single window. use crate::color::IntoLinSrgba; use crate::wgpu; use std::ops; use std::path::PathBuf; use std::sync::Mutex; use std::time::Duration; pub mod raw; pub use self::raw::RawFrame; /// A **Frame** to which the user can dr...
} = *self; // Resolve the MSAA if necessary. if let Some((_, ref msaa_texture_view)) = render_data.intermediary_lin_srgba.msaa_texture { let mut encoder = raw_frame.command_encoder(); wgpu::resolve_texture( msaa_texture_view, &render_data....
fn submit_inner(&mut self) { let Frame { ref capture_data, ref render_data, ref mut raw_frame,
random_line_split
mod.rs
//! Items related to the **Frame** type, describing a single frame of graphics for a single window. use crate::color::IntoLinSrgba; use crate::wgpu; use std::ops; use std::path::PathBuf; use std::sync::Mutex; use std::time::Duration; pub mod raw; pub use self::raw::RawFrame; /// A **Frame** to which the user can dr...
/// Submit the frame to the GPU! /// /// Note that you do not need to call this manually as submission will occur automatically when /// the **Frame** is dropped. /// /// Before submission, the frame does the following: /// /// - If the frame's intermediary linear sRGBA texture is mult...
{ let lin_srgba = color.into_lin_srgba(); let (r, g, b, a) = lin_srgba.into_components(); let (r, g, b, a) = (r as f64, g as f64, b as f64, a as f64); let color = wgpu::Color { r, g, b, a }; wgpu::clear_texture(self.texture_view(), color, &mut *self.command_encoder()) }
identifier_body
xmlname.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Functions for validating and extracting qualified XML names. use crate::dom::bindings::error::{Error, ErrorR...
(c: char) -> bool { match c { ':' | 'A'...'Z' | '_' | 'a'...'z' | '\u{C0}'...'\u{D6}' | '\u{D8}'...'\u{F6}' | '\u{F8}'...'\u{2FF}' | '\u{370}'...'\u{37D}' | '\u{37F}'...'\u{1FFF}' | '\u{200C}'...
is_valid_start
identifier_name
xmlname.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Functions for validating and extracting qualified XML names. use crate::dom::bindings::error::{Error, ErrorR...
last = c } if last == ':' { non_qname_colons = true } if non_qname_colons { XMLName::Name } else { XMLName::QName } } /// Convert a possibly-null URL to a namespace. /// /// If the URL is None, returns the empty namespace. pub fn namespace_from_domstring(url: ...
{ if seen_colon { non_qname_colons = true; } else { seen_colon = true; } }
conditional_block
xmlname.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Functions for validating and extracting qualified XML names. use crate::dom::bindings::error::{Error, ErrorR...
} /// Results of `xml_name_type`. #[derive(PartialEq)] #[allow(missing_docs)] pub enum XMLName { QName, Name, InvalidXMLName, } /// Check if an element name is valid. See http://www.w3.org/TR/xml/#NT-Name /// for details. pub fn xml_name_type(name: &str) -> XMLName { fn is_valid_start(c: char) -> bool...
Ok((ns, p.map(Prefix::from), LocalName::from(local_name))) }, }
random_line_split
protocol.rs
use std::marker::PhantomData; use std::mem; use session_types::*; use peano::{Peano,Pop}; use super::{IO, Transfers}; /// A `Protocol` describes the underlying protocol, including the "initial" session /// type. `Handler`s are defined over concrete `Protocol`s to implement the behavior /// of a protocol in a given `Se...
<P: Protocol, I: IO>(io: I, proto: P) -> Channel<P, I, (), <P::Initial as SessionType>::Dual> { Channel::new(io, proto) } impl<I, E: SessionType, S: SessionType, P: Handler<I, E, S>> Channel<P, I, E, S> { /// Defer the rest of the protocol execution. Useful for returning early. /// /// There must be a...
channel_dual
identifier_name
protocol.rs
use std::marker::PhantomData; use std::mem; use session_types::*; use peano::{Peano,Pop}; use super::{IO, Transfers}; /// A `Protocol` describes the underlying protocol, including the "initial" session /// type. `Handler`s are defined over concrete `Protocol`s to implement the behavior /// of a protocol in a given `Se...
pub fn channel_dual<P: Protocol, I: IO>(io: I, proto: P) -> Channel<P, I, (), <P::Initial as SessionType>::Dual> { Channel::new(io, proto) } impl<I, E: SessionType, S: SessionType, P: Handler<I, E, S>> Channel<P, I, E, S> { /// Defer the rest of the protocol execution. Useful for returning early. /// ...
{ Channel::new(io, proto) }
identifier_body
protocol.rs
use std::marker::PhantomData; use std::mem; use session_types::*; use peano::{Peano,Pop}; use super::{IO, Transfers}; /// A `Protocol` describes the underlying protocol, including the "initial" session /// type. `Handler`s are defined over concrete `Protocol`s to implement the behavior /// of a protocol in a given `Se...
pub fn channel<P: Protocol, I: IO>(io: I, proto: P) -> Channel<P, I, (), P::Initial> { Channel::new(io, proto) } pub fn channel_dual<P: Protocol, I: IO>(io: I, proto: P) -> Channel<P, I, (), <P::Initial as SessionType>::Dual> { Channel::new(io, proto) } impl<I, E: SessionType, S: SessionType, P: Handler<I, E,...
}
random_line_split
hosts.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 parse_hosts::HostsFile; use servo_url::ServoUrl; use std::collections::HashMap; use std::env; use std::fs::Fil...
fn create_host_table() -> Option<HashMap<String, IpAddr>> { // TODO: handle bad file path let path = match env::var("HOST_FILE") { Ok(host_file_path) => host_file_path, Err(_) => return None, }; let mut file = match File::open(&path) { Ok(f) => BufReader::new(f), Err(_)...
}
random_line_split
hosts.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 parse_hosts::HostsFile; use servo_url::ServoUrl; use std::collections::HashMap; use std::env; use std::fs::Fil...
{ url.domain() .and_then(|domain| { host_table.get(domain).map(|ip| { let mut new_url = url.clone(); new_url.set_ip_host(*ip).unwrap(); new_url }) }) .unwrap_or_else(|| url.clone()) }
identifier_body
hosts.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 parse_hosts::HostsFile; use servo_url::ServoUrl; use std::collections::HashMap; use std::env; use std::fs::Fil...
(host_table: &HashMap<String, IpAddr>, url: &ServoUrl) -> ServoUrl { url.domain() .and_then(|domain| { host_table.get(domain).map(|ip| { let mut new_url = url.clone(); new_url.set_ip_host(*ip).unwrap(); new_url }) }) .unwr...
host_replacement
identifier_name
messages.rs
// Copyright 2015 © Samuel Dolt <samuel@dolt.ch> // // This file is part of orion_backend. // // Orion_backend is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your ...
"; pub static INVALID_VALUE: &'static str = " Invalid value - Value should represent one or more measurements Example: - 9[V] - 9[V] 3[A] 5[K] Valid unit: - [V] for Volt - [A] for Ampere - [Ω] for Ohm - [W] for Watt - [K] for Kelvin - [s] for second - [kg] for Kilogram "; pub static INVALID...
More info at `https://www.ietf.org/rfc/rfc3339.txt`
random_line_split
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId};
use util::{CargoResult, Config}; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present. /// /// This function will also write the result of resolution as a new /// lockfile. pub fn resolve_pkg(registry: &mut PackageRegistry, package: &Package,...
use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops;
random_line_split
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::{CargoResult, Config}; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present...
<'a>(registry: &mut PackageRegistry, package: &Package, method: Method, previous: Option<&'a Resolve>, to_avoid: Option<&HashSet<&'a PackageId>>) -> CargoR...
resolve_with_previous
identifier_name
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::{CargoResult, Config}; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present...
}
{ !to_avoid_sources.contains(&p.source_id()) && match to_avoid_packages { Some(set) => !set.contains(p), None => true, } }
identifier_body
resolve.rs
use std::collections::{HashMap, HashSet}; use core::{Package, PackageId, SourceId}; use core::registry::PackageRegistry; use core::resolver::{self, Resolve, Method}; use ops; use util::{CargoResult, Config}; /// Resolve all dependencies for the specified `package` using the previous /// lockfile as a guide if present...
} (spec.clone(), dep.clone()) }).collect::<Vec<_>>(); (summary, replace) } None => (summary, package.manifest().replace().to_owned()), }; let mut resolved = try!(resolver::resolve(&summary, &method, &replace, ...
{ return (spec.clone(), dep.clone().lock_to(val)) }
conditional_block
main.rs
extern crate rand; use rand::Rng; use std::io; use std::cmp::Ordering; fn main()
println!("Expected an integer number, found non integer, ignoring the input."); continue; }, } } }; println!("You guessed {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too Small"), Ordering::Greater => println!("Too Big"), Ordering::Equal => { ...
{ let stopper = String::from("Quit"); let secret_number = rand::thread_rng().gen_range(1, 101); loop{ println!("Please enter your guess!"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Failed to read line"); let guess:i32 = match guess.trim().parse() { Ok(num) => num, Er...
identifier_body
main.rs
extern crate rand; use rand::Rng; use std::io; use std::cmp::Ordering; fn main() { let stopper = String::from("Quit"); let secret_number = rand::thread_rng().gen_range(1, 101); loop{ println!("Please enter your guess!"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Failed to re...
} println!(""); } }
},
random_line_split
main.rs
extern crate rand; use rand::Rng; use std::io; use std::cmp::Ordering; fn
() { let stopper = String::from("Quit"); let secret_number = rand::thread_rng().gen_range(1, 101); loop{ println!("Please enter your guess!"); let mut guess = String::new(); io::stdin().read_line(&mut guess).expect("Failed to read line"); let guess:i32 = match guess.trim().parse() { Ok(num) => num, ...
main
identifier_name
text.rs
use std::borrow::ToOwned; use std::any::Any; use { GenericEvent, TEXT }; /// When receiving text from user, such as typing a character pub trait TextEvent: Sized { /// Creates a text event. fn from_text(text: &str, old_event: &Self) -> Option<Self>; /// Calls closure if this is a text event. fn text<U...
self.with_args(|any| { if let Some(text) = any.downcast_ref::<String>() { Some(f(&text)) } else { panic!("Expected &str") } }) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_input_text() { use supe...
{ return None; }
conditional_block
text.rs
use std::borrow::ToOwned; use std::any::Any; use { GenericEvent, TEXT }; /// When receiving text from user, such as typing a character pub trait TextEvent: Sized { /// Creates a text event. fn from_text(text: &str, old_event: &Self) -> Option<Self>; /// Calls closure if this is a text event. fn text<U...
() { use Event; use super::super::Input; let e = Event::Input(Input::Text("".to_string())); let x: Option<Event> = TextEvent::from_text("hello", &e); let y: Option<Event> = x.clone().unwrap().text(|text| TextEvent::from_text(text, x.as_ref().unwrap())).unwrap(); ...
test_event_text
identifier_name
text.rs
use std::borrow::ToOwned; use std::any::Any; use { GenericEvent, TEXT }; /// When receiving text from user, such as typing a character pub trait TextEvent: Sized { /// Creates a text event. fn from_text(text: &str, old_event: &Self) -> Option<Self>; /// Calls closure if this is a text event. fn text<U...
} #[cfg(test)] mod tests { use super::*; #[test] fn test_input_text() { use super::super::Input; let e = Input::Text("".to_string()); let x: Option<Input> = TextEvent::from_text("hello", &e); let y: Option<Input> = x.clone().unwrap().text(|text| TextEvent::fro...
{ if self.event_id() != TEXT { return None; } self.with_args(|any| { if let Some(text) = any.downcast_ref::<String>() { Some(f(&text)) } else { panic!("Expected &str") } }) }
identifier_body
text.rs
use std::borrow::ToOwned; use std::any::Any; use { GenericEvent, TEXT }; /// When receiving text from user, such as typing a character pub trait TextEvent: Sized { /// Creates a text event. fn from_text(text: &str, old_event: &Self) -> Option<Self>; /// Calls closure if this is a text event. fn text<U...
}) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_input_text() { use super::super::Input; let e = Input::Text("".to_string()); let x: Option<Input> = TextEvent::from_text("hello", &e); let y: Option<Input> = x.clone().unwrap().text(|text| ...
}
random_line_split
deriving-cmp-generic-enum.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 ...
assert_eq!(*e1 == *e2, eq); assert_eq!(*e1!= *e2,!eq); // PartialOrd assert_eq!(*e1 < *e2, lt); assert_eq!(*e1 > *e2, gt); assert_eq!(*e1 <= *e2, le); assert_eq!(*e1 >= *e2, ge); // Ord assert_eq!(e1.cmp(e2), ...
let le = i <= j; let gt = i > j; let ge = i >= j; // PartialEq
random_line_split
deriving-cmp-generic-enum.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 ...
<T> { E0, E1(T), E2(T,T) } pub fn main() { let e0 = E::E0; let e11 = E::E1(1); let e12 = E::E1(2); let e21 = E::E2(1, 1); let e22 = E::E2(1, 2); // in order for both PartialOrd and Ord let es = [e0, e11, e12, e21, e22]; for (i, e1) in es.iter().enumerate() { for (j...
E
identifier_name
adt-brace-structs.rs
// Copyright 2017 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 ...
() { }
main
identifier_name
adt-brace-structs.rs
// Copyright 2017 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 ...
fn annot_reference_any_lifetime() { let c = 66; SomeStruct::<&u32> { t: &c }; } fn annot_reference_static_lifetime() { let c = 66; SomeStruct::<&'static u32> { t: &c }; //~ ERROR } fn annot_reference_named_lifetime<'a>(_d: &'a u32) { let c = 66; SomeStruct::<&'a u32> { t: &c }; //~ ERROR } ...
{ let c = 66; SomeStruct::<_> { t: &c }; }
identifier_body
adt-brace-structs.rs
// Copyright 2017 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 ...
} fn annot_reference_named_lifetime_in_closure_ok<'a>(c: &'a u32) { let _closure = || { SomeStruct::<&'a u32> { t: c }; }; } fn main() { }
fn annot_reference_named_lifetime_in_closure<'a>(_: &'a u32) { let _closure = || { let c = 66; SomeStruct::<&'a u32> { t: &c }; //~ ERROR };
random_line_split
onig.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 ...
) -> onig::FindMatches<'r, 't> { self.0.find_iter(text) } }
&'r self, text: &'t str,
random_line_split
onig.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 ...
pub fn is_match(&self, text: &str) -> bool { // Gah. onig's is_match function is anchored, but find is not. self.0.search_with_options( text, 0, text.len(), onig::SEARCH_OPTION_NONE, None).is_some() } pub fn find_iter<'r, 't>( &'r self, text: &'t str, ) -> ...
{ onig::Regex::new(pattern).map(Regex) }
identifier_body
onig.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 ...
(onig::Regex); unsafe impl Send for Regex {} impl Regex { pub fn new(pattern: &str) -> Result<Self, onig::Error> { onig::Regex::new(pattern).map(Regex) } pub fn is_match(&self, text: &str) -> bool { // Gah. onig's is_match function is anchored, but find is not. self.0.search_with_...
Regex
identifier_name
types.rs
#![allow(unused_variables)] #![allow(non_upper_case_globals)] #![allow(dead_code)] #![allow(improper_ctypes)] use std::slice; use std::os::raw::c_char; #[repr(C)] pub struct mpc_state_t { pub pos: i64, pub row: i64, pub col: i64, } #[repr(C)] pub struct mpc_ast_t { pub tag: *mut c_char, pub conte...
; //TODO map structs to C #[repr(C)] pub struct module { pub name: *mut c_char, pub imports: *mut vector, pub functions: *mut vector, pub types: *mut vector, } #[repr(C)] pub struct import { pub name: *mut c_char, pub alias: *mut c_char, pub local: bool, pub w_alias: bool, } #[repr(C...
vector
identifier_name
types.rs
#![allow(unused_variables)] #![allow(non_upper_case_globals)] #![allow(dead_code)] #![allow(improper_ctypes)] use std::slice; use std::os::raw::c_char; #[repr(C)] pub struct mpc_state_t {
#[repr(C)] pub struct mpc_ast_t { pub tag: *mut c_char, pub contents: *mut c_char, pub state: mpc_state_t, pub children_num: i32, pub children: *const *const mpc_ast_t, } #[repr(C)] pub struct vector; //TODO map structs to C #[repr(C)] pub struct module { pub name: *mut c_char, pub impor...
pub pos: i64, pub row: i64, pub col: i64, }
random_line_split
main.rs
extern crate byteorder; extern crate num; #[macro_use] extern crate enum_primitive; mod n64; mod cpu; mod pif; mod rsp; mod audio_interface; mod video_interface; mod peripheral_interface; mod serial_interface; mod interconnect; mod mem_map; use std::env; use std::fs; use std::io::Read; use std::path::Path; fn
() { let pif_file_name = env::args().nth(1).unwrap(); let rom_file_name = env::args().nth(2).unwrap(); let pif = read_bin(pif_file_name); let rom = read_bin(rom_file_name); let mut n64 = n64::N64::new(pif, rom); loop { //println!("N64: {:#?}", &n64); n64.run_instruction(); ...
main
identifier_name
main.rs
#[macro_use] extern crate enum_primitive; mod n64; mod cpu; mod pif; mod rsp; mod audio_interface; mod video_interface; mod peripheral_interface; mod serial_interface; mod interconnect; mod mem_map; use std::env; use std::fs; use std::io::Read; use std::path::Path; fn main() { let pif_file_name = env::args().nt...
extern crate byteorder; extern crate num;
random_line_split
main.rs
extern crate byteorder; extern crate num; #[macro_use] extern crate enum_primitive; mod n64; mod cpu; mod pif; mod rsp; mod audio_interface; mod video_interface; mod peripheral_interface; mod serial_interface; mod interconnect; mod mem_map; use std::env; use std::fs; use std::io::Read; use std::path::Path; fn main...
fn read_bin<P: AsRef<Path>>(path: P) -> Box<[u8]> { let mut file = fs::File::open(path).unwrap(); let mut file_buf = Vec::new(); file.read_to_end(&mut file_buf).unwrap(); file_buf.into_boxed_slice() }
{ let pif_file_name = env::args().nth(1).unwrap(); let rom_file_name = env::args().nth(2).unwrap(); let pif = read_bin(pif_file_name); let rom = read_bin(rom_file_name); let mut n64 = n64::N64::new(pif, rom); loop { //println!("N64: {:#?}", &n64); n64.run_instruction(); } }
identifier_body
day_2.rs
pub use tdd_kata::sorting_kata::day_2::{Sort, BubbleSort, InsertSort, InPlaceMergeSort}; pub use rand::distributions::range::Range; pub use rand::distributions::Sample; pub use rand; pub use expectest::prelude::be_equal_to;
before_each { let mut between = Range::new(0, 1000); let mut rng = rand::thread_rng(); let mut data = Vec::with_capacity(10); let mut ret = Vec::with_capacity(10); for _ in 0..10 { let datum = between.sample(&mut rng); data.push(datum); r...
describe! array {
random_line_split
main.rs
extern crate failure; extern crate rand; use failure::{err_msg, Error}; use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); loop { println!(...
{ value: u32, } impl Guess { pub fn new(value: u32) -> Result<Guess, Error> { if value > 100 || value < 1 { // 由作者抛出的应用异常 return Err(err_msg("Guess value must be between 1 and 100")); }; let guess = Guess { value }; Ok(guess) } pub fn value(&self...
Guess
identifier_name
main.rs
extern crate failure; extern crate rand; use failure::{err_msg, Error}; use rand::Rng; use std::cmp::Ordering; use std::io; fn main()
Ok(value) => value.value, Err(_) => { print!("Guess value must be between 1 and 100"); continue; } }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), ...
{ println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); loop { println!("Please input you guess."); let mut guess = String::new(); io::stdin() .read_line(&mut guess) ...
identifier_body
main.rs
extern crate failure; extern crate rand; use failure::{err_msg, Error}; use rand::Rng; use std::cmp::Ordering; use std::io; fn main() { println!("Guess the number!"); let secret_number = rand::thread_rng().gen_range(1, 101); println!("The secret number is: {}", secret_number); loop { println!(...
continue; } }; println!("You guessed: {}", guess); match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => { println!("You win!"); ...
Ok(value) => value.value, Err(_) => { print!("Guess value must be between 1 and 100");
random_line_split
core.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use fnv::FnvHasher; use std::ops::Deref; use std::sync::Arc; use std::{fmt, hash}; use crate::externs; use crate::handles::Handle; use rule_graph; use smallvec::{smallvec, SmallVec}; ...
(id: Id, type_id: TypeId) -> Key { Key { id, type_id } } pub fn id(&self) -> Id { self.id } pub fn type_id(&self) -> &TypeId { &self.type_id } } /// /// A wrapper around a Arc<Handle> /// #[derive(Clone, Eq, PartialEq)] pub struct Value(Arc<Handle>); impl Value { pub fn new(handle: Handle) -...
new
identifier_name
core.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use fnv::FnvHasher; use std::ops::Deref; use std::sync::Arc; use std::{fmt, hash}; use crate::externs; use crate::handles::Handle; use rule_graph; use smallvec::{smallvec, SmallVec}; ...
} pub type Id = u64; // The type of a python object (which itself has a type, but which is not represented // by a Key, because that would result in a infinitely recursive structure.) #[repr(C)] #[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct TypeId(pub Id); impl TypeId { fn pretty_print(s...
{ write!(f, "{}", Self::display(self.0.iter())) }
identifier_body
core.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use fnv::FnvHasher; use std::ops::Deref; use std::sync::Arc; use std::{fmt, hash}; use crate::externs; use crate::handles::Handle; use rule_graph; use smallvec::{smallvec, SmallVec}; ...
fn hash<H: hash::Hasher>(&self, state: &mut H) { self.id.hash(state); } } impl fmt::Display for Key { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", externs::key_to_str(self)) } } impl Key { pub fn new(id: Id, type_id: TypeId) -> Key { Key { id, type_id } } pub f...
impl hash::Hash for Key {
random_line_split
abi.rs
//! RISC-V ABI implementation. //! //! This module implements the RISC-V calling convention through the primary `legalize_signature()` //! entry point. //! //! This doesn't support the soft-float ABI at the moment. use super::registers::{FPR, GPR}; use super::settings; use crate::abi::{legalize_args, ArgAction, ArgAss...
(_func: &ir::Function, isa_flags: &settings::Flags) -> RegisterSet { let mut regs = RegisterSet::new(); regs.take(GPR, GPR.unit(0)); // Hard-wired 0. // %x1 is the link register which is available for allocation. regs.take(GPR, GPR.unit(2)); // Stack pointer. regs.take(G...
allocatable_registers
identifier_name
abi.rs
//! RISC-V ABI implementation. //! //! This module implements the RISC-V calling convention through the primary `legalize_signature()` //! entry point. //! //! This doesn't support the soft-float ABI at the moment. use super::registers::{FPR, GPR}; use super::settings; use crate::abi::{legalize_args, ArgAction, ArgAss...
else { // Assign a stack location. let loc = ArgumentLoc::Stack(self.offset as i32); self.offset += u32::from(self.pointer_bytes); debug_assert!(self.offset <= i32::MAX as u32); loc.into() } } } /// Legalize `sig` for RISC-V. pub fn legalize_sign...
{ // Assign to a register. let reg = if ty.is_float() { FPR.unit(10 + self.regs as usize) } else { GPR.unit(10 + self.regs as usize) }; self.regs += 1; ArgumentLoc::Reg(reg).into() }
conditional_block
abi.rs
//! RISC-V ABI implementation. //! //! This module implements the RISC-V calling convention through the primary `legalize_signature()` //! entry point. //! //! This doesn't support the soft-float ABI at the moment. use super::registers::{FPR, GPR}; use super::settings; use crate::abi::{legalize_args, ArgAction, ArgAss...
} } /// Get register class for a type appearing in a legalized signature. pub fn regclass_for_abi_type(ty: Type) -> RegClass { if ty.is_float() { FPR } else { GPR } } pub fn allocatable_registers(_func: &ir::Function, isa_flags: &settings::Flags) -> RegisterSet { let mut regs = Re...
{ let bits = triple.pointer_width().unwrap().bits(); let mut args = Args::new(bits, isa_flags.enable_e()); legalize_args(&mut sig.params, &mut args); let mut rets = Args::new(bits, isa_flags.enable_e()); legalize_args(&mut sig.returns, &mut rets); if current { let ptr = Type::int(u16:...
identifier_body
abi.rs
//! RISC-V ABI implementation. //! //! This module implements the RISC-V calling convention through the primary `legalize_signature()` //! entry point. //! //! This doesn't support the soft-float ABI at the moment. use super::registers::{FPR, GPR}; use super::settings; use crate::abi::{legalize_args, ArgAction, ArgAss...
// TODO: %x8 is the frame pointer. Reserve it? // Remove %x16 and up for RV32E. if isa_flags.enable_e() { for u in 16..32 { regs.take(GPR, GPR.unit(u)); } } regs }
regs.take(GPR, GPR.unit(4)); // Thread pointer.
random_line_split
main.rs
#![crate_id = "spliced#0.1-pre"] #![license = "MIT"] #![crate_type = "bin"] extern crate green; extern crate rustuv; extern crate serialize; extern crate splice; use std::comm::{Disconnected, Empty}; use proto::{KeepAlive, OpenBuffer, OpenFile, RunCommand}; use proto::{Ack, Allow, Deny, Handle}; use proto::{RequestId...
(argc: int, argv: **u8) -> int { green::start(argc, argv, rustuv::event_loop, main) } fn main() { let cfg = splice::conf::load_default().unwrap(); let mut server = conn::Server::new( cfg.default_server_addr.as_slice(), cfg.default_server_port, None).unwrap(); loop { let raw_client = ser...
start
identifier_name
main.rs
#![crate_id = "spliced#0.1-pre"] #![license = "MIT"] #![crate_type = "bin"] extern crate green; extern crate rustuv; extern crate serialize; extern crate splice; use std::comm::{Disconnected, Empty}; use proto::{KeepAlive, OpenBuffer, OpenFile, RunCommand}; use proto::{Ack, Allow, Deny, Handle}; use proto::{RequestId...
cfg.default_server_addr.as_slice(), cfg.default_server_port, None).unwrap(); loop { let raw_client = server.accept(); spawn(proc() { match raw_client.ok() { Some(c) => { match c.negotiate().ok() { Some((down, mut up)) =>...
random_line_split
main.rs
#![crate_id = "spliced#0.1-pre"] #![license = "MIT"] #![crate_type = "bin"] extern crate green; extern crate rustuv; extern crate serialize; extern crate splice; use std::comm::{Disconnected, Empty}; use proto::{KeepAlive, OpenBuffer, OpenFile, RunCommand}; use proto::{Ack, Allow, Deny, Handle}; use proto::{RequestId...
fn main() { let cfg = splice::conf::load_default().unwrap(); let mut server = conn::Server::new( cfg.default_server_addr.as_slice(), cfg.default_server_port, None).unwrap(); loop { let raw_client = server.accept(); spawn(proc() { match raw_client.ok() { ...
{ green::start(argc, argv, rustuv::event_loop, main) }
identifier_body
power_set.rs
// Given a set, generate its power set, which is the set of all subsets of that // set: http://rosettacode.org/wiki/Power_set use std::vec::Vec; use std::slice::Items; // If set == {} // return {{}} // else if set == {a} U rest // return power_set(rest) U ({a} U each set in power_set(rest)) fn power_set<'a, T: Cl...
() { let mut set = Vec::<int>::new(); set.push(1); set.push(2); set.push(3); set.push(4); let power = power_set(&mut set.iter()); println!("Set : {}", set); println!("Power Set: {}", power); }
main
identifier_name
power_set.rs
// Given a set, generate its power set, which is the set of all subsets of that // set: http://rosettacode.org/wiki/Power_set use std::vec::Vec; use std::slice::Items; // If set == {} // return {{}} // else if set == {a} U rest // return power_set(rest) U ({a} U each set in power_set(rest)) fn power_set<'a, T: Cl...
}
random_line_split
power_set.rs
// Given a set, generate its power set, which is the set of all subsets of that // set: http://rosettacode.org/wiki/Power_set use std::vec::Vec; use std::slice::Items; // If set == {} // return {{}} // else if set == {a} U rest // return power_set(rest) U ({a} U each set in power_set(rest)) fn power_set<'a, T: Cl...
#[cfg(not(test))] fn main() { let mut set = Vec::<int>::new(); set.push(1); set.push(2); set.push(3); set.push(4); let power = power_set(&mut set.iter()); println!("Set : {}", set); println!("Power Set: {}", power); }
{ let set = Vec::<int>::new(); let power = power_set(&mut set.iter()); assert!(power == vec!(vec!())); let mut set = Vec::<int>::new(); set.push(1); set.push(2); set.push(3); let power = power_set(&mut set.iter()); assert!(power == vec!(vec!(), vec!(1), vec!(2), vec!(2, 1), ...
identifier_body
create.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::release_flow::{ hash_for_modules, load_artifact, save_release_artifact, verify::verify_payload_change, ReleaseArtifact, }; use anyhow::{bail, Result}; use diem_types::{ access_path::AccessPath, chain_id::ChainI...
pub(crate) fn create_release_writeset( remote_frameworks: &[CompiledModule], local_frameworks: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let remote_framework_map = remote_frameworks .iter() .map(|m| (m.self_id(), m)) .collect::<BTreeMap<_, _>>(); let remote_ids ...
{ let remote = JsonRpcDebuggerInterface::new(remote_url)?; let remote_modules = remote.get_diem_framework_modules_by_version(artifact.version)?; create_release_writeset(&remote_modules, release_modules) }
identifier_body
create.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::release_flow::{ hash_for_modules, load_artifact, save_release_artifact, verify::verify_payload_change, ReleaseArtifact, }; use anyhow::{bail, Result}; use diem_types::{ access_path::AccessPath, chain_id::ChainI...
( artifact: &ReleaseArtifact, remote_url: &str, release_modules: &[(Vec<u8>, CompiledModule)], ) -> Result<WriteSetPayload> { let remote = JsonRpcDebuggerInterface::new(remote_url)?; let remote_modules = remote.get_diem_framework_modules_by_version(artifact.version)?; create_release_writeset(&re...
create_release_from_artifact
identifier_name
create.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::release_flow::{ hash_for_modules, load_artifact, save_release_artifact, verify::verify_payload_change, ReleaseArtifact, }; use anyhow::{bail, Result}; use diem_types::{ access_path::AccessPath, chain_id::ChainI...
Ok(WriteSetPayload::Direct(ChangeSet::new( write_patch.freeze()?, vec![], ))) }
} None => write_patch.push((path, WriteOp::Deletion)), } }
random_line_split
parse_test.rs
extern crate mair; use std::fs::*; use std::path::{Path, PathBuf}; use std::io::{self, Read, Write}; use std::ffi::OsStr; use mair::parse::str_ptr_diff; use mair::parse::error::*; use mair::parse::lexer::*; use mair::parse::parser::*; use mair::parse::ast::*; fn test_dir_helper<P: AsRef<Path>, F: Fn(&mut Write, &str) ...
fn tts(input: &str) -> Result<Vec<TT>, UnmatchedDelimError> { let ltoks = lex(input).unwrap(); parse_tts(input, &ltoks) } fn parse(input: &str) -> (Mod, Vec<HardSyntaxError>) { let tts_ = tts(input).unwrap(); parse_crate(input, tts_) } #[test] fn parse_test() { test_dir_lines("lexer_unit", |f, s...
{ let mut v = vec![]; for c in Lexer::new(input) { v.push(c?); } Ok(v) }
identifier_body
parse_test.rs
extern crate mair; use std::fs::*; use std::path::{Path, PathBuf}; use std::io::{self, Read, Write}; use std::ffi::OsStr; use mair::parse::str_ptr_diff; use mair::parse::error::*; use mair::parse::lexer::*; use mair::parse::parser::*; use mair::parse::ast::*; fn test_dir_helper<P: AsRef<Path>, F: Fn(&mut Write, &str) ...
fn test_dir<F: Fn(&mut Write, &str) -> io::Result<()>>(dir: &str, f: F) { let mut path = PathBuf::new(); path.push("."); path.push("tests"); path.push(dir); match test_dir_helper(path, f) { Err(e) => panic!("os error: {:?}", e), Ok(false) => panic!("test fail"), Ok(true) => (...
random_line_split
parse_test.rs
extern crate mair; use std::fs::*; use std::path::{Path, PathBuf}; use std::io::{self, Read, Write}; use std::ffi::OsStr; use mair::parse::str_ptr_diff; use mair::parse::error::*; use mair::parse::lexer::*; use mair::parse::parser::*; use mair::parse::ast::*; fn test_dir_helper<P: AsRef<Path>, F: Fn(&mut Write, &str) ...
(input: &str) -> Result<Vec<TT>, UnmatchedDelimError> { let ltoks = lex(input).unwrap(); parse_tts(input, &ltoks) } fn parse(input: &str) -> (Mod, Vec<HardSyntaxError>) { let tts_ = tts(input).unwrap(); parse_crate(input, tts_) } #[test] fn parse_test() { test_dir_lines("lexer_unit", |f, s| { ...
tts
identifier_name
main.rs
extern crate num; use num::Float; /// Note: We cannot use `range_step` here because Floats don't implement /// the `CheckedAdd` trait. fn
<T, F>(f: F, start: T, stop: T, step: T, epsilon: T) -> Vec<T> where T: Copy + PartialOrd + Float, F: Fn(T) -> T, { let mut ret = vec![]; let mut current = start; while current < stop { if f(current).abs() < epsilon { ret.push(current); } current = current + step;...
find_roots
identifier_name
main.rs
extern crate num; use num::Float; /// Note: We cannot use `range_step` here because Floats don't implement /// the `CheckedAdd` trait. fn find_roots<T, F>(f: F, start: T, stop: T, step: T, epsilon: T) -> Vec<T> where T: Copy + PartialOrd + Float, F: Fn(T) -> T, { let mut ret = vec![]; let mut current ...
fn main() { let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0, 3.0, 0.0001, 0.00000001, ); println!("roots of f(x) = x^3 - 3x^2 + 2x are: {:?}", roots); }
{ let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0, 3.0, 0.0001, 0.00000001, ); let expected = [0.0f64, 1.0, 2.0]; for (&a, &b) in roots.iter().zip(expected.iter()) { assert!((a - b).abs() < 0.0001); } }
identifier_body
main.rs
extern crate num; use num::Float; /// Note: We cannot use `range_step` here because Floats don't implement /// the `CheckedAdd` trait. fn find_roots<T, F>(f: F, start: T, stop: T, step: T, epsilon: T) -> Vec<T> where T: Copy + PartialOrd + Float, F: Fn(T) -> T, { let mut ret = vec![]; let mut current ...
0.00000001, ); println!("roots of f(x) = x^3 - 3x^2 + 2x are: {:?}", roots); }
3.0, 0.0001,
random_line_split
main.rs
extern crate num; use num::Float; /// Note: We cannot use `range_step` here because Floats don't implement /// the `CheckedAdd` trait. fn find_roots<T, F>(f: F, start: T, stop: T, step: T, epsilon: T) -> Vec<T> where T: Copy + PartialOrd + Float, F: Fn(T) -> T, { let mut ret = vec![]; let mut current ...
current = current + step; } ret } #[test] fn test_find_roots() { let roots = find_roots( |x: f64| x * x * x - 3.0 * x * x + 2.0 * x, -1.0, 3.0, 0.0001, 0.00000001, ); let expected = [0.0f64, 1.0, 2.0]; for (&a, &b) in roots.iter().zip(expected.i...
{ ret.push(current); }
conditional_block
mod.rs
use std::io::{self, Write}; use std::collections::HashMap; mod parser; use nes::Nes; use self::parser::Command; pub struct Debugger<'a> { nes: Nes<'a>, pub breakpoints: HashMap<usize, usize>, } impl<'a> Debugger<'a> { pub fn init(nes: Nes<'a>) -> Self { let mut debugger = Debugger { ...
fn step(&mut self, num_steps: usize) { for _ in 0..num_steps { let opcode = self.nes.step(); print!("{:02X} {}", opcode, opcode_to_name(opcode)); println!("{:?}", self.nes.cpu); } } fn step_forever(&mut self) { self.nes.run(Some(&self.breakpoint...
{ self.nes.reset(); }
identifier_body
mod.rs
use std::io::{self, Write}; use std::collections::HashMap; mod parser; use nes::Nes; use self::parser::Command; pub struct Debugger<'a> { nes: Nes<'a>, pub breakpoints: HashMap<usize, usize>, } impl<'a> Debugger<'a> { pub fn init(nes: Nes<'a>) -> Self { let mut debugger = Debugger { ...
(&mut self, addr: usize) { if addr <= 0xFFFF { println!("M[${:04X}] = {:X}", addr, self.nes.cpu.fetch_byte(&mut self.nes.interconnect, addr as u16)); } else { println!("Invalid address: ${:X}", addr); } } fn print_range(&mut self, low_addr: usize, high_addr: usiz...
print
identifier_name
mod.rs
use std::io::{self, Write}; use std::collections::HashMap; mod parser; use nes::Nes; use self::parser::Command; pub struct Debugger<'a> { nes: Nes<'a>, pub breakpoints: HashMap<usize, usize>, } impl<'a> Debugger<'a> { pub fn init(nes: Nes<'a>) -> Self {
breakpoints: HashMap::new(), }; debugger.reset(); debugger } pub fn run(&mut self){ let mut next_key = 1; loop { print!("Gidget>"); io::stdout().flush().unwrap(); let mut input = String::new(); io::stdin().read...
let mut debugger = Debugger { nes: nes,
random_line_split
mod.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
( window: &mut Window, save_data: &mut SaveData, ) -> Mode { let view = { let visible_rect = window.visible_rect(); View::new( &mut window.resources(), visible_rect, &save_data.game_mut().shifting_ground, ) }; run_puzzle(window, save_data, ...
run_shifting_ground
identifier_name
mod.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
// ========================================================================= //
{ let view = { let visible_rect = window.visible_rect(); View::new( &mut window.resources(), visible_rect, &save_data.game_mut().shifting_ground, ) }; run_puzzle(window, save_data, view) }
identifier_body
mod.rs
// +--------------------------------------------------------------------------+ // | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> | // | | // | This file is part of System Syzygy. | ...
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | // | General Public License for details. | // | | // | You should have received a copy of the GNU General Public License along | ...
// | WITHOUT ANY WARRANTY; without even the implied warranty of |
random_line_split
mod.rs
mod test; use sourcefile::SourceFile as SourceFile; use dispatch::InvokeReceivier as InvokeReceivier; use dispatch::Dispatch as Dispatch; use dispatch::Invoke as Invoke; use type_name::TypeName as TypeName; use common::ParseError as ParseError; use arguments::Argument as Argument; pub fn compile_dispatch(dispatch: &...
fn compile_type_invoke(invoke: &Box<Invoke>, type_name: &Box<TypeName>, sourcefile: &Box<SourceFile>) -> Result<String, ParseError> { if! sourcefile.has_external(type_name.name.clone()) { return Err(ParseError::new_msg(&format!("Unkown type {}", type_name.canonical()))); } let external = sourcefil...
{ match dispatch.stack[0].receiver { Some(InvokeReceivier::Constant{ref value}) => panic!("not implemented"), Some(InvokeReceivier::InstanceObject{ref value}) => panic!("not implemented"), Some(InvokeReceivier::TypeObject{ref value}) => return compile_type_invoke(&dispatch.stack[0], &value, ...
identifier_body
mod.rs
mod test; use sourcefile::SourceFile as SourceFile; use dispatch::InvokeReceivier as InvokeReceivier; use dispatch::Dispatch as Dispatch; use dispatch::Invoke as Invoke; use type_name::TypeName as TypeName; use common::ParseError as ParseError; use arguments::Argument as Argument; pub fn compile_dispatch(dispatch: &...
output.push_str(&format!("{}.{}{}(", external.reference_name(), static_call_chain(&invoke), invoke.message_name())); output.push_str(&arguments(&invoke)); output.push_str(");"); return Ok(output); } return Ok("".to_string()); } fn static_call_chain(invoke: &Box<Invoke>) -> Strin...
if ! external.is_roo() { let mut output = "".to_string();
random_line_split
mod.rs
mod test; use sourcefile::SourceFile as SourceFile; use dispatch::InvokeReceivier as InvokeReceivier; use dispatch::Dispatch as Dispatch; use dispatch::Invoke as Invoke; use type_name::TypeName as TypeName; use common::ParseError as ParseError; use arguments::Argument as Argument; pub fn compile_dispatch(dispatch: &...
(invoke: &Box<Invoke>, type_name: &Box<TypeName>, sourcefile: &Box<SourceFile>) -> Result<String, ParseError> { if! sourcefile.has_external(type_name.name.clone()) { return Err(ParseError::new_msg(&format!("Unkown type {}", type_name.canonical()))); } let external = sourcefile.get_external(&type_nam...
compile_type_invoke
identifier_name
day6.rs
#[macro_use] extern crate derive_builder; #[derive(Clone, Debug)] struct
{ width: u32, height: u32, } impl Default for Resolution { fn default() -> Resolution { Resolution { width: 1920, height: 1080, } } } #[derive(Debug, Default, Builder)] #[builder(field(private), setter(into))] struct GameConfig { #[builder(default)] res...
Resolution
identifier_name
day6.rs
#[macro_use] extern crate derive_builder; #[derive(Clone, Debug)] struct Resolution { width: u32, height: u32, } impl Default for Resolution { fn default() -> Resolution { Resolution { width: 1920, height: 1080, } } } #[derive(Debug, Default, Builder)] #[builde...
resolution: Resolution, save_dir: Option<String>, #[builder(default)] autosave: bool, fov: f32, render_distance: u32, } fn main() { println!("24 Days of Rust vol. 2 - derive_builder"); let conf = GameConfigBuilder::default() .save_dir("saves".to_string()) .fov(70.0) ...
struct GameConfig { #[builder(default)]
random_line_split
progress.rs
use std::io::{Read, Result}; use std::time::{Duration, Instant}; pub struct Progress<R> { bytes: usize, tick: Instant, stream: R, } impl<R> Progress<R> { pub fn new(stream: R) -> Self { Progress { bytes: 0, tick: Instant::now() + Duration::from_millis(2000), ...
Ok(num) } } impl<R> Drop for Progress<R> { fn drop(&mut self) { errorf!("done ({} bytes)\n", self.bytes); } }
{ self.tick = now + Duration::from_millis(500); errorf!("downloading... {} bytes\n", self.bytes); }
conditional_block
progress.rs
use std::io::{Read, Result}; use std::time::{Duration, Instant}; pub struct Progress<R> { bytes: usize, tick: Instant, stream: R, } impl<R> Progress<R> {
pub fn new(stream: R) -> Self { Progress { bytes: 0, tick: Instant::now() + Duration::from_millis(2000), stream, } } } impl<R: Read> Read for Progress<R> { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { let num = self.stream.read(buf)?; ...
random_line_split
progress.rs
use std::io::{Read, Result}; use std::time::{Duration, Instant}; pub struct
<R> { bytes: usize, tick: Instant, stream: R, } impl<R> Progress<R> { pub fn new(stream: R) -> Self { Progress { bytes: 0, tick: Instant::now() + Duration::from_millis(2000), stream, } } } impl<R: Read> Read for Progress<R> { fn read(&mut sel...
Progress
identifier_name
tile.rs
use colors; use pixset; use pixset::PixLike; use std::default::Default; #[derive(Clone, Copy, Debug, Default)] pub struct
<P: PixLike> { pub fg: colors::Rgb, pub bg: colors::Rgb, pub pix: P, } // TODO default? impl<P> Tile<P> where P: pixset::PixLike, { pub fn new() -> Self { Tile { fg: *colors::BLACK, bg: *colors::BLACK, pix: Default::default(), } } pub fn ...
Tile
identifier_name
tile.rs
use colors; use pixset; use pixset::PixLike; use std::default::Default; #[derive(Clone, Copy, Debug, Default)] pub struct Tile<P: PixLike> { pub fg: colors::Rgb, pub bg: colors::Rgb, pub pix: P, } // TODO default?
impl<P> Tile<P> where P: pixset::PixLike, { pub fn new() -> Self { Tile { fg: *colors::BLACK, bg: *colors::BLACK, pix: Default::default(), } } pub fn make(fg: colors::Rgb, bg: colors::Rgb, pix: P) -> Self { Tile { fg: fg, ...
random_line_split
tile.rs
use colors; use pixset; use pixset::PixLike; use std::default::Default; #[derive(Clone, Copy, Debug, Default)] pub struct Tile<P: PixLike> { pub fg: colors::Rgb, pub bg: colors::Rgb, pub pix: P, } // TODO default? impl<P> Tile<P> where P: pixset::PixLike, { pub fn new() -> Self { Tile { ...
pub fn clear(&mut self) { // TODO gross let t = Tile::new(); self.fg = t.fg; self.bg = t.bg; self.pix = t.pix; } }
{ Tile { fg: fg, bg: bg, pix: pix, } }
identifier_body
load.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
for plugin in plugins { // plugins must have a name and can't be key = value match plugin.name() { Some(name) if!plugin.is_value_str() => { let args = plugin.meta_item_list().map(ToOwned::to_owned); loader.lo...
{ let mut loader = PluginLoader::new(sess, cstore, crate_name); // do not report any error now. since crate attributes are // not touched by expansion, every use of plugin without // the feature enabled will result in an error later... if sess.features_untracked().plugin { for attr in &krat...
identifier_body
load.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
<'a> { sess: &'a Session, reader: CrateLoader<'a>, plugins: Vec<PluginRegistrar>, } fn call_malformed_plugin_attribute(a: &Session, b: Span) { span_err!(a, b, E0498, "malformed plugin attribute"); } /// Read plugin metadata and dynamically load registrar functions. pub fn load_plugins(sess: &Session, ...
PluginLoader
identifier_name
load.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} fn load_plugin(&mut self, span: Span, name: &str, args: Vec<ast::NestedMetaItem>) { let registrar = self.reader.find_plugin_registrar(span, name); if let Some((lib, disambiguator)) = registrar { let symbol = self.sess.generate_plugin_registrar_symbol(disambiguator); l...
plugins: vec![], }
random_line_split
load.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} // Dynamically link a registrar function into the compiler process. fn dylink_registrar(&mut self, span: Span, path: PathBuf, symbol: String) -> PluginRegistrarFun { use rustc_metadata::dynamic_lib::DynamicLibrary; ...
{ let symbol = self.sess.generate_plugin_registrar_symbol(disambiguator); let fun = self.dylink_registrar(span, lib, symbol); self.plugins.push(PluginRegistrar { fun, args, }); }
conditional_block
bracket-push.rs
extern crate bracket_push; use bracket_push::*; #[test] fn paired_square_brackets() { assert!(Brackets::from("[]").are_balanced()); } #[test] fn empty_string() { assert!(Brackets::from("").are_balanced()); } #[test] fn unpaired_brackets() { assert!(!Brackets::from("[[").are_balanced()); } #[test] fn wr...
#[test] fn wrong_closing_bracket() { assert!(!Brackets::from("{]").are_balanced()); } #[test] fn paired_with_whitespace() { assert!(Brackets::from("{ }").are_balanced()); } #[test] fn simple_nested_brackets() { assert!(Brackets::from("{[]}").are_balanced()); } #[test] fn several_paired_brackets() { ...
{ assert!(!Brackets::from("}{").are_balanced()); }
identifier_body
bracket-push.rs
extern crate bracket_push; use bracket_push::*; #[test] fn paired_square_brackets() { assert!(Brackets::from("[]").are_balanced()); } #[test] fn empty_string() { assert!(Brackets::from("").are_balanced()); } #[test] fn unpaired_brackets() { assert!(!Brackets::from("[[").are_balanced()); } #[test] fn wr...
() { assert!(!Brackets::from("[({]})").are_balanced()); } #[test] fn math_expression() { assert!(Brackets::from("(((185 + 223.85) * 15) - 543)/2").are_balanced()); } #[test] fn complex_latex_expression() { let input = "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \ ...
paired_and_wrong_nested_brackets
identifier_name
bracket-push.rs
extern crate bracket_push; use bracket_push::*;
assert!(Brackets::from("[]").are_balanced()); } #[test] fn empty_string() { assert!(Brackets::from("").are_balanced()); } #[test] fn unpaired_brackets() { assert!(!Brackets::from("[[").are_balanced()); } #[test] fn wrong_ordered_brackets() { assert!(!Brackets::from("}{").are_balanced()); } #[test] f...
#[test] fn paired_square_brackets() {
random_line_split