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 |
---|---|---|---|---|
lib.rs | //! # Getting started
//!
//! ```rust,no_run
//! extern crate sdl2;
//!
//! use sdl2::pixels::Color;
//! use sdl2::event::Event;
//! use sdl2::keyboard::Keycode;
//! use std::time::Duration;
//!
//! pub fn main() {
//! let sdl_context = sdl2::init().unwrap();
//! let video_subsystem = sdl_context.video().unwrap();
//!
//! let window = video_subsystem.window("rust-sdl2 demo", 800, 600)
//! .position_centered()
//! .build()
//! .unwrap();
//!
//! let mut canvas = window.into_canvas().build().unwrap();
//!
//! canvas.set_draw_color(Color::RGB(0, 255, 255));
//! canvas.clear();
//! canvas.present();
//! let mut event_pump = sdl_context.event_pump().unwrap();
//! let mut i = 0;
//! 'running: loop {
//! i = (i + 1) % 255;
//! canvas.set_draw_color(Color::RGB(i, 64, 255 - i));
//! canvas.clear();
//! for event in event_pump.poll_iter() {
//! match event {
//! Event::Quit {..} |
//! Event::KeyDown { keycode: Some(Keycode::Escape),.. } => {
//! break 'running
//! },
//! _ => {}
//! }
//! }
//! // The rest of the game loop goes here...
//!
//! canvas.present();
//! ::std::thread::sleep(Duration::new(0, 1_000_000_000u32 / 60));
//! }
//! }
//! ```
#![crate_name = "sdl2"]
#![crate_type = "lib"]
#![allow(clippy::cast_lossless, clippy::transmute_ptr_to_ref)]
pub extern crate libc;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate bitflags;
pub extern crate sdl2_sys as sys; | pub use crate::sdl::*;
pub mod clipboard;
pub mod cpuinfo;
#[macro_use]
mod macros;
pub mod audio;
pub mod controller;
pub mod event;
pub mod filesystem;
pub mod haptic;
pub mod hint;
pub mod joystick;
pub mod keyboard;
pub mod log;
pub mod messagebox;
pub mod mouse;
pub mod pixels;
pub mod rect;
pub mod render;
pub mod rwops;
mod sdl;
pub mod surface;
pub mod timer;
pub mod touch;
pub mod version;
pub mod video;
// modules
#[cfg(feature = "gfx")]
pub mod gfx;
#[cfg(feature = "image")]
pub mod image;
#[cfg(feature = "mixer")]
pub mod mixer;
#[cfg(feature = "ttf")]
pub mod ttf;
mod common;
// Export return types and such from the common module.
pub use crate::common::IntegerOrSdlError;
#[cfg(feature = "raw-window-handle")]
pub mod raw_window_handle; |
#[cfg(feature = "gfx")]
extern crate c_vec;
| random_line_split |
mod.rs | extern crate bip_metainfo;
extern crate bip_disk;
extern crate bip_util;
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate rand;
use std::collections::HashMap;
use std::io::{self};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Arc};
use std::cmp;
use std::time::Duration;
use bip_disk::{FileSystem, IDiskMessage, BlockMetadata, BlockMut};
use bip_metainfo::{IntoAccessor, Accessor, PieceAccess};
use bip_util::bt::InfoHash;
use bytes::BytesMut;
use rand::Rng;
use tokio_core::reactor::{Core, Timeout};
use futures::future::{self, Loop, Future};
use futures::stream::Stream;
use futures::sink::{Sink, Wait};
mod add_torrent;
mod disk_manager_send_backpressure;
mod complete_torrent;
mod load_block;
mod process_block;
mod remove_torrent;
mod resume_torrent;
/// Generate buffer of size random bytes.
fn random_buffer(size: usize) -> Vec<u8> {
let mut buffer = vec![0u8; size];
let mut rng = rand::weak_rng();
for i in 0..size {
buffer[i] = rng.gen();
}
buffer
}
/// Initiate a core loop with the given timeout, state, and closure.
///
/// Returns R or panics if an error occurred in the loop (including a timeout).
fn core_loop_with_timeout<I, S, F, R>(core: &mut Core, timeout_ms: u64, state: (I, S), call: F) -> R
where F: FnMut(I, S, S::Item) -> Loop<R, (I, S)>,
S: Stream {
let timeout = Timeout::new(Duration::from_millis(timeout_ms), &core.handle())
.unwrap()
.then(|_| Err(()));
// Have to stick the call in our init state so that we transfer ownership between loops
core.run(
future::loop_fn((call, state), |(mut call, (init, stream))| {
stream.into_future()
.map(|(opt_msg, stream)| {
let msg = opt_msg
.unwrap_or_else(|| panic!("End Of Stream Reached"));
match call(init, stream, msg) {
Loop::Continue((init, stream)) => Loop::Continue((call, (init, stream))),
Loop::Break(ret) => Loop::Break(ret)
}
})
})
.map_err(|_| ())
.select(timeout)
.map(|(item, _)| item)
).unwrap_or_else(|_| panic!("Core Loop Timed Out"))
}
/// Send block with the given metadata and entire data given.
fn send_block<S, M>(blocking_send: &mut Wait<S>, data: &[u8], hash: InfoHash, piece_index: u64, block_offset: u64, block_len: usize, modify: M)
where S: Sink<SinkItem=IDiskMessage>, M: Fn(&mut [u8]) {
let mut bytes = BytesMut::new();
bytes.extend_from_slice(data);
let mut block = BlockMut::new(BlockMetadata::new(hash, piece_index, block_offset, block_len), bytes);
modify(&mut block[..]);
blocking_send.send(IDiskMessage::ProcessBlock(block.into())).unwrap_or_else(|_| panic!("Failed To Send Process Block Message"));
}
//----------------------------------------------------------------------------//
/// Allow us to mock out multi file torrents.
struct MultiFileDirectAccessor {
dir: PathBuf,
files: Vec<(Vec<u8>, PathBuf)>
}
impl MultiFileDirectAccessor {
pub fn new(dir: PathBuf, files: Vec<(Vec<u8>, PathBuf)>) -> MultiFileDirectAccessor {
MultiFileDirectAccessor{ dir: dir, files: files }
}
}
// TODO: Ugh, once specialization lands, we can see about having a default impl for IntoAccessor
impl IntoAccessor for MultiFileDirectAccessor {
type Accessor = MultiFileDirectAccessor;
fn into_accessor(self) -> io::Result<MultiFileDirectAccessor> {
Ok(self)
}
}
impl Accessor for MultiFileDirectAccessor {
fn access_directory(&self) -> Option<&Path> {
// Do not just return the option here, unwrap it and put it in
// another Option (since we know this is a multi file torrent)
Some(self.dir.as_ref())
}
fn access_metadata<C>(&self, mut callback: C) -> io::Result<()>
where C: FnMut(u64, &Path) {
for &(ref buffer, ref path) in self.files.iter() {
callback(buffer.len() as u64, &*path)
}
Ok(())
}
fn access_pieces<C>(&self, mut callback: C) -> io::Result<()>
where C: for<'a> FnMut(PieceAccess<'a>) -> io::Result<()> {
for &(ref buffer, _) in self.files.iter() {
try!(callback(PieceAccess::Compute(&mut &buffer[..])))
}
Ok(())
}
}
//----------------------------------------------------------------------------//
/// Allow us to mock out the file system.
#[derive(Clone)]
struct InMemoryFileSystem {
files: Arc<Mutex<HashMap<PathBuf, Vec<u8>>>>
}
impl InMemoryFileSystem {
pub fn new() -> InMemoryFileSystem {
InMemoryFileSystem{ files: Arc::new(Mutex::new(HashMap::new())) }
}
pub fn run_with_lock<C, R>(&self, call: C) -> R
where C: FnOnce(&mut HashMap<PathBuf, Vec<u8>>) -> R {
let mut lock_files = self.files.lock().unwrap();
call(&mut *lock_files)
}
}
struct InMemoryFile {
path: PathBuf
} | impl FileSystem for InMemoryFileSystem {
type File = InMemoryFile;
fn open_file<P>(&self, path: P) -> io::Result<Self::File>
where P: AsRef<Path> + Send +'static {
let file_path = path.as_ref().to_path_buf();
self.run_with_lock(|files| {
if!files.contains_key(&file_path) {
files.insert(file_path.clone(), Vec::new());
}
});
Ok(InMemoryFile{ path: file_path })
}
fn sync_file<P>(&self, _path: P) -> io::Result<()>
where P: AsRef<Path> + Send +'static {
Ok(())
}
fn file_size(&self, file: &Self::File) -> io::Result<u64> {
self.run_with_lock(|files| {
files.get(&file.path)
.map(|file| file.len() as u64)
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
fn read_file(&self, file: &mut Self::File, offset: u64, buffer: &mut [u8]) -> io::Result<usize> {
self.run_with_lock(|files| {
files.get(&file.path)
.map(|file_buffer| {
let cast_offset = offset as usize;
let bytes_to_copy = cmp::min(file_buffer.len() - cast_offset, buffer.len());
let bytes = &file_buffer[cast_offset..(bytes_to_copy + cast_offset)];
buffer.clone_from_slice(bytes);
bytes_to_copy
})
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
fn write_file(&self, file: &mut Self::File, offset: u64, buffer: &[u8]) -> io::Result<usize> {
self.run_with_lock(|files| {
files.get_mut(&file.path)
.map(|file_buffer| {
let cast_offset = offset as usize;
let last_byte_pos = cast_offset + buffer.len();
if last_byte_pos > file_buffer.len() {
file_buffer.resize(last_byte_pos, 0);
}
let bytes_to_copy = cmp::min(file_buffer.len() - cast_offset, buffer.len());
if bytes_to_copy!= 0 {
file_buffer[cast_offset..(cast_offset + bytes_to_copy)].clone_from_slice(buffer);
}
// TODO: If the file is full, this will return zero, we should also simulate io::ErrorKind::WriteZero
bytes_to_copy
})
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
} | random_line_split |
|
mod.rs | extern crate bip_metainfo;
extern crate bip_disk;
extern crate bip_util;
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate rand;
use std::collections::HashMap;
use std::io::{self};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Arc};
use std::cmp;
use std::time::Duration;
use bip_disk::{FileSystem, IDiskMessage, BlockMetadata, BlockMut};
use bip_metainfo::{IntoAccessor, Accessor, PieceAccess};
use bip_util::bt::InfoHash;
use bytes::BytesMut;
use rand::Rng;
use tokio_core::reactor::{Core, Timeout};
use futures::future::{self, Loop, Future};
use futures::stream::Stream;
use futures::sink::{Sink, Wait};
mod add_torrent;
mod disk_manager_send_backpressure;
mod complete_torrent;
mod load_block;
mod process_block;
mod remove_torrent;
mod resume_torrent;
/// Generate buffer of size random bytes.
fn random_buffer(size: usize) -> Vec<u8> {
let mut buffer = vec![0u8; size];
let mut rng = rand::weak_rng();
for i in 0..size {
buffer[i] = rng.gen();
}
buffer
}
/// Initiate a core loop with the given timeout, state, and closure.
///
/// Returns R or panics if an error occurred in the loop (including a timeout).
fn core_loop_with_timeout<I, S, F, R>(core: &mut Core, timeout_ms: u64, state: (I, S), call: F) -> R
where F: FnMut(I, S, S::Item) -> Loop<R, (I, S)>,
S: Stream {
let timeout = Timeout::new(Duration::from_millis(timeout_ms), &core.handle())
.unwrap()
.then(|_| Err(()));
// Have to stick the call in our init state so that we transfer ownership between loops
core.run(
future::loop_fn((call, state), |(mut call, (init, stream))| {
stream.into_future()
.map(|(opt_msg, stream)| {
let msg = opt_msg
.unwrap_or_else(|| panic!("End Of Stream Reached"));
match call(init, stream, msg) {
Loop::Continue((init, stream)) => Loop::Continue((call, (init, stream))),
Loop::Break(ret) => Loop::Break(ret)
}
})
})
.map_err(|_| ())
.select(timeout)
.map(|(item, _)| item)
).unwrap_or_else(|_| panic!("Core Loop Timed Out"))
}
/// Send block with the given metadata and entire data given.
fn send_block<S, M>(blocking_send: &mut Wait<S>, data: &[u8], hash: InfoHash, piece_index: u64, block_offset: u64, block_len: usize, modify: M)
where S: Sink<SinkItem=IDiskMessage>, M: Fn(&mut [u8]) {
let mut bytes = BytesMut::new();
bytes.extend_from_slice(data);
let mut block = BlockMut::new(BlockMetadata::new(hash, piece_index, block_offset, block_len), bytes);
modify(&mut block[..]);
blocking_send.send(IDiskMessage::ProcessBlock(block.into())).unwrap_or_else(|_| panic!("Failed To Send Process Block Message"));
}
//----------------------------------------------------------------------------//
/// Allow us to mock out multi file torrents.
struct MultiFileDirectAccessor {
dir: PathBuf,
files: Vec<(Vec<u8>, PathBuf)>
}
impl MultiFileDirectAccessor {
pub fn new(dir: PathBuf, files: Vec<(Vec<u8>, PathBuf)>) -> MultiFileDirectAccessor {
MultiFileDirectAccessor{ dir: dir, files: files }
}
}
// TODO: Ugh, once specialization lands, we can see about having a default impl for IntoAccessor
impl IntoAccessor for MultiFileDirectAccessor {
type Accessor = MultiFileDirectAccessor;
fn into_accessor(self) -> io::Result<MultiFileDirectAccessor> {
Ok(self)
}
}
impl Accessor for MultiFileDirectAccessor {
fn access_directory(&self) -> Option<&Path> {
// Do not just return the option here, unwrap it and put it in
// another Option (since we know this is a multi file torrent)
Some(self.dir.as_ref())
}
fn access_metadata<C>(&self, mut callback: C) -> io::Result<()>
where C: FnMut(u64, &Path) {
for &(ref buffer, ref path) in self.files.iter() {
callback(buffer.len() as u64, &*path)
}
Ok(())
}
fn access_pieces<C>(&self, mut callback: C) -> io::Result<()>
where C: for<'a> FnMut(PieceAccess<'a>) -> io::Result<()> {
for &(ref buffer, _) in self.files.iter() {
try!(callback(PieceAccess::Compute(&mut &buffer[..])))
}
Ok(())
}
}
//----------------------------------------------------------------------------//
/// Allow us to mock out the file system.
#[derive(Clone)]
struct InMemoryFileSystem {
files: Arc<Mutex<HashMap<PathBuf, Vec<u8>>>>
}
impl InMemoryFileSystem {
pub fn | () -> InMemoryFileSystem {
InMemoryFileSystem{ files: Arc::new(Mutex::new(HashMap::new())) }
}
pub fn run_with_lock<C, R>(&self, call: C) -> R
where C: FnOnce(&mut HashMap<PathBuf, Vec<u8>>) -> R {
let mut lock_files = self.files.lock().unwrap();
call(&mut *lock_files)
}
}
struct InMemoryFile {
path: PathBuf
}
impl FileSystem for InMemoryFileSystem {
type File = InMemoryFile;
fn open_file<P>(&self, path: P) -> io::Result<Self::File>
where P: AsRef<Path> + Send +'static {
let file_path = path.as_ref().to_path_buf();
self.run_with_lock(|files| {
if!files.contains_key(&file_path) {
files.insert(file_path.clone(), Vec::new());
}
});
Ok(InMemoryFile{ path: file_path })
}
fn sync_file<P>(&self, _path: P) -> io::Result<()>
where P: AsRef<Path> + Send +'static {
Ok(())
}
fn file_size(&self, file: &Self::File) -> io::Result<u64> {
self.run_with_lock(|files| {
files.get(&file.path)
.map(|file| file.len() as u64)
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
fn read_file(&self, file: &mut Self::File, offset: u64, buffer: &mut [u8]) -> io::Result<usize> {
self.run_with_lock(|files| {
files.get(&file.path)
.map(|file_buffer| {
let cast_offset = offset as usize;
let bytes_to_copy = cmp::min(file_buffer.len() - cast_offset, buffer.len());
let bytes = &file_buffer[cast_offset..(bytes_to_copy + cast_offset)];
buffer.clone_from_slice(bytes);
bytes_to_copy
})
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
fn write_file(&self, file: &mut Self::File, offset: u64, buffer: &[u8]) -> io::Result<usize> {
self.run_with_lock(|files| {
files.get_mut(&file.path)
.map(|file_buffer| {
let cast_offset = offset as usize;
let last_byte_pos = cast_offset + buffer.len();
if last_byte_pos > file_buffer.len() {
file_buffer.resize(last_byte_pos, 0);
}
let bytes_to_copy = cmp::min(file_buffer.len() - cast_offset, buffer.len());
if bytes_to_copy!= 0 {
file_buffer[cast_offset..(cast_offset + bytes_to_copy)].clone_from_slice(buffer);
}
// TODO: If the file is full, this will return zero, we should also simulate io::ErrorKind::WriteZero
bytes_to_copy
})
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
}
| new | identifier_name |
mod.rs | extern crate bip_metainfo;
extern crate bip_disk;
extern crate bip_util;
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate rand;
use std::collections::HashMap;
use std::io::{self};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Arc};
use std::cmp;
use std::time::Duration;
use bip_disk::{FileSystem, IDiskMessage, BlockMetadata, BlockMut};
use bip_metainfo::{IntoAccessor, Accessor, PieceAccess};
use bip_util::bt::InfoHash;
use bytes::BytesMut;
use rand::Rng;
use tokio_core::reactor::{Core, Timeout};
use futures::future::{self, Loop, Future};
use futures::stream::Stream;
use futures::sink::{Sink, Wait};
mod add_torrent;
mod disk_manager_send_backpressure;
mod complete_torrent;
mod load_block;
mod process_block;
mod remove_torrent;
mod resume_torrent;
/// Generate buffer of size random bytes.
fn random_buffer(size: usize) -> Vec<u8> {
let mut buffer = vec![0u8; size];
let mut rng = rand::weak_rng();
for i in 0..size {
buffer[i] = rng.gen();
}
buffer
}
/// Initiate a core loop with the given timeout, state, and closure.
///
/// Returns R or panics if an error occurred in the loop (including a timeout).
fn core_loop_with_timeout<I, S, F, R>(core: &mut Core, timeout_ms: u64, state: (I, S), call: F) -> R
where F: FnMut(I, S, S::Item) -> Loop<R, (I, S)>,
S: Stream {
let timeout = Timeout::new(Duration::from_millis(timeout_ms), &core.handle())
.unwrap()
.then(|_| Err(()));
// Have to stick the call in our init state so that we transfer ownership between loops
core.run(
future::loop_fn((call, state), |(mut call, (init, stream))| {
stream.into_future()
.map(|(opt_msg, stream)| {
let msg = opt_msg
.unwrap_or_else(|| panic!("End Of Stream Reached"));
match call(init, stream, msg) {
Loop::Continue((init, stream)) => Loop::Continue((call, (init, stream))),
Loop::Break(ret) => Loop::Break(ret)
}
})
})
.map_err(|_| ())
.select(timeout)
.map(|(item, _)| item)
).unwrap_or_else(|_| panic!("Core Loop Timed Out"))
}
/// Send block with the given metadata and entire data given.
fn send_block<S, M>(blocking_send: &mut Wait<S>, data: &[u8], hash: InfoHash, piece_index: u64, block_offset: u64, block_len: usize, modify: M)
where S: Sink<SinkItem=IDiskMessage>, M: Fn(&mut [u8]) {
let mut bytes = BytesMut::new();
bytes.extend_from_slice(data);
let mut block = BlockMut::new(BlockMetadata::new(hash, piece_index, block_offset, block_len), bytes);
modify(&mut block[..]);
blocking_send.send(IDiskMessage::ProcessBlock(block.into())).unwrap_or_else(|_| panic!("Failed To Send Process Block Message"));
}
//----------------------------------------------------------------------------//
/// Allow us to mock out multi file torrents.
struct MultiFileDirectAccessor {
dir: PathBuf,
files: Vec<(Vec<u8>, PathBuf)>
}
impl MultiFileDirectAccessor {
pub fn new(dir: PathBuf, files: Vec<(Vec<u8>, PathBuf)>) -> MultiFileDirectAccessor {
MultiFileDirectAccessor{ dir: dir, files: files }
}
}
// TODO: Ugh, once specialization lands, we can see about having a default impl for IntoAccessor
impl IntoAccessor for MultiFileDirectAccessor {
type Accessor = MultiFileDirectAccessor;
fn into_accessor(self) -> io::Result<MultiFileDirectAccessor> {
Ok(self)
}
}
impl Accessor for MultiFileDirectAccessor {
fn access_directory(&self) -> Option<&Path> {
// Do not just return the option here, unwrap it and put it in
// another Option (since we know this is a multi file torrent)
Some(self.dir.as_ref())
}
fn access_metadata<C>(&self, mut callback: C) -> io::Result<()>
where C: FnMut(u64, &Path) {
for &(ref buffer, ref path) in self.files.iter() {
callback(buffer.len() as u64, &*path)
}
Ok(())
}
fn access_pieces<C>(&self, mut callback: C) -> io::Result<()>
where C: for<'a> FnMut(PieceAccess<'a>) -> io::Result<()> {
for &(ref buffer, _) in self.files.iter() {
try!(callback(PieceAccess::Compute(&mut &buffer[..])))
}
Ok(())
}
}
//----------------------------------------------------------------------------//
/// Allow us to mock out the file system.
#[derive(Clone)]
struct InMemoryFileSystem {
files: Arc<Mutex<HashMap<PathBuf, Vec<u8>>>>
}
impl InMemoryFileSystem {
pub fn new() -> InMemoryFileSystem {
InMemoryFileSystem{ files: Arc::new(Mutex::new(HashMap::new())) }
}
pub fn run_with_lock<C, R>(&self, call: C) -> R
where C: FnOnce(&mut HashMap<PathBuf, Vec<u8>>) -> R |
}
struct InMemoryFile {
path: PathBuf
}
impl FileSystem for InMemoryFileSystem {
type File = InMemoryFile;
fn open_file<P>(&self, path: P) -> io::Result<Self::File>
where P: AsRef<Path> + Send +'static {
let file_path = path.as_ref().to_path_buf();
self.run_with_lock(|files| {
if!files.contains_key(&file_path) {
files.insert(file_path.clone(), Vec::new());
}
});
Ok(InMemoryFile{ path: file_path })
}
fn sync_file<P>(&self, _path: P) -> io::Result<()>
where P: AsRef<Path> + Send +'static {
Ok(())
}
fn file_size(&self, file: &Self::File) -> io::Result<u64> {
self.run_with_lock(|files| {
files.get(&file.path)
.map(|file| file.len() as u64)
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
fn read_file(&self, file: &mut Self::File, offset: u64, buffer: &mut [u8]) -> io::Result<usize> {
self.run_with_lock(|files| {
files.get(&file.path)
.map(|file_buffer| {
let cast_offset = offset as usize;
let bytes_to_copy = cmp::min(file_buffer.len() - cast_offset, buffer.len());
let bytes = &file_buffer[cast_offset..(bytes_to_copy + cast_offset)];
buffer.clone_from_slice(bytes);
bytes_to_copy
})
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
fn write_file(&self, file: &mut Self::File, offset: u64, buffer: &[u8]) -> io::Result<usize> {
self.run_with_lock(|files| {
files.get_mut(&file.path)
.map(|file_buffer| {
let cast_offset = offset as usize;
let last_byte_pos = cast_offset + buffer.len();
if last_byte_pos > file_buffer.len() {
file_buffer.resize(last_byte_pos, 0);
}
let bytes_to_copy = cmp::min(file_buffer.len() - cast_offset, buffer.len());
if bytes_to_copy!= 0 {
file_buffer[cast_offset..(cast_offset + bytes_to_copy)].clone_from_slice(buffer);
}
// TODO: If the file is full, this will return zero, we should also simulate io::ErrorKind::WriteZero
bytes_to_copy
})
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
}
| {
let mut lock_files = self.files.lock().unwrap();
call(&mut *lock_files)
} | identifier_body |
mod.rs | extern crate bip_metainfo;
extern crate bip_disk;
extern crate bip_util;
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate rand;
use std::collections::HashMap;
use std::io::{self};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Arc};
use std::cmp;
use std::time::Duration;
use bip_disk::{FileSystem, IDiskMessage, BlockMetadata, BlockMut};
use bip_metainfo::{IntoAccessor, Accessor, PieceAccess};
use bip_util::bt::InfoHash;
use bytes::BytesMut;
use rand::Rng;
use tokio_core::reactor::{Core, Timeout};
use futures::future::{self, Loop, Future};
use futures::stream::Stream;
use futures::sink::{Sink, Wait};
mod add_torrent;
mod disk_manager_send_backpressure;
mod complete_torrent;
mod load_block;
mod process_block;
mod remove_torrent;
mod resume_torrent;
/// Generate buffer of size random bytes.
fn random_buffer(size: usize) -> Vec<u8> {
let mut buffer = vec![0u8; size];
let mut rng = rand::weak_rng();
for i in 0..size {
buffer[i] = rng.gen();
}
buffer
}
/// Initiate a core loop with the given timeout, state, and closure.
///
/// Returns R or panics if an error occurred in the loop (including a timeout).
fn core_loop_with_timeout<I, S, F, R>(core: &mut Core, timeout_ms: u64, state: (I, S), call: F) -> R
where F: FnMut(I, S, S::Item) -> Loop<R, (I, S)>,
S: Stream {
let timeout = Timeout::new(Duration::from_millis(timeout_ms), &core.handle())
.unwrap()
.then(|_| Err(()));
// Have to stick the call in our init state so that we transfer ownership between loops
core.run(
future::loop_fn((call, state), |(mut call, (init, stream))| {
stream.into_future()
.map(|(opt_msg, stream)| {
let msg = opt_msg
.unwrap_or_else(|| panic!("End Of Stream Reached"));
match call(init, stream, msg) {
Loop::Continue((init, stream)) => Loop::Continue((call, (init, stream))),
Loop::Break(ret) => Loop::Break(ret)
}
})
})
.map_err(|_| ())
.select(timeout)
.map(|(item, _)| item)
).unwrap_or_else(|_| panic!("Core Loop Timed Out"))
}
/// Send block with the given metadata and entire data given.
fn send_block<S, M>(blocking_send: &mut Wait<S>, data: &[u8], hash: InfoHash, piece_index: u64, block_offset: u64, block_len: usize, modify: M)
where S: Sink<SinkItem=IDiskMessage>, M: Fn(&mut [u8]) {
let mut bytes = BytesMut::new();
bytes.extend_from_slice(data);
let mut block = BlockMut::new(BlockMetadata::new(hash, piece_index, block_offset, block_len), bytes);
modify(&mut block[..]);
blocking_send.send(IDiskMessage::ProcessBlock(block.into())).unwrap_or_else(|_| panic!("Failed To Send Process Block Message"));
}
//----------------------------------------------------------------------------//
/// Allow us to mock out multi file torrents.
struct MultiFileDirectAccessor {
dir: PathBuf,
files: Vec<(Vec<u8>, PathBuf)>
}
impl MultiFileDirectAccessor {
pub fn new(dir: PathBuf, files: Vec<(Vec<u8>, PathBuf)>) -> MultiFileDirectAccessor {
MultiFileDirectAccessor{ dir: dir, files: files }
}
}
// TODO: Ugh, once specialization lands, we can see about having a default impl for IntoAccessor
impl IntoAccessor for MultiFileDirectAccessor {
type Accessor = MultiFileDirectAccessor;
fn into_accessor(self) -> io::Result<MultiFileDirectAccessor> {
Ok(self)
}
}
impl Accessor for MultiFileDirectAccessor {
fn access_directory(&self) -> Option<&Path> {
// Do not just return the option here, unwrap it and put it in
// another Option (since we know this is a multi file torrent)
Some(self.dir.as_ref())
}
fn access_metadata<C>(&self, mut callback: C) -> io::Result<()>
where C: FnMut(u64, &Path) {
for &(ref buffer, ref path) in self.files.iter() {
callback(buffer.len() as u64, &*path)
}
Ok(())
}
fn access_pieces<C>(&self, mut callback: C) -> io::Result<()>
where C: for<'a> FnMut(PieceAccess<'a>) -> io::Result<()> {
for &(ref buffer, _) in self.files.iter() {
try!(callback(PieceAccess::Compute(&mut &buffer[..])))
}
Ok(())
}
}
//----------------------------------------------------------------------------//
/// Allow us to mock out the file system.
#[derive(Clone)]
struct InMemoryFileSystem {
files: Arc<Mutex<HashMap<PathBuf, Vec<u8>>>>
}
impl InMemoryFileSystem {
pub fn new() -> InMemoryFileSystem {
InMemoryFileSystem{ files: Arc::new(Mutex::new(HashMap::new())) }
}
pub fn run_with_lock<C, R>(&self, call: C) -> R
where C: FnOnce(&mut HashMap<PathBuf, Vec<u8>>) -> R {
let mut lock_files = self.files.lock().unwrap();
call(&mut *lock_files)
}
}
struct InMemoryFile {
path: PathBuf
}
impl FileSystem for InMemoryFileSystem {
type File = InMemoryFile;
fn open_file<P>(&self, path: P) -> io::Result<Self::File>
where P: AsRef<Path> + Send +'static {
let file_path = path.as_ref().to_path_buf();
self.run_with_lock(|files| {
if!files.contains_key(&file_path) {
files.insert(file_path.clone(), Vec::new());
}
});
Ok(InMemoryFile{ path: file_path })
}
fn sync_file<P>(&self, _path: P) -> io::Result<()>
where P: AsRef<Path> + Send +'static {
Ok(())
}
fn file_size(&self, file: &Self::File) -> io::Result<u64> {
self.run_with_lock(|files| {
files.get(&file.path)
.map(|file| file.len() as u64)
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
fn read_file(&self, file: &mut Self::File, offset: u64, buffer: &mut [u8]) -> io::Result<usize> {
self.run_with_lock(|files| {
files.get(&file.path)
.map(|file_buffer| {
let cast_offset = offset as usize;
let bytes_to_copy = cmp::min(file_buffer.len() - cast_offset, buffer.len());
let bytes = &file_buffer[cast_offset..(bytes_to_copy + cast_offset)];
buffer.clone_from_slice(bytes);
bytes_to_copy
})
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
fn write_file(&self, file: &mut Self::File, offset: u64, buffer: &[u8]) -> io::Result<usize> {
self.run_with_lock(|files| {
files.get_mut(&file.path)
.map(|file_buffer| {
let cast_offset = offset as usize;
let last_byte_pos = cast_offset + buffer.len();
if last_byte_pos > file_buffer.len() |
let bytes_to_copy = cmp::min(file_buffer.len() - cast_offset, buffer.len());
if bytes_to_copy!= 0 {
file_buffer[cast_offset..(cast_offset + bytes_to_copy)].clone_from_slice(buffer);
}
// TODO: If the file is full, this will return zero, we should also simulate io::ErrorKind::WriteZero
bytes_to_copy
})
.ok_or(io::Error::new(io::ErrorKind::NotFound, "File Not Found"))
})
}
}
| {
file_buffer.resize(last_byte_pos, 0);
} | conditional_block |
harmonic.rs | //! Provides functions for calculating
//! [harmonic](https://en.wikipedia.org/wiki/Harmonic_number)
//! numbers
use crate::consts;
use crate::function::gamma;
/// Computes the `t`-th harmonic number
///
/// # Remarks
///
/// Returns `1` as a special case when `t == 0`
pub fn harmonic(t: u64) -> f64 {
match t {
0 => 1.0,
_ => consts::EULER_MASCHERONI + gamma::digamma(t as f64 + 1.0),
}
}
/// Computes the generalized harmonic number of order `n` of `m`
/// e.g. `(1 + 1/2^m + 1/3^m +... + 1/n^m)`
///
/// # Remarks
///
/// Returns `1` as a special case when `n == 0`
pub fn gen_harmonic(n: u64, m: f64) -> f64 {
match n {
0 => 1.0,
_ => (0..n).fold(0.0, |acc, x| acc + (x as f64 + 1.0).powf(-m)),
}
}
#[rustfmt::skip]
#[cfg(test)]
mod tests {
use std::f64;
#[test]
fn test_harmonic() {
assert_eq!(super::harmonic(0), 1.0);
assert_almost_eq!(super::harmonic(1), 1.0, 1e-14);
assert_almost_eq!(super::harmonic(2), 1.5, 1e-14);
assert_almost_eq!(super::harmonic(4), 2.083333333333333333333, 1e-14);
assert_almost_eq!(super::harmonic(8), 2.717857142857142857143, 1e-14);
assert_almost_eq!(super::harmonic(16), 3.380728993228993228993, 1e-14);
}
#[test]
fn test_gen_harmonic() {
assert_eq!(super::gen_harmonic(0, 0.0), 1.0);
assert_eq!(super::gen_harmonic(0, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(0, f64::NEG_INFINITY), 1.0);
assert_eq!(super::gen_harmonic(1, 0.0), 1.0);
assert_eq!(super::gen_harmonic(1, f64::INFINITY), 1.0); | assert_almost_eq!(super::gen_harmonic(4, 1.0), 2.083333333333333333333, 1e-14);
assert_eq!(super::gen_harmonic(4, 3.0), 1.177662037037037037037);
assert_eq!(super::gen_harmonic(4, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(4, f64::NEG_INFINITY), f64::INFINITY);
}
} | assert_eq!(super::gen_harmonic(1, f64::NEG_INFINITY), 1.0);
assert_eq!(super::gen_harmonic(2, 1.0), 1.5);
assert_eq!(super::gen_harmonic(2, 3.0), 1.125);
assert_eq!(super::gen_harmonic(2, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(2, f64::NEG_INFINITY), f64::INFINITY); | random_line_split |
harmonic.rs | //! Provides functions for calculating
//! [harmonic](https://en.wikipedia.org/wiki/Harmonic_number)
//! numbers
use crate::consts;
use crate::function::gamma;
/// Computes the `t`-th harmonic number
///
/// # Remarks
///
/// Returns `1` as a special case when `t == 0`
pub fn harmonic(t: u64) -> f64 {
match t {
0 => 1.0,
_ => consts::EULER_MASCHERONI + gamma::digamma(t as f64 + 1.0),
}
}
/// Computes the generalized harmonic number of order `n` of `m`
/// e.g. `(1 + 1/2^m + 1/3^m +... + 1/n^m)`
///
/// # Remarks
///
/// Returns `1` as a special case when `n == 0`
pub fn gen_harmonic(n: u64, m: f64) -> f64 {
match n {
0 => 1.0,
_ => (0..n).fold(0.0, |acc, x| acc + (x as f64 + 1.0).powf(-m)),
}
}
#[rustfmt::skip]
#[cfg(test)]
mod tests {
use std::f64;
#[test]
fn test_harmonic() {
assert_eq!(super::harmonic(0), 1.0);
assert_almost_eq!(super::harmonic(1), 1.0, 1e-14);
assert_almost_eq!(super::harmonic(2), 1.5, 1e-14);
assert_almost_eq!(super::harmonic(4), 2.083333333333333333333, 1e-14);
assert_almost_eq!(super::harmonic(8), 2.717857142857142857143, 1e-14);
assert_almost_eq!(super::harmonic(16), 3.380728993228993228993, 1e-14);
}
#[test]
fn | () {
assert_eq!(super::gen_harmonic(0, 0.0), 1.0);
assert_eq!(super::gen_harmonic(0, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(0, f64::NEG_INFINITY), 1.0);
assert_eq!(super::gen_harmonic(1, 0.0), 1.0);
assert_eq!(super::gen_harmonic(1, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(1, f64::NEG_INFINITY), 1.0);
assert_eq!(super::gen_harmonic(2, 1.0), 1.5);
assert_eq!(super::gen_harmonic(2, 3.0), 1.125);
assert_eq!(super::gen_harmonic(2, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(2, f64::NEG_INFINITY), f64::INFINITY);
assert_almost_eq!(super::gen_harmonic(4, 1.0), 2.083333333333333333333, 1e-14);
assert_eq!(super::gen_harmonic(4, 3.0), 1.177662037037037037037);
assert_eq!(super::gen_harmonic(4, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(4, f64::NEG_INFINITY), f64::INFINITY);
}
}
| test_gen_harmonic | identifier_name |
harmonic.rs | //! Provides functions for calculating
//! [harmonic](https://en.wikipedia.org/wiki/Harmonic_number)
//! numbers
use crate::consts;
use crate::function::gamma;
/// Computes the `t`-th harmonic number
///
/// # Remarks
///
/// Returns `1` as a special case when `t == 0`
pub fn harmonic(t: u64) -> f64 {
match t {
0 => 1.0,
_ => consts::EULER_MASCHERONI + gamma::digamma(t as f64 + 1.0),
}
}
/// Computes the generalized harmonic number of order `n` of `m`
/// e.g. `(1 + 1/2^m + 1/3^m +... + 1/n^m)`
///
/// # Remarks
///
/// Returns `1` as a special case when `n == 0`
pub fn gen_harmonic(n: u64, m: f64) -> f64 {
match n {
0 => 1.0,
_ => (0..n).fold(0.0, |acc, x| acc + (x as f64 + 1.0).powf(-m)),
}
}
#[rustfmt::skip]
#[cfg(test)]
mod tests {
use std::f64;
#[test]
fn test_harmonic() |
#[test]
fn test_gen_harmonic() {
assert_eq!(super::gen_harmonic(0, 0.0), 1.0);
assert_eq!(super::gen_harmonic(0, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(0, f64::NEG_INFINITY), 1.0);
assert_eq!(super::gen_harmonic(1, 0.0), 1.0);
assert_eq!(super::gen_harmonic(1, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(1, f64::NEG_INFINITY), 1.0);
assert_eq!(super::gen_harmonic(2, 1.0), 1.5);
assert_eq!(super::gen_harmonic(2, 3.0), 1.125);
assert_eq!(super::gen_harmonic(2, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(2, f64::NEG_INFINITY), f64::INFINITY);
assert_almost_eq!(super::gen_harmonic(4, 1.0), 2.083333333333333333333, 1e-14);
assert_eq!(super::gen_harmonic(4, 3.0), 1.177662037037037037037);
assert_eq!(super::gen_harmonic(4, f64::INFINITY), 1.0);
assert_eq!(super::gen_harmonic(4, f64::NEG_INFINITY), f64::INFINITY);
}
}
| {
assert_eq!(super::harmonic(0), 1.0);
assert_almost_eq!(super::harmonic(1), 1.0, 1e-14);
assert_almost_eq!(super::harmonic(2), 1.5, 1e-14);
assert_almost_eq!(super::harmonic(4), 2.083333333333333333333, 1e-14);
assert_almost_eq!(super::harmonic(8), 2.717857142857142857143, 1e-14);
assert_almost_eq!(super::harmonic(16), 3.380728993228993228993, 1e-14);
} | identifier_body |
epoll.rs | use {Errno, Result};
use libc::{self, c_int};
use std::os::unix::io::RawFd;
use std::ptr;
use std::mem;
use ::Error;
libc_bitflags!(
pub flags EpollFlags: libc::c_int {
EPOLLIN,
EPOLLPRI,
EPOLLOUT,
EPOLLRDNORM,
EPOLLRDBAND,
EPOLLWRNORM,
EPOLLWRBAND,
EPOLLMSG,
EPOLLERR,
EPOLLHUP,
EPOLLRDHUP,
#[cfg(target_os = "linux")] // Added in 4.5; not in Android.
EPOLLEXCLUSIVE,
#[cfg(not(target_arch = "mips"))]
EPOLLWAKEUP,
EPOLLONESHOT,
EPOLLET,
}
);
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(C)]
pub enum EpollOp {
EpollCtlAdd = 1,
EpollCtlDel = 2,
EpollCtlMod = 3
}
libc_bitflags!{
pub flags EpollCreateFlags: c_int {
EPOLL_CLOEXEC,
}
}
#[derive(Clone, Copy)]
#[repr(C)]
pub struct | {
event: libc::epoll_event,
}
impl EpollEvent {
pub fn new(events: EpollFlags, data: u64) -> Self {
EpollEvent { event: libc::epoll_event { events: events.bits() as u32, u64: data } }
}
pub fn empty() -> Self {
unsafe { mem::zeroed::<EpollEvent>() }
}
pub fn events(&self) -> EpollFlags {
EpollFlags::from_bits(self.event.events as libc::c_int).unwrap()
}
pub fn data(&self) -> u64 {
self.event.u64
}
}
impl<'a> Into<&'a mut EpollEvent> for Option<&'a mut EpollEvent> {
#[inline]
fn into(self) -> &'a mut EpollEvent {
match self {
Some(epoll_event) => epoll_event,
None => unsafe { &mut *ptr::null_mut::<EpollEvent>() }
}
}
}
#[inline]
pub fn epoll_create() -> Result<RawFd> {
let res = unsafe { libc::epoll_create(1024) };
Errno::result(res)
}
#[inline]
pub fn epoll_create1(flags: EpollCreateFlags) -> Result<RawFd> {
let res = unsafe { libc::epoll_create1(flags.bits()) };
Errno::result(res)
}
#[inline]
pub fn epoll_ctl<'a, T>(epfd: RawFd, op: EpollOp, fd: RawFd, event: T) -> Result<()>
where T: Into<&'a mut EpollEvent>
{
let event: &mut EpollEvent = event.into();
if event as *const EpollEvent == ptr::null() && op!= EpollOp::EpollCtlDel {
Err(Error::Sys(Errno::EINVAL))
} else {
let res = unsafe { libc::epoll_ctl(epfd, op as c_int, fd, &mut event.event) };
Errno::result(res).map(drop)
}
}
#[inline]
pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> {
let res = unsafe {
libc::epoll_wait(epfd, events.as_mut_ptr() as *mut libc::epoll_event, events.len() as c_int, timeout_ms as c_int)
};
Errno::result(res).map(|r| r as usize)
}
| EpollEvent | identifier_name |
epoll.rs | use {Errno, Result};
use libc::{self, c_int};
use std::os::unix::io::RawFd;
use std::ptr;
use std::mem;
use ::Error;
libc_bitflags!(
pub flags EpollFlags: libc::c_int {
EPOLLIN,
EPOLLPRI,
EPOLLOUT,
EPOLLRDNORM,
EPOLLRDBAND,
EPOLLWRNORM,
EPOLLWRBAND,
EPOLLMSG,
EPOLLERR,
EPOLLHUP,
EPOLLRDHUP,
#[cfg(target_os = "linux")] // Added in 4.5; not in Android.
EPOLLEXCLUSIVE,
#[cfg(not(target_arch = "mips"))]
EPOLLWAKEUP,
EPOLLONESHOT,
EPOLLET,
}
);
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(C)]
pub enum EpollOp {
EpollCtlAdd = 1,
EpollCtlDel = 2,
EpollCtlMod = 3
}
libc_bitflags!{
pub flags EpollCreateFlags: c_int {
EPOLL_CLOEXEC,
}
}
#[derive(Clone, Copy)]
#[repr(C)]
pub struct EpollEvent {
event: libc::epoll_event,
}
impl EpollEvent {
pub fn new(events: EpollFlags, data: u64) -> Self {
EpollEvent { event: libc::epoll_event { events: events.bits() as u32, u64: data } }
}
pub fn empty() -> Self {
unsafe { mem::zeroed::<EpollEvent>() }
}
pub fn events(&self) -> EpollFlags {
EpollFlags::from_bits(self.event.events as libc::c_int).unwrap()
}
pub fn data(&self) -> u64 |
}
impl<'a> Into<&'a mut EpollEvent> for Option<&'a mut EpollEvent> {
#[inline]
fn into(self) -> &'a mut EpollEvent {
match self {
Some(epoll_event) => epoll_event,
None => unsafe { &mut *ptr::null_mut::<EpollEvent>() }
}
}
}
#[inline]
pub fn epoll_create() -> Result<RawFd> {
let res = unsafe { libc::epoll_create(1024) };
Errno::result(res)
}
#[inline]
pub fn epoll_create1(flags: EpollCreateFlags) -> Result<RawFd> {
let res = unsafe { libc::epoll_create1(flags.bits()) };
Errno::result(res)
}
#[inline]
pub fn epoll_ctl<'a, T>(epfd: RawFd, op: EpollOp, fd: RawFd, event: T) -> Result<()>
where T: Into<&'a mut EpollEvent>
{
let event: &mut EpollEvent = event.into();
if event as *const EpollEvent == ptr::null() && op!= EpollOp::EpollCtlDel {
Err(Error::Sys(Errno::EINVAL))
} else {
let res = unsafe { libc::epoll_ctl(epfd, op as c_int, fd, &mut event.event) };
Errno::result(res).map(drop)
}
}
#[inline]
pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> {
let res = unsafe {
libc::epoll_wait(epfd, events.as_mut_ptr() as *mut libc::epoll_event, events.len() as c_int, timeout_ms as c_int)
};
Errno::result(res).map(|r| r as usize)
}
| {
self.event.u64
} | identifier_body |
epoll.rs | use {Errno, Result};
use libc::{self, c_int};
use std::os::unix::io::RawFd;
use std::ptr;
use std::mem;
use ::Error;
libc_bitflags!(
pub flags EpollFlags: libc::c_int {
EPOLLIN,
EPOLLPRI,
EPOLLOUT,
EPOLLRDNORM,
EPOLLRDBAND,
EPOLLWRNORM,
EPOLLWRBAND,
EPOLLMSG,
EPOLLERR,
EPOLLHUP,
EPOLLRDHUP,
#[cfg(target_os = "linux")] // Added in 4.5; not in Android.
EPOLLEXCLUSIVE,
#[cfg(not(target_arch = "mips"))]
EPOLLWAKEUP,
EPOLLONESHOT,
EPOLLET,
}
);
#[derive(Clone, Copy, Eq, PartialEq)]
#[repr(C)]
pub enum EpollOp {
EpollCtlAdd = 1,
EpollCtlDel = 2,
EpollCtlMod = 3
}
libc_bitflags!{
pub flags EpollCreateFlags: c_int {
EPOLL_CLOEXEC,
}
}
#[derive(Clone, Copy)]
#[repr(C)]
pub struct EpollEvent {
event: libc::epoll_event,
}
impl EpollEvent {
pub fn new(events: EpollFlags, data: u64) -> Self {
EpollEvent { event: libc::epoll_event { events: events.bits() as u32, u64: data } }
}
pub fn empty() -> Self {
unsafe { mem::zeroed::<EpollEvent>() }
}
pub fn events(&self) -> EpollFlags {
EpollFlags::from_bits(self.event.events as libc::c_int).unwrap()
}
pub fn data(&self) -> u64 {
self.event.u64
}
}
impl<'a> Into<&'a mut EpollEvent> for Option<&'a mut EpollEvent> {
#[inline]
fn into(self) -> &'a mut EpollEvent {
match self {
Some(epoll_event) => epoll_event,
None => unsafe { &mut *ptr::null_mut::<EpollEvent>() }
}
}
}
#[inline]
pub fn epoll_create() -> Result<RawFd> {
let res = unsafe { libc::epoll_create(1024) };
Errno::result(res)
}
#[inline]
pub fn epoll_create1(flags: EpollCreateFlags) -> Result<RawFd> {
let res = unsafe { libc::epoll_create1(flags.bits()) };
Errno::result(res)
}
#[inline]
pub fn epoll_ctl<'a, T>(epfd: RawFd, op: EpollOp, fd: RawFd, event: T) -> Result<()>
where T: Into<&'a mut EpollEvent> | } else {
let res = unsafe { libc::epoll_ctl(epfd, op as c_int, fd, &mut event.event) };
Errno::result(res).map(drop)
}
}
#[inline]
pub fn epoll_wait(epfd: RawFd, events: &mut [EpollEvent], timeout_ms: isize) -> Result<usize> {
let res = unsafe {
libc::epoll_wait(epfd, events.as_mut_ptr() as *mut libc::epoll_event, events.len() as c_int, timeout_ms as c_int)
};
Errno::result(res).map(|r| r as usize)
} | {
let event: &mut EpollEvent = event.into();
if event as *const EpollEvent == ptr::null() && op != EpollOp::EpollCtlDel {
Err(Error::Sys(Errno::EINVAL)) | random_line_split |
marching_triangles_performance.rs | extern crate isosurface;
extern crate ndarray;
use ndarray::Array;
use isosurface::marching_triangles;
fn | () {
let n = 256;
let xs = Array::linspace(-0.5f64, 0.5, n);
let ys = Array::linspace(-0.5, 0.5, n);
let dim = (xs.len(), ys.len());
let u = {
let mut u = Array::from_elem(dim, 0.);
for ((i, j), u) in u.indexed_iter_mut() {
let (x, y) = (xs[i], ys[j]);
*u = (x * x + y * y).sqrt() - 0.4;
}
u
};
let mut m = 0;
for _ in 0..1000 {
let verts = marching_triangles(u.as_slice().unwrap(), dim, 0.);
m += verts.len();
}
println!("total vert num = {}", m);
}
| main | identifier_name |
marching_triangles_performance.rs | extern crate isosurface;
extern crate ndarray;
use ndarray::Array;
use isosurface::marching_triangles;
fn main() | m += verts.len();
}
println!("total vert num = {}", m);
}
| {
let n = 256;
let xs = Array::linspace(-0.5f64, 0.5, n);
let ys = Array::linspace(-0.5, 0.5, n);
let dim = (xs.len(), ys.len());
let u = {
let mut u = Array::from_elem(dim, 0.);
for ((i, j), u) in u.indexed_iter_mut() {
let (x, y) = (xs[i], ys[j]);
*u = (x * x + y * y).sqrt() - 0.4;
}
u
};
let mut m = 0;
for _ in 0..1000 {
let verts = marching_triangles(u.as_slice().unwrap(), dim, 0.); | identifier_body |
marching_triangles_performance.rs | extern crate isosurface;
extern crate ndarray;
use ndarray::Array;
use isosurface::marching_triangles;
fn main() {
let n = 256;
let xs = Array::linspace(-0.5f64, 0.5, n);
let ys = Array::linspace(-0.5, 0.5, n); | let u = {
let mut u = Array::from_elem(dim, 0.);
for ((i, j), u) in u.indexed_iter_mut() {
let (x, y) = (xs[i], ys[j]);
*u = (x * x + y * y).sqrt() - 0.4;
}
u
};
let mut m = 0;
for _ in 0..1000 {
let verts = marching_triangles(u.as_slice().unwrap(), dim, 0.);
m += verts.len();
}
println!("total vert num = {}", m);
} |
let dim = (xs.len(), ys.len());
| random_line_split |
generic-lifetime-trait-impl.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.
// This code used to produce an ICE on the definition of trait Bar
// with the following message:
//
// Type parameter out of range when substituting in region 'a (root
// type=fn(Self) -> 'astr) (space=FnSpace, index=0)
//
// Regression test for issue #16218.
trait Bar<'a> {}
trait Foo<'a> {
fn bar<'a, T: Bar<'a>>(self) -> &'a str;
}
impl<'a> Foo<'a> for &'a str {
fn bar<T: Bar<'a>>(self) -> &'a str { fail!() } //~ ERROR lifetime
}
fn | () {
}
| main | identifier_name |
generic-lifetime-trait-impl.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.
// This code used to produce an ICE on the definition of trait Bar
// with the following message:
//
// Type parameter out of range when substituting in region 'a (root
// type=fn(Self) -> 'astr) (space=FnSpace, index=0)
//
// Regression test for issue #16218.
trait Bar<'a> {}
trait Foo<'a> {
fn bar<'a, T: Bar<'a>>(self) -> &'a str;
}
impl<'a> Foo<'a> for &'a str {
fn bar<T: Bar<'a>>(self) -> &'a str | //~ ERROR lifetime
}
fn main() {
}
| { fail!() } | identifier_body |
generic-lifetime-trait-impl.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 | // except according to those terms.
// This code used to produce an ICE on the definition of trait Bar
// with the following message:
//
// Type parameter out of range when substituting in region 'a (root
// type=fn(Self) -> 'astr) (space=FnSpace, index=0)
//
// Regression test for issue #16218.
trait Bar<'a> {}
trait Foo<'a> {
fn bar<'a, T: Bar<'a>>(self) -> &'a str;
}
impl<'a> Foo<'a> for &'a str {
fn bar<T: Bar<'a>>(self) -> &'a str { fail!() } //~ ERROR lifetime
}
fn main() {
} | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
urlsearchparams.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsWrap;
use dom::bindings::codegen::UnionTypes::USVStringOrURLSearchParams;
use dom::bindings::error::Fallible;
use dom::bindings::iterable::Iterable;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{DOMString, USVString};
use dom::bindings::weakref::MutableWeakRef;
use dom::globalscope::GlobalScope;
use dom::url::URL;
use dom_struct::dom_struct;
use encoding::types::EncodingRef;
use url::form_urlencoded;
// https://url.spec.whatwg.org/#interface-urlsearchparams
#[dom_struct]
pub struct URLSearchParams {
reflector_: Reflector,
// https://url.spec.whatwg.org/#concept-urlsearchparams-list
list: DomRefCell<Vec<(String, String)>>,
// https://url.spec.whatwg.org/#concept-urlsearchparams-url-object
url: MutableWeakRef<URL>,
}
impl URLSearchParams {
fn new_inherited(url: Option<&URL>) -> URLSearchParams {
URLSearchParams {
reflector_: Reflector::new(),
list: DomRefCell::new(url.map_or(Vec::new(), |url| url.query_pairs())),
url: MutableWeakRef::new(url),
}
}
pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> {
reflect_dom_object(Box::new(URLSearchParams::new_inherited(url)), global,
URLSearchParamsWrap)
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
pub fn Constructor(global: &GlobalScope, init: Option<USVStringOrURLSearchParams>) ->
Fallible<DomRoot<URLSearchParams>> {
// Step 1.
let query = URLSearchParams::new(global, None);
match init {
Some(USVStringOrURLSearchParams::USVString(init)) => | ,
Some(USVStringOrURLSearchParams::URLSearchParams(init)) => {
// Step 3.
*query.list.borrow_mut() = init.list.borrow().clone();
},
None => {}
}
// Step 4.
Ok(query)
}
pub fn set_list(&self, list: Vec<(String, String)>) {
*self.list.borrow_mut() = list;
}
}
impl URLSearchParamsMethods for URLSearchParams {
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
fn Append(&self, name: USVString, value: USVString) {
// Step 1.
self.list.borrow_mut().push((name.0, value.0));
// Step 2.
self.update_steps();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
fn Delete(&self, name: USVString) {
// Step 1.
self.list.borrow_mut().retain(|&(ref k, _)| k!= &name.0);
// Step 2.
self.update_steps();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
fn Get(&self, name: USVString) -> Option<USVString> {
let list = self.list.borrow();
list.iter().find(|&kv| kv.0 == name.0)
.map(|ref kv| USVString(kv.1.clone()))
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
fn GetAll(&self, name: USVString) -> Vec<USVString> {
let list = self.list.borrow();
list.iter().filter_map(|&(ref k, ref v)| {
if k == &name.0 {
Some(USVString(v.clone()))
} else {
None
}
}).collect()
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
fn Has(&self, name: USVString) -> bool {
let list = self.list.borrow();
list.iter().any(|&(ref k, _)| k == &name.0)
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
fn Set(&self, name: USVString, value: USVString) {
{
// Step 1.
let mut list = self.list.borrow_mut();
let mut index = None;
let mut i = 0;
list.retain(|&(ref k, _)| {
if index.is_none() {
if k == &name.0 {
index = Some(i);
} else {
i += 1;
}
true
} else {
k!= &name.0
}
});
match index {
Some(index) => list[index].1 = value.0,
None => list.push((name.0, value.0)), // Step 2.
};
} // Un-borrow self.list
// Step 3.
self.update_steps();
}
// https://url.spec.whatwg.org/#stringification-behavior
fn Stringifier(&self) -> DOMString {
DOMString::from(self.serialize(None))
}
}
impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlencoded-serializer
pub fn serialize(&self, encoding: Option<EncodingRef>) -> String {
let list = self.list.borrow();
form_urlencoded::Serializer::new(String::new())
.encoding_override(encoding)
.extend_pairs(&*list)
.finish()
}
}
impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlsearchparams-update
fn update_steps(&self) {
if let Some(url) = self.url.root() {
url.set_query_pairs(&self.list.borrow())
}
}
}
impl Iterable for URLSearchParams {
type Key = USVString;
type Value = USVString;
fn get_iterable_length(&self) -> u32 {
self.list.borrow().len() as u32
}
fn get_value_at_index(&self, n: u32) -> USVString {
let value = self.list.borrow()[n as usize].1.clone();
USVString(value)
}
fn get_key_at_index(&self, n: u32) -> USVString {
let key = self.list.borrow()[n as usize].0.clone();
USVString(key)
}
}
| {
// Step 2.
*query.list.borrow_mut() = form_urlencoded::parse(init.0.as_bytes())
.into_owned().collect();
} | conditional_block |
urlsearchparams.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsWrap;
use dom::bindings::codegen::UnionTypes::USVStringOrURLSearchParams;
use dom::bindings::error::Fallible;
use dom::bindings::iterable::Iterable;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{DOMString, USVString};
use dom::bindings::weakref::MutableWeakRef;
use dom::globalscope::GlobalScope;
use dom::url::URL;
use dom_struct::dom_struct;
use encoding::types::EncodingRef;
use url::form_urlencoded;
// https://url.spec.whatwg.org/#interface-urlsearchparams
#[dom_struct]
pub struct URLSearchParams {
reflector_: Reflector,
// https://url.spec.whatwg.org/#concept-urlsearchparams-list
list: DomRefCell<Vec<(String, String)>>,
// https://url.spec.whatwg.org/#concept-urlsearchparams-url-object
url: MutableWeakRef<URL>,
}
impl URLSearchParams {
fn new_inherited(url: Option<&URL>) -> URLSearchParams {
URLSearchParams {
reflector_: Reflector::new(),
list: DomRefCell::new(url.map_or(Vec::new(), |url| url.query_pairs())),
url: MutableWeakRef::new(url),
}
}
pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> {
reflect_dom_object(Box::new(URLSearchParams::new_inherited(url)), global,
URLSearchParamsWrap)
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
pub fn Constructor(global: &GlobalScope, init: Option<USVStringOrURLSearchParams>) ->
Fallible<DomRoot<URLSearchParams>> {
// Step 1.
let query = URLSearchParams::new(global, None);
match init {
Some(USVStringOrURLSearchParams::USVString(init)) => {
// Step 2.
*query.list.borrow_mut() = form_urlencoded::parse(init.0.as_bytes())
.into_owned().collect();
},
Some(USVStringOrURLSearchParams::URLSearchParams(init)) => {
// Step 3.
*query.list.borrow_mut() = init.list.borrow().clone();
},
None => {}
}
// Step 4.
Ok(query)
}
pub fn set_list(&self, list: Vec<(String, String)>) {
*self.list.borrow_mut() = list;
}
}
impl URLSearchParamsMethods for URLSearchParams {
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
fn Append(&self, name: USVString, value: USVString) {
// Step 1.
self.list.borrow_mut().push((name.0, value.0));
// Step 2.
self.update_steps();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
fn Delete(&self, name: USVString) {
// Step 1.
self.list.borrow_mut().retain(|&(ref k, _)| k!= &name.0);
// Step 2.
self.update_steps();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
fn Get(&self, name: USVString) -> Option<USVString> {
let list = self.list.borrow();
list.iter().find(|&kv| kv.0 == name.0)
.map(|ref kv| USVString(kv.1.clone()))
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
fn GetAll(&self, name: USVString) -> Vec<USVString> {
let list = self.list.borrow();
list.iter().filter_map(|&(ref k, ref v)| {
if k == &name.0 {
Some(USVString(v.clone()))
} else {
None
}
}).collect()
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
fn Has(&self, name: USVString) -> bool {
let list = self.list.borrow();
list.iter().any(|&(ref k, _)| k == &name.0)
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
fn | (&self, name: USVString, value: USVString) {
{
// Step 1.
let mut list = self.list.borrow_mut();
let mut index = None;
let mut i = 0;
list.retain(|&(ref k, _)| {
if index.is_none() {
if k == &name.0 {
index = Some(i);
} else {
i += 1;
}
true
} else {
k!= &name.0
}
});
match index {
Some(index) => list[index].1 = value.0,
None => list.push((name.0, value.0)), // Step 2.
};
} // Un-borrow self.list
// Step 3.
self.update_steps();
}
// https://url.spec.whatwg.org/#stringification-behavior
fn Stringifier(&self) -> DOMString {
DOMString::from(self.serialize(None))
}
}
impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlencoded-serializer
pub fn serialize(&self, encoding: Option<EncodingRef>) -> String {
let list = self.list.borrow();
form_urlencoded::Serializer::new(String::new())
.encoding_override(encoding)
.extend_pairs(&*list)
.finish()
}
}
impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlsearchparams-update
fn update_steps(&self) {
if let Some(url) = self.url.root() {
url.set_query_pairs(&self.list.borrow())
}
}
}
impl Iterable for URLSearchParams {
type Key = USVString;
type Value = USVString;
fn get_iterable_length(&self) -> u32 {
self.list.borrow().len() as u32
}
fn get_value_at_index(&self, n: u32) -> USVString {
let value = self.list.borrow()[n as usize].1.clone();
USVString(value)
}
fn get_key_at_index(&self, n: u32) -> USVString {
let key = self.list.borrow()[n as usize].0.clone();
USVString(key)
}
}
| Set | identifier_name |
urlsearchparams.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsWrap;
use dom::bindings::codegen::UnionTypes::USVStringOrURLSearchParams;
use dom::bindings::error::Fallible;
use dom::bindings::iterable::Iterable;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{DOMString, USVString};
use dom::bindings::weakref::MutableWeakRef;
use dom::globalscope::GlobalScope;
use dom::url::URL;
use dom_struct::dom_struct;
use encoding::types::EncodingRef;
use url::form_urlencoded;
// https://url.spec.whatwg.org/#interface-urlsearchparams
#[dom_struct]
pub struct URLSearchParams {
reflector_: Reflector,
// https://url.spec.whatwg.org/#concept-urlsearchparams-list
list: DomRefCell<Vec<(String, String)>>,
// https://url.spec.whatwg.org/#concept-urlsearchparams-url-object
url: MutableWeakRef<URL>,
}
impl URLSearchParams {
fn new_inherited(url: Option<&URL>) -> URLSearchParams {
URLSearchParams {
reflector_: Reflector::new(),
list: DomRefCell::new(url.map_or(Vec::new(), |url| url.query_pairs())),
url: MutableWeakRef::new(url),
}
}
pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> {
reflect_dom_object(Box::new(URLSearchParams::new_inherited(url)), global,
URLSearchParamsWrap)
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
pub fn Constructor(global: &GlobalScope, init: Option<USVStringOrURLSearchParams>) ->
Fallible<DomRoot<URLSearchParams>> {
// Step 1.
let query = URLSearchParams::new(global, None);
match init {
Some(USVStringOrURLSearchParams::USVString(init)) => {
// Step 2.
*query.list.borrow_mut() = form_urlencoded::parse(init.0.as_bytes())
.into_owned().collect();
},
Some(USVStringOrURLSearchParams::URLSearchParams(init)) => {
// Step 3.
*query.list.borrow_mut() = init.list.borrow().clone();
},
None => {}
}
// Step 4.
Ok(query)
}
pub fn set_list(&self, list: Vec<(String, String)>) {
*self.list.borrow_mut() = list;
}
}
impl URLSearchParamsMethods for URLSearchParams {
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
fn Append(&self, name: USVString, value: USVString) {
// Step 1.
self.list.borrow_mut().push((name.0, value.0));
// Step 2.
self.update_steps();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
fn Delete(&self, name: USVString) {
// Step 1.
self.list.borrow_mut().retain(|&(ref k, _)| k!= &name.0);
// Step 2.
self.update_steps();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
fn Get(&self, name: USVString) -> Option<USVString> {
let list = self.list.borrow();
list.iter().find(|&kv| kv.0 == name.0)
.map(|ref kv| USVString(kv.1.clone()))
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
fn GetAll(&self, name: USVString) -> Vec<USVString> {
let list = self.list.borrow();
list.iter().filter_map(|&(ref k, ref v)| {
if k == &name.0 {
Some(USVString(v.clone()))
} else {
None
}
}).collect()
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
fn Has(&self, name: USVString) -> bool {
let list = self.list.borrow();
list.iter().any(|&(ref k, _)| k == &name.0)
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
fn Set(&self, name: USVString, value: USVString) {
{
// Step 1.
let mut list = self.list.borrow_mut();
let mut index = None;
let mut i = 0;
list.retain(|&(ref k, _)| {
if index.is_none() {
if k == &name.0 {
index = Some(i);
} else {
i += 1;
}
true
} else {
k!= &name.0
}
});
match index {
Some(index) => list[index].1 = value.0,
None => list.push((name.0, value.0)), // Step 2.
};
} // Un-borrow self.list
// Step 3.
self.update_steps();
}
// https://url.spec.whatwg.org/#stringification-behavior
fn Stringifier(&self) -> DOMString {
DOMString::from(self.serialize(None))
}
}
impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlencoded-serializer
pub fn serialize(&self, encoding: Option<EncodingRef>) -> String {
let list = self.list.borrow();
form_urlencoded::Serializer::new(String::new())
.encoding_override(encoding)
.extend_pairs(&*list)
.finish()
}
}
impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlsearchparams-update
fn update_steps(&self) {
if let Some(url) = self.url.root() {
url.set_query_pairs(&self.list.borrow())
}
}
}
impl Iterable for URLSearchParams {
type Key = USVString;
type Value = USVString;
fn get_iterable_length(&self) -> u32 {
self.list.borrow().len() as u32
} | USVString(value)
}
fn get_key_at_index(&self, n: u32) -> USVString {
let key = self.list.borrow()[n as usize].0.clone();
USVString(key)
}
} |
fn get_value_at_index(&self, n: u32) -> USVString {
let value = self.list.borrow()[n as usize].1.clone(); | random_line_split |
urlsearchparams.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsMethods;
use dom::bindings::codegen::Bindings::URLSearchParamsBinding::URLSearchParamsWrap;
use dom::bindings::codegen::UnionTypes::USVStringOrURLSearchParams;
use dom::bindings::error::Fallible;
use dom::bindings::iterable::Iterable;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::bindings::str::{DOMString, USVString};
use dom::bindings::weakref::MutableWeakRef;
use dom::globalscope::GlobalScope;
use dom::url::URL;
use dom_struct::dom_struct;
use encoding::types::EncodingRef;
use url::form_urlencoded;
// https://url.spec.whatwg.org/#interface-urlsearchparams
#[dom_struct]
pub struct URLSearchParams {
reflector_: Reflector,
// https://url.spec.whatwg.org/#concept-urlsearchparams-list
list: DomRefCell<Vec<(String, String)>>,
// https://url.spec.whatwg.org/#concept-urlsearchparams-url-object
url: MutableWeakRef<URL>,
}
impl URLSearchParams {
fn new_inherited(url: Option<&URL>) -> URLSearchParams {
URLSearchParams {
reflector_: Reflector::new(),
list: DomRefCell::new(url.map_or(Vec::new(), |url| url.query_pairs())),
url: MutableWeakRef::new(url),
}
}
pub fn new(global: &GlobalScope, url: Option<&URL>) -> DomRoot<URLSearchParams> {
reflect_dom_object(Box::new(URLSearchParams::new_inherited(url)), global,
URLSearchParamsWrap)
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-urlsearchparams
pub fn Constructor(global: &GlobalScope, init: Option<USVStringOrURLSearchParams>) ->
Fallible<DomRoot<URLSearchParams>> {
// Step 1.
let query = URLSearchParams::new(global, None);
match init {
Some(USVStringOrURLSearchParams::USVString(init)) => {
// Step 2.
*query.list.borrow_mut() = form_urlencoded::parse(init.0.as_bytes())
.into_owned().collect();
},
Some(USVStringOrURLSearchParams::URLSearchParams(init)) => {
// Step 3.
*query.list.borrow_mut() = init.list.borrow().clone();
},
None => {}
}
// Step 4.
Ok(query)
}
pub fn set_list(&self, list: Vec<(String, String)>) {
*self.list.borrow_mut() = list;
}
}
impl URLSearchParamsMethods for URLSearchParams {
// https://url.spec.whatwg.org/#dom-urlsearchparams-append
fn Append(&self, name: USVString, value: USVString) {
// Step 1.
self.list.borrow_mut().push((name.0, value.0));
// Step 2.
self.update_steps();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-delete
fn Delete(&self, name: USVString) {
// Step 1.
self.list.borrow_mut().retain(|&(ref k, _)| k!= &name.0);
// Step 2.
self.update_steps();
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-get
fn Get(&self, name: USVString) -> Option<USVString> {
let list = self.list.borrow();
list.iter().find(|&kv| kv.0 == name.0)
.map(|ref kv| USVString(kv.1.clone()))
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-getall
fn GetAll(&self, name: USVString) -> Vec<USVString> {
let list = self.list.borrow();
list.iter().filter_map(|&(ref k, ref v)| {
if k == &name.0 {
Some(USVString(v.clone()))
} else {
None
}
}).collect()
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-has
fn Has(&self, name: USVString) -> bool {
let list = self.list.borrow();
list.iter().any(|&(ref k, _)| k == &name.0)
}
// https://url.spec.whatwg.org/#dom-urlsearchparams-set
fn Set(&self, name: USVString, value: USVString) {
{
// Step 1.
let mut list = self.list.borrow_mut();
let mut index = None;
let mut i = 0;
list.retain(|&(ref k, _)| {
if index.is_none() {
if k == &name.0 {
index = Some(i);
} else {
i += 1;
}
true
} else {
k!= &name.0
}
});
match index {
Some(index) => list[index].1 = value.0,
None => list.push((name.0, value.0)), // Step 2.
};
} // Un-borrow self.list
// Step 3.
self.update_steps();
}
// https://url.spec.whatwg.org/#stringification-behavior
fn Stringifier(&self) -> DOMString {
DOMString::from(self.serialize(None))
}
}
impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlencoded-serializer
pub fn serialize(&self, encoding: Option<EncodingRef>) -> String |
}
impl URLSearchParams {
// https://url.spec.whatwg.org/#concept-urlsearchparams-update
fn update_steps(&self) {
if let Some(url) = self.url.root() {
url.set_query_pairs(&self.list.borrow())
}
}
}
impl Iterable for URLSearchParams {
type Key = USVString;
type Value = USVString;
fn get_iterable_length(&self) -> u32 {
self.list.borrow().len() as u32
}
fn get_value_at_index(&self, n: u32) -> USVString {
let value = self.list.borrow()[n as usize].1.clone();
USVString(value)
}
fn get_key_at_index(&self, n: u32) -> USVString {
let key = self.list.borrow()[n as usize].0.clone();
USVString(key)
}
}
| {
let list = self.list.borrow();
form_urlencoded::Serializer::new(String::new())
.encoding_override(encoding)
.extend_pairs(&*list)
.finish()
} | identifier_body |
result.rs | [I/O](../../std/io/index.html).
//!
//! A simple function returning `Result` might be
//! defined and used like so:
//!
//! ~~~
//! #[deriving(Show)]
//! enum Version { Version1, Version2 }
//!
//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
//! if header.len() < 1 {
//! return Err("invalid header length");
//! }
//! match header[0] {
//! 1 => Ok(Version1),
//! 2 => Ok(Version2),
//! _ => Err("invalid version")
//! }
//! }
//!
//! let version = parse_version(&[1, 2, 3, 4]);
//! match version {
//! Ok(v) => {
//! println!("working with version: {}", v);
//! }
//! Err(e) => {
//! println!("error parsing header: {}", e);
//! }
//! }
//! ~~~
//!
//! Pattern matching on `Result`s is clear and straightforward for
//! simple cases, but `Result` comes with some convenience methods
//! that make working it more succinct.
//!
//! ~~~
//! let good_result: Result<int, int> = Ok(10);
//! let bad_result: Result<int, int> = Err(10);
//!
//! // The `is_ok` and `is_err` methods do what they say.
//! assert!(good_result.is_ok() &&!good_result.is_err());
//! assert!(bad_result.is_err() &&!bad_result.is_ok());
//!
//! // `map` consumes the `Result` and produces another.
//! let good_result: Result<int, int> = good_result.map(|i| i + 1);
//! let bad_result: Result<int, int> = bad_result.map(|i| i - 1);
//!
//! // Use `and_then` to continue the computation.
//! let good_result: Result<bool, int> = good_result.and_then(|i| Ok(i == 11));
//!
//! // Use `or_else` to handle the error.
//! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
//!
//! // Consume the result and return the contents with `unwrap`.
//! let final_awesome_result = good_result.ok().unwrap();
//! ~~~
//!
//! # Results must be used
//!
//! A common problem with using return values to indicate errors is
//! that it is easy to ignore the return value, thus failing to handle
//! the error. Result is annotated with the #[must_use] attribute,
//! which will cause the compiler to issue a warning when a Result
//! value is ignored. This makes `Result` especially useful with
//! functions that may encounter errors but don't otherwise return a
//! useful value.
//!
//! Consider the `write_line` method defined for I/O types
//! by the [`Writer`](../io/trait.Writer.html) trait:
//!
//! ~~~
//! use std::io::IoError;
//!
//! trait Writer {
//! fn write_line(&mut self, s: &str) -> Result<(), IoError>;
//! }
//! ~~~
//!
//! *Note: The actual definition of `Writer` uses `IoResult`, which
//! is just a synonym for `Result<T, IoError>`.*
//!
//! This method doesn't produce a value, but the write may
//! fail. It's crucial to handle the error case, and *not* write
//! something like this:
//!
//! ~~~ignore
//! use std::io::{File, Open, Write};
//!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! // If `write_line` errors, then we'll never know, because the return
//! // value is ignored.
//! file.write_line("important message");
//! drop(file);
//! ~~~
//!
//! If you *do* write that in Rust, the compiler will by give you a
//! warning (by default, controlled by the `unused_must_use` lint).
//!
//! You might instead, if you don't want to handle the error, simply
//! fail, by converting to an `Option` with `ok`, then asserting
//! success with `expect`. This will fail if the write fails, proving
//! a marginally useful message indicating why:
//!
//! ~~~no_run
//! use std::io::{File, Open, Write};
//!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! file.write_line("important message").ok().expect("failed to write message");
//! drop(file);
//! ~~~
//!
//! You might also simply assert success:
//!
//! ~~~no_run
//! # use std::io::{File, Open, Write};
//!
//! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! assert!(file.write_line("important message").is_ok());
//! # drop(file);
//! ~~~
//!
//! Or propagate the error up the call stack with `try!`:
//!
//! ~~~
//! # use std::io::{File, Open, Write, IoError};
//! fn write_message() -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! try!(file.write_line("important message"));
//! drop(file);
//! return Ok(());
//! }
//! ~~~
//!
//! # The `try!` macro
//!
//! When writing code that calls many functions that return the
//! `Result` type, the error handling can be tedious. The `try!`
//! macro hides some of the boilerplate of propagating errors up the
//! call stack.
//!
//! It replaces this:
//!
//! ~~~
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info {
//! name: String,
//! age: int,
//! rating: int
//! }
//!
//! fn write_info(info: &Info) -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
//! // Early return on error
//! match file.write_line(format!("name: {}", info.name).as_slice()) {
//! Ok(_) => (), | //! Err(e) => return Err(e)
//! }
//! return file.write_line(format!("rating: {}", info.rating).as_slice());
//! }
//! ~~~
//!
//! With this:
//!
//! ~~~
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info {
//! name: String,
//! age: int,
//! rating: int
//! }
//!
//! fn write_info(info: &Info) -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
//! // Early return on error
//! try!(file.write_line(format!("name: {}", info.name).as_slice()));
//! try!(file.write_line(format!("age: {}", info.age).as_slice()));
//! try!(file.write_line(format!("rating: {}", info.rating).as_slice()));
//! return Ok(());
//! }
//! ~~~
//!
//! *It's much nicer!*
//!
//! Wrapping an expression in `try!` will result in the unwrapped
//! success (`Ok`) value, unless the result is `Err`, in which case
//! `Err` is returned early from the enclosing function. Its simple definition
//! makes it clear:
//!
//! ~~~
//! # #![feature(macro_rules)]
//! macro_rules! try(
//! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
//! )
//! # fn main() { }
//! ~~~
//!
//! `try!` is imported by the prelude, and is available everywhere.
//!
//! # `Result` and `Option`
//!
//! The `Result` and [`Option`](../option/index.html) types are
//! similar and complementary: they are often employed to indicate a
//! lack of a return value; and they are trivially converted between
//! each other, so `Result`s are often handled by first converting to
//! `Option` with the [`ok`](type.Result.html#method.ok) and
//! [`err`](type.Result.html#method.ok) methods.
//!
//! Whereas `Option` only indicates the lack of a value, `Result` is
//! specifically for error reporting, and carries with it an error
//! value. Sometimes `Option` is used for indicating errors, but this
//! is only for simple cases and is generally discouraged. Even when
//! there is no useful error value to return, prefer `Result<T, ()>`.
//!
//! Converting to an `Option` with `ok()` to handle an error:
//!
//! ~~~
//! use std::io::Timer;
//! let mut t = Timer::new().ok().expect("failed to create timer!");
//! ~~~
//!
//! # `Result` vs. `fail!`
//!
//! `Result` is for recoverable errors; `fail!` is for unrecoverable
//! errors. Callers should always be able to avoid failure if they
//! take the proper precautions, for example, calling `is_some()`
//! on an `Option` type before calling `unwrap`.
//!
//! The suitability of `fail!` as an error handling mechanism is
//! limited by Rust's lack of any way to "catch" and resume execution
//! from a thrown exception. Therefore using failure for error
//! handling requires encapsulating fallible code in a task. Calling
//! the `fail!` macro, or invoking `fail!` indirectly should be
//! avoided as an error reporting strategy. Failure is only for
//! unrecoverable errors and a failing task is typically the sign of
//! a bug.
//!
//! A module that instead returns `Results` is alerting the caller
//! that failure is possible, and providing precise control over how
//! it is handled.
//!
//! Furthermore, failure may not be recoverable at all, depending on
//! the context. The caller of `fail!` should assume that execution
//! will not resume after failure, that failure is catastrophic.
#![stable]
use clone::Clone;
use cmp::PartialEq;
use std::fmt::Show;
use slice;
use slice::Slice;
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use option::{None, Option, Some};
/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
///
/// See the [`std::result`](index.html) module documentation for details.
#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Show)]
#[must_use]
#[stable]
pub enum Result<T, E> {
/// Contains the success value
Ok(T),
/// Contains the error value
Err(E)
}
/////////////////////////////////////////////////////////////////////////////
// Type implementation
/////////////////////////////////////////////////////////////////////////////
impl<T, E> Result<T, E> {
/////////////////////////////////////////////////////////////////////////
// Querying the contained values
/////////////////////////////////////////////////////////////////////////
/// Returns true if the result is `Ok`
///
/// # Example
///
/// ~~~
/// use std::io::{File, Open, Write};
///
/// # fn do_not_run_example() { // creates a file
/// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
/// assert!(file.write_line("it's cold in here").is_ok());
/// # }
/// ~~~
#[inline]
#[stable]
pub fn is_ok(&self) -> bool {
match *self {
Ok(_) => true,
Err(_) => false
}
}
/// Returns true if the result is `Err`
///
/// # Example
///
/// ~~~
/// use std::io::{File, Open, Read};
///
/// // When opening with `Read` access, if the file does not exist
/// // then `open_mode` returns an error.
/// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
/// assert!(bogus.is_err());
/// ~~~
#[inline]
#[stable]
pub fn is_err(&self) -> bool {
!self.is_ok()
}
/////////////////////////////////////////////////////////////////////////
// Adapter for each variant
/////////////////////////////////////////////////////////////////////////
/// Convert from `Result<T, E>` to `Option<T>`
///
/// Converts `self` into an `Option<T>`, consuming `self`,
/// and discarding the error, if any.
///
/// To convert to an `Option` without discarding the error value,
/// use `as_ref` to first convert the `Result<T, E>` into a
/// `Result<&T, &E>`.
///
/// # Examples
///
/// ~~~{.should_fail}
/// use std::io::{File, IoResult};
///
/// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
/// let bdays: File = bdays.ok().expect("unable to open birthday file");
/// ~~~
#[inline]
#[stable]
pub fn ok(self) -> Option<T> {
match self {
Ok(x) => Some(x),
Err(_) => None,
}
}
/// Convert from `Result<T, E>` to `Option<E>`
///
/// Converts `self` into an `Option<T>`, consuming `self`,
/// and discarding the value, if any.
#[inline]
#[stable]
pub fn err(self) -> Option<E> {
match self {
Ok(_) => None,
Err(x) => Some(x),
}
}
/////////////////////////////////////////////////////////////////////////
// Adapter for working with references
/////////////////////////////////////////////////////////////////////////
/// Convert from `Result<T, E>` to `Result<&T, &E>`
///
/// Produces a new `Result`, containing a reference
/// into the original, leaving the original in place.
#[inline]
#[stable]
pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
match *self {
Ok(ref x) => Ok(x),
Err(ref x) => Err(x),
}
}
/// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
#[inline]
#[unstable = "waiting for mut conventions"]
pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
match *self {
Ok(ref mut x) => Ok(x),
Err(ref mut x) => Err(x),
}
}
/// Convert from `Result<T, E>` to `&mut [T]` (without copying)
#[inline]
#[unstable = "waiting for mut conventions"]
pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
match *self {
Ok(ref mut x) => slice::mut_ref_slice(x),
Err(_) => {
// work around lack of implicit coercion from fixed-size array to slice
let emp: &mut [_] = &mut [];
emp
}
}
}
/////////////////////////////////////////////////////////////////////////
// Transforming contained values
/////////////////////////////////////////////////////////////////////////
/// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
/// contained `Ok` value, leaving an `Err` value untouched.
///
/// This function can be used to compose the results of two functions.
///
/// # Examples
///
/// Sum the lines of a buffer by mapping strings to numbers,
/// ignoring I/O and parse errors:
///
/// ~~~
/// use std::io::{BufReader, IoResult};
///
/// let buffer = "1\n2\n3\n4\n";
/// let mut reader = BufReader::new(buffer.as_bytes());
///
/// let mut sum = 0;
///
/// while!reader.eof() {
/// let line: IoResult<String> = reader.read_line();
/// // Convert the string line to a number using `map` and `from_str`
/// let val: IoResult<int> = line.map(|line| {
/// from_str::<int>(line.as_slice().trim_right()).unwrap_or(0)
/// });
/// // Add the value if there were no errors, otherwise add 0
/// sum += val.ok().unwrap_or(0);
/// }
///
/// assert!(sum == 10);
/// ~~~
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
match self {
Ok(t) => Ok(op(t)),
Err(e) => Err(e)
}
}
/// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
/// contained `Err` value, leaving an `Ok` value untouched.
///
/// This function can be used to pass through a successful result while handling
/// an error.
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
match self {
Ok(t) => Ok(t),
Err(e) => Err(op(e))
}
}
/////////////////////////////////////////////////////////////////////////
// Iterator constructors
/////////////////////////////////////////////////////////////////////////
/// Returns an iterator over the possibly contained value.
#[inline]
#[unstable = "waiting for iterator conventions"]
pub fn iter<'r>(&'r self) -> Item<&'r T> {
Item{opt: self.as_ref().ok()}
}
/// Returns a mutable iterator over the possibly contained value.
#[inline]
#[unstable = "waiting for iterator conventions"]
pub fn mut_iter<'r>(&'r mut self) -> Item<&'r mut T> {
Item{opt: self.as_mut().ok()}
}
/// Returns a consuming iterator over the possibly contained value.
#[inline]
#[unstable = "waiting for iterator conventions"]
pub fn move_iter(self) -> Item<T> {
Item{opt: self.ok()}
}
////////////////////////////////////////////////////////////////////////
// Boolean operations on the values, eager and lazy
/////////////////////////////////////////////////////////////////////////
/// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
#[inline]
#[stable]
pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
match self {
Ok(_) => res,
Err(e) => Err(e),
}
}
/// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
///
/// This function can be used for control flow based on result values
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
match self {
Ok(t) => op(t),
Err(e) => Err(e),
}
}
/// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
#[inline]
#[stable]
pub fn or(self, res: Result<T, E>) -> Result<T, E> {
match self {
Ok(_) => self,
Err(_) => res,
}
}
/// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
///
/// This function can be used for control flow based on result values
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
match self {
Ok(t) => Ok(t),
Err(e) => op(e),
}
}
/// Unwraps a result, yielding the content of an `Ok`.
/// Else it returns `optb`.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap_or(self, optb: T) -> T {
match self {
Ok(t) => t,
Err(_) => optb
}
}
/// Unwraps a result, yielding the content of an `Ok`.
/// If the value is an `Err` then it calls `op` with its value.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap_or_else(self, op: |E| -> T) -> T {
match self {
Ok(t) => t,
Err(e) => op(e)
}
}
/// Deprecated name for `unwrap_or_else()`.
#[deprecated = "replaced by.unwrap_or_else()"]
#[inline]
pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
self.unwrap_or_else(op)
}
}
impl<T, E: Show> Result<T, E> {
/// Unwraps a result, yielding the content of an `Ok`.
///
/// # Failure
///
/// Fails if the value is an `Err`, with a custom failure message provided
/// by the `Err`'s value.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap(self) -> T {
match self {
Ok(t) => t,
Err(e) =>
fail!("called `Result::unwrap()` on an `Err` value: {}", e)
}
}
}
impl<T: Show, E> Result<T, E> {
/// Unwraps a result, yielding the content of an `Err`.
///
/// # Failure
///
/// Fails if the value is an `Ok`, with a custom failure message provided
/// by the `Ok`'s value.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap_err(self) -> E {
match self {
Ok(t) =>
fail!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
Err(e) => e
}
}
}
/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
impl<T, E> Slice<T> for Result<T, E> {
/// Convert from `Result<T, E>` to `&[T]` (without copying)
#[inline]
#[stable]
fn as_slice<'a>(&'a self) -> &'a [T] {
match *self {
Ok(ref x) => slice::ref_slice(x),
Err(_) => {
// work around lack of implicit coercion from fixed-size array to slice
let emp: &[_] = &[];
emp
}
}
}
}
/////////////////////////////////////////////////////////////////////////////
// The Result Iterator
/////////////////////////////////////////////////////////////////////////////
/// A `Result` iterator that yields either one or zero elements
///
/// The `Item` iterator is returned by the `iter`, `mut_iter` and `move_iter`
/// methods on `Result`.
#[deriving(Clone)]
#[unstable = "waiting for iterator conventions"]
pub struct Item<T> {
opt: Option<T>
}
impl<T> Iterator<T> for Item<T> {
#[inline]
fn next(&mut self) -> Option<T> {
self.opt.take()
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
match self.opt {
Some(_) => (1, Some(1)),
None => (0, Some(0)),
}
}
}
impl<A> DoubleEndedIterator<A> for Item<A> {
#[inline]
fn next_back(&mut self) -> Option<A> {
self.opt.take()
}
}
impl<A> ExactSize<A> for Item<A> {}
/////////////////////////////////////////////////////////////////////////////
// Free functions
/////////////////////////////////////////////////////////////////////////////
/// Deprecated: use `Iterator::collect`.
#[inline]
#[deprecated = "use Iterator::collect instead"]
pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(mut iter: Iter)
-> Result<V, E> {
iter.collect()
}
impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
/// Takes each element in the `Iterator`: if it is an `Err`, no further
/// elements are taken, and the `Err` is returned. Should no `Err` occur, a
/// container with the values of each `Result` is returned.
///
/// Here is an example which increments every integer in a vector,
/// checking for overflow:
///
/// ```rust
/// use std::uint;
///
/// let v = vec!(1u, 2u);
/// let res: Result<Vec<uint>, &'static str> = v.iter().map(|x: &uint|
/// if *x == uint::MAX { Err("Overflow!") }
/// else { Ok(x + 1) }
/// ).collect();
/// assert!(res == Ok(vec!(2u, 3u)));
/// ```
#[inline]
fn from_iter<I: Iterator<Result<A, E>>>(iter: I) -> Result<V, E> {
// FIXME(#11084): This could be replaced with Iterator::scan when this
// performance bug is closed.
struct Adapter<Iter, E> {
iter: Iter,
err: Option<E>,
}
impl<T, E, Iter: Iterator<Result<T, E>>> Iterator<T> for Adapter<Iter, E> {
#[inline]
fn next(&mut self) -> Option<T> {
match self.iter.next() {
Some(Ok(value)) => Some(value),
Some(Err(err)) => {
| //! Err(e) => return Err(e)
//! }
//! match file.write_line(format!("age: {}", info.age).as_slice()) {
//! Ok(_) => (), | random_line_split |
result.rs | /O](../../std/io/index.html).
//!
//! A simple function returning `Result` might be
//! defined and used like so:
//!
//! ~~~
//! #[deriving(Show)]
//! enum Version { Version1, Version2 }
//!
//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
//! if header.len() < 1 {
//! return Err("invalid header length");
//! }
//! match header[0] {
//! 1 => Ok(Version1),
//! 2 => Ok(Version2),
//! _ => Err("invalid version")
//! }
//! }
//!
//! let version = parse_version(&[1, 2, 3, 4]);
//! match version {
//! Ok(v) => {
//! println!("working with version: {}", v);
//! }
//! Err(e) => {
//! println!("error parsing header: {}", e);
//! }
//! }
//! ~~~
//!
//! Pattern matching on `Result`s is clear and straightforward for
//! simple cases, but `Result` comes with some convenience methods
//! that make working it more succinct.
//!
//! ~~~
//! let good_result: Result<int, int> = Ok(10);
//! let bad_result: Result<int, int> = Err(10);
//!
//! // The `is_ok` and `is_err` methods do what they say.
//! assert!(good_result.is_ok() &&!good_result.is_err());
//! assert!(bad_result.is_err() &&!bad_result.is_ok());
//!
//! // `map` consumes the `Result` and produces another.
//! let good_result: Result<int, int> = good_result.map(|i| i + 1);
//! let bad_result: Result<int, int> = bad_result.map(|i| i - 1);
//!
//! // Use `and_then` to continue the computation.
//! let good_result: Result<bool, int> = good_result.and_then(|i| Ok(i == 11));
//!
//! // Use `or_else` to handle the error.
//! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
//!
//! // Consume the result and return the contents with `unwrap`.
//! let final_awesome_result = good_result.ok().unwrap();
//! ~~~
//!
//! # Results must be used
//!
//! A common problem with using return values to indicate errors is
//! that it is easy to ignore the return value, thus failing to handle
//! the error. Result is annotated with the #[must_use] attribute,
//! which will cause the compiler to issue a warning when a Result
//! value is ignored. This makes `Result` especially useful with
//! functions that may encounter errors but don't otherwise return a
//! useful value.
//!
//! Consider the `write_line` method defined for I/O types
//! by the [`Writer`](../io/trait.Writer.html) trait:
//!
//! ~~~
//! use std::io::IoError;
//!
//! trait Writer {
//! fn write_line(&mut self, s: &str) -> Result<(), IoError>;
//! }
//! ~~~
//!
//! *Note: The actual definition of `Writer` uses `IoResult`, which
//! is just a synonym for `Result<T, IoError>`.*
//!
//! This method doesn't produce a value, but the write may
//! fail. It's crucial to handle the error case, and *not* write
//! something like this:
//!
//! ~~~ignore
//! use std::io::{File, Open, Write};
//!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! // If `write_line` errors, then we'll never know, because the return
//! // value is ignored.
//! file.write_line("important message");
//! drop(file);
//! ~~~
//!
//! If you *do* write that in Rust, the compiler will by give you a
//! warning (by default, controlled by the `unused_must_use` lint).
//!
//! You might instead, if you don't want to handle the error, simply
//! fail, by converting to an `Option` with `ok`, then asserting
//! success with `expect`. This will fail if the write fails, proving
//! a marginally useful message indicating why:
//!
//! ~~~no_run
//! use std::io::{File, Open, Write};
//!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! file.write_line("important message").ok().expect("failed to write message");
//! drop(file);
//! ~~~
//!
//! You might also simply assert success:
//!
//! ~~~no_run
//! # use std::io::{File, Open, Write};
//!
//! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! assert!(file.write_line("important message").is_ok());
//! # drop(file);
//! ~~~
//!
//! Or propagate the error up the call stack with `try!`:
//!
//! ~~~
//! # use std::io::{File, Open, Write, IoError};
//! fn write_message() -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! try!(file.write_line("important message"));
//! drop(file);
//! return Ok(());
//! }
//! ~~~
//!
//! # The `try!` macro
//!
//! When writing code that calls many functions that return the
//! `Result` type, the error handling can be tedious. The `try!`
//! macro hides some of the boilerplate of propagating errors up the
//! call stack.
//!
//! It replaces this:
//!
//! ~~~
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info {
//! name: String,
//! age: int,
//! rating: int
//! }
//!
//! fn write_info(info: &Info) -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
//! // Early return on error
//! match file.write_line(format!("name: {}", info.name).as_slice()) {
//! Ok(_) => (),
//! Err(e) => return Err(e)
//! }
//! match file.write_line(format!("age: {}", info.age).as_slice()) {
//! Ok(_) => (),
//! Err(e) => return Err(e)
//! }
//! return file.write_line(format!("rating: {}", info.rating).as_slice());
//! }
//! ~~~
//!
//! With this:
//!
//! ~~~
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info {
//! name: String,
//! age: int,
//! rating: int
//! }
//!
//! fn write_info(info: &Info) -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
//! // Early return on error
//! try!(file.write_line(format!("name: {}", info.name).as_slice()));
//! try!(file.write_line(format!("age: {}", info.age).as_slice()));
//! try!(file.write_line(format!("rating: {}", info.rating).as_slice()));
//! return Ok(());
//! }
//! ~~~
//!
//! *It's much nicer!*
//!
//! Wrapping an expression in `try!` will result in the unwrapped
//! success (`Ok`) value, unless the result is `Err`, in which case
//! `Err` is returned early from the enclosing function. Its simple definition
//! makes it clear:
//!
//! ~~~
//! # #![feature(macro_rules)]
//! macro_rules! try(
//! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
//! )
//! # fn main() { }
//! ~~~
//!
//! `try!` is imported by the prelude, and is available everywhere.
//!
//! # `Result` and `Option`
//!
//! The `Result` and [`Option`](../option/index.html) types are
//! similar and complementary: they are often employed to indicate a
//! lack of a return value; and they are trivially converted between
//! each other, so `Result`s are often handled by first converting to
//! `Option` with the [`ok`](type.Result.html#method.ok) and
//! [`err`](type.Result.html#method.ok) methods.
//!
//! Whereas `Option` only indicates the lack of a value, `Result` is
//! specifically for error reporting, and carries with it an error
//! value. Sometimes `Option` is used for indicating errors, but this
//! is only for simple cases and is generally discouraged. Even when
//! there is no useful error value to return, prefer `Result<T, ()>`.
//!
//! Converting to an `Option` with `ok()` to handle an error:
//!
//! ~~~
//! use std::io::Timer;
//! let mut t = Timer::new().ok().expect("failed to create timer!");
//! ~~~
//!
//! # `Result` vs. `fail!`
//!
//! `Result` is for recoverable errors; `fail!` is for unrecoverable
//! errors. Callers should always be able to avoid failure if they
//! take the proper precautions, for example, calling `is_some()`
//! on an `Option` type before calling `unwrap`.
//!
//! The suitability of `fail!` as an error handling mechanism is
//! limited by Rust's lack of any way to "catch" and resume execution
//! from a thrown exception. Therefore using failure for error
//! handling requires encapsulating fallible code in a task. Calling
//! the `fail!` macro, or invoking `fail!` indirectly should be
//! avoided as an error reporting strategy. Failure is only for
//! unrecoverable errors and a failing task is typically the sign of
//! a bug.
//!
//! A module that instead returns `Results` is alerting the caller
//! that failure is possible, and providing precise control over how
//! it is handled.
//!
//! Furthermore, failure may not be recoverable at all, depending on
//! the context. The caller of `fail!` should assume that execution
//! will not resume after failure, that failure is catastrophic.
#![stable]
use clone::Clone;
use cmp::PartialEq;
use std::fmt::Show;
use slice;
use slice::Slice;
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use option::{None, Option, Some};
/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
///
/// See the [`std::result`](index.html) module documentation for details.
#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Show)]
#[must_use]
#[stable]
pub enum Result<T, E> {
/// Contains the success value
Ok(T),
/// Contains the error value
Err(E)
}
/////////////////////////////////////////////////////////////////////////////
// Type implementation
/////////////////////////////////////////////////////////////////////////////
impl<T, E> Result<T, E> {
/////////////////////////////////////////////////////////////////////////
// Querying the contained values
/////////////////////////////////////////////////////////////////////////
/// Returns true if the result is `Ok`
///
/// # Example
///
/// ~~~
/// use std::io::{File, Open, Write};
///
/// # fn do_not_run_example() { // creates a file
/// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
/// assert!(file.write_line("it's cold in here").is_ok());
/// # }
/// ~~~
#[inline]
#[stable]
pub fn is_ok(&self) -> bool {
match *self {
Ok(_) => true,
Err(_) => false
}
}
/// Returns true if the result is `Err`
///
/// # Example
///
/// ~~~
/// use std::io::{File, Open, Read};
///
/// // When opening with `Read` access, if the file does not exist
/// // then `open_mode` returns an error.
/// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
/// assert!(bogus.is_err());
/// ~~~
#[inline]
#[stable]
pub fn is_err(&self) -> bool {
!self.is_ok()
}
/////////////////////////////////////////////////////////////////////////
// Adapter for each variant
/////////////////////////////////////////////////////////////////////////
/// Convert from `Result<T, E>` to `Option<T>`
///
/// Converts `self` into an `Option<T>`, consuming `self`,
/// and discarding the error, if any.
///
/// To convert to an `Option` without discarding the error value,
/// use `as_ref` to first convert the `Result<T, E>` into a
/// `Result<&T, &E>`.
///
/// # Examples
///
/// ~~~{.should_fail}
/// use std::io::{File, IoResult};
///
/// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
/// let bdays: File = bdays.ok().expect("unable to open birthday file");
/// ~~~
#[inline]
#[stable]
pub fn ok(self) -> Option<T> {
match self {
Ok(x) => Some(x),
Err(_) => None,
}
}
/// Convert from `Result<T, E>` to `Option<E>`
///
/// Converts `self` into an `Option<T>`, consuming `self`,
/// and discarding the value, if any.
#[inline]
#[stable]
pub fn err(self) -> Option<E> {
match self {
Ok(_) => None,
Err(x) => Some(x),
}
}
/////////////////////////////////////////////////////////////////////////
// Adapter for working with references
/////////////////////////////////////////////////////////////////////////
/// Convert from `Result<T, E>` to `Result<&T, &E>`
///
/// Produces a new `Result`, containing a reference
/// into the original, leaving the original in place.
#[inline]
#[stable]
pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
match *self {
Ok(ref x) => Ok(x),
Err(ref x) => Err(x),
}
}
/// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
#[inline]
#[unstable = "waiting for mut conventions"]
pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
match *self {
Ok(ref mut x) => Ok(x),
Err(ref mut x) => Err(x),
}
}
/// Convert from `Result<T, E>` to `&mut [T]` (without copying)
#[inline]
#[unstable = "waiting for mut conventions"]
pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
match *self {
Ok(ref mut x) => slice::mut_ref_slice(x),
Err(_) => {
// work around lack of implicit coercion from fixed-size array to slice
let emp: &mut [_] = &mut [];
emp
}
}
}
/////////////////////////////////////////////////////////////////////////
// Transforming contained values
/////////////////////////////////////////////////////////////////////////
/// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
/// contained `Ok` value, leaving an `Err` value untouched.
///
/// This function can be used to compose the results of two functions.
///
/// # Examples
///
/// Sum the lines of a buffer by mapping strings to numbers,
/// ignoring I/O and parse errors:
///
/// ~~~
/// use std::io::{BufReader, IoResult};
///
/// let buffer = "1\n2\n3\n4\n";
/// let mut reader = BufReader::new(buffer.as_bytes());
///
/// let mut sum = 0;
///
/// while!reader.eof() {
/// let line: IoResult<String> = reader.read_line();
/// // Convert the string line to a number using `map` and `from_str`
/// let val: IoResult<int> = line.map(|line| {
/// from_str::<int>(line.as_slice().trim_right()).unwrap_or(0)
/// });
/// // Add the value if there were no errors, otherwise add 0
/// sum += val.ok().unwrap_or(0);
/// }
///
/// assert!(sum == 10);
/// ~~~
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
match self {
Ok(t) => Ok(op(t)),
Err(e) => Err(e)
}
}
/// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
/// contained `Err` value, leaving an `Ok` value untouched.
///
/// This function can be used to pass through a successful result while handling
/// an error.
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
match self {
Ok(t) => Ok(t),
Err(e) => Err(op(e))
}
}
/////////////////////////////////////////////////////////////////////////
// Iterator constructors
/////////////////////////////////////////////////////////////////////////
/// Returns an iterator over the possibly contained value.
#[inline]
#[unstable = "waiting for iterator conventions"]
pub fn iter<'r>(&'r self) -> Item<&'r T> {
Item{opt: self.as_ref().ok()}
}
/// Returns a mutable iterator over the possibly contained value.
#[inline]
#[unstable = "waiting for iterator conventions"]
pub fn mut_iter<'r>(&'r mut self) -> Item<&'r mut T> {
Item{opt: self.as_mut().ok()}
}
/// Returns a consuming iterator over the possibly contained value.
#[inline]
#[unstable = "waiting for iterator conventions"]
pub fn move_iter(self) -> Item<T> {
Item{opt: self.ok()}
}
////////////////////////////////////////////////////////////////////////
// Boolean operations on the values, eager and lazy
/////////////////////////////////////////////////////////////////////////
/// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
#[inline]
#[stable]
pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> |
/// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
///
/// This function can be used for control flow based on result values
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
match self {
Ok(t) => op(t),
Err(e) => Err(e),
}
}
/// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
#[inline]
#[stable]
pub fn or(self, res: Result<T, E>) -> Result<T, E> {
match self {
Ok(_) => self,
Err(_) => res,
}
}
/// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
///
/// This function can be used for control flow based on result values
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
match self {
Ok(t) => Ok(t),
Err(e) => op(e),
}
}
/// Unwraps a result, yielding the content of an `Ok`.
/// Else it returns `optb`.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap_or(self, optb: T) -> T {
match self {
Ok(t) => t,
Err(_) => optb
}
}
/// Unwraps a result, yielding the content of an `Ok`.
/// If the value is an `Err` then it calls `op` with its value.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap_or_else(self, op: |E| -> T) -> T {
match self {
Ok(t) => t,
Err(e) => op(e)
}
}
/// Deprecated name for `unwrap_or_else()`.
#[deprecated = "replaced by.unwrap_or_else()"]
#[inline]
pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
self.unwrap_or_else(op)
}
}
impl<T, E: Show> Result<T, E> {
/// Unwraps a result, yielding the content of an `Ok`.
///
/// # Failure
///
/// Fails if the value is an `Err`, with a custom failure message provided
/// by the `Err`'s value.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap(self) -> T {
match self {
Ok(t) => t,
Err(e) =>
fail!("called `Result::unwrap()` on an `Err` value: {}", e)
}
}
}
impl<T: Show, E> Result<T, E> {
/// Unwraps a result, yielding the content of an `Err`.
///
/// # Failure
///
/// Fails if the value is an `Ok`, with a custom failure message provided
/// by the `Ok`'s value.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap_err(self) -> E {
match self {
Ok(t) =>
fail!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
Err(e) => e
}
}
}
/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
impl<T, E> Slice<T> for Result<T, E> {
/// Convert from `Result<T, E>` to `&[T]` (without copying)
#[inline]
#[stable]
fn as_slice<'a>(&'a self) -> &'a [T] {
match *self {
Ok(ref x) => slice::ref_slice(x),
Err(_) => {
// work around lack of implicit coercion from fixed-size array to slice
let emp: &[_] = &[];
emp
}
}
}
}
/////////////////////////////////////////////////////////////////////////////
// The Result Iterator
/////////////////////////////////////////////////////////////////////////////
/// A `Result` iterator that yields either one or zero elements
///
/// The `Item` iterator is returned by the `iter`, `mut_iter` and `move_iter`
/// methods on `Result`.
#[deriving(Clone)]
#[unstable = "waiting for iterator conventions"]
pub struct Item<T> {
opt: Option<T>
}
impl<T> Iterator<T> for Item<T> {
#[inline]
fn next(&mut self) -> Option<T> {
self.opt.take()
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
match self.opt {
Some(_) => (1, Some(1)),
None => (0, Some(0)),
}
}
}
impl<A> DoubleEndedIterator<A> for Item<A> {
#[inline]
fn next_back(&mut self) -> Option<A> {
self.opt.take()
}
}
impl<A> ExactSize<A> for Item<A> {}
/////////////////////////////////////////////////////////////////////////////
// Free functions
/////////////////////////////////////////////////////////////////////////////
/// Deprecated: use `Iterator::collect`.
#[inline]
#[deprecated = "use Iterator::collect instead"]
pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(mut iter: Iter)
-> Result<V, E> {
iter.collect()
}
impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
/// Takes each element in the `Iterator`: if it is an `Err`, no further
/// elements are taken, and the `Err` is returned. Should no `Err` occur, a
/// container with the values of each `Result` is returned.
///
/// Here is an example which increments every integer in a vector,
/// checking for overflow:
///
/// ```rust
/// use std::uint;
///
/// let v = vec!(1u, 2u);
/// let res: Result<Vec<uint>, &'static str> = v.iter().map(|x: &uint|
/// if *x == uint::MAX { Err("Overflow!") }
/// else { Ok(x + 1) }
/// ).collect();
/// assert!(res == Ok(vec!(2u, 3u)));
/// ```
#[inline]
fn from_iter<I: Iterator<Result<A, E>>>(iter: I) -> Result<V, E> {
// FIXME(#11084): This could be replaced with Iterator::scan when this
// performance bug is closed.
struct Adapter<Iter, E> {
iter: Iter,
err: Option<E>,
}
impl<T, E, Iter: Iterator<Result<T, E>>> Iterator<T> for Adapter<Iter, E> {
#[inline]
fn next(&mut self) -> Option<T> {
match self.iter.next() {
Some(Ok(value)) => Some(value),
Some(Err(err)) => {
| {
match self {
Ok(_) => res,
Err(e) => Err(e),
}
} | identifier_body |
result.rs | /O](../../std/io/index.html).
//!
//! A simple function returning `Result` might be
//! defined and used like so:
//!
//! ~~~
//! #[deriving(Show)]
//! enum Version { Version1, Version2 }
//!
//! fn parse_version(header: &[u8]) -> Result<Version, &'static str> {
//! if header.len() < 1 {
//! return Err("invalid header length");
//! }
//! match header[0] {
//! 1 => Ok(Version1),
//! 2 => Ok(Version2),
//! _ => Err("invalid version")
//! }
//! }
//!
//! let version = parse_version(&[1, 2, 3, 4]);
//! match version {
//! Ok(v) => {
//! println!("working with version: {}", v);
//! }
//! Err(e) => {
//! println!("error parsing header: {}", e);
//! }
//! }
//! ~~~
//!
//! Pattern matching on `Result`s is clear and straightforward for
//! simple cases, but `Result` comes with some convenience methods
//! that make working it more succinct.
//!
//! ~~~
//! let good_result: Result<int, int> = Ok(10);
//! let bad_result: Result<int, int> = Err(10);
//!
//! // The `is_ok` and `is_err` methods do what they say.
//! assert!(good_result.is_ok() &&!good_result.is_err());
//! assert!(bad_result.is_err() &&!bad_result.is_ok());
//!
//! // `map` consumes the `Result` and produces another.
//! let good_result: Result<int, int> = good_result.map(|i| i + 1);
//! let bad_result: Result<int, int> = bad_result.map(|i| i - 1);
//!
//! // Use `and_then` to continue the computation.
//! let good_result: Result<bool, int> = good_result.and_then(|i| Ok(i == 11));
//!
//! // Use `or_else` to handle the error.
//! let bad_result: Result<int, int> = bad_result.or_else(|i| Ok(11));
//!
//! // Consume the result and return the contents with `unwrap`.
//! let final_awesome_result = good_result.ok().unwrap();
//! ~~~
//!
//! # Results must be used
//!
//! A common problem with using return values to indicate errors is
//! that it is easy to ignore the return value, thus failing to handle
//! the error. Result is annotated with the #[must_use] attribute,
//! which will cause the compiler to issue a warning when a Result
//! value is ignored. This makes `Result` especially useful with
//! functions that may encounter errors but don't otherwise return a
//! useful value.
//!
//! Consider the `write_line` method defined for I/O types
//! by the [`Writer`](../io/trait.Writer.html) trait:
//!
//! ~~~
//! use std::io::IoError;
//!
//! trait Writer {
//! fn write_line(&mut self, s: &str) -> Result<(), IoError>;
//! }
//! ~~~
//!
//! *Note: The actual definition of `Writer` uses `IoResult`, which
//! is just a synonym for `Result<T, IoError>`.*
//!
//! This method doesn't produce a value, but the write may
//! fail. It's crucial to handle the error case, and *not* write
//! something like this:
//!
//! ~~~ignore
//! use std::io::{File, Open, Write};
//!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! // If `write_line` errors, then we'll never know, because the return
//! // value is ignored.
//! file.write_line("important message");
//! drop(file);
//! ~~~
//!
//! If you *do* write that in Rust, the compiler will by give you a
//! warning (by default, controlled by the `unused_must_use` lint).
//!
//! You might instead, if you don't want to handle the error, simply
//! fail, by converting to an `Option` with `ok`, then asserting
//! success with `expect`. This will fail if the write fails, proving
//! a marginally useful message indicating why:
//!
//! ~~~no_run
//! use std::io::{File, Open, Write};
//!
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! file.write_line("important message").ok().expect("failed to write message");
//! drop(file);
//! ~~~
//!
//! You might also simply assert success:
//!
//! ~~~no_run
//! # use std::io::{File, Open, Write};
//!
//! # let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! assert!(file.write_line("important message").is_ok());
//! # drop(file);
//! ~~~
//!
//! Or propagate the error up the call stack with `try!`:
//!
//! ~~~
//! # use std::io::{File, Open, Write, IoError};
//! fn write_message() -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("valuable_data.txt"), Open, Write);
//! try!(file.write_line("important message"));
//! drop(file);
//! return Ok(());
//! }
//! ~~~
//!
//! # The `try!` macro
//!
//! When writing code that calls many functions that return the
//! `Result` type, the error handling can be tedious. The `try!`
//! macro hides some of the boilerplate of propagating errors up the
//! call stack.
//!
//! It replaces this:
//!
//! ~~~
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info {
//! name: String,
//! age: int,
//! rating: int
//! }
//!
//! fn write_info(info: &Info) -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
//! // Early return on error
//! match file.write_line(format!("name: {}", info.name).as_slice()) {
//! Ok(_) => (),
//! Err(e) => return Err(e)
//! }
//! match file.write_line(format!("age: {}", info.age).as_slice()) {
//! Ok(_) => (),
//! Err(e) => return Err(e)
//! }
//! return file.write_line(format!("rating: {}", info.rating).as_slice());
//! }
//! ~~~
//!
//! With this:
//!
//! ~~~
//! use std::io::{File, Open, Write, IoError};
//!
//! struct Info {
//! name: String,
//! age: int,
//! rating: int
//! }
//!
//! fn write_info(info: &Info) -> Result<(), IoError> {
//! let mut file = File::open_mode(&Path::new("my_best_friends.txt"), Open, Write);
//! // Early return on error
//! try!(file.write_line(format!("name: {}", info.name).as_slice()));
//! try!(file.write_line(format!("age: {}", info.age).as_slice()));
//! try!(file.write_line(format!("rating: {}", info.rating).as_slice()));
//! return Ok(());
//! }
//! ~~~
//!
//! *It's much nicer!*
//!
//! Wrapping an expression in `try!` will result in the unwrapped
//! success (`Ok`) value, unless the result is `Err`, in which case
//! `Err` is returned early from the enclosing function. Its simple definition
//! makes it clear:
//!
//! ~~~
//! # #![feature(macro_rules)]
//! macro_rules! try(
//! ($e:expr) => (match $e { Ok(e) => e, Err(e) => return Err(e) })
//! )
//! # fn main() { }
//! ~~~
//!
//! `try!` is imported by the prelude, and is available everywhere.
//!
//! # `Result` and `Option`
//!
//! The `Result` and [`Option`](../option/index.html) types are
//! similar and complementary: they are often employed to indicate a
//! lack of a return value; and they are trivially converted between
//! each other, so `Result`s are often handled by first converting to
//! `Option` with the [`ok`](type.Result.html#method.ok) and
//! [`err`](type.Result.html#method.ok) methods.
//!
//! Whereas `Option` only indicates the lack of a value, `Result` is
//! specifically for error reporting, and carries with it an error
//! value. Sometimes `Option` is used for indicating errors, but this
//! is only for simple cases and is generally discouraged. Even when
//! there is no useful error value to return, prefer `Result<T, ()>`.
//!
//! Converting to an `Option` with `ok()` to handle an error:
//!
//! ~~~
//! use std::io::Timer;
//! let mut t = Timer::new().ok().expect("failed to create timer!");
//! ~~~
//!
//! # `Result` vs. `fail!`
//!
//! `Result` is for recoverable errors; `fail!` is for unrecoverable
//! errors. Callers should always be able to avoid failure if they
//! take the proper precautions, for example, calling `is_some()`
//! on an `Option` type before calling `unwrap`.
//!
//! The suitability of `fail!` as an error handling mechanism is
//! limited by Rust's lack of any way to "catch" and resume execution
//! from a thrown exception. Therefore using failure for error
//! handling requires encapsulating fallible code in a task. Calling
//! the `fail!` macro, or invoking `fail!` indirectly should be
//! avoided as an error reporting strategy. Failure is only for
//! unrecoverable errors and a failing task is typically the sign of
//! a bug.
//!
//! A module that instead returns `Results` is alerting the caller
//! that failure is possible, and providing precise control over how
//! it is handled.
//!
//! Furthermore, failure may not be recoverable at all, depending on
//! the context. The caller of `fail!` should assume that execution
//! will not resume after failure, that failure is catastrophic.
#![stable]
use clone::Clone;
use cmp::PartialEq;
use std::fmt::Show;
use slice;
use slice::Slice;
use iter::{Iterator, DoubleEndedIterator, FromIterator, ExactSize};
use option::{None, Option, Some};
/// `Result` is a type that represents either success (`Ok`) or failure (`Err`).
///
/// See the [`std::result`](index.html) module documentation for details.
#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Show)]
#[must_use]
#[stable]
pub enum Result<T, E> {
/// Contains the success value
Ok(T),
/// Contains the error value
Err(E)
}
/////////////////////////////////////////////////////////////////////////////
// Type implementation
/////////////////////////////////////////////////////////////////////////////
impl<T, E> Result<T, E> {
/////////////////////////////////////////////////////////////////////////
// Querying the contained values
/////////////////////////////////////////////////////////////////////////
/// Returns true if the result is `Ok`
///
/// # Example
///
/// ~~~
/// use std::io::{File, Open, Write};
///
/// # fn do_not_run_example() { // creates a file
/// let mut file = File::open_mode(&Path::new("secret.txt"), Open, Write);
/// assert!(file.write_line("it's cold in here").is_ok());
/// # }
/// ~~~
#[inline]
#[stable]
pub fn is_ok(&self) -> bool {
match *self {
Ok(_) => true,
Err(_) => false
}
}
/// Returns true if the result is `Err`
///
/// # Example
///
/// ~~~
/// use std::io::{File, Open, Read};
///
/// // When opening with `Read` access, if the file does not exist
/// // then `open_mode` returns an error.
/// let bogus = File::open_mode(&Path::new("not_a_file.txt"), Open, Read);
/// assert!(bogus.is_err());
/// ~~~
#[inline]
#[stable]
pub fn is_err(&self) -> bool {
!self.is_ok()
}
/////////////////////////////////////////////////////////////////////////
// Adapter for each variant
/////////////////////////////////////////////////////////////////////////
/// Convert from `Result<T, E>` to `Option<T>`
///
/// Converts `self` into an `Option<T>`, consuming `self`,
/// and discarding the error, if any.
///
/// To convert to an `Option` without discarding the error value,
/// use `as_ref` to first convert the `Result<T, E>` into a
/// `Result<&T, &E>`.
///
/// # Examples
///
/// ~~~{.should_fail}
/// use std::io::{File, IoResult};
///
/// let bdays: IoResult<File> = File::open(&Path::new("important_birthdays.txt"));
/// let bdays: File = bdays.ok().expect("unable to open birthday file");
/// ~~~
#[inline]
#[stable]
pub fn ok(self) -> Option<T> {
match self {
Ok(x) => Some(x),
Err(_) => None,
}
}
/// Convert from `Result<T, E>` to `Option<E>`
///
/// Converts `self` into an `Option<T>`, consuming `self`,
/// and discarding the value, if any.
#[inline]
#[stable]
pub fn err(self) -> Option<E> {
match self {
Ok(_) => None,
Err(x) => Some(x),
}
}
/////////////////////////////////////////////////////////////////////////
// Adapter for working with references
/////////////////////////////////////////////////////////////////////////
/// Convert from `Result<T, E>` to `Result<&T, &E>`
///
/// Produces a new `Result`, containing a reference
/// into the original, leaving the original in place.
#[inline]
#[stable]
pub fn as_ref<'r>(&'r self) -> Result<&'r T, &'r E> {
match *self {
Ok(ref x) => Ok(x),
Err(ref x) => Err(x),
}
}
/// Convert from `Result<T, E>` to `Result<&mut T, &mut E>`
#[inline]
#[unstable = "waiting for mut conventions"]
pub fn as_mut<'r>(&'r mut self) -> Result<&'r mut T, &'r mut E> {
match *self {
Ok(ref mut x) => Ok(x),
Err(ref mut x) => Err(x),
}
}
/// Convert from `Result<T, E>` to `&mut [T]` (without copying)
#[inline]
#[unstable = "waiting for mut conventions"]
pub fn as_mut_slice<'r>(&'r mut self) -> &'r mut [T] {
match *self {
Ok(ref mut x) => slice::mut_ref_slice(x),
Err(_) => {
// work around lack of implicit coercion from fixed-size array to slice
let emp: &mut [_] = &mut [];
emp
}
}
}
/////////////////////////////////////////////////////////////////////////
// Transforming contained values
/////////////////////////////////////////////////////////////////////////
/// Maps a `Result<T, E>` to `Result<U, E>` by applying a function to an
/// contained `Ok` value, leaving an `Err` value untouched.
///
/// This function can be used to compose the results of two functions.
///
/// # Examples
///
/// Sum the lines of a buffer by mapping strings to numbers,
/// ignoring I/O and parse errors:
///
/// ~~~
/// use std::io::{BufReader, IoResult};
///
/// let buffer = "1\n2\n3\n4\n";
/// let mut reader = BufReader::new(buffer.as_bytes());
///
/// let mut sum = 0;
///
/// while!reader.eof() {
/// let line: IoResult<String> = reader.read_line();
/// // Convert the string line to a number using `map` and `from_str`
/// let val: IoResult<int> = line.map(|line| {
/// from_str::<int>(line.as_slice().trim_right()).unwrap_or(0)
/// });
/// // Add the value if there were no errors, otherwise add 0
/// sum += val.ok().unwrap_or(0);
/// }
///
/// assert!(sum == 10);
/// ~~~
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn map<U>(self, op: |T| -> U) -> Result<U,E> {
match self {
Ok(t) => Ok(op(t)),
Err(e) => Err(e)
}
}
/// Maps a `Result<T, E>` to `Result<T, F>` by applying a function to an
/// contained `Err` value, leaving an `Ok` value untouched.
///
/// This function can be used to pass through a successful result while handling
/// an error.
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn map_err<F>(self, op: |E| -> F) -> Result<T,F> {
match self {
Ok(t) => Ok(t),
Err(e) => Err(op(e))
}
}
/////////////////////////////////////////////////////////////////////////
// Iterator constructors
/////////////////////////////////////////////////////////////////////////
/// Returns an iterator over the possibly contained value.
#[inline]
#[unstable = "waiting for iterator conventions"]
pub fn iter<'r>(&'r self) -> Item<&'r T> {
Item{opt: self.as_ref().ok()}
}
/// Returns a mutable iterator over the possibly contained value.
#[inline]
#[unstable = "waiting for iterator conventions"]
pub fn mut_iter<'r>(&'r mut self) -> Item<&'r mut T> {
Item{opt: self.as_mut().ok()}
}
/// Returns a consuming iterator over the possibly contained value.
#[inline]
#[unstable = "waiting for iterator conventions"]
pub fn | (self) -> Item<T> {
Item{opt: self.ok()}
}
////////////////////////////////////////////////////////////////////////
// Boolean operations on the values, eager and lazy
/////////////////////////////////////////////////////////////////////////
/// Returns `res` if the result is `Ok`, otherwise returns the `Err` value of `self`.
#[inline]
#[stable]
pub fn and<U>(self, res: Result<U, E>) -> Result<U, E> {
match self {
Ok(_) => res,
Err(e) => Err(e),
}
}
/// Calls `op` if the result is `Ok`, otherwise returns the `Err` value of `self`.
///
/// This function can be used for control flow based on result values
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn and_then<U>(self, op: |T| -> Result<U, E>) -> Result<U, E> {
match self {
Ok(t) => op(t),
Err(e) => Err(e),
}
}
/// Returns `res` if the result is `Err`, otherwise returns the `Ok` value of `self`.
#[inline]
#[stable]
pub fn or(self, res: Result<T, E>) -> Result<T, E> {
match self {
Ok(_) => self,
Err(_) => res,
}
}
/// Calls `op` if the result is `Err`, otherwise returns the `Ok` value of `self`.
///
/// This function can be used for control flow based on result values
#[inline]
#[unstable = "waiting for unboxed closures"]
pub fn or_else<F>(self, op: |E| -> Result<T, F>) -> Result<T, F> {
match self {
Ok(t) => Ok(t),
Err(e) => op(e),
}
}
/// Unwraps a result, yielding the content of an `Ok`.
/// Else it returns `optb`.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap_or(self, optb: T) -> T {
match self {
Ok(t) => t,
Err(_) => optb
}
}
/// Unwraps a result, yielding the content of an `Ok`.
/// If the value is an `Err` then it calls `op` with its value.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap_or_else(self, op: |E| -> T) -> T {
match self {
Ok(t) => t,
Err(e) => op(e)
}
}
/// Deprecated name for `unwrap_or_else()`.
#[deprecated = "replaced by.unwrap_or_else()"]
#[inline]
pub fn unwrap_or_handle(self, op: |E| -> T) -> T {
self.unwrap_or_else(op)
}
}
impl<T, E: Show> Result<T, E> {
/// Unwraps a result, yielding the content of an `Ok`.
///
/// # Failure
///
/// Fails if the value is an `Err`, with a custom failure message provided
/// by the `Err`'s value.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap(self) -> T {
match self {
Ok(t) => t,
Err(e) =>
fail!("called `Result::unwrap()` on an `Err` value: {}", e)
}
}
}
impl<T: Show, E> Result<T, E> {
/// Unwraps a result, yielding the content of an `Err`.
///
/// # Failure
///
/// Fails if the value is an `Ok`, with a custom failure message provided
/// by the `Ok`'s value.
#[inline]
#[unstable = "waiting for conventions"]
pub fn unwrap_err(self) -> E {
match self {
Ok(t) =>
fail!("called `Result::unwrap_err()` on an `Ok` value: {}", t),
Err(e) => e
}
}
}
/////////////////////////////////////////////////////////////////////////////
// Trait implementations
/////////////////////////////////////////////////////////////////////////////
impl<T, E> Slice<T> for Result<T, E> {
/// Convert from `Result<T, E>` to `&[T]` (without copying)
#[inline]
#[stable]
fn as_slice<'a>(&'a self) -> &'a [T] {
match *self {
Ok(ref x) => slice::ref_slice(x),
Err(_) => {
// work around lack of implicit coercion from fixed-size array to slice
let emp: &[_] = &[];
emp
}
}
}
}
/////////////////////////////////////////////////////////////////////////////
// The Result Iterator
/////////////////////////////////////////////////////////////////////////////
/// A `Result` iterator that yields either one or zero elements
///
/// The `Item` iterator is returned by the `iter`, `mut_iter` and `move_iter`
/// methods on `Result`.
#[deriving(Clone)]
#[unstable = "waiting for iterator conventions"]
pub struct Item<T> {
opt: Option<T>
}
impl<T> Iterator<T> for Item<T> {
#[inline]
fn next(&mut self) -> Option<T> {
self.opt.take()
}
#[inline]
fn size_hint(&self) -> (uint, Option<uint>) {
match self.opt {
Some(_) => (1, Some(1)),
None => (0, Some(0)),
}
}
}
impl<A> DoubleEndedIterator<A> for Item<A> {
#[inline]
fn next_back(&mut self) -> Option<A> {
self.opt.take()
}
}
impl<A> ExactSize<A> for Item<A> {}
/////////////////////////////////////////////////////////////////////////////
// Free functions
/////////////////////////////////////////////////////////////////////////////
/// Deprecated: use `Iterator::collect`.
#[inline]
#[deprecated = "use Iterator::collect instead"]
pub fn collect<T, E, Iter: Iterator<Result<T, E>>, V: FromIterator<T>>(mut iter: Iter)
-> Result<V, E> {
iter.collect()
}
impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> {
/// Takes each element in the `Iterator`: if it is an `Err`, no further
/// elements are taken, and the `Err` is returned. Should no `Err` occur, a
/// container with the values of each `Result` is returned.
///
/// Here is an example which increments every integer in a vector,
/// checking for overflow:
///
/// ```rust
/// use std::uint;
///
/// let v = vec!(1u, 2u);
/// let res: Result<Vec<uint>, &'static str> = v.iter().map(|x: &uint|
/// if *x == uint::MAX { Err("Overflow!") }
/// else { Ok(x + 1) }
/// ).collect();
/// assert!(res == Ok(vec!(2u, 3u)));
/// ```
#[inline]
fn from_iter<I: Iterator<Result<A, E>>>(iter: I) -> Result<V, E> {
// FIXME(#11084): This could be replaced with Iterator::scan when this
// performance bug is closed.
struct Adapter<Iter, E> {
iter: Iter,
err: Option<E>,
}
impl<T, E, Iter: Iterator<Result<T, E>>> Iterator<T> for Adapter<Iter, E> {
#[inline]
fn next(&mut self) -> Option<T> {
match self.iter.next() {
Some(Ok(value)) => Some(value),
Some(Err(err)) => {
| move_iter | identifier_name |
cpp_box.rs | use crate::ops::{Begin, BeginMut, End, EndMut, Increment, Indirection};
use crate::vector_ops::{Data, DataMut, Size};
use crate::{cpp_iter, CppIterator, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast};
use std::ops::Deref;
use std::{fmt, mem, ptr, slice};
/// Objects that can be deleted using C++'s `delete` operator.
///
/// This trait is automatically implemented for class types by `ritual`.
pub trait CppDeletable: Sized {
/// Calls C++'s `delete x` on `self`.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
/// Note that deleting an object multiple times is undefined behavior.
unsafe fn delete(&self);
}
/// An owning pointer to a C++ object.
///
/// `CppBox` is automatically used in places where C++ class objects are passed by value
/// and in return values of constructors because the ownership is apparent in these cases.
/// However, sometimes an object is returned as a pointer but you must accept the ownership
/// of the object. It's not possible to automatically determine ownership semantics
/// of C++ code in this case, so you should manually convert `Ptr` to `CppBox`
/// using `to_box` method.
///
/// When `CppBox` is dropped, it will automatically delete the object using C++'s `delete`
/// operator.
///
/// Objects stored in `CppBox` are usually placed on the heap by the C++ code.
///
/// If a C++ API accepts an object by pointer and takes ownership of it, it's not possible to
/// automatically detect this, so you must manually convert `CppBox` to a non-owning `Ptr`
/// using `into_ptr` before passing it to such a function.
///
/// `&CppBox<T>` and `&mut CppBox<T>` implement operator traits and delegate them
/// to the corresponding C++ operators.
/// This means that you can use `&box1 + value` to access the object's `operator+`.
///
/// `CppBox` implements `Deref`, allowing to call the object's methods
/// directly. In addition, methods of the object's first base class are also directly available
/// thanks to nested `Deref` implementations.
///
/// If the object provides an iterator interface through `begin()` and `end()` functions,
/// `&CppBox<T>` and `&mut CppBox<T>` will implement `IntoIterator`,
/// so you can iterate on them directly.
///
/// ### Safety
///
/// It's not possible to automatically track the ownership of objects possibly managed by C++
/// libraries. The user must ensure that the object is alive while `CppBox` exists and that
/// no pointers to the object are used after the object is deleted
/// by `CppBox`'s `Drop` implementation. Note that with `CppBox`,
/// it's possible to call unsafe C++ code without using any more unsafe code, for example, by
/// using operator traits or simply dropping the box, so care should be taken when exposing
/// `CppBox` in a safe interface.
pub struct CppBox<T: CppDeletable>(ptr::NonNull<T>);
impl<T: CppDeletable> CppBox<T> {
/// Encapsulates the object into a `CppBox`. Returns `None` if the pointer is null.
///
/// The same operation can be done by calling `to_box` function on `Ptr`.
///
/// You should use this function only for
/// pointers that were created on C++ side and passed through
/// a FFI boundary to Rust. An object created with C++ `new`
/// must be deleted using C++ `delete`, which is executed by `CppBox`.
///
/// Do not use this function for objects that would be deleted by other means.
/// If another C++ object is the owner of the passed object,
/// it will attempt to delete it. If `CppBox` containing the object still exists,
/// it would result in a double deletion, which must never happen.
///
/// Use `CppBox::into_ptr` to unwrap the pointer before passing it to
/// a function that takes ownership of the object.
///
/// ### Safety
///
/// The pointer must point to an object that can be
/// safely deleted using C++'s `delete` operator.
/// The object must not be deleted by other means while `CppBox` exists.
/// Any other pointers to the object must not be used after `CppBox` is dropped.
pub unsafe fn new(ptr: Ptr<T>) -> Option<Self> {
Self::from_raw(ptr.as_raw_ptr())
}
/// Encapsulates the object into a `CppBox`. Returns `None` if the pointer is null.
///
/// See `CppBox::new` for more information.
///
/// ### Safety
///
/// The pointer must point to an object that can be
/// safely deleted using C++'s `delete` operator.
/// The object must not be deleted by other means while `CppBox` exists.
/// Any other pointers to the object must not be used after `CppBox` is dropped.
pub unsafe fn from_raw(ptr: *const T) -> Option<Self> {
ptr::NonNull::new(ptr as *mut T).map(CppBox)
}
/// Returns a constant pointer to the value in the box.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn as_ptr(&self) -> Ptr<T> {
Ptr::from_raw(self.0.as_ptr())
}
/// Returns a constant raw pointer to the value in the box.
pub fn as_mut_raw_ptr(&self) -> *mut T {
self.0.as_ptr()
}
/// Returns a mutable raw pointer to the value in the box.
pub fn as_raw_ptr(&self) -> *const T {
self.0.as_ptr() as *const T
}
/// Destroys the box without deleting the object and returns a raw pointer to the content.
/// The caller of the function becomes the owner of the object and should
/// ensure that the object will be deleted at some point.
pub fn into_raw_ptr(self) -> *mut T {
let ptr = self.0.as_ptr();
mem::forget(self);
ptr
}
/// Destroys the box without deleting the object and returns a pointer to the content.
/// The caller of the function becomes the owner of the object and should
/// ensure that the object will be deleted at some point.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn into_ptr(self) -> Ptr<T> {
let ptr = Ptr::from_raw(self.0.as_ptr());
mem::forget(self);
ptr
}
/// Returns a constant reference to the value in the box.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
#[allow(clippy::should_implement_trait)]
pub unsafe fn as_ref(&self) -> Ref<T> {
Ref::from_raw_non_null(self.0)
}
/// Returns a reference to the value.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_raw_ref<'a>(&self) -> &'a T {
&*self.0.as_ptr()
}
/// Returns a mutable reference to the value.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_mut_raw_ref<'a>(&self) -> &'a mut T {
&mut *self.0.as_ptr()
}
/// Returns a non-owning reference to the content converted to the base class type `U`.
/// `CppBox` retains the ownership of the object.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn static_upcast<U>(&self) -> Ref<U>
where
T: StaticUpcast<U>,
{
StaticUpcast::static_upcast(self.as_ptr())
.as_ref()
.expect("StaticUpcast returned null on CppBox input")
}
/// Returns a non-owning reference to the content converted to the derived class type `U`.
/// `CppBox` retains the ownership of the object.
///
/// It's recommended to use `dynamic_cast` instead because it performs a checked conversion.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid and it's type is `U` or inherits from `U`.
pub unsafe fn static_downcast<U>(&self) -> Ref<U>
where
T: StaticDowncast<U>,
{
StaticDowncast::static_downcast(self.as_ptr())
.as_ref()
.expect("StaticDowncast returned null on CppBox input")
}
/// Returns a non-owning reference to the content converted to the derived class type `U`.
/// `CppBox` retains the ownership of the object. Returns `None` if the object's type is not `U`
/// and doesn't inherit `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn dynamic_cast<U>(&self) -> Option<Ref<U>>
where
T: DynamicCast<U>,
{
DynamicCast::dynamic_cast(self.as_ptr()).as_ref()
}
}
impl<V, T> CppBox<V>
where
V: Data<Output = *const T> + Size + CppDeletable,
{
/// Returns the content of the object as a slice, based on `data()` and `size()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn as_slice<'a>(&self) -> &'a [T] {
let ptr = self.data();
let size = self.size();
slice::from_raw_parts(ptr, size)
}
}
impl<V, T> CppBox<V>
where
V: DataMut<Output = *mut T> + Size + CppDeletable,
{
/// Returns the content of the vector as a mutable slice,
/// based on `data()` and `size()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn as_mut_slice<'a>(&self) -> &'a mut [T] {
let ptr = self.data_mut();
let size = self.size();
slice::from_raw_parts_mut(ptr, size)
}
}
impl<T, T1, T2> CppBox<T>
where
T: Begin<Output = CppBox<T1>> + End<Output = CppBox<T2>> + CppDeletable,
T1: CppDeletable + PartialEq<Ref<T2>> + Increment + Indirection,
T2: CppDeletable,
{
/// Returns an iterator over the content of the object,
/// based on `begin()` and `end()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn iter(&self) -> CppIterator<T1, T2> {
cpp_iter(self.begin(), self.end())
}
}
impl<T, T1, T2> CppBox<T>
where
T: BeginMut<Output = CppBox<T1>> + EndMut<Output = CppBox<T2>> + CppDeletable,
T1: CppDeletable + PartialEq<Ref<T2>> + Increment + Indirection,
T2: CppDeletable,
{
/// Returns a mutable iterator over the content of the object,
/// based on `begin()` and `end()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn iter_mut(&self) -> CppIterator<T1, T2> {
cpp_iter(self.begin_mut(), self.end_mut())
}
}
/// Allows to call member functions of `T` and its base classes directly on the pointer.
impl<T: CppDeletable> Deref for CppBox<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.0.as_ref() }
}
}
/// Deletes the stored object using C++'s `delete` operator.
impl<T: CppDeletable> Drop for CppBox<T> {
fn drop(&mut self) {
unsafe {
T::delete(self.0.as_ref());
}
}
}
impl<T: CppDeletable> fmt::Debug for CppBox<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CppBox({:?})", self.0)
}
}
#[cfg(test)]
mod tests {
use crate::{CppBox, CppDeletable, Ptr};
use std::cell::RefCell;
use std::rc::Rc;
struct Struct1 {
value: Rc<RefCell<i32>>,
}
unsafe extern "C" fn struct1_delete(this_ptr: *const Struct1) {
(*this_ptr).value.borrow_mut().clone_from(&42);
}
impl CppDeletable for Struct1 {
unsafe fn delete(&self) {
struct1_delete(self);
}
}
#[test]
fn | () {
let value1 = Rc::new(RefCell::new(10));
let object1 = Struct1 {
value: value1.clone(),
};
assert!(*value1.borrow() == 10);
unsafe {
CppBox::new(Ptr::from_raw(&object1));
}
assert!(*value1.borrow() == 42);
}
}
| test_drop_calls_deleter | identifier_name |
cpp_box.rs | use crate::ops::{Begin, BeginMut, End, EndMut, Increment, Indirection};
use crate::vector_ops::{Data, DataMut, Size};
use crate::{cpp_iter, CppIterator, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast};
use std::ops::Deref;
use std::{fmt, mem, ptr, slice};
/// Objects that can be deleted using C++'s `delete` operator.
///
/// This trait is automatically implemented for class types by `ritual`.
pub trait CppDeletable: Sized {
/// Calls C++'s `delete x` on `self`.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
/// Note that deleting an object multiple times is undefined behavior.
unsafe fn delete(&self);
}
/// An owning pointer to a C++ object.
///
/// `CppBox` is automatically used in places where C++ class objects are passed by value
/// and in return values of constructors because the ownership is apparent in these cases.
/// However, sometimes an object is returned as a pointer but you must accept the ownership
/// of the object. It's not possible to automatically determine ownership semantics
/// of C++ code in this case, so you should manually convert `Ptr` to `CppBox`
/// using `to_box` method.
///
/// When `CppBox` is dropped, it will automatically delete the object using C++'s `delete`
/// operator.
///
/// Objects stored in `CppBox` are usually placed on the heap by the C++ code.
///
/// If a C++ API accepts an object by pointer and takes ownership of it, it's not possible to
/// automatically detect this, so you must manually convert `CppBox` to a non-owning `Ptr`
/// using `into_ptr` before passing it to such a function.
///
/// `&CppBox<T>` and `&mut CppBox<T>` implement operator traits and delegate them
/// to the corresponding C++ operators.
/// This means that you can use `&box1 + value` to access the object's `operator+`.
///
/// `CppBox` implements `Deref`, allowing to call the object's methods
/// directly. In addition, methods of the object's first base class are also directly available
/// thanks to nested `Deref` implementations.
///
/// If the object provides an iterator interface through `begin()` and `end()` functions,
/// `&CppBox<T>` and `&mut CppBox<T>` will implement `IntoIterator`,
/// so you can iterate on them directly.
///
/// ### Safety
///
/// It's not possible to automatically track the ownership of objects possibly managed by C++
/// libraries. The user must ensure that the object is alive while `CppBox` exists and that
/// no pointers to the object are used after the object is deleted
/// by `CppBox`'s `Drop` implementation. Note that with `CppBox`,
/// it's possible to call unsafe C++ code without using any more unsafe code, for example, by
/// using operator traits or simply dropping the box, so care should be taken when exposing
/// `CppBox` in a safe interface.
pub struct CppBox<T: CppDeletable>(ptr::NonNull<T>);
impl<T: CppDeletable> CppBox<T> {
/// Encapsulates the object into a `CppBox`. Returns `None` if the pointer is null.
///
/// The same operation can be done by calling `to_box` function on `Ptr`.
///
/// You should use this function only for
/// pointers that were created on C++ side and passed through
/// a FFI boundary to Rust. An object created with C++ `new`
/// must be deleted using C++ `delete`, which is executed by `CppBox`.
///
/// Do not use this function for objects that would be deleted by other means.
/// If another C++ object is the owner of the passed object,
/// it will attempt to delete it. If `CppBox` containing the object still exists,
/// it would result in a double deletion, which must never happen.
///
/// Use `CppBox::into_ptr` to unwrap the pointer before passing it to
/// a function that takes ownership of the object.
///
/// ### Safety
///
/// The pointer must point to an object that can be
/// safely deleted using C++'s `delete` operator.
/// The object must not be deleted by other means while `CppBox` exists.
/// Any other pointers to the object must not be used after `CppBox` is dropped.
pub unsafe fn new(ptr: Ptr<T>) -> Option<Self> {
Self::from_raw(ptr.as_raw_ptr())
}
/// Encapsulates the object into a `CppBox`. Returns `None` if the pointer is null.
///
/// See `CppBox::new` for more information.
///
/// ### Safety
///
/// The pointer must point to an object that can be
/// safely deleted using C++'s `delete` operator.
/// The object must not be deleted by other means while `CppBox` exists.
/// Any other pointers to the object must not be used after `CppBox` is dropped.
pub unsafe fn from_raw(ptr: *const T) -> Option<Self> {
ptr::NonNull::new(ptr as *mut T).map(CppBox)
}
/// Returns a constant pointer to the value in the box.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn as_ptr(&self) -> Ptr<T> {
Ptr::from_raw(self.0.as_ptr())
}
/// Returns a constant raw pointer to the value in the box.
pub fn as_mut_raw_ptr(&self) -> *mut T {
self.0.as_ptr()
}
/// Returns a mutable raw pointer to the value in the box.
pub fn as_raw_ptr(&self) -> *const T {
self.0.as_ptr() as *const T
}
| /// ensure that the object will be deleted at some point.
pub fn into_raw_ptr(self) -> *mut T {
let ptr = self.0.as_ptr();
mem::forget(self);
ptr
}
/// Destroys the box without deleting the object and returns a pointer to the content.
/// The caller of the function becomes the owner of the object and should
/// ensure that the object will be deleted at some point.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn into_ptr(self) -> Ptr<T> {
let ptr = Ptr::from_raw(self.0.as_ptr());
mem::forget(self);
ptr
}
/// Returns a constant reference to the value in the box.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
#[allow(clippy::should_implement_trait)]
pub unsafe fn as_ref(&self) -> Ref<T> {
Ref::from_raw_non_null(self.0)
}
/// Returns a reference to the value.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_raw_ref<'a>(&self) -> &'a T {
&*self.0.as_ptr()
}
/// Returns a mutable reference to the value.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_mut_raw_ref<'a>(&self) -> &'a mut T {
&mut *self.0.as_ptr()
}
/// Returns a non-owning reference to the content converted to the base class type `U`.
/// `CppBox` retains the ownership of the object.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn static_upcast<U>(&self) -> Ref<U>
where
T: StaticUpcast<U>,
{
StaticUpcast::static_upcast(self.as_ptr())
.as_ref()
.expect("StaticUpcast returned null on CppBox input")
}
/// Returns a non-owning reference to the content converted to the derived class type `U`.
/// `CppBox` retains the ownership of the object.
///
/// It's recommended to use `dynamic_cast` instead because it performs a checked conversion.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid and it's type is `U` or inherits from `U`.
pub unsafe fn static_downcast<U>(&self) -> Ref<U>
where
T: StaticDowncast<U>,
{
StaticDowncast::static_downcast(self.as_ptr())
.as_ref()
.expect("StaticDowncast returned null on CppBox input")
}
/// Returns a non-owning reference to the content converted to the derived class type `U`.
/// `CppBox` retains the ownership of the object. Returns `None` if the object's type is not `U`
/// and doesn't inherit `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn dynamic_cast<U>(&self) -> Option<Ref<U>>
where
T: DynamicCast<U>,
{
DynamicCast::dynamic_cast(self.as_ptr()).as_ref()
}
}
impl<V, T> CppBox<V>
where
V: Data<Output = *const T> + Size + CppDeletable,
{
/// Returns the content of the object as a slice, based on `data()` and `size()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn as_slice<'a>(&self) -> &'a [T] {
let ptr = self.data();
let size = self.size();
slice::from_raw_parts(ptr, size)
}
}
impl<V, T> CppBox<V>
where
V: DataMut<Output = *mut T> + Size + CppDeletable,
{
/// Returns the content of the vector as a mutable slice,
/// based on `data()` and `size()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn as_mut_slice<'a>(&self) -> &'a mut [T] {
let ptr = self.data_mut();
let size = self.size();
slice::from_raw_parts_mut(ptr, size)
}
}
impl<T, T1, T2> CppBox<T>
where
T: Begin<Output = CppBox<T1>> + End<Output = CppBox<T2>> + CppDeletable,
T1: CppDeletable + PartialEq<Ref<T2>> + Increment + Indirection,
T2: CppDeletable,
{
/// Returns an iterator over the content of the object,
/// based on `begin()` and `end()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn iter(&self) -> CppIterator<T1, T2> {
cpp_iter(self.begin(), self.end())
}
}
impl<T, T1, T2> CppBox<T>
where
T: BeginMut<Output = CppBox<T1>> + EndMut<Output = CppBox<T2>> + CppDeletable,
T1: CppDeletable + PartialEq<Ref<T2>> + Increment + Indirection,
T2: CppDeletable,
{
/// Returns a mutable iterator over the content of the object,
/// based on `begin()` and `end()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn iter_mut(&self) -> CppIterator<T1, T2> {
cpp_iter(self.begin_mut(), self.end_mut())
}
}
/// Allows to call member functions of `T` and its base classes directly on the pointer.
impl<T: CppDeletable> Deref for CppBox<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.0.as_ref() }
}
}
/// Deletes the stored object using C++'s `delete` operator.
impl<T: CppDeletable> Drop for CppBox<T> {
fn drop(&mut self) {
unsafe {
T::delete(self.0.as_ref());
}
}
}
impl<T: CppDeletable> fmt::Debug for CppBox<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CppBox({:?})", self.0)
}
}
#[cfg(test)]
mod tests {
use crate::{CppBox, CppDeletable, Ptr};
use std::cell::RefCell;
use std::rc::Rc;
struct Struct1 {
value: Rc<RefCell<i32>>,
}
unsafe extern "C" fn struct1_delete(this_ptr: *const Struct1) {
(*this_ptr).value.borrow_mut().clone_from(&42);
}
impl CppDeletable for Struct1 {
unsafe fn delete(&self) {
struct1_delete(self);
}
}
#[test]
fn test_drop_calls_deleter() {
let value1 = Rc::new(RefCell::new(10));
let object1 = Struct1 {
value: value1.clone(),
};
assert!(*value1.borrow() == 10);
unsafe {
CppBox::new(Ptr::from_raw(&object1));
}
assert!(*value1.borrow() == 42);
}
} | /// Destroys the box without deleting the object and returns a raw pointer to the content.
/// The caller of the function becomes the owner of the object and should | random_line_split |
cpp_box.rs | use crate::ops::{Begin, BeginMut, End, EndMut, Increment, Indirection};
use crate::vector_ops::{Data, DataMut, Size};
use crate::{cpp_iter, CppIterator, DynamicCast, Ptr, Ref, StaticDowncast, StaticUpcast};
use std::ops::Deref;
use std::{fmt, mem, ptr, slice};
/// Objects that can be deleted using C++'s `delete` operator.
///
/// This trait is automatically implemented for class types by `ritual`.
pub trait CppDeletable: Sized {
/// Calls C++'s `delete x` on `self`.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
/// Note that deleting an object multiple times is undefined behavior.
unsafe fn delete(&self);
}
/// An owning pointer to a C++ object.
///
/// `CppBox` is automatically used in places where C++ class objects are passed by value
/// and in return values of constructors because the ownership is apparent in these cases.
/// However, sometimes an object is returned as a pointer but you must accept the ownership
/// of the object. It's not possible to automatically determine ownership semantics
/// of C++ code in this case, so you should manually convert `Ptr` to `CppBox`
/// using `to_box` method.
///
/// When `CppBox` is dropped, it will automatically delete the object using C++'s `delete`
/// operator.
///
/// Objects stored in `CppBox` are usually placed on the heap by the C++ code.
///
/// If a C++ API accepts an object by pointer and takes ownership of it, it's not possible to
/// automatically detect this, so you must manually convert `CppBox` to a non-owning `Ptr`
/// using `into_ptr` before passing it to such a function.
///
/// `&CppBox<T>` and `&mut CppBox<T>` implement operator traits and delegate them
/// to the corresponding C++ operators.
/// This means that you can use `&box1 + value` to access the object's `operator+`.
///
/// `CppBox` implements `Deref`, allowing to call the object's methods
/// directly. In addition, methods of the object's first base class are also directly available
/// thanks to nested `Deref` implementations.
///
/// If the object provides an iterator interface through `begin()` and `end()` functions,
/// `&CppBox<T>` and `&mut CppBox<T>` will implement `IntoIterator`,
/// so you can iterate on them directly.
///
/// ### Safety
///
/// It's not possible to automatically track the ownership of objects possibly managed by C++
/// libraries. The user must ensure that the object is alive while `CppBox` exists and that
/// no pointers to the object are used after the object is deleted
/// by `CppBox`'s `Drop` implementation. Note that with `CppBox`,
/// it's possible to call unsafe C++ code without using any more unsafe code, for example, by
/// using operator traits or simply dropping the box, so care should be taken when exposing
/// `CppBox` in a safe interface.
pub struct CppBox<T: CppDeletable>(ptr::NonNull<T>);
impl<T: CppDeletable> CppBox<T> {
/// Encapsulates the object into a `CppBox`. Returns `None` if the pointer is null.
///
/// The same operation can be done by calling `to_box` function on `Ptr`.
///
/// You should use this function only for
/// pointers that were created on C++ side and passed through
/// a FFI boundary to Rust. An object created with C++ `new`
/// must be deleted using C++ `delete`, which is executed by `CppBox`.
///
/// Do not use this function for objects that would be deleted by other means.
/// If another C++ object is the owner of the passed object,
/// it will attempt to delete it. If `CppBox` containing the object still exists,
/// it would result in a double deletion, which must never happen.
///
/// Use `CppBox::into_ptr` to unwrap the pointer before passing it to
/// a function that takes ownership of the object.
///
/// ### Safety
///
/// The pointer must point to an object that can be
/// safely deleted using C++'s `delete` operator.
/// The object must not be deleted by other means while `CppBox` exists.
/// Any other pointers to the object must not be used after `CppBox` is dropped.
pub unsafe fn new(ptr: Ptr<T>) -> Option<Self> {
Self::from_raw(ptr.as_raw_ptr())
}
/// Encapsulates the object into a `CppBox`. Returns `None` if the pointer is null.
///
/// See `CppBox::new` for more information.
///
/// ### Safety
///
/// The pointer must point to an object that can be
/// safely deleted using C++'s `delete` operator.
/// The object must not be deleted by other means while `CppBox` exists.
/// Any other pointers to the object must not be used after `CppBox` is dropped.
pub unsafe fn from_raw(ptr: *const T) -> Option<Self> {
ptr::NonNull::new(ptr as *mut T).map(CppBox)
}
/// Returns a constant pointer to the value in the box.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn as_ptr(&self) -> Ptr<T> {
Ptr::from_raw(self.0.as_ptr())
}
/// Returns a constant raw pointer to the value in the box.
pub fn as_mut_raw_ptr(&self) -> *mut T {
self.0.as_ptr()
}
/// Returns a mutable raw pointer to the value in the box.
pub fn as_raw_ptr(&self) -> *const T {
self.0.as_ptr() as *const T
}
/// Destroys the box without deleting the object and returns a raw pointer to the content.
/// The caller of the function becomes the owner of the object and should
/// ensure that the object will be deleted at some point.
pub fn into_raw_ptr(self) -> *mut T {
let ptr = self.0.as_ptr();
mem::forget(self);
ptr
}
/// Destroys the box without deleting the object and returns a pointer to the content.
/// The caller of the function becomes the owner of the object and should
/// ensure that the object will be deleted at some point.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn into_ptr(self) -> Ptr<T> {
let ptr = Ptr::from_raw(self.0.as_ptr());
mem::forget(self);
ptr
}
/// Returns a constant reference to the value in the box.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
#[allow(clippy::should_implement_trait)]
pub unsafe fn as_ref(&self) -> Ref<T> |
/// Returns a reference to the value.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_raw_ref<'a>(&self) -> &'a T {
&*self.0.as_ptr()
}
/// Returns a mutable reference to the value.
///
/// ### Safety
///
/// `self` must be valid.
/// The content must not be read or modified through other ways while the returned reference
/// exists.See type level documentation.
pub unsafe fn as_mut_raw_ref<'a>(&self) -> &'a mut T {
&mut *self.0.as_ptr()
}
/// Returns a non-owning reference to the content converted to the base class type `U`.
/// `CppBox` retains the ownership of the object.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn static_upcast<U>(&self) -> Ref<U>
where
T: StaticUpcast<U>,
{
StaticUpcast::static_upcast(self.as_ptr())
.as_ref()
.expect("StaticUpcast returned null on CppBox input")
}
/// Returns a non-owning reference to the content converted to the derived class type `U`.
/// `CppBox` retains the ownership of the object.
///
/// It's recommended to use `dynamic_cast` instead because it performs a checked conversion.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid and it's type is `U` or inherits from `U`.
pub unsafe fn static_downcast<U>(&self) -> Ref<U>
where
T: StaticDowncast<U>,
{
StaticDowncast::static_downcast(self.as_ptr())
.as_ref()
.expect("StaticDowncast returned null on CppBox input")
}
/// Returns a non-owning reference to the content converted to the derived class type `U`.
/// `CppBox` retains the ownership of the object. Returns `None` if the object's type is not `U`
/// and doesn't inherit `U`.
///
/// ### Safety
///
/// This operation is safe as long as `self` is valid.
pub unsafe fn dynamic_cast<U>(&self) -> Option<Ref<U>>
where
T: DynamicCast<U>,
{
DynamicCast::dynamic_cast(self.as_ptr()).as_ref()
}
}
impl<V, T> CppBox<V>
where
V: Data<Output = *const T> + Size + CppDeletable,
{
/// Returns the content of the object as a slice, based on `data()` and `size()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn as_slice<'a>(&self) -> &'a [T] {
let ptr = self.data();
let size = self.size();
slice::from_raw_parts(ptr, size)
}
}
impl<V, T> CppBox<V>
where
V: DataMut<Output = *mut T> + Size + CppDeletable,
{
/// Returns the content of the vector as a mutable slice,
/// based on `data()` and `size()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn as_mut_slice<'a>(&self) -> &'a mut [T] {
let ptr = self.data_mut();
let size = self.size();
slice::from_raw_parts_mut(ptr, size)
}
}
impl<T, T1, T2> CppBox<T>
where
T: Begin<Output = CppBox<T1>> + End<Output = CppBox<T2>> + CppDeletable,
T1: CppDeletable + PartialEq<Ref<T2>> + Increment + Indirection,
T2: CppDeletable,
{
/// Returns an iterator over the content of the object,
/// based on `begin()` and `end()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn iter(&self) -> CppIterator<T1, T2> {
cpp_iter(self.begin(), self.end())
}
}
impl<T, T1, T2> CppBox<T>
where
T: BeginMut<Output = CppBox<T1>> + EndMut<Output = CppBox<T2>> + CppDeletable,
T1: CppDeletable + PartialEq<Ref<T2>> + Increment + Indirection,
T2: CppDeletable,
{
/// Returns a mutable iterator over the content of the object,
/// based on `begin()` and `end()` methods.
///
/// # Safety
///
/// The caller must make sure `self` contains a valid pointer. The content must
/// not be read or modified through other ways while the returned slice exists.
/// This function
/// may invoke arbitrary foreign code, so no safety guarantees can be made.
pub unsafe fn iter_mut(&self) -> CppIterator<T1, T2> {
cpp_iter(self.begin_mut(), self.end_mut())
}
}
/// Allows to call member functions of `T` and its base classes directly on the pointer.
impl<T: CppDeletable> Deref for CppBox<T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { self.0.as_ref() }
}
}
/// Deletes the stored object using C++'s `delete` operator.
impl<T: CppDeletable> Drop for CppBox<T> {
fn drop(&mut self) {
unsafe {
T::delete(self.0.as_ref());
}
}
}
impl<T: CppDeletable> fmt::Debug for CppBox<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "CppBox({:?})", self.0)
}
}
#[cfg(test)]
mod tests {
use crate::{CppBox, CppDeletable, Ptr};
use std::cell::RefCell;
use std::rc::Rc;
struct Struct1 {
value: Rc<RefCell<i32>>,
}
unsafe extern "C" fn struct1_delete(this_ptr: *const Struct1) {
(*this_ptr).value.borrow_mut().clone_from(&42);
}
impl CppDeletable for Struct1 {
unsafe fn delete(&self) {
struct1_delete(self);
}
}
#[test]
fn test_drop_calls_deleter() {
let value1 = Rc::new(RefCell::new(10));
let object1 = Struct1 {
value: value1.clone(),
};
assert!(*value1.borrow() == 10);
unsafe {
CppBox::new(Ptr::from_raw(&object1));
}
assert!(*value1.borrow() == 42);
}
}
| {
Ref::from_raw_non_null(self.0)
} | identifier_body |
opt_vec.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.
/*!
*
* Defines a type OptVec<T> that can be used in place of ~[T].
* OptVec avoids the need for allocation for empty vectors.
* OptVec implements the iterable interface as well as
* other useful things like `push()` and `len()`.
*/
use core::prelude::*;
use core::old_iter;
use core::old_iter::BaseIter;
#[deriving(Encodable, Decodable)]
pub enum OptVec<T> {
Empty,
Vec(~[T])
}
pub fn with<T>(t: T) -> OptVec<T> {
Vec(~[t])
}
pub fn from<T>(t: ~[T]) -> OptVec<T> {
if t.len() == 0 {
Empty
} else {
Vec(t)
}
}
impl<T> OptVec<T> {
fn push(&mut self, t: T) {
match *self {
Vec(ref mut v) => {
v.push(t);
return;
}
Empty => {}
}
// FIXME(#5074): flow insensitive means we can't move
// assignment inside `match`
*self = Vec(~[t]);
}
fn map<U>(&self, op: &fn(&T) -> U) -> OptVec<U> {
match *self {
Empty => Empty,
Vec(ref v) => Vec(v.map(op))
}
}
fn get<'a>(&'a self, i: uint) -> &'a T {
match *self {
Empty => fail!("Invalid index %u", i),
Vec(ref v) => &v[i]
}
}
fn is_empty(&self) -> bool {
self.len() == 0
}
fn len(&self) -> uint {
match *self {
Empty => 0,
Vec(ref v) => v.len()
}
}
}
pub fn take_vec<T>(v: OptVec<T>) -> ~[T] |
impl<T:Copy> OptVec<T> {
fn prepend(&self, t: T) -> OptVec<T> {
let mut v0 = ~[t];
match *self {
Empty => {}
Vec(ref v1) => { v0.push_all(*v1); }
}
return Vec(v0);
}
fn push_all<I: BaseIter<T>>(&mut self, from: &I) {
for from.each |e| {
self.push(copy *e);
}
}
#[inline(always)]
fn mapi_to_vec<B>(&self, op: &fn(uint, &T) -> B) -> ~[B] {
let mut index = 0;
old_iter::map_to_vec(self, |a| {
let i = index;
index += 1;
op(i, a)
})
}
}
impl<A:Eq> Eq for OptVec<A> {
fn eq(&self, other: &OptVec<A>) -> bool {
// Note: cannot use #[deriving(Eq)] here because
// (Empty, Vec(~[])) ought to be equal.
match (self, other) {
(&Empty, &Empty) => true,
(&Empty, &Vec(ref v)) => v.is_empty(),
(&Vec(ref v), &Empty) => v.is_empty(),
(&Vec(ref v1), &Vec(ref v2)) => *v1 == *v2
}
}
fn ne(&self, other: &OptVec<A>) -> bool {
!self.eq(other)
}
}
impl<A> BaseIter<A> for OptVec<A> {
#[cfg(stage0)]
fn each(&self, blk: &fn(v: &A) -> bool) {
match *self {
Empty => {}
Vec(ref v) => v.each(blk)
}
}
#[cfg(not(stage0))]
fn each(&self, blk: &fn(v: &A) -> bool) -> bool {
match *self {
Empty => true,
Vec(ref v) => v.each(blk)
}
}
fn size_hint(&self) -> Option<uint> {
Some(self.len())
}
}
impl<A> old_iter::ExtendedIter<A> for OptVec<A> {
#[inline(always)]
#[cfg(stage0)]
fn eachi(&self, blk: &fn(v: uint, v: &A) -> bool) {
old_iter::eachi(self, blk)
}
#[inline(always)]
#[cfg(not(stage0))]
fn eachi(&self, blk: &fn(v: uint, v: &A) -> bool) -> bool {
old_iter::eachi(self, blk)
}
#[inline(always)]
fn all(&self, blk: &fn(&A) -> bool) -> bool {
old_iter::all(self, blk)
}
#[inline(always)]
fn any(&self, blk: &fn(&A) -> bool) -> bool {
old_iter::any(self, blk)
}
#[inline(always)]
fn foldl<B>(&self, b0: B, blk: &fn(&B, &A) -> B) -> B {
old_iter::foldl(self, b0, blk)
}
#[inline(always)]
fn position(&self, f: &fn(&A) -> bool) -> Option<uint> {
old_iter::position(self, f)
}
#[inline(always)]
fn map_to_vec<B>(&self, op: &fn(&A) -> B) -> ~[B] {
old_iter::map_to_vec(self, op)
}
#[inline(always)]
fn flat_map_to_vec<B,IB:BaseIter<B>>(&self, op: &fn(&A) -> IB)
-> ~[B] {
old_iter::flat_map_to_vec(self, op)
}
}
impl<A: Eq> old_iter::EqIter<A> for OptVec<A> {
#[inline(always)]
fn contains(&self, x: &A) -> bool { old_iter::contains(self, x) }
#[inline(always)]
fn count(&self, x: &A) -> uint { old_iter::count(self, x) }
}
impl<A: Copy> old_iter::CopyableIter<A> for OptVec<A> {
#[inline(always)]
fn filter_to_vec(&self, pred: &fn(&A) -> bool) -> ~[A] {
old_iter::filter_to_vec(self, pred)
}
#[inline(always)]
fn to_vec(&self) -> ~[A] { old_iter::to_vec(self) }
#[inline(always)]
fn find(&self, f: &fn(&A) -> bool) -> Option<A> {
old_iter::find(self, f)
}
}
impl<A: Copy+Ord> old_iter::CopyableOrderedIter<A> for OptVec<A> {
#[inline(always)]
fn min(&self) -> A { old_iter::min(self) }
#[inline(always)]
fn max(&self) -> A { old_iter::max(self) }
}
| {
match v {
Empty => ~[],
Vec(v) => v
}
} | identifier_body |
opt_vec.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.
/*!
*
* Defines a type OptVec<T> that can be used in place of ~[T].
* OptVec avoids the need for allocation for empty vectors.
* OptVec implements the iterable interface as well as
* other useful things like `push()` and `len()`.
*/
use core::prelude::*;
use core::old_iter;
use core::old_iter::BaseIter;
#[deriving(Encodable, Decodable)]
pub enum OptVec<T> {
Empty,
Vec(~[T])
}
pub fn with<T>(t: T) -> OptVec<T> {
Vec(~[t])
}
pub fn from<T>(t: ~[T]) -> OptVec<T> {
if t.len() == 0 {
Empty
} else {
Vec(t)
}
}
impl<T> OptVec<T> {
fn push(&mut self, t: T) {
match *self {
Vec(ref mut v) => {
v.push(t);
return;
}
Empty => {}
}
// FIXME(#5074): flow insensitive means we can't move
// assignment inside `match`
*self = Vec(~[t]);
}
fn map<U>(&self, op: &fn(&T) -> U) -> OptVec<U> {
match *self {
Empty => Empty,
Vec(ref v) => Vec(v.map(op))
}
}
fn get<'a>(&'a self, i: uint) -> &'a T {
match *self {
Empty => fail!("Invalid index %u", i),
Vec(ref v) => &v[i]
}
}
fn is_empty(&self) -> bool {
self.len() == 0
}
fn len(&self) -> uint {
match *self {
Empty => 0,
Vec(ref v) => v.len()
}
}
}
pub fn take_vec<T>(v: OptVec<T>) -> ~[T] {
match v {
Empty => ~[], | Vec(v) => v
}
}
impl<T:Copy> OptVec<T> {
fn prepend(&self, t: T) -> OptVec<T> {
let mut v0 = ~[t];
match *self {
Empty => {}
Vec(ref v1) => { v0.push_all(*v1); }
}
return Vec(v0);
}
fn push_all<I: BaseIter<T>>(&mut self, from: &I) {
for from.each |e| {
self.push(copy *e);
}
}
#[inline(always)]
fn mapi_to_vec<B>(&self, op: &fn(uint, &T) -> B) -> ~[B] {
let mut index = 0;
old_iter::map_to_vec(self, |a| {
let i = index;
index += 1;
op(i, a)
})
}
}
impl<A:Eq> Eq for OptVec<A> {
fn eq(&self, other: &OptVec<A>) -> bool {
// Note: cannot use #[deriving(Eq)] here because
// (Empty, Vec(~[])) ought to be equal.
match (self, other) {
(&Empty, &Empty) => true,
(&Empty, &Vec(ref v)) => v.is_empty(),
(&Vec(ref v), &Empty) => v.is_empty(),
(&Vec(ref v1), &Vec(ref v2)) => *v1 == *v2
}
}
fn ne(&self, other: &OptVec<A>) -> bool {
!self.eq(other)
}
}
impl<A> BaseIter<A> for OptVec<A> {
#[cfg(stage0)]
fn each(&self, blk: &fn(v: &A) -> bool) {
match *self {
Empty => {}
Vec(ref v) => v.each(blk)
}
}
#[cfg(not(stage0))]
fn each(&self, blk: &fn(v: &A) -> bool) -> bool {
match *self {
Empty => true,
Vec(ref v) => v.each(blk)
}
}
fn size_hint(&self) -> Option<uint> {
Some(self.len())
}
}
impl<A> old_iter::ExtendedIter<A> for OptVec<A> {
#[inline(always)]
#[cfg(stage0)]
fn eachi(&self, blk: &fn(v: uint, v: &A) -> bool) {
old_iter::eachi(self, blk)
}
#[inline(always)]
#[cfg(not(stage0))]
fn eachi(&self, blk: &fn(v: uint, v: &A) -> bool) -> bool {
old_iter::eachi(self, blk)
}
#[inline(always)]
fn all(&self, blk: &fn(&A) -> bool) -> bool {
old_iter::all(self, blk)
}
#[inline(always)]
fn any(&self, blk: &fn(&A) -> bool) -> bool {
old_iter::any(self, blk)
}
#[inline(always)]
fn foldl<B>(&self, b0: B, blk: &fn(&B, &A) -> B) -> B {
old_iter::foldl(self, b0, blk)
}
#[inline(always)]
fn position(&self, f: &fn(&A) -> bool) -> Option<uint> {
old_iter::position(self, f)
}
#[inline(always)]
fn map_to_vec<B>(&self, op: &fn(&A) -> B) -> ~[B] {
old_iter::map_to_vec(self, op)
}
#[inline(always)]
fn flat_map_to_vec<B,IB:BaseIter<B>>(&self, op: &fn(&A) -> IB)
-> ~[B] {
old_iter::flat_map_to_vec(self, op)
}
}
impl<A: Eq> old_iter::EqIter<A> for OptVec<A> {
#[inline(always)]
fn contains(&self, x: &A) -> bool { old_iter::contains(self, x) }
#[inline(always)]
fn count(&self, x: &A) -> uint { old_iter::count(self, x) }
}
impl<A: Copy> old_iter::CopyableIter<A> for OptVec<A> {
#[inline(always)]
fn filter_to_vec(&self, pred: &fn(&A) -> bool) -> ~[A] {
old_iter::filter_to_vec(self, pred)
}
#[inline(always)]
fn to_vec(&self) -> ~[A] { old_iter::to_vec(self) }
#[inline(always)]
fn find(&self, f: &fn(&A) -> bool) -> Option<A> {
old_iter::find(self, f)
}
}
impl<A: Copy+Ord> old_iter::CopyableOrderedIter<A> for OptVec<A> {
#[inline(always)]
fn min(&self) -> A { old_iter::min(self) }
#[inline(always)]
fn max(&self) -> A { old_iter::max(self) }
} | random_line_split |
|
opt_vec.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.
/*!
*
* Defines a type OptVec<T> that can be used in place of ~[T].
* OptVec avoids the need for allocation for empty vectors.
* OptVec implements the iterable interface as well as
* other useful things like `push()` and `len()`.
*/
use core::prelude::*;
use core::old_iter;
use core::old_iter::BaseIter;
#[deriving(Encodable, Decodable)]
pub enum OptVec<T> {
Empty,
Vec(~[T])
}
pub fn with<T>(t: T) -> OptVec<T> {
Vec(~[t])
}
pub fn from<T>(t: ~[T]) -> OptVec<T> {
if t.len() == 0 {
Empty
} else {
Vec(t)
}
}
impl<T> OptVec<T> {
fn push(&mut self, t: T) {
match *self {
Vec(ref mut v) => {
v.push(t);
return;
}
Empty => {}
}
// FIXME(#5074): flow insensitive means we can't move
// assignment inside `match`
*self = Vec(~[t]);
}
fn map<U>(&self, op: &fn(&T) -> U) -> OptVec<U> {
match *self {
Empty => Empty,
Vec(ref v) => Vec(v.map(op))
}
}
fn | <'a>(&'a self, i: uint) -> &'a T {
match *self {
Empty => fail!("Invalid index %u", i),
Vec(ref v) => &v[i]
}
}
fn is_empty(&self) -> bool {
self.len() == 0
}
fn len(&self) -> uint {
match *self {
Empty => 0,
Vec(ref v) => v.len()
}
}
}
pub fn take_vec<T>(v: OptVec<T>) -> ~[T] {
match v {
Empty => ~[],
Vec(v) => v
}
}
impl<T:Copy> OptVec<T> {
fn prepend(&self, t: T) -> OptVec<T> {
let mut v0 = ~[t];
match *self {
Empty => {}
Vec(ref v1) => { v0.push_all(*v1); }
}
return Vec(v0);
}
fn push_all<I: BaseIter<T>>(&mut self, from: &I) {
for from.each |e| {
self.push(copy *e);
}
}
#[inline(always)]
fn mapi_to_vec<B>(&self, op: &fn(uint, &T) -> B) -> ~[B] {
let mut index = 0;
old_iter::map_to_vec(self, |a| {
let i = index;
index += 1;
op(i, a)
})
}
}
impl<A:Eq> Eq for OptVec<A> {
fn eq(&self, other: &OptVec<A>) -> bool {
// Note: cannot use #[deriving(Eq)] here because
// (Empty, Vec(~[])) ought to be equal.
match (self, other) {
(&Empty, &Empty) => true,
(&Empty, &Vec(ref v)) => v.is_empty(),
(&Vec(ref v), &Empty) => v.is_empty(),
(&Vec(ref v1), &Vec(ref v2)) => *v1 == *v2
}
}
fn ne(&self, other: &OptVec<A>) -> bool {
!self.eq(other)
}
}
impl<A> BaseIter<A> for OptVec<A> {
#[cfg(stage0)]
fn each(&self, blk: &fn(v: &A) -> bool) {
match *self {
Empty => {}
Vec(ref v) => v.each(blk)
}
}
#[cfg(not(stage0))]
fn each(&self, blk: &fn(v: &A) -> bool) -> bool {
match *self {
Empty => true,
Vec(ref v) => v.each(blk)
}
}
fn size_hint(&self) -> Option<uint> {
Some(self.len())
}
}
impl<A> old_iter::ExtendedIter<A> for OptVec<A> {
#[inline(always)]
#[cfg(stage0)]
fn eachi(&self, blk: &fn(v: uint, v: &A) -> bool) {
old_iter::eachi(self, blk)
}
#[inline(always)]
#[cfg(not(stage0))]
fn eachi(&self, blk: &fn(v: uint, v: &A) -> bool) -> bool {
old_iter::eachi(self, blk)
}
#[inline(always)]
fn all(&self, blk: &fn(&A) -> bool) -> bool {
old_iter::all(self, blk)
}
#[inline(always)]
fn any(&self, blk: &fn(&A) -> bool) -> bool {
old_iter::any(self, blk)
}
#[inline(always)]
fn foldl<B>(&self, b0: B, blk: &fn(&B, &A) -> B) -> B {
old_iter::foldl(self, b0, blk)
}
#[inline(always)]
fn position(&self, f: &fn(&A) -> bool) -> Option<uint> {
old_iter::position(self, f)
}
#[inline(always)]
fn map_to_vec<B>(&self, op: &fn(&A) -> B) -> ~[B] {
old_iter::map_to_vec(self, op)
}
#[inline(always)]
fn flat_map_to_vec<B,IB:BaseIter<B>>(&self, op: &fn(&A) -> IB)
-> ~[B] {
old_iter::flat_map_to_vec(self, op)
}
}
impl<A: Eq> old_iter::EqIter<A> for OptVec<A> {
#[inline(always)]
fn contains(&self, x: &A) -> bool { old_iter::contains(self, x) }
#[inline(always)]
fn count(&self, x: &A) -> uint { old_iter::count(self, x) }
}
impl<A: Copy> old_iter::CopyableIter<A> for OptVec<A> {
#[inline(always)]
fn filter_to_vec(&self, pred: &fn(&A) -> bool) -> ~[A] {
old_iter::filter_to_vec(self, pred)
}
#[inline(always)]
fn to_vec(&self) -> ~[A] { old_iter::to_vec(self) }
#[inline(always)]
fn find(&self, f: &fn(&A) -> bool) -> Option<A> {
old_iter::find(self, f)
}
}
impl<A: Copy+Ord> old_iter::CopyableOrderedIter<A> for OptVec<A> {
#[inline(always)]
fn min(&self) -> A { old_iter::min(self) }
#[inline(always)]
fn max(&self) -> A { old_iter::max(self) }
}
| get | identifier_name |
font_template.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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use std::fmt::{Debug, Error, Formatter};
use std::io::Error as IoError;
use std::sync::{Arc, Weak};
use std::u32;
use string_cache::Atom;
use style::computed_values::{font_stretch, font_weight};
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Eq, Hash, Deserialize, Serialize, Debug)]
pub struct FontTemplateDescriptor {
pub weight: font_weight::T,
pub stretch: font_stretch::T,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: font_weight::T, stretch: font_stretch::T, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
/// Returns a score indicating how far apart visually the two font descriptors are. This is
/// used for fuzzy font selection.
///
/// The smaller the score, the better the fonts match. 0 indicates an exact match. This must
/// be commutative (distance(A, B) == distance(B, A)).
#[inline]
fn distance_from(&self, other: &FontTemplateDescriptor) -> u32 {
if self.stretch!= other.stretch || self.italic!= other.italic {
// A value higher than all weights.
return 1000
}
((self.weight as i16) - (other.weight as i16)).abs() as u32
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight == other.weight && self.stretch == other.stretch && self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
impl Debug for FontTemplate {
fn | (&self, f: &mut Formatter) -> Result<(), Error> {
self.identifier.fmt(f)
}
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> Result<FontTemplate, IoError> {
let maybe_data = match maybe_bytes {
Some(_) => Some(try!(FontTemplateData::new(identifier.clone(), maybe_bytes))),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(Arc::downgrade(strong_ref)),
None => None,
};
Ok(FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
})
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn data_for_descriptor(&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
match self.descriptor {
Some(actual_desc) if *requested_desc == actual_desc => self.data().ok(),
Some(_) => None,
None => {
if self.instantiate(fctx).is_err() {
return None
}
if self.descriptor
.as_ref()
.expect("Instantiation succeeded but no descriptor?") == requested_desc {
self.data().ok()
} else {
None
}
}
}
}
/// Returns the font data along with the distance between this font's descriptor and the given
/// descriptor, if the font can be loaded.
pub fn data_for_approximate_descriptor(&mut self,
font_context: &FontContextHandle,
requested_descriptor: &FontTemplateDescriptor)
-> Option<(Arc<FontTemplateData>, u32)> {
match self.descriptor {
Some(actual_descriptor) => {
self.data().ok().map(|data| {
(data, actual_descriptor.distance_from(requested_descriptor))
})
}
None => {
if self.instantiate(font_context).is_ok() {
let distance = self.descriptor
.as_ref()
.expect("Instantiation successful but no descriptor?")
.distance_from(requested_descriptor);
self.data().ok().map(|data| (data, distance))
} else {
None
}
}
}
}
fn instantiate(&mut self, font_context: &FontContextHandle) -> Result<(), ()> {
if!self.is_valid {
return Err(())
}
let data = try!(self.data().map_err(|_| ()));
let handle: Result<FontHandle, ()> = FontHandleMethods::new_from_template(font_context,
data,
None);
self.is_valid = handle.is_ok();
let handle = try!(handle);
self.descriptor = Some(FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
handle.is_italic()));
Ok(())
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
self.data().ok()
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn data(&mut self) -> Result<Arc<FontTemplateData>, IoError> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return Ok(data)
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(try!(FontTemplateData::new(self.identifier.clone(), None)));
self.weak_ref = Some(Arc::downgrade(&template_data));
Ok(template_data)
}
}
| fmt | identifier_name |
font_template.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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use std::fmt::{Debug, Error, Formatter};
use std::io::Error as IoError;
use std::sync::{Arc, Weak};
use std::u32;
use string_cache::Atom;
use style::computed_values::{font_stretch, font_weight};
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Eq, Hash, Deserialize, Serialize, Debug)]
pub struct FontTemplateDescriptor {
pub weight: font_weight::T,
pub stretch: font_stretch::T,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: font_weight::T, stretch: font_stretch::T, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
/// Returns a score indicating how far apart visually the two font descriptors are. This is
/// used for fuzzy font selection.
///
/// The smaller the score, the better the fonts match. 0 indicates an exact match. This must
/// be commutative (distance(A, B) == distance(B, A)).
#[inline]
fn distance_from(&self, other: &FontTemplateDescriptor) -> u32 {
if self.stretch!= other.stretch || self.italic!= other.italic {
// A value higher than all weights.
return 1000
}
((self.weight as i16) - (other.weight as i16)).abs() as u32
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool |
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
impl Debug for FontTemplate {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
self.identifier.fmt(f)
}
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> Result<FontTemplate, IoError> {
let maybe_data = match maybe_bytes {
Some(_) => Some(try!(FontTemplateData::new(identifier.clone(), maybe_bytes))),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(Arc::downgrade(strong_ref)),
None => None,
};
Ok(FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
})
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn data_for_descriptor(&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
match self.descriptor {
Some(actual_desc) if *requested_desc == actual_desc => self.data().ok(),
Some(_) => None,
None => {
if self.instantiate(fctx).is_err() {
return None
}
if self.descriptor
.as_ref()
.expect("Instantiation succeeded but no descriptor?") == requested_desc {
self.data().ok()
} else {
None
}
}
}
}
/// Returns the font data along with the distance between this font's descriptor and the given
/// descriptor, if the font can be loaded.
pub fn data_for_approximate_descriptor(&mut self,
font_context: &FontContextHandle,
requested_descriptor: &FontTemplateDescriptor)
-> Option<(Arc<FontTemplateData>, u32)> {
match self.descriptor {
Some(actual_descriptor) => {
self.data().ok().map(|data| {
(data, actual_descriptor.distance_from(requested_descriptor))
})
}
None => {
if self.instantiate(font_context).is_ok() {
let distance = self.descriptor
.as_ref()
.expect("Instantiation successful but no descriptor?")
.distance_from(requested_descriptor);
self.data().ok().map(|data| (data, distance))
} else {
None
}
}
}
}
fn instantiate(&mut self, font_context: &FontContextHandle) -> Result<(), ()> {
if!self.is_valid {
return Err(())
}
let data = try!(self.data().map_err(|_| ()));
let handle: Result<FontHandle, ()> = FontHandleMethods::new_from_template(font_context,
data,
None);
self.is_valid = handle.is_ok();
let handle = try!(handle);
self.descriptor = Some(FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
handle.is_italic()));
Ok(())
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
self.data().ok()
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn data(&mut self) -> Result<Arc<FontTemplateData>, IoError> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return Ok(data)
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(try!(FontTemplateData::new(self.identifier.clone(), None)));
self.weak_ref = Some(Arc::downgrade(&template_data));
Ok(template_data)
}
}
| {
self.weight == other.weight && self.stretch == other.stretch && self.italic == other.italic
} | identifier_body |
font_template.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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use std::fmt::{Debug, Error, Formatter};
use std::io::Error as IoError;
use std::sync::{Arc, Weak};
use std::u32;
use string_cache::Atom;
use style::computed_values::{font_stretch, font_weight};
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Eq, Hash, Deserialize, Serialize, Debug)]
pub struct FontTemplateDescriptor {
pub weight: font_weight::T,
pub stretch: font_stretch::T,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: font_weight::T, stretch: font_stretch::T, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
/// Returns a score indicating how far apart visually the two font descriptors are. This is
/// used for fuzzy font selection.
/// | #[inline]
fn distance_from(&self, other: &FontTemplateDescriptor) -> u32 {
if self.stretch!= other.stretch || self.italic!= other.italic {
// A value higher than all weights.
return 1000
}
((self.weight as i16) - (other.weight as i16)).abs() as u32
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight == other.weight && self.stretch == other.stretch && self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
impl Debug for FontTemplate {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
self.identifier.fmt(f)
}
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> Result<FontTemplate, IoError> {
let maybe_data = match maybe_bytes {
Some(_) => Some(try!(FontTemplateData::new(identifier.clone(), maybe_bytes))),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(Arc::downgrade(strong_ref)),
None => None,
};
Ok(FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
})
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn data_for_descriptor(&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
match self.descriptor {
Some(actual_desc) if *requested_desc == actual_desc => self.data().ok(),
Some(_) => None,
None => {
if self.instantiate(fctx).is_err() {
return None
}
if self.descriptor
.as_ref()
.expect("Instantiation succeeded but no descriptor?") == requested_desc {
self.data().ok()
} else {
None
}
}
}
}
/// Returns the font data along with the distance between this font's descriptor and the given
/// descriptor, if the font can be loaded.
pub fn data_for_approximate_descriptor(&mut self,
font_context: &FontContextHandle,
requested_descriptor: &FontTemplateDescriptor)
-> Option<(Arc<FontTemplateData>, u32)> {
match self.descriptor {
Some(actual_descriptor) => {
self.data().ok().map(|data| {
(data, actual_descriptor.distance_from(requested_descriptor))
})
}
None => {
if self.instantiate(font_context).is_ok() {
let distance = self.descriptor
.as_ref()
.expect("Instantiation successful but no descriptor?")
.distance_from(requested_descriptor);
self.data().ok().map(|data| (data, distance))
} else {
None
}
}
}
}
fn instantiate(&mut self, font_context: &FontContextHandle) -> Result<(), ()> {
if!self.is_valid {
return Err(())
}
let data = try!(self.data().map_err(|_| ()));
let handle: Result<FontHandle, ()> = FontHandleMethods::new_from_template(font_context,
data,
None);
self.is_valid = handle.is_ok();
let handle = try!(handle);
self.descriptor = Some(FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
handle.is_italic()));
Ok(())
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
self.data().ok()
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn data(&mut self) -> Result<Arc<FontTemplateData>, IoError> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return Ok(data)
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(try!(FontTemplateData::new(self.identifier.clone(), None)));
self.weak_ref = Some(Arc::downgrade(&template_data));
Ok(template_data)
}
} | /// The smaller the score, the better the fonts match. 0 indicates an exact match. This must
/// be commutative (distance(A, B) == distance(B, A)). | random_line_split |
x86_64_unknown_dragonfly.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.
use target::Target;
pub fn | () -> Target {
let mut base = super::dragonfly_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.push("-m64".to_string());
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(),
llvm_target: "x86_64-unknown-dragonfly".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
arch: "x86_64".to_string(),
target_os: "dragonfly".to_string(),
target_env: "".to_string(),
options: base,
}
}
| target | identifier_name |
x86_64_unknown_dragonfly.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.
use target::Target;
pub fn target() -> Target {
let mut base = super::dragonfly_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.push("-m64".to_string());
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(),
llvm_target: "x86_64-unknown-dragonfly".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
arch: "x86_64".to_string(),
target_os: "dragonfly".to_string(),
target_env: "".to_string(),
options: base,
} | } | random_line_split |
|
x86_64_unknown_dragonfly.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.
use target::Target;
pub fn target() -> Target | {
let mut base = super::dragonfly_base::opts();
base.cpu = "x86-64".to_string();
base.pre_link_args.push("-m64".to_string());
Target {
data_layout: "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-\
f32:32:32-f64:64:64-v64:64:64-v128:128:128-a:0:64-\
s0:64:64-f80:128:128-n8:16:32:64-S128".to_string(),
llvm_target: "x86_64-unknown-dragonfly".to_string(),
target_endian: "little".to_string(),
target_pointer_width: "64".to_string(),
arch: "x86_64".to_string(),
target_os: "dragonfly".to_string(),
target_env: "".to_string(),
options: base,
}
} | identifier_body |
|
parallel.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/. */
//! Implements parallel traversal over the DOM tree.
//!
//! This traversal is based on Rayon, and therefore its safety is largely
//! verified by the type system.
//!
//! The primary trickiness and fine print for the above relates to the
//! thread safety of the DOM nodes themselves. Accessing a DOM element
//! concurrently on multiple threads is actually mostly "safe", since all
//! the mutable state is protected by an AtomicRefCell, and so we'll
//! generally panic if something goes wrong. Still, we try to to enforce our
//! thread invariants at compile time whenever possible. As such, TNode and
//! TElement are not Send, so ordinary style system code cannot accidentally
//! share them with other threads. In the parallel traversal, we explicitly
//! invoke |unsafe { SendNode::new(n) }| to put nodes in containers that may
//! be sent to other threads. This occurs in only a handful of places and is
//! easy to grep for. At the time of this writing, there is no other unsafe
//! code in the parallel traversal.
#![deny(missing_docs)]
use arrayvec::ArrayVec;
use context::TraversalStatistics;
use dom::{OpaqueNode, SendNode, TElement, TNode};
use rayon;
use scoped_tls::ScopedTLS;
use smallvec::SmallVec;
use std::borrow::Borrow;
use std::mem;
use time;
use traversal::{DomTraversal, PerLevelTraversalData, PreTraverseToken};
/// The maximum number of child nodes that we will process as a single unit.
///
/// Larger values will increase style sharing cache hits and general DOM locality
/// at the expense of decreased opportunities for parallelism. This value has not
/// been measured and could potentially be tuned.
pub const WORK_UNIT_MAX: usize = 16;
/// A set of nodes, sized to the work unit. This gets copied when sent to other
/// threads, so we keep it compact.
type WorkUnit<N> = ArrayVec<[SendNode<N>; WORK_UNIT_MAX]>;
/// Entry point for the parallel traversal.
#[allow(unsafe_code)]
pub fn traverse_dom<E, D>(traversal: &D,
root: E,
token: PreTraverseToken,
pool: &rayon::ThreadPool)
where E: TElement,
D: DomTraversal<E>,
{
let dump_stats = traversal.shared_context().options.dump_style_statistics;
let start_time = if dump_stats { Some(time::precise_time_s()) } else { None };
// Set up the SmallVec. We need to move this, and in most cases this is just
// one node, so keep it small.
let mut nodes = SmallVec::<[SendNode<E::ConcreteNode>; 8]>::new();
debug_assert!(traversal.is_parallel());
// Handle Gecko's eager initial styling. We don't currently support it
// in conjunction with bottom-up traversal. If we did, we'd need to put
// it on the context to make it available to the bottom-up phase.
let depth = if token.traverse_unstyled_children_only() {
debug_assert!(!D::needs_postorder_traversal());
for kid in root.as_node().traversal_children() {
if kid.as_element().map_or(false, |el| el.get_data().is_none()) {
nodes.push(unsafe { SendNode::new(kid) });
}
}
root.depth() + 1
} else {
nodes.push(unsafe { SendNode::new(root.as_node()) });
root.depth()
};
if nodes.is_empty() {
return;
}
let traversal_data = PerLevelTraversalData {
current_dom_depth: depth,
};
let tls = ScopedTLS::<D::ThreadLocalContext>::new(pool);
let root = root.as_node().opaque();
pool.install(|| {
rayon::scope(|scope| {
let nodes = nodes;
traverse_nodes(&*nodes,
DispatchMode::TailCall,
root,
traversal_data,
scope,
pool,
traversal,
&tls);
});
});
// Dump statistics to stdout if requested.
if dump_stats {
let slots = unsafe { tls.unsafe_get() };
let mut aggregate = slots.iter().fold(TraversalStatistics::default(), |acc, t| {
match *t.borrow() {
None => acc,
Some(ref cx) => &cx.borrow().statistics + &acc,
}
});
aggregate.finish(traversal, start_time.unwrap());
if aggregate.is_large_traversal() {
println!("{}", aggregate);
}
}
}
/// A callback to create our thread local context. This needs to be
/// out of line so we don't allocate stack space for the entire struct
/// in the caller.
#[inline(never)]
fn create_thread_local_context<'scope, E, D>(
traversal: &'scope D,
slot: &mut Option<D::ThreadLocalContext>)
where E: TElement +'scope,
D: DomTraversal<E>
{
*slot = Some(traversal.create_thread_local_context())
}
/// A parallel top-down DOM traversal.
///
/// This algorithm traverses the DOM in a breadth-first, top-down manner. The
/// goals are:
/// * Never process a child before its parent (since child style depends on
/// parent style). If this were to happen, the styling algorithm would panic.
/// * Prioritize discovering nodes as quickly as possible to maximize
/// opportunities for parallelism.
/// * Style all the children of a given node (i.e. all sibling nodes) on
/// a single thread (with an upper bound to handle nodes with an
/// abnormally large number of children). This is important because we use
/// a thread-local cache to share styles between siblings.
#[inline(always)]
#[allow(unsafe_code)]
fn top_down_dom<'a,'scope, E, D>(nodes: &'a [SendNode<E::ConcreteNode>],
root: OpaqueNode,
mut traversal_data: PerLevelTraversalData,
scope: &'a rayon::Scope<'scope>,
pool: &'scope rayon::ThreadPool,
traversal: &'scope D,
tls: &'scope ScopedTLS<'scope, D::ThreadLocalContext>)
where E: TElement +'scope,
D: DomTraversal<E>,
{
debug_assert!(nodes.len() <= WORK_UNIT_MAX);
// Collect all the children of the elements in our work unit. This will
// contain the combined children of up to WORK_UNIT_MAX nodes, which may
// be numerous. As such, we store it in a large SmallVec to minimize heap-
// spilling, and never move it.
let mut discovered_child_nodes = SmallVec::<[SendNode<E::ConcreteNode>; 128]>::new();
{
// Scope the borrow of the TLS so that the borrow is dropped before
// a potential recursive call when we pass TailCall.
let mut tlc = tls.ensure(
|slot: &mut Option<D::ThreadLocalContext>| create_thread_local_context(traversal, slot));
for n in nodes {
// If the last node we processed produced children, spawn them off
// into a work item. We do this at the beginning of the loop (rather
// than at the end) so that we can traverse the children of the last
// sibling directly on this thread without a spawn call.
//
// This has the important effect of removing the allocation and
// context-switching overhead of the parallel traversal for perfectly
// linear regions of the DOM, i.e.:
//
// <russian><doll><tag><nesting></nesting></tag></doll></russian>
//
// Which are not at all uncommon.
if!discovered_child_nodes.is_empty() {
let children = mem::replace(&mut discovered_child_nodes, Default::default());
let mut traversal_data_copy = traversal_data.clone();
traversal_data_copy.current_dom_depth += 1;
traverse_nodes(&*children,
DispatchMode::NotTailCall,
root,
traversal_data_copy,
scope,
pool,
traversal,
tls);
}
let node = **n;
let mut children_to_process = 0isize;
traversal.process_preorder(&traversal_data, &mut *tlc, node);
if let Some(el) = node.as_element() {
traversal.traverse_children(&mut *tlc, el, |_tlc, kid| {
children_to_process += 1;
discovered_child_nodes.push(unsafe { SendNode::new(kid) })
});
}
traversal.handle_postorder_traversal(&mut *tlc, root, node,
children_to_process);
}
}
// Handle the children of the last element in this work unit. If any exist,
// we can process them (or at least one work unit's worth of them) directly
// on this thread by passing TailCall.
if!discovered_child_nodes.is_empty() {
traversal_data.current_dom_depth += 1;
traverse_nodes(&discovered_child_nodes,
DispatchMode::TailCall,
root,
traversal_data,
scope,
pool,
traversal,
tls);
}
}
/// Controls whether traverse_nodes may make a recursive call to continue
/// doing work, or whether it should always dispatch work asynchronously.
#[derive(Clone, Copy, PartialEq)]
enum DispatchMode {
TailCall,
NotTailCall,
}
impl DispatchMode {
fn is_tail_call(&self) -> bool { matches!(*self, DispatchMode::TailCall) }
}
#[inline]
fn traverse_nodes<'a,'scope, E, D>(nodes: &[SendNode<E::ConcreteNode>],
mode: DispatchMode,
root: OpaqueNode,
traversal_data: PerLevelTraversalData,
scope: &'a rayon::Scope<'scope>,
pool: &'scope rayon::ThreadPool,
traversal: &'scope D,
tls: &'scope ScopedTLS<'scope, D::ThreadLocalContext>)
where E: TElement +'scope,
D: DomTraversal<E>,
{
debug_assert!(!nodes.is_empty());
// This is a tail call from the perspective of the caller. However, we only
// want to actually dispatch the job as a tail call if there's nothing left
// in our local queue. Otherwise we need to return to it to maintain proper
// breadth-first ordering.
let may_dispatch_tail = mode.is_tail_call() &&
!pool.current_thread_has_pending_tasks().unwrap();
// In the common case, our children fit within a single work unit, in which
// case we can pass the SmallVec directly and avoid extra allocation.
if nodes.len() <= WORK_UNIT_MAX {
let work = nodes.iter().cloned().collect::<WorkUnit<E::ConcreteNode>>(); | if may_dispatch_tail {
top_down_dom(&work, root, traversal_data, scope, pool, traversal, tls);
} else {
scope.spawn(move |scope| {
let work = work;
top_down_dom(&work, root, traversal_data, scope, pool, traversal, tls);
});
}
} else {
for chunk in nodes.chunks(WORK_UNIT_MAX) {
let nodes = chunk.iter().cloned().collect::<WorkUnit<E::ConcreteNode>>();
let traversal_data_copy = traversal_data.clone();
scope.spawn(move |scope| {
let n = nodes;
top_down_dom(&*n, root, traversal_data_copy, scope, pool, traversal, tls)
});
}
}
} | random_line_split |
|
parallel.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/. */
//! Implements parallel traversal over the DOM tree.
//!
//! This traversal is based on Rayon, and therefore its safety is largely
//! verified by the type system.
//!
//! The primary trickiness and fine print for the above relates to the
//! thread safety of the DOM nodes themselves. Accessing a DOM element
//! concurrently on multiple threads is actually mostly "safe", since all
//! the mutable state is protected by an AtomicRefCell, and so we'll
//! generally panic if something goes wrong. Still, we try to to enforce our
//! thread invariants at compile time whenever possible. As such, TNode and
//! TElement are not Send, so ordinary style system code cannot accidentally
//! share them with other threads. In the parallel traversal, we explicitly
//! invoke |unsafe { SendNode::new(n) }| to put nodes in containers that may
//! be sent to other threads. This occurs in only a handful of places and is
//! easy to grep for. At the time of this writing, there is no other unsafe
//! code in the parallel traversal.
#![deny(missing_docs)]
use arrayvec::ArrayVec;
use context::TraversalStatistics;
use dom::{OpaqueNode, SendNode, TElement, TNode};
use rayon;
use scoped_tls::ScopedTLS;
use smallvec::SmallVec;
use std::borrow::Borrow;
use std::mem;
use time;
use traversal::{DomTraversal, PerLevelTraversalData, PreTraverseToken};
/// The maximum number of child nodes that we will process as a single unit.
///
/// Larger values will increase style sharing cache hits and general DOM locality
/// at the expense of decreased opportunities for parallelism. This value has not
/// been measured and could potentially be tuned.
pub const WORK_UNIT_MAX: usize = 16;
/// A set of nodes, sized to the work unit. This gets copied when sent to other
/// threads, so we keep it compact.
type WorkUnit<N> = ArrayVec<[SendNode<N>; WORK_UNIT_MAX]>;
/// Entry point for the parallel traversal.
#[allow(unsafe_code)]
pub fn | <E, D>(traversal: &D,
root: E,
token: PreTraverseToken,
pool: &rayon::ThreadPool)
where E: TElement,
D: DomTraversal<E>,
{
let dump_stats = traversal.shared_context().options.dump_style_statistics;
let start_time = if dump_stats { Some(time::precise_time_s()) } else { None };
// Set up the SmallVec. We need to move this, and in most cases this is just
// one node, so keep it small.
let mut nodes = SmallVec::<[SendNode<E::ConcreteNode>; 8]>::new();
debug_assert!(traversal.is_parallel());
// Handle Gecko's eager initial styling. We don't currently support it
// in conjunction with bottom-up traversal. If we did, we'd need to put
// it on the context to make it available to the bottom-up phase.
let depth = if token.traverse_unstyled_children_only() {
debug_assert!(!D::needs_postorder_traversal());
for kid in root.as_node().traversal_children() {
if kid.as_element().map_or(false, |el| el.get_data().is_none()) {
nodes.push(unsafe { SendNode::new(kid) });
}
}
root.depth() + 1
} else {
nodes.push(unsafe { SendNode::new(root.as_node()) });
root.depth()
};
if nodes.is_empty() {
return;
}
let traversal_data = PerLevelTraversalData {
current_dom_depth: depth,
};
let tls = ScopedTLS::<D::ThreadLocalContext>::new(pool);
let root = root.as_node().opaque();
pool.install(|| {
rayon::scope(|scope| {
let nodes = nodes;
traverse_nodes(&*nodes,
DispatchMode::TailCall,
root,
traversal_data,
scope,
pool,
traversal,
&tls);
});
});
// Dump statistics to stdout if requested.
if dump_stats {
let slots = unsafe { tls.unsafe_get() };
let mut aggregate = slots.iter().fold(TraversalStatistics::default(), |acc, t| {
match *t.borrow() {
None => acc,
Some(ref cx) => &cx.borrow().statistics + &acc,
}
});
aggregate.finish(traversal, start_time.unwrap());
if aggregate.is_large_traversal() {
println!("{}", aggregate);
}
}
}
/// A callback to create our thread local context. This needs to be
/// out of line so we don't allocate stack space for the entire struct
/// in the caller.
#[inline(never)]
fn create_thread_local_context<'scope, E, D>(
traversal: &'scope D,
slot: &mut Option<D::ThreadLocalContext>)
where E: TElement +'scope,
D: DomTraversal<E>
{
*slot = Some(traversal.create_thread_local_context())
}
/// A parallel top-down DOM traversal.
///
/// This algorithm traverses the DOM in a breadth-first, top-down manner. The
/// goals are:
/// * Never process a child before its parent (since child style depends on
/// parent style). If this were to happen, the styling algorithm would panic.
/// * Prioritize discovering nodes as quickly as possible to maximize
/// opportunities for parallelism.
/// * Style all the children of a given node (i.e. all sibling nodes) on
/// a single thread (with an upper bound to handle nodes with an
/// abnormally large number of children). This is important because we use
/// a thread-local cache to share styles between siblings.
#[inline(always)]
#[allow(unsafe_code)]
fn top_down_dom<'a,'scope, E, D>(nodes: &'a [SendNode<E::ConcreteNode>],
root: OpaqueNode,
mut traversal_data: PerLevelTraversalData,
scope: &'a rayon::Scope<'scope>,
pool: &'scope rayon::ThreadPool,
traversal: &'scope D,
tls: &'scope ScopedTLS<'scope, D::ThreadLocalContext>)
where E: TElement +'scope,
D: DomTraversal<E>,
{
debug_assert!(nodes.len() <= WORK_UNIT_MAX);
// Collect all the children of the elements in our work unit. This will
// contain the combined children of up to WORK_UNIT_MAX nodes, which may
// be numerous. As such, we store it in a large SmallVec to minimize heap-
// spilling, and never move it.
let mut discovered_child_nodes = SmallVec::<[SendNode<E::ConcreteNode>; 128]>::new();
{
// Scope the borrow of the TLS so that the borrow is dropped before
// a potential recursive call when we pass TailCall.
let mut tlc = tls.ensure(
|slot: &mut Option<D::ThreadLocalContext>| create_thread_local_context(traversal, slot));
for n in nodes {
// If the last node we processed produced children, spawn them off
// into a work item. We do this at the beginning of the loop (rather
// than at the end) so that we can traverse the children of the last
// sibling directly on this thread without a spawn call.
//
// This has the important effect of removing the allocation and
// context-switching overhead of the parallel traversal for perfectly
// linear regions of the DOM, i.e.:
//
// <russian><doll><tag><nesting></nesting></tag></doll></russian>
//
// Which are not at all uncommon.
if!discovered_child_nodes.is_empty() {
let children = mem::replace(&mut discovered_child_nodes, Default::default());
let mut traversal_data_copy = traversal_data.clone();
traversal_data_copy.current_dom_depth += 1;
traverse_nodes(&*children,
DispatchMode::NotTailCall,
root,
traversal_data_copy,
scope,
pool,
traversal,
tls);
}
let node = **n;
let mut children_to_process = 0isize;
traversal.process_preorder(&traversal_data, &mut *tlc, node);
if let Some(el) = node.as_element() {
traversal.traverse_children(&mut *tlc, el, |_tlc, kid| {
children_to_process += 1;
discovered_child_nodes.push(unsafe { SendNode::new(kid) })
});
}
traversal.handle_postorder_traversal(&mut *tlc, root, node,
children_to_process);
}
}
// Handle the children of the last element in this work unit. If any exist,
// we can process them (or at least one work unit's worth of them) directly
// on this thread by passing TailCall.
if!discovered_child_nodes.is_empty() {
traversal_data.current_dom_depth += 1;
traverse_nodes(&discovered_child_nodes,
DispatchMode::TailCall,
root,
traversal_data,
scope,
pool,
traversal,
tls);
}
}
/// Controls whether traverse_nodes may make a recursive call to continue
/// doing work, or whether it should always dispatch work asynchronously.
#[derive(Clone, Copy, PartialEq)]
enum DispatchMode {
TailCall,
NotTailCall,
}
impl DispatchMode {
fn is_tail_call(&self) -> bool { matches!(*self, DispatchMode::TailCall) }
}
#[inline]
fn traverse_nodes<'a,'scope, E, D>(nodes: &[SendNode<E::ConcreteNode>],
mode: DispatchMode,
root: OpaqueNode,
traversal_data: PerLevelTraversalData,
scope: &'a rayon::Scope<'scope>,
pool: &'scope rayon::ThreadPool,
traversal: &'scope D,
tls: &'scope ScopedTLS<'scope, D::ThreadLocalContext>)
where E: TElement +'scope,
D: DomTraversal<E>,
{
debug_assert!(!nodes.is_empty());
// This is a tail call from the perspective of the caller. However, we only
// want to actually dispatch the job as a tail call if there's nothing left
// in our local queue. Otherwise we need to return to it to maintain proper
// breadth-first ordering.
let may_dispatch_tail = mode.is_tail_call() &&
!pool.current_thread_has_pending_tasks().unwrap();
// In the common case, our children fit within a single work unit, in which
// case we can pass the SmallVec directly and avoid extra allocation.
if nodes.len() <= WORK_UNIT_MAX {
let work = nodes.iter().cloned().collect::<WorkUnit<E::ConcreteNode>>();
if may_dispatch_tail {
top_down_dom(&work, root, traversal_data, scope, pool, traversal, tls);
} else {
scope.spawn(move |scope| {
let work = work;
top_down_dom(&work, root, traversal_data, scope, pool, traversal, tls);
});
}
} else {
for chunk in nodes.chunks(WORK_UNIT_MAX) {
let nodes = chunk.iter().cloned().collect::<WorkUnit<E::ConcreteNode>>();
let traversal_data_copy = traversal_data.clone();
scope.spawn(move |scope| {
let n = nodes;
top_down_dom(&*n, root, traversal_data_copy, scope, pool, traversal, tls)
});
}
}
}
| traverse_dom | identifier_name |
keypad.rs | use sdl::event::Key;
pub struct Keypad {
keys: [bool; 16],
}
impl Keypad {
pub fn new() -> Keypad {
Keypad { keys: [false; 16] }
}
pub fn pressed(&mut self, index: usize) -> bool {
self.keys[index]
}
pub fn press(&mut self, key: Key, state: bool) {
match key {
Key::Num1 => self.set_key(0x1, state),
Key::Num2 => self.set_key(0x2, state),
Key::Num3 => self.set_key(0x3, state),
Key::Num4 => self.set_key(0xc, state),
Key::Q => self.set_key(0x4, state),
Key::W => self.set_key(0x5, state),
Key::E => self.set_key(0x6, state), | Key::A => self.set_key(0x7, state),
Key::S => self.set_key(0x8, state),
Key::D => self.set_key(0x9, state),
Key::F => self.set_key(0xe, state),
Key::Z => self.set_key(0xa, state),
Key::X => self.set_key(0x0, state),
Key::C => self.set_key(0xb, state),
Key::V => self.set_key(0xf, state),
_ => (),
}
}
fn set_key(&mut self, index: usize, state: bool) {
self.keys[index] = state;
}
} | Key::R => self.set_key(0xd, state), | random_line_split |
keypad.rs | use sdl::event::Key;
pub struct Keypad {
keys: [bool; 16],
}
impl Keypad {
pub fn new() -> Keypad {
Keypad { keys: [false; 16] }
}
pub fn pressed(&mut self, index: usize) -> bool {
self.keys[index]
}
pub fn press(&mut self, key: Key, state: bool) | }
fn set_key(&mut self, index: usize, state: bool) {
self.keys[index] = state;
}
}
| {
match key {
Key::Num1 => self.set_key(0x1, state),
Key::Num2 => self.set_key(0x2, state),
Key::Num3 => self.set_key(0x3, state),
Key::Num4 => self.set_key(0xc, state),
Key::Q => self.set_key(0x4, state),
Key::W => self.set_key(0x5, state),
Key::E => self.set_key(0x6, state),
Key::R => self.set_key(0xd, state),
Key::A => self.set_key(0x7, state),
Key::S => self.set_key(0x8, state),
Key::D => self.set_key(0x9, state),
Key::F => self.set_key(0xe, state),
Key::Z => self.set_key(0xa, state),
Key::X => self.set_key(0x0, state),
Key::C => self.set_key(0xb, state),
Key::V => self.set_key(0xf, state),
_ => (),
} | identifier_body |
keypad.rs | use sdl::event::Key;
pub struct Keypad {
keys: [bool; 16],
}
impl Keypad {
pub fn | () -> Keypad {
Keypad { keys: [false; 16] }
}
pub fn pressed(&mut self, index: usize) -> bool {
self.keys[index]
}
pub fn press(&mut self, key: Key, state: bool) {
match key {
Key::Num1 => self.set_key(0x1, state),
Key::Num2 => self.set_key(0x2, state),
Key::Num3 => self.set_key(0x3, state),
Key::Num4 => self.set_key(0xc, state),
Key::Q => self.set_key(0x4, state),
Key::W => self.set_key(0x5, state),
Key::E => self.set_key(0x6, state),
Key::R => self.set_key(0xd, state),
Key::A => self.set_key(0x7, state),
Key::S => self.set_key(0x8, state),
Key::D => self.set_key(0x9, state),
Key::F => self.set_key(0xe, state),
Key::Z => self.set_key(0xa, state),
Key::X => self.set_key(0x0, state),
Key::C => self.set_key(0xb, state),
Key::V => self.set_key(0xf, state),
_ => (),
}
}
fn set_key(&mut self, index: usize, state: bool) {
self.keys[index] = state;
}
}
| new | identifier_name |
allocate.rs | // Our use cases
use super::expander;
pub fn allocate_expander(par_eax: i32, par_edx: i32) -> expander::SoundExpander {
let mut sound_expander = expander::SoundExpander::new();
let mut par_eax = par_eax;
let mut par_edx = par_edx;
sound_expander.wave_format_ex.format_tag = expander::WAVE_FORMAT_PCM as u16;
sound_expander.wave_format_ex.channels = 1;
if 8 & par_edx!= 0 {
sound_expander.wave_format_ex.bits_per_sample = 16;
} else {
sound_expander.wave_format_ex.bits_per_sample = 8;
}
sound_expander.wave_format_ex.samples_per_second = 22050; // MixRate
sound_expander.wave_format_ex.block_align = (sound_expander.wave_format_ex.channels * sound_expander.wave_format_ex.bits_per_sample) >> 3;
sound_expander.wave_format_ex.cb_size = 0;
sound_expander.wave_format_ex.average_bytes_per_second = ((sound_expander.wave_format_ex.samples_per_second as u16) * (sound_expander.wave_format_ex.block_align as u16)) as i32;
par_edx = par_edx | 2;
sound_expander.flags1 = par_edx;
sound_expander.flags2 = par_eax;
sound_expander.some_var_6680E8 = 0x10000; // SomeConst6680E8
sound_expander.some_var_6680EC = 0x10; // SomeConst6680EC
sound_expander.read_limit = 0x10000 & 0x10;
sound_expander.memb_64 = 0;
sound_expander.memb_24 = 0;
sound_expander.memb_40 = 0;
sound_expander.memb_28 = 0x14;
sound_expander.flags0 = 0x10000;
if 2 & par_edx!= 0 {
sound_expander.flags0 = sound_expander.flags0 | 0x80;
} else if 4 & par_edx!= 0 {
sound_expander.flags0 = sound_expander.flags0 | 0x40;
} else if 0x40 & par_edx!= 0 {
sound_expander.flags0 = sound_expander.flags0 | 0x20;
}
if 0x10 & par_eax!= 0 {
sound_expander.flags1 = sound_expander.flags1 | 0x20;
sound_expander.loop_point = -1;
} else {
sound_expander.loop_point = 0;
}
sound_expander.memb_58 = -1; | sound_expander.memb_5C = 1;
sound_expander.memb_4C = 0x7FFF;
sound_expander.memb_54 = 0;
sound_expander.previous = Box::new(expander::SoundExpander::new());
sound_expander.next = Box::new(expander::SoundExpander::new());
sound_expander
}
pub fn allocate_sound(par_ecx: i32, par_ebx: i32) -> expander::SoundExpander {
let mut edx = 0x0A;
let mut eax = 0;
match par_ebx {
0x0D => eax = 1,
0x0E => eax = 2,
_ => eax = 0,
}
match par_ecx {
0x0F => eax = eax | 4,
_ => edx = edx | 0x20,
}
allocate_expander(eax, edx)
} | random_line_split |
|
allocate.rs | // Our use cases
use super::expander;
pub fn | (par_eax: i32, par_edx: i32) -> expander::SoundExpander {
let mut sound_expander = expander::SoundExpander::new();
let mut par_eax = par_eax;
let mut par_edx = par_edx;
sound_expander.wave_format_ex.format_tag = expander::WAVE_FORMAT_PCM as u16;
sound_expander.wave_format_ex.channels = 1;
if 8 & par_edx!= 0 {
sound_expander.wave_format_ex.bits_per_sample = 16;
} else {
sound_expander.wave_format_ex.bits_per_sample = 8;
}
sound_expander.wave_format_ex.samples_per_second = 22050; // MixRate
sound_expander.wave_format_ex.block_align = (sound_expander.wave_format_ex.channels * sound_expander.wave_format_ex.bits_per_sample) >> 3;
sound_expander.wave_format_ex.cb_size = 0;
sound_expander.wave_format_ex.average_bytes_per_second = ((sound_expander.wave_format_ex.samples_per_second as u16) * (sound_expander.wave_format_ex.block_align as u16)) as i32;
par_edx = par_edx | 2;
sound_expander.flags1 = par_edx;
sound_expander.flags2 = par_eax;
sound_expander.some_var_6680E8 = 0x10000; // SomeConst6680E8
sound_expander.some_var_6680EC = 0x10; // SomeConst6680EC
sound_expander.read_limit = 0x10000 & 0x10;
sound_expander.memb_64 = 0;
sound_expander.memb_24 = 0;
sound_expander.memb_40 = 0;
sound_expander.memb_28 = 0x14;
sound_expander.flags0 = 0x10000;
if 2 & par_edx!= 0 {
sound_expander.flags0 = sound_expander.flags0 | 0x80;
} else if 4 & par_edx!= 0 {
sound_expander.flags0 = sound_expander.flags0 | 0x40;
} else if 0x40 & par_edx!= 0 {
sound_expander.flags0 = sound_expander.flags0 | 0x20;
}
if 0x10 & par_eax!= 0 {
sound_expander.flags1 = sound_expander.flags1 | 0x20;
sound_expander.loop_point = -1;
} else {
sound_expander.loop_point = 0;
}
sound_expander.memb_58 = -1;
sound_expander.memb_5C = 1;
sound_expander.memb_4C = 0x7FFF;
sound_expander.memb_54 = 0;
sound_expander.previous = Box::new(expander::SoundExpander::new());
sound_expander.next = Box::new(expander::SoundExpander::new());
sound_expander
}
pub fn allocate_sound(par_ecx: i32, par_ebx: i32) -> expander::SoundExpander {
let mut edx = 0x0A;
let mut eax = 0;
match par_ebx {
0x0D => eax = 1,
0x0E => eax = 2,
_ => eax = 0,
}
match par_ecx {
0x0F => eax = eax | 4,
_ => edx = edx | 0x20,
}
allocate_expander(eax, edx)
}
| allocate_expander | identifier_name |
allocate.rs | // Our use cases
use super::expander;
pub fn allocate_expander(par_eax: i32, par_edx: i32) -> expander::SoundExpander {
let mut sound_expander = expander::SoundExpander::new();
let mut par_eax = par_eax;
let mut par_edx = par_edx;
sound_expander.wave_format_ex.format_tag = expander::WAVE_FORMAT_PCM as u16;
sound_expander.wave_format_ex.channels = 1;
if 8 & par_edx!= 0 {
sound_expander.wave_format_ex.bits_per_sample = 16;
} else {
sound_expander.wave_format_ex.bits_per_sample = 8;
}
sound_expander.wave_format_ex.samples_per_second = 22050; // MixRate
sound_expander.wave_format_ex.block_align = (sound_expander.wave_format_ex.channels * sound_expander.wave_format_ex.bits_per_sample) >> 3;
sound_expander.wave_format_ex.cb_size = 0;
sound_expander.wave_format_ex.average_bytes_per_second = ((sound_expander.wave_format_ex.samples_per_second as u16) * (sound_expander.wave_format_ex.block_align as u16)) as i32;
par_edx = par_edx | 2;
sound_expander.flags1 = par_edx;
sound_expander.flags2 = par_eax;
sound_expander.some_var_6680E8 = 0x10000; // SomeConst6680E8
sound_expander.some_var_6680EC = 0x10; // SomeConst6680EC
sound_expander.read_limit = 0x10000 & 0x10;
sound_expander.memb_64 = 0;
sound_expander.memb_24 = 0;
sound_expander.memb_40 = 0;
sound_expander.memb_28 = 0x14;
sound_expander.flags0 = 0x10000;
if 2 & par_edx!= 0 {
sound_expander.flags0 = sound_expander.flags0 | 0x80;
} else if 4 & par_edx!= 0 {
sound_expander.flags0 = sound_expander.flags0 | 0x40;
} else if 0x40 & par_edx!= 0 {
sound_expander.flags0 = sound_expander.flags0 | 0x20;
}
if 0x10 & par_eax!= 0 {
sound_expander.flags1 = sound_expander.flags1 | 0x20;
sound_expander.loop_point = -1;
} else {
sound_expander.loop_point = 0;
}
sound_expander.memb_58 = -1;
sound_expander.memb_5C = 1;
sound_expander.memb_4C = 0x7FFF;
sound_expander.memb_54 = 0;
sound_expander.previous = Box::new(expander::SoundExpander::new());
sound_expander.next = Box::new(expander::SoundExpander::new());
sound_expander
}
pub fn allocate_sound(par_ecx: i32, par_ebx: i32) -> expander::SoundExpander | {
let mut edx = 0x0A;
let mut eax = 0;
match par_ebx {
0x0D => eax = 1,
0x0E => eax = 2,
_ => eax = 0,
}
match par_ecx {
0x0F => eax = eax | 4,
_ => edx = edx | 0x20,
}
allocate_expander(eax, edx)
} | identifier_body |
|
de.rs | use serde::{Deserialize, Deserializer};
use serde_derive::Deserialize;
use tera::{Map, Value};
/// Used as an attribute when we want to convert from TOML to a string date
/// If a TOML datetime isn't present, it will accept a string and push it through
/// TOML's date time parser to ensure only valid dates are accepted.
/// Inspired by this proposal: https://github.com/alexcrichton/toml-rs/issues/269
pub fn from_toml_datetime<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
use std::str::FromStr;
#[derive(Deserialize)]
#[serde(untagged)]
enum | {
Datetime(toml::value::Datetime),
String(String),
}
match MaybeDatetime::deserialize(deserializer)? {
MaybeDatetime::Datetime(d) => Ok(Some(d.to_string())),
MaybeDatetime::String(s) => match toml::value::Datetime::from_str(&s) {
Ok(d) => Ok(Some(d.to_string())),
Err(e) => Err(D::Error::custom(e)),
},
}
}
/// Returns key/value for a converted date from TOML.
/// If the table itself is the TOML struct, only return its value without the key
fn convert_toml_date(table: Map<String, Value>) -> Value {
let mut new = Map::new();
for (k, v) in table {
if k == "$__toml_private_datetime" {
return v;
}
match v {
Value::Object(o) => {
new.insert(k, convert_toml_date(o));
}
_ => {
new.insert(k, v);
}
}
}
Value::Object(new)
}
/// TOML datetimes will be serialized as a struct but we want the
/// stringified version for json, otherwise they are going to be weird
pub fn fix_toml_dates(table: Map<String, Value>) -> Value {
let mut new = Map::new();
for (key, value) in table {
match value {
Value::Object(o) => {
new.insert(key, convert_toml_date(o));
}
Value::Array(arr) => {
let mut new_arr = Vec::with_capacity(arr.len());
for v in arr {
match v {
Value::Object(o) => new_arr.push(fix_toml_dates(o)),
_ => new_arr.push(v),
};
}
new.insert(key, Value::Array(new_arr));
}
_ => {
new.insert(key, value);
}
}
}
Value::Object(new)
}
| MaybeDatetime | identifier_name |
de.rs | use serde::{Deserialize, Deserializer};
use serde_derive::Deserialize;
use tera::{Map, Value};
/// Used as an attribute when we want to convert from TOML to a string date
/// If a TOML datetime isn't present, it will accept a string and push it through
/// TOML's date time parser to ensure only valid dates are accepted.
/// Inspired by this proposal: https://github.com/alexcrichton/toml-rs/issues/269
pub fn from_toml_datetime<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
use std::str::FromStr;
#[derive(Deserialize)]
#[serde(untagged)]
enum MaybeDatetime {
Datetime(toml::value::Datetime),
String(String),
}
match MaybeDatetime::deserialize(deserializer)? {
MaybeDatetime::Datetime(d) => Ok(Some(d.to_string())),
MaybeDatetime::String(s) => match toml::value::Datetime::from_str(&s) {
Ok(d) => Ok(Some(d.to_string())),
Err(e) => Err(D::Error::custom(e)),
},
}
}
/// Returns key/value for a converted date from TOML.
/// If the table itself is the TOML struct, only return its value without the key
fn convert_toml_date(table: Map<String, Value>) -> Value {
let mut new = Map::new();
for (k, v) in table {
if k == "$__toml_private_datetime" {
return v;
}
match v {
Value::Object(o) => {
new.insert(k, convert_toml_date(o));
}
_ => {
new.insert(k, v);
}
}
}
Value::Object(new)
}
/// TOML datetimes will be serialized as a struct but we want the
/// stringified version for json, otherwise they are going to be weird
pub fn fix_toml_dates(table: Map<String, Value>) -> Value {
let mut new = Map::new();
for (key, value) in table {
match value {
Value::Object(o) => {
new.insert(key, convert_toml_date(o));
}
Value::Array(arr) => {
let mut new_arr = Vec::with_capacity(arr.len());
for v in arr {
match v {
Value::Object(o) => new_arr.push(fix_toml_dates(o)),
_ => new_arr.push(v),
};
} | new.insert(key, Value::Array(new_arr));
}
_ => {
new.insert(key, value);
}
}
}
Value::Object(new)
} | random_line_split |
|
errhandlingapi.rs | // Copyright © 2015-2017 winapi-rs developers
// 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.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
//! ApiSet Contract for api-ms-win-core-errorhandling-l1
use shared::basetsd::ULONG_PTR;
use shared::minwindef::{BOOL, DWORD, LPDWORD, UINT, ULONG};
use um::winnt::{
EXCEPTION_POINTERS, LONG, LPCSTR, LPCWSTR, PCONTEXT, PEXCEPTION_RECORD,
PVECTORED_EXCEPTION_HANDLER, PVOID,
};
FN!{stdcall PTOP_LEVEL_EXCEPTION_FILTER(
ExceptionInfo: *mut EXCEPTION_POINTERS,
) -> LONG}
pub type LPTOP_LEVEL_EXCEPTION_FILTER = PTOP_LEVEL_EXCEPTION_FILTER;
extern "system" {
pub fn RaiseException(
dwExceptionCode: DWORD,
dwExceptionFlags: DWORD, | ) -> LONG;
pub fn SetUnhandledExceptionFilter(
lpTopLevelExceptionFilter: LPTOP_LEVEL_EXCEPTION_FILTER,
) -> LPTOP_LEVEL_EXCEPTION_FILTER;
pub fn GetLastError() -> DWORD;
pub fn SetLastError(
dwErrCode: DWORD,
);
pub fn GetErrorMode() -> UINT;
pub fn SetErrorMode(
uMode: UINT,
) -> UINT;
pub fn AddVectoredExceptionHandler(
First: ULONG,
Handler: PVECTORED_EXCEPTION_HANDLER,
) -> PVOID;
pub fn RemoveVectoredExceptionHandler(
Handle: PVOID,
) -> ULONG;
pub fn AddVectoredContinueHandler(
First: ULONG,
Handler: PVECTORED_EXCEPTION_HANDLER,
) -> PVOID;
pub fn RemoveVectoredContinueHandler(
Handle: PVOID,
) -> ULONG;
}
// RestoreLastError
extern "system" {
pub fn RaiseFailFastException(
pExceptionRecord: PEXCEPTION_RECORD,
pContextRecord: PCONTEXT,
dwFlags: DWORD,
);
pub fn FatalAppExitA(
uAction: UINT,
lpMessageText: LPCSTR,
);
pub fn FatalAppExitW(
uAction: UINT,
lpMessageText: LPCWSTR,
);
pub fn GetThreadErrorMode() -> DWORD;
pub fn SetThreadErrorMode(
dwNewMode: DWORD,
lpOldMode: LPDWORD,
) -> BOOL;
}
// What library provides this function?
// TerminateProcessOnMemoryExhaustion | nNumberOfArguments: DWORD,
lpArguments: *const ULONG_PTR,
);
pub fn UnhandledExceptionFilter(
ExceptionInfo: *mut EXCEPTION_POINTERS, | random_line_split |
atmega328p.rs | use chips;
use io;
pub struct Chip;
impl chips::Chip for Chip
{
fn flash_size() -> usize {
32 * 1024 // 32 KB
}
fn memory_size() -> usize {
2 * 1024 // 2KB
}
fn io_ports() -> Vec<io::Port> |
}
| {
vec![
io::Port::new(0x03), // PINB
io::Port::new(0x04), // DDRB
io::Port::new(0x05), // PORTB
io::Port::new(0x06), // PINC
io::Port::new(0x07), // DDRC
io::Port::new(0x08), // PORTC
io::Port::new(0x09), // PIND
io::Port::new(0x0a), // DDRD
io::Port::new(0x0b), // PORTD
]
} | identifier_body |
atmega328p.rs | use chips;
use io;
pub struct Chip;
impl chips::Chip for Chip
{
fn flash_size() -> usize {
32 * 1024 // 32 KB
}
fn | () -> usize {
2 * 1024 // 2KB
}
fn io_ports() -> Vec<io::Port> {
vec![
io::Port::new(0x03), // PINB
io::Port::new(0x04), // DDRB
io::Port::new(0x05), // PORTB
io::Port::new(0x06), // PINC
io::Port::new(0x07), // DDRC
io::Port::new(0x08), // PORTC
io::Port::new(0x09), // PIND
io::Port::new(0x0a), // DDRD
io::Port::new(0x0b), // PORTD
]
}
}
| memory_size | identifier_name |
atmega328p.rs | use chips;
use io;
pub struct Chip;
| {
fn flash_size() -> usize {
32 * 1024 // 32 KB
}
fn memory_size() -> usize {
2 * 1024 // 2KB
}
fn io_ports() -> Vec<io::Port> {
vec![
io::Port::new(0x03), // PINB
io::Port::new(0x04), // DDRB
io::Port::new(0x05), // PORTB
io::Port::new(0x06), // PINC
io::Port::new(0x07), // DDRC
io::Port::new(0x08), // PORTC
io::Port::new(0x09), // PIND
io::Port::new(0x0a), // DDRD
io::Port::new(0x0b), // PORTD
]
}
} | impl chips::Chip for Chip | random_line_split |
context.rs | use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use num::BigRational;
use lang::Filter;
#[derive(Clone, Debug)]
pub enum PrecedenceGroup {
AndThen,
Circumfix
}
#[derive(Clone)]
pub struct Context {
/// A function called each time the parser constructs a new filter anywhere in the syntax tree. If it returns false, the filter is replaced with one that generates an exception.
pub filter_allowed: Arc<Box<Fn(&Filter) -> bool + Send + Sync>>,
/// The context's operators, in decreasing precedence.
pub operators: BTreeMap<BigRational, PrecedenceGroup>
}
impl fmt::Debug for Context {
fn | (&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Context {{ filter_allowed: [Fn(&Filter) -> bool], operators: {:?} }}", self.operators)
}
}
| fmt | identifier_name |
context.rs | use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use num::BigRational;
use lang::Filter;
#[derive(Clone, Debug)]
pub enum PrecedenceGroup {
AndThen,
Circumfix
}
#[derive(Clone)]
pub struct Context {
/// A function called each time the parser constructs a new filter anywhere in the syntax tree. If it returns false, the filter is replaced with one that generates an exception.
pub filter_allowed: Arc<Box<Fn(&Filter) -> bool + Send + Sync>>,
/// The context's operators, in decreasing precedence.
pub operators: BTreeMap<BigRational, PrecedenceGroup>
} | } |
impl fmt::Debug for Context {
fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
write!(w, "Context {{ filter_allowed: [Fn(&Filter) -> bool], operators: {:?} }}", self.operators)
} | random_line_split |
mod.rs | extern crate time;
extern crate slog;
extern crate slog_term;
extern crate slog_envlogger;
extern crate slog_stdlog;
pub mod replica;
pub mod api_server;
pub mod messages;
use std::thread::{self, JoinHandle};
use std::net::TcpStream;
use amy::{Poller, Receiver, Sender};
use self::slog::DrainExt;
use self::time::{SteadyTime, Duration};
use utils::messages::*;
use rabble::{
self,
NodeId,
Node,
Envelope,
Pid,
CorrelationId,
Msg
};
use rabble::serialize::{Serialize, MsgpackSerializer};
type CrNode = Node<RabbleUserMsg>;
type CrReceiver = Receiver<Envelope<RabbleUserMsg>>;
type CrSender = Sender<Envelope<RabbleUserMsg>>;
/// Wait for a function to return true
///
/// After each call of `f()` that returns `false`, sleep for `sleep_time`
/// Returns true if `f()` returns true before the timeout expires
/// Returns false if the runtime of the test exceeds `timeout`
#[allow(dead_code)] // Not used in all tests
pub fn wait_for<F>(timeout: Duration, mut f: F) -> bool
where F: FnMut() -> bool
{
let sleep_time = Duration::milliseconds(10);
let start = SteadyTime::now();
while let false = f() {
thread::sleep(sleep_time.to_std().unwrap());
if SteadyTime::now() - start > timeout {
return false;
}
}
true
}
/// Send a message over a non-blocking socket
/// Wait for it to finish sending or timeout after 5 seconds
/// In practice the first call to serializer.write_msgs should succeed unless the TCP send buffer is
/// tiny.
#[allow(dead_code)] // Not used in all tests
pub fn send(sock: &mut TcpStream,
serializer: &mut MsgpackSerializer<ApiClientMsg>,
msg: ApiClientMsg)
{
if let Ok(true) = serializer.write_msgs(sock, Some(&msg)) {
return;
}
// Just busy wait instead of using a poller in this test.
assert_eq!(true, wait_for(Duration::seconds(5), || {
// We don't know if it's writable, but we want to actually try the write
serializer.set_writable();
match serializer.write_msgs(sock, None) {
Ok(true) => true,
Ok(false) => false,
Err(e) => {
println!("Failed to write to socket: {}", e);
assert!(false);
unreachable!();
}
}
}));
}
#[allow(dead_code)] // Not used in all tests
pub fn create_node_ids(n: usize) -> Vec<NodeId> {
(1..n + 1).map(|n| {
NodeId {
name: format!("node{}", n),
addr: format!("127.0.0.1:1100{}", n)
}
}).collect()
}
#[allow(dead_code)] // Not used in all tests
pub fn start_nodes(n: usize) -> (Vec<Node<RabbleUserMsg>>, Vec<JoinHandle<()>>) {
let term = slog_term::streamer().build();
let drain = slog_envlogger::LogBuilder::new(term)
.filter(None, slog::FilterLevel::Debug).build();
let root_logger = slog::Logger::root(drain.fuse(), None);
slog_stdlog::set_logger(root_logger.clone()).unwrap();
create_node_ids(n).into_iter().fold((Vec::new(), Vec::new()),
|(mut nodes, mut handles), node_id| {
let (node, handle_list) = rabble::rouse(node_id, Some(root_logger.clone()));
nodes.push(node);
handles.extend(handle_list);
(nodes, handles)
})
}
#[allow(dead_code)] // Not used in all tests
pub fn test_pid(node_id: NodeId) -> Pid {
Pid {
name: "test-runner".to_string(),
group: None,
node: node_id
}
}
#[allow(dead_code)] // Not used in all tests
pub fn register_test_as_service(poller: &mut Poller,
nodes: &Vec<CrNode>,
test_tx: &CrSender,
test_rx: &CrReceiver)
{
for node in nodes {
let test_pid = test_pid(node.id.clone());
let correlation_id = CorrelationId::pid(test_pid.clone());
node.register_service(&test_pid, &test_tx).unwrap();
// Wait for registration to succeed
loop {
node.cluster_status(correlation_id.clone()).unwrap(); | while let Ok(envelope) = test_rx.try_recv() {
assert_matches!(envelope.msg, Msg::ClusterStatus(_));
}
break;
}
}
}
} | let notifications = poller.wait(10).unwrap();
if notifications.len() != 0 {
// We have registered, otherwise we wouldn't have gotten a response
// Let's drain the receiver, because we may have returned from a previous poll
// before the previous ClusterStatus response was sent | random_line_split |
mod.rs | extern crate time;
extern crate slog;
extern crate slog_term;
extern crate slog_envlogger;
extern crate slog_stdlog;
pub mod replica;
pub mod api_server;
pub mod messages;
use std::thread::{self, JoinHandle};
use std::net::TcpStream;
use amy::{Poller, Receiver, Sender};
use self::slog::DrainExt;
use self::time::{SteadyTime, Duration};
use utils::messages::*;
use rabble::{
self,
NodeId,
Node,
Envelope,
Pid,
CorrelationId,
Msg
};
use rabble::serialize::{Serialize, MsgpackSerializer};
type CrNode = Node<RabbleUserMsg>;
type CrReceiver = Receiver<Envelope<RabbleUserMsg>>;
type CrSender = Sender<Envelope<RabbleUserMsg>>;
/// Wait for a function to return true
///
/// After each call of `f()` that returns `false`, sleep for `sleep_time`
/// Returns true if `f()` returns true before the timeout expires
/// Returns false if the runtime of the test exceeds `timeout`
#[allow(dead_code)] // Not used in all tests
pub fn wait_for<F>(timeout: Duration, mut f: F) -> bool
where F: FnMut() -> bool
{
let sleep_time = Duration::milliseconds(10);
let start = SteadyTime::now();
while let false = f() {
thread::sleep(sleep_time.to_std().unwrap());
if SteadyTime::now() - start > timeout {
return false;
}
}
true
}
/// Send a message over a non-blocking socket
/// Wait for it to finish sending or timeout after 5 seconds
/// In practice the first call to serializer.write_msgs should succeed unless the TCP send buffer is
/// tiny.
#[allow(dead_code)] // Not used in all tests
pub fn send(sock: &mut TcpStream,
serializer: &mut MsgpackSerializer<ApiClientMsg>,
msg: ApiClientMsg)
{
if let Ok(true) = serializer.write_msgs(sock, Some(&msg)) {
return;
}
// Just busy wait instead of using a poller in this test.
assert_eq!(true, wait_for(Duration::seconds(5), || {
// We don't know if it's writable, but we want to actually try the write
serializer.set_writable();
match serializer.write_msgs(sock, None) {
Ok(true) => true,
Ok(false) => false,
Err(e) => {
println!("Failed to write to socket: {}", e);
assert!(false);
unreachable!();
}
}
}));
}
#[allow(dead_code)] // Not used in all tests
pub fn create_node_ids(n: usize) -> Vec<NodeId> |
#[allow(dead_code)] // Not used in all tests
pub fn start_nodes(n: usize) -> (Vec<Node<RabbleUserMsg>>, Vec<JoinHandle<()>>) {
let term = slog_term::streamer().build();
let drain = slog_envlogger::LogBuilder::new(term)
.filter(None, slog::FilterLevel::Debug).build();
let root_logger = slog::Logger::root(drain.fuse(), None);
slog_stdlog::set_logger(root_logger.clone()).unwrap();
create_node_ids(n).into_iter().fold((Vec::new(), Vec::new()),
|(mut nodes, mut handles), node_id| {
let (node, handle_list) = rabble::rouse(node_id, Some(root_logger.clone()));
nodes.push(node);
handles.extend(handle_list);
(nodes, handles)
})
}
#[allow(dead_code)] // Not used in all tests
pub fn test_pid(node_id: NodeId) -> Pid {
Pid {
name: "test-runner".to_string(),
group: None,
node: node_id
}
}
#[allow(dead_code)] // Not used in all tests
pub fn register_test_as_service(poller: &mut Poller,
nodes: &Vec<CrNode>,
test_tx: &CrSender,
test_rx: &CrReceiver)
{
for node in nodes {
let test_pid = test_pid(node.id.clone());
let correlation_id = CorrelationId::pid(test_pid.clone());
node.register_service(&test_pid, &test_tx).unwrap();
// Wait for registration to succeed
loop {
node.cluster_status(correlation_id.clone()).unwrap();
let notifications = poller.wait(10).unwrap();
if notifications.len()!= 0 {
// We have registered, otherwise we wouldn't have gotten a response
// Let's drain the receiver, because we may have returned from a previous poll
// before the previous ClusterStatus response was sent
while let Ok(envelope) = test_rx.try_recv() {
assert_matches!(envelope.msg, Msg::ClusterStatus(_));
}
break;
}
}
}
}
| {
(1..n + 1).map(|n| {
NodeId {
name: format!("node{}", n),
addr: format!("127.0.0.1:1100{}", n)
}
}).collect()
} | identifier_body |
mod.rs | extern crate time;
extern crate slog;
extern crate slog_term;
extern crate slog_envlogger;
extern crate slog_stdlog;
pub mod replica;
pub mod api_server;
pub mod messages;
use std::thread::{self, JoinHandle};
use std::net::TcpStream;
use amy::{Poller, Receiver, Sender};
use self::slog::DrainExt;
use self::time::{SteadyTime, Duration};
use utils::messages::*;
use rabble::{
self,
NodeId,
Node,
Envelope,
Pid,
CorrelationId,
Msg
};
use rabble::serialize::{Serialize, MsgpackSerializer};
type CrNode = Node<RabbleUserMsg>;
type CrReceiver = Receiver<Envelope<RabbleUserMsg>>;
type CrSender = Sender<Envelope<RabbleUserMsg>>;
/// Wait for a function to return true
///
/// After each call of `f()` that returns `false`, sleep for `sleep_time`
/// Returns true if `f()` returns true before the timeout expires
/// Returns false if the runtime of the test exceeds `timeout`
#[allow(dead_code)] // Not used in all tests
pub fn | <F>(timeout: Duration, mut f: F) -> bool
where F: FnMut() -> bool
{
let sleep_time = Duration::milliseconds(10);
let start = SteadyTime::now();
while let false = f() {
thread::sleep(sleep_time.to_std().unwrap());
if SteadyTime::now() - start > timeout {
return false;
}
}
true
}
/// Send a message over a non-blocking socket
/// Wait for it to finish sending or timeout after 5 seconds
/// In practice the first call to serializer.write_msgs should succeed unless the TCP send buffer is
/// tiny.
#[allow(dead_code)] // Not used in all tests
pub fn send(sock: &mut TcpStream,
serializer: &mut MsgpackSerializer<ApiClientMsg>,
msg: ApiClientMsg)
{
if let Ok(true) = serializer.write_msgs(sock, Some(&msg)) {
return;
}
// Just busy wait instead of using a poller in this test.
assert_eq!(true, wait_for(Duration::seconds(5), || {
// We don't know if it's writable, but we want to actually try the write
serializer.set_writable();
match serializer.write_msgs(sock, None) {
Ok(true) => true,
Ok(false) => false,
Err(e) => {
println!("Failed to write to socket: {}", e);
assert!(false);
unreachable!();
}
}
}));
}
#[allow(dead_code)] // Not used in all tests
pub fn create_node_ids(n: usize) -> Vec<NodeId> {
(1..n + 1).map(|n| {
NodeId {
name: format!("node{}", n),
addr: format!("127.0.0.1:1100{}", n)
}
}).collect()
}
#[allow(dead_code)] // Not used in all tests
pub fn start_nodes(n: usize) -> (Vec<Node<RabbleUserMsg>>, Vec<JoinHandle<()>>) {
let term = slog_term::streamer().build();
let drain = slog_envlogger::LogBuilder::new(term)
.filter(None, slog::FilterLevel::Debug).build();
let root_logger = slog::Logger::root(drain.fuse(), None);
slog_stdlog::set_logger(root_logger.clone()).unwrap();
create_node_ids(n).into_iter().fold((Vec::new(), Vec::new()),
|(mut nodes, mut handles), node_id| {
let (node, handle_list) = rabble::rouse(node_id, Some(root_logger.clone()));
nodes.push(node);
handles.extend(handle_list);
(nodes, handles)
})
}
#[allow(dead_code)] // Not used in all tests
pub fn test_pid(node_id: NodeId) -> Pid {
Pid {
name: "test-runner".to_string(),
group: None,
node: node_id
}
}
#[allow(dead_code)] // Not used in all tests
pub fn register_test_as_service(poller: &mut Poller,
nodes: &Vec<CrNode>,
test_tx: &CrSender,
test_rx: &CrReceiver)
{
for node in nodes {
let test_pid = test_pid(node.id.clone());
let correlation_id = CorrelationId::pid(test_pid.clone());
node.register_service(&test_pid, &test_tx).unwrap();
// Wait for registration to succeed
loop {
node.cluster_status(correlation_id.clone()).unwrap();
let notifications = poller.wait(10).unwrap();
if notifications.len()!= 0 {
// We have registered, otherwise we wouldn't have gotten a response
// Let's drain the receiver, because we may have returned from a previous poll
// before the previous ClusterStatus response was sent
while let Ok(envelope) = test_rx.try_recv() {
assert_matches!(envelope.msg, Msg::ClusterStatus(_));
}
break;
}
}
}
}
| wait_for | identifier_name |
mod.rs | extern crate time;
extern crate slog;
extern crate slog_term;
extern crate slog_envlogger;
extern crate slog_stdlog;
pub mod replica;
pub mod api_server;
pub mod messages;
use std::thread::{self, JoinHandle};
use std::net::TcpStream;
use amy::{Poller, Receiver, Sender};
use self::slog::DrainExt;
use self::time::{SteadyTime, Duration};
use utils::messages::*;
use rabble::{
self,
NodeId,
Node,
Envelope,
Pid,
CorrelationId,
Msg
};
use rabble::serialize::{Serialize, MsgpackSerializer};
type CrNode = Node<RabbleUserMsg>;
type CrReceiver = Receiver<Envelope<RabbleUserMsg>>;
type CrSender = Sender<Envelope<RabbleUserMsg>>;
/// Wait for a function to return true
///
/// After each call of `f()` that returns `false`, sleep for `sleep_time`
/// Returns true if `f()` returns true before the timeout expires
/// Returns false if the runtime of the test exceeds `timeout`
#[allow(dead_code)] // Not used in all tests
pub fn wait_for<F>(timeout: Duration, mut f: F) -> bool
where F: FnMut() -> bool
{
let sleep_time = Duration::milliseconds(10);
let start = SteadyTime::now();
while let false = f() {
thread::sleep(sleep_time.to_std().unwrap());
if SteadyTime::now() - start > timeout {
return false;
}
}
true
}
/// Send a message over a non-blocking socket
/// Wait for it to finish sending or timeout after 5 seconds
/// In practice the first call to serializer.write_msgs should succeed unless the TCP send buffer is
/// tiny.
#[allow(dead_code)] // Not used in all tests
pub fn send(sock: &mut TcpStream,
serializer: &mut MsgpackSerializer<ApiClientMsg>,
msg: ApiClientMsg)
{
if let Ok(true) = serializer.write_msgs(sock, Some(&msg)) |
// Just busy wait instead of using a poller in this test.
assert_eq!(true, wait_for(Duration::seconds(5), || {
// We don't know if it's writable, but we want to actually try the write
serializer.set_writable();
match serializer.write_msgs(sock, None) {
Ok(true) => true,
Ok(false) => false,
Err(e) => {
println!("Failed to write to socket: {}", e);
assert!(false);
unreachable!();
}
}
}));
}
#[allow(dead_code)] // Not used in all tests
pub fn create_node_ids(n: usize) -> Vec<NodeId> {
(1..n + 1).map(|n| {
NodeId {
name: format!("node{}", n),
addr: format!("127.0.0.1:1100{}", n)
}
}).collect()
}
#[allow(dead_code)] // Not used in all tests
pub fn start_nodes(n: usize) -> (Vec<Node<RabbleUserMsg>>, Vec<JoinHandle<()>>) {
let term = slog_term::streamer().build();
let drain = slog_envlogger::LogBuilder::new(term)
.filter(None, slog::FilterLevel::Debug).build();
let root_logger = slog::Logger::root(drain.fuse(), None);
slog_stdlog::set_logger(root_logger.clone()).unwrap();
create_node_ids(n).into_iter().fold((Vec::new(), Vec::new()),
|(mut nodes, mut handles), node_id| {
let (node, handle_list) = rabble::rouse(node_id, Some(root_logger.clone()));
nodes.push(node);
handles.extend(handle_list);
(nodes, handles)
})
}
#[allow(dead_code)] // Not used in all tests
pub fn test_pid(node_id: NodeId) -> Pid {
Pid {
name: "test-runner".to_string(),
group: None,
node: node_id
}
}
#[allow(dead_code)] // Not used in all tests
pub fn register_test_as_service(poller: &mut Poller,
nodes: &Vec<CrNode>,
test_tx: &CrSender,
test_rx: &CrReceiver)
{
for node in nodes {
let test_pid = test_pid(node.id.clone());
let correlation_id = CorrelationId::pid(test_pid.clone());
node.register_service(&test_pid, &test_tx).unwrap();
// Wait for registration to succeed
loop {
node.cluster_status(correlation_id.clone()).unwrap();
let notifications = poller.wait(10).unwrap();
if notifications.len()!= 0 {
// We have registered, otherwise we wouldn't have gotten a response
// Let's drain the receiver, because we may have returned from a previous poll
// before the previous ClusterStatus response was sent
while let Ok(envelope) = test_rx.try_recv() {
assert_matches!(envelope.msg, Msg::ClusterStatus(_));
}
break;
}
}
}
}
| {
return;
} | conditional_block |
conrod.rs | extern crate lazybox_graphics as graphics;
extern crate lazybox_frameclock as frameclock;
#[macro_use] extern crate conrod;
extern crate glutin;
extern crate cgmath;
extern crate rayon;
use graphics::Graphics;
use graphics::combined::conrod::Renderer;
use graphics::types::ColorFormat;
use conrod::widget;
use glutin::{WindowBuilder, Event};
use frameclock::*;
fn main() | image_green,
image_blue,
}
}
let ids = Ids::new(ui.widget_id_generator());
let texture = graphics.load_texture_from_image::<ColorFormat>("resources/cloud.png");
let image_map = image_map! {
(ids.image_red, texture.clone()),
(ids.image_green, texture.clone()),
(ids.image_blue, texture),
};
let mut frameclock = FrameClock::start(1.);
let mut fps_counter = FpsCounter::new(1.);
let mut mspf = 0.0;
let mut fps = 0;
'main: loop {
let delta_time = frameclock.reset();
if let Some(fps_sample) = fps_counter.update(delta_time) {
mspf = 1000. / fps_sample;
fps = fps_sample as u32;
}
for event in window.poll_events() {
match event {
Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
Event::Closed => break'main,
_ => {},
}
if let Some(event) = conrod::backend::glutin::convert(event.clone(), &window) {
ui.handle_event(event);
}
}
{
let mut ui = &mut ui.set_widgets();
use conrod::{Colorable, Positionable, Sizeable, Widget};
widget::Canvas::new().color(conrod::color::DARK_CHARCOAL).set(ids.canvas, ui);
let demo_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
Mauris aliquet porttitor tellus vel euismod. Integer lobortis volutpat bibendum. \
Nulla finibus odio nec elit condimentum, rhoncus fermentum purus lacinia. \
Interdum et malesuada fames ac ante ipsum primis in faucibus. \
Cras rhoncus nisi nec dolor bibendum pellentesque. \
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \
Quisque commodo nibh hendrerit nunc sollicitudin sodales. Cras vitae tempus ipsum. \
Nam magna est, efficitur suscipit dolor eu, consectetur consectetur urna.";
widget::Text::new(demo_text)
.middle_of(ids.canvas)
.w_of(ids.canvas)
.font_size(20)
.color(conrod::color::BLACK)
.align_text_middle()
.set(ids.text, ui);
let fps_text = &format!("{:.2} ms/frame - {} fps", mspf, fps);
widget::Text::new(fps_text)
.top_left_with_margin_on(ids.canvas, 6.)
.wh_of(ids.canvas)
.font_size(14)
.color(conrod::color::PURPLE)
.align_text_left()
.set(ids.fps, ui);
let style = widget::line::Style {
maybe_pattern: None,
maybe_color: None,
maybe_thickness: Some(20.),
maybe_cap: Some(widget::line::Cap::Round),
};
widget::Line::abs_styled([0., 0.], [120., 0.], style).set(ids.line, ui);
let image = widget::Image::new().w_h(64., 64.);
image.clone()
.color(Some(conrod::color::RED))
.bottom_left_with_margin_on(ids.canvas, 12.)
.set(ids.image_red, ui);
image.clone()
.color(Some(conrod::color::GREEN))
.right_from(ids.image_red, 12.)
.set(ids.image_green, ui);
image.clone()
.color(Some(conrod::color::BLUE))
.right_from(ids.image_green, 12.)
.set(ids.image_blue, ui);
}
let mut frame = graphics.draw();
ui.draw_if_changed().map(|ps| renderer.changed(ps, &image_map, &mut frame));
renderer.render(&mut frame);
frame.present(&window);
}
}
| {
let builder = WindowBuilder::new()
.with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (2, 1)))
.with_title("Conrod".to_string())
.with_dimensions(512, 512);
let (window, mut graphics) = Graphics::new(builder);
let mut renderer = Renderer::new(window.hidpi_factor(), &mut graphics);
let mut ui = conrod::UiBuilder::new([512., 512.]).build();
ui.fonts.insert_from_file("resources/fonts/NotoSans/NotoSans-Regular.ttf").unwrap();
widget_ids!{
struct Ids {
canvas,
button,
text,
fps,
line,
image_red,
| identifier_body |
conrod.rs | extern crate lazybox_graphics as graphics;
extern crate lazybox_frameclock as frameclock;
#[macro_use] extern crate conrod;
extern crate glutin;
extern crate cgmath;
extern crate rayon;
use graphics::Graphics;
use graphics::combined::conrod::Renderer;
use graphics::types::ColorFormat;
use conrod::widget;
use glutin::{WindowBuilder, Event};
use frameclock::*;
fn main() {
let builder = WindowBuilder::new()
.with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (2, 1)))
.with_title("Conrod".to_string())
.with_dimensions(512, 512);
let (window, mut graphics) = Graphics::new(builder);
let mut renderer = Renderer::new(window.hidpi_factor(), &mut graphics);
let mut ui = conrod::UiBuilder::new([512., 512.]).build();
ui.fonts.insert_from_file("resources/fonts/NotoSans/NotoSans-Regular.ttf").unwrap();
widget_ids!{
struct Ids {
canvas,
button,
text,
fps,
line,
image_red,
image_green,
image_blue,
}
}
let ids = Ids::new(ui.widget_id_generator());
let texture = graphics.load_texture_from_image::<ColorFormat>("resources/cloud.png");
let image_map = image_map! {
(ids.image_red, texture.clone()),
(ids.image_green, texture.clone()),
(ids.image_blue, texture),
};
let mut frameclock = FrameClock::start(1.);
let mut fps_counter = FpsCounter::new(1.);
let mut mspf = 0.0;
let mut fps = 0;
'main: loop {
let delta_time = frameclock.reset();
if let Some(fps_sample) = fps_counter.update(delta_time) {
mspf = 1000. / fps_sample;
fps = fps_sample as u32;
}
for event in window.poll_events() {
match event {
Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
Event::Closed => break'main,
_ => {},
}
if let Some(event) = conrod::backend::glutin::convert(event.clone(), &window) |
}
{
let mut ui = &mut ui.set_widgets();
use conrod::{Colorable, Positionable, Sizeable, Widget};
widget::Canvas::new().color(conrod::color::DARK_CHARCOAL).set(ids.canvas, ui);
let demo_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
Mauris aliquet porttitor tellus vel euismod. Integer lobortis volutpat bibendum. \
Nulla finibus odio nec elit condimentum, rhoncus fermentum purus lacinia. \
Interdum et malesuada fames ac ante ipsum primis in faucibus. \
Cras rhoncus nisi nec dolor bibendum pellentesque. \
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \
Quisque commodo nibh hendrerit nunc sollicitudin sodales. Cras vitae tempus ipsum. \
Nam magna est, efficitur suscipit dolor eu, consectetur consectetur urna.";
widget::Text::new(demo_text)
.middle_of(ids.canvas)
.w_of(ids.canvas)
.font_size(20)
.color(conrod::color::BLACK)
.align_text_middle()
.set(ids.text, ui);
let fps_text = &format!("{:.2} ms/frame - {} fps", mspf, fps);
widget::Text::new(fps_text)
.top_left_with_margin_on(ids.canvas, 6.)
.wh_of(ids.canvas)
.font_size(14)
.color(conrod::color::PURPLE)
.align_text_left()
.set(ids.fps, ui);
let style = widget::line::Style {
maybe_pattern: None,
maybe_color: None,
maybe_thickness: Some(20.),
maybe_cap: Some(widget::line::Cap::Round),
};
widget::Line::abs_styled([0., 0.], [120., 0.], style).set(ids.line, ui);
let image = widget::Image::new().w_h(64., 64.);
image.clone()
.color(Some(conrod::color::RED))
.bottom_left_with_margin_on(ids.canvas, 12.)
.set(ids.image_red, ui);
image.clone()
.color(Some(conrod::color::GREEN))
.right_from(ids.image_red, 12.)
.set(ids.image_green, ui);
image.clone()
.color(Some(conrod::color::BLUE))
.right_from(ids.image_green, 12.)
.set(ids.image_blue, ui);
}
let mut frame = graphics.draw();
ui.draw_if_changed().map(|ps| renderer.changed(ps, &image_map, &mut frame));
renderer.render(&mut frame);
frame.present(&window);
}
}
| {
ui.handle_event(event);
} | conditional_block |
conrod.rs | extern crate lazybox_graphics as graphics;
extern crate lazybox_frameclock as frameclock;
#[macro_use] extern crate conrod;
extern crate glutin;
extern crate cgmath;
extern crate rayon;
use graphics::Graphics;
use graphics::combined::conrod::Renderer;
use graphics::types::ColorFormat;
use conrod::widget;
use glutin::{WindowBuilder, Event};
use frameclock::*;
fn main() {
let builder = WindowBuilder::new()
.with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (2, 1)))
.with_title("Conrod".to_string())
.with_dimensions(512, 512);
let (window, mut graphics) = Graphics::new(builder);
let mut renderer = Renderer::new(window.hidpi_factor(), &mut graphics);
let mut ui = conrod::UiBuilder::new([512., 512.]).build();
ui.fonts.insert_from_file("resources/fonts/NotoSans/NotoSans-Regular.ttf").unwrap();
widget_ids!{
struct Ids {
canvas,
button,
text,
fps,
line,
image_red,
image_green,
image_blue,
}
}
let ids = Ids::new(ui.widget_id_generator());
let texture = graphics.load_texture_from_image::<ColorFormat>("resources/cloud.png");
let image_map = image_map! {
(ids.image_red, texture.clone()),
(ids.image_green, texture.clone()),
(ids.image_blue, texture),
};
let mut frameclock = FrameClock::start(1.);
let mut fps_counter = FpsCounter::new(1.);
let mut mspf = 0.0;
| let delta_time = frameclock.reset();
if let Some(fps_sample) = fps_counter.update(delta_time) {
mspf = 1000. / fps_sample;
fps = fps_sample as u32;
}
for event in window.poll_events() {
match event {
Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
Event::Closed => break'main,
_ => {},
}
if let Some(event) = conrod::backend::glutin::convert(event.clone(), &window) {
ui.handle_event(event);
}
}
{
let mut ui = &mut ui.set_widgets();
use conrod::{Colorable, Positionable, Sizeable, Widget};
widget::Canvas::new().color(conrod::color::DARK_CHARCOAL).set(ids.canvas, ui);
let demo_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
Mauris aliquet porttitor tellus vel euismod. Integer lobortis volutpat bibendum. \
Nulla finibus odio nec elit condimentum, rhoncus fermentum purus lacinia. \
Interdum et malesuada fames ac ante ipsum primis in faucibus. \
Cras rhoncus nisi nec dolor bibendum pellentesque. \
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \
Quisque commodo nibh hendrerit nunc sollicitudin sodales. Cras vitae tempus ipsum. \
Nam magna est, efficitur suscipit dolor eu, consectetur consectetur urna.";
widget::Text::new(demo_text)
.middle_of(ids.canvas)
.w_of(ids.canvas)
.font_size(20)
.color(conrod::color::BLACK)
.align_text_middle()
.set(ids.text, ui);
let fps_text = &format!("{:.2} ms/frame - {} fps", mspf, fps);
widget::Text::new(fps_text)
.top_left_with_margin_on(ids.canvas, 6.)
.wh_of(ids.canvas)
.font_size(14)
.color(conrod::color::PURPLE)
.align_text_left()
.set(ids.fps, ui);
let style = widget::line::Style {
maybe_pattern: None,
maybe_color: None,
maybe_thickness: Some(20.),
maybe_cap: Some(widget::line::Cap::Round),
};
widget::Line::abs_styled([0., 0.], [120., 0.], style).set(ids.line, ui);
let image = widget::Image::new().w_h(64., 64.);
image.clone()
.color(Some(conrod::color::RED))
.bottom_left_with_margin_on(ids.canvas, 12.)
.set(ids.image_red, ui);
image.clone()
.color(Some(conrod::color::GREEN))
.right_from(ids.image_red, 12.)
.set(ids.image_green, ui);
image.clone()
.color(Some(conrod::color::BLUE))
.right_from(ids.image_green, 12.)
.set(ids.image_blue, ui);
}
let mut frame = graphics.draw();
ui.draw_if_changed().map(|ps| renderer.changed(ps, &image_map, &mut frame));
renderer.render(&mut frame);
frame.present(&window);
}
} | let mut fps = 0;
'main: loop {
| random_line_split |
conrod.rs | extern crate lazybox_graphics as graphics;
extern crate lazybox_frameclock as frameclock;
#[macro_use] extern crate conrod;
extern crate glutin;
extern crate cgmath;
extern crate rayon;
use graphics::Graphics;
use graphics::combined::conrod::Renderer;
use graphics::types::ColorFormat;
use conrod::widget;
use glutin::{WindowBuilder, Event};
use frameclock::*;
fn | () {
let builder = WindowBuilder::new()
.with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (2, 1)))
.with_title("Conrod".to_string())
.with_dimensions(512, 512);
let (window, mut graphics) = Graphics::new(builder);
let mut renderer = Renderer::new(window.hidpi_factor(), &mut graphics);
let mut ui = conrod::UiBuilder::new([512., 512.]).build();
ui.fonts.insert_from_file("resources/fonts/NotoSans/NotoSans-Regular.ttf").unwrap();
widget_ids!{
struct Ids {
canvas,
button,
text,
fps,
line,
image_red,
image_green,
image_blue,
}
}
let ids = Ids::new(ui.widget_id_generator());
let texture = graphics.load_texture_from_image::<ColorFormat>("resources/cloud.png");
let image_map = image_map! {
(ids.image_red, texture.clone()),
(ids.image_green, texture.clone()),
(ids.image_blue, texture),
};
let mut frameclock = FrameClock::start(1.);
let mut fps_counter = FpsCounter::new(1.);
let mut mspf = 0.0;
let mut fps = 0;
'main: loop {
let delta_time = frameclock.reset();
if let Some(fps_sample) = fps_counter.update(delta_time) {
mspf = 1000. / fps_sample;
fps = fps_sample as u32;
}
for event in window.poll_events() {
match event {
Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
Event::Closed => break'main,
_ => {},
}
if let Some(event) = conrod::backend::glutin::convert(event.clone(), &window) {
ui.handle_event(event);
}
}
{
let mut ui = &mut ui.set_widgets();
use conrod::{Colorable, Positionable, Sizeable, Widget};
widget::Canvas::new().color(conrod::color::DARK_CHARCOAL).set(ids.canvas, ui);
let demo_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. \
Mauris aliquet porttitor tellus vel euismod. Integer lobortis volutpat bibendum. \
Nulla finibus odio nec elit condimentum, rhoncus fermentum purus lacinia. \
Interdum et malesuada fames ac ante ipsum primis in faucibus. \
Cras rhoncus nisi nec dolor bibendum pellentesque. \
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. \
Quisque commodo nibh hendrerit nunc sollicitudin sodales. Cras vitae tempus ipsum. \
Nam magna est, efficitur suscipit dolor eu, consectetur consectetur urna.";
widget::Text::new(demo_text)
.middle_of(ids.canvas)
.w_of(ids.canvas)
.font_size(20)
.color(conrod::color::BLACK)
.align_text_middle()
.set(ids.text, ui);
let fps_text = &format!("{:.2} ms/frame - {} fps", mspf, fps);
widget::Text::new(fps_text)
.top_left_with_margin_on(ids.canvas, 6.)
.wh_of(ids.canvas)
.font_size(14)
.color(conrod::color::PURPLE)
.align_text_left()
.set(ids.fps, ui);
let style = widget::line::Style {
maybe_pattern: None,
maybe_color: None,
maybe_thickness: Some(20.),
maybe_cap: Some(widget::line::Cap::Round),
};
widget::Line::abs_styled([0., 0.], [120., 0.], style).set(ids.line, ui);
let image = widget::Image::new().w_h(64., 64.);
image.clone()
.color(Some(conrod::color::RED))
.bottom_left_with_margin_on(ids.canvas, 12.)
.set(ids.image_red, ui);
image.clone()
.color(Some(conrod::color::GREEN))
.right_from(ids.image_red, 12.)
.set(ids.image_green, ui);
image.clone()
.color(Some(conrod::color::BLUE))
.right_from(ids.image_green, 12.)
.set(ids.image_blue, ui);
}
let mut frame = graphics.draw();
ui.draw_if_changed().map(|ps| renderer.changed(ps, &image_map, &mut frame));
renderer.render(&mut frame);
frame.present(&window);
}
}
| main | identifier_name |
mkfifo.rs | #![crate_name = "mkfifo"]
#![feature(macro_rules)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
use std::num::FromStrRadix;
use std::os;
use libc::funcs::posix88::stat_::mkfifo;
#[path = "../common/util.rs"]
mod util;
static NAME : &'static str = "mkfifo";
static VERSION : &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> int {
let opts = [
getopts::optopt("m", "mode", "file permissions for the fifo", "(default 0666)"),
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => m,
Err(err) => panic!("{}", err),
};
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
} | println!("");
println!("Usage:");
println!(" {} [OPTIONS] NAME...", NAME);
println!("");
print!("{}", getopts::usage("Create a FIFO with the given name.", opts.as_slice()).as_slice());
if matches.free.is_empty() {
return 1;
}
return 0;
}
let mode = match matches.opt_str("m") {
Some(m) => match FromStrRadix::from_str_radix(m.as_slice(), 8) {
Some(m) => m,
None => {
show_error!("invalid mode");
return 1;
}
},
None => 0o666,
};
let mut exit_status = 0;
for f in matches.free.iter() {
f.with_c_str(|name| {
let err = unsafe { mkfifo(name, mode) };
if err == -1 {
show_error!("creating '{}': {}", f, os::error_string(os::errno()));
exit_status = 1;
}
});
}
exit_status
} |
if matches.opt_present("help") || matches.free.is_empty() {
println!("{} {}", NAME, VERSION); | random_line_split |
mkfifo.rs | #![crate_name = "mkfifo"]
#![feature(macro_rules)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
use std::num::FromStrRadix;
use std::os;
use libc::funcs::posix88::stat_::mkfifo;
#[path = "../common/util.rs"]
mod util;
static NAME : &'static str = "mkfifo";
static VERSION : &'static str = "1.0.0";
pub fn | (args: Vec<String>) -> int {
let opts = [
getopts::optopt("m", "mode", "file permissions for the fifo", "(default 0666)"),
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => m,
Err(err) => panic!("{}", err),
};
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.opt_present("help") || matches.free.is_empty() {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTIONS] NAME...", NAME);
println!("");
print!("{}", getopts::usage("Create a FIFO with the given name.", opts.as_slice()).as_slice());
if matches.free.is_empty() {
return 1;
}
return 0;
}
let mode = match matches.opt_str("m") {
Some(m) => match FromStrRadix::from_str_radix(m.as_slice(), 8) {
Some(m) => m,
None => {
show_error!("invalid mode");
return 1;
}
},
None => 0o666,
};
let mut exit_status = 0;
for f in matches.free.iter() {
f.with_c_str(|name| {
let err = unsafe { mkfifo(name, mode) };
if err == -1 {
show_error!("creating '{}': {}", f, os::error_string(os::errno()));
exit_status = 1;
}
});
}
exit_status
}
| uumain | identifier_name |
mkfifo.rs | #![crate_name = "mkfifo"]
#![feature(macro_rules)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
use std::num::FromStrRadix;
use std::os;
use libc::funcs::posix88::stat_::mkfifo;
#[path = "../common/util.rs"]
mod util;
static NAME : &'static str = "mkfifo";
static VERSION : &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> int {
let opts = [
getopts::optopt("m", "mode", "file permissions for the fifo", "(default 0666)"),
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => m,
Err(err) => panic!("{}", err),
};
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.opt_present("help") || matches.free.is_empty() |
let mode = match matches.opt_str("m") {
Some(m) => match FromStrRadix::from_str_radix(m.as_slice(), 8) {
Some(m) => m,
None => {
show_error!("invalid mode");
return 1;
}
},
None => 0o666,
};
let mut exit_status = 0;
for f in matches.free.iter() {
f.with_c_str(|name| {
let err = unsafe { mkfifo(name, mode) };
if err == -1 {
show_error!("creating '{}': {}", f, os::error_string(os::errno()));
exit_status = 1;
}
});
}
exit_status
}
| {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTIONS] NAME...", NAME);
println!("");
print!("{}", getopts::usage("Create a FIFO with the given name.", opts.as_slice()).as_slice());
if matches.free.is_empty() {
return 1;
}
return 0;
} | conditional_block |
mkfifo.rs | #![crate_name = "mkfifo"]
#![feature(macro_rules)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Michael Gehring <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
extern crate getopts;
extern crate libc;
use std::num::FromStrRadix;
use std::os;
use libc::funcs::posix88::stat_::mkfifo;
#[path = "../common/util.rs"]
mod util;
static NAME : &'static str = "mkfifo";
static VERSION : &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> int | println!("Usage:");
println!(" {} [OPTIONS] NAME...", NAME);
println!("");
print!("{}", getopts::usage("Create a FIFO with the given name.", opts.as_slice()).as_slice());
if matches.free.is_empty() {
return 1;
}
return 0;
}
let mode = match matches.opt_str("m") {
Some(m) => match FromStrRadix::from_str_radix(m.as_slice(), 8) {
Some(m) => m,
None => {
show_error!("invalid mode");
return 1;
}
},
None => 0o666,
};
let mut exit_status = 0;
for f in matches.free.iter() {
f.with_c_str(|name| {
let err = unsafe { mkfifo(name, mode) };
if err == -1 {
show_error!("creating '{}': {}", f, os::error_string(os::errno()));
exit_status = 1;
}
});
}
exit_status
}
| {
let opts = [
getopts::optopt("m", "mode", "file permissions for the fifo", "(default 0666)"),
getopts::optflag("h", "help", "display this help and exit"),
getopts::optflag("V", "version", "output version information and exit"),
];
let matches = match getopts::getopts(args.tail(), &opts) {
Ok(m) => m,
Err(err) => panic!("{}", err),
};
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
if matches.opt_present("help") || matches.free.is_empty() {
println!("{} {}", NAME, VERSION);
println!(""); | identifier_body |
visible-private-types-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT | // <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.
trait Foo {
fn dummy(&self) { }
}
pub fn f<
T
: Foo //~ ERROR private trait in exported type parameter bound
>() {}
pub fn g<T>() where
T
: Foo //~ ERROR private trait in exported type parameter bound
{}
pub struct S;
impl S {
pub fn f<
T
: Foo //~ ERROR private trait in exported type parameter bound
>() {}
pub fn g<T>() where
T
: Foo //~ ERROR private trait in exported type parameter bound
{}
}
pub struct S1<
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
x: T
}
pub struct S2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
x: T
}
pub enum E1<
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
V1(T)
}
pub enum E2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
V2(T)
}
fn main() {} | // 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 | random_line_split |
visible-private-types-generics.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Foo {
fn dummy(&self) { }
}
pub fn f<
T
: Foo //~ ERROR private trait in exported type parameter bound
>() {}
pub fn g<T>() where
T
: Foo //~ ERROR private trait in exported type parameter bound
{}
pub struct S;
impl S {
pub fn f<
T
: Foo //~ ERROR private trait in exported type parameter bound
>() {}
pub fn g<T>() where
T
: Foo //~ ERROR private trait in exported type parameter bound
{}
}
pub struct | <
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
x: T
}
pub struct S2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
x: T
}
pub enum E1<
T
: Foo //~ ERROR private trait in exported type parameter bound
> {
V1(T)
}
pub enum E2<T> where
T
: Foo //~ ERROR private trait in exported type parameter bound
{
V2(T)
}
fn main() {}
| S1 | identifier_name |
ip_utils.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
// Based on original work by David Levy https://raw.githubusercontent.com/dlevy47/rust-interfaces
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::io;
use igd::{PortMappingProtocol, search_gateway_from_timeout};
use std::time::Duration;
use node_table::{NodeEndpoint};
/// Socket address extension for rustc beta. To be replaces with now unstable API
pub trait SocketAddrExt {
/// Returns true for the special 'unspecified' address 0.0.0.0.
fn is_unspecified_s(&self) -> bool;
/// Returns true if the address appears to be globally routable.
fn is_global_s(&self) -> bool;
}
impl SocketAddrExt for Ipv4Addr {
fn is_unspecified_s(&self) -> bool {
self.octets() == [0, 0, 0, 0]
}
fn is_global_s(&self) -> bool {
!self.is_private() &&!self.is_loopback() &&!self.is_link_local() &&
!self.is_broadcast() &&!self.is_documentation()
}
}
impl SocketAddrExt for Ipv6Addr {
fn is_unspecified_s(&self) -> bool {
self.segments() == [0, 0, 0, 0, 0, 0, 0, 0]
}
fn is_global_s(&self) -> bool {
if self.is_multicast() {
self.segments()[0] & 0x000f == 14
} else {
!self.is_loopback() &&!((self.segments()[0] & 0xffc0) == 0xfe80) &&
!((self.segments()[0] & 0xffc0) == 0xfec0) &&!((self.segments()[0] & 0xfe00) == 0xfc00)
}
}
}
impl SocketAddrExt for IpAddr {
fn is_unspecified_s(&self) -> bool {
match *self {
IpAddr::V4(ref ip) => ip.is_unspecified_s(),
IpAddr::V6(ref ip) => ip.is_unspecified_s(),
}
}
fn is_global_s(&self) -> bool {
match *self {
IpAddr::V4(ref ip) => ip.is_global_s(),
IpAddr::V6(ref ip) => ip.is_global_s(),
}
}
}
#[cfg(not(windows))]
mod getinterfaces {
use std::{mem, io, ptr};
use libc::{AF_INET, AF_INET6};
use libc::{getifaddrs, freeifaddrs, ifaddrs, sockaddr, sockaddr_in, sockaddr_in6};
use std::net::{Ipv4Addr, Ipv6Addr, IpAddr};
fn convert_sockaddr (sa: *mut sockaddr) -> Option<IpAddr> {
if sa == ptr::null_mut() { return None; }
let (addr, _) = match unsafe { *sa }.sa_family as i32 {
AF_INET => {
let sa: *const sockaddr_in = unsafe { mem::transmute(sa) };
let sa = & unsafe { *sa };
let (addr, port) = (sa.sin_addr.s_addr, sa.sin_port);
(IpAddr::V4(Ipv4Addr::new(
(addr & 0x000000FF) as u8,
((addr & 0x0000FF00) >> 8) as u8,
((addr & 0x00FF0000) >> 16) as u8,
((addr & 0xFF000000) >> 24) as u8)),
port)
},
AF_INET6 => {
let sa: *const sockaddr_in6 = unsafe { mem::transmute(sa) };
let sa = & unsafe { *sa };
let (addr, port) = (sa.sin6_addr.s6_addr, sa.sin6_port);
let addr: [u16; 8] = unsafe { mem::transmute(addr) };
(IpAddr::V6(Ipv6Addr::new(
addr[0],
addr[1],
addr[2],
addr[3],
addr[4],
addr[5],
addr[6],
addr[7])),
port)
},
_ => return None,
};
Some(addr)
}
fn convert_ifaddrs (ifa: *mut ifaddrs) -> Option<IpAddr> {
let ifa = unsafe { &mut *ifa };
convert_sockaddr(ifa.ifa_addr)
}
pub fn get_all() -> io::Result<Vec<IpAddr>> {
let mut ifap: *mut ifaddrs = unsafe { mem::zeroed() };
if unsafe { getifaddrs(&mut ifap as *mut _) }!= 0 {
return Err(io::Error::last_os_error());
}
let mut ret = Vec::new();
let mut cur: *mut ifaddrs = ifap;
while cur!= ptr::null_mut() {
if let Some(ip_addr) = convert_ifaddrs(cur) {
ret.push(ip_addr);
}
//TODO: do something else maybe?
cur = unsafe { (*cur).ifa_next };
}
unsafe { freeifaddrs(ifap) };
Ok(ret)
}
}
#[cfg(not(windows))]
fn get_if_addrs() -> io::Result<Vec<IpAddr>> {
getinterfaces::get_all()
}
#[cfg(windows)]
fn get_if_addrs() -> io::Result<Vec<IpAddr>> {
Ok(Vec::new())
}
/// Select the best available public address
pub fn select_public_address(port: u16) -> SocketAddr {
match get_if_addrs() {
Ok(list) => {
//prefer IPV4 bindings
for addr in &list { //TODO: use better criteria than just the first in the list
match *addr {
IpAddr::V4(a) if!a.is_unspecified_s() &&!a.is_loopback() &&!a.is_link_local() => {
return SocketAddr::V4(SocketAddrV4::new(a, port));
},
_ => {},
}
}
for addr in list {
match addr {
IpAddr::V6(a) if!a.is_unspecified_s() &&!a.is_loopback() => {
return SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0));
},
_ => {},
}
}
},
Err(e) => debug!("Error listing public interfaces: {:?}", e)
}
SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port))
}
pub fn map_external_address(local: &NodeEndpoint) -> Option<NodeEndpoint> | return Some(NodeEndpoint { address: SocketAddr::V4(SocketAddrV4::new(external_addr, tcp_port)), udp_port: udp_port });
},
}
},
}
},
}
},
}
}
None
}
#[test]
fn can_select_public_address() {
let pub_address = select_public_address(40477);
assert!(pub_address.port() == 40477);
}
#[ignore]
#[test]
fn can_map_external_address_or_fail() {
let pub_address = select_public_address(40478);
let _ = map_external_address(&NodeEndpoint { address: pub_address, udp_port: 40478 });
}
#[test]
fn ipv4_properties() {
#![cfg_attr(feature="dev", allow(too_many_arguments))]
fn check(octets: &[u8; 4], unspec: bool, loopback: bool,
private: bool, link_local: bool, global: bool,
multicast: bool, broadcast: bool, documentation: bool) {
let ip = Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]);
assert_eq!(octets, &ip.octets());
assert_eq!(ip.is_unspecified_s(), unspec);
assert_eq!(ip.is_loopback(), loopback);
assert_eq!(ip.is_private(), private);
assert_eq!(ip.is_link_local(), link_local);
assert_eq!(ip.is_global_s(), global);
assert_eq!(ip.is_multicast(), multicast);
assert_eq!(ip.is_broadcast(), broadcast);
assert_eq!(ip.is_documentation(), documentation);
}
// address unspec loopbk privt linloc global multicast brdcast doc
check(&[0, 0, 0, 0], true, false, false, false, true, false, false, false);
check(&[0, 0, 0, 1], false, false, false, false, true, false, false, false);
check(&[1, 0, 0, 0], false, false, false, false, true, false, false, false);
check(&[10, 9, 8, 7], false, false, true, false, false, false, false, false);
check(&[127, 1, 2, 3], false, true, false, false, false, false, false, false);
check(&[172, 31, 254, 253], false, false, true, false, false, false, false, false);
check(&[169, 254, 253, 242], false, false, false, true, false, false, false, false);
check(&[192, 0, 2, 183], false, false, false, false, false, false, false, true);
check(&[192, 1, 2, 183], false, false, false, false, true, false, false, false);
check(&[192, 168, 254, 253], false, false, true, false, false, false, false, false);
check(&[198, 51, 100, 0], false, false, false, false, false, false, false, true);
check(&[203, 0, 113, 0], false, false, false, false, false, false, false, true);
check(&[203, 2, 113, 0], false, false, false, false, true, false, false, false);
check(&[224, 0, 0, 0], false, false, false, false, true, true, false, false);
check(&[239, 255, 255, 255], false, false, false, false, true, true, false, false);
check(&[255, 255, 255, 255], false, false, false, false, false, false, true, false);
}
#[test]
fn ipv6_properties() {
fn check(str_addr: &str, unspec: bool, loopback: bool, global: bool) {
let ip: Ipv6Addr = str_addr.parse().unwrap();
assert_eq!(str_addr, ip.to_string());
assert_eq!(ip.is_unspecified_s(), unspec);
assert_eq!(ip.is_loopback(), loopback);
assert_eq!(ip.is_global_s(), global);
}
// unspec loopbk global
check("::", true, false, true);
check("::1", false, true, false);
}
| {
if let SocketAddr::V4(ref local_addr) = local.address {
match search_gateway_from_timeout(local_addr.ip().clone(), Duration::new(5, 0)) {
Err(ref err) => debug!("Gateway search error: {}", err),
Ok(gateway) => {
match gateway.get_external_ip() {
Err(ref err) => {
debug!("IP request error: {}", err);
},
Ok(external_addr) => {
match gateway.add_any_port(PortMappingProtocol::TCP, SocketAddrV4::new(local_addr.ip().clone(), local_addr.port()), 0, "Parity Node/TCP") {
Err(ref err) => {
debug!("Port mapping error: {}", err);
},
Ok(tcp_port) => {
match gateway.add_any_port(PortMappingProtocol::UDP, SocketAddrV4::new(local_addr.ip().clone(), local.udp_port), 0, "Parity Node/UDP") {
Err(ref err) => {
debug!("Port mapping error: {}", err);
},
Ok(udp_port) => { | identifier_body |
ip_utils.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
// Based on original work by David Levy https://raw.githubusercontent.com/dlevy47/rust-interfaces
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::io;
use igd::{PortMappingProtocol, search_gateway_from_timeout};
use std::time::Duration;
use node_table::{NodeEndpoint};
/// Socket address extension for rustc beta. To be replaces with now unstable API
pub trait SocketAddrExt {
/// Returns true for the special 'unspecified' address 0.0.0.0.
fn is_unspecified_s(&self) -> bool;
/// Returns true if the address appears to be globally routable.
fn is_global_s(&self) -> bool;
}
impl SocketAddrExt for Ipv4Addr {
fn is_unspecified_s(&self) -> bool {
self.octets() == [0, 0, 0, 0]
}
fn is_global_s(&self) -> bool {
!self.is_private() &&!self.is_loopback() &&!self.is_link_local() &&
!self.is_broadcast() &&!self.is_documentation()
}
}
impl SocketAddrExt for Ipv6Addr {
fn is_unspecified_s(&self) -> bool {
self.segments() == [0, 0, 0, 0, 0, 0, 0, 0]
}
fn is_global_s(&self) -> bool {
if self.is_multicast() {
self.segments()[0] & 0x000f == 14
} else {
!self.is_loopback() &&!((self.segments()[0] & 0xffc0) == 0xfe80) &&
!((self.segments()[0] & 0xffc0) == 0xfec0) &&!((self.segments()[0] & 0xfe00) == 0xfc00)
}
}
}
impl SocketAddrExt for IpAddr {
fn is_unspecified_s(&self) -> bool {
match *self {
IpAddr::V4(ref ip) => ip.is_unspecified_s(),
IpAddr::V6(ref ip) => ip.is_unspecified_s(),
}
}
fn is_global_s(&self) -> bool {
match *self {
IpAddr::V4(ref ip) => ip.is_global_s(),
IpAddr::V6(ref ip) => ip.is_global_s(),
}
}
}
#[cfg(not(windows))]
mod getinterfaces {
use std::{mem, io, ptr};
use libc::{AF_INET, AF_INET6};
use libc::{getifaddrs, freeifaddrs, ifaddrs, sockaddr, sockaddr_in, sockaddr_in6};
use std::net::{Ipv4Addr, Ipv6Addr, IpAddr};
fn convert_sockaddr (sa: *mut sockaddr) -> Option<IpAddr> {
if sa == ptr::null_mut() { return None; }
let (addr, _) = match unsafe { *sa }.sa_family as i32 {
AF_INET => {
let sa: *const sockaddr_in = unsafe { mem::transmute(sa) };
let sa = & unsafe { *sa };
let (addr, port) = (sa.sin_addr.s_addr, sa.sin_port);
(IpAddr::V4(Ipv4Addr::new(
(addr & 0x000000FF) as u8,
((addr & 0x0000FF00) >> 8) as u8,
((addr & 0x00FF0000) >> 16) as u8,
((addr & 0xFF000000) >> 24) as u8)),
port)
},
AF_INET6 => {
let sa: *const sockaddr_in6 = unsafe { mem::transmute(sa) };
let sa = & unsafe { *sa };
let (addr, port) = (sa.sin6_addr.s6_addr, sa.sin6_port);
let addr: [u16; 8] = unsafe { mem::transmute(addr) };
(IpAddr::V6(Ipv6Addr::new(
addr[0],
addr[1],
addr[2],
addr[3],
addr[4],
addr[5],
addr[6],
addr[7])),
port)
},
_ => return None,
};
Some(addr)
}
fn convert_ifaddrs (ifa: *mut ifaddrs) -> Option<IpAddr> {
let ifa = unsafe { &mut *ifa };
convert_sockaddr(ifa.ifa_addr)
}
pub fn get_all() -> io::Result<Vec<IpAddr>> {
let mut ifap: *mut ifaddrs = unsafe { mem::zeroed() };
if unsafe { getifaddrs(&mut ifap as *mut _) }!= 0 {
return Err(io::Error::last_os_error());
}
let mut ret = Vec::new();
let mut cur: *mut ifaddrs = ifap;
while cur!= ptr::null_mut() {
if let Some(ip_addr) = convert_ifaddrs(cur) {
ret.push(ip_addr);
}
//TODO: do something else maybe?
cur = unsafe { (*cur).ifa_next };
}
unsafe { freeifaddrs(ifap) };
Ok(ret)
}
}
#[cfg(not(windows))]
fn get_if_addrs() -> io::Result<Vec<IpAddr>> {
getinterfaces::get_all()
}
#[cfg(windows)]
fn get_if_addrs() -> io::Result<Vec<IpAddr>> {
Ok(Vec::new())
}
/// Select the best available public address | for addr in &list { //TODO: use better criteria than just the first in the list
match *addr {
IpAddr::V4(a) if!a.is_unspecified_s() &&!a.is_loopback() &&!a.is_link_local() => {
return SocketAddr::V4(SocketAddrV4::new(a, port));
},
_ => {},
}
}
for addr in list {
match addr {
IpAddr::V6(a) if!a.is_unspecified_s() &&!a.is_loopback() => {
return SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0));
},
_ => {},
}
}
},
Err(e) => debug!("Error listing public interfaces: {:?}", e)
}
SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port))
}
pub fn map_external_address(local: &NodeEndpoint) -> Option<NodeEndpoint> {
if let SocketAddr::V4(ref local_addr) = local.address {
match search_gateway_from_timeout(local_addr.ip().clone(), Duration::new(5, 0)) {
Err(ref err) => debug!("Gateway search error: {}", err),
Ok(gateway) => {
match gateway.get_external_ip() {
Err(ref err) => {
debug!("IP request error: {}", err);
},
Ok(external_addr) => {
match gateway.add_any_port(PortMappingProtocol::TCP, SocketAddrV4::new(local_addr.ip().clone(), local_addr.port()), 0, "Parity Node/TCP") {
Err(ref err) => {
debug!("Port mapping error: {}", err);
},
Ok(tcp_port) => {
match gateway.add_any_port(PortMappingProtocol::UDP, SocketAddrV4::new(local_addr.ip().clone(), local.udp_port), 0, "Parity Node/UDP") {
Err(ref err) => {
debug!("Port mapping error: {}", err);
},
Ok(udp_port) => {
return Some(NodeEndpoint { address: SocketAddr::V4(SocketAddrV4::new(external_addr, tcp_port)), udp_port: udp_port });
},
}
},
}
},
}
},
}
}
None
}
#[test]
fn can_select_public_address() {
let pub_address = select_public_address(40477);
assert!(pub_address.port() == 40477);
}
#[ignore]
#[test]
fn can_map_external_address_or_fail() {
let pub_address = select_public_address(40478);
let _ = map_external_address(&NodeEndpoint { address: pub_address, udp_port: 40478 });
}
#[test]
fn ipv4_properties() {
#![cfg_attr(feature="dev", allow(too_many_arguments))]
fn check(octets: &[u8; 4], unspec: bool, loopback: bool,
private: bool, link_local: bool, global: bool,
multicast: bool, broadcast: bool, documentation: bool) {
let ip = Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]);
assert_eq!(octets, &ip.octets());
assert_eq!(ip.is_unspecified_s(), unspec);
assert_eq!(ip.is_loopback(), loopback);
assert_eq!(ip.is_private(), private);
assert_eq!(ip.is_link_local(), link_local);
assert_eq!(ip.is_global_s(), global);
assert_eq!(ip.is_multicast(), multicast);
assert_eq!(ip.is_broadcast(), broadcast);
assert_eq!(ip.is_documentation(), documentation);
}
// address unspec loopbk privt linloc global multicast brdcast doc
check(&[0, 0, 0, 0], true, false, false, false, true, false, false, false);
check(&[0, 0, 0, 1], false, false, false, false, true, false, false, false);
check(&[1, 0, 0, 0], false, false, false, false, true, false, false, false);
check(&[10, 9, 8, 7], false, false, true, false, false, false, false, false);
check(&[127, 1, 2, 3], false, true, false, false, false, false, false, false);
check(&[172, 31, 254, 253], false, false, true, false, false, false, false, false);
check(&[169, 254, 253, 242], false, false, false, true, false, false, false, false);
check(&[192, 0, 2, 183], false, false, false, false, false, false, false, true);
check(&[192, 1, 2, 183], false, false, false, false, true, false, false, false);
check(&[192, 168, 254, 253], false, false, true, false, false, false, false, false);
check(&[198, 51, 100, 0], false, false, false, false, false, false, false, true);
check(&[203, 0, 113, 0], false, false, false, false, false, false, false, true);
check(&[203, 2, 113, 0], false, false, false, false, true, false, false, false);
check(&[224, 0, 0, 0], false, false, false, false, true, true, false, false);
check(&[239, 255, 255, 255], false, false, false, false, true, true, false, false);
check(&[255, 255, 255, 255], false, false, false, false, false, false, true, false);
}
#[test]
fn ipv6_properties() {
fn check(str_addr: &str, unspec: bool, loopback: bool, global: bool) {
let ip: Ipv6Addr = str_addr.parse().unwrap();
assert_eq!(str_addr, ip.to_string());
assert_eq!(ip.is_unspecified_s(), unspec);
assert_eq!(ip.is_loopback(), loopback);
assert_eq!(ip.is_global_s(), global);
}
// unspec loopbk global
check("::", true, false, true);
check("::1", false, true, false);
} | pub fn select_public_address(port: u16) -> SocketAddr {
match get_if_addrs() {
Ok(list) => {
//prefer IPV4 bindings | random_line_split |
ip_utils.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
// Based on original work by David Levy https://raw.githubusercontent.com/dlevy47/rust-interfaces
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::io;
use igd::{PortMappingProtocol, search_gateway_from_timeout};
use std::time::Duration;
use node_table::{NodeEndpoint};
/// Socket address extension for rustc beta. To be replaces with now unstable API
pub trait SocketAddrExt {
/// Returns true for the special 'unspecified' address 0.0.0.0.
fn is_unspecified_s(&self) -> bool;
/// Returns true if the address appears to be globally routable.
fn is_global_s(&self) -> bool;
}
impl SocketAddrExt for Ipv4Addr {
fn is_unspecified_s(&self) -> bool {
self.octets() == [0, 0, 0, 0]
}
fn is_global_s(&self) -> bool {
!self.is_private() &&!self.is_loopback() &&!self.is_link_local() &&
!self.is_broadcast() &&!self.is_documentation()
}
}
impl SocketAddrExt for Ipv6Addr {
fn is_unspecified_s(&self) -> bool {
self.segments() == [0, 0, 0, 0, 0, 0, 0, 0]
}
fn is_global_s(&self) -> bool {
if self.is_multicast() {
self.segments()[0] & 0x000f == 14
} else {
!self.is_loopback() &&!((self.segments()[0] & 0xffc0) == 0xfe80) &&
!((self.segments()[0] & 0xffc0) == 0xfec0) &&!((self.segments()[0] & 0xfe00) == 0xfc00)
}
}
}
impl SocketAddrExt for IpAddr {
fn is_unspecified_s(&self) -> bool {
match *self {
IpAddr::V4(ref ip) => ip.is_unspecified_s(),
IpAddr::V6(ref ip) => ip.is_unspecified_s(),
}
}
fn is_global_s(&self) -> bool {
match *self {
IpAddr::V4(ref ip) => ip.is_global_s(),
IpAddr::V6(ref ip) => ip.is_global_s(),
}
}
}
#[cfg(not(windows))]
mod getinterfaces {
use std::{mem, io, ptr};
use libc::{AF_INET, AF_INET6};
use libc::{getifaddrs, freeifaddrs, ifaddrs, sockaddr, sockaddr_in, sockaddr_in6};
use std::net::{Ipv4Addr, Ipv6Addr, IpAddr};
fn convert_sockaddr (sa: *mut sockaddr) -> Option<IpAddr> {
if sa == ptr::null_mut() { return None; }
let (addr, _) = match unsafe { *sa }.sa_family as i32 {
AF_INET => {
let sa: *const sockaddr_in = unsafe { mem::transmute(sa) };
let sa = & unsafe { *sa };
let (addr, port) = (sa.sin_addr.s_addr, sa.sin_port);
(IpAddr::V4(Ipv4Addr::new(
(addr & 0x000000FF) as u8,
((addr & 0x0000FF00) >> 8) as u8,
((addr & 0x00FF0000) >> 16) as u8,
((addr & 0xFF000000) >> 24) as u8)),
port)
},
AF_INET6 => {
let sa: *const sockaddr_in6 = unsafe { mem::transmute(sa) };
let sa = & unsafe { *sa };
let (addr, port) = (sa.sin6_addr.s6_addr, sa.sin6_port);
let addr: [u16; 8] = unsafe { mem::transmute(addr) };
(IpAddr::V6(Ipv6Addr::new(
addr[0],
addr[1],
addr[2],
addr[3],
addr[4],
addr[5],
addr[6],
addr[7])),
port)
},
_ => return None,
};
Some(addr)
}
fn convert_ifaddrs (ifa: *mut ifaddrs) -> Option<IpAddr> {
let ifa = unsafe { &mut *ifa };
convert_sockaddr(ifa.ifa_addr)
}
pub fn get_all() -> io::Result<Vec<IpAddr>> {
let mut ifap: *mut ifaddrs = unsafe { mem::zeroed() };
if unsafe { getifaddrs(&mut ifap as *mut _) }!= 0 {
return Err(io::Error::last_os_error());
}
let mut ret = Vec::new();
let mut cur: *mut ifaddrs = ifap;
while cur!= ptr::null_mut() {
if let Some(ip_addr) = convert_ifaddrs(cur) {
ret.push(ip_addr);
}
//TODO: do something else maybe?
cur = unsafe { (*cur).ifa_next };
}
unsafe { freeifaddrs(ifap) };
Ok(ret)
}
}
#[cfg(not(windows))]
fn get_if_addrs() -> io::Result<Vec<IpAddr>> {
getinterfaces::get_all()
}
#[cfg(windows)]
fn get_if_addrs() -> io::Result<Vec<IpAddr>> {
Ok(Vec::new())
}
/// Select the best available public address
pub fn select_public_address(port: u16) -> SocketAddr {
match get_if_addrs() {
Ok(list) => {
//prefer IPV4 bindings
for addr in &list { //TODO: use better criteria than just the first in the list
match *addr {
IpAddr::V4(a) if!a.is_unspecified_s() &&!a.is_loopback() &&!a.is_link_local() => {
return SocketAddr::V4(SocketAddrV4::new(a, port));
},
_ => {},
}
}
for addr in list {
match addr {
IpAddr::V6(a) if!a.is_unspecified_s() &&!a.is_loopback() => {
return SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0));
},
_ => {},
}
}
},
Err(e) => debug!("Error listing public interfaces: {:?}", e)
}
SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port))
}
pub fn map_external_address(local: &NodeEndpoint) -> Option<NodeEndpoint> {
if let SocketAddr::V4(ref local_addr) = local.address {
match search_gateway_from_timeout(local_addr.ip().clone(), Duration::new(5, 0)) {
Err(ref err) => debug!("Gateway search error: {}", err),
Ok(gateway) => | }
},
}
}
,
}
}
None
}
#[test]
fn can_select_public_address() {
let pub_address = select_public_address(40477);
assert!(pub_address.port() == 40477);
}
#[ignore]
#[test]
fn can_map_external_address_or_fail() {
let pub_address = select_public_address(40478);
let _ = map_external_address(&NodeEndpoint { address: pub_address, udp_port: 40478 });
}
#[test]
fn ipv4_properties() {
#![cfg_attr(feature="dev", allow(too_many_arguments))]
fn check(octets: &[u8; 4], unspec: bool, loopback: bool,
private: bool, link_local: bool, global: bool,
multicast: bool, broadcast: bool, documentation: bool) {
let ip = Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]);
assert_eq!(octets, &ip.octets());
assert_eq!(ip.is_unspecified_s(), unspec);
assert_eq!(ip.is_loopback(), loopback);
assert_eq!(ip.is_private(), private);
assert_eq!(ip.is_link_local(), link_local);
assert_eq!(ip.is_global_s(), global);
assert_eq!(ip.is_multicast(), multicast);
assert_eq!(ip.is_broadcast(), broadcast);
assert_eq!(ip.is_documentation(), documentation);
}
// address unspec loopbk privt linloc global multicast brdcast doc
check(&[0, 0, 0, 0], true, false, false, false, true, false, false, false);
check(&[0, 0, 0, 1], false, false, false, false, true, false, false, false);
check(&[1, 0, 0, 0], false, false, false, false, true, false, false, false);
check(&[10, 9, 8, 7], false, false, true, false, false, false, false, false);
check(&[127, 1, 2, 3], false, true, false, false, false, false, false, false);
check(&[172, 31, 254, 253], false, false, true, false, false, false, false, false);
check(&[169, 254, 253, 242], false, false, false, true, false, false, false, false);
check(&[192, 0, 2, 183], false, false, false, false, false, false, false, true);
check(&[192, 1, 2, 183], false, false, false, false, true, false, false, false);
check(&[192, 168, 254, 253], false, false, true, false, false, false, false, false);
check(&[198, 51, 100, 0], false, false, false, false, false, false, false, true);
check(&[203, 0, 113, 0], false, false, false, false, false, false, false, true);
check(&[203, 2, 113, 0], false, false, false, false, true, false, false, false);
check(&[224, 0, 0, 0], false, false, false, false, true, true, false, false);
check(&[239, 255, 255, 255], false, false, false, false, true, true, false, false);
check(&[255, 255, 255, 255], false, false, false, false, false, false, true, false);
}
#[test]
fn ipv6_properties() {
fn check(str_addr: &str, unspec: bool, loopback: bool, global: bool) {
let ip: Ipv6Addr = str_addr.parse().unwrap();
assert_eq!(str_addr, ip.to_string());
assert_eq!(ip.is_unspecified_s(), unspec);
assert_eq!(ip.is_loopback(), loopback);
assert_eq!(ip.is_global_s(), global);
}
// unspec loopbk global
check("::", true, false, true);
check("::1", false, true, false);
}
| {
match gateway.get_external_ip() {
Err(ref err) => {
debug!("IP request error: {}", err);
},
Ok(external_addr) => {
match gateway.add_any_port(PortMappingProtocol::TCP, SocketAddrV4::new(local_addr.ip().clone(), local_addr.port()), 0, "Parity Node/TCP") {
Err(ref err) => {
debug!("Port mapping error: {}", err);
},
Ok(tcp_port) => {
match gateway.add_any_port(PortMappingProtocol::UDP, SocketAddrV4::new(local_addr.ip().clone(), local.udp_port), 0, "Parity Node/UDP") {
Err(ref err) => {
debug!("Port mapping error: {}", err);
},
Ok(udp_port) => {
return Some(NodeEndpoint { address: SocketAddr::V4(SocketAddrV4::new(external_addr, tcp_port)), udp_port: udp_port });
},
}
}, | conditional_block |
ip_utils.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
// Based on original work by David Levy https://raw.githubusercontent.com/dlevy47/rust-interfaces
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use std::io;
use igd::{PortMappingProtocol, search_gateway_from_timeout};
use std::time::Duration;
use node_table::{NodeEndpoint};
/// Socket address extension for rustc beta. To be replaces with now unstable API
pub trait SocketAddrExt {
/// Returns true for the special 'unspecified' address 0.0.0.0.
fn is_unspecified_s(&self) -> bool;
/// Returns true if the address appears to be globally routable.
fn is_global_s(&self) -> bool;
}
impl SocketAddrExt for Ipv4Addr {
fn is_unspecified_s(&self) -> bool {
self.octets() == [0, 0, 0, 0]
}
fn is_global_s(&self) -> bool {
!self.is_private() &&!self.is_loopback() &&!self.is_link_local() &&
!self.is_broadcast() &&!self.is_documentation()
}
}
impl SocketAddrExt for Ipv6Addr {
fn is_unspecified_s(&self) -> bool {
self.segments() == [0, 0, 0, 0, 0, 0, 0, 0]
}
fn is_global_s(&self) -> bool {
if self.is_multicast() {
self.segments()[0] & 0x000f == 14
} else {
!self.is_loopback() &&!((self.segments()[0] & 0xffc0) == 0xfe80) &&
!((self.segments()[0] & 0xffc0) == 0xfec0) &&!((self.segments()[0] & 0xfe00) == 0xfc00)
}
}
}
impl SocketAddrExt for IpAddr {
fn is_unspecified_s(&self) -> bool {
match *self {
IpAddr::V4(ref ip) => ip.is_unspecified_s(),
IpAddr::V6(ref ip) => ip.is_unspecified_s(),
}
}
fn is_global_s(&self) -> bool {
match *self {
IpAddr::V4(ref ip) => ip.is_global_s(),
IpAddr::V6(ref ip) => ip.is_global_s(),
}
}
}
#[cfg(not(windows))]
mod getinterfaces {
use std::{mem, io, ptr};
use libc::{AF_INET, AF_INET6};
use libc::{getifaddrs, freeifaddrs, ifaddrs, sockaddr, sockaddr_in, sockaddr_in6};
use std::net::{Ipv4Addr, Ipv6Addr, IpAddr};
fn convert_sockaddr (sa: *mut sockaddr) -> Option<IpAddr> {
if sa == ptr::null_mut() { return None; }
let (addr, _) = match unsafe { *sa }.sa_family as i32 {
AF_INET => {
let sa: *const sockaddr_in = unsafe { mem::transmute(sa) };
let sa = & unsafe { *sa };
let (addr, port) = (sa.sin_addr.s_addr, sa.sin_port);
(IpAddr::V4(Ipv4Addr::new(
(addr & 0x000000FF) as u8,
((addr & 0x0000FF00) >> 8) as u8,
((addr & 0x00FF0000) >> 16) as u8,
((addr & 0xFF000000) >> 24) as u8)),
port)
},
AF_INET6 => {
let sa: *const sockaddr_in6 = unsafe { mem::transmute(sa) };
let sa = & unsafe { *sa };
let (addr, port) = (sa.sin6_addr.s6_addr, sa.sin6_port);
let addr: [u16; 8] = unsafe { mem::transmute(addr) };
(IpAddr::V6(Ipv6Addr::new(
addr[0],
addr[1],
addr[2],
addr[3],
addr[4],
addr[5],
addr[6],
addr[7])),
port)
},
_ => return None,
};
Some(addr)
}
fn convert_ifaddrs (ifa: *mut ifaddrs) -> Option<IpAddr> {
let ifa = unsafe { &mut *ifa };
convert_sockaddr(ifa.ifa_addr)
}
pub fn get_all() -> io::Result<Vec<IpAddr>> {
let mut ifap: *mut ifaddrs = unsafe { mem::zeroed() };
if unsafe { getifaddrs(&mut ifap as *mut _) }!= 0 {
return Err(io::Error::last_os_error());
}
let mut ret = Vec::new();
let mut cur: *mut ifaddrs = ifap;
while cur!= ptr::null_mut() {
if let Some(ip_addr) = convert_ifaddrs(cur) {
ret.push(ip_addr);
}
//TODO: do something else maybe?
cur = unsafe { (*cur).ifa_next };
}
unsafe { freeifaddrs(ifap) };
Ok(ret)
}
}
#[cfg(not(windows))]
fn get_if_addrs() -> io::Result<Vec<IpAddr>> {
getinterfaces::get_all()
}
#[cfg(windows)]
fn get_if_addrs() -> io::Result<Vec<IpAddr>> {
Ok(Vec::new())
}
/// Select the best available public address
pub fn select_public_address(port: u16) -> SocketAddr {
match get_if_addrs() {
Ok(list) => {
//prefer IPV4 bindings
for addr in &list { //TODO: use better criteria than just the first in the list
match *addr {
IpAddr::V4(a) if!a.is_unspecified_s() &&!a.is_loopback() &&!a.is_link_local() => {
return SocketAddr::V4(SocketAddrV4::new(a, port));
},
_ => {},
}
}
for addr in list {
match addr {
IpAddr::V6(a) if!a.is_unspecified_s() &&!a.is_loopback() => {
return SocketAddr::V6(SocketAddrV6::new(a, port, 0, 0));
},
_ => {},
}
}
},
Err(e) => debug!("Error listing public interfaces: {:?}", e)
}
SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), port))
}
pub fn map_external_address(local: &NodeEndpoint) -> Option<NodeEndpoint> {
if let SocketAddr::V4(ref local_addr) = local.address {
match search_gateway_from_timeout(local_addr.ip().clone(), Duration::new(5, 0)) {
Err(ref err) => debug!("Gateway search error: {}", err),
Ok(gateway) => {
match gateway.get_external_ip() {
Err(ref err) => {
debug!("IP request error: {}", err);
},
Ok(external_addr) => {
match gateway.add_any_port(PortMappingProtocol::TCP, SocketAddrV4::new(local_addr.ip().clone(), local_addr.port()), 0, "Parity Node/TCP") {
Err(ref err) => {
debug!("Port mapping error: {}", err);
},
Ok(tcp_port) => {
match gateway.add_any_port(PortMappingProtocol::UDP, SocketAddrV4::new(local_addr.ip().clone(), local.udp_port), 0, "Parity Node/UDP") {
Err(ref err) => {
debug!("Port mapping error: {}", err);
},
Ok(udp_port) => {
return Some(NodeEndpoint { address: SocketAddr::V4(SocketAddrV4::new(external_addr, tcp_port)), udp_port: udp_port });
},
}
},
}
},
}
},
}
}
None
}
#[test]
fn | () {
let pub_address = select_public_address(40477);
assert!(pub_address.port() == 40477);
}
#[ignore]
#[test]
fn can_map_external_address_or_fail() {
let pub_address = select_public_address(40478);
let _ = map_external_address(&NodeEndpoint { address: pub_address, udp_port: 40478 });
}
#[test]
fn ipv4_properties() {
#![cfg_attr(feature="dev", allow(too_many_arguments))]
fn check(octets: &[u8; 4], unspec: bool, loopback: bool,
private: bool, link_local: bool, global: bool,
multicast: bool, broadcast: bool, documentation: bool) {
let ip = Ipv4Addr::new(octets[0], octets[1], octets[2], octets[3]);
assert_eq!(octets, &ip.octets());
assert_eq!(ip.is_unspecified_s(), unspec);
assert_eq!(ip.is_loopback(), loopback);
assert_eq!(ip.is_private(), private);
assert_eq!(ip.is_link_local(), link_local);
assert_eq!(ip.is_global_s(), global);
assert_eq!(ip.is_multicast(), multicast);
assert_eq!(ip.is_broadcast(), broadcast);
assert_eq!(ip.is_documentation(), documentation);
}
// address unspec loopbk privt linloc global multicast brdcast doc
check(&[0, 0, 0, 0], true, false, false, false, true, false, false, false);
check(&[0, 0, 0, 1], false, false, false, false, true, false, false, false);
check(&[1, 0, 0, 0], false, false, false, false, true, false, false, false);
check(&[10, 9, 8, 7], false, false, true, false, false, false, false, false);
check(&[127, 1, 2, 3], false, true, false, false, false, false, false, false);
check(&[172, 31, 254, 253], false, false, true, false, false, false, false, false);
check(&[169, 254, 253, 242], false, false, false, true, false, false, false, false);
check(&[192, 0, 2, 183], false, false, false, false, false, false, false, true);
check(&[192, 1, 2, 183], false, false, false, false, true, false, false, false);
check(&[192, 168, 254, 253], false, false, true, false, false, false, false, false);
check(&[198, 51, 100, 0], false, false, false, false, false, false, false, true);
check(&[203, 0, 113, 0], false, false, false, false, false, false, false, true);
check(&[203, 2, 113, 0], false, false, false, false, true, false, false, false);
check(&[224, 0, 0, 0], false, false, false, false, true, true, false, false);
check(&[239, 255, 255, 255], false, false, false, false, true, true, false, false);
check(&[255, 255, 255, 255], false, false, false, false, false, false, true, false);
}
#[test]
fn ipv6_properties() {
fn check(str_addr: &str, unspec: bool, loopback: bool, global: bool) {
let ip: Ipv6Addr = str_addr.parse().unwrap();
assert_eq!(str_addr, ip.to_string());
assert_eq!(ip.is_unspecified_s(), unspec);
assert_eq!(ip.is_loopback(), loopback);
assert_eq!(ip.is_global_s(), global);
}
// unspec loopbk global
check("::", true, false, true);
check("::1", false, true, false);
}
| can_select_public_address | identifier_name |
genesis.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::{Address, H256, Uint, U256, FixedHash};
use util::sha3::SHA3_NULL_RLP;
use ethjson;
use super::seal::Seal;
/// Genesis components.
pub struct Genesis {
/// Seal.
pub seal: Seal,
/// Difficulty.
pub difficulty: U256, | /// Timestamp.
pub timestamp: u64,
/// Parent hash.
pub parent_hash: H256,
/// Gas limit.
pub gas_limit: U256,
/// Transactions root.
pub transactions_root: H256,
/// Receipts root.
pub receipts_root: H256,
/// State root.
pub state_root: Option<H256>,
/// Gas used.
pub gas_used: U256,
/// Extra data.
pub extra_data: Vec<u8>,
}
impl From<ethjson::spec::Genesis> for Genesis {
fn from(g: ethjson::spec::Genesis) -> Self {
Genesis {
seal: From::from(g.seal),
difficulty: g.difficulty.into(),
author: g.author.map_or_else(Address::zero, Into::into),
timestamp: g.timestamp.map_or(0, Into::into),
parent_hash: g.parent_hash.map_or_else(H256::zero, Into::into),
gas_limit: g.gas_limit.into(),
transactions_root: g.transactions_root.map_or_else(|| SHA3_NULL_RLP.clone(), Into::into),
receipts_root: g.receipts_root.map_or_else(|| SHA3_NULL_RLP.clone(), Into::into),
state_root: g.state_root.map(Into::into),
gas_used: g.gas_used.map_or_else(U256::zero, Into::into),
extra_data: g.extra_data.map_or_else(Vec::new, Into::into),
}
}
} | /// Author.
pub author: Address, | random_line_split |
genesis.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use util::{Address, H256, Uint, U256, FixedHash};
use util::sha3::SHA3_NULL_RLP;
use ethjson;
use super::seal::Seal;
/// Genesis components.
pub struct | {
/// Seal.
pub seal: Seal,
/// Difficulty.
pub difficulty: U256,
/// Author.
pub author: Address,
/// Timestamp.
pub timestamp: u64,
/// Parent hash.
pub parent_hash: H256,
/// Gas limit.
pub gas_limit: U256,
/// Transactions root.
pub transactions_root: H256,
/// Receipts root.
pub receipts_root: H256,
/// State root.
pub state_root: Option<H256>,
/// Gas used.
pub gas_used: U256,
/// Extra data.
pub extra_data: Vec<u8>,
}
impl From<ethjson::spec::Genesis> for Genesis {
fn from(g: ethjson::spec::Genesis) -> Self {
Genesis {
seal: From::from(g.seal),
difficulty: g.difficulty.into(),
author: g.author.map_or_else(Address::zero, Into::into),
timestamp: g.timestamp.map_or(0, Into::into),
parent_hash: g.parent_hash.map_or_else(H256::zero, Into::into),
gas_limit: g.gas_limit.into(),
transactions_root: g.transactions_root.map_or_else(|| SHA3_NULL_RLP.clone(), Into::into),
receipts_root: g.receipts_root.map_or_else(|| SHA3_NULL_RLP.clone(), Into::into),
state_root: g.state_root.map(Into::into),
gas_used: g.gas_used.map_or_else(U256::zero, Into::into),
extra_data: g.extra_data.map_or_else(Vec::new, Into::into),
}
}
}
| Genesis | identifier_name |
accept_language.rs | use language_tags::LanguageTag;
use header::QualityItem;
header! {
/// `Accept-Language` header, defined in
/// [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.5)
///
/// The `Accept-Language` header field can be used by user agents to
/// indicate the set of natural languages that are preferred in the
/// response.
///
/// # ABNF
/// ```plain
/// Accept-Language = 1#( language-range [ weight ] )
/// language-range = <language-range, see [RFC4647], Section 2.1>
/// ```
///
/// # Example values
/// * `da, en-gb;q=0.8, en;q=0.7`
/// * `en-us;q=1.0, en;q=0.5, fr`
///
/// # Examples
/// ```
/// use hyper::header::{Headers, AcceptLanguage, LanguageTag, qitem};
///
/// let mut headers = Headers::new();
/// let mut langtag: LanguageTag = Default::default();
/// langtag.language = Some("en".to_owned());
/// langtag.region = Some("US".to_owned());
/// headers.set(
/// AcceptLanguage(vec![
/// qitem(langtag),
/// ])
/// );
/// ```
/// ```
/// # extern crate hyper;
/// # #[macro_use] extern crate language_tags;
/// # use hyper::header::{Headers, AcceptLanguage, QualityItem, Quality, qitem}; | /// # fn main() {
/// let mut headers = Headers::new();
/// headers.set(
/// AcceptLanguage(vec![
/// qitem(langtag!(da)),
/// QualityItem::new(langtag!(en;;;GB), Quality(800)),
/// QualityItem::new(langtag!(en), Quality(700)),
/// ])
/// );
/// # }
/// ```
(AcceptLanguage, "Accept-Language") => (QualityItem<LanguageTag>)+
test_accept_language {
// From the RFC
test_header!(test1, vec![b"da, en-gb;q=0.8, en;q=0.7"]);
// Own test
test_header!(
test2, vec![b"en-US, en; q=0.5, fr"],
Some(AcceptLanguage(vec![
qitem(langtag!(en;;;US)),
QualityItem::new(langtag!(en), Quality(500)),
qitem(langtag!(fr)),
])));
}
}
bench_header!(bench, AcceptLanguage,
{ vec![b"en-us;q=1.0, en;q=0.5, fr".to_vec()] }); | /// # | random_line_split |
main.rs | // Copyright 2019 Google LLC
//
// 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.
#[macro_use]
extern crate structure;
extern crate base64;
extern crate memmap;
extern crate rand;
use rand::*;
const NN: usize = 312;
const BITS: usize = 64;
const PSIZE: usize = NN * BITS;
const NSAMPLES: usize = (NN + 2) * BITS;
const MM: usize = NN / 2;
const K: usize = 1337;
fn jumble(key: [u64; NN]) -> [u64; NN] {
let mut state = [0u64; NN];
let mut i = 1;
for _ in 0..K * (NN - 1) {
// Replace the slow + and * operations with something faster.
state[i] = state[i]
^ ((state[i - 1] ^ (state[i - 1] >> 62)) ^
((state[i - 1] >> 32) & 0xdeadbeefu64));
// state[i-1] ^ Wrapping(key[i]) ^
i += 1;
if i >= NN {
state[0] ^= state[NN - 1];
i = 1;
}
}
return state;
}
use std::fs::File;
use std::io::prelude::*;
use memmap::MmapMut;
fn | (fname: String) -> MmapMut {
use std::fs::OpenOptions;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&fname)
.expect("failed to open file");
file.set_len((NSAMPLES * NN * 8) as u64)
.expect("failed to set length");
return unsafe { MmapMut::map_mut(&file).expect("failed to map") };
}
fn main() {
let mut rng = thread_rng();
let mut startb = ropen("start".to_string());
let mut endb = ropen("end".to_string());
for j in 0..NSAMPLES {
if j % 100 == 0 {
println!("{:?}", j);
}
let mut buffer = [0u64; NN];
for i in 0..NN {
buffer[i] = rng.next_u64();
for k in 0..8 {
startb[j * NN * 8 + i * 8 + k] = (buffer[i] >> k * 8) as u8;
}
}
let end = jumble(buffer);
for i in 0..NN {
for k in 0..8 {
endb[j * NN * 8 + i * 8 + k] = (end[i] >> k * 8) as u8;
}
}
}
startb.flush().expect("failed to flush");
endb.flush().expect("failed to flush");
}
| ropen | identifier_name |
main.rs | // Copyright 2019 Google LLC
//
// 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.
#[macro_use]
extern crate structure;
extern crate base64;
extern crate memmap;
extern crate rand;
use rand::*;
const NN: usize = 312;
const BITS: usize = 64;
const PSIZE: usize = NN * BITS;
const NSAMPLES: usize = (NN + 2) * BITS;
const MM: usize = NN / 2;
const K: usize = 1337;
fn jumble(key: [u64; NN]) -> [u64; NN] {
let mut state = [0u64; NN];
let mut i = 1;
for _ in 0..K * (NN - 1) {
// Replace the slow + and * operations with something faster.
state[i] = state[i]
^ ((state[i - 1] ^ (state[i - 1] >> 62)) ^
((state[i - 1] >> 32) & 0xdeadbeefu64));
// state[i-1] ^ Wrapping(key[i]) ^
i += 1;
if i >= NN {
state[0] ^= state[NN - 1];
i = 1;
}
}
return state;
}
use std::fs::File;
use std::io::prelude::*;
use memmap::MmapMut;
fn ropen(fname: String) -> MmapMut {
use std::fs::OpenOptions;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&fname)
.expect("failed to open file");
file.set_len((NSAMPLES * NN * 8) as u64)
.expect("failed to set length");
return unsafe { MmapMut::map_mut(&file).expect("failed to map") };
}
fn main() {
let mut rng = thread_rng();
let mut startb = ropen("start".to_string());
let mut endb = ropen("end".to_string());
for j in 0..NSAMPLES {
if j % 100 == 0 {
println!("{:?}", j);
}
let mut buffer = [0u64; NN];
for i in 0..NN {
buffer[i] = rng.next_u64(); | }
}
let end = jumble(buffer);
for i in 0..NN {
for k in 0..8 {
endb[j * NN * 8 + i * 8 + k] = (end[i] >> k * 8) as u8;
}
}
}
startb.flush().expect("failed to flush");
endb.flush().expect("failed to flush");
} | for k in 0..8 {
startb[j * NN * 8 + i * 8 + k] = (buffer[i] >> k * 8) as u8; | random_line_split |
main.rs | // Copyright 2019 Google LLC
//
// 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.
#[macro_use]
extern crate structure;
extern crate base64;
extern crate memmap;
extern crate rand;
use rand::*;
const NN: usize = 312;
const BITS: usize = 64;
const PSIZE: usize = NN * BITS;
const NSAMPLES: usize = (NN + 2) * BITS;
const MM: usize = NN / 2;
const K: usize = 1337;
fn jumble(key: [u64; NN]) -> [u64; NN] {
let mut state = [0u64; NN];
let mut i = 1;
for _ in 0..K * (NN - 1) {
// Replace the slow + and * operations with something faster.
state[i] = state[i]
^ ((state[i - 1] ^ (state[i - 1] >> 62)) ^
((state[i - 1] >> 32) & 0xdeadbeefu64));
// state[i-1] ^ Wrapping(key[i]) ^
i += 1;
if i >= NN |
}
return state;
}
use std::fs::File;
use std::io::prelude::*;
use memmap::MmapMut;
fn ropen(fname: String) -> MmapMut {
use std::fs::OpenOptions;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&fname)
.expect("failed to open file");
file.set_len((NSAMPLES * NN * 8) as u64)
.expect("failed to set length");
return unsafe { MmapMut::map_mut(&file).expect("failed to map") };
}
fn main() {
let mut rng = thread_rng();
let mut startb = ropen("start".to_string());
let mut endb = ropen("end".to_string());
for j in 0..NSAMPLES {
if j % 100 == 0 {
println!("{:?}", j);
}
let mut buffer = [0u64; NN];
for i in 0..NN {
buffer[i] = rng.next_u64();
for k in 0..8 {
startb[j * NN * 8 + i * 8 + k] = (buffer[i] >> k * 8) as u8;
}
}
let end = jumble(buffer);
for i in 0..NN {
for k in 0..8 {
endb[j * NN * 8 + i * 8 + k] = (end[i] >> k * 8) as u8;
}
}
}
startb.flush().expect("failed to flush");
endb.flush().expect("failed to flush");
}
| {
state[0] ^= state[NN - 1];
i = 1;
} | conditional_block |
main.rs | // Copyright 2019 Google LLC
//
// 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.
#[macro_use]
extern crate structure;
extern crate base64;
extern crate memmap;
extern crate rand;
use rand::*;
const NN: usize = 312;
const BITS: usize = 64;
const PSIZE: usize = NN * BITS;
const NSAMPLES: usize = (NN + 2) * BITS;
const MM: usize = NN / 2;
const K: usize = 1337;
fn jumble(key: [u64; NN]) -> [u64; NN] {
let mut state = [0u64; NN];
let mut i = 1;
for _ in 0..K * (NN - 1) {
// Replace the slow + and * operations with something faster.
state[i] = state[i]
^ ((state[i - 1] ^ (state[i - 1] >> 62)) ^
((state[i - 1] >> 32) & 0xdeadbeefu64));
// state[i-1] ^ Wrapping(key[i]) ^
i += 1;
if i >= NN {
state[0] ^= state[NN - 1];
i = 1;
}
}
return state;
}
use std::fs::File;
use std::io::prelude::*;
use memmap::MmapMut;
fn ropen(fname: String) -> MmapMut {
use std::fs::OpenOptions;
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(&fname)
.expect("failed to open file");
file.set_len((NSAMPLES * NN * 8) as u64)
.expect("failed to set length");
return unsafe { MmapMut::map_mut(&file).expect("failed to map") };
}
fn main() | }
}
startb.flush().expect("failed to flush");
endb.flush().expect("failed to flush");
}
| {
let mut rng = thread_rng();
let mut startb = ropen("start".to_string());
let mut endb = ropen("end".to_string());
for j in 0..NSAMPLES {
if j % 100 == 0 {
println!("{:?}", j);
}
let mut buffer = [0u64; NN];
for i in 0..NN {
buffer[i] = rng.next_u64();
for k in 0..8 {
startb[j * NN * 8 + i * 8 + k] = (buffer[i] >> k * 8) as u8;
}
}
let end = jumble(buffer);
for i in 0..NN {
for k in 0..8 {
endb[j * NN * 8 + i * 8 + k] = (end[i] >> k * 8) as u8;
} | identifier_body |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn new(e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option<Box<Node>>,
tail: Option<Shared<Node>>
}
#[allow(boxed_local)]
impl Queue {
pub fn new() -> Queue {
Queue {
size: 0,
head: None,
tail: None
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.size
}
pub fn enqueue(&mut self, e: i32) {
self.size += 1;
let mut node = Box::new(Node::new(e));
let raw: *mut _ = &mut *node;
match self.tail {
Some(share) => unsafe { (**share).next = Some(node) },
None => self.head = Some(node),
}
unsafe {
self.tail = Some(Shared::new(raw));
}
}
pub fn contains(&self, e: i32) -> bool {
match self.head {
Some(ref head) => {
let mut node = head;
while (*node).elem!= e && (*node).next.is_some() {
node = (*node).next.as_ref().unwrap(); | (*node).elem == e
},
None => false,
}
}
pub fn dequeue(&mut self) -> Option<i32> {
self.head.take().map(
|head| {
let h = *head;
self.head = h.next;
self.size -= 1;
h.elem
}
)
}
} | } | random_line_split |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn | (e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option<Box<Node>>,
tail: Option<Shared<Node>>
}
#[allow(boxed_local)]
impl Queue {
pub fn new() -> Queue {
Queue {
size: 0,
head: None,
tail: None
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.size
}
pub fn enqueue(&mut self, e: i32) {
self.size += 1;
let mut node = Box::new(Node::new(e));
let raw: *mut _ = &mut *node;
match self.tail {
Some(share) => unsafe { (**share).next = Some(node) },
None => self.head = Some(node),
}
unsafe {
self.tail = Some(Shared::new(raw));
}
}
pub fn contains(&self, e: i32) -> bool {
match self.head {
Some(ref head) => {
let mut node = head;
while (*node).elem!= e && (*node).next.is_some() {
node = (*node).next.as_ref().unwrap();
}
(*node).elem == e
},
None => false,
}
}
pub fn dequeue(&mut self) -> Option<i32> {
self.head.take().map(
|head| {
let h = *head;
self.head = h.next;
self.size -= 1;
h.elem
}
)
}
}
| new | identifier_name |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn new(e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option<Box<Node>>,
tail: Option<Shared<Node>>
}
#[allow(boxed_local)]
impl Queue {
pub fn new() -> Queue {
Queue {
size: 0,
head: None,
tail: None
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.size
}
pub fn enqueue(&mut self, e: i32) {
self.size += 1;
let mut node = Box::new(Node::new(e));
let raw: *mut _ = &mut *node;
match self.tail {
Some(share) => unsafe { (**share).next = Some(node) },
None => self.head = Some(node),
}
unsafe {
self.tail = Some(Shared::new(raw));
}
}
pub fn contains(&self, e: i32) -> bool {
match self.head {
Some(ref head) => | ,
None => false,
}
}
pub fn dequeue(&mut self) -> Option<i32> {
self.head.take().map(
|head| {
let h = *head;
self.head = h.next;
self.size -= 1;
h.elem
}
)
}
}
| {
let mut node = head;
while (*node).elem != e && (*node).next.is_some() {
node = (*node).next.as_ref().unwrap();
}
(*node).elem == e
} | conditional_block |
day_5.rs | use std::boxed::Box;
use std::ptr::Shared;
use std::option::Option;
struct Node {
elem: i32,
next: Option<Box<Node>>
}
impl Node {
fn new(e: i32) -> Node {
Node {
elem: e,
next: None
}
}
}
#[derive(Default)]
pub struct Queue {
size: usize,
head: Option<Box<Node>>,
tail: Option<Shared<Node>>
}
#[allow(boxed_local)]
impl Queue {
pub fn new() -> Queue {
Queue {
size: 0,
head: None,
tail: None
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize |
pub fn enqueue(&mut self, e: i32) {
self.size += 1;
let mut node = Box::new(Node::new(e));
let raw: *mut _ = &mut *node;
match self.tail {
Some(share) => unsafe { (**share).next = Some(node) },
None => self.head = Some(node),
}
unsafe {
self.tail = Some(Shared::new(raw));
}
}
pub fn contains(&self, e: i32) -> bool {
match self.head {
Some(ref head) => {
let mut node = head;
while (*node).elem!= e && (*node).next.is_some() {
node = (*node).next.as_ref().unwrap();
}
(*node).elem == e
},
None => false,
}
}
pub fn dequeue(&mut self) -> Option<i32> {
self.head.take().map(
|head| {
let h = *head;
self.head = h.next;
self.size -= 1;
h.elem
}
)
}
}
| {
self.size
} | identifier_body |
server.rs | extern crate iron;
extern crate handlebars_iron as hbs;
extern crate rustc_serialize;
use iron::prelude::*;
use iron::{status};
use hbs::{Template, HandlebarsEngine};
use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
struct Team {
name: String,
pts: u16
}
impl ToJson for Team {
fn to_json(&self) -> Json {
let mut m: BTreeMap<String, Json> = BTreeMap::new();
m.insert("name".to_string(), self.name.to_json());
m.insert("pts".to_string(), self.pts.to_json()); | m.to_json()
}
}
fn make_data () -> BTreeMap<String, Json> {
let mut data = BTreeMap::new();
data.insert("year".to_string(), "2015".to_json());
let teams = vec![ Team { name: "Jiangsu Sainty".to_string(),
pts: 43u16 },
Team { name: "Beijing Guoan".to_string(),
pts: 27u16 },
Team { name: "Guangzhou Evergrand".to_string(),
pts: 22u16 },
Team { name: "Shandong Luneng".to_string(),
pts: 12u16 } ];
data.insert("teams".to_string(), teams.to_json());
data
}
/// the handler
fn hello_world(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("index", data)).set_mut(status::Ok);
Ok(resp)
}
fn main() {
let mut chain = Chain::new(hello_world);
chain.link_after(HandlebarsEngine::new("./examples/templates/", ".hbs"));
println!("Server running at http://localhost:3000/");
Iron::new(chain).http("localhost:3000").unwrap();
} | random_line_split |
|
server.rs | extern crate iron;
extern crate handlebars_iron as hbs;
extern crate rustc_serialize;
use iron::prelude::*;
use iron::{status};
use hbs::{Template, HandlebarsEngine};
use rustc_serialize::json::{ToJson, Json};
use std::collections::BTreeMap;
struct Team {
name: String,
pts: u16
}
impl ToJson for Team {
fn to_json(&self) -> Json {
let mut m: BTreeMap<String, Json> = BTreeMap::new();
m.insert("name".to_string(), self.name.to_json());
m.insert("pts".to_string(), self.pts.to_json());
m.to_json()
}
}
fn | () -> BTreeMap<String, Json> {
let mut data = BTreeMap::new();
data.insert("year".to_string(), "2015".to_json());
let teams = vec![ Team { name: "Jiangsu Sainty".to_string(),
pts: 43u16 },
Team { name: "Beijing Guoan".to_string(),
pts: 27u16 },
Team { name: "Guangzhou Evergrand".to_string(),
pts: 22u16 },
Team { name: "Shandong Luneng".to_string(),
pts: 12u16 } ];
data.insert("teams".to_string(), teams.to_json());
data
}
/// the handler
fn hello_world(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("index", data)).set_mut(status::Ok);
Ok(resp)
}
fn main() {
let mut chain = Chain::new(hello_world);
chain.link_after(HandlebarsEngine::new("./examples/templates/", ".hbs"));
println!("Server running at http://localhost:3000/");
Iron::new(chain).http("localhost:3000").unwrap();
}
| make_data | identifier_name |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone'?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding sphere.
pub struct SpacializedCone {
sphere: BoundingSphere,
axis: Vect,
hangle: N,
}
impl SpacializedCone {
/// Creates a new spacialized cone with a given bounding sphere, axis, and half-angle.
pub fn new(sphere: BoundingSphere, axis: Vect, hangle: N) -> SpacializedCone {
let axis = na::normalize(&axis);
unsafe { SpacializedCone::new_normalized(sphere, axis, hangle) }
}
/// Creates a new spacialized cone with a given bounding sphere, unit axis, and half-angle.
pub unsafe fn new_normalized(sphere: BoundingSphere, axis: Vect, hangle: N) -> SpacializedCone {
SpacializedCone {
sphere: sphere,
axis: axis,
hangle: hangle
}
}
/// The bounding sphere of this spacialized cone.
#[inline]
pub fn sphere<'a>(&'a self) -> &'a BoundingSphere {
&self.sphere
}
/// This cone axis.
#[inline]
pub fn axis<'a>(&'a self) -> &'a Vect {
&self.axis
}
/// This cone half angle.
#[inline]
pub fn hangle(&self) -> N {
self.hangle.clone()
}
/// Transforms the spacialized cone by `m`.
pub fn transform_by(&self, m: &Matrix) -> SpacializedCone {
unsafe {
let sphere = self.sphere.transform_by(m);
let axis = na::rotate(m, &self.axis);
SpacializedCone::new_normalized(sphere, axis, self.hangle)
}
}
// FIXME: create a Cone bounding volume and move this method to it.
/// Tests whether the given direction is inside of the cone.
#[inline]
pub fn contains_direction(&self, dir: &Vect) -> bool {
let angle = na::dot(&self.axis, dir);
let angle = na::clamp(angle, -na::one::<N>(), na::one()).acos();
angle <= self.hangle
}
}
#[cfg(not(feature = "4d"))]
impl BoundingVolume for SpacializedCone {
#[inline]
fn intersects(&self, other: &SpacializedCone) -> bool {
if self.sphere.intersects(&other.sphere) {
let dangle = na::dot(&self.axis, &(-other.axis));
let dangle = na::clamp(dangle, -na::one::<N>(), na::one()).acos();
let angsum = self.hangle + other.hangle;
dangle <= angsum
}
else {
false
}
}
#[inline]
fn contains(&self, other: &SpacializedCone) -> bool {
if self.sphere.contains(&other.sphere) {
panic!("Not yet implemented.")
}
else {
false
}
}
#[inline]
fn merge(&mut self, other: &SpacializedCone) {
self.sphere.merge(&other.sphere);
// merge the cone
let alpha = na::clamp(na::dot(&self.axis, &other.axis), -na::one::<N>(), na::one()).acos();
let mut rot_axis = na::cross(&self.axis, &other.axis);
if!na::is_zero(&rot_axis.normalize_mut()) {
let dangle = (alpha - self.hangle + other.hangle) * na::cast(0.5f64);
let rot = na::append_rotation(&na::one::<RotationMatrix>(), &(rot_axis * dangle));
self.axis = rot * self.axis;
self.hangle = na::clamp((self.hangle + other.hangle + alpha) * na::cast(0.5f64), na::zero(), BaseFloat::pi());
}
else {
// This happens if alpha ~= 0 or alpha ~= pi.
if alpha > na::one() { // NOTE: 1.0 is just a randomly chosen number in-between 0 and pi.
// alpha ~= pi
self.hangle = alpha;
}
else {
// alpha ~= 0, do nothing.
}
}
}
#[inline]
fn merged(&self, other: &SpacializedCone) -> SpacializedCone {
let mut res = self.clone();
res.merge(other);
res
}
}
impl Translation<Vect> for SpacializedCone {
#[inline]
fn translation(&self) -> Vect {
self.sphere.center().as_vec().clone()
}
#[inline]
fn inv_translation(&self) -> Vect {
-self.sphere.translation()
}
#[inline]
fn append_translation(&mut self, dv: &Vect) {
self.sphere.append_translation(dv);
}
#[inline]
fn append_translation_cpy(sc: &SpacializedCone, dv: &Vect) -> SpacializedCone {
SpacializedCone::new(
Translation::append_translation_cpy(&sc.sphere, dv),
sc.axis.clone(),
sc.hangle.clone())
}
#[inline]
fn prepend_translation(&mut self, dv: &Vect) {
self.sphere.append_translation(dv)
}
#[inline]
fn prepend_translation_cpy(sc: &SpacializedCone, dv: &Vect) -> SpacializedCone {
Translation::append_translation_cpy(sc, dv)
}
#[inline]
fn set_translation(&mut self, v: Vect) |
}
#[cfg(test)]
mod test {
use na::Vec3;
use na;
use super::SpacializedCone;
use bounding_volume::{BoundingVolume, BoundingSphere};
#[test]
#[cfg(feature = "3d")]
fn test_merge_vee() {
let sp = BoundingSphere::new(na::orig(), na::one());
let pi: N = BaseFloat::pi();
let pi_12 = pi / na::cast(12.0f64);
let a = SpacializedCone::new(sp.clone(), Vec3::new(1.0, 1.0, 0.0), pi_12);
let b = SpacializedCone::new(sp.clone(), Vec3::new(-1.0, 1.0, 0.0), pi_12);
let ab = a.merged(&b);
assert!(na::approx_eq(&ab.hangle, &(pi_12 * na::cast(4.0f64))))
}
}
| {
self.sphere.set_translation(v)
} | identifier_body |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone'?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding sphere.
pub struct SpacializedCone {
sphere: BoundingSphere,
axis: Vect,
hangle: N,
}
impl SpacializedCone {
/// Creates a new spacialized cone with a given bounding sphere, axis, and half-angle.
pub fn new(sphere: BoundingSphere, axis: Vect, hangle: N) -> SpacializedCone {
let axis = na::normalize(&axis);
unsafe { SpacializedCone::new_normalized(sphere, axis, hangle) }
}
/// Creates a new spacialized cone with a given bounding sphere, unit axis, and half-angle.
pub unsafe fn new_normalized(sphere: BoundingSphere, axis: Vect, hangle: N) -> SpacializedCone {
SpacializedCone {
sphere: sphere,
axis: axis,
hangle: hangle
}
}
/// The bounding sphere of this spacialized cone.
#[inline]
pub fn sphere<'a>(&'a self) -> &'a BoundingSphere {
&self.sphere
}
/// This cone axis.
#[inline]
pub fn axis<'a>(&'a self) -> &'a Vect {
&self.axis
}
/// This cone half angle.
#[inline]
pub fn hangle(&self) -> N {
self.hangle.clone()
}
/// Transforms the spacialized cone by `m`.
pub fn transform_by(&self, m: &Matrix) -> SpacializedCone {
unsafe {
let sphere = self.sphere.transform_by(m);
let axis = na::rotate(m, &self.axis);
SpacializedCone::new_normalized(sphere, axis, self.hangle)
}
}
// FIXME: create a Cone bounding volume and move this method to it.
/// Tests whether the given direction is inside of the cone.
#[inline]
pub fn contains_direction(&self, dir: &Vect) -> bool {
let angle = na::dot(&self.axis, dir);
let angle = na::clamp(angle, -na::one::<N>(), na::one()).acos();
angle <= self.hangle
}
}
#[cfg(not(feature = "4d"))]
impl BoundingVolume for SpacializedCone {
#[inline]
fn intersects(&self, other: &SpacializedCone) -> bool {
if self.sphere.intersects(&other.sphere) {
let dangle = na::dot(&self.axis, &(-other.axis));
let dangle = na::clamp(dangle, -na::one::<N>(), na::one()).acos();
let angsum = self.hangle + other.hangle;
dangle <= angsum
}
else {
false
}
}
#[inline]
fn contains(&self, other: &SpacializedCone) -> bool {
if self.sphere.contains(&other.sphere) {
panic!("Not yet implemented.")
}
else {
false
}
}
#[inline]
fn merge(&mut self, other: &SpacializedCone) {
self.sphere.merge(&other.sphere);
// merge the cone
let alpha = na::clamp(na::dot(&self.axis, &other.axis), -na::one::<N>(), na::one()).acos();
let mut rot_axis = na::cross(&self.axis, &other.axis);
if!na::is_zero(&rot_axis.normalize_mut()) {
let dangle = (alpha - self.hangle + other.hangle) * na::cast(0.5f64);
let rot = na::append_rotation(&na::one::<RotationMatrix>(), &(rot_axis * dangle));
self.axis = rot * self.axis;
self.hangle = na::clamp((self.hangle + other.hangle + alpha) * na::cast(0.5f64), na::zero(), BaseFloat::pi());
}
else |
}
#[inline]
fn merged(&self, other: &SpacializedCone) -> SpacializedCone {
let mut res = self.clone();
res.merge(other);
res
}
}
impl Translation<Vect> for SpacializedCone {
#[inline]
fn translation(&self) -> Vect {
self.sphere.center().as_vec().clone()
}
#[inline]
fn inv_translation(&self) -> Vect {
-self.sphere.translation()
}
#[inline]
fn append_translation(&mut self, dv: &Vect) {
self.sphere.append_translation(dv);
}
#[inline]
fn append_translation_cpy(sc: &SpacializedCone, dv: &Vect) -> SpacializedCone {
SpacializedCone::new(
Translation::append_translation_cpy(&sc.sphere, dv),
sc.axis.clone(),
sc.hangle.clone())
}
#[inline]
fn prepend_translation(&mut self, dv: &Vect) {
self.sphere.append_translation(dv)
}
#[inline]
fn prepend_translation_cpy(sc: &SpacializedCone, dv: &Vect) -> SpacializedCone {
Translation::append_translation_cpy(sc, dv)
}
#[inline]
fn set_translation(&mut self, v: Vect) {
self.sphere.set_translation(v)
}
}
#[cfg(test)]
mod test {
use na::Vec3;
use na;
use super::SpacializedCone;
use bounding_volume::{BoundingVolume, BoundingSphere};
#[test]
#[cfg(feature = "3d")]
fn test_merge_vee() {
let sp = BoundingSphere::new(na::orig(), na::one());
let pi: N = BaseFloat::pi();
let pi_12 = pi / na::cast(12.0f64);
let a = SpacializedCone::new(sp.clone(), Vec3::new(1.0, 1.0, 0.0), pi_12);
let b = SpacializedCone::new(sp.clone(), Vec3::new(-1.0, 1.0, 0.0), pi_12);
let ab = a.merged(&b);
assert!(na::approx_eq(&ab.hangle, &(pi_12 * na::cast(4.0f64))))
}
}
| {
// This happens if alpha ~= 0 or alpha ~= pi.
if alpha > na::one() { // NOTE: 1.0 is just a randomly chosen number in-between 0 and pi.
// alpha ~= pi
self.hangle = alpha;
}
else {
// alpha ~= 0, do nothing.
}
} | conditional_block |
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone'?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding sphere.
pub struct SpacializedCone {
sphere: BoundingSphere,
axis: Vect,
hangle: N,
}
impl SpacializedCone {
/// Creates a new spacialized cone with a given bounding sphere, axis, and half-angle.
pub fn new(sphere: BoundingSphere, axis: Vect, hangle: N) -> SpacializedCone {
let axis = na::normalize(&axis);
unsafe { SpacializedCone::new_normalized(sphere, axis, hangle) }
}
/// Creates a new spacialized cone with a given bounding sphere, unit axis, and half-angle.
pub unsafe fn new_normalized(sphere: BoundingSphere, axis: Vect, hangle: N) -> SpacializedCone {
SpacializedCone {
sphere: sphere,
axis: axis,
hangle: hangle
}
}
/// The bounding sphere of this spacialized cone.
#[inline]
pub fn sphere<'a>(&'a self) -> &'a BoundingSphere {
&self.sphere
}
/// This cone axis.
#[inline]
pub fn axis<'a>(&'a self) -> &'a Vect {
&self.axis
}
/// This cone half angle.
#[inline]
pub fn hangle(&self) -> N {
self.hangle.clone()
}
/// Transforms the spacialized cone by `m`.
pub fn transform_by(&self, m: &Matrix) -> SpacializedCone {
unsafe {
let sphere = self.sphere.transform_by(m);
let axis = na::rotate(m, &self.axis);
SpacializedCone::new_normalized(sphere, axis, self.hangle)
}
}
// FIXME: create a Cone bounding volume and move this method to it.
/// Tests whether the given direction is inside of the cone.
#[inline]
pub fn contains_direction(&self, dir: &Vect) -> bool {
let angle = na::dot(&self.axis, dir);
let angle = na::clamp(angle, -na::one::<N>(), na::one()).acos();
angle <= self.hangle
}
}
#[cfg(not(feature = "4d"))]
impl BoundingVolume for SpacializedCone {
#[inline]
fn intersects(&self, other: &SpacializedCone) -> bool {
if self.sphere.intersects(&other.sphere) {
let dangle = na::dot(&self.axis, &(-other.axis));
let dangle = na::clamp(dangle, -na::one::<N>(), na::one()).acos();
let angsum = self.hangle + other.hangle;
dangle <= angsum
}
else {
false
}
}
#[inline]
fn contains(&self, other: &SpacializedCone) -> bool {
if self.sphere.contains(&other.sphere) {
panic!("Not yet implemented.")
}
else {
false
}
}
#[inline]
fn merge(&mut self, other: &SpacializedCone) {
self.sphere.merge(&other.sphere);
// merge the cone
let alpha = na::clamp(na::dot(&self.axis, &other.axis), -na::one::<N>(), na::one()).acos();
let mut rot_axis = na::cross(&self.axis, &other.axis);
if!na::is_zero(&rot_axis.normalize_mut()) {
let dangle = (alpha - self.hangle + other.hangle) * na::cast(0.5f64);
let rot = na::append_rotation(&na::one::<RotationMatrix>(), &(rot_axis * dangle));
self.axis = rot * self.axis;
self.hangle = na::clamp((self.hangle + other.hangle + alpha) * na::cast(0.5f64), na::zero(), BaseFloat::pi());
}
else {
// This happens if alpha ~= 0 or alpha ~= pi.
if alpha > na::one() { // NOTE: 1.0 is just a randomly chosen number in-between 0 and pi.
// alpha ~= pi
self.hangle = alpha;
}
else {
// alpha ~= 0, do nothing.
}
}
}
#[inline]
fn merged(&self, other: &SpacializedCone) -> SpacializedCone {
let mut res = self.clone();
res.merge(other);
res
}
}
impl Translation<Vect> for SpacializedCone {
#[inline]
fn translation(&self) -> Vect {
self.sphere.center().as_vec().clone()
}
#[inline]
fn inv_translation(&self) -> Vect {
-self.sphere.translation()
}
#[inline]
fn append_translation(&mut self, dv: &Vect) {
self.sphere.append_translation(dv);
}
#[inline]
fn append_translation_cpy(sc: &SpacializedCone, dv: &Vect) -> SpacializedCone {
SpacializedCone::new(
Translation::append_translation_cpy(&sc.sphere, dv),
sc.axis.clone(),
sc.hangle.clone())
}
#[inline]
fn prepend_translation(&mut self, dv: &Vect) {
self.sphere.append_translation(dv)
}
#[inline]
fn prepend_translation_cpy(sc: &SpacializedCone, dv: &Vect) -> SpacializedCone {
Translation::append_translation_cpy(sc, dv)
}
#[inline]
fn set_translation(&mut self, v: Vect) {
self.sphere.set_translation(v)
}
}
#[cfg(test)]
mod test {
use na::Vec3;
use na;
use super::SpacializedCone;
use bounding_volume::{BoundingVolume, BoundingSphere};
#[test]
#[cfg(feature = "3d")]
fn test_merge_vee() {
let sp = BoundingSphere::new(na::orig(), na::one());
let pi: N = BaseFloat::pi();
let pi_12 = pi / na::cast(12.0f64);
let a = SpacializedCone::new(sp.clone(), Vec3::new(1.0, 1.0, 0.0), pi_12);
let b = SpacializedCone::new(sp.clone(), Vec3::new(-1.0, 1.0, 0.0), pi_12); |
let ab = a.merged(&b);
assert!(na::approx_eq(&ab.hangle, &(pi_12 * na::cast(4.0f64))))
}
} | random_line_split |
|
spacialized_cone.rs | use na::{Translation, Norm, RotationMatrix, BaseFloat};
use na;
use math::{N, Vect, Matrix};
use bounding_volume::{BoundingVolume, BoundingSphere};
use math::{Scalar, Point, Vect};
// FIXME: make a structure 'cone'?
#[derive(Debug, PartialEq, Clone, RustcEncodable, RustcDecodable)]
/// A normal cone with a bounding sphere.
pub struct SpacializedCone {
sphere: BoundingSphere,
axis: Vect,
hangle: N,
}
impl SpacializedCone {
/// Creates a new spacialized cone with a given bounding sphere, axis, and half-angle.
pub fn new(sphere: BoundingSphere, axis: Vect, hangle: N) -> SpacializedCone {
let axis = na::normalize(&axis);
unsafe { SpacializedCone::new_normalized(sphere, axis, hangle) }
}
/// Creates a new spacialized cone with a given bounding sphere, unit axis, and half-angle.
pub unsafe fn new_normalized(sphere: BoundingSphere, axis: Vect, hangle: N) -> SpacializedCone {
SpacializedCone {
sphere: sphere,
axis: axis,
hangle: hangle
}
}
/// The bounding sphere of this spacialized cone.
#[inline]
pub fn sphere<'a>(&'a self) -> &'a BoundingSphere {
&self.sphere
}
/// This cone axis.
#[inline]
pub fn axis<'a>(&'a self) -> &'a Vect {
&self.axis
}
/// This cone half angle.
#[inline]
pub fn hangle(&self) -> N {
self.hangle.clone()
}
/// Transforms the spacialized cone by `m`.
pub fn transform_by(&self, m: &Matrix) -> SpacializedCone {
unsafe {
let sphere = self.sphere.transform_by(m);
let axis = na::rotate(m, &self.axis);
SpacializedCone::new_normalized(sphere, axis, self.hangle)
}
}
// FIXME: create a Cone bounding volume and move this method to it.
/// Tests whether the given direction is inside of the cone.
#[inline]
pub fn contains_direction(&self, dir: &Vect) -> bool {
let angle = na::dot(&self.axis, dir);
let angle = na::clamp(angle, -na::one::<N>(), na::one()).acos();
angle <= self.hangle
}
}
#[cfg(not(feature = "4d"))]
impl BoundingVolume for SpacializedCone {
#[inline]
fn intersects(&self, other: &SpacializedCone) -> bool {
if self.sphere.intersects(&other.sphere) {
let dangle = na::dot(&self.axis, &(-other.axis));
let dangle = na::clamp(dangle, -na::one::<N>(), na::one()).acos();
let angsum = self.hangle + other.hangle;
dangle <= angsum
}
else {
false
}
}
#[inline]
fn contains(&self, other: &SpacializedCone) -> bool {
if self.sphere.contains(&other.sphere) {
panic!("Not yet implemented.")
}
else {
false
}
}
#[inline]
fn merge(&mut self, other: &SpacializedCone) {
self.sphere.merge(&other.sphere);
// merge the cone
let alpha = na::clamp(na::dot(&self.axis, &other.axis), -na::one::<N>(), na::one()).acos();
let mut rot_axis = na::cross(&self.axis, &other.axis);
if!na::is_zero(&rot_axis.normalize_mut()) {
let dangle = (alpha - self.hangle + other.hangle) * na::cast(0.5f64);
let rot = na::append_rotation(&na::one::<RotationMatrix>(), &(rot_axis * dangle));
self.axis = rot * self.axis;
self.hangle = na::clamp((self.hangle + other.hangle + alpha) * na::cast(0.5f64), na::zero(), BaseFloat::pi());
}
else {
// This happens if alpha ~= 0 or alpha ~= pi.
if alpha > na::one() { // NOTE: 1.0 is just a randomly chosen number in-between 0 and pi.
// alpha ~= pi
self.hangle = alpha;
}
else {
// alpha ~= 0, do nothing.
}
}
}
#[inline]
fn merged(&self, other: &SpacializedCone) -> SpacializedCone {
let mut res = self.clone();
res.merge(other);
res
}
}
impl Translation<Vect> for SpacializedCone {
#[inline]
fn | (&self) -> Vect {
self.sphere.center().as_vec().clone()
}
#[inline]
fn inv_translation(&self) -> Vect {
-self.sphere.translation()
}
#[inline]
fn append_translation(&mut self, dv: &Vect) {
self.sphere.append_translation(dv);
}
#[inline]
fn append_translation_cpy(sc: &SpacializedCone, dv: &Vect) -> SpacializedCone {
SpacializedCone::new(
Translation::append_translation_cpy(&sc.sphere, dv),
sc.axis.clone(),
sc.hangle.clone())
}
#[inline]
fn prepend_translation(&mut self, dv: &Vect) {
self.sphere.append_translation(dv)
}
#[inline]
fn prepend_translation_cpy(sc: &SpacializedCone, dv: &Vect) -> SpacializedCone {
Translation::append_translation_cpy(sc, dv)
}
#[inline]
fn set_translation(&mut self, v: Vect) {
self.sphere.set_translation(v)
}
}
#[cfg(test)]
mod test {
use na::Vec3;
use na;
use super::SpacializedCone;
use bounding_volume::{BoundingVolume, BoundingSphere};
#[test]
#[cfg(feature = "3d")]
fn test_merge_vee() {
let sp = BoundingSphere::new(na::orig(), na::one());
let pi: N = BaseFloat::pi();
let pi_12 = pi / na::cast(12.0f64);
let a = SpacializedCone::new(sp.clone(), Vec3::new(1.0, 1.0, 0.0), pi_12);
let b = SpacializedCone::new(sp.clone(), Vec3::new(-1.0, 1.0, 0.0), pi_12);
let ab = a.merged(&b);
assert!(na::approx_eq(&ab.hangle, &(pi_12 * na::cast(4.0f64))))
}
}
| translation | identifier_name |
primitives_arrays.rs | use std::mem;
// This function borrows a slice
fn analyze_slice(slice: &[i32]) {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
}
pub fn main() {
// Fixed-size array (type signature is superfluous)
let xs: [i32; 5] = [1, 2, 3, 4, 5];
// All elements can be initialized to the same value
let ys: [i32; 500] = [0; 500];
println!("Array xs: {:?}", xs);
// Indexing starts at 0
println!("first element of the array: {}", xs[0]);
println!("second element of the array: {}", xs[1]);
// `len` returns the size of the array
println!("array xs size: {}", xs.len());
// Arrays are stack allocated
println!("array xs occupies {} bytes", mem::size_of_val(&xs));
println!("array ys size: {}", ys.len());
println!("array ys occupies {} bytes", mem::size_of_val(&ys));
// Arrays can be automatically borrowed as slices
println!("borrow the whole array as a slice");
analyze_slice(&xs);
// Slices can point to a section of an array
println!("borrow a section of the array as a slice");
analyze_slice(&ys[1.. 4]);
// Out of bound indexing yields a panic
//println!("{}", xs[5]); | println!("Slice: {:?}", &ps[1.. 4]);
} |
let ps: &[i32] = &[1, 3, 5, 6, 9];
analyze_slice(&ps[1 .. 4]); | random_line_split |
primitives_arrays.rs | use std::mem;
// This function borrows a slice
fn analyze_slice(slice: &[i32]) |
pub fn main() {
// Fixed-size array (type signature is superfluous)
let xs: [i32; 5] = [1, 2, 3, 4, 5];
// All elements can be initialized to the same value
let ys: [i32; 500] = [0; 500];
println!("Array xs: {:?}", xs);
// Indexing starts at 0
println!("first element of the array: {}", xs[0]);
println!("second element of the array: {}", xs[1]);
// `len` returns the size of the array
println!("array xs size: {}", xs.len());
// Arrays are stack allocated
println!("array xs occupies {} bytes", mem::size_of_val(&xs));
println!("array ys size: {}", ys.len());
println!("array ys occupies {} bytes", mem::size_of_val(&ys));
// Arrays can be automatically borrowed as slices
println!("borrow the whole array as a slice");
analyze_slice(&xs);
// Slices can point to a section of an array
println!("borrow a section of the array as a slice");
analyze_slice(&ys[1.. 4]);
// Out of bound indexing yields a panic
//println!("{}", xs[5]);
let ps: &[i32] = &[1, 3, 5, 6, 9];
analyze_slice(&ps[1.. 4]);
println!("Slice: {:?}", &ps[1.. 4]);
} | {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
} | identifier_body |
primitives_arrays.rs | use std::mem;
// This function borrows a slice
fn analyze_slice(slice: &[i32]) {
println!("first element of the slice: {}", slice[0]);
println!("the slice has {} elements", slice.len());
}
pub fn | () {
// Fixed-size array (type signature is superfluous)
let xs: [i32; 5] = [1, 2, 3, 4, 5];
// All elements can be initialized to the same value
let ys: [i32; 500] = [0; 500];
println!("Array xs: {:?}", xs);
// Indexing starts at 0
println!("first element of the array: {}", xs[0]);
println!("second element of the array: {}", xs[1]);
// `len` returns the size of the array
println!("array xs size: {}", xs.len());
// Arrays are stack allocated
println!("array xs occupies {} bytes", mem::size_of_val(&xs));
println!("array ys size: {}", ys.len());
println!("array ys occupies {} bytes", mem::size_of_val(&ys));
// Arrays can be automatically borrowed as slices
println!("borrow the whole array as a slice");
analyze_slice(&xs);
// Slices can point to a section of an array
println!("borrow a section of the array as a slice");
analyze_slice(&ys[1.. 4]);
// Out of bound indexing yields a panic
//println!("{}", xs[5]);
let ps: &[i32] = &[1, 3, 5, 6, 9];
analyze_slice(&ps[1.. 4]);
println!("Slice: {:?}", &ps[1.. 4]);
} | main | identifier_name |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: ObjectHash,
commit: CommitObject,
}
impl PartialEq for TimeOrdered {
fn eq(&self, other: &Self) -> bool {
self.commit.timestamp == other.commit.timestamp
}
}
impl PartialOrd for TimeOrdered {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TimeOrdered {
fn cmp(&self, other: &Self) -> Ordering |
}
pub fn command() -> App<'static,'static> {
SubCommand::with_name("log").about("View repository commit history.")
}
pub fn go(repository: &mut Repository, _matches: &ArgMatches) -> Result<()> {
let mut commits = {
let ctx = repository.local(())?;
let mut commits = BinaryHeap::new();
let mut hashes = ctx.refs.head().into_iter().collect::<Vec<_>>();
let mut visited = HashSet::new();
while!hashes.is_empty() {
let commit_stream = {
let next_hashes = hashes.drain(..).filter(|&hash| visited.insert(hash));
stream::futures_unordered(next_hashes.map(|hash| {
ctx.read_commit(hash).map(move |commit| (hash, commit))
}))
};
commit_stream
.for_each(|(hash, commit)| {
hashes.extend(commit.parents.iter().cloned());
commits.push(TimeOrdered { hash, commit });
Ok(())
})
.wait()?;
}
ctx.close().wait()?;
commits.into_sorted_vec()
};
let mut buf = String::new();
if let Some(TimeOrdered { hash, commit }) = commits.pop() {
write!(
buf,
"commit {} \nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
}
for TimeOrdered { hash, commit } in commits.into_iter().rev() {
write!(
buf,
"\ncommit {}\nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
}
print!("{}", buf);
Ok(())
}
| {
self.commit.timestamp.cmp(&other.commit.timestamp)
} | identifier_body |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: ObjectHash,
commit: CommitObject,
}
impl PartialEq for TimeOrdered {
fn eq(&self, other: &Self) -> bool {
self.commit.timestamp == other.commit.timestamp
}
}
impl PartialOrd for TimeOrdered {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TimeOrdered {
fn cmp(&self, other: &Self) -> Ordering {
self.commit.timestamp.cmp(&other.commit.timestamp)
}
}
pub fn command() -> App<'static,'static> {
SubCommand::with_name("log").about("View repository commit history.")
}
pub fn go(repository: &mut Repository, _matches: &ArgMatches) -> Result<()> {
let mut commits = {
let ctx = repository.local(())?;
let mut commits = BinaryHeap::new();
let mut hashes = ctx.refs.head().into_iter().collect::<Vec<_>>();
let mut visited = HashSet::new();
while!hashes.is_empty() {
let commit_stream = {
let next_hashes = hashes.drain(..).filter(|&hash| visited.insert(hash));
stream::futures_unordered(next_hashes.map(|hash| {
ctx.read_commit(hash).map(move |commit| (hash, commit))
}))
};
commit_stream
.for_each(|(hash, commit)| {
hashes.extend(commit.parents.iter().cloned());
commits.push(TimeOrdered { hash, commit });
Ok(())
})
.wait()?;
}
ctx.close().wait()?;
commits.into_sorted_vec()
};
let mut buf = String::new();
if let Some(TimeOrdered { hash, commit }) = commits.pop() {
write!(
buf,
"commit {} \nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?; | for TimeOrdered { hash, commit } in commits.into_iter().rev() {
write!(
buf,
"\ncommit {}\nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
}
print!("{}", buf);
Ok(())
} | }
| random_line_split |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: ObjectHash,
commit: CommitObject,
}
impl PartialEq for TimeOrdered {
fn eq(&self, other: &Self) -> bool {
self.commit.timestamp == other.commit.timestamp
}
}
impl PartialOrd for TimeOrdered {
fn | (&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TimeOrdered {
fn cmp(&self, other: &Self) -> Ordering {
self.commit.timestamp.cmp(&other.commit.timestamp)
}
}
pub fn command() -> App<'static,'static> {
SubCommand::with_name("log").about("View repository commit history.")
}
pub fn go(repository: &mut Repository, _matches: &ArgMatches) -> Result<()> {
let mut commits = {
let ctx = repository.local(())?;
let mut commits = BinaryHeap::new();
let mut hashes = ctx.refs.head().into_iter().collect::<Vec<_>>();
let mut visited = HashSet::new();
while!hashes.is_empty() {
let commit_stream = {
let next_hashes = hashes.drain(..).filter(|&hash| visited.insert(hash));
stream::futures_unordered(next_hashes.map(|hash| {
ctx.read_commit(hash).map(move |commit| (hash, commit))
}))
};
commit_stream
.for_each(|(hash, commit)| {
hashes.extend(commit.parents.iter().cloned());
commits.push(TimeOrdered { hash, commit });
Ok(())
})
.wait()?;
}
ctx.close().wait()?;
commits.into_sorted_vec()
};
let mut buf = String::new();
if let Some(TimeOrdered { hash, commit }) = commits.pop() {
write!(
buf,
"commit {} \nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
}
for TimeOrdered { hash, commit } in commits.into_iter().rev() {
write!(
buf,
"\ncommit {}\nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
}
print!("{}", buf);
Ok(())
}
| partial_cmp | identifier_name |
log.rs | use std::cmp::Ordering;
use std::collections::{BinaryHeap, HashSet};
use std::fmt::Write;
use clap::{App, ArgMatches, SubCommand};
use futures::prelude::*;
use futures::stream;
use attaca::marshal::{CommitObject, ObjectHash};
use attaca::Repository;
use errors::*;
#[derive(Eq)]
struct TimeOrdered {
hash: ObjectHash,
commit: CommitObject,
}
impl PartialEq for TimeOrdered {
fn eq(&self, other: &Self) -> bool {
self.commit.timestamp == other.commit.timestamp
}
}
impl PartialOrd for TimeOrdered {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for TimeOrdered {
fn cmp(&self, other: &Self) -> Ordering {
self.commit.timestamp.cmp(&other.commit.timestamp)
}
}
pub fn command() -> App<'static,'static> {
SubCommand::with_name("log").about("View repository commit history.")
}
pub fn go(repository: &mut Repository, _matches: &ArgMatches) -> Result<()> {
let mut commits = {
let ctx = repository.local(())?;
let mut commits = BinaryHeap::new();
let mut hashes = ctx.refs.head().into_iter().collect::<Vec<_>>();
let mut visited = HashSet::new();
while!hashes.is_empty() {
let commit_stream = {
let next_hashes = hashes.drain(..).filter(|&hash| visited.insert(hash));
stream::futures_unordered(next_hashes.map(|hash| {
ctx.read_commit(hash).map(move |commit| (hash, commit))
}))
};
commit_stream
.for_each(|(hash, commit)| {
hashes.extend(commit.parents.iter().cloned());
commits.push(TimeOrdered { hash, commit });
Ok(())
})
.wait()?;
}
ctx.close().wait()?;
commits.into_sorted_vec()
};
let mut buf = String::new();
if let Some(TimeOrdered { hash, commit }) = commits.pop() |
for TimeOrdered { hash, commit } in commits.into_iter().rev() {
write!(
buf,
"\ncommit {}\nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
}
print!("{}", buf);
Ok(())
}
| {
write!(
buf,
"commit {} \nDate: {}\n\t{}\n",
hash,
commit.timestamp,
commit.message
)?;
} | conditional_block |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
/// This mutex will block threads waiting for the lock to become available. The
/// mutex can also be statically initialized or created via a [`new`]
/// constructor. Each mutex has a type parameter which represents the data that
/// it is protecting. The data can only be accessed through the RAII guards
/// returned from [`lock`] and [`try_lock`], which guarantees that the data is only
/// ever accessed when the mutex is locked.
///
/// # Poisoning
///
/// The mutexes in this module implement a strategy called "poisoning" where a
/// mutex is considered poisoned whenever a thread panics while holding the
/// mutex. Once a mutex is poisoned, all other threads are unable to access the
/// data by default as it is likely tainted (some invariant is not being
/// upheld).
///
/// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a
/// [`Result`] which indicates whether a mutex has been poisoned or not. Most
/// usage of a mutex will simply [`unwrap()`] these results, propagating panics
/// among threads to ensure that a possibly invalid invariant is not witnessed.
///
/// A poisoned mutex, however, does not prevent all access to the underlying
/// data. The [`PoisonError`] type has an [`into_inner`] method which will return
/// the guard that would have otherwise been returned on a successful lock. This
/// allows access to the data, despite the lock being poisoned.
///
/// [`new`]: Self::new
/// [`lock`]: Self::lock
/// [`try_lock`]: Self::try_lock
/// [`unwrap()`]: Result::unwrap
/// [`PoisonError`]: super::PoisonError
/// [`into_inner`]: super::PoisonError::into_inner
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
/// use std::sync::mpsc::channel;
///
/// const N: usize = 10;
///
/// // Spawn a few threads to increment a shared variable (non-atomically), and
/// // let the main thread know once all increments are done.
/// //
/// // Here we're using an Arc to share memory among threads, and the data inside
/// // the Arc is protected with a mutex.
/// let data = Arc::new(Mutex::new(0));
///
/// let (tx, rx) = channel();
/// for _ in 0..N {
/// let (data, tx) = (Arc::clone(&data), tx.clone());
/// thread::spawn(move || {
/// // The shared state can only be accessed once the lock is held.
/// // Our non-atomic increment is safe because we're the only thread
/// // which can access the shared state when the lock is held.
/// //
/// // We unwrap() the return value to assert that we are not expecting
/// // threads to ever fail while holding the lock.
/// let mut data = data.lock().unwrap();
/// *data += 1;
/// if *data == N {
/// tx.send(()).unwrap();
/// }
/// // the lock is unlocked here when `data` goes out of scope.
/// });
/// }
///
/// rx.recv().unwrap();
/// ```
///
/// To recover from a poisoned mutex:
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let lock = Arc::new(Mutex::new(0_u32));
/// let lock2 = Arc::clone(&lock);
///
/// let _ = thread::spawn(move || -> () {
/// // This thread will acquire the mutex first, unwrapping the result of
/// // `lock` because the lock has not been poisoned.
/// let _guard = lock2.lock().unwrap();
///
/// // This panic while holding the lock (`_guard` is in scope) will poison
/// // the mutex.
/// panic!();
/// }).join();
///
/// // The lock is poisoned by this point, but the returned result can be
/// // pattern matched on to return the underlying guard on both branches.
/// let mut guard = match lock.lock() {
/// Ok(guard) => guard,
/// Err(poisoned) => poisoned.into_inner(),
/// };
///
/// *guard += 1;
/// ```
///
/// It is sometimes necessary to manually drop the mutex guard to unlock it
/// sooner than the end of the enclosing scope.
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// const N: usize = 3;
///
/// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
/// let res_mutex = Arc::new(Mutex::new(0));
///
/// let mut threads = Vec::with_capacity(N);
/// (0..N).for_each(|_| {
/// let data_mutex_clone = Arc::clone(&data_mutex);
/// let res_mutex_clone = Arc::clone(&res_mutex);
///
/// threads.push(thread::spawn(move || {
/// let mut data = data_mutex_clone.lock().unwrap();
/// // This is the result of some important and long-ish work.
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
/// data.push(result);
/// drop(data);
/// *res_mutex_clone.lock().unwrap() += result;
/// }));
/// });
///
/// let mut data = data_mutex.lock().unwrap();
/// // This is the result of some important and long-ish work.
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
/// data.push(result);
/// // We drop the `data` explicitly because it's not necessary anymore and the
/// // thread still has work to do. This allow other threads to start working on
/// // the data immediately, without waiting for the rest of the unrelated work
/// // to be done here.
/// //
/// // It's even more important here than in the threads because we `.join` the
/// // threads after that. If we had not dropped the mutex guard, a thread could
/// // be waiting forever for it, causing a deadlock.
/// drop(data);
/// // Here the mutex guard is not assigned to a variable and so, even if the
/// // scope does not end after this line, the mutex is still released: there is
/// // no deadlock.
/// *res_mutex.lock().unwrap() += result;
///
/// threads.into_iter().for_each(|thread| {
/// thread
/// .join()
/// .expect("The thread creating or execution failed!")
/// });
///
/// assert_eq!(*res_mutex.lock().unwrap(), 800);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "Mutex")]
pub struct Mutex<T:?Sized> {
inner: sys::MovableMutex,
poison: poison::Flag,
data: UnsafeCell<T>,
}
// these are the only places where `T: Send` matters; all other
// functionality works fine on a single thread.
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T:?Sized + Send> Send for Mutex<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T:?Sized + Send> Sync for Mutex<T> {}
/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// [`Deref`] and [`DerefMut`] implementations.
///
/// This structure is created by the [`lock`] and [`try_lock`] methods on
/// [`Mutex`].
///
/// [`lock`]: Mutex::lock
/// [`try_lock`]: Mutex::try_lock
#[must_use = "if unused the Mutex will immediately unlock"]
#[cfg_attr(
not(bootstrap),
must_not_suspend = "holding a MutexGuard across suspend \
points can cause deadlocks, delays, \
and cause Futures to not implement `Send`"
)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct MutexGuard<'a, T:?Sized + 'a> {
lock: &'a Mutex<T>,
poison: poison::Guard,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized>!Send for MutexGuard<'_, T> {}
#[stable(feature = "mutexguard", since = "1.19.0")]
unsafe impl<T:?Sized + Sync> Sync for MutexGuard<'_, T> {}
impl<T> Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mutex = Mutex::new(0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new(t: T) -> Mutex<T> {
Mutex {
inner: sys::MovableMutex::new(),
poison: poison::Flag::new(),
data: UnsafeCell::new(t),
}
}
}
impl<T:?Sized> Mutex<T> {
/// Acquires a mutex, blocking the current thread until it is able to do so.
///
/// This function will block the local thread until it is available to acquire
/// the mutex. Upon returning, the thread is the only thread with the lock
/// held. An RAII guard is returned to allow scoped unlock of the lock. When
/// the guard goes out of scope, the mutex will be unlocked.
///
/// The exact behavior on locking a mutex in the thread which already holds
/// the lock is left unspecified. However, this function will not return on
/// the second call (it might panic or deadlock, for example).
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error once the mutex is acquired.
///
/// # Panics
///
/// This function might panic when called if the lock is already held by
/// the current thread.
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// thread::spawn(move || {
/// *c_mutex.lock().unwrap() = 10;
/// }).join().expect("thread::spawn failed");
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
unsafe {
self.inner.raw_lock();
MutexGuard::new(self)
}
}
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then [`Err`] is returned.
/// Otherwise, an RAII guard is returned. The lock will be unlocked when the
/// guard is dropped.
///
/// This function does not block.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return the [`Poisoned`] error if the mutex would
/// otherwise be acquired.
///
/// If the mutex could not be acquired because it is already locked, then
/// this call will return the [`WouldBlock`] error.
///
/// [`Poisoned`]: TryLockError::Poisoned
/// [`WouldBlock`]: TryLockError::WouldBlock
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// thread::spawn(move || {
/// let mut lock = c_mutex.try_lock();
/// if let Ok(ref mut mutex) = lock {
/// **mutex = 10;
/// } else {
/// println!("try_lock failed");
/// }
/// }).join().expect("thread::spawn failed");
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
unsafe {
if self.inner.try_lock() {
Ok(MutexGuard::new(self)?)
} else {
Err(TryLockError::WouldBlock)
}
}
}
/// Immediately drops the guard, and consequently unlocks the mutex.
///
/// This function is equivalent to calling [`drop`] on the guard but is more self-documenting.
/// Alternately, the guard will be automatically dropped when it goes out of scope.
///
/// ```
/// #![feature(mutex_unlock)]
///
/// use std::sync::Mutex;
/// let mutex = Mutex::new(0);
///
/// let mut guard = mutex.lock().unwrap();
/// *guard += 20;
/// Mutex::unlock(guard);
/// ```
#[unstable(feature = "mutex_unlock", issue = "81872")]
pub fn unlock(guard: MutexGuard<'_, T>) {
drop(guard);
}
/// Determines whether the mutex is poisoned.
///
/// If another thread is active, the mutex can still become poisoned at any
/// time. You should not trust a `false` value for program correctness
/// without additional synchronization.
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// let _ = thread::spawn(move || {
/// let _lock = c_mutex.lock().unwrap();
/// panic!(); // the mutex gets poisoned
/// }).join();
/// assert_eq!(mutex.is_poisoned(), true);
/// ```
#[inline]
#[stable(feature = "sync_poison", since = "1.2.0")]
pub fn is_poisoned(&self) -> bool {
self.poison.get()
}
/// Consumes this mutex, returning the underlying data.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error instead.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mutex = Mutex::new(0);
/// assert_eq!(mutex.into_inner().unwrap(), 0);
/// ```
#[stable(feature = "mutex_into_inner", since = "1.6.0")]
pub fn into_inner(self) -> LockResult<T>
where
T: Sized,
{
let data = self.data.into_inner();
poison::map_result(self.poison.borrow(), |_| data)
}
/// Returns a mutable reference to the underlying data.
///
/// Since this call borrows the `Mutex` mutably, no actual locking needs to
/// take place -- the mutable borrow statically guarantees no locks exist.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error instead.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mut mutex = Mutex::new(0);
/// *mutex.get_mut().unwrap() = 10;
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "mutex_get_mut", since = "1.6.0")]
pub fn get_mut(&mut self) -> LockResult<&mut T> {
let data = self.data.get_mut();
poison::map_result(self.poison.borrow(), |_| data)
}
}
#[stable(feature = "mutex_from", since = "1.24.0")]
impl<T> From<T> for Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
/// This is equivalent to [`Mutex::new`].
fn from(t: T) -> Self {
Mutex::new(t)
}
}
#[stable(feature = "mutex_default", since = "1.10.0")]
impl<T:?Sized + Default> Default for Mutex<T> {
/// Creates a `Mutex<T>`, with the `Default` value for T.
fn default() -> Mutex<T> {
Mutex::new(Default::default())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("Mutex");
match self.try_lock() {
Ok(guard) => |
Err(TryLockError::Poisoned(err)) => {
d.field("data", &&**err.get_ref());
}
Err(TryLockError::WouldBlock) => {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<locked>")
}
}
d.field("data", &LockedPlaceholder);
}
}
d.field("poisoned", &self.poison.get());
d.finish_non_exhaustive()
}
}
impl<'mutex, T:?Sized> MutexGuard<'mutex, T> {
unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard })
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.lock.data.get() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.lock.data.get() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Drop for MutexGuard<'_, T> {
#[inline]
fn drop(&mut self) {
unsafe {
self.lock.poison.done(&self.poison);
self.lock.inner.raw_unlock();
}
}
}
#[stable(feature = "std_debug", since = "1.16.0")]
impl<T:?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "std_guard_impls", since = "1.20.0")]
impl<T:?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
pub fn guard_lock<'a, T:?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::MovableMutex {
&guard.lock.inner
}
pub fn guard_poison<'a, T:?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
&guard.lock.poison
}
| {
d.field("data", &&*guard);
} | conditional_block |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
/// This mutex will block threads waiting for the lock to become available. The
/// mutex can also be statically initialized or created via a [`new`]
/// constructor. Each mutex has a type parameter which represents the data that
/// it is protecting. The data can only be accessed through the RAII guards
/// returned from [`lock`] and [`try_lock`], which guarantees that the data is only
/// ever accessed when the mutex is locked.
///
/// # Poisoning
///
/// The mutexes in this module implement a strategy called "poisoning" where a
/// mutex is considered poisoned whenever a thread panics while holding the
/// mutex. Once a mutex is poisoned, all other threads are unable to access the
/// data by default as it is likely tainted (some invariant is not being
/// upheld).
///
/// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a
/// [`Result`] which indicates whether a mutex has been poisoned or not. Most
/// usage of a mutex will simply [`unwrap()`] these results, propagating panics
/// among threads to ensure that a possibly invalid invariant is not witnessed.
///
/// A poisoned mutex, however, does not prevent all access to the underlying
/// data. The [`PoisonError`] type has an [`into_inner`] method which will return
/// the guard that would have otherwise been returned on a successful lock. This
/// allows access to the data, despite the lock being poisoned.
///
/// [`new`]: Self::new
/// [`lock`]: Self::lock
/// [`try_lock`]: Self::try_lock
/// [`unwrap()`]: Result::unwrap
/// [`PoisonError`]: super::PoisonError
/// [`into_inner`]: super::PoisonError::into_inner
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
/// use std::sync::mpsc::channel;
///
/// const N: usize = 10;
///
/// // Spawn a few threads to increment a shared variable (non-atomically), and
/// // let the main thread know once all increments are done.
/// //
/// // Here we're using an Arc to share memory among threads, and the data inside
/// // the Arc is protected with a mutex.
/// let data = Arc::new(Mutex::new(0));
///
/// let (tx, rx) = channel();
/// for _ in 0..N {
/// let (data, tx) = (Arc::clone(&data), tx.clone());
/// thread::spawn(move || {
/// // The shared state can only be accessed once the lock is held.
/// // Our non-atomic increment is safe because we're the only thread
/// // which can access the shared state when the lock is held.
/// //
/// // We unwrap() the return value to assert that we are not expecting
/// // threads to ever fail while holding the lock.
/// let mut data = data.lock().unwrap();
/// *data += 1;
/// if *data == N {
/// tx.send(()).unwrap();
/// }
/// // the lock is unlocked here when `data` goes out of scope.
/// });
/// }
///
/// rx.recv().unwrap();
/// ```
///
/// To recover from a poisoned mutex:
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let lock = Arc::new(Mutex::new(0_u32));
/// let lock2 = Arc::clone(&lock);
///
/// let _ = thread::spawn(move || -> () {
/// // This thread will acquire the mutex first, unwrapping the result of
/// // `lock` because the lock has not been poisoned.
/// let _guard = lock2.lock().unwrap();
///
/// // This panic while holding the lock (`_guard` is in scope) will poison
/// // the mutex.
/// panic!();
/// }).join();
///
/// // The lock is poisoned by this point, but the returned result can be
/// // pattern matched on to return the underlying guard on both branches.
/// let mut guard = match lock.lock() {
/// Ok(guard) => guard,
/// Err(poisoned) => poisoned.into_inner(),
/// };
///
/// *guard += 1;
/// ```
///
/// It is sometimes necessary to manually drop the mutex guard to unlock it
/// sooner than the end of the enclosing scope.
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// const N: usize = 3;
///
/// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
/// let res_mutex = Arc::new(Mutex::new(0));
///
/// let mut threads = Vec::with_capacity(N);
/// (0..N).for_each(|_| {
/// let data_mutex_clone = Arc::clone(&data_mutex);
/// let res_mutex_clone = Arc::clone(&res_mutex);
///
/// threads.push(thread::spawn(move || {
/// let mut data = data_mutex_clone.lock().unwrap();
/// // This is the result of some important and long-ish work.
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
/// data.push(result);
/// drop(data);
/// *res_mutex_clone.lock().unwrap() += result;
/// }));
/// });
///
/// let mut data = data_mutex.lock().unwrap();
/// // This is the result of some important and long-ish work.
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
/// data.push(result);
/// // We drop the `data` explicitly because it's not necessary anymore and the
/// // thread still has work to do. This allow other threads to start working on
/// // the data immediately, without waiting for the rest of the unrelated work
/// // to be done here.
/// //
/// // It's even more important here than in the threads because we `.join` the
/// // threads after that. If we had not dropped the mutex guard, a thread could
/// // be waiting forever for it, causing a deadlock.
/// drop(data);
/// // Here the mutex guard is not assigned to a variable and so, even if the
/// // scope does not end after this line, the mutex is still released: there is
/// // no deadlock.
/// *res_mutex.lock().unwrap() += result;
///
/// threads.into_iter().for_each(|thread| {
/// thread
/// .join()
/// .expect("The thread creating or execution failed!")
/// });
///
/// assert_eq!(*res_mutex.lock().unwrap(), 800);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "Mutex")]
pub struct Mutex<T:?Sized> {
inner: sys::MovableMutex,
poison: poison::Flag,
data: UnsafeCell<T>,
}
// these are the only places where `T: Send` matters; all other
// functionality works fine on a single thread.
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T:?Sized + Send> Send for Mutex<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T:?Sized + Send> Sync for Mutex<T> {}
/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// [`Deref`] and [`DerefMut`] implementations.
///
/// This structure is created by the [`lock`] and [`try_lock`] methods on
/// [`Mutex`].
///
/// [`lock`]: Mutex::lock
/// [`try_lock`]: Mutex::try_lock
#[must_use = "if unused the Mutex will immediately unlock"]
#[cfg_attr(
not(bootstrap),
must_not_suspend = "holding a MutexGuard across suspend \
points can cause deadlocks, delays, \
and cause Futures to not implement `Send`"
)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct MutexGuard<'a, T:?Sized + 'a> {
lock: &'a Mutex<T>,
poison: poison::Guard,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized>!Send for MutexGuard<'_, T> {}
#[stable(feature = "mutexguard", since = "1.19.0")]
unsafe impl<T:?Sized + Sync> Sync for MutexGuard<'_, T> {}
impl<T> Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mutex = Mutex::new(0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new(t: T) -> Mutex<T> {
Mutex {
inner: sys::MovableMutex::new(),
poison: poison::Flag::new(),
data: UnsafeCell::new(t),
}
}
}
impl<T:?Sized> Mutex<T> {
/// Acquires a mutex, blocking the current thread until it is able to do so.
///
/// This function will block the local thread until it is available to acquire
/// the mutex. Upon returning, the thread is the only thread with the lock
/// held. An RAII guard is returned to allow scoped unlock of the lock. When
/// the guard goes out of scope, the mutex will be unlocked.
///
/// The exact behavior on locking a mutex in the thread which already holds
/// the lock is left unspecified. However, this function will not return on
/// the second call (it might panic or deadlock, for example).
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error once the mutex is acquired.
///
/// # Panics
///
/// This function might panic when called if the lock is already held by
/// the current thread.
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// thread::spawn(move || {
/// *c_mutex.lock().unwrap() = 10;
/// }).join().expect("thread::spawn failed");
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
unsafe {
self.inner.raw_lock();
MutexGuard::new(self)
}
}
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then [`Err`] is returned.
/// Otherwise, an RAII guard is returned. The lock will be unlocked when the
/// guard is dropped.
///
/// This function does not block.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return the [`Poisoned`] error if the mutex would
/// otherwise be acquired.
///
/// If the mutex could not be acquired because it is already locked, then
/// this call will return the [`WouldBlock`] error.
///
/// [`Poisoned`]: TryLockError::Poisoned
/// [`WouldBlock`]: TryLockError::WouldBlock
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// thread::spawn(move || {
/// let mut lock = c_mutex.try_lock();
/// if let Ok(ref mut mutex) = lock {
/// **mutex = 10;
/// } else {
/// println!("try_lock failed");
/// }
/// }).join().expect("thread::spawn failed");
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
unsafe {
if self.inner.try_lock() {
Ok(MutexGuard::new(self)?)
} else {
Err(TryLockError::WouldBlock)
}
}
}
/// Immediately drops the guard, and consequently unlocks the mutex.
///
/// This function is equivalent to calling [`drop`] on the guard but is more self-documenting.
/// Alternately, the guard will be automatically dropped when it goes out of scope.
///
/// ```
/// #![feature(mutex_unlock)]
///
/// use std::sync::Mutex;
/// let mutex = Mutex::new(0);
///
/// let mut guard = mutex.lock().unwrap();
/// *guard += 20;
/// Mutex::unlock(guard);
/// ```
#[unstable(feature = "mutex_unlock", issue = "81872")]
pub fn unlock(guard: MutexGuard<'_, T>) {
drop(guard);
}
/// Determines whether the mutex is poisoned.
///
/// If another thread is active, the mutex can still become poisoned at any
/// time. You should not trust a `false` value for program correctness
/// without additional synchronization.
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// let _ = thread::spawn(move || {
/// let _lock = c_mutex.lock().unwrap();
/// panic!(); // the mutex gets poisoned
/// }).join();
/// assert_eq!(mutex.is_poisoned(), true);
/// ```
#[inline]
#[stable(feature = "sync_poison", since = "1.2.0")]
pub fn is_poisoned(&self) -> bool {
self.poison.get()
}
/// Consumes this mutex, returning the underlying data.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error instead.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mutex = Mutex::new(0);
/// assert_eq!(mutex.into_inner().unwrap(), 0);
/// ```
#[stable(feature = "mutex_into_inner", since = "1.6.0")]
pub fn into_inner(self) -> LockResult<T>
where
T: Sized,
{
let data = self.data.into_inner();
poison::map_result(self.poison.borrow(), |_| data)
}
/// Returns a mutable reference to the underlying data.
///
/// Since this call borrows the `Mutex` mutably, no actual locking needs to
/// take place -- the mutable borrow statically guarantees no locks exist.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error instead.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mut mutex = Mutex::new(0);
/// *mutex.get_mut().unwrap() = 10;
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "mutex_get_mut", since = "1.6.0")]
pub fn | (&mut self) -> LockResult<&mut T> {
let data = self.data.get_mut();
poison::map_result(self.poison.borrow(), |_| data)
}
}
#[stable(feature = "mutex_from", since = "1.24.0")]
impl<T> From<T> for Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
/// This is equivalent to [`Mutex::new`].
fn from(t: T) -> Self {
Mutex::new(t)
}
}
#[stable(feature = "mutex_default", since = "1.10.0")]
impl<T:?Sized + Default> Default for Mutex<T> {
/// Creates a `Mutex<T>`, with the `Default` value for T.
fn default() -> Mutex<T> {
Mutex::new(Default::default())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("Mutex");
match self.try_lock() {
Ok(guard) => {
d.field("data", &&*guard);
}
Err(TryLockError::Poisoned(err)) => {
d.field("data", &&**err.get_ref());
}
Err(TryLockError::WouldBlock) => {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<locked>")
}
}
d.field("data", &LockedPlaceholder);
}
}
d.field("poisoned", &self.poison.get());
d.finish_non_exhaustive()
}
}
impl<'mutex, T:?Sized> MutexGuard<'mutex, T> {
unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard })
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.lock.data.get() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.lock.data.get() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Drop for MutexGuard<'_, T> {
#[inline]
fn drop(&mut self) {
unsafe {
self.lock.poison.done(&self.poison);
self.lock.inner.raw_unlock();
}
}
}
#[stable(feature = "std_debug", since = "1.16.0")]
impl<T:?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "std_guard_impls", since = "1.20.0")]
impl<T:?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
pub fn guard_lock<'a, T:?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::MovableMutex {
&guard.lock.inner
}
pub fn guard_poison<'a, T:?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
&guard.lock.poison
}
| get_mut | identifier_name |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
/// This mutex will block threads waiting for the lock to become available. The
/// mutex can also be statically initialized or created via a [`new`]
/// constructor. Each mutex has a type parameter which represents the data that
/// it is protecting. The data can only be accessed through the RAII guards
/// returned from [`lock`] and [`try_lock`], which guarantees that the data is only
/// ever accessed when the mutex is locked.
///
/// # Poisoning
///
/// The mutexes in this module implement a strategy called "poisoning" where a
/// mutex is considered poisoned whenever a thread panics while holding the
/// mutex. Once a mutex is poisoned, all other threads are unable to access the
/// data by default as it is likely tainted (some invariant is not being
/// upheld).
///
/// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a
/// [`Result`] which indicates whether a mutex has been poisoned or not. Most
/// usage of a mutex will simply [`unwrap()`] these results, propagating panics
/// among threads to ensure that a possibly invalid invariant is not witnessed.
///
/// A poisoned mutex, however, does not prevent all access to the underlying
/// data. The [`PoisonError`] type has an [`into_inner`] method which will return
/// the guard that would have otherwise been returned on a successful lock. This
/// allows access to the data, despite the lock being poisoned.
///
/// [`new`]: Self::new
/// [`lock`]: Self::lock
/// [`try_lock`]: Self::try_lock
/// [`unwrap()`]: Result::unwrap
/// [`PoisonError`]: super::PoisonError
/// [`into_inner`]: super::PoisonError::into_inner
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
/// use std::sync::mpsc::channel;
///
/// const N: usize = 10;
///
/// // Spawn a few threads to increment a shared variable (non-atomically), and
/// // let the main thread know once all increments are done.
/// //
/// // Here we're using an Arc to share memory among threads, and the data inside
/// // the Arc is protected with a mutex.
/// let data = Arc::new(Mutex::new(0));
///
/// let (tx, rx) = channel();
/// for _ in 0..N {
/// let (data, tx) = (Arc::clone(&data), tx.clone());
/// thread::spawn(move || {
/// // The shared state can only be accessed once the lock is held.
/// // Our non-atomic increment is safe because we're the only thread
/// // which can access the shared state when the lock is held.
/// //
/// // We unwrap() the return value to assert that we are not expecting
/// // threads to ever fail while holding the lock.
/// let mut data = data.lock().unwrap();
/// *data += 1;
/// if *data == N {
/// tx.send(()).unwrap();
/// }
/// // the lock is unlocked here when `data` goes out of scope.
/// });
/// }
///
/// rx.recv().unwrap();
/// ```
///
/// To recover from a poisoned mutex:
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let lock = Arc::new(Mutex::new(0_u32));
/// let lock2 = Arc::clone(&lock);
///
/// let _ = thread::spawn(move || -> () {
/// // This thread will acquire the mutex first, unwrapping the result of
/// // `lock` because the lock has not been poisoned.
/// let _guard = lock2.lock().unwrap();
///
/// // This panic while holding the lock (`_guard` is in scope) will poison
/// // the mutex.
/// panic!();
/// }).join();
///
/// // The lock is poisoned by this point, but the returned result can be
/// // pattern matched on to return the underlying guard on both branches.
/// let mut guard = match lock.lock() {
/// Ok(guard) => guard,
/// Err(poisoned) => poisoned.into_inner(),
/// };
///
/// *guard += 1;
/// ```
///
/// It is sometimes necessary to manually drop the mutex guard to unlock it
/// sooner than the end of the enclosing scope.
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// const N: usize = 3;
///
/// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
/// let res_mutex = Arc::new(Mutex::new(0));
///
/// let mut threads = Vec::with_capacity(N);
/// (0..N).for_each(|_| {
/// let data_mutex_clone = Arc::clone(&data_mutex);
/// let res_mutex_clone = Arc::clone(&res_mutex);
///
/// threads.push(thread::spawn(move || {
/// let mut data = data_mutex_clone.lock().unwrap();
/// // This is the result of some important and long-ish work.
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
/// data.push(result);
/// drop(data);
/// *res_mutex_clone.lock().unwrap() += result;
/// }));
/// });
///
/// let mut data = data_mutex.lock().unwrap();
/// // This is the result of some important and long-ish work.
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
/// data.push(result);
/// // We drop the `data` explicitly because it's not necessary anymore and the
/// // thread still has work to do. This allow other threads to start working on
/// // the data immediately, without waiting for the rest of the unrelated work
/// // to be done here.
/// //
/// // It's even more important here than in the threads because we `.join` the
/// // threads after that. If we had not dropped the mutex guard, a thread could
/// // be waiting forever for it, causing a deadlock.
/// drop(data);
/// // Here the mutex guard is not assigned to a variable and so, even if the
/// // scope does not end after this line, the mutex is still released: there is
/// // no deadlock.
/// *res_mutex.lock().unwrap() += result;
///
/// threads.into_iter().for_each(|thread| {
/// thread
/// .join()
/// .expect("The thread creating or execution failed!")
/// });
///
/// assert_eq!(*res_mutex.lock().unwrap(), 800);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "Mutex")]
pub struct Mutex<T:?Sized> {
inner: sys::MovableMutex,
poison: poison::Flag,
data: UnsafeCell<T>,
}
// these are the only places where `T: Send` matters; all other
// functionality works fine on a single thread.
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T:?Sized + Send> Send for Mutex<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T:?Sized + Send> Sync for Mutex<T> {}
/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// [`Deref`] and [`DerefMut`] implementations.
///
/// This structure is created by the [`lock`] and [`try_lock`] methods on
/// [`Mutex`].
///
/// [`lock`]: Mutex::lock
/// [`try_lock`]: Mutex::try_lock
#[must_use = "if unused the Mutex will immediately unlock"]
#[cfg_attr(
not(bootstrap),
must_not_suspend = "holding a MutexGuard across suspend \
points can cause deadlocks, delays, \
and cause Futures to not implement `Send`"
)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct MutexGuard<'a, T:?Sized + 'a> {
lock: &'a Mutex<T>,
poison: poison::Guard,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized>!Send for MutexGuard<'_, T> {}
#[stable(feature = "mutexguard", since = "1.19.0")]
unsafe impl<T:?Sized + Sync> Sync for MutexGuard<'_, T> {}
impl<T> Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mutex = Mutex::new(0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new(t: T) -> Mutex<T> {
Mutex {
inner: sys::MovableMutex::new(),
poison: poison::Flag::new(),
data: UnsafeCell::new(t),
}
}
}
impl<T:?Sized> Mutex<T> {
/// Acquires a mutex, blocking the current thread until it is able to do so.
///
/// This function will block the local thread until it is available to acquire
/// the mutex. Upon returning, the thread is the only thread with the lock
/// held. An RAII guard is returned to allow scoped unlock of the lock. When
/// the guard goes out of scope, the mutex will be unlocked.
///
/// The exact behavior on locking a mutex in the thread which already holds
/// the lock is left unspecified. However, this function will not return on
/// the second call (it might panic or deadlock, for example).
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error once the mutex is acquired.
///
/// # Panics
///
/// This function might panic when called if the lock is already held by
/// the current thread.
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// thread::spawn(move || {
/// *c_mutex.lock().unwrap() = 10;
/// }).join().expect("thread::spawn failed");
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> |
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then [`Err`] is returned.
/// Otherwise, an RAII guard is returned. The lock will be unlocked when the
/// guard is dropped.
///
/// This function does not block.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return the [`Poisoned`] error if the mutex would
/// otherwise be acquired.
///
/// If the mutex could not be acquired because it is already locked, then
/// this call will return the [`WouldBlock`] error.
///
/// [`Poisoned`]: TryLockError::Poisoned
/// [`WouldBlock`]: TryLockError::WouldBlock
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// thread::spawn(move || {
/// let mut lock = c_mutex.try_lock();
/// if let Ok(ref mut mutex) = lock {
/// **mutex = 10;
/// } else {
/// println!("try_lock failed");
/// }
/// }).join().expect("thread::spawn failed");
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
unsafe {
if self.inner.try_lock() {
Ok(MutexGuard::new(self)?)
} else {
Err(TryLockError::WouldBlock)
}
}
}
/// Immediately drops the guard, and consequently unlocks the mutex.
///
/// This function is equivalent to calling [`drop`] on the guard but is more self-documenting.
/// Alternately, the guard will be automatically dropped when it goes out of scope.
///
/// ```
/// #![feature(mutex_unlock)]
///
/// use std::sync::Mutex;
/// let mutex = Mutex::new(0);
///
/// let mut guard = mutex.lock().unwrap();
/// *guard += 20;
/// Mutex::unlock(guard);
/// ```
#[unstable(feature = "mutex_unlock", issue = "81872")]
pub fn unlock(guard: MutexGuard<'_, T>) {
drop(guard);
}
/// Determines whether the mutex is poisoned.
///
/// If another thread is active, the mutex can still become poisoned at any
/// time. You should not trust a `false` value for program correctness
/// without additional synchronization.
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// let _ = thread::spawn(move || {
/// let _lock = c_mutex.lock().unwrap();
/// panic!(); // the mutex gets poisoned
/// }).join();
/// assert_eq!(mutex.is_poisoned(), true);
/// ```
#[inline]
#[stable(feature = "sync_poison", since = "1.2.0")]
pub fn is_poisoned(&self) -> bool {
self.poison.get()
}
/// Consumes this mutex, returning the underlying data.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error instead.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mutex = Mutex::new(0);
/// assert_eq!(mutex.into_inner().unwrap(), 0);
/// ```
#[stable(feature = "mutex_into_inner", since = "1.6.0")]
pub fn into_inner(self) -> LockResult<T>
where
T: Sized,
{
let data = self.data.into_inner();
poison::map_result(self.poison.borrow(), |_| data)
}
/// Returns a mutable reference to the underlying data.
///
/// Since this call borrows the `Mutex` mutably, no actual locking needs to
/// take place -- the mutable borrow statically guarantees no locks exist.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error instead.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mut mutex = Mutex::new(0);
/// *mutex.get_mut().unwrap() = 10;
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "mutex_get_mut", since = "1.6.0")]
pub fn get_mut(&mut self) -> LockResult<&mut T> {
let data = self.data.get_mut();
poison::map_result(self.poison.borrow(), |_| data)
}
}
#[stable(feature = "mutex_from", since = "1.24.0")]
impl<T> From<T> for Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
/// This is equivalent to [`Mutex::new`].
fn from(t: T) -> Self {
Mutex::new(t)
}
}
#[stable(feature = "mutex_default", since = "1.10.0")]
impl<T:?Sized + Default> Default for Mutex<T> {
/// Creates a `Mutex<T>`, with the `Default` value for T.
fn default() -> Mutex<T> {
Mutex::new(Default::default())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("Mutex");
match self.try_lock() {
Ok(guard) => {
d.field("data", &&*guard);
}
Err(TryLockError::Poisoned(err)) => {
d.field("data", &&**err.get_ref());
}
Err(TryLockError::WouldBlock) => {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<locked>")
}
}
d.field("data", &LockedPlaceholder);
}
}
d.field("poisoned", &self.poison.get());
d.finish_non_exhaustive()
}
}
impl<'mutex, T:?Sized> MutexGuard<'mutex, T> {
unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard })
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.lock.data.get() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.lock.data.get() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Drop for MutexGuard<'_, T> {
#[inline]
fn drop(&mut self) {
unsafe {
self.lock.poison.done(&self.poison);
self.lock.inner.raw_unlock();
}
}
}
#[stable(feature = "std_debug", since = "1.16.0")]
impl<T:?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "std_guard_impls", since = "1.20.0")]
impl<T:?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
pub fn guard_lock<'a, T:?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::MovableMutex {
&guard.lock.inner
}
pub fn guard_poison<'a, T:?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
&guard.lock.poison
}
| {
unsafe {
self.inner.raw_lock();
MutexGuard::new(self)
}
} | identifier_body |
mutex.rs | #[cfg(all(test, not(target_os = "emscripten")))]
mod tests;
use crate::cell::UnsafeCell;
use crate::fmt;
use crate::ops::{Deref, DerefMut};
use crate::sync::{poison, LockResult, TryLockError, TryLockResult};
use crate::sys_common::mutex as sys;
/// A mutual exclusion primitive useful for protecting shared data
///
/// This mutex will block threads waiting for the lock to become available. The
/// mutex can also be statically initialized or created via a [`new`]
/// constructor. Each mutex has a type parameter which represents the data that
/// it is protecting. The data can only be accessed through the RAII guards
/// returned from [`lock`] and [`try_lock`], which guarantees that the data is only
/// ever accessed when the mutex is locked.
///
/// # Poisoning
///
/// The mutexes in this module implement a strategy called "poisoning" where a
/// mutex is considered poisoned whenever a thread panics while holding the
/// mutex. Once a mutex is poisoned, all other threads are unable to access the
/// data by default as it is likely tainted (some invariant is not being
/// upheld).
///
/// For a mutex, this means that the [`lock`] and [`try_lock`] methods return a
/// [`Result`] which indicates whether a mutex has been poisoned or not. Most
/// usage of a mutex will simply [`unwrap()`] these results, propagating panics
/// among threads to ensure that a possibly invalid invariant is not witnessed.
///
/// A poisoned mutex, however, does not prevent all access to the underlying
/// data. The [`PoisonError`] type has an [`into_inner`] method which will return
/// the guard that would have otherwise been returned on a successful lock. This
/// allows access to the data, despite the lock being poisoned.
///
/// [`new`]: Self::new
/// [`lock`]: Self::lock
/// [`try_lock`]: Self::try_lock
/// [`unwrap()`]: Result::unwrap
/// [`PoisonError`]: super::PoisonError
/// [`into_inner`]: super::PoisonError::into_inner
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
/// use std::sync::mpsc::channel;
///
/// const N: usize = 10;
///
/// // Spawn a few threads to increment a shared variable (non-atomically), and
/// // let the main thread know once all increments are done.
/// //
/// // Here we're using an Arc to share memory among threads, and the data inside
/// // the Arc is protected with a mutex.
/// let data = Arc::new(Mutex::new(0));
///
/// let (tx, rx) = channel();
/// for _ in 0..N {
/// let (data, tx) = (Arc::clone(&data), tx.clone());
/// thread::spawn(move || {
/// // The shared state can only be accessed once the lock is held.
/// // Our non-atomic increment is safe because we're the only thread
/// // which can access the shared state when the lock is held.
/// //
/// // We unwrap() the return value to assert that we are not expecting
/// // threads to ever fail while holding the lock.
/// let mut data = data.lock().unwrap();
/// *data += 1;
/// if *data == N {
/// tx.send(()).unwrap();
/// }
/// // the lock is unlocked here when `data` goes out of scope.
/// });
/// }
///
/// rx.recv().unwrap();
/// ```
///
/// To recover from a poisoned mutex:
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let lock = Arc::new(Mutex::new(0_u32));
/// let lock2 = Arc::clone(&lock);
///
/// let _ = thread::spawn(move || -> () {
/// // This thread will acquire the mutex first, unwrapping the result of
/// // `lock` because the lock has not been poisoned.
/// let _guard = lock2.lock().unwrap();
///
/// // This panic while holding the lock (`_guard` is in scope) will poison
/// // the mutex.
/// panic!();
/// }).join();
///
/// // The lock is poisoned by this point, but the returned result can be
/// // pattern matched on to return the underlying guard on both branches.
/// let mut guard = match lock.lock() {
/// Ok(guard) => guard,
/// Err(poisoned) => poisoned.into_inner(),
/// };
///
/// *guard += 1;
/// ```
///
/// It is sometimes necessary to manually drop the mutex guard to unlock it
/// sooner than the end of the enclosing scope.
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// const N: usize = 3;
///
/// let data_mutex = Arc::new(Mutex::new(vec![1, 2, 3, 4]));
/// let res_mutex = Arc::new(Mutex::new(0));
///
/// let mut threads = Vec::with_capacity(N);
/// (0..N).for_each(|_| {
/// let data_mutex_clone = Arc::clone(&data_mutex);
/// let res_mutex_clone = Arc::clone(&res_mutex);
///
/// threads.push(thread::spawn(move || {
/// let mut data = data_mutex_clone.lock().unwrap();
/// // This is the result of some important and long-ish work.
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
/// data.push(result);
/// drop(data);
/// *res_mutex_clone.lock().unwrap() += result;
/// }));
/// });
///
/// let mut data = data_mutex.lock().unwrap();
/// // This is the result of some important and long-ish work.
/// let result = data.iter().fold(0, |acc, x| acc + x * 2);
/// data.push(result);
/// // We drop the `data` explicitly because it's not necessary anymore and the
/// // thread still has work to do. This allow other threads to start working on
/// // the data immediately, without waiting for the rest of the unrelated work
/// // to be done here.
/// //
/// // It's even more important here than in the threads because we `.join` the
/// // threads after that. If we had not dropped the mutex guard, a thread could
/// // be waiting forever for it, causing a deadlock.
/// drop(data);
/// // Here the mutex guard is not assigned to a variable and so, even if the
/// // scope does not end after this line, the mutex is still released: there is
/// // no deadlock.
/// *res_mutex.lock().unwrap() += result;
///
/// threads.into_iter().for_each(|thread| {
/// thread
/// .join()
/// .expect("The thread creating or execution failed!")
/// });
///
/// assert_eq!(*res_mutex.lock().unwrap(), 800);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[cfg_attr(not(test), rustc_diagnostic_item = "Mutex")]
pub struct Mutex<T:?Sized> {
inner: sys::MovableMutex,
poison: poison::Flag,
data: UnsafeCell<T>,
}
// these are the only places where `T: Send` matters; all other
// functionality works fine on a single thread.
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T:?Sized + Send> Send for Mutex<T> {}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T:?Sized + Send> Sync for Mutex<T> {}
/// An RAII implementation of a "scoped lock" of a mutex. When this structure is
/// dropped (falls out of scope), the lock will be unlocked.
///
/// The data protected by the mutex can be accessed through this guard via its
/// [`Deref`] and [`DerefMut`] implementations.
///
/// This structure is created by the [`lock`] and [`try_lock`] methods on
/// [`Mutex`].
///
/// [`lock`]: Mutex::lock
/// [`try_lock`]: Mutex::try_lock
#[must_use = "if unused the Mutex will immediately unlock"]
#[cfg_attr( | #[stable(feature = "rust1", since = "1.0.0")]
pub struct MutexGuard<'a, T:?Sized + 'a> {
lock: &'a Mutex<T>,
poison: poison::Guard,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized>!Send for MutexGuard<'_, T> {}
#[stable(feature = "mutexguard", since = "1.19.0")]
unsafe impl<T:?Sized + Sync> Sync for MutexGuard<'_, T> {}
impl<T> Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mutex = Mutex::new(0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new(t: T) -> Mutex<T> {
Mutex {
inner: sys::MovableMutex::new(),
poison: poison::Flag::new(),
data: UnsafeCell::new(t),
}
}
}
impl<T:?Sized> Mutex<T> {
/// Acquires a mutex, blocking the current thread until it is able to do so.
///
/// This function will block the local thread until it is available to acquire
/// the mutex. Upon returning, the thread is the only thread with the lock
/// held. An RAII guard is returned to allow scoped unlock of the lock. When
/// the guard goes out of scope, the mutex will be unlocked.
///
/// The exact behavior on locking a mutex in the thread which already holds
/// the lock is left unspecified. However, this function will not return on
/// the second call (it might panic or deadlock, for example).
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error once the mutex is acquired.
///
/// # Panics
///
/// This function might panic when called if the lock is already held by
/// the current thread.
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// thread::spawn(move || {
/// *c_mutex.lock().unwrap() = 10;
/// }).join().expect("thread::spawn failed");
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn lock(&self) -> LockResult<MutexGuard<'_, T>> {
unsafe {
self.inner.raw_lock();
MutexGuard::new(self)
}
}
/// Attempts to acquire this lock.
///
/// If the lock could not be acquired at this time, then [`Err`] is returned.
/// Otherwise, an RAII guard is returned. The lock will be unlocked when the
/// guard is dropped.
///
/// This function does not block.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return the [`Poisoned`] error if the mutex would
/// otherwise be acquired.
///
/// If the mutex could not be acquired because it is already locked, then
/// this call will return the [`WouldBlock`] error.
///
/// [`Poisoned`]: TryLockError::Poisoned
/// [`WouldBlock`]: TryLockError::WouldBlock
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// thread::spawn(move || {
/// let mut lock = c_mutex.try_lock();
/// if let Ok(ref mut mutex) = lock {
/// **mutex = 10;
/// } else {
/// println!("try_lock failed");
/// }
/// }).join().expect("thread::spawn failed");
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn try_lock(&self) -> TryLockResult<MutexGuard<'_, T>> {
unsafe {
if self.inner.try_lock() {
Ok(MutexGuard::new(self)?)
} else {
Err(TryLockError::WouldBlock)
}
}
}
/// Immediately drops the guard, and consequently unlocks the mutex.
///
/// This function is equivalent to calling [`drop`] on the guard but is more self-documenting.
/// Alternately, the guard will be automatically dropped when it goes out of scope.
///
/// ```
/// #![feature(mutex_unlock)]
///
/// use std::sync::Mutex;
/// let mutex = Mutex::new(0);
///
/// let mut guard = mutex.lock().unwrap();
/// *guard += 20;
/// Mutex::unlock(guard);
/// ```
#[unstable(feature = "mutex_unlock", issue = "81872")]
pub fn unlock(guard: MutexGuard<'_, T>) {
drop(guard);
}
/// Determines whether the mutex is poisoned.
///
/// If another thread is active, the mutex can still become poisoned at any
/// time. You should not trust a `false` value for program correctness
/// without additional synchronization.
///
/// # Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use std::thread;
///
/// let mutex = Arc::new(Mutex::new(0));
/// let c_mutex = Arc::clone(&mutex);
///
/// let _ = thread::spawn(move || {
/// let _lock = c_mutex.lock().unwrap();
/// panic!(); // the mutex gets poisoned
/// }).join();
/// assert_eq!(mutex.is_poisoned(), true);
/// ```
#[inline]
#[stable(feature = "sync_poison", since = "1.2.0")]
pub fn is_poisoned(&self) -> bool {
self.poison.get()
}
/// Consumes this mutex, returning the underlying data.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error instead.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mutex = Mutex::new(0);
/// assert_eq!(mutex.into_inner().unwrap(), 0);
/// ```
#[stable(feature = "mutex_into_inner", since = "1.6.0")]
pub fn into_inner(self) -> LockResult<T>
where
T: Sized,
{
let data = self.data.into_inner();
poison::map_result(self.poison.borrow(), |_| data)
}
/// Returns a mutable reference to the underlying data.
///
/// Since this call borrows the `Mutex` mutably, no actual locking needs to
/// take place -- the mutable borrow statically guarantees no locks exist.
///
/// # Errors
///
/// If another user of this mutex panicked while holding the mutex, then
/// this call will return an error instead.
///
/// # Examples
///
/// ```
/// use std::sync::Mutex;
///
/// let mut mutex = Mutex::new(0);
/// *mutex.get_mut().unwrap() = 10;
/// assert_eq!(*mutex.lock().unwrap(), 10);
/// ```
#[stable(feature = "mutex_get_mut", since = "1.6.0")]
pub fn get_mut(&mut self) -> LockResult<&mut T> {
let data = self.data.get_mut();
poison::map_result(self.poison.borrow(), |_| data)
}
}
#[stable(feature = "mutex_from", since = "1.24.0")]
impl<T> From<T> for Mutex<T> {
/// Creates a new mutex in an unlocked state ready for use.
/// This is equivalent to [`Mutex::new`].
fn from(t: T) -> Self {
Mutex::new(t)
}
}
#[stable(feature = "mutex_default", since = "1.10.0")]
impl<T:?Sized + Default> Default for Mutex<T> {
/// Creates a `Mutex<T>`, with the `Default` value for T.
fn default() -> Mutex<T> {
Mutex::new(Default::default())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + fmt::Debug> fmt::Debug for Mutex<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("Mutex");
match self.try_lock() {
Ok(guard) => {
d.field("data", &&*guard);
}
Err(TryLockError::Poisoned(err)) => {
d.field("data", &&**err.get_ref());
}
Err(TryLockError::WouldBlock) => {
struct LockedPlaceholder;
impl fmt::Debug for LockedPlaceholder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("<locked>")
}
}
d.field("data", &LockedPlaceholder);
}
}
d.field("poisoned", &self.poison.get());
d.finish_non_exhaustive()
}
}
impl<'mutex, T:?Sized> MutexGuard<'mutex, T> {
unsafe fn new(lock: &'mutex Mutex<T>) -> LockResult<MutexGuard<'mutex, T>> {
poison::map_result(lock.poison.borrow(), |guard| MutexGuard { lock, poison: guard })
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Deref for MutexGuard<'_, T> {
type Target = T;
fn deref(&self) -> &T {
unsafe { &*self.lock.data.get() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> DerefMut for MutexGuard<'_, T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { &mut *self.lock.data.get() }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized> Drop for MutexGuard<'_, T> {
#[inline]
fn drop(&mut self) {
unsafe {
self.lock.poison.done(&self.poison);
self.lock.inner.raw_unlock();
}
}
}
#[stable(feature = "std_debug", since = "1.16.0")]
impl<T:?Sized + fmt::Debug> fmt::Debug for MutexGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
#[stable(feature = "std_guard_impls", since = "1.20.0")]
impl<T:?Sized + fmt::Display> fmt::Display for MutexGuard<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
(**self).fmt(f)
}
}
pub fn guard_lock<'a, T:?Sized>(guard: &MutexGuard<'a, T>) -> &'a sys::MovableMutex {
&guard.lock.inner
}
pub fn guard_poison<'a, T:?Sized>(guard: &MutexGuard<'a, T>) -> &'a poison::Flag {
&guard.lock.poison
} | not(bootstrap),
must_not_suspend = "holding a MutexGuard across suspend \
points can cause deadlocks, delays, \
and cause Futures to not implement `Send`"
)] | random_line_split |
pretty.rs | // Pris -- A language for designing slides
// Copyright 2017 Ruud van Asseldonk
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3. A copy
// of the License is available in the root of the repository.
//! The string formatting primitives in `std::fmt` are not really suitable for
//! pretty-printing code, because they do not support indentation in a proper
//! way. This module provides an alternative abstraction for pretty printing
//! that automatically inserts indents after newlines. It also assumes that
//! printing cannot fail, which avoids clumsy error handling.
use std::fmt::Write;
use std::rc::Rc;
// The compiler is wrong, this function *is* used, from the macro at the end of
// this file. And that macro itself is also used, in tests.
#[allow(dead_code)]
pub fn print<P: Print>(content: P) -> String {
let mut f = Formatter::new();
f.print(content);
f.into_string()
}
pub trait Print {
fn print(&self, f: &mut Formatter);
}
pub struct Formatter {
target: String,
indent: u32,
}
impl<'a, P: Print> Print for &'a P {
fn print(&self, f: &mut Formatter) {
(*self).print(f);
}
}
impl<P: Print> Print for Box<P> {
fn print(&self, f: &mut Formatter) {
(**self).print(f);
}
}
impl<P: Print> Print for Rc<P> {
fn print(&self, f: &mut Formatter) {
(**self).print(f);
}
}
impl<'a> Print for &'a str {
fn print(&self, f: &mut Formatter) {
f.target.push_str(self);
}
}
impl Print for i32 {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Print for u32 {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Print for usize {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Print for f64 {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Formatter {
pub fn new() -> Formatter {
Formatter { target: String::new(), indent: 0 }
}
pub fn indent_more(&mut self) {
self.indent += 1;
}
pub fn indent_less(&mut self) |
pub fn print<P: Print>(&mut self, content: P) {
content.print(self);
}
pub fn println<P: Print>(&mut self, content: P) {
for _ in 0..self.indent * 2 {
self.target.push(' ');
}
self.print(content);
}
pub fn print_hex_byte(&mut self, content: u8) {
write!(&mut self.target, "{:2x}", content).unwrap();
}
pub fn into_string(self) -> String {
self.target
}
}
/// Assert that two values of type `P: Print` are equal.
///
/// This is similar to `assert_eq!`, but using `Print` rather than `fmt::Debug`.
#[macro_export]
macro_rules! assert_preq {
($left: expr, $right: expr) => {
{
use pretty;
let left = &$left;
let right = &$right;
assert!(left == right,
"\nExpected:\n\n{}\n\nBut found:\n\n{}\n\n",
pretty::print(right),
pretty::print(left));
}
}
}
| {
assert!(self.indent > 0);
self.indent -= 1;
} | identifier_body |
pretty.rs | // Pris -- A language for designing slides
// Copyright 2017 Ruud van Asseldonk
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3. A copy
// of the License is available in the root of the repository.
//! The string formatting primitives in `std::fmt` are not really suitable for
//! pretty-printing code, because they do not support indentation in a proper
//! way. This module provides an alternative abstraction for pretty printing
//! that automatically inserts indents after newlines. It also assumes that
//! printing cannot fail, which avoids clumsy error handling.
use std::fmt::Write;
use std::rc::Rc;
// The compiler is wrong, this function *is* used, from the macro at the end of
// this file. And that macro itself is also used, in tests.
#[allow(dead_code)]
pub fn print<P: Print>(content: P) -> String {
let mut f = Formatter::new();
f.print(content);
f.into_string()
}
pub trait Print {
fn print(&self, f: &mut Formatter);
}
pub struct Formatter {
target: String,
indent: u32,
}
impl<'a, P: Print> Print for &'a P {
fn print(&self, f: &mut Formatter) {
(*self).print(f);
}
}
impl<P: Print> Print for Box<P> {
fn print(&self, f: &mut Formatter) {
(**self).print(f);
}
}
impl<P: Print> Print for Rc<P> {
fn print(&self, f: &mut Formatter) {
(**self).print(f);
}
}
impl<'a> Print for &'a str {
fn print(&self, f: &mut Formatter) {
f.target.push_str(self);
}
}
impl Print for i32 {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Print for u32 { | write!(&mut f.target, "{}", self).unwrap();
}
}
impl Print for usize {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Print for f64 {
fn print(&self, f: &mut Formatter) {
write!(&mut f.target, "{}", self).unwrap();
}
}
impl Formatter {
pub fn new() -> Formatter {
Formatter { target: String::new(), indent: 0 }
}
pub fn indent_more(&mut self) {
self.indent += 1;
}
pub fn indent_less(&mut self) {
assert!(self.indent > 0);
self.indent -= 1;
}
pub fn print<P: Print>(&mut self, content: P) {
content.print(self);
}
pub fn println<P: Print>(&mut self, content: P) {
for _ in 0..self.indent * 2 {
self.target.push(' ');
}
self.print(content);
}
pub fn print_hex_byte(&mut self, content: u8) {
write!(&mut self.target, "{:2x}", content).unwrap();
}
pub fn into_string(self) -> String {
self.target
}
}
/// Assert that two values of type `P: Print` are equal.
///
/// This is similar to `assert_eq!`, but using `Print` rather than `fmt::Debug`.
#[macro_export]
macro_rules! assert_preq {
($left: expr, $right: expr) => {
{
use pretty;
let left = &$left;
let right = &$right;
assert!(left == right,
"\nExpected:\n\n{}\n\nBut found:\n\n{}\n\n",
pretty::print(right),
pretty::print(left));
}
}
} | fn print(&self, f: &mut Formatter) { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.