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
encrypted.rs
// Copyright (c) 2018, Ben Boeckel // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of cond...
keytype, description, } => format!("update {}:{}", keytype.name(), description), } .into_bytes() .into() } }
{ match self { Payload::New { format, keytype, description, keylen, } => { format!( "new {} {}:{} {}", format.unwrap_or_default().name(), keytype.na...
identifier_body
mod.rs
// The MIT License (MIT) // Copyright (c) 2015 Y. T. Chung <zonyitoo@gmail.com> // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // t...
// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LI...
// The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software.
random_line_split
gesture_long_press.rs
// This file was generated by gir (b7f5189) from gir-files (71d73f0) // DO NOT EDIT use EventController; use Gesture; use GestureSingle; #[cfg(feature = "v3_14")] use Widget; use ffi; use glib::Value; use glib::object::Downcast; use glib::object::IsA; #[cfg(feature = "v3_14")] use glib::signal::connect; use glib::tran...
(this: *mut ffi::GtkGestureLongPress, f: glib_ffi::gpointer) { callback_guard!(); let f: &Box_<Fn(&GestureLongPress) +'static> = transmute(f); f(&from_glib_none(this)) } #[cfg(feature = "v3_14")] unsafe extern "C" fn pressed_trampoline(this: *mut ffi::GtkGestureLongPress, x: libc::c_double, y: libc::c_doub...
cancelled_trampoline
identifier_name
gesture_long_press.rs
// This file was generated by gir (b7f5189) from gir-files (71d73f0) // DO NOT EDIT use EventController; use Gesture; use GestureSingle; #[cfg(feature = "v3_14")] use Widget; use ffi; use glib::Value; use glib::object::Downcast; use glib::object::IsA; #[cfg(feature = "v3_14")] use glib::signal::connect; use glib::tran...
} #[cfg(feature = "v3_14")] unsafe extern "C" fn cancelled_trampoline(this: *mut ffi::GtkGestureLongPress, f: glib_ffi::gpointer) { callback_guard!(); let f: &Box_<Fn(&GestureLongPress) +'static> = transmute(f); f(&from_glib_none(this)) } #[cfg(feature = "v3_14")] unsafe extern "C" fn pressed_trampoline(...
{ unsafe { let f: Box_<Box_<Fn(&GestureLongPress, f64, f64) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "pressed", transmute(pressed_trampoline as usize), Box_::into_raw(f) as *mut _) } }
identifier_body
gesture_long_press.rs
// This file was generated by gir (b7f5189) from gir-files (71d73f0) // DO NOT EDIT use EventController; use Gesture; use GestureSingle; #[cfg(feature = "v3_14")] use Widget; use ffi; use glib::Value; use glib::object::Downcast; use glib::object::IsA; #[cfg(feature = "v3_14")] use glib::signal::connect; use glib::tran...
#[cfg(feature = "v3_14")] pub fn connect_cancelled<F: Fn(&GestureLongPress) +'static>(&self, f: F) -> u64 { unsafe { let f: Box_<Box_<Fn(&GestureLongPress) +'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "cancelled", transmute(cancelled_trampo...
} }
random_line_split
issue-3953.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 ...
() { if Lol(2) == Lol(4) { println!("2 == 4"); } else { println!("2!= 4"); } }
main
identifier_name
issue-3953.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 ...
else { println!("2!= 4"); } }
{ println!("2 == 4"); }
conditional_block
issue-3953.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 std::cmp::Eq; trait Hahaha: Eq + Eq + Eq + Eq + Eq + //~ ERROR duplicate supertrait Eq + Eq + Eq + Eq + Eq + Eq + Eq + Eq + Eq + Eq + E...
random_line_split
task-perf-one-million.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...
(children: uint, parent_wait_chan: &Sender<Sender<Sender<int>>>) { let wait_ports: Vec<Reciever<Sender<Sender<int>>>> = vec::from_fn(children, |_| { let (wait_port, wait_chan) = stream::<Sender<Sender<int>>>(); task::spawn(move|| { calc(children / 2, &wait_chan); }); wai...
calc
identifier_name
task-perf-one-million.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...
child_start_chan.send(child_sum_chan); child_sum_port }).collect(); let sum = child_sum_ports.into_iter().fold(0, |sum, sum_port| sum + sum_port.recv() ); parent_result_chan.send(sum + 1); } fn main() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some...
{ let wait_ports: Vec<Reciever<Sender<Sender<int>>>> = vec::from_fn(children, |_| { let (wait_port, wait_chan) = stream::<Sender<Sender<int>>>(); task::spawn(move|| { calc(children / 2, &wait_chan); }); wait_port }); let child_start_chans: Vec<Sender<Sender<int>...
identifier_body
task-perf-one-million.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...
else { args }; let children = from_str::<uint>(args[1]).unwrap(); let (wait_port, wait_chan) = stream(); task::spawn(move|| { calc(children, &wait_chan); }); let start_chan = wait_port.recv(); let (sum_port, sum_chan) = stream::<int>(); start_chan.send(sum_chan); l...
{ vec!("".to_string(), "10".to_string()) }
conditional_block
task-perf-one-million.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...
use std::slice; fn calc(children: uint, parent_wait_chan: &Sender<Sender<Sender<int>>>) { let wait_ports: Vec<Reciever<Sender<Sender<int>>>> = vec::from_fn(children, |_| { let (wait_port, wait_chan) = stream::<Sender<Sender<int>>>(); task::spawn(move|| { calc(children / 2, &wait_chan);...
use std::uint;
random_line_split
htmlformcontrolscollection.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; use dom::bindings::codegen::Bi...
else { // Step 4-5 let once = iter::once(Root::upcast::<Node>(elem)); let list = once.chain(peekable.map(Root::upcast)); let global = self.global(); let window = global.as_window(); Some(RadioNodeListOrElement::RadioNodeLis...
{ Some(RadioNodeListOrElement::Element(elem)) }
conditional_block
htmlformcontrolscollection.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; use dom::bindings::codegen::Bi...
// https://html.spec.whatwg.org/multipage/#the-htmlformcontrolscollection-interface:supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { self.collection.SupportedPropertyNames() } // FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of ...
self.NamedItem(name) }
random_line_split
htmlformcontrolscollection.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; use dom::bindings::codegen::Bi...
pub fn new(window: &Window, root: &Node, filter: Box<CollectionFilter +'static>) -> Root<HTMLFormControlsCollection> { reflect_dom_object(box HTMLFormControlsCollection::new_inherited(root, filter), window, HTMLFormControlsCollectionBinding...
{ HTMLFormControlsCollection { collection: HTMLCollection::new_inherited(root, filter) } }
identifier_body
htmlformcontrolscollection.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; use dom::bindings::codegen::Bi...
(&self, name: DOMString) -> Option<RadioNodeListOrElement> { self.NamedItem(name) } // https://html.spec.whatwg.org/multipage/#the-htmlformcontrolscollection-interface:supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMString> { self.collection.SupportedPropertyNames() ...
NamedGetter
identifier_name
chinese_remainder.rs
// http://rosettacode.org/wiki/Chinese_remainder_theorem fn main() { let l = [(2, 3), (3, 5), (2, 7)]; println!("{:?}", chinese_remainder(&l)); } fn
(l: &[(i32, i32)]) -> Option<i32> { let product = l.iter().fold(1, |prod, &(_, n)| prod * n); let mut sum = 0; for &(a, n) in l { let mut term = product / n; let inv = match mul_inv(term, n) { Some(inv) => inv, None => return None, }; term *= inv; ...
chinese_remainder
identifier_name
chinese_remainder.rs
// http://rosettacode.org/wiki/Chinese_remainder_theorem fn main() { let l = [(2, 3), (3, 5), (2, 7)]; println!("{:?}", chinese_remainder(&l)); } fn chinese_remainder(l: &[(i32, i32)]) -> Option<i32> { let product = l.iter().fold(1, |prod, &(_, n)| prod * n); let mut sum = 0; for &(a, n) in l { ...
#[test] fn test() { let l = [(2, 3), (3, 5), (2, 7)]; assert_eq!(chinese_remainder(&l), Some(23)); let l = [(10, 11), (4, 22), (9, 19)]; assert_eq!(chinese_remainder(&l), None); }
(g, x - (b / a) * y, y) }
random_line_split
chinese_remainder.rs
// http://rosettacode.org/wiki/Chinese_remainder_theorem fn main() { let l = [(2, 3), (3, 5), (2, 7)]; println!("{:?}", chinese_remainder(&l)); } fn chinese_remainder(l: &[(i32, i32)]) -> Option<i32>
fn mul_inv(a: i32, b: i32) -> Option<i32> { let (gcd, mut x, _) = egcd(a, b); if gcd!= 1 { // No multiplicative inverse exists return None; } if x < 0 { x += b; } Some(x % b) } fn egcd(a: i32, b: i32) -> (i32, i32, i32) { if a == 0 { return (b, 0, 1); }...
{ let product = l.iter().fold(1, |prod, &(_, n)| prod * n); let mut sum = 0; for &(a, n) in l { let mut term = product / n; let inv = match mul_inv(term, n) { Some(inv) => inv, None => return None, }; term *= inv; term *= a; sum += t...
identifier_body
rename.rs
//! Test for Clippy lint renames. // run-rustfix #![allow(dead_code)] // allow the new lint name here, to test if the new name works #![allow(clippy::module_name_repetitions)] #![allow(clippy::new_without_default)] #![allow(clippy::redundant_static_lifetimes)] #![allow(clippy::bind_instead_of_map)] #![allow(clippy::bo...
#![allow(clippy::single_char_add_str)] #![allow(clippy::match_result_ok)] // uplifted lints #![allow(invalid_value)] #![allow(array_into_iter)] #![allow(unused_labels)] #![allow(drop_bounds)] #![allow(temporary_cstring_as_ptr)] #![allow(non_fmt_panics)] #![allow(unknown_lints)] #![allow(invalid_atomic_ordering)] #![all...
#![allow(clippy::unwrap_used)] #![allow(clippy::expect_used)] #![allow(clippy::for_loops_over_fallibles)] #![allow(clippy::useless_conversion)] #![allow(clippy::invisible_characters)]
random_line_split
rename.rs
//! Test for Clippy lint renames. // run-rustfix #![allow(dead_code)] // allow the new lint name here, to test if the new name works #![allow(clippy::module_name_repetitions)] #![allow(clippy::new_without_default)] #![allow(clippy::redundant_static_lifetimes)] #![allow(clippy::bind_instead_of_map)] #![allow(clippy::bo...
() {}
main
identifier_name
rename.rs
//! Test for Clippy lint renames. // run-rustfix #![allow(dead_code)] // allow the new lint name here, to test if the new name works #![allow(clippy::module_name_repetitions)] #![allow(clippy::new_without_default)] #![allow(clippy::redundant_static_lifetimes)] #![allow(clippy::bind_instead_of_map)] #![allow(clippy::bo...
{}
identifier_body
c.rs
use super::{error, store::path, store::StorePath, util}; #[no_mangle] pub unsafe extern "C" fn ffi_String_new(s: &str, out: *mut String) { // FIXME: check whether's' is valid UTF-8? out.write(s.to_string()) } #[no_mangle] pub unsafe extern "C" fn ffi_String_drop(self_: *mut String)
#[no_mangle] pub extern "C" fn ffi_StorePath_new( path: &str, store_dir: &str, ) -> Result<StorePath, error::CppException> { StorePath::new(std::path::Path::new(path), std::path::Path::new(store_dir)) .map_err(|err| err.into()) } #[no_mangle] pub extern "C" fn ffi_StorePath_new2( hash: &[u8; c...
{ std::ptr::drop_in_place(self_); }
identifier_body
c.rs
use super::{error, store::path, store::StorePath, util}; #[no_mangle] pub unsafe extern "C" fn ffi_String_new(s: &str, out: *mut String) { // FIXME: check whether's' is valid UTF-8? out.write(s.to_string()) } #[no_mangle] pub unsafe extern "C" fn ffi_String_drop(self_: *mut String) { std::ptr::drop_in_pla...
(self_: &StorePath) -> Vec<u8> { let mut buf = vec![0; path::STORE_PATH_HASH_CHARS + 1 + self_.name.name().len()]; util::base32::encode_into(self_.hash.hash(), &mut buf[0..path::STORE_PATH_HASH_CHARS]); buf[path::STORE_PATH_HASH_CHARS] = b'-'; buf[path::STORE_PATH_HASH_CHARS + 1..].clone_from_slice(self...
ffi_StorePath_to_string
identifier_name
c.rs
use super::{error, store::path, store::StorePath, util};
#[no_mangle] pub unsafe extern "C" fn ffi_String_new(s: &str, out: *mut String) { // FIXME: check whether's' is valid UTF-8? out.write(s.to_string()) } #[no_mangle] pub unsafe extern "C" fn ffi_String_drop(self_: *mut String) { std::ptr::drop_in_place(self_); } #[no_mangle] pub extern "C" fn ffi_StorePat...
random_line_split
mod.rs
// This file is a part of Chekhov, an actor/model concurrency framework for Rust. // // Chekhov is free software; you can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, either version 3 of the // License or (at your option) any later v...
Understudy(Sender<M>), } impl<M: Send +'static> Actor<M> { pub fn new(tx: Sender<Message<M>>) -> Actor<M> { Actor::Actor(tx) } pub fn new_mut(tx: Sender<Message<M>>) -> Actor<M> { Actor::ActorMut(tx, true) } pub fn new_loop(tx: Sender<Message<M>>) -> Actor<M> { Actor::ActorLoop(tx) } pub fn new...
random_line_split
mod.rs
// This file is a part of Chekhov, an actor/model concurrency framework for Rust. // // Chekhov is free software; you can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, either version 3 of the // License or (at your option) any later v...
pub fn stage(&self) -> Actor<M> { match *self { Actor::Actor(ref tx) => Actor::new(tx.clone()), Actor::ActorMut(ref tx, _) => Actor::ActorMut(tx.clone(), false), Actor::ActorLoop(ref tx) => Actor::new_loop(tx.clone()), Actor::Understudy(ref tx) => A...
{ self.pass_msg(Message::Cut) }
identifier_body
mod.rs
// This file is a part of Chekhov, an actor/model concurrency framework for Rust. // // Chekhov is free software; you can redistribute it and/or modify it under the terms of the GNU // General Public License as published by the Free Software Foundation, either version 3 of the // License or (at your option) any later v...
(&self) -> ActorResult { self.pass_msg(Message::Start) } fn pause(&self) -> ActorResult { self.pass_msg(Message::Pause) } } pub type ActorResult = Result<(), Box<Error>>; #[derive(PartialEq)] pub enum Message<M: Send +'static> { Cue(M), Start, Pause, Cut, } impl<M: Send +'static> In...
start
identifier_name
libloaderapi.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! ApiSet Contract for api-ms-win-core-libraryloader-l1 pub type DLL_DIRECTORY_COOKIE = ::PVOID; pub type PDLL_DIRECTORY_COOKIE = *mut ::PVOID; pub type ENUMRESLANGPROCA = Option<unsafe extern "system" fn( hModule: ::HMODULE, lpType...
) -> ::BOOL>;
pub type ENUMRESTYPEPROCA = Option<unsafe extern "system" fn( hModule: ::HMODULE, lpType: ::LPSTR, lParam: ::LONG_PTR, ) -> ::BOOL>; pub type ENUMRESTYPEPROCW = Option<unsafe extern "system" fn( hModule: ::HMODULE, lpType: ::LPWSTR, lParam: ::LONG_PTR,
random_line_split
eta_reduction.rs
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::higher::VecArgs; use clippy_utils::source::snippet_opt; use clippy_utils::usage::UsedAfterExprVisitor; use clippy_utils::{get_enclosing_loop_or_closure, higher, path_to_local_id}; use if_chain::if_chain; use rustc_errors::Applica...
fn get_ufcs_type_name(cx: &LateContext<'_>, method_def_id: DefId) -> String { match cx.tcx.associated_item(method_def_id).container { ty::TraitContainer(def_id) => cx.tcx.def_path_str(def_id), ty::ImplContainer(def_id) => { let ty = cx.tcx.type_of(def_id); match ty.kind() {...
{ let call_sig = call_ty.fn_sig(cx.tcx); if call_sig.unsafety() == Unsafety::Unsafe { return false; } if !closure_ty.has_late_bound_regions() { return true; } let substs = match closure_ty.kind() { ty::Closure(_, substs) => substs, _ => return false, }; le...
identifier_body
eta_reduction.rs
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::higher::VecArgs; use clippy_utils::source::snippet_opt; use clippy_utils::usage::UsedAfterExprVisitor; use clippy_utils::{get_enclosing_loop_or_closure, higher, path_to_local_id}; use if_chain::if_chain; use rustc_errors::Applica...
(cx: &LateContext<'_>, method_def_id: DefId) -> String { match cx.tcx.associated_item(method_def_id).container { ty::TraitContainer(def_id) => cx.tcx.def_path_str(def_id), ty::ImplContainer(def_id) => { let ty = cx.tcx.type_of(def_id); match ty.kind() { ty::Ad...
get_ufcs_type_name
identifier_name
eta_reduction.rs
use clippy_utils::diagnostics::{span_lint_and_sugg, span_lint_and_then}; use clippy_utils::higher::VecArgs; use clippy_utils::source::snippet_opt; use clippy_utils::usage::UsedAfterExprVisitor; use clippy_utils::{get_enclosing_loop_or_closure, higher, path_to_local_id}; use if_chain::if_chain; use rustc_errors::Applica...
if body.params.is_empty() { if let Some(VecArgs::Vec(&[])) = higher::VecArgs::hir(cx, &body.value) { // replace `|| vec![]` with `Vec::new` span_lint_and_sugg( cx, REDUNDANT_CLOSURE, ...
ExprKind::Closure(_, _, id, _, _) => cx.tcx.hir().body(id), _ => return, }; if body.value.span.from_expansion() {
random_line_split
io.rs
use crate::error::IoError; use core::usize; type Result<T> = core::result::Result<T, IoError>; #[derive(Clone, Copy)] pub enum SeekFrom { Start(usize), End(isize), Current(isize), } /// Implementation of loadable asset for buffer-like type pub struct BufferCursor<T: AsRef<[u8]>> { data: T, pos: u...
} #[cfg(test)] mod tests { use super::*; #[test] fn buffer_cursor_seek_works() { const BUFFER: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let mut cursor = BufferCursor::new(BUFFER); let mut tmp = [0u8; 1]; cursor.read_exact(&mut tmp).unwrap(); assert_eq!(tmp[0], 1)...
{ while !buf.is_empty() { match self.write(buf)? { 0 => return Err(IoError::WriteZero), n => buf = &buf[n..], } } Ok(()) }
identifier_body
io.rs
use crate::error::IoError; use core::usize; type Result<T> = core::result::Result<T, IoError>; #[derive(Clone, Copy)] pub enum SeekFrom { Start(usize), End(isize), Current(isize), } /// Implementation of loadable asset for buffer-like type pub struct BufferCursor<T: AsRef<[u8]>> { data: T, pos: u...
/// more bytes fn write_all(&mut self, mut buf: &[u8]) -> Result<()> { while!buf.is_empty() { match self.write(buf)? { 0 => return Err(IoError::WriteZero), n => buf = &buf[n..], } } Ok(()) } } #[cfg(test)] mod tests { use s...
/// [IoError::WriteZero] if destination refused to accept
random_line_split
io.rs
use crate::error::IoError; use core::usize; type Result<T> = core::result::Result<T, IoError>; #[derive(Clone, Copy)] pub enum SeekFrom { Start(usize), End(isize), Current(isize), } /// Implementation of loadable asset for buffer-like type pub struct BufferCursor<T: AsRef<[u8]>> { data: T, pos: u...
(self) -> T { self.data } } impl<T: AsRef<[u8]>> BufferCursor<T> { pub fn new(data: T) -> Self { Self { data, pos: 0 } } } impl<T: AsRef<[u8]>> SeekableAsset for BufferCursor<T> { fn seek(&mut self, pos: SeekFrom) -> Result<usize> { let new_pos = match pos { SeekFro...
into_inner
identifier_name
concat.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 ...
} ast::LitUint(u, _) => { accumulator.push_str(format!("{}", u)); } ast::LitNil => {} ast::LitBool(b) => { accumulator.push_str(format!("{}", b)); } ...
{ let es = match base::get_exprs_from_tts(cx, sp, tts) { Some(e) => e, None => return base::MacResult::dummy_expr() }; let mut accumulator = ~""; for e in es.move_iter() { let e = cx.expand_expr(e); match e.node { ast::ExprLit(lit) => { match l...
identifier_body
concat.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 ...
ast::LitUint(u, _) => { accumulator.push_str(format!("{}", u)); } ast::LitNil => {} ast::LitBool(b) => { accumulator.push_str(format!("{}", b)); } ast:...
{ accumulator.push_str(format!("{}", i)); }
conditional_block
concat.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 ...
accumulator.push_char(char::from_u32(c).unwrap()); } ast::LitInt(i, _) | ast::LitIntUnsuffixed(i) => { accumulator.push_str(format!("{}", i)); } ast::LitUint(u, _) => { ...
| ast::LitFloatUnsuffixed(s) => { accumulator.push_str(s); } ast::LitChar(c) => {
random_line_split
concat.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 ...
(cx: &mut base::ExtCtxt, sp: codemap::Span, tts: &[ast::TokenTree]) -> base::MacResult { let es = match base::get_exprs_from_tts(cx, sp, tts) { Some(e) => e, None => return base::MacResult::dummy_expr() }; let mut accumulator = ~""; for e...
expand_syntax_ext
identifier_name
small-enum-range-edge.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!((Eu::Hu as u8) + 1, Eu::Lu as u8); assert_eq!((Es::Hs as i8) + 1, Es::Ls as i8); assert_eq!(CLu as u8, Eu::Lu as u8); assert_eq!(CHu as u8, Eu::Hu as u8); assert_eq!(CLs as i8, Es::Ls as i8); assert_eq!(CHs as i8, Es::Hs as i8); }
identifier_body
small-enum-range-edge.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 ...
pub fn main() { assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8); assert_eq!((Es::Hs as i8) + 1, Es::Ls as i8); assert_eq!(CLu as u8, Eu::Lu as u8); assert_eq!(CHu as u8, Eu::Hu as u8); assert_eq!(CLs as i8, Es::Ls as i8); assert_eq!(CHs as i8, Es::Hs as i8); }
#[repr(i8)] enum Es { Ls = -128, Hs = 127 } static CLs: Es = Es::Ls; static CHs: Es = Es::Hs;
random_line_split
small-enum-range-edge.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 ...
{ Lu = 0, Hu = 255 } static CLu: Eu = Eu::Lu; static CHu: Eu = Eu::Hu; #[repr(i8)] enum Es { Ls = -128, Hs = 127 } static CLs: Es = Es::Ls; static CHs: Es = Es::Hs; pub fn main() { assert_eq!((Eu::Hu as u8) + 1, Eu::Lu as u8); assert_eq!((Es::Hs as i8) + 1, Es::Ls as i8); assert_eq!(CLu as u8, Eu::Lu as ...
Eu
identifier_name
token.rs
/// Associates readiness events with [`event::Source`]s. /// /// `Token` is a wrapper around `usize` and is used as an argument to /// [`Registry::register`] and [`Registry::reregister`]. /// /// See [`Poll`] for more documentation on polling. /// /// [`event::Source`]:./event/trait.Source.html /// [`Poll`]: struct.Pol...
}
{ val.0 }
identifier_body
token.rs
/// Associates readiness events with [`event::Source`]s. /// /// `Token` is a wrapper around `usize` and is used as an argument to /// [`Registry::register`] and [`Registry::reregister`]. /// /// See [`Poll`] for more documentation on polling. /// /// [`event::Source`]:./event/trait.Source.html /// [`Poll`]: struct.Pol...
(pub usize); impl From<Token> for usize { fn from(val: Token) -> usize { val.0 } }
Token
identifier_name
token.rs
/// Associates readiness events with [`event::Source`]s. /// /// `Token` is a wrapper around `usize` and is used as an argument to /// [`Registry::register`] and [`Registry::reregister`]. /// /// See [`Poll`] for more documentation on polling. /// /// [`event::Source`]:./event/trait.Source.html /// [`Poll`]: struct.Pol...
/// // Wait for events /// poll.poll(&mut events, None)?; /// /// for event in &events { /// match event.token() { /// LISTENER => { /// // Perform operations in a loop until `WouldBlock` is /// // encountered. /// loop { /// ...
random_line_split
power_of_2.rs
use integer::Integer; use malachite_base::num::arithmetic::traits::PowerOf2; use malachite_base::num::basic::traits::One; impl PowerOf2<u64> for Integer { /// Computes 2<sup>`pow`</sup>. /// /// Time: worst case O(`pow`) /// /// Additional memory: worst case O(`pow`) /// /// # Examples ...
Integer::ONE << pow } }
#[inline] fn power_of_2(pow: u64) -> Integer {
random_line_split
power_of_2.rs
use integer::Integer; use malachite_base::num::arithmetic::traits::PowerOf2; use malachite_base::num::basic::traits::One; impl PowerOf2<u64> for Integer { /// Computes 2<sup>`pow`</sup>. /// /// Time: worst case O(`pow`) /// /// Additional memory: worst case O(`pow`) /// /// # Examples ...
(pow: u64) -> Integer { Integer::ONE << pow } }
power_of_2
identifier_name
power_of_2.rs
use integer::Integer; use malachite_base::num::arithmetic::traits::PowerOf2; use malachite_base::num::basic::traits::One; impl PowerOf2<u64> for Integer { /// Computes 2<sup>`pow`</sup>. /// /// Time: worst case O(`pow`) /// /// Additional memory: worst case O(`pow`) /// /// # Examples ...
}
{ Integer::ONE << pow }
identifier_body
cssimportrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CSSImportRuleBinding; use dom::bindings::js::Root; use dom::bindings::reflec...
impl CSSImportRule { fn new_inherited(parent_stylesheet: &CSSStyleSheet, import_rule: Arc<RwLock<ImportRule>>) -> Self { CSSImportRule { cssrule: CSSRule::new_inherited(parent_stylesheet), import_rule: import_rule, } } #[allo...
cssrule: CSSRule, #[ignore_heap_size_of = "Arc"] import_rule: Arc<RwLock<ImportRule>>, }
random_line_split
cssimportrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CSSImportRuleBinding; use dom::bindings::js::Root; use dom::bindings::reflec...
#[allow(unrooted_must_root)] pub fn new(window: &Window, parent_stylesheet: &CSSStyleSheet, import_rule: Arc<RwLock<ImportRule>>) -> Root<Self> { reflect_dom_object(box Self::new_inherited(parent_stylesheet, import_rule), window, ...
{ CSSImportRule { cssrule: CSSRule::new_inherited(parent_stylesheet), import_rule: import_rule, } }
identifier_body
cssimportrule.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::CSSImportRuleBinding; use dom::bindings::js::Root; use dom::bindings::reflec...
(&self) -> DOMString { self.import_rule.read().to_css_string().into() } }
get_css
identifier_name
lib.rs
//! # Getting started //! //! ```rust,no_run //! extern crate sdl2; //! //! use sdl2::pixels::Color; //! use sdl2::event::Event; //! use sdl2::keyboard::Keycode; //! use std::time::Duration; //! //! pub fn main() { //! let sdl_context = sdl2::init().unwrap(); //! let video_subsystem = sdl_context.video().unwr...
pub mod render; pub mod rwops; pub mod log; mod sdl; pub mod audio; pub mod version; pub mod messagebox; pub mod hint; // modules #[cfg(feature = "ttf")] pub mod ttf; #[cfg(feature = "image")] pub mod image; #[cfg(feature = "mixer")] pub mod mixer; #[cfg(feature = "gfx")] pub mod gfx; mod common; // Export return typ...
pub mod pixels; pub mod video; pub mod timer;
random_line_split
lib.rs
ipc::{IpcReceiver, IpcSender}; use libc::c_void; use msg::constellation_msg::{FrameId, FrameType, Key, KeyModifiers, KeyState}; use msg::constellation_msg::{PipelineId, PipelineNamespaceId, TraversalDirection}; use net_traits::{ReferrerPolicy, ResourceThreads}; use net_traits::image::base::Image; use net_traits::image_...
} } /// Used to determine if a script has any pending asynchronous activity. #[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize)] pub enum DocumentState { /// The document has been loaded and is idle. Idle, /// The document is either loading or waiting on an event. Pending, } /// For a...
WebVREvent(..) => "WebVREvent", }; write!(formatter, "ConstellationMsg::{}", variant)
random_line_split
lib.rs
IpcReceiver, IpcSender}; use libc::c_void; use msg::constellation_msg::{FrameId, FrameType, Key, KeyModifiers, KeyState}; use msg::constellation_msg::{PipelineId, PipelineNamespaceId, TraversalDirection}; use net_traits::{ReferrerPolicy, ResourceThreads}; use net_traits::image::base::Image; use net_traits::image_cache_...
(pub i32); /// The mouse button involved in the event. #[derive(Clone, Copy, Debug, Deserialize, Serialize)] pub enum MouseButton { /// The left mouse button. Left, /// The middle mouse button. Middle, /// The right mouse button. Right, } /// The types of mouse events #[derive(Deserialize, Hea...
TouchId
identifier_name
value.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 cssparser::{Parser, ParserInput}; use style::context::QuirksMode; use style::parser::ParserContext; use style:...
{ // In SVG length mode, non-zero lengths are assumed to be px. let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Some(CssRuleType::Style), PARSING_MODE_ALLOW_ALL_NUMERIC_VALUES, ...
identifier_body
value.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 cssparser::{Parser, ParserInput}; use style::context::QuirksMode; use style::parser::ParserContext; use style:...
() { // In SVG length mode, non-zero lengths are assumed to be px. let url = ::servo_url::ServoUrl::parse("http://localhost").unwrap(); let context = ParserContext::new(Origin::Author, &url, Some(CssRuleType::Style), PARSING_MODE_ALLOW_ALL_NUMERIC_VALUES, ...
test_parsing_allo_all_numeric_values
identifier_name
value.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 cssparser::{Parser, ParserInput}; use style::context::QuirksMode; use style::parser::ParserContext; use style:...
assert!(result.is_ok()); assert_eq!(result.unwrap(), Number::new(-1.)); }
let result = Number::parse_non_negative(&context, &mut parser);
random_line_split
pulseaudio.rs
use super::{Open, Sink, SinkAsBytes, SinkError, SinkResult}; use crate::config::AudioFormat; use crate::convert::Converter; use crate::decoder::AudioPacket; use crate::{NUM_CHANNELS, SAMPLE_RATE}; use libpulse_binding::{self as pulse, error::PAErr, stream::Direction}; use libpulse_simple_binding::Simple; use thiserror:...
fn open(device: Option<String>, format: AudioFormat) -> Self { let mut actual_format = format; if actual_format == AudioFormat::F64 { warn!("PulseAudio currently does not support F64 output"); actual_format = AudioFormat::F32; } info!("Using PulseAudioSink w...
random_line_split
pulseaudio.rs
use super::{Open, Sink, SinkAsBytes, SinkError, SinkResult}; use crate::config::AudioFormat; use crate::convert::Converter; use crate::decoder::AudioPacket; use crate::{NUM_CHANNELS, SAMPLE_RATE}; use libpulse_binding::{self as pulse, error::PAErr, stream::Direction}; use libpulse_simple_binding::Simple; use thiserror:...
} impl Sink for PulseAudioSink { fn start(&mut self) -> SinkResult<()> { if self.s.is_none() { // PulseAudio calls S24 and S24_3 different from the rest of the world let pulse_format = match self.format { AudioFormat::F32 => pulse::sample::Format::FLOAT32NE, ...
{ let mut actual_format = format; if actual_format == AudioFormat::F64 { warn!("PulseAudio currently does not support F64 output"); actual_format = AudioFormat::F32; } info!("Using PulseAudioSink with format: {:?}", actual_format); Self { s:...
identifier_body
pulseaudio.rs
use super::{Open, Sink, SinkAsBytes, SinkError, SinkResult}; use crate::config::AudioFormat; use crate::convert::Converter; use crate::decoder::AudioPacket; use crate::{NUM_CHANNELS, SAMPLE_RATE}; use libpulse_binding::{self as pulse, error::PAErr, stream::Direction}; use libpulse_simple_binding::Simple; use thiserror:...
(&mut self) -> SinkResult<()> { if self.s.is_none() { // PulseAudio calls S24 and S24_3 different from the rest of the world let pulse_format = match self.format { AudioFormat::F32 => pulse::sample::Format::FLOAT32NE, AudioFormat::S32 => pulse::sample::For...
start
identifier_name
extern-yield.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 ...
{ for _ in range(0, 10u) { task::spawn(proc() { let result = count(5u); println!("result = {}", result); assert_eq!(result, 16u); }); } }
identifier_body
extern-yield.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 ...
() { for _ in range(0, 10u) { task::spawn(proc() { let result = count(5u); println!("result = {}", result); assert_eq!(result, 16u); }); } }
main
identifier_name
extern-yield.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 main() { for _ in range(0, 10u) { task::spawn(proc() { let result = count(5u); println!("result = {}", result); assert_eq!(result, 16u); }); } }
}
random_line_split
extern-yield.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 count(n: uint) -> uint { unsafe { task::deschedule(); rustrt::rust_dbg_call(cb, n) } } pub fn main() { for _ in range(0, 10u) { task::spawn(proc() { let result = count(5u); println!("result = {}", result); assert_eq!(result, 16u); }...
{ count(data - 1u) + count(data - 1u) }
conditional_block
lib.rs
use habitat_core::{self as hab_core, util}; use habitat_http_client as hab_http; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; #[allow(unused_imports)] #[macro_use] extern crate serde_json; mod allow_std_io; pub mod builder; pub mod error; pub mod response; use std::str::...
} } write!(f, "{}", output.join("\n")) } } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct OriginPrivateSigningKey { #[serde(with = "util::serde::string")] pub id: u64, #[serde(with = "util::serde::string")] pub origin_id: u64, pub name: Strin...
output.push(project.to_string())
random_line_split
lib.rs
use habitat_core::{self as hab_core, util}; use habitat_http_client as hab_http; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; #[allow(unused_imports)] #[macro_use] extern crate serde_json; mod allow_std_io; pub mod builder; pub mod error; pub mod response; use std::str::...
write!(f, "{}", output.join("\n")) } } #[derive(Clone, Serialize, Deserialize, Debug)] pub struct OriginPrivateSigningKey { #[serde(with = "util::serde::string")] pub id: u64, #[serde(with = "util::serde::string")] pub origin_id: u64, pub name: String, pub revision: S...
{ output.push("".to_string()); output.push("Reverse dependencies:".to_string()); let mut projects = self.projects.clone(); projects.sort_by(|a, b| a.ident.cmp(&b.ident)); for project in projects.iter() { output.push(project.to_string()) ...
conditional_block
lib.rs
use habitat_core::{self as hab_core, util}; use habitat_http_client as hab_http; #[macro_use] extern crate log; #[macro_use] extern crate serde_derive; #[allow(unused_imports)] #[macro_use] extern crate serde_json; mod allow_std_io; pub mod builder; pub mod error; pub mod response; use std::str::...
(s: &str) -> std::result::Result<Self, Self::Err> { let re = Regex::new(r"([\w]+)([-])([\d]+)").unwrap(); let caps = match re.captures(s) { Some(caps) => caps, None => return Err(Error::NotSupported), }; Ok(OriginKeyIdent { origin: caps.get(1).unwrap().as_str(...
from_str
identifier_name
authentication.rs
use std::io::{self, Read}; use aes::Aes192; use byteorder::{BigEndian, ByteOrder}; use hmac::Hmac; use pbkdf2::pbkdf2; use protobuf::ProtobufEnum; use serde::{Deserialize, Serialize}; use sha1::{Digest, Sha1}; use crate::protocol::authentication::AuthenticationType; /// The credentials are used to log into the Spoti...
let hi = read_u8(stream)? as u32; Ok(lo & 0x7f | hi << 7) } fn read_bytes<R: Read>(stream: &mut R) -> io::Result<Vec<u8>> { let length = read_int(stream)?; let mut data = vec![0u8; length as usize]; stream.read_exact(&mut data)?; ...
{ return Ok(lo); }
conditional_block
authentication.rs
use std::io::{self, Read}; use aes::Aes192; use byteorder::{BigEndian, ByteOrder}; use hmac::Hmac; use pbkdf2::pbkdf2; use protobuf::ProtobufEnum; use serde::{Deserialize, Serialize}; use sha1::{Digest, Sha1}; use crate::protocol::authentication::AuthenticationType; /// The credentials are used to log into the Spoti...
fn read_int<R: Read>(stream: &mut R) -> io::Result<u32> { let lo = read_u8(stream)? as u32; if lo & 0x80 == 0 { return Ok(lo); } let hi = read_u8(stream)? as u32; Ok(lo & 0x7f | hi << 7) } fn read_bytes<R: Read>(stre...
{ let mut data = [0u8]; stream.read_exact(&mut data)?; Ok(data[0]) }
identifier_body
authentication.rs
use std::io::{self, Read}; use aes::Aes192; use byteorder::{BigEndian, ByteOrder}; use hmac::Hmac; use pbkdf2::pbkdf2; use protobuf::ProtobufEnum; use serde::{Deserialize, Serialize}; use sha1::{Digest, Sha1}; use crate::protocol::authentication::AuthenticationType; /// The credentials are used to log into the Spoti...
<'de, D>(de: D) -> Result<Vec<u8>, D::Error> where D: serde::Deserializer<'de>, { let v: String = serde::Deserialize::deserialize(de)?; base64::decode(&v).map_err(|e| serde::de::Error::custom(e.to_string())) }
deserialize_base64
identifier_name
authentication.rs
use std::io::{self, Read}; use aes::Aes192; use byteorder::{BigEndian, ByteOrder}; use hmac::Hmac; use pbkdf2::pbkdf2; use protobuf::ProtobufEnum; use serde::{Deserialize, Serialize}; use sha1::{Digest, Sha1}; use crate::protocol::authentication::AuthenticationType; /// The credentials are used to log into the Spoti...
let hi = read_u8(stream)? as u32; Ok(lo & 0x7f | hi << 7) } fn read_bytes<R: Read>(stream: &mut R) -> io::Result<Vec<u8>> { let length = read_int(stream)?; let mut data = vec![0u8; length as usize]; stream.read_exact(&mut data)?; ...
random_line_split
alloc.rs
use crate::{ alloc::{GlobalAlloc, Layout, System}, sys::common::alloc::{realloc_fallback, MIN_ALIGN}, }; #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { if layout.align() <= MIN_ALIGN &...
}
{ unsafe { if layout.align() <= MIN_ALIGN && layout.align() <= new_size { libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 } else { realloc_fallback(self, ptr, layout, new_size) } } }
identifier_body
alloc.rs
use crate::{ alloc::{GlobalAlloc, Layout, System}, sys::common::alloc::{realloc_fallback, MIN_ALIGN}, }; #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { if layout.align() <= MIN_ALIGN &...
#[inline] unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { unsafe { libc::free(ptr as *mut libc::c_void) } } #[inline] unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { unsafe { if layout.align() <= MIN_ALIGN && layout.align()...
}
random_line_split
alloc.rs
use crate::{ alloc::{GlobalAlloc, Layout, System}, sys::common::alloc::{realloc_fallback, MIN_ALIGN}, }; #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { if layout.align() <= MIN_ALIGN &...
else { unsafe { libc::memalign(layout.align(), layout.size()) as *mut u8 } } } #[inline] unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) { unsafe { libc::free(ptr as *mut libc::c_void) } } #[inline] unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new...
{ unsafe { libc::malloc(layout.size()) as *mut u8 } }
conditional_block
alloc.rs
use crate::{ alloc::{GlobalAlloc, Layout, System}, sys::common::alloc::{realloc_fallback, MIN_ALIGN}, }; #[stable(feature = "alloc_system_type", since = "1.28.0")] unsafe impl GlobalAlloc for System { #[inline] unsafe fn alloc(&self, layout: Layout) -> *mut u8 { if layout.align() <= MIN_ALIGN &...
(&self, ptr: *mut u8, _layout: Layout) { unsafe { libc::free(ptr as *mut libc::c_void) } } #[inline] unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { unsafe { if layout.align() <= MIN_ALIGN && layout.align() <= new_size { libc:...
dealloc
identifier_name
lib.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 ...
/// A random number generator that can be explicitly seeded to produce /// the same stream of randomness multiple times. pub trait SeedableRng<Seed>: Rng { /// Reseed an RNG with the given seed. /// /// # Example /// /// ```rust /// use std::rand::{Rng, SeedableRng, StdRng}; /// /// let ...
}
random_line_split
lib.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 ...
} impl Rand for XorShiftRng { fn rand<R: Rng>(rng: &mut R) -> XorShiftRng { let mut tuple: (u32, u32, u32, u32) = rng.gen(); while tuple == (0, 0, 0, 0) { tuple = rng.gen(); } let (x, y, z, w) = tuple; XorShiftRng { x: x, y: y, z: z, w: w } } } /// A wrappe...
{ assert!(!seed.iter().all(|&x| x == 0), "XorShiftRng::from_seed called with an all zero seed."); XorShiftRng { x: seed[0], y: seed[1], z: seed[2], w: seed[3] } }
identifier_body
lib.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>(&mut self, values: &mut [T]) { let mut i = values.len(); while i >= 2u { // invariant: elements with index >= i have been locked in place. i -= 1u; // lock element i in place. values.swap(i, self.gen_range(0u, i + 1u)); } } } /// Iterator ...
shuffle
identifier_name
lib.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 ...
else { Some(&values[self.gen_range(0u, values.len())]) } } /// Shuffle a mutable slice in place. /// /// # Example /// /// ```rust /// use std::rand::{task_rng, Rng}; /// /// let mut rng = task_rng(); /// let mut y = [1i, 2, 3]; /// rng.shuffle(&mut y); ...
{ None }
conditional_block
mod.rs
use crate::{crypto::PublicKey, serializer::*}; use std::{ borrow::Cow, fmt::{self, Debug, Formatter}, io::{self, BufRead as IoBufRead, Cursor}, ops::Deref, }; pub mod builder; pub mod engine; pub mod error; pub mod op; mod stack; pub use self::builder::*; pub use self::engine::*; pub use self::error::...
cur.consume(4); } Ok(None) } } impl Debug for Script { fn fmt(&self, f: &mut Formatter) -> fmt::Result { let digest = faster_hex::hex_string(self.as_ref()).unwrap(); f.debug_tuple("Script").field(&digest).finish() } } impl From<&[u8]> for Script { #[inline...
{ let pos = cur.take_u32()?; return Ok(Some(pos)); }
conditional_block
mod.rs
use crate::{crypto::PublicKey, serializer::*}; use std::{ borrow::Cow, fmt::{self, Debug, Formatter}, io::{self, BufRead as IoBufRead, Cursor}, ops::Deref, }; pub mod builder; pub mod engine; pub mod error; pub mod op; mod stack; pub use self::builder::*; pub use self::engine::*; pub use self::error::...
} impl AsRef<[u8]> for Script { #[inline] fn as_ref(&self) -> &[u8] { &self.0 } } impl Deref for Script { type Target = [u8]; #[inline] fn deref(&self) -> &[u8] { &self.0 } }
{ Cow::Borrowed(self) }
identifier_body
mod.rs
use crate::{crypto::PublicKey, serializer::*}; use std::{ borrow::Cow, fmt::{self, Debug, Formatter}, io::{self, BufRead as IoBufRead, Cursor}, ops::Deref, }; pub mod builder; pub mod engine; pub mod error; pub mod op; mod stack; pub use self::builder::*; pub use self::engine::*; pub use self::error::...
(self) -> Cow<'a, Script> { Cow::Borrowed(self) } } impl AsRef<[u8]> for Script { #[inline] fn as_ref(&self) -> &[u8] { &self.0 } } impl Deref for Script { type Target = [u8]; #[inline] fn deref(&self) -> &[u8] { &self.0 } }
into
identifier_name
mod.rs
use crate::{crypto::PublicKey, serializer::*}; use std::{ borrow::Cow, fmt::{self, Debug, Formatter}, io::{self, BufRead as IoBufRead, Cursor}, ops::Deref, }; pub mod builder; pub mod engine; pub mod error; pub mod op; mod stack; pub use self::builder::*; pub use self::engine::*; pub use self::error::...
} } impl AsRef<[u8]> for Script { #[inline] fn as_ref(&self) -> &[u8] { &self.0 } } impl Deref for Script { type Target = [u8]; #[inline] fn deref(&self) -> &[u8] { &self.0 } }
fn into(self) -> Cow<'a, Script> { Cow::Borrowed(self)
random_line_split
dbscan.rs
//! Implementation of the [DBSCAN](https://en.wikipedia.org/wiki/DBSCAN) //! clustering algorithm. use matrix::SymmetricMatrix; use std::collections::VecDeque; /// Implementation of the [DBSCAN](https://en.wikipedia.org/wiki/DBSCAN) /// clustering algorithm. #[derive(Debug)] pub struct DBSCAN<T> { eps: T, min...
(&mut self, matrix: &SymmetricMatrix<T>, point: usize, mut neighbors: VecDeque<usize>) { self.clusters[point] = Some(self.current_cluster); while let Some(other_point) = neighbors.pop_front() { if!self.visited[other_point] { ...
expand_cluster
identifier_name
dbscan.rs
//! Implementation of the [DBSCAN](https://en.wikipedia.org/wiki/DBSCAN) //! clustering algorithm. use matrix::SymmetricMatrix; use std::collections::VecDeque; /// Implementation of the [DBSCAN](https://en.wikipedia.org/wiki/DBSCAN) /// clustering algorithm. #[derive(Debug)] pub struct DBSCAN<T> { eps: T, min...
} if self.clusters[other_point].is_none() { self.clusters[other_point] = Some(self.current_cluster); } } } fn region_query(&self, matrix: &SymmetricMatrix<T>, point: usize) -> VecDeque<usize> { let mut n...
neighbors.append(&mut other_neighbors); }
random_line_split
dbscan.rs
//! Implementation of the [DBSCAN](https://en.wikipedia.org/wiki/DBSCAN) //! clustering algorithm. use matrix::SymmetricMatrix; use std::collections::VecDeque; /// Implementation of the [DBSCAN](https://en.wikipedia.org/wiki/DBSCAN) /// clustering algorithm. #[derive(Debug)] pub struct DBSCAN<T> { eps: T, min...
if self.clusters[other_point].is_none() { self.clusters[other_point] = Some(self.current_cluster); } } } fn region_query(&self, matrix: &SymmetricMatrix<T>, point: usize) -> VecDeque<usize> { let mut neighbors = Ve...
{ self.visited[other_point] = true; let mut other_neighbors = self.region_query(matrix, other_point); if other_neighbors.len() >= self.min_points { neighbors.append(&mut other_neighbors); } }
conditional_block
dbscan.rs
//! Implementation of the [DBSCAN](https://en.wikipedia.org/wiki/DBSCAN) //! clustering algorithm. use matrix::SymmetricMatrix; use std::collections::VecDeque; /// Implementation of the [DBSCAN](https://en.wikipedia.org/wiki/DBSCAN) /// clustering algorithm. #[derive(Debug)] pub struct DBSCAN<T> { eps: T, min...
assert_eq!(clustering[4], None); } #[test] fn test_neighboring_points_are_put_into_cluster_even_if_they_have_been_visited() { // In 2D, the points in this test are placed as follows: // // 0 // 1 // 2 // // Epsilon is set to 1 ...
{ let mut dbscan = DBSCAN::new(1, 2); let mut m = SymmetricMatrix::<i8>::new(5); m.set(0, 1, 1); m.set(0, 2, 9); m.set(0, 3, 9); m.set(0, 4, 9); m.set(1, 2, 9); m.set(1, 3, 9); m.set(1, 4, 9); m.set(2, 3, 1); m.set(2, 4, 9); ...
identifier_body
cmp.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...
(&self, other: &bool) -> Option<Ordering> { (*self as u8).partial_cmp(&(*other as u8)) } } partial_ord_impl!(char uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64) macro_rules! ord_impl( ($($t:ty)*) => ($( #[unstable = "Trait is unstable."] impl Ord for $t...
partial_cmp
identifier_name
cmp.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...
) #[unstable = "Trait is unstable."] impl PartialEq for () { #[inline] fn eq(&self, _other: &()) -> bool { true } #[inline] fn ne(&self, _other: &()) -> bool { false } } partial_eq_impl!(bool char uint u8 u16 u32 u64 int i8 i16 i32 i64 f32 f64) macro_rules! eq_...
fn eq(&self, other: &$t) -> bool { (*self) == (*other) } #[inline] fn ne(&self, other: &$t) -> bool { (*self) != (*other) } } )*)
random_line_split
cmp.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...
} #[unstable = "Trait is unstable."] impl<'a, T: Eq> Eq for &'a mut T {} }
{ (**self).cmp(*other) }
identifier_body
osx_clipboard.rs
/* Copyright 2016 Avraham Weinstock 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 in writing, softwar...
fn get_contents(&mut self) -> Result<String, Box<Error>> { let string_class: Id<NSObject> = { let cls: Id<Class> = unsafe { Id::from_ptr(class("NSString")) }; unsafe { transmute(cls) } }; let classes: Id<NSArray<NSObject, Owned>> = NSArray::from_vec(vec![string_class...
{ let cls = try!(Class::get("NSPasteboard").ok_or(err("Class::get(\"NSPasteboard\")"))); let pasteboard: *mut Object = unsafe { msg_send![cls, generalPasteboard] }; if pasteboard.is_null() { return Err(err("NSPasteboard#generalPasteboard returned null")); } let pasteb...
identifier_body
osx_clipboard.rs
/* Copyright 2016 Avraham Weinstock 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 in writing, softwar...
else { Ok(string_array[0].as_str().to_owned()) } } fn set_contents(&mut self, data: String) -> Result<(), Box<Error>> { let string_array = NSArray::from_vec(vec![NSString::from_str(&data)]); let _: usize = unsafe { msg_send![self.pasteboard, clearContents] }; let suc...
{ Err(err("pasteboard#readObjectsForClasses:options: returned empty")) }
conditional_block
osx_clipboard.rs
/* Copyright 2016 Avraham Weinstock 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 in writing, softwar...
(name: &str) -> *mut Class { unsafe { transmute(Class::get(name)) } }
class
identifier_name
osx_clipboard.rs
/* Copyright 2016 Avraham Weinstock 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 in writing, softwar...
fn set_contents(&mut self, data: String) -> Result<(), Box<Error>> { let string_array = NSArray::from_vec(vec![NSString::from_str(&data)]); let _: usize = unsafe { msg_send![self.pasteboard, clearContents] }; let success: bool = unsafe { msg_send![self.pasteboard, writeObjects:string_array] ...
Err(err("pasteboard#readObjectsForClasses:options: returned empty")) } else { Ok(string_array[0].as_str().to_owned()) } }
random_line_split
poi.rs
use common::document::{ContainerDocument, Document}; use geojson::Geometry; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::sync::Arc; use super::admin::Admin; use super::context::Context; use super::coord::Coord; use super::i18n_properties::I18nProperties; use super::Members; use crate::...
}
{ geojson::Geometry::from(poi.coord) }
identifier_body
poi.rs
use common::document::{ContainerDocument, Document}; use geojson::Geometry; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::sync::Arc; use super::admin::Admin; use super::context::Context; use super::coord::Coord; use super::i18n_properties::I18nProperties; use super::Members; use crate::...
pub struct PoiType { pub id: String, pub name: String, } impl From<&navitia_poi_model::PoiType> for PoiType { fn from(poi_type: &navitia_poi_model::PoiType) -> PoiType { PoiType { id: normalize_id("poi_type:", poi_type.id.as_str()), name: poi_type.name.clone(), } ...
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
random_line_split
poi.rs
use common::document::{ContainerDocument, Document}; use geojson::Geometry; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; use std::sync::Arc; use super::admin::Admin; use super::context::Context; use super::coord::Coord; use super::i18n_properties::I18nProperties; use super::Members; use crate::...
(&self) -> Vec<Arc<Admin>> { self.administrative_regions.clone() } } impl From<&Poi> for geojson::Geometry { fn from(poi: &Poi) -> Self { geojson::Geometry::from(poi.coord) } }
admins
identifier_name
manager.rs
use anyhow::anyhow; use diesel::prelude::*; use std::time::{SystemTime, UNIX_EPOCH}; use super::*; use crate::app::settings::AuthSecret; use crate::db::DB; const HASH_ITERATIONS: u32 = 10000; #[derive(Clone)] pub struct Manager { // TODO make this private and move preferences methods in this file pub db: DB, auth...
.select(lastfm_session_key) .get_result(&connection)?; match token { Some(t) => Ok(t), _ => Err(anyhow!("Missing LastFM credentials")), } } pub fn is_lastfm_linked(&self, username: &str) -> bool { self.get_lastfm_session_key(username).is_ok() } pub fn lastfm_unlink(&self, username: &str) -> anyh...
random_line_split
manager.rs
use anyhow::anyhow; use diesel::prelude::*; use std::time::{SystemTime, UNIX_EPOCH}; use super::*; use crate::app::settings::AuthSecret; use crate::db::DB; const HASH_ITERATIONS: u32 = 10000; #[derive(Clone)] pub struct Manager { // TODO make this private and move preferences methods in this file pub db: DB, auth...
pub fn login(&self, username: &str, password: &str) -> Result<AuthToken, Error> { use crate::db::users::dsl::*; let connection = self.db.connect()?; match users .select(password_hash) .filter(name.eq(username)) .get_result(&connection) { Err(diesel::result::Error::NotFound) => Err(Error::Incorrec...
{ use crate::db::users::dsl::*; let connection = self.db.connect()?; diesel::update(users.filter(name.eq(username))) .set(admin.eq(is_admin as i32)) .execute(&connection) .map_err(|_| Error::Unspecified)?; Ok(()) }
identifier_body
manager.rs
use anyhow::anyhow; use diesel::prelude::*; use std::time::{SystemTime, UNIX_EPOCH}; use super::*; use crate::app::settings::AuthSecret; use crate::db::DB; const HASH_ITERATIONS: u32 = 10000; #[derive(Clone)] pub struct Manager { // TODO make this private and move preferences methods in this file pub db: DB, auth...
(password: &str) -> Result<String, Error> { if password.is_empty() { return Err(Error::EmptyPassword); } pbkdf2::pbkdf2_simple(password, HASH_ITERATIONS).map_err(|_| Error::Unspecified) } fn verify_password(password_hash: &str, attempted_password: &str) -> bool { pbkdf2::pbkdf2_check(attempted_password, password...
hash_password
identifier_name