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
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 lat...
() { // given let mem: &mut Memory = &mut vec![]; mem.resize(32); // when mem.write_byte(U256::from(0x1d), U256::from(0xab)); mem.write_byte(U256::from(0x1e), U256::from(0xcd)); mem.write_byte(U256::from(0x1f), U256::from(0xef)); // then assert_eq!(mem.read(U256::from(0x00)), U256::from(0xabcdef)); }
test_memory_read_and_write_byte
identifier_name
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 lat...
// GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use util::{U256, Uint}; pub trait Memory { /// Retrieve current size of the memory fn size(&self) -> usize; /// Resize (shrink or ...
random_line_split
match-in-macro.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() { assert_eq!(match_inside_expansion!(),129);
random_line_split
match-in-macro.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 ...
{ B { b1: int, bb1: int}, } macro_rules! match_inside_expansion( () => ( match B { b1:29, bb1: 100} { B { b1:b2, bb1:bb2 } => b2+bb2 } ) ) pub fn main() { assert_eq!(match_inside_expansion!(),129); }
Foo
identifier_name
match-in-macro.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 ...
{ assert_eq!(match_inside_expansion!(),129); }
identifier_body
deb.rs
use std::process::Command; use datatype::{Error, Package, UpdateResultCode}; use package_manager::package_manager::{InstallOutcome, parse_package}; /// Returns a list of installed DEB packages with /// `dpkg-query -f='${Package} ${Version}\n' -W`. pub fn installed_packages() -> Result<Vec<Package>, Error> { Comm...
} }
{ let output = try!(Command::new("dpkg").arg("-E").arg("-i").arg(path) .output() .map_err(|e| (UpdateResultCode::GENERAL_ERROR, format!("{:?}", e)))); let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); let stderr = String::from_utf8_lossy(&output.stderr).into_owned(); m...
identifier_body
deb.rs
use std::process::Command; use datatype::{Error, Package, UpdateResultCode}; use package_manager::package_manager::{InstallOutcome, parse_package}; /// Returns a list of installed DEB packages with /// `dpkg-query -f='${Package} ${Version}\n' -W`. pub fn installed_packages() -> Result<Vec<Package>, Error> { Comm...
Ok((UpdateResultCode::ALREADY_PROCESSED, stdout)) } else { Ok((UpdateResultCode::OK, stdout)) } } _ => { let out = format!("stdout: {}\nstderr: {}", stdout, stderr); Err((UpdateResultCode::INSTALL_FAILED, out)) } ...
match output.status.code() { Some(0) => { if (&stdout).contains("already installed") {
random_line_split
deb.rs
use std::process::Command; use datatype::{Error, Package, UpdateResultCode}; use package_manager::package_manager::{InstallOutcome, parse_package}; /// Returns a list of installed DEB packages with /// `dpkg-query -f='${Package} ${Version}\n' -W`. pub fn installed_packages() -> Result<Vec<Package>, Error> { Comm...
_ => { let out = format!("stdout: {}\nstderr: {}", stdout, stderr); Err((UpdateResultCode::INSTALL_FAILED, out)) } } }
{ if (&stdout).contains("already installed") { Ok((UpdateResultCode::ALREADY_PROCESSED, stdout)) } else { Ok((UpdateResultCode::OK, stdout)) } }
conditional_block
deb.rs
use std::process::Command; use datatype::{Error, Package, UpdateResultCode}; use package_manager::package_manager::{InstallOutcome, parse_package}; /// Returns a list of installed DEB packages with /// `dpkg-query -f='${Package} ${Version}\n' -W`. pub fn
() -> Result<Vec<Package>, Error> { Command::new("dpkg-query").arg("-f='${Package} ${Version}\n'").arg("-W") .output() .map_err(|e| Error::Package(format!("Error fetching packages: {}", e))) .and_then(|c| { String::from_utf8(c.stdout) .map_err(|e| Error::Parse(format!...
installed_packages
identifier_name
variable3x5x8.rs
pub fn bits_used_for_label(label: u64) -> u8 { if label & 0b1!= 0 { 3 + 1 } else if label & 0b10!= 0 { 5 + 2 } else { 8 + 2 } } pub fn bits_used_for_number(number: u32) -> u8 { match number { n if n < 8 => 3 + 1, n if n < 33 => 5 + 2, _ => 8 + 2 } } pub fn compress(number: u32) -> u64 { ...
(label: u64) -> u32 { match bits_used_for_label(label) { 4 => { match (label >> 1) & 0b111 { 0b000 => 1, 0b001 => 0, n => n as u32 } }, 7 => { match (label >> 2) & 0b1_1111 { 0b0_0000 => 0, n => (n + 1) as u32 } }, 10 => { match (label >> 2) & 0b1111_1111 { 0...
decompress
identifier_name
variable3x5x8.rs
pub fn bits_used_for_label(label: u64) -> u8 { if label & 0b1!= 0 { 3 + 1 } else if label & 0b10!= 0 { 5 + 2 } else { 8 + 2 } } pub fn bits_used_for_number(number: u32) -> u8 { match number { n if n < 8 => 3 + 1, n if n < 33 => 5 + 2, _ => 8 + 2 } } pub fn compress(number: u32) -> u64 { ...
}, _ => unreachable!() } } #[cfg(test)] mod tests { use super::*; #[test] fn test_compress_decompress() { for i in range(0, 257) { assert_eq!(i, decompress(compress(i))) } } }
0b0000_0000 => 0, n => (n + 1) as u32 }
random_line_split
variable3x5x8.rs
pub fn bits_used_for_label(label: u64) -> u8 { if label & 0b1!= 0 { 3 + 1 } else if label & 0b10!= 0 { 5 + 2 } else { 8 + 2 } } pub fn bits_used_for_number(number: u32) -> u8
pub fn compress(number: u32) -> u64 { if number == 1 { return 1; } match bits_used_for_number(number) { 4 => { match number { 0 => 0b0011, n => ((n << 1) | 0b1) as u64 } }, 7 => { match number { 0 => 0b000_0010, n => (((n - 1) << 2) | 0b10) as u64 } }, 10 => { match numb...
{ match number { n if n < 8 => 3 + 1, n if n < 33 => 5 + 2, _ => 8 + 2 } }
identifier_body
timer.rs
use super::RW; use super::thread::Handler; use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl}; use mio_orig::{self, EventLoop, Token, EventSet}; use std::time::{Instant, Duration}; /// A Timer generating event after a given time /// /// Use `MiocoHandle::select()` to wait for an event, or `rea...
fn should_resume(&self) -> bool { trace!("Timer: should_resume? {}", self.timeout <= Instant::now()); self.timeout <= Instant::now() } } impl EventSourceTrait for TimerCore { fn register(&mut self, event_loop: &mut EventLoop<Handler>, token: To...
self.rc.io_ref().timeout } } impl TimerCore {
random_line_split
timer.rs
use super::RW; use super::thread::Handler; use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl}; use mio_orig::{self, EventLoop, Token, EventSet}; use std::time::{Instant, Duration}; /// A Timer generating event after a given time /// /// Use `MiocoHandle::select()` to wait for an event, or `rea...
} impl EventedImpl for Timer { type Raw = TimerCore; fn shared(&self) -> &RcEventSource<TimerCore> { &self.rc } } impl Timer { /// Read a timer to block on it until it is done. /// /// Returns current time /// /// TODO: Return wakeup time instead pub fn read(&mut self) ->...
{ Timer::new() }
identifier_body
timer.rs
use super::RW; use super::thread::Handler; use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl}; use mio_orig::{self, EventLoop, Token, EventSet}; use std::time::{Instant, Duration}; /// A Timer generating event after a given time /// /// Use `MiocoHandle::select()` to wait for an event, or `rea...
} false } fn reregister(&mut self, event_loop: &mut EventLoop<Handler>, token: Token, interest: EventSet) -> bool { if let Some(timeout) = self.mio_timeout { event_loop.clear_timeout(timeout); } self.regi...
{ panic!("Could not create mio::Timeout: {:?}", reason); }
conditional_block
timer.rs
use super::RW; use super::thread::Handler; use super::evented::{EventSourceTrait, RcEventSource, Evented, EventedImpl}; use mio_orig::{self, EventLoop, Token, EventSet}; use std::time::{Instant, Duration}; /// A Timer generating event after a given time /// /// Use `MiocoHandle::select()` to wait for an event, or `rea...
(&mut self, event_loop: &mut EventLoop<Handler>, _token: Token) { if let Some(timeout) = self.mio_timeout { event_loop.clear_timeout(timeout); } } } unsafe impl Send for Timer {}
deregister
identifier_name
sched.rs
/* Precached - A Linux process monitor and pre-caching daemon Copyright (C) 2017-2020 the precached developers This file is part of precached. Precached 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 Softwar...
/// Lock the calling thread to CPU `cpu_index` pub fn set_cpu_affinity(cpu_index: usize) -> Result<(), nix::Error> { let pid = nix::unistd::Pid::from_raw(0); let mut cpuset = nix::sched::CpuSet::new(); cpuset.set(cpu_index)?; nix::sched::sched_setaffinity(pid, &cpuset)?; Ok(()) }
random_line_split
sched.rs
/* Precached - A Linux process monitor and pre-caching daemon Copyright (C) 2017-2020 the precached developers This file is part of precached. Precached 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 Softwar...
{ let pid = nix::unistd::Pid::from_raw(0); let mut cpuset = nix::sched::CpuSet::new(); cpuset.set(cpu_index)?; nix::sched::sched_setaffinity(pid, &cpuset)?; Ok(()) }
identifier_body
sched.rs
/* Precached - A Linux process monitor and pre-caching daemon Copyright (C) 2017-2020 the precached developers This file is part of precached. Precached 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 Softwar...
(cpu_index: usize) -> Result<(), nix::Error> { let pid = nix::unistd::Pid::from_raw(0); let mut cpuset = nix::sched::CpuSet::new(); cpuset.set(cpu_index)?; nix::sched::sched_setaffinity(pid, &cpuset)?; Ok(()) }
set_cpu_affinity
identifier_name
multiwindow.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use std::thread::Thread; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main() { println!("This example requires glutin to be compiled with the `window` feature"); } #[cf...
context.draw_frame(color); window.swap_buffers(); window.wait_events().next(); } }
unsafe { window.make_current() }; let context = support::load(&window); while !window.is_closed() {
random_line_split
multiwindow.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use std::thread::Thread; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main() { println!("This example requires glutin to be compiled with the `window` feature"); } #[cf...
} #[cfg(feature = "window")] fn run(window: glutin::Window, color: (f32, f32, f32, f32)) { unsafe { window.make_current() }; let context = support::load(&window); while!window.is_closed() { context.draw_frame(color); window.swap_buffers(); window.wait_events().next(); } }
{ let window1 = glutin::Window::new().unwrap(); let window2 = glutin::Window::new().unwrap(); let window3 = glutin::Window::new().unwrap(); let t1 = Thread::scoped(move || { run(window1, (0.0, 1.0, 0.0, 1.0)); }); let t2 = Thread::scoped(move || { run(window2, (0.0, 0.0, 1.0, 1...
identifier_body
multiwindow.rs
#[cfg(target_os = "android")] #[macro_use] extern crate android_glue; extern crate glutin; use std::thread::Thread; mod support; #[cfg(target_os = "android")] android_start!(main); #[cfg(not(feature = "window"))] fn main() { println!("This example requires glutin to be compiled with the `window` feature"); } #[cf...
(window: glutin::Window, color: (f32, f32, f32, f32)) { unsafe { window.make_current() }; let context = support::load(&window); while!window.is_closed() { context.draw_frame(color); window.swap_buffers(); window.wait_events().next(); } }
run
identifier_name
les_request.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity.
// it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTA...
// Parity is free software: you can redistribute it and/or modify
random_line_split
les_request.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 la...
{ /// Requesting headers. Headers, /// Requesting block bodies. Bodies, /// Requesting transaction receipts. Receipts, /// Requesting proofs of state trie nodes. StateProofs, /// Requesting contract code by hash. Codes, /// Requesting header proofs (from the CHT). HeaderProofs, } /// Encompasses all possi...
Kind
identifier_name
untrusted_rlp.rs
// Copyright 2015-2017 Parity Technologies // // 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 ...
{ pub fn new(bytes: &'a [u8]) -> UntrustedRlp<'a> { UntrustedRlp { bytes: bytes, offset_cache: Cell::new(OffsetCache::new(usize::max_value(), 0)), count_cache: Cell::new(None), } } pub fn as_raw(&'view self) -> &'a [u8] { self.bytes } pub...
random_line_split
untrusted_rlp.rs
// Copyright 2015-2017 Parity Technologies // // 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 ...
(bytes: &[u8]) -> Result<PayloadInfo, DecoderError> { let item = PayloadInfo::from(bytes)?; match item.header_len.checked_add(item.value_len) { Some(x) if x <= bytes.len() => Ok(item), _ => Err(DecoderError::RlpIsTooShort), } } pub fn decode_value<T, F>(&self, f:...
payload_info
identifier_name
http.rs
use hyper::{Client, Error}; use hyper::client::Response; use hyper::header::ContentType; use hyper::method::Method; /// Makes a DELETE request to etcd. pub fn delete(url: String) -> Result<Response, Error> { request(Method::Delete, url) } /// Makes a GET request to etcd. pub fn
(url: String) -> Result<Response, Error> { request(Method::Get, url) } /// Makes a POST request to etcd. pub fn post(url: String, body: String) -> Result<Response, Error> { request_with_body(Method::Post, url, body) } /// Makes a PUT request to etcd. pub fn put(url: String, body: String) -> Result<Response, E...
get
identifier_name
http.rs
use hyper::{Client, Error}; use hyper::client::Response; use hyper::header::ContentType; use hyper::method::Method; /// Makes a DELETE request to etcd. pub fn delete(url: String) -> Result<Response, Error>
/// Makes a GET request to etcd. pub fn get(url: String) -> Result<Response, Error> { request(Method::Get, url) } /// Makes a POST request to etcd. pub fn post(url: String, body: String) -> Result<Response, Error> { request_with_body(Method::Post, url, body) } /// Makes a PUT request to etcd. pub fn put(url...
{ request(Method::Delete, url) }
identifier_body
http.rs
use hyper::{Client, Error}; use hyper::client::Response; use hyper::header::ContentType; use hyper::method::Method; /// Makes a DELETE request to etcd. pub fn delete(url: String) -> Result<Response, Error> { request(Method::Delete, url) } /// Makes a GET request to etcd. pub fn get(url: String) -> Result<Response...
/// Makes a PUT request to etcd. pub fn put(url: String, body: String) -> Result<Response, Error> { request_with_body(Method::Put, url, body) } // private /// Makes a request to etcd. fn request(method: Method, url: String) -> Result<Response, Error> { let client = Client::new(); let request = client.requ...
random_line_split
include.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
{ counter: i32, } // The messages that can be sent to the update function. #[derive(Msg)] pub enum Msg { Decrement, Increment, Quit, } #[widget] impl Widget for Win { // The initial model. fn model() -> Model { Model { counter: 0, } } // Update the model a...
Model
identifier_name
include.rs
/* * Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, ...
#[cfg(test)] mod tests { use gtk::prelude::{ButtonExt, LabelExt}; use gtk_test::{assert_label, assert_text}; use relm_test::click; use crate::Win; #[test] fn label_change() { let (_component, _, widgets) = relm::init_test::<Win>(()).expect("init_test failed"); let inc_button...
{ Win::run(()).expect("Win::run failed"); }
identifier_body
include.rs
/*
* * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell...
* Copyright (c) 2017-2020 Boucher, Antoni <bouanto@zoho.com>
random_line_split
main.rs
extern crate gtk; pub mod stack; pub mod calc; // use gdk::prelude::*; use gtk::prelude::*; use gtk::{Builder, Button, Window, TextView, TextBuffer}; fn map_number_btns(text_view: &TextView, nums_vec: &Vec<Button>) { let mut idx = 0; for num in nums_vec { let tv = text_view.clone(); num.con...
// let btn: Button = builder.get_object("btn1").unwrap(); // let image: Image = builder.get_object("image1").unwrap(); window.connect_delete_event(|_, _| { gtk::main_quit(); Inhibit(false) }); //Clear output view on input view changed let tv = text_view.clone(); let tv_ou...
let btn_par_left: Button = builder.get_object("btn_par_left").unwrap(); let btn_par_right: Button = builder.get_object("btn_par_right").unwrap();
random_line_split
main.rs
extern crate gtk; pub mod stack; pub mod calc; // use gdk::prelude::*; use gtk::prelude::*; use gtk::{Builder, Button, Window, TextView, TextBuffer}; fn map_number_btns(text_view: &TextView, nums_vec: &Vec<Button>) { let mut idx = 0; for num in nums_vec { let tv = text_view.clone(); num.con...
(text_view: &TextView, btn: &Button, txt: &str) { let tv = text_view.clone(); let txt_cpy: String = (*txt).to_string(); btn.connect_clicked(move |_| { let buf = tv.get_buffer().unwrap(); buf.insert_at_cursor(&txt_cpy); }); } fn calc_and_set_result(in_buf: &TextBuffer, out_buf: &TextBuf...
map_btn_insert_at_cursor
identifier_name
main.rs
extern crate gtk; pub mod stack; pub mod calc; // use gdk::prelude::*; use gtk::prelude::*; use gtk::{Builder, Button, Window, TextView, TextBuffer}; fn map_number_btns(text_view: &TextView, nums_vec: &Vec<Button>) { let mut idx = 0; for num in nums_vec { let tv = text_view.clone(); num.con...
let glade_src = include_str!("calc_win.glade"); let builder = Builder::new_from_string(glade_src); let window: Window = builder.get_object("calc_app_win").unwrap(); let text_view: TextView = builder.get_object("input_view").unwrap(); let output_view: TextView = builder.get_object("output_view")...
{ println!("Failed to initialize GTK."); return; }
conditional_block
main.rs
extern crate gtk; pub mod stack; pub mod calc; // use gdk::prelude::*; use gtk::prelude::*; use gtk::{Builder, Button, Window, TextView, TextBuffer}; fn map_number_btns(text_view: &TextView, nums_vec: &Vec<Button>) { let mut idx = 0; for num in nums_vec { let tv = text_view.clone(); num.con...
builder.get_object("btn_4").unwrap(), builder.get_object("btn_5").unwrap(), builder.get_object("btn_6").unwrap(), builder.get_object("btn_7").unwrap(), ...
{ if gtk::init().is_err() { println!("Failed to initialize GTK."); return; } let glade_src = include_str!("calc_win.glade"); let builder = Builder::new_from_string(glade_src); let window: Window = builder.get_object("calc_app_win").unwrap(); let text_view: TextView = builder....
identifier_body
build.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 lat...
{ gcc::compile_library("libtinykeccak.a", &["src/tinykeccak.c"]); }
identifier_body
build.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 lat...
() { gcc::compile_library("libtinykeccak.a", &["src/tinykeccak.c"]); }
main
identifier_name
build.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 lat...
fn main() { gcc::compile_library("libtinykeccak.a", &["src/tinykeccak.c"]); }
// Bring in a dependency on an externally maintained `gcc` package which manages // invoking the C compiler. extern crate gcc;
random_line_split
music.rs
//! This module provides the music struct, which allows to play and control a music from a file. use libc; use mpv; use std::rc::Rc; use std::cell::RefCell; /// The music struct. pub struct Music { /// Indicates wether the music is playing, paused or stopped. status: MusicStatus, /// The mpv handler to...
/// /// Tells MPV to set the pause property to true, and to reset the playback-time. pub fn stop(&mut self) { self.status = MusicStatus::Stopped; let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("playback-time", 0); let _ = self.mpv.as_ref().unwrap().borrow_mut().set_prop...
let _ = self.mpv.as_ref().unwrap().borrow_mut().set_property("pause", false); } /// Stops the current music.
random_line_split
music.rs
//! This module provides the music struct, which allows to play and control a music from a file. use libc; use mpv; use std::rc::Rc; use std::cell::RefCell; /// The music struct. pub struct Music { /// Indicates wether the music is playing, paused or stopped. status: MusicStatus, /// The mpv handler to...
if ended { self.stop(); } ended } } #[derive(Copy, Clone)] /// The different possible music statuses. pub enum MusicStatus { Stopped, Playing, Paused } impl MusicStatus { /// Returns a UTF-8 icon representing the music status. pub fn get_icon(&self) -> St...
{ let mut ended = false; if ! self.mpv.is_none() { let mpv = self.mpv.as_mut().unwrap(); loop { match mpv.borrow_mut().wait_event(0.0) { Some(mpv::Event::EndFile(_)) => { ended = true; }, ...
identifier_body
music.rs
//! This module provides the music struct, which allows to play and control a music from a file. use libc; use mpv; use std::rc::Rc; use std::cell::RefCell; /// The music struct. pub struct Music { /// Indicates wether the music is playing, paused or stopped. status: MusicStatus, /// The mpv handler to...
(path: &str) -> Result<Music, ()> { // Set locale, because apparently, mpv needs it unsafe { libc::setlocale(libc::LC_NUMERIC, &('C' as i8)); } let mpv_builder = mpv::MpvHandlerBuilder::new().expect("Failed to init MPV builder"); let mut mpv = mpv_builder.build().exp...
new
identifier_name
util.rs
use std::io::{self, Result, Read, Write, ErrorKind}; //copy with length limiting pub fn copy<R: Read, W: Write>(r: &mut R, w: &mut W, len_max: u64) -> io::Result<u64> { let mut buf = [0; 1024]; let mut written : u64 = 0; while written < len_max { let len = match r.read(&mut buf) { Ok(0) => return Ok(written...
} else { let to_write : usize = len_max as usize - written as usize; let to_write = if to_write > len {len} else {to_write}; //required? try!(w.write_all(&buf[..to_write])); written += to_write as u64; } } Ok(written) }
}; if (written+len as u64) < len_max { try!(w.write_all(&buf[..len])); written += len as u64;
random_line_split
util.rs
use std::io::{self, Result, Read, Write, ErrorKind}; //copy with length limiting pub fn copy<R: Read, W: Write>(r: &mut R, w: &mut W, len_max: u64) -> io::Result<u64>
written += to_write as u64; } } Ok(written) }
{ let mut buf = [0; 1024]; let mut written : u64 = 0; while written < len_max { let len = match r.read(&mut buf) { Ok(0) => return Ok(written), Ok(len) => len, Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return Err(e), }; if (written+len as u64) < len_max { try!(...
identifier_body
util.rs
use std::io::{self, Result, Read, Write, ErrorKind}; //copy with length limiting pub fn
<R: Read, W: Write>(r: &mut R, w: &mut W, len_max: u64) -> io::Result<u64> { let mut buf = [0; 1024]; let mut written : u64 = 0; while written < len_max { let len = match r.read(&mut buf) { Ok(0) => return Ok(written), Ok(len) => len, Err(ref e) if e.kind() == ErrorKind::Interrupted => continue, Err(...
copy
identifier_name
htmlimageelement.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::AttrValue; use dom::bindings::codegen::Bindings::HTMLImageElementBinding; use dom::bindings::codege...
} fn before_remove_attr(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.before_remove_attr(name, value.clone()), _ => (), } if "src" == name.as_slice() { self.update_image(None); } } fn parse_plain...
{ let window = window_from_node(*self).root(); let url = window.deref().get_url(); self.update_image(Some((value, &url))); }
conditional_block
htmlimageelement.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::AttrValue; use dom::bindings::codegen::Bindings::HTMLImageElementBinding; use dom::bindings::codege...
let element = HTMLImageElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLImageElementBinding::Wrap) } } pub trait LayoutHTMLImageElementHelpers { unsafe fn image(&self) -> Option<Url>; } impl LayoutHTMLImageElementHelpers for JS<HTMLImageElement> { ...
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, document: JSRef<Document>) -> Temporary<HTMLImageElement> {
random_line_split
htmlimageelement.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::AttrValue; use dom::bindings::codegen::Bindings::HTMLImageElementBinding; use dom::bindings::codege...
}
{ self.htmlelement.reflector() }
identifier_body
htmlimageelement.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::AttrValue; use dom::bindings::codegen::Bindings::HTMLImageElementBinding; use dom::bindings::codege...
(&self, name: &Atom, value: DOMString) { match self.super_type() { Some(ref s) => s.before_remove_attr(name, value.clone()), _ => (), } if "src" == name.as_slice() { self.update_image(None); } } fn parse_plain_attribute(&self, name: &str, val...
before_remove_attr
identifier_name
lib.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 mut r = rand::task_rng(); let mut words = vec!(); for _ in range(0, 20) { let range = r.gen_range(1u, 10); words.push(r.gen_vec::<u8>(range)); } for _ in range(0, 20) { let mut input = vec![]; for _ in range(0, 2000) { ...
#[allow(deprecated_owned_vector)] fn test_flate_round_trip() {
random_line_split
lib.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> { unsafe { let mut outsz : size_t = 0; let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void, bytes.len() as size_t, ...
{ deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER) }
identifier_body
lib.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 ...
(bytes: &[u8]) -> Option<CVec<u8>> { deflate_bytes_internal(bytes, LZ_NORM) } /// Compress a buffer, using a header that zlib can understand. pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> { deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER) } fn inflate_bytes_internal(bytes: &[u8],...
deflate_bytes
identifier_name
lib.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 { None } } } /// Compress a buffer, without writing any sort of header on the output. pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> { deflate_bytes_internal(bytes, LZ_NORM) } /// Compress a buffer, using a header that zlib can understand. pub fn deflate_bytes_zlib(bytes: &[u...
{ Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res))) }
conditional_block
string-self-append.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 ...
while i > 0 { println!("{}", a.len()); assert_eq!(a.len(), expected_len); a = format_strbuf!("{}{}", a, a); i -= 1; expected_len *= 2u; } }
let mut i = 20; let mut expected_len = 1u;
random_line_split
string-self-append.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 ...
() { // Make sure we properly handle repeated self-appends. let mut a: StrBuf = "A".to_strbuf(); let mut i = 20; let mut expected_len = 1u; while i > 0 { println!("{}", a.len()); assert_eq!(a.len(), expected_len); a = format_strbuf!("{}{}", a, a); i -= 1; expe...
main
identifier_name
string-self-append.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 ...
{ // Make sure we properly handle repeated self-appends. let mut a: StrBuf = "A".to_strbuf(); let mut i = 20; let mut expected_len = 1u; while i > 0 { println!("{}", a.len()); assert_eq!(a.len(), expected_len); a = format_strbuf!("{}{}", a, a); i -= 1; expecte...
identifier_body
controlflow.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<'a>(bcx: &'a Block<'a>, b: &ast::Block, dest: expr::Dest) -> &'a Block<'a> { let _icx = push_ctxt("trans_block"); let mut bcx = bcx; for s in b.stmts.iter() { bcx = trans_stmt(bcx, *s); } match b.expr { Some(e) => { bcx = expr::trans_into(bcx, e, dest)...
trans_block
identifier_name
controlflow.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 ...
Some(inf) => inf.parent, None => { unwind = match unwind.parent { Some(bcx) => bcx, // This is a return from a loop body block None => { Store(bcx, C...
{ // If we're looking for a labeled loop, check the label... target = if to_end { brk } else { unwind }; match opt_label { Some(desired) => match l { Some(a...
conditional_block
controlflow.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 trans_break_cont<'a>( bcx: &'a Block<'a>, opt_label: Option<Name>, to_end: bool) -> &'a Block<'a> { let _icx = push_ctxt("trans_break_cont"); // Locate closest loop block, outputting cleanup as we go. let...
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore); cleanup_and_Br(body_bcx_out, body_bcx_in, body_bcx_in.llbb); return next_bcx; }
random_line_split
controlflow.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 trans_if<'a>( bcx: &'a Block<'a>, cond: &ast::Expr, thn: ast::P<ast::Block>, els: Option<@ast::Expr>, dest: expr::Dest) -> &'a Block<'a> { debug!("trans_if(bcx={}, cond={}, thn={:?}, dest={})", bcx.to...
{ let _icx = push_ctxt("trans_block"); let mut bcx = bcx; for s in b.stmts.iter() { bcx = trans_stmt(bcx, *s); } match b.expr { Some(e) => { bcx = expr::trans_into(bcx, e, dest); } None => { assert!(dest == expr::Ignore || bcx.unreachable.get()...
identifier_body
lib.rs
// Copyright (C) 2020 Inderjit Gill <email@indy.io> // This file is part of Seni // Seni is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any l...
() { // vm.ip wasn't being set to 0 in-between running the preamble and running the user's program let mut vm: Vm = Default::default(); let mut context: Context = Default::default(); let s = "(rect)"; is_rendering_num_verts(&mut vm, &mut context, &s, 4); } // #[test] ...
bug_running_preamble_crashed_vm
identifier_name
lib.rs
// Copyright (C) 2020 Inderjit Gill <email@indy.io> // This file is part of Seni // Seni is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any l...
#[cfg(test)] pub mod tests { use super::*; fn is_rendering_num_verts( vm: &mut Vm, context: &mut Context, s: &str, expected_num_verts: usize, ) { let program = program_from_source(s).unwrap(); let _ = run_program_with_preamble(vm, context, &program).unwrap(...
{ s.len() as i32 }
identifier_body
lib.rs
// Copyright (C) 2020 Inderjit Gill <email@indy.io> // This file is part of Seni // Seni is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any l...
// along with this program. If not, see <https://www.gnu.org/licenses/>. #![cfg_attr( feature = "cargo-clippy", allow( clippy::many_single_char_names, clippy::too_many_arguments, clippy::excessive_precision ) )] /*! The core crate provides the basic functionality of the Seni syste...
// GNU Affero General Public License for more details. // You should have received a copy of the GNU Affero General Public License
random_line_split
dummy_variables.rs
use std::default::Default; use std::marker::PhantomData; use variable::GetVariable; /// Struct that implement [`Index`], /// used to fake variables when don't needed in expressions. /// /// Prefer using this container with the [`DummyVariable`] fake type. /// /// [`Index`]: https://doc.rust-lang.org/std/ops/trait.Inde...
} impl<T> GetVariable<()> for DummyVariables<T> { type Output = T; fn get_variable(&self, _: ()) -> Option<&Self::Output> { None } }
{ DummyVariables(PhantomData::default()) }
identifier_body
dummy_variables.rs
use std::default::Default; use std::marker::PhantomData; use variable::GetVariable; /// Struct that implement [`Index`], /// used to fake variables when don't needed in expressions. /// /// Prefer using this container with the [`DummyVariable`] fake type. /// /// [`Index`]: https://doc.rust-lang.org/std/ops/trait.Inde...
} } impl<T> GetVariable<()> for DummyVariables<T> { type Output = T; fn get_variable(&self, _: ()) -> Option<&Self::Output> { None } }
fn default() -> Self { DummyVariables(PhantomData::default())
random_line_split
dummy_variables.rs
use std::default::Default; use std::marker::PhantomData; use variable::GetVariable; /// Struct that implement [`Index`], /// used to fake variables when don't needed in expressions. /// /// Prefer using this container with the [`DummyVariable`] fake type. /// /// [`Index`]: https://doc.rust-lang.org/std/ops/trait.Inde...
(&self, _: ()) -> Option<&Self::Output> { None } }
get_variable
identifier_name
graph.rs
//! Trace and batch implementations based on sorted ranges. //! //! The types and type aliases in this module start with either //! //! * `OrdVal`: Collections whose data have the form `(key, val)` where `key` is ordered. //! * `OrdKey`: Collections whose data have the form `key` where `key` is ordered. //! //! Althoug...
fn close(&mut self) { self.spine.close() } } /// #[derive(Debug, Abomonation)] pub struct GraphBatch<N> { index: usize, peers: usize, keys: Vec<Node>, nodes: Vec<usize>, edges: Vec<N>, desc: Description<Product<RootTimestamp,()>>, } impl<N> BatchReader<Node, N, Product<RootTi...
{ self.spine.insert(batch) }
identifier_body
graph.rs
//! Trace and batch implementations based on sorted ranges. //! //! The types and type aliases in this module start with either //! //! * `OrdVal`: Collections whose data have the form `(key, val)` where `key` is ordered. //! * `OrdKey`: Collections whose data have the form `key` where `key` is ordered. //! //! Althoug...
} fn rewind_keys(&mut self, storage: &Self::Storage) { self.key_pos = 0; self.key = storage.index as Node; } fn rewind_vals(&mut self, storage: &Self::Storage) { if self.key_valid(storage) { self.val_pos = storage.nodes[self.key_pos]; } } } /// A builder for creating layers...
{ let lower = self.val_pos; let upper = storage.nodes[self.key_pos + 1]; self.val_pos += advance(&storage.edges[lower .. upper], |tuple| tuple < val); }
conditional_block
graph.rs
//! Trace and batch implementations based on sorted ranges. //! //! The types and type aliases in this module start with either //! //! * `OrdVal`: Collections whose data have the form `(key, val)` where `key` is ordered. //! * `OrdKey`: Collections whose data have the form `key` where `key` is ordered. //! //! Althoug...
} } // Ideally, this method acts as insertion of `batch`, even if we are not yet able to begin // merging the batch. This means it is a good time to perform amortized work proportional // to the size of batch. fn insert(&mut self, batch: Self::Batch) { self.spine.insert(batch) }...
GraphSpine { spine: Spine::<Node, N, Product<RootTimestamp, ()>, isize, Rc<GraphBatch<N>>>::new()
random_line_split
graph.rs
//! Trace and batch implementations based on sorted ranges. //! //! The types and type aliases in this module start with either //! //! * `OrdVal`: Collections whose data have the form `(key, val)` where `key` is ordered. //! * `OrdKey`: Collections whose data have the form `key` where `key` is ordered. //! //! Althoug...
<'a>(&self, storage: &'a Self::Storage) -> &'a N { &storage.edges[self.val_pos] } fn map_times<L: FnMut(&Product<RootTimestamp,()>, isize)>(&mut self, _storage: &Self::Storage, mut logic: L) { logic(&Product::new(RootTimestamp, ()), 1); } fn key_valid(&self, storage: &Self::Storage) -> bool { (self....
val
identifier_name
tmux.rs
use fastup::{Document, Node}; use fastup::Node::*; use color::Color888; use std::fmt; #[derive(Debug, Copy, Clone, Default)] pub struct Renderer; impl super::Renderer for Renderer { fn render(&self, doc: &Document) -> String { let env = Environment::default(); tmux_from_document(doc, &env) + "#[de...
if let Some(color) = env.background { style += &format!(",bg=#{}", color); } if env.bold { style += &format!(",bold"); } style += "]"; style } } impl fmt::Display for Environment { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result ...
{ style += &format!(",fg=#{}", color); }
conditional_block
tmux.rs
use fastup::{Document, Node}; use fastup::Node::*; use color::Color888; use std::fmt; #[derive(Debug, Copy, Clone, Default)] pub struct Renderer; impl super::Renderer for Renderer { fn render(&self, doc: &Document) -> String { let env = Environment::default(); tmux_from_document(doc, &env) + "#[de...
style += &format!(",bold"); } style += "]"; style } } impl fmt::Display for Environment { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", String::from(self)) } } fn tmux_from_document(doc: &Document, env: &Environment) -> String { ...
random_line_split
tmux.rs
use fastup::{Document, Node}; use fastup::Node::*; use color::Color888; use std::fmt; #[derive(Debug, Copy, Clone, Default)] pub struct Renderer; impl super::Renderer for Renderer { fn render(&self, doc: &Document) -> String { let env = Environment::default(); tmux_from_document(doc, &env) + "#[de...
(env: &'a Environment) -> Self { let mut style = "#[default".to_string(); if let Some(color) = env.foreground { style += &format!(",fg=#{}", color); } if let Some(color) = env.background { style += &format!(",bg=#{}", color); } if env.bold { ...
from
identifier_name
htmliframeelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLIFrameElementBinding; use dom::bindings::utils::{DOMString, ErrorResult, null_str_...
pub fn Srcdoc(&self) -> DOMString { None } pub fn SetSrcdoc(&mut self, _srcdoc: &DOMString) -> ErrorResult { Ok(()) } pub fn Name(&self) -> DOMString { None } pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult { Ok(()) } pub fn Sandbox(&...
{ Ok(()) }
identifier_body
htmliframeelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLIFrameElementBinding; use dom::bindings::utils::{DOMString, ErrorResult, null_str_...
(&mut self, _allow: bool) -> ErrorResult { Ok(()) } pub fn Width(&self) -> DOMString { None } pub fn SetWidth(&mut self, _width: &DOMString) -> ErrorResult { Ok(()) } pub fn Height(&self) -> DOMString { None } pub fn SetHeight(&mut self, _height: &DOMS...
SetAllowFullscreen
identifier_name
htmliframeelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::HTMLIFrameElementBinding; use dom::bindings::utils::{DOMString, ErrorResult, null_str_...
pub fn Srcdoc(&self) -> DOMString { None } pub fn SetSrcdoc(&mut self, _srcdoc: &DOMString) -> ErrorResult { Ok(()) } pub fn Name(&self) -> DOMString { None } pub fn SetName(&mut self, _name: &DOMString) -> ErrorResult { Ok(()) } pub fn Sandbox(&s...
random_line_split
capture.rs
fn main()
// that. Immediately borrows `count`. // // A `mut` is required on `inc` because a `&mut` is stored inside. // Thus, calling the closure mutates the closure which requires // a `mut`. let mut inc = || { count += 1; println!("`count`: {}", count); }; // Call the closure. ...
{ use std::mem; let color = "green"; // A closure to print `color` which immediately borrows (`&`) // `color` and stores the borrow and closure in the `print` // variable. It will remain borrowed until `print` goes out of // scope. `println!` only requires `by reference` so it doesn't ...
identifier_body
capture.rs
fn
() { use std::mem; let color = "green"; // A closure to print `color` which immediately borrows (`&`) // `color` and stores the borrow and closure in the `print` // variable. It will remain borrowed until `print` goes out of // scope. `println!` only requires `by reference` so it doesn't ...
main
identifier_name
capture.rs
fn main() { use std::mem; let color = "green"; // A closure to print `color` which immediately borrows (`&`) // `color` and stores the borrow and closure in the `print` // variable. It will remain borrowed until `print` goes out of // scope. `println!` only requires `by reference` so it do...
//consume(); // ^ TODO: Try uncommenting this line. }
random_line_split
mod.rs
/*! Test supports module. */ #![allow(dead_code)] use glium::{self, glutin}; use glium::backend::Facade; use glium::index::PrimitiveType; use std::env; /// Builds a display for tests. #[cfg(not(feature = "test_headless"))] pub fn build_display() -> glium::Display { let version = parse_version(); let event_...
{ glium::Texture2d::empty(facade, 1024, 1024).unwrap() }
identifier_body
mod.rs
/*! Test supports module. */ #![allow(dead_code)] use glium::{self, glutin}; use glium::backend::Facade; use glium::index::PrimitiveType; use std::env; /// Builds a display for tests. #[cfg(not(feature = "test_headless"))] pub fn build_display() -> glium::Display { let version = parse_version(); let event_...
(display: &glium::Display) { let version = parse_version(); let event_loop = glutin::event_loop::EventLoop::new(); let wb = glutin::window::WindowBuilder::new().with_visible(false); let cb = glutin::ContextBuilder::new() .with_gl_debug_flag(true) .with_gl(version); display.rebuild(wb, ...
rebuild_display
identifier_name
mod.rs
/*! Test supports module. */ #![allow(dead_code)] use glium::{self, glutin}; use glium::backend::Facade; use glium::index::PrimitiveType; use std::env; /// Builds a display for tests. #[cfg(not(feature = "test_headless"))] pub fn build_display() -> glium::Display { let version = parse_version(); let event_...
pub fn build_unicolor_texture2d<F:?Sized>(facade: &F, red: f32, green: f32, blue: f32) -> glium::Texture2d where F: Facade { let color = ((red * 255.0) as u8, (green * 255.0) as u8, (blue * 255.0) as u8); glium::texture::Texture2d::new(facade, vec![ vec![color, color], vec![color, color], ...
Err(_) => glutin::GlRequest::Latest, } } /// Builds a 2x2 unicolor texture.
random_line_split
in_flight_requests.rs
use crate::{ context, util::{Compact, TimeUntil}, PollIo, Response, ServerError, }; use fnv::FnvHashMap; use futures::ready; use log::{debug, trace}; use std::{ collections::hash_map, io, task::{Context, Poll}, }; use tokio::sync::oneshot; use tokio_util::time::delay_queue::{self, DelayQueue}; ...
debug!( "No in-flight request found for request_id = {}.", response.request_id ); // If the response completion was absent, then the request was already canceled. false } /// Cancels a request without completing (typically used when a request handle wa...
{ self.request_data.compact(0.1); trace!("[{}] Received response.", request_data.ctx.trace_id()); self.deadlines.remove(&request_data.deadline_key); request_data.complete(response); return true; }
conditional_block
in_flight_requests.rs
use crate::{ context, util::{Compact, TimeUntil}, PollIo, Response, ServerError, }; use fnv::FnvHashMap; use futures::ready; use log::{debug, trace}; use std::{ collections::hash_map, io, task::{Context, Poll}, }; use tokio::sync::oneshot; use tokio_util::time::delay_queue::{self, DelayQueue}; ...
}
{ let _ = self.response_completion.send(response); }
identifier_body
in_flight_requests.rs
use crate::{ context, util::{Compact, TimeUntil}, PollIo, Response, ServerError, }; use fnv::FnvHashMap; use futures::ready; use log::{debug, trace}; use std::{ collections::hash_map, io, task::{Context, Poll}, }; use tokio::sync::oneshot; use tokio_util::time::delay_queue::{self, DelayQueue}; ...
) -> Result<(), AlreadyExistsError> { match self.request_data.entry(request_id) { hash_map::Entry::Vacant(vacant) => { let timeout = ctx.deadline.time_until(); trace!( "[{}] Queuing request with timeout {:?}.", ctx.trace_id(...
pub fn insert_request( &mut self, request_id: u64, ctx: context::Context, response_completion: oneshot::Sender<Response<Resp>>,
random_line_split
in_flight_requests.rs
use crate::{ context, util::{Compact, TimeUntil}, PollIo, Response, ServerError, }; use fnv::FnvHashMap; use futures::ready; use log::{debug, trace}; use std::{ collections::hash_map, io, task::{Context, Poll}, }; use tokio::sync::oneshot; use tokio_util::time::delay_queue::{self, DelayQueue}; ...
(&mut self, response: Response<Resp>) -> bool { if let Some(request_data) = self.request_data.remove(&response.request_id) { self.request_data.compact(0.1); trace!("[{}] Received response.", request_data.ctx.trace_id()); self.deadlines.remove(&request_data.deadline_key); ...
complete_request
identifier_name
match-value-binding-in-guard-3291.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 ...
foo(None, true); foo(None, false); }
random_line_split
match-value-binding-in-guard-3291.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 ...
(x: Option<Box<int>>, b: bool) -> int { match x { None => { 1 } Some(ref x) if b => { *x.clone() } Some(_) => { 0 } } } pub fn main() { foo(Some(box 22), true); foo(Some(box 22), false); foo(None, true); foo(None, false); }
foo
identifier_name
match-value-binding-in-guard-3291.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() { foo(Some(box 22), true); foo(Some(box 22), false); foo(None, true); foo(None, false); }
{ match x { None => { 1 } Some(ref x) if b => { *x.clone() } Some(_) => { 0 } } }
identifier_body
connection.rs
.query_pairs() .into_iter() .filter(|&(ref key, _)| key == "db") .next() { Some((_, db)) => unwrap_or!( db.parse::<i64>().ok(), fail!((ErrorKind::InvalidClientConfig, "Invalid database number")) ), None => 0...
from_pattern
identifier_name
connection.rs
>; } impl IntoConnectionInfo for ConnectionInfo { fn into_connection_info(self) -> RedisResult<ConnectionInfo> { Ok(self) } } impl<'a> IntoConnectionInfo for &'a str { fn into_connection_info(self) -> RedisResult<ConnectionInfo> { match parse_redis_url(self) { Ok(u) => u.into_c...
_ => fail!(( ErrorKind::ResponseError, "Redis server refused to switch database" )), } } Ok(rv) } /// Implements the "stateless" part of the connection interface that is used by the /// different objects in redis-rs. Primarily it obviously appl...
{}
conditional_block
connection.rs
ConnectionInfo>; } impl IntoConnectionInfo for ConnectionInfo { fn into_connection_info(self) -> RedisResult<ConnectionInfo> { Ok(self) } } impl<'a> IntoConnectionInfo for &'a str { fn into_connection_info(self) -> RedisResult<ConnectionInfo> { match parse_redis_url(self) { Ok(...
Ok(()) } pub fn is_open(&self) -> bool { match *self { ActualConnection::Tcp(TcpConnection { open,.. }) => open, #[cfg(unix)] ActualConnection::Unix(UnixConnection { open,.. }) => open, } } } pub fn connect(connection_info: &ConnectionInfo) -> Re...
random_line_split
connection.rs
>; } impl IntoConnectionInfo for ConnectionInfo { fn into_connection_info(self) -> RedisResult<ConnectionInfo> { Ok(self) } } impl<'a> IntoConnectionInfo for &'a str { fn into_connection_info(self) -> RedisResult<ConnectionInfo> { match parse_redis_url(self) { Ok(u) => u.into_c...
pub fn as_pubsub<'a>(&'a mut self) -> PubSub<'a> { // NOTE: The pubsub flag is intentionally not raised at this time since running commands // within the pubsub state should not try and exit from the pubsub state. PubSub::new(self) } fn exit_pubsub(&mut self) -> RedisResult<()> { ...
{ self.con.set_read_timeout(dur) }
identifier_body
ike.rs
/* Copyright (C) 2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
() -> IkeHeaderWrapper { IkeHeaderWrapper { spi_initiator: String::new(), spi_responder: String::new(), maj_ver: 0, min_ver: 0, msg_id: 0, flags: 0, ikev1_transforms: Vec::new(), ikev2_transforms: Vec::new(), ...
new
identifier_name
ike.rs
/* Copyright (C) 2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
else if isakmp_header.maj_ver == 2 { if isakmp_header.min_ver!= 0 { SCLogDebug!( "ipsec_probe: could be ipsec, but with unsupported/invalid version {}.{}", isakmp_header.maj_ver, isakmp_header.min_ver ...
{ if isakmp_header.resp_spi == 0 && direction != Direction::ToServer { unsafe { *rdir = Direction::ToServer.into(); } } return true; }
conditional_block
ike.rs
/* Copyright (C) 2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
#[no_mangle] pub extern "C" fn rs_ike_state_progress_completion_status(_direction: u8) -> std::os::raw::c_int { // This parser uses 1 to signal transaction completion status. return 1; } #[no_mangle] pub extern "C" fn rs_ike_tx_get_alstate_progress( _tx: *mut std::os::raw::c_void, _direction: u8, ) -> st...
{ let state = cast_pointer!(state, IKEState); return state.tx_id; }
identifier_body
ike.rs
/* Copyright (C) 2020 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARR...
if AppLayerProtoDetectConfProtoDetectionEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let alproto = AppLayerRegisterProtocolDetection(&parser, 1); ALPROTO_IKE = alproto; if AppLayerParserConfParserEnabled(ip_proto_str.as_ptr(), parser.name)!= 0 { let _ = AppLayerRegisterParse...
}; let ip_proto_str = CString::new("udp").unwrap();
random_line_split
net.rs
//! A collection of traits abstracting over Listeners and Streams. use std::any::{Any, AnyRefExt}; use std::boxed::BoxAny; use std::fmt; use std::intrinsics::TypeId; use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError, Stream, Listener, Acceptor}; use std::io::net::ip::{SocketAd...
} impl BoxAny for Box<NetworkStream + Send> { fn downcast<T:'static>(self) -> Result<Box<T>, Box<NetworkStream + Send>> { if self.is::<T>() { Ok(unsafe { self.downcast_unchecked() }) } else { Err(self) } } } /// A `NetworkListener` for `HttpStream`s. pub struct...
{ if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute_copy(&self); // Extract the data pointer Some(transmute(to.data)) } } else { None }...
identifier_body
net.rs
//! A collection of traits abstracting over Listeners and Streams. use std::any::{Any, AnyRefExt}; use std::boxed::BoxAny; use std::fmt; use std::intrinsics::TypeId; use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError, Stream, Listener, Acceptor}; use std::io::net::ip::{SocketAd...
(&mut self) -> IoResult<()> { (**self).flush() } } impl<'a> Reader for &'a mut NetworkStream { #[inline] fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) } } impl<'a> Writer for &'a mut NetworkStream { #[inline] fn write(&mut self, msg: &[u8]) -> IoResult<()> { (**self).write(...
flush
identifier_name
net.rs
//! A collection of traits abstracting over Listeners and Streams. use std::any::{Any, AnyRefExt}; use std::boxed::BoxAny; use std::fmt; use std::intrinsics::TypeId; use std::io::{IoResult, IoError, ConnectionAborted, InvalidInput, OtherIoError, Stream, Listener, Acceptor}; use std::io::net::ip::{SocketAd...
impl Clone for Box<NetworkStream + Send> { #[inline] fn clone(&self) -> Box<NetworkStream + Send> { self.clone_box() } } impl Reader for Box<NetworkStream + Send> { #[inline] fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (**self).read(buf) } } impl Writer for Box<NetworkStream + Send> { ...
}
random_line_split