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 |
---|---|---|---|---|
estimate_pi.rs
|
// A very inefficient way to approximate PI using random number.
//
// with const N: u64 = 100_000_000_000;
// ~14mn
// pi ~= 3.14159183515999985
// error ~= 0.00000081842979327
extern crate pcgrng;
use std::f64;
fn main()
|
{
let mut rng = pcgrng::PCG32::seed(0, 0);
const N: u64 = 1_000_000;
let mut nb_inside = 0;
for _ in 0..N+1 {
let (x,y) = (rng.next_f64(), rng.next_f64());
let d = x*x + y*y; // check if randomly select point is inside the circle
nb_inside += (d < 1.0) as u64;
};
let pi_estimate = (4 * nb_inside) as f64 / (N as f64);
println!("pi ~= {:.17}", pi_estimate);
let error = (f64::consts::PI - pi_estimate).abs();
println!("error ~= {:.17}", error);
}
|
identifier_body
|
|
estimate_pi.rs
|
// A very inefficient way to approximate PI using random number.
//
// with const N: u64 = 100_000_000_000;
// ~14mn
// pi ~= 3.14159183515999985
// error ~= 0.00000081842979327
extern crate pcgrng;
use std::f64;
fn main() {
let mut rng = pcgrng::PCG32::seed(0, 0);
|
let (x,y) = (rng.next_f64(), rng.next_f64());
let d = x*x + y*y; // check if randomly select point is inside the circle
nb_inside += (d < 1.0) as u64;
};
let pi_estimate = (4 * nb_inside) as f64 / (N as f64);
println!("pi ~= {:.17}", pi_estimate);
let error = (f64::consts::PI - pi_estimate).abs();
println!("error ~= {:.17}", error);
}
|
const N: u64 = 1_000_000;
let mut nb_inside = 0;
for _ in 0..N+1 {
|
random_line_split
|
estimate_pi.rs
|
// A very inefficient way to approximate PI using random number.
//
// with const N: u64 = 100_000_000_000;
// ~14mn
// pi ~= 3.14159183515999985
// error ~= 0.00000081842979327
extern crate pcgrng;
use std::f64;
fn
|
() {
let mut rng = pcgrng::PCG32::seed(0, 0);
const N: u64 = 1_000_000;
let mut nb_inside = 0;
for _ in 0..N+1 {
let (x,y) = (rng.next_f64(), rng.next_f64());
let d = x*x + y*y; // check if randomly select point is inside the circle
nb_inside += (d < 1.0) as u64;
};
let pi_estimate = (4 * nb_inside) as f64 / (N as f64);
println!("pi ~= {:.17}", pi_estimate);
let error = (f64::consts::PI - pi_estimate).abs();
println!("error ~= {:.17}", error);
}
|
main
|
identifier_name
|
stack.rs
|
//! A lock-free stack which supports concurrent pushes and a concurrent call to
//! drain the entire stack all at once.
use std::prelude::v1::*;
use std::sync::atomic::AtomicUsize;
use std::mem;
use std::marker;
use std::sync::atomic::Ordering::SeqCst;
use task::EventSet;
pub struct Stack<T> {
head: AtomicUsize,
_marker: marker::PhantomData<T>,
}
struct Node<T> {
data: T,
next: *mut Node<T>,
}
pub struct Drain<T> {
head: *mut Node<T>,
}
impl<T> Stack<T> {
pub fn new() -> Stack<T> {
Stack {
head: AtomicUsize::new(0),
_marker: marker::PhantomData,
}
}
pub fn push(&self, data: T) {
let mut node = Box::new(Node { data: data, next: 0 as *mut _ });
let mut head = self.head.load(SeqCst);
loop {
node.next = head as *mut _;
let ptr = &*node as *const Node<T> as usize;
match self.head.compare_exchange(head, ptr, SeqCst, SeqCst) {
Ok(_) => {
mem::forget(node);
return
}
Err(cur) => head = cur,
}
}
}
pub fn drain(&self) -> Drain<T> {
Drain {
head: self.head.swap(0, SeqCst) as *mut _,
}
}
}
impl<T> Drop for Stack<T> {
fn drop(&mut self) {
self.drain();
}
}
impl<T> Iterator for Drain<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.head.is_null() {
return None
}
unsafe {
let node = Box::from_raw(self.head);
self.head = node.next;
return Some(node.data)
}
}
}
|
fn drop(&mut self) {
for item in self.by_ref() {
drop(item);
}
}
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
use std::rc::Rc;
use std::cell::Cell;
use super::Stack;
struct Set(Rc<Cell<usize>>, usize);
impl Drop for Set {
fn drop(&mut self) {
self.0.set(self.1);
}
}
#[test]
fn simple() {
let s = Stack::new();
s.push(1);
s.push(2);
s.push(4);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![4, 2, 1]);
s.push(5);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![5]);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![]);
}
#[test]
fn drain_drops() {
let data = Rc::new(Cell::new(0));
let s = Stack::new();
s.push(Set(data.clone(), 1));
drop(s.drain());
assert_eq!(data.get(), 1);
}
#[test]
fn drop_drops() {
let data = Rc::new(Cell::new(0));
let s = Stack::new();
s.push(Set(data.clone(), 1));
drop(s);
assert_eq!(data.get(), 1);
}
}
impl EventSet for Stack<usize> {
fn insert(&self, id: usize) {
self.push(id);
}
}
|
impl<T> Drop for Drain<T> {
|
random_line_split
|
stack.rs
|
//! A lock-free stack which supports concurrent pushes and a concurrent call to
//! drain the entire stack all at once.
use std::prelude::v1::*;
use std::sync::atomic::AtomicUsize;
use std::mem;
use std::marker;
use std::sync::atomic::Ordering::SeqCst;
use task::EventSet;
pub struct Stack<T> {
head: AtomicUsize,
_marker: marker::PhantomData<T>,
}
struct Node<T> {
data: T,
next: *mut Node<T>,
}
pub struct Drain<T> {
head: *mut Node<T>,
}
impl<T> Stack<T> {
pub fn new() -> Stack<T> {
Stack {
head: AtomicUsize::new(0),
_marker: marker::PhantomData,
}
}
pub fn push(&self, data: T) {
let mut node = Box::new(Node { data: data, next: 0 as *mut _ });
let mut head = self.head.load(SeqCst);
loop {
node.next = head as *mut _;
let ptr = &*node as *const Node<T> as usize;
match self.head.compare_exchange(head, ptr, SeqCst, SeqCst) {
Ok(_) => {
mem::forget(node);
return
}
Err(cur) => head = cur,
}
}
}
pub fn drain(&self) -> Drain<T> {
Drain {
head: self.head.swap(0, SeqCst) as *mut _,
}
}
}
impl<T> Drop for Stack<T> {
fn drop(&mut self) {
self.drain();
}
}
impl<T> Iterator for Drain<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.head.is_null()
|
unsafe {
let node = Box::from_raw(self.head);
self.head = node.next;
return Some(node.data)
}
}
}
impl<T> Drop for Drain<T> {
fn drop(&mut self) {
for item in self.by_ref() {
drop(item);
}
}
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
use std::rc::Rc;
use std::cell::Cell;
use super::Stack;
struct Set(Rc<Cell<usize>>, usize);
impl Drop for Set {
fn drop(&mut self) {
self.0.set(self.1);
}
}
#[test]
fn simple() {
let s = Stack::new();
s.push(1);
s.push(2);
s.push(4);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![4, 2, 1]);
s.push(5);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![5]);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![]);
}
#[test]
fn drain_drops() {
let data = Rc::new(Cell::new(0));
let s = Stack::new();
s.push(Set(data.clone(), 1));
drop(s.drain());
assert_eq!(data.get(), 1);
}
#[test]
fn drop_drops() {
let data = Rc::new(Cell::new(0));
let s = Stack::new();
s.push(Set(data.clone(), 1));
drop(s);
assert_eq!(data.get(), 1);
}
}
impl EventSet for Stack<usize> {
fn insert(&self, id: usize) {
self.push(id);
}
}
|
{
return None
}
|
conditional_block
|
stack.rs
|
//! A lock-free stack which supports concurrent pushes and a concurrent call to
//! drain the entire stack all at once.
use std::prelude::v1::*;
use std::sync::atomic::AtomicUsize;
use std::mem;
use std::marker;
use std::sync::atomic::Ordering::SeqCst;
use task::EventSet;
pub struct Stack<T> {
head: AtomicUsize,
_marker: marker::PhantomData<T>,
}
struct Node<T> {
data: T,
next: *mut Node<T>,
}
pub struct
|
<T> {
head: *mut Node<T>,
}
impl<T> Stack<T> {
pub fn new() -> Stack<T> {
Stack {
head: AtomicUsize::new(0),
_marker: marker::PhantomData,
}
}
pub fn push(&self, data: T) {
let mut node = Box::new(Node { data: data, next: 0 as *mut _ });
let mut head = self.head.load(SeqCst);
loop {
node.next = head as *mut _;
let ptr = &*node as *const Node<T> as usize;
match self.head.compare_exchange(head, ptr, SeqCst, SeqCst) {
Ok(_) => {
mem::forget(node);
return
}
Err(cur) => head = cur,
}
}
}
pub fn drain(&self) -> Drain<T> {
Drain {
head: self.head.swap(0, SeqCst) as *mut _,
}
}
}
impl<T> Drop for Stack<T> {
fn drop(&mut self) {
self.drain();
}
}
impl<T> Iterator for Drain<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.head.is_null() {
return None
}
unsafe {
let node = Box::from_raw(self.head);
self.head = node.next;
return Some(node.data)
}
}
}
impl<T> Drop for Drain<T> {
fn drop(&mut self) {
for item in self.by_ref() {
drop(item);
}
}
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
use std::rc::Rc;
use std::cell::Cell;
use super::Stack;
struct Set(Rc<Cell<usize>>, usize);
impl Drop for Set {
fn drop(&mut self) {
self.0.set(self.1);
}
}
#[test]
fn simple() {
let s = Stack::new();
s.push(1);
s.push(2);
s.push(4);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![4, 2, 1]);
s.push(5);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![5]);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![]);
}
#[test]
fn drain_drops() {
let data = Rc::new(Cell::new(0));
let s = Stack::new();
s.push(Set(data.clone(), 1));
drop(s.drain());
assert_eq!(data.get(), 1);
}
#[test]
fn drop_drops() {
let data = Rc::new(Cell::new(0));
let s = Stack::new();
s.push(Set(data.clone(), 1));
drop(s);
assert_eq!(data.get(), 1);
}
}
impl EventSet for Stack<usize> {
fn insert(&self, id: usize) {
self.push(id);
}
}
|
Drain
|
identifier_name
|
stack.rs
|
//! A lock-free stack which supports concurrent pushes and a concurrent call to
//! drain the entire stack all at once.
use std::prelude::v1::*;
use std::sync::atomic::AtomicUsize;
use std::mem;
use std::marker;
use std::sync::atomic::Ordering::SeqCst;
use task::EventSet;
pub struct Stack<T> {
head: AtomicUsize,
_marker: marker::PhantomData<T>,
}
struct Node<T> {
data: T,
next: *mut Node<T>,
}
pub struct Drain<T> {
head: *mut Node<T>,
}
impl<T> Stack<T> {
pub fn new() -> Stack<T> {
Stack {
head: AtomicUsize::new(0),
_marker: marker::PhantomData,
}
}
pub fn push(&self, data: T) {
let mut node = Box::new(Node { data: data, next: 0 as *mut _ });
let mut head = self.head.load(SeqCst);
loop {
node.next = head as *mut _;
let ptr = &*node as *const Node<T> as usize;
match self.head.compare_exchange(head, ptr, SeqCst, SeqCst) {
Ok(_) => {
mem::forget(node);
return
}
Err(cur) => head = cur,
}
}
}
pub fn drain(&self) -> Drain<T> {
Drain {
head: self.head.swap(0, SeqCst) as *mut _,
}
}
}
impl<T> Drop for Stack<T> {
fn drop(&mut self)
|
}
impl<T> Iterator for Drain<T> {
type Item = T;
fn next(&mut self) -> Option<T> {
if self.head.is_null() {
return None
}
unsafe {
let node = Box::from_raw(self.head);
self.head = node.next;
return Some(node.data)
}
}
}
impl<T> Drop for Drain<T> {
fn drop(&mut self) {
for item in self.by_ref() {
drop(item);
}
}
}
#[cfg(test)]
mod tests {
use std::prelude::v1::*;
use std::rc::Rc;
use std::cell::Cell;
use super::Stack;
struct Set(Rc<Cell<usize>>, usize);
impl Drop for Set {
fn drop(&mut self) {
self.0.set(self.1);
}
}
#[test]
fn simple() {
let s = Stack::new();
s.push(1);
s.push(2);
s.push(4);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![4, 2, 1]);
s.push(5);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![5]);
assert_eq!(s.drain().collect::<Vec<_>>(), vec![]);
}
#[test]
fn drain_drops() {
let data = Rc::new(Cell::new(0));
let s = Stack::new();
s.push(Set(data.clone(), 1));
drop(s.drain());
assert_eq!(data.get(), 1);
}
#[test]
fn drop_drops() {
let data = Rc::new(Cell::new(0));
let s = Stack::new();
s.push(Set(data.clone(), 1));
drop(s);
assert_eq!(data.get(), 1);
}
}
impl EventSet for Stack<usize> {
fn insert(&self, id: usize) {
self.push(id);
}
}
|
{
self.drain();
}
|
identifier_body
|
windowing.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/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use compositor_thread::{CompositorProxy, CompositorReceiver};
use euclid::{Point2D, Size2D};
use euclid::point::TypedPoint2D;
use euclid::rect::TypedRect;
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use gleam::gl;
use msg::constellation_msg::{Key, KeyModifiers, KeyState};
use net_traits::net_error_list::NetError;
use script_traits::{DevicePixel, MouseButton, TouchEventType, TouchId, TouchpadPressurePhase};
use servo_geometry::DeviceIndependentPixel;
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::rc::Rc;
use style_traits::cursor::Cursor;
use webrender_traits::ScrollLocation;
#[derive(Clone)]
pub enum MouseWindowEvent {
Click(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseDown(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseUp(MouseButton, TypedPoint2D<f32, DevicePixel>),
}
#[derive(Clone)]
pub enum
|
{
Forward,
Back,
}
/// Events that the windowing system sends to Servo.
#[derive(Clone)]
pub enum WindowEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem).
///
/// FIXME(pcwalton): This is kind of ugly and may not work well with multiprocess Servo.
/// It's possible that this should be something like
/// `CompositorMessageWindowEvent(compositor_thread::Msg)` instead.
Idle,
/// Sent when part of the window is marked dirty and needs to be redrawn. Before sending this
/// message, the window must make the same GL context as in `PrepareRenderingEvent` current.
Refresh,
/// Sent to initialize the GL context. The windowing system must have a valid, current GL
/// context when this message is sent.
InitializeCompositing,
/// Sent when the window is resized.
Resize(TypedSize2D<u32, DevicePixel>),
/// Touchpad Pressure
TouchpadPressure(TypedPoint2D<f32, DevicePixel>, f32, TouchpadPressurePhase),
/// Sent when you want to override the viewport.
Viewport(TypedPoint2D<u32, DevicePixel>, TypedSize2D<u32, DevicePixel>),
/// Sent when a new URL is to be loaded.
LoadUrl(String),
/// Sent when a mouse hit test is to be performed.
MouseWindowEventClass(MouseWindowEvent),
/// Sent when a mouse move.
MouseWindowMoveEventClass(TypedPoint2D<f32, DevicePixel>),
/// Touch event: type, identifier, point
Touch(TouchEventType, TouchId, TypedPoint2D<f32, DevicePixel>),
/// Sent when the user scrolls. The first point is the delta and the second point is the
/// origin.
Scroll(ScrollLocation, TypedPoint2D<i32, DevicePixel>, TouchEventType),
/// Sent when the user zooms.
Zoom(f32),
/// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel).
PinchZoom(f32),
/// Sent when the user resets zoom to default.
ResetZoom,
/// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace).
Navigation(WindowNavigateMsg),
/// Sent when the user quits the application
Quit,
/// Sent when a key input state changes
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Sent when Ctr+R/Apple+R is called to reload the current page.
Reload,
}
impl Debug for WindowEvent {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
WindowEvent::Idle => write!(f, "Idle"),
WindowEvent::Refresh => write!(f, "Refresh"),
WindowEvent::InitializeCompositing => write!(f, "InitializeCompositing"),
WindowEvent::Resize(..) => write!(f, "Resize"),
WindowEvent::TouchpadPressure(..) => write!(f, "TouchpadPressure"),
WindowEvent::Viewport(..) => write!(f, "Viewport"),
WindowEvent::KeyEvent(..) => write!(f, "Key"),
WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"),
WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"),
WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"),
WindowEvent::Touch(..) => write!(f, "Touch"),
WindowEvent::Scroll(..) => write!(f, "Scroll"),
WindowEvent::Zoom(..) => write!(f, "Zoom"),
WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"),
WindowEvent::ResetZoom => write!(f, "ResetZoom"),
WindowEvent::Navigation(..) => write!(f, "Navigation"),
WindowEvent::Quit => write!(f, "Quit"),
WindowEvent::Reload => write!(f, "Reload"),
}
}
}
pub trait WindowMethods {
/// Returns the rendering area size in hardware pixels.
fn framebuffer_size(&self) -> TypedSize2D<u32, DevicePixel>;
/// Returns the position and size of the window within the rendering area.
fn window_rect(&self) -> TypedRect<u32, DevicePixel>;
/// Returns the size of the window in density-independent "px" units.
fn size(&self) -> TypedSize2D<f32, DeviceIndependentPixel>;
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self);
/// Return the size of the window with head and borders and position of the window values
fn client_window(&self) -> (Size2D<u32>, Point2D<i32>);
/// Set the size inside of borders and head
fn set_inner_size(&self, size: Size2D<u32>);
/// Set the window position
fn set_position(&self, point: Point2D<i32>);
/// Set fullscreen state
fn set_fullscreen_state(&self, state: bool);
/// Sets the page title for the current page.
fn set_page_title(&self, title: Option<String>);
/// Sets the load data for the current page.
fn set_page_url(&self, url: ServoUrl);
/// Called when the browser chrome should display a status message.
fn status(&self, Option<String>);
/// Called when the browser has started loading a frame.
fn load_start(&self, back: bool, forward: bool);
/// Called when the browser is done loading a frame.
fn load_end(&self, back: bool, forward: bool, root: bool);
/// Called when the browser encounters an error while loading a URL
fn load_error(&self, code: NetError, url: String);
/// Wether or not to follow a link
fn allow_navigation(&self, url: ServoUrl) -> bool;
/// Called when the <head> tag has finished parsing
fn head_parsed(&self);
/// Returns the scale factor of the system (device pixels / device independent pixels).
fn hidpi_factor(&self) -> ScaleFactor<f32, DeviceIndependentPixel, DevicePixel>;
/// Creates a channel to the compositor. The dummy parameter is needed because we don't have
/// UFCS in Rust yet.
///
/// This is part of the windowing system because its implementation often involves OS-specific
/// magic to wake the up window's event loop.
fn create_compositor_channel(&self) -> (Box<CompositorProxy + Send>, Box<CompositorReceiver>);
/// Requests that the window system prepare a composite. Typically this will involve making
/// some type of platform-specific graphics context current. Returns true if the composite may
/// proceed and false if it should not.
fn prepare_for_composite(&self, width: usize, height: usize) -> bool;
/// Sets the cursor to be used in the window.
fn set_cursor(&self, cursor: Cursor);
/// Process a key event.
fn handle_key(&self, ch: Option<char>, key: Key, mods: KeyModifiers);
/// Does this window support a clipboard
fn supports_clipboard(&self) -> bool;
/// Add a favicon
fn set_favicon(&self, url: ServoUrl);
/// Return the GL function pointer trait.
fn gl(&self) -> Rc<gl::Gl>;
}
|
WindowNavigateMsg
|
identifier_name
|
windowing.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/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use compositor_thread::{CompositorProxy, CompositorReceiver};
use euclid::{Point2D, Size2D};
use euclid::point::TypedPoint2D;
use euclid::rect::TypedRect;
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use gleam::gl;
use msg::constellation_msg::{Key, KeyModifiers, KeyState};
use net_traits::net_error_list::NetError;
use script_traits::{DevicePixel, MouseButton, TouchEventType, TouchId, TouchpadPressurePhase};
use servo_geometry::DeviceIndependentPixel;
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::rc::Rc;
use style_traits::cursor::Cursor;
use webrender_traits::ScrollLocation;
#[derive(Clone)]
pub enum MouseWindowEvent {
Click(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseDown(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseUp(MouseButton, TypedPoint2D<f32, DevicePixel>),
}
#[derive(Clone)]
pub enum WindowNavigateMsg {
Forward,
Back,
}
/// Events that the windowing system sends to Servo.
#[derive(Clone)]
pub enum WindowEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem).
///
/// FIXME(pcwalton): This is kind of ugly and may not work well with multiprocess Servo.
/// It's possible that this should be something like
/// `CompositorMessageWindowEvent(compositor_thread::Msg)` instead.
Idle,
/// Sent when part of the window is marked dirty and needs to be redrawn. Before sending this
/// message, the window must make the same GL context as in `PrepareRenderingEvent` current.
Refresh,
/// Sent to initialize the GL context. The windowing system must have a valid, current GL
/// context when this message is sent.
InitializeCompositing,
/// Sent when the window is resized.
Resize(TypedSize2D<u32, DevicePixel>),
/// Touchpad Pressure
TouchpadPressure(TypedPoint2D<f32, DevicePixel>, f32, TouchpadPressurePhase),
/// Sent when you want to override the viewport.
Viewport(TypedPoint2D<u32, DevicePixel>, TypedSize2D<u32, DevicePixel>),
/// Sent when a new URL is to be loaded.
LoadUrl(String),
/// Sent when a mouse hit test is to be performed.
MouseWindowEventClass(MouseWindowEvent),
/// Sent when a mouse move.
MouseWindowMoveEventClass(TypedPoint2D<f32, DevicePixel>),
/// Touch event: type, identifier, point
Touch(TouchEventType, TouchId, TypedPoint2D<f32, DevicePixel>),
/// Sent when the user scrolls. The first point is the delta and the second point is the
/// origin.
Scroll(ScrollLocation, TypedPoint2D<i32, DevicePixel>, TouchEventType),
/// Sent when the user zooms.
Zoom(f32),
/// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel).
PinchZoom(f32),
/// Sent when the user resets zoom to default.
ResetZoom,
/// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace).
Navigation(WindowNavigateMsg),
/// Sent when the user quits the application
Quit,
/// Sent when a key input state changes
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Sent when Ctr+R/Apple+R is called to reload the current page.
Reload,
}
impl Debug for WindowEvent {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
WindowEvent::Idle => write!(f, "Idle"),
WindowEvent::Refresh => write!(f, "Refresh"),
WindowEvent::InitializeCompositing => write!(f, "InitializeCompositing"),
WindowEvent::Resize(..) => write!(f, "Resize"),
WindowEvent::TouchpadPressure(..) => write!(f, "TouchpadPressure"),
WindowEvent::Viewport(..) => write!(f, "Viewport"),
WindowEvent::KeyEvent(..) => write!(f, "Key"),
WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"),
WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"),
WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"),
WindowEvent::Touch(..) => write!(f, "Touch"),
WindowEvent::Scroll(..) => write!(f, "Scroll"),
WindowEvent::Zoom(..) => write!(f, "Zoom"),
WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"),
WindowEvent::ResetZoom => write!(f, "ResetZoom"),
WindowEvent::Navigation(..) => write!(f, "Navigation"),
WindowEvent::Quit => write!(f, "Quit"),
WindowEvent::Reload => write!(f, "Reload"),
}
}
}
pub trait WindowMethods {
/// Returns the rendering area size in hardware pixels.
fn framebuffer_size(&self) -> TypedSize2D<u32, DevicePixel>;
/// Returns the position and size of the window within the rendering area.
fn window_rect(&self) -> TypedRect<u32, DevicePixel>;
/// Returns the size of the window in density-independent "px" units.
fn size(&self) -> TypedSize2D<f32, DeviceIndependentPixel>;
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self);
/// Return the size of the window with head and borders and position of the window values
fn client_window(&self) -> (Size2D<u32>, Point2D<i32>);
/// Set the size inside of borders and head
fn set_inner_size(&self, size: Size2D<u32>);
/// Set the window position
fn set_position(&self, point: Point2D<i32>);
/// Set fullscreen state
fn set_fullscreen_state(&self, state: bool);
/// Sets the page title for the current page.
|
/// Sets the load data for the current page.
fn set_page_url(&self, url: ServoUrl);
/// Called when the browser chrome should display a status message.
fn status(&self, Option<String>);
/// Called when the browser has started loading a frame.
fn load_start(&self, back: bool, forward: bool);
/// Called when the browser is done loading a frame.
fn load_end(&self, back: bool, forward: bool, root: bool);
/// Called when the browser encounters an error while loading a URL
fn load_error(&self, code: NetError, url: String);
/// Wether or not to follow a link
fn allow_navigation(&self, url: ServoUrl) -> bool;
/// Called when the <head> tag has finished parsing
fn head_parsed(&self);
/// Returns the scale factor of the system (device pixels / device independent pixels).
fn hidpi_factor(&self) -> ScaleFactor<f32, DeviceIndependentPixel, DevicePixel>;
/// Creates a channel to the compositor. The dummy parameter is needed because we don't have
/// UFCS in Rust yet.
///
/// This is part of the windowing system because its implementation often involves OS-specific
/// magic to wake the up window's event loop.
fn create_compositor_channel(&self) -> (Box<CompositorProxy + Send>, Box<CompositorReceiver>);
/// Requests that the window system prepare a composite. Typically this will involve making
/// some type of platform-specific graphics context current. Returns true if the composite may
/// proceed and false if it should not.
fn prepare_for_composite(&self, width: usize, height: usize) -> bool;
/// Sets the cursor to be used in the window.
fn set_cursor(&self, cursor: Cursor);
/// Process a key event.
fn handle_key(&self, ch: Option<char>, key: Key, mods: KeyModifiers);
/// Does this window support a clipboard
fn supports_clipboard(&self) -> bool;
/// Add a favicon
fn set_favicon(&self, url: ServoUrl);
/// Return the GL function pointer trait.
fn gl(&self) -> Rc<gl::Gl>;
}
|
fn set_page_title(&self, title: Option<String>);
|
random_line_split
|
select_handler.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/. */
///
/// Implementation of the callbacks that the CSS selector engine uses to query the DOM.
///
use dom::node::AbstractNode;
use newcss::select::SelectHandler;
|
pub struct NodeSelectHandler {
node: AbstractNode
}
fn with_node_name<R>(node: AbstractNode, f: &fn(&str) -> R) -> R {
if!node.is_element() {
fail!(~"attempting to style non-element node");
}
do node.with_imm_element |element_n| {
f(element_n.tag_name)
}
}
impl SelectHandler<AbstractNode> for NodeSelectHandler {
fn with_node_name<R>(&self, node: &AbstractNode, f: &fn(&str) -> R) -> R {
with_node_name(*node, f)
}
fn named_parent_node(&self, node: &AbstractNode, name: &str) -> Option<AbstractNode> {
match node.parent_node() {
Some(parent) => {
do with_node_name(parent) |node_name| {
if eq_slice(name, node_name) {
Some(parent)
} else {
None
}
}
}
None => None
}
}
fn parent_node(&self, node: &AbstractNode) -> Option<AbstractNode> {
node.parent_node()
}
// TODO: Use a Bloom filter.
fn named_ancestor_node(&self, node: &AbstractNode, name: &str) -> Option<AbstractNode> {
let mut node = *node;
loop {
let parent = node.parent_node();
match parent {
Some(parent) => {
let mut found = false;
do with_node_name(parent) |node_name| {
if eq_slice(name, node_name) {
found = true;
}
}
if found {
return Some(parent);
}
node = parent;
}
None => return None
}
}
}
fn node_is_root(&self, node: &AbstractNode) -> bool {
self.parent_node(node).is_none()
}
fn with_node_id<R>(&self, node: &AbstractNode, f: &fn(Option<&str>) -> R) -> R {
if!node.is_element() {
fail!(~"attempting to style non-element node");
}
do node.with_imm_element() |element_n| {
f(element_n.get_attr("id"))
}
}
fn node_has_id(&self, node: &AbstractNode, id: &str) -> bool {
if!node.is_element() {
fail!(~"attempting to style non-element node");
}
do node.with_imm_element |element_n| {
match element_n.get_attr("id") {
None => false,
Some(existing_id) => id == existing_id
}
}
}
}
|
use core::str::eq_slice;
|
random_line_split
|
select_handler.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/. */
///
/// Implementation of the callbacks that the CSS selector engine uses to query the DOM.
///
use dom::node::AbstractNode;
use newcss::select::SelectHandler;
use core::str::eq_slice;
pub struct NodeSelectHandler {
node: AbstractNode
}
fn with_node_name<R>(node: AbstractNode, f: &fn(&str) -> R) -> R {
if!node.is_element() {
fail!(~"attempting to style non-element node");
}
do node.with_imm_element |element_n| {
f(element_n.tag_name)
}
}
impl SelectHandler<AbstractNode> for NodeSelectHandler {
fn with_node_name<R>(&self, node: &AbstractNode, f: &fn(&str) -> R) -> R {
with_node_name(*node, f)
}
fn
|
(&self, node: &AbstractNode, name: &str) -> Option<AbstractNode> {
match node.parent_node() {
Some(parent) => {
do with_node_name(parent) |node_name| {
if eq_slice(name, node_name) {
Some(parent)
} else {
None
}
}
}
None => None
}
}
fn parent_node(&self, node: &AbstractNode) -> Option<AbstractNode> {
node.parent_node()
}
// TODO: Use a Bloom filter.
fn named_ancestor_node(&self, node: &AbstractNode, name: &str) -> Option<AbstractNode> {
let mut node = *node;
loop {
let parent = node.parent_node();
match parent {
Some(parent) => {
let mut found = false;
do with_node_name(parent) |node_name| {
if eq_slice(name, node_name) {
found = true;
}
}
if found {
return Some(parent);
}
node = parent;
}
None => return None
}
}
}
fn node_is_root(&self, node: &AbstractNode) -> bool {
self.parent_node(node).is_none()
}
fn with_node_id<R>(&self, node: &AbstractNode, f: &fn(Option<&str>) -> R) -> R {
if!node.is_element() {
fail!(~"attempting to style non-element node");
}
do node.with_imm_element() |element_n| {
f(element_n.get_attr("id"))
}
}
fn node_has_id(&self, node: &AbstractNode, id: &str) -> bool {
if!node.is_element() {
fail!(~"attempting to style non-element node");
}
do node.with_imm_element |element_n| {
match element_n.get_attr("id") {
None => false,
Some(existing_id) => id == existing_id
}
}
}
}
|
named_parent_node
|
identifier_name
|
select_handler.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/. */
///
/// Implementation of the callbacks that the CSS selector engine uses to query the DOM.
///
use dom::node::AbstractNode;
use newcss::select::SelectHandler;
use core::str::eq_slice;
pub struct NodeSelectHandler {
node: AbstractNode
}
fn with_node_name<R>(node: AbstractNode, f: &fn(&str) -> R) -> R {
if!node.is_element() {
fail!(~"attempting to style non-element node");
}
do node.with_imm_element |element_n| {
f(element_n.tag_name)
}
}
impl SelectHandler<AbstractNode> for NodeSelectHandler {
fn with_node_name<R>(&self, node: &AbstractNode, f: &fn(&str) -> R) -> R {
with_node_name(*node, f)
}
fn named_parent_node(&self, node: &AbstractNode, name: &str) -> Option<AbstractNode> {
match node.parent_node() {
Some(parent) => {
do with_node_name(parent) |node_name| {
if eq_slice(name, node_name) {
Some(parent)
} else {
None
}
}
}
None => None
}
}
fn parent_node(&self, node: &AbstractNode) -> Option<AbstractNode>
|
// TODO: Use a Bloom filter.
fn named_ancestor_node(&self, node: &AbstractNode, name: &str) -> Option<AbstractNode> {
let mut node = *node;
loop {
let parent = node.parent_node();
match parent {
Some(parent) => {
let mut found = false;
do with_node_name(parent) |node_name| {
if eq_slice(name, node_name) {
found = true;
}
}
if found {
return Some(parent);
}
node = parent;
}
None => return None
}
}
}
fn node_is_root(&self, node: &AbstractNode) -> bool {
self.parent_node(node).is_none()
}
fn with_node_id<R>(&self, node: &AbstractNode, f: &fn(Option<&str>) -> R) -> R {
if!node.is_element() {
fail!(~"attempting to style non-element node");
}
do node.with_imm_element() |element_n| {
f(element_n.get_attr("id"))
}
}
fn node_has_id(&self, node: &AbstractNode, id: &str) -> bool {
if!node.is_element() {
fail!(~"attempting to style non-element node");
}
do node.with_imm_element |element_n| {
match element_n.get_attr("id") {
None => false,
Some(existing_id) => id == existing_id
}
}
}
}
|
{
node.parent_node()
}
|
identifier_body
|
json.rs
|
//! Experimental loader which takes a program specification in Json form.
use crate::architecture::*;
use crate::loader::*;
use crate::memory::backing::*;
use crate::memory::MemoryPermissions;
use serde_json::Value;
use std::fs::File;
use std::io::Read;
use std::path::Path;
/// Experimental loader which takes a program specification in Json form.
///
/// See the binary ninja script for an example use.
#[derive(Debug)]
pub struct Json {
function_entries: Vec<FunctionEntry>,
memory: Memory,
architecture: Box<dyn Architecture>,
entry: u64,
}
impl Json {
/// Create a new `Json` loader from the given file.
pub fn from_file(filename: &Path) -> Result<Json> {
let mut file = File::open(filename)?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
let root: Value = serde_json::from_str(&String::from_utf8(buf)?)?;
let architecture = match root["arch"] {
Value::String(ref architecture) => {
if architecture == "x86" {
Box::new(X86::new())
} else {
bail!("unsupported architecture {}", root["arch"])
}
}
_ => bail!("architecture missing"),
};
let entry = match root["entry"] {
Value::Number(ref number) => number.as_u64().unwrap(),
_ => bail!("entry missing"),
};
let mut function_entries = Vec::new();
if let Value::Array(ref functions) = root["functions"] {
for function in functions {
let address = match function["address"] {
Value::Number(ref address) => match address.as_u64() {
Some(address) => address,
None => bail!("function address not u64"),
},
_ => bail!("address missing for function"),
};
let name = match function["name"] {
Value::String(ref name) => name.to_string(),
_ => bail!("name missing for function"),
};
function_entries.push(FunctionEntry::new(address, Some(name)));
}
} else {
bail!("functions missing");
}
let mut memory = Memory::new(architecture.endian());
if let Value::Array(ref segments) = root["segments"] {
for segment in segments {
let address = match segment["address"] {
Value::Number(ref address) => match address.as_u64() {
Some(address) => address,
None => bail!("segment address not u64"),
},
_ => bail!("address missing for segment"),
};
let bytes = match segment["bytes"] {
Value::String(ref bytes) => base64::decode(&bytes)?,
_ => bail!("bytes missing for segment"),
};
memory.set_memory(address, bytes, MemoryPermissions::ALL);
}
} else {
bail!("segments missing");
}
Ok(Json {
function_entries,
memory,
architecture,
entry,
})
}
}
impl Loader for Json {
fn memory(&self) -> Result<Memory> {
Ok(self.memory.clone())
}
fn function_entries(&self) -> Result<Vec<FunctionEntry>> {
Ok(self.function_entries.clone())
}
fn program_entry(&self) -> u64 {
self.entry
}
fn architecture(&self) -> &dyn Architecture {
self.architecture.as_ref()
}
fn as_any(&self) -> &dyn Any {
self
}
fn symbols(&self) -> Vec<Symbol>
|
}
|
{
Vec::new()
}
|
identifier_body
|
json.rs
|
//! Experimental loader which takes a program specification in Json form.
use crate::architecture::*;
use crate::loader::*;
use crate::memory::backing::*;
use crate::memory::MemoryPermissions;
use serde_json::Value;
use std::fs::File;
use std::io::Read;
use std::path::Path;
/// Experimental loader which takes a program specification in Json form.
///
/// See the binary ninja script for an example use.
#[derive(Debug)]
pub struct Json {
function_entries: Vec<FunctionEntry>,
memory: Memory,
architecture: Box<dyn Architecture>,
entry: u64,
}
impl Json {
/// Create a new `Json` loader from the given file.
pub fn from_file(filename: &Path) -> Result<Json> {
let mut file = File::open(filename)?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
let root: Value = serde_json::from_str(&String::from_utf8(buf)?)?;
let architecture = match root["arch"] {
Value::String(ref architecture) => {
if architecture == "x86" {
Box::new(X86::new())
} else {
bail!("unsupported architecture {}", root["arch"])
}
}
_ => bail!("architecture missing"),
};
let entry = match root["entry"] {
Value::Number(ref number) => number.as_u64().unwrap(),
_ => bail!("entry missing"),
};
let mut function_entries = Vec::new();
if let Value::Array(ref functions) = root["functions"] {
for function in functions {
let address = match function["address"] {
Value::Number(ref address) => match address.as_u64() {
Some(address) => address,
None => bail!("function address not u64"),
},
_ => bail!("address missing for function"),
};
let name = match function["name"] {
Value::String(ref name) => name.to_string(),
_ => bail!("name missing for function"),
};
function_entries.push(FunctionEntry::new(address, Some(name)));
}
} else {
bail!("functions missing");
}
let mut memory = Memory::new(architecture.endian());
if let Value::Array(ref segments) = root["segments"] {
for segment in segments {
let address = match segment["address"] {
Value::Number(ref address) => match address.as_u64() {
Some(address) => address,
None => bail!("segment address not u64"),
},
_ => bail!("address missing for segment"),
};
let bytes = match segment["bytes"] {
Value::String(ref bytes) => base64::decode(&bytes)?,
_ => bail!("bytes missing for segment"),
};
memory.set_memory(address, bytes, MemoryPermissions::ALL);
}
} else {
bail!("segments missing");
}
Ok(Json {
function_entries,
memory,
architecture,
entry,
})
}
}
impl Loader for Json {
fn
|
(&self) -> Result<Memory> {
Ok(self.memory.clone())
}
fn function_entries(&self) -> Result<Vec<FunctionEntry>> {
Ok(self.function_entries.clone())
}
fn program_entry(&self) -> u64 {
self.entry
}
fn architecture(&self) -> &dyn Architecture {
self.architecture.as_ref()
}
fn as_any(&self) -> &dyn Any {
self
}
fn symbols(&self) -> Vec<Symbol> {
Vec::new()
}
}
|
memory
|
identifier_name
|
json.rs
|
//! Experimental loader which takes a program specification in Json form.
use crate::architecture::*;
use crate::loader::*;
use crate::memory::backing::*;
use crate::memory::MemoryPermissions;
use serde_json::Value;
use std::fs::File;
use std::io::Read;
use std::path::Path;
/// Experimental loader which takes a program specification in Json form.
///
/// See the binary ninja script for an example use.
#[derive(Debug)]
pub struct Json {
function_entries: Vec<FunctionEntry>,
memory: Memory,
architecture: Box<dyn Architecture>,
entry: u64,
}
impl Json {
/// Create a new `Json` loader from the given file.
pub fn from_file(filename: &Path) -> Result<Json> {
let mut file = File::open(filename)?;
let mut buf = Vec::new();
file.read_to_end(&mut buf)?;
let root: Value = serde_json::from_str(&String::from_utf8(buf)?)?;
let architecture = match root["arch"] {
Value::String(ref architecture) => {
if architecture == "x86" {
Box::new(X86::new())
} else {
bail!("unsupported architecture {}", root["arch"])
}
}
_ => bail!("architecture missing"),
};
let entry = match root["entry"] {
Value::Number(ref number) => number.as_u64().unwrap(),
_ => bail!("entry missing"),
};
let mut function_entries = Vec::new();
if let Value::Array(ref functions) = root["functions"] {
for function in functions {
let address = match function["address"] {
Value::Number(ref address) => match address.as_u64() {
Some(address) => address,
None => bail!("function address not u64"),
},
_ => bail!("address missing for function"),
};
let name = match function["name"] {
Value::String(ref name) => name.to_string(),
_ => bail!("name missing for function"),
};
|
function_entries.push(FunctionEntry::new(address, Some(name)));
}
} else {
bail!("functions missing");
}
let mut memory = Memory::new(architecture.endian());
if let Value::Array(ref segments) = root["segments"] {
for segment in segments {
let address = match segment["address"] {
Value::Number(ref address) => match address.as_u64() {
Some(address) => address,
None => bail!("segment address not u64"),
},
_ => bail!("address missing for segment"),
};
let bytes = match segment["bytes"] {
Value::String(ref bytes) => base64::decode(&bytes)?,
_ => bail!("bytes missing for segment"),
};
memory.set_memory(address, bytes, MemoryPermissions::ALL);
}
} else {
bail!("segments missing");
}
Ok(Json {
function_entries,
memory,
architecture,
entry,
})
}
}
impl Loader for Json {
fn memory(&self) -> Result<Memory> {
Ok(self.memory.clone())
}
fn function_entries(&self) -> Result<Vec<FunctionEntry>> {
Ok(self.function_entries.clone())
}
fn program_entry(&self) -> u64 {
self.entry
}
fn architecture(&self) -> &dyn Architecture {
self.architecture.as_ref()
}
fn as_any(&self) -> &dyn Any {
self
}
fn symbols(&self) -> Vec<Symbol> {
Vec::new()
}
}
|
random_line_split
|
|
test.rs
|
use common;
use token;
use sourcefile;
use assembler::definition as definition_assembler;
#[test]
fn empty() {
assert("test_code/roo/definition/Empty.roo", "test_code/java/definition/Empty.java");
}
#[test]
fn record() {
assert("test_code/roo/definition/Record.roo", "test_code/java/definition/Record.java");
}
fn assert(roo_file: &str, java_file: &str) {
let tokens = token::tokenize_string(common::read_file(roo_file), roo_file.to_string());
let sourecfile_result = sourcefile::get_sourcefile(&tokens, 0);
match sourecfile_result {
Err(e) => panic!("expecting definition result to be valid, got {}", e.error_message()),
Ok(sourcefile) => {
let output = definition_assembler::compile(&sourcefile.defs[0], &sourcefile.package);
assert_output(output, java_file);
}
|
}
}
fn assert_output(output: String, file: &str) {
let code = common::read_file(file);
assert!(output == code, "expecting compiled code to be \n'{}'\n, got \n'{}'\n", code, output);
}
|
random_line_split
|
|
test.rs
|
use common;
use token;
use sourcefile;
use assembler::definition as definition_assembler;
#[test]
fn empty() {
assert("test_code/roo/definition/Empty.roo", "test_code/java/definition/Empty.java");
}
#[test]
fn record() {
assert("test_code/roo/definition/Record.roo", "test_code/java/definition/Record.java");
}
fn
|
(roo_file: &str, java_file: &str) {
let tokens = token::tokenize_string(common::read_file(roo_file), roo_file.to_string());
let sourecfile_result = sourcefile::get_sourcefile(&tokens, 0);
match sourecfile_result {
Err(e) => panic!("expecting definition result to be valid, got {}", e.error_message()),
Ok(sourcefile) => {
let output = definition_assembler::compile(&sourcefile.defs[0], &sourcefile.package);
assert_output(output, java_file);
}
}
}
fn assert_output(output: String, file: &str) {
let code = common::read_file(file);
assert!(output == code, "expecting compiled code to be \n'{}'\n, got \n'{}'\n", code, output);
}
|
assert
|
identifier_name
|
test.rs
|
use common;
use token;
use sourcefile;
use assembler::definition as definition_assembler;
#[test]
fn empty() {
assert("test_code/roo/definition/Empty.roo", "test_code/java/definition/Empty.java");
}
#[test]
fn record() {
assert("test_code/roo/definition/Record.roo", "test_code/java/definition/Record.java");
}
fn assert(roo_file: &str, java_file: &str)
|
fn assert_output(output: String, file: &str) {
let code = common::read_file(file);
assert!(output == code, "expecting compiled code to be \n'{}'\n, got \n'{}'\n", code, output);
}
|
{
let tokens = token::tokenize_string(common::read_file(roo_file), roo_file.to_string());
let sourecfile_result = sourcefile::get_sourcefile(&tokens, 0);
match sourecfile_result {
Err(e) => panic!("expecting definition result to be valid, got {}", e.error_message()),
Ok(sourcefile) => {
let output = definition_assembler::compile(&sourcefile.defs[0], &sourcefile.package);
assert_output(output, java_file);
}
}
}
|
identifier_body
|
request.rs
|
//! DNS requests: the bridge between query and transport.
//!
//! While the future of the `Query` can be driven by any task, the network
//! transports are spawned into a reactor core each as a task of their own.
//! Requests and responses are exchanged between them using futures’s sync
//! primitives. Each transport holds the receiving end of an unbounded MPSC
//! channel for requests (defined as a type alias `RequestReceiver` herein),
//! with the sending end wrapped into the `TransportHandle` type and stored
//! in the `Resolver` for use by `Query`s.
//!
//! The query takes this transport handle and a `RequestMessage` (a light
//! wrapper around a DNS message ensuring that it is of the expected format)
//! and creates the query side of a request, aptly named `QueryRequest`. It
//! is a future resolving into either a response and the original request
//! message or an error and the very same request message.
//!
//! The reason for handing back the request message is that we can then
//! reuse it for further requests. Since we internally store DNS messages in
//! wire-format, anyway, they can be used as the send buffer directly and
//! reuse does make sense.
//!
//! The request sent over the channel is a `TransportRequest`. It consists
//! of the actual message now in the disguise of a `TransportMessage`
//! providing what the transport needs and the sending end of a oneshot
//! channel into which the transport is supposed to throw the response to
//! the request.
//!
//! The receiving end of the oneshot is part of the query request which polls
//! it for its completion.
//!
//! Note that timeouts happen on the transport side. While this is a little
//! less robust that we’d like, timeouts are tokio-core thing and need a
//! reactor. This way, we also potentially need fewer timeouts of lots of
//! requests are in flight.
use std::{fmt, io, ops};
use futures::{Async, Future, Poll};
use futures::sync::{mpsc, oneshot, BiLock, BiLockGuard};
use ::bits::{AdditionalBuilder, ComposeMode, ComposeResult, DName,
Message, MessageBuf, MessageBuilder, Question};
use super::conf::ResolvConf;
use super::error::Error;
//============ The Path of a Message Through a Request =======================
//------------ RequestMessage ------------------------------------------------
/// The DNS message for input into a request.
///
/// The wrapped message is a message builder in stream mode. It consists of
/// exactly one question which is why compression is unnecessary and turned
/// off. It also has been advanced into a additional section builder. This
/// allows transports to add their EDNS0 information and, once they are done
/// with that, rewind their additions for reuse.
///
/// The only thing you can do with a request message is turn them into a
/// transport message using the `into_service()` method.
pub struct RequestMessage(AdditionalBuilder);
impl RequestMessage {
/// Creates a new request message from a question and resolver config.
///
/// This may fail if the domain name of the question isn’t absolute.
pub fn new<N, Q>(question: Q, conf: &ResolvConf) -> ComposeResult<Self>
where N: DName,
Q: Into<Question<N>> {
let mut msg = MessageBuilder::new(ComposeMode::Stream, false)?;
msg.header_mut().set_rd(conf.options.recurse);
msg.push(question)?;
Ok(RequestMessage(msg.additional()))
}
/// Converts the request message into a transport message.
///
/// This method returns the transport message wrapped into a pair of
/// bi-locks. See `TransportMessage` for a discussion as to why that
/// is useful.
fn into_service(self) -> (BiLock<Option<TransportMessage>>,
BiLock<Option<TransportMessage>>) {
BiLock::new(Some(TransportMessage(self.0)))
}
}
//------------ TransportMessage ----------------------------------------------
/// The DNS message passed to and used by the service.
///
/// This is a DNS request with exactly one question. The transport can add
/// its EDNS0 information to it and then access the message bytes for
/// sending. Once done, the transport message can be returned into a
/// request message by dropping all EDNS0 information thus making it ready
/// for reuse by the next transport.
///
/// *Note:* EDNS0 is not yet implemented.
///
/// Transport messages are always kept wrapped into a pair of bi-locks. One
/// of those locks goes into the transport request for use by the transport,
/// the other one is kept by the query request. This way, we don’t need to
/// pass the message back when the transport is done which makes a lot easier
/// to treat all these cases where values along the way are dropped. In order
/// to allow the message being taken out of the lock, the lock’s content is
/// an option.
///
/// The rule is simple, violation will result in panics (but everything is
/// wrapped in `QueryRequest` and `TransportRequest` herein): The locks are
/// created with `Some` message. As long as the oneshot of the query request
/// has not been resolved, either successfully or by the sending end being
/// dropped, the transport has exclusive access to the message. It must,
/// however, not `take()` out the message. By resolving the oneshot, access
/// is transferred back to the query request. It then can `take()` out the
/// message.
pub struct TransportM
|
lBuilder);
impl TransportMessage {
/// Sets the message ID to the given value.
pub fn set_id(&mut self, id: u16) {
self.0.header_mut().set_id(id)
}
/// Checks whether `answer` is an answer to this message.
pub fn is_answer(&self, answer: &Message) -> bool {
answer.is_answer(&self.0)
}
/// Trades in this transport message for a request message.
///
/// This rewinds all additions made to the message since creation but
/// leaves the ID in place.
pub fn rewind(self) -> RequestMessage {
RequestMessage(self.0)
}
/// Returns a bytes slice with the data to be sent over stream transports.
pub fn stream_bytes(&mut self) -> &[u8] {
self.0.preview()
}
/// Returns a bytes slice for sending over datagram transports.
pub fn dgram_bytes(&mut self) -> &[u8] {
&self.0.preview()[2..]
}
}
//------------ TransportMessageGuard -----------------------------------------
/// A RAII guard for a locked transport message.
///
/// This implements both `Deref` and `DerefMut` into the underlying, locked
/// transport message. Once the value is dropped, the lock is released.
pub struct TransportMessageGuard<'a>(
BiLockGuard<'a, Option<TransportMessage>>
);
//--- Deref, DerefMut
impl<'a> ops::Deref for TransportMessageGuard<'a> {
type Target = TransportMessage;
fn deref(&self) -> &TransportMessage {
self.0.deref().as_ref().expect("message already taken")
}
}
impl<'a> ops::DerefMut for TransportMessageGuard<'a> {
fn deref_mut(&mut self) -> &mut TransportMessage {
self.0.deref_mut().as_mut().expect("message alread taken")
}
}
//------------ TransportResult -----------------------------------------------
/// The result returned by the transport.
///
/// This is the item type of the oneshot channel between transport request and
/// query request.
type TransportResult = Result<MessageBuf, Error>;
//============ The Query Side of a Request ===================================
//------------ QueryRequest --------------------------------------------------
/// The query side of a request.
///
/// This type is used by `Query` to dispatch and wait for requests. It is a
/// future resolving either into a both the response and request message or
/// an error and the request message.
pub struct QueryRequest {
/// The reading end of the oneshot channel for the reponse.
rx: Option<oneshot::Receiver<TransportResult>>,
/// Our side of the bi-locked transport message.
msg: BiLock<Option<TransportMessage>>,
}
impl QueryRequest {
/// Creates a new query request.
///
/// The request will attempt to answer `message` using the transport
/// referenced by `transport`.
pub fn new(message: RequestMessage, transport: &TransportHandle) -> Self {
let (tx, rx) = oneshot::channel();
let (smsg, qmsg) = message.into_service();
let sreq = TransportRequest::new(smsg, tx);
let rx = transport.send(sreq).ok().map(|_| rx);
QueryRequest {
rx: rx,
msg: qmsg
}
}
}
//--- Future
impl Future for QueryRequest {
type Item = (MessageBuf, RequestMessage);
type Error = (Error, RequestMessage);
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.rx {
Some(ref mut rx) => {
match rx.poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(response)) => {
let msg = into_message(&mut self.msg);
match response {
Ok(response) => Ok(Async::Ready((response, msg))),
Err(err) => Err((err, msg)),
}
}
Err(_) => {
// The transport disappeared. Let’s do a connection
// aborted error even if that isn’t quite right for
// UDP.
let msg = into_message(&mut self.msg);
Err((Error::Io(
io::Error::new(
io::ErrorKind::ConnectionAborted,
"transport disappeared")),
msg))
}
}
}
None => {
let msg = into_message(&mut self.msg);
Err((Error::Io(
io::Error::new(io::ErrorKind::ConnectionAborted,
"service disappeared")),
msg))
}
}
}
}
/// Helper function for unwrapping the transport message.
///
/// The function will take the transport message out of the lock if and only
/// if it can do so without blocking, panicing otherwise. See
/// `TransportMessage` for the rules when this is allowed.
fn into_message(msg: &mut BiLock<Option<TransportMessage>>) -> RequestMessage {
match msg.poll_lock() {
Async::Ready(ref mut msg) => {
match msg.take() {
Some(msg) => msg.rewind(),
None => panic!("called poll on a resolved QueryRequest"),
}
}
Async::NotReady => panic!("service kept message locked"),
}
}
//============ The Transport Side of a Request ===============================
//------------ TransportRequest ----------------------------------------------
/// The transport side of a request.
///
/// This type is used by a transport to try and discover the answer to a DNS
/// request. It contains both the message for this request and the sending
/// end of a oneshot channel to deliver the result to.
///
/// The transport requesst can safely be dropped at any time. However, it is
/// always better to resolve it with a specific error, allowing the query to
/// decide on its strategy based on this error instead of having to guess.
pub struct TransportRequest {
/// The request message behind a bi-lock.
message: BiLock<Option<TransportMessage>>,
/// The sending side of a oneshot channel for the result of the request.
complete: oneshot::Sender<TransportResult>,
/// The message ID of the request message.
///
/// This is initially `None` to indicate that it hasn’t been set for this
/// particular iteration yet.
id: Option<u16>,
}
impl TransportRequest {
/// Creates a new transport request from its components.
fn new(message: BiLock<Option<TransportMessage>>,
complete: oneshot::Sender<TransportResult>)
-> Self {
TransportRequest {
message: message,
complete: complete,
id: None
}
}
/// Provides access to the transport message.
///
/// Access happens in the form of a RAII guard that locks the message
/// while being alive.
///
/// # Panics
///
/// Panics if the message has been taken out of the lock. This should
/// not happen while the transport request is alive. Hence the panic.
pub fn message(&self) -> TransportMessageGuard {
if let Async::Ready(guard) = self.message.poll_lock() {
TransportMessageGuard(guard)
}
else {
panic!("message not ready");
}
}
/// Returns the request message’s ID or `None` if it hasn’t been set yet.
pub fn id(&self) -> Option<u16> {
self.id
}
/// Sets the request message’s ID to the given value.
pub fn set_id(&mut self, id: u16) {
self.id = Some(id);
self.message().set_id(id)
}
/// Completes the request with the given result.
pub fn complete(self, result: TransportResult) {
// Drop the message’s lock before completing as per the rules for
// transport messages.
let complete = self.complete;
drop(self.message);
complete.send(result).ok();
}
/// Completes the request with a response message.
///
/// This will produce a successful result only if `response` actually is
/// an answer to the request message. Else drops the message and produces
/// an error.
pub fn response(self, response: MessageBuf) {
if self.message().is_answer(&response) {
self.complete(Ok(response))
}
else {
self.fail(io::Error::new(io::ErrorKind::Other, "server failure")
.into())
}
}
/// Completes the request with the given error.
pub fn fail(self, err: Error) {
self.complete(Err(err))
}
/// Completes the request with a timeout error.
pub fn timeout(self) {
self.complete(Err(Error::Timeout))
}
}
//------------ TransportHandle -----------------------------------------------
/// A handle for communicating with a transport.
///
/// You can use this handle to send requests to the transport via the `send()`
/// method.
#[derive(Clone)]
pub struct TransportHandle {
/// The sending end of the transport’s request queue
tx: mpsc::UnboundedSender<TransportRequest>,
}
impl TransportHandle {
/// Creates a new request channel, returning both ends.
pub fn channel() -> (TransportHandle, RequestReceiver) {
let (tx, rx) = mpsc::unbounded();
(TransportHandle::from_sender(tx), rx)
}
/// Creates a new handle from the sender side of an MPCS channel.
pub fn from_sender(tx: mpsc::UnboundedSender<TransportRequest>) -> Self {
TransportHandle {
tx: tx
}
}
/// Sends a transport request to the transport.
///
/// This only fails if the receiver was dropped.
#[allow(deprecated)]
pub fn send(&self, sreq: TransportRequest)
-> Result<(), mpsc::SendError<TransportRequest>> {
self.tx.send(sreq)
}
}
//--- Debug
impl fmt::Debug for TransportHandle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TransportHandle{{...}}")
}
}
//------------ RequestReceiver -----------------------------------------------
/// The type of the receiving end of the request channel.
pub type RequestReceiver = mpsc::UnboundedReceiver<TransportRequest>;
|
essage(Additiona
|
identifier_name
|
request.rs
|
//! DNS requests: the bridge between query and transport.
//!
//! While the future of the `Query` can be driven by any task, the network
//! transports are spawned into a reactor core each as a task of their own.
//! Requests and responses are exchanged between them using futures’s sync
//! primitives. Each transport holds the receiving end of an unbounded MPSC
//! channel for requests (defined as a type alias `RequestReceiver` herein),
//! with the sending end wrapped into the `TransportHandle` type and stored
//! in the `Resolver` for use by `Query`s.
//!
//! The query takes this transport handle and a `RequestMessage` (a light
//! wrapper around a DNS message ensuring that it is of the expected format)
//! and creates the query side of a request, aptly named `QueryRequest`. It
//! is a future resolving into either a response and the original request
//! message or an error and the very same request message.
//!
//! The reason for handing back the request message is that we can then
//! reuse it for further requests. Since we internally store DNS messages in
//! wire-format, anyway, they can be used as the send buffer directly and
//! reuse does make sense.
//!
//! The request sent over the channel is a `TransportRequest`. It consists
//! of the actual message now in the disguise of a `TransportMessage`
//! providing what the transport needs and the sending end of a oneshot
//! channel into which the transport is supposed to throw the response to
//! the request.
//!
//! The receiving end of the oneshot is part of the query request which polls
//! it for its completion.
//!
//! Note that timeouts happen on the transport side. While this is a little
//! less robust that we’d like, timeouts are tokio-core thing and need a
//! reactor. This way, we also potentially need fewer timeouts of lots of
//! requests are in flight.
use std::{fmt, io, ops};
use futures::{Async, Future, Poll};
use futures::sync::{mpsc, oneshot, BiLock, BiLockGuard};
use ::bits::{AdditionalBuilder, ComposeMode, ComposeResult, DName,
Message, MessageBuf, MessageBuilder, Question};
use super::conf::ResolvConf;
use super::error::Error;
//============ The Path of a Message Through a Request =======================
//------------ RequestMessage ------------------------------------------------
/// The DNS message for input into a request.
///
/// The wrapped message is a message builder in stream mode. It consists of
/// exactly one question which is why compression is unnecessary and turned
/// off. It also has been advanced into a additional section builder. This
/// allows transports to add their EDNS0 information and, once they are done
/// with that, rewind their additions for reuse.
///
/// The only thing you can do with a request message is turn them into a
/// transport message using the `into_service()` method.
pub struct RequestMessage(AdditionalBuilder);
impl RequestMessage {
/// Creates a new request message from a question and resolver config.
///
/// This may fail if the domain name of the question isn’t absolute.
pub fn new<N, Q>(question: Q, conf: &ResolvConf) -> ComposeResult<Self>
where N: DName,
Q: Into<Question<N>> {
let mut msg = MessageBuilder::new(ComposeMode::Stream, false)?;
msg.header_mut().set_rd(conf.options.recurse);
msg.push(question)?;
Ok(RequestMessage(msg.additional()))
}
/// Converts the request message into a transport message.
///
/// This method returns the transport message wrapped into a pair of
/// bi-locks. See `TransportMessage` for a discussion as to why that
/// is useful.
fn into_service(self) -> (BiLock<Option<TransportMessage>>,
BiLock<Option<TransportMessage>>) {
BiLock::new(Some(TransportMessage(self.0)))
}
}
//------------ TransportMessage ----------------------------------------------
/// The DNS message passed to and used by the service.
///
/// This is a DNS request with exactly one question. The transport can add
/// its EDNS0 information to it and then access the message bytes for
/// sending. Once done, the transport message can be returned into a
/// request message by dropping all EDNS0 information thus making it ready
/// for reuse by the next transport.
///
/// *Note:* EDNS0 is not yet implemented.
///
|
/// the other one is kept by the query request. This way, we don’t need to
/// pass the message back when the transport is done which makes a lot easier
/// to treat all these cases where values along the way are dropped. In order
/// to allow the message being taken out of the lock, the lock’s content is
/// an option.
///
/// The rule is simple, violation will result in panics (but everything is
/// wrapped in `QueryRequest` and `TransportRequest` herein): The locks are
/// created with `Some` message. As long as the oneshot of the query request
/// has not been resolved, either successfully or by the sending end being
/// dropped, the transport has exclusive access to the message. It must,
/// however, not `take()` out the message. By resolving the oneshot, access
/// is transferred back to the query request. It then can `take()` out the
/// message.
pub struct TransportMessage(AdditionalBuilder);
impl TransportMessage {
/// Sets the message ID to the given value.
pub fn set_id(&mut self, id: u16) {
self.0.header_mut().set_id(id)
}
/// Checks whether `answer` is an answer to this message.
pub fn is_answer(&self, answer: &Message) -> bool {
answer.is_answer(&self.0)
}
/// Trades in this transport message for a request message.
///
/// This rewinds all additions made to the message since creation but
/// leaves the ID in place.
pub fn rewind(self) -> RequestMessage {
RequestMessage(self.0)
}
/// Returns a bytes slice with the data to be sent over stream transports.
pub fn stream_bytes(&mut self) -> &[u8] {
self.0.preview()
}
/// Returns a bytes slice for sending over datagram transports.
pub fn dgram_bytes(&mut self) -> &[u8] {
&self.0.preview()[2..]
}
}
//------------ TransportMessageGuard -----------------------------------------
/// A RAII guard for a locked transport message.
///
/// This implements both `Deref` and `DerefMut` into the underlying, locked
/// transport message. Once the value is dropped, the lock is released.
pub struct TransportMessageGuard<'a>(
BiLockGuard<'a, Option<TransportMessage>>
);
//--- Deref, DerefMut
impl<'a> ops::Deref for TransportMessageGuard<'a> {
type Target = TransportMessage;
fn deref(&self) -> &TransportMessage {
self.0.deref().as_ref().expect("message already taken")
}
}
impl<'a> ops::DerefMut for TransportMessageGuard<'a> {
fn deref_mut(&mut self) -> &mut TransportMessage {
self.0.deref_mut().as_mut().expect("message alread taken")
}
}
//------------ TransportResult -----------------------------------------------
/// The result returned by the transport.
///
/// This is the item type of the oneshot channel between transport request and
/// query request.
type TransportResult = Result<MessageBuf, Error>;
//============ The Query Side of a Request ===================================
//------------ QueryRequest --------------------------------------------------
/// The query side of a request.
///
/// This type is used by `Query` to dispatch and wait for requests. It is a
/// future resolving either into a both the response and request message or
/// an error and the request message.
pub struct QueryRequest {
/// The reading end of the oneshot channel for the reponse.
rx: Option<oneshot::Receiver<TransportResult>>,
/// Our side of the bi-locked transport message.
msg: BiLock<Option<TransportMessage>>,
}
impl QueryRequest {
/// Creates a new query request.
///
/// The request will attempt to answer `message` using the transport
/// referenced by `transport`.
pub fn new(message: RequestMessage, transport: &TransportHandle) -> Self {
let (tx, rx) = oneshot::channel();
let (smsg, qmsg) = message.into_service();
let sreq = TransportRequest::new(smsg, tx);
let rx = transport.send(sreq).ok().map(|_| rx);
QueryRequest {
rx: rx,
msg: qmsg
}
}
}
//--- Future
impl Future for QueryRequest {
type Item = (MessageBuf, RequestMessage);
type Error = (Error, RequestMessage);
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.rx {
Some(ref mut rx) => {
match rx.poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(response)) => {
let msg = into_message(&mut self.msg);
match response {
Ok(response) => Ok(Async::Ready((response, msg))),
Err(err) => Err((err, msg)),
}
}
Err(_) => {
// The transport disappeared. Let’s do a connection
// aborted error even if that isn’t quite right for
// UDP.
let msg = into_message(&mut self.msg);
Err((Error::Io(
io::Error::new(
io::ErrorKind::ConnectionAborted,
"transport disappeared")),
msg))
}
}
}
None => {
let msg = into_message(&mut self.msg);
Err((Error::Io(
io::Error::new(io::ErrorKind::ConnectionAborted,
"service disappeared")),
msg))
}
}
}
}
/// Helper function for unwrapping the transport message.
///
/// The function will take the transport message out of the lock if and only
/// if it can do so without blocking, panicing otherwise. See
/// `TransportMessage` for the rules when this is allowed.
fn into_message(msg: &mut BiLock<Option<TransportMessage>>) -> RequestMessage {
match msg.poll_lock() {
Async::Ready(ref mut msg) => {
match msg.take() {
Some(msg) => msg.rewind(),
None => panic!("called poll on a resolved QueryRequest"),
}
}
Async::NotReady => panic!("service kept message locked"),
}
}
//============ The Transport Side of a Request ===============================
//------------ TransportRequest ----------------------------------------------
/// The transport side of a request.
///
/// This type is used by a transport to try and discover the answer to a DNS
/// request. It contains both the message for this request and the sending
/// end of a oneshot channel to deliver the result to.
///
/// The transport requesst can safely be dropped at any time. However, it is
/// always better to resolve it with a specific error, allowing the query to
/// decide on its strategy based on this error instead of having to guess.
pub struct TransportRequest {
/// The request message behind a bi-lock.
message: BiLock<Option<TransportMessage>>,
/// The sending side of a oneshot channel for the result of the request.
complete: oneshot::Sender<TransportResult>,
/// The message ID of the request message.
///
/// This is initially `None` to indicate that it hasn’t been set for this
/// particular iteration yet.
id: Option<u16>,
}
impl TransportRequest {
/// Creates a new transport request from its components.
fn new(message: BiLock<Option<TransportMessage>>,
complete: oneshot::Sender<TransportResult>)
-> Self {
TransportRequest {
message: message,
complete: complete,
id: None
}
}
/// Provides access to the transport message.
///
/// Access happens in the form of a RAII guard that locks the message
/// while being alive.
///
/// # Panics
///
/// Panics if the message has been taken out of the lock. This should
/// not happen while the transport request is alive. Hence the panic.
pub fn message(&self) -> TransportMessageGuard {
if let Async::Ready(guard) = self.message.poll_lock() {
TransportMessageGuard(guard)
}
else {
panic!("message not ready");
}
}
/// Returns the request message’s ID or `None` if it hasn’t been set yet.
pub fn id(&self) -> Option<u16> {
self.id
}
/// Sets the request message’s ID to the given value.
pub fn set_id(&mut self, id: u16) {
self.id = Some(id);
self.message().set_id(id)
}
/// Completes the request with the given result.
pub fn complete(self, result: TransportResult) {
// Drop the message’s lock before completing as per the rules for
// transport messages.
let complete = self.complete;
drop(self.message);
complete.send(result).ok();
}
/// Completes the request with a response message.
///
/// This will produce a successful result only if `response` actually is
/// an answer to the request message. Else drops the message and produces
/// an error.
pub fn response(self, response: MessageBuf) {
if self.message().is_answer(&response) {
self.complete(Ok(response))
}
else {
self.fail(io::Error::new(io::ErrorKind::Other, "server failure")
.into())
}
}
/// Completes the request with the given error.
pub fn fail(self, err: Error) {
self.complete(Err(err))
}
/// Completes the request with a timeout error.
pub fn timeout(self) {
self.complete(Err(Error::Timeout))
}
}
//------------ TransportHandle -----------------------------------------------
/// A handle for communicating with a transport.
///
/// You can use this handle to send requests to the transport via the `send()`
/// method.
#[derive(Clone)]
pub struct TransportHandle {
/// The sending end of the transport’s request queue
tx: mpsc::UnboundedSender<TransportRequest>,
}
impl TransportHandle {
/// Creates a new request channel, returning both ends.
pub fn channel() -> (TransportHandle, RequestReceiver) {
let (tx, rx) = mpsc::unbounded();
(TransportHandle::from_sender(tx), rx)
}
/// Creates a new handle from the sender side of an MPCS channel.
pub fn from_sender(tx: mpsc::UnboundedSender<TransportRequest>) -> Self {
TransportHandle {
tx: tx
}
}
/// Sends a transport request to the transport.
///
/// This only fails if the receiver was dropped.
#[allow(deprecated)]
pub fn send(&self, sreq: TransportRequest)
-> Result<(), mpsc::SendError<TransportRequest>> {
self.tx.send(sreq)
}
}
//--- Debug
impl fmt::Debug for TransportHandle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TransportHandle{{...}}")
}
}
//------------ RequestReceiver -----------------------------------------------
/// The type of the receiving end of the request channel.
pub type RequestReceiver = mpsc::UnboundedReceiver<TransportRequest>;
|
/// Transport messages are always kept wrapped into a pair of bi-locks. One
/// of those locks goes into the transport request for use by the transport,
|
random_line_split
|
request.rs
|
//! DNS requests: the bridge between query and transport.
//!
//! While the future of the `Query` can be driven by any task, the network
//! transports are spawned into a reactor core each as a task of their own.
//! Requests and responses are exchanged between them using futures’s sync
//! primitives. Each transport holds the receiving end of an unbounded MPSC
//! channel for requests (defined as a type alias `RequestReceiver` herein),
//! with the sending end wrapped into the `TransportHandle` type and stored
//! in the `Resolver` for use by `Query`s.
//!
//! The query takes this transport handle and a `RequestMessage` (a light
//! wrapper around a DNS message ensuring that it is of the expected format)
//! and creates the query side of a request, aptly named `QueryRequest`. It
//! is a future resolving into either a response and the original request
//! message or an error and the very same request message.
//!
//! The reason for handing back the request message is that we can then
//! reuse it for further requests. Since we internally store DNS messages in
//! wire-format, anyway, they can be used as the send buffer directly and
//! reuse does make sense.
//!
//! The request sent over the channel is a `TransportRequest`. It consists
//! of the actual message now in the disguise of a `TransportMessage`
//! providing what the transport needs and the sending end of a oneshot
//! channel into which the transport is supposed to throw the response to
//! the request.
//!
//! The receiving end of the oneshot is part of the query request which polls
//! it for its completion.
//!
//! Note that timeouts happen on the transport side. While this is a little
//! less robust that we’d like, timeouts are tokio-core thing and need a
//! reactor. This way, we also potentially need fewer timeouts of lots of
//! requests are in flight.
use std::{fmt, io, ops};
use futures::{Async, Future, Poll};
use futures::sync::{mpsc, oneshot, BiLock, BiLockGuard};
use ::bits::{AdditionalBuilder, ComposeMode, ComposeResult, DName,
Message, MessageBuf, MessageBuilder, Question};
use super::conf::ResolvConf;
use super::error::Error;
//============ The Path of a Message Through a Request =======================
//------------ RequestMessage ------------------------------------------------
/// The DNS message for input into a request.
///
/// The wrapped message is a message builder in stream mode. It consists of
/// exactly one question which is why compression is unnecessary and turned
/// off. It also has been advanced into a additional section builder. This
/// allows transports to add their EDNS0 information and, once they are done
/// with that, rewind their additions for reuse.
///
/// The only thing you can do with a request message is turn them into a
/// transport message using the `into_service()` method.
pub struct RequestMessage(AdditionalBuilder);
impl RequestMessage {
/// Creates a new request message from a question and resolver config.
///
/// This may fail if the domain name of the question isn’t absolute.
pub fn new<N, Q>(question: Q, conf: &ResolvConf) -> ComposeResult<Self>
where N: DName,
Q: Into<Question<N>> {
let mut msg = MessageBuilder::new(ComposeMode::Stream, false)?;
msg.header_mut().set_rd(conf.options.recurse);
msg.push(question)?;
Ok(RequestMessage(msg.additional()))
}
/// Converts the request message into a transport message.
///
/// This method returns the transport message wrapped into a pair of
/// bi-locks. See `TransportMessage` for a discussion as to why that
/// is useful.
fn into_service(self) -> (BiLock<Option<TransportMessage>>,
BiLock<Option<TransportMessage>>) {
BiLock::new(Some(TransportMessage(self.0)))
}
}
//------------ TransportMessage ----------------------------------------------
/// The DNS message passed to and used by the service.
///
/// This is a DNS request with exactly one question. The transport can add
/// its EDNS0 information to it and then access the message bytes for
/// sending. Once done, the transport message can be returned into a
/// request message by dropping all EDNS0 information thus making it ready
/// for reuse by the next transport.
///
/// *Note:* EDNS0 is not yet implemented.
///
/// Transport messages are always kept wrapped into a pair of bi-locks. One
/// of those locks goes into the transport request for use by the transport,
/// the other one is kept by the query request. This way, we don’t need to
/// pass the message back when the transport is done which makes a lot easier
/// to treat all these cases where values along the way are dropped. In order
/// to allow the message being taken out of the lock, the lock’s content is
/// an option.
///
/// The rule is simple, violation will result in panics (but everything is
/// wrapped in `QueryRequest` and `TransportRequest` herein): The locks are
/// created with `Some` message. As long as the oneshot of the query request
/// has not been resolved, either successfully or by the sending end being
/// dropped, the transport has exclusive access to the message. It must,
/// however, not `take()` out the message. By resolving the oneshot, access
/// is transferred back to the query request. It then can `take()` out the
/// message.
pub struct TransportMessage(AdditionalBuilder);
impl TransportMessage {
/// Sets the message ID to the given value.
pub fn set_id(&mut self, id: u16) {
self.0.header_mut().set_id(id)
}
/// Checks whether `answer` is an answer to this message.
pub fn is_answer(&self, answer: &Message) -> bool {
answer.is_answer(&self.0)
}
/// Trades in this transport message for a request message.
///
/// This rewinds all additions made to the message since creation but
/// leaves the ID in place.
pub fn rewind(self) -> RequestMessage {
RequestMessage(self.0)
}
/// Returns a bytes slice with the data to be sent over stream transports.
pub fn stream_bytes(&mut self) -> &[u8] {
|
Returns a bytes slice for sending over datagram transports.
pub fn dgram_bytes(&mut self) -> &[u8] {
&self.0.preview()[2..]
}
}
//------------ TransportMessageGuard -----------------------------------------
/// A RAII guard for a locked transport message.
///
/// This implements both `Deref` and `DerefMut` into the underlying, locked
/// transport message. Once the value is dropped, the lock is released.
pub struct TransportMessageGuard<'a>(
BiLockGuard<'a, Option<TransportMessage>>
);
//--- Deref, DerefMut
impl<'a> ops::Deref for TransportMessageGuard<'a> {
type Target = TransportMessage;
fn deref(&self) -> &TransportMessage {
self.0.deref().as_ref().expect("message already taken")
}
}
impl<'a> ops::DerefMut for TransportMessageGuard<'a> {
fn deref_mut(&mut self) -> &mut TransportMessage {
self.0.deref_mut().as_mut().expect("message alread taken")
}
}
//------------ TransportResult -----------------------------------------------
/// The result returned by the transport.
///
/// This is the item type of the oneshot channel between transport request and
/// query request.
type TransportResult = Result<MessageBuf, Error>;
//============ The Query Side of a Request ===================================
//------------ QueryRequest --------------------------------------------------
/// The query side of a request.
///
/// This type is used by `Query` to dispatch and wait for requests. It is a
/// future resolving either into a both the response and request message or
/// an error and the request message.
pub struct QueryRequest {
/// The reading end of the oneshot channel for the reponse.
rx: Option<oneshot::Receiver<TransportResult>>,
/// Our side of the bi-locked transport message.
msg: BiLock<Option<TransportMessage>>,
}
impl QueryRequest {
/// Creates a new query request.
///
/// The request will attempt to answer `message` using the transport
/// referenced by `transport`.
pub fn new(message: RequestMessage, transport: &TransportHandle) -> Self {
let (tx, rx) = oneshot::channel();
let (smsg, qmsg) = message.into_service();
let sreq = TransportRequest::new(smsg, tx);
let rx = transport.send(sreq).ok().map(|_| rx);
QueryRequest {
rx: rx,
msg: qmsg
}
}
}
//--- Future
impl Future for QueryRequest {
type Item = (MessageBuf, RequestMessage);
type Error = (Error, RequestMessage);
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.rx {
Some(ref mut rx) => {
match rx.poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(response)) => {
let msg = into_message(&mut self.msg);
match response {
Ok(response) => Ok(Async::Ready((response, msg))),
Err(err) => Err((err, msg)),
}
}
Err(_) => {
// The transport disappeared. Let’s do a connection
// aborted error even if that isn’t quite right for
// UDP.
let msg = into_message(&mut self.msg);
Err((Error::Io(
io::Error::new(
io::ErrorKind::ConnectionAborted,
"transport disappeared")),
msg))
}
}
}
None => {
let msg = into_message(&mut self.msg);
Err((Error::Io(
io::Error::new(io::ErrorKind::ConnectionAborted,
"service disappeared")),
msg))
}
}
}
}
/// Helper function for unwrapping the transport message.
///
/// The function will take the transport message out of the lock if and only
/// if it can do so without blocking, panicing otherwise. See
/// `TransportMessage` for the rules when this is allowed.
fn into_message(msg: &mut BiLock<Option<TransportMessage>>) -> RequestMessage {
match msg.poll_lock() {
Async::Ready(ref mut msg) => {
match msg.take() {
Some(msg) => msg.rewind(),
None => panic!("called poll on a resolved QueryRequest"),
}
}
Async::NotReady => panic!("service kept message locked"),
}
}
//============ The Transport Side of a Request ===============================
//------------ TransportRequest ----------------------------------------------
/// The transport side of a request.
///
/// This type is used by a transport to try and discover the answer to a DNS
/// request. It contains both the message for this request and the sending
/// end of a oneshot channel to deliver the result to.
///
/// The transport requesst can safely be dropped at any time. However, it is
/// always better to resolve it with a specific error, allowing the query to
/// decide on its strategy based on this error instead of having to guess.
pub struct TransportRequest {
/// The request message behind a bi-lock.
message: BiLock<Option<TransportMessage>>,
/// The sending side of a oneshot channel for the result of the request.
complete: oneshot::Sender<TransportResult>,
/// The message ID of the request message.
///
/// This is initially `None` to indicate that it hasn’t been set for this
/// particular iteration yet.
id: Option<u16>,
}
impl TransportRequest {
/// Creates a new transport request from its components.
fn new(message: BiLock<Option<TransportMessage>>,
complete: oneshot::Sender<TransportResult>)
-> Self {
TransportRequest {
message: message,
complete: complete,
id: None
}
}
/// Provides access to the transport message.
///
/// Access happens in the form of a RAII guard that locks the message
/// while being alive.
///
/// # Panics
///
/// Panics if the message has been taken out of the lock. This should
/// not happen while the transport request is alive. Hence the panic.
pub fn message(&self) -> TransportMessageGuard {
if let Async::Ready(guard) = self.message.poll_lock() {
TransportMessageGuard(guard)
}
else {
panic!("message not ready");
}
}
/// Returns the request message’s ID or `None` if it hasn’t been set yet.
pub fn id(&self) -> Option<u16> {
self.id
}
/// Sets the request message’s ID to the given value.
pub fn set_id(&mut self, id: u16) {
self.id = Some(id);
self.message().set_id(id)
}
/// Completes the request with the given result.
pub fn complete(self, result: TransportResult) {
// Drop the message’s lock before completing as per the rules for
// transport messages.
let complete = self.complete;
drop(self.message);
complete.send(result).ok();
}
/// Completes the request with a response message.
///
/// This will produce a successful result only if `response` actually is
/// an answer to the request message. Else drops the message and produces
/// an error.
pub fn response(self, response: MessageBuf) {
if self.message().is_answer(&response) {
self.complete(Ok(response))
}
else {
self.fail(io::Error::new(io::ErrorKind::Other, "server failure")
.into())
}
}
/// Completes the request with the given error.
pub fn fail(self, err: Error) {
self.complete(Err(err))
}
/// Completes the request with a timeout error.
pub fn timeout(self) {
self.complete(Err(Error::Timeout))
}
}
//------------ TransportHandle -----------------------------------------------
/// A handle for communicating with a transport.
///
/// You can use this handle to send requests to the transport via the `send()`
/// method.
#[derive(Clone)]
pub struct TransportHandle {
/// The sending end of the transport’s request queue
tx: mpsc::UnboundedSender<TransportRequest>,
}
impl TransportHandle {
/// Creates a new request channel, returning both ends.
pub fn channel() -> (TransportHandle, RequestReceiver) {
let (tx, rx) = mpsc::unbounded();
(TransportHandle::from_sender(tx), rx)
}
/// Creates a new handle from the sender side of an MPCS channel.
pub fn from_sender(tx: mpsc::UnboundedSender<TransportRequest>) -> Self {
TransportHandle {
tx: tx
}
}
/// Sends a transport request to the transport.
///
/// This only fails if the receiver was dropped.
#[allow(deprecated)]
pub fn send(&self, sreq: TransportRequest)
-> Result<(), mpsc::SendError<TransportRequest>> {
self.tx.send(sreq)
}
}
//--- Debug
impl fmt::Debug for TransportHandle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TransportHandle{{...}}")
}
}
//------------ RequestReceiver -----------------------------------------------
/// The type of the receiving end of the request channel.
pub type RequestReceiver = mpsc::UnboundedReceiver<TransportRequest>;
|
self.0.preview()
}
///
|
identifier_body
|
day_10.rs
|
#![allow(transmute_ptr_to_ref)]
use std::mem;
use std::boxed::Box;
use std::option::Option;
use std::ops::Deref;
use std::ops::DerefMut;
use std::marker::Copy;
use std::clone::Clone;
struct Bucket {
key: Option<i32>,
value: Option<i32>,
next: Option<Link>
}
impl Bucket {
fn new(key: i32, value: i32) -> Bucket {
Bucket {
key: Some(key),
value: Some(value),
next: None
}
}
fn empty() -> Bucket {
|
key: None,
value: None,
next: None
}
}
}
struct Link {
ptr: *mut Bucket
}
impl Link {
fn new(bucket: Bucket) -> Link {
Link {
ptr: Box::into_raw(Box::new(bucket))
}
}
}
impl Deref for Link {
type Target = Bucket;
fn deref(&self) -> &Bucket {
unsafe { mem::transmute(self.ptr) }
}
}
impl DerefMut for Link {
fn deref_mut(&mut self) -> &mut Bucket {
unsafe { mem::transmute(self.ptr) }
}
}
impl Copy for Link { }
impl Clone for Link {
fn clone(&self) -> Link {
Link {
ptr: self.ptr
}
}
}
const CAPACITY: usize = 16;
#[derive(Default)]
pub struct Map {
size: usize,
table: Vec<Link>
}
impl Map {
pub fn new() -> Map {
let mut table = Vec::with_capacity(CAPACITY);
for _ in 0..CAPACITY {
table.push(Link::new(Bucket::empty()));
}
Map {
size: 0,
table: table
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.size
}
pub fn insert(&mut self, key: i32, value: i32) {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
if (*link).key!= Some(key) {
self.size += 1;
let mut new_bucket = Bucket::new(key, value);
let link = self.table[index];
new_bucket.next = Some(link);
self.table[index] = Link::new(new_bucket);
}
}
pub fn contains(&self, key: i32) -> bool {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
(*link).key == Some(key)
}
fn iterate(&self, key: i32, index: usize) -> Link {
let mut link = self.table[index];
while (*link).key!= Some(key) && (*link).next.is_some() {
link = (*link).next.unwrap();
}
link
}
pub fn get(&self, key: i32) -> Option<i32> {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
(*link).value
}
}
|
Bucket {
|
random_line_split
|
day_10.rs
|
#![allow(transmute_ptr_to_ref)]
use std::mem;
use std::boxed::Box;
use std::option::Option;
use std::ops::Deref;
use std::ops::DerefMut;
use std::marker::Copy;
use std::clone::Clone;
struct Bucket {
key: Option<i32>,
value: Option<i32>,
next: Option<Link>
}
impl Bucket {
fn new(key: i32, value: i32) -> Bucket {
Bucket {
key: Some(key),
value: Some(value),
next: None
}
}
fn empty() -> Bucket {
Bucket {
key: None,
value: None,
next: None
}
}
}
struct Link {
ptr: *mut Bucket
}
impl Link {
fn new(bucket: Bucket) -> Link {
Link {
ptr: Box::into_raw(Box::new(bucket))
}
}
}
impl Deref for Link {
type Target = Bucket;
fn deref(&self) -> &Bucket {
unsafe { mem::transmute(self.ptr) }
}
}
impl DerefMut for Link {
fn
|
(&mut self) -> &mut Bucket {
unsafe { mem::transmute(self.ptr) }
}
}
impl Copy for Link { }
impl Clone for Link {
fn clone(&self) -> Link {
Link {
ptr: self.ptr
}
}
}
const CAPACITY: usize = 16;
#[derive(Default)]
pub struct Map {
size: usize,
table: Vec<Link>
}
impl Map {
pub fn new() -> Map {
let mut table = Vec::with_capacity(CAPACITY);
for _ in 0..CAPACITY {
table.push(Link::new(Bucket::empty()));
}
Map {
size: 0,
table: table
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.size
}
pub fn insert(&mut self, key: i32, value: i32) {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
if (*link).key!= Some(key) {
self.size += 1;
let mut new_bucket = Bucket::new(key, value);
let link = self.table[index];
new_bucket.next = Some(link);
self.table[index] = Link::new(new_bucket);
}
}
pub fn contains(&self, key: i32) -> bool {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
(*link).key == Some(key)
}
fn iterate(&self, key: i32, index: usize) -> Link {
let mut link = self.table[index];
while (*link).key!= Some(key) && (*link).next.is_some() {
link = (*link).next.unwrap();
}
link
}
pub fn get(&self, key: i32) -> Option<i32> {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
(*link).value
}
}
|
deref_mut
|
identifier_name
|
day_10.rs
|
#![allow(transmute_ptr_to_ref)]
use std::mem;
use std::boxed::Box;
use std::option::Option;
use std::ops::Deref;
use std::ops::DerefMut;
use std::marker::Copy;
use std::clone::Clone;
struct Bucket {
key: Option<i32>,
value: Option<i32>,
next: Option<Link>
}
impl Bucket {
fn new(key: i32, value: i32) -> Bucket {
Bucket {
key: Some(key),
value: Some(value),
next: None
}
}
fn empty() -> Bucket {
Bucket {
key: None,
value: None,
next: None
}
}
}
struct Link {
ptr: *mut Bucket
}
impl Link {
fn new(bucket: Bucket) -> Link {
Link {
ptr: Box::into_raw(Box::new(bucket))
}
}
}
impl Deref for Link {
type Target = Bucket;
fn deref(&self) -> &Bucket {
unsafe { mem::transmute(self.ptr) }
}
}
impl DerefMut for Link {
fn deref_mut(&mut self) -> &mut Bucket {
unsafe { mem::transmute(self.ptr) }
}
}
impl Copy for Link { }
impl Clone for Link {
fn clone(&self) -> Link {
Link {
ptr: self.ptr
}
}
}
const CAPACITY: usize = 16;
#[derive(Default)]
pub struct Map {
size: usize,
table: Vec<Link>
}
impl Map {
pub fn new() -> Map {
let mut table = Vec::with_capacity(CAPACITY);
for _ in 0..CAPACITY {
table.push(Link::new(Bucket::empty()));
}
Map {
size: 0,
table: table
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.size
}
pub fn insert(&mut self, key: i32, value: i32) {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
if (*link).key!= Some(key)
|
}
pub fn contains(&self, key: i32) -> bool {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
(*link).key == Some(key)
}
fn iterate(&self, key: i32, index: usize) -> Link {
let mut link = self.table[index];
while (*link).key!= Some(key) && (*link).next.is_some() {
link = (*link).next.unwrap();
}
link
}
pub fn get(&self, key: i32) -> Option<i32> {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
(*link).value
}
}
|
{
self.size += 1;
let mut new_bucket = Bucket::new(key, value);
let link = self.table[index];
new_bucket.next = Some(link);
self.table[index] = Link::new(new_bucket);
}
|
conditional_block
|
day_10.rs
|
#![allow(transmute_ptr_to_ref)]
use std::mem;
use std::boxed::Box;
use std::option::Option;
use std::ops::Deref;
use std::ops::DerefMut;
use std::marker::Copy;
use std::clone::Clone;
struct Bucket {
key: Option<i32>,
value: Option<i32>,
next: Option<Link>
}
impl Bucket {
fn new(key: i32, value: i32) -> Bucket {
Bucket {
key: Some(key),
value: Some(value),
next: None
}
}
fn empty() -> Bucket {
Bucket {
key: None,
value: None,
next: None
}
}
}
struct Link {
ptr: *mut Bucket
}
impl Link {
fn new(bucket: Bucket) -> Link {
Link {
ptr: Box::into_raw(Box::new(bucket))
}
}
}
impl Deref for Link {
type Target = Bucket;
fn deref(&self) -> &Bucket {
unsafe { mem::transmute(self.ptr) }
}
}
impl DerefMut for Link {
fn deref_mut(&mut self) -> &mut Bucket {
unsafe { mem::transmute(self.ptr) }
}
}
impl Copy for Link { }
impl Clone for Link {
fn clone(&self) -> Link {
Link {
ptr: self.ptr
}
}
}
const CAPACITY: usize = 16;
#[derive(Default)]
pub struct Map {
size: usize,
table: Vec<Link>
}
impl Map {
pub fn new() -> Map {
let mut table = Vec::with_capacity(CAPACITY);
for _ in 0..CAPACITY {
table.push(Link::new(Bucket::empty()));
}
Map {
size: 0,
table: table
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn len(&self) -> usize {
self.size
}
pub fn insert(&mut self, key: i32, value: i32) {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
if (*link).key!= Some(key) {
self.size += 1;
let mut new_bucket = Bucket::new(key, value);
let link = self.table[index];
new_bucket.next = Some(link);
self.table[index] = Link::new(new_bucket);
}
}
pub fn contains(&self, key: i32) -> bool
|
fn iterate(&self, key: i32, index: usize) -> Link {
let mut link = self.table[index];
while (*link).key!= Some(key) && (*link).next.is_some() {
link = (*link).next.unwrap();
}
link
}
pub fn get(&self, key: i32) -> Option<i32> {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
(*link).value
}
}
|
{
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
(*link).key == Some(key)
}
|
identifier_body
|
day_4.rs
|
use std::borrow::Cow;
use std::str::Chars;
use std::iter::Peekable;
pub fn evaluate<'s>(src: Cow<'s, str>) -> f64 {
let mut chars = (*src).chars().peekable();
parse_expression(chars.by_ref())
}
fn parse_expression(chars: &mut Peekable<Chars>) -> f64 {
let mut result = parse_term(chars.by_ref());
loop {
match chars.peek().cloned() {
Some('+') => {
chars.next();
result += parse_term(chars.by_ref());
},
Some('-') => {
chars.next();
result -= parse_term(chars.by_ref());
},
_ => break
}
|
}
fn parse_term(chars: &mut Peekable<Chars>) -> f64 {
let mut result = parse_arg(chars.by_ref());
loop {
match chars.peek().cloned() {
Some('×') => {
chars.next();
result *= parse_arg(chars.by_ref());
},
Some('÷') => {
chars.next();
result /= parse_arg(chars.by_ref());
},
_ => break
}
}
result
}
fn parse_arg(chars: &mut Peekable<Chars>) -> f64 {
match chars.peek().cloned() {
Some('(') => {
chars.next();
let ret = parse_expression(chars);
chars.next();
ret
},
_ => {
let mut arg = 0.0;
while let Some(digit) = chars.peek().cloned().and_then(|c| c.to_digit(10)) {
arg = 10.0 * arg + (digit as f64);
chars.next();
}
arg
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::borrow::Cow;
#[test]
fn evaluate_num() {
assert_eq!(evaluate(Cow::Borrowed("10")), 10.0);
}
#[test]
fn evaluate_add() {
assert_eq!(evaluate(Cow::Borrowed("1+2")), 3.0);
}
#[test]
fn evaluate_sub() {
assert_eq!(evaluate(Cow::Borrowed("4-1")), 3.0);
}
#[test]
fn evaluate_mul() {
assert_eq!(evaluate(Cow::Borrowed("5×6")), 30.0);
}
#[test]
fn evaluate_div() {
assert_eq!(evaluate(Cow::Borrowed("40÷10")), 4.0);
}
#[test]
fn evaluate_multiple_operations() {
assert_eq!(evaluate(Cow::Borrowed("4+10÷2-3×4")), -3.0);
}
#[test]
fn evaluate_expression_with_parenthesis() {
assert_eq!(evaluate(Cow::Borrowed("(4+10)÷2-3×((4+6)-2)")), -17.0);
}
}
|
}
result
|
random_line_split
|
day_4.rs
|
use std::borrow::Cow;
use std::str::Chars;
use std::iter::Peekable;
pub fn evaluate<'s>(src: Cow<'s, str>) -> f64 {
let mut chars = (*src).chars().peekable();
parse_expression(chars.by_ref())
}
fn parse_expression(chars: &mut Peekable<Chars>) -> f64 {
let mut result = parse_term(chars.by_ref());
loop {
match chars.peek().cloned() {
Some('+') => {
chars.next();
result += parse_term(chars.by_ref());
},
Some('-') => {
chars.next();
result -= parse_term(chars.by_ref());
},
_ => break
}
}
result
}
fn parse_term(chars: &mut Peekable<Chars>) -> f64 {
let mut result = parse_arg(chars.by_ref());
loop {
match chars.peek().cloned() {
Some('×') => {
chars.next();
result *= parse_arg(chars.by_ref());
},
Some('÷') => {
chars.next();
result /= parse_arg(chars.by_ref());
},
_ => break
}
}
result
}
fn parse_arg(chars: &mut Peekable<Chars>) -> f64 {
match chars.peek().cloned() {
Some('(') => {
chars.next();
let ret = parse_expression(chars);
chars.next();
ret
},
_ => {
let mut arg = 0.0;
while let Some(digit) = chars.peek().cloned().and_then(|c| c.to_digit(10)) {
arg = 10.0 * arg + (digit as f64);
chars.next();
}
arg
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::borrow::Cow;
#[test]
fn evaluate_num() {
assert_eq!(evaluate(Cow::Borrowed("10")), 10.0);
}
#[test]
fn evaluate_add() {
assert_eq!(evaluate(Cow::Borrowed("1+2")), 3.0);
}
#[test]
fn evaluate_sub() {
assert_eq!(evaluate(Cow::Borrowed("4-1")), 3.0);
}
#[test]
fn evaluate_mul() {
assert_eq!(evaluate(Cow::Borrowed("5×6")), 30.0);
}
#[test]
fn evaluate_div() {
assert_eq!(evaluate(Cow::Borrowed("40÷10")), 4.0);
}
#[test]
fn evaluate_multiple_operations() {
assert_eq!(evaluate(Cow::Borrowed("4+10÷2-3×4")), -3.0);
}
#[test]
fn evaluate_expression_with_parenthesis() {
|
assert_eq!(evaluate(Cow::Borrowed("(4+10)÷2-3×((4+6)-2)")), -17.0);
}
}
|
identifier_body
|
|
day_4.rs
|
use std::borrow::Cow;
use std::str::Chars;
use std::iter::Peekable;
pub fn evaluate<'s>(src: Cow<'s, str>) -> f64 {
let mut chars = (*src).chars().peekable();
parse_expression(chars.by_ref())
}
fn parse_expression(chars: &mut Peekable<Chars>) -> f64 {
let mut result = parse_term(chars.by_ref());
loop {
match chars.peek().cloned() {
Some('+') => {
chars.next();
result += parse_term(chars.by_ref());
},
Some('-') => {
chars.next();
result -= parse_term(chars.by_ref());
},
_ => break
}
}
result
}
fn parse_term(chars: &mut Peekable<Chars>) -> f64 {
let mut result = parse_arg(chars.by_ref());
loop {
match chars.peek().cloned() {
Some('×') => {
chars.next();
result *= parse_arg(chars.by_ref());
},
Some('÷') => {
chars.next();
result /= parse_arg(chars.by_ref());
},
_ => break
}
}
result
}
fn parse_arg(chars: &mut Peekable<Chars>) -> f64 {
match chars.peek().cloned() {
Some('(') => {
chars.next();
let ret = parse_expression(chars);
chars.next();
ret
},
_ => {
let mut arg = 0.0;
while let Some(digit) = chars.peek().cloned().and_then(|c| c.to_digit(10)) {
arg = 10.0 * arg + (digit as f64);
chars.next();
}
arg
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::borrow::Cow;
#[test]
fn evaluate_num() {
assert_eq!(evaluate(Cow::Borrowed("10")), 10.0);
}
#[test]
fn evaluate_add() {
assert_eq!(evaluate(Cow::Borrowed("1+2")), 3.0);
}
#[test]
fn ev
|
{
assert_eq!(evaluate(Cow::Borrowed("4-1")), 3.0);
}
#[test]
fn evaluate_mul() {
assert_eq!(evaluate(Cow::Borrowed("5×6")), 30.0);
}
#[test]
fn evaluate_div() {
assert_eq!(evaluate(Cow::Borrowed("40÷10")), 4.0);
}
#[test]
fn evaluate_multiple_operations() {
assert_eq!(evaluate(Cow::Borrowed("4+10÷2-3×4")), -3.0);
}
#[test]
fn evaluate_expression_with_parenthesis() {
assert_eq!(evaluate(Cow::Borrowed("(4+10)÷2-3×((4+6)-2)")), -17.0);
}
}
|
aluate_sub()
|
identifier_name
|
resolve-type-param-in-item-in-trait.rs
|
// Issue #14603: Check for references to type parameters from the
// outer scope (in this case, the trait) used on items in an inner
// scope (in this case, the enum).
trait TraitA<A> {
fn outer(&self) {
enum Foo<B> {
Variance(A)
//~^ ERROR can't use generic parameters from outer function
}
}
}
trait TraitB<A> {
fn outer(&self) {
struct Foo<B>(A);
//~^ ERROR can't use generic parameters from outer function
}
}
trait TraitC<A> {
fn outer(&self)
|
}
trait TraitD<A> {
fn outer(&self) {
fn foo<B>(a: A) { }
//~^ ERROR can't use generic parameters from outer function
}
}
fn main() { }
|
{
struct Foo<B> { a: A }
//~^ ERROR can't use generic parameters from outer function
}
|
identifier_body
|
resolve-type-param-in-item-in-trait.rs
|
// Issue #14603: Check for references to type parameters from the
// outer scope (in this case, the trait) used on items in an inner
// scope (in this case, the enum).
trait TraitA<A> {
fn outer(&self) {
enum Foo<B> {
Variance(A)
//~^ ERROR can't use generic parameters from outer function
}
}
}
trait TraitB<A> {
fn outer(&self) {
struct Foo<B>(A);
//~^ ERROR can't use generic parameters from outer function
}
}
trait TraitC<A> {
fn outer(&self) {
struct Foo<B> { a: A }
//~^ ERROR can't use generic parameters from outer function
}
}
trait TraitD<A> {
fn outer(&self) {
fn foo<B>(a: A) { }
//~^ ERROR can't use generic parameters from outer function
}
}
fn
|
() { }
|
main
|
identifier_name
|
resolve-type-param-in-item-in-trait.rs
|
// Issue #14603: Check for references to type parameters from the
// outer scope (in this case, the trait) used on items in an inner
|
trait TraitA<A> {
fn outer(&self) {
enum Foo<B> {
Variance(A)
//~^ ERROR can't use generic parameters from outer function
}
}
}
trait TraitB<A> {
fn outer(&self) {
struct Foo<B>(A);
//~^ ERROR can't use generic parameters from outer function
}
}
trait TraitC<A> {
fn outer(&self) {
struct Foo<B> { a: A }
//~^ ERROR can't use generic parameters from outer function
}
}
trait TraitD<A> {
fn outer(&self) {
fn foo<B>(a: A) { }
//~^ ERROR can't use generic parameters from outer function
}
}
fn main() { }
|
// scope (in this case, the enum).
|
random_line_split
|
client_only.rs
|
extern crate jsonrpc_core;
extern crate jsonrpc_core_client;
#[macro_use]
extern crate jsonrpc_derive;
use jsonrpc_core::IoHandler;
use jsonrpc_core::futures::{self, TryFutureExt};
use jsonrpc_core_client::transports::local;
#[rpc(client)]
pub trait Rpc {
/// Returns a protocol version
#[rpc(name = "protocolVersion")]
fn protocol_version(&self) -> Result<String>;
/// Adds two numbers and returns a result
#[rpc(name = "add", alias("callAsyncMetaAlias"))]
fn add(&self, a: u64, b: u64) -> Result<u64>;
}
fn main()
|
{
let fut = {
let handler = IoHandler::new();
let (client, _rpc_client) = local::connect::<gen_client::Client, _, _>(handler);
client
.add(5, 6)
.map_ok(|res| println!("5 + 6 = {}", res))
};
let _ = futures::executor::block_on(fut);
}
|
identifier_body
|
|
client_only.rs
|
extern crate jsonrpc_core;
extern crate jsonrpc_core_client;
#[macro_use]
extern crate jsonrpc_derive;
use jsonrpc_core::IoHandler;
use jsonrpc_core::futures::{self, TryFutureExt};
use jsonrpc_core_client::transports::local;
#[rpc(client)]
pub trait Rpc {
/// Returns a protocol version
|
/// Adds two numbers and returns a result
#[rpc(name = "add", alias("callAsyncMetaAlias"))]
fn add(&self, a: u64, b: u64) -> Result<u64>;
}
fn main() {
let fut = {
let handler = IoHandler::new();
let (client, _rpc_client) = local::connect::<gen_client::Client, _, _>(handler);
client
.add(5, 6)
.map_ok(|res| println!("5 + 6 = {}", res))
};
let _ = futures::executor::block_on(fut);
}
|
#[rpc(name = "protocolVersion")]
fn protocol_version(&self) -> Result<String>;
|
random_line_split
|
client_only.rs
|
extern crate jsonrpc_core;
extern crate jsonrpc_core_client;
#[macro_use]
extern crate jsonrpc_derive;
use jsonrpc_core::IoHandler;
use jsonrpc_core::futures::{self, TryFutureExt};
use jsonrpc_core_client::transports::local;
#[rpc(client)]
pub trait Rpc {
/// Returns a protocol version
#[rpc(name = "protocolVersion")]
fn protocol_version(&self) -> Result<String>;
/// Adds two numbers and returns a result
#[rpc(name = "add", alias("callAsyncMetaAlias"))]
fn add(&self, a: u64, b: u64) -> Result<u64>;
}
fn
|
() {
let fut = {
let handler = IoHandler::new();
let (client, _rpc_client) = local::connect::<gen_client::Client, _, _>(handler);
client
.add(5, 6)
.map_ok(|res| println!("5 + 6 = {}", res))
};
let _ = futures::executor::block_on(fut);
}
|
main
|
identifier_name
|
contract.rs
|
// PactHash
// Written in 2015 by
// Andrew Poelstra <[email protected]>
|
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! # Contracts
//! Support for Elements Alpha contracts
//!
use bitcoin::network::constants::Network;
use bitcoin::util::address::{self, Address};
use bitcoin::util::base58::{self, FromBase58};
use serialize::hex::{self, FromHex};
use std::fmt;
/// Total length of a contract in bytes
pub const CONTRACT_LEN: usize = 40;
/// Length of the data portion of the contract in bytes
pub const DATA_LEN: usize = 20;
/// Type of contract encoding
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum Type {
/// Plain text
Text,
/// Pay-to-pubkeyhash Bitcoin script
PubkeyHash,
/// P2SH Bitcoin script
ScriptHash
}
impl Type {
/// Serialize the type in a way that can be used for contracthash key tweaking
pub fn serialize(&self) -> &'static [u8; 4] {
match *self {
Type::Text => b"TEXT",
Type::PubkeyHash => b"P2PH",
Type::ScriptHash => b"P2SH"
}
}
/// Interpret a 4-byte sequence as a type
pub fn deserialize(data: &[u8]) -> Result<Type, Error> {
match data {
b"TEXT" => Ok(Type::Text),
b"P2PH" => Ok(Type::PubkeyHash),
b"P2SH" => Ok(Type::ScriptHash),
x => Err(Error::BadType(x.to_owned()))
}
}
}
/// Nonce length in bytes
pub const NONCE_LEN: usize = 16;
/// Nonce
pub struct Nonce([u8; NONCE_LEN]);
impl_array_newtype!(Nonce, u8, NONCE_LEN);
impl Nonce {
/// Serialize the contract in a way that can be used for contracthash key tweaking
#[inline]
pub fn serialize(&self) -> Vec<u8> {
self[..].to_owned()
}
/// Decode a hex string as a Nonce
pub fn from_hex(data: &str) -> Result<Nonce, Error> {
let bytes = try!(data.from_hex().map_err(Error::Hex));
if bytes.len()!= NONCE_LEN {
return Err(Error::BadLength(bytes.len()));
}
unsafe {
use std::{mem, ptr};
let mut ret: [u8; NONCE_LEN] = mem::uninitialized();
ptr::copy_nonoverlapping(bytes.as_ptr(), ret.as_mut_ptr(), NONCE_LEN);
Ok(Nonce(ret))
}
}
/// Parse a Nonce out of a contract
pub fn from_contract(contract: &Contract) -> Nonce {
contract.nonce
}
}
impl fmt::LowerHex for Nonce {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for ch in &self.0[..] {
try!(write!(f, "{:02x}", *ch));
}
Ok(())
}
}
/// Contract
#[derive(Clone, PartialEq, Eq)]
pub struct Contract {
ty: Type,
nonce: Nonce,
data: Vec<u8>
}
/// Contract-related error
#[derive(Clone, Debug)]
pub enum Error {
/// Base58 decoding error
Base58(base58::Error),
/// Hex decoding error
Hex(hex::FromHexError),
/// Network did not match our expectation (got, expected)
WrongNetwork(Network, Network),
/// Contract was invalid length
BadLength(usize),
/// Unknown contract type
BadType(Vec<u8>)
}
impl Contract {
/// Serialize the contract in a way that can be used for contracthash key tweaking
pub fn serialize(&self) -> Vec<u8> {
let ty = self.ty.serialize();
let mut ret = Vec::with_capacity(ty.len() + self.nonce.len() + self.data.len());
ret.extend(&ty[..]);
ret.extend(&self.nonce[..]);
ret.extend(&self.data[..]);
ret
}
/// Decode a hex string as a contract
pub fn from_hex(data: &str) -> Result<Contract, Error> {
let bytes = try!(data.from_hex().map_err(Error::Hex));
if bytes.len()!= CONTRACT_LEN {
return Err(Error::BadLength(bytes.len()));
}
let ty = try!(Type::deserialize(&bytes[0..4]));
Ok(Contract {
ty: ty,
nonce: Nonce::from(&bytes[4..20]),
data: bytes[20..].to_owned()
})
}
/// Decode a P2SH address as a contract
pub fn from_p2sh_base58_str(s: &str, nonce: Nonce, expected_network: Network) -> Result<Contract, Error> {
let addr: Address = try!(FromBase58::from_base58check(s).map_err(Error::Base58));
if addr.network!= expected_network {
return Err(Error::WrongNetwork(addr.network, expected_network));
}
Ok(Contract {
ty: match addr.ty {
address::Type::PubkeyHash => Type::PubkeyHash,
address::Type::ScriptHash => Type::ScriptHash
},
nonce: nonce,
data: addr.hash[..].to_owned()
})
}
/// Decode an ASCII string as a contract
pub fn from_ascii_str(s: &str, nonce: Nonce) -> Result<Contract, Error> {
let bytes = s.as_bytes();
if bytes.len()!= DATA_LEN {
Err(Error::BadLength(bytes.len()))
} else {
Ok(Contract {
ty: Type::Text,
nonce: nonce,
data: bytes.to_owned()
})
}
}
}
impl fmt::LowerHex for Contract {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// TODO no need to allocate here, I'm just being lazy
for ch in &self.serialize()[..] {
try!(write!(f, "{:02x}", *ch));
}
Ok(())
}
}
|
//
|
random_line_split
|
contract.rs
|
// PactHash
// Written in 2015 by
// Andrew Poelstra <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! # Contracts
//! Support for Elements Alpha contracts
//!
use bitcoin::network::constants::Network;
use bitcoin::util::address::{self, Address};
use bitcoin::util::base58::{self, FromBase58};
use serialize::hex::{self, FromHex};
use std::fmt;
/// Total length of a contract in bytes
pub const CONTRACT_LEN: usize = 40;
/// Length of the data portion of the contract in bytes
pub const DATA_LEN: usize = 20;
/// Type of contract encoding
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum Type {
/// Plain text
Text,
/// Pay-to-pubkeyhash Bitcoin script
PubkeyHash,
/// P2SH Bitcoin script
ScriptHash
}
impl Type {
/// Serialize the type in a way that can be used for contracthash key tweaking
pub fn serialize(&self) -> &'static [u8; 4] {
match *self {
Type::Text => b"TEXT",
Type::PubkeyHash => b"P2PH",
Type::ScriptHash => b"P2SH"
}
}
/// Interpret a 4-byte sequence as a type
pub fn deserialize(data: &[u8]) -> Result<Type, Error> {
match data {
b"TEXT" => Ok(Type::Text),
b"P2PH" => Ok(Type::PubkeyHash),
b"P2SH" => Ok(Type::ScriptHash),
x => Err(Error::BadType(x.to_owned()))
}
}
}
/// Nonce length in bytes
pub const NONCE_LEN: usize = 16;
/// Nonce
pub struct Nonce([u8; NONCE_LEN]);
impl_array_newtype!(Nonce, u8, NONCE_LEN);
impl Nonce {
/// Serialize the contract in a way that can be used for contracthash key tweaking
#[inline]
pub fn serialize(&self) -> Vec<u8> {
self[..].to_owned()
}
/// Decode a hex string as a Nonce
pub fn
|
(data: &str) -> Result<Nonce, Error> {
let bytes = try!(data.from_hex().map_err(Error::Hex));
if bytes.len()!= NONCE_LEN {
return Err(Error::BadLength(bytes.len()));
}
unsafe {
use std::{mem, ptr};
let mut ret: [u8; NONCE_LEN] = mem::uninitialized();
ptr::copy_nonoverlapping(bytes.as_ptr(), ret.as_mut_ptr(), NONCE_LEN);
Ok(Nonce(ret))
}
}
/// Parse a Nonce out of a contract
pub fn from_contract(contract: &Contract) -> Nonce {
contract.nonce
}
}
impl fmt::LowerHex for Nonce {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for ch in &self.0[..] {
try!(write!(f, "{:02x}", *ch));
}
Ok(())
}
}
/// Contract
#[derive(Clone, PartialEq, Eq)]
pub struct Contract {
ty: Type,
nonce: Nonce,
data: Vec<u8>
}
/// Contract-related error
#[derive(Clone, Debug)]
pub enum Error {
/// Base58 decoding error
Base58(base58::Error),
/// Hex decoding error
Hex(hex::FromHexError),
/// Network did not match our expectation (got, expected)
WrongNetwork(Network, Network),
/// Contract was invalid length
BadLength(usize),
/// Unknown contract type
BadType(Vec<u8>)
}
impl Contract {
/// Serialize the contract in a way that can be used for contracthash key tweaking
pub fn serialize(&self) -> Vec<u8> {
let ty = self.ty.serialize();
let mut ret = Vec::with_capacity(ty.len() + self.nonce.len() + self.data.len());
ret.extend(&ty[..]);
ret.extend(&self.nonce[..]);
ret.extend(&self.data[..]);
ret
}
/// Decode a hex string as a contract
pub fn from_hex(data: &str) -> Result<Contract, Error> {
let bytes = try!(data.from_hex().map_err(Error::Hex));
if bytes.len()!= CONTRACT_LEN {
return Err(Error::BadLength(bytes.len()));
}
let ty = try!(Type::deserialize(&bytes[0..4]));
Ok(Contract {
ty: ty,
nonce: Nonce::from(&bytes[4..20]),
data: bytes[20..].to_owned()
})
}
/// Decode a P2SH address as a contract
pub fn from_p2sh_base58_str(s: &str, nonce: Nonce, expected_network: Network) -> Result<Contract, Error> {
let addr: Address = try!(FromBase58::from_base58check(s).map_err(Error::Base58));
if addr.network!= expected_network {
return Err(Error::WrongNetwork(addr.network, expected_network));
}
Ok(Contract {
ty: match addr.ty {
address::Type::PubkeyHash => Type::PubkeyHash,
address::Type::ScriptHash => Type::ScriptHash
},
nonce: nonce,
data: addr.hash[..].to_owned()
})
}
/// Decode an ASCII string as a contract
pub fn from_ascii_str(s: &str, nonce: Nonce) -> Result<Contract, Error> {
let bytes = s.as_bytes();
if bytes.len()!= DATA_LEN {
Err(Error::BadLength(bytes.len()))
} else {
Ok(Contract {
ty: Type::Text,
nonce: nonce,
data: bytes.to_owned()
})
}
}
}
impl fmt::LowerHex for Contract {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// TODO no need to allocate here, I'm just being lazy
for ch in &self.serialize()[..] {
try!(write!(f, "{:02x}", *ch));
}
Ok(())
}
}
|
from_hex
|
identifier_name
|
contract.rs
|
// PactHash
// Written in 2015 by
// Andrew Poelstra <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! # Contracts
//! Support for Elements Alpha contracts
//!
use bitcoin::network::constants::Network;
use bitcoin::util::address::{self, Address};
use bitcoin::util::base58::{self, FromBase58};
use serialize::hex::{self, FromHex};
use std::fmt;
/// Total length of a contract in bytes
pub const CONTRACT_LEN: usize = 40;
/// Length of the data portion of the contract in bytes
pub const DATA_LEN: usize = 20;
/// Type of contract encoding
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum Type {
/// Plain text
Text,
/// Pay-to-pubkeyhash Bitcoin script
PubkeyHash,
/// P2SH Bitcoin script
ScriptHash
}
impl Type {
/// Serialize the type in a way that can be used for contracthash key tweaking
pub fn serialize(&self) -> &'static [u8; 4] {
match *self {
Type::Text => b"TEXT",
Type::PubkeyHash => b"P2PH",
Type::ScriptHash => b"P2SH"
}
}
/// Interpret a 4-byte sequence as a type
pub fn deserialize(data: &[u8]) -> Result<Type, Error> {
match data {
b"TEXT" => Ok(Type::Text),
b"P2PH" => Ok(Type::PubkeyHash),
b"P2SH" => Ok(Type::ScriptHash),
x => Err(Error::BadType(x.to_owned()))
}
}
}
/// Nonce length in bytes
pub const NONCE_LEN: usize = 16;
/// Nonce
pub struct Nonce([u8; NONCE_LEN]);
impl_array_newtype!(Nonce, u8, NONCE_LEN);
impl Nonce {
/// Serialize the contract in a way that can be used for contracthash key tweaking
#[inline]
pub fn serialize(&self) -> Vec<u8> {
self[..].to_owned()
}
/// Decode a hex string as a Nonce
pub fn from_hex(data: &str) -> Result<Nonce, Error> {
let bytes = try!(data.from_hex().map_err(Error::Hex));
if bytes.len()!= NONCE_LEN {
return Err(Error::BadLength(bytes.len()));
}
unsafe {
use std::{mem, ptr};
let mut ret: [u8; NONCE_LEN] = mem::uninitialized();
ptr::copy_nonoverlapping(bytes.as_ptr(), ret.as_mut_ptr(), NONCE_LEN);
Ok(Nonce(ret))
}
}
/// Parse a Nonce out of a contract
pub fn from_contract(contract: &Contract) -> Nonce {
contract.nonce
}
}
impl fmt::LowerHex for Nonce {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for ch in &self.0[..] {
try!(write!(f, "{:02x}", *ch));
}
Ok(())
}
}
/// Contract
#[derive(Clone, PartialEq, Eq)]
pub struct Contract {
ty: Type,
nonce: Nonce,
data: Vec<u8>
}
/// Contract-related error
#[derive(Clone, Debug)]
pub enum Error {
/// Base58 decoding error
Base58(base58::Error),
/// Hex decoding error
Hex(hex::FromHexError),
/// Network did not match our expectation (got, expected)
WrongNetwork(Network, Network),
/// Contract was invalid length
BadLength(usize),
/// Unknown contract type
BadType(Vec<u8>)
}
impl Contract {
/// Serialize the contract in a way that can be used for contracthash key tweaking
pub fn serialize(&self) -> Vec<u8> {
let ty = self.ty.serialize();
let mut ret = Vec::with_capacity(ty.len() + self.nonce.len() + self.data.len());
ret.extend(&ty[..]);
ret.extend(&self.nonce[..]);
ret.extend(&self.data[..]);
ret
}
/// Decode a hex string as a contract
pub fn from_hex(data: &str) -> Result<Contract, Error> {
let bytes = try!(data.from_hex().map_err(Error::Hex));
if bytes.len()!= CONTRACT_LEN {
return Err(Error::BadLength(bytes.len()));
}
let ty = try!(Type::deserialize(&bytes[0..4]));
Ok(Contract {
ty: ty,
nonce: Nonce::from(&bytes[4..20]),
data: bytes[20..].to_owned()
})
}
/// Decode a P2SH address as a contract
pub fn from_p2sh_base58_str(s: &str, nonce: Nonce, expected_network: Network) -> Result<Contract, Error>
|
/// Decode an ASCII string as a contract
pub fn from_ascii_str(s: &str, nonce: Nonce) -> Result<Contract, Error> {
let bytes = s.as_bytes();
if bytes.len()!= DATA_LEN {
Err(Error::BadLength(bytes.len()))
} else {
Ok(Contract {
ty: Type::Text,
nonce: nonce,
data: bytes.to_owned()
})
}
}
}
impl fmt::LowerHex for Contract {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// TODO no need to allocate here, I'm just being lazy
for ch in &self.serialize()[..] {
try!(write!(f, "{:02x}", *ch));
}
Ok(())
}
}
|
{
let addr: Address = try!(FromBase58::from_base58check(s).map_err(Error::Base58));
if addr.network != expected_network {
return Err(Error::WrongNetwork(addr.network, expected_network));
}
Ok(Contract {
ty: match addr.ty {
address::Type::PubkeyHash => Type::PubkeyHash,
address::Type::ScriptHash => Type::ScriptHash
},
nonce: nonce,
data: addr.hash[..].to_owned()
})
}
|
identifier_body
|
contract.rs
|
// PactHash
// Written in 2015 by
// Andrew Poelstra <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this software.
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
//
//! # Contracts
//! Support for Elements Alpha contracts
//!
use bitcoin::network::constants::Network;
use bitcoin::util::address::{self, Address};
use bitcoin::util::base58::{self, FromBase58};
use serialize::hex::{self, FromHex};
use std::fmt;
/// Total length of a contract in bytes
pub const CONTRACT_LEN: usize = 40;
/// Length of the data portion of the contract in bytes
pub const DATA_LEN: usize = 20;
/// Type of contract encoding
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum Type {
/// Plain text
Text,
/// Pay-to-pubkeyhash Bitcoin script
PubkeyHash,
/// P2SH Bitcoin script
ScriptHash
}
impl Type {
/// Serialize the type in a way that can be used for contracthash key tweaking
pub fn serialize(&self) -> &'static [u8; 4] {
match *self {
Type::Text => b"TEXT",
Type::PubkeyHash => b"P2PH",
Type::ScriptHash => b"P2SH"
}
}
/// Interpret a 4-byte sequence as a type
pub fn deserialize(data: &[u8]) -> Result<Type, Error> {
match data {
b"TEXT" => Ok(Type::Text),
b"P2PH" => Ok(Type::PubkeyHash),
b"P2SH" => Ok(Type::ScriptHash),
x => Err(Error::BadType(x.to_owned()))
}
}
}
/// Nonce length in bytes
pub const NONCE_LEN: usize = 16;
/// Nonce
pub struct Nonce([u8; NONCE_LEN]);
impl_array_newtype!(Nonce, u8, NONCE_LEN);
impl Nonce {
/// Serialize the contract in a way that can be used for contracthash key tweaking
#[inline]
pub fn serialize(&self) -> Vec<u8> {
self[..].to_owned()
}
/// Decode a hex string as a Nonce
pub fn from_hex(data: &str) -> Result<Nonce, Error> {
let bytes = try!(data.from_hex().map_err(Error::Hex));
if bytes.len()!= NONCE_LEN {
return Err(Error::BadLength(bytes.len()));
}
unsafe {
use std::{mem, ptr};
let mut ret: [u8; NONCE_LEN] = mem::uninitialized();
ptr::copy_nonoverlapping(bytes.as_ptr(), ret.as_mut_ptr(), NONCE_LEN);
Ok(Nonce(ret))
}
}
/// Parse a Nonce out of a contract
pub fn from_contract(contract: &Contract) -> Nonce {
contract.nonce
}
}
impl fmt::LowerHex for Nonce {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for ch in &self.0[..] {
try!(write!(f, "{:02x}", *ch));
}
Ok(())
}
}
/// Contract
#[derive(Clone, PartialEq, Eq)]
pub struct Contract {
ty: Type,
nonce: Nonce,
data: Vec<u8>
}
/// Contract-related error
#[derive(Clone, Debug)]
pub enum Error {
/// Base58 decoding error
Base58(base58::Error),
/// Hex decoding error
Hex(hex::FromHexError),
/// Network did not match our expectation (got, expected)
WrongNetwork(Network, Network),
/// Contract was invalid length
BadLength(usize),
/// Unknown contract type
BadType(Vec<u8>)
}
impl Contract {
/// Serialize the contract in a way that can be used for contracthash key tweaking
pub fn serialize(&self) -> Vec<u8> {
let ty = self.ty.serialize();
let mut ret = Vec::with_capacity(ty.len() + self.nonce.len() + self.data.len());
ret.extend(&ty[..]);
ret.extend(&self.nonce[..]);
ret.extend(&self.data[..]);
ret
}
/// Decode a hex string as a contract
pub fn from_hex(data: &str) -> Result<Contract, Error> {
let bytes = try!(data.from_hex().map_err(Error::Hex));
if bytes.len()!= CONTRACT_LEN {
return Err(Error::BadLength(bytes.len()));
}
let ty = try!(Type::deserialize(&bytes[0..4]));
Ok(Contract {
ty: ty,
nonce: Nonce::from(&bytes[4..20]),
data: bytes[20..].to_owned()
})
}
/// Decode a P2SH address as a contract
pub fn from_p2sh_base58_str(s: &str, nonce: Nonce, expected_network: Network) -> Result<Contract, Error> {
let addr: Address = try!(FromBase58::from_base58check(s).map_err(Error::Base58));
if addr.network!= expected_network {
return Err(Error::WrongNetwork(addr.network, expected_network));
}
Ok(Contract {
ty: match addr.ty {
address::Type::PubkeyHash => Type::PubkeyHash,
address::Type::ScriptHash => Type::ScriptHash
},
nonce: nonce,
data: addr.hash[..].to_owned()
})
}
/// Decode an ASCII string as a contract
pub fn from_ascii_str(s: &str, nonce: Nonce) -> Result<Contract, Error> {
let bytes = s.as_bytes();
if bytes.len()!= DATA_LEN {
Err(Error::BadLength(bytes.len()))
} else
|
}
}
impl fmt::LowerHex for Contract {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// TODO no need to allocate here, I'm just being lazy
for ch in &self.serialize()[..] {
try!(write!(f, "{:02x}", *ch));
}
Ok(())
}
}
|
{
Ok(Contract {
ty: Type::Text,
nonce: nonce,
data: bytes.to_owned()
})
}
|
conditional_block
|
clone.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-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 ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use parse::token::InternedString;
pub fn expand_deriving_clone(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "clone", "Clone")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "clone",
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: Vec::new(),
ret_ty: Self,
attributes: attrs,
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_clone("Clone", c, s, sub)
}),
}
)
};
trait_def.expand(cx, mitem, item, push)
}
fn cs_clone(
name: &str,
cx: &mut ExtCtxt, trait_span: Span,
substr: &Substructure) -> @Expr {
let clone_ident = substr.method_ident;
let ctor_ident;
let all_fields;
let subcall = |field: &FieldInfo|
cx.expr_method_call(field.span, field.self_, clone_ident, Vec::new());
match *substr.fields {
Struct(ref af) => {
ctor_ident = substr.type_ident;
all_fields = af;
}
EnumMatching(_, variant, ref af) => {
ctor_ident = variant.node.name;
all_fields = af;
},
EnumNonMatching(..) => cx.span_bug(trait_span,
format!("non-matching enum variants in `deriving({})`",
name)),
StaticEnum(..) | StaticStruct(..) => cx.span_bug(trait_span,
format!("static method in `deriving({})`",
name))
}
if all_fields.len() >= 1 && all_fields.get(0).name.is_none() {
// enum-like
let subcalls = all_fields.iter().map(subcall).collect();
cx.expr_call_ident(trait_span, ctor_ident, subcalls)
} else {
// struct-like
|
Some(i) => i,
None => cx.span_bug(trait_span,
format!("unnamed field in normal struct in `deriving({})`",
name))
};
cx.field_imm(field.span, ident, subcall(field))
}).collect::<Vec<_>>();
if fields.is_empty() {
// no fields, so construct like `None`
cx.expr_ident(trait_span, ctor_ident)
} else {
cx.expr_struct_ident(trait_span, ctor_ident, fields)
}
}
}
|
let fields = all_fields.iter().map(|field| {
let ident = match field.name {
|
random_line_split
|
clone.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-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 ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use parse::token::InternedString;
pub fn expand_deriving_clone(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "clone", "Clone")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "clone",
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: Vec::new(),
ret_ty: Self,
attributes: attrs,
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_clone("Clone", c, s, sub)
}),
}
)
};
trait_def.expand(cx, mitem, item, push)
}
fn cs_clone(
name: &str,
cx: &mut ExtCtxt, trait_span: Span,
substr: &Substructure) -> @Expr
|
format!("static method in `deriving({})`",
name))
}
if all_fields.len() >= 1 && all_fields.get(0).name.is_none() {
// enum-like
let subcalls = all_fields.iter().map(subcall).collect();
cx.expr_call_ident(trait_span, ctor_ident, subcalls)
} else {
// struct-like
let fields = all_fields.iter().map(|field| {
let ident = match field.name {
Some(i) => i,
None => cx.span_bug(trait_span,
format!("unnamed field in normal struct in `deriving({})`",
name))
};
cx.field_imm(field.span, ident, subcall(field))
}).collect::<Vec<_>>();
if fields.is_empty() {
// no fields, so construct like `None`
cx.expr_ident(trait_span, ctor_ident)
} else {
cx.expr_struct_ident(trait_span, ctor_ident, fields)
}
}
}
|
{
let clone_ident = substr.method_ident;
let ctor_ident;
let all_fields;
let subcall = |field: &FieldInfo|
cx.expr_method_call(field.span, field.self_, clone_ident, Vec::new());
match *substr.fields {
Struct(ref af) => {
ctor_ident = substr.type_ident;
all_fields = af;
}
EnumMatching(_, variant, ref af) => {
ctor_ident = variant.node.name;
all_fields = af;
},
EnumNonMatching(..) => cx.span_bug(trait_span,
format!("non-matching enum variants in `deriving({})`",
name)),
StaticEnum(..) | StaticStruct(..) => cx.span_bug(trait_span,
|
identifier_body
|
clone.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-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 ast::{MetaItem, Item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use parse::token::InternedString;
pub fn
|
(cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("std", "clone", "Clone")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "clone",
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: Vec::new(),
ret_ty: Self,
attributes: attrs,
const_nonmatching: false,
combine_substructure: combine_substructure(|c, s, sub| {
cs_clone("Clone", c, s, sub)
}),
}
)
};
trait_def.expand(cx, mitem, item, push)
}
fn cs_clone(
name: &str,
cx: &mut ExtCtxt, trait_span: Span,
substr: &Substructure) -> @Expr {
let clone_ident = substr.method_ident;
let ctor_ident;
let all_fields;
let subcall = |field: &FieldInfo|
cx.expr_method_call(field.span, field.self_, clone_ident, Vec::new());
match *substr.fields {
Struct(ref af) => {
ctor_ident = substr.type_ident;
all_fields = af;
}
EnumMatching(_, variant, ref af) => {
ctor_ident = variant.node.name;
all_fields = af;
},
EnumNonMatching(..) => cx.span_bug(trait_span,
format!("non-matching enum variants in `deriving({})`",
name)),
StaticEnum(..) | StaticStruct(..) => cx.span_bug(trait_span,
format!("static method in `deriving({})`",
name))
}
if all_fields.len() >= 1 && all_fields.get(0).name.is_none() {
// enum-like
let subcalls = all_fields.iter().map(subcall).collect();
cx.expr_call_ident(trait_span, ctor_ident, subcalls)
} else {
// struct-like
let fields = all_fields.iter().map(|field| {
let ident = match field.name {
Some(i) => i,
None => cx.span_bug(trait_span,
format!("unnamed field in normal struct in `deriving({})`",
name))
};
cx.field_imm(field.span, ident, subcall(field))
}).collect::<Vec<_>>();
if fields.is_empty() {
// no fields, so construct like `None`
cx.expr_ident(trait_span, ctor_ident)
} else {
cx.expr_struct_ident(trait_span, ctor_ident, fields)
}
}
}
|
expand_deriving_clone
|
identifier_name
|
test_helpers.rs
|
//! A testing module for Runner/Process traits.
//!
//! When implementing different pieces of this crate, it was expedient
//! to have some testing structs in place. This might also be useful for
//! other developers who would want to ensure proper functionality.
use std::thread;
use std::sync::mpsc;
use chan;
use std::error::Error;
use std::fmt;
use {MaridError, Signal, Process, Runner, Receiver, Sender};
/// A test struct that implements the Runner trait.
pub struct TestRunner {
data: usize,
sender: Sender<bool>
}
#[derive(Debug, Eq, PartialEq, Clone)]
/// Error type for testing
pub struct TestError;
impl fmt::Display for TestError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a testing error")
}
}
impl Error for TestError {
fn description(&self) -> &str {
"a testing error"
}
}
impl TestRunner {
/// Create a new TestRunner.
pub fn new(data: usize, sender: Sender<bool>) -> TestRunner {
TestRunner {
data: data,
sender: sender,
}
}
}
impl Runner for TestRunner {
fn setup(&mut self) -> Result<(), MaridError> {
self.data = 27;
Ok(())
}
fn run(mut self: Box<Self>, signals: Receiver<Signal>) -> Result<(), MaridError> {
self.data += 73;
assert_eq!(self.data, 100);
let sig = signals.recv().expect("Could not recv signal");
if sig == Signal::INT {
self.sender.send(true);
Ok(())
} else {
self.sender.send(false);
Err(Box::new(TestError))
}
}
}
/// A test struct that implements the Process trait.
pub struct TestProcess {
runner: mpsc::Receiver<bool>,
signals: Sender<Signal>,
}
|
impl TestProcess {
/// Create a new TestProcess.
pub fn new(runner: TestRunner) -> TestProcess {
let (sn, rc) = mpsc::channel();
let (send_runner, recv_runner) = mpsc::channel::<TestRunner>();
// Marid sender/receiver
let (signals, sig_recv) = chan::async();
thread::spawn(move || {
let mut runner = Box::new(recv_runner.recv().unwrap());
match runner.setup() {
Ok(_) => sn.send(true),
Err(_) => sn.send(false),
}.unwrap();
match runner.run(sig_recv) {
Ok(_) => sn.send(true),
Err(_) => sn.send(false),
}.unwrap();
});
send_runner.send(runner).unwrap();
TestProcess{
runner: rc,
signals: signals,
}
}
}
impl Process for TestProcess {
type Error = TestError;
fn ready(&self) -> Result<(), Self::Error> {
if self.runner.recv().unwrap() {
Ok(())
} else {
Err(TestError)
}
}
fn wait(&self) -> Result<(), Self::Error> {
match self.runner.recv() {
Ok(b) => if b { Ok(()) } else { Err(TestError) },
Err(_) => Err(TestError),
}
}
fn signal(&self, signal: Signal) {
self.signals.send(signal);
}
}
|
random_line_split
|
|
test_helpers.rs
|
//! A testing module for Runner/Process traits.
//!
//! When implementing different pieces of this crate, it was expedient
//! to have some testing structs in place. This might also be useful for
//! other developers who would want to ensure proper functionality.
use std::thread;
use std::sync::mpsc;
use chan;
use std::error::Error;
use std::fmt;
use {MaridError, Signal, Process, Runner, Receiver, Sender};
/// A test struct that implements the Runner trait.
pub struct TestRunner {
data: usize,
sender: Sender<bool>
}
#[derive(Debug, Eq, PartialEq, Clone)]
/// Error type for testing
pub struct TestError;
impl fmt::Display for TestError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a testing error")
}
}
impl Error for TestError {
fn description(&self) -> &str
|
}
impl TestRunner {
/// Create a new TestRunner.
pub fn new(data: usize, sender: Sender<bool>) -> TestRunner {
TestRunner {
data: data,
sender: sender,
}
}
}
impl Runner for TestRunner {
fn setup(&mut self) -> Result<(), MaridError> {
self.data = 27;
Ok(())
}
fn run(mut self: Box<Self>, signals: Receiver<Signal>) -> Result<(), MaridError> {
self.data += 73;
assert_eq!(self.data, 100);
let sig = signals.recv().expect("Could not recv signal");
if sig == Signal::INT {
self.sender.send(true);
Ok(())
} else {
self.sender.send(false);
Err(Box::new(TestError))
}
}
}
/// A test struct that implements the Process trait.
pub struct TestProcess {
runner: mpsc::Receiver<bool>,
signals: Sender<Signal>,
}
impl TestProcess {
/// Create a new TestProcess.
pub fn new(runner: TestRunner) -> TestProcess {
let (sn, rc) = mpsc::channel();
let (send_runner, recv_runner) = mpsc::channel::<TestRunner>();
// Marid sender/receiver
let (signals, sig_recv) = chan::async();
thread::spawn(move || {
let mut runner = Box::new(recv_runner.recv().unwrap());
match runner.setup() {
Ok(_) => sn.send(true),
Err(_) => sn.send(false),
}.unwrap();
match runner.run(sig_recv) {
Ok(_) => sn.send(true),
Err(_) => sn.send(false),
}.unwrap();
});
send_runner.send(runner).unwrap();
TestProcess{
runner: rc,
signals: signals,
}
}
}
impl Process for TestProcess {
type Error = TestError;
fn ready(&self) -> Result<(), Self::Error> {
if self.runner.recv().unwrap() {
Ok(())
} else {
Err(TestError)
}
}
fn wait(&self) -> Result<(), Self::Error> {
match self.runner.recv() {
Ok(b) => if b { Ok(()) } else { Err(TestError) },
Err(_) => Err(TestError),
}
}
fn signal(&self, signal: Signal) {
self.signals.send(signal);
}
}
|
{
"a testing error"
}
|
identifier_body
|
test_helpers.rs
|
//! A testing module for Runner/Process traits.
//!
//! When implementing different pieces of this crate, it was expedient
//! to have some testing structs in place. This might also be useful for
//! other developers who would want to ensure proper functionality.
use std::thread;
use std::sync::mpsc;
use chan;
use std::error::Error;
use std::fmt;
use {MaridError, Signal, Process, Runner, Receiver, Sender};
/// A test struct that implements the Runner trait.
pub struct TestRunner {
data: usize,
sender: Sender<bool>
}
#[derive(Debug, Eq, PartialEq, Clone)]
/// Error type for testing
pub struct TestError;
impl fmt::Display for TestError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "a testing error")
}
}
impl Error for TestError {
fn description(&self) -> &str {
"a testing error"
}
}
impl TestRunner {
/// Create a new TestRunner.
pub fn new(data: usize, sender: Sender<bool>) -> TestRunner {
TestRunner {
data: data,
sender: sender,
}
}
}
impl Runner for TestRunner {
fn setup(&mut self) -> Result<(), MaridError> {
self.data = 27;
Ok(())
}
fn run(mut self: Box<Self>, signals: Receiver<Signal>) -> Result<(), MaridError> {
self.data += 73;
assert_eq!(self.data, 100);
let sig = signals.recv().expect("Could not recv signal");
if sig == Signal::INT {
self.sender.send(true);
Ok(())
} else {
self.sender.send(false);
Err(Box::new(TestError))
}
}
}
/// A test struct that implements the Process trait.
pub struct TestProcess {
runner: mpsc::Receiver<bool>,
signals: Sender<Signal>,
}
impl TestProcess {
/// Create a new TestProcess.
pub fn
|
(runner: TestRunner) -> TestProcess {
let (sn, rc) = mpsc::channel();
let (send_runner, recv_runner) = mpsc::channel::<TestRunner>();
// Marid sender/receiver
let (signals, sig_recv) = chan::async();
thread::spawn(move || {
let mut runner = Box::new(recv_runner.recv().unwrap());
match runner.setup() {
Ok(_) => sn.send(true),
Err(_) => sn.send(false),
}.unwrap();
match runner.run(sig_recv) {
Ok(_) => sn.send(true),
Err(_) => sn.send(false),
}.unwrap();
});
send_runner.send(runner).unwrap();
TestProcess{
runner: rc,
signals: signals,
}
}
}
impl Process for TestProcess {
type Error = TestError;
fn ready(&self) -> Result<(), Self::Error> {
if self.runner.recv().unwrap() {
Ok(())
} else {
Err(TestError)
}
}
fn wait(&self) -> Result<(), Self::Error> {
match self.runner.recv() {
Ok(b) => if b { Ok(()) } else { Err(TestError) },
Err(_) => Err(TestError),
}
}
fn signal(&self, signal: Signal) {
self.signals.send(signal);
}
}
|
new
|
identifier_name
|
cityhash.rs
|
use std::mem;
pub fn cityhash32(mut s: &[u8], len: usize) -> u32 { // mut s: &[u8]
if len <= 24 {
return if len <= 12 {
if len <= 4 {
hash32Len0to4(s, len)
} else {
hash32_len_5_to_12(s, len)
}
} else {
hash32_len_13_to_24(s, len)
}
}
// len > 32
let mut h = len as u32;
let mut g = (len as u32).wrapping_mul(C1);
let mut f = g;
let mut a0 = rotate32(fetch32(&s[len-4..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a1 = rotate32(fetch32(&s[len-8..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a2 = rotate32(fetch32(&s[len-16..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a3 = rotate32(fetch32(&s[len-12..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a4 = rotate32(fetch32(&s[len-20..]).wrapping_mul(C1), 17).wrapping_mul(C2);
h ^= a0;
h = rotate32(h, 19);
h = h.wrapping_mul(5).wrapping_add(0xe6546b64);
h ^= a2;
h = rotate32(h, 19);
h = h.wrapping_mul(5).wrapping_add(0xe6546b64);
g ^= a1;
g = rotate32(g, 19);
g = g.wrapping_mul(5).wrapping_add(0xe6546b64);
g ^= a3;
g = rotate32(g, 19);
g = g.wrapping_mul(5).wrapping_add(0xe6546b64);
f = f.wrapping_add(a4);
f = rotate32(f, 19).wrapping_add(113);
f = f.wrapping_mul(5).wrapping_add(0xe6546b64);
let mut iters = ((len - 1) / 20) as u64;
while iters > 0 {
let a0 = rotate32(fetch32(&s[..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a1 = fetch32(&s[4..]);
let a2 = rotate32(fetch32(&s[8..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a3 = rotate32(fetch32(&s[12..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a4 = fetch32(&s[16..]);
h ^= a0;
h = rotate32(h, 18);
h = (h * 5).wrapping_add(0xe6546b64);
f += a1;
f = rotate32(f, 19);
f = f.wrapping_mul(C1);
g += a2;
g = rotate32(g, 18);
g = (g * 5).wrapping_add(0xe6546b64);
h ^= a3 + a1;
h = rotate32(h, 19);
h = (h * 5).wrapping_add(0xe6546b64);
g ^= a4;
g = bswap32(g) * 5;
h += a4 * 5;
h = bswap32(h);
f += a0;
//#define PERMUTE3(a, b, c) do { std::swap(a, b); std::swap(a, c); } while (0)
//PERMUTE3(f, h, g);
mem::swap(&mut h, &mut f);
mem::swap(&mut g, &mut f);
s = &s[20..];
iters -= 1;
}
g = rotate32(g, 11) * C1;
g = rotate32(g, 17) * C1;
f = rotate32(f, 11) * C1;
f = rotate32(f, 17) * C1;
h = rotate32(h + g, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * C1;
h = rotate32(h + f, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * C1;
return h;
}
fn hash32Len0to4(s: &[u8], len: usize) -> u32 {
let mut b: u32 = 0;
let mut c: u32 = 9;
for i in 0..len {
let v: u8 = s[i];
b = b.wrapping_mul(C1) + v as u32;
c ^= b;
}
return fmix(mur(b, mur(len as u32, c)));
}
fn fetch32(p: &[u8]) -> u32 {
(p[0] as u32) | (p[1] as u32) << 8 | (p[2] as u32) << 16 | (p[3] as u32) << 24
}
// rotate32 is a bitwise rotate
fn rotate32(val: u32, shift: u32) -> u32 {
if shift == 0 {
return val;
}
return val >> shift | val << (32 - shift)
}
// Some primes between 2^63 and 2^64 for various uses.
pub const K0: u64 = 0xc3a5c85c97cb3127;
pub const K1: u64 = 0xb492b66fbe98f273;
pub const K2: u64 = 0x9ae16a3b2f90404f;
// Magic numbers for 32-bit hashing. Copied from Murmur3.
pub const C1: u32 = 0xcc9e2d51;
pub const C2: u32 = 0x1b873593;
// fmix is a 32-bit to 32-bit integer hash copied from Murmur3.
fn
|
(mut h: u32) -> u32 {
h ^= h >> 16;
h = h.wrapping_mul(0x85ebca6b);
h ^= h >> 13;
h = h.wrapping_mul(0xc2b2ae35);
h ^= h >> 16;
return h;
}
// Mur is a helper from Murmur3 for combining two 32-bit values.
fn mur(mut a: u32, mut h: u32) -> u32 {
a = a.wrapping_mul(C1);
a = rotate32(a, 17);
a = a.wrapping_mul(C2);
h ^= a;
h = rotate32(h, 19);
return h.wrapping_mul(5).wrapping_add(0xe6546b64);
}
fn hash32_len_5_to_12(s: &[u8], len: usize) -> u32 {
let mut a = len as u32;
let mut b = len as u32 * 5;
let mut c: u32 = 9;
let d: u32 = b;
a += fetch32(&s[0..]);
b += fetch32(&s[len-4..]);
c += fetch32(&s[((len >> 1) & 4)..]);
return fmix(mur(c, mur(b, mur(a, d))));
}
fn hash32_len_13_to_24(s: &[u8], len: usize) -> u32 {
let a = fetch32(&s[-4+(len>>1 as u64)..]);
let b = fetch32(&s[4..]);
let c = fetch32(&s[len-8..]);
let d = fetch32(&s[len>>1..]);
let e = fetch32(&s[0..]);
let f = fetch32(&s[len-4..]);
let h = len as u32;
return fmix(mur(f, mur(e, mur(d, mur(c, mur(b, mur(a, h)))))));
}
fn bswap32(x: u32) -> u32 {
return ((x >> 24) & 0xFF) | ((x >> 8) & 0xFF00) |
((x << 8) & 0xFF0000) | ((x << 24) & 0xFF000000)
}
|
fmix
|
identifier_name
|
cityhash.rs
|
use std::mem;
|
return if len <= 12 {
if len <= 4 {
hash32Len0to4(s, len)
} else {
hash32_len_5_to_12(s, len)
}
} else {
hash32_len_13_to_24(s, len)
}
}
// len > 32
let mut h = len as u32;
let mut g = (len as u32).wrapping_mul(C1);
let mut f = g;
let mut a0 = rotate32(fetch32(&s[len-4..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a1 = rotate32(fetch32(&s[len-8..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a2 = rotate32(fetch32(&s[len-16..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a3 = rotate32(fetch32(&s[len-12..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a4 = rotate32(fetch32(&s[len-20..]).wrapping_mul(C1), 17).wrapping_mul(C2);
h ^= a0;
h = rotate32(h, 19);
h = h.wrapping_mul(5).wrapping_add(0xe6546b64);
h ^= a2;
h = rotate32(h, 19);
h = h.wrapping_mul(5).wrapping_add(0xe6546b64);
g ^= a1;
g = rotate32(g, 19);
g = g.wrapping_mul(5).wrapping_add(0xe6546b64);
g ^= a3;
g = rotate32(g, 19);
g = g.wrapping_mul(5).wrapping_add(0xe6546b64);
f = f.wrapping_add(a4);
f = rotate32(f, 19).wrapping_add(113);
f = f.wrapping_mul(5).wrapping_add(0xe6546b64);
let mut iters = ((len - 1) / 20) as u64;
while iters > 0 {
let a0 = rotate32(fetch32(&s[..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a1 = fetch32(&s[4..]);
let a2 = rotate32(fetch32(&s[8..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a3 = rotate32(fetch32(&s[12..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a4 = fetch32(&s[16..]);
h ^= a0;
h = rotate32(h, 18);
h = (h * 5).wrapping_add(0xe6546b64);
f += a1;
f = rotate32(f, 19);
f = f.wrapping_mul(C1);
g += a2;
g = rotate32(g, 18);
g = (g * 5).wrapping_add(0xe6546b64);
h ^= a3 + a1;
h = rotate32(h, 19);
h = (h * 5).wrapping_add(0xe6546b64);
g ^= a4;
g = bswap32(g) * 5;
h += a4 * 5;
h = bswap32(h);
f += a0;
//#define PERMUTE3(a, b, c) do { std::swap(a, b); std::swap(a, c); } while (0)
//PERMUTE3(f, h, g);
mem::swap(&mut h, &mut f);
mem::swap(&mut g, &mut f);
s = &s[20..];
iters -= 1;
}
g = rotate32(g, 11) * C1;
g = rotate32(g, 17) * C1;
f = rotate32(f, 11) * C1;
f = rotate32(f, 17) * C1;
h = rotate32(h + g, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * C1;
h = rotate32(h + f, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * C1;
return h;
}
fn hash32Len0to4(s: &[u8], len: usize) -> u32 {
let mut b: u32 = 0;
let mut c: u32 = 9;
for i in 0..len {
let v: u8 = s[i];
b = b.wrapping_mul(C1) + v as u32;
c ^= b;
}
return fmix(mur(b, mur(len as u32, c)));
}
fn fetch32(p: &[u8]) -> u32 {
(p[0] as u32) | (p[1] as u32) << 8 | (p[2] as u32) << 16 | (p[3] as u32) << 24
}
// rotate32 is a bitwise rotate
fn rotate32(val: u32, shift: u32) -> u32 {
if shift == 0 {
return val;
}
return val >> shift | val << (32 - shift)
}
// Some primes between 2^63 and 2^64 for various uses.
pub const K0: u64 = 0xc3a5c85c97cb3127;
pub const K1: u64 = 0xb492b66fbe98f273;
pub const K2: u64 = 0x9ae16a3b2f90404f;
// Magic numbers for 32-bit hashing. Copied from Murmur3.
pub const C1: u32 = 0xcc9e2d51;
pub const C2: u32 = 0x1b873593;
// fmix is a 32-bit to 32-bit integer hash copied from Murmur3.
fn fmix(mut h: u32) -> u32 {
h ^= h >> 16;
h = h.wrapping_mul(0x85ebca6b);
h ^= h >> 13;
h = h.wrapping_mul(0xc2b2ae35);
h ^= h >> 16;
return h;
}
// Mur is a helper from Murmur3 for combining two 32-bit values.
fn mur(mut a: u32, mut h: u32) -> u32 {
a = a.wrapping_mul(C1);
a = rotate32(a, 17);
a = a.wrapping_mul(C2);
h ^= a;
h = rotate32(h, 19);
return h.wrapping_mul(5).wrapping_add(0xe6546b64);
}
fn hash32_len_5_to_12(s: &[u8], len: usize) -> u32 {
let mut a = len as u32;
let mut b = len as u32 * 5;
let mut c: u32 = 9;
let d: u32 = b;
a += fetch32(&s[0..]);
b += fetch32(&s[len-4..]);
c += fetch32(&s[((len >> 1) & 4)..]);
return fmix(mur(c, mur(b, mur(a, d))));
}
fn hash32_len_13_to_24(s: &[u8], len: usize) -> u32 {
let a = fetch32(&s[-4+(len>>1 as u64)..]);
let b = fetch32(&s[4..]);
let c = fetch32(&s[len-8..]);
let d = fetch32(&s[len>>1..]);
let e = fetch32(&s[0..]);
let f = fetch32(&s[len-4..]);
let h = len as u32;
return fmix(mur(f, mur(e, mur(d, mur(c, mur(b, mur(a, h)))))));
}
fn bswap32(x: u32) -> u32 {
return ((x >> 24) & 0xFF) | ((x >> 8) & 0xFF00) |
((x << 8) & 0xFF0000) | ((x << 24) & 0xFF000000)
}
|
pub fn cityhash32(mut s: &[u8], len: usize) -> u32 { // mut s: &[u8]
if len <= 24 {
|
random_line_split
|
cityhash.rs
|
use std::mem;
pub fn cityhash32(mut s: &[u8], len: usize) -> u32 { // mut s: &[u8]
if len <= 24 {
return if len <= 12 {
if len <= 4 {
hash32Len0to4(s, len)
} else {
hash32_len_5_to_12(s, len)
}
} else {
hash32_len_13_to_24(s, len)
}
}
// len > 32
let mut h = len as u32;
let mut g = (len as u32).wrapping_mul(C1);
let mut f = g;
let mut a0 = rotate32(fetch32(&s[len-4..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a1 = rotate32(fetch32(&s[len-8..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a2 = rotate32(fetch32(&s[len-16..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a3 = rotate32(fetch32(&s[len-12..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a4 = rotate32(fetch32(&s[len-20..]).wrapping_mul(C1), 17).wrapping_mul(C2);
h ^= a0;
h = rotate32(h, 19);
h = h.wrapping_mul(5).wrapping_add(0xe6546b64);
h ^= a2;
h = rotate32(h, 19);
h = h.wrapping_mul(5).wrapping_add(0xe6546b64);
g ^= a1;
g = rotate32(g, 19);
g = g.wrapping_mul(5).wrapping_add(0xe6546b64);
g ^= a3;
g = rotate32(g, 19);
g = g.wrapping_mul(5).wrapping_add(0xe6546b64);
f = f.wrapping_add(a4);
f = rotate32(f, 19).wrapping_add(113);
f = f.wrapping_mul(5).wrapping_add(0xe6546b64);
let mut iters = ((len - 1) / 20) as u64;
while iters > 0 {
let a0 = rotate32(fetch32(&s[..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a1 = fetch32(&s[4..]);
let a2 = rotate32(fetch32(&s[8..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a3 = rotate32(fetch32(&s[12..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a4 = fetch32(&s[16..]);
h ^= a0;
h = rotate32(h, 18);
h = (h * 5).wrapping_add(0xe6546b64);
f += a1;
f = rotate32(f, 19);
f = f.wrapping_mul(C1);
g += a2;
g = rotate32(g, 18);
g = (g * 5).wrapping_add(0xe6546b64);
h ^= a3 + a1;
h = rotate32(h, 19);
h = (h * 5).wrapping_add(0xe6546b64);
g ^= a4;
g = bswap32(g) * 5;
h += a4 * 5;
h = bswap32(h);
f += a0;
//#define PERMUTE3(a, b, c) do { std::swap(a, b); std::swap(a, c); } while (0)
//PERMUTE3(f, h, g);
mem::swap(&mut h, &mut f);
mem::swap(&mut g, &mut f);
s = &s[20..];
iters -= 1;
}
g = rotate32(g, 11) * C1;
g = rotate32(g, 17) * C1;
f = rotate32(f, 11) * C1;
f = rotate32(f, 17) * C1;
h = rotate32(h + g, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * C1;
h = rotate32(h + f, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * C1;
return h;
}
fn hash32Len0to4(s: &[u8], len: usize) -> u32 {
let mut b: u32 = 0;
let mut c: u32 = 9;
for i in 0..len {
let v: u8 = s[i];
b = b.wrapping_mul(C1) + v as u32;
c ^= b;
}
return fmix(mur(b, mur(len as u32, c)));
}
fn fetch32(p: &[u8]) -> u32
|
// rotate32 is a bitwise rotate
fn rotate32(val: u32, shift: u32) -> u32 {
if shift == 0 {
return val;
}
return val >> shift | val << (32 - shift)
}
// Some primes between 2^63 and 2^64 for various uses.
pub const K0: u64 = 0xc3a5c85c97cb3127;
pub const K1: u64 = 0xb492b66fbe98f273;
pub const K2: u64 = 0x9ae16a3b2f90404f;
// Magic numbers for 32-bit hashing. Copied from Murmur3.
pub const C1: u32 = 0xcc9e2d51;
pub const C2: u32 = 0x1b873593;
// fmix is a 32-bit to 32-bit integer hash copied from Murmur3.
fn fmix(mut h: u32) -> u32 {
h ^= h >> 16;
h = h.wrapping_mul(0x85ebca6b);
h ^= h >> 13;
h = h.wrapping_mul(0xc2b2ae35);
h ^= h >> 16;
return h;
}
// Mur is a helper from Murmur3 for combining two 32-bit values.
fn mur(mut a: u32, mut h: u32) -> u32 {
a = a.wrapping_mul(C1);
a = rotate32(a, 17);
a = a.wrapping_mul(C2);
h ^= a;
h = rotate32(h, 19);
return h.wrapping_mul(5).wrapping_add(0xe6546b64);
}
fn hash32_len_5_to_12(s: &[u8], len: usize) -> u32 {
let mut a = len as u32;
let mut b = len as u32 * 5;
let mut c: u32 = 9;
let d: u32 = b;
a += fetch32(&s[0..]);
b += fetch32(&s[len-4..]);
c += fetch32(&s[((len >> 1) & 4)..]);
return fmix(mur(c, mur(b, mur(a, d))));
}
fn hash32_len_13_to_24(s: &[u8], len: usize) -> u32 {
let a = fetch32(&s[-4+(len>>1 as u64)..]);
let b = fetch32(&s[4..]);
let c = fetch32(&s[len-8..]);
let d = fetch32(&s[len>>1..]);
let e = fetch32(&s[0..]);
let f = fetch32(&s[len-4..]);
let h = len as u32;
return fmix(mur(f, mur(e, mur(d, mur(c, mur(b, mur(a, h)))))));
}
fn bswap32(x: u32) -> u32 {
return ((x >> 24) & 0xFF) | ((x >> 8) & 0xFF00) |
((x << 8) & 0xFF0000) | ((x << 24) & 0xFF000000)
}
|
{
(p[0] as u32) | (p[1] as u32) << 8 | (p[2] as u32) << 16 | (p[3] as u32) << 24
}
|
identifier_body
|
cityhash.rs
|
use std::mem;
pub fn cityhash32(mut s: &[u8], len: usize) -> u32 { // mut s: &[u8]
if len <= 24 {
return if len <= 12
|
else {
hash32_len_13_to_24(s, len)
}
}
// len > 32
let mut h = len as u32;
let mut g = (len as u32).wrapping_mul(C1);
let mut f = g;
let mut a0 = rotate32(fetch32(&s[len-4..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a1 = rotate32(fetch32(&s[len-8..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a2 = rotate32(fetch32(&s[len-16..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a3 = rotate32(fetch32(&s[len-12..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a4 = rotate32(fetch32(&s[len-20..]).wrapping_mul(C1), 17).wrapping_mul(C2);
h ^= a0;
h = rotate32(h, 19);
h = h.wrapping_mul(5).wrapping_add(0xe6546b64);
h ^= a2;
h = rotate32(h, 19);
h = h.wrapping_mul(5).wrapping_add(0xe6546b64);
g ^= a1;
g = rotate32(g, 19);
g = g.wrapping_mul(5).wrapping_add(0xe6546b64);
g ^= a3;
g = rotate32(g, 19);
g = g.wrapping_mul(5).wrapping_add(0xe6546b64);
f = f.wrapping_add(a4);
f = rotate32(f, 19).wrapping_add(113);
f = f.wrapping_mul(5).wrapping_add(0xe6546b64);
let mut iters = ((len - 1) / 20) as u64;
while iters > 0 {
let a0 = rotate32(fetch32(&s[..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a1 = fetch32(&s[4..]);
let a2 = rotate32(fetch32(&s[8..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a3 = rotate32(fetch32(&s[12..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let a4 = fetch32(&s[16..]);
h ^= a0;
h = rotate32(h, 18);
h = (h * 5).wrapping_add(0xe6546b64);
f += a1;
f = rotate32(f, 19);
f = f.wrapping_mul(C1);
g += a2;
g = rotate32(g, 18);
g = (g * 5).wrapping_add(0xe6546b64);
h ^= a3 + a1;
h = rotate32(h, 19);
h = (h * 5).wrapping_add(0xe6546b64);
g ^= a4;
g = bswap32(g) * 5;
h += a4 * 5;
h = bswap32(h);
f += a0;
//#define PERMUTE3(a, b, c) do { std::swap(a, b); std::swap(a, c); } while (0)
//PERMUTE3(f, h, g);
mem::swap(&mut h, &mut f);
mem::swap(&mut g, &mut f);
s = &s[20..];
iters -= 1;
}
g = rotate32(g, 11) * C1;
g = rotate32(g, 17) * C1;
f = rotate32(f, 11) * C1;
f = rotate32(f, 17) * C1;
h = rotate32(h + g, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * C1;
h = rotate32(h + f, 19);
h = h * 5 + 0xe6546b64;
h = rotate32(h, 17) * C1;
return h;
}
fn hash32Len0to4(s: &[u8], len: usize) -> u32 {
let mut b: u32 = 0;
let mut c: u32 = 9;
for i in 0..len {
let v: u8 = s[i];
b = b.wrapping_mul(C1) + v as u32;
c ^= b;
}
return fmix(mur(b, mur(len as u32, c)));
}
fn fetch32(p: &[u8]) -> u32 {
(p[0] as u32) | (p[1] as u32) << 8 | (p[2] as u32) << 16 | (p[3] as u32) << 24
}
// rotate32 is a bitwise rotate
fn rotate32(val: u32, shift: u32) -> u32 {
if shift == 0 {
return val;
}
return val >> shift | val << (32 - shift)
}
// Some primes between 2^63 and 2^64 for various uses.
pub const K0: u64 = 0xc3a5c85c97cb3127;
pub const K1: u64 = 0xb492b66fbe98f273;
pub const K2: u64 = 0x9ae16a3b2f90404f;
// Magic numbers for 32-bit hashing. Copied from Murmur3.
pub const C1: u32 = 0xcc9e2d51;
pub const C2: u32 = 0x1b873593;
// fmix is a 32-bit to 32-bit integer hash copied from Murmur3.
fn fmix(mut h: u32) -> u32 {
h ^= h >> 16;
h = h.wrapping_mul(0x85ebca6b);
h ^= h >> 13;
h = h.wrapping_mul(0xc2b2ae35);
h ^= h >> 16;
return h;
}
// Mur is a helper from Murmur3 for combining two 32-bit values.
fn mur(mut a: u32, mut h: u32) -> u32 {
a = a.wrapping_mul(C1);
a = rotate32(a, 17);
a = a.wrapping_mul(C2);
h ^= a;
h = rotate32(h, 19);
return h.wrapping_mul(5).wrapping_add(0xe6546b64);
}
fn hash32_len_5_to_12(s: &[u8], len: usize) -> u32 {
let mut a = len as u32;
let mut b = len as u32 * 5;
let mut c: u32 = 9;
let d: u32 = b;
a += fetch32(&s[0..]);
b += fetch32(&s[len-4..]);
c += fetch32(&s[((len >> 1) & 4)..]);
return fmix(mur(c, mur(b, mur(a, d))));
}
fn hash32_len_13_to_24(s: &[u8], len: usize) -> u32 {
let a = fetch32(&s[-4+(len>>1 as u64)..]);
let b = fetch32(&s[4..]);
let c = fetch32(&s[len-8..]);
let d = fetch32(&s[len>>1..]);
let e = fetch32(&s[0..]);
let f = fetch32(&s[len-4..]);
let h = len as u32;
return fmix(mur(f, mur(e, mur(d, mur(c, mur(b, mur(a, h)))))));
}
fn bswap32(x: u32) -> u32 {
return ((x >> 24) & 0xFF) | ((x >> 8) & 0xFF00) |
((x << 8) & 0xFF0000) | ((x << 24) & 0xFF000000)
}
|
{
if len <= 4 {
hash32Len0to4(s, len)
} else {
hash32_len_5_to_12(s, len)
}
}
|
conditional_block
|
ec_public_key.rs
|
// Copyright 2017 Brian Smith <[email protected]>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 super::Algorithm;
use crate::error::*;
pub struct ECPublicKey {
buf: [u8; MAX_LEN],
len: usize,
|
}
// The length of the longest supported EC public key (P-384).
const MAX_LEN: usize = 1 + (2 * 48);
impl ECPublicKey {
// DNSSEC encodes uncompressed EC public keys without the standard 0x04
// prefix that indicates they are uncompressed, but crypto libraries
// require that prefix.
pub fn from_unprefixed(without_prefix: &[u8], algorithm: Algorithm) -> ProtoResult<Self> {
let field_len = match algorithm {
Algorithm::ECDSAP256SHA256 => 32,
Algorithm::ECDSAP384SHA384 => 48,
_ => return Err("only ECDSAP256SHA256 and ECDSAP384SHA384 are supported by Ec".into()),
};
let len = 1 + (2 * field_len);
if len - 1!= without_prefix.len() {
return Err("EC public key is the wrong length".into());
}
let mut buf = [0x04u8; MAX_LEN];
buf[1..len].copy_from_slice(without_prefix);
Ok(ECPublicKey { buf, len })
}
pub fn prefixed_bytes(&self) -> &[u8] {
&self.buf[..self.len]
}
#[cfg(feature = "ring")]
pub fn unprefixed_bytes(&self) -> &[u8] {
&self.buf[1..self.len]
}
}
|
random_line_split
|
|
ec_public_key.rs
|
// Copyright 2017 Brian Smith <[email protected]>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 super::Algorithm;
use crate::error::*;
pub struct
|
{
buf: [u8; MAX_LEN],
len: usize,
}
// The length of the longest supported EC public key (P-384).
const MAX_LEN: usize = 1 + (2 * 48);
impl ECPublicKey {
// DNSSEC encodes uncompressed EC public keys without the standard 0x04
// prefix that indicates they are uncompressed, but crypto libraries
// require that prefix.
pub fn from_unprefixed(without_prefix: &[u8], algorithm: Algorithm) -> ProtoResult<Self> {
let field_len = match algorithm {
Algorithm::ECDSAP256SHA256 => 32,
Algorithm::ECDSAP384SHA384 => 48,
_ => return Err("only ECDSAP256SHA256 and ECDSAP384SHA384 are supported by Ec".into()),
};
let len = 1 + (2 * field_len);
if len - 1!= without_prefix.len() {
return Err("EC public key is the wrong length".into());
}
let mut buf = [0x04u8; MAX_LEN];
buf[1..len].copy_from_slice(without_prefix);
Ok(ECPublicKey { buf, len })
}
pub fn prefixed_bytes(&self) -> &[u8] {
&self.buf[..self.len]
}
#[cfg(feature = "ring")]
pub fn unprefixed_bytes(&self) -> &[u8] {
&self.buf[1..self.len]
}
}
|
ECPublicKey
|
identifier_name
|
ec_public_key.rs
|
// Copyright 2017 Brian Smith <[email protected]>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 super::Algorithm;
use crate::error::*;
pub struct ECPublicKey {
buf: [u8; MAX_LEN],
len: usize,
}
// The length of the longest supported EC public key (P-384).
const MAX_LEN: usize = 1 + (2 * 48);
impl ECPublicKey {
// DNSSEC encodes uncompressed EC public keys without the standard 0x04
// prefix that indicates they are uncompressed, but crypto libraries
// require that prefix.
pub fn from_unprefixed(without_prefix: &[u8], algorithm: Algorithm) -> ProtoResult<Self>
|
pub fn prefixed_bytes(&self) -> &[u8] {
&self.buf[..self.len]
}
#[cfg(feature = "ring")]
pub fn unprefixed_bytes(&self) -> &[u8] {
&self.buf[1..self.len]
}
}
|
{
let field_len = match algorithm {
Algorithm::ECDSAP256SHA256 => 32,
Algorithm::ECDSAP384SHA384 => 48,
_ => return Err("only ECDSAP256SHA256 and ECDSAP384SHA384 are supported by Ec".into()),
};
let len = 1 + (2 * field_len);
if len - 1 != without_prefix.len() {
return Err("EC public key is the wrong length".into());
}
let mut buf = [0x04u8; MAX_LEN];
buf[1..len].copy_from_slice(without_prefix);
Ok(ECPublicKey { buf, len })
}
|
identifier_body
|
newtype-struct-drop-run.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
// Make sure the destructor is run for newtype structs.
use std::cell::Cell;
struct Foo(@Cell<int>);
#[unsafe_destructor]
impl Drop for Foo {
fn drop(&mut self) {
let Foo(i) = *self;
i.set(23);
}
}
pub fn
|
() {
let y = @Cell::new(32);
{
let _x = Foo(y);
}
assert_eq!(y.get(), 23);
}
|
main
|
identifier_name
|
newtype-struct-drop-run.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
// Make sure the destructor is run for newtype structs.
use std::cell::Cell;
struct Foo(@Cell<int>);
#[unsafe_destructor]
impl Drop for Foo {
fn drop(&mut self) {
let Foo(i) = *self;
i.set(23);
}
}
|
let y = @Cell::new(32);
{
let _x = Foo(y);
}
assert_eq!(y.get(), 23);
}
|
pub fn main() {
|
random_line_split
|
newtype-struct-drop-run.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(managed_boxes)]
// Make sure the destructor is run for newtype structs.
use std::cell::Cell;
struct Foo(@Cell<int>);
#[unsafe_destructor]
impl Drop for Foo {
fn drop(&mut self) {
let Foo(i) = *self;
i.set(23);
}
}
pub fn main()
|
{
let y = @Cell::new(32);
{
let _x = Foo(y);
}
assert_eq!(y.get(), 23);
}
|
identifier_body
|
|
body.rs
|
use url::form_urlencoded;
use hyper::Chunk;
use mime;
use controller::context::BodyContent;
pub fn parse_body(content_type: Option<&mime::Mime>, body_data: Chunk) -> Option<BodyContent>
{
if body_data.is_empty() {
None
} else {
let is_multipart_form_data = if let Some(ref content_mime) = content_type {
content_mime.type_() == mime::MULTIPART && content_mime.subtype() == mime::FORM_DATA
} else {
false
};
|
} else {
parse_form_urlencoded(body_data)
};
Some(body_parsed)
}
}
fn parse_form_urlencoded(body_data: Chunk) -> BodyContent
{
let vec: Vec<u8> = body_data.iter().cloned().collect();
form_urlencoded::parse(vec.as_ref())
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect()
}
// TODO: realize this function
// https://github.com/abonander/multipart-async
// https://ru.wikipedia.org/wiki/HTTP#Множественное_содержимое
fn parse_multipart_form_data(content_type: Option<&mime::Mime>, body_data: Chunk) -> BodyContent
{
if let Some(boundary) = get_boundary(content_type) {
println!("multipart request received, boundary: {}", boundary);
}
parse_form_urlencoded(body_data) // TODO: this is stub
}
fn get_boundary(content_type: Option<&mime::Mime>) -> Option<String> {
content_type
.and_then(|content_mime| {
content_mime.get_param(mime::BOUNDARY).map(|boundary|boundary.as_ref().into())
})
}
|
let body_parsed = if is_multipart_form_data {
parse_multipart_form_data(content_type, body_data)
|
random_line_split
|
body.rs
|
use url::form_urlencoded;
use hyper::Chunk;
use mime;
use controller::context::BodyContent;
pub fn parse_body(content_type: Option<&mime::Mime>, body_data: Chunk) -> Option<BodyContent>
{
if body_data.is_empty() {
None
} else {
let is_multipart_form_data = if let Some(ref content_mime) = content_type {
content_mime.type_() == mime::MULTIPART && content_mime.subtype() == mime::FORM_DATA
} else {
false
};
let body_parsed = if is_multipart_form_data {
parse_multipart_form_data(content_type, body_data)
} else {
parse_form_urlencoded(body_data)
};
Some(body_parsed)
}
}
fn parse_form_urlencoded(body_data: Chunk) -> BodyContent
{
let vec: Vec<u8> = body_data.iter().cloned().collect();
form_urlencoded::parse(vec.as_ref())
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect()
}
// TODO: realize this function
// https://github.com/abonander/multipart-async
// https://ru.wikipedia.org/wiki/HTTP#Множественное_содержимое
fn parse_multipart_form_da
|
mime::Mime>, body_data: Chunk) -> BodyContent
{
if let Some(boundary) = get_boundary(content_type) {
println!("multipart request received, boundary: {}", boundary);
}
parse_form_urlencoded(body_data) // TODO: this is stub
}
fn get_boundary(content_type: Option<&mime::Mime>) -> Option<String> {
content_type
.and_then(|content_mime| {
content_mime.get_param(mime::BOUNDARY).map(|boundary|boundary.as_ref().into())
})
}
|
ta(content_type: Option<&
|
identifier_name
|
body.rs
|
use url::form_urlencoded;
use hyper::Chunk;
use mime;
use controller::context::BodyContent;
pub fn parse_body(content_type: Option<&mime::Mime>, body_data: Chunk) -> Option<BodyContent>
{
if body_data.is_empty() {
None
} else {
let is_multipart_form_data = if let Some(ref content_mime) = content_type {
content_mime.type_() == mime::MULTIPART && content_mime.subtype() == mime::FORM_DATA
} else {
false
};
let body_parsed = if is_multipart_form_data {
parse_multipart_form_data(content_type, body_data)
} else {
parse_form_urlencoded(body_data)
};
Some(body_parsed)
}
}
fn parse_form_urlencoded(body_data: Chunk) -> BodyContent
{
let vec: Vec<u8> = body_data.iter().cloned().collect();
form_urlencoded::parse(vec.as_ref())
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect()
}
// TODO: realize this function
// https://github.com/abonander/multipart-async
// https://ru.wikipedia.org/wiki/HTTP#Множественное_содержимое
fn parse_multipart_form_data(content_type: Option<&mime::Mime>, body_data: Chunk) -> BodyContent
{
if let Some(bound
|
nt_type: Option<&mime::Mime>) -> Option<String> {
content_type
.and_then(|content_mime| {
content_mime.get_param(mime::BOUNDARY).map(|boundary|boundary.as_ref().into())
})
}
|
ary) = get_boundary(content_type) {
println!("multipart request received, boundary: {}", boundary);
}
parse_form_urlencoded(body_data) // TODO: this is stub
}
fn get_boundary(conte
|
identifier_body
|
body.rs
|
use url::form_urlencoded;
use hyper::Chunk;
use mime;
use controller::context::BodyContent;
pub fn parse_body(content_type: Option<&mime::Mime>, body_data: Chunk) -> Option<BodyContent>
{
if body_data.is_empty() {
None
} else {
let is_multipart_form_data = if let Some(ref content_mime) = content_type {
content_mime.type_() == mime::MULTIPART && content_mime.subtype() == mime::FORM_DATA
} else {
false
};
let body_parsed = if is_multipart_form_data {
parse_multipart_form_data(content_type, body_data)
} else
|
;
Some(body_parsed)
}
}
fn parse_form_urlencoded(body_data: Chunk) -> BodyContent
{
let vec: Vec<u8> = body_data.iter().cloned().collect();
form_urlencoded::parse(vec.as_ref())
.map(|(key, value)| (key.to_string(), value.to_string()))
.collect()
}
// TODO: realize this function
// https://github.com/abonander/multipart-async
// https://ru.wikipedia.org/wiki/HTTP#Множественное_содержимое
fn parse_multipart_form_data(content_type: Option<&mime::Mime>, body_data: Chunk) -> BodyContent
{
if let Some(boundary) = get_boundary(content_type) {
println!("multipart request received, boundary: {}", boundary);
}
parse_form_urlencoded(body_data) // TODO: this is stub
}
fn get_boundary(content_type: Option<&mime::Mime>) -> Option<String> {
content_type
.and_then(|content_mime| {
content_mime.get_param(mime::BOUNDARY).map(|boundary|boundary.as_ref().into())
})
}
|
{
parse_form_urlencoded(body_data)
}
|
conditional_block
|
mayberef.rs
|
use std::ops::Deref;
use self::MaybeRef::*;
pub enum MaybeRef<'a, T: 'a> {
Ref(&'a T),
Val(T),
}
impl<'a, T: Clone> MaybeRef<'a, T> {
pub fn take(self) -> T {
match self {
Val(t) => t,
Ref(t) => t.clone(),
}
}
}
impl<'a, T> Deref for MaybeRef<'a, T> {
type Target = T;
fn
|
(&self) -> &T {
match *self {
Ref(t) => t,
Val(ref t) => t,
}
}
}
#[cfg(test)]
mod test {
use super::MaybeRef::*;
#[test]
fn test() {
let x = "foo";
let r = Ref(&x);
let v = Val(x);
assert_eq!(r.take(), v.take());
}
}
|
deref
|
identifier_name
|
mayberef.rs
|
use std::ops::Deref;
use self::MaybeRef::*;
pub enum MaybeRef<'a, T: 'a> {
Ref(&'a T),
Val(T),
}
impl<'a, T: Clone> MaybeRef<'a, T> {
pub fn take(self) -> T {
match self {
Val(t) => t,
Ref(t) => t.clone(),
}
}
}
impl<'a, T> Deref for MaybeRef<'a, T> {
type Target = T;
fn deref(&self) -> &T {
match *self {
Ref(t) => t,
Val(ref t) => t,
}
}
}
#[cfg(test)]
mod test {
use super::MaybeRef::*;
#[test]
fn test()
|
}
|
{
let x = "foo";
let r = Ref(&x);
let v = Val(x);
assert_eq!(r.take(), v.take());
}
|
identifier_body
|
mayberef.rs
|
use std::ops::Deref;
use self::MaybeRef::*;
pub enum MaybeRef<'a, T: 'a> {
Ref(&'a T),
Val(T),
}
impl<'a, T: Clone> MaybeRef<'a, T> {
pub fn take(self) -> T {
match self {
Val(t) => t,
Ref(t) => t.clone(),
}
}
}
impl<'a, T> Deref for MaybeRef<'a, T> {
type Target = T;
fn deref(&self) -> &T {
match *self {
Ref(t) => t,
Val(ref t) => t,
}
}
}
#[cfg(test)]
mod test {
use super::MaybeRef::*;
#[test]
fn test() {
let x = "foo";
|
}
}
|
let r = Ref(&x);
let v = Val(x);
assert_eq!(r.take(), v.take());
|
random_line_split
|
bitmap_glyph.rs
|
use std::ptr::null_mut;
use { ffi, Bitmap };
pub struct BitmapGlyph {
library_raw: ffi::FT_Library,
raw: ffi::FT_BitmapGlyph
}
impl BitmapGlyph {
pub unsafe fn from_raw(library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph) -> Self {
ffi::FT_Reference_Library(library_raw);
BitmapGlyph { library_raw, raw }
}
#[inline(always)]
|
}
#[inline(always)]
pub fn top(&self) -> i32 {
unsafe {
(*self.raw).top
}
}
#[inline(always)]
pub fn bitmap(&self) -> Bitmap {
unsafe { Bitmap::from_raw(&(*self.raw).bitmap) }
}
#[inline(always)]
pub fn raw(&self) -> &ffi::FT_BitmapGlyphRec {
unsafe {
&*self.raw
}
}
}
impl Clone for BitmapGlyph {
fn clone(&self) -> Self {
let mut target = null_mut();
let err = unsafe {
ffi::FT_Glyph_Copy(self.raw as ffi::FT_Glyph, &mut target)
};
if err == ffi::FT_Err_Ok {
unsafe { BitmapGlyph::from_raw(self.library_raw, target as ffi::FT_BitmapGlyph) }
} else {
panic!("Failed to copy bitmap glyph")
}
}
}
impl Drop for BitmapGlyph {
fn drop(&mut self) {
let err = unsafe {
ffi::FT_Done_Glyph(self.raw as ffi::FT_Glyph);
ffi::FT_Done_Library(self.library_raw)
};
if err!= ffi::FT_Err_Ok {
panic!("Failed to drop library")
}
}
}
|
pub fn left(&self) -> i32 {
unsafe {
(*self.raw).left
}
|
random_line_split
|
bitmap_glyph.rs
|
use std::ptr::null_mut;
use { ffi, Bitmap };
pub struct BitmapGlyph {
library_raw: ffi::FT_Library,
raw: ffi::FT_BitmapGlyph
}
impl BitmapGlyph {
pub unsafe fn from_raw(library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph) -> Self {
ffi::FT_Reference_Library(library_raw);
BitmapGlyph { library_raw, raw }
}
#[inline(always)]
pub fn left(&self) -> i32 {
unsafe {
(*self.raw).left
}
}
#[inline(always)]
pub fn top(&self) -> i32 {
unsafe {
(*self.raw).top
}
}
#[inline(always)]
pub fn bitmap(&self) -> Bitmap {
unsafe { Bitmap::from_raw(&(*self.raw).bitmap) }
}
#[inline(always)]
pub fn raw(&self) -> &ffi::FT_BitmapGlyphRec {
unsafe {
&*self.raw
}
}
}
impl Clone for BitmapGlyph {
fn
|
(&self) -> Self {
let mut target = null_mut();
let err = unsafe {
ffi::FT_Glyph_Copy(self.raw as ffi::FT_Glyph, &mut target)
};
if err == ffi::FT_Err_Ok {
unsafe { BitmapGlyph::from_raw(self.library_raw, target as ffi::FT_BitmapGlyph) }
} else {
panic!("Failed to copy bitmap glyph")
}
}
}
impl Drop for BitmapGlyph {
fn drop(&mut self) {
let err = unsafe {
ffi::FT_Done_Glyph(self.raw as ffi::FT_Glyph);
ffi::FT_Done_Library(self.library_raw)
};
if err!= ffi::FT_Err_Ok {
panic!("Failed to drop library")
}
}
}
|
clone
|
identifier_name
|
bitmap_glyph.rs
|
use std::ptr::null_mut;
use { ffi, Bitmap };
pub struct BitmapGlyph {
library_raw: ffi::FT_Library,
raw: ffi::FT_BitmapGlyph
}
impl BitmapGlyph {
pub unsafe fn from_raw(library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph) -> Self {
ffi::FT_Reference_Library(library_raw);
BitmapGlyph { library_raw, raw }
}
#[inline(always)]
pub fn left(&self) -> i32
|
#[inline(always)]
pub fn top(&self) -> i32 {
unsafe {
(*self.raw).top
}
}
#[inline(always)]
pub fn bitmap(&self) -> Bitmap {
unsafe { Bitmap::from_raw(&(*self.raw).bitmap) }
}
#[inline(always)]
pub fn raw(&self) -> &ffi::FT_BitmapGlyphRec {
unsafe {
&*self.raw
}
}
}
impl Clone for BitmapGlyph {
fn clone(&self) -> Self {
let mut target = null_mut();
let err = unsafe {
ffi::FT_Glyph_Copy(self.raw as ffi::FT_Glyph, &mut target)
};
if err == ffi::FT_Err_Ok {
unsafe { BitmapGlyph::from_raw(self.library_raw, target as ffi::FT_BitmapGlyph) }
} else {
panic!("Failed to copy bitmap glyph")
}
}
}
impl Drop for BitmapGlyph {
fn drop(&mut self) {
let err = unsafe {
ffi::FT_Done_Glyph(self.raw as ffi::FT_Glyph);
ffi::FT_Done_Library(self.library_raw)
};
if err!= ffi::FT_Err_Ok {
panic!("Failed to drop library")
}
}
}
|
{
unsafe {
(*self.raw).left
}
}
|
identifier_body
|
bitmap_glyph.rs
|
use std::ptr::null_mut;
use { ffi, Bitmap };
pub struct BitmapGlyph {
library_raw: ffi::FT_Library,
raw: ffi::FT_BitmapGlyph
}
impl BitmapGlyph {
pub unsafe fn from_raw(library_raw: ffi::FT_Library, raw: ffi::FT_BitmapGlyph) -> Self {
ffi::FT_Reference_Library(library_raw);
BitmapGlyph { library_raw, raw }
}
#[inline(always)]
pub fn left(&self) -> i32 {
unsafe {
(*self.raw).left
}
}
#[inline(always)]
pub fn top(&self) -> i32 {
unsafe {
(*self.raw).top
}
}
#[inline(always)]
pub fn bitmap(&self) -> Bitmap {
unsafe { Bitmap::from_raw(&(*self.raw).bitmap) }
}
#[inline(always)]
pub fn raw(&self) -> &ffi::FT_BitmapGlyphRec {
unsafe {
&*self.raw
}
}
}
impl Clone for BitmapGlyph {
fn clone(&self) -> Self {
let mut target = null_mut();
let err = unsafe {
ffi::FT_Glyph_Copy(self.raw as ffi::FT_Glyph, &mut target)
};
if err == ffi::FT_Err_Ok {
unsafe { BitmapGlyph::from_raw(self.library_raw, target as ffi::FT_BitmapGlyph) }
} else {
panic!("Failed to copy bitmap glyph")
}
}
}
impl Drop for BitmapGlyph {
fn drop(&mut self) {
let err = unsafe {
ffi::FT_Done_Glyph(self.raw as ffi::FT_Glyph);
ffi::FT_Done_Library(self.library_raw)
};
if err!= ffi::FT_Err_Ok
|
}
}
|
{
panic!("Failed to drop library")
}
|
conditional_block
|
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task for asynchronous events). Akin to Gecko's
//! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures
//! that the actual SpiderMonkey GC integration occurs on the script task via
//! message passing. Ownership of a `Trusted<T>` object means the DOM object of
//! type T to which it points remains alive. Any other behaviour is undefined.
//! To guarantee the lifetime of a DOM object when performing asynchronous operations,
//! obtain a `Trusted<T>` from that object and pass it along with each operation.
//! A usable pointer to the original DOM object can be obtained on the script task
//! from a `Trusted<T>` via the `to_temporary` method.
//!
//! The implementation of Trusted<T> is as follows:
//! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object.
//! The values in this hashtable are atomic reference counts. When a Trusted<T> object is
//! created or cloned, this count is increased. When a Trusted<T> is dropped, the count
//! decreases. If the count hits zero, a message is dispatched to the script task to remove
//! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object
//! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry
//! is removed.
use core::nonzero::NonZero;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflectable, Reflector};
use dom::bindings::trace::trace_reflector;
use js::jsapi::JSTracer;
use libc;
use script_task::{CommonScriptMsg, ScriptChan};
use std::cell::RefCell;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_map::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
#[allow(missing_docs)] // FIXME
mod dummy { // Attributes don’t apply through the macro.
use std::cell::RefCell;
use std::rc::Rc;
use super::LiveDOMReferences;
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
Rc::new(RefCell::new(None)));
}
pub use self::dummy::LIVE_REFERENCES;
/// A pointer to a Rust DOM object that needs to be destroyed.
pub struct TrustedReference(*const libc::c_void);
unsafe impl Send for TrustedReference {}
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
/// DOM object is guaranteed to live at least as long as the last outstanding
/// `Trusted<T>` instance.
#[allow_unrooted_interior]
pub struct Trusted<T: Reflectable> {
/// A pointer to the Rust DOM object of type T, but void to allow
/// sending `Trusted<T>` between tasks, regardless of T's sendability.
ptr: *const libc::c_void,
refcount: Arc<Mutex<usize>>,
script_chan: Box<ScriptChan + Send>,
owner_thread: *const libc::c_void,
phantom: PhantomData<T>,
}
unsafe impl<T: Reflectable> Send for Trusted<T> {}
impl<T: Reflectable> Trusted<T> {
/// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
/// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
/// lifetime.
pub fn new(ptr: &T, script_chan: Box<ScriptChan + Send>) -> Trusted<T> {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let refcount = live_references.addref(&*ptr as *const T);
Trusted {
ptr: &*ptr as *const T as *const libc::c_void,
refcount: refcount,
script_chan: script_chan.clone(),
owner_thread: (&*live_references) as *const _ as *const libc::c_void,
phantom: PhantomData,
}
})
}
/// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
/// a different thread than the original value from which this `Trusted<T>` was
/// obtained.
pub fn root(&self) -> Root<T> {
assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
}));
unsafe {
Root::new(NonZero::new(self.ptr as *const T))
}
}
}
impl<T: Reflectable> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
{
let mut refcount = self.refcount.lock().unwrap();
*refcount += 1;
}
Trusted {
ptr: self.ptr,
refcount: self.refcount.clone(),
script_chan: self.script_chan.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) {
let mut refcount = self.refcount.lock().unwrap();
assert!(*refcount > 0);
*refcount -= 1;
if *refcount == 0 {
// It's possible this send will fail if the script task
// has already exited. There's not much we can do at this
// point though.
let msg = CommonScriptMsg::RefcountCleanup(TrustedReference(self.ptr));
let _ = self.script_chan.send(msg);
}
}
}
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
pub struct LiveDOMReferences {
// keyed on pointer to Rust DOM object
table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>>,
}
impl LiveDOMReferences {
/// Set up the task-local data required for storing the outstanding DOM references.
pub fn initialize() {
LIVE_REFERENCES.with(|ref r| {
*r.borrow_mut() = Some(LiveDOMReferences {
table: RefCell::new(HashMap::new()),
})
});
}
fn addref<T: Reflectable>(&self, ptr: *const T) -> Arc<Mutex<usize>> {
let mut table = self.table.borrow_mut();
match table.entry(ptr as *const libc::c_void) {
Occupied(mut entry) => {
let refcount = entry.get_mut();
*refcount.lock().unwrap() += 1;
refcount.clone()
}
Vacant(entry) => {
let refcount = Arc::new(Mutex::new(1));
entry.insert(refcount.clone());
refcount
}
}
}
/// Unpin the given DOM object if its refcount is 0.
pub fn cleanup(raw_reflectable: TrustedReference) {
let TrustedReference(raw_reflectable) = raw_reflectable;
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let mut table = live_references.table.borrow_mut();
match table.entry(raw_reflectable) {
Occupied(entry) => {
if *entry.get().lock().unwrap()!= 0 {
// there could have been a new reference taken since
// this message was dispatched.
return;
}
let _ = entry.remove();
}
Vacant(_) => {
|
// hashtable entry.
info!("attempt to cleanup an unrecognized reflector");
}
}
})
}
}
/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
pub unsafe extern "C" fn trace_refcounted_objects(tracer: *mut JSTracer,
_data: *mut libc::c_void) {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let table = live_references.table.borrow();
for obj in table.keys() {
let reflectable = &*(*obj as *const Reflector);
trace_reflector(tracer, "LIVE_REFERENCES", reflectable);
}
});
}
|
// there could be a cleanup message dispatched, then a new
// pinned reference obtained and released before the message
// is processed, at which point there would be no matching
|
random_line_split
|
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task for asynchronous events). Akin to Gecko's
//! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures
//! that the actual SpiderMonkey GC integration occurs on the script task via
//! message passing. Ownership of a `Trusted<T>` object means the DOM object of
//! type T to which it points remains alive. Any other behaviour is undefined.
//! To guarantee the lifetime of a DOM object when performing asynchronous operations,
//! obtain a `Trusted<T>` from that object and pass it along with each operation.
//! A usable pointer to the original DOM object can be obtained on the script task
//! from a `Trusted<T>` via the `to_temporary` method.
//!
//! The implementation of Trusted<T> is as follows:
//! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object.
//! The values in this hashtable are atomic reference counts. When a Trusted<T> object is
//! created or cloned, this count is increased. When a Trusted<T> is dropped, the count
//! decreases. If the count hits zero, a message is dispatched to the script task to remove
//! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object
//! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry
//! is removed.
use core::nonzero::NonZero;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflectable, Reflector};
use dom::bindings::trace::trace_reflector;
use js::jsapi::JSTracer;
use libc;
use script_task::{CommonScriptMsg, ScriptChan};
use std::cell::RefCell;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_map::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
#[allow(missing_docs)] // FIXME
mod dummy { // Attributes don’t apply through the macro.
use std::cell::RefCell;
use std::rc::Rc;
use super::LiveDOMReferences;
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
Rc::new(RefCell::new(None)));
}
pub use self::dummy::LIVE_REFERENCES;
/// A pointer to a Rust DOM object that needs to be destroyed.
pub struct TrustedReference(*const libc::c_void);
unsafe impl Send for TrustedReference {}
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
/// DOM object is guaranteed to live at least as long as the last outstanding
/// `Trusted<T>` instance.
#[allow_unrooted_interior]
pub struct Trusted<T: Reflectable> {
/// A pointer to the Rust DOM object of type T, but void to allow
/// sending `Trusted<T>` between tasks, regardless of T's sendability.
ptr: *const libc::c_void,
refcount: Arc<Mutex<usize>>,
script_chan: Box<ScriptChan + Send>,
owner_thread: *const libc::c_void,
phantom: PhantomData<T>,
}
unsafe impl<T: Reflectable> Send for Trusted<T> {}
impl<T: Reflectable> Trusted<T> {
/// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
/// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
/// lifetime.
pub fn new(ptr: &T, script_chan: Box<ScriptChan + Send>) -> Trusted<T> {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let refcount = live_references.addref(&*ptr as *const T);
Trusted {
ptr: &*ptr as *const T as *const libc::c_void,
refcount: refcount,
script_chan: script_chan.clone(),
owner_thread: (&*live_references) as *const _ as *const libc::c_void,
phantom: PhantomData,
}
})
}
/// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
/// a different thread than the original value from which this `Trusted<T>` was
/// obtained.
pub fn ro
|
self) -> Root<T> {
assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
}));
unsafe {
Root::new(NonZero::new(self.ptr as *const T))
}
}
}
impl<T: Reflectable> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
{
let mut refcount = self.refcount.lock().unwrap();
*refcount += 1;
}
Trusted {
ptr: self.ptr,
refcount: self.refcount.clone(),
script_chan: self.script_chan.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) {
let mut refcount = self.refcount.lock().unwrap();
assert!(*refcount > 0);
*refcount -= 1;
if *refcount == 0 {
// It's possible this send will fail if the script task
// has already exited. There's not much we can do at this
// point though.
let msg = CommonScriptMsg::RefcountCleanup(TrustedReference(self.ptr));
let _ = self.script_chan.send(msg);
}
}
}
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
pub struct LiveDOMReferences {
// keyed on pointer to Rust DOM object
table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>>,
}
impl LiveDOMReferences {
/// Set up the task-local data required for storing the outstanding DOM references.
pub fn initialize() {
LIVE_REFERENCES.with(|ref r| {
*r.borrow_mut() = Some(LiveDOMReferences {
table: RefCell::new(HashMap::new()),
})
});
}
fn addref<T: Reflectable>(&self, ptr: *const T) -> Arc<Mutex<usize>> {
let mut table = self.table.borrow_mut();
match table.entry(ptr as *const libc::c_void) {
Occupied(mut entry) => {
let refcount = entry.get_mut();
*refcount.lock().unwrap() += 1;
refcount.clone()
}
Vacant(entry) => {
let refcount = Arc::new(Mutex::new(1));
entry.insert(refcount.clone());
refcount
}
}
}
/// Unpin the given DOM object if its refcount is 0.
pub fn cleanup(raw_reflectable: TrustedReference) {
let TrustedReference(raw_reflectable) = raw_reflectable;
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let mut table = live_references.table.borrow_mut();
match table.entry(raw_reflectable) {
Occupied(entry) => {
if *entry.get().lock().unwrap()!= 0 {
// there could have been a new reference taken since
// this message was dispatched.
return;
}
let _ = entry.remove();
}
Vacant(_) => {
// there could be a cleanup message dispatched, then a new
// pinned reference obtained and released before the message
// is processed, at which point there would be no matching
// hashtable entry.
info!("attempt to cleanup an unrecognized reflector");
}
}
})
}
}
/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
pub unsafe extern "C" fn trace_refcounted_objects(tracer: *mut JSTracer,
_data: *mut libc::c_void) {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let table = live_references.table.borrow();
for obj in table.keys() {
let reflectable = &*(*obj as *const Reflector);
trace_reflector(tracer, "LIVE_REFERENCES", reflectable);
}
});
}
|
ot(&
|
identifier_name
|
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task for asynchronous events). Akin to Gecko's
//! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures
//! that the actual SpiderMonkey GC integration occurs on the script task via
//! message passing. Ownership of a `Trusted<T>` object means the DOM object of
//! type T to which it points remains alive. Any other behaviour is undefined.
//! To guarantee the lifetime of a DOM object when performing asynchronous operations,
//! obtain a `Trusted<T>` from that object and pass it along with each operation.
//! A usable pointer to the original DOM object can be obtained on the script task
//! from a `Trusted<T>` via the `to_temporary` method.
//!
//! The implementation of Trusted<T> is as follows:
//! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object.
//! The values in this hashtable are atomic reference counts. When a Trusted<T> object is
//! created or cloned, this count is increased. When a Trusted<T> is dropped, the count
//! decreases. If the count hits zero, a message is dispatched to the script task to remove
//! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object
//! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry
//! is removed.
use core::nonzero::NonZero;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflectable, Reflector};
use dom::bindings::trace::trace_reflector;
use js::jsapi::JSTracer;
use libc;
use script_task::{CommonScriptMsg, ScriptChan};
use std::cell::RefCell;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_map::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
#[allow(missing_docs)] // FIXME
mod dummy { // Attributes don’t apply through the macro.
use std::cell::RefCell;
use std::rc::Rc;
use super::LiveDOMReferences;
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
Rc::new(RefCell::new(None)));
}
pub use self::dummy::LIVE_REFERENCES;
/// A pointer to a Rust DOM object that needs to be destroyed.
pub struct TrustedReference(*const libc::c_void);
unsafe impl Send for TrustedReference {}
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
/// DOM object is guaranteed to live at least as long as the last outstanding
/// `Trusted<T>` instance.
#[allow_unrooted_interior]
pub struct Trusted<T: Reflectable> {
/// A pointer to the Rust DOM object of type T, but void to allow
/// sending `Trusted<T>` between tasks, regardless of T's sendability.
ptr: *const libc::c_void,
refcount: Arc<Mutex<usize>>,
script_chan: Box<ScriptChan + Send>,
owner_thread: *const libc::c_void,
phantom: PhantomData<T>,
}
unsafe impl<T: Reflectable> Send for Trusted<T> {}
impl<T: Reflectable> Trusted<T> {
/// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
/// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
/// lifetime.
pub fn new(ptr: &T, script_chan: Box<ScriptChan + Send>) -> Trusted<T> {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let refcount = live_references.addref(&*ptr as *const T);
Trusted {
ptr: &*ptr as *const T as *const libc::c_void,
refcount: refcount,
script_chan: script_chan.clone(),
owner_thread: (&*live_references) as *const _ as *const libc::c_void,
phantom: PhantomData,
}
})
}
/// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
/// a different thread than the original value from which this `Trusted<T>` was
/// obtained.
pub fn root(&self) -> Root<T> {
assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
}));
unsafe {
Root::new(NonZero::new(self.ptr as *const T))
}
}
}
impl<T: Reflectable> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
{
let mut refcount = self.refcount.lock().unwrap();
*refcount += 1;
}
Trusted {
ptr: self.ptr,
refcount: self.refcount.clone(),
script_chan: self.script_chan.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) {
let mut refcount = self.refcount.lock().unwrap();
assert!(*refcount > 0);
*refcount -= 1;
if *refcount == 0 {
// It's possible this send will fail if the script task
// has already exited. There's not much we can do at this
// point though.
let msg = CommonScriptMsg::RefcountCleanup(TrustedReference(self.ptr));
let _ = self.script_chan.send(msg);
}
}
}
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
pub struct LiveDOMReferences {
// keyed on pointer to Rust DOM object
table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>>,
}
impl LiveDOMReferences {
/// Set up the task-local data required for storing the outstanding DOM references.
pub fn initialize() {
LIVE_REFERENCES.with(|ref r| {
*r.borrow_mut() = Some(LiveDOMReferences {
table: RefCell::new(HashMap::new()),
})
});
}
fn addref<T: Reflectable>(&self, ptr: *const T) -> Arc<Mutex<usize>> {
let mut table = self.table.borrow_mut();
match table.entry(ptr as *const libc::c_void) {
Occupied(mut entry) => {
let refcount = entry.get_mut();
*refcount.lock().unwrap() += 1;
refcount.clone()
}
Vacant(entry) => {
|
}
}
/// Unpin the given DOM object if its refcount is 0.
pub fn cleanup(raw_reflectable: TrustedReference) {
let TrustedReference(raw_reflectable) = raw_reflectable;
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let mut table = live_references.table.borrow_mut();
match table.entry(raw_reflectable) {
Occupied(entry) => {
if *entry.get().lock().unwrap()!= 0 {
// there could have been a new reference taken since
// this message was dispatched.
return;
}
let _ = entry.remove();
}
Vacant(_) => {
// there could be a cleanup message dispatched, then a new
// pinned reference obtained and released before the message
// is processed, at which point there would be no matching
// hashtable entry.
info!("attempt to cleanup an unrecognized reflector");
}
}
})
}
}
/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
pub unsafe extern "C" fn trace_refcounted_objects(tracer: *mut JSTracer,
_data: *mut libc::c_void) {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let table = live_references.table.borrow();
for obj in table.keys() {
let reflectable = &*(*obj as *const Reflector);
trace_reflector(tracer, "LIVE_REFERENCES", reflectable);
}
});
}
|
let refcount = Arc::new(Mutex::new(1));
entry.insert(refcount.clone());
refcount
}
|
conditional_block
|
refcounted.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/. */
//! A generic, safe mechanism by which DOM objects can be pinned and transferred
//! between tasks (or intra-task for asynchronous events). Akin to Gecko's
//! nsMainThreadPtrHandle, this uses thread-safe reference counting and ensures
//! that the actual SpiderMonkey GC integration occurs on the script task via
//! message passing. Ownership of a `Trusted<T>` object means the DOM object of
//! type T to which it points remains alive. Any other behaviour is undefined.
//! To guarantee the lifetime of a DOM object when performing asynchronous operations,
//! obtain a `Trusted<T>` from that object and pass it along with each operation.
//! A usable pointer to the original DOM object can be obtained on the script task
//! from a `Trusted<T>` via the `to_temporary` method.
//!
//! The implementation of Trusted<T> is as follows:
//! A hashtable resides in the script task, keyed on the pointer to the Rust DOM object.
//! The values in this hashtable are atomic reference counts. When a Trusted<T> object is
//! created or cloned, this count is increased. When a Trusted<T> is dropped, the count
//! decreases. If the count hits zero, a message is dispatched to the script task to remove
//! the entry from the hashmap if the count is still zero. The JS reflector for the DOM object
//! is rooted when a hashmap entry is first created, and unrooted when the hashmap entry
//! is removed.
use core::nonzero::NonZero;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflectable, Reflector};
use dom::bindings::trace::trace_reflector;
use js::jsapi::JSTracer;
use libc;
use script_task::{CommonScriptMsg, ScriptChan};
use std::cell::RefCell;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::hash_map::HashMap;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex};
#[allow(missing_docs)] // FIXME
mod dummy { // Attributes don’t apply through the macro.
use std::cell::RefCell;
use std::rc::Rc;
use super::LiveDOMReferences;
thread_local!(pub static LIVE_REFERENCES: Rc<RefCell<Option<LiveDOMReferences>>> =
Rc::new(RefCell::new(None)));
}
pub use self::dummy::LIVE_REFERENCES;
/// A pointer to a Rust DOM object that needs to be destroyed.
pub struct TrustedReference(*const libc::c_void);
unsafe impl Send for TrustedReference {}
/// A safe wrapper around a raw pointer to a DOM object that can be
/// shared among tasks for use in asynchronous operations. The underlying
/// DOM object is guaranteed to live at least as long as the last outstanding
/// `Trusted<T>` instance.
#[allow_unrooted_interior]
pub struct Trusted<T: Reflectable> {
/// A pointer to the Rust DOM object of type T, but void to allow
/// sending `Trusted<T>` between tasks, regardless of T's sendability.
ptr: *const libc::c_void,
refcount: Arc<Mutex<usize>>,
script_chan: Box<ScriptChan + Send>,
owner_thread: *const libc::c_void,
phantom: PhantomData<T>,
}
unsafe impl<T: Reflectable> Send for Trusted<T> {}
impl<T: Reflectable> Trusted<T> {
/// Create a new `Trusted<T>` instance from an existing DOM pointer. The DOM object will
/// be prevented from being GCed for the duration of the resulting `Trusted<T>` object's
/// lifetime.
pub fn new(ptr: &T, script_chan: Box<ScriptChan + Send>) -> Trusted<T> {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let refcount = live_references.addref(&*ptr as *const T);
Trusted {
ptr: &*ptr as *const T as *const libc::c_void,
refcount: refcount,
script_chan: script_chan.clone(),
owner_thread: (&*live_references) as *const _ as *const libc::c_void,
phantom: PhantomData,
}
})
}
/// Obtain a usable DOM pointer from a pinned `Trusted<T>` value. Fails if used on
/// a different thread than the original value from which this `Trusted<T>` was
/// obtained.
pub fn root(&self) -> Root<T> {
assert!(LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
self.owner_thread == (&*live_references) as *const _ as *const libc::c_void
}));
unsafe {
Root::new(NonZero::new(self.ptr as *const T))
}
}
}
impl<T: Reflectable> Clone for Trusted<T> {
fn clone(&self) -> Trusted<T> {
{
let mut refcount = self.refcount.lock().unwrap();
*refcount += 1;
}
Trusted {
ptr: self.ptr,
refcount: self.refcount.clone(),
script_chan: self.script_chan.clone(),
owner_thread: self.owner_thread,
phantom: PhantomData,
}
}
}
impl<T: Reflectable> Drop for Trusted<T> {
fn drop(&mut self) {
let mut refcount = self.refcount.lock().unwrap();
assert!(*refcount > 0);
*refcount -= 1;
if *refcount == 0 {
// It's possible this send will fail if the script task
// has already exited. There's not much we can do at this
// point though.
let msg = CommonScriptMsg::RefcountCleanup(TrustedReference(self.ptr));
let _ = self.script_chan.send(msg);
}
}
}
/// The set of live, pinned DOM objects that are currently prevented
/// from being garbage collected due to outstanding references.
pub struct LiveDOMReferences {
// keyed on pointer to Rust DOM object
table: RefCell<HashMap<*const libc::c_void, Arc<Mutex<usize>>>>,
}
impl LiveDOMReferences {
/// Set up the task-local data required for storing the outstanding DOM references.
pub fn initialize() {
LIVE_REFERENCES.with(|ref r| {
*r.borrow_mut() = Some(LiveDOMReferences {
table: RefCell::new(HashMap::new()),
})
});
}
fn addref<T: Reflectable>(&self, ptr: *const T) -> Arc<Mutex<usize>> {
let mut table = self.table.borrow_mut();
match table.entry(ptr as *const libc::c_void) {
Occupied(mut entry) => {
let refcount = entry.get_mut();
*refcount.lock().unwrap() += 1;
refcount.clone()
}
Vacant(entry) => {
let refcount = Arc::new(Mutex::new(1));
entry.insert(refcount.clone());
refcount
}
}
}
/// Unpin the given DOM object if its refcount is 0.
pub fn cleanup(raw_reflectable: TrustedReference) {
|
info!("attempt to cleanup an unrecognized reflector");
}
}
})
}
}
/// A JSTraceDataOp for tracing reflectors held in LIVE_REFERENCES
pub unsafe extern "C" fn trace_refcounted_objects(tracer: *mut JSTracer,
_data: *mut libc::c_void) {
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let table = live_references.table.borrow();
for obj in table.keys() {
let reflectable = &*(*obj as *const Reflector);
trace_reflector(tracer, "LIVE_REFERENCES", reflectable);
}
});
}
|
let TrustedReference(raw_reflectable) = raw_reflectable;
LIVE_REFERENCES.with(|ref r| {
let r = r.borrow();
let live_references = r.as_ref().unwrap();
let mut table = live_references.table.borrow_mut();
match table.entry(raw_reflectable) {
Occupied(entry) => {
if *entry.get().lock().unwrap() != 0 {
// there could have been a new reference taken since
// this message was dispatched.
return;
}
let _ = entry.remove();
}
Vacant(_) => {
// there could be a cleanup message dispatched, then a new
// pinned reference obtained and released before the message
// is processed, at which point there would be no matching
// hashtable entry.
|
identifier_body
|
address.rs
|
//! Ethereum address
use std::str::FromStr;
use std::fmt;
use utils::bigint::M256;
use utils::{read_hex, ParseHexError};
use rlp::{Encodable, RlpStream};
#[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)]
/// Represents an Ethereum address. This address is 20 bytes long.
pub struct Address([u8; 20]);
impl Address {
/// Bits needed to represent this value.
pub fn bits(&self) -> usize {
let u: M256 = self.clone().into();
u.bits()
}
}
impl Default for Address {
fn default() -> Address {
Address([0u8; 20])
}
}
impl Encodable for Address {
fn rlp_append(&self, s: &mut RlpStream) {
let buffer: [u8; 20] = self.clone().into();
s.encoder().encode_value(&buffer);
}
}
impl Into<M256> for Address {
fn into(self) -> M256 {
M256::from(self.0.as_ref())
}
}
impl From<M256> for Address {
fn from(mut val: M256) -> Address {
let mut i = 20;
let mut a = [0u8; 20];
while i!= 0 {
let u: u64 = (val & 0xFF.into()).into();
a[i-1] = u as u8;
i -= 1;
val = val >> 8;
}
Address(a)
}
}
impl Into<[u8; 20]> for Address {
fn into(self) -> [u8; 20] {
self.0
}
}
impl FromStr for Address {
type Err = ParseHexError;
fn from_str(s: &str) -> Result<Address, ParseHexError> {
read_hex(s).and_then(|v| {
if v.len() > 20 {
Err(ParseHexError::TooLong)
} else if v.len() < 20 {
Err(ParseHexError::TooShort)
} else {
let mut a = [0u8; 20];
for i in 0..20 {
a[i] = v[i];
}
Ok(Address(a))
}
})
}
}
impl fmt::LowerHex for Address {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..20 {
write!(f, "{:02x}", self.0[i])?;
}
Ok(())
}
}
impl fmt::UpperHex for Address {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
|
}
|
{
for i in 0..20 {
write!(f, "{:02X}", self.0[i])?;
}
Ok(())
}
|
identifier_body
|
address.rs
|
//! Ethereum address
use std::str::FromStr;
use std::fmt;
use utils::bigint::M256;
use utils::{read_hex, ParseHexError};
use rlp::{Encodable, RlpStream};
#[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)]
/// Represents an Ethereum address. This address is 20 bytes long.
pub struct Address([u8; 20]);
impl Address {
/// Bits needed to represent this value.
pub fn bits(&self) -> usize {
let u: M256 = self.clone().into();
u.bits()
}
}
impl Default for Address {
fn default() -> Address {
Address([0u8; 20])
}
}
impl Encodable for Address {
fn rlp_append(&self, s: &mut RlpStream) {
let buffer: [u8; 20] = self.clone().into();
s.encoder().encode_value(&buffer);
}
}
impl Into<M256> for Address {
fn into(self) -> M256 {
M256::from(self.0.as_ref())
}
}
impl From<M256> for Address {
fn from(mut val: M256) -> Address {
let mut i = 20;
let mut a = [0u8; 20];
while i!= 0 {
let u: u64 = (val & 0xFF.into()).into();
a[i-1] = u as u8;
i -= 1;
val = val >> 8;
}
Address(a)
}
}
impl Into<[u8; 20]> for Address {
fn
|
(self) -> [u8; 20] {
self.0
}
}
impl FromStr for Address {
type Err = ParseHexError;
fn from_str(s: &str) -> Result<Address, ParseHexError> {
read_hex(s).and_then(|v| {
if v.len() > 20 {
Err(ParseHexError::TooLong)
} else if v.len() < 20 {
Err(ParseHexError::TooShort)
} else {
let mut a = [0u8; 20];
for i in 0..20 {
a[i] = v[i];
}
Ok(Address(a))
}
})
}
}
impl fmt::LowerHex for Address {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..20 {
write!(f, "{:02x}", self.0[i])?;
}
Ok(())
}
}
impl fmt::UpperHex for Address {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..20 {
write!(f, "{:02X}", self.0[i])?;
}
Ok(())
}
}
|
into
|
identifier_name
|
address.rs
|
//! Ethereum address
use std::str::FromStr;
use std::fmt;
use utils::bigint::M256;
use utils::{read_hex, ParseHexError};
use rlp::{Encodable, RlpStream};
#[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)]
/// Represents an Ethereum address. This address is 20 bytes long.
pub struct Address([u8; 20]);
impl Address {
/// Bits needed to represent this value.
pub fn bits(&self) -> usize {
let u: M256 = self.clone().into();
u.bits()
}
}
impl Default for Address {
fn default() -> Address {
Address([0u8; 20])
}
}
impl Encodable for Address {
fn rlp_append(&self, s: &mut RlpStream) {
let buffer: [u8; 20] = self.clone().into();
s.encoder().encode_value(&buffer);
}
}
impl Into<M256> for Address {
fn into(self) -> M256 {
M256::from(self.0.as_ref())
}
}
impl From<M256> for Address {
fn from(mut val: M256) -> Address {
let mut i = 20;
let mut a = [0u8; 20];
while i!= 0 {
let u: u64 = (val & 0xFF.into()).into();
a[i-1] = u as u8;
i -= 1;
val = val >> 8;
}
|
impl Into<[u8; 20]> for Address {
fn into(self) -> [u8; 20] {
self.0
}
}
impl FromStr for Address {
type Err = ParseHexError;
fn from_str(s: &str) -> Result<Address, ParseHexError> {
read_hex(s).and_then(|v| {
if v.len() > 20 {
Err(ParseHexError::TooLong)
} else if v.len() < 20 {
Err(ParseHexError::TooShort)
} else {
let mut a = [0u8; 20];
for i in 0..20 {
a[i] = v[i];
}
Ok(Address(a))
}
})
}
}
impl fmt::LowerHex for Address {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..20 {
write!(f, "{:02x}", self.0[i])?;
}
Ok(())
}
}
impl fmt::UpperHex for Address {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..20 {
write!(f, "{:02X}", self.0[i])?;
}
Ok(())
}
}
|
Address(a)
}
}
|
random_line_split
|
mod.rs
|
type.
#[experimental = "implementation detail of the `format_args!` macro"]
pub struct Argument<'a> {
formatter: extern "Rust" fn(&Void, &mut Formatter) -> Result,
value: &'a Void,
}
impl<'a> Arguments<'a> {
/// When using the format_args!() macro, this function is used to generate the
/// Arguments structure. The compiler inserts an `unsafe` block to call this,
/// which is valid because the compiler performs all necessary validation to
/// ensure that the resulting call to format/write would be safe.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub unsafe fn new<'a>(pieces: &'static [&'static str],
args: &'a [Argument<'a>]) -> Arguments<'a> {
Arguments {
pieces: mem::transmute(pieces),
fmt: None,
args: args
}
}
/// This function is used to specify nonstandard formatting parameters.
/// The `pieces` array must be at least as long as `fmt` to construct
/// a valid Arguments structure.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub unsafe fn with_placeholders<'a>(pieces: &'static [&'static str],
fmt: &'static [rt::Argument<'static>],
args: &'a [Argument<'a>]) -> Arguments<'a> {
Arguments {
pieces: mem::transmute(pieces),
fmt: Some(mem::transmute(fmt)),
args: args
}
}
}
/// This structure represents a safely precompiled version of a format string
/// and its arguments. This cannot be generated at runtime because it cannot
/// safely be done so, so no constructors are given and the fields are private
/// to prevent modification.
///
/// The `format_args!` macro will safely create an instance of this structure
/// and pass it to a function or closure, passed as the first argument. The
/// macro validates the format string at compile-time so usage of the `write`
/// and `format` functions can be safely performed.
#[stable]
pub struct Arguments<'a> {
// Format string pieces to print.
pieces: &'a [&'a str],
// Placeholder specs, or `None` if all specs are default (as in "{}{}").
fmt: Option<&'a [rt::Argument<'a>]>,
// Dynamic arguments for interpolation, to be interleaved with string
// pieces. (Every argument is preceded by a string piece.)
args: &'a [Argument<'a>],
}
impl<'a> Show for Arguments<'a> {
fn fmt(&self, fmt: &mut Formatter) -> Result
|
}
/// When a format is not otherwise specified, types are formatted by ascribing
/// to this trait. There is not an explicit way of selecting this trait to be
/// used for formatting, it is only if no other format is specified.
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Show for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `o` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Octal for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `t` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Binary for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `x` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait LowerHex for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `X` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait UpperHex for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `p` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Pointer for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `e` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait LowerExp for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `E` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait UpperExp for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
static DEFAULT_ARGUMENT: rt::Argument<'static> = rt::Argument {
position: rt::ArgumentNext,
format: rt::FormatSpec {
fill:'',
align: rt::AlignUnknown,
flags: 0,
precision: rt::CountImplied,
width: rt::CountImplied,
}
};
/// The `write` function takes an output stream, a precompiled format string,
/// and a list of arguments. The arguments will be formatted according to the
/// specified format string into the output stream provided.
///
/// # Arguments
///
/// * output - the buffer to write output to
/// * args - the precompiled arguments generated by `format_args!`
#[experimental = "libcore and I/O have yet to be reconciled, and this is an \
implementation detail which should not otherwise be exported"]
pub fn write(output: &mut FormatWriter, args: &Arguments) -> Result {
let mut formatter = Formatter {
flags: 0,
width: None,
precision: None,
buf: output,
align: rt::AlignUnknown,
fill:'',
args: args.args,
curarg: args.args.iter(),
};
let mut pieces = args.pieces.iter();
match args.fmt {
None => {
// We can use default formatting parameters for all arguments.
for _ in range(0, args.args.len()) {
try!(formatter.buf.write(pieces.next().unwrap().as_bytes()));
try!(formatter.run(&DEFAULT_ARGUMENT));
}
}
Some(fmt) => {
// Every spec has a corresponding argument that is preceded by
// a string piece.
for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
try!(formatter.buf.write(piece.as_bytes()));
try!(formatter.run(arg));
}
}
}
// There can be only one trailing string piece left.
match pieces.next() {
Some(piece) => {
try!(formatter.buf.write(piece.as_bytes()));
}
None => {}
}
Ok(())
}
impl<'a> Formatter<'a> {
// First up is the collection of functions used to execute a format string
// at runtime. This consumes all of the compile-time statics generated by
// the format! syntax extension.
fn run(&mut self, arg: &rt::Argument) -> Result {
// Fill in the format parameters into the formatter
self.fill = arg.format.fill;
self.align = arg.format.align;
self.flags = arg.format.flags;
self.width = self.getcount(&arg.format.width);
self.precision = self.getcount(&arg.format.precision);
// Extract the correct argument
let value = match arg.position {
rt::ArgumentNext => { *self.curarg.next().unwrap() }
rt::ArgumentIs(i) => self.args[i],
};
// Then actually do some printing
(value.formatter)(value.value, self)
}
fn getcount(&mut self, cnt: &rt::Count) -> Option<uint> {
match *cnt {
rt::CountIs(n) => { Some(n) }
rt::CountImplied => { None }
rt::CountIsParam(i) => {
let v = self.args[i].value;
unsafe { Some(*(v as *const _ as *const uint)) }
}
rt::CountIsNextParam => {
let v = self.curarg.next().unwrap().value;
unsafe { Some(*(v as *const _ as *const uint)) }
}
}
}
// Helper methods used for padding and processing formatting arguments that
// all formatting traits can use.
/// Performs the correct padding for an integer which has already been
/// emitted into a byte-array. The byte-array should *not* contain the sign
/// for the integer, that will be added by this method.
///
/// # Arguments
///
/// * is_positive - whether the original integer was positive or not.
/// * prefix - if the '#' character (FlagAlternate) is provided, this
/// is the prefix to put in front of the number.
/// * buf - the byte array that the number has been formatted into
///
/// This function will correctly account for the flags provided as well as
/// the minimum width. It will not take precision into account.
#[unstable = "definition may change slightly over time"]
pub fn pad_integral(&mut self,
is_positive: bool,
prefix: &str,
buf: &[u8])
-> Result {
use char::Char;
use fmt::rt::{FlagAlternate, FlagSignPlus, FlagSignAwareZeroPad};
let mut width = buf.len();
let mut sign = None;
if!is_positive {
sign = Some('-'); width += 1;
} else if self.flags & (1 << (FlagSignPlus as uint))!= 0 {
sign = Some('+'); width += 1;
}
let mut prefixed = false;
if self.flags & (1 << (FlagAlternate as uint))!= 0 {
prefixed = true; width += prefix.char_len();
}
// Writes the sign if it exists, and then the prefix if it was requested
let write_prefix = |f: &mut Formatter| {
for c in sign.into_iter() {
let mut b = [0,..4];
let n = c.encode_utf8(&mut b).unwrap_or(0);
try!(f.buf.write(b[..n]));
}
if prefixed { f.buf.write(prefix.as_bytes()) }
else { Ok(()) }
};
// The `width` field is more of a `min-width` parameter at this point.
match self.width {
// If there's no minimum length requirements then we can just
// write the bytes.
None => {
try!(write_prefix(self)); self.buf.write(buf)
}
// Check if we're over the minimum width, if so then we can also
// just write the bytes.
Some(min) if width >= min => {
try!(write_prefix(self)); self.buf.write(buf)
}
// The sign and prefix goes before the padding if the fill character
// is zero
Some(min) if self.flags & (1 << (FlagSignAwareZeroPad as uint))!= 0 => {
self.fill = '0';
try!(write_prefix(self));
self.with_padding(min - width, rt::AlignRight, |f| f.buf.write(buf))
}
// Otherwise, the sign and prefix goes after the padding
Some(min) => {
self.with_padding(min - width, rt::AlignRight, |f| {
try!(write_prefix(f)); f.buf.write(buf)
})
}
}
}
/// This function takes a string slice and emits it to the internal buffer
/// after applying the relevant formatting flags specified. The flags
/// recognized for generic strings are:
///
/// * width - the minimum width of what to emit
/// * fill/align - what to emit and where to emit it if the string
/// provided needs to be padded
/// * precision - the maximum length to emit, the string is truncated if it
/// is longer than this length
///
/// Notably this function ignored the `flag` parameters
#[unstable = "definition may change slightly over time"]
pub fn pad(&mut self, s: &str) -> Result {
// Make sure there's a fast path up front
if self.width.is_none() && self.precision.is_none() {
return self.buf.write(s.as_bytes());
}
// The `precision` field can be interpreted as a `max-width` for the
// string being formatted
match self.precision {
Some(max) => {
// If there's a maximum width and our string is longer than
// that, then we must always have truncation. This is the only
// case where the maximum length will matter.
let char_len = s.char_len();
if char_len >= max {
let nchars = ::cmp::min(max, char_len);
return self.buf.write(s.slice_chars(0, nchars).as_bytes());
}
}
None => {}
}
// The `width` field is more of a `min-width` parameter at this point.
match self.width {
// If we're under the maximum length, and there's no minimum length
// requirements, then we can just emit the string
None => self.buf.write(s.as_bytes()),
// If we're under the maximum width, check if we're over the minimum
// width, if so it's as easy as just emitting the string.
Some(width) if s.char_len() >= width => {
self.buf.write(s.as_bytes())
}
// If we're under both the maximum and the minimum width, then fill
// up the minimum width with the specified string + some alignment.
Some(width) => {
self.with_padding(width - s.char_len(), rt::AlignLeft, |me| {
me.buf.write(s.as_bytes())
})
}
}
}
/// Runs a callback, emitting the correct padding either before or
/// afterwards depending on whether right or left alignment is requested.
fn with_padding(&mut self,
padding: uint,
default: rt::Alignment,
f: |&mut Formatter| -> Result) -> Result {
use char::Char;
let align = match self.align {
rt::AlignUnknown => default,
_ => self.align
};
let (pre_pad, post_pad) = match align {
rt::AlignLeft => (0u, padding),
rt::AlignRight | rt::AlignUnknown => (padding, 0u),
rt::AlignCenter => (padding / 2, (padding + 1) / 2),
};
let mut fill = [0u8,..4];
let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
for _ in range(0, pre_pad) {
try!(self.buf.write(fill[..len]));
}
try!(f(self));
for _ in range(0, post_pad) {
try!(self.buf.write(fill[..len]));
}
Ok(())
}
/// Writes some data to the underlying buffer contained within this
/// formatter.
#[unstable = "reconciling core and I/O may alter this definition"]
pub fn write(&mut self, data: &[u8]) -> Result {
self.buf.write(data)
}
/// Writes some formatted information into this instance
#[unstable = "reconciling core and I/O may alter this definition"]
pub fn write_fmt(&mut self, fmt: &Arguments) -> Result {
write(self.buf, fmt)
}
/// Flags for formatting (packed version of rt::Flag)
#[experimental = "return type may change and method was just created"]
pub fn flags(&self) -> uint { self.flags }
/// Character used as 'fill' whenever there is alignment
#[unstable = "method was just created"]
pub fn fill(&self) -> char { self.fill }
/// Flag indicating what form of alignment was requested
#[unstable = "method was just created"]
pub fn align(&self) -> rt::Alignment { self.align }
/// Optionally specified integer width that the output should be
#[unstable = "method was just created"]
pub fn width(&self) -> Option<uint> { self.width }
/// Optionally specified precision for numeric types
#[unstable = "method was just created"]
pub fn precision(&self) -> Option<uint> { self.precision }
}
impl Show for Error {
fn fmt(&self, f: &mut Formatter) -> Result {
"an error occurred when formatting an argument".fmt(f)
}
}
/// This is a function which calls are emitted to by the compiler itself to
/// create the Argument structures that are passed into the `format` function.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result,
t: &'a T) -> Argument<'a> {
unsafe {
Argument {
formatter: mem::transmute(f),
value: mem::transmute(t)
}
}
}
/// When the compiler determines that the type of an argument *must* be a string
/// (such as for select), then it invokes this method.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argumentstr<'a>(s: &'a &str) -> Argument<'a> {
argument(Show::fmt, s)
}
/// When the compiler determines that the type of an argument *must* be a uint
/// (such as for plural), then it invokes this method.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
argument(Show::fmt, s)
}
// Implementations of the core formatting traits
impl<'a, Sized? T: Show> Show for &'a T {
fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
}
impl<'a, Sized? T: Show> Show for &'a mut T {
fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
}
impl<'a> Show for &'a Show+'a {
fn fmt(&self, f: &mut Formatter) -> Result { (*self).fmt(f) }
}
impl Show for bool {
fn fmt(&self, f: &mut Formatter) -> Result {
Show::fmt(if *self { "true" } else { "false" }, f)
}
}
impl Show for str {
fn fmt(&self, f: &mut Formatter) -> Result {
f.pad(self)
}
}
impl Show for char {
fn fmt(&self, f: &mut Formatter) -> Result {
use char::Char;
let mut utf8 = [0u8,..4];
let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
let s: &str = unsafe { mem::transmute(utf8[..amt]) };
Show::fmt(s, f)
}
}
impl<T> Pointer for *const T {
fn fmt(&self, f: &mut Formatter) -> Result {
f.flags |= 1 << (rt::FlagAlternate as uint);
LowerHex::fmt(&(*self as uint), f)
}
}
impl<T> Pointer for *mut T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(*self as *const T), f)
}
}
impl<'a, T> Pointer for &'a T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(*self as *const T), f)
}
}
impl<'a, T> Pointer for &'a mut T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(&**self as *const T), f)
}
}
macro_rules! floating(($ty:ident) => {
impl Show for $ty {
fn fmt(&self, fmt: &mut Formatter) -> Result {
use num::Float;
let digits = match fmt.precision {
Some(i) => float::DigExact(i),
None => float::DigMax(6),
};
float::float_to_str_bytes_common(self.abs(),
10,
true,
float::SignNeg,
digits,
float::ExpNone,
false,
|bytes| {
fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
})
}
}
impl LowerExp for $ty {
fn fmt(&self, fmt: &mut Formatter) -> Result {
use num::Float;
let digits = match fmt.precision {
Some(i) => float::DigExact(i),
None => float::DigMax(6),
};
float::float_to_str_bytes_common(self.abs(),
|
{
write(fmt.buf, self)
}
|
identifier_body
|
mod.rs
|
type.
#[experimental = "implementation detail of the `format_args!` macro"]
pub struct Argument<'a> {
formatter: extern "Rust" fn(&Void, &mut Formatter) -> Result,
value: &'a Void,
}
impl<'a> Arguments<'a> {
/// When using the format_args!() macro, this function is used to generate the
/// Arguments structure. The compiler inserts an `unsafe` block to call this,
/// which is valid because the compiler performs all necessary validation to
/// ensure that the resulting call to format/write would be safe.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub unsafe fn new<'a>(pieces: &'static [&'static str],
args: &'a [Argument<'a>]) -> Arguments<'a> {
Arguments {
pieces: mem::transmute(pieces),
fmt: None,
args: args
}
}
/// This function is used to specify nonstandard formatting parameters.
/// The `pieces` array must be at least as long as `fmt` to construct
/// a valid Arguments structure.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub unsafe fn with_placeholders<'a>(pieces: &'static [&'static str],
fmt: &'static [rt::Argument<'static>],
args: &'a [Argument<'a>]) -> Arguments<'a> {
Arguments {
pieces: mem::transmute(pieces),
fmt: Some(mem::transmute(fmt)),
args: args
}
}
}
/// This structure represents a safely precompiled version of a format string
/// and its arguments. This cannot be generated at runtime because it cannot
/// safely be done so, so no constructors are given and the fields are private
/// to prevent modification.
///
/// The `format_args!` macro will safely create an instance of this structure
/// and pass it to a function or closure, passed as the first argument. The
/// macro validates the format string at compile-time so usage of the `write`
/// and `format` functions can be safely performed.
#[stable]
pub struct Arguments<'a> {
// Format string pieces to print.
pieces: &'a [&'a str],
// Placeholder specs, or `None` if all specs are default (as in "{}{}").
fmt: Option<&'a [rt::Argument<'a>]>,
// Dynamic arguments for interpolation, to be interleaved with string
// pieces. (Every argument is preceded by a string piece.)
args: &'a [Argument<'a>],
}
impl<'a> Show for Arguments<'a> {
fn fmt(&self, fmt: &mut Formatter) -> Result {
write(fmt.buf, self)
}
}
/// When a format is not otherwise specified, types are formatted by ascribing
/// to this trait. There is not an explicit way of selecting this trait to be
/// used for formatting, it is only if no other format is specified.
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Show for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `o` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Octal for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `t` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Binary for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `x` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait LowerHex for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `X` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait UpperHex for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `p` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Pointer for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `e` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait LowerExp for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `E` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait UpperExp for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
static DEFAULT_ARGUMENT: rt::Argument<'static> = rt::Argument {
position: rt::ArgumentNext,
format: rt::FormatSpec {
fill:'',
align: rt::AlignUnknown,
flags: 0,
precision: rt::CountImplied,
width: rt::CountImplied,
}
};
/// The `write` function takes an output stream, a precompiled format string,
/// and a list of arguments. The arguments will be formatted according to the
/// specified format string into the output stream provided.
///
/// # Arguments
///
/// * output - the buffer to write output to
/// * args - the precompiled arguments generated by `format_args!`
#[experimental = "libcore and I/O have yet to be reconciled, and this is an \
implementation detail which should not otherwise be exported"]
pub fn write(output: &mut FormatWriter, args: &Arguments) -> Result {
let mut formatter = Formatter {
flags: 0,
width: None,
precision: None,
buf: output,
align: rt::AlignUnknown,
fill:'',
args: args.args,
curarg: args.args.iter(),
};
let mut pieces = args.pieces.iter();
match args.fmt {
None => {
// We can use default formatting parameters for all arguments.
for _ in range(0, args.args.len()) {
try!(formatter.buf.write(pieces.next().unwrap().as_bytes()));
try!(formatter.run(&DEFAULT_ARGUMENT));
}
}
Some(fmt) => {
// Every spec has a corresponding argument that is preceded by
// a string piece.
for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
try!(formatter.buf.write(piece.as_bytes()));
try!(formatter.run(arg));
}
}
}
// There can be only one trailing string piece left.
match pieces.next() {
Some(piece) => {
try!(formatter.buf.write(piece.as_bytes()));
}
None => {}
}
Ok(())
}
impl<'a> Formatter<'a> {
// First up is the collection of functions used to execute a format string
// at runtime. This consumes all of the compile-time statics generated by
// the format! syntax extension.
fn run(&mut self, arg: &rt::Argument) -> Result {
// Fill in the format parameters into the formatter
self.fill = arg.format.fill;
self.align = arg.format.align;
self.flags = arg.format.flags;
self.width = self.getcount(&arg.format.width);
self.precision = self.getcount(&arg.format.precision);
// Extract the correct argument
let value = match arg.position {
rt::ArgumentNext => { *self.curarg.next().unwrap() }
rt::ArgumentIs(i) => self.args[i],
};
// Then actually do some printing
(value.formatter)(value.value, self)
}
fn getcount(&mut self, cnt: &rt::Count) -> Option<uint> {
match *cnt {
rt::CountIs(n) => { Some(n) }
rt::CountImplied => { None }
rt::CountIsParam(i) => {
let v = self.args[i].value;
unsafe { Some(*(v as *const _ as *const uint)) }
}
rt::CountIsNextParam => {
let v = self.curarg.next().unwrap().value;
unsafe { Some(*(v as *const _ as *const uint)) }
}
}
}
// Helper methods used for padding and processing formatting arguments that
// all formatting traits can use.
/// Performs the correct padding for an integer which has already been
/// emitted into a byte-array. The byte-array should *not* contain the sign
/// for the integer, that will be added by this method.
///
/// # Arguments
///
/// * is_positive - whether the original integer was positive or not.
/// * prefix - if the '#' character (FlagAlternate) is provided, this
/// is the prefix to put in front of the number.
/// * buf - the byte array that the number has been formatted into
///
/// This function will correctly account for the flags provided as well as
/// the minimum width. It will not take precision into account.
#[unstable = "definition may change slightly over time"]
pub fn pad_integral(&mut self,
is_positive: bool,
prefix: &str,
buf: &[u8])
-> Result {
use char::Char;
use fmt::rt::{FlagAlternate, FlagSignPlus, FlagSignAwareZeroPad};
let mut width = buf.len();
let mut sign = None;
if!is_positive {
sign = Some('-'); width += 1;
} else if self.flags & (1 << (FlagSignPlus as uint))!= 0 {
sign = Some('+'); width += 1;
}
let mut prefixed = false;
if self.flags & (1 << (FlagAlternate as uint))!= 0 {
prefixed = true; width += prefix.char_len();
}
// Writes the sign if it exists, and then the prefix if it was requested
let write_prefix = |f: &mut Formatter| {
for c in sign.into_iter() {
let mut b = [0,..4];
let n = c.encode_utf8(&mut b).unwrap_or(0);
try!(f.buf.write(b[..n]));
}
if prefixed { f.buf.write(prefix.as_bytes()) }
else { Ok(()) }
};
// The `width` field is more of a `min-width` parameter at this point.
match self.width {
// If there's no minimum length requirements then we can just
// write the bytes.
None => {
try!(write_prefix(self)); self.buf.write(buf)
}
// Check if we're over the minimum width, if so then we can also
// just write the bytes.
Some(min) if width >= min => {
try!(write_prefix(self)); self.buf.write(buf)
}
// The sign and prefix goes before the padding if the fill character
// is zero
Some(min) if self.flags & (1 << (FlagSignAwareZeroPad as uint))!= 0 => {
self.fill = '0';
try!(write_prefix(self));
self.with_padding(min - width, rt::AlignRight, |f| f.buf.write(buf))
}
// Otherwise, the sign and prefix goes after the padding
Some(min) => {
self.with_padding(min - width, rt::AlignRight, |f| {
try!(write_prefix(f)); f.buf.write(buf)
})
}
}
}
/// This function takes a string slice and emits it to the internal buffer
/// after applying the relevant formatting flags specified. The flags
/// recognized for generic strings are:
///
/// * width - the minimum width of what to emit
/// * fill/align - what to emit and where to emit it if the string
/// provided needs to be padded
/// * precision - the maximum length to emit, the string is truncated if it
/// is longer than this length
///
/// Notably this function ignored the `flag` parameters
#[unstable = "definition may change slightly over time"]
pub fn
|
(&mut self, s: &str) -> Result {
// Make sure there's a fast path up front
if self.width.is_none() && self.precision.is_none() {
return self.buf.write(s.as_bytes());
}
// The `precision` field can be interpreted as a `max-width` for the
// string being formatted
match self.precision {
Some(max) => {
// If there's a maximum width and our string is longer than
// that, then we must always have truncation. This is the only
// case where the maximum length will matter.
let char_len = s.char_len();
if char_len >= max {
let nchars = ::cmp::min(max, char_len);
return self.buf.write(s.slice_chars(0, nchars).as_bytes());
}
}
None => {}
}
// The `width` field is more of a `min-width` parameter at this point.
match self.width {
// If we're under the maximum length, and there's no minimum length
// requirements, then we can just emit the string
None => self.buf.write(s.as_bytes()),
// If we're under the maximum width, check if we're over the minimum
// width, if so it's as easy as just emitting the string.
Some(width) if s.char_len() >= width => {
self.buf.write(s.as_bytes())
}
// If we're under both the maximum and the minimum width, then fill
// up the minimum width with the specified string + some alignment.
Some(width) => {
self.with_padding(width - s.char_len(), rt::AlignLeft, |me| {
me.buf.write(s.as_bytes())
})
}
}
}
/// Runs a callback, emitting the correct padding either before or
/// afterwards depending on whether right or left alignment is requested.
fn with_padding(&mut self,
padding: uint,
default: rt::Alignment,
f: |&mut Formatter| -> Result) -> Result {
use char::Char;
let align = match self.align {
rt::AlignUnknown => default,
_ => self.align
};
let (pre_pad, post_pad) = match align {
rt::AlignLeft => (0u, padding),
rt::AlignRight | rt::AlignUnknown => (padding, 0u),
rt::AlignCenter => (padding / 2, (padding + 1) / 2),
};
let mut fill = [0u8,..4];
let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
for _ in range(0, pre_pad) {
try!(self.buf.write(fill[..len]));
}
try!(f(self));
for _ in range(0, post_pad) {
try!(self.buf.write(fill[..len]));
}
Ok(())
}
/// Writes some data to the underlying buffer contained within this
/// formatter.
#[unstable = "reconciling core and I/O may alter this definition"]
pub fn write(&mut self, data: &[u8]) -> Result {
self.buf.write(data)
}
/// Writes some formatted information into this instance
#[unstable = "reconciling core and I/O may alter this definition"]
pub fn write_fmt(&mut self, fmt: &Arguments) -> Result {
write(self.buf, fmt)
}
/// Flags for formatting (packed version of rt::Flag)
#[experimental = "return type may change and method was just created"]
pub fn flags(&self) -> uint { self.flags }
/// Character used as 'fill' whenever there is alignment
#[unstable = "method was just created"]
pub fn fill(&self) -> char { self.fill }
/// Flag indicating what form of alignment was requested
#[unstable = "method was just created"]
pub fn align(&self) -> rt::Alignment { self.align }
/// Optionally specified integer width that the output should be
#[unstable = "method was just created"]
pub fn width(&self) -> Option<uint> { self.width }
/// Optionally specified precision for numeric types
#[unstable = "method was just created"]
pub fn precision(&self) -> Option<uint> { self.precision }
}
impl Show for Error {
fn fmt(&self, f: &mut Formatter) -> Result {
"an error occurred when formatting an argument".fmt(f)
}
}
/// This is a function which calls are emitted to by the compiler itself to
/// create the Argument structures that are passed into the `format` function.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result,
t: &'a T) -> Argument<'a> {
unsafe {
Argument {
formatter: mem::transmute(f),
value: mem::transmute(t)
}
}
}
/// When the compiler determines that the type of an argument *must* be a string
/// (such as for select), then it invokes this method.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argumentstr<'a>(s: &'a &str) -> Argument<'a> {
argument(Show::fmt, s)
}
/// When the compiler determines that the type of an argument *must* be a uint
/// (such as for plural), then it invokes this method.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
argument(Show::fmt, s)
}
// Implementations of the core formatting traits
impl<'a, Sized? T: Show> Show for &'a T {
fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
}
impl<'a, Sized? T: Show> Show for &'a mut T {
fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
}
impl<'a> Show for &'a Show+'a {
fn fmt(&self, f: &mut Formatter) -> Result { (*self).fmt(f) }
}
impl Show for bool {
fn fmt(&self, f: &mut Formatter) -> Result {
Show::fmt(if *self { "true" } else { "false" }, f)
}
}
impl Show for str {
fn fmt(&self, f: &mut Formatter) -> Result {
f.pad(self)
}
}
impl Show for char {
fn fmt(&self, f: &mut Formatter) -> Result {
use char::Char;
let mut utf8 = [0u8,..4];
let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
let s: &str = unsafe { mem::transmute(utf8[..amt]) };
Show::fmt(s, f)
}
}
impl<T> Pointer for *const T {
fn fmt(&self, f: &mut Formatter) -> Result {
f.flags |= 1 << (rt::FlagAlternate as uint);
LowerHex::fmt(&(*self as uint), f)
}
}
impl<T> Pointer for *mut T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(*self as *const T), f)
}
}
impl<'a, T> Pointer for &'a T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(*self as *const T), f)
}
}
impl<'a, T> Pointer for &'a mut T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(&**self as *const T), f)
}
}
macro_rules! floating(($ty:ident) => {
impl Show for $ty {
fn fmt(&self, fmt: &mut Formatter) -> Result {
use num::Float;
let digits = match fmt.precision {
Some(i) => float::DigExact(i),
None => float::DigMax(6),
};
float::float_to_str_bytes_common(self.abs(),
10,
true,
float::SignNeg,
digits,
float::ExpNone,
false,
|bytes| {
fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
})
}
}
impl LowerExp for $ty {
fn fmt(&self, fmt: &mut Formatter) -> Result {
use num::Float;
let digits = match fmt.precision {
Some(i) => float::DigExact(i),
None => float::DigMax(6),
};
float::float_to_str_bytes_common(self.abs(),
|
pad
|
identifier_name
|
mod.rs
|
to one type.
#[experimental = "implementation detail of the `format_args!` macro"]
pub struct Argument<'a> {
formatter: extern "Rust" fn(&Void, &mut Formatter) -> Result,
value: &'a Void,
}
impl<'a> Arguments<'a> {
/// When using the format_args!() macro, this function is used to generate the
/// Arguments structure. The compiler inserts an `unsafe` block to call this,
/// which is valid because the compiler performs all necessary validation to
/// ensure that the resulting call to format/write would be safe.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub unsafe fn new<'a>(pieces: &'static [&'static str],
args: &'a [Argument<'a>]) -> Arguments<'a> {
Arguments {
pieces: mem::transmute(pieces),
fmt: None,
args: args
}
}
/// This function is used to specify nonstandard formatting parameters.
/// The `pieces` array must be at least as long as `fmt` to construct
/// a valid Arguments structure.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub unsafe fn with_placeholders<'a>(pieces: &'static [&'static str],
fmt: &'static [rt::Argument<'static>],
args: &'a [Argument<'a>]) -> Arguments<'a> {
Arguments {
pieces: mem::transmute(pieces),
fmt: Some(mem::transmute(fmt)),
args: args
}
}
}
/// This structure represents a safely precompiled version of a format string
/// and its arguments. This cannot be generated at runtime because it cannot
/// safely be done so, so no constructors are given and the fields are private
/// to prevent modification.
///
/// The `format_args!` macro will safely create an instance of this structure
/// and pass it to a function or closure, passed as the first argument. The
/// macro validates the format string at compile-time so usage of the `write`
/// and `format` functions can be safely performed.
#[stable]
pub struct Arguments<'a> {
// Format string pieces to print.
pieces: &'a [&'a str],
// Placeholder specs, or `None` if all specs are default (as in "{}{}").
fmt: Option<&'a [rt::Argument<'a>]>,
// Dynamic arguments for interpolation, to be interleaved with string
// pieces. (Every argument is preceded by a string piece.)
args: &'a [Argument<'a>],
}
impl<'a> Show for Arguments<'a> {
fn fmt(&self, fmt: &mut Formatter) -> Result {
write(fmt.buf, self)
}
}
/// When a format is not otherwise specified, types are formatted by ascribing
/// to this trait. There is not an explicit way of selecting this trait to be
/// used for formatting, it is only if no other format is specified.
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Show for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `o` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Octal for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `t` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Binary for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `x` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait LowerHex for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `X` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait UpperHex for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `p` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Pointer for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `e` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait LowerExp for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `E` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait UpperExp for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
static DEFAULT_ARGUMENT: rt::Argument<'static> = rt::Argument {
position: rt::ArgumentNext,
format: rt::FormatSpec {
fill:'',
align: rt::AlignUnknown,
flags: 0,
precision: rt::CountImplied,
width: rt::CountImplied,
}
};
/// The `write` function takes an output stream, a precompiled format string,
/// and a list of arguments. The arguments will be formatted according to the
/// specified format string into the output stream provided.
///
/// # Arguments
///
/// * output - the buffer to write output to
/// * args - the precompiled arguments generated by `format_args!`
#[experimental = "libcore and I/O have yet to be reconciled, and this is an \
implementation detail which should not otherwise be exported"]
pub fn write(output: &mut FormatWriter, args: &Arguments) -> Result {
let mut formatter = Formatter {
flags: 0,
width: None,
precision: None,
buf: output,
align: rt::AlignUnknown,
fill:'',
args: args.args,
curarg: args.args.iter(),
};
let mut pieces = args.pieces.iter();
match args.fmt {
None => {
// We can use default formatting parameters for all arguments.
for _ in range(0, args.args.len()) {
try!(formatter.buf.write(pieces.next().unwrap().as_bytes()));
try!(formatter.run(&DEFAULT_ARGUMENT));
}
}
Some(fmt) => {
// Every spec has a corresponding argument that is preceded by
// a string piece.
for (arg, piece) in fmt.iter().zip(pieces.by_ref()) {
try!(formatter.buf.write(piece.as_bytes()));
try!(formatter.run(arg));
}
}
}
// There can be only one trailing string piece left.
match pieces.next() {
Some(piece) => {
try!(formatter.buf.write(piece.as_bytes()));
}
None => {}
}
Ok(())
}
impl<'a> Formatter<'a> {
// First up is the collection of functions used to execute a format string
// at runtime. This consumes all of the compile-time statics generated by
// the format! syntax extension.
fn run(&mut self, arg: &rt::Argument) -> Result {
// Fill in the format parameters into the formatter
self.fill = arg.format.fill;
self.align = arg.format.align;
self.flags = arg.format.flags;
self.width = self.getcount(&arg.format.width);
self.precision = self.getcount(&arg.format.precision);
// Extract the correct argument
let value = match arg.position {
rt::ArgumentNext => { *self.curarg.next().unwrap() }
rt::ArgumentIs(i) => self.args[i],
};
// Then actually do some printing
(value.formatter)(value.value, self)
}
fn getcount(&mut self, cnt: &rt::Count) -> Option<uint> {
match *cnt {
rt::CountIs(n) => { Some(n) }
rt::CountImplied => { None }
rt::CountIsParam(i) => {
let v = self.args[i].value;
unsafe { Some(*(v as *const _ as *const uint)) }
}
rt::CountIsNextParam => {
let v = self.curarg.next().unwrap().value;
unsafe { Some(*(v as *const _ as *const uint)) }
}
}
}
// Helper methods used for padding and processing formatting arguments that
// all formatting traits can use.
/// Performs the correct padding for an integer which has already been
/// emitted into a byte-array. The byte-array should *not* contain the sign
/// for the integer, that will be added by this method.
///
/// # Arguments
///
/// * is_positive - whether the original integer was positive or not.
/// * prefix - if the '#' character (FlagAlternate) is provided, this
/// is the prefix to put in front of the number.
/// * buf - the byte array that the number has been formatted into
///
/// This function will correctly account for the flags provided as well as
/// the minimum width. It will not take precision into account.
#[unstable = "definition may change slightly over time"]
pub fn pad_integral(&mut self,
is_positive: bool,
prefix: &str,
buf: &[u8])
-> Result {
use char::Char;
use fmt::rt::{FlagAlternate, FlagSignPlus, FlagSignAwareZeroPad};
let mut width = buf.len();
let mut sign = None;
if!is_positive {
sign = Some('-'); width += 1;
} else if self.flags & (1 << (FlagSignPlus as uint))!= 0 {
sign = Some('+'); width += 1;
}
let mut prefixed = false;
if self.flags & (1 << (FlagAlternate as uint))!= 0 {
prefixed = true; width += prefix.char_len();
}
// Writes the sign if it exists, and then the prefix if it was requested
let write_prefix = |f: &mut Formatter| {
for c in sign.into_iter() {
let mut b = [0,..4];
let n = c.encode_utf8(&mut b).unwrap_or(0);
try!(f.buf.write(b[..n]));
}
if prefixed { f.buf.write(prefix.as_bytes()) }
else { Ok(()) }
};
// The `width` field is more of a `min-width` parameter at this point.
match self.width {
// If there's no minimum length requirements then we can just
// write the bytes.
None => {
try!(write_prefix(self)); self.buf.write(buf)
}
// Check if we're over the minimum width, if so then we can also
// just write the bytes.
Some(min) if width >= min => {
try!(write_prefix(self)); self.buf.write(buf)
}
// The sign and prefix goes before the padding if the fill character
// is zero
Some(min) if self.flags & (1 << (FlagSignAwareZeroPad as uint))!= 0 => {
self.fill = '0';
try!(write_prefix(self));
self.with_padding(min - width, rt::AlignRight, |f| f.buf.write(buf))
}
// Otherwise, the sign and prefix goes after the padding
Some(min) => {
self.with_padding(min - width, rt::AlignRight, |f| {
try!(write_prefix(f)); f.buf.write(buf)
})
}
}
}
/// This function takes a string slice and emits it to the internal buffer
/// after applying the relevant formatting flags specified. The flags
/// recognized for generic strings are:
///
|
/// provided needs to be padded
/// * precision - the maximum length to emit, the string is truncated if it
/// is longer than this length
///
/// Notably this function ignored the `flag` parameters
#[unstable = "definition may change slightly over time"]
pub fn pad(&mut self, s: &str) -> Result {
// Make sure there's a fast path up front
if self.width.is_none() && self.precision.is_none() {
return self.buf.write(s.as_bytes());
}
// The `precision` field can be interpreted as a `max-width` for the
// string being formatted
match self.precision {
Some(max) => {
// If there's a maximum width and our string is longer than
// that, then we must always have truncation. This is the only
// case where the maximum length will matter.
let char_len = s.char_len();
if char_len >= max {
let nchars = ::cmp::min(max, char_len);
return self.buf.write(s.slice_chars(0, nchars).as_bytes());
}
}
None => {}
}
// The `width` field is more of a `min-width` parameter at this point.
match self.width {
// If we're under the maximum length, and there's no minimum length
// requirements, then we can just emit the string
None => self.buf.write(s.as_bytes()),
// If we're under the maximum width, check if we're over the minimum
// width, if so it's as easy as just emitting the string.
Some(width) if s.char_len() >= width => {
self.buf.write(s.as_bytes())
}
// If we're under both the maximum and the minimum width, then fill
// up the minimum width with the specified string + some alignment.
Some(width) => {
self.with_padding(width - s.char_len(), rt::AlignLeft, |me| {
me.buf.write(s.as_bytes())
})
}
}
}
/// Runs a callback, emitting the correct padding either before or
/// afterwards depending on whether right or left alignment is requested.
fn with_padding(&mut self,
padding: uint,
default: rt::Alignment,
f: |&mut Formatter| -> Result) -> Result {
use char::Char;
let align = match self.align {
rt::AlignUnknown => default,
_ => self.align
};
let (pre_pad, post_pad) = match align {
rt::AlignLeft => (0u, padding),
rt::AlignRight | rt::AlignUnknown => (padding, 0u),
rt::AlignCenter => (padding / 2, (padding + 1) / 2),
};
let mut fill = [0u8,..4];
let len = self.fill.encode_utf8(&mut fill).unwrap_or(0);
for _ in range(0, pre_pad) {
try!(self.buf.write(fill[..len]));
}
try!(f(self));
for _ in range(0, post_pad) {
try!(self.buf.write(fill[..len]));
}
Ok(())
}
/// Writes some data to the underlying buffer contained within this
/// formatter.
#[unstable = "reconciling core and I/O may alter this definition"]
pub fn write(&mut self, data: &[u8]) -> Result {
self.buf.write(data)
}
/// Writes some formatted information into this instance
#[unstable = "reconciling core and I/O may alter this definition"]
pub fn write_fmt(&mut self, fmt: &Arguments) -> Result {
write(self.buf, fmt)
}
/// Flags for formatting (packed version of rt::Flag)
#[experimental = "return type may change and method was just created"]
pub fn flags(&self) -> uint { self.flags }
/// Character used as 'fill' whenever there is alignment
#[unstable = "method was just created"]
pub fn fill(&self) -> char { self.fill }
/// Flag indicating what form of alignment was requested
#[unstable = "method was just created"]
pub fn align(&self) -> rt::Alignment { self.align }
/// Optionally specified integer width that the output should be
#[unstable = "method was just created"]
pub fn width(&self) -> Option<uint> { self.width }
/// Optionally specified precision for numeric types
#[unstable = "method was just created"]
pub fn precision(&self) -> Option<uint> { self.precision }
}
impl Show for Error {
fn fmt(&self, f: &mut Formatter) -> Result {
"an error occurred when formatting an argument".fmt(f)
}
}
/// This is a function which calls are emitted to by the compiler itself to
/// create the Argument structures that are passed into the `format` function.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argument<'a, T>(f: extern "Rust" fn(&T, &mut Formatter) -> Result,
t: &'a T) -> Argument<'a> {
unsafe {
Argument {
formatter: mem::transmute(f),
value: mem::transmute(t)
}
}
}
/// When the compiler determines that the type of an argument *must* be a string
/// (such as for select), then it invokes this method.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argumentstr<'a>(s: &'a &str) -> Argument<'a> {
argument(Show::fmt, s)
}
/// When the compiler determines that the type of an argument *must* be a uint
/// (such as for plural), then it invokes this method.
#[doc(hidden)] #[inline]
#[experimental = "implementation detail of the `format_args!` macro"]
pub fn argumentuint<'a>(s: &'a uint) -> Argument<'a> {
argument(Show::fmt, s)
}
// Implementations of the core formatting traits
impl<'a, Sized? T: Show> Show for &'a T {
fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
}
impl<'a, Sized? T: Show> Show for &'a mut T {
fn fmt(&self, f: &mut Formatter) -> Result { (**self).fmt(f) }
}
impl<'a> Show for &'a Show+'a {
fn fmt(&self, f: &mut Formatter) -> Result { (*self).fmt(f) }
}
impl Show for bool {
fn fmt(&self, f: &mut Formatter) -> Result {
Show::fmt(if *self { "true" } else { "false" }, f)
}
}
impl Show for str {
fn fmt(&self, f: &mut Formatter) -> Result {
f.pad(self)
}
}
impl Show for char {
fn fmt(&self, f: &mut Formatter) -> Result {
use char::Char;
let mut utf8 = [0u8,..4];
let amt = self.encode_utf8(&mut utf8).unwrap_or(0);
let s: &str = unsafe { mem::transmute(utf8[..amt]) };
Show::fmt(s, f)
}
}
impl<T> Pointer for *const T {
fn fmt(&self, f: &mut Formatter) -> Result {
f.flags |= 1 << (rt::FlagAlternate as uint);
LowerHex::fmt(&(*self as uint), f)
}
}
impl<T> Pointer for *mut T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(*self as *const T), f)
}
}
impl<'a, T> Pointer for &'a T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(*self as *const T), f)
}
}
impl<'a, T> Pointer for &'a mut T {
fn fmt(&self, f: &mut Formatter) -> Result {
Pointer::fmt(&(&**self as *const T), f)
}
}
macro_rules! floating(($ty:ident) => {
impl Show for $ty {
fn fmt(&self, fmt: &mut Formatter) -> Result {
use num::Float;
let digits = match fmt.precision {
Some(i) => float::DigExact(i),
None => float::DigMax(6),
};
float::float_to_str_bytes_common(self.abs(),
10,
true,
float::SignNeg,
digits,
float::ExpNone,
false,
|bytes| {
fmt.pad_integral(self.is_nan() || *self >= 0.0, "", bytes)
})
}
}
impl LowerExp for $ty {
fn fmt(&self, fmt: &mut Formatter) -> Result {
use num::Float;
let digits = match fmt.precision {
Some(i) => float::DigExact(i),
None => float::DigMax(6),
};
float::float_to_str_bytes_common(self.abs(),
|
/// * width - the minimum width of what to emit
/// * fill/align - what to emit and where to emit it if the string
|
random_line_split
|
syntax_test_union.rs
|
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax"
union Union {
//^^^ meta.union storage.type.union
//^^^^^^^^^^^ meta.union
// ^^^^^ entity.name.union
// ^ meta.block punctuation.definition.block.begin
f: u32,
// ^ meta.union meta.block variable.other.member
// ^ meta.union meta.block punctuation.separator
// ^^^ meta.union meta.block storage.type
}
// <- meta.union meta.block punctuation.definition.block.end
pub union Foo<'a, Y: Baz>
// <- storage.modifier
// ^^^^^^^^^^^^^^^^^^^^^ meta.union
// ^^^^^ meta.union storage.type.union
// ^^^ meta.union meta.generic entity.name.union
// ^ meta.union meta.generic meta.generic punctuation.definition.generic.begin
// ^^ meta.union meta.generic meta.generic storage.modifier.lifetime
where X: Whatever,
// ^^^^^ meta.union meta.where keyword.other
// ^ meta.union meta.where
// ^ meta.union meta.where punctuation.separator
// ^^^^^^^^^^ meta.union meta.where
{
// <- meta.union meta.block punctuation.definition.block.begin
f: SomeType, // Comment beside a field
// ^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.union meta.block comment.line.double-slash
}
// <- meta.union meta.block punctuation.definition.block.end
// Union was implemented in such a way that `union` is not a keyword. Verify
// that we don't accidentally interpret it as a keyword.
fn
|
() {}
// ^^^^^ meta.function entity.name.function
union /*comment*/ U {}
// ^^^^^^^^^^^ meta.union comment.block
|
union
|
identifier_name
|
syntax_test_union.rs
|
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax"
union Union {
//^^^ meta.union storage.type.union
|
// ^ meta.block punctuation.definition.block.begin
f: u32,
// ^ meta.union meta.block variable.other.member
// ^ meta.union meta.block punctuation.separator
// ^^^ meta.union meta.block storage.type
}
// <- meta.union meta.block punctuation.definition.block.end
pub union Foo<'a, Y: Baz>
// <- storage.modifier
// ^^^^^^^^^^^^^^^^^^^^^ meta.union
// ^^^^^ meta.union storage.type.union
// ^^^ meta.union meta.generic entity.name.union
// ^ meta.union meta.generic meta.generic punctuation.definition.generic.begin
// ^^ meta.union meta.generic meta.generic storage.modifier.lifetime
where X: Whatever,
// ^^^^^ meta.union meta.where keyword.other
// ^ meta.union meta.where
// ^ meta.union meta.where punctuation.separator
// ^^^^^^^^^^ meta.union meta.where
{
// <- meta.union meta.block punctuation.definition.block.begin
f: SomeType, // Comment beside a field
// ^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.union meta.block comment.line.double-slash
}
// <- meta.union meta.block punctuation.definition.block.end
// Union was implemented in such a way that `union` is not a keyword. Verify
// that we don't accidentally interpret it as a keyword.
fn union() {}
// ^^^^^ meta.function entity.name.function
union /*comment*/ U {}
// ^^^^^^^^^^^ meta.union comment.block
|
//^^^^^^^^^^^ meta.union
// ^^^^^ entity.name.union
|
random_line_split
|
syntax_test_union.rs
|
// SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax"
union Union {
//^^^ meta.union storage.type.union
//^^^^^^^^^^^ meta.union
// ^^^^^ entity.name.union
// ^ meta.block punctuation.definition.block.begin
f: u32,
// ^ meta.union meta.block variable.other.member
// ^ meta.union meta.block punctuation.separator
// ^^^ meta.union meta.block storage.type
}
// <- meta.union meta.block punctuation.definition.block.end
pub union Foo<'a, Y: Baz>
// <- storage.modifier
// ^^^^^^^^^^^^^^^^^^^^^ meta.union
// ^^^^^ meta.union storage.type.union
// ^^^ meta.union meta.generic entity.name.union
// ^ meta.union meta.generic meta.generic punctuation.definition.generic.begin
// ^^ meta.union meta.generic meta.generic storage.modifier.lifetime
where X: Whatever,
// ^^^^^ meta.union meta.where keyword.other
// ^ meta.union meta.where
// ^ meta.union meta.where punctuation.separator
// ^^^^^^^^^^ meta.union meta.where
{
// <- meta.union meta.block punctuation.definition.block.begin
f: SomeType, // Comment beside a field
// ^^^^^^^^^^^^^^^^^^^^^^^^^^ meta.union meta.block comment.line.double-slash
}
// <- meta.union meta.block punctuation.definition.block.end
// Union was implemented in such a way that `union` is not a keyword. Verify
// that we don't accidentally interpret it as a keyword.
fn union()
|
// ^^^^^ meta.function entity.name.function
union /*comment*/ U {}
// ^^^^^^^^^^^ meta.union comment.block
|
{}
|
identifier_body
|
u_str.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Unicode-intensive string manipulations.
//!
//! This module provides functionality to `str` that requires the Unicode methods provided by the
//! unicode parts of the CharExt trait.
use core::char;
use core::iter::Filter;
use core::slice;
use core::str::Split;
/// An iterator over the non-whitespace substrings of a string,
/// separated by any amount of whitespace.
#[stable(feature = "split_whitespace", since = "1.1.0")]
pub struct SplitWhitespace<'a> {
inner: Filter<Split<'a, fn(char) -> bool>, fn(&&str) -> bool>,
}
/// Methods for Unicode string slices
#[allow(missing_docs)] // docs in libcollections
pub trait UnicodeStr {
fn split_whitespace<'a>(&'a self) -> SplitWhitespace<'a>;
fn is_whitespace(&self) -> bool;
fn is_alphanumeric(&self) -> bool;
fn trim<'a>(&'a self) -> &'a str;
fn trim_left<'a>(&'a self) -> &'a str;
fn trim_right<'a>(&'a self) -> &'a str;
}
impl UnicodeStr for str {
#[inline]
fn split_whitespace(&self) -> SplitWhitespace {
fn is_not_empty(s: &&str) -> bool {!s.is_empty() }
let is_not_empty: fn(&&str) -> bool = is_not_empty; // coerce to fn pointer
fn is_whitespace(c: char) -> bool { c.is_whitespace() }
let is_whitespace: fn(char) -> bool = is_whitespace; // coerce to fn pointer
SplitWhitespace { inner: self.split(is_whitespace).filter(is_not_empty) }
}
#[inline]
fn is_whitespace(&self) -> bool { self.chars().all(|c| c.is_whitespace()) }
#[inline]
fn is_alphanumeric(&self) -> bool { self.chars().all(|c| c.is_alphanumeric()) }
#[inline]
fn trim(&self) -> &str {
self.trim_matches(|c: char| c.is_whitespace())
}
#[inline]
fn trim_left(&self) -> &str {
self.trim_left_matches(|c: char| c.is_whitespace())
}
#[inline]
fn trim_right(&self) -> &str {
self.trim_right_matches(|c: char| c.is_whitespace())
}
}
// https://tools.ietf.org/html/rfc3629
static UTF8_CHAR_WIDTH: [u8; 256] = [
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
];
/// Given a first byte, determine how many bytes are in this UTF-8 character
#[inline]
pub fn utf8_char_width(b: u8) -> usize {
return UTF8_CHAR_WIDTH[b as usize] as usize;
}
/// Determines if a vector of `u16` contains valid UTF-16
pub fn is_utf16(v: &[u16]) -> bool {
let mut it = v.iter();
macro_rules! next { ($ret:expr) => {
match it.next() { Some(u) => *u, None => return $ret }
}
}
loop {
let u = next!(true);
match char::from_u32(u as u32) {
Some(_) => {}
None => {
let u2 = next!(false);
if u < 0xD7FF || u > 0xDBFF ||
u2 < 0xDC00 || u2 > 0xDFFF { return false; }
}
}
}
}
/// An iterator that decodes UTF-16 encoded codepoints from a vector
/// of `u16`s.
#[derive(Clone)]
pub struct Utf16Items<'a> {
iter: slice::Iter<'a, u16>
}
/// The possibilities for values decoded from a `u16` stream.
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
pub enum Utf16Item {
/// A valid codepoint.
ScalarValue(char),
/// An invalid surrogate without its pair.
LoneSurrogate(u16)
}
impl Utf16Item {
/// Convert `self` to a `char`, taking `LoneSurrogate`s to the
/// replacement character (U+FFFD).
#[inline]
pub fn to_char_lossy(&self) -> char {
match *self {
Utf16Item::ScalarValue(c) => c,
Utf16Item::LoneSurrogate(_) => '\u{FFFD}'
}
}
}
impl<'a> Iterator for Utf16Items<'a> {
type Item = Utf16Item;
fn next(&mut self) -> Option<Utf16Item> {
let u = match self.iter.next() {
Some(u) => *u,
None => return None
};
if u < 0xD800 || 0xDFFF < u {
// not a surrogate
Some(Utf16Item::ScalarValue(unsafe { char::from_u32_unchecked(u as u32) }))
} else if u >= 0xDC00 {
// a trailing surrogate
Some(Utf16Item::LoneSurrogate(u))
} else {
// preserve state for rewinding.
let old = self.iter.clone();
let u2 = match self.iter.next() {
Some(u2) => *u2,
// eof
None => return Some(Utf16Item::LoneSurrogate(u))
};
if u2 < 0xDC00 || u2 > 0xDFFF {
// not a trailing surrogate so we're not a valid
// surrogate pair, so rewind to redecode u2 next time.
self.iter = old.clone();
return Some(Utf16Item::LoneSurrogate(u))
}
// all ok, so lets decode it.
let c = (((u - 0xD800) as u32) << 10 | (u2 - 0xDC00) as u32) + 0x1_0000;
Some(Utf16Item::ScalarValue(unsafe { char::from_u32_unchecked(c) }))
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (low, high) = self.iter.size_hint();
// we could be entirely valid surrogates (2 elements per
// char), or entirely non-surrogates (1 element per char)
(low / 2, high)
}
}
/// Create an iterator over the UTF-16 encoded codepoints in `v`,
/// returning invalid surrogates as `LoneSurrogate`s.
///
/// # Examples
///
/// ```
/// #![feature(unicode)]
///
/// extern crate rustc_unicode;
///
/// use rustc_unicode::str::Utf16Item::{ScalarValue, LoneSurrogate};
///
/// fn main() {
/// // 𝄞mus<invalid>ic<invalid>
/// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0xDD1E, 0x0069, 0x0063,
/// 0xD834];
///
/// assert_eq!(rustc_unicode::str::utf16_items(&v).collect::<Vec<_>>(),
/// vec![ScalarValue('𝄞'),
/// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
/// LoneSurrogate(0xDD1E),
/// ScalarValue('i'), ScalarValue('c'),
/// LoneSurrogate(0xD834)]);
/// }
/// ```
pub fn utf16_items<'a>(v: &'a [u16]) -> Utf16Items<'a> {
Utf16Items { iter : v.iter() }
}
/// Iterator adaptor for encoding `char`s to UTF-16.
#[derive(Clone)]
pub struct Utf16Encoder<I> {
chars: I,
extra: u16
}
impl<I> Utf16Encoder<I> {
/// Create a UTF-16 encoder from any `char` iterator.
pub fn new(chars: I) -> Utf16Encoder<I> where I: Iterator<Item=char> {
Utf16Encoder { chars: chars, extra: 0 }
}
}
impl<I> Iterator for Utf16Encoder<I> where I: Iterator<Item=char> {
type Item = u16;
#[inline]
fn next(&mut self) -> Option<u16> {
if self.extra!= 0 {
let tmp = self.extra;
self.extra = 0;
return Some(tmp);
}
let mut buf = [0; 2];
self.chars.next().map(|ch| {
let n = CharExt::encode_utf16(ch, &mut buf).unwrap_or(0);
if n == 2 { self.extra = buf[1]; }
buf[0]
})
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
|
// every char gets either one u16 or two u16,
// so this iterator is between 1 or 2 times as
// long as the underlying iterator.
(low, high.and_then(|n| n.checked_mul(2)))
}
}
impl<'a> Iterator for SplitWhitespace<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> { self.inner.next() }
}
impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back() }
}
|
let (low, high) = self.chars.size_hint();
|
random_line_split
|
u_str.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Unicode-intensive string manipulations.
//!
//! This module provides functionality to `str` that requires the Unicode methods provided by the
//! unicode parts of the CharExt trait.
use core::char;
use core::iter::Filter;
use core::slice;
use core::str::Split;
/// An iterator over the non-whitespace substrings of a string,
/// separated by any amount of whitespace.
#[stable(feature = "split_whitespace", since = "1.1.0")]
pub struct SplitWhitespace<'a> {
inner: Filter<Split<'a, fn(char) -> bool>, fn(&&str) -> bool>,
}
/// Methods for Unicode string slices
#[allow(missing_docs)] // docs in libcollections
pub trait UnicodeStr {
fn split_whitespace<'a>(&'a self) -> SplitWhitespace<'a>;
fn is_whitespace(&self) -> bool;
fn is_alphanumeric(&self) -> bool;
fn trim<'a>(&'a self) -> &'a str;
fn trim_left<'a>(&'a self) -> &'a str;
fn trim_right<'a>(&'a self) -> &'a str;
}
impl UnicodeStr for str {
#[inline]
fn split_whitespace(&self) -> SplitWhitespace {
fn is_not_empty(s: &&str) -> bool {!s.is_empty() }
let is_not_empty: fn(&&str) -> bool = is_not_empty; // coerce to fn pointer
fn is_whitespace(c: char) -> bool { c.is_whitespace() }
let is_whitespace: fn(char) -> bool = is_whitespace; // coerce to fn pointer
SplitWhitespace { inner: self.split(is_whitespace).filter(is_not_empty) }
}
#[inline]
fn is_whitespace(&self) -> bool { self.chars().all(|c| c.is_whitespace()) }
#[inline]
fn is_alphanumeric(&self) -> bool { self.chars().all(|c| c.is_alphanumeric()) }
#[inline]
fn trim(&self) -> &str {
self.trim_matches(|c: char| c.is_whitespace())
}
#[inline]
fn trim_left(&self) -> &str {
self.trim_left_matches(|c: char| c.is_whitespace())
}
#[inline]
fn trim_right(&self) -> &str {
self.trim_right_matches(|c: char| c.is_whitespace())
}
}
// https://tools.ietf.org/html/rfc3629
static UTF8_CHAR_WIDTH: [u8; 256] = [
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
];
/// Given a first byte, determine how many bytes are in this UTF-8 character
#[inline]
pub fn utf8_char_width(b: u8) -> usize {
return UTF8_CHAR_WIDTH[b as usize] as usize;
}
/// Determines if a vector of `u16` contains valid UTF-16
pub fn is_utf16(v: &[u16]) -> bool {
let mut it = v.iter();
macro_rules! next { ($ret:expr) => {
match it.next() { Some(u) => *u, None => return $ret }
}
}
loop {
let u = next!(true);
match char::from_u32(u as u32) {
Some(_) => {}
None => {
let u2 = next!(false);
if u < 0xD7FF || u > 0xDBFF ||
u2 < 0xDC00 || u2 > 0xDFFF { return false; }
}
}
}
}
/// An iterator that decodes UTF-16 encoded codepoints from a vector
/// of `u16`s.
#[derive(Clone)]
pub struct Utf16Items<'a> {
iter: slice::Iter<'a, u16>
}
/// The possibilities for values decoded from a `u16` stream.
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
pub enum Utf16Item {
/// A valid codepoint.
ScalarValue(char),
/// An invalid surrogate without its pair.
LoneSurrogate(u16)
}
impl Utf16Item {
/// Convert `self` to a `char`, taking `LoneSurrogate`s to the
/// replacement character (U+FFFD).
#[inline]
pub fn to_char_lossy(&self) -> char {
match *self {
Utf16Item::ScalarValue(c) => c,
Utf16Item::LoneSurrogate(_) => '\u{FFFD}'
}
}
}
impl<'a> Iterator for Utf16Items<'a> {
type Item = Utf16Item;
fn next(&mut self) -> Option<Utf16Item> {
let u = match self.iter.next() {
Some(u) => *u,
None => return None
};
if u < 0xD800 || 0xDFFF < u {
// not a surrogate
Some(Utf16Item::ScalarValue(unsafe { char::from_u32_unchecked(u as u32) }))
} else if u >= 0xDC00 {
// a trailing surrogate
Some(Utf16Item::LoneSurrogate(u))
} else {
// preserve state for rewinding.
let old = self.iter.clone();
let u2 = match self.iter.next() {
Some(u2) => *u2,
// eof
None => return Some(Utf16Item::LoneSurrogate(u))
};
if u2 < 0xDC00 || u2 > 0xDFFF {
// not a trailing surrogate so we're not a valid
// surrogate pair, so rewind to redecode u2 next time.
self.iter = old.clone();
return Some(Utf16Item::LoneSurrogate(u))
}
// all ok, so lets decode it.
let c = (((u - 0xD800) as u32) << 10 | (u2 - 0xDC00) as u32) + 0x1_0000;
Some(Utf16Item::ScalarValue(unsafe { char::from_u32_unchecked(c) }))
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (low, high) = self.iter.size_hint();
// we could be entirely valid surrogates (2 elements per
// char), or entirely non-surrogates (1 element per char)
(low / 2, high)
}
}
/// Create an iterator over the UTF-16 encoded codepoints in `v`,
/// returning invalid surrogates as `LoneSurrogate`s.
///
/// # Examples
///
/// ```
/// #![feature(unicode)]
///
/// extern crate rustc_unicode;
///
/// use rustc_unicode::str::Utf16Item::{ScalarValue, LoneSurrogate};
///
/// fn main() {
/// // 𝄞mus<invalid>ic<invalid>
/// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0xDD1E, 0x0069, 0x0063,
/// 0xD834];
///
/// assert_eq!(rustc_unicode::str::utf16_items(&v).collect::<Vec<_>>(),
/// vec![ScalarValue('𝄞'),
/// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
/// LoneSurrogate(0xDD1E),
/// ScalarValue('i'), ScalarValue('c'),
/// LoneSurrogate(0xD834)]);
/// }
/// ```
pub fn utf16_
|
: &'a [u16]) -> Utf16Items<'a> {
Utf16Items { iter : v.iter() }
}
/// Iterator adaptor for encoding `char`s to UTF-16.
#[derive(Clone)]
pub struct Utf16Encoder<I> {
chars: I,
extra: u16
}
impl<I> Utf16Encoder<I> {
/// Create a UTF-16 encoder from any `char` iterator.
pub fn new(chars: I) -> Utf16Encoder<I> where I: Iterator<Item=char> {
Utf16Encoder { chars: chars, extra: 0 }
}
}
impl<I> Iterator for Utf16Encoder<I> where I: Iterator<Item=char> {
type Item = u16;
#[inline]
fn next(&mut self) -> Option<u16> {
if self.extra!= 0 {
let tmp = self.extra;
self.extra = 0;
return Some(tmp);
}
let mut buf = [0; 2];
self.chars.next().map(|ch| {
let n = CharExt::encode_utf16(ch, &mut buf).unwrap_or(0);
if n == 2 { self.extra = buf[1]; }
buf[0]
})
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (low, high) = self.chars.size_hint();
// every char gets either one u16 or two u16,
// so this iterator is between 1 or 2 times as
// long as the underlying iterator.
(low, high.and_then(|n| n.checked_mul(2)))
}
}
impl<'a> Iterator for SplitWhitespace<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> { self.inner.next() }
}
impl<'a> DoubleEndedIterator for SplitWhitespace<'a> {
fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back() }
}
|
items<'a>(v
|
identifier_name
|
u_str.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Unicode-intensive string manipulations.
//!
//! This module provides functionality to `str` that requires the Unicode methods provided by the
//! unicode parts of the CharExt trait.
use core::char;
use core::iter::Filter;
use core::slice;
use core::str::Split;
/// An iterator over the non-whitespace substrings of a string,
/// separated by any amount of whitespace.
#[stable(feature = "split_whitespace", since = "1.1.0")]
pub struct SplitWhitespace<'a> {
inner: Filter<Split<'a, fn(char) -> bool>, fn(&&str) -> bool>,
}
/// Methods for Unicode string slices
#[allow(missing_docs)] // docs in libcollections
pub trait UnicodeStr {
fn split_whitespace<'a>(&'a self) -> SplitWhitespace<'a>;
fn is_whitespace(&self) -> bool;
fn is_alphanumeric(&self) -> bool;
fn trim<'a>(&'a self) -> &'a str;
fn trim_left<'a>(&'a self) -> &'a str;
fn trim_right<'a>(&'a self) -> &'a str;
}
impl UnicodeStr for str {
#[inline]
fn split_whitespace(&self) -> SplitWhitespace {
fn is_not_empty(s: &&str) -> bool {!s.is_empty() }
let is_not_empty: fn(&&str) -> bool = is_not_empty; // coerce to fn pointer
fn is_whitespace(c: char) -> bool { c.is_whitespace() }
let is_whitespace: fn(char) -> bool = is_whitespace; // coerce to fn pointer
SplitWhitespace { inner: self.split(is_whitespace).filter(is_not_empty) }
}
#[inline]
fn is_whitespace(&self) -> bool { self.chars().all(|c| c.is_whitespace()) }
#[inline]
fn is_alphanumeric(&self) -> bool { self.chars().all(|c| c.is_alphanumeric()) }
#[inline]
fn trim(&self) -> &str {
self.trim_matches(|c: char| c.is_whitespace())
}
#[inline]
fn trim_left(&self) -> &str {
self.trim_left_matches(|c: char| c.is_whitespace())
}
#[inline]
fn trim_right(&self) -> &str {
self.trim_right_matches(|c: char| c.is_whitespace())
}
}
// https://tools.ietf.org/html/rfc3629
static UTF8_CHAR_WIDTH: [u8; 256] = [
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0xBF
0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // 0xDF
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, // 0xEF
4,4,4,4,4,0,0,0,0,0,0,0,0,0,0,0, // 0xFF
];
/// Given a first byte, determine how many bytes are in this UTF-8 character
#[inline]
pub fn utf8_char_width(b: u8) -> usize {
return UTF8_CHAR_WIDTH[b as usize] as usize;
}
/// Determines if a vector of `u16` contains valid UTF-16
pub fn is_utf16(v: &[u16]) -> bool {
let mut it = v.iter();
macro_rules! next { ($ret:expr) => {
match it.next() { Some(u) => *u, None => return $ret }
}
}
loop {
let u = next!(true);
match char::from_u32(u as u32) {
Some(_) => {}
None => {
let u2 = next!(false);
if u < 0xD7FF || u > 0xDBFF ||
u2 < 0xDC00 || u2 > 0xDFFF { return false; }
}
}
}
}
/// An iterator that decodes UTF-16 encoded codepoints from a vector
/// of `u16`s.
#[derive(Clone)]
pub struct Utf16Items<'a> {
iter: slice::Iter<'a, u16>
}
/// The possibilities for values decoded from a `u16` stream.
#[derive(Copy, PartialEq, Eq, Clone, Debug)]
pub enum Utf16Item {
/// A valid codepoint.
ScalarValue(char),
/// An invalid surrogate without its pair.
LoneSurrogate(u16)
}
impl Utf16Item {
/// Convert `self` to a `char`, taking `LoneSurrogate`s to the
/// replacement character (U+FFFD).
#[inline]
pub fn to_char_lossy(&self) -> char {
match *self {
Utf16Item::ScalarValue(c) => c,
Utf16Item::LoneSurrogate(_) => '\u{FFFD}'
}
}
}
impl<'a> Iterator for Utf16Items<'a> {
type Item = Utf16Item;
fn next(&mut self) -> Option<Utf16Item> {
let u = match self.iter.next() {
Some(u) => *u,
None => return None
};
if u < 0xD800 || 0xDFFF < u {
// not a surrogate
Some(Utf16Item::ScalarValue(unsafe { char::from_u32_unchecked(u as u32) }))
} else if u >= 0xDC00 {
// a trailing surrogate
Some(Utf16Item::LoneSurrogate(u))
} else {
// preserve state for rewinding.
let old = self.iter.clone();
let u2 = match self.iter.next() {
Some(u2) => *u2,
// eof
None => return Some(Utf16Item::LoneSurrogate(u))
};
if u2 < 0xDC00 || u2 > 0xDFFF {
// not a trailing surrogate so we're not a valid
// surrogate pair, so rewind to redecode u2 next time.
self.iter = old.clone();
return Some(Utf16Item::LoneSurrogate(u))
}
// all ok, so lets decode it.
let c = (((u - 0xD800) as u32) << 10 | (u2 - 0xDC00) as u32) + 0x1_0000;
Some(Utf16Item::ScalarValue(unsafe { char::from_u32_unchecked(c) }))
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (low, high) = self.iter.size_hint();
// we could be entirely valid surrogates (2 elements per
// char), or entirely non-surrogates (1 element per char)
(low / 2, high)
}
}
/// Create an iterator over the UTF-16 encoded codepoints in `v`,
/// returning invalid surrogates as `LoneSurrogate`s.
///
/// # Examples
///
/// ```
/// #![feature(unicode)]
///
/// extern crate rustc_unicode;
///
/// use rustc_unicode::str::Utf16Item::{ScalarValue, LoneSurrogate};
///
/// fn main() {
/// // 𝄞mus<invalid>ic<invalid>
/// let v = [0xD834, 0xDD1E, 0x006d, 0x0075,
/// 0x0073, 0xDD1E, 0x0069, 0x0063,
/// 0xD834];
///
/// assert_eq!(rustc_unicode::str::utf16_items(&v).collect::<Vec<_>>(),
/// vec![ScalarValue('𝄞'),
/// ScalarValue('m'), ScalarValue('u'), ScalarValue('s'),
/// LoneSurrogate(0xDD1E),
/// ScalarValue('i'), ScalarValue('c'),
/// LoneSurrogate(0xD834)]);
/// }
/// ```
pub fn utf16_items<'a>(v: &'a [u16]) -> Utf16Items<'a> {
Utf16Items { iter : v.iter() }
}
/// Iterator adaptor for encoding `char`s to UTF-16.
#[derive(Clone)]
pub struct Utf16Encoder<I> {
chars: I,
extra: u16
}
impl<I> Utf16Encoder<I> {
/// Create a UTF-16 encoder from any `char` iterator.
pub fn new(chars: I) -> Utf16Encoder<I> where I: Iterator<Item=char> {
Utf16Encoder { chars: chars, extra: 0 }
}
}
impl<I> Iterator for Utf16Encoder<I> where I: Iterator<Item=char> {
type Item = u16;
#[inline]
fn next(&mut self) -> Option<u16> {
if self.extra!= 0 {
let tmp = self.extra;
self.extra = 0;
return Some(tmp);
}
let mut buf = [0; 2];
self.chars.next().map(|ch| {
let n = CharExt::encode_utf16(ch, &mut buf).unwrap_or(0);
if n == 2 { self.extra = buf[1]; }
buf[0]
})
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let (low, high) = self.chars.size_hint();
// every char gets either one u16 or two u16,
// so this iterator is between 1 or 2 times as
// long as the underlying iterator.
(low, high.and_then(|n| n.checked_mul(2)))
}
}
impl<'a> Iterator for SplitWhitespace<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> { self
|
l<'a> DoubleEndedIterator for SplitWhitespace<'a> {
fn next_back(&mut self) -> Option<&'a str> { self.inner.next_back() }
}
|
.inner.next() }
}
imp
|
identifier_body
|
vote_genesis.rs
|
//this module spits out a structured vote as json data
//save the vote to a file
use safex::genesis::key_generation::KeyPair;
use utils::get_address_methods::OmniList;
use utils::dirs::{make_app_root_dir, touch};
use voting::poll_genesis::PollRound;
use voting::validate_genesis::VotingOutcome;
use rustc_serialize::{Decodable, Decoder};
use rustc_serialize::json::{self, ToJson, Json};
use bitcoin::util::hash::Sha256dHash;
use std::error::Error;
use std::fs;
use std::fs::File;
use std::path::Path;
use std::env;
use std::io::Write;
use std::io;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::{BufRead};
pub struct VotePersona {
voter_keys: KeyPair,
voting_round: VoteRound,
}
impl VotePersona {
pub fn import_keys() -> VotePersona {
println!("input your private key");
let mut input2 = String::new();
let stdin2 = io::stdin();
stdin2.lock().read_line(&mut input2).unwrap();
let trimmed = input2.trim_right_matches("\n");
let persona = VotePersona::persona_fromstring(trimmed.to_string());
persona
}
pub fn persona_fromstring(secret: String) -> VotePersona {
let new_keys = KeyPair::keypair_frombase64(secret);
let votings = VoteRound::new();
VotePersona {
voter_keys: new_keys,
voting_round: votings,
}
}
pub fn return_keys(&self) -> &KeyPair
|
}
#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct VoteHash {
pub poll_hash: Vec<u8>,
pub vote_message: String,
pub vote_msgindex: i32,
pub vote_publickey: String,
}
impl VoteHash {
pub fn return_hash(&self) -> String {
let encoded = json::encode(&self).unwrap();
let the_sha = Sha256dHash::from_data(&encoded.as_bytes());
the_sha.to_string()
}
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct VoteRound {
pub poll_hash: Vec<u8>,
pub vote_hash: Vec<u8>,
pub vote_message: String,
pub vote_msgindex: i32,
pub vote_signature: Vec<u8>,
pub vote_publickey: String,
}
impl VoteRound {
pub fn new() -> VoteRound {
VoteRound {
poll_hash: Vec::new(),
vote_hash: Vec::new(),
vote_message: String::new(),
vote_msgindex: 0,
vote_signature: Vec::new(),
vote_publickey: String::new(),
}
}
///form a vote taking a poll json string, and a VotePersona
pub fn from_poll(poll_round: String, persona: VotePersona) -> VoteRound {
//get the poll's hash
//need to validate the poll contents as well
let poll = PollRound::poll_fromjson(poll_round);
let poll_hash = poll.return_pollhash();
let mut pollhash: Vec<u8> = Vec::new();
for a in poll_hash.iter() {
pollhash.push(*a);
}
let pollhash_clone = pollhash.clone();
let poll_choices = poll.return_pollchoices();
let vote_index = VoteRound::select_answer(poll_choices);
let vote_string = poll_choices[vote_index as usize].to_string();
let vstring_clone = vote_string.clone();
let keys = persona.voter_keys;
let pk_string = KeyPair::address_base58(&keys.public);
let pkstr_clone = pk_string.clone();
let vote_hash = VoteHash {
poll_hash: pollhash,
vote_message: vote_string,
vote_msgindex: vote_index,
vote_publickey: pk_string,
};
let vote_hash = vote_hash.return_hash();
let vhash_clone = vote_hash.clone();
let vote_signature = KeyPair::sign(&keys.secret, vote_hash.into_bytes());
let the_vote = VoteRound {
poll_hash: pollhash_clone,
vote_hash: vhash_clone.into_bytes(),
vote_message: vstring_clone,
vote_msgindex: vote_index,
vote_signature: vote_signature,
vote_publickey: pkstr_clone,
};
the_vote
//let poll_data: PollRound = json::decode(&poll_round).unwrap();
//let poll_hash =
}
///forms a vote using a VotePersona import keys
pub fn form_vote() {
let persona = VotePersona::import_keys();
println!("please enter path of the poll you intend to vote on");
let mut path = String::new();
let stdin = io::stdin();
stdin.lock().read_line(&mut path).unwrap();
let path_trim = path.trim_right_matches("\n");
let path = Path::new(&path_trim);
let display = "a";
let mut file = match OpenOptions::new().read(true).write(false).open(path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let mut file_string = String::new();
match file.read_to_string(&mut file_string) {
Err(why) => panic!("couldn't read {}: {}", display, Error::description(&why)),
Ok(_) => println!("ok"),
}
let the_poll: PollRound = json::decode(&file_string).unwrap();
let key_hash160 = KeyPair::address_base58(&persona.voter_keys.public);
let key_hashclone = key_hash160.clone();
let addresses = the_poll.return_eligibleaddresses();
if addresses.check_existence(key_hash160) == true {
let vote = VoteRound::from_poll(the_poll.return_jsonstring(), persona);
vote.write_vote();
} else {
println!("you have the wrong kind of key");
}
}
///helper function to accept answers from a poll through commandline by index
pub fn select_answer(poll_choices: &[String]) -> i32 {
println!("choices are: ");
let mut index = 0;
for choice in poll_choices.iter() {
println!("index {:?}, {:?}", index, choice);
index += 1;
}
println!("enter the index number of your selection");
let mut input2 = String::new();
let stdin2 = io::stdin();
stdin2.lock().read_line(&mut input2).unwrap();
let trimmed = input2.trim_right_matches("\n");
let the_index: i32 = trimmed.parse().ok().expect("invalid input");
the_index
}
///writes the vote to a file
pub fn write_vote(&self) {
let mut the_home_dir = String::new();
let home_dirclone = the_home_dir.clone();
match env::home_dir() {
Some(ref p) => the_home_dir = p.display().to_string(),
None => println!("Impossible to get your home dir!")
}
let vote_hash = self.return_votehash();
let mut votehash: Vec<u8> = Vec::new();
for a in vote_hash.iter() {
votehash.push(*a);
}
let hash_path = String::from_utf8(votehash).unwrap();
let path_string = String::from("/make_votes/");
let app_root = home_dirclone + "/make_votes/";
make_app_root_dir(app_root);
let path_string2 = path_string + &hash_path;
let path_string3 = path_string2 + ".vote";
let path_string4 = the_home_dir + &path_string3;
let path = Path::new(&path_string4);
println!("{:?}", path);
touch(&path).unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
let display = "a";
let mut file = match OpenOptions::new().read(true).write(true).open(path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let encoded = VoteRound::return_jsonstring(self);
let json_str = encoded.to_string();
file.write_all(&encoded.as_bytes()).unwrap();
}
///returns a json encoded string from the VoteRound struct
pub fn return_jsonstring(&self) -> String {
let encoded = json::encode(&self).unwrap();
encoded
}
///returns a VoteRound struct based on a json encoded string
pub fn vote_fromjson(json: String) -> VoteRound {
let vote_data: VoteRound = json::decode(&json).unwrap();
vote_data
}
///returns the vote hash from the VoteRound struct
pub fn return_votehash(&self) -> &[u8] {
&self.vote_hash[..]
}
///returns the poll hash from the VoteRound struct
pub fn return_pollhash(&self) -> &[u8] {
&self.poll_hash[..]
}
///returns the signature from the VoteRound struct
pub fn return_signature(&self) -> &[u8] {
&self.vote_signature
}
///returns the string of the vote answer from the poll
pub fn return_votemsg(&self) -> String {
let our_string = self.vote_message.to_string();
our_string
}
///returns the index of the vote as per the poll
pub fn return_voteindex(&self) -> i32 {
let mut int = 0;
int += self.vote_msgindex;
int
}
///returns the index of the vote as per the poll
pub fn return_votecount(&self, list: &OmniList) -> i32 {
list.return_balance(self.vote_publickey.to_string())
}
///returns a VoteRound from a file path
pub fn return_votefromfile(path: &Path) -> VoteRound {
let display = "a";
let mut file = match OpenOptions::new().read(true).write(false).open(path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let mut file_string = String::new();
match file.read_to_string(&mut file_string) {
Err(why) => panic!("couldn't read {}: {}", display, Error::description(&why)),
Ok(_) => println!("ok"),
}
let the_vote: VoteRound = json::decode(&file_string).unwrap();
the_vote
}
}
|
{
&self.voter_keys
}
|
identifier_body
|
vote_genesis.rs
|
//this module spits out a structured vote as json data
//save the vote to a file
use safex::genesis::key_generation::KeyPair;
use utils::get_address_methods::OmniList;
use utils::dirs::{make_app_root_dir, touch};
use voting::poll_genesis::PollRound;
use voting::validate_genesis::VotingOutcome;
use rustc_serialize::{Decodable, Decoder};
use rustc_serialize::json::{self, ToJson, Json};
use bitcoin::util::hash::Sha256dHash;
use std::error::Error;
use std::fs;
use std::fs::File;
use std::path::Path;
use std::env;
use std::io::Write;
use std::io;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::{BufRead};
pub struct VotePersona {
voter_keys: KeyPair,
voting_round: VoteRound,
}
impl VotePersona {
pub fn import_keys() -> VotePersona {
println!("input your private key");
let mut input2 = String::new();
let stdin2 = io::stdin();
stdin2.lock().read_line(&mut input2).unwrap();
let trimmed = input2.trim_right_matches("\n");
let persona = VotePersona::persona_fromstring(trimmed.to_string());
persona
}
pub fn persona_fromstring(secret: String) -> VotePersona {
let new_keys = KeyPair::keypair_frombase64(secret);
let votings = VoteRound::new();
VotePersona {
voter_keys: new_keys,
voting_round: votings,
}
}
pub fn return_keys(&self) -> &KeyPair {
&self.voter_keys
}
}
#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct VoteHash {
pub poll_hash: Vec<u8>,
pub vote_message: String,
pub vote_msgindex: i32,
pub vote_publickey: String,
}
impl VoteHash {
pub fn return_hash(&self) -> String {
let encoded = json::encode(&self).unwrap();
let the_sha = Sha256dHash::from_data(&encoded.as_bytes());
the_sha.to_string()
}
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct VoteRound {
pub poll_hash: Vec<u8>,
pub vote_hash: Vec<u8>,
pub vote_message: String,
pub vote_msgindex: i32,
pub vote_signature: Vec<u8>,
pub vote_publickey: String,
}
impl VoteRound {
pub fn new() -> VoteRound {
VoteRound {
poll_hash: Vec::new(),
vote_hash: Vec::new(),
vote_message: String::new(),
vote_msgindex: 0,
vote_signature: Vec::new(),
vote_publickey: String::new(),
}
}
///form a vote taking a poll json string, and a VotePersona
pub fn from_poll(poll_round: String, persona: VotePersona) -> VoteRound {
//get the poll's hash
//need to validate the poll contents as well
let poll = PollRound::poll_fromjson(poll_round);
let poll_hash = poll.return_pollhash();
let mut pollhash: Vec<u8> = Vec::new();
for a in poll_hash.iter() {
pollhash.push(*a);
}
let pollhash_clone = pollhash.clone();
let poll_choices = poll.return_pollchoices();
let vote_index = VoteRound::select_answer(poll_choices);
let vote_string = poll_choices[vote_index as usize].to_string();
let vstring_clone = vote_string.clone();
let keys = persona.voter_keys;
let pk_string = KeyPair::address_base58(&keys.public);
let pkstr_clone = pk_string.clone();
let vote_hash = VoteHash {
poll_hash: pollhash,
vote_message: vote_string,
vote_msgindex: vote_index,
vote_publickey: pk_string,
};
let vote_hash = vote_hash.return_hash();
let vhash_clone = vote_hash.clone();
let vote_signature = KeyPair::sign(&keys.secret, vote_hash.into_bytes());
let the_vote = VoteRound {
poll_hash: pollhash_clone,
vote_hash: vhash_clone.into_bytes(),
vote_message: vstring_clone,
vote_msgindex: vote_index,
vote_signature: vote_signature,
vote_publickey: pkstr_clone,
};
the_vote
//let poll_data: PollRound = json::decode(&poll_round).unwrap();
//let poll_hash =
}
///forms a vote using a VotePersona import keys
pub fn form_vote() {
|
let persona = VotePersona::import_keys();
println!("please enter path of the poll you intend to vote on");
let mut path = String::new();
let stdin = io::stdin();
stdin.lock().read_line(&mut path).unwrap();
let path_trim = path.trim_right_matches("\n");
let path = Path::new(&path_trim);
let display = "a";
let mut file = match OpenOptions::new().read(true).write(false).open(path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let mut file_string = String::new();
match file.read_to_string(&mut file_string) {
Err(why) => panic!("couldn't read {}: {}", display, Error::description(&why)),
Ok(_) => println!("ok"),
}
let the_poll: PollRound = json::decode(&file_string).unwrap();
let key_hash160 = KeyPair::address_base58(&persona.voter_keys.public);
let key_hashclone = key_hash160.clone();
let addresses = the_poll.return_eligibleaddresses();
if addresses.check_existence(key_hash160) == true {
let vote = VoteRound::from_poll(the_poll.return_jsonstring(), persona);
vote.write_vote();
} else {
println!("you have the wrong kind of key");
}
}
///helper function to accept answers from a poll through commandline by index
pub fn select_answer(poll_choices: &[String]) -> i32 {
println!("choices are: ");
let mut index = 0;
for choice in poll_choices.iter() {
println!("index {:?}, {:?}", index, choice);
index += 1;
}
println!("enter the index number of your selection");
let mut input2 = String::new();
let stdin2 = io::stdin();
stdin2.lock().read_line(&mut input2).unwrap();
let trimmed = input2.trim_right_matches("\n");
let the_index: i32 = trimmed.parse().ok().expect("invalid input");
the_index
}
///writes the vote to a file
pub fn write_vote(&self) {
let mut the_home_dir = String::new();
let home_dirclone = the_home_dir.clone();
match env::home_dir() {
Some(ref p) => the_home_dir = p.display().to_string(),
None => println!("Impossible to get your home dir!")
}
let vote_hash = self.return_votehash();
let mut votehash: Vec<u8> = Vec::new();
for a in vote_hash.iter() {
votehash.push(*a);
}
let hash_path = String::from_utf8(votehash).unwrap();
let path_string = String::from("/make_votes/");
let app_root = home_dirclone + "/make_votes/";
make_app_root_dir(app_root);
let path_string2 = path_string + &hash_path;
let path_string3 = path_string2 + ".vote";
let path_string4 = the_home_dir + &path_string3;
let path = Path::new(&path_string4);
println!("{:?}", path);
touch(&path).unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
let display = "a";
let mut file = match OpenOptions::new().read(true).write(true).open(path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let encoded = VoteRound::return_jsonstring(self);
let json_str = encoded.to_string();
file.write_all(&encoded.as_bytes()).unwrap();
}
///returns a json encoded string from the VoteRound struct
pub fn return_jsonstring(&self) -> String {
let encoded = json::encode(&self).unwrap();
encoded
}
///returns a VoteRound struct based on a json encoded string
pub fn vote_fromjson(json: String) -> VoteRound {
let vote_data: VoteRound = json::decode(&json).unwrap();
vote_data
}
///returns the vote hash from the VoteRound struct
pub fn return_votehash(&self) -> &[u8] {
&self.vote_hash[..]
}
///returns the poll hash from the VoteRound struct
pub fn return_pollhash(&self) -> &[u8] {
&self.poll_hash[..]
}
///returns the signature from the VoteRound struct
pub fn return_signature(&self) -> &[u8] {
&self.vote_signature
}
///returns the string of the vote answer from the poll
pub fn return_votemsg(&self) -> String {
let our_string = self.vote_message.to_string();
our_string
}
///returns the index of the vote as per the poll
pub fn return_voteindex(&self) -> i32 {
let mut int = 0;
int += self.vote_msgindex;
int
}
///returns the index of the vote as per the poll
pub fn return_votecount(&self, list: &OmniList) -> i32 {
list.return_balance(self.vote_publickey.to_string())
}
///returns a VoteRound from a file path
pub fn return_votefromfile(path: &Path) -> VoteRound {
let display = "a";
let mut file = match OpenOptions::new().read(true).write(false).open(path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let mut file_string = String::new();
match file.read_to_string(&mut file_string) {
Err(why) => panic!("couldn't read {}: {}", display, Error::description(&why)),
Ok(_) => println!("ok"),
}
let the_vote: VoteRound = json::decode(&file_string).unwrap();
the_vote
}
}
|
random_line_split
|
|
vote_genesis.rs
|
//this module spits out a structured vote as json data
//save the vote to a file
use safex::genesis::key_generation::KeyPair;
use utils::get_address_methods::OmniList;
use utils::dirs::{make_app_root_dir, touch};
use voting::poll_genesis::PollRound;
use voting::validate_genesis::VotingOutcome;
use rustc_serialize::{Decodable, Decoder};
use rustc_serialize::json::{self, ToJson, Json};
use bitcoin::util::hash::Sha256dHash;
use std::error::Error;
use std::fs;
use std::fs::File;
use std::path::Path;
use std::env;
use std::io::Write;
use std::io;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::{BufRead};
pub struct VotePersona {
voter_keys: KeyPair,
voting_round: VoteRound,
}
impl VotePersona {
pub fn import_keys() -> VotePersona {
println!("input your private key");
let mut input2 = String::new();
let stdin2 = io::stdin();
stdin2.lock().read_line(&mut input2).unwrap();
let trimmed = input2.trim_right_matches("\n");
let persona = VotePersona::persona_fromstring(trimmed.to_string());
persona
}
pub fn persona_fromstring(secret: String) -> VotePersona {
let new_keys = KeyPair::keypair_frombase64(secret);
let votings = VoteRound::new();
VotePersona {
voter_keys: new_keys,
voting_round: votings,
}
}
pub fn return_keys(&self) -> &KeyPair {
&self.voter_keys
}
}
#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct VoteHash {
pub poll_hash: Vec<u8>,
pub vote_message: String,
pub vote_msgindex: i32,
pub vote_publickey: String,
}
impl VoteHash {
pub fn return_hash(&self) -> String {
let encoded = json::encode(&self).unwrap();
let the_sha = Sha256dHash::from_data(&encoded.as_bytes());
the_sha.to_string()
}
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct VoteRound {
pub poll_hash: Vec<u8>,
pub vote_hash: Vec<u8>,
pub vote_message: String,
pub vote_msgindex: i32,
pub vote_signature: Vec<u8>,
pub vote_publickey: String,
}
impl VoteRound {
pub fn new() -> VoteRound {
VoteRound {
poll_hash: Vec::new(),
vote_hash: Vec::new(),
vote_message: String::new(),
vote_msgindex: 0,
vote_signature: Vec::new(),
vote_publickey: String::new(),
}
}
///form a vote taking a poll json string, and a VotePersona
pub fn from_poll(poll_round: String, persona: VotePersona) -> VoteRound {
//get the poll's hash
//need to validate the poll contents as well
let poll = PollRound::poll_fromjson(poll_round);
let poll_hash = poll.return_pollhash();
let mut pollhash: Vec<u8> = Vec::new();
for a in poll_hash.iter() {
pollhash.push(*a);
}
let pollhash_clone = pollhash.clone();
let poll_choices = poll.return_pollchoices();
let vote_index = VoteRound::select_answer(poll_choices);
let vote_string = poll_choices[vote_index as usize].to_string();
let vstring_clone = vote_string.clone();
let keys = persona.voter_keys;
let pk_string = KeyPair::address_base58(&keys.public);
let pkstr_clone = pk_string.clone();
let vote_hash = VoteHash {
poll_hash: pollhash,
vote_message: vote_string,
vote_msgindex: vote_index,
vote_publickey: pk_string,
};
let vote_hash = vote_hash.return_hash();
let vhash_clone = vote_hash.clone();
let vote_signature = KeyPair::sign(&keys.secret, vote_hash.into_bytes());
let the_vote = VoteRound {
poll_hash: pollhash_clone,
vote_hash: vhash_clone.into_bytes(),
vote_message: vstring_clone,
vote_msgindex: vote_index,
vote_signature: vote_signature,
vote_publickey: pkstr_clone,
};
the_vote
//let poll_data: PollRound = json::decode(&poll_round).unwrap();
//let poll_hash =
}
///forms a vote using a VotePersona import keys
pub fn form_vote() {
let persona = VotePersona::import_keys();
println!("please enter path of the poll you intend to vote on");
let mut path = String::new();
let stdin = io::stdin();
stdin.lock().read_line(&mut path).unwrap();
let path_trim = path.trim_right_matches("\n");
let path = Path::new(&path_trim);
let display = "a";
let mut file = match OpenOptions::new().read(true).write(false).open(path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let mut file_string = String::new();
match file.read_to_string(&mut file_string) {
Err(why) => panic!("couldn't read {}: {}", display, Error::description(&why)),
Ok(_) => println!("ok"),
}
let the_poll: PollRound = json::decode(&file_string).unwrap();
let key_hash160 = KeyPair::address_base58(&persona.voter_keys.public);
let key_hashclone = key_hash160.clone();
let addresses = the_poll.return_eligibleaddresses();
if addresses.check_existence(key_hash160) == true {
let vote = VoteRound::from_poll(the_poll.return_jsonstring(), persona);
vote.write_vote();
} else {
println!("you have the wrong kind of key");
}
}
///helper function to accept answers from a poll through commandline by index
pub fn select_answer(poll_choices: &[String]) -> i32 {
println!("choices are: ");
let mut index = 0;
for choice in poll_choices.iter() {
println!("index {:?}, {:?}", index, choice);
index += 1;
}
println!("enter the index number of your selection");
let mut input2 = String::new();
let stdin2 = io::stdin();
stdin2.lock().read_line(&mut input2).unwrap();
let trimmed = input2.trim_right_matches("\n");
let the_index: i32 = trimmed.parse().ok().expect("invalid input");
the_index
}
///writes the vote to a file
pub fn write_vote(&self) {
let mut the_home_dir = String::new();
let home_dirclone = the_home_dir.clone();
match env::home_dir() {
Some(ref p) => the_home_dir = p.display().to_string(),
None => println!("Impossible to get your home dir!")
}
let vote_hash = self.return_votehash();
let mut votehash: Vec<u8> = Vec::new();
for a in vote_hash.iter() {
votehash.push(*a);
}
let hash_path = String::from_utf8(votehash).unwrap();
let path_string = String::from("/make_votes/");
let app_root = home_dirclone + "/make_votes/";
make_app_root_dir(app_root);
let path_string2 = path_string + &hash_path;
let path_string3 = path_string2 + ".vote";
let path_string4 = the_home_dir + &path_string3;
let path = Path::new(&path_string4);
println!("{:?}", path);
touch(&path).unwrap_or_else(|why| {
println!("! {:?}", why.kind());
});
let display = "a";
let mut file = match OpenOptions::new().read(true).write(true).open(path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let encoded = VoteRound::return_jsonstring(self);
let json_str = encoded.to_string();
file.write_all(&encoded.as_bytes()).unwrap();
}
///returns a json encoded string from the VoteRound struct
pub fn return_jsonstring(&self) -> String {
let encoded = json::encode(&self).unwrap();
encoded
}
///returns a VoteRound struct based on a json encoded string
pub fn vote_fromjson(json: String) -> VoteRound {
let vote_data: VoteRound = json::decode(&json).unwrap();
vote_data
}
///returns the vote hash from the VoteRound struct
pub fn return_votehash(&self) -> &[u8] {
&self.vote_hash[..]
}
///returns the poll hash from the VoteRound struct
pub fn return_pollhash(&self) -> &[u8] {
&self.poll_hash[..]
}
///returns the signature from the VoteRound struct
pub fn return_signature(&self) -> &[u8] {
&self.vote_signature
}
///returns the string of the vote answer from the poll
pub fn return_votemsg(&self) -> String {
let our_string = self.vote_message.to_string();
our_string
}
///returns the index of the vote as per the poll
pub fn return_voteindex(&self) -> i32 {
let mut int = 0;
int += self.vote_msgindex;
int
}
///returns the index of the vote as per the poll
pub fn
|
(&self, list: &OmniList) -> i32 {
list.return_balance(self.vote_publickey.to_string())
}
///returns a VoteRound from a file path
pub fn return_votefromfile(path: &Path) -> VoteRound {
let display = "a";
let mut file = match OpenOptions::new().read(true).write(false).open(path) {
// The `description` method of `io::Error` returns a string that
// describes the error
Err(why) => panic!("couldn't open {}: {}", display, Error::description(&why)),
Ok(file) => file,
};
let mut file_string = String::new();
match file.read_to_string(&mut file_string) {
Err(why) => panic!("couldn't read {}: {}", display, Error::description(&why)),
Ok(_) => println!("ok"),
}
let the_vote: VoteRound = json::decode(&file_string).unwrap();
the_vote
}
}
|
return_votecount
|
identifier_name
|
workerlocation.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerLocationBinding;
use dom::bindings::codegen::Bindings::WorkerLocationBinding::WorkerLocationMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::{DOMString, USVString};
use dom::urlhelper::UrlHelper;
use dom::workerglobalscope::WorkerGlobalScope;
use url::Url;
// https://html.spec.whatwg.org/multipage/#worker-locations
#[dom_struct]
pub struct
|
{
reflector_: Reflector,
url: Url,
}
impl WorkerLocation {
fn new_inherited(url: Url) -> WorkerLocation {
WorkerLocation {
reflector_: Reflector::new(),
url: url,
}
}
pub fn new(global: &WorkerGlobalScope, url: Url) -> Root<WorkerLocation> {
reflect_dom_object(box WorkerLocation::new_inherited(url),
GlobalRef::Worker(global),
WorkerLocationBinding::Wrap)
}
}
impl WorkerLocationMethods for WorkerLocation {
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-hash
fn Hash(&self) -> USVString {
UrlHelper::Hash(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-host
fn Host(&self) -> USVString {
UrlHelper::Host(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-hostname
fn Hostname(&self) -> USVString {
UrlHelper::Hostname(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-href
fn Href(&self) -> USVString {
UrlHelper::Href(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-pathname
fn Pathname(&self) -> USVString {
UrlHelper::Pathname(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-port
fn Port(&self) -> USVString {
UrlHelper::Port(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-protocol
fn Protocol(&self) -> USVString {
UrlHelper::Protocol(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-search
fn Search(&self) -> USVString {
UrlHelper::Search(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-href
fn Stringifier(&self) -> DOMString {
DOMString::from(self.Href().0)
}
}
|
WorkerLocation
|
identifier_name
|
workerlocation.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerLocationBinding;
use dom::bindings::codegen::Bindings::WorkerLocationBinding::WorkerLocationMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::{DOMString, USVString};
use dom::urlhelper::UrlHelper;
use dom::workerglobalscope::WorkerGlobalScope;
use url::Url;
// https://html.spec.whatwg.org/multipage/#worker-locations
#[dom_struct]
pub struct WorkerLocation {
reflector_: Reflector,
url: Url,
}
impl WorkerLocation {
fn new_inherited(url: Url) -> WorkerLocation {
WorkerLocation {
reflector_: Reflector::new(),
url: url,
}
}
pub fn new(global: &WorkerGlobalScope, url: Url) -> Root<WorkerLocation> {
reflect_dom_object(box WorkerLocation::new_inherited(url),
GlobalRef::Worker(global),
WorkerLocationBinding::Wrap)
}
}
impl WorkerLocationMethods for WorkerLocation {
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-hash
fn Hash(&self) -> USVString {
UrlHelper::Hash(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-host
fn Host(&self) -> USVString {
UrlHelper::Host(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-hostname
fn Hostname(&self) -> USVString {
UrlHelper::Hostname(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-href
fn Href(&self) -> USVString {
UrlHelper::Href(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-pathname
fn Pathname(&self) -> USVString {
UrlHelper::Pathname(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-port
fn Port(&self) -> USVString {
UrlHelper::Port(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-protocol
fn Protocol(&self) -> USVString
|
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-search
fn Search(&self) -> USVString {
UrlHelper::Search(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-href
fn Stringifier(&self) -> DOMString {
DOMString::from(self.Href().0)
}
}
|
{
UrlHelper::Protocol(&self.url)
}
|
identifier_body
|
workerlocation.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerLocationBinding;
|
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::{DOMString, USVString};
use dom::urlhelper::UrlHelper;
use dom::workerglobalscope::WorkerGlobalScope;
use url::Url;
// https://html.spec.whatwg.org/multipage/#worker-locations
#[dom_struct]
pub struct WorkerLocation {
reflector_: Reflector,
url: Url,
}
impl WorkerLocation {
fn new_inherited(url: Url) -> WorkerLocation {
WorkerLocation {
reflector_: Reflector::new(),
url: url,
}
}
pub fn new(global: &WorkerGlobalScope, url: Url) -> Root<WorkerLocation> {
reflect_dom_object(box WorkerLocation::new_inherited(url),
GlobalRef::Worker(global),
WorkerLocationBinding::Wrap)
}
}
impl WorkerLocationMethods for WorkerLocation {
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-hash
fn Hash(&self) -> USVString {
UrlHelper::Hash(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-host
fn Host(&self) -> USVString {
UrlHelper::Host(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-hostname
fn Hostname(&self) -> USVString {
UrlHelper::Hostname(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-href
fn Href(&self) -> USVString {
UrlHelper::Href(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-pathname
fn Pathname(&self) -> USVString {
UrlHelper::Pathname(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-port
fn Port(&self) -> USVString {
UrlHelper::Port(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-protocol
fn Protocol(&self) -> USVString {
UrlHelper::Protocol(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-search
fn Search(&self) -> USVString {
UrlHelper::Search(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-href
fn Stringifier(&self) -> DOMString {
DOMString::from(self.Href().0)
}
}
|
use dom::bindings::codegen::Bindings::WorkerLocationBinding::WorkerLocationMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
|
random_line_split
|
tag_sets.rs
|
// Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.
//! Various sets of HTML tag names, and macros for declaring them.
use string_cache::QualName;
macro_rules! declare_tag_set_impl ( ($param:ident, $b:ident, $supr:ident, $($tag:tt)+) => (
match $param {
$( qualname!(HTML, $tag) => $b, )+
p => $supr(p),
}
));
macro_rules! declare_tag_set_body (
($param:ident = $supr:ident - $($tag:tt)+)
=> ( declare_tag_set_impl!($param, false, $supr, $($tag)+) );
($param:ident = $supr:ident + $($tag:tt)+)
=> ( declare_tag_set_impl!($param, true, $supr, $($tag)+) );
($param:ident = $($tag:tt)+)
=> ( declare_tag_set_impl!($param, true, empty_set, $($tag)+) );
);
macro_rules! declare_tag_set (
(pub $name:ident = $($toks:tt)+) => (
pub fn $name(p: ::string_cache::QualName) -> bool {
declare_tag_set_body!(p = $($toks)+)
}
);
($name:ident = $($toks:tt)+) => (
fn $name(p: ::string_cache::QualName) -> bool {
declare_tag_set_body!(p = $($toks)+)
}
);
);
#[inline(always)] pub fn
|
(_: QualName) -> bool { false }
#[inline(always)] pub fn full_set(_: QualName) -> bool { true }
// FIXME: MathML, SVG
declare_tag_set!(pub default_scope = applet caption html table td th marquee object template);
declare_tag_set!(pub list_item_scope = default_scope + ol ul);
declare_tag_set!(pub button_scope = default_scope + button);
declare_tag_set!(pub table_scope = html table template);
declare_tag_set!(pub select_scope = full_set - optgroup option);
declare_tag_set!(pub table_body_context = tbody tfoot thead template html);
declare_tag_set!(pub table_row_context = tr template html);
declare_tag_set!(pub td_th = td th);
declare_tag_set!(pub cursory_implied_end = dd dt li option optgroup p rp rt);
declare_tag_set!(pub thorough_implied_end = cursory_implied_end
+ caption colgroup tbody td tfoot th thead tr);
declare_tag_set!(pub heading_tag = h1 h2 h3 h4 h5 h6);
declare_tag_set!(pub special_tag =
address applet area article aside base basefont bgsound blockquote body br button caption
center col colgroup dd details dir div dl dt embed fieldset figcaption figure footer form
frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html iframe img input isindex li
link listing main marquee menu menuitem meta nav noembed noframes noscript object ol p
param plaintext pre script section select source style summary table tbody td template
textarea tfoot th thead title tr track ul wbr xmp);
//§ END
|
empty_set
|
identifier_name
|
tag_sets.rs
|
// Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.
//! Various sets of HTML tag names, and macros for declaring them.
use string_cache::QualName;
macro_rules! declare_tag_set_impl ( ($param:ident, $b:ident, $supr:ident, $($tag:tt)+) => (
match $param {
$( qualname!(HTML, $tag) => $b, )+
p => $supr(p),
}
));
macro_rules! declare_tag_set_body (
($param:ident = $supr:ident - $($tag:tt)+)
=> ( declare_tag_set_impl!($param, false, $supr, $($tag)+) );
($param:ident = $supr:ident + $($tag:tt)+)
=> ( declare_tag_set_impl!($param, true, $supr, $($tag)+) );
($param:ident = $($tag:tt)+)
=> ( declare_tag_set_impl!($param, true, empty_set, $($tag)+) );
);
macro_rules! declare_tag_set (
(pub $name:ident = $($toks:tt)+) => (
pub fn $name(p: ::string_cache::QualName) -> bool {
declare_tag_set_body!(p = $($toks)+)
}
);
($name:ident = $($toks:tt)+) => (
fn $name(p: ::string_cache::QualName) -> bool {
declare_tag_set_body!(p = $($toks)+)
}
);
);
#[inline(always)] pub fn empty_set(_: QualName) -> bool { false }
#[inline(always)] pub fn full_set(_: QualName) -> bool
|
// FIXME: MathML, SVG
declare_tag_set!(pub default_scope = applet caption html table td th marquee object template);
declare_tag_set!(pub list_item_scope = default_scope + ol ul);
declare_tag_set!(pub button_scope = default_scope + button);
declare_tag_set!(pub table_scope = html table template);
declare_tag_set!(pub select_scope = full_set - optgroup option);
declare_tag_set!(pub table_body_context = tbody tfoot thead template html);
declare_tag_set!(pub table_row_context = tr template html);
declare_tag_set!(pub td_th = td th);
declare_tag_set!(pub cursory_implied_end = dd dt li option optgroup p rp rt);
declare_tag_set!(pub thorough_implied_end = cursory_implied_end
+ caption colgroup tbody td tfoot th thead tr);
declare_tag_set!(pub heading_tag = h1 h2 h3 h4 h5 h6);
declare_tag_set!(pub special_tag =
address applet area article aside base basefont bgsound blockquote body br button caption
center col colgroup dd details dir div dl dt embed fieldset figcaption figure footer form
frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html iframe img input isindex li
link listing main marquee menu menuitem meta nav noembed noframes noscript object ol p
param plaintext pre script section select source style summary table tbody td template
textarea tfoot th thead title tr track ul wbr xmp);
//§ END
|
{ true }
|
identifier_body
|
tag_sets.rs
|
// Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// 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.
//! Various sets of HTML tag names, and macros for declaring them.
use string_cache::QualName;
macro_rules! declare_tag_set_impl ( ($param:ident, $b:ident, $supr:ident, $($tag:tt)+) => (
match $param {
$( qualname!(HTML, $tag) => $b, )+
p => $supr(p),
}
));
macro_rules! declare_tag_set_body (
($param:ident = $supr:ident - $($tag:tt)+)
=> ( declare_tag_set_impl!($param, false, $supr, $($tag)+) );
($param:ident = $supr:ident + $($tag:tt)+)
=> ( declare_tag_set_impl!($param, true, $supr, $($tag)+) );
($param:ident = $($tag:tt)+)
=> ( declare_tag_set_impl!($param, true, empty_set, $($tag)+) );
);
macro_rules! declare_tag_set (
(pub $name:ident = $($toks:tt)+) => (
pub fn $name(p: ::string_cache::QualName) -> bool {
declare_tag_set_body!(p = $($toks)+)
}
);
($name:ident = $($toks:tt)+) => (
fn $name(p: ::string_cache::QualName) -> bool {
declare_tag_set_body!(p = $($toks)+)
}
);
);
#[inline(always)] pub fn empty_set(_: QualName) -> bool { false }
#[inline(always)] pub fn full_set(_: QualName) -> bool { true }
// FIXME: MathML, SVG
declare_tag_set!(pub default_scope = applet caption html table td th marquee object template);
declare_tag_set!(pub list_item_scope = default_scope + ol ul);
declare_tag_set!(pub button_scope = default_scope + button);
declare_tag_set!(pub table_scope = html table template);
declare_tag_set!(pub select_scope = full_set - optgroup option);
declare_tag_set!(pub table_body_context = tbody tfoot thead template html);
declare_tag_set!(pub table_row_context = tr template html);
declare_tag_set!(pub td_th = td th);
declare_tag_set!(pub cursory_implied_end = dd dt li option optgroup p rp rt);
declare_tag_set!(pub thorough_implied_end = cursory_implied_end
+ caption colgroup tbody td tfoot th thead tr);
declare_tag_set!(pub heading_tag = h1 h2 h3 h4 h5 h6);
declare_tag_set!(pub special_tag =
address applet area article aside base basefont bgsound blockquote body br button caption
center col colgroup dd details dir div dl dt embed fieldset figcaption figure footer form
|
frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html iframe img input isindex li
link listing main marquee menu menuitem meta nav noembed noframes noscript object ol p
param plaintext pre script section select source style summary table tbody td template
textarea tfoot th thead title tr track ul wbr xmp);
//§ END
|
random_line_split
|
|
group_device_list.rs
|
use dioxus::prelude::*;
use dioxus_router::use_route;
use fermi::use_read;
use homectl_types::group::GroupId;
use crate::{app_state::GROUPS_ATOM, device_list::DeviceList, scene_list::SceneList};
#[allow(non_snake_case)]
pub fn GroupDeviceList(cx: Scope) -> Element
|
{
let group_id: GroupId = use_route(&cx).segment("group_id")?.ok()?;
let groups = use_read(&cx, GROUPS_ATOM);
let (_, group) = groups
.iter()
.find(|(candidate_group_id, _)| *candidate_group_id == &group_id)?;
let name = &group.name;
cx.render(rsx! {
DeviceList { filters: Some(group.device_ids.clone()) }
h2 { class: "mt-4", "{name} scenes:" }
SceneList { filter_by_device_ids: group.device_ids.clone() }
})
}
|
identifier_body
|
|
group_device_list.rs
|
use dioxus::prelude::*;
use dioxus_router::use_route;
use fermi::use_read;
use homectl_types::group::GroupId;
use crate::{app_state::GROUPS_ATOM, device_list::DeviceList, scene_list::SceneList};
#[allow(non_snake_case)]
pub fn
|
(cx: Scope) -> Element {
let group_id: GroupId = use_route(&cx).segment("group_id")?.ok()?;
let groups = use_read(&cx, GROUPS_ATOM);
let (_, group) = groups
.iter()
.find(|(candidate_group_id, _)| *candidate_group_id == &group_id)?;
let name = &group.name;
cx.render(rsx! {
DeviceList { filters: Some(group.device_ids.clone()) }
h2 { class: "mt-4", "{name} scenes:" }
SceneList { filter_by_device_ids: group.device_ids.clone() }
})
}
|
GroupDeviceList
|
identifier_name
|
group_device_list.rs
|
use dioxus::prelude::*;
use dioxus_router::use_route;
|
use homectl_types::group::GroupId;
use crate::{app_state::GROUPS_ATOM, device_list::DeviceList, scene_list::SceneList};
#[allow(non_snake_case)]
pub fn GroupDeviceList(cx: Scope) -> Element {
let group_id: GroupId = use_route(&cx).segment("group_id")?.ok()?;
let groups = use_read(&cx, GROUPS_ATOM);
let (_, group) = groups
.iter()
.find(|(candidate_group_id, _)| *candidate_group_id == &group_id)?;
let name = &group.name;
cx.render(rsx! {
DeviceList { filters: Some(group.device_ids.clone()) }
h2 { class: "mt-4", "{name} scenes:" }
SceneList { filter_by_device_ids: group.device_ids.clone() }
})
}
|
use fermi::use_read;
|
random_line_split
|
pad.rs
|
use ffi::*;
use caps::Caps;
use reference::Reference;
use object::Object;
use std::ptr;
use std::mem;
use std::ops::{Deref, DerefMut};
pub struct Pad{
pad: Object
}
#[derive(Debug)]
#[repr(isize)]
pub enum LinkReturn{
WrongHierarchy = GST_PAD_LINK_WRONG_HIERARCHY as isize,
WasLinked = GST_PAD_LINK_WAS_LINKED as isize,
WrongDirection = GST_PAD_LINK_WRONG_DIRECTION as isize,
NoFormat = GST_PAD_LINK_NOFORMAT as isize,
NoSched = GST_PAD_LINK_NOSCHED as isize,
Refused = GST_PAD_LINK_REFUSED as isize,
}
impl Pad{
pub unsafe fn new(pad: *mut GstPad) -> Option<Pad>{
Object::new(pad as *mut GstObject).map(|obj| Pad{ pad: obj })
}
pub fn link(&mut self, sink: &mut Pad) -> Result<(), LinkReturn>{
unsafe{
let ret = gst_pad_link(self.gst_pad_mut(), sink.gst_pad_mut());
if ret == GST_PAD_LINK_OK{
Ok(())
}else{
Err(mem::transmute(ret as isize))
}
}
}
pub fn is_linked(&self) -> bool{
unsafe{
let pad: &mut GstPad = mem::transmute(self.gst_pad());
pad.peer!= ptr::null_mut()
}
}
pub fn query_caps(&self, filter: Option<Caps>) -> Option<Caps>{
unsafe{
let caps = gst_pad_query_caps(self.gst_pad() as *mut GstPad, filter.map(|mut caps| caps.gst_caps_mut()).unwrap_or(ptr::null_mut()));
Caps::new(caps)
}
}
pub unsafe fn gst_pad(&self) -> *const GstPad{
self.pad.gst_object() as *const GstPad
|
}
impl ::Transfer<GstPad> for Pad{
unsafe fn transfer(self) -> *mut GstPad{
self.pad.transfer() as *mut GstPad
}
}
impl Reference for Pad{
fn reference(&self) -> Pad{
Pad{ pad: self.pad.reference() }
}
}
impl AsRef<Object> for Pad{
fn as_ref(&self) -> &Object{
&self.pad
}
}
impl AsMut<Object> for Pad{
fn as_mut(&mut self) -> &mut Object{
&mut self.pad
}
}
impl From<Pad> for Object{
fn from(b: Pad) -> Object{
b.pad
}
}
impl Deref for Pad{
type Target = Object;
fn deref(&self) -> &Object{
&self.pad
}
}
impl DerefMut for Pad{
fn deref_mut(&mut self) -> &mut Object{
&mut self.pad
}
}
|
}
pub unsafe fn gst_pad_mut(&mut self) -> *mut GstPad{
self.pad.gst_object_mut() as *mut GstPad
}
|
random_line_split
|
pad.rs
|
use ffi::*;
use caps::Caps;
use reference::Reference;
use object::Object;
use std::ptr;
use std::mem;
use std::ops::{Deref, DerefMut};
pub struct Pad{
pad: Object
}
#[derive(Debug)]
#[repr(isize)]
pub enum LinkReturn{
WrongHierarchy = GST_PAD_LINK_WRONG_HIERARCHY as isize,
WasLinked = GST_PAD_LINK_WAS_LINKED as isize,
WrongDirection = GST_PAD_LINK_WRONG_DIRECTION as isize,
NoFormat = GST_PAD_LINK_NOFORMAT as isize,
NoSched = GST_PAD_LINK_NOSCHED as isize,
Refused = GST_PAD_LINK_REFUSED as isize,
}
impl Pad{
pub unsafe fn new(pad: *mut GstPad) -> Option<Pad>{
Object::new(pad as *mut GstObject).map(|obj| Pad{ pad: obj })
}
pub fn link(&mut self, sink: &mut Pad) -> Result<(), LinkReturn>{
unsafe{
let ret = gst_pad_link(self.gst_pad_mut(), sink.gst_pad_mut());
if ret == GST_PAD_LINK_OK{
Ok(())
}else
|
}
}
pub fn is_linked(&self) -> bool{
unsafe{
let pad: &mut GstPad = mem::transmute(self.gst_pad());
pad.peer!= ptr::null_mut()
}
}
pub fn query_caps(&self, filter: Option<Caps>) -> Option<Caps>{
unsafe{
let caps = gst_pad_query_caps(self.gst_pad() as *mut GstPad, filter.map(|mut caps| caps.gst_caps_mut()).unwrap_or(ptr::null_mut()));
Caps::new(caps)
}
}
pub unsafe fn gst_pad(&self) -> *const GstPad{
self.pad.gst_object() as *const GstPad
}
pub unsafe fn gst_pad_mut(&mut self) -> *mut GstPad{
self.pad.gst_object_mut() as *mut GstPad
}
}
impl ::Transfer<GstPad> for Pad{
unsafe fn transfer(self) -> *mut GstPad{
self.pad.transfer() as *mut GstPad
}
}
impl Reference for Pad{
fn reference(&self) -> Pad{
Pad{ pad: self.pad.reference() }
}
}
impl AsRef<Object> for Pad{
fn as_ref(&self) -> &Object{
&self.pad
}
}
impl AsMut<Object> for Pad{
fn as_mut(&mut self) -> &mut Object{
&mut self.pad
}
}
impl From<Pad> for Object{
fn from(b: Pad) -> Object{
b.pad
}
}
impl Deref for Pad{
type Target = Object;
fn deref(&self) -> &Object{
&self.pad
}
}
impl DerefMut for Pad{
fn deref_mut(&mut self) -> &mut Object{
&mut self.pad
}
}
|
{
Err(mem::transmute(ret as isize))
}
|
conditional_block
|
pad.rs
|
use ffi::*;
use caps::Caps;
use reference::Reference;
use object::Object;
use std::ptr;
use std::mem;
use std::ops::{Deref, DerefMut};
pub struct Pad{
pad: Object
}
#[derive(Debug)]
#[repr(isize)]
pub enum LinkReturn{
WrongHierarchy = GST_PAD_LINK_WRONG_HIERARCHY as isize,
WasLinked = GST_PAD_LINK_WAS_LINKED as isize,
WrongDirection = GST_PAD_LINK_WRONG_DIRECTION as isize,
NoFormat = GST_PAD_LINK_NOFORMAT as isize,
NoSched = GST_PAD_LINK_NOSCHED as isize,
Refused = GST_PAD_LINK_REFUSED as isize,
}
impl Pad{
pub unsafe fn new(pad: *mut GstPad) -> Option<Pad>{
Object::new(pad as *mut GstObject).map(|obj| Pad{ pad: obj })
}
pub fn link(&mut self, sink: &mut Pad) -> Result<(), LinkReturn>{
unsafe{
let ret = gst_pad_link(self.gst_pad_mut(), sink.gst_pad_mut());
if ret == GST_PAD_LINK_OK{
Ok(())
}else{
Err(mem::transmute(ret as isize))
}
}
}
pub fn
|
(&self) -> bool{
unsafe{
let pad: &mut GstPad = mem::transmute(self.gst_pad());
pad.peer!= ptr::null_mut()
}
}
pub fn query_caps(&self, filter: Option<Caps>) -> Option<Caps>{
unsafe{
let caps = gst_pad_query_caps(self.gst_pad() as *mut GstPad, filter.map(|mut caps| caps.gst_caps_mut()).unwrap_or(ptr::null_mut()));
Caps::new(caps)
}
}
pub unsafe fn gst_pad(&self) -> *const GstPad{
self.pad.gst_object() as *const GstPad
}
pub unsafe fn gst_pad_mut(&mut self) -> *mut GstPad{
self.pad.gst_object_mut() as *mut GstPad
}
}
impl ::Transfer<GstPad> for Pad{
unsafe fn transfer(self) -> *mut GstPad{
self.pad.transfer() as *mut GstPad
}
}
impl Reference for Pad{
fn reference(&self) -> Pad{
Pad{ pad: self.pad.reference() }
}
}
impl AsRef<Object> for Pad{
fn as_ref(&self) -> &Object{
&self.pad
}
}
impl AsMut<Object> for Pad{
fn as_mut(&mut self) -> &mut Object{
&mut self.pad
}
}
impl From<Pad> for Object{
fn from(b: Pad) -> Object{
b.pad
}
}
impl Deref for Pad{
type Target = Object;
fn deref(&self) -> &Object{
&self.pad
}
}
impl DerefMut for Pad{
fn deref_mut(&mut self) -> &mut Object{
&mut self.pad
}
}
|
is_linked
|
identifier_name
|
pad.rs
|
use ffi::*;
use caps::Caps;
use reference::Reference;
use object::Object;
use std::ptr;
use std::mem;
use std::ops::{Deref, DerefMut};
pub struct Pad{
pad: Object
}
#[derive(Debug)]
#[repr(isize)]
pub enum LinkReturn{
WrongHierarchy = GST_PAD_LINK_WRONG_HIERARCHY as isize,
WasLinked = GST_PAD_LINK_WAS_LINKED as isize,
WrongDirection = GST_PAD_LINK_WRONG_DIRECTION as isize,
NoFormat = GST_PAD_LINK_NOFORMAT as isize,
NoSched = GST_PAD_LINK_NOSCHED as isize,
Refused = GST_PAD_LINK_REFUSED as isize,
}
impl Pad{
pub unsafe fn new(pad: *mut GstPad) -> Option<Pad>{
Object::new(pad as *mut GstObject).map(|obj| Pad{ pad: obj })
}
pub fn link(&mut self, sink: &mut Pad) -> Result<(), LinkReturn>{
unsafe{
let ret = gst_pad_link(self.gst_pad_mut(), sink.gst_pad_mut());
if ret == GST_PAD_LINK_OK{
Ok(())
}else{
Err(mem::transmute(ret as isize))
}
}
}
pub fn is_linked(&self) -> bool{
unsafe{
let pad: &mut GstPad = mem::transmute(self.gst_pad());
pad.peer!= ptr::null_mut()
}
}
pub fn query_caps(&self, filter: Option<Caps>) -> Option<Caps>{
unsafe{
let caps = gst_pad_query_caps(self.gst_pad() as *mut GstPad, filter.map(|mut caps| caps.gst_caps_mut()).unwrap_or(ptr::null_mut()));
Caps::new(caps)
}
}
pub unsafe fn gst_pad(&self) -> *const GstPad{
self.pad.gst_object() as *const GstPad
}
pub unsafe fn gst_pad_mut(&mut self) -> *mut GstPad{
self.pad.gst_object_mut() as *mut GstPad
}
}
impl ::Transfer<GstPad> for Pad{
unsafe fn transfer(self) -> *mut GstPad{
self.pad.transfer() as *mut GstPad
}
}
impl Reference for Pad{
fn reference(&self) -> Pad
|
}
impl AsRef<Object> for Pad{
fn as_ref(&self) -> &Object{
&self.pad
}
}
impl AsMut<Object> for Pad{
fn as_mut(&mut self) -> &mut Object{
&mut self.pad
}
}
impl From<Pad> for Object{
fn from(b: Pad) -> Object{
b.pad
}
}
impl Deref for Pad{
type Target = Object;
fn deref(&self) -> &Object{
&self.pad
}
}
impl DerefMut for Pad{
fn deref_mut(&mut self) -> &mut Object{
&mut self.pad
}
}
|
{
Pad{ pad: self.pad.reference() }
}
|
identifier_body
|
visitor.rs
|
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use kythe::corpus::Corpus;
use kythe::schema::{Complete, EdgeKind, Fact, NodeKind, VName};
use kythe::writer::EntryWriter;
use rustc::hir;
use rustc::hir::{Block, Expr, ImplItem, ItemId, Pat};
use rustc::hir::def_id::DefId;
use rustc::hir::Expr_::{ExprCall, ExprLoop, ExprMatch, ExprMethodCall, ExprPath};
use rustc::hir::intravisit::*;
use rustc::hir::MatchSource::ForLoopDesugar;
use rustc::lint::{LateContext, LintContext};
use rustc::ty::{MethodCall, TyCtxt};
use syntax::ast;
use syntax::codemap::{CodeMap, Pos, Span, Spanned};
/// Indexes all kythe entries except files
pub struct KytheVisitor<'a, 'tcx: 'a> {
pub writer: &'a Box<EntryWriter>,
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
pub codemap: &'a CodeMap,
pub corpus: &'a Corpus,
/// The vname of the parent item. The value changes as we recurse through the HIR, and is used
/// for childof relationships
parent_vname: Option<VName>,
}
impl<'a, 'tcx> KytheVisitor<'a, 'tcx> {
/// Creates a new KytheVisitor
pub fn new(writer: &'a Box<EntryWriter>,
corpus: &'a Corpus,
cx: &'a LateContext<'a, 'tcx>)
-> KytheVisitor<'a, 'tcx> {
KytheVisitor {
writer: writer,
tcx: cx.tcx,
codemap: cx.sess().codemap(),
corpus: corpus,
parent_vname: None,
}
}
/// Emits the appropriate node and facts for an anchor defined by a span
/// and returns the node's VName
fn anchor_from_span(&self, span: Span) -> VName {
let start = self.codemap.lookup_byte_offset(span.lo);
let end = self.codemap.lookup_byte_offset(span.hi);
let start_byte = start.pos.to_usize();
let end_byte = end.pos.to_usize();
|
fn anchor_from_sub_span(&self, span: Span, sub: &str) -> Result<VName, String> {
let start = self.codemap.lookup_byte_offset(span.lo);
let snippet = match self.codemap.span_to_snippet(span) {
Ok(s) => s,
Err(e) => return Err(format!("{:?}", e)),
};
let sub_start = match snippet.find(sub) {
None => return Err(format!("Substring: '{}' not found in snippet '{}'", sub, snippet)),
Some(s) => s,
};
let start_byte = start.pos.to_usize() + sub_start;
let end_byte = start_byte + sub.len();
Ok(self.anchor(&start.fm.name, start_byte, end_byte))
}
/// Emits an anchor node based on the byte range provided
fn anchor(&self, file_name: &str, start_byte: usize, end_byte: usize) -> VName {
let vname = self.corpus.anchor_vname(file_name, start_byte, end_byte);
let start_str: String = start_byte.to_string();
let end_str: String = end_byte.to_string();
let file_vname = self.corpus.file_vname(&file_name);
self.writer.node(&vname, Fact::NodeKind, &NodeKind::Anchor);
self.writer.node(&vname, Fact::LocStart, &start_str);
self.writer.node(&vname, Fact::LocEnd, &end_str);
self.writer.edge(&vname, EdgeKind::ChildOf, &file_vname);
vname
}
/// Produces a vname unique to a given DefId
fn vname_from_defid(&self, def_id: DefId) -> VName {
let def_id_num = def_id.index.as_u32();
let var_name = self.tcx.absolute_item_path_str(def_id);
self.corpus.def_vname(&var_name, def_id_num)
}
/// Emits the appropriate ref/call and childof nodes for a function call
fn function_call(&self, call_node_id: ast::NodeId, callee_def_id: DefId) {
let call_span = self.tcx.map.span(call_node_id);
// The call anchor includes the subject (if function is a method) and the params
let call_anchor_vname = self.anchor_from_span(call_span);
let callee_vname = self.vname_from_defid(callee_def_id);
self.writer.edge(&call_anchor_vname, EdgeKind::RefCall, &callee_vname);
if let Some(ref parent_vname) = self.parent_vname {
self.writer.edge(&call_anchor_vname, EdgeKind::ChildOf, &parent_vname);
}
}
}
/// Tests whether a span is the result of macro expansion
fn is_from_macro(span: &Span) -> bool {
span.expn_id.into_u32()!= u32::max_value()
}
impl<'v, 'tcx: 'v> Visitor<'v> for KytheVisitor<'v, 'tcx> {
/// Enables recursing through nested items
fn visit_nested_item(&mut self, id: ItemId) {
let item = self.tcx.map.expect_item(id.id);
self.visit_item(item);
}
/// Captures variable bindings
fn visit_pat(&mut self, pat: &'v Pat) {
use rustc::hir::PatKind::Binding;
if let Binding(_, _, _) = pat.node {
if let Some(def) = self.tcx.expect_def_or_none(pat.id) {
let local_vname = self.vname_from_defid(def.def_id());
let anchor_vname = self.anchor_from_span(pat.span);
self.writer.edge(&anchor_vname, EdgeKind::DefinesBinding, &local_vname);
self.writer.node(&local_vname, Fact::NodeKind, &NodeKind::Variable);
}
}
walk_pat(self, pat);
}
/// Navigates the visitor around desugared for loops while hitting their important
/// components
fn visit_block(&mut self, block: &'v Block) {
// Desugaring for loops turns:
// [opt_ident]: for <pat> in <head> {
// <body>
// }
//
// into
//
// {
// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
// mut iter => {
// [opt_ident]: loop {
// match ::std::iter::Iterator::next(&mut iter) {
// ::std::option::Option::Some(<pat>) => <body>,
// ::std::option::Option::None => break
// }
// }
// }
// };
// result
// }
//
// Here we check block contents to pick out <pat> <head> and <body>
use rustc::hir::Decl_::DeclLocal;
use rustc::hir::Stmt_::StmtDecl;
use rustc::hir::PatKind::TupleStruct;
if let [Spanned { node: StmtDecl(ref decl, _),.. }] = *block.stmts {
if let DeclLocal(ref local) = decl.node {
if let Some(ref expr) = local.init {
if let ExprMatch(ref base, ref outer_arms, ForLoopDesugar) = expr.node {
if let ExprCall(_, ref args) = base.node {
if let ExprLoop(ref block, _) = outer_arms[0].body.node {
if let Some(ref expr) = block.expr {
if let ExprMatch(_, ref arms, _) = expr.node {
if let TupleStruct(_, ref pats, _) = arms[0].pats[0].node {
// Walk the interesting parts of <head>
for a in args {
self.visit_expr(&a);
}
// Walk <pat>
self.visit_pat(&pats[0]);
// Walk <body>
self.visit_expr(&arms[0].body);
return;
}
}
}
}
}
}
}
}
}
walk_block(self, block);
}
/// Captures refs and ref/calls
fn visit_expr(&mut self, expr: &'v Expr) {
if is_from_macro(&expr.span) {
return walk_expr(self, expr);
}
match expr.node {
// Paths are static references to items (including static methods)
ExprPath(..) => {
if let Some(def) = self.tcx.expect_def_or_none(expr.id) {
let def_id = def.def_id();
let local_vname = self.vname_from_defid(def_id);
let anchor_vname = self.anchor_from_span(expr.span);
self.writer.edge(&anchor_vname, EdgeKind::Ref, &local_vname);
}
}
// Method calls are calls to any impl_fn that consumes self (requiring a vtable)
ExprMethodCall(sp_name, _, _) => {
let callee = self.tcx.tables.borrow().method_map[&MethodCall::expr(expr.id)];
let local_vname = self.vname_from_defid(callee.def_id);
let anchor_vname = self.anchor_from_span(sp_name.span);
self.function_call(expr.id, callee.def_id);
self.writer.edge(&anchor_vname, EdgeKind::Ref, &local_vname);
}
// Calls to statically addressable functions. The ref edge is handled in the ExprPath
// branch
ExprCall(ref fn_expr, _) => {
let callee = self.tcx.def_map.borrow()[&fn_expr.id].base_def;
self.function_call(expr.id, callee.def_id());
}
_ => (),
}
walk_expr(self, expr);
}
/// Captures function and method decl/bindings
fn visit_fn(&mut self,
kind: hir::intravisit::FnKind<'v>,
decl: &'v hir::FnDecl,
body: &'v hir::Block,
span: Span,
id: ast::NodeId) {
use rustc::hir::intravisit::FnKind;
match kind {
FnKind::ItemFn(n, _, _, _, _, _, _) |
FnKind::Method(n, _, _, _) => {
let fn_name = n.to_string();
let def_id = self.tcx.map.get_parent_did(body.id);
let fn_vname = self.vname_from_defid(def_id);
let decl_vname = self.anchor_from_span(span);
self.writer.node(&fn_vname, Fact::NodeKind, &NodeKind::Function);
self.writer.node(&fn_vname, Fact::Complete, &Complete::Definition);
self.writer.edge(&decl_vname, EdgeKind::Defines, &fn_vname);
if let Ok(bind_vname) = self.anchor_from_sub_span(span, &fn_name) {
self.writer.edge(&bind_vname, EdgeKind::DefinesBinding, &fn_vname)
}
}
_ => (),
};
walk_fn(self, kind, decl, body, span, id);
}
/// Called instead of visit_item for items inside an impl, this function sets the
/// parent_vname to the impl's vname
fn visit_impl_item(&mut self, impl_item: &'v ImplItem) {
let old_parent = self.parent_vname.clone();
let def_id = self.tcx.map.local_def_id(impl_item.id);
self.parent_vname = Some(self.vname_from_defid(def_id));
walk_impl_item(self, impl_item);
self.parent_vname = old_parent;
}
/// Run on every module-level item. Currently we only capture static and const items.
/// (Functions are handled in visit_fn)
fn visit_item(&mut self, item: &'v hir::Item) {
let old_parent = self.parent_vname.clone();
let def_id = self.tcx.map.local_def_id(item.id);
let def_name = item.name.to_string();
let def_vname = self.vname_from_defid(def_id);
use rustc::hir::Item_::*;
match item.node {
ItemStatic(..) | ItemConst(..) => {
let kind = if let ItemStatic(..) = item.node {
NodeKind::Variable
} else {
NodeKind::Constant
};
let anchor_vname = self.anchor_from_span(item.span);
self.writer.node(&def_vname, Fact::NodeKind, &kind);
self.writer.edge(&anchor_vname, EdgeKind::Defines, &def_vname);
// Substring matching is suboptimal, but there doesn't appear to be an accessible
// node or span for the item name
if let Ok(bind_vname) = self.anchor_from_sub_span(item.span, &def_name) {
self.writer.edge(&bind_vname, EdgeKind::DefinesBinding, &def_vname)
}
}
_ => (),
}
self.parent_vname = Some(self.vname_from_defid(def_id));
walk_item(self, item);
self.parent_vname = old_parent;
}
}
|
self.anchor(&start.fm.name, start_byte, end_byte)
}
/// Emits the appropriate node and facts for an anchor defined as a substring within a span
/// and returns the node's VName
|
random_line_split
|
visitor.rs
|
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use kythe::corpus::Corpus;
use kythe::schema::{Complete, EdgeKind, Fact, NodeKind, VName};
use kythe::writer::EntryWriter;
use rustc::hir;
use rustc::hir::{Block, Expr, ImplItem, ItemId, Pat};
use rustc::hir::def_id::DefId;
use rustc::hir::Expr_::{ExprCall, ExprLoop, ExprMatch, ExprMethodCall, ExprPath};
use rustc::hir::intravisit::*;
use rustc::hir::MatchSource::ForLoopDesugar;
use rustc::lint::{LateContext, LintContext};
use rustc::ty::{MethodCall, TyCtxt};
use syntax::ast;
use syntax::codemap::{CodeMap, Pos, Span, Spanned};
/// Indexes all kythe entries except files
pub struct KytheVisitor<'a, 'tcx: 'a> {
pub writer: &'a Box<EntryWriter>,
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
pub codemap: &'a CodeMap,
pub corpus: &'a Corpus,
/// The vname of the parent item. The value changes as we recurse through the HIR, and is used
/// for childof relationships
parent_vname: Option<VName>,
}
impl<'a, 'tcx> KytheVisitor<'a, 'tcx> {
/// Creates a new KytheVisitor
pub fn new(writer: &'a Box<EntryWriter>,
corpus: &'a Corpus,
cx: &'a LateContext<'a, 'tcx>)
-> KytheVisitor<'a, 'tcx> {
KytheVisitor {
writer: writer,
tcx: cx.tcx,
codemap: cx.sess().codemap(),
corpus: corpus,
parent_vname: None,
}
}
/// Emits the appropriate node and facts for an anchor defined by a span
/// and returns the node's VName
fn anchor_from_span(&self, span: Span) -> VName {
let start = self.codemap.lookup_byte_offset(span.lo);
let end = self.codemap.lookup_byte_offset(span.hi);
let start_byte = start.pos.to_usize();
let end_byte = end.pos.to_usize();
self.anchor(&start.fm.name, start_byte, end_byte)
}
/// Emits the appropriate node and facts for an anchor defined as a substring within a span
/// and returns the node's VName
fn anchor_from_sub_span(&self, span: Span, sub: &str) -> Result<VName, String> {
let start = self.codemap.lookup_byte_offset(span.lo);
let snippet = match self.codemap.span_to_snippet(span) {
Ok(s) => s,
Err(e) => return Err(format!("{:?}", e)),
};
let sub_start = match snippet.find(sub) {
None => return Err(format!("Substring: '{}' not found in snippet '{}'", sub, snippet)),
Some(s) => s,
};
let start_byte = start.pos.to_usize() + sub_start;
let end_byte = start_byte + sub.len();
Ok(self.anchor(&start.fm.name, start_byte, end_byte))
}
/// Emits an anchor node based on the byte range provided
fn anchor(&self, file_name: &str, start_byte: usize, end_byte: usize) -> VName {
let vname = self.corpus.anchor_vname(file_name, start_byte, end_byte);
let start_str: String = start_byte.to_string();
let end_str: String = end_byte.to_string();
let file_vname = self.corpus.file_vname(&file_name);
self.writer.node(&vname, Fact::NodeKind, &NodeKind::Anchor);
self.writer.node(&vname, Fact::LocStart, &start_str);
self.writer.node(&vname, Fact::LocEnd, &end_str);
self.writer.edge(&vname, EdgeKind::ChildOf, &file_vname);
vname
}
/// Produces a vname unique to a given DefId
fn vname_from_defid(&self, def_id: DefId) -> VName {
let def_id_num = def_id.index.as_u32();
let var_name = self.tcx.absolute_item_path_str(def_id);
self.corpus.def_vname(&var_name, def_id_num)
}
/// Emits the appropriate ref/call and childof nodes for a function call
fn function_call(&self, call_node_id: ast::NodeId, callee_def_id: DefId) {
let call_span = self.tcx.map.span(call_node_id);
// The call anchor includes the subject (if function is a method) and the params
let call_anchor_vname = self.anchor_from_span(call_span);
let callee_vname = self.vname_from_defid(callee_def_id);
self.writer.edge(&call_anchor_vname, EdgeKind::RefCall, &callee_vname);
if let Some(ref parent_vname) = self.parent_vname {
self.writer.edge(&call_anchor_vname, EdgeKind::ChildOf, &parent_vname);
}
}
}
/// Tests whether a span is the result of macro expansion
fn is_from_macro(span: &Span) -> bool {
span.expn_id.into_u32()!= u32::max_value()
}
impl<'v, 'tcx: 'v> Visitor<'v> for KytheVisitor<'v, 'tcx> {
/// Enables recursing through nested items
fn visit_nested_item(&mut self, id: ItemId) {
let item = self.tcx.map.expect_item(id.id);
self.visit_item(item);
}
/// Captures variable bindings
fn visit_pat(&mut self, pat: &'v Pat) {
use rustc::hir::PatKind::Binding;
if let Binding(_, _, _) = pat.node {
if let Some(def) = self.tcx.expect_def_or_none(pat.id) {
let local_vname = self.vname_from_defid(def.def_id());
let anchor_vname = self.anchor_from_span(pat.span);
self.writer.edge(&anchor_vname, EdgeKind::DefinesBinding, &local_vname);
self.writer.node(&local_vname, Fact::NodeKind, &NodeKind::Variable);
}
}
walk_pat(self, pat);
}
/// Navigates the visitor around desugared for loops while hitting their important
/// components
fn visit_block(&mut self, block: &'v Block) {
// Desugaring for loops turns:
// [opt_ident]: for <pat> in <head> {
// <body>
// }
//
// into
//
// {
// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
// mut iter => {
// [opt_ident]: loop {
// match ::std::iter::Iterator::next(&mut iter) {
// ::std::option::Option::Some(<pat>) => <body>,
// ::std::option::Option::None => break
// }
// }
// }
// };
// result
// }
//
// Here we check block contents to pick out <pat> <head> and <body>
use rustc::hir::Decl_::DeclLocal;
use rustc::hir::Stmt_::StmtDecl;
use rustc::hir::PatKind::TupleStruct;
if let [Spanned { node: StmtDecl(ref decl, _),.. }] = *block.stmts {
if let DeclLocal(ref local) = decl.node {
if let Some(ref expr) = local.init {
if let ExprMatch(ref base, ref outer_arms, ForLoopDesugar) = expr.node {
if let ExprCall(_, ref args) = base.node {
if let ExprLoop(ref block, _) = outer_arms[0].body.node {
if let Some(ref expr) = block.expr {
if let ExprMatch(_, ref arms, _) = expr.node {
if let TupleStruct(_, ref pats, _) = arms[0].pats[0].node {
// Walk the interesting parts of <head>
for a in args {
self.visit_expr(&a);
}
// Walk <pat>
self.visit_pat(&pats[0]);
// Walk <body>
self.visit_expr(&arms[0].body);
return;
}
}
}
}
}
}
}
}
}
walk_block(self, block);
}
/// Captures refs and ref/calls
fn visit_expr(&mut self, expr: &'v Expr) {
if is_from_macro(&expr.span) {
return walk_expr(self, expr);
}
match expr.node {
// Paths are static references to items (including static methods)
ExprPath(..) => {
if let Some(def) = self.tcx.expect_def_or_none(expr.id) {
let def_id = def.def_id();
let local_vname = self.vname_from_defid(def_id);
let anchor_vname = self.anchor_from_span(expr.span);
self.writer.edge(&anchor_vname, EdgeKind::Ref, &local_vname);
}
}
// Method calls are calls to any impl_fn that consumes self (requiring a vtable)
ExprMethodCall(sp_name, _, _) => {
let callee = self.tcx.tables.borrow().method_map[&MethodCall::expr(expr.id)];
let local_vname = self.vname_from_defid(callee.def_id);
let anchor_vname = self.anchor_from_span(sp_name.span);
self.function_call(expr.id, callee.def_id);
self.writer.edge(&anchor_vname, EdgeKind::Ref, &local_vname);
}
// Calls to statically addressable functions. The ref edge is handled in the ExprPath
// branch
ExprCall(ref fn_expr, _) => {
let callee = self.tcx.def_map.borrow()[&fn_expr.id].base_def;
self.function_call(expr.id, callee.def_id());
}
_ => (),
}
walk_expr(self, expr);
}
/// Captures function and method decl/bindings
fn visit_fn(&mut self,
kind: hir::intravisit::FnKind<'v>,
decl: &'v hir::FnDecl,
body: &'v hir::Block,
span: Span,
id: ast::NodeId) {
use rustc::hir::intravisit::FnKind;
match kind {
FnKind::ItemFn(n, _, _, _, _, _, _) |
FnKind::Method(n, _, _, _) => {
let fn_name = n.to_string();
let def_id = self.tcx.map.get_parent_did(body.id);
let fn_vname = self.vname_from_defid(def_id);
let decl_vname = self.anchor_from_span(span);
self.writer.node(&fn_vname, Fact::NodeKind, &NodeKind::Function);
self.writer.node(&fn_vname, Fact::Complete, &Complete::Definition);
self.writer.edge(&decl_vname, EdgeKind::Defines, &fn_vname);
if let Ok(bind_vname) = self.anchor_from_sub_span(span, &fn_name) {
self.writer.edge(&bind_vname, EdgeKind::DefinesBinding, &fn_vname)
}
}
_ => (),
};
walk_fn(self, kind, decl, body, span, id);
}
/// Called instead of visit_item for items inside an impl, this function sets the
/// parent_vname to the impl's vname
fn
|
(&mut self, impl_item: &'v ImplItem) {
let old_parent = self.parent_vname.clone();
let def_id = self.tcx.map.local_def_id(impl_item.id);
self.parent_vname = Some(self.vname_from_defid(def_id));
walk_impl_item(self, impl_item);
self.parent_vname = old_parent;
}
/// Run on every module-level item. Currently we only capture static and const items.
/// (Functions are handled in visit_fn)
fn visit_item(&mut self, item: &'v hir::Item) {
let old_parent = self.parent_vname.clone();
let def_id = self.tcx.map.local_def_id(item.id);
let def_name = item.name.to_string();
let def_vname = self.vname_from_defid(def_id);
use rustc::hir::Item_::*;
match item.node {
ItemStatic(..) | ItemConst(..) => {
let kind = if let ItemStatic(..) = item.node {
NodeKind::Variable
} else {
NodeKind::Constant
};
let anchor_vname = self.anchor_from_span(item.span);
self.writer.node(&def_vname, Fact::NodeKind, &kind);
self.writer.edge(&anchor_vname, EdgeKind::Defines, &def_vname);
// Substring matching is suboptimal, but there doesn't appear to be an accessible
// node or span for the item name
if let Ok(bind_vname) = self.anchor_from_sub_span(item.span, &def_name) {
self.writer.edge(&bind_vname, EdgeKind::DefinesBinding, &def_vname)
}
}
_ => (),
}
self.parent_vname = Some(self.vname_from_defid(def_id));
walk_item(self, item);
self.parent_vname = old_parent;
}
}
|
visit_impl_item
|
identifier_name
|
visitor.rs
|
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use kythe::corpus::Corpus;
use kythe::schema::{Complete, EdgeKind, Fact, NodeKind, VName};
use kythe::writer::EntryWriter;
use rustc::hir;
use rustc::hir::{Block, Expr, ImplItem, ItemId, Pat};
use rustc::hir::def_id::DefId;
use rustc::hir::Expr_::{ExprCall, ExprLoop, ExprMatch, ExprMethodCall, ExprPath};
use rustc::hir::intravisit::*;
use rustc::hir::MatchSource::ForLoopDesugar;
use rustc::lint::{LateContext, LintContext};
use rustc::ty::{MethodCall, TyCtxt};
use syntax::ast;
use syntax::codemap::{CodeMap, Pos, Span, Spanned};
/// Indexes all kythe entries except files
pub struct KytheVisitor<'a, 'tcx: 'a> {
pub writer: &'a Box<EntryWriter>,
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
pub codemap: &'a CodeMap,
pub corpus: &'a Corpus,
/// The vname of the parent item. The value changes as we recurse through the HIR, and is used
/// for childof relationships
parent_vname: Option<VName>,
}
impl<'a, 'tcx> KytheVisitor<'a, 'tcx> {
/// Creates a new KytheVisitor
pub fn new(writer: &'a Box<EntryWriter>,
corpus: &'a Corpus,
cx: &'a LateContext<'a, 'tcx>)
-> KytheVisitor<'a, 'tcx> {
KytheVisitor {
writer: writer,
tcx: cx.tcx,
codemap: cx.sess().codemap(),
corpus: corpus,
parent_vname: None,
}
}
/// Emits the appropriate node and facts for an anchor defined by a span
/// and returns the node's VName
fn anchor_from_span(&self, span: Span) -> VName {
let start = self.codemap.lookup_byte_offset(span.lo);
let end = self.codemap.lookup_byte_offset(span.hi);
let start_byte = start.pos.to_usize();
let end_byte = end.pos.to_usize();
self.anchor(&start.fm.name, start_byte, end_byte)
}
/// Emits the appropriate node and facts for an anchor defined as a substring within a span
/// and returns the node's VName
fn anchor_from_sub_span(&self, span: Span, sub: &str) -> Result<VName, String> {
let start = self.codemap.lookup_byte_offset(span.lo);
let snippet = match self.codemap.span_to_snippet(span) {
Ok(s) => s,
Err(e) => return Err(format!("{:?}", e)),
};
let sub_start = match snippet.find(sub) {
None => return Err(format!("Substring: '{}' not found in snippet '{}'", sub, snippet)),
Some(s) => s,
};
let start_byte = start.pos.to_usize() + sub_start;
let end_byte = start_byte + sub.len();
Ok(self.anchor(&start.fm.name, start_byte, end_byte))
}
/// Emits an anchor node based on the byte range provided
fn anchor(&self, file_name: &str, start_byte: usize, end_byte: usize) -> VName {
let vname = self.corpus.anchor_vname(file_name, start_byte, end_byte);
let start_str: String = start_byte.to_string();
let end_str: String = end_byte.to_string();
let file_vname = self.corpus.file_vname(&file_name);
self.writer.node(&vname, Fact::NodeKind, &NodeKind::Anchor);
self.writer.node(&vname, Fact::LocStart, &start_str);
self.writer.node(&vname, Fact::LocEnd, &end_str);
self.writer.edge(&vname, EdgeKind::ChildOf, &file_vname);
vname
}
/// Produces a vname unique to a given DefId
fn vname_from_defid(&self, def_id: DefId) -> VName {
let def_id_num = def_id.index.as_u32();
let var_name = self.tcx.absolute_item_path_str(def_id);
self.corpus.def_vname(&var_name, def_id_num)
}
/// Emits the appropriate ref/call and childof nodes for a function call
fn function_call(&self, call_node_id: ast::NodeId, callee_def_id: DefId) {
let call_span = self.tcx.map.span(call_node_id);
// The call anchor includes the subject (if function is a method) and the params
let call_anchor_vname = self.anchor_from_span(call_span);
let callee_vname = self.vname_from_defid(callee_def_id);
self.writer.edge(&call_anchor_vname, EdgeKind::RefCall, &callee_vname);
if let Some(ref parent_vname) = self.parent_vname {
self.writer.edge(&call_anchor_vname, EdgeKind::ChildOf, &parent_vname);
}
}
}
/// Tests whether a span is the result of macro expansion
fn is_from_macro(span: &Span) -> bool {
span.expn_id.into_u32()!= u32::max_value()
}
impl<'v, 'tcx: 'v> Visitor<'v> for KytheVisitor<'v, 'tcx> {
/// Enables recursing through nested items
fn visit_nested_item(&mut self, id: ItemId) {
let item = self.tcx.map.expect_item(id.id);
self.visit_item(item);
}
/// Captures variable bindings
fn visit_pat(&mut self, pat: &'v Pat) {
use rustc::hir::PatKind::Binding;
if let Binding(_, _, _) = pat.node {
if let Some(def) = self.tcx.expect_def_or_none(pat.id) {
let local_vname = self.vname_from_defid(def.def_id());
let anchor_vname = self.anchor_from_span(pat.span);
self.writer.edge(&anchor_vname, EdgeKind::DefinesBinding, &local_vname);
self.writer.node(&local_vname, Fact::NodeKind, &NodeKind::Variable);
}
}
walk_pat(self, pat);
}
/// Navigates the visitor around desugared for loops while hitting their important
/// components
fn visit_block(&mut self, block: &'v Block) {
// Desugaring for loops turns:
// [opt_ident]: for <pat> in <head> {
// <body>
// }
//
// into
//
// {
// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
// mut iter => {
// [opt_ident]: loop {
// match ::std::iter::Iterator::next(&mut iter) {
// ::std::option::Option::Some(<pat>) => <body>,
// ::std::option::Option::None => break
// }
// }
// }
// };
// result
// }
//
// Here we check block contents to pick out <pat> <head> and <body>
use rustc::hir::Decl_::DeclLocal;
use rustc::hir::Stmt_::StmtDecl;
use rustc::hir::PatKind::TupleStruct;
if let [Spanned { node: StmtDecl(ref decl, _),.. }] = *block.stmts {
if let DeclLocal(ref local) = decl.node {
if let Some(ref expr) = local.init {
if let ExprMatch(ref base, ref outer_arms, ForLoopDesugar) = expr.node
|
}
}
}
}
walk_block(self, block);
}
/// Captures refs and ref/calls
fn visit_expr(&mut self, expr: &'v Expr) {
if is_from_macro(&expr.span) {
return walk_expr(self, expr);
}
match expr.node {
// Paths are static references to items (including static methods)
ExprPath(..) => {
if let Some(def) = self.tcx.expect_def_or_none(expr.id) {
let def_id = def.def_id();
let local_vname = self.vname_from_defid(def_id);
let anchor_vname = self.anchor_from_span(expr.span);
self.writer.edge(&anchor_vname, EdgeKind::Ref, &local_vname);
}
}
// Method calls are calls to any impl_fn that consumes self (requiring a vtable)
ExprMethodCall(sp_name, _, _) => {
let callee = self.tcx.tables.borrow().method_map[&MethodCall::expr(expr.id)];
let local_vname = self.vname_from_defid(callee.def_id);
let anchor_vname = self.anchor_from_span(sp_name.span);
self.function_call(expr.id, callee.def_id);
self.writer.edge(&anchor_vname, EdgeKind::Ref, &local_vname);
}
// Calls to statically addressable functions. The ref edge is handled in the ExprPath
// branch
ExprCall(ref fn_expr, _) => {
let callee = self.tcx.def_map.borrow()[&fn_expr.id].base_def;
self.function_call(expr.id, callee.def_id());
}
_ => (),
}
walk_expr(self, expr);
}
/// Captures function and method decl/bindings
fn visit_fn(&mut self,
kind: hir::intravisit::FnKind<'v>,
decl: &'v hir::FnDecl,
body: &'v hir::Block,
span: Span,
id: ast::NodeId) {
use rustc::hir::intravisit::FnKind;
match kind {
FnKind::ItemFn(n, _, _, _, _, _, _) |
FnKind::Method(n, _, _, _) => {
let fn_name = n.to_string();
let def_id = self.tcx.map.get_parent_did(body.id);
let fn_vname = self.vname_from_defid(def_id);
let decl_vname = self.anchor_from_span(span);
self.writer.node(&fn_vname, Fact::NodeKind, &NodeKind::Function);
self.writer.node(&fn_vname, Fact::Complete, &Complete::Definition);
self.writer.edge(&decl_vname, EdgeKind::Defines, &fn_vname);
if let Ok(bind_vname) = self.anchor_from_sub_span(span, &fn_name) {
self.writer.edge(&bind_vname, EdgeKind::DefinesBinding, &fn_vname)
}
}
_ => (),
};
walk_fn(self, kind, decl, body, span, id);
}
/// Called instead of visit_item for items inside an impl, this function sets the
/// parent_vname to the impl's vname
fn visit_impl_item(&mut self, impl_item: &'v ImplItem) {
let old_parent = self.parent_vname.clone();
let def_id = self.tcx.map.local_def_id(impl_item.id);
self.parent_vname = Some(self.vname_from_defid(def_id));
walk_impl_item(self, impl_item);
self.parent_vname = old_parent;
}
/// Run on every module-level item. Currently we only capture static and const items.
/// (Functions are handled in visit_fn)
fn visit_item(&mut self, item: &'v hir::Item) {
let old_parent = self.parent_vname.clone();
let def_id = self.tcx.map.local_def_id(item.id);
let def_name = item.name.to_string();
let def_vname = self.vname_from_defid(def_id);
use rustc::hir::Item_::*;
match item.node {
ItemStatic(..) | ItemConst(..) => {
let kind = if let ItemStatic(..) = item.node {
NodeKind::Variable
} else {
NodeKind::Constant
};
let anchor_vname = self.anchor_from_span(item.span);
self.writer.node(&def_vname, Fact::NodeKind, &kind);
self.writer.edge(&anchor_vname, EdgeKind::Defines, &def_vname);
// Substring matching is suboptimal, but there doesn't appear to be an accessible
// node or span for the item name
if let Ok(bind_vname) = self.anchor_from_sub_span(item.span, &def_name) {
self.writer.edge(&bind_vname, EdgeKind::DefinesBinding, &def_vname)
}
}
_ => (),
}
self.parent_vname = Some(self.vname_from_defid(def_id));
walk_item(self, item);
self.parent_vname = old_parent;
}
}
|
{
if let ExprCall(_, ref args) = base.node {
if let ExprLoop(ref block, _) = outer_arms[0].body.node {
if let Some(ref expr) = block.expr {
if let ExprMatch(_, ref arms, _) = expr.node {
if let TupleStruct(_, ref pats, _) = arms[0].pats[0].node {
// Walk the interesting parts of <head>
for a in args {
self.visit_expr(&a);
}
// Walk <pat>
self.visit_pat(&pats[0]);
// Walk <body>
self.visit_expr(&arms[0].body);
return;
}
}
}
}
}
|
conditional_block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.