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 |
---|---|---|---|---|
content.rs
|
#![stable]
use libc;
use std;
/// Opaque struct which holds a reference to the underlying Clutter object.
#[repr(C)]
pub struct ContentRef {
opaque: *mut libc::c_void
}
/// Delegate for painting the content of an actor
///
/// Content is an interface to implement types responsible for painting the
/// content of an Actor.
///
/// Multiple actors can use the same Content instance, in order to share the
/// resources associated with painting the same content.
///
/// _Since 1.10_
pub trait Content {
/// Returns a pointer to the the underlying C object.
///
/// Generally only used internally.
fn as_content(&self) -> *mut libc::c_void;
/// Retrieves the natural size of the content, if any.
///
/// The natural size of a Content is defined as the size the content would
/// have regardless of the allocation of the actor that is painting it, for
/// instance the size of an image data.
///
/// _Since 1.10_
fn get_preferred_size(&mut self) -> (bool, f32, f32) {
unsafe {
let mut width:f32 = std::intrinsics::init();
let mut height:f32 = std::intrinsics::init();
let foreign_result = clutter_content_get_preferred_size(self.as_content(), &mut width, &mut height);
return (foreign_result!= 0, width, height);
}
}
/// Invalidates a Content.
///
/// This function should be called by Content implementations when they change
/// the way the content should be painted regardless of the actor state.
///
/// _Since 1.10_
fn
|
(&mut self) {
unsafe {
clutter_content_invalidate(self.as_content());
}
}
}
impl Content for ContentRef {
fn as_content(&self) -> *mut libc::c_void {
return self.opaque;
}
}
extern {
fn clutter_content_get_preferred_size(self_value: *mut libc::c_void, width: *mut f32, height: *mut f32) -> i32;
fn clutter_content_invalidate(self_value: *mut libc::c_void);
}
|
invalidate
|
identifier_name
|
content.rs
|
#![stable]
use libc;
use std;
/// Opaque struct which holds a reference to the underlying Clutter object.
#[repr(C)]
pub struct ContentRef {
opaque: *mut libc::c_void
}
/// Delegate for painting the content of an actor
///
/// Content is an interface to implement types responsible for painting the
/// content of an Actor.
///
/// Multiple actors can use the same Content instance, in order to share the
/// resources associated with painting the same content.
///
/// _Since 1.10_
pub trait Content {
/// Returns a pointer to the the underlying C object.
///
/// Generally only used internally.
fn as_content(&self) -> *mut libc::c_void;
/// Retrieves the natural size of the content, if any.
///
/// The natural size of a Content is defined as the size the content would
/// have regardless of the allocation of the actor that is painting it, for
/// instance the size of an image data.
///
/// _Since 1.10_
fn get_preferred_size(&mut self) -> (bool, f32, f32)
|
/// Invalidates a Content.
///
/// This function should be called by Content implementations when they change
/// the way the content should be painted regardless of the actor state.
///
/// _Since 1.10_
fn invalidate(&mut self) {
unsafe {
clutter_content_invalidate(self.as_content());
}
}
}
impl Content for ContentRef {
fn as_content(&self) -> *mut libc::c_void {
return self.opaque;
}
}
extern {
fn clutter_content_get_preferred_size(self_value: *mut libc::c_void, width: *mut f32, height: *mut f32) -> i32;
fn clutter_content_invalidate(self_value: *mut libc::c_void);
}
|
{
unsafe {
let mut width:f32 = std::intrinsics::init();
let mut height:f32 = std::intrinsics::init();
let foreign_result = clutter_content_get_preferred_size(self.as_content(), &mut width, &mut height);
return (foreign_result != 0, width, height);
}
}
|
identifier_body
|
issue-643-inner-struct.rs
|
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub const fn new() -> Self {
__IncompleteArrayField(::std::marker::PhantomData, [])
}
#[inline]
pub fn as_ptr(&self) -> *const T {
self as *const _ as *const T
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
self as *mut _ as *mut T
}
#[inline]
pub unsafe fn as_slice(&self, len: usize) -> &[T] {
::std::slice::from_raw_parts(self.as_ptr(), len)
}
#[inline]
pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] {
::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len)
}
}
impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> {
fn
|
(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_str("__IncompleteArrayField")
}
}
#[repr(C)]
#[derive(Debug)]
pub struct rte_ring {
pub memzone: *mut rte_memzone,
pub prod: rte_ring_prod,
pub cons: rte_ring_cons,
pub ring: __IncompleteArrayField<*mut ::std::os::raw::c_void>,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct rte_ring_prod {
pub watermark: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_test_layout_rte_ring_prod() {
assert_eq!(
::std::mem::size_of::<rte_ring_prod>(),
4usize,
concat!("Size of: ", stringify!(rte_ring_prod))
);
assert_eq!(
::std::mem::align_of::<rte_ring_prod>(),
4usize,
concat!("Alignment of ", stringify!(rte_ring_prod))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rte_ring_prod>())).watermark as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rte_ring_prod),
"::",
stringify!(watermark)
)
);
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct rte_ring_cons {
pub sc_dequeue: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_test_layout_rte_ring_cons() {
assert_eq!(
::std::mem::size_of::<rte_ring_cons>(),
4usize,
concat!("Size of: ", stringify!(rte_ring_cons))
);
assert_eq!(
::std::mem::align_of::<rte_ring_cons>(),
4usize,
concat!("Alignment of ", stringify!(rte_ring_cons))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rte_ring_cons>())).sc_dequeue as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rte_ring_cons),
"::",
stringify!(sc_dequeue)
)
);
}
#[test]
fn bindgen_test_layout_rte_ring() {
assert_eq!(
::std::mem::size_of::<rte_ring>(),
16usize,
concat!("Size of: ", stringify!(rte_ring))
);
assert_eq!(
::std::mem::align_of::<rte_ring>(),
8usize,
concat!("Alignment of ", stringify!(rte_ring))
);
}
impl Default for rte_ring {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct rte_memzone {
pub _address: u8,
}
|
fmt
|
identifier_name
|
issue-643-inner-struct.rs
|
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Default)]
pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>, [T; 0]);
impl<T> __IncompleteArrayField<T> {
#[inline]
pub const fn new() -> Self {
__IncompleteArrayField(::std::marker::PhantomData, [])
}
#[inline]
pub fn as_ptr(&self) -> *const T {
self as *const _ as *const T
}
#[inline]
pub fn as_mut_ptr(&mut self) -> *mut T {
self as *mut _ as *mut T
}
#[inline]
pub unsafe fn as_slice(&self, len: usize) -> &[T] {
::std::slice::from_raw_parts(self.as_ptr(), len)
}
#[inline]
pub unsafe fn as_mut_slice(&mut self, len: usize) -> &mut [T] {
::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len)
}
}
impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
fmt.write_str("__IncompleteArrayField")
}
}
#[repr(C)]
#[derive(Debug)]
pub struct rte_ring {
pub memzone: *mut rte_memzone,
pub prod: rte_ring_prod,
pub cons: rte_ring_cons,
pub ring: __IncompleteArrayField<*mut ::std::os::raw::c_void>,
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct rte_ring_prod {
pub watermark: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_test_layout_rte_ring_prod() {
assert_eq!(
::std::mem::size_of::<rte_ring_prod>(),
4usize,
concat!("Size of: ", stringify!(rte_ring_prod))
);
assert_eq!(
::std::mem::align_of::<rte_ring_prod>(),
4usize,
concat!("Alignment of ", stringify!(rte_ring_prod))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<rte_ring_prod>())).watermark as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rte_ring_prod),
"::",
stringify!(watermark)
)
);
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct rte_ring_cons {
pub sc_dequeue: ::std::os::raw::c_uint,
}
#[test]
fn bindgen_test_layout_rte_ring_cons() {
assert_eq!(
::std::mem::size_of::<rte_ring_cons>(),
4usize,
concat!("Size of: ", stringify!(rte_ring_cons))
);
assert_eq!(
::std::mem::align_of::<rte_ring_cons>(),
4usize,
concat!("Alignment of ", stringify!(rte_ring_cons))
|
&(*(::std::ptr::null::<rte_ring_cons>())).sc_dequeue as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(rte_ring_cons),
"::",
stringify!(sc_dequeue)
)
);
}
#[test]
fn bindgen_test_layout_rte_ring() {
assert_eq!(
::std::mem::size_of::<rte_ring>(),
16usize,
concat!("Size of: ", stringify!(rte_ring))
);
assert_eq!(
::std::mem::align_of::<rte_ring>(),
8usize,
concat!("Alignment of ", stringify!(rte_ring))
);
}
impl Default for rte_ring {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct rte_memzone {
pub _address: u8,
}
|
);
assert_eq!(
unsafe {
|
random_line_split
|
challenge36.rs
|
use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use srp::client::Client;
use srp::server::ClientHandler;
use srp::server::Server;
use crate::errors::*;
#[allow(clippy::type_complexity)]
pub fn start_server<T: ClientHandler>(
mut server: T,
port: u16,
) -> Result<(Sender<u8>, thread::JoinHandle<Result<()>>)> {
let listener = TcpListener::bind(("localhost", port))?;
let (tx, rx) = channel();
let join_handle = thread::spawn(move || loop {
match listener.accept() {
Ok((mut stream, _)) => {
// Check for shutdown signal
if rx.try_recv().is_ok() {
return Ok(());
}
server.handle_client(&mut stream)?;
}
Err(_) => return Err(ConnectionFailed.into()),
};
});
Ok((tx, join_handle))
}
pub fn
|
(port: u16, tx: &Sender<u8>) -> Result<()> {
// Ugly hack for shutting down the server
tx.send(1)?;
let stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
stream.shutdown(Shutdown::Both)?;
Ok(())
}
pub fn connect_and_execute(port: u16, action: impl Fn(&mut TcpStream) -> Result<()>) -> Result<()> {
let mut stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
action(&mut stream)?;
stream.shutdown(Shutdown::Both)?;
Ok(())
}
pub fn run() -> Result<()> {
let port: u16 = 8080;
let (tx, join_handle) = start_server(Server::default(), port)?;
let user_name = b"foo";
let password = b"baz";
let client = Client::new(user_name.to_vec(), password.to_vec());
connect_and_execute(port, |stream| client.register(stream))?;
connect_and_execute(port, |stream| client.login(stream))?;
shutdown_server(port, &tx)?;
match join_handle.join() {
Ok(result) => result,
_ => Err("tcp listener thread panicked".into()),
}
}
|
shutdown_server
|
identifier_name
|
challenge36.rs
|
use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use srp::client::Client;
use srp::server::ClientHandler;
use srp::server::Server;
use crate::errors::*;
#[allow(clippy::type_complexity)]
pub fn start_server<T: ClientHandler>(
mut server: T,
port: u16,
) -> Result<(Sender<u8>, thread::JoinHandle<Result<()>>)> {
let listener = TcpListener::bind(("localhost", port))?;
let (tx, rx) = channel();
let join_handle = thread::spawn(move || loop {
match listener.accept() {
Ok((mut stream, _)) => {
// Check for shutdown signal
if rx.try_recv().is_ok() {
return Ok(());
}
server.handle_client(&mut stream)?;
}
Err(_) => return Err(ConnectionFailed.into()),
};
});
Ok((tx, join_handle))
}
pub fn shutdown_server(port: u16, tx: &Sender<u8>) -> Result<()>
|
pub fn connect_and_execute(port: u16, action: impl Fn(&mut TcpStream) -> Result<()>) -> Result<()> {
let mut stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
action(&mut stream)?;
stream.shutdown(Shutdown::Both)?;
Ok(())
}
pub fn run() -> Result<()> {
let port: u16 = 8080;
let (tx, join_handle) = start_server(Server::default(), port)?;
let user_name = b"foo";
let password = b"baz";
let client = Client::new(user_name.to_vec(), password.to_vec());
connect_and_execute(port, |stream| client.register(stream))?;
connect_and_execute(port, |stream| client.login(stream))?;
shutdown_server(port, &tx)?;
match join_handle.join() {
Ok(result) => result,
_ => Err("tcp listener thread panicked".into()),
}
}
|
{
// Ugly hack for shutting down the server
tx.send(1)?;
let stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
stream.shutdown(Shutdown::Both)?;
Ok(())
}
|
identifier_body
|
challenge36.rs
|
use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::mpsc::{channel, Sender};
use std::thread;
use srp::client::Client;
use srp::server::ClientHandler;
use srp::server::Server;
use crate::errors::*;
#[allow(clippy::type_complexity)]
pub fn start_server<T: ClientHandler>(
mut server: T,
port: u16,
) -> Result<(Sender<u8>, thread::JoinHandle<Result<()>>)> {
let listener = TcpListener::bind(("localhost", port))?;
let (tx, rx) = channel();
let join_handle = thread::spawn(move || loop {
match listener.accept() {
Ok((mut stream, _)) => {
// Check for shutdown signal
if rx.try_recv().is_ok() {
return Ok(());
}
server.handle_client(&mut stream)?;
}
Err(_) => return Err(ConnectionFailed.into()),
};
});
Ok((tx, join_handle))
}
pub fn shutdown_server(port: u16, tx: &Sender<u8>) -> Result<()> {
// Ugly hack for shutting down the server
tx.send(1)?;
let stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
stream.shutdown(Shutdown::Both)?;
Ok(())
}
pub fn connect_and_execute(port: u16, action: impl Fn(&mut TcpStream) -> Result<()>) -> Result<()> {
let mut stream = TcpStream::connect(("localhost", port)).map_err(|err| AnnotatedError {
message: "client failed to connect".to_string(),
error: err.into(),
})?;
action(&mut stream)?;
stream.shutdown(Shutdown::Both)?;
Ok(())
|
pub fn run() -> Result<()> {
let port: u16 = 8080;
let (tx, join_handle) = start_server(Server::default(), port)?;
let user_name = b"foo";
let password = b"baz";
let client = Client::new(user_name.to_vec(), password.to_vec());
connect_and_execute(port, |stream| client.register(stream))?;
connect_and_execute(port, |stream| client.login(stream))?;
shutdown_server(port, &tx)?;
match join_handle.join() {
Ok(result) => result,
_ => Err("tcp listener thread panicked".into()),
}
}
|
}
|
random_line_split
|
fdt.rs
|
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use arch::android::create_android_fdt;
use arch::fdt::{Error, FdtWriter};
use data_model::DataInit;
use std::fs::File;
use std::mem;
use vm_memory::{GuestAddress, GuestMemory};
use crate::bootparam::setup_data;
use crate::{SETUP_DTB, X86_64_FDT_MAX_SIZE};
// Like `setup_data` without the incomplete array field at the end, which allows us to safely
// implement Copy, Clone, and DataInit.
#[repr(C)]
#[derive(Copy, Clone, Default)]
struct setup_data_hdr {
pub next: u64,
pub type_: u32,
pub len: u32,
}
unsafe impl DataInit for setup_data_hdr {}
/// Creates a flattened device tree containing all of the parameters for the
/// kernel and loads it into the guest memory at the specified offset.
///
/// # Arguments
///
/// * `fdt_max_size` - The amount of space reserved for the device tree
/// * `guest_mem` - The guest memory object
/// * `fdt_load_offset` - The offset into physical memory for the device tree
/// * `android_fstab` - the File object for the android fstab
pub fn
|
(
fdt_max_size: usize,
guest_mem: &GuestMemory,
fdt_load_offset: u64,
android_fstab: File,
) -> Result<usize, Error> {
// Reserve space for the setup_data
let fdt_data_size = fdt_max_size - mem::size_of::<setup_data>();
let mut fdt = FdtWriter::new(&[]);
// The whole thing is put into one giant node with some top level properties
let root_node = fdt.begin_node("")?;
create_android_fdt(&mut fdt, android_fstab)?;
fdt.end_node(root_node)?;
let fdt_final = fdt.finish(fdt_data_size)?;
assert_eq!(
mem::size_of::<setup_data>(),
mem::size_of::<setup_data_hdr>()
);
let hdr = setup_data_hdr {
next: 0,
type_: SETUP_DTB,
len: fdt_data_size as u32,
};
assert!(fdt_data_size as u64 <= X86_64_FDT_MAX_SIZE);
let fdt_address = GuestAddress(fdt_load_offset);
guest_mem
.checked_offset(fdt_address, fdt_data_size as u64)
.ok_or(Error::FdtGuestMemoryWriteError)?;
guest_mem
.write_obj_at_addr(hdr, fdt_address)
.map_err(|_| Error::FdtGuestMemoryWriteError)?;
let fdt_data_address = GuestAddress(fdt_load_offset + mem::size_of::<setup_data>() as u64);
let written = guest_mem
.write_at_addr(fdt_final.as_slice(), fdt_data_address)
.map_err(|_| Error::FdtGuestMemoryWriteError)?;
if written < fdt_data_size {
return Err(Error::FdtGuestMemoryWriteError);
}
Ok(fdt_data_size)
}
|
create_fdt
|
identifier_name
|
fdt.rs
|
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use arch::android::create_android_fdt;
use arch::fdt::{Error, FdtWriter};
use data_model::DataInit;
use std::fs::File;
use std::mem;
use vm_memory::{GuestAddress, GuestMemory};
use crate::bootparam::setup_data;
use crate::{SETUP_DTB, X86_64_FDT_MAX_SIZE};
// Like `setup_data` without the incomplete array field at the end, which allows us to safely
// implement Copy, Clone, and DataInit.
#[repr(C)]
#[derive(Copy, Clone, Default)]
struct setup_data_hdr {
pub next: u64,
pub type_: u32,
pub len: u32,
}
unsafe impl DataInit for setup_data_hdr {}
/// Creates a flattened device tree containing all of the parameters for the
/// kernel and loads it into the guest memory at the specified offset.
///
/// # Arguments
///
/// * `fdt_max_size` - The amount of space reserved for the device tree
/// * `guest_mem` - The guest memory object
/// * `fdt_load_offset` - The offset into physical memory for the device tree
/// * `android_fstab` - the File object for the android fstab
pub fn create_fdt(
fdt_max_size: usize,
guest_mem: &GuestMemory,
|
// Reserve space for the setup_data
let fdt_data_size = fdt_max_size - mem::size_of::<setup_data>();
let mut fdt = FdtWriter::new(&[]);
// The whole thing is put into one giant node with some top level properties
let root_node = fdt.begin_node("")?;
create_android_fdt(&mut fdt, android_fstab)?;
fdt.end_node(root_node)?;
let fdt_final = fdt.finish(fdt_data_size)?;
assert_eq!(
mem::size_of::<setup_data>(),
mem::size_of::<setup_data_hdr>()
);
let hdr = setup_data_hdr {
next: 0,
type_: SETUP_DTB,
len: fdt_data_size as u32,
};
assert!(fdt_data_size as u64 <= X86_64_FDT_MAX_SIZE);
let fdt_address = GuestAddress(fdt_load_offset);
guest_mem
.checked_offset(fdt_address, fdt_data_size as u64)
.ok_or(Error::FdtGuestMemoryWriteError)?;
guest_mem
.write_obj_at_addr(hdr, fdt_address)
.map_err(|_| Error::FdtGuestMemoryWriteError)?;
let fdt_data_address = GuestAddress(fdt_load_offset + mem::size_of::<setup_data>() as u64);
let written = guest_mem
.write_at_addr(fdt_final.as_slice(), fdt_data_address)
.map_err(|_| Error::FdtGuestMemoryWriteError)?;
if written < fdt_data_size {
return Err(Error::FdtGuestMemoryWriteError);
}
Ok(fdt_data_size)
}
|
fdt_load_offset: u64,
android_fstab: File,
) -> Result<usize, Error> {
|
random_line_split
|
fdt.rs
|
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use arch::android::create_android_fdt;
use arch::fdt::{Error, FdtWriter};
use data_model::DataInit;
use std::fs::File;
use std::mem;
use vm_memory::{GuestAddress, GuestMemory};
use crate::bootparam::setup_data;
use crate::{SETUP_DTB, X86_64_FDT_MAX_SIZE};
// Like `setup_data` without the incomplete array field at the end, which allows us to safely
// implement Copy, Clone, and DataInit.
#[repr(C)]
#[derive(Copy, Clone, Default)]
struct setup_data_hdr {
pub next: u64,
pub type_: u32,
pub len: u32,
}
unsafe impl DataInit for setup_data_hdr {}
/// Creates a flattened device tree containing all of the parameters for the
/// kernel and loads it into the guest memory at the specified offset.
///
/// # Arguments
///
/// * `fdt_max_size` - The amount of space reserved for the device tree
/// * `guest_mem` - The guest memory object
/// * `fdt_load_offset` - The offset into physical memory for the device tree
/// * `android_fstab` - the File object for the android fstab
pub fn create_fdt(
fdt_max_size: usize,
guest_mem: &GuestMemory,
fdt_load_offset: u64,
android_fstab: File,
) -> Result<usize, Error> {
// Reserve space for the setup_data
let fdt_data_size = fdt_max_size - mem::size_of::<setup_data>();
let mut fdt = FdtWriter::new(&[]);
// The whole thing is put into one giant node with some top level properties
let root_node = fdt.begin_node("")?;
create_android_fdt(&mut fdt, android_fstab)?;
fdt.end_node(root_node)?;
let fdt_final = fdt.finish(fdt_data_size)?;
assert_eq!(
mem::size_of::<setup_data>(),
mem::size_of::<setup_data_hdr>()
);
let hdr = setup_data_hdr {
next: 0,
type_: SETUP_DTB,
len: fdt_data_size as u32,
};
assert!(fdt_data_size as u64 <= X86_64_FDT_MAX_SIZE);
let fdt_address = GuestAddress(fdt_load_offset);
guest_mem
.checked_offset(fdt_address, fdt_data_size as u64)
.ok_or(Error::FdtGuestMemoryWriteError)?;
guest_mem
.write_obj_at_addr(hdr, fdt_address)
.map_err(|_| Error::FdtGuestMemoryWriteError)?;
let fdt_data_address = GuestAddress(fdt_load_offset + mem::size_of::<setup_data>() as u64);
let written = guest_mem
.write_at_addr(fdt_final.as_slice(), fdt_data_address)
.map_err(|_| Error::FdtGuestMemoryWriteError)?;
if written < fdt_data_size
|
Ok(fdt_data_size)
}
|
{
return Err(Error::FdtGuestMemoryWriteError);
}
|
conditional_block
|
fdt.rs
|
// Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use arch::android::create_android_fdt;
use arch::fdt::{Error, FdtWriter};
use data_model::DataInit;
use std::fs::File;
use std::mem;
use vm_memory::{GuestAddress, GuestMemory};
use crate::bootparam::setup_data;
use crate::{SETUP_DTB, X86_64_FDT_MAX_SIZE};
// Like `setup_data` without the incomplete array field at the end, which allows us to safely
// implement Copy, Clone, and DataInit.
#[repr(C)]
#[derive(Copy, Clone, Default)]
struct setup_data_hdr {
pub next: u64,
pub type_: u32,
pub len: u32,
}
unsafe impl DataInit for setup_data_hdr {}
/// Creates a flattened device tree containing all of the parameters for the
/// kernel and loads it into the guest memory at the specified offset.
///
/// # Arguments
///
/// * `fdt_max_size` - The amount of space reserved for the device tree
/// * `guest_mem` - The guest memory object
/// * `fdt_load_offset` - The offset into physical memory for the device tree
/// * `android_fstab` - the File object for the android fstab
pub fn create_fdt(
fdt_max_size: usize,
guest_mem: &GuestMemory,
fdt_load_offset: u64,
android_fstab: File,
) -> Result<usize, Error>
|
len: fdt_data_size as u32,
};
assert!(fdt_data_size as u64 <= X86_64_FDT_MAX_SIZE);
let fdt_address = GuestAddress(fdt_load_offset);
guest_mem
.checked_offset(fdt_address, fdt_data_size as u64)
.ok_or(Error::FdtGuestMemoryWriteError)?;
guest_mem
.write_obj_at_addr(hdr, fdt_address)
.map_err(|_| Error::FdtGuestMemoryWriteError)?;
let fdt_data_address = GuestAddress(fdt_load_offset + mem::size_of::<setup_data>() as u64);
let written = guest_mem
.write_at_addr(fdt_final.as_slice(), fdt_data_address)
.map_err(|_| Error::FdtGuestMemoryWriteError)?;
if written < fdt_data_size {
return Err(Error::FdtGuestMemoryWriteError);
}
Ok(fdt_data_size)
}
|
{
// Reserve space for the setup_data
let fdt_data_size = fdt_max_size - mem::size_of::<setup_data>();
let mut fdt = FdtWriter::new(&[]);
// The whole thing is put into one giant node with some top level properties
let root_node = fdt.begin_node("")?;
create_android_fdt(&mut fdt, android_fstab)?;
fdt.end_node(root_node)?;
let fdt_final = fdt.finish(fdt_data_size)?;
assert_eq!(
mem::size_of::<setup_data>(),
mem::size_of::<setup_data_hdr>()
);
let hdr = setup_data_hdr {
next: 0,
type_: SETUP_DTB,
|
identifier_body
|
lib.rs
|
//! Watchexec: the library
//!
//! This is the library version of the CLI tool [watchexec]. The tool is
//! implemented with this library, but the purpose of the watchexec project is
//! to deliver the CLI tool, instead of focusing on the library interface first
//! and foremost. **For this reason, semver guarantees do _not_ apply to this
//! library.** Please use exact version matching, as this API may break even
//! between patch point releases. This policy may change in the future.
//!
//! [watchexec]: https://github.com/watchexec/watchexec
#![forbid(deprecated)]
#![warn(
clippy::all,
clippy::missing_const_for_fn,
clippy::option_unwrap_used,
clippy::result_unwrap_used,
intra_doc_link_resolution_failure
)]
#[macro_use]
extern crate clap;
#[macro_use]
extern crate derive_builder;
#[macro_use]
extern crate log;
#[macro_use]
extern crate lazy_static;
pub mod cli;
pub mod error;
mod gitignore;
mod ignore;
mod notification_filter;
pub mod pathop;
mod process;
pub mod run;
mod signal;
|
pub use cli::{Args, ArgsBuilder};
pub use run::{run, watch, Handler};
|
mod watcher;
|
random_line_split
|
notify.rs
|
use notify_rust::{Notification, NotificationHint, NotificationUrgency};
use rusthub::notifications;
use std::process::Command;
use std::thread;
use std::path::Path;
const APP_NAME: &'static str = "gh-notify";
pub fn
|
(notification: ¬ifications::Notification) {
let subject = format!("{} - {}", notification.subject.subject_type, notification.repository.name);
let body = notification.subject.title.clone();
let url = notification.subject.url.clone();
let url = url.replace("api.", "").replace("repos/", "").replace("/pulls/", "/pull/");
thread::spawn(move || {
notify_action(
&subject,
&body,
"Open in Browser",
120,
|action| {
match action {
"default" | "clicked" => {
open_link(&url);
},
"__closed" => (),
_ => ()
}
}
).unwrap_or_else(|err| error!("While showing notification: {}", err));
});
}
pub fn open_link(url: &str) {
debug!("Opening browser link: {}", url);
let _ = Command::new("sh")
.arg("-c")
.arg(format!("xdg-open '{}'", url))
.output()
.expect("Failed to open web browser instance.");
}
pub fn notify_action<F>(summary: &str, body: &str, button_text: &str, timeout: i32, action: F) -> Result<(), String> where F: FnOnce(&str) {
let icon = match Path::new("./icon.png").canonicalize() {
Ok(path) => path.to_string_lossy().into_owned(),
Err(_) => "clock".to_string()
};
let handle = try!(Notification::new()
.appname(APP_NAME)
.summary(&summary)
.icon(&icon)
.body(&body)
.action("default", &button_text) // IDENTIFIER, LABEL
.action("clicked", &button_text) // IDENTIFIER, LABEL
.hint(NotificationHint::Urgency(NotificationUrgency::Normal))
.timeout(timeout)
.show().map_err(|err| err.to_string()));
handle.wait_for_action(action);
Ok(())
}
|
show_notification
|
identifier_name
|
notify.rs
|
use notify_rust::{Notification, NotificationHint, NotificationUrgency};
use rusthub::notifications;
use std::process::Command;
use std::thread;
use std::path::Path;
const APP_NAME: &'static str = "gh-notify";
pub fn show_notification(notification: ¬ifications::Notification) {
let subject = format!("{} - {}", notification.subject.subject_type, notification.repository.name);
let body = notification.subject.title.clone();
let url = notification.subject.url.clone();
let url = url.replace("api.", "").replace("repos/", "").replace("/pulls/", "/pull/");
thread::spawn(move || {
notify_action(
&subject,
&body,
"Open in Browser",
120,
|action| {
match action {
"default" | "clicked" => {
open_link(&url);
},
"__closed" => (),
_ => ()
}
|
}
).unwrap_or_else(|err| error!("While showing notification: {}", err));
});
}
pub fn open_link(url: &str) {
debug!("Opening browser link: {}", url);
let _ = Command::new("sh")
.arg("-c")
.arg(format!("xdg-open '{}'", url))
.output()
.expect("Failed to open web browser instance.");
}
pub fn notify_action<F>(summary: &str, body: &str, button_text: &str, timeout: i32, action: F) -> Result<(), String> where F: FnOnce(&str) {
let icon = match Path::new("./icon.png").canonicalize() {
Ok(path) => path.to_string_lossy().into_owned(),
Err(_) => "clock".to_string()
};
let handle = try!(Notification::new()
.appname(APP_NAME)
.summary(&summary)
.icon(&icon)
.body(&body)
.action("default", &button_text) // IDENTIFIER, LABEL
.action("clicked", &button_text) // IDENTIFIER, LABEL
.hint(NotificationHint::Urgency(NotificationUrgency::Normal))
.timeout(timeout)
.show().map_err(|err| err.to_string()));
handle.wait_for_action(action);
Ok(())
}
|
random_line_split
|
|
notify.rs
|
use notify_rust::{Notification, NotificationHint, NotificationUrgency};
use rusthub::notifications;
use std::process::Command;
use std::thread;
use std::path::Path;
const APP_NAME: &'static str = "gh-notify";
pub fn show_notification(notification: ¬ifications::Notification) {
let subject = format!("{} - {}", notification.subject.subject_type, notification.repository.name);
let body = notification.subject.title.clone();
let url = notification.subject.url.clone();
let url = url.replace("api.", "").replace("repos/", "").replace("/pulls/", "/pull/");
thread::spawn(move || {
notify_action(
&subject,
&body,
"Open in Browser",
120,
|action| {
match action {
"default" | "clicked" => {
open_link(&url);
},
"__closed" => (),
_ => ()
}
}
).unwrap_or_else(|err| error!("While showing notification: {}", err));
});
}
pub fn open_link(url: &str)
|
pub fn notify_action<F>(summary: &str, body: &str, button_text: &str, timeout: i32, action: F) -> Result<(), String> where F: FnOnce(&str) {
let icon = match Path::new("./icon.png").canonicalize() {
Ok(path) => path.to_string_lossy().into_owned(),
Err(_) => "clock".to_string()
};
let handle = try!(Notification::new()
.appname(APP_NAME)
.summary(&summary)
.icon(&icon)
.body(&body)
.action("default", &button_text) // IDENTIFIER, LABEL
.action("clicked", &button_text) // IDENTIFIER, LABEL
.hint(NotificationHint::Urgency(NotificationUrgency::Normal))
.timeout(timeout)
.show().map_err(|err| err.to_string()));
handle.wait_for_action(action);
Ok(())
}
|
{
debug!("Opening browser link: {}", url);
let _ = Command::new("sh")
.arg("-c")
.arg(format!("xdg-open '{}'", url))
.output()
.expect("Failed to open web browser instance.");
}
|
identifier_body
|
lint-group-plugin.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:lint_group_plugin_test.rs
// ignore-stage1
// ignore-pretty
#![feature(plugin)]
#![plugin(lint_group_plugin_test)]
fn lintme() { } //~ WARNING item is named 'lintme'
fn pleaselintme() { } //~ WARNING item is named 'pleaselintme'
#[allow(lint_me)]
pub fn main() {
fn lintme() { }
fn
|
() { }
}
|
pleaselintme
|
identifier_name
|
lint-group-plugin.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
|
// 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.
// aux-build:lint_group_plugin_test.rs
// ignore-stage1
// ignore-pretty
#![feature(plugin)]
#![plugin(lint_group_plugin_test)]
fn lintme() { } //~ WARNING item is named 'lintme'
fn pleaselintme() { } //~ WARNING item is named 'pleaselintme'
#[allow(lint_me)]
pub fn main() {
fn lintme() { }
fn pleaselintme() { }
}
|
// file at the top-level directory of this distribution and at
|
random_line_split
|
lint-group-plugin.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:lint_group_plugin_test.rs
// ignore-stage1
// ignore-pretty
#![feature(plugin)]
#![plugin(lint_group_plugin_test)]
fn lintme() { } //~ WARNING item is named 'lintme'
fn pleaselintme()
|
//~ WARNING item is named 'pleaselintme'
#[allow(lint_me)]
pub fn main() {
fn lintme() { }
fn pleaselintme() { }
}
|
{ }
|
identifier_body
|
build.rs
|
extern crate gcc;
use std::env;
fn
|
() {
let mut cfg = gcc::Config::new();
if env::var("TARGET").unwrap().contains("windows") {
cfg.define("_WIN32", None);
cfg.define("BZ_EXPORT", None);
}
cfg.include("bzip2-1.0.6")
.define("BZ_NO_STDIO", None)
.file("bzip2-1.0.6/blocksort.c")
.file("bzip2-1.0.6/huffman.c")
.file("bzip2-1.0.6/crctable.c")
.file("bzip2-1.0.6/randtable.c")
.file("bzip2-1.0.6/compress.c")
.file("bzip2-1.0.6/decompress.c")
.file("bzip2-1.0.6/bzlib.c")
.compile("libbz2.a");
}
|
main
|
identifier_name
|
build.rs
|
extern crate gcc;
use std::env;
fn main() {
let mut cfg = gcc::Config::new();
if env::var("TARGET").unwrap().contains("windows") {
cfg.define("_WIN32", None);
cfg.define("BZ_EXPORT", None);
}
cfg.include("bzip2-1.0.6")
.define("BZ_NO_STDIO", None)
.file("bzip2-1.0.6/blocksort.c")
.file("bzip2-1.0.6/huffman.c")
.file("bzip2-1.0.6/crctable.c")
.file("bzip2-1.0.6/randtable.c")
.file("bzip2-1.0.6/compress.c")
|
.file("bzip2-1.0.6/decompress.c")
.file("bzip2-1.0.6/bzlib.c")
.compile("libbz2.a");
}
|
random_line_split
|
|
build.rs
|
extern crate gcc;
use std::env;
fn main() {
let mut cfg = gcc::Config::new();
if env::var("TARGET").unwrap().contains("windows")
|
cfg.include("bzip2-1.0.6")
.define("BZ_NO_STDIO", None)
.file("bzip2-1.0.6/blocksort.c")
.file("bzip2-1.0.6/huffman.c")
.file("bzip2-1.0.6/crctable.c")
.file("bzip2-1.0.6/randtable.c")
.file("bzip2-1.0.6/compress.c")
.file("bzip2-1.0.6/decompress.c")
.file("bzip2-1.0.6/bzlib.c")
.compile("libbz2.a");
}
|
{
cfg.define("_WIN32", None);
cfg.define("BZ_EXPORT", None);
}
|
conditional_block
|
build.rs
|
extern crate gcc;
use std::env;
fn main()
|
{
let mut cfg = gcc::Config::new();
if env::var("TARGET").unwrap().contains("windows") {
cfg.define("_WIN32", None);
cfg.define("BZ_EXPORT", None);
}
cfg.include("bzip2-1.0.6")
.define("BZ_NO_STDIO", None)
.file("bzip2-1.0.6/blocksort.c")
.file("bzip2-1.0.6/huffman.c")
.file("bzip2-1.0.6/crctable.c")
.file("bzip2-1.0.6/randtable.c")
.file("bzip2-1.0.6/compress.c")
.file("bzip2-1.0.6/decompress.c")
.file("bzip2-1.0.6/bzlib.c")
.compile("libbz2.a");
}
|
identifier_body
|
|
data_store.rs
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
loaded_data::runtime_types::Type,
values::{GlobalValue, Value},
};
use move_core_types::{account_address::AccountAddress, language_storage::ModuleId};
use vm::errors::{PartialVMResult, VMResult};
/// Provide an implementation for bytecodes related to data with a given data store.
///
|
pub trait DataStore {
// ---
// StateStore operations
// ---
/// Try to load a resource from remote storage and create a corresponding GlobalValue
/// that is owned by the data store.
fn load_resource(
&mut self,
addr: AccountAddress,
ty: &Type,
) -> PartialVMResult<&mut GlobalValue>;
/// Get the serialized format of a `CompiledModule` given a `ModuleId`.
fn load_module(&self, module_id: &ModuleId) -> VMResult<Vec<u8>>;
/// Publish a module.
fn publish_module(&mut self, module_id: &ModuleId, blob: Vec<u8>) -> VMResult<()>;
/// Check if this module exists.
fn exists_module(&self, module_id: &ModuleId) -> VMResult<bool>;
// ---
// EventStore operations
// ---
/// Emit an event to the EventStore
fn emit_event(
&mut self,
guid: Vec<u8>,
seq_num: u64,
ty: Type,
val: Value,
) -> PartialVMResult<()>;
}
|
/// The `DataStore` is a generic concept that includes both data and events.
/// A default implementation of the `DataStore` is `TransactionDataCache` which provides
/// an in memory cache for a given transaction and the atomic transactional changes
/// proper of a script execution (transaction).
|
random_line_split
|
lib.rs
|
// Copyright 2016 Mozilla Foundation
//
// 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.
#![deny(rust_2018_idioms)]
#![recursion_limit = "256"]
#[macro_use]
extern crate clap;
#[macro_use]
extern crate counted_array;
#[macro_use]
extern crate futures;
#[cfg(feature = "jsonwebtoken")]
use jsonwebtoken as jwt;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[cfg(feature = "rouille")]
#[macro_use(router)]
extern crate rouille;
#[macro_use]
extern crate serde_derive;
// To get macros in scope, this has to be first.
#[cfg(test)]
#[macro_use]
mod test;
#[macro_use]
pub mod errors;
#[cfg(feature = "azure")]
mod azure;
mod cache;
mod client;
mod cmdline;
mod commands;
mod compiler;
pub mod config;
pub mod dist;
mod jobserver;
mod mock_command;
mod protocol;
pub mod server;
#[cfg(feature = "simple-s3")]
mod simples3;
#[doc(hidden)]
pub mod util;
use std::env;
const LOGGING_ENV: &str = "SCCACHE_LOG";
pub fn main()
|
1
}
});
}
fn init_logging() {
if env::var(LOGGING_ENV).is_ok() {
match env_logger::Builder::from_env(LOGGING_ENV).try_init() {
Ok(_) => (),
Err(e) => panic!(format!("Failed to initalize logging: {:?}", e)),
}
}
}
|
{
init_logging();
std::process::exit(match cmdline::parse() {
Ok(cmd) => match commands::run_command(cmd) {
Ok(s) => s,
Err(e) => {
eprintln!("sccache: error: {}", e);
for e in e.chain().skip(1) {
eprintln!("sccache: caused by: {}", e);
}
2
}
},
Err(e) => {
println!("sccache: {}", e);
for e in e.chain().skip(1) {
println!("sccache: caused by: {}", e);
}
cmdline::get_app().print_help().unwrap();
println!();
|
identifier_body
|
lib.rs
|
// Copyright 2016 Mozilla Foundation
//
// 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.
#![deny(rust_2018_idioms)]
#![recursion_limit = "256"]
#[macro_use]
extern crate clap;
#[macro_use]
extern crate counted_array;
#[macro_use]
extern crate futures;
#[cfg(feature = "jsonwebtoken")]
use jsonwebtoken as jwt;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[cfg(feature = "rouille")]
#[macro_use(router)]
extern crate rouille;
#[macro_use]
extern crate serde_derive;
// To get macros in scope, this has to be first.
#[cfg(test)]
#[macro_use]
mod test;
#[macro_use]
pub mod errors;
#[cfg(feature = "azure")]
mod azure;
mod cache;
mod client;
mod cmdline;
mod commands;
mod compiler;
pub mod config;
pub mod dist;
mod jobserver;
mod mock_command;
mod protocol;
pub mod server;
#[cfg(feature = "simple-s3")]
mod simples3;
#[doc(hidden)]
pub mod util;
use std::env;
const LOGGING_ENV: &str = "SCCACHE_LOG";
pub fn main() {
init_logging();
std::process::exit(match cmdline::parse() {
Ok(cmd) => match commands::run_command(cmd) {
Ok(s) => s,
Err(e) => {
eprintln!("sccache: error: {}", e);
for e in e.chain().skip(1) {
eprintln!("sccache: caused by: {}", e);
}
2
}
},
Err(e) =>
|
});
}
fn init_logging() {
if env::var(LOGGING_ENV).is_ok() {
match env_logger::Builder::from_env(LOGGING_ENV).try_init() {
Ok(_) => (),
Err(e) => panic!(format!("Failed to initalize logging: {:?}", e)),
}
}
}
|
{
println!("sccache: {}", e);
for e in e.chain().skip(1) {
println!("sccache: caused by: {}", e);
}
cmdline::get_app().print_help().unwrap();
println!();
1
}
|
conditional_block
|
lib.rs
|
// Copyright 2016 Mozilla Foundation
//
// 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.
#![deny(rust_2018_idioms)]
#![recursion_limit = "256"]
#[macro_use]
extern crate clap;
#[macro_use]
extern crate counted_array;
#[macro_use]
extern crate futures;
#[cfg(feature = "jsonwebtoken")]
use jsonwebtoken as jwt;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[cfg(feature = "rouille")]
#[macro_use(router)]
extern crate rouille;
#[macro_use]
extern crate serde_derive;
// To get macros in scope, this has to be first.
#[cfg(test)]
#[macro_use]
mod test;
#[macro_use]
pub mod errors;
#[cfg(feature = "azure")]
mod azure;
mod cache;
mod client;
mod cmdline;
mod commands;
mod compiler;
|
mod protocol;
pub mod server;
#[cfg(feature = "simple-s3")]
mod simples3;
#[doc(hidden)]
pub mod util;
use std::env;
const LOGGING_ENV: &str = "SCCACHE_LOG";
pub fn main() {
init_logging();
std::process::exit(match cmdline::parse() {
Ok(cmd) => match commands::run_command(cmd) {
Ok(s) => s,
Err(e) => {
eprintln!("sccache: error: {}", e);
for e in e.chain().skip(1) {
eprintln!("sccache: caused by: {}", e);
}
2
}
},
Err(e) => {
println!("sccache: {}", e);
for e in e.chain().skip(1) {
println!("sccache: caused by: {}", e);
}
cmdline::get_app().print_help().unwrap();
println!();
1
}
});
}
fn init_logging() {
if env::var(LOGGING_ENV).is_ok() {
match env_logger::Builder::from_env(LOGGING_ENV).try_init() {
Ok(_) => (),
Err(e) => panic!(format!("Failed to initalize logging: {:?}", e)),
}
}
}
|
pub mod config;
pub mod dist;
mod jobserver;
mod mock_command;
|
random_line_split
|
lib.rs
|
// Copyright 2016 Mozilla Foundation
//
// 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.
#![deny(rust_2018_idioms)]
#![recursion_limit = "256"]
#[macro_use]
extern crate clap;
#[macro_use]
extern crate counted_array;
#[macro_use]
extern crate futures;
#[cfg(feature = "jsonwebtoken")]
use jsonwebtoken as jwt;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[cfg(feature = "rouille")]
#[macro_use(router)]
extern crate rouille;
#[macro_use]
extern crate serde_derive;
// To get macros in scope, this has to be first.
#[cfg(test)]
#[macro_use]
mod test;
#[macro_use]
pub mod errors;
#[cfg(feature = "azure")]
mod azure;
mod cache;
mod client;
mod cmdline;
mod commands;
mod compiler;
pub mod config;
pub mod dist;
mod jobserver;
mod mock_command;
mod protocol;
pub mod server;
#[cfg(feature = "simple-s3")]
mod simples3;
#[doc(hidden)]
pub mod util;
use std::env;
const LOGGING_ENV: &str = "SCCACHE_LOG";
pub fn main() {
init_logging();
std::process::exit(match cmdline::parse() {
Ok(cmd) => match commands::run_command(cmd) {
Ok(s) => s,
Err(e) => {
eprintln!("sccache: error: {}", e);
for e in e.chain().skip(1) {
eprintln!("sccache: caused by: {}", e);
}
2
}
},
Err(e) => {
println!("sccache: {}", e);
for e in e.chain().skip(1) {
println!("sccache: caused by: {}", e);
}
cmdline::get_app().print_help().unwrap();
println!();
1
}
});
}
fn
|
() {
if env::var(LOGGING_ENV).is_ok() {
match env_logger::Builder::from_env(LOGGING_ENV).try_init() {
Ok(_) => (),
Err(e) => panic!(format!("Failed to initalize logging: {:?}", e)),
}
}
}
|
init_logging
|
identifier_name
|
mod.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod heartbeat;
mod lsp_notification_dispatch;
mod lsp_request_dispatch;
mod lsp_state;
mod lsp_state_resources;
use crate::{
code_action::on_code_action,
completion::on_completion,
goto_definition::{
on_get_source_location_of_type_definition, on_goto_definition,
GetSourceLocationOfTypeDefinition,
},
graphql_tools::on_graphql_execute_query,
graphql_tools::GraphQLExecuteQuery,
hover::on_hover,
js_language_server::JSLanguageServer,
lsp::{
set_initializing_status, CompletionOptions, Connection, GotoDefinition, HoverRequest,
InitializeParams, Message, ServerCapabilities, ServerResponse, TextDocumentSyncCapability,
TextDocumentSyncKind, WorkDoneProgressOptions,
},
lsp_process_error::{LSPProcessError, LSPProcessResult},
lsp_runtime_error::LSPRuntimeError,
references::on_references,
resolved_types_at_location::{on_get_resolved_types_at_location, ResolvedTypesAtLocation},
search_schema_items::{on_search_schema_items, SearchSchemaItems},
shutdown::{on_exit, on_shutdown},
status_reporting::{LSPStatusReporter, StatusReportingArtifactWriter},
text_documents::{
on_did_change_text_document, on_did_close_text_document, on_did_open_text_document,
on_did_save_text_document,
},
ExtensionConfig,
};
use common::{PerfLogEvent, PerfLogger};
use crossbeam::{SendError, Sender};
use log::debug;
use lsp_notification_dispatch::LSPNotificationDispatch;
use lsp_request_dispatch::LSPRequestDispatch;
use lsp_server::{ErrorCode, Notification, ResponseError};
use lsp_types::{
notification::{
DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, Exit,
},
request::{CodeActionRequest, Completion, References, Shutdown},
CodeActionProviderCapability,
};
use relay_compiler::{config::Config, NoopArtifactWriter};
use std::sync::Arc;
pub use crate::LSPExtraDataProvider;
pub use lsp_state::LSPState;
pub use lsp_state::{Schemas, SourcePrograms};
use heartbeat::{on_heartbeat, HeartbeatRequest};
/// Initializes an LSP connection, handling the `initialize` message and `initialized` notification
/// handshake.
pub fn initialize(connection: &Connection) -> LSPProcessResult<InitializeParams> {
let server_capabilities = ServerCapabilities {
// Enable text document syncing so we can know when files are opened/changed/saved/closed
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::Full)),
completion_provider: Some(CompletionOptions {
resolve_provider: Some(true),
trigger_characters: Some(vec!["(".into(), "\n".into(), ",".into(), "@".into()]),
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
}),
hover_provider: Some(true),
definition_provider: Some(true),
references_provider: Some(true),
code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
..Default::default()
};
let server_capabilities = serde_json::to_value(&server_capabilities)?;
let params = connection.initialize(server_capabilities)?;
let params: InitializeParams = serde_json::from_value(params)?;
Ok(params)
}
/// Run the main server loop
pub async fn run<TPerfLogger: PerfLogger +'static>(
connection: Connection,
mut config: Config,
extension_config: ExtensionConfig,
_params: InitializeParams,
perf_logger: Arc<TPerfLogger>,
extra_data_provider: Box<dyn LSPExtraDataProvider + Send + Sync>,
js_resource: Box<dyn JSLanguageServer<TPerfLogger>>,
) -> LSPProcessResult<()>
where
TPerfLogger: PerfLogger +'static,
{
debug!(
"Running language server with config root {:?}",
config.root_dir
);
set_initializing_status(&connection.sender);
config.artifact_writer = if extension_config.no_artifacts {
Box::new(NoopArtifactWriter)
} else {
Box::new(StatusReportingArtifactWriter::new(
connection.sender.clone(),
config.artifact_writer,
))
};
config.status_reporter = Box::new(LSPStatusReporter::new(
config.root_dir.clone(),
connection.sender.clone(),
));
let mut lsp_state = LSPState::create_state(
Arc::new(config),
Arc::clone(&perf_logger),
extra_data_provider,
js_resource,
&extension_config,
connection.sender.clone(),
);
loop {
debug!("waiting for incoming messages...");
match connection.receiver.recv() {
Ok(Message::Request(req)) => {
handle_request(&mut lsp_state, req, &connection.sender, &perf_logger)
.map_err(LSPProcessError::from)?;
}
Ok(Message::Notification(notification)) => {
handle_notification(&mut lsp_state, notification, &perf_logger);
}
Ok(_) => {
// Ignore responses for now
}
Err(error) => {
panic!("Relay Language Server receiver error {:?}", error);
}
}
}
}
fn handle_request<TPerfLogger: PerfLogger +'static>(
lsp_state: &mut LSPState<TPerfLogger>,
request: lsp_server::Request,
sender: &Sender<Message>,
perf_logger: &Arc<TPerfLogger>,
) -> Result<(), SendError<Message>> {
debug!("request received {:?}", request);
let get_server_response_bound = |req| dispatch_request(req, lsp_state);
let get_response = with_request_logging(perf_logger, get_server_response_bound);
sender.send(Message::Response(get_response(request)))
}
fn dispatch_request<TPerfLogger: PerfLogger +'static>(
request: lsp_server::Request,
lsp_state: &mut LSPState<TPerfLogger>,
) -> ServerResponse {
let get_response = || -> Result<_, ServerResponse> {
let request = LSPRequestDispatch::new(request, lsp_state)
.on_request_sync::<ResolvedTypesAtLocation>(on_get_resolved_types_at_location)?
.on_request_sync::<SearchSchemaItems>(on_search_schema_items)?
.on_request_sync::<GetSourceLocationOfTypeDefinition>(
on_get_source_location_of_type_definition,
)?
.on_request_sync::<HoverRequest>(on_hover)?
.on_request_sync::<GotoDefinition>(on_goto_definition)?
.on_request_sync::<References>(on_references)?
.on_request_sync::<Completion>(on_completion)?
.on_request_sync::<CodeActionRequest>(on_code_action)?
.on_request_sync::<Shutdown>(on_shutdown)?
.on_request_sync::<GraphQLExecuteQuery>(on_graphql_execute_query)?
.on_request_sync::<HeartbeatRequest>(on_heartbeat)?
.request();
// If we have gotten here, we have not handled the request
Ok(ServerResponse {
id: request.id,
result: None,
error: Some(ResponseError {
code: ErrorCode::MethodNotFound as i32,
data: None,
message: format!("No handler registered for method '{}'", request.method),
}),
})
};
get_response().unwrap_or_else(|response| response)
}
fn with_request_logging<'a, TPerfLogger: PerfLogger +'static>(
perf_logger: &'a Arc<TPerfLogger>,
get_response: impl FnOnce(lsp_server::Request) -> ServerResponse + 'a,
) -> impl FnOnce(lsp_server::Request) -> ServerResponse + 'a {
move |request| {
let lsp_request_event = perf_logger.create_event("lsp_message");
lsp_request_event.string("lsp_method", request.method.clone());
lsp_request_event.string("lsp_type", "request".to_string());
let lsp_request_processing_time = lsp_request_event.start("lsp_message_processing_time");
let response = get_response(request);
if response.result.is_some() {
lsp_request_event.string("lsp_outcome", "success".to_string());
} else if let Some(error) = &response.error {
lsp_request_event.string("lsp_outcome", "error".to_string());
if error.code!= ErrorCode::RequestCanceled as i32 {
lsp_request_event.string("lsp_error_message", error.message.to_string());
}
if let Some(data) = &error.data {
lsp_request_event.string("lsp_error_data", data.to_string());
}
}
// N.B. we don't handle the case where the ServerResponse has neither a result nor
// an error, which is an invalid state.
lsp_request_event.stop(lsp_request_processing_time);
perf_logger.complete_event(lsp_request_event);
response
}
}
fn handle_notification<TPerfLogger: PerfLogger +'static>(
lsp_state: &mut LSPState<TPerfLogger>,
notification: Notification,
perf_logger: &Arc<TPerfLogger>,
) {
debug!("notification received {:?}", notification);
let lsp_notification_event = perf_logger.create_event("lsp_message");
lsp_notification_event.string("lsp_method", notification.method.clone());
lsp_notification_event.string("lsp_type", "notification".to_string());
let lsp_notification_processing_time =
lsp_notification_event.start("lsp_message_processing_time");
let notification_result = dispatch_notification(notification, lsp_state);
match notification_result {
Ok(()) => {
// The notification is not handled
lsp_notification_event.string("lsp_outcome", "error".to_string());
}
Err(err) => {
if let Some(err) = err {
lsp_notification_event.string("lsp_outcome", "error".to_string());
if let LSPRuntimeError::UnexpectedError(message) = err {
lsp_notification_event.string("lsp_error_message", message);
}
} else {
lsp_notification_event.string("lsp_outcome", "success".to_string());
}
}
}
lsp_notification_event.stop(lsp_notification_processing_time);
perf_logger.complete_event(lsp_notification_event);
}
fn dispatch_notification<TPerfLogger: PerfLogger +'static>(
notification: lsp_server::Notification,
lsp_state: &mut LSPState<TPerfLogger>,
) -> Result<(), Option<LSPRuntimeError>>
|
{
let notification = LSPNotificationDispatch::new(notification, lsp_state)
.on_notification_sync::<DidOpenTextDocument>(on_did_open_text_document)?
.on_notification_sync::<DidCloseTextDocument>(on_did_close_text_document)?
.on_notification_sync::<DidChangeTextDocument>(on_did_change_text_document)?
.on_notification_sync::<DidSaveTextDocument>(on_did_save_text_document)?
.on_notification_sync::<Exit>(on_exit)?
.notification();
// If we have gotten here, we have not handled the notification
debug!(
"Error: no handler registered for notification '{}'",
notification.method
);
Ok(())
}
|
identifier_body
|
|
mod.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod heartbeat;
mod lsp_notification_dispatch;
mod lsp_request_dispatch;
mod lsp_state;
mod lsp_state_resources;
use crate::{
code_action::on_code_action,
completion::on_completion,
goto_definition::{
on_get_source_location_of_type_definition, on_goto_definition,
GetSourceLocationOfTypeDefinition,
},
graphql_tools::on_graphql_execute_query,
graphql_tools::GraphQLExecuteQuery,
hover::on_hover,
js_language_server::JSLanguageServer,
lsp::{
set_initializing_status, CompletionOptions, Connection, GotoDefinition, HoverRequest,
InitializeParams, Message, ServerCapabilities, ServerResponse, TextDocumentSyncCapability,
TextDocumentSyncKind, WorkDoneProgressOptions,
},
lsp_process_error::{LSPProcessError, LSPProcessResult},
lsp_runtime_error::LSPRuntimeError,
references::on_references,
resolved_types_at_location::{on_get_resolved_types_at_location, ResolvedTypesAtLocation},
search_schema_items::{on_search_schema_items, SearchSchemaItems},
shutdown::{on_exit, on_shutdown},
status_reporting::{LSPStatusReporter, StatusReportingArtifactWriter},
text_documents::{
on_did_change_text_document, on_did_close_text_document, on_did_open_text_document,
on_did_save_text_document,
},
ExtensionConfig,
};
use common::{PerfLogEvent, PerfLogger};
use crossbeam::{SendError, Sender};
use log::debug;
use lsp_notification_dispatch::LSPNotificationDispatch;
use lsp_request_dispatch::LSPRequestDispatch;
use lsp_server::{ErrorCode, Notification, ResponseError};
use lsp_types::{
notification::{
DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, Exit,
},
request::{CodeActionRequest, Completion, References, Shutdown},
CodeActionProviderCapability,
};
use relay_compiler::{config::Config, NoopArtifactWriter};
use std::sync::Arc;
pub use crate::LSPExtraDataProvider;
pub use lsp_state::LSPState;
pub use lsp_state::{Schemas, SourcePrograms};
use heartbeat::{on_heartbeat, HeartbeatRequest};
/// Initializes an LSP connection, handling the `initialize` message and `initialized` notification
/// handshake.
pub fn initialize(connection: &Connection) -> LSPProcessResult<InitializeParams> {
let server_capabilities = ServerCapabilities {
// Enable text document syncing so we can know when files are opened/changed/saved/closed
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::Full)),
completion_provider: Some(CompletionOptions {
resolve_provider: Some(true),
trigger_characters: Some(vec!["(".into(), "\n".into(), ",".into(), "@".into()]),
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
}),
hover_provider: Some(true),
definition_provider: Some(true),
references_provider: Some(true),
code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
..Default::default()
};
let server_capabilities = serde_json::to_value(&server_capabilities)?;
let params = connection.initialize(server_capabilities)?;
let params: InitializeParams = serde_json::from_value(params)?;
Ok(params)
}
/// Run the main server loop
pub async fn run<TPerfLogger: PerfLogger +'static>(
connection: Connection,
mut config: Config,
extension_config: ExtensionConfig,
_params: InitializeParams,
perf_logger: Arc<TPerfLogger>,
extra_data_provider: Box<dyn LSPExtraDataProvider + Send + Sync>,
js_resource: Box<dyn JSLanguageServer<TPerfLogger>>,
) -> LSPProcessResult<()>
where
TPerfLogger: PerfLogger +'static,
{
debug!(
"Running language server with config root {:?}",
config.root_dir
);
set_initializing_status(&connection.sender);
config.artifact_writer = if extension_config.no_artifacts {
Box::new(NoopArtifactWriter)
} else {
Box::new(StatusReportingArtifactWriter::new(
connection.sender.clone(),
config.artifact_writer,
))
};
config.status_reporter = Box::new(LSPStatusReporter::new(
config.root_dir.clone(),
connection.sender.clone(),
));
let mut lsp_state = LSPState::create_state(
Arc::new(config),
Arc::clone(&perf_logger),
extra_data_provider,
js_resource,
&extension_config,
connection.sender.clone(),
);
loop {
debug!("waiting for incoming messages...");
match connection.receiver.recv() {
Ok(Message::Request(req)) => {
handle_request(&mut lsp_state, req, &connection.sender, &perf_logger)
.map_err(LSPProcessError::from)?;
}
Ok(Message::Notification(notification)) => {
handle_notification(&mut lsp_state, notification, &perf_logger);
}
Ok(_) => {
// Ignore responses for now
}
Err(error) => {
panic!("Relay Language Server receiver error {:?}", error);
}
}
}
}
fn handle_request<TPerfLogger: PerfLogger +'static>(
lsp_state: &mut LSPState<TPerfLogger>,
request: lsp_server::Request,
sender: &Sender<Message>,
perf_logger: &Arc<TPerfLogger>,
) -> Result<(), SendError<Message>> {
debug!("request received {:?}", request);
let get_server_response_bound = |req| dispatch_request(req, lsp_state);
let get_response = with_request_logging(perf_logger, get_server_response_bound);
sender.send(Message::Response(get_response(request)))
}
fn dispatch_request<TPerfLogger: PerfLogger +'static>(
request: lsp_server::Request,
lsp_state: &mut LSPState<TPerfLogger>,
) -> ServerResponse {
let get_response = || -> Result<_, ServerResponse> {
let request = LSPRequestDispatch::new(request, lsp_state)
.on_request_sync::<ResolvedTypesAtLocation>(on_get_resolved_types_at_location)?
.on_request_sync::<SearchSchemaItems>(on_search_schema_items)?
.on_request_sync::<GetSourceLocationOfTypeDefinition>(
on_get_source_location_of_type_definition,
)?
.on_request_sync::<HoverRequest>(on_hover)?
.on_request_sync::<GotoDefinition>(on_goto_definition)?
.on_request_sync::<References>(on_references)?
.on_request_sync::<Completion>(on_completion)?
.on_request_sync::<CodeActionRequest>(on_code_action)?
.on_request_sync::<Shutdown>(on_shutdown)?
.on_request_sync::<GraphQLExecuteQuery>(on_graphql_execute_query)?
.on_request_sync::<HeartbeatRequest>(on_heartbeat)?
.request();
// If we have gotten here, we have not handled the request
Ok(ServerResponse {
id: request.id,
result: None,
error: Some(ResponseError {
code: ErrorCode::MethodNotFound as i32,
data: None,
message: format!("No handler registered for method '{}'", request.method),
}),
})
};
get_response().unwrap_or_else(|response| response)
}
fn with_request_logging<'a, TPerfLogger: PerfLogger +'static>(
perf_logger: &'a Arc<TPerfLogger>,
get_response: impl FnOnce(lsp_server::Request) -> ServerResponse + 'a,
) -> impl FnOnce(lsp_server::Request) -> ServerResponse + 'a {
move |request| {
let lsp_request_event = perf_logger.create_event("lsp_message");
lsp_request_event.string("lsp_method", request.method.clone());
lsp_request_event.string("lsp_type", "request".to_string());
let lsp_request_processing_time = lsp_request_event.start("lsp_message_processing_time");
let response = get_response(request);
if response.result.is_some() {
lsp_request_event.string("lsp_outcome", "success".to_string());
} else if let Some(error) = &response.error {
lsp_request_event.string("lsp_outcome", "error".to_string());
if error.code!= ErrorCode::RequestCanceled as i32 {
lsp_request_event.string("lsp_error_message", error.message.to_string());
}
if let Some(data) = &error.data {
lsp_request_event.string("lsp_error_data", data.to_string());
}
}
// N.B. we don't handle the case where the ServerResponse has neither a result nor
// an error, which is an invalid state.
lsp_request_event.stop(lsp_request_processing_time);
perf_logger.complete_event(lsp_request_event);
response
}
}
fn handle_notification<TPerfLogger: PerfLogger +'static>(
lsp_state: &mut LSPState<TPerfLogger>,
notification: Notification,
perf_logger: &Arc<TPerfLogger>,
) {
debug!("notification received {:?}", notification);
let lsp_notification_event = perf_logger.create_event("lsp_message");
lsp_notification_event.string("lsp_method", notification.method.clone());
lsp_notification_event.string("lsp_type", "notification".to_string());
let lsp_notification_processing_time =
lsp_notification_event.start("lsp_message_processing_time");
let notification_result = dispatch_notification(notification, lsp_state);
match notification_result {
Ok(()) => {
// The notification is not handled
lsp_notification_event.string("lsp_outcome", "error".to_string());
}
Err(err) => {
if let Some(err) = err {
lsp_notification_event.string("lsp_outcome", "error".to_string());
if let LSPRuntimeError::UnexpectedError(message) = err {
lsp_notification_event.string("lsp_error_message", message);
}
} else {
lsp_notification_event.string("lsp_outcome", "success".to_string());
}
}
}
lsp_notification_event.stop(lsp_notification_processing_time);
perf_logger.complete_event(lsp_notification_event);
}
fn
|
<TPerfLogger: PerfLogger +'static>(
notification: lsp_server::Notification,
lsp_state: &mut LSPState<TPerfLogger>,
) -> Result<(), Option<LSPRuntimeError>> {
let notification = LSPNotificationDispatch::new(notification, lsp_state)
.on_notification_sync::<DidOpenTextDocument>(on_did_open_text_document)?
.on_notification_sync::<DidCloseTextDocument>(on_did_close_text_document)?
.on_notification_sync::<DidChangeTextDocument>(on_did_change_text_document)?
.on_notification_sync::<DidSaveTextDocument>(on_did_save_text_document)?
.on_notification_sync::<Exit>(on_exit)?
.notification();
// If we have gotten here, we have not handled the notification
debug!(
"Error: no handler registered for notification '{}'",
notification.method
);
Ok(())
}
|
dispatch_notification
|
identifier_name
|
mod.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod heartbeat;
mod lsp_notification_dispatch;
mod lsp_request_dispatch;
mod lsp_state;
mod lsp_state_resources;
use crate::{
code_action::on_code_action,
completion::on_completion,
goto_definition::{
on_get_source_location_of_type_definition, on_goto_definition,
GetSourceLocationOfTypeDefinition,
},
graphql_tools::on_graphql_execute_query,
graphql_tools::GraphQLExecuteQuery,
hover::on_hover,
js_language_server::JSLanguageServer,
lsp::{
set_initializing_status, CompletionOptions, Connection, GotoDefinition, HoverRequest,
InitializeParams, Message, ServerCapabilities, ServerResponse, TextDocumentSyncCapability,
TextDocumentSyncKind, WorkDoneProgressOptions,
},
lsp_process_error::{LSPProcessError, LSPProcessResult},
lsp_runtime_error::LSPRuntimeError,
references::on_references,
resolved_types_at_location::{on_get_resolved_types_at_location, ResolvedTypesAtLocation},
search_schema_items::{on_search_schema_items, SearchSchemaItems},
shutdown::{on_exit, on_shutdown},
status_reporting::{LSPStatusReporter, StatusReportingArtifactWriter},
text_documents::{
on_did_change_text_document, on_did_close_text_document, on_did_open_text_document,
on_did_save_text_document,
},
ExtensionConfig,
};
use common::{PerfLogEvent, PerfLogger};
use crossbeam::{SendError, Sender};
use log::debug;
use lsp_notification_dispatch::LSPNotificationDispatch;
use lsp_request_dispatch::LSPRequestDispatch;
use lsp_server::{ErrorCode, Notification, ResponseError};
use lsp_types::{
notification::{
DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, Exit,
},
request::{CodeActionRequest, Completion, References, Shutdown},
CodeActionProviderCapability,
};
use relay_compiler::{config::Config, NoopArtifactWriter};
use std::sync::Arc;
pub use crate::LSPExtraDataProvider;
pub use lsp_state::LSPState;
pub use lsp_state::{Schemas, SourcePrograms};
use heartbeat::{on_heartbeat, HeartbeatRequest};
/// Initializes an LSP connection, handling the `initialize` message and `initialized` notification
/// handshake.
pub fn initialize(connection: &Connection) -> LSPProcessResult<InitializeParams> {
let server_capabilities = ServerCapabilities {
// Enable text document syncing so we can know when files are opened/changed/saved/closed
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::Full)),
completion_provider: Some(CompletionOptions {
resolve_provider: Some(true),
trigger_characters: Some(vec!["(".into(), "\n".into(), ",".into(), "@".into()]),
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
}),
hover_provider: Some(true),
definition_provider: Some(true),
references_provider: Some(true),
code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
..Default::default()
};
let server_capabilities = serde_json::to_value(&server_capabilities)?;
let params = connection.initialize(server_capabilities)?;
let params: InitializeParams = serde_json::from_value(params)?;
Ok(params)
}
/// Run the main server loop
pub async fn run<TPerfLogger: PerfLogger +'static>(
connection: Connection,
mut config: Config,
extension_config: ExtensionConfig,
_params: InitializeParams,
perf_logger: Arc<TPerfLogger>,
extra_data_provider: Box<dyn LSPExtraDataProvider + Send + Sync>,
js_resource: Box<dyn JSLanguageServer<TPerfLogger>>,
) -> LSPProcessResult<()>
where
TPerfLogger: PerfLogger +'static,
{
debug!(
"Running language server with config root {:?}",
config.root_dir
);
set_initializing_status(&connection.sender);
config.artifact_writer = if extension_config.no_artifacts {
Box::new(NoopArtifactWriter)
} else {
Box::new(StatusReportingArtifactWriter::new(
connection.sender.clone(),
config.artifact_writer,
))
};
config.status_reporter = Box::new(LSPStatusReporter::new(
config.root_dir.clone(),
connection.sender.clone(),
));
let mut lsp_state = LSPState::create_state(
Arc::new(config),
Arc::clone(&perf_logger),
extra_data_provider,
js_resource,
&extension_config,
connection.sender.clone(),
);
loop {
debug!("waiting for incoming messages...");
match connection.receiver.recv() {
Ok(Message::Request(req)) => {
handle_request(&mut lsp_state, req, &connection.sender, &perf_logger)
.map_err(LSPProcessError::from)?;
}
Ok(Message::Notification(notification)) => {
handle_notification(&mut lsp_state, notification, &perf_logger);
}
Ok(_) => {
// Ignore responses for now
}
Err(error) =>
|
}
}
}
fn handle_request<TPerfLogger: PerfLogger +'static>(
lsp_state: &mut LSPState<TPerfLogger>,
request: lsp_server::Request,
sender: &Sender<Message>,
perf_logger: &Arc<TPerfLogger>,
) -> Result<(), SendError<Message>> {
debug!("request received {:?}", request);
let get_server_response_bound = |req| dispatch_request(req, lsp_state);
let get_response = with_request_logging(perf_logger, get_server_response_bound);
sender.send(Message::Response(get_response(request)))
}
fn dispatch_request<TPerfLogger: PerfLogger +'static>(
request: lsp_server::Request,
lsp_state: &mut LSPState<TPerfLogger>,
) -> ServerResponse {
let get_response = || -> Result<_, ServerResponse> {
let request = LSPRequestDispatch::new(request, lsp_state)
.on_request_sync::<ResolvedTypesAtLocation>(on_get_resolved_types_at_location)?
.on_request_sync::<SearchSchemaItems>(on_search_schema_items)?
.on_request_sync::<GetSourceLocationOfTypeDefinition>(
on_get_source_location_of_type_definition,
)?
.on_request_sync::<HoverRequest>(on_hover)?
.on_request_sync::<GotoDefinition>(on_goto_definition)?
.on_request_sync::<References>(on_references)?
.on_request_sync::<Completion>(on_completion)?
.on_request_sync::<CodeActionRequest>(on_code_action)?
.on_request_sync::<Shutdown>(on_shutdown)?
.on_request_sync::<GraphQLExecuteQuery>(on_graphql_execute_query)?
.on_request_sync::<HeartbeatRequest>(on_heartbeat)?
.request();
// If we have gotten here, we have not handled the request
Ok(ServerResponse {
id: request.id,
result: None,
error: Some(ResponseError {
code: ErrorCode::MethodNotFound as i32,
data: None,
message: format!("No handler registered for method '{}'", request.method),
}),
})
};
get_response().unwrap_or_else(|response| response)
}
fn with_request_logging<'a, TPerfLogger: PerfLogger +'static>(
perf_logger: &'a Arc<TPerfLogger>,
get_response: impl FnOnce(lsp_server::Request) -> ServerResponse + 'a,
) -> impl FnOnce(lsp_server::Request) -> ServerResponse + 'a {
move |request| {
let lsp_request_event = perf_logger.create_event("lsp_message");
lsp_request_event.string("lsp_method", request.method.clone());
lsp_request_event.string("lsp_type", "request".to_string());
let lsp_request_processing_time = lsp_request_event.start("lsp_message_processing_time");
let response = get_response(request);
if response.result.is_some() {
lsp_request_event.string("lsp_outcome", "success".to_string());
} else if let Some(error) = &response.error {
lsp_request_event.string("lsp_outcome", "error".to_string());
if error.code!= ErrorCode::RequestCanceled as i32 {
lsp_request_event.string("lsp_error_message", error.message.to_string());
}
if let Some(data) = &error.data {
lsp_request_event.string("lsp_error_data", data.to_string());
}
}
// N.B. we don't handle the case where the ServerResponse has neither a result nor
// an error, which is an invalid state.
lsp_request_event.stop(lsp_request_processing_time);
perf_logger.complete_event(lsp_request_event);
response
}
}
fn handle_notification<TPerfLogger: PerfLogger +'static>(
lsp_state: &mut LSPState<TPerfLogger>,
notification: Notification,
perf_logger: &Arc<TPerfLogger>,
) {
debug!("notification received {:?}", notification);
let lsp_notification_event = perf_logger.create_event("lsp_message");
lsp_notification_event.string("lsp_method", notification.method.clone());
lsp_notification_event.string("lsp_type", "notification".to_string());
let lsp_notification_processing_time =
lsp_notification_event.start("lsp_message_processing_time");
let notification_result = dispatch_notification(notification, lsp_state);
match notification_result {
Ok(()) => {
// The notification is not handled
lsp_notification_event.string("lsp_outcome", "error".to_string());
}
Err(err) => {
if let Some(err) = err {
lsp_notification_event.string("lsp_outcome", "error".to_string());
if let LSPRuntimeError::UnexpectedError(message) = err {
lsp_notification_event.string("lsp_error_message", message);
}
} else {
lsp_notification_event.string("lsp_outcome", "success".to_string());
}
}
}
lsp_notification_event.stop(lsp_notification_processing_time);
perf_logger.complete_event(lsp_notification_event);
}
fn dispatch_notification<TPerfLogger: PerfLogger +'static>(
notification: lsp_server::Notification,
lsp_state: &mut LSPState<TPerfLogger>,
) -> Result<(), Option<LSPRuntimeError>> {
let notification = LSPNotificationDispatch::new(notification, lsp_state)
.on_notification_sync::<DidOpenTextDocument>(on_did_open_text_document)?
.on_notification_sync::<DidCloseTextDocument>(on_did_close_text_document)?
.on_notification_sync::<DidChangeTextDocument>(on_did_change_text_document)?
.on_notification_sync::<DidSaveTextDocument>(on_did_save_text_document)?
.on_notification_sync::<Exit>(on_exit)?
.notification();
// If we have gotten here, we have not handled the notification
debug!(
"Error: no handler registered for notification '{}'",
notification.method
);
Ok(())
}
|
{
panic!("Relay Language Server receiver error {:?}", error);
}
|
conditional_block
|
mod.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod heartbeat;
mod lsp_notification_dispatch;
mod lsp_request_dispatch;
|
use crate::{
code_action::on_code_action,
completion::on_completion,
goto_definition::{
on_get_source_location_of_type_definition, on_goto_definition,
GetSourceLocationOfTypeDefinition,
},
graphql_tools::on_graphql_execute_query,
graphql_tools::GraphQLExecuteQuery,
hover::on_hover,
js_language_server::JSLanguageServer,
lsp::{
set_initializing_status, CompletionOptions, Connection, GotoDefinition, HoverRequest,
InitializeParams, Message, ServerCapabilities, ServerResponse, TextDocumentSyncCapability,
TextDocumentSyncKind, WorkDoneProgressOptions,
},
lsp_process_error::{LSPProcessError, LSPProcessResult},
lsp_runtime_error::LSPRuntimeError,
references::on_references,
resolved_types_at_location::{on_get_resolved_types_at_location, ResolvedTypesAtLocation},
search_schema_items::{on_search_schema_items, SearchSchemaItems},
shutdown::{on_exit, on_shutdown},
status_reporting::{LSPStatusReporter, StatusReportingArtifactWriter},
text_documents::{
on_did_change_text_document, on_did_close_text_document, on_did_open_text_document,
on_did_save_text_document,
},
ExtensionConfig,
};
use common::{PerfLogEvent, PerfLogger};
use crossbeam::{SendError, Sender};
use log::debug;
use lsp_notification_dispatch::LSPNotificationDispatch;
use lsp_request_dispatch::LSPRequestDispatch;
use lsp_server::{ErrorCode, Notification, ResponseError};
use lsp_types::{
notification::{
DidChangeTextDocument, DidCloseTextDocument, DidOpenTextDocument, DidSaveTextDocument, Exit,
},
request::{CodeActionRequest, Completion, References, Shutdown},
CodeActionProviderCapability,
};
use relay_compiler::{config::Config, NoopArtifactWriter};
use std::sync::Arc;
pub use crate::LSPExtraDataProvider;
pub use lsp_state::LSPState;
pub use lsp_state::{Schemas, SourcePrograms};
use heartbeat::{on_heartbeat, HeartbeatRequest};
/// Initializes an LSP connection, handling the `initialize` message and `initialized` notification
/// handshake.
pub fn initialize(connection: &Connection) -> LSPProcessResult<InitializeParams> {
let server_capabilities = ServerCapabilities {
// Enable text document syncing so we can know when files are opened/changed/saved/closed
text_document_sync: Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::Full)),
completion_provider: Some(CompletionOptions {
resolve_provider: Some(true),
trigger_characters: Some(vec!["(".into(), "\n".into(), ",".into(), "@".into()]),
work_done_progress_options: WorkDoneProgressOptions {
work_done_progress: None,
},
}),
hover_provider: Some(true),
definition_provider: Some(true),
references_provider: Some(true),
code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
..Default::default()
};
let server_capabilities = serde_json::to_value(&server_capabilities)?;
let params = connection.initialize(server_capabilities)?;
let params: InitializeParams = serde_json::from_value(params)?;
Ok(params)
}
/// Run the main server loop
pub async fn run<TPerfLogger: PerfLogger +'static>(
connection: Connection,
mut config: Config,
extension_config: ExtensionConfig,
_params: InitializeParams,
perf_logger: Arc<TPerfLogger>,
extra_data_provider: Box<dyn LSPExtraDataProvider + Send + Sync>,
js_resource: Box<dyn JSLanguageServer<TPerfLogger>>,
) -> LSPProcessResult<()>
where
TPerfLogger: PerfLogger +'static,
{
debug!(
"Running language server with config root {:?}",
config.root_dir
);
set_initializing_status(&connection.sender);
config.artifact_writer = if extension_config.no_artifacts {
Box::new(NoopArtifactWriter)
} else {
Box::new(StatusReportingArtifactWriter::new(
connection.sender.clone(),
config.artifact_writer,
))
};
config.status_reporter = Box::new(LSPStatusReporter::new(
config.root_dir.clone(),
connection.sender.clone(),
));
let mut lsp_state = LSPState::create_state(
Arc::new(config),
Arc::clone(&perf_logger),
extra_data_provider,
js_resource,
&extension_config,
connection.sender.clone(),
);
loop {
debug!("waiting for incoming messages...");
match connection.receiver.recv() {
Ok(Message::Request(req)) => {
handle_request(&mut lsp_state, req, &connection.sender, &perf_logger)
.map_err(LSPProcessError::from)?;
}
Ok(Message::Notification(notification)) => {
handle_notification(&mut lsp_state, notification, &perf_logger);
}
Ok(_) => {
// Ignore responses for now
}
Err(error) => {
panic!("Relay Language Server receiver error {:?}", error);
}
}
}
}
fn handle_request<TPerfLogger: PerfLogger +'static>(
lsp_state: &mut LSPState<TPerfLogger>,
request: lsp_server::Request,
sender: &Sender<Message>,
perf_logger: &Arc<TPerfLogger>,
) -> Result<(), SendError<Message>> {
debug!("request received {:?}", request);
let get_server_response_bound = |req| dispatch_request(req, lsp_state);
let get_response = with_request_logging(perf_logger, get_server_response_bound);
sender.send(Message::Response(get_response(request)))
}
fn dispatch_request<TPerfLogger: PerfLogger +'static>(
request: lsp_server::Request,
lsp_state: &mut LSPState<TPerfLogger>,
) -> ServerResponse {
let get_response = || -> Result<_, ServerResponse> {
let request = LSPRequestDispatch::new(request, lsp_state)
.on_request_sync::<ResolvedTypesAtLocation>(on_get_resolved_types_at_location)?
.on_request_sync::<SearchSchemaItems>(on_search_schema_items)?
.on_request_sync::<GetSourceLocationOfTypeDefinition>(
on_get_source_location_of_type_definition,
)?
.on_request_sync::<HoverRequest>(on_hover)?
.on_request_sync::<GotoDefinition>(on_goto_definition)?
.on_request_sync::<References>(on_references)?
.on_request_sync::<Completion>(on_completion)?
.on_request_sync::<CodeActionRequest>(on_code_action)?
.on_request_sync::<Shutdown>(on_shutdown)?
.on_request_sync::<GraphQLExecuteQuery>(on_graphql_execute_query)?
.on_request_sync::<HeartbeatRequest>(on_heartbeat)?
.request();
// If we have gotten here, we have not handled the request
Ok(ServerResponse {
id: request.id,
result: None,
error: Some(ResponseError {
code: ErrorCode::MethodNotFound as i32,
data: None,
message: format!("No handler registered for method '{}'", request.method),
}),
})
};
get_response().unwrap_or_else(|response| response)
}
fn with_request_logging<'a, TPerfLogger: PerfLogger +'static>(
perf_logger: &'a Arc<TPerfLogger>,
get_response: impl FnOnce(lsp_server::Request) -> ServerResponse + 'a,
) -> impl FnOnce(lsp_server::Request) -> ServerResponse + 'a {
move |request| {
let lsp_request_event = perf_logger.create_event("lsp_message");
lsp_request_event.string("lsp_method", request.method.clone());
lsp_request_event.string("lsp_type", "request".to_string());
let lsp_request_processing_time = lsp_request_event.start("lsp_message_processing_time");
let response = get_response(request);
if response.result.is_some() {
lsp_request_event.string("lsp_outcome", "success".to_string());
} else if let Some(error) = &response.error {
lsp_request_event.string("lsp_outcome", "error".to_string());
if error.code!= ErrorCode::RequestCanceled as i32 {
lsp_request_event.string("lsp_error_message", error.message.to_string());
}
if let Some(data) = &error.data {
lsp_request_event.string("lsp_error_data", data.to_string());
}
}
// N.B. we don't handle the case where the ServerResponse has neither a result nor
// an error, which is an invalid state.
lsp_request_event.stop(lsp_request_processing_time);
perf_logger.complete_event(lsp_request_event);
response
}
}
fn handle_notification<TPerfLogger: PerfLogger +'static>(
lsp_state: &mut LSPState<TPerfLogger>,
notification: Notification,
perf_logger: &Arc<TPerfLogger>,
) {
debug!("notification received {:?}", notification);
let lsp_notification_event = perf_logger.create_event("lsp_message");
lsp_notification_event.string("lsp_method", notification.method.clone());
lsp_notification_event.string("lsp_type", "notification".to_string());
let lsp_notification_processing_time =
lsp_notification_event.start("lsp_message_processing_time");
let notification_result = dispatch_notification(notification, lsp_state);
match notification_result {
Ok(()) => {
// The notification is not handled
lsp_notification_event.string("lsp_outcome", "error".to_string());
}
Err(err) => {
if let Some(err) = err {
lsp_notification_event.string("lsp_outcome", "error".to_string());
if let LSPRuntimeError::UnexpectedError(message) = err {
lsp_notification_event.string("lsp_error_message", message);
}
} else {
lsp_notification_event.string("lsp_outcome", "success".to_string());
}
}
}
lsp_notification_event.stop(lsp_notification_processing_time);
perf_logger.complete_event(lsp_notification_event);
}
fn dispatch_notification<TPerfLogger: PerfLogger +'static>(
notification: lsp_server::Notification,
lsp_state: &mut LSPState<TPerfLogger>,
) -> Result<(), Option<LSPRuntimeError>> {
let notification = LSPNotificationDispatch::new(notification, lsp_state)
.on_notification_sync::<DidOpenTextDocument>(on_did_open_text_document)?
.on_notification_sync::<DidCloseTextDocument>(on_did_close_text_document)?
.on_notification_sync::<DidChangeTextDocument>(on_did_change_text_document)?
.on_notification_sync::<DidSaveTextDocument>(on_did_save_text_document)?
.on_notification_sync::<Exit>(on_exit)?
.notification();
// If we have gotten here, we have not handled the notification
debug!(
"Error: no handler registered for notification '{}'",
notification.method
);
Ok(())
}
|
mod lsp_state;
mod lsp_state_resources;
|
random_line_split
|
wad.rs
|
use std::u8;
use nom::{self, IResult, Needed, le_u32};
use super::util::fixed_length_ascii;
use ::errors::{Result, nom_to_result};
use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType};
named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD")));
named!(pwad_tag<WADType>, value!(WADType::PWAD, tag!(b"PWAD")));
named!(wad_header<BareWADHeader>, do_parse!(
identification: return_error!(
nom::ErrorKind::Custom(1),
alt!(iwad_tag | pwad_tag)) >>
numlumps: le_u32 >>
infotableofs: le_u32 >>
(BareWADHeader{ identification, numlumps, infotableofs })
));
named!(wad_entry<BareWADDirectoryEntry>, dbg_dmp!(do_parse!(
filepos: le_u32 >>
size: le_u32 >>
name: apply!(fixed_length_ascii, 8) >>
(BareWADDirectoryEntry{ filepos, size, name })
)));
fn wad_directory<'a>(buf: &'a [u8], header: &BareWADHeader) -> IResult<&'a [u8], Vec<BareWADDirectoryEntry<'a>>> {
let lumpct = header.numlumps as usize;
let offset = header.infotableofs as usize;
// TODO can i unhardcode the size of a wad entry here?
let tablelen = lumpct * 16;
if buf.len() < offset + tablelen {
return Err(nom::Err::Incomplete(Needed::Size(tablelen)));
}
let mut ret = Vec::with_capacity(lumpct);
let mut parse_from = &buf[offset..];
for _ in 0..lumpct {
let (leftovers, entry) = try_parse!(parse_from, wad_entry);
ret.push(entry);
parse_from = leftovers;
}
Ok((parse_from, ret))
}
// TODO problems to scan a wad map for:
// - missing a required lump
// TODO curiosities to scan a wad map for:
// - content in ENDMAP
// - UDMF along with the old-style text maps
// FIXME use Result, but, figure out how to get an actual error out of here
// FIXME actually this fairly simple format is a good place to start thinking about how to return errors in general; like, do i want custom errors for tags? etc
pub fn parse_wad(buf: &[u8]) -> Result<BareWAD>
|
{
// FIXME ambiguous whether the error was from parsing the header or the entries
let header = nom_to_result("wad header", buf, wad_header(buf))?;
// TODO buf is not actually the right place here
let entries = nom_to_result("wad index", buf, wad_directory(buf, &header))?;
Ok(BareWAD{ buffer: buf, header, directory: entries })
}
|
identifier_body
|
|
wad.rs
|
use std::u8;
use nom::{self, IResult, Needed, le_u32};
use super::util::fixed_length_ascii;
use ::errors::{Result, nom_to_result};
use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType};
|
named!(wad_header<BareWADHeader>, do_parse!(
identification: return_error!(
nom::ErrorKind::Custom(1),
alt!(iwad_tag | pwad_tag)) >>
numlumps: le_u32 >>
infotableofs: le_u32 >>
(BareWADHeader{ identification, numlumps, infotableofs })
));
named!(wad_entry<BareWADDirectoryEntry>, dbg_dmp!(do_parse!(
filepos: le_u32 >>
size: le_u32 >>
name: apply!(fixed_length_ascii, 8) >>
(BareWADDirectoryEntry{ filepos, size, name })
)));
fn wad_directory<'a>(buf: &'a [u8], header: &BareWADHeader) -> IResult<&'a [u8], Vec<BareWADDirectoryEntry<'a>>> {
let lumpct = header.numlumps as usize;
let offset = header.infotableofs as usize;
// TODO can i unhardcode the size of a wad entry here?
let tablelen = lumpct * 16;
if buf.len() < offset + tablelen {
return Err(nom::Err::Incomplete(Needed::Size(tablelen)));
}
let mut ret = Vec::with_capacity(lumpct);
let mut parse_from = &buf[offset..];
for _ in 0..lumpct {
let (leftovers, entry) = try_parse!(parse_from, wad_entry);
ret.push(entry);
parse_from = leftovers;
}
Ok((parse_from, ret))
}
// TODO problems to scan a wad map for:
// - missing a required lump
// TODO curiosities to scan a wad map for:
// - content in ENDMAP
// - UDMF along with the old-style text maps
// FIXME use Result, but, figure out how to get an actual error out of here
// FIXME actually this fairly simple format is a good place to start thinking about how to return errors in general; like, do i want custom errors for tags? etc
pub fn parse_wad(buf: &[u8]) -> Result<BareWAD> {
// FIXME ambiguous whether the error was from parsing the header or the entries
let header = nom_to_result("wad header", buf, wad_header(buf))?;
// TODO buf is not actually the right place here
let entries = nom_to_result("wad index", buf, wad_directory(buf, &header))?;
Ok(BareWAD{ buffer: buf, header, directory: entries })
}
|
named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD")));
named!(pwad_tag<WADType>, value!(WADType::PWAD, tag!(b"PWAD")));
|
random_line_split
|
wad.rs
|
use std::u8;
use nom::{self, IResult, Needed, le_u32};
use super::util::fixed_length_ascii;
use ::errors::{Result, nom_to_result};
use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType};
named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD")));
named!(pwad_tag<WADType>, value!(WADType::PWAD, tag!(b"PWAD")));
named!(wad_header<BareWADHeader>, do_parse!(
identification: return_error!(
nom::ErrorKind::Custom(1),
alt!(iwad_tag | pwad_tag)) >>
numlumps: le_u32 >>
infotableofs: le_u32 >>
(BareWADHeader{ identification, numlumps, infotableofs })
));
named!(wad_entry<BareWADDirectoryEntry>, dbg_dmp!(do_parse!(
filepos: le_u32 >>
size: le_u32 >>
name: apply!(fixed_length_ascii, 8) >>
(BareWADDirectoryEntry{ filepos, size, name })
)));
fn
|
<'a>(buf: &'a [u8], header: &BareWADHeader) -> IResult<&'a [u8], Vec<BareWADDirectoryEntry<'a>>> {
let lumpct = header.numlumps as usize;
let offset = header.infotableofs as usize;
// TODO can i unhardcode the size of a wad entry here?
let tablelen = lumpct * 16;
if buf.len() < offset + tablelen {
return Err(nom::Err::Incomplete(Needed::Size(tablelen)));
}
let mut ret = Vec::with_capacity(lumpct);
let mut parse_from = &buf[offset..];
for _ in 0..lumpct {
let (leftovers, entry) = try_parse!(parse_from, wad_entry);
ret.push(entry);
parse_from = leftovers;
}
Ok((parse_from, ret))
}
// TODO problems to scan a wad map for:
// - missing a required lump
// TODO curiosities to scan a wad map for:
// - content in ENDMAP
// - UDMF along with the old-style text maps
// FIXME use Result, but, figure out how to get an actual error out of here
// FIXME actually this fairly simple format is a good place to start thinking about how to return errors in general; like, do i want custom errors for tags? etc
pub fn parse_wad(buf: &[u8]) -> Result<BareWAD> {
// FIXME ambiguous whether the error was from parsing the header or the entries
let header = nom_to_result("wad header", buf, wad_header(buf))?;
// TODO buf is not actually the right place here
let entries = nom_to_result("wad index", buf, wad_directory(buf, &header))?;
Ok(BareWAD{ buffer: buf, header, directory: entries })
}
|
wad_directory
|
identifier_name
|
wad.rs
|
use std::u8;
use nom::{self, IResult, Needed, le_u32};
use super::util::fixed_length_ascii;
use ::errors::{Result, nom_to_result};
use ::archive::wad::{BareWAD, BareWADHeader, BareWADDirectoryEntry, WADType};
named!(iwad_tag<WADType>, value!(WADType::IWAD, tag!(b"IWAD")));
named!(pwad_tag<WADType>, value!(WADType::PWAD, tag!(b"PWAD")));
named!(wad_header<BareWADHeader>, do_parse!(
identification: return_error!(
nom::ErrorKind::Custom(1),
alt!(iwad_tag | pwad_tag)) >>
numlumps: le_u32 >>
infotableofs: le_u32 >>
(BareWADHeader{ identification, numlumps, infotableofs })
));
named!(wad_entry<BareWADDirectoryEntry>, dbg_dmp!(do_parse!(
filepos: le_u32 >>
size: le_u32 >>
name: apply!(fixed_length_ascii, 8) >>
(BareWADDirectoryEntry{ filepos, size, name })
)));
fn wad_directory<'a>(buf: &'a [u8], header: &BareWADHeader) -> IResult<&'a [u8], Vec<BareWADDirectoryEntry<'a>>> {
let lumpct = header.numlumps as usize;
let offset = header.infotableofs as usize;
// TODO can i unhardcode the size of a wad entry here?
let tablelen = lumpct * 16;
if buf.len() < offset + tablelen
|
let mut ret = Vec::with_capacity(lumpct);
let mut parse_from = &buf[offset..];
for _ in 0..lumpct {
let (leftovers, entry) = try_parse!(parse_from, wad_entry);
ret.push(entry);
parse_from = leftovers;
}
Ok((parse_from, ret))
}
// TODO problems to scan a wad map for:
// - missing a required lump
// TODO curiosities to scan a wad map for:
// - content in ENDMAP
// - UDMF along with the old-style text maps
// FIXME use Result, but, figure out how to get an actual error out of here
// FIXME actually this fairly simple format is a good place to start thinking about how to return errors in general; like, do i want custom errors for tags? etc
pub fn parse_wad(buf: &[u8]) -> Result<BareWAD> {
// FIXME ambiguous whether the error was from parsing the header or the entries
let header = nom_to_result("wad header", buf, wad_header(buf))?;
// TODO buf is not actually the right place here
let entries = nom_to_result("wad index", buf, wad_directory(buf, &header))?;
Ok(BareWAD{ buffer: buf, header, directory: entries })
}
|
{
return Err(nom::Err::Incomplete(Needed::Size(tablelen)));
}
|
conditional_block
|
mod.rs
|
try!(mkdir_recursive(&self.dirname()));
let mut file = try!(
fs::File::create(&self.path)
.with_err_msg(format!("Could not create file; path={}",
self.path.display())));
file.write_all(self.body.as_bytes())
.with_err_msg(format!("Could not write to file; path={}",
self.path.display()))
}
fn dirname(&self) -> &Path {
self.path.parent().unwrap()
}
}
#[derive(PartialEq,Clone)]
struct SymlinkBuilder {
dst: PathBuf,
src: PathBuf,
}
impl SymlinkBuilder {
pub fn new(dst: PathBuf, src: PathBuf) -> SymlinkBuilder {
SymlinkBuilder { dst: dst, src: src }
}
#[cfg(unix)]
fn mk(&self) -> Result<(), String> {
try!(mkdir_recursive(&self.dirname()));
os::unix::fs::symlink(&self.dst, &self.src)
.with_err_msg(format!("Could not create symlink; dst={} src={}",
self.dst.display(), self.src.display()))
}
#[cfg(windows)]
fn mk(&self) -> Result<(), String> {
try!(mkdir_recursive(&self.dirname()));
os::windows::fs::symlink_file(&self.dst, &self.src)
.with_err_msg(format!("Could not create symlink; dst={} src={}",
self.dst.display(), self.src.display()))
}
fn dirname(&self) -> &Path {
self.src.parent().unwrap()
}
}
#[derive(PartialEq,Clone)]
pub struct ProjectBuilder {
name: String,
root: PathBuf,
files: Vec<FileBuilder>,
symlinks: Vec<SymlinkBuilder>
}
impl ProjectBuilder {
pub fn new(name: &str, root: PathBuf) -> ProjectBuilder {
ProjectBuilder {
name: name.to_string(),
root: root,
files: vec![],
symlinks: vec![]
}
}
pub fn root(&self) -> PathBuf {
self.root.clone()
}
pub fn url(&self) -> Url { path2url(self.root()) }
pub fn bin(&self, b: &str) -> PathBuf {
self.build_dir().join("debug").join(&format!("{}{}", b,
env::consts::EXE_SUFFIX))
}
pub fn release_bin(&self, b: &str) -> PathBuf {
self.build_dir().join("release").join(&format!("{}{}", b,
env::consts::EXE_SUFFIX))
}
pub fn target_bin(&self, target: &str, b: &str) -> PathBuf {
self.build_dir().join(target).join("debug")
.join(&format!("{}{}", b, env::consts::EXE_SUFFIX))
}
pub fn build_dir(&self) -> PathBuf {
self.root.join("target")
}
pub fn process<T: AsRef<OsStr>>(&self, program: T) -> ProcessBuilder {
let mut p = ::process(program);
p.cwd(self.root());
return p
}
pub fn cargo(&self, cmd: &str) -> ProcessBuilder {
let mut p = self.process(&cargo_dir().join("cargo"));
p.arg(cmd);
return p;
}
pub fn cargo_process(&self, cmd: &str) -> ProcessBuilder {
self.build();
self.cargo(cmd)
}
pub fn file<B: AsRef<Path>>(mut self, path: B,
body: &str) -> ProjectBuilder {
self.files.push(FileBuilder::new(self.root.join(path), body));
self
}
pub fn symlink<T: AsRef<Path>>(mut self, dst: T,
src: T) -> ProjectBuilder {
self.symlinks.push(SymlinkBuilder::new(self.root.join(dst),
self.root.join(src)));
self
}
// TODO: return something different than a ProjectBuilder
pub fn build(&self) -> &ProjectBuilder {
match self.build_with_result() {
Err(e) => panic!(e),
_ => return self
}
}
pub fn build_with_result(&self) -> Result<(), String> {
// First, clean the directory if it already exists
try!(self.rm_root());
// Create the empty directory
try!(mkdir_recursive(&self.root));
for file in self.files.iter() {
try!(file.mk());
}
for symlink in self.symlinks.iter() {
try!(symlink.mk());
}
Ok(())
}
fn rm_root(&self) -> Result<(), String> {
if self.root.c_exists() {
rmdir_recursive(&self.root)
} else {
Ok(())
}
}
}
// Generates a project layout
pub fn project(name: &str) -> ProjectBuilder {
ProjectBuilder::new(name, paths::root().join(name))
}
// === Helpers ===
pub fn mkdir_recursive(path: &Path) -> Result<(), String> {
fs::create_dir_all(path)
.with_err_msg(format!("could not create directory; path={}",
path.display()))
}
pub fn rmdir_recursive(path: &Path) -> Result<(), String> {
path.rm_rf()
.with_err_msg(format!("could not rm directory; path={}",
path.display()))
}
pub fn main_file(println: &str, deps: &[&str]) -> String {
let mut buf = String::new();
for dep in deps.iter() {
buf.push_str(&format!("extern crate {};\n", dep));
}
buf.push_str("fn main() { println!(");
buf.push_str(&println);
buf.push_str("); }\n");
buf.to_string()
}
trait ErrMsg<T> {
fn with_err_msg(self, val: String) -> Result<T, String>;
}
impl<T, E: fmt::Display> ErrMsg<T> for Result<T, E> {
fn with_err_msg(self, val: String) -> Result<T, String> {
match self {
Ok(val) => Ok(val),
Err(err) => Err(format!("{}; original={}", val, err))
}
}
}
// Path to cargo executables
pub fn cargo_dir() -> PathBuf {
env::var_os("CARGO_BIN_PATH").map(PathBuf::from).or_else(|| {
env::current_exe().ok().as_ref().and_then(|s| s.parent())
.map(|s| s.to_path_buf())
}).unwrap_or_else(|| {
panic!("CARGO_BIN_PATH wasn't set. Cannot continue running test")
})
}
/// Returns an absolute path in the filesystem that `path` points to. The
/// returned path does not contain any symlinks in its hierarchy.
/*
*
* ===== Matchers =====
*
*/
#[derive(Clone)]
pub struct Execs {
expect_stdout: Option<String>,
expect_stdin: Option<String>,
expect_stderr: Option<String>,
expect_exit_code: Option<i32>,
expect_stdout_contains: Vec<String>,
expect_stderr_contains: Vec<String>,
expect_json: Option<Json>,
}
impl Execs {
pub fn with_stdout<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stdout = Some(expected.to_string());
self
}
pub fn with_stderr<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stderr = Some(expected.to_string());
self
}
pub fn
|
(mut self, expected: i32) -> Execs {
self.expect_exit_code = Some(expected);
self
}
pub fn with_stdout_contains<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stdout_contains.push(expected.to_string());
self
}
pub fn with_stderr_contains<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stderr_contains.push(expected.to_string());
self
}
pub fn with_json(mut self, expected: &str) -> Execs {
self.expect_json = Some(Json::from_str(expected).unwrap());
self
}
fn match_output(&self, actual: &Output) -> ham::MatchResult {
self.match_status(actual)
.and(self.match_stdout(actual))
.and(self.match_stderr(actual))
}
fn match_status(&self, actual: &Output) -> ham::MatchResult {
match self.expect_exit_code {
None => ham::success(),
Some(code) => {
ham::expect(
actual.status.code() == Some(code),
format!("exited with {}\n--- stdout\n{}\n--- stderr\n{}",
actual.status,
String::from_utf8_lossy(&actual.stdout),
String::from_utf8_lossy(&actual.stderr)))
}
}
}
fn match_stdout(&self, actual: &Output) -> ham::MatchResult {
try!(self.match_std(self.expect_stdout.as_ref(), &actual.stdout,
"stdout", &actual.stderr, false));
for expect in self.expect_stdout_contains.iter() {
try!(self.match_std(Some(expect), &actual.stdout, "stdout",
&actual.stderr, true));
}
for expect in self.expect_stderr_contains.iter() {
try!(self.match_std(Some(expect), &actual.stderr, "stderr",
&actual.stdout, true));
}
if let Some(ref expect_json) = self.expect_json {
try!(self.match_json(expect_json, &actual.stdout));
}
Ok(())
}
fn match_stderr(&self, actual: &Output) -> ham::MatchResult {
self.match_std(self.expect_stderr.as_ref(), &actual.stderr,
"stderr", &actual.stdout, false)
}
#[allow(deprecated)] // connect => join in 1.3
fn match_std(&self, expected: Option<&String>, actual: &[u8],
description: &str, extra: &[u8],
partial: bool) -> ham::MatchResult {
let out = match expected {
Some(out) => out,
None => return ham::success(),
};
let actual = match str::from_utf8(actual) {
Err(..) => return Err(format!("{} was not utf8 encoded",
description)),
Ok(actual) => actual,
};
// Let's not deal with \r\n vs \n on windows...
let actual = actual.replace("\r", "");
let actual = actual.replace("\t", "<tab>");
let mut a = actual.lines();
let e = out.lines();
let diffs = if partial {
let mut min = self.diff_lines(a.clone(), e.clone(), partial);
while let Some(..) = a.next() {
let a = self.diff_lines(a.clone(), e.clone(), partial);
if a.len() < min.len() {
min = a;
}
}
min
} else {
self.diff_lines(a, e, partial)
};
ham::expect(diffs.is_empty(),
format!("differences:\n\
{}\n\n\
other output:\n\
`{}`", diffs.connect("\n"),
String::from_utf8_lossy(extra)))
}
fn match_json(&self, expected: &Json, stdout: &[u8]) -> ham::MatchResult {
let stdout = match str::from_utf8(stdout) {
Err(..) => return Err("stdout was not utf8 encoded".to_owned()),
Ok(stdout) => stdout,
};
let actual = match Json::from_str(stdout) {
Err(..) => return Err(format!("Invalid json {}", stdout)),
Ok(actual) => actual,
};
match find_mismatch(expected, &actual) {
Some((expected_part, actual_part)) => Err(format!(
"JSON mismatch\nExpected:\n{}\nWas:\n{}\nExpected part:\n{}\nActual part:\n{}\n",
expected.pretty(), actual.pretty(),
expected_part.pretty(), actual_part.pretty()
)),
None => Ok(()),
}
}
fn diff_lines<'a>(&self, actual: str::Lines<'a>, expected: str::Lines<'a>,
partial: bool) -> Vec<String> {
let actual = actual.take(if partial {
expected.clone().count()
} else {
usize::MAX
});
zip_all(actual, expected).enumerate().filter_map(|(i, (a,e))| {
match (a, e) {
(Some(a), Some(e)) => {
if lines_match(&e, &a) {
None
} else {
Some(format!("{:3} - |{}|\n + |{}|\n", i, e, a))
}
},
(Some(a), None) => {
Some(format!("{:3} -\n + |{}|\n", i, a))
},
(None, Some(e)) => {
Some(format!("{:3} - |{}|\n +\n", i, e))
},
(None, None) => panic!("Cannot get here")
}
}).collect()
}
}
fn lines_match(expected: &str, mut actual: &str) -> bool {
for part in expected.split("[..]") {
match actual.find(part) {
Some(i) => actual = &actual[i + part.len()..],
None => {
return false
}
}
}
actual.is_empty() || expected.ends_with("[..]")
}
// Compares JSON object for approximate equality.
// You can use `[..]` wildcard in strings (useful for OS dependent things such as paths).
// Arrays are sorted before comparison.
fn find_mismatch<'a>(expected: &'a Json, actual: &'a Json) -> Option<(&'a Json, &'a Json)> {
use rustc_serialize::json::Json::*;
match (expected, actual) {
(&I64(l), &I64(r)) if l == r => None,
(&F64(l), &F64(r)) if l == r => None,
(&U64(l), &U64(r)) if l == r => None,
(&Boolean(l), &Boolean(r)) if l == r => None,
(&String(ref l), &String(ref r)) if lines_match(l, r) => None,
(&Array(ref l), &Array(ref r)) => {
if l.len()!= r.len() {
return Some((expected, actual));
}
fn sorted(xs: &Vec<Json>) -> Vec<&Json> {
let mut result = xs.iter().collect::<Vec<_>>();
// `unwrap` should be safe because JSON spec does not allow NaNs
result.sort_by(|x, y| x.partial_cmp(y).unwrap());
result
}
sorted(l).iter().zip(sorted(r))
.filter_map(|(l, r)| find_mismatch(l, r))
.nth(0)
}
(&Object(ref l), &Object(ref r)) => {
let same_keys = l.len() == r.len() && l.keys().all(|k| r.contains_key(k));
if!same_keys {
return Some((expected, actual));
}
l.values().zip(r.values())
.filter_map(|(l, r)| find_mismatch(l, r))
.nth(0)
}
(&Null, &Null) => None,
_ => Some((expected, actual)),
}
}
struct ZipAll<I1: Iterator, I2: Iterator> {
first: I1,
second: I2,
}
impl<T, I1: Iterator<Item=T>, I2: Iterator<Item=T>> Iterator for ZipAll<I1, I2> {
type Item = (Option<T>, Option<T>);
fn next(&mut self) -> Option<(Option<T>, Option<T>)> {
let first = self.first.next();
let second = self.second.next();
match (first, second) {
(None, None) => None,
(a, b) => Some((a, b))
}
}
}
fn zip_all<T, I1: Iterator<Item=T>, I2: Iterator<Item=T>>(a: I1, b: I2) -> ZipAll<I1, I2> {
ZipAll {
first: a,
second: b,
}
}
impl fmt::Display for Execs {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "execs")
}
}
impl ham::Matcher<ProcessBuilder> for Execs {
fn matches(&self, mut process: ProcessBuilder) -> ham::MatchResult {
self.matches(&mut process)
}
}
impl<'a> ham::Matcher<&'a mut ProcessBuilder> for Execs {
fn matches(&self, process: &'a mut ProcessBuilder) -> ham::MatchResult {
let res = process.exec_with_output();
match res {
Ok(out) => self.match_output(&out),
Err(ProcessError { output: Some(ref out),.. }) => {
self.match_output(out)
}
Err(e) => {
let mut s = format!("could not exec process {}: {}", process, e);
match e.cause() {
Some(cause) => s.push_str(&format!("\ncaused by: {}",
cause.description())),
None => {}
}
Err(s)
}
}
}
}
pub fn execs() -> Execs {
Execs {
expect_stdout: None,
expect_stderr: None,
expect_stdin: None,
expect_exit_code: None,
expect_stdout_contains: Vec::new(),
expect_stderr_contains: Vec::new(),
expect_json: None,
}
}
#[derive(Clone)]
pub struct ShellWrites {
expected: String
}
impl fmt::Display for ShellWrites {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "`{}` written to the shell", self.expected)
}
}
impl<'a> ham::Matcher<&'a [u8]> for ShellWrites {
fn matches(&self, actual: &[u8])
-> ham::MatchResult
{
let actual = String::from_utf8_lossy(actual);
let actual = actual.to_string();
ham::expect(actual == self.expected, actual)
}
}
pub fn shell_writes<T: fmt::Display>(string: T) -> ShellWrites {
ShellWrites {
|
with_status
|
identifier_name
|
mod.rs
|
{
try!(mkdir_recursive(&self.dirname()));
let mut file = try!(
fs::File::create(&self.path)
.with_err_msg(format!("Could not create file; path={}",
self.path.display())));
file.write_all(self.body.as_bytes())
.with_err_msg(format!("Could not write to file; path={}",
self.path.display()))
}
fn dirname(&self) -> &Path {
self.path.parent().unwrap()
}
}
#[derive(PartialEq,Clone)]
struct SymlinkBuilder {
dst: PathBuf,
src: PathBuf,
}
impl SymlinkBuilder {
pub fn new(dst: PathBuf, src: PathBuf) -> SymlinkBuilder {
SymlinkBuilder { dst: dst, src: src }
}
#[cfg(unix)]
fn mk(&self) -> Result<(), String> {
try!(mkdir_recursive(&self.dirname()));
os::unix::fs::symlink(&self.dst, &self.src)
.with_err_msg(format!("Could not create symlink; dst={} src={}",
self.dst.display(), self.src.display()))
}
#[cfg(windows)]
fn mk(&self) -> Result<(), String> {
try!(mkdir_recursive(&self.dirname()));
os::windows::fs::symlink_file(&self.dst, &self.src)
.with_err_msg(format!("Could not create symlink; dst={} src={}",
self.dst.display(), self.src.display()))
}
fn dirname(&self) -> &Path {
self.src.parent().unwrap()
}
}
#[derive(PartialEq,Clone)]
pub struct ProjectBuilder {
name: String,
root: PathBuf,
files: Vec<FileBuilder>,
symlinks: Vec<SymlinkBuilder>
}
impl ProjectBuilder {
pub fn new(name: &str, root: PathBuf) -> ProjectBuilder {
ProjectBuilder {
name: name.to_string(),
root: root,
files: vec![],
symlinks: vec![]
}
}
pub fn root(&self) -> PathBuf {
self.root.clone()
}
pub fn url(&self) -> Url { path2url(self.root()) }
pub fn bin(&self, b: &str) -> PathBuf {
self.build_dir().join("debug").join(&format!("{}{}", b,
env::consts::EXE_SUFFIX))
}
pub fn release_bin(&self, b: &str) -> PathBuf {
self.build_dir().join("release").join(&format!("{}{}", b,
env::consts::EXE_SUFFIX))
}
pub fn target_bin(&self, target: &str, b: &str) -> PathBuf {
self.build_dir().join(target).join("debug")
.join(&format!("{}{}", b, env::consts::EXE_SUFFIX))
}
pub fn build_dir(&self) -> PathBuf {
self.root.join("target")
}
pub fn process<T: AsRef<OsStr>>(&self, program: T) -> ProcessBuilder {
let mut p = ::process(program);
p.cwd(self.root());
return p
}
pub fn cargo(&self, cmd: &str) -> ProcessBuilder {
let mut p = self.process(&cargo_dir().join("cargo"));
p.arg(cmd);
return p;
}
pub fn cargo_process(&self, cmd: &str) -> ProcessBuilder {
self.build();
self.cargo(cmd)
}
pub fn file<B: AsRef<Path>>(mut self, path: B,
body: &str) -> ProjectBuilder {
self.files.push(FileBuilder::new(self.root.join(path), body));
self
}
pub fn symlink<T: AsRef<Path>>(mut self, dst: T,
src: T) -> ProjectBuilder {
self.symlinks.push(SymlinkBuilder::new(self.root.join(dst),
self.root.join(src)));
self
}
// TODO: return something different than a ProjectBuilder
pub fn build(&self) -> &ProjectBuilder {
match self.build_with_result() {
Err(e) => panic!(e),
_ => return self
}
}
pub fn build_with_result(&self) -> Result<(), String> {
// First, clean the directory if it already exists
try!(self.rm_root());
// Create the empty directory
try!(mkdir_recursive(&self.root));
for file in self.files.iter() {
try!(file.mk());
}
for symlink in self.symlinks.iter() {
try!(symlink.mk());
}
Ok(())
}
fn rm_root(&self) -> Result<(), String> {
if self.root.c_exists() {
rmdir_recursive(&self.root)
} else {
Ok(())
}
}
}
// Generates a project layout
pub fn project(name: &str) -> ProjectBuilder {
ProjectBuilder::new(name, paths::root().join(name))
}
// === Helpers ===
pub fn mkdir_recursive(path: &Path) -> Result<(), String> {
fs::create_dir_all(path)
.with_err_msg(format!("could not create directory; path={}",
path.display()))
}
pub fn rmdir_recursive(path: &Path) -> Result<(), String> {
path.rm_rf()
.with_err_msg(format!("could not rm directory; path={}",
path.display()))
}
pub fn main_file(println: &str, deps: &[&str]) -> String {
let mut buf = String::new();
for dep in deps.iter() {
buf.push_str(&format!("extern crate {};\n", dep));
}
buf.push_str("fn main() { println!(");
buf.push_str(&println);
buf.push_str("); }\n");
buf.to_string()
}
trait ErrMsg<T> {
fn with_err_msg(self, val: String) -> Result<T, String>;
}
impl<T, E: fmt::Display> ErrMsg<T> for Result<T, E> {
fn with_err_msg(self, val: String) -> Result<T, String> {
match self {
Ok(val) => Ok(val),
Err(err) => Err(format!("{}; original={}", val, err))
}
}
}
// Path to cargo executables
pub fn cargo_dir() -> PathBuf {
env::var_os("CARGO_BIN_PATH").map(PathBuf::from).or_else(|| {
env::current_exe().ok().as_ref().and_then(|s| s.parent())
.map(|s| s.to_path_buf())
}).unwrap_or_else(|| {
panic!("CARGO_BIN_PATH wasn't set. Cannot continue running test")
})
}
/// Returns an absolute path in the filesystem that `path` points to. The
/// returned path does not contain any symlinks in its hierarchy.
/*
*
* ===== Matchers =====
*
*/
#[derive(Clone)]
pub struct Execs {
expect_stdout: Option<String>,
expect_stdin: Option<String>,
expect_stderr: Option<String>,
expect_exit_code: Option<i32>,
expect_stdout_contains: Vec<String>,
expect_stderr_contains: Vec<String>,
expect_json: Option<Json>,
}
impl Execs {
pub fn with_stdout<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stdout = Some(expected.to_string());
self
}
pub fn with_stderr<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stderr = Some(expected.to_string());
self
}
pub fn with_status(mut self, expected: i32) -> Execs {
self.expect_exit_code = Some(expected);
self
}
pub fn with_stdout_contains<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stdout_contains.push(expected.to_string());
self
}
pub fn with_stderr_contains<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stderr_contains.push(expected.to_string());
self
}
pub fn with_json(mut self, expected: &str) -> Execs {
self.expect_json = Some(Json::from_str(expected).unwrap());
self
}
fn match_output(&self, actual: &Output) -> ham::MatchResult {
self.match_status(actual)
.and(self.match_stdout(actual))
.and(self.match_stderr(actual))
}
fn match_status(&self, actual: &Output) -> ham::MatchResult {
match self.expect_exit_code {
None => ham::success(),
Some(code) => {
ham::expect(
actual.status.code() == Some(code),
format!("exited with {}\n--- stdout\n{}\n--- stderr\n{}",
actual.status,
String::from_utf8_lossy(&actual.stdout),
String::from_utf8_lossy(&actual.stderr)))
}
}
}
fn match_stdout(&self, actual: &Output) -> ham::MatchResult {
try!(self.match_std(self.expect_stdout.as_ref(), &actual.stdout,
"stdout", &actual.stderr, false));
for expect in self.expect_stdout_contains.iter() {
try!(self.match_std(Some(expect), &actual.stdout, "stdout",
&actual.stderr, true));
}
for expect in self.expect_stderr_contains.iter() {
try!(self.match_std(Some(expect), &actual.stderr, "stderr",
&actual.stdout, true));
}
if let Some(ref expect_json) = self.expect_json {
try!(self.match_json(expect_json, &actual.stdout));
}
Ok(())
}
fn match_stderr(&self, actual: &Output) -> ham::MatchResult {
self.match_std(self.expect_stderr.as_ref(), &actual.stderr,
"stderr", &actual.stdout, false)
}
#[allow(deprecated)] // connect => join in 1.3
fn match_std(&self, expected: Option<&String>, actual: &[u8],
description: &str, extra: &[u8],
partial: bool) -> ham::MatchResult {
let out = match expected {
Some(out) => out,
None => return ham::success(),
};
let actual = match str::from_utf8(actual) {
Err(..) => return Err(format!("{} was not utf8 encoded",
description)),
Ok(actual) => actual,
};
// Let's not deal with \r\n vs \n on windows...
let actual = actual.replace("\r", "");
let actual = actual.replace("\t", "<tab>");
let mut a = actual.lines();
let e = out.lines();
let diffs = if partial {
let mut min = self.diff_lines(a.clone(), e.clone(), partial);
while let Some(..) = a.next() {
let a = self.diff_lines(a.clone(), e.clone(), partial);
if a.len() < min.len() {
min = a;
}
}
min
} else {
self.diff_lines(a, e, partial)
};
ham::expect(diffs.is_empty(),
format!("differences:\n\
{}\n\n\
|
`{}`", diffs.connect("\n"),
String::from_utf8_lossy(extra)))
}
fn match_json(&self, expected: &Json, stdout: &[u8]) -> ham::MatchResult {
let stdout = match str::from_utf8(stdout) {
Err(..) => return Err("stdout was not utf8 encoded".to_owned()),
Ok(stdout) => stdout,
};
let actual = match Json::from_str(stdout) {
Err(..) => return Err(format!("Invalid json {}", stdout)),
Ok(actual) => actual,
};
match find_mismatch(expected, &actual) {
Some((expected_part, actual_part)) => Err(format!(
"JSON mismatch\nExpected:\n{}\nWas:\n{}\nExpected part:\n{}\nActual part:\n{}\n",
expected.pretty(), actual.pretty(),
expected_part.pretty(), actual_part.pretty()
)),
None => Ok(()),
}
}
fn diff_lines<'a>(&self, actual: str::Lines<'a>, expected: str::Lines<'a>,
partial: bool) -> Vec<String> {
let actual = actual.take(if partial {
expected.clone().count()
} else {
usize::MAX
});
zip_all(actual, expected).enumerate().filter_map(|(i, (a,e))| {
match (a, e) {
(Some(a), Some(e)) => {
if lines_match(&e, &a) {
None
} else {
Some(format!("{:3} - |{}|\n + |{}|\n", i, e, a))
}
},
(Some(a), None) => {
Some(format!("{:3} -\n + |{}|\n", i, a))
},
(None, Some(e)) => {
Some(format!("{:3} - |{}|\n +\n", i, e))
},
(None, None) => panic!("Cannot get here")
}
}).collect()
}
}
fn lines_match(expected: &str, mut actual: &str) -> bool {
for part in expected.split("[..]") {
match actual.find(part) {
Some(i) => actual = &actual[i + part.len()..],
None => {
return false
}
}
}
actual.is_empty() || expected.ends_with("[..]")
}
// Compares JSON object for approximate equality.
// You can use `[..]` wildcard in strings (useful for OS dependent things such as paths).
// Arrays are sorted before comparison.
fn find_mismatch<'a>(expected: &'a Json, actual: &'a Json) -> Option<(&'a Json, &'a Json)> {
use rustc_serialize::json::Json::*;
match (expected, actual) {
(&I64(l), &I64(r)) if l == r => None,
(&F64(l), &F64(r)) if l == r => None,
(&U64(l), &U64(r)) if l == r => None,
(&Boolean(l), &Boolean(r)) if l == r => None,
(&String(ref l), &String(ref r)) if lines_match(l, r) => None,
(&Array(ref l), &Array(ref r)) => {
if l.len()!= r.len() {
return Some((expected, actual));
}
fn sorted(xs: &Vec<Json>) -> Vec<&Json> {
let mut result = xs.iter().collect::<Vec<_>>();
// `unwrap` should be safe because JSON spec does not allow NaNs
result.sort_by(|x, y| x.partial_cmp(y).unwrap());
result
}
sorted(l).iter().zip(sorted(r))
.filter_map(|(l, r)| find_mismatch(l, r))
.nth(0)
}
(&Object(ref l), &Object(ref r)) => {
let same_keys = l.len() == r.len() && l.keys().all(|k| r.contains_key(k));
if!same_keys {
return Some((expected, actual));
}
l.values().zip(r.values())
.filter_map(|(l, r)| find_mismatch(l, r))
.nth(0)
}
(&Null, &Null) => None,
_ => Some((expected, actual)),
}
}
struct ZipAll<I1: Iterator, I2: Iterator> {
first: I1,
second: I2,
}
impl<T, I1: Iterator<Item=T>, I2: Iterator<Item=T>> Iterator for ZipAll<I1, I2> {
type Item = (Option<T>, Option<T>);
fn next(&mut self) -> Option<(Option<T>, Option<T>)> {
let first = self.first.next();
let second = self.second.next();
match (first, second) {
(None, None) => None,
(a, b) => Some((a, b))
}
}
}
fn zip_all<T, I1: Iterator<Item=T>, I2: Iterator<Item=T>>(a: I1, b: I2) -> ZipAll<I1, I2> {
ZipAll {
first: a,
second: b,
}
}
impl fmt::Display for Execs {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "execs")
}
}
impl ham::Matcher<ProcessBuilder> for Execs {
fn matches(&self, mut process: ProcessBuilder) -> ham::MatchResult {
self.matches(&mut process)
}
}
impl<'a> ham::Matcher<&'a mut ProcessBuilder> for Execs {
fn matches(&self, process: &'a mut ProcessBuilder) -> ham::MatchResult {
let res = process.exec_with_output();
match res {
Ok(out) => self.match_output(&out),
Err(ProcessError { output: Some(ref out),.. }) => {
self.match_output(out)
}
Err(e) => {
let mut s = format!("could not exec process {}: {}", process, e);
match e.cause() {
Some(cause) => s.push_str(&format!("\ncaused by: {}",
cause.description())),
None => {}
}
Err(s)
}
}
}
}
pub fn execs() -> Execs {
Execs {
expect_stdout: None,
expect_stderr: None,
expect_stdin: None,
expect_exit_code: None,
expect_stdout_contains: Vec::new(),
expect_stderr_contains: Vec::new(),
expect_json: None,
}
}
#[derive(Clone)]
pub struct ShellWrites {
expected: String
}
impl fmt::Display for ShellWrites {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "`{}` written to the shell", self.expected)
}
}
impl<'a> ham::Matcher<&'a [u8]> for ShellWrites {
fn matches(&self, actual: &[u8])
-> ham::MatchResult
{
let actual = String::from_utf8_lossy(actual);
let actual = actual.to_string();
ham::expect(actual == self.expected, actual)
}
}
pub fn shell_writes<T: fmt::Display>(string: T) -> ShellWrites {
ShellWrites { expected
|
other output:\n\
|
random_line_split
|
mod.rs
|
try!(mkdir_recursive(&self.dirname()));
let mut file = try!(
fs::File::create(&self.path)
.with_err_msg(format!("Could not create file; path={}",
self.path.display())));
file.write_all(self.body.as_bytes())
.with_err_msg(format!("Could not write to file; path={}",
self.path.display()))
}
fn dirname(&self) -> &Path {
self.path.parent().unwrap()
}
}
#[derive(PartialEq,Clone)]
struct SymlinkBuilder {
dst: PathBuf,
src: PathBuf,
}
impl SymlinkBuilder {
pub fn new(dst: PathBuf, src: PathBuf) -> SymlinkBuilder {
SymlinkBuilder { dst: dst, src: src }
}
#[cfg(unix)]
fn mk(&self) -> Result<(), String> {
try!(mkdir_recursive(&self.dirname()));
os::unix::fs::symlink(&self.dst, &self.src)
.with_err_msg(format!("Could not create symlink; dst={} src={}",
self.dst.display(), self.src.display()))
}
#[cfg(windows)]
fn mk(&self) -> Result<(), String> {
try!(mkdir_recursive(&self.dirname()));
os::windows::fs::symlink_file(&self.dst, &self.src)
.with_err_msg(format!("Could not create symlink; dst={} src={}",
self.dst.display(), self.src.display()))
}
fn dirname(&self) -> &Path {
self.src.parent().unwrap()
}
}
#[derive(PartialEq,Clone)]
pub struct ProjectBuilder {
name: String,
root: PathBuf,
files: Vec<FileBuilder>,
symlinks: Vec<SymlinkBuilder>
}
impl ProjectBuilder {
pub fn new(name: &str, root: PathBuf) -> ProjectBuilder {
ProjectBuilder {
name: name.to_string(),
root: root,
files: vec![],
symlinks: vec![]
}
}
pub fn root(&self) -> PathBuf {
self.root.clone()
}
pub fn url(&self) -> Url { path2url(self.root()) }
pub fn bin(&self, b: &str) -> PathBuf {
self.build_dir().join("debug").join(&format!("{}{}", b,
env::consts::EXE_SUFFIX))
}
pub fn release_bin(&self, b: &str) -> PathBuf {
self.build_dir().join("release").join(&format!("{}{}", b,
env::consts::EXE_SUFFIX))
}
pub fn target_bin(&self, target: &str, b: &str) -> PathBuf {
self.build_dir().join(target).join("debug")
.join(&format!("{}{}", b, env::consts::EXE_SUFFIX))
}
pub fn build_dir(&self) -> PathBuf {
self.root.join("target")
}
pub fn process<T: AsRef<OsStr>>(&self, program: T) -> ProcessBuilder {
let mut p = ::process(program);
p.cwd(self.root());
return p
}
pub fn cargo(&self, cmd: &str) -> ProcessBuilder {
let mut p = self.process(&cargo_dir().join("cargo"));
p.arg(cmd);
return p;
}
pub fn cargo_process(&self, cmd: &str) -> ProcessBuilder {
self.build();
self.cargo(cmd)
}
pub fn file<B: AsRef<Path>>(mut self, path: B,
body: &str) -> ProjectBuilder {
self.files.push(FileBuilder::new(self.root.join(path), body));
self
}
pub fn symlink<T: AsRef<Path>>(mut self, dst: T,
src: T) -> ProjectBuilder {
self.symlinks.push(SymlinkBuilder::new(self.root.join(dst),
self.root.join(src)));
self
}
// TODO: return something different than a ProjectBuilder
pub fn build(&self) -> &ProjectBuilder {
match self.build_with_result() {
Err(e) => panic!(e),
_ => return self
}
}
pub fn build_with_result(&self) -> Result<(), String> {
// First, clean the directory if it already exists
try!(self.rm_root());
// Create the empty directory
try!(mkdir_recursive(&self.root));
for file in self.files.iter() {
try!(file.mk());
}
for symlink in self.symlinks.iter() {
try!(symlink.mk());
}
Ok(())
}
fn rm_root(&self) -> Result<(), String> {
if self.root.c_exists() {
rmdir_recursive(&self.root)
} else {
Ok(())
}
}
}
// Generates a project layout
pub fn project(name: &str) -> ProjectBuilder {
ProjectBuilder::new(name, paths::root().join(name))
}
// === Helpers ===
pub fn mkdir_recursive(path: &Path) -> Result<(), String> {
fs::create_dir_all(path)
.with_err_msg(format!("could not create directory; path={}",
path.display()))
}
pub fn rmdir_recursive(path: &Path) -> Result<(), String> {
path.rm_rf()
.with_err_msg(format!("could not rm directory; path={}",
path.display()))
}
pub fn main_file(println: &str, deps: &[&str]) -> String {
let mut buf = String::new();
for dep in deps.iter() {
buf.push_str(&format!("extern crate {};\n", dep));
}
buf.push_str("fn main() { println!(");
buf.push_str(&println);
buf.push_str("); }\n");
buf.to_string()
}
trait ErrMsg<T> {
fn with_err_msg(self, val: String) -> Result<T, String>;
}
impl<T, E: fmt::Display> ErrMsg<T> for Result<T, E> {
fn with_err_msg(self, val: String) -> Result<T, String> {
match self {
Ok(val) => Ok(val),
Err(err) => Err(format!("{}; original={}", val, err))
}
}
}
// Path to cargo executables
pub fn cargo_dir() -> PathBuf {
env::var_os("CARGO_BIN_PATH").map(PathBuf::from).or_else(|| {
env::current_exe().ok().as_ref().and_then(|s| s.parent())
.map(|s| s.to_path_buf())
}).unwrap_or_else(|| {
panic!("CARGO_BIN_PATH wasn't set. Cannot continue running test")
})
}
/// Returns an absolute path in the filesystem that `path` points to. The
/// returned path does not contain any symlinks in its hierarchy.
/*
*
* ===== Matchers =====
*
*/
#[derive(Clone)]
pub struct Execs {
expect_stdout: Option<String>,
expect_stdin: Option<String>,
expect_stderr: Option<String>,
expect_exit_code: Option<i32>,
expect_stdout_contains: Vec<String>,
expect_stderr_contains: Vec<String>,
expect_json: Option<Json>,
}
impl Execs {
pub fn with_stdout<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stdout = Some(expected.to_string());
self
}
pub fn with_stderr<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stderr = Some(expected.to_string());
self
}
pub fn with_status(mut self, expected: i32) -> Execs {
self.expect_exit_code = Some(expected);
self
}
pub fn with_stdout_contains<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stdout_contains.push(expected.to_string());
self
}
pub fn with_stderr_contains<S: ToString>(mut self, expected: S) -> Execs {
self.expect_stderr_contains.push(expected.to_string());
self
}
pub fn with_json(mut self, expected: &str) -> Execs {
self.expect_json = Some(Json::from_str(expected).unwrap());
self
}
fn match_output(&self, actual: &Output) -> ham::MatchResult {
self.match_status(actual)
.and(self.match_stdout(actual))
.and(self.match_stderr(actual))
}
fn match_status(&self, actual: &Output) -> ham::MatchResult {
match self.expect_exit_code {
None => ham::success(),
Some(code) => {
ham::expect(
actual.status.code() == Some(code),
format!("exited with {}\n--- stdout\n{}\n--- stderr\n{}",
actual.status,
String::from_utf8_lossy(&actual.stdout),
String::from_utf8_lossy(&actual.stderr)))
}
}
}
fn match_stdout(&self, actual: &Output) -> ham::MatchResult {
try!(self.match_std(self.expect_stdout.as_ref(), &actual.stdout,
"stdout", &actual.stderr, false));
for expect in self.expect_stdout_contains.iter() {
try!(self.match_std(Some(expect), &actual.stdout, "stdout",
&actual.stderr, true));
}
for expect in self.expect_stderr_contains.iter() {
try!(self.match_std(Some(expect), &actual.stderr, "stderr",
&actual.stdout, true));
}
if let Some(ref expect_json) = self.expect_json {
try!(self.match_json(expect_json, &actual.stdout));
}
Ok(())
}
fn match_stderr(&self, actual: &Output) -> ham::MatchResult {
self.match_std(self.expect_stderr.as_ref(), &actual.stderr,
"stderr", &actual.stdout, false)
}
#[allow(deprecated)] // connect => join in 1.3
fn match_std(&self, expected: Option<&String>, actual: &[u8],
description: &str, extra: &[u8],
partial: bool) -> ham::MatchResult {
let out = match expected {
Some(out) => out,
None => return ham::success(),
};
let actual = match str::from_utf8(actual) {
Err(..) => return Err(format!("{} was not utf8 encoded",
description)),
Ok(actual) => actual,
};
// Let's not deal with \r\n vs \n on windows...
let actual = actual.replace("\r", "");
let actual = actual.replace("\t", "<tab>");
let mut a = actual.lines();
let e = out.lines();
let diffs = if partial {
let mut min = self.diff_lines(a.clone(), e.clone(), partial);
while let Some(..) = a.next() {
let a = self.diff_lines(a.clone(), e.clone(), partial);
if a.len() < min.len() {
min = a;
}
}
min
} else {
self.diff_lines(a, e, partial)
};
ham::expect(diffs.is_empty(),
format!("differences:\n\
{}\n\n\
other output:\n\
`{}`", diffs.connect("\n"),
String::from_utf8_lossy(extra)))
}
fn match_json(&self, expected: &Json, stdout: &[u8]) -> ham::MatchResult {
let stdout = match str::from_utf8(stdout) {
Err(..) => return Err("stdout was not utf8 encoded".to_owned()),
Ok(stdout) => stdout,
};
let actual = match Json::from_str(stdout) {
Err(..) => return Err(format!("Invalid json {}", stdout)),
Ok(actual) => actual,
};
match find_mismatch(expected, &actual) {
Some((expected_part, actual_part)) => Err(format!(
"JSON mismatch\nExpected:\n{}\nWas:\n{}\nExpected part:\n{}\nActual part:\n{}\n",
expected.pretty(), actual.pretty(),
expected_part.pretty(), actual_part.pretty()
)),
None => Ok(()),
}
}
fn diff_lines<'a>(&self, actual: str::Lines<'a>, expected: str::Lines<'a>,
partial: bool) -> Vec<String> {
let actual = actual.take(if partial {
expected.clone().count()
} else {
usize::MAX
});
zip_all(actual, expected).enumerate().filter_map(|(i, (a,e))| {
match (a, e) {
(Some(a), Some(e)) => {
if lines_match(&e, &a) {
None
} else {
Some(format!("{:3} - |{}|\n + |{}|\n", i, e, a))
}
},
(Some(a), None) => {
Some(format!("{:3} -\n + |{}|\n", i, a))
},
(None, Some(e)) => {
Some(format!("{:3} - |{}|\n +\n", i, e))
},
(None, None) => panic!("Cannot get here")
}
}).collect()
}
}
fn lines_match(expected: &str, mut actual: &str) -> bool {
for part in expected.split("[..]") {
match actual.find(part) {
Some(i) => actual = &actual[i + part.len()..],
None => {
return false
}
}
}
actual.is_empty() || expected.ends_with("[..]")
}
// Compares JSON object for approximate equality.
// You can use `[..]` wildcard in strings (useful for OS dependent things such as paths).
// Arrays are sorted before comparison.
fn find_mismatch<'a>(expected: &'a Json, actual: &'a Json) -> Option<(&'a Json, &'a Json)> {
use rustc_serialize::json::Json::*;
match (expected, actual) {
(&I64(l), &I64(r)) if l == r => None,
(&F64(l), &F64(r)) if l == r => None,
(&U64(l), &U64(r)) if l == r => None,
(&Boolean(l), &Boolean(r)) if l == r => None,
(&String(ref l), &String(ref r)) if lines_match(l, r) => None,
(&Array(ref l), &Array(ref r)) => {
if l.len()!= r.len() {
return Some((expected, actual));
}
fn sorted(xs: &Vec<Json>) -> Vec<&Json> {
let mut result = xs.iter().collect::<Vec<_>>();
// `unwrap` should be safe because JSON spec does not allow NaNs
result.sort_by(|x, y| x.partial_cmp(y).unwrap());
result
}
sorted(l).iter().zip(sorted(r))
.filter_map(|(l, r)| find_mismatch(l, r))
.nth(0)
}
(&Object(ref l), &Object(ref r)) => {
let same_keys = l.len() == r.len() && l.keys().all(|k| r.contains_key(k));
if!same_keys {
return Some((expected, actual));
}
l.values().zip(r.values())
.filter_map(|(l, r)| find_mismatch(l, r))
.nth(0)
}
(&Null, &Null) => None,
_ => Some((expected, actual)),
}
}
struct ZipAll<I1: Iterator, I2: Iterator> {
first: I1,
second: I2,
}
impl<T, I1: Iterator<Item=T>, I2: Iterator<Item=T>> Iterator for ZipAll<I1, I2> {
type Item = (Option<T>, Option<T>);
fn next(&mut self) -> Option<(Option<T>, Option<T>)> {
let first = self.first.next();
let second = self.second.next();
match (first, second) {
(None, None) => None,
(a, b) => Some((a, b))
}
}
}
fn zip_all<T, I1: Iterator<Item=T>, I2: Iterator<Item=T>>(a: I1, b: I2) -> ZipAll<I1, I2> {
ZipAll {
first: a,
second: b,
}
}
impl fmt::Display for Execs {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "execs")
}
}
impl ham::Matcher<ProcessBuilder> for Execs {
fn matches(&self, mut process: ProcessBuilder) -> ham::MatchResult {
self.matches(&mut process)
}
}
impl<'a> ham::Matcher<&'a mut ProcessBuilder> for Execs {
fn matches(&self, process: &'a mut ProcessBuilder) -> ham::MatchResult {
let res = process.exec_with_output();
match res {
Ok(out) => self.match_output(&out),
Err(ProcessError { output: Some(ref out),.. }) => {
self.match_output(out)
}
Err(e) => {
let mut s = format!("could not exec process {}: {}", process, e);
match e.cause() {
Some(cause) => s.push_str(&format!("\ncaused by: {}",
cause.description())),
None => {}
}
Err(s)
}
}
}
}
pub fn execs() -> Execs {
Execs {
expect_stdout: None,
expect_stderr: None,
expect_stdin: None,
expect_exit_code: None,
expect_stdout_contains: Vec::new(),
expect_stderr_contains: Vec::new(),
expect_json: None,
}
}
#[derive(Clone)]
pub struct ShellWrites {
expected: String
}
impl fmt::Display for ShellWrites {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "`{}` written to the shell", self.expected)
}
}
impl<'a> ham::Matcher<&'a [u8]> for ShellWrites {
fn matches(&self, actual: &[u8])
-> ham::MatchResult
|
}
pub fn shell_writes<T: fmt::Display>(string: T) -> ShellWrites {
ShellWrites {
|
{
let actual = String::from_utf8_lossy(actual);
let actual = actual.to_string();
ham::expect(actual == self.expected, actual)
}
|
identifier_body
|
commands.rs
|
use std::string::String;
use regex::Regex;
use platform::EOL;
use REHolder;
pub fn show_help() -> String {
"This is help page.".to_string() + EOL.as_ref() +
"Or at leas will be....".as_ref()
}
pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String {
current_re.set(Regex::new(regex).unwrap());
format!("Regex was set: {}\n", regex)
}
pub fn
|
(input: &str, current_re: &REHolder) -> String {
if!current_re.re.is_match(input) {
return "Input does not match the pattern. ".to_string();
}
let mut output = String::new();
for (ind, cap) in current_re.re.captures_iter(input).enumerate() {
if ind > 0 {
output += format!("==========={}", EOL).as_ref();
}
output += format!(">>> Match #{}, capture groups: {}", ind + 1, EOL).as_ref();
for c_ind in 0..cap.len() {
let cg = cap.get(c_ind).unwrap();
output += format!(">>> <{}>: {}{}", c_ind, cg.as_str(), EOL).as_ref();
}
}
output
}
pub fn default_command() -> String {
"No such command was found. Type 'help' to show help page.".to_string()
}
|
test_input
|
identifier_name
|
commands.rs
|
use std::string::String;
use regex::Regex;
use platform::EOL;
use REHolder;
pub fn show_help() -> String {
"This is help page.".to_string() + EOL.as_ref() +
"Or at leas will be....".as_ref()
}
pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String {
current_re.set(Regex::new(regex).unwrap());
format!("Regex was set: {}\n", regex)
}
pub fn test_input(input: &str, current_re: &REHolder) -> String {
if!current_re.re.is_match(input)
|
let mut output = String::new();
for (ind, cap) in current_re.re.captures_iter(input).enumerate() {
if ind > 0 {
output += format!("==========={}", EOL).as_ref();
}
output += format!(">>> Match #{}, capture groups: {}", ind + 1, EOL).as_ref();
for c_ind in 0..cap.len() {
let cg = cap.get(c_ind).unwrap();
output += format!(">>> <{}>: {}{}", c_ind, cg.as_str(), EOL).as_ref();
}
}
output
}
pub fn default_command() -> String {
"No such command was found. Type 'help' to show help page.".to_string()
}
|
{
return "Input does not match the pattern. ".to_string();
}
|
conditional_block
|
commands.rs
|
use std::string::String;
use regex::Regex;
use platform::EOL;
use REHolder;
pub fn show_help() -> String {
"This is help page.".to_string() + EOL.as_ref() +
|
current_re.set(Regex::new(regex).unwrap());
format!("Regex was set: {}\n", regex)
}
pub fn test_input(input: &str, current_re: &REHolder) -> String {
if!current_re.re.is_match(input) {
return "Input does not match the pattern. ".to_string();
}
let mut output = String::new();
for (ind, cap) in current_re.re.captures_iter(input).enumerate() {
if ind > 0 {
output += format!("==========={}", EOL).as_ref();
}
output += format!(">>> Match #{}, capture groups: {}", ind + 1, EOL).as_ref();
for c_ind in 0..cap.len() {
let cg = cap.get(c_ind).unwrap();
output += format!(">>> <{}>: {}{}", c_ind, cg.as_str(), EOL).as_ref();
}
}
output
}
pub fn default_command() -> String {
"No such command was found. Type 'help' to show help page.".to_string()
}
|
"Or at leas will be....".as_ref()
}
pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String {
|
random_line_split
|
commands.rs
|
use std::string::String;
use regex::Regex;
use platform::EOL;
use REHolder;
pub fn show_help() -> String {
"This is help page.".to_string() + EOL.as_ref() +
"Or at leas will be....".as_ref()
}
pub fn set_regex(regex: &str, current_re: &mut REHolder) -> String
|
pub fn test_input(input: &str, current_re: &REHolder) -> String {
if!current_re.re.is_match(input) {
return "Input does not match the pattern. ".to_string();
}
let mut output = String::new();
for (ind, cap) in current_re.re.captures_iter(input).enumerate() {
if ind > 0 {
output += format!("==========={}", EOL).as_ref();
}
output += format!(">>> Match #{}, capture groups: {}", ind + 1, EOL).as_ref();
for c_ind in 0..cap.len() {
let cg = cap.get(c_ind).unwrap();
output += format!(">>> <{}>: {}{}", c_ind, cg.as_str(), EOL).as_ref();
}
}
output
}
pub fn default_command() -> String {
"No such command was found. Type 'help' to show help page.".to_string()
}
|
{
current_re.set(Regex::new(regex).unwrap());
format!("Regex was set: {}\n", regex)
}
|
identifier_body
|
read_manifest.rs
|
use std::env;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Print a JSON representation of a Cargo.toml manifest
|
Options:
-h, --help Print this message
-v, --verbose Use verbose output
--manifest-path PATH Path to the manifest
--color WHEN Coloring: auto, always, never
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<Package>> {
debug!("executing; cmd=cargo-read-manifest; args={:?}",
env::args().collect::<Vec<_>>());
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(options.flag_manifest_path, config.cwd()));
let mut source = try!(PathSource::for_path(root.parent().unwrap(), config));
try!(source.update());
let pkg = try!(source.root_package());
Ok(Some(pkg))
}
|
Usage:
cargo read-manifest [options]
cargo read-manifest -h | --help
|
random_line_split
|
read_manifest.rs
|
use std::env;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct Options {
flag_manifest_path: Option<String>,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Print a JSON representation of a Cargo.toml manifest
Usage:
cargo read-manifest [options]
cargo read-manifest -h | --help
Options:
-h, --help Print this message
-v, --verbose Use verbose output
--manifest-path PATH Path to the manifest
--color WHEN Coloring: auto, always, never
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<Package>>
|
{
debug!("executing; cmd=cargo-read-manifest; args={:?}",
env::args().collect::<Vec<_>>());
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(options.flag_manifest_path, config.cwd()));
let mut source = try!(PathSource::for_path(root.parent().unwrap(), config));
try!(source.update());
let pkg = try!(source.root_package());
Ok(Some(pkg))
}
|
identifier_body
|
|
read_manifest.rs
|
use std::env;
use cargo::core::{Package, Source};
use cargo::util::{CliResult, Config};
use cargo::util::important_paths::{find_root_manifest_for_wd};
use cargo::sources::{PathSource};
#[derive(RustcDecodable)]
struct
|
{
flag_manifest_path: Option<String>,
flag_color: Option<String>,
}
pub const USAGE: &'static str = "
Print a JSON representation of a Cargo.toml manifest
Usage:
cargo read-manifest [options]
cargo read-manifest -h | --help
Options:
-h, --help Print this message
-v, --verbose Use verbose output
--manifest-path PATH Path to the manifest
--color WHEN Coloring: auto, always, never
";
pub fn execute(options: Options, config: &Config) -> CliResult<Option<Package>> {
debug!("executing; cmd=cargo-read-manifest; args={:?}",
env::args().collect::<Vec<_>>());
try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..])));
let root = try!(find_root_manifest_for_wd(options.flag_manifest_path, config.cwd()));
let mut source = try!(PathSource::for_path(root.parent().unwrap(), config));
try!(source.update());
let pkg = try!(source.root_package());
Ok(Some(pkg))
}
|
Options
|
identifier_name
|
coreutils.rs
|
// This file is part of the uutils coreutils package.
//
// (c) Michael Gehring <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use clap::{App, Arg};
use clap_complete::Shell;
use std::cmp;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;
use uucore::display::Quotable;
const VERSION: &str = env!("CARGO_PKG_VERSION");
include!(concat!(env!("OUT_DIR"), "/uutils_map.rs"));
fn usage<T>(utils: &UtilityMap<T>, name: &str) {
println!("{} {} (multi-call binary)\n", name, VERSION);
println!("Usage: {} [function [arguments...]]\n", name);
println!("Currently defined functions:\n");
#[allow(clippy::map_clone)]
let mut utils: Vec<&str> = utils.keys().map(|&s| s).collect();
utils.sort_unstable();
let display_list = utils.join(", ");
let width = cmp::min(textwrap::termwidth(), 100) - 4 * 2; // (opinion/heuristic) max 100 chars wide with 4 character side indentions
println!(
"{}",
textwrap::indent(&textwrap::fill(&display_list, width), " ")
);
}
fn binary_path(args: &mut impl Iterator<Item = OsString>) -> PathBuf {
match args.next() {
Some(ref s) if!s.is_empty() => PathBuf::from(s),
_ => std::env::current_exe().unwrap(),
}
}
fn name(binary_path: &Path) -> &str {
binary_path.file_stem().unwrap().to_str().unwrap()
}
fn main() {
uucore::panic::mute_sigpipe_panic();
let utils = util_map();
let mut args = uucore::args_os();
let binary = binary_path(&mut args);
let binary_as_util = name(&binary);
// binary name equals util name?
if let Some(&(uumain, _)) = utils.get(binary_as_util) {
process::exit(uumain((vec![binary.into()].into_iter()).chain(args)));
}
// binary name equals prefixed util name?
// * prefix/stem may be any string ending in a non-alphanumeric character
let util_name = if let Some(util) = utils.keys().find(|util| {
binary_as_util.ends_with(*util)
&&!binary_as_util[..binary_as_util.len() - (*util).len()]
.ends_with(char::is_alphanumeric)
}) {
// prefixed util => replace 0th (aka, executable name) argument
Some(OsString::from(*util))
} else
|
;
// 0th argument equals util name?
if let Some(util_os) = util_name {
fn not_found(util: &OsStr) ->! {
println!("{}: function/utility not found", util.maybe_quote());
process::exit(1);
}
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
if util == "completion" {
gen_completions(args, &utils);
}
match utils.get(util) {
Some(&(uumain, _)) => {
process::exit(uumain((vec![util_os].into_iter()).chain(args)));
}
None => {
if util == "--help" || util == "-h" {
// see if they want help on a specific util
if let Some(util_os) = args.next() {
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
match utils.get(util) {
Some(&(uumain, _)) => {
let code = uumain(
(vec![util_os, OsString::from("--help")].into_iter())
.chain(args),
);
io::stdout().flush().expect("could not flush stdout");
process::exit(code);
}
None => not_found(&util_os),
}
}
usage(&utils, binary_as_util);
process::exit(0);
} else {
not_found(&util_os);
}
}
}
} else {
// no arguments provided
usage(&utils, binary_as_util);
process::exit(0);
}
}
/// Prints completions for the utility in the first parameter for the shell in the second parameter to stdout
fn gen_completions<T: uucore::Args>(
args: impl Iterator<Item = OsString>,
util_map: &UtilityMap<T>,
) ->! {
let all_utilities: Vec<_> = std::iter::once("coreutils")
.chain(util_map.keys().copied())
.collect();
let matches = App::new("completion")
.about("Prints completions to stdout")
.arg(
Arg::new("utility")
.possible_values(all_utilities)
.required(true),
)
.arg(
Arg::new("shell")
.possible_values(Shell::possible_values())
.required(true),
)
.get_matches_from(std::iter::once(OsString::from("completion")).chain(args));
let utility = matches.value_of("utility").unwrap();
let shell = matches.value_of("shell").unwrap();
let mut app = if utility == "coreutils" {
gen_coreutils_app(util_map)
} else {
util_map.get(utility).unwrap().1()
};
let shell: Shell = shell.parse().unwrap();
let bin_name = std::env::var("PROG_PREFIX").unwrap_or_default() + utility;
clap_complete::generate(shell, &mut app, bin_name, &mut io::stdout());
io::stdout().flush().unwrap();
process::exit(0);
}
fn gen_coreutils_app<T: uucore::Args>(util_map: &UtilityMap<T>) -> App<'static> {
let mut app = App::new("coreutils");
for (_, (_, sub_app)) in util_map {
app = app.subcommand(sub_app());
}
app
}
|
{
// unmatched binary name => regard as multi-binary container and advance argument list
uucore::set_utility_is_second_arg();
args.next()
}
|
conditional_block
|
coreutils.rs
|
// This file is part of the uutils coreutils package.
//
// (c) Michael Gehring <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use clap::{App, Arg};
use clap_complete::Shell;
use std::cmp;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;
use uucore::display::Quotable;
const VERSION: &str = env!("CARGO_PKG_VERSION");
include!(concat!(env!("OUT_DIR"), "/uutils_map.rs"));
fn usage<T>(utils: &UtilityMap<T>, name: &str) {
println!("{} {} (multi-call binary)\n", name, VERSION);
println!("Usage: {} [function [arguments...]]\n", name);
println!("Currently defined functions:\n");
#[allow(clippy::map_clone)]
let mut utils: Vec<&str> = utils.keys().map(|&s| s).collect();
utils.sort_unstable();
let display_list = utils.join(", ");
let width = cmp::min(textwrap::termwidth(), 100) - 4 * 2; // (opinion/heuristic) max 100 chars wide with 4 character side indentions
println!(
"{}",
textwrap::indent(&textwrap::fill(&display_list, width), " ")
);
}
fn binary_path(args: &mut impl Iterator<Item = OsString>) -> PathBuf {
match args.next() {
Some(ref s) if!s.is_empty() => PathBuf::from(s),
_ => std::env::current_exe().unwrap(),
}
}
fn name(binary_path: &Path) -> &str {
binary_path.file_stem().unwrap().to_str().unwrap()
}
fn main() {
uucore::panic::mute_sigpipe_panic();
let utils = util_map();
let mut args = uucore::args_os();
let binary = binary_path(&mut args);
let binary_as_util = name(&binary);
// binary name equals util name?
if let Some(&(uumain, _)) = utils.get(binary_as_util) {
process::exit(uumain((vec![binary.into()].into_iter()).chain(args)));
}
// binary name equals prefixed util name?
// * prefix/stem may be any string ending in a non-alphanumeric character
let util_name = if let Some(util) = utils.keys().find(|util| {
binary_as_util.ends_with(*util)
&&!binary_as_util[..binary_as_util.len() - (*util).len()]
.ends_with(char::is_alphanumeric)
}) {
// prefixed util => replace 0th (aka, executable name) argument
Some(OsString::from(*util))
} else {
// unmatched binary name => regard as multi-binary container and advance argument list
uucore::set_utility_is_second_arg();
args.next()
};
// 0th argument equals util name?
if let Some(util_os) = util_name {
fn not_found(util: &OsStr) ->!
|
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
if util == "completion" {
gen_completions(args, &utils);
}
match utils.get(util) {
Some(&(uumain, _)) => {
process::exit(uumain((vec![util_os].into_iter()).chain(args)));
}
None => {
if util == "--help" || util == "-h" {
// see if they want help on a specific util
if let Some(util_os) = args.next() {
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
match utils.get(util) {
Some(&(uumain, _)) => {
let code = uumain(
(vec![util_os, OsString::from("--help")].into_iter())
.chain(args),
);
io::stdout().flush().expect("could not flush stdout");
process::exit(code);
}
None => not_found(&util_os),
}
}
usage(&utils, binary_as_util);
process::exit(0);
} else {
not_found(&util_os);
}
}
}
} else {
// no arguments provided
usage(&utils, binary_as_util);
process::exit(0);
}
}
/// Prints completions for the utility in the first parameter for the shell in the second parameter to stdout
fn gen_completions<T: uucore::Args>(
args: impl Iterator<Item = OsString>,
util_map: &UtilityMap<T>,
) ->! {
let all_utilities: Vec<_> = std::iter::once("coreutils")
.chain(util_map.keys().copied())
.collect();
let matches = App::new("completion")
.about("Prints completions to stdout")
.arg(
Arg::new("utility")
.possible_values(all_utilities)
.required(true),
)
.arg(
Arg::new("shell")
.possible_values(Shell::possible_values())
.required(true),
)
.get_matches_from(std::iter::once(OsString::from("completion")).chain(args));
let utility = matches.value_of("utility").unwrap();
let shell = matches.value_of("shell").unwrap();
let mut app = if utility == "coreutils" {
gen_coreutils_app(util_map)
} else {
util_map.get(utility).unwrap().1()
};
let shell: Shell = shell.parse().unwrap();
let bin_name = std::env::var("PROG_PREFIX").unwrap_or_default() + utility;
clap_complete::generate(shell, &mut app, bin_name, &mut io::stdout());
io::stdout().flush().unwrap();
process::exit(0);
}
fn gen_coreutils_app<T: uucore::Args>(util_map: &UtilityMap<T>) -> App<'static> {
let mut app = App::new("coreutils");
for (_, (_, sub_app)) in util_map {
app = app.subcommand(sub_app());
}
app
}
|
{
println!("{}: function/utility not found", util.maybe_quote());
process::exit(1);
}
|
identifier_body
|
coreutils.rs
|
// This file is part of the uutils coreutils package.
//
// (c) Michael Gehring <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use clap::{App, Arg};
use clap_complete::Shell;
use std::cmp;
use std::ffi::OsStr;
|
use std::process;
use uucore::display::Quotable;
const VERSION: &str = env!("CARGO_PKG_VERSION");
include!(concat!(env!("OUT_DIR"), "/uutils_map.rs"));
fn usage<T>(utils: &UtilityMap<T>, name: &str) {
println!("{} {} (multi-call binary)\n", name, VERSION);
println!("Usage: {} [function [arguments...]]\n", name);
println!("Currently defined functions:\n");
#[allow(clippy::map_clone)]
let mut utils: Vec<&str> = utils.keys().map(|&s| s).collect();
utils.sort_unstable();
let display_list = utils.join(", ");
let width = cmp::min(textwrap::termwidth(), 100) - 4 * 2; // (opinion/heuristic) max 100 chars wide with 4 character side indentions
println!(
"{}",
textwrap::indent(&textwrap::fill(&display_list, width), " ")
);
}
fn binary_path(args: &mut impl Iterator<Item = OsString>) -> PathBuf {
match args.next() {
Some(ref s) if!s.is_empty() => PathBuf::from(s),
_ => std::env::current_exe().unwrap(),
}
}
fn name(binary_path: &Path) -> &str {
binary_path.file_stem().unwrap().to_str().unwrap()
}
fn main() {
uucore::panic::mute_sigpipe_panic();
let utils = util_map();
let mut args = uucore::args_os();
let binary = binary_path(&mut args);
let binary_as_util = name(&binary);
// binary name equals util name?
if let Some(&(uumain, _)) = utils.get(binary_as_util) {
process::exit(uumain((vec![binary.into()].into_iter()).chain(args)));
}
// binary name equals prefixed util name?
// * prefix/stem may be any string ending in a non-alphanumeric character
let util_name = if let Some(util) = utils.keys().find(|util| {
binary_as_util.ends_with(*util)
&&!binary_as_util[..binary_as_util.len() - (*util).len()]
.ends_with(char::is_alphanumeric)
}) {
// prefixed util => replace 0th (aka, executable name) argument
Some(OsString::from(*util))
} else {
// unmatched binary name => regard as multi-binary container and advance argument list
uucore::set_utility_is_second_arg();
args.next()
};
// 0th argument equals util name?
if let Some(util_os) = util_name {
fn not_found(util: &OsStr) ->! {
println!("{}: function/utility not found", util.maybe_quote());
process::exit(1);
}
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
if util == "completion" {
gen_completions(args, &utils);
}
match utils.get(util) {
Some(&(uumain, _)) => {
process::exit(uumain((vec![util_os].into_iter()).chain(args)));
}
None => {
if util == "--help" || util == "-h" {
// see if they want help on a specific util
if let Some(util_os) = args.next() {
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
match utils.get(util) {
Some(&(uumain, _)) => {
let code = uumain(
(vec![util_os, OsString::from("--help")].into_iter())
.chain(args),
);
io::stdout().flush().expect("could not flush stdout");
process::exit(code);
}
None => not_found(&util_os),
}
}
usage(&utils, binary_as_util);
process::exit(0);
} else {
not_found(&util_os);
}
}
}
} else {
// no arguments provided
usage(&utils, binary_as_util);
process::exit(0);
}
}
/// Prints completions for the utility in the first parameter for the shell in the second parameter to stdout
fn gen_completions<T: uucore::Args>(
args: impl Iterator<Item = OsString>,
util_map: &UtilityMap<T>,
) ->! {
let all_utilities: Vec<_> = std::iter::once("coreutils")
.chain(util_map.keys().copied())
.collect();
let matches = App::new("completion")
.about("Prints completions to stdout")
.arg(
Arg::new("utility")
.possible_values(all_utilities)
.required(true),
)
.arg(
Arg::new("shell")
.possible_values(Shell::possible_values())
.required(true),
)
.get_matches_from(std::iter::once(OsString::from("completion")).chain(args));
let utility = matches.value_of("utility").unwrap();
let shell = matches.value_of("shell").unwrap();
let mut app = if utility == "coreutils" {
gen_coreutils_app(util_map)
} else {
util_map.get(utility).unwrap().1()
};
let shell: Shell = shell.parse().unwrap();
let bin_name = std::env::var("PROG_PREFIX").unwrap_or_default() + utility;
clap_complete::generate(shell, &mut app, bin_name, &mut io::stdout());
io::stdout().flush().unwrap();
process::exit(0);
}
fn gen_coreutils_app<T: uucore::Args>(util_map: &UtilityMap<T>) -> App<'static> {
let mut app = App::new("coreutils");
for (_, (_, sub_app)) in util_map {
app = app.subcommand(sub_app());
}
app
}
|
use std::ffi::OsString;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
|
random_line_split
|
coreutils.rs
|
// This file is part of the uutils coreutils package.
//
// (c) Michael Gehring <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
use clap::{App, Arg};
use clap_complete::Shell;
use std::cmp;
use std::ffi::OsStr;
use std::ffi::OsString;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process;
use uucore::display::Quotable;
const VERSION: &str = env!("CARGO_PKG_VERSION");
include!(concat!(env!("OUT_DIR"), "/uutils_map.rs"));
fn usage<T>(utils: &UtilityMap<T>, name: &str) {
println!("{} {} (multi-call binary)\n", name, VERSION);
println!("Usage: {} [function [arguments...]]\n", name);
println!("Currently defined functions:\n");
#[allow(clippy::map_clone)]
let mut utils: Vec<&str> = utils.keys().map(|&s| s).collect();
utils.sort_unstable();
let display_list = utils.join(", ");
let width = cmp::min(textwrap::termwidth(), 100) - 4 * 2; // (opinion/heuristic) max 100 chars wide with 4 character side indentions
println!(
"{}",
textwrap::indent(&textwrap::fill(&display_list, width), " ")
);
}
fn binary_path(args: &mut impl Iterator<Item = OsString>) -> PathBuf {
match args.next() {
Some(ref s) if!s.is_empty() => PathBuf::from(s),
_ => std::env::current_exe().unwrap(),
}
}
fn name(binary_path: &Path) -> &str {
binary_path.file_stem().unwrap().to_str().unwrap()
}
fn
|
() {
uucore::panic::mute_sigpipe_panic();
let utils = util_map();
let mut args = uucore::args_os();
let binary = binary_path(&mut args);
let binary_as_util = name(&binary);
// binary name equals util name?
if let Some(&(uumain, _)) = utils.get(binary_as_util) {
process::exit(uumain((vec![binary.into()].into_iter()).chain(args)));
}
// binary name equals prefixed util name?
// * prefix/stem may be any string ending in a non-alphanumeric character
let util_name = if let Some(util) = utils.keys().find(|util| {
binary_as_util.ends_with(*util)
&&!binary_as_util[..binary_as_util.len() - (*util).len()]
.ends_with(char::is_alphanumeric)
}) {
// prefixed util => replace 0th (aka, executable name) argument
Some(OsString::from(*util))
} else {
// unmatched binary name => regard as multi-binary container and advance argument list
uucore::set_utility_is_second_arg();
args.next()
};
// 0th argument equals util name?
if let Some(util_os) = util_name {
fn not_found(util: &OsStr) ->! {
println!("{}: function/utility not found", util.maybe_quote());
process::exit(1);
}
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
if util == "completion" {
gen_completions(args, &utils);
}
match utils.get(util) {
Some(&(uumain, _)) => {
process::exit(uumain((vec![util_os].into_iter()).chain(args)));
}
None => {
if util == "--help" || util == "-h" {
// see if they want help on a specific util
if let Some(util_os) = args.next() {
let util = match util_os.to_str() {
Some(util) => util,
None => not_found(&util_os),
};
match utils.get(util) {
Some(&(uumain, _)) => {
let code = uumain(
(vec![util_os, OsString::from("--help")].into_iter())
.chain(args),
);
io::stdout().flush().expect("could not flush stdout");
process::exit(code);
}
None => not_found(&util_os),
}
}
usage(&utils, binary_as_util);
process::exit(0);
} else {
not_found(&util_os);
}
}
}
} else {
// no arguments provided
usage(&utils, binary_as_util);
process::exit(0);
}
}
/// Prints completions for the utility in the first parameter for the shell in the second parameter to stdout
fn gen_completions<T: uucore::Args>(
args: impl Iterator<Item = OsString>,
util_map: &UtilityMap<T>,
) ->! {
let all_utilities: Vec<_> = std::iter::once("coreutils")
.chain(util_map.keys().copied())
.collect();
let matches = App::new("completion")
.about("Prints completions to stdout")
.arg(
Arg::new("utility")
.possible_values(all_utilities)
.required(true),
)
.arg(
Arg::new("shell")
.possible_values(Shell::possible_values())
.required(true),
)
.get_matches_from(std::iter::once(OsString::from("completion")).chain(args));
let utility = matches.value_of("utility").unwrap();
let shell = matches.value_of("shell").unwrap();
let mut app = if utility == "coreutils" {
gen_coreutils_app(util_map)
} else {
util_map.get(utility).unwrap().1()
};
let shell: Shell = shell.parse().unwrap();
let bin_name = std::env::var("PROG_PREFIX").unwrap_or_default() + utility;
clap_complete::generate(shell, &mut app, bin_name, &mut io::stdout());
io::stdout().flush().unwrap();
process::exit(0);
}
fn gen_coreutils_app<T: uucore::Args>(util_map: &UtilityMap<T>) -> App<'static> {
let mut app = App::new("coreutils");
for (_, (_, sub_app)) in util_map {
app = app.subcommand(sub_app());
}
app
}
|
main
|
identifier_name
|
packet.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//! Just enough packet building to convert Eve payload's into a packet.
//!
//! TODO: Ipv6
use bytes::{Buf, BufMut, BytesMut};
use std::net::Ipv4Addr;
#[derive(Debug, Clone)]
pub enum Protocol {
Tcp,
Udp,
Other(u8),
}
impl Protocol {
pub fn from_name(proto: &str) -> Option<Protocol> {
let proto = proto.to_lowercase();
match proto.as_str() {
"tcp" => Some(Self::Tcp),
"udp" => Some(Self::Udp),
_ => None,
}
}
}
impl From<Protocol> for u8 {
fn from(p: Protocol) -> Self {
match p {
Protocol::Tcp => 6,
Protocol::Udp => 17,
Protocol::Other(n) => n,
}
}
}
pub struct UdpBuilder {
source_port: u16,
destination_port: u16,
payload: Option<Vec<u8>>,
}
impl UdpBuilder {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
destination_port,
payload: None,
}
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = Some(payload);
self
}
pub fn build(self) -> Vec<u8> {
let payload = self.payload.unwrap_or_default();
let mut buf = BytesMut::new();
buf.put_u16(self.source_port);
buf.put_u16(self.destination_port);
buf.put_u16(8 + payload.len() as u16);
buf.put_u16(0);
buf.extend_from_slice(&payload);
let udp_buf = buf.to_vec();
return udp_buf;
}
}
pub struct TcpBuilder {
source_port: u16,
destination_port: u16,
payload: Vec<u8>,
}
|
destination_port,
payload: vec![],
}
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = payload;
self
}
pub fn build(self) -> Vec<u8> {
let mut buf = BytesMut::new();
buf.put_u16(self.source_port);
buf.put_u16(self.destination_port);
buf.put_u32(0); // Sequence number
buf.put_u32(0); // Acknowledgement number
let flags = 5 << 12;
buf.put_u16(flags);
buf.put_u16(1024); // Window size
buf.put_u16(0); // Checksum
buf.put_u16(0); // Urgent pointer
buf.extend_from_slice(&self.payload);
return buf.to_vec();
}
}
pub struct Ip4Builder {
source_addr: Ipv4Addr,
dest_addr: Ipv4Addr,
protocol: Protocol,
ttl: u8,
payload: Vec<u8>,
}
impl Default for Ip4Builder {
fn default() -> Self {
Self::new()
}
}
impl Ip4Builder {
pub fn new() -> Self {
Self {
source_addr: Ipv4Addr::new(0, 0, 0, 0),
dest_addr: Ipv4Addr::new(0, 0, 0, 0),
ttl: 255,
protocol: Protocol::Udp,
payload: vec![],
}
}
pub fn source(mut self, addr: Ipv4Addr) -> Self {
self.source_addr = addr;
self
}
pub fn destination(mut self, addr: Ipv4Addr) -> Self {
self.dest_addr = addr;
self
}
pub fn ttl(mut self, ttl: u8) -> Self {
self.ttl = ttl;
self
}
pub fn protocol(mut self, protocol: Protocol) -> Self {
self.protocol = protocol;
self
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = payload;
self
}
pub fn build(self) -> Vec<u8> {
let mut buf = BytesMut::new();
buf.put_u16(0x4500); // Version(4) + IHL(4) + DSCP + ECN
buf.put_u16(20 + self.payload.len() as u16); // Total length (header + payload)
buf.put_u32(0); // ID(2 bytes), Flags(3 bits), Fragment offset (13 bits)
buf.put_u8(self.ttl);
buf.put_u8(self.protocol.clone().into());
buf.put_u16(0x0000); // Checksum.
buf.extend_from_slice(&self.source_addr.octets());
buf.extend_from_slice(&self.dest_addr.octets());
buf.extend(&self.payload);
let mut out = buf.to_vec();
let csum = &self.ip_checksum(&out);
out[10] = (csum >> 8 & 0xffu16) as u8;
out[11] = (csum & 0xff) as u8;
if let Protocol::Udp = &self.protocol {
let csum = &self.tcpudp_checksum(&out, Protocol::Udp);
out[26] = (csum >> 8 & 0xffu16) as u8;
out[27] = (csum & 0xff) as u8;
} else if let Protocol::Tcp = &self.protocol {
let csum = &self.tcpudp_checksum(&out, Protocol::Tcp);
out[36] = (csum >> 8 & 0xffu16) as u8;
out[37] = (csum & 0xff) as u8;
}
return out;
}
fn ip_checksum(&self, input: &[u8]) -> u16 {
let mut result = 0xffffu32;
let mut hdr = &input[0..20];
while hdr.remaining() > 0 {
result += hdr.get_u16() as u32;
if result > 0xffff {
result -= 0xffff;
}
}
return!result as u16;
}
fn tcpudp_checksum(&self, input: &[u8], proto: Protocol) -> u16 {
let mut result = 0xffffu32;
let mut pseudo = BytesMut::new();
pseudo.extend_from_slice(&input[12..20]);
pseudo.put_u8(0);
pseudo.put_u8(proto.into());
pseudo.put_u16(input.len() as u16 - 20_u16);
while pseudo.remaining() > 0 {
result += pseudo.get_u16() as u32;
if result > 0xffff {
result -= 0xffff;
}
}
let mut pdu = &input[20..];
loop {
let remaining = pdu.remaining();
if remaining == 0 {
break;
}
if remaining == 1 {
result += (pdu.get_u8() as u32) << 8;
} else {
result += pdu.get_u16() as u32;
}
if result > 0xffff {
result -= 0xffff;
}
}
return!result as u16;
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::pcap;
#[test]
fn parse_ip_addr() {
let source: Ipv4Addr = "10.10.10.10".parse().unwrap();
let destination: Ipv4Addr = "127.127.127.127".parse().unwrap();
let tcp = TcpBuilder::new(5555, 6666)
.payload(vec![0x41, 0x41, 0x41, 0x41, 0x41])
.build();
let builder = Ip4Builder::new()
.protocol(Protocol::Tcp)
.source(source)
.destination(destination)
.payload(tcp);
let packet = builder.build();
let now = chrono::Utc::now();
let _pcap_buffer = pcap::create(pcap::LinkType::Raw as u32, now, &packet);
}
}
|
impl TcpBuilder {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
|
random_line_split
|
packet.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//! Just enough packet building to convert Eve payload's into a packet.
//!
//! TODO: Ipv6
use bytes::{Buf, BufMut, BytesMut};
use std::net::Ipv4Addr;
#[derive(Debug, Clone)]
pub enum Protocol {
Tcp,
Udp,
Other(u8),
}
impl Protocol {
pub fn from_name(proto: &str) -> Option<Protocol> {
let proto = proto.to_lowercase();
match proto.as_str() {
"tcp" => Some(Self::Tcp),
"udp" => Some(Self::Udp),
_ => None,
}
}
}
impl From<Protocol> for u8 {
fn from(p: Protocol) -> Self {
match p {
Protocol::Tcp => 6,
Protocol::Udp => 17,
Protocol::Other(n) => n,
}
}
}
pub struct UdpBuilder {
source_port: u16,
destination_port: u16,
payload: Option<Vec<u8>>,
}
impl UdpBuilder {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
destination_port,
payload: None,
}
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = Some(payload);
self
}
pub fn build(self) -> Vec<u8> {
let payload = self.payload.unwrap_or_default();
let mut buf = BytesMut::new();
buf.put_u16(self.source_port);
buf.put_u16(self.destination_port);
buf.put_u16(8 + payload.len() as u16);
buf.put_u16(0);
buf.extend_from_slice(&payload);
let udp_buf = buf.to_vec();
return udp_buf;
}
}
pub struct TcpBuilder {
source_port: u16,
destination_port: u16,
payload: Vec<u8>,
}
impl TcpBuilder {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
destination_port,
payload: vec![],
}
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = payload;
self
}
pub fn build(self) -> Vec<u8> {
let mut buf = BytesMut::new();
buf.put_u16(self.source_port);
buf.put_u16(self.destination_port);
buf.put_u32(0); // Sequence number
buf.put_u32(0); // Acknowledgement number
let flags = 5 << 12;
buf.put_u16(flags);
buf.put_u16(1024); // Window size
buf.put_u16(0); // Checksum
buf.put_u16(0); // Urgent pointer
buf.extend_from_slice(&self.payload);
return buf.to_vec();
}
}
pub struct Ip4Builder {
source_addr: Ipv4Addr,
dest_addr: Ipv4Addr,
protocol: Protocol,
ttl: u8,
payload: Vec<u8>,
}
impl Default for Ip4Builder {
fn default() -> Self {
Self::new()
}
}
impl Ip4Builder {
pub fn new() -> Self {
Self {
source_addr: Ipv4Addr::new(0, 0, 0, 0),
dest_addr: Ipv4Addr::new(0, 0, 0, 0),
ttl: 255,
protocol: Protocol::Udp,
payload: vec![],
}
}
pub fn source(mut self, addr: Ipv4Addr) -> Self {
self.source_addr = addr;
self
}
pub fn destination(mut self, addr: Ipv4Addr) -> Self {
self.dest_addr = addr;
self
}
pub fn ttl(mut self, ttl: u8) -> Self {
self.ttl = ttl;
self
}
pub fn protocol(mut self, protocol: Protocol) -> Self {
self.protocol = protocol;
self
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = payload;
self
}
pub fn build(self) -> Vec<u8> {
let mut buf = BytesMut::new();
buf.put_u16(0x4500); // Version(4) + IHL(4) + DSCP + ECN
buf.put_u16(20 + self.payload.len() as u16); // Total length (header + payload)
buf.put_u32(0); // ID(2 bytes), Flags(3 bits), Fragment offset (13 bits)
buf.put_u8(self.ttl);
buf.put_u8(self.protocol.clone().into());
buf.put_u16(0x0000); // Checksum.
buf.extend_from_slice(&self.source_addr.octets());
buf.extend_from_slice(&self.dest_addr.octets());
buf.extend(&self.payload);
let mut out = buf.to_vec();
let csum = &self.ip_checksum(&out);
out[10] = (csum >> 8 & 0xffu16) as u8;
out[11] = (csum & 0xff) as u8;
if let Protocol::Udp = &self.protocol {
let csum = &self.tcpudp_checksum(&out, Protocol::Udp);
out[26] = (csum >> 8 & 0xffu16) as u8;
out[27] = (csum & 0xff) as u8;
} else if let Protocol::Tcp = &self.protocol {
let csum = &self.tcpudp_checksum(&out, Protocol::Tcp);
out[36] = (csum >> 8 & 0xffu16) as u8;
out[37] = (csum & 0xff) as u8;
}
return out;
}
fn ip_checksum(&self, input: &[u8]) -> u16 {
let mut result = 0xffffu32;
let mut hdr = &input[0..20];
while hdr.remaining() > 0 {
result += hdr.get_u16() as u32;
if result > 0xffff {
result -= 0xffff;
}
}
return!result as u16;
}
fn tcpudp_checksum(&self, input: &[u8], proto: Protocol) -> u16 {
let mut result = 0xffffu32;
let mut pseudo = BytesMut::new();
pseudo.extend_from_slice(&input[12..20]);
pseudo.put_u8(0);
pseudo.put_u8(proto.into());
pseudo.put_u16(input.len() as u16 - 20_u16);
while pseudo.remaining() > 0 {
result += pseudo.get_u16() as u32;
if result > 0xffff {
result -= 0xffff;
}
}
let mut pdu = &input[20..];
loop {
let remaining = pdu.remaining();
if remaining == 0 {
break;
}
if remaining == 1 {
result += (pdu.get_u8() as u32) << 8;
} else {
result += pdu.get_u16() as u32;
}
if result > 0xffff {
result -= 0xffff;
}
}
return!result as u16;
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::pcap;
#[test]
fn
|
() {
let source: Ipv4Addr = "10.10.10.10".parse().unwrap();
let destination: Ipv4Addr = "127.127.127.127".parse().unwrap();
let tcp = TcpBuilder::new(5555, 6666)
.payload(vec![0x41, 0x41, 0x41, 0x41, 0x41])
.build();
let builder = Ip4Builder::new()
.protocol(Protocol::Tcp)
.source(source)
.destination(destination)
.payload(tcp);
let packet = builder.build();
let now = chrono::Utc::now();
let _pcap_buffer = pcap::create(pcap::LinkType::Raw as u32, now, &packet);
}
}
|
parse_ip_addr
|
identifier_name
|
packet.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//! Just enough packet building to convert Eve payload's into a packet.
//!
//! TODO: Ipv6
use bytes::{Buf, BufMut, BytesMut};
use std::net::Ipv4Addr;
#[derive(Debug, Clone)]
pub enum Protocol {
Tcp,
Udp,
Other(u8),
}
impl Protocol {
pub fn from_name(proto: &str) -> Option<Protocol> {
let proto = proto.to_lowercase();
match proto.as_str() {
"tcp" => Some(Self::Tcp),
"udp" => Some(Self::Udp),
_ => None,
}
}
}
impl From<Protocol> for u8 {
fn from(p: Protocol) -> Self {
match p {
Protocol::Tcp => 6,
Protocol::Udp => 17,
Protocol::Other(n) => n,
}
}
}
pub struct UdpBuilder {
source_port: u16,
destination_port: u16,
payload: Option<Vec<u8>>,
}
impl UdpBuilder {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
destination_port,
payload: None,
}
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = Some(payload);
self
}
pub fn build(self) -> Vec<u8> {
let payload = self.payload.unwrap_or_default();
let mut buf = BytesMut::new();
buf.put_u16(self.source_port);
buf.put_u16(self.destination_port);
buf.put_u16(8 + payload.len() as u16);
buf.put_u16(0);
buf.extend_from_slice(&payload);
let udp_buf = buf.to_vec();
return udp_buf;
}
}
pub struct TcpBuilder {
source_port: u16,
destination_port: u16,
payload: Vec<u8>,
}
impl TcpBuilder {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
destination_port,
payload: vec![],
}
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = payload;
self
}
pub fn build(self) -> Vec<u8> {
let mut buf = BytesMut::new();
buf.put_u16(self.source_port);
buf.put_u16(self.destination_port);
buf.put_u32(0); // Sequence number
buf.put_u32(0); // Acknowledgement number
let flags = 5 << 12;
buf.put_u16(flags);
buf.put_u16(1024); // Window size
buf.put_u16(0); // Checksum
buf.put_u16(0); // Urgent pointer
buf.extend_from_slice(&self.payload);
return buf.to_vec();
}
}
pub struct Ip4Builder {
source_addr: Ipv4Addr,
dest_addr: Ipv4Addr,
protocol: Protocol,
ttl: u8,
payload: Vec<u8>,
}
impl Default for Ip4Builder {
fn default() -> Self {
Self::new()
}
}
impl Ip4Builder {
pub fn new() -> Self {
Self {
source_addr: Ipv4Addr::new(0, 0, 0, 0),
dest_addr: Ipv4Addr::new(0, 0, 0, 0),
ttl: 255,
protocol: Protocol::Udp,
payload: vec![],
}
}
pub fn source(mut self, addr: Ipv4Addr) -> Self
|
pub fn destination(mut self, addr: Ipv4Addr) -> Self {
self.dest_addr = addr;
self
}
pub fn ttl(mut self, ttl: u8) -> Self {
self.ttl = ttl;
self
}
pub fn protocol(mut self, protocol: Protocol) -> Self {
self.protocol = protocol;
self
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = payload;
self
}
pub fn build(self) -> Vec<u8> {
let mut buf = BytesMut::new();
buf.put_u16(0x4500); // Version(4) + IHL(4) + DSCP + ECN
buf.put_u16(20 + self.payload.len() as u16); // Total length (header + payload)
buf.put_u32(0); // ID(2 bytes), Flags(3 bits), Fragment offset (13 bits)
buf.put_u8(self.ttl);
buf.put_u8(self.protocol.clone().into());
buf.put_u16(0x0000); // Checksum.
buf.extend_from_slice(&self.source_addr.octets());
buf.extend_from_slice(&self.dest_addr.octets());
buf.extend(&self.payload);
let mut out = buf.to_vec();
let csum = &self.ip_checksum(&out);
out[10] = (csum >> 8 & 0xffu16) as u8;
out[11] = (csum & 0xff) as u8;
if let Protocol::Udp = &self.protocol {
let csum = &self.tcpudp_checksum(&out, Protocol::Udp);
out[26] = (csum >> 8 & 0xffu16) as u8;
out[27] = (csum & 0xff) as u8;
} else if let Protocol::Tcp = &self.protocol {
let csum = &self.tcpudp_checksum(&out, Protocol::Tcp);
out[36] = (csum >> 8 & 0xffu16) as u8;
out[37] = (csum & 0xff) as u8;
}
return out;
}
fn ip_checksum(&self, input: &[u8]) -> u16 {
let mut result = 0xffffu32;
let mut hdr = &input[0..20];
while hdr.remaining() > 0 {
result += hdr.get_u16() as u32;
if result > 0xffff {
result -= 0xffff;
}
}
return!result as u16;
}
fn tcpudp_checksum(&self, input: &[u8], proto: Protocol) -> u16 {
let mut result = 0xffffu32;
let mut pseudo = BytesMut::new();
pseudo.extend_from_slice(&input[12..20]);
pseudo.put_u8(0);
pseudo.put_u8(proto.into());
pseudo.put_u16(input.len() as u16 - 20_u16);
while pseudo.remaining() > 0 {
result += pseudo.get_u16() as u32;
if result > 0xffff {
result -= 0xffff;
}
}
let mut pdu = &input[20..];
loop {
let remaining = pdu.remaining();
if remaining == 0 {
break;
}
if remaining == 1 {
result += (pdu.get_u8() as u32) << 8;
} else {
result += pdu.get_u16() as u32;
}
if result > 0xffff {
result -= 0xffff;
}
}
return!result as u16;
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::pcap;
#[test]
fn parse_ip_addr() {
let source: Ipv4Addr = "10.10.10.10".parse().unwrap();
let destination: Ipv4Addr = "127.127.127.127".parse().unwrap();
let tcp = TcpBuilder::new(5555, 6666)
.payload(vec![0x41, 0x41, 0x41, 0x41, 0x41])
.build();
let builder = Ip4Builder::new()
.protocol(Protocol::Tcp)
.source(source)
.destination(destination)
.payload(tcp);
let packet = builder.build();
let now = chrono::Utc::now();
let _pcap_buffer = pcap::create(pcap::LinkType::Raw as u32, now, &packet);
}
}
|
{
self.source_addr = addr;
self
}
|
identifier_body
|
packet.rs
|
// Copyright (C) 2020 Jason Ish
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//! Just enough packet building to convert Eve payload's into a packet.
//!
//! TODO: Ipv6
use bytes::{Buf, BufMut, BytesMut};
use std::net::Ipv4Addr;
#[derive(Debug, Clone)]
pub enum Protocol {
Tcp,
Udp,
Other(u8),
}
impl Protocol {
pub fn from_name(proto: &str) -> Option<Protocol> {
let proto = proto.to_lowercase();
match proto.as_str() {
"tcp" => Some(Self::Tcp),
"udp" => Some(Self::Udp),
_ => None,
}
}
}
impl From<Protocol> for u8 {
fn from(p: Protocol) -> Self {
match p {
Protocol::Tcp => 6,
Protocol::Udp => 17,
Protocol::Other(n) => n,
}
}
}
pub struct UdpBuilder {
source_port: u16,
destination_port: u16,
payload: Option<Vec<u8>>,
}
impl UdpBuilder {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
destination_port,
payload: None,
}
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = Some(payload);
self
}
pub fn build(self) -> Vec<u8> {
let payload = self.payload.unwrap_or_default();
let mut buf = BytesMut::new();
buf.put_u16(self.source_port);
buf.put_u16(self.destination_port);
buf.put_u16(8 + payload.len() as u16);
buf.put_u16(0);
buf.extend_from_slice(&payload);
let udp_buf = buf.to_vec();
return udp_buf;
}
}
pub struct TcpBuilder {
source_port: u16,
destination_port: u16,
payload: Vec<u8>,
}
impl TcpBuilder {
pub fn new(source_port: u16, destination_port: u16) -> Self {
Self {
source_port,
destination_port,
payload: vec![],
}
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = payload;
self
}
pub fn build(self) -> Vec<u8> {
let mut buf = BytesMut::new();
buf.put_u16(self.source_port);
buf.put_u16(self.destination_port);
buf.put_u32(0); // Sequence number
buf.put_u32(0); // Acknowledgement number
let flags = 5 << 12;
buf.put_u16(flags);
buf.put_u16(1024); // Window size
buf.put_u16(0); // Checksum
buf.put_u16(0); // Urgent pointer
buf.extend_from_slice(&self.payload);
return buf.to_vec();
}
}
pub struct Ip4Builder {
source_addr: Ipv4Addr,
dest_addr: Ipv4Addr,
protocol: Protocol,
ttl: u8,
payload: Vec<u8>,
}
impl Default for Ip4Builder {
fn default() -> Self {
Self::new()
}
}
impl Ip4Builder {
pub fn new() -> Self {
Self {
source_addr: Ipv4Addr::new(0, 0, 0, 0),
dest_addr: Ipv4Addr::new(0, 0, 0, 0),
ttl: 255,
protocol: Protocol::Udp,
payload: vec![],
}
}
pub fn source(mut self, addr: Ipv4Addr) -> Self {
self.source_addr = addr;
self
}
pub fn destination(mut self, addr: Ipv4Addr) -> Self {
self.dest_addr = addr;
self
}
pub fn ttl(mut self, ttl: u8) -> Self {
self.ttl = ttl;
self
}
pub fn protocol(mut self, protocol: Protocol) -> Self {
self.protocol = protocol;
self
}
pub fn payload(mut self, payload: Vec<u8>) -> Self {
self.payload = payload;
self
}
pub fn build(self) -> Vec<u8> {
let mut buf = BytesMut::new();
buf.put_u16(0x4500); // Version(4) + IHL(4) + DSCP + ECN
buf.put_u16(20 + self.payload.len() as u16); // Total length (header + payload)
buf.put_u32(0); // ID(2 bytes), Flags(3 bits), Fragment offset (13 bits)
buf.put_u8(self.ttl);
buf.put_u8(self.protocol.clone().into());
buf.put_u16(0x0000); // Checksum.
buf.extend_from_slice(&self.source_addr.octets());
buf.extend_from_slice(&self.dest_addr.octets());
buf.extend(&self.payload);
let mut out = buf.to_vec();
let csum = &self.ip_checksum(&out);
out[10] = (csum >> 8 & 0xffu16) as u8;
out[11] = (csum & 0xff) as u8;
if let Protocol::Udp = &self.protocol {
let csum = &self.tcpudp_checksum(&out, Protocol::Udp);
out[26] = (csum >> 8 & 0xffu16) as u8;
out[27] = (csum & 0xff) as u8;
} else if let Protocol::Tcp = &self.protocol {
let csum = &self.tcpudp_checksum(&out, Protocol::Tcp);
out[36] = (csum >> 8 & 0xffu16) as u8;
out[37] = (csum & 0xff) as u8;
}
return out;
}
fn ip_checksum(&self, input: &[u8]) -> u16 {
let mut result = 0xffffu32;
let mut hdr = &input[0..20];
while hdr.remaining() > 0 {
result += hdr.get_u16() as u32;
if result > 0xffff {
result -= 0xffff;
}
}
return!result as u16;
}
fn tcpudp_checksum(&self, input: &[u8], proto: Protocol) -> u16 {
let mut result = 0xffffu32;
let mut pseudo = BytesMut::new();
pseudo.extend_from_slice(&input[12..20]);
pseudo.put_u8(0);
pseudo.put_u8(proto.into());
pseudo.put_u16(input.len() as u16 - 20_u16);
while pseudo.remaining() > 0 {
result += pseudo.get_u16() as u32;
if result > 0xffff {
result -= 0xffff;
}
}
let mut pdu = &input[20..];
loop {
let remaining = pdu.remaining();
if remaining == 0 {
break;
}
if remaining == 1
|
else {
result += pdu.get_u16() as u32;
}
if result > 0xffff {
result -= 0xffff;
}
}
return!result as u16;
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::pcap;
#[test]
fn parse_ip_addr() {
let source: Ipv4Addr = "10.10.10.10".parse().unwrap();
let destination: Ipv4Addr = "127.127.127.127".parse().unwrap();
let tcp = TcpBuilder::new(5555, 6666)
.payload(vec![0x41, 0x41, 0x41, 0x41, 0x41])
.build();
let builder = Ip4Builder::new()
.protocol(Protocol::Tcp)
.source(source)
.destination(destination)
.payload(tcp);
let packet = builder.build();
let now = chrono::Utc::now();
let _pcap_buffer = pcap::create(pcap::LinkType::Raw as u32, now, &packet);
}
}
|
{
result += (pdu.get_u8() as u32) << 8;
}
|
conditional_block
|
universal_fn_syntax_call.rs
|
pub fn universal_fn_syntax_call() {
println!("***Universal Function Syntax Call***");
one();
println!("");
}
trait Foo {
fn f(&self);
}
trait Bar {
fn f(&self);
}
struct Baz;
impl Foo for Baz {
fn f(&self)
|
}
impl Bar for Baz {
fn f(&self) {
println!("Baz's implementation of bar.");
}
}
trait Foo2 {
fn foo() -> i32;
}
struct Bar2;
impl Bar2 {
fn foo() -> i32 {
20
}
}
impl Foo2 for Bar2 {
fn foo() -> i32 {
10
}
}
fn one() {
let b = Baz;
// b.f(); // can't call because of disambiguity
Foo::f(&b); // same as f.b();
Bar::f(&b); // same as f.b();
// angle-bracket form
assert_eq!(10, <Bar2 as Foo2>::foo());
assert_eq!(20, Bar2::foo());
}
|
{
println!("Baz's implementation of foo.");
}
|
identifier_body
|
universal_fn_syntax_call.rs
|
pub fn universal_fn_syntax_call() {
println!("***Universal Function Syntax Call***");
one();
println!("");
}
|
fn f(&self);
}
trait Bar {
fn f(&self);
}
struct Baz;
impl Foo for Baz {
fn f(&self) {
println!("Baz's implementation of foo.");
}
}
impl Bar for Baz {
fn f(&self) {
println!("Baz's implementation of bar.");
}
}
trait Foo2 {
fn foo() -> i32;
}
struct Bar2;
impl Bar2 {
fn foo() -> i32 {
20
}
}
impl Foo2 for Bar2 {
fn foo() -> i32 {
10
}
}
fn one() {
let b = Baz;
// b.f(); // can't call because of disambiguity
Foo::f(&b); // same as f.b();
Bar::f(&b); // same as f.b();
// angle-bracket form
assert_eq!(10, <Bar2 as Foo2>::foo());
assert_eq!(20, Bar2::foo());
}
|
trait Foo {
|
random_line_split
|
universal_fn_syntax_call.rs
|
pub fn universal_fn_syntax_call() {
println!("***Universal Function Syntax Call***");
one();
println!("");
}
trait Foo {
fn f(&self);
}
trait Bar {
fn f(&self);
}
struct Baz;
impl Foo for Baz {
fn f(&self) {
println!("Baz's implementation of foo.");
}
}
impl Bar for Baz {
fn f(&self) {
println!("Baz's implementation of bar.");
}
}
trait Foo2 {
fn foo() -> i32;
}
struct Bar2;
impl Bar2 {
fn foo() -> i32 {
20
}
}
impl Foo2 for Bar2 {
fn
|
() -> i32 {
10
}
}
fn one() {
let b = Baz;
// b.f(); // can't call because of disambiguity
Foo::f(&b); // same as f.b();
Bar::f(&b); // same as f.b();
// angle-bracket form
assert_eq!(10, <Bar2 as Foo2>::foo());
assert_eq!(20, Bar2::foo());
}
|
foo
|
identifier_name
|
basic_usage.rs
|
// Copyright 2015, Igor Shaula
// Licensed under the MIT License <LICENSE or
// http://opensource.org/licenses/MIT>. This file
// may not be copied, modified, or distributed
// except according to those terms.
extern crate winreg;
use std::io;
use std::path::Path;
use winreg::enums::*;
use winreg::RegKey;
fn main() -> io::Result<()>
|
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let path = Path::new("Software").join("WinregRsExample1");
let (key, disp) = hkcu.create_subkey(&path)?;
match disp {
REG_CREATED_NEW_KEY => println!("A new key has been created"),
REG_OPENED_EXISTING_KEY => println!("An existing key has been opened"),
}
key.set_value("TestSZ", &"written by Rust")?;
let sz_val: String = key.get_value("TestSZ")?;
key.delete_value("TestSZ")?;
println!("TestSZ = {}", sz_val);
key.set_value("TestMultiSZ", &vec!["written", "by", "Rust"])?;
let multi_sz_val: Vec<String> = key.get_value("TestMultiSZ")?;
key.delete_value("TestMultiSZ")?;
println!("TestMultiSZ = {:?}", multi_sz_val);
key.set_value("TestDWORD", &1_234_567_890u32)?;
let dword_val: u32 = key.get_value("TestDWORD")?;
println!("TestDWORD = {}", dword_val);
key.set_value("TestQWORD", &1_234_567_891_011_121_314u64)?;
let qword_val: u64 = key.get_value("TestQWORD")?;
println!("TestQWORD = {}", qword_val);
key.create_subkey("sub\\key")?;
hkcu.delete_subkey_all(&path)?;
println!("Trying to open nonexistent key...");
hkcu.open_subkey(&path).unwrap_or_else(|e| match e.kind() {
io::ErrorKind::NotFound => panic!("Key doesn't exist"),
io::ErrorKind::PermissionDenied => panic!("Access denied"),
_ => panic!("{:?}", e),
});
Ok(())
}
|
{
println!("Reading some system info...");
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?;
let pf: String = cur_ver.get_value("ProgramFilesDir")?;
let dp: String = cur_ver.get_value("DevicePath")?;
println!("ProgramFiles = {}\nDevicePath = {}", pf, dp);
let info = cur_ver.query_info()?;
println!("info = {:?}", info);
let mt = info.get_last_write_time_system();
println!(
"last_write_time as winapi::um::minwinbase::SYSTEMTIME = {}-{:02}-{:02} {:02}:{:02}:{:02}",
mt.wYear, mt.wMonth, mt.wDay, mt.wHour, mt.wMinute, mt.wSecond
);
println!(
"last_write_time as chrono::NaiveDateTime = {}",
info.get_last_write_time_chrono()
);
println!("And now lets write something...");
|
identifier_body
|
basic_usage.rs
|
// Copyright 2015, Igor Shaula
// Licensed under the MIT License <LICENSE or
// http://opensource.org/licenses/MIT>. This file
// may not be copied, modified, or distributed
// except according to those terms.
extern crate winreg;
use std::io;
use std::path::Path;
use winreg::enums::*;
use winreg::RegKey;
fn main() -> io::Result<()> {
println!("Reading some system info...");
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?;
let pf: String = cur_ver.get_value("ProgramFilesDir")?;
let dp: String = cur_ver.get_value("DevicePath")?;
println!("ProgramFiles = {}\nDevicePath = {}", pf, dp);
let info = cur_ver.query_info()?;
println!("info = {:?}", info);
let mt = info.get_last_write_time_system();
println!(
"last_write_time as winapi::um::minwinbase::SYSTEMTIME = {}-{:02}-{:02} {:02}:{:02}:{:02}",
mt.wYear, mt.wMonth, mt.wDay, mt.wHour, mt.wMinute, mt.wSecond
);
println!(
"last_write_time as chrono::NaiveDateTime = {}",
info.get_last_write_time_chrono()
);
println!("And now lets write something...");
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let path = Path::new("Software").join("WinregRsExample1");
let (key, disp) = hkcu.create_subkey(&path)?;
match disp {
REG_CREATED_NEW_KEY => println!("A new key has been created"),
REG_OPENED_EXISTING_KEY => println!("An existing key has been opened"),
}
key.set_value("TestSZ", &"written by Rust")?;
let sz_val: String = key.get_value("TestSZ")?;
|
let multi_sz_val: Vec<String> = key.get_value("TestMultiSZ")?;
key.delete_value("TestMultiSZ")?;
println!("TestMultiSZ = {:?}", multi_sz_val);
key.set_value("TestDWORD", &1_234_567_890u32)?;
let dword_val: u32 = key.get_value("TestDWORD")?;
println!("TestDWORD = {}", dword_val);
key.set_value("TestQWORD", &1_234_567_891_011_121_314u64)?;
let qword_val: u64 = key.get_value("TestQWORD")?;
println!("TestQWORD = {}", qword_val);
key.create_subkey("sub\\key")?;
hkcu.delete_subkey_all(&path)?;
println!("Trying to open nonexistent key...");
hkcu.open_subkey(&path).unwrap_or_else(|e| match e.kind() {
io::ErrorKind::NotFound => panic!("Key doesn't exist"),
io::ErrorKind::PermissionDenied => panic!("Access denied"),
_ => panic!("{:?}", e),
});
Ok(())
}
|
key.delete_value("TestSZ")?;
println!("TestSZ = {}", sz_val);
key.set_value("TestMultiSZ", &vec!["written", "by", "Rust"])?;
|
random_line_split
|
basic_usage.rs
|
// Copyright 2015, Igor Shaula
// Licensed under the MIT License <LICENSE or
// http://opensource.org/licenses/MIT>. This file
// may not be copied, modified, or distributed
// except according to those terms.
extern crate winreg;
use std::io;
use std::path::Path;
use winreg::enums::*;
use winreg::RegKey;
fn
|
() -> io::Result<()> {
println!("Reading some system info...");
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?;
let pf: String = cur_ver.get_value("ProgramFilesDir")?;
let dp: String = cur_ver.get_value("DevicePath")?;
println!("ProgramFiles = {}\nDevicePath = {}", pf, dp);
let info = cur_ver.query_info()?;
println!("info = {:?}", info);
let mt = info.get_last_write_time_system();
println!(
"last_write_time as winapi::um::minwinbase::SYSTEMTIME = {}-{:02}-{:02} {:02}:{:02}:{:02}",
mt.wYear, mt.wMonth, mt.wDay, mt.wHour, mt.wMinute, mt.wSecond
);
println!(
"last_write_time as chrono::NaiveDateTime = {}",
info.get_last_write_time_chrono()
);
println!("And now lets write something...");
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
let path = Path::new("Software").join("WinregRsExample1");
let (key, disp) = hkcu.create_subkey(&path)?;
match disp {
REG_CREATED_NEW_KEY => println!("A new key has been created"),
REG_OPENED_EXISTING_KEY => println!("An existing key has been opened"),
}
key.set_value("TestSZ", &"written by Rust")?;
let sz_val: String = key.get_value("TestSZ")?;
key.delete_value("TestSZ")?;
println!("TestSZ = {}", sz_val);
key.set_value("TestMultiSZ", &vec!["written", "by", "Rust"])?;
let multi_sz_val: Vec<String> = key.get_value("TestMultiSZ")?;
key.delete_value("TestMultiSZ")?;
println!("TestMultiSZ = {:?}", multi_sz_val);
key.set_value("TestDWORD", &1_234_567_890u32)?;
let dword_val: u32 = key.get_value("TestDWORD")?;
println!("TestDWORD = {}", dword_val);
key.set_value("TestQWORD", &1_234_567_891_011_121_314u64)?;
let qword_val: u64 = key.get_value("TestQWORD")?;
println!("TestQWORD = {}", qword_val);
key.create_subkey("sub\\key")?;
hkcu.delete_subkey_all(&path)?;
println!("Trying to open nonexistent key...");
hkcu.open_subkey(&path).unwrap_or_else(|e| match e.kind() {
io::ErrorKind::NotFound => panic!("Key doesn't exist"),
io::ErrorKind::PermissionDenied => panic!("Access denied"),
_ => panic!("{:?}", e),
});
Ok(())
}
|
main
|
identifier_name
|
externalities.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Transaction Execution environment.
use util::*;
use action_params::{ActionParams, ActionValue};
use state::{State, Substate};
use engines::Engine;
use env_info::EnvInfo;
use executive::*;
use evm::{self, Schedule, Ext, ContractCreateResult, MessageCallResult, Factory};
use types::executed::CallType;
use trace::{Tracer, VMTracer};
/// Policy for handling output data on `RETURN` opcode.
pub enum OutputPolicy<'a, 'b> {
/// Return reference to fixed sized output.
/// Used for message calls.
Return(BytesRef<'a>, Option<&'b mut Bytes>),
/// Init new contract as soon as `RETURN` is called.
InitContract(Option<&'b mut Bytes>),
}
/// Transaction properties that externalities need to know about.
pub struct OriginInfo {
address: Address,
origin: Address,
gas_price: U256,
value: U256
}
impl OriginInfo {
/// Populates origin info from action params.
pub fn from(params: &ActionParams) -> Self {
OriginInfo {
address: params.address.clone(),
origin: params.origin.clone(),
gas_price: params.gas_price,
value: match params.value {
ActionValue::Transfer(val) | ActionValue::Apparent(val) => val
}
}
}
}
/// Implementation of evm Externalities.
pub struct Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
state: &'a mut State,
env_info: &'a EnvInfo,
engine: &'a Engine,
vm_factory: &'a Factory,
depth: usize,
origin_info: OriginInfo,
substate: &'a mut Substate,
schedule: Schedule,
output: OutputPolicy<'a, 'a>,
tracer: &'a mut T,
vm_tracer: &'a mut V,
}
impl<'a, T, V> Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
#[cfg_attr(feature="dev", allow(too_many_arguments))]
/// Basic `Externalities` constructor.
pub fn new(state: &'a mut State,
env_info: &'a EnvInfo,
engine: &'a Engine,
vm_factory: &'a Factory,
depth: usize,
origin_info: OriginInfo,
substate: &'a mut Substate,
output: OutputPolicy<'a, 'a>,
tracer: &'a mut T,
vm_tracer: &'a mut V,
) -> Self {
Externalities {
state: state,
env_info: env_info,
engine: engine,
vm_factory: vm_factory,
depth: depth,
origin_info: origin_info,
substate: substate,
schedule: engine.schedule(env_info),
output: output,
tracer: tracer,
vm_tracer: vm_tracer,
}
}
}
impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
fn storage_at(&self, key: &H256) -> H256 {
self.state.storage_at(&self.origin_info.address, key)
}
fn set_storage(&mut self, key: H256, value: H256) {
self.state.set_storage(&self.origin_info.address, key, value)
}
fn exists(&self, address: &Address) -> bool {
self.state.exists(address)
}
fn balance(&self, address: &Address) -> U256 {
self.state.balance(address)
}
fn blockhash(&self, number: &U256) -> H256 {
// TODO: comment out what this function expects from env_info, since it will produce panics if the latter is inconsistent
match *number < U256::from(self.env_info.number) && number.low_u64() >= cmp::max(256, self.env_info.number) - 256 {
true => {
let index = self.env_info.number - number.low_u64() - 1;
assert!(index < self.env_info.last_hashes.len() as u64, format!("Inconsistent env_info, should contain at least {:?} last hashes", index+1));
let r = self.env_info.last_hashes[index as usize].clone();
trace!("ext: blockhash({}) -> {} self.env_info.number={}\n", number, r, self.env_info.number);
r
},
false => {
trace!("ext: blockhash({}) -> null self.env_info.number={}\n", number, self.env_info.number);
H256::zero()
},
}
}
fn
|
(&mut self, gas: &U256, value: &U256, code: &[u8]) -> ContractCreateResult {
// create new contract address
let address = contract_address(&self.origin_info.address, &self.state.nonce(&self.origin_info.address));
// prepare the params
let params = ActionParams {
code_address: address.clone(),
address: address.clone(),
sender: self.origin_info.address.clone(),
origin: self.origin_info.origin.clone(),
gas: *gas,
gas_price: self.origin_info.gas_price,
value: ActionValue::Transfer(*value),
code: Some(Arc::new(code.to_vec())),
code_hash: code.sha3(),
data: None,
call_type: CallType::None,
};
self.state.inc_nonce(&self.origin_info.address);
let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.vm_factory, self.depth);
// TODO: handle internal error separately
match ex.create(params, self.substate, self.tracer, self.vm_tracer) {
Ok(gas_left) => {
self.substate.contracts_created.push(address.clone());
ContractCreateResult::Created(address, gas_left)
},
_ => ContractCreateResult::Failed
}
}
fn call(&mut self,
gas: &U256,
sender_address: &Address,
receive_address: &Address,
value: Option<U256>,
data: &[u8],
code_address: &Address,
output: &mut [u8],
call_type: CallType
) -> MessageCallResult {
trace!(target: "externalities", "call");
let mut params = ActionParams {
sender: sender_address.clone(),
address: receive_address.clone(),
value: ActionValue::Apparent(self.origin_info.value),
code_address: code_address.clone(),
origin: self.origin_info.origin.clone(),
gas: *gas,
gas_price: self.origin_info.gas_price,
code: self.state.code(code_address),
code_hash: self.state.code_hash(code_address),
data: Some(data.to_vec()),
call_type: call_type,
};
if let Some(value) = value {
params.value = ActionValue::Transfer(value);
}
let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.vm_factory, self.depth);
match ex.call(params, self.substate, BytesRef::Fixed(output), self.tracer, self.vm_tracer) {
Ok(gas_left) => MessageCallResult::Success(gas_left),
_ => MessageCallResult::Failed
}
}
fn extcode(&self, address: &Address) -> Arc<Bytes> {
self.state.code(address).unwrap_or_else(|| Arc::new(vec![]))
}
fn extcodesize(&self, address: &Address) -> usize {
self.state.code_size(address).unwrap_or(0)
}
#[cfg_attr(feature="dev", allow(match_ref_pats))]
fn ret(mut self, gas: &U256, data: &[u8]) -> evm::Result<U256>
where Self: Sized {
let handle_copy = |to: &mut Option<&mut Bytes>| {
to.as_mut().map(|b| **b = data.to_owned());
};
match self.output {
OutputPolicy::Return(BytesRef::Fixed(ref mut slice), ref mut copy) => {
handle_copy(copy);
let len = cmp::min(slice.len(), data.len());
(&mut slice[..len]).copy_from_slice(&data[..len]);
Ok(*gas)
},
OutputPolicy::Return(BytesRef::Flexible(ref mut vec), ref mut copy) => {
handle_copy(copy);
vec.clear();
vec.extend_from_slice(data);
Ok(*gas)
},
OutputPolicy::InitContract(ref mut copy) => {
let return_cost = U256::from(data.len()) * U256::from(self.schedule.create_data_gas);
if return_cost > *gas {
return match self.schedule.exceptional_failed_code_deposit {
true => Err(evm::Error::OutOfGas),
false => Ok(*gas)
}
}
handle_copy(copy);
let mut code = vec![];
code.extend_from_slice(data);
self.state.init_code(&self.origin_info.address, code);
Ok(*gas - return_cost)
}
}
}
fn log(&mut self, topics: Vec<H256>, data: &[u8]) {
use log_entry::LogEntry;
let address = self.origin_info.address.clone();
self.substate.logs.push(LogEntry {
address: address,
topics: topics,
data: data.to_vec()
});
}
fn suicide(&mut self, refund_address: &Address) {
let address = self.origin_info.address.clone();
let balance = self.balance(&address);
if &address == refund_address {
// TODO [todr] To be consisted with CPP client we set balance to 0 in that case.
self.state.sub_balance(&address, &balance);
} else {
trace!("Suiciding {} -> {} (xfer: {})", address, refund_address, balance);
self.state.transfer_balance(&address, refund_address, &balance);
}
self.tracer.trace_suicide(address, balance, refund_address.clone());
self.substate.suicides.insert(address);
}
fn schedule(&self) -> &Schedule {
&self.schedule
}
fn env_info(&self) -> &EnvInfo {
self.env_info
}
fn depth(&self) -> usize {
self.depth
}
fn inc_sstore_clears(&mut self) {
self.substate.sstore_clears_count = self.substate.sstore_clears_count + U256::one();
}
fn trace_prepare_execute(&mut self, pc: usize, instruction: u8, gas_cost: &U256) -> bool {
self.vm_tracer.trace_prepare_execute(pc, instruction, gas_cost)
}
fn trace_executed(&mut self, gas_used: U256, stack_push: &[U256], mem_diff: Option<(usize, &[u8])>, store_diff: Option<(U256, U256)>) {
self.vm_tracer.trace_executed(gas_used, stack_push, mem_diff, store_diff)
}
}
#[cfg(test)]
mod tests {
use util::*;
use engines::Engine;
use env_info::EnvInfo;
use evm::Ext;
use state::{State, Substate};
use tests::helpers::*;
use devtools::GuardedTempResult;
use super::*;
use trace::{NoopTracer, NoopVMTracer};
use types::executed::CallType;
fn get_test_origin() -> OriginInfo {
OriginInfo {
address: Address::zero(),
origin: Address::zero(),
gas_price: U256::zero(),
value: U256::zero()
}
}
fn get_test_env_info() -> EnvInfo {
EnvInfo {
number: 100,
author: 0.into(),
timestamp: 0,
difficulty: 0.into(),
last_hashes: Arc::new(vec![]),
gas_used: 0.into(),
gas_limit: 0.into(),
}
}
struct TestSetup {
state: GuardedTempResult<State>,
engine: Arc<Engine>,
sub_state: Substate,
env_info: EnvInfo
}
impl Default for TestSetup {
fn default() -> Self {
TestSetup::new()
}
}
impl TestSetup {
fn new() -> Self {
TestSetup {
state: get_temp_state(),
engine: get_test_spec().engine,
sub_state: Substate::new(),
env_info: get_test_env_info()
}
}
}
#[test]
fn can_be_created() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
assert_eq!(ext.env_info().number, 100);
}
#[test]
fn can_return_block_hash_no_env() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap());
assert_eq!(hash, H256::zero());
}
#[test]
fn can_return_block_hash() {
let test_hash = H256::from("afafafafafafafafafafafbcbcbcbcbcbcbcbcbcbeeeeeeeeeeeeedddddddddd");
let test_env_number = 0x120001;
let mut setup = TestSetup::new();
{
let env_info = &mut setup.env_info;
env_info.number = test_env_number;
let mut last_hashes = (*env_info.last_hashes).clone();
last_hashes.push(test_hash.clone());
env_info.last_hashes = Arc::new(last_hashes);
}
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap());
assert_eq!(test_hash, hash);
}
#[test]
#[should_panic]
fn can_call_fail_empty() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let mut output = vec![];
// this should panic because we have no balance on any account
ext.call(
&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap(),
&Address::new(),
&Address::new(),
Some(U256::from_str("0000000000000000000000000000000000000000000000000000000000150000").unwrap()),
&[],
&Address::new(),
&mut output,
CallType::Call
);
}
#[test]
fn can_log() {
let log_data = vec![120u8, 110u8];
let log_topics = vec![H256::from("af0fa234a6af46afa23faf23bcbc1c1cb4bcb7bcbe7e7e7ee3ee2edddddddddd")];
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
{
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
ext.log(log_topics, &log_data);
}
assert_eq!(setup.sub_state.logs.len(), 1);
}
#[test]
fn can_suicide() {
let refund_account = &Address::new();
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
{
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
ext.suicide(refund_account);
}
assert_eq!(setup.sub_state.suicides.len(), 1);
}
}
|
create
|
identifier_name
|
externalities.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Transaction Execution environment.
use util::*;
use action_params::{ActionParams, ActionValue};
use state::{State, Substate};
use engines::Engine;
use env_info::EnvInfo;
use executive::*;
use evm::{self, Schedule, Ext, ContractCreateResult, MessageCallResult, Factory};
use types::executed::CallType;
use trace::{Tracer, VMTracer};
/// Policy for handling output data on `RETURN` opcode.
pub enum OutputPolicy<'a, 'b> {
/// Return reference to fixed sized output.
/// Used for message calls.
Return(BytesRef<'a>, Option<&'b mut Bytes>),
/// Init new contract as soon as `RETURN` is called.
InitContract(Option<&'b mut Bytes>),
}
/// Transaction properties that externalities need to know about.
pub struct OriginInfo {
address: Address,
origin: Address,
gas_price: U256,
value: U256
}
impl OriginInfo {
/// Populates origin info from action params.
pub fn from(params: &ActionParams) -> Self
|
}
/// Implementation of evm Externalities.
pub struct Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
state: &'a mut State,
env_info: &'a EnvInfo,
engine: &'a Engine,
vm_factory: &'a Factory,
depth: usize,
origin_info: OriginInfo,
substate: &'a mut Substate,
schedule: Schedule,
output: OutputPolicy<'a, 'a>,
tracer: &'a mut T,
vm_tracer: &'a mut V,
}
impl<'a, T, V> Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
#[cfg_attr(feature="dev", allow(too_many_arguments))]
/// Basic `Externalities` constructor.
pub fn new(state: &'a mut State,
env_info: &'a EnvInfo,
engine: &'a Engine,
vm_factory: &'a Factory,
depth: usize,
origin_info: OriginInfo,
substate: &'a mut Substate,
output: OutputPolicy<'a, 'a>,
tracer: &'a mut T,
vm_tracer: &'a mut V,
) -> Self {
Externalities {
state: state,
env_info: env_info,
engine: engine,
vm_factory: vm_factory,
depth: depth,
origin_info: origin_info,
substate: substate,
schedule: engine.schedule(env_info),
output: output,
tracer: tracer,
vm_tracer: vm_tracer,
}
}
}
impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
fn storage_at(&self, key: &H256) -> H256 {
self.state.storage_at(&self.origin_info.address, key)
}
fn set_storage(&mut self, key: H256, value: H256) {
self.state.set_storage(&self.origin_info.address, key, value)
}
fn exists(&self, address: &Address) -> bool {
self.state.exists(address)
}
fn balance(&self, address: &Address) -> U256 {
self.state.balance(address)
}
fn blockhash(&self, number: &U256) -> H256 {
// TODO: comment out what this function expects from env_info, since it will produce panics if the latter is inconsistent
match *number < U256::from(self.env_info.number) && number.low_u64() >= cmp::max(256, self.env_info.number) - 256 {
true => {
let index = self.env_info.number - number.low_u64() - 1;
assert!(index < self.env_info.last_hashes.len() as u64, format!("Inconsistent env_info, should contain at least {:?} last hashes", index+1));
let r = self.env_info.last_hashes[index as usize].clone();
trace!("ext: blockhash({}) -> {} self.env_info.number={}\n", number, r, self.env_info.number);
r
},
false => {
trace!("ext: blockhash({}) -> null self.env_info.number={}\n", number, self.env_info.number);
H256::zero()
},
}
}
fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> ContractCreateResult {
// create new contract address
let address = contract_address(&self.origin_info.address, &self.state.nonce(&self.origin_info.address));
// prepare the params
let params = ActionParams {
code_address: address.clone(),
address: address.clone(),
sender: self.origin_info.address.clone(),
origin: self.origin_info.origin.clone(),
gas: *gas,
gas_price: self.origin_info.gas_price,
value: ActionValue::Transfer(*value),
code: Some(Arc::new(code.to_vec())),
code_hash: code.sha3(),
data: None,
call_type: CallType::None,
};
self.state.inc_nonce(&self.origin_info.address);
let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.vm_factory, self.depth);
// TODO: handle internal error separately
match ex.create(params, self.substate, self.tracer, self.vm_tracer) {
Ok(gas_left) => {
self.substate.contracts_created.push(address.clone());
ContractCreateResult::Created(address, gas_left)
},
_ => ContractCreateResult::Failed
}
}
fn call(&mut self,
gas: &U256,
sender_address: &Address,
receive_address: &Address,
value: Option<U256>,
data: &[u8],
code_address: &Address,
output: &mut [u8],
call_type: CallType
) -> MessageCallResult {
trace!(target: "externalities", "call");
let mut params = ActionParams {
sender: sender_address.clone(),
address: receive_address.clone(),
value: ActionValue::Apparent(self.origin_info.value),
code_address: code_address.clone(),
origin: self.origin_info.origin.clone(),
gas: *gas,
gas_price: self.origin_info.gas_price,
code: self.state.code(code_address),
code_hash: self.state.code_hash(code_address),
data: Some(data.to_vec()),
call_type: call_type,
};
if let Some(value) = value {
params.value = ActionValue::Transfer(value);
}
let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.vm_factory, self.depth);
match ex.call(params, self.substate, BytesRef::Fixed(output), self.tracer, self.vm_tracer) {
Ok(gas_left) => MessageCallResult::Success(gas_left),
_ => MessageCallResult::Failed
}
}
fn extcode(&self, address: &Address) -> Arc<Bytes> {
self.state.code(address).unwrap_or_else(|| Arc::new(vec![]))
}
fn extcodesize(&self, address: &Address) -> usize {
self.state.code_size(address).unwrap_or(0)
}
#[cfg_attr(feature="dev", allow(match_ref_pats))]
fn ret(mut self, gas: &U256, data: &[u8]) -> evm::Result<U256>
where Self: Sized {
let handle_copy = |to: &mut Option<&mut Bytes>| {
to.as_mut().map(|b| **b = data.to_owned());
};
match self.output {
OutputPolicy::Return(BytesRef::Fixed(ref mut slice), ref mut copy) => {
handle_copy(copy);
let len = cmp::min(slice.len(), data.len());
(&mut slice[..len]).copy_from_slice(&data[..len]);
Ok(*gas)
},
OutputPolicy::Return(BytesRef::Flexible(ref mut vec), ref mut copy) => {
handle_copy(copy);
vec.clear();
vec.extend_from_slice(data);
Ok(*gas)
},
OutputPolicy::InitContract(ref mut copy) => {
let return_cost = U256::from(data.len()) * U256::from(self.schedule.create_data_gas);
if return_cost > *gas {
return match self.schedule.exceptional_failed_code_deposit {
true => Err(evm::Error::OutOfGas),
false => Ok(*gas)
}
}
handle_copy(copy);
let mut code = vec![];
code.extend_from_slice(data);
self.state.init_code(&self.origin_info.address, code);
Ok(*gas - return_cost)
}
}
}
fn log(&mut self, topics: Vec<H256>, data: &[u8]) {
use log_entry::LogEntry;
let address = self.origin_info.address.clone();
self.substate.logs.push(LogEntry {
address: address,
topics: topics,
data: data.to_vec()
});
}
fn suicide(&mut self, refund_address: &Address) {
let address = self.origin_info.address.clone();
let balance = self.balance(&address);
if &address == refund_address {
// TODO [todr] To be consisted with CPP client we set balance to 0 in that case.
self.state.sub_balance(&address, &balance);
} else {
trace!("Suiciding {} -> {} (xfer: {})", address, refund_address, balance);
self.state.transfer_balance(&address, refund_address, &balance);
}
self.tracer.trace_suicide(address, balance, refund_address.clone());
self.substate.suicides.insert(address);
}
fn schedule(&self) -> &Schedule {
&self.schedule
}
fn env_info(&self) -> &EnvInfo {
self.env_info
}
fn depth(&self) -> usize {
self.depth
}
fn inc_sstore_clears(&mut self) {
self.substate.sstore_clears_count = self.substate.sstore_clears_count + U256::one();
}
fn trace_prepare_execute(&mut self, pc: usize, instruction: u8, gas_cost: &U256) -> bool {
self.vm_tracer.trace_prepare_execute(pc, instruction, gas_cost)
}
fn trace_executed(&mut self, gas_used: U256, stack_push: &[U256], mem_diff: Option<(usize, &[u8])>, store_diff: Option<(U256, U256)>) {
self.vm_tracer.trace_executed(gas_used, stack_push, mem_diff, store_diff)
}
}
#[cfg(test)]
mod tests {
use util::*;
use engines::Engine;
use env_info::EnvInfo;
use evm::Ext;
use state::{State, Substate};
use tests::helpers::*;
use devtools::GuardedTempResult;
use super::*;
use trace::{NoopTracer, NoopVMTracer};
use types::executed::CallType;
fn get_test_origin() -> OriginInfo {
OriginInfo {
address: Address::zero(),
origin: Address::zero(),
gas_price: U256::zero(),
value: U256::zero()
}
}
fn get_test_env_info() -> EnvInfo {
EnvInfo {
number: 100,
author: 0.into(),
timestamp: 0,
difficulty: 0.into(),
last_hashes: Arc::new(vec![]),
gas_used: 0.into(),
gas_limit: 0.into(),
}
}
struct TestSetup {
state: GuardedTempResult<State>,
engine: Arc<Engine>,
sub_state: Substate,
env_info: EnvInfo
}
impl Default for TestSetup {
fn default() -> Self {
TestSetup::new()
}
}
impl TestSetup {
fn new() -> Self {
TestSetup {
state: get_temp_state(),
engine: get_test_spec().engine,
sub_state: Substate::new(),
env_info: get_test_env_info()
}
}
}
#[test]
fn can_be_created() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
assert_eq!(ext.env_info().number, 100);
}
#[test]
fn can_return_block_hash_no_env() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap());
assert_eq!(hash, H256::zero());
}
#[test]
fn can_return_block_hash() {
let test_hash = H256::from("afafafafafafafafafafafbcbcbcbcbcbcbcbcbcbeeeeeeeeeeeeedddddddddd");
let test_env_number = 0x120001;
let mut setup = TestSetup::new();
{
let env_info = &mut setup.env_info;
env_info.number = test_env_number;
let mut last_hashes = (*env_info.last_hashes).clone();
last_hashes.push(test_hash.clone());
env_info.last_hashes = Arc::new(last_hashes);
}
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap());
assert_eq!(test_hash, hash);
}
#[test]
#[should_panic]
fn can_call_fail_empty() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let mut output = vec![];
// this should panic because we have no balance on any account
ext.call(
&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap(),
&Address::new(),
&Address::new(),
Some(U256::from_str("0000000000000000000000000000000000000000000000000000000000150000").unwrap()),
&[],
&Address::new(),
&mut output,
CallType::Call
);
}
#[test]
fn can_log() {
let log_data = vec![120u8, 110u8];
let log_topics = vec![H256::from("af0fa234a6af46afa23faf23bcbc1c1cb4bcb7bcbe7e7e7ee3ee2edddddddddd")];
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
{
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
ext.log(log_topics, &log_data);
}
assert_eq!(setup.sub_state.logs.len(), 1);
}
#[test]
fn can_suicide() {
let refund_account = &Address::new();
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
{
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
ext.suicide(refund_account);
}
assert_eq!(setup.sub_state.suicides.len(), 1);
}
}
|
{
OriginInfo {
address: params.address.clone(),
origin: params.origin.clone(),
gas_price: params.gas_price,
value: match params.value {
ActionValue::Transfer(val) | ActionValue::Apparent(val) => val
}
}
}
|
identifier_body
|
externalities.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Transaction Execution environment.
use util::*;
use action_params::{ActionParams, ActionValue};
use state::{State, Substate};
use engines::Engine;
use env_info::EnvInfo;
use executive::*;
use evm::{self, Schedule, Ext, ContractCreateResult, MessageCallResult, Factory};
use types::executed::CallType;
use trace::{Tracer, VMTracer};
/// Policy for handling output data on `RETURN` opcode.
pub enum OutputPolicy<'a, 'b> {
/// Return reference to fixed sized output.
/// Used for message calls.
Return(BytesRef<'a>, Option<&'b mut Bytes>),
/// Init new contract as soon as `RETURN` is called.
InitContract(Option<&'b mut Bytes>),
}
/// Transaction properties that externalities need to know about.
pub struct OriginInfo {
address: Address,
origin: Address,
gas_price: U256,
value: U256
}
impl OriginInfo {
/// Populates origin info from action params.
pub fn from(params: &ActionParams) -> Self {
OriginInfo {
address: params.address.clone(),
origin: params.origin.clone(),
gas_price: params.gas_price,
value: match params.value {
ActionValue::Transfer(val) | ActionValue::Apparent(val) => val
}
}
}
}
/// Implementation of evm Externalities.
pub struct Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
state: &'a mut State,
env_info: &'a EnvInfo,
engine: &'a Engine,
vm_factory: &'a Factory,
depth: usize,
origin_info: OriginInfo,
substate: &'a mut Substate,
schedule: Schedule,
output: OutputPolicy<'a, 'a>,
tracer: &'a mut T,
vm_tracer: &'a mut V,
}
impl<'a, T, V> Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
#[cfg_attr(feature="dev", allow(too_many_arguments))]
/// Basic `Externalities` constructor.
pub fn new(state: &'a mut State,
env_info: &'a EnvInfo,
engine: &'a Engine,
vm_factory: &'a Factory,
depth: usize,
origin_info: OriginInfo,
substate: &'a mut Substate,
output: OutputPolicy<'a, 'a>,
tracer: &'a mut T,
vm_tracer: &'a mut V,
) -> Self {
Externalities {
state: state,
env_info: env_info,
engine: engine,
vm_factory: vm_factory,
depth: depth,
origin_info: origin_info,
substate: substate,
schedule: engine.schedule(env_info),
output: output,
tracer: tracer,
vm_tracer: vm_tracer,
}
}
}
impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
fn storage_at(&self, key: &H256) -> H256 {
self.state.storage_at(&self.origin_info.address, key)
}
fn set_storage(&mut self, key: H256, value: H256) {
self.state.set_storage(&self.origin_info.address, key, value)
}
fn exists(&self, address: &Address) -> bool {
self.state.exists(address)
}
fn balance(&self, address: &Address) -> U256 {
self.state.balance(address)
}
fn blockhash(&self, number: &U256) -> H256 {
// TODO: comment out what this function expects from env_info, since it will produce panics if the latter is inconsistent
match *number < U256::from(self.env_info.number) && number.low_u64() >= cmp::max(256, self.env_info.number) - 256 {
true => {
let index = self.env_info.number - number.low_u64() - 1;
assert!(index < self.env_info.last_hashes.len() as u64, format!("Inconsistent env_info, should contain at least {:?} last hashes", index+1));
let r = self.env_info.last_hashes[index as usize].clone();
trace!("ext: blockhash({}) -> {} self.env_info.number={}\n", number, r, self.env_info.number);
r
},
false =>
|
,
}
}
fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> ContractCreateResult {
// create new contract address
let address = contract_address(&self.origin_info.address, &self.state.nonce(&self.origin_info.address));
// prepare the params
let params = ActionParams {
code_address: address.clone(),
address: address.clone(),
sender: self.origin_info.address.clone(),
origin: self.origin_info.origin.clone(),
gas: *gas,
gas_price: self.origin_info.gas_price,
value: ActionValue::Transfer(*value),
code: Some(Arc::new(code.to_vec())),
code_hash: code.sha3(),
data: None,
call_type: CallType::None,
};
self.state.inc_nonce(&self.origin_info.address);
let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.vm_factory, self.depth);
// TODO: handle internal error separately
match ex.create(params, self.substate, self.tracer, self.vm_tracer) {
Ok(gas_left) => {
self.substate.contracts_created.push(address.clone());
ContractCreateResult::Created(address, gas_left)
},
_ => ContractCreateResult::Failed
}
}
fn call(&mut self,
gas: &U256,
sender_address: &Address,
receive_address: &Address,
value: Option<U256>,
data: &[u8],
code_address: &Address,
output: &mut [u8],
call_type: CallType
) -> MessageCallResult {
trace!(target: "externalities", "call");
let mut params = ActionParams {
sender: sender_address.clone(),
address: receive_address.clone(),
value: ActionValue::Apparent(self.origin_info.value),
code_address: code_address.clone(),
origin: self.origin_info.origin.clone(),
gas: *gas,
gas_price: self.origin_info.gas_price,
code: self.state.code(code_address),
code_hash: self.state.code_hash(code_address),
data: Some(data.to_vec()),
call_type: call_type,
};
if let Some(value) = value {
params.value = ActionValue::Transfer(value);
}
let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.vm_factory, self.depth);
match ex.call(params, self.substate, BytesRef::Fixed(output), self.tracer, self.vm_tracer) {
Ok(gas_left) => MessageCallResult::Success(gas_left),
_ => MessageCallResult::Failed
}
}
fn extcode(&self, address: &Address) -> Arc<Bytes> {
self.state.code(address).unwrap_or_else(|| Arc::new(vec![]))
}
fn extcodesize(&self, address: &Address) -> usize {
self.state.code_size(address).unwrap_or(0)
}
#[cfg_attr(feature="dev", allow(match_ref_pats))]
fn ret(mut self, gas: &U256, data: &[u8]) -> evm::Result<U256>
where Self: Sized {
let handle_copy = |to: &mut Option<&mut Bytes>| {
to.as_mut().map(|b| **b = data.to_owned());
};
match self.output {
OutputPolicy::Return(BytesRef::Fixed(ref mut slice), ref mut copy) => {
handle_copy(copy);
let len = cmp::min(slice.len(), data.len());
(&mut slice[..len]).copy_from_slice(&data[..len]);
Ok(*gas)
},
OutputPolicy::Return(BytesRef::Flexible(ref mut vec), ref mut copy) => {
handle_copy(copy);
vec.clear();
vec.extend_from_slice(data);
Ok(*gas)
},
OutputPolicy::InitContract(ref mut copy) => {
let return_cost = U256::from(data.len()) * U256::from(self.schedule.create_data_gas);
if return_cost > *gas {
return match self.schedule.exceptional_failed_code_deposit {
true => Err(evm::Error::OutOfGas),
false => Ok(*gas)
}
}
handle_copy(copy);
let mut code = vec![];
code.extend_from_slice(data);
self.state.init_code(&self.origin_info.address, code);
Ok(*gas - return_cost)
}
}
}
fn log(&mut self, topics: Vec<H256>, data: &[u8]) {
use log_entry::LogEntry;
let address = self.origin_info.address.clone();
self.substate.logs.push(LogEntry {
address: address,
topics: topics,
data: data.to_vec()
});
}
fn suicide(&mut self, refund_address: &Address) {
let address = self.origin_info.address.clone();
let balance = self.balance(&address);
if &address == refund_address {
// TODO [todr] To be consisted with CPP client we set balance to 0 in that case.
self.state.sub_balance(&address, &balance);
} else {
trace!("Suiciding {} -> {} (xfer: {})", address, refund_address, balance);
self.state.transfer_balance(&address, refund_address, &balance);
}
self.tracer.trace_suicide(address, balance, refund_address.clone());
self.substate.suicides.insert(address);
}
fn schedule(&self) -> &Schedule {
&self.schedule
}
fn env_info(&self) -> &EnvInfo {
self.env_info
}
fn depth(&self) -> usize {
self.depth
}
fn inc_sstore_clears(&mut self) {
self.substate.sstore_clears_count = self.substate.sstore_clears_count + U256::one();
}
fn trace_prepare_execute(&mut self, pc: usize, instruction: u8, gas_cost: &U256) -> bool {
self.vm_tracer.trace_prepare_execute(pc, instruction, gas_cost)
}
fn trace_executed(&mut self, gas_used: U256, stack_push: &[U256], mem_diff: Option<(usize, &[u8])>, store_diff: Option<(U256, U256)>) {
self.vm_tracer.trace_executed(gas_used, stack_push, mem_diff, store_diff)
}
}
#[cfg(test)]
mod tests {
use util::*;
use engines::Engine;
use env_info::EnvInfo;
use evm::Ext;
use state::{State, Substate};
use tests::helpers::*;
use devtools::GuardedTempResult;
use super::*;
use trace::{NoopTracer, NoopVMTracer};
use types::executed::CallType;
fn get_test_origin() -> OriginInfo {
OriginInfo {
address: Address::zero(),
origin: Address::zero(),
gas_price: U256::zero(),
value: U256::zero()
}
}
fn get_test_env_info() -> EnvInfo {
EnvInfo {
number: 100,
author: 0.into(),
timestamp: 0,
difficulty: 0.into(),
last_hashes: Arc::new(vec![]),
gas_used: 0.into(),
gas_limit: 0.into(),
}
}
struct TestSetup {
state: GuardedTempResult<State>,
engine: Arc<Engine>,
sub_state: Substate,
env_info: EnvInfo
}
impl Default for TestSetup {
fn default() -> Self {
TestSetup::new()
}
}
impl TestSetup {
fn new() -> Self {
TestSetup {
state: get_temp_state(),
engine: get_test_spec().engine,
sub_state: Substate::new(),
env_info: get_test_env_info()
}
}
}
#[test]
fn can_be_created() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
assert_eq!(ext.env_info().number, 100);
}
#[test]
fn can_return_block_hash_no_env() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap());
assert_eq!(hash, H256::zero());
}
#[test]
fn can_return_block_hash() {
let test_hash = H256::from("afafafafafafafafafafafbcbcbcbcbcbcbcbcbcbeeeeeeeeeeeeedddddddddd");
let test_env_number = 0x120001;
let mut setup = TestSetup::new();
{
let env_info = &mut setup.env_info;
env_info.number = test_env_number;
let mut last_hashes = (*env_info.last_hashes).clone();
last_hashes.push(test_hash.clone());
env_info.last_hashes = Arc::new(last_hashes);
}
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap());
assert_eq!(test_hash, hash);
}
#[test]
#[should_panic]
fn can_call_fail_empty() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let mut output = vec![];
// this should panic because we have no balance on any account
ext.call(
&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap(),
&Address::new(),
&Address::new(),
Some(U256::from_str("0000000000000000000000000000000000000000000000000000000000150000").unwrap()),
&[],
&Address::new(),
&mut output,
CallType::Call
);
}
#[test]
fn can_log() {
let log_data = vec![120u8, 110u8];
let log_topics = vec![H256::from("af0fa234a6af46afa23faf23bcbc1c1cb4bcb7bcbe7e7e7ee3ee2edddddddddd")];
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
{
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
ext.log(log_topics, &log_data);
}
assert_eq!(setup.sub_state.logs.len(), 1);
}
#[test]
fn can_suicide() {
let refund_account = &Address::new();
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
{
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
ext.suicide(refund_account);
}
assert_eq!(setup.sub_state.suicides.len(), 1);
}
}
|
{
trace!("ext: blockhash({}) -> null self.env_info.number={}\n", number, self.env_info.number);
H256::zero()
}
|
conditional_block
|
externalities.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Transaction Execution environment.
use util::*;
use action_params::{ActionParams, ActionValue};
use state::{State, Substate};
use engines::Engine;
use env_info::EnvInfo;
use executive::*;
use evm::{self, Schedule, Ext, ContractCreateResult, MessageCallResult, Factory};
use types::executed::CallType;
use trace::{Tracer, VMTracer};
/// Policy for handling output data on `RETURN` opcode.
pub enum OutputPolicy<'a, 'b> {
/// Return reference to fixed sized output.
/// Used for message calls.
Return(BytesRef<'a>, Option<&'b mut Bytes>),
/// Init new contract as soon as `RETURN` is called.
InitContract(Option<&'b mut Bytes>),
}
/// Transaction properties that externalities need to know about.
pub struct OriginInfo {
address: Address,
origin: Address,
gas_price: U256,
value: U256
}
impl OriginInfo {
/// Populates origin info from action params.
pub fn from(params: &ActionParams) -> Self {
OriginInfo {
address: params.address.clone(),
origin: params.origin.clone(),
gas_price: params.gas_price,
value: match params.value {
ActionValue::Transfer(val) | ActionValue::Apparent(val) => val
}
}
}
}
/// Implementation of evm Externalities.
pub struct Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
state: &'a mut State,
env_info: &'a EnvInfo,
engine: &'a Engine,
vm_factory: &'a Factory,
depth: usize,
origin_info: OriginInfo,
substate: &'a mut Substate,
schedule: Schedule,
output: OutputPolicy<'a, 'a>,
tracer: &'a mut T,
vm_tracer: &'a mut V,
}
impl<'a, T, V> Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
#[cfg_attr(feature="dev", allow(too_many_arguments))]
/// Basic `Externalities` constructor.
pub fn new(state: &'a mut State,
env_info: &'a EnvInfo,
engine: &'a Engine,
vm_factory: &'a Factory,
depth: usize,
origin_info: OriginInfo,
substate: &'a mut Substate,
output: OutputPolicy<'a, 'a>,
tracer: &'a mut T,
vm_tracer: &'a mut V,
) -> Self {
Externalities {
state: state,
env_info: env_info,
engine: engine,
vm_factory: vm_factory,
depth: depth,
origin_info: origin_info,
substate: substate,
schedule: engine.schedule(env_info),
output: output,
tracer: tracer,
vm_tracer: vm_tracer,
}
}
}
impl<'a, T, V> Ext for Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer {
fn storage_at(&self, key: &H256) -> H256 {
self.state.storage_at(&self.origin_info.address, key)
}
fn set_storage(&mut self, key: H256, value: H256) {
self.state.set_storage(&self.origin_info.address, key, value)
}
fn exists(&self, address: &Address) -> bool {
self.state.exists(address)
}
fn balance(&self, address: &Address) -> U256 {
self.state.balance(address)
}
fn blockhash(&self, number: &U256) -> H256 {
// TODO: comment out what this function expects from env_info, since it will produce panics if the latter is inconsistent
match *number < U256::from(self.env_info.number) && number.low_u64() >= cmp::max(256, self.env_info.number) - 256 {
true => {
let index = self.env_info.number - number.low_u64() - 1;
assert!(index < self.env_info.last_hashes.len() as u64, format!("Inconsistent env_info, should contain at least {:?} last hashes", index+1));
let r = self.env_info.last_hashes[index as usize].clone();
trace!("ext: blockhash({}) -> {} self.env_info.number={}\n", number, r, self.env_info.number);
r
},
false => {
trace!("ext: blockhash({}) -> null self.env_info.number={}\n", number, self.env_info.number);
H256::zero()
},
}
}
fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> ContractCreateResult {
// create new contract address
let address = contract_address(&self.origin_info.address, &self.state.nonce(&self.origin_info.address));
// prepare the params
let params = ActionParams {
code_address: address.clone(),
address: address.clone(),
sender: self.origin_info.address.clone(),
origin: self.origin_info.origin.clone(),
gas: *gas,
gas_price: self.origin_info.gas_price,
value: ActionValue::Transfer(*value),
code: Some(Arc::new(code.to_vec())),
code_hash: code.sha3(),
data: None,
call_type: CallType::None,
};
self.state.inc_nonce(&self.origin_info.address);
let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.vm_factory, self.depth);
// TODO: handle internal error separately
match ex.create(params, self.substate, self.tracer, self.vm_tracer) {
Ok(gas_left) => {
self.substate.contracts_created.push(address.clone());
ContractCreateResult::Created(address, gas_left)
},
_ => ContractCreateResult::Failed
}
}
fn call(&mut self,
gas: &U256,
sender_address: &Address,
receive_address: &Address,
value: Option<U256>,
data: &[u8],
code_address: &Address,
output: &mut [u8],
call_type: CallType
) -> MessageCallResult {
trace!(target: "externalities", "call");
let mut params = ActionParams {
sender: sender_address.clone(),
address: receive_address.clone(),
value: ActionValue::Apparent(self.origin_info.value),
code_address: code_address.clone(),
origin: self.origin_info.origin.clone(),
gas: *gas,
gas_price: self.origin_info.gas_price,
code: self.state.code(code_address),
code_hash: self.state.code_hash(code_address),
data: Some(data.to_vec()),
call_type: call_type,
};
if let Some(value) = value {
params.value = ActionValue::Transfer(value);
}
let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.vm_factory, self.depth);
match ex.call(params, self.substate, BytesRef::Fixed(output), self.tracer, self.vm_tracer) {
Ok(gas_left) => MessageCallResult::Success(gas_left),
_ => MessageCallResult::Failed
}
}
fn extcode(&self, address: &Address) -> Arc<Bytes> {
self.state.code(address).unwrap_or_else(|| Arc::new(vec![]))
}
fn extcodesize(&self, address: &Address) -> usize {
self.state.code_size(address).unwrap_or(0)
}
#[cfg_attr(feature="dev", allow(match_ref_pats))]
fn ret(mut self, gas: &U256, data: &[u8]) -> evm::Result<U256>
where Self: Sized {
let handle_copy = |to: &mut Option<&mut Bytes>| {
to.as_mut().map(|b| **b = data.to_owned());
};
match self.output {
OutputPolicy::Return(BytesRef::Fixed(ref mut slice), ref mut copy) => {
handle_copy(copy);
let len = cmp::min(slice.len(), data.len());
(&mut slice[..len]).copy_from_slice(&data[..len]);
Ok(*gas)
},
OutputPolicy::Return(BytesRef::Flexible(ref mut vec), ref mut copy) => {
handle_copy(copy);
vec.clear();
vec.extend_from_slice(data);
Ok(*gas)
},
OutputPolicy::InitContract(ref mut copy) => {
let return_cost = U256::from(data.len()) * U256::from(self.schedule.create_data_gas);
if return_cost > *gas {
return match self.schedule.exceptional_failed_code_deposit {
|
true => Err(evm::Error::OutOfGas),
false => Ok(*gas)
}
}
handle_copy(copy);
let mut code = vec![];
code.extend_from_slice(data);
self.state.init_code(&self.origin_info.address, code);
Ok(*gas - return_cost)
}
}
}
fn log(&mut self, topics: Vec<H256>, data: &[u8]) {
use log_entry::LogEntry;
let address = self.origin_info.address.clone();
self.substate.logs.push(LogEntry {
address: address,
topics: topics,
data: data.to_vec()
});
}
fn suicide(&mut self, refund_address: &Address) {
let address = self.origin_info.address.clone();
let balance = self.balance(&address);
if &address == refund_address {
// TODO [todr] To be consisted with CPP client we set balance to 0 in that case.
self.state.sub_balance(&address, &balance);
} else {
trace!("Suiciding {} -> {} (xfer: {})", address, refund_address, balance);
self.state.transfer_balance(&address, refund_address, &balance);
}
self.tracer.trace_suicide(address, balance, refund_address.clone());
self.substate.suicides.insert(address);
}
fn schedule(&self) -> &Schedule {
&self.schedule
}
fn env_info(&self) -> &EnvInfo {
self.env_info
}
fn depth(&self) -> usize {
self.depth
}
fn inc_sstore_clears(&mut self) {
self.substate.sstore_clears_count = self.substate.sstore_clears_count + U256::one();
}
fn trace_prepare_execute(&mut self, pc: usize, instruction: u8, gas_cost: &U256) -> bool {
self.vm_tracer.trace_prepare_execute(pc, instruction, gas_cost)
}
fn trace_executed(&mut self, gas_used: U256, stack_push: &[U256], mem_diff: Option<(usize, &[u8])>, store_diff: Option<(U256, U256)>) {
self.vm_tracer.trace_executed(gas_used, stack_push, mem_diff, store_diff)
}
}
#[cfg(test)]
mod tests {
use util::*;
use engines::Engine;
use env_info::EnvInfo;
use evm::Ext;
use state::{State, Substate};
use tests::helpers::*;
use devtools::GuardedTempResult;
use super::*;
use trace::{NoopTracer, NoopVMTracer};
use types::executed::CallType;
fn get_test_origin() -> OriginInfo {
OriginInfo {
address: Address::zero(),
origin: Address::zero(),
gas_price: U256::zero(),
value: U256::zero()
}
}
fn get_test_env_info() -> EnvInfo {
EnvInfo {
number: 100,
author: 0.into(),
timestamp: 0,
difficulty: 0.into(),
last_hashes: Arc::new(vec![]),
gas_used: 0.into(),
gas_limit: 0.into(),
}
}
struct TestSetup {
state: GuardedTempResult<State>,
engine: Arc<Engine>,
sub_state: Substate,
env_info: EnvInfo
}
impl Default for TestSetup {
fn default() -> Self {
TestSetup::new()
}
}
impl TestSetup {
fn new() -> Self {
TestSetup {
state: get_temp_state(),
engine: get_test_spec().engine,
sub_state: Substate::new(),
env_info: get_test_env_info()
}
}
}
#[test]
fn can_be_created() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
assert_eq!(ext.env_info().number, 100);
}
#[test]
fn can_return_block_hash_no_env() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap());
assert_eq!(hash, H256::zero());
}
#[test]
fn can_return_block_hash() {
let test_hash = H256::from("afafafafafafafafafafafbcbcbcbcbcbcbcbcbcbeeeeeeeeeeeeedddddddddd");
let test_env_number = 0x120001;
let mut setup = TestSetup::new();
{
let env_info = &mut setup.env_info;
env_info.number = test_env_number;
let mut last_hashes = (*env_info.last_hashes).clone();
last_hashes.push(test_hash.clone());
env_info.last_hashes = Arc::new(last_hashes);
}
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let hash = ext.blockhash(&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap());
assert_eq!(test_hash, hash);
}
#[test]
#[should_panic]
fn can_call_fail_empty() {
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
let mut output = vec![];
// this should panic because we have no balance on any account
ext.call(
&U256::from_str("0000000000000000000000000000000000000000000000000000000000120000").unwrap(),
&Address::new(),
&Address::new(),
Some(U256::from_str("0000000000000000000000000000000000000000000000000000000000150000").unwrap()),
&[],
&Address::new(),
&mut output,
CallType::Call
);
}
#[test]
fn can_log() {
let log_data = vec![120u8, 110u8];
let log_topics = vec![H256::from("af0fa234a6af46afa23faf23bcbc1c1cb4bcb7bcbe7e7e7ee3ee2edddddddddd")];
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
{
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
ext.log(log_topics, &log_data);
}
assert_eq!(setup.sub_state.logs.len(), 1);
}
#[test]
fn can_suicide() {
let refund_account = &Address::new();
let mut setup = TestSetup::new();
let state = setup.state.reference_mut();
let mut tracer = NoopTracer;
let mut vm_tracer = NoopVMTracer;
{
let vm_factory = Default::default();
let mut ext = Externalities::new(state, &setup.env_info, &*setup.engine, &vm_factory, 0, get_test_origin(), &mut setup.sub_state, OutputPolicy::InitContract(None), &mut tracer, &mut vm_tracer);
ext.suicide(refund_account);
}
assert_eq!(setup.sub_state.suicides.len(), 1);
}
}
|
random_line_split
|
|
default.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, Expr};
use codemap::Span;
use ext::base::{ExtCtxt, Annotatable};
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use ptr::P;
pub fn expand_deriving_default(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable))
{
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_std!(cx, core::default::Default),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: Vec::new(),
ret_ty: Self_,
attributes: attrs,
is_unsafe: false,
combine_substructure: combine_substructure(Box::new(|a, b, c| {
default_substructure(a, b, c)
}))
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
return match *substr.fields {
StaticStruct(_, ref summary) =>
|
StaticEnum(..) => {
cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
// let compilation continue
cx.expr_usize(trait_span, 0)
}
_ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`")
};
}
|
{
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
}
}
Named(ref fields) => {
let default_fields = fields.iter().map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
}).collect();
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
}
}
}
|
conditional_block
|
default.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, Expr};
use codemap::Span;
use ext::base::{ExtCtxt, Annotatable};
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use ptr::P;
pub fn expand_deriving_default(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable))
{
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_std!(cx, core::default::Default),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
|
attributes: attrs,
is_unsafe: false,
combine_substructure: combine_substructure(Box::new(|a, b, c| {
default_substructure(a, b, c)
}))
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
return match *substr.fields {
StaticStruct(_, ref summary) => {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
}
}
Named(ref fields) => {
let default_fields = fields.iter().map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
}).collect();
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
}
}
}
StaticEnum(..) => {
cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
// let compilation continue
cx.expr_usize(trait_span, 0)
}
_ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`")
};
}
|
explicit_self: None,
args: Vec::new(),
ret_ty: Self_,
|
random_line_split
|
default.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, Expr};
use codemap::Span;
use ext::base::{ExtCtxt, Annotatable};
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use ptr::P;
pub fn expand_deriving_default(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable))
|
}))
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
return match *substr.fields {
StaticStruct(_, ref summary) => {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
}
}
Named(ref fields) => {
let default_fields = fields.iter().map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
}).collect();
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
}
}
}
StaticEnum(..) => {
cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
// let compilation continue
cx.expr_usize(trait_span, 0)
}
_ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`")
};
}
|
{
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_std!(cx, core::default::Default),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: Vec::new(),
ret_ty: Self_,
attributes: attrs,
is_unsafe: false,
combine_substructure: combine_substructure(Box::new(|a, b, c| {
default_substructure(a, b, c)
|
identifier_body
|
default.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, Expr};
use codemap::Span;
use ext::base::{ExtCtxt, Annotatable};
use ext::build::AstBuilder;
use ext::deriving::generic::*;
use ext::deriving::generic::ty::*;
use parse::token::InternedString;
use ptr::P;
pub fn expand_deriving_default(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut FnMut(Annotatable))
{
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_std!(cx, core::default::Default),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
methods: vec!(
MethodDef {
name: "default",
generics: LifetimeBounds::empty(),
explicit_self: None,
args: Vec::new(),
ret_ty: Self_,
attributes: attrs,
is_unsafe: false,
combine_substructure: combine_substructure(Box::new(|a, b, c| {
default_substructure(a, b, c)
}))
}
),
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
fn
|
(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
let default_ident = vec!(
cx.ident_of_std("core"),
cx.ident_of("default"),
cx.ident_of("Default"),
cx.ident_of("default")
);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
return match *substr.fields {
StaticStruct(_, ref summary) => {
match *summary {
Unnamed(ref fields) => {
if fields.is_empty() {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
}
}
Named(ref fields) => {
let default_fields = fields.iter().map(|&(ident, span)| {
cx.field_imm(span, ident, default_call(span))
}).collect();
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
}
}
}
StaticEnum(..) => {
cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs");
// let compilation continue
cx.expr_usize(trait_span, 0)
}
_ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`")
};
}
|
default_substructure
|
identifier_name
|
gecko.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Specified types for legacy Gecko-only properties.
use crate::parser::{Parse, ParserContext};
use crate::values::computed::length::CSSPixelLength;
use crate::values::computed::{self, LengthPercentage};
use crate::values::generics::gecko::ScrollSnapPoint as GenericScrollSnapPoint;
use crate::values::generics::rect::Rect;
use crate::values::specified::length::LengthPercentage as SpecifiedLengthPercentage;
use cssparser::{Parser, Token};
use std::fmt;
use style_traits::values::SequenceWriter;
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
/// A specified type for scroll snap points.
pub type ScrollSnapPoint = GenericScrollSnapPoint<SpecifiedLengthPercentage>;
impl Parse for ScrollSnapPoint {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
return Ok(GenericScrollSnapPoint::None);
}
input.expect_function_matching("repeat")?;
// FIXME(emilio): This won't clamp properly when animating.
let length = input
.parse_nested_block(|i| SpecifiedLengthPercentage::parse_non_negative(context, i))?;
Ok(GenericScrollSnapPoint::Repeat(length))
}
}
fn parse_pixel_or_percent<'i, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<LengthPercentage, ParseError<'i>> {
let location = input.current_source_location();
let token = input.next()?;
let value = match *token {
Token::Dimension {
value, ref unit,..
} => {
match_ignore_ascii_case! { unit,
"px" => Ok(LengthPercentage::new(CSSPixelLength::new(value), None)),
_ => Err(()),
}
},
Token::Percentage { unit_value,.. } => Ok(LengthPercentage::new_percent(
computed::Percentage(unit_value),
)),
_ => Err(()),
};
value.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
/// The value of an IntersectionObserver's rootMargin property.
///
/// Only bare px or percentage values are allowed. Other length units and
/// calc() values are not allowed.
///
/// <https://w3c.github.io/IntersectionObserver/#parse-a-root-margin>
#[repr(transparent)]
pub struct IntersectionObserverRootMargin(pub Rect<LengthPercentage>);
impl Parse for IntersectionObserverRootMargin {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let rect = Rect::parse_with(context, input, parse_pixel_or_percent)?;
Ok(IntersectionObserverRootMargin(rect))
}
}
// Strictly speaking this is not ToCss. It's serializing for DOM. But
// we can just reuse the infrastructure of this.
//
// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-rootmargin>
impl ToCss for IntersectionObserverRootMargin {
fn
|
<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
// We cannot use the ToCss impl of Rect, because that would
// merge items when they are equal. We want to list them all.
let mut writer = SequenceWriter::new(dest, " ");
let rect = &self.0;
writer.item(&rect.0)?;
writer.item(&rect.1)?;
writer.item(&rect.2)?;
writer.item(&rect.3)
}
}
|
to_css
|
identifier_name
|
gecko.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Specified types for legacy Gecko-only properties.
use crate::parser::{Parse, ParserContext};
use crate::values::computed::length::CSSPixelLength;
use crate::values::computed::{self, LengthPercentage};
use crate::values::generics::gecko::ScrollSnapPoint as GenericScrollSnapPoint;
use crate::values::generics::rect::Rect;
use crate::values::specified::length::LengthPercentage as SpecifiedLengthPercentage;
use cssparser::{Parser, Token};
use std::fmt;
use style_traits::values::SequenceWriter;
use style_traits::{CssWriter, ParseError, StyleParseErrorKind, ToCss};
/// A specified type for scroll snap points.
pub type ScrollSnapPoint = GenericScrollSnapPoint<SpecifiedLengthPercentage>;
impl Parse for ScrollSnapPoint {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
return Ok(GenericScrollSnapPoint::None);
}
input.expect_function_matching("repeat")?;
// FIXME(emilio): This won't clamp properly when animating.
let length = input
.parse_nested_block(|i| SpecifiedLengthPercentage::parse_non_negative(context, i))?;
Ok(GenericScrollSnapPoint::Repeat(length))
}
}
fn parse_pixel_or_percent<'i, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<LengthPercentage, ParseError<'i>> {
let location = input.current_source_location();
let token = input.next()?;
let value = match *token {
Token::Dimension {
value, ref unit,..
} => {
match_ignore_ascii_case! { unit,
"px" => Ok(LengthPercentage::new(CSSPixelLength::new(value), None)),
_ => Err(()),
}
},
Token::Percentage { unit_value,.. } => Ok(LengthPercentage::new_percent(
computed::Percentage(unit_value),
)),
_ => Err(()),
};
value.map_err(|()| location.new_custom_error(StyleParseErrorKind::UnspecifiedError))
}
/// The value of an IntersectionObserver's rootMargin property.
///
/// Only bare px or percentage values are allowed. Other length units and
/// calc() values are not allowed.
|
/// <https://w3c.github.io/IntersectionObserver/#parse-a-root-margin>
#[repr(transparent)]
pub struct IntersectionObserverRootMargin(pub Rect<LengthPercentage>);
impl Parse for IntersectionObserverRootMargin {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
let rect = Rect::parse_with(context, input, parse_pixel_or_percent)?;
Ok(IntersectionObserverRootMargin(rect))
}
}
// Strictly speaking this is not ToCss. It's serializing for DOM. But
// we can just reuse the infrastructure of this.
//
// <https://w3c.github.io/IntersectionObserver/#dom-intersectionobserver-rootmargin>
impl ToCss for IntersectionObserverRootMargin {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
// We cannot use the ToCss impl of Rect, because that would
// merge items when they are equal. We want to list them all.
let mut writer = SequenceWriter::new(dest, " ");
let rect = &self.0;
writer.item(&rect.0)?;
writer.item(&rect.1)?;
writer.item(&rect.2)?;
writer.item(&rect.3)
}
}
|
///
|
random_line_split
|
directconnect.rs
|
#![cfg(feature = "directconnect")]
extern crate rusoto;
use rusoto::directconnect::{DirectConnectClient, DescribeConnectionsRequest, DescribeConnectionsError};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn should_describe_connections() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = DescribeConnectionsRequest::default();
client.describe_connections(&request).unwrap();
}
#[test]
fn should_fail_gracefully()
|
#[test]
fn should_describe_locations() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
client.describe_locations().unwrap();
}
#[test]
fn should_describe_virtual_gateways() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
client.describe_virtual_gateways().unwrap();
}
|
{
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = DescribeConnectionsRequest {
connection_id: Some("invalid".to_string())
};
match client.describe_connections(&request) {
Err(DescribeConnectionsError::DirectConnectClient(msg)) => assert!(msg.contains("Connection ID")),
err @ _ => panic!("Expected DirectConnectClient error, got {:#?}", err)
};
}
|
identifier_body
|
directconnect.rs
|
#![cfg(feature = "directconnect")]
extern crate rusoto;
use rusoto::directconnect::{DirectConnectClient, DescribeConnectionsRequest, DescribeConnectionsError};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn should_describe_connections() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = DescribeConnectionsRequest::default();
client.describe_connections(&request).unwrap();
}
#[test]
fn should_fail_gracefully() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = DescribeConnectionsRequest {
connection_id: Some("invalid".to_string())
};
match client.describe_connections(&request) {
Err(DescribeConnectionsError::DirectConnectClient(msg)) => assert!(msg.contains("Connection ID")),
err @ _ => panic!("Expected DirectConnectClient error, got {:#?}", err)
};
}
#[test]
fn should_describe_locations() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
client.describe_locations().unwrap();
}
#[test]
fn
|
() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
client.describe_virtual_gateways().unwrap();
}
|
should_describe_virtual_gateways
|
identifier_name
|
directconnect.rs
|
#![cfg(feature = "directconnect")]
extern crate rusoto;
use rusoto::directconnect::{DirectConnectClient, DescribeConnectionsRequest, DescribeConnectionsError};
use rusoto::{DefaultCredentialsProvider, Region};
use rusoto::default_tls_client;
#[test]
fn should_describe_connections() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = DescribeConnectionsRequest::default();
client.describe_connections(&request).unwrap();
}
|
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
let request = DescribeConnectionsRequest {
connection_id: Some("invalid".to_string())
};
match client.describe_connections(&request) {
Err(DescribeConnectionsError::DirectConnectClient(msg)) => assert!(msg.contains("Connection ID")),
err @ _ => panic!("Expected DirectConnectClient error, got {:#?}", err)
};
}
#[test]
fn should_describe_locations() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
client.describe_locations().unwrap();
}
#[test]
fn should_describe_virtual_gateways() {
let credentials = DefaultCredentialsProvider::new().unwrap();
let client = DirectConnectClient::new(default_tls_client().unwrap(), credentials, Region::UsEast1);
client.describe_virtual_gateways().unwrap();
}
|
#[test]
fn should_fail_gracefully() {
|
random_line_split
|
thread.rs
|
use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::os::windows::io::{AsRawHandle, FromRawHandle};
use crate::ptr;
use crate::sys::c;
use crate::sys::handle::Handle;
use crate::sys::stack_overflow;
use crate::time::Duration;
use libc::c_void;
use super::to_u16s;
pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
pub struct Thread {
handle: Handle,
}
impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
let p = Box::into_raw(box p);
// FIXME On UNIX, we guard against stack sizes that are too small but
// that's because pthreads enforces that stacks are at least
// PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's
// just that below a certain threshold you can't do anything useful.
// That threshold is application and architecture-specific, however.
// Round up to the next 64 kB because that's what the NT kernel does,
// might as well make it explicit.
let stack_size = (stack + 0xfffe) & (!0xfffe);
let ret = c::CreateThread(
ptr::null_mut(),
stack_size,
thread_start,
p as *mut _,
c::STACK_SIZE_PARAM_IS_A_RESERVATION,
ptr::null_mut(),
);
return if ret as usize == 0 {
// The thread failed to start and as a result p was not consumed. Therefore, it is
// safe to reconstruct the box so that it gets deallocated.
drop(Box::from_raw(p));
Err(io::Error::last_os_error())
} else {
Ok(Thread { handle: Handle::from_raw_handle(ret) })
};
extern "system" fn
|
(main: *mut c_void) -> c::DWORD {
unsafe {
// Next, set up our stack overflow handler which may get triggered if we run
// out of stack.
let _handler = stack_overflow::Handler::new();
// Finally, let's run some code.
Box::from_raw(main as *mut Box<dyn FnOnce()>)();
}
0
}
}
pub fn set_name(name: &CStr) {
if let Ok(utf8) = name.to_str() {
if let Ok(utf16) = to_u16s(utf8) {
unsafe {
c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr());
};
};
};
}
pub fn join(self) {
let rc = unsafe { c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE) };
if rc == c::WAIT_FAILED {
panic!("failed to join on thread: {}", io::Error::last_os_error());
}
}
pub fn yield_now() {
// This function will return 0 if there are no other threads to execute,
// but this also means that the yield was useless so this isn't really a
// case that needs to be worried about.
unsafe {
c::SwitchToThread();
}
}
pub fn sleep(dur: Duration) {
unsafe { c::Sleep(super::dur2timeout(dur)) }
}
pub fn handle(&self) -> &Handle {
&self.handle
}
pub fn into_handle(self) -> Handle {
self.handle
}
}
pub fn available_parallelism() -> io::Result<NonZeroUsize> {
let res = unsafe {
let mut sysinfo: c::SYSTEM_INFO = crate::mem::zeroed();
c::GetSystemInfo(&mut sysinfo);
sysinfo.dwNumberOfProcessors as usize
};
match res {
0 => Err(io::Error::new_const(
io::ErrorKind::NotFound,
&"The number of hardware threads is not known for the target platform",
)),
cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus) }),
}
}
#[cfg_attr(test, allow(dead_code))]
pub mod guard {
pub type Guard =!;
pub unsafe fn current() -> Option<Guard> {
None
}
pub unsafe fn init() -> Option<Guard> {
None
}
}
|
thread_start
|
identifier_name
|
thread.rs
|
use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::os::windows::io::{AsRawHandle, FromRawHandle};
use crate::ptr;
use crate::sys::c;
use crate::sys::handle::Handle;
use crate::sys::stack_overflow;
use crate::time::Duration;
use libc::c_void;
use super::to_u16s;
pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
pub struct Thread {
handle: Handle,
}
impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
let p = Box::into_raw(box p);
// FIXME On UNIX, we guard against stack sizes that are too small but
// that's because pthreads enforces that stacks are at least
// PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's
// just that below a certain threshold you can't do anything useful.
// That threshold is application and architecture-specific, however.
// Round up to the next 64 kB because that's what the NT kernel does,
// might as well make it explicit.
let stack_size = (stack + 0xfffe) & (!0xfffe);
let ret = c::CreateThread(
ptr::null_mut(),
stack_size,
thread_start,
p as *mut _,
c::STACK_SIZE_PARAM_IS_A_RESERVATION,
ptr::null_mut(),
);
return if ret as usize == 0 {
// The thread failed to start and as a result p was not consumed. Therefore, it is
// safe to reconstruct the box so that it gets deallocated.
drop(Box::from_raw(p));
Err(io::Error::last_os_error())
} else {
Ok(Thread { handle: Handle::from_raw_handle(ret) })
};
extern "system" fn thread_start(main: *mut c_void) -> c::DWORD {
unsafe {
// Next, set up our stack overflow handler which may get triggered if we run
// out of stack.
let _handler = stack_overflow::Handler::new();
// Finally, let's run some code.
Box::from_raw(main as *mut Box<dyn FnOnce()>)();
}
0
}
}
pub fn set_name(name: &CStr) {
if let Ok(utf8) = name.to_str() {
if let Ok(utf16) = to_u16s(utf8) {
unsafe {
c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr());
};
};
};
}
pub fn join(self) {
|
}
}
pub fn yield_now() {
// This function will return 0 if there are no other threads to execute,
// but this also means that the yield was useless so this isn't really a
// case that needs to be worried about.
unsafe {
c::SwitchToThread();
}
}
pub fn sleep(dur: Duration) {
unsafe { c::Sleep(super::dur2timeout(dur)) }
}
pub fn handle(&self) -> &Handle {
&self.handle
}
pub fn into_handle(self) -> Handle {
self.handle
}
}
pub fn available_parallelism() -> io::Result<NonZeroUsize> {
let res = unsafe {
let mut sysinfo: c::SYSTEM_INFO = crate::mem::zeroed();
c::GetSystemInfo(&mut sysinfo);
sysinfo.dwNumberOfProcessors as usize
};
match res {
0 => Err(io::Error::new_const(
io::ErrorKind::NotFound,
&"The number of hardware threads is not known for the target platform",
)),
cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus) }),
}
}
#[cfg_attr(test, allow(dead_code))]
pub mod guard {
pub type Guard =!;
pub unsafe fn current() -> Option<Guard> {
None
}
pub unsafe fn init() -> Option<Guard> {
None
}
}
|
let rc = unsafe { c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE) };
if rc == c::WAIT_FAILED {
panic!("failed to join on thread: {}", io::Error::last_os_error());
|
random_line_split
|
thread.rs
|
use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::os::windows::io::{AsRawHandle, FromRawHandle};
use crate::ptr;
use crate::sys::c;
use crate::sys::handle::Handle;
use crate::sys::stack_overflow;
use crate::time::Duration;
use libc::c_void;
use super::to_u16s;
pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
pub struct Thread {
handle: Handle,
}
impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
let p = Box::into_raw(box p);
// FIXME On UNIX, we guard against stack sizes that are too small but
// that's because pthreads enforces that stacks are at least
// PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's
// just that below a certain threshold you can't do anything useful.
// That threshold is application and architecture-specific, however.
// Round up to the next 64 kB because that's what the NT kernel does,
// might as well make it explicit.
let stack_size = (stack + 0xfffe) & (!0xfffe);
let ret = c::CreateThread(
ptr::null_mut(),
stack_size,
thread_start,
p as *mut _,
c::STACK_SIZE_PARAM_IS_A_RESERVATION,
ptr::null_mut(),
);
return if ret as usize == 0 {
// The thread failed to start and as a result p was not consumed. Therefore, it is
// safe to reconstruct the box so that it gets deallocated.
drop(Box::from_raw(p));
Err(io::Error::last_os_error())
} else {
Ok(Thread { handle: Handle::from_raw_handle(ret) })
};
extern "system" fn thread_start(main: *mut c_void) -> c::DWORD {
unsafe {
// Next, set up our stack overflow handler which may get triggered if we run
// out of stack.
let _handler = stack_overflow::Handler::new();
// Finally, let's run some code.
Box::from_raw(main as *mut Box<dyn FnOnce()>)();
}
0
}
}
pub fn set_name(name: &CStr) {
if let Ok(utf8) = name.to_str() {
if let Ok(utf16) = to_u16s(utf8) {
unsafe {
c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr());
};
};
};
}
pub fn join(self) {
let rc = unsafe { c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE) };
if rc == c::WAIT_FAILED
|
}
pub fn yield_now() {
// This function will return 0 if there are no other threads to execute,
// but this also means that the yield was useless so this isn't really a
// case that needs to be worried about.
unsafe {
c::SwitchToThread();
}
}
pub fn sleep(dur: Duration) {
unsafe { c::Sleep(super::dur2timeout(dur)) }
}
pub fn handle(&self) -> &Handle {
&self.handle
}
pub fn into_handle(self) -> Handle {
self.handle
}
}
pub fn available_parallelism() -> io::Result<NonZeroUsize> {
let res = unsafe {
let mut sysinfo: c::SYSTEM_INFO = crate::mem::zeroed();
c::GetSystemInfo(&mut sysinfo);
sysinfo.dwNumberOfProcessors as usize
};
match res {
0 => Err(io::Error::new_const(
io::ErrorKind::NotFound,
&"The number of hardware threads is not known for the target platform",
)),
cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus) }),
}
}
#[cfg_attr(test, allow(dead_code))]
pub mod guard {
pub type Guard =!;
pub unsafe fn current() -> Option<Guard> {
None
}
pub unsafe fn init() -> Option<Guard> {
None
}
}
|
{
panic!("failed to join on thread: {}", io::Error::last_os_error());
}
|
conditional_block
|
thread.rs
|
use crate::ffi::CStr;
use crate::io;
use crate::num::NonZeroUsize;
use crate::os::windows::io::{AsRawHandle, FromRawHandle};
use crate::ptr;
use crate::sys::c;
use crate::sys::handle::Handle;
use crate::sys::stack_overflow;
use crate::time::Duration;
use libc::c_void;
use super::to_u16s;
pub const DEFAULT_MIN_STACK_SIZE: usize = 2 * 1024 * 1024;
pub struct Thread {
handle: Handle,
}
impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
let p = Box::into_raw(box p);
// FIXME On UNIX, we guard against stack sizes that are too small but
// that's because pthreads enforces that stacks are at least
// PTHREAD_STACK_MIN bytes big. Windows has no such lower limit, it's
// just that below a certain threshold you can't do anything useful.
// That threshold is application and architecture-specific, however.
// Round up to the next 64 kB because that's what the NT kernel does,
// might as well make it explicit.
let stack_size = (stack + 0xfffe) & (!0xfffe);
let ret = c::CreateThread(
ptr::null_mut(),
stack_size,
thread_start,
p as *mut _,
c::STACK_SIZE_PARAM_IS_A_RESERVATION,
ptr::null_mut(),
);
return if ret as usize == 0 {
// The thread failed to start and as a result p was not consumed. Therefore, it is
// safe to reconstruct the box so that it gets deallocated.
drop(Box::from_raw(p));
Err(io::Error::last_os_error())
} else {
Ok(Thread { handle: Handle::from_raw_handle(ret) })
};
extern "system" fn thread_start(main: *mut c_void) -> c::DWORD {
unsafe {
// Next, set up our stack overflow handler which may get triggered if we run
// out of stack.
let _handler = stack_overflow::Handler::new();
// Finally, let's run some code.
Box::from_raw(main as *mut Box<dyn FnOnce()>)();
}
0
}
}
pub fn set_name(name: &CStr) {
if let Ok(utf8) = name.to_str() {
if let Ok(utf16) = to_u16s(utf8) {
unsafe {
c::SetThreadDescription(c::GetCurrentThread(), utf16.as_ptr());
};
};
};
}
pub fn join(self) {
let rc = unsafe { c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE) };
if rc == c::WAIT_FAILED {
panic!("failed to join on thread: {}", io::Error::last_os_error());
}
}
pub fn yield_now()
|
pub fn sleep(dur: Duration) {
unsafe { c::Sleep(super::dur2timeout(dur)) }
}
pub fn handle(&self) -> &Handle {
&self.handle
}
pub fn into_handle(self) -> Handle {
self.handle
}
}
pub fn available_parallelism() -> io::Result<NonZeroUsize> {
let res = unsafe {
let mut sysinfo: c::SYSTEM_INFO = crate::mem::zeroed();
c::GetSystemInfo(&mut sysinfo);
sysinfo.dwNumberOfProcessors as usize
};
match res {
0 => Err(io::Error::new_const(
io::ErrorKind::NotFound,
&"The number of hardware threads is not known for the target platform",
)),
cpus => Ok(unsafe { NonZeroUsize::new_unchecked(cpus) }),
}
}
#[cfg_attr(test, allow(dead_code))]
pub mod guard {
pub type Guard =!;
pub unsafe fn current() -> Option<Guard> {
None
}
pub unsafe fn init() -> Option<Guard> {
None
}
}
|
{
// This function will return 0 if there are no other threads to execute,
// but this also means that the yield was useless so this isn't really a
// case that needs to be worried about.
unsafe {
c::SwitchToThread();
}
}
|
identifier_body
|
htmlobjectelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding::HTMLObjectElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::node::{Node, window_from_node};
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use net_traits::image::base::Image;
use std::sync::Arc;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLObjectElement {
htmlelement: HTMLElement,
image: DOMRefCell<Option<Arc<Image>>>,
}
impl HTMLObjectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLObjectElement {
HTMLObjectElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document),
image: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn
|
(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLObjectElement> {
let element = HTMLObjectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap)
}
}
trait ProcessDataURL {
fn process_data_url(&self);
}
impl<'a> ProcessDataURL for &'a HTMLObjectElement {
// Makes the local `data` member match the status of the `data` attribute and starts
/// prefetching the image. This method must be called after `data` is changed.
fn process_data_url(&self) {
let elem = self.upcast::<Element>();
// TODO: support other values
match (elem.get_attribute(&ns!(), &atom!("type")),
elem.get_attribute(&ns!(), &atom!("data"))) {
(None, Some(_uri)) => {
// TODO(gw): Prefetch the image here.
}
_ => { }
}
}
}
pub fn is_image_data(uri: &str) -> bool {
static TYPES: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"];
TYPES.iter().any(|&type_| uri.starts_with(type_))
}
impl HTMLObjectElementMethods for HTMLObjectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
}
impl VirtualMethods for HTMLObjectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("data") => {
if let AttributeMutation::Set(_) = mutation {
self.process_data_url();
}
},
_ => {},
}
}
}
impl FormControl for HTMLObjectElement {}
|
new
|
identifier_name
|
htmlobjectelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding::HTMLObjectElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::node::{Node, window_from_node};
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use net_traits::image::base::Image;
use std::sync::Arc;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLObjectElement {
htmlelement: HTMLElement,
image: DOMRefCell<Option<Arc<Image>>>,
}
impl HTMLObjectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLObjectElement {
HTMLObjectElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document),
image: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLObjectElement>
|
}
trait ProcessDataURL {
fn process_data_url(&self);
}
impl<'a> ProcessDataURL for &'a HTMLObjectElement {
// Makes the local `data` member match the status of the `data` attribute and starts
/// prefetching the image. This method must be called after `data` is changed.
fn process_data_url(&self) {
let elem = self.upcast::<Element>();
// TODO: support other values
match (elem.get_attribute(&ns!(), &atom!("type")),
elem.get_attribute(&ns!(), &atom!("data"))) {
(None, Some(_uri)) => {
// TODO(gw): Prefetch the image here.
}
_ => { }
}
}
}
pub fn is_image_data(uri: &str) -> bool {
static TYPES: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"];
TYPES.iter().any(|&type_| uri.starts_with(type_))
}
impl HTMLObjectElementMethods for HTMLObjectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
}
impl VirtualMethods for HTMLObjectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("data") => {
if let AttributeMutation::Set(_) = mutation {
self.process_data_url();
}
},
_ => {},
}
}
}
impl FormControl for HTMLObjectElement {}
|
{
let element = HTMLObjectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap)
}
|
identifier_body
|
htmlobjectelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding::HTMLObjectElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::node::{Node, window_from_node};
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use net_traits::image::base::Image;
use std::sync::Arc;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLObjectElement {
htmlelement: HTMLElement,
image: DOMRefCell<Option<Arc<Image>>>,
}
impl HTMLObjectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLObjectElement {
HTMLObjectElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document),
image: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLObjectElement> {
let element = HTMLObjectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLObjectElementBinding::Wrap)
}
}
trait ProcessDataURL {
fn process_data_url(&self);
}
impl<'a> ProcessDataURL for &'a HTMLObjectElement {
// Makes the local `data` member match the status of the `data` attribute and starts
/// prefetching the image. This method must be called after `data` is changed.
fn process_data_url(&self) {
let elem = self.upcast::<Element>();
// TODO: support other values
match (elem.get_attribute(&ns!(), &atom!("type")),
elem.get_attribute(&ns!(), &atom!("data"))) {
(None, Some(_uri)) => {
// TODO(gw): Prefetch the image here.
}
_ => { }
}
}
}
pub fn is_image_data(uri: &str) -> bool {
static TYPES: &'static [&'static str] = &["data:image/png", "data:image/gif", "data:image/jpeg"];
TYPES.iter().any(|&type_| uri.starts_with(type_))
}
impl HTMLObjectElementMethods for HTMLObjectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
}
impl VirtualMethods for HTMLObjectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("data") =>
|
,
_ => {},
}
}
}
impl FormControl for HTMLObjectElement {}
|
{
if let AttributeMutation::Set(_) = mutation {
self.process_data_url();
}
}
|
conditional_block
|
simple.rs
|
use std::env;
use std::io;
use std::io::{Error, Write};
use std::path::Path;
use std::sync::Arc;
use log::error;
use petgraph::Graph;
use tempdir::TempDir;
use crate::clang::compiler::ClangCompiler;
use crate::cluster::client::RemoteCompiler;
use crate::compiler::*;
use crate::config::Config;
use crate::vs::compiler::VsCompiler;
use crate::worker::execute_graph;
use crate::worker::{BuildAction, BuildGraph, BuildResult, BuildTask};
pub fn supported_compilers(temp_dir: &Arc<TempDir>) -> CompilerGroup {
CompilerGroup::new()
.add(VsCompiler::new(temp_dir))
.add(ClangCompiler::new())
}
pub fn create_temp_dir() -> Result<Arc<TempDir>, Error>
|
pub fn simple_compile<C, F>(exec: &str, factory: F) -> i32
where
C: Compiler,
F: FnOnce(&Config) -> Result<C, Error>,
{
let config = match Config::new() {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR: Can't load configuration {}", e);
return 501;
}
};
let state = match SharedState::new(&config) {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR: Can't create shared state {}", e);
return 502;
}
};
let compiler = match factory(&config) {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR: Can't create compiler instance {}", e);
return 503;
}
};
match compile(&config, &state, exec, compiler) {
Ok(status) => status.unwrap_or(503),
Err(e) => {
println!("FATAL ERROR: {}", e);
500
}
}
}
pub fn compile<C>(
config: &Config,
state: &SharedState,
exec: &str,
compiler: C,
) -> Result<Option<i32>, Error>
where
C: Compiler,
{
let args: Vec<String> = env::args().collect();
let command_info = CommandInfo::simple(Path::new(exec));
let remote = RemoteCompiler::new(&config.coordinator, compiler);
let actions = BuildAction::create_tasks(&remote, command_info, &args[1..], exec);
let mut build_graph: BuildGraph = Graph::new();
for action in actions.into_iter() {
build_graph.add_node(Arc::new(BuildTask {
title: action.title().into_owned(),
action,
}));
}
let result = execute_graph(state, build_graph, config.process_limit, print_task_result);
println!("{}", state.statistic.to_string());
result
}
fn print_task_result(result: BuildResult) -> Result<(), Error> {
match result.result {
Ok(ref output) => {
io::stdout().write_all(&output.stdout)?;
io::stderr().write_all(&output.stderr)?;
}
Err(_) => {}
}
Ok(())
}
|
{
TempDir::new("octobuild").map(Arc::new)
}
|
identifier_body
|
simple.rs
|
use std::env;
use std::io;
use std::io::{Error, Write};
use std::path::Path;
use std::sync::Arc;
use log::error;
use petgraph::Graph;
use tempdir::TempDir;
use crate::clang::compiler::ClangCompiler;
use crate::cluster::client::RemoteCompiler;
use crate::compiler::*;
use crate::config::Config;
use crate::vs::compiler::VsCompiler;
use crate::worker::execute_graph;
use crate::worker::{BuildAction, BuildGraph, BuildResult, BuildTask};
pub fn supported_compilers(temp_dir: &Arc<TempDir>) -> CompilerGroup {
CompilerGroup::new()
.add(VsCompiler::new(temp_dir))
.add(ClangCompiler::new())
}
pub fn create_temp_dir() -> Result<Arc<TempDir>, Error> {
TempDir::new("octobuild").map(Arc::new)
}
pub fn simple_compile<C, F>(exec: &str, factory: F) -> i32
where
C: Compiler,
F: FnOnce(&Config) -> Result<C, Error>,
{
let config = match Config::new() {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR: Can't load configuration {}", e);
return 501;
}
};
let state = match SharedState::new(&config) {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR: Can't create shared state {}", e);
return 502;
}
};
let compiler = match factory(&config) {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR: Can't create compiler instance {}", e);
return 503;
}
};
match compile(&config, &state, exec, compiler) {
Ok(status) => status.unwrap_or(503),
Err(e) => {
println!("FATAL ERROR: {}", e);
500
}
}
}
pub fn
|
<C>(
config: &Config,
state: &SharedState,
exec: &str,
compiler: C,
) -> Result<Option<i32>, Error>
where
C: Compiler,
{
let args: Vec<String> = env::args().collect();
let command_info = CommandInfo::simple(Path::new(exec));
let remote = RemoteCompiler::new(&config.coordinator, compiler);
let actions = BuildAction::create_tasks(&remote, command_info, &args[1..], exec);
let mut build_graph: BuildGraph = Graph::new();
for action in actions.into_iter() {
build_graph.add_node(Arc::new(BuildTask {
title: action.title().into_owned(),
action,
}));
}
let result = execute_graph(state, build_graph, config.process_limit, print_task_result);
println!("{}", state.statistic.to_string());
result
}
fn print_task_result(result: BuildResult) -> Result<(), Error> {
match result.result {
Ok(ref output) => {
io::stdout().write_all(&output.stdout)?;
io::stderr().write_all(&output.stderr)?;
}
Err(_) => {}
}
Ok(())
}
|
compile
|
identifier_name
|
simple.rs
|
use std::env;
use std::io;
use std::io::{Error, Write};
use std::path::Path;
use std::sync::Arc;
use log::error;
use petgraph::Graph;
use tempdir::TempDir;
use crate::clang::compiler::ClangCompiler;
use crate::cluster::client::RemoteCompiler;
use crate::compiler::*;
use crate::config::Config;
use crate::vs::compiler::VsCompiler;
use crate::worker::execute_graph;
use crate::worker::{BuildAction, BuildGraph, BuildResult, BuildTask};
pub fn supported_compilers(temp_dir: &Arc<TempDir>) -> CompilerGroup {
CompilerGroup::new()
.add(VsCompiler::new(temp_dir))
.add(ClangCompiler::new())
}
pub fn create_temp_dir() -> Result<Arc<TempDir>, Error> {
TempDir::new("octobuild").map(Arc::new)
}
pub fn simple_compile<C, F>(exec: &str, factory: F) -> i32
where
C: Compiler,
F: FnOnce(&Config) -> Result<C, Error>,
{
let config = match Config::new() {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR: Can't load configuration {}", e);
return 501;
}
};
let state = match SharedState::new(&config) {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR: Can't create shared state {}", e);
return 502;
}
};
let compiler = match factory(&config) {
Ok(v) => v,
Err(e) => {
error!("FATAL ERROR: Can't create compiler instance {}", e);
return 503;
}
};
match compile(&config, &state, exec, compiler) {
Ok(status) => status.unwrap_or(503),
Err(e) => {
println!("FATAL ERROR: {}", e);
500
}
}
}
pub fn compile<C>(
config: &Config,
state: &SharedState,
exec: &str,
compiler: C,
) -> Result<Option<i32>, Error>
where
|
let args: Vec<String> = env::args().collect();
let command_info = CommandInfo::simple(Path::new(exec));
let remote = RemoteCompiler::new(&config.coordinator, compiler);
let actions = BuildAction::create_tasks(&remote, command_info, &args[1..], exec);
let mut build_graph: BuildGraph = Graph::new();
for action in actions.into_iter() {
build_graph.add_node(Arc::new(BuildTask {
title: action.title().into_owned(),
action,
}));
}
let result = execute_graph(state, build_graph, config.process_limit, print_task_result);
println!("{}", state.statistic.to_string());
result
}
fn print_task_result(result: BuildResult) -> Result<(), Error> {
match result.result {
Ok(ref output) => {
io::stdout().write_all(&output.stdout)?;
io::stderr().write_all(&output.stderr)?;
}
Err(_) => {}
}
Ok(())
}
|
C: Compiler,
{
|
random_line_split
|
nodemap.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::Range;
use std::path::Path;
use anyhow::Result;
use indexedlog::{
log::{self, IndexOutput, Log},
DefaultOpenOptions,
};
use thiserror::Error;
use types::errors::KeyError;
use types::node::Node;
#[derive(Debug, Error)]
#[error("Node Map Error: {0:?}")]
struct NodeMapError(String);
impl From<NodeMapError> for KeyError {
fn from(err: NodeMapError) -> Self {
KeyError::new(err.into())
}
}
/// A persistent bidirectional mapping between two Nodes
///
/// [NodeMap] is implemented on top of [indexedlog::log::Log] to store a mapping between two kinds
/// of nodes.
pub struct NodeMap {
log: Log,
}
impl DefaultOpenOptions<log::OpenOptions> for NodeMap {
fn default_open_options() -> log::OpenOptions {
let first_index = |_data: &[u8]| vec![IndexOutput::Reference(0..20)];
let second_index = |_data: &[u8]| vec![IndexOutput::Reference(20..40)];
log::OpenOptions::new()
.create(true)
.index("first", first_index)
.index("second", second_index)
}
}
impl NodeMap {
pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
Ok(NodeMap {
log: Self::default_open_options().open(dir.as_ref())?,
})
}
pub fn flush(&mut self) -> Result<()> {
self.log.flush()?;
Ok(())
}
pub fn add(&mut self, first: &Node, second: &Node) -> Result<()> {
let mut buf = Vec::with_capacity(40);
buf.extend_from_slice(first.as_ref());
buf.extend_from_slice(second.as_ref());
self.log.append(buf).map_err(|e| e.into())
}
pub fn lookup_by_first(&self, first: &Node) -> Result<Option<Node>> {
self.lookup(first, 0, 20..40)
}
pub fn lookup_by_second(&self, second: &Node) -> Result<Option<Node>> {
self.lookup(second, 1, 0..20)
}
fn lookup(&self, key: &Node, index_id: usize, range: Range<usize>) -> Result<Option<Node>> {
let mut lookup_iter = self.log.lookup(index_id, key)?;
Ok(match lookup_iter.next() {
Some(result) => Some(Node::from_slice(&result?[range])?),
None => None,
})
}
pub fn iter<'a>(&'a self) -> Result<Box<dyn Iterator<Item = Result<(Node, Node)>> + 'a>>
|
}
let second = second.pop().unwrap();
Ok((Node::from_slice(&first)?, Node::from_slice(&second)?))
}
Err(e) => Err(e.into()),
}
});
Ok(Box::new(iter))
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::quickcheck;
use tempfile::TempDir;
quickcheck! {
fn test_roundtrip(pairs: Vec<(Node, Node)>) -> bool {
let mut pairs = pairs;
if pairs.len() == 0 {
return true;
}
let dir = TempDir::new().unwrap();
let mut map = NodeMap::open(dir).unwrap();
let last = pairs.pop().unwrap();
for (first, second) in pairs.iter() {
map.add(&first, &second).unwrap();
}
for (first, second) in pairs.iter() {
if first!= &map.lookup_by_second(second).unwrap().unwrap() {
return false;
}
if second!= &map.lookup_by_first(first).unwrap().unwrap() {
return false;
}
}
for value in vec![last.0, last.1].iter() {
if!map.lookup_by_first(value).unwrap().is_none() {
return false;
}
if!map.lookup_by_second(value).unwrap().is_none() {
return false;
}
}
let actual_pairs = map.iter().unwrap().collect::<Result<Vec<_>>>().unwrap();
actual_pairs == pairs
}
}
}
|
{
let iter = self.log.iter().map(move |entry| {
match entry {
Ok(data) => {
let mut first = self.log.index_func(0, &data)?;
if first.len() != 1 {
return Err(NodeMapError(format!(
"invalid index 1 keys in {:?}",
self.log.dir
))
.into());
}
let first = first.pop().unwrap();
let mut second = self.log.index_func(1, &data)?;
if second.len() != 1 {
return Err(NodeMapError(format!(
"invalid index 2 keys in {:?}",
self.log.dir
))
.into());
|
identifier_body
|
nodemap.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::Range;
use std::path::Path;
use anyhow::Result;
use indexedlog::{
log::{self, IndexOutput, Log},
DefaultOpenOptions,
};
use thiserror::Error;
use types::errors::KeyError;
use types::node::Node;
#[derive(Debug, Error)]
#[error("Node Map Error: {0:?}")]
struct NodeMapError(String);
impl From<NodeMapError> for KeyError {
fn from(err: NodeMapError) -> Self {
KeyError::new(err.into())
}
}
/// A persistent bidirectional mapping between two Nodes
///
/// [NodeMap] is implemented on top of [indexedlog::log::Log] to store a mapping between two kinds
/// of nodes.
pub struct NodeMap {
log: Log,
}
impl DefaultOpenOptions<log::OpenOptions> for NodeMap {
fn default_open_options() -> log::OpenOptions {
let first_index = |_data: &[u8]| vec![IndexOutput::Reference(0..20)];
let second_index = |_data: &[u8]| vec![IndexOutput::Reference(20..40)];
log::OpenOptions::new()
.create(true)
.index("first", first_index)
.index("second", second_index)
}
}
impl NodeMap {
pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
Ok(NodeMap {
log: Self::default_open_options().open(dir.as_ref())?,
})
}
pub fn flush(&mut self) -> Result<()> {
self.log.flush()?;
Ok(())
}
pub fn add(&mut self, first: &Node, second: &Node) -> Result<()> {
let mut buf = Vec::with_capacity(40);
buf.extend_from_slice(first.as_ref());
buf.extend_from_slice(second.as_ref());
self.log.append(buf).map_err(|e| e.into())
}
pub fn lookup_by_first(&self, first: &Node) -> Result<Option<Node>> {
self.lookup(first, 0, 20..40)
}
pub fn lookup_by_second(&self, second: &Node) -> Result<Option<Node>> {
self.lookup(second, 1, 0..20)
}
fn lookup(&self, key: &Node, index_id: usize, range: Range<usize>) -> Result<Option<Node>> {
let mut lookup_iter = self.log.lookup(index_id, key)?;
Ok(match lookup_iter.next() {
Some(result) => Some(Node::from_slice(&result?[range])?),
None => None,
})
}
pub fn iter<'a>(&'a self) -> Result<Box<dyn Iterator<Item = Result<(Node, Node)>> + 'a>> {
let iter = self.log.iter().map(move |entry| {
match entry {
Ok(data) => {
let mut first = self.log.index_func(0, &data)?;
if first.len()!= 1 {
return Err(NodeMapError(format!(
"invalid index 1 keys in {:?}",
self.log.dir
))
.into());
}
let first = first.pop().unwrap();
let mut second = self.log.index_func(1, &data)?;
if second.len()!= 1
|
let second = second.pop().unwrap();
Ok((Node::from_slice(&first)?, Node::from_slice(&second)?))
}
Err(e) => Err(e.into()),
}
});
Ok(Box::new(iter))
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::quickcheck;
use tempfile::TempDir;
quickcheck! {
fn test_roundtrip(pairs: Vec<(Node, Node)>) -> bool {
let mut pairs = pairs;
if pairs.len() == 0 {
return true;
}
let dir = TempDir::new().unwrap();
let mut map = NodeMap::open(dir).unwrap();
let last = pairs.pop().unwrap();
for (first, second) in pairs.iter() {
map.add(&first, &second).unwrap();
}
for (first, second) in pairs.iter() {
if first!= &map.lookup_by_second(second).unwrap().unwrap() {
return false;
}
if second!= &map.lookup_by_first(first).unwrap().unwrap() {
return false;
}
}
for value in vec![last.0, last.1].iter() {
if!map.lookup_by_first(value).unwrap().is_none() {
return false;
}
if!map.lookup_by_second(value).unwrap().is_none() {
return false;
}
}
let actual_pairs = map.iter().unwrap().collect::<Result<Vec<_>>>().unwrap();
actual_pairs == pairs
}
}
}
|
{
return Err(NodeMapError(format!(
"invalid index 2 keys in {:?}",
self.log.dir
))
.into());
}
|
conditional_block
|
nodemap.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::Range;
|
log::{self, IndexOutput, Log},
DefaultOpenOptions,
};
use thiserror::Error;
use types::errors::KeyError;
use types::node::Node;
#[derive(Debug, Error)]
#[error("Node Map Error: {0:?}")]
struct NodeMapError(String);
impl From<NodeMapError> for KeyError {
fn from(err: NodeMapError) -> Self {
KeyError::new(err.into())
}
}
/// A persistent bidirectional mapping between two Nodes
///
/// [NodeMap] is implemented on top of [indexedlog::log::Log] to store a mapping between two kinds
/// of nodes.
pub struct NodeMap {
log: Log,
}
impl DefaultOpenOptions<log::OpenOptions> for NodeMap {
fn default_open_options() -> log::OpenOptions {
let first_index = |_data: &[u8]| vec![IndexOutput::Reference(0..20)];
let second_index = |_data: &[u8]| vec![IndexOutput::Reference(20..40)];
log::OpenOptions::new()
.create(true)
.index("first", first_index)
.index("second", second_index)
}
}
impl NodeMap {
pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
Ok(NodeMap {
log: Self::default_open_options().open(dir.as_ref())?,
})
}
pub fn flush(&mut self) -> Result<()> {
self.log.flush()?;
Ok(())
}
pub fn add(&mut self, first: &Node, second: &Node) -> Result<()> {
let mut buf = Vec::with_capacity(40);
buf.extend_from_slice(first.as_ref());
buf.extend_from_slice(second.as_ref());
self.log.append(buf).map_err(|e| e.into())
}
pub fn lookup_by_first(&self, first: &Node) -> Result<Option<Node>> {
self.lookup(first, 0, 20..40)
}
pub fn lookup_by_second(&self, second: &Node) -> Result<Option<Node>> {
self.lookup(second, 1, 0..20)
}
fn lookup(&self, key: &Node, index_id: usize, range: Range<usize>) -> Result<Option<Node>> {
let mut lookup_iter = self.log.lookup(index_id, key)?;
Ok(match lookup_iter.next() {
Some(result) => Some(Node::from_slice(&result?[range])?),
None => None,
})
}
pub fn iter<'a>(&'a self) -> Result<Box<dyn Iterator<Item = Result<(Node, Node)>> + 'a>> {
let iter = self.log.iter().map(move |entry| {
match entry {
Ok(data) => {
let mut first = self.log.index_func(0, &data)?;
if first.len()!= 1 {
return Err(NodeMapError(format!(
"invalid index 1 keys in {:?}",
self.log.dir
))
.into());
}
let first = first.pop().unwrap();
let mut second = self.log.index_func(1, &data)?;
if second.len()!= 1 {
return Err(NodeMapError(format!(
"invalid index 2 keys in {:?}",
self.log.dir
))
.into());
}
let second = second.pop().unwrap();
Ok((Node::from_slice(&first)?, Node::from_slice(&second)?))
}
Err(e) => Err(e.into()),
}
});
Ok(Box::new(iter))
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::quickcheck;
use tempfile::TempDir;
quickcheck! {
fn test_roundtrip(pairs: Vec<(Node, Node)>) -> bool {
let mut pairs = pairs;
if pairs.len() == 0 {
return true;
}
let dir = TempDir::new().unwrap();
let mut map = NodeMap::open(dir).unwrap();
let last = pairs.pop().unwrap();
for (first, second) in pairs.iter() {
map.add(&first, &second).unwrap();
}
for (first, second) in pairs.iter() {
if first!= &map.lookup_by_second(second).unwrap().unwrap() {
return false;
}
if second!= &map.lookup_by_first(first).unwrap().unwrap() {
return false;
}
}
for value in vec![last.0, last.1].iter() {
if!map.lookup_by_first(value).unwrap().is_none() {
return false;
}
if!map.lookup_by_second(value).unwrap().is_none() {
return false;
}
}
let actual_pairs = map.iter().unwrap().collect::<Result<Vec<_>>>().unwrap();
actual_pairs == pairs
}
}
}
|
use std::path::Path;
use anyhow::Result;
use indexedlog::{
|
random_line_split
|
nodemap.rs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::ops::Range;
use std::path::Path;
use anyhow::Result;
use indexedlog::{
log::{self, IndexOutput, Log},
DefaultOpenOptions,
};
use thiserror::Error;
use types::errors::KeyError;
use types::node::Node;
#[derive(Debug, Error)]
#[error("Node Map Error: {0:?}")]
struct NodeMapError(String);
impl From<NodeMapError> for KeyError {
fn from(err: NodeMapError) -> Self {
KeyError::new(err.into())
}
}
/// A persistent bidirectional mapping between two Nodes
///
/// [NodeMap] is implemented on top of [indexedlog::log::Log] to store a mapping between two kinds
/// of nodes.
pub struct
|
{
log: Log,
}
impl DefaultOpenOptions<log::OpenOptions> for NodeMap {
fn default_open_options() -> log::OpenOptions {
let first_index = |_data: &[u8]| vec![IndexOutput::Reference(0..20)];
let second_index = |_data: &[u8]| vec![IndexOutput::Reference(20..40)];
log::OpenOptions::new()
.create(true)
.index("first", first_index)
.index("second", second_index)
}
}
impl NodeMap {
pub fn open(dir: impl AsRef<Path>) -> Result<Self> {
Ok(NodeMap {
log: Self::default_open_options().open(dir.as_ref())?,
})
}
pub fn flush(&mut self) -> Result<()> {
self.log.flush()?;
Ok(())
}
pub fn add(&mut self, first: &Node, second: &Node) -> Result<()> {
let mut buf = Vec::with_capacity(40);
buf.extend_from_slice(first.as_ref());
buf.extend_from_slice(second.as_ref());
self.log.append(buf).map_err(|e| e.into())
}
pub fn lookup_by_first(&self, first: &Node) -> Result<Option<Node>> {
self.lookup(first, 0, 20..40)
}
pub fn lookup_by_second(&self, second: &Node) -> Result<Option<Node>> {
self.lookup(second, 1, 0..20)
}
fn lookup(&self, key: &Node, index_id: usize, range: Range<usize>) -> Result<Option<Node>> {
let mut lookup_iter = self.log.lookup(index_id, key)?;
Ok(match lookup_iter.next() {
Some(result) => Some(Node::from_slice(&result?[range])?),
None => None,
})
}
pub fn iter<'a>(&'a self) -> Result<Box<dyn Iterator<Item = Result<(Node, Node)>> + 'a>> {
let iter = self.log.iter().map(move |entry| {
match entry {
Ok(data) => {
let mut first = self.log.index_func(0, &data)?;
if first.len()!= 1 {
return Err(NodeMapError(format!(
"invalid index 1 keys in {:?}",
self.log.dir
))
.into());
}
let first = first.pop().unwrap();
let mut second = self.log.index_func(1, &data)?;
if second.len()!= 1 {
return Err(NodeMapError(format!(
"invalid index 2 keys in {:?}",
self.log.dir
))
.into());
}
let second = second.pop().unwrap();
Ok((Node::from_slice(&first)?, Node::from_slice(&second)?))
}
Err(e) => Err(e.into()),
}
});
Ok(Box::new(iter))
}
}
#[cfg(test)]
mod tests {
use super::*;
use quickcheck::quickcheck;
use tempfile::TempDir;
quickcheck! {
fn test_roundtrip(pairs: Vec<(Node, Node)>) -> bool {
let mut pairs = pairs;
if pairs.len() == 0 {
return true;
}
let dir = TempDir::new().unwrap();
let mut map = NodeMap::open(dir).unwrap();
let last = pairs.pop().unwrap();
for (first, second) in pairs.iter() {
map.add(&first, &second).unwrap();
}
for (first, second) in pairs.iter() {
if first!= &map.lookup_by_second(second).unwrap().unwrap() {
return false;
}
if second!= &map.lookup_by_first(first).unwrap().unwrap() {
return false;
}
}
for value in vec![last.0, last.1].iter() {
if!map.lookup_by_first(value).unwrap().is_none() {
return false;
}
if!map.lookup_by_second(value).unwrap().is_none() {
return false;
}
}
let actual_pairs = map.iter().unwrap().collect::<Result<Vec<_>>>().unwrap();
actual_pairs == pairs
}
}
}
|
NodeMap
|
identifier_name
|
domparser.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::DOMParserBinding;
use dom::bindings::utils::{CacheableWrapper, WrapperCache};
use dom::bindings::utils::{BindingObject, DerivedWrapper};
use dom::domparser::DOMParser;
use js::jsapi::{JSContext, JSObject, JSVal};
use js::glue::bindgen::{RUST_OBJECT_TO_JSVAL};
impl CacheableWrapper for DOMParser {
fn
|
(&mut self) -> &mut WrapperCache {
unsafe { cast::transmute(&self.wrapper) }
}
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
let mut unused = false;
DOMParserBinding::Wrap(cx, scope, self, &mut unused)
}
}
impl BindingObject for DOMParser {
fn GetParentObject(&self, _cx: *JSContext) -> @mut CacheableWrapper {
return self.owner as @mut CacheableWrapper;
}
}
impl DerivedWrapper for DOMParser {
fn wrap(&mut self, _cx: *JSContext, _scope: *JSObject, _vp: *mut JSVal) -> i32 {
fail!(~"nyi")
}
fn wrap_shared(@mut self, cx: *JSContext, scope: *JSObject, vp: *mut JSVal) -> i32 {
let obj = self.wrap_object_shared(cx, scope);
if obj.is_null() {
return 0;
} else {
unsafe { *vp = RUST_OBJECT_TO_JSVAL(obj) };
return 1;
}
}
}
|
get_wrappercache
|
identifier_name
|
domparser.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::DOMParserBinding;
use dom::bindings::utils::{CacheableWrapper, WrapperCache};
use dom::bindings::utils::{BindingObject, DerivedWrapper};
use dom::domparser::DOMParser;
use js::jsapi::{JSContext, JSObject, JSVal};
use js::glue::bindgen::{RUST_OBJECT_TO_JSVAL};
impl CacheableWrapper for DOMParser {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
unsafe { cast::transmute(&self.wrapper) }
}
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
let mut unused = false;
DOMParserBinding::Wrap(cx, scope, self, &mut unused)
}
}
impl BindingObject for DOMParser {
fn GetParentObject(&self, _cx: *JSContext) -> @mut CacheableWrapper {
return self.owner as @mut CacheableWrapper;
}
}
impl DerivedWrapper for DOMParser {
fn wrap(&mut self, _cx: *JSContext, _scope: *JSObject, _vp: *mut JSVal) -> i32 {
fail!(~"nyi")
}
fn wrap_shared(@mut self, cx: *JSContext, scope: *JSObject, vp: *mut JSVal) -> i32 {
let obj = self.wrap_object_shared(cx, scope);
if obj.is_null()
|
else {
unsafe { *vp = RUST_OBJECT_TO_JSVAL(obj) };
return 1;
}
}
}
|
{
return 0;
}
|
conditional_block
|
domparser.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::DOMParserBinding;
use dom::bindings::utils::{CacheableWrapper, WrapperCache};
use dom::bindings::utils::{BindingObject, DerivedWrapper};
use dom::domparser::DOMParser;
use js::jsapi::{JSContext, JSObject, JSVal};
use js::glue::bindgen::{RUST_OBJECT_TO_JSVAL};
impl CacheableWrapper for DOMParser {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
unsafe { cast::transmute(&self.wrapper) }
}
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
let mut unused = false;
DOMParserBinding::Wrap(cx, scope, self, &mut unused)
}
}
impl BindingObject for DOMParser {
fn GetParentObject(&self, _cx: *JSContext) -> @mut CacheableWrapper {
return self.owner as @mut CacheableWrapper;
}
}
impl DerivedWrapper for DOMParser {
fn wrap(&mut self, _cx: *JSContext, _scope: *JSObject, _vp: *mut JSVal) -> i32 {
|
let obj = self.wrap_object_shared(cx, scope);
if obj.is_null() {
return 0;
} else {
unsafe { *vp = RUST_OBJECT_TO_JSVAL(obj) };
return 1;
}
}
}
|
fail!(~"nyi")
}
fn wrap_shared(@mut self, cx: *JSContext, scope: *JSObject, vp: *mut JSVal) -> i32 {
|
random_line_split
|
domparser.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::DOMParserBinding;
use dom::bindings::utils::{CacheableWrapper, WrapperCache};
use dom::bindings::utils::{BindingObject, DerivedWrapper};
use dom::domparser::DOMParser;
use js::jsapi::{JSContext, JSObject, JSVal};
use js::glue::bindgen::{RUST_OBJECT_TO_JSVAL};
impl CacheableWrapper for DOMParser {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
unsafe { cast::transmute(&self.wrapper) }
}
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
let mut unused = false;
DOMParserBinding::Wrap(cx, scope, self, &mut unused)
}
}
impl BindingObject for DOMParser {
fn GetParentObject(&self, _cx: *JSContext) -> @mut CacheableWrapper {
return self.owner as @mut CacheableWrapper;
}
}
impl DerivedWrapper for DOMParser {
fn wrap(&mut self, _cx: *JSContext, _scope: *JSObject, _vp: *mut JSVal) -> i32 {
fail!(~"nyi")
}
fn wrap_shared(@mut self, cx: *JSContext, scope: *JSObject, vp: *mut JSVal) -> i32
|
}
|
{
let obj = self.wrap_object_shared(cx, scope);
if obj.is_null() {
return 0;
} else {
unsafe { *vp = RUST_OBJECT_TO_JSVAL(obj) };
return 1;
}
}
|
identifier_body
|
issue-2895.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem;
struct Cat {
x: int
}
struct Kitty {
x: int,
}
impl Drop for Kitty {
fn drop(&mut self) {}
}
#[cfg(target_arch = "x86_64")]
pub fn main() {
assert_eq!(mem::size_of::<Cat>(), 8 as uint);
assert_eq!(mem::size_of::<Kitty>(), 16 as uint);
}
#[cfg(any(target_arch = "x86", target_arch = "arm"))]
pub fn main()
|
{
assert_eq!(mem::size_of::<Cat>(), 4 as uint);
assert_eq!(mem::size_of::<Kitty>(), 8 as uint);
}
|
identifier_body
|
|
issue-2895.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem;
struct Cat {
x: int
}
struct Kitty {
x: int,
}
impl Drop for Kitty {
fn
|
(&mut self) {}
}
#[cfg(target_arch = "x86_64")]
pub fn main() {
assert_eq!(mem::size_of::<Cat>(), 8 as uint);
assert_eq!(mem::size_of::<Kitty>(), 16 as uint);
}
#[cfg(any(target_arch = "x86", target_arch = "arm"))]
pub fn main() {
assert_eq!(mem::size_of::<Cat>(), 4 as uint);
assert_eq!(mem::size_of::<Kitty>(), 8 as uint);
}
|
drop
|
identifier_name
|
issue-2895.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem;
struct Cat {
x: int
}
|
impl Drop for Kitty {
fn drop(&mut self) {}
}
#[cfg(target_arch = "x86_64")]
pub fn main() {
assert_eq!(mem::size_of::<Cat>(), 8 as uint);
assert_eq!(mem::size_of::<Kitty>(), 16 as uint);
}
#[cfg(any(target_arch = "x86", target_arch = "arm"))]
pub fn main() {
assert_eq!(mem::size_of::<Cat>(), 4 as uint);
assert_eq!(mem::size_of::<Kitty>(), 8 as uint);
}
|
struct Kitty {
x: int,
}
|
random_line_split
|
keywords.rs
|
use nom::branch::alt;
use nom::bytes::complete::{tag, tag_no_case};
use nom::combinator::peek;
use nom::sequence::terminated;
use nom::IResult;
use crate::parsers::parser::elements::eof;
fn keyword_follow_char(input: &str) -> IResult<&str, &str>
|
pub fn sql_keyword(input: &str) -> IResult<&str, &str> {
alt((
terminated(tag_no_case("SELECT"), keyword_follow_char),
terminated(tag_no_case("FROM"), keyword_follow_char),
terminated(tag_no_case("WHERE"), keyword_follow_char),
terminated(tag_no_case("ORDER"), keyword_follow_char),
terminated(tag_no_case("BY"), keyword_follow_char),
terminated(tag_no_case("ASC"), keyword_follow_char),
terminated(tag_no_case("DESC"), keyword_follow_char),
terminated(tag_no_case("LIMIT"), keyword_follow_char),
terminated(tag_no_case("OFFSET"), keyword_follow_char),
))(input)
}
pub fn clause_delimiter(input: &str) -> IResult<&str, &str> {
alt((sql_keyword, eof))(input)
}
|
{
peek(alt((
tag(" "),
tag("\n"),
tag(";"),
tag("("),
tag(")"),
tag("\t"),
tag(","),
tag("="),
eof,
)))(input)
}
|
identifier_body
|
keywords.rs
|
use nom::branch::alt;
use nom::bytes::complete::{tag, tag_no_case};
use nom::combinator::peek;
use nom::sequence::terminated;
use nom::IResult;
use crate::parsers::parser::elements::eof;
fn
|
(input: &str) -> IResult<&str, &str> {
peek(alt((
tag(" "),
tag("\n"),
tag(";"),
tag("("),
tag(")"),
tag("\t"),
tag(","),
tag("="),
eof,
)))(input)
}
pub fn sql_keyword(input: &str) -> IResult<&str, &str> {
alt((
terminated(tag_no_case("SELECT"), keyword_follow_char),
terminated(tag_no_case("FROM"), keyword_follow_char),
terminated(tag_no_case("WHERE"), keyword_follow_char),
terminated(tag_no_case("ORDER"), keyword_follow_char),
terminated(tag_no_case("BY"), keyword_follow_char),
terminated(tag_no_case("ASC"), keyword_follow_char),
terminated(tag_no_case("DESC"), keyword_follow_char),
terminated(tag_no_case("LIMIT"), keyword_follow_char),
terminated(tag_no_case("OFFSET"), keyword_follow_char),
))(input)
}
pub fn clause_delimiter(input: &str) -> IResult<&str, &str> {
alt((sql_keyword, eof))(input)
}
|
keyword_follow_char
|
identifier_name
|
keywords.rs
|
use nom::branch::alt;
use nom::bytes::complete::{tag, tag_no_case};
use nom::combinator::peek;
use nom::sequence::terminated;
use nom::IResult;
use crate::parsers::parser::elements::eof;
fn keyword_follow_char(input: &str) -> IResult<&str, &str> {
peek(alt((
tag(" "),
tag("\n"),
tag(";"),
tag("("),
tag(")"),
tag("\t"),
tag(","),
tag("="),
eof,
)))(input)
}
pub fn sql_keyword(input: &str) -> IResult<&str, &str> {
alt((
|
terminated(tag_no_case("ORDER"), keyword_follow_char),
terminated(tag_no_case("BY"), keyword_follow_char),
terminated(tag_no_case("ASC"), keyword_follow_char),
terminated(tag_no_case("DESC"), keyword_follow_char),
terminated(tag_no_case("LIMIT"), keyword_follow_char),
terminated(tag_no_case("OFFSET"), keyword_follow_char),
))(input)
}
pub fn clause_delimiter(input: &str) -> IResult<&str, &str> {
alt((sql_keyword, eof))(input)
}
|
terminated(tag_no_case("SELECT"), keyword_follow_char),
terminated(tag_no_case("FROM"), keyword_follow_char),
terminated(tag_no_case("WHERE"), keyword_follow_char),
|
random_line_split
|
dining_philosophers.rs
|
// http://rosettacode.org/wiki/Dining_philosophers
//! A Rust implementation of a solution for the Dining Philosophers Problem. We prevent a deadlock
//! by using Dijkstra's solution of making a single diner "left-handed." That is, all diners except
//! one pick up the chopstick "to their left" and then the chopstick "to their right." The
//! remaining diner performs this in reverse.
use std::thread;
use std::time::Duration;
use std::sync::{Mutex, Arc};
struct Philosopher {
name: String,
left: usize,
right: usize,
}
impl Philosopher {
fn new(name: &str, left: usize, right: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left: left,
right: right,
}
}
fn eat(&self, table: &Table) {
let _left = table.forks[self.left].lock().unwrap();
let _right = table.forks[self.right].lock().unwrap();
println!("{} is eating.", self.name);
thread::sleep(Duration::from_secs(1));
println!("{} is done eating.", self.name);
}
}
struct Table {
forks: Vec<Mutex<()>>,
}
fn
|
() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
],
});
let philosophers = vec![
Philosopher::new("Baruch Spinoza", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
Philosopher::new("Friedrich Nietzsche", 3, 4),
Philosopher::new("Michel Foucault", 0, 4),
];
let handles: Vec<_> = philosophers.into_iter()
.map(|p| {
let table = table.clone();
thread::spawn(move || {
p.eat(&table);
})
})
.collect();
for h in handles {
h.join().unwrap();
}
}
|
main
|
identifier_name
|
dining_philosophers.rs
|
// http://rosettacode.org/wiki/Dining_philosophers
//! A Rust implementation of a solution for the Dining Philosophers Problem. We prevent a deadlock
//! by using Dijkstra's solution of making a single diner "left-handed." That is, all diners except
//! one pick up the chopstick "to their left" and then the chopstick "to their right." The
//! remaining diner performs this in reverse.
use std::thread;
use std::time::Duration;
use std::sync::{Mutex, Arc};
struct Philosopher {
name: String,
left: usize,
right: usize,
}
impl Philosopher {
fn new(name: &str, left: usize, right: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left: left,
right: right,
}
}
fn eat(&self, table: &Table)
|
}
struct Table {
forks: Vec<Mutex<()>>,
}
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
],
});
let philosophers = vec![
Philosopher::new("Baruch Spinoza", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
Philosopher::new("Friedrich Nietzsche", 3, 4),
Philosopher::new("Michel Foucault", 0, 4),
];
let handles: Vec<_> = philosophers.into_iter()
.map(|p| {
let table = table.clone();
thread::spawn(move || {
p.eat(&table);
})
})
.collect();
for h in handles {
h.join().unwrap();
}
}
|
{
let _left = table.forks[self.left].lock().unwrap();
let _right = table.forks[self.right].lock().unwrap();
println!("{} is eating.", self.name);
thread::sleep(Duration::from_secs(1));
println!("{} is done eating.", self.name);
}
|
identifier_body
|
dining_philosophers.rs
|
// http://rosettacode.org/wiki/Dining_philosophers
//! A Rust implementation of a solution for the Dining Philosophers Problem. We prevent a deadlock
//! by using Dijkstra's solution of making a single diner "left-handed." That is, all diners except
|
use std::thread;
use std::time::Duration;
use std::sync::{Mutex, Arc};
struct Philosopher {
name: String,
left: usize,
right: usize,
}
impl Philosopher {
fn new(name: &str, left: usize, right: usize) -> Philosopher {
Philosopher {
name: name.to_string(),
left: left,
right: right,
}
}
fn eat(&self, table: &Table) {
let _left = table.forks[self.left].lock().unwrap();
let _right = table.forks[self.right].lock().unwrap();
println!("{} is eating.", self.name);
thread::sleep(Duration::from_secs(1));
println!("{} is done eating.", self.name);
}
}
struct Table {
forks: Vec<Mutex<()>>,
}
fn main() {
let table = Arc::new(Table {
forks: vec![
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
Mutex::new(()),
],
});
let philosophers = vec![
Philosopher::new("Baruch Spinoza", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
Philosopher::new("Friedrich Nietzsche", 3, 4),
Philosopher::new("Michel Foucault", 0, 4),
];
let handles: Vec<_> = philosophers.into_iter()
.map(|p| {
let table = table.clone();
thread::spawn(move || {
p.eat(&table);
})
})
.collect();
for h in handles {
h.join().unwrap();
}
}
|
//! one pick up the chopstick "to their left" and then the chopstick "to their right." The
//! remaining diner performs this in reverse.
|
random_line_split
|
utmpx.rs
|
// This file is part of the uutils coreutils package.
//
// (c) Jian Zeng <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
//! Aims to provide platform-independent methods to obtain login records
//!
//! **ONLY** support linux, macos and freebsd for the time being
//!
//! # Examples:
//!
//! ```
//! use uucore::utmpx::Utmpx;
//! for ut in Utmpx::iter_all_records() {
//! if ut.is_user_process() {
//! println!("{}: {}", ut.host(), ut.user())
//! }
//! }
//! ```
//!
//! Specifying the path to login record:
//!
//! ```
//! use uucore::utmpx::Utmpx;
//! for ut in Utmpx::iter_all_records().read_from("/some/where/else") {
//! if ut.is_user_process() {
//! println!("{}: {}", ut.host(), ut.user())
//! }
//! }
//! ```
use super::libc;
pub extern crate time;
use self::time::{Tm, Timespec};
use ::std::io::Result as IOResult;
use ::std::io::Error as IOError;
use ::std::ptr;
use ::std::ffi::CString;
pub use self::ut::*;
use libc::utmpx;
// pub use libc::getutxid;
// pub use libc::getutxline;
// pub use libc::pututxline;
pub use libc::getutxent;
pub use libc::setutxent;
pub use libc::endutxent;
#[cfg(any(target_os = "macos", target_os = "linux"))]
pub use libc::utmpxname;
#[cfg(target_os = "freebsd")]
pub unsafe extern "C" fn utmpxname(_file: *const libc::c_char) -> libc::c_int {
0
}
// In case the c_char array doesn' t end with NULL
macro_rules! chars2string {
($arr:expr) => (
$arr.iter().take_while(|i| **i > 0).map(|&i| i as u8 as char).collect::<String>()
)
}
#[cfg(target_os = "linux")]
mod ut {
pub static DEFAULT_FILE: &'static str = "/var/run/utmp";
pub use libc::__UT_LINESIZE as UT_LINESIZE;
pub use libc::__UT_NAMESIZE as UT_NAMESIZE;
pub use libc::__UT_HOSTSIZE as UT_HOSTSIZE;
pub const UT_IDSIZE: usize = 4;
pub use libc::EMPTY;
pub use libc::RUN_LVL;
pub use libc::BOOT_TIME;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::ACCOUNTING;
}
#[cfg(target_os = "macos")]
mod ut {
pub static DEFAULT_FILE: &'static str = "/var/run/utmpx";
pub use libc::_UTX_LINESIZE as UT_LINESIZE;
pub use libc::_UTX_USERSIZE as UT_NAMESIZE;
pub use libc::_UTX_HOSTSIZE as UT_HOSTSIZE;
pub use libc::_UTX_IDSIZE as UT_IDSIZE;
pub use libc::EMPTY;
pub use libc::RUN_LVL;
pub use libc::BOOT_TIME;
pub use libc::NEW_TIME;
pub use libc::OLD_TIME;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::USER_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::ACCOUNTING;
pub use libc::SIGNATURE;
pub use libc::SHUTDOWN_TIME;
}
#[cfg(target_os = "freebsd")]
mod ut {
use super::libc;
pub static DEFAULT_FILE: &'static str = "";
pub const UT_LINESIZE: usize = 16;
pub const UT_NAMESIZE: usize = 32;
pub const UT_IDSIZE: usize = 8;
pub const UT_HOSTSIZE: usize = 128;
pub use libc::EMPTY;
pub use libc::BOOT_TIME;
pub use libc::OLD_TIME;
pub use libc::NEW_TIME;
pub use libc::USER_PROCESS;
pub use libc::INIT_PROCESS;
pub use libc::LOGIN_PROCESS;
pub use libc::DEAD_PROCESS;
pub use libc::SHUTDOWN_TIME;
}
pub struct Utmpx {
inner: utmpx,
}
impl Utmpx {
/// A.K.A. ut.ut_type
pub fn record_type(&self) -> i16 {
self.inner.ut_type as i16
}
/// A.K.A. ut.ut_pid
pub fn pid(&self) -> i32 {
self.inner.ut_pid as i32
}
/// A.K.A. ut.ut_id
pub fn terminal_suffix(&self) -> String {
chars2string!(self.inner.ut_id)
}
/// A.K.A. ut.ut_user
pub fn user(&self) -> String {
chars2string!(self.inner.ut_user)
}
/// A.K.A. ut.ut_host
pub fn
|
(&self) -> String {
chars2string!(self.inner.ut_host)
}
/// A.K.A. ut.ut_line
pub fn tty_device(&self) -> String {
chars2string!(self.inner.ut_line)
}
/// A.K.A. ut.ut_tv
pub fn login_time(&self) -> Tm {
time::at(Timespec::new(self.inner.ut_tv.tv_sec as i64,
self.inner.ut_tv.tv_usec as i32))
}
/// A.K.A. ut.ut_exit
///
/// Return (e_termination, e_exit)
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn exit_status(&self) -> (i16, i16) {
(self.inner.ut_exit.e_termination, self.inner.ut_exit.e_exit)
}
/// A.K.A. ut.ut_exit
///
/// Return (0, 0) on Non-Linux platform
#[cfg(not(any(target_os = "linux", target_os = "android")))]
pub fn exit_status(&self) -> (i16, i16) {
(0, 0)
}
/// Consumes the `Utmpx`, returning the underlying C struct utmpx
pub fn into_inner(self) -> utmpx {
self.inner
}
pub fn is_user_process(&self) -> bool {
!self.user().is_empty() && self.record_type() == USER_PROCESS
}
/// Canonicalize host name using DNS
pub fn canon_host(&self) -> IOResult<String> {
const AI_CANONNAME: libc::c_int = 0x2;
let host = self.host();
let host = host.split(':').nth(0).unwrap();
let hints = libc::addrinfo {
ai_flags: AI_CANONNAME,
ai_family: 0,
ai_socktype: 0,
ai_protocol: 0,
ai_addrlen: 0,
ai_addr: ptr::null_mut(),
ai_canonname: ptr::null_mut(),
ai_next: ptr::null_mut(),
};
let c_host = CString::new(host).unwrap();
let mut res = ptr::null_mut();
let status = unsafe {
libc::getaddrinfo(c_host.as_ptr(),
ptr::null(),
&hints as *const _,
&mut res as *mut _)
};
if status == 0 {
let info: libc::addrinfo = unsafe { ptr::read(res as *const _) };
// http://lists.gnu.org/archive/html/bug-coreutils/2006-09/msg00300.html
// says Darwin 7.9.0 getaddrinfo returns 0 but sets
// res->ai_canonname to NULL.
let ret = if info.ai_canonname.is_null() {
Ok(String::from(host))
} else {
Ok(unsafe { CString::from_raw(info.ai_canonname).into_string().unwrap() })
};
unsafe {
libc::freeaddrinfo(res);
}
ret
} else {
Err(IOError::last_os_error())
}
}
pub fn iter_all_records() -> UtmpxIter {
UtmpxIter
}
}
/// Iterator of login records
pub struct UtmpxIter;
impl UtmpxIter {
/// Sets the name of the utmpx-format file for the other utmpx functions to access.
///
/// If not set, default record file will be used(file path depends on the target OS)
pub fn read_from(self, f: &str) -> Self {
let res = unsafe { utmpxname(CString::new(f).unwrap().as_ptr()) };
if res!= 0 {
println!("Warning: {}", IOError::last_os_error());
}
unsafe {
setutxent();
}
self
}
}
impl Iterator for UtmpxIter {
type Item = Utmpx;
fn next(&mut self) -> Option<Self::Item> {
unsafe {
let res = getutxent();
if!res.is_null() {
Some(Utmpx { inner: ptr::read(res as *const _) })
} else {
endutxent();
None
}
}
}
}
|
host
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.