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 |
---|---|---|---|---|
mod.rs
|
//! Utilities for handling shell surfaces with the `wl_shell` protocol
//!
//! This module provides automatic handling of shell surfaces objects, by being registered
//! as a global handler for `wl_shell`. This protocol is deprecated in favor of `xdg_shell`,
//! thus this module is provided as a compatibility layer with older clients. As a consequence,
//! you can as a compositor-writer decide to only support its functionality in a best-effort
//! manner: as this global is part of the core protocol, you are still required to provide
//! some support for it.
//!
//! ## Why use this implementation
//!
//! This implementation can track for you the various shell surfaces defined by the
//! clients by handling the `wl_shell` protocol.
//!
//! It allows you to easily access a list of all shell surfaces defined by your clients
//! access their associated metadata and underlying `wl_surface`s.
//!
//! This handler only handles the protocol exchanges with the client to present you the
//! information in a coherent and relatively easy to use manner. All the actual drawing
//! and positioning logic of windows is out of its scope.
//!
//! ## How to use it
//!
//! ### Initialization
//!
//! To initialize this handler, simple use the [`wl_shell_init`] function provided in this module.
//! You need to provide a closure that will be invoked whenever some action is required from you,
//! are represented by the [`ShellRequest`] enum.
//!
//! ```no_run
//! # extern crate wayland_server;
//! #
//! use smithay::wayland::shell::legacy::{wl_shell_init, ShellRequest};
//!
//! # let mut display = wayland_server::Display::new();
//! let (shell_state, _) = wl_shell_init(
//! &mut display,
//! // your implementation
//! |event: ShellRequest, dispatch_data| { /* handle the shell requests here */ },
//! None // put a logger if you want
//! );
//!
//! // You're now ready to go!
//! ```
use std::{
cell::RefCell,
rc::Rc,
sync::{Arc, Mutex},
};
use crate::{
utils::{Logical, Point, Size},
wayland::{compositor, Serial},
};
use wayland_server::{
protocol::{wl_output, wl_seat, wl_shell, wl_shell_surface, wl_surface},
DispatchData, Display, Filter, Global,
};
use super::PingError;
/// The role of a wl_shell_surface.
pub const WL_SHELL_SURFACE_ROLE: &str = "wl_shell_surface";
mod wl_handlers;
/// Metadata associated with the `wl_surface` role
#[derive(Debug)]
pub struct ShellSurfaceAttributes {
/// Title of the surface
pub title: String,
/// Class of the surface
pub class: String,
pending_ping: Option<Serial>,
}
/// A handle to a shell surface
#[derive(Debug, Clone)]
pub struct ShellSurface {
wl_surface: wl_surface::WlSurface,
shell_surface: wl_shell_surface::WlShellSurface,
}
impl std::cmp::PartialEq for ShellSurface {
fn eq(&self, other: &Self) -> bool {
self.shell_surface == other.shell_surface
}
}
impl ShellSurface {
/// Is the shell surface referred by this handle still alive?
pub fn alive(&self) -> bool {
self.shell_surface.as_ref().is_alive() && self.wl_surface.as_ref().is_alive()
}
/// Access the underlying `wl_surface` of this toplevel surface
///
/// Returns `None` if the toplevel surface actually no longer exists.
pub fn get_surface(&self) -> Option<&wl_surface::WlSurface> {
if self.alive() {
Some(&self.wl_surface)
} else {
None
}
}
/// Send a ping request to this shell surface
///
/// You'll receive the reply as a [`ShellRequest::Pong`] request
///
/// A typical use is to start a timer at the same time you send this ping
/// request, and cancel it when you receive the pong. If the timer runs
/// down to 0 before a pong is received, mark the client as unresponsive.
///
/// Fails if this shell client already has a pending ping or is already dead.
pub fn send_ping(&self, serial: Serial) -> Result<(), PingError> {
if!self.alive()
|
compositor::with_states(&self.wl_surface, |states| {
let mut data = states
.data_map
.get::<Mutex<ShellSurfaceAttributes>>()
.unwrap()
.lock()
.unwrap();
if let Some(pending_ping) = data.pending_ping {
return Err(PingError::PingAlreadyPending(pending_ping));
}
data.pending_ping = Some(serial);
Ok(())
})
.unwrap()?;
self.shell_surface.ping(serial.into());
Ok(())
}
/// Send a configure event to this toplevel surface to suggest it a new configuration
pub fn send_configure(&self, size: Size<i32, Logical>, edges: wl_shell_surface::Resize) {
self.shell_surface.configure(edges, size.w, size.h)
}
/// Signal a popup surface that it has lost focus
pub fn send_popup_done(&self) {
self.shell_surface.popup_done()
}
}
/// Possible kinds of shell surface of the `wl_shell` protocol
#[derive(Debug)]
pub enum ShellSurfaceKind {
/// Toplevel, a regular window displayed somewhere in the compositor space
Toplevel,
/// Transient, this surface has a parent surface
///
/// These are sub-windows of an application (for example a configuration window),
/// and as such should only be visible in their parent window is, and on top of it.
Transient {
/// The surface considered as parent
parent: wl_surface::WlSurface,
/// Location relative to the parent
location: Point<i32, Logical>,
/// Weather this window should be marked as inactive
inactive: bool,
},
/// Fullscreen surface, covering an entire output
Fullscreen {
/// Method used for fullscreen
method: wl_shell_surface::FullscreenMethod,
/// Framerate (relevant only for driver fullscreen)
framerate: u32,
/// Requested output if any
output: Option<wl_output::WlOutput>,
},
/// A popup surface
///
/// Short-lived surface, typically referred as "tooltips" in many
/// contexts.
Popup {
/// The parent surface of this popup
parent: wl_surface::WlSurface,
/// The serial of the input event triggering the creation of this
/// popup
serial: Serial,
/// Weather this popup should be marked as inactive
inactive: bool,
/// Location of the popup relative to its parent
location: Point<i32, Logical>,
/// Seat associated this the input that triggered the creation of the
/// popup. Used to define when the "popup done" event is sent.
seat: wl_seat::WlSeat,
},
/// A maximized surface
///
/// Like a toplevel surface, but as big as possible on a single output
/// while keeping any relevant desktop-environment interface visible.
Maximized {
/// Requested output for maximization
output: Option<wl_output::WlOutput>,
},
}
/// A request triggered by a `wl_shell_surface`
#[derive(Debug)]
pub enum ShellRequest {
/// A new shell surface was created
///
/// by default it has no kind and this should not be displayed
NewShellSurface {
/// The created surface
surface: ShellSurface,
},
/// A pong event
///
/// The surface responded to its pending ping. If you receive this
/// event, smithay has already checked that the responded serial was valid.
Pong {
/// The surface that sent the pong
surface: ShellSurface,
},
/// Start of an interactive move
///
/// The surface requests that an interactive move is started on it
Move {
/// The surface requesting the move
surface: ShellSurface,
/// Serial of the implicit grab that initiated the move
serial: Serial,
/// Seat associated with the move
seat: wl_seat::WlSeat,
},
/// Start of an interactive resize
///
/// The surface requests that an interactive resize is started on it
Resize {
/// The surface requesting the resize
surface: ShellSurface,
/// Serial of the implicit grab that initiated the resize
serial: Serial,
/// Seat associated with the resize
seat: wl_seat::WlSeat,
/// Direction of the resize
edges: wl_shell_surface::Resize,
},
/// The surface changed its kind
SetKind {
/// The surface
surface: ShellSurface,
/// Its new kind
kind: ShellSurfaceKind,
},
}
/// Shell global state
///
/// This state allows you to retrieve a list of surfaces
/// currently known to the shell global.
#[derive(Debug)]
pub struct ShellState {
known_surfaces: Vec<ShellSurface>,
}
impl ShellState {
/// Cleans the internal surface storage by removing all dead surfaces
pub(crate) fn cleanup_surfaces(&mut self) {
self.known_surfaces.retain(|s| s.alive());
}
/// Access all the shell surfaces known by this handler
pub fn surfaces(&self) -> &[ShellSurface] {
&self.known_surfaces[..]
}
}
/// Create a new `wl_shell` global
pub fn wl_shell_init<L, Impl>(
display: &mut Display,
implementation: Impl,
logger: L,
) -> (Arc<Mutex<ShellState>>, Global<wl_shell::WlShell>)
where
L: Into<Option<::slog::Logger>>,
Impl: FnMut(ShellRequest, DispatchData<'_>) +'static,
{
let _log = crate::slog_or_fallback(logger);
let implementation = Rc::new(RefCell::new(implementation));
let state = Arc::new(Mutex::new(ShellState {
known_surfaces: Vec::new(),
}));
let state2 = state.clone();
let global = display.create_global(
1,
Filter::new(move |(shell, _version), _, _data| {
self::wl_handlers::implement_shell(shell, implementation.clone(), state2.clone());
}),
);
(state, global)
}
|
{
return Err(PingError::DeadSurface);
}
|
conditional_block
|
mod.rs
|
//! Utilities for handling shell surfaces with the `wl_shell` protocol
//!
//! This module provides automatic handling of shell surfaces objects, by being registered
//! as a global handler for `wl_shell`. This protocol is deprecated in favor of `xdg_shell`,
//! thus this module is provided as a compatibility layer with older clients. As a consequence,
//! you can as a compositor-writer decide to only support its functionality in a best-effort
//! manner: as this global is part of the core protocol, you are still required to provide
//! some support for it.
//!
//! ## Why use this implementation
//!
//! This implementation can track for you the various shell surfaces defined by the
//! clients by handling the `wl_shell` protocol.
//!
//! It allows you to easily access a list of all shell surfaces defined by your clients
//! access their associated metadata and underlying `wl_surface`s.
//!
//! This handler only handles the protocol exchanges with the client to present you the
//! information in a coherent and relatively easy to use manner. All the actual drawing
//! and positioning logic of windows is out of its scope.
//!
//! ## How to use it
//!
//! ### Initialization
//!
//! To initialize this handler, simple use the [`wl_shell_init`] function provided in this module.
//! You need to provide a closure that will be invoked whenever some action is required from you,
//! are represented by the [`ShellRequest`] enum.
//!
//! ```no_run
//! # extern crate wayland_server;
//! #
//! use smithay::wayland::shell::legacy::{wl_shell_init, ShellRequest};
//!
//! # let mut display = wayland_server::Display::new();
//! let (shell_state, _) = wl_shell_init(
//! &mut display,
//! // your implementation
//! |event: ShellRequest, dispatch_data| { /* handle the shell requests here */ },
//! None // put a logger if you want
//! );
//!
//! // You're now ready to go!
//! ```
use std::{
cell::RefCell,
rc::Rc,
sync::{Arc, Mutex},
};
use crate::{
utils::{Logical, Point, Size},
wayland::{compositor, Serial},
};
use wayland_server::{
protocol::{wl_output, wl_seat, wl_shell, wl_shell_surface, wl_surface},
DispatchData, Display, Filter, Global,
};
use super::PingError;
/// The role of a wl_shell_surface.
pub const WL_SHELL_SURFACE_ROLE: &str = "wl_shell_surface";
mod wl_handlers;
/// Metadata associated with the `wl_surface` role
#[derive(Debug)]
pub struct ShellSurfaceAttributes {
/// Title of the surface
pub title: String,
/// Class of the surface
pub class: String,
pending_ping: Option<Serial>,
}
/// A handle to a shell surface
#[derive(Debug, Clone)]
pub struct
|
{
wl_surface: wl_surface::WlSurface,
shell_surface: wl_shell_surface::WlShellSurface,
}
impl std::cmp::PartialEq for ShellSurface {
fn eq(&self, other: &Self) -> bool {
self.shell_surface == other.shell_surface
}
}
impl ShellSurface {
/// Is the shell surface referred by this handle still alive?
pub fn alive(&self) -> bool {
self.shell_surface.as_ref().is_alive() && self.wl_surface.as_ref().is_alive()
}
/// Access the underlying `wl_surface` of this toplevel surface
///
/// Returns `None` if the toplevel surface actually no longer exists.
pub fn get_surface(&self) -> Option<&wl_surface::WlSurface> {
if self.alive() {
Some(&self.wl_surface)
} else {
None
}
}
/// Send a ping request to this shell surface
///
/// You'll receive the reply as a [`ShellRequest::Pong`] request
///
/// A typical use is to start a timer at the same time you send this ping
/// request, and cancel it when you receive the pong. If the timer runs
/// down to 0 before a pong is received, mark the client as unresponsive.
///
/// Fails if this shell client already has a pending ping or is already dead.
pub fn send_ping(&self, serial: Serial) -> Result<(), PingError> {
if!self.alive() {
return Err(PingError::DeadSurface);
}
compositor::with_states(&self.wl_surface, |states| {
let mut data = states
.data_map
.get::<Mutex<ShellSurfaceAttributes>>()
.unwrap()
.lock()
.unwrap();
if let Some(pending_ping) = data.pending_ping {
return Err(PingError::PingAlreadyPending(pending_ping));
}
data.pending_ping = Some(serial);
Ok(())
})
.unwrap()?;
self.shell_surface.ping(serial.into());
Ok(())
}
/// Send a configure event to this toplevel surface to suggest it a new configuration
pub fn send_configure(&self, size: Size<i32, Logical>, edges: wl_shell_surface::Resize) {
self.shell_surface.configure(edges, size.w, size.h)
}
/// Signal a popup surface that it has lost focus
pub fn send_popup_done(&self) {
self.shell_surface.popup_done()
}
}
/// Possible kinds of shell surface of the `wl_shell` protocol
#[derive(Debug)]
pub enum ShellSurfaceKind {
/// Toplevel, a regular window displayed somewhere in the compositor space
Toplevel,
/// Transient, this surface has a parent surface
///
/// These are sub-windows of an application (for example a configuration window),
/// and as such should only be visible in their parent window is, and on top of it.
Transient {
/// The surface considered as parent
parent: wl_surface::WlSurface,
/// Location relative to the parent
location: Point<i32, Logical>,
/// Weather this window should be marked as inactive
inactive: bool,
},
/// Fullscreen surface, covering an entire output
Fullscreen {
/// Method used for fullscreen
method: wl_shell_surface::FullscreenMethod,
/// Framerate (relevant only for driver fullscreen)
framerate: u32,
/// Requested output if any
output: Option<wl_output::WlOutput>,
},
/// A popup surface
///
/// Short-lived surface, typically referred as "tooltips" in many
/// contexts.
Popup {
/// The parent surface of this popup
parent: wl_surface::WlSurface,
/// The serial of the input event triggering the creation of this
/// popup
serial: Serial,
/// Weather this popup should be marked as inactive
inactive: bool,
/// Location of the popup relative to its parent
location: Point<i32, Logical>,
/// Seat associated this the input that triggered the creation of the
/// popup. Used to define when the "popup done" event is sent.
seat: wl_seat::WlSeat,
},
/// A maximized surface
///
/// Like a toplevel surface, but as big as possible on a single output
/// while keeping any relevant desktop-environment interface visible.
Maximized {
/// Requested output for maximization
output: Option<wl_output::WlOutput>,
},
}
/// A request triggered by a `wl_shell_surface`
#[derive(Debug)]
pub enum ShellRequest {
/// A new shell surface was created
///
/// by default it has no kind and this should not be displayed
NewShellSurface {
/// The created surface
surface: ShellSurface,
},
/// A pong event
///
/// The surface responded to its pending ping. If you receive this
/// event, smithay has already checked that the responded serial was valid.
Pong {
/// The surface that sent the pong
surface: ShellSurface,
},
/// Start of an interactive move
///
/// The surface requests that an interactive move is started on it
Move {
/// The surface requesting the move
surface: ShellSurface,
/// Serial of the implicit grab that initiated the move
serial: Serial,
/// Seat associated with the move
seat: wl_seat::WlSeat,
},
/// Start of an interactive resize
///
/// The surface requests that an interactive resize is started on it
Resize {
/// The surface requesting the resize
surface: ShellSurface,
/// Serial of the implicit grab that initiated the resize
serial: Serial,
/// Seat associated with the resize
seat: wl_seat::WlSeat,
/// Direction of the resize
edges: wl_shell_surface::Resize,
},
/// The surface changed its kind
SetKind {
/// The surface
surface: ShellSurface,
/// Its new kind
kind: ShellSurfaceKind,
},
}
/// Shell global state
///
/// This state allows you to retrieve a list of surfaces
/// currently known to the shell global.
#[derive(Debug)]
pub struct ShellState {
known_surfaces: Vec<ShellSurface>,
}
impl ShellState {
/// Cleans the internal surface storage by removing all dead surfaces
pub(crate) fn cleanup_surfaces(&mut self) {
self.known_surfaces.retain(|s| s.alive());
}
/// Access all the shell surfaces known by this handler
pub fn surfaces(&self) -> &[ShellSurface] {
&self.known_surfaces[..]
}
}
/// Create a new `wl_shell` global
pub fn wl_shell_init<L, Impl>(
display: &mut Display,
implementation: Impl,
logger: L,
) -> (Arc<Mutex<ShellState>>, Global<wl_shell::WlShell>)
where
L: Into<Option<::slog::Logger>>,
Impl: FnMut(ShellRequest, DispatchData<'_>) +'static,
{
let _log = crate::slog_or_fallback(logger);
let implementation = Rc::new(RefCell::new(implementation));
let state = Arc::new(Mutex::new(ShellState {
known_surfaces: Vec::new(),
}));
let state2 = state.clone();
let global = display.create_global(
1,
Filter::new(move |(shell, _version), _, _data| {
self::wl_handlers::implement_shell(shell, implementation.clone(), state2.clone());
}),
);
(state, global)
}
|
ShellSurface
|
identifier_name
|
fulfill.rs
|
http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::infer::InferCtxt;
use middle::ty::{self, RegionEscape, Ty};
use std::collections::HashSet;
use std::default::Default;
use syntax::ast;
use util::common::ErrorReported;
use util::ppaux::Repr;
use util::nodemap::NodeMap;
use super::CodeAmbiguity;
use super::CodeProjectionError;
use super::CodeSelectionError;
use super::FulfillmentError;
use super::ObligationCause;
use super::PredicateObligation;
use super::project;
use super::select::SelectionContext;
use super::Unimplemented;
use super::util::predicate_for_builtin_bound;
/// The fulfillment context is used to drive trait resolution. It
/// consists of a list of obligations that must be (eventually)
/// satisfied. The job is to track which are satisfied, which yielded
/// errors, and which are still pending. At any point, users can call
/// `select_where_possible`, and the fulfilment context will try to do
/// selection, retaining only those obligations that remain
/// ambiguous. This may be helpful in pushing type inference
/// along. Once all type inference constraints have been generated, the
/// method `select_all_or_error` can be used to report any remaining
/// ambiguous cases as errors.
pub struct FulfillmentContext<'tcx> {
// a simple cache that aims to cache *exact duplicate obligations*
// and avoid adding them twice. This serves a different purpose
// than the `SelectionCache`: it avoids duplicate errors and
// permits recursive obligations, which are often generated from
// traits like `Send` et al.
duplicate_set: HashSet<ty::Predicate<'tcx>>,
// A list of all obligations that have been registered with this
// fulfillment context.
predicates: Vec<PredicateObligation<'tcx>>,
// Remembers the count of trait obligations that we have already
// attempted to select. This is used to avoid repeating work
// when `select_new_obligations` is called.
attempted_mark: usize,
// A set of constraints that regionck must validate. Each
// constraint has the form `T:'a`, meaning "some type `T` must
// outlive the lifetime 'a". These constraints derive from
// instantiated type parameters. So if you had a struct defined
// like
//
// struct Foo<T:'static> {... }
//
// then in some expression `let x = Foo {... }` it will
// instantiate the type parameter `T` with a fresh type `$0`. At
// the same time, it will record a region obligation of
// `$0:'static`. This will get checked later by regionck. (We
// can't generally check these things right away because we have
// to wait until types are resolved.)
//
// These are stored in a map keyed to the id of the innermost
// enclosing fn body / static initializer expression. This is
// because the location where the obligation was incurred can be
// relevant with respect to which sublifetime assumptions are in
// place. The reason that we store under the fn-id, and not
// something more fine-grained, is so that it is easier for
// regionck to be sure that it has found *all* the region
// obligations (otherwise, it's easy to fail to walk to a
// particular node-id).
region_obligations: NodeMap<Vec<RegionObligation<'tcx>>>,
}
#[derive(Clone)]
pub struct RegionObligation<'tcx> {
pub sub_region: ty::Region,
pub sup_type: Ty<'tcx>,
pub cause: ObligationCause<'tcx>,
}
impl<'tcx> FulfillmentContext<'tcx> {
pub fn new() -> FulfillmentContext<'tcx> {
FulfillmentContext {
duplicate_set: HashSet::new(),
predicates: Vec::new(),
attempted_mark: 0,
region_obligations: NodeMap(),
}
}
/// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
/// creating a fresh type variable `$0` as well as a projection
/// predicate `<SomeType as SomeTrait>::X == $0`. When the
/// inference engine runs, it will attempt to find an impl of
/// `SomeTrait` or a where clause that lets us unify `$0` with
/// something concrete. If this fails, we'll unify `$0` with
/// `projection_ty` again.
pub fn normalize_projection_type<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>,
projection_ty: ty::ProjectionTy<'tcx>,
cause: ObligationCause<'tcx>)
-> Ty<'tcx>
{
debug!("normalize_associated_type(projection_ty={})",
projection_ty.repr(infcx.tcx));
assert!(!projection_ty.has_escaping_regions());
// FIXME(#20304) -- cache
let mut selcx = SelectionContext::new(infcx, typer);
let normalized = project::normalize_projection_type(&mut selcx, projection_ty, cause, 0);
for obligation in normalized.obligations {
self.register_predicate_obligation(infcx, obligation);
}
debug!("normalize_associated_type: result={}", normalized.value.repr(infcx.tcx));
normalized.value
}
pub fn register_builtin_bound<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
ty: Ty<'tcx>,
builtin_bound: ty::BuiltinBound,
cause: ObligationCause<'tcx>)
{
match predicate_for_builtin_bound(infcx.tcx, cause, builtin_bound, 0, ty) {
Ok(predicate) => {
self.register_predicate_obligation(infcx, predicate);
}
Err(ErrorReported) => { }
}
}
pub fn register_region_obligation<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
t_a: Ty<'tcx>,
r_b: ty::Region,
cause: ObligationCause<'tcx>)
{
register_region_obligation(infcx.tcx, t_a, r_b, cause, &mut self.region_obligations);
}
pub fn register_predicate_obligation<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
obligation: PredicateObligation<'tcx>)
{
// this helps to reduce duplicate errors, as well as making
// debug output much nicer to read and so on.
let obligation = infcx.resolve_type_vars_if_possible(&obligation);
assert!(!obligation.has_escaping_regions());
if!self.duplicate_set.insert(obligation.predicate.clone()) {
debug!("register_predicate({}) -- already seen, skip", obligation.repr(infcx.tcx));
return;
}
debug!("register_predicate({})", obligation.repr(infcx.tcx));
self.predicates.push(obligation);
}
pub fn region_obligations(&self,
body_id: ast::NodeId)
-> &[RegionObligation<'tcx>]
{
match self.region_obligations.get(&body_id) {
None => Default::default(),
Some(vec) => vec,
}
}
pub fn select_all_or_error<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
try!(self.select_where_possible(infcx, typer));
// Anything left is ambiguous.
let errors: Vec<FulfillmentError> =
self.predicates
.iter()
.map(|o| FulfillmentError::new((*o).clone(), CodeAmbiguity))
.collect();
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
/// Attempts to select obligations that were registered since the call to a selection routine.
/// This is used by the type checker to eagerly attempt to resolve obligations in hopes of
/// gaining type information. It'd be equally valid to use `select_where_possible` but it
/// results in `O(n^2)` performance (#18208).
pub fn select_new_obligations<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
let mut selcx = SelectionContext::new(infcx, typer);
self.select(&mut selcx, true)
}
pub fn select_where_possible<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
let mut selcx = SelectionContext::new(infcx, typer);
self.select(&mut selcx, false)
}
pub fn pending_obligations(&self) -> &[PredicateObligation<'tcx>] {
&self.predicates
}
/// Attempts to select obligations using `selcx`. If `only_new_obligations` is true, then it
/// only attempts to select obligations that haven't been seen before.
fn select<'a>(&mut self,
selcx: &mut SelectionContext<'a, 'tcx>,
only_new_obligations: bool)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
debug!("select({} obligations, only_new_obligations={}) start",
self.predicates.len(),
only_new_obligations);
let mut errors = Vec::new();
loop {
let count = self.predicates.len();
debug!("select_where_possible({} obligations) iteration",
count);
let mut new_obligations = Vec::new();
// If we are only attempting obligations we haven't seen yet,
// then set `skip` to the number of obligations we've already
// seen.
let mut skip = if only_new_obligations {
self.attempted_mark
} else {
0
};
// First pass: walk each obligation, retaining
// only those that we cannot yet process.
{
let region_obligations = &mut self.region_obligations;
self.predicates.retain(|predicate| {
// Hack: Retain does not pass in the index, but we want
// to avoid processing the first `start_count` entries.
let processed =
if skip == 0 {
process_predicate(selcx, predicate,
&mut new_obligations, &mut errors, region_obligations)
} else {
skip -= 1;
false
};
!processed
});
}
self.attempted_mark = self.predicates.len();
if self.predicates.len() == count {
// Nothing changed.
break;
}
// Now go through all the successful ones,
// registering any nested obligations for the future.
for new_obligation in new_obligations {
self.register_predicate_obligation(selcx.infcx(), new_obligation);
}
}
debug!("select({} obligations, {} errors) done",
self.predicates.len(),
errors.len());
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
fn process_predicate<'a,'tcx>(selcx: &mut SelectionContext<'a,'tcx>,
obligation: &PredicateObligation<'tcx>,
new_obligations: &mut Vec<PredicateObligation<'tcx>>,
errors: &mut Vec<FulfillmentError<'tcx>>,
region_obligations: &mut NodeMap<Vec<RegionObligation<'tcx>>>)
-> bool
{
/*!
* Processes a predicate obligation and modifies the appropriate
* output array with the successful/error result. Returns `false`
* if the predicate could not be processed due to insufficient
* type inference.
*/
let tcx = selcx.tcx();
match obligation.predicate {
ty::Predicate::Trait(ref data) => {
let trait_obligation = obligation.with(data.clone());
match selcx.select(&trait_obligation) {
Ok(None) => {
false
}
Ok(Some(s)) => {
new_obligations.append(&mut s.nested_obligations());
true
}
Err(selection_err) => {
debug!("predicate: {} error: {}",
obligation.repr(tcx),
selection_err.repr(tcx));
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(selection_err)));
true
}
}
}
ty::Predicate::Equate(ref binder) => {
match selcx.infcx().equality_predicate(obligation.cause.span, binder) {
Ok(()) => { }
Err(_) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
}
}
true
}
ty::Predicate::RegionOutlives(ref binder) => {
match selcx.infcx().region_outlives_predicate(obligation.cause.span, binder) {
Ok(()) => { }
Err(_) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
}
}
true
}
ty::Predicate::TypeOutlives(ref binder) => {
// For now, we just check that there are no higher-ranked
// regions. If there are, we will call this obligation an
// error. Eventually we should be able to support some
// cases here, I imagine (e.g., `for<'a> int : 'a`).
if ty::count_late_bound_regions(selcx.tcx(), binder)!= 0 {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
} else {
let ty::OutlivesPredicate(t_a, r_b) = binder.0;
register_region_obligation(tcx, t_a, r_b,
obligation.cause.clone(),
region_obligations);
}
true
}
ty::Predicate::Projection(ref data) => {
let project_obligation = obligation.with(data.clone());
let result = project::poly_project_and_unify_type(selcx, &project_obligation);
debug!("process_predicate: poly_project_and_unify_type({}) returned {}",
project_obligation.repr(tcx),
result.repr(tcx));
match result {
Ok(Some(obligations)) => {
new_obligations.extend(obligations.into_iter());
true
}
Ok(None) => {
false
}
Err(err) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeProjectionError(err)));
true
}
}
}
}
}
impl<'tcx> Repr<'tcx> for RegionObligation<'tcx> {
fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
format!("RegionObligation(sub_region={}, sup_type={})",
self.sub_region.repr(tcx),
self.sup_type.repr(tcx))
}
}
fn
|
<'tcx>(tcx: &ty::ctxt<'tcx>,
t_a: Ty<'tcx>,
r_b: ty::Region,
cause: ObligationCause<'tcx>,
region_obligations: &mut NodeMap<Vec<RegionObligation<'tcx>>>)
{
let region_obligation = RegionObligation { sup_type: t_a,
sub_region: r_b,
cause: cause };
debug!("register_region_obligation({})",
|
register_region_obligation
|
identifier_name
|
fulfill.rs
|
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::infer::InferCtxt;
use middle::ty::{self, RegionEscape, Ty};
use std::collections::HashSet;
use std::default::Default;
use syntax::ast;
use util::common::ErrorReported;
use util::ppaux::Repr;
use util::nodemap::NodeMap;
use super::CodeAmbiguity;
use super::CodeProjectionError;
use super::CodeSelectionError;
use super::FulfillmentError;
use super::ObligationCause;
use super::PredicateObligation;
use super::project;
use super::select::SelectionContext;
use super::Unimplemented;
use super::util::predicate_for_builtin_bound;
/// The fulfillment context is used to drive trait resolution. It
/// consists of a list of obligations that must be (eventually)
/// satisfied. The job is to track which are satisfied, which yielded
/// errors, and which are still pending. At any point, users can call
/// `select_where_possible`, and the fulfilment context will try to do
/// selection, retaining only those obligations that remain
/// ambiguous. This may be helpful in pushing type inference
/// along. Once all type inference constraints have been generated, the
/// method `select_all_or_error` can be used to report any remaining
/// ambiguous cases as errors.
pub struct FulfillmentContext<'tcx> {
// a simple cache that aims to cache *exact duplicate obligations*
// and avoid adding them twice. This serves a different purpose
// than the `SelectionCache`: it avoids duplicate errors and
// permits recursive obligations, which are often generated from
// traits like `Send` et al.
duplicate_set: HashSet<ty::Predicate<'tcx>>,
// A list of all obligations that have been registered with this
// fulfillment context.
predicates: Vec<PredicateObligation<'tcx>>,
// Remembers the count of trait obligations that we have already
// attempted to select. This is used to avoid repeating work
// when `select_new_obligations` is called.
attempted_mark: usize,
// A set of constraints that regionck must validate. Each
// constraint has the form `T:'a`, meaning "some type `T` must
// outlive the lifetime 'a". These constraints derive from
// instantiated type parameters. So if you had a struct defined
// like
//
// struct Foo<T:'static> {... }
//
// then in some expression `let x = Foo {... }` it will
// instantiate the type parameter `T` with a fresh type `$0`. At
// the same time, it will record a region obligation of
// `$0:'static`. This will get checked later by regionck. (We
// can't generally check these things right away because we have
// to wait until types are resolved.)
//
// These are stored in a map keyed to the id of the innermost
// enclosing fn body / static initializer expression. This is
// because the location where the obligation was incurred can be
// relevant with respect to which sublifetime assumptions are in
// place. The reason that we store under the fn-id, and not
// something more fine-grained, is so that it is easier for
// regionck to be sure that it has found *all* the region
// obligations (otherwise, it's easy to fail to walk to a
// particular node-id).
region_obligations: NodeMap<Vec<RegionObligation<'tcx>>>,
}
#[derive(Clone)]
pub struct RegionObligation<'tcx> {
pub sub_region: ty::Region,
pub sup_type: Ty<'tcx>,
pub cause: ObligationCause<'tcx>,
}
impl<'tcx> FulfillmentContext<'tcx> {
pub fn new() -> FulfillmentContext<'tcx> {
FulfillmentContext {
duplicate_set: HashSet::new(),
predicates: Vec::new(),
attempted_mark: 0,
region_obligations: NodeMap(),
}
}
/// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
/// creating a fresh type variable `$0` as well as a projection
/// predicate `<SomeType as SomeTrait>::X == $0`. When the
/// inference engine runs, it will attempt to find an impl of
/// `SomeTrait` or a where clause that lets us unify `$0` with
/// something concrete. If this fails, we'll unify `$0` with
/// `projection_ty` again.
pub fn normalize_projection_type<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>,
projection_ty: ty::ProjectionTy<'tcx>,
cause: ObligationCause<'tcx>)
-> Ty<'tcx>
{
debug!("normalize_associated_type(projection_ty={})",
projection_ty.repr(infcx.tcx));
assert!(!projection_ty.has_escaping_regions());
// FIXME(#20304) -- cache
let mut selcx = SelectionContext::new(infcx, typer);
let normalized = project::normalize_projection_type(&mut selcx, projection_ty, cause, 0);
for obligation in normalized.obligations {
self.register_predicate_obligation(infcx, obligation);
}
debug!("normalize_associated_type: result={}", normalized.value.repr(infcx.tcx));
normalized.value
}
pub fn register_builtin_bound<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
ty: Ty<'tcx>,
builtin_bound: ty::BuiltinBound,
cause: ObligationCause<'tcx>)
{
match predicate_for_builtin_bound(infcx.tcx, cause, builtin_bound, 0, ty) {
Ok(predicate) => {
self.register_predicate_obligation(infcx, predicate);
}
Err(ErrorReported) => { }
}
}
pub fn register_region_obligation<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
t_a: Ty<'tcx>,
r_b: ty::Region,
cause: ObligationCause<'tcx>)
{
register_region_obligation(infcx.tcx, t_a, r_b, cause, &mut self.region_obligations);
}
pub fn register_predicate_obligation<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
obligation: PredicateObligation<'tcx>)
{
// this helps to reduce duplicate errors, as well as making
// debug output much nicer to read and so on.
let obligation = infcx.resolve_type_vars_if_possible(&obligation);
assert!(!obligation.has_escaping_regions());
if!self.duplicate_set.insert(obligation.predicate.clone()) {
debug!("register_predicate({}) -- already seen, skip", obligation.repr(infcx.tcx));
return;
}
debug!("register_predicate({})", obligation.repr(infcx.tcx));
self.predicates.push(obligation);
}
pub fn region_obligations(&self,
body_id: ast::NodeId)
-> &[RegionObligation<'tcx>]
{
match self.region_obligations.get(&body_id) {
None => Default::default(),
Some(vec) => vec,
}
}
pub fn select_all_or_error<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
try!(self.select_where_possible(infcx, typer));
// Anything left is ambiguous.
let errors: Vec<FulfillmentError> =
self.predicates
.iter()
.map(|o| FulfillmentError::new((*o).clone(), CodeAmbiguity))
.collect();
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
/// Attempts to select obligations that were registered since the call to a selection routine.
/// This is used by the type checker to eagerly attempt to resolve obligations in hopes of
/// gaining type information. It'd be equally valid to use `select_where_possible` but it
/// results in `O(n^2)` performance (#18208).
pub fn select_new_obligations<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
let mut selcx = SelectionContext::new(infcx, typer);
self.select(&mut selcx, true)
}
pub fn select_where_possible<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
let mut selcx = SelectionContext::new(infcx, typer);
self.select(&mut selcx, false)
}
pub fn pending_obligations(&self) -> &[PredicateObligation<'tcx>] {
&self.predicates
}
/// Attempts to select obligations using `selcx`. If `only_new_obligations` is true, then it
/// only attempts to select obligations that haven't been seen before.
fn select<'a>(&mut self,
selcx: &mut SelectionContext<'a, 'tcx>,
only_new_obligations: bool)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
debug!("select({} obligations, only_new_obligations={}) start",
self.predicates.len(),
only_new_obligations);
let mut errors = Vec::new();
loop {
let count = self.predicates.len();
debug!("select_where_possible({} obligations) iteration",
count);
let mut new_obligations = Vec::new();
// If we are only attempting obligations we haven't seen yet,
// then set `skip` to the number of obligations we've already
// seen.
let mut skip = if only_new_obligations {
self.attempted_mark
} else {
0
};
// First pass: walk each obligation, retaining
// only those that we cannot yet process.
{
let region_obligations = &mut self.region_obligations;
self.predicates.retain(|predicate| {
// Hack: Retain does not pass in the index, but we want
// to avoid processing the first `start_count` entries.
let processed =
if skip == 0 {
process_predicate(selcx, predicate,
&mut new_obligations, &mut errors, region_obligations)
} else {
skip -= 1;
false
};
!processed
});
}
|
if self.predicates.len() == count {
// Nothing changed.
break;
}
// Now go through all the successful ones,
// registering any nested obligations for the future.
for new_obligation in new_obligations {
self.register_predicate_obligation(selcx.infcx(), new_obligation);
}
}
debug!("select({} obligations, {} errors) done",
self.predicates.len(),
errors.len());
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
fn process_predicate<'a,'tcx>(selcx: &mut SelectionContext<'a,'tcx>,
obligation: &PredicateObligation<'tcx>,
new_obligations: &mut Vec<PredicateObligation<'tcx>>,
errors: &mut Vec<FulfillmentError<'tcx>>,
region_obligations: &mut NodeMap<Vec<RegionObligation<'tcx>>>)
-> bool
{
/*!
* Processes a predicate obligation and modifies the appropriate
* output array with the successful/error result. Returns `false`
* if the predicate could not be processed due to insufficient
* type inference.
*/
let tcx = selcx.tcx();
match obligation.predicate {
ty::Predicate::Trait(ref data) => {
let trait_obligation = obligation.with(data.clone());
match selcx.select(&trait_obligation) {
Ok(None) => {
false
}
Ok(Some(s)) => {
new_obligations.append(&mut s.nested_obligations());
true
}
Err(selection_err) => {
debug!("predicate: {} error: {}",
obligation.repr(tcx),
selection_err.repr(tcx));
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(selection_err)));
true
}
}
}
ty::Predicate::Equate(ref binder) => {
match selcx.infcx().equality_predicate(obligation.cause.span, binder) {
Ok(()) => { }
Err(_) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
}
}
true
}
ty::Predicate::RegionOutlives(ref binder) => {
match selcx.infcx().region_outlives_predicate(obligation.cause.span, binder) {
Ok(()) => { }
Err(_) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
}
}
true
}
ty::Predicate::TypeOutlives(ref binder) => {
// For now, we just check that there are no higher-ranked
// regions. If there are, we will call this obligation an
// error. Eventually we should be able to support some
// cases here, I imagine (e.g., `for<'a> int : 'a`).
if ty::count_late_bound_regions(selcx.tcx(), binder)!= 0 {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
} else {
let ty::OutlivesPredicate(t_a, r_b) = binder.0;
register_region_obligation(tcx, t_a, r_b,
obligation.cause.clone(),
region_obligations);
}
true
}
ty::Predicate::Projection(ref data) => {
let project_obligation = obligation.with(data.clone());
let result = project::poly_project_and_unify_type(selcx, &project_obligation);
debug!("process_predicate: poly_project_and_unify_type({}) returned {}",
project_obligation.repr(tcx),
result.repr(tcx));
match result {
Ok(Some(obligations)) => {
new_obligations.extend(obligations.into_iter());
true
}
Ok(None) => {
false
}
Err(err) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeProjectionError(err)));
true
}
}
}
}
}
impl<'tcx> Repr<'tcx> for RegionObligation<'tcx> {
fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
format!("RegionObligation(sub_region={}, sup_type={})",
self.sub_region.repr(tcx),
self.sup_type.repr(tcx))
}
}
fn register_region_obligation<'tcx>(tcx: &ty::ctxt<'tcx>,
t_a: Ty<'tcx>,
r_b: ty::Region,
cause: ObligationCause<'tcx>,
region_obligations: &mut NodeMap<Vec<RegionObligation<'tcx>>>)
{
let region_obligation = RegionObligation { sup_type: t_a,
sub_region: r_b,
cause: cause };
debug!("register_region_obligation({})",
|
self.attempted_mark = self.predicates.len();
|
random_line_split
|
fulfill.rs
|
http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::infer::InferCtxt;
use middle::ty::{self, RegionEscape, Ty};
use std::collections::HashSet;
use std::default::Default;
use syntax::ast;
use util::common::ErrorReported;
use util::ppaux::Repr;
use util::nodemap::NodeMap;
use super::CodeAmbiguity;
use super::CodeProjectionError;
use super::CodeSelectionError;
use super::FulfillmentError;
use super::ObligationCause;
use super::PredicateObligation;
use super::project;
use super::select::SelectionContext;
use super::Unimplemented;
use super::util::predicate_for_builtin_bound;
/// The fulfillment context is used to drive trait resolution. It
/// consists of a list of obligations that must be (eventually)
/// satisfied. The job is to track which are satisfied, which yielded
/// errors, and which are still pending. At any point, users can call
/// `select_where_possible`, and the fulfilment context will try to do
/// selection, retaining only those obligations that remain
/// ambiguous. This may be helpful in pushing type inference
/// along. Once all type inference constraints have been generated, the
/// method `select_all_or_error` can be used to report any remaining
/// ambiguous cases as errors.
pub struct FulfillmentContext<'tcx> {
// a simple cache that aims to cache *exact duplicate obligations*
// and avoid adding them twice. This serves a different purpose
// than the `SelectionCache`: it avoids duplicate errors and
// permits recursive obligations, which are often generated from
// traits like `Send` et al.
duplicate_set: HashSet<ty::Predicate<'tcx>>,
// A list of all obligations that have been registered with this
// fulfillment context.
predicates: Vec<PredicateObligation<'tcx>>,
// Remembers the count of trait obligations that we have already
// attempted to select. This is used to avoid repeating work
// when `select_new_obligations` is called.
attempted_mark: usize,
// A set of constraints that regionck must validate. Each
// constraint has the form `T:'a`, meaning "some type `T` must
// outlive the lifetime 'a". These constraints derive from
// instantiated type parameters. So if you had a struct defined
// like
//
// struct Foo<T:'static> {... }
//
// then in some expression `let x = Foo {... }` it will
// instantiate the type parameter `T` with a fresh type `$0`. At
// the same time, it will record a region obligation of
// `$0:'static`. This will get checked later by regionck. (We
// can't generally check these things right away because we have
// to wait until types are resolved.)
//
// These are stored in a map keyed to the id of the innermost
// enclosing fn body / static initializer expression. This is
// because the location where the obligation was incurred can be
// relevant with respect to which sublifetime assumptions are in
// place. The reason that we store under the fn-id, and not
// something more fine-grained, is so that it is easier for
// regionck to be sure that it has found *all* the region
// obligations (otherwise, it's easy to fail to walk to a
// particular node-id).
region_obligations: NodeMap<Vec<RegionObligation<'tcx>>>,
}
#[derive(Clone)]
pub struct RegionObligation<'tcx> {
pub sub_region: ty::Region,
pub sup_type: Ty<'tcx>,
pub cause: ObligationCause<'tcx>,
}
impl<'tcx> FulfillmentContext<'tcx> {
pub fn new() -> FulfillmentContext<'tcx> {
FulfillmentContext {
duplicate_set: HashSet::new(),
predicates: Vec::new(),
attempted_mark: 0,
region_obligations: NodeMap(),
}
}
/// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
/// creating a fresh type variable `$0` as well as a projection
/// predicate `<SomeType as SomeTrait>::X == $0`. When the
/// inference engine runs, it will attempt to find an impl of
/// `SomeTrait` or a where clause that lets us unify `$0` with
/// something concrete. If this fails, we'll unify `$0` with
/// `projection_ty` again.
pub fn normalize_projection_type<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>,
projection_ty: ty::ProjectionTy<'tcx>,
cause: ObligationCause<'tcx>)
-> Ty<'tcx>
|
pub fn register_builtin_bound<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
ty: Ty<'tcx>,
builtin_bound: ty::BuiltinBound,
cause: ObligationCause<'tcx>)
{
match predicate_for_builtin_bound(infcx.tcx, cause, builtin_bound, 0, ty) {
Ok(predicate) => {
self.register_predicate_obligation(infcx, predicate);
}
Err(ErrorReported) => { }
}
}
pub fn register_region_obligation<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
t_a: Ty<'tcx>,
r_b: ty::Region,
cause: ObligationCause<'tcx>)
{
register_region_obligation(infcx.tcx, t_a, r_b, cause, &mut self.region_obligations);
}
pub fn register_predicate_obligation<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
obligation: PredicateObligation<'tcx>)
{
// this helps to reduce duplicate errors, as well as making
// debug output much nicer to read and so on.
let obligation = infcx.resolve_type_vars_if_possible(&obligation);
assert!(!obligation.has_escaping_regions());
if!self.duplicate_set.insert(obligation.predicate.clone()) {
debug!("register_predicate({}) -- already seen, skip", obligation.repr(infcx.tcx));
return;
}
debug!("register_predicate({})", obligation.repr(infcx.tcx));
self.predicates.push(obligation);
}
pub fn region_obligations(&self,
body_id: ast::NodeId)
-> &[RegionObligation<'tcx>]
{
match self.region_obligations.get(&body_id) {
None => Default::default(),
Some(vec) => vec,
}
}
pub fn select_all_or_error<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
try!(self.select_where_possible(infcx, typer));
// Anything left is ambiguous.
let errors: Vec<FulfillmentError> =
self.predicates
.iter()
.map(|o| FulfillmentError::new((*o).clone(), CodeAmbiguity))
.collect();
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
/// Attempts to select obligations that were registered since the call to a selection routine.
/// This is used by the type checker to eagerly attempt to resolve obligations in hopes of
/// gaining type information. It'd be equally valid to use `select_where_possible` but it
/// results in `O(n^2)` performance (#18208).
pub fn select_new_obligations<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
let mut selcx = SelectionContext::new(infcx, typer);
self.select(&mut selcx, true)
}
pub fn select_where_possible<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
typer: &ty::ClosureTyper<'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
let mut selcx = SelectionContext::new(infcx, typer);
self.select(&mut selcx, false)
}
pub fn pending_obligations(&self) -> &[PredicateObligation<'tcx>] {
&self.predicates
}
/// Attempts to select obligations using `selcx`. If `only_new_obligations` is true, then it
/// only attempts to select obligations that haven't been seen before.
fn select<'a>(&mut self,
selcx: &mut SelectionContext<'a, 'tcx>,
only_new_obligations: bool)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
debug!("select({} obligations, only_new_obligations={}) start",
self.predicates.len(),
only_new_obligations);
let mut errors = Vec::new();
loop {
let count = self.predicates.len();
debug!("select_where_possible({} obligations) iteration",
count);
let mut new_obligations = Vec::new();
// If we are only attempting obligations we haven't seen yet,
// then set `skip` to the number of obligations we've already
// seen.
let mut skip = if only_new_obligations {
self.attempted_mark
} else {
0
};
// First pass: walk each obligation, retaining
// only those that we cannot yet process.
{
let region_obligations = &mut self.region_obligations;
self.predicates.retain(|predicate| {
// Hack: Retain does not pass in the index, but we want
// to avoid processing the first `start_count` entries.
let processed =
if skip == 0 {
process_predicate(selcx, predicate,
&mut new_obligations, &mut errors, region_obligations)
} else {
skip -= 1;
false
};
!processed
});
}
self.attempted_mark = self.predicates.len();
if self.predicates.len() == count {
// Nothing changed.
break;
}
// Now go through all the successful ones,
// registering any nested obligations for the future.
for new_obligation in new_obligations {
self.register_predicate_obligation(selcx.infcx(), new_obligation);
}
}
debug!("select({} obligations, {} errors) done",
self.predicates.len(),
errors.len());
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
fn process_predicate<'a,'tcx>(selcx: &mut SelectionContext<'a,'tcx>,
obligation: &PredicateObligation<'tcx>,
new_obligations: &mut Vec<PredicateObligation<'tcx>>,
errors: &mut Vec<FulfillmentError<'tcx>>,
region_obligations: &mut NodeMap<Vec<RegionObligation<'tcx>>>)
-> bool
{
/*!
* Processes a predicate obligation and modifies the appropriate
* output array with the successful/error result. Returns `false`
* if the predicate could not be processed due to insufficient
* type inference.
*/
let tcx = selcx.tcx();
match obligation.predicate {
ty::Predicate::Trait(ref data) => {
let trait_obligation = obligation.with(data.clone());
match selcx.select(&trait_obligation) {
Ok(None) => {
false
}
Ok(Some(s)) => {
new_obligations.append(&mut s.nested_obligations());
true
}
Err(selection_err) => {
debug!("predicate: {} error: {}",
obligation.repr(tcx),
selection_err.repr(tcx));
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(selection_err)));
true
}
}
}
ty::Predicate::Equate(ref binder) => {
match selcx.infcx().equality_predicate(obligation.cause.span, binder) {
Ok(()) => { }
Err(_) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
}
}
true
}
ty::Predicate::RegionOutlives(ref binder) => {
match selcx.infcx().region_outlives_predicate(obligation.cause.span, binder) {
Ok(()) => { }
Err(_) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
}
}
true
}
ty::Predicate::TypeOutlives(ref binder) => {
// For now, we just check that there are no higher-ranked
// regions. If there are, we will call this obligation an
// error. Eventually we should be able to support some
// cases here, I imagine (e.g., `for<'a> int : 'a`).
if ty::count_late_bound_regions(selcx.tcx(), binder)!= 0 {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
} else {
let ty::OutlivesPredicate(t_a, r_b) = binder.0;
register_region_obligation(tcx, t_a, r_b,
obligation.cause.clone(),
region_obligations);
}
true
}
ty::Predicate::Projection(ref data) => {
let project_obligation = obligation.with(data.clone());
let result = project::poly_project_and_unify_type(selcx, &project_obligation);
debug!("process_predicate: poly_project_and_unify_type({}) returned {}",
project_obligation.repr(tcx),
result.repr(tcx));
match result {
Ok(Some(obligations)) => {
new_obligations.extend(obligations.into_iter());
true
}
Ok(None) => {
false
}
Err(err) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeProjectionError(err)));
true
}
}
}
}
}
impl<'tcx> Repr<'tcx> for RegionObligation<'tcx> {
fn repr(&self, tcx: &ty::ctxt<'tcx>) -> String {
format!("RegionObligation(sub_region={}, sup_type={})",
self.sub_region.repr(tcx),
self.sup_type.repr(tcx))
}
}
fn register_region_obligation<'tcx>(tcx: &ty::ctxt<'tcx>,
t_a: Ty<'tcx>,
r_b: ty::Region,
cause: ObligationCause<'tcx>,
region_obligations: &mut NodeMap<Vec<RegionObligation<'tcx>>>)
{
let region_obligation = RegionObligation { sup_type: t_a,
sub_region: r_b,
cause: cause };
debug!("register_region_obligation({})",
|
{
debug!("normalize_associated_type(projection_ty={})",
projection_ty.repr(infcx.tcx));
assert!(!projection_ty.has_escaping_regions());
// FIXME(#20304) -- cache
let mut selcx = SelectionContext::new(infcx, typer);
let normalized = project::normalize_projection_type(&mut selcx, projection_ty, cause, 0);
for obligation in normalized.obligations {
self.register_predicate_obligation(infcx, obligation);
}
debug!("normalize_associated_type: result={}", normalized.value.repr(infcx.tcx));
normalized.value
}
|
identifier_body
|
game.rs
|
use std::ops::{AddAssign, Not};
use std::sync::Arc;
// The two dimensional position is a number between 0 and 15,
// the three dimensional position is a number between 0 and 63.
//
// But still, they should be differentiated and the type system must track this.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Position2(pub u8);
// Position3 is also known as FlatCoordinate in "legacy" code.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Position3(pub u8);
// Used for the Structure. This is a [bool; 64] in disguise.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Subset(pub u64);
impl Position2 {
pub fn new(x: u8, y: u8) -> Self {
debug_assert!(x <= 3 && y <= 3);
Position2(x + 4 * y)
}
pub fn with_height(self, z: u8) -> Position3 {
debug_assert!(z <= 3);
Position3(self.0 + 16 * z)
}
pub fn coords(self) -> (u8, u8) {
(self.0 % 4, self.0 / 4)
}
}
impl Position3 {
#[allow(dead_code)]
pub fn new(x: u8, y: u8, z: u8) -> Self {
debug_assert!(x <= 3 && y <= 3 && z <= 3);
Position3(x + 4 * y + 16 * z)
}
pub fn coords(self) -> (u8, u8, u8) {
(self.0 % 4, (self.0 / 4) % 4, self.0 / 16)
}
}
impl From<Position3> for Position2 {
fn from(position3: Position3) -> Position2 {
Position2(position3.0 % 16)
}
}
impl Subset {
#[allow(dead_code)]
// This is used by the tests and in general a nice function to have
// around.
pub fn contains(self, position: Position3) -> bool {
(self.0 >> position.0) % 2 == 1
}
pub fn iter(self) -> SubsetIterator {
SubsetIterator {
step_count: 0,
shape: self.0,
}
}
pub fn win_state(self, state: &State) -> LineState {
let mut stats = SubsetStats {
color: None,
objects: 0,
full: true,
mixed: false,
};
for point in self.iter().map(|p| state.at(p)) {
stats += point;
}
if stats.mixed {
LineState::Mixed
} else if stats.full {
LineState::Win(stats.color.unwrap())
} else if stats.color == None {
LineState::Empty
} else {
LineState::Pure {
color: stats.color.unwrap(),
count: stats.objects as i8,
}
}
}
}
#[derive(Debug)]
struct SubsetStats {
color: Option<Color>,
objects: u8,
full: bool,
mixed: bool,
}
impl AddAssign<PointState> for SubsetStats {
fn add_assign(&mut self, new_point: PointState) {
match new_point {
PointState::Empty => self.full = false,
PointState::Piece(color) => {
self.objects += 1;
match self.color {
None => self.color = Some(color),
Some(new_color) => {
if color!= new_color {
self.mixed = true
}
}
}
}
}
}
}
pub struct SubsetIterator {
step_count: u8,
shape: u64,
}
impl Iterator for SubsetIterator {
type Item = Position3;
fn next(&mut self) -> Option<Self::Item> {
if self.step_count == 64 {
None
} else {
if self.step_count!= 0 {
self.shape /= 2;
}
self.step_count += 1;
if self.shape % 2 == 1 {
Some(Position3(self.step_count - 1))
} else {
self.next()
}
}
}
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub enum Color {
White,
Black,
}
// This implementation allows Color::White ==!Color::Black.
impl Not for Color {
type Output = Color;
fn not(self) -> Color {
match self {
Color::White => Color::Black,
Color::Black => Color::White,
}
}
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub enum PointState {
Piece(Color),
Empty,
}
// TODO: Move this into AI. There is no reason to store it inside the game::State.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum LineState {
Empty,
Pure { color: Color, count: i8 },
Mixed,
Win(Color),
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub enum VictoryState {
Undecided,
Win {
winner: Color,
reason: Option<Subset>,
},
Draw,
}
impl VictoryState {
pub fn active(&self) -> bool {
match *self {
VictoryState::Undecided => true,
_ => false,
}
}
pub fn scoring(&self, color: Color) -> Option<i8> {
match *self {
VictoryState::Win { winner,.. } => if winner == color { Some(1) } else { Some(-1) },
VictoryState::Draw => Some(0),
VictoryState::Undecided => None,
}
}
}
// TODO: Move this elsewhere, helpers for a start. Implement some traits
#[derive(Debug, Copy, Clone)]
pub struct VictoryStats {
pub white: i32,
pub black: i32,
pub draws: i32,
}
impl VictoryStats {
pub fn new() -> VictoryStats {
VictoryStats {
white: 0,
black: 0,
draws: 0,
}
}
}
pub struct Structure {
// A vector of all Subsets, complete one to win the game.
pub source: Vec<Subset>,
// Contains a lookup table, given a Position3, this returns a vector of indices.
// The indices tell you which Subsets contain the Position3.
pub reverse: [Vec<usize>; 64],
// The size of a victory object. While not technically necessary, having
// uniform victory objects seems like a reasonable restriction.
pub object_size: u8,
}
impl Structure {
pub fn new(victory_objects: &[u64]) -> Structure {
use helpers::EqualityVerifier;
// Convert raw u64 into Subset objects. (Which are u64 with extra structure.)
let source: Vec<Subset> = victory_objects.iter().map(|v| Subset(*v)).collect();
// Unfortunately, [vec![]; 64] does not work :-/
let mut reverse = [
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
];
let mut object_size = EqualityVerifier::NoValue;
for (index, subset) in source.iter().enumerate() {
let mut subset_size = 0;
for position in subset.iter() {
reverse[position.0 as usize].push(index);
subset_size += 1;
}
object_size = object_size.update(subset_size);
}
Structure {
source,
reverse,
object_size: object_size.unwrap(),
}
}
}
pub struct State {
pub points: [PointState; 64],
pub current_color: Color,
pub age: u8, // How many actions were played?
// Everything below here is cached information.
pub victory_state: VictoryState,
// Caches the column height (0, 1, 2, 3) to quickly determine available moves.
pub column_height: [u8; 16],
pub structure: Arc<Structure>,
}
impl State {
pub fn new(structure: Arc<Structure>) -> Self {
State {
points: [PointState::Empty; 64],
current_color: Color::White,
age: 0,
victory_state: VictoryState::Undecided,
column_height: [0; 16],
structure,
}
}
pub fn at(&self, position: Position3) -> PointState {
self.points[position.0 as usize]
}
pub fn
|
(&mut self, column: Position2) {
let position = self.insert(column);
let color =!self.current_color;
self.update_victory_state(position, color);
}
// Panics, if the column is already full.
// This does NOT update the victory state. Use `.execute` for this.
pub fn insert(&mut self, column: Position2) -> Position3 {
let position = {
let z = self.column_height.get_mut(column.0 as usize).unwrap();
let position = column.with_height(*z);
*z += 1;
position
};
self.points[position.0 as usize] = PointState::Piece(self.current_color);
self.age += 1;
self.current_color =!self.current_color;
position
}
fn update_victory_state(&mut self, position: Position3, color: Color) {
for subset_index in self.structure.reverse[position.0 as usize].iter() {
let subset = self.structure.source[*subset_index];
if subset.iter().all(|pos2| {
self.at(pos2) == PointState::Piece(color)
})
{
self.victory_state = VictoryState::Win {
winner: color,
reason: Some(subset),
};
return;
}
}
if self.age == 64 {
self.victory_state = VictoryState::Draw;
}
}
// TODO: Remove the Box when `impl Trait` lands.
// This is predicted for 1.20 on 31st of August 2017.
// https://internals.rust-lang.org/t/rust-release-milestone-predictions/4591
// Or change to nightly at any point :P
pub fn legal_actions<'a>(&'a self) -> Box<Iterator<Item = Position2> + 'a> {
// Fuck missing impl trait xP
Box::new(
self.column_height
.iter()
.enumerate()
.filter(|&(_, h)| *h <= 3)
.map(|(i, _)| Position2(i as u8)),
)
}
pub fn column_full(&self, column: Position2) -> bool {
self.column_height[column.0 as usize] == 4
}
}
// Once [T; 64] becomes Clone, not just Copy, this can be derived.
impl Clone for State {
fn clone(&self) -> Self {
State {
points: self.points,
current_color: self.current_color,
age: self.age,
victory_state: self.victory_state,
column_height: self.column_height,
structure: self.structure.clone(),
}
}
}
|
execute
|
identifier_name
|
game.rs
|
use std::ops::{AddAssign, Not};
use std::sync::Arc;
// The two dimensional position is a number between 0 and 15,
// the three dimensional position is a number between 0 and 63.
//
// But still, they should be differentiated and the type system must track this.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Position2(pub u8);
// Position3 is also known as FlatCoordinate in "legacy" code.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Position3(pub u8);
// Used for the Structure. This is a [bool; 64] in disguise.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct Subset(pub u64);
impl Position2 {
pub fn new(x: u8, y: u8) -> Self {
debug_assert!(x <= 3 && y <= 3);
Position2(x + 4 * y)
}
pub fn with_height(self, z: u8) -> Position3 {
debug_assert!(z <= 3);
Position3(self.0 + 16 * z)
}
pub fn coords(self) -> (u8, u8) {
(self.0 % 4, self.0 / 4)
}
}
impl Position3 {
#[allow(dead_code)]
pub fn new(x: u8, y: u8, z: u8) -> Self {
debug_assert!(x <= 3 && y <= 3 && z <= 3);
Position3(x + 4 * y + 16 * z)
}
pub fn coords(self) -> (u8, u8, u8) {
(self.0 % 4, (self.0 / 4) % 4, self.0 / 16)
}
}
impl From<Position3> for Position2 {
fn from(position3: Position3) -> Position2 {
Position2(position3.0 % 16)
}
}
impl Subset {
#[allow(dead_code)]
// This is used by the tests and in general a nice function to have
// around.
pub fn contains(self, position: Position3) -> bool {
(self.0 >> position.0) % 2 == 1
}
pub fn iter(self) -> SubsetIterator {
SubsetIterator {
step_count: 0,
shape: self.0,
}
}
pub fn win_state(self, state: &State) -> LineState {
let mut stats = SubsetStats {
color: None,
objects: 0,
full: true,
mixed: false,
};
for point in self.iter().map(|p| state.at(p)) {
stats += point;
}
if stats.mixed {
LineState::Mixed
} else if stats.full {
LineState::Win(stats.color.unwrap())
} else if stats.color == None {
LineState::Empty
} else {
LineState::Pure {
color: stats.color.unwrap(),
count: stats.objects as i8,
}
}
}
}
#[derive(Debug)]
struct SubsetStats {
color: Option<Color>,
objects: u8,
full: bool,
mixed: bool,
}
impl AddAssign<PointState> for SubsetStats {
fn add_assign(&mut self, new_point: PointState) {
match new_point {
PointState::Empty => self.full = false,
PointState::Piece(color) => {
self.objects += 1;
match self.color {
None => self.color = Some(color),
Some(new_color) => {
if color!= new_color {
self.mixed = true
}
}
}
}
}
}
}
pub struct SubsetIterator {
step_count: u8,
shape: u64,
}
impl Iterator for SubsetIterator {
type Item = Position3;
fn next(&mut self) -> Option<Self::Item> {
if self.step_count == 64 {
None
} else {
if self.step_count!= 0 {
self.shape /= 2;
}
self.step_count += 1;
if self.shape % 2 == 1 {
Some(Position3(self.step_count - 1))
} else {
self.next()
}
}
}
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub enum Color {
White,
Black,
}
// This implementation allows Color::White ==!Color::Black.
impl Not for Color {
type Output = Color;
fn not(self) -> Color {
match self {
Color::White => Color::Black,
Color::Black => Color::White,
}
}
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub enum PointState {
Piece(Color),
Empty,
}
// TODO: Move this into AI. There is no reason to store it inside the game::State.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum LineState {
Empty,
Pure { color: Color, count: i8 },
Mixed,
Win(Color),
}
#[derive(PartialEq, Eq, Debug, Copy, Clone)]
pub enum VictoryState {
Undecided,
Win {
winner: Color,
reason: Option<Subset>,
},
Draw,
}
impl VictoryState {
pub fn active(&self) -> bool {
match *self {
VictoryState::Undecided => true,
_ => false,
}
}
pub fn scoring(&self, color: Color) -> Option<i8> {
match *self {
VictoryState::Win { winner,.. } => if winner == color { Some(1) } else { Some(-1) },
VictoryState::Draw => Some(0),
VictoryState::Undecided => None,
}
}
}
// TODO: Move this elsewhere, helpers for a start. Implement some traits
#[derive(Debug, Copy, Clone)]
pub struct VictoryStats {
pub white: i32,
pub black: i32,
pub draws: i32,
}
impl VictoryStats {
pub fn new() -> VictoryStats {
VictoryStats {
white: 0,
black: 0,
|
}
pub struct Structure {
// A vector of all Subsets, complete one to win the game.
pub source: Vec<Subset>,
// Contains a lookup table, given a Position3, this returns a vector of indices.
// The indices tell you which Subsets contain the Position3.
pub reverse: [Vec<usize>; 64],
// The size of a victory object. While not technically necessary, having
// uniform victory objects seems like a reasonable restriction.
pub object_size: u8,
}
impl Structure {
pub fn new(victory_objects: &[u64]) -> Structure {
use helpers::EqualityVerifier;
// Convert raw u64 into Subset objects. (Which are u64 with extra structure.)
let source: Vec<Subset> = victory_objects.iter().map(|v| Subset(*v)).collect();
// Unfortunately, [vec![]; 64] does not work :-/
let mut reverse = [
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
vec![],
];
let mut object_size = EqualityVerifier::NoValue;
for (index, subset) in source.iter().enumerate() {
let mut subset_size = 0;
for position in subset.iter() {
reverse[position.0 as usize].push(index);
subset_size += 1;
}
object_size = object_size.update(subset_size);
}
Structure {
source,
reverse,
object_size: object_size.unwrap(),
}
}
}
pub struct State {
pub points: [PointState; 64],
pub current_color: Color,
pub age: u8, // How many actions were played?
// Everything below here is cached information.
pub victory_state: VictoryState,
// Caches the column height (0, 1, 2, 3) to quickly determine available moves.
pub column_height: [u8; 16],
pub structure: Arc<Structure>,
}
impl State {
pub fn new(structure: Arc<Structure>) -> Self {
State {
points: [PointState::Empty; 64],
current_color: Color::White,
age: 0,
victory_state: VictoryState::Undecided,
column_height: [0; 16],
structure,
}
}
pub fn at(&self, position: Position3) -> PointState {
self.points[position.0 as usize]
}
pub fn execute(&mut self, column: Position2) {
let position = self.insert(column);
let color =!self.current_color;
self.update_victory_state(position, color);
}
// Panics, if the column is already full.
// This does NOT update the victory state. Use `.execute` for this.
pub fn insert(&mut self, column: Position2) -> Position3 {
let position = {
let z = self.column_height.get_mut(column.0 as usize).unwrap();
let position = column.with_height(*z);
*z += 1;
position
};
self.points[position.0 as usize] = PointState::Piece(self.current_color);
self.age += 1;
self.current_color =!self.current_color;
position
}
fn update_victory_state(&mut self, position: Position3, color: Color) {
for subset_index in self.structure.reverse[position.0 as usize].iter() {
let subset = self.structure.source[*subset_index];
if subset.iter().all(|pos2| {
self.at(pos2) == PointState::Piece(color)
})
{
self.victory_state = VictoryState::Win {
winner: color,
reason: Some(subset),
};
return;
}
}
if self.age == 64 {
self.victory_state = VictoryState::Draw;
}
}
// TODO: Remove the Box when `impl Trait` lands.
// This is predicted for 1.20 on 31st of August 2017.
// https://internals.rust-lang.org/t/rust-release-milestone-predictions/4591
// Or change to nightly at any point :P
pub fn legal_actions<'a>(&'a self) -> Box<Iterator<Item = Position2> + 'a> {
// Fuck missing impl trait xP
Box::new(
self.column_height
.iter()
.enumerate()
.filter(|&(_, h)| *h <= 3)
.map(|(i, _)| Position2(i as u8)),
)
}
pub fn column_full(&self, column: Position2) -> bool {
self.column_height[column.0 as usize] == 4
}
}
// Once [T; 64] becomes Clone, not just Copy, this can be derived.
impl Clone for State {
fn clone(&self) -> Self {
State {
points: self.points,
current_color: self.current_color,
age: self.age,
victory_state: self.victory_state,
column_height: self.column_height,
structure: self.structure.clone(),
}
}
}
|
draws: 0,
}
}
|
random_line_split
|
tuple-style-enum.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.
// ignore-tidy-linelength
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:set print union on
// gdb-command:run
// gdb-command:print case1
// gdb-check:$1 = {{RUST$ENUM$DISR = Case1, 0, 31868, 31868, 31868, 31868}, {RUST$ENUM$DISR = Case1, 0, 2088533116, 2088533116}, {RUST$ENUM$DISR = Case1, 0, 8970181431921507452}}
// gdb-command:print case2
// gdb-check:$2 = {{RUST$ENUM$DISR = Case2, 0, 4369, 4369, 4369, 4369}, {RUST$ENUM$DISR = Case2, 0, 286331153, 286331153}, {RUST$ENUM$DISR = Case2, 0, 1229782938247303441}}
// gdb-command:print case3
// gdb-check:$3 = {{RUST$ENUM$DISR = Case3, 0, 22873, 22873, 22873, 22873}, {RUST$ENUM$DISR = Case3, 0, 1499027801, 1499027801}, {RUST$ENUM$DISR = Case3, 0, 6438275382588823897}}
// gdb-command:print univariant
// gdb-check:$4 = {{-1}}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print case1
// lldb-check:[...]$0 = Case1(0, 31868, 31868, 31868, 31868)
// lldb-command:print case2
// lldb-check:[...]$1 = Case2(0, 286331153, 286331153)
// lldb-command:print case3
// lldb-check:[...]$2 = Case3(0, 6438275382588823897)
// lldb-command:print univariant
// lldb-check:[...]$3 = TheOnlyCase(-1)
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
use self::Regular::{Case1, Case2, Case3};
use self::Univariant::TheOnlyCase;
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Regular {
Case1(u64, u16, u16, u16, u16),
Case2(u64, u32, u32),
Case3(u64, u64)
}
enum Univariant {
TheOnlyCase(i64)
}
fn
|
() {
// In order to avoid endianness trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
let case1 = Case1(0, 31868, 31868, 31868, 31868);
// 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
// 0b00010001000100010001000100010001 = 286331153
// 0b0001000100010001 = 4369
// 0b00010001 = 17
let case2 = Case2(0, 286331153, 286331153);
// 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897
// 0b01011001010110010101100101011001 = 1499027801
// 0b0101100101011001 = 22873
// 0b01011001 = 89
let case3 = Case3(0, 6438275382588823897);
let univariant = TheOnlyCase(-1);
zzz(); // #break
}
fn zzz() {()}
|
main
|
identifier_name
|
tuple-style-enum.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.
// ignore-tidy-linelength
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:set print union on
// gdb-command:run
// gdb-command:print case1
// gdb-check:$1 = {{RUST$ENUM$DISR = Case1, 0, 31868, 31868, 31868, 31868}, {RUST$ENUM$DISR = Case1, 0, 2088533116, 2088533116}, {RUST$ENUM$DISR = Case1, 0, 8970181431921507452}}
// gdb-command:print case2
// gdb-check:$2 = {{RUST$ENUM$DISR = Case2, 0, 4369, 4369, 4369, 4369}, {RUST$ENUM$DISR = Case2, 0, 286331153, 286331153}, {RUST$ENUM$DISR = Case2, 0, 1229782938247303441}}
// gdb-command:print case3
// gdb-check:$3 = {{RUST$ENUM$DISR = Case3, 0, 22873, 22873, 22873, 22873}, {RUST$ENUM$DISR = Case3, 0, 1499027801, 1499027801}, {RUST$ENUM$DISR = Case3, 0, 6438275382588823897}}
// gdb-command:print univariant
// gdb-check:$4 = {{-1}}
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print case1
// lldb-check:[...]$0 = Case1(0, 31868, 31868, 31868, 31868)
// lldb-command:print case2
// lldb-check:[...]$1 = Case2(0, 286331153, 286331153)
// lldb-command:print case3
// lldb-check:[...]$2 = Case3(0, 6438275382588823897)
// lldb-command:print univariant
// lldb-check:[...]$3 = TheOnlyCase(-1)
#![allow(unused_variables)]
#![omit_gdb_pretty_printer_section]
use self::Regular::{Case1, Case2, Case3};
use self::Univariant::TheOnlyCase;
// The first element is to ensure proper alignment, irrespective of the machines word size. Since
// the size of the discriminant value is machine dependent, this has be taken into account when
// datatype layout should be predictable as in this case.
enum Regular {
Case1(u64, u16, u16, u16, u16),
Case2(u64, u32, u32),
Case3(u64, u64)
}
enum Univariant {
TheOnlyCase(i64)
}
|
// In order to avoid endianness trouble all of the following test values consist of a single
// repeated byte. This way each interpretation of the union should look the same, no matter if
// this is a big or little endian machine.
// 0b0111110001111100011111000111110001111100011111000111110001111100 = 8970181431921507452
// 0b01111100011111000111110001111100 = 2088533116
// 0b0111110001111100 = 31868
// 0b01111100 = 124
let case1 = Case1(0, 31868, 31868, 31868, 31868);
// 0b0001000100010001000100010001000100010001000100010001000100010001 = 1229782938247303441
// 0b00010001000100010001000100010001 = 286331153
// 0b0001000100010001 = 4369
// 0b00010001 = 17
let case2 = Case2(0, 286331153, 286331153);
// 0b0101100101011001010110010101100101011001010110010101100101011001 = 6438275382588823897
// 0b01011001010110010101100101011001 = 1499027801
// 0b0101100101011001 = 22873
// 0b01011001 = 89
let case3 = Case3(0, 6438275382588823897);
let univariant = TheOnlyCase(-1);
zzz(); // #break
}
fn zzz() {()}
|
fn main() {
|
random_line_split
|
load.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Used by `rustc` when loading a plugin.
use session::Session;
use metadata::creader::PluginMetadataReader;
use plugin::registry::Registry;
use std::mem;
use std::os;
use std::dynamic_lib::DynamicLibrary;
use syntax::ast;
use syntax::attr;
use syntax::visit;
use syntax::visit::Visitor;
use syntax::ext::expand::ExportedMacros;
use syntax::attr::AttrMetaMethods;
/// Plugin-related crate metadata.
pub struct PluginMetadata {
/// Source code of macros exported by the crate.
pub macros: Vec<String>,
/// Path to the shared library file.
pub lib: Option<Path>,
/// Symbol name of the plugin registrar function.
pub registrar_symbol: Option<String>,
}
/// Pointer to a registrar function.
pub type PluginRegistrarFun =
fn(&mut Registry);
/// Information about loaded plugins.
pub struct Plugins {
/// Source code of exported macros.
pub macros: Vec<ExportedMacros>,
/// Registrars, as function pointers.
pub registrars: Vec<PluginRegistrarFun>,
}
struct PluginLoader<'a> {
sess: &'a Session,
reader: PluginMetadataReader<'a>,
plugins: Plugins,
}
impl<'a> PluginLoader<'a> {
fn new(sess: &'a Session) -> PluginLoader<'a> {
PluginLoader {
sess: sess,
reader: PluginMetadataReader::new(sess),
plugins: Plugins {
macros: vec!(),
registrars: vec!(),
},
}
}
}
/// Read plugin metadata and dynamically load registrar functions.
pub fn load_plugins(sess: &Session, krate: &ast::Crate,
addl_plugins: Option<Plugins>) -> Plugins {
let mut loader = PluginLoader::new(sess);
visit::walk_crate(&mut loader, krate);
let mut plugins = loader.plugins;
match addl_plugins {
Some(addl_plugins) => {
// Add in the additional plugins requested by the frontend
let Plugins { macros: addl_macros, registrars: addl_registrars } = addl_plugins;
plugins.macros.extend(addl_macros.into_iter());
plugins.registrars.extend(addl_registrars.into_iter());
}
None => ()
}
return plugins;
}
// note that macros aren't expanded yet, and therefore macros can't add plugins.
impl<'a, 'v> Visitor<'v> for PluginLoader<'a> {
fn visit_view_item(&mut self, vi: &ast::ViewItem) {
match vi.node {
ast::ViewItemExternCrate(name, _, _) => {
let mut plugin_phase = false;
for attr in vi.attrs.iter().filter(|a| a.check_name("phase")) {
let phases = attr.meta_item_list().unwrap_or(&[]);
if attr::contains_name(phases, "plugin") {
plugin_phase = true;
}
if attr::contains_name(phases, "syntax") {
plugin_phase = true;
self.sess.span_warn(attr.span,
"phase(syntax) is a deprecated synonym for phase(plugin)");
}
}
if!plugin_phase { return; }
let PluginMetadata { macros, lib, registrar_symbol } =
self.reader.read_plugin_metadata(vi);
self.plugins.macros.push(ExportedMacros {
crate_name: name,
macros: macros,
});
match (lib, registrar_symbol) {
(Some(lib), Some(symbol))
=> self.dylink_registrar(vi, lib, symbol),
_ => (),
}
}
_ => (),
}
}
fn visit_mac(&mut self, _: &ast::Mac) {
// bummer... can't see plugins inside macros.
// do nothing.
}
}
impl<'a> PluginLoader<'a> {
// Dynamically link a registrar function into the compiler process.
fn
|
(&mut self, vi: &ast::ViewItem, path: Path, symbol: String) {
// Make sure the path contains a / or the linker will search for it.
let path = os::make_absolute(&path).unwrap();
let lib = match DynamicLibrary::open(Some(&path)) {
Ok(lib) => lib,
// this is fatal: there are almost certainly macros we need
// inside this crate, so continue would spew "macro undefined"
// errors
Err(err) => self.sess.span_fatal(vi.span, err.as_slice())
};
unsafe {
let registrar =
match lib.symbol(symbol.as_slice()) {
Ok(registrar) => {
mem::transmute::<*mut u8,PluginRegistrarFun>(registrar)
}
// again fatal if we can't register macros
Err(err) => self.sess.span_fatal(vi.span, err.as_slice())
};
self.plugins.registrars.push(registrar);
// Intentionally leak the dynamic library. We can't ever unload it
// since the library can make things that will live arbitrarily long
// (e.g. an @-box cycle or a task).
mem::forget(lib);
}
}
}
|
dylink_registrar
|
identifier_name
|
load.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Used by `rustc` when loading a plugin.
use session::Session;
use metadata::creader::PluginMetadataReader;
use plugin::registry::Registry;
use std::mem;
use std::os;
use std::dynamic_lib::DynamicLibrary;
use syntax::ast;
use syntax::attr;
use syntax::visit;
use syntax::visit::Visitor;
use syntax::ext::expand::ExportedMacros;
use syntax::attr::AttrMetaMethods;
/// Plugin-related crate metadata.
pub struct PluginMetadata {
/// Source code of macros exported by the crate.
pub macros: Vec<String>,
/// Path to the shared library file.
pub lib: Option<Path>,
/// Symbol name of the plugin registrar function.
pub registrar_symbol: Option<String>,
}
/// Pointer to a registrar function.
pub type PluginRegistrarFun =
fn(&mut Registry);
/// Information about loaded plugins.
pub struct Plugins {
/// Source code of exported macros.
pub macros: Vec<ExportedMacros>,
/// Registrars, as function pointers.
pub registrars: Vec<PluginRegistrarFun>,
}
struct PluginLoader<'a> {
sess: &'a Session,
reader: PluginMetadataReader<'a>,
plugins: Plugins,
}
impl<'a> PluginLoader<'a> {
fn new(sess: &'a Session) -> PluginLoader<'a> {
PluginLoader {
sess: sess,
reader: PluginMetadataReader::new(sess),
plugins: Plugins {
macros: vec!(),
registrars: vec!(),
},
}
}
}
/// Read plugin metadata and dynamically load registrar functions.
pub fn load_plugins(sess: &Session, krate: &ast::Crate,
addl_plugins: Option<Plugins>) -> Plugins {
let mut loader = PluginLoader::new(sess);
visit::walk_crate(&mut loader, krate);
let mut plugins = loader.plugins;
match addl_plugins {
Some(addl_plugins) => {
// Add in the additional plugins requested by the frontend
let Plugins { macros: addl_macros, registrars: addl_registrars } = addl_plugins;
plugins.macros.extend(addl_macros.into_iter());
plugins.registrars.extend(addl_registrars.into_iter());
}
None => ()
}
return plugins;
}
// note that macros aren't expanded yet, and therefore macros can't add plugins.
impl<'a, 'v> Visitor<'v> for PluginLoader<'a> {
fn visit_view_item(&mut self, vi: &ast::ViewItem) {
match vi.node {
ast::ViewItemExternCrate(name, _, _) => {
let mut plugin_phase = false;
for attr in vi.attrs.iter().filter(|a| a.check_name("phase")) {
let phases = attr.meta_item_list().unwrap_or(&[]);
if attr::contains_name(phases, "plugin") {
plugin_phase = true;
}
if attr::contains_name(phases, "syntax") {
plugin_phase = true;
self.sess.span_warn(attr.span,
"phase(syntax) is a deprecated synonym for phase(plugin)");
}
}
if!plugin_phase { return; }
let PluginMetadata { macros, lib, registrar_symbol } =
self.reader.read_plugin_metadata(vi);
self.plugins.macros.push(ExportedMacros {
crate_name: name,
macros: macros,
});
match (lib, registrar_symbol) {
(Some(lib), Some(symbol))
=> self.dylink_registrar(vi, lib, symbol),
_ => (),
}
}
_ => (),
}
}
fn visit_mac(&mut self, _: &ast::Mac) {
// bummer... can't see plugins inside macros.
// do nothing.
}
}
impl<'a> PluginLoader<'a> {
// Dynamically link a registrar function into the compiler process.
fn dylink_registrar(&mut self, vi: &ast::ViewItem, path: Path, symbol: String) {
// Make sure the path contains a / or the linker will search for it.
let path = os::make_absolute(&path).unwrap();
let lib = match DynamicLibrary::open(Some(&path)) {
Ok(lib) => lib,
// this is fatal: there are almost certainly macros we need
// inside this crate, so continue would spew "macro undefined"
// errors
Err(err) => self.sess.span_fatal(vi.span, err.as_slice())
};
unsafe {
let registrar =
match lib.symbol(symbol.as_slice()) {
Ok(registrar) => {
mem::transmute::<*mut u8,PluginRegistrarFun>(registrar)
}
// again fatal if we can't register macros
Err(err) => self.sess.span_fatal(vi.span, err.as_slice())
};
self.plugins.registrars.push(registrar);
// Intentionally leak the dynamic library. We can't ever unload it
// since the library can make things that will live arbitrarily long
// (e.g. an @-box cycle or a task).
mem::forget(lib);
}
}
|
}
|
random_line_split
|
|
load.rs
|
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Used by `rustc` when loading a plugin.
use session::Session;
use metadata::creader::PluginMetadataReader;
use plugin::registry::Registry;
use std::mem;
use std::os;
use std::dynamic_lib::DynamicLibrary;
use syntax::ast;
use syntax::attr;
use syntax::visit;
use syntax::visit::Visitor;
use syntax::ext::expand::ExportedMacros;
use syntax::attr::AttrMetaMethods;
/// Plugin-related crate metadata.
pub struct PluginMetadata {
/// Source code of macros exported by the crate.
pub macros: Vec<String>,
/// Path to the shared library file.
pub lib: Option<Path>,
/// Symbol name of the plugin registrar function.
pub registrar_symbol: Option<String>,
}
/// Pointer to a registrar function.
pub type PluginRegistrarFun =
fn(&mut Registry);
/// Information about loaded plugins.
pub struct Plugins {
/// Source code of exported macros.
pub macros: Vec<ExportedMacros>,
/// Registrars, as function pointers.
pub registrars: Vec<PluginRegistrarFun>,
}
struct PluginLoader<'a> {
sess: &'a Session,
reader: PluginMetadataReader<'a>,
plugins: Plugins,
}
impl<'a> PluginLoader<'a> {
fn new(sess: &'a Session) -> PluginLoader<'a> {
PluginLoader {
sess: sess,
reader: PluginMetadataReader::new(sess),
plugins: Plugins {
macros: vec!(),
registrars: vec!(),
},
}
}
}
/// Read plugin metadata and dynamically load registrar functions.
pub fn load_plugins(sess: &Session, krate: &ast::Crate,
addl_plugins: Option<Plugins>) -> Plugins {
let mut loader = PluginLoader::new(sess);
visit::walk_crate(&mut loader, krate);
let mut plugins = loader.plugins;
match addl_plugins {
Some(addl_plugins) => {
// Add in the additional plugins requested by the frontend
let Plugins { macros: addl_macros, registrars: addl_registrars } = addl_plugins;
plugins.macros.extend(addl_macros.into_iter());
plugins.registrars.extend(addl_registrars.into_iter());
}
None => ()
}
return plugins;
}
// note that macros aren't expanded yet, and therefore macros can't add plugins.
impl<'a, 'v> Visitor<'v> for PluginLoader<'a> {
fn visit_view_item(&mut self, vi: &ast::ViewItem) {
match vi.node {
ast::ViewItemExternCrate(name, _, _) =>
|
self.plugins.macros.push(ExportedMacros {
crate_name: name,
macros: macros,
});
match (lib, registrar_symbol) {
(Some(lib), Some(symbol))
=> self.dylink_registrar(vi, lib, symbol),
_ => (),
}
}
_ => (),
}
}
fn visit_mac(&mut self, _: &ast::Mac) {
// bummer... can't see plugins inside macros.
// do nothing.
}
}
impl<'a> PluginLoader<'a> {
// Dynamically link a registrar function into the compiler process.
fn dylink_registrar(&mut self, vi: &ast::ViewItem, path: Path, symbol: String) {
// Make sure the path contains a / or the linker will search for it.
let path = os::make_absolute(&path).unwrap();
let lib = match DynamicLibrary::open(Some(&path)) {
Ok(lib) => lib,
// this is fatal: there are almost certainly macros we need
// inside this crate, so continue would spew "macro undefined"
// errors
Err(err) => self.sess.span_fatal(vi.span, err.as_slice())
};
unsafe {
let registrar =
match lib.symbol(symbol.as_slice()) {
Ok(registrar) => {
mem::transmute::<*mut u8,PluginRegistrarFun>(registrar)
}
// again fatal if we can't register macros
Err(err) => self.sess.span_fatal(vi.span, err.as_slice())
};
self.plugins.registrars.push(registrar);
// Intentionally leak the dynamic library. We can't ever unload it
// since the library can make things that will live arbitrarily long
// (e.g. an @-box cycle or a task).
mem::forget(lib);
}
}
}
|
{
let mut plugin_phase = false;
for attr in vi.attrs.iter().filter(|a| a.check_name("phase")) {
let phases = attr.meta_item_list().unwrap_or(&[]);
if attr::contains_name(phases, "plugin") {
plugin_phase = true;
}
if attr::contains_name(phases, "syntax") {
plugin_phase = true;
self.sess.span_warn(attr.span,
"phase(syntax) is a deprecated synonym for phase(plugin)");
}
}
if !plugin_phase { return; }
let PluginMetadata { macros, lib, registrar_symbol } =
self.reader.read_plugin_metadata(vi);
|
conditional_block
|
service.rs
|
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::proto::{Health, HealthCheckRequest, HealthCheckResponse, ServingStatus};
use futures_util::{FutureExt as _, SinkExt as _, Stream, StreamExt as _};
use grpcio::{RpcContext, RpcStatus, RpcStatusCode, ServerStreamingSink, UnarySink, WriteFlags};
use log::info;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
#[cfg(feature = "protobuf-codec")]
use protobuf::ProtobufEnum;
const VERSION_STEP: usize = 8;
const STATUS_MASK: usize = 7;
fn state_to_status(state: usize) -> ServingStatus {
ServingStatus::from_i32((state & STATUS_MASK) as i32).unwrap()
}
/// Struct that stores the state of a service and wake all subscribers when there
/// is any updates.
struct StatusCast {
state: AtomicUsize,
subscribers: Mutex<HashMap<u64, Waker>>,
}
impl StatusCast {
fn new(status: ServingStatus) -> StatusCast {
StatusCast {
state: AtomicUsize::new(VERSION_STEP | (status as usize)),
subscribers: Mutex::default(),
}
}
/// Updates the status to specified one and update version.
fn broadcast(&self, status: ServingStatus) {
let mut subscribers = self.subscribers.lock().unwrap();
let state = self.state.load(Ordering::Relaxed);
let new_state = ((state + VERSION_STEP) &!STATUS_MASK) | (status as usize);
self.state.store(new_state, Ordering::Relaxed);
for (_, s) in subscribers.drain() {
s.wake();
}
}
}
/// Struct that gets notified when service status changes.
struct StatusSubscriber {
cast: Arc<StatusCast>,
last_state: usize,
id: u64,
}
impl StatusSubscriber {
fn new(id: u64, cast: Arc<StatusCast>) -> StatusSubscriber {
StatusSubscriber {
cast,
last_state: 0,
id,
}
}
}
impl Stream for StatusSubscriber {
type Item = ServingStatus;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<ServingStatus>> {
let s = &mut *self;
let cur_state = s.cast.state.load(Ordering::Relaxed);
if cur_state!= s.last_state {
let status = state_to_status(cur_state);
s.last_state = cur_state;
return Poll::Ready(Some(status));
}
let mut subscribers = s.cast.subscribers.lock().unwrap();
let cur_state = s.cast.state.load(Ordering::Relaxed);
if cur_state!= s.last_state {
let status = state_to_status(cur_state);
s.last_state = cur_state;
return Poll::Ready(Some(status));
}
match subscribers.entry(s.id) {
Entry::Occupied(mut e) => {
if!e.get().will_wake(cx.waker()) {
e.insert(cx.waker().clone());
}
}
Entry::Vacant(v) => {
v.insert(cx.waker().clone());
}
}
Poll::Pending
}
}
impl Drop for StatusSubscriber {
fn drop(&mut self) {
let mut subscribers = self.cast.subscribers.lock().unwrap();
subscribers.remove(&self.id);
}
}
#[derive(Default)]
struct Inner {
id: u64,
shutdown: bool,
status: HashMap<String, ServingStatus>,
casts: HashMap<String, Arc<StatusCast>>,
}
/// Simple implementation for `Health` service.
#[derive(Clone, Default)]
pub struct HealthService {
inner: Arc<Mutex<Inner>>,
}
impl HealthService {
/// Resets the serving status of a service or inserts a new service status.
pub fn set_serving_status(&self, service: &str, status: ServingStatus)
|
cast.broadcast(status);
}
/// Sets all serving status to NotServing, and configures the server to
/// ignore all future status changes.
///
/// This changes serving status for all services.
pub fn shutdown(&self) {
let mut inner = self.inner.lock().unwrap();
inner.shutdown = true;
for val in inner.status.values_mut() {
*val = ServingStatus::NotServing;
}
for cast in inner.casts.values() {
cast.broadcast(ServingStatus::NotServing);
}
}
}
#[allow(clippy::useless_conversion)]
fn build_response(status: ServingStatus) -> HealthCheckResponse {
HealthCheckResponse {
status: status.into(),
..Default::default()
}
}
impl Health for HealthService {
fn check(
&mut self,
ctx: RpcContext,
req: HealthCheckRequest,
sink: UnarySink<HealthCheckResponse>,
) {
let status = {
let inner = self.inner.lock().unwrap();
inner.status.get(&req.service).cloned()
};
if let Some(status) = status {
let resp = build_response(status);
ctx.spawn(sink.success(resp).map(|_| ()));
return;
}
ctx.spawn(
sink.fail(RpcStatus::with_message(
RpcStatusCode::NOT_FOUND,
"unknown service".to_owned(),
))
.map(|_| ()),
)
}
fn watch(
&mut self,
ctx: RpcContext,
req: HealthCheckRequest,
mut sink: ServerStreamingSink<HealthCheckResponse>,
) {
let name = req.service;
let (id, v) = {
let mut inner = self.inner.lock().unwrap();
inner.id += 1;
if let Some(c) = inner.casts.get(&name) {
(inner.id, c.clone())
} else {
let status = match inner.status.get(&name) {
Some(s) => *s,
None => ServingStatus::ServiceUnknown,
};
let c = Arc::new(StatusCast::new(status));
inner.casts.insert(name.clone(), c.clone());
(inner.id, c)
}
};
let sub = StatusSubscriber::new(id, v);
let inner = self.inner.clone();
ctx.spawn(async move {
let _ = sink
.send_all(&mut sub.map(|s| Ok((build_response(s), WriteFlags::default()))))
.await;
let mut inner = inner.lock().unwrap();
if let Some(c) = inner.casts.get(&name) {
// If there is any subscriber, then cast reference count should not be 1 as
// it's referenced by all subscriber.
if Arc::strong_count(c) == 1 {
inner.casts.remove(&name);
}
}
})
}
}
|
{
let cast = {
let mut inner = self.inner.lock().unwrap();
if inner.shutdown {
info!("health: status changing for {} to {:?} is ignored because health service is shutdown", service, status);
return;
}
if let Some(val) = inner.status.get_mut(service) {
*val = status;
} else {
inner.status.insert(service.to_string(), status);
}
if let Some(cast) = inner.casts.get(service) {
cast.clone()
} else {
return;
}
};
|
identifier_body
|
service.rs
|
use futures_util::{FutureExt as _, SinkExt as _, Stream, StreamExt as _};
use grpcio::{RpcContext, RpcStatus, RpcStatusCode, ServerStreamingSink, UnarySink, WriteFlags};
use log::info;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
#[cfg(feature = "protobuf-codec")]
use protobuf::ProtobufEnum;
const VERSION_STEP: usize = 8;
const STATUS_MASK: usize = 7;
fn state_to_status(state: usize) -> ServingStatus {
ServingStatus::from_i32((state & STATUS_MASK) as i32).unwrap()
}
/// Struct that stores the state of a service and wake all subscribers when there
/// is any updates.
struct StatusCast {
state: AtomicUsize,
subscribers: Mutex<HashMap<u64, Waker>>,
}
impl StatusCast {
fn new(status: ServingStatus) -> StatusCast {
StatusCast {
state: AtomicUsize::new(VERSION_STEP | (status as usize)),
subscribers: Mutex::default(),
}
}
/// Updates the status to specified one and update version.
fn broadcast(&self, status: ServingStatus) {
let mut subscribers = self.subscribers.lock().unwrap();
let state = self.state.load(Ordering::Relaxed);
let new_state = ((state + VERSION_STEP) &!STATUS_MASK) | (status as usize);
self.state.store(new_state, Ordering::Relaxed);
for (_, s) in subscribers.drain() {
s.wake();
}
}
}
/// Struct that gets notified when service status changes.
struct StatusSubscriber {
cast: Arc<StatusCast>,
last_state: usize,
id: u64,
}
impl StatusSubscriber {
fn new(id: u64, cast: Arc<StatusCast>) -> StatusSubscriber {
StatusSubscriber {
cast,
last_state: 0,
id,
}
}
}
impl Stream for StatusSubscriber {
type Item = ServingStatus;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<ServingStatus>> {
let s = &mut *self;
let cur_state = s.cast.state.load(Ordering::Relaxed);
if cur_state!= s.last_state {
let status = state_to_status(cur_state);
s.last_state = cur_state;
return Poll::Ready(Some(status));
}
let mut subscribers = s.cast.subscribers.lock().unwrap();
let cur_state = s.cast.state.load(Ordering::Relaxed);
if cur_state!= s.last_state {
let status = state_to_status(cur_state);
s.last_state = cur_state;
return Poll::Ready(Some(status));
}
match subscribers.entry(s.id) {
Entry::Occupied(mut e) => {
if!e.get().will_wake(cx.waker()) {
e.insert(cx.waker().clone());
}
}
Entry::Vacant(v) => {
v.insert(cx.waker().clone());
}
}
Poll::Pending
}
}
impl Drop for StatusSubscriber {
fn drop(&mut self) {
let mut subscribers = self.cast.subscribers.lock().unwrap();
subscribers.remove(&self.id);
}
}
#[derive(Default)]
struct Inner {
id: u64,
shutdown: bool,
status: HashMap<String, ServingStatus>,
casts: HashMap<String, Arc<StatusCast>>,
}
/// Simple implementation for `Health` service.
#[derive(Clone, Default)]
pub struct HealthService {
inner: Arc<Mutex<Inner>>,
}
impl HealthService {
/// Resets the serving status of a service or inserts a new service status.
pub fn set_serving_status(&self, service: &str, status: ServingStatus) {
let cast = {
let mut inner = self.inner.lock().unwrap();
if inner.shutdown {
info!("health: status changing for {} to {:?} is ignored because health service is shutdown", service, status);
return;
}
if let Some(val) = inner.status.get_mut(service) {
*val = status;
} else {
inner.status.insert(service.to_string(), status);
}
if let Some(cast) = inner.casts.get(service) {
cast.clone()
} else {
return;
}
};
cast.broadcast(status);
}
/// Sets all serving status to NotServing, and configures the server to
/// ignore all future status changes.
///
/// This changes serving status for all services.
pub fn shutdown(&self) {
let mut inner = self.inner.lock().unwrap();
inner.shutdown = true;
for val in inner.status.values_mut() {
*val = ServingStatus::NotServing;
}
for cast in inner.casts.values() {
cast.broadcast(ServingStatus::NotServing);
}
}
}
#[allow(clippy::useless_conversion)]
fn build_response(status: ServingStatus) -> HealthCheckResponse {
HealthCheckResponse {
status: status.into(),
..Default::default()
}
}
impl Health for HealthService {
fn check(
&mut self,
ctx: RpcContext,
req: HealthCheckRequest,
sink: UnarySink<HealthCheckResponse>,
) {
let status = {
let inner = self.inner.lock().unwrap();
inner.status.get(&req.service).cloned()
};
if let Some(status) = status {
let resp = build_response(status);
ctx.spawn(sink.success(resp).map(|_| ()));
return;
}
ctx.spawn(
sink.fail(RpcStatus::with_message(
RpcStatusCode::NOT_FOUND,
"unknown service".to_owned(),
))
.map(|_| ()),
)
}
fn watch(
&mut self,
ctx: RpcContext,
req: HealthCheckRequest,
mut sink: ServerStreamingSink<HealthCheckResponse>,
) {
let name = req.service;
let (id, v) = {
let mut inner = self.inner.lock().unwrap();
inner.id += 1;
if let Some(c) = inner.casts.get(&name) {
(inner.id, c.clone())
} else {
let status = match inner.status.get(&name) {
Some(s) => *s,
None => ServingStatus::ServiceUnknown,
};
let c = Arc::new(StatusCast::new(status));
inner.casts.insert(name.clone(), c.clone());
(inner.id, c)
}
};
let sub = StatusSubscriber::new(id, v);
let inner = self.inner.clone();
ctx.spawn(async move {
let _ = sink
.send_all(&mut sub.map(|s| Ok((build_response(s), WriteFlags::default()))))
.await;
let mut inner = inner.lock().unwrap();
if let Some(c) = inner.casts.get(&name) {
// If there is any subscriber, then cast reference count should not be 1 as
// it's referenced by all subscriber.
if Arc::strong_count(c) == 1 {
inner.casts.remove(&name);
}
}
})
}
}
|
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::proto::{Health, HealthCheckRequest, HealthCheckResponse, ServingStatus};
|
random_line_split
|
|
service.rs
|
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::proto::{Health, HealthCheckRequest, HealthCheckResponse, ServingStatus};
use futures_util::{FutureExt as _, SinkExt as _, Stream, StreamExt as _};
use grpcio::{RpcContext, RpcStatus, RpcStatusCode, ServerStreamingSink, UnarySink, WriteFlags};
use log::info;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
#[cfg(feature = "protobuf-codec")]
use protobuf::ProtobufEnum;
const VERSION_STEP: usize = 8;
const STATUS_MASK: usize = 7;
fn state_to_status(state: usize) -> ServingStatus {
ServingStatus::from_i32((state & STATUS_MASK) as i32).unwrap()
}
/// Struct that stores the state of a service and wake all subscribers when there
/// is any updates.
struct StatusCast {
state: AtomicUsize,
subscribers: Mutex<HashMap<u64, Waker>>,
}
impl StatusCast {
fn new(status: ServingStatus) -> StatusCast {
StatusCast {
state: AtomicUsize::new(VERSION_STEP | (status as usize)),
subscribers: Mutex::default(),
}
}
/// Updates the status to specified one and update version.
fn broadcast(&self, status: ServingStatus) {
let mut subscribers = self.subscribers.lock().unwrap();
let state = self.state.load(Ordering::Relaxed);
let new_state = ((state + VERSION_STEP) &!STATUS_MASK) | (status as usize);
self.state.store(new_state, Ordering::Relaxed);
for (_, s) in subscribers.drain() {
s.wake();
}
}
}
/// Struct that gets notified when service status changes.
struct StatusSubscriber {
cast: Arc<StatusCast>,
last_state: usize,
id: u64,
}
impl StatusSubscriber {
fn new(id: u64, cast: Arc<StatusCast>) -> StatusSubscriber {
StatusSubscriber {
cast,
last_state: 0,
id,
}
}
}
impl Stream for StatusSubscriber {
type Item = ServingStatus;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<ServingStatus>> {
let s = &mut *self;
let cur_state = s.cast.state.load(Ordering::Relaxed);
if cur_state!= s.last_state {
let status = state_to_status(cur_state);
s.last_state = cur_state;
return Poll::Ready(Some(status));
}
let mut subscribers = s.cast.subscribers.lock().unwrap();
let cur_state = s.cast.state.load(Ordering::Relaxed);
if cur_state!= s.last_state {
let status = state_to_status(cur_state);
s.last_state = cur_state;
return Poll::Ready(Some(status));
}
match subscribers.entry(s.id) {
Entry::Occupied(mut e) => {
if!e.get().will_wake(cx.waker()) {
e.insert(cx.waker().clone());
}
}
Entry::Vacant(v) =>
|
}
Poll::Pending
}
}
impl Drop for StatusSubscriber {
fn drop(&mut self) {
let mut subscribers = self.cast.subscribers.lock().unwrap();
subscribers.remove(&self.id);
}
}
#[derive(Default)]
struct Inner {
id: u64,
shutdown: bool,
status: HashMap<String, ServingStatus>,
casts: HashMap<String, Arc<StatusCast>>,
}
/// Simple implementation for `Health` service.
#[derive(Clone, Default)]
pub struct HealthService {
inner: Arc<Mutex<Inner>>,
}
impl HealthService {
/// Resets the serving status of a service or inserts a new service status.
pub fn set_serving_status(&self, service: &str, status: ServingStatus) {
let cast = {
let mut inner = self.inner.lock().unwrap();
if inner.shutdown {
info!("health: status changing for {} to {:?} is ignored because health service is shutdown", service, status);
return;
}
if let Some(val) = inner.status.get_mut(service) {
*val = status;
} else {
inner.status.insert(service.to_string(), status);
}
if let Some(cast) = inner.casts.get(service) {
cast.clone()
} else {
return;
}
};
cast.broadcast(status);
}
/// Sets all serving status to NotServing, and configures the server to
/// ignore all future status changes.
///
/// This changes serving status for all services.
pub fn shutdown(&self) {
let mut inner = self.inner.lock().unwrap();
inner.shutdown = true;
for val in inner.status.values_mut() {
*val = ServingStatus::NotServing;
}
for cast in inner.casts.values() {
cast.broadcast(ServingStatus::NotServing);
}
}
}
#[allow(clippy::useless_conversion)]
fn build_response(status: ServingStatus) -> HealthCheckResponse {
HealthCheckResponse {
status: status.into(),
..Default::default()
}
}
impl Health for HealthService {
fn check(
&mut self,
ctx: RpcContext,
req: HealthCheckRequest,
sink: UnarySink<HealthCheckResponse>,
) {
let status = {
let inner = self.inner.lock().unwrap();
inner.status.get(&req.service).cloned()
};
if let Some(status) = status {
let resp = build_response(status);
ctx.spawn(sink.success(resp).map(|_| ()));
return;
}
ctx.spawn(
sink.fail(RpcStatus::with_message(
RpcStatusCode::NOT_FOUND,
"unknown service".to_owned(),
))
.map(|_| ()),
)
}
fn watch(
&mut self,
ctx: RpcContext,
req: HealthCheckRequest,
mut sink: ServerStreamingSink<HealthCheckResponse>,
) {
let name = req.service;
let (id, v) = {
let mut inner = self.inner.lock().unwrap();
inner.id += 1;
if let Some(c) = inner.casts.get(&name) {
(inner.id, c.clone())
} else {
let status = match inner.status.get(&name) {
Some(s) => *s,
None => ServingStatus::ServiceUnknown,
};
let c = Arc::new(StatusCast::new(status));
inner.casts.insert(name.clone(), c.clone());
(inner.id, c)
}
};
let sub = StatusSubscriber::new(id, v);
let inner = self.inner.clone();
ctx.spawn(async move {
let _ = sink
.send_all(&mut sub.map(|s| Ok((build_response(s), WriteFlags::default()))))
.await;
let mut inner = inner.lock().unwrap();
if let Some(c) = inner.casts.get(&name) {
// If there is any subscriber, then cast reference count should not be 1 as
// it's referenced by all subscriber.
if Arc::strong_count(c) == 1 {
inner.casts.remove(&name);
}
}
})
}
}
|
{
v.insert(cx.waker().clone());
}
|
conditional_block
|
service.rs
|
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
use crate::proto::{Health, HealthCheckRequest, HealthCheckResponse, ServingStatus};
use futures_util::{FutureExt as _, SinkExt as _, Stream, StreamExt as _};
use grpcio::{RpcContext, RpcStatus, RpcStatusCode, ServerStreamingSink, UnarySink, WriteFlags};
use log::info;
use std::collections::hash_map::Entry;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
#[cfg(feature = "protobuf-codec")]
use protobuf::ProtobufEnum;
const VERSION_STEP: usize = 8;
const STATUS_MASK: usize = 7;
fn state_to_status(state: usize) -> ServingStatus {
ServingStatus::from_i32((state & STATUS_MASK) as i32).unwrap()
}
/// Struct that stores the state of a service and wake all subscribers when there
/// is any updates.
struct StatusCast {
state: AtomicUsize,
subscribers: Mutex<HashMap<u64, Waker>>,
}
impl StatusCast {
fn new(status: ServingStatus) -> StatusCast {
StatusCast {
state: AtomicUsize::new(VERSION_STEP | (status as usize)),
subscribers: Mutex::default(),
}
}
/// Updates the status to specified one and update version.
fn broadcast(&self, status: ServingStatus) {
let mut subscribers = self.subscribers.lock().unwrap();
let state = self.state.load(Ordering::Relaxed);
let new_state = ((state + VERSION_STEP) &!STATUS_MASK) | (status as usize);
self.state.store(new_state, Ordering::Relaxed);
for (_, s) in subscribers.drain() {
s.wake();
}
}
}
/// Struct that gets notified when service status changes.
struct StatusSubscriber {
cast: Arc<StatusCast>,
last_state: usize,
id: u64,
}
impl StatusSubscriber {
fn new(id: u64, cast: Arc<StatusCast>) -> StatusSubscriber {
StatusSubscriber {
cast,
last_state: 0,
id,
}
}
}
impl Stream for StatusSubscriber {
type Item = ServingStatus;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<ServingStatus>> {
let s = &mut *self;
let cur_state = s.cast.state.load(Ordering::Relaxed);
if cur_state!= s.last_state {
let status = state_to_status(cur_state);
s.last_state = cur_state;
return Poll::Ready(Some(status));
}
let mut subscribers = s.cast.subscribers.lock().unwrap();
let cur_state = s.cast.state.load(Ordering::Relaxed);
if cur_state!= s.last_state {
let status = state_to_status(cur_state);
s.last_state = cur_state;
return Poll::Ready(Some(status));
}
match subscribers.entry(s.id) {
Entry::Occupied(mut e) => {
if!e.get().will_wake(cx.waker()) {
e.insert(cx.waker().clone());
}
}
Entry::Vacant(v) => {
v.insert(cx.waker().clone());
}
}
Poll::Pending
}
}
impl Drop for StatusSubscriber {
fn drop(&mut self) {
let mut subscribers = self.cast.subscribers.lock().unwrap();
subscribers.remove(&self.id);
}
}
#[derive(Default)]
struct Inner {
id: u64,
shutdown: bool,
status: HashMap<String, ServingStatus>,
casts: HashMap<String, Arc<StatusCast>>,
}
/// Simple implementation for `Health` service.
#[derive(Clone, Default)]
pub struct HealthService {
inner: Arc<Mutex<Inner>>,
}
impl HealthService {
/// Resets the serving status of a service or inserts a new service status.
pub fn set_serving_status(&self, service: &str, status: ServingStatus) {
let cast = {
let mut inner = self.inner.lock().unwrap();
if inner.shutdown {
info!("health: status changing for {} to {:?} is ignored because health service is shutdown", service, status);
return;
}
if let Some(val) = inner.status.get_mut(service) {
*val = status;
} else {
inner.status.insert(service.to_string(), status);
}
if let Some(cast) = inner.casts.get(service) {
cast.clone()
} else {
return;
}
};
cast.broadcast(status);
}
/// Sets all serving status to NotServing, and configures the server to
/// ignore all future status changes.
///
/// This changes serving status for all services.
pub fn shutdown(&self) {
let mut inner = self.inner.lock().unwrap();
inner.shutdown = true;
for val in inner.status.values_mut() {
*val = ServingStatus::NotServing;
}
for cast in inner.casts.values() {
cast.broadcast(ServingStatus::NotServing);
}
}
}
#[allow(clippy::useless_conversion)]
fn build_response(status: ServingStatus) -> HealthCheckResponse {
HealthCheckResponse {
status: status.into(),
..Default::default()
}
}
impl Health for HealthService {
fn
|
(
&mut self,
ctx: RpcContext,
req: HealthCheckRequest,
sink: UnarySink<HealthCheckResponse>,
) {
let status = {
let inner = self.inner.lock().unwrap();
inner.status.get(&req.service).cloned()
};
if let Some(status) = status {
let resp = build_response(status);
ctx.spawn(sink.success(resp).map(|_| ()));
return;
}
ctx.spawn(
sink.fail(RpcStatus::with_message(
RpcStatusCode::NOT_FOUND,
"unknown service".to_owned(),
))
.map(|_| ()),
)
}
fn watch(
&mut self,
ctx: RpcContext,
req: HealthCheckRequest,
mut sink: ServerStreamingSink<HealthCheckResponse>,
) {
let name = req.service;
let (id, v) = {
let mut inner = self.inner.lock().unwrap();
inner.id += 1;
if let Some(c) = inner.casts.get(&name) {
(inner.id, c.clone())
} else {
let status = match inner.status.get(&name) {
Some(s) => *s,
None => ServingStatus::ServiceUnknown,
};
let c = Arc::new(StatusCast::new(status));
inner.casts.insert(name.clone(), c.clone());
(inner.id, c)
}
};
let sub = StatusSubscriber::new(id, v);
let inner = self.inner.clone();
ctx.spawn(async move {
let _ = sink
.send_all(&mut sub.map(|s| Ok((build_response(s), WriteFlags::default()))))
.await;
let mut inner = inner.lock().unwrap();
if let Some(c) = inner.casts.get(&name) {
// If there is any subscriber, then cast reference count should not be 1 as
// it's referenced by all subscriber.
if Arc::strong_count(c) == 1 {
inner.casts.remove(&name);
}
}
})
}
}
|
check
|
identifier_name
|
percentage.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/. */
//! Computed percentages.
use std::fmt;
use style_traits::{CssWriter, ToCss};
use values::{serialize_percentage, CSSFloat};
use values::animated::ToAnimatedValue;
use values::generics::NonNegative;
/// A computed percentage.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
Default,
MallocSizeOf,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
)]
#[repr(C)]
pub struct Percentage(pub CSSFloat);
impl Percentage {
/// 0%
#[inline]
pub fn zero() -> Self {
Percentage(0.)
}
/// 100%
#[inline]
pub fn hundred() -> Self {
Percentage(1.)
}
/// Returns the absolute value for this percentage.
#[inline]
pub fn abs(&self) -> Self {
Percentage(self.0.abs())
}
/// Clamps this percentage to a non-negative percentage.
#[inline]
pub fn clamp_to_non_negative(self) -> Self {
Percentage(self.0.max(0.))
}
}
impl ToCss for Percentage {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
|
/// A wrapper over a `Percentage`, whose value should be clamped to 0.
pub type NonNegativePercentage = NonNegative<Percentage>;
impl NonNegativePercentage {
/// 0%
#[inline]
pub fn zero() -> Self {
NonNegative(Percentage::zero())
}
/// 100%
#[inline]
pub fn hundred() -> Self {
NonNegative(Percentage::hundred())
}
}
impl ToAnimatedValue for NonNegativePercentage {
type AnimatedValue = Percentage;
#[inline]
fn to_animated_value(self) -> Self::AnimatedValue {
self.0
}
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
NonNegative(animated.clamp_to_non_negative())
}
}
|
W: fmt::Write,
{
serialize_percentage(self.0, dest)
}
}
|
random_line_split
|
percentage.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/. */
//! Computed percentages.
use std::fmt;
use style_traits::{CssWriter, ToCss};
use values::{serialize_percentage, CSSFloat};
use values::animated::ToAnimatedValue;
use values::generics::NonNegative;
/// A computed percentage.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
Default,
MallocSizeOf,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
)]
#[repr(C)]
pub struct Percentage(pub CSSFloat);
impl Percentage {
/// 0%
#[inline]
pub fn zero() -> Self {
Percentage(0.)
}
/// 100%
#[inline]
pub fn
|
() -> Self {
Percentage(1.)
}
/// Returns the absolute value for this percentage.
#[inline]
pub fn abs(&self) -> Self {
Percentage(self.0.abs())
}
/// Clamps this percentage to a non-negative percentage.
#[inline]
pub fn clamp_to_non_negative(self) -> Self {
Percentage(self.0.max(0.))
}
}
impl ToCss for Percentage {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
serialize_percentage(self.0, dest)
}
}
/// A wrapper over a `Percentage`, whose value should be clamped to 0.
pub type NonNegativePercentage = NonNegative<Percentage>;
impl NonNegativePercentage {
/// 0%
#[inline]
pub fn zero() -> Self {
NonNegative(Percentage::zero())
}
/// 100%
#[inline]
pub fn hundred() -> Self {
NonNegative(Percentage::hundred())
}
}
impl ToAnimatedValue for NonNegativePercentage {
type AnimatedValue = Percentage;
#[inline]
fn to_animated_value(self) -> Self::AnimatedValue {
self.0
}
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
NonNegative(animated.clamp_to_non_negative())
}
}
|
hundred
|
identifier_name
|
percentage.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/. */
//! Computed percentages.
use std::fmt;
use style_traits::{CssWriter, ToCss};
use values::{serialize_percentage, CSSFloat};
use values::animated::ToAnimatedValue;
use values::generics::NonNegative;
/// A computed percentage.
#[cfg_attr(feature = "servo", derive(Deserialize, Serialize))]
#[derive(
Animate,
Clone,
ComputeSquaredDistance,
Copy,
Debug,
Default,
MallocSizeOf,
PartialEq,
PartialOrd,
SpecifiedValueInfo,
ToAnimatedValue,
ToAnimatedZero,
ToComputedValue,
)]
#[repr(C)]
pub struct Percentage(pub CSSFloat);
impl Percentage {
/// 0%
#[inline]
pub fn zero() -> Self {
Percentage(0.)
}
/// 100%
#[inline]
pub fn hundred() -> Self {
Percentage(1.)
}
/// Returns the absolute value for this percentage.
#[inline]
pub fn abs(&self) -> Self {
Percentage(self.0.abs())
}
/// Clamps this percentage to a non-negative percentage.
#[inline]
pub fn clamp_to_non_negative(self) -> Self {
Percentage(self.0.max(0.))
}
}
impl ToCss for Percentage {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: fmt::Write,
{
serialize_percentage(self.0, dest)
}
}
/// A wrapper over a `Percentage`, whose value should be clamped to 0.
pub type NonNegativePercentage = NonNegative<Percentage>;
impl NonNegativePercentage {
/// 0%
#[inline]
pub fn zero() -> Self {
NonNegative(Percentage::zero())
}
/// 100%
#[inline]
pub fn hundred() -> Self {
NonNegative(Percentage::hundred())
}
}
impl ToAnimatedValue for NonNegativePercentage {
type AnimatedValue = Percentage;
#[inline]
fn to_animated_value(self) -> Self::AnimatedValue
|
#[inline]
fn from_animated_value(animated: Self::AnimatedValue) -> Self {
NonNegative(animated.clamp_to_non_negative())
}
}
|
{
self.0
}
|
identifier_body
|
single_threaded.rs
|
#![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;
extern crate tokio;
use std::cell::Cell;
use std::rc::Rc;
use hyper::{Body, Response, Server};
use hyper::service::service_fn_ok;
use hyper::rt::Future;
use tokio::runtime::current_thread;
fn main()
|
// to configure an Executor that can spawn!Send futures...
let exec = current_thread::TaskExecutor::current();
let server = Server::bind(&addr)
.executor(exec)
.serve(new_service)
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
current_thread::Runtime::new()
.expect("rt new")
.spawn(server)
.run()
.expect("rt run");
}
|
{
pretty_env_logger::init();
let addr = ([127, 0, 0, 1], 3000).into();
// Using a !Send request counter is fine on 1 thread...
let counter = Rc::new(Cell::new(0));
let new_service = move || {
// For each connection, clone the counter to use in our service...
let cnt = counter.clone();
service_fn_ok(move |_| {
let prev = cnt.get();
cnt.set(prev + 1);
Response::new(Body::from(format!("Request count: {}", prev + 1)))
})
};
// Since the Server needs to spawn some background tasks, we needed
|
identifier_body
|
single_threaded.rs
|
#![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;
extern crate tokio;
use std::cell::Cell;
use std::rc::Rc;
use hyper::{Body, Response, Server};
use hyper::service::service_fn_ok;
use hyper::rt::Future;
use tokio::runtime::current_thread;
fn
|
() {
pretty_env_logger::init();
let addr = ([127, 0, 0, 1], 3000).into();
// Using a!Send request counter is fine on 1 thread...
let counter = Rc::new(Cell::new(0));
let new_service = move || {
// For each connection, clone the counter to use in our service...
let cnt = counter.clone();
service_fn_ok(move |_| {
let prev = cnt.get();
cnt.set(prev + 1);
Response::new(Body::from(format!("Request count: {}", prev + 1)))
})
};
// Since the Server needs to spawn some background tasks, we needed
// to configure an Executor that can spawn!Send futures...
let exec = current_thread::TaskExecutor::current();
let server = Server::bind(&addr)
.executor(exec)
.serve(new_service)
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
current_thread::Runtime::new()
.expect("rt new")
.spawn(server)
.run()
.expect("rt run");
}
|
main
|
identifier_name
|
single_threaded.rs
|
#![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;
extern crate tokio;
use std::cell::Cell;
use std::rc::Rc;
use hyper::{Body, Response, Server};
use hyper::service::service_fn_ok;
use hyper::rt::Future;
use tokio::runtime::current_thread;
fn main() {
pretty_env_logger::init();
let addr = ([127, 0, 0, 1], 3000).into();
// Using a!Send request counter is fine on 1 thread...
let counter = Rc::new(Cell::new(0));
let new_service = move || {
// For each connection, clone the counter to use in our service...
let cnt = counter.clone();
service_fn_ok(move |_| {
let prev = cnt.get();
cnt.set(prev + 1);
Response::new(Body::from(format!("Request count: {}", prev + 1)))
})
};
// Since the Server needs to spawn some background tasks, we needed
// to configure an Executor that can spawn!Send futures...
|
let exec = current_thread::TaskExecutor::current();
let server = Server::bind(&addr)
.executor(exec)
.serve(new_service)
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
current_thread::Runtime::new()
.expect("rt new")
.spawn(server)
.run()
.expect("rt run");
}
|
random_line_split
|
|
mod.rs
|
use crate::resource::IResource;
use com_wrapper::ComWrapper;
use winapi::um::d2d1::{ID2D1Image, ID2D1Resource};
use wio::com::ComPtr;
pub use self::bitmap::{Bitmap, IBitmap};
pub use self::bitmap1::{Bitmap1, IBitmap1};
pub mod bitmap;
pub mod bitmap1;
#[repr(transparent)]
#[derive(ComWrapper)]
#[com(send, sync, debug)]
pub struct
|
{
ptr: ComPtr<ID2D1Image>,
}
pub unsafe trait IImage: IResource {
unsafe fn raw_img(&self) -> &ID2D1Image;
}
unsafe impl IResource for Image {
unsafe fn raw_resource(&self) -> &ID2D1Resource {
&self.ptr
}
}
unsafe impl IImage for Image {
unsafe fn raw_img(&self) -> &ID2D1Image {
&self.ptr
}
}
|
Image
|
identifier_name
|
mod.rs
|
use crate::resource::IResource;
use com_wrapper::ComWrapper;
use winapi::um::d2d1::{ID2D1Image, ID2D1Resource};
use wio::com::ComPtr;
pub use self::bitmap::{Bitmap, IBitmap};
pub use self::bitmap1::{Bitmap1, IBitmap1};
pub mod bitmap;
pub mod bitmap1;
#[repr(transparent)]
#[derive(ComWrapper)]
#[com(send, sync, debug)]
pub struct Image {
ptr: ComPtr<ID2D1Image>,
}
pub unsafe trait IImage: IResource {
unsafe fn raw_img(&self) -> &ID2D1Image;
}
unsafe impl IResource for Image {
unsafe fn raw_resource(&self) -> &ID2D1Resource {
&self.ptr
}
}
unsafe impl IImage for Image {
|
unsafe fn raw_img(&self) -> &ID2D1Image {
&self.ptr
}
}
|
random_line_split
|
|
oop.rs
|
/// Ordinary object pointers and memory layouts.
/// (I did try to come up with a better name but failed.)
use super::gc::INFO_FRESH_TAG;
use super::stackmap::OopStackMapOffsets;
use ast::id::Id;
use std::slice;
use std::ptr;
use std::ops::{Deref, DerefMut};
use std::marker::PhantomData;
use std::mem::{size_of, transmute, replace};
use std::fmt::{self, Formatter, Debug};
use std::cell::UnsafeCell;
pub type Oop = usize;
pub const NULL_OOP: Oop = 0;
// Tagging: currently only booleans are tagged.
pub const OOP_TAG_SHIFT: u8 = 3;
pub const OOP_TAG_MASK: usize = (1 << OOP_TAG_SHIFT) - 1;
#[repr(u8)]
pub enum OopTag {
Fixnum = 0x1,
Singleton = 0x2,
}
pub fn sizeof_ptrs(nptrs: usize) -> usize {
nptrs * 8
}
#[repr(u16)]
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum OopKind {
Plain,
Callable,
OopArray,
I64Array,
}
impl OopKind {
pub fn is_array(self) -> bool {
self == OopKind::OopArray || self == OopKind::I64Array
}
pub fn is_closure(self) -> bool {
self == OopKind::Callable
}
}
#[repr(C)]
pub struct InfoTable<A> {
// XXX: Using Option<Box<T>> safely with mem::zeroed relies on that
// Rust internally treats None<Box<T>> as nullptr.
gcrefs: Option<Box<[GcRef]>>,
smo: Option<Box<OopStackMapOffsets>>,
name: Option<Box<String>>,
gc_mark_word: UnsafeCell<usize>,
arity: u16,
kind: OopKind,
ptr_payloads: u16, // GC ptrs
word_payloads: u16, // Unmanaged qwords
entry: [u8; 0],
phantom_data: PhantomData<A>,
}
pub const INFOTABLE_ARITY_OFFSET: isize = -8;
pub const INFOTABLE_KIND_OFFSET: isize = -6;
impl<A> Debug for InfoTable<A> {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
write!(fmt, "<InfoTable {}>", self.name())
}
}
impl<A> InfoTable<A> {
pub fn size_of() -> usize {
size_of::<Self>()
}
pub fn replace(&mut self, o: Self)
|
pub fn new(ptr_payloads: u16,
word_payloads: u16,
arity: u16,
kind: OopKind,
name: &str)
-> Self {
InfoTable {
ptr_payloads: ptr_payloads,
word_payloads: word_payloads,
arity: arity,
gc_mark_word: UnsafeCell::new(INFO_FRESH_TAG),
kind: kind,
name: Some(Box::new( name.to_owned())),
gcrefs: Default::default(),
smo: Default::default(),
entry: [],
phantom_data: PhantomData,
}
}
pub fn sizeof_instance(&self) -> usize {
assert!(!self.is_array());
sizeof_ptrs(self.ptr_payloads as usize + self.word_payloads as usize + 1)
}
pub fn sizeof_array_instance(&self, size: usize) -> usize {
assert!(self.is_array());
sizeof_ptrs(size + 2)
}
pub fn is_array(&self) -> bool {
self.kind.is_array()
}
pub fn is_ooparray(&self) -> bool {
self.kind == OopKind::OopArray
}
pub fn is_closure(&self) -> bool {
self.kind.is_closure()
}
pub fn set_gcrefs(&mut self, v: Vec<GcRef>) {
self.gcrefs = Some(v.into_boxed_slice());
}
pub unsafe fn gcrefs(&self) -> Option<&[GcRef]> {
self.gcrefs.as_ref().map(|rb| &**rb)
}
pub fn set_smo(&mut self, smo: OopStackMapOffsets) {
self.smo = Some(Box::new( smo));
}
pub fn gc_mark_word(&self) -> &mut usize {
unsafe { &mut *self.gc_mark_word.get() }
}
pub fn name(&self) -> &str {
&*self.name.as_ref().unwrap()
}
pub unsafe fn from_entry<'a>(entry: usize) -> &'a mut Self {
&mut *((entry - size_of::<Self>()) as *mut _)
}
pub fn entry_word(&self) -> usize {
self.entry.as_ptr() as usize
}
}
fn mk_infotable_for_data<A>(nptrs: u16, nwords: u16, name: &str, kind: OopKind) -> InfoTable<A> {
InfoTable::new(nptrs, nwords, 0, kind, name)
}
pub fn infotable_for_pair() -> InfoTable<Pair> {
mk_infotable_for_data(2, 0, "<Pair>", OopKind::Plain)
}
pub fn infotable_for_box() -> InfoTable<MutBox> {
mk_infotable_for_data(1, 0, "<Box>", OopKind::Plain)
}
pub fn infotable_for_fixnum() -> InfoTable<Fixnum> {
mk_infotable_for_data(0, 1, "<Fixnum>", OopKind::Plain)
}
pub fn infotable_for_symbol() -> InfoTable<Symbol> {
mk_infotable_for_data(0, 1, "<Symbol>", OopKind::Plain)
}
pub fn infotable_for_ooparray() -> InfoTable<OopArray> {
mk_infotable_for_data(0, 0, "<OopArray>", OopKind::OopArray)
}
pub fn infotable_for_i64array() -> InfoTable<I64Array> {
mk_infotable_for_data(0, 0, "<I64Array>", OopKind::I64Array)
}
// Encodes different kinds of Oops that a InfoTable might points to.
#[derive(Copy, Clone, Debug)]
pub enum GcRef {
// *(entry + u32) contains a ptr-sized, i.e. u64, Oop.
OopConst(u32),
// *(entry + u32) contains an i32 PC-relative offset to another
// InfoTable's entry.
PcRelInfoEntry(u32),
}
/// A Closure is not exactly an ordinary callable object in the narrow sense -
/// it's a generic heap object, with a info table and some payloads (fields).
/// Yes, we are using Haskell's nomenclature here.
#[repr(C)]
pub struct Closure {
// *info points directly to the entry field in the InfoTable.
// See Haskell's `tables-next-to-code` trick.
info: *const (),
payloads: [Oop; 0],
}
impl Closure {
pub unsafe fn info_is<A>(&self, info: &InfoTable<A>) -> bool {
*self.entry_word() == info.entry_word()
}
pub unsafe fn info(&self) -> &InfoTable<Self> {
InfoTable::<Self>::from_entry(*self.entry_word())
}
pub unsafe fn info_mut(&mut self) -> &mut InfoTable<Self> {
InfoTable::<Self>::from_entry(*self.entry_word())
}
pub unsafe fn entry_word(&self) -> &mut usize {
&mut *(&self.info as *const _ as *mut _)
}
pub unsafe fn payload_start(&self) -> usize {
self.payloads.as_ptr() as usize
}
pub unsafe fn ptr_payloads(&self) -> &mut [Oop] {
let base = self.payload_start() as *mut _;
let len = self.info().ptr_payloads as usize;
slice::from_raw_parts_mut(base, len)
}
pub unsafe fn word_payloads(&self) -> &mut [usize] {
let base = self.payload_start() + sizeof_ptrs(self.info().ptr_payloads as usize);
let len = self.info().word_payloads as usize;
slice::from_raw_parts_mut(base as *mut _, len)
}
pub unsafe fn as_word(&self) -> usize {
transmute(self)
}
}
pub type ClosureInfo = InfoTable<Closure>;
#[repr(C)]
pub struct Fixnum {
info: *const (),
value: isize,
}
impl Fixnum {
pub fn set_value(&mut self, v: isize) {
self.value = v
}
pub fn value(&self) -> isize {
self.value
}
}
#[repr(C)]
pub struct Pair {
info: *const (),
pub car: Oop,
pub cdr: Oop,
}
#[repr(C)]
pub struct Symbol {
info: *const (),
id: Id,
}
impl Symbol {
pub fn as_str(&self) -> &str {
self.id.as_str()
}
pub fn set_value(&mut self, id: Id) {
self.id = id;
}
}
#[repr(C)]
pub struct MutBox {
info: *const (),
value: Oop,
}
impl MutBox {
pub fn set_value(&mut self, v: Oop) {
self.value = v
}
pub fn value(&self) -> Oop {
self.value
}
}
#[derive(Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum Singleton {
False = 0,
True = 1,
Nil = 2,
}
impl Singleton {
pub fn as_oop(self) -> Oop {
((self as usize) << OOP_TAG_SHIFT) + (OopTag::Singleton as usize)
}
pub fn from_oop(oop: Oop) -> Option<Self> {
Some(match oop >> OOP_TAG_SHIFT {
0 => Singleton::False,
1 => Singleton::True,
2 => Singleton::Nil,
_ => return None,
})
}
pub fn is_singleton(oop: Oop) -> bool {
oop & OOP_TAG_MASK == (OopTag::Singleton as usize)
}
pub fn is_nil(oop: Oop) -> bool {
oop == Singleton::Nil.as_oop()
}
}
// Assumes arrays have the same layout: [info, len, content...]
pub trait IsArray<A: Sized> : Sized {
unsafe fn len(&self) -> usize {
*transmute::<usize, *const usize>(self as *const _ as usize + 8)
}
unsafe fn content(&self) -> &mut [A] {
let content_ptr = self as *const _ as usize + 16;
slice::from_raw_parts_mut(content_ptr as *mut _, self.len())
}
}
#[repr(C)]
pub struct OopArray {
info: *const (),
pub len: usize,
pub content: [Oop; 0],
}
impl IsArray<Oop> for OopArray {}
#[repr(C)]
pub struct I64Array {
info: *const (),
pub len: usize,
pub content: [i64; 0],
}
impl IsArray<i64> for I64Array {}
// Doubly-linked list of oops. Used to manage root of stacks.
pub struct RawHandle<A> {
oop: Oop,
prev: *mut OopHandle,
next: *mut OopHandle,
phantom_data: PhantomData<A>,
}
pub type OopHandle = RawHandle<Oop>;
pub type Handle<A> = Box<RawHandle<A>>;
pub struct HandleBlock(OopHandle);
// Just a marker.
pub trait IsOop : Sized {
unsafe fn as_oop(&self) -> Oop {
transmute(self)
}
unsafe fn oop_cast<A: IsOop>(&self) -> &A {
transmute(self)
}
unsafe fn from_raw<'a>(oop: Oop) -> &'a mut Self {
&mut *transmute::<Oop, *mut Self>(oop)
}
}
impl IsOop for Closure {}
impl IsOop for Fixnum {}
impl IsOop for Symbol {}
impl IsOop for Pair {}
impl IsOop for MutBox {}
impl IsOop for OopArray {}
impl IsOop for I64Array {}
impl HandleBlock {
pub fn new() -> Box<HandleBlock> {
let mut thiz = Box::new(HandleBlock(RawHandle {
oop: NULL_OOP,
prev: ptr::null_mut(),
next: ptr::null_mut(),
phantom_data: PhantomData,
}));
(*thiz).0.prev = (*thiz).0.as_ptr();
(*thiz).0.next = (*thiz).0.as_ptr();
thiz
}
pub fn head(&self) -> &OopHandle {
&(*self).0
}
pub fn len(&self) -> usize {
unsafe {
let mut res = 0;
self.head().foreach_oop(|_| res += 1);
res
}
}
pub fn new_handle<A: IsOop>(&self, a: *mut A) -> Box<RawHandle<A>> {
unsafe { RawHandle::new(a, self.head()) }
}
pub fn new_ref_handle<A: IsOop>(&self, a: &A) -> Box<RawHandle<A>> {
unsafe { RawHandle::new_ref(a, &self.0) }
}
}
impl<A> RawHandle<A> {
pub unsafe fn oop(&self) -> &mut Oop {
&mut *(&self.oop as *const _ as *mut _)
}
unsafe fn same_ptr(&self, rhs: &OopHandle) -> bool {
self.as_ptr() == rhs.as_ptr()
}
pub unsafe fn foreach_oop<F: FnMut(&mut Oop)>(&self, mut f: F) {
let mut curr = self.next();
loop {
if self.same_ptr(curr) {
break;
}
let next = curr.next();
f(curr.oop());
curr = next;
}
}
unsafe fn next<'a, 'b>(&'a self) -> &'b mut OopHandle {
&mut *self.next
}
#[allow(unused)]
unsafe fn set_next(&self, next: *mut OopHandle) {
(&mut *(self as *const _ as *mut Self)).next = next;
}
unsafe fn prev(&self) -> &mut OopHandle {
&mut *self.prev
}
unsafe fn set_prev(&self, prev: *mut OopHandle) {
(&mut *(self as *const _ as *mut Self)).prev = prev;
}
pub fn as_ptr(&self) -> *mut OopHandle {
self as *const _ as *const _ as *mut _
}
unsafe fn new(oop: *mut A, head: &OopHandle) -> Box<Self> {
let thiz = Box::new(RawHandle {
oop: oop as Oop,
prev: head.prev,
next: head.as_ptr(),
phantom_data: PhantomData,
});
head.prev().next = RawHandle::<A>::as_ptr(&*thiz);
(*head).set_prev(thiz.as_ptr());
thiz
}
unsafe fn new_ref(oop_ref: &A, head: &OopHandle) -> Box<Self> {
RawHandle::new(oop_ref as *const _ as *mut A, head)
}
pub unsafe fn dup(&self) -> Box<Self> {
RawHandle::<A>::new(*self.oop() as *mut _, &*self.as_ptr())
}
}
impl<A> Drop for RawHandle<A> {
fn drop(&mut self) {
unsafe {
self.next().prev = self.prev().as_ptr();
self.prev().next = self.next().as_ptr();
}
}
}
impl<A> Deref for RawHandle<A> {
type Target = A;
fn deref(&self) -> &A {
unsafe { &*(self.oop as *const A) }
}
}
impl<A> DerefMut for RawHandle<A> {
fn deref_mut(&mut self) -> &mut A {
unsafe { &mut *(self.oop as *mut A) }
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem;
#[test]
fn test_handle() {
unsafe {
let block = HandleBlock::new();
{
let mut oop = mem::zeroed::<Fixnum>();
oop.value = 42;
let foo1 = block.new_ref_handle(&oop);
let _foo2 = block.new_ref_handle(&oop);
let _foo3 = block.new_ref_handle(&oop);
assert_eq!(&oop as *const _ as Oop, *foo1.oop());
assert_eq!(oop.value, foo1.value);
assert_eq!(3, block.len());
}
assert_eq!(0, block.len());
}
}
#[test]
fn test_info_offsets() {
unsafe {
let info = infotable_for_pair();
let entry = info.entry_word();
assert_eq!(InfoTable::<Pair>::from_entry(entry).entry_word(), entry);
}
}
}
|
{
replace(self, o);
}
|
identifier_body
|
oop.rs
|
/// Ordinary object pointers and memory layouts.
/// (I did try to come up with a better name but failed.)
use super::gc::INFO_FRESH_TAG;
use super::stackmap::OopStackMapOffsets;
use ast::id::Id;
use std::slice;
use std::ptr;
use std::ops::{Deref, DerefMut};
use std::marker::PhantomData;
use std::mem::{size_of, transmute, replace};
use std::fmt::{self, Formatter, Debug};
use std::cell::UnsafeCell;
pub type Oop = usize;
pub const NULL_OOP: Oop = 0;
// Tagging: currently only booleans are tagged.
pub const OOP_TAG_SHIFT: u8 = 3;
pub const OOP_TAG_MASK: usize = (1 << OOP_TAG_SHIFT) - 1;
#[repr(u8)]
pub enum OopTag {
Fixnum = 0x1,
Singleton = 0x2,
}
pub fn sizeof_ptrs(nptrs: usize) -> usize {
nptrs * 8
}
#[repr(u16)]
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum OopKind {
Plain,
Callable,
OopArray,
I64Array,
}
impl OopKind {
pub fn is_array(self) -> bool {
self == OopKind::OopArray || self == OopKind::I64Array
}
pub fn is_closure(self) -> bool {
self == OopKind::Callable
}
}
#[repr(C)]
pub struct InfoTable<A> {
// XXX: Using Option<Box<T>> safely with mem::zeroed relies on that
// Rust internally treats None<Box<T>> as nullptr.
gcrefs: Option<Box<[GcRef]>>,
smo: Option<Box<OopStackMapOffsets>>,
name: Option<Box<String>>,
gc_mark_word: UnsafeCell<usize>,
arity: u16,
kind: OopKind,
ptr_payloads: u16, // GC ptrs
word_payloads: u16, // Unmanaged qwords
entry: [u8; 0],
phantom_data: PhantomData<A>,
}
pub const INFOTABLE_ARITY_OFFSET: isize = -8;
pub const INFOTABLE_KIND_OFFSET: isize = -6;
impl<A> Debug for InfoTable<A> {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
write!(fmt, "<InfoTable {}>", self.name())
}
}
impl<A> InfoTable<A> {
pub fn size_of() -> usize {
size_of::<Self>()
}
pub fn replace(&mut self, o: Self) {
replace(self, o);
}
pub fn new(ptr_payloads: u16,
word_payloads: u16,
arity: u16,
kind: OopKind,
name: &str)
-> Self {
InfoTable {
ptr_payloads: ptr_payloads,
word_payloads: word_payloads,
arity: arity,
gc_mark_word: UnsafeCell::new(INFO_FRESH_TAG),
kind: kind,
name: Some(Box::new( name.to_owned())),
gcrefs: Default::default(),
smo: Default::default(),
entry: [],
phantom_data: PhantomData,
}
}
pub fn sizeof_instance(&self) -> usize {
assert!(!self.is_array());
sizeof_ptrs(self.ptr_payloads as usize + self.word_payloads as usize + 1)
}
pub fn sizeof_array_instance(&self, size: usize) -> usize {
assert!(self.is_array());
sizeof_ptrs(size + 2)
}
pub fn is_array(&self) -> bool {
self.kind.is_array()
}
pub fn is_ooparray(&self) -> bool {
self.kind == OopKind::OopArray
}
pub fn is_closure(&self) -> bool {
self.kind.is_closure()
}
pub fn set_gcrefs(&mut self, v: Vec<GcRef>) {
self.gcrefs = Some(v.into_boxed_slice());
}
pub unsafe fn gcrefs(&self) -> Option<&[GcRef]> {
self.gcrefs.as_ref().map(|rb| &**rb)
}
pub fn set_smo(&mut self, smo: OopStackMapOffsets) {
self.smo = Some(Box::new( smo));
}
pub fn gc_mark_word(&self) -> &mut usize {
unsafe { &mut *self.gc_mark_word.get() }
}
pub fn name(&self) -> &str {
&*self.name.as_ref().unwrap()
}
pub unsafe fn from_entry<'a>(entry: usize) -> &'a mut Self {
&mut *((entry - size_of::<Self>()) as *mut _)
}
pub fn entry_word(&self) -> usize {
self.entry.as_ptr() as usize
}
}
fn mk_infotable_for_data<A>(nptrs: u16, nwords: u16, name: &str, kind: OopKind) -> InfoTable<A> {
InfoTable::new(nptrs, nwords, 0, kind, name)
}
pub fn infotable_for_pair() -> InfoTable<Pair> {
mk_infotable_for_data(2, 0, "<Pair>", OopKind::Plain)
}
pub fn infotable_for_box() -> InfoTable<MutBox> {
mk_infotable_for_data(1, 0, "<Box>", OopKind::Plain)
}
pub fn infotable_for_fixnum() -> InfoTable<Fixnum> {
mk_infotable_for_data(0, 1, "<Fixnum>", OopKind::Plain)
}
pub fn infotable_for_symbol() -> InfoTable<Symbol> {
mk_infotable_for_data(0, 1, "<Symbol>", OopKind::Plain)
}
pub fn infotable_for_ooparray() -> InfoTable<OopArray> {
mk_infotable_for_data(0, 0, "<OopArray>", OopKind::OopArray)
}
pub fn infotable_for_i64array() -> InfoTable<I64Array> {
mk_infotable_for_data(0, 0, "<I64Array>", OopKind::I64Array)
}
// Encodes different kinds of Oops that a InfoTable might points to.
#[derive(Copy, Clone, Debug)]
pub enum GcRef {
// *(entry + u32) contains a ptr-sized, i.e. u64, Oop.
OopConst(u32),
// *(entry + u32) contains an i32 PC-relative offset to another
// InfoTable's entry.
PcRelInfoEntry(u32),
}
/// A Closure is not exactly an ordinary callable object in the narrow sense -
/// it's a generic heap object, with a info table and some payloads (fields).
/// Yes, we are using Haskell's nomenclature here.
#[repr(C)]
pub struct Closure {
// *info points directly to the entry field in the InfoTable.
// See Haskell's `tables-next-to-code` trick.
info: *const (),
payloads: [Oop; 0],
}
impl Closure {
pub unsafe fn info_is<A>(&self, info: &InfoTable<A>) -> bool {
*self.entry_word() == info.entry_word()
}
pub unsafe fn info(&self) -> &InfoTable<Self> {
InfoTable::<Self>::from_entry(*self.entry_word())
}
pub unsafe fn info_mut(&mut self) -> &mut InfoTable<Self> {
InfoTable::<Self>::from_entry(*self.entry_word())
}
pub unsafe fn entry_word(&self) -> &mut usize {
&mut *(&self.info as *const _ as *mut _)
}
pub unsafe fn payload_start(&self) -> usize {
self.payloads.as_ptr() as usize
}
pub unsafe fn ptr_payloads(&self) -> &mut [Oop] {
let base = self.payload_start() as *mut _;
let len = self.info().ptr_payloads as usize;
slice::from_raw_parts_mut(base, len)
}
pub unsafe fn word_payloads(&self) -> &mut [usize] {
let base = self.payload_start() + sizeof_ptrs(self.info().ptr_payloads as usize);
let len = self.info().word_payloads as usize;
slice::from_raw_parts_mut(base as *mut _, len)
}
pub unsafe fn as_word(&self) -> usize {
transmute(self)
}
}
pub type ClosureInfo = InfoTable<Closure>;
#[repr(C)]
pub struct Fixnum {
info: *const (),
value: isize,
}
impl Fixnum {
pub fn set_value(&mut self, v: isize) {
self.value = v
}
pub fn value(&self) -> isize {
self.value
}
}
#[repr(C)]
pub struct Pair {
info: *const (),
pub car: Oop,
pub cdr: Oop,
}
#[repr(C)]
pub struct Symbol {
info: *const (),
id: Id,
}
impl Symbol {
pub fn as_str(&self) -> &str {
self.id.as_str()
}
pub fn set_value(&mut self, id: Id) {
self.id = id;
}
}
#[repr(C)]
pub struct MutBox {
info: *const (),
value: Oop,
}
impl MutBox {
pub fn set_value(&mut self, v: Oop) {
self.value = v
}
pub fn value(&self) -> Oop {
self.value
}
}
#[derive(Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum Singleton {
False = 0,
True = 1,
Nil = 2,
}
impl Singleton {
pub fn as_oop(self) -> Oop {
((self as usize) << OOP_TAG_SHIFT) + (OopTag::Singleton as usize)
}
pub fn from_oop(oop: Oop) -> Option<Self> {
Some(match oop >> OOP_TAG_SHIFT {
0 => Singleton::False,
1 => Singleton::True,
2 => Singleton::Nil,
_ => return None,
})
}
pub fn is_singleton(oop: Oop) -> bool {
oop & OOP_TAG_MASK == (OopTag::Singleton as usize)
}
pub fn is_nil(oop: Oop) -> bool {
oop == Singleton::Nil.as_oop()
}
}
// Assumes arrays have the same layout: [info, len, content...]
pub trait IsArray<A: Sized> : Sized {
unsafe fn len(&self) -> usize {
*transmute::<usize, *const usize>(self as *const _ as usize + 8)
}
unsafe fn content(&self) -> &mut [A] {
let content_ptr = self as *const _ as usize + 16;
slice::from_raw_parts_mut(content_ptr as *mut _, self.len())
}
}
#[repr(C)]
pub struct OopArray {
info: *const (),
pub len: usize,
pub content: [Oop; 0],
}
impl IsArray<Oop> for OopArray {}
#[repr(C)]
pub struct I64Array {
info: *const (),
pub len: usize,
pub content: [i64; 0],
}
impl IsArray<i64> for I64Array {}
// Doubly-linked list of oops. Used to manage root of stacks.
pub struct RawHandle<A> {
oop: Oop,
prev: *mut OopHandle,
next: *mut OopHandle,
phantom_data: PhantomData<A>,
}
pub type OopHandle = RawHandle<Oop>;
pub type Handle<A> = Box<RawHandle<A>>;
pub struct HandleBlock(OopHandle);
// Just a marker.
pub trait IsOop : Sized {
unsafe fn as_oop(&self) -> Oop {
transmute(self)
}
unsafe fn oop_cast<A: IsOop>(&self) -> &A {
transmute(self)
}
unsafe fn from_raw<'a>(oop: Oop) -> &'a mut Self {
&mut *transmute::<Oop, *mut Self>(oop)
}
}
impl IsOop for Closure {}
impl IsOop for Fixnum {}
impl IsOop for Symbol {}
impl IsOop for Pair {}
impl IsOop for MutBox {}
impl IsOop for OopArray {}
impl IsOop for I64Array {}
impl HandleBlock {
pub fn new() -> Box<HandleBlock> {
let mut thiz = Box::new(HandleBlock(RawHandle {
oop: NULL_OOP,
prev: ptr::null_mut(),
next: ptr::null_mut(),
phantom_data: PhantomData,
}));
(*thiz).0.prev = (*thiz).0.as_ptr();
(*thiz).0.next = (*thiz).0.as_ptr();
thiz
}
pub fn head(&self) -> &OopHandle {
&(*self).0
}
pub fn len(&self) -> usize {
unsafe {
let mut res = 0;
self.head().foreach_oop(|_| res += 1);
res
}
}
pub fn new_handle<A: IsOop>(&self, a: *mut A) -> Box<RawHandle<A>> {
unsafe { RawHandle::new(a, self.head()) }
}
pub fn new_ref_handle<A: IsOop>(&self, a: &A) -> Box<RawHandle<A>> {
unsafe { RawHandle::new_ref(a, &self.0) }
}
}
impl<A> RawHandle<A> {
pub unsafe fn oop(&self) -> &mut Oop {
&mut *(&self.oop as *const _ as *mut _)
}
unsafe fn same_ptr(&self, rhs: &OopHandle) -> bool {
self.as_ptr() == rhs.as_ptr()
}
pub unsafe fn foreach_oop<F: FnMut(&mut Oop)>(&self, mut f: F) {
let mut curr = self.next();
loop {
if self.same_ptr(curr) {
break;
}
let next = curr.next();
f(curr.oop());
curr = next;
}
}
unsafe fn next<'a, 'b>(&'a self) -> &'b mut OopHandle {
&mut *self.next
}
#[allow(unused)]
unsafe fn set_next(&self, next: *mut OopHandle) {
(&mut *(self as *const _ as *mut Self)).next = next;
}
unsafe fn prev(&self) -> &mut OopHandle {
&mut *self.prev
}
unsafe fn set_prev(&self, prev: *mut OopHandle) {
(&mut *(self as *const _ as *mut Self)).prev = prev;
}
pub fn
|
(&self) -> *mut OopHandle {
self as *const _ as *const _ as *mut _
}
unsafe fn new(oop: *mut A, head: &OopHandle) -> Box<Self> {
let thiz = Box::new(RawHandle {
oop: oop as Oop,
prev: head.prev,
next: head.as_ptr(),
phantom_data: PhantomData,
});
head.prev().next = RawHandle::<A>::as_ptr(&*thiz);
(*head).set_prev(thiz.as_ptr());
thiz
}
unsafe fn new_ref(oop_ref: &A, head: &OopHandle) -> Box<Self> {
RawHandle::new(oop_ref as *const _ as *mut A, head)
}
pub unsafe fn dup(&self) -> Box<Self> {
RawHandle::<A>::new(*self.oop() as *mut _, &*self.as_ptr())
}
}
impl<A> Drop for RawHandle<A> {
fn drop(&mut self) {
unsafe {
self.next().prev = self.prev().as_ptr();
self.prev().next = self.next().as_ptr();
}
}
}
impl<A> Deref for RawHandle<A> {
type Target = A;
fn deref(&self) -> &A {
unsafe { &*(self.oop as *const A) }
}
}
impl<A> DerefMut for RawHandle<A> {
fn deref_mut(&mut self) -> &mut A {
unsafe { &mut *(self.oop as *mut A) }
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem;
#[test]
fn test_handle() {
unsafe {
let block = HandleBlock::new();
{
let mut oop = mem::zeroed::<Fixnum>();
oop.value = 42;
let foo1 = block.new_ref_handle(&oop);
let _foo2 = block.new_ref_handle(&oop);
let _foo3 = block.new_ref_handle(&oop);
assert_eq!(&oop as *const _ as Oop, *foo1.oop());
assert_eq!(oop.value, foo1.value);
assert_eq!(3, block.len());
}
assert_eq!(0, block.len());
}
}
#[test]
fn test_info_offsets() {
unsafe {
let info = infotable_for_pair();
let entry = info.entry_word();
assert_eq!(InfoTable::<Pair>::from_entry(entry).entry_word(), entry);
}
}
}
|
as_ptr
|
identifier_name
|
oop.rs
|
/// Ordinary object pointers and memory layouts.
/// (I did try to come up with a better name but failed.)
use super::gc::INFO_FRESH_TAG;
use super::stackmap::OopStackMapOffsets;
use ast::id::Id;
use std::slice;
use std::ptr;
use std::ops::{Deref, DerefMut};
use std::marker::PhantomData;
use std::mem::{size_of, transmute, replace};
use std::fmt::{self, Formatter, Debug};
use std::cell::UnsafeCell;
pub type Oop = usize;
pub const NULL_OOP: Oop = 0;
// Tagging: currently only booleans are tagged.
pub const OOP_TAG_SHIFT: u8 = 3;
pub const OOP_TAG_MASK: usize = (1 << OOP_TAG_SHIFT) - 1;
#[repr(u8)]
pub enum OopTag {
Fixnum = 0x1,
Singleton = 0x2,
}
pub fn sizeof_ptrs(nptrs: usize) -> usize {
nptrs * 8
}
#[repr(u16)]
#[derive(Eq, PartialEq, Copy, Clone)]
pub enum OopKind {
Plain,
Callable,
OopArray,
I64Array,
}
impl OopKind {
pub fn is_array(self) -> bool {
self == OopKind::OopArray || self == OopKind::I64Array
}
pub fn is_closure(self) -> bool {
self == OopKind::Callable
}
}
#[repr(C)]
pub struct InfoTable<A> {
// XXX: Using Option<Box<T>> safely with mem::zeroed relies on that
// Rust internally treats None<Box<T>> as nullptr.
gcrefs: Option<Box<[GcRef]>>,
smo: Option<Box<OopStackMapOffsets>>,
name: Option<Box<String>>,
gc_mark_word: UnsafeCell<usize>,
arity: u16,
kind: OopKind,
ptr_payloads: u16, // GC ptrs
word_payloads: u16, // Unmanaged qwords
entry: [u8; 0],
phantom_data: PhantomData<A>,
}
pub const INFOTABLE_ARITY_OFFSET: isize = -8;
pub const INFOTABLE_KIND_OFFSET: isize = -6;
impl<A> Debug for InfoTable<A> {
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error> {
write!(fmt, "<InfoTable {}>", self.name())
}
}
impl<A> InfoTable<A> {
pub fn size_of() -> usize {
size_of::<Self>()
}
pub fn replace(&mut self, o: Self) {
replace(self, o);
}
pub fn new(ptr_payloads: u16,
word_payloads: u16,
arity: u16,
kind: OopKind,
name: &str)
-> Self {
InfoTable {
ptr_payloads: ptr_payloads,
word_payloads: word_payloads,
arity: arity,
gc_mark_word: UnsafeCell::new(INFO_FRESH_TAG),
kind: kind,
name: Some(Box::new( name.to_owned())),
gcrefs: Default::default(),
smo: Default::default(),
entry: [],
phantom_data: PhantomData,
}
}
pub fn sizeof_instance(&self) -> usize {
assert!(!self.is_array());
sizeof_ptrs(self.ptr_payloads as usize + self.word_payloads as usize + 1)
}
pub fn sizeof_array_instance(&self, size: usize) -> usize {
assert!(self.is_array());
sizeof_ptrs(size + 2)
}
pub fn is_array(&self) -> bool {
self.kind.is_array()
}
pub fn is_ooparray(&self) -> bool {
self.kind == OopKind::OopArray
}
pub fn is_closure(&self) -> bool {
self.kind.is_closure()
}
pub fn set_gcrefs(&mut self, v: Vec<GcRef>) {
self.gcrefs = Some(v.into_boxed_slice());
}
pub unsafe fn gcrefs(&self) -> Option<&[GcRef]> {
self.gcrefs.as_ref().map(|rb| &**rb)
}
pub fn set_smo(&mut self, smo: OopStackMapOffsets) {
self.smo = Some(Box::new( smo));
}
|
pub fn gc_mark_word(&self) -> &mut usize {
unsafe { &mut *self.gc_mark_word.get() }
}
pub fn name(&self) -> &str {
&*self.name.as_ref().unwrap()
}
pub unsafe fn from_entry<'a>(entry: usize) -> &'a mut Self {
&mut *((entry - size_of::<Self>()) as *mut _)
}
pub fn entry_word(&self) -> usize {
self.entry.as_ptr() as usize
}
}
fn mk_infotable_for_data<A>(nptrs: u16, nwords: u16, name: &str, kind: OopKind) -> InfoTable<A> {
InfoTable::new(nptrs, nwords, 0, kind, name)
}
pub fn infotable_for_pair() -> InfoTable<Pair> {
mk_infotable_for_data(2, 0, "<Pair>", OopKind::Plain)
}
pub fn infotable_for_box() -> InfoTable<MutBox> {
mk_infotable_for_data(1, 0, "<Box>", OopKind::Plain)
}
pub fn infotable_for_fixnum() -> InfoTable<Fixnum> {
mk_infotable_for_data(0, 1, "<Fixnum>", OopKind::Plain)
}
pub fn infotable_for_symbol() -> InfoTable<Symbol> {
mk_infotable_for_data(0, 1, "<Symbol>", OopKind::Plain)
}
pub fn infotable_for_ooparray() -> InfoTable<OopArray> {
mk_infotable_for_data(0, 0, "<OopArray>", OopKind::OopArray)
}
pub fn infotable_for_i64array() -> InfoTable<I64Array> {
mk_infotable_for_data(0, 0, "<I64Array>", OopKind::I64Array)
}
// Encodes different kinds of Oops that a InfoTable might points to.
#[derive(Copy, Clone, Debug)]
pub enum GcRef {
// *(entry + u32) contains a ptr-sized, i.e. u64, Oop.
OopConst(u32),
// *(entry + u32) contains an i32 PC-relative offset to another
// InfoTable's entry.
PcRelInfoEntry(u32),
}
/// A Closure is not exactly an ordinary callable object in the narrow sense -
/// it's a generic heap object, with a info table and some payloads (fields).
/// Yes, we are using Haskell's nomenclature here.
#[repr(C)]
pub struct Closure {
// *info points directly to the entry field in the InfoTable.
// See Haskell's `tables-next-to-code` trick.
info: *const (),
payloads: [Oop; 0],
}
impl Closure {
pub unsafe fn info_is<A>(&self, info: &InfoTable<A>) -> bool {
*self.entry_word() == info.entry_word()
}
pub unsafe fn info(&self) -> &InfoTable<Self> {
InfoTable::<Self>::from_entry(*self.entry_word())
}
pub unsafe fn info_mut(&mut self) -> &mut InfoTable<Self> {
InfoTable::<Self>::from_entry(*self.entry_word())
}
pub unsafe fn entry_word(&self) -> &mut usize {
&mut *(&self.info as *const _ as *mut _)
}
pub unsafe fn payload_start(&self) -> usize {
self.payloads.as_ptr() as usize
}
pub unsafe fn ptr_payloads(&self) -> &mut [Oop] {
let base = self.payload_start() as *mut _;
let len = self.info().ptr_payloads as usize;
slice::from_raw_parts_mut(base, len)
}
pub unsafe fn word_payloads(&self) -> &mut [usize] {
let base = self.payload_start() + sizeof_ptrs(self.info().ptr_payloads as usize);
let len = self.info().word_payloads as usize;
slice::from_raw_parts_mut(base as *mut _, len)
}
pub unsafe fn as_word(&self) -> usize {
transmute(self)
}
}
pub type ClosureInfo = InfoTable<Closure>;
#[repr(C)]
pub struct Fixnum {
info: *const (),
value: isize,
}
impl Fixnum {
pub fn set_value(&mut self, v: isize) {
self.value = v
}
pub fn value(&self) -> isize {
self.value
}
}
#[repr(C)]
pub struct Pair {
info: *const (),
pub car: Oop,
pub cdr: Oop,
}
#[repr(C)]
pub struct Symbol {
info: *const (),
id: Id,
}
impl Symbol {
pub fn as_str(&self) -> &str {
self.id.as_str()
}
pub fn set_value(&mut self, id: Id) {
self.id = id;
}
}
#[repr(C)]
pub struct MutBox {
info: *const (),
value: Oop,
}
impl MutBox {
pub fn set_value(&mut self, v: Oop) {
self.value = v
}
pub fn value(&self) -> Oop {
self.value
}
}
#[derive(Debug, Eq, PartialEq)]
#[repr(u8)]
pub enum Singleton {
False = 0,
True = 1,
Nil = 2,
}
impl Singleton {
pub fn as_oop(self) -> Oop {
((self as usize) << OOP_TAG_SHIFT) + (OopTag::Singleton as usize)
}
pub fn from_oop(oop: Oop) -> Option<Self> {
Some(match oop >> OOP_TAG_SHIFT {
0 => Singleton::False,
1 => Singleton::True,
2 => Singleton::Nil,
_ => return None,
})
}
pub fn is_singleton(oop: Oop) -> bool {
oop & OOP_TAG_MASK == (OopTag::Singleton as usize)
}
pub fn is_nil(oop: Oop) -> bool {
oop == Singleton::Nil.as_oop()
}
}
// Assumes arrays have the same layout: [info, len, content...]
pub trait IsArray<A: Sized> : Sized {
unsafe fn len(&self) -> usize {
*transmute::<usize, *const usize>(self as *const _ as usize + 8)
}
unsafe fn content(&self) -> &mut [A] {
let content_ptr = self as *const _ as usize + 16;
slice::from_raw_parts_mut(content_ptr as *mut _, self.len())
}
}
#[repr(C)]
pub struct OopArray {
info: *const (),
pub len: usize,
pub content: [Oop; 0],
}
impl IsArray<Oop> for OopArray {}
#[repr(C)]
pub struct I64Array {
info: *const (),
pub len: usize,
pub content: [i64; 0],
}
impl IsArray<i64> for I64Array {}
// Doubly-linked list of oops. Used to manage root of stacks.
pub struct RawHandle<A> {
oop: Oop,
prev: *mut OopHandle,
next: *mut OopHandle,
phantom_data: PhantomData<A>,
}
pub type OopHandle = RawHandle<Oop>;
pub type Handle<A> = Box<RawHandle<A>>;
pub struct HandleBlock(OopHandle);
// Just a marker.
pub trait IsOop : Sized {
unsafe fn as_oop(&self) -> Oop {
transmute(self)
}
unsafe fn oop_cast<A: IsOop>(&self) -> &A {
transmute(self)
}
unsafe fn from_raw<'a>(oop: Oop) -> &'a mut Self {
&mut *transmute::<Oop, *mut Self>(oop)
}
}
impl IsOop for Closure {}
impl IsOop for Fixnum {}
impl IsOop for Symbol {}
impl IsOop for Pair {}
impl IsOop for MutBox {}
impl IsOop for OopArray {}
impl IsOop for I64Array {}
impl HandleBlock {
pub fn new() -> Box<HandleBlock> {
let mut thiz = Box::new(HandleBlock(RawHandle {
oop: NULL_OOP,
prev: ptr::null_mut(),
next: ptr::null_mut(),
phantom_data: PhantomData,
}));
(*thiz).0.prev = (*thiz).0.as_ptr();
(*thiz).0.next = (*thiz).0.as_ptr();
thiz
}
pub fn head(&self) -> &OopHandle {
&(*self).0
}
pub fn len(&self) -> usize {
unsafe {
let mut res = 0;
self.head().foreach_oop(|_| res += 1);
res
}
}
pub fn new_handle<A: IsOop>(&self, a: *mut A) -> Box<RawHandle<A>> {
unsafe { RawHandle::new(a, self.head()) }
}
pub fn new_ref_handle<A: IsOop>(&self, a: &A) -> Box<RawHandle<A>> {
unsafe { RawHandle::new_ref(a, &self.0) }
}
}
impl<A> RawHandle<A> {
pub unsafe fn oop(&self) -> &mut Oop {
&mut *(&self.oop as *const _ as *mut _)
}
unsafe fn same_ptr(&self, rhs: &OopHandle) -> bool {
self.as_ptr() == rhs.as_ptr()
}
pub unsafe fn foreach_oop<F: FnMut(&mut Oop)>(&self, mut f: F) {
let mut curr = self.next();
loop {
if self.same_ptr(curr) {
break;
}
let next = curr.next();
f(curr.oop());
curr = next;
}
}
unsafe fn next<'a, 'b>(&'a self) -> &'b mut OopHandle {
&mut *self.next
}
#[allow(unused)]
unsafe fn set_next(&self, next: *mut OopHandle) {
(&mut *(self as *const _ as *mut Self)).next = next;
}
unsafe fn prev(&self) -> &mut OopHandle {
&mut *self.prev
}
unsafe fn set_prev(&self, prev: *mut OopHandle) {
(&mut *(self as *const _ as *mut Self)).prev = prev;
}
pub fn as_ptr(&self) -> *mut OopHandle {
self as *const _ as *const _ as *mut _
}
unsafe fn new(oop: *mut A, head: &OopHandle) -> Box<Self> {
let thiz = Box::new(RawHandle {
oop: oop as Oop,
prev: head.prev,
next: head.as_ptr(),
phantom_data: PhantomData,
});
head.prev().next = RawHandle::<A>::as_ptr(&*thiz);
(*head).set_prev(thiz.as_ptr());
thiz
}
unsafe fn new_ref(oop_ref: &A, head: &OopHandle) -> Box<Self> {
RawHandle::new(oop_ref as *const _ as *mut A, head)
}
pub unsafe fn dup(&self) -> Box<Self> {
RawHandle::<A>::new(*self.oop() as *mut _, &*self.as_ptr())
}
}
impl<A> Drop for RawHandle<A> {
fn drop(&mut self) {
unsafe {
self.next().prev = self.prev().as_ptr();
self.prev().next = self.next().as_ptr();
}
}
}
impl<A> Deref for RawHandle<A> {
type Target = A;
fn deref(&self) -> &A {
unsafe { &*(self.oop as *const A) }
}
}
impl<A> DerefMut for RawHandle<A> {
fn deref_mut(&mut self) -> &mut A {
unsafe { &mut *(self.oop as *mut A) }
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem;
#[test]
fn test_handle() {
unsafe {
let block = HandleBlock::new();
{
let mut oop = mem::zeroed::<Fixnum>();
oop.value = 42;
let foo1 = block.new_ref_handle(&oop);
let _foo2 = block.new_ref_handle(&oop);
let _foo3 = block.new_ref_handle(&oop);
assert_eq!(&oop as *const _ as Oop, *foo1.oop());
assert_eq!(oop.value, foo1.value);
assert_eq!(3, block.len());
}
assert_eq!(0, block.len());
}
}
#[test]
fn test_info_offsets() {
unsafe {
let info = infotable_for_pair();
let entry = info.entry_word();
assert_eq!(InfoTable::<Pair>::from_entry(entry).entry_word(), entry);
}
}
}
|
random_line_split
|
|
hash.rs
|
// Copyright 2015-2017 Parity Technologies
//
// 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.
//! General hash types, a fixed-size raw-data type used as the output of hash functions.
use std::{ops, fmt, cmp};
use std::cmp::{min, Ordering};
use std::ops::{Deref, DerefMut, BitXor, BitAnd, BitOr, IndexMut, Index};
use std::hash::{Hash, Hasher, BuildHasherDefault};
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use rand::Rng;
use rand::os::OsRng;
use rustc_serialize::hex::{FromHex, FromHexError};
use bigint::U256;
use libc::{c_void, memcmp};
/// Return `s` without the `0x` at the beginning of it, if any.
pub fn clean_0x(s: &str) -> &str {
if s.starts_with("0x") {
&s[2..]
} else {
s
}
}
macro_rules! impl_hash {
($from: ident, $size: expr) => {
#[repr(C)]
/// Unformatted binary data of fixed length.
pub struct $from (pub [u8; $size]);
impl From<[u8; $size]> for $from {
fn from(bytes: [u8; $size]) -> Self {
$from(bytes)
}
}
impl From<$from> for [u8; $size] {
fn from(s: $from) -> Self {
s.0
}
}
impl Deref for $from {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
&self.0
}
}
impl AsRef<[u8]> for $from {
#[inline]
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl DerefMut for $from {
#[inline]
fn deref_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
impl $from {
/// Create a new, zero-initialised, instance.
pub fn new() -> $from {
$from([0; $size])
}
/// Synonym for `new()`. Prefer to new as it's more readable.
pub fn zero() -> $from {
$from([0; $size])
}
/// Create a new, cryptographically random, instance.
pub fn random() -> $from {
let mut hash = $from::new();
hash.randomize();
hash
}
/// Assign self have a cryptographically random value.
pub fn randomize(&mut self) {
let mut rng = OsRng::new().unwrap();
rng.fill_bytes(&mut self.0);
}
/// Get the size of this object in bytes.
pub fn len() -> usize {
$size
}
#[inline]
/// Assign self to be of the same value as a slice of bytes of length `len()`.
pub fn clone_from_slice(&mut self, src: &[u8]) -> usize {
let min = cmp::min($size, src.len());
self.0[..min].copy_from_slice(&src[..min]);
min
}
/// Convert a slice of bytes of length `len()` to an instance of this type.
pub fn from_slice(src: &[u8]) -> Self {
let mut r = Self::new();
r.clone_from_slice(src);
r
}
/// Copy the data of this object into some mutable slice of length `len()`.
pub fn copy_to(&self, dest: &mut[u8]) {
let min = cmp::min($size, dest.len());
dest[..min].copy_from_slice(&self.0[..min]);
}
/// Returns `true` if all bits set in `b` are also set in `self`.
pub fn contains<'a>(&'a self, b: &'a Self) -> bool {
&(b & self) == b
}
/// Returns `true` if no bits are set.
pub fn is_zero(&self) -> bool {
self.eq(&Self::new())
}
/// Returns the lowest 8 bytes interpreted as a BigEndian integer.
pub fn low_u64(&self) -> u64 {
let mut ret = 0u64;
for i in 0..min($size, 8) {
ret |= (self.0[$size - 1 - i] as u64) << (i * 8);
}
ret
}
}
impl FromStr for $from {
type Err = FromHexError;
fn from_str(s: &str) -> Result<$from, FromHexError> {
let a = s.from_hex()?;
if a.len()!= $size {
return Err(FromHexError::InvalidHexLength);
}
let mut ret = [0;$size];
ret.copy_from_slice(&a);
Ok($from(ret))
}
}
impl fmt::Debug for $from {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in &self.0[..] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl fmt::Display for $from {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in &self.0[0..2] {
write!(f, "{:02x}", i)?;
}
write!(f, "…")?;
for i in &self.0[$size - 2..$size] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl Copy for $from {}
#[cfg_attr(feature="dev", allow(expl_impl_clone_on_copy))]
impl Clone for $from {
fn clone(&self) -> $from {
let mut ret = $from::new();
ret.0.copy_from_slice(&self.0);
ret
}
}
impl Eq for $from {}
impl PartialEq for $from {
fn eq(&self, other: &Self) -> bool {
unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) == 0 }
}
}
impl Ord for $from {
fn cmp(&self, other: &Self) -> Ordering {
let r = unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) };
if r < 0 { return Ordering::Less }
if r > 0 { return Ordering::Greater }
return Ordering::Equal;
}
}
impl PartialOrd for $from {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Hash for $from {
fn hash<H>(&self, state: &mut H) where H: Hasher {
state.write(&self.0);
state.finish();
}
}
impl Index<usize> for $from {
type Output = u8;
fn index(&self, index: usize) -> &u8 {
&self.0[index]
}
}
impl IndexMut<usize> for $from {
fn index_mut(&mut self, index: usize) -> &mut u8 {
&mut self.0[index]
}
}
impl Index<ops::Range<usize>> for $from {
type Output = [u8];
fn index(&self, index: ops::Range<usize>) -> &[u8] {
&self.0[index]
}
}
impl IndexMut<ops::Range<usize>> for $from {
fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [u8] {
&mut self.0[index]
}
}
impl Index<ops::RangeFull> for $from {
type Output = [u8];
fn index(&self, _index: ops::RangeFull) -> &[u8] {
&self.0
}
}
impl IndexMut<ops::RangeFull> for $from {
fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [u8] {
&mut self.0
}
}
/// `BitOr` on references
impl<'a> BitOr for &'a $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] | rhs.0[i];
}
ret
}
}
/// Moving `BitOr`
impl BitOr for $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
&self | &rhs
}
}
/// `BitAnd` on references
impl <'a> BitAnd for &'a $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] & rhs.0[i];
}
ret
}
}
/// Moving `BitAnd`
impl BitAnd for $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
&self & &rhs
}
}
/// `BitXor` on references
impl <'a> BitXor for &'a $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] ^ rhs.0[i];
}
ret
}
}
/// Moving `BitXor`
impl BitXor for $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
&self ^ &rhs
}
}
impl $from {
/// Get a hex representation.
pub fn hex(&self) -> String {
format!("{:?}", self)
}
}
impl Default for $from {
fn default() -> Self { $from::new() }
}
impl From<u64> for $from {
fn from(mut value: u64) -> $from {
let mut ret = $from::new();
for i in 0..8 {
if i < $size {
ret.0[$size - i - 1] = (value & 0xff) as u8;
value >>= 8;
}
}
ret
}
}
impl From<&'static str> for $from {
fn from(s: &'static str) -> $from {
let s = clean_0x(s);
if s.len() % 2 == 1 {
$from::from_str(&("0".to_owned() + s)).unwrap()
} else {
$from::from_str(s).unwrap()
}
}
}
impl<'a> From<&'a [u8]> for $from {
fn from(s: &'a [u8]) -> $from {
$from::from_slice(s)
}
}
}
}
impl From<U256> for H256 {
fn from(value: U256) -> H256 {
let mut ret = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl<'a> From<&'a U256> for H256 {
fn from(value: &'a U256) -> H256 {
let mut ret: H256 = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl From<H256> for U256 {
fn from(value: H256) -> U256 {
U256::from(&value)
}
}
impl<'a> From<&'a H256> for U256 {
fn from(value: &'a H256) -> U256 {
U256::from(value.as_ref() as &[u8])
}
}
impl From<H256> for H160 {
fn from(value: H256) -> H160 {
let mut ret = H160::new();
ret.0.copy_from_slice(&value[12..32]);
ret
}
}
impl From<H256> for H64 {
fn from(value: H256) -> H64 {
let mut ret = H64::new();
ret.0.copy_from_slice(&value[20..28]);
ret
}
}
impl From<H160> for H256 {
fn from(value: H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(&value);
ret
}
}
impl<'a> From<&'a H160> for H256 {
fn from(value: &'a H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(value);
ret
}
}
impl_hash!(H32, 4);
impl_hash!(H64, 8);
impl_hash!(H128, 16);
impl_hash!(H160, 20);
impl_hash!(H256, 32);
impl_hash!(H264, 33);
impl_hash!(H512, 64);
impl_hash!(H520, 65);
impl_hash!(H1024, 128);
impl_hash!(H2048, 256);
known_heap_size!(0, H32, H64, H128, H160, H256, H264, H512, H520, H1024, H2048);
// Specialized HashMap and HashSet
/// Hasher that just takes 8 bytes of the provided value.
/// May only be used for keys which are 32 bytes.
pub struct PlainHasher {
prefix: [u8; 8],
_marker: [u64; 0], // for alignment
}
impl Default for PlainHasher {
#[inline]
fn default() -> PlainHasher {
PlainHasher {
prefix: [0; 8],
_marker: [0; 0],
}
}
}
impl Hasher for PlainHasher {
#[inline]
fn finish(&self) -> u64 {
unsafe { ::std::mem::transmute(self.prefix) }
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
debug_assert!(bytes.len() == 32);
for quarter in bytes.chunks(8) {
for (x, y) in self.prefix.iter_mut().zip(quarter) {
*x ^= *y
}
}
}
}
/// Specialized version of `HashMap` with H256 keys and fast hashing function.
pub type H256FastMap<T> = HashMap<H256, T, BuildHasherDefault<PlainHasher>>;
/// Specialized version of `HashSet` with H256 keys and fast hashing function.
pub type H256FastSet = HashSet<H256, BuildHasherDefault<PlainHasher>>;
#[cfg(test)]
mod tests {
use hash::*;
use std::str::FromStr;
#[test]
fn hasher_alignment() {
use std::mem::align_of;
assert_eq!(align_of::<u64>(), align_of::<PlainHasher>());
}
#[test]
#[cfg_attr(feature="dev", allow(eq_op))]
fn hash() {
let h = H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
assert_eq!(H64::from_str("0123456789abcdef").unwrap(), h);
assert_eq!(format!("{}", h), "0123…cdef");
assert_eq!(format!("{:?}", h), "0123456789abcdef");
assert_eq!(h.hex(), "0123456789abcdef");
assert!(h == h);
assert!(h!= H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xee]));
assert!(h!= H64([0; 8]));
}
#[test]
fn hash_bitor() {
let a = H64([1; 8]);
let b = H64([2; 8]);
let c = H64([3; 8]);
// borrow
assert_eq!(&a | &b, c);
// move
assert_eq!(a | b, c);
}
#[test]
fn from_and_to_address() {
let address: H160 = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into();
let h = H256::from(address.clone());
let a = H160::from(h);
assert_eq!(address, a);
}
#[test]
fn from
|
assert_eq!(H128::from(0x1234567890abcdef), H128::from_str("00000000000000001234567890abcdef").unwrap());
assert_eq!(H64::from(0x1234567890abcdef), H64::from_str("1234567890abcdef").unwrap());
assert_eq!(H32::from(0x1234567890abcdef), H32::from_str("90abcdef").unwrap());
}
#[test]
fn from_str() {
assert_eq!(H64::from(0x1234567890abcdef), H64::from("0x1234567890abcdef"));
assert_eq!(H64::from(0x1234567890abcdef), H64::from("1234567890abcdef"));
assert_eq!(H64::from(0x234567890abcdef), H64::from("0x234567890abcdef"));
}
#[test]
fn from_and_to_u256() {
let u: U256 = 0x123456789abcdef0u64.into();
let h = H256::from(u);
assert_eq!(H256::from(u), H256::from("000000000000000000000000000000000000000000000000123456789abcdef0"));
let h_ref = H256::from(&u);
assert_eq!(h, h_ref);
let r_ref: U256 = From::from(&h);
assert_eq!(r_ref, u);
let r: U256 = From::from(h);
assert_eq!(r, u);
}
}
|
_u64() {
|
identifier_name
|
hash.rs
|
// Copyright 2015-2017 Parity Technologies
//
// 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.
//! General hash types, a fixed-size raw-data type used as the output of hash functions.
use std::{ops, fmt, cmp};
use std::cmp::{min, Ordering};
use std::ops::{Deref, DerefMut, BitXor, BitAnd, BitOr, IndexMut, Index};
use std::hash::{Hash, Hasher, BuildHasherDefault};
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use rand::Rng;
use rand::os::OsRng;
use rustc_serialize::hex::{FromHex, FromHexError};
use bigint::U256;
use libc::{c_void, memcmp};
/// Return `s` without the `0x` at the beginning of it, if any.
pub fn clean_0x(s: &str) -> &str {
if s.starts_with("0x")
|
else {
s
}
}
macro_rules! impl_hash {
($from: ident, $size: expr) => {
#[repr(C)]
/// Unformatted binary data of fixed length.
pub struct $from (pub [u8; $size]);
impl From<[u8; $size]> for $from {
fn from(bytes: [u8; $size]) -> Self {
$from(bytes)
}
}
impl From<$from> for [u8; $size] {
fn from(s: $from) -> Self {
s.0
}
}
impl Deref for $from {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
&self.0
}
}
impl AsRef<[u8]> for $from {
#[inline]
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl DerefMut for $from {
#[inline]
fn deref_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
impl $from {
/// Create a new, zero-initialised, instance.
pub fn new() -> $from {
$from([0; $size])
}
/// Synonym for `new()`. Prefer to new as it's more readable.
pub fn zero() -> $from {
$from([0; $size])
}
/// Create a new, cryptographically random, instance.
pub fn random() -> $from {
let mut hash = $from::new();
hash.randomize();
hash
}
/// Assign self have a cryptographically random value.
pub fn randomize(&mut self) {
let mut rng = OsRng::new().unwrap();
rng.fill_bytes(&mut self.0);
}
/// Get the size of this object in bytes.
pub fn len() -> usize {
$size
}
#[inline]
/// Assign self to be of the same value as a slice of bytes of length `len()`.
pub fn clone_from_slice(&mut self, src: &[u8]) -> usize {
let min = cmp::min($size, src.len());
self.0[..min].copy_from_slice(&src[..min]);
min
}
/// Convert a slice of bytes of length `len()` to an instance of this type.
pub fn from_slice(src: &[u8]) -> Self {
let mut r = Self::new();
r.clone_from_slice(src);
r
}
/// Copy the data of this object into some mutable slice of length `len()`.
pub fn copy_to(&self, dest: &mut[u8]) {
let min = cmp::min($size, dest.len());
dest[..min].copy_from_slice(&self.0[..min]);
}
/// Returns `true` if all bits set in `b` are also set in `self`.
pub fn contains<'a>(&'a self, b: &'a Self) -> bool {
&(b & self) == b
}
/// Returns `true` if no bits are set.
pub fn is_zero(&self) -> bool {
self.eq(&Self::new())
}
/// Returns the lowest 8 bytes interpreted as a BigEndian integer.
pub fn low_u64(&self) -> u64 {
let mut ret = 0u64;
for i in 0..min($size, 8) {
ret |= (self.0[$size - 1 - i] as u64) << (i * 8);
}
ret
}
}
impl FromStr for $from {
type Err = FromHexError;
fn from_str(s: &str) -> Result<$from, FromHexError> {
let a = s.from_hex()?;
if a.len()!= $size {
return Err(FromHexError::InvalidHexLength);
}
let mut ret = [0;$size];
ret.copy_from_slice(&a);
Ok($from(ret))
}
}
impl fmt::Debug for $from {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in &self.0[..] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl fmt::Display for $from {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in &self.0[0..2] {
write!(f, "{:02x}", i)?;
}
write!(f, "…")?;
for i in &self.0[$size - 2..$size] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl Copy for $from {}
#[cfg_attr(feature="dev", allow(expl_impl_clone_on_copy))]
impl Clone for $from {
fn clone(&self) -> $from {
let mut ret = $from::new();
ret.0.copy_from_slice(&self.0);
ret
}
}
impl Eq for $from {}
impl PartialEq for $from {
fn eq(&self, other: &Self) -> bool {
unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) == 0 }
}
}
impl Ord for $from {
fn cmp(&self, other: &Self) -> Ordering {
let r = unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) };
if r < 0 { return Ordering::Less }
if r > 0 { return Ordering::Greater }
return Ordering::Equal;
}
}
impl PartialOrd for $from {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Hash for $from {
fn hash<H>(&self, state: &mut H) where H: Hasher {
state.write(&self.0);
state.finish();
}
}
impl Index<usize> for $from {
type Output = u8;
fn index(&self, index: usize) -> &u8 {
&self.0[index]
}
}
impl IndexMut<usize> for $from {
fn index_mut(&mut self, index: usize) -> &mut u8 {
&mut self.0[index]
}
}
impl Index<ops::Range<usize>> for $from {
type Output = [u8];
fn index(&self, index: ops::Range<usize>) -> &[u8] {
&self.0[index]
}
}
impl IndexMut<ops::Range<usize>> for $from {
fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [u8] {
&mut self.0[index]
}
}
impl Index<ops::RangeFull> for $from {
type Output = [u8];
fn index(&self, _index: ops::RangeFull) -> &[u8] {
&self.0
}
}
impl IndexMut<ops::RangeFull> for $from {
fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [u8] {
&mut self.0
}
}
/// `BitOr` on references
impl<'a> BitOr for &'a $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] | rhs.0[i];
}
ret
}
}
/// Moving `BitOr`
impl BitOr for $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
&self | &rhs
}
}
/// `BitAnd` on references
impl <'a> BitAnd for &'a $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] & rhs.0[i];
}
ret
}
}
/// Moving `BitAnd`
impl BitAnd for $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
&self & &rhs
}
}
/// `BitXor` on references
impl <'a> BitXor for &'a $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] ^ rhs.0[i];
}
ret
}
}
/// Moving `BitXor`
impl BitXor for $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
&self ^ &rhs
}
}
impl $from {
/// Get a hex representation.
pub fn hex(&self) -> String {
format!("{:?}", self)
}
}
impl Default for $from {
fn default() -> Self { $from::new() }
}
impl From<u64> for $from {
fn from(mut value: u64) -> $from {
let mut ret = $from::new();
for i in 0..8 {
if i < $size {
ret.0[$size - i - 1] = (value & 0xff) as u8;
value >>= 8;
}
}
ret
}
}
impl From<&'static str> for $from {
fn from(s: &'static str) -> $from {
let s = clean_0x(s);
if s.len() % 2 == 1 {
$from::from_str(&("0".to_owned() + s)).unwrap()
} else {
$from::from_str(s).unwrap()
}
}
}
impl<'a> From<&'a [u8]> for $from {
fn from(s: &'a [u8]) -> $from {
$from::from_slice(s)
}
}
}
}
impl From<U256> for H256 {
fn from(value: U256) -> H256 {
let mut ret = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl<'a> From<&'a U256> for H256 {
fn from(value: &'a U256) -> H256 {
let mut ret: H256 = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl From<H256> for U256 {
fn from(value: H256) -> U256 {
U256::from(&value)
}
}
impl<'a> From<&'a H256> for U256 {
fn from(value: &'a H256) -> U256 {
U256::from(value.as_ref() as &[u8])
}
}
impl From<H256> for H160 {
fn from(value: H256) -> H160 {
let mut ret = H160::new();
ret.0.copy_from_slice(&value[12..32]);
ret
}
}
impl From<H256> for H64 {
fn from(value: H256) -> H64 {
let mut ret = H64::new();
ret.0.copy_from_slice(&value[20..28]);
ret
}
}
impl From<H160> for H256 {
fn from(value: H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(&value);
ret
}
}
impl<'a> From<&'a H160> for H256 {
fn from(value: &'a H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(value);
ret
}
}
impl_hash!(H32, 4);
impl_hash!(H64, 8);
impl_hash!(H128, 16);
impl_hash!(H160, 20);
impl_hash!(H256, 32);
impl_hash!(H264, 33);
impl_hash!(H512, 64);
impl_hash!(H520, 65);
impl_hash!(H1024, 128);
impl_hash!(H2048, 256);
known_heap_size!(0, H32, H64, H128, H160, H256, H264, H512, H520, H1024, H2048);
// Specialized HashMap and HashSet
/// Hasher that just takes 8 bytes of the provided value.
/// May only be used for keys which are 32 bytes.
pub struct PlainHasher {
prefix: [u8; 8],
_marker: [u64; 0], // for alignment
}
impl Default for PlainHasher {
#[inline]
fn default() -> PlainHasher {
PlainHasher {
prefix: [0; 8],
_marker: [0; 0],
}
}
}
impl Hasher for PlainHasher {
#[inline]
fn finish(&self) -> u64 {
unsafe { ::std::mem::transmute(self.prefix) }
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
debug_assert!(bytes.len() == 32);
for quarter in bytes.chunks(8) {
for (x, y) in self.prefix.iter_mut().zip(quarter) {
*x ^= *y
}
}
}
}
/// Specialized version of `HashMap` with H256 keys and fast hashing function.
pub type H256FastMap<T> = HashMap<H256, T, BuildHasherDefault<PlainHasher>>;
/// Specialized version of `HashSet` with H256 keys and fast hashing function.
pub type H256FastSet = HashSet<H256, BuildHasherDefault<PlainHasher>>;
#[cfg(test)]
mod tests {
use hash::*;
use std::str::FromStr;
#[test]
fn hasher_alignment() {
use std::mem::align_of;
assert_eq!(align_of::<u64>(), align_of::<PlainHasher>());
}
#[test]
#[cfg_attr(feature="dev", allow(eq_op))]
fn hash() {
let h = H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
assert_eq!(H64::from_str("0123456789abcdef").unwrap(), h);
assert_eq!(format!("{}", h), "0123…cdef");
assert_eq!(format!("{:?}", h), "0123456789abcdef");
assert_eq!(h.hex(), "0123456789abcdef");
assert!(h == h);
assert!(h!= H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xee]));
assert!(h!= H64([0; 8]));
}
#[test]
fn hash_bitor() {
let a = H64([1; 8]);
let b = H64([2; 8]);
let c = H64([3; 8]);
// borrow
assert_eq!(&a | &b, c);
// move
assert_eq!(a | b, c);
}
#[test]
fn from_and_to_address() {
let address: H160 = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into();
let h = H256::from(address.clone());
let a = H160::from(h);
assert_eq!(address, a);
}
#[test]
fn from_u64() {
assert_eq!(H128::from(0x1234567890abcdef), H128::from_str("00000000000000001234567890abcdef").unwrap());
assert_eq!(H64::from(0x1234567890abcdef), H64::from_str("1234567890abcdef").unwrap());
assert_eq!(H32::from(0x1234567890abcdef), H32::from_str("90abcdef").unwrap());
}
#[test]
fn from_str() {
assert_eq!(H64::from(0x1234567890abcdef), H64::from("0x1234567890abcdef"));
assert_eq!(H64::from(0x1234567890abcdef), H64::from("1234567890abcdef"));
assert_eq!(H64::from(0x234567890abcdef), H64::from("0x234567890abcdef"));
}
#[test]
fn from_and_to_u256() {
let u: U256 = 0x123456789abcdef0u64.into();
let h = H256::from(u);
assert_eq!(H256::from(u), H256::from("000000000000000000000000000000000000000000000000123456789abcdef0"));
let h_ref = H256::from(&u);
assert_eq!(h, h_ref);
let r_ref: U256 = From::from(&h);
assert_eq!(r_ref, u);
let r: U256 = From::from(h);
assert_eq!(r, u);
}
}
|
{
&s[2..]
}
|
conditional_block
|
hash.rs
|
// Copyright 2015-2017 Parity Technologies
//
// 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.
//! General hash types, a fixed-size raw-data type used as the output of hash functions.
use std::{ops, fmt, cmp};
use std::cmp::{min, Ordering};
use std::ops::{Deref, DerefMut, BitXor, BitAnd, BitOr, IndexMut, Index};
use std::hash::{Hash, Hasher, BuildHasherDefault};
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use rand::Rng;
use rand::os::OsRng;
use rustc_serialize::hex::{FromHex, FromHexError};
use bigint::U256;
use libc::{c_void, memcmp};
/// Return `s` without the `0x` at the beginning of it, if any.
pub fn clean_0x(s: &str) -> &str {
if s.starts_with("0x") {
&s[2..]
} else {
s
}
}
macro_rules! impl_hash {
($from: ident, $size: expr) => {
#[repr(C)]
/// Unformatted binary data of fixed length.
pub struct $from (pub [u8; $size]);
impl From<[u8; $size]> for $from {
fn from(bytes: [u8; $size]) -> Self {
$from(bytes)
}
}
impl From<$from> for [u8; $size] {
fn from(s: $from) -> Self {
s.0
}
}
impl Deref for $from {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
&self.0
}
}
impl AsRef<[u8]> for $from {
#[inline]
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl DerefMut for $from {
#[inline]
fn deref_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
impl $from {
/// Create a new, zero-initialised, instance.
pub fn new() -> $from {
$from([0; $size])
}
/// Synonym for `new()`. Prefer to new as it's more readable.
pub fn zero() -> $from {
$from([0; $size])
}
/// Create a new, cryptographically random, instance.
pub fn random() -> $from {
let mut hash = $from::new();
hash.randomize();
hash
}
/// Assign self have a cryptographically random value.
pub fn randomize(&mut self) {
let mut rng = OsRng::new().unwrap();
rng.fill_bytes(&mut self.0);
}
/// Get the size of this object in bytes.
pub fn len() -> usize {
$size
}
#[inline]
/// Assign self to be of the same value as a slice of bytes of length `len()`.
pub fn clone_from_slice(&mut self, src: &[u8]) -> usize {
let min = cmp::min($size, src.len());
self.0[..min].copy_from_slice(&src[..min]);
min
}
/// Convert a slice of bytes of length `len()` to an instance of this type.
pub fn from_slice(src: &[u8]) -> Self {
let mut r = Self::new();
r.clone_from_slice(src);
r
}
/// Copy the data of this object into some mutable slice of length `len()`.
pub fn copy_to(&self, dest: &mut[u8]) {
let min = cmp::min($size, dest.len());
dest[..min].copy_from_slice(&self.0[..min]);
}
/// Returns `true` if all bits set in `b` are also set in `self`.
pub fn contains<'a>(&'a self, b: &'a Self) -> bool {
&(b & self) == b
}
/// Returns `true` if no bits are set.
pub fn is_zero(&self) -> bool {
self.eq(&Self::new())
}
/// Returns the lowest 8 bytes interpreted as a BigEndian integer.
pub fn low_u64(&self) -> u64 {
let mut ret = 0u64;
for i in 0..min($size, 8) {
ret |= (self.0[$size - 1 - i] as u64) << (i * 8);
}
ret
}
}
impl FromStr for $from {
type Err = FromHexError;
fn from_str(s: &str) -> Result<$from, FromHexError> {
let a = s.from_hex()?;
if a.len()!= $size {
return Err(FromHexError::InvalidHexLength);
}
let mut ret = [0;$size];
ret.copy_from_slice(&a);
Ok($from(ret))
}
}
impl fmt::Debug for $from {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in &self.0[..] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl fmt::Display for $from {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in &self.0[0..2] {
write!(f, "{:02x}", i)?;
}
write!(f, "…")?;
for i in &self.0[$size - 2..$size] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl Copy for $from {}
#[cfg_attr(feature="dev", allow(expl_impl_clone_on_copy))]
impl Clone for $from {
fn clone(&self) -> $from {
let mut ret = $from::new();
ret.0.copy_from_slice(&self.0);
ret
}
}
impl Eq for $from {}
impl PartialEq for $from {
fn eq(&self, other: &Self) -> bool {
unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) == 0 }
}
}
impl Ord for $from {
fn cmp(&self, other: &Self) -> Ordering {
let r = unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) };
if r < 0 { return Ordering::Less }
if r > 0 { return Ordering::Greater }
return Ordering::Equal;
}
}
impl PartialOrd for $from {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Hash for $from {
fn hash<H>(&self, state: &mut H) where H: Hasher {
state.write(&self.0);
state.finish();
}
}
impl Index<usize> for $from {
type Output = u8;
fn index(&self, index: usize) -> &u8 {
&self.0[index]
}
}
impl IndexMut<usize> for $from {
fn index_mut(&mut self, index: usize) -> &mut u8 {
&mut self.0[index]
}
}
impl Index<ops::Range<usize>> for $from {
type Output = [u8];
fn index(&self, index: ops::Range<usize>) -> &[u8] {
&self.0[index]
}
}
impl IndexMut<ops::Range<usize>> for $from {
fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [u8] {
&mut self.0[index]
}
}
impl Index<ops::RangeFull> for $from {
type Output = [u8];
fn index(&self, _index: ops::RangeFull) -> &[u8] {
&self.0
}
}
impl IndexMut<ops::RangeFull> for $from {
fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [u8] {
&mut self.0
}
}
/// `BitOr` on references
impl<'a> BitOr for &'a $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] | rhs.0[i];
}
ret
}
}
/// Moving `BitOr`
impl BitOr for $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
&self | &rhs
}
}
/// `BitAnd` on references
impl <'a> BitAnd for &'a $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] & rhs.0[i];
}
ret
}
}
/// Moving `BitAnd`
impl BitAnd for $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
&self & &rhs
}
}
/// `BitXor` on references
impl <'a> BitXor for &'a $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] ^ rhs.0[i];
}
ret
}
}
/// Moving `BitXor`
impl BitXor for $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
&self ^ &rhs
}
}
impl $from {
/// Get a hex representation.
pub fn hex(&self) -> String {
format!("{:?}", self)
}
}
impl Default for $from {
fn default() -> Self { $from::new() }
}
impl From<u64> for $from {
fn from(mut value: u64) -> $from {
let mut ret = $from::new();
for i in 0..8 {
if i < $size {
ret.0[$size - i - 1] = (value & 0xff) as u8;
value >>= 8;
}
}
ret
}
}
impl From<&'static str> for $from {
fn from(s: &'static str) -> $from {
let s = clean_0x(s);
if s.len() % 2 == 1 {
$from::from_str(&("0".to_owned() + s)).unwrap()
} else {
$from::from_str(s).unwrap()
}
}
}
impl<'a> From<&'a [u8]> for $from {
fn from(s: &'a [u8]) -> $from {
$from::from_slice(s)
}
}
}
}
impl From<U256> for H256 {
fn from(value: U256) -> H256 {
let mut ret = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl<'a> From<&'a U256> for H256 {
fn from(value: &'a U256) -> H256 {
|
impl From<H256> for U256 {
fn from(value: H256) -> U256 {
U256::from(&value)
}
}
impl<'a> From<&'a H256> for U256 {
fn from(value: &'a H256) -> U256 {
U256::from(value.as_ref() as &[u8])
}
}
impl From<H256> for H160 {
fn from(value: H256) -> H160 {
let mut ret = H160::new();
ret.0.copy_from_slice(&value[12..32]);
ret
}
}
impl From<H256> for H64 {
fn from(value: H256) -> H64 {
let mut ret = H64::new();
ret.0.copy_from_slice(&value[20..28]);
ret
}
}
impl From<H160> for H256 {
fn from(value: H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(&value);
ret
}
}
impl<'a> From<&'a H160> for H256 {
fn from(value: &'a H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(value);
ret
}
}
impl_hash!(H32, 4);
impl_hash!(H64, 8);
impl_hash!(H128, 16);
impl_hash!(H160, 20);
impl_hash!(H256, 32);
impl_hash!(H264, 33);
impl_hash!(H512, 64);
impl_hash!(H520, 65);
impl_hash!(H1024, 128);
impl_hash!(H2048, 256);
known_heap_size!(0, H32, H64, H128, H160, H256, H264, H512, H520, H1024, H2048);
// Specialized HashMap and HashSet
/// Hasher that just takes 8 bytes of the provided value.
/// May only be used for keys which are 32 bytes.
pub struct PlainHasher {
prefix: [u8; 8],
_marker: [u64; 0], // for alignment
}
impl Default for PlainHasher {
#[inline]
fn default() -> PlainHasher {
PlainHasher {
prefix: [0; 8],
_marker: [0; 0],
}
}
}
impl Hasher for PlainHasher {
#[inline]
fn finish(&self) -> u64 {
unsafe { ::std::mem::transmute(self.prefix) }
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
debug_assert!(bytes.len() == 32);
for quarter in bytes.chunks(8) {
for (x, y) in self.prefix.iter_mut().zip(quarter) {
*x ^= *y
}
}
}
}
/// Specialized version of `HashMap` with H256 keys and fast hashing function.
pub type H256FastMap<T> = HashMap<H256, T, BuildHasherDefault<PlainHasher>>;
/// Specialized version of `HashSet` with H256 keys and fast hashing function.
pub type H256FastSet = HashSet<H256, BuildHasherDefault<PlainHasher>>;
#[cfg(test)]
mod tests {
use hash::*;
use std::str::FromStr;
#[test]
fn hasher_alignment() {
use std::mem::align_of;
assert_eq!(align_of::<u64>(), align_of::<PlainHasher>());
}
#[test]
#[cfg_attr(feature="dev", allow(eq_op))]
fn hash() {
let h = H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
assert_eq!(H64::from_str("0123456789abcdef").unwrap(), h);
assert_eq!(format!("{}", h), "0123…cdef");
assert_eq!(format!("{:?}", h), "0123456789abcdef");
assert_eq!(h.hex(), "0123456789abcdef");
assert!(h == h);
assert!(h!= H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xee]));
assert!(h!= H64([0; 8]));
}
#[test]
fn hash_bitor() {
let a = H64([1; 8]);
let b = H64([2; 8]);
let c = H64([3; 8]);
// borrow
assert_eq!(&a | &b, c);
// move
assert_eq!(a | b, c);
}
#[test]
fn from_and_to_address() {
let address: H160 = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into();
let h = H256::from(address.clone());
let a = H160::from(h);
assert_eq!(address, a);
}
#[test]
fn from_u64() {
assert_eq!(H128::from(0x1234567890abcdef), H128::from_str("00000000000000001234567890abcdef").unwrap());
assert_eq!(H64::from(0x1234567890abcdef), H64::from_str("1234567890abcdef").unwrap());
assert_eq!(H32::from(0x1234567890abcdef), H32::from_str("90abcdef").unwrap());
}
#[test]
fn from_str() {
assert_eq!(H64::from(0x1234567890abcdef), H64::from("0x1234567890abcdef"));
assert_eq!(H64::from(0x1234567890abcdef), H64::from("1234567890abcdef"));
assert_eq!(H64::from(0x234567890abcdef), H64::from("0x234567890abcdef"));
}
#[test]
fn from_and_to_u256() {
let u: U256 = 0x123456789abcdef0u64.into();
let h = H256::from(u);
assert_eq!(H256::from(u), H256::from("000000000000000000000000000000000000000000000000123456789abcdef0"));
let h_ref = H256::from(&u);
assert_eq!(h, h_ref);
let r_ref: U256 = From::from(&h);
assert_eq!(r_ref, u);
let r: U256 = From::from(h);
assert_eq!(r, u);
}
}
|
let mut ret: H256 = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
|
identifier_body
|
hash.rs
|
// Copyright 2015-2017 Parity Technologies
//
// 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.
//! General hash types, a fixed-size raw-data type used as the output of hash functions.
use std::{ops, fmt, cmp};
use std::cmp::{min, Ordering};
use std::ops::{Deref, DerefMut, BitXor, BitAnd, BitOr, IndexMut, Index};
use std::hash::{Hash, Hasher, BuildHasherDefault};
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
use rand::Rng;
use rand::os::OsRng;
use rustc_serialize::hex::{FromHex, FromHexError};
use bigint::U256;
use libc::{c_void, memcmp};
/// Return `s` without the `0x` at the beginning of it, if any.
pub fn clean_0x(s: &str) -> &str {
if s.starts_with("0x") {
&s[2..]
} else {
s
}
}
macro_rules! impl_hash {
($from: ident, $size: expr) => {
#[repr(C)]
/// Unformatted binary data of fixed length.
pub struct $from (pub [u8; $size]);
impl From<[u8; $size]> for $from {
fn from(bytes: [u8; $size]) -> Self {
$from(bytes)
}
}
impl From<$from> for [u8; $size] {
fn from(s: $from) -> Self {
s.0
}
}
impl Deref for $from {
type Target = [u8];
#[inline]
fn deref(&self) -> &[u8] {
&self.0
}
}
impl AsRef<[u8]> for $from {
#[inline]
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl DerefMut for $from {
#[inline]
fn deref_mut(&mut self) -> &mut [u8] {
&mut self.0
}
}
impl $from {
/// Create a new, zero-initialised, instance.
pub fn new() -> $from {
$from([0; $size])
}
/// Synonym for `new()`. Prefer to new as it's more readable.
pub fn zero() -> $from {
$from([0; $size])
}
/// Create a new, cryptographically random, instance.
pub fn random() -> $from {
let mut hash = $from::new();
hash.randomize();
hash
}
/// Assign self have a cryptographically random value.
pub fn randomize(&mut self) {
let mut rng = OsRng::new().unwrap();
rng.fill_bytes(&mut self.0);
}
/// Get the size of this object in bytes.
pub fn len() -> usize {
$size
}
#[inline]
/// Assign self to be of the same value as a slice of bytes of length `len()`.
pub fn clone_from_slice(&mut self, src: &[u8]) -> usize {
let min = cmp::min($size, src.len());
self.0[..min].copy_from_slice(&src[..min]);
min
}
/// Convert a slice of bytes of length `len()` to an instance of this type.
pub fn from_slice(src: &[u8]) -> Self {
let mut r = Self::new();
r.clone_from_slice(src);
r
}
/// Copy the data of this object into some mutable slice of length `len()`.
pub fn copy_to(&self, dest: &mut[u8]) {
let min = cmp::min($size, dest.len());
dest[..min].copy_from_slice(&self.0[..min]);
}
/// Returns `true` if all bits set in `b` are also set in `self`.
pub fn contains<'a>(&'a self, b: &'a Self) -> bool {
&(b & self) == b
}
/// Returns `true` if no bits are set.
pub fn is_zero(&self) -> bool {
self.eq(&Self::new())
}
/// Returns the lowest 8 bytes interpreted as a BigEndian integer.
pub fn low_u64(&self) -> u64 {
let mut ret = 0u64;
for i in 0..min($size, 8) {
ret |= (self.0[$size - 1 - i] as u64) << (i * 8);
}
ret
}
}
impl FromStr for $from {
type Err = FromHexError;
fn from_str(s: &str) -> Result<$from, FromHexError> {
let a = s.from_hex()?;
if a.len()!= $size {
return Err(FromHexError::InvalidHexLength);
}
let mut ret = [0;$size];
ret.copy_from_slice(&a);
Ok($from(ret))
}
}
impl fmt::Debug for $from {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in &self.0[..] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl fmt::Display for $from {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in &self.0[0..2] {
write!(f, "{:02x}", i)?;
}
write!(f, "…")?;
for i in &self.0[$size - 2..$size] {
write!(f, "{:02x}", i)?;
}
Ok(())
}
}
impl Copy for $from {}
#[cfg_attr(feature="dev", allow(expl_impl_clone_on_copy))]
impl Clone for $from {
fn clone(&self) -> $from {
let mut ret = $from::new();
ret.0.copy_from_slice(&self.0);
ret
}
}
impl Eq for $from {}
impl PartialEq for $from {
fn eq(&self, other: &Self) -> bool {
unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) == 0 }
}
}
impl Ord for $from {
fn cmp(&self, other: &Self) -> Ordering {
let r = unsafe { memcmp(self.0.as_ptr() as *const c_void, other.0.as_ptr() as *const c_void, $size) };
if r < 0 { return Ordering::Less }
if r > 0 { return Ordering::Greater }
return Ordering::Equal;
}
}
impl PartialOrd for $from {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Hash for $from {
fn hash<H>(&self, state: &mut H) where H: Hasher {
state.write(&self.0);
state.finish();
}
}
impl Index<usize> for $from {
type Output = u8;
fn index(&self, index: usize) -> &u8 {
&self.0[index]
}
}
impl IndexMut<usize> for $from {
fn index_mut(&mut self, index: usize) -> &mut u8 {
&mut self.0[index]
}
}
impl Index<ops::Range<usize>> for $from {
type Output = [u8];
fn index(&self, index: ops::Range<usize>) -> &[u8] {
&self.0[index]
}
}
impl IndexMut<ops::Range<usize>> for $from {
fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [u8] {
&mut self.0[index]
}
}
impl Index<ops::RangeFull> for $from {
type Output = [u8];
fn index(&self, _index: ops::RangeFull) -> &[u8] {
&self.0
}
}
impl IndexMut<ops::RangeFull> for $from {
fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [u8] {
&mut self.0
}
}
/// `BitOr` on references
impl<'a> BitOr for &'a $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] | rhs.0[i];
}
ret
}
}
/// Moving `BitOr`
impl BitOr for $from {
type Output = $from;
fn bitor(self, rhs: Self) -> Self::Output {
&self | &rhs
}
}
/// `BitAnd` on references
impl <'a> BitAnd for &'a $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] & rhs.0[i];
}
ret
}
}
/// Moving `BitAnd`
impl BitAnd for $from {
type Output = $from;
fn bitand(self, rhs: Self) -> Self::Output {
&self & &rhs
}
}
/// `BitXor` on references
impl <'a> BitXor for &'a $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
let mut ret: $from = $from::default();
for i in 0..$size {
ret.0[i] = self.0[i] ^ rhs.0[i];
}
ret
}
}
/// Moving `BitXor`
impl BitXor for $from {
type Output = $from;
fn bitxor(self, rhs: Self) -> Self::Output {
&self ^ &rhs
}
}
impl $from {
/// Get a hex representation.
pub fn hex(&self) -> String {
format!("{:?}", self)
}
}
impl Default for $from {
fn default() -> Self { $from::new() }
}
impl From<u64> for $from {
fn from(mut value: u64) -> $from {
let mut ret = $from::new();
for i in 0..8 {
if i < $size {
ret.0[$size - i - 1] = (value & 0xff) as u8;
value >>= 8;
}
}
ret
}
}
impl From<&'static str> for $from {
fn from(s: &'static str) -> $from {
let s = clean_0x(s);
if s.len() % 2 == 1 {
$from::from_str(&("0".to_owned() + s)).unwrap()
} else {
$from::from_str(s).unwrap()
}
}
}
impl<'a> From<&'a [u8]> for $from {
fn from(s: &'a [u8]) -> $from {
$from::from_slice(s)
}
}
}
}
impl From<U256> for H256 {
fn from(value: U256) -> H256 {
let mut ret = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl<'a> From<&'a U256> for H256 {
fn from(value: &'a U256) -> H256 {
let mut ret: H256 = H256::new();
value.to_big_endian(&mut ret);
ret
}
}
impl From<H256> for U256 {
fn from(value: H256) -> U256 {
U256::from(&value)
}
}
impl<'a> From<&'a H256> for U256 {
fn from(value: &'a H256) -> U256 {
U256::from(value.as_ref() as &[u8])
}
}
impl From<H256> for H160 {
fn from(value: H256) -> H160 {
let mut ret = H160::new();
ret.0.copy_from_slice(&value[12..32]);
ret
}
}
impl From<H256> for H64 {
fn from(value: H256) -> H64 {
let mut ret = H64::new();
ret.0.copy_from_slice(&value[20..28]);
ret
}
}
impl From<H160> for H256 {
fn from(value: H160) -> H256 {
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(&value);
ret
}
}
|
let mut ret = H256::new();
ret.0[12..32].copy_from_slice(value);
ret
}
}
impl_hash!(H32, 4);
impl_hash!(H64, 8);
impl_hash!(H128, 16);
impl_hash!(H160, 20);
impl_hash!(H256, 32);
impl_hash!(H264, 33);
impl_hash!(H512, 64);
impl_hash!(H520, 65);
impl_hash!(H1024, 128);
impl_hash!(H2048, 256);
known_heap_size!(0, H32, H64, H128, H160, H256, H264, H512, H520, H1024, H2048);
// Specialized HashMap and HashSet
/// Hasher that just takes 8 bytes of the provided value.
/// May only be used for keys which are 32 bytes.
pub struct PlainHasher {
prefix: [u8; 8],
_marker: [u64; 0], // for alignment
}
impl Default for PlainHasher {
#[inline]
fn default() -> PlainHasher {
PlainHasher {
prefix: [0; 8],
_marker: [0; 0],
}
}
}
impl Hasher for PlainHasher {
#[inline]
fn finish(&self) -> u64 {
unsafe { ::std::mem::transmute(self.prefix) }
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
debug_assert!(bytes.len() == 32);
for quarter in bytes.chunks(8) {
for (x, y) in self.prefix.iter_mut().zip(quarter) {
*x ^= *y
}
}
}
}
/// Specialized version of `HashMap` with H256 keys and fast hashing function.
pub type H256FastMap<T> = HashMap<H256, T, BuildHasherDefault<PlainHasher>>;
/// Specialized version of `HashSet` with H256 keys and fast hashing function.
pub type H256FastSet = HashSet<H256, BuildHasherDefault<PlainHasher>>;
#[cfg(test)]
mod tests {
use hash::*;
use std::str::FromStr;
#[test]
fn hasher_alignment() {
use std::mem::align_of;
assert_eq!(align_of::<u64>(), align_of::<PlainHasher>());
}
#[test]
#[cfg_attr(feature="dev", allow(eq_op))]
fn hash() {
let h = H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef]);
assert_eq!(H64::from_str("0123456789abcdef").unwrap(), h);
assert_eq!(format!("{}", h), "0123…cdef");
assert_eq!(format!("{:?}", h), "0123456789abcdef");
assert_eq!(h.hex(), "0123456789abcdef");
assert!(h == h);
assert!(h!= H64([0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xee]));
assert!(h!= H64([0; 8]));
}
#[test]
fn hash_bitor() {
let a = H64([1; 8]);
let b = H64([2; 8]);
let c = H64([3; 8]);
// borrow
assert_eq!(&a | &b, c);
// move
assert_eq!(a | b, c);
}
#[test]
fn from_and_to_address() {
let address: H160 = "ef2d6d194084c2de36e0dabfce45d046b37d1106".into();
let h = H256::from(address.clone());
let a = H160::from(h);
assert_eq!(address, a);
}
#[test]
fn from_u64() {
assert_eq!(H128::from(0x1234567890abcdef), H128::from_str("00000000000000001234567890abcdef").unwrap());
assert_eq!(H64::from(0x1234567890abcdef), H64::from_str("1234567890abcdef").unwrap());
assert_eq!(H32::from(0x1234567890abcdef), H32::from_str("90abcdef").unwrap());
}
#[test]
fn from_str() {
assert_eq!(H64::from(0x1234567890abcdef), H64::from("0x1234567890abcdef"));
assert_eq!(H64::from(0x1234567890abcdef), H64::from("1234567890abcdef"));
assert_eq!(H64::from(0x234567890abcdef), H64::from("0x234567890abcdef"));
}
#[test]
fn from_and_to_u256() {
let u: U256 = 0x123456789abcdef0u64.into();
let h = H256::from(u);
assert_eq!(H256::from(u), H256::from("000000000000000000000000000000000000000000000000123456789abcdef0"));
let h_ref = H256::from(&u);
assert_eq!(h, h_ref);
let r_ref: U256 = From::from(&h);
assert_eq!(r_ref, u);
let r: U256 = From::from(h);
assert_eq!(r, u);
}
}
|
impl<'a> From<&'a H160> for H256 {
fn from(value: &'a H160) -> H256 {
|
random_line_split
|
problem11.rs
|
// In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
// The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
//
// What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
fn main() {
let range = 4;
let val = [[08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65],
[52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92],
[16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40],
[04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54],
[01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48]];
println!("Solution: {}", solve(&val, &range));
}
fn solve(vals: &[[i64; 20]; 20], range: &usize) -> (i64){
let mut max: i64 = 0;
for col in 0..vals.len() {
for row in 0..vals[col].len() {
check_vertical(&vals, row, col, *range, &mut max);
check_horizontal(&vals, row, col, *range, &mut max);
check_diagonal_left(&vals, row, col, *range, &mut max);
check_diagonal_right(&vals, row, col, *range, &mut max);
}
}
return max;
}
fn check_vertical(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
|
check_horizontal(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if col <= vals[row].len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_diagonal_left(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if col <= vals.len() - range && row >= range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row - i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_diagonal_right(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if row <= vals[col].len() - range && col <= vals.len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row + i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
|
if row <= vals.len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col][row + i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn
|
identifier_body
|
problem11.rs
|
// In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
// The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
//
// What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
fn main() {
let range = 4;
let val = [[08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65],
[52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92],
[16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40],
[04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54],
[01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48]];
println!("Solution: {}", solve(&val, &range));
}
fn solve(vals: &[[i64; 20]; 20], range: &usize) -> (i64){
let mut max: i64 = 0;
for col in 0..vals.len() {
for row in 0..vals[col].len() {
check_vertical(&vals, row, col, *range, &mut max);
check_horizontal(&vals, row, col, *range, &mut max);
check_diagonal_left(&vals, row, col, *range, &mut max);
check_diagonal_right(&vals, row, col, *range, &mut max);
}
}
return max;
}
fn check_vertical(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if row <= vals.len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col][row + i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_horizontal(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if col <= vals[row].len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row];
}
if product > *curr_max {
*curr_max = product;
}
|
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row - i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_diagonal_right(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if row <= vals[col].len() - range && col <= vals.len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row + i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
|
}
}
fn check_diagonal_left(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if col <= vals.len() - range && row >= range {
|
random_line_split
|
problem11.rs
|
// In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
// The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
//
// What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
fn main() {
let range = 4;
let val = [[08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65],
[52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92],
[16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40],
[04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54],
[01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48]];
println!("Solution: {}", solve(&val, &range));
}
fn solve(vals: &[[i64; 20]; 20], range: &usize) -> (i64){
let mut max: i64 = 0;
for col in 0..vals.len() {
for row in 0..vals[col].len() {
check_vertical(&vals, row, col, *range, &mut max);
check_horizontal(&vals, row, col, *range, &mut max);
check_diagonal_left(&vals, row, col, *range, &mut max);
check_diagonal_right(&vals, row, col, *range, &mut max);
}
}
return max;
}
fn check_vertical(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if row <= vals.len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col][row + i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_horizontal(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if col <= vals[row].len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check
|
: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if col <= vals.len() - range && row >= range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row - i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_diagonal_right(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if row <= vals[col].len() - range && col <= vals.len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row + i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
|
_diagonal_left(vals
|
identifier_name
|
problem11.rs
|
// In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
// The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
//
// What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
fn main() {
let range = 4;
let val = [[08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65],
[52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92],
[16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40],
[04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54],
[01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48]];
println!("Solution: {}", solve(&val, &range));
}
fn solve(vals: &[[i64; 20]; 20], range: &usize) -> (i64){
let mut max: i64 = 0;
for col in 0..vals.len() {
for row in 0..vals[col].len() {
check_vertical(&vals, row, col, *range, &mut max);
check_horizontal(&vals, row, col, *range, &mut max);
check_diagonal_left(&vals, row, col, *range, &mut max);
check_diagonal_right(&vals, row, col, *range, &mut max);
}
}
return max;
}
fn check_vertical(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if row <= vals.len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col][row + i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_horizontal(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if col <= vals[row].len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row];
}
if product > *curr_max {
*curr_max = product;
}
}
}
fn check_diagonal_left(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if col <= vals.len() - range && row >= range {
|
n check_diagonal_right(vals: &[[i64; 20]; 20], row: usize, col: usize, range: usize, curr_max: &mut i64) {
if row <= vals[col].len() - range && col <= vals.len() - range {
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row + i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
|
let mut product: i64 = 1;
for i in 0..range {
product *= vals[col + i][row - i];
}
if product > *curr_max {
*curr_max = product;
}
}
}
f
|
conditional_block
|
borrowck-loan-of-static-data-issue-27616.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem;
fn leak<T>(mut b: Box<T>) -> &'static mut T
|
fn evil(mut s: &'static mut String)
{
// create alias
let alias: &'static mut String = s;
let inner: &str = &alias;
// free value
*s = String::new(); //~ ERROR cannot assign
let _spray = "0wned".to_owned();
//... and then use it
println!("{}", inner);
}
fn main() {
evil(leak(Box::new("hello".to_owned())));
}
|
{
// isn't this supposed to be safe?
let inner = &mut *b as *mut _;
mem::forget(b);
unsafe { &mut *inner }
}
|
identifier_body
|
borrowck-loan-of-static-data-issue-27616.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem;
fn
|
<T>(mut b: Box<T>) -> &'static mut T {
// isn't this supposed to be safe?
let inner = &mut *b as *mut _;
mem::forget(b);
unsafe { &mut *inner }
}
fn evil(mut s: &'static mut String)
{
// create alias
let alias: &'static mut String = s;
let inner: &str = &alias;
// free value
*s = String::new(); //~ ERROR cannot assign
let _spray = "0wned".to_owned();
//... and then use it
println!("{}", inner);
}
fn main() {
evil(leak(Box::new("hello".to_owned())));
}
|
leak
|
identifier_name
|
borrowck-loan-of-static-data-issue-27616.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::mem;
|
}
fn evil(mut s: &'static mut String)
{
// create alias
let alias: &'static mut String = s;
let inner: &str = &alias;
// free value
*s = String::new(); //~ ERROR cannot assign
let _spray = "0wned".to_owned();
//... and then use it
println!("{}", inner);
}
fn main() {
evil(leak(Box::new("hello".to_owned())));
}
|
fn leak<T>(mut b: Box<T>) -> &'static mut T {
// isn't this supposed to be safe?
let inner = &mut *b as *mut _;
mem::forget(b);
unsafe { &mut *inner }
|
random_line_split
|
main.rs
|
/* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations
// Iterator in Rust
fn ma
|
{
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
// `iter()` for vec yields `&i32, Destructure to `i32`
println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2));
// `into_iter()` for vecs yields `i32`, No destructuring required,
println!("2 in vec2: {}", vec2.into_iter().any(| x| x == 2));
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
// `iter()` for arrays yield `&i32`.
println!("2 in array1: {}", array1.iter() .any(|&x| x == 2));
// `into_iter()` for arrays unnusually yields `&i32`
println!("2 in array2; {}", array2.into_iter().any(|&x| x == 2));
}
|
in()
|
identifier_name
|
main.rs
|
/* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations
// Iterator in Rust
fn main() {
|
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
// `iter()` for vec yields `&i32, Destructure to `i32`
println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2));
// `into_iter()` for vecs yields `i32`, No destructuring required,
println!("2 in vec2: {}", vec2.into_iter().any(| x| x == 2));
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
// `iter()` for arrays yield `&i32`.
println!("2 in array1: {}", array1.iter() .any(|&x| x == 2));
// `into_iter()` for arrays unnusually yields `&i32`
println!("2 in array2; {}", array2.into_iter().any(|&x| x == 2));
}
|
identifier_body
|
|
main.rs
|
/* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations
// Iterator in Rust
fn main() {
let vec1 = vec![1, 2, 3];
let vec2 = vec![4, 5, 6];
// `iter()` for vec yields `&i32, Destructure to `i32`
println!("2 in vec1: {}", vec1.iter() .any(|&x| x == 2));
// `into_iter()` for vecs yields `i32`, No destructuring required,
println!("2 in vec2: {}", vec2.into_iter().any(| x| x == 2));
let array1 = [1, 2, 3];
let array2 = [4, 5, 6];
// `iter()` for arrays yield `&i32`.
|
println!("2 in array1: {}", array1.iter() .any(|&x| x == 2));
// `into_iter()` for arrays unnusually yields `&i32`
println!("2 in array2; {}", array2.into_iter().any(|&x| x == 2));
}
|
random_line_split
|
|
const-vecs-and-slices.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.
static x : [isize; 4] = [1,2,3,4];
static y : &'static [isize] = &[1,2,3,4];
static z : &'static [isize; 4] = &[1,2,3,4];
static zz : &'static [isize] = &[1,2,3,4];
pub fn main()
|
{
println!("{}", x[1]);
println!("{}", y[1]);
println!("{}", z[1]);
println!("{}", zz[1]);
assert_eq!(x[1], 2);
assert_eq!(x[3], 4);
assert_eq!(x[3], y[3]);
assert_eq!(z[1], 2);
assert_eq!(z[3], 4);
assert_eq!(z[3], y[3]);
assert_eq!(zz[1], 2);
assert_eq!(zz[3], 4);
assert_eq!(zz[3], y[3]);
}
|
identifier_body
|
|
const-vecs-and-slices.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
|
static z : &'static [isize; 4] = &[1,2,3,4];
static zz : &'static [isize] = &[1,2,3,4];
pub fn main() {
println!("{}", x[1]);
println!("{}", y[1]);
println!("{}", z[1]);
println!("{}", zz[1]);
assert_eq!(x[1], 2);
assert_eq!(x[3], 4);
assert_eq!(x[3], y[3]);
assert_eq!(z[1], 2);
assert_eq!(z[3], 4);
assert_eq!(z[3], y[3]);
assert_eq!(zz[1], 2);
assert_eq!(zz[3], 4);
assert_eq!(zz[3], y[3]);
}
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
static x : [isize; 4] = [1,2,3,4];
static y : &'static [isize] = &[1,2,3,4];
|
random_line_split
|
const-vecs-and-slices.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.
static x : [isize; 4] = [1,2,3,4];
static y : &'static [isize] = &[1,2,3,4];
static z : &'static [isize; 4] = &[1,2,3,4];
static zz : &'static [isize] = &[1,2,3,4];
pub fn
|
() {
println!("{}", x[1]);
println!("{}", y[1]);
println!("{}", z[1]);
println!("{}", zz[1]);
assert_eq!(x[1], 2);
assert_eq!(x[3], 4);
assert_eq!(x[3], y[3]);
assert_eq!(z[1], 2);
assert_eq!(z[3], 4);
assert_eq!(z[3], y[3]);
assert_eq!(zz[1], 2);
assert_eq!(zz[3], 4);
assert_eq!(zz[3], y[3]);
}
|
main
|
identifier_name
|
totaleq.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.
use ast::{MetaItem, item, Expr};
use codemap::Span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
pub fn expand_deriving_totaleq(cx: @ExtCtxt,
span: Span,
mitem: @MetaItem,
in_items: ~[@item]) -> ~[@item] {
fn cs_equals(cx: @ExtCtxt, span: Span, substr: &Substructure) -> @Expr {
cs_and(|cx, span, _, _| cx.expr_bool(span, false),
cx, span, substr)
}
let trait_def = TraitDef {
cx: cx, span: span,
path: Path::new(~["std", "cmp", "TotalEq"]),
additional_bounds: ~[],
generics: LifetimeBounds::empty(),
methods: ~[
MethodDef {
name: "equals",
generics: LifetimeBounds::empty(),
|
const_nonmatching: true,
combine_substructure: cs_equals
}
]
};
trait_def.expand(mitem, in_items)
}
|
explicit_self: borrowed_explicit_self(),
args: ~[borrowed_self()],
ret_ty: Literal(Path::new(~["bool"])),
inline: true,
|
random_line_split
|
lock.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use core::ty::Unsafe;
use core::option::Option::{self, Some, None};
use core::ops::Drop;
use core::kinds::Share;
/// A lock. Note that this disables interrupts. Consequently, a task
/// dying (e.g. by running out of stack space) while holding a lock
/// may cause a deadlock.
pub struct Lock {
locked: Unsafe<bool>
}
#[must_use]
pub struct Guard<'a>(&'a Lock);
pub static STATIC_LOCK: Lock = Lock { locked: Unsafe { value: false, marker1: InvariantType } };
impl Lock {
pub fn new() -> Lock {
Lock { locked: Unsafe::new(false) }
}
pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> {
unsafe {
let crit = NoInterrupts::new();
let locked = self.locked.get();
match *locked {
true => return None,
false => {
*locked = true;
return Some(Guard(self));
}
}
}
}
fn
|
<'a>(&'a self) {
unsafe {
let crit = NoInterrupts::new();
*self.locked.get() = false;
}
}
}
#[unsafe_destructor]
impl<'a> Drop for Guard<'a> {
fn drop(&mut self) {
let &Guard(ref lock) = self;
lock.unlock();
}
}
impl Share for Lock { }
|
unlock
|
identifier_name
|
lock.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[email protected]>
//
|
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use core::ty::Unsafe;
use core::option::Option::{self, Some, None};
use core::ops::Drop;
use core::kinds::Share;
/// A lock. Note that this disables interrupts. Consequently, a task
/// dying (e.g. by running out of stack space) while holding a lock
/// may cause a deadlock.
pub struct Lock {
locked: Unsafe<bool>
}
#[must_use]
pub struct Guard<'a>(&'a Lock);
pub static STATIC_LOCK: Lock = Lock { locked: Unsafe { value: false, marker1: InvariantType } };
impl Lock {
pub fn new() -> Lock {
Lock { locked: Unsafe::new(false) }
}
pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> {
unsafe {
let crit = NoInterrupts::new();
let locked = self.locked.get();
match *locked {
true => return None,
false => {
*locked = true;
return Some(Guard(self));
}
}
}
}
fn unlock<'a>(&'a self) {
unsafe {
let crit = NoInterrupts::new();
*self.locked.get() = false;
}
}
}
#[unsafe_destructor]
impl<'a> Drop for Guard<'a> {
fn drop(&mut self) {
let &Guard(ref lock) = self;
lock.unlock();
}
}
impl Share for Lock { }
|
// 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
//
|
random_line_split
|
lock.rs
|
// Zinc, the bare metal stack for rust.
// Copyright 2014 Ben Gamari <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use core::ty::Unsafe;
use core::option::Option::{self, Some, None};
use core::ops::Drop;
use core::kinds::Share;
/// A lock. Note that this disables interrupts. Consequently, a task
/// dying (e.g. by running out of stack space) while holding a lock
/// may cause a deadlock.
pub struct Lock {
locked: Unsafe<bool>
}
#[must_use]
pub struct Guard<'a>(&'a Lock);
pub static STATIC_LOCK: Lock = Lock { locked: Unsafe { value: false, marker1: InvariantType } };
impl Lock {
pub fn new() -> Lock {
Lock { locked: Unsafe::new(false) }
}
pub fn try_lock<'a>(&'a self) -> Option<Guard<'a>> {
unsafe {
let crit = NoInterrupts::new();
let locked = self.locked.get();
match *locked {
true => return None,
false =>
|
}
}
}
fn unlock<'a>(&'a self) {
unsafe {
let crit = NoInterrupts::new();
*self.locked.get() = false;
}
}
}
#[unsafe_destructor]
impl<'a> Drop for Guard<'a> {
fn drop(&mut self) {
let &Guard(ref lock) = self;
lock.unlock();
}
}
impl Share for Lock { }
|
{
*locked = true;
return Some(Guard(self));
}
|
conditional_block
|
variadic-ffi.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.
extern crate libc;
use std::ffi::{self, CString};
use libc::{c_char, c_int};
// ignore-fast doesn't like extern crate
extern {
fn sprintf(s: *mut c_char, format: *const c_char,...) -> c_int;
}
unsafe fn check<T, F>(expected: &str, f: F) where F: FnOnce(*mut c_char) -> T {
let mut x = [0 as c_char; 50];
f(&mut x[0] as *mut c_char);
assert_eq!(expected.as_bytes(), ffi::c_str_to_bytes(&x.as_ptr()));
}
pub fn main() {
unsafe {
// Call with just the named parameter
let c = CString::from_slice(b"Hello World\n");
check("Hello World\n", |s| sprintf(s, c.as_ptr()));
|
check("42 42.500000 a %d %f %c %s\n\n", |s| {
sprintf(s, c.as_ptr(), 42i, 42.5f64, 'a' as c_int, c.as_ptr());
});
// Make a function pointer
let x: unsafe extern fn(*mut c_char, *const c_char,...) -> c_int = sprintf;
// A function that takes a function pointer
unsafe fn call(p: unsafe extern fn(*mut c_char, *const c_char,...) -> c_int) {
// Call with just the named parameter
let c = CString::from_slice(b"Hello World\n");
check("Hello World\n", |s| sprintf(s, c.as_ptr()));
// Call with variable number of arguments
let c = CString::from_slice(b"%d %f %c %s\n");
check("42 42.500000 a %d %f %c %s\n\n", |s| {
sprintf(s, c.as_ptr(), 42i, 42.5f64, 'a' as c_int, c.as_ptr());
});
}
// Pass sprintf directly
call(sprintf);
// Pass sprintf indirectly
call(x);
}
}
|
// Call with variable number of arguments
let c = CString::from_slice(b"%d %f %c %s\n");
|
random_line_split
|
variadic-ffi.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.
extern crate libc;
use std::ffi::{self, CString};
use libc::{c_char, c_int};
// ignore-fast doesn't like extern crate
extern {
fn sprintf(s: *mut c_char, format: *const c_char,...) -> c_int;
}
unsafe fn check<T, F>(expected: &str, f: F) where F: FnOnce(*mut c_char) -> T {
let mut x = [0 as c_char; 50];
f(&mut x[0] as *mut c_char);
assert_eq!(expected.as_bytes(), ffi::c_str_to_bytes(&x.as_ptr()));
}
pub fn
|
() {
unsafe {
// Call with just the named parameter
let c = CString::from_slice(b"Hello World\n");
check("Hello World\n", |s| sprintf(s, c.as_ptr()));
// Call with variable number of arguments
let c = CString::from_slice(b"%d %f %c %s\n");
check("42 42.500000 a %d %f %c %s\n\n", |s| {
sprintf(s, c.as_ptr(), 42i, 42.5f64, 'a' as c_int, c.as_ptr());
});
// Make a function pointer
let x: unsafe extern fn(*mut c_char, *const c_char,...) -> c_int = sprintf;
// A function that takes a function pointer
unsafe fn call(p: unsafe extern fn(*mut c_char, *const c_char,...) -> c_int) {
// Call with just the named parameter
let c = CString::from_slice(b"Hello World\n");
check("Hello World\n", |s| sprintf(s, c.as_ptr()));
// Call with variable number of arguments
let c = CString::from_slice(b"%d %f %c %s\n");
check("42 42.500000 a %d %f %c %s\n\n", |s| {
sprintf(s, c.as_ptr(), 42i, 42.5f64, 'a' as c_int, c.as_ptr());
});
}
// Pass sprintf directly
call(sprintf);
// Pass sprintf indirectly
call(x);
}
}
|
main
|
identifier_name
|
variadic-ffi.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.
extern crate libc;
use std::ffi::{self, CString};
use libc::{c_char, c_int};
// ignore-fast doesn't like extern crate
extern {
fn sprintf(s: *mut c_char, format: *const c_char,...) -> c_int;
}
unsafe fn check<T, F>(expected: &str, f: F) where F: FnOnce(*mut c_char) -> T {
let mut x = [0 as c_char; 50];
f(&mut x[0] as *mut c_char);
assert_eq!(expected.as_bytes(), ffi::c_str_to_bytes(&x.as_ptr()));
}
pub fn main()
|
check("Hello World\n", |s| sprintf(s, c.as_ptr()));
// Call with variable number of arguments
let c = CString::from_slice(b"%d %f %c %s\n");
check("42 42.500000 a %d %f %c %s\n\n", |s| {
sprintf(s, c.as_ptr(), 42i, 42.5f64, 'a' as c_int, c.as_ptr());
});
}
// Pass sprintf directly
call(sprintf);
// Pass sprintf indirectly
call(x);
}
}
|
{
unsafe {
// Call with just the named parameter
let c = CString::from_slice(b"Hello World\n");
check("Hello World\n", |s| sprintf(s, c.as_ptr()));
// Call with variable number of arguments
let c = CString::from_slice(b"%d %f %c %s\n");
check("42 42.500000 a %d %f %c %s\n\n", |s| {
sprintf(s, c.as_ptr(), 42i, 42.5f64, 'a' as c_int, c.as_ptr());
});
// Make a function pointer
let x: unsafe extern fn(*mut c_char, *const c_char, ...) -> c_int = sprintf;
// A function that takes a function pointer
unsafe fn call(p: unsafe extern fn(*mut c_char, *const c_char, ...) -> c_int) {
// Call with just the named parameter
let c = CString::from_slice(b"Hello World\n");
|
identifier_body
|
trait-bounds-on-structs-and-enums-xc1.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:trait_bounds_on_structs_and_enums_xc.rs
extern crate trait_bounds_on_structs_and_enums_xc;
use trait_bounds_on_structs_and_enums_xc::{Bar, Foo, Trait};
fn main()
|
{
let foo = Foo {
//~^ ERROR not implemented
x: 3i
};
let bar: Bar<f64> = return;
//~^ ERROR not implemented
let _ = bar;
}
|
identifier_body
|
|
trait-bounds-on-structs-and-enums-xc1.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.
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:trait_bounds_on_structs_and_enums_xc.rs
extern crate trait_bounds_on_structs_and_enums_xc;
use trait_bounds_on_structs_and_enums_xc::{Bar, Foo, Trait};
fn main() {
let foo = Foo {
//~^ ERROR not implemented
x: 3i
};
let bar: Bar<f64> = return;
//~^ ERROR not implemented
let _ = bar;
}
|
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
random_line_split
|
trait-bounds-on-structs-and-enums-xc1.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:trait_bounds_on_structs_and_enums_xc.rs
extern crate trait_bounds_on_structs_and_enums_xc;
use trait_bounds_on_structs_and_enums_xc::{Bar, Foo, Trait};
fn
|
() {
let foo = Foo {
//~^ ERROR not implemented
x: 3i
};
let bar: Bar<f64> = return;
//~^ ERROR not implemented
let _ = bar;
}
|
main
|
identifier_name
|
issue-21726.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Regression test for #21726: an issue arose around the rules for
// subtyping of projection types that resulted in an unconstrained
// region, yielding region inference failures.
fn main() { }
fn foo<'a>(s: &'a str) {
let b: B<()> = B::new(s, ());
b.get_short();
}
trait IntoRef<'a> {
type T: Clone;
fn into_ref(self, &'a str) -> Self::T;
}
impl<'a> IntoRef<'a> for () {
type T = &'a str;
fn into_ref(self, s: &'a str) -> &'a str {
s
}
}
struct B<'a, P: IntoRef<'a>>(P::T);
impl<'a, P: IntoRef<'a>> B<'a, P> {
fn new(s: &'a str, i: P) -> B<'a, P> {
B(i.into_ref(s))
}
fn get_short(&self) -> P::T {
self.0.clone()
}
}
|
// 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
|
random_line_split
|
issue-21726.rs
|
// Copyright 2015 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.
// Regression test for #21726: an issue arose around the rules for
// subtyping of projection types that resulted in an unconstrained
// region, yielding region inference failures.
fn main() { }
fn foo<'a>(s: &'a str) {
let b: B<()> = B::new(s, ());
b.get_short();
}
trait IntoRef<'a> {
type T: Clone;
fn into_ref(self, &'a str) -> Self::T;
}
impl<'a> IntoRef<'a> for () {
type T = &'a str;
fn into_ref(self, s: &'a str) -> &'a str {
s
}
}
struct B<'a, P: IntoRef<'a>>(P::T);
impl<'a, P: IntoRef<'a>> B<'a, P> {
fn new(s: &'a str, i: P) -> B<'a, P> {
B(i.into_ref(s))
}
fn
|
(&self) -> P::T {
self.0.clone()
}
}
|
get_short
|
identifier_name
|
issue-21726.rs
|
// Copyright 2015 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.
// Regression test for #21726: an issue arose around the rules for
// subtyping of projection types that resulted in an unconstrained
// region, yielding region inference failures.
fn main() { }
fn foo<'a>(s: &'a str) {
let b: B<()> = B::new(s, ());
b.get_short();
}
trait IntoRef<'a> {
type T: Clone;
fn into_ref(self, &'a str) -> Self::T;
}
impl<'a> IntoRef<'a> for () {
type T = &'a str;
fn into_ref(self, s: &'a str) -> &'a str
|
}
struct B<'a, P: IntoRef<'a>>(P::T);
impl<'a, P: IntoRef<'a>> B<'a, P> {
fn new(s: &'a str, i: P) -> B<'a, P> {
B(i.into_ref(s))
}
fn get_short(&self) -> P::T {
self.0.clone()
}
}
|
{
s
}
|
identifier_body
|
lib.rs
|
/*
* Copyright (c) 2018 Boucher, Antoni <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use std::cell::RefCell;
use std::rc::Rc;
use enigo::{Enigo, KeyboardControllable, MouseButton, MouseControllable};
use gdk::keys::Key;
use gdk::keys::constants as key;
use glib::{IsA, Object, object::Cast};
use gtk::{prelude::*, Inhibit, ToolButton, Widget};
use gtk_test::{self, focus, mouse_move, run_loop, wait_for_draw};
use relm::StreamHandle;
// TODO: should remove the signal after wait()?
// FIXME: remove when it's in gtk-test.
macro_rules! gtk_observer_new {
($widget:expr, $signal_name:ident, |$e1:pat $(,$e:pat)*|) => {{
let observer = gtk_test::Observer::new();
let res = (*observer.get_inner()).clone();
$widget.$signal_name(move |$e1 $(,$e:expr)*| {
*res.borrow_mut() = true;
});
observer
}};
($widget:expr, $signal_name:ident, |$e1:pat $(,$e:pat)*| $block:block) => {{
let observer = gtk_test::Observer::new();
let res = (*observer.get_inner()).clone();
$widget.$signal_name(move |$e1 $(,$e)*| {
*res.borrow_mut() = true;
$block
});
observer
}}
}
pub struct Observer<MSG> {
result: Rc<RefCell<Option<MSG>>>,
}
impl<MSG: Clone +'static> Observer<MSG> {
pub fn new<F: Fn(&MSG) -> bool +'static>(stream: StreamHandle<MSG>, predicate: F) -> Self {
let result = Rc::new(RefCell::new(None));
let res = result.clone();
stream.observe(move |msg| {
if predicate(msg) {
*res.borrow_mut() = Some(msg.clone());
}
});
Self {
result,
}
}
pub fn wait(&self) -> MSG {
loop {
if let Ok(ref result) = self.result.try_borrow() {
if result.is_some() {
break;
}
}
gtk_test::run_loop();
}
self.result.borrow_mut().take()
.expect("Message to take")
}
}
#[macro_export]
macro_rules! relm_observer_new {
($component:expr, $pat:pat) => {
$crate::Observer::new($component.stream(), |msg|
if let $pat = msg {
true
}
else {
false
}
);
};
}
#[macro_export]
macro_rules! relm_observer_wait {
(let $($variant:ident)::*($name1:ident, $name2:ident $(,$rest:ident)*) = $observer:expr) => {
let ($name1, $name2 $(, $rest)*) = {
let msg = $observer.wait();
if let $($variant)::*($name1, $name2 $(, $rest)*) = msg {
($name1, $name2 $(, $rest)*)
}
else {
panic!("Wrong message type.");
}
};
};
(let $($variant:ident)::*($name:ident) = $observer:expr) => {
let $name = {
let msg = $observer.wait();
if let $($variant)::*($name) = msg {
$name
}
else {
panic!("Wrong message type.");
}
};
};
(let $($variant:ident)::* = $observer:expr) => {
let () = {
let msg = $observer.wait();
if let $($variant)::* = msg {
()
}
else {
panic!("Wrong message type.");
}
};
};
}
// FIXME: remove when it's in gtk-test.
pub fn click<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt + IsA<W>>(widget: &W) {
wait_for_draw(widget, || {
let observer =
if let Ok(tool_button) = widget.clone().dynamic_cast::<ToolButton>() {
gtk_observer_new!(tool_button, connect_clicked, |_|)
}
else {
gtk_observer_new!(widget, connect_button_press_event, |_, _| {
Inhibit(false)
})
};
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
let mut enigo = Enigo::new();
enigo.mouse_click(MouseButton::Left);
observer.wait();
wait_for_relm_events();
});
}
pub fn
|
<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt + IsA<W>>(widget: &W) {
wait_for_draw(widget, || {
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
wait_for_relm_events();
});
}
pub fn double_click<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_button_release_event, |_, _| {
Inhibit(false)
});
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
let mut enigo = Enigo::new();
enigo.mouse_click(MouseButton::Left);
observer.wait();
let observer = gtk_observer_new!(widget, connect_button_release_event, |_, _| {
Inhibit(false)
});
enigo.mouse_click(MouseButton::Left);
observer.wait();
wait_for_relm_events();
});
}
// FIXME: don't wait the observer for modifier keys like shift?
pub fn key_press<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_press_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_down(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn key_release<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_up(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn enter_key<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_click(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn enter_keys<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, text: &str) {
wait_for_draw(widget, || {
focus(widget);
let mut enigo = Enigo::new();
for char in text.chars() {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
enigo.key_sequence(&char.to_string());
observer.wait();
}
wait_for_relm_events();
});
}
fn wait_for_relm_events() {
gtk_test::wait(1);
while gtk::events_pending() {
run_loop();
gtk_test::wait(1);
}
}
fn gdk_key_to_enigo_key(key: Key) -> enigo::Key {
use enigo::Key::*;
match key {
key::Return => Return,
key::Tab => Tab,
key::space => Space,
key::BackSpace => Backspace,
key::Escape => Escape,
key::Super_L | key::Super_R => Meta,
key::Control_L | key::Control_R => Control,
key::Shift_L | key::Shift_R => Shift,
key::Shift_Lock => CapsLock,
key::Alt_L | key::Alt_R => Alt,
key::Option => Option,
key::End => End,
key::Home => Home,
key::Page_Down => PageDown,
key::Page_Up => PageUp,
key::leftarrow => LeftArrow,
key::rightarrow => RightArrow,
key::downarrow => DownArrow,
key::uparrow => UpArrow,
key::F1 => F1,
key::F2 => F2,
key::F3 => F3,
key::F4 => F4,
key::F5 => F5,
key::F6 => F6,
key::F7 => F7,
key::F8 => F8,
key::F9 => F9,
key::F10 => F10,
key::F11 => F11,
key::F12 => F12,
_ => {
if let Some(char) = key.to_unicode() {
Layout(char)
}
else {
Raw(*key as u16)
}
},
}
}
|
mouse_move_to
|
identifier_name
|
lib.rs
|
/*
* Copyright (c) 2018 Boucher, Antoni <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use std::cell::RefCell;
use std::rc::Rc;
use enigo::{Enigo, KeyboardControllable, MouseButton, MouseControllable};
use gdk::keys::Key;
use gdk::keys::constants as key;
use glib::{IsA, Object, object::Cast};
use gtk::{prelude::*, Inhibit, ToolButton, Widget};
use gtk_test::{self, focus, mouse_move, run_loop, wait_for_draw};
use relm::StreamHandle;
// TODO: should remove the signal after wait()?
// FIXME: remove when it's in gtk-test.
macro_rules! gtk_observer_new {
($widget:expr, $signal_name:ident, |$e1:pat $(,$e:pat)*|) => {{
let observer = gtk_test::Observer::new();
let res = (*observer.get_inner()).clone();
$widget.$signal_name(move |$e1 $(,$e:expr)*| {
*res.borrow_mut() = true;
});
observer
}};
($widget:expr, $signal_name:ident, |$e1:pat $(,$e:pat)*| $block:block) => {{
let observer = gtk_test::Observer::new();
let res = (*observer.get_inner()).clone();
$widget.$signal_name(move |$e1 $(,$e)*| {
*res.borrow_mut() = true;
$block
});
observer
}}
}
pub struct Observer<MSG> {
result: Rc<RefCell<Option<MSG>>>,
}
impl<MSG: Clone +'static> Observer<MSG> {
pub fn new<F: Fn(&MSG) -> bool +'static>(stream: StreamHandle<MSG>, predicate: F) -> Self {
let result = Rc::new(RefCell::new(None));
let res = result.clone();
stream.observe(move |msg| {
if predicate(msg) {
*res.borrow_mut() = Some(msg.clone());
}
});
Self {
result,
}
}
pub fn wait(&self) -> MSG {
loop {
if let Ok(ref result) = self.result.try_borrow() {
if result.is_some() {
break;
}
}
gtk_test::run_loop();
}
self.result.borrow_mut().take()
.expect("Message to take")
}
}
#[macro_export]
macro_rules! relm_observer_new {
($component:expr, $pat:pat) => {
$crate::Observer::new($component.stream(), |msg|
if let $pat = msg {
true
}
else {
false
}
);
};
}
#[macro_export]
macro_rules! relm_observer_wait {
(let $($variant:ident)::*($name1:ident, $name2:ident $(,$rest:ident)*) = $observer:expr) => {
let ($name1, $name2 $(, $rest)*) = {
let msg = $observer.wait();
if let $($variant)::*($name1, $name2 $(, $rest)*) = msg {
($name1, $name2 $(, $rest)*)
}
else {
panic!("Wrong message type.");
}
};
};
(let $($variant:ident)::*($name:ident) = $observer:expr) => {
let $name = {
let msg = $observer.wait();
if let $($variant)::*($name) = msg {
$name
}
else {
panic!("Wrong message type.");
}
};
};
(let $($variant:ident)::* = $observer:expr) => {
let () = {
let msg = $observer.wait();
if let $($variant)::* = msg {
()
}
else {
panic!("Wrong message type.");
}
};
};
}
// FIXME: remove when it's in gtk-test.
pub fn click<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt + IsA<W>>(widget: &W) {
wait_for_draw(widget, || {
let observer =
if let Ok(tool_button) = widget.clone().dynamic_cast::<ToolButton>() {
gtk_observer_new!(tool_button, connect_clicked, |_|)
}
else {
gtk_observer_new!(widget, connect_button_press_event, |_, _| {
Inhibit(false)
})
};
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
let mut enigo = Enigo::new();
enigo.mouse_click(MouseButton::Left);
observer.wait();
wait_for_relm_events();
});
}
pub fn mouse_move_to<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt + IsA<W>>(widget: &W) {
wait_for_draw(widget, || {
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
wait_for_relm_events();
|
}
pub fn double_click<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_button_release_event, |_, _| {
Inhibit(false)
});
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
let mut enigo = Enigo::new();
enigo.mouse_click(MouseButton::Left);
observer.wait();
let observer = gtk_observer_new!(widget, connect_button_release_event, |_, _| {
Inhibit(false)
});
enigo.mouse_click(MouseButton::Left);
observer.wait();
wait_for_relm_events();
});
}
// FIXME: don't wait the observer for modifier keys like shift?
pub fn key_press<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_press_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_down(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn key_release<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_up(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn enter_key<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_click(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn enter_keys<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, text: &str) {
wait_for_draw(widget, || {
focus(widget);
let mut enigo = Enigo::new();
for char in text.chars() {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
enigo.key_sequence(&char.to_string());
observer.wait();
}
wait_for_relm_events();
});
}
fn wait_for_relm_events() {
gtk_test::wait(1);
while gtk::events_pending() {
run_loop();
gtk_test::wait(1);
}
}
fn gdk_key_to_enigo_key(key: Key) -> enigo::Key {
use enigo::Key::*;
match key {
key::Return => Return,
key::Tab => Tab,
key::space => Space,
key::BackSpace => Backspace,
key::Escape => Escape,
key::Super_L | key::Super_R => Meta,
key::Control_L | key::Control_R => Control,
key::Shift_L | key::Shift_R => Shift,
key::Shift_Lock => CapsLock,
key::Alt_L | key::Alt_R => Alt,
key::Option => Option,
key::End => End,
key::Home => Home,
key::Page_Down => PageDown,
key::Page_Up => PageUp,
key::leftarrow => LeftArrow,
key::rightarrow => RightArrow,
key::downarrow => DownArrow,
key::uparrow => UpArrow,
key::F1 => F1,
key::F2 => F2,
key::F3 => F3,
key::F4 => F4,
key::F5 => F5,
key::F6 => F6,
key::F7 => F7,
key::F8 => F8,
key::F9 => F9,
key::F10 => F10,
key::F11 => F11,
key::F12 => F12,
_ => {
if let Some(char) = key.to_unicode() {
Layout(char)
}
else {
Raw(*key as u16)
}
},
}
}
|
});
|
random_line_split
|
lib.rs
|
/*
* Copyright (c) 2018 Boucher, Antoni <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use std::cell::RefCell;
use std::rc::Rc;
use enigo::{Enigo, KeyboardControllable, MouseButton, MouseControllable};
use gdk::keys::Key;
use gdk::keys::constants as key;
use glib::{IsA, Object, object::Cast};
use gtk::{prelude::*, Inhibit, ToolButton, Widget};
use gtk_test::{self, focus, mouse_move, run_loop, wait_for_draw};
use relm::StreamHandle;
// TODO: should remove the signal after wait()?
// FIXME: remove when it's in gtk-test.
macro_rules! gtk_observer_new {
($widget:expr, $signal_name:ident, |$e1:pat $(,$e:pat)*|) => {{
let observer = gtk_test::Observer::new();
let res = (*observer.get_inner()).clone();
$widget.$signal_name(move |$e1 $(,$e:expr)*| {
*res.borrow_mut() = true;
});
observer
}};
($widget:expr, $signal_name:ident, |$e1:pat $(,$e:pat)*| $block:block) => {{
let observer = gtk_test::Observer::new();
let res = (*observer.get_inner()).clone();
$widget.$signal_name(move |$e1 $(,$e)*| {
*res.borrow_mut() = true;
$block
});
observer
}}
}
pub struct Observer<MSG> {
result: Rc<RefCell<Option<MSG>>>,
}
impl<MSG: Clone +'static> Observer<MSG> {
pub fn new<F: Fn(&MSG) -> bool +'static>(stream: StreamHandle<MSG>, predicate: F) -> Self {
let result = Rc::new(RefCell::new(None));
let res = result.clone();
stream.observe(move |msg| {
if predicate(msg) {
*res.borrow_mut() = Some(msg.clone());
}
});
Self {
result,
}
}
pub fn wait(&self) -> MSG {
loop {
if let Ok(ref result) = self.result.try_borrow() {
if result.is_some() {
break;
}
}
gtk_test::run_loop();
}
self.result.borrow_mut().take()
.expect("Message to take")
}
}
#[macro_export]
macro_rules! relm_observer_new {
($component:expr, $pat:pat) => {
$crate::Observer::new($component.stream(), |msg|
if let $pat = msg {
true
}
else {
false
}
);
};
}
#[macro_export]
macro_rules! relm_observer_wait {
(let $($variant:ident)::*($name1:ident, $name2:ident $(,$rest:ident)*) = $observer:expr) => {
let ($name1, $name2 $(, $rest)*) = {
let msg = $observer.wait();
if let $($variant)::*($name1, $name2 $(, $rest)*) = msg {
($name1, $name2 $(, $rest)*)
}
else {
panic!("Wrong message type.");
}
};
};
(let $($variant:ident)::*($name:ident) = $observer:expr) => {
let $name = {
let msg = $observer.wait();
if let $($variant)::*($name) = msg {
$name
}
else {
panic!("Wrong message type.");
}
};
};
(let $($variant:ident)::* = $observer:expr) => {
let () = {
let msg = $observer.wait();
if let $($variant)::* = msg {
()
}
else {
panic!("Wrong message type.");
}
};
};
}
// FIXME: remove when it's in gtk-test.
pub fn click<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt + IsA<W>>(widget: &W) {
wait_for_draw(widget, || {
let observer =
if let Ok(tool_button) = widget.clone().dynamic_cast::<ToolButton>() {
gtk_observer_new!(tool_button, connect_clicked, |_|)
}
else {
gtk_observer_new!(widget, connect_button_press_event, |_, _| {
Inhibit(false)
})
};
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
let mut enigo = Enigo::new();
enigo.mouse_click(MouseButton::Left);
observer.wait();
wait_for_relm_events();
});
}
pub fn mouse_move_to<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt + IsA<W>>(widget: &W) {
wait_for_draw(widget, || {
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
wait_for_relm_events();
});
}
pub fn double_click<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_button_release_event, |_, _| {
Inhibit(false)
});
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
let mut enigo = Enigo::new();
enigo.mouse_click(MouseButton::Left);
observer.wait();
let observer = gtk_observer_new!(widget, connect_button_release_event, |_, _| {
Inhibit(false)
});
enigo.mouse_click(MouseButton::Left);
observer.wait();
wait_for_relm_events();
});
}
// FIXME: don't wait the observer for modifier keys like shift?
pub fn key_press<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_press_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_down(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn key_release<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_up(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn enter_key<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_click(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn enter_keys<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, text: &str) {
wait_for_draw(widget, || {
focus(widget);
let mut enigo = Enigo::new();
for char in text.chars() {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
enigo.key_sequence(&char.to_string());
observer.wait();
}
wait_for_relm_events();
});
}
fn wait_for_relm_events() {
gtk_test::wait(1);
while gtk::events_pending() {
run_loop();
gtk_test::wait(1);
}
}
fn gdk_key_to_enigo_key(key: Key) -> enigo::Key {
use enigo::Key::*;
match key {
key::Return => Return,
key::Tab => Tab,
key::space => Space,
key::BackSpace => Backspace,
key::Escape => Escape,
key::Super_L | key::Super_R => Meta,
key::Control_L | key::Control_R => Control,
key::Shift_L | key::Shift_R => Shift,
key::Shift_Lock => CapsLock,
key::Alt_L | key::Alt_R => Alt,
key::Option => Option,
key::End => End,
key::Home => Home,
key::Page_Down => PageDown,
key::Page_Up => PageUp,
key::leftarrow => LeftArrow,
key::rightarrow => RightArrow,
key::downarrow => DownArrow,
key::uparrow => UpArrow,
key::F1 => F1,
key::F2 => F2,
key::F3 => F3,
key::F4 => F4,
key::F5 => F5,
key::F6 => F6,
key::F7 => F7,
key::F8 => F8,
key::F9 => F9,
key::F10 => F10,
key::F11 => F11,
key::F12 => F12,
_ =>
|
,
}
}
|
{
if let Some(char) = key.to_unicode() {
Layout(char)
}
else {
Raw(*key as u16)
}
}
|
conditional_block
|
lib.rs
|
/*
* Copyright (c) 2018 Boucher, Antoni <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
use std::cell::RefCell;
use std::rc::Rc;
use enigo::{Enigo, KeyboardControllable, MouseButton, MouseControllable};
use gdk::keys::Key;
use gdk::keys::constants as key;
use glib::{IsA, Object, object::Cast};
use gtk::{prelude::*, Inhibit, ToolButton, Widget};
use gtk_test::{self, focus, mouse_move, run_loop, wait_for_draw};
use relm::StreamHandle;
// TODO: should remove the signal after wait()?
// FIXME: remove when it's in gtk-test.
macro_rules! gtk_observer_new {
($widget:expr, $signal_name:ident, |$e1:pat $(,$e:pat)*|) => {{
let observer = gtk_test::Observer::new();
let res = (*observer.get_inner()).clone();
$widget.$signal_name(move |$e1 $(,$e:expr)*| {
*res.borrow_mut() = true;
});
observer
}};
($widget:expr, $signal_name:ident, |$e1:pat $(,$e:pat)*| $block:block) => {{
let observer = gtk_test::Observer::new();
let res = (*observer.get_inner()).clone();
$widget.$signal_name(move |$e1 $(,$e)*| {
*res.borrow_mut() = true;
$block
});
observer
}}
}
pub struct Observer<MSG> {
result: Rc<RefCell<Option<MSG>>>,
}
impl<MSG: Clone +'static> Observer<MSG> {
pub fn new<F: Fn(&MSG) -> bool +'static>(stream: StreamHandle<MSG>, predicate: F) -> Self {
let result = Rc::new(RefCell::new(None));
let res = result.clone();
stream.observe(move |msg| {
if predicate(msg) {
*res.borrow_mut() = Some(msg.clone());
}
});
Self {
result,
}
}
pub fn wait(&self) -> MSG {
loop {
if let Ok(ref result) = self.result.try_borrow() {
if result.is_some() {
break;
}
}
gtk_test::run_loop();
}
self.result.borrow_mut().take()
.expect("Message to take")
}
}
#[macro_export]
macro_rules! relm_observer_new {
($component:expr, $pat:pat) => {
$crate::Observer::new($component.stream(), |msg|
if let $pat = msg {
true
}
else {
false
}
);
};
}
#[macro_export]
macro_rules! relm_observer_wait {
(let $($variant:ident)::*($name1:ident, $name2:ident $(,$rest:ident)*) = $observer:expr) => {
let ($name1, $name2 $(, $rest)*) = {
let msg = $observer.wait();
if let $($variant)::*($name1, $name2 $(, $rest)*) = msg {
($name1, $name2 $(, $rest)*)
}
else {
panic!("Wrong message type.");
}
};
};
(let $($variant:ident)::*($name:ident) = $observer:expr) => {
let $name = {
let msg = $observer.wait();
if let $($variant)::*($name) = msg {
$name
}
else {
panic!("Wrong message type.");
}
};
};
(let $($variant:ident)::* = $observer:expr) => {
let () = {
let msg = $observer.wait();
if let $($variant)::* = msg {
()
}
else {
panic!("Wrong message type.");
}
};
};
}
// FIXME: remove when it's in gtk-test.
pub fn click<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt + IsA<W>>(widget: &W) {
wait_for_draw(widget, || {
let observer =
if let Ok(tool_button) = widget.clone().dynamic_cast::<ToolButton>() {
gtk_observer_new!(tool_button, connect_clicked, |_|)
}
else {
gtk_observer_new!(widget, connect_button_press_event, |_, _| {
Inhibit(false)
})
};
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
let mut enigo = Enigo::new();
enigo.mouse_click(MouseButton::Left);
observer.wait();
wait_for_relm_events();
});
}
pub fn mouse_move_to<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt + IsA<W>>(widget: &W) {
wait_for_draw(widget, || {
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
wait_for_relm_events();
});
}
pub fn double_click<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_button_release_event, |_, _| {
Inhibit(false)
});
let allocation = widget.allocation();
mouse_move(widget, allocation.width() / 2, allocation.height() / 2);
let mut enigo = Enigo::new();
enigo.mouse_click(MouseButton::Left);
observer.wait();
let observer = gtk_observer_new!(widget, connect_button_release_event, |_, _| {
Inhibit(false)
});
enigo.mouse_click(MouseButton::Left);
observer.wait();
wait_for_relm_events();
});
}
// FIXME: don't wait the observer for modifier keys like shift?
pub fn key_press<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key)
|
pub fn key_release<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_up(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn enter_key<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, key: Key) {
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_click(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
pub fn enter_keys<W: Clone + IsA<Object> + IsA<Widget> + WidgetExt>(widget: &W, text: &str) {
wait_for_draw(widget, || {
focus(widget);
let mut enigo = Enigo::new();
for char in text.chars() {
let observer = gtk_observer_new!(widget, connect_key_release_event, |_, _| {
Inhibit(false)
});
enigo.key_sequence(&char.to_string());
observer.wait();
}
wait_for_relm_events();
});
}
fn wait_for_relm_events() {
gtk_test::wait(1);
while gtk::events_pending() {
run_loop();
gtk_test::wait(1);
}
}
fn gdk_key_to_enigo_key(key: Key) -> enigo::Key {
use enigo::Key::*;
match key {
key::Return => Return,
key::Tab => Tab,
key::space => Space,
key::BackSpace => Backspace,
key::Escape => Escape,
key::Super_L | key::Super_R => Meta,
key::Control_L | key::Control_R => Control,
key::Shift_L | key::Shift_R => Shift,
key::Shift_Lock => CapsLock,
key::Alt_L | key::Alt_R => Alt,
key::Option => Option,
key::End => End,
key::Home => Home,
key::Page_Down => PageDown,
key::Page_Up => PageUp,
key::leftarrow => LeftArrow,
key::rightarrow => RightArrow,
key::downarrow => DownArrow,
key::uparrow => UpArrow,
key::F1 => F1,
key::F2 => F2,
key::F3 => F3,
key::F4 => F4,
key::F5 => F5,
key::F6 => F6,
key::F7 => F7,
key::F8 => F8,
key::F9 => F9,
key::F10 => F10,
key::F11 => F11,
key::F12 => F12,
_ => {
if let Some(char) = key.to_unicode() {
Layout(char)
}
else {
Raw(*key as u16)
}
},
}
}
|
{
wait_for_draw(widget, || {
let observer = gtk_observer_new!(widget, connect_key_press_event, |_, _| {
Inhibit(false)
});
focus(widget);
let mut enigo = Enigo::new();
enigo.key_down(gdk_key_to_enigo_key(key));
observer.wait();
wait_for_relm_events();
});
}
|
identifier_body
|
trainer.rs
|
extern crate csv;
extern crate getopts;
extern crate gnuplot;
use gnuplot::{Figure, Caption, Color};
use getopts::Options;
use std::f32;
mod common;
fn train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
norm_data: &Vec<(f32, f32)>) -> (f32, f32) {
let m = norm_data.len() as f32;
let mut sum0 = 0_f32;
let mut sum1 = 0_f32;
for &(miles, price) in norm_data {
let d = (common::estimate_price(miles, theta0, theta1) - price as f32) as f32;
sum0 += d;
sum1 += d * miles;
}
(learn_rate * (1_f32 / m) * sum0, learn_rate * (1_f32 / m) * sum1)
}
fn loop_train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
norm_data: &Vec<(f32, f32)>) -> (f32, f32) {
let mut theta0 = theta0;
let mut theta1 = theta1;
// while error > 0.03_f32 {
for _ in 0..50_000 {
let (tmp_theta0, tmp_theta1) = train_thetas(learn_rate, theta0, theta1, &norm_data);
theta0 -= tmp_theta0;
theta1 -= tmp_theta1;
}
(theta0, theta1)
}
fn save_thetas(file: &str, theta0: f32, theta1: f32) {
let mut wtr = csv::Writer::from_file(file).unwrap();
let result = wtr.encode(("theta0", "theta1"));
assert!(result.is_ok());
let result = wtr.encode((theta0, theta1));
assert!(result.is_ok());
}
fn
|
(file: &str, min: f32, max: f32) {
let mut wtr = csv::Writer::from_file(file).unwrap();
let result = wtr.encode(("min", "max"));
assert!(result.is_ok());
let result = wtr.encode((min, max));
assert!(result.is_ok());
}
fn min_tuple0(data: &Vec<(f32, f32)>) -> f32 {
let mut ret = f32::MAX;
for &(val, _) in data {
if val < ret {
ret = val;
}
}
ret
}
fn max_tuple0(data: &Vec<(f32, f32)>) -> f32 {
let mut ret = f32::MIN;
for &(val, _) in data {
if val > ret {
ret = val;
}
}
ret
}
fn normalize_data(data: &Vec<(f32, f32)>, out: &mut Vec<(f32, f32)>, min_max: (f32, f32)) {
// let min = min_tuple0(data) as f32;
// let max = max_tuple0(data) as f32;
let (min, max) = min_max;
out.clear();
for &(miles, price) in data {
out.push( (common::normalize(miles, min, max), price) );
}
}
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} -d DATASET [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("d", "dataset", "the file containing the dataset you want to read", "DATASET");
opts.optopt("l", "learning-rate", "set the learning rate. default is 0.1", "VALUE");
opts.optopt("", "tmp-file-thetas", format!("set the file where you want to save thetas values, default {}", common::TMP_FILE_THETAS).as_ref(), "FILE");
opts.optopt("", "tmp-file-min-max", format!("set the file where you want to save min-max values, default {}", common::TMP_FILE_MIN_MAX).as_ref(), "FILE");
opts.optflag("g", "graph", "display a graph representing the data and the curve found");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
let filename = matches.opt_str("d").unwrap();
let mut rdr = csv::Reader::from_file(filename).unwrap();
let data = rdr.decode().collect::<csv::Result<Vec<(f32, f32)>>>().unwrap();
let min_max = (min_tuple0(&data), max_tuple0(&data));
let mut norm_data: Vec<(f32, f32)> = Vec::with_capacity(data.len());
normalize_data(&data, &mut norm_data, min_max);
let learn_rate: f32 = matches.opt_str("l").unwrap_or("0.1".to_string()).parse().ok().expect("We want a number...");
let (theta0, theta1) = (0_f32, 0_f32);
let (trained_theta0, trained_theta1) = loop_train_thetas(learn_rate, theta0, theta1, &norm_data);
println!("After computation: ({}, {})", trained_theta0, trained_theta1);
let tmp_file_thetas = matches.opt_str("tmp-file-thetas").unwrap_or(common::TMP_FILE_THETAS.to_string());
let tmp_file_min_max = matches.opt_str("tmp-file-min-max").unwrap_or(common::TMP_FILE_MIN_MAX.to_string());
save_thetas(tmp_file_thetas.as_ref(), trained_theta0, trained_theta1);
save_min_max(tmp_file_min_max.as_ref(), min_max.0, min_max.1);
if matches.opt_present("g") {
let x = [0u32, 1, 2];
let y = [3u32, 4, 5];
let mut fg = Figure::new();
fg.axes2d().lines(&x, &y, &[Caption("A line"), Color("black")]);
fg.show();
return;
}
}
|
save_min_max
|
identifier_name
|
trainer.rs
|
extern crate csv;
extern crate getopts;
extern crate gnuplot;
use gnuplot::{Figure, Caption, Color};
use getopts::Options;
use std::f32;
mod common;
fn train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
norm_data: &Vec<(f32, f32)>) -> (f32, f32) {
let m = norm_data.len() as f32;
let mut sum0 = 0_f32;
let mut sum1 = 0_f32;
for &(miles, price) in norm_data {
let d = (common::estimate_price(miles, theta0, theta1) - price as f32) as f32;
sum0 += d;
sum1 += d * miles;
}
(learn_rate * (1_f32 / m) * sum0, learn_rate * (1_f32 / m) * sum1)
}
fn loop_train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
norm_data: &Vec<(f32, f32)>) -> (f32, f32) {
let mut theta0 = theta0;
let mut theta1 = theta1;
// while error > 0.03_f32 {
for _ in 0..50_000 {
let (tmp_theta0, tmp_theta1) = train_thetas(learn_rate, theta0, theta1, &norm_data);
theta0 -= tmp_theta0;
theta1 -= tmp_theta1;
}
(theta0, theta1)
}
fn save_thetas(file: &str, theta0: f32, theta1: f32) {
let mut wtr = csv::Writer::from_file(file).unwrap();
let result = wtr.encode(("theta0", "theta1"));
assert!(result.is_ok());
let result = wtr.encode((theta0, theta1));
assert!(result.is_ok());
}
fn save_min_max(file: &str, min: f32, max: f32)
|
fn min_tuple0(data: &Vec<(f32, f32)>) -> f32 {
let mut ret = f32::MAX;
for &(val, _) in data {
if val < ret {
ret = val;
}
}
ret
}
fn max_tuple0(data: &Vec<(f32, f32)>) -> f32 {
let mut ret = f32::MIN;
for &(val, _) in data {
if val > ret {
ret = val;
}
}
ret
}
fn normalize_data(data: &Vec<(f32, f32)>, out: &mut Vec<(f32, f32)>, min_max: (f32, f32)) {
// let min = min_tuple0(data) as f32;
// let max = max_tuple0(data) as f32;
let (min, max) = min_max;
out.clear();
for &(miles, price) in data {
out.push( (common::normalize(miles, min, max), price) );
}
}
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} -d DATASET [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("d", "dataset", "the file containing the dataset you want to read", "DATASET");
opts.optopt("l", "learning-rate", "set the learning rate. default is 0.1", "VALUE");
opts.optopt("", "tmp-file-thetas", format!("set the file where you want to save thetas values, default {}", common::TMP_FILE_THETAS).as_ref(), "FILE");
opts.optopt("", "tmp-file-min-max", format!("set the file where you want to save min-max values, default {}", common::TMP_FILE_MIN_MAX).as_ref(), "FILE");
opts.optflag("g", "graph", "display a graph representing the data and the curve found");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
let filename = matches.opt_str("d").unwrap();
let mut rdr = csv::Reader::from_file(filename).unwrap();
let data = rdr.decode().collect::<csv::Result<Vec<(f32, f32)>>>().unwrap();
let min_max = (min_tuple0(&data), max_tuple0(&data));
let mut norm_data: Vec<(f32, f32)> = Vec::with_capacity(data.len());
normalize_data(&data, &mut norm_data, min_max);
let learn_rate: f32 = matches.opt_str("l").unwrap_or("0.1".to_string()).parse().ok().expect("We want a number...");
let (theta0, theta1) = (0_f32, 0_f32);
let (trained_theta0, trained_theta1) = loop_train_thetas(learn_rate, theta0, theta1, &norm_data);
println!("After computation: ({}, {})", trained_theta0, trained_theta1);
let tmp_file_thetas = matches.opt_str("tmp-file-thetas").unwrap_or(common::TMP_FILE_THETAS.to_string());
let tmp_file_min_max = matches.opt_str("tmp-file-min-max").unwrap_or(common::TMP_FILE_MIN_MAX.to_string());
save_thetas(tmp_file_thetas.as_ref(), trained_theta0, trained_theta1);
save_min_max(tmp_file_min_max.as_ref(), min_max.0, min_max.1);
if matches.opt_present("g") {
let x = [0u32, 1, 2];
let y = [3u32, 4, 5];
let mut fg = Figure::new();
fg.axes2d().lines(&x, &y, &[Caption("A line"), Color("black")]);
fg.show();
return;
}
}
|
{
let mut wtr = csv::Writer::from_file(file).unwrap();
let result = wtr.encode(("min", "max"));
assert!(result.is_ok());
let result = wtr.encode((min, max));
assert!(result.is_ok());
}
|
identifier_body
|
trainer.rs
|
extern crate csv;
extern crate getopts;
extern crate gnuplot;
use gnuplot::{Figure, Caption, Color};
use getopts::Options;
use std::f32;
mod common;
fn train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
norm_data: &Vec<(f32, f32)>) -> (f32, f32) {
let m = norm_data.len() as f32;
let mut sum0 = 0_f32;
let mut sum1 = 0_f32;
for &(miles, price) in norm_data {
let d = (common::estimate_price(miles, theta0, theta1) - price as f32) as f32;
sum0 += d;
sum1 += d * miles;
}
(learn_rate * (1_f32 / m) * sum0, learn_rate * (1_f32 / m) * sum1)
}
fn loop_train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
norm_data: &Vec<(f32, f32)>) -> (f32, f32) {
let mut theta0 = theta0;
let mut theta1 = theta1;
// while error > 0.03_f32 {
for _ in 0..50_000 {
let (tmp_theta0, tmp_theta1) = train_thetas(learn_rate, theta0, theta1, &norm_data);
theta0 -= tmp_theta0;
theta1 -= tmp_theta1;
}
(theta0, theta1)
}
fn save_thetas(file: &str, theta0: f32, theta1: f32) {
let mut wtr = csv::Writer::from_file(file).unwrap();
let result = wtr.encode(("theta0", "theta1"));
assert!(result.is_ok());
let result = wtr.encode((theta0, theta1));
|
let mut wtr = csv::Writer::from_file(file).unwrap();
let result = wtr.encode(("min", "max"));
assert!(result.is_ok());
let result = wtr.encode((min, max));
assert!(result.is_ok());
}
fn min_tuple0(data: &Vec<(f32, f32)>) -> f32 {
let mut ret = f32::MAX;
for &(val, _) in data {
if val < ret {
ret = val;
}
}
ret
}
fn max_tuple0(data: &Vec<(f32, f32)>) -> f32 {
let mut ret = f32::MIN;
for &(val, _) in data {
if val > ret {
ret = val;
}
}
ret
}
fn normalize_data(data: &Vec<(f32, f32)>, out: &mut Vec<(f32, f32)>, min_max: (f32, f32)) {
// let min = min_tuple0(data) as f32;
// let max = max_tuple0(data) as f32;
let (min, max) = min_max;
out.clear();
for &(miles, price) in data {
out.push( (common::normalize(miles, min, max), price) );
}
}
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} -d DATASET [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("d", "dataset", "the file containing the dataset you want to read", "DATASET");
opts.optopt("l", "learning-rate", "set the learning rate. default is 0.1", "VALUE");
opts.optopt("", "tmp-file-thetas", format!("set the file where you want to save thetas values, default {}", common::TMP_FILE_THETAS).as_ref(), "FILE");
opts.optopt("", "tmp-file-min-max", format!("set the file where you want to save min-max values, default {}", common::TMP_FILE_MIN_MAX).as_ref(), "FILE");
opts.optflag("g", "graph", "display a graph representing the data and the curve found");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
let filename = matches.opt_str("d").unwrap();
let mut rdr = csv::Reader::from_file(filename).unwrap();
let data = rdr.decode().collect::<csv::Result<Vec<(f32, f32)>>>().unwrap();
let min_max = (min_tuple0(&data), max_tuple0(&data));
let mut norm_data: Vec<(f32, f32)> = Vec::with_capacity(data.len());
normalize_data(&data, &mut norm_data, min_max);
let learn_rate: f32 = matches.opt_str("l").unwrap_or("0.1".to_string()).parse().ok().expect("We want a number...");
let (theta0, theta1) = (0_f32, 0_f32);
let (trained_theta0, trained_theta1) = loop_train_thetas(learn_rate, theta0, theta1, &norm_data);
println!("After computation: ({}, {})", trained_theta0, trained_theta1);
let tmp_file_thetas = matches.opt_str("tmp-file-thetas").unwrap_or(common::TMP_FILE_THETAS.to_string());
let tmp_file_min_max = matches.opt_str("tmp-file-min-max").unwrap_or(common::TMP_FILE_MIN_MAX.to_string());
save_thetas(tmp_file_thetas.as_ref(), trained_theta0, trained_theta1);
save_min_max(tmp_file_min_max.as_ref(), min_max.0, min_max.1);
if matches.opt_present("g") {
let x = [0u32, 1, 2];
let y = [3u32, 4, 5];
let mut fg = Figure::new();
fg.axes2d().lines(&x, &y, &[Caption("A line"), Color("black")]);
fg.show();
return;
}
}
|
assert!(result.is_ok());
}
fn save_min_max(file: &str, min: f32, max: f32) {
|
random_line_split
|
trainer.rs
|
extern crate csv;
extern crate getopts;
extern crate gnuplot;
use gnuplot::{Figure, Caption, Color};
use getopts::Options;
use std::f32;
mod common;
fn train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
norm_data: &Vec<(f32, f32)>) -> (f32, f32) {
let m = norm_data.len() as f32;
let mut sum0 = 0_f32;
let mut sum1 = 0_f32;
for &(miles, price) in norm_data {
let d = (common::estimate_price(miles, theta0, theta1) - price as f32) as f32;
sum0 += d;
sum1 += d * miles;
}
(learn_rate * (1_f32 / m) * sum0, learn_rate * (1_f32 / m) * sum1)
}
fn loop_train_thetas(learn_rate: f32, theta0: f32, theta1: f32,
norm_data: &Vec<(f32, f32)>) -> (f32, f32) {
let mut theta0 = theta0;
let mut theta1 = theta1;
// while error > 0.03_f32 {
for _ in 0..50_000 {
let (tmp_theta0, tmp_theta1) = train_thetas(learn_rate, theta0, theta1, &norm_data);
theta0 -= tmp_theta0;
theta1 -= tmp_theta1;
}
(theta0, theta1)
}
fn save_thetas(file: &str, theta0: f32, theta1: f32) {
let mut wtr = csv::Writer::from_file(file).unwrap();
let result = wtr.encode(("theta0", "theta1"));
assert!(result.is_ok());
let result = wtr.encode((theta0, theta1));
assert!(result.is_ok());
}
fn save_min_max(file: &str, min: f32, max: f32) {
let mut wtr = csv::Writer::from_file(file).unwrap();
let result = wtr.encode(("min", "max"));
assert!(result.is_ok());
let result = wtr.encode((min, max));
assert!(result.is_ok());
}
fn min_tuple0(data: &Vec<(f32, f32)>) -> f32 {
let mut ret = f32::MAX;
for &(val, _) in data {
if val < ret {
ret = val;
}
}
ret
}
fn max_tuple0(data: &Vec<(f32, f32)>) -> f32 {
let mut ret = f32::MIN;
for &(val, _) in data {
if val > ret {
ret = val;
}
}
ret
}
fn normalize_data(data: &Vec<(f32, f32)>, out: &mut Vec<(f32, f32)>, min_max: (f32, f32)) {
// let min = min_tuple0(data) as f32;
// let max = max_tuple0(data) as f32;
let (min, max) = min_max;
out.clear();
for &(miles, price) in data {
out.push( (common::normalize(miles, min, max), price) );
}
}
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} -d DATASET [options]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
let mut opts = Options::new();
opts.reqopt("d", "dataset", "the file containing the dataset you want to read", "DATASET");
opts.optopt("l", "learning-rate", "set the learning rate. default is 0.1", "VALUE");
opts.optopt("", "tmp-file-thetas", format!("set the file where you want to save thetas values, default {}", common::TMP_FILE_THETAS).as_ref(), "FILE");
opts.optopt("", "tmp-file-min-max", format!("set the file where you want to save min-max values, default {}", common::TMP_FILE_MIN_MAX).as_ref(), "FILE");
opts.optflag("g", "graph", "display a graph representing the data and the curve found");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) =>
|
Err(f) => { panic!(f.to_string()) }
};
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
let filename = matches.opt_str("d").unwrap();
let mut rdr = csv::Reader::from_file(filename).unwrap();
let data = rdr.decode().collect::<csv::Result<Vec<(f32, f32)>>>().unwrap();
let min_max = (min_tuple0(&data), max_tuple0(&data));
let mut norm_data: Vec<(f32, f32)> = Vec::with_capacity(data.len());
normalize_data(&data, &mut norm_data, min_max);
let learn_rate: f32 = matches.opt_str("l").unwrap_or("0.1".to_string()).parse().ok().expect("We want a number...");
let (theta0, theta1) = (0_f32, 0_f32);
let (trained_theta0, trained_theta1) = loop_train_thetas(learn_rate, theta0, theta1, &norm_data);
println!("After computation: ({}, {})", trained_theta0, trained_theta1);
let tmp_file_thetas = matches.opt_str("tmp-file-thetas").unwrap_or(common::TMP_FILE_THETAS.to_string());
let tmp_file_min_max = matches.opt_str("tmp-file-min-max").unwrap_or(common::TMP_FILE_MIN_MAX.to_string());
save_thetas(tmp_file_thetas.as_ref(), trained_theta0, trained_theta1);
save_min_max(tmp_file_min_max.as_ref(), min_max.0, min_max.1);
if matches.opt_present("g") {
let x = [0u32, 1, 2];
let y = [3u32, 4, 5];
let mut fg = Figure::new();
fg.axes2d().lines(&x, &y, &[Caption("A line"), Color("black")]);
fg.show();
return;
}
}
|
{ m }
|
conditional_block
|
tcp-accept-stress.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.
// ignore-macos osx really doesn't like cycling through large numbers of
// sockets as calls to connect() will start returning EADDRNOTAVAIL
// quite quickly and it takes a few seconds for the sockets to get
// recycled.
#![feature(phase)]
#[phase(plugin)]
extern crate green;
extern crate native;
use std::io::{TcpListener, Listener, Acceptor, EndOfFile, TcpStream};
use std::sync::{atomic, Arc};
use std::task::TaskBuilder;
use native::NativeTaskBuilder;
static N: uint = 8;
static M: uint = 20;
|
test();
let (tx, rx) = channel();
TaskBuilder::new().native().spawn(proc() {
tx.send(test());
});
rx.recv();
}
fn test() {
let mut l = TcpListener::bind("127.0.0.1", 0).unwrap();
let addr = l.socket_name().unwrap();
let mut a = l.listen().unwrap();
let cnt = Arc::new(atomic::AtomicUint::new(0));
let (srv_tx, srv_rx) = channel();
let (cli_tx, cli_rx) = channel();
for _ in range(0, N) {
let a = a.clone();
let cnt = cnt.clone();
let srv_tx = srv_tx.clone();
spawn(proc() {
let mut a = a;
loop {
match a.accept() {
Ok(..) => {
if cnt.fetch_add(1, atomic::SeqCst) == N * M - 1 {
break
}
}
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => fail!("{}", e),
}
}
srv_tx.send(());
});
}
for _ in range(0, N) {
let cli_tx = cli_tx.clone();
spawn(proc() {
for _ in range(0, M) {
let _s = TcpStream::connect(addr.ip.to_string().as_slice(),
addr.port).unwrap();
}
cli_tx.send(());
});
}
drop((cli_tx, srv_tx));
// wait for senders
if cli_rx.iter().take(N).count()!= N {
a.close_accept().unwrap();
fail!("clients failed");
}
// wait for one acceptor to die
let _ = srv_rx.recv();
// Notify other receivers should die
a.close_accept().unwrap();
// wait for receivers
assert_eq!(srv_rx.iter().take(N - 1).count(), N - 1);
// Everything should have been accepted.
assert_eq!(cnt.load(atomic::SeqCst), N * M);
}
|
green_start!(main)
fn main() {
|
random_line_split
|
tcp-accept-stress.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.
// ignore-macos osx really doesn't like cycling through large numbers of
// sockets as calls to connect() will start returning EADDRNOTAVAIL
// quite quickly and it takes a few seconds for the sockets to get
// recycled.
#![feature(phase)]
#[phase(plugin)]
extern crate green;
extern crate native;
use std::io::{TcpListener, Listener, Acceptor, EndOfFile, TcpStream};
use std::sync::{atomic, Arc};
use std::task::TaskBuilder;
use native::NativeTaskBuilder;
static N: uint = 8;
static M: uint = 20;
green_start!(main)
fn
|
() {
test();
let (tx, rx) = channel();
TaskBuilder::new().native().spawn(proc() {
tx.send(test());
});
rx.recv();
}
fn test() {
let mut l = TcpListener::bind("127.0.0.1", 0).unwrap();
let addr = l.socket_name().unwrap();
let mut a = l.listen().unwrap();
let cnt = Arc::new(atomic::AtomicUint::new(0));
let (srv_tx, srv_rx) = channel();
let (cli_tx, cli_rx) = channel();
for _ in range(0, N) {
let a = a.clone();
let cnt = cnt.clone();
let srv_tx = srv_tx.clone();
spawn(proc() {
let mut a = a;
loop {
match a.accept() {
Ok(..) => {
if cnt.fetch_add(1, atomic::SeqCst) == N * M - 1 {
break
}
}
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => fail!("{}", e),
}
}
srv_tx.send(());
});
}
for _ in range(0, N) {
let cli_tx = cli_tx.clone();
spawn(proc() {
for _ in range(0, M) {
let _s = TcpStream::connect(addr.ip.to_string().as_slice(),
addr.port).unwrap();
}
cli_tx.send(());
});
}
drop((cli_tx, srv_tx));
// wait for senders
if cli_rx.iter().take(N).count()!= N {
a.close_accept().unwrap();
fail!("clients failed");
}
// wait for one acceptor to die
let _ = srv_rx.recv();
// Notify other receivers should die
a.close_accept().unwrap();
// wait for receivers
assert_eq!(srv_rx.iter().take(N - 1).count(), N - 1);
// Everything should have been accepted.
assert_eq!(cnt.load(atomic::SeqCst), N * M);
}
|
main
|
identifier_name
|
tcp-accept-stress.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.
// ignore-macos osx really doesn't like cycling through large numbers of
// sockets as calls to connect() will start returning EADDRNOTAVAIL
// quite quickly and it takes a few seconds for the sockets to get
// recycled.
#![feature(phase)]
#[phase(plugin)]
extern crate green;
extern crate native;
use std::io::{TcpListener, Listener, Acceptor, EndOfFile, TcpStream};
use std::sync::{atomic, Arc};
use std::task::TaskBuilder;
use native::NativeTaskBuilder;
static N: uint = 8;
static M: uint = 20;
green_start!(main)
fn main() {
test();
let (tx, rx) = channel();
TaskBuilder::new().native().spawn(proc() {
tx.send(test());
});
rx.recv();
}
fn test()
|
}
Err(ref e) if e.kind == EndOfFile => break,
Err(e) => fail!("{}", e),
}
}
srv_tx.send(());
});
}
for _ in range(0, N) {
let cli_tx = cli_tx.clone();
spawn(proc() {
for _ in range(0, M) {
let _s = TcpStream::connect(addr.ip.to_string().as_slice(),
addr.port).unwrap();
}
cli_tx.send(());
});
}
drop((cli_tx, srv_tx));
// wait for senders
if cli_rx.iter().take(N).count()!= N {
a.close_accept().unwrap();
fail!("clients failed");
}
// wait for one acceptor to die
let _ = srv_rx.recv();
// Notify other receivers should die
a.close_accept().unwrap();
// wait for receivers
assert_eq!(srv_rx.iter().take(N - 1).count(), N - 1);
// Everything should have been accepted.
assert_eq!(cnt.load(atomic::SeqCst), N * M);
}
|
{
let mut l = TcpListener::bind("127.0.0.1", 0).unwrap();
let addr = l.socket_name().unwrap();
let mut a = l.listen().unwrap();
let cnt = Arc::new(atomic::AtomicUint::new(0));
let (srv_tx, srv_rx) = channel();
let (cli_tx, cli_rx) = channel();
for _ in range(0, N) {
let a = a.clone();
let cnt = cnt.clone();
let srv_tx = srv_tx.clone();
spawn(proc() {
let mut a = a;
loop {
match a.accept() {
Ok(..) => {
if cnt.fetch_add(1, atomic::SeqCst) == N * M - 1 {
break
}
|
identifier_body
|
error.rs
|
// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::{error, fmt};
use super::ssa_traits::SSA;
use super::ssastorage::SSAStorage;
use std::fmt::Debug;
#[derive(Debug)]
pub enum SSAErr<T: SSA + Debug> {
InvalidBlock(T::ActionRef),
InvalidType(String),
InvalidTarget(T::ActionRef, T::CFEdgeRef, T::ActionRef),
InvalidControl(T::ActionRef, T::CFEdgeRef),
WrongNumOperands(T::ValueRef, usize, usize),
WrongNumEdges(T::ActionRef, usize, usize),
NoSelector(T::ActionRef),
UnexpectedSelector(T::ActionRef, T::ValueRef),
UnreachableBlock(T::ActionRef),
InvalidExpr(T::ValueRef),
IncompatibleWidth(T::ValueRef, u16, u16),
}
impl fmt::Display for SSAErr<SSAStorage> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let err = match *self {
SSAErr::InvalidBlock(ni) =>
|
SSAErr::InvalidType(ref e) => {
format!("Expected type: {}.", e)
}
SSAErr::InvalidControl(bi, ei) => {
format!("Block {:?} has invalid outgoing edge: {:?}", bi, ei)
}
SSAErr::WrongNumOperands(n, e, f) => {
format!("{:?} expected {} number of operands, found: {}", n, e, f)
}
SSAErr::InvalidTarget(bi, ei, ti) => {
format!("Block {:?} has Edge {:?} with invalid target {:?}",
bi,
ei,
ti)
}
SSAErr::WrongNumEdges(ni, e, f) => {
format!("Block {:?} expects {} edge(s), found: {}", ni, e, f)
}
SSAErr::NoSelector(bi) => {
format!("Block {:?} expects a selector. None found.", bi)
}
SSAErr::UnexpectedSelector(bi, ni) => {
format!("Block {:?} expected no selector, found: {:?}", bi, ni)
}
SSAErr::UnreachableBlock(bi) => {
format!("Unreachable block found: {:?}", bi)
}
SSAErr::InvalidExpr(ni) => {
format!("Found an invalid expression: {:?}", ni)
}
SSAErr::IncompatibleWidth(ni, e, f) => {
format!("{:?} expected with to be {}, found width: {}", ni, e, f)
}
};
write!(f, "{}.", err)
}
}
impl error::Error for SSAErr<SSAStorage> {
fn description(&self) -> &str {
""
}
fn cause(&self) -> Option<&error::Error> {
None
}
}
|
{
format!("Found Block with index: {:?}.", ni)
}
|
conditional_block
|
error.rs
|
// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::{error, fmt};
use super::ssa_traits::SSA;
use super::ssastorage::SSAStorage;
use std::fmt::Debug;
#[derive(Debug)]
pub enum SSAErr<T: SSA + Debug> {
InvalidBlock(T::ActionRef),
InvalidType(String),
InvalidTarget(T::ActionRef, T::CFEdgeRef, T::ActionRef),
InvalidControl(T::ActionRef, T::CFEdgeRef),
WrongNumOperands(T::ValueRef, usize, usize),
WrongNumEdges(T::ActionRef, usize, usize),
NoSelector(T::ActionRef),
UnexpectedSelector(T::ActionRef, T::ValueRef),
UnreachableBlock(T::ActionRef),
InvalidExpr(T::ValueRef),
IncompatibleWidth(T::ValueRef, u16, u16),
}
impl fmt::Display for SSAErr<SSAStorage> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let err = match *self {
SSAErr::InvalidBlock(ni) => {
format!("Found Block with index: {:?}.", ni)
}
SSAErr::InvalidType(ref e) => {
format!("Expected type: {}.", e)
}
SSAErr::InvalidControl(bi, ei) => {
format!("Block {:?} has invalid outgoing edge: {:?}", bi, ei)
}
SSAErr::WrongNumOperands(n, e, f) => {
format!("{:?} expected {} number of operands, found: {}", n, e, f)
}
SSAErr::InvalidTarget(bi, ei, ti) => {
format!("Block {:?} has Edge {:?} with invalid target {:?}",
bi,
ei,
ti)
}
SSAErr::WrongNumEdges(ni, e, f) => {
format!("Block {:?} expects {} edge(s), found: {}", ni, e, f)
}
SSAErr::NoSelector(bi) => {
format!("Block {:?} expects a selector. None found.", bi)
}
SSAErr::UnexpectedSelector(bi, ni) => {
format!("Block {:?} expected no selector, found: {:?}", bi, ni)
}
SSAErr::UnreachableBlock(bi) => {
format!("Unreachable block found: {:?}", bi)
}
SSAErr::InvalidExpr(ni) => {
format!("Found an invalid expression: {:?}", ni)
}
SSAErr::IncompatibleWidth(ni, e, f) => {
format!("{:?} expected with to be {}, found width: {}", ni, e, f)
}
};
write!(f, "{}.", err)
}
}
impl error::Error for SSAErr<SSAStorage> {
fn description(&self) -> &str {
""
}
fn
|
(&self) -> Option<&error::Error> {
None
}
}
|
cause
|
identifier_name
|
error.rs
|
// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::{error, fmt};
use super::ssa_traits::SSA;
use super::ssastorage::SSAStorage;
use std::fmt::Debug;
#[derive(Debug)]
pub enum SSAErr<T: SSA + Debug> {
InvalidBlock(T::ActionRef),
InvalidType(String),
InvalidTarget(T::ActionRef, T::CFEdgeRef, T::ActionRef),
InvalidControl(T::ActionRef, T::CFEdgeRef),
WrongNumOperands(T::ValueRef, usize, usize),
WrongNumEdges(T::ActionRef, usize, usize),
NoSelector(T::ActionRef),
UnexpectedSelector(T::ActionRef, T::ValueRef),
UnreachableBlock(T::ActionRef),
InvalidExpr(T::ValueRef),
IncompatibleWidth(T::ValueRef, u16, u16),
}
impl fmt::Display for SSAErr<SSAStorage> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let err = match *self {
SSAErr::InvalidBlock(ni) => {
format!("Found Block with index: {:?}.", ni)
}
SSAErr::InvalidType(ref e) => {
format!("Expected type: {}.", e)
}
SSAErr::InvalidControl(bi, ei) => {
format!("Block {:?} has invalid outgoing edge: {:?}", bi, ei)
}
SSAErr::WrongNumOperands(n, e, f) => {
format!("{:?} expected {} number of operands, found: {}", n, e, f)
}
SSAErr::InvalidTarget(bi, ei, ti) => {
format!("Block {:?} has Edge {:?} with invalid target {:?}",
bi,
ei,
ti)
}
SSAErr::WrongNumEdges(ni, e, f) => {
format!("Block {:?} expects {} edge(s), found: {}", ni, e, f)
}
SSAErr::NoSelector(bi) => {
format!("Block {:?} expects a selector. None found.", bi)
}
SSAErr::UnexpectedSelector(bi, ni) => {
format!("Block {:?} expected no selector, found: {:?}", bi, ni)
}
SSAErr::UnreachableBlock(bi) => {
format!("Unreachable block found: {:?}", bi)
}
SSAErr::InvalidExpr(ni) => {
format!("Found an invalid expression: {:?}", ni)
}
SSAErr::IncompatibleWidth(ni, e, f) => {
format!("{:?} expected with to be {}, found width: {}", ni, e, f)
}
};
write!(f, "{}.", err)
}
}
impl error::Error for SSAErr<SSAStorage> {
fn description(&self) -> &str {
""
}
fn cause(&self) -> Option<&error::Error>
|
}
|
{
None
}
|
identifier_body
|
error.rs
|
// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.
use std::{error, fmt};
use super::ssa_traits::SSA;
use super::ssastorage::SSAStorage;
use std::fmt::Debug;
#[derive(Debug)]
pub enum SSAErr<T: SSA + Debug> {
InvalidBlock(T::ActionRef),
InvalidType(String),
InvalidTarget(T::ActionRef, T::CFEdgeRef, T::ActionRef),
InvalidControl(T::ActionRef, T::CFEdgeRef),
WrongNumOperands(T::ValueRef, usize, usize),
WrongNumEdges(T::ActionRef, usize, usize),
NoSelector(T::ActionRef),
UnexpectedSelector(T::ActionRef, T::ValueRef),
UnreachableBlock(T::ActionRef),
InvalidExpr(T::ValueRef),
IncompatibleWidth(T::ValueRef, u16, u16),
}
impl fmt::Display for SSAErr<SSAStorage> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let err = match *self {
SSAErr::InvalidBlock(ni) => {
format!("Found Block with index: {:?}.", ni)
}
SSAErr::InvalidType(ref e) => {
format!("Expected type: {}.", e)
}
SSAErr::InvalidControl(bi, ei) => {
format!("Block {:?} has invalid outgoing edge: {:?}", bi, ei)
}
SSAErr::WrongNumOperands(n, e, f) => {
format!("{:?} expected {} number of operands, found: {}", n, e, f)
}
SSAErr::InvalidTarget(bi, ei, ti) => {
format!("Block {:?} has Edge {:?} with invalid target {:?}",
bi,
ei,
ti)
}
SSAErr::WrongNumEdges(ni, e, f) => {
format!("Block {:?} expects {} edge(s), found: {}", ni, e, f)
}
SSAErr::NoSelector(bi) => {
format!("Block {:?} expects a selector. None found.", bi)
}
|
}
SSAErr::UnreachableBlock(bi) => {
format!("Unreachable block found: {:?}", bi)
}
SSAErr::InvalidExpr(ni) => {
format!("Found an invalid expression: {:?}", ni)
}
SSAErr::IncompatibleWidth(ni, e, f) => {
format!("{:?} expected with to be {}, found width: {}", ni, e, f)
}
};
write!(f, "{}.", err)
}
}
impl error::Error for SSAErr<SSAStorage> {
fn description(&self) -> &str {
""
}
fn cause(&self) -> Option<&error::Error> {
None
}
}
|
SSAErr::UnexpectedSelector(bi, ni) => {
format!("Block {:?} expected no selector, found: {:?}", bi, ni)
|
random_line_split
|
num.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.
//! Integer and floating-point number formatting
// FIXME: #6220 Implement floating point formatting
#![allow(unsigned_negation)]
use fmt;
use iter::DoubleEndedIteratorExt;
use kinds::Copy;
use num::{Int, cast};
use slice::SlicePrelude;
/// A type that represents a specific radix
#[doc(hidden)]
trait GenericRadix {
/// The number of digits.
fn base(&self) -> u8;
/// A radix-specific prefix string.
fn prefix(&self) -> &'static str { "" }
/// Converts an integer to corresponding radix digit.
fn digit(&self, x: u8) -> u8;
/// Format an integer using the radix using a formatter.
fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
// The radix can be as low as 2, so we need a buffer of at least 64
// characters for a base 2 number.
let zero = Int::zero();
let is_positive = x >= zero;
let mut buf = [0u8,..64];
let mut curr = buf.len();
let base = cast(self.base()).unwrap();
if is_positive {
// Accumulate each digit of the number from the least significant
// to the most significant figure.
for byte in buf.iter_mut().rev() {
let n = x % base; // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero { break }; // No more digits left to accumulate.
}
} else {
// Do the same as above, but accounting for two's complement.
for byte in buf.iter_mut().rev() {
let n = zero - (x % base); // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero { break }; // No more digits left to accumulate.
}
}
f.pad_integral(is_positive, self.prefix(), buf[curr..])
}
}
/// A binary (base 2) radix
#[deriving(Clone, PartialEq)]
struct Binary;
|
/// A decimal (base 10) radix
#[deriving(Clone, PartialEq)]
struct Decimal;
/// A hexadecimal (base 16) radix, formatted with lower-case characters
#[deriving(Clone, PartialEq)]
struct LowerHex;
/// A hexadecimal (base 16) radix, formatted with upper-case characters
#[deriving(Clone, PartialEq)]
pub struct UpperHex;
macro_rules! radix {
($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
impl GenericRadix for $T {
fn base(&self) -> u8 { $base }
fn prefix(&self) -> &'static str { $prefix }
fn digit(&self, x: u8) -> u8 {
match x {
$($x => $conv,)+
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
}
}
radix!(Binary, 2, "0b", x @ 0... 2 => b'0' + x)
radix!(Octal, 8, "0o", x @ 0... 7 => b'0' + x)
radix!(Decimal, 10, "", x @ 0... 9 => b'0' + x)
radix!(LowerHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'a' + (x - 10))
radix!(UpperHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'A' + (x - 10))
/// A radix with in the range of `2..36`.
#[deriving(Clone, PartialEq)]
#[unstable = "may be renamed or move to a different module"]
pub struct Radix {
base: u8,
}
impl Copy for Radix {}
impl Radix {
fn new(base: u8) -> Radix {
assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
Radix { base: base }
}
}
impl GenericRadix for Radix {
fn base(&self) -> u8 { self.base }
fn digit(&self, x: u8) -> u8 {
match x {
x @ 0... 9 => b'0' + x,
x if x < self.base() => b'a' + (x - 10),
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
/// A helper type for formatting radixes.
#[unstable = "may be renamed or move to a different module"]
pub struct RadixFmt<T, R>(T, R);
impl<T,R> Copy for RadixFmt<T,R> where T: Copy, R: Copy {}
/// Constructs a radix formatter in the range of `2..36`.
///
/// # Example
///
/// ```
/// use std::fmt::radix;
/// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
/// ```
#[unstable = "may be renamed or move to a different module"]
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base))
}
macro_rules! radix_fmt {
($T:ty as $U:ty, $fmt:ident) => {
impl fmt::Show for RadixFmt<$T, Radix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
}
}
}
}
macro_rules! int_base {
($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
impl fmt::$Trait for $T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
$Radix.fmt_int(*self as $U, f)
}
}
}
}
macro_rules! integer {
($Int:ident, $Uint:ident) => {
int_base!(Show for $Int as $Int -> Decimal)
int_base!(Binary for $Int as $Uint -> Binary)
int_base!(Octal for $Int as $Uint -> Octal)
int_base!(LowerHex for $Int as $Uint -> LowerHex)
int_base!(UpperHex for $Int as $Uint -> UpperHex)
radix_fmt!($Int as $Int, fmt_int)
int_base!(Show for $Uint as $Uint -> Decimal)
int_base!(Binary for $Uint as $Uint -> Binary)
int_base!(Octal for $Uint as $Uint -> Octal)
int_base!(LowerHex for $Uint as $Uint -> LowerHex)
int_base!(UpperHex for $Uint as $Uint -> UpperHex)
radix_fmt!($Uint as $Uint, fmt_int)
}
}
integer!(int, uint)
integer!(i8, u8)
integer!(i16, u16)
integer!(i32, u32)
integer!(i64, u64)
|
/// An octal (base 8) radix
#[deriving(Clone, PartialEq)]
struct Octal;
|
random_line_split
|
num.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.
//! Integer and floating-point number formatting
// FIXME: #6220 Implement floating point formatting
#![allow(unsigned_negation)]
use fmt;
use iter::DoubleEndedIteratorExt;
use kinds::Copy;
use num::{Int, cast};
use slice::SlicePrelude;
/// A type that represents a specific radix
#[doc(hidden)]
trait GenericRadix {
/// The number of digits.
fn base(&self) -> u8;
/// A radix-specific prefix string.
fn prefix(&self) -> &'static str { "" }
/// Converts an integer to corresponding radix digit.
fn digit(&self, x: u8) -> u8;
/// Format an integer using the radix using a formatter.
fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
// The radix can be as low as 2, so we need a buffer of at least 64
// characters for a base 2 number.
let zero = Int::zero();
let is_positive = x >= zero;
let mut buf = [0u8,..64];
let mut curr = buf.len();
let base = cast(self.base()).unwrap();
if is_positive {
// Accumulate each digit of the number from the least significant
// to the most significant figure.
for byte in buf.iter_mut().rev() {
let n = x % base; // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero
|
; // No more digits left to accumulate.
}
} else {
// Do the same as above, but accounting for two's complement.
for byte in buf.iter_mut().rev() {
let n = zero - (x % base); // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero { break }; // No more digits left to accumulate.
}
}
f.pad_integral(is_positive, self.prefix(), buf[curr..])
}
}
/// A binary (base 2) radix
#[deriving(Clone, PartialEq)]
struct Binary;
/// An octal (base 8) radix
#[deriving(Clone, PartialEq)]
struct Octal;
/// A decimal (base 10) radix
#[deriving(Clone, PartialEq)]
struct Decimal;
/// A hexadecimal (base 16) radix, formatted with lower-case characters
#[deriving(Clone, PartialEq)]
struct LowerHex;
/// A hexadecimal (base 16) radix, formatted with upper-case characters
#[deriving(Clone, PartialEq)]
pub struct UpperHex;
macro_rules! radix {
($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
impl GenericRadix for $T {
fn base(&self) -> u8 { $base }
fn prefix(&self) -> &'static str { $prefix }
fn digit(&self, x: u8) -> u8 {
match x {
$($x => $conv,)+
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
}
}
radix!(Binary, 2, "0b", x @ 0... 2 => b'0' + x)
radix!(Octal, 8, "0o", x @ 0... 7 => b'0' + x)
radix!(Decimal, 10, "", x @ 0... 9 => b'0' + x)
radix!(LowerHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'a' + (x - 10))
radix!(UpperHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'A' + (x - 10))
/// A radix with in the range of `2..36`.
#[deriving(Clone, PartialEq)]
#[unstable = "may be renamed or move to a different module"]
pub struct Radix {
base: u8,
}
impl Copy for Radix {}
impl Radix {
fn new(base: u8) -> Radix {
assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
Radix { base: base }
}
}
impl GenericRadix for Radix {
fn base(&self) -> u8 { self.base }
fn digit(&self, x: u8) -> u8 {
match x {
x @ 0... 9 => b'0' + x,
x if x < self.base() => b'a' + (x - 10),
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
/// A helper type for formatting radixes.
#[unstable = "may be renamed or move to a different module"]
pub struct RadixFmt<T, R>(T, R);
impl<T,R> Copy for RadixFmt<T,R> where T: Copy, R: Copy {}
/// Constructs a radix formatter in the range of `2..36`.
///
/// # Example
///
/// ```
/// use std::fmt::radix;
/// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
/// ```
#[unstable = "may be renamed or move to a different module"]
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base))
}
macro_rules! radix_fmt {
($T:ty as $U:ty, $fmt:ident) => {
impl fmt::Show for RadixFmt<$T, Radix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
}
}
}
}
macro_rules! int_base {
($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
impl fmt::$Trait for $T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
$Radix.fmt_int(*self as $U, f)
}
}
}
}
macro_rules! integer {
($Int:ident, $Uint:ident) => {
int_base!(Show for $Int as $Int -> Decimal)
int_base!(Binary for $Int as $Uint -> Binary)
int_base!(Octal for $Int as $Uint -> Octal)
int_base!(LowerHex for $Int as $Uint -> LowerHex)
int_base!(UpperHex for $Int as $Uint -> UpperHex)
radix_fmt!($Int as $Int, fmt_int)
int_base!(Show for $Uint as $Uint -> Decimal)
int_base!(Binary for $Uint as $Uint -> Binary)
int_base!(Octal for $Uint as $Uint -> Octal)
int_base!(LowerHex for $Uint as $Uint -> LowerHex)
int_base!(UpperHex for $Uint as $Uint -> UpperHex)
radix_fmt!($Uint as $Uint, fmt_int)
}
}
integer!(int, uint)
integer!(i8, u8)
integer!(i16, u16)
integer!(i32, u32)
integer!(i64, u64)
|
{ break }
|
conditional_block
|
num.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.
//! Integer and floating-point number formatting
// FIXME: #6220 Implement floating point formatting
#![allow(unsigned_negation)]
use fmt;
use iter::DoubleEndedIteratorExt;
use kinds::Copy;
use num::{Int, cast};
use slice::SlicePrelude;
/// A type that represents a specific radix
#[doc(hidden)]
trait GenericRadix {
/// The number of digits.
fn base(&self) -> u8;
/// A radix-specific prefix string.
fn
|
(&self) -> &'static str { "" }
/// Converts an integer to corresponding radix digit.
fn digit(&self, x: u8) -> u8;
/// Format an integer using the radix using a formatter.
fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
// The radix can be as low as 2, so we need a buffer of at least 64
// characters for a base 2 number.
let zero = Int::zero();
let is_positive = x >= zero;
let mut buf = [0u8,..64];
let mut curr = buf.len();
let base = cast(self.base()).unwrap();
if is_positive {
// Accumulate each digit of the number from the least significant
// to the most significant figure.
for byte in buf.iter_mut().rev() {
let n = x % base; // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero { break }; // No more digits left to accumulate.
}
} else {
// Do the same as above, but accounting for two's complement.
for byte in buf.iter_mut().rev() {
let n = zero - (x % base); // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero { break }; // No more digits left to accumulate.
}
}
f.pad_integral(is_positive, self.prefix(), buf[curr..])
}
}
/// A binary (base 2) radix
#[deriving(Clone, PartialEq)]
struct Binary;
/// An octal (base 8) radix
#[deriving(Clone, PartialEq)]
struct Octal;
/// A decimal (base 10) radix
#[deriving(Clone, PartialEq)]
struct Decimal;
/// A hexadecimal (base 16) radix, formatted with lower-case characters
#[deriving(Clone, PartialEq)]
struct LowerHex;
/// A hexadecimal (base 16) radix, formatted with upper-case characters
#[deriving(Clone, PartialEq)]
pub struct UpperHex;
macro_rules! radix {
($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
impl GenericRadix for $T {
fn base(&self) -> u8 { $base }
fn prefix(&self) -> &'static str { $prefix }
fn digit(&self, x: u8) -> u8 {
match x {
$($x => $conv,)+
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
}
}
radix!(Binary, 2, "0b", x @ 0... 2 => b'0' + x)
radix!(Octal, 8, "0o", x @ 0... 7 => b'0' + x)
radix!(Decimal, 10, "", x @ 0... 9 => b'0' + x)
radix!(LowerHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'a' + (x - 10))
radix!(UpperHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'A' + (x - 10))
/// A radix with in the range of `2..36`.
#[deriving(Clone, PartialEq)]
#[unstable = "may be renamed or move to a different module"]
pub struct Radix {
base: u8,
}
impl Copy for Radix {}
impl Radix {
fn new(base: u8) -> Radix {
assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
Radix { base: base }
}
}
impl GenericRadix for Radix {
fn base(&self) -> u8 { self.base }
fn digit(&self, x: u8) -> u8 {
match x {
x @ 0... 9 => b'0' + x,
x if x < self.base() => b'a' + (x - 10),
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
/// A helper type for formatting radixes.
#[unstable = "may be renamed or move to a different module"]
pub struct RadixFmt<T, R>(T, R);
impl<T,R> Copy for RadixFmt<T,R> where T: Copy, R: Copy {}
/// Constructs a radix formatter in the range of `2..36`.
///
/// # Example
///
/// ```
/// use std::fmt::radix;
/// assert_eq!(format!("{}", radix(55i, 36)), "1j".to_string());
/// ```
#[unstable = "may be renamed or move to a different module"]
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base))
}
macro_rules! radix_fmt {
($T:ty as $U:ty, $fmt:ident) => {
impl fmt::Show for RadixFmt<$T, Radix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
}
}
}
}
macro_rules! int_base {
($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
impl fmt::$Trait for $T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
$Radix.fmt_int(*self as $U, f)
}
}
}
}
macro_rules! integer {
($Int:ident, $Uint:ident) => {
int_base!(Show for $Int as $Int -> Decimal)
int_base!(Binary for $Int as $Uint -> Binary)
int_base!(Octal for $Int as $Uint -> Octal)
int_base!(LowerHex for $Int as $Uint -> LowerHex)
int_base!(UpperHex for $Int as $Uint -> UpperHex)
radix_fmt!($Int as $Int, fmt_int)
int_base!(Show for $Uint as $Uint -> Decimal)
int_base!(Binary for $Uint as $Uint -> Binary)
int_base!(Octal for $Uint as $Uint -> Octal)
int_base!(LowerHex for $Uint as $Uint -> LowerHex)
int_base!(UpperHex for $Uint as $Uint -> UpperHex)
radix_fmt!($Uint as $Uint, fmt_int)
}
}
integer!(int, uint)
integer!(i8, u8)
integer!(i16, u16)
integer!(i32, u32)
integer!(i64, u64)
|
prefix
|
identifier_name
|
test_unistd.rs
|
extern crate tempdir;
use nix::fcntl;
use nix::unistd::*;
use nix::unistd::ForkResult::*;
use nix::sys::wait::*;
use nix::sys::stat;
use std::{self, env, iter};
use std::ffi::CString;
use std::fs::File;
use std::io::Write;
use std::os::unix::prelude::*;
use tempfile::tempfile;
use tempdir::TempDir;
use libc::{_exit, off_t};
#[test]
fn test_fork_and_waitpid() {
#[allow(unused_variables)]
let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
// Safe: Child only calls `_exit`, which is signal-safe
match fork() {
Ok(Child) => unsafe { _exit(0) },
Ok(Parent { child }) => {
// assert that child was created and pid > 0
let child_raw: ::libc::pid_t = child.into();
assert!(child_raw > 0);
let wait_status = waitpid(child, None);
match wait_status {
// assert that waitpid returned correct status and the pid is the one of the child
Ok(WaitStatus::Exited(pid_t, _)) => assert!(pid_t == child),
// panic, must never happen
s @ Ok(_) => panic!("Child exited {:?}, should never happen", s),
// panic, waitpid should never fail
Err(s) => panic!("Error: waitpid returned Err({:?}", s)
}
},
// panic, fork should never fail unless there is a serious problem with the OS
Err(_) => panic!("Error: Fork Failed")
}
}
#[test]
fn test_wait() {
// Grab FORK_MTX so wait doesn't reap a different test's child process
#[allow(unused_variables)]
let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
// Safe: Child only calls `_exit`, which is signal-safe
let pid = fork();
match pid {
Ok(Child) => unsafe { _exit(0) },
Ok(Parent { child }) => {
let wait_status = wait();
// just assert that (any) one child returns with WaitStatus::Exited
assert_eq!(wait_status, Ok(WaitStatus::Exited(child, 0)));
},
// panic, fork should never fail unless there is a serious problem with the OS
Err(_) => panic!("Error: Fork Failed")
}
}
#[test]
fn test_mkstemp()
|
#[test]
fn test_mkstemp_directory() {
// mkstemp should fail if a directory is given
assert!(mkstemp(&env::temp_dir()).is_err());
}
#[test]
fn test_mkfifo() {
let tempdir = TempDir::new("nix-test_mkfifo").unwrap();
let mkfifo_fifo = tempdir.path().join("mkfifo_fifo");
mkfifo(&mkfifo_fifo, stat::S_IRUSR).unwrap();
let stats = stat::stat(&mkfifo_fifo).unwrap();
let typ = stat::SFlag::from_bits_truncate(stats.st_mode);
assert!(typ == stat::S_IFIFO);
}
#[test]
fn test_mkfifo_directory() {
// mkfifo should fail if a directory is given
assert!(mkfifo(&env::temp_dir(), stat::S_IRUSR).is_err());
}
#[test]
fn test_getpid() {
let pid: ::libc::pid_t = getpid().into();
let ppid: ::libc::pid_t = getppid().into();
assert!(pid > 0);
assert!(ppid > 0);
}
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux_android {
use nix::unistd::gettid;
#[test]
fn test_gettid() {
let tid: ::libc::pid_t = gettid().into();
assert!(tid > 0);
}
}
#[test]
// `getgroups()` and `setgroups()` do not behave as expected on Apple platforms
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
fn test_setgroups() {
// Skip this test when not run as root as `setgroups()` requires root.
if!Uid::current().is_root() {
let stderr = std::io::stderr();
let mut handle = stderr.lock();
writeln!(handle, "test_setgroups requires root privileges. Skipping test.").unwrap();
return;
}
#[allow(unused_variables)]
let m = ::GROUPS_MTX.lock().expect("Mutex got poisoned by another test");
// Save the existing groups
let old_groups = getgroups().unwrap();
// Set some new made up groups
let groups = [Gid::from_raw(123), Gid::from_raw(456)];
setgroups(&groups).unwrap();
let new_groups = getgroups().unwrap();
assert_eq!(new_groups, groups);
// Revert back to the old groups
setgroups(&old_groups).unwrap();
}
#[test]
// `getgroups()` and `setgroups()` do not behave as expected on Apple platforms
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
fn test_initgroups() {
// Skip this test when not run as root as `initgroups()` and `setgroups()`
// require root.
if!Uid::current().is_root() {
let stderr = std::io::stderr();
let mut handle = stderr.lock();
writeln!(handle, "test_initgroups requires root privileges. Skipping test.").unwrap();
return;
}
#[allow(unused_variables)]
let m = ::GROUPS_MTX.lock().expect("Mutex got poisoned by another test");
// Save the existing groups
let old_groups = getgroups().unwrap();
// It doesn't matter if the root user is not called "root" or if a user
// called "root" doesn't exist. We are just checking that the extra,
// made-up group, `123`, is set.
// FIXME: Test the other half of initgroups' functionality: whether the
// groups that the user belongs to are also set.
let user = CString::new("root").unwrap();
let group = Gid::from_raw(123);
let group_list = getgrouplist(&user, group).unwrap();
assert!(group_list.contains(&group));
initgroups(&user, group).unwrap();
let new_groups = getgroups().unwrap();
assert_eq!(new_groups, group_list);
// Revert back to the old groups
setgroups(&old_groups).unwrap();
}
macro_rules! execve_test_factory(
($test_name:ident, $syscall:ident, $exe: expr $(, $pathname:expr, $flags:expr)*) => (
#[test]
fn $test_name() {
#[allow(unused_variables)]
let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
// The `exec`d process will write to `writer`, and we'll read that
// data from `reader`.
let (reader, writer) = pipe().unwrap();
// Safe: Child calls `exit`, `dup`, `close` and the provided `exec*` family function.
// NOTE: Technically, this makes the macro unsafe to use because you could pass anything.
// The tests make sure not to do that, though.
match fork().unwrap() {
Child => {
// Close stdout.
close(1).unwrap();
// Make `writer` be the stdout of the new process.
dup(writer).unwrap();
// exec!
$syscall(
$exe,
$(&CString::new($pathname).unwrap(), )*
&[CString::new(b"".as_ref()).unwrap(),
CString::new(b"-c".as_ref()).unwrap(),
CString::new(b"echo nix!!! && echo foo=$foo && echo baz=$baz"
.as_ref()).unwrap()],
&[CString::new(b"foo=bar".as_ref()).unwrap(),
CString::new(b"baz=quux".as_ref()).unwrap()]
$(, $flags)*).unwrap();
},
Parent { child } => {
// Wait for the child to exit.
waitpid(child, None).unwrap();
// Read 1024 bytes.
let mut buf = [0u8; 1024];
read(reader, &mut buf).unwrap();
// It should contain the things we printed using `/bin/sh`.
let string = String::from_utf8_lossy(&buf);
assert!(string.contains("nix!!!"));
assert!(string.contains("foo=bar"));
assert!(string.contains("baz=quux"));
}
}
}
)
);
cfg_if!{
if #[cfg(target_os = "android")] {
execve_test_factory!(test_execve, execve, &CString::new("/system/bin/sh").unwrap());
execve_test_factory!(test_fexecve, fexecve, File::open("/system/bin/sh").unwrap().into_raw_fd());
} else if #[cfg(any(target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "linux", ))] {
execve_test_factory!(test_execve, execve, &CString::new("/bin/sh").unwrap());
execve_test_factory!(test_fexecve, fexecve, File::open("/bin/sh").unwrap().into_raw_fd());
} else if #[cfg(any(target_os = "ios", target_os = "macos", ))] {
execve_test_factory!(test_execve, execve, &CString::new("/bin/sh").unwrap());
// No fexecve() on macos/ios.
}
}
cfg_if!{
if #[cfg(target_os = "android")] {
execve_test_factory!(test_execveat_empty, execveat, File::open("/system/bin/sh").unwrap().into_raw_fd(),
"", fcntl::AT_EMPTY_PATH);
execve_test_factory!(test_execveat_relative, execveat, File::open("/system/bin/").unwrap().into_raw_fd(),
"./sh", fcntl::AtFlags::empty());
execve_test_factory!(test_execveat_absolute, execveat, File::open("/").unwrap().into_raw_fd(),
"/system/bin/sh", fcntl::AtFlags::empty());
} else if #[cfg(all(target_os = "linux"), any(target_arch ="x86_64", target_arch ="x86"))] {
execve_test_factory!(test_execveat_empty, execveat, File::open("/bin/sh").unwrap().into_raw_fd(),
"", fcntl::AT_EMPTY_PATH);
execve_test_factory!(test_execveat_relative, execveat, File::open("/bin/").unwrap().into_raw_fd(),
"./sh", fcntl::AtFlags::empty());
execve_test_factory!(test_execveat_absolute, execveat, File::open("/").unwrap().into_raw_fd(),
"/bin/sh", fcntl::AtFlags::empty());
}
}
#[test]
fn test_fchdir() {
// fchdir changes the process's cwd
#[allow(unused_variables)]
let m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test");
let tmpdir = TempDir::new("test_fchdir").unwrap();
let tmpdir_path = tmpdir.path().canonicalize().unwrap();
let tmpdir_fd = File::open(&tmpdir_path).unwrap().into_raw_fd();
assert!(fchdir(tmpdir_fd).is_ok());
assert_eq!(getcwd().unwrap(), tmpdir_path);
assert!(close(tmpdir_fd).is_ok());
}
#[test]
fn test_getcwd() {
// chdir changes the process's cwd
#[allow(unused_variables)]
let m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test");
let tmpdir = TempDir::new("test_getcwd").unwrap();
let tmpdir_path = tmpdir.path().canonicalize().unwrap();
assert!(chdir(&tmpdir_path).is_ok());
assert_eq!(getcwd().unwrap(), tmpdir_path);
// make path 500 chars longer so that buffer doubling in getcwd
// kicks in. Note: One path cannot be longer than 255 bytes
// (NAME_MAX) whole path cannot be longer than PATH_MAX (usually
// 4096 on linux, 1024 on macos)
let mut inner_tmp_dir = tmpdir_path.to_path_buf();
for _ in 0..5 {
let newdir = iter::repeat("a").take(100).collect::<String>();
inner_tmp_dir.push(newdir);
assert!(mkdir(inner_tmp_dir.as_path(), stat::S_IRWXU).is_ok());
}
assert!(chdir(inner_tmp_dir.as_path()).is_ok());
assert_eq!(getcwd().unwrap(), inner_tmp_dir.as_path());
}
#[test]
fn test_lseek() {
const CONTENTS: &'static [u8] = b"abcdef123456";
let mut tmp = tempfile().unwrap();
tmp.write_all(CONTENTS).unwrap();
let tmpfd = tmp.into_raw_fd();
let offset: off_t = 5;
lseek(tmpfd, offset, Whence::SeekSet).unwrap();
let mut buf = [0u8; 7];
::read_exact(tmpfd, &mut buf);
assert_eq!(b"f123456", &buf);
close(tmpfd).unwrap();
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[test]
fn test_lseek64() {
const CONTENTS: &'static [u8] = b"abcdef123456";
let mut tmp = tempfile().unwrap();
tmp.write(CONTENTS).unwrap();
let tmpfd = tmp.into_raw_fd();
lseek64(tmpfd, 5, Whence::SeekSet).unwrap();
let mut buf = [0u8; 7];
::read_exact(tmpfd, &mut buf);
assert_eq!(b"f123456", &buf);
close(tmpfd).unwrap();
}
#[test]
fn test_fpathconf_limited() {
let f = tempfile().unwrap();
// AFAIK, PATH_MAX is limited on all platforms, so it makes a good test
let path_max = fpathconf(f.as_raw_fd(), PathconfVar::PATH_MAX);
assert!(path_max.expect("fpathconf failed").expect("PATH_MAX is unlimited") > 0);
}
#[test]
fn test_pathconf_limited() {
// AFAIK, PATH_MAX is limited on all platforms, so it makes a good test
let path_max = pathconf("/", PathconfVar::PATH_MAX);
assert!(path_max.expect("pathconf failed").expect("PATH_MAX is unlimited") > 0);
}
#[test]
fn test_sysconf_limited() {
// AFAIK, OPEN_MAX is limited on all platforms, so it makes a good test
let open_max = sysconf(SysconfVar::OPEN_MAX);
assert!(open_max.expect("sysconf failed").expect("OPEN_MAX is unlimited") > 0);
}
#[cfg(target_os = "freebsd")]
#[test]
fn test_sysconf_unsupported() {
// I know of no sysconf variables that are unsupported everywhere, but
// _XOPEN_CRYPT is unsupported on FreeBSD 11.0, which is one of the platforms
// we test.
let open_max = sysconf(SysconfVar::_XOPEN_CRYPT);
assert!(open_max.expect("sysconf failed").is_none())
}
|
{
let mut path = env::temp_dir();
path.push("nix_tempfile.XXXXXX");
let result = mkstemp(&path);
match result {
Ok((fd, path)) => {
close(fd).unwrap();
unlink(path.as_path()).unwrap();
},
Err(e) => panic!("mkstemp failed: {}", e)
}
}
|
identifier_body
|
test_unistd.rs
|
extern crate tempdir;
use nix::fcntl;
use nix::unistd::*;
use nix::unistd::ForkResult::*;
use nix::sys::wait::*;
use nix::sys::stat;
use std::{self, env, iter};
use std::ffi::CString;
use std::fs::File;
use std::io::Write;
use std::os::unix::prelude::*;
use tempfile::tempfile;
use tempdir::TempDir;
use libc::{_exit, off_t};
#[test]
fn test_fork_and_waitpid() {
#[allow(unused_variables)]
let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
// Safe: Child only calls `_exit`, which is signal-safe
match fork() {
Ok(Child) => unsafe { _exit(0) },
Ok(Parent { child }) => {
// assert that child was created and pid > 0
let child_raw: ::libc::pid_t = child.into();
assert!(child_raw > 0);
let wait_status = waitpid(child, None);
match wait_status {
// assert that waitpid returned correct status and the pid is the one of the child
Ok(WaitStatus::Exited(pid_t, _)) => assert!(pid_t == child),
// panic, must never happen
s @ Ok(_) => panic!("Child exited {:?}, should never happen", s),
// panic, waitpid should never fail
Err(s) => panic!("Error: waitpid returned Err({:?}", s)
}
},
// panic, fork should never fail unless there is a serious problem with the OS
Err(_) => panic!("Error: Fork Failed")
}
}
#[test]
fn test_wait() {
// Grab FORK_MTX so wait doesn't reap a different test's child process
#[allow(unused_variables)]
let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
// Safe: Child only calls `_exit`, which is signal-safe
let pid = fork();
match pid {
Ok(Child) => unsafe { _exit(0) },
Ok(Parent { child }) => {
let wait_status = wait();
// just assert that (any) one child returns with WaitStatus::Exited
assert_eq!(wait_status, Ok(WaitStatus::Exited(child, 0)));
},
// panic, fork should never fail unless there is a serious problem with the OS
Err(_) => panic!("Error: Fork Failed")
}
}
#[test]
fn test_mkstemp() {
let mut path = env::temp_dir();
path.push("nix_tempfile.XXXXXX");
let result = mkstemp(&path);
match result {
Ok((fd, path)) => {
close(fd).unwrap();
unlink(path.as_path()).unwrap();
},
Err(e) => panic!("mkstemp failed: {}", e)
}
}
#[test]
fn test_mkstemp_directory() {
// mkstemp should fail if a directory is given
assert!(mkstemp(&env::temp_dir()).is_err());
}
#[test]
fn test_mkfifo() {
let tempdir = TempDir::new("nix-test_mkfifo").unwrap();
let mkfifo_fifo = tempdir.path().join("mkfifo_fifo");
mkfifo(&mkfifo_fifo, stat::S_IRUSR).unwrap();
let stats = stat::stat(&mkfifo_fifo).unwrap();
let typ = stat::SFlag::from_bits_truncate(stats.st_mode);
assert!(typ == stat::S_IFIFO);
}
#[test]
fn test_mkfifo_directory() {
// mkfifo should fail if a directory is given
assert!(mkfifo(&env::temp_dir(), stat::S_IRUSR).is_err());
}
#[test]
fn
|
() {
let pid: ::libc::pid_t = getpid().into();
let ppid: ::libc::pid_t = getppid().into();
assert!(pid > 0);
assert!(ppid > 0);
}
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux_android {
use nix::unistd::gettid;
#[test]
fn test_gettid() {
let tid: ::libc::pid_t = gettid().into();
assert!(tid > 0);
}
}
#[test]
// `getgroups()` and `setgroups()` do not behave as expected on Apple platforms
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
fn test_setgroups() {
// Skip this test when not run as root as `setgroups()` requires root.
if!Uid::current().is_root() {
let stderr = std::io::stderr();
let mut handle = stderr.lock();
writeln!(handle, "test_setgroups requires root privileges. Skipping test.").unwrap();
return;
}
#[allow(unused_variables)]
let m = ::GROUPS_MTX.lock().expect("Mutex got poisoned by another test");
// Save the existing groups
let old_groups = getgroups().unwrap();
// Set some new made up groups
let groups = [Gid::from_raw(123), Gid::from_raw(456)];
setgroups(&groups).unwrap();
let new_groups = getgroups().unwrap();
assert_eq!(new_groups, groups);
// Revert back to the old groups
setgroups(&old_groups).unwrap();
}
#[test]
// `getgroups()` and `setgroups()` do not behave as expected on Apple platforms
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
fn test_initgroups() {
// Skip this test when not run as root as `initgroups()` and `setgroups()`
// require root.
if!Uid::current().is_root() {
let stderr = std::io::stderr();
let mut handle = stderr.lock();
writeln!(handle, "test_initgroups requires root privileges. Skipping test.").unwrap();
return;
}
#[allow(unused_variables)]
let m = ::GROUPS_MTX.lock().expect("Mutex got poisoned by another test");
// Save the existing groups
let old_groups = getgroups().unwrap();
// It doesn't matter if the root user is not called "root" or if a user
// called "root" doesn't exist. We are just checking that the extra,
// made-up group, `123`, is set.
// FIXME: Test the other half of initgroups' functionality: whether the
// groups that the user belongs to are also set.
let user = CString::new("root").unwrap();
let group = Gid::from_raw(123);
let group_list = getgrouplist(&user, group).unwrap();
assert!(group_list.contains(&group));
initgroups(&user, group).unwrap();
let new_groups = getgroups().unwrap();
assert_eq!(new_groups, group_list);
// Revert back to the old groups
setgroups(&old_groups).unwrap();
}
macro_rules! execve_test_factory(
($test_name:ident, $syscall:ident, $exe: expr $(, $pathname:expr, $flags:expr)*) => (
#[test]
fn $test_name() {
#[allow(unused_variables)]
let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
// The `exec`d process will write to `writer`, and we'll read that
// data from `reader`.
let (reader, writer) = pipe().unwrap();
// Safe: Child calls `exit`, `dup`, `close` and the provided `exec*` family function.
// NOTE: Technically, this makes the macro unsafe to use because you could pass anything.
// The tests make sure not to do that, though.
match fork().unwrap() {
Child => {
// Close stdout.
close(1).unwrap();
// Make `writer` be the stdout of the new process.
dup(writer).unwrap();
// exec!
$syscall(
$exe,
$(&CString::new($pathname).unwrap(), )*
&[CString::new(b"".as_ref()).unwrap(),
CString::new(b"-c".as_ref()).unwrap(),
CString::new(b"echo nix!!! && echo foo=$foo && echo baz=$baz"
.as_ref()).unwrap()],
&[CString::new(b"foo=bar".as_ref()).unwrap(),
CString::new(b"baz=quux".as_ref()).unwrap()]
$(, $flags)*).unwrap();
},
Parent { child } => {
// Wait for the child to exit.
waitpid(child, None).unwrap();
// Read 1024 bytes.
let mut buf = [0u8; 1024];
read(reader, &mut buf).unwrap();
// It should contain the things we printed using `/bin/sh`.
let string = String::from_utf8_lossy(&buf);
assert!(string.contains("nix!!!"));
assert!(string.contains("foo=bar"));
assert!(string.contains("baz=quux"));
}
}
}
)
);
cfg_if!{
if #[cfg(target_os = "android")] {
execve_test_factory!(test_execve, execve, &CString::new("/system/bin/sh").unwrap());
execve_test_factory!(test_fexecve, fexecve, File::open("/system/bin/sh").unwrap().into_raw_fd());
} else if #[cfg(any(target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "linux", ))] {
execve_test_factory!(test_execve, execve, &CString::new("/bin/sh").unwrap());
execve_test_factory!(test_fexecve, fexecve, File::open("/bin/sh").unwrap().into_raw_fd());
} else if #[cfg(any(target_os = "ios", target_os = "macos", ))] {
execve_test_factory!(test_execve, execve, &CString::new("/bin/sh").unwrap());
// No fexecve() on macos/ios.
}
}
cfg_if!{
if #[cfg(target_os = "android")] {
execve_test_factory!(test_execveat_empty, execveat, File::open("/system/bin/sh").unwrap().into_raw_fd(),
"", fcntl::AT_EMPTY_PATH);
execve_test_factory!(test_execveat_relative, execveat, File::open("/system/bin/").unwrap().into_raw_fd(),
"./sh", fcntl::AtFlags::empty());
execve_test_factory!(test_execveat_absolute, execveat, File::open("/").unwrap().into_raw_fd(),
"/system/bin/sh", fcntl::AtFlags::empty());
} else if #[cfg(all(target_os = "linux"), any(target_arch ="x86_64", target_arch ="x86"))] {
execve_test_factory!(test_execveat_empty, execveat, File::open("/bin/sh").unwrap().into_raw_fd(),
"", fcntl::AT_EMPTY_PATH);
execve_test_factory!(test_execveat_relative, execveat, File::open("/bin/").unwrap().into_raw_fd(),
"./sh", fcntl::AtFlags::empty());
execve_test_factory!(test_execveat_absolute, execveat, File::open("/").unwrap().into_raw_fd(),
"/bin/sh", fcntl::AtFlags::empty());
}
}
#[test]
fn test_fchdir() {
// fchdir changes the process's cwd
#[allow(unused_variables)]
let m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test");
let tmpdir = TempDir::new("test_fchdir").unwrap();
let tmpdir_path = tmpdir.path().canonicalize().unwrap();
let tmpdir_fd = File::open(&tmpdir_path).unwrap().into_raw_fd();
assert!(fchdir(tmpdir_fd).is_ok());
assert_eq!(getcwd().unwrap(), tmpdir_path);
assert!(close(tmpdir_fd).is_ok());
}
#[test]
fn test_getcwd() {
// chdir changes the process's cwd
#[allow(unused_variables)]
let m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test");
let tmpdir = TempDir::new("test_getcwd").unwrap();
let tmpdir_path = tmpdir.path().canonicalize().unwrap();
assert!(chdir(&tmpdir_path).is_ok());
assert_eq!(getcwd().unwrap(), tmpdir_path);
// make path 500 chars longer so that buffer doubling in getcwd
// kicks in. Note: One path cannot be longer than 255 bytes
// (NAME_MAX) whole path cannot be longer than PATH_MAX (usually
// 4096 on linux, 1024 on macos)
let mut inner_tmp_dir = tmpdir_path.to_path_buf();
for _ in 0..5 {
let newdir = iter::repeat("a").take(100).collect::<String>();
inner_tmp_dir.push(newdir);
assert!(mkdir(inner_tmp_dir.as_path(), stat::S_IRWXU).is_ok());
}
assert!(chdir(inner_tmp_dir.as_path()).is_ok());
assert_eq!(getcwd().unwrap(), inner_tmp_dir.as_path());
}
#[test]
fn test_lseek() {
const CONTENTS: &'static [u8] = b"abcdef123456";
let mut tmp = tempfile().unwrap();
tmp.write_all(CONTENTS).unwrap();
let tmpfd = tmp.into_raw_fd();
let offset: off_t = 5;
lseek(tmpfd, offset, Whence::SeekSet).unwrap();
let mut buf = [0u8; 7];
::read_exact(tmpfd, &mut buf);
assert_eq!(b"f123456", &buf);
close(tmpfd).unwrap();
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[test]
fn test_lseek64() {
const CONTENTS: &'static [u8] = b"abcdef123456";
let mut tmp = tempfile().unwrap();
tmp.write(CONTENTS).unwrap();
let tmpfd = tmp.into_raw_fd();
lseek64(tmpfd, 5, Whence::SeekSet).unwrap();
let mut buf = [0u8; 7];
::read_exact(tmpfd, &mut buf);
assert_eq!(b"f123456", &buf);
close(tmpfd).unwrap();
}
#[test]
fn test_fpathconf_limited() {
let f = tempfile().unwrap();
// AFAIK, PATH_MAX is limited on all platforms, so it makes a good test
let path_max = fpathconf(f.as_raw_fd(), PathconfVar::PATH_MAX);
assert!(path_max.expect("fpathconf failed").expect("PATH_MAX is unlimited") > 0);
}
#[test]
fn test_pathconf_limited() {
// AFAIK, PATH_MAX is limited on all platforms, so it makes a good test
let path_max = pathconf("/", PathconfVar::PATH_MAX);
assert!(path_max.expect("pathconf failed").expect("PATH_MAX is unlimited") > 0);
}
#[test]
fn test_sysconf_limited() {
// AFAIK, OPEN_MAX is limited on all platforms, so it makes a good test
let open_max = sysconf(SysconfVar::OPEN_MAX);
assert!(open_max.expect("sysconf failed").expect("OPEN_MAX is unlimited") > 0);
}
#[cfg(target_os = "freebsd")]
#[test]
fn test_sysconf_unsupported() {
// I know of no sysconf variables that are unsupported everywhere, but
// _XOPEN_CRYPT is unsupported on FreeBSD 11.0, which is one of the platforms
// we test.
let open_max = sysconf(SysconfVar::_XOPEN_CRYPT);
assert!(open_max.expect("sysconf failed").is_none())
}
|
test_getpid
|
identifier_name
|
test_unistd.rs
|
extern crate tempdir;
use nix::fcntl;
use nix::unistd::*;
use nix::unistd::ForkResult::*;
use nix::sys::wait::*;
use nix::sys::stat;
use std::{self, env, iter};
use std::ffi::CString;
use std::fs::File;
use std::io::Write;
use std::os::unix::prelude::*;
use tempfile::tempfile;
use tempdir::TempDir;
use libc::{_exit, off_t};
#[test]
fn test_fork_and_waitpid() {
#[allow(unused_variables)]
let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
// Safe: Child only calls `_exit`, which is signal-safe
match fork() {
Ok(Child) => unsafe { _exit(0) },
Ok(Parent { child }) => {
// assert that child was created and pid > 0
let child_raw: ::libc::pid_t = child.into();
assert!(child_raw > 0);
let wait_status = waitpid(child, None);
match wait_status {
// assert that waitpid returned correct status and the pid is the one of the child
Ok(WaitStatus::Exited(pid_t, _)) => assert!(pid_t == child),
// panic, must never happen
s @ Ok(_) => panic!("Child exited {:?}, should never happen", s),
// panic, waitpid should never fail
Err(s) => panic!("Error: waitpid returned Err({:?}", s)
}
},
// panic, fork should never fail unless there is a serious problem with the OS
Err(_) => panic!("Error: Fork Failed")
}
}
#[test]
fn test_wait() {
// Grab FORK_MTX so wait doesn't reap a different test's child process
#[allow(unused_variables)]
let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
// Safe: Child only calls `_exit`, which is signal-safe
let pid = fork();
match pid {
Ok(Child) => unsafe { _exit(0) },
Ok(Parent { child }) => {
let wait_status = wait();
// just assert that (any) one child returns with WaitStatus::Exited
assert_eq!(wait_status, Ok(WaitStatus::Exited(child, 0)));
},
// panic, fork should never fail unless there is a serious problem with the OS
Err(_) => panic!("Error: Fork Failed")
}
}
#[test]
fn test_mkstemp() {
let mut path = env::temp_dir();
path.push("nix_tempfile.XXXXXX");
let result = mkstemp(&path);
match result {
Ok((fd, path)) => {
close(fd).unwrap();
unlink(path.as_path()).unwrap();
},
Err(e) => panic!("mkstemp failed: {}", e)
}
}
#[test]
fn test_mkstemp_directory() {
// mkstemp should fail if a directory is given
assert!(mkstemp(&env::temp_dir()).is_err());
}
#[test]
fn test_mkfifo() {
let tempdir = TempDir::new("nix-test_mkfifo").unwrap();
let mkfifo_fifo = tempdir.path().join("mkfifo_fifo");
mkfifo(&mkfifo_fifo, stat::S_IRUSR).unwrap();
let stats = stat::stat(&mkfifo_fifo).unwrap();
let typ = stat::SFlag::from_bits_truncate(stats.st_mode);
assert!(typ == stat::S_IFIFO);
}
#[test]
fn test_mkfifo_directory() {
// mkfifo should fail if a directory is given
assert!(mkfifo(&env::temp_dir(), stat::S_IRUSR).is_err());
}
#[test]
fn test_getpid() {
let pid: ::libc::pid_t = getpid().into();
let ppid: ::libc::pid_t = getppid().into();
assert!(pid > 0);
assert!(ppid > 0);
}
#[cfg(any(target_os = "linux", target_os = "android"))]
mod linux_android {
use nix::unistd::gettid;
#[test]
fn test_gettid() {
let tid: ::libc::pid_t = gettid().into();
assert!(tid > 0);
}
}
#[test]
// `getgroups()` and `setgroups()` do not behave as expected on Apple platforms
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
fn test_setgroups() {
// Skip this test when not run as root as `setgroups()` requires root.
if!Uid::current().is_root() {
let stderr = std::io::stderr();
let mut handle = stderr.lock();
writeln!(handle, "test_setgroups requires root privileges. Skipping test.").unwrap();
return;
}
#[allow(unused_variables)]
let m = ::GROUPS_MTX.lock().expect("Mutex got poisoned by another test");
// Save the existing groups
let old_groups = getgroups().unwrap();
// Set some new made up groups
let groups = [Gid::from_raw(123), Gid::from_raw(456)];
setgroups(&groups).unwrap();
let new_groups = getgroups().unwrap();
assert_eq!(new_groups, groups);
// Revert back to the old groups
setgroups(&old_groups).unwrap();
}
#[test]
// `getgroups()` and `setgroups()` do not behave as expected on Apple platforms
#[cfg(not(any(target_os = "ios", target_os = "macos")))]
fn test_initgroups() {
// Skip this test when not run as root as `initgroups()` and `setgroups()`
// require root.
if!Uid::current().is_root() {
let stderr = std::io::stderr();
let mut handle = stderr.lock();
writeln!(handle, "test_initgroups requires root privileges. Skipping test.").unwrap();
return;
}
#[allow(unused_variables)]
let m = ::GROUPS_MTX.lock().expect("Mutex got poisoned by another test");
// Save the existing groups
let old_groups = getgroups().unwrap();
// It doesn't matter if the root user is not called "root" or if a user
// called "root" doesn't exist. We are just checking that the extra,
// made-up group, `123`, is set.
// FIXME: Test the other half of initgroups' functionality: whether the
// groups that the user belongs to are also set.
let user = CString::new("root").unwrap();
let group = Gid::from_raw(123);
let group_list = getgrouplist(&user, group).unwrap();
assert!(group_list.contains(&group));
initgroups(&user, group).unwrap();
let new_groups = getgroups().unwrap();
assert_eq!(new_groups, group_list);
// Revert back to the old groups
setgroups(&old_groups).unwrap();
}
macro_rules! execve_test_factory(
($test_name:ident, $syscall:ident, $exe: expr $(, $pathname:expr, $flags:expr)*) => (
#[test]
fn $test_name() {
#[allow(unused_variables)]
let m = ::FORK_MTX.lock().expect("Mutex got poisoned by another test");
// The `exec`d process will write to `writer`, and we'll read that
// data from `reader`.
|
match fork().unwrap() {
Child => {
// Close stdout.
close(1).unwrap();
// Make `writer` be the stdout of the new process.
dup(writer).unwrap();
// exec!
$syscall(
$exe,
$(&CString::new($pathname).unwrap(), )*
&[CString::new(b"".as_ref()).unwrap(),
CString::new(b"-c".as_ref()).unwrap(),
CString::new(b"echo nix!!! && echo foo=$foo && echo baz=$baz"
.as_ref()).unwrap()],
&[CString::new(b"foo=bar".as_ref()).unwrap(),
CString::new(b"baz=quux".as_ref()).unwrap()]
$(, $flags)*).unwrap();
},
Parent { child } => {
// Wait for the child to exit.
waitpid(child, None).unwrap();
// Read 1024 bytes.
let mut buf = [0u8; 1024];
read(reader, &mut buf).unwrap();
// It should contain the things we printed using `/bin/sh`.
let string = String::from_utf8_lossy(&buf);
assert!(string.contains("nix!!!"));
assert!(string.contains("foo=bar"));
assert!(string.contains("baz=quux"));
}
}
}
)
);
cfg_if!{
if #[cfg(target_os = "android")] {
execve_test_factory!(test_execve, execve, &CString::new("/system/bin/sh").unwrap());
execve_test_factory!(test_fexecve, fexecve, File::open("/system/bin/sh").unwrap().into_raw_fd());
} else if #[cfg(any(target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd",
target_os = "linux", ))] {
execve_test_factory!(test_execve, execve, &CString::new("/bin/sh").unwrap());
execve_test_factory!(test_fexecve, fexecve, File::open("/bin/sh").unwrap().into_raw_fd());
} else if #[cfg(any(target_os = "ios", target_os = "macos", ))] {
execve_test_factory!(test_execve, execve, &CString::new("/bin/sh").unwrap());
// No fexecve() on macos/ios.
}
}
cfg_if!{
if #[cfg(target_os = "android")] {
execve_test_factory!(test_execveat_empty, execveat, File::open("/system/bin/sh").unwrap().into_raw_fd(),
"", fcntl::AT_EMPTY_PATH);
execve_test_factory!(test_execveat_relative, execveat, File::open("/system/bin/").unwrap().into_raw_fd(),
"./sh", fcntl::AtFlags::empty());
execve_test_factory!(test_execveat_absolute, execveat, File::open("/").unwrap().into_raw_fd(),
"/system/bin/sh", fcntl::AtFlags::empty());
} else if #[cfg(all(target_os = "linux"), any(target_arch ="x86_64", target_arch ="x86"))] {
execve_test_factory!(test_execveat_empty, execveat, File::open("/bin/sh").unwrap().into_raw_fd(),
"", fcntl::AT_EMPTY_PATH);
execve_test_factory!(test_execveat_relative, execveat, File::open("/bin/").unwrap().into_raw_fd(),
"./sh", fcntl::AtFlags::empty());
execve_test_factory!(test_execveat_absolute, execveat, File::open("/").unwrap().into_raw_fd(),
"/bin/sh", fcntl::AtFlags::empty());
}
}
#[test]
fn test_fchdir() {
// fchdir changes the process's cwd
#[allow(unused_variables)]
let m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test");
let tmpdir = TempDir::new("test_fchdir").unwrap();
let tmpdir_path = tmpdir.path().canonicalize().unwrap();
let tmpdir_fd = File::open(&tmpdir_path).unwrap().into_raw_fd();
assert!(fchdir(tmpdir_fd).is_ok());
assert_eq!(getcwd().unwrap(), tmpdir_path);
assert!(close(tmpdir_fd).is_ok());
}
#[test]
fn test_getcwd() {
// chdir changes the process's cwd
#[allow(unused_variables)]
let m = ::CWD_MTX.lock().expect("Mutex got poisoned by another test");
let tmpdir = TempDir::new("test_getcwd").unwrap();
let tmpdir_path = tmpdir.path().canonicalize().unwrap();
assert!(chdir(&tmpdir_path).is_ok());
assert_eq!(getcwd().unwrap(), tmpdir_path);
// make path 500 chars longer so that buffer doubling in getcwd
// kicks in. Note: One path cannot be longer than 255 bytes
// (NAME_MAX) whole path cannot be longer than PATH_MAX (usually
// 4096 on linux, 1024 on macos)
let mut inner_tmp_dir = tmpdir_path.to_path_buf();
for _ in 0..5 {
let newdir = iter::repeat("a").take(100).collect::<String>();
inner_tmp_dir.push(newdir);
assert!(mkdir(inner_tmp_dir.as_path(), stat::S_IRWXU).is_ok());
}
assert!(chdir(inner_tmp_dir.as_path()).is_ok());
assert_eq!(getcwd().unwrap(), inner_tmp_dir.as_path());
}
#[test]
fn test_lseek() {
const CONTENTS: &'static [u8] = b"abcdef123456";
let mut tmp = tempfile().unwrap();
tmp.write_all(CONTENTS).unwrap();
let tmpfd = tmp.into_raw_fd();
let offset: off_t = 5;
lseek(tmpfd, offset, Whence::SeekSet).unwrap();
let mut buf = [0u8; 7];
::read_exact(tmpfd, &mut buf);
assert_eq!(b"f123456", &buf);
close(tmpfd).unwrap();
}
#[cfg(any(target_os = "linux", target_os = "android"))]
#[test]
fn test_lseek64() {
const CONTENTS: &'static [u8] = b"abcdef123456";
let mut tmp = tempfile().unwrap();
tmp.write(CONTENTS).unwrap();
let tmpfd = tmp.into_raw_fd();
lseek64(tmpfd, 5, Whence::SeekSet).unwrap();
let mut buf = [0u8; 7];
::read_exact(tmpfd, &mut buf);
assert_eq!(b"f123456", &buf);
close(tmpfd).unwrap();
}
#[test]
fn test_fpathconf_limited() {
let f = tempfile().unwrap();
// AFAIK, PATH_MAX is limited on all platforms, so it makes a good test
let path_max = fpathconf(f.as_raw_fd(), PathconfVar::PATH_MAX);
assert!(path_max.expect("fpathconf failed").expect("PATH_MAX is unlimited") > 0);
}
#[test]
fn test_pathconf_limited() {
// AFAIK, PATH_MAX is limited on all platforms, so it makes a good test
let path_max = pathconf("/", PathconfVar::PATH_MAX);
assert!(path_max.expect("pathconf failed").expect("PATH_MAX is unlimited") > 0);
}
#[test]
fn test_sysconf_limited() {
// AFAIK, OPEN_MAX is limited on all platforms, so it makes a good test
let open_max = sysconf(SysconfVar::OPEN_MAX);
assert!(open_max.expect("sysconf failed").expect("OPEN_MAX is unlimited") > 0);
}
#[cfg(target_os = "freebsd")]
#[test]
fn test_sysconf_unsupported() {
// I know of no sysconf variables that are unsupported everywhere, but
// _XOPEN_CRYPT is unsupported on FreeBSD 11.0, which is one of the platforms
// we test.
let open_max = sysconf(SysconfVar::_XOPEN_CRYPT);
assert!(open_max.expect("sysconf failed").is_none())
}
|
let (reader, writer) = pipe().unwrap();
// Safe: Child calls `exit`, `dup`, `close` and the provided `exec*` family function.
// NOTE: Technically, this makes the macro unsafe to use because you could pass anything.
// The tests make sure not to do that, though.
|
random_line_split
|
item.rs
|
use std::any::Any;
use std::any::TypeId;
use std::fmt;
use std::str::from_utf8;
use typeable::Typeable;
use super::cell::{OptCell, PtrMapCell};
use header::{Header, HeaderFormat};
#[derive(Clone)]
pub struct Item {
raw: OptCell<Vec<Vec<u8>>>,
typed: PtrMapCell<HeaderFormat + Send + Sync>
}
impl Item {
#[inline]
pub fn new_raw(data: Vec<Vec<u8>>) -> Item {
Item {
raw: OptCell::new(Some(data)),
typed: PtrMapCell::new(),
}
}
#[inline]
pub fn new_typed(ty: Box<HeaderFormat + Send + Sync>) -> Item
|
#[inline]
pub fn mut_raw(&mut self) -> &mut Vec<Vec<u8>> {
self.typed = PtrMapCell::new();
unsafe {
self.raw.get_mut()
}
}
pub fn raw(&self) -> &[Vec<u8>] {
if let Some(ref raw) = *self.raw {
return &raw[..];
}
let raw = vec![unsafe { self.typed.one() }.to_string().into_bytes()];
self.raw.set(raw);
let raw = self.raw.as_ref().unwrap();
&raw[..]
}
pub fn typed<H: Header + HeaderFormat + Any>(&self) -> Option<&H> {
let tid = TypeId::of::<H>();
match self.typed.get(tid) {
Some(val) => Some(val),
None => {
match parse::<H>(self.raw.as_ref().expect("item.raw must exist")) {
Ok(typed) => {
unsafe { self.typed.insert(tid, typed); }
self.typed.get(tid)
},
Err(_) => None
}
}
}.map(|typed| unsafe { typed.downcast_ref_unchecked() })
}
pub fn typed_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> {
let tid = TypeId::of::<H>();
if self.typed.get_mut(tid).is_none() {
match parse::<H>(self.raw.as_ref().expect("item.raw must exist")) {
Ok(typed) => {
unsafe { self.typed.insert(tid, typed); }
},
Err(_) => ()
}
}
self.typed.get_mut(tid).map(|typed| unsafe { typed.downcast_mut_unchecked() })
}
}
#[inline]
fn parse<H: Header + HeaderFormat>(raw: &Vec<Vec<u8>>) -> ::Result<Box<HeaderFormat + Send + Sync>> {
Header::parse_header(&raw[..]).map(|h: H| {
// FIXME: Use Type ascription
let h: Box<HeaderFormat + Send + Sync> = Box::new(h);
h
})
}
impl fmt::Display for Item {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.raw {
Some(ref raw) => {
for part in raw.iter() {
match from_utf8(&part[..]) {
Ok(s) => try!(f.write_str(s)),
Err(e) => {
error!("raw header value is not utf8. header={:?}, error={:?}", part, e);
return Err(fmt::Error);
}
}
}
Ok(())
},
None => fmt::Display::fmt(&unsafe { self.typed.one() }, f)
}
}
}
|
{
let map = PtrMapCell::new();
unsafe { map.insert((*ty).get_type(), ty); }
Item {
raw: OptCell::new(None),
typed: map,
}
}
|
identifier_body
|
item.rs
|
use std::any::Any;
use std::any::TypeId;
use std::fmt;
use std::str::from_utf8;
use typeable::Typeable;
use super::cell::{OptCell, PtrMapCell};
use header::{Header, HeaderFormat};
#[derive(Clone)]
pub struct Item {
raw: OptCell<Vec<Vec<u8>>>,
typed: PtrMapCell<HeaderFormat + Send + Sync>
}
impl Item {
#[inline]
pub fn new_raw(data: Vec<Vec<u8>>) -> Item {
Item {
raw: OptCell::new(Some(data)),
typed: PtrMapCell::new(),
}
}
#[inline]
pub fn new_typed(ty: Box<HeaderFormat + Send + Sync>) -> Item {
let map = PtrMapCell::new();
unsafe { map.insert((*ty).get_type(), ty); }
Item {
raw: OptCell::new(None),
typed: map,
}
}
#[inline]
pub fn mut_raw(&mut self) -> &mut Vec<Vec<u8>> {
self.typed = PtrMapCell::new();
unsafe {
self.raw.get_mut()
}
}
pub fn raw(&self) -> &[Vec<u8>] {
if let Some(ref raw) = *self.raw {
return &raw[..];
}
let raw = vec![unsafe { self.typed.one() }.to_string().into_bytes()];
self.raw.set(raw);
let raw = self.raw.as_ref().unwrap();
&raw[..]
}
pub fn
|
<H: Header + HeaderFormat + Any>(&self) -> Option<&H> {
let tid = TypeId::of::<H>();
match self.typed.get(tid) {
Some(val) => Some(val),
None => {
match parse::<H>(self.raw.as_ref().expect("item.raw must exist")) {
Ok(typed) => {
unsafe { self.typed.insert(tid, typed); }
self.typed.get(tid)
},
Err(_) => None
}
}
}.map(|typed| unsafe { typed.downcast_ref_unchecked() })
}
pub fn typed_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> {
let tid = TypeId::of::<H>();
if self.typed.get_mut(tid).is_none() {
match parse::<H>(self.raw.as_ref().expect("item.raw must exist")) {
Ok(typed) => {
unsafe { self.typed.insert(tid, typed); }
},
Err(_) => ()
}
}
self.typed.get_mut(tid).map(|typed| unsafe { typed.downcast_mut_unchecked() })
}
}
#[inline]
fn parse<H: Header + HeaderFormat>(raw: &Vec<Vec<u8>>) -> ::Result<Box<HeaderFormat + Send + Sync>> {
Header::parse_header(&raw[..]).map(|h: H| {
// FIXME: Use Type ascription
let h: Box<HeaderFormat + Send + Sync> = Box::new(h);
h
})
}
impl fmt::Display for Item {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.raw {
Some(ref raw) => {
for part in raw.iter() {
match from_utf8(&part[..]) {
Ok(s) => try!(f.write_str(s)),
Err(e) => {
error!("raw header value is not utf8. header={:?}, error={:?}", part, e);
return Err(fmt::Error);
}
}
}
Ok(())
},
None => fmt::Display::fmt(&unsafe { self.typed.one() }, f)
}
}
}
|
typed
|
identifier_name
|
item.rs
|
use std::any::Any;
use std::any::TypeId;
use std::fmt;
use std::str::from_utf8;
use typeable::Typeable;
use super::cell::{OptCell, PtrMapCell};
use header::{Header, HeaderFormat};
#[derive(Clone)]
pub struct Item {
raw: OptCell<Vec<Vec<u8>>>,
typed: PtrMapCell<HeaderFormat + Send + Sync>
}
impl Item {
#[inline]
pub fn new_raw(data: Vec<Vec<u8>>) -> Item {
Item {
raw: OptCell::new(Some(data)),
typed: PtrMapCell::new(),
}
}
#[inline]
pub fn new_typed(ty: Box<HeaderFormat + Send + Sync>) -> Item {
let map = PtrMapCell::new();
unsafe { map.insert((*ty).get_type(), ty); }
Item {
raw: OptCell::new(None),
typed: map,
}
}
#[inline]
pub fn mut_raw(&mut self) -> &mut Vec<Vec<u8>> {
self.typed = PtrMapCell::new();
unsafe {
self.raw.get_mut()
}
}
pub fn raw(&self) -> &[Vec<u8>] {
if let Some(ref raw) = *self.raw {
return &raw[..];
}
let raw = vec![unsafe { self.typed.one() }.to_string().into_bytes()];
self.raw.set(raw);
let raw = self.raw.as_ref().unwrap();
&raw[..]
}
pub fn typed<H: Header + HeaderFormat + Any>(&self) -> Option<&H> {
let tid = TypeId::of::<H>();
match self.typed.get(tid) {
Some(val) => Some(val),
None => {
match parse::<H>(self.raw.as_ref().expect("item.raw must exist")) {
Ok(typed) => {
unsafe { self.typed.insert(tid, typed); }
self.typed.get(tid)
},
Err(_) => None
}
}
}.map(|typed| unsafe { typed.downcast_ref_unchecked() })
}
pub fn typed_mut<H: Header + HeaderFormat>(&mut self) -> Option<&mut H> {
let tid = TypeId::of::<H>();
if self.typed.get_mut(tid).is_none() {
match parse::<H>(self.raw.as_ref().expect("item.raw must exist")) {
Ok(typed) => {
unsafe { self.typed.insert(tid, typed); }
},
Err(_) => ()
}
}
|
#[inline]
fn parse<H: Header + HeaderFormat>(raw: &Vec<Vec<u8>>) -> ::Result<Box<HeaderFormat + Send + Sync>> {
Header::parse_header(&raw[..]).map(|h: H| {
// FIXME: Use Type ascription
let h: Box<HeaderFormat + Send + Sync> = Box::new(h);
h
})
}
impl fmt::Display for Item {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.raw {
Some(ref raw) => {
for part in raw.iter() {
match from_utf8(&part[..]) {
Ok(s) => try!(f.write_str(s)),
Err(e) => {
error!("raw header value is not utf8. header={:?}, error={:?}", part, e);
return Err(fmt::Error);
}
}
}
Ok(())
},
None => fmt::Display::fmt(&unsafe { self.typed.one() }, f)
}
}
}
|
self.typed.get_mut(tid).map(|typed| unsafe { typed.downcast_mut_unchecked() })
}
}
|
random_line_split
|
expr-match-generic.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.
// xfail-fast
// -*- rust -*-
type compare<T> = extern "Rust" fn(T, T) -> bool;
fn test_generic<T:Clone>(expected: T, eq: compare<T>) {
let actual: T = match true { true => { expected.clone() }, _ => fail!("wat") };
assert!((eq(expected, actual)));
}
fn test_bool() {
fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; }
test_generic::<bool>(true, compare_bool);
}
#[deriving(Clone)]
struct Pair {
a: int,
b: int,
}
fn test_rec() {
fn
|
(t1: Pair, t2: Pair) -> bool {
t1.a == t2.a && t1.b == t2.b
}
test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec);
}
pub fn main() { test_bool(); test_rec(); }
|
compare_rec
|
identifier_name
|
expr-match-generic.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.
// xfail-fast
// -*- rust -*-
type compare<T> = extern "Rust" fn(T, T) -> bool;
fn test_generic<T:Clone>(expected: T, eq: compare<T>) {
let actual: T = match true { true => { expected.clone() }, _ => fail!("wat") };
assert!((eq(expected, actual)));
}
fn test_bool()
|
#[deriving(Clone)]
struct Pair {
a: int,
b: int,
}
fn test_rec() {
fn compare_rec(t1: Pair, t2: Pair) -> bool {
t1.a == t2.a && t1.b == t2.b
}
test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec);
}
pub fn main() { test_bool(); test_rec(); }
|
{
fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; }
test_generic::<bool>(true, compare_bool);
}
|
identifier_body
|
expr-match-generic.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.
// xfail-fast
// -*- rust -*-
type compare<T> = extern "Rust" fn(T, T) -> bool;
fn test_generic<T:Clone>(expected: T, eq: compare<T>) {
let actual: T = match true { true => { expected.clone() }, _ => fail!("wat") };
assert!((eq(expected, actual)));
}
fn test_bool() {
fn compare_bool(b1: bool, b2: bool) -> bool { return b1 == b2; }
test_generic::<bool>(true, compare_bool);
}
#[deriving(Clone)]
struct Pair {
a: int,
b: int,
}
fn test_rec() {
fn compare_rec(t1: Pair, t2: Pair) -> bool {
t1.a == t2.a && t1.b == t2.b
}
test_generic::<Pair>(Pair {a: 1, b: 2}, compare_rec);
}
pub fn main() { test_bool(); test_rec(); }
|
random_line_split
|
|
issue-85454.rs
|
// aux-build:issue-85454.rs
// build-aux-docs
#![crate_name = "foo"]
extern crate issue_85454;
// @has foo/trait.FromResidual.html
// @has - '//pre[@class="rust trait"]' 'pub trait FromResidual<R = <Self as Try>::Residual> { fn from_residual(residual: R) -> Self; }'
pub trait FromResidual<R = <Self as Try>::Residual> {
fn from_residual(residual: R) -> Self;
}
pub trait Try: FromResidual {
type Output;
type Residual;
fn from_output(output: Self::Output) -> Self;
|
Break(B),
}
pub mod reexport {
// @has foo/reexport/trait.FromResidual.html
// @has - '//pre[@class="rust trait"]' 'pub trait FromResidual<R = <Self as Try>::Residual> { fn from_residual(residual: R) -> Self; }'
pub use issue_85454::*;
}
|
fn branch(self) -> ControlFlow<Self::Residual, Self::Output>;
}
pub enum ControlFlow<B, C = ()> {
Continue(C),
|
random_line_split
|
issue-85454.rs
|
// aux-build:issue-85454.rs
// build-aux-docs
#![crate_name = "foo"]
extern crate issue_85454;
// @has foo/trait.FromResidual.html
// @has - '//pre[@class="rust trait"]' 'pub trait FromResidual<R = <Self as Try>::Residual> { fn from_residual(residual: R) -> Self; }'
pub trait FromResidual<R = <Self as Try>::Residual> {
fn from_residual(residual: R) -> Self;
}
pub trait Try: FromResidual {
type Output;
type Residual;
fn from_output(output: Self::Output) -> Self;
fn branch(self) -> ControlFlow<Self::Residual, Self::Output>;
}
pub enum
|
<B, C = ()> {
Continue(C),
Break(B),
}
pub mod reexport {
// @has foo/reexport/trait.FromResidual.html
// @has - '//pre[@class="rust trait"]' 'pub trait FromResidual<R = <Self as Try>::Residual> { fn from_residual(residual: R) -> Self; }'
pub use issue_85454::*;
}
|
ControlFlow
|
identifier_name
|
idcode.rs
|
use std::fmt::{self, Display};
use std::str::FromStr;
use crate::InvalidData;
/// An ID used within the file to refer to a particular variable.
#[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct IdCode(u64);
const ID_CHAR_MIN: u8 = b'!';
const ID_CHAR_MAX: u8 = b'~';
const NUM_ID_CHARS: u64 = (ID_CHAR_MAX - ID_CHAR_MIN + 1) as u64;
impl IdCode {
fn new(v: &[u8]) -> Result<IdCode, InvalidData> {
if v.is_empty() {
return Err(InvalidData("ID cannot be empty"));
}
let mut result = 0u64;
for &i in v.iter().rev() {
if i < ID_CHAR_MIN || i > ID_CHAR_MAX {
return Err(InvalidData("invalid characters in ID"));
}
let c = ((i - ID_CHAR_MIN) as u64) + 1;
result = result
.checked_mul(NUM_ID_CHARS)
.and_then(|x| x.checked_add(c))
.ok_or(InvalidData("ID too long"))?;
}
Ok(IdCode(result - 1))
}
/// An arbitrary IdCode with a short representation.
pub const FIRST: IdCode = IdCode(0);
/// Returns the IdCode following this one in an arbitrary sequence.
pub fn next(&self) -> IdCode {
IdCode(self.0 + 1)
}
}
impl FromStr for IdCode {
type Err = InvalidData;
fn from_str(s: &str) -> Result<Self, Self::Err> {
IdCode::new(s.as_bytes())
}
}
impl From<u32> for IdCode {
fn from(i: u32) -> IdCode {
IdCode(i as u64)
}
}
impl From<u64> for IdCode {
fn from(i: u64) -> IdCode {
IdCode(i)
}
}
impl Display for IdCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut i = self.0;
loop {
let r = i % NUM_ID_CHARS;
write!(f, "{}", (r as u8 + ID_CHAR_MIN) as char)?;
if i < NUM_ID_CHARS {
break;
}
i = i / NUM_ID_CHARS - 1;
}
Ok(())
}
}
#[test]
fn test_id_code()
|
"n999999999"
);
assert!("n9999999999".parse::<IdCode>().is_err());
}
|
{
let mut id = IdCode::FIRST;
for i in 0..10000 {
println!("{} {}", i, id);
assert_eq!(id.to_string().parse::<IdCode>().unwrap(), id);
id = id.next();
}
assert_eq!("!".parse::<IdCode>().unwrap().to_string(), "!");
assert_eq!(
"!!!!!!!!!!".parse::<IdCode>().unwrap().to_string(),
"!!!!!!!!!!"
);
assert_eq!("~".parse::<IdCode>().unwrap().to_string(), "~");
assert_eq!(
"~~~~~~~~~".parse::<IdCode>().unwrap().to_string(),
"~~~~~~~~~"
);
assert_eq!(
"n999999999".parse::<IdCode>().unwrap().to_string(),
|
identifier_body
|
idcode.rs
|
use std::fmt::{self, Display};
use std::str::FromStr;
use crate::InvalidData;
/// An ID used within the file to refer to a particular variable.
#[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct IdCode(u64);
const ID_CHAR_MIN: u8 = b'!';
const ID_CHAR_MAX: u8 = b'~';
const NUM_ID_CHARS: u64 = (ID_CHAR_MAX - ID_CHAR_MIN + 1) as u64;
impl IdCode {
fn new(v: &[u8]) -> Result<IdCode, InvalidData> {
if v.is_empty() {
return Err(InvalidData("ID cannot be empty"));
}
let mut result = 0u64;
for &i in v.iter().rev() {
if i < ID_CHAR_MIN || i > ID_CHAR_MAX {
return Err(InvalidData("invalid characters in ID"));
}
let c = ((i - ID_CHAR_MIN) as u64) + 1;
result = result
.checked_mul(NUM_ID_CHARS)
.and_then(|x| x.checked_add(c))
.ok_or(InvalidData("ID too long"))?;
}
Ok(IdCode(result - 1))
}
/// An arbitrary IdCode with a short representation.
pub const FIRST: IdCode = IdCode(0);
/// Returns the IdCode following this one in an arbitrary sequence.
pub fn next(&self) -> IdCode {
IdCode(self.0 + 1)
}
}
impl FromStr for IdCode {
type Err = InvalidData;
fn
|
(s: &str) -> Result<Self, Self::Err> {
IdCode::new(s.as_bytes())
}
}
impl From<u32> for IdCode {
fn from(i: u32) -> IdCode {
IdCode(i as u64)
}
}
impl From<u64> for IdCode {
fn from(i: u64) -> IdCode {
IdCode(i)
}
}
impl Display for IdCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut i = self.0;
loop {
let r = i % NUM_ID_CHARS;
write!(f, "{}", (r as u8 + ID_CHAR_MIN) as char)?;
if i < NUM_ID_CHARS {
break;
}
i = i / NUM_ID_CHARS - 1;
}
Ok(())
}
}
#[test]
fn test_id_code() {
let mut id = IdCode::FIRST;
for i in 0..10000 {
println!("{} {}", i, id);
assert_eq!(id.to_string().parse::<IdCode>().unwrap(), id);
id = id.next();
}
assert_eq!("!".parse::<IdCode>().unwrap().to_string(), "!");
assert_eq!(
"!!!!!!!!!!".parse::<IdCode>().unwrap().to_string(),
"!!!!!!!!!!"
);
assert_eq!("~".parse::<IdCode>().unwrap().to_string(), "~");
assert_eq!(
"~~~~~~~~~".parse::<IdCode>().unwrap().to_string(),
"~~~~~~~~~"
);
assert_eq!(
"n999999999".parse::<IdCode>().unwrap().to_string(),
"n999999999"
);
assert!("n9999999999".parse::<IdCode>().is_err());
}
|
from_str
|
identifier_name
|
idcode.rs
|
use std::fmt::{self, Display};
use std::str::FromStr;
use crate::InvalidData;
/// An ID used within the file to refer to a particular variable.
#[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct IdCode(u64);
const ID_CHAR_MIN: u8 = b'!';
const ID_CHAR_MAX: u8 = b'~';
const NUM_ID_CHARS: u64 = (ID_CHAR_MAX - ID_CHAR_MIN + 1) as u64;
impl IdCode {
fn new(v: &[u8]) -> Result<IdCode, InvalidData> {
if v.is_empty()
|
let mut result = 0u64;
for &i in v.iter().rev() {
if i < ID_CHAR_MIN || i > ID_CHAR_MAX {
return Err(InvalidData("invalid characters in ID"));
}
let c = ((i - ID_CHAR_MIN) as u64) + 1;
result = result
.checked_mul(NUM_ID_CHARS)
.and_then(|x| x.checked_add(c))
.ok_or(InvalidData("ID too long"))?;
}
Ok(IdCode(result - 1))
}
/// An arbitrary IdCode with a short representation.
pub const FIRST: IdCode = IdCode(0);
/// Returns the IdCode following this one in an arbitrary sequence.
pub fn next(&self) -> IdCode {
IdCode(self.0 + 1)
}
}
impl FromStr for IdCode {
type Err = InvalidData;
fn from_str(s: &str) -> Result<Self, Self::Err> {
IdCode::new(s.as_bytes())
}
}
impl From<u32> for IdCode {
fn from(i: u32) -> IdCode {
IdCode(i as u64)
}
}
impl From<u64> for IdCode {
fn from(i: u64) -> IdCode {
IdCode(i)
}
}
impl Display for IdCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut i = self.0;
loop {
let r = i % NUM_ID_CHARS;
write!(f, "{}", (r as u8 + ID_CHAR_MIN) as char)?;
if i < NUM_ID_CHARS {
break;
}
i = i / NUM_ID_CHARS - 1;
}
Ok(())
}
}
#[test]
fn test_id_code() {
let mut id = IdCode::FIRST;
for i in 0..10000 {
println!("{} {}", i, id);
assert_eq!(id.to_string().parse::<IdCode>().unwrap(), id);
id = id.next();
}
assert_eq!("!".parse::<IdCode>().unwrap().to_string(), "!");
assert_eq!(
"!!!!!!!!!!".parse::<IdCode>().unwrap().to_string(),
"!!!!!!!!!!"
);
assert_eq!("~".parse::<IdCode>().unwrap().to_string(), "~");
assert_eq!(
"~~~~~~~~~".parse::<IdCode>().unwrap().to_string(),
"~~~~~~~~~"
);
assert_eq!(
"n999999999".parse::<IdCode>().unwrap().to_string(),
"n999999999"
);
assert!("n9999999999".parse::<IdCode>().is_err());
}
|
{
return Err(InvalidData("ID cannot be empty"));
}
|
conditional_block
|
idcode.rs
|
use std::fmt::{self, Display};
use std::str::FromStr;
use crate::InvalidData;
/// An ID used within the file to refer to a particular variable.
#[derive(Debug, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Hash)]
pub struct IdCode(u64);
const ID_CHAR_MIN: u8 = b'!';
const ID_CHAR_MAX: u8 = b'~';
const NUM_ID_CHARS: u64 = (ID_CHAR_MAX - ID_CHAR_MIN + 1) as u64;
impl IdCode {
fn new(v: &[u8]) -> Result<IdCode, InvalidData> {
if v.is_empty() {
return Err(InvalidData("ID cannot be empty"));
}
let mut result = 0u64;
for &i in v.iter().rev() {
if i < ID_CHAR_MIN || i > ID_CHAR_MAX {
return Err(InvalidData("invalid characters in ID"));
}
let c = ((i - ID_CHAR_MIN) as u64) + 1;
result = result
.checked_mul(NUM_ID_CHARS)
.and_then(|x| x.checked_add(c))
.ok_or(InvalidData("ID too long"))?;
}
Ok(IdCode(result - 1))
}
/// An arbitrary IdCode with a short representation.
pub const FIRST: IdCode = IdCode(0);
/// Returns the IdCode following this one in an arbitrary sequence.
pub fn next(&self) -> IdCode {
IdCode(self.0 + 1)
}
}
impl FromStr for IdCode {
type Err = InvalidData;
fn from_str(s: &str) -> Result<Self, Self::Err> {
IdCode::new(s.as_bytes())
}
}
impl From<u32> for IdCode {
fn from(i: u32) -> IdCode {
IdCode(i as u64)
}
}
impl From<u64> for IdCode {
fn from(i: u64) -> IdCode {
IdCode(i)
}
}
impl Display for IdCode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut i = self.0;
loop {
let r = i % NUM_ID_CHARS;
write!(f, "{}", (r as u8 + ID_CHAR_MIN) as char)?;
if i < NUM_ID_CHARS {
break;
}
i = i / NUM_ID_CHARS - 1;
}
Ok(())
}
}
|
#[test]
fn test_id_code() {
let mut id = IdCode::FIRST;
for i in 0..10000 {
println!("{} {}", i, id);
assert_eq!(id.to_string().parse::<IdCode>().unwrap(), id);
id = id.next();
}
assert_eq!("!".parse::<IdCode>().unwrap().to_string(), "!");
assert_eq!(
"!!!!!!!!!!".parse::<IdCode>().unwrap().to_string(),
"!!!!!!!!!!"
);
assert_eq!("~".parse::<IdCode>().unwrap().to_string(), "~");
assert_eq!(
"~~~~~~~~~".parse::<IdCode>().unwrap().to_string(),
"~~~~~~~~~"
);
assert_eq!(
"n999999999".parse::<IdCode>().unwrap().to_string(),
"n999999999"
);
assert!("n9999999999".parse::<IdCode>().is_err());
}
|
random_line_split
|
|
check_static_recursion.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.
// This compiler pass detects constants that refer to themselves
// recursively.
use ast_map;
use session::Session;
use middle::def::{DefStatic, DefConst, DefAssociatedConst, DefVariant, DefMap};
use util::nodemap::NodeMap;
use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::feature_gate::emit_feature_err;
use syntax::visit::Visitor;
use syntax::visit;
use std::cell::RefCell;
struct CheckCrateVisitor<'a, 'ast: 'a> {
sess: &'a Session,
def_map: &'a DefMap,
ast_map: &'a ast_map::Map<'ast>,
// `discriminant_map` is a cache that associates the `NodeId`s of local
// variant definitions with the discriminant expression that applies to
// each one. If the variant uses the default values (starting from `0`),
// then `None` is stored.
discriminant_map: RefCell<NodeMap<Option<&'ast ast::Expr>>>,
}
impl<'a, 'ast: 'a> Visitor<'ast> for CheckCrateVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &'ast ast::Item) {
match it.node {
|
},
ast::ItemEnum(ref enum_def, ref generics) => {
// We could process the whole enum, but handling the variants
// with discriminant expressions one by one gives more specific,
// less redundant output.
for variant in &enum_def.variants {
if let Some(_) = variant.node.disr_expr {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &variant.span);
recursion_visitor.populate_enum_discriminants(enum_def);
recursion_visitor.visit_variant(variant, generics);
}
}
}
_ => {}
}
visit::walk_item(self, it)
}
fn visit_trait_item(&mut self, ti: &'ast ast::TraitItem) {
match ti.node {
ast::ConstTraitItem(_, ref default) => {
if let Some(_) = *default {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ti.span);
recursion_visitor.visit_trait_item(ti);
}
}
_ => {}
}
visit::walk_trait_item(self, ti)
}
fn visit_impl_item(&mut self, ii: &'ast ast::ImplItem) {
match ii.node {
ast::ConstImplItem(..) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ii.span);
recursion_visitor.visit_impl_item(ii);
}
_ => {}
}
visit::walk_impl_item(self, ii)
}
}
pub fn check_crate<'ast>(sess: &Session,
krate: &'ast ast::Crate,
def_map: &DefMap,
ast_map: &ast_map::Map<'ast>) {
let mut visitor = CheckCrateVisitor {
sess: sess,
def_map: def_map,
ast_map: ast_map,
discriminant_map: RefCell::new(NodeMap()),
};
visit::walk_crate(&mut visitor, krate);
sess.abort_if_errors();
}
struct CheckItemRecursionVisitor<'a, 'ast: 'a> {
root_span: &'a Span,
sess: &'a Session,
ast_map: &'a ast_map::Map<'ast>,
def_map: &'a DefMap,
discriminant_map: &'a RefCell<NodeMap<Option<&'ast ast::Expr>>>,
idstack: Vec<ast::NodeId>,
}
impl<'a, 'ast: 'a> CheckItemRecursionVisitor<'a, 'ast> {
fn new(v: &'a CheckCrateVisitor<'a, 'ast>, span: &'a Span)
-> CheckItemRecursionVisitor<'a, 'ast> {
CheckItemRecursionVisitor {
root_span: span,
sess: v.sess,
ast_map: v.ast_map,
def_map: v.def_map,
discriminant_map: &v.discriminant_map,
idstack: Vec::new(),
}
}
fn with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F)
where F: Fn(&mut Self) {
if self.idstack.iter().any(|&x| x == id) {
let any_static = self.idstack.iter().any(|&x| {
if let ast_map::NodeItem(item) = self.ast_map.get(x) {
if let ast::ItemStatic(..) = item.node {
true
} else {
false
}
} else {
false
}
});
if any_static {
if!self.sess.features.borrow().static_recursion {
emit_feature_err(&self.sess.parse_sess.span_diagnostic,
"static_recursion",
*self.root_span, "recursive static");
}
} else {
span_err!(self.sess, *self.root_span, E0265, "recursive constant");
}
return;
}
self.idstack.push(id);
f(self);
self.idstack.pop();
}
// If a variant has an expression specifying its discriminant, then it needs
// to be checked just like a static or constant. However, if there are more
// variants with no explicitly specified discriminant, those variants will
// increment the same expression to get their values.
//
// So for every variant, we need to track whether there is an expression
// somewhere in the enum definition that controls its discriminant. We do
// this by starting from the end and searching backward.
fn populate_enum_discriminants(&self, enum_definition: &'ast ast::EnumDef) {
// Get the map, and return if we already processed this enum or if it
// has no variants.
let mut discriminant_map = self.discriminant_map.borrow_mut();
match enum_definition.variants.first() {
None => { return; }
Some(variant) if discriminant_map.contains_key(&variant.node.id) => {
return;
}
_ => {}
}
// Go through all the variants.
let mut variant_stack: Vec<ast::NodeId> = Vec::new();
for variant in enum_definition.variants.iter().rev() {
variant_stack.push(variant.node.id);
// When we find an expression, every variant currently on the stack
// is affected by that expression.
if let Some(ref expr) = variant.node.disr_expr {
for id in &variant_stack {
discriminant_map.insert(*id, Some(expr));
}
variant_stack.clear()
}
}
// If we are at the top, that always starts at 0, so any variant on the
// stack has a default value and does not need to be checked.
for id in &variant_stack {
discriminant_map.insert(*id, None);
}
}
}
impl<'a, 'ast: 'a> Visitor<'ast> for CheckItemRecursionVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &'ast ast::Item) {
self.with_item_id_pushed(it.id, |v| visit::walk_item(v, it));
}
fn visit_enum_def(&mut self, enum_definition: &'ast ast::EnumDef,
generics: &'ast ast::Generics) {
self.populate_enum_discriminants(enum_definition);
visit::walk_enum_def(self, enum_definition, generics);
}
fn visit_variant(&mut self, variant: &'ast ast::Variant,
_: &'ast ast::Generics) {
let variant_id = variant.node.id;
let maybe_expr;
if let Some(get_expr) = self.discriminant_map.borrow().get(&variant_id) {
// This is necessary because we need to let the `discriminant_map`
// borrow fall out of scope, so that we can reborrow farther down.
maybe_expr = (*get_expr).clone();
} else {
self.sess.span_bug(variant.span,
"`check_static_recursion` attempted to visit \
variant with unknown discriminant")
}
// If `maybe_expr` is `None`, that's because no discriminant is
// specified that affects this variant. Thus, no risk of recursion.
if let Some(expr) = maybe_expr {
self.with_item_id_pushed(expr.id, |v| visit::walk_expr(v, expr));
}
}
fn visit_trait_item(&mut self, ti: &'ast ast::TraitItem) {
self.with_item_id_pushed(ti.id, |v| visit::walk_trait_item(v, ti));
}
fn visit_impl_item(&mut self, ii: &'ast ast::ImplItem) {
self.with_item_id_pushed(ii.id, |v| visit::walk_impl_item(v, ii));
}
fn visit_expr(&mut self, e: &'ast ast::Expr) {
match e.node {
ast::ExprPath(..) => {
match self.def_map.borrow().get(&e.id).map(|d| d.base_def) {
Some(DefStatic(def_id, _)) |
Some(DefAssociatedConst(def_id)) |
Some(DefConst(def_id))
if ast_util::is_local(def_id) => {
match self.ast_map.get(def_id.node) {
ast_map::NodeItem(item) =>
self.visit_item(item),
ast_map::NodeTraitItem(item) =>
self.visit_trait_item(item),
ast_map::NodeImplItem(item) =>
self.visit_impl_item(item),
ast_map::NodeForeignItem(_) => {},
_ => {
self.sess.span_bug(
e.span,
&format!("expected item, found {}",
self.ast_map.node_to_string(def_id.node)));
}
}
}
// For variants, we only want to check expressions that
// affect the specific variant used, but we need to check
// the whole enum definition to see what expression that
// might be (if any).
Some(DefVariant(enum_id, variant_id, false))
if ast_util::is_local(enum_id) => {
if let ast::ItemEnum(ref enum_def, ref generics) =
self.ast_map.expect_item(enum_id.local_id()).node {
self.populate_enum_discriminants(enum_def);
let variant = self.ast_map.expect_variant(variant_id.local_id());
self.visit_variant(variant, generics);
} else {
self.sess.span_bug(e.span,
"`check_static_recursion` found \
non-enum in DefVariant");
}
}
_ => ()
}
},
_ => ()
}
visit::walk_expr(self, e);
}
}
|
ast::ItemStatic(..) |
ast::ItemConst(..) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &it.span);
recursion_visitor.visit_item(it);
|
random_line_split
|
check_static_recursion.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.
// This compiler pass detects constants that refer to themselves
// recursively.
use ast_map;
use session::Session;
use middle::def::{DefStatic, DefConst, DefAssociatedConst, DefVariant, DefMap};
use util::nodemap::NodeMap;
use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::feature_gate::emit_feature_err;
use syntax::visit::Visitor;
use syntax::visit;
use std::cell::RefCell;
struct CheckCrateVisitor<'a, 'ast: 'a> {
sess: &'a Session,
def_map: &'a DefMap,
ast_map: &'a ast_map::Map<'ast>,
// `discriminant_map` is a cache that associates the `NodeId`s of local
// variant definitions with the discriminant expression that applies to
// each one. If the variant uses the default values (starting from `0`),
// then `None` is stored.
discriminant_map: RefCell<NodeMap<Option<&'ast ast::Expr>>>,
}
impl<'a, 'ast: 'a> Visitor<'ast> for CheckCrateVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &'ast ast::Item) {
match it.node {
ast::ItemStatic(..) |
ast::ItemConst(..) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &it.span);
recursion_visitor.visit_item(it);
},
ast::ItemEnum(ref enum_def, ref generics) => {
// We could process the whole enum, but handling the variants
// with discriminant expressions one by one gives more specific,
// less redundant output.
for variant in &enum_def.variants {
if let Some(_) = variant.node.disr_expr {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &variant.span);
recursion_visitor.populate_enum_discriminants(enum_def);
recursion_visitor.visit_variant(variant, generics);
}
}
}
_ => {}
}
visit::walk_item(self, it)
}
fn visit_trait_item(&mut self, ti: &'ast ast::TraitItem) {
match ti.node {
ast::ConstTraitItem(_, ref default) => {
if let Some(_) = *default {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ti.span);
recursion_visitor.visit_trait_item(ti);
}
}
_ => {}
}
visit::walk_trait_item(self, ti)
}
fn visit_impl_item(&mut self, ii: &'ast ast::ImplItem) {
match ii.node {
ast::ConstImplItem(..) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ii.span);
recursion_visitor.visit_impl_item(ii);
}
_ => {}
}
visit::walk_impl_item(self, ii)
}
}
pub fn check_crate<'ast>(sess: &Session,
krate: &'ast ast::Crate,
def_map: &DefMap,
ast_map: &ast_map::Map<'ast>) {
let mut visitor = CheckCrateVisitor {
sess: sess,
def_map: def_map,
ast_map: ast_map,
discriminant_map: RefCell::new(NodeMap()),
};
visit::walk_crate(&mut visitor, krate);
sess.abort_if_errors();
}
struct CheckItemRecursionVisitor<'a, 'ast: 'a> {
root_span: &'a Span,
sess: &'a Session,
ast_map: &'a ast_map::Map<'ast>,
def_map: &'a DefMap,
discriminant_map: &'a RefCell<NodeMap<Option<&'ast ast::Expr>>>,
idstack: Vec<ast::NodeId>,
}
impl<'a, 'ast: 'a> CheckItemRecursionVisitor<'a, 'ast> {
fn new(v: &'a CheckCrateVisitor<'a, 'ast>, span: &'a Span)
-> CheckItemRecursionVisitor<'a, 'ast> {
CheckItemRecursionVisitor {
root_span: span,
sess: v.sess,
ast_map: v.ast_map,
def_map: v.def_map,
discriminant_map: &v.discriminant_map,
idstack: Vec::new(),
}
}
fn with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F)
where F: Fn(&mut Self) {
if self.idstack.iter().any(|&x| x == id) {
let any_static = self.idstack.iter().any(|&x| {
if let ast_map::NodeItem(item) = self.ast_map.get(x) {
if let ast::ItemStatic(..) = item.node {
true
} else {
false
}
} else {
false
}
});
if any_static {
if!self.sess.features.borrow().static_recursion {
emit_feature_err(&self.sess.parse_sess.span_diagnostic,
"static_recursion",
*self.root_span, "recursive static");
}
} else {
span_err!(self.sess, *self.root_span, E0265, "recursive constant");
}
return;
}
self.idstack.push(id);
f(self);
self.idstack.pop();
}
// If a variant has an expression specifying its discriminant, then it needs
// to be checked just like a static or constant. However, if there are more
// variants with no explicitly specified discriminant, those variants will
// increment the same expression to get their values.
//
// So for every variant, we need to track whether there is an expression
// somewhere in the enum definition that controls its discriminant. We do
// this by starting from the end and searching backward.
fn populate_enum_discriminants(&self, enum_definition: &'ast ast::EnumDef) {
// Get the map, and return if we already processed this enum or if it
// has no variants.
let mut discriminant_map = self.discriminant_map.borrow_mut();
match enum_definition.variants.first() {
None => { return; }
Some(variant) if discriminant_map.contains_key(&variant.node.id) => {
return;
}
_ => {}
}
// Go through all the variants.
let mut variant_stack: Vec<ast::NodeId> = Vec::new();
for variant in enum_definition.variants.iter().rev() {
variant_stack.push(variant.node.id);
// When we find an expression, every variant currently on the stack
// is affected by that expression.
if let Some(ref expr) = variant.node.disr_expr {
for id in &variant_stack {
discriminant_map.insert(*id, Some(expr));
}
variant_stack.clear()
}
}
// If we are at the top, that always starts at 0, so any variant on the
// stack has a default value and does not need to be checked.
for id in &variant_stack {
discriminant_map.insert(*id, None);
}
}
}
impl<'a, 'ast: 'a> Visitor<'ast> for CheckItemRecursionVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &'ast ast::Item) {
self.with_item_id_pushed(it.id, |v| visit::walk_item(v, it));
}
fn visit_enum_def(&mut self, enum_definition: &'ast ast::EnumDef,
generics: &'ast ast::Generics) {
self.populate_enum_discriminants(enum_definition);
visit::walk_enum_def(self, enum_definition, generics);
}
fn visit_variant(&mut self, variant: &'ast ast::Variant,
_: &'ast ast::Generics) {
let variant_id = variant.node.id;
let maybe_expr;
if let Some(get_expr) = self.discriminant_map.borrow().get(&variant_id) {
// This is necessary because we need to let the `discriminant_map`
// borrow fall out of scope, so that we can reborrow farther down.
maybe_expr = (*get_expr).clone();
} else {
self.sess.span_bug(variant.span,
"`check_static_recursion` attempted to visit \
variant with unknown discriminant")
}
// If `maybe_expr` is `None`, that's because no discriminant is
// specified that affects this variant. Thus, no risk of recursion.
if let Some(expr) = maybe_expr {
self.with_item_id_pushed(expr.id, |v| visit::walk_expr(v, expr));
}
}
fn visit_trait_item(&mut self, ti: &'ast ast::TraitItem) {
self.with_item_id_pushed(ti.id, |v| visit::walk_trait_item(v, ti));
}
fn
|
(&mut self, ii: &'ast ast::ImplItem) {
self.with_item_id_pushed(ii.id, |v| visit::walk_impl_item(v, ii));
}
fn visit_expr(&mut self, e: &'ast ast::Expr) {
match e.node {
ast::ExprPath(..) => {
match self.def_map.borrow().get(&e.id).map(|d| d.base_def) {
Some(DefStatic(def_id, _)) |
Some(DefAssociatedConst(def_id)) |
Some(DefConst(def_id))
if ast_util::is_local(def_id) => {
match self.ast_map.get(def_id.node) {
ast_map::NodeItem(item) =>
self.visit_item(item),
ast_map::NodeTraitItem(item) =>
self.visit_trait_item(item),
ast_map::NodeImplItem(item) =>
self.visit_impl_item(item),
ast_map::NodeForeignItem(_) => {},
_ => {
self.sess.span_bug(
e.span,
&format!("expected item, found {}",
self.ast_map.node_to_string(def_id.node)));
}
}
}
// For variants, we only want to check expressions that
// affect the specific variant used, but we need to check
// the whole enum definition to see what expression that
// might be (if any).
Some(DefVariant(enum_id, variant_id, false))
if ast_util::is_local(enum_id) => {
if let ast::ItemEnum(ref enum_def, ref generics) =
self.ast_map.expect_item(enum_id.local_id()).node {
self.populate_enum_discriminants(enum_def);
let variant = self.ast_map.expect_variant(variant_id.local_id());
self.visit_variant(variant, generics);
} else {
self.sess.span_bug(e.span,
"`check_static_recursion` found \
non-enum in DefVariant");
}
}
_ => ()
}
},
_ => ()
}
visit::walk_expr(self, e);
}
}
|
visit_impl_item
|
identifier_name
|
check_static_recursion.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.
// This compiler pass detects constants that refer to themselves
// recursively.
use ast_map;
use session::Session;
use middle::def::{DefStatic, DefConst, DefAssociatedConst, DefVariant, DefMap};
use util::nodemap::NodeMap;
use syntax::{ast, ast_util};
use syntax::codemap::Span;
use syntax::feature_gate::emit_feature_err;
use syntax::visit::Visitor;
use syntax::visit;
use std::cell::RefCell;
struct CheckCrateVisitor<'a, 'ast: 'a> {
sess: &'a Session,
def_map: &'a DefMap,
ast_map: &'a ast_map::Map<'ast>,
// `discriminant_map` is a cache that associates the `NodeId`s of local
// variant definitions with the discriminant expression that applies to
// each one. If the variant uses the default values (starting from `0`),
// then `None` is stored.
discriminant_map: RefCell<NodeMap<Option<&'ast ast::Expr>>>,
}
impl<'a, 'ast: 'a> Visitor<'ast> for CheckCrateVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &'ast ast::Item) {
match it.node {
ast::ItemStatic(..) |
ast::ItemConst(..) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &it.span);
recursion_visitor.visit_item(it);
},
ast::ItemEnum(ref enum_def, ref generics) => {
// We could process the whole enum, but handling the variants
// with discriminant expressions one by one gives more specific,
// less redundant output.
for variant in &enum_def.variants {
if let Some(_) = variant.node.disr_expr {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &variant.span);
recursion_visitor.populate_enum_discriminants(enum_def);
recursion_visitor.visit_variant(variant, generics);
}
}
}
_ => {}
}
visit::walk_item(self, it)
}
fn visit_trait_item(&mut self, ti: &'ast ast::TraitItem) {
match ti.node {
ast::ConstTraitItem(_, ref default) => {
if let Some(_) = *default {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ti.span);
recursion_visitor.visit_trait_item(ti);
}
}
_ => {}
}
visit::walk_trait_item(self, ti)
}
fn visit_impl_item(&mut self, ii: &'ast ast::ImplItem) {
match ii.node {
ast::ConstImplItem(..) => {
let mut recursion_visitor =
CheckItemRecursionVisitor::new(self, &ii.span);
recursion_visitor.visit_impl_item(ii);
}
_ => {}
}
visit::walk_impl_item(self, ii)
}
}
pub fn check_crate<'ast>(sess: &Session,
krate: &'ast ast::Crate,
def_map: &DefMap,
ast_map: &ast_map::Map<'ast>) {
let mut visitor = CheckCrateVisitor {
sess: sess,
def_map: def_map,
ast_map: ast_map,
discriminant_map: RefCell::new(NodeMap()),
};
visit::walk_crate(&mut visitor, krate);
sess.abort_if_errors();
}
struct CheckItemRecursionVisitor<'a, 'ast: 'a> {
root_span: &'a Span,
sess: &'a Session,
ast_map: &'a ast_map::Map<'ast>,
def_map: &'a DefMap,
discriminant_map: &'a RefCell<NodeMap<Option<&'ast ast::Expr>>>,
idstack: Vec<ast::NodeId>,
}
impl<'a, 'ast: 'a> CheckItemRecursionVisitor<'a, 'ast> {
fn new(v: &'a CheckCrateVisitor<'a, 'ast>, span: &'a Span)
-> CheckItemRecursionVisitor<'a, 'ast> {
CheckItemRecursionVisitor {
root_span: span,
sess: v.sess,
ast_map: v.ast_map,
def_map: v.def_map,
discriminant_map: &v.discriminant_map,
idstack: Vec::new(),
}
}
fn with_item_id_pushed<F>(&mut self, id: ast::NodeId, f: F)
where F: Fn(&mut Self) {
if self.idstack.iter().any(|&x| x == id) {
let any_static = self.idstack.iter().any(|&x| {
if let ast_map::NodeItem(item) = self.ast_map.get(x) {
if let ast::ItemStatic(..) = item.node {
true
} else {
false
}
} else {
false
}
});
if any_static {
if!self.sess.features.borrow().static_recursion {
emit_feature_err(&self.sess.parse_sess.span_diagnostic,
"static_recursion",
*self.root_span, "recursive static");
}
} else {
span_err!(self.sess, *self.root_span, E0265, "recursive constant");
}
return;
}
self.idstack.push(id);
f(self);
self.idstack.pop();
}
// If a variant has an expression specifying its discriminant, then it needs
// to be checked just like a static or constant. However, if there are more
// variants with no explicitly specified discriminant, those variants will
// increment the same expression to get their values.
//
// So for every variant, we need to track whether there is an expression
// somewhere in the enum definition that controls its discriminant. We do
// this by starting from the end and searching backward.
fn populate_enum_discriminants(&self, enum_definition: &'ast ast::EnumDef) {
// Get the map, and return if we already processed this enum or if it
// has no variants.
let mut discriminant_map = self.discriminant_map.borrow_mut();
match enum_definition.variants.first() {
None => { return; }
Some(variant) if discriminant_map.contains_key(&variant.node.id) => {
return;
}
_ => {}
}
// Go through all the variants.
let mut variant_stack: Vec<ast::NodeId> = Vec::new();
for variant in enum_definition.variants.iter().rev() {
variant_stack.push(variant.node.id);
// When we find an expression, every variant currently on the stack
// is affected by that expression.
if let Some(ref expr) = variant.node.disr_expr {
for id in &variant_stack {
discriminant_map.insert(*id, Some(expr));
}
variant_stack.clear()
}
}
// If we are at the top, that always starts at 0, so any variant on the
// stack has a default value and does not need to be checked.
for id in &variant_stack {
discriminant_map.insert(*id, None);
}
}
}
impl<'a, 'ast: 'a> Visitor<'ast> for CheckItemRecursionVisitor<'a, 'ast> {
fn visit_item(&mut self, it: &'ast ast::Item) {
self.with_item_id_pushed(it.id, |v| visit::walk_item(v, it));
}
fn visit_enum_def(&mut self, enum_definition: &'ast ast::EnumDef,
generics: &'ast ast::Generics) {
self.populate_enum_discriminants(enum_definition);
visit::walk_enum_def(self, enum_definition, generics);
}
fn visit_variant(&mut self, variant: &'ast ast::Variant,
_: &'ast ast::Generics) {
let variant_id = variant.node.id;
let maybe_expr;
if let Some(get_expr) = self.discriminant_map.borrow().get(&variant_id) {
// This is necessary because we need to let the `discriminant_map`
// borrow fall out of scope, so that we can reborrow farther down.
maybe_expr = (*get_expr).clone();
} else {
self.sess.span_bug(variant.span,
"`check_static_recursion` attempted to visit \
variant with unknown discriminant")
}
// If `maybe_expr` is `None`, that's because no discriminant is
// specified that affects this variant. Thus, no risk of recursion.
if let Some(expr) = maybe_expr {
self.with_item_id_pushed(expr.id, |v| visit::walk_expr(v, expr));
}
}
fn visit_trait_item(&mut self, ti: &'ast ast::TraitItem)
|
fn visit_impl_item(&mut self, ii: &'ast ast::ImplItem) {
self.with_item_id_pushed(ii.id, |v| visit::walk_impl_item(v, ii));
}
fn visit_expr(&mut self, e: &'ast ast::Expr) {
match e.node {
ast::ExprPath(..) => {
match self.def_map.borrow().get(&e.id).map(|d| d.base_def) {
Some(DefStatic(def_id, _)) |
Some(DefAssociatedConst(def_id)) |
Some(DefConst(def_id))
if ast_util::is_local(def_id) => {
match self.ast_map.get(def_id.node) {
ast_map::NodeItem(item) =>
self.visit_item(item),
ast_map::NodeTraitItem(item) =>
self.visit_trait_item(item),
ast_map::NodeImplItem(item) =>
self.visit_impl_item(item),
ast_map::NodeForeignItem(_) => {},
_ => {
self.sess.span_bug(
e.span,
&format!("expected item, found {}",
self.ast_map.node_to_string(def_id.node)));
}
}
}
// For variants, we only want to check expressions that
// affect the specific variant used, but we need to check
// the whole enum definition to see what expression that
// might be (if any).
Some(DefVariant(enum_id, variant_id, false))
if ast_util::is_local(enum_id) => {
if let ast::ItemEnum(ref enum_def, ref generics) =
self.ast_map.expect_item(enum_id.local_id()).node {
self.populate_enum_discriminants(enum_def);
let variant = self.ast_map.expect_variant(variant_id.local_id());
self.visit_variant(variant, generics);
} else {
self.sess.span_bug(e.span,
"`check_static_recursion` found \
non-enum in DefVariant");
}
}
_ => ()
}
},
_ => ()
}
visit::walk_expr(self, e);
}
}
|
{
self.with_item_id_pushed(ti.id, |v| visit::walk_trait_item(v, ti));
}
|
identifier_body
|
borrowck-loan-rcvr.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.
struct point { x: int, y: int }
trait methods {
fn impurem(&self);
fn blockm(&self, f: ||);
}
impl methods for point {
fn impurem(&self) {
}
fn blockm(&self, f: ||) { f() }
}
fn a() {
let mut p = point {x: 3, y: 4};
// Here: it's ok to call even though receiver is mutable, because we
// can loan it out.
p.impurem();
// But in this case we do not honor the loan:
p.blockm(|| {
p.x = 10; //~ ERROR cannot assign
})
}
fn b()
|
fn c() {
// Loaning @mut as & is considered legal due to dynamic checks...
let q = @mut point {x: 3, y: 4};
q.impurem();
//...but we still detect errors statically when we can.
q.blockm(|| {
q.x = 10; //~ ERROR cannot assign
})
}
fn main() {
}
|
{
let mut p = point {x: 3, y: 4};
// Here I create an outstanding loan and check that we get conflicts:
let l = &mut p;
p.impurem(); //~ ERROR cannot borrow
l.x += 1;
}
|
identifier_body
|
borrowck-loan-rcvr.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.
struct
|
{ x: int, y: int }
trait methods {
fn impurem(&self);
fn blockm(&self, f: ||);
}
impl methods for point {
fn impurem(&self) {
}
fn blockm(&self, f: ||) { f() }
}
fn a() {
let mut p = point {x: 3, y: 4};
// Here: it's ok to call even though receiver is mutable, because we
// can loan it out.
p.impurem();
// But in this case we do not honor the loan:
p.blockm(|| {
p.x = 10; //~ ERROR cannot assign
})
}
fn b() {
let mut p = point {x: 3, y: 4};
// Here I create an outstanding loan and check that we get conflicts:
let l = &mut p;
p.impurem(); //~ ERROR cannot borrow
l.x += 1;
}
fn c() {
// Loaning @mut as & is considered legal due to dynamic checks...
let q = @mut point {x: 3, y: 4};
q.impurem();
//...but we still detect errors statically when we can.
q.blockm(|| {
q.x = 10; //~ ERROR cannot assign
})
}
fn main() {
}
|
point
|
identifier_name
|
borrowck-loan-rcvr.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.
struct point { x: int, y: int }
trait methods {
fn impurem(&self);
fn blockm(&self, f: ||);
}
impl methods for point {
fn impurem(&self) {
}
fn blockm(&self, f: ||) { f() }
}
fn a() {
let mut p = point {x: 3, y: 4};
// Here: it's ok to call even though receiver is mutable, because we
// can loan it out.
p.impurem();
// But in this case we do not honor the loan:
p.blockm(|| {
p.x = 10; //~ ERROR cannot assign
})
}
fn b() {
let mut p = point {x: 3, y: 4};
// Here I create an outstanding loan and check that we get conflicts:
let l = &mut p;
p.impurem(); //~ ERROR cannot borrow
l.x += 1;
}
fn c() {
// Loaning @mut as & is considered legal due to dynamic checks...
let q = @mut point {x: 3, y: 4};
q.impurem();
//...but we still detect errors statically when we can.
|
})
}
fn main() {
}
|
q.blockm(|| {
q.x = 10; //~ ERROR cannot assign
|
random_line_split
|
unreachable-in-call.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.
#![allow(dead_code)]
#![deny(unreachable_code)]
fn diverge() ->! { panic!() }
fn
|
() -> u8 {
1
}
fn call(_: u8, _: u8) {
}
fn diverge_first() {
call(diverge(),
get_u8()); //~ ERROR unreachable expression
}
fn diverge_second() {
call( //~ ERROR unreachable expression
get_u8(),
diverge());
}
fn main() {}
|
get_u8
|
identifier_name
|
unreachable-in-call.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
|
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(dead_code)]
#![deny(unreachable_code)]
fn diverge() ->! { panic!() }
fn get_u8() -> u8 {
1
}
fn call(_: u8, _: u8) {
}
fn diverge_first() {
call(diverge(),
get_u8()); //~ ERROR unreachable expression
}
fn diverge_second() {
call( //~ ERROR unreachable expression
get_u8(),
diverge());
}
fn main() {}
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
random_line_split
|
unreachable-in-call.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.
#![allow(dead_code)]
#![deny(unreachable_code)]
fn diverge() ->! { panic!() }
fn get_u8() -> u8 {
1
}
fn call(_: u8, _: u8)
|
fn diverge_first() {
call(diverge(),
get_u8()); //~ ERROR unreachable expression
}
fn diverge_second() {
call( //~ ERROR unreachable expression
get_u8(),
diverge());
}
fn main() {}
|
{
}
|
identifier_body
|
mod.rs
|
/* Copyright (C) 2017-2019 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// written by Pierre Chifflier <[email protected]>
extern crate snmp_parser;
pub mod snmp;
pub mod log;
pub mod detect;
|
* 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
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.