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 |
---|---|---|---|---|
hunter.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use common::module_common::{move_by, print_str, srand, Context, GRID_H, GRID_W};
use common::println;
use common::shared::{cptr, State};
#[no_mangle]
pub extern "C" fn malloc_(size: usize) -> cptr |
#[no_mangle]
pub extern "C" fn create_context(ro_ptr: cptr, rw_ptr: cptr) -> *const Context {
Context::new_unowned(ro_ptr, rw_ptr)
}
#[no_mangle]
pub extern "C" fn update_context(ctx: &mut Context, ro_ptr: cptr, rw_ptr: cptr) {
ctx.update(ro_ptr, rw_ptr);
}
#[no_mangle]
pub extern "C" fn init(ctx: &mut Context, rand_seed: i32) {
srand(rand_seed as usize);
ctx.hunter.x = GRID_W / 2;
ctx.hunter.y = GRID_H / 2;
}
#[no_mangle]
pub extern "C" fn tick(ctx: &mut Context) {
// Find the closest runner and move towards it.
let mut min_dx: i32 = 0;
let mut min_dy: i32 = 0;
let mut min_dist = 99999;
for r in &*ctx.runners {
if r.state == State::Dead {
continue;
}
let dx: i32 = r.x as i32 - ctx.hunter.x as i32;
let dy: i32 = r.y as i32 - ctx.hunter.y as i32;
let dist = dx * dx + dy * dy;
if dist < min_dist {
min_dx = dx;
min_dy = dy;
min_dist = dist;
}
}
move_by(&ctx.grid, &mut ctx.hunter.x, &mut ctx.hunter.y, min_dx, min_dy);
}
#[no_mangle]
pub extern "C" fn large_alloc() {
println!("[h] Requesting large allocation");
std::mem::forget(Vec::<u8>::with_capacity(100000));
}
#[no_mangle]
pub extern "C" fn modify_grid(ctx: &mut Context) {
println!("[h] Attempting to write to read-only memory...");
ctx.grid[0][0] = 2;
}
fn main() {
println!("hunter: Not meant to be run as a main");
}
| {
let vec: Vec<u8> = Vec::with_capacity(size);
let ptr = vec.as_ptr();
std::mem::forget(vec); // Leak the vector
ptr as cptr
} | identifier_body |
hunter.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use common::module_common::{move_by, print_str, srand, Context, GRID_H, GRID_W};
use common::println;
use common::shared::{cptr, State};
#[no_mangle]
pub extern "C" fn malloc_(size: usize) -> cptr {
let vec: Vec<u8> = Vec::with_capacity(size);
let ptr = vec.as_ptr();
std::mem::forget(vec); // Leak the vector
ptr as cptr
}
#[no_mangle]
pub extern "C" fn create_context(ro_ptr: cptr, rw_ptr: cptr) -> *const Context {
Context::new_unowned(ro_ptr, rw_ptr)
}
#[no_mangle]
pub extern "C" fn update_context(ctx: &mut Context, ro_ptr: cptr, rw_ptr: cptr) {
ctx.update(ro_ptr, rw_ptr);
}
#[no_mangle]
pub extern "C" fn init(ctx: &mut Context, rand_seed: i32) {
srand(rand_seed as usize);
ctx.hunter.x = GRID_W / 2;
ctx.hunter.y = GRID_H / 2;
}
#[no_mangle]
pub extern "C" fn tick(ctx: &mut Context) {
// Find the closest runner and move towards it.
let mut min_dx: i32 = 0;
let mut min_dy: i32 = 0;
let mut min_dist = 99999;
for r in &*ctx.runners {
if r.state == State::Dead |
let dx: i32 = r.x as i32 - ctx.hunter.x as i32;
let dy: i32 = r.y as i32 - ctx.hunter.y as i32;
let dist = dx * dx + dy * dy;
if dist < min_dist {
min_dx = dx;
min_dy = dy;
min_dist = dist;
}
}
move_by(&ctx.grid, &mut ctx.hunter.x, &mut ctx.hunter.y, min_dx, min_dy);
}
#[no_mangle]
pub extern "C" fn large_alloc() {
println!("[h] Requesting large allocation");
std::mem::forget(Vec::<u8>::with_capacity(100000));
}
#[no_mangle]
pub extern "C" fn modify_grid(ctx: &mut Context) {
println!("[h] Attempting to write to read-only memory...");
ctx.grid[0][0] = 2;
}
fn main() {
println!("hunter: Not meant to be run as a main");
}
| {
continue;
} | conditional_block |
hunter.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use common::module_common::{move_by, print_str, srand, Context, GRID_H, GRID_W};
use common::println;
use common::shared::{cptr, State};
#[no_mangle]
pub extern "C" fn | (size: usize) -> cptr {
let vec: Vec<u8> = Vec::with_capacity(size);
let ptr = vec.as_ptr();
std::mem::forget(vec); // Leak the vector
ptr as cptr
}
#[no_mangle]
pub extern "C" fn create_context(ro_ptr: cptr, rw_ptr: cptr) -> *const Context {
Context::new_unowned(ro_ptr, rw_ptr)
}
#[no_mangle]
pub extern "C" fn update_context(ctx: &mut Context, ro_ptr: cptr, rw_ptr: cptr) {
ctx.update(ro_ptr, rw_ptr);
}
#[no_mangle]
pub extern "C" fn init(ctx: &mut Context, rand_seed: i32) {
srand(rand_seed as usize);
ctx.hunter.x = GRID_W / 2;
ctx.hunter.y = GRID_H / 2;
}
#[no_mangle]
pub extern "C" fn tick(ctx: &mut Context) {
// Find the closest runner and move towards it.
let mut min_dx: i32 = 0;
let mut min_dy: i32 = 0;
let mut min_dist = 99999;
for r in &*ctx.runners {
if r.state == State::Dead {
continue;
}
let dx: i32 = r.x as i32 - ctx.hunter.x as i32;
let dy: i32 = r.y as i32 - ctx.hunter.y as i32;
let dist = dx * dx + dy * dy;
if dist < min_dist {
min_dx = dx;
min_dy = dy;
min_dist = dist;
}
}
move_by(&ctx.grid, &mut ctx.hunter.x, &mut ctx.hunter.y, min_dx, min_dy);
}
#[no_mangle]
pub extern "C" fn large_alloc() {
println!("[h] Requesting large allocation");
std::mem::forget(Vec::<u8>::with_capacity(100000));
}
#[no_mangle]
pub extern "C" fn modify_grid(ctx: &mut Context) {
println!("[h] Attempting to write to read-only memory...");
ctx.grid[0][0] = 2;
}
fn main() {
println!("hunter: Not meant to be run as a main");
}
| malloc_ | identifier_name |
shift-near-oflo.rs | // run-pass
// compile-flags: -C debug-assertions
// Check that we do *not* overflow on a number of edge cases.
// (compare with test/run-fail/overflowing-{lsh,rsh}*.rs)
fn main() {
test_left_shift();
test_right_shift();
}
pub static mut HACK: i32 = 0;
// Work around constant-evaluation
// The point of this test is to exercise the code generated for execution at runtime,
// `id` can never be flagged as a const fn by future aggressive analyses...
// due to the modification of the static
#[inline(never)]
fn id<T>(x: T) -> T {
unsafe { HACK += 1; }
x
}
fn | () {
// negative rhs can panic, but values in [0,N-1] are okay for iN
macro_rules! tests {
($iN:ty, $uN:ty, $max_rhs:expr, $expect_i:expr, $expect_u:expr) => { {
let x = (1 as $iN) << id(0);
assert_eq!(x, 1);
let x = (1 as $uN) << id(0);
assert_eq!(x, 1);
let x = (1 as $iN) << id($max_rhs);
assert_eq!(x, $expect_i);
let x = (1 as $uN) << id($max_rhs);
assert_eq!(x, $expect_u);
// high-order bits on LHS are silently discarded without panic.
let x = (3 as $iN) << id($max_rhs);
assert_eq!(x, $expect_i);
let x = (3 as $uN) << id($max_rhs);
assert_eq!(x, $expect_u);
} }
}
let x = 1_i8 << id(0);
assert_eq!(x, 1);
let x = 1_u8 << id(0);
assert_eq!(x, 1);
let x = 1_i8 << id(7);
assert_eq!(x, i8::MIN);
let x = 1_u8 << id(7);
assert_eq!(x, 0x80);
// high-order bits on LHS are silently discarded without panic.
let x = 3_i8 << id(7);
assert_eq!(x, i8::MIN);
let x = 3_u8 << id(7);
assert_eq!(x, 0x80);
// above is (approximately) expanded from:
tests!(i8, u8, 7, i8::MIN, 0x80_u8);
tests!(i16, u16, 15, i16::MIN, 0x8000_u16);
tests!(i32, u32, 31, i32::MIN, 0x8000_0000_u32);
tests!(i64, u64, 63, i64::MIN, 0x8000_0000_0000_0000_u64);
}
fn test_right_shift() {
// negative rhs can panic, but values in [0,N-1] are okay for iN
macro_rules! tests {
($iN:ty, $uN:ty, $max_rhs:expr,
$signbit_i:expr, $highbit_i:expr, $highbit_u:expr) =>
{ {
let x = (1 as $iN) >> id(0);
assert_eq!(x, 1);
let x = (1 as $uN) >> id(0);
assert_eq!(x, 1);
let x = ($highbit_i) >> id($max_rhs-1);
assert_eq!(x, 1);
let x = ($highbit_u) >> id($max_rhs);
assert_eq!(x, 1);
// sign-bit is carried by arithmetic right shift
let x = ($signbit_i) >> id($max_rhs);
assert_eq!(x, -1);
// low-order bits on LHS are silently discarded without panic.
let x = ($highbit_i + 1) >> id($max_rhs-1);
assert_eq!(x, 1);
let x = ($highbit_u + 1) >> id($max_rhs);
assert_eq!(x, 1);
let x = ($signbit_i + 1) >> id($max_rhs);
assert_eq!(x, -1);
} }
}
tests!(i8, u8, 7, i8::MIN, 0x40_i8, 0x80_u8);
tests!(i16, u16, 15, i16::MIN, 0x4000_u16, 0x8000_u16);
tests!(i32, u32, 31, i32::MIN, 0x4000_0000_u32, 0x8000_0000_u32);
tests!(i64, u64, 63, i64::MIN,
0x4000_0000_0000_0000_u64, 0x8000_0000_0000_0000_u64);
}
| test_left_shift | identifier_name |
shift-near-oflo.rs | // run-pass
// compile-flags: -C debug-assertions
// Check that we do *not* overflow on a number of edge cases.
// (compare with test/run-fail/overflowing-{lsh,rsh}*.rs)
fn main() {
test_left_shift();
test_right_shift();
}
pub static mut HACK: i32 = 0;
// Work around constant-evaluation
// The point of this test is to exercise the code generated for execution at runtime,
// `id` can never be flagged as a const fn by future aggressive analyses...
// due to the modification of the static
#[inline(never)]
fn id<T>(x: T) -> T {
unsafe { HACK += 1; }
x
}
fn test_left_shift() {
// negative rhs can panic, but values in [0,N-1] are okay for iN
macro_rules! tests {
($iN:ty, $uN:ty, $max_rhs:expr, $expect_i:expr, $expect_u:expr) => { {
let x = (1 as $iN) << id(0);
assert_eq!(x, 1);
let x = (1 as $uN) << id(0); | assert_eq!(x, 1);
let x = (1 as $iN) << id($max_rhs);
assert_eq!(x, $expect_i);
let x = (1 as $uN) << id($max_rhs);
assert_eq!(x, $expect_u);
// high-order bits on LHS are silently discarded without panic.
let x = (3 as $iN) << id($max_rhs);
assert_eq!(x, $expect_i);
let x = (3 as $uN) << id($max_rhs);
assert_eq!(x, $expect_u);
} }
}
let x = 1_i8 << id(0);
assert_eq!(x, 1);
let x = 1_u8 << id(0);
assert_eq!(x, 1);
let x = 1_i8 << id(7);
assert_eq!(x, i8::MIN);
let x = 1_u8 << id(7);
assert_eq!(x, 0x80);
// high-order bits on LHS are silently discarded without panic.
let x = 3_i8 << id(7);
assert_eq!(x, i8::MIN);
let x = 3_u8 << id(7);
assert_eq!(x, 0x80);
// above is (approximately) expanded from:
tests!(i8, u8, 7, i8::MIN, 0x80_u8);
tests!(i16, u16, 15, i16::MIN, 0x8000_u16);
tests!(i32, u32, 31, i32::MIN, 0x8000_0000_u32);
tests!(i64, u64, 63, i64::MIN, 0x8000_0000_0000_0000_u64);
}
fn test_right_shift() {
// negative rhs can panic, but values in [0,N-1] are okay for iN
macro_rules! tests {
($iN:ty, $uN:ty, $max_rhs:expr,
$signbit_i:expr, $highbit_i:expr, $highbit_u:expr) =>
{ {
let x = (1 as $iN) >> id(0);
assert_eq!(x, 1);
let x = (1 as $uN) >> id(0);
assert_eq!(x, 1);
let x = ($highbit_i) >> id($max_rhs-1);
assert_eq!(x, 1);
let x = ($highbit_u) >> id($max_rhs);
assert_eq!(x, 1);
// sign-bit is carried by arithmetic right shift
let x = ($signbit_i) >> id($max_rhs);
assert_eq!(x, -1);
// low-order bits on LHS are silently discarded without panic.
let x = ($highbit_i + 1) >> id($max_rhs-1);
assert_eq!(x, 1);
let x = ($highbit_u + 1) >> id($max_rhs);
assert_eq!(x, 1);
let x = ($signbit_i + 1) >> id($max_rhs);
assert_eq!(x, -1);
} }
}
tests!(i8, u8, 7, i8::MIN, 0x40_i8, 0x80_u8);
tests!(i16, u16, 15, i16::MIN, 0x4000_u16, 0x8000_u16);
tests!(i32, u32, 31, i32::MIN, 0x4000_0000_u32, 0x8000_0000_u32);
tests!(i64, u64, 63, i64::MIN,
0x4000_0000_0000_0000_u64, 0x8000_0000_0000_0000_u64);
} | random_line_split |
|
shift-near-oflo.rs | // run-pass
// compile-flags: -C debug-assertions
// Check that we do *not* overflow on a number of edge cases.
// (compare with test/run-fail/overflowing-{lsh,rsh}*.rs)
fn main() {
test_left_shift();
test_right_shift();
}
pub static mut HACK: i32 = 0;
// Work around constant-evaluation
// The point of this test is to exercise the code generated for execution at runtime,
// `id` can never be flagged as a const fn by future aggressive analyses...
// due to the modification of the static
#[inline(never)]
fn id<T>(x: T) -> T {
unsafe { HACK += 1; }
x
}
fn test_left_shift() {
// negative rhs can panic, but values in [0,N-1] are okay for iN
macro_rules! tests {
($iN:ty, $uN:ty, $max_rhs:expr, $expect_i:expr, $expect_u:expr) => { {
let x = (1 as $iN) << id(0);
assert_eq!(x, 1);
let x = (1 as $uN) << id(0);
assert_eq!(x, 1);
let x = (1 as $iN) << id($max_rhs);
assert_eq!(x, $expect_i);
let x = (1 as $uN) << id($max_rhs);
assert_eq!(x, $expect_u);
// high-order bits on LHS are silently discarded without panic.
let x = (3 as $iN) << id($max_rhs);
assert_eq!(x, $expect_i);
let x = (3 as $uN) << id($max_rhs);
assert_eq!(x, $expect_u);
} }
}
let x = 1_i8 << id(0);
assert_eq!(x, 1);
let x = 1_u8 << id(0);
assert_eq!(x, 1);
let x = 1_i8 << id(7);
assert_eq!(x, i8::MIN);
let x = 1_u8 << id(7);
assert_eq!(x, 0x80);
// high-order bits on LHS are silently discarded without panic.
let x = 3_i8 << id(7);
assert_eq!(x, i8::MIN);
let x = 3_u8 << id(7);
assert_eq!(x, 0x80);
// above is (approximately) expanded from:
tests!(i8, u8, 7, i8::MIN, 0x80_u8);
tests!(i16, u16, 15, i16::MIN, 0x8000_u16);
tests!(i32, u32, 31, i32::MIN, 0x8000_0000_u32);
tests!(i64, u64, 63, i64::MIN, 0x8000_0000_0000_0000_u64);
}
fn test_right_shift() | assert_eq!(x, 1);
let x = ($highbit_u + 1) >> id($max_rhs);
assert_eq!(x, 1);
let x = ($signbit_i + 1) >> id($max_rhs);
assert_eq!(x, -1);
} }
}
tests!(i8, u8, 7, i8::MIN, 0x40_i8, 0x80_u8);
tests!(i16, u16, 15, i16::MIN, 0x4000_u16, 0x8000_u16);
tests!(i32, u32, 31, i32::MIN, 0x4000_0000_u32, 0x8000_0000_u32);
tests!(i64, u64, 63, i64::MIN,
0x4000_0000_0000_0000_u64, 0x8000_0000_0000_0000_u64);
}
| {
// negative rhs can panic, but values in [0,N-1] are okay for iN
macro_rules! tests {
($iN:ty, $uN:ty, $max_rhs:expr,
$signbit_i:expr, $highbit_i:expr, $highbit_u:expr) =>
{ {
let x = (1 as $iN) >> id(0);
assert_eq!(x, 1);
let x = (1 as $uN) >> id(0);
assert_eq!(x, 1);
let x = ($highbit_i) >> id($max_rhs-1);
assert_eq!(x, 1);
let x = ($highbit_u) >> id($max_rhs);
assert_eq!(x, 1);
// sign-bit is carried by arithmetic right shift
let x = ($signbit_i) >> id($max_rhs);
assert_eq!(x, -1);
// low-order bits on LHS are silently discarded without panic.
let x = ($highbit_i + 1) >> id($max_rhs-1); | identifier_body |
packet_recv_server.rs | #![no_main]
#[macro_use]
extern crate libfuzzer_sys;
#[macro_use]
extern crate lazy_static;
use std::net::SocketAddr;
use std::sync::Mutex;
| .unwrap_or_else(|_| "fuzz/cert.key".to_string());
let mut config = quiche::Config::new(quiche::PROTOCOL_VERSION).unwrap();
config.load_cert_chain_from_pem_file(&crt_path).unwrap();
config.load_priv_key_from_pem_file(&key_path).unwrap();
config
.set_application_protos(b"\x05hq-23\x08http/0.9")
.unwrap();
config.set_initial_max_data(30);
config.set_initial_max_stream_data_bidi_local(15);
config.set_initial_max_stream_data_bidi_remote(15);
config.set_initial_max_stream_data_uni(10);
config.set_initial_max_streams_bidi(3);
config.set_initial_max_streams_uni(3);
Mutex::new(config)
};
}
static SCID: quiche::ConnectionId<'static> =
quiche::ConnectionId::from_ref(&[0; quiche::MAX_CONN_ID_LEN]);
fuzz_target!(|data: &[u8]| {
let from: SocketAddr = "127.0.0.1:1234".parse().unwrap();
let mut buf = data.to_vec();
let mut conn =
quiche::accept(&SCID, None, from, &mut CONFIG.lock().unwrap()).unwrap();
let info = quiche::RecvInfo { from };
conn.recv(&mut buf, info).ok();
}); | lazy_static! {
static ref CONFIG: Mutex<quiche::Config> = {
let crt_path = std::env::var("QUICHE_FUZZ_CRT")
.unwrap_or_else(|_| "fuzz/cert.crt".to_string());
let key_path = std::env::var("QUICHE_FUZZ_KEY") | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_name = "flate"]
#![experimental]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(phase)]
#[cfg(test)] #[phase(plugin, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} 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: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> |
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0u, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0u, 20) {
let mut input = vec![];
for _ in range(0u, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
| {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *const _,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
} | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_name = "flate"]
#![experimental]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(phase)]
#[cfg(test)] #[phase(plugin, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} 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: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
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 *const _,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0u, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0u, 20) {
let mut input = vec![];
for _ in range(0u, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn | () {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
| test_zlib_flate | identifier_name |
lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // 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.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_name = "flate"]
#![experimental]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(phase)]
#[cfg(test)] #[phase(plugin, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} 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: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
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 *const _,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0u, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0u, 20) {
let mut input = vec![];
for _ in range(0u, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
} | // http://rust-lang.org/COPYRIGHT.
// | 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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_name = "flate"]
#![experimental]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(phase)]
#[cfg(test)] #[phase(plugin, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *const c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *const c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *const _,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} 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: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
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 *const _,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else |
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0u, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0u, 20) {
let mut input = vec![];
for _ in range(0u, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
| {
None
} | conditional_block |
io.rs | use buf::{Buf, MutBuf};
use error::MioResult;
use self::NonBlock::{Ready, WouldBlock};
use error::MioErrorKind as mek;
use os;
pub use os::IoDesc;
/// The result of a non-blocking operation.
#[derive(Debug)]
pub enum NonBlock<T> {
Ready(T),
WouldBlock
}
impl<T> NonBlock<T> {
pub fn would_block(&self) -> bool {
match *self {
WouldBlock => true,
_ => false
}
}
pub fn unwrap(self) -> T {
match self {
Ready(v) => v,
_ => panic!("would have blocked, no result to take")
}
}
}
pub trait IoHandle {
fn desc(&self) -> &IoDesc;
}
pub trait FromIoDesc {
fn from_desc(desc: IoDesc) -> Self;
}
pub trait IoReader {
fn read<B: MutBuf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>>;
fn read_slice(&self, buf: &mut [u8]) -> MioResult<NonBlock<usize>>;
}
pub trait IoWriter {
fn write<B: Buf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>>;
fn write_slice(&self, buf: &[u8]) -> MioResult<NonBlock<usize>>;
}
pub trait IoAcceptor {
type Output;
fn accept(&mut self) -> MioResult<NonBlock<Self::Output>>;
}
pub fn pipe() -> MioResult<(PipeReader, PipeWriter)> {
let (rd, wr) = try!(os::pipe());
Ok((PipeReader { desc: rd }, PipeWriter { desc: wr }))
}
pub struct PipeReader {
desc: os::IoDesc
}
impl IoHandle for PipeReader {
fn desc(&self) -> &os::IoDesc {
&self.desc
}
}
impl FromIoDesc for PipeReader {
fn from_desc(desc: IoDesc) -> Self {
PipeReader { desc: desc }
}
}
pub struct PipeWriter {
desc: os::IoDesc
}
impl IoHandle for PipeWriter {
fn desc(&self) -> &os::IoDesc {
&self.desc
}
}
impl FromIoDesc for PipeWriter {
fn from_desc(desc: IoDesc) -> Self {
PipeWriter { desc: desc }
}
}
impl IoReader for PipeReader {
fn read<B: MutBuf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>> {
read(self, buf)
}
fn read_slice(&self, buf: &mut [u8]) -> MioResult<NonBlock<usize>> {
read_slice(self, buf)
}
}
impl IoWriter for PipeWriter {
fn write<B: Buf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>> {
write(self, buf)
}
fn write_slice(&self, buf: &[u8]) -> MioResult<NonBlock<usize>> {
write_slice(self, buf)
}
}
/// Reads the length of the slice supplied by buf.mut_bytes into the buffer
/// This is not guaranteed to consume an entire datagram or segment.
/// If your protocol is msg based (instead of continuous stream) you should
/// ensure that your buffer is large enough to hold an entire segment (1532 bytes if not jumbo
/// frames)
#[inline]
pub fn read<I: IoHandle, B: MutBuf>(io: &I, buf: &mut B) -> MioResult<NonBlock<usize>> {
let res = read_slice(io, buf.mut_bytes());
match res {
// Successfully read some bytes, advance the cursor
Ok(Ready(cnt)) => { buf.advance(cnt); },
_ => {}
}
res
}
///writes the length of the slice supplied by Buf.bytes into the socket
///then advances the buffer that many bytes
#[inline]
pub fn write<O: IoHandle, B: Buf>(io: &O, buf: &mut B) -> MioResult<NonBlock<usize>> |
///reads the length of the supplied slice from the socket into the slice
#[inline]
pub fn read_slice<I: IoHandle>(io: & I, buf: &mut [u8]) -> MioResult<NonBlock<usize>> {
match os::read(io.desc(), buf) {
Ok(cnt) => {
Ok(Ready(cnt))
}
Err(e) => {
match e.kind {
mek::WouldBlock => Ok(WouldBlock),
_ => Err(e)
}
}
}
}
///writes the length of the supplied slice into the socket from the slice
#[inline]
pub fn write_slice<I: IoHandle>(io: & I, buf: & [u8]) -> MioResult<NonBlock<usize>> {
match os::write(io.desc(), buf) {
Ok(cnt) => { Ok(Ready(cnt)) }
Err(e) => {
match e.kind {
mek::WouldBlock => Ok(WouldBlock),
_ => Err(e)
}
}
}
}
| {
let res = write_slice(io, buf.bytes());
match res {
Ok(Ready(cnt)) => buf.advance(cnt),
_ => {}
}
res
} | identifier_body |
io.rs | use buf::{Buf, MutBuf};
use error::MioResult;
use self::NonBlock::{Ready, WouldBlock};
use error::MioErrorKind as mek;
use os;
pub use os::IoDesc;
/// The result of a non-blocking operation.
#[derive(Debug)]
pub enum NonBlock<T> {
Ready(T),
WouldBlock
}
impl<T> NonBlock<T> {
pub fn would_block(&self) -> bool {
match *self {
WouldBlock => true,
_ => false
}
}
pub fn unwrap(self) -> T {
match self {
Ready(v) => v,
_ => panic!("would have blocked, no result to take")
}
}
}
pub trait IoHandle {
fn desc(&self) -> &IoDesc;
}
pub trait FromIoDesc {
fn from_desc(desc: IoDesc) -> Self;
}
pub trait IoReader { | pub trait IoWriter {
fn write<B: Buf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>>;
fn write_slice(&self, buf: &[u8]) -> MioResult<NonBlock<usize>>;
}
pub trait IoAcceptor {
type Output;
fn accept(&mut self) -> MioResult<NonBlock<Self::Output>>;
}
pub fn pipe() -> MioResult<(PipeReader, PipeWriter)> {
let (rd, wr) = try!(os::pipe());
Ok((PipeReader { desc: rd }, PipeWriter { desc: wr }))
}
pub struct PipeReader {
desc: os::IoDesc
}
impl IoHandle for PipeReader {
fn desc(&self) -> &os::IoDesc {
&self.desc
}
}
impl FromIoDesc for PipeReader {
fn from_desc(desc: IoDesc) -> Self {
PipeReader { desc: desc }
}
}
pub struct PipeWriter {
desc: os::IoDesc
}
impl IoHandle for PipeWriter {
fn desc(&self) -> &os::IoDesc {
&self.desc
}
}
impl FromIoDesc for PipeWriter {
fn from_desc(desc: IoDesc) -> Self {
PipeWriter { desc: desc }
}
}
impl IoReader for PipeReader {
fn read<B: MutBuf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>> {
read(self, buf)
}
fn read_slice(&self, buf: &mut [u8]) -> MioResult<NonBlock<usize>> {
read_slice(self, buf)
}
}
impl IoWriter for PipeWriter {
fn write<B: Buf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>> {
write(self, buf)
}
fn write_slice(&self, buf: &[u8]) -> MioResult<NonBlock<usize>> {
write_slice(self, buf)
}
}
/// Reads the length of the slice supplied by buf.mut_bytes into the buffer
/// This is not guaranteed to consume an entire datagram or segment.
/// If your protocol is msg based (instead of continuous stream) you should
/// ensure that your buffer is large enough to hold an entire segment (1532 bytes if not jumbo
/// frames)
#[inline]
pub fn read<I: IoHandle, B: MutBuf>(io: &I, buf: &mut B) -> MioResult<NonBlock<usize>> {
let res = read_slice(io, buf.mut_bytes());
match res {
// Successfully read some bytes, advance the cursor
Ok(Ready(cnt)) => { buf.advance(cnt); },
_ => {}
}
res
}
///writes the length of the slice supplied by Buf.bytes into the socket
///then advances the buffer that many bytes
#[inline]
pub fn write<O: IoHandle, B: Buf>(io: &O, buf: &mut B) -> MioResult<NonBlock<usize>> {
let res = write_slice(io, buf.bytes());
match res {
Ok(Ready(cnt)) => buf.advance(cnt),
_ => {}
}
res
}
///reads the length of the supplied slice from the socket into the slice
#[inline]
pub fn read_slice<I: IoHandle>(io: & I, buf: &mut [u8]) -> MioResult<NonBlock<usize>> {
match os::read(io.desc(), buf) {
Ok(cnt) => {
Ok(Ready(cnt))
}
Err(e) => {
match e.kind {
mek::WouldBlock => Ok(WouldBlock),
_ => Err(e)
}
}
}
}
///writes the length of the supplied slice into the socket from the slice
#[inline]
pub fn write_slice<I: IoHandle>(io: & I, buf: & [u8]) -> MioResult<NonBlock<usize>> {
match os::write(io.desc(), buf) {
Ok(cnt) => { Ok(Ready(cnt)) }
Err(e) => {
match e.kind {
mek::WouldBlock => Ok(WouldBlock),
_ => Err(e)
}
}
}
} | fn read<B: MutBuf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>>;
fn read_slice(&self, buf: &mut [u8]) -> MioResult<NonBlock<usize>>;
}
| random_line_split |
io.rs | use buf::{Buf, MutBuf};
use error::MioResult;
use self::NonBlock::{Ready, WouldBlock};
use error::MioErrorKind as mek;
use os;
pub use os::IoDesc;
/// The result of a non-blocking operation.
#[derive(Debug)]
pub enum NonBlock<T> {
Ready(T),
WouldBlock
}
impl<T> NonBlock<T> {
pub fn would_block(&self) -> bool {
match *self {
WouldBlock => true,
_ => false
}
}
pub fn unwrap(self) -> T {
match self {
Ready(v) => v,
_ => panic!("would have blocked, no result to take")
}
}
}
pub trait IoHandle {
fn desc(&self) -> &IoDesc;
}
pub trait FromIoDesc {
fn from_desc(desc: IoDesc) -> Self;
}
pub trait IoReader {
fn read<B: MutBuf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>>;
fn read_slice(&self, buf: &mut [u8]) -> MioResult<NonBlock<usize>>;
}
pub trait IoWriter {
fn write<B: Buf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>>;
fn write_slice(&self, buf: &[u8]) -> MioResult<NonBlock<usize>>;
}
pub trait IoAcceptor {
type Output;
fn accept(&mut self) -> MioResult<NonBlock<Self::Output>>;
}
pub fn pipe() -> MioResult<(PipeReader, PipeWriter)> {
let (rd, wr) = try!(os::pipe());
Ok((PipeReader { desc: rd }, PipeWriter { desc: wr }))
}
pub struct PipeReader {
desc: os::IoDesc
}
impl IoHandle for PipeReader {
fn desc(&self) -> &os::IoDesc {
&self.desc
}
}
impl FromIoDesc for PipeReader {
fn from_desc(desc: IoDesc) -> Self {
PipeReader { desc: desc }
}
}
pub struct | {
desc: os::IoDesc
}
impl IoHandle for PipeWriter {
fn desc(&self) -> &os::IoDesc {
&self.desc
}
}
impl FromIoDesc for PipeWriter {
fn from_desc(desc: IoDesc) -> Self {
PipeWriter { desc: desc }
}
}
impl IoReader for PipeReader {
fn read<B: MutBuf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>> {
read(self, buf)
}
fn read_slice(&self, buf: &mut [u8]) -> MioResult<NonBlock<usize>> {
read_slice(self, buf)
}
}
impl IoWriter for PipeWriter {
fn write<B: Buf>(&self, buf: &mut B) -> MioResult<NonBlock<usize>> {
write(self, buf)
}
fn write_slice(&self, buf: &[u8]) -> MioResult<NonBlock<usize>> {
write_slice(self, buf)
}
}
/// Reads the length of the slice supplied by buf.mut_bytes into the buffer
/// This is not guaranteed to consume an entire datagram or segment.
/// If your protocol is msg based (instead of continuous stream) you should
/// ensure that your buffer is large enough to hold an entire segment (1532 bytes if not jumbo
/// frames)
#[inline]
pub fn read<I: IoHandle, B: MutBuf>(io: &I, buf: &mut B) -> MioResult<NonBlock<usize>> {
let res = read_slice(io, buf.mut_bytes());
match res {
// Successfully read some bytes, advance the cursor
Ok(Ready(cnt)) => { buf.advance(cnt); },
_ => {}
}
res
}
///writes the length of the slice supplied by Buf.bytes into the socket
///then advances the buffer that many bytes
#[inline]
pub fn write<O: IoHandle, B: Buf>(io: &O, buf: &mut B) -> MioResult<NonBlock<usize>> {
let res = write_slice(io, buf.bytes());
match res {
Ok(Ready(cnt)) => buf.advance(cnt),
_ => {}
}
res
}
///reads the length of the supplied slice from the socket into the slice
#[inline]
pub fn read_slice<I: IoHandle>(io: & I, buf: &mut [u8]) -> MioResult<NonBlock<usize>> {
match os::read(io.desc(), buf) {
Ok(cnt) => {
Ok(Ready(cnt))
}
Err(e) => {
match e.kind {
mek::WouldBlock => Ok(WouldBlock),
_ => Err(e)
}
}
}
}
///writes the length of the supplied slice into the socket from the slice
#[inline]
pub fn write_slice<I: IoHandle>(io: & I, buf: & [u8]) -> MioResult<NonBlock<usize>> {
match os::write(io.desc(), buf) {
Ok(cnt) => { Ok(Ready(cnt)) }
Err(e) => {
match e.kind {
mek::WouldBlock => Ok(WouldBlock),
_ => Err(e)
}
}
}
}
| PipeWriter | identifier_name |
futures_unordered.rs | use future::{Future, IntoFuture};
use stream::Stream;
use poll::Poll;
use Async;
use stack::{Stack, Drain};
use std::sync::Arc;
use task::{self, UnparkEvent};
use std::prelude::v1::*;
/// An adaptor for a stream of futures to execute the futures concurrently, if
/// possible, delivering results as they become available.
///
/// This adaptor will return their results in the order that they complete.
/// This is created by the `futures` method.
///
#[must_use = "streams do nothing unless polled"]
pub struct FuturesUnordered<F>
where F: Future
{
futures: Vec<Option<F>>,
stack: Arc<Stack<usize>>,
pending: Option<Drain<usize>>,
active: usize,
}
/// Converts a list of futures into a `Stream` of results from the futures.
///
/// This function will take an list of futures (e.g. a vector, an iterator,
/// etc), and return a stream. The stream will yield items as they become
/// available on the futures internally, in the order that they become
/// available. This function is similar to `buffer_unordered` in that it may
/// return items in a different order than in the list specified.
pub fn futures_unordered<I>(futures: I) -> FuturesUnordered<<I::Item as IntoFuture>::Future>
where I: IntoIterator,
I::Item: IntoFuture
{
let futures = futures.into_iter()
.map(IntoFuture::into_future)
.map(Some)
.collect::<Vec<_>>();
let stack = Arc::new(Stack::new());
for i in 0..futures.len() {
stack.push(i);
}
FuturesUnordered {
active: futures.len(),
futures: futures,
pending: None,
stack: stack,
}
}
impl<F> FuturesUnordered<F>
where F: Future
{
fn poll_pending(&mut self, mut drain: Drain<usize>)
-> Option<Poll<Option<F::Item>, F::Error>> | return Some(ret)
}
None
}
}
impl<F> Stream for FuturesUnordered<F>
where F: Future
{
type Item = F::Item;
type Error = F::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
if self.active == 0 {
return Ok(Async::Ready(None))
}
if let Some(drain) = self.pending.take() {
if let Some(ret) = self.poll_pending(drain) {
return ret
}
}
let drain = self.stack.drain();
if let Some(ret) = self.poll_pending(drain) {
return ret
}
assert!(self.active > 0);
Ok(Async::NotReady)
}
}
| {
while let Some(id) = drain.next() {
// If this future was already done just skip the notification
if self.futures[id].is_none() {
continue
}
let event = UnparkEvent::new(self.stack.clone(), id);
let ret = match task::with_unpark_event(event, || {
self.futures[id]
.as_mut()
.unwrap()
.poll()
}) {
Ok(Async::NotReady) => continue,
Ok(Async::Ready(val)) => Ok(Async::Ready(Some(val))),
Err(e) => Err(e),
};
self.pending = Some(drain);
self.active -= 1;
self.futures[id] = None; | identifier_body |
futures_unordered.rs | use future::{Future, IntoFuture};
use stream::Stream;
use poll::Poll;
use Async;
use stack::{Stack, Drain};
use std::sync::Arc;
use task::{self, UnparkEvent};
use std::prelude::v1::*;
/// An adaptor for a stream of futures to execute the futures concurrently, if
/// possible, delivering results as they become available.
///
/// This adaptor will return their results in the order that they complete.
/// This is created by the `futures` method.
///
#[must_use = "streams do nothing unless polled"]
pub struct FuturesUnordered<F>
where F: Future
{
futures: Vec<Option<F>>,
stack: Arc<Stack<usize>>,
pending: Option<Drain<usize>>,
active: usize,
}
/// Converts a list of futures into a `Stream` of results from the futures.
///
/// This function will take an list of futures (e.g. a vector, an iterator,
/// etc), and return a stream. The stream will yield items as they become
/// available on the futures internally, in the order that they become
/// available. This function is similar to `buffer_unordered` in that it may
/// return items in a different order than in the list specified.
pub fn futures_unordered<I>(futures: I) -> FuturesUnordered<<I::Item as IntoFuture>::Future>
where I: IntoIterator,
I::Item: IntoFuture
{
let futures = futures.into_iter()
.map(IntoFuture::into_future)
.map(Some)
.collect::<Vec<_>>();
let stack = Arc::new(Stack::new());
for i in 0..futures.len() {
stack.push(i);
}
FuturesUnordered {
active: futures.len(),
futures: futures,
pending: None,
stack: stack,
}
}
impl<F> FuturesUnordered<F>
where F: Future
{
fn poll_pending(&mut self, mut drain: Drain<usize>)
-> Option<Poll<Option<F::Item>, F::Error>> {
while let Some(id) = drain.next() {
// If this future was already done just skip the notification
if self.futures[id].is_none() {
continue
}
let event = UnparkEvent::new(self.stack.clone(), id);
let ret = match task::with_unpark_event(event, || {
self.futures[id]
.as_mut()
.unwrap()
.poll()
}) {
Ok(Async::NotReady) => continue,
Ok(Async::Ready(val)) => Ok(Async::Ready(Some(val))),
Err(e) => Err(e),
};
self.pending = Some(drain);
self.active -= 1;
self.futures[id] = None;
return Some(ret)
}
None
}
}
impl<F> Stream for FuturesUnordered<F>
where F: Future
{
type Item = F::Item;
type Error = F::Error;
fn | (&mut self) -> Poll<Option<Self::Item>, Self::Error> {
if self.active == 0 {
return Ok(Async::Ready(None))
}
if let Some(drain) = self.pending.take() {
if let Some(ret) = self.poll_pending(drain) {
return ret
}
}
let drain = self.stack.drain();
if let Some(ret) = self.poll_pending(drain) {
return ret
}
assert!(self.active > 0);
Ok(Async::NotReady)
}
}
| poll | identifier_name |
futures_unordered.rs | use future::{Future, IntoFuture};
use stream::Stream;
use poll::Poll;
use Async;
use stack::{Stack, Drain};
use std::sync::Arc;
use task::{self, UnparkEvent};
use std::prelude::v1::*;
/// An adaptor for a stream of futures to execute the futures concurrently, if
/// possible, delivering results as they become available.
///
/// This adaptor will return their results in the order that they complete.
/// This is created by the `futures` method.
///
#[must_use = "streams do nothing unless polled"]
pub struct FuturesUnordered<F> | {
futures: Vec<Option<F>>,
stack: Arc<Stack<usize>>,
pending: Option<Drain<usize>>,
active: usize,
}
/// Converts a list of futures into a `Stream` of results from the futures.
///
/// This function will take an list of futures (e.g. a vector, an iterator,
/// etc), and return a stream. The stream will yield items as they become
/// available on the futures internally, in the order that they become
/// available. This function is similar to `buffer_unordered` in that it may
/// return items in a different order than in the list specified.
pub fn futures_unordered<I>(futures: I) -> FuturesUnordered<<I::Item as IntoFuture>::Future>
where I: IntoIterator,
I::Item: IntoFuture
{
let futures = futures.into_iter()
.map(IntoFuture::into_future)
.map(Some)
.collect::<Vec<_>>();
let stack = Arc::new(Stack::new());
for i in 0..futures.len() {
stack.push(i);
}
FuturesUnordered {
active: futures.len(),
futures: futures,
pending: None,
stack: stack,
}
}
impl<F> FuturesUnordered<F>
where F: Future
{
fn poll_pending(&mut self, mut drain: Drain<usize>)
-> Option<Poll<Option<F::Item>, F::Error>> {
while let Some(id) = drain.next() {
// If this future was already done just skip the notification
if self.futures[id].is_none() {
continue
}
let event = UnparkEvent::new(self.stack.clone(), id);
let ret = match task::with_unpark_event(event, || {
self.futures[id]
.as_mut()
.unwrap()
.poll()
}) {
Ok(Async::NotReady) => continue,
Ok(Async::Ready(val)) => Ok(Async::Ready(Some(val))),
Err(e) => Err(e),
};
self.pending = Some(drain);
self.active -= 1;
self.futures[id] = None;
return Some(ret)
}
None
}
}
impl<F> Stream for FuturesUnordered<F>
where F: Future
{
type Item = F::Item;
type Error = F::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
if self.active == 0 {
return Ok(Async::Ready(None))
}
if let Some(drain) = self.pending.take() {
if let Some(ret) = self.poll_pending(drain) {
return ret
}
}
let drain = self.stack.drain();
if let Some(ret) = self.poll_pending(drain) {
return ret
}
assert!(self.active > 0);
Ok(Async::NotReady)
}
} | where F: Future | random_line_split |
camera.rs | extern crate mithril;
use std::f64;
use std::num::Float;
use self::mithril::math::{ Vector, Quaternion };
pub struct Camera {
position: Vector,
focus_point: Vector,
up: Vector,
field_of_view: f64,
aspect_ratio: f64,
far: f64,
near: f64,
anchor_point: Option<[f64; 2]>,
control_point: [f64; 2],
}
impl Camera {
pub fn | (position: Vector, focus_point: Vector, up: Vector) -> Camera {
Camera{
position: position,
focus_point: focus_point,
up: up.normalize(),
field_of_view: (90.0 * f64::consts::PI / 180.0),
aspect_ratio: 640.0/480.0,
far: 100.0,
near: 1.0,
anchor_point: None,
control_point: [0.0; 2],
}
}
pub fn position(&self) -> Vector {
self.position
}
pub fn focus_point(&self) -> Vector {
self.focus_point
}
pub fn go_to(&mut self, position: Vector) {
self.position = position;
}
pub fn update(&mut self) {
}
pub fn start_control(&mut self, x: f64, y: f64) {
self.anchor_point = Some([x, y]);
self.control_point[0] = x;
self.control_point[1] = y;
}
pub fn set_control_point(&mut self, x: f64, y: f64) {
self.control_point[0] = x;
self.control_point[1] = y;
}
pub fn release_controls(&mut self) {
self.anchor_point = None;
}
pub fn is_controlled(&self) -> bool {
self.anchor_point!= None
}
pub fn view_matrix(&self) -> [f32; 16] {
let mut z_view = (self.position - self.focus_point).normalize();
let mut x_view = self.up.cross(z_view).normalize();
let mut y_view = z_view.cross(x_view).normalize();
let x_trans = -self.position.dot(x_view);
let y_trans = -self.position.dot(y_view);
let z_trans = -self.position.dot(z_view);
match self.anchor_point {
Some(anchor_point) => {
let diff = [
(self.control_point[1] - anchor_point[1]) as f32,
(anchor_point[0] - self.control_point[0]) as f32,
];
let diff_sq = (diff[0] * diff[0] + diff[1] * diff[1]).sqrt();
if diff_sq > 0.0001 {
let diff_length = diff_sq.sqrt();
let rot_axis = (x_view * diff[0] + y_view * diff[1]) / diff_length;
let rot_in_radians = diff_length * 2.0;
let u_quat = Quaternion::new(0.0, x_view[0], x_view[1], x_view[2]);
let v_quat = Quaternion::new(0.0, y_view[0], y_view[1], y_view[2]);
let w_quat = Quaternion::new(0.0, z_view[0], z_view[1], z_view[2]);
let rot_quat = Quaternion::new_from_rotation(rot_in_radians, rot_axis[0], rot_axis[1], rot_axis[2]);
let new_u_quat = rot_quat * u_quat * rot_quat.inverse();
let new_v_quat = rot_quat * v_quat * rot_quat.inverse();
let new_w_quat = rot_quat * w_quat * rot_quat.inverse();
x_view[0] = new_u_quat[1];
x_view[1] = new_u_quat[2];
x_view[2] = new_u_quat[3];
y_view[0] = new_v_quat[1];
y_view[1] = new_v_quat[2];
y_view[2] = new_v_quat[3];
z_view[0] = new_w_quat[1];
z_view[1] = new_w_quat[2];
z_view[2] = new_w_quat[3];
}
}
None => {
// do nothing
}
}
[
x_view[0], x_view[1], x_view[2], x_trans,
y_view[0], y_view[1], y_view[2], y_trans,
z_view[0], z_view[1], z_view[2], z_trans,
0.0, 0.0, 0.0, 1.0,
]
}
pub fn projection_matrix(&self) -> [f32; 16] {
let m_11 = (1.0 / (self.field_of_view / 2.0).tan()) as f32;
let m_22 = m_11 * (self.aspect_ratio as f32);
let m_33 = -((self.far + self.near) / (self.far - self.near)) as f32;
let m_43 = -((2.0 * self.far * self.near) / (self.far - self.near)) as f32;
[
m_11, 0.0, 0.0, 0.0,
0.0, m_22, 0.0, 0.0,
0.0, 0.0, m_33, m_43,
0.0, 0.0, -1.0, 0.0,
]
}
}
| new | identifier_name |
camera.rs | extern crate mithril;
use std::f64;
use std::num::Float;
use self::mithril::math::{ Vector, Quaternion };
pub struct Camera {
position: Vector,
focus_point: Vector,
up: Vector,
field_of_view: f64,
aspect_ratio: f64,
far: f64,
near: f64,
anchor_point: Option<[f64; 2]>,
control_point: [f64; 2],
}
impl Camera {
pub fn new(position: Vector, focus_point: Vector, up: Vector) -> Camera {
Camera{
position: position,
focus_point: focus_point,
up: up.normalize(),
field_of_view: (90.0 * f64::consts::PI / 180.0),
aspect_ratio: 640.0/480.0,
far: 100.0,
near: 1.0,
anchor_point: None,
control_point: [0.0; 2],
}
}
pub fn position(&self) -> Vector {
self.position
}
pub fn focus_point(&self) -> Vector {
self.focus_point
}
pub fn go_to(&mut self, position: Vector) {
self.position = position;
}
pub fn update(&mut self) {
}
pub fn start_control(&mut self, x: f64, y: f64) {
self.anchor_point = Some([x, y]);
self.control_point[0] = x;
self.control_point[1] = y;
}
pub fn set_control_point(&mut self, x: f64, y: f64) {
self.control_point[0] = x;
self.control_point[1] = y;
}
pub fn release_controls(&mut self) {
self.anchor_point = None;
}
pub fn is_controlled(&self) -> bool {
self.anchor_point!= None
}
pub fn view_matrix(&self) -> [f32; 16] {
let mut z_view = (self.position - self.focus_point).normalize();
let mut x_view = self.up.cross(z_view).normalize();
let mut y_view = z_view.cross(x_view).normalize();
let x_trans = -self.position.dot(x_view);
let y_trans = -self.position.dot(y_view);
let z_trans = -self.position.dot(z_view);
match self.anchor_point {
Some(anchor_point) => | x_view[0] = new_u_quat[1];
x_view[1] = new_u_quat[2];
x_view[2] = new_u_quat[3];
y_view[0] = new_v_quat[1];
y_view[1] = new_v_quat[2];
y_view[2] = new_v_quat[3];
z_view[0] = new_w_quat[1];
z_view[1] = new_w_quat[2];
z_view[2] = new_w_quat[3];
}
}
None => {
// do nothing
}
}
[
x_view[0], x_view[1], x_view[2], x_trans,
y_view[0], y_view[1], y_view[2], y_trans,
z_view[0], z_view[1], z_view[2], z_trans,
0.0, 0.0, 0.0, 1.0,
]
}
pub fn projection_matrix(&self) -> [f32; 16] {
let m_11 = (1.0 / (self.field_of_view / 2.0).tan()) as f32;
let m_22 = m_11 * (self.aspect_ratio as f32);
let m_33 = -((self.far + self.near) / (self.far - self.near)) as f32;
let m_43 = -((2.0 * self.far * self.near) / (self.far - self.near)) as f32;
[
m_11, 0.0, 0.0, 0.0,
0.0, m_22, 0.0, 0.0,
0.0, 0.0, m_33, m_43,
0.0, 0.0, -1.0, 0.0,
]
}
}
| {
let diff = [
(self.control_point[1] - anchor_point[1]) as f32,
(anchor_point[0] - self.control_point[0]) as f32,
];
let diff_sq = (diff[0] * diff[0] + diff[1] * diff[1]).sqrt();
if diff_sq > 0.0001 {
let diff_length = diff_sq.sqrt();
let rot_axis = (x_view * diff[0] + y_view * diff[1]) / diff_length;
let rot_in_radians = diff_length * 2.0;
let u_quat = Quaternion::new(0.0, x_view[0], x_view[1], x_view[2]);
let v_quat = Quaternion::new(0.0, y_view[0], y_view[1], y_view[2]);
let w_quat = Quaternion::new(0.0, z_view[0], z_view[1], z_view[2]);
let rot_quat = Quaternion::new_from_rotation(rot_in_radians, rot_axis[0], rot_axis[1], rot_axis[2]);
let new_u_quat = rot_quat * u_quat * rot_quat.inverse();
let new_v_quat = rot_quat * v_quat * rot_quat.inverse();
let new_w_quat = rot_quat * w_quat * rot_quat.inverse(); | conditional_block |
camera.rs | extern crate mithril;
use std::f64;
use std::num::Float;
use self::mithril::math::{ Vector, Quaternion };
pub struct Camera {
position: Vector,
focus_point: Vector,
up: Vector,
field_of_view: f64,
aspect_ratio: f64,
far: f64,
near: f64,
anchor_point: Option<[f64; 2]>,
control_point: [f64; 2],
}
impl Camera {
pub fn new(position: Vector, focus_point: Vector, up: Vector) -> Camera {
Camera{
position: position,
focus_point: focus_point,
up: up.normalize(),
field_of_view: (90.0 * f64::consts::PI / 180.0),
aspect_ratio: 640.0/480.0,
far: 100.0,
near: 1.0,
anchor_point: None,
control_point: [0.0; 2],
}
}
pub fn position(&self) -> Vector {
self.position
}
pub fn focus_point(&self) -> Vector {
self.focus_point
}
pub fn go_to(&mut self, position: Vector) {
self.position = position;
}
pub fn update(&mut self) {
}
pub fn start_control(&mut self, x: f64, y: f64) {
self.anchor_point = Some([x, y]);
self.control_point[0] = x;
self.control_point[1] = y;
}
pub fn set_control_point(&mut self, x: f64, y: f64) |
pub fn release_controls(&mut self) {
self.anchor_point = None;
}
pub fn is_controlled(&self) -> bool {
self.anchor_point!= None
}
pub fn view_matrix(&self) -> [f32; 16] {
let mut z_view = (self.position - self.focus_point).normalize();
let mut x_view = self.up.cross(z_view).normalize();
let mut y_view = z_view.cross(x_view).normalize();
let x_trans = -self.position.dot(x_view);
let y_trans = -self.position.dot(y_view);
let z_trans = -self.position.dot(z_view);
match self.anchor_point {
Some(anchor_point) => {
let diff = [
(self.control_point[1] - anchor_point[1]) as f32,
(anchor_point[0] - self.control_point[0]) as f32,
];
let diff_sq = (diff[0] * diff[0] + diff[1] * diff[1]).sqrt();
if diff_sq > 0.0001 {
let diff_length = diff_sq.sqrt();
let rot_axis = (x_view * diff[0] + y_view * diff[1]) / diff_length;
let rot_in_radians = diff_length * 2.0;
let u_quat = Quaternion::new(0.0, x_view[0], x_view[1], x_view[2]);
let v_quat = Quaternion::new(0.0, y_view[0], y_view[1], y_view[2]);
let w_quat = Quaternion::new(0.0, z_view[0], z_view[1], z_view[2]);
let rot_quat = Quaternion::new_from_rotation(rot_in_radians, rot_axis[0], rot_axis[1], rot_axis[2]);
let new_u_quat = rot_quat * u_quat * rot_quat.inverse();
let new_v_quat = rot_quat * v_quat * rot_quat.inverse();
let new_w_quat = rot_quat * w_quat * rot_quat.inverse();
x_view[0] = new_u_quat[1];
x_view[1] = new_u_quat[2];
x_view[2] = new_u_quat[3];
y_view[0] = new_v_quat[1];
y_view[1] = new_v_quat[2];
y_view[2] = new_v_quat[3];
z_view[0] = new_w_quat[1];
z_view[1] = new_w_quat[2];
z_view[2] = new_w_quat[3];
}
}
None => {
// do nothing
}
}
[
x_view[0], x_view[1], x_view[2], x_trans,
y_view[0], y_view[1], y_view[2], y_trans,
z_view[0], z_view[1], z_view[2], z_trans,
0.0, 0.0, 0.0, 1.0,
]
}
pub fn projection_matrix(&self) -> [f32; 16] {
let m_11 = (1.0 / (self.field_of_view / 2.0).tan()) as f32;
let m_22 = m_11 * (self.aspect_ratio as f32);
let m_33 = -((self.far + self.near) / (self.far - self.near)) as f32;
let m_43 = -((2.0 * self.far * self.near) / (self.far - self.near)) as f32;
[
m_11, 0.0, 0.0, 0.0,
0.0, m_22, 0.0, 0.0,
0.0, 0.0, m_33, m_43,
0.0, 0.0, -1.0, 0.0,
]
}
}
| {
self.control_point[0] = x;
self.control_point[1] = y;
} | identifier_body |
camera.rs | extern crate mithril;
use std::f64;
use std::num::Float;
use self::mithril::math::{ Vector, Quaternion };
pub struct Camera {
position: Vector,
focus_point: Vector,
up: Vector,
field_of_view: f64,
aspect_ratio: f64,
far: f64,
near: f64,
anchor_point: Option<[f64; 2]>,
control_point: [f64; 2],
}
impl Camera {
pub fn new(position: Vector, focus_point: Vector, up: Vector) -> Camera {
Camera{
position: position,
focus_point: focus_point,
up: up.normalize(),
field_of_view: (90.0 * f64::consts::PI / 180.0),
aspect_ratio: 640.0/480.0,
far: 100.0,
near: 1.0,
anchor_point: None,
control_point: [0.0; 2],
}
}
pub fn position(&self) -> Vector {
self.position | self.focus_point
}
pub fn go_to(&mut self, position: Vector) {
self.position = position;
}
pub fn update(&mut self) {
}
pub fn start_control(&mut self, x: f64, y: f64) {
self.anchor_point = Some([x, y]);
self.control_point[0] = x;
self.control_point[1] = y;
}
pub fn set_control_point(&mut self, x: f64, y: f64) {
self.control_point[0] = x;
self.control_point[1] = y;
}
pub fn release_controls(&mut self) {
self.anchor_point = None;
}
pub fn is_controlled(&self) -> bool {
self.anchor_point!= None
}
pub fn view_matrix(&self) -> [f32; 16] {
let mut z_view = (self.position - self.focus_point).normalize();
let mut x_view = self.up.cross(z_view).normalize();
let mut y_view = z_view.cross(x_view).normalize();
let x_trans = -self.position.dot(x_view);
let y_trans = -self.position.dot(y_view);
let z_trans = -self.position.dot(z_view);
match self.anchor_point {
Some(anchor_point) => {
let diff = [
(self.control_point[1] - anchor_point[1]) as f32,
(anchor_point[0] - self.control_point[0]) as f32,
];
let diff_sq = (diff[0] * diff[0] + diff[1] * diff[1]).sqrt();
if diff_sq > 0.0001 {
let diff_length = diff_sq.sqrt();
let rot_axis = (x_view * diff[0] + y_view * diff[1]) / diff_length;
let rot_in_radians = diff_length * 2.0;
let u_quat = Quaternion::new(0.0, x_view[0], x_view[1], x_view[2]);
let v_quat = Quaternion::new(0.0, y_view[0], y_view[1], y_view[2]);
let w_quat = Quaternion::new(0.0, z_view[0], z_view[1], z_view[2]);
let rot_quat = Quaternion::new_from_rotation(rot_in_radians, rot_axis[0], rot_axis[1], rot_axis[2]);
let new_u_quat = rot_quat * u_quat * rot_quat.inverse();
let new_v_quat = rot_quat * v_quat * rot_quat.inverse();
let new_w_quat = rot_quat * w_quat * rot_quat.inverse();
x_view[0] = new_u_quat[1];
x_view[1] = new_u_quat[2];
x_view[2] = new_u_quat[3];
y_view[0] = new_v_quat[1];
y_view[1] = new_v_quat[2];
y_view[2] = new_v_quat[3];
z_view[0] = new_w_quat[1];
z_view[1] = new_w_quat[2];
z_view[2] = new_w_quat[3];
}
}
None => {
// do nothing
}
}
[
x_view[0], x_view[1], x_view[2], x_trans,
y_view[0], y_view[1], y_view[2], y_trans,
z_view[0], z_view[1], z_view[2], z_trans,
0.0, 0.0, 0.0, 1.0,
]
}
pub fn projection_matrix(&self) -> [f32; 16] {
let m_11 = (1.0 / (self.field_of_view / 2.0).tan()) as f32;
let m_22 = m_11 * (self.aspect_ratio as f32);
let m_33 = -((self.far + self.near) / (self.far - self.near)) as f32;
let m_43 = -((2.0 * self.far * self.near) / (self.far - self.near)) as f32;
[
m_11, 0.0, 0.0, 0.0,
0.0, m_22, 0.0, 0.0,
0.0, 0.0, m_33, m_43,
0.0, 0.0, -1.0, 0.0,
]
}
} | }
pub fn focus_point(&self) -> Vector { | random_line_split |
generic-temporary.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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
fn mk() -> isize { return 1; }
fn chk(a: isize) { println!("{}", a); assert_eq!(a, 1); }
fn apply<T>(produce: fn() -> T,
consume: fn(T)) {
consume(produce());
}
pub fn | () {
let produce: fn() -> isize = mk;
let consume: fn(v: isize) = chk;
apply::<isize>(produce, consume);
}
| main | identifier_name |
generic-temporary.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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
fn mk() -> isize |
fn chk(a: isize) { println!("{}", a); assert_eq!(a, 1); }
fn apply<T>(produce: fn() -> T,
consume: fn(T)) {
consume(produce());
}
pub fn main() {
let produce: fn() -> isize = mk;
let consume: fn(v: isize) = chk;
apply::<isize>(produce, consume);
}
| { return 1; } | identifier_body |
generic-temporary.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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
fn mk() -> isize { return 1; } |
fn apply<T>(produce: fn() -> T,
consume: fn(T)) {
consume(produce());
}
pub fn main() {
let produce: fn() -> isize = mk;
let consume: fn(v: isize) = chk;
apply::<isize>(produce, consume);
} |
fn chk(a: isize) { println!("{}", a); assert_eq!(a, 1); } | random_line_split |
main.rs | //! Initium is a modern bootloader with no legacy components.
#![no_std]
#![no_main]
#![feature(asm)]
#![feature(try_trait)]
#![feature(abi_efiapi)]
#![feature(global_asm)]
#![feature(const_mut_refs)]
#![feature(num_as_ne_bytes)]
#![feature(in_band_lifetimes)]
#![feature(panic_info_message)]
#![feature(alloc_error_handler)]
use alloc::{boxed::Box, string::String, vec::Vec};
use console::get_console_out;
use ui::{ChoiceEntry, ListWindow};
use common::{command_manager::get_command_manager, BuiltinCommand};
extern crate alloc;
#[macro_use]
extern crate log;
extern crate common;
// HAL(Hardware Abstraction Layer)
#[macro_use]
mod platform;
mod config;
mod console;
mod device;
mod disk;
mod line_editor;
mod shell;
mod ui;
#[no_mangle]
pub fn loader_main() {
use crate::alloc::string::ToString;
// init console
get_console_out().init();
device::init();
register_commands();
// TODO: this is a simple test is to be removed on the future
let mut window = ListWindow::new("Boot Menu".to_string(), false);
// create a list of entries
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice".to_string(),
}),
false,
);
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice 2".to_string(),
}),
false,
);
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice 3".to_string(),
}),
false,
);
{
let console = get_console_out();
window.render(console, 0);
}
// TODO: remove this as soon as we have the environment loader implemented
loop {}
}
/// Register about command
fn register_commands() {
let command_manager = get_command_manager();
command_manager.add_command(BuiltinCommand {
name: "about",
description: "Shows the bootloader version",
func: about_command,
});
// we can't implement the 'help' command on the common crate since the println! macro isn't available there
command_manager.add_command(BuiltinCommand {
name: "help",
description: "List all available commands",
func: help_command,
});
command_manager.add_command(BuiltinCommand {
name: "reboot",
description: "Reboot the system",
func: reboot_command,
});
}
/// Reboot platform
fn reboot_command(_: Vec<String>) -> bool {
self::platform::target_reboot();
}
/// Show current Initium version
fn about_command(_: Vec<String>) -> bool {
println!("Initium version {}", env!("CARGO_PKG_VERSION"));
true
}
/// Show all available commands
fn help_command(_: Vec<String>) -> bool {
let manager = get_command_manager();
println!("Command Description");
println!("------- -----------");
manager.get_commands().iter().for_each(|c| {
println!("{:<16} {}", &c.name, &c.description);
});
true
}
#[panic_handler]
fn panic_handler(info: &core::panic::PanicInfo) ->! | {
if let Some(location) = info.location() {
error!(
"Panic in {} at ({}, {}):",
location.file(),
location.line(),
location.column()
);
if let Some(message) = info.message() {
error!("{}", message);
}
}
// TODO: halt in a way that makes sense for the platform
loop {}
} | identifier_body |
|
main.rs | //! Initium is a modern bootloader with no legacy components.
#![no_std]
#![no_main]
#![feature(asm)]
#![feature(try_trait)]
#![feature(abi_efiapi)]
#![feature(global_asm)]
#![feature(const_mut_refs)]
#![feature(num_as_ne_bytes)]
#![feature(in_band_lifetimes)]
#![feature(panic_info_message)]
#![feature(alloc_error_handler)]
use alloc::{boxed::Box, string::String, vec::Vec};
use console::get_console_out;
use ui::{ChoiceEntry, ListWindow};
use common::{command_manager::get_command_manager, BuiltinCommand};
extern crate alloc;
#[macro_use]
extern crate log;
extern crate common;
// HAL(Hardware Abstraction Layer)
#[macro_use]
mod platform;
mod config;
mod console;
mod device;
mod disk;
mod line_editor;
mod shell;
mod ui; | #[no_mangle]
pub fn loader_main() {
use crate::alloc::string::ToString;
// init console
get_console_out().init();
device::init();
register_commands();
// TODO: this is a simple test is to be removed on the future
let mut window = ListWindow::new("Boot Menu".to_string(), false);
// create a list of entries
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice".to_string(),
}),
false,
);
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice 2".to_string(),
}),
false,
);
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice 3".to_string(),
}),
false,
);
{
let console = get_console_out();
window.render(console, 0);
}
// TODO: remove this as soon as we have the environment loader implemented
loop {}
}
/// Register about command
fn register_commands() {
let command_manager = get_command_manager();
command_manager.add_command(BuiltinCommand {
name: "about",
description: "Shows the bootloader version",
func: about_command,
});
// we can't implement the 'help' command on the common crate since the println! macro isn't available there
command_manager.add_command(BuiltinCommand {
name: "help",
description: "List all available commands",
func: help_command,
});
command_manager.add_command(BuiltinCommand {
name: "reboot",
description: "Reboot the system",
func: reboot_command,
});
}
/// Reboot platform
fn reboot_command(_: Vec<String>) -> bool {
self::platform::target_reboot();
}
/// Show current Initium version
fn about_command(_: Vec<String>) -> bool {
println!("Initium version {}", env!("CARGO_PKG_VERSION"));
true
}
/// Show all available commands
fn help_command(_: Vec<String>) -> bool {
let manager = get_command_manager();
println!("Command Description");
println!("------- -----------");
manager.get_commands().iter().for_each(|c| {
println!("{:<16} {}", &c.name, &c.description);
});
true
}
#[panic_handler]
fn panic_handler(info: &core::panic::PanicInfo) ->! {
if let Some(location) = info.location() {
error!(
"Panic in {} at ({}, {}):",
location.file(),
location.line(),
location.column()
);
if let Some(message) = info.message() {
error!("{}", message);
}
}
// TODO: halt in a way that makes sense for the platform
loop {}
} | random_line_split |
|
main.rs | //! Initium is a modern bootloader with no legacy components.
#![no_std]
#![no_main]
#![feature(asm)]
#![feature(try_trait)]
#![feature(abi_efiapi)]
#![feature(global_asm)]
#![feature(const_mut_refs)]
#![feature(num_as_ne_bytes)]
#![feature(in_band_lifetimes)]
#![feature(panic_info_message)]
#![feature(alloc_error_handler)]
use alloc::{boxed::Box, string::String, vec::Vec};
use console::get_console_out;
use ui::{ChoiceEntry, ListWindow};
use common::{command_manager::get_command_manager, BuiltinCommand};
extern crate alloc;
#[macro_use]
extern crate log;
extern crate common;
// HAL(Hardware Abstraction Layer)
#[macro_use]
mod platform;
mod config;
mod console;
mod device;
mod disk;
mod line_editor;
mod shell;
mod ui;
#[no_mangle]
pub fn loader_main() {
use crate::alloc::string::ToString;
// init console
get_console_out().init();
device::init();
register_commands();
// TODO: this is a simple test is to be removed on the future
let mut window = ListWindow::new("Boot Menu".to_string(), false);
// create a list of entries
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice".to_string(),
}),
false,
);
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice 2".to_string(),
}),
false,
);
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice 3".to_string(),
}),
false,
);
{
let console = get_console_out();
window.render(console, 0);
}
// TODO: remove this as soon as we have the environment loader implemented
loop {}
}
/// Register about command
fn register_commands() {
let command_manager = get_command_manager();
command_manager.add_command(BuiltinCommand {
name: "about",
description: "Shows the bootloader version",
func: about_command,
});
// we can't implement the 'help' command on the common crate since the println! macro isn't available there
command_manager.add_command(BuiltinCommand {
name: "help",
description: "List all available commands",
func: help_command,
});
command_manager.add_command(BuiltinCommand {
name: "reboot",
description: "Reboot the system",
func: reboot_command,
});
}
/// Reboot platform
fn reboot_command(_: Vec<String>) -> bool {
self::platform::target_reboot();
}
/// Show current Initium version
fn about_command(_: Vec<String>) -> bool {
println!("Initium version {}", env!("CARGO_PKG_VERSION"));
true
}
/// Show all available commands
fn help_command(_: Vec<String>) -> bool {
let manager = get_command_manager();
println!("Command Description");
println!("------- -----------");
manager.get_commands().iter().for_each(|c| {
println!("{:<16} {}", &c.name, &c.description);
});
true
}
#[panic_handler]
fn | (info: &core::panic::PanicInfo) ->! {
if let Some(location) = info.location() {
error!(
"Panic in {} at ({}, {}):",
location.file(),
location.line(),
location.column()
);
if let Some(message) = info.message() {
error!("{}", message);
}
}
// TODO: halt in a way that makes sense for the platform
loop {}
}
| panic_handler | identifier_name |
main.rs | //! Initium is a modern bootloader with no legacy components.
#![no_std]
#![no_main]
#![feature(asm)]
#![feature(try_trait)]
#![feature(abi_efiapi)]
#![feature(global_asm)]
#![feature(const_mut_refs)]
#![feature(num_as_ne_bytes)]
#![feature(in_band_lifetimes)]
#![feature(panic_info_message)]
#![feature(alloc_error_handler)]
use alloc::{boxed::Box, string::String, vec::Vec};
use console::get_console_out;
use ui::{ChoiceEntry, ListWindow};
use common::{command_manager::get_command_manager, BuiltinCommand};
extern crate alloc;
#[macro_use]
extern crate log;
extern crate common;
// HAL(Hardware Abstraction Layer)
#[macro_use]
mod platform;
mod config;
mod console;
mod device;
mod disk;
mod line_editor;
mod shell;
mod ui;
#[no_mangle]
pub fn loader_main() {
use crate::alloc::string::ToString;
// init console
get_console_out().init();
device::init();
register_commands();
// TODO: this is a simple test is to be removed on the future
let mut window = ListWindow::new("Boot Menu".to_string(), false);
// create a list of entries
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice".to_string(),
}),
false,
);
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice 2".to_string(),
}),
false,
);
window.add_list(
Box::new(ChoiceEntry {
label: "Example OS Choice 3".to_string(),
}),
false,
);
{
let console = get_console_out();
window.render(console, 0);
}
// TODO: remove this as soon as we have the environment loader implemented
loop {}
}
/// Register about command
fn register_commands() {
let command_manager = get_command_manager();
command_manager.add_command(BuiltinCommand {
name: "about",
description: "Shows the bootloader version",
func: about_command,
});
// we can't implement the 'help' command on the common crate since the println! macro isn't available there
command_manager.add_command(BuiltinCommand {
name: "help",
description: "List all available commands",
func: help_command,
});
command_manager.add_command(BuiltinCommand {
name: "reboot",
description: "Reboot the system",
func: reboot_command,
});
}
/// Reboot platform
fn reboot_command(_: Vec<String>) -> bool {
self::platform::target_reboot();
}
/// Show current Initium version
fn about_command(_: Vec<String>) -> bool {
println!("Initium version {}", env!("CARGO_PKG_VERSION"));
true
}
/// Show all available commands
fn help_command(_: Vec<String>) -> bool {
let manager = get_command_manager();
println!("Command Description");
println!("------- -----------");
manager.get_commands().iter().for_each(|c| {
println!("{:<16} {}", &c.name, &c.description);
});
true
}
#[panic_handler]
fn panic_handler(info: &core::panic::PanicInfo) ->! {
if let Some(location) = info.location() |
// TODO: halt in a way that makes sense for the platform
loop {}
}
| {
error!(
"Panic in {} at ({}, {}):",
location.file(),
location.line(),
location.column()
);
if let Some(message) = info.message() {
error!("{}", message);
}
} | conditional_block |
parser.rs | //! A simple parser for a tiny subset of HTML and CSS.
use std::ascii::OwnedStrAsciiExt; // for `into_ascii_lower`
use std::collections::hashmap::HashMap;
use std::num::FromStrRadix;
use css::{Stylesheet,Rule,Selector,Simple,SimpleSelector,Declaration,Value,Keyword,Length,Unit,Color,Px};
use dom;
/// Parse an HTML document and return the root element.
pub fn parse_html(source: String) -> dom::Node {
let mut nodes = Parser { pos: 0u, input: source }.parse_nodes();
// If the document contains a root element, just return it. Otherwise create one.
if nodes.len() == 1 {
nodes.swap_remove(0).unwrap()
} else {
dom::elem("html".to_string(), HashMap::new(), nodes)
}
}
/// Parse a whole CSS stylesheet.
pub fn parse_css(source: String) -> Stylesheet {
let mut parser = Parser { pos: 0u, input: source };
Stylesheet { rules: parser.parse_rules() }
}
struct Parser {
pos: uint,
input: String,
}
impl Parser {
/// Read the next character without consuming it.
fn next_char(&self) -> char {
self.input.as_slice().char_at(self.pos)
}
/// Do the next characters start with the given string?
fn starts_with(&self, s: &str) -> bool {
self.input.as_slice().slice_from(self.pos).starts_with(s)
}
/// Return true if all input is consumed.
fn eof(&self) -> bool {
self.pos >= self.input.len()
}
/// Return the current character and advance to the next character.
fn consume_char(&mut self) -> char {
let range = self.input.as_slice().char_range_at(self.pos);
self.pos = range.next;
range.ch
}
/// Consume characters until `test` returns false.
fn consume_while(&mut self, test: |char| -> bool) -> String {
let mut result = String::new();
while!self.eof() && test(self.next_char()) {
result.push_char(self.consume_char());
}
result
}
/// Consume and discard zero or more whitespace
fn consume_whitespace(&mut self) {
self.consume_while(|c| c.is_whitespace());
}
// HTML parsing
/// Parse a tag or attribute name.
fn parse_tag_name(&mut self) -> String {
self.consume_while(|c| match c {
'a'..'z' | 'A'..'Z' | '0'..'9' => true,
_ => false
})
}
/// Parse a single node.
fn parse_node(&mut self) -> dom::Node {
match self.next_char() {
'<' => self.parse_element(),
_ => self.parse_text()
}
}
/// Parse a text node.
fn parse_text(&mut self) -> dom::Node {
dom::text(self.consume_while(|c| c!= '<'))
}
/// Parse a single element inlcuding its open tag, contents and closing tag.
fn parse_element(&mut self) -> dom::Node {
// Opening tag
assert!(self.consume_char() == '<');
let tag_name = self.parse_tag_name();
let attrs = self.parse_attributes();
assert!(self.consume_char() == '>');
// Contents
let children = self.parse_nodes();
// Closing tag
assert!(self.consume_char() == '<');
assert!(self.consume_char() == '/');
assert!(self.parse_tag_name() == tag_name);
assert!(self.consume_char() == '>');
dom::elem(tag_name, attrs, children)
}
/// Parse a single name="value" pair.
fn parse_attr(&mut self) -> (String, String) {
let name = self.parse_tag_name();
assert!(self.consume_char() == '=');
let value = self.parse_attr_value();
(name, value)
}
/// Parse a quoted value.
fn parse_attr_value(&mut self) -> String {
let open_quote = self.consume_char();
assert!(open_quote == '"' || open_quote == '\'');
let value = self.consume_while(|c| c!= open_quote);
assert!(self.consume_char() == open_quote);
value
}
/// Parse attributes.
fn parse_attributes(&mut self) -> dom::AttrMap {
let mut attributes = HashMap::new();
loop {
self.consume_whitespace();
if self.next_char() == '>' {
break;
}
let (name, value) = self.parse_attr();
attributes.insert(name, value);
}
attributes
}
/// Parse a sequence of sibling nodes.
fn parse_nodes(&mut self) -> Vec<dom::Node> {
let mut nodes = vec!();
loop {
self.consume_whitespace();
if self.eof() || self.starts_with("</") {
break;
}
nodes.push(self.parse_node());
}
nodes
}
// Parse CSS | let mut rules = Vec::new();
loop {
self.consume_whitespace();
if self.eof() {
break;
}
rules.push(self.parse_rule());
}
rules
}
/// Parse a rule set: `<selectors> { <declarations> }`.
fn parse_rule(&mut self) -> Rule {
Rule {
selectors: self.parse_selectors(),
declarations: self.parse_declarations(),
}
}
// Parse a comma separated list of selectors.
fn parse_selectors(&mut self) -> Vec<Selector> {
let mut selectors = Vec::new();
loop {
selectors.push(Simple(self.parse_simple_selector()));
self.consume_whitespace();
match self.next_char() {
',' => {
self.consume_char();
self.consume_whitespace()
}
'{' => break,
c => fail!("Unexpected character {} in selector list", c)
}
}
// Sort by specificity (highest first)
selectors.sort_by(|a, b| b.specificity().cmp(&a.specificity()));
selectors
}
/// Parse one simple selector, e.g.: `type#id.class1.class2.classn`
fn parse_simple_selector(&mut self) -> SimpleSelector {
let mut selector = SimpleSelector { tag_name: None, id: None, class: Vec::new() };
while!self.eof() {
match self.next_char() {
'#' => {
self.consume_char();
selector.id = Some(self.parse_identifier());
}
'.' => {
self.consume_char();
selector.class.push(self.parse_identifier());
}
'*' => {
// universal selector
self.consume_char();
}
c if valid_identifier_char(c) => {
selector.tag_name = Some(self.parse_identifier());
}
_ => break
}
}
selector
}
/// Parse a list of declarations enclosed by `{ }`.
fn parse_declarations(&mut self) -> Vec<Declaration> {
let mut declarations = Vec::new();
assert!(self.consume_char() == '{');
loop {
self.consume_whitespace();
if self.next_char() == '}' {
self.consume_char();
break;
}
declarations.push(self.parse_declaration());
}
declarations
}
/// Parse a `<property>: <value>;` declaration.
fn parse_declaration(&mut self) -> Declaration {
let property_name = self.parse_identifier();
self.consume_whitespace();
assert!(self.consume_char() == ':');
self.consume_whitespace();
let value = self.parse_value();
self.consume_whitespace();
assert!(self.consume_char() == ';');
Declaration {
name: property_name,
value: value,
}
}
/// Parse a value
fn parse_value(&mut self) -> Value {
match self.next_char() {
'0'..'9' => self.parse_length(),
'#' => self.parse_color(),
_ => Keyword(self.parse_identifier())
}
}
fn parse_length(&mut self) -> Value {
Length(self.parse_float(), self.parse_unit())
}
fn parse_float(&mut self) -> f32 {
let s = self.consume_while(|c| match c {
'0'..'9' | '.' => true,
_ => false
});
let f: Option<f32> = from_str(s.as_slice());
f.unwrap()
}
fn parse_unit(&mut self) -> Unit {
match self.parse_identifier().into_ascii_lower().as_slice() {
"px" => Px,
_ => fail!("unrecognized unit")
}
}
fn parse_color(&mut self) -> Value {
assert!(self.consume_char() == '#');
Color(self.parse_hex_pair(), self.parse_hex_pair(), self.parse_hex_pair(), 255)
}
fn parse_hex_pair(&mut self) -> u8 {
let s = self.input.as_slice().slice(self.pos, self.pos + 2);
self.pos = self.pos + 2;
FromStrRadix::from_str_radix(s, 16).unwrap()
}
fn parse_identifier(&mut self) -> String {
self.consume_while(valid_identifier_char)
}
}
fn valid_identifier_char(c: char) -> bool {
match c {
'a'..'z' | 'A'..'Z' | '0'..'9' | '-' | '_' => true,
_ => false
}
} |
/// Parse a list of rules separated by optional whitespace.
fn parse_rules(&mut self) -> Vec<Rule> { | random_line_split |
parser.rs | //! A simple parser for a tiny subset of HTML and CSS.
use std::ascii::OwnedStrAsciiExt; // for `into_ascii_lower`
use std::collections::hashmap::HashMap;
use std::num::FromStrRadix;
use css::{Stylesheet,Rule,Selector,Simple,SimpleSelector,Declaration,Value,Keyword,Length,Unit,Color,Px};
use dom;
/// Parse an HTML document and return the root element.
pub fn parse_html(source: String) -> dom::Node {
let mut nodes = Parser { pos: 0u, input: source }.parse_nodes();
// If the document contains a root element, just return it. Otherwise create one.
if nodes.len() == 1 {
nodes.swap_remove(0).unwrap()
} else {
dom::elem("html".to_string(), HashMap::new(), nodes)
}
}
/// Parse a whole CSS stylesheet.
pub fn parse_css(source: String) -> Stylesheet {
let mut parser = Parser { pos: 0u, input: source };
Stylesheet { rules: parser.parse_rules() }
}
struct Parser {
pos: uint,
input: String,
}
impl Parser {
/// Read the next character without consuming it.
fn | (&self) -> char {
self.input.as_slice().char_at(self.pos)
}
/// Do the next characters start with the given string?
fn starts_with(&self, s: &str) -> bool {
self.input.as_slice().slice_from(self.pos).starts_with(s)
}
/// Return true if all input is consumed.
fn eof(&self) -> bool {
self.pos >= self.input.len()
}
/// Return the current character and advance to the next character.
fn consume_char(&mut self) -> char {
let range = self.input.as_slice().char_range_at(self.pos);
self.pos = range.next;
range.ch
}
/// Consume characters until `test` returns false.
fn consume_while(&mut self, test: |char| -> bool) -> String {
let mut result = String::new();
while!self.eof() && test(self.next_char()) {
result.push_char(self.consume_char());
}
result
}
/// Consume and discard zero or more whitespace
fn consume_whitespace(&mut self) {
self.consume_while(|c| c.is_whitespace());
}
// HTML parsing
/// Parse a tag or attribute name.
fn parse_tag_name(&mut self) -> String {
self.consume_while(|c| match c {
'a'..'z' | 'A'..'Z' | '0'..'9' => true,
_ => false
})
}
/// Parse a single node.
fn parse_node(&mut self) -> dom::Node {
match self.next_char() {
'<' => self.parse_element(),
_ => self.parse_text()
}
}
/// Parse a text node.
fn parse_text(&mut self) -> dom::Node {
dom::text(self.consume_while(|c| c!= '<'))
}
/// Parse a single element inlcuding its open tag, contents and closing tag.
fn parse_element(&mut self) -> dom::Node {
// Opening tag
assert!(self.consume_char() == '<');
let tag_name = self.parse_tag_name();
let attrs = self.parse_attributes();
assert!(self.consume_char() == '>');
// Contents
let children = self.parse_nodes();
// Closing tag
assert!(self.consume_char() == '<');
assert!(self.consume_char() == '/');
assert!(self.parse_tag_name() == tag_name);
assert!(self.consume_char() == '>');
dom::elem(tag_name, attrs, children)
}
/// Parse a single name="value" pair.
fn parse_attr(&mut self) -> (String, String) {
let name = self.parse_tag_name();
assert!(self.consume_char() == '=');
let value = self.parse_attr_value();
(name, value)
}
/// Parse a quoted value.
fn parse_attr_value(&mut self) -> String {
let open_quote = self.consume_char();
assert!(open_quote == '"' || open_quote == '\'');
let value = self.consume_while(|c| c!= open_quote);
assert!(self.consume_char() == open_quote);
value
}
/// Parse attributes.
fn parse_attributes(&mut self) -> dom::AttrMap {
let mut attributes = HashMap::new();
loop {
self.consume_whitespace();
if self.next_char() == '>' {
break;
}
let (name, value) = self.parse_attr();
attributes.insert(name, value);
}
attributes
}
/// Parse a sequence of sibling nodes.
fn parse_nodes(&mut self) -> Vec<dom::Node> {
let mut nodes = vec!();
loop {
self.consume_whitespace();
if self.eof() || self.starts_with("</") {
break;
}
nodes.push(self.parse_node());
}
nodes
}
// Parse CSS
/// Parse a list of rules separated by optional whitespace.
fn parse_rules(&mut self) -> Vec<Rule> {
let mut rules = Vec::new();
loop {
self.consume_whitespace();
if self.eof() {
break;
}
rules.push(self.parse_rule());
}
rules
}
/// Parse a rule set: `<selectors> { <declarations> }`.
fn parse_rule(&mut self) -> Rule {
Rule {
selectors: self.parse_selectors(),
declarations: self.parse_declarations(),
}
}
// Parse a comma separated list of selectors.
fn parse_selectors(&mut self) -> Vec<Selector> {
let mut selectors = Vec::new();
loop {
selectors.push(Simple(self.parse_simple_selector()));
self.consume_whitespace();
match self.next_char() {
',' => {
self.consume_char();
self.consume_whitespace()
}
'{' => break,
c => fail!("Unexpected character {} in selector list", c)
}
}
// Sort by specificity (highest first)
selectors.sort_by(|a, b| b.specificity().cmp(&a.specificity()));
selectors
}
/// Parse one simple selector, e.g.: `type#id.class1.class2.classn`
fn parse_simple_selector(&mut self) -> SimpleSelector {
let mut selector = SimpleSelector { tag_name: None, id: None, class: Vec::new() };
while!self.eof() {
match self.next_char() {
'#' => {
self.consume_char();
selector.id = Some(self.parse_identifier());
}
'.' => {
self.consume_char();
selector.class.push(self.parse_identifier());
}
'*' => {
// universal selector
self.consume_char();
}
c if valid_identifier_char(c) => {
selector.tag_name = Some(self.parse_identifier());
}
_ => break
}
}
selector
}
/// Parse a list of declarations enclosed by `{ }`.
fn parse_declarations(&mut self) -> Vec<Declaration> {
let mut declarations = Vec::new();
assert!(self.consume_char() == '{');
loop {
self.consume_whitespace();
if self.next_char() == '}' {
self.consume_char();
break;
}
declarations.push(self.parse_declaration());
}
declarations
}
/// Parse a `<property>: <value>;` declaration.
fn parse_declaration(&mut self) -> Declaration {
let property_name = self.parse_identifier();
self.consume_whitespace();
assert!(self.consume_char() == ':');
self.consume_whitespace();
let value = self.parse_value();
self.consume_whitespace();
assert!(self.consume_char() == ';');
Declaration {
name: property_name,
value: value,
}
}
/// Parse a value
fn parse_value(&mut self) -> Value {
match self.next_char() {
'0'..'9' => self.parse_length(),
'#' => self.parse_color(),
_ => Keyword(self.parse_identifier())
}
}
fn parse_length(&mut self) -> Value {
Length(self.parse_float(), self.parse_unit())
}
fn parse_float(&mut self) -> f32 {
let s = self.consume_while(|c| match c {
'0'..'9' | '.' => true,
_ => false
});
let f: Option<f32> = from_str(s.as_slice());
f.unwrap()
}
fn parse_unit(&mut self) -> Unit {
match self.parse_identifier().into_ascii_lower().as_slice() {
"px" => Px,
_ => fail!("unrecognized unit")
}
}
fn parse_color(&mut self) -> Value {
assert!(self.consume_char() == '#');
Color(self.parse_hex_pair(), self.parse_hex_pair(), self.parse_hex_pair(), 255)
}
fn parse_hex_pair(&mut self) -> u8 {
let s = self.input.as_slice().slice(self.pos, self.pos + 2);
self.pos = self.pos + 2;
FromStrRadix::from_str_radix(s, 16).unwrap()
}
fn parse_identifier(&mut self) -> String {
self.consume_while(valid_identifier_char)
}
}
fn valid_identifier_char(c: char) -> bool {
match c {
'a'..'z' | 'A'..'Z' | '0'..'9' | '-' | '_' => true,
_ => false
}
}
| next_char | identifier_name |
parser.rs | //! A simple parser for a tiny subset of HTML and CSS.
use std::ascii::OwnedStrAsciiExt; // for `into_ascii_lower`
use std::collections::hashmap::HashMap;
use std::num::FromStrRadix;
use css::{Stylesheet,Rule,Selector,Simple,SimpleSelector,Declaration,Value,Keyword,Length,Unit,Color,Px};
use dom;
/// Parse an HTML document and return the root element.
pub fn parse_html(source: String) -> dom::Node {
let mut nodes = Parser { pos: 0u, input: source }.parse_nodes();
// If the document contains a root element, just return it. Otherwise create one.
if nodes.len() == 1 {
nodes.swap_remove(0).unwrap()
} else {
dom::elem("html".to_string(), HashMap::new(), nodes)
}
}
/// Parse a whole CSS stylesheet.
pub fn parse_css(source: String) -> Stylesheet {
let mut parser = Parser { pos: 0u, input: source };
Stylesheet { rules: parser.parse_rules() }
}
struct Parser {
pos: uint,
input: String,
}
impl Parser {
/// Read the next character without consuming it.
fn next_char(&self) -> char {
self.input.as_slice().char_at(self.pos)
}
/// Do the next characters start with the given string?
fn starts_with(&self, s: &str) -> bool {
self.input.as_slice().slice_from(self.pos).starts_with(s)
}
/// Return true if all input is consumed.
fn eof(&self) -> bool {
self.pos >= self.input.len()
}
/// Return the current character and advance to the next character.
fn consume_char(&mut self) -> char {
let range = self.input.as_slice().char_range_at(self.pos);
self.pos = range.next;
range.ch
}
/// Consume characters until `test` returns false.
fn consume_while(&mut self, test: |char| -> bool) -> String {
let mut result = String::new();
while!self.eof() && test(self.next_char()) {
result.push_char(self.consume_char());
}
result
}
/// Consume and discard zero or more whitespace
fn consume_whitespace(&mut self) {
self.consume_while(|c| c.is_whitespace());
}
// HTML parsing
/// Parse a tag or attribute name.
fn parse_tag_name(&mut self) -> String {
self.consume_while(|c| match c {
'a'..'z' | 'A'..'Z' | '0'..'9' => true,
_ => false
})
}
/// Parse a single node.
fn parse_node(&mut self) -> dom::Node {
match self.next_char() {
'<' => self.parse_element(),
_ => self.parse_text()
}
}
/// Parse a text node.
fn parse_text(&mut self) -> dom::Node {
dom::text(self.consume_while(|c| c!= '<'))
}
/// Parse a single element inlcuding its open tag, contents and closing tag.
fn parse_element(&mut self) -> dom::Node {
// Opening tag
assert!(self.consume_char() == '<');
let tag_name = self.parse_tag_name();
let attrs = self.parse_attributes();
assert!(self.consume_char() == '>');
// Contents
let children = self.parse_nodes();
// Closing tag
assert!(self.consume_char() == '<');
assert!(self.consume_char() == '/');
assert!(self.parse_tag_name() == tag_name);
assert!(self.consume_char() == '>');
dom::elem(tag_name, attrs, children)
}
/// Parse a single name="value" pair.
fn parse_attr(&mut self) -> (String, String) |
/// Parse a quoted value.
fn parse_attr_value(&mut self) -> String {
let open_quote = self.consume_char();
assert!(open_quote == '"' || open_quote == '\'');
let value = self.consume_while(|c| c!= open_quote);
assert!(self.consume_char() == open_quote);
value
}
/// Parse attributes.
fn parse_attributes(&mut self) -> dom::AttrMap {
let mut attributes = HashMap::new();
loop {
self.consume_whitespace();
if self.next_char() == '>' {
break;
}
let (name, value) = self.parse_attr();
attributes.insert(name, value);
}
attributes
}
/// Parse a sequence of sibling nodes.
fn parse_nodes(&mut self) -> Vec<dom::Node> {
let mut nodes = vec!();
loop {
self.consume_whitespace();
if self.eof() || self.starts_with("</") {
break;
}
nodes.push(self.parse_node());
}
nodes
}
// Parse CSS
/// Parse a list of rules separated by optional whitespace.
fn parse_rules(&mut self) -> Vec<Rule> {
let mut rules = Vec::new();
loop {
self.consume_whitespace();
if self.eof() {
break;
}
rules.push(self.parse_rule());
}
rules
}
/// Parse a rule set: `<selectors> { <declarations> }`.
fn parse_rule(&mut self) -> Rule {
Rule {
selectors: self.parse_selectors(),
declarations: self.parse_declarations(),
}
}
// Parse a comma separated list of selectors.
fn parse_selectors(&mut self) -> Vec<Selector> {
let mut selectors = Vec::new();
loop {
selectors.push(Simple(self.parse_simple_selector()));
self.consume_whitespace();
match self.next_char() {
',' => {
self.consume_char();
self.consume_whitespace()
}
'{' => break,
c => fail!("Unexpected character {} in selector list", c)
}
}
// Sort by specificity (highest first)
selectors.sort_by(|a, b| b.specificity().cmp(&a.specificity()));
selectors
}
/// Parse one simple selector, e.g.: `type#id.class1.class2.classn`
fn parse_simple_selector(&mut self) -> SimpleSelector {
let mut selector = SimpleSelector { tag_name: None, id: None, class: Vec::new() };
while!self.eof() {
match self.next_char() {
'#' => {
self.consume_char();
selector.id = Some(self.parse_identifier());
}
'.' => {
self.consume_char();
selector.class.push(self.parse_identifier());
}
'*' => {
// universal selector
self.consume_char();
}
c if valid_identifier_char(c) => {
selector.tag_name = Some(self.parse_identifier());
}
_ => break
}
}
selector
}
/// Parse a list of declarations enclosed by `{ }`.
fn parse_declarations(&mut self) -> Vec<Declaration> {
let mut declarations = Vec::new();
assert!(self.consume_char() == '{');
loop {
self.consume_whitespace();
if self.next_char() == '}' {
self.consume_char();
break;
}
declarations.push(self.parse_declaration());
}
declarations
}
/// Parse a `<property>: <value>;` declaration.
fn parse_declaration(&mut self) -> Declaration {
let property_name = self.parse_identifier();
self.consume_whitespace();
assert!(self.consume_char() == ':');
self.consume_whitespace();
let value = self.parse_value();
self.consume_whitespace();
assert!(self.consume_char() == ';');
Declaration {
name: property_name,
value: value,
}
}
/// Parse a value
fn parse_value(&mut self) -> Value {
match self.next_char() {
'0'..'9' => self.parse_length(),
'#' => self.parse_color(),
_ => Keyword(self.parse_identifier())
}
}
fn parse_length(&mut self) -> Value {
Length(self.parse_float(), self.parse_unit())
}
fn parse_float(&mut self) -> f32 {
let s = self.consume_while(|c| match c {
'0'..'9' | '.' => true,
_ => false
});
let f: Option<f32> = from_str(s.as_slice());
f.unwrap()
}
fn parse_unit(&mut self) -> Unit {
match self.parse_identifier().into_ascii_lower().as_slice() {
"px" => Px,
_ => fail!("unrecognized unit")
}
}
fn parse_color(&mut self) -> Value {
assert!(self.consume_char() == '#');
Color(self.parse_hex_pair(), self.parse_hex_pair(), self.parse_hex_pair(), 255)
}
fn parse_hex_pair(&mut self) -> u8 {
let s = self.input.as_slice().slice(self.pos, self.pos + 2);
self.pos = self.pos + 2;
FromStrRadix::from_str_radix(s, 16).unwrap()
}
fn parse_identifier(&mut self) -> String {
self.consume_while(valid_identifier_char)
}
}
fn valid_identifier_char(c: char) -> bool {
match c {
'a'..'z' | 'A'..'Z' | '0'..'9' | '-' | '_' => true,
_ => false
}
}
| {
let name = self.parse_tag_name();
assert!(self.consume_char() == '=');
let value = self.parse_attr_value();
(name, value)
} | identifier_body |
worker.rs | //! Client socket I/O operation `Worker`.
use std::io::Write;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::thread;
use wrust_async::crossbeam::sync::chase_lev::Steal;
use wrust_io::mio::{TryRead, TryWrite, EventSet};
use wrust_types::{Result, Error};
use wrust_types::net::Protocol;
use wrust_types::net::connection::State;
use wrust_module::stream::{Behavior, Intention, Flush};
use ::net::{EventChannel, Request};
use ::net::client::{Client, LeftData};
use ::net::server::Server;
use super::{Queue, Parcel};
/// I/O event worker
/// New `Worker`s can be spawned using method `worker` on the live queue.
pub struct Worker {
_child: thread::JoinHandle<()>,
_id: usize,
}
impl Worker {
/// Create a new `Worker` which handles client socket I/O operations.
pub fn run(queue: &Queue, id: usize, event_channel: EventChannel) -> Self {
let stealer = queue.stealer();
let ready = queue.ready();
let counter = queue.worker_count();
let child = thread::spawn(move || {
debug!("Worker {} started", id);
let mut done = false;
// The main loop where the worker tries to steal parcels from the deque and process them
while!done {
match stealer.steal() {
Steal::Empty => {
// No items in the deque, the worker can sleep
ready.wait();
},
Steal::Abort => {
// Do nothing, just try to steal again
},
Steal::Data(parcel) => {
match parcel {
Parcel::Shutdown => {
done = true;
},
Parcel::Open { server, client } => {
trace!("{} -> {:?} opens {:?}", id, *server, *client);
Worker::open(&server, &client, &event_channel);
},
Parcel::Close { server, client } => {
trace!("{} -> {:?} closes {:?}", id, *server, *client);
Worker::close(&server, &client, &event_channel);
},
Parcel::Ready { server, client, events } => {
trace!("{} -> {:?} processes {:?} for {:?}", id, *server, *client, events);
match client.state() {
State::Reading => {
assert!(events.is_readable(), "unexpected events; events={:?}", events);
Worker::read(&server, &client, &event_channel);
},
State::Writing => {
assert!(events.is_writable(), "unexpected events; events={:?}", events);
Worker::write(&server, &client, &event_channel);
},
State::Flushing => {
assert!(events.is_writable(), "unexpected events; events={:?}", events);
Worker::write(&server, &client, &event_channel);
},
_ => unimplemented!(),
};
},
};
},
};
}
// Decrease the number of running workers
counter.fetch_sub(1, Ordering::SeqCst);
debug!("Worker {} finished", id);
});
Worker {
_child: child,
_id: id,
}
}
fn open(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// Ask the stream processing module what to do next
let further_action = server.forward()
.open(client.descriptor());
// Close the client connection if the stream processing module said to
// or register in the event loop
if let Intention::Close(err) = further_action {
if err.is_some() {
error!("{}", err.unwrap());
}
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
}
else {
// Change the client state
client.set_state(further_action.as_state());
event_channel
.send(Request::Open {
client_token: *client.token(),
events: further_action.as_event_set(),
})
.unwrap();
};
}
fn close(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// Ask the stream processing to free resources associated with the connection
server.forward()
.close(client.descriptor());
// Send the event loop request to close the connection
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
}
fn reregister(client: &Arc<Client>, event_channel: &EventChannel, intention: Intention) {
// Close the client connection if the stream processing module said to
// or reregister in the event loop
if let Intention::Close(err) = intention {
if err.is_some() {
error!("{}", err.unwrap());
}
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
}
else {
// Change the client state
client.set_state(intention.as_state());
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: intention.as_event_set(),
})
.unwrap();
};
}
fn read(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// Read data from the socket
let mut buf: Vec<u8> = Vec::new();
let read_result = Worker::try_read_buf(client, &mut buf);
// Check what we'v got
match read_result {
Ok(Some(0)) => {
// The socket is currently closed, in which case writing
// will result in an error, or the client only shutdown
// half of the socket and is still expecting to receive
// the buffered data back.
// Change the client state
client.set_state(State::Flushing);
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: EventSet::writable(),
})
.unwrap();
},
Ok(Some(_)) => {
// Pass read data to the stream processing module
let further_action = server.forward()
.read(client.descriptor(), &mut buf);
// Re-register the socket with the event loop. The current
// state is used to determine whether we are currently reading
// or writing.
Worker::reregister(client, event_channel, further_action);
},
Ok(None) => {
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: EventSet::readable(),
})
.unwrap();
},
Err(e) => {
panic!("got an error trying to read; err={:?}", e);
}
}
}
fn write(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// If there is data left unwritten since the last write operation
// then we try to write it before we get data from the stream processing module
// and write to the stream
let left_data = client.left_data();
let (mut buf, further_action) = match left_data {
Some(data) => {
// Some data left
data.consume()
},
None => {
// Get the new chunk of data from the module
let mut buf = Vec::new();
let further_action = server.forward()
.write(client.descriptor(), &mut buf);
(buf, further_action)
}
};
let write_result = Worker::try_write_buf(client, &mut buf);
// Check the result of the I/O operation
match write_result {
Ok(Some(n)) => {
if n < buf.len() {
// Not all data has been written. Drain the written part and
// left unwritten data for future write tries.
buf.drain(0..n);
client.set_left_data(Some(LeftData::new(buf, further_action.0, further_action.1)));
Worker::reregister(client, event_channel, Intention::Write);
}
else {
// When one half of the socket is closed valid intentions
// only are Close ot Write.
if client.state() == State::Flushing {
if further_action.0 == Intention::Read {
// Read channel is closed at the moment so further reading
// has no reason. Closing the connection.
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
return;
}
}
// Force flush buffered data because the modele asked for that
if further_action.1 == Flush::Force {
match Worker::try_flush(client) {
Err(msg) => error!("{}", msg),
Ok(_) => {}
};
}
// Re-register the socket with the event loop.
Worker::reregister(client, event_channel, further_action.0);
}
}
Ok(None) => {
// The socket wasn't actually ready, re-register the socket
// with the event loop
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: EventSet::writable(),
})
.unwrap();
}
Err(e) => {
panic!("got an error trying to write; err={:?}", e); | }
fn try_read_buf(client: &Arc<Client>, buf: &mut Vec<u8>) -> Result<Option<usize>> {
client.then_on_socket(|sock| -> Result<Option<usize>> {
match sock {
&mut Protocol::Tcp(ref mut stream) => match stream.try_read_buf(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot read from client socket").because(msg).result()
},
&mut Protocol::Unix(ref mut stream) => match stream.try_read_buf(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot read from client socket").because(msg).result()
},
_ => Error::new("Cannot read from client socket because UDP is not supported").result()
}
})
}
fn try_write_buf(client: &Arc<Client>, buf: &mut Vec<u8>) -> Result<Option<usize>> {
client.then_on_socket(|sock| -> Result<Option<usize>> {
match sock {
&mut Protocol::Tcp(ref mut stream) => match stream.try_write(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot write to client socket").because(msg).result()
},
&mut Protocol::Unix(ref mut stream) => match stream.try_write(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot write to client socket").because(msg).result()
},
_ => Error::new("Cannot write to client socket because UDP is not supported").result()
}
})
}
fn try_flush(client: &Arc<Client>) -> Result<()> {
client.then_on_socket(|sock| -> Result<()> {
match sock {
&mut Protocol::Tcp(ref mut stream) => match stream.flush() {
Ok(()) => Ok(()),
Err(msg) => Error::new("Cannot flush client socket").because(msg).result()
},
&mut Protocol::Unix(ref mut stream) => match stream.flush() {
Ok(()) => Ok(()),
Err(msg) => Error::new("Cannot flush client socket").because(msg).result()
},
_ => Error::new("Cannot flush client socket because UDP is not supported").result()
}
})
}
} | }
} | random_line_split |
worker.rs | //! Client socket I/O operation `Worker`.
use std::io::Write;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::thread;
use wrust_async::crossbeam::sync::chase_lev::Steal;
use wrust_io::mio::{TryRead, TryWrite, EventSet};
use wrust_types::{Result, Error};
use wrust_types::net::Protocol;
use wrust_types::net::connection::State;
use wrust_module::stream::{Behavior, Intention, Flush};
use ::net::{EventChannel, Request};
use ::net::client::{Client, LeftData};
use ::net::server::Server;
use super::{Queue, Parcel};
/// I/O event worker
/// New `Worker`s can be spawned using method `worker` on the live queue.
pub struct Worker {
_child: thread::JoinHandle<()>,
_id: usize,
}
impl Worker {
/// Create a new `Worker` which handles client socket I/O operations.
pub fn run(queue: &Queue, id: usize, event_channel: EventChannel) -> Self {
let stealer = queue.stealer();
let ready = queue.ready();
let counter = queue.worker_count();
let child = thread::spawn(move || {
debug!("Worker {} started", id);
let mut done = false;
// The main loop where the worker tries to steal parcels from the deque and process them
while!done {
match stealer.steal() {
Steal::Empty => {
// No items in the deque, the worker can sleep
ready.wait();
},
Steal::Abort => {
// Do nothing, just try to steal again
},
Steal::Data(parcel) => {
match parcel {
Parcel::Shutdown => {
done = true;
},
Parcel::Open { server, client } => {
trace!("{} -> {:?} opens {:?}", id, *server, *client);
Worker::open(&server, &client, &event_channel);
},
Parcel::Close { server, client } => {
trace!("{} -> {:?} closes {:?}", id, *server, *client);
Worker::close(&server, &client, &event_channel);
},
Parcel::Ready { server, client, events } => {
trace!("{} -> {:?} processes {:?} for {:?}", id, *server, *client, events);
match client.state() {
State::Reading => {
assert!(events.is_readable(), "unexpected events; events={:?}", events);
Worker::read(&server, &client, &event_channel);
},
State::Writing => {
assert!(events.is_writable(), "unexpected events; events={:?}", events);
Worker::write(&server, &client, &event_channel);
},
State::Flushing => {
assert!(events.is_writable(), "unexpected events; events={:?}", events);
Worker::write(&server, &client, &event_channel);
},
_ => unimplemented!(),
};
},
};
},
};
}
// Decrease the number of running workers
counter.fetch_sub(1, Ordering::SeqCst);
debug!("Worker {} finished", id);
});
Worker {
_child: child,
_id: id,
}
}
fn open(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// Ask the stream processing module what to do next
let further_action = server.forward()
.open(client.descriptor());
// Close the client connection if the stream processing module said to
// or register in the event loop
if let Intention::Close(err) = further_action {
if err.is_some() {
error!("{}", err.unwrap());
}
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
}
else {
// Change the client state
client.set_state(further_action.as_state());
event_channel
.send(Request::Open {
client_token: *client.token(),
events: further_action.as_event_set(),
})
.unwrap();
};
}
fn close(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// Ask the stream processing to free resources associated with the connection
server.forward()
.close(client.descriptor());
// Send the event loop request to close the connection
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
}
fn reregister(client: &Arc<Client>, event_channel: &EventChannel, intention: Intention) {
// Close the client connection if the stream processing module said to
// or reregister in the event loop
if let Intention::Close(err) = intention {
if err.is_some() {
error!("{}", err.unwrap());
}
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
}
else {
// Change the client state
client.set_state(intention.as_state());
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: intention.as_event_set(),
})
.unwrap();
};
}
fn read(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// Read data from the socket
let mut buf: Vec<u8> = Vec::new();
let read_result = Worker::try_read_buf(client, &mut buf);
// Check what we'v got
match read_result {
Ok(Some(0)) => {
// The socket is currently closed, in which case writing
// will result in an error, or the client only shutdown
// half of the socket and is still expecting to receive
// the buffered data back.
// Change the client state
client.set_state(State::Flushing);
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: EventSet::writable(),
})
.unwrap();
},
Ok(Some(_)) => {
// Pass read data to the stream processing module
let further_action = server.forward()
.read(client.descriptor(), &mut buf);
// Re-register the socket with the event loop. The current
// state is used to determine whether we are currently reading
// or writing.
Worker::reregister(client, event_channel, further_action);
},
Ok(None) => {
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: EventSet::readable(),
})
.unwrap();
},
Err(e) => {
panic!("got an error trying to read; err={:?}", e);
}
}
}
fn write(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) |
let write_result = Worker::try_write_buf(client, &mut buf);
// Check the result of the I/O operation
match write_result {
Ok(Some(n)) => {
if n < buf.len() {
// Not all data has been written. Drain the written part and
// left unwritten data for future write tries.
buf.drain(0..n);
client.set_left_data(Some(LeftData::new(buf, further_action.0, further_action.1)));
Worker::reregister(client, event_channel, Intention::Write);
}
else {
// When one half of the socket is closed valid intentions
// only are Close ot Write.
if client.state() == State::Flushing {
if further_action.0 == Intention::Read {
// Read channel is closed at the moment so further reading
// has no reason. Closing the connection.
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
return;
}
}
// Force flush buffered data because the modele asked for that
if further_action.1 == Flush::Force {
match Worker::try_flush(client) {
Err(msg) => error!("{}", msg),
Ok(_) => {}
};
}
// Re-register the socket with the event loop.
Worker::reregister(client, event_channel, further_action.0);
}
}
Ok(None) => {
// The socket wasn't actually ready, re-register the socket
// with the event loop
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: EventSet::writable(),
})
.unwrap();
}
Err(e) => {
panic!("got an error trying to write; err={:?}", e);
}
}
}
fn try_read_buf(client: &Arc<Client>, buf: &mut Vec<u8>) -> Result<Option<usize>> {
client.then_on_socket(|sock| -> Result<Option<usize>> {
match sock {
&mut Protocol::Tcp(ref mut stream) => match stream.try_read_buf(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot read from client socket").because(msg).result()
},
&mut Protocol::Unix(ref mut stream) => match stream.try_read_buf(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot read from client socket").because(msg).result()
},
_ => Error::new("Cannot read from client socket because UDP is not supported").result()
}
})
}
fn try_write_buf(client: &Arc<Client>, buf: &mut Vec<u8>) -> Result<Option<usize>> {
client.then_on_socket(|sock| -> Result<Option<usize>> {
match sock {
&mut Protocol::Tcp(ref mut stream) => match stream.try_write(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot write to client socket").because(msg).result()
},
&mut Protocol::Unix(ref mut stream) => match stream.try_write(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot write to client socket").because(msg).result()
},
_ => Error::new("Cannot write to client socket because UDP is not supported").result()
}
})
}
fn try_flush(client: &Arc<Client>) -> Result<()> {
client.then_on_socket(|sock| -> Result<()> {
match sock {
&mut Protocol::Tcp(ref mut stream) => match stream.flush() {
Ok(()) => Ok(()),
Err(msg) => Error::new("Cannot flush client socket").because(msg).result()
},
&mut Protocol::Unix(ref mut stream) => match stream.flush() {
Ok(()) => Ok(()),
Err(msg) => Error::new("Cannot flush client socket").because(msg).result()
},
_ => Error::new("Cannot flush client socket because UDP is not supported").result()
}
})
}
}
| {
// If there is data left unwritten since the last write operation
// then we try to write it before we get data from the stream processing module
// and write to the stream
let left_data = client.left_data();
let (mut buf, further_action) = match left_data {
Some(data) => {
// Some data left
data.consume()
},
None => {
// Get the new chunk of data from the module
let mut buf = Vec::new();
let further_action = server.forward()
.write(client.descriptor(), &mut buf);
(buf, further_action)
}
}; | identifier_body |
worker.rs | //! Client socket I/O operation `Worker`.
use std::io::Write;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::thread;
use wrust_async::crossbeam::sync::chase_lev::Steal;
use wrust_io::mio::{TryRead, TryWrite, EventSet};
use wrust_types::{Result, Error};
use wrust_types::net::Protocol;
use wrust_types::net::connection::State;
use wrust_module::stream::{Behavior, Intention, Flush};
use ::net::{EventChannel, Request};
use ::net::client::{Client, LeftData};
use ::net::server::Server;
use super::{Queue, Parcel};
/// I/O event worker
/// New `Worker`s can be spawned using method `worker` on the live queue.
pub struct Worker {
_child: thread::JoinHandle<()>,
_id: usize,
}
impl Worker {
/// Create a new `Worker` which handles client socket I/O operations.
pub fn run(queue: &Queue, id: usize, event_channel: EventChannel) -> Self {
let stealer = queue.stealer();
let ready = queue.ready();
let counter = queue.worker_count();
let child = thread::spawn(move || {
debug!("Worker {} started", id);
let mut done = false;
// The main loop where the worker tries to steal parcels from the deque and process them
while!done {
match stealer.steal() {
Steal::Empty => {
// No items in the deque, the worker can sleep
ready.wait();
},
Steal::Abort => {
// Do nothing, just try to steal again
},
Steal::Data(parcel) => {
match parcel {
Parcel::Shutdown => {
done = true;
},
Parcel::Open { server, client } => {
trace!("{} -> {:?} opens {:?}", id, *server, *client);
Worker::open(&server, &client, &event_channel);
},
Parcel::Close { server, client } => {
trace!("{} -> {:?} closes {:?}", id, *server, *client);
Worker::close(&server, &client, &event_channel);
},
Parcel::Ready { server, client, events } => {
trace!("{} -> {:?} processes {:?} for {:?}", id, *server, *client, events);
match client.state() {
State::Reading => {
assert!(events.is_readable(), "unexpected events; events={:?}", events);
Worker::read(&server, &client, &event_channel);
},
State::Writing => {
assert!(events.is_writable(), "unexpected events; events={:?}", events);
Worker::write(&server, &client, &event_channel);
},
State::Flushing => {
assert!(events.is_writable(), "unexpected events; events={:?}", events);
Worker::write(&server, &client, &event_channel);
},
_ => unimplemented!(),
};
},
};
},
};
}
// Decrease the number of running workers
counter.fetch_sub(1, Ordering::SeqCst);
debug!("Worker {} finished", id);
});
Worker {
_child: child,
_id: id,
}
}
fn open(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// Ask the stream processing module what to do next
let further_action = server.forward()
.open(client.descriptor());
// Close the client connection if the stream processing module said to
// or register in the event loop
if let Intention::Close(err) = further_action {
if err.is_some() {
error!("{}", err.unwrap());
}
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
}
else {
// Change the client state
client.set_state(further_action.as_state());
event_channel
.send(Request::Open {
client_token: *client.token(),
events: further_action.as_event_set(),
})
.unwrap();
};
}
fn close(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// Ask the stream processing to free resources associated with the connection
server.forward()
.close(client.descriptor());
// Send the event loop request to close the connection
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
}
fn reregister(client: &Arc<Client>, event_channel: &EventChannel, intention: Intention) {
// Close the client connection if the stream processing module said to
// or reregister in the event loop
if let Intention::Close(err) = intention {
if err.is_some() {
error!("{}", err.unwrap());
}
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
}
else {
// Change the client state
client.set_state(intention.as_state());
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: intention.as_event_set(),
})
.unwrap();
};
}
fn read(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// Read data from the socket
let mut buf: Vec<u8> = Vec::new();
let read_result = Worker::try_read_buf(client, &mut buf);
// Check what we'v got
match read_result {
Ok(Some(0)) => {
// The socket is currently closed, in which case writing
// will result in an error, or the client only shutdown
// half of the socket and is still expecting to receive
// the buffered data back.
// Change the client state
client.set_state(State::Flushing);
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: EventSet::writable(),
})
.unwrap();
},
Ok(Some(_)) => {
// Pass read data to the stream processing module
let further_action = server.forward()
.read(client.descriptor(), &mut buf);
// Re-register the socket with the event loop. The current
// state is used to determine whether we are currently reading
// or writing.
Worker::reregister(client, event_channel, further_action);
},
Ok(None) => {
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: EventSet::readable(),
})
.unwrap();
},
Err(e) => {
panic!("got an error trying to read; err={:?}", e);
}
}
}
fn write(server: &Arc<Server>, client: &Arc<Client>, event_channel: &EventChannel) {
// If there is data left unwritten since the last write operation
// then we try to write it before we get data from the stream processing module
// and write to the stream
let left_data = client.left_data();
let (mut buf, further_action) = match left_data {
Some(data) => {
// Some data left
data.consume()
},
None => {
// Get the new chunk of data from the module
let mut buf = Vec::new();
let further_action = server.forward()
.write(client.descriptor(), &mut buf);
(buf, further_action)
}
};
let write_result = Worker::try_write_buf(client, &mut buf);
// Check the result of the I/O operation
match write_result {
Ok(Some(n)) => {
if n < buf.len() {
// Not all data has been written. Drain the written part and
// left unwritten data for future write tries.
buf.drain(0..n);
client.set_left_data(Some(LeftData::new(buf, further_action.0, further_action.1)));
Worker::reregister(client, event_channel, Intention::Write);
}
else {
// When one half of the socket is closed valid intentions
// only are Close ot Write.
if client.state() == State::Flushing {
if further_action.0 == Intention::Read {
// Read channel is closed at the moment so further reading
// has no reason. Closing the connection.
event_channel
.send(Request::Close { client_token: *client.token() })
.unwrap();
return;
}
}
// Force flush buffered data because the modele asked for that
if further_action.1 == Flush::Force {
match Worker::try_flush(client) {
Err(msg) => error!("{}", msg),
Ok(_) => {}
};
}
// Re-register the socket with the event loop.
Worker::reregister(client, event_channel, further_action.0);
}
}
Ok(None) => {
// The socket wasn't actually ready, re-register the socket
// with the event loop
event_channel
.send(Request::Wait {
client_token: *client.token(),
events: EventSet::writable(),
})
.unwrap();
}
Err(e) => {
panic!("got an error trying to write; err={:?}", e);
}
}
}
fn | (client: &Arc<Client>, buf: &mut Vec<u8>) -> Result<Option<usize>> {
client.then_on_socket(|sock| -> Result<Option<usize>> {
match sock {
&mut Protocol::Tcp(ref mut stream) => match stream.try_read_buf(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot read from client socket").because(msg).result()
},
&mut Protocol::Unix(ref mut stream) => match stream.try_read_buf(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot read from client socket").because(msg).result()
},
_ => Error::new("Cannot read from client socket because UDP is not supported").result()
}
})
}
fn try_write_buf(client: &Arc<Client>, buf: &mut Vec<u8>) -> Result<Option<usize>> {
client.then_on_socket(|sock| -> Result<Option<usize>> {
match sock {
&mut Protocol::Tcp(ref mut stream) => match stream.try_write(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot write to client socket").because(msg).result()
},
&mut Protocol::Unix(ref mut stream) => match stream.try_write(buf) {
Ok(count) => Ok(count),
Err(msg) => Error::new("Cannot write to client socket").because(msg).result()
},
_ => Error::new("Cannot write to client socket because UDP is not supported").result()
}
})
}
fn try_flush(client: &Arc<Client>) -> Result<()> {
client.then_on_socket(|sock| -> Result<()> {
match sock {
&mut Protocol::Tcp(ref mut stream) => match stream.flush() {
Ok(()) => Ok(()),
Err(msg) => Error::new("Cannot flush client socket").because(msg).result()
},
&mut Protocol::Unix(ref mut stream) => match stream.flush() {
Ok(()) => Ok(()),
Err(msg) => Error::new("Cannot flush client socket").because(msg).result()
},
_ => Error::new("Cannot flush client socket because UDP is not supported").result()
}
})
}
}
| try_read_buf | identifier_name |
issue-75525-bounds-checks.rs | // Regression test for #75525, verifies that no bounds checks are generated.
// compile-flags: -O
#![crate_type = "lib"]
// CHECK-LABEL: @f0
// CHECK-NOT: panic
#[no_mangle]
pub fn f0(idx: usize, buf: &[u8; 10]) -> u8 {
if idx < 8 { buf[idx + 1] } else { 0 }
}
// CHECK-LABEL: @f1
// CHECK-NOT: panic
#[no_mangle]
pub fn | (idx: usize, buf: &[u8; 10]) -> u8 {
if idx > 5 && idx < 8 { buf[idx - 1] } else { 0 }
}
// CHECK-LABEL: @f2
// CHECK-NOT: panic
#[no_mangle]
pub fn f2(idx: usize, buf: &[u8; 10]) -> u8 {
if idx > 5 && idx < 8 { buf[idx] } else { 0 }
}
| f1 | identifier_name |
issue-75525-bounds-checks.rs | #![crate_type = "lib"]
// CHECK-LABEL: @f0
// CHECK-NOT: panic
#[no_mangle]
pub fn f0(idx: usize, buf: &[u8; 10]) -> u8 {
if idx < 8 { buf[idx + 1] } else { 0 }
}
// CHECK-LABEL: @f1
// CHECK-NOT: panic
#[no_mangle]
pub fn f1(idx: usize, buf: &[u8; 10]) -> u8 {
if idx > 5 && idx < 8 { buf[idx - 1] } else { 0 }
}
// CHECK-LABEL: @f2
// CHECK-NOT: panic
#[no_mangle]
pub fn f2(idx: usize, buf: &[u8; 10]) -> u8 {
if idx > 5 && idx < 8 { buf[idx] } else { 0 }
} | // Regression test for #75525, verifies that no bounds checks are generated.
// compile-flags: -O
| random_line_split |
|
issue-75525-bounds-checks.rs | // Regression test for #75525, verifies that no bounds checks are generated.
// compile-flags: -O
#![crate_type = "lib"]
// CHECK-LABEL: @f0
// CHECK-NOT: panic
#[no_mangle]
pub fn f0(idx: usize, buf: &[u8; 10]) -> u8 {
if idx < 8 { buf[idx + 1] } else { 0 }
}
// CHECK-LABEL: @f1
// CHECK-NOT: panic
#[no_mangle]
pub fn f1(idx: usize, buf: &[u8; 10]) -> u8 {
if idx > 5 && idx < 8 { buf[idx - 1] } else { 0 }
}
// CHECK-LABEL: @f2
// CHECK-NOT: panic
#[no_mangle]
pub fn f2(idx: usize, buf: &[u8; 10]) -> u8 | {
if idx > 5 && idx < 8 { buf[idx] } else { 0 }
} | identifier_body |
|
issue-75525-bounds-checks.rs | // Regression test for #75525, verifies that no bounds checks are generated.
// compile-flags: -O
#![crate_type = "lib"]
// CHECK-LABEL: @f0
// CHECK-NOT: panic
#[no_mangle]
pub fn f0(idx: usize, buf: &[u8; 10]) -> u8 {
if idx < 8 { buf[idx + 1] } else { 0 }
}
// CHECK-LABEL: @f1
// CHECK-NOT: panic
#[no_mangle]
pub fn f1(idx: usize, buf: &[u8; 10]) -> u8 {
if idx > 5 && idx < 8 { buf[idx - 1] } else { 0 }
}
// CHECK-LABEL: @f2
// CHECK-NOT: panic
#[no_mangle]
pub fn f2(idx: usize, buf: &[u8; 10]) -> u8 {
if idx > 5 && idx < 8 { buf[idx] } else |
}
| { 0 } | conditional_block |
rustc.rs | use std::path::PathBuf;
use util::{self, CargoResult, internal, ProcessBuilder};
/// Information on the `rustc` executable
#[derive(Debug)]
pub struct Rustc {
/// The location of the exe
pub path: PathBuf,
/// An optional program that will be passed the path of the rust exe as its first argument, and
/// rustc args following this.
pub wrapper: Option<PathBuf>,
/// Verbose version information (the output of `rustc -vV`)
pub verbose_version: String,
/// The host triple (arch-platform-OS), this comes from verbose_version.
pub host: String,
}
impl Rustc {
/// Run the compiler at `path` to learn various pieces of information about
/// it, with an optional wrapper.
///
/// If successful this function returns a description of the compiler along
/// with a list of its capabilities.
pub fn new(path: PathBuf, wrapper: Option<PathBuf>) -> CargoResult<Rustc> | verbose_version: verbose_version,
host: host,
})
}
/// Get a process builder set up to use the found rustc version, with a wrapper if Some
pub fn process(&self) -> ProcessBuilder {
if let Some(ref wrapper) = self.wrapper {
let mut cmd = util::process(wrapper);
{
cmd.arg(&self.path);
}
cmd
} else {
util::process(&self.path)
}
}
}
| {
let mut cmd = util::process(&path);
cmd.arg("-vV");
let output = cmd.exec_with_output()?;
let verbose_version = String::from_utf8(output.stdout).map_err(|_| {
internal("rustc -v didn't return utf8 output")
})?;
let host = {
let triple = verbose_version.lines().find(|l| {
l.starts_with("host: ")
}).map(|l| &l[6..]).ok_or_else(|| internal("rustc -v didn't have a line for `host:`"))?;
triple.to_string()
};
Ok(Rustc {
path: path,
wrapper: wrapper, | identifier_body |
rustc.rs | use std::path::PathBuf;
use util::{self, CargoResult, internal, ProcessBuilder};
/// Information on the `rustc` executable
#[derive(Debug)]
pub struct | {
/// The location of the exe
pub path: PathBuf,
/// An optional program that will be passed the path of the rust exe as its first argument, and
/// rustc args following this.
pub wrapper: Option<PathBuf>,
/// Verbose version information (the output of `rustc -vV`)
pub verbose_version: String,
/// The host triple (arch-platform-OS), this comes from verbose_version.
pub host: String,
}
impl Rustc {
/// Run the compiler at `path` to learn various pieces of information about
/// it, with an optional wrapper.
///
/// If successful this function returns a description of the compiler along
/// with a list of its capabilities.
pub fn new(path: PathBuf, wrapper: Option<PathBuf>) -> CargoResult<Rustc> {
let mut cmd = util::process(&path);
cmd.arg("-vV");
let output = cmd.exec_with_output()?;
let verbose_version = String::from_utf8(output.stdout).map_err(|_| {
internal("rustc -v didn't return utf8 output")
})?;
let host = {
let triple = verbose_version.lines().find(|l| {
l.starts_with("host: ")
}).map(|l| &l[6..]).ok_or_else(|| internal("rustc -v didn't have a line for `host:`"))?;
triple.to_string()
};
Ok(Rustc {
path: path,
wrapper: wrapper,
verbose_version: verbose_version,
host: host,
})
}
/// Get a process builder set up to use the found rustc version, with a wrapper if Some
pub fn process(&self) -> ProcessBuilder {
if let Some(ref wrapper) = self.wrapper {
let mut cmd = util::process(wrapper);
{
cmd.arg(&self.path);
}
cmd
} else {
util::process(&self.path)
}
}
}
| Rustc | identifier_name |
rustc.rs | use std::path::PathBuf;
use util::{self, CargoResult, internal, ProcessBuilder};
/// Information on the `rustc` executable
#[derive(Debug)]
pub struct Rustc {
/// The location of the exe
pub path: PathBuf,
/// An optional program that will be passed the path of the rust exe as its first argument, and
/// rustc args following this.
pub wrapper: Option<PathBuf>,
/// Verbose version information (the output of `rustc -vV`)
pub verbose_version: String,
/// The host triple (arch-platform-OS), this comes from verbose_version.
pub host: String,
}
impl Rustc {
/// Run the compiler at `path` to learn various pieces of information about
/// it, with an optional wrapper.
///
/// If successful this function returns a description of the compiler along
/// with a list of its capabilities.
pub fn new(path: PathBuf, wrapper: Option<PathBuf>) -> CargoResult<Rustc> {
let mut cmd = util::process(&path);
cmd.arg("-vV");
let output = cmd.exec_with_output()?;
let verbose_version = String::from_utf8(output.stdout).map_err(|_| {
internal("rustc -v didn't return utf8 output")
})?;
let host = {
let triple = verbose_version.lines().find(|l| {
l.starts_with("host: ")
}).map(|l| &l[6..]).ok_or_else(|| internal("rustc -v didn't have a line for `host:`"))?;
triple.to_string()
};
Ok(Rustc {
path: path,
wrapper: wrapper,
verbose_version: verbose_version,
host: host,
})
}
/// Get a process builder set up to use the found rustc version, with a wrapper if Some
pub fn process(&self) -> ProcessBuilder {
if let Some(ref wrapper) = self.wrapper | else {
util::process(&self.path)
}
}
}
| {
let mut cmd = util::process(wrapper);
{
cmd.arg(&self.path);
}
cmd
} | conditional_block |
rustc.rs | use std::path::PathBuf;
use util::{self, CargoResult, internal, ProcessBuilder};
/// Information on the `rustc` executable
#[derive(Debug)]
pub struct Rustc {
/// The location of the exe
pub path: PathBuf,
/// An optional program that will be passed the path of the rust exe as its first argument, and
/// rustc args following this.
pub wrapper: Option<PathBuf>,
/// Verbose version information (the output of `rustc -vV`)
pub verbose_version: String,
/// The host triple (arch-platform-OS), this comes from verbose_version.
pub host: String,
}
impl Rustc {
/// Run the compiler at `path` to learn various pieces of information about
/// it, with an optional wrapper.
///
/// If successful this function returns a description of the compiler along
/// with a list of its capabilities.
pub fn new(path: PathBuf, wrapper: Option<PathBuf>) -> CargoResult<Rustc> {
let mut cmd = util::process(&path);
cmd.arg("-vV");
let output = cmd.exec_with_output()?;
let verbose_version = String::from_utf8(output.stdout).map_err(|_| { | let triple = verbose_version.lines().find(|l| {
l.starts_with("host: ")
}).map(|l| &l[6..]).ok_or_else(|| internal("rustc -v didn't have a line for `host:`"))?;
triple.to_string()
};
Ok(Rustc {
path: path,
wrapper: wrapper,
verbose_version: verbose_version,
host: host,
})
}
/// Get a process builder set up to use the found rustc version, with a wrapper if Some
pub fn process(&self) -> ProcessBuilder {
if let Some(ref wrapper) = self.wrapper {
let mut cmd = util::process(wrapper);
{
cmd.arg(&self.path);
}
cmd
} else {
util::process(&self.path)
}
}
} | internal("rustc -v didn't return utf8 output")
})?;
let host = { | random_line_split |
lib.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! This is the documentation of the Oak runtime. Oak is a parser generator of _Parsing Expression Grammar_, please read first the [manual](http://hyc.io/oak).
//!
//! This library is used by the generated code of Oak and is also necessary to any Oak users for interfacing with the code generated.
//! A PEG combinator returns a `ParseState`, please consult the methods `into_result` or `unwrap_data` as they are good starting point for retrieving useful information.
extern crate syntex_pos;
pub use str_stream::*;
pub use stream::*;
pub use parse_state::*;
use syntex_pos::{BytePos, mk_sp};
pub mod str_stream;
pub mod parse_state;
pub mod stream;
pub mod file_map_stream;
pub fn | (lo: usize, hi: usize) -> Span {
mk_sp(
BytePos(lo as u32),
BytePos(hi as u32))
}
| make_span | identifier_name |
lib.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! This is the documentation of the Oak runtime. Oak is a parser generator of _Parsing Expression Grammar_, please read first the [manual](http://hyc.io/oak).
//!
//! This library is used by the generated code of Oak and is also necessary to any Oak users for interfacing with the code generated.
//! A PEG combinator returns a `ParseState`, please consult the methods `into_result` or `unwrap_data` as they are good starting point for retrieving useful information.
extern crate syntex_pos;
pub use str_stream::*;
pub use stream::*;
pub use parse_state::*;
use syntex_pos::{BytePos, mk_sp};
pub mod str_stream;
pub mod parse_state;
pub mod stream;
pub mod file_map_stream;
pub fn make_span(lo: usize, hi: usize) -> Span | {
mk_sp(
BytePos(lo as u32),
BytePos(hi as u32))
} | identifier_body |
|
lib.rs | // Copyright 2014 Pierre Talbot (IRCAM)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at |
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! This is the documentation of the Oak runtime. Oak is a parser generator of _Parsing Expression Grammar_, please read first the [manual](http://hyc.io/oak).
//!
//! This library is used by the generated code of Oak and is also necessary to any Oak users for interfacing with the code generated.
//! A PEG combinator returns a `ParseState`, please consult the methods `into_result` or `unwrap_data` as they are good starting point for retrieving useful information.
extern crate syntex_pos;
pub use str_stream::*;
pub use stream::*;
pub use parse_state::*;
use syntex_pos::{BytePos, mk_sp};
pub mod str_stream;
pub mod parse_state;
pub mod stream;
pub mod file_map_stream;
pub fn make_span(lo: usize, hi: usize) -> Span {
mk_sp(
BytePos(lo as u32),
BytePos(hi as u32))
} | random_line_split |
|
lib.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
///! Async job scheduling utilities for a blocking application
///!
///! We have a blocking application. We have async libraries. This crate provides common utilities
///! for communicating between the blocking world and the async world. It is intended to be a guide
///! so that not all developers have to get in depth understanding of Tokio in order to use async
///! functions.
///!
///! The crate sets up a common Runtime that all async tasks run on. We use a threaded scheduler
///! which enables parallelism. The async code is expected to be ran in parallel, not just
///! concurrently. As a reminder, Python has concurrency with multiple threads but no parallelism
///! because of the global interpreter lock.
///! The Runtime will get forcefully shut down when the main thread exits. Any running background
///! work will be lost at that time. This is not a hard requirement though, we can be tweak it to
///! wait for tasks to finish but requires some ceremony around the Runtime. Since we have no need
///! for that right now so that feature is skipped for now.
///!
///! TODO(T74221415): monitoring, signal handling
use futures::future::Future;
use futures::stream::{BoxStream, Stream, StreamExt};
use futures::FutureExt;
use futures::{pin_mut, select};
use once_cell::sync::Lazy;
use std::io::{Error, ErrorKind};
use tokio::runtime::{Builder as RuntimeBuilder, Runtime};
use tokio::task::JoinHandle;
static RUNTIME: Lazy<Runtime> = Lazy::new(|| {
let nproc = num_cpus::get();
RuntimeBuilder::new_multi_thread()
.worker_threads(nproc.min(8))
.enable_all()
.build()
.expect("failed to initialize the async runtime")
});
pub static STREAM_BUFFER_SIZE: usize = 128;
/// Spawn a task using the runtime.
pub fn spawn<T>(task: T) -> JoinHandle<T::Output>
where
T: Future + Send +'static,
T::Output: Send +'static,
{
RUNTIME.spawn(task)
}
/// Run the provided function on an executor dedicated to blocking operations.
pub fn spawn_blocking<F, R>(func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send +'static,
R: Send +'static,
{
RUNTIME.spawn_blocking(func)
}
/// Blocks the current thread while waiting for the computation defined by the Future `f` to
/// complete.
///
/// Unlike `block_on_exclusive`, this can be nested without panic.
pub fn block_on_future<F>(f: F) -> F::Output
where
F::Output: Send,
F: Future + Send +'static,
{
block_on_exclusive(f)
}
/// Blocks the current thread while waiting for the computation defined by the Future `f`.
/// Also blocks other `block_on_future` calls.
///
/// This is intended to be used when `f` is not `'static` and cannot be used in
/// `block_on_future`.
pub fn block_on_exclusive<F>(f: F) -> F::Output
where
F: Future,
{
RUNTIME.block_on(f)
}
/// Takes an async stream and provide its contents in the form of a regular iterator.
///
/// If processing one of the items in the stream panics then the stream stops without further
/// feedback. It wouldn't be a bad idea to propagate the issue somehow.
///
/// This implementation will poll as long as there is space in the buffer. The sync iterator will
/// be returned practically right after the function is called. Calls to `next()` on the
/// iterator will block as long as there are no items to read from the buffer and stream items are
/// in flight. Calls to `next()` return as soon as items are available to pop from the buffer.
/// `STREAM_BUFFER_SIZE` determines the default size of the buffer. If this value is inconvenient
/// then check out `RunStreamOptions` which allows tweaking the buffer size. The buffering is just
/// to streamline the async/parallel computation and manage some of the synchronization overhead.
/// Unless the stream `s` is buffered, the items in the stream will be processed one after the
/// other.
/// When you want to process items strictly one after the other without any sort of buffering, you
/// should use `block_on_future(my_stream.next())`.
/// Example.
/// 1. unbuffered stream, stream_to_iter buffer size = 2.
/// - the stream has the first item polled and the result is added to the buffer
/// - the stream continues with polling the second item; while this is happening the iterator
/// that is returned may start being consumed releasing capacity in the buffer; for our example
/// let's say that the blocking thread hasn't reached that point yet and the stream fills the
/// buffer using the second item
/// - the stream will now poll the third item; assuming that the buffer is still full when the
/// computation is done, it will yield the thread that is is running on until the blocking
/// thread reads one of the items in the buffer.
/// 2. buffered stream over 2 items (ordered), stream_to_iter buffer = 2
/// - the stream will take 2 futures from the underlying iterator and poll on them; when the
/// first one returns it enquees the result in our buffer and polls the third future in the
/// underlying stream. Assuming that f(x) produces r(x) we could write:
/// stream: #f1, *f2, *f3, f4, f5
/// buffer: r1
/// - let's assume that the blocking thread will not consume the buffer and the next future
/// finishes; the result then fills the buffer and f4 will get polled:
/// stream: #f1, #f2, *f3, *f4, f5
/// buffer: r1, r2
/// - adding the result of the third future to the buffer will have to wait until the blocking
/// thread consumes the returned iterator; only after that will the stream proceed with
/// polling the fifth future in the stream
pub fn stream_to_iter<S>(s: S) -> RunStream<S::Item>
where
S: Stream + Unpin + Send +'static,
S::Item: Send,
{
RunStreamOptions::new().run(s)
}
/// See `stream_to_iter`. Allows tweaking run parameters. See individual methods for parameter
/// details.
pub struct RunStreamOptions {
buffer_size: usize,
}
impl RunStreamOptions {
pub fn new() -> Self {
Self {
buffer_size: STREAM_BUFFER_SIZE,
}
}
/// When dealing with heavy computation or objects a smaller buffer size may be appropriate.
/// The current implementation does not provide a means to completely wait on polling the
/// second item until the blocking thread reads the first value.
pub fn buffer_size(&mut self, buffer_size: usize) -> &mut Self {
self.buffer_size = buffer_size;
self
}
/// Takes an async stream and provide it's contents in the form of a regular iterator.
/// See `stream_to_iter`.
pub fn run<S>(&self, mut s: S) -> RunStream<S::Item>
where
S: Stream + Unpin + Send +'static,
S::Item: Send,
{
// Why use a channel vs using `std::iter::from_fn`
// It is probably a bit easier to reason about what happens when using the channel. The
// implementation details of the executor and the buffered stream don't come in discussion
// as when directly scheduling the next future. It's a bit of insurance against changes and
// it separates the two worlds more clearly. The channel approach can be optimized to
// reduce entering the async runtime context when the stream is completed faster that it is
// processed on the main thread. We could also add multiple consumers.
let (tx, rx) = tokio::sync::mpsc::channel(self.buffer_size);
let _guard = RUNTIME.enter();
tokio::spawn(async move {
while let Some(v) = s.next().await {
if tx.send(v).await.is_err() {
// receiver dropped; TODO(T74252041): add logging
return;
}
}
});
RunStream { rx: Some(rx) }
}
}
/// Blocking thread handler for receiving the results following processing a `Stream`.
pub struct RunStream<T> {
// Option is used to workaround lifetime in Iterator::next.
rx: Option<tokio::sync::mpsc::Receiver<T>>,
}
impl<T: Send +'static> Iterator for RunStream<T> {
type Item = T;
/// Returns the items extracted from processing the stream. Will return `None` when the stream's
/// end is reached or when processing an item panics.
/// See `stream_to_iter`.
fn next(&mut self) -> Option<Self::Item> {
let mut rx = self.rx.take().unwrap();
let (next, rx) = block_on_future(async {
let next = rx.recv().await;
(next, rx)
});
self.rx = Some(rx);
next
}
}
| /// Unlike `futures::stream::iter`, the iterator's `next()` function could be
/// blocking.
pub fn iter_to_stream<I: Send +'static>(
iter: impl Iterator<Item = I> + Send +'static,
) -> BoxStream<'static, I> {
let stream = futures::stream::unfold(iter, |mut iter| async {
let (item, iter) = tokio::task::spawn_blocking(move || {
let item = iter.next();
(item, iter)
})
.await
.unwrap();
item.map(|item| (item, iter))
});
Box::pin(stream.fuse())
}
/// Blocks on the future from python code, interrupting future execution on Ctrl+C
/// Wraps future's output with Result that returns error when interrupted
/// If future already returns Result, use try_block_unless_interrupted
///
/// Send on this future only needed to prevent including `py` into this future
pub fn block_unless_interrupted<F: Future>(f: F) -> Result<F::Output, Error> {
block_on_exclusive(unless_interrupted(f))
}
/// Same as block_unless_interrupted but for futures that returns Result
pub fn try_block_unless_interrupted<O, E, F: Future<Output = Result<O, E>>>(f: F) -> Result<O, E>
where
E: Send,
E: From<Error>,
{
block_on_exclusive(async move { Ok(unless_interrupted(f).await??) })
}
async fn unless_interrupted<F: Future>(f: F) -> Result<F::Output, Error> {
let f = f.fuse();
let ctrlc = tokio::signal::ctrl_c().fuse();
pin_mut!(f, ctrlc);
select! {
_ = ctrlc => Err(ErrorKind::Interrupted.into()),
res = f => Ok(res),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread;
use futures::future;
use futures::stream;
#[test]
fn test_block_on_future() {
assert_eq!(block_on_future(async { 2 + 2 }), 4);
}
#[test]
#[should_panic]
fn test_block_on_future_will_panic() {
block_on_future(async {
panic!("hello future");
});
}
#[test]
fn test_panic_in_future_does_not_poisons_runtime() {
let th = thread::spawn(|| {
block_on_future(async {
panic!("no poison");
})
});
assert!(th.join().is_err());
assert_eq!(block_on_future(async { 2 + 2 }), 4);
}
#[test]
fn test_block_on_future_block_on_other_thread() {
let (tx, rx) = std::sync::mpsc::sync_channel(1);
thread::spawn(|| {
block_on_future(async move {
for i in 12.. {
tx.send(i).unwrap();
}
})
});
assert_eq!(
rx.into_iter().take(5).collect::<Vec<i32>>(),
vec![12, 13, 14, 15, 16]
);
}
#[test]
fn test_block_on_future_pseudo_parallelism() {
// This test will deadlock if threads can't schedule tasks while another thread
// is waiting for a result
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
let th1 = thread::spawn(|| block_on_future(async move { rx.recv().await }));
let _th2 = thread::spawn(|| block_on_future(async move { tx.send(5).await }));
assert_eq!(th1.join().unwrap(), Some(5));
}
#[test]
fn test_stream_to_iter() {
let stream = stream::iter(vec![42, 33, 12]);
let iter = stream_to_iter(stream);
assert_eq!(iter.collect::<Vec<_>>(), vec![42, 33, 12]);
}
#[test]
fn test_stream_to_iter_two_instances() {
let mut options = RunStreamOptions::new();
options.buffer_size(1);
let mut iter1 = options.run(stream::iter(vec![42, 33, 12]));
let mut iter2 = options.run(stream::iter(vec![11, 25, 67]));
assert_eq!(iter2.next(), Some(11));
assert_eq!(iter2.next(), Some(25));
assert_eq!(iter1.next(), Some(42));
assert_eq!(iter2.next(), Some(67));
assert_eq!(iter2.next(), None);
assert_eq!(iter1.next(), Some(33));
assert_eq!(iter1.next(), Some(12));
assert_eq!(iter1.next(), None);
}
#[test]
fn test_stream_to_iter_some_items_panic() {
let stream = stream::iter(vec![43, 33, 12, 11])
.then(future::ready)
.map(|v| {
assert!(v & 1 == 1);
v + 1
});
let iter = stream_to_iter(stream);
assert_eq!(iter.collect::<Vec<_>>(), vec![44, 34]);
}
#[tokio::test]
async fn test_iter_to_stream() {
let iter = vec![1u8, 10, 20].into_iter();
let mut stream = iter_to_stream(iter);
assert_eq!(stream.next().await, Some(1));
assert_eq!(stream.next().await, Some(10));
assert_eq!(stream.next().await, Some(20));
assert_eq!(stream.next().await, None);
assert_eq!(stream.next().await, None);
}
} | /// Convert a blocking iterator to an async stream.
/// | random_line_split |
lib.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
///! Async job scheduling utilities for a blocking application
///!
///! We have a blocking application. We have async libraries. This crate provides common utilities
///! for communicating between the blocking world and the async world. It is intended to be a guide
///! so that not all developers have to get in depth understanding of Tokio in order to use async
///! functions.
///!
///! The crate sets up a common Runtime that all async tasks run on. We use a threaded scheduler
///! which enables parallelism. The async code is expected to be ran in parallel, not just
///! concurrently. As a reminder, Python has concurrency with multiple threads but no parallelism
///! because of the global interpreter lock.
///! The Runtime will get forcefully shut down when the main thread exits. Any running background
///! work will be lost at that time. This is not a hard requirement though, we can be tweak it to
///! wait for tasks to finish but requires some ceremony around the Runtime. Since we have no need
///! for that right now so that feature is skipped for now.
///!
///! TODO(T74221415): monitoring, signal handling
use futures::future::Future;
use futures::stream::{BoxStream, Stream, StreamExt};
use futures::FutureExt;
use futures::{pin_mut, select};
use once_cell::sync::Lazy;
use std::io::{Error, ErrorKind};
use tokio::runtime::{Builder as RuntimeBuilder, Runtime};
use tokio::task::JoinHandle;
static RUNTIME: Lazy<Runtime> = Lazy::new(|| {
let nproc = num_cpus::get();
RuntimeBuilder::new_multi_thread()
.worker_threads(nproc.min(8))
.enable_all()
.build()
.expect("failed to initialize the async runtime")
});
pub static STREAM_BUFFER_SIZE: usize = 128;
/// Spawn a task using the runtime.
pub fn spawn<T>(task: T) -> JoinHandle<T::Output>
where
T: Future + Send +'static,
T::Output: Send +'static,
{
RUNTIME.spawn(task)
}
/// Run the provided function on an executor dedicated to blocking operations.
pub fn spawn_blocking<F, R>(func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send +'static,
R: Send +'static,
{
RUNTIME.spawn_blocking(func)
}
/// Blocks the current thread while waiting for the computation defined by the Future `f` to
/// complete.
///
/// Unlike `block_on_exclusive`, this can be nested without panic.
pub fn block_on_future<F>(f: F) -> F::Output
where
F::Output: Send,
F: Future + Send +'static,
{
block_on_exclusive(f)
}
/// Blocks the current thread while waiting for the computation defined by the Future `f`.
/// Also blocks other `block_on_future` calls.
///
/// This is intended to be used when `f` is not `'static` and cannot be used in
/// `block_on_future`.
pub fn block_on_exclusive<F>(f: F) -> F::Output
where
F: Future,
{
RUNTIME.block_on(f)
}
/// Takes an async stream and provide its contents in the form of a regular iterator.
///
/// If processing one of the items in the stream panics then the stream stops without further
/// feedback. It wouldn't be a bad idea to propagate the issue somehow.
///
/// This implementation will poll as long as there is space in the buffer. The sync iterator will
/// be returned practically right after the function is called. Calls to `next()` on the
/// iterator will block as long as there are no items to read from the buffer and stream items are
/// in flight. Calls to `next()` return as soon as items are available to pop from the buffer.
/// `STREAM_BUFFER_SIZE` determines the default size of the buffer. If this value is inconvenient
/// then check out `RunStreamOptions` which allows tweaking the buffer size. The buffering is just
/// to streamline the async/parallel computation and manage some of the synchronization overhead.
/// Unless the stream `s` is buffered, the items in the stream will be processed one after the
/// other.
/// When you want to process items strictly one after the other without any sort of buffering, you
/// should use `block_on_future(my_stream.next())`.
/// Example.
/// 1. unbuffered stream, stream_to_iter buffer size = 2.
/// - the stream has the first item polled and the result is added to the buffer
/// - the stream continues with polling the second item; while this is happening the iterator
/// that is returned may start being consumed releasing capacity in the buffer; for our example
/// let's say that the blocking thread hasn't reached that point yet and the stream fills the
/// buffer using the second item
/// - the stream will now poll the third item; assuming that the buffer is still full when the
/// computation is done, it will yield the thread that is is running on until the blocking
/// thread reads one of the items in the buffer.
/// 2. buffered stream over 2 items (ordered), stream_to_iter buffer = 2
/// - the stream will take 2 futures from the underlying iterator and poll on them; when the
/// first one returns it enquees the result in our buffer and polls the third future in the
/// underlying stream. Assuming that f(x) produces r(x) we could write:
/// stream: #f1, *f2, *f3, f4, f5
/// buffer: r1
/// - let's assume that the blocking thread will not consume the buffer and the next future
/// finishes; the result then fills the buffer and f4 will get polled:
/// stream: #f1, #f2, *f3, *f4, f5
/// buffer: r1, r2
/// - adding the result of the third future to the buffer will have to wait until the blocking
/// thread consumes the returned iterator; only after that will the stream proceed with
/// polling the fifth future in the stream
pub fn stream_to_iter<S>(s: S) -> RunStream<S::Item>
where
S: Stream + Unpin + Send +'static,
S::Item: Send,
{
RunStreamOptions::new().run(s)
}
/// See `stream_to_iter`. Allows tweaking run parameters. See individual methods for parameter
/// details.
pub struct RunStreamOptions {
buffer_size: usize,
}
impl RunStreamOptions {
pub fn new() -> Self {
Self {
buffer_size: STREAM_BUFFER_SIZE,
}
}
/// When dealing with heavy computation or objects a smaller buffer size may be appropriate.
/// The current implementation does not provide a means to completely wait on polling the
/// second item until the blocking thread reads the first value.
pub fn buffer_size(&mut self, buffer_size: usize) -> &mut Self {
self.buffer_size = buffer_size;
self
}
/// Takes an async stream and provide it's contents in the form of a regular iterator.
/// See `stream_to_iter`.
pub fn run<S>(&self, mut s: S) -> RunStream<S::Item>
where
S: Stream + Unpin + Send +'static,
S::Item: Send,
{
// Why use a channel vs using `std::iter::from_fn`
// It is probably a bit easier to reason about what happens when using the channel. The
// implementation details of the executor and the buffered stream don't come in discussion
// as when directly scheduling the next future. It's a bit of insurance against changes and
// it separates the two worlds more clearly. The channel approach can be optimized to
// reduce entering the async runtime context when the stream is completed faster that it is
// processed on the main thread. We could also add multiple consumers.
let (tx, rx) = tokio::sync::mpsc::channel(self.buffer_size);
let _guard = RUNTIME.enter();
tokio::spawn(async move {
while let Some(v) = s.next().await {
if tx.send(v).await.is_err() {
// receiver dropped; TODO(T74252041): add logging
return;
}
}
});
RunStream { rx: Some(rx) }
}
}
/// Blocking thread handler for receiving the results following processing a `Stream`.
pub struct RunStream<T> {
// Option is used to workaround lifetime in Iterator::next.
rx: Option<tokio::sync::mpsc::Receiver<T>>,
}
impl<T: Send +'static> Iterator for RunStream<T> {
type Item = T;
/// Returns the items extracted from processing the stream. Will return `None` when the stream's
/// end is reached or when processing an item panics.
/// See `stream_to_iter`.
fn next(&mut self) -> Option<Self::Item> {
let mut rx = self.rx.take().unwrap();
let (next, rx) = block_on_future(async {
let next = rx.recv().await;
(next, rx)
});
self.rx = Some(rx);
next
}
}
/// Convert a blocking iterator to an async stream.
///
/// Unlike `futures::stream::iter`, the iterator's `next()` function could be
/// blocking.
pub fn | <I: Send +'static>(
iter: impl Iterator<Item = I> + Send +'static,
) -> BoxStream<'static, I> {
let stream = futures::stream::unfold(iter, |mut iter| async {
let (item, iter) = tokio::task::spawn_blocking(move || {
let item = iter.next();
(item, iter)
})
.await
.unwrap();
item.map(|item| (item, iter))
});
Box::pin(stream.fuse())
}
/// Blocks on the future from python code, interrupting future execution on Ctrl+C
/// Wraps future's output with Result that returns error when interrupted
/// If future already returns Result, use try_block_unless_interrupted
///
/// Send on this future only needed to prevent including `py` into this future
pub fn block_unless_interrupted<F: Future>(f: F) -> Result<F::Output, Error> {
block_on_exclusive(unless_interrupted(f))
}
/// Same as block_unless_interrupted but for futures that returns Result
pub fn try_block_unless_interrupted<O, E, F: Future<Output = Result<O, E>>>(f: F) -> Result<O, E>
where
E: Send,
E: From<Error>,
{
block_on_exclusive(async move { Ok(unless_interrupted(f).await??) })
}
async fn unless_interrupted<F: Future>(f: F) -> Result<F::Output, Error> {
let f = f.fuse();
let ctrlc = tokio::signal::ctrl_c().fuse();
pin_mut!(f, ctrlc);
select! {
_ = ctrlc => Err(ErrorKind::Interrupted.into()),
res = f => Ok(res),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread;
use futures::future;
use futures::stream;
#[test]
fn test_block_on_future() {
assert_eq!(block_on_future(async { 2 + 2 }), 4);
}
#[test]
#[should_panic]
fn test_block_on_future_will_panic() {
block_on_future(async {
panic!("hello future");
});
}
#[test]
fn test_panic_in_future_does_not_poisons_runtime() {
let th = thread::spawn(|| {
block_on_future(async {
panic!("no poison");
})
});
assert!(th.join().is_err());
assert_eq!(block_on_future(async { 2 + 2 }), 4);
}
#[test]
fn test_block_on_future_block_on_other_thread() {
let (tx, rx) = std::sync::mpsc::sync_channel(1);
thread::spawn(|| {
block_on_future(async move {
for i in 12.. {
tx.send(i).unwrap();
}
})
});
assert_eq!(
rx.into_iter().take(5).collect::<Vec<i32>>(),
vec![12, 13, 14, 15, 16]
);
}
#[test]
fn test_block_on_future_pseudo_parallelism() {
// This test will deadlock if threads can't schedule tasks while another thread
// is waiting for a result
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
let th1 = thread::spawn(|| block_on_future(async move { rx.recv().await }));
let _th2 = thread::spawn(|| block_on_future(async move { tx.send(5).await }));
assert_eq!(th1.join().unwrap(), Some(5));
}
#[test]
fn test_stream_to_iter() {
let stream = stream::iter(vec![42, 33, 12]);
let iter = stream_to_iter(stream);
assert_eq!(iter.collect::<Vec<_>>(), vec![42, 33, 12]);
}
#[test]
fn test_stream_to_iter_two_instances() {
let mut options = RunStreamOptions::new();
options.buffer_size(1);
let mut iter1 = options.run(stream::iter(vec![42, 33, 12]));
let mut iter2 = options.run(stream::iter(vec![11, 25, 67]));
assert_eq!(iter2.next(), Some(11));
assert_eq!(iter2.next(), Some(25));
assert_eq!(iter1.next(), Some(42));
assert_eq!(iter2.next(), Some(67));
assert_eq!(iter2.next(), None);
assert_eq!(iter1.next(), Some(33));
assert_eq!(iter1.next(), Some(12));
assert_eq!(iter1.next(), None);
}
#[test]
fn test_stream_to_iter_some_items_panic() {
let stream = stream::iter(vec![43, 33, 12, 11])
.then(future::ready)
.map(|v| {
assert!(v & 1 == 1);
v + 1
});
let iter = stream_to_iter(stream);
assert_eq!(iter.collect::<Vec<_>>(), vec![44, 34]);
}
#[tokio::test]
async fn test_iter_to_stream() {
let iter = vec![1u8, 10, 20].into_iter();
let mut stream = iter_to_stream(iter);
assert_eq!(stream.next().await, Some(1));
assert_eq!(stream.next().await, Some(10));
assert_eq!(stream.next().await, Some(20));
assert_eq!(stream.next().await, None);
assert_eq!(stream.next().await, None);
}
}
| iter_to_stream | identifier_name |
lib.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
///! Async job scheduling utilities for a blocking application
///!
///! We have a blocking application. We have async libraries. This crate provides common utilities
///! for communicating between the blocking world and the async world. It is intended to be a guide
///! so that not all developers have to get in depth understanding of Tokio in order to use async
///! functions.
///!
///! The crate sets up a common Runtime that all async tasks run on. We use a threaded scheduler
///! which enables parallelism. The async code is expected to be ran in parallel, not just
///! concurrently. As a reminder, Python has concurrency with multiple threads but no parallelism
///! because of the global interpreter lock.
///! The Runtime will get forcefully shut down when the main thread exits. Any running background
///! work will be lost at that time. This is not a hard requirement though, we can be tweak it to
///! wait for tasks to finish but requires some ceremony around the Runtime. Since we have no need
///! for that right now so that feature is skipped for now.
///!
///! TODO(T74221415): monitoring, signal handling
use futures::future::Future;
use futures::stream::{BoxStream, Stream, StreamExt};
use futures::FutureExt;
use futures::{pin_mut, select};
use once_cell::sync::Lazy;
use std::io::{Error, ErrorKind};
use tokio::runtime::{Builder as RuntimeBuilder, Runtime};
use tokio::task::JoinHandle;
static RUNTIME: Lazy<Runtime> = Lazy::new(|| {
let nproc = num_cpus::get();
RuntimeBuilder::new_multi_thread()
.worker_threads(nproc.min(8))
.enable_all()
.build()
.expect("failed to initialize the async runtime")
});
pub static STREAM_BUFFER_SIZE: usize = 128;
/// Spawn a task using the runtime.
pub fn spawn<T>(task: T) -> JoinHandle<T::Output>
where
T: Future + Send +'static,
T::Output: Send +'static,
{
RUNTIME.spawn(task)
}
/// Run the provided function on an executor dedicated to blocking operations.
pub fn spawn_blocking<F, R>(func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send +'static,
R: Send +'static,
{
RUNTIME.spawn_blocking(func)
}
/// Blocks the current thread while waiting for the computation defined by the Future `f` to
/// complete.
///
/// Unlike `block_on_exclusive`, this can be nested without panic.
pub fn block_on_future<F>(f: F) -> F::Output
where
F::Output: Send,
F: Future + Send +'static,
{
block_on_exclusive(f)
}
/// Blocks the current thread while waiting for the computation defined by the Future `f`.
/// Also blocks other `block_on_future` calls.
///
/// This is intended to be used when `f` is not `'static` and cannot be used in
/// `block_on_future`.
pub fn block_on_exclusive<F>(f: F) -> F::Output
where
F: Future,
{
RUNTIME.block_on(f)
}
/// Takes an async stream and provide its contents in the form of a regular iterator.
///
/// If processing one of the items in the stream panics then the stream stops without further
/// feedback. It wouldn't be a bad idea to propagate the issue somehow.
///
/// This implementation will poll as long as there is space in the buffer. The sync iterator will
/// be returned practically right after the function is called. Calls to `next()` on the
/// iterator will block as long as there are no items to read from the buffer and stream items are
/// in flight. Calls to `next()` return as soon as items are available to pop from the buffer.
/// `STREAM_BUFFER_SIZE` determines the default size of the buffer. If this value is inconvenient
/// then check out `RunStreamOptions` which allows tweaking the buffer size. The buffering is just
/// to streamline the async/parallel computation and manage some of the synchronization overhead.
/// Unless the stream `s` is buffered, the items in the stream will be processed one after the
/// other.
/// When you want to process items strictly one after the other without any sort of buffering, you
/// should use `block_on_future(my_stream.next())`.
/// Example.
/// 1. unbuffered stream, stream_to_iter buffer size = 2.
/// - the stream has the first item polled and the result is added to the buffer
/// - the stream continues with polling the second item; while this is happening the iterator
/// that is returned may start being consumed releasing capacity in the buffer; for our example
/// let's say that the blocking thread hasn't reached that point yet and the stream fills the
/// buffer using the second item
/// - the stream will now poll the third item; assuming that the buffer is still full when the
/// computation is done, it will yield the thread that is is running on until the blocking
/// thread reads one of the items in the buffer.
/// 2. buffered stream over 2 items (ordered), stream_to_iter buffer = 2
/// - the stream will take 2 futures from the underlying iterator and poll on them; when the
/// first one returns it enquees the result in our buffer and polls the third future in the
/// underlying stream. Assuming that f(x) produces r(x) we could write:
/// stream: #f1, *f2, *f3, f4, f5
/// buffer: r1
/// - let's assume that the blocking thread will not consume the buffer and the next future
/// finishes; the result then fills the buffer and f4 will get polled:
/// stream: #f1, #f2, *f3, *f4, f5
/// buffer: r1, r2
/// - adding the result of the third future to the buffer will have to wait until the blocking
/// thread consumes the returned iterator; only after that will the stream proceed with
/// polling the fifth future in the stream
pub fn stream_to_iter<S>(s: S) -> RunStream<S::Item>
where
S: Stream + Unpin + Send +'static,
S::Item: Send,
{
RunStreamOptions::new().run(s)
}
/// See `stream_to_iter`. Allows tweaking run parameters. See individual methods for parameter
/// details.
pub struct RunStreamOptions {
buffer_size: usize,
}
impl RunStreamOptions {
pub fn new() -> Self {
Self {
buffer_size: STREAM_BUFFER_SIZE,
}
}
/// When dealing with heavy computation or objects a smaller buffer size may be appropriate.
/// The current implementation does not provide a means to completely wait on polling the
/// second item until the blocking thread reads the first value.
pub fn buffer_size(&mut self, buffer_size: usize) -> &mut Self {
self.buffer_size = buffer_size;
self
}
/// Takes an async stream and provide it's contents in the form of a regular iterator.
/// See `stream_to_iter`.
pub fn run<S>(&self, mut s: S) -> RunStream<S::Item>
where
S: Stream + Unpin + Send +'static,
S::Item: Send,
{
// Why use a channel vs using `std::iter::from_fn`
// It is probably a bit easier to reason about what happens when using the channel. The
// implementation details of the executor and the buffered stream don't come in discussion
// as when directly scheduling the next future. It's a bit of insurance against changes and
// it separates the two worlds more clearly. The channel approach can be optimized to
// reduce entering the async runtime context when the stream is completed faster that it is
// processed on the main thread. We could also add multiple consumers.
let (tx, rx) = tokio::sync::mpsc::channel(self.buffer_size);
let _guard = RUNTIME.enter();
tokio::spawn(async move {
while let Some(v) = s.next().await {
if tx.send(v).await.is_err() {
// receiver dropped; TODO(T74252041): add logging
return;
}
}
});
RunStream { rx: Some(rx) }
}
}
/// Blocking thread handler for receiving the results following processing a `Stream`.
pub struct RunStream<T> {
// Option is used to workaround lifetime in Iterator::next.
rx: Option<tokio::sync::mpsc::Receiver<T>>,
}
impl<T: Send +'static> Iterator for RunStream<T> {
type Item = T;
/// Returns the items extracted from processing the stream. Will return `None` when the stream's
/// end is reached or when processing an item panics.
/// See `stream_to_iter`.
fn next(&mut self) -> Option<Self::Item> |
}
/// Convert a blocking iterator to an async stream.
///
/// Unlike `futures::stream::iter`, the iterator's `next()` function could be
/// blocking.
pub fn iter_to_stream<I: Send +'static>(
iter: impl Iterator<Item = I> + Send +'static,
) -> BoxStream<'static, I> {
let stream = futures::stream::unfold(iter, |mut iter| async {
let (item, iter) = tokio::task::spawn_blocking(move || {
let item = iter.next();
(item, iter)
})
.await
.unwrap();
item.map(|item| (item, iter))
});
Box::pin(stream.fuse())
}
/// Blocks on the future from python code, interrupting future execution on Ctrl+C
/// Wraps future's output with Result that returns error when interrupted
/// If future already returns Result, use try_block_unless_interrupted
///
/// Send on this future only needed to prevent including `py` into this future
pub fn block_unless_interrupted<F: Future>(f: F) -> Result<F::Output, Error> {
block_on_exclusive(unless_interrupted(f))
}
/// Same as block_unless_interrupted but for futures that returns Result
pub fn try_block_unless_interrupted<O, E, F: Future<Output = Result<O, E>>>(f: F) -> Result<O, E>
where
E: Send,
E: From<Error>,
{
block_on_exclusive(async move { Ok(unless_interrupted(f).await??) })
}
async fn unless_interrupted<F: Future>(f: F) -> Result<F::Output, Error> {
let f = f.fuse();
let ctrlc = tokio::signal::ctrl_c().fuse();
pin_mut!(f, ctrlc);
select! {
_ = ctrlc => Err(ErrorKind::Interrupted.into()),
res = f => Ok(res),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread;
use futures::future;
use futures::stream;
#[test]
fn test_block_on_future() {
assert_eq!(block_on_future(async { 2 + 2 }), 4);
}
#[test]
#[should_panic]
fn test_block_on_future_will_panic() {
block_on_future(async {
panic!("hello future");
});
}
#[test]
fn test_panic_in_future_does_not_poisons_runtime() {
let th = thread::spawn(|| {
block_on_future(async {
panic!("no poison");
})
});
assert!(th.join().is_err());
assert_eq!(block_on_future(async { 2 + 2 }), 4);
}
#[test]
fn test_block_on_future_block_on_other_thread() {
let (tx, rx) = std::sync::mpsc::sync_channel(1);
thread::spawn(|| {
block_on_future(async move {
for i in 12.. {
tx.send(i).unwrap();
}
})
});
assert_eq!(
rx.into_iter().take(5).collect::<Vec<i32>>(),
vec![12, 13, 14, 15, 16]
);
}
#[test]
fn test_block_on_future_pseudo_parallelism() {
// This test will deadlock if threads can't schedule tasks while another thread
// is waiting for a result
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
let th1 = thread::spawn(|| block_on_future(async move { rx.recv().await }));
let _th2 = thread::spawn(|| block_on_future(async move { tx.send(5).await }));
assert_eq!(th1.join().unwrap(), Some(5));
}
#[test]
fn test_stream_to_iter() {
let stream = stream::iter(vec![42, 33, 12]);
let iter = stream_to_iter(stream);
assert_eq!(iter.collect::<Vec<_>>(), vec![42, 33, 12]);
}
#[test]
fn test_stream_to_iter_two_instances() {
let mut options = RunStreamOptions::new();
options.buffer_size(1);
let mut iter1 = options.run(stream::iter(vec![42, 33, 12]));
let mut iter2 = options.run(stream::iter(vec![11, 25, 67]));
assert_eq!(iter2.next(), Some(11));
assert_eq!(iter2.next(), Some(25));
assert_eq!(iter1.next(), Some(42));
assert_eq!(iter2.next(), Some(67));
assert_eq!(iter2.next(), None);
assert_eq!(iter1.next(), Some(33));
assert_eq!(iter1.next(), Some(12));
assert_eq!(iter1.next(), None);
}
#[test]
fn test_stream_to_iter_some_items_panic() {
let stream = stream::iter(vec![43, 33, 12, 11])
.then(future::ready)
.map(|v| {
assert!(v & 1 == 1);
v + 1
});
let iter = stream_to_iter(stream);
assert_eq!(iter.collect::<Vec<_>>(), vec![44, 34]);
}
#[tokio::test]
async fn test_iter_to_stream() {
let iter = vec![1u8, 10, 20].into_iter();
let mut stream = iter_to_stream(iter);
assert_eq!(stream.next().await, Some(1));
assert_eq!(stream.next().await, Some(10));
assert_eq!(stream.next().await, Some(20));
assert_eq!(stream.next().await, None);
assert_eq!(stream.next().await, None);
}
}
| {
let mut rx = self.rx.take().unwrap();
let (next, rx) = block_on_future(async {
let next = rx.recv().await;
(next, rx)
});
self.rx = Some(rx);
next
} | identifier_body |
lib.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
///! Async job scheduling utilities for a blocking application
///!
///! We have a blocking application. We have async libraries. This crate provides common utilities
///! for communicating between the blocking world and the async world. It is intended to be a guide
///! so that not all developers have to get in depth understanding of Tokio in order to use async
///! functions.
///!
///! The crate sets up a common Runtime that all async tasks run on. We use a threaded scheduler
///! which enables parallelism. The async code is expected to be ran in parallel, not just
///! concurrently. As a reminder, Python has concurrency with multiple threads but no parallelism
///! because of the global interpreter lock.
///! The Runtime will get forcefully shut down when the main thread exits. Any running background
///! work will be lost at that time. This is not a hard requirement though, we can be tweak it to
///! wait for tasks to finish but requires some ceremony around the Runtime. Since we have no need
///! for that right now so that feature is skipped for now.
///!
///! TODO(T74221415): monitoring, signal handling
use futures::future::Future;
use futures::stream::{BoxStream, Stream, StreamExt};
use futures::FutureExt;
use futures::{pin_mut, select};
use once_cell::sync::Lazy;
use std::io::{Error, ErrorKind};
use tokio::runtime::{Builder as RuntimeBuilder, Runtime};
use tokio::task::JoinHandle;
static RUNTIME: Lazy<Runtime> = Lazy::new(|| {
let nproc = num_cpus::get();
RuntimeBuilder::new_multi_thread()
.worker_threads(nproc.min(8))
.enable_all()
.build()
.expect("failed to initialize the async runtime")
});
pub static STREAM_BUFFER_SIZE: usize = 128;
/// Spawn a task using the runtime.
pub fn spawn<T>(task: T) -> JoinHandle<T::Output>
where
T: Future + Send +'static,
T::Output: Send +'static,
{
RUNTIME.spawn(task)
}
/// Run the provided function on an executor dedicated to blocking operations.
pub fn spawn_blocking<F, R>(func: F) -> JoinHandle<R>
where
F: FnOnce() -> R + Send +'static,
R: Send +'static,
{
RUNTIME.spawn_blocking(func)
}
/// Blocks the current thread while waiting for the computation defined by the Future `f` to
/// complete.
///
/// Unlike `block_on_exclusive`, this can be nested without panic.
pub fn block_on_future<F>(f: F) -> F::Output
where
F::Output: Send,
F: Future + Send +'static,
{
block_on_exclusive(f)
}
/// Blocks the current thread while waiting for the computation defined by the Future `f`.
/// Also blocks other `block_on_future` calls.
///
/// This is intended to be used when `f` is not `'static` and cannot be used in
/// `block_on_future`.
pub fn block_on_exclusive<F>(f: F) -> F::Output
where
F: Future,
{
RUNTIME.block_on(f)
}
/// Takes an async stream and provide its contents in the form of a regular iterator.
///
/// If processing one of the items in the stream panics then the stream stops without further
/// feedback. It wouldn't be a bad idea to propagate the issue somehow.
///
/// This implementation will poll as long as there is space in the buffer. The sync iterator will
/// be returned practically right after the function is called. Calls to `next()` on the
/// iterator will block as long as there are no items to read from the buffer and stream items are
/// in flight. Calls to `next()` return as soon as items are available to pop from the buffer.
/// `STREAM_BUFFER_SIZE` determines the default size of the buffer. If this value is inconvenient
/// then check out `RunStreamOptions` which allows tweaking the buffer size. The buffering is just
/// to streamline the async/parallel computation and manage some of the synchronization overhead.
/// Unless the stream `s` is buffered, the items in the stream will be processed one after the
/// other.
/// When you want to process items strictly one after the other without any sort of buffering, you
/// should use `block_on_future(my_stream.next())`.
/// Example.
/// 1. unbuffered stream, stream_to_iter buffer size = 2.
/// - the stream has the first item polled and the result is added to the buffer
/// - the stream continues with polling the second item; while this is happening the iterator
/// that is returned may start being consumed releasing capacity in the buffer; for our example
/// let's say that the blocking thread hasn't reached that point yet and the stream fills the
/// buffer using the second item
/// - the stream will now poll the third item; assuming that the buffer is still full when the
/// computation is done, it will yield the thread that is is running on until the blocking
/// thread reads one of the items in the buffer.
/// 2. buffered stream over 2 items (ordered), stream_to_iter buffer = 2
/// - the stream will take 2 futures from the underlying iterator and poll on them; when the
/// first one returns it enquees the result in our buffer and polls the third future in the
/// underlying stream. Assuming that f(x) produces r(x) we could write:
/// stream: #f1, *f2, *f3, f4, f5
/// buffer: r1
/// - let's assume that the blocking thread will not consume the buffer and the next future
/// finishes; the result then fills the buffer and f4 will get polled:
/// stream: #f1, #f2, *f3, *f4, f5
/// buffer: r1, r2
/// - adding the result of the third future to the buffer will have to wait until the blocking
/// thread consumes the returned iterator; only after that will the stream proceed with
/// polling the fifth future in the stream
pub fn stream_to_iter<S>(s: S) -> RunStream<S::Item>
where
S: Stream + Unpin + Send +'static,
S::Item: Send,
{
RunStreamOptions::new().run(s)
}
/// See `stream_to_iter`. Allows tweaking run parameters. See individual methods for parameter
/// details.
pub struct RunStreamOptions {
buffer_size: usize,
}
impl RunStreamOptions {
pub fn new() -> Self {
Self {
buffer_size: STREAM_BUFFER_SIZE,
}
}
/// When dealing with heavy computation or objects a smaller buffer size may be appropriate.
/// The current implementation does not provide a means to completely wait on polling the
/// second item until the blocking thread reads the first value.
pub fn buffer_size(&mut self, buffer_size: usize) -> &mut Self {
self.buffer_size = buffer_size;
self
}
/// Takes an async stream and provide it's contents in the form of a regular iterator.
/// See `stream_to_iter`.
pub fn run<S>(&self, mut s: S) -> RunStream<S::Item>
where
S: Stream + Unpin + Send +'static,
S::Item: Send,
{
// Why use a channel vs using `std::iter::from_fn`
// It is probably a bit easier to reason about what happens when using the channel. The
// implementation details of the executor and the buffered stream don't come in discussion
// as when directly scheduling the next future. It's a bit of insurance against changes and
// it separates the two worlds more clearly. The channel approach can be optimized to
// reduce entering the async runtime context when the stream is completed faster that it is
// processed on the main thread. We could also add multiple consumers.
let (tx, rx) = tokio::sync::mpsc::channel(self.buffer_size);
let _guard = RUNTIME.enter();
tokio::spawn(async move {
while let Some(v) = s.next().await {
if tx.send(v).await.is_err() |
}
});
RunStream { rx: Some(rx) }
}
}
/// Blocking thread handler for receiving the results following processing a `Stream`.
pub struct RunStream<T> {
// Option is used to workaround lifetime in Iterator::next.
rx: Option<tokio::sync::mpsc::Receiver<T>>,
}
impl<T: Send +'static> Iterator for RunStream<T> {
type Item = T;
/// Returns the items extracted from processing the stream. Will return `None` when the stream's
/// end is reached or when processing an item panics.
/// See `stream_to_iter`.
fn next(&mut self) -> Option<Self::Item> {
let mut rx = self.rx.take().unwrap();
let (next, rx) = block_on_future(async {
let next = rx.recv().await;
(next, rx)
});
self.rx = Some(rx);
next
}
}
/// Convert a blocking iterator to an async stream.
///
/// Unlike `futures::stream::iter`, the iterator's `next()` function could be
/// blocking.
pub fn iter_to_stream<I: Send +'static>(
iter: impl Iterator<Item = I> + Send +'static,
) -> BoxStream<'static, I> {
let stream = futures::stream::unfold(iter, |mut iter| async {
let (item, iter) = tokio::task::spawn_blocking(move || {
let item = iter.next();
(item, iter)
})
.await
.unwrap();
item.map(|item| (item, iter))
});
Box::pin(stream.fuse())
}
/// Blocks on the future from python code, interrupting future execution on Ctrl+C
/// Wraps future's output with Result that returns error when interrupted
/// If future already returns Result, use try_block_unless_interrupted
///
/// Send on this future only needed to prevent including `py` into this future
pub fn block_unless_interrupted<F: Future>(f: F) -> Result<F::Output, Error> {
block_on_exclusive(unless_interrupted(f))
}
/// Same as block_unless_interrupted but for futures that returns Result
pub fn try_block_unless_interrupted<O, E, F: Future<Output = Result<O, E>>>(f: F) -> Result<O, E>
where
E: Send,
E: From<Error>,
{
block_on_exclusive(async move { Ok(unless_interrupted(f).await??) })
}
async fn unless_interrupted<F: Future>(f: F) -> Result<F::Output, Error> {
let f = f.fuse();
let ctrlc = tokio::signal::ctrl_c().fuse();
pin_mut!(f, ctrlc);
select! {
_ = ctrlc => Err(ErrorKind::Interrupted.into()),
res = f => Ok(res),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread;
use futures::future;
use futures::stream;
#[test]
fn test_block_on_future() {
assert_eq!(block_on_future(async { 2 + 2 }), 4);
}
#[test]
#[should_panic]
fn test_block_on_future_will_panic() {
block_on_future(async {
panic!("hello future");
});
}
#[test]
fn test_panic_in_future_does_not_poisons_runtime() {
let th = thread::spawn(|| {
block_on_future(async {
panic!("no poison");
})
});
assert!(th.join().is_err());
assert_eq!(block_on_future(async { 2 + 2 }), 4);
}
#[test]
fn test_block_on_future_block_on_other_thread() {
let (tx, rx) = std::sync::mpsc::sync_channel(1);
thread::spawn(|| {
block_on_future(async move {
for i in 12.. {
tx.send(i).unwrap();
}
})
});
assert_eq!(
rx.into_iter().take(5).collect::<Vec<i32>>(),
vec![12, 13, 14, 15, 16]
);
}
#[test]
fn test_block_on_future_pseudo_parallelism() {
// This test will deadlock if threads can't schedule tasks while another thread
// is waiting for a result
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
let th1 = thread::spawn(|| block_on_future(async move { rx.recv().await }));
let _th2 = thread::spawn(|| block_on_future(async move { tx.send(5).await }));
assert_eq!(th1.join().unwrap(), Some(5));
}
#[test]
fn test_stream_to_iter() {
let stream = stream::iter(vec![42, 33, 12]);
let iter = stream_to_iter(stream);
assert_eq!(iter.collect::<Vec<_>>(), vec![42, 33, 12]);
}
#[test]
fn test_stream_to_iter_two_instances() {
let mut options = RunStreamOptions::new();
options.buffer_size(1);
let mut iter1 = options.run(stream::iter(vec![42, 33, 12]));
let mut iter2 = options.run(stream::iter(vec![11, 25, 67]));
assert_eq!(iter2.next(), Some(11));
assert_eq!(iter2.next(), Some(25));
assert_eq!(iter1.next(), Some(42));
assert_eq!(iter2.next(), Some(67));
assert_eq!(iter2.next(), None);
assert_eq!(iter1.next(), Some(33));
assert_eq!(iter1.next(), Some(12));
assert_eq!(iter1.next(), None);
}
#[test]
fn test_stream_to_iter_some_items_panic() {
let stream = stream::iter(vec![43, 33, 12, 11])
.then(future::ready)
.map(|v| {
assert!(v & 1 == 1);
v + 1
});
let iter = stream_to_iter(stream);
assert_eq!(iter.collect::<Vec<_>>(), vec![44, 34]);
}
#[tokio::test]
async fn test_iter_to_stream() {
let iter = vec![1u8, 10, 20].into_iter();
let mut stream = iter_to_stream(iter);
assert_eq!(stream.next().await, Some(1));
assert_eq!(stream.next().await, Some(10));
assert_eq!(stream.next().await, Some(20));
assert_eq!(stream.next().await, None);
assert_eq!(stream.next().await, None);
}
}
| {
// receiver dropped; TODO(T74252041): add logging
return;
} | conditional_block |
lib.rs | use anyhow::{Context, Error};
use next_swc::{custom_before_pass, TransformOptions};
use once_cell::sync::Lazy;
use std::sync::Arc;
use swc::{config::JsMinifyOptions, try_with_handler, Compiler};
use swc_common::{FileName, FilePathMapping, SourceMap};
use swc_ecmascript::transforms::pass::noop;
use wasm_bindgen::prelude::*;
fn convert_err(err: Error) -> JsValue {
format!("{:?}", err).into()
}
#[wasm_bindgen(js_name = "minifySync")]
pub fn minify_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once();
let c = compiler();
try_with_handler(c.cm.clone(), false, |handler| {
let opts: JsMinifyOptions = opts.into_serde().context("failed to parse options")?;
let fm = c.cm.new_source_file(FileName::Anon, s.into());
let program = c
.minify(fm, handler, &opts)
.context("failed to minify file")?;
JsValue::from_serde(&program).context("failed to serialize json")
})
.map_err(convert_err)
}
#[wasm_bindgen(js_name = "transformSync")]
pub fn transform_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once();
let c = compiler();
try_with_handler(c.cm.clone(), false, |handler| {
let opts: TransformOptions = opts.into_serde().context("failed to parse options")?;
let fm = c.cm.new_source_file(
if opts.swc.filename.is_empty() | else {
FileName::Real(opts.swc.filename.clone().into())
},
s.into(),
);
let before_pass = custom_before_pass(c.cm.clone(), fm.clone(), &opts);
let out = c
.process_js_with_custom_pass(fm, None, handler, &opts.swc, |_| before_pass, |_| noop())
.context("failed to process js file")?;
JsValue::from_serde(&out).context("failed to serialize json")
})
.map_err(convert_err)
}
/// Get global sourcemap
fn compiler() -> Arc<Compiler> {
static C: Lazy<Arc<Compiler>> = Lazy::new(|| {
let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));
Arc::new(Compiler::new(cm))
});
C.clone()
}
| {
FileName::Anon
} | conditional_block |
lib.rs | use anyhow::{Context, Error};
use next_swc::{custom_before_pass, TransformOptions};
use once_cell::sync::Lazy;
use std::sync::Arc;
use swc::{config::JsMinifyOptions, try_with_handler, Compiler};
use swc_common::{FileName, FilePathMapping, SourceMap};
use swc_ecmascript::transforms::pass::noop;
use wasm_bindgen::prelude::*;
fn convert_err(err: Error) -> JsValue {
format!("{:?}", err).into()
}
#[wasm_bindgen(js_name = "minifySync")]
pub fn minify_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once();
let c = compiler();
try_with_handler(c.cm.clone(), false, |handler| {
let opts: JsMinifyOptions = opts.into_serde().context("failed to parse options")?;
let fm = c.cm.new_source_file(FileName::Anon, s.into());
let program = c
.minify(fm, handler, &opts)
.context("failed to minify file")?;
JsValue::from_serde(&program).context("failed to serialize json")
})
.map_err(convert_err)
}
#[wasm_bindgen(js_name = "transformSync")]
pub fn transform_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once();
let c = compiler();
try_with_handler(c.cm.clone(), false, |handler| {
let opts: TransformOptions = opts.into_serde().context("failed to parse options")?;
let fm = c.cm.new_source_file(
if opts.swc.filename.is_empty() {
FileName::Anon
} else {
FileName::Real(opts.swc.filename.clone().into())
},
s.into(), |
JsValue::from_serde(&out).context("failed to serialize json")
})
.map_err(convert_err)
}
/// Get global sourcemap
fn compiler() -> Arc<Compiler> {
static C: Lazy<Arc<Compiler>> = Lazy::new(|| {
let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));
Arc::new(Compiler::new(cm))
});
C.clone()
} | );
let before_pass = custom_before_pass(c.cm.clone(), fm.clone(), &opts);
let out = c
.process_js_with_custom_pass(fm, None, handler, &opts.swc, |_| before_pass, |_| noop())
.context("failed to process js file")?; | random_line_split |
lib.rs | use anyhow::{Context, Error};
use next_swc::{custom_before_pass, TransformOptions};
use once_cell::sync::Lazy;
use std::sync::Arc;
use swc::{config::JsMinifyOptions, try_with_handler, Compiler};
use swc_common::{FileName, FilePathMapping, SourceMap};
use swc_ecmascript::transforms::pass::noop;
use wasm_bindgen::prelude::*;
fn convert_err(err: Error) -> JsValue {
format!("{:?}", err).into()
}
#[wasm_bindgen(js_name = "minifySync")]
pub fn minify_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once();
let c = compiler();
try_with_handler(c.cm.clone(), false, |handler| {
let opts: JsMinifyOptions = opts.into_serde().context("failed to parse options")?;
let fm = c.cm.new_source_file(FileName::Anon, s.into());
let program = c
.minify(fm, handler, &opts)
.context("failed to minify file")?;
JsValue::from_serde(&program).context("failed to serialize json")
})
.map_err(convert_err)
}
#[wasm_bindgen(js_name = "transformSync")]
pub fn transform_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once();
let c = compiler();
try_with_handler(c.cm.clone(), false, |handler| {
let opts: TransformOptions = opts.into_serde().context("failed to parse options")?;
let fm = c.cm.new_source_file(
if opts.swc.filename.is_empty() {
FileName::Anon
} else {
FileName::Real(opts.swc.filename.clone().into())
},
s.into(),
);
let before_pass = custom_before_pass(c.cm.clone(), fm.clone(), &opts);
let out = c
.process_js_with_custom_pass(fm, None, handler, &opts.swc, |_| before_pass, |_| noop())
.context("failed to process js file")?;
JsValue::from_serde(&out).context("failed to serialize json")
})
.map_err(convert_err)
}
/// Get global sourcemap
fn | () -> Arc<Compiler> {
static C: Lazy<Arc<Compiler>> = Lazy::new(|| {
let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));
Arc::new(Compiler::new(cm))
});
C.clone()
}
| compiler | identifier_name |
lib.rs | use anyhow::{Context, Error};
use next_swc::{custom_before_pass, TransformOptions};
use once_cell::sync::Lazy;
use std::sync::Arc;
use swc::{config::JsMinifyOptions, try_with_handler, Compiler};
use swc_common::{FileName, FilePathMapping, SourceMap};
use swc_ecmascript::transforms::pass::noop;
use wasm_bindgen::prelude::*;
fn convert_err(err: Error) -> JsValue {
format!("{:?}", err).into()
}
#[wasm_bindgen(js_name = "minifySync")]
pub fn minify_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once();
let c = compiler();
try_with_handler(c.cm.clone(), false, |handler| {
let opts: JsMinifyOptions = opts.into_serde().context("failed to parse options")?;
let fm = c.cm.new_source_file(FileName::Anon, s.into());
let program = c
.minify(fm, handler, &opts)
.context("failed to minify file")?;
JsValue::from_serde(&program).context("failed to serialize json")
})
.map_err(convert_err)
}
#[wasm_bindgen(js_name = "transformSync")]
pub fn transform_sync(s: &str, opts: JsValue) -> Result<JsValue, JsValue> {
console_error_panic_hook::set_once();
let c = compiler();
try_with_handler(c.cm.clone(), false, |handler| {
let opts: TransformOptions = opts.into_serde().context("failed to parse options")?;
let fm = c.cm.new_source_file(
if opts.swc.filename.is_empty() {
FileName::Anon
} else {
FileName::Real(opts.swc.filename.clone().into())
},
s.into(),
);
let before_pass = custom_before_pass(c.cm.clone(), fm.clone(), &opts);
let out = c
.process_js_with_custom_pass(fm, None, handler, &opts.swc, |_| before_pass, |_| noop())
.context("failed to process js file")?;
JsValue::from_serde(&out).context("failed to serialize json")
})
.map_err(convert_err)
}
/// Get global sourcemap
fn compiler() -> Arc<Compiler> | {
static C: Lazy<Arc<Compiler>> = Lazy::new(|| {
let cm = Arc::new(SourceMap::new(FilePathMapping::empty()));
Arc::new(Compiler::new(cm))
});
C.clone()
} | identifier_body |
|
11_only_specific_values.rs | extern crate clap;
use clap::{App, Arg};
fn main() {
// If you have arguments of specific values you want to test for, you can use the
//.possible_values() method of Arg
//
// This allows you specify the valid values for that argument. If the user does not use one of
// those specific values, they will receive a graceful exit with error message informing them
// of the mistake, and what the possible valid values are
//
// For this example, assume you want one positional argument of either "fast" or "slow"
// i.e. the only possible ways to run the program are "myprog fast" or "myprog slow"
let mode_vals = ["fast", "slow"];
let matches = App::new("myapp").about("does awesome things")
.arg(Arg::with_name("MODE")
.help("What mode to run the program in")
.index(1)
.possible_values(&mode_vals)
.required(true))
.get_matches();
// Note, it's safe to call unwrap() because the arg is required
match matches.value_of("MODE").unwrap() {
"fast" => | ,
"slow" => {
// Do slow things...
},
_ => unreachable!()
}
} | {
// Do fast things...
} | conditional_block |
11_only_specific_values.rs | extern crate clap;
use clap::{App, Arg};
fn main() | match matches.value_of("MODE").unwrap() {
"fast" => {
// Do fast things...
},
"slow" => {
// Do slow things...
},
_ => unreachable!()
}
} | {
// If you have arguments of specific values you want to test for, you can use the
// .possible_values() method of Arg
//
// This allows you specify the valid values for that argument. If the user does not use one of
// those specific values, they will receive a graceful exit with error message informing them
// of the mistake, and what the possible valid values are
//
// For this example, assume you want one positional argument of either "fast" or "slow"
// i.e. the only possible ways to run the program are "myprog fast" or "myprog slow"
let mode_vals = ["fast", "slow"];
let matches = App::new("myapp").about("does awesome things")
.arg(Arg::with_name("MODE")
.help("What mode to run the program in")
.index(1)
.possible_values(&mode_vals)
.required(true))
.get_matches();
// Note, it's safe to call unwrap() because the arg is required | identifier_body |
11_only_specific_values.rs | extern crate clap;
use clap::{App, Arg};
fn | () {
// If you have arguments of specific values you want to test for, you can use the
//.possible_values() method of Arg
//
// This allows you specify the valid values for that argument. If the user does not use one of
// those specific values, they will receive a graceful exit with error message informing them
// of the mistake, and what the possible valid values are
//
// For this example, assume you want one positional argument of either "fast" or "slow"
// i.e. the only possible ways to run the program are "myprog fast" or "myprog slow"
let mode_vals = ["fast", "slow"];
let matches = App::new("myapp").about("does awesome things")
.arg(Arg::with_name("MODE")
.help("What mode to run the program in")
.index(1)
.possible_values(&mode_vals)
.required(true))
.get_matches();
// Note, it's safe to call unwrap() because the arg is required
match matches.value_of("MODE").unwrap() {
"fast" => {
// Do fast things...
},
"slow" => {
// Do slow things...
},
_ => unreachable!()
}
} | main | identifier_name |
11_only_specific_values.rs | extern crate clap;
use clap::{App, Arg};
fn main() {
// If you have arguments of specific values you want to test for, you can use the
//.possible_values() method of Arg
//
// This allows you specify the valid values for that argument. If the user does not use one of
// those specific values, they will receive a graceful exit with error message informing them
// of the mistake, and what the possible valid values are
//
// For this example, assume you want one positional argument of either "fast" or "slow"
// i.e. the only possible ways to run the program are "myprog fast" or "myprog slow"
let mode_vals = ["fast", "slow"];
let matches = App::new("myapp").about("does awesome things")
.arg(Arg::with_name("MODE")
.help("What mode to run the program in")
.index(1) |
// Note, it's safe to call unwrap() because the arg is required
match matches.value_of("MODE").unwrap() {
"fast" => {
// Do fast things...
},
"slow" => {
// Do slow things...
},
_ => unreachable!()
}
} | .possible_values(&mode_vals)
.required(true))
.get_matches(); | random_line_split |
2_primitives.rs | /*
array A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time constant size, N.
bool The boolean type.
char A character type.
f32 The 32-bit floating point type.
f64 The 64-bit floating point type.
i16 The 16-bit signed integer type.
i32 The 32-bit signed integer type.
i64 The 64-bit signed integer type.
i8 The 8-bit signed integer type.
isize The pointer-sized signed integer type.
pointer Raw, unsafe pointers, *const T, and *mut T.
slice A dynamically-sized view into a contiguous sequence, [T].
str String slices.
tuple A finite heterogeneous sequence, (T, U,..).
u16 The 16-bit unsigned integer type.
u32 The 32-bit unsigned integer type.
u64 The 64-bit unsigned integer type.
u8 The 8-bit unsigned integer type.
usize The pointer-sized unsigned integer type.
*/
fn main() | {
let age: u32 = 30;
let score: f64 = std::f64::consts::PI;
{
let mut age_copy = age;
age_copy = 15;
println!("age_copy = {:?}\n", age_copy);
}
assert_eq!(30, age);
println!("age = {:?}", age);
println!("score = {:?}", score);
// tuple
let tuple = (1, 2, 3, 4);
let (a, b, c, d) = tuple;
println!("a = {:?}", a);
println!("b = {:?}", b);
println!("c = {:?}", c);
println!("d = {:?}", d);
} | identifier_body |
|
2_primitives.rs | /*
array A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time constant size, N.
bool The boolean type.
char A character type.
f32 The 32-bit floating point type.
f64 The 64-bit floating point type.
i16 The 16-bit signed integer type.
i32 The 32-bit signed integer type.
i64 The 64-bit signed integer type.
i8 The 8-bit signed integer type.
isize The pointer-sized signed integer type.
pointer Raw, unsafe pointers, *const T, and *mut T.
slice A dynamically-sized view into a contiguous sequence, [T].
str String slices.
tuple A finite heterogeneous sequence, (T, U,..).
u16 The 16-bit unsigned integer type.
u32 The 32-bit unsigned integer type.
u64 The 64-bit unsigned integer type.
u8 The 8-bit unsigned integer type.
usize The pointer-sized unsigned integer type.
*/
fn | () {
let age: u32 = 30;
let score: f64 = std::f64::consts::PI;
{
let mut age_copy = age;
age_copy = 15;
println!("age_copy = {:?}\n", age_copy);
}
assert_eq!(30, age);
println!("age = {:?}", age);
println!("score = {:?}", score);
// tuple
let tuple = (1, 2, 3, 4);
let (a, b, c, d) = tuple;
println!("a = {:?}", a);
println!("b = {:?}", b);
println!("c = {:?}", c);
println!("d = {:?}", d);
}
| main | identifier_name |
2_primitives.rs | /*
array A fixed-size array, denoted [T; N], for the element type, T, and the non-negative compile-time constant size, N.
bool The boolean type.
char A character type.
f32 The 32-bit floating point type.
f64 The 64-bit floating point type.
i16 The 16-bit signed integer type.
i32 The 32-bit signed integer type.
i64 The 64-bit signed integer type.
i8 The 8-bit signed integer type.
isize The pointer-sized signed integer type.
pointer Raw, unsafe pointers, *const T, and *mut T.
slice A dynamically-sized view into a contiguous sequence, [T].
str String slices.
tuple A finite heterogeneous sequence, (T, U,..).
u16 The 16-bit unsigned integer type.
u32 The 32-bit unsigned integer type.
u64 The 64-bit unsigned integer type.
u8 The 8-bit unsigned integer type.
usize The pointer-sized unsigned integer type.
*/
fn main() {
let age: u32 = 30; | age_copy = 15;
println!("age_copy = {:?}\n", age_copy);
}
assert_eq!(30, age);
println!("age = {:?}", age);
println!("score = {:?}", score);
// tuple
let tuple = (1, 2, 3, 4);
let (a, b, c, d) = tuple;
println!("a = {:?}", a);
println!("b = {:?}", b);
println!("c = {:?}", c);
println!("d = {:?}", d);
} | let score: f64 = std::f64::consts::PI;
{
let mut age_copy = age; | random_line_split |
issue-14865.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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
enum X {
Foo(usize),
Bar(bool)
}
fn main() | {
let x = match X::Foo(42) {
X::Foo(..) => 1,
_ if true => 0,
X::Bar(..) => panic!("Oh dear")
};
assert_eq!(x, 1);
let x = match X::Foo(42) {
_ if true => 0,
X::Foo(..) => 1,
X::Bar(..) => panic!("Oh dear")
};
assert_eq!(x, 0);
} | identifier_body |
|
issue-14865.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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
enum | {
Foo(usize),
Bar(bool)
}
fn main() {
let x = match X::Foo(42) {
X::Foo(..) => 1,
_ if true => 0,
X::Bar(..) => panic!("Oh dear")
};
assert_eq!(x, 1);
let x = match X::Foo(42) {
_ if true => 0,
X::Foo(..) => 1,
X::Bar(..) => panic!("Oh dear")
};
assert_eq!(x, 0);
}
| X | identifier_name |
issue-14865.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-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
enum X {
Foo(usize),
Bar(bool)
}
fn main() {
let x = match X::Foo(42) {
X::Foo(..) => 1,
_ if true => 0,
X::Bar(..) => panic!("Oh dear")
};
assert_eq!(x, 1);
let x = match X::Foo(42) {
_ if true => 0,
X::Foo(..) => 1,
X::Bar(..) => panic!("Oh dear") | } | };
assert_eq!(x, 0); | random_line_split |
sweep.rs | use error::{CliError, Usage, UsageKind};
use super::Command;
use constant::MAIN_DIR;
use lib::fs::*;
use lib::setting::{Config, ConfigKey, Ignore, Storage};
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct Sweep {
option1: Option<String>,
option2: Option<String>,
}
impl Command for Sweep {
fn usage(&self) -> Usage {
return Usage::new(UsageKind::Sweep);
}
fn main(&self) -> Result<(), CliError> {
let indeed = [&self.option1, &self.option2]
.iter()
.any(|option| match option {
&&Some(ref o) => o == "indeed",
&&None => false,
});
let all = match &self.option1 {
&Some(ref o) => match o.as_ref() {
"all" => true,
"indeed" => false,
_ => return Err(From::from(self.usage())),
},
&None => false,
}; | let storage = Storage::new("sweep", indeed);
try!(storage.create_box());
let config = try!(Config::read());
let moratorium = try!(config.get(ConfigKey::SweepMoratorium));
let moratorium = Config::to_duration(moratorium);
let ignore = try!(Ignore::read());
let (ignored_dirs, ignored_files) = ignore.dirs_and_files();
let target_files = walk_dir(MAIN_DIR)
.difference(&ignored_files)
.filter(|f| if all { true } else {!is_recently_accessed(f, &moratorium) })
.filter(|f|!ignored_dirs.iter().any(|d| f.starts_with(d)))
.cloned()
.collect::<Vec<String>>();
try!(storage.squeeze_dusts(&target_files));
let phantom_files = if indeed {
Vec::new()
} else {
target_files
.iter()
.map(|f| Path::new(f).to_path_buf())
.collect::<Vec<PathBuf>>()
};
let potentially_empty_dirs = potentially_empty_dirs(MAIN_DIR, phantom_files);
storage.squeeze_empty_dirs(potentially_empty_dirs).map_err(|e| From::from(e))
}
}
impl Sweep {
pub fn new(option1: Option<String>, option2: Option<String>) -> Self {
Sweep { option1: option1, option2: option2 }
}
} | random_line_split |
|
sweep.rs | use error::{CliError, Usage, UsageKind};
use super::Command;
use constant::MAIN_DIR;
use lib::fs::*;
use lib::setting::{Config, ConfigKey, Ignore, Storage};
use std::path::{Path, PathBuf};
#[derive(Debug)]
pub struct | {
option1: Option<String>,
option2: Option<String>,
}
impl Command for Sweep {
fn usage(&self) -> Usage {
return Usage::new(UsageKind::Sweep);
}
fn main(&self) -> Result<(), CliError> {
let indeed = [&self.option1, &self.option2]
.iter()
.any(|option| match option {
&&Some(ref o) => o == "indeed",
&&None => false,
});
let all = match &self.option1 {
&Some(ref o) => match o.as_ref() {
"all" => true,
"indeed" => false,
_ => return Err(From::from(self.usage())),
},
&None => false,
};
let storage = Storage::new("sweep", indeed);
try!(storage.create_box());
let config = try!(Config::read());
let moratorium = try!(config.get(ConfigKey::SweepMoratorium));
let moratorium = Config::to_duration(moratorium);
let ignore = try!(Ignore::read());
let (ignored_dirs, ignored_files) = ignore.dirs_and_files();
let target_files = walk_dir(MAIN_DIR)
.difference(&ignored_files)
.filter(|f| if all { true } else {!is_recently_accessed(f, &moratorium) })
.filter(|f|!ignored_dirs.iter().any(|d| f.starts_with(d)))
.cloned()
.collect::<Vec<String>>();
try!(storage.squeeze_dusts(&target_files));
let phantom_files = if indeed {
Vec::new()
} else {
target_files
.iter()
.map(|f| Path::new(f).to_path_buf())
.collect::<Vec<PathBuf>>()
};
let potentially_empty_dirs = potentially_empty_dirs(MAIN_DIR, phantom_files);
storage.squeeze_empty_dirs(potentially_empty_dirs).map_err(|e| From::from(e))
}
}
impl Sweep {
pub fn new(option1: Option<String>, option2: Option<String>) -> Self {
Sweep { option1: option1, option2: option2 }
}
}
| Sweep | identifier_name |
crc64.rs | pub struct Crc64 {
table: [u64; 256],
value: u64,
count: u32,
}
fn table_maker(polynomial: u64) -> [u64; 256] {
let mut table: [u64; 256] = [0; 256];
for i in 0..256 {
let mut v = i as u64;
for _ in 0..8 {
v = if v & 1!= 0 {
polynomial ^ (v >> 1)
} else {
v >> 1
}
}
table[i] = v;
}
table
}
impl Crc64 {
pub fn new() -> Crc64 {
let polynomial = 0xC96C5795D7870F42;
let c64 = Crc64 {
table: table_maker(polynomial),
value: 0xffffffffffffffff,
count: 0,
};
c64
}
pub fn reset(&mut self) {
self.value = 0xffffffffffffffff;
self.count = 0;
}
pub fn update(&mut self, buf: &[u8]) {
for &i in buf {
self.value = self.table[((self.value as u8) ^ i) as usize] ^ (self.value >> 8);
self.count += 1; | self.value = self.value ^ 0xffffffffffffffffu64;
}
pub fn checksum(&mut self, buf: &[u8]) -> u64 {
self.reset();
self.update(buf);
self.finalize();
self.getsum()
}
pub fn getsum(&self) -> u64 {
self.value
}
pub fn bytecount(&self) -> u32 {
self.count
}
}
#[test]
fn crc32_test() {
let mut crc64 = Crc64::new();
crc64.checksum(b"0000");
assert_eq!(crc64.getsum(), 0x2B5C866A7CBEF446);
} | }
}
pub fn finalize(&mut self) { | random_line_split |
crc64.rs | pub struct Crc64 {
table: [u64; 256],
value: u64,
count: u32,
}
fn table_maker(polynomial: u64) -> [u64; 256] {
let mut table: [u64; 256] = [0; 256];
for i in 0..256 {
let mut v = i as u64;
for _ in 0..8 {
v = if v & 1!= 0 {
polynomial ^ (v >> 1)
} else {
v >> 1
}
}
table[i] = v;
}
table
}
impl Crc64 {
pub fn new() -> Crc64 {
let polynomial = 0xC96C5795D7870F42;
let c64 = Crc64 {
table: table_maker(polynomial),
value: 0xffffffffffffffff,
count: 0,
};
c64
}
pub fn reset(&mut self) {
self.value = 0xffffffffffffffff;
self.count = 0;
}
pub fn update(&mut self, buf: &[u8]) {
for &i in buf {
self.value = self.table[((self.value as u8) ^ i) as usize] ^ (self.value >> 8);
self.count += 1;
}
}
pub fn finalize(&mut self) {
self.value = self.value ^ 0xffffffffffffffffu64;
}
pub fn checksum(&mut self, buf: &[u8]) -> u64 |
pub fn getsum(&self) -> u64 {
self.value
}
pub fn bytecount(&self) -> u32 {
self.count
}
}
#[test]
fn crc32_test() {
let mut crc64 = Crc64::new();
crc64.checksum(b"0000");
assert_eq!(crc64.getsum(), 0x2B5C866A7CBEF446);
}
| {
self.reset();
self.update(buf);
self.finalize();
self.getsum()
} | identifier_body |
crc64.rs | pub struct Crc64 {
table: [u64; 256],
value: u64,
count: u32,
}
fn table_maker(polynomial: u64) -> [u64; 256] {
let mut table: [u64; 256] = [0; 256];
for i in 0..256 {
let mut v = i as u64;
for _ in 0..8 {
v = if v & 1!= 0 {
polynomial ^ (v >> 1)
} else |
}
table[i] = v;
}
table
}
impl Crc64 {
pub fn new() -> Crc64 {
let polynomial = 0xC96C5795D7870F42;
let c64 = Crc64 {
table: table_maker(polynomial),
value: 0xffffffffffffffff,
count: 0,
};
c64
}
pub fn reset(&mut self) {
self.value = 0xffffffffffffffff;
self.count = 0;
}
pub fn update(&mut self, buf: &[u8]) {
for &i in buf {
self.value = self.table[((self.value as u8) ^ i) as usize] ^ (self.value >> 8);
self.count += 1;
}
}
pub fn finalize(&mut self) {
self.value = self.value ^ 0xffffffffffffffffu64;
}
pub fn checksum(&mut self, buf: &[u8]) -> u64 {
self.reset();
self.update(buf);
self.finalize();
self.getsum()
}
pub fn getsum(&self) -> u64 {
self.value
}
pub fn bytecount(&self) -> u32 {
self.count
}
}
#[test]
fn crc32_test() {
let mut crc64 = Crc64::new();
crc64.checksum(b"0000");
assert_eq!(crc64.getsum(), 0x2B5C866A7CBEF446);
}
| {
v >> 1
} | conditional_block |
crc64.rs | pub struct | {
table: [u64; 256],
value: u64,
count: u32,
}
fn table_maker(polynomial: u64) -> [u64; 256] {
let mut table: [u64; 256] = [0; 256];
for i in 0..256 {
let mut v = i as u64;
for _ in 0..8 {
v = if v & 1!= 0 {
polynomial ^ (v >> 1)
} else {
v >> 1
}
}
table[i] = v;
}
table
}
impl Crc64 {
pub fn new() -> Crc64 {
let polynomial = 0xC96C5795D7870F42;
let c64 = Crc64 {
table: table_maker(polynomial),
value: 0xffffffffffffffff,
count: 0,
};
c64
}
pub fn reset(&mut self) {
self.value = 0xffffffffffffffff;
self.count = 0;
}
pub fn update(&mut self, buf: &[u8]) {
for &i in buf {
self.value = self.table[((self.value as u8) ^ i) as usize] ^ (self.value >> 8);
self.count += 1;
}
}
pub fn finalize(&mut self) {
self.value = self.value ^ 0xffffffffffffffffu64;
}
pub fn checksum(&mut self, buf: &[u8]) -> u64 {
self.reset();
self.update(buf);
self.finalize();
self.getsum()
}
pub fn getsum(&self) -> u64 {
self.value
}
pub fn bytecount(&self) -> u32 {
self.count
}
}
#[test]
fn crc32_test() {
let mut crc64 = Crc64::new();
crc64.checksum(b"0000");
assert_eq!(crc64.getsum(), 0x2B5C866A7CBEF446);
}
| Crc64 | identifier_name |
trim_pass.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Pulls a brief description out of a long description.
If the first paragraph of a long description is short enough then it
is interpreted as the brief description.
*/
use pass::Pass;
use text_pass;
pub fn | () -> Pass {
text_pass::mk_pass(~"trim", |s| s.trim().to_owned() )
}
#[cfg(test)]
mod test {
use astsrv;
use attr_pass;
use doc;
use extract;
use prune_hidden_pass;
use trim_pass::mk_pass;
fn mk_doc(source: ~str) -> doc::Doc {
do astsrv::from_str(copy source) |srv| {
let doc = extract::from_srv(srv.clone(), ~"");
let doc = (attr_pass::mk_pass().f)(srv.clone(), doc);
let doc = (prune_hidden_pass::mk_pass().f)(srv.clone(), doc);
(mk_pass().f)(srv.clone(), doc)
}
}
#[test]
fn should_trim_text() {
use std::option::Some;
let doc = mk_doc(~"#[doc = \" desc \"] \
mod m {
}");
assert_eq!(doc.cratemod().mods()[0].desc(), Some(~"desc"));
}
}
| mk_pass | identifier_name |
trim_pass.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Pulls a brief description out of a long description.
If the first paragraph of a long description is short enough then it
is interpreted as the brief description.
*/
use pass::Pass;
use text_pass;
pub fn mk_pass() -> Pass {
text_pass::mk_pass(~"trim", |s| s.trim().to_owned() )
}
#[cfg(test)]
mod test {
use astsrv;
use attr_pass;
use doc;
use extract;
use prune_hidden_pass;
use trim_pass::mk_pass;
fn mk_doc(source: ~str) -> doc::Doc {
do astsrv::from_str(copy source) |srv| {
let doc = extract::from_srv(srv.clone(), ~"");
let doc = (attr_pass::mk_pass().f)(srv.clone(), doc);
let doc = (prune_hidden_pass::mk_pass().f)(srv.clone(), doc);
(mk_pass().f)(srv.clone(), doc)
}
}
#[test]
fn should_trim_text() |
}
| {
use std::option::Some;
let doc = mk_doc(~"#[doc = \" desc \"] \
mod m {
}");
assert_eq!(doc.cratemod().mods()[0].desc(), Some(~"desc"));
} | identifier_body |
trim_pass.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Pulls a brief description out of a long description.
If the first paragraph of a long description is short enough then it
is interpreted as the brief description.
*/
use pass::Pass;
use text_pass;
pub fn mk_pass() -> Pass {
text_pass::mk_pass(~"trim", |s| s.trim().to_owned() )
}
#[cfg(test)]
mod test {
use astsrv;
use attr_pass;
use doc;
use extract;
use prune_hidden_pass;
use trim_pass::mk_pass; | do astsrv::from_str(copy source) |srv| {
let doc = extract::from_srv(srv.clone(), ~"");
let doc = (attr_pass::mk_pass().f)(srv.clone(), doc);
let doc = (prune_hidden_pass::mk_pass().f)(srv.clone(), doc);
(mk_pass().f)(srv.clone(), doc)
}
}
#[test]
fn should_trim_text() {
use std::option::Some;
let doc = mk_doc(~"#[doc = \" desc \"] \
mod m {
}");
assert_eq!(doc.cratemod().mods()[0].desc(), Some(~"desc"));
}
} |
fn mk_doc(source: ~str) -> doc::Doc { | random_line_split |
htmlulistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLUListElementBinding;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLUListElement {
htmlelement: HTMLElement
}
impl HTMLUListElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUListElement {
HTMLUListElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLUListElement> |
}
| {
let element = HTMLUListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLUListElementBinding::Wrap)
} | identifier_body |
htmlulistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLUListElementBinding;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLUListElement {
htmlelement: HTMLElement
} | impl HTMLUListElement {
fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUListElement {
HTMLUListElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLUListElement> {
let element = HTMLUListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLUListElementBinding::Wrap)
}
} | random_line_split |
|
htmlulistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLUListElementBinding;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLUListElement {
htmlelement: HTMLElement
}
impl HTMLUListElement {
fn | (localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLUListElement {
HTMLUListElement {
htmlelement: HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLUListElement> {
let element = HTMLUListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLUListElementBinding::Wrap)
}
}
| new_inherited | identifier_name |
evolve.rs | extern crate rand;
extern crate nadezhda;
|
use nadezhda::grammar::Program;
use nadezhda::environment::Environment;
use nadezhda::population::Population;
use nadezhda::evaluate::Evaluator;
use nadezhda::darwin::evolve::succesion;
fn survivors(population: Population, environment: Environment) -> Vec<Program> {
let Population(generation) = population;
let survivors: Vec<Program> = generation
.iter()
.map(|program| (program.clone(), program.evaluate_on(environment.clone())))
.filter(|&(_, ref env)| env.cockroach_location - env.food_location == 0)
.map(|(program, _)| program)
.collect();
survivors
}
fn main() {
if env::args().len() < 3 {
println!("Usage: evolve FOOD POPULATION");
process::exit(1);
}
let food_string: String = env::args().nth(1).unwrap();
let food: i32 = match i32::from_str_radix(&food_string, 10) {
Ok(value) => value,
Err(_) => {
println!("FOOD argument is not an integer");
process::exit(2);
}
};
let population_count_string: String = env::args().nth(2).unwrap();
let population_count: i32 = match i32::from_str_radix(&population_count_string, 10) {
Ok(value) => value,
Err(_) => {
println!("POPULATION argument is not an integer");
process::exit(3);
}
};
let mut rng = rand::thread_rng();
let environment: Environment = Environment::new(food);
let mut last_population: Population = Population::new(population_count);
let mut generation_count = 0;
while generation_count < 100 {
let next_population = succesion(&mut rng, environment.clone(), last_population.clone());
let survivors: Vec<Program> = survivors(next_population.clone(), environment.clone());
last_population = next_population;
if survivors.len() > 0 { break; }
generation_count += 1;
}
let survivors: Vec<Program> = survivors(last_population.clone(), environment.clone());
if survivors.len() > 0 {
println!("{} {} {:?}", generation_count, survivors.len(), survivors[0]);
} else {
println!("{} {:?}", generation_count, last_population);
}
} | use std::env;
use std::process; | random_line_split |
evolve.rs | extern crate rand;
extern crate nadezhda;
use std::env;
use std::process;
use nadezhda::grammar::Program;
use nadezhda::environment::Environment;
use nadezhda::population::Population;
use nadezhda::evaluate::Evaluator;
use nadezhda::darwin::evolve::succesion;
fn survivors(population: Population, environment: Environment) -> Vec<Program> |
fn main() {
if env::args().len() < 3 {
println!("Usage: evolve FOOD POPULATION");
process::exit(1);
}
let food_string: String = env::args().nth(1).unwrap();
let food: i32 = match i32::from_str_radix(&food_string, 10) {
Ok(value) => value,
Err(_) => {
println!("FOOD argument is not an integer");
process::exit(2);
}
};
let population_count_string: String = env::args().nth(2).unwrap();
let population_count: i32 = match i32::from_str_radix(&population_count_string, 10) {
Ok(value) => value,
Err(_) => {
println!("POPULATION argument is not an integer");
process::exit(3);
}
};
let mut rng = rand::thread_rng();
let environment: Environment = Environment::new(food);
let mut last_population: Population = Population::new(population_count);
let mut generation_count = 0;
while generation_count < 100 {
let next_population = succesion(&mut rng, environment.clone(), last_population.clone());
let survivors: Vec<Program> = survivors(next_population.clone(), environment.clone());
last_population = next_population;
if survivors.len() > 0 { break; }
generation_count += 1;
}
let survivors: Vec<Program> = survivors(last_population.clone(), environment.clone());
if survivors.len() > 0 {
println!("{} {} {:?}", generation_count, survivors.len(), survivors[0]);
} else {
println!("{} {:?}", generation_count, last_population);
}
}
| {
let Population(generation) = population;
let survivors: Vec<Program> = generation
.iter()
.map(|program| (program.clone(), program.evaluate_on(environment.clone())))
.filter(|&(_, ref env)| env.cockroach_location - env.food_location == 0)
.map(|(program, _)| program)
.collect();
survivors
} | identifier_body |
evolve.rs | extern crate rand;
extern crate nadezhda;
use std::env;
use std::process;
use nadezhda::grammar::Program;
use nadezhda::environment::Environment;
use nadezhda::population::Population;
use nadezhda::evaluate::Evaluator;
use nadezhda::darwin::evolve::succesion;
fn survivors(population: Population, environment: Environment) -> Vec<Program> {
let Population(generation) = population;
let survivors: Vec<Program> = generation
.iter()
.map(|program| (program.clone(), program.evaluate_on(environment.clone())))
.filter(|&(_, ref env)| env.cockroach_location - env.food_location == 0)
.map(|(program, _)| program)
.collect();
survivors
}
fn main() {
if env::args().len() < 3 {
println!("Usage: evolve FOOD POPULATION");
process::exit(1);
}
let food_string: String = env::args().nth(1).unwrap();
let food: i32 = match i32::from_str_radix(&food_string, 10) {
Ok(value) => value,
Err(_) => |
};
let population_count_string: String = env::args().nth(2).unwrap();
let population_count: i32 = match i32::from_str_radix(&population_count_string, 10) {
Ok(value) => value,
Err(_) => {
println!("POPULATION argument is not an integer");
process::exit(3);
}
};
let mut rng = rand::thread_rng();
let environment: Environment = Environment::new(food);
let mut last_population: Population = Population::new(population_count);
let mut generation_count = 0;
while generation_count < 100 {
let next_population = succesion(&mut rng, environment.clone(), last_population.clone());
let survivors: Vec<Program> = survivors(next_population.clone(), environment.clone());
last_population = next_population;
if survivors.len() > 0 { break; }
generation_count += 1;
}
let survivors: Vec<Program> = survivors(last_population.clone(), environment.clone());
if survivors.len() > 0 {
println!("{} {} {:?}", generation_count, survivors.len(), survivors[0]);
} else {
println!("{} {:?}", generation_count, last_population);
}
}
| {
println!("FOOD argument is not an integer");
process::exit(2);
} | conditional_block |
evolve.rs | extern crate rand;
extern crate nadezhda;
use std::env;
use std::process;
use nadezhda::grammar::Program;
use nadezhda::environment::Environment;
use nadezhda::population::Population;
use nadezhda::evaluate::Evaluator;
use nadezhda::darwin::evolve::succesion;
fn survivors(population: Population, environment: Environment) -> Vec<Program> {
let Population(generation) = population;
let survivors: Vec<Program> = generation
.iter()
.map(|program| (program.clone(), program.evaluate_on(environment.clone())))
.filter(|&(_, ref env)| env.cockroach_location - env.food_location == 0)
.map(|(program, _)| program)
.collect();
survivors
}
fn | () {
if env::args().len() < 3 {
println!("Usage: evolve FOOD POPULATION");
process::exit(1);
}
let food_string: String = env::args().nth(1).unwrap();
let food: i32 = match i32::from_str_radix(&food_string, 10) {
Ok(value) => value,
Err(_) => {
println!("FOOD argument is not an integer");
process::exit(2);
}
};
let population_count_string: String = env::args().nth(2).unwrap();
let population_count: i32 = match i32::from_str_radix(&population_count_string, 10) {
Ok(value) => value,
Err(_) => {
println!("POPULATION argument is not an integer");
process::exit(3);
}
};
let mut rng = rand::thread_rng();
let environment: Environment = Environment::new(food);
let mut last_population: Population = Population::new(population_count);
let mut generation_count = 0;
while generation_count < 100 {
let next_population = succesion(&mut rng, environment.clone(), last_population.clone());
let survivors: Vec<Program> = survivors(next_population.clone(), environment.clone());
last_population = next_population;
if survivors.len() > 0 { break; }
generation_count += 1;
}
let survivors: Vec<Program> = survivors(last_population.clone(), environment.clone());
if survivors.len() > 0 {
println!("{} {} {:?}", generation_count, survivors.len(), survivors[0]);
} else {
println!("{} {:?}", generation_count, last_population);
}
}
| main | identifier_name |
test.rs | //!
//! test.rs.rs
//!
//! Created by Mitchell Nordine at 05:57PM on December 19, 2014.
//!
//! Always remember to run high performance Rust code with the --release flag. `Synth`
//!
extern crate pitch_calc as pitch;
extern crate portaudio;
extern crate sample;
extern crate synth;
use portaudio as pa;
use pitch::{Letter, LetterOctave};
use synth::Synth;
// Currently supports i8, i32, f32.
pub type AudioSample = f32;
pub type Input = AudioSample;
pub type Output = AudioSample;
const CHANNELS: i32 = 2;
const FRAMES: u32 = 64;
const SAMPLE_HZ: f64 = 44_100.0;
fn main() {
run().unwrap()
}
fn run() -> Result<(), pa::Error> {
// Construct our fancy Synth!
let mut synth = {
use synth::{Point, Oscillator, oscillator, Envelope};
// The following envelopes should create a downward pitching sine wave that gradually quietens.
// Try messing around with the points and adding some of your own!
let amp_env = Envelope::from(vec!(
// Time, Amp, Curve
Point::new(0.0 , 0.0, 0.0),
Point::new(0.01, 1.0, 0.0),
Point::new(0.45, 1.0, 0.0),
Point::new(0.81, 0.8, 0.0),
Point::new(1.0 , 0.0, 0.0),
));
let freq_env = Envelope::from(vec!(
// Time , Freq , Curve
Point::new(0.0 , 0.0 , 0.0),
Point::new(0.00136, 1.0 , 0.0),
Point::new(0.015 , 0.02 , 0.0),
Point::new(0.045 , 0.005 , 0.0),
Point::new(0.1 , 0.0022, 0.0),
Point::new(0.35 , 0.0011, 0.0),
Point::new(1.0 , 0.0 , 0.0),
));
// Now we can create our oscillator from our envelopes.
// There are also Sine, Noise, NoiseWalk, SawExp and Square waveforms.
let oscillator = Oscillator::new(oscillator::waveform::Square, amp_env, freq_env, ());
// Here we construct our Synth from our oscillator.
Synth::retrigger(())
.oscillator(oscillator) // Add as many different oscillators as desired.
.duration(6000.0) // Milliseconds.
.base_pitch(LetterOctave(Letter::C, 1).hz()) // Hz.
.loop_points(0.49, 0.51) // Loop start and end points.
.fade(500.0, 500.0) // Attack and Release in milliseconds.
.num_voices(16) // By default Synth is monophonic but this gives it `n` voice polyphony.
.volume(0.2)
.detune(0.5)
.spread(1.0)
// Other methods include:
//.loop_start(0.0)
//.loop_end(1.0)
//.attack(ms)
//.release(ms)
//.note_freq_generator(nfg)
//.oscillators([oscA, oscB, oscC])
//.volume(1.0)
};
// Construct a note for the synth to perform. Have a play around with the pitch and duration! | let note = LetterOctave(Letter::C, 1);
let note_velocity = 1.0;
synth.note_on(note, note_velocity);
// We'll call this to release the note after 4 seconds.
let note_duration = 4.0;
let mut is_note_off = false;
// We'll use this to keep track of time and break from the loop after 6 seconds.
let mut timer: f64 = 0.0;
// This will be used to determine the delta time between calls to the callback.
let mut prev_time = None;
// The callback we'll use to pass to the Stream.
let callback = move |pa::OutputStreamCallbackArgs { buffer, time,.. }| {
let buffer: &mut [[f32; CHANNELS as usize]] = sample::slice::to_frame_slice_mut(buffer).unwrap();
sample::slice::equilibrium(buffer);
synth.fill_slice(buffer, SAMPLE_HZ as f64);
if timer < 6.0 {
let last_time = prev_time.unwrap_or(time.current);
let dt = time.current - last_time;
timer += dt;
prev_time = Some(time.current);
// Once the timer exceeds our note duration, send the note_off.
if timer > note_duration {
if!is_note_off {
synth.note_off(note);
is_note_off = true;
}
}
pa::Continue
} else {
pa::Complete
}
};
// Construct PortAudio and the stream.
let pa = try!(pa::PortAudio::new());
let settings = try!(pa.default_output_stream_settings::<f32>(CHANNELS, SAMPLE_HZ, FRAMES));
let mut stream = try!(pa.open_non_blocking_stream(settings, callback));
try!(stream.start());
// Loop while the stream is active.
while let Ok(true) = stream.is_active() {
std::thread::sleep(std::time::Duration::from_millis(16));
}
Ok(())
} | random_line_split |
|
test.rs | //!
//! test.rs.rs
//!
//! Created by Mitchell Nordine at 05:57PM on December 19, 2014.
//!
//! Always remember to run high performance Rust code with the --release flag. `Synth`
//!
extern crate pitch_calc as pitch;
extern crate portaudio;
extern crate sample;
extern crate synth;
use portaudio as pa;
use pitch::{Letter, LetterOctave};
use synth::Synth;
// Currently supports i8, i32, f32.
pub type AudioSample = f32;
pub type Input = AudioSample;
pub type Output = AudioSample;
const CHANNELS: i32 = 2;
const FRAMES: u32 = 64;
const SAMPLE_HZ: f64 = 44_100.0;
fn | () {
run().unwrap()
}
fn run() -> Result<(), pa::Error> {
// Construct our fancy Synth!
let mut synth = {
use synth::{Point, Oscillator, oscillator, Envelope};
// The following envelopes should create a downward pitching sine wave that gradually quietens.
// Try messing around with the points and adding some of your own!
let amp_env = Envelope::from(vec!(
// Time, Amp, Curve
Point::new(0.0 , 0.0, 0.0),
Point::new(0.01, 1.0, 0.0),
Point::new(0.45, 1.0, 0.0),
Point::new(0.81, 0.8, 0.0),
Point::new(1.0 , 0.0, 0.0),
));
let freq_env = Envelope::from(vec!(
// Time , Freq , Curve
Point::new(0.0 , 0.0 , 0.0),
Point::new(0.00136, 1.0 , 0.0),
Point::new(0.015 , 0.02 , 0.0),
Point::new(0.045 , 0.005 , 0.0),
Point::new(0.1 , 0.0022, 0.0),
Point::new(0.35 , 0.0011, 0.0),
Point::new(1.0 , 0.0 , 0.0),
));
// Now we can create our oscillator from our envelopes.
// There are also Sine, Noise, NoiseWalk, SawExp and Square waveforms.
let oscillator = Oscillator::new(oscillator::waveform::Square, amp_env, freq_env, ());
// Here we construct our Synth from our oscillator.
Synth::retrigger(())
.oscillator(oscillator) // Add as many different oscillators as desired.
.duration(6000.0) // Milliseconds.
.base_pitch(LetterOctave(Letter::C, 1).hz()) // Hz.
.loop_points(0.49, 0.51) // Loop start and end points.
.fade(500.0, 500.0) // Attack and Release in milliseconds.
.num_voices(16) // By default Synth is monophonic but this gives it `n` voice polyphony.
.volume(0.2)
.detune(0.5)
.spread(1.0)
// Other methods include:
//.loop_start(0.0)
//.loop_end(1.0)
//.attack(ms)
//.release(ms)
//.note_freq_generator(nfg)
//.oscillators([oscA, oscB, oscC])
//.volume(1.0)
};
// Construct a note for the synth to perform. Have a play around with the pitch and duration!
let note = LetterOctave(Letter::C, 1);
let note_velocity = 1.0;
synth.note_on(note, note_velocity);
// We'll call this to release the note after 4 seconds.
let note_duration = 4.0;
let mut is_note_off = false;
// We'll use this to keep track of time and break from the loop after 6 seconds.
let mut timer: f64 = 0.0;
// This will be used to determine the delta time between calls to the callback.
let mut prev_time = None;
// The callback we'll use to pass to the Stream.
let callback = move |pa::OutputStreamCallbackArgs { buffer, time,.. }| {
let buffer: &mut [[f32; CHANNELS as usize]] = sample::slice::to_frame_slice_mut(buffer).unwrap();
sample::slice::equilibrium(buffer);
synth.fill_slice(buffer, SAMPLE_HZ as f64);
if timer < 6.0 {
let last_time = prev_time.unwrap_or(time.current);
let dt = time.current - last_time;
timer += dt;
prev_time = Some(time.current);
// Once the timer exceeds our note duration, send the note_off.
if timer > note_duration {
if!is_note_off {
synth.note_off(note);
is_note_off = true;
}
}
pa::Continue
} else {
pa::Complete
}
};
// Construct PortAudio and the stream.
let pa = try!(pa::PortAudio::new());
let settings = try!(pa.default_output_stream_settings::<f32>(CHANNELS, SAMPLE_HZ, FRAMES));
let mut stream = try!(pa.open_non_blocking_stream(settings, callback));
try!(stream.start());
// Loop while the stream is active.
while let Ok(true) = stream.is_active() {
std::thread::sleep(std::time::Duration::from_millis(16));
}
Ok(())
}
| main | identifier_name |
test.rs | //!
//! test.rs.rs
//!
//! Created by Mitchell Nordine at 05:57PM on December 19, 2014.
//!
//! Always remember to run high performance Rust code with the --release flag. `Synth`
//!
extern crate pitch_calc as pitch;
extern crate portaudio;
extern crate sample;
extern crate synth;
use portaudio as pa;
use pitch::{Letter, LetterOctave};
use synth::Synth;
// Currently supports i8, i32, f32.
pub type AudioSample = f32;
pub type Input = AudioSample;
pub type Output = AudioSample;
const CHANNELS: i32 = 2;
const FRAMES: u32 = 64;
const SAMPLE_HZ: f64 = 44_100.0;
fn main() |
fn run() -> Result<(), pa::Error> {
// Construct our fancy Synth!
let mut synth = {
use synth::{Point, Oscillator, oscillator, Envelope};
// The following envelopes should create a downward pitching sine wave that gradually quietens.
// Try messing around with the points and adding some of your own!
let amp_env = Envelope::from(vec!(
// Time, Amp, Curve
Point::new(0.0 , 0.0, 0.0),
Point::new(0.01, 1.0, 0.0),
Point::new(0.45, 1.0, 0.0),
Point::new(0.81, 0.8, 0.0),
Point::new(1.0 , 0.0, 0.0),
));
let freq_env = Envelope::from(vec!(
// Time , Freq , Curve
Point::new(0.0 , 0.0 , 0.0),
Point::new(0.00136, 1.0 , 0.0),
Point::new(0.015 , 0.02 , 0.0),
Point::new(0.045 , 0.005 , 0.0),
Point::new(0.1 , 0.0022, 0.0),
Point::new(0.35 , 0.0011, 0.0),
Point::new(1.0 , 0.0 , 0.0),
));
// Now we can create our oscillator from our envelopes.
// There are also Sine, Noise, NoiseWalk, SawExp and Square waveforms.
let oscillator = Oscillator::new(oscillator::waveform::Square, amp_env, freq_env, ());
// Here we construct our Synth from our oscillator.
Synth::retrigger(())
.oscillator(oscillator) // Add as many different oscillators as desired.
.duration(6000.0) // Milliseconds.
.base_pitch(LetterOctave(Letter::C, 1).hz()) // Hz.
.loop_points(0.49, 0.51) // Loop start and end points.
.fade(500.0, 500.0) // Attack and Release in milliseconds.
.num_voices(16) // By default Synth is monophonic but this gives it `n` voice polyphony.
.volume(0.2)
.detune(0.5)
.spread(1.0)
// Other methods include:
//.loop_start(0.0)
//.loop_end(1.0)
//.attack(ms)
//.release(ms)
//.note_freq_generator(nfg)
//.oscillators([oscA, oscB, oscC])
//.volume(1.0)
};
// Construct a note for the synth to perform. Have a play around with the pitch and duration!
let note = LetterOctave(Letter::C, 1);
let note_velocity = 1.0;
synth.note_on(note, note_velocity);
// We'll call this to release the note after 4 seconds.
let note_duration = 4.0;
let mut is_note_off = false;
// We'll use this to keep track of time and break from the loop after 6 seconds.
let mut timer: f64 = 0.0;
// This will be used to determine the delta time between calls to the callback.
let mut prev_time = None;
// The callback we'll use to pass to the Stream.
let callback = move |pa::OutputStreamCallbackArgs { buffer, time,.. }| {
let buffer: &mut [[f32; CHANNELS as usize]] = sample::slice::to_frame_slice_mut(buffer).unwrap();
sample::slice::equilibrium(buffer);
synth.fill_slice(buffer, SAMPLE_HZ as f64);
if timer < 6.0 {
let last_time = prev_time.unwrap_or(time.current);
let dt = time.current - last_time;
timer += dt;
prev_time = Some(time.current);
// Once the timer exceeds our note duration, send the note_off.
if timer > note_duration {
if!is_note_off {
synth.note_off(note);
is_note_off = true;
}
}
pa::Continue
} else {
pa::Complete
}
};
// Construct PortAudio and the stream.
let pa = try!(pa::PortAudio::new());
let settings = try!(pa.default_output_stream_settings::<f32>(CHANNELS, SAMPLE_HZ, FRAMES));
let mut stream = try!(pa.open_non_blocking_stream(settings, callback));
try!(stream.start());
// Loop while the stream is active.
while let Ok(true) = stream.is_active() {
std::thread::sleep(std::time::Duration::from_millis(16));
}
Ok(())
}
| {
run().unwrap()
} | identifier_body |
test.rs | //!
//! test.rs.rs
//!
//! Created by Mitchell Nordine at 05:57PM on December 19, 2014.
//!
//! Always remember to run high performance Rust code with the --release flag. `Synth`
//!
extern crate pitch_calc as pitch;
extern crate portaudio;
extern crate sample;
extern crate synth;
use portaudio as pa;
use pitch::{Letter, LetterOctave};
use synth::Synth;
// Currently supports i8, i32, f32.
pub type AudioSample = f32;
pub type Input = AudioSample;
pub type Output = AudioSample;
const CHANNELS: i32 = 2;
const FRAMES: u32 = 64;
const SAMPLE_HZ: f64 = 44_100.0;
fn main() {
run().unwrap()
}
fn run() -> Result<(), pa::Error> {
// Construct our fancy Synth!
let mut synth = {
use synth::{Point, Oscillator, oscillator, Envelope};
// The following envelopes should create a downward pitching sine wave that gradually quietens.
// Try messing around with the points and adding some of your own!
let amp_env = Envelope::from(vec!(
// Time, Amp, Curve
Point::new(0.0 , 0.0, 0.0),
Point::new(0.01, 1.0, 0.0),
Point::new(0.45, 1.0, 0.0),
Point::new(0.81, 0.8, 0.0),
Point::new(1.0 , 0.0, 0.0),
));
let freq_env = Envelope::from(vec!(
// Time , Freq , Curve
Point::new(0.0 , 0.0 , 0.0),
Point::new(0.00136, 1.0 , 0.0),
Point::new(0.015 , 0.02 , 0.0),
Point::new(0.045 , 0.005 , 0.0),
Point::new(0.1 , 0.0022, 0.0),
Point::new(0.35 , 0.0011, 0.0),
Point::new(1.0 , 0.0 , 0.0),
));
// Now we can create our oscillator from our envelopes.
// There are also Sine, Noise, NoiseWalk, SawExp and Square waveforms.
let oscillator = Oscillator::new(oscillator::waveform::Square, amp_env, freq_env, ());
// Here we construct our Synth from our oscillator.
Synth::retrigger(())
.oscillator(oscillator) // Add as many different oscillators as desired.
.duration(6000.0) // Milliseconds.
.base_pitch(LetterOctave(Letter::C, 1).hz()) // Hz.
.loop_points(0.49, 0.51) // Loop start and end points.
.fade(500.0, 500.0) // Attack and Release in milliseconds.
.num_voices(16) // By default Synth is monophonic but this gives it `n` voice polyphony.
.volume(0.2)
.detune(0.5)
.spread(1.0)
// Other methods include:
//.loop_start(0.0)
//.loop_end(1.0)
//.attack(ms)
//.release(ms)
//.note_freq_generator(nfg)
//.oscillators([oscA, oscB, oscC])
//.volume(1.0)
};
// Construct a note for the synth to perform. Have a play around with the pitch and duration!
let note = LetterOctave(Letter::C, 1);
let note_velocity = 1.0;
synth.note_on(note, note_velocity);
// We'll call this to release the note after 4 seconds.
let note_duration = 4.0;
let mut is_note_off = false;
// We'll use this to keep track of time and break from the loop after 6 seconds.
let mut timer: f64 = 0.0;
// This will be used to determine the delta time between calls to the callback.
let mut prev_time = None;
// The callback we'll use to pass to the Stream.
let callback = move |pa::OutputStreamCallbackArgs { buffer, time,.. }| {
let buffer: &mut [[f32; CHANNELS as usize]] = sample::slice::to_frame_slice_mut(buffer).unwrap();
sample::slice::equilibrium(buffer);
synth.fill_slice(buffer, SAMPLE_HZ as f64);
if timer < 6.0 {
let last_time = prev_time.unwrap_or(time.current);
let dt = time.current - last_time;
timer += dt;
prev_time = Some(time.current);
// Once the timer exceeds our note duration, send the note_off.
if timer > note_duration |
pa::Continue
} else {
pa::Complete
}
};
// Construct PortAudio and the stream.
let pa = try!(pa::PortAudio::new());
let settings = try!(pa.default_output_stream_settings::<f32>(CHANNELS, SAMPLE_HZ, FRAMES));
let mut stream = try!(pa.open_non_blocking_stream(settings, callback));
try!(stream.start());
// Loop while the stream is active.
while let Ok(true) = stream.is_active() {
std::thread::sleep(std::time::Duration::from_millis(16));
}
Ok(())
}
| {
if !is_note_off {
synth.note_off(note);
is_note_off = true;
}
} | conditional_block |
types.rs | //! Representation of an email address
use std::{
convert::{TryFrom, TryInto},
error::Error,
ffi::OsStr,
fmt::{Display, Formatter, Result as FmtResult},
net::IpAddr,
str::FromStr,
};
use idna::domain_to_ascii;
use once_cell::sync::Lazy;
use regex::Regex;
/// Represents an email address with a user and a domain name.
///
/// This type contains email in canonical form ([email protected]_).
///
/// **NOTE**: Enable feature "serde" to be able serialize/deserialize it using [serde](https://serde.rs/).
///
/// # Examples
///
/// You can create an `Address` from a user and a domain:
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.user(), "user");
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
///
/// You can also create an `Address` from a string literal by parsing it:
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = "[email protected]".parse::<Address>()?;
/// assert_eq!(address.user(), "user");
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Address {
/// Complete address
serialized: String,
/// Index into `serialized` before the '@'
at_start: usize,
}
// Regex from the specs
// https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
// It will mark esoteric email addresses like quoted string as invalid
static USER_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+\z").unwrap());
static DOMAIN_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r"(?i)^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$",
)
.unwrap()
});
// literal form, ipv4 or ipv6 address (SMTP 4.1.3)
static LITERAL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\[([A-f0-9:\.]+)\]\z").unwrap());
impl Address {
/// Creates a new email address from a user and domain.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// let expected = "[email protected]".parse::<Address>()?;
/// assert_eq!(expected, address);
/// # Ok(())
/// # }
/// ```
pub fn new<U: AsRef<str>, D: AsRef<str>>(user: U, domain: D) -> Result<Self, AddressError> {
(user, domain).try_into()
}
/// Gets the user portion of the `Address`.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.user(), "user");
/// # Ok(())
/// # }
/// ```
pub fn | (&self) -> &str {
&self.serialized[..self.at_start]
}
/// Gets the domain portion of the `Address`.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
pub fn domain(&self) -> &str {
&self.serialized[self.at_start + 1..]
}
pub(super) fn check_user(user: &str) -> Result<(), AddressError> {
if USER_RE.is_match(user) {
Ok(())
} else {
Err(AddressError::InvalidUser)
}
}
pub(super) fn check_domain(domain: &str) -> Result<(), AddressError> {
Address::check_domain_ascii(domain).or_else(|_| {
domain_to_ascii(domain)
.map_err(|_| AddressError::InvalidDomain)
.and_then(|domain| Address::check_domain_ascii(&domain))
})
}
fn check_domain_ascii(domain: &str) -> Result<(), AddressError> {
if DOMAIN_RE.is_match(domain) {
return Ok(());
}
if let Some(caps) = LITERAL_RE.captures(domain) {
if let Some(cap) = caps.get(1) {
if cap.as_str().parse::<IpAddr>().is_ok() {
return Ok(());
}
}
}
Err(AddressError::InvalidDomain)
}
#[cfg(feature = "smtp-transport")]
/// Check if the address contains non-ascii chars
pub(super) fn is_ascii(&self) -> bool {
self.serialized.is_ascii()
}
}
impl Display for Address {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str(&self.serialized)
}
}
impl FromStr for Address {
type Err = AddressError;
fn from_str(val: &str) -> Result<Self, AddressError> {
let at_start = check_address(val)?;
Ok(Address {
serialized: val.into(),
at_start,
})
}
}
impl<U, D> TryFrom<(U, D)> for Address
where
U: AsRef<str>,
D: AsRef<str>,
{
type Error = AddressError;
fn try_from((user, domain): (U, D)) -> Result<Self, Self::Error> {
let user = user.as_ref();
Address::check_user(user)?;
let domain = domain.as_ref();
Address::check_domain(domain)?;
let serialized = format!("{}@{}", user, domain);
Ok(Address {
serialized,
at_start: user.len(),
})
}
}
impl TryFrom<String> for Address {
type Error = AddressError;
fn try_from(serialized: String) -> Result<Self, AddressError> {
let at_start = check_address(&serialized)?;
Ok(Address {
serialized,
at_start,
})
}
}
impl AsRef<str> for Address {
fn as_ref(&self) -> &str {
&self.serialized
}
}
impl AsRef<OsStr> for Address {
fn as_ref(&self) -> &OsStr {
self.serialized.as_ref()
}
}
fn check_address(val: &str) -> Result<usize, AddressError> {
let mut parts = val.rsplitn(2, '@');
let domain = parts.next().ok_or(AddressError::MissingParts)?;
let user = parts.next().ok_or(AddressError::MissingParts)?;
Address::check_user(user)?;
Address::check_domain(domain)?;
Ok(user.len())
}
#[derive(Debug, PartialEq, Clone, Copy)]
/// Errors in email addresses parsing
pub enum AddressError {
/// Missing domain or user
MissingParts,
/// Unbalanced angle bracket
Unbalanced,
/// Invalid email user
InvalidUser,
/// Invalid email domain
InvalidDomain,
}
impl Error for AddressError {}
impl Display for AddressError {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
AddressError::MissingParts => f.write_str("Missing domain or user"),
AddressError::Unbalanced => f.write_str("Unbalanced angle bracket"),
AddressError::InvalidUser => f.write_str("Invalid email user"),
AddressError::InvalidDomain => f.write_str("Invalid email domain"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_address() {
let addr_str = "[email protected]";
let addr = Address::from_str(addr_str).unwrap();
let addr2 = Address::new("something", "example.com").unwrap();
assert_eq!(addr, addr2);
assert_eq!(addr.user(), "something");
assert_eq!(addr.domain(), "example.com");
assert_eq!(addr2.user(), "something");
assert_eq!(addr2.domain(), "example.com");
}
}
| user | identifier_name |
types.rs | //! Representation of an email address
use std::{
convert::{TryFrom, TryInto},
error::Error,
ffi::OsStr,
fmt::{Display, Formatter, Result as FmtResult},
net::IpAddr,
str::FromStr,
};
use idna::domain_to_ascii;
use once_cell::sync::Lazy;
use regex::Regex;
/// Represents an email address with a user and a domain name.
///
/// This type contains email in canonical form ([email protected]_).
///
/// **NOTE**: Enable feature "serde" to be able serialize/deserialize it using [serde](https://serde.rs/).
///
/// # Examples
///
/// You can create an `Address` from a user and a domain:
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.user(), "user");
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
///
/// You can also create an `Address` from a string literal by parsing it:
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = "[email protected]".parse::<Address>()?;
/// assert_eq!(address.user(), "user");
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Address {
/// Complete address
serialized: String,
/// Index into `serialized` before the '@'
at_start: usize,
}
// Regex from the specs
// https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
// It will mark esoteric email addresses like quoted string as invalid
static USER_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+\z").unwrap());
static DOMAIN_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r"(?i)^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$",
)
.unwrap()
});
// literal form, ipv4 or ipv6 address (SMTP 4.1.3)
static LITERAL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\[([A-f0-9:\.]+)\]\z").unwrap());
impl Address {
/// Creates a new email address from a user and domain.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// let expected = "[email protected]".parse::<Address>()?;
/// assert_eq!(expected, address);
/// # Ok(())
/// # }
/// ```
pub fn new<U: AsRef<str>, D: AsRef<str>>(user: U, domain: D) -> Result<Self, AddressError> {
(user, domain).try_into()
}
/// Gets the user portion of the `Address`.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.user(), "user");
/// # Ok(())
/// # }
/// ```
pub fn user(&self) -> &str {
&self.serialized[..self.at_start]
}
/// Gets the domain portion of the `Address`.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
pub fn domain(&self) -> &str {
&self.serialized[self.at_start + 1..]
}
pub(super) fn check_user(user: &str) -> Result<(), AddressError> {
if USER_RE.is_match(user) {
Ok(())
} else {
Err(AddressError::InvalidUser)
}
}
pub(super) fn check_domain(domain: &str) -> Result<(), AddressError> {
Address::check_domain_ascii(domain).or_else(|_| {
domain_to_ascii(domain)
.map_err(|_| AddressError::InvalidDomain)
.and_then(|domain| Address::check_domain_ascii(&domain))
})
}
fn check_domain_ascii(domain: &str) -> Result<(), AddressError> {
if DOMAIN_RE.is_match(domain) {
return Ok(());
}
if let Some(caps) = LITERAL_RE.captures(domain) {
if let Some(cap) = caps.get(1) {
if cap.as_str().parse::<IpAddr>().is_ok() {
return Ok(());
}
}
}
Err(AddressError::InvalidDomain)
}
#[cfg(feature = "smtp-transport")]
/// Check if the address contains non-ascii chars
pub(super) fn is_ascii(&self) -> bool {
self.serialized.is_ascii()
}
}
impl Display for Address {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str(&self.serialized)
}
}
impl FromStr for Address {
type Err = AddressError;
fn from_str(val: &str) -> Result<Self, AddressError> {
let at_start = check_address(val)?;
Ok(Address {
serialized: val.into(),
at_start,
})
}
}
impl<U, D> TryFrom<(U, D)> for Address
where
U: AsRef<str>,
D: AsRef<str>,
{
type Error = AddressError;
fn try_from((user, domain): (U, D)) -> Result<Self, Self::Error> {
let user = user.as_ref();
Address::check_user(user)?;
let domain = domain.as_ref();
Address::check_domain(domain)?;
let serialized = format!("{}@{}", user, domain);
Ok(Address {
serialized,
at_start: user.len(),
})
}
} | impl TryFrom<String> for Address {
type Error = AddressError;
fn try_from(serialized: String) -> Result<Self, AddressError> {
let at_start = check_address(&serialized)?;
Ok(Address {
serialized,
at_start,
})
}
}
impl AsRef<str> for Address {
fn as_ref(&self) -> &str {
&self.serialized
}
}
impl AsRef<OsStr> for Address {
fn as_ref(&self) -> &OsStr {
self.serialized.as_ref()
}
}
fn check_address(val: &str) -> Result<usize, AddressError> {
let mut parts = val.rsplitn(2, '@');
let domain = parts.next().ok_or(AddressError::MissingParts)?;
let user = parts.next().ok_or(AddressError::MissingParts)?;
Address::check_user(user)?;
Address::check_domain(domain)?;
Ok(user.len())
}
#[derive(Debug, PartialEq, Clone, Copy)]
/// Errors in email addresses parsing
pub enum AddressError {
/// Missing domain or user
MissingParts,
/// Unbalanced angle bracket
Unbalanced,
/// Invalid email user
InvalidUser,
/// Invalid email domain
InvalidDomain,
}
impl Error for AddressError {}
impl Display for AddressError {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
AddressError::MissingParts => f.write_str("Missing domain or user"),
AddressError::Unbalanced => f.write_str("Unbalanced angle bracket"),
AddressError::InvalidUser => f.write_str("Invalid email user"),
AddressError::InvalidDomain => f.write_str("Invalid email domain"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_address() {
let addr_str = "[email protected]";
let addr = Address::from_str(addr_str).unwrap();
let addr2 = Address::new("something", "example.com").unwrap();
assert_eq!(addr, addr2);
assert_eq!(addr.user(), "something");
assert_eq!(addr.domain(), "example.com");
assert_eq!(addr2.user(), "something");
assert_eq!(addr2.domain(), "example.com");
}
} | random_line_split |
|
types.rs | //! Representation of an email address
use std::{
convert::{TryFrom, TryInto},
error::Error,
ffi::OsStr,
fmt::{Display, Formatter, Result as FmtResult},
net::IpAddr,
str::FromStr,
};
use idna::domain_to_ascii;
use once_cell::sync::Lazy;
use regex::Regex;
/// Represents an email address with a user and a domain name.
///
/// This type contains email in canonical form ([email protected]_).
///
/// **NOTE**: Enable feature "serde" to be able serialize/deserialize it using [serde](https://serde.rs/).
///
/// # Examples
///
/// You can create an `Address` from a user and a domain:
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.user(), "user");
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
///
/// You can also create an `Address` from a string literal by parsing it:
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = "[email protected]".parse::<Address>()?;
/// assert_eq!(address.user(), "user");
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Address {
/// Complete address
serialized: String,
/// Index into `serialized` before the '@'
at_start: usize,
}
// Regex from the specs
// https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
// It will mark esoteric email addresses like quoted string as invalid
static USER_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+\z").unwrap());
static DOMAIN_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r"(?i)^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$",
)
.unwrap()
});
// literal form, ipv4 or ipv6 address (SMTP 4.1.3)
static LITERAL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\[([A-f0-9:\.]+)\]\z").unwrap());
impl Address {
/// Creates a new email address from a user and domain.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// let expected = "[email protected]".parse::<Address>()?;
/// assert_eq!(expected, address);
/// # Ok(())
/// # }
/// ```
pub fn new<U: AsRef<str>, D: AsRef<str>>(user: U, domain: D) -> Result<Self, AddressError> {
(user, domain).try_into()
}
/// Gets the user portion of the `Address`.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.user(), "user");
/// # Ok(())
/// # }
/// ```
pub fn user(&self) -> &str {
&self.serialized[..self.at_start]
}
/// Gets the domain portion of the `Address`.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
pub fn domain(&self) -> &str {
&self.serialized[self.at_start + 1..]
}
pub(super) fn check_user(user: &str) -> Result<(), AddressError> {
if USER_RE.is_match(user) {
Ok(())
} else {
Err(AddressError::InvalidUser)
}
}
pub(super) fn check_domain(domain: &str) -> Result<(), AddressError> {
Address::check_domain_ascii(domain).or_else(|_| {
domain_to_ascii(domain)
.map_err(|_| AddressError::InvalidDomain)
.and_then(|domain| Address::check_domain_ascii(&domain))
})
}
fn check_domain_ascii(domain: &str) -> Result<(), AddressError> {
if DOMAIN_RE.is_match(domain) {
return Ok(());
}
if let Some(caps) = LITERAL_RE.captures(domain) {
if let Some(cap) = caps.get(1) {
if cap.as_str().parse::<IpAddr>().is_ok() {
return Ok(());
}
}
}
Err(AddressError::InvalidDomain)
}
#[cfg(feature = "smtp-transport")]
/// Check if the address contains non-ascii chars
pub(super) fn is_ascii(&self) -> bool {
self.serialized.is_ascii()
}
}
impl Display for Address {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str(&self.serialized)
}
}
impl FromStr for Address {
type Err = AddressError;
fn from_str(val: &str) -> Result<Self, AddressError> {
let at_start = check_address(val)?;
Ok(Address {
serialized: val.into(),
at_start,
})
}
}
impl<U, D> TryFrom<(U, D)> for Address
where
U: AsRef<str>,
D: AsRef<str>,
{
type Error = AddressError;
fn try_from((user, domain): (U, D)) -> Result<Self, Self::Error> |
}
impl TryFrom<String> for Address {
type Error = AddressError;
fn try_from(serialized: String) -> Result<Self, AddressError> {
let at_start = check_address(&serialized)?;
Ok(Address {
serialized,
at_start,
})
}
}
impl AsRef<str> for Address {
fn as_ref(&self) -> &str {
&self.serialized
}
}
impl AsRef<OsStr> for Address {
fn as_ref(&self) -> &OsStr {
self.serialized.as_ref()
}
}
fn check_address(val: &str) -> Result<usize, AddressError> {
let mut parts = val.rsplitn(2, '@');
let domain = parts.next().ok_or(AddressError::MissingParts)?;
let user = parts.next().ok_or(AddressError::MissingParts)?;
Address::check_user(user)?;
Address::check_domain(domain)?;
Ok(user.len())
}
#[derive(Debug, PartialEq, Clone, Copy)]
/// Errors in email addresses parsing
pub enum AddressError {
/// Missing domain or user
MissingParts,
/// Unbalanced angle bracket
Unbalanced,
/// Invalid email user
InvalidUser,
/// Invalid email domain
InvalidDomain,
}
impl Error for AddressError {}
impl Display for AddressError {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
AddressError::MissingParts => f.write_str("Missing domain or user"),
AddressError::Unbalanced => f.write_str("Unbalanced angle bracket"),
AddressError::InvalidUser => f.write_str("Invalid email user"),
AddressError::InvalidDomain => f.write_str("Invalid email domain"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_address() {
let addr_str = "[email protected]";
let addr = Address::from_str(addr_str).unwrap();
let addr2 = Address::new("something", "example.com").unwrap();
assert_eq!(addr, addr2);
assert_eq!(addr.user(), "something");
assert_eq!(addr.domain(), "example.com");
assert_eq!(addr2.user(), "something");
assert_eq!(addr2.domain(), "example.com");
}
}
| {
let user = user.as_ref();
Address::check_user(user)?;
let domain = domain.as_ref();
Address::check_domain(domain)?;
let serialized = format!("{}@{}", user, domain);
Ok(Address {
serialized,
at_start: user.len(),
})
} | identifier_body |
types.rs | //! Representation of an email address
use std::{
convert::{TryFrom, TryInto},
error::Error,
ffi::OsStr,
fmt::{Display, Formatter, Result as FmtResult},
net::IpAddr,
str::FromStr,
};
use idna::domain_to_ascii;
use once_cell::sync::Lazy;
use regex::Regex;
/// Represents an email address with a user and a domain name.
///
/// This type contains email in canonical form ([email protected]_).
///
/// **NOTE**: Enable feature "serde" to be able serialize/deserialize it using [serde](https://serde.rs/).
///
/// # Examples
///
/// You can create an `Address` from a user and a domain:
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.user(), "user");
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
///
/// You can also create an `Address` from a string literal by parsing it:
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = "[email protected]".parse::<Address>()?;
/// assert_eq!(address.user(), "user");
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct Address {
/// Complete address
serialized: String,
/// Index into `serialized` before the '@'
at_start: usize,
}
// Regex from the specs
// https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address
// It will mark esoteric email addresses like quoted string as invalid
static USER_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+\z").unwrap());
static DOMAIN_RE: Lazy<Regex> = Lazy::new(|| {
Regex::new(
r"(?i)^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$",
)
.unwrap()
});
// literal form, ipv4 or ipv6 address (SMTP 4.1.3)
static LITERAL_RE: Lazy<Regex> = Lazy::new(|| Regex::new(r"(?i)\[([A-f0-9:\.]+)\]\z").unwrap());
impl Address {
/// Creates a new email address from a user and domain.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// let expected = "[email protected]".parse::<Address>()?;
/// assert_eq!(expected, address);
/// # Ok(())
/// # }
/// ```
pub fn new<U: AsRef<str>, D: AsRef<str>>(user: U, domain: D) -> Result<Self, AddressError> {
(user, domain).try_into()
}
/// Gets the user portion of the `Address`.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.user(), "user");
/// # Ok(())
/// # }
/// ```
pub fn user(&self) -> &str {
&self.serialized[..self.at_start]
}
/// Gets the domain portion of the `Address`.
///
/// # Examples
///
/// ```
/// use lettre::Address;
///
/// # use std::error::Error;
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let address = Address::new("user", "email.com")?;
/// assert_eq!(address.domain(), "email.com");
/// # Ok(())
/// # }
/// ```
pub fn domain(&self) -> &str {
&self.serialized[self.at_start + 1..]
}
pub(super) fn check_user(user: &str) -> Result<(), AddressError> {
if USER_RE.is_match(user) | else {
Err(AddressError::InvalidUser)
}
}
pub(super) fn check_domain(domain: &str) -> Result<(), AddressError> {
Address::check_domain_ascii(domain).or_else(|_| {
domain_to_ascii(domain)
.map_err(|_| AddressError::InvalidDomain)
.and_then(|domain| Address::check_domain_ascii(&domain))
})
}
fn check_domain_ascii(domain: &str) -> Result<(), AddressError> {
if DOMAIN_RE.is_match(domain) {
return Ok(());
}
if let Some(caps) = LITERAL_RE.captures(domain) {
if let Some(cap) = caps.get(1) {
if cap.as_str().parse::<IpAddr>().is_ok() {
return Ok(());
}
}
}
Err(AddressError::InvalidDomain)
}
#[cfg(feature = "smtp-transport")]
/// Check if the address contains non-ascii chars
pub(super) fn is_ascii(&self) -> bool {
self.serialized.is_ascii()
}
}
impl Display for Address {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
f.write_str(&self.serialized)
}
}
impl FromStr for Address {
type Err = AddressError;
fn from_str(val: &str) -> Result<Self, AddressError> {
let at_start = check_address(val)?;
Ok(Address {
serialized: val.into(),
at_start,
})
}
}
impl<U, D> TryFrom<(U, D)> for Address
where
U: AsRef<str>,
D: AsRef<str>,
{
type Error = AddressError;
fn try_from((user, domain): (U, D)) -> Result<Self, Self::Error> {
let user = user.as_ref();
Address::check_user(user)?;
let domain = domain.as_ref();
Address::check_domain(domain)?;
let serialized = format!("{}@{}", user, domain);
Ok(Address {
serialized,
at_start: user.len(),
})
}
}
impl TryFrom<String> for Address {
type Error = AddressError;
fn try_from(serialized: String) -> Result<Self, AddressError> {
let at_start = check_address(&serialized)?;
Ok(Address {
serialized,
at_start,
})
}
}
impl AsRef<str> for Address {
fn as_ref(&self) -> &str {
&self.serialized
}
}
impl AsRef<OsStr> for Address {
fn as_ref(&self) -> &OsStr {
self.serialized.as_ref()
}
}
fn check_address(val: &str) -> Result<usize, AddressError> {
let mut parts = val.rsplitn(2, '@');
let domain = parts.next().ok_or(AddressError::MissingParts)?;
let user = parts.next().ok_or(AddressError::MissingParts)?;
Address::check_user(user)?;
Address::check_domain(domain)?;
Ok(user.len())
}
#[derive(Debug, PartialEq, Clone, Copy)]
/// Errors in email addresses parsing
pub enum AddressError {
/// Missing domain or user
MissingParts,
/// Unbalanced angle bracket
Unbalanced,
/// Invalid email user
InvalidUser,
/// Invalid email domain
InvalidDomain,
}
impl Error for AddressError {}
impl Display for AddressError {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
AddressError::MissingParts => f.write_str("Missing domain or user"),
AddressError::Unbalanced => f.write_str("Unbalanced angle bracket"),
AddressError::InvalidUser => f.write_str("Invalid email user"),
AddressError::InvalidDomain => f.write_str("Invalid email domain"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_address() {
let addr_str = "[email protected]";
let addr = Address::from_str(addr_str).unwrap();
let addr2 = Address::new("something", "example.com").unwrap();
assert_eq!(addr, addr2);
assert_eq!(addr.user(), "something");
assert_eq!(addr.domain(), "example.com");
assert_eq!(addr2.user(), "something");
assert_eq!(addr2.domain(), "example.com");
}
}
| {
Ok(())
} | conditional_block |
list_retention.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use super::*;
use crate::{extensions::RequestExt, font_awesome};
use iml_wire_types::snapshot::{ReserveUnit, SnapshotRetention};
#[derive(Clone, Debug)]
pub enum Msg {
Page(paging::Msg),
Delete(Arc<SnapshotRetention>),
DeleteRetentionResp(fetch::ResponseDataResult<Response<snapshot::remove_retention::Resp>>),
}
#[derive(Default, Debug)]
pub struct Model {
pager: paging::Model,
rows: Vec<Arc<SnapshotRetention>>,
take: take::Model,
}
pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) {
match msg {
Msg::Page(msg) => |
Msg::Delete(x) => {
if let Ok(true) = window().confirm_with_message("Are you sure you want to delete this retention policy?") {
let query = snapshot::remove_retention::build(x.id);
let req = fetch::Request::graphql_query(&query);
orders.perform_cmd(req.fetch_json_data(|x| Msg::DeleteRetentionResp(x)));
}
}
Msg::DeleteRetentionResp(x) => match x {
Ok(Response::Data(_)) => {}
Ok(Response::Errors(e)) => {
error!("An error has occurred during Snapshot deletion: ", e);
}
Err(e) => {
error!("An error has occurred during Snapshot deletion: ", e);
}
},
};
}
impl RecordChange<Msg> for Model {
fn update_record(&mut self, _: ArcRecord, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
fn remove_record(&mut self, _: RecordId, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
fn set_records(&mut self, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
}
pub fn view(model: &Model, cache: &ArcCache, session: Option<&Session>) -> Node<Msg> {
panel::view(
h3![class![C.py_4, C.font_normal, C.text_lg], "Snapshot Retention Policies"],
div![
table::wrapper_view(vec![
table::thead_view(vec![
table::th_view(plain!["Filesystem"]),
table::th_view(plain!["Reserve"]),
table::th_view(plain!["Keep"]),
table::th_view(plain!["Last Run"]),
restrict::view(session, GroupType::FilesystemAdministrators, th![]),
]),
tbody![model.rows[model.pager.range()].iter().map(|x| {
tr![
td![
table::td_cls(),
class![C.text_center],
match get_fs_by_name(cache, &x.filesystem_name) {
Some(x) => {
div![resource_links::fs_link(&x)]
}
None => {
plain![x.filesystem_name.to_string()]
}
}
],
table::td_center(plain![format!(
"{} {}",
x.reserve_value,
match x.reserve_unit {
ReserveUnit::Percent => "%",
ReserveUnit::Gibibytes => "GiB",
ReserveUnit::Tebibytes => "TiB",
}
)]),
table::td_center(plain![x.keep_num.to_string()]),
table::td_center(plain![x
.last_run
.map(|x| x.format("%m/%d/%Y %H:%M:%S").to_string())
.unwrap_or_else(|| "---".to_string())]),
td![
class![C.flex, C.justify_center, C.p_4, C.px_3],
restrict::view(
session,
GroupType::FilesystemAdministrators,
button![
class![
C.bg_blue_500,
C.duration_300,
C.flex,
C.hover__bg_blue_400,
C.items_center,
C.px_6,
C.py_2,
C.rounded_sm,
C.text_white,
C.transition_colors,
],
font_awesome(class![C.w_3, C.h_3, C.inline, C.mr_1], "trash"),
"Delete Policy",
simple_ev(Ev::Click, Msg::Delete(Arc::clone(&x)))
]
)
]
]
})]
])
.merge_attrs(class![C.my_6]),
div![
class![C.flex, C.justify_end, C.py_1, C.pr_3],
paging::limit_selection_view(&model.pager).map_msg(Msg::Page),
paging::page_count_view(&model.pager),
paging::next_prev_view(&model.pager).map_msg(Msg::Page)
]
],
)
}
| {
paging::update(msg, &mut model.pager, &mut orders.proxy(Msg::Page));
} | conditional_block |
list_retention.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use super::*;
use crate::{extensions::RequestExt, font_awesome};
use iml_wire_types::snapshot::{ReserveUnit, SnapshotRetention};
#[derive(Clone, Debug)]
pub enum Msg {
Page(paging::Msg),
Delete(Arc<SnapshotRetention>),
DeleteRetentionResp(fetch::ResponseDataResult<Response<snapshot::remove_retention::Resp>>),
}
#[derive(Default, Debug)]
pub struct Model {
pager: paging::Model,
rows: Vec<Arc<SnapshotRetention>>,
take: take::Model,
}
pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) {
match msg {
Msg::Page(msg) => {
paging::update(msg, &mut model.pager, &mut orders.proxy(Msg::Page));
}
Msg::Delete(x) => {
if let Ok(true) = window().confirm_with_message("Are you sure you want to delete this retention policy?") {
let query = snapshot::remove_retention::build(x.id);
let req = fetch::Request::graphql_query(&query);
orders.perform_cmd(req.fetch_json_data(|x| Msg::DeleteRetentionResp(x)));
}
}
Msg::DeleteRetentionResp(x) => match x {
Ok(Response::Data(_)) => {}
Ok(Response::Errors(e)) => {
error!("An error has occurred during Snapshot deletion: ", e);
}
Err(e) => {
error!("An error has occurred during Snapshot deletion: ", e);
}
},
};
}
impl RecordChange<Msg> for Model {
fn update_record(&mut self, _: ArcRecord, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
fn remove_record(&mut self, _: RecordId, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
fn set_records(&mut self, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
}
pub fn view(model: &Model, cache: &ArcCache, session: Option<&Session>) -> Node<Msg> {
panel::view(
h3![class![C.py_4, C.font_normal, C.text_lg], "Snapshot Retention Policies"],
div![
table::wrapper_view(vec![
table::thead_view(vec![
table::th_view(plain!["Filesystem"]),
table::th_view(plain!["Reserve"]),
table::th_view(plain!["Keep"]),
table::th_view(plain!["Last Run"]),
restrict::view(session, GroupType::FilesystemAdministrators, th![]),
]),
tbody![model.rows[model.pager.range()].iter().map(|x| {
tr![
td![
table::td_cls(),
class![C.text_center],
match get_fs_by_name(cache, &x.filesystem_name) {
Some(x) => {
div![resource_links::fs_link(&x)]
}
None => {
plain![x.filesystem_name.to_string()]
}
}
],
table::td_center(plain![format!(
"{} {}",
x.reserve_value,
match x.reserve_unit {
ReserveUnit::Percent => "%",
ReserveUnit::Gibibytes => "GiB",
ReserveUnit::Tebibytes => "TiB",
}
)]),
table::td_center(plain![x.keep_num.to_string()]),
table::td_center(plain![x
.last_run
.map(|x| x.format("%m/%d/%Y %H:%M:%S").to_string())
.unwrap_or_else(|| "---".to_string())]),
td![ | session,
GroupType::FilesystemAdministrators,
button![
class![
C.bg_blue_500,
C.duration_300,
C.flex,
C.hover__bg_blue_400,
C.items_center,
C.px_6,
C.py_2,
C.rounded_sm,
C.text_white,
C.transition_colors,
],
font_awesome(class![C.w_3, C.h_3, C.inline, C.mr_1], "trash"),
"Delete Policy",
simple_ev(Ev::Click, Msg::Delete(Arc::clone(&x)))
]
)
]
]
})]
])
.merge_attrs(class![C.my_6]),
div![
class![C.flex, C.justify_end, C.py_1, C.pr_3],
paging::limit_selection_view(&model.pager).map_msg(Msg::Page),
paging::page_count_view(&model.pager),
paging::next_prev_view(&model.pager).map_msg(Msg::Page)
]
],
)
} | class![C.flex, C.justify_center, C.p_4, C.px_3],
restrict::view( | random_line_split |
list_retention.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use super::*;
use crate::{extensions::RequestExt, font_awesome};
use iml_wire_types::snapshot::{ReserveUnit, SnapshotRetention};
#[derive(Clone, Debug)]
pub enum Msg {
Page(paging::Msg),
Delete(Arc<SnapshotRetention>),
DeleteRetentionResp(fetch::ResponseDataResult<Response<snapshot::remove_retention::Resp>>),
}
#[derive(Default, Debug)]
pub struct Model {
pager: paging::Model,
rows: Vec<Arc<SnapshotRetention>>,
take: take::Model,
}
pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) {
match msg {
Msg::Page(msg) => {
paging::update(msg, &mut model.pager, &mut orders.proxy(Msg::Page));
}
Msg::Delete(x) => {
if let Ok(true) = window().confirm_with_message("Are you sure you want to delete this retention policy?") {
let query = snapshot::remove_retention::build(x.id);
let req = fetch::Request::graphql_query(&query);
orders.perform_cmd(req.fetch_json_data(|x| Msg::DeleteRetentionResp(x)));
}
}
Msg::DeleteRetentionResp(x) => match x {
Ok(Response::Data(_)) => {}
Ok(Response::Errors(e)) => {
error!("An error has occurred during Snapshot deletion: ", e);
}
Err(e) => {
error!("An error has occurred during Snapshot deletion: ", e);
}
},
};
}
impl RecordChange<Msg> for Model {
fn update_record(&mut self, _: ArcRecord, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) |
fn remove_record(&mut self, _: RecordId, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
fn set_records(&mut self, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
}
pub fn view(model: &Model, cache: &ArcCache, session: Option<&Session>) -> Node<Msg> {
panel::view(
h3![class![C.py_4, C.font_normal, C.text_lg], "Snapshot Retention Policies"],
div![
table::wrapper_view(vec![
table::thead_view(vec![
table::th_view(plain!["Filesystem"]),
table::th_view(plain!["Reserve"]),
table::th_view(plain!["Keep"]),
table::th_view(plain!["Last Run"]),
restrict::view(session, GroupType::FilesystemAdministrators, th![]),
]),
tbody![model.rows[model.pager.range()].iter().map(|x| {
tr![
td![
table::td_cls(),
class![C.text_center],
match get_fs_by_name(cache, &x.filesystem_name) {
Some(x) => {
div![resource_links::fs_link(&x)]
}
None => {
plain![x.filesystem_name.to_string()]
}
}
],
table::td_center(plain![format!(
"{} {}",
x.reserve_value,
match x.reserve_unit {
ReserveUnit::Percent => "%",
ReserveUnit::Gibibytes => "GiB",
ReserveUnit::Tebibytes => "TiB",
}
)]),
table::td_center(plain![x.keep_num.to_string()]),
table::td_center(plain![x
.last_run
.map(|x| x.format("%m/%d/%Y %H:%M:%S").to_string())
.unwrap_or_else(|| "---".to_string())]),
td![
class![C.flex, C.justify_center, C.p_4, C.px_3],
restrict::view(
session,
GroupType::FilesystemAdministrators,
button![
class![
C.bg_blue_500,
C.duration_300,
C.flex,
C.hover__bg_blue_400,
C.items_center,
C.px_6,
C.py_2,
C.rounded_sm,
C.text_white,
C.transition_colors,
],
font_awesome(class![C.w_3, C.h_3, C.inline, C.mr_1], "trash"),
"Delete Policy",
simple_ev(Ev::Click, Msg::Delete(Arc::clone(&x)))
]
)
]
]
})]
])
.merge_attrs(class![C.my_6]),
div![
class![C.flex, C.justify_end, C.py_1, C.pr_3],
paging::limit_selection_view(&model.pager).map_msg(Msg::Page),
paging::page_count_view(&model.pager),
paging::next_prev_view(&model.pager).map_msg(Msg::Page)
]
],
)
}
| {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
} | identifier_body |
list_retention.rs | // Copyright (c) 2020 DDN. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
use super::*;
use crate::{extensions::RequestExt, font_awesome};
use iml_wire_types::snapshot::{ReserveUnit, SnapshotRetention};
#[derive(Clone, Debug)]
pub enum Msg {
Page(paging::Msg),
Delete(Arc<SnapshotRetention>),
DeleteRetentionResp(fetch::ResponseDataResult<Response<snapshot::remove_retention::Resp>>),
}
#[derive(Default, Debug)]
pub struct Model {
pager: paging::Model,
rows: Vec<Arc<SnapshotRetention>>,
take: take::Model,
}
pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg, GMsg>) {
match msg {
Msg::Page(msg) => {
paging::update(msg, &mut model.pager, &mut orders.proxy(Msg::Page));
}
Msg::Delete(x) => {
if let Ok(true) = window().confirm_with_message("Are you sure you want to delete this retention policy?") {
let query = snapshot::remove_retention::build(x.id);
let req = fetch::Request::graphql_query(&query);
orders.perform_cmd(req.fetch_json_data(|x| Msg::DeleteRetentionResp(x)));
}
}
Msg::DeleteRetentionResp(x) => match x {
Ok(Response::Data(_)) => {}
Ok(Response::Errors(e)) => {
error!("An error has occurred during Snapshot deletion: ", e);
}
Err(e) => {
error!("An error has occurred during Snapshot deletion: ", e);
}
},
};
}
impl RecordChange<Msg> for Model {
fn update_record(&mut self, _: ArcRecord, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
fn remove_record(&mut self, _: RecordId, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
fn set_records(&mut self, cache: &ArcCache, orders: &mut impl Orders<Msg, GMsg>) {
self.rows = cache.snapshot_retention.values().cloned().collect();
orders.proxy(Msg::Page).send_msg(paging::Msg::SetTotal(self.rows.len()));
}
}
pub fn | (model: &Model, cache: &ArcCache, session: Option<&Session>) -> Node<Msg> {
panel::view(
h3![class![C.py_4, C.font_normal, C.text_lg], "Snapshot Retention Policies"],
div![
table::wrapper_view(vec![
table::thead_view(vec![
table::th_view(plain!["Filesystem"]),
table::th_view(plain!["Reserve"]),
table::th_view(plain!["Keep"]),
table::th_view(plain!["Last Run"]),
restrict::view(session, GroupType::FilesystemAdministrators, th![]),
]),
tbody![model.rows[model.pager.range()].iter().map(|x| {
tr![
td![
table::td_cls(),
class![C.text_center],
match get_fs_by_name(cache, &x.filesystem_name) {
Some(x) => {
div![resource_links::fs_link(&x)]
}
None => {
plain![x.filesystem_name.to_string()]
}
}
],
table::td_center(plain![format!(
"{} {}",
x.reserve_value,
match x.reserve_unit {
ReserveUnit::Percent => "%",
ReserveUnit::Gibibytes => "GiB",
ReserveUnit::Tebibytes => "TiB",
}
)]),
table::td_center(plain![x.keep_num.to_string()]),
table::td_center(plain![x
.last_run
.map(|x| x.format("%m/%d/%Y %H:%M:%S").to_string())
.unwrap_or_else(|| "---".to_string())]),
td![
class![C.flex, C.justify_center, C.p_4, C.px_3],
restrict::view(
session,
GroupType::FilesystemAdministrators,
button![
class![
C.bg_blue_500,
C.duration_300,
C.flex,
C.hover__bg_blue_400,
C.items_center,
C.px_6,
C.py_2,
C.rounded_sm,
C.text_white,
C.transition_colors,
],
font_awesome(class![C.w_3, C.h_3, C.inline, C.mr_1], "trash"),
"Delete Policy",
simple_ev(Ev::Click, Msg::Delete(Arc::clone(&x)))
]
)
]
]
})]
])
.merge_attrs(class![C.my_6]),
div![
class![C.flex, C.justify_end, C.py_1, C.pr_3],
paging::limit_selection_view(&model.pager).map_msg(Msg::Page),
paging::page_count_view(&model.pager),
paging::next_prev_view(&model.pager).map_msg(Msg::Page)
]
],
)
}
| view | identifier_name |
vec.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//#[path = "../rust-core/"]
extern mod core;
use core::container::Container;
use core::mem::{forget, move_val_init, size_of, transmute};
use core::fail::out_of_memory;
use kernel::*;
use kernel::memory::*;
use kernel::memory::Allocator;
//use core::heap::{free, alloc, realloc};
use core::ops::Drop;
use core::slice::{Items, Slice, iter, unchecked_get, unchecked_mut_get};
use core::ptr::{offset, read_ptr};
use core::uint::mul_with_overflow;
use core::option::{Option, Some, None};
use core::iter::{Iterator, DoubleEndedIterator};
use core::cmp::expect;
use core::clone::Clone;
#[path = "../rust-core/macros.rs"]
mod macros;
pub struct Vec<T> {
priv len: uint,
priv cap: uint,
priv ptr: *mut T
}
impl<T> Vec<T> {
#[inline(always)]
pub fn new() -> Vec<T> {
Vec { len: 0, cap: 0, ptr: 0 as *mut T }
}
pub fn with_capacity(capacity: uint) -> Vec<T> {
if capacity == 0 {
Vec::new()
} else {
let (size, overflow) = mul_with_overflow(capacity, size_of::<T>());
if overflow {
out_of_memory();
}
let (addr, sz) = unsafe { heap.alloc(size) };
Vec { len: 0, cap: sz, ptr: addr as *mut T }
}
}
#[inline(always)]
pub fn capacity(&self) -> uint {
self.cap
}
pub fn reserve(&mut self, capacity: uint) {
if capacity >= self.len {
let (size, overflow) = mul_with_overflow(capacity, size_of::<T>());
if overflow {
out_of_memory();
}
self.cap = capacity;
unsafe {
let (addr, sz) = heap.realloc(self.ptr as *mut u8, size);
self.ptr = addr as *mut T;
self.cap = sz;
}
}
}
#[inline]
pub fn shrink_to_fit(&mut self) {
if self.len == 0 {
unsafe { heap.free(self.ptr as *mut u8) };
self.cap = 0;
self.ptr = 0 as *mut T;
} else {
unsafe {
// Overflow check is unnecessary as the vector is already at least this large.
let (addr, sz) = heap.realloc(self.ptr as *mut u8, self.len * size_of::<T>());
self.ptr = addr as *mut T;
self.cap = sz;
}
//self.cap = self.len;
}
}
pub fn pop(&mut self) -> Option<T> {
if self.len == 0 {
None
} else {
unsafe {
self.len -= 1;
Some(read_ptr(unchecked_get(self.as_slice(), self.len())))
}
}
}
#[inline]
pub fn push(&mut self, value: T) {
if unlikely!(self.len == self.cap) {
if self.cap == 0 { self.cap += 2 }
let old_size = self.cap * size_of::<T>();
self.cap = self.cap * 2;
let size = old_size * 2;
if old_size > size { out_of_memory() }
unsafe {
let (addr, sz) = heap.realloc(self.ptr as *mut u8, size);
self.ptr = addr as *mut T;
self.cap = sz;
}
}
unsafe {
let end = offset(self.ptr as *T, self.len as int) as *mut T;
move_val_init(&mut *end, value);
self.len += 1;
}
}
pub fn truncate(&mut self, len: uint) {
unsafe {
let mut i = len;
// drop any extra elements
while i < self.len {
read_ptr(unchecked_get(self.as_slice(), i));
i += 1;
}
}
self.len = len;
}
#[inline]
pub fn as_slice<'a>(&'a self) -> &'a [T] {
let slice = Slice { data: self.ptr as *T, len: self.len };
unsafe { transmute(slice) }
}
#[inline]
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] |
pub fn move_iter(self) -> MoveItems<T> {
unsafe {
let iter = transmute(iter(self.as_slice()));
let ptr = self.ptr as *mut u8;
forget(self);
MoveItems { allocation: ptr, iter: iter }
}
}
pub unsafe fn set_len(&mut self, len: uint) {
self.len = len;
}
}
impl<T: Clone> Vec<T> {
pub fn from_elem(length: uint, value: T) -> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
while xs.len < length {
move_val_init(unchecked_mut_get(xs.as_mut_slice(), xs.len), value.clone());
xs.len += 1;
}
xs
}
}
pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
while xs.len < length {
move_val_init(unchecked_mut_get(xs.as_mut_slice(), xs.len), op(xs.len));
xs.len += 1;
}
xs
}
}
}
impl<T> Container for Vec<T> {
#[inline(always)]
fn len(&self) -> uint {
self.len
}
}
#[unsafe_destructor]
impl<T> Drop for Vec<T> {
fn drop(&mut self) {
unsafe {
for x in iter(self.as_mut_slice()) {
read_ptr(x);
}
heap.free(self.ptr as *mut u8)
}
}
}
pub struct MoveItems<T> {
priv allocation: *mut u8, // the block of memory allocated for the vector
priv iter: Items<'static, T>
}
impl<T> Iterator<T> for MoveItems<T> {
fn next(&mut self) -> Option<T> {
unsafe {
self.iter.next().map(|x| read_ptr(x))
}
}
fn size_hint(&self) -> (uint, Option<uint>) {
self.iter.size_hint()
}
}
impl<T> DoubleEndedIterator<T> for MoveItems<T> {
fn next_back(&mut self) -> Option<T> {
unsafe {
self.iter.next_back().map(|x| read_ptr(x))
}
}
}
#[unsafe_destructor]
impl<T> Drop for MoveItems<T> {
fn drop(&mut self) {
// destroy the remaining elements
for _x in *self {}
unsafe {
heap.free(self.allocation)
}
}
}
/*
mod detail {
extern {
pub fn free(ptr: *mut u8);
pub fn realloc(ptr: *mut u8, size: uint) -> *mut u8;
}
}
extern {
fn calloc(nmemb: uint, size: uint) -> *mut u8;
fn malloc(size: uint) -> *mut u8;
}
#[inline(always)]
#[lang = "exchange_free"]
pub unsafe fn free(ptr: *mut u8) {
detail::free(ptr)
}
#[inline]
#[lang = "exchange_malloc"]
pub unsafe fn alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = malloc(size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn zero_alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = alloc(1, size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn realloc(ptr: *mut u8, size: uint) -> *mut u8 {
if size == 0 {
free(ptr);
0 as *mut u8
} else {
let ptr = detail::realloc(ptr, size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}*/ | {
let slice = Slice { data: self.ptr as *T, len: self.len };
unsafe { transmute(slice) }
} | identifier_body |
vec.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//#[path = "../rust-core/"]
extern mod core;
use core::container::Container;
use core::mem::{forget, move_val_init, size_of, transmute};
use core::fail::out_of_memory;
use kernel::*;
use kernel::memory::*;
use kernel::memory::Allocator;
//use core::heap::{free, alloc, realloc};
use core::ops::Drop;
use core::slice::{Items, Slice, iter, unchecked_get, unchecked_mut_get};
use core::ptr::{offset, read_ptr};
use core::uint::mul_with_overflow;
use core::option::{Option, Some, None};
use core::iter::{Iterator, DoubleEndedIterator};
use core::cmp::expect;
use core::clone::Clone;
#[path = "../rust-core/macros.rs"]
mod macros;
pub struct Vec<T> {
priv len: uint,
priv cap: uint,
priv ptr: *mut T
}
impl<T> Vec<T> {
#[inline(always)]
pub fn new() -> Vec<T> {
Vec { len: 0, cap: 0, ptr: 0 as *mut T }
}
pub fn with_capacity(capacity: uint) -> Vec<T> {
if capacity == 0 {
Vec::new()
} else {
let (size, overflow) = mul_with_overflow(capacity, size_of::<T>());
if overflow {
out_of_memory();
}
let (addr, sz) = unsafe { heap.alloc(size) };
Vec { len: 0, cap: sz, ptr: addr as *mut T }
}
}
#[inline(always)]
pub fn capacity(&self) -> uint {
self.cap
}
pub fn reserve(&mut self, capacity: uint) {
if capacity >= self.len {
let (size, overflow) = mul_with_overflow(capacity, size_of::<T>());
if overflow {
out_of_memory();
}
self.cap = capacity;
unsafe {
let (addr, sz) = heap.realloc(self.ptr as *mut u8, size);
self.ptr = addr as *mut T;
self.cap = sz;
}
}
}
#[inline]
pub fn shrink_to_fit(&mut self) {
if self.len == 0 {
unsafe { heap.free(self.ptr as *mut u8) };
self.cap = 0;
self.ptr = 0 as *mut T;
} else {
unsafe {
// Overflow check is unnecessary as the vector is already at least this large.
let (addr, sz) = heap.realloc(self.ptr as *mut u8, self.len * size_of::<T>());
self.ptr = addr as *mut T;
self.cap = sz;
}
//self.cap = self.len;
}
}
pub fn pop(&mut self) -> Option<T> {
if self.len == 0 {
None
} else {
unsafe {
self.len -= 1;
Some(read_ptr(unchecked_get(self.as_slice(), self.len())))
}
}
}
#[inline]
pub fn push(&mut self, value: T) {
if unlikely!(self.len == self.cap) {
if self.cap == 0 { self.cap += 2 }
let old_size = self.cap * size_of::<T>();
self.cap = self.cap * 2;
let size = old_size * 2;
if old_size > size { out_of_memory() }
unsafe {
let (addr, sz) = heap.realloc(self.ptr as *mut u8, size);
self.ptr = addr as *mut T;
self.cap = sz;
}
}
unsafe {
let end = offset(self.ptr as *T, self.len as int) as *mut T;
move_val_init(&mut *end, value);
self.len += 1;
}
}
pub fn truncate(&mut self, len: uint) {
unsafe {
let mut i = len;
// drop any extra elements
while i < self.len {
read_ptr(unchecked_get(self.as_slice(), i));
i += 1;
}
}
self.len = len;
}
#[inline]
pub fn as_slice<'a>(&'a self) -> &'a [T] {
let slice = Slice { data: self.ptr as *T, len: self.len };
unsafe { transmute(slice) }
}
#[inline]
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
let slice = Slice { data: self.ptr as *T, len: self.len };
unsafe { transmute(slice) }
}
pub fn move_iter(self) -> MoveItems<T> {
unsafe {
let iter = transmute(iter(self.as_slice()));
let ptr = self.ptr as *mut u8;
forget(self);
MoveItems { allocation: ptr, iter: iter }
}
}
pub unsafe fn set_len(&mut self, len: uint) {
self.len = len;
}
}
impl<T: Clone> Vec<T> {
pub fn from_elem(length: uint, value: T) -> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
while xs.len < length {
move_val_init(unchecked_mut_get(xs.as_mut_slice(), xs.len), value.clone());
xs.len += 1;
}
xs
}
}
pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
while xs.len < length {
move_val_init(unchecked_mut_get(xs.as_mut_slice(), xs.len), op(xs.len));
xs.len += 1;
}
xs
}
}
}
impl<T> Container for Vec<T> {
#[inline(always)]
fn len(&self) -> uint {
self.len
}
}
#[unsafe_destructor]
impl<T> Drop for Vec<T> {
fn drop(&mut self) {
unsafe {
for x in iter(self.as_mut_slice()) {
read_ptr(x);
} |
pub struct MoveItems<T> {
priv allocation: *mut u8, // the block of memory allocated for the vector
priv iter: Items<'static, T>
}
impl<T> Iterator<T> for MoveItems<T> {
fn next(&mut self) -> Option<T> {
unsafe {
self.iter.next().map(|x| read_ptr(x))
}
}
fn size_hint(&self) -> (uint, Option<uint>) {
self.iter.size_hint()
}
}
impl<T> DoubleEndedIterator<T> for MoveItems<T> {
fn next_back(&mut self) -> Option<T> {
unsafe {
self.iter.next_back().map(|x| read_ptr(x))
}
}
}
#[unsafe_destructor]
impl<T> Drop for MoveItems<T> {
fn drop(&mut self) {
// destroy the remaining elements
for _x in *self {}
unsafe {
heap.free(self.allocation)
}
}
}
/*
mod detail {
extern {
pub fn free(ptr: *mut u8);
pub fn realloc(ptr: *mut u8, size: uint) -> *mut u8;
}
}
extern {
fn calloc(nmemb: uint, size: uint) -> *mut u8;
fn malloc(size: uint) -> *mut u8;
}
#[inline(always)]
#[lang = "exchange_free"]
pub unsafe fn free(ptr: *mut u8) {
detail::free(ptr)
}
#[inline]
#[lang = "exchange_malloc"]
pub unsafe fn alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = malloc(size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn zero_alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = alloc(1, size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn realloc(ptr: *mut u8, size: uint) -> *mut u8 {
if size == 0 {
free(ptr);
0 as *mut u8
} else {
let ptr = detail::realloc(ptr, size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}*/ | heap.free(self.ptr as *mut u8)
}
}
} | random_line_split |
vec.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//#[path = "../rust-core/"]
extern mod core;
use core::container::Container;
use core::mem::{forget, move_val_init, size_of, transmute};
use core::fail::out_of_memory;
use kernel::*;
use kernel::memory::*;
use kernel::memory::Allocator;
//use core::heap::{free, alloc, realloc};
use core::ops::Drop;
use core::slice::{Items, Slice, iter, unchecked_get, unchecked_mut_get};
use core::ptr::{offset, read_ptr};
use core::uint::mul_with_overflow;
use core::option::{Option, Some, None};
use core::iter::{Iterator, DoubleEndedIterator};
use core::cmp::expect;
use core::clone::Clone;
#[path = "../rust-core/macros.rs"]
mod macros;
pub struct Vec<T> {
priv len: uint,
priv cap: uint,
priv ptr: *mut T
}
impl<T> Vec<T> {
#[inline(always)]
pub fn new() -> Vec<T> {
Vec { len: 0, cap: 0, ptr: 0 as *mut T }
}
pub fn with_capacity(capacity: uint) -> Vec<T> {
if capacity == 0 {
Vec::new()
} else {
let (size, overflow) = mul_with_overflow(capacity, size_of::<T>());
if overflow {
out_of_memory();
}
let (addr, sz) = unsafe { heap.alloc(size) };
Vec { len: 0, cap: sz, ptr: addr as *mut T }
}
}
#[inline(always)]
pub fn capacity(&self) -> uint {
self.cap
}
pub fn reserve(&mut self, capacity: uint) {
if capacity >= self.len {
let (size, overflow) = mul_with_overflow(capacity, size_of::<T>());
if overflow {
out_of_memory();
}
self.cap = capacity;
unsafe {
let (addr, sz) = heap.realloc(self.ptr as *mut u8, size);
self.ptr = addr as *mut T;
self.cap = sz;
}
}
}
#[inline]
pub fn shrink_to_fit(&mut self) {
if self.len == 0 {
unsafe { heap.free(self.ptr as *mut u8) };
self.cap = 0;
self.ptr = 0 as *mut T;
} else {
unsafe {
// Overflow check is unnecessary as the vector is already at least this large.
let (addr, sz) = heap.realloc(self.ptr as *mut u8, self.len * size_of::<T>());
self.ptr = addr as *mut T;
self.cap = sz;
}
//self.cap = self.len;
}
}
pub fn pop(&mut self) -> Option<T> {
if self.len == 0 {
None
} else {
unsafe {
self.len -= 1;
Some(read_ptr(unchecked_get(self.as_slice(), self.len())))
}
}
}
#[inline]
pub fn push(&mut self, value: T) {
if unlikely!(self.len == self.cap) {
if self.cap == 0 |
let old_size = self.cap * size_of::<T>();
self.cap = self.cap * 2;
let size = old_size * 2;
if old_size > size { out_of_memory() }
unsafe {
let (addr, sz) = heap.realloc(self.ptr as *mut u8, size);
self.ptr = addr as *mut T;
self.cap = sz;
}
}
unsafe {
let end = offset(self.ptr as *T, self.len as int) as *mut T;
move_val_init(&mut *end, value);
self.len += 1;
}
}
pub fn truncate(&mut self, len: uint) {
unsafe {
let mut i = len;
// drop any extra elements
while i < self.len {
read_ptr(unchecked_get(self.as_slice(), i));
i += 1;
}
}
self.len = len;
}
#[inline]
pub fn as_slice<'a>(&'a self) -> &'a [T] {
let slice = Slice { data: self.ptr as *T, len: self.len };
unsafe { transmute(slice) }
}
#[inline]
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
let slice = Slice { data: self.ptr as *T, len: self.len };
unsafe { transmute(slice) }
}
pub fn move_iter(self) -> MoveItems<T> {
unsafe {
let iter = transmute(iter(self.as_slice()));
let ptr = self.ptr as *mut u8;
forget(self);
MoveItems { allocation: ptr, iter: iter }
}
}
pub unsafe fn set_len(&mut self, len: uint) {
self.len = len;
}
}
impl<T: Clone> Vec<T> {
pub fn from_elem(length: uint, value: T) -> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
while xs.len < length {
move_val_init(unchecked_mut_get(xs.as_mut_slice(), xs.len), value.clone());
xs.len += 1;
}
xs
}
}
pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
while xs.len < length {
move_val_init(unchecked_mut_get(xs.as_mut_slice(), xs.len), op(xs.len));
xs.len += 1;
}
xs
}
}
}
impl<T> Container for Vec<T> {
#[inline(always)]
fn len(&self) -> uint {
self.len
}
}
#[unsafe_destructor]
impl<T> Drop for Vec<T> {
fn drop(&mut self) {
unsafe {
for x in iter(self.as_mut_slice()) {
read_ptr(x);
}
heap.free(self.ptr as *mut u8)
}
}
}
pub struct MoveItems<T> {
priv allocation: *mut u8, // the block of memory allocated for the vector
priv iter: Items<'static, T>
}
impl<T> Iterator<T> for MoveItems<T> {
fn next(&mut self) -> Option<T> {
unsafe {
self.iter.next().map(|x| read_ptr(x))
}
}
fn size_hint(&self) -> (uint, Option<uint>) {
self.iter.size_hint()
}
}
impl<T> DoubleEndedIterator<T> for MoveItems<T> {
fn next_back(&mut self) -> Option<T> {
unsafe {
self.iter.next_back().map(|x| read_ptr(x))
}
}
}
#[unsafe_destructor]
impl<T> Drop for MoveItems<T> {
fn drop(&mut self) {
// destroy the remaining elements
for _x in *self {}
unsafe {
heap.free(self.allocation)
}
}
}
/*
mod detail {
extern {
pub fn free(ptr: *mut u8);
pub fn realloc(ptr: *mut u8, size: uint) -> *mut u8;
}
}
extern {
fn calloc(nmemb: uint, size: uint) -> *mut u8;
fn malloc(size: uint) -> *mut u8;
}
#[inline(always)]
#[lang = "exchange_free"]
pub unsafe fn free(ptr: *mut u8) {
detail::free(ptr)
}
#[inline]
#[lang = "exchange_malloc"]
pub unsafe fn alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = malloc(size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn zero_alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = alloc(1, size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn realloc(ptr: *mut u8, size: uint) -> *mut u8 {
if size == 0 {
free(ptr);
0 as *mut u8
} else {
let ptr = detail::realloc(ptr, size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}*/ | { self.cap += 2 } | conditional_block |
vec.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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//#[path = "../rust-core/"]
extern mod core;
use core::container::Container;
use core::mem::{forget, move_val_init, size_of, transmute};
use core::fail::out_of_memory;
use kernel::*;
use kernel::memory::*;
use kernel::memory::Allocator;
//use core::heap::{free, alloc, realloc};
use core::ops::Drop;
use core::slice::{Items, Slice, iter, unchecked_get, unchecked_mut_get};
use core::ptr::{offset, read_ptr};
use core::uint::mul_with_overflow;
use core::option::{Option, Some, None};
use core::iter::{Iterator, DoubleEndedIterator};
use core::cmp::expect;
use core::clone::Clone;
#[path = "../rust-core/macros.rs"]
mod macros;
pub struct Vec<T> {
priv len: uint,
priv cap: uint,
priv ptr: *mut T
}
impl<T> Vec<T> {
#[inline(always)]
pub fn new() -> Vec<T> {
Vec { len: 0, cap: 0, ptr: 0 as *mut T }
}
pub fn | (capacity: uint) -> Vec<T> {
if capacity == 0 {
Vec::new()
} else {
let (size, overflow) = mul_with_overflow(capacity, size_of::<T>());
if overflow {
out_of_memory();
}
let (addr, sz) = unsafe { heap.alloc(size) };
Vec { len: 0, cap: sz, ptr: addr as *mut T }
}
}
#[inline(always)]
pub fn capacity(&self) -> uint {
self.cap
}
pub fn reserve(&mut self, capacity: uint) {
if capacity >= self.len {
let (size, overflow) = mul_with_overflow(capacity, size_of::<T>());
if overflow {
out_of_memory();
}
self.cap = capacity;
unsafe {
let (addr, sz) = heap.realloc(self.ptr as *mut u8, size);
self.ptr = addr as *mut T;
self.cap = sz;
}
}
}
#[inline]
pub fn shrink_to_fit(&mut self) {
if self.len == 0 {
unsafe { heap.free(self.ptr as *mut u8) };
self.cap = 0;
self.ptr = 0 as *mut T;
} else {
unsafe {
// Overflow check is unnecessary as the vector is already at least this large.
let (addr, sz) = heap.realloc(self.ptr as *mut u8, self.len * size_of::<T>());
self.ptr = addr as *mut T;
self.cap = sz;
}
//self.cap = self.len;
}
}
pub fn pop(&mut self) -> Option<T> {
if self.len == 0 {
None
} else {
unsafe {
self.len -= 1;
Some(read_ptr(unchecked_get(self.as_slice(), self.len())))
}
}
}
#[inline]
pub fn push(&mut self, value: T) {
if unlikely!(self.len == self.cap) {
if self.cap == 0 { self.cap += 2 }
let old_size = self.cap * size_of::<T>();
self.cap = self.cap * 2;
let size = old_size * 2;
if old_size > size { out_of_memory() }
unsafe {
let (addr, sz) = heap.realloc(self.ptr as *mut u8, size);
self.ptr = addr as *mut T;
self.cap = sz;
}
}
unsafe {
let end = offset(self.ptr as *T, self.len as int) as *mut T;
move_val_init(&mut *end, value);
self.len += 1;
}
}
pub fn truncate(&mut self, len: uint) {
unsafe {
let mut i = len;
// drop any extra elements
while i < self.len {
read_ptr(unchecked_get(self.as_slice(), i));
i += 1;
}
}
self.len = len;
}
#[inline]
pub fn as_slice<'a>(&'a self) -> &'a [T] {
let slice = Slice { data: self.ptr as *T, len: self.len };
unsafe { transmute(slice) }
}
#[inline]
pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
let slice = Slice { data: self.ptr as *T, len: self.len };
unsafe { transmute(slice) }
}
pub fn move_iter(self) -> MoveItems<T> {
unsafe {
let iter = transmute(iter(self.as_slice()));
let ptr = self.ptr as *mut u8;
forget(self);
MoveItems { allocation: ptr, iter: iter }
}
}
pub unsafe fn set_len(&mut self, len: uint) {
self.len = len;
}
}
impl<T: Clone> Vec<T> {
pub fn from_elem(length: uint, value: T) -> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
while xs.len < length {
move_val_init(unchecked_mut_get(xs.as_mut_slice(), xs.len), value.clone());
xs.len += 1;
}
xs
}
}
pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
unsafe {
let mut xs = Vec::with_capacity(length);
while xs.len < length {
move_val_init(unchecked_mut_get(xs.as_mut_slice(), xs.len), op(xs.len));
xs.len += 1;
}
xs
}
}
}
impl<T> Container for Vec<T> {
#[inline(always)]
fn len(&self) -> uint {
self.len
}
}
#[unsafe_destructor]
impl<T> Drop for Vec<T> {
fn drop(&mut self) {
unsafe {
for x in iter(self.as_mut_slice()) {
read_ptr(x);
}
heap.free(self.ptr as *mut u8)
}
}
}
pub struct MoveItems<T> {
priv allocation: *mut u8, // the block of memory allocated for the vector
priv iter: Items<'static, T>
}
impl<T> Iterator<T> for MoveItems<T> {
fn next(&mut self) -> Option<T> {
unsafe {
self.iter.next().map(|x| read_ptr(x))
}
}
fn size_hint(&self) -> (uint, Option<uint>) {
self.iter.size_hint()
}
}
impl<T> DoubleEndedIterator<T> for MoveItems<T> {
fn next_back(&mut self) -> Option<T> {
unsafe {
self.iter.next_back().map(|x| read_ptr(x))
}
}
}
#[unsafe_destructor]
impl<T> Drop for MoveItems<T> {
fn drop(&mut self) {
// destroy the remaining elements
for _x in *self {}
unsafe {
heap.free(self.allocation)
}
}
}
/*
mod detail {
extern {
pub fn free(ptr: *mut u8);
pub fn realloc(ptr: *mut u8, size: uint) -> *mut u8;
}
}
extern {
fn calloc(nmemb: uint, size: uint) -> *mut u8;
fn malloc(size: uint) -> *mut u8;
}
#[inline(always)]
#[lang = "exchange_free"]
pub unsafe fn free(ptr: *mut u8) {
detail::free(ptr)
}
#[inline]
#[lang = "exchange_malloc"]
pub unsafe fn alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = malloc(size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn zero_alloc(size: uint) -> *mut u8 {
if size == 0 {
0 as *mut u8
} else {
let ptr = alloc(1, size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}
#[inline]
pub unsafe fn realloc(ptr: *mut u8, size: uint) -> *mut u8 {
if size == 0 {
free(ptr);
0 as *mut u8
} else {
let ptr = detail::realloc(ptr, size);
if ptr == 0 as *mut u8 {
out_of_memory()
}
ptr
}
}*/ | with_capacity | identifier_name |
kindck-nonsendable-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
fn foo(_x: @uint) |
fn main() {
let x = @3u;
let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send`
let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send`
let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send`
let _: proc() = proc() foo(x);
}
| {} | identifier_body |
kindck-nonsendable-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | // except according to those terms.
#![feature(managed_boxes)]
fn foo(_x: @uint) {}
fn main() {
let x = @3u;
let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send`
let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send`
let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send`
let _: proc() = proc() foo(x);
} | random_line_split |
|
kindck-nonsendable-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
fn | (_x: @uint) {}
fn main() {
let x = @3u;
let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send`
let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send`
let _: proc():Send = proc() foo(x); //~ ERROR does not fulfill `Send`
let _: proc() = proc() foo(x);
}
| foo | identifier_name |
lib.rs | //! The purpose of this library is to provide an OpenGL context on as many
//! platforms as possible.
//!
//! # Building a window
//!
//! There are two ways to create a window:
//!
//! - Calling `Window::new()`.
//! - Calling `let builder = WindowBuilder::new()` then `builder.build()`.
//!
//! The first way is the simpliest way and will give you default values.
//!
//! The second way allows you to customize the way your window and GL context
//! will look and behave.
//!
//! # Features
//!
//! This crate has two Cargo features: `window` and `headless`.
//!
//! - `window` allows you to create regular windows and enables the `WindowBuilder` object.
//! - `headless` allows you to do headless rendering, and enables
//! the `HeadlessRendererBuilder` object.
//!
//! By default only `window` is enabled.
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate shared_library;
extern crate libc;
extern crate winit;
#[cfg(target_os = "windows")]
extern crate winapi;
#[cfg(target_os = "windows")]
extern crate kernel32;
#[cfg(target_os = "windows")]
extern crate shell32;
#[cfg(target_os = "windows")]
extern crate gdi32;
#[cfg(target_os = "windows")]
extern crate user32;
#[cfg(target_os = "windows")]
extern crate dwmapi;
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[macro_use]
extern crate objc;
#[cfg(target_os = "macos")]
extern crate cgl;
#[cfg(target_os = "macos")]
extern crate cocoa;
#[cfg(target_os = "macos")]
extern crate core_foundation;
#[cfg(target_os = "macos")]
extern crate core_graphics;
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
extern crate x11_dl;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
#[macro_use(wayland_env)]
extern crate wayland_client;
pub use events::*;
pub use headless::{HeadlessRendererBuilder, HeadlessContext};
pub use window::{AvailableMonitorsIter, MonitorId, WindowId, get_available_monitors, get_primary_monitor};
pub use winit::NativeMonitorId;
use std::io;
mod api;
mod platform;
mod events;
mod headless;
mod window;
pub mod os;
/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```ignore
/// let window = Window::new(&events_loop).unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
/// events_loop.poll_events(|event| {
/// match(event) {
/// // process events here
/// _ => ()
/// }
/// });
///
/// // draw everything here
///
/// window.swap_buffers();
/// std::thread::sleep(std::time::Duration::from_millis(17));
/// }
/// ```
pub struct Window {
window: platform::Window,
}
/// Object that allows you to build windows.
#[derive(Clone)]
pub struct WindowBuilder<'a> {
winit_builder: winit::WindowBuilder,
/// The attributes to use to create the context.
pub opengl: GlAttributes<&'a platform::Window>,
// Should be made public once it's stabilized.
pf_reqs: PixelFormatRequirements,
}
/// Provides a way to retreive events from the windows that are registered to it.
// TODO: document usage in multiple threads
pub struct EventsLoop {
events_loop: platform::EventsLoop,
}
impl EventsLoop {
/// Builds a new events loop.
pub fn new() -> EventsLoop {
EventsLoop {
events_loop: platform::EventsLoop::new(),
}
}
/// Fetches all the events that are pending, calls the callback function for each of them,
/// and returns.
#[inline]
pub fn poll_events<F>(&self, callback: F)
where F: FnMut(Event)
{
self.events_loop.poll_events(callback)
}
/// Runs forever until `interrupt()` is called. Whenever an event happens, calls the callback.
#[inline]
pub fn run_forever<F>(&self, callback: F)
where F: FnMut(Event)
{
self.events_loop.run_forever(callback)
}
/// If we called `run_forever()`, stops the process of waiting for events.
#[inline]
pub fn interrupt(&self) {
self.events_loop.interrupt()
}
}
/// Trait that describes objects that have access to an OpenGL context.
pub trait GlContext {
/// Sets the context as the current context.
unsafe fn make_current(&self) -> Result<(), ContextError>;
/// Returns true if this context is the current one in this thread.
fn is_current(&self) -> bool;
/// Returns the address of an OpenGL function.
fn get_proc_address(&self, addr: &str) -> *const ();
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
fn swap_buffers(&self) -> Result<(), ContextError>;
/// Returns the OpenGL API being used.
fn get_api(&self) -> Api;
/// Returns the pixel format of the main framebuffer of the context.
fn get_pixel_format(&self) -> PixelFormat;
}
/// Error that can happen while creating a window or a headless renderer.
#[derive(Debug)]
pub enum CreationError {
OsError(String),
/// TODO: remove this error
NotSupported,
NoBackendAvailable(Box<std::error::Error + Send>),
RobustnessNotSupported,
OpenGlVersionNotSupported,
NoAvailablePixelFormat,
}
impl CreationError {
fn to_string(&self) -> &str {
match *self {
CreationError::OsError(ref text) => &text,
CreationError::NotSupported => "Some of the requested attributes are not supported",
CreationError::NoBackendAvailable(_) => "No backend is available",
CreationError::RobustnessNotSupported => "You requested robustness, but it is \
not supported.",
CreationError::OpenGlVersionNotSupported => "The requested OpenGL version is not \
supported.",
CreationError::NoAvailablePixelFormat => "Couldn't find any pixel format that matches \
the criterias.",
}
}
}
impl std::fmt::Display for CreationError {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
formatter.write_str(self.to_string())?;
if let Some(err) = std::error::Error::cause(self) {
write!(formatter, ": {}", err)?;
}
Ok(())
}
}
impl std::error::Error for CreationError {
fn description(&self) -> &str |
fn cause(&self) -> Option<&std::error::Error> {
match *self {
CreationError::NoBackendAvailable(ref err) => Some(&**err),
_ => None
}
}
}
/// Error that can happen when manipulating an OpenGL context.
#[derive(Debug)]
pub enum ContextError {
IoError(io::Error),
ContextLost,
}
impl ContextError {
fn to_string(&self) -> &str {
use std::error::Error;
match *self {
ContextError::IoError(ref err) => err.description(),
ContextError::ContextLost => "Context lost"
}
}
}
impl std::fmt::Display for ContextError {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
formatter.write_str(self.to_string())
}
}
impl std::error::Error for ContextError {
fn description(&self) -> &str {
self.to_string()
}
}
/// All APIs related to OpenGL that you can possibly get while using glutin.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Api {
/// The classical OpenGL. Available on Windows, Linux, OS/X.
OpenGl,
/// OpenGL embedded system. Available on Linux, Android.
OpenGlEs,
/// OpenGL for the web. Very similar to OpenGL ES.
WebGl,
}
/// Describes the requested OpenGL context profiles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlProfile {
/// Include all the immediate more functions and definitions.
Compatibility,
/// Include all the future-compatible functions and definitions.
Core,
}
/// Describes the OpenGL API and version that are being requested when a context is created.
#[derive(Debug, Copy, Clone)]
pub enum GlRequest {
/// Request the latest version of the "best" API of this platform.
///
/// On desktop, will try OpenGL.
Latest,
/// Request a specific version of a specific API.
///
/// Example: `GlRequest::Specific(Api::OpenGl, (3, 3))`.
Specific(Api, (u8, u8)),
/// If OpenGL is available, create an OpenGL context with the specified `opengl_version`.
/// Else if OpenGL ES or WebGL is available, create a context with the
/// specified `opengles_version`.
GlThenGles {
/// The version to use for OpenGL.
opengl_version: (u8, u8),
/// The version to use for OpenGL ES.
opengles_version: (u8, u8),
},
}
impl GlRequest {
/// Extract the desktop GL version, if any.
pub fn to_gl_version(&self) -> Option<(u8, u8)> {
match self {
&GlRequest::Specific(Api::OpenGl, version) => Some(version),
&GlRequest::GlThenGles { opengl_version: version,.. } => Some(version),
_ => None,
}
}
}
/// The minimum core profile GL context. Useful for getting the minimum
/// required GL version while still running on OSX, which often forbids
/// the compatibility profile features.
pub static GL_CORE: GlRequest = GlRequest::Specific(Api::OpenGl, (3, 2));
/// Specifies the tolerance of the OpenGL context to faults. If you accept raw OpenGL commands
/// and/or raw shader code from an untrusted source, you should definitely care about this.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Robustness {
/// Not everything is checked. Your application can crash if you do something wrong with your
/// shaders.
NotRobust,
/// The driver doesn't check anything. This option is very dangerous. Please know what you're
/// doing before using it. See the `GL_KHR_no_error` extension.
///
/// Since this option is purely an optimisation, no error will be returned if the backend
/// doesn't support it. Instead it will automatically fall back to `NotRobust`.
NoError,
/// Everything is checked to avoid any crash. The driver will attempt to avoid any problem,
/// but if a problem occurs the behavior is implementation-defined. You are just guaranteed not
/// to get a crash.
RobustNoResetNotification,
/// Same as `RobustNoResetNotification` but the context creation doesn't fail if it's not
/// supported.
TryRobustNoResetNotification,
/// Everything is checked to avoid any crash. If a problem occurs, the context will enter a
/// "context lost" state. It must then be recreated. For the moment, glutin doesn't provide a
/// way to recreate a context with the same window :-/
RobustLoseContextOnReset,
/// Same as `RobustLoseContextOnReset` but the context creation doesn't fail if it's not
/// supported.
TryRobustLoseContextOnReset,
}
/// The behavior of the driver when you change the current context.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ReleaseBehavior {
/// Doesn't do anything. Most notably doesn't flush.
None,
/// Flushes the context that was previously current as if `glFlush` was called.
Flush,
}
pub use winit::MouseCursor;
pub use winit::CursorState;
/// Describes a possible format. Unused.
#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub struct PixelFormat {
pub hardware_accelerated: bool,
pub color_bits: u8,
pub alpha_bits: u8,
pub depth_bits: u8,
pub stencil_bits: u8,
pub stereoscopy: bool,
pub double_buffer: bool,
pub multisampling: Option<u16>,
pub srgb: bool,
}
/// Describes how the backend should choose a pixel format.
// TODO: swap method? (swap, copy)
#[derive(Clone, Debug)]
pub struct PixelFormatRequirements {
/// If true, only hardware-accelerated formats will be conisdered. If false, only software
/// renderers. `None` means "don't care". Default is `Some(true)`.
pub hardware_accelerated: Option<bool>,
/// Minimum number of bits for the color buffer, excluding alpha. `None` means "don't care".
/// The default is `Some(24)`.
pub color_bits: Option<u8>,
/// If true, the color buffer must be in a floating point format. Default is `false`.
///
/// Using floating points allows you to write values outside of the `[0.0, 1.0]` range.
pub float_color_buffer: bool,
/// Minimum number of bits for the alpha in the color buffer. `None` means "don't care".
/// The default is `Some(8)`.
pub alpha_bits: Option<u8>,
/// Minimum number of bits for the depth buffer. `None` means "don't care".
/// The default value is `Some(24)`.
pub depth_bits: Option<u8>,
/// Minimum number of bits for the depth buffer. `None` means "don't care".
/// The default value is `Some(8)`.
pub stencil_bits: Option<u8>,
/// If true, only double-buffered formats will be considered. If false, only single-buffer
/// formats. `None` means "don't care". The default is `Some(true)`.
pub double_buffer: Option<bool>,
/// Contains the minimum number of samples per pixel in the color, depth and stencil buffers.
/// `None` means "don't care". Default is `None`.
/// A value of `Some(0)` indicates that multisampling must not be enabled.
pub multisampling: Option<u16>,
/// If true, only stereoscopic formats will be considered. If false, only non-stereoscopic
/// formats. The default is `false`.
pub stereoscopy: bool,
/// If true, only sRGB-capable formats will be considered. If false, don't care.
/// The default is `false`.
pub srgb: bool,
/// The behavior when changing the current context. Default is `Flush`.
pub release_behavior: ReleaseBehavior,
}
impl Default for PixelFormatRequirements {
#[inline]
fn default() -> PixelFormatRequirements {
PixelFormatRequirements {
hardware_accelerated: Some(true),
color_bits: Some(24),
float_color_buffer: false,
alpha_bits: Some(8),
depth_bits: Some(24),
stencil_bits: Some(8),
double_buffer: None,
multisampling: None,
stereoscopy: false,
srgb: false,
release_behavior: ReleaseBehavior::Flush,
}
}
}
pub use winit::WindowAttributes; // TODO
/// Attributes to use when creating an OpenGL context.
#[derive(Clone)]
pub struct GlAttributes<S> {
/// An existing context to share the new the context with.
///
/// The default is `None`.
pub sharing: Option<S>,
/// Version to try create. See `GlRequest` for more infos.
///
/// The default is `Latest`.
pub version: GlRequest,
/// OpenGL profile to use.
///
/// The default is `None`.
pub profile: Option<GlProfile>,
/// Whether to enable the `debug` flag of the context.
///
/// Debug contexts are usually slower but give better error reporting.
///
/// The default is `true` in debug mode and `false` in release mode.
pub debug: bool,
/// How the OpenGL context should detect errors.
///
/// The default is `NotRobust` because this is what is typically expected when you create an
/// OpenGL context. However for safety you should consider `TryRobustLoseContextOnReset`.
pub robustness: Robustness,
/// Whether to use vsync. If vsync is enabled, calling `swap_buffers` will block until the
/// screen refreshes. This is typically used to prevent screen tearing.
///
/// The default is `false`.
pub vsync: bool,
}
impl<S> GlAttributes<S> {
/// Turns the `sharing` parameter into another type by calling a closure.
#[inline]
pub fn map_sharing<F, T>(self, f: F) -> GlAttributes<T> where F: FnOnce(S) -> T {
GlAttributes {
sharing: self.sharing.map(f),
version: self.version,
profile: self.profile,
debug: self.debug,
robustness: self.robustness,
vsync: self.vsync,
}
}
}
impl<S> Default for GlAttributes<S> {
#[inline]
fn default() -> GlAttributes<S> {
GlAttributes {
sharing: None,
version: GlRequest::Latest,
profile: None,
debug: cfg!(debug_assertions),
robustness: Robustness::NotRobust,
vsync: false,
}
}
}
| {
self.to_string()
} | identifier_body |
lib.rs | //! The purpose of this library is to provide an OpenGL context on as many
//! platforms as possible.
//!
//! # Building a window
//!
//! There are two ways to create a window:
//!
//! - Calling `Window::new()`.
//! - Calling `let builder = WindowBuilder::new()` then `builder.build()`.
//!
//! The first way is the simpliest way and will give you default values.
//!
//! The second way allows you to customize the way your window and GL context
//! will look and behave.
//!
//! # Features
//!
//! This crate has two Cargo features: `window` and `headless`.
//!
//! - `window` allows you to create regular windows and enables the `WindowBuilder` object.
//! - `headless` allows you to do headless rendering, and enables
//! the `HeadlessRendererBuilder` object.
//!
//! By default only `window` is enabled.
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate shared_library;
extern crate libc;
extern crate winit;
#[cfg(target_os = "windows")]
extern crate winapi;
#[cfg(target_os = "windows")]
extern crate kernel32;
#[cfg(target_os = "windows")]
extern crate shell32;
#[cfg(target_os = "windows")]
extern crate gdi32;
#[cfg(target_os = "windows")]
extern crate user32;
#[cfg(target_os = "windows")]
extern crate dwmapi;
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[macro_use]
extern crate objc;
#[cfg(target_os = "macos")]
extern crate cgl;
#[cfg(target_os = "macos")]
extern crate cocoa;
#[cfg(target_os = "macos")]
extern crate core_foundation;
#[cfg(target_os = "macos")]
extern crate core_graphics;
#[cfg(any(target_os = "linux", target_os = "dragonfly", target_os = "freebsd", target_os = "openbsd"))]
extern crate x11_dl;
#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "openbsd"))]
#[macro_use(wayland_env)]
extern crate wayland_client;
pub use events::*;
pub use headless::{HeadlessRendererBuilder, HeadlessContext};
pub use window::{AvailableMonitorsIter, MonitorId, WindowId, get_available_monitors, get_primary_monitor};
pub use winit::NativeMonitorId;
use std::io;
mod api;
mod platform;
mod events;
mod headless;
mod window;
pub mod os;
/// Represents an OpenGL context and the Window or environment around it.
///
/// # Example
///
/// ```ignore
/// let window = Window::new(&events_loop).unwrap();
///
/// unsafe { window.make_current() };
///
/// loop {
/// events_loop.poll_events(|event| {
/// match(event) {
/// // process events here
/// _ => ()
/// }
/// });
///
/// // draw everything here
///
/// window.swap_buffers();
/// std::thread::sleep(std::time::Duration::from_millis(17));
/// }
/// ```
pub struct Window {
window: platform::Window,
}
/// Object that allows you to build windows.
#[derive(Clone)]
pub struct | <'a> {
winit_builder: winit::WindowBuilder,
/// The attributes to use to create the context.
pub opengl: GlAttributes<&'a platform::Window>,
// Should be made public once it's stabilized.
pf_reqs: PixelFormatRequirements,
}
/// Provides a way to retreive events from the windows that are registered to it.
// TODO: document usage in multiple threads
pub struct EventsLoop {
events_loop: platform::EventsLoop,
}
impl EventsLoop {
/// Builds a new events loop.
pub fn new() -> EventsLoop {
EventsLoop {
events_loop: platform::EventsLoop::new(),
}
}
/// Fetches all the events that are pending, calls the callback function for each of them,
/// and returns.
#[inline]
pub fn poll_events<F>(&self, callback: F)
where F: FnMut(Event)
{
self.events_loop.poll_events(callback)
}
/// Runs forever until `interrupt()` is called. Whenever an event happens, calls the callback.
#[inline]
pub fn run_forever<F>(&self, callback: F)
where F: FnMut(Event)
{
self.events_loop.run_forever(callback)
}
/// If we called `run_forever()`, stops the process of waiting for events.
#[inline]
pub fn interrupt(&self) {
self.events_loop.interrupt()
}
}
/// Trait that describes objects that have access to an OpenGL context.
pub trait GlContext {
/// Sets the context as the current context.
unsafe fn make_current(&self) -> Result<(), ContextError>;
/// Returns true if this context is the current one in this thread.
fn is_current(&self) -> bool;
/// Returns the address of an OpenGL function.
fn get_proc_address(&self, addr: &str) -> *const ();
/// Swaps the buffers in case of double or triple buffering.
///
/// You should call this function every time you have finished rendering, or the image
/// may not be displayed on the screen.
///
/// **Warning**: if you enabled vsync, this function will block until the next time the screen
/// is refreshed. However drivers can choose to override your vsync settings, which means that
/// you can't know in advance whether `swap_buffers` will block or not.
fn swap_buffers(&self) -> Result<(), ContextError>;
/// Returns the OpenGL API being used.
fn get_api(&self) -> Api;
/// Returns the pixel format of the main framebuffer of the context.
fn get_pixel_format(&self) -> PixelFormat;
}
/// Error that can happen while creating a window or a headless renderer.
#[derive(Debug)]
pub enum CreationError {
OsError(String),
/// TODO: remove this error
NotSupported,
NoBackendAvailable(Box<std::error::Error + Send>),
RobustnessNotSupported,
OpenGlVersionNotSupported,
NoAvailablePixelFormat,
}
impl CreationError {
fn to_string(&self) -> &str {
match *self {
CreationError::OsError(ref text) => &text,
CreationError::NotSupported => "Some of the requested attributes are not supported",
CreationError::NoBackendAvailable(_) => "No backend is available",
CreationError::RobustnessNotSupported => "You requested robustness, but it is \
not supported.",
CreationError::OpenGlVersionNotSupported => "The requested OpenGL version is not \
supported.",
CreationError::NoAvailablePixelFormat => "Couldn't find any pixel format that matches \
the criterias.",
}
}
}
impl std::fmt::Display for CreationError {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
formatter.write_str(self.to_string())?;
if let Some(err) = std::error::Error::cause(self) {
write!(formatter, ": {}", err)?;
}
Ok(())
}
}
impl std::error::Error for CreationError {
fn description(&self) -> &str {
self.to_string()
}
fn cause(&self) -> Option<&std::error::Error> {
match *self {
CreationError::NoBackendAvailable(ref err) => Some(&**err),
_ => None
}
}
}
/// Error that can happen when manipulating an OpenGL context.
#[derive(Debug)]
pub enum ContextError {
IoError(io::Error),
ContextLost,
}
impl ContextError {
fn to_string(&self) -> &str {
use std::error::Error;
match *self {
ContextError::IoError(ref err) => err.description(),
ContextError::ContextLost => "Context lost"
}
}
}
impl std::fmt::Display for ContextError {
fn fmt(&self, formatter: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
formatter.write_str(self.to_string())
}
}
impl std::error::Error for ContextError {
fn description(&self) -> &str {
self.to_string()
}
}
/// All APIs related to OpenGL that you can possibly get while using glutin.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Api {
/// The classical OpenGL. Available on Windows, Linux, OS/X.
OpenGl,
/// OpenGL embedded system. Available on Linux, Android.
OpenGlEs,
/// OpenGL for the web. Very similar to OpenGL ES.
WebGl,
}
/// Describes the requested OpenGL context profiles.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlProfile {
/// Include all the immediate more functions and definitions.
Compatibility,
/// Include all the future-compatible functions and definitions.
Core,
}
/// Describes the OpenGL API and version that are being requested when a context is created.
#[derive(Debug, Copy, Clone)]
pub enum GlRequest {
/// Request the latest version of the "best" API of this platform.
///
/// On desktop, will try OpenGL.
Latest,
/// Request a specific version of a specific API.
///
/// Example: `GlRequest::Specific(Api::OpenGl, (3, 3))`.
Specific(Api, (u8, u8)),
/// If OpenGL is available, create an OpenGL context with the specified `opengl_version`.
/// Else if OpenGL ES or WebGL is available, create a context with the
/// specified `opengles_version`.
GlThenGles {
/// The version to use for OpenGL.
opengl_version: (u8, u8),
/// The version to use for OpenGL ES.
opengles_version: (u8, u8),
},
}
impl GlRequest {
/// Extract the desktop GL version, if any.
pub fn to_gl_version(&self) -> Option<(u8, u8)> {
match self {
&GlRequest::Specific(Api::OpenGl, version) => Some(version),
&GlRequest::GlThenGles { opengl_version: version,.. } => Some(version),
_ => None,
}
}
}
/// The minimum core profile GL context. Useful for getting the minimum
/// required GL version while still running on OSX, which often forbids
/// the compatibility profile features.
pub static GL_CORE: GlRequest = GlRequest::Specific(Api::OpenGl, (3, 2));
/// Specifies the tolerance of the OpenGL context to faults. If you accept raw OpenGL commands
/// and/or raw shader code from an untrusted source, you should definitely care about this.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Robustness {
/// Not everything is checked. Your application can crash if you do something wrong with your
/// shaders.
NotRobust,
/// The driver doesn't check anything. This option is very dangerous. Please know what you're
/// doing before using it. See the `GL_KHR_no_error` extension.
///
/// Since this option is purely an optimisation, no error will be returned if the backend
/// doesn't support it. Instead it will automatically fall back to `NotRobust`.
NoError,
/// Everything is checked to avoid any crash. The driver will attempt to avoid any problem,
/// but if a problem occurs the behavior is implementation-defined. You are just guaranteed not
/// to get a crash.
RobustNoResetNotification,
/// Same as `RobustNoResetNotification` but the context creation doesn't fail if it's not
/// supported.
TryRobustNoResetNotification,
/// Everything is checked to avoid any crash. If a problem occurs, the context will enter a
/// "context lost" state. It must then be recreated. For the moment, glutin doesn't provide a
/// way to recreate a context with the same window :-/
RobustLoseContextOnReset,
/// Same as `RobustLoseContextOnReset` but the context creation doesn't fail if it's not
/// supported.
TryRobustLoseContextOnReset,
}
/// The behavior of the driver when you change the current context.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum ReleaseBehavior {
/// Doesn't do anything. Most notably doesn't flush.
None,
/// Flushes the context that was previously current as if `glFlush` was called.
Flush,
}
pub use winit::MouseCursor;
pub use winit::CursorState;
/// Describes a possible format. Unused.
#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub struct PixelFormat {
pub hardware_accelerated: bool,
pub color_bits: u8,
pub alpha_bits: u8,
pub depth_bits: u8,
pub stencil_bits: u8,
pub stereoscopy: bool,
pub double_buffer: bool,
pub multisampling: Option<u16>,
pub srgb: bool,
}
/// Describes how the backend should choose a pixel format.
// TODO: swap method? (swap, copy)
#[derive(Clone, Debug)]
pub struct PixelFormatRequirements {
/// If true, only hardware-accelerated formats will be conisdered. If false, only software
/// renderers. `None` means "don't care". Default is `Some(true)`.
pub hardware_accelerated: Option<bool>,
/// Minimum number of bits for the color buffer, excluding alpha. `None` means "don't care".
/// The default is `Some(24)`.
pub color_bits: Option<u8>,
/// If true, the color buffer must be in a floating point format. Default is `false`.
///
/// Using floating points allows you to write values outside of the `[0.0, 1.0]` range.
pub float_color_buffer: bool,
/// Minimum number of bits for the alpha in the color buffer. `None` means "don't care".
/// The default is `Some(8)`.
pub alpha_bits: Option<u8>,
/// Minimum number of bits for the depth buffer. `None` means "don't care".
/// The default value is `Some(24)`.
pub depth_bits: Option<u8>,
/// Minimum number of bits for the depth buffer. `None` means "don't care".
/// The default value is `Some(8)`.
pub stencil_bits: Option<u8>,
/// If true, only double-buffered formats will be considered. If false, only single-buffer
/// formats. `None` means "don't care". The default is `Some(true)`.
pub double_buffer: Option<bool>,
/// Contains the minimum number of samples per pixel in the color, depth and stencil buffers.
/// `None` means "don't care". Default is `None`.
/// A value of `Some(0)` indicates that multisampling must not be enabled.
pub multisampling: Option<u16>,
/// If true, only stereoscopic formats will be considered. If false, only non-stereoscopic
/// formats. The default is `false`.
pub stereoscopy: bool,
/// If true, only sRGB-capable formats will be considered. If false, don't care.
/// The default is `false`.
pub srgb: bool,
/// The behavior when changing the current context. Default is `Flush`.
pub release_behavior: ReleaseBehavior,
}
impl Default for PixelFormatRequirements {
#[inline]
fn default() -> PixelFormatRequirements {
PixelFormatRequirements {
hardware_accelerated: Some(true),
color_bits: Some(24),
float_color_buffer: false,
alpha_bits: Some(8),
depth_bits: Some(24),
stencil_bits: Some(8),
double_buffer: None,
multisampling: None,
stereoscopy: false,
srgb: false,
release_behavior: ReleaseBehavior::Flush,
}
}
}
pub use winit::WindowAttributes; // TODO
/// Attributes to use when creating an OpenGL context.
#[derive(Clone)]
pub struct GlAttributes<S> {
/// An existing context to share the new the context with.
///
/// The default is `None`.
pub sharing: Option<S>,
/// Version to try create. See `GlRequest` for more infos.
///
/// The default is `Latest`.
pub version: GlRequest,
/// OpenGL profile to use.
///
/// The default is `None`.
pub profile: Option<GlProfile>,
/// Whether to enable the `debug` flag of the context.
///
/// Debug contexts are usually slower but give better error reporting.
///
/// The default is `true` in debug mode and `false` in release mode.
pub debug: bool,
/// How the OpenGL context should detect errors.
///
/// The default is `NotRobust` because this is what is typically expected when you create an
/// OpenGL context. However for safety you should consider `TryRobustLoseContextOnReset`.
pub robustness: Robustness,
/// Whether to use vsync. If vsync is enabled, calling `swap_buffers` will block until the
/// screen refreshes. This is typically used to prevent screen tearing.
///
/// The default is `false`.
pub vsync: bool,
}
impl<S> GlAttributes<S> {
/// Turns the `sharing` parameter into another type by calling a closure.
#[inline]
pub fn map_sharing<F, T>(self, f: F) -> GlAttributes<T> where F: FnOnce(S) -> T {
GlAttributes {
sharing: self.sharing.map(f),
version: self.version,
profile: self.profile,
debug: self.debug,
robustness: self.robustness,
vsync: self.vsync,
}
}
}
impl<S> Default for GlAttributes<S> {
#[inline]
fn default() -> GlAttributes<S> {
GlAttributes {
sharing: None,
version: GlRequest::Latest,
profile: None,
debug: cfg!(debug_assertions),
robustness: Robustness::NotRobust,
vsync: false,
}
}
}
| WindowBuilder | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.