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
mode.rs
use state::State; use std::marker::PhantomData; use typeahead::Parse; pub trait Transition<K> where K: Ord, K: Copy, K: Parse, { fn name(&self) -> &'static str; fn transition(&self, state: &mut State<K>) -> Mode<K>; } #[derive(Clone, Copy, Debug)] pub struct NormalMode<K> { t: PhantomData<K>, ...
pub fn insert<K>() -> Mode<K> { Mode::Insert(InsertMode::<K> { t: PhantomData::<K> {}, replace_mode: false, }) } pub fn replace<K>() -> Mode<K> { Mode::Insert(InsertMode::<K> { t: PhantomData::<K> {}, replace_mode: true, }) } impl<K> Transition<K> for Mode<K> where ...
{ Mode::Pending(PendingMode::<K> { t: PhantomData::<K> {}, next_mode: orig.next_mode, }) }
identifier_body
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum ...
} } fn start(&mut self, rx: Receiver<CommandMapperDispatch>) { for m in rx.iter() { match m.command().token { CMD_WSERVER => self.handle_wserver(&m), _ => () } } } } pub struct WserverPlugin { sender: Option<SyncSender<Co...
{ m.reply(&format!("Error: {:?}", err)); }
conditional_block
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum ...
(&mut self) { let (tx, rx) = sync_channel(10); let _ = ::std::thread::Builder::new().name("plugin-wserver".to_string()).spawn(move || { let mut internal_state = WserverInternalState::new(); internal_state.start(rx); }); self.sender = Some(tx); } fn dispat...
start
identifier_name
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum ...
}
{ match self.sender { Some(ref sender) => { if let Err(err) = sender.send(m.clone()) { m.reply(&format!("Service ``wserver'' unavailable: {:?}", err)); } } None => () } }
identifier_body
wserver.rs
use std::convert::From; use std::sync::mpsc::{sync_channel, SyncSender, Receiver}; use hyper; use hyper::header::Server; use irc::IrcMsg; use command_mapper::{ RustBotPlugin, CommandMapperDispatch, IrcBotConfigurator, Format, Token, }; const CMD_WSERVER: Token = Token(0); #[derive(Debug)] enum ...
} pub fn get_plugin_name() -> &'static str { "wserver" } } impl RustBotPlugin for WserverPlugin { fn configure(&mut self, configurator: &mut IrcBotConfigurator) { configurator.map_format(CMD_WSERVER, Format::from_str("wserver {host:s}").unwrap()); } fn start(&mut self) { ...
sender: None }
random_line_split
material.rs
use std::io::{Cursor, Read}; use anyhow::Error; use image::{self, GenericImage, GenericImageView}; use zip::ZipArchive; use cache::{AssetLoadContext, GeneratedAsset, WebAsset}; use srgb::{LINEAR_TO_SRGB, SRGB_TO_LINEAR}; #[derive(Clone, Copy)] pub enum MaterialType { Dirt = 0, Grass = 1, GrassRocky = 2, ...
struct MaterialTypeRaw(MaterialType); impl WebAsset for MaterialTypeRaw { type Type = MaterialRaw; fn url(&self) -> String { match self.0 { _ => "https://opengameart.org/sites/default/files/terrain_0.zip", }.to_owned() } fn filename(&self) -> String { let name = ma...
}
random_line_split
material.rs
use std::io::{Cursor, Read}; use anyhow::Error; use image::{self, GenericImage, GenericImageView}; use zip::ZipArchive; use cache::{AssetLoadContext, GeneratedAsset, WebAsset}; use srgb::{LINEAR_TO_SRGB, SRGB_TO_LINEAR}; #[derive(Clone, Copy)] pub enum MaterialType { Dirt = 0, Grass = 1, GrassRocky = 2, ...
(&self) -> String { match self.0 { _ => "https://opengameart.org/sites/default/files/terrain_0.zip", }.to_owned() } fn filename(&self) -> String { let name = match self.0 { _ => "terrain.zip", }; format!("materials/raw/{}", name) } fn par...
url
identifier_name
uri.rs
//! HTTP RequestUris use std::str::FromStr; use url::Url; use url::ParseError as UrlError; use error::HttpError; /// The Request-URI of a Request's StartLine. /// /// From Section 5.3, Request Target: /// > Once an inbound connection is obtained, the client sends an HTTP /// > request message (Section 3) with a reque...
(s: &str) -> Result<RequestUri, HttpError> { match s.as_bytes() { [] => Err(HttpError::HttpUriError(UrlError::InvalidCharacter)), [b'*'] => Ok(RequestUri::Star), [b'/',..] => Ok(RequestUri::AbsolutePath(s.to_string())), bytes if bytes.contains(&b'/') => { ...
from_str
identifier_name
uri.rs
//! HTTP RequestUris use std::str::FromStr; use url::Url; use url::ParseError as UrlError; use error::HttpError; /// The Request-URI of a Request's StartLine. /// /// From Section 5.3, Request Target: /// > Once an inbound connection is obtained, the client sends an HTTP /// > request message (Section 3) with a reque...
/// > /// > ```notrust /// > request-target = origin-form /// > / absolute-form /// > / authority-form /// > / asterisk-form /// > ``` #[derive(Debug, PartialEq, Clone)] pub enum RequestUri { /// The most common request target, an absolute path and optional query. //...
/// > target URI. There are four distinct formats for the request-target, /// > depending on both the method being requested and whether the request /// > is to a proxy.
random_line_split
uri.rs
//! HTTP RequestUris use std::str::FromStr; use url::Url; use url::ParseError as UrlError; use error::HttpError; /// The Request-URI of a Request's StartLine. /// /// From Section 5.3, Request Target: /// > Once an inbound connection is obtained, the client sends an HTTP /// > request message (Section 3) with a reque...
} } } #[test] fn test_uri_fromstr() { use error::HttpResult; fn read(s: &str, result: HttpResult<RequestUri>) { assert_eq!(s.parse(), result); } read("*", Ok(RequestUri::Star)); read("http://hyper.rs/", Ok(RequestUri::AbsoluteUri(Url::parse("http://hyper.rs/").unwrap()))); ...
{ let mut temp = "http://".to_string(); temp.push_str(s); try!(Url::parse(&temp[..])); todo!("compare vs u.authority()"); Ok(RequestUri::Authority(s.to_string())) }
conditional_block
shape.rs
use inflector::Inflector; use linked_hash_map::LinkedHashMap; use serde_json::{json, Value}; use crate::options::Options; use crate::shape::{self, Shape}; #[allow(dead_code)] pub struct Ctxt { options: Options, } pub type Ident = String; pub type Code = String; pub fn shape_string(name: &str, shape: &Shape, opt...
if folded == Any && shapes.iter().any(|s| s!= &Any) { generate_tuple_type(ctxt, path, shapes) } else { generate_vec_type(ctxt, path, &folded) } } VecT { elem_type: ref e } => generate_vec_type(ctxt, path, e), Struct { fields: re...
let folded = shape::fold_shapes(shapes.clone());
random_line_split
shape.rs
use inflector::Inflector; use linked_hash_map::LinkedHashMap; use serde_json::{json, Value}; use crate::options::Options; use crate::shape::{self, Shape}; #[allow(dead_code)] pub struct
{ options: Options, } pub type Ident = String; pub type Code = String; pub fn shape_string(name: &str, shape: &Shape, options: Options) -> (Ident, Option<Code>) { let mut ctxt = Ctxt { options }; let ident = "".to_string(); let value = type_from_shape(&mut ctxt, name, shape); let code = ::serde...
Ctxt
identifier_name
shape.rs
use inflector::Inflector; use linked_hash_map::LinkedHashMap; use serde_json::{json, Value}; use crate::options::Options; use crate::shape::{self, Shape}; #[allow(dead_code)] pub struct Ctxt { options: Options, } pub type Ident = String; pub type Code = String; pub fn shape_string(name: &str, shape: &Shape, opt...
fn collapse_option(typ: &Shape) -> (bool, &Shape) { if let Shape::Optional(inner) = typ { return (true, &**inner); } (false, typ) } fn generate_struct_from_field_shapes( ctxt: &mut Ctxt, _path: &str, map: &LinkedHashMap<String, Shape>, ) -> Value { let mut properties = json!({}); ...
{ let mut types = Vec::new(); for shape in shapes { let typ = type_from_shape(ctxt, path, shape); types.push(typ); } json!({ "__type__": "tuple", "items": types, }) }
identifier_body
auth.rs
use base64::{decode_config, URL_SAFE}; use hyper::header; use std::{net::SocketAddr, str}; use crate::{ base::{ctx::Ctx, middleware::MiddleWare, response, HeaderGetStr, Request, Response}, config::Auth, handlers::method_maybe_proxy, }; #[derive(Debug, Clone)] pub struct Authenticator { auth: Auth, } ...
let www = req.headers().get_str(authorization); let auth = match www_base64_to_auth(www) { Ok(a) => a, Err(e) => return Err(f(e)), }; debug!("addr: {}, www: {}, auth: {:?}", addr, www, auth); if auth!= self.auth { return Err(f("wrong username...
{ // info!("url: {:?}", req.uri()); // info!("header: {:?}", req.headers()); let method_is_proxy = method_maybe_proxy(req).is_some(); let (authorization, code, authenticate) = if method_is_proxy { (header::PROXY_AUTHORIZATION, 407, header::PROXY_AUTHENTICATE) } else...
identifier_body
auth.rs
use base64::{decode_config, URL_SAFE}; use hyper::header; use std::{net::SocketAddr, str}; use crate::{ base::{ctx::Ctx, middleware::MiddleWare, response, HeaderGetStr, Request, Response}, config::Auth, handlers::method_maybe_proxy, }; #[derive(Debug, Clone)] pub struct Authenticator { auth: Auth, } ...
(value: &str) -> Result<Auth, &'static str> { let value = value.trim(); if value.len() <= "basic".len() || value[0.."basic".len()].to_lowercase()!= "basic" { return Err("not basic"); } let value = (&value["basic".len()..]).trim(); decode_config(value, URL_SAFE) .map_err(|_| "invali...
www_base64_to_auth
identifier_name
auth.rs
use base64::{decode_config, URL_SAFE}; use hyper::header; use std::{net::SocketAddr, str}; use crate::{ base::{ctx::Ctx, middleware::MiddleWare, response, HeaderGetStr, Request, Response}, config::Auth, handlers::method_maybe_proxy, }; #[derive(Debug, Clone)] pub struct Authenticator { auth: Auth,
impl Authenticator { pub fn new(auth: Auth) -> Self { Self { auth } } } // https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication // HTTP/1.0 401 Authorization Required // WWW-Authenticate: Basic realm="Secure Area" // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ== // tips: base64encode(...
}
random_line_split
lib.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
trivial_numeric_casts, unstable_features, unused_allocation, unused_import_braces, unused_imports, unused_must_use, unused_mut, unused_qualifications, while_true, )] extern crate filters; extern crate chrono; extern crate toml; extern crate toml_query; #[macro_use] extern crate lazy...
path_statements,
random_line_split
cryptocurrency-migration.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
() -> anyhow::Result<()> { exonum::helpers::init_logger()?; NodeBuilder::new() .with(Spec::new(OldService).with_default_instance()) .with(JustFactory::migrating(CryptocurrencyService)) .run() .await }
main
identifier_name
cryptocurrency-migration.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
async fn main() -> anyhow::Result<()> { exonum::helpers::init_logger()?; NodeBuilder::new() .with(Spec::new(OldService).with_default_instance()) .with(JustFactory::migrating(CryptocurrencyService)) .run() .await }
use exonum_cryptocurrency_advanced::CryptocurrencyService; use old_cryptocurrency::contracts::CryptocurrencyService as OldService; #[tokio::main]
random_line_split
cryptocurrency-migration.rs
// Copyright 2020 The Exonum Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
{ exonum::helpers::init_logger()?; NodeBuilder::new() .with(Spec::new(OldService).with_default_instance()) .with(JustFactory::migrating(CryptocurrencyService)) .run() .await }
identifier_body
typedrw.rs
use std::mem; // use core::raw::Slice as RawSlice; use mmap::MapOption::{MapReadable, MapFd}; use mmap::MemoryMap; use std::os::unix::prelude::AsRawFd; use std::slice; use std::ops; use std::fs::File; use std::marker::PhantomData; pub struct TypedMemoryMap<T:Copy> { map: MemoryMap, // mapped file len: ...
// })} unsafe { slice::from_raw_parts(self.map.data() as *const T, self.len) } } }
random_line_split
typedrw.rs
use std::mem; // use core::raw::Slice as RawSlice; use mmap::MapOption::{MapReadable, MapFd}; use mmap::MemoryMap; use std::os::unix::prelude::AsRawFd; use std::slice; use std::ops; use std::fs::File; use std::marker::PhantomData; pub struct TypedMemoryMap<T:Copy> { map: MemoryMap, // mapped file len: ...
(filename: String) -> TypedMemoryMap<T> { let file = File::open(filename).unwrap(); let size = file.metadata().unwrap().len() as usize; TypedMemoryMap { map: MemoryMap::new(size, &[MapReadable, MapFd(file.as_raw_fd())]).unwrap(), len: size / mem::size_of::<T>(), ...
new
identifier_name
function.rs
use ast::{Node, Loc, IdentifierNode, ExpressionNode}; use ast::{BlockNode, Statement, PatternList, PropertyKey}; pub trait Name<'ast>: Copy { fn empty() -> Self; } #[derive(Debug, PartialEq, Clone, Copy)] pub struct EmptyName; #[derive(Debug, PartialEq, Clone, Copy)] pub struct MandatoryName<'ast>(pub Identifier...
pub type Method<'ast> = Function<'ast, EmptyName>; impl<'ast> Name<'ast> for EmptyName { fn empty() -> Self { EmptyName } } impl<'ast> Name<'ast> for MandatoryName<'ast> { fn empty() -> Self { MandatoryName(Node::new(&Loc { start: 0, end: 0, item: "" ...
#[derive(Debug, PartialEq, Clone, Copy)] pub struct OptionalName<'ast>(pub Option<IdentifierNode<'ast>>);
random_line_split
function.rs
use ast::{Node, Loc, IdentifierNode, ExpressionNode}; use ast::{BlockNode, Statement, PatternList, PropertyKey}; pub trait Name<'ast>: Copy { fn empty() -> Self; } #[derive(Debug, PartialEq, Clone, Copy)] pub struct EmptyName; #[derive(Debug, PartialEq, Clone, Copy)] pub struct MandatoryName<'ast>(pub Identifier...
() -> Self { MandatoryName(Node::new(&Loc { start: 0, end: 0, item: "" })) } } impl<'ast> Name<'ast> for OptionalName<'ast> { fn empty() -> Self { OptionalName(None) } } #[cfg(test)] impl<'ast> From<IdentifierNode<'ast>> for MandatoryName<'ast> {...
empty
identifier_name
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal;...
term.set_foreground( Colour::def_yellow() ); let _ = write!(&mut term, " {}\n", ::syscalls::get_text_info(::syscalls::TEXTINFO_KERNEL, 1, &mut buf)); // Kernel 1: Build line term.set_foreground( Colour::white() ); let _ = write!(&mut term, "Simple console\n"); } window.show(); // Initial prompt term.write...
{ use syscalls::gui::{Group,Window}; use syscalls::threads::{S_THIS_PROCESS,ThisProcessWaits}; ::syscalls::threads::wait(&mut [S_THIS_PROCESS.get_wait(ThisProcessWaits::new().recv_obj())], !0); ::syscalls::gui::set_group( S_THIS_PROCESS.receive_object::<Group>(0).unwrap() ); // Create maximised window let wind...
identifier_body
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal;...
fn main() { use syscalls::gui::{Group,Window}; use syscalls::threads::{S_THIS_PROCESS,ThisProcessWaits}; ::syscalls::threads::wait(&mut [S_THIS_PROCESS.get_wait(ThisProcessWaits::new().recv_obj())],!0); ::syscalls::gui::set_group( S_THIS_PROCESS.receive_object::<Group>(0).unwrap() ); // Create maximised window ...
use std::fmt::Write;
random_line_split
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal;...
, }; let mut buf = [0; 256]; loop { let name_bytes = match handle.read_ent(&mut buf) { Ok(v) => v, Err(e) => { print!(term, "Read error: {:?}", e); return ; }, }; if name_bytes == b"" { break ; } let name = ::std::str::from_utf8(name_bytes).expect("Filename not utf-8"); print!(t...
{ print!(term, "Unable to open '{}': {:?}", path, e); return ; }
conditional_block
main.rs
// Tifflin OS - simple_console // - By John Hodge (thePowersGang) // // Simplistic console, used as a quick test case (fullscreen window) #![feature(const_fn)] #[macro_use] extern crate syscalls; extern crate cmdline_words_parser; use syscalls::Object; use syscalls::gui::Colour; mod terminal_surface; mod terminal;...
(&mut self, term: &mut terminal::Terminal, mut cmdline: String) { use cmdline_words_parser::StrExt; let mut args = cmdline.parse_cmdline_words(); match args.next() { None => {}, // 'pwd' - Print working directory Some("pwd") => print!(term, "/{}", self.cwd_rel), // 'cd' - Change directory Some("cd") ...
handle_command
identifier_name
tabs.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
pub fn next(&self, n: i32, start: u32) -> u32 { let mut end = start; if n > 0 { while end < self.cols { end += 1; if self.get(end) { break; } } } else { while end!= 0 { end -= 1; if self.get(end) { break; } } } if end == self.cols &&!self.get(end) { star...
self.inner.clear() }
identifier_body
tabs.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
ols: u32, rows: u32) -> Self { Tabs { cols: cols, rows: rows, inner: BitVec::from_fn(cols as usize, |i| i % 8 == 0) } } pub fn resize(&mut self, cols: u32, rows: u32) { self.inner.grow(cols as usize, false); if cols > self.cols { for i in (self.cols.. cols).filter(|i| i % 8 == 0) { self.inn...
w(c
identifier_name
tabs.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
self.cols = cols; self.rows = rows; } pub fn set(&mut self, x: u32, value: bool) { self.inner.set(x as usize, value); } pub fn get(&self, x: u32) -> bool { self.inner.get(x as usize).unwrap_or(false) } pub fn clear(&mut self) { self.inner.clear() } pub fn next(&self, n: i32, start: u32) -> u32 { ...
for i in (self.cols .. cols).filter(|i| i % 8 == 0) { self.inner.set(i as usize, true); } }
conditional_block
tabs.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer 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 // (a...
if n > 0 { while end < self.cols { end += 1; if self.get(end) { break; } } } else { while end!= 0 { end -= 1; if self.get(end) { break; } } } if end == self.cols &&!self.get(end) { start } else { end } } }
random_line_split
operator-multidispatch.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
// points can be added, and a point can be added to an integer. use std::ops; #[derive(Show,PartialEq,Eq)] struct Point { x: int, y: int } impl ops::Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point {x: self.x + other.x, y: self.y + other.y} } } impl ops::...
// <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. // Test that we can overload the `+` operator for points so that two
random_line_split
operator-multidispatch.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, other: int) -> Point { Point {x: self.x + other, y: self.y + other} } } pub fn main() { let mut p = Point {x: 10, y: 20}; p = p + Point {x: 101, y: 102}; assert_eq!(p, Point {x: 111, y: 122}); p = p + 1; assert_eq!(p, Point {x: 112, y: 123}); }
add
identifier_name
operator-multidispatch.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 main() { let mut p = Point {x: 10, y: 20}; p = p + Point {x: 101, y: 102}; assert_eq!(p, Point {x: 111, y: 122}); p = p + 1; assert_eq!(p, Point {x: 112, y: 123}); }
{ Point {x: self.x + other, y: self.y + other} }
identifier_body
alg_runner.rs
use std::collections::HashMap; use network::{ DoubleVec, Network, NodeId }; use network::algorithms::{ dijkstra, pagerank }; use usage::{ DEFAULT_BETA, DEFAULT_EPS, DEFAULT_START_ID, Args }; #[derive(Debug, RustcDecodable)] pub enum Algorithm { dijkstra, pagerank } pub fn run_algorithm<N: Network>(network: &N, args:...
} fn print_dijkstra_result(pred: &Vec<NodeId>, cost: &DoubleVec, node_to_id: &HashMap<String, NodeId>) { let id_to_node: HashMap<NodeId, String> = node_to_id.iter() .map(|(k,v)| (*v,k.clone())) .collect(); for i in (0..pred.len()).take(100) { let to_id = i as NodeId; let from_node...
random_line_split
alg_runner.rs
use std::collections::HashMap; use network::{ DoubleVec, Network, NodeId }; use network::algorithms::{ dijkstra, pagerank }; use usage::{ DEFAULT_BETA, DEFAULT_EPS, DEFAULT_START_ID, Args }; #[derive(Debug, RustcDecodable)] pub enum
{ dijkstra, pagerank } pub fn run_algorithm<N: Network>(network: &N, args: &Args, node_to_id: &HashMap<String, NodeId>) { match args.arg_algorithm { Algorithm::dijkstra => run_dijkstra(network, args, node_to_id), Algorithm::pagerank => run_pagerank(network, args, node_to_id), } } fn run_dijks...
Algorithm
identifier_name
alg_runner.rs
use std::collections::HashMap; use network::{ DoubleVec, Network, NodeId }; use network::algorithms::{ dijkstra, pagerank }; use usage::{ DEFAULT_BETA, DEFAULT_EPS, DEFAULT_START_ID, Args }; #[derive(Debug, RustcDecodable)] pub enum Algorithm { dijkstra, pagerank } pub fn run_algorithm<N: Network>(network: &N, args:...
fn print_pagerank_results(ranks: &Vec<f64>, node_to_id: &HashMap<String, NodeId>, target_node: Option<&String>) { match target_node { None => println!("No target node given."), Some(name) => { let id = node_to_id[name] as usize; println!("Rank of node {}: {} ({:e})", name, ...
{ let id_to_node: HashMap<NodeId, String> = node_to_id.iter() .map(|(k,v)| (*v,k.clone())) .collect(); for i in (0..pred.len()).take(100) { let to_id = i as NodeId; let from_node = get_node_name(pred.get(i).unwrap(), &id_to_node); let to_node = get_node_name(&to_id, &id_t...
identifier_body
syntax_extension_with_dll_deps_2.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 ...
fn expand_foo(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { let answer = other::the_answer(); MacEager::expr(quote_expr!(cx, $answer)) }
#[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("foo", expand_foo); }
random_line_split
syntax_extension_with_dll_deps_2.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 answer = other::the_answer(); MacEager::expr(quote_expr!(cx, $answer)) }
identifier_body
syntax_extension_with_dll_deps_2.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 ...
(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { let answer = other::the_answer(); MacEager::expr(quote_expr!(cx, $answer)) }
expand_foo
identifier_name
ui_ffi.rs
// Disable this warning until all code has been fixed #[allow(non_upper_case_globals)] extern crate bitflags; use std::os::raw::{c_char, c_float, c_int, c_uint, c_ushort, c_void}; use scintilla::PDUISCInterface; include!("ui_ffi_autogen.rs"); #[repr(C)] pub enum
{ Tab, // for tabbing through fields LeftArrow, // for text edit RightArrow,// for text edit UpArrow, // for text edit DownArrow, // for text edit PageUp, PageDown, Home, // for text edit End, // for text edit Delete, // for text edit Backspace, // for ...
ImguiKey
identifier_name
ui_ffi.rs
// Disable this warning until all code has been fixed #[allow(non_upper_case_globals)] extern crate bitflags; use std::os::raw::{c_char, c_float, c_int, c_uint, c_ushort, c_void}; use scintilla::PDUISCInterface; include!("ui_ffi_autogen.rs"); #[repr(C)] pub enum ImguiKey { Tab, // for tabbing through fiel...
Z, // for text edit CTRL+Z: undo }
C, // for text edit CTRL+C: copy V, // for text edit CTRL+V: paste X, // for text edit CTRL+X: cut Y, // for text edit CTRL+Y: redo
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/. */ #![feature(append)] #![feature(arc_unique)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_r...
#![feature(vec_push_all)] #![deny(unsafe_code)] #![allow(non_snake_case)] #![doc="The script crate contains all matters DOM."] #![plugin(string_cache_plugin)] #![plugin(plugins)] #[macro_use] extern crate log; #[macro_use] extern crate bitflags; extern crate core; extern crate devtools_traits; extern crate csspars...
#![feature(slice_chars)] #![feature(str_utf16)] #![feature(unicode)]
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/. */ #![feature(append)] #![feature(arc_unique)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_r...
() { unsafe { assert_eq!(js::jsapi::JS_Init(), 1); } }
init
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/. */ #![feature(append)] #![feature(arc_unique)] #![feature(as_unsafe_cell)] #![feature(borrow_state)] #![feature(box_r...
{ unsafe { assert_eq!(js::jsapi::JS_Init(), 1); } }
identifier_body
webgluniformlocation.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLUn...
(&self) -> i32 { self.id } pub fn program_id(&self) -> WebGLProgramId { self.program_id } }
id
identifier_name
webgluniformlocation.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/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLUn...
pub fn id(&self) -> i32 { self.id } pub fn program_id(&self) -> WebGLProgramId { self.program_id } }
{ reflect_dom_object(box WebGLUniformLocation::new_inherited(id, program_id), global, WebGLUniformLocationBinding::Wrap) }
identifier_body
problem-039.rs
// Copyright 2016 Peter Beard // Distributed under the GNU GPL v2. For full terms, see the LICENSE file. // // If p is the perimeter of a right angle triangle with integral length sides, // {a,b,c}, there are exactly three solutions for p = 120. // // {20,48,52}, {24,45,51}, {30,40,50} // // For which value of p ≤ 10...
pub fn solution() -> u32 { let mut max = 0; let mut max_p = 0; for p in 1..1001 { // Perimeter will always be even if p % 2!= 0 { continue; } let count = num_triangles(p); if count > max { max = count; max_p = p; } } ...
let mut count = 0; let psq = p*p; // a^2 + b^2 = c^2, a + b + c = p; substitute c = p - a - b and rearrange // solutions must satisfy 2p(a+b) = p^2 + ab // TODO: This can probably be simplified further, but algebra for a in 1..p { for b in 1..p { if 2*p*(a + b) == psq + a*b {...
identifier_body
problem-039.rs
// Copyright 2016 Peter Beard // Distributed under the GNU GPL v2. For full terms, see the LICENSE file. // // If p is the perimeter of a right angle triangle with integral length sides, // {a,b,c}, there are exactly three solutions for p = 120. // // {20,48,52}, {24,45,51}, {30,40,50} // // For which value of p ≤ 10...
} } } count } pub fn solution() -> u32 { let mut max = 0; let mut max_p = 0; for p in 1..1001 { // Perimeter will always be even if p % 2!= 0 { continue; } let count = num_triangles(p); if count > max { max = count;...
if 2*p*(a + b) == psq + a*b { count += 1;
random_line_split
problem-039.rs
// Copyright 2016 Peter Beard // Distributed under the GNU GPL v2. For full terms, see the LICENSE file. // // If p is the perimeter of a right angle triangle with integral length sides, // {a,b,c}, there are exactly three solutions for p = 120. // // {20,48,52}, {24,45,51}, {30,40,50} // // For which value of p ≤ 10...
{ println!("p = {} has the maximum number of solutions.", solution()); } #[cfg(test)] mod tests { use super::*; use test::Bencher; #[test] fn correct() { assert_eq!(840, solution()); } #[bench] fn bench(b: &mut Bencher) { b.iter(|| solution()); } }
in()
identifier_name
problem-039.rs
// Copyright 2016 Peter Beard // Distributed under the GNU GPL v2. For full terms, see the LICENSE file. // // If p is the perimeter of a right angle triangle with integral length sides, // {a,b,c}, there are exactly three solutions for p = 120. // // {20,48,52}, {24,45,51}, {30,40,50} // // For which value of p ≤ 10...
} } count } pub fn solution() -> u32 { let mut max = 0; let mut max_p = 0; for p in 1..1001 { // Perimeter will always be even if p % 2!= 0 { continue; } let count = num_triangles(p); if count > max { max = count; ma...
count += 1; }
conditional_block
sub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty:...
random_line_split
sub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a>(&'a self) -> Lub<'a> { Lub(*self.get_ref()) } fn glb<'a>(&'a self) -> Glb<'a> { Glb(*self.get_ref()) } fn contratys(&self, a: ty::t, b: ty::t) -> cres<ty::t> { let opp = CombineFields { a_is_expected:!self.get_ref().a_is_expected,.. *self.get_ref() }; Sub(opp).tys(b, a)...
lub
identifier_name
sub.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn glb<'a>(&'a self) -> Glb<'a> { Glb(*self.get_ref()) } fn contratys(&self, a: ty::t, b: ty::t) -> cres<ty::t> { let opp = CombineFields { a_is_expected:!self.get_ref().a_is_expected,.. *self.get_ref() }; Sub(opp).tys(b, a) } fn contraregions(&self, a: ty::Region,...
{ Lub(*self.get_ref()) }
identifier_body
overloaded-deref-count.rs
// run-pass use std::cell::Cell; use std::ops::{Deref, DerefMut}; use std::vec::Vec; struct DerefCounter<T> { count_imm: Cell<usize>, count_mut: usize, value: T } impl<T> DerefCounter<T> { fn new(value: T) -> DerefCounter<T> { DerefCounter { count_imm: Cell::new(0), co...
} pub fn main() { let mut n = DerefCounter::new(0); let mut v = DerefCounter::new(Vec::new()); let _ = *n; // Immutable deref + copy a POD. assert_eq!(n.counts(), (1, 0)); let _ = (&*n, &*v); // Immutable deref + borrow. assert_eq!(n.counts(), (2, 0)); assert_eq!(v.counts(), (1, 0)); le...
{ self.count_mut += 1; &mut self.value }
identifier_body
overloaded-deref-count.rs
// run-pass
use std::vec::Vec; struct DerefCounter<T> { count_imm: Cell<usize>, count_mut: usize, value: T } impl<T> DerefCounter<T> { fn new(value: T) -> DerefCounter<T> { DerefCounter { count_imm: Cell::new(0), count_mut: 0, value: value } } fn counts...
use std::cell::Cell; use std::ops::{Deref, DerefMut};
random_line_split
overloaded-deref-count.rs
// run-pass use std::cell::Cell; use std::ops::{Deref, DerefMut}; use std::vec::Vec; struct
<T> { count_imm: Cell<usize>, count_mut: usize, value: T } impl<T> DerefCounter<T> { fn new(value: T) -> DerefCounter<T> { DerefCounter { count_imm: Cell::new(0), count_mut: 0, value: value } } fn counts(&self) -> (usize, usize) { (se...
DerefCounter
identifier_name
uuid.rs
//! Conversions between ULID and UUID. use crate::Ulid; use uuid::Uuid; impl From<Uuid> for Ulid { fn from(uuid: Uuid) -> Self { Ulid(uuid.as_u128()) } } impl From<Ulid> for Uuid { fn from(ulid: Ulid) -> Self { Uuid::from_u128(ulid.0) } } #[cfg(test)] mod test { use super::*; ...
() { let uuid_txt = "771a3bce-02e9-4428-a68e-b1e7e82b7f9f"; let ulid_txt = "3Q38XWW0Q98GMAD3NHWZM2PZWZ"; let ulid: Ulid = Uuid::parse_str(uuid_txt).unwrap().into(); assert_eq!(ulid.to_string(), ulid_txt); let uuid: Uuid = ulid.into(); assert_eq!(uuid.to_string(), uuid_t...
uuid_str_cycle
identifier_name
uuid.rs
//! Conversions between ULID and UUID. use crate::Ulid; use uuid::Uuid; impl From<Uuid> for Ulid { fn from(uuid: Uuid) -> Self { Ulid(uuid.as_u128()) } } impl From<Ulid> for Uuid { fn from(ulid: Ulid) -> Self
} #[cfg(test)] mod test { use super::*; #[test] fn uuid_cycle() { let ulid = Ulid::new(); let uuid: Uuid = ulid.into(); let ulid2: Ulid = uuid.into(); assert_eq!(ulid, ulid2); } #[test] fn uuid_str_cycle() { let uuid_txt = "771a3bce-02e9-4428-a68e-b1e...
{ Uuid::from_u128(ulid.0) }
identifier_body
uuid.rs
//! Conversions between ULID and UUID.
fn from(uuid: Uuid) -> Self { Ulid(uuid.as_u128()) } } impl From<Ulid> for Uuid { fn from(ulid: Ulid) -> Self { Uuid::from_u128(ulid.0) } } #[cfg(test)] mod test { use super::*; #[test] fn uuid_cycle() { let ulid = Ulid::new(); let uuid: Uuid = ulid.into();...
use crate::Ulid; use uuid::Uuid; impl From<Uuid> for Ulid {
random_line_split
mv.rs
#![crate_name = "uu_mv"] /* * This file is part of the uutils coreutils package. * * (c) Orvar Segerström <orvarsegerstrom@gmail.com> * (c) Sokovikov Evgeniy <skv-headless@yandex.ru> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. ...
loop { let new_path = simple_backup_path(path, &format!(".~{}~", i)); if!new_path.exists() { return new_path; } i = i + 1; } } fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf { let test_path = simple_backup_path(path, &".~1~".to_owned()); if...
let mut i: u64 = 1;
identifier_name
mv.rs
#![crate_name = "uu_mv"] /* * This file is part of the uutils coreutils package. * * (c) Orvar Segerström <orvarsegerstrom@gmail.com> * (c) Sokovikov Evgeniy <skv-headless@yandex.ru> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. ...
Some(x) => x, None => { show_error!("option '--suffix' requires an argument\n\ Try '{} --help' for more information.", NAME); return 1; } } } else { "~".to_owned() }; if matches.opt_present("T") ...
let backup_suffix = if matches.opt_present("suffix") { match matches.opt_str("suffix") {
random_line_split
mv.rs
#![crate_name = "uu_mv"] /* * This file is part of the uutils coreutils package. * * (c) Orvar Segerström <orvarsegerstrom@gmail.com> * (c) Sokovikov Evgeniy <skv-headless@yandex.ru> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. ...
if!source.is_dir() { show_error!("cannot overwrite directory ‘{}’ with non-directory", target.display()); return 1; } return match rename(source, target, &b) { ...
ch b.target_dir { Some(ref name) => return move_files_into_dir(files, &PathBuf::from(name), &b), None => {} } match files.len() { 0 | 1 => { show_error!("missing file operand\n\ Try '{} --help' for more information.", NAME); return 1; ...
identifier_body
tree.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/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use at...
}
{ false }
identifier_body
tree.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/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use at...
}
}
random_line_split
tree.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/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use at...
(&self) -> bool { false } /// Return true if we want to stop lookup ancestor of the current /// element while matching complex selectors with descendant/child /// combinator. fn blocks_ancestor_combinators(&self) -> bool { false } }
ignores_nth_child_selectors
identifier_name
mod.rs
//! A Collection of Header implementations for common HTTP Headers. //! //! ## Mime //! //! Several header fields use MIME values for their contents. Keeping with the //! strongly-typed theme, the [mime](http://seanmonstar.github.io/mime.rs) crate //! is used, such as `ContentType(pub Mime)`. pub use self::access_cont...
fn parse_header(raw: &[Vec<u8>]) -> Option<$from> { $crate::header::parsing::from_one_raw_str(raw).map($from) } } impl header::HeaderFormat for $from { fn fmt_header(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { ::std::...
fn header_name() -> &'static str { $name }
random_line_split
mul.rs
use std::ops::Mul; use traits::{Flops, Matrix, UnsafeGet}; impl<A, B> Flops for ::Mul<A, B> where A: Flops + UnsafeGet, B: Flops + UnsafeGet, A::Output: Mul<B::Output>, { #[inline(always)] fn flops() -> usize { A::flops() + B::flops() + 1 } } impl<A, B, C> Matrix for ::Mul<A, B> where...
}
#[inline(always)] unsafe fn unsafe_get(&self, i: (u32, u32)) -> C { self.0.unsafe_get(i) * self.1.unsafe_get(i) }
random_line_split
mul.rs
use std::ops::Mul; use traits::{Flops, Matrix, UnsafeGet}; impl<A, B> Flops for ::Mul<A, B> where A: Flops + UnsafeGet, B: Flops + UnsafeGet, A::Output: Mul<B::Output>, { #[inline(always)] fn flops() -> usize { A::flops() + B::flops() + 1 } } impl<A, B, C> Matrix for ::Mul<A, B> where...
(&self) -> (u32, u32) { B::size(&self.1) } } impl<A, B, C> UnsafeGet for ::Mul<A, B> where A: UnsafeGet, B: UnsafeGet, A::Output: Mul<B::Output, Output=C>, { type Output = C; #[inline(always)] unsafe fn unsafe_get(&self, i: (u32, u32)) -> C { self.0.unsafe_get(i) * self.1.u...
size
identifier_name
mul.rs
use std::ops::Mul; use traits::{Flops, Matrix, UnsafeGet}; impl<A, B> Flops for ::Mul<A, B> where A: Flops + UnsafeGet, B: Flops + UnsafeGet, A::Output: Mul<B::Output>, { #[inline(always)] fn flops() -> usize
} impl<A, B, C> Matrix for ::Mul<A, B> where A: UnsafeGet, B: Matrix + UnsafeGet, A::Output: Mul<B::Output, Output=C>, { #[inline(always)] fn nrows(&self) -> u32 { B::nrows(&self.1) } #[inline(always)] fn ncols(&self) -> u32 { B::ncols(&self.1) } #[inline(alwa...
{ A::flops() + B::flops() + 1 }
identifier_body
platform.rs
/* Copyright ⓒ 2015 cargo-script contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modifie...
-> u64 { /* This is kinda dicey, since *ideally* both this function and `file_last_modified` would be using the same underlying APIs. They are not, insofar as I know. At least, not when targetting Windows. That said, so long as everything is in the same units and uses the same epoch,...
rrent_time()
identifier_name
platform.rs
/* Copyright ⓒ 2015 cargo-script contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modifie...
} fn SHGetKnownFolderPath(rfid: &winapi::KNOWNFOLDERID, dwFlags: winapi::DWORD, hToken: winapi::HANDLE) -> WinResult<OsString> { use self::winapi::PWSTR; let mut psz_path: PWSTR = unsafe { mem::uninitialized() }; let hresult = unsafe { shell32::SHGetKnownFolderPath( ...
write!(fmt, "HRESULT({})", self.0) }
identifier_body
platform.rs
/* Copyright ⓒ 2015 cargo-script contributors. Licensed under the MIT license (see LICENSE or <http://opensource.org /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All files in the project carrying such notice may not be copied, modifie...
+ (now_1970_utc.nsec as u64 / 1_000_000); now_ms_1970_utc } } #[cfg(unix)] mod inner { pub use super::inner_unix_or_windows::current_time; use std::path::{Path, PathBuf}; use std::{cmp, env, fs}; use std::os::unix::fs::MetadataExt; use error::{MainError, Blame}; /** ...
return 0 } let now_ms_1970_utc = (now_1970_utc.sec as u64 * 1000)
random_line_split
tag-align-u64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn is_8_byte_aligned(u: &Tag) -> bool { let p: uint = unsafe { cast::transmute(u) }; return (p & 7u) == 0u; } pub fn main() { let x = mk_rec(); assert!(is_8_byte_aligned(&x.t)); }
fn mk_rec() -> Rec { return Rec { c8:0u8, t:Tag(0u64) }; }
random_line_split
tag-align-u64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn is_8_byte_aligned(u: &Tag) -> bool { let p: uint = unsafe { cast::transmute(u) }; return (p & 7u) == 0u; } pub fn main() { let x = mk_rec(); assert!(is_8_byte_aligned(&x.t)); }
{ return Rec { c8:0u8, t:Tag(0u64) }; }
identifier_body
tag-align-u64.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ c8: u8, t: Tag } fn mk_rec() -> Rec { return Rec { c8:0u8, t:Tag(0u64) }; } fn is_8_byte_aligned(u: &Tag) -> bool { let p: uint = unsafe { cast::transmute(u) }; return (p & 7u) == 0u; } pub fn main() { let x = mk_rec(); assert!(is_8_byte_aligned(&x.t)); }
Rec
identifier_name
leaf_set.rs
// Copyright 2021 The Grin Developers // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
( &self, cutoff_pos: u64, rewind_rm_pos: &Bitmap, prune_list: &PruneList, ) -> Bitmap { let mut bitmap = self.bitmap.clone(); // First remove pos from leaf_set that were // added after the point we are rewinding to. let to_remove = ((cutoff_pos + 1) as u32)..bitmap.maximum().unwrap_or(0); bitmap.rem...
removed_pre_cutoff
identifier_name
leaf_set.rs
// Copyright 2021 The Grin Developers // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
if!bitmap.is_empty() { debug!( "bitmap {} pos ({} bytes)", bitmap.cardinality(), bitmap.get_serialized_size_in_bytes(), ); } Ok(LeafSet { path: file_path.to_path_buf(), bitmap_bak: bitmap.clone(), bitmap, }) } /// Copies a snapshot of the utxo file into the primary utxo file. pub...
} else { Bitmap::create() };
random_line_split
leaf_set.rs
// Copyright 2021 The Grin Developers // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
/// Remove the provided position from the leaf_set. pub fn remove(&mut self, pos0: u64) { self.bitmap.remove(1 + pos0 as u32); } /// Saves the utxo file tagged with block hash as filename suffix. /// Needed during fast-sync as the receiving node cannot rewind /// after receiving the txhashset zip file. pub ...
{ self.bitmap.add(1 + pos0 as u32); }
identifier_body
leaf_set.rs
// Copyright 2021 The Grin Developers // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed t...
let bitmap = read_bitmap(&cp_file_path)?; debug!( "leaf_set: copying rewound file {} to {}", cp_file_path.display(), path.as_ref().display() ); let mut leaf_set = LeafSet { path: path.as_ref().to_path_buf(), bitmap_bak: bitmap.clone(), bitmap, }; leaf_set.flush()?; Ok(()) } /// Ca...
{ debug!( "leaf_set: rewound leaf file not found: {}", cp_file_path.display() ); return Ok(()); }
conditional_block
usage.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
Install a package from a URL by Git or cURL (FTP, HTTP, etc.). If target is provided, Git will checkout the branch or tag before continuing. If the URL is a TAR file (with or without compression), extract it before installing. If a URL isn't provided, the package will be built and installed from the current directory (...
pub fn install() { io::println("rustpkg [options..] install [url] [target]
random_line_split
usage.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { io::println("rustpkg [options..] build Build all targets described in the package script in the current directory. Options: -c, --cfg Pass a cfg flag to the package script"); } pub fn clean() { io::println("rustpkg clean Remove all build files in the work cache for the package in the current d...
build
identifier_name
usage.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn unprefer() { io::println("rustpkg [options..] unprefer <id|name>[@version] Remove all symlinks from the store to the binary directory for a package name and optionally version. If version is not supplied, the latest version of the package will be unpreferred. See `rustpkg prefer -h` for more information."...
{ io::println("rustpkg [options..] prefer <id|name>[@version] By default all binaries are given a unique name so that multiple versions can coexist. The prefer command will symlink the uniquely named binary to the binary directory under its bare name. If version is not supplied, the latest version of the package w...
identifier_body
shellscalingapi.rs
// except according to those terms. ENUM!{enum PROCESS_DPI_AWARENESS { Process_DPI_Unaware = 0, Process_System_DPI_Aware = 1, Process_Per_Monitor_DPI_Aware = 2, }} ENUM!{enum MONITOR_DPI_TYPE { MDT_EFFECTIVE_DPI = 0, MDT_ANGULAR_DPI = 1, MDT_RAW_DPI = 2, MDT_DEFAULT = MDT_EFFECTIVE_DPI, }} ...
// Copyright © 2015-2017 winapi-rs developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied,...
random_line_split
system_allocator.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use base::pagesize; use crate::address_allocator::{AddressAllocator, AddressAllocatorSet}; use crate::{Alloc, Error, R...
/// Allocate PCI slot location. pub fn allocate_pci(&mut self, bus: u8, tag: String) -> Option<Alloc> { let id = self.get_anon_alloc(); let allocator = match self.get_pci_allocator_mut(bus) { Some(v) => v, None => return None, }; allocator .al...
{ if self.pci_allocator.get(&bus).is_none() { true } else { false } }
identifier_body
system_allocator.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use base::pagesize; use crate::address_allocator::{AddressAllocator, AddressAllocatorSet}; use crate::{Alloc, Error, R...
(&mut self, bus: u8) -> Option<&mut AddressAllocator> { // pci root is 00:00.0, Bus 0 next device is 00:01.0 with mandatory function // number zero. if self.pci_allocator.get(&bus).is_none() { let base = if bus == 0 { 8 } else { 0 }; // Each bus supports up to 32 (device...
get_pci_allocator_mut
identifier_name
system_allocator.rs
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::collections::BTreeMap; use base::pagesize; use crate::address_allocator::{AddressAllocator, AddressAllocatorSet}; use crate::{Alloc, Error, R...
} /// Reserves the next available system irq number. pub fn reserve_irq(&mut self, irq: u32) -> bool { let id = self.get_anon_alloc(); self.irq_allocator .allocate_at(irq as u64, 1, id, "irq-fixed".to_string()) .is_ok() } fn get_pci_allocator_mut(&mut self, bu...
random_line_split
ping.rs
// This file is generated by rust-protobuf 2.6.2. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![a...
os.write_unknown_fields(self.get_unknown_fields())?; ::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self...
{ os.write_uint32(1, self.current_utc)?; }
conditional_block
ping.rs
// This file is generated by rust-protobuf 2.6.2. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![a...
fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknown_fields } fn as_any(&self) -> &::std::any::Any { self as &::std::any::Any } fn as_any_mut(&mut self) -> &mut ::std::any::Any { self as &mut ::std::any::Any } fn into_any(self: Box...
{ &self.unknown_fields }
identifier_body
ping.rs
// This file is generated by rust-protobuf 2.6.2. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![a...
::std::result::Result::Ok(()) } fn get_cached_size(&self) -> u32 { self.cached_size.get() } fn get_unknown_fields(&self) -> &::protobuf::UnknownFields { &self.unknown_fields } fn mut_unknown_fields(&mut self) -> &mut ::protobuf::UnknownFields { &mut self.unknow...
os.write_unknown_fields(self.get_unknown_fields())?;
random_line_split
ping.rs
// This file is generated by rust-protobuf 2.6.2. Do not edit // @generated // https://github.com/Manishearth/rust-clippy/issues/702 #![allow(unknown_lints)] #![allow(clippy)] #![cfg_attr(rustfmt, rustfmt_skip)] #![allow(box_pointers)] #![allow(dead_code)] #![allow(missing_docs)] #![allow(non_camel_case_types)] #![a...
(&self) -> u32 { self.current_utc } pub fn clear_current_utc(&mut self) { self.current_utc = 0; } // Param is passed by value, moved pub fn set_current_utc(&mut self, v: u32) { self.current_utc = v; } } impl ::protobuf::Message for PING_MESSAGE { fn is_initialized(&...
get_current_utc
identifier_name
directory.rs
use std::collections::HashMap; use std::fmt::{self, Debug, Formatter}; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use hex::ToHex; use serde_json; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use sources::PathSource; use util::{Config, Sha256}; use util::...
{ package: String, files: HashMap<String, String>, } impl<'cfg> DirectorySource<'cfg> { pub fn new(path: &Path, id: &SourceId, config: &'cfg Config) -> DirectorySource<'cfg> { DirectorySource { source_id: id.clone(), root: path.to_path_buf(), conf...
Checksum
identifier_name
directory.rs
use std::collections::HashMap; use std::fmt::{self, Debug, Formatter}; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use hex::ToHex; use serde_json; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use sources::PathSource; use util::{Config, Sha256}; use util::...
only_dotfile = false; } if only_dotfile { continue } let mut src = PathSource::new(&path, &self.source_id, self.config); src.update()?; let pkg = src.root_package()?; let cksum_file = path.join(".cargo-...
}
random_line_split
directory.rs
use std::collections::HashMap; use std::fmt::{self, Debug, Formatter}; use std::fs::File; use std::io::Read; use std::path::{Path, PathBuf}; use hex::ToHex; use serde_json; use core::{Package, PackageId, Summary, SourceId, Source, Dependency, Registry}; use sources::PathSource; use util::{Config, Sha256}; use util::...
} impl<'cfg> Debug for DirectorySource<'cfg> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "DirectorySource {{ root: {:?} }}", self.root) } } impl<'cfg> Registry for DirectorySource<'cfg> { fn query(&mut self, dep: &Dependency, f: &mut FnMut(Summary)) -> ...
{ DirectorySource { source_id: id.clone(), root: path.to_path_buf(), config: config, packages: HashMap::new(), } }
identifier_body
texttrackcue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TextTrackCueBinding::{se...
(&self, value: DOMString) { *self.id.borrow_mut() = value; } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-track fn GetTrack(&self) -> Option<DomRoot<TextTrack>> { self.get_track() } // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-starttime fn StartTim...
SetId
identifier_name
texttrackcue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TextTrackCueBinding::{se...
// https://html.spec.whatwg.org/multipage/#handler-texttrackcue-onenter event_handler!(enter, GetOnenter, SetOnenter); // https://html.spec.whatwg.org/multipage/#handler-texttrackcue-onexit event_handler!(exit, GetOnexit, SetOnexit); }
}
random_line_split
texttrackcue.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::cell::DomRefCell; use crate::dom::bindings::codegen::Bindings::TextTrackCueBinding::{se...
pub fn get_track(&self) -> Option<DomRoot<TextTrack>> { self.track.as_ref().map(|t| DomRoot::from_ref(&**t)) } } impl TextTrackCueMethods for TextTrackCue { // https://html.spec.whatwg.org/multipage/#dom-texttrackcue-id fn Id(&self) -> DOMString { self.id() } // https://html....
{ self.id.borrow().clone() }
identifier_body
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn
<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uint) -> HashMap<N, uint> { assert!(goals.len() > 0); let mut ret = HashMap::new(); // Init goal nodes to zero score. for k in goals.iter() { ret.insert(k.clone(), 0); } let mut edge = ~HashSet::new(); for k ...
build_map
identifier_name
dijkstra.rs
use std::hash::Hash; use collections::hashmap::HashMap; use collections::hashmap::HashSet; /// Build a Dijkstra map starting from the goal nodes and using the neighbors /// function to define the graph to up to limit distance. pub fn build_map<N: Hash + Eq + Clone>( goals: ~[N], neighbors: |&N| -> ~[N], limit: uin...
} } edge = new_edge; } ret }
{ new_edge.insert(n.clone()); }
conditional_block