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
checkbox.rs
use crate::direction::Direction; use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent}; use crate::theme::ColorStyle; use crate::view::View; use crate::Cursive; use crate::Printer; use crate::Vec2; use crate::With; use std::rc::Rc; /// Checkable box. /// /// # Examples /// /// ``` /// use cursive_core::...
s.set_checked(is_checked); }) } fn draw_internal(&self, printer: &Printer) { printer.print((0, 0), "[ ]"); if self.checked { printer.print((1, 0), "X"); } } } impl View for Checkbox { fn required_size(&mut self, _: Vec2) -> Vec2 { Vec2::n...
/// Set the checkbox state. /// /// Chainable variant. pub fn with_checked(self, is_checked: bool) -> Self { self.with(|s| {
random_line_split
checkbox.rs
use crate::direction::Direction; use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent}; use crate::theme::ColorStyle; use crate::view::View; use crate::Cursive; use crate::Printer; use crate::Vec2; use crate::With; use std::rc::Rc; /// Checkable box. /// /// # Examples /// /// ``` /// use cursive_core::...
(&self, printer: &Printer) { printer.print((0, 0), "[ ]"); if self.checked { printer.print((1, 0), "X"); } } } impl View for Checkbox { fn required_size(&mut self, _: Vec2) -> Vec2 { Vec2::new(3, 1) } fn take_focus(&mut self, _: Direction) -> bool { ...
draw_internal
identifier_name
checkbox.rs
use crate::direction::Direction; use crate::event::{Event, EventResult, Key, MouseButton, MouseEvent}; use crate::theme::ColorStyle; use crate::view::View; use crate::Cursive; use crate::Printer; use crate::Vec2; use crate::With; use std::rc::Rc; /// Checkable box. /// /// # Examples /// /// ``` /// use cursive_core::...
match event { Event::Key(Key::Enter) | Event::Char(' ') => self.toggle(), Event::Mouse { event: MouseEvent::Release(MouseButton::Left), position, offset, } if position.fits_in_rect(offset, (3, 1)) => self.toggle(), ...
{ return EventResult::Ignored; }
conditional_block
x2apic.rs
//! x2APIC, the most recent APIC on x86 for large servers with more than 255 cores. use bit_field::BitField; use super::*; use crate::msr::{ rdmsr, wrmsr, IA32_APIC_BASE, IA32_TSC_DEADLINE, IA32_X2APIC_APICID, IA32_X2APIC_EOI, IA32_X2APIC_ESR, IA32_X2APIC_ICR, IA32_X2APIC_LDR, IA32_X2APIC_LVT_LINT0, IA32_X...
/// Send an IPI to yourself. /// /// # Safety /// Will interrupt core with `vector`. pub unsafe fn send_self_ipi(&self, vector: u64) { wrmsr(IA32_X2APIC_SELF_IPI, vector); } } /// Abstracts common interface of APIC (x2APIC, xAPIC) hardware devices. impl ApicControl for X2APIC { /// ...
random_line_split
x2apic.rs
//! x2APIC, the most recent APIC on x86 for large servers with more than 255 cores. use bit_field::BitField; use super::*; use crate::msr::{ rdmsr, wrmsr, IA32_APIC_BASE, IA32_TSC_DEADLINE, IA32_X2APIC_APICID, IA32_X2APIC_EOI, IA32_X2APIC_ESR, IA32_X2APIC_ICR, IA32_X2APIC_LDR, IA32_X2APIC_LVT_LINT0, IA32_X...
{ /// Initial BASE msr register value. base: u64, } impl Default for X2APIC { fn default() -> Self { unsafe { X2APIC { base: rdmsr(IA32_APIC_BASE), } } } } impl X2APIC { /// Create a new x2APIC driver object for the local core. pub fn ne...
X2APIC
identifier_name
x2apic.rs
//! x2APIC, the most recent APIC on x86 for large servers with more than 255 cores. use bit_field::BitField; use super::*; use crate::msr::{ rdmsr, wrmsr, IA32_APIC_BASE, IA32_TSC_DEADLINE, IA32_X2APIC_APICID, IA32_X2APIC_EOI, IA32_X2APIC_ESR, IA32_X2APIC_ICR, IA32_X2APIC_LDR, IA32_X2APIC_LVT_LINT0, IA32_X...
/// Read APIC version. fn version(&self) -> u32 { unsafe { rdmsr(IA32_X2APIC_VERSION) as u32 } } /// Enable TSC timer fn tsc_enable(&mut self, vector: u8) { unsafe { wrmsr(IA32_TSC_DEADLINE, 0); let mut lvt: u64 = rdmsr(IA32_X2APIC_LVT_TIMER); ...
{ unsafe { rdmsr(IA32_X2APIC_LDR) as u32 } }
identifier_body
x2apic.rs
//! x2APIC, the most recent APIC on x86 for large servers with more than 255 cores. use bit_field::BitField; use super::*; use crate::msr::{ rdmsr, wrmsr, IA32_APIC_BASE, IA32_TSC_DEADLINE, IA32_X2APIC_APICID, IA32_X2APIC_EOI, IA32_X2APIC_ESR, IA32_X2APIC_ICR, IA32_X2APIC_LDR, IA32_X2APIC_LVT_LINT0, IA32_X...
} } }
{ break; }
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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; use crate::dom::bindin...
fn SupportedPropertyNames(&self) -> Vec<DOMString> { self.collection.SupportedPropertyNames() } // FIXME: This shouldn't need to be implemented here since HTMLCollection (the parent of // HTMLFormControlsCollection) implements IndexedGetter. // https://github.com/servo/servo/issues/5875 ...
} // https://html.spec.whatwg.org/multipage/#the-htmlformcontrolscollection-interface:supported-property-names
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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; use crate::dom::bindin...
} // https://html.spec.whatwg.org/multipage/#dom-htmlformcontrolscollection-nameditem fn NamedGetter(&self, name: DOMString) -> Option<RadioNodeListOrElement> { self.NamedItem(name) } // https://html.spec.whatwg.org/multipage/#the-htmlformcontrolscollection-interface:supported-property-na...
{ None }
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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; use crate::dom::bindin...
{ collection: HTMLCollection, form: Dom<HTMLFormElement>, } impl HTMLFormControlsCollection { fn new_inherited( form: &HTMLFormElement, filter: Box<dyn CollectionFilter +'static>, ) -> HTMLFormControlsCollection { let root_of_form = form .upcast::<Node>() ...
HTMLFormControlsCollection
identifier_name
lib.rs
#![crate_type= "lib"] #![cfg_attr(feature = "nightly", feature(plugin))] //#![cfg_attr(feature = "lints", plugin(clippy))] //#![cfg_attr(feature = "lints", allow(option_unwrap_used))] //#![cfg_attr(feature = "lints", allow(explicit_iter_loop))] //#![cfg_attr(feature = "lints", deny(warnings))] // Fix until clippy on cr...
extern crate strsim; #[cfg(feature = "color")] extern crate ansi_term; #[cfg(feature = "yaml")] extern crate yaml_rust; #[cfg(feature = "yaml")] pub use yaml_rust::YamlLoader; pub use args::{Arg, SubCommand, ArgMatches, ArgGroup}; pub use app::{App, AppSettings, ClapError, ClapErrorType}; pub use fmt::Format; #[macro...
// DOCS #[cfg(feature = "suggestions")]
random_line_split
mod.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/. */ //! Generic types that share their serialization implementations //! for both specified and computed values. use ...
() -> Self { CounterStyleOrNone::Name(CustomIdent(atom!("decimal"))) } } impl Parse for CounterStyleOrNone { fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> { if let Ok(name) = input.try(|i| parse_counter_style_name(i)) { return...
decimal
identifier_name
mod.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/. */ //! Generic types that share their serialization implementations //! for both specified and computed values. use ...
return Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)); } Ok(CounterStyleOrNone::Symbols(symbols_type, symbols)) }); } Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) } } /// A wrapper of Non-nega...
{ if let Ok(name) = input.try(|i| parse_counter_style_name(i)) { return Ok(CounterStyleOrNone::Name(name)); } if input.try(|i| i.expect_ident_matching("none")).is_ok() { return Ok(CounterStyleOrNone::None); } if input.try(|i| i.expect_function_matching("sy...
identifier_body
mod.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/. */ //! Generic types that share their serialization implementations //! for both specified and computed values. use ...
#[cfg(feature = "gecko")] pub mod gecko; pub mod grid; pub mod image; pub mod position; pub mod rect; pub mod size; pub mod svg; pub mod text; pub mod transform; // https://drafts.csswg.org/css-counter-styles/#typedef-symbols-type #[allow(missing_docs)] #[cfg_attr(feature = "servo", derive(Deserialize, Serialize))] #[...
pub mod effects; pub mod flex; pub mod font;
random_line_split
command.rs
//! This module provides the command enum. use std::path::PathBuf; use library::RepeatMode; #[derive(Debug)] /// The different commands that one can send to a server. pub enum Command { /// Does nothing, used to get the status from the server. NoOp, /// Switches between playing and paused. PlayPause, ...
_ => Err(()), } } }
{ match v[0] { 0 => Ok(Command::NoOp), 1 => Ok(Command::PlayPause), 2 => Ok(Command::Stop), 3 => Ok(Command::NextSong), 4 => Ok(Command::PreviousSong), 5 => { use std::iter::FromIterator; let mut iter = v[1.....
identifier_body
command.rs
//! This module provides the command enum. use std::path::PathBuf; use library::RepeatMode; #[derive(Debug)] /// The different commands that one can send to a server. pub enum
{ /// Does nothing, used to get the status from the server. NoOp, /// Switches between playing and paused. PlayPause, /// Stops the current song. Stop, /// Goes to the next song. NextSong, /// Goes to the previous song, even if the current song has already started since a while. ...
Command
identifier_name
command.rs
//! This module provides the command enum. use std::path::PathBuf; use library::RepeatMode; #[derive(Debug)] /// The different commands that one can send to a server. pub enum Command { /// Does nothing, used to get the status from the server. NoOp, /// Switches between playing and paused. PlayPause, ...
, 6 => Ok(Command::StopServer), 7 => Ok(Command::ChangeRepeatMode(RepeatMode::NoRepeat)), 8 => Ok(Command::ChangeRepeatMode(RepeatMode::RepeatOne)), 9 => Ok(Command::ChangeRepeatMode(RepeatMode::RepeatAll)), 10 => Ok(Command::NextAlbum), 11 => Ok(C...
{ use std::iter::FromIterator; let mut iter = v[1..255].iter(); let index = (iter.position(|&x| x == 0 ).unwrap()) as usize; let path = String::from_iter(v[1..index+1].iter().map(|x| *x as char)); Ok(Command::Song(PathBuf::from(path))) ...
conditional_block
command.rs
//! This module provides the command enum. use std::path::PathBuf;
#[derive(Debug)] /// The different commands that one can send to a server. pub enum Command { /// Does nothing, used to get the status from the server. NoOp, /// Switches between playing and paused. PlayPause, /// Stops the current song. Stop, /// Goes to the next song. NextSong, ///...
use library::RepeatMode;
random_line_split
build.rs
extern crate protobuf_build; use std::env; use std::path::PathBuf; use std::fs::File; use std::io::{Read, Write}; fn main() { let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let out = PathBuf::from(env::var("OUT_DIR").unwrap()); let proto = root.join("proto"); let mut compiler = pr...
let mut contents = Vec::new(); src.read_to_end(&mut contents).unwrap(); contents }; let mut dst = File::create(out.join(&((*file).to_owned() + ".rs"))).unwrap(); dst.write_all(format!("pub mod {} {{\n", file).as_bytes()).unwrap(); dst.write_all(&conte...
let path = out.join(&((*file).to_owned() + ".rs")); let contents = { let mut src = File::open(path).unwrap();
random_line_split
build.rs
extern crate protobuf_build; use std::env; use std::path::PathBuf; use std::fs::File; use std::io::{Read, Write}; fn
() { let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let out = PathBuf::from(env::var("OUT_DIR").unwrap()); let proto = root.join("proto"); let mut compiler = protobuf_build::Compiler::new(&proto, &out); let files = ["keyexchange", "authentication", ...
main
identifier_name
build.rs
extern crate protobuf_build; use std::env; use std::path::PathBuf; use std::fs::File; use std::io::{Read, Write}; fn main()
let path = out.join(&((*file).to_owned() + ".rs")); let contents = { let mut src = File::open(path).unwrap(); let mut contents = Vec::new(); src.read_to_end(&mut contents).unwrap(); contents }; let mut dst = File::create(out.join(&((*file)...
{ let root = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); let out = PathBuf::from(env::var("OUT_DIR").unwrap()); let proto = root.join("proto"); let mut compiler = protobuf_build::Compiler::new(&proto, &out); let files = ["keyexchange", "authentication", ...
identifier_body
minibuf.rs
//! Minibuffer input and completion. use remacs_macros::lisp_fn; use crate::{ buffers::{current_buffer, LispBufferOrName}, editfns::field_end, eval::unbind_to, keymap::get_keymap, lisp::LispObject, lists::{car_safe, cdr_safe, memq}, multibyte::LispStringRef, obarray::{intern, lisp_inte...
else { lisp_intern(name.into(), None) } } /// Read the name of a command and return as a symbol. */ /// Prompt with PROMPT. By default, return DEFAULT-VALUE or its first element */ /// if it is a list. #[lisp_fn(min = "1")] pub fn read_command(prompt: LispObject, default_value: LispObject) -> LispObject ...
{ name }
conditional_block
minibuf.rs
//! Minibuffer input and completion. use remacs_macros::lisp_fn; use crate::{ buffers::{current_buffer, LispBufferOrName}, editfns::field_end, eval::unbind_to, keymap::get_keymap, lisp::LispObject, lists::{car_safe, cdr_safe, memq}, multibyte::LispStringRef, obarray::{intern, lisp_inte...
unsafe { make_buffer_string(prompt_end, ThreadState::current_buffer_unchecked().zv, true) } } /// Return the user input in a minibuffer as a string, without text-properties. /// If the current buffer is not a minibuffer, return its entire contents. #[lisp_fn] pub fn minibuffer_contents_no_properties() -> LispObjec...
random_line_split
minibuf.rs
//! Minibuffer input and completion. use remacs_macros::lisp_fn; use crate::{ buffers::{current_buffer, LispBufferOrName}, editfns::field_end, eval::unbind_to, keymap::get_keymap, lisp::LispObject, lists::{car_safe, cdr_safe, memq}, multibyte::LispStringRef, obarray::{intern, lisp_inte...
/// Read a string from the terminal, not allowing blanks. /// Prompt with PROMPT. Whitespace terminates the input. If INITIAL is /// non-nil, it should be a string, which is used as initial input, with /// point positioned at the end, so that SPACE will accept the input. /// (Actually, INITIAL can also be a cons of...
{ read_command_or_variable(prompt, default_value, Qcustom_variable_p) }
identifier_body
minibuf.rs
//! Minibuffer input and completion. use remacs_macros::lisp_fn; use crate::{ buffers::{current_buffer, LispBufferOrName}, editfns::field_end, eval::unbind_to, keymap::get_keymap, lisp::LispObject, lists::{car_safe, cdr_safe, memq}, multibyte::LispStringRef, obarray::{intern, lisp_inte...
( prompt: LispStringRef, initial_contents: LispObject, mut keymap: LispObject, read: bool, hist: LispObject, default_value: LispObject, inherit_input_method: bool, ) -> LispObject { keymap = if keymap.is_nil() { unsafe { globals.Vminibuffer_local_map } } else { get_ke...
read_from_minibuffer
identifier_name
x86_64.rs
//! x86_64-specific definitions for 64-bit linux-like values pub type c_char = i8; pub type wchar_t = i32; pub type nlink_t = u64; pub type blksize_t = i64; pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 40; pub const __SIZEOF_PTHREAD_MUTEXATTR_T: usize = 4; s! { pub struct stat { pub st_dev: ::dev_t, ...
} pub struct pthread_attr_t { __size: [u64; 7] } }
pub st_ctime_nsec: ::c_long, __unused: [::c_long; 3],
random_line_split
cat.rs
use std::io::{Result, Read, Write, copy, stdout, stderr}; use std::env::args_os; use std::process::exit; use std::ffi::OsString; use std::fs::File; use std::path::Path; extern crate concat; use concat::concat; fn main() { let mut args = args_os(); let progname = args.next().unwrap_or_else(|| OsString::from("c...
} struct InputSource { path: OsString, file: Option<File>, } impl InputSource { pub fn path(&self) -> &Path { self.path.as_ref() } } impl From<OsString> for InputSource { fn from(path: OsString) -> InputSource { InputSource { path: path, file: None, ...
{ match c.current() { None => { writeln!(&mut stderr(), "{}: {}\n", AsRef::<Path>::as_ref(&progname).display(), e).unwrap(); }, Some(ref f) => { writeln!(&mut stderr(),...
conditional_block
cat.rs
use std::io::{Result, Read, Write, copy, stdout, stderr}; use std::env::args_os; use std::process::exit; use std::ffi::OsString; use std::fs::File; use std::path::Path; extern crate concat; use concat::concat; fn main() { let mut args = args_os(); let progname = args.next().unwrap_or_else(|| OsString::from("c...
(&self) -> &Path { self.path.as_ref() } } impl From<OsString> for InputSource { fn from(path: OsString) -> InputSource { InputSource { path: path, file: None, } } } impl Read for InputSource { fn read(&mut self, buf: &mut [u8]) -> Result<usize> { ...
path
identifier_name
cat.rs
use std::io::{Result, Read, Write, copy, stdout, stderr}; use std::env::args_os; use std::process::exit; use std::ffi::OsString; use std::fs::File; use std::path::Path; extern crate concat; use concat::concat;
let mut c = concat(args.map(InputSource::from)); let res = copy(&mut c, &mut stdout()); if let Err(e) = res { match c.current() { None => { writeln!(&mut stderr(), "{}: {}\n", AsRef::<Path>::as_ref(&progname).display(), ...
fn main() { let mut args = args_os(); let progname = args.next().unwrap_or_else(|| OsString::from("cat"));
random_line_split
ms.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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...
(&mut self) -> &mut SpecifiedTokenProps { &mut self.token_props } } impl Token<Ms> for Ms {} impl Presentation<Ms> for Ms {} #[cfg(test)] mod test { use super::*; use ::test::skia::Snapshot; use ::props::{Color, MathSize, MathVariant}; #[test] fn it_works() { let snap = Snap...
get_specified_token_props_mut
identifier_name
ms.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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...
fn it_works() { let snap = Snapshot::default(); snap.snap_element( &Ms::new(String::from("hello ms")), "ms_text" ); snap.snap_element( Ms::new(String::from("hello fraktur")) .with_math_variant(Some(MathVariant::Fraktur)), ...
use ::test::skia::Snapshot; use ::props::{Color, MathSize, MathVariant}; #[test]
random_line_split
ms.rs
/* * Copyright 2017 Sreejith Krishnan R * * 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...
fn get_specified_token_props_mut(&mut self) -> &mut SpecifiedTokenProps { &mut self.token_props } } impl Token<Ms> for Ms {} impl Presentation<Ms> for Ms {} #[cfg(test)] mod test { use super::*; use ::test::skia::Snapshot; use ::props::{Color, MathSize, MathVariant}; #[test] f...
{ &self.token_props }
identifier_body
set_cookie.rs
use header::{Header, HeaderFormat}; use std::fmt::{self, Display}; use std::str::from_utf8; use cookie::Cookie; use cookie::CookieJar; /// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1) /// /// The Set-Cookie HTTP response header is used to send cookies from the /// server to t...
/// ; defined in [RFC1034], Section 3.5, as /// ; enhanced by [RFC1123], Section 2.1 /// path-av = "Path=" path-value /// path-value = <any CHAR except CTLs or ";"> /// secure-av = "Secure" /// httponly-av = "HttpOnly" /// extension-av = <a...
random_line_split
set_cookie.rs
use header::{Header, HeaderFormat}; use std::fmt::{self, Display}; use std::str::from_utf8; use cookie::Cookie; use cookie::CookieJar; /// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1) /// /// The Set-Cookie HTTP response header is used to send cookies from the /// server to t...
() { let jar = CookieJar::new(b"secret"); let cookie = Cookie::new("foo".to_owned(), "bar".to_owned()); jar.encrypted().add(cookie); let cookies = SetCookie::from_cookie_jar(&jar); let mut new_jar = CookieJar::new(b"secret"); cookies.apply_to_cookie_jar(&mut new_jar); assert_eq!(jar.encry...
cookie_jar
identifier_name
set_cookie.rs
use header::{Header, HeaderFormat}; use std::fmt::{self, Display}; use std::str::from_utf8; use cookie::Cookie; use cookie::CookieJar; /// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1) /// /// The Set-Cookie HTTP response header is used to send cookies from the /// server to t...
} if!set_cookies.is_empty() { Ok(SetCookie(set_cookies)) } else { Err(::Error::Header) } } } impl HeaderFormat for SetCookie { fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { for (i, cookie) in self.0.iter().enumerate() { ...
{ if let Ok(cookie) = s.parse() { set_cookies.push(cookie); } }
conditional_block
set_cookie.rs
use header::{Header, HeaderFormat}; use std::fmt::{self, Display}; use std::str::from_utf8; use cookie::Cookie; use cookie::CookieJar; /// `Set-Cookie` header, defined [RFC6265](http://tools.ietf.org/html/rfc6265#section-4.1) /// /// The Set-Cookie HTTP response header is used to send cookies from the /// server to t...
#[test] fn test_fmt() { use header::Headers; let mut cookie = Cookie::new("foo".to_owned(), "bar".to_owned()); cookie.httponly = true; cookie.path = Some("/p".to_owned()); let cookies = SetCookie(vec![cookie, Cookie::new("baz".to_owned(), "quux".to_owned())]); let mut headers = Headers::new()...
{ let h = Header::parse_header(&[b"foo=bar; HttpOnly".to_vec()][..]); let mut c1 = Cookie::new("foo".to_owned(), "bar".to_owned()); c1.httponly = true; assert_eq!(h.ok(), Some(SetCookie(vec![c1]))); }
identifier_body
test_support.rs
// -*- coding: utf-8 -*- // ------------------------------------------------------------------------------------------------ // Copyright © 2020, HST authors. // // 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 ...
ut negated_twice = a.clone(); negated_twice.negate(); negated_twice.negate(); assert_eq!(a, negated_twice); } #[proptest] fn can_subtract(a: NumberedEvents, b: NumberedEvents, event: NumberedEvent) { let mut difference = a.clone(); difference.subtract(&b); as...
vents) { let m
identifier_name
test_support.rs
// -*- coding: utf-8 -*- // ------------------------------------------------------------------------------------------------ // Copyright © 2020, HST authors. // // 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 ...
NumberedEvent { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let digits: String = self .0 .to_string() .chars() .map(|ch| SUBSCRIPT_DIGITS[ch.to_digit(10).unwrap() as usize]) .collect(); write!(f, "E{}", digits) } } impl...
yn Display).fmt(f) } } impl Display for
identifier_body
test_support.rs
// -*- coding: utf-8 -*- // ------------------------------------------------------------------------------------------------ // Copyright © 2020, HST authors. // // 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 ...
} } impl From<NumberedEvent> for NumberedEvents { fn from(event: NumberedEvent) -> NumberedEvents { let mut events = NumberedEvents::empty(); events.add(event); events } } impl From<HashSet<NumberedEvent>> for NumberedEvents { fn from(set: HashSet<NumberedEvent>) -> NumberedEve...
.map(NumberedEvent::from), ) .finish()
random_line_split
document_highlight.rs
use languageserver_types::{DocumentHighlight, TextDocumentPositionParams}; use super::*; use crate::completion; pub fn
(io: &mut IoHandler, thread: &RootedThread) { let thread = thread.clone(); let f = move |params: TextDocumentPositionParams| { let thread = thread.clone(); async move { retrieve_expr(&thread, &params.text_document.uri, |module| { let expr = module.expr.expr(); ...
register
identifier_name
document_highlight.rs
use languageserver_types::{DocumentHighlight, TextDocumentPositionParams}; use super::*; use crate::completion; pub fn register(io: &mut IoHandler, thread: &RootedThread)
kind: None, range: byte_span_to_range(&source, span)?, }) }) .collect::<Result<_, _>>() .map(Some) }) .await } }; io.add_async_method(request!(...
{ let thread = thread.clone(); let f = move |params: TextDocumentPositionParams| { let thread = thread.clone(); async move { retrieve_expr(&thread, &params.text_document.uri, |module| { let expr = module.expr.expr(); let source = &module.source; ...
identifier_body
document_highlight.rs
use languageserver_types::{DocumentHighlight, TextDocumentPositionParams}; use super::*; use crate::completion; pub fn register(io: &mut IoHandler, thread: &RootedThread) { let thread = thread.clone(); let f = move |params: TextDocumentPositionParams| { let thread = thread.clone(); async move...
.map(Some) }) .await } }; io.add_async_method(request!("textDocument/documentHighlight"), f); }
}) .collect::<Result<_, _>>()
random_line_split
lookup_json.rs
use global::Context; use lookup_service::lookup_api; use rustc_serialize::json; use iron::prelude::*; use config; pub fn
(context: &mut Context, table: &str) -> Result<String, String> { match lookup_api::get_lookup_data(context, table) { Ok(lookup_data) => { let json = if config::PRETTY_JSON { format!("{}", json::as_pretty_json(&lookup_data)) } else { json::encode(&looku...
json_get_lookup_data
identifier_name
lookup_json.rs
use global::Context; use lookup_service::lookup_api; use rustc_serialize::json; use iron::prelude::*; use config; pub fn json_get_lookup_data(context: &mut Context, table: &str) -> Result<String, String> { match lookup_api::get_lookup_data(context, table) { Ok(lookup_data) => { let json = if co...
Err(e) => Err(format!("{}", e)), } }
{ let json = if config::PRETTY_JSON { format!("{}", json::as_pretty_json(&lookup_data)) } else { json::encode(&lookup_data).unwrap() }; Ok(json) }
conditional_block
lookup_json.rs
use global::Context; use lookup_service::lookup_api; use rustc_serialize::json; use iron::prelude::*; use config; pub fn json_get_lookup_data(context: &mut Context, table: &str) -> Result<String, String>
pub fn json_get_lookup_tabs(context: &mut Context, table: &str) -> Result<String, String> { match lookup_api::get_lookup_tabs(context, table) { Ok(lookup_data) => { let json = if config::PRETTY_JSON { format!("{}", json::as_pretty_json(&lookup_data)) } else { ...
{ match lookup_api::get_lookup_data(context, table) { Ok(lookup_data) => { let json = if config::PRETTY_JSON { format!("{}", json::as_pretty_json(&lookup_data)) } else { json::encode(&lookup_data).unwrap() }; Ok(json) } ...
identifier_body
lookup_json.rs
use global::Context; use lookup_service::lookup_api; use rustc_serialize::json; use iron::prelude::*; use config; pub fn json_get_lookup_data(context: &mut Context, table: &str) -> Result<String, String> { match lookup_api::get_lookup_data(context, table) { Ok(lookup_data) => { let json = if co...
} pub fn json_get_lookup_tabs(context: &mut Context, table: &str) -> Result<String, String> { match lookup_api::get_lookup_tabs(context, table) { Ok(lookup_data) => { let json = if config::PRETTY_JSON { format!("{}", json::as_pretty_json(&lookup_data)) } else { ...
}
random_line_split
texture_swap.rs
extern crate rand; extern crate piston_window; extern crate image as im; use im::GenericImage; use piston_window::*; fn main() { let texture_count = 1024; let frames = 200; let size = 32.0; let window: PistonWindow = WindowSettings::new("piston", [1024; 2]).into(); let textures = { let m...
} e.draw_2d(|c, g| { clear([0.0, 0.0, 0.0, 1.0], g); for p in &mut positions { let (x, y) = *p; *p = (x + (rand::random::<f64>() - 0.5) * 0.01, y + (rand::random::<f64>() - 0.5) * 0.01); } for i in (0....
{ break; }
conditional_block
texture_swap.rs
extern crate rand; extern crate piston_window; extern crate image as im; use im::GenericImage; use piston_window::*; fn main() { let texture_count = 1024; let frames = 200; let size = 32.0; let window: PistonWindow = WindowSettings::new("piston", [1024; 2]).into(); let textures = { let m...
} }); } }
random_line_split
texture_swap.rs
extern crate rand; extern crate piston_window; extern crate image as im; use im::GenericImage; use piston_window::*; fn
() { let texture_count = 1024; let frames = 200; let size = 32.0; let window: PistonWindow = WindowSettings::new("piston", [1024; 2]).into(); let textures = { let mut factory = window.factory.borrow_mut(); let factory = &mut *factory; (0..texture_count).map(|_| { ...
main
identifier_name
texture_swap.rs
extern crate rand; extern crate piston_window; extern crate image as im; use im::GenericImage; use piston_window::*; fn main()
&img, &TextureSettings::new() ).unwrap() }).collect::<Vec<Texture<_>>>() }; let mut positions = (0..texture_count) .map(|_| (rand::random(), rand::random())) .collect::<Vec<(f64, f64)>>(); let mut counter = 0; for e in window.bench_mode...
{ let texture_count = 1024; let frames = 200; let size = 32.0; let window: PistonWindow = WindowSettings::new("piston", [1024; 2]).into(); let textures = { let mut factory = window.factory.borrow_mut(); let factory = &mut *factory; (0..texture_count).map(|_| { l...
identifier_body
test_utils.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // This program 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 ...
{ Node::new(address, MemoryRegion::new(&[0; 1])) }
identifier_body
test_utils.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // This program 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 ...
<T>(address: Address, content: &[T]) -> Node { Node::new( address, MemoryRegion::new(unsafe { from_raw_parts( content.as_ptr() as *const u8, content.len() * size_of::<T>(), ) }), ) } pub(crate) fn simple_node(address: Address) -> N...
simple_node_content
identifier_name
test_utils.rs
// ams - Advanced Memory Scanner // Copyright (C) 2018 th0rex // // This program 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 ...
use std::slice::from_raw_parts; use communication::MemoryRegion; use {Address, Node}; pub(crate) fn simple_node_content<T>(address: Address, content: &[T]) -> Node { Node::new( address, MemoryRegion::new(unsafe { from_raw_parts( content.as_ptr() as *const u8, ...
// // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. use std::mem::size_of;
random_line_split
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
} } Err(::Error::Application(ApplicationError { kind: ApplicationErrorKind::Unknown, message: "aborted listen loop".into(), })) } fn new_protocols_for_connection( &mut self, stream: TcpStream, ) -> ::Result<(Box<dyn TInputProtoco...
{ warn!("failed to accept remote connection with error {:?}", e); }
conditional_block
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
{ let mut i_prot = i_prot; let mut o_prot = o_prot; loop { let r = processor.process(&mut *i_prot, &mut *o_prot); if let Err(e) = r { warn!("processor completed with error: {:?}", e); break; } } }
identifier_body
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
(&mut self, listen_address: &str) -> ::Result<()> { let listener = TcpListener::bind(listen_address)?; for stream in listener.incoming() { match stream { Ok(s) => { let (i_prot, o_prot) = self.new_protocols_for_connection(s)?; let proce...
listen
identifier_name
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
loop { let r = processor.process(&mut *i_prot, &mut *o_prot); if let Err(e) = r { warn!("processor completed with error: {:?}", e); break; } } }
let mut o_prot = o_prot;
random_line_split
record-pat.rs
// run-pass #![allow(non_camel_case_types)] #![allow(non_shorthand_field_patterns)] enum t1 { a(isize), b(usize), } struct T2 {x: t1, y: isize} enum t3 { c(T2, usize), } fn m(input: t3) -> isize { match input { t3::c(T2 {x: t1::a(m),..}, _) => { return m; } t3::c(T2 {x: t1::b(m), y: y}, z) => { return...
{ assert_eq!(m(t3::c(T2 {x: t1::a(10), y: 5}, 4)), 10); assert_eq!(m(t3::c(T2 {x: t1::b(10), y: 5}, 4)), 19); }
identifier_body
record-pat.rs
// run-pass #![allow(non_camel_case_types)] #![allow(non_shorthand_field_patterns)] enum t1 { a(isize), b(usize), } struct
{x: t1, y: isize} enum t3 { c(T2, usize), } fn m(input: t3) -> isize { match input { t3::c(T2 {x: t1::a(m),..}, _) => { return m; } t3::c(T2 {x: t1::b(m), y: y}, z) => { return ((m + z) as isize) + y; } } } pub fn main() { assert_eq!(m(t3::c(T2 {x: t1::a(10), y: 5}, 4)), 10); assert_eq!(m...
T2
identifier_name
record-pat.rs
// run-pass
#![allow(non_camel_case_types)] #![allow(non_shorthand_field_patterns)] enum t1 { a(isize), b(usize), } struct T2 {x: t1, y: isize} enum t3 { c(T2, usize), } fn m(input: t3) -> isize { match input { t3::c(T2 {x: t1::a(m),..}, _) => { return m; } t3::c(T2 {x: t1::b(m), y: y}, z) => { return ((m + z) as...
random_line_split
load_block.rs
use {MultiFileDirectAccessor, InMemoryFileSystem}; use bip_disk::{DiskManagerBuilder, IDiskMessage, ODiskMessage, BlockMetadata, Block, BlockMut}; use bip_metainfo::{MetainfoBuilder, PieceLength, Metainfo}; use bytes::BytesMut; use tokio_core::reactor::{Core}; use futures::future::{Loop}; use futures::stream::Stream; u...
() { // Create some "files" as random bytes let data_a = (::random_buffer(1023), "/path/to/file/a".into()); let data_b = (::random_buffer(2000), "/path/to/file/b".into()); // Create our accessor for our in memory files and create a torrent file for them let files_accessor = MultiFileDirectAccessor:...
positive_load_block
identifier_name
load_block.rs
use {MultiFileDirectAccessor, InMemoryFileSystem}; use bip_disk::{DiskManagerBuilder, IDiskMessage, ODiskMessage, BlockMetadata, Block, BlockMut}; use bip_metainfo::{MetainfoBuilder, PieceLength, Metainfo}; use bytes::BytesMut; use tokio_core::reactor::{Core}; use futures::future::{Loop}; use futures::stream::Stream; u...
let mut load_block = BytesMut::with_capacity(50); load_block.extend_from_slice(&[0u8; 50]); let process_block = Block::new(BlockMetadata::new(metainfo_file.info().info_hash(), 1, 0, 50), process_block.freeze()); let load_block = BlockMut::new(BlockMetadata::new(metainfo_file.info().info_hash(), 1, ...
{ // Create some "files" as random bytes let data_a = (::random_buffer(1023), "/path/to/file/a".into()); let data_b = (::random_buffer(2000), "/path/to/file/b".into()); // Create our accessor for our in memory files and create a torrent file for them let files_accessor = MultiFileDirectAccessor::ne...
identifier_body
load_block.rs
use {MultiFileDirectAccessor, InMemoryFileSystem}; use bip_disk::{DiskManagerBuilder, IDiskMessage, ODiskMessage, BlockMetadata, Block, BlockMut}; use bip_metainfo::{MetainfoBuilder, PieceLength, Metainfo}; use bytes::BytesMut; use tokio_core::reactor::{Core}; use futures::future::{Loop}; use futures::stream::Stream; u...
}, ODiskMessage::BlockLoaded(block) => Loop::Break((opt_pblock.unwrap(), block)), unexpected @ _ => panic!("Unexpected Message: {:?}", unexpected) } } ); // Verify lblock contains our data assert_eq!(*pblock, *lblock); }
blocking_send.send(IDiskMessage::LoadBlock(opt_lblock.unwrap())).unwrap(); Loop::Continue(((blocking_send, Some(block), None), recv))
random_line_split
rtdeps.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 ...
extern {}
extern {} #[cfg(target_os = "macos")] #[link(name = "System")]
random_line_split
binary_digits.rs
// Implements http://rosettacode.org/wiki/Binary_digits use std::iter::range_inclusive; trait BinaryString { fn to_binary_string(&self) -> String; } impl BinaryString for uint { fn to_binary_string(&self) -> String { format!("{:t}", *self) } } #[cfg(not(test))] fn main() { for s in range_incl...
for (n, expected) in range_inclusive(0, 16u).zip(expected.iter()) { assert_eq!(n.to_binary_string().as_slice(), *expected); } }
random_line_split
binary_digits.rs
// Implements http://rosettacode.org/wiki/Binary_digits use std::iter::range_inclusive; trait BinaryString { fn to_binary_string(&self) -> String; } impl BinaryString for uint { fn to_binary_string(&self) -> String { format!("{:t}", *self) } } #[cfg(not(test))] fn
() { for s in range_inclusive(0, 16u) { println!("{}", s.to_binary_string()); } } #[test] fn test_digits() { let expected = ["0", "1", "10", "11", "100", "101", "110", "111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"];...
main
identifier_name
binary_digits.rs
// Implements http://rosettacode.org/wiki/Binary_digits use std::iter::range_inclusive; trait BinaryString { fn to_binary_string(&self) -> String; } impl BinaryString for uint { fn to_binary_string(&self) -> String { format!("{:t}", *self) } } #[cfg(not(test))] fn main() { for s in range_incl...
{ let expected = ["0", "1", "10", "11", "100", "101", "110", "111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"]; for (n, expected) in range_inclusive(0, 16u).zip(expected.iter()) { assert_eq!(n.to_binary_string().as_slice()...
identifier_body
crypto.rs
// // Copyright 2021 The Project Oak Authors // // 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...
#[derive(PartialEq)] pub(crate) struct DecryptionKey(pub(crate) [u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]); /// Implementation of Authenticated Encryption with Associated Data (AEAD). /// /// <https://datatracker.ietf.org/doc/html/rfc5116> /// /// This implementation uses separate keys for encrypting data and decryptin...
/// Convenience struct for passing an encryption key as an argument. #[derive(PartialEq)] pub(crate) struct EncryptionKey(pub(crate) [u8; KEY_AGREEMENT_ALGORITHM_KEY_LENGTH]); /// Convenience struct for passing a decryption key as an argument.
random_line_split
crypto.rs
// // Copyright 2021 The Project Oak Authors // // 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...
<const L: usize>() -> anyhow::Result<[u8; L]> { let mut result: [u8; L] = [Default::default(); L]; let rng = SystemRandom::new(); rng.fill(&mut result[..]) .map_err(|error| anyhow!("Couldn't create random value: {:?}", error))?; Ok(result) }
get_random
identifier_name
crypto.rs
// // Copyright 2021 The Project Oak Authors // // 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...
} }, ) .context("Couldn't agree on session keys")?; Ok(( EncryptionKey(encryption_key.context("Couldn't derive encryption key")?), DecryptionKey(decryption_key.context("Couldn't derive decryption key")?), )) } /// Derives a ses...
{ let encryption_key = Self::key_derivation_function( key_material, CLIENT_KEY_PURPOSE, &peer_public_key, &self_public_key, ); let decry...
conditional_block
u512.rs
//! Unsigned 512-bit integer use std::convert::{From, Into}; use std::ops::{Add, Sub, Mul, Div, Shr, Shl, BitAnd, Rem}; use std::cmp::Ordering; use std::fmt; use super::U256; use super::algorithms::{add2, mac3, from_signed, sub2_sign}; #[repr(C)] #[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)] /// Represents an u...
(mut self, other: U512) -> U512 { let U512(ref mut a) = self; let U512(ref b) = other; let carry = add2(a, b); assert!(carry == 0); U512(*a) } } impl Sub for U512 { type Output = U512; fn sub(mut self, other: U512) -> U512 { let U512(ref mut a) = self; ...
add
identifier_name
u512.rs
//! Unsigned 512-bit integer use std::convert::{From, Into}; use std::ops::{Add, Sub, Mul, Div, Shr, Shl, BitAnd, Rem}; use std::cmp::Ordering; use std::fmt; use super::U256; use super::algorithms::{add2, mac3, from_signed, sub2_sign}; #[repr(C)] #[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)] /// Represents an u...
} impl Mul for U512 { type Output = U512; fn mul(mut self, other: U512) -> U512 { let mut ret = [0u32; 16]; let U512(ref mut a) = self; let U512(ref b) = other; let mut carry = 0; for (i, bi) in b.iter().rev().enumerate() { carry = mac3(&mut ret[0..(16-i)...
{ let U512(ref mut a) = self; let U512(ref b) = other; let sign = sub2_sign(a, b); from_signed(sign, a); U512(*a) }
identifier_body
u512.rs
//! Unsigned 512-bit integer use std::convert::{From, Into}; use std::ops::{Add, Sub, Mul, Div, Shr, Shl, BitAnd, Rem}; use std::cmp::Ordering; use std::fmt; use super::U256; use super::algorithms::{add2, mac3, from_signed, sub2_sign}; #[repr(C)] #[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)] /// Represents an u...
U512([0u32; 16]) } } impl From<U256> for U512 { fn from(val: U256) -> U512 { let mut ret = [0u32; 16]; let val: [u32; 8] = val.into(); for i in 0..8 { ret[8 + i] = val[i]; } U512(ret) } } impl Into<U256> for U512 { fn into(self) -> U256 { ...
} /// Zero value of U512. pub fn zero() -> U512 {
random_line_split
u512.rs
//! Unsigned 512-bit integer use std::convert::{From, Into}; use std::ops::{Add, Sub, Mul, Div, Shr, Shl, BitAnd, Rem}; use std::cmp::Ordering; use std::fmt; use super::U256; use super::algorithms::{add2, mac3, from_signed, sub2_sign}; #[repr(C)] #[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)] /// Represents an u...
current_bits = (32 - arr[i].leading_zeros() as usize) + ((15 - i) * 32); } current_bits } /// Zero value of U512. pub fn zero() -> U512 { U512([0u32; 16]) } } impl From<U256> for U512 { fn from(val: U256) -> U512 { let mut ret = [0u32; 16]; let...
{ continue; }
conditional_block
struct-fields-typo.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 ...
() { let foo = BuildData { foo: 0, bar: 0.5, }; let x = foo.baa;//~ ERROR attempted access of field `baa` on type `BuildData` //~^ HELP did you mean `bar`? println!("{}", x); }
main
identifier_name
p_2_1_5_02.rs
// P_2_1_5_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung....
max_radius: 250.0, density: 5, } } fn view(app: &App, model: &Model, frame: Frame) { // Prepare to draw. let draw = app.draw(); draw.background().color(WHITE); model.shapes.iter().for_each(|shape| { shape.display(&draw, &model); }); // Write to the window frame. ...
random_line_split
p_2_1_5_02.rs
// P_2_1_5_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung....
p: &App, _model: &mut Model, key: Key) { if key == Key::S { app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } }
_released(ap
identifier_name
p_2_1_5_02.rs
// P_2_1_5_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung....
n view(app: &App, model: &Model, frame: Frame) { // Prepare to draw. let draw = app.draw(); draw.background().color(WHITE); model.shapes.iter().for_each(|shape| { shape.display(&draw, &model); }); // Write to the window frame. draw.to_frame(app, &frame).unwrap(); } fn mouse_releas...
let _window = app .new_window() .size(800, 800) .view(view) .mouse_released(mouse_released) .key_released(key_released) .build() .unwrap(); let shapes = vec![Shape::new(0.0, 0.0, app.window_rect().w()); 1]; Model { shapes, min_radius: 5...
identifier_body
p_2_1_5_02.rs
// P_2_1_5_02 // // Generative Gestaltung – Creative Coding im Web // ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018 // Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni // with contributions by Joey Lee and Niels Poldervaart // Copyright 2018 // // http://www.generative-gestaltung....
app.main_window() .capture_frame(app.exe_name().unwrap() + ".png"); } }
conditional_block
mod.rs
use crate::context::Context; use crate::error::RenderError; use crate::json::value::ScopedJson; use crate::output::Output; use crate::registry::Registry; use crate::render::{do_escape, Helper, RenderContext}; pub use self::helper_each::EACH_HELPER; pub use self::helper_if::{IF_HELPER, UNLESS_HELPER}; pub use self::hel...
/// When calling the helper as a subexpression, the value and its type can /// be received by upper level helpers. /// /// Note that the value can be `json!(null)` which is treated as `false` in /// helpers like `if` and rendered as empty string. fn call_inner<'reg: 'rc, 'rc>( &self, ...
/// /// ### Calling from subexpression ///
random_line_split
mod.rs
use crate::context::Context; use crate::error::RenderError; use crate::json::value::ScopedJson; use crate::output::Output; use crate::registry::Registry; use crate::render::{do_escape, Helper, RenderContext}; pub use self::helper_each::EACH_HELPER; pub use self::helper_if::{IF_HELPER, UNLESS_HELPER}; pub use self::hel...
/// A complex version of helper interface. /// /// This function offers `Output`, which you can write custom string into /// and render child template. Helpers like `if` and `each` are implemented /// with this. Because the data written into `Output` are typically without /// type information....
{ Err(RenderError::unimplemented()) }
identifier_body
mod.rs
use crate::context::Context; use crate::error::RenderError; use crate::json::value::ScopedJson; use crate::output::Output; use crate::registry::Registry; use crate::render::{do_escape, Helper, RenderContext}; pub use self::helper_each::EACH_HELPER; pub use self::helper_if::{IF_HELPER, UNLESS_HELPER}; pub use self::hel...
else { Err(e) } } } } } /// implement HelperDef for bare function so we can use function as helper impl< F: for<'reg, 'rc> Fn( &Helper<'reg, 'rc>, &'reg Registry<'reg>, &'rc Context, &mut RenderContext<...
{ // default implementation, do nothing Ok(()) }
conditional_block
mod.rs
use crate::context::Context; use crate::error::RenderError; use crate::json::value::ScopedJson; use crate::output::Output; use crate::registry::Registry; use crate::render::{do_escape, Helper, RenderContext}; pub use self::helper_each::EACH_HELPER; pub use self::helper_if::{IF_HELPER, UNLESS_HELPER}; pub use self::hel...
<'reg: 'rc, 'rc>( &self, _: &Helper<'reg, 'rc>, _: &'reg Registry<'reg>, _: &'rc Context, _: &mut RenderContext<'reg, 'rc>, ) -> Result<ScopedJson<'reg, 'rc>, RenderError> { Err(RenderError::unimplemented()) } /// A complex version of helper interface. //...
call_inner
identifier_name
manual.rs
extern crate ralloc; use std::ptr; fn main()
for i in 0..300 { *ptr1.offset(i) = i as u8; } assert_eq!(*ptr1, 0); assert_eq!(*ptr1.offset(200), 200); ralloc::free(ptr1, 30); ralloc::free(ptr2, 500); } }
{ let ptr1 = ralloc::alloc(30, 3); let ptr2 = ralloc::alloc(500, 20); assert_eq!(0, ptr1 as usize % 3); assert_eq!(0, ptr2 as usize % 20); unsafe { ptr::write_bytes(ptr1, 0x22, 30); for i in 0..500 { *ptr2.offset(i) = i as u8; } assert_eq!(*ptr1, 0x22);...
identifier_body
manual.rs
extern crate ralloc; use std::ptr; fn main() { let ptr1 = ralloc::alloc(30, 3); let ptr2 = ralloc::alloc(500, 20); assert_eq!(0, ptr1 as usize % 3); assert_eq!(0, ptr2 as usize % 20); unsafe { ptr::write_bytes(ptr1, 0x22, 30); for i in 0..500 { *ptr2.offset(i) = i as ...
assert_eq!(*ptr2, 0); assert_eq!(*ptr2.offset(15), 15); let ptr1 = ralloc::realloc(ptr1, 30, 300, 3); for i in 0..300 { *ptr1.offset(i) = i as u8; } assert_eq!(*ptr1, 0); assert_eq!(*ptr1.offset(200), 200); ralloc::free(ptr1, 30); ral...
assert_eq!(*ptr1, 0x22); assert_eq!(*ptr1.offset(5), 0x22);
random_line_split
manual.rs
extern crate ralloc; use std::ptr; fn
() { let ptr1 = ralloc::alloc(30, 3); let ptr2 = ralloc::alloc(500, 20); assert_eq!(0, ptr1 as usize % 3); assert_eq!(0, ptr2 as usize % 20); unsafe { ptr::write_bytes(ptr1, 0x22, 30); for i in 0..500 { *ptr2.offset(i) = i as u8; } assert_eq!(*ptr1, 0x2...
main
identifier_name
build.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...
, _ => { diagnostic.handler().err("multiple plugin registration functions found"); for &(_, span) in finder.registrars.iter() { diagnostic.span_note(span, "one is here"); } diagnostic.handler().abort_if_errors(); unreachable!(); ...
{ let (node_id, _) = finder.registrars.pop().unwrap(); Some(node_id) }
conditional_block
build.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...
{ let mut finder = RegistrarFinder { registrars: Vec::new() }; visit::walk_crate(&mut finder, krate, ()); match finder.registrars.len() { 0 => None, 1 => { let (node_id, _) = finder.registrars.pop().unwrap(); Some(node_id) }, _ => { diagno...
identifier_body
build.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...
{ registrars: Vec<(ast::NodeId, Span)>, } impl Visitor<()> for RegistrarFinder { fn visit_item(&mut self, item: &ast::Item, _: ()) { match item.node { ast::ItemFn(..) => { if attr::contains_name(item.attrs.as_slice(), "plugin_registrar...
RegistrarFinder
identifier_name
build.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...
use syntax::visit; use syntax::visit::Visitor; struct RegistrarFinder { registrars: Vec<(ast::NodeId, Span)>, } impl Visitor<()> for RegistrarFinder { fn visit_item(&mut self, item: &ast::Item, _: ()) { match item.node { ast::ItemFn(..) => { if attr::contains_name(item.attr...
use syntax::diagnostic;
random_line_split
lib.rs
//! ### TODO //! //! * offer GC interface and example GCs //! * rust currently doesn't allow generic static values - when it does, make this library //! truely generic: Add `read_pool`, `write_pool`. Keep `[Byte]Symbol`, `[Byte]SymbolPool` as //! useful aliases. //! #![feature(hashmap_hasher)] #![feature(set_recove...
pub fn read_byte_symbol_pool() -> RwLockReadGuard<'static, ByteSymbolPool> { byte_symbol_pool_instance().read().unwrap() } pub fn write_byte_symbol_pool() -> RwLockWriteGuard<'static, ByteSymbolPool> { byte_symbol_pool_instance().write().unwrap() } impl<'a> From<&'a [u8]> for ByteSymbol { fn from(s: &'a ...
} } }
random_line_split
lib.rs
//! ### TODO //! //! * offer GC interface and example GCs //! * rust currently doesn't allow generic static values - when it does, make this library //! truely generic: Add `read_pool`, `write_pool`. Keep `[Byte]Symbol`, `[Byte]SymbolPool` as //! useful aliases. //! #![feature(hashmap_hasher)] #![feature(set_recove...
pub fn read_byte_symbol_pool() -> RwLockReadGuard<'static, ByteSymbolPool> { byte_symbol_pool_instance().read().unwrap() } pub fn write_byte_symbol_pool() -> RwLockWriteGuard<'static, ByteSymbolPool> { byte_symbol_pool_instance().write().unwrap() } impl<'a> From<&'a [u8]> for ByteSymbol { fn from(s: &'a...
{ static POOL: Option<RwLock<ByteSymbolPool>> = None; match &POOL { &Some(ref r) => r, // beware of racey hack! pool => unsafe { let init = Some(RwLock::new(ByteSymbolPool::new())); ::std::ptr::write(pool as *const _ as *mut Option<RwLock<ByteSymbolPool>>, init)...
identifier_body
lib.rs
//! ### TODO //! //! * offer GC interface and example GCs //! * rust currently doesn't allow generic static values - when it does, make this library //! truely generic: Add `read_pool`, `write_pool`. Keep `[Byte]Symbol`, `[Byte]SymbolPool` as //! useful aliases. //! #![feature(hashmap_hasher)] #![feature(set_recove...
<S: rustc_serialize::Encoder>(&self, s: &mut S) -> Result<(), S::Error> { (*self.inner).encode(s) } } impl<B:?Sized, O> Decodable for Interned<B, O> where O: Decodable, Interned<B, O>: From<O> { fn decode<D: rustc_serialize::Decoder>(d: &mut D) -> Result<Self, D::Error> { Ok(Self::from(t...
encode
identifier_name
p1.rs
use serialize::base64::{self, ToBase64}; use serialize::hex::FromHex; #[test] fn run() { let hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f697 \ 36f6e6f7573206d757368726f6f6d"; let b64_exp = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
}
let b64_act = hex.from_hex().unwrap().to_base64(base64::STANDARD); assert_eq!(b64_exp, b64_act);
random_line_split
p1.rs
use serialize::base64::{self, ToBase64}; use serialize::hex::FromHex; #[test] fn run()
{ let hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f697 \ 36f6e6f7573206d757368726f6f6d"; let b64_exp = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"; let b64_act = hex.from_hex().unwrap().to_base64(base64::STANDARD); assert_eq!(b64_exp, b64_ac...
identifier_body
p1.rs
use serialize::base64::{self, ToBase64}; use serialize::hex::FromHex; #[test] fn
() { let hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f697 \ 36f6e6f7573206d757368726f6f6d"; let b64_exp = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"; let b64_act = hex.from_hex().unwrap().to_base64(base64::STANDARD); assert_eq!(b64_exp, b64...
run
identifier_name
04_using_matches.rs
extern crate clap; use clap::{App, Arg}; fn
() { // Once all App settings (including all arguments) have been set, you call get_matches() which // parses the string provided by the user, and returns all the valid matches to the ones you // specified. // // You can then query the matches struct to get information about how the user ran the pr...
main
identifier_name
04_using_matches.rs
extern crate clap; use clap::{App, Arg}; fn main() { // Once all App settings (including all arguments) have been set, you call get_matches() which // parses the string provided by the user, and returns all the valid matches to the ones you // specified. // // You can then query the matches struc...
.arg(Arg::with_name("config") .help("sets the config file to use") .short("c") .long("config")) .arg(Arg::with_name("input") .help("th...
.author("Kevin K. <kbknapp@gmail.com>") .arg(Arg::with_name("debug") .help("turn on debugging information") .short("d") .long("debug"))
random_line_split
04_using_matches.rs
extern crate clap; use clap::{App, Arg}; fn main() { // Once all App settings (including all arguments) have been set, you call get_matches() which // parses the string provided by the user, and returns all the valid matches to the ones you // specified. // // You can then query the matches struc...
// Because "input" is required we can safely call unwrap() because had the user NOT // specified a value, clap would have explained the error the user, and exited. println!("Doing real work with file: {}", matches.value_of("input").unwrap() ); // Continued program logic goes here... }
{ println!("Using config file: {}", file); }
conditional_block
04_using_matches.rs
extern crate clap; use clap::{App, Arg}; fn main()
.help("turn on debugging information") .short("d") .long("debug")) .arg(Arg::with_name("config") .help("sets the config file to use") ...
{ // Once all App settings (including all arguments) have been set, you call get_matches() which // parses the string provided by the user, and returns all the valid matches to the ones you // specified. // // You can then query the matches struct to get information about how the user ran the progr...
identifier_body