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 |
---|---|---|---|---|
stylesheet_loader.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 std::sync::Arc;
use style::gecko_bindings::bindings::Gecko_LoadStyleSheet;
use style::gecko_bindings::structs::{Loader, ServoStyleSheet};
use style::gecko_bindings::sugar::ownership::HasArcFFI;
use style::media_queries::MediaList;
use style::shared_lock::Locked;
use style::stylesheets::{ImportRule, StylesheetLoader as StyleStylesheetLoader};
use style_traits::ToCss;
pub struct StylesheetLoader(*mut Loader, *mut ServoStyleSheet);
impl StylesheetLoader {
pub fn | (loader: *mut Loader, parent: *mut ServoStyleSheet) -> Self {
StylesheetLoader(loader, parent)
}
}
impl StyleStylesheetLoader for StylesheetLoader {
fn request_stylesheet(
&self,
media: MediaList,
make_import: &mut FnMut(MediaList) -> ImportRule,
make_arc: &mut FnMut(ImportRule) -> Arc<Locked<ImportRule>>,
) -> Arc<Locked<ImportRule>> {
// TODO(emilio): We probably want to share media representation with
// Gecko in Stylo.
//
// This also allows us to get rid of a bunch of extra work to evaluate
// and ensure parity, and shouldn't be much Gecko work given we always
// evaluate them on the main thread.
//
// Meanwhile, this works.
let media_string = media.to_css_string();
let import = make_import(media);
// After we get this raw pointer ImportRule will be moved into a lock and Arc
// and so the Arc<Url> pointer inside will also move,
// but the Url it points to or the allocating backing the String inside that Url won’t,
// so this raw pointer will still be valid.
let (spec_bytes, spec_len): (*const u8, usize) = import.url.as_slice_components()
.expect("Import only loads valid URLs");
let arc = make_arc(import);
unsafe {
Gecko_LoadStyleSheet(self.0,
self.1,
HasArcFFI::arc_as_borrowed(&arc),
spec_bytes,
spec_len as u32,
media_string.as_bytes().as_ptr(),
media_string.len() as u32);
}
arc
}
}
| new | identifier_name |
pipe.rs | //!
//! Desync pipes provide a way to generate and process streams via a `Desync` object
//!
//! Pipes are an excellent way to interface `Desync` objects and the futures library. Piping
//! a stream into a `Desync` object is equivalent to spawning it with an executor, except
//! without the need to dedicate a thread to running it.
//!
//! There are two kinds of pipe. The `pipe_in` function creates a pipe that processes each
//! value made available from a stream on a desync object as they arrive, producing no
//! results. This is useful for cases where a `Desync` object is being used as the endpoint
//! for some data processing (for example, to insert the results of an operation into an
//! asynchronous database object).
//!
//! The `pipe` function pipes data through an object. For every input value, it produces
//! an output value. This is good for creating streams that perform some kind of asynchronous
//! processing operation or that need to access data from inside a `Desync` object.
//!
//! Here's an example of using `pipe_in` to store data in a `HashSet`:
//!
//! ```
//! # extern crate futures;
//! # extern crate desync;
//! # use std::collections::HashSet;
//! # use std::sync::*;
//! #
//! use futures::future;
//! use futures::channel::mpsc;
//! use futures::executor;
//! use futures::prelude::*;
//! # use ::desync::*;
//!
//! executor::block_on(async {
//! let desync_hashset = Arc::new(Desync::new(HashSet::new()));
//! let (mut sender, receiver) = mpsc::channel(5);
//!
//! pipe_in(Arc::clone(&desync_hashset), receiver, |hashset, value| { hashset.insert(value); future::ready(()).boxed() });
//!
//! sender.send("Test".to_string()).await.unwrap();
//! sender.send("Another value".to_string()).await.unwrap();
//! #
//! # assert!(desync_hashset.sync(|hashset| hashset.contains(&("Test".to_string()))))
//! });
//! ```
//!
use super::desync::*;
use futures::*;
use futures::future::{BoxFuture};
use futures::stream::{Stream};
use futures::task;
use futures::task::{Poll, Context};
use std::sync::*;
use std::pin::{Pin};
use std::collections::VecDeque;
lazy_static! {
/// Desync for disposing of references used in pipes (if a pipe is closed with pending data, this avoids clearing it in the same context as the pipe monitor)
static ref REFERENCE_CHUTE: Desync<()> = Desync::new(());
}
/// The maximum number of items to queue on a pipe stream before we stop accepting new input
const PIPE_BACKPRESSURE_COUNT: usize = 5;
///
/// Futures notifier used to wake up a pipe when a stream or future notifies
///
struct PipeContext<Core, PollFn>
where Core: Send+Unpin {
/// The desync target that will be woken when the stream notifies that it needs to be polled
/// We keep a weak reference so that if the stream/future is all that's left referencing the
/// desync, it's thrown away
target: Weak<Desync<Core>>,
/// The function that should be called to poll this stream. Returns false if we should no longer keep polling the stream
poll_fn: Arc<Mutex<Option<PollFn>>>
}
impl<Core, PollFn> PipeContext<Core, PollFn>
where Core: 'static+Send+Unpin,
PollFn:'static+Send+for<'a> FnMut(&'a mut Core, Context<'a>) -> BoxFuture<'a, bool> {
///
/// Creates a new pipe context, ready to poll
///
fn new(target: &Arc<Desync<Core>>, poll_fn: PollFn) -> Arc<PipeContext<Core, PollFn>> {
let context = PipeContext {
target: Arc::downgrade(target),
poll_fn: Arc::new(Mutex::new(Some(poll_fn)))
};
Arc::new(context)
}
///
/// Triggers the poll function in the context of the target desync
///
fn poll(arc_self: Arc<Self>) {
// If the desync is stil live...
if let Some(target) = arc_self.target.upgrade() {
// Grab the poll function
let maybe_poll_fn = Arc::clone(&arc_self.poll_fn);
// Schedule a polling operation on the desync
let _ = target.future_desync(move |core| {
async move {
// Create a futures context from the context reference
let waker = task::waker_ref(&arc_self);
let context = Context::from_waker(&waker);
// Pass in to the poll function
let future_poll = {
let mut maybe_poll_fn = maybe_poll_fn.lock().unwrap();
let future_poll = maybe_poll_fn.as_mut().map(|poll_fn| (poll_fn)(core, context));
future_poll
};
if let Some(future_poll) = future_poll {
let keep_polling = future_poll.await;
if!keep_polling {
// Deallocate the function when it's time to stop polling altogether
(*arc_self.poll_fn.lock().unwrap()) = None;
}
}
}.boxed()
});
} else {
// Stream has woken up but the desync is no longer listening
(*arc_self.poll_fn.lock().unwrap()) = None;
}
}
}
impl<Core, PollFn> task::ArcWake for PipeContext<Core, PollFn>
where Core: 'static+Send+Unpin,
PollFn:'static+Send+for<'a> FnMut(&'a mut Core, Context<'a>) -> BoxFuture<'a, bool> {
fn wake_by_ref(arc_self: &Arc<Self>) {
Self::poll(Arc::clone(arc_self));
}
fn wake(self: Arc<Self>) {
Self::poll(self);
}
}
///
/// Pipes a stream into a desync object. Whenever an item becomes available on the stream, the
/// processing function is called asynchronously with the item that was received.
///
/// This takes a weak reference to the passed in `Desync` object, so the pipe will stop if it's
/// the only thing referencing this object.
///
/// Piping a stream to a `Desync` like this will cause it to start executing: ie, this is
/// similar to calling `executor::spawn(stream)`, except that the stream will immediately
/// start draining into the `Desync` object.
///
pub fn pipe_in<Core, S, ProcessFn>(desync: Arc<Desync<Core>>, stream: S, process: ProcessFn)
where Core: 'static+Send+Unpin,
S: 'static+Send+Unpin+Stream,
S::Item: Send,
ProcessFn: 'static+Send+for<'a> FnMut(&'a mut Core, S::Item) -> BoxFuture<'a, ()> {
let stream = Arc::new(Mutex::new(stream));
let process = Arc::new(Mutex::new(process));
// The context is used to trigger polling of the stream
let context = PipeContext::new(&desync, move |core, context| {
let process = Arc::clone(&process);
let stream = Arc::clone(&stream);
async move {
let mut context = context;
loop {
// Poll the stream
let next = stream.lock().unwrap().poll_next_unpin(&mut context);
match next {
// Wait for notification when the stream goes pending
Poll::Pending => return true,
// Stop polling when the stream stops generating new events
Poll::Ready(None) => return false,
// Invoke the callback when there's some data on the stream
Poll::Ready(Some(next)) => {
let process_future = (&mut *process.lock().unwrap())(core, next);
process_future.await;
}
}
}
}.boxed()
});
// Trigger the initial poll
PipeContext::poll(context);
}
///
/// Pipes a stream into this object. Whenever an item becomes available on the stream, the
/// processing function is called asynchronously with the item that was received. The
/// return value is placed onto the output stream.
///
/// Unlike `pipe_in`, this keeps a strong reference to the `Desync` object so the processing
/// will continue so long as the input stream has data and the output stream is not dropped.
///
/// The input stream will start executing and reading values immediately when this is called.
/// Dropping the output stream will cause the pipe to be closed (the input stream will be
/// dropped and no further processing will occur).
///
/// This example demonstrates how to create a simple demonstration pipe that takes hashset values
/// and returns a stream indicating whether or not they were already included:
///
/// ```
/// # extern crate futures;
/// # extern crate desync;
/// # use std::collections::HashSet;
/// # use std::sync::*;
/// #
/// use futures::prelude::*;
/// use futures::future;
/// use futures::channel::mpsc;
/// use futures::executor;
/// # use ::desync::*;
///
/// executor::block_on(async {
/// let desync_hashset = Arc::new(Desync::new(HashSet::new()));
/// let (mut sender, receiver) = mpsc::channel::<String>(5);
///
/// let mut value_inserted = pipe(Arc::clone(&desync_hashset), receiver,
/// |hashset, value| { future::ready((value.clone(), hashset.insert(value))).boxed() });
///
/// sender.send("Test".to_string()).await.unwrap();
/// sender.send("Another value".to_string()).await.unwrap();
/// sender.send("Test".to_string()).await.unwrap();
///
/// assert!(value_inserted.next().await == Some(("Test".to_string(), true)));
/// assert!(value_inserted.next().await == Some(("Another value".to_string(), true)));
/// assert!(value_inserted.next().await == Some(("Test".to_string(), false)));
/// });
/// ```
///
pub fn pipe<Core, S, Output, ProcessFn>(desync: Arc<Desync<Core>>, stream: S, process: ProcessFn) -> PipeStream<Output>
where Core: 'static+Send+Unpin,
S: 'static+Send+Unpin+Stream,
S::Item: Send,
Output: 'static+Send,
ProcessFn: 'static+Send+for <'a> FnMut(&'a mut Core, S::Item) -> BoxFuture<'a, Output> {
// Prepare the streams
let input_stream = Arc::new(Mutex::new(stream));
let process = Arc::new(Mutex::new(process));
let mut output_desync = Some(Arc::clone(&desync));
let output_stream = PipeStream::<Output>::new(move || {
output_desync.take();
});
// Get the core from the output stream
let stream_core = Arc::clone(&output_stream.core);
let stream_core = Arc::downgrade(&stream_core);
// Create the read context
let context = PipeContext::new(&desync, move |core, context| {
let stream_core = stream_core.upgrade();
let mut context = context;
let input_stream = Arc::clone(&input_stream);
let process = Arc::clone(&process);
async move {
if let Some(stream_core) = stream_core {
// Defer processing if the stream core is full
let is_closed = {
// Fetch the core
let mut stream_core = stream_core.lock().unwrap();
// If the pending queue is full, then stop processing events
if stream_core.pending.len() >= stream_core.max_pipe_depth {
// Wake when the stream accepts some input
stream_core.backpressure_release_notify = Some(context.waker().clone());
// Go back to sleep without reading from the stream
return true;
}
// If the core is closed, finish up
stream_core.closed
};
// Wake up the stream and stop reading from the stream if the core is closed
if is_closed {
let notify = { stream_core.lock().unwrap().notify.take() };
notify.map(|notify| notify.wake());
return false;
}
loop {
// Disable the notifier if there was one left over
stream_core.lock().unwrap().notify_stream_closed = None;
// Poll the stream
let next = input_stream.lock().unwrap().poll_next_unpin(&mut context);
match next {
// Wait for notification when the stream goes pending
Poll::Pending => {
stream_core.lock().unwrap().notify_stream_closed = Some(context.waker().clone());
return true
},
// Stop polling when the stream stops generating new events
Poll::Ready(None) => {
// Mark the stream as closed, and wake it up
let notify = {
let mut stream_core = stream_core.lock().unwrap();
stream_core.closed = true;
stream_core.notify.take()
};
notify.map(|notify| notify.wake());
return false;
},
// Invoke the callback when there's some data on the stream
Poll::Ready(Some(next)) => {
// Pipe the next item through
let next_item = (&mut *process.lock().unwrap())(core, next);
let next_item = next_item.await;
// Send to the pipe stream, and wake it up
let notify = {
let mut stream_core = stream_core.lock().unwrap();
stream_core.pending.push_back(next_item);
stream_core.notify.take()
};
notify.map(|notify| notify.wake());
}
}
}
} else {
// The stream core has been released
return false;
}
}.boxed()
});
// Poll the context to start the stream running
PipeContext::poll(context);
output_stream
}
///
/// The shared data for a pipe stream
///
struct PipeStreamCore<Item> {
/// The maximum number of items we allow to be queued in this stream before producing backpressure
max_pipe_depth: usize,
/// The pending data for this stream
pending: VecDeque<Item>,
/// True if the input stream has closed (the stream is closed once this is true and there are no more pending items)
closed: bool,
/// The task to notify when the stream changes
notify: Option<task::Waker>,
/// The task to notify when the stream changes
notify_stream_closed: Option<task::Waker>,
/// The task to notify when we reduce the amount of pending data
backpressure_release_notify: Option<task::Waker>
}
///
/// A stream generated by a pipe
///
pub struct PipeStream<Item> {
/// The core contains the stream state
core: Arc<Mutex<PipeStreamCore<Item>>>,
/// Called when dropping the output stream
on_drop: Option<Box<dyn Send+Sync+FnMut() -> ()>>
}
impl<Item> PipeStream<Item> {
///
/// Creates a new, empty, pipestream
///
fn new<FnOnDrop:'static+Send+Sync+FnMut() -> ()>(on_drop: FnOnDrop) -> PipeStream<Item> {
PipeStream {
core: Arc::new(Mutex::new(PipeStreamCore {
max_pipe_depth: PIPE_BACKPRESSURE_COUNT,
pending: VecDeque::new(),
closed: false,
notify: None,
notify_stream_closed: None,
backpressure_release_notify: None
})),
on_drop: Some(Box::new(on_drop))
}
}
///
/// Sets the number of items that this pipe stream will buffer before producing backpressure
///
/// If this call is not made, this will be set to 5.
///
pub fn set_backpressure_depth(&mut self, max_depth: usize) {
self.core.lock().unwrap().max_pipe_depth = max_depth;
}
}
impl<Item> Drop for PipeStream<Item> {
fn drop(&mut self) {
let mut core = self.core.lock().unwrap();
// Flush the pending queue
core.pending = VecDeque::new();
// Mark the core as closed to stop it from reading from the stream
core.closed = true;
// Wake the stream to finish closing it
core.notify_stream_closed.take().map(|notify_stream_closed| notify_stream_closed.wake());
// Run the drop function
self.on_drop.take().map(|mut on_drop| {
REFERENCE_CHUTE.desync(move |_| {
(on_drop)()
})
});
}
}
impl<Item> Stream for PipeStream<Item> {
type Item = Item;
fn poll_next(self: Pin<&mut Self>, context: &mut Context) -> Poll<Option<Item>> | };
// If anything needs notifying, do so outside of the lock
notify.map(|notify| notify.wake());
result
}
}
| {
let (result, notify) = {
// Fetch the state from the core (locking the state)
let mut core = self.core.lock().unwrap();
if let Some(item) = core.pending.pop_front() {
// Value waiting at the start of the stream
let notify_backpressure = core.backpressure_release_notify.take();
(Poll::Ready(Some(item)), notify_backpressure)
} else if core.closed {
// No more data will be returned from this stream
(Poll::Ready(None), None)
} else {
// Stream not ready
let notify_backpressure = core.backpressure_release_notify.take();
core.notify = Some(context.waker().clone());
(Poll::Pending, notify_backpressure)
} | identifier_body |
pipe.rs | //!
//! Desync pipes provide a way to generate and process streams via a `Desync` object
//!
//! Pipes are an excellent way to interface `Desync` objects and the futures library. Piping
//! a stream into a `Desync` object is equivalent to spawning it with an executor, except
//! without the need to dedicate a thread to running it.
//!
//! There are two kinds of pipe. The `pipe_in` function creates a pipe that processes each
//! value made available from a stream on a desync object as they arrive, producing no
//! results. This is useful for cases where a `Desync` object is being used as the endpoint
//! for some data processing (for example, to insert the results of an operation into an
//! asynchronous database object).
//!
//! The `pipe` function pipes data through an object. For every input value, it produces
//! an output value. This is good for creating streams that perform some kind of asynchronous
//! processing operation or that need to access data from inside a `Desync` object.
//!
//! Here's an example of using `pipe_in` to store data in a `HashSet`:
//!
//! ```
//! # extern crate futures;
//! # extern crate desync;
//! # use std::collections::HashSet;
//! # use std::sync::*;
//! #
//! use futures::future;
//! use futures::channel::mpsc;
//! use futures::executor;
//! use futures::prelude::*;
//! # use ::desync::*;
//!
//! executor::block_on(async {
//! let desync_hashset = Arc::new(Desync::new(HashSet::new()));
//! let (mut sender, receiver) = mpsc::channel(5);
//!
//! pipe_in(Arc::clone(&desync_hashset), receiver, |hashset, value| { hashset.insert(value); future::ready(()).boxed() });
//!
//! sender.send("Test".to_string()).await.unwrap();
//! sender.send("Another value".to_string()).await.unwrap();
//! #
//! # assert!(desync_hashset.sync(|hashset| hashset.contains(&("Test".to_string()))))
//! });
//! ```
//!
use super::desync::*;
use futures::*;
use futures::future::{BoxFuture};
use futures::stream::{Stream};
use futures::task;
use futures::task::{Poll, Context};
use std::sync::*;
use std::pin::{Pin};
use std::collections::VecDeque;
lazy_static! {
/// Desync for disposing of references used in pipes (if a pipe is closed with pending data, this avoids clearing it in the same context as the pipe monitor)
static ref REFERENCE_CHUTE: Desync<()> = Desync::new(());
}
/// The maximum number of items to queue on a pipe stream before we stop accepting new input
const PIPE_BACKPRESSURE_COUNT: usize = 5;
///
/// Futures notifier used to wake up a pipe when a stream or future notifies
///
struct PipeContext<Core, PollFn>
where Core: Send+Unpin {
/// The desync target that will be woken when the stream notifies that it needs to be polled
/// We keep a weak reference so that if the stream/future is all that's left referencing the
/// desync, it's thrown away
target: Weak<Desync<Core>>,
/// The function that should be called to poll this stream. Returns false if we should no longer keep polling the stream
poll_fn: Arc<Mutex<Option<PollFn>>>
}
impl<Core, PollFn> PipeContext<Core, PollFn>
where Core: 'static+Send+Unpin,
PollFn:'static+Send+for<'a> FnMut(&'a mut Core, Context<'a>) -> BoxFuture<'a, bool> {
///
/// Creates a new pipe context, ready to poll
///
fn new(target: &Arc<Desync<Core>>, poll_fn: PollFn) -> Arc<PipeContext<Core, PollFn>> {
let context = PipeContext {
target: Arc::downgrade(target),
poll_fn: Arc::new(Mutex::new(Some(poll_fn)))
};
Arc::new(context)
}
///
/// Triggers the poll function in the context of the target desync
///
fn poll(arc_self: Arc<Self>) {
// If the desync is stil live...
if let Some(target) = arc_self.target.upgrade() {
// Grab the poll function
let maybe_poll_fn = Arc::clone(&arc_self.poll_fn);
// Schedule a polling operation on the desync
let _ = target.future_desync(move |core| {
async move {
// Create a futures context from the context reference
let waker = task::waker_ref(&arc_self);
let context = Context::from_waker(&waker);
// Pass in to the poll function
let future_poll = {
let mut maybe_poll_fn = maybe_poll_fn.lock().unwrap();
let future_poll = maybe_poll_fn.as_mut().map(|poll_fn| (poll_fn)(core, context));
future_poll
};
if let Some(future_poll) = future_poll {
let keep_polling = future_poll.await;
if!keep_polling {
// Deallocate the function when it's time to stop polling altogether
(*arc_self.poll_fn.lock().unwrap()) = None;
}
}
}.boxed()
});
} else {
// Stream has woken up but the desync is no longer listening
(*arc_self.poll_fn.lock().unwrap()) = None;
}
}
}
impl<Core, PollFn> task::ArcWake for PipeContext<Core, PollFn>
where Core: 'static+Send+Unpin,
PollFn:'static+Send+for<'a> FnMut(&'a mut Core, Context<'a>) -> BoxFuture<'a, bool> {
fn wake_by_ref(arc_self: &Arc<Self>) {
Self::poll(Arc::clone(arc_self));
}
fn wake(self: Arc<Self>) {
Self::poll(self);
}
}
///
/// Pipes a stream into a desync object. Whenever an item becomes available on the stream, the
/// processing function is called asynchronously with the item that was received.
///
/// This takes a weak reference to the passed in `Desync` object, so the pipe will stop if it's
/// the only thing referencing this object.
///
/// Piping a stream to a `Desync` like this will cause it to start executing: ie, this is
/// similar to calling `executor::spawn(stream)`, except that the stream will immediately
/// start draining into the `Desync` object.
///
pub fn pipe_in<Core, S, ProcessFn>(desync: Arc<Desync<Core>>, stream: S, process: ProcessFn)
where Core: 'static+Send+Unpin,
S: 'static+Send+Unpin+Stream,
S::Item: Send,
ProcessFn: 'static+Send+for<'a> FnMut(&'a mut Core, S::Item) -> BoxFuture<'a, ()> {
let stream = Arc::new(Mutex::new(stream));
let process = Arc::new(Mutex::new(process));
// The context is used to trigger polling of the stream
let context = PipeContext::new(&desync, move |core, context| {
let process = Arc::clone(&process);
let stream = Arc::clone(&stream);
async move {
let mut context = context;
loop {
// Poll the stream
let next = stream.lock().unwrap().poll_next_unpin(&mut context);
match next {
// Wait for notification when the stream goes pending
Poll::Pending => return true,
// Stop polling when the stream stops generating new events
Poll::Ready(None) => return false,
// Invoke the callback when there's some data on the stream
Poll::Ready(Some(next)) => {
let process_future = (&mut *process.lock().unwrap())(core, next);
process_future.await;
}
}
}
}.boxed()
});
// Trigger the initial poll
PipeContext::poll(context);
}
///
/// Pipes a stream into this object. Whenever an item becomes available on the stream, the
/// processing function is called asynchronously with the item that was received. The
/// return value is placed onto the output stream.
///
/// Unlike `pipe_in`, this keeps a strong reference to the `Desync` object so the processing
/// will continue so long as the input stream has data and the output stream is not dropped.
///
/// The input stream will start executing and reading values immediately when this is called.
/// Dropping the output stream will cause the pipe to be closed (the input stream will be
/// dropped and no further processing will occur).
///
/// This example demonstrates how to create a simple demonstration pipe that takes hashset values
/// and returns a stream indicating whether or not they were already included:
///
/// ```
/// # extern crate futures;
/// # extern crate desync;
/// # use std::collections::HashSet;
/// # use std::sync::*;
/// #
/// use futures::prelude::*;
/// use futures::future;
/// use futures::channel::mpsc;
/// use futures::executor;
/// # use ::desync::*;
///
/// executor::block_on(async {
/// let desync_hashset = Arc::new(Desync::new(HashSet::new()));
/// let (mut sender, receiver) = mpsc::channel::<String>(5);
///
/// let mut value_inserted = pipe(Arc::clone(&desync_hashset), receiver,
/// |hashset, value| { future::ready((value.clone(), hashset.insert(value))).boxed() });
///
/// sender.send("Test".to_string()).await.unwrap();
/// sender.send("Another value".to_string()).await.unwrap();
/// sender.send("Test".to_string()).await.unwrap();
///
/// assert!(value_inserted.next().await == Some(("Test".to_string(), true)));
/// assert!(value_inserted.next().await == Some(("Another value".to_string(), true)));
/// assert!(value_inserted.next().await == Some(("Test".to_string(), false)));
/// });
/// ```
///
pub fn pipe<Core, S, Output, ProcessFn>(desync: Arc<Desync<Core>>, stream: S, process: ProcessFn) -> PipeStream<Output>
where Core: 'static+Send+Unpin,
S: 'static+Send+Unpin+Stream,
S::Item: Send,
Output: 'static+Send,
ProcessFn: 'static+Send+for <'a> FnMut(&'a mut Core, S::Item) -> BoxFuture<'a, Output> {
// Prepare the streams
let input_stream = Arc::new(Mutex::new(stream));
let process = Arc::new(Mutex::new(process));
let mut output_desync = Some(Arc::clone(&desync));
let output_stream = PipeStream::<Output>::new(move || {
output_desync.take();
});
// Get the core from the output stream
let stream_core = Arc::clone(&output_stream.core);
let stream_core = Arc::downgrade(&stream_core);
// Create the read context
let context = PipeContext::new(&desync, move |core, context| {
let stream_core = stream_core.upgrade(); | if let Some(stream_core) = stream_core {
// Defer processing if the stream core is full
let is_closed = {
// Fetch the core
let mut stream_core = stream_core.lock().unwrap();
// If the pending queue is full, then stop processing events
if stream_core.pending.len() >= stream_core.max_pipe_depth {
// Wake when the stream accepts some input
stream_core.backpressure_release_notify = Some(context.waker().clone());
// Go back to sleep without reading from the stream
return true;
}
// If the core is closed, finish up
stream_core.closed
};
// Wake up the stream and stop reading from the stream if the core is closed
if is_closed {
let notify = { stream_core.lock().unwrap().notify.take() };
notify.map(|notify| notify.wake());
return false;
}
loop {
// Disable the notifier if there was one left over
stream_core.lock().unwrap().notify_stream_closed = None;
// Poll the stream
let next = input_stream.lock().unwrap().poll_next_unpin(&mut context);
match next {
// Wait for notification when the stream goes pending
Poll::Pending => {
stream_core.lock().unwrap().notify_stream_closed = Some(context.waker().clone());
return true
},
// Stop polling when the stream stops generating new events
Poll::Ready(None) => {
// Mark the stream as closed, and wake it up
let notify = {
let mut stream_core = stream_core.lock().unwrap();
stream_core.closed = true;
stream_core.notify.take()
};
notify.map(|notify| notify.wake());
return false;
},
// Invoke the callback when there's some data on the stream
Poll::Ready(Some(next)) => {
// Pipe the next item through
let next_item = (&mut *process.lock().unwrap())(core, next);
let next_item = next_item.await;
// Send to the pipe stream, and wake it up
let notify = {
let mut stream_core = stream_core.lock().unwrap();
stream_core.pending.push_back(next_item);
stream_core.notify.take()
};
notify.map(|notify| notify.wake());
}
}
}
} else {
// The stream core has been released
return false;
}
}.boxed()
});
// Poll the context to start the stream running
PipeContext::poll(context);
output_stream
}
///
/// The shared data for a pipe stream
///
struct PipeStreamCore<Item> {
/// The maximum number of items we allow to be queued in this stream before producing backpressure
max_pipe_depth: usize,
/// The pending data for this stream
pending: VecDeque<Item>,
/// True if the input stream has closed (the stream is closed once this is true and there are no more pending items)
closed: bool,
/// The task to notify when the stream changes
notify: Option<task::Waker>,
/// The task to notify when the stream changes
notify_stream_closed: Option<task::Waker>,
/// The task to notify when we reduce the amount of pending data
backpressure_release_notify: Option<task::Waker>
}
///
/// A stream generated by a pipe
///
pub struct PipeStream<Item> {
/// The core contains the stream state
core: Arc<Mutex<PipeStreamCore<Item>>>,
/// Called when dropping the output stream
on_drop: Option<Box<dyn Send+Sync+FnMut() -> ()>>
}
impl<Item> PipeStream<Item> {
///
/// Creates a new, empty, pipestream
///
fn new<FnOnDrop:'static+Send+Sync+FnMut() -> ()>(on_drop: FnOnDrop) -> PipeStream<Item> {
PipeStream {
core: Arc::new(Mutex::new(PipeStreamCore {
max_pipe_depth: PIPE_BACKPRESSURE_COUNT,
pending: VecDeque::new(),
closed: false,
notify: None,
notify_stream_closed: None,
backpressure_release_notify: None
})),
on_drop: Some(Box::new(on_drop))
}
}
///
/// Sets the number of items that this pipe stream will buffer before producing backpressure
///
/// If this call is not made, this will be set to 5.
///
pub fn set_backpressure_depth(&mut self, max_depth: usize) {
self.core.lock().unwrap().max_pipe_depth = max_depth;
}
}
impl<Item> Drop for PipeStream<Item> {
fn drop(&mut self) {
let mut core = self.core.lock().unwrap();
// Flush the pending queue
core.pending = VecDeque::new();
// Mark the core as closed to stop it from reading from the stream
core.closed = true;
// Wake the stream to finish closing it
core.notify_stream_closed.take().map(|notify_stream_closed| notify_stream_closed.wake());
// Run the drop function
self.on_drop.take().map(|mut on_drop| {
REFERENCE_CHUTE.desync(move |_| {
(on_drop)()
})
});
}
}
impl<Item> Stream for PipeStream<Item> {
type Item = Item;
fn poll_next(self: Pin<&mut Self>, context: &mut Context) -> Poll<Option<Item>> {
let (result, notify) = {
// Fetch the state from the core (locking the state)
let mut core = self.core.lock().unwrap();
if let Some(item) = core.pending.pop_front() {
// Value waiting at the start of the stream
let notify_backpressure = core.backpressure_release_notify.take();
(Poll::Ready(Some(item)), notify_backpressure)
} else if core.closed {
// No more data will be returned from this stream
(Poll::Ready(None), None)
} else {
// Stream not ready
let notify_backpressure = core.backpressure_release_notify.take();
core.notify = Some(context.waker().clone());
(Poll::Pending, notify_backpressure)
}
};
// If anything needs notifying, do so outside of the lock
notify.map(|notify| notify.wake());
result
}
} | let mut context = context;
let input_stream = Arc::clone(&input_stream);
let process = Arc::clone(&process);
async move { | random_line_split |
pipe.rs | //!
//! Desync pipes provide a way to generate and process streams via a `Desync` object
//!
//! Pipes are an excellent way to interface `Desync` objects and the futures library. Piping
//! a stream into a `Desync` object is equivalent to spawning it with an executor, except
//! without the need to dedicate a thread to running it.
//!
//! There are two kinds of pipe. The `pipe_in` function creates a pipe that processes each
//! value made available from a stream on a desync object as they arrive, producing no
//! results. This is useful for cases where a `Desync` object is being used as the endpoint
//! for some data processing (for example, to insert the results of an operation into an
//! asynchronous database object).
//!
//! The `pipe` function pipes data through an object. For every input value, it produces
//! an output value. This is good for creating streams that perform some kind of asynchronous
//! processing operation or that need to access data from inside a `Desync` object.
//!
//! Here's an example of using `pipe_in` to store data in a `HashSet`:
//!
//! ```
//! # extern crate futures;
//! # extern crate desync;
//! # use std::collections::HashSet;
//! # use std::sync::*;
//! #
//! use futures::future;
//! use futures::channel::mpsc;
//! use futures::executor;
//! use futures::prelude::*;
//! # use ::desync::*;
//!
//! executor::block_on(async {
//! let desync_hashset = Arc::new(Desync::new(HashSet::new()));
//! let (mut sender, receiver) = mpsc::channel(5);
//!
//! pipe_in(Arc::clone(&desync_hashset), receiver, |hashset, value| { hashset.insert(value); future::ready(()).boxed() });
//!
//! sender.send("Test".to_string()).await.unwrap();
//! sender.send("Another value".to_string()).await.unwrap();
//! #
//! # assert!(desync_hashset.sync(|hashset| hashset.contains(&("Test".to_string()))))
//! });
//! ```
//!
use super::desync::*;
use futures::*;
use futures::future::{BoxFuture};
use futures::stream::{Stream};
use futures::task;
use futures::task::{Poll, Context};
use std::sync::*;
use std::pin::{Pin};
use std::collections::VecDeque;
lazy_static! {
/// Desync for disposing of references used in pipes (if a pipe is closed with pending data, this avoids clearing it in the same context as the pipe monitor)
static ref REFERENCE_CHUTE: Desync<()> = Desync::new(());
}
/// The maximum number of items to queue on a pipe stream before we stop accepting new input
const PIPE_BACKPRESSURE_COUNT: usize = 5;
///
/// Futures notifier used to wake up a pipe when a stream or future notifies
///
struct PipeContext<Core, PollFn>
where Core: Send+Unpin {
/// The desync target that will be woken when the stream notifies that it needs to be polled
/// We keep a weak reference so that if the stream/future is all that's left referencing the
/// desync, it's thrown away
target: Weak<Desync<Core>>,
/// The function that should be called to poll this stream. Returns false if we should no longer keep polling the stream
poll_fn: Arc<Mutex<Option<PollFn>>>
}
impl<Core, PollFn> PipeContext<Core, PollFn>
where Core: 'static+Send+Unpin,
PollFn:'static+Send+for<'a> FnMut(&'a mut Core, Context<'a>) -> BoxFuture<'a, bool> {
///
/// Creates a new pipe context, ready to poll
///
fn new(target: &Arc<Desync<Core>>, poll_fn: PollFn) -> Arc<PipeContext<Core, PollFn>> {
let context = PipeContext {
target: Arc::downgrade(target),
poll_fn: Arc::new(Mutex::new(Some(poll_fn)))
};
Arc::new(context)
}
///
/// Triggers the poll function in the context of the target desync
///
fn poll(arc_self: Arc<Self>) {
// If the desync is stil live...
if let Some(target) = arc_self.target.upgrade() {
// Grab the poll function
let maybe_poll_fn = Arc::clone(&arc_self.poll_fn);
// Schedule a polling operation on the desync
let _ = target.future_desync(move |core| {
async move {
// Create a futures context from the context reference
let waker = task::waker_ref(&arc_self);
let context = Context::from_waker(&waker);
// Pass in to the poll function
let future_poll = {
let mut maybe_poll_fn = maybe_poll_fn.lock().unwrap();
let future_poll = maybe_poll_fn.as_mut().map(|poll_fn| (poll_fn)(core, context));
future_poll
};
if let Some(future_poll) = future_poll {
let keep_polling = future_poll.await;
if!keep_polling {
// Deallocate the function when it's time to stop polling altogether
(*arc_self.poll_fn.lock().unwrap()) = None;
}
}
}.boxed()
});
} else {
// Stream has woken up but the desync is no longer listening
(*arc_self.poll_fn.lock().unwrap()) = None;
}
}
}
impl<Core, PollFn> task::ArcWake for PipeContext<Core, PollFn>
where Core: 'static+Send+Unpin,
PollFn:'static+Send+for<'a> FnMut(&'a mut Core, Context<'a>) -> BoxFuture<'a, bool> {
fn wake_by_ref(arc_self: &Arc<Self>) {
Self::poll(Arc::clone(arc_self));
}
fn wake(self: Arc<Self>) {
Self::poll(self);
}
}
///
/// Pipes a stream into a desync object. Whenever an item becomes available on the stream, the
/// processing function is called asynchronously with the item that was received.
///
/// This takes a weak reference to the passed in `Desync` object, so the pipe will stop if it's
/// the only thing referencing this object.
///
/// Piping a stream to a `Desync` like this will cause it to start executing: ie, this is
/// similar to calling `executor::spawn(stream)`, except that the stream will immediately
/// start draining into the `Desync` object.
///
pub fn pipe_in<Core, S, ProcessFn>(desync: Arc<Desync<Core>>, stream: S, process: ProcessFn)
where Core: 'static+Send+Unpin,
S: 'static+Send+Unpin+Stream,
S::Item: Send,
ProcessFn: 'static+Send+for<'a> FnMut(&'a mut Core, S::Item) -> BoxFuture<'a, ()> {
let stream = Arc::new(Mutex::new(stream));
let process = Arc::new(Mutex::new(process));
// The context is used to trigger polling of the stream
let context = PipeContext::new(&desync, move |core, context| {
let process = Arc::clone(&process);
let stream = Arc::clone(&stream);
async move {
let mut context = context;
loop {
// Poll the stream
let next = stream.lock().unwrap().poll_next_unpin(&mut context);
match next {
// Wait for notification when the stream goes pending
Poll::Pending => return true,
// Stop polling when the stream stops generating new events
Poll::Ready(None) => return false,
// Invoke the callback when there's some data on the stream
Poll::Ready(Some(next)) => {
let process_future = (&mut *process.lock().unwrap())(core, next);
process_future.await;
}
}
}
}.boxed()
});
// Trigger the initial poll
PipeContext::poll(context);
}
///
/// Pipes a stream into this object. Whenever an item becomes available on the stream, the
/// processing function is called asynchronously with the item that was received. The
/// return value is placed onto the output stream.
///
/// Unlike `pipe_in`, this keeps a strong reference to the `Desync` object so the processing
/// will continue so long as the input stream has data and the output stream is not dropped.
///
/// The input stream will start executing and reading values immediately when this is called.
/// Dropping the output stream will cause the pipe to be closed (the input stream will be
/// dropped and no further processing will occur).
///
/// This example demonstrates how to create a simple demonstration pipe that takes hashset values
/// and returns a stream indicating whether or not they were already included:
///
/// ```
/// # extern crate futures;
/// # extern crate desync;
/// # use std::collections::HashSet;
/// # use std::sync::*;
/// #
/// use futures::prelude::*;
/// use futures::future;
/// use futures::channel::mpsc;
/// use futures::executor;
/// # use ::desync::*;
///
/// executor::block_on(async {
/// let desync_hashset = Arc::new(Desync::new(HashSet::new()));
/// let (mut sender, receiver) = mpsc::channel::<String>(5);
///
/// let mut value_inserted = pipe(Arc::clone(&desync_hashset), receiver,
/// |hashset, value| { future::ready((value.clone(), hashset.insert(value))).boxed() });
///
/// sender.send("Test".to_string()).await.unwrap();
/// sender.send("Another value".to_string()).await.unwrap();
/// sender.send("Test".to_string()).await.unwrap();
///
/// assert!(value_inserted.next().await == Some(("Test".to_string(), true)));
/// assert!(value_inserted.next().await == Some(("Another value".to_string(), true)));
/// assert!(value_inserted.next().await == Some(("Test".to_string(), false)));
/// });
/// ```
///
pub fn pipe<Core, S, Output, ProcessFn>(desync: Arc<Desync<Core>>, stream: S, process: ProcessFn) -> PipeStream<Output>
where Core: 'static+Send+Unpin,
S: 'static+Send+Unpin+Stream,
S::Item: Send,
Output: 'static+Send,
ProcessFn: 'static+Send+for <'a> FnMut(&'a mut Core, S::Item) -> BoxFuture<'a, Output> {
// Prepare the streams
let input_stream = Arc::new(Mutex::new(stream));
let process = Arc::new(Mutex::new(process));
let mut output_desync = Some(Arc::clone(&desync));
let output_stream = PipeStream::<Output>::new(move || {
output_desync.take();
});
// Get the core from the output stream
let stream_core = Arc::clone(&output_stream.core);
let stream_core = Arc::downgrade(&stream_core);
// Create the read context
let context = PipeContext::new(&desync, move |core, context| {
let stream_core = stream_core.upgrade();
let mut context = context;
let input_stream = Arc::clone(&input_stream);
let process = Arc::clone(&process);
async move {
if let Some(stream_core) = stream_core {
// Defer processing if the stream core is full
let is_closed = {
// Fetch the core
let mut stream_core = stream_core.lock().unwrap();
// If the pending queue is full, then stop processing events
if stream_core.pending.len() >= stream_core.max_pipe_depth {
// Wake when the stream accepts some input
stream_core.backpressure_release_notify = Some(context.waker().clone());
// Go back to sleep without reading from the stream
return true;
}
// If the core is closed, finish up
stream_core.closed
};
// Wake up the stream and stop reading from the stream if the core is closed
if is_closed {
let notify = { stream_core.lock().unwrap().notify.take() };
notify.map(|notify| notify.wake());
return false;
}
loop {
// Disable the notifier if there was one left over
stream_core.lock().unwrap().notify_stream_closed = None;
// Poll the stream
let next = input_stream.lock().unwrap().poll_next_unpin(&mut context);
match next {
// Wait for notification when the stream goes pending
Poll::Pending => {
stream_core.lock().unwrap().notify_stream_closed = Some(context.waker().clone());
return true
},
// Stop polling when the stream stops generating new events
Poll::Ready(None) => {
// Mark the stream as closed, and wake it up
let notify = {
let mut stream_core = stream_core.lock().unwrap();
stream_core.closed = true;
stream_core.notify.take()
};
notify.map(|notify| notify.wake());
return false;
},
// Invoke the callback when there's some data on the stream
Poll::Ready(Some(next)) => {
// Pipe the next item through
let next_item = (&mut *process.lock().unwrap())(core, next);
let next_item = next_item.await;
// Send to the pipe stream, and wake it up
let notify = {
let mut stream_core = stream_core.lock().unwrap();
stream_core.pending.push_back(next_item);
stream_core.notify.take()
};
notify.map(|notify| notify.wake());
}
}
}
} else {
// The stream core has been released
return false;
}
}.boxed()
});
// Poll the context to start the stream running
PipeContext::poll(context);
output_stream
}
///
/// The shared data for a pipe stream
///
struct PipeStreamCore<Item> {
/// The maximum number of items we allow to be queued in this stream before producing backpressure
max_pipe_depth: usize,
/// The pending data for this stream
pending: VecDeque<Item>,
/// True if the input stream has closed (the stream is closed once this is true and there are no more pending items)
closed: bool,
/// The task to notify when the stream changes
notify: Option<task::Waker>,
/// The task to notify when the stream changes
notify_stream_closed: Option<task::Waker>,
/// The task to notify when we reduce the amount of pending data
backpressure_release_notify: Option<task::Waker>
}
///
/// A stream generated by a pipe
///
pub struct PipeStream<Item> {
/// The core contains the stream state
core: Arc<Mutex<PipeStreamCore<Item>>>,
/// Called when dropping the output stream
on_drop: Option<Box<dyn Send+Sync+FnMut() -> ()>>
}
impl<Item> PipeStream<Item> {
///
/// Creates a new, empty, pipestream
///
fn new<FnOnDrop:'static+Send+Sync+FnMut() -> ()>(on_drop: FnOnDrop) -> PipeStream<Item> {
PipeStream {
core: Arc::new(Mutex::new(PipeStreamCore {
max_pipe_depth: PIPE_BACKPRESSURE_COUNT,
pending: VecDeque::new(),
closed: false,
notify: None,
notify_stream_closed: None,
backpressure_release_notify: None
})),
on_drop: Some(Box::new(on_drop))
}
}
///
/// Sets the number of items that this pipe stream will buffer before producing backpressure
///
/// If this call is not made, this will be set to 5.
///
pub fn set_backpressure_depth(&mut self, max_depth: usize) {
self.core.lock().unwrap().max_pipe_depth = max_depth;
}
}
impl<Item> Drop for PipeStream<Item> {
fn drop(&mut self) {
let mut core = self.core.lock().unwrap();
// Flush the pending queue
core.pending = VecDeque::new();
// Mark the core as closed to stop it from reading from the stream
core.closed = true;
// Wake the stream to finish closing it
core.notify_stream_closed.take().map(|notify_stream_closed| notify_stream_closed.wake());
// Run the drop function
self.on_drop.take().map(|mut on_drop| {
REFERENCE_CHUTE.desync(move |_| {
(on_drop)()
})
});
}
}
impl<Item> Stream for PipeStream<Item> {
type Item = Item;
fn poll_next(self: Pin<&mut Self>, context: &mut Context) -> Poll<Option<Item>> {
let (result, notify) = {
// Fetch the state from the core (locking the state)
let mut core = self.core.lock().unwrap();
if let Some(item) = core.pending.pop_front() {
// Value waiting at the start of the stream
let notify_backpressure = core.backpressure_release_notify.take();
(Poll::Ready(Some(item)), notify_backpressure)
} else if core.closed {
// No more data will be returned from this stream
(Poll::Ready(None), None)
} else |
};
// If anything needs notifying, do so outside of the lock
notify.map(|notify| notify.wake());
result
}
}
| {
// Stream not ready
let notify_backpressure = core.backpressure_release_notify.take();
core.notify = Some(context.waker().clone());
(Poll::Pending, notify_backpressure)
} | conditional_block |
pipe.rs | //!
//! Desync pipes provide a way to generate and process streams via a `Desync` object
//!
//! Pipes are an excellent way to interface `Desync` objects and the futures library. Piping
//! a stream into a `Desync` object is equivalent to spawning it with an executor, except
//! without the need to dedicate a thread to running it.
//!
//! There are two kinds of pipe. The `pipe_in` function creates a pipe that processes each
//! value made available from a stream on a desync object as they arrive, producing no
//! results. This is useful for cases where a `Desync` object is being used as the endpoint
//! for some data processing (for example, to insert the results of an operation into an
//! asynchronous database object).
//!
//! The `pipe` function pipes data through an object. For every input value, it produces
//! an output value. This is good for creating streams that perform some kind of asynchronous
//! processing operation or that need to access data from inside a `Desync` object.
//!
//! Here's an example of using `pipe_in` to store data in a `HashSet`:
//!
//! ```
//! # extern crate futures;
//! # extern crate desync;
//! # use std::collections::HashSet;
//! # use std::sync::*;
//! #
//! use futures::future;
//! use futures::channel::mpsc;
//! use futures::executor;
//! use futures::prelude::*;
//! # use ::desync::*;
//!
//! executor::block_on(async {
//! let desync_hashset = Arc::new(Desync::new(HashSet::new()));
//! let (mut sender, receiver) = mpsc::channel(5);
//!
//! pipe_in(Arc::clone(&desync_hashset), receiver, |hashset, value| { hashset.insert(value); future::ready(()).boxed() });
//!
//! sender.send("Test".to_string()).await.unwrap();
//! sender.send("Another value".to_string()).await.unwrap();
//! #
//! # assert!(desync_hashset.sync(|hashset| hashset.contains(&("Test".to_string()))))
//! });
//! ```
//!
use super::desync::*;
use futures::*;
use futures::future::{BoxFuture};
use futures::stream::{Stream};
use futures::task;
use futures::task::{Poll, Context};
use std::sync::*;
use std::pin::{Pin};
use std::collections::VecDeque;
lazy_static! {
/// Desync for disposing of references used in pipes (if a pipe is closed with pending data, this avoids clearing it in the same context as the pipe monitor)
static ref REFERENCE_CHUTE: Desync<()> = Desync::new(());
}
/// The maximum number of items to queue on a pipe stream before we stop accepting new input
const PIPE_BACKPRESSURE_COUNT: usize = 5;
///
/// Futures notifier used to wake up a pipe when a stream or future notifies
///
struct PipeContext<Core, PollFn>
where Core: Send+Unpin {
/// The desync target that will be woken when the stream notifies that it needs to be polled
/// We keep a weak reference so that if the stream/future is all that's left referencing the
/// desync, it's thrown away
target: Weak<Desync<Core>>,
/// The function that should be called to poll this stream. Returns false if we should no longer keep polling the stream
poll_fn: Arc<Mutex<Option<PollFn>>>
}
impl<Core, PollFn> PipeContext<Core, PollFn>
where Core: 'static+Send+Unpin,
PollFn:'static+Send+for<'a> FnMut(&'a mut Core, Context<'a>) -> BoxFuture<'a, bool> {
///
/// Creates a new pipe context, ready to poll
///
fn new(target: &Arc<Desync<Core>>, poll_fn: PollFn) -> Arc<PipeContext<Core, PollFn>> {
let context = PipeContext {
target: Arc::downgrade(target),
poll_fn: Arc::new(Mutex::new(Some(poll_fn)))
};
Arc::new(context)
}
///
/// Triggers the poll function in the context of the target desync
///
fn poll(arc_self: Arc<Self>) {
// If the desync is stil live...
if let Some(target) = arc_self.target.upgrade() {
// Grab the poll function
let maybe_poll_fn = Arc::clone(&arc_self.poll_fn);
// Schedule a polling operation on the desync
let _ = target.future_desync(move |core| {
async move {
// Create a futures context from the context reference
let waker = task::waker_ref(&arc_self);
let context = Context::from_waker(&waker);
// Pass in to the poll function
let future_poll = {
let mut maybe_poll_fn = maybe_poll_fn.lock().unwrap();
let future_poll = maybe_poll_fn.as_mut().map(|poll_fn| (poll_fn)(core, context));
future_poll
};
if let Some(future_poll) = future_poll {
let keep_polling = future_poll.await;
if!keep_polling {
// Deallocate the function when it's time to stop polling altogether
(*arc_self.poll_fn.lock().unwrap()) = None;
}
}
}.boxed()
});
} else {
// Stream has woken up but the desync is no longer listening
(*arc_self.poll_fn.lock().unwrap()) = None;
}
}
}
impl<Core, PollFn> task::ArcWake for PipeContext<Core, PollFn>
where Core: 'static+Send+Unpin,
PollFn:'static+Send+for<'a> FnMut(&'a mut Core, Context<'a>) -> BoxFuture<'a, bool> {
fn wake_by_ref(arc_self: &Arc<Self>) {
Self::poll(Arc::clone(arc_self));
}
fn wake(self: Arc<Self>) {
Self::poll(self);
}
}
///
/// Pipes a stream into a desync object. Whenever an item becomes available on the stream, the
/// processing function is called asynchronously with the item that was received.
///
/// This takes a weak reference to the passed in `Desync` object, so the pipe will stop if it's
/// the only thing referencing this object.
///
/// Piping a stream to a `Desync` like this will cause it to start executing: ie, this is
/// similar to calling `executor::spawn(stream)`, except that the stream will immediately
/// start draining into the `Desync` object.
///
pub fn pipe_in<Core, S, ProcessFn>(desync: Arc<Desync<Core>>, stream: S, process: ProcessFn)
where Core: 'static+Send+Unpin,
S: 'static+Send+Unpin+Stream,
S::Item: Send,
ProcessFn: 'static+Send+for<'a> FnMut(&'a mut Core, S::Item) -> BoxFuture<'a, ()> {
let stream = Arc::new(Mutex::new(stream));
let process = Arc::new(Mutex::new(process));
// The context is used to trigger polling of the stream
let context = PipeContext::new(&desync, move |core, context| {
let process = Arc::clone(&process);
let stream = Arc::clone(&stream);
async move {
let mut context = context;
loop {
// Poll the stream
let next = stream.lock().unwrap().poll_next_unpin(&mut context);
match next {
// Wait for notification when the stream goes pending
Poll::Pending => return true,
// Stop polling when the stream stops generating new events
Poll::Ready(None) => return false,
// Invoke the callback when there's some data on the stream
Poll::Ready(Some(next)) => {
let process_future = (&mut *process.lock().unwrap())(core, next);
process_future.await;
}
}
}
}.boxed()
});
// Trigger the initial poll
PipeContext::poll(context);
}
///
/// Pipes a stream into this object. Whenever an item becomes available on the stream, the
/// processing function is called asynchronously with the item that was received. The
/// return value is placed onto the output stream.
///
/// Unlike `pipe_in`, this keeps a strong reference to the `Desync` object so the processing
/// will continue so long as the input stream has data and the output stream is not dropped.
///
/// The input stream will start executing and reading values immediately when this is called.
/// Dropping the output stream will cause the pipe to be closed (the input stream will be
/// dropped and no further processing will occur).
///
/// This example demonstrates how to create a simple demonstration pipe that takes hashset values
/// and returns a stream indicating whether or not they were already included:
///
/// ```
/// # extern crate futures;
/// # extern crate desync;
/// # use std::collections::HashSet;
/// # use std::sync::*;
/// #
/// use futures::prelude::*;
/// use futures::future;
/// use futures::channel::mpsc;
/// use futures::executor;
/// # use ::desync::*;
///
/// executor::block_on(async {
/// let desync_hashset = Arc::new(Desync::new(HashSet::new()));
/// let (mut sender, receiver) = mpsc::channel::<String>(5);
///
/// let mut value_inserted = pipe(Arc::clone(&desync_hashset), receiver,
/// |hashset, value| { future::ready((value.clone(), hashset.insert(value))).boxed() });
///
/// sender.send("Test".to_string()).await.unwrap();
/// sender.send("Another value".to_string()).await.unwrap();
/// sender.send("Test".to_string()).await.unwrap();
///
/// assert!(value_inserted.next().await == Some(("Test".to_string(), true)));
/// assert!(value_inserted.next().await == Some(("Another value".to_string(), true)));
/// assert!(value_inserted.next().await == Some(("Test".to_string(), false)));
/// });
/// ```
///
pub fn pipe<Core, S, Output, ProcessFn>(desync: Arc<Desync<Core>>, stream: S, process: ProcessFn) -> PipeStream<Output>
where Core: 'static+Send+Unpin,
S: 'static+Send+Unpin+Stream,
S::Item: Send,
Output: 'static+Send,
ProcessFn: 'static+Send+for <'a> FnMut(&'a mut Core, S::Item) -> BoxFuture<'a, Output> {
// Prepare the streams
let input_stream = Arc::new(Mutex::new(stream));
let process = Arc::new(Mutex::new(process));
let mut output_desync = Some(Arc::clone(&desync));
let output_stream = PipeStream::<Output>::new(move || {
output_desync.take();
});
// Get the core from the output stream
let stream_core = Arc::clone(&output_stream.core);
let stream_core = Arc::downgrade(&stream_core);
// Create the read context
let context = PipeContext::new(&desync, move |core, context| {
let stream_core = stream_core.upgrade();
let mut context = context;
let input_stream = Arc::clone(&input_stream);
let process = Arc::clone(&process);
async move {
if let Some(stream_core) = stream_core {
// Defer processing if the stream core is full
let is_closed = {
// Fetch the core
let mut stream_core = stream_core.lock().unwrap();
// If the pending queue is full, then stop processing events
if stream_core.pending.len() >= stream_core.max_pipe_depth {
// Wake when the stream accepts some input
stream_core.backpressure_release_notify = Some(context.waker().clone());
// Go back to sleep without reading from the stream
return true;
}
// If the core is closed, finish up
stream_core.closed
};
// Wake up the stream and stop reading from the stream if the core is closed
if is_closed {
let notify = { stream_core.lock().unwrap().notify.take() };
notify.map(|notify| notify.wake());
return false;
}
loop {
// Disable the notifier if there was one left over
stream_core.lock().unwrap().notify_stream_closed = None;
// Poll the stream
let next = input_stream.lock().unwrap().poll_next_unpin(&mut context);
match next {
// Wait for notification when the stream goes pending
Poll::Pending => {
stream_core.lock().unwrap().notify_stream_closed = Some(context.waker().clone());
return true
},
// Stop polling when the stream stops generating new events
Poll::Ready(None) => {
// Mark the stream as closed, and wake it up
let notify = {
let mut stream_core = stream_core.lock().unwrap();
stream_core.closed = true;
stream_core.notify.take()
};
notify.map(|notify| notify.wake());
return false;
},
// Invoke the callback when there's some data on the stream
Poll::Ready(Some(next)) => {
// Pipe the next item through
let next_item = (&mut *process.lock().unwrap())(core, next);
let next_item = next_item.await;
// Send to the pipe stream, and wake it up
let notify = {
let mut stream_core = stream_core.lock().unwrap();
stream_core.pending.push_back(next_item);
stream_core.notify.take()
};
notify.map(|notify| notify.wake());
}
}
}
} else {
// The stream core has been released
return false;
}
}.boxed()
});
// Poll the context to start the stream running
PipeContext::poll(context);
output_stream
}
///
/// The shared data for a pipe stream
///
struct PipeStreamCore<Item> {
/// The maximum number of items we allow to be queued in this stream before producing backpressure
max_pipe_depth: usize,
/// The pending data for this stream
pending: VecDeque<Item>,
/// True if the input stream has closed (the stream is closed once this is true and there are no more pending items)
closed: bool,
/// The task to notify when the stream changes
notify: Option<task::Waker>,
/// The task to notify when the stream changes
notify_stream_closed: Option<task::Waker>,
/// The task to notify when we reduce the amount of pending data
backpressure_release_notify: Option<task::Waker>
}
///
/// A stream generated by a pipe
///
pub struct PipeStream<Item> {
/// The core contains the stream state
core: Arc<Mutex<PipeStreamCore<Item>>>,
/// Called when dropping the output stream
on_drop: Option<Box<dyn Send+Sync+FnMut() -> ()>>
}
impl<Item> PipeStream<Item> {
///
/// Creates a new, empty, pipestream
///
fn new<FnOnDrop:'static+Send+Sync+FnMut() -> ()>(on_drop: FnOnDrop) -> PipeStream<Item> {
PipeStream {
core: Arc::new(Mutex::new(PipeStreamCore {
max_pipe_depth: PIPE_BACKPRESSURE_COUNT,
pending: VecDeque::new(),
closed: false,
notify: None,
notify_stream_closed: None,
backpressure_release_notify: None
})),
on_drop: Some(Box::new(on_drop))
}
}
///
/// Sets the number of items that this pipe stream will buffer before producing backpressure
///
/// If this call is not made, this will be set to 5.
///
pub fn set_backpressure_depth(&mut self, max_depth: usize) {
self.core.lock().unwrap().max_pipe_depth = max_depth;
}
}
impl<Item> Drop for PipeStream<Item> {
fn | (&mut self) {
let mut core = self.core.lock().unwrap();
// Flush the pending queue
core.pending = VecDeque::new();
// Mark the core as closed to stop it from reading from the stream
core.closed = true;
// Wake the stream to finish closing it
core.notify_stream_closed.take().map(|notify_stream_closed| notify_stream_closed.wake());
// Run the drop function
self.on_drop.take().map(|mut on_drop| {
REFERENCE_CHUTE.desync(move |_| {
(on_drop)()
})
});
}
}
impl<Item> Stream for PipeStream<Item> {
type Item = Item;
fn poll_next(self: Pin<&mut Self>, context: &mut Context) -> Poll<Option<Item>> {
let (result, notify) = {
// Fetch the state from the core (locking the state)
let mut core = self.core.lock().unwrap();
if let Some(item) = core.pending.pop_front() {
// Value waiting at the start of the stream
let notify_backpressure = core.backpressure_release_notify.take();
(Poll::Ready(Some(item)), notify_backpressure)
} else if core.closed {
// No more data will be returned from this stream
(Poll::Ready(None), None)
} else {
// Stream not ready
let notify_backpressure = core.backpressure_release_notify.take();
core.notify = Some(context.waker().clone());
(Poll::Pending, notify_backpressure)
}
};
// If anything needs notifying, do so outside of the lock
notify.map(|notify| notify.wake());
result
}
}
| drop | identifier_name |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool {
slice.bytes().all(|c|
c == b'\x21' || (c >= b'\x23' && c <= b'\x7e') | (c >= b'\x80' && c <= b'\xff'))
}
/// An entity tag, defined in [RFC7232](https://tools.ietf.org/html/rfc7232#section-2.3)
///
/// An entity tag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like `W/`. Examples for valid tags are `"xyzzy"` and `W/"xyzzy"`.
///
/// # ABNF
/// ```plain
/// entity-tag = [ weak ] opaque-tag
/// weak = %x57.2F ; "W/", case-sensitive
/// opaque-tag = DQUOTE *etagc DQUOTE
/// etagc = %x21 / %x23-7E / obs-text
/// ; VCHAR except double quotes, plus obs-text
/// ```
///
/// # Comparison
/// To check if two entity tags are equivalent in an application always use the `strong_eq` or
/// `weak_eq` methods based on the context of the Tag. Only use `==` to check if two tags are
/// identical.
///
/// The example below shows the results for a set of entity-tag pairs and
/// both the weak and strong comparison function results:
///
/// | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison |
/// |---------|---------|-------------------|-----------------|
/// | `W/"1"` | `W/"1"` | no match | match |
/// | `W/"1"` | `W/"2"` | no match | no match |
/// | `W/"1"` | `"1"` | no match | match |
/// | `"1"` | `"1"` | match | match |
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
tag: String
}
impl EntityTag {
/// Constructs a new EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn new(weak: bool, tag: String) -> EntityTag {
assert!(check_slice_validity(&tag), "Invalid tag: {:?}", tag);
EntityTag { weak: weak, tag: tag }
}
/// Constructs a new weak EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn weak(tag: String) -> EntityTag {
EntityTag::new(true, tag)
}
/// Constructs a new strong EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn strong(tag: String) -> EntityTag {
EntityTag::new(false, tag)
}
/// Get the tag.
pub fn tag(&self) -> &str {
self.tag.as_ref()
}
/// Set the tag.
/// # Panics
/// If the tag contains invalid characters.
pub fn set_tag(&mut self, tag: String) {
assert!(check_slice_validity(&tag), "Invalid tag: {:?}", tag);
self.tag = tag
}
/// For strong comparison two entity-tags are equivalent if both are not weak and their
/// opaque-tags match character-by-character.
pub fn strong_eq(&self, other: &EntityTag) -> bool {
!self.weak &&!other.weak && self.tag == other.tag
}
/// For weak comparison two entity-tags are equivalent if their
/// opaque-tags match character-by-character, regardless of either or
/// both being tagged as "weak".
pub fn weak_eq(&self, other: &EntityTag) -> bool {
self.tag == other.tag
}
/// The inverse of `EntityTag.strong_eq()`.
pub fn strong_ne(&self, other: &EntityTag) -> bool {
!self.strong_eq(other)
}
| !self.weak_eq(other)
}
}
impl Display for EntityTag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
write!(f, "W/\"{}\"", self.tag)
} else {
write!(f, "\"{}\"", self.tag)
}
}
}
impl FromStr for EntityTag {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<EntityTag> {
let length: usize = s.len();
let slice = &s[..];
// Early exits if it doesn't terminate in a DQUOTE.
if!slice.ends_with('"') {
return Err(::Error::Header);
}
// The etag is weak if its first char is not a DQUOTE.
if slice.starts_with('"') && check_slice_validity(&slice[1..length-1]) {
// No need to check if the last char is a DQUOTE,
// we already did that above.
return Ok(EntityTag { weak: false, tag: slice[1..length-1].to_owned() });
} else if slice.starts_with("W/\"") && check_slice_validity(&slice[3..length-1]) {
return Ok(EntityTag { weak: true, tag: slice[3..length-1].to_owned() });
}
Err(::Error::Header)
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_parse_success() {
// Expected success
assert_eq!("\"foobar\"".parse::<EntityTag>().unwrap(),
EntityTag::strong("foobar".to_owned()));
assert_eq!("\"\"".parse::<EntityTag>().unwrap(),
EntityTag::strong("".to_owned()));
assert_eq!("W/\"weaktag\"".parse::<EntityTag>().unwrap(),
EntityTag::weak("weaktag".to_owned()));
assert_eq!("W/\"\x65\x62\"".parse::<EntityTag>().unwrap(),
EntityTag::weak("\x65\x62".to_owned()));
assert_eq!("W/\"\"".parse::<EntityTag>().unwrap(), EntityTag::weak("".to_owned()));
}
#[test]
fn test_etag_parse_failures() {
// Expected failures
assert!("no-dquotes".parse::<EntityTag>().is_err());
assert!("w/\"the-first-w-is-case-sensitive\"".parse::<EntityTag>().is_err());
assert!("".parse::<EntityTag>().is_err());
assert!("\"unmatched-dquotes1".parse::<EntityTag>().is_err());
assert!("unmatched-dquotes2\"".parse::<EntityTag>().is_err());
assert!("matched-\"dquotes\"".parse::<EntityTag>().is_err());
}
#[test]
fn test_etag_fmt() {
assert_eq!(format!("{}", EntityTag::strong("foobar".to_owned())), "\"foobar\"");
assert_eq!(format!("{}", EntityTag::strong("".to_owned())), "\"\"");
assert_eq!(format!("{}", EntityTag::weak("weak-etag".to_owned())), "W/\"weak-etag\"");
assert_eq!(format!("{}", EntityTag::weak("\u{0065}".to_owned())), "W/\"\x65\"");
assert_eq!(format!("{}", EntityTag::weak("".to_owned())), "W/\"\"");
}
#[test]
fn test_cmp() {
// | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison |
// |---------|---------|-------------------|-----------------|
// | `W/"1"` | `W/"1"` | no match | match |
// | `W/"1"` | `W/"2"` | no match | no match |
// | `W/"1"` | `"1"` | no match | match |
// | `"1"` | `"1"` | match | match |
let mut etag1 = EntityTag::weak("1".to_owned());
let mut etag2 = EntityTag::weak("1".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
etag1 = EntityTag::weak("1".to_owned());
etag2 = EntityTag::weak("2".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(!etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(etag1.weak_ne(&etag2));
etag1 = EntityTag::weak("1".to_owned());
etag2 = EntityTag::strong("1".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
etag1 = EntityTag::strong("1".to_owned());
etag2 = EntityTag::strong("1".to_owned());
assert!(etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(!etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
}
} | /// The inverse of `EntityTag.weak_eq()`.
pub fn weak_ne(&self, other: &EntityTag) -> bool { | random_line_split |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool {
slice.bytes().all(|c|
c == b'\x21' || (c >= b'\x23' && c <= b'\x7e') | (c >= b'\x80' && c <= b'\xff'))
}
/// An entity tag, defined in [RFC7232](https://tools.ietf.org/html/rfc7232#section-2.3)
///
/// An entity tag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like `W/`. Examples for valid tags are `"xyzzy"` and `W/"xyzzy"`.
///
/// # ABNF
/// ```plain
/// entity-tag = [ weak ] opaque-tag
/// weak = %x57.2F ; "W/", case-sensitive
/// opaque-tag = DQUOTE *etagc DQUOTE
/// etagc = %x21 / %x23-7E / obs-text
/// ; VCHAR except double quotes, plus obs-text
/// ```
///
/// # Comparison
/// To check if two entity tags are equivalent in an application always use the `strong_eq` or
/// `weak_eq` methods based on the context of the Tag. Only use `==` to check if two tags are
/// identical.
///
/// The example below shows the results for a set of entity-tag pairs and
/// both the weak and strong comparison function results:
///
/// | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison |
/// |---------|---------|-------------------|-----------------|
/// | `W/"1"` | `W/"1"` | no match | match |
/// | `W/"1"` | `W/"2"` | no match | no match |
/// | `W/"1"` | `"1"` | no match | match |
/// | `"1"` | `"1"` | match | match |
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
tag: String
}
impl EntityTag {
/// Constructs a new EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn new(weak: bool, tag: String) -> EntityTag {
assert!(check_slice_validity(&tag), "Invalid tag: {:?}", tag);
EntityTag { weak: weak, tag: tag }
}
/// Constructs a new weak EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn weak(tag: String) -> EntityTag {
EntityTag::new(true, tag)
}
/// Constructs a new strong EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn strong(tag: String) -> EntityTag {
EntityTag::new(false, tag)
}
/// Get the tag.
pub fn tag(&self) -> &str {
self.tag.as_ref()
}
/// Set the tag.
/// # Panics
/// If the tag contains invalid characters.
pub fn set_tag(&mut self, tag: String) {
assert!(check_slice_validity(&tag), "Invalid tag: {:?}", tag);
self.tag = tag
}
/// For strong comparison two entity-tags are equivalent if both are not weak and their
/// opaque-tags match character-by-character.
pub fn strong_eq(&self, other: &EntityTag) -> bool {
!self.weak &&!other.weak && self.tag == other.tag
}
/// For weak comparison two entity-tags are equivalent if their
/// opaque-tags match character-by-character, regardless of either or
/// both being tagged as "weak".
pub fn weak_eq(&self, other: &EntityTag) -> bool {
self.tag == other.tag
}
/// The inverse of `EntityTag.strong_eq()`.
pub fn strong_ne(&self, other: &EntityTag) -> bool {
!self.strong_eq(other)
}
/// The inverse of `EntityTag.weak_eq()`.
pub fn weak_ne(&self, other: &EntityTag) -> bool {
!self.weak_eq(other)
}
}
impl Display for EntityTag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
write!(f, "W/\"{}\"", self.tag)
} else {
write!(f, "\"{}\"", self.tag)
}
}
}
impl FromStr for EntityTag {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<EntityTag> {
let length: usize = s.len();
let slice = &s[..];
// Early exits if it doesn't terminate in a DQUOTE.
if!slice.ends_with('"') {
return Err(::Error::Header);
}
// The etag is weak if its first char is not a DQUOTE.
if slice.starts_with('"') && check_slice_validity(&slice[1..length-1]) {
// No need to check if the last char is a DQUOTE,
// we already did that above.
return Ok(EntityTag { weak: false, tag: slice[1..length-1].to_owned() });
} else if slice.starts_with("W/\"") && check_slice_validity(&slice[3..length-1]) |
Err(::Error::Header)
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_parse_success() {
// Expected success
assert_eq!("\"foobar\"".parse::<EntityTag>().unwrap(),
EntityTag::strong("foobar".to_owned()));
assert_eq!("\"\"".parse::<EntityTag>().unwrap(),
EntityTag::strong("".to_owned()));
assert_eq!("W/\"weaktag\"".parse::<EntityTag>().unwrap(),
EntityTag::weak("weaktag".to_owned()));
assert_eq!("W/\"\x65\x62\"".parse::<EntityTag>().unwrap(),
EntityTag::weak("\x65\x62".to_owned()));
assert_eq!("W/\"\"".parse::<EntityTag>().unwrap(), EntityTag::weak("".to_owned()));
}
#[test]
fn test_etag_parse_failures() {
// Expected failures
assert!("no-dquotes".parse::<EntityTag>().is_err());
assert!("w/\"the-first-w-is-case-sensitive\"".parse::<EntityTag>().is_err());
assert!("".parse::<EntityTag>().is_err());
assert!("\"unmatched-dquotes1".parse::<EntityTag>().is_err());
assert!("unmatched-dquotes2\"".parse::<EntityTag>().is_err());
assert!("matched-\"dquotes\"".parse::<EntityTag>().is_err());
}
#[test]
fn test_etag_fmt() {
assert_eq!(format!("{}", EntityTag::strong("foobar".to_owned())), "\"foobar\"");
assert_eq!(format!("{}", EntityTag::strong("".to_owned())), "\"\"");
assert_eq!(format!("{}", EntityTag::weak("weak-etag".to_owned())), "W/\"weak-etag\"");
assert_eq!(format!("{}", EntityTag::weak("\u{0065}".to_owned())), "W/\"\x65\"");
assert_eq!(format!("{}", EntityTag::weak("".to_owned())), "W/\"\"");
}
#[test]
fn test_cmp() {
// | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison |
// |---------|---------|-------------------|-----------------|
// | `W/"1"` | `W/"1"` | no match | match |
// | `W/"1"` | `W/"2"` | no match | no match |
// | `W/"1"` | `"1"` | no match | match |
// | `"1"` | `"1"` | match | match |
let mut etag1 = EntityTag::weak("1".to_owned());
let mut etag2 = EntityTag::weak("1".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
etag1 = EntityTag::weak("1".to_owned());
etag2 = EntityTag::weak("2".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(!etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(etag1.weak_ne(&etag2));
etag1 = EntityTag::weak("1".to_owned());
etag2 = EntityTag::strong("1".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
etag1 = EntityTag::strong("1".to_owned());
etag2 = EntityTag::strong("1".to_owned());
assert!(etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(!etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
}
}
| {
return Ok(EntityTag { weak: true, tag: slice[3..length-1].to_owned() });
} | conditional_block |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool {
slice.bytes().all(|c|
c == b'\x21' || (c >= b'\x23' && c <= b'\x7e') | (c >= b'\x80' && c <= b'\xff'))
}
/// An entity tag, defined in [RFC7232](https://tools.ietf.org/html/rfc7232#section-2.3)
///
/// An entity tag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like `W/`. Examples for valid tags are `"xyzzy"` and `W/"xyzzy"`.
///
/// # ABNF
/// ```plain
/// entity-tag = [ weak ] opaque-tag
/// weak = %x57.2F ; "W/", case-sensitive
/// opaque-tag = DQUOTE *etagc DQUOTE
/// etagc = %x21 / %x23-7E / obs-text
/// ; VCHAR except double quotes, plus obs-text
/// ```
///
/// # Comparison
/// To check if two entity tags are equivalent in an application always use the `strong_eq` or
/// `weak_eq` methods based on the context of the Tag. Only use `==` to check if two tags are
/// identical.
///
/// The example below shows the results for a set of entity-tag pairs and
/// both the weak and strong comparison function results:
///
/// | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison |
/// |---------|---------|-------------------|-----------------|
/// | `W/"1"` | `W/"1"` | no match | match |
/// | `W/"1"` | `W/"2"` | no match | no match |
/// | `W/"1"` | `"1"` | no match | match |
/// | `"1"` | `"1"` | match | match |
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
tag: String
}
impl EntityTag {
/// Constructs a new EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn new(weak: bool, tag: String) -> EntityTag {
assert!(check_slice_validity(&tag), "Invalid tag: {:?}", tag);
EntityTag { weak: weak, tag: tag }
}
/// Constructs a new weak EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn weak(tag: String) -> EntityTag {
EntityTag::new(true, tag)
}
/// Constructs a new strong EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn strong(tag: String) -> EntityTag {
EntityTag::new(false, tag)
}
/// Get the tag.
pub fn tag(&self) -> &str {
self.tag.as_ref()
}
/// Set the tag.
/// # Panics
/// If the tag contains invalid characters.
pub fn set_tag(&mut self, tag: String) {
assert!(check_slice_validity(&tag), "Invalid tag: {:?}", tag);
self.tag = tag
}
/// For strong comparison two entity-tags are equivalent if both are not weak and their
/// opaque-tags match character-by-character.
pub fn strong_eq(&self, other: &EntityTag) -> bool {
!self.weak &&!other.weak && self.tag == other.tag
}
/// For weak comparison two entity-tags are equivalent if their
/// opaque-tags match character-by-character, regardless of either or
/// both being tagged as "weak".
pub fn weak_eq(&self, other: &EntityTag) -> bool {
self.tag == other.tag
}
/// The inverse of `EntityTag.strong_eq()`.
pub fn strong_ne(&self, other: &EntityTag) -> bool {
!self.strong_eq(other)
}
/// The inverse of `EntityTag.weak_eq()`.
pub fn weak_ne(&self, other: &EntityTag) -> bool {
!self.weak_eq(other)
}
}
impl Display for EntityTag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
write!(f, "W/\"{}\"", self.tag)
} else {
write!(f, "\"{}\"", self.tag)
}
}
}
impl FromStr for EntityTag {
type Err = ::Error;
fn | (s: &str) -> ::Result<EntityTag> {
let length: usize = s.len();
let slice = &s[..];
// Early exits if it doesn't terminate in a DQUOTE.
if!slice.ends_with('"') {
return Err(::Error::Header);
}
// The etag is weak if its first char is not a DQUOTE.
if slice.starts_with('"') && check_slice_validity(&slice[1..length-1]) {
// No need to check if the last char is a DQUOTE,
// we already did that above.
return Ok(EntityTag { weak: false, tag: slice[1..length-1].to_owned() });
} else if slice.starts_with("W/\"") && check_slice_validity(&slice[3..length-1]) {
return Ok(EntityTag { weak: true, tag: slice[3..length-1].to_owned() });
}
Err(::Error::Header)
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_parse_success() {
// Expected success
assert_eq!("\"foobar\"".parse::<EntityTag>().unwrap(),
EntityTag::strong("foobar".to_owned()));
assert_eq!("\"\"".parse::<EntityTag>().unwrap(),
EntityTag::strong("".to_owned()));
assert_eq!("W/\"weaktag\"".parse::<EntityTag>().unwrap(),
EntityTag::weak("weaktag".to_owned()));
assert_eq!("W/\"\x65\x62\"".parse::<EntityTag>().unwrap(),
EntityTag::weak("\x65\x62".to_owned()));
assert_eq!("W/\"\"".parse::<EntityTag>().unwrap(), EntityTag::weak("".to_owned()));
}
#[test]
fn test_etag_parse_failures() {
// Expected failures
assert!("no-dquotes".parse::<EntityTag>().is_err());
assert!("w/\"the-first-w-is-case-sensitive\"".parse::<EntityTag>().is_err());
assert!("".parse::<EntityTag>().is_err());
assert!("\"unmatched-dquotes1".parse::<EntityTag>().is_err());
assert!("unmatched-dquotes2\"".parse::<EntityTag>().is_err());
assert!("matched-\"dquotes\"".parse::<EntityTag>().is_err());
}
#[test]
fn test_etag_fmt() {
assert_eq!(format!("{}", EntityTag::strong("foobar".to_owned())), "\"foobar\"");
assert_eq!(format!("{}", EntityTag::strong("".to_owned())), "\"\"");
assert_eq!(format!("{}", EntityTag::weak("weak-etag".to_owned())), "W/\"weak-etag\"");
assert_eq!(format!("{}", EntityTag::weak("\u{0065}".to_owned())), "W/\"\x65\"");
assert_eq!(format!("{}", EntityTag::weak("".to_owned())), "W/\"\"");
}
#[test]
fn test_cmp() {
// | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison |
// |---------|---------|-------------------|-----------------|
// | `W/"1"` | `W/"1"` | no match | match |
// | `W/"1"` | `W/"2"` | no match | no match |
// | `W/"1"` | `"1"` | no match | match |
// | `"1"` | `"1"` | match | match |
let mut etag1 = EntityTag::weak("1".to_owned());
let mut etag2 = EntityTag::weak("1".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
etag1 = EntityTag::weak("1".to_owned());
etag2 = EntityTag::weak("2".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(!etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(etag1.weak_ne(&etag2));
etag1 = EntityTag::weak("1".to_owned());
etag2 = EntityTag::strong("1".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
etag1 = EntityTag::strong("1".to_owned());
etag2 = EntityTag::strong("1".to_owned());
assert!(etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(!etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
}
}
| from_str | identifier_name |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool {
slice.bytes().all(|c|
c == b'\x21' || (c >= b'\x23' && c <= b'\x7e') | (c >= b'\x80' && c <= b'\xff'))
}
/// An entity tag, defined in [RFC7232](https://tools.ietf.org/html/rfc7232#section-2.3)
///
/// An entity tag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like `W/`. Examples for valid tags are `"xyzzy"` and `W/"xyzzy"`.
///
/// # ABNF
/// ```plain
/// entity-tag = [ weak ] opaque-tag
/// weak = %x57.2F ; "W/", case-sensitive
/// opaque-tag = DQUOTE *etagc DQUOTE
/// etagc = %x21 / %x23-7E / obs-text
/// ; VCHAR except double quotes, plus obs-text
/// ```
///
/// # Comparison
/// To check if two entity tags are equivalent in an application always use the `strong_eq` or
/// `weak_eq` methods based on the context of the Tag. Only use `==` to check if two tags are
/// identical.
///
/// The example below shows the results for a set of entity-tag pairs and
/// both the weak and strong comparison function results:
///
/// | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison |
/// |---------|---------|-------------------|-----------------|
/// | `W/"1"` | `W/"1"` | no match | match |
/// | `W/"1"` | `W/"2"` | no match | no match |
/// | `W/"1"` | `"1"` | no match | match |
/// | `"1"` | `"1"` | match | match |
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
tag: String
}
impl EntityTag {
/// Constructs a new EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn new(weak: bool, tag: String) -> EntityTag {
assert!(check_slice_validity(&tag), "Invalid tag: {:?}", tag);
EntityTag { weak: weak, tag: tag }
}
/// Constructs a new weak EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn weak(tag: String) -> EntityTag {
EntityTag::new(true, tag)
}
/// Constructs a new strong EntityTag.
/// # Panics
/// If the tag contains invalid characters.
pub fn strong(tag: String) -> EntityTag {
EntityTag::new(false, tag)
}
/// Get the tag.
pub fn tag(&self) -> &str {
self.tag.as_ref()
}
/// Set the tag.
/// # Panics
/// If the tag contains invalid characters.
pub fn set_tag(&mut self, tag: String) {
assert!(check_slice_validity(&tag), "Invalid tag: {:?}", tag);
self.tag = tag
}
/// For strong comparison two entity-tags are equivalent if both are not weak and their
/// opaque-tags match character-by-character.
pub fn strong_eq(&self, other: &EntityTag) -> bool {
!self.weak &&!other.weak && self.tag == other.tag
}
/// For weak comparison two entity-tags are equivalent if their
/// opaque-tags match character-by-character, regardless of either or
/// both being tagged as "weak".
pub fn weak_eq(&self, other: &EntityTag) -> bool {
self.tag == other.tag
}
/// The inverse of `EntityTag.strong_eq()`.
pub fn strong_ne(&self, other: &EntityTag) -> bool {
!self.strong_eq(other)
}
/// The inverse of `EntityTag.weak_eq()`.
pub fn weak_ne(&self, other: &EntityTag) -> bool {
!self.weak_eq(other)
}
}
impl Display for EntityTag {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
write!(f, "W/\"{}\"", self.tag)
} else {
write!(f, "\"{}\"", self.tag)
}
}
}
impl FromStr for EntityTag {
type Err = ::Error;
fn from_str(s: &str) -> ::Result<EntityTag> {
let length: usize = s.len();
let slice = &s[..];
// Early exits if it doesn't terminate in a DQUOTE.
if!slice.ends_with('"') {
return Err(::Error::Header);
}
// The etag is weak if its first char is not a DQUOTE.
if slice.starts_with('"') && check_slice_validity(&slice[1..length-1]) {
// No need to check if the last char is a DQUOTE,
// we already did that above.
return Ok(EntityTag { weak: false, tag: slice[1..length-1].to_owned() });
} else if slice.starts_with("W/\"") && check_slice_validity(&slice[3..length-1]) {
return Ok(EntityTag { weak: true, tag: slice[3..length-1].to_owned() });
}
Err(::Error::Header)
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_parse_success() |
#[test]
fn test_etag_parse_failures() {
// Expected failures
assert!("no-dquotes".parse::<EntityTag>().is_err());
assert!("w/\"the-first-w-is-case-sensitive\"".parse::<EntityTag>().is_err());
assert!("".parse::<EntityTag>().is_err());
assert!("\"unmatched-dquotes1".parse::<EntityTag>().is_err());
assert!("unmatched-dquotes2\"".parse::<EntityTag>().is_err());
assert!("matched-\"dquotes\"".parse::<EntityTag>().is_err());
}
#[test]
fn test_etag_fmt() {
assert_eq!(format!("{}", EntityTag::strong("foobar".to_owned())), "\"foobar\"");
assert_eq!(format!("{}", EntityTag::strong("".to_owned())), "\"\"");
assert_eq!(format!("{}", EntityTag::weak("weak-etag".to_owned())), "W/\"weak-etag\"");
assert_eq!(format!("{}", EntityTag::weak("\u{0065}".to_owned())), "W/\"\x65\"");
assert_eq!(format!("{}", EntityTag::weak("".to_owned())), "W/\"\"");
}
#[test]
fn test_cmp() {
// | ETag 1 | ETag 2 | Strong Comparison | Weak Comparison |
// |---------|---------|-------------------|-----------------|
// | `W/"1"` | `W/"1"` | no match | match |
// | `W/"1"` | `W/"2"` | no match | no match |
// | `W/"1"` | `"1"` | no match | match |
// | `"1"` | `"1"` | match | match |
let mut etag1 = EntityTag::weak("1".to_owned());
let mut etag2 = EntityTag::weak("1".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
etag1 = EntityTag::weak("1".to_owned());
etag2 = EntityTag::weak("2".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(!etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(etag1.weak_ne(&etag2));
etag1 = EntityTag::weak("1".to_owned());
etag2 = EntityTag::strong("1".to_owned());
assert!(!etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
etag1 = EntityTag::strong("1".to_owned());
etag2 = EntityTag::strong("1".to_owned());
assert!(etag1.strong_eq(&etag2));
assert!(etag1.weak_eq(&etag2));
assert!(!etag1.strong_ne(&etag2));
assert!(!etag1.weak_ne(&etag2));
}
}
| {
// Expected success
assert_eq!("\"foobar\"".parse::<EntityTag>().unwrap(),
EntityTag::strong("foobar".to_owned()));
assert_eq!("\"\"".parse::<EntityTag>().unwrap(),
EntityTag::strong("".to_owned()));
assert_eq!("W/\"weaktag\"".parse::<EntityTag>().unwrap(),
EntityTag::weak("weaktag".to_owned()));
assert_eq!("W/\"\x65\x62\"".parse::<EntityTag>().unwrap(),
EntityTag::weak("\x65\x62".to_owned()));
assert_eq!("W/\"\"".parse::<EntityTag>().unwrap(), EntityTag::weak("".to_owned()));
} | identifier_body |
issue-2817-2.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::uint;
fn not_bool(f: &fn(int) -> ~str) -> bool {}
fn main() | {
for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but
false
};
for not_bool |_i| {
//~^ ERROR A `for` loop iterator should expect a closure that returns `bool`
~"hi"
};
for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but
~"hi"
};
for not_bool() |_i| {
//~^ ERROR A `for` loop iterator should expect a closure that returns `bool`
};
} | identifier_body |
|
issue-2817-2.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::uint;
fn | (f: &fn(int) -> ~str) -> bool {}
fn main() {
for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but
false
};
for not_bool |_i| {
//~^ ERROR A `for` loop iterator should expect a closure that returns `bool`
~"hi"
};
for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but
~"hi"
};
for not_bool() |_i| {
//~^ ERROR A `for` loop iterator should expect a closure that returns `bool`
};
}
| not_bool | identifier_name |
issue-2817-2.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::uint;
fn not_bool(f: &fn(int) -> ~str) -> bool {}
fn main() {
for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but
false
};
for not_bool |_i| {
//~^ ERROR A `for` loop iterator should expect a closure that returns `bool`
~"hi"
};
for uint::range(0, 100000) |_i| { //~ ERROR A for-loop body must return (), but
~"hi"
};
for not_bool() |_i| {
//~^ ERROR A `for` loop iterator should expect a closure that returns `bool` | };
} | random_line_split |
|
parsing.rs | //! Utility functions for Header implementations.
use language_tags::LanguageTag;
use std::str;
use std::str::FromStr;
use std::fmt::{self, Display};
use url::percent_encoding;
use header::Raw;
use header::shared::Charset;
/// Reads a single raw string when parsing a header.
pub fn from_one_raw_str<T: str::FromStr>(raw: &Raw) -> ::Result<T> {
if let Some(line) = raw.one() {
if!line.is_empty() {
return from_raw_str(line)
}
}
Err(::Error::Header)
}
/// Reads a raw string into a value.
pub fn from_raw_str<T: str::FromStr>(raw: &[u8]) -> ::Result<T> {
let s = try!(str::from_utf8(raw)).trim();
T::from_str(s).or(Err(::Error::Header))
}
/// Reads a comma-delimited raw header into a Vec.
#[inline]
pub fn from_comma_delimited<T: str::FromStr>(raw: &Raw) -> ::Result<Vec<T>> {
let mut result = Vec::new();
for s in raw {
let s = try!(str::from_utf8(s.as_ref()));
result.extend(s.split(',')
.filter_map(|x| match x.trim() {
"" => None,
y => Some(y)
})
.filter_map(|x| x.trim().parse().ok()))
}
Ok(result)
}
/// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
for (i, part) in parts.iter().enumerate() {
if i!= 0 {
try!(f.write_str(", "));
}
try!(Display::fmt(part, f));
}
Ok(())
}
/// An extended header parameter value (i.e., tagged with a character set and optionally,
/// a language), as defined in [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
#[derive(Clone, Debug, PartialEq)]
pub struct ExtendedValue {
/// The character set that is used to encode the `value` to a string.
pub charset: Charset,
/// The human language details of the `value`, if available.
pub language_tag: Option<LanguageTag>,
/// The parameter value, as expressed in octets.
pub value: Vec<u8>,
}
/// Parses extended header parameter values (`ext-value`), as defined in
/// [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
///
/// Extended values are denoted by parameter names that end with `*`.
///
/// ## ABNF
/// ```plain
/// ext-value = charset "'" [ language ] "'" value-chars
/// ; like RFC 2231's <extended-initial-value>
/// ; (see [RFC2231], Section 7)
///
/// charset = "UTF-8" / "ISO-8859-1" / mime-charset
///
/// mime-charset = 1*mime-charsetc
/// mime-charsetc = ALPHA / DIGIT
/// / "!" / "#" / "$" / "%" / "&"
/// / "+" / "-" / "^" / "_" / "`"
/// / "{" / "}" / "~"
/// ; as <mime-charset> in Section 2.3 of [RFC2978]
/// ; except that the single quote is not included
/// ; SHOULD be registered in the IANA charset registry
///
/// language = <Language-Tag, defined in [RFC5646], Section 2.1>
///
/// value-chars = *( pct-encoded / attr-char )
///
/// pct-encoded = "%" HEXDIG HEXDIG
/// ; see [RFC3986], Section 2.1
///
/// attr-char = ALPHA / DIGIT
/// / "!" / "#" / "$" / "&" / "+" / "-" / "."
/// / "^" / "_" / "`" / "|" / "~"
/// ; token except ( "*" / "'" / "%" )
/// ```
pub fn parse_extended_value(val: &str) -> ::Result<ExtendedValue> {
// Break into three pieces separated by the single-quote character
let mut parts = val.splitn(3,'\'');
// Interpret the first piece as a Charset
let charset: Charset = match parts.next() {
None => return Err(::Error::Header),
Some(n) => try!(FromStr::from_str(n)),
};
// Interpret the second piece as a language tag
let lang: Option<LanguageTag> = match parts.next() {
None => return Err(::Error::Header),
Some("") => None,
Some(s) => match s.parse() {
Ok(lt) => Some(lt),
Err(_) => return Err(::Error::Header),
}
};
// Interpret the third piece as a sequence of value characters
let value: Vec<u8> = match parts.next() {
None => return Err(::Error::Header),
Some(v) => percent_encoding::percent_decode(v.as_bytes()).collect(),
};
Ok(ExtendedValue {
charset: charset,
language_tag: lang,
value: value,
})
}
define_encode_set! {
/// This encode set is used for HTTP header values and is defined at
/// https://tools.ietf.org/html/rfc5987#section-3.2
pub HTTP_VALUE = [percent_encoding::SIMPLE_ENCODE_SET] | {
'', '"', '%', '\'', '(', ')', '*', ',', '/', ':', ';', '<', '-', '>', '?',
'[', '\\', ']', '{', '}'
}
}
impl fmt::Debug for HTTP_VALUE {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("HTTP_VALUE")
}
}
impl Display for ExtendedValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let encoded_value =
percent_encoding::percent_encode(&self.value[..], HTTP_VALUE);
if let Some(ref lang) = self.language_tag {
write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
} else {
write!(f, "{}''{}", self.charset, encoded_value)
}
}
}
#[cfg(test)]
mod tests {
use header::shared::Charset;
use super::{ExtendedValue, parse_extended_value};
#[test]
fn test_parse_extended_value_with_encoding_and_language_tag() {
let expected_language_tag = langtag!(en);
// RFC 5987, Section 3.2.2
// Extended notation, using the Unicode character U+00A3 (POUND SIGN)
let result = parse_extended_value("iso-8859-1'en'%A3%20rates");
assert!(result.is_ok());
let extended_value = result.unwrap();
assert_eq!(Charset::Iso_8859_1, extended_value.charset);
assert!(extended_value.language_tag.is_some());
assert_eq!(expected_language_tag, extended_value.language_tag.unwrap());
assert_eq!(vec![163, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value);
}
#[test]
fn test_parse_extended_value_with_encoding() {
// RFC 5987, Section 3.2.2
// Extended notation, using the Unicode characters U+00A3 (POUND SIGN)
// and U+20AC (EURO SIGN)
let result = parse_extended_value("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates");
assert!(result.is_ok());
let extended_value = result.unwrap();
assert_eq!(Charset::Ext("UTF-8".to_string()), extended_value.charset);
assert!(extended_value.language_tag.is_none());
assert_eq!(vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value);
}
#[test]
fn test_parse_extended_value_missing_language_tag_and_encoding() {
// From: https://greenbytes.de/tech/tc2231/#attwithfn2231quot2
let result = parse_extended_value("foo%20bar.html");
assert!(result.is_err());
}
#[test]
fn test_parse_extended_value_partially_formatted() {
let result = parse_extended_value("UTF-8'missing third part");
assert!(result.is_err());
}
#[test]
fn test_parse_extended_value_partially_formatted_blank() {
let result = parse_extended_value("blank second part'");
assert!(result.is_err());
}
#[test]
fn test_fmt_extended_value_with_encoding_and_language_tag() { | let extended_value = ExtendedValue {
charset: Charset::Iso_8859_1,
language_tag: Some("en".parse().expect("Could not parse language tag")),
value: vec![163, b' ', b'r', b'a', b't', b'e', b's'],
};
assert_eq!("ISO-8859-1'en'%A3%20rates", format!("{}", extended_value));
}
#[test]
fn test_fmt_extended_value_with_encoding() {
let extended_value = ExtendedValue {
charset: Charset::Ext("UTF-8".to_string()),
language_tag: None,
value: vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a',
b't', b'e', b's'],
};
assert_eq!("UTF-8''%C2%A3%20and%20%E2%82%AC%20rates",
format!("{}", extended_value));
}
} | random_line_split |
|
parsing.rs | //! Utility functions for Header implementations.
use language_tags::LanguageTag;
use std::str;
use std::str::FromStr;
use std::fmt::{self, Display};
use url::percent_encoding;
use header::Raw;
use header::shared::Charset;
/// Reads a single raw string when parsing a header.
pub fn from_one_raw_str<T: str::FromStr>(raw: &Raw) -> ::Result<T> {
if let Some(line) = raw.one() {
if!line.is_empty() {
return from_raw_str(line)
}
}
Err(::Error::Header)
}
/// Reads a raw string into a value.
pub fn from_raw_str<T: str::FromStr>(raw: &[u8]) -> ::Result<T> {
let s = try!(str::from_utf8(raw)).trim();
T::from_str(s).or(Err(::Error::Header))
}
/// Reads a comma-delimited raw header into a Vec.
#[inline]
pub fn from_comma_delimited<T: str::FromStr>(raw: &Raw) -> ::Result<Vec<T>> {
let mut result = Vec::new();
for s in raw {
let s = try!(str::from_utf8(s.as_ref()));
result.extend(s.split(',')
.filter_map(|x| match x.trim() {
"" => None,
y => Some(y)
})
.filter_map(|x| x.trim().parse().ok()))
}
Ok(result)
}
/// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
for (i, part) in parts.iter().enumerate() {
if i!= 0 {
try!(f.write_str(", "));
}
try!(Display::fmt(part, f));
}
Ok(())
}
/// An extended header parameter value (i.e., tagged with a character set and optionally,
/// a language), as defined in [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
#[derive(Clone, Debug, PartialEq)]
pub struct ExtendedValue {
/// The character set that is used to encode the `value` to a string.
pub charset: Charset,
/// The human language details of the `value`, if available.
pub language_tag: Option<LanguageTag>,
/// The parameter value, as expressed in octets.
pub value: Vec<u8>,
}
/// Parses extended header parameter values (`ext-value`), as defined in
/// [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
///
/// Extended values are denoted by parameter names that end with `*`.
///
/// ## ABNF
/// ```plain
/// ext-value = charset "'" [ language ] "'" value-chars
/// ; like RFC 2231's <extended-initial-value>
/// ; (see [RFC2231], Section 7)
///
/// charset = "UTF-8" / "ISO-8859-1" / mime-charset
///
/// mime-charset = 1*mime-charsetc
/// mime-charsetc = ALPHA / DIGIT
/// / "!" / "#" / "$" / "%" / "&"
/// / "+" / "-" / "^" / "_" / "`"
/// / "{" / "}" / "~"
/// ; as <mime-charset> in Section 2.3 of [RFC2978]
/// ; except that the single quote is not included
/// ; SHOULD be registered in the IANA charset registry
///
/// language = <Language-Tag, defined in [RFC5646], Section 2.1>
///
/// value-chars = *( pct-encoded / attr-char )
///
/// pct-encoded = "%" HEXDIG HEXDIG
/// ; see [RFC3986], Section 2.1
///
/// attr-char = ALPHA / DIGIT
/// / "!" / "#" / "$" / "&" / "+" / "-" / "."
/// / "^" / "_" / "`" / "|" / "~"
/// ; token except ( "*" / "'" / "%" )
/// ```
pub fn parse_extended_value(val: &str) -> ::Result<ExtendedValue> {
// Break into three pieces separated by the single-quote character
let mut parts = val.splitn(3,'\'');
// Interpret the first piece as a Charset
let charset: Charset = match parts.next() {
None => return Err(::Error::Header),
Some(n) => try!(FromStr::from_str(n)),
};
// Interpret the second piece as a language tag
let lang: Option<LanguageTag> = match parts.next() {
None => return Err(::Error::Header),
Some("") => None,
Some(s) => match s.parse() {
Ok(lt) => Some(lt),
Err(_) => return Err(::Error::Header),
}
};
// Interpret the third piece as a sequence of value characters
let value: Vec<u8> = match parts.next() {
None => return Err(::Error::Header),
Some(v) => percent_encoding::percent_decode(v.as_bytes()).collect(),
};
Ok(ExtendedValue {
charset: charset,
language_tag: lang,
value: value,
})
}
define_encode_set! {
/// This encode set is used for HTTP header values and is defined at
/// https://tools.ietf.org/html/rfc5987#section-3.2
pub HTTP_VALUE = [percent_encoding::SIMPLE_ENCODE_SET] | {
'', '"', '%', '\'', '(', ')', '*', ',', '/', ':', ';', '<', '-', '>', '?',
'[', '\\', ']', '{', '}'
}
}
impl fmt::Debug for HTTP_VALUE {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("HTTP_VALUE")
}
}
impl Display for ExtendedValue {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
#[cfg(test)]
mod tests {
use header::shared::Charset;
use super::{ExtendedValue, parse_extended_value};
#[test]
fn test_parse_extended_value_with_encoding_and_language_tag() {
let expected_language_tag = langtag!(en);
// RFC 5987, Section 3.2.2
// Extended notation, using the Unicode character U+00A3 (POUND SIGN)
let result = parse_extended_value("iso-8859-1'en'%A3%20rates");
assert!(result.is_ok());
let extended_value = result.unwrap();
assert_eq!(Charset::Iso_8859_1, extended_value.charset);
assert!(extended_value.language_tag.is_some());
assert_eq!(expected_language_tag, extended_value.language_tag.unwrap());
assert_eq!(vec![163, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value);
}
#[test]
fn test_parse_extended_value_with_encoding() {
// RFC 5987, Section 3.2.2
// Extended notation, using the Unicode characters U+00A3 (POUND SIGN)
// and U+20AC (EURO SIGN)
let result = parse_extended_value("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates");
assert!(result.is_ok());
let extended_value = result.unwrap();
assert_eq!(Charset::Ext("UTF-8".to_string()), extended_value.charset);
assert!(extended_value.language_tag.is_none());
assert_eq!(vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value);
}
#[test]
fn test_parse_extended_value_missing_language_tag_and_encoding() {
// From: https://greenbytes.de/tech/tc2231/#attwithfn2231quot2
let result = parse_extended_value("foo%20bar.html");
assert!(result.is_err());
}
#[test]
fn test_parse_extended_value_partially_formatted() {
let result = parse_extended_value("UTF-8'missing third part");
assert!(result.is_err());
}
#[test]
fn test_parse_extended_value_partially_formatted_blank() {
let result = parse_extended_value("blank second part'");
assert!(result.is_err());
}
#[test]
fn test_fmt_extended_value_with_encoding_and_language_tag() {
let extended_value = ExtendedValue {
charset: Charset::Iso_8859_1,
language_tag: Some("en".parse().expect("Could not parse language tag")),
value: vec![163, b' ', b'r', b'a', b't', b'e', b's'],
};
assert_eq!("ISO-8859-1'en'%A3%20rates", format!("{}", extended_value));
}
#[test]
fn test_fmt_extended_value_with_encoding() {
let extended_value = ExtendedValue {
charset: Charset::Ext("UTF-8".to_string()),
language_tag: None,
value: vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a',
b't', b'e', b's'],
};
assert_eq!("UTF-8''%C2%A3%20and%20%E2%82%AC%20rates",
format!("{}", extended_value));
}
}
| {
let encoded_value =
percent_encoding::percent_encode(&self.value[..], HTTP_VALUE);
if let Some(ref lang) = self.language_tag {
write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
} else {
write!(f, "{}''{}", self.charset, encoded_value)
}
} | identifier_body |
parsing.rs | //! Utility functions for Header implementations.
use language_tags::LanguageTag;
use std::str;
use std::str::FromStr;
use std::fmt::{self, Display};
use url::percent_encoding;
use header::Raw;
use header::shared::Charset;
/// Reads a single raw string when parsing a header.
pub fn from_one_raw_str<T: str::FromStr>(raw: &Raw) -> ::Result<T> {
if let Some(line) = raw.one() {
if!line.is_empty() {
return from_raw_str(line)
}
}
Err(::Error::Header)
}
/// Reads a raw string into a value.
pub fn from_raw_str<T: str::FromStr>(raw: &[u8]) -> ::Result<T> {
let s = try!(str::from_utf8(raw)).trim();
T::from_str(s).or(Err(::Error::Header))
}
/// Reads a comma-delimited raw header into a Vec.
#[inline]
pub fn from_comma_delimited<T: str::FromStr>(raw: &Raw) -> ::Result<Vec<T>> {
let mut result = Vec::new();
for s in raw {
let s = try!(str::from_utf8(s.as_ref()));
result.extend(s.split(',')
.filter_map(|x| match x.trim() {
"" => None,
y => Some(y)
})
.filter_map(|x| x.trim().parse().ok()))
}
Ok(result)
}
/// Format an array into a comma-delimited string.
pub fn fmt_comma_delimited<T: Display>(f: &mut fmt::Formatter, parts: &[T]) -> fmt::Result {
for (i, part) in parts.iter().enumerate() {
if i!= 0 {
try!(f.write_str(", "));
}
try!(Display::fmt(part, f));
}
Ok(())
}
/// An extended header parameter value (i.e., tagged with a character set and optionally,
/// a language), as defined in [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
#[derive(Clone, Debug, PartialEq)]
pub struct ExtendedValue {
/// The character set that is used to encode the `value` to a string.
pub charset: Charset,
/// The human language details of the `value`, if available.
pub language_tag: Option<LanguageTag>,
/// The parameter value, as expressed in octets.
pub value: Vec<u8>,
}
/// Parses extended header parameter values (`ext-value`), as defined in
/// [RFC 5987](https://tools.ietf.org/html/rfc5987#section-3.2).
///
/// Extended values are denoted by parameter names that end with `*`.
///
/// ## ABNF
/// ```plain
/// ext-value = charset "'" [ language ] "'" value-chars
/// ; like RFC 2231's <extended-initial-value>
/// ; (see [RFC2231], Section 7)
///
/// charset = "UTF-8" / "ISO-8859-1" / mime-charset
///
/// mime-charset = 1*mime-charsetc
/// mime-charsetc = ALPHA / DIGIT
/// / "!" / "#" / "$" / "%" / "&"
/// / "+" / "-" / "^" / "_" / "`"
/// / "{" / "}" / "~"
/// ; as <mime-charset> in Section 2.3 of [RFC2978]
/// ; except that the single quote is not included
/// ; SHOULD be registered in the IANA charset registry
///
/// language = <Language-Tag, defined in [RFC5646], Section 2.1>
///
/// value-chars = *( pct-encoded / attr-char )
///
/// pct-encoded = "%" HEXDIG HEXDIG
/// ; see [RFC3986], Section 2.1
///
/// attr-char = ALPHA / DIGIT
/// / "!" / "#" / "$" / "&" / "+" / "-" / "."
/// / "^" / "_" / "`" / "|" / "~"
/// ; token except ( "*" / "'" / "%" )
/// ```
pub fn parse_extended_value(val: &str) -> ::Result<ExtendedValue> {
// Break into three pieces separated by the single-quote character
let mut parts = val.splitn(3,'\'');
// Interpret the first piece as a Charset
let charset: Charset = match parts.next() {
None => return Err(::Error::Header),
Some(n) => try!(FromStr::from_str(n)),
};
// Interpret the second piece as a language tag
let lang: Option<LanguageTag> = match parts.next() {
None => return Err(::Error::Header),
Some("") => None,
Some(s) => match s.parse() {
Ok(lt) => Some(lt),
Err(_) => return Err(::Error::Header),
}
};
// Interpret the third piece as a sequence of value characters
let value: Vec<u8> = match parts.next() {
None => return Err(::Error::Header),
Some(v) => percent_encoding::percent_decode(v.as_bytes()).collect(),
};
Ok(ExtendedValue {
charset: charset,
language_tag: lang,
value: value,
})
}
define_encode_set! {
/// This encode set is used for HTTP header values and is defined at
/// https://tools.ietf.org/html/rfc5987#section-3.2
pub HTTP_VALUE = [percent_encoding::SIMPLE_ENCODE_SET] | {
'', '"', '%', '\'', '(', ')', '*', ',', '/', ':', ';', '<', '-', '>', '?',
'[', '\\', ']', '{', '}'
}
}
impl fmt::Debug for HTTP_VALUE {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("HTTP_VALUE")
}
}
impl Display for ExtendedValue {
fn | (&self, f: &mut fmt::Formatter) -> fmt::Result {
let encoded_value =
percent_encoding::percent_encode(&self.value[..], HTTP_VALUE);
if let Some(ref lang) = self.language_tag {
write!(f, "{}'{}'{}", self.charset, lang, encoded_value)
} else {
write!(f, "{}''{}", self.charset, encoded_value)
}
}
}
#[cfg(test)]
mod tests {
use header::shared::Charset;
use super::{ExtendedValue, parse_extended_value};
#[test]
fn test_parse_extended_value_with_encoding_and_language_tag() {
let expected_language_tag = langtag!(en);
// RFC 5987, Section 3.2.2
// Extended notation, using the Unicode character U+00A3 (POUND SIGN)
let result = parse_extended_value("iso-8859-1'en'%A3%20rates");
assert!(result.is_ok());
let extended_value = result.unwrap();
assert_eq!(Charset::Iso_8859_1, extended_value.charset);
assert!(extended_value.language_tag.is_some());
assert_eq!(expected_language_tag, extended_value.language_tag.unwrap());
assert_eq!(vec![163, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value);
}
#[test]
fn test_parse_extended_value_with_encoding() {
// RFC 5987, Section 3.2.2
// Extended notation, using the Unicode characters U+00A3 (POUND SIGN)
// and U+20AC (EURO SIGN)
let result = parse_extended_value("UTF-8''%c2%a3%20and%20%e2%82%ac%20rates");
assert!(result.is_ok());
let extended_value = result.unwrap();
assert_eq!(Charset::Ext("UTF-8".to_string()), extended_value.charset);
assert!(extended_value.language_tag.is_none());
assert_eq!(vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a', b't', b'e', b's'], extended_value.value);
}
#[test]
fn test_parse_extended_value_missing_language_tag_and_encoding() {
// From: https://greenbytes.de/tech/tc2231/#attwithfn2231quot2
let result = parse_extended_value("foo%20bar.html");
assert!(result.is_err());
}
#[test]
fn test_parse_extended_value_partially_formatted() {
let result = parse_extended_value("UTF-8'missing third part");
assert!(result.is_err());
}
#[test]
fn test_parse_extended_value_partially_formatted_blank() {
let result = parse_extended_value("blank second part'");
assert!(result.is_err());
}
#[test]
fn test_fmt_extended_value_with_encoding_and_language_tag() {
let extended_value = ExtendedValue {
charset: Charset::Iso_8859_1,
language_tag: Some("en".parse().expect("Could not parse language tag")),
value: vec![163, b' ', b'r', b'a', b't', b'e', b's'],
};
assert_eq!("ISO-8859-1'en'%A3%20rates", format!("{}", extended_value));
}
#[test]
fn test_fmt_extended_value_with_encoding() {
let extended_value = ExtendedValue {
charset: Charset::Ext("UTF-8".to_string()),
language_tag: None,
value: vec![194, 163, b' ', b'a', b'n', b'd', b' ', 226, 130, 172, b' ', b'r', b'a',
b't', b'e', b's'],
};
assert_eq!("UTF-8''%C2%A3%20and%20%E2%82%AC%20rates",
format!("{}", extended_value));
}
}
| fmt | identifier_name |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::InheritTypes::{EventCast, CustomEventDerived};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary, MutHeap};
use dom::bindings::utils::reflect_dom_object;
use dom::event::{Event, EventTypeId};
use js::jsapi::JSContext;
use js::jsval::{JSVal, NullValue};
use servo_util::str::DOMString;
#[dom_struct]
pub struct CustomEvent {
event: Event,
detail: MutHeap<JSVal>,
}
impl CustomEventDerived for Event {
fn is_customevent(&self) -> bool {
*self.type_id() == EventTypeId::CustomEvent
}
}
impl CustomEvent {
fn new_inherited(type_id: EventTypeId) -> CustomEvent {
CustomEvent {
event: Event::new_inherited(type_id),
detail: MutHeap::new(NullValue()),
}
}
pub fn new_uninitialized(global: GlobalRef) -> Temporary<CustomEvent> {
reflect_dom_object(box CustomEvent::new_inherited(EventTypeId::CustomEvent),
global,
CustomEventBinding::Wrap)
}
pub fn new(global: GlobalRef, type_: DOMString, bubbles: bool, cancelable: bool, detail: JSVal) -> Temporary<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global).root();
ev.r().InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail);
Temporary::from_rooted(ev.r())
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &CustomEventBinding::CustomEventInit) -> Fallible<Temporary<CustomEvent>>{
Ok(CustomEvent::new(global, type_, init.parent.bubbles, init.parent.cancelable, init.detail))
}
}
impl<'a> CustomEventMethods for JSRef<'a, CustomEvent> {
fn Detail(self, _cx: *mut JSContext) -> JSVal |
fn InitCustomEvent(self,
_cx: *mut JSContext,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
detail: JSVal) {
let event: JSRef<Event> = EventCast::from_ref(self);
if event.dispatching() {
return;
}
self.detail.set(detail);
event.InitEvent(type_, can_bubble, cancelable);
}
}
| {
self.detail.get()
} | identifier_body |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::InheritTypes::{EventCast, CustomEventDerived};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary, MutHeap};
use dom::bindings::utils::reflect_dom_object;
use dom::event::{Event, EventTypeId};
use js::jsapi::JSContext;
use js::jsval::{JSVal, NullValue};
use servo_util::str::DOMString;
#[dom_struct]
pub struct CustomEvent {
event: Event,
detail: MutHeap<JSVal>,
}
impl CustomEventDerived for Event {
fn is_customevent(&self) -> bool {
*self.type_id() == EventTypeId::CustomEvent
}
}
impl CustomEvent {
fn new_inherited(type_id: EventTypeId) -> CustomEvent {
CustomEvent {
event: Event::new_inherited(type_id),
detail: MutHeap::new(NullValue()),
}
}
pub fn new_uninitialized(global: GlobalRef) -> Temporary<CustomEvent> {
reflect_dom_object(box CustomEvent::new_inherited(EventTypeId::CustomEvent),
global,
CustomEventBinding::Wrap)
}
pub fn new(global: GlobalRef, type_: DOMString, bubbles: bool, cancelable: bool, detail: JSVal) -> Temporary<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global).root();
ev.r().InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail);
Temporary::from_rooted(ev.r())
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &CustomEventBinding::CustomEventInit) -> Fallible<Temporary<CustomEvent>>{
Ok(CustomEvent::new(global, type_, init.parent.bubbles, init.parent.cancelable, init.detail))
}
}
impl<'a> CustomEventMethods for JSRef<'a, CustomEvent> {
fn | (self, _cx: *mut JSContext) -> JSVal {
self.detail.get()
}
fn InitCustomEvent(self,
_cx: *mut JSContext,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
detail: JSVal) {
let event: JSRef<Event> = EventCast::from_ref(self);
if event.dispatching() {
return;
}
self.detail.set(detail);
event.InitEvent(type_, can_bubble, cancelable);
}
}
| Detail | identifier_name |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::InheritTypes::{EventCast, CustomEventDerived};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary, MutHeap};
use dom::bindings::utils::reflect_dom_object;
use dom::event::{Event, EventTypeId};
use js::jsapi::JSContext;
use js::jsval::{JSVal, NullValue};
use servo_util::str::DOMString;
| pub struct CustomEvent {
event: Event,
detail: MutHeap<JSVal>,
}
impl CustomEventDerived for Event {
fn is_customevent(&self) -> bool {
*self.type_id() == EventTypeId::CustomEvent
}
}
impl CustomEvent {
fn new_inherited(type_id: EventTypeId) -> CustomEvent {
CustomEvent {
event: Event::new_inherited(type_id),
detail: MutHeap::new(NullValue()),
}
}
pub fn new_uninitialized(global: GlobalRef) -> Temporary<CustomEvent> {
reflect_dom_object(box CustomEvent::new_inherited(EventTypeId::CustomEvent),
global,
CustomEventBinding::Wrap)
}
pub fn new(global: GlobalRef, type_: DOMString, bubbles: bool, cancelable: bool, detail: JSVal) -> Temporary<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global).root();
ev.r().InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail);
Temporary::from_rooted(ev.r())
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &CustomEventBinding::CustomEventInit) -> Fallible<Temporary<CustomEvent>>{
Ok(CustomEvent::new(global, type_, init.parent.bubbles, init.parent.cancelable, init.detail))
}
}
impl<'a> CustomEventMethods for JSRef<'a, CustomEvent> {
fn Detail(self, _cx: *mut JSContext) -> JSVal {
self.detail.get()
}
fn InitCustomEvent(self,
_cx: *mut JSContext,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
detail: JSVal) {
let event: JSRef<Event> = EventCast::from_ref(self);
if event.dispatching() {
return;
}
self.detail.set(detail);
event.InitEvent(type_, can_bubble, cancelable);
}
} | #[dom_struct] | random_line_split |
customevent.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::InheritTypes::{EventCast, CustomEventDerived};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JSRef, Temporary, MutHeap};
use dom::bindings::utils::reflect_dom_object;
use dom::event::{Event, EventTypeId};
use js::jsapi::JSContext;
use js::jsval::{JSVal, NullValue};
use servo_util::str::DOMString;
#[dom_struct]
pub struct CustomEvent {
event: Event,
detail: MutHeap<JSVal>,
}
impl CustomEventDerived for Event {
fn is_customevent(&self) -> bool {
*self.type_id() == EventTypeId::CustomEvent
}
}
impl CustomEvent {
fn new_inherited(type_id: EventTypeId) -> CustomEvent {
CustomEvent {
event: Event::new_inherited(type_id),
detail: MutHeap::new(NullValue()),
}
}
pub fn new_uninitialized(global: GlobalRef) -> Temporary<CustomEvent> {
reflect_dom_object(box CustomEvent::new_inherited(EventTypeId::CustomEvent),
global,
CustomEventBinding::Wrap)
}
pub fn new(global: GlobalRef, type_: DOMString, bubbles: bool, cancelable: bool, detail: JSVal) -> Temporary<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global).root();
ev.r().InitCustomEvent(global.get_cx(), type_, bubbles, cancelable, detail);
Temporary::from_rooted(ev.r())
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &CustomEventBinding::CustomEventInit) -> Fallible<Temporary<CustomEvent>>{
Ok(CustomEvent::new(global, type_, init.parent.bubbles, init.parent.cancelable, init.detail))
}
}
impl<'a> CustomEventMethods for JSRef<'a, CustomEvent> {
fn Detail(self, _cx: *mut JSContext) -> JSVal {
self.detail.get()
}
fn InitCustomEvent(self,
_cx: *mut JSContext,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
detail: JSVal) {
let event: JSRef<Event> = EventCast::from_ref(self);
if event.dispatching() |
self.detail.set(detail);
event.InitEvent(type_, can_bubble, cancelable);
}
}
| {
return;
} | conditional_block |
chacha20.rs | use std::slice;
use super::{StreamEncrypt, StreamDecrypt};
use byteorder::{ByteOrder, LittleEndian};
const ROUNDS: usize = 20;
const STATE_WORDS: usize = 16;
const STATE_BYTES: usize = STATE_WORDS * 4;
#[derive(Copy, Clone)]
struct State([u32; STATE_WORDS]);
macro_rules! quarter_round {
($a:expr, $b:expr, $c:expr, $d:expr) => {{
$a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left(16);
$c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left(12);
$a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left( 8);
$c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left( 7);
}}
}
macro_rules! double_round {
($x:expr) => {{
// Column round
quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]);
quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]);
quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]);
quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]);
// Diagonal round
quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]);
quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]);
quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]);
quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]);
}}
}
impl State {
fn expand(key: &[u8], nonce: &[u8], position: u32) -> Self |
fn update(&mut self, output: &mut [u32]) {
let mut state = self.0;
for _ in 0..ROUNDS / 2 {
double_round!(state);
}
for i in 0..STATE_WORDS {
output[i] = self.0[i].wrapping_add(state[i]);
}
self.0[12] += 1;
}
}
pub struct ChaCha20 {
state: State,
buffer: [u32; STATE_WORDS],
index: usize,
}
impl ChaCha20 {
pub fn init(key: &[u8], nonce: &[u8], position: u32) -> Self {
ChaCha20 {
state: State::expand(key.as_ref(), nonce.as_ref(), position),
buffer: [0; STATE_WORDS],
index: STATE_BYTES,
}
}
pub fn new<Key, Nonce>(key: Key, nonce: Nonce) -> Self
where Key: AsRef<[u8]>,
Nonce: AsRef<[u8]>
{
Self::init(key.as_ref(), nonce.as_ref(), 1)
}
fn update(&mut self) {
self.state.update(&mut self.buffer[..]);
self.index = 0;
}
fn crypt(&mut self, input: &[u8], output: &mut [u8]) {
if self.index == STATE_BYTES {
self.update()
}
let buffer = unsafe {
slice::from_raw_parts(self.buffer.as_ptr() as *const u8, STATE_BYTES)
};
for i in self.index..input.len() {
output[i] = input[i] ^ buffer[i];
}
self.index = input.len();
}
}
impl StreamEncrypt for ChaCha20 {
fn encrypt_stream<I, O>(&mut self, input: I, mut output: O)
where I: AsRef<[u8]>,
O: AsMut<[u8]>
{
assert_eq!(input.as_ref().len(), output.as_mut().len());
let input = input.as_ref();
let output = output.as_mut();
let from = STATE_BYTES - self.index;
if from > 0 {
self.crypt(&input[..from], &mut output[..from]);
}
for (i, o) in input[from..]
.chunks(STATE_BYTES)
.zip(output[from..].chunks_mut(STATE_BYTES)) {
self.crypt(i, o)
}
}
}
impl StreamDecrypt for ChaCha20 {
fn decrypt_stream<I, O>(&mut self, input: I, mut output: O)
where I: AsRef<[u8]>,
O: AsMut<[u8]>
{
assert_eq!(input.as_ref().len(), output.as_mut().len());
let input = input.as_ref().chunks(STATE_BYTES);
let output = output.as_mut().chunks_mut(STATE_BYTES);
for (i, o) in input.zip(output) {
self.crypt(i, o)
}
}
}
| {
let mut state = [0u32; STATE_WORDS];
state[0] = 0x61707865;
state[1] = 0x3320646e;
state[2] = 0x79622d32;
state[3] = 0x6b206574;
for (state, chunk) in state[4..12].iter_mut().zip(key.chunks(4)) {
*state = LittleEndian::read_u32(chunk);
}
state[12] = position;
for (state, chunk) in state[13..16].iter_mut().zip(nonce.chunks(4)) {
*state = LittleEndian::read_u32(chunk);
}
State(state)
} | identifier_body |
chacha20.rs | use std::slice;
use super::{StreamEncrypt, StreamDecrypt};
use byteorder::{ByteOrder, LittleEndian};
const ROUNDS: usize = 20;
const STATE_WORDS: usize = 16;
const STATE_BYTES: usize = STATE_WORDS * 4;
#[derive(Copy, Clone)]
struct State([u32; STATE_WORDS]);
macro_rules! quarter_round {
($a:expr, $b:expr, $c:expr, $d:expr) => {{
$a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left(16);
$c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left(12);
$a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left( 8);
$c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left( 7);
}}
}
macro_rules! double_round {
($x:expr) => {{
// Column round
quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]);
quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]);
quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]);
quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]);
// Diagonal round
quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]);
quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]);
quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]);
quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]);
}}
}
impl State {
fn expand(key: &[u8], nonce: &[u8], position: u32) -> Self {
let mut state = [0u32; STATE_WORDS];
state[0] = 0x61707865;
state[1] = 0x3320646e;
state[2] = 0x79622d32;
state[3] = 0x6b206574;
for (state, chunk) in state[4..12].iter_mut().zip(key.chunks(4)) {
*state = LittleEndian::read_u32(chunk);
}
state[12] = position;
for (state, chunk) in state[13..16].iter_mut().zip(nonce.chunks(4)) {
*state = LittleEndian::read_u32(chunk);
}
State(state)
}
fn update(&mut self, output: &mut [u32]) {
let mut state = self.0;
for _ in 0..ROUNDS / 2 {
double_round!(state);
}
for i in 0..STATE_WORDS {
output[i] = self.0[i].wrapping_add(state[i]);
}
self.0[12] += 1;
}
}
pub struct ChaCha20 {
state: State,
buffer: [u32; STATE_WORDS],
index: usize,
}
impl ChaCha20 {
pub fn init(key: &[u8], nonce: &[u8], position: u32) -> Self {
ChaCha20 {
state: State::expand(key.as_ref(), nonce.as_ref(), position),
buffer: [0; STATE_WORDS],
index: STATE_BYTES,
}
}
pub fn new<Key, Nonce>(key: Key, nonce: Nonce) -> Self
where Key: AsRef<[u8]>,
Nonce: AsRef<[u8]>
{
Self::init(key.as_ref(), nonce.as_ref(), 1)
}
fn update(&mut self) {
self.state.update(&mut self.buffer[..]);
self.index = 0;
}
fn | (&mut self, input: &[u8], output: &mut [u8]) {
if self.index == STATE_BYTES {
self.update()
}
let buffer = unsafe {
slice::from_raw_parts(self.buffer.as_ptr() as *const u8, STATE_BYTES)
};
for i in self.index..input.len() {
output[i] = input[i] ^ buffer[i];
}
self.index = input.len();
}
}
impl StreamEncrypt for ChaCha20 {
fn encrypt_stream<I, O>(&mut self, input: I, mut output: O)
where I: AsRef<[u8]>,
O: AsMut<[u8]>
{
assert_eq!(input.as_ref().len(), output.as_mut().len());
let input = input.as_ref();
let output = output.as_mut();
let from = STATE_BYTES - self.index;
if from > 0 {
self.crypt(&input[..from], &mut output[..from]);
}
for (i, o) in input[from..]
.chunks(STATE_BYTES)
.zip(output[from..].chunks_mut(STATE_BYTES)) {
self.crypt(i, o)
}
}
}
impl StreamDecrypt for ChaCha20 {
fn decrypt_stream<I, O>(&mut self, input: I, mut output: O)
where I: AsRef<[u8]>,
O: AsMut<[u8]>
{
assert_eq!(input.as_ref().len(), output.as_mut().len());
let input = input.as_ref().chunks(STATE_BYTES);
let output = output.as_mut().chunks_mut(STATE_BYTES);
for (i, o) in input.zip(output) {
self.crypt(i, o)
}
}
}
| crypt | identifier_name |
chacha20.rs | use std::slice;
use super::{StreamEncrypt, StreamDecrypt};
use byteorder::{ByteOrder, LittleEndian};
const ROUNDS: usize = 20;
const STATE_WORDS: usize = 16;
const STATE_BYTES: usize = STATE_WORDS * 4;
#[derive(Copy, Clone)]
struct State([u32; STATE_WORDS]);
macro_rules! quarter_round {
($a:expr, $b:expr, $c:expr, $d:expr) => {{
$a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left(16);
$c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left(12);
$a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left( 8);
$c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left( 7);
}}
}
macro_rules! double_round {
($x:expr) => {{
// Column round
quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]);
quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]);
quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]);
quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]);
// Diagonal round
quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]);
quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]);
quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]);
quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]);
}}
}
impl State {
fn expand(key: &[u8], nonce: &[u8], position: u32) -> Self {
let mut state = [0u32; STATE_WORDS];
state[0] = 0x61707865;
state[1] = 0x3320646e;
state[2] = 0x79622d32;
state[3] = 0x6b206574;
for (state, chunk) in state[4..12].iter_mut().zip(key.chunks(4)) {
*state = LittleEndian::read_u32(chunk);
}
state[12] = position;
for (state, chunk) in state[13..16].iter_mut().zip(nonce.chunks(4)) {
*state = LittleEndian::read_u32(chunk);
}
State(state)
}
fn update(&mut self, output: &mut [u32]) {
let mut state = self.0;
for _ in 0..ROUNDS / 2 {
double_round!(state);
}
for i in 0..STATE_WORDS {
output[i] = self.0[i].wrapping_add(state[i]);
}
self.0[12] += 1;
}
}
pub struct ChaCha20 {
state: State,
buffer: [u32; STATE_WORDS],
index: usize,
}
impl ChaCha20 {
pub fn init(key: &[u8], nonce: &[u8], position: u32) -> Self {
ChaCha20 {
state: State::expand(key.as_ref(), nonce.as_ref(), position),
buffer: [0; STATE_WORDS],
index: STATE_BYTES,
}
}
pub fn new<Key, Nonce>(key: Key, nonce: Nonce) -> Self
where Key: AsRef<[u8]>,
Nonce: AsRef<[u8]>
{
Self::init(key.as_ref(), nonce.as_ref(), 1)
}
fn update(&mut self) {
self.state.update(&mut self.buffer[..]);
self.index = 0;
}
fn crypt(&mut self, input: &[u8], output: &mut [u8]) {
if self.index == STATE_BYTES |
let buffer = unsafe {
slice::from_raw_parts(self.buffer.as_ptr() as *const u8, STATE_BYTES)
};
for i in self.index..input.len() {
output[i] = input[i] ^ buffer[i];
}
self.index = input.len();
}
}
impl StreamEncrypt for ChaCha20 {
fn encrypt_stream<I, O>(&mut self, input: I, mut output: O)
where I: AsRef<[u8]>,
O: AsMut<[u8]>
{
assert_eq!(input.as_ref().len(), output.as_mut().len());
let input = input.as_ref();
let output = output.as_mut();
let from = STATE_BYTES - self.index;
if from > 0 {
self.crypt(&input[..from], &mut output[..from]);
}
for (i, o) in input[from..]
.chunks(STATE_BYTES)
.zip(output[from..].chunks_mut(STATE_BYTES)) {
self.crypt(i, o)
}
}
}
impl StreamDecrypt for ChaCha20 {
fn decrypt_stream<I, O>(&mut self, input: I, mut output: O)
where I: AsRef<[u8]>,
O: AsMut<[u8]>
{
assert_eq!(input.as_ref().len(), output.as_mut().len());
let input = input.as_ref().chunks(STATE_BYTES);
let output = output.as_mut().chunks_mut(STATE_BYTES);
for (i, o) in input.zip(output) {
self.crypt(i, o)
}
}
}
| {
self.update()
} | conditional_block |
chacha20.rs | use std::slice;
use super::{StreamEncrypt, StreamDecrypt};
use byteorder::{ByteOrder, LittleEndian};
const ROUNDS: usize = 20;
const STATE_WORDS: usize = 16;
const STATE_BYTES: usize = STATE_WORDS * 4;
#[derive(Copy, Clone)]
struct State([u32; STATE_WORDS]);
macro_rules! quarter_round {
($a:expr, $b:expr, $c:expr, $d:expr) => {{
$a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left(16);
$c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left(12);
$a = $a.wrapping_add($b); $d ^= $a; $d = $d.rotate_left( 8);
$c = $c.wrapping_add($d); $b ^= $c; $b = $b.rotate_left( 7);
}}
}
macro_rules! double_round {
($x:expr) => {{
// Column round
quarter_round!($x[ 0], $x[ 4], $x[ 8], $x[12]);
quarter_round!($x[ 1], $x[ 5], $x[ 9], $x[13]);
quarter_round!($x[ 2], $x[ 6], $x[10], $x[14]);
quarter_round!($x[ 3], $x[ 7], $x[11], $x[15]);
// Diagonal round
quarter_round!($x[ 0], $x[ 5], $x[10], $x[15]);
quarter_round!($x[ 1], $x[ 6], $x[11], $x[12]);
quarter_round!($x[ 2], $x[ 7], $x[ 8], $x[13]);
quarter_round!($x[ 3], $x[ 4], $x[ 9], $x[14]);
}}
}
impl State {
fn expand(key: &[u8], nonce: &[u8], position: u32) -> Self {
let mut state = [0u32; STATE_WORDS];
state[0] = 0x61707865;
state[1] = 0x3320646e;
state[2] = 0x79622d32;
state[3] = 0x6b206574;
for (state, chunk) in state[4..12].iter_mut().zip(key.chunks(4)) {
*state = LittleEndian::read_u32(chunk);
}
state[12] = position;
for (state, chunk) in state[13..16].iter_mut().zip(nonce.chunks(4)) {
*state = LittleEndian::read_u32(chunk);
}
State(state)
}
fn update(&mut self, output: &mut [u32]) {
let mut state = self.0;
for _ in 0..ROUNDS / 2 {
double_round!(state);
}
for i in 0..STATE_WORDS {
output[i] = self.0[i].wrapping_add(state[i]);
}
self.0[12] += 1;
}
}
pub struct ChaCha20 {
state: State,
buffer: [u32; STATE_WORDS],
index: usize,
}
impl ChaCha20 { | state: State::expand(key.as_ref(), nonce.as_ref(), position),
buffer: [0; STATE_WORDS],
index: STATE_BYTES,
}
}
pub fn new<Key, Nonce>(key: Key, nonce: Nonce) -> Self
where Key: AsRef<[u8]>,
Nonce: AsRef<[u8]>
{
Self::init(key.as_ref(), nonce.as_ref(), 1)
}
fn update(&mut self) {
self.state.update(&mut self.buffer[..]);
self.index = 0;
}
fn crypt(&mut self, input: &[u8], output: &mut [u8]) {
if self.index == STATE_BYTES {
self.update()
}
let buffer = unsafe {
slice::from_raw_parts(self.buffer.as_ptr() as *const u8, STATE_BYTES)
};
for i in self.index..input.len() {
output[i] = input[i] ^ buffer[i];
}
self.index = input.len();
}
}
impl StreamEncrypt for ChaCha20 {
fn encrypt_stream<I, O>(&mut self, input: I, mut output: O)
where I: AsRef<[u8]>,
O: AsMut<[u8]>
{
assert_eq!(input.as_ref().len(), output.as_mut().len());
let input = input.as_ref();
let output = output.as_mut();
let from = STATE_BYTES - self.index;
if from > 0 {
self.crypt(&input[..from], &mut output[..from]);
}
for (i, o) in input[from..]
.chunks(STATE_BYTES)
.zip(output[from..].chunks_mut(STATE_BYTES)) {
self.crypt(i, o)
}
}
}
impl StreamDecrypt for ChaCha20 {
fn decrypt_stream<I, O>(&mut self, input: I, mut output: O)
where I: AsRef<[u8]>,
O: AsMut<[u8]>
{
assert_eq!(input.as_ref().len(), output.as_mut().len());
let input = input.as_ref().chunks(STATE_BYTES);
let output = output.as_mut().chunks_mut(STATE_BYTES);
for (i, o) in input.zip(output) {
self.crypt(i, o)
}
}
} | pub fn init(key: &[u8], nonce: &[u8], position: u32) -> Self {
ChaCha20 { | random_line_split |
directory.rs | }
/// A Digest for a directory, optionally with its content stored as a DigestTrie.
///
/// If a DirectoryDigest has a DigestTrie reference, then its Digest _might not_ be persisted to
/// the Store. If the DirectoryDigest does not hold a DigestTrie, then that Digest _must_ have been
/// persisted to the Store (either locally or remotely). The field thus acts likes a cache in some
/// cases, but in other cases is an indication that the tree must first be persisted (or loaded)
/// before the Digest may be operated on.
#[derive(Clone, DeepSizeOf)]
pub struct DirectoryDigest {
// NB: Private in order to force a choice between `todo_as_digest` and `as_digest`.
digest: Digest,
pub tree: Option<DigestTrie>,
}
impl workunit_store::DirectoryDigest for DirectoryDigest {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl Eq for DirectoryDigest {}
impl PartialEq for DirectoryDigest {
fn eq(&self, other: &Self) -> bool {
self.digest == other.digest
}
}
impl Hash for DirectoryDigest {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.digest.hash(state);
}
}
impl Debug for DirectoryDigest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// NB: To avoid over-large output, we don't render the Trie. It would likely be best rendered
// as e.g. JSON.
let tree = if self.tree.is_some() {
"Some(..)"
} else {
"None"
};
write!(f, "DirectoryDigest({:?}, tree: {})", self.digest, tree)
}
}
impl DirectoryDigest {
/// Construct a DirectoryDigest from a Digest and DigestTrie (by asserting that the Digest
/// identifies the DigestTrie).
pub fn new(digest: Digest, tree: DigestTrie) -> Self {
if cfg!(debug_assertions) {
assert!(digest == tree.compute_root_digest());
}
Self {
digest,
tree: Some(tree),
}
}
/// Creates a DirectoryDigest which asserts that the given Digest represents a Directory structure
/// which is persisted in a Store.
///
/// Use of this method should be rare: code should prefer to pass around a `DirectoryDigest` rather
/// than to create one from a `Digest` (as the latter requires loading the content from disk).
///
/// TODO: If a callsite needs to create a `DirectoryDigest` as a convenience (i.e. in a location
/// where its signature could be changed to accept a `DirectoryDigest` instead of constructing
/// one) during the porting effort of #13112, it should use `todo_from_digest` rather than
/// `from_persisted_digest`.
pub fn from_persisted_digest(digest: Digest) -> Self {
Self { digest, tree: None }
}
/// Marks a callsite that is creating a `DirectoryDigest` as a temporary convenience, rather than
/// accepting a `DirectoryDigest` in its signature. All usages of this method should be removed
/// before closing #13112.
pub fn todo_from_digest(digest: Digest) -> Self {
Self { digest, tree: None }
}
pub fn from_tree(tree: DigestTrie) -> Self {
Self {
digest: tree.compute_root_digest(),
tree: Some(tree),
}
}
/// Returns the `Digest` for this `DirectoryDigest`.
///
/// TODO: If a callsite needs to convert to `Digest` as a convenience (i.e. in a location where
/// its signature could be changed to return a `DirectoryDigest` instead) during the porting
/// effort of #13112, it should use `todo_as_digest` rather than `as_digest`.
pub fn as_digest(&self) -> Digest {
self.digest
}
/// Marks a callsite that is discarding the `DigestTrie` held by this `DirectoryDigest` as a
/// temporary convenience, rather than updating its signature to return a `DirectoryDigest`. All
/// usages of this method should be removed before closing #13112.
pub fn todo_as_digest(self) -> Digest {
self.digest
}
/// Returns the digests reachable from this DirectoryDigest.
///
/// If this DirectoryDigest has been persisted to disk (i.e., does not have a DigestTrie) then
/// this will only include the root.
pub fn digests(&self) -> Vec<Digest> {
if let Some(tree) = &self.tree {
let mut digests = tree.digests();
digests.push(self.digest);
digests
} else {
vec![self.digest]
}
}
}
/// A single component of a filesystem path.
///
/// For example: the path `foo/bar` will be broken up into `Name("foo")` and `Name("bar")`.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Name(Intern<String>);
// NB: Calculating the actual deep size of an `Intern` is very challenging, because it does not
// keep any record of the number of held references, and instead effectively makes its held value
// static. Switching to `ArcIntern` would get accurate counts at the cost of performance and size.
known_deep_size!(0; Name);
impl Deref for Name {
type Target = Intern<String>;
fn deref(&self) -> &Intern<String> {
&self.0
}
}
#[derive(Clone, DeepSizeOf)]
pub enum Entry {
Directory(Directory),
File(File),
}
impl Entry {
fn name(&self) -> Name {
match self {
Entry::Directory(d) => d.name,
Entry::File(f) => f.name,
}
}
}
#[derive(Clone, DeepSizeOf)]
pub struct Directory {
name: Name,
digest: Digest,
tree: DigestTrie,
}
impl Directory {
fn new(name: Name, entries: Vec<Entry>) -> Self {
Self::from_digest_tree(name, DigestTrie(entries.into()))
}
fn from_digest_tree(name: Name, tree: DigestTrie) -> Self {
Self {
name,
digest: tree.compute_root_digest(),
tree,
}
}
pub fn name(&self) -> &str {
self.name.as_ref()
}
pub fn digest(&self) -> Digest {
self.digest
}
pub fn tree(&self) -> &DigestTrie {
&self.tree
}
pub fn as_remexec_directory(&self) -> remexec::Directory {
self.tree.as_remexec_directory()
}
pub fn as_remexec_directory_node(&self) -> remexec::DirectoryNode {
remexec::DirectoryNode {
name: self.name.as_ref().to_owned(),
digest: Some((&self.digest).into()),
}
}
}
#[derive(Clone, DeepSizeOf)]
pub struct File {
name: Name,
digest: Digest,
is_executable: bool,
}
impl File {
pub fn name(&self) -> &str {
self.name.as_ref()
}
pub fn digest(&self) -> Digest {
self.digest
}
pub fn is_executable(&self) -> bool {
self.is_executable
}
pub fn as_remexec_file_node(&self) -> remexec::FileNode {
remexec::FileNode {
name: self.name.as_ref().to_owned(),
digest: Some(self.digest.into()),
is_executable: self.is_executable,
..remexec::FileNode::default()
}
}
}
// TODO: `PathStat` owns its path, which means it can't be used via recursive slicing. See
// whether these types can be merged.
enum TypedPath<'a> {
File { path: &'a Path, is_executable: bool },
Dir(&'a Path),
}
impl<'a> Deref for TypedPath<'a> {
type Target = Path;
fn deref(&self) -> &Path {
match self {
TypedPath::File { path,.. } => path,
TypedPath::Dir(d) => d,
}
}
}
impl<'a> From<&'a PathStat> for TypedPath<'a> {
fn from(p: &'a PathStat) -> Self {
match p {
PathStat::File { path, stat } => TypedPath::File {
path,
is_executable: stat.is_executable,
},
PathStat::Dir { path,.. } => TypedPath::Dir(path),
}
}
}
#[derive(Clone, DeepSizeOf)]
pub struct DigestTrie(Arc<[Entry]>);
// TODO: This avoids a `rustc` crasher (repro on 7f319ee84ad41bc0aea3cb01fb2f32dcd51be704).
unsafe impl Sync for DigestTrie {}
impl DigestTrie {
/// Create a DigestTrie from unique PathStats. Fails for duplicate items.
pub fn from_path_stats(
mut path_stats: Vec<PathStat>,
file_digests: &HashMap<PathBuf, Digest>,
) -> Result<Self, String> {
// Sort and ensure that there were no duplicate entries.
//#[allow(clippy::unnecessary_sort_by)]
path_stats.sort_by(|a, b| a.path().cmp(b.path()));
// The helper assumes that if a Path has multiple children, it must be a directory.
// Proactively error if we run into identically named files, because otherwise we will treat
// them like empty directories.
let pre_dedupe_len = path_stats.len();
path_stats.dedup_by(|a, b| a.path() == b.path());
if path_stats.len()!= pre_dedupe_len {
return Err(format!(
"Snapshots must be constructed from unique path stats; got duplicates in {:?}",
path_stats
));
}
Self::from_sorted_paths(
PathBuf::new(),
path_stats.iter().map(|p| p.into()).collect(),
file_digests,
)
}
fn from_sorted_paths(
prefix: PathBuf,
paths: Vec<TypedPath>,
file_digests: &HashMap<PathBuf, Digest>,
) -> Result<Self, String> {
let mut entries = Vec::new();
for (name_res, group) in &paths
.into_iter()
.group_by(|s| first_path_component_to_name(s))
{
let name = name_res?;
let mut path_group: Vec<TypedPath> = group.collect();
if path_group.len() == 1 && path_group[0].components().count() == 1 {
// Exactly one entry with exactly one component indicates either a file in this directory,
// or an empty directory.
// If the child is a non-empty directory, or a file therein, there must be multiple
// PathStats with that prefix component, and we will handle that recursively.
match path_group.pop().unwrap() {
TypedPath::File {
path,
is_executable,
} => {
let digest = *file_digests.get(prefix.join(path).as_path()).unwrap();
entries.push(Entry::File(File {
name,
digest,
is_executable,
}));
}
TypedPath::Dir {.. } => {
// Because there are no children of this Dir, it must be empty.
entries.push(Entry::Directory(Directory::new(name, vec![])));
}
}
} else {
// Because there are no children of this Dir, it must be empty.
entries.push(Entry::Directory(Directory::from_digest_tree(
name,
Self::from_sorted_paths(
prefix.join(name.as_ref()),
paths_of_child_dir(name, path_group),
file_digests,
)?,
)));
}
}
Ok(Self(entries.into()))
}
pub fn as_remexec_directory(&self) -> remexec::Directory {
let mut files = Vec::new();
let mut directories = Vec::new();
for entry in &*self.0 {
match entry {
Entry::File(f) => files.push(f.as_remexec_file_node()),
Entry::Directory(d) => directories.push(d.as_remexec_directory_node()),
}
}
remexec::Directory {
directories,
files,
..remexec::Directory::default()
}
}
pub fn compute_root_digest(&self) -> Digest {
if self.0.is_empty() {
return EMPTY_DIGEST;
}
Digest::of_bytes(&self.as_remexec_directory().to_bytes())
}
pub fn entries(&self) -> &[Entry] {
&*self.0
}
/// Returns the digests reachable from this DigestTrie.
pub fn digests(&self) -> Vec<Digest> {
// Walk the tree and collect Digests.
let mut digests = Vec::new();
let mut stack = self.0.iter().collect::<Vec<_>>();
while let Some(entry) = stack.pop() {
match entry {
Entry::Directory(d) => {
digests.push(d.digest);
stack.extend(d.tree.0.iter());
}
Entry::File(f) => {
digests.push(f.digest);
}
}
}
digests
} | /// can directly allocate the collections that they need.
pub fn files_and_directories(&self) -> (Vec<PathBuf>, Vec<PathBuf>) {
let mut files = Vec::new();
let mut directories = Vec::new();
self.walk(&mut |path, entry| {
match entry {
Entry::File(_) => files.push(path.to_owned()),
Entry::Directory(d) if d.name.is_empty() => {
// Is the root directory, which is not emitted here.
}
Entry::Directory(_) => directories.push(path.to_owned()),
}
});
(files, directories)
}
/// Visit every node in the tree, calling the given function with the path to the Node, and its
/// entries.
pub fn walk(&self, f: &mut impl FnMut(&Path, &Entry)) {
{
// TODO: It's likely that a DigestTrie should hold its own Digest, to avoid re-computing it
// here.
let root = Entry::Directory(Directory::from_digest_tree(
Name(Intern::from("")),
self.clone(),
));
f(&PathBuf::new(), &root);
}
self.walk_helper(PathBuf::new(), f)
}
fn walk_helper(&self, path_so_far: PathBuf, f: &mut impl FnMut(&Path, &Entry)) {
for entry in &*self.0 {
let path = path_so_far.join(entry.name().as_ref());
f(&path, entry);
if let Entry::Directory(d) = entry {
d.tree.walk_helper(path, f);
}
}
}
/// Add the given path as a prefix for this trie, returning the resulting trie.
pub fn add_prefix(self, prefix: &RelativePath) -> Result<DigestTrie, String> {
let mut prefix_iter = prefix.iter();
let mut tree = self;
while let Some(parent) = prefix_iter.next_back() {
let directory = Directory {
name: first_path_component_to_name(parent.as_ref())?,
digest: tree.compute_root_digest(),
tree,
};
tree = DigestTrie(vec![Entry::Directory(directory)].into());
}
Ok(tree)
}
/// Remove the given prefix from this trie, returning the resulting trie.
pub fn remove_prefix(self, prefix: &RelativePath) -> Result<DigestTrie, String> {
let root = self.clone();
let mut tree = self;
let mut already_stripped = PathBuf::new();
for component_to_strip in prefix.components() {
let component_to_strip = component_to_strip.as_os_str();
let mut matching_dir = None;
let mut extra_directories = Vec::new();
let mut files = Vec::new();
for entry in tree.entries() {
match entry {
Entry::Directory(d) if Path::new(d.name.as_ref()).as_os_str() == component_to_strip => {
matching_dir = Some(d)
}
Entry::Directory(d) => extra_directories.push(d.name.as_ref().to_owned()),
Entry::File(f) => files.push(f.name.as_ref().to_owned()),
}
}
let has_already_stripped_any = already_stripped.components().next().is_some();
match (
matching_dir,
extra_directories.is_empty() && files.is_empty(),
) {
(None, true) => {
tree = EMPTY_DIGEST_TREE.clone();
break;
}
(None, false) => {
// Prefer "No subdirectory found" error to "had extra files" error.
return Err(format!(
"Cannot strip prefix {} from root directory (Digest with hash {:?}) - \
{}directory{} didn't contain a directory named {}{}",
prefix.display(),
root.compute_root_digest().hash,
if has_already_stripped_any {
"sub"
} else {
"root "
},
if has_already_stripped_any {
format!(" {}", already_stripped.display())
} else {
String::new()
},
Path::new(component_to_strip).display(),
if!extra_directories.is_empty() ||!files.is_empty() {
format!(
" but did contain {}",
format_directories_and_files(&extra_directories, &files)
)
} else {
String::new()
},
));
}
(Some(_), false) => {
return Err(format!(
"Cannot strip prefix {} from root directory (Digest with hash {:?}) - \
{}directory{} contained non-matching {}",
prefix.display(),
root.compute_root_digest().hash,
if has_already_stripped_any {
"sub"
} else {
"root "
},
if has_already_stripped_any {
format!(" {}", already_stripped.display())
} else {
String::new()
},
format_directories_and_files(&extra_directories, &files),
))
}
(Some(d), true) => {
already_stripped = already_stripped.join(component_to_strip);
tree = d.tree.clone();
}
}
}
Ok(tree)
}
/// Given DigestTries, merge them recursively into a single DigestTrie.
///
/// If a file is present with the same name and contents multiple times, it will appear once.
/// If a file is present with the same name, but different contents, an error will be returned.
pub fn merge(trees: Vec<DigestTrie>) -> Result<DigestTrie, MergeError> {
Self::merge_helper(PathBuf::new(), trees)
}
fn merge_helper(parent_path: PathBuf, trees: Vec<DigestTrie>) -> Result<DigestTrie, MergeError> {
if trees.is_empty() {
return Ok(EMPTY_DIGEST_TREE.clone());
} else if trees.len() == 1 {
let mut trees = trees;
return Ok(trees.pop().unwrap());
}
// Merge and sort Entries.
let input_entries = trees
.iter()
.map(|tree| tree.entries())
.flatten()
.sorted_by(|a, b| a.name().cmp(&b.name()));
// Then group by name, and merge into an output list.
let mut entries: Vec<Entry> = Vec::new();
for (name, group) in &input_entries.into_iter().group_by(|e| e.name()) {
let mut group = group.peekable();
let first = group.next().unwrap();
if group.peek().is_none() {
// There was only one Entry: emit it.
entries.push(first.clone());
continue;
}
match first {
Entry::File(f) => {
// If any Entry is a File, then they must all be identical.
let (mut mismatched_files, mismatched_dirs) = collisions(f.digest, group);
if!mismatched_files.is_empty() ||!mismatched_dirs.is_empty() {
mismatched_files.push(f);
return Err(MergeError::duplicates(
parent_path,
mismatched_files,
mismatched_dirs,
));
}
// All entries matched: emit one copy.
entries.push(first.clone());
}
Entry::Directory(d) => {
// If any Entry is a Directory, then they must all be Directories which will be merged.
let (mismatched_files, mut mismatched_dirs) = collisions(d.digest, group);
// If there were any Files, error.
if!mismatched_files.is_empty() {
mismatched_dirs.push(d);
return Err(MergeError::duplicates(
parent_path,
mismatched_files,
mismatched_dirs,
));
}
if mismatched_dirs.is_empty() {
// All directories matched: emit one copy.
entries.push(first.clone());
} else {
// Some directories mismatched, so merge all of them into a new entry and emit that.
mismatched_dirs.push(d);
let merged_tree = Self::merge_helper(
parent_path.join(name.as_ref()),
mismatched_dirs
.into_iter()
.map(|d| d.tree.clone())
.collect(),
)?;
entries.push(Entry::Directory(Directory::from_digest_tree(
name,
merged_tree,
)));
}
}
}
}
Ok(DigestTrie(entries.into()))
}
}
pub enum MergeError {
Duplicates {
parent_path: PathBuf,
files: Vec<File>,
directories: Vec<Directory>,
},
}
impl MergeError {
fn duplicates(parent_path: PathBuf, files: Vec<&File>, directories: Vec<&Directory>) -> Self {
MergeError::Duplicates {
parent_path,
files: files.into_iter().cloned().collect(),
directories: directories.into_iter().cloned().collect(),
}
}
}
fn paths_of_child_dir(name: Name, paths: Vec<TypedPath>) -> Vec<TypedPath> {
paths
.into_iter()
.filter_map(|s| {
if s.components().count() == 1 {
return None;
}
Some(match s {
TypedPath::File {
path,
is_executable,
} => TypedPath::File {
path: path.strip_prefix(name.as_ref()).unwrap(),
is_executable,
},
TypedPath::Dir(path) => TypedPath::Dir(path.strip_prefix(name.as_ref()).unwrap()),
})
})
.collect()
}
fn first_path_component_to_name(path |
/// Return a pair of Vecs of the file paths and directory paths in this DigestTrie, each in
/// sorted order.
///
/// TODO: This should probably be implemented directly by consumers via `walk`, since they | random_line_split |
directory.rs |
/// A Digest for a directory, optionally with its content stored as a DigestTrie.
///
/// If a DirectoryDigest has a DigestTrie reference, then its Digest _might not_ be persisted to
/// the Store. If the DirectoryDigest does not hold a DigestTrie, then that Digest _must_ have been
/// persisted to the Store (either locally or remotely). The field thus acts likes a cache in some
/// cases, but in other cases is an indication that the tree must first be persisted (or loaded)
/// before the Digest may be operated on.
#[derive(Clone, DeepSizeOf)]
pub struct DirectoryDigest {
// NB: Private in order to force a choice between `todo_as_digest` and `as_digest`.
digest: Digest,
pub tree: Option<DigestTrie>,
}
impl workunit_store::DirectoryDigest for DirectoryDigest {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl Eq for DirectoryDigest {}
impl PartialEq for DirectoryDigest {
fn eq(&self, other: &Self) -> bool {
self.digest == other.digest
}
}
impl Hash for DirectoryDigest {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.digest.hash(state);
}
}
impl Debug for DirectoryDigest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// NB: To avoid over-large output, we don't render the Trie. It would likely be best rendered
// as e.g. JSON.
let tree = if self.tree.is_some() {
"Some(..)"
} else {
"None"
};
write!(f, "DirectoryDigest({:?}, tree: {})", self.digest, tree)
}
}
impl DirectoryDigest {
/// Construct a DirectoryDigest from a Digest and DigestTrie (by asserting that the Digest
/// identifies the DigestTrie).
pub fn new(digest: Digest, tree: DigestTrie) -> Self |
/// Creates a DirectoryDigest which asserts that the given Digest represents a Directory structure
/// which is persisted in a Store.
///
/// Use of this method should be rare: code should prefer to pass around a `DirectoryDigest` rather
/// than to create one from a `Digest` (as the latter requires loading the content from disk).
///
/// TODO: If a callsite needs to create a `DirectoryDigest` as a convenience (i.e. in a location
/// where its signature could be changed to accept a `DirectoryDigest` instead of constructing
/// one) during the porting effort of #13112, it should use `todo_from_digest` rather than
/// `from_persisted_digest`.
pub fn from_persisted_digest(digest: Digest) -> Self {
Self { digest, tree: None }
}
/// Marks a callsite that is creating a `DirectoryDigest` as a temporary convenience, rather than
/// accepting a `DirectoryDigest` in its signature. All usages of this method should be removed
/// before closing #13112.
pub fn todo_from_digest(digest: Digest) -> Self {
Self { digest, tree: None }
}
pub fn from_tree(tree: DigestTrie) -> Self {
Self {
digest: tree.compute_root_digest(),
tree: Some(tree),
}
}
/// Returns the `Digest` for this `DirectoryDigest`.
///
/// TODO: If a callsite needs to convert to `Digest` as a convenience (i.e. in a location where
/// its signature could be changed to return a `DirectoryDigest` instead) during the porting
/// effort of #13112, it should use `todo_as_digest` rather than `as_digest`.
pub fn as_digest(&self) -> Digest {
self.digest
}
/// Marks a callsite that is discarding the `DigestTrie` held by this `DirectoryDigest` as a
/// temporary convenience, rather than updating its signature to return a `DirectoryDigest`. All
/// usages of this method should be removed before closing #13112.
pub fn todo_as_digest(self) -> Digest {
self.digest
}
/// Returns the digests reachable from this DirectoryDigest.
///
/// If this DirectoryDigest has been persisted to disk (i.e., does not have a DigestTrie) then
/// this will only include the root.
pub fn digests(&self) -> Vec<Digest> {
if let Some(tree) = &self.tree {
let mut digests = tree.digests();
digests.push(self.digest);
digests
} else {
vec![self.digest]
}
}
}
/// A single component of a filesystem path.
///
/// For example: the path `foo/bar` will be broken up into `Name("foo")` and `Name("bar")`.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Name(Intern<String>);
// NB: Calculating the actual deep size of an `Intern` is very challenging, because it does not
// keep any record of the number of held references, and instead effectively makes its held value
// static. Switching to `ArcIntern` would get accurate counts at the cost of performance and size.
known_deep_size!(0; Name);
impl Deref for Name {
type Target = Intern<String>;
fn deref(&self) -> &Intern<String> {
&self.0
}
}
#[derive(Clone, DeepSizeOf)]
pub enum Entry {
Directory(Directory),
File(File),
}
impl Entry {
fn name(&self) -> Name {
match self {
Entry::Directory(d) => d.name,
Entry::File(f) => f.name,
}
}
}
#[derive(Clone, DeepSizeOf)]
pub struct Directory {
name: Name,
digest: Digest,
tree: DigestTrie,
}
impl Directory {
fn new(name: Name, entries: Vec<Entry>) -> Self {
Self::from_digest_tree(name, DigestTrie(entries.into()))
}
fn from_digest_tree(name: Name, tree: DigestTrie) -> Self {
Self {
name,
digest: tree.compute_root_digest(),
tree,
}
}
pub fn name(&self) -> &str {
self.name.as_ref()
}
pub fn digest(&self) -> Digest {
self.digest
}
pub fn tree(&self) -> &DigestTrie {
&self.tree
}
pub fn as_remexec_directory(&self) -> remexec::Directory {
self.tree.as_remexec_directory()
}
pub fn as_remexec_directory_node(&self) -> remexec::DirectoryNode {
remexec::DirectoryNode {
name: self.name.as_ref().to_owned(),
digest: Some((&self.digest).into()),
}
}
}
#[derive(Clone, DeepSizeOf)]
pub struct File {
name: Name,
digest: Digest,
is_executable: bool,
}
impl File {
pub fn name(&self) -> &str {
self.name.as_ref()
}
pub fn digest(&self) -> Digest {
self.digest
}
pub fn is_executable(&self) -> bool {
self.is_executable
}
pub fn as_remexec_file_node(&self) -> remexec::FileNode {
remexec::FileNode {
name: self.name.as_ref().to_owned(),
digest: Some(self.digest.into()),
is_executable: self.is_executable,
..remexec::FileNode::default()
}
}
}
// TODO: `PathStat` owns its path, which means it can't be used via recursive slicing. See
// whether these types can be merged.
enum TypedPath<'a> {
File { path: &'a Path, is_executable: bool },
Dir(&'a Path),
}
impl<'a> Deref for TypedPath<'a> {
type Target = Path;
fn deref(&self) -> &Path {
match self {
TypedPath::File { path,.. } => path,
TypedPath::Dir(d) => d,
}
}
}
impl<'a> From<&'a PathStat> for TypedPath<'a> {
fn from(p: &'a PathStat) -> Self {
match p {
PathStat::File { path, stat } => TypedPath::File {
path,
is_executable: stat.is_executable,
},
PathStat::Dir { path,.. } => TypedPath::Dir(path),
}
}
}
#[derive(Clone, DeepSizeOf)]
pub struct DigestTrie(Arc<[Entry]>);
// TODO: This avoids a `rustc` crasher (repro on 7f319ee84ad41bc0aea3cb01fb2f32dcd51be704).
unsafe impl Sync for DigestTrie {}
impl DigestTrie {
/// Create a DigestTrie from unique PathStats. Fails for duplicate items.
pub fn from_path_stats(
mut path_stats: Vec<PathStat>,
file_digests: &HashMap<PathBuf, Digest>,
) -> Result<Self, String> {
// Sort and ensure that there were no duplicate entries.
//#[allow(clippy::unnecessary_sort_by)]
path_stats.sort_by(|a, b| a.path().cmp(b.path()));
// The helper assumes that if a Path has multiple children, it must be a directory.
// Proactively error if we run into identically named files, because otherwise we will treat
// them like empty directories.
let pre_dedupe_len = path_stats.len();
path_stats.dedup_by(|a, b| a.path() == b.path());
if path_stats.len()!= pre_dedupe_len {
return Err(format!(
"Snapshots must be constructed from unique path stats; got duplicates in {:?}",
path_stats
));
}
Self::from_sorted_paths(
PathBuf::new(),
path_stats.iter().map(|p| p.into()).collect(),
file_digests,
)
}
fn from_sorted_paths(
prefix: PathBuf,
paths: Vec<TypedPath>,
file_digests: &HashMap<PathBuf, Digest>,
) -> Result<Self, String> {
let mut entries = Vec::new();
for (name_res, group) in &paths
.into_iter()
.group_by(|s| first_path_component_to_name(s))
{
let name = name_res?;
let mut path_group: Vec<TypedPath> = group.collect();
if path_group.len() == 1 && path_group[0].components().count() == 1 {
// Exactly one entry with exactly one component indicates either a file in this directory,
// or an empty directory.
// If the child is a non-empty directory, or a file therein, there must be multiple
// PathStats with that prefix component, and we will handle that recursively.
match path_group.pop().unwrap() {
TypedPath::File {
path,
is_executable,
} => {
let digest = *file_digests.get(prefix.join(path).as_path()).unwrap();
entries.push(Entry::File(File {
name,
digest,
is_executable,
}));
}
TypedPath::Dir {.. } => {
// Because there are no children of this Dir, it must be empty.
entries.push(Entry::Directory(Directory::new(name, vec![])));
}
}
} else {
// Because there are no children of this Dir, it must be empty.
entries.push(Entry::Directory(Directory::from_digest_tree(
name,
Self::from_sorted_paths(
prefix.join(name.as_ref()),
paths_of_child_dir(name, path_group),
file_digests,
)?,
)));
}
}
Ok(Self(entries.into()))
}
pub fn as_remexec_directory(&self) -> remexec::Directory {
let mut files = Vec::new();
let mut directories = Vec::new();
for entry in &*self.0 {
match entry {
Entry::File(f) => files.push(f.as_remexec_file_node()),
Entry::Directory(d) => directories.push(d.as_remexec_directory_node()),
}
}
remexec::Directory {
directories,
files,
..remexec::Directory::default()
}
}
pub fn compute_root_digest(&self) -> Digest {
if self.0.is_empty() {
return EMPTY_DIGEST;
}
Digest::of_bytes(&self.as_remexec_directory().to_bytes())
}
pub fn entries(&self) -> &[Entry] {
&*self.0
}
/// Returns the digests reachable from this DigestTrie.
pub fn digests(&self) -> Vec<Digest> {
// Walk the tree and collect Digests.
let mut digests = Vec::new();
let mut stack = self.0.iter().collect::<Vec<_>>();
while let Some(entry) = stack.pop() {
match entry {
Entry::Directory(d) => {
digests.push(d.digest);
stack.extend(d.tree.0.iter());
}
Entry::File(f) => {
digests.push(f.digest);
}
}
}
digests
}
/// Return a pair of Vecs of the file paths and directory paths in this DigestTrie, each in
/// sorted order.
///
/// TODO: This should probably be implemented directly by consumers via `walk`, since they
/// can directly allocate the collections that they need.
pub fn files_and_directories(&self) -> (Vec<PathBuf>, Vec<PathBuf>) {
let mut files = Vec::new();
let mut directories = Vec::new();
self.walk(&mut |path, entry| {
match entry {
Entry::File(_) => files.push(path.to_owned()),
Entry::Directory(d) if d.name.is_empty() => {
// Is the root directory, which is not emitted here.
}
Entry::Directory(_) => directories.push(path.to_owned()),
}
});
(files, directories)
}
/// Visit every node in the tree, calling the given function with the path to the Node, and its
/// entries.
pub fn walk(&self, f: &mut impl FnMut(&Path, &Entry)) {
{
// TODO: It's likely that a DigestTrie should hold its own Digest, to avoid re-computing it
// here.
let root = Entry::Directory(Directory::from_digest_tree(
Name(Intern::from("")),
self.clone(),
));
f(&PathBuf::new(), &root);
}
self.walk_helper(PathBuf::new(), f)
}
fn walk_helper(&self, path_so_far: PathBuf, f: &mut impl FnMut(&Path, &Entry)) {
for entry in &*self.0 {
let path = path_so_far.join(entry.name().as_ref());
f(&path, entry);
if let Entry::Directory(d) = entry {
d.tree.walk_helper(path, f);
}
}
}
/// Add the given path as a prefix for this trie, returning the resulting trie.
pub fn add_prefix(self, prefix: &RelativePath) -> Result<DigestTrie, String> {
let mut prefix_iter = prefix.iter();
let mut tree = self;
while let Some(parent) = prefix_iter.next_back() {
let directory = Directory {
name: first_path_component_to_name(parent.as_ref())?,
digest: tree.compute_root_digest(),
tree,
};
tree = DigestTrie(vec![Entry::Directory(directory)].into());
}
Ok(tree)
}
/// Remove the given prefix from this trie, returning the resulting trie.
pub fn remove_prefix(self, prefix: &RelativePath) -> Result<DigestTrie, String> {
let root = self.clone();
let mut tree = self;
let mut already_stripped = PathBuf::new();
for component_to_strip in prefix.components() {
let component_to_strip = component_to_strip.as_os_str();
let mut matching_dir = None;
let mut extra_directories = Vec::new();
let mut files = Vec::new();
for entry in tree.entries() {
match entry {
Entry::Directory(d) if Path::new(d.name.as_ref()).as_os_str() == component_to_strip => {
matching_dir = Some(d)
}
Entry::Directory(d) => extra_directories.push(d.name.as_ref().to_owned()),
Entry::File(f) => files.push(f.name.as_ref().to_owned()),
}
}
let has_already_stripped_any = already_stripped.components().next().is_some();
match (
matching_dir,
extra_directories.is_empty() && files.is_empty(),
) {
(None, true) => {
tree = EMPTY_DIGEST_TREE.clone();
break;
}
(None, false) => {
// Prefer "No subdirectory found" error to "had extra files" error.
return Err(format!(
"Cannot strip prefix {} from root directory (Digest with hash {:?}) - \
{}directory{} didn't contain a directory named {}{}",
prefix.display(),
root.compute_root_digest().hash,
if has_already_stripped_any {
"sub"
} else {
"root "
},
if has_already_stripped_any {
format!(" {}", already_stripped.display())
} else {
String::new()
},
Path::new(component_to_strip).display(),
if!extra_directories.is_empty() ||!files.is_empty() {
format!(
" but did contain {}",
format_directories_and_files(&extra_directories, &files)
)
} else {
String::new()
},
));
}
(Some(_), false) => {
return Err(format!(
"Cannot strip prefix {} from root directory (Digest with hash {:?}) - \
{}directory{} contained non-matching {}",
prefix.display(),
root.compute_root_digest().hash,
if has_already_stripped_any {
"sub"
} else {
"root "
},
if has_already_stripped_any {
format!(" {}", already_stripped.display())
} else {
String::new()
},
format_directories_and_files(&extra_directories, &files),
))
}
(Some(d), true) => {
already_stripped = already_stripped.join(component_to_strip);
tree = d.tree.clone();
}
}
}
Ok(tree)
}
/// Given DigestTries, merge them recursively into a single DigestTrie.
///
/// If a file is present with the same name and contents multiple times, it will appear once.
/// If a file is present with the same name, but different contents, an error will be returned.
pub fn merge(trees: Vec<DigestTrie>) -> Result<DigestTrie, MergeError> {
Self::merge_helper(PathBuf::new(), trees)
}
fn merge_helper(parent_path: PathBuf, trees: Vec<DigestTrie>) -> Result<DigestTrie, MergeError> {
if trees.is_empty() {
return Ok(EMPTY_DIGEST_TREE.clone());
} else if trees.len() == 1 {
let mut trees = trees;
return Ok(trees.pop().unwrap());
}
// Merge and sort Entries.
let input_entries = trees
.iter()
.map(|tree| tree.entries())
.flatten()
.sorted_by(|a, b| a.name().cmp(&b.name()));
// Then group by name, and merge into an output list.
let mut entries: Vec<Entry> = Vec::new();
for (name, group) in &input_entries.into_iter().group_by(|e| e.name()) {
let mut group = group.peekable();
let first = group.next().unwrap();
if group.peek().is_none() {
// There was only one Entry: emit it.
entries.push(first.clone());
continue;
}
match first {
Entry::File(f) => {
// If any Entry is a File, then they must all be identical.
let (mut mismatched_files, mismatched_dirs) = collisions(f.digest, group);
if!mismatched_files.is_empty() ||!mismatched_dirs.is_empty() {
mismatched_files.push(f);
return Err(MergeError::duplicates(
parent_path,
mismatched_files,
mismatched_dirs,
));
}
// All entries matched: emit one copy.
entries.push(first.clone());
}
Entry::Directory(d) => {
// If any Entry is a Directory, then they must all be Directories which will be merged.
let (mismatched_files, mut mismatched_dirs) = collisions(d.digest, group);
// If there were any Files, error.
if!mismatched_files.is_empty() {
mismatched_dirs.push(d);
return Err(MergeError::duplicates(
parent_path,
mismatched_files,
mismatched_dirs,
));
}
if mismatched_dirs.is_empty() {
// All directories matched: emit one copy.
entries.push(first.clone());
} else {
// Some directories mismatched, so merge all of them into a new entry and emit that.
mismatched_dirs.push(d);
let merged_tree = Self::merge_helper(
parent_path.join(name.as_ref()),
mismatched_dirs
.into_iter()
.map(|d| d.tree.clone())
.collect(),
)?;
entries.push(Entry::Directory(Directory::from_digest_tree(
name,
merged_tree,
)));
}
}
}
}
Ok(DigestTrie(entries.into()))
}
}
pub enum MergeError {
Duplicates {
parent_path: PathBuf,
files: Vec<File>,
directories: Vec<Directory>,
},
}
impl MergeError {
fn duplicates(parent_path: PathBuf, files: Vec<&File>, directories: Vec<&Directory>) -> Self {
MergeError::Duplicates {
parent_path,
files: files.into_iter().cloned().collect(),
directories: directories.into_iter().cloned().collect(),
}
}
}
fn paths_of_child_dir(name: Name, paths: Vec<TypedPath>) -> Vec<TypedPath> {
paths
.into_iter()
.filter_map(|s| {
if s.components().count() == 1 {
return None;
}
Some(match s {
TypedPath::File {
path,
is_executable,
} => TypedPath::File {
path: path.strip_prefix(name.as_ref()).unwrap(),
is_executable,
},
TypedPath::Dir(path) => TypedPath::Dir(path.strip_prefix(name.as_ref()).unwrap()),
})
})
.collect()
}
fn first_path_component_to_name | {
if cfg!(debug_assertions) {
assert!(digest == tree.compute_root_digest());
}
Self {
digest,
tree: Some(tree),
}
} | identifier_body |
directory.rs |
/// A Digest for a directory, optionally with its content stored as a DigestTrie.
///
/// If a DirectoryDigest has a DigestTrie reference, then its Digest _might not_ be persisted to
/// the Store. If the DirectoryDigest does not hold a DigestTrie, then that Digest _must_ have been
/// persisted to the Store (either locally or remotely). The field thus acts likes a cache in some
/// cases, but in other cases is an indication that the tree must first be persisted (or loaded)
/// before the Digest may be operated on.
#[derive(Clone, DeepSizeOf)]
pub struct DirectoryDigest {
// NB: Private in order to force a choice between `todo_as_digest` and `as_digest`.
digest: Digest,
pub tree: Option<DigestTrie>,
}
impl workunit_store::DirectoryDigest for DirectoryDigest {
fn as_any(&self) -> &dyn std::any::Any {
self
}
}
impl Eq for DirectoryDigest {}
impl PartialEq for DirectoryDigest {
fn eq(&self, other: &Self) -> bool {
self.digest == other.digest
}
}
impl Hash for DirectoryDigest {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.digest.hash(state);
}
}
impl Debug for DirectoryDigest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// NB: To avoid over-large output, we don't render the Trie. It would likely be best rendered
// as e.g. JSON.
let tree = if self.tree.is_some() {
"Some(..)"
} else {
"None"
};
write!(f, "DirectoryDigest({:?}, tree: {})", self.digest, tree)
}
}
impl DirectoryDigest {
/// Construct a DirectoryDigest from a Digest and DigestTrie (by asserting that the Digest
/// identifies the DigestTrie).
pub fn new(digest: Digest, tree: DigestTrie) -> Self {
if cfg!(debug_assertions) {
assert!(digest == tree.compute_root_digest());
}
Self {
digest,
tree: Some(tree),
}
}
/// Creates a DirectoryDigest which asserts that the given Digest represents a Directory structure
/// which is persisted in a Store.
///
/// Use of this method should be rare: code should prefer to pass around a `DirectoryDigest` rather
/// than to create one from a `Digest` (as the latter requires loading the content from disk).
///
/// TODO: If a callsite needs to create a `DirectoryDigest` as a convenience (i.e. in a location
/// where its signature could be changed to accept a `DirectoryDigest` instead of constructing
/// one) during the porting effort of #13112, it should use `todo_from_digest` rather than
/// `from_persisted_digest`.
pub fn from_persisted_digest(digest: Digest) -> Self {
Self { digest, tree: None }
}
/// Marks a callsite that is creating a `DirectoryDigest` as a temporary convenience, rather than
/// accepting a `DirectoryDigest` in its signature. All usages of this method should be removed
/// before closing #13112.
pub fn todo_from_digest(digest: Digest) -> Self {
Self { digest, tree: None }
}
pub fn from_tree(tree: DigestTrie) -> Self {
Self {
digest: tree.compute_root_digest(),
tree: Some(tree),
}
}
/// Returns the `Digest` for this `DirectoryDigest`.
///
/// TODO: If a callsite needs to convert to `Digest` as a convenience (i.e. in a location where
/// its signature could be changed to return a `DirectoryDigest` instead) during the porting
/// effort of #13112, it should use `todo_as_digest` rather than `as_digest`.
pub fn as_digest(&self) -> Digest {
self.digest
}
/// Marks a callsite that is discarding the `DigestTrie` held by this `DirectoryDigest` as a
/// temporary convenience, rather than updating its signature to return a `DirectoryDigest`. All
/// usages of this method should be removed before closing #13112.
pub fn todo_as_digest(self) -> Digest {
self.digest
}
/// Returns the digests reachable from this DirectoryDigest.
///
/// If this DirectoryDigest has been persisted to disk (i.e., does not have a DigestTrie) then
/// this will only include the root.
pub fn digests(&self) -> Vec<Digest> {
if let Some(tree) = &self.tree {
let mut digests = tree.digests();
digests.push(self.digest);
digests
} else {
vec![self.digest]
}
}
}
/// A single component of a filesystem path.
///
/// For example: the path `foo/bar` will be broken up into `Name("foo")` and `Name("bar")`.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Name(Intern<String>);
// NB: Calculating the actual deep size of an `Intern` is very challenging, because it does not
// keep any record of the number of held references, and instead effectively makes its held value
// static. Switching to `ArcIntern` would get accurate counts at the cost of performance and size.
known_deep_size!(0; Name);
impl Deref for Name {
type Target = Intern<String>;
fn deref(&self) -> &Intern<String> {
&self.0
}
}
#[derive(Clone, DeepSizeOf)]
pub enum Entry {
Directory(Directory),
File(File),
}
impl Entry {
fn name(&self) -> Name {
match self {
Entry::Directory(d) => d.name,
Entry::File(f) => f.name,
}
}
}
#[derive(Clone, DeepSizeOf)]
pub struct Directory {
name: Name,
digest: Digest,
tree: DigestTrie,
}
impl Directory {
fn new(name: Name, entries: Vec<Entry>) -> Self {
Self::from_digest_tree(name, DigestTrie(entries.into()))
}
fn from_digest_tree(name: Name, tree: DigestTrie) -> Self {
Self {
name,
digest: tree.compute_root_digest(),
tree,
}
}
pub fn name(&self) -> &str {
self.name.as_ref()
}
pub fn digest(&self) -> Digest {
self.digest
}
pub fn tree(&self) -> &DigestTrie {
&self.tree
}
pub fn as_remexec_directory(&self) -> remexec::Directory {
self.tree.as_remexec_directory()
}
pub fn as_remexec_directory_node(&self) -> remexec::DirectoryNode {
remexec::DirectoryNode {
name: self.name.as_ref().to_owned(),
digest: Some((&self.digest).into()),
}
}
}
#[derive(Clone, DeepSizeOf)]
pub struct File {
name: Name,
digest: Digest,
is_executable: bool,
}
impl File {
pub fn name(&self) -> &str {
self.name.as_ref()
}
pub fn digest(&self) -> Digest {
self.digest
}
pub fn is_executable(&self) -> bool {
self.is_executable
}
pub fn as_remexec_file_node(&self) -> remexec::FileNode {
remexec::FileNode {
name: self.name.as_ref().to_owned(),
digest: Some(self.digest.into()),
is_executable: self.is_executable,
..remexec::FileNode::default()
}
}
}
// TODO: `PathStat` owns its path, which means it can't be used via recursive slicing. See
// whether these types can be merged.
enum TypedPath<'a> {
File { path: &'a Path, is_executable: bool },
Dir(&'a Path),
}
impl<'a> Deref for TypedPath<'a> {
type Target = Path;
fn | (&self) -> &Path {
match self {
TypedPath::File { path,.. } => path,
TypedPath::Dir(d) => d,
}
}
}
impl<'a> From<&'a PathStat> for TypedPath<'a> {
fn from(p: &'a PathStat) -> Self {
match p {
PathStat::File { path, stat } => TypedPath::File {
path,
is_executable: stat.is_executable,
},
PathStat::Dir { path,.. } => TypedPath::Dir(path),
}
}
}
#[derive(Clone, DeepSizeOf)]
pub struct DigestTrie(Arc<[Entry]>);
// TODO: This avoids a `rustc` crasher (repro on 7f319ee84ad41bc0aea3cb01fb2f32dcd51be704).
unsafe impl Sync for DigestTrie {}
impl DigestTrie {
/// Create a DigestTrie from unique PathStats. Fails for duplicate items.
pub fn from_path_stats(
mut path_stats: Vec<PathStat>,
file_digests: &HashMap<PathBuf, Digest>,
) -> Result<Self, String> {
// Sort and ensure that there were no duplicate entries.
//#[allow(clippy::unnecessary_sort_by)]
path_stats.sort_by(|a, b| a.path().cmp(b.path()));
// The helper assumes that if a Path has multiple children, it must be a directory.
// Proactively error if we run into identically named files, because otherwise we will treat
// them like empty directories.
let pre_dedupe_len = path_stats.len();
path_stats.dedup_by(|a, b| a.path() == b.path());
if path_stats.len()!= pre_dedupe_len {
return Err(format!(
"Snapshots must be constructed from unique path stats; got duplicates in {:?}",
path_stats
));
}
Self::from_sorted_paths(
PathBuf::new(),
path_stats.iter().map(|p| p.into()).collect(),
file_digests,
)
}
fn from_sorted_paths(
prefix: PathBuf,
paths: Vec<TypedPath>,
file_digests: &HashMap<PathBuf, Digest>,
) -> Result<Self, String> {
let mut entries = Vec::new();
for (name_res, group) in &paths
.into_iter()
.group_by(|s| first_path_component_to_name(s))
{
let name = name_res?;
let mut path_group: Vec<TypedPath> = group.collect();
if path_group.len() == 1 && path_group[0].components().count() == 1 {
// Exactly one entry with exactly one component indicates either a file in this directory,
// or an empty directory.
// If the child is a non-empty directory, or a file therein, there must be multiple
// PathStats with that prefix component, and we will handle that recursively.
match path_group.pop().unwrap() {
TypedPath::File {
path,
is_executable,
} => {
let digest = *file_digests.get(prefix.join(path).as_path()).unwrap();
entries.push(Entry::File(File {
name,
digest,
is_executable,
}));
}
TypedPath::Dir {.. } => {
// Because there are no children of this Dir, it must be empty.
entries.push(Entry::Directory(Directory::new(name, vec![])));
}
}
} else {
// Because there are no children of this Dir, it must be empty.
entries.push(Entry::Directory(Directory::from_digest_tree(
name,
Self::from_sorted_paths(
prefix.join(name.as_ref()),
paths_of_child_dir(name, path_group),
file_digests,
)?,
)));
}
}
Ok(Self(entries.into()))
}
pub fn as_remexec_directory(&self) -> remexec::Directory {
let mut files = Vec::new();
let mut directories = Vec::new();
for entry in &*self.0 {
match entry {
Entry::File(f) => files.push(f.as_remexec_file_node()),
Entry::Directory(d) => directories.push(d.as_remexec_directory_node()),
}
}
remexec::Directory {
directories,
files,
..remexec::Directory::default()
}
}
pub fn compute_root_digest(&self) -> Digest {
if self.0.is_empty() {
return EMPTY_DIGEST;
}
Digest::of_bytes(&self.as_remexec_directory().to_bytes())
}
pub fn entries(&self) -> &[Entry] {
&*self.0
}
/// Returns the digests reachable from this DigestTrie.
pub fn digests(&self) -> Vec<Digest> {
// Walk the tree and collect Digests.
let mut digests = Vec::new();
let mut stack = self.0.iter().collect::<Vec<_>>();
while let Some(entry) = stack.pop() {
match entry {
Entry::Directory(d) => {
digests.push(d.digest);
stack.extend(d.tree.0.iter());
}
Entry::File(f) => {
digests.push(f.digest);
}
}
}
digests
}
/// Return a pair of Vecs of the file paths and directory paths in this DigestTrie, each in
/// sorted order.
///
/// TODO: This should probably be implemented directly by consumers via `walk`, since they
/// can directly allocate the collections that they need.
pub fn files_and_directories(&self) -> (Vec<PathBuf>, Vec<PathBuf>) {
let mut files = Vec::new();
let mut directories = Vec::new();
self.walk(&mut |path, entry| {
match entry {
Entry::File(_) => files.push(path.to_owned()),
Entry::Directory(d) if d.name.is_empty() => {
// Is the root directory, which is not emitted here.
}
Entry::Directory(_) => directories.push(path.to_owned()),
}
});
(files, directories)
}
/// Visit every node in the tree, calling the given function with the path to the Node, and its
/// entries.
pub fn walk(&self, f: &mut impl FnMut(&Path, &Entry)) {
{
// TODO: It's likely that a DigestTrie should hold its own Digest, to avoid re-computing it
// here.
let root = Entry::Directory(Directory::from_digest_tree(
Name(Intern::from("")),
self.clone(),
));
f(&PathBuf::new(), &root);
}
self.walk_helper(PathBuf::new(), f)
}
fn walk_helper(&self, path_so_far: PathBuf, f: &mut impl FnMut(&Path, &Entry)) {
for entry in &*self.0 {
let path = path_so_far.join(entry.name().as_ref());
f(&path, entry);
if let Entry::Directory(d) = entry {
d.tree.walk_helper(path, f);
}
}
}
/// Add the given path as a prefix for this trie, returning the resulting trie.
pub fn add_prefix(self, prefix: &RelativePath) -> Result<DigestTrie, String> {
let mut prefix_iter = prefix.iter();
let mut tree = self;
while let Some(parent) = prefix_iter.next_back() {
let directory = Directory {
name: first_path_component_to_name(parent.as_ref())?,
digest: tree.compute_root_digest(),
tree,
};
tree = DigestTrie(vec![Entry::Directory(directory)].into());
}
Ok(tree)
}
/// Remove the given prefix from this trie, returning the resulting trie.
pub fn remove_prefix(self, prefix: &RelativePath) -> Result<DigestTrie, String> {
let root = self.clone();
let mut tree = self;
let mut already_stripped = PathBuf::new();
for component_to_strip in prefix.components() {
let component_to_strip = component_to_strip.as_os_str();
let mut matching_dir = None;
let mut extra_directories = Vec::new();
let mut files = Vec::new();
for entry in tree.entries() {
match entry {
Entry::Directory(d) if Path::new(d.name.as_ref()).as_os_str() == component_to_strip => {
matching_dir = Some(d)
}
Entry::Directory(d) => extra_directories.push(d.name.as_ref().to_owned()),
Entry::File(f) => files.push(f.name.as_ref().to_owned()),
}
}
let has_already_stripped_any = already_stripped.components().next().is_some();
match (
matching_dir,
extra_directories.is_empty() && files.is_empty(),
) {
(None, true) => {
tree = EMPTY_DIGEST_TREE.clone();
break;
}
(None, false) => {
// Prefer "No subdirectory found" error to "had extra files" error.
return Err(format!(
"Cannot strip prefix {} from root directory (Digest with hash {:?}) - \
{}directory{} didn't contain a directory named {}{}",
prefix.display(),
root.compute_root_digest().hash,
if has_already_stripped_any {
"sub"
} else {
"root "
},
if has_already_stripped_any {
format!(" {}", already_stripped.display())
} else {
String::new()
},
Path::new(component_to_strip).display(),
if!extra_directories.is_empty() ||!files.is_empty() {
format!(
" but did contain {}",
format_directories_and_files(&extra_directories, &files)
)
} else {
String::new()
},
));
}
(Some(_), false) => {
return Err(format!(
"Cannot strip prefix {} from root directory (Digest with hash {:?}) - \
{}directory{} contained non-matching {}",
prefix.display(),
root.compute_root_digest().hash,
if has_already_stripped_any {
"sub"
} else {
"root "
},
if has_already_stripped_any {
format!(" {}", already_stripped.display())
} else {
String::new()
},
format_directories_and_files(&extra_directories, &files),
))
}
(Some(d), true) => {
already_stripped = already_stripped.join(component_to_strip);
tree = d.tree.clone();
}
}
}
Ok(tree)
}
/// Given DigestTries, merge them recursively into a single DigestTrie.
///
/// If a file is present with the same name and contents multiple times, it will appear once.
/// If a file is present with the same name, but different contents, an error will be returned.
pub fn merge(trees: Vec<DigestTrie>) -> Result<DigestTrie, MergeError> {
Self::merge_helper(PathBuf::new(), trees)
}
fn merge_helper(parent_path: PathBuf, trees: Vec<DigestTrie>) -> Result<DigestTrie, MergeError> {
if trees.is_empty() {
return Ok(EMPTY_DIGEST_TREE.clone());
} else if trees.len() == 1 {
let mut trees = trees;
return Ok(trees.pop().unwrap());
}
// Merge and sort Entries.
let input_entries = trees
.iter()
.map(|tree| tree.entries())
.flatten()
.sorted_by(|a, b| a.name().cmp(&b.name()));
// Then group by name, and merge into an output list.
let mut entries: Vec<Entry> = Vec::new();
for (name, group) in &input_entries.into_iter().group_by(|e| e.name()) {
let mut group = group.peekable();
let first = group.next().unwrap();
if group.peek().is_none() {
// There was only one Entry: emit it.
entries.push(first.clone());
continue;
}
match first {
Entry::File(f) => {
// If any Entry is a File, then they must all be identical.
let (mut mismatched_files, mismatched_dirs) = collisions(f.digest, group);
if!mismatched_files.is_empty() ||!mismatched_dirs.is_empty() {
mismatched_files.push(f);
return Err(MergeError::duplicates(
parent_path,
mismatched_files,
mismatched_dirs,
));
}
// All entries matched: emit one copy.
entries.push(first.clone());
}
Entry::Directory(d) => {
// If any Entry is a Directory, then they must all be Directories which will be merged.
let (mismatched_files, mut mismatched_dirs) = collisions(d.digest, group);
// If there were any Files, error.
if!mismatched_files.is_empty() {
mismatched_dirs.push(d);
return Err(MergeError::duplicates(
parent_path,
mismatched_files,
mismatched_dirs,
));
}
if mismatched_dirs.is_empty() {
// All directories matched: emit one copy.
entries.push(first.clone());
} else {
// Some directories mismatched, so merge all of them into a new entry and emit that.
mismatched_dirs.push(d);
let merged_tree = Self::merge_helper(
parent_path.join(name.as_ref()),
mismatched_dirs
.into_iter()
.map(|d| d.tree.clone())
.collect(),
)?;
entries.push(Entry::Directory(Directory::from_digest_tree(
name,
merged_tree,
)));
}
}
}
}
Ok(DigestTrie(entries.into()))
}
}
pub enum MergeError {
Duplicates {
parent_path: PathBuf,
files: Vec<File>,
directories: Vec<Directory>,
},
}
impl MergeError {
fn duplicates(parent_path: PathBuf, files: Vec<&File>, directories: Vec<&Directory>) -> Self {
MergeError::Duplicates {
parent_path,
files: files.into_iter().cloned().collect(),
directories: directories.into_iter().cloned().collect(),
}
}
}
fn paths_of_child_dir(name: Name, paths: Vec<TypedPath>) -> Vec<TypedPath> {
paths
.into_iter()
.filter_map(|s| {
if s.components().count() == 1 {
return None;
}
Some(match s {
TypedPath::File {
path,
is_executable,
} => TypedPath::File {
path: path.strip_prefix(name.as_ref()).unwrap(),
is_executable,
},
TypedPath::Dir(path) => TypedPath::Dir(path.strip_prefix(name.as_ref()).unwrap()),
})
})
.collect()
}
fn first_path_component_to_name | deref | identifier_name |
stack.rs | //! Algorithm 1.2: Pushdown stack.
struct Node<T> {
value: T,
next: Option<Box<Node<T>>>,
}
impl<T> Node<T> {
fn new(value: T, next: Option<Box<Node<T>>>) -> Node<T> {
Node { value: value, next: next }
}
}
pub struct Stack<T> {
first: Option<Box<Node<T>>>,
n: usize,
}
/// A stack implementation based on a linked list.
impl <T> Stack<T> {
/// Constructs a new, empty stack.
pub fn new() -> Stack<T> {
Stack { first: None, n: 0 }
}
/// Returns `true` if the stack is empty.
pub fn is_empty(&self) -> bool {
self.n == 0
}
/// Returns the number of elements in the stack.
pub fn size(&self) -> usize {
self.n
}
/// Adds an element to the stack.
pub fn push(&mut self, value: T) {
self.first = Some(Box::new(Node::new(value, self.first.take())));
self.n += 1;
}
/// Removes an element from the stack and returns it.
pub fn pop(&mut self) -> Option<T> {
self.first.take().map(|mut node| {
self.first = node.next.take();
self.n -= 1;
node.value
})
}
}
#[cfg(test)]
mod tests {
use super::Stack;
#[test]
fn empty_stack() {
let mut s: Stack<isize> = Stack::new();
assert!(s.is_empty());
assert_eq!(s.size(), 0);
assert_eq!(s.pop(), None);
}
#[test]
fn single_element() {
let mut s = Stack::new();
s.push("hello");
assert!(! s.is_empty());
assert_eq!(s.size(), 1);
assert_eq!(s.pop(), Some("hello"));
assert!(s.is_empty());
assert_eq!(s.size(), 0);
assert_eq!(s.pop(), None);
}
#[test]
fn ten_elements() {
let mut s = Stack::new();
for i in 0..10 {
s.push(i);
}
for i in 0..10 {
assert_eq!(s.pop(), Some(9 - i)); | }
assert_eq!(s.pop(), None);
}
} | random_line_split |
|
stack.rs | //! Algorithm 1.2: Pushdown stack.
struct Node<T> {
value: T,
next: Option<Box<Node<T>>>,
}
impl<T> Node<T> {
fn | (value: T, next: Option<Box<Node<T>>>) -> Node<T> {
Node { value: value, next: next }
}
}
pub struct Stack<T> {
first: Option<Box<Node<T>>>,
n: usize,
}
/// A stack implementation based on a linked list.
impl <T> Stack<T> {
/// Constructs a new, empty stack.
pub fn new() -> Stack<T> {
Stack { first: None, n: 0 }
}
/// Returns `true` if the stack is empty.
pub fn is_empty(&self) -> bool {
self.n == 0
}
/// Returns the number of elements in the stack.
pub fn size(&self) -> usize {
self.n
}
/// Adds an element to the stack.
pub fn push(&mut self, value: T) {
self.first = Some(Box::new(Node::new(value, self.first.take())));
self.n += 1;
}
/// Removes an element from the stack and returns it.
pub fn pop(&mut self) -> Option<T> {
self.first.take().map(|mut node| {
self.first = node.next.take();
self.n -= 1;
node.value
})
}
}
#[cfg(test)]
mod tests {
use super::Stack;
#[test]
fn empty_stack() {
let mut s: Stack<isize> = Stack::new();
assert!(s.is_empty());
assert_eq!(s.size(), 0);
assert_eq!(s.pop(), None);
}
#[test]
fn single_element() {
let mut s = Stack::new();
s.push("hello");
assert!(! s.is_empty());
assert_eq!(s.size(), 1);
assert_eq!(s.pop(), Some("hello"));
assert!(s.is_empty());
assert_eq!(s.size(), 0);
assert_eq!(s.pop(), None);
}
#[test]
fn ten_elements() {
let mut s = Stack::new();
for i in 0..10 {
s.push(i);
}
for i in 0..10 {
assert_eq!(s.pop(), Some(9 - i));
}
assert_eq!(s.pop(), None);
}
}
| new | identifier_name |
stack.rs | //! Algorithm 1.2: Pushdown stack.
struct Node<T> {
value: T,
next: Option<Box<Node<T>>>,
}
impl<T> Node<T> {
fn new(value: T, next: Option<Box<Node<T>>>) -> Node<T> {
Node { value: value, next: next }
}
}
pub struct Stack<T> {
first: Option<Box<Node<T>>>,
n: usize,
}
/// A stack implementation based on a linked list.
impl <T> Stack<T> {
/// Constructs a new, empty stack.
pub fn new() -> Stack<T> {
Stack { first: None, n: 0 }
}
/// Returns `true` if the stack is empty.
pub fn is_empty(&self) -> bool {
self.n == 0
}
/// Returns the number of elements in the stack.
pub fn size(&self) -> usize {
self.n
}
/// Adds an element to the stack.
pub fn push(&mut self, value: T) {
self.first = Some(Box::new(Node::new(value, self.first.take())));
self.n += 1;
}
/// Removes an element from the stack and returns it.
pub fn pop(&mut self) -> Option<T> {
self.first.take().map(|mut node| {
self.first = node.next.take();
self.n -= 1;
node.value
})
}
}
#[cfg(test)]
mod tests {
use super::Stack;
#[test]
fn empty_stack() {
let mut s: Stack<isize> = Stack::new();
assert!(s.is_empty());
assert_eq!(s.size(), 0);
assert_eq!(s.pop(), None);
}
#[test]
fn single_element() {
let mut s = Stack::new();
s.push("hello");
assert!(! s.is_empty());
assert_eq!(s.size(), 1);
assert_eq!(s.pop(), Some("hello"));
assert!(s.is_empty());
assert_eq!(s.size(), 0);
assert_eq!(s.pop(), None);
}
#[test]
fn ten_elements() |
}
| {
let mut s = Stack::new();
for i in 0..10 {
s.push(i);
}
for i in 0..10 {
assert_eq!(s.pop(), Some(9 - i));
}
assert_eq!(s.pop(), None);
} | identifier_body |
kqueue.rs | use {io, EventSet, PollOpt, Token};
use event::IoEvent;
use nix::sys::event::{EventFilter, EventFlag, FilterFlag, KEvent, kqueue, kevent};
use nix::sys::event::{EV_ADD, EV_CLEAR, EV_DELETE, EV_DISABLE, EV_ENABLE, EV_EOF, EV_ERROR, EV_ONESHOT};
use std::{fmt, slice};
use std::os::unix::io::RawFd;
use std::collections::HashMap;
#[derive(Debug)]
pub struct Selector {
kq: RawFd,
changes: Events
}
impl Selector {
pub fn new() -> io::Result<Selector> {
Ok(Selector {
kq: try!(kqueue().map_err(super::from_nix_error)),
changes: Events::new()
})
}
pub fn select(&mut self, evts: &mut Events, timeout_ms: usize) -> io::Result<()> {
let cnt = try!(kevent(self.kq, &[], evts.as_mut_slice(), timeout_ms)
.map_err(super::from_nix_error));
self.changes.sys_events.clear();
unsafe {
evts.sys_events.set_len(cnt);
}
evts.coalesce();
Ok(())
}
pub fn register(&mut self, fd: RawFd, token: Token, interests: EventSet, opts: PollOpt) -> io::Result<()> {
trace!("registering; token={:?}; interests={:?}", token, interests);
self.ev_register(fd, token.as_usize(), EventFilter::EVFILT_READ, interests.contains(EventSet::readable()), opts);
self.ev_register(fd, token.as_usize(), EventFilter::EVFILT_WRITE, interests.contains(EventSet::writable()), opts);
self.flush_changes()
}
pub fn reregister(&mut self, fd: RawFd, token: Token, interests: EventSet, opts: PollOpt) -> io::Result<()> {
// Just need to call register here since EV_ADD is a mod if already
// registered
self.register(fd, token, interests, opts)
}
pub fn deregister(&mut self, fd: RawFd) -> io::Result<()> {
self.ev_push(fd, 0, EventFilter::EVFILT_READ, EV_DELETE);
self.ev_push(fd, 0, EventFilter::EVFILT_WRITE, EV_DELETE);
self.flush_changes()
}
fn ev_register(&mut self, fd: RawFd, token: usize, filter: EventFilter, enable: bool, opts: PollOpt) {
let mut flags = EV_ADD;
if enable {
flags = flags | EV_ENABLE;
} else {
flags = flags | EV_DISABLE;
}
if opts.contains(PollOpt::edge()) {
flags = flags | EV_CLEAR;
}
if opts.contains(PollOpt::oneshot()) {
flags = flags | EV_ONESHOT;
}
self.ev_push(fd, token, filter, flags);
}
fn ev_push(&mut self, fd: RawFd, token: usize, filter: EventFilter, flags: EventFlag) {
self.changes.sys_events.push(
KEvent {
ident: fd as ::libc::uintptr_t,
filter: filter,
flags: flags,
fflags: FilterFlag::empty(),
data: 0,
udata: token
});
}
fn flush_changes(&mut self) -> io::Result<()> {
let result = kevent(self.kq, self.changes.as_slice(), &mut [], 0).map(|_| ())
.map_err(super::from_nix_error).map(|_| ());
self.changes.sys_events.clear();
result
}
}
pub struct Events {
sys_events: Vec<KEvent>,
events: Vec<IoEvent>,
event_map: HashMap<Token, usize>,
}
impl Events {
pub fn new() -> Events {
Events {
sys_events: Vec::with_capacity(1024),
events: Vec::with_capacity(1024),
event_map: HashMap::with_capacity(1024)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
pub fn get(&self, idx: usize) -> IoEvent {
self.events[idx]
}
pub fn | (&mut self) {
self.events.clear();
self.event_map.clear();
for e in self.sys_events.iter() {
let token = Token(e.udata as usize);
let len = self.events.len();
let idx = *self.event_map.entry(token)
.or_insert(len);
if idx == len {
// New entry, insert the default
self.events.push(IoEvent::new(EventSet::none(), token));
}
if e.flags.contains(EV_ERROR) {
self.events[idx].kind.insert(EventSet::error());
}
if e.filter == EventFilter::EVFILT_READ {
self.events[idx].kind.insert(EventSet::readable());
} else if e.filter == EventFilter::EVFILT_WRITE {
self.events[idx].kind.insert(EventSet::writable());
}
if e.flags.contains(EV_EOF) {
self.events[idx].kind.insert(EventSet::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if!e.fflags.is_empty() {
self.events[idx].kind.insert(EventSet::error());
}
}
}
}
fn as_slice(&self) -> &[KEvent] {
unsafe {
let ptr = (&self.sys_events[..]).as_ptr();
slice::from_raw_parts(ptr, self.sys_events.len())
}
}
fn as_mut_slice(&mut self) -> &mut [KEvent] {
unsafe {
let ptr = (&mut self.sys_events[..]).as_mut_ptr();
slice::from_raw_parts_mut(ptr, self.sys_events.capacity())
}
}
}
impl fmt::Debug for Events {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Events {{ len: {} }}", self.sys_events.len())
}
}
| coalesce | identifier_name |
kqueue.rs | use {io, EventSet, PollOpt, Token};
use event::IoEvent;
use nix::sys::event::{EventFilter, EventFlag, FilterFlag, KEvent, kqueue, kevent};
use nix::sys::event::{EV_ADD, EV_CLEAR, EV_DELETE, EV_DISABLE, EV_ENABLE, EV_EOF, EV_ERROR, EV_ONESHOT};
use std::{fmt, slice};
use std::os::unix::io::RawFd;
use std::collections::HashMap;
#[derive(Debug)]
pub struct Selector {
kq: RawFd,
changes: Events
}
impl Selector {
pub fn new() -> io::Result<Selector> {
Ok(Selector {
kq: try!(kqueue().map_err(super::from_nix_error)),
changes: Events::new()
})
}
pub fn select(&mut self, evts: &mut Events, timeout_ms: usize) -> io::Result<()> {
let cnt = try!(kevent(self.kq, &[], evts.as_mut_slice(), timeout_ms)
.map_err(super::from_nix_error));
self.changes.sys_events.clear();
unsafe {
evts.sys_events.set_len(cnt);
}
evts.coalesce();
Ok(())
}
pub fn register(&mut self, fd: RawFd, token: Token, interests: EventSet, opts: PollOpt) -> io::Result<()> {
trace!("registering; token={:?}; interests={:?}", token, interests);
self.ev_register(fd, token.as_usize(), EventFilter::EVFILT_READ, interests.contains(EventSet::readable()), opts);
self.ev_register(fd, token.as_usize(), EventFilter::EVFILT_WRITE, interests.contains(EventSet::writable()), opts);
self.flush_changes()
}
pub fn reregister(&mut self, fd: RawFd, token: Token, interests: EventSet, opts: PollOpt) -> io::Result<()> {
// Just need to call register here since EV_ADD is a mod if already
// registered
self.register(fd, token, interests, opts)
}
pub fn deregister(&mut self, fd: RawFd) -> io::Result<()> {
self.ev_push(fd, 0, EventFilter::EVFILT_READ, EV_DELETE);
self.ev_push(fd, 0, EventFilter::EVFILT_WRITE, EV_DELETE);
self.flush_changes()
}
fn ev_register(&mut self, fd: RawFd, token: usize, filter: EventFilter, enable: bool, opts: PollOpt) {
let mut flags = EV_ADD;
if enable {
flags = flags | EV_ENABLE;
} else {
flags = flags | EV_DISABLE;
}
if opts.contains(PollOpt::edge()) {
flags = flags | EV_CLEAR;
}
if opts.contains(PollOpt::oneshot()) {
flags = flags | EV_ONESHOT;
}
self.ev_push(fd, token, filter, flags);
}
fn ev_push(&mut self, fd: RawFd, token: usize, filter: EventFilter, flags: EventFlag) {
self.changes.sys_events.push(
KEvent {
ident: fd as ::libc::uintptr_t,
filter: filter,
flags: flags,
fflags: FilterFlag::empty(),
data: 0,
udata: token
});
}
fn flush_changes(&mut self) -> io::Result<()> {
let result = kevent(self.kq, self.changes.as_slice(), &mut [], 0).map(|_| ())
.map_err(super::from_nix_error).map(|_| ());
self.changes.sys_events.clear();
result
}
}
pub struct Events {
sys_events: Vec<KEvent>,
events: Vec<IoEvent>,
event_map: HashMap<Token, usize>,
}
impl Events {
pub fn new() -> Events {
Events {
sys_events: Vec::with_capacity(1024),
events: Vec::with_capacity(1024),
event_map: HashMap::with_capacity(1024)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
pub fn get(&self, idx: usize) -> IoEvent |
pub fn coalesce(&mut self) {
self.events.clear();
self.event_map.clear();
for e in self.sys_events.iter() {
let token = Token(e.udata as usize);
let len = self.events.len();
let idx = *self.event_map.entry(token)
.or_insert(len);
if idx == len {
// New entry, insert the default
self.events.push(IoEvent::new(EventSet::none(), token));
}
if e.flags.contains(EV_ERROR) {
self.events[idx].kind.insert(EventSet::error());
}
if e.filter == EventFilter::EVFILT_READ {
self.events[idx].kind.insert(EventSet::readable());
} else if e.filter == EventFilter::EVFILT_WRITE {
self.events[idx].kind.insert(EventSet::writable());
}
if e.flags.contains(EV_EOF) {
self.events[idx].kind.insert(EventSet::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if!e.fflags.is_empty() {
self.events[idx].kind.insert(EventSet::error());
}
}
}
}
fn as_slice(&self) -> &[KEvent] {
unsafe {
let ptr = (&self.sys_events[..]).as_ptr();
slice::from_raw_parts(ptr, self.sys_events.len())
}
}
fn as_mut_slice(&mut self) -> &mut [KEvent] {
unsafe {
let ptr = (&mut self.sys_events[..]).as_mut_ptr();
slice::from_raw_parts_mut(ptr, self.sys_events.capacity())
}
}
}
impl fmt::Debug for Events {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Events {{ len: {} }}", self.sys_events.len())
}
}
| {
self.events[idx]
} | identifier_body |
kqueue.rs | use {io, EventSet, PollOpt, Token};
use event::IoEvent;
use nix::sys::event::{EventFilter, EventFlag, FilterFlag, KEvent, kqueue, kevent};
use nix::sys::event::{EV_ADD, EV_CLEAR, EV_DELETE, EV_DISABLE, EV_ENABLE, EV_EOF, EV_ERROR, EV_ONESHOT};
use std::{fmt, slice};
use std::os::unix::io::RawFd;
use std::collections::HashMap;
#[derive(Debug)]
pub struct Selector {
kq: RawFd,
changes: Events
}
impl Selector {
pub fn new() -> io::Result<Selector> {
Ok(Selector { |
pub fn select(&mut self, evts: &mut Events, timeout_ms: usize) -> io::Result<()> {
let cnt = try!(kevent(self.kq, &[], evts.as_mut_slice(), timeout_ms)
.map_err(super::from_nix_error));
self.changes.sys_events.clear();
unsafe {
evts.sys_events.set_len(cnt);
}
evts.coalesce();
Ok(())
}
pub fn register(&mut self, fd: RawFd, token: Token, interests: EventSet, opts: PollOpt) -> io::Result<()> {
trace!("registering; token={:?}; interests={:?}", token, interests);
self.ev_register(fd, token.as_usize(), EventFilter::EVFILT_READ, interests.contains(EventSet::readable()), opts);
self.ev_register(fd, token.as_usize(), EventFilter::EVFILT_WRITE, interests.contains(EventSet::writable()), opts);
self.flush_changes()
}
pub fn reregister(&mut self, fd: RawFd, token: Token, interests: EventSet, opts: PollOpt) -> io::Result<()> {
// Just need to call register here since EV_ADD is a mod if already
// registered
self.register(fd, token, interests, opts)
}
pub fn deregister(&mut self, fd: RawFd) -> io::Result<()> {
self.ev_push(fd, 0, EventFilter::EVFILT_READ, EV_DELETE);
self.ev_push(fd, 0, EventFilter::EVFILT_WRITE, EV_DELETE);
self.flush_changes()
}
fn ev_register(&mut self, fd: RawFd, token: usize, filter: EventFilter, enable: bool, opts: PollOpt) {
let mut flags = EV_ADD;
if enable {
flags = flags | EV_ENABLE;
} else {
flags = flags | EV_DISABLE;
}
if opts.contains(PollOpt::edge()) {
flags = flags | EV_CLEAR;
}
if opts.contains(PollOpt::oneshot()) {
flags = flags | EV_ONESHOT;
}
self.ev_push(fd, token, filter, flags);
}
fn ev_push(&mut self, fd: RawFd, token: usize, filter: EventFilter, flags: EventFlag) {
self.changes.sys_events.push(
KEvent {
ident: fd as ::libc::uintptr_t,
filter: filter,
flags: flags,
fflags: FilterFlag::empty(),
data: 0,
udata: token
});
}
fn flush_changes(&mut self) -> io::Result<()> {
let result = kevent(self.kq, self.changes.as_slice(), &mut [], 0).map(|_| ())
.map_err(super::from_nix_error).map(|_| ());
self.changes.sys_events.clear();
result
}
}
pub struct Events {
sys_events: Vec<KEvent>,
events: Vec<IoEvent>,
event_map: HashMap<Token, usize>,
}
impl Events {
pub fn new() -> Events {
Events {
sys_events: Vec::with_capacity(1024),
events: Vec::with_capacity(1024),
event_map: HashMap::with_capacity(1024)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
pub fn get(&self, idx: usize) -> IoEvent {
self.events[idx]
}
pub fn coalesce(&mut self) {
self.events.clear();
self.event_map.clear();
for e in self.sys_events.iter() {
let token = Token(e.udata as usize);
let len = self.events.len();
let idx = *self.event_map.entry(token)
.or_insert(len);
if idx == len {
// New entry, insert the default
self.events.push(IoEvent::new(EventSet::none(), token));
}
if e.flags.contains(EV_ERROR) {
self.events[idx].kind.insert(EventSet::error());
}
if e.filter == EventFilter::EVFILT_READ {
self.events[idx].kind.insert(EventSet::readable());
} else if e.filter == EventFilter::EVFILT_WRITE {
self.events[idx].kind.insert(EventSet::writable());
}
if e.flags.contains(EV_EOF) {
self.events[idx].kind.insert(EventSet::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if!e.fflags.is_empty() {
self.events[idx].kind.insert(EventSet::error());
}
}
}
}
fn as_slice(&self) -> &[KEvent] {
unsafe {
let ptr = (&self.sys_events[..]).as_ptr();
slice::from_raw_parts(ptr, self.sys_events.len())
}
}
fn as_mut_slice(&mut self) -> &mut [KEvent] {
unsafe {
let ptr = (&mut self.sys_events[..]).as_mut_ptr();
slice::from_raw_parts_mut(ptr, self.sys_events.capacity())
}
}
}
impl fmt::Debug for Events {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Events {{ len: {} }}", self.sys_events.len())
}
} | kq: try!(kqueue().map_err(super::from_nix_error)),
changes: Events::new()
})
} | random_line_split |
kqueue.rs | use {io, EventSet, PollOpt, Token};
use event::IoEvent;
use nix::sys::event::{EventFilter, EventFlag, FilterFlag, KEvent, kqueue, kevent};
use nix::sys::event::{EV_ADD, EV_CLEAR, EV_DELETE, EV_DISABLE, EV_ENABLE, EV_EOF, EV_ERROR, EV_ONESHOT};
use std::{fmt, slice};
use std::os::unix::io::RawFd;
use std::collections::HashMap;
#[derive(Debug)]
pub struct Selector {
kq: RawFd,
changes: Events
}
impl Selector {
pub fn new() -> io::Result<Selector> {
Ok(Selector {
kq: try!(kqueue().map_err(super::from_nix_error)),
changes: Events::new()
})
}
pub fn select(&mut self, evts: &mut Events, timeout_ms: usize) -> io::Result<()> {
let cnt = try!(kevent(self.kq, &[], evts.as_mut_slice(), timeout_ms)
.map_err(super::from_nix_error));
self.changes.sys_events.clear();
unsafe {
evts.sys_events.set_len(cnt);
}
evts.coalesce();
Ok(())
}
pub fn register(&mut self, fd: RawFd, token: Token, interests: EventSet, opts: PollOpt) -> io::Result<()> {
trace!("registering; token={:?}; interests={:?}", token, interests);
self.ev_register(fd, token.as_usize(), EventFilter::EVFILT_READ, interests.contains(EventSet::readable()), opts);
self.ev_register(fd, token.as_usize(), EventFilter::EVFILT_WRITE, interests.contains(EventSet::writable()), opts);
self.flush_changes()
}
pub fn reregister(&mut self, fd: RawFd, token: Token, interests: EventSet, opts: PollOpt) -> io::Result<()> {
// Just need to call register here since EV_ADD is a mod if already
// registered
self.register(fd, token, interests, opts)
}
pub fn deregister(&mut self, fd: RawFd) -> io::Result<()> {
self.ev_push(fd, 0, EventFilter::EVFILT_READ, EV_DELETE);
self.ev_push(fd, 0, EventFilter::EVFILT_WRITE, EV_DELETE);
self.flush_changes()
}
fn ev_register(&mut self, fd: RawFd, token: usize, filter: EventFilter, enable: bool, opts: PollOpt) {
let mut flags = EV_ADD;
if enable {
flags = flags | EV_ENABLE;
} else {
flags = flags | EV_DISABLE;
}
if opts.contains(PollOpt::edge()) |
if opts.contains(PollOpt::oneshot()) {
flags = flags | EV_ONESHOT;
}
self.ev_push(fd, token, filter, flags);
}
fn ev_push(&mut self, fd: RawFd, token: usize, filter: EventFilter, flags: EventFlag) {
self.changes.sys_events.push(
KEvent {
ident: fd as ::libc::uintptr_t,
filter: filter,
flags: flags,
fflags: FilterFlag::empty(),
data: 0,
udata: token
});
}
fn flush_changes(&mut self) -> io::Result<()> {
let result = kevent(self.kq, self.changes.as_slice(), &mut [], 0).map(|_| ())
.map_err(super::from_nix_error).map(|_| ());
self.changes.sys_events.clear();
result
}
}
pub struct Events {
sys_events: Vec<KEvent>,
events: Vec<IoEvent>,
event_map: HashMap<Token, usize>,
}
impl Events {
pub fn new() -> Events {
Events {
sys_events: Vec::with_capacity(1024),
events: Vec::with_capacity(1024),
event_map: HashMap::with_capacity(1024)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
pub fn get(&self, idx: usize) -> IoEvent {
self.events[idx]
}
pub fn coalesce(&mut self) {
self.events.clear();
self.event_map.clear();
for e in self.sys_events.iter() {
let token = Token(e.udata as usize);
let len = self.events.len();
let idx = *self.event_map.entry(token)
.or_insert(len);
if idx == len {
// New entry, insert the default
self.events.push(IoEvent::new(EventSet::none(), token));
}
if e.flags.contains(EV_ERROR) {
self.events[idx].kind.insert(EventSet::error());
}
if e.filter == EventFilter::EVFILT_READ {
self.events[idx].kind.insert(EventSet::readable());
} else if e.filter == EventFilter::EVFILT_WRITE {
self.events[idx].kind.insert(EventSet::writable());
}
if e.flags.contains(EV_EOF) {
self.events[idx].kind.insert(EventSet::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if!e.fflags.is_empty() {
self.events[idx].kind.insert(EventSet::error());
}
}
}
}
fn as_slice(&self) -> &[KEvent] {
unsafe {
let ptr = (&self.sys_events[..]).as_ptr();
slice::from_raw_parts(ptr, self.sys_events.len())
}
}
fn as_mut_slice(&mut self) -> &mut [KEvent] {
unsafe {
let ptr = (&mut self.sys_events[..]).as_mut_ptr();
slice::from_raw_parts_mut(ptr, self.sys_events.capacity())
}
}
}
impl fmt::Debug for Events {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Events {{ len: {} }}", self.sys_events.len())
}
}
| {
flags = flags | EV_CLEAR;
} | conditional_block |
bitmap_font.rs |
use render::TextureRegion;
use image::{RgbaImage, Rgba};
use {load_file_contents};
use aphid::HashMap;
use std::path::{PathBuf, Path};
use std::io;
use std::ops::Range;
use rusttype::{self, FontCollection, Scale, Font, point};
use std::fmt;
#[derive(Debug, Clone)]
pub struct FontDirectory {
pub path: PathBuf,
}
impl FontDirectory {
pub fn for_path(path:&str) -> FontDirectory {
FontDirectory {
path: PathBuf::from(path) // convert to absolute here?
}
}
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct FontDescription {
pub family: String,
pub pixel_size: u32, // what about, what code points do you want... and what
}
#[derive(Debug)]
pub struct BitmapGlyph {
pub texture_region: Option<TextureRegion>, // space doesnt have a texture region :-/ stupid space
pub advance: i32, // I think advance should always be u32... right?!
}
pub struct LoadedBitmapFont {
pub image: RgbaImage,
pub font: BitmapFont,
}
impl fmt::Debug for LoadedBitmapFont {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "LoadedBitmapFont {{ image: {:?} font: {:?} }}", self.image.dimensions(), self.font)
}
}
pub struct BitmapFont {
pub description: FontDescription,
pub glyphs: HashMap<char, BitmapGlyph>,
pub kerning: HashMap<(char, char), i32>,
}
impl fmt::Debug for BitmapFont {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "BitmapFont {{ description: {:?} glyphs: {:?} kerning: {:?} }}", self.description, self.glyphs, self.kerning)
}
}
#[derive(Debug)]
pub enum FontLoadError {
CouldntLoadFile(PathBuf, io::Error),
CouldntReadAsFont(PathBuf),
TextureSizeTooSmall { requested: u32, required: Option<u32> },
What,
}
const PADDING: i32 = 2;
pub fn min_square_texture_size(font: &Font, chars: &Vec<char>, pixel_size: u32) -> Option<u32> {
let scale = Scale { x: pixel_size as f32, y: pixel_size as f32 };
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
let pixel_height = scale.y.ceil() as i32;
'sizes: for n in 8..14 { // exclusive, 256 -> 2048
let texture_size : u32 = 2u32.pow(n);
let mut at_x : i32 = PADDING;
let mut at_y : i32 = PADDING;
for &c in chars {
if let Some(glyph) = font.glyph(c) {
let scaled = glyph.scaled(scale);
let positioned = scaled.positioned(offset);
if let Some(bb) = positioned.pixel_bounding_box() |
}
}
return Some(texture_size)
}
None
}
pub fn build_font(full_path: &Path, font_description: &FontDescription, image_size: u32) -> Result<LoadedBitmapFont, FontLoadError> {
let font_data = load_file_contents(&full_path).map_err(|io| FontLoadError::CouldntLoadFile(full_path.to_path_buf(), io))?;
let collection = FontCollection::from_bytes(&font_data[..]);
let font = collection.into_font().ok_or(FontLoadError::CouldntReadAsFont(full_path.to_path_buf()))?; // this is an option
let scale = Scale { x: font_description.pixel_size as f32, y: font_description.pixel_size as f32 };
let pixel_height = scale.y.ceil() as i32;
// println!("pixel height {:?}", pixel_height);
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
// let line_height = v_metrics.ascent - v_metrics.descent + v_metrics.line_gap;
let char_range : Range<u8> = (32)..(127); // from space to tilde
let chars : Vec<char> = char_range.map(|n| n as char).collect();
let mut img = RgbaImage::from_pixel(image_size, image_size, Rgba { data: [255,255,255,0] }); // transparent white
// top left write location of the next glyph
let mut write_x : i32 = PADDING;
let mut write_y : i32 = PADDING;
let mut glyphs : HashMap<char, BitmapGlyph> = HashMap::default();
for &c in &chars {
if let Some(glyph) = font.glyph(c) {
let scaled = glyph.scaled(scale);
let h_metrics = scaled.h_metrics();
let advance = h_metrics.advance_width.ceil() as i32;
let positioned = scaled.positioned(offset);
if let Some(bb) = positioned.pixel_bounding_box() {
// println!("x {:?} y {:?}", write_x, write_y);
// println!("check stuff -> {:?} pixel height -> {:?}", bb.width() + write_x, pixel_height);
if bb.width() + write_x > image_size as i32 {
write_x = PADDING;
write_y += pixel_height + PADDING;
// println!("new height {:?} max {:?} for image size {:?}", write_y, write_y + pixel_height, image_size);
}
if write_y + pixel_height >= image_size as i32 - PADDING {
return Err(FontLoadError::TextureSizeTooSmall { requested: image_size, required: min_square_texture_size(&font, &chars, font_description.pixel_size) });
}
write_x -= bb.min.x;
positioned.draw(|x, y, v| {
let c = (v * 255.0) as u8;
let x = (x as i32 + bb.min.x + write_x) as u32;
let y = (y as i32 + bb.min.y + write_y) as u32;
// img.put_pixel(x, y, Rgba { data: [c,c,c,255] });
img.put_pixel(x, y, Rgba { data: [255,255,255, c] });
});
// let bearing = bb.min.x as i32;
let bitmap_glyph = BitmapGlyph {
texture_region: Some(TextureRegion {
u_min: (write_x + bb.min.x - 1) as u32,
u_max: (write_x + bb.max.x + 1) as u32,
v_min: image_size - (write_y + pixel_height) as u32,
v_max: image_size - (write_y) as u32,
layer: 0,
texture_size: image_size,
}),
advance: advance,
};
glyphs.insert(c, bitmap_glyph);
write_x += (bb.max.x + PADDING) as i32;
// println!("{:?} -> h_metrics are {:?} and bb is {:?} bearing {:?} advance {:?}", c, h_metrics, bb, bearing, advance);
} else {
let bitmap_glyph = BitmapGlyph {
texture_region: None,
advance: advance,
};
glyphs.insert(c, bitmap_glyph);
}
} else {
println!("wtf, no glyph for '{:?}'", c);
}
}
let mut kerning_map : HashMap<(char, char), i32> = HashMap::default();
for &from in &chars {
for &to in &chars {
let kerning = font.pair_kerning(scale, from, to);
let kerning_i : i32 = kerning.round() as i32;
if kerning_i!= 0 {
kerning_map.insert((from,to), kerning_i);
}
}
}
Ok(LoadedBitmapFont {
image: img,
font: BitmapFont {
description: font_description.clone(),
glyphs: glyphs,
kerning: kerning_map,
}
})
} | {
if bb.width() + at_x > texture_size as i32 {
at_x = PADDING;
at_y += pixel_height + PADDING;
}
if at_y + pixel_height >= texture_size as i32 - PADDING {
continue 'sizes;
}
at_x -= bb.min.x;
at_x += (bb.max.x + PADDING) as i32;
} | conditional_block |
bitmap_font.rs | use render::TextureRegion;
use image::{RgbaImage, Rgba};
use {load_file_contents};
use aphid::HashMap;
use std::path::{PathBuf, Path};
use std::io;
use std::ops::Range;
use rusttype::{self, FontCollection, Scale, Font, point};
use std::fmt;
#[derive(Debug, Clone)]
pub struct FontDirectory {
pub path: PathBuf,
}
impl FontDirectory {
pub fn for_path(path:&str) -> FontDirectory {
FontDirectory {
path: PathBuf::from(path) // convert to absolute here?
}
}
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct FontDescription {
pub family: String,
pub pixel_size: u32, // what about, what code points do you want... and what
}
#[derive(Debug)]
pub struct BitmapGlyph {
pub texture_region: Option<TextureRegion>, // space doesnt have a texture region :-/ stupid space
pub advance: i32, // I think advance should always be u32... right?!
}
pub struct LoadedBitmapFont { |
impl fmt::Debug for LoadedBitmapFont {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "LoadedBitmapFont {{ image: {:?} font: {:?} }}", self.image.dimensions(), self.font)
}
}
pub struct BitmapFont {
pub description: FontDescription,
pub glyphs: HashMap<char, BitmapGlyph>,
pub kerning: HashMap<(char, char), i32>,
}
impl fmt::Debug for BitmapFont {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "BitmapFont {{ description: {:?} glyphs: {:?} kerning: {:?} }}", self.description, self.glyphs, self.kerning)
}
}
#[derive(Debug)]
pub enum FontLoadError {
CouldntLoadFile(PathBuf, io::Error),
CouldntReadAsFont(PathBuf),
TextureSizeTooSmall { requested: u32, required: Option<u32> },
What,
}
const PADDING: i32 = 2;
pub fn min_square_texture_size(font: &Font, chars: &Vec<char>, pixel_size: u32) -> Option<u32> {
let scale = Scale { x: pixel_size as f32, y: pixel_size as f32 };
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
let pixel_height = scale.y.ceil() as i32;
'sizes: for n in 8..14 { // exclusive, 256 -> 2048
let texture_size : u32 = 2u32.pow(n);
let mut at_x : i32 = PADDING;
let mut at_y : i32 = PADDING;
for &c in chars {
if let Some(glyph) = font.glyph(c) {
let scaled = glyph.scaled(scale);
let positioned = scaled.positioned(offset);
if let Some(bb) = positioned.pixel_bounding_box() {
if bb.width() + at_x > texture_size as i32 {
at_x = PADDING;
at_y += pixel_height + PADDING;
}
if at_y + pixel_height >= texture_size as i32 - PADDING {
continue'sizes;
}
at_x -= bb.min.x;
at_x += (bb.max.x + PADDING) as i32;
}
}
}
return Some(texture_size)
}
None
}
pub fn build_font(full_path: &Path, font_description: &FontDescription, image_size: u32) -> Result<LoadedBitmapFont, FontLoadError> {
let font_data = load_file_contents(&full_path).map_err(|io| FontLoadError::CouldntLoadFile(full_path.to_path_buf(), io))?;
let collection = FontCollection::from_bytes(&font_data[..]);
let font = collection.into_font().ok_or(FontLoadError::CouldntReadAsFont(full_path.to_path_buf()))?; // this is an option
let scale = Scale { x: font_description.pixel_size as f32, y: font_description.pixel_size as f32 };
let pixel_height = scale.y.ceil() as i32;
// println!("pixel height {:?}", pixel_height);
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
// let line_height = v_metrics.ascent - v_metrics.descent + v_metrics.line_gap;
let char_range : Range<u8> = (32)..(127); // from space to tilde
let chars : Vec<char> = char_range.map(|n| n as char).collect();
let mut img = RgbaImage::from_pixel(image_size, image_size, Rgba { data: [255,255,255,0] }); // transparent white
// top left write location of the next glyph
let mut write_x : i32 = PADDING;
let mut write_y : i32 = PADDING;
let mut glyphs : HashMap<char, BitmapGlyph> = HashMap::default();
for &c in &chars {
if let Some(glyph) = font.glyph(c) {
let scaled = glyph.scaled(scale);
let h_metrics = scaled.h_metrics();
let advance = h_metrics.advance_width.ceil() as i32;
let positioned = scaled.positioned(offset);
if let Some(bb) = positioned.pixel_bounding_box() {
// println!("x {:?} y {:?}", write_x, write_y);
// println!("check stuff -> {:?} pixel height -> {:?}", bb.width() + write_x, pixel_height);
if bb.width() + write_x > image_size as i32 {
write_x = PADDING;
write_y += pixel_height + PADDING;
// println!("new height {:?} max {:?} for image size {:?}", write_y, write_y + pixel_height, image_size);
}
if write_y + pixel_height >= image_size as i32 - PADDING {
return Err(FontLoadError::TextureSizeTooSmall { requested: image_size, required: min_square_texture_size(&font, &chars, font_description.pixel_size) });
}
write_x -= bb.min.x;
positioned.draw(|x, y, v| {
let c = (v * 255.0) as u8;
let x = (x as i32 + bb.min.x + write_x) as u32;
let y = (y as i32 + bb.min.y + write_y) as u32;
// img.put_pixel(x, y, Rgba { data: [c,c,c,255] });
img.put_pixel(x, y, Rgba { data: [255,255,255, c] });
});
// let bearing = bb.min.x as i32;
let bitmap_glyph = BitmapGlyph {
texture_region: Some(TextureRegion {
u_min: (write_x + bb.min.x - 1) as u32,
u_max: (write_x + bb.max.x + 1) as u32,
v_min: image_size - (write_y + pixel_height) as u32,
v_max: image_size - (write_y) as u32,
layer: 0,
texture_size: image_size,
}),
advance: advance,
};
glyphs.insert(c, bitmap_glyph);
write_x += (bb.max.x + PADDING) as i32;
// println!("{:?} -> h_metrics are {:?} and bb is {:?} bearing {:?} advance {:?}", c, h_metrics, bb, bearing, advance);
} else {
let bitmap_glyph = BitmapGlyph {
texture_region: None,
advance: advance,
};
glyphs.insert(c, bitmap_glyph);
}
} else {
println!("wtf, no glyph for '{:?}'", c);
}
}
let mut kerning_map : HashMap<(char, char), i32> = HashMap::default();
for &from in &chars {
for &to in &chars {
let kerning = font.pair_kerning(scale, from, to);
let kerning_i : i32 = kerning.round() as i32;
if kerning_i!= 0 {
kerning_map.insert((from,to), kerning_i);
}
}
}
Ok(LoadedBitmapFont {
image: img,
font: BitmapFont {
description: font_description.clone(),
glyphs: glyphs,
kerning: kerning_map,
}
})
} | pub image: RgbaImage,
pub font: BitmapFont,
} | random_line_split |
bitmap_font.rs |
use render::TextureRegion;
use image::{RgbaImage, Rgba};
use {load_file_contents};
use aphid::HashMap;
use std::path::{PathBuf, Path};
use std::io;
use std::ops::Range;
use rusttype::{self, FontCollection, Scale, Font, point};
use std::fmt;
#[derive(Debug, Clone)]
pub struct FontDirectory {
pub path: PathBuf,
}
impl FontDirectory {
pub fn for_path(path:&str) -> FontDirectory {
FontDirectory {
path: PathBuf::from(path) // convert to absolute here?
}
}
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct FontDescription {
pub family: String,
pub pixel_size: u32, // what about, what code points do you want... and what
}
#[derive(Debug)]
pub struct BitmapGlyph {
pub texture_region: Option<TextureRegion>, // space doesnt have a texture region :-/ stupid space
pub advance: i32, // I think advance should always be u32... right?!
}
pub struct LoadedBitmapFont {
pub image: RgbaImage,
pub font: BitmapFont,
}
impl fmt::Debug for LoadedBitmapFont {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "LoadedBitmapFont {{ image: {:?} font: {:?} }}", self.image.dimensions(), self.font)
}
}
pub struct BitmapFont {
pub description: FontDescription,
pub glyphs: HashMap<char, BitmapGlyph>,
pub kerning: HashMap<(char, char), i32>,
}
impl fmt::Debug for BitmapFont {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "BitmapFont {{ description: {:?} glyphs: {:?} kerning: {:?} }}", self.description, self.glyphs, self.kerning)
}
}
#[derive(Debug)]
pub enum FontLoadError {
CouldntLoadFile(PathBuf, io::Error),
CouldntReadAsFont(PathBuf),
TextureSizeTooSmall { requested: u32, required: Option<u32> },
What,
}
const PADDING: i32 = 2;
pub fn | (font: &Font, chars: &Vec<char>, pixel_size: u32) -> Option<u32> {
let scale = Scale { x: pixel_size as f32, y: pixel_size as f32 };
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
let pixel_height = scale.y.ceil() as i32;
'sizes: for n in 8..14 { // exclusive, 256 -> 2048
let texture_size : u32 = 2u32.pow(n);
let mut at_x : i32 = PADDING;
let mut at_y : i32 = PADDING;
for &c in chars {
if let Some(glyph) = font.glyph(c) {
let scaled = glyph.scaled(scale);
let positioned = scaled.positioned(offset);
if let Some(bb) = positioned.pixel_bounding_box() {
if bb.width() + at_x > texture_size as i32 {
at_x = PADDING;
at_y += pixel_height + PADDING;
}
if at_y + pixel_height >= texture_size as i32 - PADDING {
continue'sizes;
}
at_x -= bb.min.x;
at_x += (bb.max.x + PADDING) as i32;
}
}
}
return Some(texture_size)
}
None
}
pub fn build_font(full_path: &Path, font_description: &FontDescription, image_size: u32) -> Result<LoadedBitmapFont, FontLoadError> {
let font_data = load_file_contents(&full_path).map_err(|io| FontLoadError::CouldntLoadFile(full_path.to_path_buf(), io))?;
let collection = FontCollection::from_bytes(&font_data[..]);
let font = collection.into_font().ok_or(FontLoadError::CouldntReadAsFont(full_path.to_path_buf()))?; // this is an option
let scale = Scale { x: font_description.pixel_size as f32, y: font_description.pixel_size as f32 };
let pixel_height = scale.y.ceil() as i32;
// println!("pixel height {:?}", pixel_height);
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
// let line_height = v_metrics.ascent - v_metrics.descent + v_metrics.line_gap;
let char_range : Range<u8> = (32)..(127); // from space to tilde
let chars : Vec<char> = char_range.map(|n| n as char).collect();
let mut img = RgbaImage::from_pixel(image_size, image_size, Rgba { data: [255,255,255,0] }); // transparent white
// top left write location of the next glyph
let mut write_x : i32 = PADDING;
let mut write_y : i32 = PADDING;
let mut glyphs : HashMap<char, BitmapGlyph> = HashMap::default();
for &c in &chars {
if let Some(glyph) = font.glyph(c) {
let scaled = glyph.scaled(scale);
let h_metrics = scaled.h_metrics();
let advance = h_metrics.advance_width.ceil() as i32;
let positioned = scaled.positioned(offset);
if let Some(bb) = positioned.pixel_bounding_box() {
// println!("x {:?} y {:?}", write_x, write_y);
// println!("check stuff -> {:?} pixel height -> {:?}", bb.width() + write_x, pixel_height);
if bb.width() + write_x > image_size as i32 {
write_x = PADDING;
write_y += pixel_height + PADDING;
// println!("new height {:?} max {:?} for image size {:?}", write_y, write_y + pixel_height, image_size);
}
if write_y + pixel_height >= image_size as i32 - PADDING {
return Err(FontLoadError::TextureSizeTooSmall { requested: image_size, required: min_square_texture_size(&font, &chars, font_description.pixel_size) });
}
write_x -= bb.min.x;
positioned.draw(|x, y, v| {
let c = (v * 255.0) as u8;
let x = (x as i32 + bb.min.x + write_x) as u32;
let y = (y as i32 + bb.min.y + write_y) as u32;
// img.put_pixel(x, y, Rgba { data: [c,c,c,255] });
img.put_pixel(x, y, Rgba { data: [255,255,255, c] });
});
// let bearing = bb.min.x as i32;
let bitmap_glyph = BitmapGlyph {
texture_region: Some(TextureRegion {
u_min: (write_x + bb.min.x - 1) as u32,
u_max: (write_x + bb.max.x + 1) as u32,
v_min: image_size - (write_y + pixel_height) as u32,
v_max: image_size - (write_y) as u32,
layer: 0,
texture_size: image_size,
}),
advance: advance,
};
glyphs.insert(c, bitmap_glyph);
write_x += (bb.max.x + PADDING) as i32;
// println!("{:?} -> h_metrics are {:?} and bb is {:?} bearing {:?} advance {:?}", c, h_metrics, bb, bearing, advance);
} else {
let bitmap_glyph = BitmapGlyph {
texture_region: None,
advance: advance,
};
glyphs.insert(c, bitmap_glyph);
}
} else {
println!("wtf, no glyph for '{:?}'", c);
}
}
let mut kerning_map : HashMap<(char, char), i32> = HashMap::default();
for &from in &chars {
for &to in &chars {
let kerning = font.pair_kerning(scale, from, to);
let kerning_i : i32 = kerning.round() as i32;
if kerning_i!= 0 {
kerning_map.insert((from,to), kerning_i);
}
}
}
Ok(LoadedBitmapFont {
image: img,
font: BitmapFont {
description: font_description.clone(),
glyphs: glyphs,
kerning: kerning_map,
}
})
} | min_square_texture_size | identifier_name |
bitmap_font.rs |
use render::TextureRegion;
use image::{RgbaImage, Rgba};
use {load_file_contents};
use aphid::HashMap;
use std::path::{PathBuf, Path};
use std::io;
use std::ops::Range;
use rusttype::{self, FontCollection, Scale, Font, point};
use std::fmt;
#[derive(Debug, Clone)]
pub struct FontDirectory {
pub path: PathBuf,
}
impl FontDirectory {
pub fn for_path(path:&str) -> FontDirectory {
FontDirectory {
path: PathBuf::from(path) // convert to absolute here?
}
}
}
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub struct FontDescription {
pub family: String,
pub pixel_size: u32, // what about, what code points do you want... and what
}
#[derive(Debug)]
pub struct BitmapGlyph {
pub texture_region: Option<TextureRegion>, // space doesnt have a texture region :-/ stupid space
pub advance: i32, // I think advance should always be u32... right?!
}
pub struct LoadedBitmapFont {
pub image: RgbaImage,
pub font: BitmapFont,
}
impl fmt::Debug for LoadedBitmapFont {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "LoadedBitmapFont {{ image: {:?} font: {:?} }}", self.image.dimensions(), self.font)
}
}
pub struct BitmapFont {
pub description: FontDescription,
pub glyphs: HashMap<char, BitmapGlyph>,
pub kerning: HashMap<(char, char), i32>,
}
impl fmt::Debug for BitmapFont {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result |
}
#[derive(Debug)]
pub enum FontLoadError {
CouldntLoadFile(PathBuf, io::Error),
CouldntReadAsFont(PathBuf),
TextureSizeTooSmall { requested: u32, required: Option<u32> },
What,
}
const PADDING: i32 = 2;
pub fn min_square_texture_size(font: &Font, chars: &Vec<char>, pixel_size: u32) -> Option<u32> {
let scale = Scale { x: pixel_size as f32, y: pixel_size as f32 };
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
let pixel_height = scale.y.ceil() as i32;
'sizes: for n in 8..14 { // exclusive, 256 -> 2048
let texture_size : u32 = 2u32.pow(n);
let mut at_x : i32 = PADDING;
let mut at_y : i32 = PADDING;
for &c in chars {
if let Some(glyph) = font.glyph(c) {
let scaled = glyph.scaled(scale);
let positioned = scaled.positioned(offset);
if let Some(bb) = positioned.pixel_bounding_box() {
if bb.width() + at_x > texture_size as i32 {
at_x = PADDING;
at_y += pixel_height + PADDING;
}
if at_y + pixel_height >= texture_size as i32 - PADDING {
continue'sizes;
}
at_x -= bb.min.x;
at_x += (bb.max.x + PADDING) as i32;
}
}
}
return Some(texture_size)
}
None
}
pub fn build_font(full_path: &Path, font_description: &FontDescription, image_size: u32) -> Result<LoadedBitmapFont, FontLoadError> {
let font_data = load_file_contents(&full_path).map_err(|io| FontLoadError::CouldntLoadFile(full_path.to_path_buf(), io))?;
let collection = FontCollection::from_bytes(&font_data[..]);
let font = collection.into_font().ok_or(FontLoadError::CouldntReadAsFont(full_path.to_path_buf()))?; // this is an option
let scale = Scale { x: font_description.pixel_size as f32, y: font_description.pixel_size as f32 };
let pixel_height = scale.y.ceil() as i32;
// println!("pixel height {:?}", pixel_height);
let v_metrics = font.v_metrics(scale);
let offset = point(0.0, v_metrics.ascent);
// let line_height = v_metrics.ascent - v_metrics.descent + v_metrics.line_gap;
let char_range : Range<u8> = (32)..(127); // from space to tilde
let chars : Vec<char> = char_range.map(|n| n as char).collect();
let mut img = RgbaImage::from_pixel(image_size, image_size, Rgba { data: [255,255,255,0] }); // transparent white
// top left write location of the next glyph
let mut write_x : i32 = PADDING;
let mut write_y : i32 = PADDING;
let mut glyphs : HashMap<char, BitmapGlyph> = HashMap::default();
for &c in &chars {
if let Some(glyph) = font.glyph(c) {
let scaled = glyph.scaled(scale);
let h_metrics = scaled.h_metrics();
let advance = h_metrics.advance_width.ceil() as i32;
let positioned = scaled.positioned(offset);
if let Some(bb) = positioned.pixel_bounding_box() {
// println!("x {:?} y {:?}", write_x, write_y);
// println!("check stuff -> {:?} pixel height -> {:?}", bb.width() + write_x, pixel_height);
if bb.width() + write_x > image_size as i32 {
write_x = PADDING;
write_y += pixel_height + PADDING;
// println!("new height {:?} max {:?} for image size {:?}", write_y, write_y + pixel_height, image_size);
}
if write_y + pixel_height >= image_size as i32 - PADDING {
return Err(FontLoadError::TextureSizeTooSmall { requested: image_size, required: min_square_texture_size(&font, &chars, font_description.pixel_size) });
}
write_x -= bb.min.x;
positioned.draw(|x, y, v| {
let c = (v * 255.0) as u8;
let x = (x as i32 + bb.min.x + write_x) as u32;
let y = (y as i32 + bb.min.y + write_y) as u32;
// img.put_pixel(x, y, Rgba { data: [c,c,c,255] });
img.put_pixel(x, y, Rgba { data: [255,255,255, c] });
});
// let bearing = bb.min.x as i32;
let bitmap_glyph = BitmapGlyph {
texture_region: Some(TextureRegion {
u_min: (write_x + bb.min.x - 1) as u32,
u_max: (write_x + bb.max.x + 1) as u32,
v_min: image_size - (write_y + pixel_height) as u32,
v_max: image_size - (write_y) as u32,
layer: 0,
texture_size: image_size,
}),
advance: advance,
};
glyphs.insert(c, bitmap_glyph);
write_x += (bb.max.x + PADDING) as i32;
// println!("{:?} -> h_metrics are {:?} and bb is {:?} bearing {:?} advance {:?}", c, h_metrics, bb, bearing, advance);
} else {
let bitmap_glyph = BitmapGlyph {
texture_region: None,
advance: advance,
};
glyphs.insert(c, bitmap_glyph);
}
} else {
println!("wtf, no glyph for '{:?}'", c);
}
}
let mut kerning_map : HashMap<(char, char), i32> = HashMap::default();
for &from in &chars {
for &to in &chars {
let kerning = font.pair_kerning(scale, from, to);
let kerning_i : i32 = kerning.round() as i32;
if kerning_i!= 0 {
kerning_map.insert((from,to), kerning_i);
}
}
}
Ok(LoadedBitmapFont {
image: img,
font: BitmapFont {
description: font_description.clone(),
glyphs: glyphs,
kerning: kerning_map,
}
})
} | {
write!(f, "BitmapFont {{ description: {:?} glyphs: {:?} kerning: {:?} }}", self.description, self.glyphs, self.kerning)
} | identifier_body |
removing-extern-crate.rs | // Copyright 2018 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.
// edition:2018
// aux-build:removing-extern-crate.rs
// run-rustfix
// compile-pass
#![warn(rust_2018_idioms)]
#![allow(unused_imports)]
extern crate removing_extern_crate as foo;
extern crate core;
mod another {
extern crate removing_extern_crate as foo;
extern crate core;
}
fn | () {}
| main | identifier_name |
removing-extern-crate.rs | // Copyright 2018 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.
// edition:2018
// aux-build:removing-extern-crate.rs
// run-rustfix
// compile-pass
#![warn(rust_2018_idioms)]
#![allow(unused_imports)]
extern crate removing_extern_crate as foo;
extern crate core;
mod another {
extern crate removing_extern_crate as foo;
extern crate core;
}
fn main() | {} | identifier_body |
|
removing-extern-crate.rs | // Copyright 2018 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.
// edition:2018
// aux-build:removing-extern-crate.rs
// run-rustfix
// compile-pass
#![warn(rust_2018_idioms)] |
extern crate removing_extern_crate as foo;
extern crate core;
mod another {
extern crate removing_extern_crate as foo;
extern crate core;
}
fn main() {} | #![allow(unused_imports)] | random_line_split |
uniq.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 lib::llvm::ValueRef;
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::common::*;
use middle::trans::datum::immediate_rvalue;
use middle::trans::datum;
use middle::trans::glue;
use middle::ty;
pub fn make_free_glue(bcx: block, vptrptr: ValueRef, box_ty: ty::t)
-> block {
let _icx = push_ctxt("uniq::make_free_glue");
let box_datum = immediate_rvalue(Load(bcx, vptrptr), box_ty);
let not_null = IsNotNull(bcx, box_datum.val);
do with_cond(bcx, not_null) |bcx| {
let body_datum = box_datum.box_body(bcx);
let bcx = glue::drop_ty(bcx, body_datum.to_ref_llval(bcx),
body_datum.ty);
if ty::type_contents(bcx.tcx(), box_ty).contains_managed() {
glue::trans_free(bcx, box_datum.val)
} else |
}
}
pub fn duplicate(bcx: block, src_box: ValueRef, src_ty: ty::t) -> Result {
let _icx = push_ctxt("uniq::duplicate");
// Load the body of the source (*src)
let src_datum = immediate_rvalue(src_box, src_ty);
let body_datum = src_datum.box_body(bcx);
// Malloc space in exchange heap and copy src into it
let MallocResult {
bcx: bcx,
box: dst_box,
body: dst_body
} = malloc_unique(bcx, body_datum.ty);
body_datum.copy_to(bcx, datum::INIT, dst_body);
rslt(bcx, dst_box)
}
| {
glue::trans_exchange_free(bcx, box_datum.val)
} | conditional_block |
uniq.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 lib::llvm::ValueRef;
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::common::*;
use middle::trans::datum::immediate_rvalue;
use middle::trans::datum;
use middle::trans::glue;
use middle::ty;
pub fn | (bcx: block, vptrptr: ValueRef, box_ty: ty::t)
-> block {
let _icx = push_ctxt("uniq::make_free_glue");
let box_datum = immediate_rvalue(Load(bcx, vptrptr), box_ty);
let not_null = IsNotNull(bcx, box_datum.val);
do with_cond(bcx, not_null) |bcx| {
let body_datum = box_datum.box_body(bcx);
let bcx = glue::drop_ty(bcx, body_datum.to_ref_llval(bcx),
body_datum.ty);
if ty::type_contents(bcx.tcx(), box_ty).contains_managed() {
glue::trans_free(bcx, box_datum.val)
} else {
glue::trans_exchange_free(bcx, box_datum.val)
}
}
}
pub fn duplicate(bcx: block, src_box: ValueRef, src_ty: ty::t) -> Result {
let _icx = push_ctxt("uniq::duplicate");
// Load the body of the source (*src)
let src_datum = immediate_rvalue(src_box, src_ty);
let body_datum = src_datum.box_body(bcx);
// Malloc space in exchange heap and copy src into it
let MallocResult {
bcx: bcx,
box: dst_box,
body: dst_body
} = malloc_unique(bcx, body_datum.ty);
body_datum.copy_to(bcx, datum::INIT, dst_body);
rslt(bcx, dst_box)
}
| make_free_glue | identifier_name |
uniq.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 lib::llvm::ValueRef;
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::common::*;
use middle::trans::datum::immediate_rvalue;
use middle::trans::datum;
use middle::trans::glue;
use middle::ty;
pub fn make_free_glue(bcx: block, vptrptr: ValueRef, box_ty: ty::t)
-> block {
let _icx = push_ctxt("uniq::make_free_glue");
let box_datum = immediate_rvalue(Load(bcx, vptrptr), box_ty);
let not_null = IsNotNull(bcx, box_datum.val);
do with_cond(bcx, not_null) |bcx| {
let body_datum = box_datum.box_body(bcx);
let bcx = glue::drop_ty(bcx, body_datum.to_ref_llval(bcx),
body_datum.ty);
if ty::type_contents(bcx.tcx(), box_ty).contains_managed() {
glue::trans_free(bcx, box_datum.val)
} else {
glue::trans_exchange_free(bcx, box_datum.val)
}
}
}
pub fn duplicate(bcx: block, src_box: ValueRef, src_ty: ty::t) -> Result {
let _icx = push_ctxt("uniq::duplicate");
// Load the body of the source (*src)
let src_datum = immediate_rvalue(src_box, src_ty);
let body_datum = src_datum.box_body(bcx);
// Malloc space in exchange heap and copy src into it
let MallocResult {
bcx: bcx,
box: dst_box,
body: dst_body | } = malloc_unique(bcx, body_datum.ty);
body_datum.copy_to(bcx, datum::INIT, dst_body);
rslt(bcx, dst_box)
} | random_line_split |
|
uniq.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 lib::llvm::ValueRef;
use middle::trans::base::*;
use middle::trans::build::*;
use middle::trans::common::*;
use middle::trans::datum::immediate_rvalue;
use middle::trans::datum;
use middle::trans::glue;
use middle::ty;
pub fn make_free_glue(bcx: block, vptrptr: ValueRef, box_ty: ty::t)
-> block |
pub fn duplicate(bcx: block, src_box: ValueRef, src_ty: ty::t) -> Result {
let _icx = push_ctxt("uniq::duplicate");
// Load the body of the source (*src)
let src_datum = immediate_rvalue(src_box, src_ty);
let body_datum = src_datum.box_body(bcx);
// Malloc space in exchange heap and copy src into it
let MallocResult {
bcx: bcx,
box: dst_box,
body: dst_body
} = malloc_unique(bcx, body_datum.ty);
body_datum.copy_to(bcx, datum::INIT, dst_body);
rslt(bcx, dst_box)
}
| {
let _icx = push_ctxt("uniq::make_free_glue");
let box_datum = immediate_rvalue(Load(bcx, vptrptr), box_ty);
let not_null = IsNotNull(bcx, box_datum.val);
do with_cond(bcx, not_null) |bcx| {
let body_datum = box_datum.box_body(bcx);
let bcx = glue::drop_ty(bcx, body_datum.to_ref_llval(bcx),
body_datum.ty);
if ty::type_contents(bcx.tcx(), box_ty).contains_managed() {
glue::trans_free(bcx, box_datum.val)
} else {
glue::trans_exchange_free(bcx, box_datum.val)
}
}
} | identifier_body |
brotli.rs | use super::{Format, Quality, App, SubCommand, ArgMatches, Arg, Operation, Comp, File, PathBuf,
get_comp_level, valid_item, item_exists};
pub fn build<'a>() -> App<'static, 'a> {
SubCommand::with_name("brotli")
.about("Create a tar file with brotli compression")
.arg(
Arg::with_name("file")
.short("f")
.long("file")
.takes_value(true)
.multiple(true)
.value_name("FILE/DIR")
.required(true)
.validator(valid_item) | .help("what to tar"),
)
.arg(
Arg::with_name("output")
.short("o")
.long("out")
.takes_value(true)
.multiple(false)
.value_name("OUTFILE")
.required(true)
.validator(item_exists)
.global(true)
.help("tarball output"),
)
.arg(
Arg::with_name("slow")
.long("slow")
.takes_value(false)
.global(true)
.conflicts_with("fast")
.help("sets the slow compression mode"),
)
.arg(
Arg::with_name("fast")
.long("fast")
.takes_value(false)
.global(true)
.conflicts_with("slow")
.help("sets the fast compression mode"),
)
}
pub fn get(x: &ArgMatches) -> Operation {
Operation::Create(
{
let path = x.value_of("output").unwrap();
let w = match File::create(&path) {
Ok(x) => x,
Err(e) => {
println!("Could not create output {}", &path);
println!("Error {:?}", e);
::std::process::exit(1)
}
};
match Comp::from_format(Format::Brotli(get_comp_level(x)), w) {
Ok(x) => x,
Err(e) => {
println!("Building brotli compressor failed");
println!("{:?}", e);
::std::process::exit(1);
}
}
},
x.values_of("file").unwrap().map(PathBuf::from).collect(),
)
} | .next_line_help(true)
.global(true) | random_line_split |
brotli.rs | use super::{Format, Quality, App, SubCommand, ArgMatches, Arg, Operation, Comp, File, PathBuf,
get_comp_level, valid_item, item_exists};
pub fn build<'a>() -> App<'static, 'a> {
SubCommand::with_name("brotli")
.about("Create a tar file with brotli compression")
.arg(
Arg::with_name("file")
.short("f")
.long("file")
.takes_value(true)
.multiple(true)
.value_name("FILE/DIR")
.required(true)
.validator(valid_item)
.next_line_help(true)
.global(true)
.help("what to tar"),
)
.arg(
Arg::with_name("output")
.short("o")
.long("out")
.takes_value(true)
.multiple(false)
.value_name("OUTFILE")
.required(true)
.validator(item_exists)
.global(true)
.help("tarball output"),
)
.arg(
Arg::with_name("slow")
.long("slow")
.takes_value(false)
.global(true)
.conflicts_with("fast")
.help("sets the slow compression mode"),
)
.arg(
Arg::with_name("fast")
.long("fast")
.takes_value(false)
.global(true)
.conflicts_with("slow")
.help("sets the fast compression mode"),
)
}
pub fn get(x: &ArgMatches) -> Operation | },
x.values_of("file").unwrap().map(PathBuf::from).collect(),
)
}
| {
Operation::Create(
{
let path = x.value_of("output").unwrap();
let w = match File::create(&path) {
Ok(x) => x,
Err(e) => {
println!("Could not create output {}", &path);
println!("Error {:?}", e);
::std::process::exit(1)
}
};
match Comp::from_format(Format::Brotli(get_comp_level(x)), w) {
Ok(x) => x,
Err(e) => {
println!("Building brotli compressor failed");
println!("{:?}", e);
::std::process::exit(1);
}
} | identifier_body |
brotli.rs | use super::{Format, Quality, App, SubCommand, ArgMatches, Arg, Operation, Comp, File, PathBuf,
get_comp_level, valid_item, item_exists};
pub fn | <'a>() -> App<'static, 'a> {
SubCommand::with_name("brotli")
.about("Create a tar file with brotli compression")
.arg(
Arg::with_name("file")
.short("f")
.long("file")
.takes_value(true)
.multiple(true)
.value_name("FILE/DIR")
.required(true)
.validator(valid_item)
.next_line_help(true)
.global(true)
.help("what to tar"),
)
.arg(
Arg::with_name("output")
.short("o")
.long("out")
.takes_value(true)
.multiple(false)
.value_name("OUTFILE")
.required(true)
.validator(item_exists)
.global(true)
.help("tarball output"),
)
.arg(
Arg::with_name("slow")
.long("slow")
.takes_value(false)
.global(true)
.conflicts_with("fast")
.help("sets the slow compression mode"),
)
.arg(
Arg::with_name("fast")
.long("fast")
.takes_value(false)
.global(true)
.conflicts_with("slow")
.help("sets the fast compression mode"),
)
}
pub fn get(x: &ArgMatches) -> Operation {
Operation::Create(
{
let path = x.value_of("output").unwrap();
let w = match File::create(&path) {
Ok(x) => x,
Err(e) => {
println!("Could not create output {}", &path);
println!("Error {:?}", e);
::std::process::exit(1)
}
};
match Comp::from_format(Format::Brotli(get_comp_level(x)), w) {
Ok(x) => x,
Err(e) => {
println!("Building brotli compressor failed");
println!("{:?}", e);
::std::process::exit(1);
}
}
},
x.values_of("file").unwrap().map(PathBuf::from).collect(),
)
}
| build | identifier_name |
color.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Color", inherited=True) %>
<% from data import to_rust_ident %>
${helpers.predefined_type(
"color",
"ColorPropertyValue",
"::cssparser::RGBA::new(0, 0, 0, 255)",
animation_value_type="AnimatedRGBA",
flags="""PropertyFlags::APPLIES_TO_FIRST_LETTER PropertyFlags::APPLIES_TO_FIRST_LINE
PropertyFlags::APPLIES_TO_PLACEHOLDER""",
ignored_when_colors_disabled="True",
spec="https://drafts.csswg.org/css-color/#color"
)}
// FIXME(#15973): Add servo support for system colors
//
// FIXME(emilio): Move outside of mako.
% if product == "gecko":
pub mod system_colors {
<%
# These are actually parsed. See nsCSSProps::kColorKTable
system_colors = """activeborder activecaption appworkspace background buttonface
buttonhighlight buttonshadow buttontext captiontext graytext highlight
highlighttext inactiveborder inactivecaption inactivecaptiontext
infobackground infotext menu menutext scrollbar threeddarkshadow
threedface threedhighlight threedlightshadow threedshadow window
windowframe windowtext -moz-buttondefault -moz-buttonhoverface
-moz-buttonhovertext -moz-cellhighlight -moz-cellhighlighttext
-moz-eventreerow -moz-field -moz-fieldtext -moz-dialog -moz-dialogtext
-moz-dragtargetzone -moz-gtk-info-bar-text -moz-html-cellhighlight
-moz-html-cellhighlighttext -moz-mac-buttonactivetext
-moz-mac-chrome-active -moz-mac-chrome-inactive
-moz-mac-defaultbuttontext -moz-mac-focusring -moz-mac-menuselect
-moz-mac-menushadow -moz-mac-menutextdisable -moz-mac-menutextselect
-moz-mac-disabledtoolbartext -moz-mac-secondaryhighlight
-moz-mac-vibrancy-light -moz-mac-vibrancy-dark -moz-mac-menupopup
-moz-mac-menuitem -moz-mac-active-menuitem -moz-mac-source-list
-moz-mac-source-list-selection -moz-mac-active-source-list-selection
-moz-mac-tooltip
-moz-menuhover -moz-menuhovertext -moz-menubartext -moz-menubarhovertext
-moz-oddtreerow -moz-win-mediatext -moz-win-communicationstext
-moz-win-accentcolor -moz-win-accentcolortext
-moz-nativehyperlinktext -moz-comboboxtext -moz-combobox""".split()
# These are not parsed but must be serialized
# They are only ever set directly by Gecko
extra_colors = """WindowBackground WindowForeground WidgetBackground WidgetForeground
WidgetSelectBackground WidgetSelectForeground Widget3DHighlight Widget3DShadow
TextBackground TextForeground TextSelectBackground TextSelectForeground
TextSelectForegroundCustom TextSelectBackgroundDisabled TextSelectBackgroundAttention
TextHighlightBackground TextHighlightForeground IMERawInputBackground
IMERawInputForeground IMERawInputUnderline IMESelectedRawTextBackground
IMESelectedRawTextForeground IMESelectedRawTextUnderline
IMEConvertedTextBackground IMEConvertedTextForeground IMEConvertedTextUnderline
IMESelectedConvertedTextBackground IMESelectedConvertedTextForeground
IMESelectedConvertedTextUnderline SpellCheckerUnderline""".split()
%>
use cssparser::Parser;
use gecko_bindings::bindings::Gecko_GetLookAndFeelSystemColor;
use gecko_bindings::structs::root::mozilla::LookAndFeel_ColorID;
use std::fmt;
use style_traits::ToCss;
use values::computed::{Context, ToComputedValue};
pub type SystemColor = LookAndFeel_ColorID;
// It's hard to implement MallocSizeOf for LookAndFeel_ColorID because it
// is a bindgen type. So we implement it on the typedef instead.
malloc_size_of_is_0!(SystemColor);
impl ToCss for SystemColor {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let s = match *self {
% for color in system_colors + extra_colors:
LookAndFeel_ColorID::eColorID_${to_rust_ident(color)} => "${color}",
% endfor
LookAndFeel_ColorID::eColorID_LAST_COLOR => unreachable!(),
};
dest.write_str(s)
}
}
impl ToComputedValue for SystemColor {
type ComputedValue = u32; // nscolor
#[inline]
fn to_computed_value(&self, cx: &Context) -> Self::ComputedValue {
unsafe {
Gecko_GetLookAndFeelSystemColor(*self as i32,
cx.device().pres_context())
}
}
#[inline]
fn from_computed_value(_: &Self::ComputedValue) -> Self {
unreachable!()
}
}
impl SystemColor {
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>,) -> Result<Self, ()> {
ascii_case_insensitive_phf_map! {
color_name -> SystemColor = {
% for color in system_colors:
"${color}" => LookAndFeel_ColorID::eColorID_${to_rust_ident(color)},
% endfor
}
}
let ident = input.expect_ident().map_err(|_| ())?;
color_name(ident).cloned().ok_or(())
}
} | }
% endif | random_line_split |
|
lookup.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use crate::{
logger::Logger,
lookup_data::LookupData,
server::{
format_bytes, AbiPointer, AbiPointerOffset, BoxedExtension, BoxedExtensionFactory,
ExtensionFactory, OakApiNativeExtension, WasmState, ABI_USIZE,
},
};
use log::Level;
use oak_functions_abi::proto::OakStatus;
use oak_logger::OakLogger;
use std::sync::Arc;
use wasmi::ValueType;
// Host function name for invoking lookup in lookup data.
const LOOKUP_ABI_FUNCTION_NAME: &str = "storage_get_item";
pub struct LookupExtension {
lookup_data: Arc<LookupData>,
logger: Logger,
}
pub struct LookupFactory {
lookup_data: Arc<LookupData>,
logger: Logger,
}
impl LookupFactory {
pub fn new_boxed_extension_factory(
lookup_data: Arc<LookupData>,
logger: Logger,
) -> anyhow::Result<BoxedExtensionFactory> {
let lookup_factory = Self {
lookup_data,
logger,
};
Ok(Box::new(lookup_factory))
}
}
impl ExtensionFactory for LookupFactory {
fn create(&self) -> anyhow::Result<BoxedExtension> {
let extension = LookupExtension {
lookup_data: self.lookup_data.clone(),
logger: self.logger.clone(),
};
Ok(BoxedExtension::Native(Box::new(extension)))
}
}
/// Corresponds to the host ABI function [`storage_get_item`](https://github.com/project-oak/oak/blob/main/docs/oak_functions_abi.md#storage_get_item).
pub fn storage_get_item(
wasm_state: &mut WasmState,
extension: &mut LookupExtension,
key_ptr: AbiPointer,
key_len: AbiPointerOffset,
value_ptr_ptr: AbiPointer,
value_len_ptr: AbiPointer,
) -> Result<(), OakStatus> {
let key = wasm_state
.get_memory()
.get(key_ptr, key_len as usize)
.map_err(|err| {
extension.logger.log_sensitive(
Level::Error,
&format!(
"storage_get_item(): Unable to read key from guest memory: {:?}",
err
),
);
OakStatus::ErrInvalidArgs
})?;
extension.logger.log_sensitive(
Level::Debug,
&format!("storage_get_item(): key: {}", format_bytes(&key)),
);
match extension.lookup_data.get(&key) {
Some(value) => {
// Truncate value for logging.
let value_to_log = value.clone().into_iter().take(512).collect::<Vec<_>>();
extension.logger.log_sensitive(
Level::Debug,
&format!("storage_get_item(): value: {}", format_bytes(&value_to_log)),
);
let dest_ptr = wasm_state.alloc(value.len() as u32);
wasm_state.write_buffer_to_wasm_memory(&value, dest_ptr)?;
wasm_state.write_u32_to_wasm_memory(dest_ptr, value_ptr_ptr)?;
wasm_state.write_u32_to_wasm_memory(value.len() as u32, value_len_ptr)?;
Ok(())
} | None => {
extension
.logger
.log_sensitive(Level::Debug, "storage_get_item(): value not found");
Err(OakStatus::ErrStorageItemNotFound)
}
}
}
impl OakApiNativeExtension for LookupExtension {
fn invoke(
&mut self,
wasm_state: &mut WasmState,
args: wasmi::RuntimeArgs,
) -> Result<Result<(), OakStatus>, wasmi::Trap> {
Ok(storage_get_item(
wasm_state,
self,
args.nth_checked(0)?,
args.nth_checked(1)?,
args.nth_checked(2)?,
args.nth_checked(3)?,
))
}
fn get_metadata(&self) -> (String, wasmi::Signature) {
let signature = wasmi::Signature::new(
&[
ABI_USIZE, // key_ptr
ABI_USIZE, // key_len
ABI_USIZE, // value_ptr_ptr
ABI_USIZE, // value_len_ptr
][..],
Some(ValueType::I32),
);
(LOOKUP_ABI_FUNCTION_NAME.to_string(), signature)
}
fn terminate(&mut self) -> anyhow::Result<()> {
Ok(())
}
} | random_line_split |
|
lookup.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use crate::{
logger::Logger,
lookup_data::LookupData,
server::{
format_bytes, AbiPointer, AbiPointerOffset, BoxedExtension, BoxedExtensionFactory,
ExtensionFactory, OakApiNativeExtension, WasmState, ABI_USIZE,
},
};
use log::Level;
use oak_functions_abi::proto::OakStatus;
use oak_logger::OakLogger;
use std::sync::Arc;
use wasmi::ValueType;
// Host function name for invoking lookup in lookup data.
const LOOKUP_ABI_FUNCTION_NAME: &str = "storage_get_item";
pub struct LookupExtension {
lookup_data: Arc<LookupData>,
logger: Logger,
}
pub struct LookupFactory {
lookup_data: Arc<LookupData>,
logger: Logger,
}
impl LookupFactory {
pub fn new_boxed_extension_factory(
lookup_data: Arc<LookupData>,
logger: Logger,
) -> anyhow::Result<BoxedExtensionFactory> {
let lookup_factory = Self {
lookup_data,
logger,
};
Ok(Box::new(lookup_factory))
}
}
impl ExtensionFactory for LookupFactory {
fn create(&self) -> anyhow::Result<BoxedExtension> {
let extension = LookupExtension {
lookup_data: self.lookup_data.clone(),
logger: self.logger.clone(),
};
Ok(BoxedExtension::Native(Box::new(extension)))
}
}
/// Corresponds to the host ABI function [`storage_get_item`](https://github.com/project-oak/oak/blob/main/docs/oak_functions_abi.md#storage_get_item).
pub fn storage_get_item(
wasm_state: &mut WasmState,
extension: &mut LookupExtension,
key_ptr: AbiPointer,
key_len: AbiPointerOffset,
value_ptr_ptr: AbiPointer,
value_len_ptr: AbiPointer,
) -> Result<(), OakStatus> {
let key = wasm_state
.get_memory()
.get(key_ptr, key_len as usize)
.map_err(|err| {
extension.logger.log_sensitive(
Level::Error,
&format!(
"storage_get_item(): Unable to read key from guest memory: {:?}",
err
),
);
OakStatus::ErrInvalidArgs
})?;
extension.logger.log_sensitive(
Level::Debug,
&format!("storage_get_item(): key: {}", format_bytes(&key)),
);
match extension.lookup_data.get(&key) {
Some(value) => {
// Truncate value for logging.
let value_to_log = value.clone().into_iter().take(512).collect::<Vec<_>>();
extension.logger.log_sensitive(
Level::Debug,
&format!("storage_get_item(): value: {}", format_bytes(&value_to_log)),
);
let dest_ptr = wasm_state.alloc(value.len() as u32);
wasm_state.write_buffer_to_wasm_memory(&value, dest_ptr)?;
wasm_state.write_u32_to_wasm_memory(dest_ptr, value_ptr_ptr)?;
wasm_state.write_u32_to_wasm_memory(value.len() as u32, value_len_ptr)?;
Ok(())
}
None => {
extension
.logger
.log_sensitive(Level::Debug, "storage_get_item(): value not found");
Err(OakStatus::ErrStorageItemNotFound)
}
}
}
impl OakApiNativeExtension for LookupExtension {
fn | (
&mut self,
wasm_state: &mut WasmState,
args: wasmi::RuntimeArgs,
) -> Result<Result<(), OakStatus>, wasmi::Trap> {
Ok(storage_get_item(
wasm_state,
self,
args.nth_checked(0)?,
args.nth_checked(1)?,
args.nth_checked(2)?,
args.nth_checked(3)?,
))
}
fn get_metadata(&self) -> (String, wasmi::Signature) {
let signature = wasmi::Signature::new(
&[
ABI_USIZE, // key_ptr
ABI_USIZE, // key_len
ABI_USIZE, // value_ptr_ptr
ABI_USIZE, // value_len_ptr
][..],
Some(ValueType::I32),
);
(LOOKUP_ABI_FUNCTION_NAME.to_string(), signature)
}
fn terminate(&mut self) -> anyhow::Result<()> {
Ok(())
}
}
| invoke | identifier_name |
lookup.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use crate::{
logger::Logger,
lookup_data::LookupData,
server::{
format_bytes, AbiPointer, AbiPointerOffset, BoxedExtension, BoxedExtensionFactory,
ExtensionFactory, OakApiNativeExtension, WasmState, ABI_USIZE,
},
};
use log::Level;
use oak_functions_abi::proto::OakStatus;
use oak_logger::OakLogger;
use std::sync::Arc;
use wasmi::ValueType;
// Host function name for invoking lookup in lookup data.
const LOOKUP_ABI_FUNCTION_NAME: &str = "storage_get_item";
pub struct LookupExtension {
lookup_data: Arc<LookupData>,
logger: Logger,
}
pub struct LookupFactory {
lookup_data: Arc<LookupData>,
logger: Logger,
}
impl LookupFactory {
pub fn new_boxed_extension_factory(
lookup_data: Arc<LookupData>,
logger: Logger,
) -> anyhow::Result<BoxedExtensionFactory> {
let lookup_factory = Self {
lookup_data,
logger,
};
Ok(Box::new(lookup_factory))
}
}
impl ExtensionFactory for LookupFactory {
fn create(&self) -> anyhow::Result<BoxedExtension> {
let extension = LookupExtension {
lookup_data: self.lookup_data.clone(),
logger: self.logger.clone(),
};
Ok(BoxedExtension::Native(Box::new(extension)))
}
}
/// Corresponds to the host ABI function [`storage_get_item`](https://github.com/project-oak/oak/blob/main/docs/oak_functions_abi.md#storage_get_item).
pub fn storage_get_item(
wasm_state: &mut WasmState,
extension: &mut LookupExtension,
key_ptr: AbiPointer,
key_len: AbiPointerOffset,
value_ptr_ptr: AbiPointer,
value_len_ptr: AbiPointer,
) -> Result<(), OakStatus> {
let key = wasm_state
.get_memory()
.get(key_ptr, key_len as usize)
.map_err(|err| {
extension.logger.log_sensitive(
Level::Error,
&format!(
"storage_get_item(): Unable to read key from guest memory: {:?}",
err
),
);
OakStatus::ErrInvalidArgs
})?;
extension.logger.log_sensitive(
Level::Debug,
&format!("storage_get_item(): key: {}", format_bytes(&key)),
);
match extension.lookup_data.get(&key) {
Some(value) => {
// Truncate value for logging.
let value_to_log = value.clone().into_iter().take(512).collect::<Vec<_>>();
extension.logger.log_sensitive(
Level::Debug,
&format!("storage_get_item(): value: {}", format_bytes(&value_to_log)),
);
let dest_ptr = wasm_state.alloc(value.len() as u32);
wasm_state.write_buffer_to_wasm_memory(&value, dest_ptr)?;
wasm_state.write_u32_to_wasm_memory(dest_ptr, value_ptr_ptr)?;
wasm_state.write_u32_to_wasm_memory(value.len() as u32, value_len_ptr)?;
Ok(())
}
None => {
extension
.logger
.log_sensitive(Level::Debug, "storage_get_item(): value not found");
Err(OakStatus::ErrStorageItemNotFound)
}
}
}
impl OakApiNativeExtension for LookupExtension {
fn invoke(
&mut self,
wasm_state: &mut WasmState,
args: wasmi::RuntimeArgs,
) -> Result<Result<(), OakStatus>, wasmi::Trap> {
Ok(storage_get_item(
wasm_state,
self,
args.nth_checked(0)?,
args.nth_checked(1)?,
args.nth_checked(2)?,
args.nth_checked(3)?,
))
}
fn get_metadata(&self) -> (String, wasmi::Signature) {
let signature = wasmi::Signature::new(
&[
ABI_USIZE, // key_ptr
ABI_USIZE, // key_len
ABI_USIZE, // value_ptr_ptr
ABI_USIZE, // value_len_ptr
][..],
Some(ValueType::I32),
);
(LOOKUP_ABI_FUNCTION_NAME.to_string(), signature)
}
fn terminate(&mut self) -> anyhow::Result<()> |
}
| {
Ok(())
} | identifier_body |
lookup.rs | //
// Copyright 2021 The Project Oak Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
use crate::{
logger::Logger,
lookup_data::LookupData,
server::{
format_bytes, AbiPointer, AbiPointerOffset, BoxedExtension, BoxedExtensionFactory,
ExtensionFactory, OakApiNativeExtension, WasmState, ABI_USIZE,
},
};
use log::Level;
use oak_functions_abi::proto::OakStatus;
use oak_logger::OakLogger;
use std::sync::Arc;
use wasmi::ValueType;
// Host function name for invoking lookup in lookup data.
const LOOKUP_ABI_FUNCTION_NAME: &str = "storage_get_item";
pub struct LookupExtension {
lookup_data: Arc<LookupData>,
logger: Logger,
}
pub struct LookupFactory {
lookup_data: Arc<LookupData>,
logger: Logger,
}
impl LookupFactory {
pub fn new_boxed_extension_factory(
lookup_data: Arc<LookupData>,
logger: Logger,
) -> anyhow::Result<BoxedExtensionFactory> {
let lookup_factory = Self {
lookup_data,
logger,
};
Ok(Box::new(lookup_factory))
}
}
impl ExtensionFactory for LookupFactory {
fn create(&self) -> anyhow::Result<BoxedExtension> {
let extension = LookupExtension {
lookup_data: self.lookup_data.clone(),
logger: self.logger.clone(),
};
Ok(BoxedExtension::Native(Box::new(extension)))
}
}
/// Corresponds to the host ABI function [`storage_get_item`](https://github.com/project-oak/oak/blob/main/docs/oak_functions_abi.md#storage_get_item).
pub fn storage_get_item(
wasm_state: &mut WasmState,
extension: &mut LookupExtension,
key_ptr: AbiPointer,
key_len: AbiPointerOffset,
value_ptr_ptr: AbiPointer,
value_len_ptr: AbiPointer,
) -> Result<(), OakStatus> {
let key = wasm_state
.get_memory()
.get(key_ptr, key_len as usize)
.map_err(|err| {
extension.logger.log_sensitive(
Level::Error,
&format!(
"storage_get_item(): Unable to read key from guest memory: {:?}",
err
),
);
OakStatus::ErrInvalidArgs
})?;
extension.logger.log_sensitive(
Level::Debug,
&format!("storage_get_item(): key: {}", format_bytes(&key)),
);
match extension.lookup_data.get(&key) {
Some(value) => {
// Truncate value for logging.
let value_to_log = value.clone().into_iter().take(512).collect::<Vec<_>>();
extension.logger.log_sensitive(
Level::Debug,
&format!("storage_get_item(): value: {}", format_bytes(&value_to_log)),
);
let dest_ptr = wasm_state.alloc(value.len() as u32);
wasm_state.write_buffer_to_wasm_memory(&value, dest_ptr)?;
wasm_state.write_u32_to_wasm_memory(dest_ptr, value_ptr_ptr)?;
wasm_state.write_u32_to_wasm_memory(value.len() as u32, value_len_ptr)?;
Ok(())
}
None => |
}
}
impl OakApiNativeExtension for LookupExtension {
fn invoke(
&mut self,
wasm_state: &mut WasmState,
args: wasmi::RuntimeArgs,
) -> Result<Result<(), OakStatus>, wasmi::Trap> {
Ok(storage_get_item(
wasm_state,
self,
args.nth_checked(0)?,
args.nth_checked(1)?,
args.nth_checked(2)?,
args.nth_checked(3)?,
))
}
fn get_metadata(&self) -> (String, wasmi::Signature) {
let signature = wasmi::Signature::new(
&[
ABI_USIZE, // key_ptr
ABI_USIZE, // key_len
ABI_USIZE, // value_ptr_ptr
ABI_USIZE, // value_len_ptr
][..],
Some(ValueType::I32),
);
(LOOKUP_ABI_FUNCTION_NAME.to_string(), signature)
}
fn terminate(&mut self) -> anyhow::Result<()> {
Ok(())
}
}
| {
extension
.logger
.log_sensitive(Level::Debug, "storage_get_item(): value not found");
Err(OakStatus::ErrStorageItemNotFound)
} | conditional_block |
model.rs | use std::collections::HashMap;
use itertools::Itertools;
use rustc_serialize::json;
use ngrams::ngrams;
use errors::DeserializeError;
pub struct Model {
pub ngram_ranks: HashMap<String, usize>,
}
impl Model {
pub fn build_from_text(text: &str) -> Self {
let mut ngram_counts = HashMap::new();
let words = text.split(|ch: char|!ch.is_alphabetic()).filter(|s|!s.is_empty());
for word in words {
for n in 1..6 {
for ngram in ngrams(word, n) {
// If you don't want to unecessarily allocate strings, this is
// the only way to do it. This RFC should fix this if it ever
// gets accepted: // https://github.com/rust-lang/rfcs/pull/1533
if let Some(count) = ngram_counts.get_mut(ngram) |
ngram_counts.insert(ngram.to_owned(), 1);
}
}
}
let ngrams = ngram_counts
.into_iter()
.sorted_by(|a, b| Ord::cmp(&b.1, &a.1))
.into_iter()
.take(300) // Models need to have the same size, or have normalized "differences"
.map(|(ngram, _count)| ngram);
// Nicer way to build a hash map.
Model { ngram_ranks: ngrams.enumerate().map(|(a, b)| (b, a)).collect() }
}
pub fn deserialize(bytes: Vec<u8>) -> Result<Self, DeserializeError> {
let string = try!(String::from_utf8(bytes));
let ngram_ranks = try!(json::decode(string.as_str()));
let model = Model { ngram_ranks: ngram_ranks };
Ok(model)
}
pub fn serialize(&self) -> Vec<u8> {
json::encode(&self.ngram_ranks).unwrap().into_bytes()
}
pub fn compare(&self, other: &Model) -> usize {
let max_difference = other.ngram_ranks.len();
let mut difference = 0;
for (ngram, rank) in &self.ngram_ranks {
difference += match other.ngram_ranks.get(ngram) {
Some(other_rank) => get_difference(*rank, *other_rank),
None => max_difference,
}
}
difference
}
}
fn get_difference(a: usize, b: usize) -> usize {
if a > b { a - b } else { b - a }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialization_and_deserialization() {
let model = Model::build_from_text("Testing text for serialization");
let serialized = model.serialize();
let deserialized = Model::deserialize(serialized).unwrap();
assert_eq!(model.ngram_ranks, deserialized.ngram_ranks);
}
}
| {
*count += 1;
continue;
} | conditional_block |
model.rs | use std::collections::HashMap;
use itertools::Itertools;
use rustc_serialize::json;
use ngrams::ngrams;
use errors::DeserializeError;
pub struct Model {
pub ngram_ranks: HashMap<String, usize>,
}
impl Model {
pub fn build_from_text(text: &str) -> Self {
let mut ngram_counts = HashMap::new();
let words = text.split(|ch: char|!ch.is_alphabetic()).filter(|s|!s.is_empty());
for word in words {
for n in 1..6 {
for ngram in ngrams(word, n) {
// If you don't want to unecessarily allocate strings, this is
// the only way to do it. This RFC should fix this if it ever
// gets accepted: // https://github.com/rust-lang/rfcs/pull/1533
if let Some(count) = ngram_counts.get_mut(ngram) {
*count += 1;
continue;
}
ngram_counts.insert(ngram.to_owned(), 1);
}
}
}
let ngrams = ngram_counts
.into_iter()
.sorted_by(|a, b| Ord::cmp(&b.1, &a.1))
.into_iter()
.take(300) // Models need to have the same size, or have normalized "differences"
.map(|(ngram, _count)| ngram);
// Nicer way to build a hash map.
Model { ngram_ranks: ngrams.enumerate().map(|(a, b)| (b, a)).collect() }
}
pub fn | (bytes: Vec<u8>) -> Result<Self, DeserializeError> {
let string = try!(String::from_utf8(bytes));
let ngram_ranks = try!(json::decode(string.as_str()));
let model = Model { ngram_ranks: ngram_ranks };
Ok(model)
}
pub fn serialize(&self) -> Vec<u8> {
json::encode(&self.ngram_ranks).unwrap().into_bytes()
}
pub fn compare(&self, other: &Model) -> usize {
let max_difference = other.ngram_ranks.len();
let mut difference = 0;
for (ngram, rank) in &self.ngram_ranks {
difference += match other.ngram_ranks.get(ngram) {
Some(other_rank) => get_difference(*rank, *other_rank),
None => max_difference,
}
}
difference
}
}
fn get_difference(a: usize, b: usize) -> usize {
if a > b { a - b } else { b - a }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialization_and_deserialization() {
let model = Model::build_from_text("Testing text for serialization");
let serialized = model.serialize();
let deserialized = Model::deserialize(serialized).unwrap();
assert_eq!(model.ngram_ranks, deserialized.ngram_ranks);
}
}
| deserialize | identifier_name |
model.rs | use std::collections::HashMap;
use itertools::Itertools;
use rustc_serialize::json;
use ngrams::ngrams;
use errors::DeserializeError;
pub struct Model {
pub ngram_ranks: HashMap<String, usize>,
}
impl Model {
pub fn build_from_text(text: &str) -> Self {
let mut ngram_counts = HashMap::new();
let words = text.split(|ch: char|!ch.is_alphabetic()).filter(|s|!s.is_empty());
for word in words {
for n in 1..6 {
for ngram in ngrams(word, n) {
// If you don't want to unecessarily allocate strings, this is
// the only way to do it. This RFC should fix this if it ever
// gets accepted: // https://github.com/rust-lang/rfcs/pull/1533
if let Some(count) = ngram_counts.get_mut(ngram) {
*count += 1;
continue;
}
ngram_counts.insert(ngram.to_owned(), 1);
}
}
}
let ngrams = ngram_counts
.into_iter()
.sorted_by(|a, b| Ord::cmp(&b.1, &a.1))
.into_iter()
.take(300) // Models need to have the same size, or have normalized "differences"
.map(|(ngram, _count)| ngram);
// Nicer way to build a hash map.
Model { ngram_ranks: ngrams.enumerate().map(|(a, b)| (b, a)).collect() }
}
pub fn deserialize(bytes: Vec<u8>) -> Result<Self, DeserializeError> {
let string = try!(String::from_utf8(bytes));
let ngram_ranks = try!(json::decode(string.as_str()));
let model = Model { ngram_ranks: ngram_ranks };
Ok(model)
}
pub fn serialize(&self) -> Vec<u8> {
json::encode(&self.ngram_ranks).unwrap().into_bytes()
}
pub fn compare(&self, other: &Model) -> usize {
let max_difference = other.ngram_ranks.len();
let mut difference = 0;
for (ngram, rank) in &self.ngram_ranks {
difference += match other.ngram_ranks.get(ngram) {
Some(other_rank) => get_difference(*rank, *other_rank),
None => max_difference,
}
}
difference
}
}
fn get_difference(a: usize, b: usize) -> usize {
if a > b { a - b } else { b - a }
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn serialization_and_deserialization() {
let model = Model::build_from_text("Testing text for serialization"); | let serialized = model.serialize();
let deserialized = Model::deserialize(serialized).unwrap();
assert_eq!(model.ngram_ranks, deserialized.ngram_ranks);
}
} | random_line_split |
|
inventory_vector.rs | use Encode;
#[derive(Debug, Default, Encode, PartialEq)]
pub struct | {
flags: InvFlags,
pub hash: [u8; 32],
}
bitflags! {
#[derive(Default, Encode)]
flags InvFlags: u32 {
const ERROR = 0b0,
const MSG_TX = 0b00000001,
const MSG_BLOCK = 0b00000010,
const MSG_FILTERED_BLOCK = 0b00000100,
const MSG_CMPCT_BLOCK = 0b00001000
}
}
impl InventoryVector {
pub fn new(flags: u32, hash: &[u8]) -> InventoryVector {
debug_assert!(hash.len() == 32);
let mut a: [u8; 32] = Default::default();
a.copy_from_slice(&hash);
InventoryVector {
flags: InvFlags { bits: flags },
hash: a,
}
}
}
| InventoryVector | identifier_name |
inventory_vector.rs | use Encode;
#[derive(Debug, Default, Encode, PartialEq)]
pub struct InventoryVector {
flags: InvFlags,
pub hash: [u8; 32],
}
bitflags! {
#[derive(Default, Encode)] | flags InvFlags: u32 {
const ERROR = 0b0,
const MSG_TX = 0b00000001,
const MSG_BLOCK = 0b00000010,
const MSG_FILTERED_BLOCK = 0b00000100,
const MSG_CMPCT_BLOCK = 0b00001000
}
}
impl InventoryVector {
pub fn new(flags: u32, hash: &[u8]) -> InventoryVector {
debug_assert!(hash.len() == 32);
let mut a: [u8; 32] = Default::default();
a.copy_from_slice(&hash);
InventoryVector {
flags: InvFlags { bits: flags },
hash: a,
}
}
} | random_line_split |
|
either.rs | // Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos.
//
// Serkr 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.
//
// Serkr 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 Serkr. If not, see <http://www.gnu.org/licenses/>.
//
/// The Either type represents values with two possibilities.
/// It is similar to Result, but the second possibility is not necessarily an error.
#[derive(Debug)]
#[allow(missing_docs)]
pub enum | <L, R> {
Left(L),
Right(R)
}
impl<L, R> Either<L, R> {
}
| Either | identifier_name |
either.rs | // Serkr - An automated theorem prover. Copyright (C) 2015-2016 Mikko Aarnos.
//
// Serkr 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.
//
// Serkr 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 Serkr. If not, see <http://www.gnu.org/licenses/>.
//
/// The Either type represents values with two possibilities.
/// It is similar to Result, but the second possibility is not necessarily an error. | }
impl<L, R> Either<L, R> {
} | #[derive(Debug)]
#[allow(missing_docs)]
pub enum Either<L, R> {
Left(L),
Right(R) | random_line_split |
script_msg.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 AnimationState;
use AuxiliaryBrowsingContextLoadInfo;
use DocumentState;
use IFrameLoadInfo;
use IFrameLoadInfoWithData;
use LayoutControlMsg;
use LoadData;
use WorkerGlobalScopeInit;
use WorkerScriptLoadOrigin;
use canvas_traits::canvas::{CanvasMsg, CanvasId};
use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId};
use embedder_traits::EmbedderMsg;
use euclid::{Size2D, TypedSize2D};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use msg::constellation_msg::{BrowsingContextId, PipelineId, TopLevelBrowsingContextId};
use msg::constellation_msg::{HistoryStateId, TraversalDirection};
use net_traits::CoreResourceMsg;
use net_traits::request::RequestInit;
use net_traits::storage_thread::StorageType;
use servo_url::ImmutableOrigin;
use servo_url::ServoUrl;
use std::fmt;
use style_traits::CSSPixel;
use style_traits::cursor::CursorKind;
use style_traits::viewport::ViewportConstraints;
use webrender_api::{DeviceIntPoint, DeviceUintSize};
/// Messages from the layout to the constellation.
#[derive(Deserialize, Serialize)]
pub enum LayoutMsg {
/// Indicates whether this pipeline is currently running animations.
ChangeRunningAnimationsState(PipelineId, AnimationState),
/// Inform the constellation of the size of the iframe's viewport.
IFrameSizes(Vec<(BrowsingContextId, TypedSize2D<f32, CSSPixel>)>),
/// Requests that the constellation inform the compositor that it needs to record
/// the time when the frame with the given ID (epoch) is painted.
PendingPaintMetric(PipelineId, Epoch),
/// Requests that the constellation inform the compositor of the a cursor change.
SetCursor(CursorKind),
/// Notifies the constellation that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
}
impl fmt::Debug for LayoutMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::LayoutMsg::*;
let variant = match *self {
ChangeRunningAnimationsState(..) => "ChangeRunningAnimationsState",
IFrameSizes(..) => "IFrameSizes",
PendingPaintMetric(..) => "PendingPaintMetric",
SetCursor(..) => "SetCursor",
ViewportConstrained(..) => "ViewportConstrained",
};
write!(formatter, "LayoutMsg::{}", variant)
}
}
/// Whether a DOM event was prevented by web content
#[derive(Deserialize, Serialize)]
pub enum EventResult {
/// Allowed by web content
DefaultAllowed,
/// Prevented by web content
DefaultPrevented,
}
/// A log entry reported to the constellation
/// We don't report all log entries, just serious ones.
/// We need a separate type for this because `LogLevel` isn't serializable.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum LogEntry {
/// Panic, with a reason and backtrace
Panic(String, String),
/// Error, with a reason
Error(String),
/// warning, with a reason
Warn(String),
}
/// Messages from the script to the constellation.
#[derive(Deserialize, Serialize)]
pub enum ScriptMsg {
/// Forward a message to the embedder.
ForwardToEmbedder(EmbedderMsg),
/// Requests are sent to constellation and fetches are checked manually
/// for cross-origin loads
InitiateNavigateRequest(RequestInit, /* cancellation_chan */ IpcReceiver<()>),
/// Broadcast a storage event to every same-origin pipeline.
/// The strings are key, old value and new value.
BroadcastStorageEvent(
StorageType,
ServoUrl,
Option<String>,
Option<String>,
Option<String>,
),
/// Indicates whether this pipeline is currently running animations.
ChangeRunningAnimationsState(AnimationState),
/// Requests that a new 2D canvas thread be created. (This is done in the constellation because
/// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.)
CreateCanvasPaintThread(Size2D<u32>, IpcSender<(IpcSender<CanvasMsg>, CanvasId)>),
/// Notifies the constellation that this frame has received focus.
Focus,
/// Requests that the constellation retrieve the current contents of the clipboard
GetClipboardContents(IpcSender<String>),
/// Get the top-level browsing context info for a given browsing context.
GetTopForBrowsingContext(
BrowsingContextId,
IpcSender<Option<TopLevelBrowsingContextId>>,
),
/// Get the browsing context id of the browsing context in which pipeline is
/// embedded and the parent pipeline id of that browsing context.
GetBrowsingContextInfo(
PipelineId,
IpcSender<Option<(BrowsingContextId, Option<PipelineId>)>>,
),
/// Get the nth child browsing context ID for a given browsing context, sorted in tree order.
GetChildBrowsingContextId(
BrowsingContextId,
usize,
IpcSender<Option<BrowsingContextId>>,
),
/// All pending loads are complete, and the `load` event for this pipeline
/// has been dispatched.
LoadComplete,
/// A new load has been requested, with an option to replace the current entry once loaded
/// instead of adding a new entry.
LoadUrl(LoadData, bool),
/// Abort loading after sending a LoadUrl message.
AbortLoadUrl,
/// Post a message to the currently active window of a given browsing context.
PostMessage(BrowsingContextId, Option<ImmutableOrigin>, Vec<u8>),
/// Inform the constellation that a fragment was navigated to and whether or not it was a replacement navigation.
NavigatedToFragment(ServoUrl, bool),
/// HTMLIFrameElement Forward or Back traversal.
TraverseHistory(TraversalDirection),
/// Inform the constellation of a pushed history state.
PushHistoryState(HistoryStateId, ServoUrl),
/// Inform the constellation of a replaced history state.
ReplaceHistoryState(HistoryStateId, ServoUrl),
/// Gets the length of the joint session history from the constellation.
JointSessionHistoryLength(IpcSender<u32>),
/// Notification that this iframe should be removed.
/// Returns a list of pipelines which were closed.
RemoveIFrame(BrowsingContextId, IpcSender<Vec<PipelineId>>),
/// Change pipeline visibility
SetVisible(bool),
/// Notifies constellation that an iframe's visibility has been changed.
VisibilityChangeComplete(bool),
/// A load has been requested in an IFrame.
ScriptLoadedURLInIFrame(IFrameLoadInfoWithData),
/// A load of the initial `about:blank` has been completed in an IFrame.
ScriptNewIFrame(IFrameLoadInfo, IpcSender<LayoutControlMsg>),
/// Script has opened a new auxiliary browsing context.
ScriptNewAuxiliary(
AuxiliaryBrowsingContextLoadInfo,
IpcSender<LayoutControlMsg>,
),
/// Requests that the constellation set the contents of the clipboard
SetClipboardContents(String),
/// Mark a new document as active
ActivateDocument,
/// Set the document state for a pipeline (used by screenshot / reftests)
SetDocumentState(DocumentState),
/// Update the pipeline Url, which can change after redirections.
SetFinalUrl(ServoUrl),
/// Script has handled a touch event, and either prevented or allowed default actions.
TouchEventProcessed(EventResult),
/// A log entry, with the top-level browsing context id and thread name
LogEntry(Option<String>, LogEntry),
/// Discard the document.
DiscardDocument,
/// Discard the browsing context.
DiscardTopLevelBrowsingContext,
/// Notifies the constellation that this pipeline has exited.
PipelineExited,
/// Send messages from postMessage calls from serviceworker
/// to constellation for storing in service worker manager
ForwardDOMMessage(DOMMessage, ServoUrl),
/// Store the data required to activate a service worker for the given scope
RegisterServiceWorker(ScopeThings, ServoUrl),
/// Get Window Informations size and position
GetClientWindow(IpcSender<(DeviceUintSize, DeviceIntPoint)>),
/// Get the screen size (pixel)
GetScreenSize(IpcSender<(DeviceUintSize)>),
/// Get the available screen size (pixel)
GetScreenAvailSize(IpcSender<(DeviceUintSize)>),
}
impl fmt::Debug for ScriptMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ScriptMsg::*;
let variant = match *self {
ForwardToEmbedder(..) => "ForwardToEmbedder", | CreateCanvasPaintThread(..) => "CreateCanvasPaintThread",
Focus => "Focus",
GetClipboardContents(..) => "GetClipboardContents",
GetBrowsingContextInfo(..) => "GetBrowsingContextInfo",
GetTopForBrowsingContext(..) => "GetParentBrowsingContext",
GetChildBrowsingContextId(..) => "GetChildBrowsingContextId",
LoadComplete => "LoadComplete",
LoadUrl(..) => "LoadUrl",
AbortLoadUrl => "AbortLoadUrl",
PostMessage(..) => "PostMessage",
NavigatedToFragment(..) => "NavigatedToFragment",
TraverseHistory(..) => "TraverseHistory",
PushHistoryState(..) => "PushHistoryState",
ReplaceHistoryState(..) => "ReplaceHistoryState",
JointSessionHistoryLength(..) => "JointSessionHistoryLength",
RemoveIFrame(..) => "RemoveIFrame",
SetVisible(..) => "SetVisible",
VisibilityChangeComplete(..) => "VisibilityChangeComplete",
ScriptLoadedURLInIFrame(..) => "ScriptLoadedURLInIFrame",
ScriptNewIFrame(..) => "ScriptNewIFrame",
ScriptNewAuxiliary(..) => "ScriptNewAuxiliary",
SetClipboardContents(..) => "SetClipboardContents",
ActivateDocument => "ActivateDocument",
SetDocumentState(..) => "SetDocumentState",
SetFinalUrl(..) => "SetFinalUrl",
TouchEventProcessed(..) => "TouchEventProcessed",
LogEntry(..) => "LogEntry",
DiscardDocument => "DiscardDocument",
DiscardTopLevelBrowsingContext => "DiscardTopLevelBrowsingContext",
PipelineExited => "PipelineExited",
ForwardDOMMessage(..) => "ForwardDOMMessage",
RegisterServiceWorker(..) => "RegisterServiceWorker",
GetClientWindow(..) => "GetClientWindow",
GetScreenSize(..) => "GetScreenSize",
GetScreenAvailSize(..) => "GetScreenAvailSize",
};
write!(formatter, "ScriptMsg::{}", variant)
}
}
/// Entities required to spawn service workers
#[derive(Clone, Deserialize, Serialize)]
pub struct ScopeThings {
/// script resource url
pub script_url: ServoUrl,
/// network load origin of the resource
pub worker_load_origin: WorkerScriptLoadOrigin,
/// base resources required to create worker global scopes
pub init: WorkerGlobalScopeInit,
/// the port to receive devtools message from
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// service worker id
pub worker_id: WorkerId,
}
/// Message that gets passed to service worker scope on postMessage
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DOMMessage(pub Vec<u8>);
/// Channels to allow service worker manager to communicate with constellation and resource thread
pub struct SWManagerSenders {
/// sender for communicating with constellation
pub swmanager_sender: IpcSender<SWManagerMsg>,
/// sender for communicating with resource thread
pub resource_sender: IpcSender<CoreResourceMsg>,
}
/// Messages sent to Service Worker Manager thread
#[derive(Deserialize, Serialize)]
pub enum ServiceWorkerMsg {
/// Message to register the service worker
RegisterServiceWorker(ScopeThings, ServoUrl),
/// Timeout message sent by active service workers
Timeout(ServoUrl),
/// Message sent by constellation to forward to a running service worker
ForwardDOMMessage(DOMMessage, ServoUrl),
/// Exit the service worker manager
Exit,
}
/// Messages outgoing from the Service Worker Manager thread to constellation
#[derive(Deserialize, Serialize)]
pub enum SWManagerMsg {
/// Provide the constellation with a means of communicating with the Service Worker Manager
OwnSender(IpcSender<ServiceWorkerMsg>),
} | InitiateNavigateRequest(..) => "InitiateNavigateRequest",
BroadcastStorageEvent(..) => "BroadcastStorageEvent",
ChangeRunningAnimationsState(..) => "ChangeRunningAnimationsState", | random_line_split |
script_msg.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 AnimationState;
use AuxiliaryBrowsingContextLoadInfo;
use DocumentState;
use IFrameLoadInfo;
use IFrameLoadInfoWithData;
use LayoutControlMsg;
use LoadData;
use WorkerGlobalScopeInit;
use WorkerScriptLoadOrigin;
use canvas_traits::canvas::{CanvasMsg, CanvasId};
use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId};
use embedder_traits::EmbedderMsg;
use euclid::{Size2D, TypedSize2D};
use gfx_traits::Epoch;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use msg::constellation_msg::{BrowsingContextId, PipelineId, TopLevelBrowsingContextId};
use msg::constellation_msg::{HistoryStateId, TraversalDirection};
use net_traits::CoreResourceMsg;
use net_traits::request::RequestInit;
use net_traits::storage_thread::StorageType;
use servo_url::ImmutableOrigin;
use servo_url::ServoUrl;
use std::fmt;
use style_traits::CSSPixel;
use style_traits::cursor::CursorKind;
use style_traits::viewport::ViewportConstraints;
use webrender_api::{DeviceIntPoint, DeviceUintSize};
/// Messages from the layout to the constellation.
#[derive(Deserialize, Serialize)]
pub enum | {
/// Indicates whether this pipeline is currently running animations.
ChangeRunningAnimationsState(PipelineId, AnimationState),
/// Inform the constellation of the size of the iframe's viewport.
IFrameSizes(Vec<(BrowsingContextId, TypedSize2D<f32, CSSPixel>)>),
/// Requests that the constellation inform the compositor that it needs to record
/// the time when the frame with the given ID (epoch) is painted.
PendingPaintMetric(PipelineId, Epoch),
/// Requests that the constellation inform the compositor of the a cursor change.
SetCursor(CursorKind),
/// Notifies the constellation that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
}
impl fmt::Debug for LayoutMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::LayoutMsg::*;
let variant = match *self {
ChangeRunningAnimationsState(..) => "ChangeRunningAnimationsState",
IFrameSizes(..) => "IFrameSizes",
PendingPaintMetric(..) => "PendingPaintMetric",
SetCursor(..) => "SetCursor",
ViewportConstrained(..) => "ViewportConstrained",
};
write!(formatter, "LayoutMsg::{}", variant)
}
}
/// Whether a DOM event was prevented by web content
#[derive(Deserialize, Serialize)]
pub enum EventResult {
/// Allowed by web content
DefaultAllowed,
/// Prevented by web content
DefaultPrevented,
}
/// A log entry reported to the constellation
/// We don't report all log entries, just serious ones.
/// We need a separate type for this because `LogLevel` isn't serializable.
#[derive(Clone, Debug, Deserialize, Serialize)]
pub enum LogEntry {
/// Panic, with a reason and backtrace
Panic(String, String),
/// Error, with a reason
Error(String),
/// warning, with a reason
Warn(String),
}
/// Messages from the script to the constellation.
#[derive(Deserialize, Serialize)]
pub enum ScriptMsg {
/// Forward a message to the embedder.
ForwardToEmbedder(EmbedderMsg),
/// Requests are sent to constellation and fetches are checked manually
/// for cross-origin loads
InitiateNavigateRequest(RequestInit, /* cancellation_chan */ IpcReceiver<()>),
/// Broadcast a storage event to every same-origin pipeline.
/// The strings are key, old value and new value.
BroadcastStorageEvent(
StorageType,
ServoUrl,
Option<String>,
Option<String>,
Option<String>,
),
/// Indicates whether this pipeline is currently running animations.
ChangeRunningAnimationsState(AnimationState),
/// Requests that a new 2D canvas thread be created. (This is done in the constellation because
/// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.)
CreateCanvasPaintThread(Size2D<u32>, IpcSender<(IpcSender<CanvasMsg>, CanvasId)>),
/// Notifies the constellation that this frame has received focus.
Focus,
/// Requests that the constellation retrieve the current contents of the clipboard
GetClipboardContents(IpcSender<String>),
/// Get the top-level browsing context info for a given browsing context.
GetTopForBrowsingContext(
BrowsingContextId,
IpcSender<Option<TopLevelBrowsingContextId>>,
),
/// Get the browsing context id of the browsing context in which pipeline is
/// embedded and the parent pipeline id of that browsing context.
GetBrowsingContextInfo(
PipelineId,
IpcSender<Option<(BrowsingContextId, Option<PipelineId>)>>,
),
/// Get the nth child browsing context ID for a given browsing context, sorted in tree order.
GetChildBrowsingContextId(
BrowsingContextId,
usize,
IpcSender<Option<BrowsingContextId>>,
),
/// All pending loads are complete, and the `load` event for this pipeline
/// has been dispatched.
LoadComplete,
/// A new load has been requested, with an option to replace the current entry once loaded
/// instead of adding a new entry.
LoadUrl(LoadData, bool),
/// Abort loading after sending a LoadUrl message.
AbortLoadUrl,
/// Post a message to the currently active window of a given browsing context.
PostMessage(BrowsingContextId, Option<ImmutableOrigin>, Vec<u8>),
/// Inform the constellation that a fragment was navigated to and whether or not it was a replacement navigation.
NavigatedToFragment(ServoUrl, bool),
/// HTMLIFrameElement Forward or Back traversal.
TraverseHistory(TraversalDirection),
/// Inform the constellation of a pushed history state.
PushHistoryState(HistoryStateId, ServoUrl),
/// Inform the constellation of a replaced history state.
ReplaceHistoryState(HistoryStateId, ServoUrl),
/// Gets the length of the joint session history from the constellation.
JointSessionHistoryLength(IpcSender<u32>),
/// Notification that this iframe should be removed.
/// Returns a list of pipelines which were closed.
RemoveIFrame(BrowsingContextId, IpcSender<Vec<PipelineId>>),
/// Change pipeline visibility
SetVisible(bool),
/// Notifies constellation that an iframe's visibility has been changed.
VisibilityChangeComplete(bool),
/// A load has been requested in an IFrame.
ScriptLoadedURLInIFrame(IFrameLoadInfoWithData),
/// A load of the initial `about:blank` has been completed in an IFrame.
ScriptNewIFrame(IFrameLoadInfo, IpcSender<LayoutControlMsg>),
/// Script has opened a new auxiliary browsing context.
ScriptNewAuxiliary(
AuxiliaryBrowsingContextLoadInfo,
IpcSender<LayoutControlMsg>,
),
/// Requests that the constellation set the contents of the clipboard
SetClipboardContents(String),
/// Mark a new document as active
ActivateDocument,
/// Set the document state for a pipeline (used by screenshot / reftests)
SetDocumentState(DocumentState),
/// Update the pipeline Url, which can change after redirections.
SetFinalUrl(ServoUrl),
/// Script has handled a touch event, and either prevented or allowed default actions.
TouchEventProcessed(EventResult),
/// A log entry, with the top-level browsing context id and thread name
LogEntry(Option<String>, LogEntry),
/// Discard the document.
DiscardDocument,
/// Discard the browsing context.
DiscardTopLevelBrowsingContext,
/// Notifies the constellation that this pipeline has exited.
PipelineExited,
/// Send messages from postMessage calls from serviceworker
/// to constellation for storing in service worker manager
ForwardDOMMessage(DOMMessage, ServoUrl),
/// Store the data required to activate a service worker for the given scope
RegisterServiceWorker(ScopeThings, ServoUrl),
/// Get Window Informations size and position
GetClientWindow(IpcSender<(DeviceUintSize, DeviceIntPoint)>),
/// Get the screen size (pixel)
GetScreenSize(IpcSender<(DeviceUintSize)>),
/// Get the available screen size (pixel)
GetScreenAvailSize(IpcSender<(DeviceUintSize)>),
}
impl fmt::Debug for ScriptMsg {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use self::ScriptMsg::*;
let variant = match *self {
ForwardToEmbedder(..) => "ForwardToEmbedder",
InitiateNavigateRequest(..) => "InitiateNavigateRequest",
BroadcastStorageEvent(..) => "BroadcastStorageEvent",
ChangeRunningAnimationsState(..) => "ChangeRunningAnimationsState",
CreateCanvasPaintThread(..) => "CreateCanvasPaintThread",
Focus => "Focus",
GetClipboardContents(..) => "GetClipboardContents",
GetBrowsingContextInfo(..) => "GetBrowsingContextInfo",
GetTopForBrowsingContext(..) => "GetParentBrowsingContext",
GetChildBrowsingContextId(..) => "GetChildBrowsingContextId",
LoadComplete => "LoadComplete",
LoadUrl(..) => "LoadUrl",
AbortLoadUrl => "AbortLoadUrl",
PostMessage(..) => "PostMessage",
NavigatedToFragment(..) => "NavigatedToFragment",
TraverseHistory(..) => "TraverseHistory",
PushHistoryState(..) => "PushHistoryState",
ReplaceHistoryState(..) => "ReplaceHistoryState",
JointSessionHistoryLength(..) => "JointSessionHistoryLength",
RemoveIFrame(..) => "RemoveIFrame",
SetVisible(..) => "SetVisible",
VisibilityChangeComplete(..) => "VisibilityChangeComplete",
ScriptLoadedURLInIFrame(..) => "ScriptLoadedURLInIFrame",
ScriptNewIFrame(..) => "ScriptNewIFrame",
ScriptNewAuxiliary(..) => "ScriptNewAuxiliary",
SetClipboardContents(..) => "SetClipboardContents",
ActivateDocument => "ActivateDocument",
SetDocumentState(..) => "SetDocumentState",
SetFinalUrl(..) => "SetFinalUrl",
TouchEventProcessed(..) => "TouchEventProcessed",
LogEntry(..) => "LogEntry",
DiscardDocument => "DiscardDocument",
DiscardTopLevelBrowsingContext => "DiscardTopLevelBrowsingContext",
PipelineExited => "PipelineExited",
ForwardDOMMessage(..) => "ForwardDOMMessage",
RegisterServiceWorker(..) => "RegisterServiceWorker",
GetClientWindow(..) => "GetClientWindow",
GetScreenSize(..) => "GetScreenSize",
GetScreenAvailSize(..) => "GetScreenAvailSize",
};
write!(formatter, "ScriptMsg::{}", variant)
}
}
/// Entities required to spawn service workers
#[derive(Clone, Deserialize, Serialize)]
pub struct ScopeThings {
/// script resource url
pub script_url: ServoUrl,
/// network load origin of the resource
pub worker_load_origin: WorkerScriptLoadOrigin,
/// base resources required to create worker global scopes
pub init: WorkerGlobalScopeInit,
/// the port to receive devtools message from
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// service worker id
pub worker_id: WorkerId,
}
/// Message that gets passed to service worker scope on postMessage
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DOMMessage(pub Vec<u8>);
/// Channels to allow service worker manager to communicate with constellation and resource thread
pub struct SWManagerSenders {
/// sender for communicating with constellation
pub swmanager_sender: IpcSender<SWManagerMsg>,
/// sender for communicating with resource thread
pub resource_sender: IpcSender<CoreResourceMsg>,
}
/// Messages sent to Service Worker Manager thread
#[derive(Deserialize, Serialize)]
pub enum ServiceWorkerMsg {
/// Message to register the service worker
RegisterServiceWorker(ScopeThings, ServoUrl),
/// Timeout message sent by active service workers
Timeout(ServoUrl),
/// Message sent by constellation to forward to a running service worker
ForwardDOMMessage(DOMMessage, ServoUrl),
/// Exit the service worker manager
Exit,
}
/// Messages outgoing from the Service Worker Manager thread to constellation
#[derive(Deserialize, Serialize)]
pub enum SWManagerMsg {
/// Provide the constellation with a means of communicating with the Service Worker Manager
OwnSender(IpcSender<ServiceWorkerMsg>),
}
| LayoutMsg | identifier_name |
main.rs | use std::thread;
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_ms(1000);
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("Judith Butler", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
Philosopher::new("Emma Goldman", 3, 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();
}
} | // 0, 4 rather than 4, 0 to avoid deadlock
Philosopher::new("Michel Foucault", 0, 4)];
| random_line_split |
main.rs | use std::thread;
use std::sync::{Mutex, Arc};
struct Philosopher {
name: String,
left: usize,
right: usize
}
impl Philosopher {
fn | (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_ms(1000);
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("Judith Butler", 0, 1),
Philosopher::new("Gilles Deleuze", 1, 2),
Philosopher::new("Karl Marx", 2, 3),
Philosopher::new("Emma Goldman", 3, 4),
// 0, 4 rather than 4, 0 to avoid deadlock
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();
}
}
| new | identifier_name |
engine.rs | use libc::{c_int, c_uint, c_ulonglong, size_t};
use ffi::{core, target};
use ffi::execution_engine as engine;
use ffi::execution_engine::*;
use ffi::target_machine::LLVMCodeModel;
use cbox::CBox;
use std::marker::PhantomData;
use std::{mem, ptr};
use std::ops::*;
use compile::Compile;
use context::{Context, GetContext};
use module::Module;
use ty::{StructType, Type};
use util::{self, CastFrom};
use value::{Function, Value};
/// An abstract interface for implementation execution of LLVM modules.
///
/// This is designed to support both interpreter and just-in-time (JIT) compiler implementations.
pub trait ExecutionEngine<'a, 'b:'a> where LLVMExecutionEngineRef:From<&'b Self> {
/// The options given to this upon creation.
type Options : Copy;
/// Create a new execution engine with the given `Module` and options, or return a
/// description of the error.
fn new(module: &'a Module, options: Self::Options) -> Result<Self, CBox<str>>;
/// Add a module to the list of modules to interpret or compile.
fn add_module(&'b self, module: &'a Module) {
unsafe { engine::LLVMAddModule(self.into(), (&*module).into()) }
}
/// Remove a module from the list of modules to interpret or compile.
fn remove_module(&'b self, module: &'a Module) -> &'a Module {
unsafe {
let mut out = mem::uninitialized();
engine::LLVMRemoveModule(self.into(), module.into(), &mut out, ptr::null_mut());
out.into()
}
}
/// Execute all of the static constructors for this program.
fn run_static_constructors(&'b self) {
unsafe { engine::LLVMRunStaticConstructors(self.into()) }
}
/// Execute all of the static destructors for this program.
fn run_static_destructors(&'b self) {
unsafe { engine::LLVMRunStaticDestructors(self.into()) }
}
/// Attempt to find a function with the name given, or `None` if there wasn't
/// a function with that name.
fn find_function(&'b self, name: &str) -> Option<&'a Function> {
util::with_cstr(name, |c_name| unsafe {
let mut out = mem::zeroed();
engine::LLVMFindFunction(self.into(), c_name, &mut out);
mem::transmute(out)
})
}
/// Run `function` with the arguments given as ``GenericValue`s, then return the result as one.
///
/// Note that if this engine is a `JitEngine`, it only supports a small fraction of combinations
/// for the arguments and return value, so be warned.
///
/// To convert the arguments to `GenericValue`s, you should use the `GenericValueCast::to_generic` method.
/// To convert the return value from a `GenericValue`, you should use the `GenericValueCast::from_generic` method.
fn run_function(&'b self, function: &'a Function, args: &[GenericValue<'a>]) -> GenericValue<'a> {
let ptr = args.as_ptr() as *mut LLVMGenericValueRef;
unsafe { engine::LLVMRunFunction(self.into(), function.into(), args.len() as c_uint, ptr).into() }
}
/// Returns a pointer to the global value given.
///
/// This is marked as unsafe because the type cannot be guranteed to be the same as the
/// type of the global value at this point.
unsafe fn get_global<T>(&'b self, global: &'a Value) -> &'b T {
mem::transmute(engine::LLVMGetPointerToGlobal(self.into(), global.into()))
}
/// Returns a pointer to the global value with the name given.
///
/// This is marked as unsafe because the type cannot be guranteed to be the same as the
/// type of the global value at this point.
unsafe fn find_global<T>(&'b self, name: &str) -> Option<&'b T> |
/// Maps a global to a specific memory location.
unsafe fn add_global_mapping<T>(&'b self, global: &'a Value, addr: *const T) {
engine::LLVMAddGlobalMapping(self.into(), global.into(), mem::transmute(addr));
}
}
/// The options to pass to the MCJIT backend.
#[derive(Copy, Clone)]
pub struct JitOptions {
/// The degree to which optimizations should be done, between 0 and 3.
///
/// 0 represents no optimizations, 3 represents maximum optimization
pub opt_level: usize
}
/// The MCJIT backend, which compiles functions and values into machine code.
pub struct JitEngine<'a> {
engine: LLVMExecutionEngineRef,
marker: PhantomData<&'a ()>
}
native_ref!{contra JitEngine, engine: LLVMExecutionEngineRef}
impl<'a, 'b> JitEngine<'a> {
/// Run the closure `cb` with the machine code for the function `function`.
///
/// This will check that the types match at runtime when in debug mode, but not release mode.
/// You should make sure to use debug mode if you want it to error when the types don't match.
pub fn with_function<C, A, R>(&self, function: &'b Function, cb: C) where A:Compile<'b>, R:Compile<'b>, C:FnOnce(extern fn(A) -> R) {
if cfg!(not(ndebug)) {
let ctx = function.get_context();
let sig = function.get_signature();
assert_eq!(Type::get::<R>(ctx), sig.get_return());
let arg = Type::get::<A>(ctx);
if let Some(args) = StructType::cast(arg) {
assert_eq!(sig.get_params(), args.get_elements());
} else {
let nparams = sig.get_params().len();
if nparams == 1 {
assert_eq!(arg, sig.get_params()[0]);
} else if nparams == 0 {
assert_eq!(arg, Type::get::<()>(ctx));
} else {
panic!("array type arguments are not yet supported; use a tuple or struct instead");
}
}
}
unsafe {
cb(self.get_function::<A, R>(function));
}
}
/// Run the closure `cb` with the machine code for the function `function`.
pub unsafe fn with_function_unchecked<C, A, R>(&self, function: &'b Function, cb: C) where A:Compile<'b>, R:Compile<'b>, C:FnOnce(extern fn(A) -> R) {
cb(self.get_function::<A, R>(function));
}
/// Returns a pointer to the machine code for the function `function`.
///
/// This is marked as unsafe because the types given as arguments and return could be different
/// from their internal representation.
pub unsafe fn get_function<A, R>(&self, function: &'b Function) -> extern fn(A) -> R {
let ptr:&u8 = self.get_global(function);
mem::transmute(ptr)
}
}
impl<'a, 'b:'a> ExecutionEngine<'a, 'b> for JitEngine<'a> {
type Options = JitOptions;
fn new(module: &'a Module, options: JitOptions) -> Result<JitEngine<'a>, CBox<str>> {
unsafe {
let mut ee = mem::uninitialized();
let mut out = mem::zeroed();
engine::LLVMLinkInMCJIT();
if target::LLVM_InitializeNativeTarget() == 1 {
return Err("failed to initialize native target".into())
}
if target::LLVM_InitializeNativeAsmPrinter() == 1 {
return Err("failed to initialize native asm printer".into())
}
let mut options = LLVMMCJITCompilerOptions {
OptLevel: options.opt_level as c_uint,
CodeModel: LLVMCodeModel::LLVMCodeModelJITDefault,
NoFramePointerElim: 0,
EnableFastISel: 1,
MCJMM: ptr::null_mut()
};
let size = mem::size_of::<LLVMMCJITCompilerOptions>();
let result = engine::LLVMCreateMCJITCompilerForModule(&mut ee, (&*module).into(), &mut options, size as size_t, &mut out);
if result == 0 {
Ok(ee.into())
} else {
Err(CBox::new(out))
}
}
}
}
/// The interpreter backend
pub struct Interpreter<'a> {
engine: LLVMExecutionEngineRef,
marker: PhantomData<&'a ()>
}
native_ref!{contra Interpreter, engine: LLVMExecutionEngineRef}
impl<'a> Interpreter<'a> {
/// Run `function` with the arguments given as ``GenericValue`s, then return the result as one.
///
/// To convert the arguments to `GenericValue`s, you should use the `GenericValueCast::to_generic` method.
/// To convert the return value from a `GenericValue`, you should use the `GenericValueCast::from_generic` method.
pub fn run_function(&self, function: &'a Function, args: &[GenericValue<'a>]) -> GenericValue<'a> {
let ptr = args.as_ptr() as *mut LLVMGenericValueRef;
unsafe { engine::LLVMRunFunction(self.into(), function.into(), args.len() as c_uint, ptr).into() }
}
}
impl<'a, 'b:'a> ExecutionEngine<'a, 'b> for Interpreter<'a> {
type Options = ();
fn new(module: &'a Module, _: ()) -> Result<Interpreter<'a>, CBox<str>> {
unsafe {
let mut ee = mem::uninitialized();
let mut out = mem::zeroed();
engine::LLVMLinkInInterpreter();
let result = engine::LLVMCreateInterpreterForModule(&mut ee, (&*module).into(), &mut out);
if result == 0 {
Ok(ee.into())
} else {
Err(CBox::new(out))
}
}
}
}
/// A wrapped value that can be passed to an interpreted function or returned from one
pub struct GenericValue<'a> {
value: LLVMGenericValueRef,
marker: PhantomData<&'a ()>
}
native_ref!(contra GenericValue, value: LLVMGenericValueRef);
impl<'a> Drop for GenericValue<'a> {
fn drop(&mut self) {
unsafe {
engine::LLVMDisposeGenericValue(self.value)
}
}
}
/// A value that can be cast into a `GenericValue` and that a `GenericValue` can be cast into.
///
/// Both these methods require contexts because some `Type` constructors are needed for the
/// conversion and these constructors need a context.
pub trait GenericValueCast<'a> {
/// Create a `GenericValue` from this value.
fn to_generic(self, context: &'a Context) -> GenericValue<'a>;
/// Convert the `GenericValue` into a value of this type again.
fn from_generic(value: GenericValue<'a>, context: &'a Context) -> Self;
}
impl<'a> GenericValueCast<'a> for f64 {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = core::LLVMDoubleTypeInContext(ctx.into());
engine::LLVMCreateGenericValueOfFloat(ty, self).into()
}
}
fn from_generic(value: GenericValue<'a>, ctx: &'a Context) -> f64 {
unsafe {
let ty = core::LLVMDoubleTypeInContext(ctx.into());
engine::LLVMGenericValueToFloat(ty, value.into())
}
}
}
impl<'a> GenericValueCast<'a> for f32 {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = core::LLVMFloatTypeInContext(ctx.into());
engine::LLVMCreateGenericValueOfFloat(ty, self as f64).into()
}
}
fn from_generic(value: GenericValue<'a>, ctx: &'a Context) -> f32 {
unsafe {
let ty = core::LLVMFloatTypeInContext(ctx.into());
engine::LLVMGenericValueToFloat(ty, value.into()) as f32
}
}
}
macro_rules! generic_int(
($ty:ty, $signed:expr) => (
impl<'a> GenericValueCast<'a> for $ty {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = <Self as Compile<'a>>::get_type(ctx);
engine::LLVMCreateGenericValueOfInt(ty.into(), self as c_ulonglong, $signed as c_int).into()
}
}
fn from_generic(value: GenericValue<'a>, _: &'a Context) -> $ty {
unsafe {
engine::LLVMGenericValueToInt(value.into(), $signed as c_int) as $ty
}
}
}
);
(some $signed:ty, $unsigned:ty) => (
generic_int!{$signed, true}
generic_int!{$unsigned, false}
);
);
impl<'a> GenericValueCast<'a> for bool {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = <Self as Compile<'a>>::get_type(ctx);
engine::LLVMCreateGenericValueOfInt(ty.into(), self as c_ulonglong, 0).into()
}
}
fn from_generic(value: GenericValue<'a>, _: &'a Context) -> bool {
unsafe {
engine::LLVMGenericValueToInt(value.into(), 0)!= 0
}
}
}
generic_int!{some i8, u8}
generic_int!{some i16, u16}
generic_int!{some i32, u32}
generic_int!{some i64, u64}
| {
util::with_cstr(name, |ptr|
mem::transmute(engine::LLVMGetGlobalValueAddress(self.into(), ptr))
)
} | identifier_body |
engine.rs | use libc::{c_int, c_uint, c_ulonglong, size_t};
use ffi::{core, target};
use ffi::execution_engine as engine;
use ffi::execution_engine::*;
use ffi::target_machine::LLVMCodeModel;
use cbox::CBox;
use std::marker::PhantomData;
use std::{mem, ptr};
use std::ops::*;
use compile::Compile;
use context::{Context, GetContext};
use module::Module;
use ty::{StructType, Type};
use util::{self, CastFrom};
use value::{Function, Value};
/// An abstract interface for implementation execution of LLVM modules.
///
/// This is designed to support both interpreter and just-in-time (JIT) compiler implementations.
pub trait ExecutionEngine<'a, 'b:'a> where LLVMExecutionEngineRef:From<&'b Self> {
/// The options given to this upon creation.
type Options : Copy; | fn add_module(&'b self, module: &'a Module) {
unsafe { engine::LLVMAddModule(self.into(), (&*module).into()) }
}
/// Remove a module from the list of modules to interpret or compile.
fn remove_module(&'b self, module: &'a Module) -> &'a Module {
unsafe {
let mut out = mem::uninitialized();
engine::LLVMRemoveModule(self.into(), module.into(), &mut out, ptr::null_mut());
out.into()
}
}
/// Execute all of the static constructors for this program.
fn run_static_constructors(&'b self) {
unsafe { engine::LLVMRunStaticConstructors(self.into()) }
}
/// Execute all of the static destructors for this program.
fn run_static_destructors(&'b self) {
unsafe { engine::LLVMRunStaticDestructors(self.into()) }
}
/// Attempt to find a function with the name given, or `None` if there wasn't
/// a function with that name.
fn find_function(&'b self, name: &str) -> Option<&'a Function> {
util::with_cstr(name, |c_name| unsafe {
let mut out = mem::zeroed();
engine::LLVMFindFunction(self.into(), c_name, &mut out);
mem::transmute(out)
})
}
/// Run `function` with the arguments given as ``GenericValue`s, then return the result as one.
///
/// Note that if this engine is a `JitEngine`, it only supports a small fraction of combinations
/// for the arguments and return value, so be warned.
///
/// To convert the arguments to `GenericValue`s, you should use the `GenericValueCast::to_generic` method.
/// To convert the return value from a `GenericValue`, you should use the `GenericValueCast::from_generic` method.
fn run_function(&'b self, function: &'a Function, args: &[GenericValue<'a>]) -> GenericValue<'a> {
let ptr = args.as_ptr() as *mut LLVMGenericValueRef;
unsafe { engine::LLVMRunFunction(self.into(), function.into(), args.len() as c_uint, ptr).into() }
}
/// Returns a pointer to the global value given.
///
/// This is marked as unsafe because the type cannot be guranteed to be the same as the
/// type of the global value at this point.
unsafe fn get_global<T>(&'b self, global: &'a Value) -> &'b T {
mem::transmute(engine::LLVMGetPointerToGlobal(self.into(), global.into()))
}
/// Returns a pointer to the global value with the name given.
///
/// This is marked as unsafe because the type cannot be guranteed to be the same as the
/// type of the global value at this point.
unsafe fn find_global<T>(&'b self, name: &str) -> Option<&'b T> {
util::with_cstr(name, |ptr|
mem::transmute(engine::LLVMGetGlobalValueAddress(self.into(), ptr))
)
}
/// Maps a global to a specific memory location.
unsafe fn add_global_mapping<T>(&'b self, global: &'a Value, addr: *const T) {
engine::LLVMAddGlobalMapping(self.into(), global.into(), mem::transmute(addr));
}
}
/// The options to pass to the MCJIT backend.
#[derive(Copy, Clone)]
pub struct JitOptions {
/// The degree to which optimizations should be done, between 0 and 3.
///
/// 0 represents no optimizations, 3 represents maximum optimization
pub opt_level: usize
}
/// The MCJIT backend, which compiles functions and values into machine code.
pub struct JitEngine<'a> {
engine: LLVMExecutionEngineRef,
marker: PhantomData<&'a ()>
}
native_ref!{contra JitEngine, engine: LLVMExecutionEngineRef}
impl<'a, 'b> JitEngine<'a> {
/// Run the closure `cb` with the machine code for the function `function`.
///
/// This will check that the types match at runtime when in debug mode, but not release mode.
/// You should make sure to use debug mode if you want it to error when the types don't match.
pub fn with_function<C, A, R>(&self, function: &'b Function, cb: C) where A:Compile<'b>, R:Compile<'b>, C:FnOnce(extern fn(A) -> R) {
if cfg!(not(ndebug)) {
let ctx = function.get_context();
let sig = function.get_signature();
assert_eq!(Type::get::<R>(ctx), sig.get_return());
let arg = Type::get::<A>(ctx);
if let Some(args) = StructType::cast(arg) {
assert_eq!(sig.get_params(), args.get_elements());
} else {
let nparams = sig.get_params().len();
if nparams == 1 {
assert_eq!(arg, sig.get_params()[0]);
} else if nparams == 0 {
assert_eq!(arg, Type::get::<()>(ctx));
} else {
panic!("array type arguments are not yet supported; use a tuple or struct instead");
}
}
}
unsafe {
cb(self.get_function::<A, R>(function));
}
}
/// Run the closure `cb` with the machine code for the function `function`.
pub unsafe fn with_function_unchecked<C, A, R>(&self, function: &'b Function, cb: C) where A:Compile<'b>, R:Compile<'b>, C:FnOnce(extern fn(A) -> R) {
cb(self.get_function::<A, R>(function));
}
/// Returns a pointer to the machine code for the function `function`.
///
/// This is marked as unsafe because the types given as arguments and return could be different
/// from their internal representation.
pub unsafe fn get_function<A, R>(&self, function: &'b Function) -> extern fn(A) -> R {
let ptr:&u8 = self.get_global(function);
mem::transmute(ptr)
}
}
impl<'a, 'b:'a> ExecutionEngine<'a, 'b> for JitEngine<'a> {
type Options = JitOptions;
fn new(module: &'a Module, options: JitOptions) -> Result<JitEngine<'a>, CBox<str>> {
unsafe {
let mut ee = mem::uninitialized();
let mut out = mem::zeroed();
engine::LLVMLinkInMCJIT();
if target::LLVM_InitializeNativeTarget() == 1 {
return Err("failed to initialize native target".into())
}
if target::LLVM_InitializeNativeAsmPrinter() == 1 {
return Err("failed to initialize native asm printer".into())
}
let mut options = LLVMMCJITCompilerOptions {
OptLevel: options.opt_level as c_uint,
CodeModel: LLVMCodeModel::LLVMCodeModelJITDefault,
NoFramePointerElim: 0,
EnableFastISel: 1,
MCJMM: ptr::null_mut()
};
let size = mem::size_of::<LLVMMCJITCompilerOptions>();
let result = engine::LLVMCreateMCJITCompilerForModule(&mut ee, (&*module).into(), &mut options, size as size_t, &mut out);
if result == 0 {
Ok(ee.into())
} else {
Err(CBox::new(out))
}
}
}
}
/// The interpreter backend
pub struct Interpreter<'a> {
engine: LLVMExecutionEngineRef,
marker: PhantomData<&'a ()>
}
native_ref!{contra Interpreter, engine: LLVMExecutionEngineRef}
impl<'a> Interpreter<'a> {
/// Run `function` with the arguments given as ``GenericValue`s, then return the result as one.
///
/// To convert the arguments to `GenericValue`s, you should use the `GenericValueCast::to_generic` method.
/// To convert the return value from a `GenericValue`, you should use the `GenericValueCast::from_generic` method.
pub fn run_function(&self, function: &'a Function, args: &[GenericValue<'a>]) -> GenericValue<'a> {
let ptr = args.as_ptr() as *mut LLVMGenericValueRef;
unsafe { engine::LLVMRunFunction(self.into(), function.into(), args.len() as c_uint, ptr).into() }
}
}
impl<'a, 'b:'a> ExecutionEngine<'a, 'b> for Interpreter<'a> {
type Options = ();
fn new(module: &'a Module, _: ()) -> Result<Interpreter<'a>, CBox<str>> {
unsafe {
let mut ee = mem::uninitialized();
let mut out = mem::zeroed();
engine::LLVMLinkInInterpreter();
let result = engine::LLVMCreateInterpreterForModule(&mut ee, (&*module).into(), &mut out);
if result == 0 {
Ok(ee.into())
} else {
Err(CBox::new(out))
}
}
}
}
/// A wrapped value that can be passed to an interpreted function or returned from one
pub struct GenericValue<'a> {
value: LLVMGenericValueRef,
marker: PhantomData<&'a ()>
}
native_ref!(contra GenericValue, value: LLVMGenericValueRef);
impl<'a> Drop for GenericValue<'a> {
fn drop(&mut self) {
unsafe {
engine::LLVMDisposeGenericValue(self.value)
}
}
}
/// A value that can be cast into a `GenericValue` and that a `GenericValue` can be cast into.
///
/// Both these methods require contexts because some `Type` constructors are needed for the
/// conversion and these constructors need a context.
pub trait GenericValueCast<'a> {
/// Create a `GenericValue` from this value.
fn to_generic(self, context: &'a Context) -> GenericValue<'a>;
/// Convert the `GenericValue` into a value of this type again.
fn from_generic(value: GenericValue<'a>, context: &'a Context) -> Self;
}
impl<'a> GenericValueCast<'a> for f64 {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = core::LLVMDoubleTypeInContext(ctx.into());
engine::LLVMCreateGenericValueOfFloat(ty, self).into()
}
}
fn from_generic(value: GenericValue<'a>, ctx: &'a Context) -> f64 {
unsafe {
let ty = core::LLVMDoubleTypeInContext(ctx.into());
engine::LLVMGenericValueToFloat(ty, value.into())
}
}
}
impl<'a> GenericValueCast<'a> for f32 {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = core::LLVMFloatTypeInContext(ctx.into());
engine::LLVMCreateGenericValueOfFloat(ty, self as f64).into()
}
}
fn from_generic(value: GenericValue<'a>, ctx: &'a Context) -> f32 {
unsafe {
let ty = core::LLVMFloatTypeInContext(ctx.into());
engine::LLVMGenericValueToFloat(ty, value.into()) as f32
}
}
}
macro_rules! generic_int(
($ty:ty, $signed:expr) => (
impl<'a> GenericValueCast<'a> for $ty {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = <Self as Compile<'a>>::get_type(ctx);
engine::LLVMCreateGenericValueOfInt(ty.into(), self as c_ulonglong, $signed as c_int).into()
}
}
fn from_generic(value: GenericValue<'a>, _: &'a Context) -> $ty {
unsafe {
engine::LLVMGenericValueToInt(value.into(), $signed as c_int) as $ty
}
}
}
);
(some $signed:ty, $unsigned:ty) => (
generic_int!{$signed, true}
generic_int!{$unsigned, false}
);
);
impl<'a> GenericValueCast<'a> for bool {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = <Self as Compile<'a>>::get_type(ctx);
engine::LLVMCreateGenericValueOfInt(ty.into(), self as c_ulonglong, 0).into()
}
}
fn from_generic(value: GenericValue<'a>, _: &'a Context) -> bool {
unsafe {
engine::LLVMGenericValueToInt(value.into(), 0)!= 0
}
}
}
generic_int!{some i8, u8}
generic_int!{some i16, u16}
generic_int!{some i32, u32}
generic_int!{some i64, u64} | /// Create a new execution engine with the given `Module` and options, or return a
/// description of the error.
fn new(module: &'a Module, options: Self::Options) -> Result<Self, CBox<str>>;
/// Add a module to the list of modules to interpret or compile. | random_line_split |
engine.rs | use libc::{c_int, c_uint, c_ulonglong, size_t};
use ffi::{core, target};
use ffi::execution_engine as engine;
use ffi::execution_engine::*;
use ffi::target_machine::LLVMCodeModel;
use cbox::CBox;
use std::marker::PhantomData;
use std::{mem, ptr};
use std::ops::*;
use compile::Compile;
use context::{Context, GetContext};
use module::Module;
use ty::{StructType, Type};
use util::{self, CastFrom};
use value::{Function, Value};
/// An abstract interface for implementation execution of LLVM modules.
///
/// This is designed to support both interpreter and just-in-time (JIT) compiler implementations.
pub trait ExecutionEngine<'a, 'b:'a> where LLVMExecutionEngineRef:From<&'b Self> {
/// The options given to this upon creation.
type Options : Copy;
/// Create a new execution engine with the given `Module` and options, or return a
/// description of the error.
fn new(module: &'a Module, options: Self::Options) -> Result<Self, CBox<str>>;
/// Add a module to the list of modules to interpret or compile.
fn add_module(&'b self, module: &'a Module) {
unsafe { engine::LLVMAddModule(self.into(), (&*module).into()) }
}
/// Remove a module from the list of modules to interpret or compile.
fn remove_module(&'b self, module: &'a Module) -> &'a Module {
unsafe {
let mut out = mem::uninitialized();
engine::LLVMRemoveModule(self.into(), module.into(), &mut out, ptr::null_mut());
out.into()
}
}
/// Execute all of the static constructors for this program.
fn run_static_constructors(&'b self) {
unsafe { engine::LLVMRunStaticConstructors(self.into()) }
}
/// Execute all of the static destructors for this program.
fn run_static_destructors(&'b self) {
unsafe { engine::LLVMRunStaticDestructors(self.into()) }
}
/// Attempt to find a function with the name given, or `None` if there wasn't
/// a function with that name.
fn find_function(&'b self, name: &str) -> Option<&'a Function> {
util::with_cstr(name, |c_name| unsafe {
let mut out = mem::zeroed();
engine::LLVMFindFunction(self.into(), c_name, &mut out);
mem::transmute(out)
})
}
/// Run `function` with the arguments given as ``GenericValue`s, then return the result as one.
///
/// Note that if this engine is a `JitEngine`, it only supports a small fraction of combinations
/// for the arguments and return value, so be warned.
///
/// To convert the arguments to `GenericValue`s, you should use the `GenericValueCast::to_generic` method.
/// To convert the return value from a `GenericValue`, you should use the `GenericValueCast::from_generic` method.
fn run_function(&'b self, function: &'a Function, args: &[GenericValue<'a>]) -> GenericValue<'a> {
let ptr = args.as_ptr() as *mut LLVMGenericValueRef;
unsafe { engine::LLVMRunFunction(self.into(), function.into(), args.len() as c_uint, ptr).into() }
}
/// Returns a pointer to the global value given.
///
/// This is marked as unsafe because the type cannot be guranteed to be the same as the
/// type of the global value at this point.
unsafe fn get_global<T>(&'b self, global: &'a Value) -> &'b T {
mem::transmute(engine::LLVMGetPointerToGlobal(self.into(), global.into()))
}
/// Returns a pointer to the global value with the name given.
///
/// This is marked as unsafe because the type cannot be guranteed to be the same as the
/// type of the global value at this point.
unsafe fn find_global<T>(&'b self, name: &str) -> Option<&'b T> {
util::with_cstr(name, |ptr|
mem::transmute(engine::LLVMGetGlobalValueAddress(self.into(), ptr))
)
}
/// Maps a global to a specific memory location.
unsafe fn add_global_mapping<T>(&'b self, global: &'a Value, addr: *const T) {
engine::LLVMAddGlobalMapping(self.into(), global.into(), mem::transmute(addr));
}
}
/// The options to pass to the MCJIT backend.
#[derive(Copy, Clone)]
pub struct JitOptions {
/// The degree to which optimizations should be done, between 0 and 3.
///
/// 0 represents no optimizations, 3 represents maximum optimization
pub opt_level: usize
}
/// The MCJIT backend, which compiles functions and values into machine code.
pub struct JitEngine<'a> {
engine: LLVMExecutionEngineRef,
marker: PhantomData<&'a ()>
}
native_ref!{contra JitEngine, engine: LLVMExecutionEngineRef}
impl<'a, 'b> JitEngine<'a> {
/// Run the closure `cb` with the machine code for the function `function`.
///
/// This will check that the types match at runtime when in debug mode, but not release mode.
/// You should make sure to use debug mode if you want it to error when the types don't match.
pub fn with_function<C, A, R>(&self, function: &'b Function, cb: C) where A:Compile<'b>, R:Compile<'b>, C:FnOnce(extern fn(A) -> R) {
if cfg!(not(ndebug)) {
let ctx = function.get_context();
let sig = function.get_signature();
assert_eq!(Type::get::<R>(ctx), sig.get_return());
let arg = Type::get::<A>(ctx);
if let Some(args) = StructType::cast(arg) {
assert_eq!(sig.get_params(), args.get_elements());
} else {
let nparams = sig.get_params().len();
if nparams == 1 | else if nparams == 0 {
assert_eq!(arg, Type::get::<()>(ctx));
} else {
panic!("array type arguments are not yet supported; use a tuple or struct instead");
}
}
}
unsafe {
cb(self.get_function::<A, R>(function));
}
}
/// Run the closure `cb` with the machine code for the function `function`.
pub unsafe fn with_function_unchecked<C, A, R>(&self, function: &'b Function, cb: C) where A:Compile<'b>, R:Compile<'b>, C:FnOnce(extern fn(A) -> R) {
cb(self.get_function::<A, R>(function));
}
/// Returns a pointer to the machine code for the function `function`.
///
/// This is marked as unsafe because the types given as arguments and return could be different
/// from their internal representation.
pub unsafe fn get_function<A, R>(&self, function: &'b Function) -> extern fn(A) -> R {
let ptr:&u8 = self.get_global(function);
mem::transmute(ptr)
}
}
impl<'a, 'b:'a> ExecutionEngine<'a, 'b> for JitEngine<'a> {
type Options = JitOptions;
fn new(module: &'a Module, options: JitOptions) -> Result<JitEngine<'a>, CBox<str>> {
unsafe {
let mut ee = mem::uninitialized();
let mut out = mem::zeroed();
engine::LLVMLinkInMCJIT();
if target::LLVM_InitializeNativeTarget() == 1 {
return Err("failed to initialize native target".into())
}
if target::LLVM_InitializeNativeAsmPrinter() == 1 {
return Err("failed to initialize native asm printer".into())
}
let mut options = LLVMMCJITCompilerOptions {
OptLevel: options.opt_level as c_uint,
CodeModel: LLVMCodeModel::LLVMCodeModelJITDefault,
NoFramePointerElim: 0,
EnableFastISel: 1,
MCJMM: ptr::null_mut()
};
let size = mem::size_of::<LLVMMCJITCompilerOptions>();
let result = engine::LLVMCreateMCJITCompilerForModule(&mut ee, (&*module).into(), &mut options, size as size_t, &mut out);
if result == 0 {
Ok(ee.into())
} else {
Err(CBox::new(out))
}
}
}
}
/// The interpreter backend
pub struct Interpreter<'a> {
engine: LLVMExecutionEngineRef,
marker: PhantomData<&'a ()>
}
native_ref!{contra Interpreter, engine: LLVMExecutionEngineRef}
impl<'a> Interpreter<'a> {
/// Run `function` with the arguments given as ``GenericValue`s, then return the result as one.
///
/// To convert the arguments to `GenericValue`s, you should use the `GenericValueCast::to_generic` method.
/// To convert the return value from a `GenericValue`, you should use the `GenericValueCast::from_generic` method.
pub fn run_function(&self, function: &'a Function, args: &[GenericValue<'a>]) -> GenericValue<'a> {
let ptr = args.as_ptr() as *mut LLVMGenericValueRef;
unsafe { engine::LLVMRunFunction(self.into(), function.into(), args.len() as c_uint, ptr).into() }
}
}
impl<'a, 'b:'a> ExecutionEngine<'a, 'b> for Interpreter<'a> {
type Options = ();
fn new(module: &'a Module, _: ()) -> Result<Interpreter<'a>, CBox<str>> {
unsafe {
let mut ee = mem::uninitialized();
let mut out = mem::zeroed();
engine::LLVMLinkInInterpreter();
let result = engine::LLVMCreateInterpreterForModule(&mut ee, (&*module).into(), &mut out);
if result == 0 {
Ok(ee.into())
} else {
Err(CBox::new(out))
}
}
}
}
/// A wrapped value that can be passed to an interpreted function or returned from one
pub struct GenericValue<'a> {
value: LLVMGenericValueRef,
marker: PhantomData<&'a ()>
}
native_ref!(contra GenericValue, value: LLVMGenericValueRef);
impl<'a> Drop for GenericValue<'a> {
fn drop(&mut self) {
unsafe {
engine::LLVMDisposeGenericValue(self.value)
}
}
}
/// A value that can be cast into a `GenericValue` and that a `GenericValue` can be cast into.
///
/// Both these methods require contexts because some `Type` constructors are needed for the
/// conversion and these constructors need a context.
pub trait GenericValueCast<'a> {
/// Create a `GenericValue` from this value.
fn to_generic(self, context: &'a Context) -> GenericValue<'a>;
/// Convert the `GenericValue` into a value of this type again.
fn from_generic(value: GenericValue<'a>, context: &'a Context) -> Self;
}
impl<'a> GenericValueCast<'a> for f64 {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = core::LLVMDoubleTypeInContext(ctx.into());
engine::LLVMCreateGenericValueOfFloat(ty, self).into()
}
}
fn from_generic(value: GenericValue<'a>, ctx: &'a Context) -> f64 {
unsafe {
let ty = core::LLVMDoubleTypeInContext(ctx.into());
engine::LLVMGenericValueToFloat(ty, value.into())
}
}
}
impl<'a> GenericValueCast<'a> for f32 {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = core::LLVMFloatTypeInContext(ctx.into());
engine::LLVMCreateGenericValueOfFloat(ty, self as f64).into()
}
}
fn from_generic(value: GenericValue<'a>, ctx: &'a Context) -> f32 {
unsafe {
let ty = core::LLVMFloatTypeInContext(ctx.into());
engine::LLVMGenericValueToFloat(ty, value.into()) as f32
}
}
}
macro_rules! generic_int(
($ty:ty, $signed:expr) => (
impl<'a> GenericValueCast<'a> for $ty {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = <Self as Compile<'a>>::get_type(ctx);
engine::LLVMCreateGenericValueOfInt(ty.into(), self as c_ulonglong, $signed as c_int).into()
}
}
fn from_generic(value: GenericValue<'a>, _: &'a Context) -> $ty {
unsafe {
engine::LLVMGenericValueToInt(value.into(), $signed as c_int) as $ty
}
}
}
);
(some $signed:ty, $unsigned:ty) => (
generic_int!{$signed, true}
generic_int!{$unsigned, false}
);
);
impl<'a> GenericValueCast<'a> for bool {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = <Self as Compile<'a>>::get_type(ctx);
engine::LLVMCreateGenericValueOfInt(ty.into(), self as c_ulonglong, 0).into()
}
}
fn from_generic(value: GenericValue<'a>, _: &'a Context) -> bool {
unsafe {
engine::LLVMGenericValueToInt(value.into(), 0)!= 0
}
}
}
generic_int!{some i8, u8}
generic_int!{some i16, u16}
generic_int!{some i32, u32}
generic_int!{some i64, u64}
| {
assert_eq!(arg, sig.get_params()[0]);
} | conditional_block |
engine.rs | use libc::{c_int, c_uint, c_ulonglong, size_t};
use ffi::{core, target};
use ffi::execution_engine as engine;
use ffi::execution_engine::*;
use ffi::target_machine::LLVMCodeModel;
use cbox::CBox;
use std::marker::PhantomData;
use std::{mem, ptr};
use std::ops::*;
use compile::Compile;
use context::{Context, GetContext};
use module::Module;
use ty::{StructType, Type};
use util::{self, CastFrom};
use value::{Function, Value};
/// An abstract interface for implementation execution of LLVM modules.
///
/// This is designed to support both interpreter and just-in-time (JIT) compiler implementations.
pub trait ExecutionEngine<'a, 'b:'a> where LLVMExecutionEngineRef:From<&'b Self> {
/// The options given to this upon creation.
type Options : Copy;
/// Create a new execution engine with the given `Module` and options, or return a
/// description of the error.
fn new(module: &'a Module, options: Self::Options) -> Result<Self, CBox<str>>;
/// Add a module to the list of modules to interpret or compile.
fn add_module(&'b self, module: &'a Module) {
unsafe { engine::LLVMAddModule(self.into(), (&*module).into()) }
}
/// Remove a module from the list of modules to interpret or compile.
fn remove_module(&'b self, module: &'a Module) -> &'a Module {
unsafe {
let mut out = mem::uninitialized();
engine::LLVMRemoveModule(self.into(), module.into(), &mut out, ptr::null_mut());
out.into()
}
}
/// Execute all of the static constructors for this program.
fn run_static_constructors(&'b self) {
unsafe { engine::LLVMRunStaticConstructors(self.into()) }
}
/// Execute all of the static destructors for this program.
fn run_static_destructors(&'b self) {
unsafe { engine::LLVMRunStaticDestructors(self.into()) }
}
/// Attempt to find a function with the name given, or `None` if there wasn't
/// a function with that name.
fn find_function(&'b self, name: &str) -> Option<&'a Function> {
util::with_cstr(name, |c_name| unsafe {
let mut out = mem::zeroed();
engine::LLVMFindFunction(self.into(), c_name, &mut out);
mem::transmute(out)
})
}
/// Run `function` with the arguments given as ``GenericValue`s, then return the result as one.
///
/// Note that if this engine is a `JitEngine`, it only supports a small fraction of combinations
/// for the arguments and return value, so be warned.
///
/// To convert the arguments to `GenericValue`s, you should use the `GenericValueCast::to_generic` method.
/// To convert the return value from a `GenericValue`, you should use the `GenericValueCast::from_generic` method.
fn run_function(&'b self, function: &'a Function, args: &[GenericValue<'a>]) -> GenericValue<'a> {
let ptr = args.as_ptr() as *mut LLVMGenericValueRef;
unsafe { engine::LLVMRunFunction(self.into(), function.into(), args.len() as c_uint, ptr).into() }
}
/// Returns a pointer to the global value given.
///
/// This is marked as unsafe because the type cannot be guranteed to be the same as the
/// type of the global value at this point.
unsafe fn get_global<T>(&'b self, global: &'a Value) -> &'b T {
mem::transmute(engine::LLVMGetPointerToGlobal(self.into(), global.into()))
}
/// Returns a pointer to the global value with the name given.
///
/// This is marked as unsafe because the type cannot be guranteed to be the same as the
/// type of the global value at this point.
unsafe fn find_global<T>(&'b self, name: &str) -> Option<&'b T> {
util::with_cstr(name, |ptr|
mem::transmute(engine::LLVMGetGlobalValueAddress(self.into(), ptr))
)
}
/// Maps a global to a specific memory location.
unsafe fn add_global_mapping<T>(&'b self, global: &'a Value, addr: *const T) {
engine::LLVMAddGlobalMapping(self.into(), global.into(), mem::transmute(addr));
}
}
/// The options to pass to the MCJIT backend.
#[derive(Copy, Clone)]
pub struct JitOptions {
/// The degree to which optimizations should be done, between 0 and 3.
///
/// 0 represents no optimizations, 3 represents maximum optimization
pub opt_level: usize
}
/// The MCJIT backend, which compiles functions and values into machine code.
pub struct JitEngine<'a> {
engine: LLVMExecutionEngineRef,
marker: PhantomData<&'a ()>
}
native_ref!{contra JitEngine, engine: LLVMExecutionEngineRef}
impl<'a, 'b> JitEngine<'a> {
/// Run the closure `cb` with the machine code for the function `function`.
///
/// This will check that the types match at runtime when in debug mode, but not release mode.
/// You should make sure to use debug mode if you want it to error when the types don't match.
pub fn with_function<C, A, R>(&self, function: &'b Function, cb: C) where A:Compile<'b>, R:Compile<'b>, C:FnOnce(extern fn(A) -> R) {
if cfg!(not(ndebug)) {
let ctx = function.get_context();
let sig = function.get_signature();
assert_eq!(Type::get::<R>(ctx), sig.get_return());
let arg = Type::get::<A>(ctx);
if let Some(args) = StructType::cast(arg) {
assert_eq!(sig.get_params(), args.get_elements());
} else {
let nparams = sig.get_params().len();
if nparams == 1 {
assert_eq!(arg, sig.get_params()[0]);
} else if nparams == 0 {
assert_eq!(arg, Type::get::<()>(ctx));
} else {
panic!("array type arguments are not yet supported; use a tuple or struct instead");
}
}
}
unsafe {
cb(self.get_function::<A, R>(function));
}
}
/// Run the closure `cb` with the machine code for the function `function`.
pub unsafe fn with_function_unchecked<C, A, R>(&self, function: &'b Function, cb: C) where A:Compile<'b>, R:Compile<'b>, C:FnOnce(extern fn(A) -> R) {
cb(self.get_function::<A, R>(function));
}
/// Returns a pointer to the machine code for the function `function`.
///
/// This is marked as unsafe because the types given as arguments and return could be different
/// from their internal representation.
pub unsafe fn get_function<A, R>(&self, function: &'b Function) -> extern fn(A) -> R {
let ptr:&u8 = self.get_global(function);
mem::transmute(ptr)
}
}
impl<'a, 'b:'a> ExecutionEngine<'a, 'b> for JitEngine<'a> {
type Options = JitOptions;
fn new(module: &'a Module, options: JitOptions) -> Result<JitEngine<'a>, CBox<str>> {
unsafe {
let mut ee = mem::uninitialized();
let mut out = mem::zeroed();
engine::LLVMLinkInMCJIT();
if target::LLVM_InitializeNativeTarget() == 1 {
return Err("failed to initialize native target".into())
}
if target::LLVM_InitializeNativeAsmPrinter() == 1 {
return Err("failed to initialize native asm printer".into())
}
let mut options = LLVMMCJITCompilerOptions {
OptLevel: options.opt_level as c_uint,
CodeModel: LLVMCodeModel::LLVMCodeModelJITDefault,
NoFramePointerElim: 0,
EnableFastISel: 1,
MCJMM: ptr::null_mut()
};
let size = mem::size_of::<LLVMMCJITCompilerOptions>();
let result = engine::LLVMCreateMCJITCompilerForModule(&mut ee, (&*module).into(), &mut options, size as size_t, &mut out);
if result == 0 {
Ok(ee.into())
} else {
Err(CBox::new(out))
}
}
}
}
/// The interpreter backend
pub struct Interpreter<'a> {
engine: LLVMExecutionEngineRef,
marker: PhantomData<&'a ()>
}
native_ref!{contra Interpreter, engine: LLVMExecutionEngineRef}
impl<'a> Interpreter<'a> {
/// Run `function` with the arguments given as ``GenericValue`s, then return the result as one.
///
/// To convert the arguments to `GenericValue`s, you should use the `GenericValueCast::to_generic` method.
/// To convert the return value from a `GenericValue`, you should use the `GenericValueCast::from_generic` method.
pub fn run_function(&self, function: &'a Function, args: &[GenericValue<'a>]) -> GenericValue<'a> {
let ptr = args.as_ptr() as *mut LLVMGenericValueRef;
unsafe { engine::LLVMRunFunction(self.into(), function.into(), args.len() as c_uint, ptr).into() }
}
}
impl<'a, 'b:'a> ExecutionEngine<'a, 'b> for Interpreter<'a> {
type Options = ();
fn new(module: &'a Module, _: ()) -> Result<Interpreter<'a>, CBox<str>> {
unsafe {
let mut ee = mem::uninitialized();
let mut out = mem::zeroed();
engine::LLVMLinkInInterpreter();
let result = engine::LLVMCreateInterpreterForModule(&mut ee, (&*module).into(), &mut out);
if result == 0 {
Ok(ee.into())
} else {
Err(CBox::new(out))
}
}
}
}
/// A wrapped value that can be passed to an interpreted function or returned from one
pub struct GenericValue<'a> {
value: LLVMGenericValueRef,
marker: PhantomData<&'a ()>
}
native_ref!(contra GenericValue, value: LLVMGenericValueRef);
impl<'a> Drop for GenericValue<'a> {
fn drop(&mut self) {
unsafe {
engine::LLVMDisposeGenericValue(self.value)
}
}
}
/// A value that can be cast into a `GenericValue` and that a `GenericValue` can be cast into.
///
/// Both these methods require contexts because some `Type` constructors are needed for the
/// conversion and these constructors need a context.
pub trait GenericValueCast<'a> {
/// Create a `GenericValue` from this value.
fn to_generic(self, context: &'a Context) -> GenericValue<'a>;
/// Convert the `GenericValue` into a value of this type again.
fn from_generic(value: GenericValue<'a>, context: &'a Context) -> Self;
}
impl<'a> GenericValueCast<'a> for f64 {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = core::LLVMDoubleTypeInContext(ctx.into());
engine::LLVMCreateGenericValueOfFloat(ty, self).into()
}
}
fn from_generic(value: GenericValue<'a>, ctx: &'a Context) -> f64 {
unsafe {
let ty = core::LLVMDoubleTypeInContext(ctx.into());
engine::LLVMGenericValueToFloat(ty, value.into())
}
}
}
impl<'a> GenericValueCast<'a> for f32 {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = core::LLVMFloatTypeInContext(ctx.into());
engine::LLVMCreateGenericValueOfFloat(ty, self as f64).into()
}
}
fn from_generic(value: GenericValue<'a>, ctx: &'a Context) -> f32 {
unsafe {
let ty = core::LLVMFloatTypeInContext(ctx.into());
engine::LLVMGenericValueToFloat(ty, value.into()) as f32
}
}
}
macro_rules! generic_int(
($ty:ty, $signed:expr) => (
impl<'a> GenericValueCast<'a> for $ty {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = <Self as Compile<'a>>::get_type(ctx);
engine::LLVMCreateGenericValueOfInt(ty.into(), self as c_ulonglong, $signed as c_int).into()
}
}
fn from_generic(value: GenericValue<'a>, _: &'a Context) -> $ty {
unsafe {
engine::LLVMGenericValueToInt(value.into(), $signed as c_int) as $ty
}
}
}
);
(some $signed:ty, $unsigned:ty) => (
generic_int!{$signed, true}
generic_int!{$unsigned, false}
);
);
impl<'a> GenericValueCast<'a> for bool {
fn to_generic(self, ctx: &'a Context) -> GenericValue<'a> {
unsafe {
let ty = <Self as Compile<'a>>::get_type(ctx);
engine::LLVMCreateGenericValueOfInt(ty.into(), self as c_ulonglong, 0).into()
}
}
fn | (value: GenericValue<'a>, _: &'a Context) -> bool {
unsafe {
engine::LLVMGenericValueToInt(value.into(), 0)!= 0
}
}
}
generic_int!{some i8, u8}
generic_int!{some i16, u16}
generic_int!{some i32, u32}
generic_int!{some i64, u64}
| from_generic | identifier_name |
main.rs | #[macro_use]
extern crate scad_generator;
extern crate scad_util as su;
use scad_generator::*;
fn ir_screwholes(depth: f32) -> ScadObject
{
let screw_distance = 38.;
let screw_diameter = 4.;
//TODO add nut
let screwhole = scad!(Cylinder(depth, Diameter(screw_diameter)));
let translated = scad!(Translate(vec3(screw_distance, 0., 0.));screwhole);
scad!(Union;
{
translated.clone(),
scad!(Mirror(vec3(1., 0., 0.)); translated)
})
}
pub fn main()
{
let mut sfile = ScadFile::new();
sfile.set_detail(50);
sfile.add_object(ir_screwholes(10.));
//Save the scad code to a file | sfile.write_to_file(String::from("out.scad"));
} | random_line_split |
|
main.rs | #[macro_use]
extern crate scad_generator;
extern crate scad_util as su;
use scad_generator::*;
fn ir_screwholes(depth: f32) -> ScadObject
|
pub fn main()
{
let mut sfile = ScadFile::new();
sfile.set_detail(50);
sfile.add_object(ir_screwholes(10.));
//Save the scad code to a file
sfile.write_to_file(String::from("out.scad"));
}
| {
let screw_distance = 38.;
let screw_diameter = 4.;
//TODO add nut
let screwhole = scad!(Cylinder(depth, Diameter(screw_diameter)));
let translated = scad!(Translate(vec3(screw_distance, 0., 0.));screwhole);
scad!(Union;
{
translated.clone(),
scad!(Mirror(vec3(1., 0., 0.)); translated)
})
} | identifier_body |
main.rs | #[macro_use]
extern crate scad_generator;
extern crate scad_util as su;
use scad_generator::*;
fn ir_screwholes(depth: f32) -> ScadObject
{
let screw_distance = 38.;
let screw_diameter = 4.;
//TODO add nut
let screwhole = scad!(Cylinder(depth, Diameter(screw_diameter)));
let translated = scad!(Translate(vec3(screw_distance, 0., 0.));screwhole);
scad!(Union;
{
translated.clone(),
scad!(Mirror(vec3(1., 0., 0.)); translated)
})
}
pub fn | ()
{
let mut sfile = ScadFile::new();
sfile.set_detail(50);
sfile.add_object(ir_screwholes(10.));
//Save the scad code to a file
sfile.write_to_file(String::from("out.scad"));
}
| main | identifier_name |
backtrace.rs | in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need to consult both the local and dynamic symbol tables.
/// With that in mind, here's our options of translating an address to
/// a symbol.
///
/// * Use dladdr(). The original backtrace()-based idea actually uses dladdr()
/// behind the scenes to translate, and this is why backtrace() was not used.
/// Conveniently, this method works fantastically on OSX. It appears dladdr()
/// uses magic to consult the local symbol table, or we're putting everything
/// in the dynamic symbol table anyway. Regardless, for OSX, this is the
/// method used for translation. It's provided by the system and easy to do.o
///
/// Sadly, all other systems have a dladdr() implementation that does not
/// consult the local symbol table. This means that most functions are blank
/// because they don't have symbols. This means that we need another solution.
///
/// * Use unw_get_proc_name(). This is part of the libunwind api (not the
/// libgcc_s version of the libunwind api), but involves taking a dependency
/// to libunwind. We may pursue this route in the future if we bundle
/// libunwind, but libunwind was unwieldy enough that it was not chosen at
/// this time to provide this functionality.
///
/// * Shell out to a utility like `readelf`. Crazy though it may sound, it's a
/// semi-reasonable solution. The stdlib already knows how to spawn processes,
/// so in theory it could invoke readelf, parse the output, and consult the
/// local/dynamic symbol tables from there. This ended up not getting chosen
/// due to the craziness of the idea plus the advent of the next option.
///
/// * Use `libbacktrace`. It turns out that this is a small library bundled in
/// the gcc repository which provides backtrace and symbol translation
/// functionality. All we really need from it is the backtrace functionality,
/// and we only really need this on everything that's not OSX, so this is the
/// chosen route for now.
///
/// In summary, the current situation uses libgcc_s to get a trace of stack
/// pointers, and we use dladdr() or libbacktrace to translate these addresses
/// to symbols. This is a bit of a hokey implementation as-is, but it works for
/// all unix platforms we support right now, so it at least gets the job done.
use prelude::v1::*;
use os::unix::prelude::*;
use ffi::{CStr, AsOsStr};
use old_io::IoResult;
use libc;
use mem;
use str;
use sync::{StaticMutex, MUTEX_INIT};
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is public
///
/// As mentioned in a huge comment block above, backtrace doesn't
/// play well with green threads, so while it is extremely nice
/// and simple to use it should be used only on iOS devices as the
/// only viable option.
#[cfg(all(target_os = "ios", target_arch = "arm"))]
#[inline(never)]
pub fn write(w: &mut Writer) -> IoResult<()> {
use result;
extern {
fn backtrace(buf: *mut *mut libc::c_void,
sz: libc::c_int) -> libc::c_int;
}
// while it doesn't requires lock for work as everything is
// local, it still displays much nicer backtraces when a
// couple of tasks panic simultaneously
static LOCK: StaticMutex = MUTEX_INIT;
let _g = unsafe { LOCK.lock() };
try!(writeln!(w, "stack backtrace:"));
// 100 lines should be enough
const SIZE: uint = 100;
let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()};
let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as uint};
// skipping the first one as it is write itself
let iter = (1..cnt).map(|i| {
print(w, i as int, buf[i], buf[i])
});
result::fold(iter, (), |_, _| ())
}
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
#[inline(never)] // if we know this is a function call, we can skip it when
// tracing
pub fn write(w: &mut Writer) -> IoResult<()> {
use old_io::IoError;
struct Context<'a> {
idx: int,
writer: &'a mut (Writer+'a),
last_error: Option<IoError>,
}
// When using libbacktrace, we use some necessary global state, so we
// need to prevent more than one thread from entering this block. This
// is semi-reasonable in terms of printing anyway, and we know that all
// I/O done here is blocking I/O, not green I/O, so we don't have to
// worry about this being a native vs green mutex.
static LOCK: StaticMutex = MUTEX_INIT;
let _g = unsafe { LOCK.lock() };
try!(writeln!(w, "stack backtrace:"));
let mut cx = Context { writer: w, last_error: None, idx: 0 };
return match unsafe {
uw::_Unwind_Backtrace(trace_fn,
&mut cx as *mut Context as *mut libc::c_void)
} {
uw::_URC_NO_REASON => {
match cx.last_error {
Some(err) => Err(err),
None => Ok(())
}
}
_ => Ok(()),
};
extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code | // pointer points *outside* of the calling function, and by
// unwinding it we go back to the original function.
let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
ip
} else {
unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
};
// Don't print out the first few frames (they're not user frames)
cx.idx += 1;
if cx.idx <= 0 { return uw::_URC_NO_REASON }
// Don't print ginormous backtraces
if cx.idx > 100 {
match write!(cx.writer, "... <frames omitted>\n") {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
return uw::_URC_FAILURE
}
// Once we hit an error, stop trying to print more frames
if cx.last_error.is_some() { return uw::_URC_FAILURE }
match print(cx.writer, cx.idx, ip, symaddr) {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
// keep going
return uw::_URC_NO_REASON
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void,
_symaddr: *mut libc::c_void) -> IoResult<()> {
use intrinsics;
#[repr(C)]
struct Dl_info {
dli_fname: *const libc::c_char,
dli_fbase: *mut libc::c_void,
dli_sname: *const libc::c_char,
dli_saddr: *mut libc::c_void,
}
extern {
fn dladdr(addr: *const libc::c_void,
info: *mut Dl_info) -> libc::c_int;
}
let mut info: Dl_info = unsafe { intrinsics::init() };
if unsafe { dladdr(addr, &mut info) == 0 } {
output(w, idx,addr, None)
} else {
output(w, idx, addr, Some(unsafe {
CStr::from_ptr(info.dli_sname).to_bytes()
}))
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void,
symaddr: *mut libc::c_void) -> IoResult<()> {
use env;
use ptr;
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
////////////////////////////////////////////////////////////////////////
type backtrace_syminfo_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
symname: *const libc::c_char,
symval: libc::uintptr_t,
symsize: libc::uintptr_t);
type backtrace_full_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
function: *const libc::c_char) -> libc::c_int;
type backtrace_error_callback =
extern "C" fn(data: *mut libc::c_void,
msg: *const libc::c_char,
errnum: libc::c_int);
enum backtrace_state {}
#[link(name = "backtrace", kind = "static")]
#[cfg(not(test))]
extern {}
extern {
fn backtrace_create_state(filename: *const libc::c_char,
threaded: libc::c_int,
error: backtrace_error_callback,
data: *mut libc::c_void)
-> *mut backtrace_state;
fn backtrace_syminfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_syminfo_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
fn backtrace_pcinfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_full_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
}
////////////////////////////////////////////////////////////////////////
// helper callbacks
////////////////////////////////////////////////////////////////////////
type FileLine = (*const libc::c_char, libc::c_int);
extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char,
_errnum: libc::c_int) {
// do nothing for now
}
extern fn syminfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
symname: *const libc::c_char,
_symval: libc::uintptr_t,
_symsize: libc::uintptr_t) {
let slot = data as *mut *const libc::c_char;
unsafe { *slot = symname; }
}
extern fn pcinfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
_function: *const libc::c_char) -> libc::c_int {
if!filename.is_null() {
let slot = data as *mut &mut [FileLine];
let buffer = unsafe {ptr::read(slot)};
// if the buffer is not full, add file:line to the buffer
// and adjust the buffer for next possible calls to pcinfo_cb.
if!buffer.is_empty() {
buffer[0] = (filename, lineno);
unsafe { ptr::write(slot, &mut buffer[1..]); }
}
}
0
}
// The libbacktrace API supports creating a state, but it does not
// support destroying a state. I personally take this to mean that a
// state is meant to be created and then live forever.
//
// I would love to register an at_exit() handler which cleans up this
// state, but libbacktrace provides no way to do so.
//
// With these constraints, this function has a statically cached state
// that is calculated the first time this is requested. Remember that
// backtracing all happens serially (one global lock).
//
// An additionally oddity in this function is that we initialize the
// filename via self_exe_name() to pass to libbacktrace. It turns out
// that on Linux libbacktrace seamlessly gets the filename of the
// current executable, but this fails on freebsd. by always providing
// it, we make sure that libbacktrace never has a reason to not look up
// the symbols. The libbacktrace API also states that the filename must
// be in "permanent memory", so we copy it to a static and then use the
// static as the pointer.
//
// FIXME: We also call self_exe_name() on DragonFly BSD. I haven't
// tested if this is required or not.
unsafe fn init_state() -> *mut backtrace_state {
static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256];
if!STATE.is_null() { return STATE }
let selfname = if cfg!(target_os = "freebsd") ||
cfg!(target_os = "dragonfly") ||
cfg!(target_os = "bitrig") ||
cfg!(target_os = "openbsd") {
env::current_exe().ok()
} else {
None
};
let filename = match selfname {
Some(path) => {
let bytes = path.as_os_str().as_bytes();
if bytes.len() < LAST_FILENAME.len() {
let i = bytes.iter();
for (slot, val) in LAST_FILENAME.iter_mut().zip(i) {
*slot = *val as libc::c_char;
}
LAST_FILENAME.as_ptr()
} else {
ptr::null()
}
}
None => ptr::null(),
};
STATE = backtrace_create_state(filename, 0, error_cb,
ptr::null_mut());
return STATE
}
////////////////////////////////////////////////////////////////////////
// translation
////////////////////////////////////////////////////////////////////////
// backtrace errors are currently swept under the rug, only I/O
// errors are reported
let state = unsafe { init_state() };
if state.is_null() {
return output(w, idx, addr, None)
}
let mut data = ptr::null();
let data_addr = &mut data as *mut *const libc::c_char;
let ret = unsafe {
backtrace_syminfo(state, symaddr as libc::uintptr_t,
syminfo_cb, error_cb,
data_addr as *mut libc::c_void)
};
if ret == 0 || data.is_null() {
try!(output(w, idx, addr, None));
} else {
try!(output(w, idx, addr, Some(unsafe { CStr::from_ptr(data).to_bytes() })));
}
// pcinfo may return an arbitrary number of file:line pairs,
// in the order of stack trace (i.e. inlined calls first).
// in order to avoid allocation, we stack-allocate a fixed size of entries.
const FILELINE_SIZE: usize = 32;
let mut fileline_buf = [(ptr::null(), -1); FILELINE_SIZE];
let ret;
let fileline_count;
{
let mut fileline_win: &mut [FileLine] = &mut fileline_buf;
let fileline_addr = &mut fileline_win as *mut &mut [FileLine];
ret = unsafe {
backtrace_pcinfo(state, addr as libc::uintptr_t,
pcinfo_cb, error_cb,
fileline_addr as *mut libc::c_void)
};
fileline_count = FILELINE_SIZE - fileline_win.len();
}
if ret == 0 {
for (i, &(file, line)) in fileline_buf[..fileline_count].iter().enumerate() {
if file.is_null() { continue; } // just to be sure
let file = unsafe { CStr::from_ptr(file).to_bytes() };
try!(output_fileline(w, file, line, i == FILELINE_SIZE - 1));
}
}
Ok(())
}
// Finally, after all that work above, we can emit a symbol.
fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void,
s: Option<&[u8]>) -> IoResult<()> {
try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH));
match s.and_then(|s| str::from_utf8(s).ok()) {
Some(string) => try!(demangle(w, string)),
None => try!(write!(w, "<unknown>")),
}
w.write_all(&['\n' as u8])
}
#[allow(dead_code)]
fn output_fileline(w: &mut Writer, file: &[u8], line: libc::c_int,
more: bool) -> IoResult<()> {
let file = str::from_utf8(file).ok().unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more {
try!(write!(w, " <... and possibly more>"));
}
w.write_all(&['\n' as u8])
}
/// Unwind library interface used for backtraces
///
/// Note that dead code is allowed as here are just bindings
/// iOS doesn't use all of them it but adding more
/// platform-specific configs pollutes the code too much
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(dead_code)]
mod uw {
pub use self::_Unwind_Reason_Code::*;
use libc;
#[repr(C)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
_URC_FAILURE = 9, // used only by ARM EABI
}
pub enum _Unwind_Context {}
pub type _Unwind_Trace_Fn =
extern fn(ctx: *mut _Unwind_Context,
arg: *mut libc::c_void) -> _Unwind_Reason_Code;
extern {
// No native _Unwind_Backtrace on iOS
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
trace_argument: *mut libc::c_void)
-> _Unwind_Reason_Code;
// available since GCC 4.2.0, should be fine for our purpose
#[cfg(all(not(all(target_os = "android", target_arch = "arm")),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context,
ip_before_insn: *mut libc::c_int)
-> libc::uintptr_t;
#[cfg(all(not(target_os = "android"),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
-> *mut libc::c_void;
}
// On android, the function _Unwind_GetIP is a macro, and this is the
// expansion of the macro. This is all copy/pasted directly from the
// header file with the definition of _Unwind_GetIP.
| {
let cx: &mut Context = unsafe { mem::transmute(arg) };
let mut ip_before_insn = 0;
let mut ip = unsafe {
uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void
};
if !ip.is_null() && ip_before_insn == 0 {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
}
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and
// it appears to work fine without it, so we only use
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
// This is often because panic involves the last instruction of a
// function being "call std::rt::begin_unwind", with no ret
// instructions after it. This means that the return instruction | identifier_body |
backtrace.rs | which in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need to consult both the local and dynamic symbol tables.
/// With that in mind, here's our options of translating an address to
/// a symbol.
///
/// * Use dladdr(). The original backtrace()-based idea actually uses dladdr()
/// behind the scenes to translate, and this is why backtrace() was not used.
/// Conveniently, this method works fantastically on OSX. It appears dladdr()
/// uses magic to consult the local symbol table, or we're putting everything
/// in the dynamic symbol table anyway. Regardless, for OSX, this is the
/// method used for translation. It's provided by the system and easy to do.o
///
/// Sadly, all other systems have a dladdr() implementation that does not
/// consult the local symbol table. This means that most functions are blank
/// because they don't have symbols. This means that we need another solution.
///
/// * Use unw_get_proc_name(). This is part of the libunwind api (not the
/// libgcc_s version of the libunwind api), but involves taking a dependency
/// to libunwind. We may pursue this route in the future if we bundle
/// libunwind, but libunwind was unwieldy enough that it was not chosen at
/// this time to provide this functionality.
///
/// * Shell out to a utility like `readelf`. Crazy though it may sound, it's a | /// semi-reasonable solution. The stdlib already knows how to spawn processes,
/// so in theory it could invoke readelf, parse the output, and consult the
/// local/dynamic symbol tables from there. This ended up not getting chosen
/// due to the craziness of the idea plus the advent of the next option.
///
/// * Use `libbacktrace`. It turns out that this is a small library bundled in
/// the gcc repository which provides backtrace and symbol translation
/// functionality. All we really need from it is the backtrace functionality,
/// and we only really need this on everything that's not OSX, so this is the
/// chosen route for now.
///
/// In summary, the current situation uses libgcc_s to get a trace of stack
/// pointers, and we use dladdr() or libbacktrace to translate these addresses
/// to symbols. This is a bit of a hokey implementation as-is, but it works for
/// all unix platforms we support right now, so it at least gets the job done.
use prelude::v1::*;
use os::unix::prelude::*;
use ffi::{CStr, AsOsStr};
use old_io::IoResult;
use libc;
use mem;
use str;
use sync::{StaticMutex, MUTEX_INIT};
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is public
///
/// As mentioned in a huge comment block above, backtrace doesn't
/// play well with green threads, so while it is extremely nice
/// and simple to use it should be used only on iOS devices as the
/// only viable option.
#[cfg(all(target_os = "ios", target_arch = "arm"))]
#[inline(never)]
pub fn write(w: &mut Writer) -> IoResult<()> {
use result;
extern {
fn backtrace(buf: *mut *mut libc::c_void,
sz: libc::c_int) -> libc::c_int;
}
// while it doesn't requires lock for work as everything is
// local, it still displays much nicer backtraces when a
// couple of tasks panic simultaneously
static LOCK: StaticMutex = MUTEX_INIT;
let _g = unsafe { LOCK.lock() };
try!(writeln!(w, "stack backtrace:"));
// 100 lines should be enough
const SIZE: uint = 100;
let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()};
let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as uint};
// skipping the first one as it is write itself
let iter = (1..cnt).map(|i| {
print(w, i as int, buf[i], buf[i])
});
result::fold(iter, (), |_, _| ())
}
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
#[inline(never)] // if we know this is a function call, we can skip it when
// tracing
pub fn write(w: &mut Writer) -> IoResult<()> {
use old_io::IoError;
struct Context<'a> {
idx: int,
writer: &'a mut (Writer+'a),
last_error: Option<IoError>,
}
// When using libbacktrace, we use some necessary global state, so we
// need to prevent more than one thread from entering this block. This
// is semi-reasonable in terms of printing anyway, and we know that all
// I/O done here is blocking I/O, not green I/O, so we don't have to
// worry about this being a native vs green mutex.
static LOCK: StaticMutex = MUTEX_INIT;
let _g = unsafe { LOCK.lock() };
try!(writeln!(w, "stack backtrace:"));
let mut cx = Context { writer: w, last_error: None, idx: 0 };
return match unsafe {
uw::_Unwind_Backtrace(trace_fn,
&mut cx as *mut Context as *mut libc::c_void)
} {
uw::_URC_NO_REASON => {
match cx.last_error {
Some(err) => Err(err),
None => Ok(())
}
}
_ => Ok(()),
};
extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code {
let cx: &mut Context = unsafe { mem::transmute(arg) };
let mut ip_before_insn = 0;
let mut ip = unsafe {
uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void
};
if!ip.is_null() && ip_before_insn == 0 {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
}
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and
// it appears to work fine without it, so we only use
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
// This is often because panic involves the last instruction of a
// function being "call std::rt::begin_unwind", with no ret
// instructions after it. This means that the return instruction
// pointer points *outside* of the calling function, and by
// unwinding it we go back to the original function.
let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
ip
} else {
unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
};
// Don't print out the first few frames (they're not user frames)
cx.idx += 1;
if cx.idx <= 0 { return uw::_URC_NO_REASON }
// Don't print ginormous backtraces
if cx.idx > 100 {
match write!(cx.writer, "... <frames omitted>\n") {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
return uw::_URC_FAILURE
}
// Once we hit an error, stop trying to print more frames
if cx.last_error.is_some() { return uw::_URC_FAILURE }
match print(cx.writer, cx.idx, ip, symaddr) {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
// keep going
return uw::_URC_NO_REASON
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void,
_symaddr: *mut libc::c_void) -> IoResult<()> {
use intrinsics;
#[repr(C)]
struct Dl_info {
dli_fname: *const libc::c_char,
dli_fbase: *mut libc::c_void,
dli_sname: *const libc::c_char,
dli_saddr: *mut libc::c_void,
}
extern {
fn dladdr(addr: *const libc::c_void,
info: *mut Dl_info) -> libc::c_int;
}
let mut info: Dl_info = unsafe { intrinsics::init() };
if unsafe { dladdr(addr, &mut info) == 0 } {
output(w, idx,addr, None)
} else {
output(w, idx, addr, Some(unsafe {
CStr::from_ptr(info.dli_sname).to_bytes()
}))
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void,
symaddr: *mut libc::c_void) -> IoResult<()> {
use env;
use ptr;
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
////////////////////////////////////////////////////////////////////////
type backtrace_syminfo_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
symname: *const libc::c_char,
symval: libc::uintptr_t,
symsize: libc::uintptr_t);
type backtrace_full_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
function: *const libc::c_char) -> libc::c_int;
type backtrace_error_callback =
extern "C" fn(data: *mut libc::c_void,
msg: *const libc::c_char,
errnum: libc::c_int);
enum backtrace_state {}
#[link(name = "backtrace", kind = "static")]
#[cfg(not(test))]
extern {}
extern {
fn backtrace_create_state(filename: *const libc::c_char,
threaded: libc::c_int,
error: backtrace_error_callback,
data: *mut libc::c_void)
-> *mut backtrace_state;
fn backtrace_syminfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_syminfo_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
fn backtrace_pcinfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_full_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
}
////////////////////////////////////////////////////////////////////////
// helper callbacks
////////////////////////////////////////////////////////////////////////
type FileLine = (*const libc::c_char, libc::c_int);
extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char,
_errnum: libc::c_int) {
// do nothing for now
}
extern fn syminfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
symname: *const libc::c_char,
_symval: libc::uintptr_t,
_symsize: libc::uintptr_t) {
let slot = data as *mut *const libc::c_char;
unsafe { *slot = symname; }
}
extern fn pcinfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
_function: *const libc::c_char) -> libc::c_int {
if!filename.is_null() {
let slot = data as *mut &mut [FileLine];
let buffer = unsafe {ptr::read(slot)};
// if the buffer is not full, add file:line to the buffer
// and adjust the buffer for next possible calls to pcinfo_cb.
if!buffer.is_empty() {
buffer[0] = (filename, lineno);
unsafe { ptr::write(slot, &mut buffer[1..]); }
}
}
0
}
// The libbacktrace API supports creating a state, but it does not
// support destroying a state. I personally take this to mean that a
// state is meant to be created and then live forever.
//
// I would love to register an at_exit() handler which cleans up this
// state, but libbacktrace provides no way to do so.
//
// With these constraints, this function has a statically cached state
// that is calculated the first time this is requested. Remember that
// backtracing all happens serially (one global lock).
//
// An additionally oddity in this function is that we initialize the
// filename via self_exe_name() to pass to libbacktrace. It turns out
// that on Linux libbacktrace seamlessly gets the filename of the
// current executable, but this fails on freebsd. by always providing
// it, we make sure that libbacktrace never has a reason to not look up
// the symbols. The libbacktrace API also states that the filename must
// be in "permanent memory", so we copy it to a static and then use the
// static as the pointer.
//
// FIXME: We also call self_exe_name() on DragonFly BSD. I haven't
// tested if this is required or not.
unsafe fn init_state() -> *mut backtrace_state {
static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256];
if!STATE.is_null() { return STATE }
let selfname = if cfg!(target_os = "freebsd") ||
cfg!(target_os = "dragonfly") ||
cfg!(target_os = "bitrig") ||
cfg!(target_os = "openbsd") {
env::current_exe().ok()
} else {
None
};
let filename = match selfname {
Some(path) => {
let bytes = path.as_os_str().as_bytes();
if bytes.len() < LAST_FILENAME.len() {
let i = bytes.iter();
for (slot, val) in LAST_FILENAME.iter_mut().zip(i) {
*slot = *val as libc::c_char;
}
LAST_FILENAME.as_ptr()
} else {
ptr::null()
}
}
None => ptr::null(),
};
STATE = backtrace_create_state(filename, 0, error_cb,
ptr::null_mut());
return STATE
}
////////////////////////////////////////////////////////////////////////
// translation
////////////////////////////////////////////////////////////////////////
// backtrace errors are currently swept under the rug, only I/O
// errors are reported
let state = unsafe { init_state() };
if state.is_null() {
return output(w, idx, addr, None)
}
let mut data = ptr::null();
let data_addr = &mut data as *mut *const libc::c_char;
let ret = unsafe {
backtrace_syminfo(state, symaddr as libc::uintptr_t,
syminfo_cb, error_cb,
data_addr as *mut libc::c_void)
};
if ret == 0 || data.is_null() {
try!(output(w, idx, addr, None));
} else {
try!(output(w, idx, addr, Some(unsafe { CStr::from_ptr(data).to_bytes() })));
}
// pcinfo may return an arbitrary number of file:line pairs,
// in the order of stack trace (i.e. inlined calls first).
// in order to avoid allocation, we stack-allocate a fixed size of entries.
const FILELINE_SIZE: usize = 32;
let mut fileline_buf = [(ptr::null(), -1); FILELINE_SIZE];
let ret;
let fileline_count;
{
let mut fileline_win: &mut [FileLine] = &mut fileline_buf;
let fileline_addr = &mut fileline_win as *mut &mut [FileLine];
ret = unsafe {
backtrace_pcinfo(state, addr as libc::uintptr_t,
pcinfo_cb, error_cb,
fileline_addr as *mut libc::c_void)
};
fileline_count = FILELINE_SIZE - fileline_win.len();
}
if ret == 0 {
for (i, &(file, line)) in fileline_buf[..fileline_count].iter().enumerate() {
if file.is_null() { continue; } // just to be sure
let file = unsafe { CStr::from_ptr(file).to_bytes() };
try!(output_fileline(w, file, line, i == FILELINE_SIZE - 1));
}
}
Ok(())
}
// Finally, after all that work above, we can emit a symbol.
fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void,
s: Option<&[u8]>) -> IoResult<()> {
try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH));
match s.and_then(|s| str::from_utf8(s).ok()) {
Some(string) => try!(demangle(w, string)),
None => try!(write!(w, "<unknown>")),
}
w.write_all(&['\n' as u8])
}
#[allow(dead_code)]
fn output_fileline(w: &mut Writer, file: &[u8], line: libc::c_int,
more: bool) -> IoResult<()> {
let file = str::from_utf8(file).ok().unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more {
try!(write!(w, " <... and possibly more>"));
}
w.write_all(&['\n' as u8])
}
/// Unwind library interface used for backtraces
///
/// Note that dead code is allowed as here are just bindings
/// iOS doesn't use all of them it but adding more
/// platform-specific configs pollutes the code too much
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(dead_code)]
mod uw {
pub use self::_Unwind_Reason_Code::*;
use libc;
#[repr(C)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
_URC_FAILURE = 9, // used only by ARM EABI
}
pub enum _Unwind_Context {}
pub type _Unwind_Trace_Fn =
extern fn(ctx: *mut _Unwind_Context,
arg: *mut libc::c_void) -> _Unwind_Reason_Code;
extern {
// No native _Unwind_Backtrace on iOS
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
trace_argument: *mut libc::c_void)
-> _Unwind_Reason_Code;
// available since GCC 4.2.0, should be fine for our purpose
#[cfg(all(not(all(target_os = "android", target_arch = "arm")),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context,
ip_before_insn: *mut libc::c_int)
-> libc::uintptr_t;
#[cfg(all(not(target_os = "android"),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
-> *mut libc::c_void;
}
// On android, the function _Unwind_GetIP is a macro, and this is the
// expansion of the macro. This is all copy/pasted directly from the
// header file with the definition of _Unwind_GetIP.
| random_line_split |
|
backtrace.rs | in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need to consult both the local and dynamic symbol tables.
/// With that in mind, here's our options of translating an address to
/// a symbol.
///
/// * Use dladdr(). The original backtrace()-based idea actually uses dladdr()
/// behind the scenes to translate, and this is why backtrace() was not used.
/// Conveniently, this method works fantastically on OSX. It appears dladdr()
/// uses magic to consult the local symbol table, or we're putting everything
/// in the dynamic symbol table anyway. Regardless, for OSX, this is the
/// method used for translation. It's provided by the system and easy to do.o
///
/// Sadly, all other systems have a dladdr() implementation that does not
/// consult the local symbol table. This means that most functions are blank
/// because they don't have symbols. This means that we need another solution.
///
/// * Use unw_get_proc_name(). This is part of the libunwind api (not the
/// libgcc_s version of the libunwind api), but involves taking a dependency
/// to libunwind. We may pursue this route in the future if we bundle
/// libunwind, but libunwind was unwieldy enough that it was not chosen at
/// this time to provide this functionality.
///
/// * Shell out to a utility like `readelf`. Crazy though it may sound, it's a
/// semi-reasonable solution. The stdlib already knows how to spawn processes,
/// so in theory it could invoke readelf, parse the output, and consult the
/// local/dynamic symbol tables from there. This ended up not getting chosen
/// due to the craziness of the idea plus the advent of the next option.
///
/// * Use `libbacktrace`. It turns out that this is a small library bundled in
/// the gcc repository which provides backtrace and symbol translation
/// functionality. All we really need from it is the backtrace functionality,
/// and we only really need this on everything that's not OSX, so this is the
/// chosen route for now.
///
/// In summary, the current situation uses libgcc_s to get a trace of stack
/// pointers, and we use dladdr() or libbacktrace to translate these addresses
/// to symbols. This is a bit of a hokey implementation as-is, but it works for
/// all unix platforms we support right now, so it at least gets the job done.
use prelude::v1::*;
use os::unix::prelude::*;
use ffi::{CStr, AsOsStr};
use old_io::IoResult;
use libc;
use mem;
use str;
use sync::{StaticMutex, MUTEX_INIT};
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is public
///
/// As mentioned in a huge comment block above, backtrace doesn't
/// play well with green threads, so while it is extremely nice
/// and simple to use it should be used only on iOS devices as the
/// only viable option.
#[cfg(all(target_os = "ios", target_arch = "arm"))]
#[inline(never)]
pub fn write(w: &mut Writer) -> IoResult<()> {
use result;
extern {
fn backtrace(buf: *mut *mut libc::c_void,
sz: libc::c_int) -> libc::c_int;
}
// while it doesn't requires lock for work as everything is
// local, it still displays much nicer backtraces when a
// couple of tasks panic simultaneously
static LOCK: StaticMutex = MUTEX_INIT;
let _g = unsafe { LOCK.lock() };
try!(writeln!(w, "stack backtrace:"));
// 100 lines should be enough
const SIZE: uint = 100;
let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()};
let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as uint};
// skipping the first one as it is write itself
let iter = (1..cnt).map(|i| {
print(w, i as int, buf[i], buf[i])
});
result::fold(iter, (), |_, _| ())
}
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
#[inline(never)] // if we know this is a function call, we can skip it when
// tracing
pub fn write(w: &mut Writer) -> IoResult<()> {
use old_io::IoError;
struct Context<'a> {
idx: int,
writer: &'a mut (Writer+'a),
last_error: Option<IoError>,
}
// When using libbacktrace, we use some necessary global state, so we
// need to prevent more than one thread from entering this block. This
// is semi-reasonable in terms of printing anyway, and we know that all
// I/O done here is blocking I/O, not green I/O, so we don't have to
// worry about this being a native vs green mutex.
static LOCK: StaticMutex = MUTEX_INIT;
let _g = unsafe { LOCK.lock() };
try!(writeln!(w, "stack backtrace:"));
let mut cx = Context { writer: w, last_error: None, idx: 0 };
return match unsafe {
uw::_Unwind_Backtrace(trace_fn,
&mut cx as *mut Context as *mut libc::c_void)
} {
uw::_URC_NO_REASON => {
match cx.last_error {
Some(err) => Err(err),
None => Ok(())
}
}
_ => Ok(()),
};
extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code {
let cx: &mut Context = unsafe { mem::transmute(arg) };
let mut ip_before_insn = 0;
let mut ip = unsafe {
uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void
};
if!ip.is_null() && ip_before_insn == 0 {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
}
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and
// it appears to work fine without it, so we only use
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
// This is often because panic involves the last instruction of a
// function being "call std::rt::begin_unwind", with no ret
// instructions after it. This means that the return instruction
// pointer points *outside* of the calling function, and by
// unwinding it we go back to the original function.
let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
ip
} else {
unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
};
// Don't print out the first few frames (they're not user frames)
cx.idx += 1;
if cx.idx <= 0 { return uw::_URC_NO_REASON }
// Don't print ginormous backtraces
if cx.idx > 100 {
match write!(cx.writer, "... <frames omitted>\n") {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
return uw::_URC_FAILURE
}
// Once we hit an error, stop trying to print more frames
if cx.last_error.is_some() { return uw::_URC_FAILURE }
match print(cx.writer, cx.idx, ip, symaddr) {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
// keep going
return uw::_URC_NO_REASON
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void,
_symaddr: *mut libc::c_void) -> IoResult<()> {
use intrinsics;
#[repr(C)]
struct Dl_info {
dli_fname: *const libc::c_char,
dli_fbase: *mut libc::c_void,
dli_sname: *const libc::c_char,
dli_saddr: *mut libc::c_void,
}
extern {
fn dladdr(addr: *const libc::c_void,
info: *mut Dl_info) -> libc::c_int;
}
let mut info: Dl_info = unsafe { intrinsics::init() };
if unsafe { dladdr(addr, &mut info) == 0 } {
output(w, idx,addr, None)
} else {
output(w, idx, addr, Some(unsafe {
CStr::from_ptr(info.dli_sname).to_bytes()
}))
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void,
symaddr: *mut libc::c_void) -> IoResult<()> {
use env;
use ptr;
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
////////////////////////////////////////////////////////////////////////
type backtrace_syminfo_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
symname: *const libc::c_char,
symval: libc::uintptr_t,
symsize: libc::uintptr_t);
type backtrace_full_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
function: *const libc::c_char) -> libc::c_int;
type backtrace_error_callback =
extern "C" fn(data: *mut libc::c_void,
msg: *const libc::c_char,
errnum: libc::c_int);
enum backtrace_state {}
#[link(name = "backtrace", kind = "static")]
#[cfg(not(test))]
extern {}
extern {
fn backtrace_create_state(filename: *const libc::c_char,
threaded: libc::c_int,
error: backtrace_error_callback,
data: *mut libc::c_void)
-> *mut backtrace_state;
fn backtrace_syminfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_syminfo_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
fn backtrace_pcinfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_full_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
}
////////////////////////////////////////////////////////////////////////
// helper callbacks
////////////////////////////////////////////////////////////////////////
type FileLine = (*const libc::c_char, libc::c_int);
extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char,
_errnum: libc::c_int) {
// do nothing for now
}
extern fn syminfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
symname: *const libc::c_char,
_symval: libc::uintptr_t,
_symsize: libc::uintptr_t) {
let slot = data as *mut *const libc::c_char;
unsafe { *slot = symname; }
}
extern fn | (data: *mut libc::c_void,
_pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
_function: *const libc::c_char) -> libc::c_int {
if!filename.is_null() {
let slot = data as *mut &mut [FileLine];
let buffer = unsafe {ptr::read(slot)};
// if the buffer is not full, add file:line to the buffer
// and adjust the buffer for next possible calls to pcinfo_cb.
if!buffer.is_empty() {
buffer[0] = (filename, lineno);
unsafe { ptr::write(slot, &mut buffer[1..]); }
}
}
0
}
// The libbacktrace API supports creating a state, but it does not
// support destroying a state. I personally take this to mean that a
// state is meant to be created and then live forever.
//
// I would love to register an at_exit() handler which cleans up this
// state, but libbacktrace provides no way to do so.
//
// With these constraints, this function has a statically cached state
// that is calculated the first time this is requested. Remember that
// backtracing all happens serially (one global lock).
//
// An additionally oddity in this function is that we initialize the
// filename via self_exe_name() to pass to libbacktrace. It turns out
// that on Linux libbacktrace seamlessly gets the filename of the
// current executable, but this fails on freebsd. by always providing
// it, we make sure that libbacktrace never has a reason to not look up
// the symbols. The libbacktrace API also states that the filename must
// be in "permanent memory", so we copy it to a static and then use the
// static as the pointer.
//
// FIXME: We also call self_exe_name() on DragonFly BSD. I haven't
// tested if this is required or not.
unsafe fn init_state() -> *mut backtrace_state {
static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256];
if!STATE.is_null() { return STATE }
let selfname = if cfg!(target_os = "freebsd") ||
cfg!(target_os = "dragonfly") ||
cfg!(target_os = "bitrig") ||
cfg!(target_os = "openbsd") {
env::current_exe().ok()
} else {
None
};
let filename = match selfname {
Some(path) => {
let bytes = path.as_os_str().as_bytes();
if bytes.len() < LAST_FILENAME.len() {
let i = bytes.iter();
for (slot, val) in LAST_FILENAME.iter_mut().zip(i) {
*slot = *val as libc::c_char;
}
LAST_FILENAME.as_ptr()
} else {
ptr::null()
}
}
None => ptr::null(),
};
STATE = backtrace_create_state(filename, 0, error_cb,
ptr::null_mut());
return STATE
}
////////////////////////////////////////////////////////////////////////
// translation
////////////////////////////////////////////////////////////////////////
// backtrace errors are currently swept under the rug, only I/O
// errors are reported
let state = unsafe { init_state() };
if state.is_null() {
return output(w, idx, addr, None)
}
let mut data = ptr::null();
let data_addr = &mut data as *mut *const libc::c_char;
let ret = unsafe {
backtrace_syminfo(state, symaddr as libc::uintptr_t,
syminfo_cb, error_cb,
data_addr as *mut libc::c_void)
};
if ret == 0 || data.is_null() {
try!(output(w, idx, addr, None));
} else {
try!(output(w, idx, addr, Some(unsafe { CStr::from_ptr(data).to_bytes() })));
}
// pcinfo may return an arbitrary number of file:line pairs,
// in the order of stack trace (i.e. inlined calls first).
// in order to avoid allocation, we stack-allocate a fixed size of entries.
const FILELINE_SIZE: usize = 32;
let mut fileline_buf = [(ptr::null(), -1); FILELINE_SIZE];
let ret;
let fileline_count;
{
let mut fileline_win: &mut [FileLine] = &mut fileline_buf;
let fileline_addr = &mut fileline_win as *mut &mut [FileLine];
ret = unsafe {
backtrace_pcinfo(state, addr as libc::uintptr_t,
pcinfo_cb, error_cb,
fileline_addr as *mut libc::c_void)
};
fileline_count = FILELINE_SIZE - fileline_win.len();
}
if ret == 0 {
for (i, &(file, line)) in fileline_buf[..fileline_count].iter().enumerate() {
if file.is_null() { continue; } // just to be sure
let file = unsafe { CStr::from_ptr(file).to_bytes() };
try!(output_fileline(w, file, line, i == FILELINE_SIZE - 1));
}
}
Ok(())
}
// Finally, after all that work above, we can emit a symbol.
fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void,
s: Option<&[u8]>) -> IoResult<()> {
try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH));
match s.and_then(|s| str::from_utf8(s).ok()) {
Some(string) => try!(demangle(w, string)),
None => try!(write!(w, "<unknown>")),
}
w.write_all(&['\n' as u8])
}
#[allow(dead_code)]
fn output_fileline(w: &mut Writer, file: &[u8], line: libc::c_int,
more: bool) -> IoResult<()> {
let file = str::from_utf8(file).ok().unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more {
try!(write!(w, " <... and possibly more>"));
}
w.write_all(&['\n' as u8])
}
/// Unwind library interface used for backtraces
///
/// Note that dead code is allowed as here are just bindings
/// iOS doesn't use all of them it but adding more
/// platform-specific configs pollutes the code too much
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(dead_code)]
mod uw {
pub use self::_Unwind_Reason_Code::*;
use libc;
#[repr(C)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
_URC_FAILURE = 9, // used only by ARM EABI
}
pub enum _Unwind_Context {}
pub type _Unwind_Trace_Fn =
extern fn(ctx: *mut _Unwind_Context,
arg: *mut libc::c_void) -> _Unwind_Reason_Code;
extern {
// No native _Unwind_Backtrace on iOS
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
trace_argument: *mut libc::c_void)
-> _Unwind_Reason_Code;
// available since GCC 4.2.0, should be fine for our purpose
#[cfg(all(not(all(target_os = "android", target_arch = "arm")),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context,
ip_before_insn: *mut libc::c_int)
-> libc::uintptr_t;
#[cfg(all(not(target_os = "android"),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
-> *mut libc::c_void;
}
// On android, the function _Unwind_GetIP is a macro, and this is the
// expansion of the macro. This is all copy/pasted directly from the
// header file with the definition of _Unwind_GetIP.
| pcinfo_cb | identifier_name |
backtrace.rs | in theory means that they're available for dynamic
/// linking and lookup. Other symbols end up only in the local symbol table of
/// the file. This loosely corresponds to pub and priv functions in Rust.
///
/// Armed with this knowledge, we know that our solution for address to symbol
/// translation will need to consult both the local and dynamic symbol tables.
/// With that in mind, here's our options of translating an address to
/// a symbol.
///
/// * Use dladdr(). The original backtrace()-based idea actually uses dladdr()
/// behind the scenes to translate, and this is why backtrace() was not used.
/// Conveniently, this method works fantastically on OSX. It appears dladdr()
/// uses magic to consult the local symbol table, or we're putting everything
/// in the dynamic symbol table anyway. Regardless, for OSX, this is the
/// method used for translation. It's provided by the system and easy to do.o
///
/// Sadly, all other systems have a dladdr() implementation that does not
/// consult the local symbol table. This means that most functions are blank
/// because they don't have symbols. This means that we need another solution.
///
/// * Use unw_get_proc_name(). This is part of the libunwind api (not the
/// libgcc_s version of the libunwind api), but involves taking a dependency
/// to libunwind. We may pursue this route in the future if we bundle
/// libunwind, but libunwind was unwieldy enough that it was not chosen at
/// this time to provide this functionality.
///
/// * Shell out to a utility like `readelf`. Crazy though it may sound, it's a
/// semi-reasonable solution. The stdlib already knows how to spawn processes,
/// so in theory it could invoke readelf, parse the output, and consult the
/// local/dynamic symbol tables from there. This ended up not getting chosen
/// due to the craziness of the idea plus the advent of the next option.
///
/// * Use `libbacktrace`. It turns out that this is a small library bundled in
/// the gcc repository which provides backtrace and symbol translation
/// functionality. All we really need from it is the backtrace functionality,
/// and we only really need this on everything that's not OSX, so this is the
/// chosen route for now.
///
/// In summary, the current situation uses libgcc_s to get a trace of stack
/// pointers, and we use dladdr() or libbacktrace to translate these addresses
/// to symbols. This is a bit of a hokey implementation as-is, but it works for
/// all unix platforms we support right now, so it at least gets the job done.
use prelude::v1::*;
use os::unix::prelude::*;
use ffi::{CStr, AsOsStr};
use old_io::IoResult;
use libc;
use mem;
use str;
use sync::{StaticMutex, MUTEX_INIT};
use sys_common::backtrace::*;
/// As always - iOS on arm uses SjLj exceptions and
/// _Unwind_Backtrace is even not available there. Still,
/// backtraces could be extracted using a backtrace function,
/// which thanks god is public
///
/// As mentioned in a huge comment block above, backtrace doesn't
/// play well with green threads, so while it is extremely nice
/// and simple to use it should be used only on iOS devices as the
/// only viable option.
#[cfg(all(target_os = "ios", target_arch = "arm"))]
#[inline(never)]
pub fn write(w: &mut Writer) -> IoResult<()> {
use result;
extern {
fn backtrace(buf: *mut *mut libc::c_void,
sz: libc::c_int) -> libc::c_int;
}
// while it doesn't requires lock for work as everything is
// local, it still displays much nicer backtraces when a
// couple of tasks panic simultaneously
static LOCK: StaticMutex = MUTEX_INIT;
let _g = unsafe { LOCK.lock() };
try!(writeln!(w, "stack backtrace:"));
// 100 lines should be enough
const SIZE: uint = 100;
let mut buf: [*mut libc::c_void; SIZE] = unsafe {mem::zeroed()};
let cnt = unsafe { backtrace(buf.as_mut_ptr(), SIZE as libc::c_int) as uint};
// skipping the first one as it is write itself
let iter = (1..cnt).map(|i| {
print(w, i as int, buf[i], buf[i])
});
result::fold(iter, (), |_, _| ())
}
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
#[inline(never)] // if we know this is a function call, we can skip it when
// tracing
pub fn write(w: &mut Writer) -> IoResult<()> {
use old_io::IoError;
struct Context<'a> {
idx: int,
writer: &'a mut (Writer+'a),
last_error: Option<IoError>,
}
// When using libbacktrace, we use some necessary global state, so we
// need to prevent more than one thread from entering this block. This
// is semi-reasonable in terms of printing anyway, and we know that all
// I/O done here is blocking I/O, not green I/O, so we don't have to
// worry about this being a native vs green mutex.
static LOCK: StaticMutex = MUTEX_INIT;
let _g = unsafe { LOCK.lock() };
try!(writeln!(w, "stack backtrace:"));
let mut cx = Context { writer: w, last_error: None, idx: 0 };
return match unsafe {
uw::_Unwind_Backtrace(trace_fn,
&mut cx as *mut Context as *mut libc::c_void)
} {
uw::_URC_NO_REASON => {
match cx.last_error {
Some(err) => Err(err),
None => Ok(())
}
}
_ => Ok(()),
};
extern fn trace_fn(ctx: *mut uw::_Unwind_Context,
arg: *mut libc::c_void) -> uw::_Unwind_Reason_Code {
let cx: &mut Context = unsafe { mem::transmute(arg) };
let mut ip_before_insn = 0;
let mut ip = unsafe {
uw::_Unwind_GetIPInfo(ctx, &mut ip_before_insn) as *mut libc::c_void
};
if!ip.is_null() && ip_before_insn == 0 {
// this is a non-signaling frame, so `ip` refers to the address
// after the calling instruction. account for that.
ip = (ip as usize - 1) as *mut _;
}
// dladdr() on osx gets whiny when we use FindEnclosingFunction, and
// it appears to work fine without it, so we only use
// FindEnclosingFunction on non-osx platforms. In doing so, we get a
// slightly more accurate stack trace in the process.
//
// This is often because panic involves the last instruction of a
// function being "call std::rt::begin_unwind", with no ret
// instructions after it. This means that the return instruction
// pointer points *outside* of the calling function, and by
// unwinding it we go back to the original function.
let symaddr = if cfg!(target_os = "macos") || cfg!(target_os = "ios") {
ip
} else {
unsafe { uw::_Unwind_FindEnclosingFunction(ip) }
};
// Don't print out the first few frames (they're not user frames)
cx.idx += 1;
if cx.idx <= 0 { return uw::_URC_NO_REASON }
// Don't print ginormous backtraces
if cx.idx > 100 {
match write!(cx.writer, "... <frames omitted>\n") {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
return uw::_URC_FAILURE
}
// Once we hit an error, stop trying to print more frames
if cx.last_error.is_some() { return uw::_URC_FAILURE }
match print(cx.writer, cx.idx, ip, symaddr) {
Ok(()) => {}
Err(e) => { cx.last_error = Some(e); }
}
// keep going
return uw::_URC_NO_REASON
}
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void,
_symaddr: *mut libc::c_void) -> IoResult<()> {
use intrinsics;
#[repr(C)]
struct Dl_info {
dli_fname: *const libc::c_char,
dli_fbase: *mut libc::c_void,
dli_sname: *const libc::c_char,
dli_saddr: *mut libc::c_void,
}
extern {
fn dladdr(addr: *const libc::c_void,
info: *mut Dl_info) -> libc::c_int;
}
let mut info: Dl_info = unsafe { intrinsics::init() };
if unsafe { dladdr(addr, &mut info) == 0 } {
output(w, idx,addr, None)
} else {
output(w, idx, addr, Some(unsafe {
CStr::from_ptr(info.dli_sname).to_bytes()
}))
}
}
#[cfg(not(any(target_os = "macos", target_os = "ios")))]
fn print(w: &mut Writer, idx: int, addr: *mut libc::c_void,
symaddr: *mut libc::c_void) -> IoResult<()> {
use env;
use ptr;
////////////////////////////////////////////////////////////////////////
// libbacktrace.h API
////////////////////////////////////////////////////////////////////////
type backtrace_syminfo_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
symname: *const libc::c_char,
symval: libc::uintptr_t,
symsize: libc::uintptr_t);
type backtrace_full_callback =
extern "C" fn(data: *mut libc::c_void,
pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
function: *const libc::c_char) -> libc::c_int;
type backtrace_error_callback =
extern "C" fn(data: *mut libc::c_void,
msg: *const libc::c_char,
errnum: libc::c_int);
enum backtrace_state {}
#[link(name = "backtrace", kind = "static")]
#[cfg(not(test))]
extern {}
extern {
fn backtrace_create_state(filename: *const libc::c_char,
threaded: libc::c_int,
error: backtrace_error_callback,
data: *mut libc::c_void)
-> *mut backtrace_state;
fn backtrace_syminfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_syminfo_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
fn backtrace_pcinfo(state: *mut backtrace_state,
addr: libc::uintptr_t,
cb: backtrace_full_callback,
error: backtrace_error_callback,
data: *mut libc::c_void) -> libc::c_int;
}
////////////////////////////////////////////////////////////////////////
// helper callbacks
////////////////////////////////////////////////////////////////////////
type FileLine = (*const libc::c_char, libc::c_int);
extern fn error_cb(_data: *mut libc::c_void, _msg: *const libc::c_char,
_errnum: libc::c_int) {
// do nothing for now
}
extern fn syminfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
symname: *const libc::c_char,
_symval: libc::uintptr_t,
_symsize: libc::uintptr_t) {
let slot = data as *mut *const libc::c_char;
unsafe { *slot = symname; }
}
extern fn pcinfo_cb(data: *mut libc::c_void,
_pc: libc::uintptr_t,
filename: *const libc::c_char,
lineno: libc::c_int,
_function: *const libc::c_char) -> libc::c_int {
if!filename.is_null() {
let slot = data as *mut &mut [FileLine];
let buffer = unsafe {ptr::read(slot)};
// if the buffer is not full, add file:line to the buffer
// and adjust the buffer for next possible calls to pcinfo_cb.
if!buffer.is_empty() {
buffer[0] = (filename, lineno);
unsafe { ptr::write(slot, &mut buffer[1..]); }
}
}
0
}
// The libbacktrace API supports creating a state, but it does not
// support destroying a state. I personally take this to mean that a
// state is meant to be created and then live forever.
//
// I would love to register an at_exit() handler which cleans up this
// state, but libbacktrace provides no way to do so.
//
// With these constraints, this function has a statically cached state
// that is calculated the first time this is requested. Remember that
// backtracing all happens serially (one global lock).
//
// An additionally oddity in this function is that we initialize the
// filename via self_exe_name() to pass to libbacktrace. It turns out
// that on Linux libbacktrace seamlessly gets the filename of the
// current executable, but this fails on freebsd. by always providing
// it, we make sure that libbacktrace never has a reason to not look up
// the symbols. The libbacktrace API also states that the filename must
// be in "permanent memory", so we copy it to a static and then use the
// static as the pointer.
//
// FIXME: We also call self_exe_name() on DragonFly BSD. I haven't
// tested if this is required or not.
unsafe fn init_state() -> *mut backtrace_state {
static mut STATE: *mut backtrace_state = 0 as *mut backtrace_state;
static mut LAST_FILENAME: [libc::c_char; 256] = [0; 256];
if!STATE.is_null() { return STATE }
let selfname = if cfg!(target_os = "freebsd") ||
cfg!(target_os = "dragonfly") ||
cfg!(target_os = "bitrig") ||
cfg!(target_os = "openbsd") {
env::current_exe().ok()
} else {
None
};
let filename = match selfname {
Some(path) => {
let bytes = path.as_os_str().as_bytes();
if bytes.len() < LAST_FILENAME.len() {
let i = bytes.iter();
for (slot, val) in LAST_FILENAME.iter_mut().zip(i) {
*slot = *val as libc::c_char;
}
LAST_FILENAME.as_ptr()
} else {
ptr::null()
}
}
None => ptr::null(),
};
STATE = backtrace_create_state(filename, 0, error_cb,
ptr::null_mut());
return STATE
}
////////////////////////////////////////////////////////////////////////
// translation
////////////////////////////////////////////////////////////////////////
// backtrace errors are currently swept under the rug, only I/O
// errors are reported
let state = unsafe { init_state() };
if state.is_null() {
return output(w, idx, addr, None)
}
let mut data = ptr::null();
let data_addr = &mut data as *mut *const libc::c_char;
let ret = unsafe {
backtrace_syminfo(state, symaddr as libc::uintptr_t,
syminfo_cb, error_cb,
data_addr as *mut libc::c_void)
};
if ret == 0 || data.is_null() {
try!(output(w, idx, addr, None));
} else {
try!(output(w, idx, addr, Some(unsafe { CStr::from_ptr(data).to_bytes() })));
}
// pcinfo may return an arbitrary number of file:line pairs,
// in the order of stack trace (i.e. inlined calls first).
// in order to avoid allocation, we stack-allocate a fixed size of entries.
const FILELINE_SIZE: usize = 32;
let mut fileline_buf = [(ptr::null(), -1); FILELINE_SIZE];
let ret;
let fileline_count;
{
let mut fileline_win: &mut [FileLine] = &mut fileline_buf;
let fileline_addr = &mut fileline_win as *mut &mut [FileLine];
ret = unsafe {
backtrace_pcinfo(state, addr as libc::uintptr_t,
pcinfo_cb, error_cb,
fileline_addr as *mut libc::c_void)
};
fileline_count = FILELINE_SIZE - fileline_win.len();
}
if ret == 0 {
for (i, &(file, line)) in fileline_buf[..fileline_count].iter().enumerate() {
if file.is_null() | // just to be sure
let file = unsafe { CStr::from_ptr(file).to_bytes() };
try!(output_fileline(w, file, line, i == FILELINE_SIZE - 1));
}
}
Ok(())
}
// Finally, after all that work above, we can emit a symbol.
fn output(w: &mut Writer, idx: int, addr: *mut libc::c_void,
s: Option<&[u8]>) -> IoResult<()> {
try!(write!(w, " {:2}: {:2$?} - ", idx, addr, HEX_WIDTH));
match s.and_then(|s| str::from_utf8(s).ok()) {
Some(string) => try!(demangle(w, string)),
None => try!(write!(w, "<unknown>")),
}
w.write_all(&['\n' as u8])
}
#[allow(dead_code)]
fn output_fileline(w: &mut Writer, file: &[u8], line: libc::c_int,
more: bool) -> IoResult<()> {
let file = str::from_utf8(file).ok().unwrap_or("<unknown>");
// prior line: " ##: {:2$} - func"
try!(write!(w, " {:3$}at {}:{}", "", file, line, HEX_WIDTH));
if more {
try!(write!(w, " <... and possibly more>"));
}
w.write_all(&['\n' as u8])
}
/// Unwind library interface used for backtraces
///
/// Note that dead code is allowed as here are just bindings
/// iOS doesn't use all of them it but adding more
/// platform-specific configs pollutes the code too much
#[allow(non_camel_case_types)]
#[allow(non_snake_case)]
#[allow(dead_code)]
mod uw {
pub use self::_Unwind_Reason_Code::*;
use libc;
#[repr(C)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
_URC_FAILURE = 9, // used only by ARM EABI
}
pub enum _Unwind_Context {}
pub type _Unwind_Trace_Fn =
extern fn(ctx: *mut _Unwind_Context,
arg: *mut libc::c_void) -> _Unwind_Reason_Code;
extern {
// No native _Unwind_Backtrace on iOS
#[cfg(not(all(target_os = "ios", target_arch = "arm")))]
pub fn _Unwind_Backtrace(trace: _Unwind_Trace_Fn,
trace_argument: *mut libc::c_void)
-> _Unwind_Reason_Code;
// available since GCC 4.2.0, should be fine for our purpose
#[cfg(all(not(all(target_os = "android", target_arch = "arm")),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_GetIPInfo(ctx: *mut _Unwind_Context,
ip_before_insn: *mut libc::c_int)
-> libc::uintptr_t;
#[cfg(all(not(target_os = "android"),
not(all(target_os = "linux", target_arch = "arm"))))]
pub fn _Unwind_FindEnclosingFunction(pc: *mut libc::c_void)
-> *mut libc::c_void;
}
// On android, the function _Unwind_GetIP is a macro, and this is the
// expansion of the macro. This is all copy/pasted directly from the
// header file with the definition of _Unwind_GetIP.
| { continue; } | conditional_block |
main.rs | use std::thread;
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 | (&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_ms(1000);
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();
}
}
| eat | identifier_name |
main.rs | use std::thread;
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_ms(1000);
println!("{} is done eating.", self.name);
} | identifier_body |
main.rs | use std::thread;
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_ms(1000);
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(()),
]});
| 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 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), | random_line_split |
lib.rs | pub mod proto;
use crate::proto::hello::{HelloReq, HelloResp};
use crate::proto::hello_grpc::HelloService;
use futures::Future;
use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink};
#[derive(Clone)]
pub struct GrpcHelloService;
impl HelloService for GrpcHelloService {
fn say_hello(&mut self, ctx: RpcContext, req: HelloReq, sink: UnarySink<HelloResp>) {
let name = req.get_Name();
let reply_msg = format!("Hey, {}!", name);
let mut reply = HelloResp::new();
reply.set_Result(reply_msg);
let f = sink
.success(reply)
.map_err(move |e| println!("failed to reply {:?}: {:?}", req, e));
ctx.spawn(f);
}
fn say_hello_strict(&mut self, ctx: RpcContext, req: HelloReq, sink: UnarySink<HelloResp>) {
let name = req.get_Name();
if name.len() >= 10 | else {
let reply_msg = format!("Hey, {}!", name);
let mut reply = HelloResp::new();
reply.set_Result(reply_msg);
let f = sink
.success(reply)
.map_err(move |e| println!("failed to reply {:?}: {:?}", req, e));
ctx.spawn(f);
}
}
}
| {
let reply_msg = "Length of `Name` cannot be more than 10 characters";
let f = sink
.fail(RpcStatus::new(
RpcStatusCode::InvalidArgument,
Some(reply_msg.to_string()),
))
.map_err(move |e| println!("failed to reply {:?}: {:?}", req, e));
ctx.spawn(f);
} | conditional_block |
lib.rs | pub mod proto;
use crate::proto::hello::{HelloReq, HelloResp};
use crate::proto::hello_grpc::HelloService;
use futures::Future;
use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink};
#[derive(Clone)]
pub struct GrpcHelloService;
impl HelloService for GrpcHelloService {
fn | (&mut self, ctx: RpcContext, req: HelloReq, sink: UnarySink<HelloResp>) {
let name = req.get_Name();
let reply_msg = format!("Hey, {}!", name);
let mut reply = HelloResp::new();
reply.set_Result(reply_msg);
let f = sink
.success(reply)
.map_err(move |e| println!("failed to reply {:?}: {:?}", req, e));
ctx.spawn(f);
}
fn say_hello_strict(&mut self, ctx: RpcContext, req: HelloReq, sink: UnarySink<HelloResp>) {
let name = req.get_Name();
if name.len() >= 10 {
let reply_msg = "Length of `Name` cannot be more than 10 characters";
let f = sink
.fail(RpcStatus::new(
RpcStatusCode::InvalidArgument,
Some(reply_msg.to_string()),
))
.map_err(move |e| println!("failed to reply {:?}: {:?}", req, e));
ctx.spawn(f);
} else {
let reply_msg = format!("Hey, {}!", name);
let mut reply = HelloResp::new();
reply.set_Result(reply_msg);
let f = sink
.success(reply)
.map_err(move |e| println!("failed to reply {:?}: {:?}", req, e));
ctx.spawn(f);
}
}
}
| say_hello | identifier_name |
lib.rs | pub mod proto;
use crate::proto::hello::{HelloReq, HelloResp};
use crate::proto::hello_grpc::HelloService;
use futures::Future;
use grpcio::{RpcContext, RpcStatus, RpcStatusCode, UnarySink};
#[derive(Clone)]
pub struct GrpcHelloService;
impl HelloService for GrpcHelloService {
fn say_hello(&mut self, ctx: RpcContext, req: HelloReq, sink: UnarySink<HelloResp>) {
let name = req.get_Name();
let reply_msg = format!("Hey, {}!", name);
let mut reply = HelloResp::new();
reply.set_Result(reply_msg);
let f = sink
.success(reply)
.map_err(move |e| println!("failed to reply {:?}: {:?}", req, e));
ctx.spawn(f);
}
fn say_hello_strict(&mut self, ctx: RpcContext, req: HelloReq, sink: UnarySink<HelloResp>) {
let name = req.get_Name();
if name.len() >= 10 {
let reply_msg = "Length of `Name` cannot be more than 10 characters";
let f = sink | Some(reply_msg.to_string()),
))
.map_err(move |e| println!("failed to reply {:?}: {:?}", req, e));
ctx.spawn(f);
} else {
let reply_msg = format!("Hey, {}!", name);
let mut reply = HelloResp::new();
reply.set_Result(reply_msg);
let f = sink
.success(reply)
.map_err(move |e| println!("failed to reply {:?}: {:?}", req, e));
ctx.spawn(f);
}
}
} | .fail(RpcStatus::new(
RpcStatusCode::InvalidArgument, | random_line_split |
builtin-superkinds-self-type.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// Tests the ability for the Self type in default methods to use
// capabilities granted by builtin kinds as supertraits.
use std::sync::mpsc::{Sender, channel};
trait Foo : Send + Sized +'static {
fn foo(self, tx: Sender<Self>) |
}
impl <T: Send +'static> Foo for T { }
pub fn main() {
let (tx, rx) = channel();
1193182.foo(tx);
assert_eq!(rx.recv().unwrap(), 1193182);
}
| {
tx.send(self).unwrap();
} | identifier_body |
builtin-superkinds-self-type.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// Tests the ability for the Self type in default methods to use
// capabilities granted by builtin kinds as supertraits. |
trait Foo : Send + Sized +'static {
fn foo(self, tx: Sender<Self>) {
tx.send(self).unwrap();
}
}
impl <T: Send +'static> Foo for T { }
pub fn main() {
let (tx, rx) = channel();
1193182.foo(tx);
assert_eq!(rx.recv().unwrap(), 1193182);
} |
use std::sync::mpsc::{Sender, channel}; | random_line_split |
builtin-superkinds-self-type.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// Tests the ability for the Self type in default methods to use
// capabilities granted by builtin kinds as supertraits.
use std::sync::mpsc::{Sender, channel};
trait Foo : Send + Sized +'static {
fn | (self, tx: Sender<Self>) {
tx.send(self).unwrap();
}
}
impl <T: Send +'static> Foo for T { }
pub fn main() {
let (tx, rx) = channel();
1193182.foo(tx);
assert_eq!(rx.recv().unwrap(), 1193182);
}
| foo | identifier_name |
tree.rs | //! Generic Tree Implementation for Plan
use std::rc::Rc;
pub enum TreeBuildError {
EmptyStack,
StillRemainStackItem,
}
pub enum TreeNode<T> {
Branch(T, Vec<Box<TreeNode<T>>>),
Leaf(T),
}
#[allow(unused_variables)]
pub trait Visitor<'v, T>: Sized {
fn accept(&mut self, data: &'v T, child: Option<&'v Vec<Box<TreeNode<T>>>>) {
self.accept_by_default(child);
}
fn accept_by_default(&mut self, child: Option<&'v Vec<Box<TreeNode<T>>>>) {
match child {
Some(v) => {
for node in v.iter().map(|n| &*n) {
walk_tree(self, node);
}
}
None => {}
};
}
}
pub fn walk_tree<'v, V, T>(v: &mut V, node: &'v TreeNode<T>)
where V: Visitor<'v, T>
{
match *node {
TreeNode::Leaf(ref data) => v.accept(data, None),
TreeNode::Branch(ref data, ref child) => v.accept(data, Some(child)),
};
}
pub type SimpleVisitor<T> = Rc<Fn(&T, Option<&Vec<Box<TreeNode<T>>>>)>;
pub struct BatchVisitor<T> {
batch: Vec<SimpleVisitor<T>>,
}
impl<T> BatchVisitor<T> {
pub fn new() -> BatchVisitor<T> {
BatchVisitor { batch: Vec::new() }
}
pub fn add(&mut self, v: SimpleVisitor<T>) -> &mut Self {
self.batch.push(v);
self
}
}
/// Tree Builder in a bottom up approach.
pub struct TreeBuilder<T> {
stack: Vec<TreeNode<T>>,
}
impl<T> TreeBuilder<T> {
pub fn new() -> TreeBuilder<T> {
TreeBuilder { stack: Vec::new() }
}
pub fn push(&mut self, node: TreeNode<T>) -> Result<usize, TreeBuildError> {
self.stack.push(node);
Ok(self.stack.len())
}
pub fn pop(&mut self) -> TreeNode<T> {
debug_assert!(self.stack.len() > 0);
self.stack.pop().unwrap()
}
pub fn pop_and_push(&mut self, data: T, child_num: usize) -> Result<usize, TreeBuildError> {
let stack_size = self.stack.len();
debug_assert!(stack_size >= child_num);
let child = self.stack
.split_off(stack_size - child_num)
.into_iter()
.map(|node| Box::new(node))
.collect::<Vec<Box<TreeNode<T>>>>();
self.stack.push(TreeNode::Branch(data, child));
Ok(self.stack.len())
}
pub fn build(&mut self) -> Result<TreeNode<T>, TreeBuildError> |
}
#[cfg(test)]
mod tests {
use super::{TreeBuilder, TreeNode, Visitor};
pub struct TestVisitor;
pub struct AA;
impl<'v> Visitor<'v, AA> for TestVisitor {
fn accept(&mut self, data: &AA, child: Option<&'v Vec<Box<TreeNode<AA>>>>) {
self.accept_by_default(child);
}
}
#[test]
fn test_tree() {
let mut builder: TreeBuilder<&'static str> = TreeBuilder::new();
builder.push(TreeNode::Leaf("l1")).ok();
builder.push(TreeNode::Leaf("l2")).ok();
builder.pop_and_push("l3", 2).ok();
let tree = builder.build().ok().unwrap();
}
}
| {
match self.stack.len() {
0 => Err(TreeBuildError::EmptyStack),
1 => Ok(self.stack.pop().unwrap()),
_ => Err(TreeBuildError::StillRemainStackItem),
}
} | identifier_body |
tree.rs | //! Generic Tree Implementation for Plan
use std::rc::Rc;
pub enum TreeBuildError {
EmptyStack,
StillRemainStackItem,
}
pub enum TreeNode<T> {
Branch(T, Vec<Box<TreeNode<T>>>),
Leaf(T),
}
#[allow(unused_variables)]
pub trait Visitor<'v, T>: Sized {
fn accept(&mut self, data: &'v T, child: Option<&'v Vec<Box<TreeNode<T>>>>) {
self.accept_by_default(child);
}
fn accept_by_default(&mut self, child: Option<&'v Vec<Box<TreeNode<T>>>>) {
match child {
Some(v) => |
None => {}
};
}
}
pub fn walk_tree<'v, V, T>(v: &mut V, node: &'v TreeNode<T>)
where V: Visitor<'v, T>
{
match *node {
TreeNode::Leaf(ref data) => v.accept(data, None),
TreeNode::Branch(ref data, ref child) => v.accept(data, Some(child)),
};
}
pub type SimpleVisitor<T> = Rc<Fn(&T, Option<&Vec<Box<TreeNode<T>>>>)>;
pub struct BatchVisitor<T> {
batch: Vec<SimpleVisitor<T>>,
}
impl<T> BatchVisitor<T> {
pub fn new() -> BatchVisitor<T> {
BatchVisitor { batch: Vec::new() }
}
pub fn add(&mut self, v: SimpleVisitor<T>) -> &mut Self {
self.batch.push(v);
self
}
}
/// Tree Builder in a bottom up approach.
pub struct TreeBuilder<T> {
stack: Vec<TreeNode<T>>,
}
impl<T> TreeBuilder<T> {
pub fn new() -> TreeBuilder<T> {
TreeBuilder { stack: Vec::new() }
}
pub fn push(&mut self, node: TreeNode<T>) -> Result<usize, TreeBuildError> {
self.stack.push(node);
Ok(self.stack.len())
}
pub fn pop(&mut self) -> TreeNode<T> {
debug_assert!(self.stack.len() > 0);
self.stack.pop().unwrap()
}
pub fn pop_and_push(&mut self, data: T, child_num: usize) -> Result<usize, TreeBuildError> {
let stack_size = self.stack.len();
debug_assert!(stack_size >= child_num);
let child = self.stack
.split_off(stack_size - child_num)
.into_iter()
.map(|node| Box::new(node))
.collect::<Vec<Box<TreeNode<T>>>>();
self.stack.push(TreeNode::Branch(data, child));
Ok(self.stack.len())
}
pub fn build(&mut self) -> Result<TreeNode<T>, TreeBuildError> {
match self.stack.len() {
0 => Err(TreeBuildError::EmptyStack),
1 => Ok(self.stack.pop().unwrap()),
_ => Err(TreeBuildError::StillRemainStackItem),
}
}
}
#[cfg(test)]
mod tests {
use super::{TreeBuilder, TreeNode, Visitor};
pub struct TestVisitor;
pub struct AA;
impl<'v> Visitor<'v, AA> for TestVisitor {
fn accept(&mut self, data: &AA, child: Option<&'v Vec<Box<TreeNode<AA>>>>) {
self.accept_by_default(child);
}
}
#[test]
fn test_tree() {
let mut builder: TreeBuilder<&'static str> = TreeBuilder::new();
builder.push(TreeNode::Leaf("l1")).ok();
builder.push(TreeNode::Leaf("l2")).ok();
builder.pop_and_push("l3", 2).ok();
let tree = builder.build().ok().unwrap();
}
}
| {
for node in v.iter().map(|n| &*n) {
walk_tree(self, node);
}
} | conditional_block |
tree.rs | //! Generic Tree Implementation for Plan
use std::rc::Rc;
pub enum TreeBuildError {
EmptyStack,
StillRemainStackItem,
}
pub enum TreeNode<T> {
Branch(T, Vec<Box<TreeNode<T>>>),
Leaf(T),
}
#[allow(unused_variables)]
pub trait Visitor<'v, T>: Sized {
fn accept(&mut self, data: &'v T, child: Option<&'v Vec<Box<TreeNode<T>>>>) {
self.accept_by_default(child);
}
fn accept_by_default(&mut self, child: Option<&'v Vec<Box<TreeNode<T>>>>) {
match child {
Some(v) => {
for node in v.iter().map(|n| &*n) {
walk_tree(self, node);
}
}
None => {}
};
}
}
pub fn walk_tree<'v, V, T>(v: &mut V, node: &'v TreeNode<T>)
where V: Visitor<'v, T>
{
match *node {
TreeNode::Leaf(ref data) => v.accept(data, None),
TreeNode::Branch(ref data, ref child) => v.accept(data, Some(child)),
};
}
pub type SimpleVisitor<T> = Rc<Fn(&T, Option<&Vec<Box<TreeNode<T>>>>)>;
pub struct BatchVisitor<T> {
batch: Vec<SimpleVisitor<T>>,
}
impl<T> BatchVisitor<T> {
pub fn new() -> BatchVisitor<T> {
BatchVisitor { batch: Vec::new() }
}
pub fn add(&mut self, v: SimpleVisitor<T>) -> &mut Self {
self.batch.push(v);
self
}
}
/// Tree Builder in a bottom up approach.
pub struct TreeBuilder<T> {
stack: Vec<TreeNode<T>>,
}
impl<T> TreeBuilder<T> {
pub fn new() -> TreeBuilder<T> {
TreeBuilder { stack: Vec::new() }
}
pub fn push(&mut self, node: TreeNode<T>) -> Result<usize, TreeBuildError> {
self.stack.push(node);
Ok(self.stack.len())
}
pub fn pop(&mut self) -> TreeNode<T> {
debug_assert!(self.stack.len() > 0);
self.stack.pop().unwrap()
}
pub fn pop_and_push(&mut self, data: T, child_num: usize) -> Result<usize, TreeBuildError> {
let stack_size = self.stack.len();
debug_assert!(stack_size >= child_num);
let child = self.stack
.split_off(stack_size - child_num)
.into_iter()
.map(|node| Box::new(node))
.collect::<Vec<Box<TreeNode<T>>>>();
self.stack.push(TreeNode::Branch(data, child));
Ok(self.stack.len())
}
pub fn build(&mut self) -> Result<TreeNode<T>, TreeBuildError> {
match self.stack.len() {
0 => Err(TreeBuildError::EmptyStack),
1 => Ok(self.stack.pop().unwrap()),
_ => Err(TreeBuildError::StillRemainStackItem),
}
}
}
#[cfg(test)]
mod tests {
use super::{TreeBuilder, TreeNode, Visitor};
|
pub struct AA;
impl<'v> Visitor<'v, AA> for TestVisitor {
fn accept(&mut self, data: &AA, child: Option<&'v Vec<Box<TreeNode<AA>>>>) {
self.accept_by_default(child);
}
}
#[test]
fn test_tree() {
let mut builder: TreeBuilder<&'static str> = TreeBuilder::new();
builder.push(TreeNode::Leaf("l1")).ok();
builder.push(TreeNode::Leaf("l2")).ok();
builder.pop_and_push("l3", 2).ok();
let tree = builder.build().ok().unwrap();
}
} | pub struct TestVisitor; | random_line_split |
tree.rs | //! Generic Tree Implementation for Plan
use std::rc::Rc;
pub enum TreeBuildError {
EmptyStack,
StillRemainStackItem,
}
pub enum TreeNode<T> {
Branch(T, Vec<Box<TreeNode<T>>>),
Leaf(T),
}
#[allow(unused_variables)]
pub trait Visitor<'v, T>: Sized {
fn accept(&mut self, data: &'v T, child: Option<&'v Vec<Box<TreeNode<T>>>>) {
self.accept_by_default(child);
}
fn accept_by_default(&mut self, child: Option<&'v Vec<Box<TreeNode<T>>>>) {
match child {
Some(v) => {
for node in v.iter().map(|n| &*n) {
walk_tree(self, node);
}
}
None => {}
};
}
}
pub fn walk_tree<'v, V, T>(v: &mut V, node: &'v TreeNode<T>)
where V: Visitor<'v, T>
{
match *node {
TreeNode::Leaf(ref data) => v.accept(data, None),
TreeNode::Branch(ref data, ref child) => v.accept(data, Some(child)),
};
}
pub type SimpleVisitor<T> = Rc<Fn(&T, Option<&Vec<Box<TreeNode<T>>>>)>;
pub struct BatchVisitor<T> {
batch: Vec<SimpleVisitor<T>>,
}
impl<T> BatchVisitor<T> {
pub fn new() -> BatchVisitor<T> {
BatchVisitor { batch: Vec::new() }
}
pub fn add(&mut self, v: SimpleVisitor<T>) -> &mut Self {
self.batch.push(v);
self
}
}
/// Tree Builder in a bottom up approach.
pub struct TreeBuilder<T> {
stack: Vec<TreeNode<T>>,
}
impl<T> TreeBuilder<T> {
pub fn new() -> TreeBuilder<T> {
TreeBuilder { stack: Vec::new() }
}
pub fn push(&mut self, node: TreeNode<T>) -> Result<usize, TreeBuildError> {
self.stack.push(node);
Ok(self.stack.len())
}
pub fn pop(&mut self) -> TreeNode<T> {
debug_assert!(self.stack.len() > 0);
self.stack.pop().unwrap()
}
pub fn pop_and_push(&mut self, data: T, child_num: usize) -> Result<usize, TreeBuildError> {
let stack_size = self.stack.len();
debug_assert!(stack_size >= child_num);
let child = self.stack
.split_off(stack_size - child_num)
.into_iter()
.map(|node| Box::new(node))
.collect::<Vec<Box<TreeNode<T>>>>();
self.stack.push(TreeNode::Branch(data, child));
Ok(self.stack.len())
}
pub fn build(&mut self) -> Result<TreeNode<T>, TreeBuildError> {
match self.stack.len() {
0 => Err(TreeBuildError::EmptyStack),
1 => Ok(self.stack.pop().unwrap()),
_ => Err(TreeBuildError::StillRemainStackItem),
}
}
}
#[cfg(test)]
mod tests {
use super::{TreeBuilder, TreeNode, Visitor};
pub struct TestVisitor;
pub struct | ;
impl<'v> Visitor<'v, AA> for TestVisitor {
fn accept(&mut self, data: &AA, child: Option<&'v Vec<Box<TreeNode<AA>>>>) {
self.accept_by_default(child);
}
}
#[test]
fn test_tree() {
let mut builder: TreeBuilder<&'static str> = TreeBuilder::new();
builder.push(TreeNode::Leaf("l1")).ok();
builder.push(TreeNode::Leaf("l2")).ok();
builder.pop_and_push("l3", 2).ok();
let tree = builder.build().ok().unwrap();
}
}
| AA | identifier_name |
mutable-class-fields.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.
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
struct cat {
meows : usize,
how_hungry : isize,
}
fn cat(in_x : usize, in_y : isize) -> cat {
cat {
meows: in_x,
how_hungry: in_y
}
}
fn main() { | let nyan : cat = cat(52, 99);
nyan.how_hungry = 0; //[ast]~ ERROR cannot assign
//[mir]~^ ERROR cannot assign
} | random_line_split |
|
mutable-class-fields.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.
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
struct cat {
meows : usize,
how_hungry : isize,
}
fn | (in_x : usize, in_y : isize) -> cat {
cat {
meows: in_x,
how_hungry: in_y
}
}
fn main() {
let nyan : cat = cat(52, 99);
nyan.how_hungry = 0; //[ast]~ ERROR cannot assign
//[mir]~^ ERROR cannot assign
}
| cat | identifier_name |
mutable-class-fields.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.
// revisions: ast mir
//[mir]compile-flags: -Z borrowck=mir
struct cat {
meows : usize,
how_hungry : isize,
}
fn cat(in_x : usize, in_y : isize) -> cat |
fn main() {
let nyan : cat = cat(52, 99);
nyan.how_hungry = 0; //[ast]~ ERROR cannot assign
//[mir]~^ ERROR cannot assign
}
| {
cat {
meows: in_x,
how_hungry: in_y
}
} | identifier_body |
sequential.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements sequential traversals over the DOM and flow trees.
use context::{LayoutContext, SharedLayoutContext};
use flow::{self, Flow, ImmutableFlowUtils, InorderFlowTraversal, MutableFlowUtils};
use flow::{PostorderFlowTraversal, PreorderFlowTraversal};
use flow_ref::FlowRef;
use fragment::FragmentBorderBoxIterator;
use generated_content::ResolveGeneratedContent;
use traversal::{BubbleISizes, RecalcStyleForNode, ConstructFlows};
use traversal::{AssignBSizesAndStoreOverflow, AssignISizes};
use traversal::{ComputeAbsolutePositions, BuildDisplayList};
use wrapper::LayoutNode;
use wrapper::{PostorderNodeMutTraversal};
use wrapper::{PreorderDomTraversal, PostorderDomTraversal};
use euclid::point::Point2D;
use util::geometry::{Au, ZERO_POINT};
use util::opts;
pub fn traverse_dom_preorder(root: LayoutNode,
shared_layout_context: &SharedLayoutContext) {
fn doit(node: LayoutNode, recalc_style: RecalcStyleForNode, construct_flows: ConstructFlows) {
recalc_style.process(node);
for kid in node.children() {
doit(kid, recalc_style, construct_flows);
}
construct_flows.process(node);
}
let layout_context = LayoutContext::new(shared_layout_context);
let recalc_style = RecalcStyleForNode { layout_context: &layout_context };
let construct_flows = ConstructFlows { layout_context: &layout_context };
doit(root, recalc_style, construct_flows);
}
pub fn resolve_generated_content(root: &mut FlowRef, shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow, level: u32, traversal: &mut ResolveGeneratedContent) {
if!traversal.should_process(flow) {
return
}
traversal.process(flow, level);
for kid in flow::mut_base(flow).children.iter_mut() {
doit(kid, level + 1, traversal)
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let mut traversal = ResolveGeneratedContent::new(&layout_context);
doit(&mut **root, 0, &mut traversal)
}
pub fn traverse_flow_tree_preorder(root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow,
assign_inline_sizes: AssignISizes,
assign_block_sizes: AssignBSizesAndStoreOverflow) {
if assign_inline_sizes.should_process(flow) {
assign_inline_sizes.process(flow);
}
for kid in flow::child_iter(flow) {
doit(kid, assign_inline_sizes, assign_block_sizes);
}
if assign_block_sizes.should_process(flow) {
assign_block_sizes.process(flow);
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let root = &mut **root;
if opts::get().bubble_inline_sizes_separately {
let bubble_inline_sizes = BubbleISizes { layout_context: &layout_context };
{
let root: &mut Flow = root;
root.traverse_postorder(&bubble_inline_sizes);
}
}
let assign_inline_sizes = AssignISizes { layout_context: &layout_context };
let assign_block_sizes = AssignBSizesAndStoreOverflow { layout_context: &layout_context };
doit(root, assign_inline_sizes, assign_block_sizes);
}
pub fn build_display_list_for_subtree(root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow,
compute_absolute_positions: ComputeAbsolutePositions,
build_display_list: BuildDisplayList) {
if compute_absolute_positions.should_process(flow) {
compute_absolute_positions.process(flow);
}
for kid in flow::mut_base(flow).child_iter() {
doit(kid, compute_absolute_positions, build_display_list);
}
if build_display_list.should_process(flow) {
build_display_list.process(flow);
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let compute_absolute_positions = ComputeAbsolutePositions { layout_context: &layout_context };
let build_display_list = BuildDisplayList { layout_context: &layout_context };
doit(&mut **root, compute_absolute_positions, build_display_list);
}
pub fn iterate_through_flow_tree_fragment_border_boxes(root: &mut FlowRef,
iterator: &mut FragmentBorderBoxIterator) | }
| {
fn doit(flow: &mut Flow,
iterator: &mut FragmentBorderBoxIterator,
stacking_context_position: &Point2D<Au>) {
flow.iterate_through_fragment_border_boxes(iterator, stacking_context_position);
for kid in flow::mut_base(flow).child_iter() {
let stacking_context_position =
if kid.is_block_flow() && kid.as_block().fragment.establishes_stacking_context() {
*stacking_context_position + flow::base(kid).stacking_relative_position
} else {
*stacking_context_position
};
// FIXME(#2795): Get the real container size.
doit(kid, iterator, &stacking_context_position);
}
}
doit(&mut **root, iterator, &ZERO_POINT); | identifier_body |
sequential.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements sequential traversals over the DOM and flow trees.
use context::{LayoutContext, SharedLayoutContext};
use flow::{self, Flow, ImmutableFlowUtils, InorderFlowTraversal, MutableFlowUtils};
use flow::{PostorderFlowTraversal, PreorderFlowTraversal};
use flow_ref::FlowRef;
use fragment::FragmentBorderBoxIterator;
use generated_content::ResolveGeneratedContent;
use traversal::{BubbleISizes, RecalcStyleForNode, ConstructFlows};
use traversal::{AssignBSizesAndStoreOverflow, AssignISizes};
use traversal::{ComputeAbsolutePositions, BuildDisplayList};
use wrapper::LayoutNode;
use wrapper::{PostorderNodeMutTraversal};
use wrapper::{PreorderDomTraversal, PostorderDomTraversal};
use euclid::point::Point2D;
use util::geometry::{Au, ZERO_POINT};
use util::opts;
pub fn traverse_dom_preorder(root: LayoutNode,
shared_layout_context: &SharedLayoutContext) {
fn | (node: LayoutNode, recalc_style: RecalcStyleForNode, construct_flows: ConstructFlows) {
recalc_style.process(node);
for kid in node.children() {
doit(kid, recalc_style, construct_flows);
}
construct_flows.process(node);
}
let layout_context = LayoutContext::new(shared_layout_context);
let recalc_style = RecalcStyleForNode { layout_context: &layout_context };
let construct_flows = ConstructFlows { layout_context: &layout_context };
doit(root, recalc_style, construct_flows);
}
pub fn resolve_generated_content(root: &mut FlowRef, shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow, level: u32, traversal: &mut ResolveGeneratedContent) {
if!traversal.should_process(flow) {
return
}
traversal.process(flow, level);
for kid in flow::mut_base(flow).children.iter_mut() {
doit(kid, level + 1, traversal)
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let mut traversal = ResolveGeneratedContent::new(&layout_context);
doit(&mut **root, 0, &mut traversal)
}
pub fn traverse_flow_tree_preorder(root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow,
assign_inline_sizes: AssignISizes,
assign_block_sizes: AssignBSizesAndStoreOverflow) {
if assign_inline_sizes.should_process(flow) {
assign_inline_sizes.process(flow);
}
for kid in flow::child_iter(flow) {
doit(kid, assign_inline_sizes, assign_block_sizes);
}
if assign_block_sizes.should_process(flow) {
assign_block_sizes.process(flow);
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let root = &mut **root;
if opts::get().bubble_inline_sizes_separately {
let bubble_inline_sizes = BubbleISizes { layout_context: &layout_context };
{
let root: &mut Flow = root;
root.traverse_postorder(&bubble_inline_sizes);
}
}
let assign_inline_sizes = AssignISizes { layout_context: &layout_context };
let assign_block_sizes = AssignBSizesAndStoreOverflow { layout_context: &layout_context };
doit(root, assign_inline_sizes, assign_block_sizes);
}
pub fn build_display_list_for_subtree(root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow,
compute_absolute_positions: ComputeAbsolutePositions,
build_display_list: BuildDisplayList) {
if compute_absolute_positions.should_process(flow) {
compute_absolute_positions.process(flow);
}
for kid in flow::mut_base(flow).child_iter() {
doit(kid, compute_absolute_positions, build_display_list);
}
if build_display_list.should_process(flow) {
build_display_list.process(flow);
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let compute_absolute_positions = ComputeAbsolutePositions { layout_context: &layout_context };
let build_display_list = BuildDisplayList { layout_context: &layout_context };
doit(&mut **root, compute_absolute_positions, build_display_list);
}
pub fn iterate_through_flow_tree_fragment_border_boxes(root: &mut FlowRef,
iterator: &mut FragmentBorderBoxIterator) {
fn doit(flow: &mut Flow,
iterator: &mut FragmentBorderBoxIterator,
stacking_context_position: &Point2D<Au>) {
flow.iterate_through_fragment_border_boxes(iterator, stacking_context_position);
for kid in flow::mut_base(flow).child_iter() {
let stacking_context_position =
if kid.is_block_flow() && kid.as_block().fragment.establishes_stacking_context() {
*stacking_context_position + flow::base(kid).stacking_relative_position
} else {
*stacking_context_position
};
// FIXME(#2795): Get the real container size.
doit(kid, iterator, &stacking_context_position);
}
}
doit(&mut **root, iterator, &ZERO_POINT);
}
| doit | identifier_name |
sequential.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements sequential traversals over the DOM and flow trees.
use context::{LayoutContext, SharedLayoutContext};
use flow::{self, Flow, ImmutableFlowUtils, InorderFlowTraversal, MutableFlowUtils};
use flow::{PostorderFlowTraversal, PreorderFlowTraversal};
use flow_ref::FlowRef;
use fragment::FragmentBorderBoxIterator;
use generated_content::ResolveGeneratedContent;
use traversal::{BubbleISizes, RecalcStyleForNode, ConstructFlows};
use traversal::{AssignBSizesAndStoreOverflow, AssignISizes};
use traversal::{ComputeAbsolutePositions, BuildDisplayList};
use wrapper::LayoutNode;
use wrapper::{PostorderNodeMutTraversal};
use wrapper::{PreorderDomTraversal, PostorderDomTraversal};
use euclid::point::Point2D;
use util::geometry::{Au, ZERO_POINT};
use util::opts;
pub fn traverse_dom_preorder(root: LayoutNode,
shared_layout_context: &SharedLayoutContext) {
fn doit(node: LayoutNode, recalc_style: RecalcStyleForNode, construct_flows: ConstructFlows) {
recalc_style.process(node);
for kid in node.children() {
doit(kid, recalc_style, construct_flows);
}
construct_flows.process(node);
}
let layout_context = LayoutContext::new(shared_layout_context);
let recalc_style = RecalcStyleForNode { layout_context: &layout_context };
let construct_flows = ConstructFlows { layout_context: &layout_context };
doit(root, recalc_style, construct_flows);
}
pub fn resolve_generated_content(root: &mut FlowRef, shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow, level: u32, traversal: &mut ResolveGeneratedContent) {
if!traversal.should_process(flow) {
return
}
traversal.process(flow, level);
for kid in flow::mut_base(flow).children.iter_mut() {
doit(kid, level + 1, traversal)
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let mut traversal = ResolveGeneratedContent::new(&layout_context);
doit(&mut **root, 0, &mut traversal)
}
pub fn traverse_flow_tree_preorder(root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow,
assign_inline_sizes: AssignISizes,
assign_block_sizes: AssignBSizesAndStoreOverflow) {
if assign_inline_sizes.should_process(flow) {
assign_inline_sizes.process(flow);
}
for kid in flow::child_iter(flow) {
doit(kid, assign_inline_sizes, assign_block_sizes);
}
if assign_block_sizes.should_process(flow) {
assign_block_sizes.process(flow);
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let root = &mut **root;
if opts::get().bubble_inline_sizes_separately {
let bubble_inline_sizes = BubbleISizes { layout_context: &layout_context };
{
let root: &mut Flow = root;
root.traverse_postorder(&bubble_inline_sizes);
}
}
let assign_inline_sizes = AssignISizes { layout_context: &layout_context };
let assign_block_sizes = AssignBSizesAndStoreOverflow { layout_context: &layout_context };
doit(root, assign_inline_sizes, assign_block_sizes);
}
pub fn build_display_list_for_subtree(root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow,
compute_absolute_positions: ComputeAbsolutePositions,
build_display_list: BuildDisplayList) {
if compute_absolute_positions.should_process(flow) {
compute_absolute_positions.process(flow); |
if build_display_list.should_process(flow) {
build_display_list.process(flow);
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let compute_absolute_positions = ComputeAbsolutePositions { layout_context: &layout_context };
let build_display_list = BuildDisplayList { layout_context: &layout_context };
doit(&mut **root, compute_absolute_positions, build_display_list);
}
pub fn iterate_through_flow_tree_fragment_border_boxes(root: &mut FlowRef,
iterator: &mut FragmentBorderBoxIterator) {
fn doit(flow: &mut Flow,
iterator: &mut FragmentBorderBoxIterator,
stacking_context_position: &Point2D<Au>) {
flow.iterate_through_fragment_border_boxes(iterator, stacking_context_position);
for kid in flow::mut_base(flow).child_iter() {
let stacking_context_position =
if kid.is_block_flow() && kid.as_block().fragment.establishes_stacking_context() {
*stacking_context_position + flow::base(kid).stacking_relative_position
} else {
*stacking_context_position
};
// FIXME(#2795): Get the real container size.
doit(kid, iterator, &stacking_context_position);
}
}
doit(&mut **root, iterator, &ZERO_POINT);
} | }
for kid in flow::mut_base(flow).child_iter() {
doit(kid, compute_absolute_positions, build_display_list);
} | random_line_split |
sequential.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Implements sequential traversals over the DOM and flow trees.
use context::{LayoutContext, SharedLayoutContext};
use flow::{self, Flow, ImmutableFlowUtils, InorderFlowTraversal, MutableFlowUtils};
use flow::{PostorderFlowTraversal, PreorderFlowTraversal};
use flow_ref::FlowRef;
use fragment::FragmentBorderBoxIterator;
use generated_content::ResolveGeneratedContent;
use traversal::{BubbleISizes, RecalcStyleForNode, ConstructFlows};
use traversal::{AssignBSizesAndStoreOverflow, AssignISizes};
use traversal::{ComputeAbsolutePositions, BuildDisplayList};
use wrapper::LayoutNode;
use wrapper::{PostorderNodeMutTraversal};
use wrapper::{PreorderDomTraversal, PostorderDomTraversal};
use euclid::point::Point2D;
use util::geometry::{Au, ZERO_POINT};
use util::opts;
pub fn traverse_dom_preorder(root: LayoutNode,
shared_layout_context: &SharedLayoutContext) {
fn doit(node: LayoutNode, recalc_style: RecalcStyleForNode, construct_flows: ConstructFlows) {
recalc_style.process(node);
for kid in node.children() {
doit(kid, recalc_style, construct_flows);
}
construct_flows.process(node);
}
let layout_context = LayoutContext::new(shared_layout_context);
let recalc_style = RecalcStyleForNode { layout_context: &layout_context };
let construct_flows = ConstructFlows { layout_context: &layout_context };
doit(root, recalc_style, construct_flows);
}
pub fn resolve_generated_content(root: &mut FlowRef, shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow, level: u32, traversal: &mut ResolveGeneratedContent) {
if!traversal.should_process(flow) {
return
}
traversal.process(flow, level);
for kid in flow::mut_base(flow).children.iter_mut() {
doit(kid, level + 1, traversal)
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let mut traversal = ResolveGeneratedContent::new(&layout_context);
doit(&mut **root, 0, &mut traversal)
}
pub fn traverse_flow_tree_preorder(root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow,
assign_inline_sizes: AssignISizes,
assign_block_sizes: AssignBSizesAndStoreOverflow) {
if assign_inline_sizes.should_process(flow) |
for kid in flow::child_iter(flow) {
doit(kid, assign_inline_sizes, assign_block_sizes);
}
if assign_block_sizes.should_process(flow) {
assign_block_sizes.process(flow);
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let root = &mut **root;
if opts::get().bubble_inline_sizes_separately {
let bubble_inline_sizes = BubbleISizes { layout_context: &layout_context };
{
let root: &mut Flow = root;
root.traverse_postorder(&bubble_inline_sizes);
}
}
let assign_inline_sizes = AssignISizes { layout_context: &layout_context };
let assign_block_sizes = AssignBSizesAndStoreOverflow { layout_context: &layout_context };
doit(root, assign_inline_sizes, assign_block_sizes);
}
pub fn build_display_list_for_subtree(root: &mut FlowRef,
shared_layout_context: &SharedLayoutContext) {
fn doit(flow: &mut Flow,
compute_absolute_positions: ComputeAbsolutePositions,
build_display_list: BuildDisplayList) {
if compute_absolute_positions.should_process(flow) {
compute_absolute_positions.process(flow);
}
for kid in flow::mut_base(flow).child_iter() {
doit(kid, compute_absolute_positions, build_display_list);
}
if build_display_list.should_process(flow) {
build_display_list.process(flow);
}
}
let layout_context = LayoutContext::new(shared_layout_context);
let compute_absolute_positions = ComputeAbsolutePositions { layout_context: &layout_context };
let build_display_list = BuildDisplayList { layout_context: &layout_context };
doit(&mut **root, compute_absolute_positions, build_display_list);
}
pub fn iterate_through_flow_tree_fragment_border_boxes(root: &mut FlowRef,
iterator: &mut FragmentBorderBoxIterator) {
fn doit(flow: &mut Flow,
iterator: &mut FragmentBorderBoxIterator,
stacking_context_position: &Point2D<Au>) {
flow.iterate_through_fragment_border_boxes(iterator, stacking_context_position);
for kid in flow::mut_base(flow).child_iter() {
let stacking_context_position =
if kid.is_block_flow() && kid.as_block().fragment.establishes_stacking_context() {
*stacking_context_position + flow::base(kid).stacking_relative_position
} else {
*stacking_context_position
};
// FIXME(#2795): Get the real container size.
doit(kid, iterator, &stacking_context_position);
}
}
doit(&mut **root, iterator, &ZERO_POINT);
}
| {
assign_inline_sizes.process(flow);
} | conditional_block |
lib.rs | use std::process::{Command, Stdio};
use std::collections::HashSet;
use std::thread;
struct ProcessSets {
prev_set: HashSet<Process>,
curr_set: HashSet<Process>,
}
#[derive(PartialEq, Eq, Clone, Hash)]
pub struct Process {
pub pid: u32,
pub description: String,
}
pub trait ProcessWatcherCallback : Send {
fn on_open(&self, process: Process) -> ();
fn on_close(&self, process: Process) -> ();
}
fn get_processes(sets: &mut ProcessSets) -> (HashSet<Process>, HashSet<Process>) {
let child = Command::new("/bin/ps").arg("-e")
.stdout(Stdio::piped()).spawn().expect("process spawn failed");
let output = child.wait_with_output().expect("failed to wait on process");
let vector = output.stdout.as_slice();
let newline : u8 = 10;
let iter = vector.split(|num| num == &newline);
for line in iter {
let str_line = String::from_utf8_lossy(line);
let mut fields = str_line.split_whitespace();
let field = fields.next();
if field.is_some() {
let pid: u32 = match field.unwrap().trim().parse() {
Ok(num) => num, | Err(_) => continue,
};
fields.next();
fields.next();
let desc : String = fields.next().unwrap().to_owned();
//filtering processes opened by calling "/bin/ps"
if desc.ne("/bin/ps") {
sets.curr_set.insert(Process { pid: pid, description: desc });
}
}
}
let open_set;
let mut closed_set: HashSet<Process> = HashSet::new();
//first run, the previous set will be empty
if sets.prev_set.is_empty() {
open_set = sets.curr_set.iter().cloned().collect();
}
else {
open_set = sets.curr_set.difference(&sets.prev_set).cloned().collect();
closed_set = sets.prev_set.difference(&sets.curr_set).cloned().collect();
}
sets.prev_set = sets.curr_set.clone();
sets.curr_set.clear();
return (open_set, closed_set);
}
pub fn watch_with_callback<TCallback :'static + ProcessWatcherCallback>(callback: TCallback) {
let mut sets = ProcessSets { prev_set: HashSet::new(), curr_set: HashSet::new() };
thread::spawn( move || {
loop {
let changed_sets = get_processes(&mut sets);
for open in changed_sets.0.iter() {
callback.on_open(open.clone());
}
for close in changed_sets.1.iter() {
callback.on_close(close.clone());
}
}
});
}
pub fn watch_with_closure<F, G>(on_open: F, on_close: G)
where F :'static + Fn(Process) + Send, G :'static + Fn(Process) + Send {
let mut sets = ProcessSets { prev_set: HashSet::new(), curr_set: HashSet::new() };
thread::spawn( move || {
loop {
let changed_sets = get_processes(&mut sets);
for open in changed_sets.0.iter() {
on_open(open.clone());
}
for close in changed_sets.1.iter() {
on_close(close.clone());
}
}
});
} | random_line_split |
|
lib.rs | use std::process::{Command, Stdio};
use std::collections::HashSet;
use std::thread;
struct ProcessSets {
prev_set: HashSet<Process>,
curr_set: HashSet<Process>,
}
#[derive(PartialEq, Eq, Clone, Hash)]
pub struct Process {
pub pid: u32,
pub description: String,
}
pub trait ProcessWatcherCallback : Send {
fn on_open(&self, process: Process) -> ();
fn on_close(&self, process: Process) -> ();
}
fn get_processes(sets: &mut ProcessSets) -> (HashSet<Process>, HashSet<Process>) {
let child = Command::new("/bin/ps").arg("-e")
.stdout(Stdio::piped()).spawn().expect("process spawn failed");
let output = child.wait_with_output().expect("failed to wait on process");
let vector = output.stdout.as_slice();
let newline : u8 = 10;
let iter = vector.split(|num| num == &newline);
for line in iter {
let str_line = String::from_utf8_lossy(line);
let mut fields = str_line.split_whitespace();
let field = fields.next();
if field.is_some() {
let pid: u32 = match field.unwrap().trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
fields.next();
fields.next();
let desc : String = fields.next().unwrap().to_owned();
//filtering processes opened by calling "/bin/ps"
if desc.ne("/bin/ps") {
sets.curr_set.insert(Process { pid: pid, description: desc });
}
}
}
let open_set;
let mut closed_set: HashSet<Process> = HashSet::new();
//first run, the previous set will be empty
if sets.prev_set.is_empty() {
open_set = sets.curr_set.iter().cloned().collect();
}
else |
sets.prev_set = sets.curr_set.clone();
sets.curr_set.clear();
return (open_set, closed_set);
}
pub fn watch_with_callback<TCallback :'static + ProcessWatcherCallback>(callback: TCallback) {
let mut sets = ProcessSets { prev_set: HashSet::new(), curr_set: HashSet::new() };
thread::spawn( move || {
loop {
let changed_sets = get_processes(&mut sets);
for open in changed_sets.0.iter() {
callback.on_open(open.clone());
}
for close in changed_sets.1.iter() {
callback.on_close(close.clone());
}
}
});
}
pub fn watch_with_closure<F, G>(on_open: F, on_close: G)
where F :'static + Fn(Process) + Send, G :'static + Fn(Process) + Send {
let mut sets = ProcessSets { prev_set: HashSet::new(), curr_set: HashSet::new() };
thread::spawn( move || {
loop {
let changed_sets = get_processes(&mut sets);
for open in changed_sets.0.iter() {
on_open(open.clone());
}
for close in changed_sets.1.iter() {
on_close(close.clone());
}
}
});
} | {
open_set = sets.curr_set.difference(&sets.prev_set).cloned().collect();
closed_set = sets.prev_set.difference(&sets.curr_set).cloned().collect();
} | conditional_block |
lib.rs | use std::process::{Command, Stdio};
use std::collections::HashSet;
use std::thread;
struct ProcessSets {
prev_set: HashSet<Process>,
curr_set: HashSet<Process>,
}
#[derive(PartialEq, Eq, Clone, Hash)]
pub struct Process {
pub pid: u32,
pub description: String,
}
pub trait ProcessWatcherCallback : Send {
fn on_open(&self, process: Process) -> ();
fn on_close(&self, process: Process) -> ();
}
fn get_processes(sets: &mut ProcessSets) -> (HashSet<Process>, HashSet<Process>) {
let child = Command::new("/bin/ps").arg("-e")
.stdout(Stdio::piped()).spawn().expect("process spawn failed");
let output = child.wait_with_output().expect("failed to wait on process");
let vector = output.stdout.as_slice();
let newline : u8 = 10;
let iter = vector.split(|num| num == &newline);
for line in iter {
let str_line = String::from_utf8_lossy(line);
let mut fields = str_line.split_whitespace();
let field = fields.next();
if field.is_some() {
let pid: u32 = match field.unwrap().trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
fields.next();
fields.next();
let desc : String = fields.next().unwrap().to_owned();
//filtering processes opened by calling "/bin/ps"
if desc.ne("/bin/ps") {
sets.curr_set.insert(Process { pid: pid, description: desc });
}
}
}
let open_set;
let mut closed_set: HashSet<Process> = HashSet::new();
//first run, the previous set will be empty
if sets.prev_set.is_empty() {
open_set = sets.curr_set.iter().cloned().collect();
}
else {
open_set = sets.curr_set.difference(&sets.prev_set).cloned().collect();
closed_set = sets.prev_set.difference(&sets.curr_set).cloned().collect();
}
sets.prev_set = sets.curr_set.clone();
sets.curr_set.clear();
return (open_set, closed_set);
}
pub fn watch_with_callback<TCallback :'static + ProcessWatcherCallback>(callback: TCallback) {
let mut sets = ProcessSets { prev_set: HashSet::new(), curr_set: HashSet::new() };
thread::spawn( move || {
loop {
let changed_sets = get_processes(&mut sets);
for open in changed_sets.0.iter() {
callback.on_open(open.clone());
}
for close in changed_sets.1.iter() {
callback.on_close(close.clone());
}
}
});
}
pub fn | <F, G>(on_open: F, on_close: G)
where F :'static + Fn(Process) + Send, G :'static + Fn(Process) + Send {
let mut sets = ProcessSets { prev_set: HashSet::new(), curr_set: HashSet::new() };
thread::spawn( move || {
loop {
let changed_sets = get_processes(&mut sets);
for open in changed_sets.0.iter() {
on_open(open.clone());
}
for close in changed_sets.1.iter() {
on_close(close.clone());
}
}
});
} | watch_with_closure | identifier_name |
client.rs | //! Handle network connections for a varlink service
#![allow(dead_code)]
use std::net::TcpStream;
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, IntoRawFd};
#[cfg(unix)]
use std::os::unix::net::UnixStream;
use std::process::Child;
#[cfg(unix)]
use libc::{close, dup2, getpid};
use tempfile::TempDir;
#[cfg(windows)]
use uds_windows::UnixStream;
use crate::error::*;
use crate::stream::Stream;
#[allow(clippy::try_err)]
pub fn varlink_connect<S:?Sized + AsRef<str>>(address: &S) -> Result<(Box<dyn Stream>, String)> {
let address = address.as_ref();
let new_address: String = address.into();
if let Some(addr) = new_address.strip_prefix("tcp:") {
Ok((
Box::new(TcpStream::connect(&addr).map_err(map_context!())?),
new_address,
))
} else if let Some(addr) = new_address.strip_prefix("unix:") {
let mut addr = String::from(addr.split(';').next().unwrap());
if addr.starts_with('@') {
addr = addr.replacen('@', "\0", 1);
return get_abstract_unixstream(&addr)
.map(|v| (Box::new(v) as Box<dyn Stream>, new_address));
}
Ok((
Box::new(UnixStream::connect(addr).map_err(map_context!())?),
new_address,
))
} else {
Err(context!(ErrorKind::InvalidAddress))?
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn get_abstract_unixstream(addr: &str) -> Result<UnixStream> {
// FIXME: abstract unix domains sockets still not in std
// FIXME: https://github.com/rust-lang/rust/issues/14194
use std::os::unix::io::FromRawFd;
use unix_socket::UnixStream as AbstractStream;
unsafe {
Ok(UnixStream::from_raw_fd(
AbstractStream::connect(addr)
.map_err(map_context!())?
.into_raw_fd(),
))
}
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn get_abstract_unixstream(_addr: &str) -> Result<UnixStream> {
Err(context!(ErrorKind::InvalidAddress))
}
#[cfg(windows)]
pub fn varlink_exec<S:?Sized + AsRef<str>>(
_address: &S,
) -> Result<(Child, String, Option<TempDir>)> {
Err(context!(ErrorKind::MethodNotImplemented(
"varlink_exec".into()
)))
}
#[cfg(unix)]
pub fn varlink_exec<S:?Sized + AsRef<str>>(
address: &S,
) -> Result<(Child, String, Option<TempDir>)> {
use std::env;
use std::os::unix::process::CommandExt;
use std::process::Command;
use tempfile::tempdir;
let executable = String::from("exec ") + address.as_ref();
use unix_socket::UnixListener;
let dir = tempdir().map_err(map_context!())?;
let file_path = dir.path().join("varlink-socket");
let listener = UnixListener::bind(file_path.clone()).map_err(map_context!())?;
let fd = listener.as_raw_fd();
let child = unsafe {
Command::new("sh")
.arg("-c")
.arg(executable)
.pre_exec({
let file_path = file_path.clone();
move || {
dup2(2, 1);
if fd!= 3 {
dup2(fd, 3);
close(fd);
}
env::set_var("VARLINK_ADDRESS", format!("unix:{}", file_path.display()));
env::set_var("LISTEN_FDS", "1");
env::set_var("LISTEN_FDNAMES", "varlink");
env::set_var("LISTEN_PID", format!("{}", getpid()));
Ok(())
}
})
.spawn()
.map_err(map_context!())?
};
Ok((child, format!("unix:{}", file_path.display()), Some(dir)))
}
#[cfg(windows)]
pub fn varlink_bridge<S:?Sized + AsRef<str>>(address: &S) -> Result<(Child, Box<dyn Stream>)> {
use std::io::copy;
use std::process::{Command, Stdio};
use std::thread;
let (stream0, stream1) = UnixStream::pair().map_err(map_context!())?;
let executable = address.as_ref();
let mut child = Command::new("cmd")
.arg("/C")
.arg(executable)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.map_err(map_context!())?;
let mut client_writer = child.stdin.take().unwrap();
let mut client_reader = child.stdout.take().unwrap();
let mut service_writer = stream1.try_clone().map_err(map_context!())?;
let mut service_reader = stream1;
thread::spawn(move || copy(&mut client_reader, &mut service_writer));
thread::spawn(move || copy(&mut service_reader, &mut client_writer));
Ok((child, Box::new(stream0)))
}
#[cfg(unix)]
pub fn varlink_bridge<S:?Sized + AsRef<str>>(address: &S) -> Result<(Child, Box<dyn Stream>)> | {
use std::os::unix::io::FromRawFd;
use std::process::Command;
let executable = address.as_ref();
// use unix_socket::UnixStream;
let (stream0, stream1) = UnixStream::pair().map_err(map_context!())?;
let fd = stream1.into_raw_fd();
let childin = unsafe { ::std::fs::File::from_raw_fd(fd) };
let childout = unsafe { ::std::fs::File::from_raw_fd(fd) };
let child = Command::new("sh")
.arg("-c")
.arg(executable)
.stdin(childin)
.stdout(childout)
.spawn()
.map_err(map_context!())?;
Ok((child, Box::new(stream0)))
} | identifier_body |
|
client.rs | //! Handle network connections for a varlink service
#![allow(dead_code)]
use std::net::TcpStream;
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, IntoRawFd};
#[cfg(unix)]
use std::os::unix::net::UnixStream;
use std::process::Child;
#[cfg(unix)]
use libc::{close, dup2, getpid};
use tempfile::TempDir;
#[cfg(windows)]
use uds_windows::UnixStream;
use crate::error::*;
use crate::stream::Stream;
#[allow(clippy::try_err)]
pub fn varlink_connect<S:?Sized + AsRef<str>>(address: &S) -> Result<(Box<dyn Stream>, String)> {
let address = address.as_ref();
let new_address: String = address.into();
if let Some(addr) = new_address.strip_prefix("tcp:") {
Ok((
Box::new(TcpStream::connect(&addr).map_err(map_context!())?),
new_address,
))
} else if let Some(addr) = new_address.strip_prefix("unix:") {
let mut addr = String::from(addr.split(';').next().unwrap());
if addr.starts_with('@') {
addr = addr.replacen('@', "\0", 1);
return get_abstract_unixstream(&addr)
.map(|v| (Box::new(v) as Box<dyn Stream>, new_address));
}
Ok((
Box::new(UnixStream::connect(addr).map_err(map_context!())?),
new_address,
))
} else {
Err(context!(ErrorKind::InvalidAddress))?
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn get_abstract_unixstream(addr: &str) -> Result<UnixStream> {
// FIXME: abstract unix domains sockets still not in std
// FIXME: https://github.com/rust-lang/rust/issues/14194
use std::os::unix::io::FromRawFd;
use unix_socket::UnixStream as AbstractStream;
unsafe {
Ok(UnixStream::from_raw_fd(
AbstractStream::connect(addr)
.map_err(map_context!())?
.into_raw_fd(),
))
}
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn | (_addr: &str) -> Result<UnixStream> {
Err(context!(ErrorKind::InvalidAddress))
}
#[cfg(windows)]
pub fn varlink_exec<S:?Sized + AsRef<str>>(
_address: &S,
) -> Result<(Child, String, Option<TempDir>)> {
Err(context!(ErrorKind::MethodNotImplemented(
"varlink_exec".into()
)))
}
#[cfg(unix)]
pub fn varlink_exec<S:?Sized + AsRef<str>>(
address: &S,
) -> Result<(Child, String, Option<TempDir>)> {
use std::env;
use std::os::unix::process::CommandExt;
use std::process::Command;
use tempfile::tempdir;
let executable = String::from("exec ") + address.as_ref();
use unix_socket::UnixListener;
let dir = tempdir().map_err(map_context!())?;
let file_path = dir.path().join("varlink-socket");
let listener = UnixListener::bind(file_path.clone()).map_err(map_context!())?;
let fd = listener.as_raw_fd();
let child = unsafe {
Command::new("sh")
.arg("-c")
.arg(executable)
.pre_exec({
let file_path = file_path.clone();
move || {
dup2(2, 1);
if fd!= 3 {
dup2(fd, 3);
close(fd);
}
env::set_var("VARLINK_ADDRESS", format!("unix:{}", file_path.display()));
env::set_var("LISTEN_FDS", "1");
env::set_var("LISTEN_FDNAMES", "varlink");
env::set_var("LISTEN_PID", format!("{}", getpid()));
Ok(())
}
})
.spawn()
.map_err(map_context!())?
};
Ok((child, format!("unix:{}", file_path.display()), Some(dir)))
}
#[cfg(windows)]
pub fn varlink_bridge<S:?Sized + AsRef<str>>(address: &S) -> Result<(Child, Box<dyn Stream>)> {
use std::io::copy;
use std::process::{Command, Stdio};
use std::thread;
let (stream0, stream1) = UnixStream::pair().map_err(map_context!())?;
let executable = address.as_ref();
let mut child = Command::new("cmd")
.arg("/C")
.arg(executable)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.map_err(map_context!())?;
let mut client_writer = child.stdin.take().unwrap();
let mut client_reader = child.stdout.take().unwrap();
let mut service_writer = stream1.try_clone().map_err(map_context!())?;
let mut service_reader = stream1;
thread::spawn(move || copy(&mut client_reader, &mut service_writer));
thread::spawn(move || copy(&mut service_reader, &mut client_writer));
Ok((child, Box::new(stream0)))
}
#[cfg(unix)]
pub fn varlink_bridge<S:?Sized + AsRef<str>>(address: &S) -> Result<(Child, Box<dyn Stream>)> {
use std::os::unix::io::FromRawFd;
use std::process::Command;
let executable = address.as_ref();
// use unix_socket::UnixStream;
let (stream0, stream1) = UnixStream::pair().map_err(map_context!())?;
let fd = stream1.into_raw_fd();
let childin = unsafe { ::std::fs::File::from_raw_fd(fd) };
let childout = unsafe { ::std::fs::File::from_raw_fd(fd) };
let child = Command::new("sh")
.arg("-c")
.arg(executable)
.stdin(childin)
.stdout(childout)
.spawn()
.map_err(map_context!())?;
Ok((child, Box::new(stream0)))
}
| get_abstract_unixstream | identifier_name |
client.rs | //! Handle network connections for a varlink service
#![allow(dead_code)]
use std::net::TcpStream;
#[cfg(unix)]
use std::os::unix::io::{AsRawFd, IntoRawFd};
#[cfg(unix)]
use std::os::unix::net::UnixStream;
use std::process::Child;
#[cfg(unix)]
use libc::{close, dup2, getpid};
use tempfile::TempDir;
#[cfg(windows)]
use uds_windows::UnixStream;
use crate::error::*;
use crate::stream::Stream;
#[allow(clippy::try_err)]
pub fn varlink_connect<S:?Sized + AsRef<str>>(address: &S) -> Result<(Box<dyn Stream>, String)> {
let address = address.as_ref();
let new_address: String = address.into();
if let Some(addr) = new_address.strip_prefix("tcp:") {
Ok((
Box::new(TcpStream::connect(&addr).map_err(map_context!())?),
new_address,
))
} else if let Some(addr) = new_address.strip_prefix("unix:") {
let mut addr = String::from(addr.split(';').next().unwrap());
if addr.starts_with('@') {
addr = addr.replacen('@', "\0", 1);
return get_abstract_unixstream(&addr)
.map(|v| (Box::new(v) as Box<dyn Stream>, new_address));
}
Ok(( | } else {
Err(context!(ErrorKind::InvalidAddress))?
}
}
#[cfg(any(target_os = "linux", target_os = "android"))]
fn get_abstract_unixstream(addr: &str) -> Result<UnixStream> {
// FIXME: abstract unix domains sockets still not in std
// FIXME: https://github.com/rust-lang/rust/issues/14194
use std::os::unix::io::FromRawFd;
use unix_socket::UnixStream as AbstractStream;
unsafe {
Ok(UnixStream::from_raw_fd(
AbstractStream::connect(addr)
.map_err(map_context!())?
.into_raw_fd(),
))
}
}
#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn get_abstract_unixstream(_addr: &str) -> Result<UnixStream> {
Err(context!(ErrorKind::InvalidAddress))
}
#[cfg(windows)]
pub fn varlink_exec<S:?Sized + AsRef<str>>(
_address: &S,
) -> Result<(Child, String, Option<TempDir>)> {
Err(context!(ErrorKind::MethodNotImplemented(
"varlink_exec".into()
)))
}
#[cfg(unix)]
pub fn varlink_exec<S:?Sized + AsRef<str>>(
address: &S,
) -> Result<(Child, String, Option<TempDir>)> {
use std::env;
use std::os::unix::process::CommandExt;
use std::process::Command;
use tempfile::tempdir;
let executable = String::from("exec ") + address.as_ref();
use unix_socket::UnixListener;
let dir = tempdir().map_err(map_context!())?;
let file_path = dir.path().join("varlink-socket");
let listener = UnixListener::bind(file_path.clone()).map_err(map_context!())?;
let fd = listener.as_raw_fd();
let child = unsafe {
Command::new("sh")
.arg("-c")
.arg(executable)
.pre_exec({
let file_path = file_path.clone();
move || {
dup2(2, 1);
if fd!= 3 {
dup2(fd, 3);
close(fd);
}
env::set_var("VARLINK_ADDRESS", format!("unix:{}", file_path.display()));
env::set_var("LISTEN_FDS", "1");
env::set_var("LISTEN_FDNAMES", "varlink");
env::set_var("LISTEN_PID", format!("{}", getpid()));
Ok(())
}
})
.spawn()
.map_err(map_context!())?
};
Ok((child, format!("unix:{}", file_path.display()), Some(dir)))
}
#[cfg(windows)]
pub fn varlink_bridge<S:?Sized + AsRef<str>>(address: &S) -> Result<(Child, Box<dyn Stream>)> {
use std::io::copy;
use std::process::{Command, Stdio};
use std::thread;
let (stream0, stream1) = UnixStream::pair().map_err(map_context!())?;
let executable = address.as_ref();
let mut child = Command::new("cmd")
.arg("/C")
.arg(executable)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()
.map_err(map_context!())?;
let mut client_writer = child.stdin.take().unwrap();
let mut client_reader = child.stdout.take().unwrap();
let mut service_writer = stream1.try_clone().map_err(map_context!())?;
let mut service_reader = stream1;
thread::spawn(move || copy(&mut client_reader, &mut service_writer));
thread::spawn(move || copy(&mut service_reader, &mut client_writer));
Ok((child, Box::new(stream0)))
}
#[cfg(unix)]
pub fn varlink_bridge<S:?Sized + AsRef<str>>(address: &S) -> Result<(Child, Box<dyn Stream>)> {
use std::os::unix::io::FromRawFd;
use std::process::Command;
let executable = address.as_ref();
// use unix_socket::UnixStream;
let (stream0, stream1) = UnixStream::pair().map_err(map_context!())?;
let fd = stream1.into_raw_fd();
let childin = unsafe { ::std::fs::File::from_raw_fd(fd) };
let childout = unsafe { ::std::fs::File::from_raw_fd(fd) };
let child = Command::new("sh")
.arg("-c")
.arg(executable)
.stdin(childin)
.stdout(childout)
.spawn()
.map_err(map_context!())?;
Ok((child, Box::new(stream0)))
} | Box::new(UnixStream::connect(addr).map_err(map_context!())?),
new_address,
)) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.