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
window-properties.rs
extern crate sdl2; use sdl2::pixels::Color; pub fn main() { let mut sdl_context = sdl2::init().video().unwrap(); let window = sdl_context.window("rust-sdl2 demo: Window", 800, 600) .resizable() .build() .unwrap(); let mut renderer = window.renderer().present_vsync().build().unwrap()...
} } { // Update the window title. // &sdl_context is needed to safely access the Window and to ensure that the event loop // isn't running (which could mutate the Window). // Note: if you don't use renderer: window.properties(&sdl_context); ...
{}
conditional_block
window-properties.rs
extern crate sdl2; use sdl2::pixels::Color; pub fn
() { let mut sdl_context = sdl2::init().video().unwrap(); let window = sdl_context.window("rust-sdl2 demo: Window", 800, 600) .resizable() .build() .unwrap(); let mut renderer = window.renderer().present_vsync().build().unwrap(); let mut running = true; let mut tick = 0; ...
main
identifier_name
window-properties.rs
extern crate sdl2; use sdl2::pixels::Color; pub fn main() { let mut sdl_context = sdl2::init().video().unwrap(); let window = sdl_context.window("rust-sdl2 demo: Window", 800, 600) .resizable() .build() .unwrap(); let mut renderer = window.renderer().present_vsync().build().unwrap()...
Event::Quit {..} | Event::KeyDown { keycode: KeyCode::Escape,.. } => { running = false }, _ => {} } } { // Update the window title. // &sdl_context is needed to safely access the Window and to ensure...
use sdl2::event::Event; use sdl2::keycode::KeyCode; match event {
random_line_split
toggle_tool_button.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Actionable; use Bin; use Buildable; use Container; use ToolButton; use ToolItem; use Widget; use ffi; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandl...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ToggleToolButton") } }
fmt
identifier_name
toggle_tool_button.rs
// This file was generated by gir (https://github.com/gtk-rs/gir) // from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Actionable; use Bin; use Buildable; use Container; use ToolButton; use ToolItem; use Widget; use ffi; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandl...
impl fmt::Display for ToggleToolButton { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "ToggleToolButton") } }
{ let f: &F = transmute(f); f(&ToggleToolButton::from_glib_borrow(this).unsafe_cast()) }
identifier_body
toggle_tool_button.rs
// This file was generated by gir (https://github.com/gtk-rs/gir)
use Buildable; use Container; use ToolButton; use ToolItem; use Widget; use ffi; use glib::object::Cast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect_raw; use glib::translate::*; use glib_ffi; use std::boxed::Box as Box_; use std::fmt; use std::mem::transmute; glib_wrapper! { ...
// from gir-files (https://github.com/gtk-rs/gir-files) // DO NOT EDIT use Actionable; use Bin;
random_line_split
move-fragments-1.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 ...
#[rustc_move_fragments] pub fn test_take_struct(_p: Pair<D, D>) { //~^ ERROR assigned_leaf_path: `$(local _p)` } #[rustc_move_fragments] pub fn test_drop_struct_part(p: Pair<D, D>) { //~^ ERROR parent_of_fragments: `$(local p)` //~| ERROR moved_leaf_pat...
pub fn test_take(_x: D) { //~^ ERROR assigned_leaf_path: `$(local _x)` } pub struct Pair<X,Y> { x: X, y: Y }
random_line_split
move-fragments-1.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 ...
() { }
main
identifier_name
move-fragments-1.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 ...
#[rustc_move_fragments] pub fn test_take(_x: D) { //~^ ERROR assigned_leaf_path: `$(local _x)` } pub struct Pair<X,Y> { x: X, y: Y } #[rustc_move_fragments] pub fn test_take_struct(_p: Pair<D, D>) { //~^ ERROR assigned_leaf_path: `$(local _p)` } #[rustc_move_fragments] pub...
{ }
identifier_body
base64.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...
() { assert_eq!("Zm9v\r\nYmFy".from_base64().unwrap().as_slice(), "foobar".as_bytes()); assert_eq!("Zm9vYg==\r\n".from_base64().unwrap().as_slice(), "foob".as_bytes()); } #[test] fn test_from_base64_urlsafe() { assert_eq!("-_8".from_base64().unw...
test_from_base64_newlines
identifier_name
base64.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...
} 2 => { let n = (self[i] as u32) << 16 | (self[i + 1u] as u32) << 8; v.push(bytes[((n >> 18) & 63) as uint]); v.push(bytes[((n >> 12) & 63) as uint]); v.push(bytes[((n >> 6 ) & 63) as uint]); if ...
random_line_split
stylesheet_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use document_loader::LoadType; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; u...
} } } /// The context required for asynchronously loading an external stylesheet. pub struct StylesheetContext { /// The element that initiated the request. elem: Trusted<HTMLElement>, source: StylesheetContextSource, metadata: Option<Metadata>, /// The response body received to date. ...
{ let import = import.read(); // Look at the parser in style::stylesheets, where we don't // trigger a load if the url is invalid. import.url.url() .expect("Invalid urls shouldn't enter the loader") .clone() ...
conditional_block
stylesheet_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use document_loader::LoadType; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; u...
fn process_request_eof(&mut self) {} fn process_response(&mut self, metadata: Result<FetchMetadata, NetworkError>) { self.metadata = metadata.ok().map(|m| { match m { FetchMetadata::Unfiltered(m) => m, FetchMetadata::Filtered { unsaf...
{}
identifier_body
stylesheet_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use document_loader::LoadType; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; u...
(element: &'a HTMLElement) -> Self { StylesheetLoader { elem: element, } } } impl<'a> StylesheetLoader<'a> { pub fn load(&self, source: StylesheetContextSource) { let url = source.url(); let context = Arc::new(Mutex::new(StylesheetContext { elem: Trusted:...
for_element
identifier_name
stylesheet_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use document_loader::LoadType; use dom::bindings::inheritance::Castable; use dom::bindings::refcounted::Trusted; u...
let data = if is_css { mem::replace(&mut self.data, vec![]) } else { vec![] }; // TODO: Get the actual value. http://dev.w3.org/csswg/css-syntax/#environment-encoding let environment_encoding = UTF_8 as EncodingRef; let protocol_encoding_label = metadata.charset.as_ref()...
let is_css = metadata.content_type.map_or(false, |Serde(ContentType(Mime(top, sub, _)))| top == TopLevel::Text && sub == SubLevel::Css);
random_line_split
main.rs
// Copyright 2014 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
<R, F>(factory: &mut F, data: &[u8]) -> Result<gfx::handle::Texture<R>, String> where R: gfx::Resources, F: gfx::device::Factory<R> { let img = image::load(Cursor::new(data), image::PNG).unwrap(); let img = match img { image::DynamicImage::ImageRgba8(img) => img, img => img.to_rgba() ...
load_texture
identifier_name
main.rs
// Copyright 2014 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
let water_texture = load_texture(&mut factory, &include_bytes!("image/water.png")[..]).unwrap(); let flow_texture = load_texture(&mut factory, &include_bytes!("image/flow.png")[..]).unwrap(); let noise_texture = load_texture(&mut factory, &include_bytes!("image/noise.png")[..]).unwrap(); let program ...
{ use time::precise_time_s; let (mut stream, mut device, mut factory) = gfx_window_glutin::init( glutin::WindowBuilder::new() .with_title("Flowmap example".to_string()) .with_dimensions(800, 600).build().unwrap() ); let vertex_data = [ Vertex::new([-1.0, -1.0], ...
identifier_body
main.rs
// Copyright 2014 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
, } } // since we sample our diffuse texture twice we need to lerp between // them to get a smooth transition (shouldn't even be noticable). // they start half a cycle apart (0.5) and is later used to calculate // the interpolation amount via `2.0 * abs(cycle0 -.5f)...
{}
conditional_block
main.rs
// Copyright 2014 The Gfx-rs Developers. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
}); stream.draw(&batch).unwrap(); stream.present(&mut device); } }
color: [0.3, 0.3, 0.3, 1.0], depth: 1.0, stencil: 0,
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of st...
pub mod timer; pub mod traversal; pub mod traversal_flags; pub mod use_counters; #[macro_use] #[allow(non_camel_case_types)] pub mod values; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache as string_cache; #[cfg(feature = "gecko")] pub use crate::gecko_string_cache::Atom; #[cfg(feature = "gecko")] pub use ...
pub mod stylesheets; pub mod stylist; pub mod thread_state;
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of st...
(self, a: &WeakAtom, b: &WeakAtom) -> bool { match self { selectors::attr::CaseSensitivity::CaseSensitive => a == b, selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } } }
eq_atom
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Calculate [specified][specified] and [computed values][computed] from a //! tree of DOM nodes and a set of st...
}
{ match self { selectors::attr::CaseSensitivity::CaseSensitive => a == b, selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b), } }
identifier_body
main.rs
extern crate mio; extern crate rand; mod quote_provider; mod server; use mio::{EventLoop,Token, Interest, PollOpt}; use mio::tcp::*; use mio::udp::*; use quote_provider::*; pub const TCP_SERVER: mio::Token = mio::Token(0); pub const UDP_SERVER: mio::Token = mio::Token(1); #[macro_export] macro_rules! mytry { ($...
() { println!("QOTD starting. Initializing quote provider."); let quote_provider: QuoteProvider = QuoteProviderImpl::new(); println!("Sample quote: {:?}", quote_provider.get_random_quote()); println!("Binding sockets"); let address = "0.0.0.0:6567".parse().unwrap(); let tcp_server = TcpListener...
main
identifier_name
main.rs
extern crate mio; extern crate rand; mod quote_provider; mod server; use mio::{EventLoop,Token, Interest, PollOpt}; use mio::tcp::*; use mio::udp::*; use quote_provider::*; pub const TCP_SERVER: mio::Token = mio::Token(0); pub const UDP_SERVER: mio::Token = mio::Token(1); #[macro_export] macro_rules! mytry { ($...
udp_server: udp_server, quote_provider: quote_provider }; let _ = event_loop.run(&mut qotd_server); drop(qotd_server.udp_server); drop(qotd_server.tcp_server); }
{ println!("QOTD starting. Initializing quote provider."); let quote_provider: QuoteProvider = QuoteProviderImpl::new(); println!("Sample quote: {:?}", quote_provider.get_random_quote()); println!("Binding sockets"); let address = "0.0.0.0:6567".parse().unwrap(); let tcp_server = TcpListener::b...
identifier_body
main.rs
extern crate mio; extern crate rand; mod quote_provider; mod server; use mio::{EventLoop,Token, Interest, PollOpt}; use mio::tcp::*; use mio::udp::*; use quote_provider::*; pub const TCP_SERVER: mio::Token = mio::Token(0); pub const UDP_SERVER: mio::Token = mio::Token(1); #[macro_export] macro_rules! mytry { ($...
drop(qotd_server.tcp_server); }
random_line_split
aarch64.rs
//! Mask reductions implementation for `aarch64` targets /// 128-bit wide vectors macro_rules! aarch64_128_neon_impl { ($id:ident, $vmin:ident, $vmax:ident) => { impl All for $id { #[inline] #[target_feature(enable = "neon")] unsafe fn all(self) -> bool { ...
union U { halves: ($id, $id), vec: $vec128, } U { halves: (self, self), }.vec.all() } } impl Any for $id { #[inline] #[target_feature(enable = "...
unsafe fn all(self) -> bool { // Duplicates the 64-bit vector into a 128-bit one and // calls all on that.
random_line_split
level.rs
use std::collections::BTreeMap; use super::machine::{Input, Output, Registers, Tile}; pub type Level = (Input, Registers, Output); // Copy inbox to outbox pub fn level_1() -> Level { let input = from_numbers(&[1, 2, 3]); let registers = BTreeMap::new(); let output = input.clone(); (input, register...
input.extend(s.chars().map(Tile::Letter)); } fn append_zero_terminated_string(input: &mut Input, s: &str) { append_string(input, s); input.push(Tile::num(0)); }
fn append_string(input: &mut Input, s: &str) {
random_line_split
level.rs
use std::collections::BTreeMap; use super::machine::{Input, Output, Registers, Tile}; pub type Level = (Input, Registers, Output); // Copy inbox to outbox pub fn level_1() -> Level { let input = from_numbers(&[1, 2, 3]); let registers = BTreeMap::new(); let output = input.clone(); (input, register...
(n: &[i16]) -> Input { let mut input = Vec::new(); append_numbers(&mut input, n); input } fn append_numbers(input: &mut Input, n: &[i16]) { input.extend(n.iter().cloned().map(Tile::num)) } fn from_string(s: &str) -> Input { let mut input = Vec::new(); append_string(&mut input, s); input } ...
from_numbers
identifier_name
level.rs
use std::collections::BTreeMap; use super::machine::{Input, Output, Registers, Tile}; pub type Level = (Input, Registers, Output); // Copy inbox to outbox pub fn level_1() -> Level { let input = from_numbers(&[1, 2, 3]); let registers = BTreeMap::new(); let output = input.clone(); (input, register...
// Copy inbox to outbox, losing duplicates pub fn level_35() -> Level { let input = from_string("eabedebaeb"); let mut registers = BTreeMap::new(); registers.insert(14, Tile::num(0)); let output = from_string("eabd"); (input, registers, output) } // Given two zero-terminated words, output the ...
{ let input = parse_mixed("6,4,-1,7,ih"); let registers = BTreeMap::new(); let output = parse_mixed("4,6,7,-1,hi"); (input, registers, output) }
identifier_body
trait-cast.rs
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test cyclic dete...
// 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. //
random_line_split
trait-cast.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 ...
} } } impl to_str for int { fn to_str_(&self) -> ~str { self.to_str() } } impl to_str for Tree { fn to_str_(&self) -> ~str { let (l, r) = (self.left, self.right); let val = &self.val; format!("[{}, {}, {}]", val.to_str_(), l.to_str_(), r.to_str_()) } } fn foo<T:to_str...
{ ~"some(" + t.to_str_() + ~")" }
conditional_block
trait-cast.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 ...
} impl to_str for Tree { fn to_str_(&self) -> ~str { let (l, r) = (self.left, self.right); let val = &self.val; format!("[{}, {}, {}]", val.to_str_(), l.to_str_(), r.to_str_()) } } fn foo<T:to_str>(x: T) -> ~str { x.to_str_() } pub fn main() { let t1 = Tree(@mut TreeR{left: None,...
{ self.to_str() }
identifier_body
trait-cast.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 ...
(@mut TreeR); struct TreeR { left: Option<Tree>, right: Option<Tree>, val: ~to_str } trait to_str { fn to_str_(&self) -> ~str; } impl<T:to_str> to_str for Option<T> { fn to_str_(&self) -> ~str { match *self { None => { ~"none" } Some(ref t) => { ~"some(" + t.to_str_() +...
Tree
identifier_name
extern-call-deep.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { count(data - 1) + 1 } } fn count(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { let result = count(1000); println!("result = {}", result); assert_eq!(result, 1000); }
{ data }
conditional_block
extern-call-deep.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let result = count(1000); println!("result = {}", result); assert_eq!(result, 1000); }
{ unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } }
identifier_body
extern-call-deep.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 ...
(data: libc::uintptr_t) -> libc::uintptr_t { if data == 1 { data } else { count(data - 1) + 1 } } fn count(n: libc::uintptr_t) -> libc::uintptr_t { unsafe { println!("n = {}", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { let result = count(1000); pri...
cb
identifier_name
extern-call-deep.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 ...
extern crate libc; mod rustrt { extern crate libc; #[link(name = "rust_test_helpers")] extern { pub fn rust_dbg_call(cb: extern "C" fn(libc::uintptr_t) -> libc::uintptr_t, data: libc::uintptr_t) -> libc::uintptr_t; } } extern fn cb(da...
// option. This file may not be copied, modified, or distributed // except according to those terms. #![feature(libc)]
random_line_split
event.rs
//! The `event` module contains traits and structs to actually run your game mainloop //! and handle top-level state, as well as handle input events such as keyboard //! and mouse. /// A key code. pub use sdl2::keyboard::Keycode; /// A struct that holds the state of modifier buttons such as ctrl or shift. pub use sdl...
use std::time::Duration; /// A trait defining event callbacks; your primary interface with /// `ggez`'s event loop. Have a type implement this trait and /// override at least the update() and draw() methods, then pass it to /// `event::run()` to run the game's mainloop. /// /// The default event handlers do nothin...
random_line_split
event.rs
//! The `event` module contains traits and structs to actually run your game mainloop //! and handle top-level state, as well as handle input events such as keyboard //! and mouse. /// A key code. pub use sdl2::keyboard::Keycode; /// A struct that holds the state of modifier buttons such as ctrl or shift. pub use sdl...
} /// Runs the game's main loop, calling event callbacks on the given state /// object as events occur. /// /// It does not try to do any type of framerate limiting. See the /// documentation for the `timer` module for more info. pub fn run<S>(ctx: &mut Context, state: &mut S) -> GameResult<()> where S: EventHan...
{ println!("Quitting game"); false }
identifier_body
event.rs
//! The `event` module contains traits and structs to actually run your game mainloop //! and handle top-level state, as well as handle input events such as keyboard //! and mouse. /// A key code. pub use sdl2::keyboard::Keycode; /// A struct that holds the state of modifier buttons such as ctrl or shift. pub use sdl...
MouseMotion { mousestate, x, y, xrel, yrel, .. } => state.mouse_motion_event(mousestate, x, y, xrel, yrel), MouseWhe...
{ state.mouse_button_up_event(mouse_btn, x, y) }
conditional_block
event.rs
//! The `event` module contains traits and structs to actually run your game mainloop //! and handle top-level state, as well as handle input events such as keyboard //! and mouse. /// A key code. pub use sdl2::keyboard::Keycode; /// A struct that holds the state of modifier buttons such as ctrl or shift. pub use sdl...
(&mut self, _gained: bool) {} /// Called upon a quit event. If it returns true, /// the game does not exit. fn quit_event(&mut self) -> bool { println!("Quitting game"); false } } /// Runs the game's main loop, calling event callbacks on the given state /// object as events occur. ///...
focus_event
identifier_name
unify.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&Some(ref v1), &Some(ref v2)) => { if *v1!= *v2 { return err(a_is_expected, (*v1).clone(), (*v2).clone()) } Some((*v1).clone()) } } }; let (new_root, new_rank) = table.borro...
{ Some((*v).clone()) }
conditional_block
unify.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
* * Implementations of this trait are at the end of this file. */ pub trait UnifyValue : Clone + Repr + PartialEq { } /** * Value of a unification key. We implement Tarjan's union-find * algorithm: when two keys are unified, one of them is converted * into a "redirect" pointing at the other. These redirects form...
* `Bounds<ty::t>`.
random_line_split
unify.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn unify(&mut self, tcx: &ty::ctxt, node_a: &Node<K,V>, node_b: &Node<K,V>) -> (K, uint) { /*! * Either redirects node_a to node_b or vice versa, depending * on the relative rank. Returns the new root and rank. ...
{ /*! * Sets the value for `vid` to `new_value`. `vid` MUST be a * root node! Also, we must be in the middle of a snapshot. */ assert!(self.is_root(&key)); assert!(self.in_snapshot()); debug!("Updating variable {} to {}", key.repr(tcx), ...
identifier_body
unify.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&mut self, tcx: &ty::ctxt, node_a: &Node<K,V>, node_b: &Node<K,V>) -> (K, uint) { /*! * Either redirects node_a to node_b or vice versa, depending * on the relative rank. Returns the new root and rank. You * sho...
unify
identifier_name
lib.rs
extern crate phf; extern crate unicase; #[cfg(test)] mod test { use unicase::Ascii; include!(concat!(env!("OUT_DIR"), "/codegen.rs")); #[test] fn map() { assert_eq!("a", MAP[&1]); assert_eq!("b", MAP[&2]); assert_eq!("c", MAP[&3]); assert!(!MAP.contains_key(&100)); ...
#[test] fn ordered_map() { assert_eq!("a", ORDERED_MAP[&1]); assert_eq!("b", ORDERED_MAP[&2]); assert_eq!("c", ORDERED_MAP[&3]); assert!(!ORDERED_MAP.contains_key(&100)); assert_eq!(&["a", "b", "c"][..], &ORDERED_MAP.values().cloned().collect::<Vec<_>>()[..]); } ...
{ assert!(SET.contains(&1)); assert!(SET.contains(&2)); assert!(SET.contains(&3)); assert!(!SET.contains(&4)); }
identifier_body
lib.rs
extern crate phf; extern crate unicase; #[cfg(test)] mod test { use unicase::Ascii; include!(concat!(env!("OUT_DIR"), "/codegen.rs")); #[test] fn map() { assert_eq!("a", MAP[&1]); assert_eq!("b", MAP[&2]); assert_eq!("c", MAP[&3]); assert!(!MAP.contains_key(&100)); ...
assert!(!UNICASE_MAP.contains_key(&Ascii::new("XyZ"))); } }
assert_eq!("b", UNICASE_MAP[&Ascii::new("DEf")]);
random_line_split
lib.rs
extern crate phf; extern crate unicase; #[cfg(test)] mod test { use unicase::Ascii; include!(concat!(env!("OUT_DIR"), "/codegen.rs")); #[test] fn
() { assert_eq!("a", MAP[&1]); assert_eq!("b", MAP[&2]); assert_eq!("c", MAP[&3]); assert!(!MAP.contains_key(&100)); } #[test] fn set() { assert!(SET.contains(&1)); assert!(SET.contains(&2)); assert!(SET.contains(&3)); assert!(!SET.contains(&4...
map
identifier_name
headless.rs
use crate::errors::*; use crate::math::prelude::Vector2; use super::super::events::Event; use super::Visitor; pub struct HeadlessVisitor {} impl Visitor for HeadlessVisitor { #[inline] fn show(&self) {} #[inline] fn hide(&self) {} #[inline] fn position(&self) -> Vector2<i32> { (0, 0...
(&self) -> Result<()> { Ok(()) } }
swap_buffers
identifier_name
headless.rs
use crate::errors::*; use crate::math::prelude::Vector2; use super::super::events::Event; use super::Visitor; pub struct HeadlessVisitor {} impl Visitor for HeadlessVisitor { #[inline] fn show(&self) {} #[inline] fn hide(&self) {} #[inline] fn position(&self) -> Vector2<i32> { (0, 0...
#[inline] fn is_current(&self) -> bool { true } #[inline] fn make_current(&self) -> Result<()> { Ok(()) } #[inline] fn swap_buffers(&self) -> Result<()> { Ok(()) } }
{}
identifier_body
headless.rs
use crate::errors::*; use crate::math::prelude::Vector2; use super::super::events::Event;
pub struct HeadlessVisitor {} impl Visitor for HeadlessVisitor { #[inline] fn show(&self) {} #[inline] fn hide(&self) {} #[inline] fn position(&self) -> Vector2<i32> { (0, 0).into() } #[inline] fn dimensions(&self) -> Vector2<u32> { (0, 0).into() } #[inli...
use super::Visitor;
random_line_split
casing.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::codemap::Span; use syntax::ast; us...
<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult + 'cx> { expand_cased(cx, sp, tts, |s| { s.to_lowercase() }) } pub fn expand_upper<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree]) -> Box<base::MacResult + 'cx> { ex...
expand_lower
identifier_name
casing.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::codemap::Span; use syntax::ast; us...
-> Box<base::MacResult + 'cx> where T: Fn(&str) -> String { let es = match base::get_exprs_from_tts(cx, sp, tts) { Some(e) => e, None => return base::DummyResult::expr(sp) }; let mut it = es.iter(); let res = if let Some(expr) = it.next() { if let ast...
} fn expand_cased<'cx, T>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree], transform: T)
random_line_split
casing.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::codemap::Span; use syntax::ast; us...
fn expand_cased<'cx, T>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree], transform: T) -> Box<base::MacResult + 'cx> where T: Fn(&str) -> String { let es = match base::get_exprs_from_tts(cx, sp, tts) { Some(e) => e, None => return base::DummyResult::expr(sp) ...
{ expand_cased(cx, sp, tts, |s| { s.to_uppercase() }) }
identifier_body
io_sync_bridge.rs
#![cfg(feature = "io-util")] use std::error::Error; use std::io::{Cursor, Read, Result as IoResult}; use tokio::io::AsyncRead; use tokio_util::io::SyncIoBridge; async fn test_reader_len( r: impl AsyncRead + Unpin + Send +'static, expected_len: usize, ) -> IoResult<()> { let mut r = SyncIoBridge::new(r); ...
() -> Result<(), Box<dyn Error>> { test_reader_len(tokio::io::empty(), 0).await?; let buf = b"hello world"; test_reader_len(Cursor::new(buf), buf.len()).await?; Ok(()) } #[tokio::test] async fn test_async_write_to_sync() -> Result<(), Box<dyn Error>> { let mut dest = Vec::new(); let src = b"hel...
test_async_read_to_sync
identifier_name
io_sync_bridge.rs
#![cfg(feature = "io-util")] use std::error::Error; use std::io::{Cursor, Read, Result as IoResult}; use tokio::io::AsyncRead; use tokio_util::io::SyncIoBridge; async fn test_reader_len( r: impl AsyncRead + Unpin + Send +'static, expected_len: usize, ) -> IoResult<()> { let mut r = SyncIoBridge::new(r); ...
test_reader_len(Cursor::new(buf), buf.len()).await?; Ok(()) } #[tokio::test] async fn test_async_write_to_sync() -> Result<(), Box<dyn Error>> { let mut dest = Vec::new(); let src = b"hello world"; let dest = tokio::task::spawn_blocking(move || -> Result<_, String> { let mut w = SyncIoBridg...
#[tokio::test] async fn test_async_read_to_sync() -> Result<(), Box<dyn Error>> { test_reader_len(tokio::io::empty(), 0).await?; let buf = b"hello world";
random_line_split
io_sync_bridge.rs
#![cfg(feature = "io-util")] use std::error::Error; use std::io::{Cursor, Read, Result as IoResult}; use tokio::io::AsyncRead; use tokio_util::io::SyncIoBridge; async fn test_reader_len( r: impl AsyncRead + Unpin + Send +'static, expected_len: usize, ) -> IoResult<()> { let mut r = SyncIoBridge::new(r); ...
#[tokio::test] async fn test_async_write_to_sync() -> Result<(), Box<dyn Error>> { let mut dest = Vec::new(); let src = b"hello world"; let dest = tokio::task::spawn_blocking(move || -> Result<_, String> { let mut w = SyncIoBridge::new(Cursor::new(&mut dest)); std::io::copy(&mut Cursor::ne...
{ test_reader_len(tokio::io::empty(), 0).await?; let buf = b"hello world"; test_reader_len(Cursor::new(buf), buf.len()).await?; Ok(()) }
identifier_body
timers.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::callback::ExceptionHandling::Report; use dom::bindings::cell::DOMRefCell; use dom::bindings::co...
pub fn suspend(&self) { assert!(self.suspended_since.get().is_none()); self.suspended_since.set(Some(precise_time_ms())); self.invalidate_expected_event_id(); } pub fn resume(&self) { assert!(self.suspended_since.get().is_some()); let additional_offset = match se...
{ if self.suspended_since.get().is_some() { // The timer will be scheduled when the pipeline is thawed. return; } let timers = self.timers.borrow(); if let Some(timer) = timers.last() { let expected_event_id = self.invalidate_expected_event_id(); ...
identifier_body
timers.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::callback::ExceptionHandling::Report; use dom::bindings::cell::DOMRefCell; use dom::bindings::co...
(timer_event_chan: IpcSender<TimerEvent>, scheduler_chan: IpcSender<TimerEventRequest>) -> ActiveTimers { ActiveTimers { timer_event_chan: timer_event_chan, scheduler_chan: scheduler_chan, next_timer_handle: Cell::new(TimerHandle(1)), ...
new
identifier_name
timers.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::callback::ExceptionHandling::Report; use dom::bindings::cell::DOMRefCell; use dom::bindings::co...
pub fn fire_timer<T: Reflectable>(&self, id: TimerEventId, this: &T) { let expected_id = self.expected_event_id.get(); if expected_id!= id { debug!("ignoring timer fire event {:?} (expected {:?}", id, expected_id); return; } assert!(self.suspended_since.get()...
random_line_split
list-all-function-runtimes.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region in...
let max_functions = functions.len(); let mut num_functions = 0; for function in functions { let rt_str: String = String::from(function.runtime().unwrap().as_ref()); // If language is set (!= ""), show only those with that runtime. let ok = rt_str .to_ascii_lowercase() ...
let resp = client.list_functions().send().await; let functions = resp.unwrap().functions.unwrap_or_default();
random_line_split
list-all-function-runtimes.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region in...
); println!(); } // Get list of available regions. let shared_config = aws_config::from_env().region(region_provider).load().await; let ec2_client = aws_sdk_ec2::Client::new(&shared_config); let resp = ec2_client.describe_regions().send().await; for region in resp.unwrap().re...
{ tracing_subscriber::fmt::init(); let Opt { language, region, verbose, } = Opt::from_args(); let region_provider = RegionProviderChain::first_try(region.map(Region::new)) .or_default_provider() .or_else(Region::new("us-west-2")); println!(); if verbose...
identifier_body
list-all-function-runtimes.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region in...
(verbose: bool, language: &str, reg: &'static str) { let region_provider = RegionProviderChain::default_provider().or_else(reg); let config = aws_config::from_env().region(region_provider).load().await; let client = Client::new(&config); let resp = client.list_functions().send().await; let function...
show_lambdas
identifier_name
list-all-function-runtimes.rs
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ use aws_config::meta::region::RegionProviderChain; use aws_sdk_lambda::{Client, Error, Region, PKG_VERSION}; use structopt::StructOpt; #[derive(Debug, StructOpt)] struct Opt { /// The AWS Region in...
} if num_functions > 0 || verbose { println!( "Found {} function(s) (out of {}) in {} region.", num_functions, max_functions, reg ); println!(); } } // snippet-end:[lambda.rust.list-all-function-runtimes] /// Lists the ARNs and runtimes of your Lambda funct...
{ println!(" ARN: {}", function.function_arn().unwrap()); println!(" Runtime: {}", rt_str); println!(); num_functions += 1; }
conditional_block
htmlfieldsetelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen:...
// https://html.spec.whatwg.org/multipage/#dom-cva-validity fn Validity(&self) -> Root<ValidityState> { let window = window_from_node(self); ValidityState::new(window.r()) } // https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled make_bool_getter!(Disabled, "disabled"); ...
{ #[derive(JSTraceable, HeapSizeOf)] struct ElementsFilter; impl CollectionFilter for ElementsFilter { fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool { static TAG_NAMES: StaticStringVec = &["button", "fieldset", "input", "keygen",...
identifier_body
htmlfieldsetelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen:...
(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &atom!("disabled") => ...
super_type
identifier_name
htmlfieldsetelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::attr::Attr; use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; use dom::bindings::codegen:...
NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLSelectElement)) | NodeTypeId::Element( ElementTypeId::HTMLElement( ...
NodeTypeId::Element( ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLInputElement)) |
random_line_split
line.rs
use super::prelude::*; use super::{BaseFloat, NumCast, Pnt2, Vec2}; #[derive(Copy, Clone, Debug)] pub struct Line2<T: BaseFloat> { pub origin: Pnt2<T>, pub displace: Vec2<T>, pub length: T, } impl<T: BaseFloat> Line2<T> { pub fn from_origin_and_displace(origin: Pnt2<T>, displace: Vec2<T>) -> Line2<T> ...
pub fn at_offset(&self, offset: T) -> Pnt2<T> { self.origin + self.displace * offset } }
{ self.intersect_offset(other) .map(|offset| self.at_offset(offset)) }
identifier_body
line.rs
use super::prelude::*; use super::{BaseFloat, NumCast, Pnt2, Vec2}; #[derive(Copy, Clone, Debug)] pub struct Line2<T: BaseFloat> { pub origin: Pnt2<T>, pub displace: Vec2<T>, pub length: T, } impl<T: BaseFloat> Line2<T> { pub fn from_origin_and_displace(origin: Pnt2<T>, displace: Vec2<T>) -> Line2<T> ...
(&self, other: &Line2<T>) -> Option<Pnt2<T>> { self.intersect_offset(other) .map(|offset| self.at_offset(offset)) } pub fn at_offset(&self, offset: T) -> Pnt2<T> { self.origin + self.displace * offset } }
intersect_point
identifier_name
line.rs
use super::prelude::*; use super::{BaseFloat, NumCast, Pnt2, Vec2}; #[derive(Copy, Clone, Debug)] pub struct Line2<T: BaseFloat> { pub origin: Pnt2<T>, pub displace: Vec2<T>, pub length: T, } impl<T: BaseFloat> Line2<T> { pub fn from_origin_and_displace(origin: Pnt2<T>, displace: Vec2<T>) -> Line2<T> ...
} } pub fn intersect_point(&self, other: &Line2<T>) -> Option<Pnt2<T>> { self.intersect_offset(other) .map(|offset| self.at_offset(offset)) } pub fn at_offset(&self, offset: T) -> Pnt2<T> { self.origin + self.displace * offset } }
} else { Some((other.origin - self.origin).perp_dot(other.displace) / denominator)
random_line_split
line.rs
use super::prelude::*; use super::{BaseFloat, NumCast, Pnt2, Vec2}; #[derive(Copy, Clone, Debug)] pub struct Line2<T: BaseFloat> { pub origin: Pnt2<T>, pub displace: Vec2<T>, pub length: T, } impl<T: BaseFloat> Line2<T> { pub fn from_origin_and_displace(origin: Pnt2<T>, displace: Vec2<T>) -> Line2<T> ...
else { (point.y - self.origin.y) / self.displace.y } } pub fn intersect_offset(&self, other: &Line2<T>) -> Option<T> { let denominator = self.displace.perp_dot(other.displace); if denominator.abs() < <T as NumCast>::from(1e-16).unwrap() { None } else { ...
{ (point.x - self.origin.x) / self.displace.x }
conditional_block
struct-in-struct.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
}; zzz(); } fn zzz() {()}
}
random_line_split
struct-in-struct.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ x: InternalPadding, y: InternalPadding, z: InternalPadding } struct PaddingAtEndParent { x: PaddingAtEnd, y: PaddingAtEnd, z: PaddingAtEnd } struct Mixed { x: PaddingAtEnd, y: InternalPadding, z: Simple, w: i16 } struct Bag { x: Simple } struct BagInBag { x: Bag } ...
InternalPaddingParent
identifier_name
slice-mut-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x: &[isize] = &[1, 2, 3, 4, 5]; // Can't mutably slice an immutable slice let slice: &mut [isize] = &mut [0, 1]; let _ = &mut x[2..4]; //~ERROR cannot borrow immutable borrowed content `*x` as mutable }
main
identifier_name
slice-mut-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x: &[isize] = &[1, 2, 3, 4, 5]; // Can't mutably slice an immutable slice let slice: &mut [isize] = &mut [0, 1]; let _ = &mut x[2..4]; //~ERROR cannot borrow immutable borrowed content `*x` as mutable }
identifier_body
slice-mut-2.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test mutability and slicing syntax. fn main() { let x: &[isize] = &[1, 2, 3, 4, 5]; // Can't mutably slice an immutable slice let slice: &...
// 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
random_line_split
authorization.rs
use std::any::Any; use std::fmt::{self, Display}; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// `Authorization` header, defined in [RFC7235](https://tools.ietf.org/html/rfc7235#secti...
None } fn fmt_scheme(&self, f: &mut fmt::Formatter) -> fmt::Result { Display::fmt(self, f) } } /// Credential holder for Basic Authentication #[derive(Clone, PartialEq, Debug)] pub struct Basic { /// The username as a possibly empty string pub username: String, /// The password...
fn scheme() -> Option<&'static str> {
random_line_split
authorization.rs
use std::any::Any; use std::fmt::{self, Display}; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// `Authorization` header, defined in [RFC7235](https://tools.ietf.org/html/rfc7235#secti...
#[test] fn test_basic_auth_parse() { let auth: Authorization<Basic> = Header::parse_header( &[b"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==".to_vec()]).unwrap(); assert_eq!(auth.0.username, "Aladdin"); assert_eq!(auth.0.password, Some("open sesame".to_owned())); } #[test] ...
{ let mut headers = Headers::new(); headers.set(Authorization(Basic { username: "Aladdin".to_owned(), password: None })); assert_eq!(headers.to_string(), "Authorization: Basic QWxhZGRpbjo=\r\n".to_owned()); }
identifier_body
authorization.rs
use std::any::Any; use std::fmt::{self, Display}; use std::str::{FromStr, from_utf8}; use std::ops::{Deref, DerefMut}; use serialize::base64::{ToBase64, FromBase64, Standard, Config, Newline}; use header::{Header, HeaderFormat}; /// `Authorization` header, defined in [RFC7235](https://tools.ietf.org/html/rfc7235#secti...
<S: Scheme>(pub S); impl<S: Scheme> Deref for Authorization<S> { type Target = S; fn deref<'a>(&'a self) -> &'a S { &self.0 } } impl<S: Scheme> DerefMut for Authorization<S> { fn deref_mut<'a>(&'a mut self) -> &'a mut S { &mut self.0 } } impl<S: Scheme + Any> Header for Authoriza...
Authorization
identifier_name
mod.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use std::collections::HashSet; use crate::{ err::Result, notes::{Note, NoteID}, notetype::NoteTypeID, tags::{join_tags, split_tags}, timestamp::TimestampMillis, }; use r...
pub(crate) fn for_each_note_tags<F>(&self, mut func: F) -> Result<()> where F: FnMut(NoteID, String) -> Result<()>, { let mut stmt = self.db.prepare_cached("select id, tags from notes")?; let mut rows = stmt.query(NO_PARAMS)?; while let Some(row) = rows.next()? { ...
{ let mut stmt = self .db .prepare_cached("select tags from notes where tags != ''")?; let mut query = stmt.query(NO_PARAMS)?; let mut seen: HashSet<String> = HashSet::new(); while let Some(rows) = query.next()? { for tag in split_tags(rows.get_raw(0)....
identifier_body
mod.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use std::collections::HashSet; use crate::{ err::Result, notes::{Note, NoteID}, notetype::NoteTypeID, tags::{join_tags, split_tags}, timestamp::TimestampMillis, }; use r...
(row: &Row) -> Result<Note> { Ok(Note { id: row.get(0)?, guid: row.get(1)?, notetype_id: row.get(2)?, mtime: row.get(3)?, usn: row.get(4)?, tags: split_tags(row.get_raw(5).as_str()?) .map(Into::into) .collect(), fields: split_fields(row.g...
row_to_note
identifier_name
mod.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use std::collections::HashSet; use crate::{ err::Result, notes::{Note, NoteID}, notetype::NoteTypeID, tags::{join_tags, split_tags}, timestamp::TimestampMillis, }; use r...
} } Ok(seen) } pub(crate) fn for_each_note_tags<F>(&self, mut func: F) -> Result<()> where F: FnMut(NoteID, String) -> Result<()>, { let mut stmt = self.db.prepare_cached("select id, tags from notes")?; let mut rows = stmt.query(NO_PARAMS)?; ...
{ seen.insert(tag.to_string()); }
conditional_block
mod.rs
// Copyright: Ankitects Pty Ltd and contributors // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html use std::collections::HashSet; use crate::{ err::Result, notes::{Note, NoteID}, notetype::NoteTypeID, tags::{join_tags, split_tags}, timestamp::TimestampMillis, }; use r...
.prepare("select count() from notes")? .query_row(NO_PARAMS, |r| r.get(0)) .map_err(Into::into) } pub(crate) fn all_tags_in_notes(&self) -> Result<HashSet<String>> { let mut stmt = self .db .prepare_cached("select tags from notes where tags!= ''")?...
self.db
random_line_split
lib.rs
#[macro_use] extern crate serde_derive; #[macro_use] extern crate log; #[macro_use] extern crate diesel; #[macro_use] extern crate diesel_codegen; #[macro_use] extern crate serde_json; #[macro_export] macro_rules! get_pg_connection { ($db_context:expr) => (&*$db_context.postgres_connection_pool.get().expect("Faile...
pub fn start() { env_logger::init().unwrap(); info!("starting spotlease..."); let api = api::ApiHandler::new(); Iron::new(api).http(("0.0.0.0", get_server_port())).unwrap(); }
{ let port_str = env::var("PORT").unwrap_or(String::new()); port_str.parse().unwrap_or(8080) }
identifier_body
lib.rs
#[macro_use] extern crate serde_derive; #[macro_use] extern crate log; #[macro_use] extern crate diesel; #[macro_use] extern crate diesel_codegen; #[macro_use] extern crate serde_json; #[macro_export] macro_rules! get_pg_connection { ($db_context:expr) => (&*$db_context.postgres_connection_pool.get().expect("Faile...
() -> u16 { let port_str = env::var("PORT").unwrap_or(String::new()); port_str.parse().unwrap_or(8080) } pub fn start() { env_logger::init().unwrap(); info!("starting spotlease..."); let api = api::ApiHandler::new(); Iron::new(api).http(("0.0.0.0", get_server_port())).unwrap(); }
get_server_port
identifier_name
lib.rs
#[macro_use] extern crate serde_derive; #[macro_use] extern crate log; #[macro_use] extern crate diesel; #[macro_use] extern crate diesel_codegen; #[macro_use] extern crate serde_json;
#[macro_export] macro_rules! get_pg_connection { ($db_context:expr) => (&*$db_context.postgres_connection_pool.get().expect("Failed to get connection from postgres pool")); } extern crate iron; extern crate bodyparser; extern crate serde_cbor; extern crate base64; extern crate crypto; extern crate unicase; extern...
random_line_split
menu.rs
use std::default::Default; use util; use util::rect::Rect; use super::common::Canceled; use super::input::Input; use super::widget::Widget; use super::view::HexEditActions; use super::super::frontend::{Frontend, Style, KeyPress}; pub enum MenuActions { Key(char), Back, Cancel, ToggleHelp, } pub enum...
self.on_selected.signal(command); return true; } &MenuEntry::SubEntries(key, _, _) if key == c => { self.menu_stack.push(&entry); return true; } _ => () } }...
match entry { &MenuEntry::CommandEntry(key, _, command) if key == c => {
random_line_split
menu.rs
use std::default::Default; use util; use util::rect::Rect; use super::common::Canceled; use super::input::Input; use super::widget::Widget; use super::view::HexEditActions; use super::super::frontend::{Frontend, Style, KeyPress}; pub enum MenuActions { Key(char), Back, Cancel, ToggleHelp, } pub enum...
fn menu_act_key(&mut self, c: char) -> bool { for entry in self.current_menu().iter() { match entry { &MenuEntry::CommandEntry(key, _, command) if key == c => { self.on_selected.signal(command); return true; } ...
{ OverlayMenu { root_menu: root_menu, menu_stack: vec![], show_help: false, on_cancel: Default::default(), on_selected: Default::default(), } }
identifier_body
menu.rs
use std::default::Default; use util; use util::rect::Rect; use super::common::Canceled; use super::input::Input; use super::widget::Widget; use super::view::HexEditActions; use super::super::frontend::{Frontend, Style, KeyPress}; pub enum MenuActions { Key(char), Back, Cancel, ToggleHelp, } pub enum...
(&mut self, rb: &Frontend, x: isize, y: isize) { let mut x_pos = 0; rb.print_style((x + x_pos) as usize, y as usize, Style::MenuTitle, " > "); x_pos += 3; for location_entry in self.menu_stack.iter() { let name = match **location_entry { MenuEntry::SubEntries(...
draw_menu_location
identifier_name
item_state.rs
use pango::{self, LayoutExt, Layout}; use cairo_sys; use pangocairo::CairoContextExt; use bar_properties::BarProperties; use xcb::{self, Window, Screen, Visualtype, Pixmap, Connection}; use cairo::{Context, Surface}; use std::rc::Rc; use error::Result; pub struct ItemState { bar_props: Rc<BarProperties>, conn:...
} pub fn update(&mut self, update: String) -> Result<()> { if update!= self.state { self.state = update; self.update_size()?; self.paint()?; } Ok(()) } pub fn paint(&mut self) -> Result<()> { self.update_surface()?; let surfac...
self.content_width = layout.get_pixel_size().0 as u16; Ok(())
random_line_split
item_state.rs
use pango::{self, LayoutExt, Layout}; use cairo_sys; use pangocairo::CairoContextExt; use bar_properties::BarProperties; use xcb::{self, Window, Screen, Visualtype, Pixmap, Connection}; use cairo::{Context, Surface}; use std::rc::Rc; use error::Result; pub struct ItemState { bar_props: Rc<BarProperties>, conn:...
pub fn paint(&mut self) -> Result<()> { self.update_surface()?; let surface = match self.surface { Some(ref surface) => surface, None => return Err("no surface".into()), }; let ctx = Context::new(&surface); let layout = self.create_layout(&ctx); ...
{ if update != self.state { self.state = update; self.update_size()?; self.paint()?; } Ok(()) }
identifier_body
item_state.rs
use pango::{self, LayoutExt, Layout}; use cairo_sys; use pangocairo::CairoContextExt; use bar_properties::BarProperties; use xcb::{self, Window, Screen, Visualtype, Pixmap, Connection}; use cairo::{Context, Surface}; use std::rc::Rc; use error::Result; pub struct ItemState { bar_props: Rc<BarProperties>, conn:...
(&self) -> Screen { let setup = self.conn.get_setup(); setup.roots().nth(self.screen_number).unwrap() } fn update_surface(&mut self) -> Result<()> { let width = self.content_width; if width > self.surface_width || width < (self.surface_width / 10) * 6 || self.surfac...
get_screen
identifier_name
mod.rs
/* Periodically crawl web pages and alert the user of changes * Copyright (C) 2016 Owen Stenson * * 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 ...
*/ /* mod.rs * This file will eventually house framework to tie in functionality for * Calendar and Action and maybe Schedule. It shouldn't be hefty. */ pub mod value_itr; pub mod calendar;
* It should probably have a test suite anyway, though smaller than what * (2) would require (and WAY smaller than what (1) would require).
random_line_split
main.rs
#[macro_use] extern crate lazy_static; extern crate termc_model; extern crate termc_ui; extern crate serde_json; extern crate regex; mod command_library; use std::env; use std::path::Path; use termc_model::get_result; use termc_model::math_context::MathContext; use termc_model::math_result::MathResult; use termc_ui::...
(exe_path: &str) -> String { let default_fd = Path::new(exe_path).parent().unwrap(); // remove termc executable name let default_fn = Path::new("termc_context.json"); // define default file name default_fd.join(default_fn).to_str().unwrap().to_string() // join current path and default file name } /// Start...
build_default_ser_path
identifier_name
main.rs
#[macro_use] extern crate lazy_static; extern crate termc_model; extern crate termc_ui; extern crate serde_json; extern crate regex; mod command_library; use std::env; use std::path::Path; use termc_model::get_result; use termc_model::math_context::MathContext; use termc_model::math_result::MathResult; use termc_ui::...
_ => () } }, None => { match get_result(arg.trim(), & mut context) { Ok(result) => { match result { Some(y)...
Ok(k) => { match k { Some(command_type) => { match command_type { CommandType::Exit => break,
random_line_split
main.rs
#[macro_use] extern crate lazy_static; extern crate termc_model; extern crate termc_ui; extern crate serde_json; extern crate regex; mod command_library; use std::env; use std::path::Path; use termc_model::get_result; use termc_model::math_context::MathContext; use termc_model::math_result::MathResult; use termc_ui::...
/// Starts termc in command line call mode. /// Prints a ';'-separated list with the results of the specified mathematical expressions. fn start_call(args: & mut Vec<String>) { // compute default file-path for the serialization file let mut iter = args.iter(); let path_str : String = iter.next().unwrap()...
{ let default_fd = Path::new(exe_path).parent().unwrap(); // remove termc executable name let default_fn = Path::new("termc_context.json"); // define default file name default_fd.join(default_fn).to_str().unwrap().to_string() // join current path and default file name }
identifier_body
settings.rs
extern crate serde; extern crate serde_json; include!(concat!(env!("OUT_DIR"), "\\serde_types.rs")); use std::io::prelude::*; use std::fs::File; use std::process::exit; pub trait Settings { fn get_socket_port(&self) -> u16; } pub struct SettingsImpl { pub settings_file_path:String, pub settings_data: Se...
(&mut self) { let mut file: File = match File::open(&self.settings_file_path) { Err(e) => { println!("Error: {0}. couldn't find file at location: {1}", e, self.settings_file_path); exit(1); // TODO: should probably return false, and then have process exit with one on ...
init
identifier_name
settings.rs
extern crate serde; extern crate serde_json; include!(concat!(env!("OUT_DIR"), "\\serde_types.rs")); use std::io::prelude::*; use std::fs::File; use std::process::exit; pub trait Settings { fn get_socket_port(&self) -> u16; } pub struct SettingsImpl { pub settings_file_path:String, pub settings_data: Se...
self.settings_data = loaded_settings_data; } } impl Settings for SettingsImpl { fn get_socket_port(&self) -> u16 { return self.settings_data.socket_port; } }
println!("Error {0}, problem serializing into SettingsData from:\n{1}", e, json_string); return; }, Ok(s) => s, };
random_line_split
font_chooser_dialog.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use FFIWidget; use cast::{GTK_WINDOW}; use glib::translate::ToGlibPtr; struct_Widge...
} impl_drop!(FontChooserDialog); impl_TraitWidget!(FontChooserDialog); impl ::ContainerTrait for FontChooserDialog {} impl ::BinTrait for FontChooserDialog {} impl ::WindowTrait for FontChooserDialog {} impl ::DialogTrait for FontChooserDialog {} impl ::FontChooserTrait for FontChooserDialog {}
{ let tmp = unsafe { ffi::gtk_font_chooser_dialog_new(title.to_glib_none().0, match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => GTK_WINDOW(::std::ptr::null_mut()) } ) }; if tmp.is_...
identifier_body
font_chooser_dialog.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use ffi; use FFIWidget; use cast::{GTK_WINDOW}; use glib::translate::ToGlibPtr; struct_Widge...
(title: &str, parent: Option<&::Window>) -> Option<FontChooserDialog> { let tmp = unsafe { ffi::gtk_font_chooser_dialog_new(title.to_glib_none().0, match parent { Some(ref p) => GTK_WINDOW(p.unwrap_widget()), None => GTK_WINDOW(::std::ptr::null...
new
identifier_name