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
borrowck-assign-comp-idx.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 ...
{ }
identifier_body
borrowck-assign-comp-idx.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 main() { }
}
random_line_split
borrowck-assign-comp-idx.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 ...
<F>(_x: &[isize], _f: F) where F: FnOnce() {} fn b() { // here we alias the mutable vector into an imm slice and try to // modify the original: let mut p = vec![1]; borrow( &p, || p[0] = 5); //~ ERROR cannot borrow `p` as mutable } fn c() { // Legal because the scope of the borro...
borrow
identifier_name
objc_protocol_inheritance.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; pub trait PFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub...
fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl PFoo for Foo {} impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref {} #[repr(transpa...
impl std::ops::Deref for Foo { type Target = objc::runtime::Object;
random_line_split
objc_protocol_inheritance.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; pub trait PFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub...
} unsafe impl objc::Message for Foo {} impl Foo { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Foo), alloc) }) } } impl PFoo for Foo {} impl IFoo for Foo {} pub trait IFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub struct Bar(pub id); impl std::ops::Deref for...
{ unsafe { &*self.0 } }
identifier_body
objc_protocol_inheritance.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; pub trait PFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub...
(pub id); impl std::ops::Deref for Bar { type Target = objc::runtime::Object; fn deref(&self) -> &Self::Target { unsafe { &*self.0 } } } unsafe impl objc::Message for Bar {} impl Bar { pub fn alloc() -> Self { Self(unsafe { msg_send!(objc::class!(Bar), alloc) }) } } impl IFoo for Bar...
Bar
identifier_name
objc_protocol_inheritance.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #![cfg(target_os = "macos")] #[macro_use] extern crate objc; #[allow(non_camel_case_types)] pub type id = *mut objc::runtime::Object; pub trait PFoo: Sized + std::ops::Deref {} #[repr(transparent)] #[derive(Clone)] pub...
else { Err("This Foo cannot be downcasted to Bar") } } } impl IBar for Bar {} pub trait IBar: Sized + std::ops::Deref {}
{ Ok(Bar(parent.0)) }
conditional_block
regions-implied-bounds-projection-gap-2.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 ...
#![allow(unused_variables)] trait Trait1<'x> { type Foo; } // calling this fn should trigger a check that the type argument // supplied is well-formed. fn wf<T>() { } fn func<'x, T:Trait1<'x>>(t: &'x T) { wf::<&'x T::Foo>(); } fn main() { }
// enough to conclude that `T::Foo: 'x`. // compile-pass #![allow(dead_code)]
random_line_split
regions-implied-bounds-projection-gap-2.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 ...
() { }
main
identifier_name
regions-implied-bounds-projection-gap-2.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 main() { }
{ wf::<&'x T::Foo>(); }
identifier_body
enable_transparency.rs
use super::internal_prelude::*; use imageflow_types::{PixelFormat, CompositingMode}; use crate::ffi::BitmapCompositingMode; use crate::graphics::bitmaps::BitmapCompositing; pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{}; pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = En...
else if parent.fmt == PixelFormat::Bgr32 { let mutate = ctx.graph .add_node(Node::n(&ENABLE_TRANSPARENCY_MUT, NodeParams::None)); ctx.replace_node_with_existing(ix, mutate); Ok(()) } else { let canvas_params = imageflow_types::Node::CreateCanvas { ...
{ ctx.delete_node_and_snap_together(ix); Ok(()) }
conditional_block
enable_transparency.rs
use super::internal_prelude::*; use imageflow_types::{PixelFormat, CompositingMode}; use crate::ffi::BitmapCompositingMode; use crate::graphics::bitmaps::BitmapCompositing; pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{}; pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = En...
w: parent.w as u32, h: parent.h as u32, x: 0, y: 0 }; let canvas = ctx.graph .add_node(Node::n(&CREATE_CANVAS, NodeParams::Json(canvas_params))); let copy = ctx.graph ...
from_x: 0, from_y: 0,
random_line_split
enable_transparency.rs
use super::internal_prelude::*; use imageflow_types::{PixelFormat, CompositingMode}; use crate::ffi::BitmapCompositingMode; use crate::graphics::bitmaps::BitmapCompositing; pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{}; pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = En...
fn expand(&self, ctx: &mut OpCtxMut, ix: NodeIndex, p: NodeParams, parent: FrameInfo) -> Result<()> { if parent.fmt == PixelFormat::Bgra32{ ctx.delete_node_and_snap_together(ix); Ok(()) }else if parent.fmt == PixelFormat::Bgr32 { let mutate = ctx.graph ...
{ "imazen.enable_transparency" }
identifier_body
enable_transparency.rs
use super::internal_prelude::*; use imageflow_types::{PixelFormat, CompositingMode}; use crate::ffi::BitmapCompositingMode; use crate::graphics::bitmaps::BitmapCompositing; pub static ENABLE_TRANSPARENCY: EnableTransparencyDef = EnableTransparencyDef{}; pub static ENABLE_TRANSPARENCY_MUT: EnableTransparencyMutDef = En...
; impl NodeDef for EnableTransparencyMutDef{ fn as_one_mutate_bitmap(&self) -> Option<&dyn NodeDefMutateBitmap>{ Some(self) } } impl NodeDefMutateBitmap for EnableTransparencyMutDef{ fn fqn(&self) -> &'static str{ "imazen.enable_transparency_mut" } fn mutate(&self, c: &Context, bitma...
EnableTransparencyMutDef
identifier_name
main.rs
extern crate rand; use rand::{thread_rng, Rng}; use std::io::stdin; const LOWEST: isize = 1; const HIGHEST: isize = 100; fn main()
None => println!("numbers only, please"), Some(n) if n == number => { println!("you got it in {} tries!", num_guesses); break; } Some(n) if n < number => println!("too low!"), Some(n) if n > number =>...
{ let mut rng = thread_rng(); loop { let number: isize = rng.gen_range(LOWEST, HIGHEST + 1); let mut num_guesses = 0; println!( "I have chosen my number between {} and {}. You know what to do", LOWEST, HIGHEST ); loop { num_guesses +...
identifier_body
main.rs
extern crate rand; use rand::{thread_rng, Rng}; use std::io::stdin; const LOWEST: isize = 1; const HIGHEST: isize = 100; fn
() { let mut rng = thread_rng(); loop { let number: isize = rng.gen_range(LOWEST, HIGHEST + 1); let mut num_guesses = 0; println!( "I have chosen my number between {} and {}. You know what to do", LOWEST, HIGHEST ); loop { num_guesse...
main
identifier_name
main.rs
extern crate rand; use rand::{thread_rng, Rng}; use std::io::stdin; const LOWEST: isize = 1; const HIGHEST: isize = 100; fn main() { let mut rng = thread_rng(); loop { let number: isize = rng.gen_range(LOWEST, HIGHEST + 1); let mut num_guesses = 0; println!( "I have chos...
} } }
Some(_) => println!("something went wrong"), }
random_line_split
assistant.rs
use std::mem::transmute; use std::boxed::Box as Box_; use Assistant; use ffi; use glib::object::IsA; use glib_ffi; pub trait AssistantExtManual { fn set_forward_page_func<F: Fn(i32) -> i32 +'static>(&self, f: F); } impl<O: IsA<Assistant>> AssistantExtManual for O { fn set_forward_page_func<F: Fn(i32) -> i32 ...
} unsafe extern "C" fn forward_page_trampoline(current_page: i32, f: glib_ffi::gpointer) -> i32 { callback_guard!(); let f: &Box_<Fn(i32) -> i32 +'static> = transmute(f); f(current_page) } unsafe extern "C" fn destroy_closure(ptr: glib_ffi::gpointer) { callback_guard!(); Box_::<Box_<Fn(i32) -> i32...
Some(forward_page_trampoline), Box_::into_raw(f) as *mut _, Some(destroy_closure)) } }
random_line_split
assistant.rs
use std::mem::transmute; use std::boxed::Box as Box_; use Assistant; use ffi; use glib::object::IsA; use glib_ffi; pub trait AssistantExtManual { fn set_forward_page_func<F: Fn(i32) -> i32 +'static>(&self, f: F); } impl<O: IsA<Assistant>> AssistantExtManual for O { fn set_forward_page_func<F: Fn(i32) -> i32 ...
(current_page: i32, f: glib_ffi::gpointer) -> i32 { callback_guard!(); let f: &Box_<Fn(i32) -> i32 +'static> = transmute(f); f(current_page) } unsafe extern "C" fn destroy_closure(ptr: glib_ffi::gpointer) { callback_guard!(); Box_::<Box_<Fn(i32) -> i32 +'static>>::from_raw(ptr as *mut _); }
forward_page_trampoline
identifier_name
assistant.rs
use std::mem::transmute; use std::boxed::Box as Box_; use Assistant; use ffi; use glib::object::IsA; use glib_ffi; pub trait AssistantExtManual { fn set_forward_page_func<F: Fn(i32) -> i32 +'static>(&self, f: F); } impl<O: IsA<Assistant>> AssistantExtManual for O { fn set_forward_page_func<F: Fn(i32) -> i32 ...
{ callback_guard!(); Box_::<Box_<Fn(i32) -> i32 + 'static>>::from_raw(ptr as *mut _); }
identifier_body
test.rs
use std::thread::{self, sleep_ms}; use std::sync::{Arc}; use std::sync::atomic::{AtomicUsize}; use std::sync::atomic::Ordering::{SeqCst}; use spsc::unbounded::{new}; use super::{Select, Selectable}; fn ms_sleep(ms: i64) { sleep_ms(ms as u32); } #[test] fn no_wait_one() { let (send, recv) = new(); send.se...
// make sure that we wait for the other thread before dropping anything else drop(thread); } #[test] fn select_chance() { // Check that only one selecting thread wakes up. let counter1 = Arc::new(AtomicUsize::new(0)); let counter2 = counter1.clone(); let counter3 = counter1.clone(); let (...
{ // Check that cross thread selecting works. let (send1, recv1) = new(); let (send2, recv2) = new(); let id1 = recv1.id(); let id2 = recv2.id(); let select1 = Arc::new(Select::new()); let select2 = select1.clone(); let thread = thread::scoped(move || { select2.add(&recv2); ...
identifier_body
test.rs
use std::thread::{self, sleep_ms}; use std::sync::{Arc}; use std::sync::atomic::{AtomicUsize}; use std::sync::atomic::Ordering::{SeqCst}; use spsc::unbounded::{new}; use super::{Select, Selectable}; fn ms_sleep(ms: i64) { sleep_ms(ms as u32); } #[test] fn no_wait_one() { let (send, recv) = new(); send.se...
} } assert!(saw1); } #[test] fn select_wrong_thread() { // Check that cross thread selecting works. let (send1, recv1) = new(); let (send2, recv2) = new(); let id1 = recv1.id(); let id2 = recv2.id(); let select1 = Arc::new(Select::new()); let select2 = select1.clone(); ...
{ break 'outer; }
conditional_block
test.rs
use std::thread::{self, sleep_ms}; use std::sync::{Arc}; use std::sync::atomic::{AtomicUsize}; use std::sync::atomic::Ordering::{SeqCst}; use spsc::unbounded::{new}; use super::{Select, Selectable}; fn ms_sleep(ms: i64) { sleep_ms(ms as u32); } #[test] fn no_wait_one() { let (send, recv) = new(); send.se...
fn no_wait_two() { let (send, recv) = new(); let (send2, recv2) = new(); send.send(1u8).unwrap(); send2.send(1u8).unwrap(); let select = Select::new(); select.add(&recv); select.add(&recv2); assert!(select.wait(&mut [0, 0]).len() == 2); } #[test] fn wait_two() { let (send, recv) = n...
} #[test]
random_line_split
test.rs
use std::thread::{self, sleep_ms}; use std::sync::{Arc}; use std::sync::atomic::{AtomicUsize}; use std::sync::atomic::Ordering::{SeqCst}; use spsc::unbounded::{new}; use super::{Select, Selectable}; fn
(ms: i64) { sleep_ms(ms as u32); } #[test] fn no_wait_one() { let (send, recv) = new(); send.send(1u8).unwrap(); let select = Select::new(); select.add(&recv); assert!(select.wait(&mut [0]).len() == 1); } #[test] fn wait_one() { let (send, recv) = new(); thread::spawn(move || { ...
ms_sleep
identifier_name
util.rs
//! Module for utility functions. /// Verifies equality between an array of length 16 and a slice of unknown length. pub fn verify_16(x: &[u8; 16], y: &[u8]) -> bool
#[inline(never)] pub(crate) fn verify_inner(x: &impl AsRef<[u8]>, y: &[u8]) -> u8 { let x = x.as_ref(); assert_eq!(x.len(), y.len()); x.iter().zip(y).fold(0, |acc, (x, y)| acc | (x ^ y)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_verify_16() { assert!(verify_16(b"abcdef...
{ x.len() == y.len() && verify_inner(x, y) == 0 }
identifier_body
util.rs
//! Module for utility functions. /// Verifies equality between an array of length 16 and a slice of unknown length. pub fn verify_16(x: &[u8; 16], y: &[u8]) -> bool { x.len() == y.len() && verify_inner(x, y) == 0 } #[inline(never)] pub(crate) fn verify_inner(x: &impl AsRef<[u8]>, y: &[u8]) -> u8 { let x = x....
() { assert!(verify_16(b"abcdefghijklmnop", b"abcdefghijklmnop")); assert!(verify_16(&[0xff; 16], &[0xff; 16])); assert!(verify_16(&[0x80; 16], &[0x80; 16])); assert!(!verify_16(b"abcdefghijklmnop", b"ponmlkjihgfedcba")); assert!(!verify_16(b"abcdefghijklmnop", b"")); as...
test_verify_16
identifier_name
util.rs
//! Module for utility functions. /// Verifies equality between an array of length 16 and a slice of unknown length. pub fn verify_16(x: &[u8; 16], y: &[u8]) -> bool { x.len() == y.len() && verify_inner(x, y) == 0 } #[inline(never)] pub(crate) fn verify_inner(x: &impl AsRef<[u8]>, y: &[u8]) -> u8 { let x = x....
fn test_verify_inner() { assert_eq!(0, verify_inner(b"", b"")); assert_eq!(0, verify_inner(b"Hello!", b"Hello!")); assert_eq!(0, verify_inner(&[0x80, 0xff], &[0x80, 0xff])); assert_ne!(0, verify_inner(b"ok", b"ko")); assert_ne!(0, verify_inner(&[0x80, 0xff], &[0xff, 0x80]));...
random_line_split
cell.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
} } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Failure /// /// Fails if the value is currently mutably borrowed. #[unstable] pub ...
{ self.borrow.set(borrow + 1); Some(Ref { _parent: self }) }
conditional_block
cell.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._parent.borrow.set(borrow - 1); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for Ref<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } /// Copy...
random_line_split
cell.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._parent.borrow.set(borrow - 1); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for Ref<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { ...
drop
identifier_name
util.rs
// Small functions of utility use core::SearchType::{self, ExactMatch, StartsWith}; use core::Session; use std::cmp; use std::path::Path; pub fn getline(filepath: &Path, linenum: usize, session: &Session) -> String { let src = session.load_file(filepath); src.code.lines().nth(linenum - 1).unwrap_or("not found...
match stype { ExactMatch => searchstr == candidate, StartsWith => candidate.starts_with(searchstr) } } // pub fn get_backtrace() -> String { // let mut m = std::old_io::MemWriter::new(); // let s = std::rt::backtrace::write(&mut m) // .ok().map_or("NO backtrace".to_string(), // ...
pub fn symbol_matches(stype: SearchType, searchstr: &str, candidate: &str) -> bool {
random_line_split
util.rs
// Small functions of utility use core::SearchType::{self, ExactMatch, StartsWith}; use core::Session; use std::cmp; use std::path::Path; pub fn getline(filepath: &Path, linenum: usize, session: &Session) -> String { let src = session.load_file(filepath); src.code.lines().nth(linenum - 1).unwrap_or("not found...
pub fn is_ident_char(c: char) -> bool { c.is_alphanumeric() || (c == '_') || (c == '!') } pub fn txt_matches(stype: SearchType, needle: &str, haystack: &str) -> bool { match stype { ExactMatch => { let n_len = needle.len(); let h_len = haystack.len(); if n_len == ...
{ c.is_alphanumeric() || (c == '_') || (c == ':') || (c == '.') }
identifier_body
util.rs
// Small functions of utility use core::SearchType::{self, ExactMatch, StartsWith}; use core::Session; use std::cmp; use std::path::Path; pub fn
(filepath: &Path, linenum: usize, session: &Session) -> String { let src = session.load_file(filepath); src.code.lines().nth(linenum - 1).unwrap_or("not found").to_string() } pub fn is_pattern_char(c: char) -> bool { c.is_alphanumeric() || c.is_whitespace() || (c == '_') || (c == ':') || (c == '.') } pub ...
getline
identifier_name
urls.rs
/* vim: set et: */ use url; use hyper; use types::FolderId; use types::ProgramId; use std::fmt; pub enum EVUrl { Login, Folder(FolderId), Program(ProgramId), Move(ProgramId, FolderId) } impl hyper::client::IntoUrl for EVUrl { fn into_url(self) -> Result<url::Url, url::ParseError> { // TOD...
} impl fmt::Display for EVUrl { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { EVUrl::Login => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/login.sl"), EVUrl::Folder(ref id) => match *id { FolderId::Root => write!(fmt, "https://api.elis...
}
random_line_split
urls.rs
/* vim: set et: */ use url; use hyper; use types::FolderId; use types::ProgramId; use std::fmt; pub enum EVUrl { Login, Folder(FolderId), Program(ProgramId), Move(ProgramId, FolderId) } impl hyper::client::IntoUrl for EVUrl { fn into_url(self) -> Result<url::Url, url::ParseError> { // TOD...
} #[cfg(test)] mod tests { use super::EVUrl; use types::FolderId; use types::ProgramId; #[test] fn show_login_url() { let url = EVUrl::Login; assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/login.sl"); } #[test] fn show_root_folder_url() { l...
{ match *self { EVUrl::Login => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/login.sl"), EVUrl::Folder(ref id) => match *id { FolderId::Root => write!(fmt, "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true"), ref id => write!(fmt, "https://...
identifier_body
urls.rs
/* vim: set et: */ use url; use hyper; use types::FolderId; use types::ProgramId; use std::fmt; pub enum EVUrl { Login, Folder(FolderId), Program(ProgramId), Move(ProgramId, FolderId) } impl hyper::client::IntoUrl for EVUrl { fn into_url(self) -> Result<url::Url, url::ParseError> { // TOD...
() { let url = EVUrl::Login; assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/login.sl"); } #[test] fn show_root_folder_url() { let url = EVUrl::Folder(FolderId::Root); assert!(url.to_string() == "https://api.elisaviihde.fi/etvrecorder/ready.sl?ajax=true");...
show_login_url
identifier_name
store.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::ErrorKind; use async_trait::async_trait; use bookmarks::BookmarkName; use bytes::Bytes; use changeset_info::ChangesetInfo; use ...
{ Directory, File(ContentId), } #[derive(Clone, Debug)] pub enum FileChange { Added(ContentId), Changed(ContentId, ContentId), Removed, }
PathContent
identifier_name
store.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::ErrorKind; use async_trait::async_trait; use bookmarks::BookmarkName; use bytes::Bytes; use changeset_info::ChangesetInfo; use ...
ctx: &'a CoreContext, bookmark: BookmarkName, paths: Vec<MPath>, ) -> Result<HashMap<MPath, PathContent>, ErrorKind>; async fn file_changes<'a>( &'a self, ctx: &'a CoreContext, new_cs_id: ChangesetId, old_cs_id: ChangesetId, ) -> Result<Vec<(MPath, Fi...
&'a self,
random_line_split
draw.rs
use specs::{ReadExpect, ReadStorage, System, WriteStorage}; use crate::animation::SpriteData; use crate::combat::components::{AnimationState, Draw, State, UnitType}; pub struct UpdateImage; impl<'a> System<'a> for UpdateImage { type SystemData = ( ReadExpect<'a, SpriteData>, WriteStorage<'a, Draw...
let animation = draw.animation.as_str(); let sprite_resource = sprites.get(&unit_type.name); if let Some(sprite) = sprite_resource { let animation = sprite .animations .get(animation) .unwrap_or_else(|| panic!("...
{
random_line_split
draw.rs
use specs::{ReadExpect, ReadStorage, System, WriteStorage}; use crate::animation::SpriteData; use crate::combat::components::{AnimationState, Draw, State, UnitType}; pub struct
; impl<'a> System<'a> for UpdateImage { type SystemData = ( ReadExpect<'a, SpriteData>, WriteStorage<'a, Draw>, ReadStorage<'a, AnimationState>, ReadStorage<'a, UnitType>, WriteStorage<'a, State>, ); fn run( &mut self, (sprite_data, mut draw, animati...
UpdateImage
identifier_name
draw.rs
use specs::{ReadExpect, ReadStorage, System, WriteStorage}; use crate::animation::SpriteData; use crate::combat::components::{AnimationState, Draw, State, UnitType}; pub struct UpdateImage; impl<'a> System<'a> for UpdateImage { type SystemData = ( ReadExpect<'a, SpriteData>, WriteStorage<'a, Draw...
} } } }
{ let animation = sprite .animations .get(animation) .unwrap_or_else(|| panic!("{} not found in yaml", animation)); match &animation.order { None => { draw.frame = ...
conditional_block
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
Named(ref fields) => { let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span)) }).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) ...
{ let default_ident = vec!( cx.ident_of("std"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new()); return match *substr.fields { StaticStruct(_, ref sum...
identifier_body
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> Gc<Expr> { let default_ident = vec!( cx.ident_of("std"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, defaul...
default_substructure
identifier_name
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
}).collect(); cx.expr_struct_ident(trait_span, substr.type_ident, default_fields) } } } StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation conti...
let default_fields = fields.iter().map(|&(ident, span)| { cx.field_imm(span, ident, default_call(span))
random_line_split
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::au...
pub fn facebook_login() -> Result<Credentials, ()> { let (tx, rx) = mpsc::channel(); let csrf = rand::thread_rng().gen_ascii_chars().take(32).collect::<String>(); let handler = ServerHandler { token_tx: Mutex::new(tx), csrf: csrf.clone() }; let ssl = ssl_context().unwrap(); ...
{ let url = format!("https://graph.facebook.com/me?fields=id&access_token={}", token); let client = hyper::Client::new(); let mut response = client.get(&url).send().unwrap(); let mut body = String::new(); response.read_to_string(&mut body).unwrap(); let mut result : BTreeMap<String, String> = ...
identifier_body
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::au...
} else { hyper::status::StatusCode::NotFound } } } fn facebook_get_me_id(token: &str) -> Result<String, ()> { let url = format!("https://graph.facebook.com/me?fields=id&access_token={}", token); let client = hyper::Client::new(); let mut response = client.get(&url).send()....
{ hyper::status::StatusCode::NotFound }
conditional_block
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::au...
let mut server = hyper::Server::new(listener).handle(handler).unwrap(); println!("Logging in using Facebook, please visit https://login.spotify.com/login-facebook-sso/?csrf={}&port={} in your browser.", csrf, port); let token = rx.recv().unwrap(); let user_id = facebook_get_me_id(&token)...
random_line_split
facebook.rs
use hyper; use hyper::net::NetworkListener; use hyper::server::Request; use hyper::server::Response; use hyper::uri::RequestUri; use hyper::header::AccessControlAllowOrigin; use rand::{self, Rng}; use serde_json; use std::collections::BTreeMap; use std::io::Read; use std::sync::{mpsc, Mutex}; use url; use protocol::au...
(&self, params: &BTreeMap<String, String>) -> hyper::status::StatusCode { let token = params.get("access_token").unwrap(); let csrf = params.get("csrf").unwrap(); if *csrf == self.csrf { self.token_tx.lock().unwrap().send(token.to_owned()).unwrap(); hyper::status::Status...
handle_login
identifier_name
scell_seal_string_echo.rs
// Copyright 2019 (c) rust-themis 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 o...
use themis::secure_cell::SecureCell; fn main() { let matches = clap_app!(scell_seal_string_echo => (version: env!("CARGO_PKG_VERSION")) (about: "Secure Cell echo testing tool (sealing mode).") (@arg mode: +required "<enc|dec>") (@arg key: +required "master key") (@arg...
use clap::clap_app;
random_line_split
scell_seal_string_echo.rs
// Copyright 2019 (c) rust-themis 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 o...
() { let matches = clap_app!(scell_seal_string_echo => (version: env!("CARGO_PKG_VERSION")) (about: "Secure Cell echo testing tool (sealing mode).") (@arg mode: +required "<enc|dec>") (@arg key: +required "master key") (@arg message: +required "message to encrypt or de...
main
identifier_name
scell_seal_string_echo.rs
// Copyright 2019 (c) rust-themis 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 o...
}) .seal(); match mode { "enc" => { let encrypted = cell .encrypt_with_context(&message, &context) .unwrap_or_else(|error| { eprintln!("failed to encrypt message: {}", error); exit(1); }); ...
{ let matches = clap_app!(scell_seal_string_echo => (version: env!("CARGO_PKG_VERSION")) (about: "Secure Cell echo testing tool (sealing mode).") (@arg mode: +required "<enc|dec>") (@arg key: +required "master key") (@arg message: +required "message to encrypt or decry...
identifier_body
user.rs
use std::convert::From; use crypto; use diesel; use errors::Error; use diesel::prelude::*; use data::schema::users; use data::users::{User as ModelUser, NewUser as ModelNewUser}; #[derive(Serialize, Deserialize)] pub struct
{ pub id: Uuid, pub email: String, #[serde(skip_serializing, skip_deserializing)] pub password: Vec<u8>, } impl From<ModelUser> for User { fn from(user: ModelUser) -> User { User { id: user.id, email: user.email, password: user.password, } } ...
User
identifier_name
user.rs
use std::convert::From; use crypto; use diesel; use errors::Error; use diesel::prelude::*; use data::schema::users; use data::users::{User as ModelUser, NewUser as ModelNewUser}; #[derive(Serialize, Deserialize)] pub struct User { pub id: Uuid, pub email: String, #[serde(skip_serializing, skip_deserializi...
} pub struct NewUser<'a> { pub email: &'a str, pub password: Vec<u8>, } pub fn create_user<'a>(user: &'a NewUser, conn: &'a PgConnection) -> Result<User, Error> { let new_user = ModelUser { email: &user.email.to_lowercase(), password: crypto::hash(user.password.as_ref(), crypto::generate_...
{ crypto::verify(&self.password, plaintext.as_bytes()).unwrap(); }
identifier_body
user.rs
use std::convert::From; use crypto; use diesel; use errors::Error; use diesel::prelude::*; use data::schema::users; use data::users::{User as ModelUser, NewUser as ModelNewUser}; #[derive(Serialize, Deserialize)] pub struct User { pub id: Uuid, pub email: String, #[serde(skip_serializing, skip_deserializi...
email: user.email, password: user.password, } } } impl User { pub fn verify_password(&self, plaintext: &str) -> bool { crypto::verify(&self.password, plaintext.as_bytes()).unwrap(); } } pub struct NewUser<'a> { pub email: &'a str, pub password: Vec<u8>, } p...
impl From<ModelUser> for User { fn from(user: ModelUser) -> User { User { id: user.id,
random_line_split
super.rs
fn function() { println!("called `function()`"); } mod cool { pub fn
() { println!("called `cool::function()`"); } } mod my { fn function() { println!("called `my::function()`"); } mod cool { pub fn function() { println!("called `my::cool::function()`"); } } pub fn indirect_call() { // Let's access al...
function
identifier_name
super.rs
fn function() { println!("called `function()`"); } mod cool { pub fn function() { println!("called `cool::function()`"); } } mod my { fn function() { println!("called `my::function()`"); } mod cool { pub fn function()
} pub fn indirect_call() { // Let's access all the functions named `function` from this scope! print!("called `my::indirect_call()`, that\n> "); // The `self` keyword refers to the current module scope - in this case `my`. // Calling `self::function()` and calling ...
{ println!("called `my::cool::function()`"); }
identifier_body
super.rs
fn function() { println!("called `function()`"); } mod cool { pub fn function() { println!("called `cool::function()`"); } } mod my { fn function() { println!("called `my::function()`"); } mod cool { pub fn function() { println!("called `my::cool::funct...
// the same result, because they refer to the same function. self::function(); function(); // We can also use `self` to access another module inside `my`: self::cool::function(); // The `super` keyword refers to the parent scope (outside the `my` module)...
// The `self` keyword refers to the current module scope - in this case `my`. // Calling `self::function()` and calling `function()` directly both give
random_line_split
hamming_numbers.rs
// http://rosettacode.org/wiki/Hamming_numbers extern crate num; use num::bigint::{BigUint, ToBigUint}; use std::cmp::min; use std::num::{One, one}; use std::collections::{RingBuf, Deque}; // needed because hamming_numbers_alt uses this as a library #[allow(dead_code)] #[cfg(not(test))] fn main() { // capacity of ...
h } /// Pushes the next multiple of `n` (x2, x3, x5) to the queues pub fn enqueue(&mut self, n: &T) { let (two, three, five) = HammingNumber::multipliers(); self.q2.push(*n * two); self.q3.push(*n * three); self.q5.push(*n * five); } } // Implements the `Iterat...
h.q2.push(one()); h.q3.push(one()); h.q5.push(one());
random_line_split
hamming_numbers.rs
// http://rosettacode.org/wiki/Hamming_numbers extern crate num; use num::bigint::{BigUint, ToBigUint}; use std::cmp::min; use std::num::{One, one}; use std::collections::{RingBuf, Deque}; // needed because hamming_numbers_alt uses this as a library #[allow(dead_code)] #[cfg(not(test))] fn main() { // capacity of ...
() { let mut hamming = Hamming::<BigUint>::new(20); assert!(hamming.nth(19).unwrap().to_biguint() == 36u.to_biguint()); } #[test] fn hamming_iter_1million() { let mut hamming = Hamming::<BigUint>::new(128); // one-million-th hamming number has index 999_999 because indexes are zero-based assert_eq!...
hamming_iter
identifier_name
hamming_numbers.rs
// http://rosettacode.org/wiki/Hamming_numbers extern crate num; use num::bigint::{BigUint, ToBigUint}; use std::cmp::min; use std::num::{One, one}; use std::collections::{RingBuf, Deque}; // needed because hamming_numbers_alt uses this as a library #[allow(dead_code)] #[cfg(not(test))] fn main() { // capacity of ...
; let h5 = if five { self.q5.pop_front() } else { None }; match h2.or(h3).or(h5) { Some(n) => { self.enqueue(&n); Some(n) } None => unreachable!() } } } #[test] fn create() { let mut h = Hamming::<BigUint>::new(5); ...
{ None }
conditional_block
lib.rs
#![allow(non_snake_case)] mod counter; use counter::Counter; use std::mem::transmute; #[no_mangle] pub extern fn createCounter(val: u32) -> *mut Counter { let _counter = unsafe { transmute(Box::new(Counter::new(val))) }; _counter } #[no_mangle] pub extern fn getCounterValue(ptr: *mut Counter) -> u32 { l...
#[no_mangle] pub extern fn incrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.incr(bys) } #[no_mangle] pub extern fn decrementCounterBy(ptr: *mut Counter, by...
_counter.get() }
random_line_split
lib.rs
#![allow(non_snake_case)] mod counter; use counter::Counter; use std::mem::transmute; #[no_mangle] pub extern fn createCounter(val: u32) -> *mut Counter { let _counter = unsafe { transmute(Box::new(Counter::new(val))) }; _counter } #[no_mangle] pub extern fn getCounterValue(ptr: *mut Counter) -> u32 { l...
#[no_mangle] pub extern fn decrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.decr(bys) } #[no_mangle] pub extern fn destroyCounter(ptr: *mut Counter) { ...
{ let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) }; _counter.incr(bys) }
identifier_body
lib.rs
#![allow(non_snake_case)] mod counter; use counter::Counter; use std::mem::transmute; #[no_mangle] pub extern fn createCounter(val: u32) -> *mut Counter { let _counter = unsafe { transmute(Box::new(Counter::new(val))) }; _counter } #[no_mangle] pub extern fn
(ptr: *mut Counter) -> u32 { let mut _counter = unsafe { &mut *ptr }; _counter.get() } #[no_mangle] pub extern fn incrementCounterBy(ptr: *mut Counter, bys_ptr: *const u32, bys_len: usize) -> u32 { let mut _counter = unsafe { &mut *ptr }; let bys = unsafe { std::slice::from_raw_parts(bys_ptr, bys_len) ...
getCounterValue
identifier_name
associated-types-in-impl-generics.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) -> &isize { &self.x } } trait Grab { type U; fn grab(&self) -> &<Self as Grab>::U; } impl<T:Get> Grab for T { type U = <T as Get>::Value; fn grab(&self) -> &<T as Get>::Value { self.get() } } fn main() { let s = Struct { x: 100, }; assert_eq!(*s.gra...
get
identifier_name
associated-types-in-impl-generics.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 ...
} trait Grab { type U; fn grab(&self) -> &<Self as Grab>::U; } impl<T:Get> Grab for T { type U = <T as Get>::Value; fn grab(&self) -> &<T as Get>::Value { self.get() } } fn main() { let s = Struct { x: 100, }; assert_eq!(*s.grab(), 100); }
{ &self.x }
identifier_body
associated-types-in-impl-generics.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 ...
} struct Struct { x: isize, } impl Get for Struct { type Value = isize; fn get(&self) -> &isize { &self.x } } trait Grab { type U; fn grab(&self) -> &<Self as Grab>::U; } impl<T:Get> Grab for T { type U = <T as Get>::Value; fn grab(&self) -> &<T as Get>::Value { self....
trait Get { type Value; fn get(&self) -> &<Self as Get>::Value;
random_line_split
merge_intervals.rs
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] ...
} }
random_line_split
merge_intervals.rs
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] ...
merged .last_mut() .map(|last| last[1] = last[1].max(interval[1])); } } merged } #[cfg(test)] mod tests { use super::*; #[test] fn test_merge() { let r = merge(vec![vec![1, 3], vec![2, 6], vec![8, 10], vec![15, 18]]); let expect = vec![v...
} else { // 和最后一个相交,两个取并集
conditional_block
merge_intervals.rs
pub fn
(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] < interval[0...
merge
identifier_name
merge_intervals.rs
pub fn merge(intervals: Vec<Vec<i32>>) -> Vec<Vec<i32>> { let mut intervals = intervals; intervals.sort_by(|a, b| a[0].cmp(&b[0])); let mut merged: Vec<Vec<i32>> = Vec::new(); for interval in intervals { // 如果是第一个,或和最后一个不相交,就放到 merged 中 if merged.is_empty() || merged.last().unwrap()[1] ...
c![15, 18]]); let expect = vec![vec![1, 6], vec![8, 10], vec![15, 18]]; assert_eq!(r, expect); let r = merge(vec![vec![1, 4], vec![4, 5]]); let expect = vec![vec![1, 5]]; assert_eq!(r, expect); } }
identifier_body
unbind_3pid.rs
//! `POST /_matrix/client/*/account/3pid/unbind` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3account3pidunbind use ruma_common::{api::ruma_api, thirdparty::Medium}; use crate::account::ThirdPartyIdRemovalStatus; ruma_api...
(id_server_unbind_result: ThirdPartyIdRemovalStatus) -> Self { Self { id_server_unbind_result } } } }
new
identifier_name
unbind_3pid.rs
//! `POST /_matrix/client/*/account/3pid/unbind` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3account3pidunbind use ruma_common::{api::ruma_api, thirdparty::Medium}; use crate::account::ThirdPartyIdRemovalStatus; ruma_api...
pub id_server_unbind_result: ThirdPartyIdRemovalStatus, } error: crate::Error } impl<'a> Request<'a> { /// Creates a new `Request` with the given medium and third-party address. pub fn new(medium: Medium, address: &'a str) -> Self { Self { id_server: Non...
response: { /// Result of unbind operation.
random_line_split
unbind_3pid.rs
//! `POST /_matrix/client/*/account/3pid/unbind` pub mod v3 { //! `/v3/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/client-server-api/#post_matrixclientv3account3pidunbind use ruma_common::{api::ruma_api, thirdparty::Medium}; use crate::account::ThirdPartyIdRemovalStatus; ruma_api...
} }
{ Self { id_server_unbind_result } }
identifier_body
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = re...
(id: u32, msg: String) -> SQError { let full_msg_str = format!("error id={} msg={}", id, &msg); SQError { id, msg, full_msg: full_msg_str, } } /// Creates an OK error. pub fn ok() -> SQError { SQError::new(0, "ok".to_string()) } /...
new
identifier_name
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = re...
} } pub fn is_sq(&self) -> bool { match *self { Error::SQ(_) => true, _ => false, } } pub fn is_other(&self) -> bool { match *self { Error::Other(_) => true, _ => false, } } } impl error::Error for Error { ...
random_line_split
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = re...
} impl From<SQError> for Error { fn from(err: SQError) -> Error { Error::SQ(err) } } impl From<AddrParseError> for Error { fn from(err: AddrParseError) -> Error { Error::Other(err.description().to_string()) } } impl<T> From<PoisonError<T>> for Error { fn from(err: PoisonError<T>)...
{ Error::Io(err) }
identifier_body
error.rs
//! error provides newtypes and Error's for sqlib. use escaping::unescape; use std::convert::From; use std::error::{self, Error as Err}; use std::fmt::{self, Display}; use std::io; use std::net::AddrParseError; use std::result; use std::sync::PoisonError; /// The standart result type of sqlib. pub type Result<T> = re...
Ok(val) => val, }; if parts[3]!= "msg" { return None; } let msg = parts[4].to_string().clone(); Some(SQError::new(id, unescape(&msg))) } pub fn id(&self) -> u32 { self.id } pub fn msg(&self) -> String { self.msg.clone() ...
{ return None; }
conditional_block
mod.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] pub fn
() { // strings are implemented as a collection of bytes plus some methods to provide useful // functionality when those bytes are interpreted as text. // the'str' type represents a string slice, and is usually seen in its borrowed form &str // str is a type in the langugage itself // String type i...
foo
identifier_name
mod.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] pub fn foo()
// Since strings are utf-8, the following are all valid let hello = "السلام عليكم"; let hello = "Dobrý den"; let hello = "Hello"; let hello = "שָׁלוֹם"; let hello = "नमस्ते"; let hello = "こんにちは"; let hello = "안녕하세요"; let hello = "你好"; let hello = "Olá"; let hello = "Здравств...
{ // strings are implemented as a collection of bytes plus some methods to provide useful // functionality when those bytes are interpreted as text. // the 'str' type represents a string slice, and is usually seen in its borrowed form &str // str is a type in the langugage itself // String type is ...
identifier_body
mod.rs
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] pub fn foo() { // strings are implemented as a collection of bytes plus some methods to provide useful // functionality when those bytes are interpreted as text. // the'str' type represents a string slice, and is usually seen in its bo...
// Since strings are utf-8, the following are all valid let hello = "السلام عليكم"; let hello = "Dobrý den"; let hello = "Hello"; let hello = "שָׁלוֹם"; let hello = "नमस्ते"; let hello = "こんにちは"; let hello = "안녕하세요"; let hello = "你好"; let hello = "Olá"; let hello = "Здравству...
random_line_split
main.rs
#![allow(clippy::unnecessary_fold)] fn
() { let numbers = [1, 2, 3, 4, 5]; let sum = numbers.iter().fold(0, |a, n| a + n); println!("{}", sum); let product = numbers.iter().fold(1, |a, n| a * n); println!("{}", product); } #[cfg(test)] mod tests { #[test] fn test_sum() { let sum = [1, 2, 3, 4, 5].iter().fold(0, |a, n| a ...
main
identifier_name
main.rs
#![allow(clippy::unnecessary_fold)] fn main()
#[cfg(test)] mod tests { #[test] fn test_sum() { let sum = [1, 2, 3, 4, 5].iter().fold(0, |a, n| a + n); assert_eq!(sum, 15); } #[test] fn test_product() { let product = [1, 2, 3, 4, 5].iter().fold(1, |a, n| a * n); assert_eq!(product, 120); } }
{ let numbers = [1, 2, 3, 4, 5]; let sum = numbers.iter().fold(0, |a, n| a + n); println!("{}", sum); let product = numbers.iter().fold(1, |a, n| a * n); println!("{}", product); }
identifier_body
main.rs
#![allow(clippy::unnecessary_fold)]
let sum = numbers.iter().fold(0, |a, n| a + n); println!("{}", sum); let product = numbers.iter().fold(1, |a, n| a * n); println!("{}", product); } #[cfg(test)] mod tests { #[test] fn test_sum() { let sum = [1, 2, 3, 4, 5].iter().fold(0, |a, n| a + n); assert_eq!(sum, 15); }...
fn main() { let numbers = [1, 2, 3, 4, 5];
random_line_split
sliceobject.rs
use libc::c_int; use pyport::Py_ssize_t; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { static mut _Py_EllipsisObject: PyObject; } #[inline(always)] pub unsafe fn Py_Ellipsis() -> *mut PyObject { &mut _Py_EllipsisObject } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { p...
(op: *mut PyObject) -> c_int { (Py_TYPE(op) == &mut PySlice_Type) as c_int } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PySlice_New(start: *mut PyObject, stop: *mut PyObject, step: *mut PyObject) -> *mut PyObject; pub fn PySlice_GetIndices(r: *mut PyObject, leng...
PySlice_Check
identifier_name
sliceobject.rs
use libc::c_int; use pyport::Py_ssize_t; use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { static mut _Py_EllipsisObject: PyObject; } #[inline(always)] pub unsafe fn Py_Ellipsis() -> *mut PyObject { &mut _Py_EllipsisObject } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { p...
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub fn PySlice_New(start: *mut PyObject, stop: *mut PyObject, step: *mut PyObject) -> *mut PyObject; pub fn PySlice_GetIndices(r: *mut PyObject, length: Py_ssize_t, start: *mut Py_ssize_t, stop: *mut ...
{ (Py_TYPE(op) == &mut PySlice_Type) as c_int }
identifier_body
sliceobject.rs
use libc::c_int; use pyport::Py_ssize_t;
static mut _Py_EllipsisObject: PyObject; } #[inline(always)] pub unsafe fn Py_Ellipsis() -> *mut PyObject { &mut _Py_EllipsisObject } #[cfg_attr(windows, link(name="pythonXY"))] extern "C" { pub static mut PySlice_Type: PyTypeObject; pub static mut PyEllipsis_Type: PyTypeObject; } #[inline(always)] p...
use object::*; #[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
random_line_split
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.g...
}; Ok(quote! { impl #impl_generics #name #ty_generics #where_clause { #vis #const_if_possible fn from_repr(discriminant: #discriminant_type) -> Option<#name #ty_generics> { #(#constant_defs)* match discriminant { #(#arms),* ...
#[rustversion::since(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { s } filter_by_rust_version(quote! { const })
random_line_split
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn
(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.generics; let (impl_generics, ty_generics, where_clause) = gen.split_for_impl(); let vis = &ast.vis; let attrs = &ast.attrs; let mut discriminant_type: Type = syn::parse("usize".parse().unwrap()).unwrap(); ...
from_repr_inner
identifier_name
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.g...
let typ_paren = match syn::parse2::<Type>(tokens.clone()) { Ok(Type::Paren(TypeParen { elem,.. })) => *elem, _ => continue, }; let inner_path = match &typ_paren { Type::Path(t) => t, _ => continue, }; if let Some(seg) = inner_path....
{ continue; }
conditional_block
from_repr.rs
use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use syn::{Data, DeriveInput, PathArguments, Type, TypeParen}; use crate::helpers::{non_enum_error, HasStrumVariantProperties}; pub fn from_repr_inner(ast: &DeriveInput) -> syn::Result<TokenStream> { let name = &ast.ident; let gen = &ast.g...
#[rustversion::since(1.46)] fn filter_by_rust_version(s: TokenStream) -> TokenStream { s } filter_by_rust_version(quote! { const }) }; Ok(quote! { impl #impl_generics #name #ty_generics #where_clause { #vis #const_if_possible fn from_repr(discri...
{ quote! {} }
identifier_body
lib.rs
// Copyright 2013-2015 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...
#[cfg(not(windows))] /// Return a Terminal wrapping stderr, or None if a terminal couldn't be /// opened. pub fn stderr() -> Option<Box<StderrTerminal>> { TerminfoTerminal::new(io::stderr()).map(|t| { Box::new(t) as Box<StderrTerminal> }) } #[cfg(windows)] /// Return a Terminal wrapping stderr, or No...
{ TerminfoTerminal::new(io::stdout()).map(|t| { Box::new(t) as Box<StdoutTerminal> }).or_else(|| WinConsole::new(io::stdout()).ok().map(|t| { Box::new(t) as Box<StdoutTerminal> })) }
identifier_body
lib.rs
// Copyright 2013-2015 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...
{ /// Bold (or possibly bright) mode Bold, /// Dim mode, also called faint or half-bright. Often not supported Dim, /// Italics mode. Often not supported Italic(bool), /// Underline mode Underline(bool), /// Blink mode Blink, /// Standout mode. Often implemented as Reverse, ...
Attr
identifier_name
lib.rs
// Copyright 2013-2015 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...
/// Gets an immutable reference to the stream inside fn get_ref<'a>(&'a self) -> &'a Self::Output; /// Gets a mutable reference to the stream inside fn get_mut<'a>(&'a mut self) -> &'a mut Self::Output; /// Returns the contained stream, destroying the `Terminal` fn into_inner(self) -> Self::O...
/// Moves the cursor to the left edge of the current line. /// /// Returns `Ok(true)` if the text was deleted, `Ok(false)` otherwise, and `Err(e)` /// if there was an I/O error. fn carriage_return(&mut self) -> io::Result<bool>;
random_line_split
p017.rs
use solutions::Solution; pub fn solve() -> Solution { let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) } /// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn wordify(n: usize) -> String { let numbers =...
if n % 100 < 20 { s += numbers[n % 100]; n /= 100; } else { // Otherwise, the construction of numbers is regular s += numbers[n % 10]; n /= 10; s = tens[n % 10].to_string() + &s; n /= 10; } if n!= 0 { // Add "and" between hundreds and whate...
// Need to account for special number names below 20
random_line_split
p017.rs
use solutions::Solution; pub fn solve() -> Solution { let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) } /// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn wordify(n: usize) -> String { let numbers =...
let mut n = n; let mut s = String::new(); // Need to account for special number names below 20 if n % 100 < 20 { s += numbers[n % 100]; n /= 100; } else { // Otherwise, the construction of numbers is regular s += numbers[n % 10]; n /= 10; s = tens[n...
{ return "onethousand".to_string(); }
conditional_block
p017.rs
use solutions::Solution; pub fn solve() -> Solution { let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) } /// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn
(n: usize) -> String { let numbers = vec!["", "one", "two", "three", "four", "five", "six", "seven", "eight", ...
wordify
identifier_name
p017.rs
use solutions::Solution; pub fn solve() -> Solution
/// Turns the given number (in the range [1,1000]) into a string with no spaces or dashes fn wordify(n: usize) -> String { let numbers = vec!["", "one", "two", "three", "four", "five", ...
{ let mut sum = 0; for n in 1..1001 { sum += wordify(n).len(); } Solution::new(&format!("{}", sum)) }
identifier_body
lib.rs
#[feature(macro_rules)]; #[crate_id = "diagrus#0.1"]; #[crate_type = "lib"]; #[crate_type = "dylib"]; #[comment = "Utilities to make using JSON easier"]; #[license = "MIT"]; extern mod extra; use std::fmt; pub use self::fromjson::FromJson; pub use self::jsonutil::JsonLike; pub mod macros; pub mod jsonutil;
pub enum ErrorTy { Conversion, Value } /// These error codes describe the actual error specifically. #[deriving(Clone, Encodable, Decodable, Eq, ToStr)] pub enum ErrorCode { NotString, NotNumber, NotInteger, NotBoolean, NotList, NotObject, NotEither, NoSuchKey, IdxOutOfBound...
pub mod fromjson; /// This enum indicates if the error is due to a conversion failure, /// or from mishandling the JSON value #[deriving(Clone, Encodable, Decodable, Eq, ToStr)]
random_line_split
lib.rs
#[feature(macro_rules)]; #[crate_id = "diagrus#0.1"]; #[crate_type = "lib"]; #[crate_type = "dylib"]; #[comment = "Utilities to make using JSON easier"]; #[license = "MIT"]; extern mod extra; use std::fmt; pub use self::fromjson::FromJson; pub use self::jsonutil::JsonLike; pub mod macros; pub mod jsonutil; pub mod...
} impl ToStr for Error { fn to_str(&self) -> ~str { format!("{}", *self) } } /// Convenience function for errors fn error<T>(ty: ErrorTy, code: ErrorCode) -> Result<T, Error> { Err(Error::new(ty, code)) }
{ let msg = match e.code { NotString => ~"Not a JSON string", NotNumber => ~"Not a JSON number", NotInteger => ~"JSON number is not an integer", NotBoolean => ~"Not a JSON boolean", NotList => ~"Not a JSON list", NotObject => ~"Not a JSON O...
identifier_body
lib.rs
#[feature(macro_rules)]; #[crate_id = "diagrus#0.1"]; #[crate_type = "lib"]; #[crate_type = "dylib"]; #[comment = "Utilities to make using JSON easier"]; #[license = "MIT"]; extern mod extra; use std::fmt; pub use self::fromjson::FromJson; pub use self::jsonutil::JsonLike; pub mod macros; pub mod jsonutil; pub mod...
{ /// Error category category: ErrorTy, /// Code indicating the specific error. code: ErrorCode } impl Error { pub fn new(ty: ErrorTy, code: ErrorCode) -> Error { Error { category: ty, code: code } } } impl fmt::Default for Error { fn fmt(e: &Error, f: &mut fmt::Formatter) { ...
Error
identifier_name