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 |
---|---|---|---|---|
oneshot.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an Arc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic uint variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
pub use self::Failure::*;
pub use self::UpgradeResult::*;
pub use self::SelectionResult::*;
use self::MyUpgrade::*;
use core::prelude::*;
use sync::mpsc::Receiver;
use sync::mpsc::blocking::{self, SignalToken};
use core::mem;
use sync::atomic::{AtomicUsize, Ordering};
// Various states you can find a port in.
const EMPTY: uint = 0; // initial state: no data, no blocked receiver
const DATA: uint = 1; // data ready for receiver to take
const DISCONNECTED: uint = 2; // channel is disconnected OR upgraded
// Any other value represents a pointer to a SignalToken value. The
// protocol ensures that when the state moves *to* a pointer,
// ownership of the token is given to the packet, and when the state
// moves *from* a pointer, ownership of the token is transferred to
// whoever changed the state.
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: AtomicUsize,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(SignalToken),
}
pub enum SelectionResult<T> {
SelCanceled,
SelUpgraded(SignalToken, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T: Send +'static> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: AtomicUsize::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> Result<(), T> {
// Sanity check
match self.upgrade {
NothingSent => {}
_ => panic!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, Ordering::SeqCst) {
// Sent the data, no one was waiting
EMPTY => Ok(()),
// Couldn't send the data, the port hung up first. Return the data
// back up the stack.
DISCONNECTED => {
Err(self.data.take().unwrap())
}
// Not possible, these are one-use channels
DATA => unreachable!(),
// There is a thread waiting on the other end. We leave the 'DATA'
// state inside so it'll pick it up on the other end.
ptr => unsafe {
SignalToken::cast_from_uint(ptr).signal();
Ok(())
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(Ordering::SeqCst) == EMPTY {
let (wait_token, signal_token) = blocking::tokens();
let ptr = unsafe { signal_token.cast_to_uint() };
// race with senders to enter the blocking state
if self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) == EMPTY {
wait_token.wait();
debug_assert!(self.state.load(Ordering::SeqCst)!= EMPTY);
} else {
// drop the signal token, since we never blocked
drop(unsafe { SignalToken::cast_from_uint(ptr) });
}
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, Ordering::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
}
}
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
// We are the sole receiver; there cannot be a blocking
// receiver already.
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => panic!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
ptr => UpWoke(unsafe { SignalToken::cast_from_uint(ptr) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
ptr => unsafe {
SignalToken::cast_from_uint(ptr).signal();
}
}
}
pub fn drop_port(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take().unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> {
let ptr = unsafe { token.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) {
EMPTY => SelSuccess,
DATA => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
DISCONNECTED if self.data.is_some() => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { SignalToken::cast_from_uint(ptr) }, upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(Ordering::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
|
ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select.
ptr => unsafe {
drop(SignalToken::cast_from_uint(ptr));
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T: Send +'static> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(Ordering::SeqCst), DISCONNECTED);
}
}
|
// of it (may fail)
|
random_line_split
|
oneshot.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an Arc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic uint variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
pub use self::Failure::*;
pub use self::UpgradeResult::*;
pub use self::SelectionResult::*;
use self::MyUpgrade::*;
use core::prelude::*;
use sync::mpsc::Receiver;
use sync::mpsc::blocking::{self, SignalToken};
use core::mem;
use sync::atomic::{AtomicUsize, Ordering};
// Various states you can find a port in.
const EMPTY: uint = 0; // initial state: no data, no blocked receiver
const DATA: uint = 1; // data ready for receiver to take
const DISCONNECTED: uint = 2; // channel is disconnected OR upgraded
// Any other value represents a pointer to a SignalToken value. The
// protocol ensures that when the state moves *to* a pointer,
// ownership of the token is given to the packet, and when the state
// moves *from* a pointer, ownership of the token is transferred to
// whoever changed the state.
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: AtomicUsize,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(SignalToken),
}
pub enum SelectionResult<T> {
SelCanceled,
SelUpgraded(SignalToken, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T: Send +'static> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: AtomicUsize::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> Result<(), T> {
// Sanity check
match self.upgrade {
NothingSent => {}
_ => panic!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, Ordering::SeqCst) {
// Sent the data, no one was waiting
EMPTY => Ok(()),
// Couldn't send the data, the port hung up first. Return the data
// back up the stack.
DISCONNECTED => {
Err(self.data.take().unwrap())
}
// Not possible, these are one-use channels
DATA => unreachable!(),
// There is a thread waiting on the other end. We leave the 'DATA'
// state inside so it'll pick it up on the other end.
ptr => unsafe {
SignalToken::cast_from_uint(ptr).signal();
Ok(())
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(Ordering::SeqCst) == EMPTY {
let (wait_token, signal_token) = blocking::tokens();
let ptr = unsafe { signal_token.cast_to_uint() };
// race with senders to enter the blocking state
if self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) == EMPTY {
wait_token.wait();
debug_assert!(self.state.load(Ordering::SeqCst)!= EMPTY);
} else {
// drop the signal token, since we never blocked
drop(unsafe { SignalToken::cast_from_uint(ptr) });
}
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, Ordering::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
}
}
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
// We are the sole receiver; there cannot be a blocking
// receiver already.
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => panic!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
ptr => UpWoke(unsafe { SignalToken::cast_from_uint(ptr) })
}
}
pub fn drop_chan(&mut self)
|
pub fn drop_port(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take().unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> {
let ptr = unsafe { token.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) {
EMPTY => SelSuccess,
DATA => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
DISCONNECTED if self.data.is_some() => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { SignalToken::cast_from_uint(ptr) }, upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(Ordering::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select.
ptr => unsafe {
drop(SignalToken::cast_from_uint(ptr));
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T: Send +'static> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(Ordering::SeqCst), DISCONNECTED);
}
}
|
{
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
ptr => unsafe {
SignalToken::cast_from_uint(ptr).signal();
}
}
}
|
identifier_body
|
oneshot.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an Arc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic uint variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
pub use self::Failure::*;
pub use self::UpgradeResult::*;
pub use self::SelectionResult::*;
use self::MyUpgrade::*;
use core::prelude::*;
use sync::mpsc::Receiver;
use sync::mpsc::blocking::{self, SignalToken};
use core::mem;
use sync::atomic::{AtomicUsize, Ordering};
// Various states you can find a port in.
const EMPTY: uint = 0; // initial state: no data, no blocked receiver
const DATA: uint = 1; // data ready for receiver to take
const DISCONNECTED: uint = 2; // channel is disconnected OR upgraded
// Any other value represents a pointer to a SignalToken value. The
// protocol ensures that when the state moves *to* a pointer,
// ownership of the token is given to the packet, and when the state
// moves *from* a pointer, ownership of the token is transferred to
// whoever changed the state.
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: AtomicUsize,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(SignalToken),
}
pub enum SelectionResult<T> {
SelCanceled,
SelUpgraded(SignalToken, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T: Send +'static> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: AtomicUsize::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> Result<(), T> {
// Sanity check
match self.upgrade {
NothingSent => {}
_ => panic!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, Ordering::SeqCst) {
// Sent the data, no one was waiting
EMPTY => Ok(()),
// Couldn't send the data, the port hung up first. Return the data
// back up the stack.
DISCONNECTED => {
Err(self.data.take().unwrap())
}
// Not possible, these are one-use channels
DATA => unreachable!(),
// There is a thread waiting on the other end. We leave the 'DATA'
// state inside so it'll pick it up on the other end.
ptr => unsafe {
SignalToken::cast_from_uint(ptr).signal();
Ok(())
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(Ordering::SeqCst) == EMPTY {
let (wait_token, signal_token) = blocking::tokens();
let ptr = unsafe { signal_token.cast_to_uint() };
// race with senders to enter the blocking state
if self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) == EMPTY {
wait_token.wait();
debug_assert!(self.state.load(Ordering::SeqCst)!= EMPTY);
} else {
// drop the signal token, since we never blocked
drop(unsafe { SignalToken::cast_from_uint(ptr) });
}
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, Ordering::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
}
}
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
// We are the sole receiver; there cannot be a blocking
// receiver already.
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => panic!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
ptr => UpWoke(unsafe { SignalToken::cast_from_uint(ptr) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
ptr => unsafe {
SignalToken::cast_from_uint(ptr).signal();
}
}
}
pub fn drop_port(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take().unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn
|
(&mut self, token: SignalToken) -> SelectionResult<T> {
let ptr = unsafe { token.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) {
EMPTY => SelSuccess,
DATA => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
DISCONNECTED if self.data.is_some() => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { SignalToken::cast_from_uint(ptr) }, upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(Ordering::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select.
ptr => unsafe {
drop(SignalToken::cast_from_uint(ptr));
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T: Send +'static> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(Ordering::SeqCst), DISCONNECTED);
}
}
|
start_selection
|
identifier_name
|
oneshot.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/// Oneshot channels/ports
///
/// This is the initial flavor of channels/ports used for comm module. This is
/// an optimization for the one-use case of a channel. The major optimization of
/// this type is to have one and exactly one allocation when the chan/port pair
/// is created.
///
/// Another possible optimization would be to not use an Arc box because
/// in theory we know when the shared packet can be deallocated (no real need
/// for the atomic reference counting), but I was having trouble how to destroy
/// the data early in a drop of a Port.
///
/// # Implementation
///
/// Oneshots are implemented around one atomic uint variable. This variable
/// indicates both the state of the port/chan but also contains any tasks
/// blocked on the port. All atomic operations happen on this one word.
///
/// In order to upgrade a oneshot channel, an upgrade is considered a disconnect
/// on behalf of the channel side of things (it can be mentally thought of as
/// consuming the port). This upgrade is then also stored in the shared packet.
/// The one caveat to consider is that when a port sees a disconnected channel
/// it must check for data because there is no "data plus upgrade" state.
pub use self::Failure::*;
pub use self::UpgradeResult::*;
pub use self::SelectionResult::*;
use self::MyUpgrade::*;
use core::prelude::*;
use sync::mpsc::Receiver;
use sync::mpsc::blocking::{self, SignalToken};
use core::mem;
use sync::atomic::{AtomicUsize, Ordering};
// Various states you can find a port in.
const EMPTY: uint = 0; // initial state: no data, no blocked receiver
const DATA: uint = 1; // data ready for receiver to take
const DISCONNECTED: uint = 2; // channel is disconnected OR upgraded
// Any other value represents a pointer to a SignalToken value. The
// protocol ensures that when the state moves *to* a pointer,
// ownership of the token is given to the packet, and when the state
// moves *from* a pointer, ownership of the token is transferred to
// whoever changed the state.
pub struct Packet<T> {
// Internal state of the chan/port pair (stores the blocked task as well)
state: AtomicUsize,
// One-shot data slot location
data: Option<T>,
// when used for the second time, a oneshot channel must be upgraded, and
// this contains the slot for the upgrade
upgrade: MyUpgrade<T>,
}
pub enum Failure<T> {
Empty,
Disconnected,
Upgraded(Receiver<T>),
}
pub enum UpgradeResult {
UpSuccess,
UpDisconnected,
UpWoke(SignalToken),
}
pub enum SelectionResult<T> {
SelCanceled,
SelUpgraded(SignalToken, Receiver<T>),
SelSuccess,
}
enum MyUpgrade<T> {
NothingSent,
SendUsed,
GoUp(Receiver<T>),
}
impl<T: Send +'static> Packet<T> {
pub fn new() -> Packet<T> {
Packet {
data: None,
upgrade: NothingSent,
state: AtomicUsize::new(EMPTY),
}
}
pub fn send(&mut self, t: T) -> Result<(), T> {
// Sanity check
match self.upgrade {
NothingSent => {}
_ => panic!("sending on a oneshot that's already sent on "),
}
assert!(self.data.is_none());
self.data = Some(t);
self.upgrade = SendUsed;
match self.state.swap(DATA, Ordering::SeqCst) {
// Sent the data, no one was waiting
EMPTY => Ok(()),
// Couldn't send the data, the port hung up first. Return the data
// back up the stack.
DISCONNECTED =>
|
// Not possible, these are one-use channels
DATA => unreachable!(),
// There is a thread waiting on the other end. We leave the 'DATA'
// state inside so it'll pick it up on the other end.
ptr => unsafe {
SignalToken::cast_from_uint(ptr).signal();
Ok(())
}
}
}
// Just tests whether this channel has been sent on or not, this is only
// safe to use from the sender.
pub fn sent(&self) -> bool {
match self.upgrade {
NothingSent => false,
_ => true,
}
}
pub fn recv(&mut self) -> Result<T, Failure<T>> {
// Attempt to not block the task (it's a little expensive). If it looks
// like we're not empty, then immediately go through to `try_recv`.
if self.state.load(Ordering::SeqCst) == EMPTY {
let (wait_token, signal_token) = blocking::tokens();
let ptr = unsafe { signal_token.cast_to_uint() };
// race with senders to enter the blocking state
if self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) == EMPTY {
wait_token.wait();
debug_assert!(self.state.load(Ordering::SeqCst)!= EMPTY);
} else {
// drop the signal token, since we never blocked
drop(unsafe { SignalToken::cast_from_uint(ptr) });
}
}
self.try_recv()
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Err(Empty),
// We saw some data on the channel, but the channel can be used
// again to send us an upgrade. As a result, we need to re-insert
// into the channel that there's no data available (otherwise we'll
// just see DATA next time). This is done as a cmpxchg because if
// the state changes under our feet we'd rather just see that state
// change.
DATA => {
self.state.compare_and_swap(DATA, EMPTY, Ordering::SeqCst);
match self.data.take() {
Some(data) => Ok(data),
None => unreachable!(),
}
}
// There's no guarantee that we receive before an upgrade happens,
// and an upgrade flags the channel as disconnected, so when we see
// this we first need to check if there's data available and *then*
// we go through and process the upgrade.
DISCONNECTED => {
match self.data.take() {
Some(data) => Ok(data),
None => {
match mem::replace(&mut self.upgrade, SendUsed) {
SendUsed | NothingSent => Err(Disconnected),
GoUp(upgrade) => Err(Upgraded(upgrade))
}
}
}
}
// We are the sole receiver; there cannot be a blocking
// receiver already.
_ => unreachable!()
}
}
// Returns whether the upgrade was completed. If the upgrade wasn't
// completed, then the port couldn't get sent to the other half (it will
// never receive it).
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
let prev = match self.upgrade {
NothingSent => NothingSent,
SendUsed => SendUsed,
_ => panic!("upgrading again"),
};
self.upgrade = GoUp(up);
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// If the channel is empty or has data on it, then we're good to go.
// Senders will check the data before the upgrade (in case we
// plastered over the DATA state).
DATA | EMPTY => UpSuccess,
// If the other end is already disconnected, then we failed the
// upgrade. Be sure to trash the port we were given.
DISCONNECTED => { self.upgrade = prev; UpDisconnected }
// If someone's waiting, we gotta wake them up
ptr => UpWoke(unsafe { SignalToken::cast_from_uint(ptr) })
}
}
pub fn drop_chan(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
DATA | DISCONNECTED | EMPTY => {}
// If someone's waiting, we gotta wake them up
ptr => unsafe {
SignalToken::cast_from_uint(ptr).signal();
}
}
}
pub fn drop_port(&mut self) {
match self.state.swap(DISCONNECTED, Ordering::SeqCst) {
// An empty channel has nothing to do, and a remotely disconnected
// channel also has nothing to do b/c we're about to run the drop
// glue
DISCONNECTED | EMPTY => {}
// There's data on the channel, so make sure we destroy it promptly.
// This is why not using an arc is a little difficult (need the box
// to stay valid while we take the data).
DATA => { self.data.take().unwrap(); }
// We're the only ones that can block on this port
_ => unreachable!()
}
}
////////////////////////////////////////////////////////////////////////////
// select implementation
////////////////////////////////////////////////////////////////////////////
// If Ok, the value is whether this port has data, if Err, then the upgraded
// port needs to be checked instead of this one.
pub fn can_recv(&mut self) -> Result<bool, Receiver<T>> {
match self.state.load(Ordering::SeqCst) {
EMPTY => Ok(false), // Welp, we tried
DATA => Ok(true), // we have some un-acquired data
DISCONNECTED if self.data.is_some() => Ok(true), // we have data
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => Err(upgrade),
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => { self.upgrade = up; Ok(true) }
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Attempts to start selection on this port. This can either succeed, fail
// because there is data, or fail because there is an upgrade pending.
pub fn start_selection(&mut self, token: SignalToken) -> SelectionResult<T> {
let ptr = unsafe { token.cast_to_uint() };
match self.state.compare_and_swap(EMPTY, ptr, Ordering::SeqCst) {
EMPTY => SelSuccess,
DATA => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
DISCONNECTED if self.data.is_some() => {
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
DISCONNECTED => {
match mem::replace(&mut self.upgrade, SendUsed) {
// The other end sent us an upgrade, so we need to
// propagate upwards whether the upgrade can receive
// data
GoUp(upgrade) => {
SelUpgraded(unsafe { SignalToken::cast_from_uint(ptr) }, upgrade)
}
// If the other end disconnected without sending an
// upgrade, then we have data to receive (the channel is
// disconnected).
up => {
self.upgrade = up;
drop(unsafe { SignalToken::cast_from_uint(ptr) });
SelCanceled
}
}
}
_ => unreachable!(), // we're the "one blocker"
}
}
// Remove a previous selecting task from this port. This ensures that the
// blocked task will no longer be visible to any other threads.
//
// The return value indicates whether there's data on this port.
pub fn abort_selection(&mut self) -> Result<bool, Receiver<T>> {
let state = match self.state.load(Ordering::SeqCst) {
// Each of these states means that no further activity will happen
// with regard to abortion selection
s @ EMPTY |
s @ DATA |
s @ DISCONNECTED => s,
// If we've got a blocked task, then use an atomic to gain ownership
// of it (may fail)
ptr => self.state.compare_and_swap(ptr, EMPTY, Ordering::SeqCst)
};
// Now that we've got ownership of our state, figure out what to do
// about it.
match state {
EMPTY => unreachable!(),
// our task used for select was stolen
DATA => Ok(true),
// If the other end has hung up, then we have complete ownership
// of the port. First, check if there was data waiting for us. This
// is possible if the other end sent something and then hung up.
//
// We then need to check to see if there was an upgrade requested,
// and if so, the upgraded port needs to have its selection aborted.
DISCONNECTED => {
if self.data.is_some() {
Ok(true)
} else {
match mem::replace(&mut self.upgrade, SendUsed) {
GoUp(port) => Err(port),
_ => Ok(true),
}
}
}
// We woke ourselves up from select.
ptr => unsafe {
drop(SignalToken::cast_from_uint(ptr));
Ok(false)
}
}
}
}
#[unsafe_destructor]
impl<T: Send +'static> Drop for Packet<T> {
fn drop(&mut self) {
assert_eq!(self.state.load(Ordering::SeqCst), DISCONNECTED);
}
}
|
{
Err(self.data.take().unwrap())
}
|
conditional_block
|
lib.rs
|
// Copyright 2016 Matthew Fornaciari <[email protected]>
//! A dead simple wrapper around file and directory manipulation.
//!
//! # Usage
//!
//! This crate is [on crates.io](https://crates.io/crates/touch) and can be
//! used by adding `args` to the dependencies in your project's `Cargo.toml`.
//!
//! ```toml
//! [dependencies]
//! touch = "0"
//! ```
//!
//! and this to your crate root:
//!
//! ```rust
//! extern crate touch;
//! ```
//!
//! # Example
//!
//! ```rust
//! extern crate touch;
//!
//! use touch::exists;
//! use touch::dir;
//! use touch::file;
//!
//! const DIR: &'static str = "/tmp/touch";
//! const FILE_NAME: &'static str = ".example";
//!
//! fn main() {
//! assert!(!exists(DIR));
//! assert!(!exists(&path()));
//!
//! // Write
//! let content = "Content";
//! assert!(file::write(&path(), content, false).is_ok());
//!
//! // Read
//! let mut output = file::read(&path());
//! assert_eq!(content, output.unwrap());
//!
//! // Overwrite
//! let new_content = "New Content";
//! assert!(file::write(&path(), new_content, true).is_ok());
//! output = file::read(&path());
//! assert_eq!(new_content, output.unwrap());
//!
//! // Delete
//! assert!(dir::delete(DIR).is_ok());
//! assert!(!exists(&path()));
//! assert!(!exists(DIR));
//! }
//!
//! fn path() -> String {
//! format!("{}/{}", DIR, FILE_NAME)
//! }
//! ```
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/")]
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]
#[macro_use] extern crate log;
use std::path::Path;
use std::result;
pub mod dir;
pub mod file;
mod error;
mod operation;
#[cfg(test)] mod tst;
/// A specialized Result type for I/O operations.
///
/// This type is broadly used across the `touch` crate for any operation which
/// may produce an error.
pub type Result<T> = result::Result<T, Error>;
pub use error::Error;
/// Returns whether or not the file at the provided path exists.
pub fn
|
(path: &str) -> bool { Path::new(path).exists() }
|
exists
|
identifier_name
|
lib.rs
|
// Copyright 2016 Matthew Fornaciari <[email protected]>
//! A dead simple wrapper around file and directory manipulation.
//!
//! # Usage
//!
//! This crate is [on crates.io](https://crates.io/crates/touch) and can be
//! used by adding `args` to the dependencies in your project's `Cargo.toml`.
//!
//! ```toml
//! [dependencies]
//! touch = "0"
//! ```
//!
//! and this to your crate root:
//!
//! ```rust
//! extern crate touch;
//! ```
//!
//! # Example
//!
//! ```rust
//! extern crate touch;
//!
//! use touch::exists;
//! use touch::dir;
//! use touch::file;
//!
//! const DIR: &'static str = "/tmp/touch";
//! const FILE_NAME: &'static str = ".example";
//!
//! fn main() {
//! assert!(!exists(DIR));
//! assert!(!exists(&path()));
//!
//! // Write
//! let content = "Content";
//! assert!(file::write(&path(), content, false).is_ok());
//!
//! // Read
//! let mut output = file::read(&path());
//! assert_eq!(content, output.unwrap());
//!
//! // Overwrite
//! let new_content = "New Content";
//! assert!(file::write(&path(), new_content, true).is_ok());
//! output = file::read(&path());
//! assert_eq!(new_content, output.unwrap());
//!
//! // Delete
//! assert!(dir::delete(DIR).is_ok());
//! assert!(!exists(&path()));
//! assert!(!exists(DIR));
//! }
//!
//! fn path() -> String {
//! format!("{}/{}", DIR, FILE_NAME)
//! }
//! ```
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/")]
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]
#[macro_use] extern crate log;
use std::path::Path;
use std::result;
pub mod dir;
pub mod file;
mod error;
mod operation;
#[cfg(test)] mod tst;
/// A specialized Result type for I/O operations.
///
/// This type is broadly used across the `touch` crate for any operation which
/// may produce an error.
pub type Result<T> = result::Result<T, Error>;
pub use error::Error;
/// Returns whether or not the file at the provided path exists.
pub fn exists(path: &str) -> bool
|
{ Path::new(path).exists() }
|
identifier_body
|
|
lib.rs
|
// Copyright 2016 Matthew Fornaciari <[email protected]>
//! A dead simple wrapper around file and directory manipulation.
//!
//! # Usage
//!
//! This crate is [on crates.io](https://crates.io/crates/touch) and can be
//! used by adding `args` to the dependencies in your project's `Cargo.toml`.
|
//!
//! ```toml
//! [dependencies]
//! touch = "0"
//! ```
//!
//! and this to your crate root:
//!
//! ```rust
//! extern crate touch;
//! ```
//!
//! # Example
//!
//! ```rust
//! extern crate touch;
//!
//! use touch::exists;
//! use touch::dir;
//! use touch::file;
//!
//! const DIR: &'static str = "/tmp/touch";
//! const FILE_NAME: &'static str = ".example";
//!
//! fn main() {
//! assert!(!exists(DIR));
//! assert!(!exists(&path()));
//!
//! // Write
//! let content = "Content";
//! assert!(file::write(&path(), content, false).is_ok());
//!
//! // Read
//! let mut output = file::read(&path());
//! assert_eq!(content, output.unwrap());
//!
//! // Overwrite
//! let new_content = "New Content";
//! assert!(file::write(&path(), new_content, true).is_ok());
//! output = file::read(&path());
//! assert_eq!(new_content, output.unwrap());
//!
//! // Delete
//! assert!(dir::delete(DIR).is_ok());
//! assert!(!exists(&path()));
//! assert!(!exists(DIR));
//! }
//!
//! fn path() -> String {
//! format!("{}/{}", DIR, FILE_NAME)
//! }
//! ```
#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "https://www.rust-lang.org/favicon.ico",
html_root_url = "https://doc.rust-lang.org/")]
#![cfg_attr(test, deny(warnings))]
#![deny(missing_docs)]
#[macro_use] extern crate log;
use std::path::Path;
use std::result;
pub mod dir;
pub mod file;
mod error;
mod operation;
#[cfg(test)] mod tst;
/// A specialized Result type for I/O operations.
///
/// This type is broadly used across the `touch` crate for any operation which
/// may produce an error.
pub type Result<T> = result::Result<T, Error>;
pub use error::Error;
/// Returns whether or not the file at the provided path exists.
pub fn exists(path: &str) -> bool { Path::new(path).exists() }
|
random_line_split
|
|
numeric.rs
|
use std::ops::{Add, Mul, Div, Rem};
use num::{Integer, PrimInt, FromPrimitive, Unsigned};
/// Computes the binomial coefficient (n choose m)
/// Returns `None` if an input is invalid
pub fn binomial<T: Integer + Clone>(n: &T, m: &T) -> Option<T> {
if n.clone() <= T::zero() || m.clone() < T::zero()
|
else {
// Recall (n choose m) = (n choose n-m), so choose the one
// which will result in fewer computations
if n.clone() - m.clone() >= m.clone() {
Some(binom_no_check(n, m))
} else {
Some(binom_no_check(n, &(n.clone() - m.clone())))
}
}
}
/// Computes the least common multiple of the two given integers
pub fn lcm<T: Integer + Clone>(n: &T, m: &T) -> T {
n.clone() * m.clone() / n.clone().gcd(m)
}
/// Computes integer powers n^m where m is a primitive integral type
pub fn pow_primint<T, U>(n: &T, m: U) -> T
where T: Integer + Clone,
for<'a> &'a T: Add<Output = T>,
for<'a> &'a T: Mul<Output = T>,
U: PrimInt + Unsigned
{
let mut m = m;
let mut pow = T::one();
// The expression which will be repeatedly squared
let mut sqr = n.clone();
// Use "binary exponentiation"; i.e. repeated squaring and multiplication
// according to the binary expansion of m
while m!= U::zero() {
if m & U::one() == U::one() {
pow = &pow * &sqr;
}
// Square the square term and divide m by 2 to get next binary digit
sqr = &sqr * &sqr;
m = m >> 1;
}
pow
}
/// Computes the sum of digits in the given integer
pub fn sum_digits<T>(n: &T) -> T
where T: Integer + Clone + FromPrimitive,
for<'a> &'a T: Add<Output = T>,
for<'a> &'a T: Div<Output = T>,
for<'a> &'a T: Rem<Output = T>
{
let mut n = n.clone();
let ten: T = FromPrimitive::from_i32(10).unwrap();
let mut sum = T::zero();
while n.clone()!= T::zero() {
sum = &sum + &(&n % &ten);
n = &n / &ten;
}
sum
}
/// Same as `binomial` but doesn't check for valid inputs
fn binom_no_check<T: Integer + Clone>(n: &T, m: &T) -> T {
if m.clone() == T::zero() {
T::one()
} else {
binom_no_check(&(n.clone() - T::one()), &(m.clone() - T::one())) * n.clone() / m.clone()
}
}
|
{
None
}
|
conditional_block
|
numeric.rs
|
use std::ops::{Add, Mul, Div, Rem};
use num::{Integer, PrimInt, FromPrimitive, Unsigned};
/// Computes the binomial coefficient (n choose m)
/// Returns `None` if an input is invalid
pub fn
|
<T: Integer + Clone>(n: &T, m: &T) -> Option<T> {
if n.clone() <= T::zero() || m.clone() < T::zero() {
None
} else {
// Recall (n choose m) = (n choose n-m), so choose the one
// which will result in fewer computations
if n.clone() - m.clone() >= m.clone() {
Some(binom_no_check(n, m))
} else {
Some(binom_no_check(n, &(n.clone() - m.clone())))
}
}
}
/// Computes the least common multiple of the two given integers
pub fn lcm<T: Integer + Clone>(n: &T, m: &T) -> T {
n.clone() * m.clone() / n.clone().gcd(m)
}
/// Computes integer powers n^m where m is a primitive integral type
pub fn pow_primint<T, U>(n: &T, m: U) -> T
where T: Integer + Clone,
for<'a> &'a T: Add<Output = T>,
for<'a> &'a T: Mul<Output = T>,
U: PrimInt + Unsigned
{
let mut m = m;
let mut pow = T::one();
// The expression which will be repeatedly squared
let mut sqr = n.clone();
// Use "binary exponentiation"; i.e. repeated squaring and multiplication
// according to the binary expansion of m
while m!= U::zero() {
if m & U::one() == U::one() {
pow = &pow * &sqr;
}
// Square the square term and divide m by 2 to get next binary digit
sqr = &sqr * &sqr;
m = m >> 1;
}
pow
}
/// Computes the sum of digits in the given integer
pub fn sum_digits<T>(n: &T) -> T
where T: Integer + Clone + FromPrimitive,
for<'a> &'a T: Add<Output = T>,
for<'a> &'a T: Div<Output = T>,
for<'a> &'a T: Rem<Output = T>
{
let mut n = n.clone();
let ten: T = FromPrimitive::from_i32(10).unwrap();
let mut sum = T::zero();
while n.clone()!= T::zero() {
sum = &sum + &(&n % &ten);
n = &n / &ten;
}
sum
}
/// Same as `binomial` but doesn't check for valid inputs
fn binom_no_check<T: Integer + Clone>(n: &T, m: &T) -> T {
if m.clone() == T::zero() {
T::one()
} else {
binom_no_check(&(n.clone() - T::one()), &(m.clone() - T::one())) * n.clone() / m.clone()
}
}
|
binomial
|
identifier_name
|
numeric.rs
|
use std::ops::{Add, Mul, Div, Rem};
use num::{Integer, PrimInt, FromPrimitive, Unsigned};
/// Computes the binomial coefficient (n choose m)
/// Returns `None` if an input is invalid
pub fn binomial<T: Integer + Clone>(n: &T, m: &T) -> Option<T> {
if n.clone() <= T::zero() || m.clone() < T::zero() {
None
} else {
// Recall (n choose m) = (n choose n-m), so choose the one
// which will result in fewer computations
if n.clone() - m.clone() >= m.clone() {
Some(binom_no_check(n, m))
} else {
Some(binom_no_check(n, &(n.clone() - m.clone())))
}
}
}
/// Computes the least common multiple of the two given integers
pub fn lcm<T: Integer + Clone>(n: &T, m: &T) -> T {
n.clone() * m.clone() / n.clone().gcd(m)
}
/// Computes integer powers n^m where m is a primitive integral type
pub fn pow_primint<T, U>(n: &T, m: U) -> T
where T: Integer + Clone,
for<'a> &'a T: Add<Output = T>,
for<'a> &'a T: Mul<Output = T>,
U: PrimInt + Unsigned
{
let mut m = m;
let mut pow = T::one();
// The expression which will be repeatedly squared
let mut sqr = n.clone();
// Use "binary exponentiation"; i.e. repeated squaring and multiplication
// according to the binary expansion of m
while m!= U::zero() {
if m & U::one() == U::one() {
pow = &pow * &sqr;
}
// Square the square term and divide m by 2 to get next binary digit
sqr = &sqr * &sqr;
m = m >> 1;
}
pow
}
/// Computes the sum of digits in the given integer
pub fn sum_digits<T>(n: &T) -> T
where T: Integer + Clone + FromPrimitive,
for<'a> &'a T: Add<Output = T>,
for<'a> &'a T: Div<Output = T>,
for<'a> &'a T: Rem<Output = T>
{
let mut n = n.clone();
let ten: T = FromPrimitive::from_i32(10).unwrap();
let mut sum = T::zero();
while n.clone()!= T::zero() {
|
}
sum
}
/// Same as `binomial` but doesn't check for valid inputs
fn binom_no_check<T: Integer + Clone>(n: &T, m: &T) -> T {
if m.clone() == T::zero() {
T::one()
} else {
binom_no_check(&(n.clone() - T::one()), &(m.clone() - T::one())) * n.clone() / m.clone()
}
}
|
sum = &sum + &(&n % &ten);
n = &n / &ten;
|
random_line_split
|
numeric.rs
|
use std::ops::{Add, Mul, Div, Rem};
use num::{Integer, PrimInt, FromPrimitive, Unsigned};
/// Computes the binomial coefficient (n choose m)
/// Returns `None` if an input is invalid
pub fn binomial<T: Integer + Clone>(n: &T, m: &T) -> Option<T>
|
/// Computes the least common multiple of the two given integers
pub fn lcm<T: Integer + Clone>(n: &T, m: &T) -> T {
n.clone() * m.clone() / n.clone().gcd(m)
}
/// Computes integer powers n^m where m is a primitive integral type
pub fn pow_primint<T, U>(n: &T, m: U) -> T
where T: Integer + Clone,
for<'a> &'a T: Add<Output = T>,
for<'a> &'a T: Mul<Output = T>,
U: PrimInt + Unsigned
{
let mut m = m;
let mut pow = T::one();
// The expression which will be repeatedly squared
let mut sqr = n.clone();
// Use "binary exponentiation"; i.e. repeated squaring and multiplication
// according to the binary expansion of m
while m!= U::zero() {
if m & U::one() == U::one() {
pow = &pow * &sqr;
}
// Square the square term and divide m by 2 to get next binary digit
sqr = &sqr * &sqr;
m = m >> 1;
}
pow
}
/// Computes the sum of digits in the given integer
pub fn sum_digits<T>(n: &T) -> T
where T: Integer + Clone + FromPrimitive,
for<'a> &'a T: Add<Output = T>,
for<'a> &'a T: Div<Output = T>,
for<'a> &'a T: Rem<Output = T>
{
let mut n = n.clone();
let ten: T = FromPrimitive::from_i32(10).unwrap();
let mut sum = T::zero();
while n.clone()!= T::zero() {
sum = &sum + &(&n % &ten);
n = &n / &ten;
}
sum
}
/// Same as `binomial` but doesn't check for valid inputs
fn binom_no_check<T: Integer + Clone>(n: &T, m: &T) -> T {
if m.clone() == T::zero() {
T::one()
} else {
binom_no_check(&(n.clone() - T::one()), &(m.clone() - T::one())) * n.clone() / m.clone()
}
}
|
{
if n.clone() <= T::zero() || m.clone() < T::zero() {
None
} else {
// Recall (n choose m) = (n choose n-m), so choose the one
// which will result in fewer computations
if n.clone() - m.clone() >= m.clone() {
Some(binom_no_check(n, m))
} else {
Some(binom_no_check(n, &(n.clone() - m.clone())))
}
}
}
|
identifier_body
|
client.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 futures::Future;
use std::io::Result;
use std::net::Shutdown;
use std::path::Path;
use tokio_core::reactor::Handle;
use tokio_uds::UnixStream;
use auth::{Authenticator, AuthError, ServerGuid};
pub struct Bus {
inner: UnixStream,
}
impl Bus {
pub fn connect<P, F, T>
(path: P,
handle: &Handle,
auth_strategy: F)
-> impl Future<Item = (ServerGuid, Self), Error = (AuthError, Option<Authenticator>)>
where P: AsRef<Path>,
F: FnOnce(Authenticator) -> T,
T: Future<Item = (ServerGuid, Authenticator),
Error = (AuthError, Option<Authenticator>)>
{
Authenticator::connect(path, handle)
.map_err(|err| (err.into(), None))
.and_then(|auth| auth_strategy(auth))
.and_then(|(server_guid, auth)| {
auth.begin()
.map(move |bus| (server_guid, bus))
.map_err(|err| (err.into(), None))
})
}
pub fn new(inner: UnixStream) -> Self {
Bus { inner: inner }
}
pub fn into_inner(self) -> UnixStream {
self.inner
}
pub fn disconnect(self) -> Result<()> {
self.into_inner().shutdown(Shutdown::Both)
}
}
|
random_line_split
|
|
client.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 futures::Future;
use std::io::Result;
use std::net::Shutdown;
use std::path::Path;
use tokio_core::reactor::Handle;
use tokio_uds::UnixStream;
use auth::{Authenticator, AuthError, ServerGuid};
pub struct Bus {
inner: UnixStream,
}
impl Bus {
pub fn
|
<P, F, T>
(path: P,
handle: &Handle,
auth_strategy: F)
-> impl Future<Item = (ServerGuid, Self), Error = (AuthError, Option<Authenticator>)>
where P: AsRef<Path>,
F: FnOnce(Authenticator) -> T,
T: Future<Item = (ServerGuid, Authenticator),
Error = (AuthError, Option<Authenticator>)>
{
Authenticator::connect(path, handle)
.map_err(|err| (err.into(), None))
.and_then(|auth| auth_strategy(auth))
.and_then(|(server_guid, auth)| {
auth.begin()
.map(move |bus| (server_guid, bus))
.map_err(|err| (err.into(), None))
})
}
pub fn new(inner: UnixStream) -> Self {
Bus { inner: inner }
}
pub fn into_inner(self) -> UnixStream {
self.inner
}
pub fn disconnect(self) -> Result<()> {
self.into_inner().shutdown(Shutdown::Both)
}
}
|
connect
|
identifier_name
|
client.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 futures::Future;
use std::io::Result;
use std::net::Shutdown;
use std::path::Path;
use tokio_core::reactor::Handle;
use tokio_uds::UnixStream;
use auth::{Authenticator, AuthError, ServerGuid};
pub struct Bus {
inner: UnixStream,
}
impl Bus {
pub fn connect<P, F, T>
(path: P,
handle: &Handle,
auth_strategy: F)
-> impl Future<Item = (ServerGuid, Self), Error = (AuthError, Option<Authenticator>)>
where P: AsRef<Path>,
F: FnOnce(Authenticator) -> T,
T: Future<Item = (ServerGuid, Authenticator),
Error = (AuthError, Option<Authenticator>)>
{
Authenticator::connect(path, handle)
.map_err(|err| (err.into(), None))
.and_then(|auth| auth_strategy(auth))
.and_then(|(server_guid, auth)| {
auth.begin()
.map(move |bus| (server_guid, bus))
.map_err(|err| (err.into(), None))
})
}
pub fn new(inner: UnixStream) -> Self {
Bus { inner: inner }
}
pub fn into_inner(self) -> UnixStream
|
pub fn disconnect(self) -> Result<()> {
self.into_inner().shutdown(Shutdown::Both)
}
}
|
{
self.inner
}
|
identifier_body
|
mod.rs
|
use std::str::FromStr;
use std::collections::HashMap;
use std::ops::{BitAnd, BitOr, Shl, Shr, Not};
const DATA: &'static str = include_str!("input.txt");
pub fn main() -> Vec<String> {
let s1 = run_circuit(DATA, "a").unwrap();
let s2 = part2(DATA, "a", "b", 956).unwrap();
vec![s1.to_string(), s2.to_string()]
}
#[derive(PartialEq, Eq, Hash, Clone)]
enum Source {
Pattern(u16),
Wire(String),
}
impl FromStr for Source {
type Err = &'static str;
fn from_str(s: &str) -> Result<Source, Self::Err> {
match s {
s if s.is_empty() => Err("empty identifier"),
s if (|s: &str| s.chars().all(|c| c.is_digit(10)))(s) => {
s.parse::<u16>().map_err(|_| "parse error").map(Source::Pattern)
}
s if (|s: &str| s.chars().all(|c| c.is_alphabetic()))(s) => {
Ok(Source::Wire(s.to_owned()))
}
_ => Err("unknown identifier format"),
}
}
}
#[derive(PartialEq, Eq, Hash, Clone)]
enum Gate {
UnaryOp {
src: Source,
out: Source,
f: fn(u16) -> u16,
},
BinaryOp {
a: Source,
b: Source,
out: Source,
f: fn(u16, u16) -> u16,
},
}
impl FromStr for Gate {
type Err = &'static str;
fn from_str(s: &str) -> Result<Gate, Self::Err> {
fn id<T>(x: T) -> T {
x
};
fn unary_from_str(a: &str, o: &str, f: fn(u16) -> u16) -> Result<Gate, &'static str>
|
fn binary_from_str(a: &str,
b: &str,
o: &str,
f: fn(u16, u16) -> u16)
-> Result<Gate, &'static str> {
a.parse::<Source>().and_then(|a| {
b.parse::<Source>().and_then(|b| {
o.parse::<Source>().map(|o| {
Gate::BinaryOp {
a: a,
b: b,
out: o,
f: f,
}
})
})
})
}
match &s.split_whitespace().collect::<Vec<_>>()[..] {
[a, "->", o] => unary_from_str(a, o, id),
["NOT", a, "->", o] => unary_from_str(a, o, Not::not),
[a, "AND", b, "->", o] => binary_from_str(a, b, o, BitAnd::bitand),
[a, "OR", b, "->", o] => binary_from_str(a, b, o, BitOr::bitor),
[a, "LSHIFT", b, "->", o] => binary_from_str(a, b, o, Shl::shl),
[a, "RSHIFT", b, "->", o] => binary_from_str(a, b, o, Shr::shr),
_ => Err("bad input"),
}
}
}
impl Gate {
fn out(&self) -> Source {
match *self {
Gate::UnaryOp{ ref out,..} => out,
Gate::BinaryOp{ ref out,..} => out,
}
.clone()
}
fn eval(&self, c: &mut Circuit) -> Option<u16> {
match *self {
Gate::UnaryOp{ ref src, ref f,.. } => c.eval(src).map(f),
Gate::BinaryOp{ ref a, ref b, ref f,.. } => {
c.eval(a).and_then(|a| c.eval(b).map(|b| f(a, b)))
}
}
}
}
struct Circuit {
gates: HashMap<Source, Gate>,
cache: HashMap<Source, u16>,
}
impl FromStr for Circuit {
type Err = &'static str;
fn from_str(input: &str) -> Result<Circuit, Self::Err> {
let mut circuit = HashMap::new();
let cache = HashMap::new();
for line in input.lines() {
if let Ok(gate) = line.parse::<Gate>() {
circuit.insert(gate.out(), gate);
} else {
return Err("gate parse error");
}
}
Ok(Circuit {
gates: circuit,
cache: cache,
})
}
}
impl Circuit {
fn eval(&mut self, wire: &Source) -> Option<u16> {
match *wire {
Source::Pattern(p) => Some(p),
ref s @ Source::Wire(_) => {
if self.cache.contains_key(s) {
self.cache.get(s).cloned()
} else {
if let Some(v) = self.gates.get(s).cloned().and_then(|g| g.eval(self)) {
self.cache.insert(s.clone(), v);
Some(v)
} else {
None
}
}
}
}
}
fn force(&mut self, s: &Source, v: u16) {
self.cache.clear();
self.cache.insert(s.clone(), v);
}
}
fn run_circuit(input: &str, target: &str) -> Option<u16> {
if let Ok(mut c) = input.parse::<Circuit>() {
c.eval(&Source::Wire(target.to_owned()))
} else {
None
}
}
fn part2(input: &str, target: &str, force: &str, v: u16) -> Option<u16> {
if let Ok(mut c) = input.parse::<Circuit>() {
c.force(&Source::Wire(force.to_owned()), v);
c.eval(&Source::Wire(target.to_owned()))
} else {
None
}
}
#[cfg(test)]
mod test {
use super::{Circuit, Source};
#[test]
fn examples() {
let cs = ["123 -> x",
"456 -> y",
"x AND y -> d",
"x OR y -> e",
"x LSHIFT 2 -> f",
"y RSHIFT 2 -> g",
"NOT x -> h",
"NOT y -> i"]
.join("\n");
let mut c = cs.parse::<Circuit>().unwrap();
assert_eq!(c.eval(&Source::Wire("d".to_owned())), Some(72));
assert_eq!(c.eval(&Source::Wire("e".to_owned())), Some(507));
assert_eq!(c.eval(&Source::Wire("f".to_owned())), Some(492));
assert_eq!(c.eval(&Source::Wire("g".to_owned())), Some(114));
assert_eq!(c.eval(&Source::Wire("h".to_owned())), Some(65412));
assert_eq!(c.eval(&Source::Wire("i".to_owned())), Some(65079));
assert_eq!(c.eval(&Source::Wire("x".to_owned())), Some(123));
assert_eq!(c.eval(&Source::Wire("y".to_owned())), Some(456));
}
}
|
{
a.parse::<Source>().and_then(|a| {
o.parse::<Source>().map(|o| {
Gate::UnaryOp {
src: a,
out: o,
f: f,
}
})
})
}
|
identifier_body
|
mod.rs
|
use std::str::FromStr;
use std::collections::HashMap;
use std::ops::{BitAnd, BitOr, Shl, Shr, Not};
const DATA: &'static str = include_str!("input.txt");
pub fn main() -> Vec<String> {
let s1 = run_circuit(DATA, "a").unwrap();
let s2 = part2(DATA, "a", "b", 956).unwrap();
vec![s1.to_string(), s2.to_string()]
}
#[derive(PartialEq, Eq, Hash, Clone)]
enum Source {
Pattern(u16),
Wire(String),
}
impl FromStr for Source {
type Err = &'static str;
fn
|
(s: &str) -> Result<Source, Self::Err> {
match s {
s if s.is_empty() => Err("empty identifier"),
s if (|s: &str| s.chars().all(|c| c.is_digit(10)))(s) => {
s.parse::<u16>().map_err(|_| "parse error").map(Source::Pattern)
}
s if (|s: &str| s.chars().all(|c| c.is_alphabetic()))(s) => {
Ok(Source::Wire(s.to_owned()))
}
_ => Err("unknown identifier format"),
}
}
}
#[derive(PartialEq, Eq, Hash, Clone)]
enum Gate {
UnaryOp {
src: Source,
out: Source,
f: fn(u16) -> u16,
},
BinaryOp {
a: Source,
b: Source,
out: Source,
f: fn(u16, u16) -> u16,
},
}
impl FromStr for Gate {
type Err = &'static str;
fn from_str(s: &str) -> Result<Gate, Self::Err> {
fn id<T>(x: T) -> T {
x
};
fn unary_from_str(a: &str, o: &str, f: fn(u16) -> u16) -> Result<Gate, &'static str> {
a.parse::<Source>().and_then(|a| {
o.parse::<Source>().map(|o| {
Gate::UnaryOp {
src: a,
out: o,
f: f,
}
})
})
}
fn binary_from_str(a: &str,
b: &str,
o: &str,
f: fn(u16, u16) -> u16)
-> Result<Gate, &'static str> {
a.parse::<Source>().and_then(|a| {
b.parse::<Source>().and_then(|b| {
o.parse::<Source>().map(|o| {
Gate::BinaryOp {
a: a,
b: b,
out: o,
f: f,
}
})
})
})
}
match &s.split_whitespace().collect::<Vec<_>>()[..] {
[a, "->", o] => unary_from_str(a, o, id),
["NOT", a, "->", o] => unary_from_str(a, o, Not::not),
[a, "AND", b, "->", o] => binary_from_str(a, b, o, BitAnd::bitand),
[a, "OR", b, "->", o] => binary_from_str(a, b, o, BitOr::bitor),
[a, "LSHIFT", b, "->", o] => binary_from_str(a, b, o, Shl::shl),
[a, "RSHIFT", b, "->", o] => binary_from_str(a, b, o, Shr::shr),
_ => Err("bad input"),
}
}
}
impl Gate {
fn out(&self) -> Source {
match *self {
Gate::UnaryOp{ ref out,..} => out,
Gate::BinaryOp{ ref out,..} => out,
}
.clone()
}
fn eval(&self, c: &mut Circuit) -> Option<u16> {
match *self {
Gate::UnaryOp{ ref src, ref f,.. } => c.eval(src).map(f),
Gate::BinaryOp{ ref a, ref b, ref f,.. } => {
c.eval(a).and_then(|a| c.eval(b).map(|b| f(a, b)))
}
}
}
}
struct Circuit {
gates: HashMap<Source, Gate>,
cache: HashMap<Source, u16>,
}
impl FromStr for Circuit {
type Err = &'static str;
fn from_str(input: &str) -> Result<Circuit, Self::Err> {
let mut circuit = HashMap::new();
let cache = HashMap::new();
for line in input.lines() {
if let Ok(gate) = line.parse::<Gate>() {
circuit.insert(gate.out(), gate);
} else {
return Err("gate parse error");
}
}
Ok(Circuit {
gates: circuit,
cache: cache,
})
}
}
impl Circuit {
fn eval(&mut self, wire: &Source) -> Option<u16> {
match *wire {
Source::Pattern(p) => Some(p),
ref s @ Source::Wire(_) => {
if self.cache.contains_key(s) {
self.cache.get(s).cloned()
} else {
if let Some(v) = self.gates.get(s).cloned().and_then(|g| g.eval(self)) {
self.cache.insert(s.clone(), v);
Some(v)
} else {
None
}
}
}
}
}
fn force(&mut self, s: &Source, v: u16) {
self.cache.clear();
self.cache.insert(s.clone(), v);
}
}
fn run_circuit(input: &str, target: &str) -> Option<u16> {
if let Ok(mut c) = input.parse::<Circuit>() {
c.eval(&Source::Wire(target.to_owned()))
} else {
None
}
}
fn part2(input: &str, target: &str, force: &str, v: u16) -> Option<u16> {
if let Ok(mut c) = input.parse::<Circuit>() {
c.force(&Source::Wire(force.to_owned()), v);
c.eval(&Source::Wire(target.to_owned()))
} else {
None
}
}
#[cfg(test)]
mod test {
use super::{Circuit, Source};
#[test]
fn examples() {
let cs = ["123 -> x",
"456 -> y",
"x AND y -> d",
"x OR y -> e",
"x LSHIFT 2 -> f",
"y RSHIFT 2 -> g",
"NOT x -> h",
"NOT y -> i"]
.join("\n");
let mut c = cs.parse::<Circuit>().unwrap();
assert_eq!(c.eval(&Source::Wire("d".to_owned())), Some(72));
assert_eq!(c.eval(&Source::Wire("e".to_owned())), Some(507));
assert_eq!(c.eval(&Source::Wire("f".to_owned())), Some(492));
assert_eq!(c.eval(&Source::Wire("g".to_owned())), Some(114));
assert_eq!(c.eval(&Source::Wire("h".to_owned())), Some(65412));
assert_eq!(c.eval(&Source::Wire("i".to_owned())), Some(65079));
assert_eq!(c.eval(&Source::Wire("x".to_owned())), Some(123));
assert_eq!(c.eval(&Source::Wire("y".to_owned())), Some(456));
}
}
|
from_str
|
identifier_name
|
mod.rs
|
use std::str::FromStr;
use std::collections::HashMap;
use std::ops::{BitAnd, BitOr, Shl, Shr, Not};
const DATA: &'static str = include_str!("input.txt");
pub fn main() -> Vec<String> {
let s1 = run_circuit(DATA, "a").unwrap();
let s2 = part2(DATA, "a", "b", 956).unwrap();
vec![s1.to_string(), s2.to_string()]
}
#[derive(PartialEq, Eq, Hash, Clone)]
enum Source {
Pattern(u16),
Wire(String),
}
impl FromStr for Source {
type Err = &'static str;
fn from_str(s: &str) -> Result<Source, Self::Err> {
match s {
s if s.is_empty() => Err("empty identifier"),
s if (|s: &str| s.chars().all(|c| c.is_digit(10)))(s) => {
s.parse::<u16>().map_err(|_| "parse error").map(Source::Pattern)
}
s if (|s: &str| s.chars().all(|c| c.is_alphabetic()))(s) => {
Ok(Source::Wire(s.to_owned()))
}
_ => Err("unknown identifier format"),
}
}
}
#[derive(PartialEq, Eq, Hash, Clone)]
enum Gate {
UnaryOp {
src: Source,
out: Source,
f: fn(u16) -> u16,
},
BinaryOp {
a: Source,
b: Source,
out: Source,
f: fn(u16, u16) -> u16,
},
}
impl FromStr for Gate {
type Err = &'static str;
|
fn from_str(s: &str) -> Result<Gate, Self::Err> {
fn id<T>(x: T) -> T {
x
};
fn unary_from_str(a: &str, o: &str, f: fn(u16) -> u16) -> Result<Gate, &'static str> {
a.parse::<Source>().and_then(|a| {
o.parse::<Source>().map(|o| {
Gate::UnaryOp {
src: a,
out: o,
f: f,
}
})
})
}
fn binary_from_str(a: &str,
b: &str,
o: &str,
f: fn(u16, u16) -> u16)
-> Result<Gate, &'static str> {
a.parse::<Source>().and_then(|a| {
b.parse::<Source>().and_then(|b| {
o.parse::<Source>().map(|o| {
Gate::BinaryOp {
a: a,
b: b,
out: o,
f: f,
}
})
})
})
}
match &s.split_whitespace().collect::<Vec<_>>()[..] {
[a, "->", o] => unary_from_str(a, o, id),
["NOT", a, "->", o] => unary_from_str(a, o, Not::not),
[a, "AND", b, "->", o] => binary_from_str(a, b, o, BitAnd::bitand),
[a, "OR", b, "->", o] => binary_from_str(a, b, o, BitOr::bitor),
[a, "LSHIFT", b, "->", o] => binary_from_str(a, b, o, Shl::shl),
[a, "RSHIFT", b, "->", o] => binary_from_str(a, b, o, Shr::shr),
_ => Err("bad input"),
}
}
}
impl Gate {
fn out(&self) -> Source {
match *self {
Gate::UnaryOp{ ref out,..} => out,
Gate::BinaryOp{ ref out,..} => out,
}
.clone()
}
fn eval(&self, c: &mut Circuit) -> Option<u16> {
match *self {
Gate::UnaryOp{ ref src, ref f,.. } => c.eval(src).map(f),
Gate::BinaryOp{ ref a, ref b, ref f,.. } => {
c.eval(a).and_then(|a| c.eval(b).map(|b| f(a, b)))
}
}
}
}
struct Circuit {
gates: HashMap<Source, Gate>,
cache: HashMap<Source, u16>,
}
impl FromStr for Circuit {
type Err = &'static str;
fn from_str(input: &str) -> Result<Circuit, Self::Err> {
let mut circuit = HashMap::new();
let cache = HashMap::new();
for line in input.lines() {
if let Ok(gate) = line.parse::<Gate>() {
circuit.insert(gate.out(), gate);
} else {
return Err("gate parse error");
}
}
Ok(Circuit {
gates: circuit,
cache: cache,
})
}
}
impl Circuit {
fn eval(&mut self, wire: &Source) -> Option<u16> {
match *wire {
Source::Pattern(p) => Some(p),
ref s @ Source::Wire(_) => {
if self.cache.contains_key(s) {
self.cache.get(s).cloned()
} else {
if let Some(v) = self.gates.get(s).cloned().and_then(|g| g.eval(self)) {
self.cache.insert(s.clone(), v);
Some(v)
} else {
None
}
}
}
}
}
fn force(&mut self, s: &Source, v: u16) {
self.cache.clear();
self.cache.insert(s.clone(), v);
}
}
fn run_circuit(input: &str, target: &str) -> Option<u16> {
if let Ok(mut c) = input.parse::<Circuit>() {
c.eval(&Source::Wire(target.to_owned()))
} else {
None
}
}
fn part2(input: &str, target: &str, force: &str, v: u16) -> Option<u16> {
if let Ok(mut c) = input.parse::<Circuit>() {
c.force(&Source::Wire(force.to_owned()), v);
c.eval(&Source::Wire(target.to_owned()))
} else {
None
}
}
#[cfg(test)]
mod test {
use super::{Circuit, Source};
#[test]
fn examples() {
let cs = ["123 -> x",
"456 -> y",
"x AND y -> d",
"x OR y -> e",
"x LSHIFT 2 -> f",
"y RSHIFT 2 -> g",
"NOT x -> h",
"NOT y -> i"]
.join("\n");
let mut c = cs.parse::<Circuit>().unwrap();
assert_eq!(c.eval(&Source::Wire("d".to_owned())), Some(72));
assert_eq!(c.eval(&Source::Wire("e".to_owned())), Some(507));
assert_eq!(c.eval(&Source::Wire("f".to_owned())), Some(492));
assert_eq!(c.eval(&Source::Wire("g".to_owned())), Some(114));
assert_eq!(c.eval(&Source::Wire("h".to_owned())), Some(65412));
assert_eq!(c.eval(&Source::Wire("i".to_owned())), Some(65079));
assert_eq!(c.eval(&Source::Wire("x".to_owned())), Some(123));
assert_eq!(c.eval(&Source::Wire("y".to_owned())), Some(456));
}
}
|
random_line_split
|
|
tempfile.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.
//! Temporary files and directories
use io::{fs, IoResult};
use io;
use iter::range;
use libc;
use ops::Drop;
use option::{Option, None, Some};
use os;
use path::{Path, GenericPath};
use result::{Ok, Err};
use sync::atomic;
/// A wrapper for a path to temporary directory implementing automatic
/// scope-based deletion.
pub struct TempDir {
path: Option<Path>,
disarmed: bool
}
impl TempDir {
/// Attempts to make a temporary directory inside of `tmpdir` whose name
/// will have the suffix `suffix`. The directory will be automatically
/// deleted once the returned wrapper is destroyed.
///
/// If no directory can be created, None is returned.
pub fn
|
(tmpdir: &Path, suffix: &str) -> Option<TempDir> {
if!tmpdir.is_absolute() {
return TempDir::new_in(&os::make_absolute(tmpdir), suffix);
}
static mut CNT: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT;
for _ in range(0u, 1000) {
let filename =
format!("rs-{}-{}-{}",
unsafe { libc::getpid() },
unsafe { CNT.fetch_add(1, atomic::SeqCst) },
suffix);
let p = tmpdir.join(filename);
match fs::mkdir(&p, io::UserRWX) {
Err(..) => {}
Ok(()) => return Some(TempDir { path: Some(p), disarmed: false })
}
}
None
}
/// Attempts to make a temporary directory inside of `os::tmpdir()` whose
/// name will have the suffix `suffix`. The directory will be automatically
/// deleted once the returned wrapper is destroyed.
///
/// If no directory can be created, None is returned.
pub fn new(suffix: &str) -> Option<TempDir> {
TempDir::new_in(&os::tmpdir(), suffix)
}
/// Unwrap the wrapped `std::path::Path` from the `TempDir` wrapper.
/// This discards the wrapper so that the automatic deletion of the
/// temporary directory is prevented.
pub fn unwrap(self) -> Path {
let mut tmpdir = self;
tmpdir.path.take_unwrap()
}
/// Access the wrapped `std::path::Path` to the temporary directory.
pub fn path<'a>(&'a self) -> &'a Path {
self.path.get_ref()
}
/// Close and remove the temporary directory
///
/// Although `TempDir` removes the directory on drop, in the destructor
/// any errors are ignored. To detect errors cleaning up the temporary
/// directory, call `close` instead.
pub fn close(mut self) -> IoResult<()> {
self.cleanup_dir()
}
fn cleanup_dir(&mut self) -> IoResult<()> {
assert!(!self.disarmed);
self.disarmed = true;
match self.path {
Some(ref p) => {
fs::rmdir_recursive(p)
}
None => Ok(())
}
}
}
impl Drop for TempDir {
fn drop(&mut self) {
if!self.disarmed {
let _ = self.cleanup_dir();
}
}
}
// the tests for this module need to change the path using change_dir,
// and this doesn't play nicely with other tests so these unit tests are located
// in src/test/run-pass/tempfile.rs
|
new_in
|
identifier_name
|
tempfile.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.
//! Temporary files and directories
use io::{fs, IoResult};
use io;
use iter::range;
use libc;
use ops::Drop;
use option::{Option, None, Some};
use os;
use path::{Path, GenericPath};
use result::{Ok, Err};
use sync::atomic;
/// A wrapper for a path to temporary directory implementing automatic
/// scope-based deletion.
pub struct TempDir {
path: Option<Path>,
disarmed: bool
}
impl TempDir {
/// Attempts to make a temporary directory inside of `tmpdir` whose name
/// will have the suffix `suffix`. The directory will be automatically
/// deleted once the returned wrapper is destroyed.
///
/// If no directory can be created, None is returned.
pub fn new_in(tmpdir: &Path, suffix: &str) -> Option<TempDir> {
if!tmpdir.is_absolute() {
return TempDir::new_in(&os::make_absolute(tmpdir), suffix);
}
static mut CNT: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT;
for _ in range(0u, 1000) {
let filename =
format!("rs-{}-{}-{}",
unsafe { libc::getpid() },
unsafe { CNT.fetch_add(1, atomic::SeqCst) },
suffix);
let p = tmpdir.join(filename);
match fs::mkdir(&p, io::UserRWX) {
Err(..) => {}
Ok(()) => return Some(TempDir { path: Some(p), disarmed: false })
}
}
None
}
/// Attempts to make a temporary directory inside of `os::tmpdir()` whose
/// name will have the suffix `suffix`. The directory will be automatically
/// deleted once the returned wrapper is destroyed.
///
/// If no directory can be created, None is returned.
pub fn new(suffix: &str) -> Option<TempDir> {
TempDir::new_in(&os::tmpdir(), suffix)
}
/// Unwrap the wrapped `std::path::Path` from the `TempDir` wrapper.
/// This discards the wrapper so that the automatic deletion of the
/// temporary directory is prevented.
pub fn unwrap(self) -> Path {
let mut tmpdir = self;
tmpdir.path.take_unwrap()
}
/// Access the wrapped `std::path::Path` to the temporary directory.
pub fn path<'a>(&'a self) -> &'a Path {
self.path.get_ref()
}
/// Close and remove the temporary directory
///
/// Although `TempDir` removes the directory on drop, in the destructor
/// any errors are ignored. To detect errors cleaning up the temporary
/// directory, call `close` instead.
pub fn close(mut self) -> IoResult<()> {
self.cleanup_dir()
}
|
match self.path {
Some(ref p) => {
fs::rmdir_recursive(p)
}
None => Ok(())
}
}
}
impl Drop for TempDir {
fn drop(&mut self) {
if!self.disarmed {
let _ = self.cleanup_dir();
}
}
}
// the tests for this module need to change the path using change_dir,
// and this doesn't play nicely with other tests so these unit tests are located
// in src/test/run-pass/tempfile.rs
|
fn cleanup_dir(&mut self) -> IoResult<()> {
assert!(!self.disarmed);
self.disarmed = true;
|
random_line_split
|
tempfile.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.
//! Temporary files and directories
use io::{fs, IoResult};
use io;
use iter::range;
use libc;
use ops::Drop;
use option::{Option, None, Some};
use os;
use path::{Path, GenericPath};
use result::{Ok, Err};
use sync::atomic;
/// A wrapper for a path to temporary directory implementing automatic
/// scope-based deletion.
pub struct TempDir {
path: Option<Path>,
disarmed: bool
}
impl TempDir {
/// Attempts to make a temporary directory inside of `tmpdir` whose name
/// will have the suffix `suffix`. The directory will be automatically
/// deleted once the returned wrapper is destroyed.
///
/// If no directory can be created, None is returned.
pub fn new_in(tmpdir: &Path, suffix: &str) -> Option<TempDir> {
if!tmpdir.is_absolute() {
return TempDir::new_in(&os::make_absolute(tmpdir), suffix);
}
static mut CNT: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT;
for _ in range(0u, 1000) {
let filename =
format!("rs-{}-{}-{}",
unsafe { libc::getpid() },
unsafe { CNT.fetch_add(1, atomic::SeqCst) },
suffix);
let p = tmpdir.join(filename);
match fs::mkdir(&p, io::UserRWX) {
Err(..) => {}
Ok(()) => return Some(TempDir { path: Some(p), disarmed: false })
}
}
None
}
/// Attempts to make a temporary directory inside of `os::tmpdir()` whose
/// name will have the suffix `suffix`. The directory will be automatically
/// deleted once the returned wrapper is destroyed.
///
/// If no directory can be created, None is returned.
pub fn new(suffix: &str) -> Option<TempDir> {
TempDir::new_in(&os::tmpdir(), suffix)
}
/// Unwrap the wrapped `std::path::Path` from the `TempDir` wrapper.
/// This discards the wrapper so that the automatic deletion of the
/// temporary directory is prevented.
pub fn unwrap(self) -> Path {
let mut tmpdir = self;
tmpdir.path.take_unwrap()
}
/// Access the wrapped `std::path::Path` to the temporary directory.
pub fn path<'a>(&'a self) -> &'a Path {
self.path.get_ref()
}
/// Close and remove the temporary directory
///
/// Although `TempDir` removes the directory on drop, in the destructor
/// any errors are ignored. To detect errors cleaning up the temporary
/// directory, call `close` instead.
pub fn close(mut self) -> IoResult<()> {
self.cleanup_dir()
}
fn cleanup_dir(&mut self) -> IoResult<()> {
assert!(!self.disarmed);
self.disarmed = true;
match self.path {
Some(ref p) => {
fs::rmdir_recursive(p)
}
None => Ok(())
}
}
}
impl Drop for TempDir {
fn drop(&mut self) {
if!self.disarmed
|
}
}
// the tests for this module need to change the path using change_dir,
// and this doesn't play nicely with other tests so these unit tests are located
// in src/test/run-pass/tempfile.rs
|
{
let _ = self.cleanup_dir();
}
|
conditional_block
|
lib.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/. */
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(step_trait)]
#![feature(zero_one)]
#![plugin(heapsize_plugin)]
#![plugin(serde_macros)]
#![deny(unsafe_code)]
extern crate heapsize;
extern crate num as num_lib;
extern crate rustc_serialize;
extern crate serde;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::num;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
fn max_value() -> Self;
fn from_usize(n: usize) -> Option<Self>;
}
impl Int for isize {
#[inline]
fn zero() -> isize { 0 }
#[inline]
fn one() -> isize { 1 }
#[inline]
fn max_value() -> isize { ::std::isize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<isize> { num_lib::NumCast::from(n) }
}
impl Int for usize {
#[inline]
fn zero() -> usize { 0 }
#[inline]
fn one() -> usize { 1 }
#[inline]
fn max_value() -> usize { ::std::usize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<usize> { Some(n) }
}
/// An index type to be used by a `Range`
pub trait RangeIndex: Int + fmt::Debug {
type Index;
fn new(x: Self::Index) -> Self;
fn get(self) -> Self::Index;
}
impl RangeIndex for isize {
type Index = isize;
#[inline]
fn new(x: isize) -> isize { x }
#[inline]
fn get(self) -> isize { self }
}
impl RangeIndex for usize {
type Index = usize;
#[inline]
fn new(x: usize) -> usize { x }
#[inline]
fn get(self) -> usize { self }
}
/// Implements a range index type with operator overloads
#[macro_export]
macro_rules! int_range_index {
($(#[$attr:meta])* struct $Self_:ident($T:ty)) => (
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)]
$(#[$attr])*
pub struct $Self_(pub $T);
impl $Self_ {
#[inline]
pub fn to_usize(self) -> usize {
self.get() as usize
}
}
impl RangeIndex for $Self_ {
type Index = $T;
#[inline]
fn new(x: $T) -> $Self_ {
$Self_(x)
}
#[inline]
fn get(self) -> $T {
match self { $Self_(x) => x }
}
}
impl $crate::Int for $Self_ {
#[inline]
fn zero() -> $Self_ { $Self_($crate::Int::zero()) }
#[inline]
fn one() -> $Self_ { $Self_($crate::Int::one()) }
#[inline]
fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) }
#[inline]
fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) }
}
impl ::std::ops::Add<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn add(self, other: $Self_) -> $Self_ {
$Self_(self.get() + other.get())
}
}
impl ::std::ops::Sub<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn sub(self, other: $Self_) -> $Self_ {
$Self_(self.get() - other.get())
}
}
impl ::std::ops::Neg for $Self_ {
type Output = $Self_;
#[inline]
fn neg(self) -> $Self_ {
$Self_(-self.get())
}
}
)
}
/// A range of indices
#[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)]
pub struct Range<I> {
begin: I,
length: I,
}
impl<I: RangeIndex> fmt::Debug for Range<I> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:?}.. {:?})", self.begin(), self.end())
}
}
/// An iterator over each index in a range
pub struct EachIndex<T, I> {
it: ops::Range<T>,
phantom: PhantomData<I>,
}
pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> {
EachIndex { it: start.get()..stop.get(), phantom: PhantomData }
}
impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I>
where T: Int + num::One + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> {
type Item = I;
#[inline]
fn next(&mut self) -> Option<I> {
self.it.next().map(RangeIndex::new)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<I: RangeIndex> Range<I> {
/// Create a new range from beginning and length offsets. This could be
/// denoted as `[begin, begin + length)`.
///
/// ~~~ignore
/// |-- begin ->|-- length ->|
/// | | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn new(begin: I, length: I) -> Range<I> {
Range { begin: begin, length: length }
}
#[inline]
pub fn empty() -> Range<I> {
Range::new(Int::zero(), Int::zero())
}
/// The index offset to the beginning of the range.
///
/// ~~~ignore
/// |-- begin ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn begin(&self) -> I { self.begin }
/// The index offset from the beginning to the end of the range.
///
/// ~~~ignore
/// |-- length ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn length(&self) -> I { self.length }
/// The index offset to the end of the range.
///
/// ~~~ignore
/// |--------- end --------->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn end(&self) -> I { self.begin + self.length }
/// `true` if the index is between the beginning and the end of the range.
///
/// ~~~ignore
/// false true false
/// | | |
/// <- o - - + - - +=====+======+ - + - ->
/// ~~~
#[inline]
pub fn contains(&self, i: I) -> bool {
i >= self.begin() && i < self.end()
}
/// `true` if the offset from the beginning to the end of the range is zero.
#[inline]
pub fn is_empty(&self) -> bool {
self.length() == Int::zero()
}
/// Shift the entire range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - +============+ - - - - - | - - - ->
/// |
/// <- o - - - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn shift_by(&mut self, delta: I) {
self.begin = self.begin + delta;
}
/// Extend the end of the range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_by(&mut self, delta: I) {
self.length = self.length + delta;
}
/// Move the end of the range to the target index.
///
/// ~~~ignore
/// target
/// |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_to(&mut self, target: I) {
self.length = target - self.begin;
}
/// Adjust the beginning offset and the length by the supplied deltas.
#[inline]
pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) {
self.begin = self.begin + begin_delta;
self.length = self.length + length_delta;
}
/// Set the begin and length values.
#[inline]
pub fn reset(&mut self, begin: I, length: I) {
self.begin = begin;
self.length = length;
}
#[inline]
pub fn intersect(&self, other: &Range<I>) -> Range<I> {
let begin = max(self.begin(), other.begin());
let end = min(self.end(), other.end());
if end < begin {
Range::empty()
} else {
Range::new(begin, end - begin)
}
}
}
/// Methods for `Range`s with indices based on integer values
impl<T: Int, I: RangeIndex<Index=T>> Range<I> {
/// Returns an iterater that increments over `[begin, end)`.
#[inline]
pub fn
|
(&self) -> EachIndex<T, I> {
each_index(self.begin(), self.end())
}
}
|
each_index
|
identifier_name
|
lib.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/. */
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(step_trait)]
#![feature(zero_one)]
#![plugin(heapsize_plugin)]
#![plugin(serde_macros)]
#![deny(unsafe_code)]
extern crate heapsize;
extern crate num as num_lib;
extern crate rustc_serialize;
extern crate serde;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::num;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
fn max_value() -> Self;
fn from_usize(n: usize) -> Option<Self>;
}
impl Int for isize {
#[inline]
fn zero() -> isize { 0 }
#[inline]
fn one() -> isize { 1 }
#[inline]
fn max_value() -> isize { ::std::isize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<isize> { num_lib::NumCast::from(n) }
}
impl Int for usize {
#[inline]
fn zero() -> usize { 0 }
#[inline]
fn one() -> usize { 1 }
#[inline]
fn max_value() -> usize { ::std::usize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<usize> { Some(n) }
}
/// An index type to be used by a `Range`
pub trait RangeIndex: Int + fmt::Debug {
type Index;
fn new(x: Self::Index) -> Self;
fn get(self) -> Self::Index;
}
impl RangeIndex for isize {
type Index = isize;
#[inline]
fn new(x: isize) -> isize { x }
#[inline]
fn get(self) -> isize { self }
}
impl RangeIndex for usize {
type Index = usize;
#[inline]
fn new(x: usize) -> usize { x }
#[inline]
fn get(self) -> usize { self }
}
/// Implements a range index type with operator overloads
#[macro_export]
macro_rules! int_range_index {
($(#[$attr:meta])* struct $Self_:ident($T:ty)) => (
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)]
$(#[$attr])*
pub struct $Self_(pub $T);
impl $Self_ {
#[inline]
pub fn to_usize(self) -> usize {
self.get() as usize
}
}
impl RangeIndex for $Self_ {
type Index = $T;
#[inline]
fn new(x: $T) -> $Self_ {
$Self_(x)
}
#[inline]
fn get(self) -> $T {
match self { $Self_(x) => x }
}
}
impl $crate::Int for $Self_ {
#[inline]
fn zero() -> $Self_ { $Self_($crate::Int::zero()) }
#[inline]
fn one() -> $Self_ { $Self_($crate::Int::one()) }
#[inline]
fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) }
#[inline]
fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) }
}
impl ::std::ops::Add<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn add(self, other: $Self_) -> $Self_ {
$Self_(self.get() + other.get())
}
}
impl ::std::ops::Sub<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn sub(self, other: $Self_) -> $Self_ {
$Self_(self.get() - other.get())
}
}
impl ::std::ops::Neg for $Self_ {
type Output = $Self_;
#[inline]
fn neg(self) -> $Self_ {
$Self_(-self.get())
}
}
)
}
/// A range of indices
#[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)]
pub struct Range<I> {
begin: I,
length: I,
}
impl<I: RangeIndex> fmt::Debug for Range<I> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:?}.. {:?})", self.begin(), self.end())
}
}
/// An iterator over each index in a range
pub struct EachIndex<T, I> {
it: ops::Range<T>,
phantom: PhantomData<I>,
}
pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> {
EachIndex { it: start.get()..stop.get(), phantom: PhantomData }
}
impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I>
where T: Int + num::One + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> {
type Item = I;
#[inline]
fn next(&mut self) -> Option<I> {
self.it.next().map(RangeIndex::new)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<I: RangeIndex> Range<I> {
/// Create a new range from beginning and length offsets. This could be
/// denoted as `[begin, begin + length)`.
///
/// ~~~ignore
/// |-- begin ->|-- length ->|
/// | | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn new(begin: I, length: I) -> Range<I> {
Range { begin: begin, length: length }
}
#[inline]
pub fn empty() -> Range<I> {
Range::new(Int::zero(), Int::zero())
}
/// The index offset to the beginning of the range.
///
/// ~~~ignore
/// |-- begin ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn begin(&self) -> I { self.begin }
/// The index offset from the beginning to the end of the range.
///
/// ~~~ignore
/// |-- length ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn length(&self) -> I { self.length }
/// The index offset to the end of the range.
///
/// ~~~ignore
/// |--------- end --------->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn end(&self) -> I { self.begin + self.length }
/// `true` if the index is between the beginning and the end of the range.
///
/// ~~~ignore
/// false true false
/// | | |
/// <- o - - + - - +=====+======+ - + - ->
/// ~~~
#[inline]
pub fn contains(&self, i: I) -> bool {
i >= self.begin() && i < self.end()
}
/// `true` if the offset from the beginning to the end of the range is zero.
#[inline]
pub fn is_empty(&self) -> bool {
self.length() == Int::zero()
}
/// Shift the entire range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - +============+ - - - - - | - - - ->
/// |
/// <- o - - - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn shift_by(&mut self, delta: I) {
self.begin = self.begin + delta;
}
/// Extend the end of the range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_by(&mut self, delta: I) {
self.length = self.length + delta;
}
|
/// Move the end of the range to the target index.
///
/// ~~~ignore
/// target
/// |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_to(&mut self, target: I) {
self.length = target - self.begin;
}
/// Adjust the beginning offset and the length by the supplied deltas.
#[inline]
pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) {
self.begin = self.begin + begin_delta;
self.length = self.length + length_delta;
}
/// Set the begin and length values.
#[inline]
pub fn reset(&mut self, begin: I, length: I) {
self.begin = begin;
self.length = length;
}
#[inline]
pub fn intersect(&self, other: &Range<I>) -> Range<I> {
let begin = max(self.begin(), other.begin());
let end = min(self.end(), other.end());
if end < begin {
Range::empty()
} else {
Range::new(begin, end - begin)
}
}
}
/// Methods for `Range`s with indices based on integer values
impl<T: Int, I: RangeIndex<Index=T>> Range<I> {
/// Returns an iterater that increments over `[begin, end)`.
#[inline]
pub fn each_index(&self) -> EachIndex<T, I> {
each_index(self.begin(), self.end())
}
}
|
random_line_split
|
|
lib.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/. */
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(step_trait)]
#![feature(zero_one)]
#![plugin(heapsize_plugin)]
#![plugin(serde_macros)]
#![deny(unsafe_code)]
extern crate heapsize;
extern crate num as num_lib;
extern crate rustc_serialize;
extern crate serde;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::num;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
fn max_value() -> Self;
fn from_usize(n: usize) -> Option<Self>;
}
impl Int for isize {
#[inline]
fn zero() -> isize { 0 }
#[inline]
fn one() -> isize { 1 }
#[inline]
fn max_value() -> isize { ::std::isize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<isize> { num_lib::NumCast::from(n) }
}
impl Int for usize {
#[inline]
fn zero() -> usize { 0 }
#[inline]
fn one() -> usize { 1 }
#[inline]
fn max_value() -> usize { ::std::usize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<usize> { Some(n) }
}
/// An index type to be used by a `Range`
pub trait RangeIndex: Int + fmt::Debug {
type Index;
fn new(x: Self::Index) -> Self;
fn get(self) -> Self::Index;
}
impl RangeIndex for isize {
type Index = isize;
#[inline]
fn new(x: isize) -> isize { x }
#[inline]
fn get(self) -> isize { self }
}
impl RangeIndex for usize {
type Index = usize;
#[inline]
fn new(x: usize) -> usize { x }
#[inline]
fn get(self) -> usize { self }
}
/// Implements a range index type with operator overloads
#[macro_export]
macro_rules! int_range_index {
($(#[$attr:meta])* struct $Self_:ident($T:ty)) => (
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)]
$(#[$attr])*
pub struct $Self_(pub $T);
impl $Self_ {
#[inline]
pub fn to_usize(self) -> usize {
self.get() as usize
}
}
impl RangeIndex for $Self_ {
type Index = $T;
#[inline]
fn new(x: $T) -> $Self_ {
$Self_(x)
}
#[inline]
fn get(self) -> $T {
match self { $Self_(x) => x }
}
}
impl $crate::Int for $Self_ {
#[inline]
fn zero() -> $Self_ { $Self_($crate::Int::zero()) }
#[inline]
fn one() -> $Self_ { $Self_($crate::Int::one()) }
#[inline]
fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) }
#[inline]
fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) }
}
impl ::std::ops::Add<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn add(self, other: $Self_) -> $Self_ {
$Self_(self.get() + other.get())
}
}
impl ::std::ops::Sub<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn sub(self, other: $Self_) -> $Self_ {
$Self_(self.get() - other.get())
}
}
impl ::std::ops::Neg for $Self_ {
type Output = $Self_;
#[inline]
fn neg(self) -> $Self_ {
$Self_(-self.get())
}
}
)
}
/// A range of indices
#[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)]
pub struct Range<I> {
begin: I,
length: I,
}
impl<I: RangeIndex> fmt::Debug for Range<I> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:?}.. {:?})", self.begin(), self.end())
}
}
/// An iterator over each index in a range
pub struct EachIndex<T, I> {
it: ops::Range<T>,
phantom: PhantomData<I>,
}
pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> {
EachIndex { it: start.get()..stop.get(), phantom: PhantomData }
}
impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I>
where T: Int + num::One + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> {
type Item = I;
#[inline]
fn next(&mut self) -> Option<I> {
self.it.next().map(RangeIndex::new)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<I: RangeIndex> Range<I> {
/// Create a new range from beginning and length offsets. This could be
/// denoted as `[begin, begin + length)`.
///
/// ~~~ignore
/// |-- begin ->|-- length ->|
/// | | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn new(begin: I, length: I) -> Range<I> {
Range { begin: begin, length: length }
}
#[inline]
pub fn empty() -> Range<I> {
Range::new(Int::zero(), Int::zero())
}
/// The index offset to the beginning of the range.
///
/// ~~~ignore
/// |-- begin ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn begin(&self) -> I { self.begin }
/// The index offset from the beginning to the end of the range.
///
/// ~~~ignore
/// |-- length ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn length(&self) -> I { self.length }
/// The index offset to the end of the range.
///
/// ~~~ignore
/// |--------- end --------->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn end(&self) -> I { self.begin + self.length }
/// `true` if the index is between the beginning and the end of the range.
///
/// ~~~ignore
/// false true false
/// | | |
/// <- o - - + - - +=====+======+ - + - ->
/// ~~~
#[inline]
pub fn contains(&self, i: I) -> bool {
i >= self.begin() && i < self.end()
}
/// `true` if the offset from the beginning to the end of the range is zero.
#[inline]
pub fn is_empty(&self) -> bool {
self.length() == Int::zero()
}
/// Shift the entire range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - +============+ - - - - - | - - - ->
/// |
/// <- o - - - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn shift_by(&mut self, delta: I) {
self.begin = self.begin + delta;
}
/// Extend the end of the range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_by(&mut self, delta: I) {
self.length = self.length + delta;
}
/// Move the end of the range to the target index.
///
/// ~~~ignore
/// target
/// |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_to(&mut self, target: I)
|
/// Adjust the beginning offset and the length by the supplied deltas.
#[inline]
pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) {
self.begin = self.begin + begin_delta;
self.length = self.length + length_delta;
}
/// Set the begin and length values.
#[inline]
pub fn reset(&mut self, begin: I, length: I) {
self.begin = begin;
self.length = length;
}
#[inline]
pub fn intersect(&self, other: &Range<I>) -> Range<I> {
let begin = max(self.begin(), other.begin());
let end = min(self.end(), other.end());
if end < begin {
Range::empty()
} else {
Range::new(begin, end - begin)
}
}
}
/// Methods for `Range`s with indices based on integer values
impl<T: Int, I: RangeIndex<Index=T>> Range<I> {
/// Returns an iterater that increments over `[begin, end)`.
#[inline]
pub fn each_index(&self) -> EachIndex<T, I> {
each_index(self.begin(), self.end())
}
}
|
{
self.length = target - self.begin;
}
|
identifier_body
|
lib.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/. */
#![feature(custom_derive)]
#![feature(plugin)]
#![feature(step_trait)]
#![feature(zero_one)]
#![plugin(heapsize_plugin)]
#![plugin(serde_macros)]
#![deny(unsafe_code)]
extern crate heapsize;
extern crate num as num_lib;
extern crate rustc_serialize;
extern crate serde;
use std::cmp::{self, max, min};
use std::fmt;
use std::iter;
use std::marker::PhantomData;
use std::num;
use std::ops;
pub trait Int:
Copy
+ ops::Add<Self, Output=Self>
+ ops::Sub<Self, Output=Self>
+ cmp::Ord
{
fn zero() -> Self;
fn one() -> Self;
fn max_value() -> Self;
fn from_usize(n: usize) -> Option<Self>;
}
impl Int for isize {
#[inline]
fn zero() -> isize { 0 }
#[inline]
fn one() -> isize { 1 }
#[inline]
fn max_value() -> isize { ::std::isize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<isize> { num_lib::NumCast::from(n) }
}
impl Int for usize {
#[inline]
fn zero() -> usize { 0 }
#[inline]
fn one() -> usize { 1 }
#[inline]
fn max_value() -> usize { ::std::usize::MAX }
#[inline]
fn from_usize(n: usize) -> Option<usize> { Some(n) }
}
/// An index type to be used by a `Range`
pub trait RangeIndex: Int + fmt::Debug {
type Index;
fn new(x: Self::Index) -> Self;
fn get(self) -> Self::Index;
}
impl RangeIndex for isize {
type Index = isize;
#[inline]
fn new(x: isize) -> isize { x }
#[inline]
fn get(self) -> isize { self }
}
impl RangeIndex for usize {
type Index = usize;
#[inline]
fn new(x: usize) -> usize { x }
#[inline]
fn get(self) -> usize { self }
}
/// Implements a range index type with operator overloads
#[macro_export]
macro_rules! int_range_index {
($(#[$attr:meta])* struct $Self_:ident($T:ty)) => (
#[derive(Clone, PartialEq, PartialOrd, Eq, Ord, Debug, Copy)]
$(#[$attr])*
pub struct $Self_(pub $T);
impl $Self_ {
#[inline]
pub fn to_usize(self) -> usize {
self.get() as usize
}
}
impl RangeIndex for $Self_ {
type Index = $T;
#[inline]
fn new(x: $T) -> $Self_ {
$Self_(x)
}
#[inline]
fn get(self) -> $T {
match self { $Self_(x) => x }
}
}
impl $crate::Int for $Self_ {
#[inline]
fn zero() -> $Self_ { $Self_($crate::Int::zero()) }
#[inline]
fn one() -> $Self_ { $Self_($crate::Int::one()) }
#[inline]
fn max_value() -> $Self_ { $Self_($crate::Int::max_value()) }
#[inline]
fn from_usize(n: usize) -> Option<$Self_> { $crate::Int::from_usize(n).map($Self_) }
}
impl ::std::ops::Add<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn add(self, other: $Self_) -> $Self_ {
$Self_(self.get() + other.get())
}
}
impl ::std::ops::Sub<$Self_> for $Self_ {
type Output = $Self_;
#[inline]
fn sub(self, other: $Self_) -> $Self_ {
$Self_(self.get() - other.get())
}
}
impl ::std::ops::Neg for $Self_ {
type Output = $Self_;
#[inline]
fn neg(self) -> $Self_ {
$Self_(-self.get())
}
}
)
}
/// A range of indices
#[derive(Clone, Copy, Deserialize, HeapSizeOf, RustcEncodable, Serialize)]
pub struct Range<I> {
begin: I,
length: I,
}
impl<I: RangeIndex> fmt::Debug for Range<I> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:?}.. {:?})", self.begin(), self.end())
}
}
/// An iterator over each index in a range
pub struct EachIndex<T, I> {
it: ops::Range<T>,
phantom: PhantomData<I>,
}
pub fn each_index<T: Int, I: RangeIndex<Index=T>>(start: I, stop: I) -> EachIndex<T, I> {
EachIndex { it: start.get()..stop.get(), phantom: PhantomData }
}
impl<T: Int, I: RangeIndex<Index=T>> Iterator for EachIndex<T, I>
where T: Int + num::One + iter::Step, for<'a> &'a T: ops::Add<&'a T, Output = T> {
type Item = I;
#[inline]
fn next(&mut self) -> Option<I> {
self.it.next().map(RangeIndex::new)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
impl<I: RangeIndex> Range<I> {
/// Create a new range from beginning and length offsets. This could be
/// denoted as `[begin, begin + length)`.
///
/// ~~~ignore
/// |-- begin ->|-- length ->|
/// | | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn new(begin: I, length: I) -> Range<I> {
Range { begin: begin, length: length }
}
#[inline]
pub fn empty() -> Range<I> {
Range::new(Int::zero(), Int::zero())
}
/// The index offset to the beginning of the range.
///
/// ~~~ignore
/// |-- begin ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn begin(&self) -> I { self.begin }
/// The index offset from the beginning to the end of the range.
///
/// ~~~ignore
/// |-- length ->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn length(&self) -> I { self.length }
/// The index offset to the end of the range.
///
/// ~~~ignore
/// |--------- end --------->|
/// | |
/// <- o - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn end(&self) -> I { self.begin + self.length }
/// `true` if the index is between the beginning and the end of the range.
///
/// ~~~ignore
/// false true false
/// | | |
/// <- o - - + - - +=====+======+ - + - ->
/// ~~~
#[inline]
pub fn contains(&self, i: I) -> bool {
i >= self.begin() && i < self.end()
}
/// `true` if the offset from the beginning to the end of the range is zero.
#[inline]
pub fn is_empty(&self) -> bool {
self.length() == Int::zero()
}
/// Shift the entire range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - +============+ - - - - - | - - - ->
/// |
/// <- o - - - - - - - +============+ - - - ->
/// ~~~
#[inline]
pub fn shift_by(&mut self, delta: I) {
self.begin = self.begin + delta;
}
/// Extend the end of the range by the supplied index delta.
///
/// ~~~ignore
/// |-- delta ->|
/// | |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_by(&mut self, delta: I) {
self.length = self.length + delta;
}
/// Move the end of the range to the target index.
///
/// ~~~ignore
/// target
/// |
/// <- o - - - - - +====+ - - - - - | - - - ->
/// |
/// <- o - - - - - +================+ - - - ->
/// ~~~
#[inline]
pub fn extend_to(&mut self, target: I) {
self.length = target - self.begin;
}
/// Adjust the beginning offset and the length by the supplied deltas.
#[inline]
pub fn adjust_by(&mut self, begin_delta: I, length_delta: I) {
self.begin = self.begin + begin_delta;
self.length = self.length + length_delta;
}
/// Set the begin and length values.
#[inline]
pub fn reset(&mut self, begin: I, length: I) {
self.begin = begin;
self.length = length;
}
#[inline]
pub fn intersect(&self, other: &Range<I>) -> Range<I> {
let begin = max(self.begin(), other.begin());
let end = min(self.end(), other.end());
if end < begin {
Range::empty()
} else
|
}
}
/// Methods for `Range`s with indices based on integer values
impl<T: Int, I: RangeIndex<Index=T>> Range<I> {
/// Returns an iterater that increments over `[begin, end)`.
#[inline]
pub fn each_index(&self) -> EachIndex<T, I> {
each_index(self.begin(), self.end())
}
}
|
{
Range::new(begin, end - begin)
}
|
conditional_block
|
semigroup.rs
|
//! Module for holding the Semigroup typeclass definition and typeclass instances
//!
//! You can, for example, combine tuples.
#![cfg_attr(
feature = "std",
doc = r#"
# Examples
```
#[macro_use]
extern crate frunk;
# fn main() {
use frunk::Semigroup;
let t1 = (1, 2.5f32, String::from("hi"), Some(3));
let t2 = (1, 2.5f32, String::from(" world"), None);
let expected = (2, 5.0f32, String::from("hi world"), Some(3));
assert_eq!(t1.combine(&t2), expected);
// ultimately, the Tuple-based Semigroup implementations are only available for a maximum of
// 26 elements. If you need more, use HList, which is has no such limit.
let h1 = hlist![1, 3.3, 53i64];
let h2 = hlist![2, 1.2, 1i64];
let h3 = hlist![3, 4.5, 54];
assert_eq!(h1.combine(&h2), h3)
# }
```"#
)]
use frunk_core::hlist::*;
use std::cell::*;
use std::cmp::Ordering;
#[cfg(feature = "std")]
use std::collections::hash_map::Entry;
#[cfg(feature = "std")]
use std::collections::{HashMap, HashSet};
#[cfg(feature = "std")]
use std::hash::Hash;
use std::ops::{BitAnd, BitOr, Deref};
/// Wrapper type for types that are ordered and can have a Max combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Max<T: Ord>(pub T);
/// Wrapper type for types that are ordered and can have a Min combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Min<T: Ord>(pub T);
/// Wrapper type for types that can have a Product combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Product<T>(pub T);
/// Wrapper type for boolean that acts as a bitwise && combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct All<T>(pub T);
/// Wrapper type for boolean that acts as a bitwise || combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Any<T>(pub T);
/// A Semigroup is a class of thing that has a definable combine operation
pub trait Semigroup {
/// Associative operation taking which combines two values.
///
/// # Examples
///
/// ```
/// use frunk::Semigroup;
///
/// assert_eq!(Some(1).combine(&Some(2)), Some(3))
/// ```
fn combine(&self, other: &Self) -> Self;
}
/// Allow the combination of any two HLists having the same structure
/// if all of the sub-element types are also Semiups
impl<H: Semigroup, T: HList + Semigroup> Semigroup for HCons<H, T> {
fn combine(&self, other: &Self) -> Self {
self.tail
.combine(&other.tail)
.prepend(self.head.combine(&other.head))
}
}
/// Since () + () = (), the same is true for HNil
impl Semigroup for HNil {
fn combine(&self, _: &Self) -> Self {
*self
}
}
/// Return this combined with itself `n` times.
pub fn combine_n<T>(o: &T, times: u32) -> T
where
T: Semigroup + Clone,
{
let mut x = o.clone();
// note: range is non-inclusive in the upper bound
for _ in 1..times {
x = o.combine(&x);
}
x
}
/// Given a sequence of `xs`, combine them and return the total
///
/// If the sequence is empty, returns None. Otherwise, returns Some(total).
///
/// # Examples
///
/// ```
/// use frunk::semigroup::combine_all_option;
///
/// let v1 = &vec![1, 2, 3];
/// assert_eq!(combine_all_option(v1), Some(6));
///
/// let v2: Vec<i16> = Vec::new(); // empty!
/// assert_eq!(combine_all_option(&v2), None);
/// ```
pub fn combine_all_option<T>(xs: &[T]) -> Option<T>
where
T: Semigroup + Clone,
{
xs.first()
.map(|head| xs[1..].iter().fold(head.clone(), |a, b| a.combine(b)))
}
macro_rules! numeric_semigroup_imps {
($($tr:ty),*) => {
$(
impl Semigroup for $tr {
fn combine(&self, other: &Self) -> Self { self + other }
}
)*
}
}
numeric_semigroup_imps!(i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64);
macro_rules! numeric_product_semigroup_imps {
($($tr:ty),*) => {
$(
impl Semigroup for Product<$tr> {
fn combine(&self, other: &Self) -> Self {
let Product(x) = *self;
let Product(y) = *other;
Product(x * y)
}
}
)*
}
}
numeric_product_semigroup_imps!(i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64);
impl<T> Semigroup for Option<T>
where
T: Semigroup + Clone,
{
fn combine(&self, other: &Self) -> Self {
match (self, other) {
(Some(ref v), Some(ref v_other)) => Some(v.combine(v_other)),
(Some(_), _) => self.clone(),
_ => other.clone(),
}
}
}
#[cfg(feature = "std")]
impl<T: Semigroup> Semigroup for Box<T> {
fn combine(&self, other: &Self) -> Self {
Box::new(self.deref().combine(other.deref()))
}
}
#[cfg(feature = "std")]
impl Semigroup for String {
fn combine(&self, other: &Self) -> Self {
let mut cloned = self.clone();
cloned.push_str(other);
cloned
}
}
#[cfg(feature = "std")]
impl<T: Clone> Semigroup for Vec<T> {
fn combine(&self, other: &Self) -> Self {
let mut v = self.clone();
v.extend_from_slice(other);
v
}
}
impl<T> Semigroup for Cell<T>
where
T: Semigroup + Copy,
{
fn combine(&self, other: &Self) -> Self {
Cell::new(self.get().combine(&(other.get())))
}
}
impl<T: Semigroup> Semigroup for RefCell<T> {
fn combine(&self, other: &Self) -> Self {
let self_b = self.borrow();
let other_b = other.borrow();
RefCell::new(self_b.deref().combine(other_b.deref()))
}
}
#[cfg(feature = "std")]
impl<T> Semigroup for HashSet<T>
where
T: Eq + Hash + Clone,
{
fn combine(&self, other: &Self) -> Self {
self.union(other).cloned().collect()
}
}
#[cfg(feature = "std")]
impl<K, V> Semigroup for HashMap<K, V>
where
K: Eq + Hash + Clone,
V: Semigroup + Clone,
{
fn combine(&self, other: &Self) -> Self {
let mut h: HashMap<K, V> = self.clone();
for (k, v) in other {
let k_clone = k.clone();
match h.entry(k_clone) {
Entry::Occupied(o) => {
let existing = o.into_mut();
let comb = existing.combine(v);
*existing = comb;
}
Entry::Vacant(o) => {
o.insert(v.clone());
}
}
}
h
}
}
impl<T> Semigroup for Max<T>
where
T: Ord + Clone,
{
fn combine(&self, other: &Self) -> Self {
let x = self.0.clone();
let y = other.0.clone();
match x.cmp(&y) {
Ordering::Less => Max(y),
_ => Max(x),
}
}
}
impl<T> Semigroup for Min<T>
where
T: Ord + Clone,
{
fn combine(&self, other: &Self) -> Self {
let x = self.0.clone();
let y = other.0.clone();
match x.cmp(&y) {
Ordering::Less => Min(x),
_ => Min(y),
}
}
}
// Deriving for all BitAnds sucks because we are then bound on ::Output, which may not be the same type
macro_rules! simple_all_impls {
($($tr:ty)*) => {
$(
impl Semigroup for All<$tr> {
fn combine(&self, other: &Self) -> Self {
let x = self.0;
let y = other.0;
All(x.bitand(y))
}
}
)*
}
}
simple_all_impls! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
macro_rules! simple_any_impls {
($($tr:ty)*) => {
$(
impl Semigroup for Any<$tr> {
fn combine(&self, other: &Self) -> Self {
let x = self.0;
let y = other.0;
Any(x.bitor(y))
}
}
)*
}
}
simple_any_impls! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
macro_rules! tuple_impls {
() => {}; // no more
(($idx:tt => $typ:ident), $( ($nidx:tt => $ntyp:ident), )*) => {
// Invoke recursive reversal of list that ends in the macro expansion implementation
// of the reversed list
//
tuple_impls!([($idx, $typ);] $( ($nidx => $ntyp), )*);
tuple_impls!($( ($nidx => $ntyp), )*); // invoke macro on tail
};
// ([accumulatedList], listToReverse); recursively calls tuple_impls until the list to reverse
// + is empty (see next pattern)
//
([$(($accIdx: tt, $accTyp: ident);)+] ($idx:tt => $typ:ident), $( ($nidx:tt => $ntyp:ident), )*) => {
tuple_impls!([($idx, $typ); $(($accIdx, $accTyp); )*] $( ($nidx => $ntyp), ) *);
};
// Finally expand into our implementation
([($idx:tt, $typ:ident); $( ($nidx:tt, $ntyp:ident); )*]) => {
impl<$typ: Semigroup, $( $ntyp: Semigroup),*> Semigroup for ($typ, $( $ntyp ),*) {
fn combine(&self, other: &Self) -> Self {
(self.$idx.combine(&other.$idx), $(self.$nidx.combine(&other.$nidx), )*)
}
}
}
}
tuple_impls! {
(20 => U),
(19 => T),
(18 => S),
(17 => R),
(16 => Q),
(15 => P),
(14 => O),
(13 => N),
(12 => M),
(11 => L),
(10 => K),
(9 => J),
(8 => I),
(7 => H),
(6 => G),
(5 => F),
(4 => E),
(3 => D),
(2 => C),
(1 => B),
(0 => A),
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! semigroup_tests {
($($name:ident, $comb: expr => $expected: expr, $tr:ty)+) => {
$(
#[test]
fn $name() {
let r: $tr = $comb;
assert_eq!(r, $expected)
}
)*
}
}
semigroup_tests! {
test_i8, 1.combine(&2) => 3, i8
test_product_i8, Product(1).combine(&Product(2)) => Product(2), Product<i8>
test_i16, 1.combine(&2) => 3, i16
test_i32, 1.combine(&2) => 3, i32
test_u8, 1.combine(&2) => 3, u8
test_u16, 1.combine(&2) => 3, u16
test_u32, 1.combine(&2) => 3, u32
test_usize, 1.combine(&2) => 3, usize
test_isize, 1.combine(&2) => 3, isize
test_f32, 1f32.combine(&2f32) => 3f32, f32
test_f64, 1f64.combine(&2f64) => 3f64, f64
test_option_i16, Some(1).combine(&Some(2)) => Some(3), Option<i16>
test_option_i16_none1, None.combine(&Some(2)) => Some(2), Option<i16>
test_option_i16_none2, Some(2).combine(&None) => Some(2), Option<i16>
}
#[test]
#[cfg(feature = "std")]
fn test_string() {
let v1 = String::from("Hello");
let v2 = String::from(" world");
assert_eq!(v1.combine(&v2), "Hello world")
}
#[test]
#[cfg(feature = "std")]
fn test_vec_i32() {
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];
assert_eq!(v1.combine(&v2), vec![1, 2, 3, 4, 5, 6])
}
#[test]
fn test_refcell() {
let v1 = RefCell::new(1);
let v2 = RefCell::new(2);
assert_eq!(v1.combine(&v2), RefCell::new(3))
}
#[test]
#[cfg(feature = "std")]
fn test_hashset() {
let mut v1 = HashSet::new();
v1.insert(1);
v1.insert(2);
assert!(!v1.contains(&3));
let mut v2 = HashSet::new();
v2.insert(3);
v2.insert(4);
assert!(!v2.contains(&1));
let mut expected = HashSet::new();
expected.insert(1);
expected.insert(2);
expected.insert(3);
expected.insert(4);
assert_eq!(v1.combine(&v2), expected)
}
#[test]
#[cfg(feature = "std")]
fn test_tuple() {
let t1 = (1, 2.5f32, String::from("hi"), Some(3));
let t2 = (1, 2.5f32, String::from(" world"), None);
let expected = (2, 5.0f32, String::from("hi world"), Some(3));
assert_eq!(t1.combine(&t2), expected)
}
#[test]
fn test_max() {
assert_eq!(Max(1).combine(&Max(2)), Max(2));
let v = [Max(1), Max(2), Max(3)];
assert_eq!(combine_all_option(&v), Some(Max(3)));
}
#[test]
fn test_min() {
assert_eq!(Min(1).combine(&Min(2)), Min(1));
let v = [Min(1), Min(2), Min(3)];
assert_eq!(combine_all_option(&v), Some(Min(1)));
}
#[test]
fn test_all() {
assert_eq!(All(3).combine(&All(5)), All(1));
assert_eq!(All(true).combine(&All(false)), All(false));
}
#[test]
fn test_any()
|
#[test]
#[cfg(feature = "std")]
fn test_hashmap() {
let mut v1: HashMap<i32, Option<String>> = HashMap::new();
v1.insert(1, Some("Hello".to_owned()));
v1.insert(2, Some("Goodbye".to_owned()));
v1.insert(4, None);
let mut v2: HashMap<i32, Option<String>> = HashMap::new();
v2.insert(1, Some(" World".to_owned()));
v2.insert(4, Some("Nope".to_owned()));
let mut expected = HashMap::new();
expected.insert(1, Some("Hello World".to_owned()));
expected.insert(2, Some("Goodbye".to_owned()));
expected.insert(4, Some("Nope".to_owned()));
assert_eq!(v1.combine(&v2), expected)
}
#[test]
fn test_combine_all_option() {
let v1 = [1, 2, 3];
assert_eq!(combine_all_option(&v1), Some(6));
let v2 = [Some(1), Some(2), Some(3)];
assert_eq!(combine_all_option(&v2), Some(Some(6)));
}
#[test]
fn test_combine_n() {
assert_eq!(combine_n(&1, 3), 3);
assert_eq!(combine_n(&2, 1), 2);
assert_eq!(combine_n(&Some(2), 4), Some(8));
}
#[test]
#[cfg(feature = "std")]
fn test_combine_hlist() {
let h1 = hlist![Some(1), 3.3, 53i64, "hello".to_owned()];
let h2 = hlist![Some(2), 1.2, 1i64, " world".to_owned()];
let h3 = hlist![Some(3), 4.5, 54, "hello world".to_owned()];
assert_eq!(h1.combine(&h2), h3)
}
}
|
{
assert_eq!(Any(3).combine(&Any(5)), Any(7));
assert_eq!(Any(true).combine(&Any(false)), Any(true));
}
|
identifier_body
|
semigroup.rs
|
//! Module for holding the Semigroup typeclass definition and typeclass instances
//!
//! You can, for example, combine tuples.
#![cfg_attr(
feature = "std",
doc = r#"
# Examples
```
#[macro_use]
extern crate frunk;
# fn main() {
use frunk::Semigroup;
let t1 = (1, 2.5f32, String::from("hi"), Some(3));
let t2 = (1, 2.5f32, String::from(" world"), None);
let expected = (2, 5.0f32, String::from("hi world"), Some(3));
assert_eq!(t1.combine(&t2), expected);
// ultimately, the Tuple-based Semigroup implementations are only available for a maximum of
// 26 elements. If you need more, use HList, which is has no such limit.
let h1 = hlist![1, 3.3, 53i64];
let h2 = hlist![2, 1.2, 1i64];
let h3 = hlist![3, 4.5, 54];
assert_eq!(h1.combine(&h2), h3)
# }
```"#
)]
use frunk_core::hlist::*;
use std::cell::*;
use std::cmp::Ordering;
#[cfg(feature = "std")]
use std::collections::hash_map::Entry;
#[cfg(feature = "std")]
use std::collections::{HashMap, HashSet};
#[cfg(feature = "std")]
use std::hash::Hash;
use std::ops::{BitAnd, BitOr, Deref};
/// Wrapper type for types that are ordered and can have a Max combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Max<T: Ord>(pub T);
/// Wrapper type for types that are ordered and can have a Min combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Min<T: Ord>(pub T);
/// Wrapper type for types that can have a Product combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Product<T>(pub T);
/// Wrapper type for boolean that acts as a bitwise && combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct All<T>(pub T);
/// Wrapper type for boolean that acts as a bitwise || combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Any<T>(pub T);
/// A Semigroup is a class of thing that has a definable combine operation
pub trait Semigroup {
/// Associative operation taking which combines two values.
///
/// # Examples
///
/// ```
/// use frunk::Semigroup;
///
/// assert_eq!(Some(1).combine(&Some(2)), Some(3))
/// ```
fn combine(&self, other: &Self) -> Self;
}
/// Allow the combination of any two HLists having the same structure
/// if all of the sub-element types are also Semiups
impl<H: Semigroup, T: HList + Semigroup> Semigroup for HCons<H, T> {
fn combine(&self, other: &Self) -> Self {
self.tail
.combine(&other.tail)
.prepend(self.head.combine(&other.head))
}
}
/// Since () + () = (), the same is true for HNil
impl Semigroup for HNil {
fn combine(&self, _: &Self) -> Self {
*self
}
}
/// Return this combined with itself `n` times.
pub fn combine_n<T>(o: &T, times: u32) -> T
where
T: Semigroup + Clone,
{
let mut x = o.clone();
// note: range is non-inclusive in the upper bound
for _ in 1..times {
x = o.combine(&x);
}
x
}
/// Given a sequence of `xs`, combine them and return the total
///
/// If the sequence is empty, returns None. Otherwise, returns Some(total).
///
/// # Examples
///
/// ```
/// use frunk::semigroup::combine_all_option;
///
/// let v1 = &vec![1, 2, 3];
/// assert_eq!(combine_all_option(v1), Some(6));
///
/// let v2: Vec<i16> = Vec::new(); // empty!
/// assert_eq!(combine_all_option(&v2), None);
/// ```
pub fn combine_all_option<T>(xs: &[T]) -> Option<T>
where
T: Semigroup + Clone,
{
xs.first()
.map(|head| xs[1..].iter().fold(head.clone(), |a, b| a.combine(b)))
}
macro_rules! numeric_semigroup_imps {
($($tr:ty),*) => {
$(
impl Semigroup for $tr {
fn combine(&self, other: &Self) -> Self { self + other }
}
)*
}
}
numeric_semigroup_imps!(i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64);
macro_rules! numeric_product_semigroup_imps {
($($tr:ty),*) => {
$(
impl Semigroup for Product<$tr> {
fn combine(&self, other: &Self) -> Self {
let Product(x) = *self;
let Product(y) = *other;
Product(x * y)
}
}
)*
}
}
numeric_product_semigroup_imps!(i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64);
impl<T> Semigroup for Option<T>
where
T: Semigroup + Clone,
{
fn combine(&self, other: &Self) -> Self {
match (self, other) {
(Some(ref v), Some(ref v_other)) => Some(v.combine(v_other)),
(Some(_), _) => self.clone(),
_ => other.clone(),
}
}
}
#[cfg(feature = "std")]
impl<T: Semigroup> Semigroup for Box<T> {
fn combine(&self, other: &Self) -> Self {
Box::new(self.deref().combine(other.deref()))
}
}
#[cfg(feature = "std")]
impl Semigroup for String {
fn combine(&self, other: &Self) -> Self {
let mut cloned = self.clone();
cloned.push_str(other);
cloned
}
}
#[cfg(feature = "std")]
impl<T: Clone> Semigroup for Vec<T> {
fn combine(&self, other: &Self) -> Self {
let mut v = self.clone();
v.extend_from_slice(other);
v
}
}
impl<T> Semigroup for Cell<T>
where
T: Semigroup + Copy,
{
fn combine(&self, other: &Self) -> Self {
Cell::new(self.get().combine(&(other.get())))
}
}
impl<T: Semigroup> Semigroup for RefCell<T> {
fn combine(&self, other: &Self) -> Self {
let self_b = self.borrow();
let other_b = other.borrow();
RefCell::new(self_b.deref().combine(other_b.deref()))
}
}
#[cfg(feature = "std")]
impl<T> Semigroup for HashSet<T>
where
T: Eq + Hash + Clone,
{
fn combine(&self, other: &Self) -> Self {
self.union(other).cloned().collect()
}
}
#[cfg(feature = "std")]
impl<K, V> Semigroup for HashMap<K, V>
where
K: Eq + Hash + Clone,
V: Semigroup + Clone,
{
fn combine(&self, other: &Self) -> Self {
let mut h: HashMap<K, V> = self.clone();
for (k, v) in other {
let k_clone = k.clone();
match h.entry(k_clone) {
Entry::Occupied(o) => {
let existing = o.into_mut();
let comb = existing.combine(v);
*existing = comb;
}
Entry::Vacant(o) => {
o.insert(v.clone());
}
}
}
h
}
}
impl<T> Semigroup for Max<T>
where
T: Ord + Clone,
{
fn combine(&self, other: &Self) -> Self {
let x = self.0.clone();
let y = other.0.clone();
match x.cmp(&y) {
Ordering::Less => Max(y),
_ => Max(x),
}
}
}
impl<T> Semigroup for Min<T>
where
T: Ord + Clone,
{
fn combine(&self, other: &Self) -> Self {
let x = self.0.clone();
let y = other.0.clone();
match x.cmp(&y) {
Ordering::Less => Min(x),
_ => Min(y),
}
}
}
// Deriving for all BitAnds sucks because we are then bound on ::Output, which may not be the same type
macro_rules! simple_all_impls {
($($tr:ty)*) => {
$(
impl Semigroup for All<$tr> {
|
}
)*
}
}
simple_all_impls! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
macro_rules! simple_any_impls {
($($tr:ty)*) => {
$(
impl Semigroup for Any<$tr> {
fn combine(&self, other: &Self) -> Self {
let x = self.0;
let y = other.0;
Any(x.bitor(y))
}
}
)*
}
}
simple_any_impls! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
macro_rules! tuple_impls {
() => {}; // no more
(($idx:tt => $typ:ident), $( ($nidx:tt => $ntyp:ident), )*) => {
// Invoke recursive reversal of list that ends in the macro expansion implementation
// of the reversed list
//
tuple_impls!([($idx, $typ);] $( ($nidx => $ntyp), )*);
tuple_impls!($( ($nidx => $ntyp), )*); // invoke macro on tail
};
// ([accumulatedList], listToReverse); recursively calls tuple_impls until the list to reverse
// + is empty (see next pattern)
//
([$(($accIdx: tt, $accTyp: ident);)+] ($idx:tt => $typ:ident), $( ($nidx:tt => $ntyp:ident), )*) => {
tuple_impls!([($idx, $typ); $(($accIdx, $accTyp); )*] $( ($nidx => $ntyp), ) *);
};
// Finally expand into our implementation
([($idx:tt, $typ:ident); $( ($nidx:tt, $ntyp:ident); )*]) => {
impl<$typ: Semigroup, $( $ntyp: Semigroup),*> Semigroup for ($typ, $( $ntyp ),*) {
fn combine(&self, other: &Self) -> Self {
(self.$idx.combine(&other.$idx), $(self.$nidx.combine(&other.$nidx), )*)
}
}
}
}
tuple_impls! {
(20 => U),
(19 => T),
(18 => S),
(17 => R),
(16 => Q),
(15 => P),
(14 => O),
(13 => N),
(12 => M),
(11 => L),
(10 => K),
(9 => J),
(8 => I),
(7 => H),
(6 => G),
(5 => F),
(4 => E),
(3 => D),
(2 => C),
(1 => B),
(0 => A),
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! semigroup_tests {
($($name:ident, $comb: expr => $expected: expr, $tr:ty)+) => {
$(
#[test]
fn $name() {
let r: $tr = $comb;
assert_eq!(r, $expected)
}
)*
}
}
semigroup_tests! {
test_i8, 1.combine(&2) => 3, i8
test_product_i8, Product(1).combine(&Product(2)) => Product(2), Product<i8>
test_i16, 1.combine(&2) => 3, i16
test_i32, 1.combine(&2) => 3, i32
test_u8, 1.combine(&2) => 3, u8
test_u16, 1.combine(&2) => 3, u16
test_u32, 1.combine(&2) => 3, u32
test_usize, 1.combine(&2) => 3, usize
test_isize, 1.combine(&2) => 3, isize
test_f32, 1f32.combine(&2f32) => 3f32, f32
test_f64, 1f64.combine(&2f64) => 3f64, f64
test_option_i16, Some(1).combine(&Some(2)) => Some(3), Option<i16>
test_option_i16_none1, None.combine(&Some(2)) => Some(2), Option<i16>
test_option_i16_none2, Some(2).combine(&None) => Some(2), Option<i16>
}
#[test]
#[cfg(feature = "std")]
fn test_string() {
let v1 = String::from("Hello");
let v2 = String::from(" world");
assert_eq!(v1.combine(&v2), "Hello world")
}
#[test]
#[cfg(feature = "std")]
fn test_vec_i32() {
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];
assert_eq!(v1.combine(&v2), vec![1, 2, 3, 4, 5, 6])
}
#[test]
fn test_refcell() {
let v1 = RefCell::new(1);
let v2 = RefCell::new(2);
assert_eq!(v1.combine(&v2), RefCell::new(3))
}
#[test]
#[cfg(feature = "std")]
fn test_hashset() {
let mut v1 = HashSet::new();
v1.insert(1);
v1.insert(2);
assert!(!v1.contains(&3));
let mut v2 = HashSet::new();
v2.insert(3);
v2.insert(4);
assert!(!v2.contains(&1));
let mut expected = HashSet::new();
expected.insert(1);
expected.insert(2);
expected.insert(3);
expected.insert(4);
assert_eq!(v1.combine(&v2), expected)
}
#[test]
#[cfg(feature = "std")]
fn test_tuple() {
let t1 = (1, 2.5f32, String::from("hi"), Some(3));
let t2 = (1, 2.5f32, String::from(" world"), None);
let expected = (2, 5.0f32, String::from("hi world"), Some(3));
assert_eq!(t1.combine(&t2), expected)
}
#[test]
fn test_max() {
assert_eq!(Max(1).combine(&Max(2)), Max(2));
let v = [Max(1), Max(2), Max(3)];
assert_eq!(combine_all_option(&v), Some(Max(3)));
}
#[test]
fn test_min() {
assert_eq!(Min(1).combine(&Min(2)), Min(1));
let v = [Min(1), Min(2), Min(3)];
assert_eq!(combine_all_option(&v), Some(Min(1)));
}
#[test]
fn test_all() {
assert_eq!(All(3).combine(&All(5)), All(1));
assert_eq!(All(true).combine(&All(false)), All(false));
}
#[test]
fn test_any() {
assert_eq!(Any(3).combine(&Any(5)), Any(7));
assert_eq!(Any(true).combine(&Any(false)), Any(true));
}
#[test]
#[cfg(feature = "std")]
fn test_hashmap() {
let mut v1: HashMap<i32, Option<String>> = HashMap::new();
v1.insert(1, Some("Hello".to_owned()));
v1.insert(2, Some("Goodbye".to_owned()));
v1.insert(4, None);
let mut v2: HashMap<i32, Option<String>> = HashMap::new();
v2.insert(1, Some(" World".to_owned()));
v2.insert(4, Some("Nope".to_owned()));
let mut expected = HashMap::new();
expected.insert(1, Some("Hello World".to_owned()));
expected.insert(2, Some("Goodbye".to_owned()));
expected.insert(4, Some("Nope".to_owned()));
assert_eq!(v1.combine(&v2), expected)
}
#[test]
fn test_combine_all_option() {
let v1 = [1, 2, 3];
assert_eq!(combine_all_option(&v1), Some(6));
let v2 = [Some(1), Some(2), Some(3)];
assert_eq!(combine_all_option(&v2), Some(Some(6)));
}
#[test]
fn test_combine_n() {
assert_eq!(combine_n(&1, 3), 3);
assert_eq!(combine_n(&2, 1), 2);
assert_eq!(combine_n(&Some(2), 4), Some(8));
}
#[test]
#[cfg(feature = "std")]
fn test_combine_hlist() {
let h1 = hlist![Some(1), 3.3, 53i64, "hello".to_owned()];
let h2 = hlist![Some(2), 1.2, 1i64, " world".to_owned()];
let h3 = hlist![Some(3), 4.5, 54, "hello world".to_owned()];
assert_eq!(h1.combine(&h2), h3)
}
}
|
fn combine(&self, other: &Self) -> Self {
let x = self.0;
let y = other.0;
All(x.bitand(y))
}
|
random_line_split
|
semigroup.rs
|
//! Module for holding the Semigroup typeclass definition and typeclass instances
//!
//! You can, for example, combine tuples.
#![cfg_attr(
feature = "std",
doc = r#"
# Examples
```
#[macro_use]
extern crate frunk;
# fn main() {
use frunk::Semigroup;
let t1 = (1, 2.5f32, String::from("hi"), Some(3));
let t2 = (1, 2.5f32, String::from(" world"), None);
let expected = (2, 5.0f32, String::from("hi world"), Some(3));
assert_eq!(t1.combine(&t2), expected);
// ultimately, the Tuple-based Semigroup implementations are only available for a maximum of
// 26 elements. If you need more, use HList, which is has no such limit.
let h1 = hlist![1, 3.3, 53i64];
let h2 = hlist![2, 1.2, 1i64];
let h3 = hlist![3, 4.5, 54];
assert_eq!(h1.combine(&h2), h3)
# }
```"#
)]
use frunk_core::hlist::*;
use std::cell::*;
use std::cmp::Ordering;
#[cfg(feature = "std")]
use std::collections::hash_map::Entry;
#[cfg(feature = "std")]
use std::collections::{HashMap, HashSet};
#[cfg(feature = "std")]
use std::hash::Hash;
use std::ops::{BitAnd, BitOr, Deref};
/// Wrapper type for types that are ordered and can have a Max combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Max<T: Ord>(pub T);
/// Wrapper type for types that are ordered and can have a Min combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Min<T: Ord>(pub T);
/// Wrapper type for types that can have a Product combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Product<T>(pub T);
/// Wrapper type for boolean that acts as a bitwise && combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct
|
<T>(pub T);
/// Wrapper type for boolean that acts as a bitwise || combination
#[derive(PartialEq, Debug, Eq, Clone, Copy, PartialOrd, Ord, Hash)]
pub struct Any<T>(pub T);
/// A Semigroup is a class of thing that has a definable combine operation
pub trait Semigroup {
/// Associative operation taking which combines two values.
///
/// # Examples
///
/// ```
/// use frunk::Semigroup;
///
/// assert_eq!(Some(1).combine(&Some(2)), Some(3))
/// ```
fn combine(&self, other: &Self) -> Self;
}
/// Allow the combination of any two HLists having the same structure
/// if all of the sub-element types are also Semiups
impl<H: Semigroup, T: HList + Semigroup> Semigroup for HCons<H, T> {
fn combine(&self, other: &Self) -> Self {
self.tail
.combine(&other.tail)
.prepend(self.head.combine(&other.head))
}
}
/// Since () + () = (), the same is true for HNil
impl Semigroup for HNil {
fn combine(&self, _: &Self) -> Self {
*self
}
}
/// Return this combined with itself `n` times.
pub fn combine_n<T>(o: &T, times: u32) -> T
where
T: Semigroup + Clone,
{
let mut x = o.clone();
// note: range is non-inclusive in the upper bound
for _ in 1..times {
x = o.combine(&x);
}
x
}
/// Given a sequence of `xs`, combine them and return the total
///
/// If the sequence is empty, returns None. Otherwise, returns Some(total).
///
/// # Examples
///
/// ```
/// use frunk::semigroup::combine_all_option;
///
/// let v1 = &vec![1, 2, 3];
/// assert_eq!(combine_all_option(v1), Some(6));
///
/// let v2: Vec<i16> = Vec::new(); // empty!
/// assert_eq!(combine_all_option(&v2), None);
/// ```
pub fn combine_all_option<T>(xs: &[T]) -> Option<T>
where
T: Semigroup + Clone,
{
xs.first()
.map(|head| xs[1..].iter().fold(head.clone(), |a, b| a.combine(b)))
}
macro_rules! numeric_semigroup_imps {
($($tr:ty),*) => {
$(
impl Semigroup for $tr {
fn combine(&self, other: &Self) -> Self { self + other }
}
)*
}
}
numeric_semigroup_imps!(i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64);
macro_rules! numeric_product_semigroup_imps {
($($tr:ty),*) => {
$(
impl Semigroup for Product<$tr> {
fn combine(&self, other: &Self) -> Self {
let Product(x) = *self;
let Product(y) = *other;
Product(x * y)
}
}
)*
}
}
numeric_product_semigroup_imps!(i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64);
impl<T> Semigroup for Option<T>
where
T: Semigroup + Clone,
{
fn combine(&self, other: &Self) -> Self {
match (self, other) {
(Some(ref v), Some(ref v_other)) => Some(v.combine(v_other)),
(Some(_), _) => self.clone(),
_ => other.clone(),
}
}
}
#[cfg(feature = "std")]
impl<T: Semigroup> Semigroup for Box<T> {
fn combine(&self, other: &Self) -> Self {
Box::new(self.deref().combine(other.deref()))
}
}
#[cfg(feature = "std")]
impl Semigroup for String {
fn combine(&self, other: &Self) -> Self {
let mut cloned = self.clone();
cloned.push_str(other);
cloned
}
}
#[cfg(feature = "std")]
impl<T: Clone> Semigroup for Vec<T> {
fn combine(&self, other: &Self) -> Self {
let mut v = self.clone();
v.extend_from_slice(other);
v
}
}
impl<T> Semigroup for Cell<T>
where
T: Semigroup + Copy,
{
fn combine(&self, other: &Self) -> Self {
Cell::new(self.get().combine(&(other.get())))
}
}
impl<T: Semigroup> Semigroup for RefCell<T> {
fn combine(&self, other: &Self) -> Self {
let self_b = self.borrow();
let other_b = other.borrow();
RefCell::new(self_b.deref().combine(other_b.deref()))
}
}
#[cfg(feature = "std")]
impl<T> Semigroup for HashSet<T>
where
T: Eq + Hash + Clone,
{
fn combine(&self, other: &Self) -> Self {
self.union(other).cloned().collect()
}
}
#[cfg(feature = "std")]
impl<K, V> Semigroup for HashMap<K, V>
where
K: Eq + Hash + Clone,
V: Semigroup + Clone,
{
fn combine(&self, other: &Self) -> Self {
let mut h: HashMap<K, V> = self.clone();
for (k, v) in other {
let k_clone = k.clone();
match h.entry(k_clone) {
Entry::Occupied(o) => {
let existing = o.into_mut();
let comb = existing.combine(v);
*existing = comb;
}
Entry::Vacant(o) => {
o.insert(v.clone());
}
}
}
h
}
}
impl<T> Semigroup for Max<T>
where
T: Ord + Clone,
{
fn combine(&self, other: &Self) -> Self {
let x = self.0.clone();
let y = other.0.clone();
match x.cmp(&y) {
Ordering::Less => Max(y),
_ => Max(x),
}
}
}
impl<T> Semigroup for Min<T>
where
T: Ord + Clone,
{
fn combine(&self, other: &Self) -> Self {
let x = self.0.clone();
let y = other.0.clone();
match x.cmp(&y) {
Ordering::Less => Min(x),
_ => Min(y),
}
}
}
// Deriving for all BitAnds sucks because we are then bound on ::Output, which may not be the same type
macro_rules! simple_all_impls {
($($tr:ty)*) => {
$(
impl Semigroup for All<$tr> {
fn combine(&self, other: &Self) -> Self {
let x = self.0;
let y = other.0;
All(x.bitand(y))
}
}
)*
}
}
simple_all_impls! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
macro_rules! simple_any_impls {
($($tr:ty)*) => {
$(
impl Semigroup for Any<$tr> {
fn combine(&self, other: &Self) -> Self {
let x = self.0;
let y = other.0;
Any(x.bitor(y))
}
}
)*
}
}
simple_any_impls! { bool usize u8 u16 u32 u64 isize i8 i16 i32 i64 }
macro_rules! tuple_impls {
() => {}; // no more
(($idx:tt => $typ:ident), $( ($nidx:tt => $ntyp:ident), )*) => {
// Invoke recursive reversal of list that ends in the macro expansion implementation
// of the reversed list
//
tuple_impls!([($idx, $typ);] $( ($nidx => $ntyp), )*);
tuple_impls!($( ($nidx => $ntyp), )*); // invoke macro on tail
};
// ([accumulatedList], listToReverse); recursively calls tuple_impls until the list to reverse
// + is empty (see next pattern)
//
([$(($accIdx: tt, $accTyp: ident);)+] ($idx:tt => $typ:ident), $( ($nidx:tt => $ntyp:ident), )*) => {
tuple_impls!([($idx, $typ); $(($accIdx, $accTyp); )*] $( ($nidx => $ntyp), ) *);
};
// Finally expand into our implementation
([($idx:tt, $typ:ident); $( ($nidx:tt, $ntyp:ident); )*]) => {
impl<$typ: Semigroup, $( $ntyp: Semigroup),*> Semigroup for ($typ, $( $ntyp ),*) {
fn combine(&self, other: &Self) -> Self {
(self.$idx.combine(&other.$idx), $(self.$nidx.combine(&other.$nidx), )*)
}
}
}
}
tuple_impls! {
(20 => U),
(19 => T),
(18 => S),
(17 => R),
(16 => Q),
(15 => P),
(14 => O),
(13 => N),
(12 => M),
(11 => L),
(10 => K),
(9 => J),
(8 => I),
(7 => H),
(6 => G),
(5 => F),
(4 => E),
(3 => D),
(2 => C),
(1 => B),
(0 => A),
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! semigroup_tests {
($($name:ident, $comb: expr => $expected: expr, $tr:ty)+) => {
$(
#[test]
fn $name() {
let r: $tr = $comb;
assert_eq!(r, $expected)
}
)*
}
}
semigroup_tests! {
test_i8, 1.combine(&2) => 3, i8
test_product_i8, Product(1).combine(&Product(2)) => Product(2), Product<i8>
test_i16, 1.combine(&2) => 3, i16
test_i32, 1.combine(&2) => 3, i32
test_u8, 1.combine(&2) => 3, u8
test_u16, 1.combine(&2) => 3, u16
test_u32, 1.combine(&2) => 3, u32
test_usize, 1.combine(&2) => 3, usize
test_isize, 1.combine(&2) => 3, isize
test_f32, 1f32.combine(&2f32) => 3f32, f32
test_f64, 1f64.combine(&2f64) => 3f64, f64
test_option_i16, Some(1).combine(&Some(2)) => Some(3), Option<i16>
test_option_i16_none1, None.combine(&Some(2)) => Some(2), Option<i16>
test_option_i16_none2, Some(2).combine(&None) => Some(2), Option<i16>
}
#[test]
#[cfg(feature = "std")]
fn test_string() {
let v1 = String::from("Hello");
let v2 = String::from(" world");
assert_eq!(v1.combine(&v2), "Hello world")
}
#[test]
#[cfg(feature = "std")]
fn test_vec_i32() {
let v1 = vec![1, 2, 3];
let v2 = vec![4, 5, 6];
assert_eq!(v1.combine(&v2), vec![1, 2, 3, 4, 5, 6])
}
#[test]
fn test_refcell() {
let v1 = RefCell::new(1);
let v2 = RefCell::new(2);
assert_eq!(v1.combine(&v2), RefCell::new(3))
}
#[test]
#[cfg(feature = "std")]
fn test_hashset() {
let mut v1 = HashSet::new();
v1.insert(1);
v1.insert(2);
assert!(!v1.contains(&3));
let mut v2 = HashSet::new();
v2.insert(3);
v2.insert(4);
assert!(!v2.contains(&1));
let mut expected = HashSet::new();
expected.insert(1);
expected.insert(2);
expected.insert(3);
expected.insert(4);
assert_eq!(v1.combine(&v2), expected)
}
#[test]
#[cfg(feature = "std")]
fn test_tuple() {
let t1 = (1, 2.5f32, String::from("hi"), Some(3));
let t2 = (1, 2.5f32, String::from(" world"), None);
let expected = (2, 5.0f32, String::from("hi world"), Some(3));
assert_eq!(t1.combine(&t2), expected)
}
#[test]
fn test_max() {
assert_eq!(Max(1).combine(&Max(2)), Max(2));
let v = [Max(1), Max(2), Max(3)];
assert_eq!(combine_all_option(&v), Some(Max(3)));
}
#[test]
fn test_min() {
assert_eq!(Min(1).combine(&Min(2)), Min(1));
let v = [Min(1), Min(2), Min(3)];
assert_eq!(combine_all_option(&v), Some(Min(1)));
}
#[test]
fn test_all() {
assert_eq!(All(3).combine(&All(5)), All(1));
assert_eq!(All(true).combine(&All(false)), All(false));
}
#[test]
fn test_any() {
assert_eq!(Any(3).combine(&Any(5)), Any(7));
assert_eq!(Any(true).combine(&Any(false)), Any(true));
}
#[test]
#[cfg(feature = "std")]
fn test_hashmap() {
let mut v1: HashMap<i32, Option<String>> = HashMap::new();
v1.insert(1, Some("Hello".to_owned()));
v1.insert(2, Some("Goodbye".to_owned()));
v1.insert(4, None);
let mut v2: HashMap<i32, Option<String>> = HashMap::new();
v2.insert(1, Some(" World".to_owned()));
v2.insert(4, Some("Nope".to_owned()));
let mut expected = HashMap::new();
expected.insert(1, Some("Hello World".to_owned()));
expected.insert(2, Some("Goodbye".to_owned()));
expected.insert(4, Some("Nope".to_owned()));
assert_eq!(v1.combine(&v2), expected)
}
#[test]
fn test_combine_all_option() {
let v1 = [1, 2, 3];
assert_eq!(combine_all_option(&v1), Some(6));
let v2 = [Some(1), Some(2), Some(3)];
assert_eq!(combine_all_option(&v2), Some(Some(6)));
}
#[test]
fn test_combine_n() {
assert_eq!(combine_n(&1, 3), 3);
assert_eq!(combine_n(&2, 1), 2);
assert_eq!(combine_n(&Some(2), 4), Some(8));
}
#[test]
#[cfg(feature = "std")]
fn test_combine_hlist() {
let h1 = hlist![Some(1), 3.3, 53i64, "hello".to_owned()];
let h2 = hlist![Some(2), 1.2, 1i64, " world".to_owned()];
let h3 = hlist![Some(3), 4.5, 54, "hello world".to_owned()];
assert_eq!(h1.combine(&h2), h3)
}
}
|
All
|
identifier_name
|
count.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Peekable;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
|
}
}
// fn peekable(self) -> Peekable<Self> where Self: Sized {
// Peekable{iter: self, peeked: None}
// }
// fn count(self) -> usize where Self: Sized {
// // Might overflow.
// self.fold(0, |cnt, _| cnt + 1)
// }
}
}
}
type T = i32;
Iterator_impl!(T);
// impl<I: Iterator> Iterator for Peekable<I> {
// type Item = I::Item;
//
// #[inline]
// fn next(&mut self) -> Option<I::Item> {
// match self.peeked {
// Some(_) => self.peeked.take(),
// None => self.iter.next(),
// }
// }
//
// #[inline]
// fn count(self) -> usize {
// (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
// }
//
// #[inline]
// fn nth(&mut self, n: usize) -> Option<I::Item> {
// match self.peeked {
// Some(_) if n == 0 => self.peeked.take(),
// Some(_) => {
// self.peeked = None;
// self.iter.nth(n-1)
// },
// None => self.iter.nth(n)
// }
// }
//
// #[inline]
// fn last(self) -> Option<I::Item> {
// self.iter.last().or(self.peeked)
// }
//
// #[inline]
// fn size_hint(&self) -> (usize, Option<usize>) {
// let (lo, hi) = self.iter.size_hint();
// if self.peeked.is_some() {
// let lo = lo.saturating_add(1);
// let hi = hi.and_then(|x| x.checked_add(1));
// (lo, hi)
// } else {
// (lo, hi)
// }
// }
// }
#[test]
fn count_test1() {
let a: A<T> = A { begin: 0, end: 10 };
let peekable: Peekable<A<T>> = a.peekable();
assert_eq!(peekable.count(), 10);
}
#[test]
fn count_test2() {
let a: A<T> = A { begin: 0, end: 10 };
let mut peekable: Peekable<A<T>> = a.peekable();
peekable.next();
assert_eq!(peekable.count(), 9);
}
}
|
} else {
None::<Self::Item>
|
random_line_split
|
count.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Peekable;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} else {
None::<Self::Item>
}
}
// fn peekable(self) -> Peekable<Self> where Self: Sized {
// Peekable{iter: self, peeked: None}
// }
// fn count(self) -> usize where Self: Sized {
// // Might overflow.
// self.fold(0, |cnt, _| cnt + 1)
// }
}
}
}
type T = i32;
Iterator_impl!(T);
// impl<I: Iterator> Iterator for Peekable<I> {
// type Item = I::Item;
//
// #[inline]
// fn next(&mut self) -> Option<I::Item> {
// match self.peeked {
// Some(_) => self.peeked.take(),
// None => self.iter.next(),
// }
// }
//
// #[inline]
// fn count(self) -> usize {
// (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
// }
//
// #[inline]
// fn nth(&mut self, n: usize) -> Option<I::Item> {
// match self.peeked {
// Some(_) if n == 0 => self.peeked.take(),
// Some(_) => {
// self.peeked = None;
// self.iter.nth(n-1)
// },
// None => self.iter.nth(n)
// }
// }
//
// #[inline]
// fn last(self) -> Option<I::Item> {
// self.iter.last().or(self.peeked)
// }
//
// #[inline]
// fn size_hint(&self) -> (usize, Option<usize>) {
// let (lo, hi) = self.iter.size_hint();
// if self.peeked.is_some() {
// let lo = lo.saturating_add(1);
// let hi = hi.and_then(|x| x.checked_add(1));
// (lo, hi)
// } else {
// (lo, hi)
// }
// }
// }
#[test]
fn count_test1() {
let a: A<T> = A { begin: 0, end: 10 };
let peekable: Peekable<A<T>> = a.peekable();
assert_eq!(peekable.count(), 10);
}
#[test]
fn count_test2()
|
}
|
{
let a: A<T> = A { begin: 0, end: 10 };
let mut peekable: Peekable<A<T>> = a.peekable();
peekable.next();
assert_eq!(peekable.count(), 9);
}
|
identifier_body
|
count.rs
|
#![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::iter::Iterator;
use core::iter::Peekable;
struct A<T> {
begin: T,
end: T
}
macro_rules! Iterator_impl {
($T:ty) => {
impl Iterator for A<$T> {
type Item = $T;
fn next(&mut self) -> Option<Self::Item> {
if self.begin < self.end {
let result = self.begin;
self.begin = self.begin.wrapping_add(1);
Some::<Self::Item>(result)
} else {
None::<Self::Item>
}
}
// fn peekable(self) -> Peekable<Self> where Self: Sized {
// Peekable{iter: self, peeked: None}
// }
// fn count(self) -> usize where Self: Sized {
// // Might overflow.
// self.fold(0, |cnt, _| cnt + 1)
// }
}
}
}
type T = i32;
Iterator_impl!(T);
// impl<I: Iterator> Iterator for Peekable<I> {
// type Item = I::Item;
//
// #[inline]
// fn next(&mut self) -> Option<I::Item> {
// match self.peeked {
// Some(_) => self.peeked.take(),
// None => self.iter.next(),
// }
// }
//
// #[inline]
// fn count(self) -> usize {
// (if self.peeked.is_some() { 1 } else { 0 }) + self.iter.count()
// }
//
// #[inline]
// fn nth(&mut self, n: usize) -> Option<I::Item> {
// match self.peeked {
// Some(_) if n == 0 => self.peeked.take(),
// Some(_) => {
// self.peeked = None;
// self.iter.nth(n-1)
// },
// None => self.iter.nth(n)
// }
// }
//
// #[inline]
// fn last(self) -> Option<I::Item> {
// self.iter.last().or(self.peeked)
// }
//
// #[inline]
// fn size_hint(&self) -> (usize, Option<usize>) {
// let (lo, hi) = self.iter.size_hint();
// if self.peeked.is_some() {
// let lo = lo.saturating_add(1);
// let hi = hi.and_then(|x| x.checked_add(1));
// (lo, hi)
// } else {
// (lo, hi)
// }
// }
// }
#[test]
fn count_test1() {
let a: A<T> = A { begin: 0, end: 10 };
let peekable: Peekable<A<T>> = a.peekable();
assert_eq!(peekable.count(), 10);
}
#[test]
fn
|
() {
let a: A<T> = A { begin: 0, end: 10 };
let mut peekable: Peekable<A<T>> = a.peekable();
peekable.next();
assert_eq!(peekable.count(), 9);
}
}
|
count_test2
|
identifier_name
|
at_exit_imp.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.
//! Implementation of running at_exit routines
//!
//! Documentation can be found on the `rt::at_exit` function.
use core::prelude::*;
|
use collections::vec::Vec;
use core::atomic;
use core::mem;
use exclusive::Exclusive;
type Queue = Exclusive<Vec<proc():Send>>;
static mut QUEUE: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT;
static mut RUNNING: atomic::AtomicBool = atomic::INIT_ATOMIC_BOOL;
pub fn init() {
let state: Box<Queue> = box Exclusive::new(Vec::new());
unsafe {
rtassert!(!RUNNING.load(atomic::SeqCst));
assert!(QUEUE.swap(mem::transmute(state), atomic::SeqCst) == 0);
}
}
pub fn push(f: proc():Send) {
unsafe {
// Note that the check against 0 for the queue pointer is not atomic at
// all with respect to `run`, meaning that this could theoretically be a
// use-after-free. There's not much we can do to protect against that,
// however. Let's just assume a well-behaved runtime and go from there!
rtassert!(!RUNNING.load(atomic::SeqCst));
let queue = QUEUE.load(atomic::SeqCst);
rtassert!(queue!= 0);
(*(queue as *const Queue)).lock().push(f);
}
}
pub fn run() {
let cur = unsafe {
rtassert!(!RUNNING.load(atomic::SeqCst));
let queue = QUEUE.swap(0, atomic::SeqCst);
rtassert!(queue!= 0);
let queue: Box<Queue> = mem::transmute(queue);
let v = mem::replace(&mut *queue.lock(), Vec::new());
v
};
for to_run in cur.into_iter() {
to_run();
}
}
|
use alloc::boxed::Box;
use collections::MutableSeq;
|
random_line_split
|
at_exit_imp.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.
//! Implementation of running at_exit routines
//!
//! Documentation can be found on the `rt::at_exit` function.
use core::prelude::*;
use alloc::boxed::Box;
use collections::MutableSeq;
use collections::vec::Vec;
use core::atomic;
use core::mem;
use exclusive::Exclusive;
type Queue = Exclusive<Vec<proc():Send>>;
static mut QUEUE: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT;
static mut RUNNING: atomic::AtomicBool = atomic::INIT_ATOMIC_BOOL;
pub fn init() {
let state: Box<Queue> = box Exclusive::new(Vec::new());
unsafe {
rtassert!(!RUNNING.load(atomic::SeqCst));
assert!(QUEUE.swap(mem::transmute(state), atomic::SeqCst) == 0);
}
}
pub fn push(f: proc():Send)
|
pub fn run() {
let cur = unsafe {
rtassert!(!RUNNING.load(atomic::SeqCst));
let queue = QUEUE.swap(0, atomic::SeqCst);
rtassert!(queue!= 0);
let queue: Box<Queue> = mem::transmute(queue);
let v = mem::replace(&mut *queue.lock(), Vec::new());
v
};
for to_run in cur.into_iter() {
to_run();
}
}
|
{
unsafe {
// Note that the check against 0 for the queue pointer is not atomic at
// all with respect to `run`, meaning that this could theoretically be a
// use-after-free. There's not much we can do to protect against that,
// however. Let's just assume a well-behaved runtime and go from there!
rtassert!(!RUNNING.load(atomic::SeqCst));
let queue = QUEUE.load(atomic::SeqCst);
rtassert!(queue != 0);
(*(queue as *const Queue)).lock().push(f);
}
}
|
identifier_body
|
at_exit_imp.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.
//! Implementation of running at_exit routines
//!
//! Documentation can be found on the `rt::at_exit` function.
use core::prelude::*;
use alloc::boxed::Box;
use collections::MutableSeq;
use collections::vec::Vec;
use core::atomic;
use core::mem;
use exclusive::Exclusive;
type Queue = Exclusive<Vec<proc():Send>>;
static mut QUEUE: atomic::AtomicUint = atomic::INIT_ATOMIC_UINT;
static mut RUNNING: atomic::AtomicBool = atomic::INIT_ATOMIC_BOOL;
pub fn init() {
let state: Box<Queue> = box Exclusive::new(Vec::new());
unsafe {
rtassert!(!RUNNING.load(atomic::SeqCst));
assert!(QUEUE.swap(mem::transmute(state), atomic::SeqCst) == 0);
}
}
pub fn push(f: proc():Send) {
unsafe {
// Note that the check against 0 for the queue pointer is not atomic at
// all with respect to `run`, meaning that this could theoretically be a
// use-after-free. There's not much we can do to protect against that,
// however. Let's just assume a well-behaved runtime and go from there!
rtassert!(!RUNNING.load(atomic::SeqCst));
let queue = QUEUE.load(atomic::SeqCst);
rtassert!(queue!= 0);
(*(queue as *const Queue)).lock().push(f);
}
}
pub fn
|
() {
let cur = unsafe {
rtassert!(!RUNNING.load(atomic::SeqCst));
let queue = QUEUE.swap(0, atomic::SeqCst);
rtassert!(queue!= 0);
let queue: Box<Queue> = mem::transmute(queue);
let v = mem::replace(&mut *queue.lock(), Vec::new());
v
};
for to_run in cur.into_iter() {
to_run();
}
}
|
run
|
identifier_name
|
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible};
use dom::bindings::conversions::root_from_object;
use dom::bindings::str::USVString;
use dom::domexception::{DOMErrorName, DOMException};
use dom::globalscope::GlobalScope;
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::HandleObject;
use js::jsapi::JSContext;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_ErrorFromException;
use js::jsapi::JS_GetPendingException;
use js::jsapi::JS_IsExceptionPending;
use js::jsapi::JS_SetPendingException;
use js::jsapi::MutableHandleValue;
use js::jsval::UndefinedValue;
use libc::c_uint;
use std::slice::from_raw_parts;
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) {
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
}
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct ErrorInfo {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject)
-> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() {
return None;
}
let filename = {
let filename = (*report).filename as *const u8;
if!filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report).lineno;
let column = (*report).column;
let message = {
let message = (*report).ucmessage;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf16_lossy(message)
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if!JS_IsExceptionPending(cx) { return; }
rooted!(in(cx) let mut value = UndefinedValue());
if!JS_GetPendingException(cx, value.handle_mut()) {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
}
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| {
ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
}
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => {
ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
}
},
_ =>
|
,
}
};
error!("Error at {}:{}:{} {}",
error_info.filename,
error_info.lineno,
error_info.column,
error_info.message);
if dispatch_event {
GlobalScope::from_context(cx)
.report_an_error(error_info, value.handle());
}
}
/// Throw an exception to signal that a `JSVal` can not be converted to any of
/// the types in an IDL union type.
pub unsafe fn throw_not_in_union(cx: *mut JSContext, names: &'static str) {
assert!(!JS_IsExceptionPending(cx));
let error = format!("argument could not be converted to any of: {}", names);
throw_type_error(cx, &error);
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!("\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id));
throw_type_error(cx, &error);
}
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
pub unsafe fn to_jsval(self, cx: *mut JSContext, global: &GlobalScope, rval: MutableHandleValue) {
assert!(!JS_IsExceptionPending(cx));
throw_dom_exception(cx, global, self);
assert!(JS_IsExceptionPending(cx));
assert!(JS_GetPendingException(cx, rval));
JS_ClearPendingException(cx);
}
}
|
{
panic!("Uncaught exception: failed to stringify primitive");
}
|
conditional_block
|
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible};
use dom::bindings::conversions::root_from_object;
use dom::bindings::str::USVString;
use dom::domexception::{DOMErrorName, DOMException};
use dom::globalscope::GlobalScope;
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::HandleObject;
use js::jsapi::JSContext;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_ErrorFromException;
use js::jsapi::JS_GetPendingException;
use js::jsapi::JS_IsExceptionPending;
use js::jsapi::JS_SetPendingException;
use js::jsapi::MutableHandleValue;
use js::jsval::UndefinedValue;
use libc::c_uint;
use std::slice::from_raw_parts;
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
|
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) {
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
}
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct ErrorInfo {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject)
-> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() {
return None;
}
let filename = {
let filename = (*report).filename as *const u8;
if!filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report).lineno;
let column = (*report).column;
let message = {
let message = (*report).ucmessage;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf16_lossy(message)
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if!JS_IsExceptionPending(cx) { return; }
rooted!(in(cx) let mut value = UndefinedValue());
if!JS_GetPendingException(cx, value.handle_mut()) {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
}
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| {
ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
}
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => {
ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
}
},
_ => {
panic!("Uncaught exception: failed to stringify primitive");
},
}
};
error!("Error at {}:{}:{} {}",
error_info.filename,
error_info.lineno,
error_info.column,
error_info.message);
if dispatch_event {
GlobalScope::from_context(cx)
.report_an_error(error_info, value.handle());
}
}
/// Throw an exception to signal that a `JSVal` can not be converted to any of
/// the types in an IDL union type.
pub unsafe fn throw_not_in_union(cx: *mut JSContext, names: &'static str) {
assert!(!JS_IsExceptionPending(cx));
let error = format!("argument could not be converted to any of: {}", names);
throw_type_error(cx, &error);
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!("\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id));
throw_type_error(cx, &error);
}
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
pub unsafe fn to_jsval(self, cx: *mut JSContext, global: &GlobalScope, rval: MutableHandleValue) {
assert!(!JS_IsExceptionPending(cx));
throw_dom_exception(cx, global, self);
assert!(JS_IsExceptionPending(cx));
assert!(JS_GetPendingException(cx, rval));
JS_ClearPendingException(cx);
}
}
|
/// NotFoundError DOMException
|
random_line_split
|
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible};
use dom::bindings::conversions::root_from_object;
use dom::bindings::str::USVString;
use dom::domexception::{DOMErrorName, DOMException};
use dom::globalscope::GlobalScope;
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::HandleObject;
use js::jsapi::JSContext;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_ErrorFromException;
use js::jsapi::JS_GetPendingException;
use js::jsapi::JS_IsExceptionPending;
use js::jsapi::JS_SetPendingException;
use js::jsapi::MutableHandleValue;
use js::jsval::UndefinedValue;
use libc::c_uint;
use std::slice::from_raw_parts;
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error)
|
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
}
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct ErrorInfo {
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject)
-> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() {
return None;
}
let filename = {
let filename = (*report).filename as *const u8;
if!filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report).lineno;
let column = (*report).column;
let message = {
let message = (*report).ucmessage;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf16_lossy(message)
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if!JS_IsExceptionPending(cx) { return; }
rooted!(in(cx) let mut value = UndefinedValue());
if!JS_GetPendingException(cx, value.handle_mut()) {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
}
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| {
ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
}
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => {
ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
}
},
_ => {
panic!("Uncaught exception: failed to stringify primitive");
},
}
};
error!("Error at {}:{}:{} {}",
error_info.filename,
error_info.lineno,
error_info.column,
error_info.message);
if dispatch_event {
GlobalScope::from_context(cx)
.report_an_error(error_info, value.handle());
}
}
/// Throw an exception to signal that a `JSVal` can not be converted to any of
/// the types in an IDL union type.
pub unsafe fn throw_not_in_union(cx: *mut JSContext, names: &'static str) {
assert!(!JS_IsExceptionPending(cx));
let error = format!("argument could not be converted to any of: {}", names);
throw_type_error(cx, &error);
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!("\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id));
throw_type_error(cx, &error);
}
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
pub unsafe fn to_jsval(self, cx: *mut JSContext, global: &GlobalScope, rval: MutableHandleValue) {
assert!(!JS_IsExceptionPending(cx));
throw_dom_exception(cx, global, self);
assert!(JS_IsExceptionPending(cx));
assert!(JS_GetPendingException(cx, rval));
JS_ClearPendingException(cx);
}
}
|
{
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
|
identifier_body
|
error.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/. */
//! Utilities to throw exceptions from Rust bindings.
use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods;
use dom::bindings::codegen::PrototypeList::proto_id_to_name;
use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible};
use dom::bindings::conversions::root_from_object;
use dom::bindings::str::USVString;
use dom::domexception::{DOMErrorName, DOMException};
use dom::globalscope::GlobalScope;
use js::error::{throw_range_error, throw_type_error};
use js::jsapi::HandleObject;
use js::jsapi::JSContext;
use js::jsapi::JS_ClearPendingException;
use js::jsapi::JS_ErrorFromException;
use js::jsapi::JS_GetPendingException;
use js::jsapi::JS_IsExceptionPending;
use js::jsapi::JS_SetPendingException;
use js::jsapi::MutableHandleValue;
use js::jsval::UndefinedValue;
use libc::c_uint;
use std::slice::from_raw_parts;
/// DOM exceptions that can be thrown by a native DOM method.
#[derive(Clone, Debug, MallocSizeOf)]
pub enum Error {
/// IndexSizeError DOMException
IndexSize,
/// NotFoundError DOMException
NotFound,
/// HierarchyRequestError DOMException
HierarchyRequest,
/// WrongDocumentError DOMException
WrongDocument,
/// InvalidCharacterError DOMException
InvalidCharacter,
/// NotSupportedError DOMException
NotSupported,
/// InUseAttributeError DOMException
InUseAttribute,
/// InvalidStateError DOMException
InvalidState,
/// SyntaxError DOMException
Syntax,
/// NamespaceError DOMException
Namespace,
/// InvalidAccessError DOMException
InvalidAccess,
/// SecurityError DOMException
Security,
/// NetworkError DOMException
Network,
/// AbortError DOMException
Abort,
/// TimeoutError DOMException
Timeout,
/// InvalidNodeTypeError DOMException
InvalidNodeType,
/// DataCloneError DOMException
DataClone,
/// NoModificationAllowedError DOMException
NoModificationAllowed,
/// QuotaExceededError DOMException
QuotaExceeded,
/// TypeMismatchError DOMException
TypeMismatch,
/// InvalidModificationError DOMException
InvalidModification,
/// TypeError JavaScript Error
Type(String),
/// RangeError JavaScript Error
Range(String),
/// A JavaScript exception is already pending.
JSFailed,
}
/// The return type for IDL operations that can throw DOM exceptions.
pub type Fallible<T> = Result<T, Error>;
/// The return type for IDL operations that can throw DOM exceptions and
/// return `()`.
pub type ErrorResult = Fallible<()>;
/// Set a pending exception for the given `result` on `cx`.
pub unsafe fn throw_dom_exception(cx: *mut JSContext, global: &GlobalScope, result: Error) {
let code = match result {
Error::IndexSize => DOMErrorName::IndexSizeError,
Error::NotFound => DOMErrorName::NotFoundError,
Error::HierarchyRequest => DOMErrorName::HierarchyRequestError,
Error::WrongDocument => DOMErrorName::WrongDocumentError,
Error::InvalidCharacter => DOMErrorName::InvalidCharacterError,
Error::NotSupported => DOMErrorName::NotSupportedError,
Error::InUseAttribute => DOMErrorName::InUseAttributeError,
Error::InvalidState => DOMErrorName::InvalidStateError,
Error::Syntax => DOMErrorName::SyntaxError,
Error::Namespace => DOMErrorName::NamespaceError,
Error::InvalidAccess => DOMErrorName::InvalidAccessError,
Error::Security => DOMErrorName::SecurityError,
Error::Network => DOMErrorName::NetworkError,
Error::Abort => DOMErrorName::AbortError,
Error::Timeout => DOMErrorName::TimeoutError,
Error::InvalidNodeType => DOMErrorName::InvalidNodeTypeError,
Error::DataClone => DOMErrorName::DataCloneError,
Error::NoModificationAllowed => DOMErrorName::NoModificationAllowedError,
Error::QuotaExceeded => DOMErrorName::QuotaExceededError,
Error::TypeMismatch => DOMErrorName::TypeMismatchError,
Error::InvalidModification => DOMErrorName::InvalidModificationError,
Error::Type(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_type_error(cx, &message);
return;
},
Error::Range(message) => {
assert!(!JS_IsExceptionPending(cx));
throw_range_error(cx, &message);
return;
},
Error::JSFailed => {
assert!(JS_IsExceptionPending(cx));
return;
}
};
assert!(!JS_IsExceptionPending(cx));
let exception = DOMException::new(global, code);
rooted!(in(cx) let mut thrown = UndefinedValue());
exception.to_jsval(cx, thrown.handle_mut());
JS_SetPendingException(cx, thrown.handle());
}
/// A struct encapsulating information about a runtime script error.
pub struct
|
{
/// The error message.
pub message: String,
/// The file name.
pub filename: String,
/// The line number.
pub lineno: c_uint,
/// The column number.
pub column: c_uint,
}
impl ErrorInfo {
unsafe fn from_native_error(cx: *mut JSContext, object: HandleObject)
-> Option<ErrorInfo> {
let report = JS_ErrorFromException(cx, object);
if report.is_null() {
return None;
}
let filename = {
let filename = (*report).filename as *const u8;
if!filename.is_null() {
let length = (0..).find(|idx| *filename.offset(*idx) == 0).unwrap();
let filename = from_raw_parts(filename, length as usize);
String::from_utf8_lossy(filename).into_owned()
} else {
"none".to_string()
}
};
let lineno = (*report).lineno;
let column = (*report).column;
let message = {
let message = (*report).ucmessage;
let length = (0..).find(|idx| *message.offset(*idx) == 0).unwrap();
let message = from_raw_parts(message, length as usize);
String::from_utf16_lossy(message)
};
Some(ErrorInfo {
filename: filename,
message: message,
lineno: lineno,
column: column,
})
}
fn from_dom_exception(object: HandleObject) -> Option<ErrorInfo> {
let exception = match root_from_object::<DOMException>(object.get()) {
Ok(exception) => exception,
Err(_) => return None,
};
Some(ErrorInfo {
filename: "".to_string(),
message: exception.Stringifier().into(),
lineno: 0,
column: 0,
})
}
}
/// Report a pending exception, thereby clearing it.
///
/// The `dispatch_event` argument is temporary and non-standard; passing false
/// prevents dispatching the `error` event.
pub unsafe fn report_pending_exception(cx: *mut JSContext, dispatch_event: bool) {
if!JS_IsExceptionPending(cx) { return; }
rooted!(in(cx) let mut value = UndefinedValue());
if!JS_GetPendingException(cx, value.handle_mut()) {
JS_ClearPendingException(cx);
error!("Uncaught exception: JS_GetPendingException failed");
return;
}
JS_ClearPendingException(cx);
let error_info = if value.is_object() {
rooted!(in(cx) let object = value.to_object());
ErrorInfo::from_native_error(cx, object.handle())
.or_else(|| ErrorInfo::from_dom_exception(object.handle()))
.unwrap_or_else(|| {
ErrorInfo {
message: format!("uncaught exception: unknown (can't convert to string)"),
filename: String::new(),
lineno: 0,
column: 0,
}
})
} else {
match USVString::from_jsval(cx, value.handle(), ()) {
Ok(ConversionResult::Success(USVString(string))) => {
ErrorInfo {
message: format!("uncaught exception: {}", string),
filename: String::new(),
lineno: 0,
column: 0,
}
},
_ => {
panic!("Uncaught exception: failed to stringify primitive");
},
}
};
error!("Error at {}:{}:{} {}",
error_info.filename,
error_info.lineno,
error_info.column,
error_info.message);
if dispatch_event {
GlobalScope::from_context(cx)
.report_an_error(error_info, value.handle());
}
}
/// Throw an exception to signal that a `JSVal` can not be converted to any of
/// the types in an IDL union type.
pub unsafe fn throw_not_in_union(cx: *mut JSContext, names: &'static str) {
assert!(!JS_IsExceptionPending(cx));
let error = format!("argument could not be converted to any of: {}", names);
throw_type_error(cx, &error);
}
/// Throw an exception to signal that a `JSObject` can not be converted to a
/// given DOM type.
pub unsafe fn throw_invalid_this(cx: *mut JSContext, proto_id: u16) {
debug_assert!(!JS_IsExceptionPending(cx));
let error = format!("\"this\" object does not implement interface {}.",
proto_id_to_name(proto_id));
throw_type_error(cx, &error);
}
impl Error {
/// Convert this error value to a JS value, consuming it in the process.
pub unsafe fn to_jsval(self, cx: *mut JSContext, global: &GlobalScope, rval: MutableHandleValue) {
assert!(!JS_IsExceptionPending(cx));
throw_dom_exception(cx, global, self);
assert!(JS_IsExceptionPending(cx));
assert!(JS_GetPendingException(cx, rval));
JS_ClearPendingException(cx);
}
}
|
ErrorInfo
|
identifier_name
|
error.rs
|
use std::fmt;
use std::error::Error;
use super::Rule;
#[derive(Debug, PartialEq, Clone)]
|
pub col: usize,
pub expected: Vec<Rule>,
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.expected.is_empty() {
write!(f, "no token expected at line {} col {}", self.line, self.col)
} else {
write!(f, "expected token(s): {} at line {} col {}",
self.expected.iter().map(|r| format!("{}", r)).collect::<Vec<String>>().join(", "),
self.line, self.col)
}
}
}
impl Error for ParseError {
fn description(&self) -> &str {
if self.expected.is_empty() {
"no tokens expected"
} else {
"expected tokens which were not found"
}
}
}
|
pub struct ParseError {
pub line: usize,
|
random_line_split
|
error.rs
|
use std::fmt;
use std::error::Error;
use super::Rule;
#[derive(Debug, PartialEq, Clone)]
pub struct ParseError {
pub line: usize,
pub col: usize,
pub expected: Vec<Rule>,
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.expected.is_empty() {
write!(f, "no token expected at line {} col {}", self.line, self.col)
} else {
write!(f, "expected token(s): {} at line {} col {}",
self.expected.iter().map(|r| format!("{}", r)).collect::<Vec<String>>().join(", "),
self.line, self.col)
}
}
}
impl Error for ParseError {
fn description(&self) -> &str {
if self.expected.is_empty() {
"no tokens expected"
} else
|
}
}
|
{
"expected tokens which were not found"
}
|
conditional_block
|
error.rs
|
use std::fmt;
use std::error::Error;
use super::Rule;
#[derive(Debug, PartialEq, Clone)]
pub struct ParseError {
pub line: usize,
pub col: usize,
pub expected: Vec<Rule>,
}
impl fmt::Display for ParseError {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.expected.is_empty() {
write!(f, "no token expected at line {} col {}", self.line, self.col)
} else {
write!(f, "expected token(s): {} at line {} col {}",
self.expected.iter().map(|r| format!("{}", r)).collect::<Vec<String>>().join(", "),
self.line, self.col)
}
}
}
impl Error for ParseError {
fn description(&self) -> &str {
if self.expected.is_empty() {
"no tokens expected"
} else {
"expected tokens which were not found"
}
}
}
|
fmt
|
identifier_name
|
while_early_ret.rs
|
#![allow(unused_assignments)]
// expect-exit-status-1
fn main() -> Result<(),u8> {
let mut countdown = 10;
|
if
countdown
<
5
{
return
if
countdown
>
8
{
Ok(())
}
else
{
Err(1)
}
;
}
countdown
-=
1
;
}
Ok(())
}
// ISSUE(77553): Originally, this test had `Err(1)` on line 22 (instead of `Ok(())`) and
// `std::process::exit(2)` on line 26 (instead of `Err(1)`); and this worked as expected on Linux
// and MacOS. But on Windows (MSVC, at least), the call to `std::process::exit()` exits the program
// without saving the InstrProf coverage counters. The use of `std::process:exit()` is not critical
// to the coverage test for early returns, but this is a limitation that should be fixed.
|
while
countdown
>
0
{
|
random_line_split
|
while_early_ret.rs
|
#![allow(unused_assignments)]
// expect-exit-status-1
fn
|
() -> Result<(),u8> {
let mut countdown = 10;
while
countdown
>
0
{
if
countdown
<
5
{
return
if
countdown
>
8
{
Ok(())
}
else
{
Err(1)
}
;
}
countdown
-=
1
;
}
Ok(())
}
// ISSUE(77553): Originally, this test had `Err(1)` on line 22 (instead of `Ok(())`) and
// `std::process::exit(2)` on line 26 (instead of `Err(1)`); and this worked as expected on Linux
// and MacOS. But on Windows (MSVC, at least), the call to `std::process::exit()` exits the program
// without saving the InstrProf coverage counters. The use of `std::process:exit()` is not critical
// to the coverage test for early returns, but this is a limitation that should be fixed.
|
main
|
identifier_name
|
while_early_ret.rs
|
#![allow(unused_assignments)]
// expect-exit-status-1
fn main() -> Result<(),u8> {
let mut countdown = 10;
while
countdown
>
0
{
if
countdown
<
5
|
countdown
-=
1
;
}
Ok(())
}
// ISSUE(77553): Originally, this test had `Err(1)` on line 22 (instead of `Ok(())`) and
// `std::process::exit(2)` on line 26 (instead of `Err(1)`); and this worked as expected on Linux
// and MacOS. But on Windows (MSVC, at least), the call to `std::process::exit()` exits the program
// without saving the InstrProf coverage counters. The use of `std::process:exit()` is not critical
// to the coverage test for early returns, but this is a limitation that should be fixed.
|
{
return
if
countdown
>
8
{
Ok(())
}
else
{
Err(1)
}
;
}
|
conditional_block
|
while_early_ret.rs
|
#![allow(unused_assignments)]
// expect-exit-status-1
fn main() -> Result<(),u8>
|
else
{
Err(1)
}
;
}
countdown
-=
1
;
}
Ok(())
}
// ISSUE(77553): Originally, this test had `Err(1)` on line 22 (instead of `Ok(())`) and
// `std::process::exit(2)` on line 26 (instead of `Err(1)`); and this worked as expected on Linux
// and MacOS. But on Windows (MSVC, at least), the call to `std::process::exit()` exits the program
// without saving the InstrProf coverage counters. The use of `std::process:exit()` is not critical
// to the coverage test for early returns, but this is a limitation that should be fixed.
|
{
let mut countdown = 10;
while
countdown
>
0
{
if
countdown
<
5
{
return
if
countdown
>
8
{
Ok(())
}
|
identifier_body
|
day_7.rs
|
use alloc::raw_vec::RawVec;
use std::ops::{Deref, DerefMut};
use std::{slice, ptr};
use std::intrinsics::assume;
pub struct Stack<T> {
size: usize,
buf: RawVec<T>
}
impl <T> Deref for Stack<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe {
slice::from_raw_parts(self.as_ptr(), self.size)
}
}
}
impl <T> DerefMut for Stack<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe {
let p = self.buf.ptr();
assume(!p.is_null());
slice::from_raw_parts_mut(self.as_ptr(), self.size)
}
}
}
impl <T> Stack<T> {
pub fn new(max_size: usize) -> Stack<T> {
Stack { size: 0, buf: RawVec::with_capacity(max_size) }
}
pub fn size(&self) -> usize {
self.size
}
pub fn is_empty(&self) -> bool {
self.size == 0
}
pub fn
|
(&mut self, v: T) -> bool {
if self.size == self.buf.cap() {
false
}
else {
unsafe {
let end = self.as_mut_ptr().offset(self.size as isize);
ptr::write(end, v);
}
self.size += 1;
true
}
}
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
None
}
else {
self.size -= 1;
unsafe {
Some(ptr::read(self.get_unchecked(self.size)))
}
}
}
unsafe fn as_ptr(&self) -> *mut T {
let p = self.buf.ptr();
assume(!p.is_null());
p
}
}
|
push
|
identifier_name
|
day_7.rs
|
use alloc::raw_vec::RawVec;
use std::ops::{Deref, DerefMut};
use std::{slice, ptr};
use std::intrinsics::assume;
pub struct Stack<T> {
size: usize,
buf: RawVec<T>
}
impl <T> Deref for Stack<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe {
slice::from_raw_parts(self.as_ptr(), self.size)
}
}
}
impl <T> DerefMut for Stack<T> {
fn deref_mut(&mut self) -> &mut [T]
|
}
impl <T> Stack<T> {
pub fn new(max_size: usize) -> Stack<T> {
Stack { size: 0, buf: RawVec::with_capacity(max_size) }
}
pub fn size(&self) -> usize {
self.size
}
pub fn is_empty(&self) -> bool {
self.size == 0
}
pub fn push(&mut self, v: T) -> bool {
if self.size == self.buf.cap() {
false
}
else {
unsafe {
let end = self.as_mut_ptr().offset(self.size as isize);
ptr::write(end, v);
}
self.size += 1;
true
}
}
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
None
}
else {
self.size -= 1;
unsafe {
Some(ptr::read(self.get_unchecked(self.size)))
}
}
}
unsafe fn as_ptr(&self) -> *mut T {
let p = self.buf.ptr();
assume(!p.is_null());
p
}
}
|
{
unsafe {
let p = self.buf.ptr();
assume(!p.is_null());
slice::from_raw_parts_mut(self.as_ptr(), self.size)
}
}
|
identifier_body
|
day_7.rs
|
use alloc::raw_vec::RawVec;
use std::ops::{Deref, DerefMut};
use std::{slice, ptr};
use std::intrinsics::assume;
pub struct Stack<T> {
size: usize,
buf: RawVec<T>
}
impl <T> Deref for Stack<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe {
slice::from_raw_parts(self.as_ptr(), self.size)
}
}
}
impl <T> DerefMut for Stack<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe {
let p = self.buf.ptr();
assume(!p.is_null());
slice::from_raw_parts_mut(self.as_ptr(), self.size)
}
|
pub fn new(max_size: usize) -> Stack<T> {
Stack { size: 0, buf: RawVec::with_capacity(max_size) }
}
pub fn size(&self) -> usize {
self.size
}
pub fn is_empty(&self) -> bool {
self.size == 0
}
pub fn push(&mut self, v: T) -> bool {
if self.size == self.buf.cap() {
false
}
else {
unsafe {
let end = self.as_mut_ptr().offset(self.size as isize);
ptr::write(end, v);
}
self.size += 1;
true
}
}
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
None
}
else {
self.size -= 1;
unsafe {
Some(ptr::read(self.get_unchecked(self.size)))
}
}
}
unsafe fn as_ptr(&self) -> *mut T {
let p = self.buf.ptr();
assume(!p.is_null());
p
}
}
|
}
}
impl <T> Stack<T> {
|
random_line_split
|
day_7.rs
|
use alloc::raw_vec::RawVec;
use std::ops::{Deref, DerefMut};
use std::{slice, ptr};
use std::intrinsics::assume;
pub struct Stack<T> {
size: usize,
buf: RawVec<T>
}
impl <T> Deref for Stack<T> {
type Target = [T];
fn deref(&self) -> &[T] {
unsafe {
slice::from_raw_parts(self.as_ptr(), self.size)
}
}
}
impl <T> DerefMut for Stack<T> {
fn deref_mut(&mut self) -> &mut [T] {
unsafe {
let p = self.buf.ptr();
assume(!p.is_null());
slice::from_raw_parts_mut(self.as_ptr(), self.size)
}
}
}
impl <T> Stack<T> {
pub fn new(max_size: usize) -> Stack<T> {
Stack { size: 0, buf: RawVec::with_capacity(max_size) }
}
pub fn size(&self) -> usize {
self.size
}
pub fn is_empty(&self) -> bool {
self.size == 0
}
pub fn push(&mut self, v: T) -> bool {
if self.size == self.buf.cap() {
false
}
else {
unsafe {
let end = self.as_mut_ptr().offset(self.size as isize);
ptr::write(end, v);
}
self.size += 1;
true
}
}
pub fn pop(&mut self) -> Option<T> {
if self.is_empty() {
None
}
else
|
}
unsafe fn as_ptr(&self) -> *mut T {
let p = self.buf.ptr();
assume(!p.is_null());
p
}
}
|
{
self.size -= 1;
unsafe {
Some(ptr::read(self.get_unchecked(self.size)))
}
}
|
conditional_block
|
lib.rs
|
// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[deny(missing_docs)]
#[macro_use]
extern crate log;
#[macro_use]
extern crate objc;
extern crate cocoa;
extern crate winit;
extern crate metal_rs as metal;
extern crate gfx_core as core;
extern crate gfx_device_metal as device_metal;
use winit::os::macos::WindowExt;
use objc::runtime::{YES};
use cocoa::base::id as cocoa_id;
//use cocoa::base::{selector, class};
use cocoa::foundation::{NSSize};
use cocoa::appkit::{NSWindow, NSView};
use core::format::{RenderFormat, Format};
use core::handle::{RawRenderTargetView, RenderTargetView};
use core::memory::Typed;
use device_metal::{Device, Factory, Resources};
use metal::*;
//use winit::{Window};
use std::ops::Deref;
use std::cell::Cell;
use std::mem;
pub struct MetalWindow {
window: winit::Window,
layer: CAMetalLayer,
drawable: *mut CAMetalDrawable,
backbuffer: *mut MTLTexture,
pool: Cell<NSAutoreleasePool>
}
impl Deref for MetalWindow {
type Target = winit::Window;
fn deref(&self) -> &winit::Window {
&self.window
}
}
impl MetalWindow {
pub fn swap_buffers(&self) -> Result<(), ()> {
// TODO: did we fail to swap buffers?
// TODO: come up with alternative to this hack
unsafe {
self.pool.get().release();
self.pool.set(NSAutoreleasePool::alloc().init());
let drawable = self.layer.next_drawable().unwrap();
//drawable.retain();
*self.drawable = drawable;
*self.backbuffer = drawable.texture();
}
Ok(())
}
}
#[derive(Copy, Clone, Debug)]
pub enum InitError {
/// Unable to create a window.
Window,
/// Unable to map format to Metal.
Format(Format),
/// Unable to find a supported driver type.
DriverType,
}
pub fn
|
<C: RenderFormat>(wb: winit::WindowBuilder)
-> Result<(MetalWindow, Device, Factory, RenderTargetView<Resources, C>), InitError>
{
init_raw(wb, C::get_format())
.map(|(window, device, factory, color)| (window, device, factory, Typed::new(color)))
}
/// Initialize with a given size. Raw format version.
pub fn init_raw(wb: winit::WindowBuilder, color_format: Format)
-> Result<(MetalWindow, Device, Factory, RawRenderTargetView<Resources>), InitError>
{
use device_metal::map_format;
let winit_window = wb.build().unwrap();
unsafe {
let wnd: cocoa_id = mem::transmute(winit_window.get_nswindow());
let layer = CAMetalLayer::new();
layer.set_pixel_format(match map_format(color_format, true) {
Some(fm) => fm,
None => return Err(InitError::Format(color_format)),
});
let draw_size = winit_window.get_inner_size().unwrap();
layer.set_edge_antialiasing_mask(0);
layer.set_masks_to_bounds(true);
//layer.set_magnification_filter(kCAFilterNearest);
//layer.set_minification_filter(kCAFilterNearest);
layer.set_drawable_size(NSSize::new(draw_size.0 as f64, draw_size.1 as f64));
layer.set_presents_with_transaction(false);
layer.remove_all_animations();
let view = wnd.contentView();
view.setWantsLayer(YES);
view.setLayer(mem::transmute(layer.0));
let (device, factory, color, daddr, addr) = device_metal::create(color_format, draw_size.0, draw_size.1).unwrap();
layer.set_device(device.device);
let drawable = layer.next_drawable().unwrap();
let window = MetalWindow {
window: winit_window,
layer: layer,
drawable: daddr,
backbuffer: addr,
pool: Cell::new(NSAutoreleasePool::alloc().init())
};
(*daddr).0 = drawable.0;
(*addr).0 = drawable.texture().0;
Ok((window, device, factory, color))
}
}
|
init
|
identifier_name
|
lib.rs
|
// Copyright 2016 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#[deny(missing_docs)]
#[macro_use]
extern crate log;
#[macro_use]
extern crate objc;
extern crate cocoa;
extern crate winit;
extern crate metal_rs as metal;
extern crate gfx_core as core;
extern crate gfx_device_metal as device_metal;
use winit::os::macos::WindowExt;
use objc::runtime::{YES};
use cocoa::base::id as cocoa_id;
//use cocoa::base::{selector, class};
use cocoa::foundation::{NSSize};
use cocoa::appkit::{NSWindow, NSView};
use core::format::{RenderFormat, Format};
use core::handle::{RawRenderTargetView, RenderTargetView};
use core::memory::Typed;
use device_metal::{Device, Factory, Resources};
use metal::*;
//use winit::{Window};
use std::ops::Deref;
use std::cell::Cell;
use std::mem;
pub struct MetalWindow {
window: winit::Window,
layer: CAMetalLayer,
drawable: *mut CAMetalDrawable,
backbuffer: *mut MTLTexture,
pool: Cell<NSAutoreleasePool>
}
impl Deref for MetalWindow {
type Target = winit::Window;
fn deref(&self) -> &winit::Window {
&self.window
}
}
impl MetalWindow {
pub fn swap_buffers(&self) -> Result<(), ()> {
// TODO: did we fail to swap buffers?
// TODO: come up with alternative to this hack
unsafe {
self.pool.get().release();
self.pool.set(NSAutoreleasePool::alloc().init());
let drawable = self.layer.next_drawable().unwrap();
//drawable.retain();
*self.drawable = drawable;
*self.backbuffer = drawable.texture();
}
Ok(())
}
}
#[derive(Copy, Clone, Debug)]
pub enum InitError {
/// Unable to create a window.
Window,
/// Unable to map format to Metal.
Format(Format),
/// Unable to find a supported driver type.
DriverType,
}
pub fn init<C: RenderFormat>(wb: winit::WindowBuilder)
-> Result<(MetalWindow, Device, Factory, RenderTargetView<Resources, C>), InitError>
{
init_raw(wb, C::get_format())
.map(|(window, device, factory, color)| (window, device, factory, Typed::new(color)))
}
/// Initialize with a given size. Raw format version.
pub fn init_raw(wb: winit::WindowBuilder, color_format: Format)
-> Result<(MetalWindow, Device, Factory, RawRenderTargetView<Resources>), InitError>
{
use device_metal::map_format;
let winit_window = wb.build().unwrap();
unsafe {
let wnd: cocoa_id = mem::transmute(winit_window.get_nswindow());
let layer = CAMetalLayer::new();
layer.set_pixel_format(match map_format(color_format, true) {
Some(fm) => fm,
None => return Err(InitError::Format(color_format)),
});
let draw_size = winit_window.get_inner_size().unwrap();
layer.set_edge_antialiasing_mask(0);
layer.set_masks_to_bounds(true);
//layer.set_magnification_filter(kCAFilterNearest);
//layer.set_minification_filter(kCAFilterNearest);
layer.set_drawable_size(NSSize::new(draw_size.0 as f64, draw_size.1 as f64));
layer.set_presents_with_transaction(false);
layer.remove_all_animations();
let view = wnd.contentView();
view.setWantsLayer(YES);
view.setLayer(mem::transmute(layer.0));
let (device, factory, color, daddr, addr) = device_metal::create(color_format, draw_size.0, draw_size.1).unwrap();
layer.set_device(device.device);
|
layer: layer,
drawable: daddr,
backbuffer: addr,
pool: Cell::new(NSAutoreleasePool::alloc().init())
};
(*daddr).0 = drawable.0;
(*addr).0 = drawable.texture().0;
Ok((window, device, factory, color))
}
}
|
let drawable = layer.next_drawable().unwrap();
let window = MetalWindow {
window: winit_window,
|
random_line_split
|
ascii.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Operations on ASCII strings and characters.
//!
//! Most string operations in Rust act on UTF-8 strings. However, at times it
//! makes more sense to only consider the ASCII character set for a specific
//! operation.
//!
//! The [`AsciiExt`] trait provides methods that allow for character
//! operations that only act on the ASCII subset and leave non-ASCII characters
//! alone.
//!
//! The [`escape_default`] function provides an iterator over the bytes of an
//! escaped version of the character given.
//!
//! [`AsciiExt`]: trait.AsciiExt.html
//! [`escape_default`]: fn.escape_default.html
#![stable(feature = "rust1", since = "1.0.0")]
#[stable(feature = "rust1", since = "1.0.0")]
pub use core::ascii::{EscapeDefault, escape_default};
/// Extension methods for ASCII-subset only operations.
///
/// Be aware that operations on seemingly non-ASCII characters can sometimes
/// have unexpected results. Consider this example:
///
/// ```
/// use std::ascii::AsciiExt;
///
/// assert_eq!(AsciiExt::to_ascii_uppercase("café"), "CAFÉ");
/// assert_eq!(AsciiExt::to_ascii_uppercase("café"), "CAFé");
/// ```
///
/// In the first example, the lowercased string is represented `"cafe\u{301}"`
/// (the last character is an acute accent [combining character]). Unlike the
/// other characters in the string, the combining character will not get mapped
/// to an uppercase variant, resulting in `"CAFE\u{301}"`. In the second
/// example, the lowercased string is represented `"caf\u{e9}"` (the last
/// character is a single Unicode character representing an 'e' with an acute
/// accent). Since the last character is defined outside the scope of ASCII,
/// it will not get mapped to an uppercase variant, resulting in `"CAF\u{e9}"`.
///
/// [combining character]: https://en.wikipedia.org/wiki/Combining_character
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_deprecated(since = "1.26.0", reason = "use inherent methods instead")]
pub trait AsciiExt {
/// Container type for copied ASCII characters.
#[stable(feature = "rust1", since = "1.0.0")]
type Owned;
/// Checks if the value is within the ASCII range.
///
/// # Note
///
/// This method will be deprecated in favor of the identically-named
/// inherent methods on `u8`, `char`, `[u8]` and `str`.
#[stable(feature = "rust1", since = "1.0.0")]
fn is_ascii(&self) -> bool;
/// Makes a copy of the value in its ASCII upper case equivalent.
///
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
/// but non-ASCII letters are unchanged.
///
/// To uppercase the value in-place, use [`make_ascii_uppercase`].
///
/// To uppercase ASCII characters in addition to non-ASCII characters, use
/// [`str::to_uppercase`].
///
/// # Note
///
/// This method will be deprecated in favor of the identically-named
/// inherent methods on `u8`, `char`, `[u8]` and `str`.
///
/// [`make_ascii_uppercase`]: #tymethod.make_ascii_uppercase
/// [`str::to_uppercase`]:../primitive.str.html#method.to_uppercase
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(deprecated)]
fn to_ascii_uppercase(&self) -> Self::Owned;
/// Makes a copy of the value in its ASCII lower case equivalent.
///
/// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
/// but non-ASCII letters are unchanged.
///
/// To lowercase the value in-place, use [`make_ascii_lowercase`].
///
/// To lowercase ASCII characters in addition to non-ASCII characters, use
/// [`str::to_lowercase`].
///
/// # Note
///
/// This method will be deprecated in favor of the identically-named
/// inherent methods on `u8`, `char`, `[u8]` and `str`.
///
/// [`make_ascii_lowercase`]: #tymethod.make_ascii_lowercase
/// [`str::to_lowercase`]:../primitive.str.html#method.to_lowercase
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(deprecated)]
fn to_ascii_lowercase(&self) -> Self::Owned;
/// Checks that two values are an ASCII case-insensitive match.
///
/// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
/// but without allocating and copying temporaries.
///
/// # Note
///
/// This method will be deprecated in favor of the identically-named
/// inherent methods on `u8`, `char`, `[u8]` and `str`.
#[stable(feature = "rust1", since = "1.0.0")]
fn eq_ignore_ascii_case(&self, other: &Self) -> bool;
/// Converts this type to its ASCII upper case equivalent in-place.
///
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
/// but non-ASCII letters are unchanged.
///
/// To return a new uppercased value without modifying the existing one, use
/// [`to_ascii_uppercase`].
///
/// # Note
///
/// This method will be deprecated in favor of the identically-named
/// inherent methods on `u8`, `char`, `[u8]` and `str`.
///
/// [`to_ascii_uppercase`]: #tymethod.to_ascii_uppercase
#[stable(feature = "ascii", since = "1.9.0")]
fn make_ascii_uppercase(&mut self);
/// Converts this type to its ASCII lower case equivalent in-place.
///
/// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
/// but non-ASCII letters are unchanged.
///
/// To return a new lowercased value without modifying the existing one, use
/// [`to_ascii_lowercase`].
///
/// # Note
///
/// This method will be deprecated in favor of the identically-named
/// inherent methods on `u8`, `char`, `[u8]` and `str`.
///
/// [`to_ascii_lowercase`]: #tymethod.to_ascii_lowercase
#[stable(feature = "ascii", since = "1.9.0")]
fn make_ascii_lowercase(&mut self);
}
macro_rules! delegating_ascii_methods {
() => {
#[inline]
fn is_ascii(&self) -> bool { self.is_ascii() }
#[inline]
fn to_ascii_uppercase(&self) -> Self::Owned { self.to_ascii_uppercase() }
#[inline]
fn to_ascii_lowercase(&self) -> Self::Owned { self.to_ascii_lowercase() }
#[inline]
fn eq_ignore_ascii_case(&self, o: &Self) -> bool { self.eq_ignore_ascii_case(o) }
#[inline]
fn make_ascii_uppercase(&mut self) { self.make_ascii_uppercase(); }
#[inline]
fn make_ascii_lowercase(&mut self) { self.make_ascii_lowercase(); }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(deprecated)]
impl AsciiExt for u8 {
type Owned = u8;
delegating_ascii_methods!();
}
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(deprecated)]
impl AsciiExt for char {
type Owned = char;
|
delegating_ascii_methods!();
}
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(deprecated)]
impl AsciiExt for [u8] {
type Owned = Vec<u8>;
delegating_ascii_methods!();
}
#[stable(feature = "rust1", since = "1.0.0")]
#[allow(deprecated)]
impl AsciiExt for str {
type Owned = String;
delegating_ascii_methods!();
}
|
random_line_split
|
|
mut.rs
|
#[allow(dead_code)]
#[derive(Clone, Copy)]
struct Book {
// `&'static str` is a reference to a string allocated in read only memory
author: &'static str,
title: &'static str,
year: u32,
}
// This function takes a reference to a book
fn borrow_book(book: &Book) {
println!("I borrowed {} {} edition", book.title, book.year);
}
// This function takes a reference to a mutable book
fn new_edition(book: &mut Book)
|
fn main() {
// An immutable Book
let geb = Book {
// string literals have type `&'static str`
author: "Douglas Hofstadter",
title: "Gödel, Escher, Bach",
year: 1979,
};
// Immutably borrow `geb`
borrow_book(&geb);
// Error! Can't borrow an immutable object as mutable
new_edition(&mut geb);
// FIXME ^ Comment out this line
// `mutable_geb` is a mutable copy of `geb`
let mut mutable_geb = geb;
// Borrow a mutable object as mutable
new_edition(&mut mutable_geb);
// Mutable objects can be immutably borrowed
borrow_book(&mutable_geb);
}
|
{
// the fields of the book can be modified
book.year = 2014;
}
|
identifier_body
|
mut.rs
|
#[allow(dead_code)]
#[derive(Clone, Copy)]
struct Book {
// `&'static str` is a reference to a string allocated in read only memory
author: &'static str,
title: &'static str,
year: u32,
}
// This function takes a reference to a book
fn borrow_book(book: &Book) {
println!("I borrowed {} {} edition", book.title, book.year);
}
// This function takes a reference to a mutable book
fn
|
(book: &mut Book) {
// the fields of the book can be modified
book.year = 2014;
}
fn main() {
// An immutable Book
let geb = Book {
// string literals have type `&'static str`
author: "Douglas Hofstadter",
title: "Gödel, Escher, Bach",
year: 1979,
};
// Immutably borrow `geb`
borrow_book(&geb);
// Error! Can't borrow an immutable object as mutable
new_edition(&mut geb);
// FIXME ^ Comment out this line
// `mutable_geb` is a mutable copy of `geb`
let mut mutable_geb = geb;
// Borrow a mutable object as mutable
new_edition(&mut mutable_geb);
// Mutable objects can be immutably borrowed
borrow_book(&mutable_geb);
}
|
new_edition
|
identifier_name
|
mut.rs
|
#[allow(dead_code)]
#[derive(Clone, Copy)]
struct Book {
|
author: &'static str,
title: &'static str,
year: u32,
}
// This function takes a reference to a book
fn borrow_book(book: &Book) {
println!("I borrowed {} {} edition", book.title, book.year);
}
// This function takes a reference to a mutable book
fn new_edition(book: &mut Book) {
// the fields of the book can be modified
book.year = 2014;
}
fn main() {
// An immutable Book
let geb = Book {
// string literals have type `&'static str`
author: "Douglas Hofstadter",
title: "Gödel, Escher, Bach",
year: 1979,
};
// Immutably borrow `geb`
borrow_book(&geb);
// Error! Can't borrow an immutable object as mutable
new_edition(&mut geb);
// FIXME ^ Comment out this line
// `mutable_geb` is a mutable copy of `geb`
let mut mutable_geb = geb;
// Borrow a mutable object as mutable
new_edition(&mut mutable_geb);
// Mutable objects can be immutably borrowed
borrow_book(&mutable_geb);
}
|
// `&'static str` is a reference to a string allocated in read only memory
|
random_line_split
|
mod.rs
|
pub mod button;
pub mod frame;
pub mod region;
pub struct Widget;
impl Widget {
fn
|
() -> Widget {
Widget
}
}
pub trait UIObject {
fn get_name(&self) -> String;
//fn get_object_type() -> String;
//fn is_object_type(type_: &str) -> String;
fn draw(&self);
}
pub trait ParentObject: UIObject {
/// Returns the object's parent object.
fn get_parent();
}
pub trait VisibleRegion: ParentObject {
/// Returns the opacity of the region relative to it's parent.
fn get_alpha();
/// Hides the region.
fn hide();
/// Returns whether the region is shown.
fn is_shown();
/// Returns whether the region is visible.
fn is_visible();
/// Sets the opacity of the region relative to its parent.
fn set_alpha();
/// Shows the region.
fn show();
}
|
new_inherited
|
identifier_name
|
mod.rs
|
pub mod button;
pub mod frame;
pub mod region;
pub struct Widget;
impl Widget {
fn new_inherited() -> Widget
|
}
pub trait UIObject {
fn get_name(&self) -> String;
//fn get_object_type() -> String;
//fn is_object_type(type_: &str) -> String;
fn draw(&self);
}
pub trait ParentObject: UIObject {
/// Returns the object's parent object.
fn get_parent();
}
pub trait VisibleRegion: ParentObject {
/// Returns the opacity of the region relative to it's parent.
fn get_alpha();
/// Hides the region.
fn hide();
/// Returns whether the region is shown.
fn is_shown();
/// Returns whether the region is visible.
fn is_visible();
/// Sets the opacity of the region relative to its parent.
fn set_alpha();
/// Shows the region.
fn show();
}
|
{
Widget
}
|
identifier_body
|
lib.rs
|
//! # SabiWM - 錆WM (Rust WM)
//!
//! SabiWM is a window manager written entirely in safe Rust.
//! It aims to be a reliable, highly customizable tiling window manager
//! in the spirit of XMonad, I3, bspwm and the like.
//!
//! ## SabiWM Lib
//!
//! The core part of SabiWM is its library. It serves as a
//! learning basis for people who want to write their own window manager
//! or as an easy place to customize it.
//!
//! The library itself is split into several parts, shortly explained below:
//!
//! ### Core
//!
//! The [`Core`] module
//!
//! The core module contains all the necessary data structures to handle the internal
//! state to tile windows, manage focus, screens, workspaces, etc.
//!
//! ### Backend
//!
//! The backend module contains the general backend trait to abstract
//! away from all the different backends, e.g. XCB, Wayland, Redox and all the others out there.
//!
//! ### Config
//!
//! The config module will contain several ways to configure the WM. All of them shall
//! be interchangeable. The first and easiest way is a simple TOML file and on top of that
//! a ctl daemon, a LUA interface and direct IPC.
//!
//! [`Core`]: core/index.html
//! ['Backend']: backend/index.html
#![deny(missing_docs)]
extern crate chrono;
#[macro_use]
extern crate error_chain;
extern crate fern;
#[macro_use]
extern crate log;
extern crate xcb;
extern crate xdg;
#[macro_use]
mod macros;
pub mod backend;
pub mod core;
mod errors {
error_chain!{
foreign_links {
Io(::std::io::Error);
Log(::log::SetLoggerError);
}
}
}
use errors::*;
use backend::{Backend, Event};
use xdg::BaseDirectories;
/// Run the actual window manager
pub fn run() -> Result<()> {
|
}
}
/// Initialize the logger
pub fn initialize_logger() -> Result<()> {
let xdg = BaseDirectories::with_prefix("sabiwm")
.chain_err(|| "unable to get xdg base directory")?;
let path = xdg.place_cache_file("sabiwm.log")
.chain_err(|| "unable to get path for log file")?;
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!("{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.target(),
record.level(),
message))
})
.level(log::LogLevelFilter::Debug)
.chain(std::io::stdout())
.chain(fern::log_file(path)?)
.apply()?;
info!("initialized logger");
info!("sabiwm version {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
|
initialize_logger()
.chain_err(|| "unable to initialize logger")?;
let xcb = backend::Xcb::new()?;
let mut workspace: core::Workspace<u32> = core::Workspace::new(0, "Main", None);
loop {
match xcb.event() {
Event::WindowCreated(window) => {
if !xcb.is_window(window) {
continue;
}
xcb.resize_window(window, 50, 50);
workspace = workspace.add(window);
}
Event::WindowClosed(window) => {
workspace = workspace.remove(window);
}
_ => (),
}
|
identifier_body
|
lib.rs
|
//! # SabiWM - 錆WM (Rust WM)
//!
//! SabiWM is a window manager written entirely in safe Rust.
//! It aims to be a reliable, highly customizable tiling window manager
//! in the spirit of XMonad, I3, bspwm and the like.
//!
//! ## SabiWM Lib
//!
//! The core part of SabiWM is its library. It serves as a
//! learning basis for people who want to write their own window manager
//! or as an easy place to customize it.
//!
//! The library itself is split into several parts, shortly explained below:
//!
//! ### Core
//!
//! The [`Core`] module
//!
//! The core module contains all the necessary data structures to handle the internal
//! state to tile windows, manage focus, screens, workspaces, etc.
//!
//! ### Backend
//!
//! The backend module contains the general backend trait to abstract
//! away from all the different backends, e.g. XCB, Wayland, Redox and all the others out there.
//!
//! ### Config
//!
//! The config module will contain several ways to configure the WM. All of them shall
//! be interchangeable. The first and easiest way is a simple TOML file and on top of that
//! a ctl daemon, a LUA interface and direct IPC.
//!
//! [`Core`]: core/index.html
//! ['Backend']: backend/index.html
#![deny(missing_docs)]
extern crate chrono;
#[macro_use]
extern crate error_chain;
extern crate fern;
#[macro_use]
extern crate log;
extern crate xcb;
extern crate xdg;
#[macro_use]
mod macros;
pub mod backend;
pub mod core;
mod errors {
error_chain!{
foreign_links {
Io(::std::io::Error);
Log(::log::SetLoggerError);
}
}
}
use errors::*;
use backend::{Backend, Event};
use xdg::BaseDirectories;
/// Run the actual window manager
pub fn run() -> Result<()> {
initialize_logger()
.chain_err(|| "unable to initialize logger")?;
let xcb = backend::Xcb::new()?;
let mut workspace: core::Workspace<u32> = core::Workspace::new(0, "Main", None);
loop {
match xcb.event() {
Event::WindowCreated(window) => {
if!xcb.is_window(window) {
continue;
}
xcb.resize_window(window, 50, 50);
workspace = workspace.add(window);
}
Event::WindowClosed(window) => {
|
_ => (),
}
}
}
/// Initialize the logger
pub fn initialize_logger() -> Result<()> {
let xdg = BaseDirectories::with_prefix("sabiwm")
.chain_err(|| "unable to get xdg base directory")?;
let path = xdg.place_cache_file("sabiwm.log")
.chain_err(|| "unable to get path for log file")?;
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!("{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.target(),
record.level(),
message))
})
.level(log::LogLevelFilter::Debug)
.chain(std::io::stdout())
.chain(fern::log_file(path)?)
.apply()?;
info!("initialized logger");
info!("sabiwm version {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
|
workspace = workspace.remove(window);
}
|
conditional_block
|
lib.rs
|
//! # SabiWM - 錆WM (Rust WM)
//!
//! SabiWM is a window manager written entirely in safe Rust.
//! It aims to be a reliable, highly customizable tiling window manager
//! in the spirit of XMonad, I3, bspwm and the like.
//!
//! ## SabiWM Lib
//!
//! The core part of SabiWM is its library. It serves as a
//! learning basis for people who want to write their own window manager
//! or as an easy place to customize it.
//!
//! The library itself is split into several parts, shortly explained below:
//!
//! ### Core
//!
//! The [`Core`] module
//!
//! The core module contains all the necessary data structures to handle the internal
//! state to tile windows, manage focus, screens, workspaces, etc.
//!
//! ### Backend
//!
//! The backend module contains the general backend trait to abstract
//! away from all the different backends, e.g. XCB, Wayland, Redox and all the others out there.
//!
//! ### Config
//!
//! The config module will contain several ways to configure the WM. All of them shall
//! be interchangeable. The first and easiest way is a simple TOML file and on top of that
//! a ctl daemon, a LUA interface and direct IPC.
//!
//! [`Core`]: core/index.html
//! ['Backend']: backend/index.html
#![deny(missing_docs)]
extern crate chrono;
#[macro_use]
extern crate error_chain;
extern crate fern;
#[macro_use]
extern crate log;
extern crate xcb;
extern crate xdg;
#[macro_use]
mod macros;
pub mod backend;
pub mod core;
mod errors {
error_chain!{
foreign_links {
Io(::std::io::Error);
Log(::log::SetLoggerError);
}
}
}
use errors::*;
use backend::{Backend, Event};
use xdg::BaseDirectories;
/// Run the actual window manager
pub fn run() -> Result<()> {
initialize_logger()
.chain_err(|| "unable to initialize logger")?;
let xcb = backend::Xcb::new()?;
let mut workspace: core::Workspace<u32> = core::Workspace::new(0, "Main", None);
loop {
match xcb.event() {
Event::WindowCreated(window) => {
if!xcb.is_window(window) {
continue;
}
xcb.resize_window(window, 50, 50);
workspace = workspace.add(window);
}
Event::WindowClosed(window) => {
workspace = workspace.remove(window);
}
_ => (),
}
}
}
/// Initialize the logger
pub fn in
|
-> Result<()> {
let xdg = BaseDirectories::with_prefix("sabiwm")
.chain_err(|| "unable to get xdg base directory")?;
let path = xdg.place_cache_file("sabiwm.log")
.chain_err(|| "unable to get path for log file")?;
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!("{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.target(),
record.level(),
message))
})
.level(log::LogLevelFilter::Debug)
.chain(std::io::stdout())
.chain(fern::log_file(path)?)
.apply()?;
info!("initialized logger");
info!("sabiwm version {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
|
itialize_logger()
|
identifier_name
|
lib.rs
|
//! # SabiWM - 錆WM (Rust WM)
//!
//! SabiWM is a window manager written entirely in safe Rust.
//! It aims to be a reliable, highly customizable tiling window manager
//! in the spirit of XMonad, I3, bspwm and the like.
//!
//! ## SabiWM Lib
//!
//! The core part of SabiWM is its library. It serves as a
//! learning basis for people who want to write their own window manager
//! or as an easy place to customize it.
//!
//! The library itself is split into several parts, shortly explained below:
//!
//! ### Core
//!
//! The [`Core`] module
//!
//! The core module contains all the necessary data structures to handle the internal
//! state to tile windows, manage focus, screens, workspaces, etc.
//!
//! ### Backend
//!
//! The backend module contains the general backend trait to abstract
//! away from all the different backends, e.g. XCB, Wayland, Redox and all the others out there.
//!
//! ### Config
//!
//! The config module will contain several ways to configure the WM. All of them shall
//! be interchangeable. The first and easiest way is a simple TOML file and on top of that
//! a ctl daemon, a LUA interface and direct IPC.
//!
//! [`Core`]: core/index.html
//! ['Backend']: backend/index.html
#![deny(missing_docs)]
extern crate chrono;
#[macro_use]
extern crate error_chain;
extern crate fern;
#[macro_use]
extern crate log;
extern crate xcb;
extern crate xdg;
#[macro_use]
mod macros;
pub mod backend;
pub mod core;
mod errors {
error_chain!{
foreign_links {
Io(::std::io::Error);
Log(::log::SetLoggerError);
}
}
}
use errors::*;
use backend::{Backend, Event};
use xdg::BaseDirectories;
/// Run the actual window manager
pub fn run() -> Result<()> {
initialize_logger()
.chain_err(|| "unable to initialize logger")?;
let xcb = backend::Xcb::new()?;
let mut workspace: core::Workspace<u32> = core::Workspace::new(0, "Main", None);
|
Event::WindowCreated(window) => {
if!xcb.is_window(window) {
continue;
}
xcb.resize_window(window, 50, 50);
workspace = workspace.add(window);
}
Event::WindowClosed(window) => {
workspace = workspace.remove(window);
}
_ => (),
}
}
}
/// Initialize the logger
pub fn initialize_logger() -> Result<()> {
let xdg = BaseDirectories::with_prefix("sabiwm")
.chain_err(|| "unable to get xdg base directory")?;
let path = xdg.place_cache_file("sabiwm.log")
.chain_err(|| "unable to get path for log file")?;
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!("{}[{}][{}] {}",
chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"),
record.target(),
record.level(),
message))
})
.level(log::LogLevelFilter::Debug)
.chain(std::io::stdout())
.chain(fern::log_file(path)?)
.apply()?;
info!("initialized logger");
info!("sabiwm version {}", env!("CARGO_PKG_VERSION"));
Ok(())
}
|
loop {
match xcb.event() {
|
random_line_split
|
testworklet.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
// check-tidy: no specs after this line
use crate::dom::bindings::codegen::Bindings::TestWorkletBinding::TestWorkletMethods;
use crate::dom::bindings::codegen::Bindings::WorkletBinding::WorkletBinding::WorkletMethods;
use crate::dom::bindings::codegen::Bindings::WorkletBinding::WorkletOptions;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::reflector::Reflector;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::str::USVString;
use crate::dom::promise::Promise;
use crate::dom::window::Window;
use crate::dom::worklet::Worklet;
use crate::dom::workletglobalscope::WorkletGlobalScopeType;
use crate::realms::InRealm;
use crate::script_thread::ScriptThread;
use dom_struct::dom_struct;
use std::rc::Rc;
#[dom_struct]
pub struct TestWorklet {
reflector: Reflector,
worklet: Dom<Worklet>,
}
impl TestWorklet {
fn new_inherited(worklet: &Worklet) -> TestWorklet {
TestWorklet {
reflector: Reflector::new(),
worklet: Dom::from_ref(worklet),
}
}
fn new(window: &Window) -> DomRoot<TestWorklet> {
let worklet = Worklet::new(window, WorkletGlobalScopeType::Test);
reflect_dom_object(Box::new(TestWorklet::new_inherited(&*worklet)), window)
}
#[allow(non_snake_case)]
pub fn Constructor(window: &Window) -> Fallible<DomRoot<TestWorklet>> {
Ok(TestWorklet::new(window))
}
}
impl TestWorkletMethods for TestWorklet {
#[allow(non_snake_case)]
fn AddModule(
&self,
moduleURL: USVString,
options: &WorkletOptions,
comp: InRealm,
) -> Rc<Promise> {
self.worklet.AddModule(moduleURL, options, comp)
}
fn Lookup(&self, key: DOMString) -> Option<DOMString>
|
}
|
{
let id = self.worklet.worklet_id();
let pool = ScriptThread::worklet_thread_pool();
pool.test_worklet_lookup(id, String::from(key))
.map(DOMString::from)
}
|
identifier_body
|
testworklet.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
// check-tidy: no specs after this line
use crate::dom::bindings::codegen::Bindings::TestWorkletBinding::TestWorkletMethods;
use crate::dom::bindings::codegen::Bindings::WorkletBinding::WorkletBinding::WorkletMethods;
use crate::dom::bindings::codegen::Bindings::WorkletBinding::WorkletOptions;
|
use crate::dom::bindings::str::USVString;
use crate::dom::promise::Promise;
use crate::dom::window::Window;
use crate::dom::worklet::Worklet;
use crate::dom::workletglobalscope::WorkletGlobalScopeType;
use crate::realms::InRealm;
use crate::script_thread::ScriptThread;
use dom_struct::dom_struct;
use std::rc::Rc;
#[dom_struct]
pub struct TestWorklet {
reflector: Reflector,
worklet: Dom<Worklet>,
}
impl TestWorklet {
fn new_inherited(worklet: &Worklet) -> TestWorklet {
TestWorklet {
reflector: Reflector::new(),
worklet: Dom::from_ref(worklet),
}
}
fn new(window: &Window) -> DomRoot<TestWorklet> {
let worklet = Worklet::new(window, WorkletGlobalScopeType::Test);
reflect_dom_object(Box::new(TestWorklet::new_inherited(&*worklet)), window)
}
#[allow(non_snake_case)]
pub fn Constructor(window: &Window) -> Fallible<DomRoot<TestWorklet>> {
Ok(TestWorklet::new(window))
}
}
impl TestWorkletMethods for TestWorklet {
#[allow(non_snake_case)]
fn AddModule(
&self,
moduleURL: USVString,
options: &WorkletOptions,
comp: InRealm,
) -> Rc<Promise> {
self.worklet.AddModule(moduleURL, options, comp)
}
fn Lookup(&self, key: DOMString) -> Option<DOMString> {
let id = self.worklet.worklet_id();
let pool = ScriptThread::worklet_thread_pool();
pool.test_worklet_lookup(id, String::from(key))
.map(DOMString::from)
}
}
|
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::reflector::Reflector;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
|
random_line_split
|
testworklet.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
// check-tidy: no specs after this line
use crate::dom::bindings::codegen::Bindings::TestWorkletBinding::TestWorkletMethods;
use crate::dom::bindings::codegen::Bindings::WorkletBinding::WorkletBinding::WorkletMethods;
use crate::dom::bindings::codegen::Bindings::WorkletBinding::WorkletOptions;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::reflector::Reflector;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::str::USVString;
use crate::dom::promise::Promise;
use crate::dom::window::Window;
use crate::dom::worklet::Worklet;
use crate::dom::workletglobalscope::WorkletGlobalScopeType;
use crate::realms::InRealm;
use crate::script_thread::ScriptThread;
use dom_struct::dom_struct;
use std::rc::Rc;
#[dom_struct]
pub struct TestWorklet {
reflector: Reflector,
worklet: Dom<Worklet>,
}
impl TestWorklet {
fn new_inherited(worklet: &Worklet) -> TestWorklet {
TestWorklet {
reflector: Reflector::new(),
worklet: Dom::from_ref(worklet),
}
}
fn new(window: &Window) -> DomRoot<TestWorklet> {
let worklet = Worklet::new(window, WorkletGlobalScopeType::Test);
reflect_dom_object(Box::new(TestWorklet::new_inherited(&*worklet)), window)
}
#[allow(non_snake_case)]
pub fn Constructor(window: &Window) -> Fallible<DomRoot<TestWorklet>> {
Ok(TestWorklet::new(window))
}
}
impl TestWorkletMethods for TestWorklet {
#[allow(non_snake_case)]
fn AddModule(
&self,
moduleURL: USVString,
options: &WorkletOptions,
comp: InRealm,
) -> Rc<Promise> {
self.worklet.AddModule(moduleURL, options, comp)
}
fn
|
(&self, key: DOMString) -> Option<DOMString> {
let id = self.worklet.worklet_id();
let pool = ScriptThread::worklet_thread_pool();
pool.test_worklet_lookup(id, String::from(key))
.map(DOMString::from)
}
}
|
Lookup
|
identifier_name
|
mod.rs
|
use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
mod password;
use self::password::Password;
pub use self::password::{
CreationError as PasswordCreationError, PlaintextPassword, ValidationError, VerificationError,
};
use schema::local_auth;
use user::{AuthenticatedUser, UnauthenticatedUser, UnverifiedUser};
/// `LocalAuth` can be queried from the database, but is only really usable as a tool to "log in" a
/// user.
#[derive(Debug, Queryable, QueryableByName)]
#[table_name = "local_auth"]
pub struct LocalAuth {
id: i32,
password: Password,
user_id: i32, // foreign key to User
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
}
impl LocalAuth {
pub fn id(&self) -> i32 {
self.id
}
pub fn created_at(&self) -> DateTime<Utc> {
self.created_at
}
pub fn user_id(&self) -> i32 {
self.user_id
}
/// Log In a user, given an `UnauthenticatedUser` and a `PlaintextPassword`.
///
/// This method ensures first that the `UnauthenticatedUser` is the same user that this
/// `LocalAuth` is associated with, and then continues to verify the `PlaintextPassword`
/// against this type's `Password`. Upon succesful password verification, an
/// `AuthenticatedUser` is created.
pub(crate) fn log_in(
self,
user: UnauthenticatedUser,
password: PlaintextPassword,
) -> Result<AuthenticatedUser, VerificationError> {
use self::password::Verify;
|
if self.user_id!= user.id {
return Err(VerificationError::Process);
}
self.password.verify(password).map(|_| AuthenticatedUser {
id: user.id,
primary_email: user.primary_email,
created_at: user.created_at,
updated_at: user.updated_at,
})
}
}
/// This type exists to create new `LocalAuth` record in the database.
#[derive(Insertable)]
#[table_name = "local_auth"]
pub struct NewLocalAuth {
password: Password,
created_at: DateTime<Utc>,
user_id: i32,
}
impl NewLocalAuth {
/// Insert into the database
pub fn insert(self, conn: &PgConnection) -> Result<LocalAuth, diesel::result::Error> {
use diesel::prelude::*;
diesel::insert_into(local_auth::table)
.values(&self)
.get_result(conn)
}
/// Create a `NewLocalAuth`
pub fn new(
user: &UnverifiedUser,
password: PlaintextPassword,
) -> Result<Self, PasswordCreationError> {
use self::password::Validate;
let password = password.validate()?;
NewLocalAuth::create(user, password)
}
/// Create a `NewLocalAuth` with a redundant password to check for consistency.
pub fn new_from_two(
user: &UnverifiedUser,
password: PlaintextPassword,
password2: PlaintextPassword,
) -> Result<Self, PasswordCreationError> {
use self::password::Validate;
let password = password
.validate()
.and_then(|password| password.compare(password2))?;
NewLocalAuth::create(user, password)
}
fn create(
user: &UnverifiedUser,
password: PlaintextPassword,
) -> Result<Self, PasswordCreationError> {
use self::password::Create;
let password = Password::create(password)?;
Ok(NewLocalAuth {
password: password,
created_at: Utc::now(),
user_id: user.id,
})
}
}
#[cfg(test)]
mod tests {
use super::NewLocalAuth;
use test_helper::*;
#[test]
fn create_local_auth() {
with_connection(|conn| {
with_unverified_user(conn, |user| {
let password = "testpass";
with_local_auth(conn, &user, password, |_| Ok(()))
})
})
}
#[test]
fn dont_create_local_auth_with_invalid_password() {
with_connection(|conn| {
with_unverified_user(conn, |user| {
let password = create_plaintext_password("short")?;
let local_auth = NewLocalAuth::new(&user, password);
assert!(
local_auth.is_err(),
"Should not have created local auth with bad password"
);
Ok(())
})
})
}
#[test]
fn dont_create_local_auth_with_mismatched_passwords() {
with_connection(|conn| {
with_unverified_user(conn, |user| {
let p1 = create_plaintext_password("agoodpassword")?;
let p2 = create_plaintext_password("abadpassword")?;
let local_auth = NewLocalAuth::new_from_two(&user, p1, p2);
assert!(
local_auth.is_err(),
"Should not have created LocalAuth from mismatched passwords"
);
Ok(())
})
})
}
}
|
random_line_split
|
|
mod.rs
|
use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
mod password;
use self::password::Password;
pub use self::password::{
CreationError as PasswordCreationError, PlaintextPassword, ValidationError, VerificationError,
};
use schema::local_auth;
use user::{AuthenticatedUser, UnauthenticatedUser, UnverifiedUser};
/// `LocalAuth` can be queried from the database, but is only really usable as a tool to "log in" a
/// user.
#[derive(Debug, Queryable, QueryableByName)]
#[table_name = "local_auth"]
pub struct LocalAuth {
id: i32,
password: Password,
user_id: i32, // foreign key to User
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
}
impl LocalAuth {
pub fn id(&self) -> i32 {
self.id
}
pub fn created_at(&self) -> DateTime<Utc> {
self.created_at
}
pub fn user_id(&self) -> i32 {
self.user_id
}
/// Log In a user, given an `UnauthenticatedUser` and a `PlaintextPassword`.
///
/// This method ensures first that the `UnauthenticatedUser` is the same user that this
/// `LocalAuth` is associated with, and then continues to verify the `PlaintextPassword`
/// against this type's `Password`. Upon succesful password verification, an
/// `AuthenticatedUser` is created.
pub(crate) fn log_in(
self,
user: UnauthenticatedUser,
password: PlaintextPassword,
) -> Result<AuthenticatedUser, VerificationError> {
use self::password::Verify;
if self.user_id!= user.id {
return Err(VerificationError::Process);
}
self.password.verify(password).map(|_| AuthenticatedUser {
id: user.id,
primary_email: user.primary_email,
created_at: user.created_at,
updated_at: user.updated_at,
})
}
}
/// This type exists to create new `LocalAuth` record in the database.
#[derive(Insertable)]
#[table_name = "local_auth"]
pub struct NewLocalAuth {
password: Password,
created_at: DateTime<Utc>,
user_id: i32,
}
impl NewLocalAuth {
/// Insert into the database
pub fn insert(self, conn: &PgConnection) -> Result<LocalAuth, diesel::result::Error> {
use diesel::prelude::*;
diesel::insert_into(local_auth::table)
.values(&self)
.get_result(conn)
}
/// Create a `NewLocalAuth`
pub fn new(
user: &UnverifiedUser,
password: PlaintextPassword,
) -> Result<Self, PasswordCreationError> {
use self::password::Validate;
let password = password.validate()?;
NewLocalAuth::create(user, password)
}
/// Create a `NewLocalAuth` with a redundant password to check for consistency.
pub fn
|
(
user: &UnverifiedUser,
password: PlaintextPassword,
password2: PlaintextPassword,
) -> Result<Self, PasswordCreationError> {
use self::password::Validate;
let password = password
.validate()
.and_then(|password| password.compare(password2))?;
NewLocalAuth::create(user, password)
}
fn create(
user: &UnverifiedUser,
password: PlaintextPassword,
) -> Result<Self, PasswordCreationError> {
use self::password::Create;
let password = Password::create(password)?;
Ok(NewLocalAuth {
password: password,
created_at: Utc::now(),
user_id: user.id,
})
}
}
#[cfg(test)]
mod tests {
use super::NewLocalAuth;
use test_helper::*;
#[test]
fn create_local_auth() {
with_connection(|conn| {
with_unverified_user(conn, |user| {
let password = "testpass";
with_local_auth(conn, &user, password, |_| Ok(()))
})
})
}
#[test]
fn dont_create_local_auth_with_invalid_password() {
with_connection(|conn| {
with_unverified_user(conn, |user| {
let password = create_plaintext_password("short")?;
let local_auth = NewLocalAuth::new(&user, password);
assert!(
local_auth.is_err(),
"Should not have created local auth with bad password"
);
Ok(())
})
})
}
#[test]
fn dont_create_local_auth_with_mismatched_passwords() {
with_connection(|conn| {
with_unverified_user(conn, |user| {
let p1 = create_plaintext_password("agoodpassword")?;
let p2 = create_plaintext_password("abadpassword")?;
let local_auth = NewLocalAuth::new_from_two(&user, p1, p2);
assert!(
local_auth.is_err(),
"Should not have created LocalAuth from mismatched passwords"
);
Ok(())
})
})
}
}
|
new_from_two
|
identifier_name
|
mod.rs
|
use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
mod password;
use self::password::Password;
pub use self::password::{
CreationError as PasswordCreationError, PlaintextPassword, ValidationError, VerificationError,
};
use schema::local_auth;
use user::{AuthenticatedUser, UnauthenticatedUser, UnverifiedUser};
/// `LocalAuth` can be queried from the database, but is only really usable as a tool to "log in" a
/// user.
#[derive(Debug, Queryable, QueryableByName)]
#[table_name = "local_auth"]
pub struct LocalAuth {
id: i32,
password: Password,
user_id: i32, // foreign key to User
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
}
impl LocalAuth {
pub fn id(&self) -> i32 {
self.id
}
pub fn created_at(&self) -> DateTime<Utc> {
self.created_at
}
pub fn user_id(&self) -> i32 {
self.user_id
}
/// Log In a user, given an `UnauthenticatedUser` and a `PlaintextPassword`.
///
/// This method ensures first that the `UnauthenticatedUser` is the same user that this
/// `LocalAuth` is associated with, and then continues to verify the `PlaintextPassword`
/// against this type's `Password`. Upon succesful password verification, an
/// `AuthenticatedUser` is created.
pub(crate) fn log_in(
self,
user: UnauthenticatedUser,
password: PlaintextPassword,
) -> Result<AuthenticatedUser, VerificationError> {
use self::password::Verify;
if self.user_id!= user.id
|
self.password.verify(password).map(|_| AuthenticatedUser {
id: user.id,
primary_email: user.primary_email,
created_at: user.created_at,
updated_at: user.updated_at,
})
}
}
/// This type exists to create new `LocalAuth` record in the database.
#[derive(Insertable)]
#[table_name = "local_auth"]
pub struct NewLocalAuth {
password: Password,
created_at: DateTime<Utc>,
user_id: i32,
}
impl NewLocalAuth {
/// Insert into the database
pub fn insert(self, conn: &PgConnection) -> Result<LocalAuth, diesel::result::Error> {
use diesel::prelude::*;
diesel::insert_into(local_auth::table)
.values(&self)
.get_result(conn)
}
/// Create a `NewLocalAuth`
pub fn new(
user: &UnverifiedUser,
password: PlaintextPassword,
) -> Result<Self, PasswordCreationError> {
use self::password::Validate;
let password = password.validate()?;
NewLocalAuth::create(user, password)
}
/// Create a `NewLocalAuth` with a redundant password to check for consistency.
pub fn new_from_two(
user: &UnverifiedUser,
password: PlaintextPassword,
password2: PlaintextPassword,
) -> Result<Self, PasswordCreationError> {
use self::password::Validate;
let password = password
.validate()
.and_then(|password| password.compare(password2))?;
NewLocalAuth::create(user, password)
}
fn create(
user: &UnverifiedUser,
password: PlaintextPassword,
) -> Result<Self, PasswordCreationError> {
use self::password::Create;
let password = Password::create(password)?;
Ok(NewLocalAuth {
password: password,
created_at: Utc::now(),
user_id: user.id,
})
}
}
#[cfg(test)]
mod tests {
use super::NewLocalAuth;
use test_helper::*;
#[test]
fn create_local_auth() {
with_connection(|conn| {
with_unverified_user(conn, |user| {
let password = "testpass";
with_local_auth(conn, &user, password, |_| Ok(()))
})
})
}
#[test]
fn dont_create_local_auth_with_invalid_password() {
with_connection(|conn| {
with_unverified_user(conn, |user| {
let password = create_plaintext_password("short")?;
let local_auth = NewLocalAuth::new(&user, password);
assert!(
local_auth.is_err(),
"Should not have created local auth with bad password"
);
Ok(())
})
})
}
#[test]
fn dont_create_local_auth_with_mismatched_passwords() {
with_connection(|conn| {
with_unverified_user(conn, |user| {
let p1 = create_plaintext_password("agoodpassword")?;
let p2 = create_plaintext_password("abadpassword")?;
let local_auth = NewLocalAuth::new_from_two(&user, p1, p2);
assert!(
local_auth.is_err(),
"Should not have created LocalAuth from mismatched passwords"
);
Ok(())
})
})
}
}
|
{
return Err(VerificationError::Process);
}
|
conditional_block
|
lib.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/. */
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead of in script so that these modules won't have
//! to depend on script.
#![feature(custom_derive, plugin)]
#![plugin(plugins, serde_macros)]
#![deny(missing_docs)]
extern crate app_units;
extern crate canvas_traits;
extern crate devtools_traits;
extern crate euclid;
extern crate ipc_channel;
extern crate libc;
extern crate msg;
extern crate net_traits;
extern crate offscreen_gl_context;
extern crate profile_traits;
extern crate serde;
extern crate style_traits;
extern crate time;
extern crate url;
extern crate util;
mod script_msg;
use app_units::Au;
use devtools_traits::ScriptToDevtoolsControlMsg;
use euclid::length::Length;
use euclid::point::Point2D;
use euclid::rect::Rect;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use libc::c_void;
use msg::compositor_msg::{Epoch, LayerId, ScriptToCompositorMsg};
use msg::constellation_msg::{ConstellationChan, Failure, PipelineId, WindowSizeData};
use msg::constellation_msg::{Key, KeyModifiers, KeyState, LoadData, SubpageId};
use msg::constellation_msg::{MouseButton, MouseEventType};
use msg::constellation_msg::{MozBrowserEvent, PipelineNamespaceId};
use msg::webdriver_msg::WebDriverScriptCommand;
use net_traits::ResourceTask;
use net_traits::image_cache_task::ImageCacheTask;
use net_traits::storage_task::StorageTask;
use profile_traits::mem;
use std::any::Any;
use util::ipc::OptionalOpaqueIpcSender;
use util::mem::HeapSizeOf;
pub use script_msg::ScriptMsg;
/// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
#[derive(Copy, Clone, Debug)]
pub struct UntrustedNodeAddress(pub *const c_void);
unsafe impl Send for UntrustedNodeAddress {}
/// Messages sent to the layout task from the constellation and/or compositor.
#[derive(Deserialize, Serialize)]
pub enum LayoutControlMsg {
/// Requests that this layout task exit.
ExitNow,
/// Requests the current epoch (layout counter) from this layout.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks layout to run another step in its animation.
TickAnimations,
/// Informs layout as to which regions of the page are visible.
SetVisibleRects(Vec<(LayerId, Rect<Au>)>),
/// Requests the current load state of Web fonts. `true` is returned if fonts are still loading
/// and `false` is returned if all fonts have loaded.
GetWebFontLoadState(IpcSender<bool>),
}
/// The initial data associated with a newly-created framed pipeline.
#[derive(Deserialize, Serialize)]
pub struct NewLayoutInfo {
/// Id of the parent of this new pipeline.
pub containing_pipeline_id: PipelineId,
/// Id of the newly-created pipeline.
pub new_pipeline_id: PipelineId,
/// Id of the new frame associated with this pipeline.
pub subpage_id: SubpageId,
/// Network request data which will be initiated by the script task.
pub load_data: LoadData,
/// The paint channel, cast to `OptionalOpaqueIpcSender`. This is really an
/// `Sender<LayoutToPaintMsg>`.
pub paint_chan: OptionalOpaqueIpcSender,
/// Information on what to do on task failure.
pub failure: Failure,
/// A port on which layout can receive messages from the pipeline.
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
/// A shutdown channel so that layout can notify others when it's done.
pub layout_shutdown_chan: IpcSender<()>,
/// A shutdown channel so that layout can tell the content process to shut down when it's done.
pub content_process_shutdown_chan: IpcSender<()>,
}
/// Used to determine if a script has any pending asynchronous activity.
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize)]
pub enum ScriptState {
/// The document has been loaded.
DocumentLoaded,
/// The document is still loading.
DocumentLoading,
}
/// Messages sent from the constellation or layout to the script task.
#[derive(Deserialize, Serialize)]
pub enum ConstellationControlMsg {
/// Gives a channel and ID to a layout task, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId),
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Requests that the script task immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script task to suspend all its timers
Freeze(PipelineId),
/// Notifies script task to resume all its timers
Thaw(PipelineId),
/// Notifies script task that a url should be loaded in this iframe.
Navigate(PipelineId, SubpageId, LoadData),
/// Requests the script task forward a mozbrowser event to an iframe it owns
MozBrowserEvent(PipelineId, SubpageId, MozBrowserEvent),
/// Updates the current subpage id of a given iframe
UpdateSubpageId(PipelineId, SubpageId, SubpageId),
/// Set an iframe to be focused. Used when an element in an iframe gains focus.
FocusIFrame(PipelineId, SubpageId),
/// Passes a webdriver command to the script task for execution
WebDriverScriptCommand(PipelineId, WebDriverScriptCommand),
/// Notifies script task that all animations are done
TickAllAnimations(PipelineId),
/// Notifies the script task that a new Web font has been loaded, and thus the page should be
/// reflowed.
WebFontLoaded(PipelineId),
/// Get the current state of the script task for a given pipeline.
GetCurrentState(IpcSender<ScriptState>, PipelineId),
/// Cause a `load` event to be dispatched at the appropriate frame element.
DispatchFrameLoadEvent {
/// The pipeline that has been marked as loaded.
target: PipelineId,
/// The pipeline that contains a frame loading the target pipeline.
parent: PipelineId
},
}
/// The type of input represented by a multi-touch event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum TouchEventType {
/// A new touch point came in contact with the screen.
Down,
/// An existing touch point changed location.
Move,
/// A touch point was removed from the screen.
Up,
/// The system stopped tracking a touch point.
Cancel,
}
/// An opaque identifier for a touch point.
///
/// http://w3c.github.io/touch-events/#widl-Touch-identifier
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct TouchId(pub i32);
/// Events from the compositor that the script task needs to know about
#[derive(Deserialize, Serialize)]
pub enum CompositorEvent {
/// The window was resized.
ResizeEvent(WindowSizeData),
/// A mouse button state changed.
MouseButtonEvent(MouseEventType, MouseButton, Point2D<f32>),
/// The mouse was moved over a point (or was moved out of the recognizable region).
MouseMoveEvent(Option<Point2D<f32>>),
/// A touch event was generated with a touch ID and location.
TouchEvent(TouchEventType, TouchId, Point2D<f32>),
/// A key was pressed.
KeyEvent(Key, KeyState, KeyModifiers),
}
/// An opaque wrapper around script<->layout channels to avoid leaking message types into
/// crates that don't need to know about them.
pub struct OpaqueScriptLayoutChannel(pub (Box<Any + Send>, Box<Any + Send>));
/// Requests a TimerEvent-Message be sent after the given duration.
#[derive(Deserialize, Serialize)]
pub struct TimerEventRequest(pub IpcSender<TimerEvent>,
pub TimerSource,
pub TimerEventId,
pub MsDuration);
/// Notifies the script task to fire due timers.
/// TimerSource must be FromWindow when dispatched to ScriptTask and
/// must be FromWorker when dispatched to a DedicatedGlobalWorkerScope
#[derive(Deserialize, Serialize)]
pub struct TimerEvent(pub TimerSource, pub TimerEventId);
|
pub enum TimerSource {
/// The event was requested from a window (ScriptTask).
FromWindow(PipelineId),
/// The event was requested from a worker (DedicatedGlobalWorkerScope).
FromWorker
}
/// The id to be used for a TimerEvent is defined by the corresponding TimerEventRequest.
#[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf, Deserialize, Serialize)]
pub struct TimerEventId(pub u32);
/// Unit of measurement.
#[derive(Clone, Copy, HeapSizeOf)]
pub enum Milliseconds {}
/// Unit of measurement.
#[derive(Clone, Copy, HeapSizeOf)]
pub enum Nanoseconds {}
/// Amount of milliseconds.
pub type MsDuration = Length<Milliseconds, u64>;
/// Amount of nanoseconds.
pub type NsDuration = Length<Nanoseconds, u64>;
/// Returns the duration since an unspecified epoch measured in ms.
pub fn precise_time_ms() -> MsDuration {
Length::new(time::precise_time_ns() / (1000 * 1000))
}
/// Returns the duration since an unspecified epoch measured in ns.
pub fn precise_time_ns() -> NsDuration {
Length::new(time::precise_time_ns())
}
/// Data needed to construct a script thread.
///
/// NB: *DO NOT* add any Senders or Receivers here! pcwalton will have to rewrite your code if you
/// do! Use IPC senders and receivers instead.
pub struct InitialScriptState {
/// The ID of the pipeline with which this script thread is associated.
pub id: PipelineId,
/// The subpage ID of this pipeline to create in its pipeline parent.
/// If `None`, this is the root.
pub parent_info: Option<(PipelineId, SubpageId)>,
/// The compositor.
pub compositor: IpcSender<ScriptToCompositorMsg>,
/// A channel with which messages can be sent to us (the script task).
pub control_chan: IpcSender<ConstellationControlMsg>,
/// A port on which messages sent by the constellation to script can be received.
pub control_port: IpcReceiver<ConstellationControlMsg>,
/// A channel on which messages can be sent to the constellation from script.
pub constellation_chan: ConstellationChan<ScriptMsg>,
/// A channel to schedule timer events.
pub scheduler_chan: IpcSender<TimerEventRequest>,
/// Information that script sends out when it panics.
pub failure_info: Failure,
/// A channel to the resource manager task.
pub resource_task: ResourceTask,
/// A channel to the storage task.
pub storage_task: StorageTask,
/// A channel to the image cache task.
pub image_cache_task: ImageCacheTask,
/// A channel to the time profiler thread.
pub time_profiler_chan: profile_traits::time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// A channel to the developer tools, if applicable.
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// The ID of the pipeline namespace for this script thread.
pub pipeline_namespace_id: PipelineNamespaceId,
/// A ping will be sent on this channel once the script thread shuts down.
pub content_process_shutdown_chan: IpcSender<()>,
}
/// Encapsulates external communication with the script task.
#[derive(Clone, Deserialize, Serialize)]
pub struct ScriptControlChan(pub IpcSender<ConstellationControlMsg>);
/// This trait allows creating a `ScriptTask` without depending on the `script`
/// crate.
pub trait ScriptTaskFactory {
/// Create a `ScriptTask`.
fn create(_phantom: Option<&mut Self>,
state: InitialScriptState,
layout_chan: &OpaqueScriptLayoutChannel,
load_data: LoadData);
/// Create a script -> layout channel (`Sender`, `Receiver` pair).
fn create_layout_channel(_phantom: Option<&mut Self>) -> OpaqueScriptLayoutChannel;
/// Clone the `Sender` in `pair`.
fn clone_layout_channel(_phantom: Option<&mut Self>, pair: &OpaqueScriptLayoutChannel)
-> Box<Any + Send>;
}
|
/// Describes the task that requested the TimerEvent.
#[derive(Copy, Clone, HeapSizeOf, Deserialize, Serialize)]
|
random_line_split
|
lib.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/. */
//! This module contains traits in script used generically in the rest of Servo.
//! The traits are here instead of in script so that these modules won't have
//! to depend on script.
#![feature(custom_derive, plugin)]
#![plugin(plugins, serde_macros)]
#![deny(missing_docs)]
extern crate app_units;
extern crate canvas_traits;
extern crate devtools_traits;
extern crate euclid;
extern crate ipc_channel;
extern crate libc;
extern crate msg;
extern crate net_traits;
extern crate offscreen_gl_context;
extern crate profile_traits;
extern crate serde;
extern crate style_traits;
extern crate time;
extern crate url;
extern crate util;
mod script_msg;
use app_units::Au;
use devtools_traits::ScriptToDevtoolsControlMsg;
use euclid::length::Length;
use euclid::point::Point2D;
use euclid::rect::Rect;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use libc::c_void;
use msg::compositor_msg::{Epoch, LayerId, ScriptToCompositorMsg};
use msg::constellation_msg::{ConstellationChan, Failure, PipelineId, WindowSizeData};
use msg::constellation_msg::{Key, KeyModifiers, KeyState, LoadData, SubpageId};
use msg::constellation_msg::{MouseButton, MouseEventType};
use msg::constellation_msg::{MozBrowserEvent, PipelineNamespaceId};
use msg::webdriver_msg::WebDriverScriptCommand;
use net_traits::ResourceTask;
use net_traits::image_cache_task::ImageCacheTask;
use net_traits::storage_task::StorageTask;
use profile_traits::mem;
use std::any::Any;
use util::ipc::OptionalOpaqueIpcSender;
use util::mem::HeapSizeOf;
pub use script_msg::ScriptMsg;
/// The address of a node. Layout sends these back. They must be validated via
/// `from_untrusted_node_address` before they can be used, because we do not trust layout.
#[derive(Copy, Clone, Debug)]
pub struct UntrustedNodeAddress(pub *const c_void);
unsafe impl Send for UntrustedNodeAddress {}
/// Messages sent to the layout task from the constellation and/or compositor.
#[derive(Deserialize, Serialize)]
pub enum LayoutControlMsg {
/// Requests that this layout task exit.
ExitNow,
/// Requests the current epoch (layout counter) from this layout.
GetCurrentEpoch(IpcSender<Epoch>),
/// Asks layout to run another step in its animation.
TickAnimations,
/// Informs layout as to which regions of the page are visible.
SetVisibleRects(Vec<(LayerId, Rect<Au>)>),
/// Requests the current load state of Web fonts. `true` is returned if fonts are still loading
/// and `false` is returned if all fonts have loaded.
GetWebFontLoadState(IpcSender<bool>),
}
/// The initial data associated with a newly-created framed pipeline.
#[derive(Deserialize, Serialize)]
pub struct NewLayoutInfo {
/// Id of the parent of this new pipeline.
pub containing_pipeline_id: PipelineId,
/// Id of the newly-created pipeline.
pub new_pipeline_id: PipelineId,
/// Id of the new frame associated with this pipeline.
pub subpage_id: SubpageId,
/// Network request data which will be initiated by the script task.
pub load_data: LoadData,
/// The paint channel, cast to `OptionalOpaqueIpcSender`. This is really an
/// `Sender<LayoutToPaintMsg>`.
pub paint_chan: OptionalOpaqueIpcSender,
/// Information on what to do on task failure.
pub failure: Failure,
/// A port on which layout can receive messages from the pipeline.
pub pipeline_port: IpcReceiver<LayoutControlMsg>,
/// A shutdown channel so that layout can notify others when it's done.
pub layout_shutdown_chan: IpcSender<()>,
/// A shutdown channel so that layout can tell the content process to shut down when it's done.
pub content_process_shutdown_chan: IpcSender<()>,
}
/// Used to determine if a script has any pending asynchronous activity.
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize)]
pub enum ScriptState {
/// The document has been loaded.
DocumentLoaded,
/// The document is still loading.
DocumentLoading,
}
/// Messages sent from the constellation or layout to the script task.
#[derive(Deserialize, Serialize)]
pub enum ConstellationControlMsg {
/// Gives a channel and ID to a layout task, as well as the ID of that layout's parent
AttachLayout(NewLayoutInfo),
/// Window resized. Sends a DOM event eventually, but first we combine events.
Resize(PipelineId, WindowSizeData),
/// Notifies script that window has been resized but to not take immediate action.
ResizeInactive(PipelineId, WindowSizeData),
/// Notifies the script that a pipeline should be closed.
ExitPipeline(PipelineId),
/// Sends a DOM event.
SendEvent(PipelineId, CompositorEvent),
/// Notifies script of the viewport.
Viewport(PipelineId, Rect<f32>),
/// Requests that the script task immediately send the constellation the title of a pipeline.
GetTitle(PipelineId),
/// Notifies script task to suspend all its timers
Freeze(PipelineId),
/// Notifies script task to resume all its timers
Thaw(PipelineId),
/// Notifies script task that a url should be loaded in this iframe.
Navigate(PipelineId, SubpageId, LoadData),
/// Requests the script task forward a mozbrowser event to an iframe it owns
MozBrowserEvent(PipelineId, SubpageId, MozBrowserEvent),
/// Updates the current subpage id of a given iframe
UpdateSubpageId(PipelineId, SubpageId, SubpageId),
/// Set an iframe to be focused. Used when an element in an iframe gains focus.
FocusIFrame(PipelineId, SubpageId),
/// Passes a webdriver command to the script task for execution
WebDriverScriptCommand(PipelineId, WebDriverScriptCommand),
/// Notifies script task that all animations are done
TickAllAnimations(PipelineId),
/// Notifies the script task that a new Web font has been loaded, and thus the page should be
/// reflowed.
WebFontLoaded(PipelineId),
/// Get the current state of the script task for a given pipeline.
GetCurrentState(IpcSender<ScriptState>, PipelineId),
/// Cause a `load` event to be dispatched at the appropriate frame element.
DispatchFrameLoadEvent {
/// The pipeline that has been marked as loaded.
target: PipelineId,
/// The pipeline that contains a frame loading the target pipeline.
parent: PipelineId
},
}
/// The type of input represented by a multi-touch event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum TouchEventType {
/// A new touch point came in contact with the screen.
Down,
/// An existing touch point changed location.
Move,
/// A touch point was removed from the screen.
Up,
/// The system stopped tracking a touch point.
Cancel,
}
/// An opaque identifier for a touch point.
///
/// http://w3c.github.io/touch-events/#widl-Touch-identifier
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct TouchId(pub i32);
/// Events from the compositor that the script task needs to know about
#[derive(Deserialize, Serialize)]
pub enum CompositorEvent {
/// The window was resized.
ResizeEvent(WindowSizeData),
/// A mouse button state changed.
MouseButtonEvent(MouseEventType, MouseButton, Point2D<f32>),
/// The mouse was moved over a point (or was moved out of the recognizable region).
MouseMoveEvent(Option<Point2D<f32>>),
/// A touch event was generated with a touch ID and location.
TouchEvent(TouchEventType, TouchId, Point2D<f32>),
/// A key was pressed.
KeyEvent(Key, KeyState, KeyModifiers),
}
/// An opaque wrapper around script<->layout channels to avoid leaking message types into
/// crates that don't need to know about them.
pub struct OpaqueScriptLayoutChannel(pub (Box<Any + Send>, Box<Any + Send>));
/// Requests a TimerEvent-Message be sent after the given duration.
#[derive(Deserialize, Serialize)]
pub struct TimerEventRequest(pub IpcSender<TimerEvent>,
pub TimerSource,
pub TimerEventId,
pub MsDuration);
/// Notifies the script task to fire due timers.
/// TimerSource must be FromWindow when dispatched to ScriptTask and
/// must be FromWorker when dispatched to a DedicatedGlobalWorkerScope
#[derive(Deserialize, Serialize)]
pub struct TimerEvent(pub TimerSource, pub TimerEventId);
/// Describes the task that requested the TimerEvent.
#[derive(Copy, Clone, HeapSizeOf, Deserialize, Serialize)]
pub enum TimerSource {
/// The event was requested from a window (ScriptTask).
FromWindow(PipelineId),
/// The event was requested from a worker (DedicatedGlobalWorkerScope).
FromWorker
}
/// The id to be used for a TimerEvent is defined by the corresponding TimerEventRequest.
#[derive(PartialEq, Eq, Copy, Clone, Debug, HeapSizeOf, Deserialize, Serialize)]
pub struct TimerEventId(pub u32);
/// Unit of measurement.
#[derive(Clone, Copy, HeapSizeOf)]
pub enum Milliseconds {}
/// Unit of measurement.
#[derive(Clone, Copy, HeapSizeOf)]
pub enum
|
{}
/// Amount of milliseconds.
pub type MsDuration = Length<Milliseconds, u64>;
/// Amount of nanoseconds.
pub type NsDuration = Length<Nanoseconds, u64>;
/// Returns the duration since an unspecified epoch measured in ms.
pub fn precise_time_ms() -> MsDuration {
Length::new(time::precise_time_ns() / (1000 * 1000))
}
/// Returns the duration since an unspecified epoch measured in ns.
pub fn precise_time_ns() -> NsDuration {
Length::new(time::precise_time_ns())
}
/// Data needed to construct a script thread.
///
/// NB: *DO NOT* add any Senders or Receivers here! pcwalton will have to rewrite your code if you
/// do! Use IPC senders and receivers instead.
pub struct InitialScriptState {
/// The ID of the pipeline with which this script thread is associated.
pub id: PipelineId,
/// The subpage ID of this pipeline to create in its pipeline parent.
/// If `None`, this is the root.
pub parent_info: Option<(PipelineId, SubpageId)>,
/// The compositor.
pub compositor: IpcSender<ScriptToCompositorMsg>,
/// A channel with which messages can be sent to us (the script task).
pub control_chan: IpcSender<ConstellationControlMsg>,
/// A port on which messages sent by the constellation to script can be received.
pub control_port: IpcReceiver<ConstellationControlMsg>,
/// A channel on which messages can be sent to the constellation from script.
pub constellation_chan: ConstellationChan<ScriptMsg>,
/// A channel to schedule timer events.
pub scheduler_chan: IpcSender<TimerEventRequest>,
/// Information that script sends out when it panics.
pub failure_info: Failure,
/// A channel to the resource manager task.
pub resource_task: ResourceTask,
/// A channel to the storage task.
pub storage_task: StorageTask,
/// A channel to the image cache task.
pub image_cache_task: ImageCacheTask,
/// A channel to the time profiler thread.
pub time_profiler_chan: profile_traits::time::ProfilerChan,
/// A channel to the memory profiler thread.
pub mem_profiler_chan: mem::ProfilerChan,
/// A channel to the developer tools, if applicable.
pub devtools_chan: Option<IpcSender<ScriptToDevtoolsControlMsg>>,
/// Information about the initial window size.
pub window_size: Option<WindowSizeData>,
/// The ID of the pipeline namespace for this script thread.
pub pipeline_namespace_id: PipelineNamespaceId,
/// A ping will be sent on this channel once the script thread shuts down.
pub content_process_shutdown_chan: IpcSender<()>,
}
/// Encapsulates external communication with the script task.
#[derive(Clone, Deserialize, Serialize)]
pub struct ScriptControlChan(pub IpcSender<ConstellationControlMsg>);
/// This trait allows creating a `ScriptTask` without depending on the `script`
/// crate.
pub trait ScriptTaskFactory {
/// Create a `ScriptTask`.
fn create(_phantom: Option<&mut Self>,
state: InitialScriptState,
layout_chan: &OpaqueScriptLayoutChannel,
load_data: LoadData);
/// Create a script -> layout channel (`Sender`, `Receiver` pair).
fn create_layout_channel(_phantom: Option<&mut Self>) -> OpaqueScriptLayoutChannel;
/// Clone the `Sender` in `pair`.
fn clone_layout_channel(_phantom: Option<&mut Self>, pair: &OpaqueScriptLayoutChannel)
-> Box<Any + Send>;
}
|
Nanoseconds
|
identifier_name
|
semistatement-in-lambda.rs
|
// Copyright 2017 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.
#![allow(unused_must_use)]
pub fn main() {
// Test that lambdas behave as unary expressions with block-like expressions
-if true { 1 } else { 2 } * 3;
|
|| if true { 1 } else { 2 } * 3;
// The following is invalid and parses as `if true { 1 } else { 2 }; *3`
// if true { 1 } else { 2 } * 3
}
|
random_line_split
|
|
semistatement-in-lambda.rs
|
// Copyright 2017 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.
#![allow(unused_must_use)]
pub fn main() {
// Test that lambdas behave as unary expressions with block-like expressions
-if true { 1 } else { 2 } * 3;
|| if true { 1 } else
|
* 3;
// The following is invalid and parses as `if true { 1 } else { 2 }; *3`
// if true { 1 } else { 2 } * 3
}
|
{ 2 }
|
conditional_block
|
semistatement-in-lambda.rs
|
// Copyright 2017 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.
#![allow(unused_must_use)]
pub fn
|
() {
// Test that lambdas behave as unary expressions with block-like expressions
-if true { 1 } else { 2 } * 3;
|| if true { 1 } else { 2 } * 3;
// The following is invalid and parses as `if true { 1 } else { 2 }; *3`
// if true { 1 } else { 2 } * 3
}
|
main
|
identifier_name
|
semistatement-in-lambda.rs
|
// Copyright 2017 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.
#![allow(unused_must_use)]
pub fn main()
|
{
// Test that lambdas behave as unary expressions with block-like expressions
-if true { 1 } else { 2 } * 3;
|| if true { 1 } else { 2 } * 3;
// The following is invalid and parses as `if true { 1 } else { 2 }; *3`
// if true { 1 } else { 2 } * 3
}
|
identifier_body
|
|
dom.rs
|
/// Returns the address of this node, for debugging purposes.
#[inline]
pub fn id(&self) -> usize {
self.0
}
}
/// Simple trait to provide basic information about the type of an element.
///
/// We avoid exposing the full type id, since computing it in the general case
/// would be difficult for Gecko nodes.
pub trait NodeInfo {
/// Whether this node is an element.
fn is_element(&self) -> bool;
/// Whether this node is a text node.
fn is_text_node(&self) -> bool;
/// Whether this node needs layout.
///
/// Comments, doctypes, etc are ignored by layout algorithms.
fn needs_layout(&self) -> bool { self.is_element() || self.is_text_node() }
}
/// A node iterator that only returns node that don't need layout.
pub struct LayoutIterator<T>(pub T);
impl<T, I> Iterator for LayoutIterator<T>
where T: Iterator<Item=I>,
I: NodeInfo,
{
type Item = I;
fn next(&mut self) -> Option<I> {
loop {
// Filter out nodes that layout should ignore.
let n = self.0.next();
if n.is_none() || n.as_ref().unwrap().needs_layout() {
return n
}
}
}
}
/// The `TNode` trait. This is the main generic trait over which the style
/// system can be implemented.
pub trait TNode : Sized + Copy + Clone + Debug + NodeInfo {
/// The concrete `TElement` type.
type ConcreteElement: TElement<ConcreteNode = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type ConcreteChildrenIterator: Iterator<Item = Self>;
/// Convert this node in an `UnsafeNode`.
fn to_unsafe(&self) -> UnsafeNode;
/// Get a node back from an `UnsafeNode`.
unsafe fn from_unsafe(n: &UnsafeNode) -> Self;
/// Get this node's parent node.
fn parent_node(&self) -> Option<Self>;
/// Get this node's parent element if present.
fn parent_element(&self) -> Option<Self::ConcreteElement> {
self.parent_node().and_then(|n| n.as_element())
}
/// Returns an iterator over this node's children.
fn children(&self) -> LayoutIterator<Self::ConcreteChildrenIterator>;
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self::ConcreteElement>;
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::ConcreteChildrenIterator>;
/// Returns whether `children()` and `traversal_children()` might return
/// iterators over different nodes.
fn children_and_traversal_children_might_differ(&self) -> bool;
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// A debug id, only useful, mm... for debugging.
fn debug_id(self) -> usize;
/// Get this node as an element, if it's one.
fn as_element(&self) -> Option<Self::ConcreteElement>;
/// Whether this node needs to be laid out on viewport size change.
fn needs_dirty_on_viewport_size_changed(&self) -> bool;
/// Mark this node as needing layout on viewport size change.
unsafe fn set_dirty_on_viewport_size_changed(&self);
/// Whether this node can be fragmented. This is used for multicol, and only
/// for Servo.
fn can_be_fragmented(&self) -> bool;
/// Set whether this node can be fragmented.
unsafe fn set_can_be_fragmented(&self, value: bool);
/// Whether this node is in the document right now needed to clear the
/// restyle data appropriately on some forced restyles.
fn is_in_doc(&self) -> bool;
}
/// Wrapper to output the ElementData along with the node when formatting for
/// Debug.
pub struct ShowData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data(f, self.0)
}
}
/// Wrapper to output the primary computed values along with the node when
/// formatting for Debug. This is very verbose.
pub struct ShowDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data_and_primary_values(f, self.0)
}
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:"));
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:"));
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:"));
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(f, "{:?} dd={} data={:?}", el, el.has_dirty_descendants(), el.borrow_data())
} else {
write!(f, "{:?}", n)
}
}
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let data = el.borrow_data();
let styles = data.as_ref().and_then(|d| d.get_styles());
let values = styles.map(|s| s.primary.values());
write!(f, "{:?} dd={} data={:?} values={:?}", el, dd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
try!(write!(f, " "));
}
try!(stringify(f, n));
for kid in n.traversal_children() {
try!(writeln!(f, ""));
try!(fmt_subtree(f, stringify, kid, indent + 1));
}
Ok(())
}
/// Flag that this element has a descendant for style processing, propagating
/// the bit up to the root as needed.
///
/// This is _not_ safe to call during the parallel traversal.
///
/// This is intended as a helper so Servo and Gecko can override it with custom
/// stuff if needed.
///
/// Returns whether no parent had already noted it, that is, whether we reached
/// the root during the walk up.
pub unsafe fn raw_note_descendants<E, B>(element: E) -> bool
where E: TElement,
B: DescendantsBit<E>,
{
debug_assert!(!thread_state::get().is_worker());
// TODO(emilio, bholley): Documenting the flags setup a bit better wouldn't
// really hurt I guess.
debug_assert!(element.get_data().is_some(),
"You should ensure you only flag styled elements");
let mut curr = Some(element);
while let Some(el) = curr {
if B::has(el) {
break;
}
B::set(el);
curr = el.traversal_parent();
}
// Note: We disable this assertion on servo because of bugs. See the
// comment around note_dirty_descendant in layout/wrapper.rs.
if cfg!(feature = "gecko") {
debug_assert!(element.descendants_bit_is_propagated::<B>());
}
curr.is_none()
}
/// A trait used to synthesize presentational hints for HTML element attributes.
pub trait PresentationalHintsSynthesizer {
/// Generate the proper applicable declarations due to presentational hints,
/// and insert them into `hints`.
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self,
visited_handling: VisitedHandlingMode,
hints: &mut V)
where V: Push<ApplicableDeclarationBlock>;
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement : Eq + PartialEq + Debug + Hash + Sized + Copy + Clone +
ElementExt + PresentationalHintsSynthesizer {
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self> {
unreachable!("Servo doesn't know about NAC");
}
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<&Arc<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<&Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Get the pre-existing style to calculate restyle damage (change hints).
///
/// This needs to be generic since it varies between Servo and Gecko.
///
/// XXX(emilio): It's a bit unfortunate we need to pass the current computed
/// values as an argument here, but otherwise Servo would crash due to
/// double borrows to return it.
fn existing_style_for_restyle_damage<'a>(&'a self,
current_computed_values: &'a ComputedValues,
pseudo: Option<&PseudoElement>)
-> Option<&'a PreExistingComputedValues>;
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
_pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date.
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.has_invalidations()
}
/// Flags an element and its ancestors with a given `DescendantsBit`.
///
/// TODO(emilio): We call this conservatively from restyle_element_internal
/// because we never flag unstyled stuff. A different setup for this may be
/// a bit cleaner, but it's probably not worth to invest on it right now
/// unless necessary.
unsafe fn note_descendants<B: DescendantsBit<Self>>(&self);
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Debug helper to be sure the bit is propagated.
fn descendants_bit_is_propagated<B: DescendantsBit<Self>>(&self) -> bool {
let mut current = Some(*self);
while let Some(el) = current {
if!B::has(el) { return false; }
current = el.traversal_parent();
}
true
}
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>> {
self.get_data().map(|x| x.borrow())
}
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do so in the future.
fn has_animations(&self) -> bool;
/// Returns true if the element has a CSS animation.
fn has_css_animations(&self) -> bool;
/// Returns true if the element has a CSS transition (including running transitions and
/// completed transitions).
fn has_css_transitions(&self) -> bool;
/// Returns true if the element has animation restyle hints.
fn has_animation_restyle_hints(&self) -> bool {
let data = match self.borrow_data() {
Some(d) => d,
None => return false,
};
return data.get_restyle()
.map_or(false, |r| r.hint.has_animation_hint());
}
/// Gets declarations from XBL bindings from the element. Only gecko element could have this.
fn get_declarations_from_xbl_bindings<V>(&self,
_: &mut V)
-> bool
where V: Push<ApplicableDeclarationBlock> + VecLike<ApplicableDeclarationBlock> {
false
}
/// Gets the current existing CSS transitions, by |property, end value| pairs in a HashMap.
#[cfg(feature = "gecko")]
fn get_css_transitions_info(&self)
-> HashMap<TransitionProperty, Arc<AnimationValue>>;
/// Does a rough (and cheap) check for whether or not transitions might need to be updated that
/// will quickly return false for the common case of no transitions specified or running. If
/// this returns false, we definitely don't need to update transitions but if it returns true
/// we can perform the more thoroughgoing check, needs_transitions_update, to further
/// reduce the possibility of false positives.
#[cfg(feature = "gecko")]
fn might_need_transitions_update(&self,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues)
-> bool;
/// Returns true if one of the transitions needs to be updated on this element. We check all
/// the transition properties to make sure that updating transitions is necessary.
/// This method should only be called if might_needs_transitions_update returns true when
/// passed the same parameters.
#[cfg(feature = "gecko")]
fn needs_transitions_update(&self,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues)
-> bool;
/// Returns true if we need to update transitions for the specified property on this element.
#[cfg(feature = "gecko")]
fn needs_transitions_update_per_property(&self,
property: &TransitionProperty,
combined_duration: f32,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues,
existing_transitions: &HashMap<TransitionProperty,
Arc<AnimationValue>>)
-> bool;
/// Returns the value of the `xml:lang=""` attribute (or, if appropriate,
/// the `lang=""` attribute) on this element.
fn lang_attr(&self) -> Option<AttrValue>;
/// Returns whether this element's language matches the language tag
/// `value`. If `override_lang` is not `None`, it specifies the value
/// of the `xml:lang=""` or `lang=""` attribute to use in place of
|
/// looking at the element and its ancestors. (This argument is used
/// to implement matching of `:lang()` against snapshots.)
fn match_element_lang(&self,
|
random_line_split
|
|
dom.rs
|
be
/// performed on this node is to compare it to another opaque handle or to another
/// OpaqueNode.
///
/// Layout and Graphics use this to safely represent nodes for comparison purposes.
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[derive(Clone, PartialEq, Copy, Debug, Hash, Eq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))]
pub struct OpaqueNode(pub usize);
impl OpaqueNode {
/// Returns the address of this node, for debugging purposes.
#[inline]
pub fn id(&self) -> usize {
self.0
}
}
/// Simple trait to provide basic information about the type of an element.
///
/// We avoid exposing the full type id, since computing it in the general case
/// would be difficult for Gecko nodes.
pub trait NodeInfo {
/// Whether this node is an element.
fn is_element(&self) -> bool;
/// Whether this node is a text node.
fn is_text_node(&self) -> bool;
/// Whether this node needs layout.
///
/// Comments, doctypes, etc are ignored by layout algorithms.
fn needs_layout(&self) -> bool { self.is_element() || self.is_text_node() }
}
/// A node iterator that only returns node that don't need layout.
pub struct LayoutIterator<T>(pub T);
impl<T, I> Iterator for LayoutIterator<T>
where T: Iterator<Item=I>,
I: NodeInfo,
{
type Item = I;
fn next(&mut self) -> Option<I> {
loop {
// Filter out nodes that layout should ignore.
let n = self.0.next();
if n.is_none() || n.as_ref().unwrap().needs_layout() {
return n
}
}
}
}
/// The `TNode` trait. This is the main generic trait over which the style
/// system can be implemented.
pub trait TNode : Sized + Copy + Clone + Debug + NodeInfo {
/// The concrete `TElement` type.
type ConcreteElement: TElement<ConcreteNode = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type ConcreteChildrenIterator: Iterator<Item = Self>;
/// Convert this node in an `UnsafeNode`.
fn to_unsafe(&self) -> UnsafeNode;
/// Get a node back from an `UnsafeNode`.
unsafe fn from_unsafe(n: &UnsafeNode) -> Self;
/// Get this node's parent node.
fn parent_node(&self) -> Option<Self>;
/// Get this node's parent element if present.
fn parent_element(&self) -> Option<Self::ConcreteElement> {
self.parent_node().and_then(|n| n.as_element())
}
/// Returns an iterator over this node's children.
fn children(&self) -> LayoutIterator<Self::ConcreteChildrenIterator>;
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self::ConcreteElement>;
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::ConcreteChildrenIterator>;
/// Returns whether `children()` and `traversal_children()` might return
/// iterators over different nodes.
fn children_and_traversal_children_might_differ(&self) -> bool;
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// A debug id, only useful, mm... for debugging.
fn debug_id(self) -> usize;
/// Get this node as an element, if it's one.
fn as_element(&self) -> Option<Self::ConcreteElement>;
/// Whether this node needs to be laid out on viewport size change.
fn needs_dirty_on_viewport_size_changed(&self) -> bool;
/// Mark this node as needing layout on viewport size change.
unsafe fn set_dirty_on_viewport_size_changed(&self);
/// Whether this node can be fragmented. This is used for multicol, and only
/// for Servo.
fn can_be_fragmented(&self) -> bool;
/// Set whether this node can be fragmented.
unsafe fn set_can_be_fragmented(&self, value: bool);
/// Whether this node is in the document right now needed to clear the
/// restyle data appropriately on some forced restyles.
fn is_in_doc(&self) -> bool;
}
/// Wrapper to output the ElementData along with the node when formatting for
/// Debug.
pub struct ShowData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data(f, self.0)
}
}
/// Wrapper to output the primary computed values along with the node when
/// formatting for Debug. This is very verbose.
pub struct ShowDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data_and_primary_values(f, self.0)
}
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:"));
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:"));
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:"));
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(f, "{:?} dd={} data={:?}", el, el.has_dirty_descendants(), el.borrow_data())
} else {
write!(f, "{:?}", n)
}
}
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let data = el.borrow_data();
let styles = data.as_ref().and_then(|d| d.get_styles());
let values = styles.map(|s| s.primary.values());
write!(f, "{:?} dd={} data={:?} values={:?}", el, dd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
try!(write!(f, " "));
}
try!(stringify(f, n));
for kid in n.traversal_children() {
try!(writeln!(f, ""));
try!(fmt_subtree(f, stringify, kid, indent + 1));
}
Ok(())
}
/// Flag that this element has a descendant for style processing, propagating
/// the bit up to the root as needed.
///
/// This is _not_ safe to call during the parallel traversal.
///
/// This is intended as a helper so Servo and Gecko can override it with custom
/// stuff if needed.
///
/// Returns whether no parent had already noted it, that is, whether we reached
/// the root during the walk up.
pub unsafe fn raw_note_descendants<E, B>(element: E) -> bool
where E: TElement,
B: DescendantsBit<E>,
{
debug_assert!(!thread_state::get().is_worker());
// TODO(emilio, bholley): Documenting the flags setup a bit better wouldn't
// really hurt I guess.
debug_assert!(element.get_data().is_some(),
"You should ensure you only flag styled elements");
let mut curr = Some(element);
while let Some(el) = curr {
if B::has(el) {
break;
}
B::set(el);
curr = el.traversal_parent();
}
// Note: We disable this assertion on servo because of bugs. See the
// comment around note_dirty_descendant in layout/wrapper.rs.
if cfg!(feature = "gecko") {
debug_assert!(element.descendants_bit_is_propagated::<B>());
}
curr.is_none()
}
/// A trait used to synthesize presentational hints for HTML element attributes.
pub trait PresentationalHintsSynthesizer {
/// Generate the proper applicable declarations due to presentational hints,
/// and insert them into `hints`.
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self,
visited_handling: VisitedHandlingMode,
hints: &mut V)
where V: Push<ApplicableDeclarationBlock>;
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement : Eq + PartialEq + Debug + Hash + Sized + Copy + Clone +
ElementExt + PresentationalHintsSynthesizer {
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self> {
unreachable!("Servo doesn't know about NAC");
}
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<&Arc<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<&Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Get the pre-existing style to calculate restyle damage (change hints).
///
/// This needs to be generic since it varies between Servo and Gecko.
///
/// XXX(emilio): It's a bit unfortunate we need to pass the current computed
/// values as an argument here, but otherwise Servo would crash due to
/// double borrows to return it.
fn existing_style_for_restyle_damage<'a>(&'a self,
current_computed_values: &'a ComputedValues,
pseudo: Option<&PseudoElement>)
-> Option<&'a PreExistingComputedValues>;
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
_pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date.
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.has_invalidations()
}
/// Flags an element and its ancestors with a given `DescendantsBit`.
///
/// TODO(emilio): We call this conservatively from restyle_element_internal
/// because we never flag unstyled stuff. A different setup for this may be
/// a bit cleaner, but it's probably not worth to invest on it right now
/// unless necessary.
unsafe fn note_descendants<B: DescendantsBit<Self>>(&self);
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Debug helper to be sure the bit is propagated.
fn descendants_bit_is_propagated<B: DescendantsBit<Self>>(&self) -> bool {
let mut current = Some(*self);
while let Some(el) = current {
if!B::has(el) { return false; }
current = el.traversal_parent();
}
true
}
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>>
|
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do so in the future.
fn has_animations(&self) -> bool;
/// Returns true if the element has a CSS animation.
fn has_css_animations(&self) -> bool;
/// Returns true if the element has a CSS transition (including running transitions and
/// completed transitions).
fn has_css_transitions(&self) -> bool;
/// Returns true if the element has animation restyle hints.
fn has_animation_restyle_hints(&self) -> bool {
let data = match self.borrow_data() {
Some(d) => d,
None => return false,
};
return data.get_restyle()
.map_or(false, |r| r.hint.has_animation_hint());
}
/// Gets declarations from XBL bindings from the element. Only gecko element could have this.
fn get_declarations_from_xbl_bindings<V>(&self,
_: &mut V)
-> bool
where V: Push<ApplicableDeclarationBlock> + VecLike<ApplicableDeclarationBlock> {
false
}
/// Gets the current existing CSS transitions, by |property, end value| pairs in a HashMap.
#[cfg(feature = "gecko")]
fn get_css_transitions_info(&self)
-> HashMap<TransitionProperty, Arc<AnimationValue>>;
/// Does a rough (and cheap) check for whether or not transitions might need to be updated that
/// will quickly return false for the common case of no transitions specified or running. If
/// this returns false, we definitely don't need to update transitions but if it returns true
/// we can perform the more thoroughgoing check, needs_transitions_update, to further
/// reduce the possibility of false positives.
#[cfg(feature = "gecko")]
fn might_need_transitions_update(&self,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues)
-> bool;
/// Returns true if one of the transitions needs to be updated on this element. We check all
/// the transition properties to make sure that updating transitions is necessary.
/// This method should only be called if might_needs_transitions_update returns true when
/// passed the same parameters.
#[cfg(feature = "gecko")]
fn needs_transitions_update(&self,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues)
-> bool;
/// Returns true if we need to update transitions for the specified property on this element.
#[cfg(feature = "gecko")]
fn needs_transitions_update_per_property(&self,
property: &TransitionProperty,
combined_duration: f32,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues,
existing_transitions: &HashMap<TransitionProperty,
Arc<AnimationValue>>)
-> bool;
/// Returns the value of the `xml:lang
|
{
self.get_data().map(|x| x.borrow())
}
|
identifier_body
|
dom.rs
|
be
/// performed on this node is to compare it to another opaque handle or to another
/// OpaqueNode.
///
/// Layout and Graphics use this to safely represent nodes for comparison purposes.
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[derive(Clone, PartialEq, Copy, Debug, Hash, Eq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf, Deserialize, Serialize))]
pub struct OpaqueNode(pub usize);
impl OpaqueNode {
/// Returns the address of this node, for debugging purposes.
#[inline]
pub fn id(&self) -> usize {
self.0
}
}
/// Simple trait to provide basic information about the type of an element.
///
/// We avoid exposing the full type id, since computing it in the general case
/// would be difficult for Gecko nodes.
pub trait NodeInfo {
/// Whether this node is an element.
fn is_element(&self) -> bool;
/// Whether this node is a text node.
fn is_text_node(&self) -> bool;
/// Whether this node needs layout.
///
/// Comments, doctypes, etc are ignored by layout algorithms.
fn
|
(&self) -> bool { self.is_element() || self.is_text_node() }
}
/// A node iterator that only returns node that don't need layout.
pub struct LayoutIterator<T>(pub T);
impl<T, I> Iterator for LayoutIterator<T>
where T: Iterator<Item=I>,
I: NodeInfo,
{
type Item = I;
fn next(&mut self) -> Option<I> {
loop {
// Filter out nodes that layout should ignore.
let n = self.0.next();
if n.is_none() || n.as_ref().unwrap().needs_layout() {
return n
}
}
}
}
/// The `TNode` trait. This is the main generic trait over which the style
/// system can be implemented.
pub trait TNode : Sized + Copy + Clone + Debug + NodeInfo {
/// The concrete `TElement` type.
type ConcreteElement: TElement<ConcreteNode = Self>;
/// A concrete children iterator type in order to iterate over the `Node`s.
///
/// TODO(emilio): We should eventually replace this with the `impl Trait`
/// syntax.
type ConcreteChildrenIterator: Iterator<Item = Self>;
/// Convert this node in an `UnsafeNode`.
fn to_unsafe(&self) -> UnsafeNode;
/// Get a node back from an `UnsafeNode`.
unsafe fn from_unsafe(n: &UnsafeNode) -> Self;
/// Get this node's parent node.
fn parent_node(&self) -> Option<Self>;
/// Get this node's parent element if present.
fn parent_element(&self) -> Option<Self::ConcreteElement> {
self.parent_node().and_then(|n| n.as_element())
}
/// Returns an iterator over this node's children.
fn children(&self) -> LayoutIterator<Self::ConcreteChildrenIterator>;
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self::ConcreteElement>;
/// Get this node's children from the perspective of a restyle traversal.
fn traversal_children(&self) -> LayoutIterator<Self::ConcreteChildrenIterator>;
/// Returns whether `children()` and `traversal_children()` might return
/// iterators over different nodes.
fn children_and_traversal_children_might_differ(&self) -> bool;
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// A debug id, only useful, mm... for debugging.
fn debug_id(self) -> usize;
/// Get this node as an element, if it's one.
fn as_element(&self) -> Option<Self::ConcreteElement>;
/// Whether this node needs to be laid out on viewport size change.
fn needs_dirty_on_viewport_size_changed(&self) -> bool;
/// Mark this node as needing layout on viewport size change.
unsafe fn set_dirty_on_viewport_size_changed(&self);
/// Whether this node can be fragmented. This is used for multicol, and only
/// for Servo.
fn can_be_fragmented(&self) -> bool;
/// Set whether this node can be fragmented.
unsafe fn set_can_be_fragmented(&self, value: bool);
/// Whether this node is in the document right now needed to clear the
/// restyle data appropriately on some forced restyles.
fn is_in_doc(&self) -> bool;
}
/// Wrapper to output the ElementData along with the node when formatting for
/// Debug.
pub struct ShowData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data(f, self.0)
}
}
/// Wrapper to output the primary computed values along with the node when
/// formatting for Debug. This is very verbose.
pub struct ShowDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_with_data_and_primary_values(f, self.0)
}
}
/// Wrapper to output the subtree rather than the single node when formatting
/// for Debug.
pub struct ShowSubtree<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtree<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:"));
fmt_subtree(f, &|f, n| write!(f, "{:?}", n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData when formatting
/// for Debug.
pub struct ShowSubtreeData<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeData<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:"));
fmt_subtree(f, &|f, n| fmt_with_data(f, n), self.0, 1)
}
}
/// Wrapper to output the subtree along with the ElementData and primary
/// ComputedValues when formatting for Debug. This is extremely verbose.
pub struct ShowSubtreeDataAndPrimaryValues<N: TNode>(pub N);
impl<N: TNode> Debug for ShowSubtreeDataAndPrimaryValues<N> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "DOM Subtree:"));
fmt_subtree(f, &|f, n| fmt_with_data_and_primary_values(f, n), self.0, 1)
}
}
fn fmt_with_data<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
write!(f, "{:?} dd={} data={:?}", el, el.has_dirty_descendants(), el.borrow_data())
} else {
write!(f, "{:?}", n)
}
}
fn fmt_with_data_and_primary_values<N: TNode>(f: &mut fmt::Formatter, n: N) -> fmt::Result {
if let Some(el) = n.as_element() {
let dd = el.has_dirty_descendants();
let data = el.borrow_data();
let styles = data.as_ref().and_then(|d| d.get_styles());
let values = styles.map(|s| s.primary.values());
write!(f, "{:?} dd={} data={:?} values={:?}", el, dd, &data, values)
} else {
write!(f, "{:?}", n)
}
}
fn fmt_subtree<F, N: TNode>(f: &mut fmt::Formatter, stringify: &F, n: N, indent: u32)
-> fmt::Result
where F: Fn(&mut fmt::Formatter, N) -> fmt::Result
{
for _ in 0..indent {
try!(write!(f, " "));
}
try!(stringify(f, n));
for kid in n.traversal_children() {
try!(writeln!(f, ""));
try!(fmt_subtree(f, stringify, kid, indent + 1));
}
Ok(())
}
/// Flag that this element has a descendant for style processing, propagating
/// the bit up to the root as needed.
///
/// This is _not_ safe to call during the parallel traversal.
///
/// This is intended as a helper so Servo and Gecko can override it with custom
/// stuff if needed.
///
/// Returns whether no parent had already noted it, that is, whether we reached
/// the root during the walk up.
pub unsafe fn raw_note_descendants<E, B>(element: E) -> bool
where E: TElement,
B: DescendantsBit<E>,
{
debug_assert!(!thread_state::get().is_worker());
// TODO(emilio, bholley): Documenting the flags setup a bit better wouldn't
// really hurt I guess.
debug_assert!(element.get_data().is_some(),
"You should ensure you only flag styled elements");
let mut curr = Some(element);
while let Some(el) = curr {
if B::has(el) {
break;
}
B::set(el);
curr = el.traversal_parent();
}
// Note: We disable this assertion on servo because of bugs. See the
// comment around note_dirty_descendant in layout/wrapper.rs.
if cfg!(feature = "gecko") {
debug_assert!(element.descendants_bit_is_propagated::<B>());
}
curr.is_none()
}
/// A trait used to synthesize presentational hints for HTML element attributes.
pub trait PresentationalHintsSynthesizer {
/// Generate the proper applicable declarations due to presentational hints,
/// and insert them into `hints`.
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self,
visited_handling: VisitedHandlingMode,
hints: &mut V)
where V: Push<ApplicableDeclarationBlock>;
}
/// The element trait, the main abstraction the style crate acts over.
pub trait TElement : Eq + PartialEq + Debug + Hash + Sized + Copy + Clone +
ElementExt + PresentationalHintsSynthesizer {
/// The concrete node type.
type ConcreteNode: TNode<ConcreteElement = Self>;
/// Type of the font metrics provider
///
/// XXXManishearth It would be better to make this a type parameter on
/// ThreadLocalStyleContext and StyleContext
type FontMetricsProvider: FontMetricsProvider;
/// Get this element as a node.
fn as_node(&self) -> Self::ConcreteNode;
/// Returns the depth of this element in the DOM.
fn depth(&self) -> usize {
let mut depth = 0;
let mut curr = *self;
while let Some(parent) = curr.traversal_parent() {
depth += 1;
curr = parent;
}
depth
}
/// Get this node's parent element from the perspective of a restyle
/// traversal.
fn traversal_parent(&self) -> Option<Self> {
self.as_node().traversal_parent()
}
/// Returns the parent element we should inherit from.
///
/// This is pretty much always the parent element itself, except in the case
/// of Gecko's Native Anonymous Content, which uses the traversal parent
/// (i.e. the flattened tree parent) and which also may need to find the
/// closest non-NAC ancestor.
fn inheritance_parent(&self) -> Option<Self> {
self.parent_element()
}
/// For a given NAC element, return the closest non-NAC ancestor, which is
/// guaranteed to exist.
fn closest_non_native_anonymous_ancestor(&self) -> Option<Self> {
unreachable!("Servo doesn't know about NAC");
}
/// Get this element's style attribute.
fn style_attribute(&self) -> Option<&Arc<Locked<PropertyDeclarationBlock>>>;
/// Unset the style attribute's dirty bit.
/// Servo doesn't need to manage ditry bit for style attribute.
fn unset_dirty_style_attribute(&self) {
}
/// Get this element's SMIL override declarations.
fn get_smil_override(&self) -> Option<&Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule by the cascade level.
fn get_animation_rule_by_cascade(&self,
_cascade_level: CascadeLevel)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's animation rule.
fn get_animation_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's transition rule.
fn get_transition_rule(&self)
-> Option<Arc<Locked<PropertyDeclarationBlock>>> {
None
}
/// Get this element's state, for non-tree-structural pseudos.
fn get_state(&self) -> ElementState;
/// Whether this element has an attribute with a given namespace.
fn has_attr(&self, namespace: &Namespace, attr: &LocalName) -> bool;
/// Internal iterator for the classes of this element.
fn each_class<F>(&self, callback: F) where F: FnMut(&Atom);
/// Get the pre-existing style to calculate restyle damage (change hints).
///
/// This needs to be generic since it varies between Servo and Gecko.
///
/// XXX(emilio): It's a bit unfortunate we need to pass the current computed
/// values as an argument here, but otherwise Servo would crash due to
/// double borrows to return it.
fn existing_style_for_restyle_damage<'a>(&'a self,
current_computed_values: &'a ComputedValues,
pseudo: Option<&PseudoElement>)
-> Option<&'a PreExistingComputedValues>;
/// Whether a given element may generate a pseudo-element.
///
/// This is useful to avoid computing, for example, pseudo styles for
/// `::-first-line` or `::-first-letter`, when we know it won't affect us.
///
/// TODO(emilio, bz): actually implement the logic for it.
fn may_generate_pseudo(
&self,
_pseudo: &PseudoElement,
_primary_style: &ComputedValues,
) -> bool {
true
}
/// Returns true if this element may have a descendant needing style processing.
///
/// Note that we cannot guarantee the existence of such an element, because
/// it may have been removed from the DOM between marking it for restyle and
/// the actual restyle traversal.
fn has_dirty_descendants(&self) -> bool;
/// Returns whether state or attributes that may change style have changed
/// on the element, and thus whether the element has been snapshotted to do
/// restyle hint computation.
fn has_snapshot(&self) -> bool;
/// Returns whether the current snapshot if present has been handled.
fn handled_snapshot(&self) -> bool;
/// Flags this element as having handled already its snapshot.
unsafe fn set_handled_snapshot(&self);
/// Returns whether the element's styles are up-to-date.
fn has_current_styles(&self, data: &ElementData) -> bool {
if self.has_snapshot() &&!self.handled_snapshot() {
return false;
}
data.has_styles() &&!data.has_invalidations()
}
/// Flags an element and its ancestors with a given `DescendantsBit`.
///
/// TODO(emilio): We call this conservatively from restyle_element_internal
/// because we never flag unstyled stuff. A different setup for this may be
/// a bit cleaner, but it's probably not worth to invest on it right now
/// unless necessary.
unsafe fn note_descendants<B: DescendantsBit<Self>>(&self);
/// Flag that this element has a descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_dirty_descendants(&self);
/// Debug helper to be sure the bit is propagated.
fn descendants_bit_is_propagated<B: DescendantsBit<Self>>(&self) -> bool {
let mut current = Some(*self);
while let Some(el) = current {
if!B::has(el) { return false; }
current = el.traversal_parent();
}
true
}
/// Flag that this element has no descendant for style processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_dirty_descendants(&self);
/// Similar to the dirty_descendants but for representing a descendant of
/// the element needs to be updated in animation-only traversal.
fn has_animation_only_dirty_descendants(&self) -> bool {
false
}
/// Flag that this element has a descendant for animation-only restyle
/// processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn set_animation_only_dirty_descendants(&self) {
}
/// Flag that this element has no descendant for animation-only restyle processing.
///
/// Only safe to call with exclusive access to the element.
unsafe fn unset_animation_only_dirty_descendants(&self) {
}
/// Returns true if this element is native anonymous (only Gecko has native
/// anonymous content).
fn is_native_anonymous(&self) -> bool { false }
/// Returns the pseudo-element implemented by this element, if any.
///
/// Gecko traverses pseudo-elements during the style traversal, and we need
/// to know this so we can properly grab the pseudo-element style from the
/// parent element.
///
/// Note that we still need to compute the pseudo-elements before-hand,
/// given otherwise we don't know if we need to create an element or not.
///
/// Servo doesn't have to deal with this.
fn implemented_pseudo_element(&self) -> Option<PseudoElement> { None }
/// Atomically stores the number of children of this node that we will
/// need to process during bottom-up traversal.
fn store_children_to_process(&self, n: isize);
/// Atomically notes that a child has been processed during bottom-up
/// traversal. Returns the number of children left to process.
fn did_process_child(&self) -> isize;
/// Gets a reference to the ElementData container.
fn get_data(&self) -> Option<&AtomicRefCell<ElementData>>;
/// Immutably borrows the ElementData.
fn borrow_data(&self) -> Option<AtomicRef<ElementData>> {
self.get_data().map(|x| x.borrow())
}
/// Mutably borrows the ElementData.
fn mutate_data(&self) -> Option<AtomicRefMut<ElementData>> {
self.get_data().map(|x| x.borrow_mut())
}
/// Whether we should skip any root- or item-based display property
/// blockification on this element. (This function exists so that Gecko
/// native anonymous content can opt out of this style fixup.)
fn skip_root_and_item_based_display_fixup(&self) -> bool;
/// Sets selector flags, which indicate what kinds of selectors may have
/// matched on this element and therefore what kind of work may need to
/// be performed when DOM state changes.
///
/// This is unsafe, like all the flag-setting methods, because it's only safe
/// to call with exclusive access to the element. When setting flags on the
/// parent during parallel traversal, we use SequentialTask to queue up the
/// set to run after the threads join.
unsafe fn set_selector_flags(&self, flags: ElementSelectorFlags);
/// Returns true if the element has all the specified selector flags.
fn has_selector_flags(&self, flags: ElementSelectorFlags) -> bool;
/// In Gecko, element has a flag that represents the element may have
/// any type of animations or not to bail out animation stuff early.
/// Whereas Servo doesn't have such flag.
fn may_have_animations(&self) -> bool { false }
/// Creates a task to update various animation state on a given (pseudo-)element.
#[cfg(feature = "gecko")]
fn update_animations(&self,
before_change_style: Option<Arc<ComputedValues>>,
tasks: UpdateAnimationsTasks);
/// Returns true if the element has relevant animations. Relevant
/// animations are those animations that are affecting the element's style
/// or are scheduled to do so in the future.
fn has_animations(&self) -> bool;
/// Returns true if the element has a CSS animation.
fn has_css_animations(&self) -> bool;
/// Returns true if the element has a CSS transition (including running transitions and
/// completed transitions).
fn has_css_transitions(&self) -> bool;
/// Returns true if the element has animation restyle hints.
fn has_animation_restyle_hints(&self) -> bool {
let data = match self.borrow_data() {
Some(d) => d,
None => return false,
};
return data.get_restyle()
.map_or(false, |r| r.hint.has_animation_hint());
}
/// Gets declarations from XBL bindings from the element. Only gecko element could have this.
fn get_declarations_from_xbl_bindings<V>(&self,
_: &mut V)
-> bool
where V: Push<ApplicableDeclarationBlock> + VecLike<ApplicableDeclarationBlock> {
false
}
/// Gets the current existing CSS transitions, by |property, end value| pairs in a HashMap.
#[cfg(feature = "gecko")]
fn get_css_transitions_info(&self)
-> HashMap<TransitionProperty, Arc<AnimationValue>>;
/// Does a rough (and cheap) check for whether or not transitions might need to be updated that
/// will quickly return false for the common case of no transitions specified or running. If
/// this returns false, we definitely don't need to update transitions but if it returns true
/// we can perform the more thoroughgoing check, needs_transitions_update, to further
/// reduce the possibility of false positives.
#[cfg(feature = "gecko")]
fn might_need_transitions_update(&self,
old_values: Option<&ComputedValues>,
new_values: &ComputedValues)
-> bool;
/// Returns true if one of the transitions needs to be updated on this element. We check all
/// the transition properties to make sure that updating transitions is necessary.
/// This method should only be called if might_needs_transitions_update returns true when
/// passed the same parameters.
#[cfg(feature = "gecko")]
fn needs_transitions_update(&self,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues)
-> bool;
/// Returns true if we need to update transitions for the specified property on this element.
#[cfg(feature = "gecko")]
fn needs_transitions_update_per_property(&self,
property: &TransitionProperty,
combined_duration: f32,
before_change_style: &ComputedValues,
after_change_style: &ComputedValues,
existing_transitions: &HashMap<TransitionProperty,
Arc<AnimationValue>>)
-> bool;
/// Returns the value of the `xml:lang
|
needs_layout
|
identifier_name
|
lib.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod ast;
mod errors;
use std::{iter::Peekable, str::Chars};
pub use ast::{DocblockAST, DocblockField, DocblockSection};
use common::{
Diagnostic, DiagnosticsResult, Location, SourceLocationKey, Span, TextSource, WithLocation,
};
use errors::SyntaxError;
use intern::string_key::{Intern, StringKey};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DocblockSource(TextSource);
impl DocblockSource {
pub fn new(text: impl Into<String>, line_index: usize, column_index: usize) -> Self {
Self(TextSource {
text: text.into(),
line_index,
column_index,
})
}
pub fn text_source(&self) -> &TextSource {
&self.0
}
pub fn to_text_source(self) -> TextSource {
self.0
}
}
type ParseResult<T> = Result<T, ()>;
/// Parses a docblock's contents.
///
/// Expectes to be passed a string containing the _contents_ of a docblock (with
/// the leading `/*` and trailing `*/` already trimmed).
///
/// The sctructure of docblocks is not well defined. To avoid needing to be
/// opinionated, we use a relatively restricted definition for now:
///
/// * Docblocks consist of n "sections" where each section is either a key/value field, or free text.
/// * Each line must take the form: WHITE_SPACE* `*` WHITE_SPACE? LINE_CONTENT
/// * Free text sections may span one or more lines.
/// * Field sections are a _single line_ of the form: `@` FIELD_NAME WHITE_SPACE* VALUE
pub fn parse_docblock(
source: &str,
source_location: SourceLocationKey,
) -> DiagnosticsResult<DocblockAST> {
DocblockParser::new(source, source_location).parse()
}
/**
* Stateful parser that tries to model parsing of docblocks using recursive
* descent.
*
* Parsing docblocks in this fashion is a bit awkward because it's not possible
* to tokenize the input without being aware of context because we would like to
* tokenize the input differently based upon what we are trying to parse.
*
* For example:
* - Docblocks allow free text which might contain strings which should be
* considered tokens in other contexts.
*
* This is why lanuages designed to be expressible in a formal grammer deliniate
* strings with quotation marks.
*
* To account for this, we parse in a single pass, essentially treating each
* character as a token. This allows us to easily interperate characters
* differently in different contexts.
*/
struct DocblockParser<'a> {
source_location: SourceLocationKey,
chars: Peekable<Chars<'a>>,
offset: u32,
errors: Vec<Diagnostic>,
in_progress_text: Option<SpanString>,
sections: Vec<DocblockSection>,
}
impl<'a> DocblockParser<'a> {
fn new(source: &'a str, source_location: SourceLocationKey) -> Self {
let chars = source.chars().peekable();
Self {
errors: Vec::new(),
source_location,
offset: 0,
chars,
in_progress_text: None,
sections: Vec::new(),
}
}
fn parse(mut self) -> DiagnosticsResult<DocblockAST> {
let start = self.offset;
// By convention most docblocks start `/**`. Since we expect the leading
// `/*` to be trimmed before it's passed to us, we want to remove the
// second `*` and its trailing whitespace/newline.
if self.peek_char(&'*') {
self.next();
self.consume_whitespace();
}
let result = self.parse_sections();
let end = self.offset;
if self.errors.is_empty() {
result.expect("Expected no parse errors.");
Ok(DocblockAST {
sections: self.sections,
location: Location::new(
self.source_location,
/*
* TODO(T113385544): Investigate if this is actaully a bug in Span::to_range.
*
* I honestly don't fully understand this. We use
* self.offset as the end position for all other spans and
* they render perfectly. However, if we try to show a
* diagnostic of the full docblock (which we do when it's
* missing a field) it breaks Span::to_range because the end
* index is greater than the index of the last char that it
* iterates over, so it never sets an end_position and
* therefore shows the end position as 0,0 and VSCode
* renders an inverted diagnostic (a range starting at 0,0
* and ending at the start position.
*
* Anyway, subtracting 1 here solves the problem for now.
*/
Span::new(start, end - 1),
),
})
} else {
Err(self.errors)
}
}
/// Loop over chars, consuming a line at a time.
fn parse_sections(&mut self) -> ParseResult<()> {
while self.chars.peek().is_some() {
if!self.parse_margin()? {
// We reached the end of the input
break;
}
if self.peek_char(&'@') {
self.next();
// The fact the encountered a field tells us the previous
// free text section is now complete.
self.complete_previous_section();
self.parse_field()?;
} else {
let free_text = self.parse_free_text_line()?;
if let Some(previous) = self.in_progress_text.as_mut() {
previous.append_line(free_text)
} else {
self.in_progress_text = Some(free_text);
}
}
}
self.complete_previous_section();
Ok(())
}
/// Consume the ` * ` left margin, returning true/false indicating if we
/// read the full margin without reaching the end of the input.
fn parse_margin(&mut self) -> ParseResult<bool> {
self.consume_whitespace();
if self.chars.peek().is_none() {
return Ok(false);
}
self.expect_str("*")?;
if self.peek_char(&' ') {
self.next();
}
if self.chars.peek().is_none() {
return Ok(false);
}
Ok(true)
}
fn parse_field(&mut self) -> ParseResult<()> {
let field_name = self.parse_field_name()?;
self.consume_non_breaking_space();
let text = self.parse_free_text_line()?;
let field_value = if text.string.is_empty() {
None
} else {
Some(text.to_with_location(self.source_location))
};
self.sections.push(DocblockSection::Field(DocblockField {
field_name: field_name.to_with_location(self.source_location),
field_value,
}));
Ok(())
}
fn parse_field_name(&mut self) -> ParseResult<SpanString>
|
/// Read until the end of the line.
fn parse_free_text_line(&mut self) -> ParseResult<SpanString> {
let start = self.offset;
let free_text = self.take_while(|c| c!= &'\n');
let end = self.offset;
Ok(SpanString::new(Span::new(start, end), free_text))
}
fn complete_previous_section(&mut self) {
if let Some(free_text) = &self.in_progress_text {
if!free_text.string.is_empty() {
self.sections.push(DocblockSection::FreeText(
free_text.to_with_location(self.source_location),
));
}
self.in_progress_text = None;
}
}
fn consume_whitespace(&mut self) {
self.next_while(|c| c.is_whitespace());
}
fn consume_non_breaking_space(&mut self) {
self.next_while(|c| c == &''|| c == &'\t');
}
fn expect_str(&mut self, expected: &'static str) -> ParseResult<()> {
for c in expected.chars() {
if self.peek_char(&c) {
self.next();
} else {
self.errors.push(Diagnostic::error(
SyntaxError::ExpectedString { expected },
self.current_position(),
));
return Err(());
}
}
Ok(())
}
fn peek_char(&mut self, c: &char) -> bool {
self.chars.peek() == Some(c)
}
fn next(&mut self) {
self.chars.next();
self.offset += 1;
}
/// Advance over a string of characters matching predicate.
fn next_while(&mut self, predicate: fn(&char) -> bool) {
while let Some(c) = self.chars.peek() {
if predicate(c) {
self.next();
} else {
break;
}
}
}
/// Consume and return a string of characters matching predicate.
fn take_while(&mut self, predicate: fn(&char) -> bool) -> String {
let mut result = String::new();
while let Some(c) = self.chars.peek() {
if predicate(c) {
result.push(self.chars.next().unwrap());
} else {
break;
}
}
self.offset += result.len() as u32;
result
}
fn current_position(&self) -> Location {
Location::new(self.source_location, Span::new(self.offset, self.offset))
}
}
fn is_field_name_char(c: &char) -> bool {
c.is_alphanumeric() || c == &'_'
}
#[derive(Debug)]
struct SpanString {
span: Span,
string: String,
}
impl SpanString {
fn new(span: Span, string: String) -> Self {
Self { span, string }
}
fn append_line(&mut self, other: Self) {
self.string.push_str("\n");
self.string.push_str(&other.string);
self.span.end = other.span.end;
}
fn to_with_location(&self, source_location: SourceLocationKey) -> WithLocation<StringKey> {
WithLocation::from_span(source_location, self.span, self.string.clone().intern())
}
}
|
{
let start = self.offset;
let name = self.take_while(is_field_name_char);
if name.is_empty() {
self.errors.push(Diagnostic::error(
SyntaxError::ExpectedFieldName,
self.current_position(),
));
return Err(());
}
let end = self.offset;
Ok(SpanString::new(Span::new(start, end), name))
}
|
identifier_body
|
lib.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod ast;
mod errors;
use std::{iter::Peekable, str::Chars};
pub use ast::{DocblockAST, DocblockField, DocblockSection};
use common::{
Diagnostic, DiagnosticsResult, Location, SourceLocationKey, Span, TextSource, WithLocation,
};
use errors::SyntaxError;
use intern::string_key::{Intern, StringKey};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DocblockSource(TextSource);
impl DocblockSource {
pub fn new(text: impl Into<String>, line_index: usize, column_index: usize) -> Self {
Self(TextSource {
text: text.into(),
line_index,
column_index,
})
}
pub fn
|
(&self) -> &TextSource {
&self.0
}
pub fn to_text_source(self) -> TextSource {
self.0
}
}
type ParseResult<T> = Result<T, ()>;
/// Parses a docblock's contents.
///
/// Expectes to be passed a string containing the _contents_ of a docblock (with
/// the leading `/*` and trailing `*/` already trimmed).
///
/// The sctructure of docblocks is not well defined. To avoid needing to be
/// opinionated, we use a relatively restricted definition for now:
///
/// * Docblocks consist of n "sections" where each section is either a key/value field, or free text.
/// * Each line must take the form: WHITE_SPACE* `*` WHITE_SPACE? LINE_CONTENT
/// * Free text sections may span one or more lines.
/// * Field sections are a _single line_ of the form: `@` FIELD_NAME WHITE_SPACE* VALUE
pub fn parse_docblock(
source: &str,
source_location: SourceLocationKey,
) -> DiagnosticsResult<DocblockAST> {
DocblockParser::new(source, source_location).parse()
}
/**
* Stateful parser that tries to model parsing of docblocks using recursive
* descent.
*
* Parsing docblocks in this fashion is a bit awkward because it's not possible
* to tokenize the input without being aware of context because we would like to
* tokenize the input differently based upon what we are trying to parse.
*
* For example:
* - Docblocks allow free text which might contain strings which should be
* considered tokens in other contexts.
*
* This is why lanuages designed to be expressible in a formal grammer deliniate
* strings with quotation marks.
*
* To account for this, we parse in a single pass, essentially treating each
* character as a token. This allows us to easily interperate characters
* differently in different contexts.
*/
struct DocblockParser<'a> {
source_location: SourceLocationKey,
chars: Peekable<Chars<'a>>,
offset: u32,
errors: Vec<Diagnostic>,
in_progress_text: Option<SpanString>,
sections: Vec<DocblockSection>,
}
impl<'a> DocblockParser<'a> {
fn new(source: &'a str, source_location: SourceLocationKey) -> Self {
let chars = source.chars().peekable();
Self {
errors: Vec::new(),
source_location,
offset: 0,
chars,
in_progress_text: None,
sections: Vec::new(),
}
}
fn parse(mut self) -> DiagnosticsResult<DocblockAST> {
let start = self.offset;
// By convention most docblocks start `/**`. Since we expect the leading
// `/*` to be trimmed before it's passed to us, we want to remove the
// second `*` and its trailing whitespace/newline.
if self.peek_char(&'*') {
self.next();
self.consume_whitespace();
}
let result = self.parse_sections();
let end = self.offset;
if self.errors.is_empty() {
result.expect("Expected no parse errors.");
Ok(DocblockAST {
sections: self.sections,
location: Location::new(
self.source_location,
/*
* TODO(T113385544): Investigate if this is actaully a bug in Span::to_range.
*
* I honestly don't fully understand this. We use
* self.offset as the end position for all other spans and
* they render perfectly. However, if we try to show a
* diagnostic of the full docblock (which we do when it's
* missing a field) it breaks Span::to_range because the end
* index is greater than the index of the last char that it
* iterates over, so it never sets an end_position and
* therefore shows the end position as 0,0 and VSCode
* renders an inverted diagnostic (a range starting at 0,0
* and ending at the start position.
*
* Anyway, subtracting 1 here solves the problem for now.
*/
Span::new(start, end - 1),
),
})
} else {
Err(self.errors)
}
}
/// Loop over chars, consuming a line at a time.
fn parse_sections(&mut self) -> ParseResult<()> {
while self.chars.peek().is_some() {
if!self.parse_margin()? {
// We reached the end of the input
break;
}
if self.peek_char(&'@') {
self.next();
// The fact the encountered a field tells us the previous
// free text section is now complete.
self.complete_previous_section();
self.parse_field()?;
} else {
let free_text = self.parse_free_text_line()?;
if let Some(previous) = self.in_progress_text.as_mut() {
previous.append_line(free_text)
} else {
self.in_progress_text = Some(free_text);
}
}
}
self.complete_previous_section();
Ok(())
}
/// Consume the ` * ` left margin, returning true/false indicating if we
/// read the full margin without reaching the end of the input.
fn parse_margin(&mut self) -> ParseResult<bool> {
self.consume_whitespace();
if self.chars.peek().is_none() {
return Ok(false);
}
self.expect_str("*")?;
if self.peek_char(&' ') {
self.next();
}
if self.chars.peek().is_none() {
return Ok(false);
}
Ok(true)
}
fn parse_field(&mut self) -> ParseResult<()> {
let field_name = self.parse_field_name()?;
self.consume_non_breaking_space();
let text = self.parse_free_text_line()?;
let field_value = if text.string.is_empty() {
None
} else {
Some(text.to_with_location(self.source_location))
};
self.sections.push(DocblockSection::Field(DocblockField {
field_name: field_name.to_with_location(self.source_location),
field_value,
}));
Ok(())
}
fn parse_field_name(&mut self) -> ParseResult<SpanString> {
let start = self.offset;
let name = self.take_while(is_field_name_char);
if name.is_empty() {
self.errors.push(Diagnostic::error(
SyntaxError::ExpectedFieldName,
self.current_position(),
));
return Err(());
}
let end = self.offset;
Ok(SpanString::new(Span::new(start, end), name))
}
/// Read until the end of the line.
fn parse_free_text_line(&mut self) -> ParseResult<SpanString> {
let start = self.offset;
let free_text = self.take_while(|c| c!= &'\n');
let end = self.offset;
Ok(SpanString::new(Span::new(start, end), free_text))
}
fn complete_previous_section(&mut self) {
if let Some(free_text) = &self.in_progress_text {
if!free_text.string.is_empty() {
self.sections.push(DocblockSection::FreeText(
free_text.to_with_location(self.source_location),
));
}
self.in_progress_text = None;
}
}
fn consume_whitespace(&mut self) {
self.next_while(|c| c.is_whitespace());
}
fn consume_non_breaking_space(&mut self) {
self.next_while(|c| c == &''|| c == &'\t');
}
fn expect_str(&mut self, expected: &'static str) -> ParseResult<()> {
for c in expected.chars() {
if self.peek_char(&c) {
self.next();
} else {
self.errors.push(Diagnostic::error(
SyntaxError::ExpectedString { expected },
self.current_position(),
));
return Err(());
}
}
Ok(())
}
fn peek_char(&mut self, c: &char) -> bool {
self.chars.peek() == Some(c)
}
fn next(&mut self) {
self.chars.next();
self.offset += 1;
}
/// Advance over a string of characters matching predicate.
fn next_while(&mut self, predicate: fn(&char) -> bool) {
while let Some(c) = self.chars.peek() {
if predicate(c) {
self.next();
} else {
break;
}
}
}
/// Consume and return a string of characters matching predicate.
fn take_while(&mut self, predicate: fn(&char) -> bool) -> String {
let mut result = String::new();
while let Some(c) = self.chars.peek() {
if predicate(c) {
result.push(self.chars.next().unwrap());
} else {
break;
}
}
self.offset += result.len() as u32;
result
}
fn current_position(&self) -> Location {
Location::new(self.source_location, Span::new(self.offset, self.offset))
}
}
fn is_field_name_char(c: &char) -> bool {
c.is_alphanumeric() || c == &'_'
}
#[derive(Debug)]
struct SpanString {
span: Span,
string: String,
}
impl SpanString {
fn new(span: Span, string: String) -> Self {
Self { span, string }
}
fn append_line(&mut self, other: Self) {
self.string.push_str("\n");
self.string.push_str(&other.string);
self.span.end = other.span.end;
}
fn to_with_location(&self, source_location: SourceLocationKey) -> WithLocation<StringKey> {
WithLocation::from_span(source_location, self.span, self.string.clone().intern())
}
}
|
text_source
|
identifier_name
|
lib.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod ast;
mod errors;
use std::{iter::Peekable, str::Chars};
pub use ast::{DocblockAST, DocblockField, DocblockSection};
use common::{
Diagnostic, DiagnosticsResult, Location, SourceLocationKey, Span, TextSource, WithLocation,
};
use errors::SyntaxError;
use intern::string_key::{Intern, StringKey};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DocblockSource(TextSource);
impl DocblockSource {
pub fn new(text: impl Into<String>, line_index: usize, column_index: usize) -> Self {
Self(TextSource {
text: text.into(),
line_index,
column_index,
})
}
pub fn text_source(&self) -> &TextSource {
&self.0
}
pub fn to_text_source(self) -> TextSource {
self.0
}
}
type ParseResult<T> = Result<T, ()>;
/// Parses a docblock's contents.
///
/// Expectes to be passed a string containing the _contents_ of a docblock (with
/// the leading `/*` and trailing `*/` already trimmed).
///
/// The sctructure of docblocks is not well defined. To avoid needing to be
/// opinionated, we use a relatively restricted definition for now:
///
/// * Docblocks consist of n "sections" where each section is either a key/value field, or free text.
/// * Each line must take the form: WHITE_SPACE* `*` WHITE_SPACE? LINE_CONTENT
/// * Free text sections may span one or more lines.
/// * Field sections are a _single line_ of the form: `@` FIELD_NAME WHITE_SPACE* VALUE
pub fn parse_docblock(
source: &str,
source_location: SourceLocationKey,
) -> DiagnosticsResult<DocblockAST> {
DocblockParser::new(source, source_location).parse()
}
/**
* Stateful parser that tries to model parsing of docblocks using recursive
* descent.
*
* Parsing docblocks in this fashion is a bit awkward because it's not possible
* to tokenize the input without being aware of context because we would like to
* tokenize the input differently based upon what we are trying to parse.
*
* For example:
* - Docblocks allow free text which might contain strings which should be
* considered tokens in other contexts.
*
* This is why lanuages designed to be expressible in a formal grammer deliniate
* strings with quotation marks.
*
* To account for this, we parse in a single pass, essentially treating each
* character as a token. This allows us to easily interperate characters
* differently in different contexts.
*/
struct DocblockParser<'a> {
source_location: SourceLocationKey,
chars: Peekable<Chars<'a>>,
offset: u32,
errors: Vec<Diagnostic>,
in_progress_text: Option<SpanString>,
sections: Vec<DocblockSection>,
}
impl<'a> DocblockParser<'a> {
fn new(source: &'a str, source_location: SourceLocationKey) -> Self {
let chars = source.chars().peekable();
Self {
errors: Vec::new(),
source_location,
offset: 0,
chars,
in_progress_text: None,
sections: Vec::new(),
}
}
fn parse(mut self) -> DiagnosticsResult<DocblockAST> {
let start = self.offset;
// By convention most docblocks start `/**`. Since we expect the leading
// `/*` to be trimmed before it's passed to us, we want to remove the
// second `*` and its trailing whitespace/newline.
if self.peek_char(&'*') {
self.next();
self.consume_whitespace();
}
let result = self.parse_sections();
let end = self.offset;
if self.errors.is_empty() {
result.expect("Expected no parse errors.");
Ok(DocblockAST {
sections: self.sections,
location: Location::new(
self.source_location,
/*
* TODO(T113385544): Investigate if this is actaully a bug in Span::to_range.
*
* I honestly don't fully understand this. We use
* self.offset as the end position for all other spans and
* they render perfectly. However, if we try to show a
* diagnostic of the full docblock (which we do when it's
* missing a field) it breaks Span::to_range because the end
* index is greater than the index of the last char that it
* iterates over, so it never sets an end_position and
* therefore shows the end position as 0,0 and VSCode
* renders an inverted diagnostic (a range starting at 0,0
* and ending at the start position.
*
* Anyway, subtracting 1 here solves the problem for now.
*/
Span::new(start, end - 1),
),
})
} else {
Err(self.errors)
}
}
/// Loop over chars, consuming a line at a time.
fn parse_sections(&mut self) -> ParseResult<()> {
while self.chars.peek().is_some() {
if!self.parse_margin()? {
// We reached the end of the input
break;
}
if self.peek_char(&'@') {
self.next();
// The fact the encountered a field tells us the previous
// free text section is now complete.
self.complete_previous_section();
self.parse_field()?;
} else {
let free_text = self.parse_free_text_line()?;
if let Some(previous) = self.in_progress_text.as_mut() {
previous.append_line(free_text)
} else
|
}
}
self.complete_previous_section();
Ok(())
}
/// Consume the ` * ` left margin, returning true/false indicating if we
/// read the full margin without reaching the end of the input.
fn parse_margin(&mut self) -> ParseResult<bool> {
self.consume_whitespace();
if self.chars.peek().is_none() {
return Ok(false);
}
self.expect_str("*")?;
if self.peek_char(&' ') {
self.next();
}
if self.chars.peek().is_none() {
return Ok(false);
}
Ok(true)
}
fn parse_field(&mut self) -> ParseResult<()> {
let field_name = self.parse_field_name()?;
self.consume_non_breaking_space();
let text = self.parse_free_text_line()?;
let field_value = if text.string.is_empty() {
None
} else {
Some(text.to_with_location(self.source_location))
};
self.sections.push(DocblockSection::Field(DocblockField {
field_name: field_name.to_with_location(self.source_location),
field_value,
}));
Ok(())
}
fn parse_field_name(&mut self) -> ParseResult<SpanString> {
let start = self.offset;
let name = self.take_while(is_field_name_char);
if name.is_empty() {
self.errors.push(Diagnostic::error(
SyntaxError::ExpectedFieldName,
self.current_position(),
));
return Err(());
}
let end = self.offset;
Ok(SpanString::new(Span::new(start, end), name))
}
/// Read until the end of the line.
fn parse_free_text_line(&mut self) -> ParseResult<SpanString> {
let start = self.offset;
let free_text = self.take_while(|c| c!= &'\n');
let end = self.offset;
Ok(SpanString::new(Span::new(start, end), free_text))
}
fn complete_previous_section(&mut self) {
if let Some(free_text) = &self.in_progress_text {
if!free_text.string.is_empty() {
self.sections.push(DocblockSection::FreeText(
free_text.to_with_location(self.source_location),
));
}
self.in_progress_text = None;
}
}
fn consume_whitespace(&mut self) {
self.next_while(|c| c.is_whitespace());
}
fn consume_non_breaking_space(&mut self) {
self.next_while(|c| c == &''|| c == &'\t');
}
fn expect_str(&mut self, expected: &'static str) -> ParseResult<()> {
for c in expected.chars() {
if self.peek_char(&c) {
self.next();
} else {
self.errors.push(Diagnostic::error(
SyntaxError::ExpectedString { expected },
self.current_position(),
));
return Err(());
}
}
Ok(())
}
fn peek_char(&mut self, c: &char) -> bool {
self.chars.peek() == Some(c)
}
fn next(&mut self) {
self.chars.next();
self.offset += 1;
}
/// Advance over a string of characters matching predicate.
fn next_while(&mut self, predicate: fn(&char) -> bool) {
while let Some(c) = self.chars.peek() {
if predicate(c) {
self.next();
} else {
break;
}
}
}
/// Consume and return a string of characters matching predicate.
fn take_while(&mut self, predicate: fn(&char) -> bool) -> String {
let mut result = String::new();
while let Some(c) = self.chars.peek() {
if predicate(c) {
result.push(self.chars.next().unwrap());
} else {
break;
}
}
self.offset += result.len() as u32;
result
}
fn current_position(&self) -> Location {
Location::new(self.source_location, Span::new(self.offset, self.offset))
}
}
fn is_field_name_char(c: &char) -> bool {
c.is_alphanumeric() || c == &'_'
}
#[derive(Debug)]
struct SpanString {
span: Span,
string: String,
}
impl SpanString {
fn new(span: Span, string: String) -> Self {
Self { span, string }
}
fn append_line(&mut self, other: Self) {
self.string.push_str("\n");
self.string.push_str(&other.string);
self.span.end = other.span.end;
}
fn to_with_location(&self, source_location: SourceLocationKey) -> WithLocation<StringKey> {
WithLocation::from_span(source_location, self.span, self.string.clone().intern())
}
}
|
{
self.in_progress_text = Some(free_text);
}
|
conditional_block
|
lib.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
mod ast;
mod errors;
use std::{iter::Peekable, str::Chars};
pub use ast::{DocblockAST, DocblockField, DocblockSection};
use common::{
Diagnostic, DiagnosticsResult, Location, SourceLocationKey, Span, TextSource, WithLocation,
};
use errors::SyntaxError;
use intern::string_key::{Intern, StringKey};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct DocblockSource(TextSource);
impl DocblockSource {
pub fn new(text: impl Into<String>, line_index: usize, column_index: usize) -> Self {
Self(TextSource {
text: text.into(),
line_index,
column_index,
})
}
pub fn text_source(&self) -> &TextSource {
&self.0
}
pub fn to_text_source(self) -> TextSource {
self.0
}
}
type ParseResult<T> = Result<T, ()>;
/// Parses a docblock's contents.
///
/// Expectes to be passed a string containing the _contents_ of a docblock (with
/// the leading `/*` and trailing `*/` already trimmed).
///
/// The sctructure of docblocks is not well defined. To avoid needing to be
/// opinionated, we use a relatively restricted definition for now:
///
/// * Docblocks consist of n "sections" where each section is either a key/value field, or free text.
/// * Each line must take the form: WHITE_SPACE* `*` WHITE_SPACE? LINE_CONTENT
/// * Free text sections may span one or more lines.
/// * Field sections are a _single line_ of the form: `@` FIELD_NAME WHITE_SPACE* VALUE
pub fn parse_docblock(
source: &str,
source_location: SourceLocationKey,
) -> DiagnosticsResult<DocblockAST> {
DocblockParser::new(source, source_location).parse()
}
/**
* Stateful parser that tries to model parsing of docblocks using recursive
* descent.
*
* Parsing docblocks in this fashion is a bit awkward because it's not possible
* to tokenize the input without being aware of context because we would like to
* tokenize the input differently based upon what we are trying to parse.
*
* For example:
* - Docblocks allow free text which might contain strings which should be
* considered tokens in other contexts.
*
* This is why lanuages designed to be expressible in a formal grammer deliniate
* strings with quotation marks.
*
* To account for this, we parse in a single pass, essentially treating each
* character as a token. This allows us to easily interperate characters
* differently in different contexts.
*/
struct DocblockParser<'a> {
source_location: SourceLocationKey,
chars: Peekable<Chars<'a>>,
offset: u32,
errors: Vec<Diagnostic>,
in_progress_text: Option<SpanString>,
sections: Vec<DocblockSection>,
}
impl<'a> DocblockParser<'a> {
fn new(source: &'a str, source_location: SourceLocationKey) -> Self {
let chars = source.chars().peekable();
Self {
errors: Vec::new(),
source_location,
offset: 0,
chars,
in_progress_text: None,
sections: Vec::new(),
}
}
fn parse(mut self) -> DiagnosticsResult<DocblockAST> {
let start = self.offset;
// By convention most docblocks start `/**`. Since we expect the leading
// `/*` to be trimmed before it's passed to us, we want to remove the
// second `*` and its trailing whitespace/newline.
if self.peek_char(&'*') {
self.next();
self.consume_whitespace();
}
let result = self.parse_sections();
let end = self.offset;
if self.errors.is_empty() {
result.expect("Expected no parse errors.");
Ok(DocblockAST {
sections: self.sections,
location: Location::new(
self.source_location,
/*
* TODO(T113385544): Investigate if this is actaully a bug in Span::to_range.
*
* I honestly don't fully understand this. We use
* self.offset as the end position for all other spans and
* they render perfectly. However, if we try to show a
* diagnostic of the full docblock (which we do when it's
* missing a field) it breaks Span::to_range because the end
* index is greater than the index of the last char that it
* iterates over, so it never sets an end_position and
* therefore shows the end position as 0,0 and VSCode
* renders an inverted diagnostic (a range starting at 0,0
* and ending at the start position.
*
* Anyway, subtracting 1 here solves the problem for now.
*/
Span::new(start, end - 1),
),
})
} else {
Err(self.errors)
}
}
/// Loop over chars, consuming a line at a time.
fn parse_sections(&mut self) -> ParseResult<()> {
while self.chars.peek().is_some() {
if!self.parse_margin()? {
// We reached the end of the input
break;
}
if self.peek_char(&'@') {
self.next();
// The fact the encountered a field tells us the previous
// free text section is now complete.
self.complete_previous_section();
self.parse_field()?;
} else {
let free_text = self.parse_free_text_line()?;
if let Some(previous) = self.in_progress_text.as_mut() {
previous.append_line(free_text)
} else {
self.in_progress_text = Some(free_text);
}
}
}
self.complete_previous_section();
Ok(())
}
/// Consume the ` * ` left margin, returning true/false indicating if we
/// read the full margin without reaching the end of the input.
fn parse_margin(&mut self) -> ParseResult<bool> {
self.consume_whitespace();
if self.chars.peek().is_none() {
return Ok(false);
}
self.expect_str("*")?;
if self.peek_char(&' ') {
self.next();
}
if self.chars.peek().is_none() {
return Ok(false);
}
Ok(true)
}
fn parse_field(&mut self) -> ParseResult<()> {
let field_name = self.parse_field_name()?;
self.consume_non_breaking_space();
let text = self.parse_free_text_line()?;
let field_value = if text.string.is_empty() {
None
} else {
Some(text.to_with_location(self.source_location))
};
self.sections.push(DocblockSection::Field(DocblockField {
field_name: field_name.to_with_location(self.source_location),
field_value,
}));
Ok(())
}
fn parse_field_name(&mut self) -> ParseResult<SpanString> {
let start = self.offset;
let name = self.take_while(is_field_name_char);
if name.is_empty() {
self.errors.push(Diagnostic::error(
|
SyntaxError::ExpectedFieldName,
self.current_position(),
));
return Err(());
}
let end = self.offset;
Ok(SpanString::new(Span::new(start, end), name))
}
/// Read until the end of the line.
fn parse_free_text_line(&mut self) -> ParseResult<SpanString> {
let start = self.offset;
let free_text = self.take_while(|c| c!= &'\n');
let end = self.offset;
Ok(SpanString::new(Span::new(start, end), free_text))
}
fn complete_previous_section(&mut self) {
if let Some(free_text) = &self.in_progress_text {
if!free_text.string.is_empty() {
self.sections.push(DocblockSection::FreeText(
free_text.to_with_location(self.source_location),
));
}
self.in_progress_text = None;
}
}
fn consume_whitespace(&mut self) {
self.next_while(|c| c.is_whitespace());
}
fn consume_non_breaking_space(&mut self) {
self.next_while(|c| c == &''|| c == &'\t');
}
fn expect_str(&mut self, expected: &'static str) -> ParseResult<()> {
for c in expected.chars() {
if self.peek_char(&c) {
self.next();
} else {
self.errors.push(Diagnostic::error(
SyntaxError::ExpectedString { expected },
self.current_position(),
));
return Err(());
}
}
Ok(())
}
fn peek_char(&mut self, c: &char) -> bool {
self.chars.peek() == Some(c)
}
fn next(&mut self) {
self.chars.next();
self.offset += 1;
}
/// Advance over a string of characters matching predicate.
fn next_while(&mut self, predicate: fn(&char) -> bool) {
while let Some(c) = self.chars.peek() {
if predicate(c) {
self.next();
} else {
break;
}
}
}
/// Consume and return a string of characters matching predicate.
fn take_while(&mut self, predicate: fn(&char) -> bool) -> String {
let mut result = String::new();
while let Some(c) = self.chars.peek() {
if predicate(c) {
result.push(self.chars.next().unwrap());
} else {
break;
}
}
self.offset += result.len() as u32;
result
}
fn current_position(&self) -> Location {
Location::new(self.source_location, Span::new(self.offset, self.offset))
}
}
fn is_field_name_char(c: &char) -> bool {
c.is_alphanumeric() || c == &'_'
}
#[derive(Debug)]
struct SpanString {
span: Span,
string: String,
}
impl SpanString {
fn new(span: Span, string: String) -> Self {
Self { span, string }
}
fn append_line(&mut self, other: Self) {
self.string.push_str("\n");
self.string.push_str(&other.string);
self.span.end = other.span.end;
}
fn to_with_location(&self, source_location: SourceLocationKey) -> WithLocation<StringKey> {
WithLocation::from_span(source_location, self.span, self.string.clone().intern())
}
}
|
random_line_split
|
|
common.rs
|
/*
* Copyright 2015 Ben Ashford
*
* 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.
*/
//! Features common to all operations
use std::fmt;
use rustc_serialize::json::{Json, ToJson};
use util::StrJoin;
/// A newtype for the value of a URI option, this is to allow conversion traits
/// to be implemented for it
pub struct OptionVal(pub String);
/// Conversion from `&str` to `OptionVal`
impl<'a> From<&'a str> for OptionVal {
fn from(from: &'a str) -> OptionVal {
OptionVal(from.to_owned())
}
}
/// Basic types have conversions to `OptionVal`
from_exp!(String, OptionVal, from, OptionVal(from));
from_exp!(i32, OptionVal, from, OptionVal(from.to_string()));
from_exp!(i64, OptionVal, from, OptionVal(from.to_string()));
from_exp!(u32, OptionVal, from, OptionVal(from.to_string()));
from_exp!(u64, OptionVal, from, OptionVal(from.to_string()));
from_exp!(bool, OptionVal, from, OptionVal(from.to_string()));
/// Every ES operation has a set of options
pub struct Options<'a>(pub Vec<(&'a str, OptionVal)>);
impl<'a> Options<'a> {
pub fn new() -> Options<'a> {
Options(Vec::new())
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Add a value
///
/// ```
/// use rs_es::operations::common::Options;
/// let mut options = Options::new();
/// options.push("a", 1);
/// options.push("b", "2");
/// ```
pub fn push<O: Into<OptionVal>>(&mut self, key: &'a str, val: O) {
self.0.push((key, val.into()));
}
}
impl<'a> fmt::Display for Options<'a> {
fn
|
(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
if!self.is_empty() {
try!(formatter.write_str("?"));
try!(formatter.write_str(&self.0.iter().map(|&(ref k, ref v)| {
format!("{}={}", k, v.0)
}).join("&")));
}
Ok(())
}
}
/// Adds a function to an operation to add specific query-string options to that
/// operations builder interface.
macro_rules! add_option {
($n:ident, $e:expr) => (
pub fn $n<T: Into<OptionVal>>(&'a mut self, val: T) -> &'a mut Self {
self.options.push($e, val);
self
}
)
}
/// Broadly similar to the `add_option` macro for query-string options, but for
/// specifying fields in the Bulk request
macro_rules! add_field {
($n:ident, $f:ident, $t:ty) => (
pub fn $n<T: Into<$t>>(mut self, val: T) -> Self {
self.$f = Some(val.into());
self
}
)
}
/// The [`version_type` field](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-versioning)
#[allow(dead_code)]
pub enum VersionType {
Internal,
External,
ExternalGt,
ExternalGte,
Force
}
impl ToString for VersionType {
fn to_string(&self) -> String {
match *self {
VersionType::Internal => "internal",
VersionType::External => "external",
VersionType::ExternalGt => "external_gt",
VersionType::ExternalGte => "external_gte",
VersionType::Force => "force"
}.to_owned()
}
}
from_exp!(VersionType, OptionVal, from, OptionVal(from.to_string()));
impl ToJson for VersionType {
fn to_json(&self) -> Json {
Json::String(self.to_string())
}
}
/// The consistency query parameter
pub enum Consistency {
One,
Quorum,
All
}
impl From<Consistency> for OptionVal {
fn from(from: Consistency) -> OptionVal {
OptionVal(match from {
Consistency::One => "one",
Consistency::Quorum => "quorum",
Consistency::All => "all"
}.to_owned())
}
}
/// Values for `default_operator` query parameters
pub enum DefaultOperator {
And,
Or
}
impl From<DefaultOperator> for OptionVal {
fn from(from: DefaultOperator) -> OptionVal {
OptionVal(match from {
DefaultOperator::And => "and",
DefaultOperator::Or => "or"
}.to_owned())
}
}
|
fmt
|
identifier_name
|
common.rs
|
/*
* Copyright 2015 Ben Ashford
*
* 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.
*/
//! Features common to all operations
use std::fmt;
use rustc_serialize::json::{Json, ToJson};
use util::StrJoin;
/// A newtype for the value of a URI option, this is to allow conversion traits
/// to be implemented for it
pub struct OptionVal(pub String);
/// Conversion from `&str` to `OptionVal`
impl<'a> From<&'a str> for OptionVal {
fn from(from: &'a str) -> OptionVal {
OptionVal(from.to_owned())
}
}
/// Basic types have conversions to `OptionVal`
from_exp!(String, OptionVal, from, OptionVal(from));
from_exp!(i32, OptionVal, from, OptionVal(from.to_string()));
from_exp!(i64, OptionVal, from, OptionVal(from.to_string()));
from_exp!(u32, OptionVal, from, OptionVal(from.to_string()));
from_exp!(u64, OptionVal, from, OptionVal(from.to_string()));
from_exp!(bool, OptionVal, from, OptionVal(from.to_string()));
/// Every ES operation has a set of options
pub struct Options<'a>(pub Vec<(&'a str, OptionVal)>);
impl<'a> Options<'a> {
pub fn new() -> Options<'a> {
Options(Vec::new())
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Add a value
///
/// ```
/// use rs_es::operations::common::Options;
/// let mut options = Options::new();
/// options.push("a", 1);
/// options.push("b", "2");
/// ```
pub fn push<O: Into<OptionVal>>(&mut self, key: &'a str, val: O)
|
}
impl<'a> fmt::Display for Options<'a> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
if!self.is_empty() {
try!(formatter.write_str("?"));
try!(formatter.write_str(&self.0.iter().map(|&(ref k, ref v)| {
format!("{}={}", k, v.0)
}).join("&")));
}
Ok(())
}
}
/// Adds a function to an operation to add specific query-string options to that
/// operations builder interface.
macro_rules! add_option {
($n:ident, $e:expr) => (
pub fn $n<T: Into<OptionVal>>(&'a mut self, val: T) -> &'a mut Self {
self.options.push($e, val);
self
}
)
}
/// Broadly similar to the `add_option` macro for query-string options, but for
/// specifying fields in the Bulk request
macro_rules! add_field {
($n:ident, $f:ident, $t:ty) => (
pub fn $n<T: Into<$t>>(mut self, val: T) -> Self {
self.$f = Some(val.into());
self
}
)
}
/// The [`version_type` field](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-versioning)
#[allow(dead_code)]
pub enum VersionType {
Internal,
External,
ExternalGt,
ExternalGte,
Force
}
impl ToString for VersionType {
fn to_string(&self) -> String {
match *self {
VersionType::Internal => "internal",
VersionType::External => "external",
VersionType::ExternalGt => "external_gt",
VersionType::ExternalGte => "external_gte",
VersionType::Force => "force"
}.to_owned()
}
}
from_exp!(VersionType, OptionVal, from, OptionVal(from.to_string()));
impl ToJson for VersionType {
fn to_json(&self) -> Json {
Json::String(self.to_string())
}
}
/// The consistency query parameter
pub enum Consistency {
One,
Quorum,
All
}
impl From<Consistency> for OptionVal {
fn from(from: Consistency) -> OptionVal {
OptionVal(match from {
Consistency::One => "one",
Consistency::Quorum => "quorum",
Consistency::All => "all"
}.to_owned())
}
}
/// Values for `default_operator` query parameters
pub enum DefaultOperator {
And,
Or
}
impl From<DefaultOperator> for OptionVal {
fn from(from: DefaultOperator) -> OptionVal {
OptionVal(match from {
DefaultOperator::And => "and",
DefaultOperator::Or => "or"
}.to_owned())
}
}
|
{
self.0.push((key, val.into()));
}
|
identifier_body
|
common.rs
|
/*
* Copyright 2015 Ben Ashford
*
* 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.
*/
//! Features common to all operations
use std::fmt;
use rustc_serialize::json::{Json, ToJson};
use util::StrJoin;
/// A newtype for the value of a URI option, this is to allow conversion traits
/// to be implemented for it
pub struct OptionVal(pub String);
/// Conversion from `&str` to `OptionVal`
impl<'a> From<&'a str> for OptionVal {
fn from(from: &'a str) -> OptionVal {
OptionVal(from.to_owned())
}
}
/// Basic types have conversions to `OptionVal`
from_exp!(String, OptionVal, from, OptionVal(from));
from_exp!(i32, OptionVal, from, OptionVal(from.to_string()));
from_exp!(i64, OptionVal, from, OptionVal(from.to_string()));
from_exp!(u32, OptionVal, from, OptionVal(from.to_string()));
from_exp!(u64, OptionVal, from, OptionVal(from.to_string()));
from_exp!(bool, OptionVal, from, OptionVal(from.to_string()));
/// Every ES operation has a set of options
pub struct Options<'a>(pub Vec<(&'a str, OptionVal)>);
impl<'a> Options<'a> {
pub fn new() -> Options<'a> {
Options(Vec::new())
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Add a value
///
/// ```
/// use rs_es::operations::common::Options;
/// let mut options = Options::new();
/// options.push("a", 1);
/// options.push("b", "2");
/// ```
pub fn push<O: Into<OptionVal>>(&mut self, key: &'a str, val: O) {
self.0.push((key, val.into()));
}
}
impl<'a> fmt::Display for Options<'a> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
if!self.is_empty() {
try!(formatter.write_str("?"));
try!(formatter.write_str(&self.0.iter().map(|&(ref k, ref v)| {
format!("{}={}", k, v.0)
}).join("&")));
}
Ok(())
}
}
/// Adds a function to an operation to add specific query-string options to that
/// operations builder interface.
macro_rules! add_option {
($n:ident, $e:expr) => (
pub fn $n<T: Into<OptionVal>>(&'a mut self, val: T) -> &'a mut Self {
self.options.push($e, val);
self
}
)
}
/// Broadly similar to the `add_option` macro for query-string options, but for
/// specifying fields in the Bulk request
macro_rules! add_field {
($n:ident, $f:ident, $t:ty) => (
pub fn $n<T: Into<$t>>(mut self, val: T) -> Self {
self.$f = Some(val.into());
self
}
)
}
/// The [`version_type` field](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-versioning)
#[allow(dead_code)]
pub enum VersionType {
Internal,
External,
ExternalGt,
ExternalGte,
Force
}
impl ToString for VersionType {
fn to_string(&self) -> String {
match *self {
VersionType::Internal => "internal",
VersionType::External => "external",
VersionType::ExternalGt => "external_gt",
VersionType::ExternalGte => "external_gte",
VersionType::Force => "force"
}.to_owned()
}
}
from_exp!(VersionType, OptionVal, from, OptionVal(from.to_string()));
impl ToJson for VersionType {
fn to_json(&self) -> Json {
Json::String(self.to_string())
}
}
/// The consistency query parameter
pub enum Consistency {
One,
Quorum,
All
}
impl From<Consistency> for OptionVal {
fn from(from: Consistency) -> OptionVal {
OptionVal(match from {
Consistency::One => "one",
Consistency::Quorum => "quorum",
Consistency::All => "all"
}.to_owned())
|
}
}
/// Values for `default_operator` query parameters
pub enum DefaultOperator {
And,
Or
}
impl From<DefaultOperator> for OptionVal {
fn from(from: DefaultOperator) -> OptionVal {
OptionVal(match from {
DefaultOperator::And => "and",
DefaultOperator::Or => "or"
}.to_owned())
}
}
|
random_line_split
|
|
E0617.rs
|
// Copyright 2017 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.
// ignore-tidy-linelength
extern {
fn printf(c: *const i8,...);
}
fn
|
() {
unsafe {
printf(::std::ptr::null(), 0f32);
//~^ ERROR can't pass `f32` to variadic function
//~| HELP cast the value to `c_double`
printf(::std::ptr::null(), 0i8);
//~^ ERROR can't pass `i8` to variadic function
//~| HELP cast the value to `c_int`
printf(::std::ptr::null(), 0i16);
//~^ ERROR can't pass `i16` to variadic function
//~| HELP cast the value to `c_int`
printf(::std::ptr::null(), 0u8);
//~^ ERROR can't pass `u8` to variadic function
//~| HELP cast the value to `c_uint`
printf(::std::ptr::null(), 0u16);
//~^ ERROR can't pass `u16` to variadic function
//~| HELP cast the value to `c_uint`
printf(::std::ptr::null(), printf);
//~^ ERROR can't pass `unsafe extern "C" fn(*const i8,...) {printf}` to variadic function
//~| HELP cast the value to `unsafe extern "C" fn(*const i8,...)`
}
}
|
main
|
identifier_name
|
E0617.rs
|
// Copyright 2017 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.
// ignore-tidy-linelength
extern {
fn printf(c: *const i8,...);
}
fn main()
|
}
}
|
{
unsafe {
printf(::std::ptr::null(), 0f32);
//~^ ERROR can't pass `f32` to variadic function
//~| HELP cast the value to `c_double`
printf(::std::ptr::null(), 0i8);
//~^ ERROR can't pass `i8` to variadic function
//~| HELP cast the value to `c_int`
printf(::std::ptr::null(), 0i16);
//~^ ERROR can't pass `i16` to variadic function
//~| HELP cast the value to `c_int`
printf(::std::ptr::null(), 0u8);
//~^ ERROR can't pass `u8` to variadic function
//~| HELP cast the value to `c_uint`
printf(::std::ptr::null(), 0u16);
//~^ ERROR can't pass `u16` to variadic function
//~| HELP cast the value to `c_uint`
printf(::std::ptr::null(), printf);
//~^ ERROR can't pass `unsafe extern "C" fn(*const i8, ...) {printf}` to variadic function
//~| HELP cast the value to `unsafe extern "C" fn(*const i8, ...)`
|
identifier_body
|
E0617.rs
|
// Copyright 2017 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
|
// <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.
// ignore-tidy-linelength
extern {
fn printf(c: *const i8,...);
}
fn main() {
unsafe {
printf(::std::ptr::null(), 0f32);
//~^ ERROR can't pass `f32` to variadic function
//~| HELP cast the value to `c_double`
printf(::std::ptr::null(), 0i8);
//~^ ERROR can't pass `i8` to variadic function
//~| HELP cast the value to `c_int`
printf(::std::ptr::null(), 0i16);
//~^ ERROR can't pass `i16` to variadic function
//~| HELP cast the value to `c_int`
printf(::std::ptr::null(), 0u8);
//~^ ERROR can't pass `u8` to variadic function
//~| HELP cast the value to `c_uint`
printf(::std::ptr::null(), 0u16);
//~^ ERROR can't pass `u16` to variadic function
//~| HELP cast the value to `c_uint`
printf(::std::ptr::null(), printf);
//~^ ERROR can't pass `unsafe extern "C" fn(*const i8,...) {printf}` to variadic function
//~| HELP cast the value to `unsafe extern "C" fn(*const i8,...)`
}
}
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
random_line_split
|
lib.rs
|
//#![allow(dead_code, unused_must_use, unused_imports, unstable)]
// Temporary warning removal until old_io is updated et al.
#![feature(io, collections, core)]
#[macro_use] extern crate log;
use factory::{Record, RecordResult};
use std::string::ToString;
pub mod controller;
pub mod factory;
mod utils;
struct
|
{
factory: factory::Factory,
}
impl Txtdb {
pub fn new(factory: factory::Factory) -> Txtdb {
Txtdb {
factory: factory,
}
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn add<T: ToString>(&mut self, record: T) -> RecordResult<u64, String> {
//! Add a new record to the database. Returns the id of the record added.
Ok(1)
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn remove_id(&mut self, id: u64) -> RecordResult<Record, String> {
//! Removes a record with the id provided if it exists.
//! Returns a `RecordResult` of the record removed.
Err("Not implemented yet".to_string())
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn remove(&mut self, record: Record) -> RecordResult<u64, String> {
//! Finds and removes the first instance of a record that matches the one provided.
//! Returns the id of the record it removes.
Err("Not implemented yet".to_string())
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn find_id(id: u64) -> RecordResult<Record, String> {
//! Searches for a record with the id provided.
//! Returns a copy of the record.
// 1. Read each line?
// 2. Check if the ID matches
// 3. Return
Err("Not implemented yet".to_string())
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn find(&self, record: Record) -> RecordResult<u64, String> {
//! Searches for the first instance of a record that matches the one provided.
//! Returns the id of the record in the database.
// TODO, how do you create a `Record` if you don't know the id?
// Since we aren't using it, should we document not having the id in there?
//
// 1. Base64 encode the Record
// 2. Read each line to find the match encoded value
// 3. Return id
Err("Not implemented yet".to_string())
}
}
|
Txtdb
|
identifier_name
|
lib.rs
|
//#![allow(dead_code, unused_must_use, unused_imports, unstable)]
// Temporary warning removal until old_io is updated et al.
#![feature(io, collections, core)]
#[macro_use] extern crate log;
use factory::{Record, RecordResult};
use std::string::ToString;
pub mod controller;
pub mod factory;
mod utils;
struct Txtdb {
factory: factory::Factory,
}
impl Txtdb {
pub fn new(factory: factory::Factory) -> Txtdb {
Txtdb {
factory: factory,
}
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn add<T: ToString>(&mut self, record: T) -> RecordResult<u64, String> {
//! Add a new record to the database. Returns the id of the record added.
Ok(1)
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn remove_id(&mut self, id: u64) -> RecordResult<Record, String> {
//! Removes a record with the id provided if it exists.
//! Returns a `RecordResult` of the record removed.
Err("Not implemented yet".to_string())
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn remove(&mut self, record: Record) -> RecordResult<u64, String> {
//! Finds and removes the first instance of a record that matches the one provided.
//! Returns the id of the record it removes.
Err("Not implemented yet".to_string())
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn find_id(id: u64) -> RecordResult<Record, String> {
//! Searches for a record with the id provided.
//! Returns a copy of the record.
// 1. Read each line?
// 2. Check if the ID matches
// 3. Return
Err("Not implemented yet".to_string())
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn find(&self, record: Record) -> RecordResult<u64, String>
|
}
|
{
//! Searches for the first instance of a record that matches the one provided.
//! Returns the id of the record in the database.
// TODO, how do you create a `Record` if you don't know the id?
// Since we aren't using it, should we document not having the id in there?
//
// 1. Base64 encode the Record
// 2. Read each line to find the match encoded value
// 3. Return id
Err("Not implemented yet".to_string())
}
|
identifier_body
|
lib.rs
|
//#![allow(dead_code, unused_must_use, unused_imports, unstable)]
// Temporary warning removal until old_io is updated et al.
#![feature(io, collections, core)]
#[macro_use] extern crate log;
use factory::{Record, RecordResult};
use std::string::ToString;
pub mod controller;
pub mod factory;
mod utils;
struct Txtdb {
factory: factory::Factory,
}
impl Txtdb {
pub fn new(factory: factory::Factory) -> Txtdb {
Txtdb {
factory: factory,
}
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn add<T: ToString>(&mut self, record: T) -> RecordResult<u64, String> {
//! Add a new record to the database. Returns the id of the record added.
Ok(1)
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn remove_id(&mut self, id: u64) -> RecordResult<Record, String> {
//! Removes a record with the id provided if it exists.
//! Returns a `RecordResult` of the record removed.
Err("Not implemented yet".to_string())
}
|
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn find_id(id: u64) -> RecordResult<Record, String> {
//! Searches for a record with the id provided.
//! Returns a copy of the record.
// 1. Read each line?
// 2. Check if the ID matches
// 3. Return
Err("Not implemented yet".to_string())
}
#[allow(dead_code, unused_must_use, unused_variables)]
fn find(&self, record: Record) -> RecordResult<u64, String> {
//! Searches for the first instance of a record that matches the one provided.
//! Returns the id of the record in the database.
// TODO, how do you create a `Record` if you don't know the id?
// Since we aren't using it, should we document not having the id in there?
//
// 1. Base64 encode the Record
// 2. Read each line to find the match encoded value
// 3. Return id
Err("Not implemented yet".to_string())
}
}
|
#[allow(dead_code, unused_must_use, unused_variables)]
fn remove(&mut self, record: Record) -> RecordResult<u64, String> {
//! Finds and removes the first instance of a record that matches the one provided.
//! Returns the id of the record it removes.
Err("Not implemented yet".to_string())
|
random_line_split
|
mod.rs
|
/*
* Copyright (C) 2017 AltOS-Rust Team
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
//! This module provides types for configuring and controlling GPIO connections.
mod port;
mod moder;
mod otyper;
mod bsrr;
mod ospeedr;
mod pupdr;
mod afr;
mod defs;
use core::ops::{Deref, DerefMut};
use volatile::Volatile;
use super::rcc;
use self::defs::*;
pub use self::port::Port;
pub use self::moder::Mode;
pub use self::otyper::Type;
pub use self::ospeedr::Speed;
pub use self::pupdr::Pull;
pub use self::afr::AlternateFunction;
use self::moder::MODER;
use self::otyper::OTYPER;
use self::ospeedr::OSPEEDR;
use self::pupdr::PUPDR;
use self::bsrr::BSRR;
use self::afr::{AFRL, AFRH};
/// An IO group containing up to 16 pins. For some reason, the datasheet shows the memory
/// for groups D and E as reserved, so for now they are left out.
#[derive(Copy, Clone)]
pub enum Group {
/// GPIO Group A
A,
/// GPIO Group B
B,
/// GPIO Group C
C,
/// GPIO Group F
F,
}
/// A GPIO contains the base address for a memory mapped GPIO group associated with it.
#[derive(Copy, Clone, Debug)]
#[repr(C)]
#[doc(hidden)]
pub struct RawGPIO {
moder: MODER,
otyper: OTYPER,
ospeedr: OSPEEDR,
pupdr: PUPDR,
idr: u32,
odr: u32,
bsrr: BSRR,
lckr: u32,
afrl: AFRL,
afrh: AFRH,
brr: u32,
}
/// Creates struct for accessing the GPIO groups.
///
/// Has a RawGPIO data member in order to access each register for the
/// GPIO peripheral.
#[derive(Copy, Clone, Debug)]
pub struct GPIO(Volatile<RawGPIO>);
impl GPIO {
fn group(group: Group) -> GPIO {
match group {
Group::A => GPIO::new(GROUPA_ADDR),
Group::B => GPIO::new(GROUPB_ADDR),
Group::C => GPIO::new(GROUPC_ADDR),
Group::F => GPIO::new(GROUPF_ADDR),
}
}
fn new(mem_addr: *const u32) -> GPIO {
unsafe {
GPIO(Volatile::new(mem_addr as *const _))
}
}
/// Wrapper for enabling a GPIO group.
pub fn enable(group: Group) {
RawGPIO::enable(group);
}
}
impl Deref for GPIO {
type Target = RawGPIO;
fn deref(&self) -> &Self::Target {
&*(self.0)
}
}
impl DerefMut for GPIO {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *(self.0)
}
}
impl RawGPIO {
/// Enable a GPIO group. This must be done before setting any pins within a group.
///
/// Example Usage:
/// ```
/// GPIO::enable(Group::B); // Enable IO group B (LED is pb3)
/// ```
pub fn enable(group: Group) {
let mut rcc = rcc::rcc();
// Get the register bit that should be set to enable this group
let io_group = match group {
Group::A => rcc::Peripheral::GPIOA,
Group::B => rcc::Peripheral::GPIOB,
Group::C => rcc::Peripheral::GPIOC,
Group::F => rcc::Peripheral::GPIOF,
};
rcc.enable_peripheral(io_group);
}
/// Set the mode for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_mode(&mut self, mode: Mode, port: u8) {
self.moder.set_mode(mode, port);
}
/// Gets the mode for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_mode(&self, port: u8) -> Mode {
self.moder.get_mode(port)
}
/// Sets the type for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_type(&mut self, p_type: Type, port: u8) {
self.otyper.set_type(p_type, port);
}
/// Gets the type for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_type(&self, port: u8) -> Type {
self.otyper.get_type(port)
}
/// Turns on GPIO pin at specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_bit(&mut self, port: u8) {
self.bsrr.set(port);
}
/// Resets bit at specified port.
///
/// # Panics
///
|
self.bsrr.reset(port);
}
/// Sets the port speed for the GPIO pin.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_speed(&mut self, speed: Speed, port: u8) {
self.ospeedr.set_speed(speed, port);
}
/// Get the current port speed.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_speed(&self, port: u8) -> Speed {
self.ospeedr.get_speed(port)
}
/// Set behavior of GPIO pin when it is not asserted.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_pull(&mut self, pull: Pull, port: u8) {
self.pupdr.set_pull(pull, port);
}
/// Get currently defined behavior of GPIO pin when not asserted.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_pull(&self, port: u8) -> Pull {
self.pupdr.get_pull(port)
}
/// Set the GPIO function type.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_function(&mut self, function: AlternateFunction, port: u8) {
match port {
0...7 => self.afrl.set_function(function, port),
8...15 => self.afrh.set_function(function, port),
_ => panic!("AFRL/AFRH::set_function - specified port must be between [0..15]!"),
}
}
/// Get the GPIO function type.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_function(&self, port: u8) -> AlternateFunction {
match port {
0...7 => self.afrl.get_function(port),
8...15 => self.afrh.get_function(port),
_ => panic!("AFRL/AFRH::set_function - specified port must be between [0..15]!"),
}
}
}
|
/// Port must be a value between [0..15] or the kernel will panic.
fn reset_bit(&mut self, port: u8) {
|
random_line_split
|
mod.rs
|
/*
* Copyright (C) 2017 AltOS-Rust Team
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
//! This module provides types for configuring and controlling GPIO connections.
mod port;
mod moder;
mod otyper;
mod bsrr;
mod ospeedr;
mod pupdr;
mod afr;
mod defs;
use core::ops::{Deref, DerefMut};
use volatile::Volatile;
use super::rcc;
use self::defs::*;
pub use self::port::Port;
pub use self::moder::Mode;
pub use self::otyper::Type;
pub use self::ospeedr::Speed;
pub use self::pupdr::Pull;
pub use self::afr::AlternateFunction;
use self::moder::MODER;
use self::otyper::OTYPER;
use self::ospeedr::OSPEEDR;
use self::pupdr::PUPDR;
use self::bsrr::BSRR;
use self::afr::{AFRL, AFRH};
/// An IO group containing up to 16 pins. For some reason, the datasheet shows the memory
/// for groups D and E as reserved, so for now they are left out.
#[derive(Copy, Clone)]
pub enum Group {
/// GPIO Group A
A,
/// GPIO Group B
B,
/// GPIO Group C
C,
/// GPIO Group F
F,
}
/// A GPIO contains the base address for a memory mapped GPIO group associated with it.
#[derive(Copy, Clone, Debug)]
#[repr(C)]
#[doc(hidden)]
pub struct RawGPIO {
moder: MODER,
otyper: OTYPER,
ospeedr: OSPEEDR,
pupdr: PUPDR,
idr: u32,
odr: u32,
bsrr: BSRR,
lckr: u32,
afrl: AFRL,
afrh: AFRH,
brr: u32,
}
/// Creates struct for accessing the GPIO groups.
///
/// Has a RawGPIO data member in order to access each register for the
/// GPIO peripheral.
#[derive(Copy, Clone, Debug)]
pub struct GPIO(Volatile<RawGPIO>);
impl GPIO {
fn group(group: Group) -> GPIO {
match group {
Group::A => GPIO::new(GROUPA_ADDR),
Group::B => GPIO::new(GROUPB_ADDR),
Group::C => GPIO::new(GROUPC_ADDR),
Group::F => GPIO::new(GROUPF_ADDR),
}
}
fn new(mem_addr: *const u32) -> GPIO {
unsafe {
GPIO(Volatile::new(mem_addr as *const _))
}
}
/// Wrapper for enabling a GPIO group.
pub fn enable(group: Group)
|
}
impl Deref for GPIO {
type Target = RawGPIO;
fn deref(&self) -> &Self::Target {
&*(self.0)
}
}
impl DerefMut for GPIO {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *(self.0)
}
}
impl RawGPIO {
/// Enable a GPIO group. This must be done before setting any pins within a group.
///
/// Example Usage:
/// ```
/// GPIO::enable(Group::B); // Enable IO group B (LED is pb3)
/// ```
pub fn enable(group: Group) {
let mut rcc = rcc::rcc();
// Get the register bit that should be set to enable this group
let io_group = match group {
Group::A => rcc::Peripheral::GPIOA,
Group::B => rcc::Peripheral::GPIOB,
Group::C => rcc::Peripheral::GPIOC,
Group::F => rcc::Peripheral::GPIOF,
};
rcc.enable_peripheral(io_group);
}
/// Set the mode for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_mode(&mut self, mode: Mode, port: u8) {
self.moder.set_mode(mode, port);
}
/// Gets the mode for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_mode(&self, port: u8) -> Mode {
self.moder.get_mode(port)
}
/// Sets the type for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_type(&mut self, p_type: Type, port: u8) {
self.otyper.set_type(p_type, port);
}
/// Gets the type for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_type(&self, port: u8) -> Type {
self.otyper.get_type(port)
}
/// Turns on GPIO pin at specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_bit(&mut self, port: u8) {
self.bsrr.set(port);
}
/// Resets bit at specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn reset_bit(&mut self, port: u8) {
self.bsrr.reset(port);
}
/// Sets the port speed for the GPIO pin.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_speed(&mut self, speed: Speed, port: u8) {
self.ospeedr.set_speed(speed, port);
}
/// Get the current port speed.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_speed(&self, port: u8) -> Speed {
self.ospeedr.get_speed(port)
}
/// Set behavior of GPIO pin when it is not asserted.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_pull(&mut self, pull: Pull, port: u8) {
self.pupdr.set_pull(pull, port);
}
/// Get currently defined behavior of GPIO pin when not asserted.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_pull(&self, port: u8) -> Pull {
self.pupdr.get_pull(port)
}
/// Set the GPIO function type.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_function(&mut self, function: AlternateFunction, port: u8) {
match port {
0...7 => self.afrl.set_function(function, port),
8...15 => self.afrh.set_function(function, port),
_ => panic!("AFRL/AFRH::set_function - specified port must be between [0..15]!"),
}
}
/// Get the GPIO function type.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_function(&self, port: u8) -> AlternateFunction {
match port {
0...7 => self.afrl.get_function(port),
8...15 => self.afrh.get_function(port),
_ => panic!("AFRL/AFRH::set_function - specified port must be between [0..15]!"),
}
}
}
|
{
RawGPIO::enable(group);
}
|
identifier_body
|
mod.rs
|
/*
* Copyright (C) 2017 AltOS-Rust Team
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
//! This module provides types for configuring and controlling GPIO connections.
mod port;
mod moder;
mod otyper;
mod bsrr;
mod ospeedr;
mod pupdr;
mod afr;
mod defs;
use core::ops::{Deref, DerefMut};
use volatile::Volatile;
use super::rcc;
use self::defs::*;
pub use self::port::Port;
pub use self::moder::Mode;
pub use self::otyper::Type;
pub use self::ospeedr::Speed;
pub use self::pupdr::Pull;
pub use self::afr::AlternateFunction;
use self::moder::MODER;
use self::otyper::OTYPER;
use self::ospeedr::OSPEEDR;
use self::pupdr::PUPDR;
use self::bsrr::BSRR;
use self::afr::{AFRL, AFRH};
/// An IO group containing up to 16 pins. For some reason, the datasheet shows the memory
/// for groups D and E as reserved, so for now they are left out.
#[derive(Copy, Clone)]
pub enum Group {
/// GPIO Group A
A,
/// GPIO Group B
B,
/// GPIO Group C
C,
/// GPIO Group F
F,
}
/// A GPIO contains the base address for a memory mapped GPIO group associated with it.
#[derive(Copy, Clone, Debug)]
#[repr(C)]
#[doc(hidden)]
pub struct RawGPIO {
moder: MODER,
otyper: OTYPER,
ospeedr: OSPEEDR,
pupdr: PUPDR,
idr: u32,
odr: u32,
bsrr: BSRR,
lckr: u32,
afrl: AFRL,
afrh: AFRH,
brr: u32,
}
/// Creates struct for accessing the GPIO groups.
///
/// Has a RawGPIO data member in order to access each register for the
/// GPIO peripheral.
#[derive(Copy, Clone, Debug)]
pub struct GPIO(Volatile<RawGPIO>);
impl GPIO {
fn group(group: Group) -> GPIO {
match group {
Group::A => GPIO::new(GROUPA_ADDR),
Group::B => GPIO::new(GROUPB_ADDR),
Group::C => GPIO::new(GROUPC_ADDR),
Group::F => GPIO::new(GROUPF_ADDR),
}
}
fn new(mem_addr: *const u32) -> GPIO {
unsafe {
GPIO(Volatile::new(mem_addr as *const _))
}
}
/// Wrapper for enabling a GPIO group.
pub fn enable(group: Group) {
RawGPIO::enable(group);
}
}
impl Deref for GPIO {
type Target = RawGPIO;
fn deref(&self) -> &Self::Target {
&*(self.0)
}
}
impl DerefMut for GPIO {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut *(self.0)
}
}
impl RawGPIO {
/// Enable a GPIO group. This must be done before setting any pins within a group.
///
/// Example Usage:
/// ```
/// GPIO::enable(Group::B); // Enable IO group B (LED is pb3)
/// ```
pub fn enable(group: Group) {
let mut rcc = rcc::rcc();
// Get the register bit that should be set to enable this group
let io_group = match group {
Group::A => rcc::Peripheral::GPIOA,
Group::B => rcc::Peripheral::GPIOB,
Group::C => rcc::Peripheral::GPIOC,
Group::F => rcc::Peripheral::GPIOF,
};
rcc.enable_peripheral(io_group);
}
/// Set the mode for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_mode(&mut self, mode: Mode, port: u8) {
self.moder.set_mode(mode, port);
}
/// Gets the mode for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_mode(&self, port: u8) -> Mode {
self.moder.get_mode(port)
}
/// Sets the type for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_type(&mut self, p_type: Type, port: u8) {
self.otyper.set_type(p_type, port);
}
/// Gets the type for the specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_type(&self, port: u8) -> Type {
self.otyper.get_type(port)
}
/// Turns on GPIO pin at specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_bit(&mut self, port: u8) {
self.bsrr.set(port);
}
/// Resets bit at specified port.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn reset_bit(&mut self, port: u8) {
self.bsrr.reset(port);
}
/// Sets the port speed for the GPIO pin.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_speed(&mut self, speed: Speed, port: u8) {
self.ospeedr.set_speed(speed, port);
}
/// Get the current port speed.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_speed(&self, port: u8) -> Speed {
self.ospeedr.get_speed(port)
}
/// Set behavior of GPIO pin when it is not asserted.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_pull(&mut self, pull: Pull, port: u8) {
self.pupdr.set_pull(pull, port);
}
/// Get currently defined behavior of GPIO pin when not asserted.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn get_pull(&self, port: u8) -> Pull {
self.pupdr.get_pull(port)
}
/// Set the GPIO function type.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn set_function(&mut self, function: AlternateFunction, port: u8) {
match port {
0...7 => self.afrl.set_function(function, port),
8...15 => self.afrh.set_function(function, port),
_ => panic!("AFRL/AFRH::set_function - specified port must be between [0..15]!"),
}
}
/// Get the GPIO function type.
///
/// # Panics
///
/// Port must be a value between [0..15] or the kernel will panic.
fn
|
(&self, port: u8) -> AlternateFunction {
match port {
0...7 => self.afrl.get_function(port),
8...15 => self.afrh.get_function(port),
_ => panic!("AFRL/AFRH::set_function - specified port must be between [0..15]!"),
}
}
}
|
get_function
|
identifier_name
|
boxed.rs
|
use std::any::{self, Any};
use std::ops::Deref;
use neon_runtime::raw;
use neon_runtime::external;
use crate::context::{Context, FinalizeContext};
use crate::context::internal::Env;
use crate::handle::{Managed, Handle};
use crate::types::internal::ValueInternal;
use crate::types::Value;
type BoxAny = Box<dyn Any + Send +'static>;
/// A smart pointer for Rust data managed by the JavaScript engine.
///
/// The type `JsBox<T>` provides shared ownership of a value of type `T`,
/// allocated in the heap. The data is owned by the JavaScript engine and the
/// lifetime is managed by the JavaScript garbage collector.
///
/// Shared references in Rust disallow mutation by default, and `JsBox` is no
/// exception: you cannot generally obtain a mutable reference to something
/// inside a `JsBox`. If you need to mutate through a `JsBox`, use
/// [`Cell`](https://doc.rust-lang.org/std/cell/struct.Cell.html),
/// [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html),
/// or one of the other types that provide
/// [interior mutability](https://doc.rust-lang.org/book/ch15-05-interior-mutability.html).
///
/// Values contained by a `JsBox` must implement the `Finalize` trait. `Finalize::finalize`
/// will execute with the value in a `JsBox` immediately before the `JsBox` is garbage
/// collected. If no additional finalization is necessary, an emply implementation may
/// be provided.
///
///
/// ## `Deref` behavior
///
/// `JsBox<T>` automatically dereferences to `T` (via the `Deref` trait), so
/// you can call `T`'s method on a value of type `JsBox<T>`.
///
/// ```rust
/// # use neon::prelude::*;
/// # fn my_neon_function(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let vec: Handle<JsBox<Vec<_>>> = cx.boxed(vec![1, 2, 3]);
///
/// println!("Length: {}", vec.len());
/// # Ok(cx.undefined())
/// # }
/// ```
///
/// ## Examples
///
/// Passing some immutable data between Rust and JavaScript.
///
/// ```rust
/// # use neon::prelude::*;
/// # use std::path::{Path, PathBuf};
/// fn create_path(mut cx: FunctionContext) -> JsResult<JsBox<PathBuf>> {
/// let path = cx.argument::<JsString>(0)?.value(&mut cx);
/// let path = Path::new(&path).to_path_buf();
///
/// Ok(cx.boxed(path))
/// }
///
/// fn print_path(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let path = cx.argument::<JsBox<PathBuf>>(0)?;
///
/// println!("{}", path.display());
///
/// Ok(cx.undefined())
/// }
/// ```
///
/// Passing a user defined struct wrapped in a `RefCell` for mutability. This
/// pattern is useful for creating classes in JavaScript.
///
/// ```rust
/// # use neon::prelude::*;
/// # use std::cell::RefCell;
///
/// type BoxedPerson = JsBox<RefCell<Person>>;
///
/// struct Person {
/// name: String,
/// }
///
/// impl Finalize for Person {}
///
/// impl Person {
/// pub fn new(name: String) -> Self {
/// Person { name }
/// }
///
/// pub fn set_name(&mut self, name: String) {
/// self.name = name;
/// }
///
/// pub fn greet(&self) -> String {
/// format!("Hello, {}!", self.name)
/// }
/// }
///
/// fn person_new(mut cx: FunctionContext) -> JsResult<BoxedPerson> {
/// let name = cx.argument::<JsString>(0)?.value(&mut cx);
/// let person = RefCell::new(Person::new(name));
///
/// Ok(cx.boxed(person))
/// }
///
/// fn person_set_name(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let person = cx.argument::<BoxedPerson>(0)?;
/// let mut person = person.borrow_mut();
/// let name = cx.argument::<JsString>(1)?.value(&mut cx);
///
/// person.set_name(name);
///
/// Ok(cx.undefined())
/// }
///
/// fn person_greet(mut cx: FunctionContext) -> JsResult<JsString> {
/// let person = cx.argument::<BoxedPerson>(0)?;
/// let person = person.borrow();
/// let greeting = person.greet();
///
/// Ok(cx.string(greeting))
/// }
pub struct JsBox<T: Send +'static> {
local: raw::Local,
// Cached raw pointer to the data contained in the `JsBox`. This value is
// required to implement `Deref` for `JsBox`. Unlike most `Js` types, `JsBox`
// is not a transparent wrapper around a `napi_value` and cannot implement `This`.
//
// Safety: `JsBox` cannot verify the lifetime. Store a raw pointer to force
// uses to be marked unsafe. In practice, it can be treated as `'static` but
// should only be exposed as part of a `Handle` tied to a `Context` lifetime.
// Safety: The value must not move on the heap; we must never give a mutable
// reference to the data until the `JsBox` is no longer accessible.
raw_data: *const T,
}
// Attempt to use a `napi_value` as a `napi_external` to unwrap a `BoxAny>
/// Safety: `local` must be a `napi_value` that is valid for the lifetime `'a`.
unsafe fn maybe_external_deref<'a>(env: Env, local: raw::Local) -> Option<&'a BoxAny> {
external::deref::<BoxAny>(env.to_raw(), local)
.map(|v| &*v)
}
// Custom `Clone` implementation since `T` might not be `Clone`
impl<T: Send +'static> Clone for JsBox<T> {
fn clone(&self) -> Self {
JsBox {
local: self.local,
raw_data: self.raw_data,
}
}
}
impl<T: Send +'static> Copy for JsBox<T> {}
impl<T: Send +'static> Value for JsBox<T> { }
impl<T: Send +'static> Managed for JsBox<T> {
fn to_raw(self) -> raw::Local {
self.local
}
fn from_raw(env: Env, local: raw::Local) -> Self {
let raw_data = unsafe { maybe_external_deref(env, local) }
.expect("Failed to unwrap napi_external as Box<Any>")
.downcast_ref()
.expect("Failed to downcast Any");
Self {
local,
raw_data,
}
}
}
impl<T: Send +'static> ValueInternal for JsBox<T> {
fn name() -> String {
any::type_name::<Self>().to_string()
}
fn is_typeof<Other: Value>(env: Env, other: Other) -> bool
|
fn downcast<Other: Value>(env: Env, other: Other) -> Option<Self> {
let local = other.to_raw();
let data = unsafe { maybe_external_deref(env, local) };
// Attempt to downcast the `Option<&BoxAny>` to `Option<*const T>`
data.and_then(|v| v.downcast_ref())
.map(|raw_data| Self {
local,
raw_data,
})
}
}
/// Values contained by a `JsBox` must be `Finalize + Send +'static`
///
/// ### `Finalize`
///
/// The `neon::prelude::Finalize` trait provides a `finalize` method that will be called
/// immediately before the `JsBox` is garbage collected.
///
/// ### `Send`
///
/// `JsBox` may be moved across threads. It is important to guarantee that the
/// contents is also safe to move across threads.
///
/// ### `'static'
///
/// The lifetime of a `JsBox` is managed by the JavaScript garbage collector. Since Rust
/// is unable to verify the lifetime of the contents, references must be valid for the
/// entire duration of the program. This does not mean that the `JsBox` will be valid
/// until the application terminates, only that its lifetime is indefinite.
impl<T: Finalize + Send +'static> JsBox<T> {
/// Constructs a new `JsBox` containing `value`.
pub fn new<'a, C>(cx: &mut C, value: T) -> Handle<'a, JsBox<T>>
where
C: Context<'a>,
T: Send +'static,
{
// This function will execute immediately before the `JsBox` is garbage collected.
// It unwraps the `napi_external`, downcasts the `BoxAny` and moves the type
// out of the `Box`. Lastly, it calls the trait method `Finalize::fianlize` of the
// contained value `T`.
fn finalizer<U: Finalize +'static>(env: raw::Env, data: BoxAny) {
let data = *data.downcast::<U>().unwrap();
let env = unsafe { std::mem::transmute(env) };
FinalizeContext::with(
env,
move |mut cx| data.finalize(&mut cx),
);
}
let v = Box::new(value) as BoxAny;
// Since this value was just constructed, we know it is `T`
let raw_data = &*v as *const dyn Any as *const T;
let local = unsafe {
external::create(cx.env().to_raw(), v, finalizer::<T>)
};
Handle::new_internal(Self {
local,
raw_data,
})
}
}
impl<'a, T: Send +'static> Deref for JsBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// Safety: This depends on a `Handle<'a, JsBox<T>>` wrapper to provide
// a proper lifetime.
unsafe { &*self.raw_data }
}
}
/// Finalize is executed on the main JavaScript thread and executed immediately
/// before garbage collection.
/// Values contained by a `JsBox` must implement `Finalize`.
///
/// ## Examples
///
/// `Finalize` provides a default implementation that does not perform any finalization.
///
/// ```rust
/// # use neon::prelude::*;
/// struct Point(f64, f64);
///
/// impl Finalize for Point {}
/// ```
///
/// A `finalize` method may be specified for performing clean-up operations before dropping
/// the contained value.
///
/// ```rust
/// # use neon::prelude::*;
/// struct Point(f64, f64);
///
/// impl Finalize for Point {
/// fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
/// let global = cx.global();
/// let emit = global
/// .get(cx, "emit")
/// .unwrap()
/// .downcast::<JsFunction, _>(cx)
/// .unwrap();
///
/// let args = vec![
/// cx.string("gc_point").upcast::<JsValue>(),
/// cx.number(self.0).upcast(),
/// cx.number(self.1).upcast(),
/// ];
///
/// emit.call(cx, global, args).unwrap();
/// }
/// }
/// ```
pub trait Finalize: Sized {
fn finalize<'a, C: Context<'a>>(self, _: &mut C) {}
}
// Primitives
impl Finalize for bool {}
impl Finalize for char {}
impl Finalize for i8 {}
impl Finalize for i16 {}
impl Finalize for i32 {}
impl Finalize for i64 {}
impl Finalize for isize {}
impl Finalize for u8 {}
impl Finalize for u16 {}
impl Finalize for u32 {}
impl Finalize for u64 {}
impl Finalize for usize {}
impl Finalize for f32 {}
impl Finalize for f64 {}
// Common types
impl Finalize for String {}
impl Finalize for std::path::PathBuf {}
// Tuples
macro_rules! finalize_tuple_impls {
($( $name:ident )+) => {
impl<$($name: Finalize),+> Finalize for ($($name,)+) {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
#![allow(non_snake_case)]
let ($($name,)+) = self;
($($name.finalize(cx),)+);
}
}
};
}
impl Finalize for () {}
finalize_tuple_impls! { T0 }
finalize_tuple_impls! { T0 T1 }
finalize_tuple_impls! { T0 T1 T2 }
finalize_tuple_impls! { T0 T1 T2 T3 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 T7 }
// Collections
impl<T: Finalize> Finalize for Vec<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
for item in self {
item.finalize(cx);
}
}
}
// Smart Pointers
impl<T: Finalize> Finalize for std::boxed::Box<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
(*self).finalize(cx);
}
}
impl<T: Finalize> Finalize for std::rc::Rc<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = std::rc::Rc::try_unwrap(self) {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::Arc<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = std::sync::Arc::try_unwrap(self) {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::Mutex<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = self.into_inner() {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::RwLock<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = self.into_inner() {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::cell::Cell<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
self.into_inner().finalize(cx);
}
}
impl<T: Finalize> Finalize for std::cell::RefCell<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
self.into_inner().finalize(cx);
}
}
|
{
let data = unsafe { maybe_external_deref(env, other.to_raw()) };
data.map(|v| v.is::<T>()).unwrap_or(false)
}
|
identifier_body
|
boxed.rs
|
use std::any::{self, Any};
use std::ops::Deref;
use neon_runtime::raw;
use neon_runtime::external;
use crate::context::{Context, FinalizeContext};
use crate::context::internal::Env;
use crate::handle::{Managed, Handle};
use crate::types::internal::ValueInternal;
use crate::types::Value;
type BoxAny = Box<dyn Any + Send +'static>;
/// A smart pointer for Rust data managed by the JavaScript engine.
///
/// The type `JsBox<T>` provides shared ownership of a value of type `T`,
/// allocated in the heap. The data is owned by the JavaScript engine and the
/// lifetime is managed by the JavaScript garbage collector.
///
/// Shared references in Rust disallow mutation by default, and `JsBox` is no
/// exception: you cannot generally obtain a mutable reference to something
/// inside a `JsBox`. If you need to mutate through a `JsBox`, use
/// [`Cell`](https://doc.rust-lang.org/std/cell/struct.Cell.html),
/// [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html),
/// or one of the other types that provide
/// [interior mutability](https://doc.rust-lang.org/book/ch15-05-interior-mutability.html).
///
/// Values contained by a `JsBox` must implement the `Finalize` trait. `Finalize::finalize`
/// will execute with the value in a `JsBox` immediately before the `JsBox` is garbage
/// collected. If no additional finalization is necessary, an emply implementation may
/// be provided.
///
///
/// ## `Deref` behavior
///
/// `JsBox<T>` automatically dereferences to `T` (via the `Deref` trait), so
/// you can call `T`'s method on a value of type `JsBox<T>`.
///
/// ```rust
/// # use neon::prelude::*;
/// # fn my_neon_function(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let vec: Handle<JsBox<Vec<_>>> = cx.boxed(vec![1, 2, 3]);
///
/// println!("Length: {}", vec.len());
/// # Ok(cx.undefined())
/// # }
/// ```
///
/// ## Examples
///
/// Passing some immutable data between Rust and JavaScript.
///
/// ```rust
/// # use neon::prelude::*;
/// # use std::path::{Path, PathBuf};
/// fn create_path(mut cx: FunctionContext) -> JsResult<JsBox<PathBuf>> {
/// let path = cx.argument::<JsString>(0)?.value(&mut cx);
/// let path = Path::new(&path).to_path_buf();
///
/// Ok(cx.boxed(path))
|
/// }
///
/// fn print_path(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let path = cx.argument::<JsBox<PathBuf>>(0)?;
///
/// println!("{}", path.display());
///
/// Ok(cx.undefined())
/// }
/// ```
///
/// Passing a user defined struct wrapped in a `RefCell` for mutability. This
/// pattern is useful for creating classes in JavaScript.
///
/// ```rust
/// # use neon::prelude::*;
/// # use std::cell::RefCell;
///
/// type BoxedPerson = JsBox<RefCell<Person>>;
///
/// struct Person {
/// name: String,
/// }
///
/// impl Finalize for Person {}
///
/// impl Person {
/// pub fn new(name: String) -> Self {
/// Person { name }
/// }
///
/// pub fn set_name(&mut self, name: String) {
/// self.name = name;
/// }
///
/// pub fn greet(&self) -> String {
/// format!("Hello, {}!", self.name)
/// }
/// }
///
/// fn person_new(mut cx: FunctionContext) -> JsResult<BoxedPerson> {
/// let name = cx.argument::<JsString>(0)?.value(&mut cx);
/// let person = RefCell::new(Person::new(name));
///
/// Ok(cx.boxed(person))
/// }
///
/// fn person_set_name(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let person = cx.argument::<BoxedPerson>(0)?;
/// let mut person = person.borrow_mut();
/// let name = cx.argument::<JsString>(1)?.value(&mut cx);
///
/// person.set_name(name);
///
/// Ok(cx.undefined())
/// }
///
/// fn person_greet(mut cx: FunctionContext) -> JsResult<JsString> {
/// let person = cx.argument::<BoxedPerson>(0)?;
/// let person = person.borrow();
/// let greeting = person.greet();
///
/// Ok(cx.string(greeting))
/// }
pub struct JsBox<T: Send +'static> {
local: raw::Local,
// Cached raw pointer to the data contained in the `JsBox`. This value is
// required to implement `Deref` for `JsBox`. Unlike most `Js` types, `JsBox`
// is not a transparent wrapper around a `napi_value` and cannot implement `This`.
//
// Safety: `JsBox` cannot verify the lifetime. Store a raw pointer to force
// uses to be marked unsafe. In practice, it can be treated as `'static` but
// should only be exposed as part of a `Handle` tied to a `Context` lifetime.
// Safety: The value must not move on the heap; we must never give a mutable
// reference to the data until the `JsBox` is no longer accessible.
raw_data: *const T,
}
// Attempt to use a `napi_value` as a `napi_external` to unwrap a `BoxAny>
/// Safety: `local` must be a `napi_value` that is valid for the lifetime `'a`.
unsafe fn maybe_external_deref<'a>(env: Env, local: raw::Local) -> Option<&'a BoxAny> {
external::deref::<BoxAny>(env.to_raw(), local)
.map(|v| &*v)
}
// Custom `Clone` implementation since `T` might not be `Clone`
impl<T: Send +'static> Clone for JsBox<T> {
fn clone(&self) -> Self {
JsBox {
local: self.local,
raw_data: self.raw_data,
}
}
}
impl<T: Send +'static> Copy for JsBox<T> {}
impl<T: Send +'static> Value for JsBox<T> { }
impl<T: Send +'static> Managed for JsBox<T> {
fn to_raw(self) -> raw::Local {
self.local
}
fn from_raw(env: Env, local: raw::Local) -> Self {
let raw_data = unsafe { maybe_external_deref(env, local) }
.expect("Failed to unwrap napi_external as Box<Any>")
.downcast_ref()
.expect("Failed to downcast Any");
Self {
local,
raw_data,
}
}
}
impl<T: Send +'static> ValueInternal for JsBox<T> {
fn name() -> String {
any::type_name::<Self>().to_string()
}
fn is_typeof<Other: Value>(env: Env, other: Other) -> bool {
let data = unsafe { maybe_external_deref(env, other.to_raw()) };
data.map(|v| v.is::<T>()).unwrap_or(false)
}
fn downcast<Other: Value>(env: Env, other: Other) -> Option<Self> {
let local = other.to_raw();
let data = unsafe { maybe_external_deref(env, local) };
// Attempt to downcast the `Option<&BoxAny>` to `Option<*const T>`
data.and_then(|v| v.downcast_ref())
.map(|raw_data| Self {
local,
raw_data,
})
}
}
/// Values contained by a `JsBox` must be `Finalize + Send +'static`
///
/// ### `Finalize`
///
/// The `neon::prelude::Finalize` trait provides a `finalize` method that will be called
/// immediately before the `JsBox` is garbage collected.
///
/// ### `Send`
///
/// `JsBox` may be moved across threads. It is important to guarantee that the
/// contents is also safe to move across threads.
///
/// ### `'static'
///
/// The lifetime of a `JsBox` is managed by the JavaScript garbage collector. Since Rust
/// is unable to verify the lifetime of the contents, references must be valid for the
/// entire duration of the program. This does not mean that the `JsBox` will be valid
/// until the application terminates, only that its lifetime is indefinite.
impl<T: Finalize + Send +'static> JsBox<T> {
/// Constructs a new `JsBox` containing `value`.
pub fn new<'a, C>(cx: &mut C, value: T) -> Handle<'a, JsBox<T>>
where
C: Context<'a>,
T: Send +'static,
{
// This function will execute immediately before the `JsBox` is garbage collected.
// It unwraps the `napi_external`, downcasts the `BoxAny` and moves the type
// out of the `Box`. Lastly, it calls the trait method `Finalize::fianlize` of the
// contained value `T`.
fn finalizer<U: Finalize +'static>(env: raw::Env, data: BoxAny) {
let data = *data.downcast::<U>().unwrap();
let env = unsafe { std::mem::transmute(env) };
FinalizeContext::with(
env,
move |mut cx| data.finalize(&mut cx),
);
}
let v = Box::new(value) as BoxAny;
// Since this value was just constructed, we know it is `T`
let raw_data = &*v as *const dyn Any as *const T;
let local = unsafe {
external::create(cx.env().to_raw(), v, finalizer::<T>)
};
Handle::new_internal(Self {
local,
raw_data,
})
}
}
impl<'a, T: Send +'static> Deref for JsBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// Safety: This depends on a `Handle<'a, JsBox<T>>` wrapper to provide
// a proper lifetime.
unsafe { &*self.raw_data }
}
}
/// Finalize is executed on the main JavaScript thread and executed immediately
/// before garbage collection.
/// Values contained by a `JsBox` must implement `Finalize`.
///
/// ## Examples
///
/// `Finalize` provides a default implementation that does not perform any finalization.
///
/// ```rust
/// # use neon::prelude::*;
/// struct Point(f64, f64);
///
/// impl Finalize for Point {}
/// ```
///
/// A `finalize` method may be specified for performing clean-up operations before dropping
/// the contained value.
///
/// ```rust
/// # use neon::prelude::*;
/// struct Point(f64, f64);
///
/// impl Finalize for Point {
/// fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
/// let global = cx.global();
/// let emit = global
/// .get(cx, "emit")
/// .unwrap()
/// .downcast::<JsFunction, _>(cx)
/// .unwrap();
///
/// let args = vec![
/// cx.string("gc_point").upcast::<JsValue>(),
/// cx.number(self.0).upcast(),
/// cx.number(self.1).upcast(),
/// ];
///
/// emit.call(cx, global, args).unwrap();
/// }
/// }
/// ```
pub trait Finalize: Sized {
fn finalize<'a, C: Context<'a>>(self, _: &mut C) {}
}
// Primitives
impl Finalize for bool {}
impl Finalize for char {}
impl Finalize for i8 {}
impl Finalize for i16 {}
impl Finalize for i32 {}
impl Finalize for i64 {}
impl Finalize for isize {}
impl Finalize for u8 {}
impl Finalize for u16 {}
impl Finalize for u32 {}
impl Finalize for u64 {}
impl Finalize for usize {}
impl Finalize for f32 {}
impl Finalize for f64 {}
// Common types
impl Finalize for String {}
impl Finalize for std::path::PathBuf {}
// Tuples
macro_rules! finalize_tuple_impls {
($( $name:ident )+) => {
impl<$($name: Finalize),+> Finalize for ($($name,)+) {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
#![allow(non_snake_case)]
let ($($name,)+) = self;
($($name.finalize(cx),)+);
}
}
};
}
impl Finalize for () {}
finalize_tuple_impls! { T0 }
finalize_tuple_impls! { T0 T1 }
finalize_tuple_impls! { T0 T1 T2 }
finalize_tuple_impls! { T0 T1 T2 T3 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 T7 }
// Collections
impl<T: Finalize> Finalize for Vec<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
for item in self {
item.finalize(cx);
}
}
}
// Smart Pointers
impl<T: Finalize> Finalize for std::boxed::Box<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
(*self).finalize(cx);
}
}
impl<T: Finalize> Finalize for std::rc::Rc<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = std::rc::Rc::try_unwrap(self) {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::Arc<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = std::sync::Arc::try_unwrap(self) {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::Mutex<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = self.into_inner() {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::RwLock<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = self.into_inner() {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::cell::Cell<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
self.into_inner().finalize(cx);
}
}
impl<T: Finalize> Finalize for std::cell::RefCell<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
self.into_inner().finalize(cx);
}
}
|
random_line_split
|
|
boxed.rs
|
use std::any::{self, Any};
use std::ops::Deref;
use neon_runtime::raw;
use neon_runtime::external;
use crate::context::{Context, FinalizeContext};
use crate::context::internal::Env;
use crate::handle::{Managed, Handle};
use crate::types::internal::ValueInternal;
use crate::types::Value;
type BoxAny = Box<dyn Any + Send +'static>;
/// A smart pointer for Rust data managed by the JavaScript engine.
///
/// The type `JsBox<T>` provides shared ownership of a value of type `T`,
/// allocated in the heap. The data is owned by the JavaScript engine and the
/// lifetime is managed by the JavaScript garbage collector.
///
/// Shared references in Rust disallow mutation by default, and `JsBox` is no
/// exception: you cannot generally obtain a mutable reference to something
/// inside a `JsBox`. If you need to mutate through a `JsBox`, use
/// [`Cell`](https://doc.rust-lang.org/std/cell/struct.Cell.html),
/// [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html),
/// or one of the other types that provide
/// [interior mutability](https://doc.rust-lang.org/book/ch15-05-interior-mutability.html).
///
/// Values contained by a `JsBox` must implement the `Finalize` trait. `Finalize::finalize`
/// will execute with the value in a `JsBox` immediately before the `JsBox` is garbage
/// collected. If no additional finalization is necessary, an emply implementation may
/// be provided.
///
///
/// ## `Deref` behavior
///
/// `JsBox<T>` automatically dereferences to `T` (via the `Deref` trait), so
/// you can call `T`'s method on a value of type `JsBox<T>`.
///
/// ```rust
/// # use neon::prelude::*;
/// # fn my_neon_function(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let vec: Handle<JsBox<Vec<_>>> = cx.boxed(vec![1, 2, 3]);
///
/// println!("Length: {}", vec.len());
/// # Ok(cx.undefined())
/// # }
/// ```
///
/// ## Examples
///
/// Passing some immutable data between Rust and JavaScript.
///
/// ```rust
/// # use neon::prelude::*;
/// # use std::path::{Path, PathBuf};
/// fn create_path(mut cx: FunctionContext) -> JsResult<JsBox<PathBuf>> {
/// let path = cx.argument::<JsString>(0)?.value(&mut cx);
/// let path = Path::new(&path).to_path_buf();
///
/// Ok(cx.boxed(path))
/// }
///
/// fn print_path(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let path = cx.argument::<JsBox<PathBuf>>(0)?;
///
/// println!("{}", path.display());
///
/// Ok(cx.undefined())
/// }
/// ```
///
/// Passing a user defined struct wrapped in a `RefCell` for mutability. This
/// pattern is useful for creating classes in JavaScript.
///
/// ```rust
/// # use neon::prelude::*;
/// # use std::cell::RefCell;
///
/// type BoxedPerson = JsBox<RefCell<Person>>;
///
/// struct Person {
/// name: String,
/// }
///
/// impl Finalize for Person {}
///
/// impl Person {
/// pub fn new(name: String) -> Self {
/// Person { name }
/// }
///
/// pub fn set_name(&mut self, name: String) {
/// self.name = name;
/// }
///
/// pub fn greet(&self) -> String {
/// format!("Hello, {}!", self.name)
/// }
/// }
///
/// fn person_new(mut cx: FunctionContext) -> JsResult<BoxedPerson> {
/// let name = cx.argument::<JsString>(0)?.value(&mut cx);
/// let person = RefCell::new(Person::new(name));
///
/// Ok(cx.boxed(person))
/// }
///
/// fn person_set_name(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let person = cx.argument::<BoxedPerson>(0)?;
/// let mut person = person.borrow_mut();
/// let name = cx.argument::<JsString>(1)?.value(&mut cx);
///
/// person.set_name(name);
///
/// Ok(cx.undefined())
/// }
///
/// fn person_greet(mut cx: FunctionContext) -> JsResult<JsString> {
/// let person = cx.argument::<BoxedPerson>(0)?;
/// let person = person.borrow();
/// let greeting = person.greet();
///
/// Ok(cx.string(greeting))
/// }
pub struct JsBox<T: Send +'static> {
local: raw::Local,
// Cached raw pointer to the data contained in the `JsBox`. This value is
// required to implement `Deref` for `JsBox`. Unlike most `Js` types, `JsBox`
// is not a transparent wrapper around a `napi_value` and cannot implement `This`.
//
// Safety: `JsBox` cannot verify the lifetime. Store a raw pointer to force
// uses to be marked unsafe. In practice, it can be treated as `'static` but
// should only be exposed as part of a `Handle` tied to a `Context` lifetime.
// Safety: The value must not move on the heap; we must never give a mutable
// reference to the data until the `JsBox` is no longer accessible.
raw_data: *const T,
}
// Attempt to use a `napi_value` as a `napi_external` to unwrap a `BoxAny>
/// Safety: `local` must be a `napi_value` that is valid for the lifetime `'a`.
unsafe fn maybe_external_deref<'a>(env: Env, local: raw::Local) -> Option<&'a BoxAny> {
external::deref::<BoxAny>(env.to_raw(), local)
.map(|v| &*v)
}
// Custom `Clone` implementation since `T` might not be `Clone`
impl<T: Send +'static> Clone for JsBox<T> {
fn clone(&self) -> Self {
JsBox {
local: self.local,
raw_data: self.raw_data,
}
}
}
impl<T: Send +'static> Copy for JsBox<T> {}
impl<T: Send +'static> Value for JsBox<T> { }
impl<T: Send +'static> Managed for JsBox<T> {
fn to_raw(self) -> raw::Local {
self.local
}
fn from_raw(env: Env, local: raw::Local) -> Self {
let raw_data = unsafe { maybe_external_deref(env, local) }
.expect("Failed to unwrap napi_external as Box<Any>")
.downcast_ref()
.expect("Failed to downcast Any");
Self {
local,
raw_data,
}
}
}
impl<T: Send +'static> ValueInternal for JsBox<T> {
fn name() -> String {
any::type_name::<Self>().to_string()
}
fn is_typeof<Other: Value>(env: Env, other: Other) -> bool {
let data = unsafe { maybe_external_deref(env, other.to_raw()) };
data.map(|v| v.is::<T>()).unwrap_or(false)
}
fn downcast<Other: Value>(env: Env, other: Other) -> Option<Self> {
let local = other.to_raw();
let data = unsafe { maybe_external_deref(env, local) };
// Attempt to downcast the `Option<&BoxAny>` to `Option<*const T>`
data.and_then(|v| v.downcast_ref())
.map(|raw_data| Self {
local,
raw_data,
})
}
}
/// Values contained by a `JsBox` must be `Finalize + Send +'static`
///
/// ### `Finalize`
///
/// The `neon::prelude::Finalize` trait provides a `finalize` method that will be called
/// immediately before the `JsBox` is garbage collected.
///
/// ### `Send`
///
/// `JsBox` may be moved across threads. It is important to guarantee that the
/// contents is also safe to move across threads.
///
/// ### `'static'
///
/// The lifetime of a `JsBox` is managed by the JavaScript garbage collector. Since Rust
/// is unable to verify the lifetime of the contents, references must be valid for the
/// entire duration of the program. This does not mean that the `JsBox` will be valid
/// until the application terminates, only that its lifetime is indefinite.
impl<T: Finalize + Send +'static> JsBox<T> {
/// Constructs a new `JsBox` containing `value`.
pub fn new<'a, C>(cx: &mut C, value: T) -> Handle<'a, JsBox<T>>
where
C: Context<'a>,
T: Send +'static,
{
// This function will execute immediately before the `JsBox` is garbage collected.
// It unwraps the `napi_external`, downcasts the `BoxAny` and moves the type
// out of the `Box`. Lastly, it calls the trait method `Finalize::fianlize` of the
// contained value `T`.
fn finalizer<U: Finalize +'static>(env: raw::Env, data: BoxAny) {
let data = *data.downcast::<U>().unwrap();
let env = unsafe { std::mem::transmute(env) };
FinalizeContext::with(
env,
move |mut cx| data.finalize(&mut cx),
);
}
let v = Box::new(value) as BoxAny;
// Since this value was just constructed, we know it is `T`
let raw_data = &*v as *const dyn Any as *const T;
let local = unsafe {
external::create(cx.env().to_raw(), v, finalizer::<T>)
};
Handle::new_internal(Self {
local,
raw_data,
})
}
}
impl<'a, T: Send +'static> Deref for JsBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// Safety: This depends on a `Handle<'a, JsBox<T>>` wrapper to provide
// a proper lifetime.
unsafe { &*self.raw_data }
}
}
/// Finalize is executed on the main JavaScript thread and executed immediately
/// before garbage collection.
/// Values contained by a `JsBox` must implement `Finalize`.
///
/// ## Examples
///
/// `Finalize` provides a default implementation that does not perform any finalization.
///
/// ```rust
/// # use neon::prelude::*;
/// struct Point(f64, f64);
///
/// impl Finalize for Point {}
/// ```
///
/// A `finalize` method may be specified for performing clean-up operations before dropping
/// the contained value.
///
/// ```rust
/// # use neon::prelude::*;
/// struct Point(f64, f64);
///
/// impl Finalize for Point {
/// fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
/// let global = cx.global();
/// let emit = global
/// .get(cx, "emit")
/// .unwrap()
/// .downcast::<JsFunction, _>(cx)
/// .unwrap();
///
/// let args = vec![
/// cx.string("gc_point").upcast::<JsValue>(),
/// cx.number(self.0).upcast(),
/// cx.number(self.1).upcast(),
/// ];
///
/// emit.call(cx, global, args).unwrap();
/// }
/// }
/// ```
pub trait Finalize: Sized {
fn finalize<'a, C: Context<'a>>(self, _: &mut C) {}
}
// Primitives
impl Finalize for bool {}
impl Finalize for char {}
impl Finalize for i8 {}
impl Finalize for i16 {}
impl Finalize for i32 {}
impl Finalize for i64 {}
impl Finalize for isize {}
impl Finalize for u8 {}
impl Finalize for u16 {}
impl Finalize for u32 {}
impl Finalize for u64 {}
impl Finalize for usize {}
impl Finalize for f32 {}
impl Finalize for f64 {}
// Common types
impl Finalize for String {}
impl Finalize for std::path::PathBuf {}
// Tuples
macro_rules! finalize_tuple_impls {
($( $name:ident )+) => {
impl<$($name: Finalize),+> Finalize for ($($name,)+) {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
#![allow(non_snake_case)]
let ($($name,)+) = self;
($($name.finalize(cx),)+);
}
}
};
}
impl Finalize for () {}
finalize_tuple_impls! { T0 }
finalize_tuple_impls! { T0 T1 }
finalize_tuple_impls! { T0 T1 T2 }
finalize_tuple_impls! { T0 T1 T2 T3 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 T7 }
// Collections
impl<T: Finalize> Finalize for Vec<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
for item in self {
item.finalize(cx);
}
}
}
// Smart Pointers
impl<T: Finalize> Finalize for std::boxed::Box<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
(*self).finalize(cx);
}
}
impl<T: Finalize> Finalize for std::rc::Rc<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = std::rc::Rc::try_unwrap(self) {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::Arc<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = std::sync::Arc::try_unwrap(self)
|
}
}
impl<T: Finalize> Finalize for std::sync::Mutex<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = self.into_inner() {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::RwLock<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = self.into_inner() {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::cell::Cell<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
self.into_inner().finalize(cx);
}
}
impl<T: Finalize> Finalize for std::cell::RefCell<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
self.into_inner().finalize(cx);
}
}
|
{
v.finalize(cx);
}
|
conditional_block
|
boxed.rs
|
use std::any::{self, Any};
use std::ops::Deref;
use neon_runtime::raw;
use neon_runtime::external;
use crate::context::{Context, FinalizeContext};
use crate::context::internal::Env;
use crate::handle::{Managed, Handle};
use crate::types::internal::ValueInternal;
use crate::types::Value;
type BoxAny = Box<dyn Any + Send +'static>;
/// A smart pointer for Rust data managed by the JavaScript engine.
///
/// The type `JsBox<T>` provides shared ownership of a value of type `T`,
/// allocated in the heap. The data is owned by the JavaScript engine and the
/// lifetime is managed by the JavaScript garbage collector.
///
/// Shared references in Rust disallow mutation by default, and `JsBox` is no
/// exception: you cannot generally obtain a mutable reference to something
/// inside a `JsBox`. If you need to mutate through a `JsBox`, use
/// [`Cell`](https://doc.rust-lang.org/std/cell/struct.Cell.html),
/// [`RefCell`](https://doc.rust-lang.org/stable/std/cell/struct.RefCell.html),
/// or one of the other types that provide
/// [interior mutability](https://doc.rust-lang.org/book/ch15-05-interior-mutability.html).
///
/// Values contained by a `JsBox` must implement the `Finalize` trait. `Finalize::finalize`
/// will execute with the value in a `JsBox` immediately before the `JsBox` is garbage
/// collected. If no additional finalization is necessary, an emply implementation may
/// be provided.
///
///
/// ## `Deref` behavior
///
/// `JsBox<T>` automatically dereferences to `T` (via the `Deref` trait), so
/// you can call `T`'s method on a value of type `JsBox<T>`.
///
/// ```rust
/// # use neon::prelude::*;
/// # fn my_neon_function(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let vec: Handle<JsBox<Vec<_>>> = cx.boxed(vec![1, 2, 3]);
///
/// println!("Length: {}", vec.len());
/// # Ok(cx.undefined())
/// # }
/// ```
///
/// ## Examples
///
/// Passing some immutable data between Rust and JavaScript.
///
/// ```rust
/// # use neon::prelude::*;
/// # use std::path::{Path, PathBuf};
/// fn create_path(mut cx: FunctionContext) -> JsResult<JsBox<PathBuf>> {
/// let path = cx.argument::<JsString>(0)?.value(&mut cx);
/// let path = Path::new(&path).to_path_buf();
///
/// Ok(cx.boxed(path))
/// }
///
/// fn print_path(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let path = cx.argument::<JsBox<PathBuf>>(0)?;
///
/// println!("{}", path.display());
///
/// Ok(cx.undefined())
/// }
/// ```
///
/// Passing a user defined struct wrapped in a `RefCell` for mutability. This
/// pattern is useful for creating classes in JavaScript.
///
/// ```rust
/// # use neon::prelude::*;
/// # use std::cell::RefCell;
///
/// type BoxedPerson = JsBox<RefCell<Person>>;
///
/// struct Person {
/// name: String,
/// }
///
/// impl Finalize for Person {}
///
/// impl Person {
/// pub fn new(name: String) -> Self {
/// Person { name }
/// }
///
/// pub fn set_name(&mut self, name: String) {
/// self.name = name;
/// }
///
/// pub fn greet(&self) -> String {
/// format!("Hello, {}!", self.name)
/// }
/// }
///
/// fn person_new(mut cx: FunctionContext) -> JsResult<BoxedPerson> {
/// let name = cx.argument::<JsString>(0)?.value(&mut cx);
/// let person = RefCell::new(Person::new(name));
///
/// Ok(cx.boxed(person))
/// }
///
/// fn person_set_name(mut cx: FunctionContext) -> JsResult<JsUndefined> {
/// let person = cx.argument::<BoxedPerson>(0)?;
/// let mut person = person.borrow_mut();
/// let name = cx.argument::<JsString>(1)?.value(&mut cx);
///
/// person.set_name(name);
///
/// Ok(cx.undefined())
/// }
///
/// fn person_greet(mut cx: FunctionContext) -> JsResult<JsString> {
/// let person = cx.argument::<BoxedPerson>(0)?;
/// let person = person.borrow();
/// let greeting = person.greet();
///
/// Ok(cx.string(greeting))
/// }
pub struct JsBox<T: Send +'static> {
local: raw::Local,
// Cached raw pointer to the data contained in the `JsBox`. This value is
// required to implement `Deref` for `JsBox`. Unlike most `Js` types, `JsBox`
// is not a transparent wrapper around a `napi_value` and cannot implement `This`.
//
// Safety: `JsBox` cannot verify the lifetime. Store a raw pointer to force
// uses to be marked unsafe. In practice, it can be treated as `'static` but
// should only be exposed as part of a `Handle` tied to a `Context` lifetime.
// Safety: The value must not move on the heap; we must never give a mutable
// reference to the data until the `JsBox` is no longer accessible.
raw_data: *const T,
}
// Attempt to use a `napi_value` as a `napi_external` to unwrap a `BoxAny>
/// Safety: `local` must be a `napi_value` that is valid for the lifetime `'a`.
unsafe fn maybe_external_deref<'a>(env: Env, local: raw::Local) -> Option<&'a BoxAny> {
external::deref::<BoxAny>(env.to_raw(), local)
.map(|v| &*v)
}
// Custom `Clone` implementation since `T` might not be `Clone`
impl<T: Send +'static> Clone for JsBox<T> {
fn clone(&self) -> Self {
JsBox {
local: self.local,
raw_data: self.raw_data,
}
}
}
impl<T: Send +'static> Copy for JsBox<T> {}
impl<T: Send +'static> Value for JsBox<T> { }
impl<T: Send +'static> Managed for JsBox<T> {
fn to_raw(self) -> raw::Local {
self.local
}
fn from_raw(env: Env, local: raw::Local) -> Self {
let raw_data = unsafe { maybe_external_deref(env, local) }
.expect("Failed to unwrap napi_external as Box<Any>")
.downcast_ref()
.expect("Failed to downcast Any");
Self {
local,
raw_data,
}
}
}
impl<T: Send +'static> ValueInternal for JsBox<T> {
fn name() -> String {
any::type_name::<Self>().to_string()
}
fn is_typeof<Other: Value>(env: Env, other: Other) -> bool {
let data = unsafe { maybe_external_deref(env, other.to_raw()) };
data.map(|v| v.is::<T>()).unwrap_or(false)
}
fn downcast<Other: Value>(env: Env, other: Other) -> Option<Self> {
let local = other.to_raw();
let data = unsafe { maybe_external_deref(env, local) };
// Attempt to downcast the `Option<&BoxAny>` to `Option<*const T>`
data.and_then(|v| v.downcast_ref())
.map(|raw_data| Self {
local,
raw_data,
})
}
}
/// Values contained by a `JsBox` must be `Finalize + Send +'static`
///
/// ### `Finalize`
///
/// The `neon::prelude::Finalize` trait provides a `finalize` method that will be called
/// immediately before the `JsBox` is garbage collected.
///
/// ### `Send`
///
/// `JsBox` may be moved across threads. It is important to guarantee that the
/// contents is also safe to move across threads.
///
/// ### `'static'
///
/// The lifetime of a `JsBox` is managed by the JavaScript garbage collector. Since Rust
/// is unable to verify the lifetime of the contents, references must be valid for the
/// entire duration of the program. This does not mean that the `JsBox` will be valid
/// until the application terminates, only that its lifetime is indefinite.
impl<T: Finalize + Send +'static> JsBox<T> {
/// Constructs a new `JsBox` containing `value`.
pub fn new<'a, C>(cx: &mut C, value: T) -> Handle<'a, JsBox<T>>
where
C: Context<'a>,
T: Send +'static,
{
// This function will execute immediately before the `JsBox` is garbage collected.
// It unwraps the `napi_external`, downcasts the `BoxAny` and moves the type
// out of the `Box`. Lastly, it calls the trait method `Finalize::fianlize` of the
// contained value `T`.
fn finalizer<U: Finalize +'static>(env: raw::Env, data: BoxAny) {
let data = *data.downcast::<U>().unwrap();
let env = unsafe { std::mem::transmute(env) };
FinalizeContext::with(
env,
move |mut cx| data.finalize(&mut cx),
);
}
let v = Box::new(value) as BoxAny;
// Since this value was just constructed, we know it is `T`
let raw_data = &*v as *const dyn Any as *const T;
let local = unsafe {
external::create(cx.env().to_raw(), v, finalizer::<T>)
};
Handle::new_internal(Self {
local,
raw_data,
})
}
}
impl<'a, T: Send +'static> Deref for JsBox<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
// Safety: This depends on a `Handle<'a, JsBox<T>>` wrapper to provide
// a proper lifetime.
unsafe { &*self.raw_data }
}
}
/// Finalize is executed on the main JavaScript thread and executed immediately
/// before garbage collection.
/// Values contained by a `JsBox` must implement `Finalize`.
///
/// ## Examples
///
/// `Finalize` provides a default implementation that does not perform any finalization.
///
/// ```rust
/// # use neon::prelude::*;
/// struct Point(f64, f64);
///
/// impl Finalize for Point {}
/// ```
///
/// A `finalize` method may be specified for performing clean-up operations before dropping
/// the contained value.
///
/// ```rust
/// # use neon::prelude::*;
/// struct Point(f64, f64);
///
/// impl Finalize for Point {
/// fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
/// let global = cx.global();
/// let emit = global
/// .get(cx, "emit")
/// .unwrap()
/// .downcast::<JsFunction, _>(cx)
/// .unwrap();
///
/// let args = vec![
/// cx.string("gc_point").upcast::<JsValue>(),
/// cx.number(self.0).upcast(),
/// cx.number(self.1).upcast(),
/// ];
///
/// emit.call(cx, global, args).unwrap();
/// }
/// }
/// ```
pub trait Finalize: Sized {
fn finalize<'a, C: Context<'a>>(self, _: &mut C) {}
}
// Primitives
impl Finalize for bool {}
impl Finalize for char {}
impl Finalize for i8 {}
impl Finalize for i16 {}
impl Finalize for i32 {}
impl Finalize for i64 {}
impl Finalize for isize {}
impl Finalize for u8 {}
impl Finalize for u16 {}
impl Finalize for u32 {}
impl Finalize for u64 {}
impl Finalize for usize {}
impl Finalize for f32 {}
impl Finalize for f64 {}
// Common types
impl Finalize for String {}
impl Finalize for std::path::PathBuf {}
// Tuples
macro_rules! finalize_tuple_impls {
($( $name:ident )+) => {
impl<$($name: Finalize),+> Finalize for ($($name,)+) {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
#![allow(non_snake_case)]
let ($($name,)+) = self;
($($name.finalize(cx),)+);
}
}
};
}
impl Finalize for () {}
finalize_tuple_impls! { T0 }
finalize_tuple_impls! { T0 T1 }
finalize_tuple_impls! { T0 T1 T2 }
finalize_tuple_impls! { T0 T1 T2 T3 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 }
finalize_tuple_impls! { T0 T1 T2 T3 T4 T5 T6 T7 }
// Collections
impl<T: Finalize> Finalize for Vec<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
for item in self {
item.finalize(cx);
}
}
}
// Smart Pointers
impl<T: Finalize> Finalize for std::boxed::Box<T> {
fn
|
<'a, C: Context<'a>>(self, cx: &mut C) {
(*self).finalize(cx);
}
}
impl<T: Finalize> Finalize for std::rc::Rc<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = std::rc::Rc::try_unwrap(self) {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::Arc<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = std::sync::Arc::try_unwrap(self) {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::Mutex<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = self.into_inner() {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::sync::RwLock<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
if let Ok(v) = self.into_inner() {
v.finalize(cx);
}
}
}
impl<T: Finalize> Finalize for std::cell::Cell<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
self.into_inner().finalize(cx);
}
}
impl<T: Finalize> Finalize for std::cell::RefCell<T> {
fn finalize<'a, C: Context<'a>>(self, cx: &mut C) {
self.into_inner().finalize(cx);
}
}
|
finalize
|
identifier_name
|
assignability-trait.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.
// Tests that type assignability is used to search for instances when
// making method calls, but only if there aren't any matches without
// it.
trait iterable<A> {
fn iterate(&self, blk: &fn(x: &A) -> bool) -> bool;
}
impl<'self,A> iterable<A> for &'self [A] {
fn iterate(&self, f: &fn(x: &A) -> bool) -> bool {
self.iter().advance(f)
}
}
impl<A> iterable<A> for ~[A] {
fn iterate(&self, f: &fn(x: &A) -> bool) -> bool {
self.iter().advance(f)
}
}
fn length<A, T: iterable<A>>(x: T) -> uint
|
pub fn main() {
let x = ~[0,1,2,3];
// Call a method
do x.iterate() |y| { assert!(x[*y] == *y); true };
// Call a parameterized function
assert_eq!(length(x.clone()), x.len());
// Call a parameterized function, with type arguments that require
// a borrow
assert_eq!(length::<int, &[int]>(x), x.len());
// Now try it with a type that *needs* to be borrowed
let z = [0,1,2,3];
// Call a method
do z.iterate() |y| { assert!(z[*y] == *y); true };
// Call a parameterized function
assert_eq!(length::<int, &[int]>(z), z.len());
}
|
{
let mut len = 0;
do x.iterate() |_y| { len += 1; true };
return len;
}
|
identifier_body
|
assignability-trait.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.
// Tests that type assignability is used to search for instances when
// making method calls, but only if there aren't any matches without
// it.
trait iterable<A> {
fn iterate(&self, blk: &fn(x: &A) -> bool) -> bool;
}
impl<'self,A> iterable<A> for &'self [A] {
fn iterate(&self, f: &fn(x: &A) -> bool) -> bool {
self.iter().advance(f)
}
}
impl<A> iterable<A> for ~[A] {
fn iterate(&self, f: &fn(x: &A) -> bool) -> bool {
self.iter().advance(f)
}
}
fn length<A, T: iterable<A>>(x: T) -> uint {
let mut len = 0;
do x.iterate() |_y| { len += 1; true };
return len;
}
pub fn main() {
let x = ~[0,1,2,3];
// Call a method
do x.iterate() |y| { assert!(x[*y] == *y); true };
// Call a parameterized function
assert_eq!(length(x.clone()), x.len());
// Call a parameterized function, with type arguments that require
// a borrow
assert_eq!(length::<int, &[int]>(x), x.len());
// Now try it with a type that *needs* to be borrowed
let z = [0,1,2,3];
// Call a method
do z.iterate() |y| { assert!(z[*y] == *y); true };
// Call a parameterized function
|
assert_eq!(length::<int, &[int]>(z), z.len());
}
|
random_line_split
|
|
assignability-trait.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.
// Tests that type assignability is used to search for instances when
// making method calls, but only if there aren't any matches without
// it.
trait iterable<A> {
fn iterate(&self, blk: &fn(x: &A) -> bool) -> bool;
}
impl<'self,A> iterable<A> for &'self [A] {
fn iterate(&self, f: &fn(x: &A) -> bool) -> bool {
self.iter().advance(f)
}
}
impl<A> iterable<A> for ~[A] {
fn
|
(&self, f: &fn(x: &A) -> bool) -> bool {
self.iter().advance(f)
}
}
fn length<A, T: iterable<A>>(x: T) -> uint {
let mut len = 0;
do x.iterate() |_y| { len += 1; true };
return len;
}
pub fn main() {
let x = ~[0,1,2,3];
// Call a method
do x.iterate() |y| { assert!(x[*y] == *y); true };
// Call a parameterized function
assert_eq!(length(x.clone()), x.len());
// Call a parameterized function, with type arguments that require
// a borrow
assert_eq!(length::<int, &[int]>(x), x.len());
// Now try it with a type that *needs* to be borrowed
let z = [0,1,2,3];
// Call a method
do z.iterate() |y| { assert!(z[*y] == *y); true };
// Call a parameterized function
assert_eq!(length::<int, &[int]>(z), z.len());
}
|
iterate
|
identifier_name
|
console.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::ConsoleBinding;
use dom::bindings::codegen::Bindings::ConsoleBinding::ConsoleMethods;
use dom::bindings::global::{GlobalRef, GlobalField};
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::window::WindowHelpers;
use devtools_traits::{DevtoolsControlMsg, ConsoleMessage};
use util::str::DOMString;
#[dom_struct]
pub struct Console {
reflector_: Reflector,
global: GlobalField,
}
impl Console {
fn new_inherited(global: GlobalRef) -> Console {
Console {
reflector_: Reflector::new(),
global: GlobalField::from_rooted(&global),
}
}
pub fn new(global: GlobalRef) -> Temporary<Console> {
reflect_dom_object(box Console::new_inherited(global), global, ConsoleBinding::Wrap)
}
}
impl<'a> ConsoleMethods for JSRef<'a, Console> {
fn Log(self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
//TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later
propagate_console_msg(&self, ConsoleMessage::LogMessage(message, String::from_str("test"), 1, 1));
}
}
fn Debug(self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
}
}
fn
|
(self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
}
}
fn Warn(self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
}
}
fn Error(self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
}
}
fn Assert(self, condition: bool, message: Option<DOMString>) {
if!condition {
let message = match message {
Some(ref message) => message.as_slice(),
None => "no message",
};
println!("Assertion failed: {}", message);
}
}
}
fn propagate_console_msg(console: &JSRef<Console>, console_message: ConsoleMessage) {
let global = console.global.root();
match global.r() {
GlobalRef::Window(window_ref) => {
let pipelineId = window_ref.pipeline();
console.global.root().r().as_window().devtools_chan().as_ref().map(|chan| {
chan.send(DevtoolsControlMsg::SendConsoleMessage(
pipelineId, console_message.clone())).unwrap();
});
},
GlobalRef::Worker(_) => {
// TODO: support worker console logs
}
}
}
|
Info
|
identifier_name
|
console.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::ConsoleBinding;
use dom::bindings::codegen::Bindings::ConsoleBinding::ConsoleMethods;
use dom::bindings::global::{GlobalRef, GlobalField};
use dom::bindings::js::{JSRef, Temporary};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::window::WindowHelpers;
use devtools_traits::{DevtoolsControlMsg, ConsoleMessage};
use util::str::DOMString;
#[dom_struct]
pub struct Console {
reflector_: Reflector,
global: GlobalField,
}
impl Console {
fn new_inherited(global: GlobalRef) -> Console {
Console {
reflector_: Reflector::new(),
global: GlobalField::from_rooted(&global),
}
}
pub fn new(global: GlobalRef) -> Temporary<Console> {
reflect_dom_object(box Console::new_inherited(global), global, ConsoleBinding::Wrap)
}
}
impl<'a> ConsoleMethods for JSRef<'a, Console> {
fn Log(self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
//TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later
propagate_console_msg(&self, ConsoleMessage::LogMessage(message, String::from_str("test"), 1, 1));
}
}
fn Debug(self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
}
}
fn Info(self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
}
|
fn Warn(self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
}
}
fn Error(self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
}
}
fn Assert(self, condition: bool, message: Option<DOMString>) {
if!condition {
let message = match message {
Some(ref message) => message.as_slice(),
None => "no message",
};
println!("Assertion failed: {}", message);
}
}
}
fn propagate_console_msg(console: &JSRef<Console>, console_message: ConsoleMessage) {
let global = console.global.root();
match global.r() {
GlobalRef::Window(window_ref) => {
let pipelineId = window_ref.pipeline();
console.global.root().r().as_window().devtools_chan().as_ref().map(|chan| {
chan.send(DevtoolsControlMsg::SendConsoleMessage(
pipelineId, console_message.clone())).unwrap();
});
},
GlobalRef::Worker(_) => {
// TODO: support worker console logs
}
}
}
|
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.