<commit_before>/*! Interactive grid projection demo */

extern crate calx;

use calx::{noise, color, V2, Rgba, Rect, Projection, Anchor};
use calx::backend::{CanvasBuilder, Canvas, CanvasUtil, Event, Key};

static PROJECTIONS: [(V2<f32>, V2<f32>); 3] = [
    (V2(16.0, 8.0), V2(-16.0, 8.0)),  // Isometric
    (V2(16.0, 0.0), V2(0.0, 16.0)),   // Topdown
    (V2(16.0, 0.0), V2(-6.0, 12.0)),  // Cavalier
];

fn draw_cell(ctx: &mut Canvas, proj: &Projection, cell: V2<i32>, dim: bool) {
    let n = cell.0 + 3329 * cell.1;
    // Procedural color.
    let mut color = Rgba::new(
        noise(n * 3) / 2.0 + 0.5,
        noise(n * 3 + 1) / 2.0 + 0.5,
        noise(n * 3 + 2) / 2.0 + 0.5,
        1.0);
    if dim {
        color = color.to_monochrome();
    }

    let tex = ctx.solid_tex_coord();
    let ind0 = ctx.num_vertices();

    // Project world-space cell base into screen space.
    let base = Rect(cell.map(|x| x as f32), V2(1.0, 1.0));
    for &p in [Anchor::TopLeft, Anchor::TopRight, Anchor::BottomRight, Anchor::BottomLeft].iter() {
        ctx.push_vertex(proj.project(base.point(p)), 0.5, tex, &color, &color::BLACK);
    }

    ctx.push_triangle(ind0, ind0 + 1, ind0 + 2);
    ctx.push_triangle(ind0, ind0 + 2, ind0 + 3);
}

fn main() {
    let mut projection = 0;
    let scroll_speed = 2f32;
    let mut mouse_pos = V2(-1i32, -1i32);
    let mut screen_offset = V2(0.0f32, 0.0f32);
    let mut scroll_delta = V2(0.0f32, 0.0f32);
    let mut ctx = CanvasBuilder::new().build();

    let screen_rect = Rect(V2(0.0f32, 0.0f32), V2(640.0f32, 360.0f32));

    loop {
        match ctx.next_event() {
            Event::Quit => { return; }
            Event::RenderFrame => {
                ctx.clear();

                screen_offset = screen_offset - scroll_delta;
                let proj = Projection::new(PROJECTIONS[projection].0, PROJECTIONS[projection].1,
                                           screen_offset).unwrap();

                let mouse_rect = Rect(mouse_pos.map(|x| x as f32) - V2(160.0, 90.0), V2(320.0, 180.0));
                let mouse_cell = proj.inv_project(mouse_pos.map(|x| x as f32)).map(|x| x as i32);

                for pt in proj.inv_project_rectangle(&screen_rect).iter() {
                    let cell = pt.map(|x| x as i32);
                    if cell != mouse_cell { draw_cell(&mut ctx, &proj, cell, true); }
                }

                for pt in proj.inv_project_rectangle(&mouse_rect).iter() {
                    let cell = pt.map(|x| x as i32);
                    if cell != mouse_cell { draw_cell(&mut ctx, &proj, cell, false); }
                }

                ctx.draw_rect(&mouse_rect, 0.5, &"cyan");
            }

            Event::KeyPressed(Key::Escape) => { return; }

            Event::KeyPressed(Key::Tab) => {
                projection += 1;
                projection %= PROJECTIONS.len();
            }

            Event::KeyPressed(k) => {
                match k {
                    Key::A => { scroll_delta.0 = -1.0 * scroll_speed; }
                    Key::D => { scroll_delta.0 =  1.0 * scroll_speed; }
                    Key::W => { scroll_delta.1 = -1.0 * scroll_speed; }
                    Key::S => { scroll_delta.1 =  1.0 * scroll_speed; }
                    _ => {}
                }
            }

            Event::KeyReleased(k) => {
                match k {
                    Key::A => { scroll_delta.0 = 0.0; }
                    Key::D => { scroll_delta.0 = 0.0; }
                    Key::W => { scroll_delta.1 = 0.0; }
                    Key::S => { scroll_delta.1 = 0.0; }
                    _ => {}
                }
            }
            Event::MouseMoved((x, y)) => {
                mouse_pos = V2(x, y);
            }
            _ => {}
        }
    }
}
<commit_msg>Grid demo screenshotting<commit_after>/*! Interactive grid projection demo */

extern crate calx;

use calx::{noise, color, V2, Rgba, Rect, Projection, Anchor};
use calx::backend::{CanvasBuilder, Canvas, CanvasUtil, Event, Key};

static PROJECTIONS: [(V2<f32>, V2<f32>); 3] = [
    (V2(16.0, 8.0), V2(-16.0, 8.0)),  // Isometric
    (V2(16.0, 0.0), V2(0.0, 16.0)),   // Topdown
    (V2(16.0, 0.0), V2(-6.0, 12.0)),  // Cavalier
];

fn draw_cell(ctx: &mut Canvas, proj: &Projection, cell: V2<i32>, dim: bool) {
    let n = cell.0 + 3329 * cell.1;
    // Procedural color.
    let mut color = Rgba::new(
        noise(n * 3) / 2.0 + 0.5,
        noise(n * 3 + 1) / 2.0 + 0.5,
        noise(n * 3 + 2) / 2.0 + 0.5,
        1.0);
    if dim {
        color = color.to_monochrome();
    }

    let tex = ctx.solid_tex_coord();
    let ind0 = ctx.num_vertices();

    // Project world-space cell base into screen space.
    let base = Rect(cell.map(|x| x as f32), V2(1.0, 1.0));
    for &p in [Anchor::TopLeft, Anchor::TopRight, Anchor::BottomRight, Anchor::BottomLeft].iter() {
        ctx.push_vertex(proj.project(base.point(p)), 0.5, tex, &color, &color::BLACK);
    }

    ctx.push_triangle(ind0, ind0 + 1, ind0 + 2);
    ctx.push_triangle(ind0, ind0 + 2, ind0 + 3);
}

fn main() {
    let mut projection = 0;
    let scroll_speed = 2f32;
    let mut mouse_pos = V2(-1i32, -1i32);
    let mut screen_offset = V2(0.0f32, 0.0f32);
    let mut scroll_delta = V2(0.0f32, 0.0f32);
    let mut ctx = CanvasBuilder::new().build();

    let screen_rect = Rect(V2(0.0f32, 0.0f32), V2(640.0f32, 360.0f32));

    loop {
        match ctx.next_event() {
            Event::Quit => { return; }
            Event::RenderFrame => {
                ctx.clear();

                screen_offset = screen_offset - scroll_delta;
                let proj = Projection::new(PROJECTIONS[projection].0, PROJECTIONS[projection].1,
                                           screen_offset).unwrap();

                let mouse_rect = Rect(mouse_pos.map(|x| x as f32) - V2(160.0, 90.0), V2(320.0, 180.0));
                let mouse_cell = proj.inv_project(mouse_pos.map(|x| x as f32)).map(|x| x as i32);

                for pt in proj.inv_project_rectangle(&screen_rect).iter() {
                    let cell = pt.map(|x| x as i32);
                    if cell != mouse_cell { draw_cell(&mut ctx, &proj, cell, true); }
                }

                for pt in proj.inv_project_rectangle(&mouse_rect).iter() {
                    let cell = pt.map(|x| x as i32);
                    if cell != mouse_cell { draw_cell(&mut ctx, &proj, cell, false); }
                }

                ctx.draw_rect(&mouse_rect, 0.5, &"cyan");
            }

            Event::KeyPressed(Key::Escape) => { return; }

            Event::KeyPressed(Key::Tab) => {
                projection += 1;
                projection %= PROJECTIONS.len();
            }

            Event::KeyPressed(Key::F12) => {
                ctx.save_screenshot(&"grid");
            }

            Event::KeyPressed(k) => {
                match k {
                    Key::A => { scroll_delta.0 = -1.0 * scroll_speed; }
                    Key::D => { scroll_delta.0 =  1.0 * scroll_speed; }
                    Key::W => { scroll_delta.1 = -1.0 * scroll_speed; }
                    Key::S => { scroll_delta.1 =  1.0 * scroll_speed; }
                    _ => {}
                }
            }

            Event::KeyReleased(k) => {
                match k {
                    Key::A => { scroll_delta.0 = 0.0; }
                    Key::D => { scroll_delta.0 = 0.0; }
                    Key::W => { scroll_delta.1 = 0.0; }
                    Key::S => { scroll_delta.1 = 0.0; }
                    _ => {}
                }
            }
            Event::MouseMoved((x, y)) => {
                mouse_pos = V2(x, y);
            }
            _ => {}
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2012-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.

//! Types which pin data to its location in memory
//!
//! It is sometimes useful to have objects that are guaranteed to not move,
//! in the sense that their placement in memory does not change, and can thus be relied upon.
//!
//! A prime example of such a scenario would be building self-referencial structs,
//! since moving an object with pointers to itself will invalidate them,
//! which could cause undefined behavior.
//!
//! In order to prevent objects from moving, they must be *pinned*,
//! by wrapping the data in special pointer types, such as [`PinMut`] and [`PinBox`].
//! On top of ensuring the data cannot be taked by value by being pointers,
//! these types restrict access to the underlying data such that it cannot be moved out of them,
//! unless the type implements the [`Unpin`] trait,
//! which indicates that it can be used safely without these restrictions.
//!
//! A type may be moved out of a reference to it using a function like [`swap`],
//! which replaces the contents of the references, and thus changes their place in memory.
//!
//! [`PinMut`]: struct.PinMut.html
//! [`PinBox`]: struct.PinBox.html
//! [`Unpin`]: ../../core/marker/trait.Unpin.html
//! [`swap`]: ../../core/mem/fn.swap.html
//!
//! # Examples
//!
//! ```rust
//! #![feature(pin)]
//!
//! use std::pin::PinBox;
//! use std::marker::Pinned;
//! use std::ptr::NonNull;
//!
//! // This is a self referencial struct since the slice field points to the data field.
//! // We cannot inform the compiler about that with a normal reference,
//! // since this pattern cannot be described with the usual borrowing rules.
//! // Instead we use a raw pointer, though one which is known to not be null,
//! // since we know it's pointing at the string.
//! struct Unmovable {
//!     data: String,
//!     slice: NonNull<String>,
//!     _pin: Pinned,
//! }
//!
//! impl Unmovable {
//!     // To ensure the data doesn't move when the function returns,
//!     // we place it in the heap where it will stay for the lifetime of the object,
//!     // and the only way to access it would be through a pointer to it.
//!     fn new(data: String) -> PinBox<Self> {
//!         let res = Unmovable {
//!             data,
//!             // we only create the pointer once the data is in place
//!             // otherwise it will have already moved before we even started
//!             slice: NonNull::dangling(),
//!             _pin: Pinned,
//!         };
//!         let mut boxed = PinBox::new(res);
//!
//!         let slice = NonNull::from(&boxed.data);
//!         // we know this is safe because modifying a field doesn't move the whole struct
//!         unsafe { PinBox::get_mut(&mut boxed).slice = slice };
//!         boxed
//!     }
//! }
//!
//! let unmoved = Unmovable::new("hello".to_string());
//! // The pointer should point to the correct location,
//! // so long as the struct hasn't moved.
//! // Meanwhile, we are free to move the pointer around.
//! let mut still_unmoved = unmoved;
//! assert_eq!(still_unmoved.slice, NonNull::from(&still_unmoved.data));
//!
//! // Since our type doesn't implement Unpin, this will fail to compile:
//! // let new_unmoved = Unmovable::new("world".to_string());
//! // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
//! ```

#![unstable(feature = "pin", issue = "49150")]

pub use core::pin::*;

use core::convert::From;
use core::fmt;
use core::future::{Future, FutureObj, LocalFutureObj, UnsafeFutureObj};
use core::marker::{Unpin, Unsize};
use core::ops::{CoerceUnsized, Deref, DerefMut};
use core::task::{Context, Poll};

use boxed::Box;

/// A pinned, heap allocated reference.
///
/// This type is similar to [`Box`], except that it pins its value,
/// which prevents it from moving out of the reference, unless it implements [`Unpin`].
///
/// See the [module documentation] for furthur explaination on pinning.
///
/// [`Box`]: ../boxed/struct.Box.html
/// [`Unpin`]: ../../core/marker/trait.Unpin.html
/// [module documentation]: index.html
#[unstable(feature = "pin", issue = "49150")]
#[fundamental]
#[repr(transparent)]
pub struct PinBox<T: ?Sized> {
    inner: Box<T>,
}

#[unstable(feature = "pin", issue = "49150")]
impl<T> PinBox<T> {
    /// Allocate memory on the heap, move the data into it and pin it.
    #[unstable(feature = "pin", issue = "49150")]
    pub fn new(data: T) -> PinBox<T> {
        PinBox { inner: Box::new(data) }
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized> PinBox<T> {
    /// Get a pinned reference to the data in this PinBox.
    #[inline]
    pub fn as_pin_mut<'a>(&'a mut self) -> PinMut<'a, T> {
        unsafe { PinMut::new_unchecked(&mut *self.inner) }
    }

    /// Constructs a `PinBox` from a raw pointer.
    ///
    /// After calling this function, the raw pointer is owned by the
    /// resulting `PinBox`. Specifically, the `PinBox` destructor will call
    /// the destructor of `T` and free the allocated memory. Since the
    /// way `PinBox` allocates and releases memory is unspecified, the
    /// only valid pointer to pass to this function is the one taken
    /// from another `PinBox` via the [`PinBox::into_raw`] function.
    ///
    /// This function is unsafe because improper use may lead to
    /// memory problems. For example, a double-free may occur if the
    /// function is called twice on the same raw pointer.
    ///
    /// [`PinBox::into_raw`]: struct.PinBox.html#method.into_raw
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(pin)]
    /// use std::pin::PinBox;
    /// let x = PinBox::new(5);
    /// let ptr = PinBox::into_raw(x);
    /// let x = unsafe { PinBox::from_raw(ptr) };
    /// ```
    #[inline]
    pub unsafe fn from_raw(raw: *mut T) -> Self {
        PinBox { inner: Box::from_raw(raw) }
    }

    /// Consumes the `PinBox`, returning the wrapped raw pointer.
    ///
    /// After calling this function, the caller is responsible for the
    /// memory previously managed by the `PinBox`. In particular, the
    /// caller should properly destroy `T` and release the memory. The
    /// proper way to do so is to convert the raw pointer back into a
    /// `PinBox` with the [`PinBox::from_raw`] function.
    ///
    /// Note: this is an associated function, which means that you have
    /// to call it as `PinBox::into_raw(b)` instead of `b.into_raw()`. This
    /// is so that there is no conflict with a method on the inner type.
    ///
    /// [`PinBox::from_raw`]: struct.PinBox.html#method.from_raw
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(pin)]
    /// use std::pin::PinBox;
    /// let x = PinBox::new(5);
    /// let ptr = PinBox::into_raw(x);
    /// ```
    #[inline]
    pub fn into_raw(b: PinBox<T>) -> *mut T {
        Box::into_raw(b.inner)
    }

    /// Get a mutable reference to the data inside this PinBox.
    ///
    /// This function is unsafe. Users must guarantee that the data is never
    /// moved out of this reference.
    #[inline]
    pub unsafe fn get_mut<'a>(this: &'a mut PinBox<T>) -> &'a mut T {
        &mut *this.inner
    }

    /// Convert this PinBox into an unpinned Box.
    ///
    /// This function is unsafe. Users must guarantee that the data is never
    /// moved out of the box.
    #[inline]
    pub unsafe fn unpin(this: PinBox<T>) -> Box<T> {
        this.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized> From<Box<T>> for PinBox<T> {
    fn from(boxed: Box<T>) -> PinBox<T> {
        PinBox { inner: boxed }
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized> Deref for PinBox<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &*self.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: Unpin + ?Sized> DerefMut for PinBox<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut *self.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: fmt::Display + ?Sized> fmt::Display for PinBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&*self.inner, f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: fmt::Debug + ?Sized> fmt::Debug for PinBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&*self.inner, f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized> fmt::Pointer for PinBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // It's not possible to extract the inner Uniq directly from the Box,
        // instead we cast it to a *const which aliases the Unique
        let ptr: *const T = &*self.inner;
        fmt::Pointer::fmt(&ptr, f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<PinBox<U>> for PinBox<T> {}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized> Unpin for PinBox<T> {}

#[unstable(feature = "futures_api", issue = "50547")]
impl<F: ?Sized + Future> Future for PinBox<F> {
    type Output = F::Output;

    fn poll(mut self: PinMut<Self>, cx: &mut Context) -> Poll<Self::Output> {
        self.as_pin_mut().poll(cx)
    }
}

#[unstable(feature = "futures_api", issue = "50547")]
unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for PinBox<F>
    where F: Future<Output = T> + 'a
{
    fn into_raw(self) -> *mut () {
        PinBox::into_raw(self) as *mut ()
    }

    unsafe fn poll(ptr: *mut (), cx: &mut Context) -> Poll<T> {
        let ptr = ptr as *mut F;
        let pin: PinMut<F> = PinMut::new_unchecked(&mut *ptr);
        pin.poll(cx)
    }

    unsafe fn drop(ptr: *mut ()) {
        drop(PinBox::from_raw(ptr as *mut F))
    }
}

#[unstable(feature = "futures_api", issue = "50547")]
impl<'a, F: Future<Output = ()> + Send + 'a> From<PinBox<F>> for FutureObj<'a, ()> {
    fn from(boxed: PinBox<F>) -> Self {
        FutureObj::new(boxed)
    }
}

#[unstable(feature = "futures_api", issue = "50547")]
impl<'a, F: Future<Output = ()> + 'a> From<PinBox<F>> for LocalFutureObj<'a, ()> {
    fn from(boxed: PinBox<F>) -> Self {
        LocalFutureObj::new(boxed)
    }
}
<commit_msg>allow unused mut for pinning explanation<commit_after>// Copyright 2012-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.

//! Types which pin data to its location in memory
//!
//! It is sometimes useful to have objects that are guaranteed to not move,
//! in the sense that their placement in memory does not change, and can thus be relied upon.
//!
//! A prime example of such a scenario would be building self-referencial structs,
//! since moving an object with pointers to itself will invalidate them,
//! which could cause undefined behavior.
//!
//! In order to prevent objects from moving, they must be *pinned*,
//! by wrapping the data in special pointer types, such as [`PinMut`] and [`PinBox`].
//! On top of ensuring the data cannot be taked by value by being pointers,
//! these types restrict access to the underlying data such that it cannot be moved out of them,
//! unless the type implements the [`Unpin`] trait,
//! which indicates that it can be used safely without these restrictions.
//!
//! A type may be moved out of a reference to it using a function like [`swap`],
//! which replaces the contents of the references, and thus changes their place in memory.
//!
//! [`PinMut`]: struct.PinMut.html
//! [`PinBox`]: struct.PinBox.html
//! [`Unpin`]: ../../core/marker/trait.Unpin.html
//! [`swap`]: ../../core/mem/fn.swap.html
//!
//! # Examples
//!
//! ```rust
//! #![feature(pin)]
//!
//! use std::pin::PinBox;
//! use std::marker::Pinned;
//! use std::ptr::NonNull;
//!
//! // This is a self referencial struct since the slice field points to the data field.
//! // We cannot inform the compiler about that with a normal reference,
//! // since this pattern cannot be described with the usual borrowing rules.
//! // Instead we use a raw pointer, though one which is known to not be null,
//! // since we know it's pointing at the string.
//! struct Unmovable {
//!     data: String,
//!     slice: NonNull<String>,
//!     _pin: Pinned,
//! }
//!
//! impl Unmovable {
//!     // To ensure the data doesn't move when the function returns,
//!     // we place it in the heap where it will stay for the lifetime of the object,
//!     // and the only way to access it would be through a pointer to it.
//!     fn new(data: String) -> PinBox<Self> {
//!         let res = Unmovable {
//!             data,
//!             // we only create the pointer once the data is in place
//!             // otherwise it will have already moved before we even started
//!             slice: NonNull::dangling(),
//!             _pin: Pinned,
//!         };
//!         let mut boxed = PinBox::new(res);
//!
//!         let slice = NonNull::from(&boxed.data);
//!         // we know this is safe because modifying a field doesn't move the whole struct
//!         unsafe { PinBox::get_mut(&mut boxed).slice = slice };
//!         boxed
//!     }
//! }
//!
//! let unmoved = Unmovable::new("hello".to_string());
//! // The pointer should point to the correct location,
//! // so long as the struct hasn't moved.
//! // Meanwhile, we are free to move the pointer around.
//! # #[allow(unused_mut)]
//! let mut still_unmoved = unmoved;
//! assert_eq!(still_unmoved.slice, NonNull::from(&still_unmoved.data));
//!
//! // Since our type doesn't implement Unpin, this will fail to compile:
//! // let new_unmoved = Unmovable::new("world".to_string());
//! // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
//! ```

#![unstable(feature = "pin", issue = "49150")]

pub use core::pin::*;

use core::convert::From;
use core::fmt;
use core::future::{Future, FutureObj, LocalFutureObj, UnsafeFutureObj};
use core::marker::{Unpin, Unsize};
use core::ops::{CoerceUnsized, Deref, DerefMut};
use core::task::{Context, Poll};

use boxed::Box;

/// A pinned, heap allocated reference.
///
/// This type is similar to [`Box`], except that it pins its value,
/// which prevents it from moving out of the reference, unless it implements [`Unpin`].
///
/// See the [module documentation] for furthur explaination on pinning.
///
/// [`Box`]: ../boxed/struct.Box.html
/// [`Unpin`]: ../../core/marker/trait.Unpin.html
/// [module documentation]: index.html
#[unstable(feature = "pin", issue = "49150")]
#[fundamental]
#[repr(transparent)]
pub struct PinBox<T: ?Sized> {
    inner: Box<T>,
}

#[unstable(feature = "pin", issue = "49150")]
impl<T> PinBox<T> {
    /// Allocate memory on the heap, move the data into it and pin it.
    #[unstable(feature = "pin", issue = "49150")]
    pub fn new(data: T) -> PinBox<T> {
        PinBox { inner: Box::new(data) }
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized> PinBox<T> {
    /// Get a pinned reference to the data in this PinBox.
    #[inline]
    pub fn as_pin_mut<'a>(&'a mut self) -> PinMut<'a, T> {
        unsafe { PinMut::new_unchecked(&mut *self.inner) }
    }

    /// Constructs a `PinBox` from a raw pointer.
    ///
    /// After calling this function, the raw pointer is owned by the
    /// resulting `PinBox`. Specifically, the `PinBox` destructor will call
    /// the destructor of `T` and free the allocated memory. Since the
    /// way `PinBox` allocates and releases memory is unspecified, the
    /// only valid pointer to pass to this function is the one taken
    /// from another `PinBox` via the [`PinBox::into_raw`] function.
    ///
    /// This function is unsafe because improper use may lead to
    /// memory problems. For example, a double-free may occur if the
    /// function is called twice on the same raw pointer.
    ///
    /// [`PinBox::into_raw`]: struct.PinBox.html#method.into_raw
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(pin)]
    /// use std::pin::PinBox;
    /// let x = PinBox::new(5);
    /// let ptr = PinBox::into_raw(x);
    /// let x = unsafe { PinBox::from_raw(ptr) };
    /// ```
    #[inline]
    pub unsafe fn from_raw(raw: *mut T) -> Self {
        PinBox { inner: Box::from_raw(raw) }
    }

    /// Consumes the `PinBox`, returning the wrapped raw pointer.
    ///
    /// After calling this function, the caller is responsible for the
    /// memory previously managed by the `PinBox`. In particular, the
    /// caller should properly destroy `T` and release the memory. The
    /// proper way to do so is to convert the raw pointer back into a
    /// `PinBox` with the [`PinBox::from_raw`] function.
    ///
    /// Note: this is an associated function, which means that you have
    /// to call it as `PinBox::into_raw(b)` instead of `b.into_raw()`. This
    /// is so that there is no conflict with a method on the inner type.
    ///
    /// [`PinBox::from_raw`]: struct.PinBox.html#method.from_raw
    ///
    /// # Examples
    ///
    /// ```
    /// #![feature(pin)]
    /// use std::pin::PinBox;
    /// let x = PinBox::new(5);
    /// let ptr = PinBox::into_raw(x);
    /// ```
    #[inline]
    pub fn into_raw(b: PinBox<T>) -> *mut T {
        Box::into_raw(b.inner)
    }

    /// Get a mutable reference to the data inside this PinBox.
    ///
    /// This function is unsafe. Users must guarantee that the data is never
    /// moved out of this reference.
    #[inline]
    pub unsafe fn get_mut<'a>(this: &'a mut PinBox<T>) -> &'a mut T {
        &mut *this.inner
    }

    /// Convert this PinBox into an unpinned Box.
    ///
    /// This function is unsafe. Users must guarantee that the data is never
    /// moved out of the box.
    #[inline]
    pub unsafe fn unpin(this: PinBox<T>) -> Box<T> {
        this.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized> From<Box<T>> for PinBox<T> {
    fn from(boxed: Box<T>) -> PinBox<T> {
        PinBox { inner: boxed }
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized> Deref for PinBox<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &*self.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: Unpin + ?Sized> DerefMut for PinBox<T> {
    fn deref_mut(&mut self) -> &mut T {
        &mut *self.inner
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: fmt::Display + ?Sized> fmt::Display for PinBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&*self.inner, f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: fmt::Debug + ?Sized> fmt::Debug for PinBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Debug::fmt(&*self.inner, f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized> fmt::Pointer for PinBox<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        // It's not possible to extract the inner Uniq directly from the Box,
        // instead we cast it to a *const which aliases the Unique
        let ptr: *const T = &*self.inner;
        fmt::Pointer::fmt(&ptr, f)
    }
}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<PinBox<U>> for PinBox<T> {}

#[unstable(feature = "pin", issue = "49150")]
impl<T: ?Sized> Unpin for PinBox<T> {}

#[unstable(feature = "futures_api", issue = "50547")]
impl<F: ?Sized + Future> Future for PinBox<F> {
    type Output = F::Output;

    fn poll(mut self: PinMut<Self>, cx: &mut Context) -> Poll<Self::Output> {
        self.as_pin_mut().poll(cx)
    }
}

#[unstable(feature = "futures_api", issue = "50547")]
unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for PinBox<F>
    where F: Future<Output = T> + 'a
{
    fn into_raw(self) -> *mut () {
        PinBox::into_raw(self) as *mut ()
    }

    unsafe fn poll(ptr: *mut (), cx: &mut Context) -> Poll<T> {
        let ptr = ptr as *mut F;
        let pin: PinMut<F> = PinMut::new_unchecked(&mut *ptr);
        pin.poll(cx)
    }

    unsafe fn drop(ptr: *mut ()) {
        drop(PinBox::from_raw(ptr as *mut F))
    }
}

#[unstable(feature = "futures_api", issue = "50547")]
impl<'a, F: Future<Output = ()> + Send + 'a> From<PinBox<F>> for FutureObj<'a, ()> {
    fn from(boxed: PinBox<F>) -> Self {
        FutureObj::new(boxed)
    }
}

#[unstable(feature = "futures_api", issue = "50547")]
impl<'a, F: Future<Output = ()> + 'a> From<PinBox<F>> for LocalFutureObj<'a, ()> {
    fn from(boxed: PinBox<F>) -> Self {
        LocalFutureObj::new(boxed)
    }
}
<|endoftext|>


<commit_before>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Character manipulation.
//!
//! For more details, see ::unicode::char (a.k.a. std::char)

#![allow(non_snake_case)]
#![doc(primitive = "char")]

use iter::Iterator;
use mem::transmute;
use option::Option::{None, Some};
use option::Option;
use slice::SliceExt;

// UTF-8 ranges and tags for encoding characters
static TAG_CONT: u8    = 0b1000_0000u8;
static TAG_TWO_B: u8   = 0b1100_0000u8;
static TAG_THREE_B: u8 = 0b1110_0000u8;
static TAG_FOUR_B: u8  = 0b1111_0000u8;
static MAX_ONE_B: u32   =     0x80u32;
static MAX_TWO_B: u32   =    0x800u32;
static MAX_THREE_B: u32 =  0x10000u32;

/*
    Lu  Uppercase_Letter        an uppercase letter
    Ll  Lowercase_Letter        a lowercase letter
    Lt  Titlecase_Letter        a digraphic character, with first part uppercase
    Lm  Modifier_Letter         a modifier letter
    Lo  Other_Letter            other letters, including syllables and ideographs
    Mn  Nonspacing_Mark         a nonspacing combining mark (zero advance width)
    Mc  Spacing_Mark            a spacing combining mark (positive advance width)
    Me  Enclosing_Mark          an enclosing combining mark
    Nd  Decimal_Number          a decimal digit
    Nl  Letter_Number           a letterlike numeric character
    No  Other_Number            a numeric character of other type
    Pc  Connector_Punctuation   a connecting punctuation mark, like a tie
    Pd  Dash_Punctuation        a dash or hyphen punctuation mark
    Ps  Open_Punctuation        an opening punctuation mark (of a pair)
    Pe  Close_Punctuation       a closing punctuation mark (of a pair)
    Pi  Initial_Punctuation     an initial quotation mark
    Pf  Final_Punctuation       a final quotation mark
    Po  Other_Punctuation       a punctuation mark of other type
    Sm  Math_Symbol             a symbol of primarily mathematical use
    Sc  Currency_Symbol         a currency sign
    Sk  Modifier_Symbol         a non-letterlike modifier symbol
    So  Other_Symbol            a symbol of other type
    Zs  Space_Separator         a space character (of various non-zero widths)
    Zl  Line_Separator          U+2028 LINE SEPARATOR only
    Zp  Paragraph_Separator     U+2029 PARAGRAPH SEPARATOR only
    Cc  Control                 a C0 or C1 control code
    Cf  Format                  a format control character
    Cs  Surrogate               a surrogate code point
    Co  Private_Use             a private-use character
    Cn  Unassigned              a reserved unassigned code point or a noncharacter
*/

/// The highest valid code point
#[stable]
pub const MAX: char = '\u{10ffff}';

/// Converts from `u32` to a `char`
#[inline]
#[unstable = "pending decisions about costructors for primitives"]
pub fn from_u32(i: u32) -> Option<char> {
    // catch out-of-bounds and surrogates
    if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
        None
    } else {
        Some(unsafe { transmute(i) })
    }
}

///
/// Converts a number to the character representing it
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Panics
///
/// Panics if given an `radix` > 36.
///
#[inline]
#[unstable = "pending decisions about costructors for primitives"]
pub fn from_digit(num: uint, radix: uint) -> Option<char> {
    if radix > 36 {
        panic!("from_digit: radix is too high (maximum 36)");
    }
    if num < radix {
        unsafe {
            if num < 10 {
                Some(transmute(('0' as uint + num) as u32))
            } else {
                Some(transmute(('a' as uint + num - 10u) as u32))
            }
        }
    } else {
        None
    }
}

/// Basic `char` manipulations.
#[experimental = "trait organization may change"]
pub trait Char {
    /// Checks if a `char` parses as a numeric digit in the given radix.
    ///
    /// Compared to `is_numeric()`, this function only recognizes the characters
    /// `0-9`, `a-z` and `A-Z`.
    ///
    /// # Return value
    ///
    /// Returns `true` if `c` is a valid digit under `radix`, and `false`
    /// otherwise.
    ///
    /// # Panics
    ///
    /// Panics if given a radix > 36.
    #[unstable = "pending error conventions"]
    fn is_digit(self, radix: uint) -> bool;

    /// Converts a character to the corresponding digit.
    ///
    /// # Return value
    ///
    /// If `c` is between '0' and '9', the corresponding value between 0 and
    /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
    /// none if the character does not refer to a digit in the given radix.
    ///
    /// # Panics
    ///
    /// Panics if given a radix outside the range [0..36].
    #[unstable = "pending error conventions, trait organization"]
    fn to_digit(self, radix: uint) -> Option<uint>;

    /// Returns an iterator that yields the hexadecimal Unicode escape
    /// of a character, as `char`s.
    ///
    /// All characters are escaped with Rust syntax of the form `\\u{NNNN}`
    /// where `NNNN` is the shortest hexadecimal representation of the code
    /// point.
    #[unstable = "pending error conventions, trait organization"]
    fn escape_unicode(self) -> EscapeUnicode;

    /// Returns an iterator that yields the 'default' ASCII and
    /// C++11-like literal escape of a character, as `char`s.
    ///
    /// The default is chosen with a bias toward producing literals that are
    /// legal in a variety of languages, including C++11 and similar C-family
    /// languages. The exact rules are:
    ///
    /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
    /// * Single-quote, double-quote and backslash chars are backslash-
    ///   escaped.
    /// * Any other chars in the range [0x20,0x7e] are not escaped.
    /// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
    #[unstable = "pending error conventions, trait organization"]
    fn escape_default(self) -> EscapeDefault;

    /// Returns the amount of bytes this character would need if encoded in
    /// UTF-8.
    #[unstable = "pending trait organization"]
    fn len_utf8(self) -> uint;

    /// Returns the amount of bytes this character would need if encoded in
    /// UTF-16.
    #[unstable = "pending trait organization"]
    fn len_utf16(self) -> uint;

    /// Encodes this character as UTF-8 into the provided byte buffer,
    /// and then returns the number of bytes written.
    ///
    /// If the buffer is not large enough, nothing will be written into it
    /// and a `None` will be returned.
    #[unstable = "pending trait organization"]
    fn encode_utf8(&self, dst: &mut [u8]) -> Option<uint>;

    /// Encodes this character as UTF-16 into the provided `u16` buffer,
    /// and then returns the number of `u16`s written.
    ///
    /// If the buffer is not large enough, nothing will be written into it
    /// and a `None` will be returned.
    #[unstable = "pending trait organization"]
    fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint>;
}

#[experimental = "trait is experimental"]
impl Char for char {
    #[unstable = "pending trait organization"]
    fn is_digit(self, radix: uint) -> bool {
        match self.to_digit(radix) {
            Some(_) => true,
            None    => false,
        }
    }

    #[unstable = "pending trait organization"]
    fn to_digit(self, radix: uint) -> Option<uint> {
        if radix > 36 {
            panic!("to_digit: radix is too high (maximum 36)");
        }
        let val = match self {
          '0' ... '9' => self as uint - ('0' as uint),
          'a' ... 'z' => self as uint + 10u - ('a' as uint),
          'A' ... 'Z' => self as uint + 10u - ('A' as uint),
          _ => return None,
        };
        if val < radix { Some(val) }
        else { None }
    }

    #[unstable = "pending error conventions, trait organization"]
    fn escape_unicode(self) -> EscapeUnicode {
        EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash }
    }

    #[unstable = "pending error conventions, trait organization"]
    fn escape_default(self) -> EscapeDefault {
        let init_state = match self {
            '\t' => EscapeDefaultState::Backslash('t'),
            '\r' => EscapeDefaultState::Backslash('r'),
            '\n' => EscapeDefaultState::Backslash('n'),
            '\\' => EscapeDefaultState::Backslash('\\'),
            '\'' => EscapeDefaultState::Backslash('\''),
            '"'  => EscapeDefaultState::Backslash('"'),
            '\x20' ... '\x7e' => EscapeDefaultState::Char(self),
            _ => EscapeDefaultState::Unicode(self.escape_unicode())
        };
        EscapeDefault { state: init_state }
    }

    #[inline]
    #[unstable = "pending trait organization"]
    fn len_utf8(self) -> uint {
        let code = self as u32;
        match () {
            _ if code < MAX_ONE_B   => 1u,
            _ if code < MAX_TWO_B   => 2u,
            _ if code < MAX_THREE_B => 3u,
            _  => 4u,
        }
    }

    #[inline]
    #[unstable = "pending trait organization"]
    fn len_utf16(self) -> uint {
        let ch = self as u32;
        if (ch & 0xFFFF_u32) == ch { 1 } else { 2 }
    }

    #[inline]
    #[unstable = "pending error conventions, trait organization"]
    fn encode_utf8<'a>(&self, dst: &'a mut [u8]) -> Option<uint> {
        // Marked #[inline] to allow llvm optimizing it away
        let code = *self as u32;
        if code < MAX_ONE_B && dst.len() >= 1 {
            dst[0] = code as u8;
            Some(1)
        } else if code < MAX_TWO_B && dst.len() >= 2 {
            dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
            dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
            Some(2)
        } else if code < MAX_THREE_B && dst.len() >= 3  {
            dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
            dst[1] = (code >>  6u & 0x3F_u32) as u8 | TAG_CONT;
            dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
            Some(3)
        } else if dst.len() >= 4 {
            dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
            dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
            dst[2] = (code >>  6u & 0x3F_u32) as u8 | TAG_CONT;
            dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
            Some(4)
        } else {
            None
        }
    }

    #[inline]
    #[unstable = "pending error conventions, trait organization"]
    fn encode_utf16(&self, dst: &mut [u16]) -> Option<uint> {
        // Marked #[inline] to allow llvm optimizing it away
        let mut ch = *self as u32;
        if (ch & 0xFFFF_u32) == ch  && dst.len() >= 1 {
            // The BMP falls through (assuming non-surrogate, as it should)
            dst[0] = ch as u16;
            Some(1)
        } else if dst.len() >= 2 {
            // Supplementary planes break into surrogates.
            ch -= 0x1_0000_u32;
            dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
            dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
            Some(2)
        } else {
            None
        }
    }
}

/// An iterator over the characters that represent a `char`, as escaped by
/// Rust's unicode escaping rules.
#[derive(Clone)]
pub struct EscapeUnicode {
    c: char,
    state: EscapeUnicodeState
}

#[derive(Clone)]
enum EscapeUnicodeState {
    Backslash,
    Type,
    LeftBrace,
    Value(uint),
    RightBrace,
    Done,
}

impl Iterator for EscapeUnicode {
    type Item = char;

    fn next(&mut self) -> Option<char> {
        match self.state {
            EscapeUnicodeState::Backslash => {
                self.state = EscapeUnicodeState::Type;
                Some('\\')
            }
            EscapeUnicodeState::Type => {
                self.state = EscapeUnicodeState::LeftBrace;
                Some('u')
            }
            EscapeUnicodeState::LeftBrace => {
                let mut n = 0u;
                while (self.c as u32) >> (4 * (n + 1)) != 0 {
                    n += 1;
                }
                self.state = EscapeUnicodeState::Value(n);
                Some('{')
            }
            EscapeUnicodeState::Value(offset) => {
                let v = match ((self.c as i32) >> (offset * 4)) & 0xf {
                    i @ 0 ... 9 => '0' as i32 + i,
                    i => 'a' as i32 + (i - 10)
                };
                if offset == 0 {
                    self.state = EscapeUnicodeState::RightBrace;
                } else {
                    self.state = EscapeUnicodeState::Value(offset - 1);
                }
                Some(unsafe { transmute(v) })
            }
            EscapeUnicodeState::RightBrace => {
                self.state = EscapeUnicodeState::Done;
                Some('}')
            }
            EscapeUnicodeState::Done => None,
        }
    }
}

/// An iterator over the characters that represent a `char`, escaped
/// for maximum portability.
#[derive(Clone)]
pub struct EscapeDefault {
    state: EscapeDefaultState
}

#[derive(Clone)]
enum EscapeDefaultState {
    Backslash(char),
    Char(char),
    Done,
    Unicode(EscapeUnicode),
}

impl Iterator for EscapeDefault {
    type Item = char;

    fn next(&mut self) -> Option<char> {
        match self.state {
            EscapeDefaultState::Backslash(c) => {
                self.state = EscapeDefaultState::Char(c);
                Some('\\')
            }
            EscapeDefaultState::Char(c) => {
                self.state = EscapeDefaultState::Done;
                Some(c)
            }
            EscapeDefaultState::Done => None,
            EscapeDefaultState::Unicode(ref mut iter) => iter.next()
        }
    }
}
<commit_msg>Switch encode_utf* to by-value self.<commit_after>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Character manipulation.
//!
//! For more details, see ::unicode::char (a.k.a. std::char)

#![allow(non_snake_case)]
#![doc(primitive = "char")]

use iter::Iterator;
use mem::transmute;
use option::Option::{None, Some};
use option::Option;
use slice::SliceExt;

// UTF-8 ranges and tags for encoding characters
static TAG_CONT: u8    = 0b1000_0000u8;
static TAG_TWO_B: u8   = 0b1100_0000u8;
static TAG_THREE_B: u8 = 0b1110_0000u8;
static TAG_FOUR_B: u8  = 0b1111_0000u8;
static MAX_ONE_B: u32   =     0x80u32;
static MAX_TWO_B: u32   =    0x800u32;
static MAX_THREE_B: u32 =  0x10000u32;

/*
    Lu  Uppercase_Letter        an uppercase letter
    Ll  Lowercase_Letter        a lowercase letter
    Lt  Titlecase_Letter        a digraphic character, with first part uppercase
    Lm  Modifier_Letter         a modifier letter
    Lo  Other_Letter            other letters, including syllables and ideographs
    Mn  Nonspacing_Mark         a nonspacing combining mark (zero advance width)
    Mc  Spacing_Mark            a spacing combining mark (positive advance width)
    Me  Enclosing_Mark          an enclosing combining mark
    Nd  Decimal_Number          a decimal digit
    Nl  Letter_Number           a letterlike numeric character
    No  Other_Number            a numeric character of other type
    Pc  Connector_Punctuation   a connecting punctuation mark, like a tie
    Pd  Dash_Punctuation        a dash or hyphen punctuation mark
    Ps  Open_Punctuation        an opening punctuation mark (of a pair)
    Pe  Close_Punctuation       a closing punctuation mark (of a pair)
    Pi  Initial_Punctuation     an initial quotation mark
    Pf  Final_Punctuation       a final quotation mark
    Po  Other_Punctuation       a punctuation mark of other type
    Sm  Math_Symbol             a symbol of primarily mathematical use
    Sc  Currency_Symbol         a currency sign
    Sk  Modifier_Symbol         a non-letterlike modifier symbol
    So  Other_Symbol            a symbol of other type
    Zs  Space_Separator         a space character (of various non-zero widths)
    Zl  Line_Separator          U+2028 LINE SEPARATOR only
    Zp  Paragraph_Separator     U+2029 PARAGRAPH SEPARATOR only
    Cc  Control                 a C0 or C1 control code
    Cf  Format                  a format control character
    Cs  Surrogate               a surrogate code point
    Co  Private_Use             a private-use character
    Cn  Unassigned              a reserved unassigned code point or a noncharacter
*/

/// The highest valid code point
#[stable]
pub const MAX: char = '\u{10ffff}';

/// Converts from `u32` to a `char`
#[inline]
#[unstable = "pending decisions about costructors for primitives"]
pub fn from_u32(i: u32) -> Option<char> {
    // catch out-of-bounds and surrogates
    if (i > MAX as u32) || (i >= 0xD800 && i <= 0xDFFF) {
        None
    } else {
        Some(unsafe { transmute(i) })
    }
}

///
/// Converts a number to the character representing it
///
/// # Return value
///
/// Returns `Some(char)` if `num` represents one digit under `radix`,
/// using one character of `0-9` or `a-z`, or `None` if it doesn't.
///
/// # Panics
///
/// Panics if given an `radix` > 36.
///
#[inline]
#[unstable = "pending decisions about costructors for primitives"]
pub fn from_digit(num: uint, radix: uint) -> Option<char> {
    if radix > 36 {
        panic!("from_digit: radix is too high (maximum 36)");
    }
    if num < radix {
        unsafe {
            if num < 10 {
                Some(transmute(('0' as uint + num) as u32))
            } else {
                Some(transmute(('a' as uint + num - 10u) as u32))
            }
        }
    } else {
        None
    }
}

/// Basic `char` manipulations.
#[experimental = "trait organization may change"]
pub trait Char {
    /// Checks if a `char` parses as a numeric digit in the given radix.
    ///
    /// Compared to `is_numeric()`, this function only recognizes the characters
    /// `0-9`, `a-z` and `A-Z`.
    ///
    /// # Return value
    ///
    /// Returns `true` if `c` is a valid digit under `radix`, and `false`
    /// otherwise.
    ///
    /// # Panics
    ///
    /// Panics if given a radix > 36.
    #[unstable = "pending error conventions"]
    fn is_digit(self, radix: uint) -> bool;

    /// Converts a character to the corresponding digit.
    ///
    /// # Return value
    ///
    /// If `c` is between '0' and '9', the corresponding value between 0 and
    /// 9. If `c` is 'a' or 'A', 10. If `c` is 'b' or 'B', 11, etc. Returns
    /// none if the character does not refer to a digit in the given radix.
    ///
    /// # Panics
    ///
    /// Panics if given a radix outside the range [0..36].
    #[unstable = "pending error conventions, trait organization"]
    fn to_digit(self, radix: uint) -> Option<uint>;

    /// Returns an iterator that yields the hexadecimal Unicode escape
    /// of a character, as `char`s.
    ///
    /// All characters are escaped with Rust syntax of the form `\\u{NNNN}`
    /// where `NNNN` is the shortest hexadecimal representation of the code
    /// point.
    #[unstable = "pending error conventions, trait organization"]
    fn escape_unicode(self) -> EscapeUnicode;

    /// Returns an iterator that yields the 'default' ASCII and
    /// C++11-like literal escape of a character, as `char`s.
    ///
    /// The default is chosen with a bias toward producing literals that are
    /// legal in a variety of languages, including C++11 and similar C-family
    /// languages. The exact rules are:
    ///
    /// * Tab, CR and LF are escaped as '\t', '\r' and '\n' respectively.
    /// * Single-quote, double-quote and backslash chars are backslash-
    ///   escaped.
    /// * Any other chars in the range [0x20,0x7e] are not escaped.
    /// * Any other chars are given hex Unicode escapes; see `escape_unicode`.
    #[unstable = "pending error conventions, trait organization"]
    fn escape_default(self) -> EscapeDefault;

    /// Returns the amount of bytes this character would need if encoded in
    /// UTF-8.
    #[unstable = "pending trait organization"]
    fn len_utf8(self) -> uint;

    /// Returns the amount of bytes this character would need if encoded in
    /// UTF-16.
    #[unstable = "pending trait organization"]
    fn len_utf16(self) -> uint;

    /// Encodes this character as UTF-8 into the provided byte buffer,
    /// and then returns the number of bytes written.
    ///
    /// If the buffer is not large enough, nothing will be written into it
    /// and a `None` will be returned.
    #[unstable = "pending trait organization"]
    fn encode_utf8(self, dst: &mut [u8]) -> Option<uint>;

    /// Encodes this character as UTF-16 into the provided `u16` buffer,
    /// and then returns the number of `u16`s written.
    ///
    /// If the buffer is not large enough, nothing will be written into it
    /// and a `None` will be returned.
    #[unstable = "pending trait organization"]
    fn encode_utf16(self, dst: &mut [u16]) -> Option<uint>;
}

#[experimental = "trait is experimental"]
impl Char for char {
    #[unstable = "pending trait organization"]
    fn is_digit(self, radix: uint) -> bool {
        match self.to_digit(radix) {
            Some(_) => true,
            None    => false,
        }
    }

    #[unstable = "pending trait organization"]
    fn to_digit(self, radix: uint) -> Option<uint> {
        if radix > 36 {
            panic!("to_digit: radix is too high (maximum 36)");
        }
        let val = match self {
          '0' ... '9' => self as uint - ('0' as uint),
          'a' ... 'z' => self as uint + 10u - ('a' as uint),
          'A' ... 'Z' => self as uint + 10u - ('A' as uint),
          _ => return None,
        };
        if val < radix { Some(val) }
        else { None }
    }

    #[unstable = "pending error conventions, trait organization"]
    fn escape_unicode(self) -> EscapeUnicode {
        EscapeUnicode { c: self, state: EscapeUnicodeState::Backslash }
    }

    #[unstable = "pending error conventions, trait organization"]
    fn escape_default(self) -> EscapeDefault {
        let init_state = match self {
            '\t' => EscapeDefaultState::Backslash('t'),
            '\r' => EscapeDefaultState::Backslash('r'),
            '\n' => EscapeDefaultState::Backslash('n'),
            '\\' => EscapeDefaultState::Backslash('\\'),
            '\'' => EscapeDefaultState::Backslash('\''),
            '"'  => EscapeDefaultState::Backslash('"'),
            '\x20' ... '\x7e' => EscapeDefaultState::Char(self),
            _ => EscapeDefaultState::Unicode(self.escape_unicode())
        };
        EscapeDefault { state: init_state }
    }

    #[inline]
    #[unstable = "pending trait organization"]
    fn len_utf8(self) -> uint {
        let code = self as u32;
        match () {
            _ if code < MAX_ONE_B   => 1u,
            _ if code < MAX_TWO_B   => 2u,
            _ if code < MAX_THREE_B => 3u,
            _  => 4u,
        }
    }

    #[inline]
    #[unstable = "pending trait organization"]
    fn len_utf16(self) -> uint {
        let ch = self as u32;
        if (ch & 0xFFFF_u32) == ch { 1 } else { 2 }
    }

    #[inline]
    #[unstable = "pending error conventions, trait organization"]
    fn encode_utf8(self, dst: &mut [u8]) -> Option<uint> {
        // Marked #[inline] to allow llvm optimizing it away
        let code = self as u32;
        if code < MAX_ONE_B && dst.len() >= 1 {
            dst[0] = code as u8;
            Some(1)
        } else if code < MAX_TWO_B && dst.len() >= 2 {
            dst[0] = (code >> 6u & 0x1F_u32) as u8 | TAG_TWO_B;
            dst[1] = (code & 0x3F_u32) as u8 | TAG_CONT;
            Some(2)
        } else if code < MAX_THREE_B && dst.len() >= 3  {
            dst[0] = (code >> 12u & 0x0F_u32) as u8 | TAG_THREE_B;
            dst[1] = (code >>  6u & 0x3F_u32) as u8 | TAG_CONT;
            dst[2] = (code & 0x3F_u32) as u8 | TAG_CONT;
            Some(3)
        } else if dst.len() >= 4 {
            dst[0] = (code >> 18u & 0x07_u32) as u8 | TAG_FOUR_B;
            dst[1] = (code >> 12u & 0x3F_u32) as u8 | TAG_CONT;
            dst[2] = (code >>  6u & 0x3F_u32) as u8 | TAG_CONT;
            dst[3] = (code & 0x3F_u32) as u8 | TAG_CONT;
            Some(4)
        } else {
            None
        }
    }

    #[inline]
    #[unstable = "pending error conventions, trait organization"]
    fn encode_utf16(self, dst: &mut [u16]) -> Option<uint> {
        // Marked #[inline] to allow llvm optimizing it away
        let mut ch = self as u32;
        if (ch & 0xFFFF_u32) == ch  && dst.len() >= 1 {
            // The BMP falls through (assuming non-surrogate, as it should)
            dst[0] = ch as u16;
            Some(1)
        } else if dst.len() >= 2 {
            // Supplementary planes break into surrogates.
            ch -= 0x1_0000_u32;
            dst[0] = 0xD800_u16 | ((ch >> 10) as u16);
            dst[1] = 0xDC00_u16 | ((ch as u16) & 0x3FF_u16);
            Some(2)
        } else {
            None
        }
    }
}

/// An iterator over the characters that represent a `char`, as escaped by
/// Rust's unicode escaping rules.
#[derive(Clone)]
pub struct EscapeUnicode {
    c: char,
    state: EscapeUnicodeState
}

#[derive(Clone)]
enum EscapeUnicodeState {
    Backslash,
    Type,
    LeftBrace,
    Value(uint),
    RightBrace,
    Done,
}

impl Iterator for EscapeUnicode {
    type Item = char;

    fn next(&mut self) -> Option<char> {
        match self.state {
            EscapeUnicodeState::Backslash => {
                self.state = EscapeUnicodeState::Type;
                Some('\\')
            }
            EscapeUnicodeState::Type => {
                self.state = EscapeUnicodeState::LeftBrace;
                Some('u')
            }
            EscapeUnicodeState::LeftBrace => {
                let mut n = 0u;
                while (self.c as u32) >> (4 * (n + 1)) != 0 {
                    n += 1;
                }
                self.state = EscapeUnicodeState::Value(n);
                Some('{')
            }
            EscapeUnicodeState::Value(offset) => {
                let v = match ((self.c as i32) >> (offset * 4)) & 0xf {
                    i @ 0 ... 9 => '0' as i32 + i,
                    i => 'a' as i32 + (i - 10)
                };
                if offset == 0 {
                    self.state = EscapeUnicodeState::RightBrace;
                } else {
                    self.state = EscapeUnicodeState::Value(offset - 1);
                }
                Some(unsafe { transmute(v) })
            }
            EscapeUnicodeState::RightBrace => {
                self.state = EscapeUnicodeState::Done;
                Some('}')
            }
            EscapeUnicodeState::Done => None,
        }
    }
}

/// An iterator over the characters that represent a `char`, escaped
/// for maximum portability.
#[derive(Clone)]
pub struct EscapeDefault {
    state: EscapeDefaultState
}

#[derive(Clone)]
enum EscapeDefaultState {
    Backslash(char),
    Char(char),
    Done,
    Unicode(EscapeUnicode),
}

impl Iterator for EscapeDefault {
    type Item = char;

    fn next(&mut self) -> Option<char> {
        match self.state {
            EscapeDefaultState::Backslash(c) => {
                self.state = EscapeDefaultState::Char(c);
                Some('\\')
            }
            EscapeDefaultState::Char(c) => {
                self.state = EscapeDefaultState::Done;
                Some(c)
            }
            EscapeDefaultState::Done => None,
            EscapeDefaultState::Unicode(ref mut iter) => iter.next()
        }
    }
}
<|endoftext|>


<commit_before>// Top-level, visible-everywhere definitions.

// Export various ubiquitous types, constructors, methods.

import option::{Some, None};
import Option = option::Option;
// XXX: snapshot rustc is generating code that wants lower-case option
#[cfg(stage0)]
import option = option::Option;

import Path = path2::Path;
import GenericPath = path2::GenericPath;
import WindowsPath = path2::WindowsPath;
import PosixPath = path2::PosixPath;

import tuple::{TupleOps, ExtendedTupleOps};
import str::{StrSlice, UniqueStr};
import vec::{ConstVector, CopyableVector, ImmutableVector};
import vec::{ImmutableCopyableVector};
import iter::{BaseIter, ExtendedIter, CopyableIter, Times, TimesIx};
import num::Num;
import ptr::Ptr;
import to_str::ToStr;

export Path, WindowsPath, PosixPath, GenericPath;
export Option, Some, None, unreachable;
export extensions;
// The following exports are the extension impls for numeric types
export Num, Times, TimesIx;
// The following exports are the common traits
export StrSlice, UniqueStr;
export ConstVector, CopyableVector, ImmutableVector;
export ImmutableCopyableVector, IterTraitExtensions;
export BaseIter, CopyableIter, ExtendedIter;
export TupleOps, ExtendedTupleOps;
export Ptr;
export ToStr;

// The following exports are the core operators and kinds
// The compiler has special knowlege of these so we must not duplicate them
// when compiling for testing
#[cfg(notest)]
import ops::{const, copy, send, owned};
#[cfg(notest)]
import ops::{add, sub, mul, div, modulo, neg, bitand, bitor, bitxor};
#[cfg(notest)]
import ops::{shl, shr, index};

#[cfg(notest)]
export const, copy, send, owned;
#[cfg(notest)]
export add, sub, mul, div, modulo, neg, bitand, bitor, bitxor;
#[cfg(notest)]
export shl, shr, index;

#[cfg(test)]
use coreops(name = "core", vers = "0.3");

#[cfg(test)]
import coreops::ops::{const, copy, send, owned};
#[cfg(test)]
import coreops::ops::{add, sub, mul, div, modulo, neg, bitand, bitor, bitxor};
#[cfg(test)]
import coreops::ops::{shl, shr, index};

// Export the log levels as global constants. Higher levels mean
// more-verbosity. Error is the bottom level, default logging level is
// warn-and-below.

export error, warn, info, debug;

/// The error log level
const error : u32 = 0_u32;
/// The warning log level
const warn : u32 = 1_u32;
/// The info log level
const info : u32 = 2_u32;
/// The debug log level
const debug : u32 = 3_u32;

// A curious inner-module that's not exported that contains the binding
// 'core' so that macro-expanded references to core::error and such
// can be resolved within libcore.
mod core {
    const error : u32 = 0_u32;
    const warn : u32 = 1_u32;
    const info : u32 = 2_u32;
    const debug : u32 = 3_u32;
}

// Similar to above. Some magic to make core testable.
#[cfg(test)]
mod std {
    use std(vers = "0.3");
    import std::test;
}

/**
 * A standard function to use to indicate unreachable code. Because the
 * function is guaranteed to fail typestate will correctly identify
 * any code paths following the appearance of this function as unreachable.
 */
fn unreachable() -> ! {
    fail ~"Internal error: entered unreachable code";
}

<commit_msg>Import Result, Ok, and Err by default. Closes #3287<commit_after>// Top-level, visible-everywhere definitions.

// Export various ubiquitous types, constructors, methods.

import option::{Some, None};
import Option = option::Option;
// XXX: snapshot rustc is generating code that wants lower-case option
#[cfg(stage0)]
import option = option::Option;

import result::{Result, Ok, Err};

import Path = path2::Path;
import GenericPath = path2::GenericPath;
import WindowsPath = path2::WindowsPath;
import PosixPath = path2::PosixPath;

import tuple::{TupleOps, ExtendedTupleOps};
import str::{StrSlice, UniqueStr};
import vec::{ConstVector, CopyableVector, ImmutableVector};
import vec::{ImmutableCopyableVector};
import iter::{BaseIter, ExtendedIter, CopyableIter, Times, TimesIx};
import num::Num;
import ptr::Ptr;
import to_str::ToStr;

export Path, WindowsPath, PosixPath, GenericPath;
export Option, Some, None, unreachable;
export Result, Ok, Error;
export extensions;
// The following exports are the extension impls for numeric types
export Num, Times, TimesIx;
// The following exports are the common traits
export StrSlice, UniqueStr;
export ConstVector, CopyableVector, ImmutableVector;
export ImmutableCopyableVector, IterTraitExtensions;
export BaseIter, CopyableIter, ExtendedIter;
export TupleOps, ExtendedTupleOps;
export Ptr;
export ToStr;

// The following exports are the core operators and kinds
// The compiler has special knowlege of these so we must not duplicate them
// when compiling for testing
#[cfg(notest)]
import ops::{const, copy, send, owned};
#[cfg(notest)]
import ops::{add, sub, mul, div, modulo, neg, bitand, bitor, bitxor};
#[cfg(notest)]
import ops::{shl, shr, index};

#[cfg(notest)]
export const, copy, send, owned;
#[cfg(notest)]
export add, sub, mul, div, modulo, neg, bitand, bitor, bitxor;
#[cfg(notest)]
export shl, shr, index;

#[cfg(test)]
use coreops(name = "core", vers = "0.3");

#[cfg(test)]
import coreops::ops::{const, copy, send, owned};
#[cfg(test)]
import coreops::ops::{add, sub, mul, div, modulo, neg, bitand, bitor, bitxor};
#[cfg(test)]
import coreops::ops::{shl, shr, index};

// Export the log levels as global constants. Higher levels mean
// more-verbosity. Error is the bottom level, default logging level is
// warn-and-below.

export error, warn, info, debug;

/// The error log level
const error : u32 = 0_u32;
/// The warning log level
const warn : u32 = 1_u32;
/// The info log level
const info : u32 = 2_u32;
/// The debug log level
const debug : u32 = 3_u32;

// A curious inner-module that's not exported that contains the binding
// 'core' so that macro-expanded references to core::error and such
// can be resolved within libcore.
mod core {
    const error : u32 = 0_u32;
    const warn : u32 = 1_u32;
    const info : u32 = 2_u32;
    const debug : u32 = 3_u32;
}

// Similar to above. Some magic to make core testable.
#[cfg(test)]
mod std {
    use std(vers = "0.3");
    import std::test;
}

/**
 * A standard function to use to indicate unreachable code. Because the
 * function is guaranteed to fail typestate will correctly identify
 * any code paths following the appearance of this function as unreachable.
 */
fn unreachable() -> ! {
    fail ~"Internal error: entered unreachable code";
}

<|endoftext|>


<commit_before>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::container::{Container, Mutable};
use core::cmp::Eq;
use core::prelude::*;
use core::uint;
use core::vec;

const initial_capacity: uint = 32u; // 2^5

pub struct Deque<T> {
    priv nelts: uint,
    priv lo: uint,
    priv hi: uint,
    priv elts: ~[Option<T>]
}

impl<T> Container for Deque<T> {
    pure fn len(&self) -> uint { self.nelts }
    pure fn is_empty(&self) -> bool { self.len() == 0 }
}

impl<T> Mutable for Deque<T> {
    fn clear(&mut self) {
        for vec::each_mut(self.elts) |x| { *x = None }
        self.nelts = 0;
        self.lo = 0;
        self.hi = 0;
    }
}

impl<T> Deque<T> {
    static pure fn new() -> Deque<T> {
        Deque{nelts: 0, lo: 0, hi: 0,
              elts: vec::from_fn(initial_capacity, |_| None)}
    }
}

impl<T: Copy> Deque<T> {
    fn add_front(&mut self, t: T) {
        let oldlo: uint = self.lo;
        if self.lo == 0u {
            self.lo = self.elts.len() - 1u;
        } else { self.lo -= 1u; }
        if self.lo == self.hi {
            self.elts = grow(self.nelts, oldlo, self.elts);
            self.lo = self.elts.len() - 1u;
            self.hi = self.nelts;
        }
        self.elts[self.lo] = Some(t);
        self.nelts += 1u;
    }

    fn add_back(&mut self, t: T) {
        if self.lo == self.hi && self.nelts != 0u {
            self.elts = grow(self.nelts, self.lo, self.elts);
            self.lo = 0u;
            self.hi = self.nelts;
        }
        self.elts[self.hi] = Some(t);
        self.hi = (self.hi + 1u) % self.elts.len();
        self.nelts += 1u;
    }

    fn pop_front(&mut self) -> T {
        let t = { *get(self.elts, self.lo) };
        self.elts[self.lo] = None;
        self.lo = (self.lo + 1u) % self.elts.len();
        self.nelts -= 1u;
        t
    }

    fn pop_back(&mut self) -> T {
        if self.hi == 0u {
            self.hi = self.elts.len() - 1u;
        } else { self.hi -= 1u; }
        let t = { *get(self.elts, self.hi) };
        self.elts[self.hi] = None;
        self.nelts -= 1u;
        t
    }

    fn peek_front(&self) -> T { *get(self.elts, self.lo) }

    fn peek_back(&self) -> T { *get(self.elts, self.hi - 1u) }

    fn get(&self, i: int) -> T {
        let idx = (self.lo + (i as uint)) % self.elts.len();
        *get(self.elts, idx)
    }
}

/// Grow is only called on full elts, so nelts is also len(elts), unlike
/// elsewhere.
fn grow<T: Copy>(nelts: uint, lo: uint, elts: &[Option<T>]) -> ~[Option<T>] {
    assert nelts == elts.len();
    let mut rv = ~[];

    let mut i = 0u;
    let nalloc = uint::next_power_of_two(nelts + 1u);
    while i < nalloc {
        if i < nelts {
            rv.push(elts[(lo + i) % nelts]);
        } else { rv.push(None); }
        i += 1u;
    }

    rv
}

fn get<T>(elts: &r/[Option<T>], i: uint) -> &r/T {
    match elts[i] { Some(ref t) => t, _ => fail!() }
}

#[cfg(test)]
mod tests {
    use core::prelude::*;
    use super::*;

    #[test]
    fn test_simple() {
        let mut d = Deque::new();
        assert (d.len() == 0u);
        d.add_front(17);
        d.add_front(42);
        d.add_back(137);
        assert (d.len() == 3u);
        d.add_back(137);
        assert (d.len() == 4u);
        log(debug, d.peek_front());
        assert (d.peek_front() == 42);
        log(debug, d.peek_back());
        assert (d.peek_back() == 137);
        let mut i: int = d.pop_front();
        log(debug, i);
        assert (i == 42);
        i = d.pop_back();
        log(debug, i);
        assert (i == 137);
        i = d.pop_back();
        log(debug, i);
        assert (i == 137);
        i = d.pop_back();
        log(debug, i);
        assert (i == 17);
        assert (d.len() == 0u);
        d.add_back(3);
        assert (d.len() == 1u);
        d.add_front(2);
        assert (d.len() == 2u);
        d.add_back(4);
        assert (d.len() == 3u);
        d.add_front(1);
        assert (d.len() == 4u);
        log(debug, d.get(0));
        log(debug, d.get(1));
        log(debug, d.get(2));
        log(debug, d.get(3));
        assert (d.get(0) == 1);
        assert (d.get(1) == 2);
        assert (d.get(2) == 3);
        assert (d.get(3) == 4);
    }

    #[test]
    fn test_boxes() {
        let a: @int = @5;
        let b: @int = @72;
        let c: @int = @64;
        let d: @int = @175;

        let mut deq = Deque::new();
        assert (deq.len() == 0u);
        deq.add_front(a);
        deq.add_front(b);
        deq.add_back(c);
        assert (deq.len() == 3u);
        deq.add_back(d);
        assert (deq.len() == 4u);
        assert (deq.peek_front() == b);
        assert (deq.peek_back() == d);
        assert (deq.pop_front() == b);
        assert (deq.pop_back() == d);
        assert (deq.pop_back() == c);
        assert (deq.pop_back() == a);
        assert (deq.len() == 0u);
        deq.add_back(c);
        assert (deq.len() == 1u);
        deq.add_front(b);
        assert (deq.len() == 2u);
        deq.add_back(d);
        assert (deq.len() == 3u);
        deq.add_front(a);
        assert (deq.len() == 4u);
        assert (deq.get(0) == a);
        assert (deq.get(1) == b);
        assert (deq.get(2) == c);
        assert (deq.get(3) == d);
    }

    fn test_parameterized<T: Copy Eq Durable>(a: T, b: T, c: T, d: T) {
        let mut deq = Deque::new();
        assert (deq.len() == 0u);
        deq.add_front(a);
        deq.add_front(b);
        deq.add_back(c);
        assert (deq.len() == 3u);
        deq.add_back(d);
        assert (deq.len() == 4u);
        assert deq.peek_front() == b;
        assert deq.peek_back() == d;
        assert deq.pop_front() == b;
        assert deq.pop_back() == d;
        assert deq.pop_back() == c;
        assert deq.pop_back() == a;
        assert (deq.len() == 0u);
        deq.add_back(c);
        assert (deq.len() == 1u);
        deq.add_front(b);
        assert (deq.len() == 2u);
        deq.add_back(d);
        assert (deq.len() == 3u);
        deq.add_front(a);
        assert (deq.len() == 4u);
        assert deq.get(0) == a;
        assert deq.get(1) == b;
        assert deq.get(2) == c;
        assert deq.get(3) == d;
    }

    #[deriving_eq]
    enum Taggy { One(int), Two(int, int), Three(int, int, int), }

    #[deriving_eq]
    enum Taggypar<T> {
        Onepar(int), Twopar(int, int), Threepar(int, int, int),
    }

    #[deriving_eq]
    struct RecCy {
        x: int,
        y: int,
        t: Taggy
    }

    #[test]
    fn test_param_int() {
        test_parameterized::<int>(5, 72, 64, 175);
    }

    #[test]
    fn test_param_at_int() {
        test_parameterized::<@int>(@5, @72, @64, @175);
    }

    #[test]
    fn test_param_taggy() {
        test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3),
                                    Two(17, 42));
    }

    #[test]
    fn test_param_taggypar() {
        test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
                                            Twopar::<int>(1, 2),
                                            Threepar::<int>(1, 2, 3),
                                            Twopar::<int>(17, 42));
    }

    #[test]
    fn test_param_reccy() {
        let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
        let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
        let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
        let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
        test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
    }
}
<commit_msg>deque: avoid Copy in peek_{front,back}<commit_after>// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use core::container::{Container, Mutable};
use core::cmp::Eq;
use core::prelude::*;
use core::uint;
use core::vec;

const initial_capacity: uint = 32u; // 2^5

pub struct Deque<T> {
    priv nelts: uint,
    priv lo: uint,
    priv hi: uint,
    priv elts: ~[Option<T>]
}

impl<T> Container for Deque<T> {
    pure fn len(&self) -> uint { self.nelts }
    pure fn is_empty(&self) -> bool { self.len() == 0 }
}

impl<T> Mutable for Deque<T> {
    fn clear(&mut self) {
        for vec::each_mut(self.elts) |x| { *x = None }
        self.nelts = 0;
        self.lo = 0;
        self.hi = 0;
    }
}

impl<T> Deque<T> {
    static pure fn new() -> Deque<T> {
        Deque{nelts: 0, lo: 0, hi: 0,
              elts: vec::from_fn(initial_capacity, |_| None)}
    }

    fn peek_front(&self) -> &self/T { get(self.elts, self.lo) }
    fn peek_back(&self) -> &self/T { get(self.elts, self.hi - 1u) }
}

impl<T: Copy> Deque<T> {
    fn add_front(&mut self, t: T) {
        let oldlo = self.lo;
        if self.lo == 0u {
            self.lo = self.elts.len() - 1u;
        } else { self.lo -= 1u; }
        if self.lo == self.hi {
            self.elts = grow(self.nelts, oldlo, self.elts);
            self.lo = self.elts.len() - 1u;
            self.hi = self.nelts;
        }
        self.elts[self.lo] = Some(t);
        self.nelts += 1u;
    }

    fn add_back(&mut self, t: T) {
        if self.lo == self.hi && self.nelts != 0u {
            self.elts = grow(self.nelts, self.lo, self.elts);
            self.lo = 0u;
            self.hi = self.nelts;
        }
        self.elts[self.hi] = Some(t);
        self.hi = (self.hi + 1u) % self.elts.len();
        self.nelts += 1u;
    }

    fn pop_front(&mut self) -> T {
        let t = { *get(self.elts, self.lo) };
        self.elts[self.lo] = None;
        self.lo = (self.lo + 1u) % self.elts.len();
        self.nelts -= 1u;
        t
    }

    fn pop_back(&mut self) -> T {
        if self.hi == 0u {
            self.hi = self.elts.len() - 1u;
        } else { self.hi -= 1u; }
        let t = { *get(self.elts, self.hi) };
        self.elts[self.hi] = None;
        self.nelts -= 1u;
        t
    }

    fn get(&self, i: int) -> T {
        let idx = (self.lo + (i as uint)) % self.elts.len();
        *get(self.elts, idx)
    }
}

/// Grow is only called on full elts, so nelts is also len(elts), unlike
/// elsewhere.
fn grow<T: Copy>(nelts: uint, lo: uint, elts: &[Option<T>]) -> ~[Option<T>] {
    assert nelts == elts.len();
    let mut rv = ~[];

    let mut i = 0u;
    let nalloc = uint::next_power_of_two(nelts + 1u);
    while i < nalloc {
        if i < nelts {
            rv.push(elts[(lo + i) % nelts]);
        } else { rv.push(None); }
        i += 1u;
    }

    rv
}

fn get<T>(elts: &r/[Option<T>], i: uint) -> &r/T {
    match elts[i] { Some(ref t) => t, _ => fail!() }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_simple() {
        let mut d = Deque::new();
        assert d.len() == 0u;
        d.add_front(17);
        d.add_front(42);
        d.add_back(137);
        assert d.len() == 3u;
        d.add_back(137);
        assert d.len() == 4u;
        log(debug, d.peek_front());
        assert *d.peek_front() == 42;
        log(debug, d.peek_back());
        assert *d.peek_back() == 137;
        let mut i: int = d.pop_front();
        log(debug, i);
        assert i == 42;
        i = d.pop_back();
        log(debug, i);
        assert i == 137;
        i = d.pop_back();
        log(debug, i);
        assert i == 137;
        i = d.pop_back();
        log(debug, i);
        assert i == 17;
        assert d.len() == 0u;
        d.add_back(3);
        assert d.len() == 1u;
        d.add_front(2);
        assert d.len() == 2u;
        d.add_back(4);
        assert d.len() == 3u;
        d.add_front(1);
        assert d.len() == 4u;
        log(debug, d.get(0));
        log(debug, d.get(1));
        log(debug, d.get(2));
        log(debug, d.get(3));
        assert d.get(0) == 1;
        assert d.get(1) == 2;
        assert d.get(2) == 3;
        assert d.get(3) == 4;
    }

    #[test]
    fn test_boxes() {
        let a: @int = @5;
        let b: @int = @72;
        let c: @int = @64;
        let d: @int = @175;

        let mut deq = Deque::new();
        assert deq.len() == 0;
        deq.add_front(a);
        deq.add_front(b);
        deq.add_back(c);
        assert deq.len() == 3;
        deq.add_back(d);
        assert deq.len() == 4;
        assert *deq.peek_front() == b;
        assert *deq.peek_back() == d;
        assert deq.pop_front() == b;
        assert deq.pop_back() == d;
        assert deq.pop_back() == c;
        assert deq.pop_back() == a;
        assert deq.len() == 0;
        deq.add_back(c);
        assert deq.len() == 1;
        deq.add_front(b);
        assert deq.len() == 2;
        deq.add_back(d);
        assert deq.len() == 3;
        deq.add_front(a);
        assert deq.len() == 4;
        assert deq.get(0) == a;
        assert deq.get(1) == b;
        assert deq.get(2) == c;
        assert deq.get(3) == d;
    }

    fn test_parameterized<T: Copy Eq Durable>(a: T, b: T, c: T, d: T) {
        let mut deq = Deque::new();
        assert deq.len() == 0;
        deq.add_front(a);
        deq.add_front(b);
        deq.add_back(c);
        assert deq.len() == 3;
        deq.add_back(d);
        assert deq.len() == 4;
        assert *deq.peek_front() == b;
        assert *deq.peek_back() == d;
        assert deq.pop_front() == b;
        assert deq.pop_back() == d;
        assert deq.pop_back() == c;
        assert deq.pop_back() == a;
        assert deq.len() == 0;
        deq.add_back(c);
        assert deq.len() == 1;
        deq.add_front(b);
        assert deq.len() == 2;
        deq.add_back(d);
        assert deq.len() == 3;
        deq.add_front(a);
        assert deq.len() == 4;
        assert deq.get(0) == a;
        assert deq.get(1) == b;
        assert deq.get(2) == c;
        assert deq.get(3) == d;
    }

    #[deriving_eq]
    enum Taggy { One(int), Two(int, int), Three(int, int, int), }

    #[deriving_eq]
    enum Taggypar<T> {
        Onepar(int), Twopar(int, int), Threepar(int, int, int),
    }

    #[deriving_eq]
    struct RecCy {
        x: int,
        y: int,
        t: Taggy
    }

    #[test]
    fn test_param_int() {
        test_parameterized::<int>(5, 72, 64, 175);
    }

    #[test]
    fn test_param_at_int() {
        test_parameterized::<@int>(@5, @72, @64, @175);
    }

    #[test]
    fn test_param_taggy() {
        test_parameterized::<Taggy>(One(1), Two(1, 2), Three(1, 2, 3),
                                    Two(17, 42));
    }

    #[test]
    fn test_param_taggypar() {
        test_parameterized::<Taggypar<int>>(Onepar::<int>(1),
                                            Twopar::<int>(1, 2),
                                            Threepar::<int>(1, 2, 3),
                                            Twopar::<int>(17, 42));
    }

    #[test]
    fn test_param_reccy() {
        let reccy1 = RecCy { x: 1, y: 2, t: One(1) };
        let reccy2 = RecCy { x: 345, y: 2, t: Two(1, 2) };
        let reccy3 = RecCy { x: 1, y: 777, t: Three(1, 2, 3) };
        let reccy4 = RecCy { x: 19, y: 252, t: Two(17, 42) };
        test_parameterized::<RecCy>(reccy1, reccy2, reccy3, reccy4);
    }
}
<|endoftext|>


<commit_before>//! Implements the `Evaluator` trait.

use std::hash::Hasher;
use std::collections::hash_map::DefaultHasher;
use uci::SetOption;
use board::*;
use value::*;
use evaluator::Evaluator;
use bitsets::*;

/// A simple evaluator that adds a random number to the available
/// material.
#[derive(Clone)]
pub struct SimpleEvaluator;

impl SetOption for SimpleEvaluator {}

impl Evaluator for SimpleEvaluator {
    #[allow(unused_variables)]
    fn new(position: &Board) -> SimpleEvaluator {
        SimpleEvaluator
    }

    fn evaluate(&self, position: &Board) -> Value {
        const PIECE_VALUES: [Value; 8] = [10000, 975, 500, 325, 325, 100, 0, 0];
        let piece_type = position.pieces.piece_type;
        let color = position.pieces.color;
        let us = position.to_move;
        let them = 1 ^ us;
        let mut result = 0;
        for piece in QUEEN..PIECE_NONE {
            result += PIECE_VALUES[piece] *
                      (pop_count(piece_type[piece] & color[us]) as i16 -
                       pop_count(piece_type[piece] & color[them]) as i16);
        }
        let mut hasher = DefaultHasher::new();
        hasher.write_u64(position.occupied);
        result + (hasher.finish() >> 59) as i16
    }

    #[allow(unused_variables)]
    #[inline]
    fn is_zugzwangy(&self, position: &Board) -> bool {
        false
    }
}
<commit_msg>improve SimpleEvaluator<commit_after>//! Implements the `Evaluator` trait.

use uci::SetOption;
use moves::*;
use board::*;
use value::*;
use evaluator::Evaluator;
use bitsets::*;

/// A simple evaluator that adds a random number to the available
/// material.
#[derive(Clone)]
pub struct SimpleEvaluator {
    material: Value,
}

impl SetOption for SimpleEvaluator {}

impl Evaluator for SimpleEvaluator {
    fn new(position: &Board) -> SimpleEvaluator {
        let us = position.to_move;
        let them = 1 ^ us;
        let color = position.pieces.color;
        let mut material = 0;
        for piece in QUEEN..PIECE_NONE {
            let occupied = position.pieces.piece_type[piece];
            let count_us = pop_count(occupied & color[us]) as i16;
            let count_them = pop_count(occupied & color[them]) as i16;
            material += PIECE_VALUES[piece] * (count_us - count_them);
        }
        SimpleEvaluator { material: material }
    }

    #[inline]
    fn done_move(&mut self, _: &Board, m: Move) {
        self.material = -(self.material + gained_material(m));
    }

    #[inline]
    fn undone_move(&mut self, _: &Board, m: Move) {
        self.material = -self.material - gained_material(m);
    }

    #[inline]
    fn evaluate(&self, position: &Board) -> Value {
        let k = (position.occupied >> 32 ^ position.occupied) as u32;
        let random_number = (k.wrapping_mul(2654435769) >> 27) as Value;
        self.material + random_number
    }

    #[allow(unused_variables)]
    #[inline]
    fn is_zugzwangy(&self, position: &Board) -> bool {
        false
    }
}

const PIECE_VALUES: [Value; 8] = [10000, 975, 500, 325, 325, 100, 0, 0];

#[inline]
fn gained_material(m: Move) -> Value {
    if m.move_type() == MOVE_PROMOTION {
        // the value of the captured piece
        PIECE_VALUES[m.captured_piece()]

        // add the value of the newly promoted piece
        + PIECE_VALUES[Move::piece_from_aux_data(m.aux_data())]

        // subtract the value of the promoted pawn
        - PIECE_VALUES[PAWN]
    } else {
        unsafe { *PIECE_VALUES.get_unchecked(m.captured_piece()) }
    }
}
<|endoftext|>


<commit_before>use crate::cpp_data::CppPathItem;
use crate::cpp_data::CppVisibility;
use crate::cpp_function::CppFunction;
use crate::cpp_function::CppFunctionKind;
use crate::cpp_function::CppFunctionMemberData;
use crate::cpp_type::CppType;
use crate::database::CppItemData;
use crate::database::DatabaseItemSource;
use crate::processor::ProcessingStep;
use crate::processor::ProcessorData;
use ritual_common::errors::Result;

pub fn add_explicit_destructors_step() -> ProcessingStep {
    ProcessingStep::new("add_explicit_destructors", add_explicit_destructors)
}

/// Adds destructors for every class that does not have explicitly
/// defined destructor, allowing to create wrappings for
/// destructors implicitly available in C++.
fn add_explicit_destructors(data: &mut ProcessorData) -> Result<()> {
    let mut methods = Vec::new();
    for type1 in &data.current_database.cpp_items {
        if let CppItemData::Type(ref type1) = type1.cpp_data {
            if type1.kind.is_class() {
                let class_name = &type1.path;
                let found_destructor = data
                    .current_database
                    .cpp_items
                    .iter()
                    .filter_map(|item| item.cpp_data.as_function_ref())
                    .any(|m| m.is_destructor() && m.class_type().as_ref() == Some(class_name));
                if !found_destructor {
                    methods.push(CppFunction {
                        path: type1
                            .path
                            .join(CppPathItem::from_str_unchecked(&format!("~{}", class_name))),
                        member: Some(CppFunctionMemberData {
                            is_virtual: false, // the destructor can actually be virtual but we don't care about it here
                            is_pure_virtual: false,
                            is_const: false,
                            is_static: false,
                            visibility: CppVisibility::Public,
                            is_signal: false,
                            is_slot: false,
                            kind: CppFunctionKind::Destructor,
                        }),
                        operator: None,
                        return_type: CppType::Void,
                        arguments: vec![],
                        allows_variadic_arguments: false,
                        declaration_code: None,
                        doc: None,
                    });
                }
            }
        }
    }
    for method in methods {
        data.current_database.add_cpp_data(
            DatabaseItemSource::ImplicitDestructor,
            CppItemData::Function(method),
        );
    }
    Ok(())
}
<commit_msg>add explicit constructors<commit_after>use crate::cpp_data::CppPathItem;
use crate::cpp_data::CppVisibility;
use crate::cpp_function::CppFunction;
use crate::cpp_function::CppFunctionKind;
use crate::cpp_function::CppFunctionMemberData;
use crate::cpp_type::CppType;
use crate::database::CppItemData;
use crate::database::DatabaseItemSource;
use crate::processor::ProcessingStep;
use crate::processor::ProcessorData;
use ritual_common::errors::Result;

pub fn add_explicit_destructors_step() -> ProcessingStep {
    ProcessingStep::new("add_explicit_destructors", add_explicit_destructors)
}

/// Adds destructors for every class that does not have explicitly
/// defined destructor, allowing to create wrappings for
/// destructors implicitly available in C++.
fn add_explicit_destructors(data: &mut ProcessorData) -> Result<()> {
    let mut methods = Vec::new();
    for type1 in &data.current_database.cpp_items {
        if let CppItemData::Type(ref type1) = type1.cpp_data {
            if type1.kind.is_class() {
                let class_path = &type1.path;
                let found_destructor = data
                    .current_database
                    .cpp_items
                    .iter()
                    .filter_map(|item| item.cpp_data.as_function_ref())
                    .any(|m| m.is_destructor() && m.class_type().as_ref() == Some(class_path));
                if !found_destructor {
                    methods.push(CppFunction {
                        path: type1
                            .path
                            .join(CppPathItem::from_str_unchecked(&format!("~{}", class_path))),
                        member: Some(CppFunctionMemberData {
                            is_virtual: false, // the destructor can actually be virtual but we don't care about it here
                            is_pure_virtual: false,
                            is_const: false,
                            is_static: false,
                            visibility: CppVisibility::Public,
                            is_signal: false,
                            is_slot: false,
                            kind: CppFunctionKind::Destructor,
                        }),
                        operator: None,
                        return_type: CppType::Void,
                        arguments: vec![],
                        allows_variadic_arguments: false,
                        declaration_code: None,
                        doc: None,
                    });
                }

                let found_constructor = data
                    .current_database
                    .cpp_items
                    .iter()
                    .filter_map(|item| item.cpp_data.as_function_ref())
                    .any(|m| m.is_constructor() && m.class_type().as_ref() == Some(class_path));
                if !found_constructor {
                    methods.push(CppFunction {
                        path: type1
                            .path
                            .join(type1.path.items.last().expect("aaa").clone()),
                        member: Some(CppFunctionMemberData {
                            is_virtual: false,
                            is_pure_virtual: false,
                            is_const: false,
                            is_static: false,
                            visibility: CppVisibility::Public,
                            is_signal: false,
                            is_slot: false,
                            kind: CppFunctionKind::Constructor,
                        }),
                        operator: None,
                        return_type: CppType::Void,
                        arguments: vec![],
                        allows_variadic_arguments: false,
                        declaration_code: None,
                        doc: None,
                    });
                }
            }
        }
    }
    for method in methods {
        data.current_database.add_cpp_data(
            DatabaseItemSource::ImplicitDestructor,
            CppItemData::Function(method),
        );
    }
    Ok(())
}
<|endoftext|>