<commit_before>// Copyright 2013-2014 The Rust Project Developers.
// Copyright 2018 The Uuid Project Developers.
//
// See the COPYRIGHT file at the top-level directory of this distribution.
//
// 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.

//! Adapters for various formats for [`Uuid`]s
//!
//! [`Uuid`]: ../struct.Uuid.html

use prelude::*;

mod core_support;

/// An adaptor for formatting an [`Uuid`] as a hyphenated string.
///
/// Takes an owned instance of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Hyphenated(Uuid);

/// An adaptor for formatting an [`Uuid`] as a hyphenated string.
///
/// Takes a reference of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct HyphenatedRef<'a>(&'a Uuid);

/// An adaptor for formatting an [`Uuid`] as a simple string.
///
/// Takes an owned instance of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Simple(Uuid);

/// An adaptor for formatting an [`Uuid`] as a simple string.
///
/// Takes a reference of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SimpleRef<'a>(&'a Uuid);

/// An adaptor for formatting an [`Uuid`] as a URN string.
///
/// Takes an owned instance of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Urn(Uuid);

/// An adaptor for formatting an [`Uuid`] as a URN string.
///
/// Takes a reference of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct UrnRef<'a>(&'a Uuid);

impl Uuid {
    /// Creates a [`UuidHyphenated`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenated`]: struct.UuidHyphenated.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_hyphenated(self) -> Hyphenated {
        Hyphenated::from_uuid(self)
    }

    /// Creates a [`UuidHyphenated`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenated`]: struct.UuidHyphenated.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_hyphenated(self) -> Hyphenated {
        Hyphenated::from_uuid(self)
    }

    /// Creates a [`UuidHyphenatedRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenatedRef`]: struct.UuidHyphenatedRef.html
    // TODO(: discuss to_ vs as_ vs into_
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_hyphenated_ref(&self) -> HyphenatedRef {
        HyphenatedRef::from_uuid_ref(self)
    }

    /// Creates a [`UuidHyphenatedRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenatedRef`]: struct.UuidHyphenatedRef.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_hyphenated_ref(&self) -> HyphenatedRef {
        HyphenatedRef::from_uuid_ref(self)
    }

    /// Creates a [`UuidSimple`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimple`]: struct.UuidSimple.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_simple(self) -> Simple {
        Simple::from_uuid(self)
    }

    /// Creates a [`UuidSimple`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimple`]: struct.UuidSimple.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_simple(self) -> Simple {
        Simple::from_uuid(self)
    }

    /// Creates a [`UuidSimpleRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimpleRef`]: struct.UuidSimpleRef.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_simple_ref(&self) -> SimpleRef {
        SimpleRef::from_uuid_ref(self)
    }

    /// Creates a [`UuidSimpleRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimpleRef`]: struct.UuidSimpleRef.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_simple_ref(&self) -> SimpleRef {
        SimpleRef::from_uuid_ref(self)
    }

    /// Creates a [`UuidUrn`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrn`]: struct.UuidUrn.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_urn(self) -> Urn {
        Urn::from_uuid(self)
    }

    /// Creates a [`UuidUrn`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrn`]: struct.UuidUrn.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_urn(self) -> Urn {
        Urn::from_uuid(self)
    }

    /// Creates a [`UuidUrnRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrnRef`]: struct.UuidUrnRef.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_urn_ref(&self) -> UrnRef {
        UrnRef::from_uuid_ref(self)
    }

    /// Creates a [`UuidUrnRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrnRef`]: struct.UuidUrnRef.html
    // TODO: discuss to_ vs as_ vs into_
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_urn_ref(&self) -> UrnRef {
        UrnRef::from_uuid_ref(self)
    }
}

impl Hyphenated {
    /// The length of a hyphenated [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 36;

    /// Creates a [`UuidHyphenated`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenated`]: struct.UuidHyphenated.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Hyphenated(uuid)
    }

    /// Creates a [`UuidHyphenated`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenated`]: struct.UuidHyphenated.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Hyphenated(uuid)
    }
}

impl<'a> HyphenatedRef<'a> {
    /// The length of a hyphenated [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 36;

    /// Creates a [`UuidHyphenatedRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenatedRef`]: struct.UuidHyphenatedRef.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        HyphenatedRef(uuid)
    }

    /// Creates a [`UuidHyphenatedRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenatedRef`]: struct.UuidHyphenatedRef.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        HyphenatedRef(uuid)
    }
}

impl Simple {
    /// The length of a simple [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 32;

    /// Creates a [`UuidSimple`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimple`]: struct.UuidSimple.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Simple(uuid)
    }

    /// Creates a [`UuidSimple`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimple`]: struct.UuidSimple.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Simple(uuid)
    }
}

impl<'a> SimpleRef<'a> {
    /// The length of a simple [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 32;

    /// Creates a [`UuidSimpleRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimpleRef`]: struct.UuidSimpleRef.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        SimpleRef(uuid)
    }

    /// Creates a [`UuidSimpleRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimpleRef`]: struct.UuidSimpleRef.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        SimpleRef(uuid)
    }
}

impl Urn {
    /// The length of a URN [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 45;

    /// Creates a [`UuidUrn`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrn`]: struct.UuidUrn.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Urn(uuid)
    }

    /// Creates a [`UuidUrn`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrn`]: struct.UuidUrn.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Urn(uuid)
    }
}

impl<'a> UrnRef<'a> {
    /// The length of a URN [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 45;

    /// Creates a [`UuidUrnRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrnRef`]: struct.UuidUrnRef.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        UrnRef(uuid)
    }

    /// Creates a [`UuidUrnRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrnRef`]: struct.UuidUrnRef.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        UrnRef(&uuid)
    }
}
<commit_msg>remove the TODO comments for to_ prefix discussion<commit_after>// Copyright 2013-2014 The Rust Project Developers.
// Copyright 2018 The Uuid Project Developers.
//
// See the COPYRIGHT file at the top-level directory of this distribution.
//
// 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.

//! Adapters for various formats for [`Uuid`]s
//!
//! [`Uuid`]: ../struct.Uuid.html

use prelude::*;

mod core_support;

/// An adaptor for formatting an [`Uuid`] as a hyphenated string.
///
/// Takes an owned instance of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Hyphenated(Uuid);

/// An adaptor for formatting an [`Uuid`] as a hyphenated string.
///
/// Takes a reference of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct HyphenatedRef<'a>(&'a Uuid);

/// An adaptor for formatting an [`Uuid`] as a simple string.
///
/// Takes an owned instance of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Simple(Uuid);

/// An adaptor for formatting an [`Uuid`] as a simple string.
///
/// Takes a reference of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct SimpleRef<'a>(&'a Uuid);

/// An adaptor for formatting an [`Uuid`] as a URN string.
///
/// Takes an owned instance of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Urn(Uuid);

/// An adaptor for formatting an [`Uuid`] as a URN string.
///
/// Takes a reference of the [`Uuid`].
///
/// [`Uuid`]: ../struct.Uuid.html
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct UrnRef<'a>(&'a Uuid);

impl Uuid {
    /// Creates a [`UuidHyphenated`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenated`]: struct.UuidHyphenated.html
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_hyphenated(self) -> Hyphenated {
        Hyphenated::from_uuid(self)
    }

    /// Creates a [`UuidHyphenated`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenated`]: struct.UuidHyphenated.html
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_hyphenated(self) -> Hyphenated {
        Hyphenated::from_uuid(self)
    }

    /// Creates a [`UuidHyphenatedRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenatedRef`]: struct.UuidHyphenatedRef.html
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_hyphenated_ref(&self) -> HyphenatedRef {
        HyphenatedRef::from_uuid_ref(self)
    }

    /// Creates a [`UuidHyphenatedRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenatedRef`]: struct.UuidHyphenatedRef.html
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_hyphenated_ref(&self) -> HyphenatedRef {
        HyphenatedRef::from_uuid_ref(self)
    }

    /// Creates a [`UuidSimple`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimple`]: struct.UuidSimple.html
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_simple(self) -> Simple {
        Simple::from_uuid(self)
    }

    /// Creates a [`UuidSimple`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimple`]: struct.UuidSimple.html
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_simple(self) -> Simple {
        Simple::from_uuid(self)
    }

    /// Creates a [`UuidSimpleRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimpleRef`]: struct.UuidSimpleRef.html
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_simple_ref(&self) -> SimpleRef {
        SimpleRef::from_uuid_ref(self)
    }

    /// Creates a [`UuidSimpleRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimpleRef`]: struct.UuidSimpleRef.html
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_simple_ref(&self) -> SimpleRef {
        SimpleRef::from_uuid_ref(self)
    }

    /// Creates a [`UuidUrn`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrn`]: struct.UuidUrn.html
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_urn(self) -> Urn {
        Urn::from_uuid(self)
    }

    /// Creates a [`UuidUrn`] instance from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrn`]: struct.UuidUrn.html
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_urn(self) -> Urn {
        Urn::from_uuid(self)
    }

    /// Creates a [`UuidUrnRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrnRef`]: struct.UuidUrnRef.html
    #[cfg(not(feature = "const_fn"))]
    #[inline]
    pub fn to_urn_ref(&self) -> UrnRef {
        UrnRef::from_uuid_ref(self)
    }

    /// Creates a [`UuidUrnRef`] instance from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrnRef`]: struct.UuidUrnRef.html
    #[cfg(feature = "const_fn")]
    #[inline]
    pub fn to_urn_ref(&self) -> UrnRef {
        UrnRef::from_uuid_ref(self)
    }
}

impl Hyphenated {
    /// The length of a hyphenated [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 36;

    /// Creates a [`UuidHyphenated`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenated`]: struct.UuidHyphenated.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Hyphenated(uuid)
    }

    /// Creates a [`UuidHyphenated`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenated`]: struct.UuidHyphenated.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Hyphenated(uuid)
    }
}

impl<'a> HyphenatedRef<'a> {
    /// The length of a hyphenated [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 36;

    /// Creates a [`UuidHyphenatedRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenatedRef`]: struct.UuidHyphenatedRef.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        HyphenatedRef(uuid)
    }

    /// Creates a [`UuidHyphenatedRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidHyphenatedRef`]: struct.UuidHyphenatedRef.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        HyphenatedRef(uuid)
    }
}

impl Simple {
    /// The length of a simple [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 32;

    /// Creates a [`UuidSimple`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimple`]: struct.UuidSimple.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Simple(uuid)
    }

    /// Creates a [`UuidSimple`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimple`]: struct.UuidSimple.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Simple(uuid)
    }
}

impl<'a> SimpleRef<'a> {
    /// The length of a simple [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 32;

    /// Creates a [`UuidSimpleRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimpleRef`]: struct.UuidSimpleRef.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        SimpleRef(uuid)
    }

    /// Creates a [`UuidSimpleRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidSimpleRef`]: struct.UuidSimpleRef.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        SimpleRef(uuid)
    }
}

impl Urn {
    /// The length of a URN [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 45;

    /// Creates a [`UuidUrn`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrn`]: struct.UuidUrn.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Urn(uuid)
    }

    /// Creates a [`UuidUrn`] from a [`Uuid`].
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrn`]: struct.UuidUrn.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid(uuid: Uuid) -> Self {
        Urn(uuid)
    }
}

impl<'a> UrnRef<'a> {
    /// The length of a URN [`Uuid`] string.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    pub const LENGTH: usize = 45;

    /// Creates a [`UuidUrnRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrnRef`]: struct.UuidUrnRef.html
    #[cfg(not(feature = "const_fn"))]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        UrnRef(uuid)
    }

    /// Creates a [`UuidUrnRef`] from a [`Uuid`] reference.
    ///
    /// [`Uuid`]: ../struct.Uuid.html
    /// [`UuidUrnRef`]: struct.UuidUrnRef.html
    #[cfg(feature = "const_fn")]
    pub fn from_uuid_ref(uuid: &'a Uuid) -> Self {
        UrnRef(&uuid)
    }
}
<|endoftext|>


<commit_before>extern mod rsfml;
use rsfml::graphics::{Color, RectangleShape, RenderWindow};
use rsfml::graphics::rc::{Sprite, Text};
use rsfml::system::{Vector2u};
use std::rand::{task_rng, Rng};
mod button;
mod control;
mod deck;
mod menu;
mod window;

pub fn main_loop() {
	// Window declare and info set
	let window_vec:Vector2u = Vector2u::new(900, 600);
	let (window_x, window_y) = (window_vec.x as f32, window_vec.y as f32);
	// Setup Cards
	let (mut card_one_rand, mut card_two_rand, mut card_three_rand, mut card_four_rand, mut card_five_rand) = (0,0,0,0,0);
	let (mut all_cards, mut all_cards_desc) = ::deck::new(window_x/4.0, window_x*3.0/4.0, window_y/4.0, window_y/2.0);
	// Create Window
	let mut window = ::window::create(window_vec);
	// Main set of bools
	let mut screen = 1; let mut is_set = false;
	// Title Text
	let jura_bold = "../resources/font/Jura-DemiBold.ttf";
	let title_text = ::menu::new(jura_bold, "Welcome To Tarot", 30, window_x/4.0, window_y/4.0, 0.0);
	// Find random card for title screen
	let mut rng = task_rng();
	let title_card = rng.gen_range(0, 77);
	// What Card are we on
	let mut card_counter = 0;
	// Clear empty indexi of Deck
	all_cards.shrink_to_fit();
	all_cards_desc.shrink_to_fit();

	while window.is_open() {
		show_blank(&mut window);
		::control::exit(&mut window);

		match screen {
			// Title Screen
			1   =>	{
				// Create buttons
				let (all_button, all_text) = ::button::new(jura_bold, "All Cards", 200.0,window_x/4.0, 0.0, 50.0, window_y/2.0, 0.0);
				let (three_button, three_text) = ::button::new(jura_bold, "3 Card Layout", 200.0, window_x/4.0, 0.0, 50.0, window_y*4.0/6.0, 75.0);
				let (five_button, five_text) = ::button::new(jura_bold, "5 Card Layout", 200.0, window_x/4.0, 0.0, 50.0, window_y*5.0/6.0, 150.0);
				let (all_clicked, is_all) = ::control::button(&mut window, all_button.get_global_bounds(),1, 2);
				let (three_clicked, is_three) = ::control::button(&mut window, three_button.get_global_bounds(),1, 3);
				let (five_clicked, is_five) = ::control::button(&mut window, five_button.get_global_bounds(),1, 4);

				if is_all {screen = all_clicked} else if is_three {screen = three_clicked} else if is_five {screen = five_clicked}

				// Reset Random Cards
				is_set = false;
				let buttons = ~[&all_button, &three_button, &five_button];
				let button_text = ~[&all_text, &three_text, &five_text];
				show_title(&mut window, &title_text, &all_cards[title_card], buttons, button_text);
			}
			// Show All Cards
			2	=>	{
				let (back_button, back_text) = ::button::new(jura_bold, "Back to Title", 200.0,window_x/4.0, 0.0, 50.0, window_y*2.0/6.0, 0.0);
				let (last_button, last_text) = ::button::new(jura_bold, "Last Card", 200.0,window_x/4.0, 0.0, 50.0, window_y*4.0/6.0, 0.0);
				let (next_button, next_text) = ::button::new(jura_bold, "Next Card", 200.0,window_x/4.0, 0.0, 50.0, window_y*5.0/6.0, 0.0);
				let (back_clicked, is_back) = ::control::button(&mut window, back_button.get_global_bounds(),2,1);
				let (_, is_left) = ::control::button(&mut window, last_button.get_global_bounds(), 2, 2);
				let (_, is_right) = ::control::button(&mut window, next_button.get_global_bounds(), 2, 2);
				if is_back {screen = back_clicked}
				if is_left && card_counter > 0 {card_counter -= 1}
				if is_right && card_counter < 77{card_counter += 1}

				let buttons = ~[&back_button, &last_button, &next_button];
				let button_text = ~[&back_text, &last_text, &next_text];
				show_all(&mut window, &all_cards[card_counter], &all_cards_desc[card_counter], buttons, button_text);
			}
			// 3 Card Reading
			3	=>	{
				let (back_button, back_text) = ::button::new(jura_bold, "Back to Title", 200.0,window_x/2.0, 0.0, 50.0, window_y*5.0/6.0, 0.0);
				let (back_clicked, is_back) = ::control::button(&mut window, back_button.get_global_bounds(),3,1);

				if is_set == false {
					// Generate three cards
					card_one_rand = rng.gen_range(0, 77);
					card_two_rand = rng.gen_range(0, 77);
					if card_one_rand != card_two_rand {} else {card_two_rand = rng.gen_range(0, 77);}
					card_three_rand = rng.gen_range(0, 77);
					if (card_three_rand != card_two_rand) || (card_three_rand != card_one_rand) {} else {card_three_rand = rng.gen_range(0, 77);}
					is_set = true;
				} else if is_set == true{
					let mut card_one = match all_cards[card_one_rand].clone() {
						Some(card_one)	=>	card_one,
						None()			=>	fail!(~"Error, card_one created.")
					};
					let mut card_two = match all_cards[card_two_rand].clone() {
						Some(card_two)	=>	card_two,
						None()			=>	fail!(~"Error, card_two created.")
					};
					let mut card_three = match all_cards[card_three_rand].clone() {
						Some(card_three)	=>	card_three,
						None()			=>	fail!(~"Error, card_three created.")
					};
					&card_one.set_position2f(window_x/6.0, window_y/3.0);&card_one.set_scale2f(0.60, 0.60);
					&card_two.set_position2f(window_x/2.0, window_y/3.0);&card_two.set_scale2f(0.60, 0.60);
					&card_three.set_position2f(window_x*5.0/6.0, window_y/3.0);&card_three.set_scale2f(0.60, 0.60);
					let mut cards = ~[card_one, card_two, card_three];
					cards.shrink_to_fit();
					show_reading(&mut window, cards, &back_button, &back_text);
				}

				screen = back_clicked;
			}
			// 5 Card Spread
			4	=> {
				let (back_button, back_text) = ::button::new(jura_bold, "Back to Title", 200.0,window_x/2.0, 0.0, 50.0, window_y*5.0/6.0, 0.0);
				let (back_clicked, is_back) = ::control::button(&mut window, back_button.get_global_bounds(),4,1);

				if is_set == false {
					card_one_rand = rng.gen_range(0, 77);
					card_two_rand = rng.gen_range(0, 77);
					if card_one_rand != card_two_rand {} else {card_two_rand = rng.gen_range(0, 77);}
					card_three_rand = rng.gen_range(0, 77);
					if (card_three_rand != card_two_rand) || (card_three_rand != card_one_rand) {} else {card_three_rand = rng.gen_range(0, 77);}
					card_four_rand = rng.gen_range(0, 77);
					if (card_four_rand != card_two_rand) || (card_four_rand != card_one_rand) || (card_four_rand != card_three_rand) {} else {card_three_rand = rng.gen_range(0, 77);}
					card_five_rand = rng.gen_range(0, 77);
					if (card_five_rand != card_two_rand) || (card_five_rand != card_one_rand) || (card_five_rand != card_four_rand) || (card_five_rand != card_three_rand) {} else {card_three_rand = rng.gen_range(0, 77);}
					is_set = true;
				} else if is_set == true{
					let mut card_one = match all_cards[card_one_rand].clone() {
						Some(card_one)	=>	card_one,
						None()			=>	fail!(~"Error, card_one created.")
					};
					let mut card_two = match all_cards[card_two_rand].clone() {
						Some(card_two)	=>	card_two,
						None()			=>	fail!(~"Error, card_two created.")
					};
					let mut card_three = match all_cards[card_three_rand].clone() {
						Some(card_three)	=>	card_three,
						None()			=>	fail!(~"Error, card_three created.")
					};
					let mut card_four = match all_cards[card_four_rand].clone() {
						Some(card_four)	=>	card_four,
						None()			=>	fail!(~"Error, card_four created.")
					};
					let mut card_five = match all_cards[card_five_rand].clone() {
						Some(card_five)	=>	card_five,
						None()			=>	fail!(~"Error, card_five created.")
					};

					&card_one.set_position2f(window_x/6.0, window_y/4.0);&card_one.set_scale2f(0.45, 0.45);
					&card_two.set_position2f(window_x/2.0, window_y/4.0);&card_two.set_scale2f(0.45, 0.45);
					&card_three.set_position2f(window_x*5.0/6.0, window_y/4.0);&card_three.set_scale2f(0.45, 0.45);
					&card_four.set_position2f(window_x/6.0, window_y*3.0/4.0);&card_four.set_scale2f(0.45, 0.45);
					&card_five.set_position2f(window_x*5.0/6.0, window_y*3.0/4.0);&card_five.set_scale2f(0.45, 0.45);
					let mut cards = ~[card_one, card_two, card_three, card_four, card_five];
					cards.shrink_to_fit();

					show_reading(&mut window, cards, &back_button, &back_text);
				}
				screen = back_clicked;

			}
			5	=> {
				show_blank(&mut window);
				screen = 1;
			}
			_		=>	{fail!(~"Error, could not figure out screen to be on.");}
		}
	}
}
fn show_blank(window: &mut RenderWindow) {
	window.clear(&Color::white());
}

fn show_title(window: &mut RenderWindow, title_text: &Text, main_card:&Sprite, buttons:~[&RectangleShape], button_text:~[&Text]) {
	window.clear(&Color::white());
	window.draw(title_text);
	for contents in buttons.iter() {
		window.draw(*contents);
	}
	for contents in button_text.iter() {
		window.draw(*contents);
	}
	window.draw(main_card);
	window.display()
}
fn show_all(window: &mut RenderWindow, current_card:&Sprite, current_description:&Text, buttons:~[&RectangleShape], button_text:~[&Text]) {
	window.clear(&Color::white());
	window.draw(current_card); window.draw(current_description);
	for contents in buttons.iter() {
		window.draw(*contents);
	}
	for contents in button_text.iter() {
		window.draw(*contents);
	}
	window.display()
}
fn show_reading(window:&mut RenderWindow, cards:~[Sprite], back_button:&RectangleShape, back_text:&Text) {
	window.clear(&Color::white());
	for card_layout in cards.iter() {
		window.draw(card_layout);
	}
	window.draw(back_button);
	window.draw(back_text);
	window.display()
}
<commit_msg>Setup a timer so buttons on diffent screens can be clicked with out the sreen reading it as a double click<commit_after>extern mod rsfml;
use rsfml::graphics::{Color, RectangleShape, RenderWindow};
use rsfml::graphics::rc::{Sprite, Text};
use rsfml::system::{Clock, Time, Vector2u};
use std::rand::{task_rng, Rng};
mod button;
mod control;
mod deck;
mod menu;
mod window;

pub fn main_loop() {
	// Window declare and info set
	let window_vec:Vector2u = Vector2u::new(900, 600);
	let (window_x, window_y) = (window_vec.x as f32, window_vec.y as f32);
	// Setup Cards
	let (mut card_one_rand, mut card_two_rand, mut card_three_rand, mut card_four_rand, mut card_five_rand) = (0,0,0,0,0);
	let (mut all_cards, mut all_cards_desc) = ::deck::new(window_x/4.0, window_x*3.0/4.0, window_y/4.0, window_y/2.0);
	// Create Window
	let mut window = ::window::create(window_vec);
	// Main set of bools
	let mut screen = 1; let mut is_set = false;
	// Title Text
	let jura_bold = "../resources/font/Jura-DemiBold.ttf";
	let title_text = ::menu::new(jura_bold, "Welcome To Tarot", 30, window_x/4.0, window_y/4.0, 0.0);
	// Find random card for title screen
	let mut rng = task_rng();
	let title_card = rng.gen_range(0, 77);
	// What Card are we on
	let mut card_counter = 0;
	// Clear empty indexi of Deck
	all_cards.shrink_to_fit();
	all_cards_desc.shrink_to_fit();
	let mut input_timer = Clock::new();

	while window.is_open() {
		show_blank(&mut window);
		::control::exit(&mut window);

		match screen {
			// Title Screen
			1   =>	{
				// Create buttons
				let (all_button, all_text) = ::button::new(jura_bold, "All Cards", 200.0,window_x/4.0, 0.0, 50.0, window_y/2.0, 0.0);
				let (three_button, three_text) = ::button::new(jura_bold, "3 Card Layout", 200.0, window_x/4.0, 0.0, 50.0, window_y*4.0/6.0, 75.0);
				let (five_button, five_text) = ::button::new(jura_bold, "5 Card Layout", 200.0, window_x/4.0, 0.0, 50.0, window_y*5.0/6.0, 150.0);
				let (all_clicked, is_all) = ::control::button(&mut window, all_button.get_global_bounds(),1, 2);
				let (three_clicked, is_three) = ::control::button(&mut window, three_button.get_global_bounds(),1, 3);
				let (five_clicked, is_five) = ::control::button(&mut window, five_button.get_global_bounds(),1, 4);

				if input_timer.get_elapsed_time() > Time::with_seconds(0.09){
					if is_all {screen = all_clicked} else if is_three {screen = three_clicked} else if is_five {screen = five_clicked}
					input_timer.restart();
				};

				// Reset Random Cards
				is_set = false;
				let buttons = ~[&all_button, &three_button, &five_button];
				let button_text = ~[&all_text, &three_text, &five_text];
				show_title(&mut window, &title_text, &all_cards[title_card], buttons, button_text);
			}
			// Show All Cards
			2	=>	{
				let (back_button, back_text) = ::button::new(jura_bold, "Back to Title", 200.0,window_x/4.0, 0.0, 50.0, window_y/2.0, 0.0);
				let (last_button, last_text) = ::button::new(jura_bold, "Last Card", 200.0,window_x/4.0, 0.0, 50.0, window_y*4.0/6.0, 0.0);
				let (next_button, next_text) = ::button::new(jura_bold, "Next Card", 200.0,window_x/4.0, 0.0, 50.0, window_y*5.0/6.0, 0.0);
				let (back_clicked, is_back) = ::control::button(&mut window, back_button.get_global_bounds(),2,1);
				let (_, is_left) = ::control::button(&mut window, last_button.get_global_bounds(), 2, 2);
				let (_, is_right) = ::control::button(&mut window, next_button.get_global_bounds(), 2, 2);
				if input_timer.get_elapsed_time() > Time::with_seconds(0.09){
					if is_back {screen = back_clicked}
					if is_left && card_counter > 0 {card_counter -= 1};
					if is_right && card_counter < 77{card_counter += 1};
					input_timer.restart();
				};

				let buttons = ~[&back_button, &last_button, &next_button];
				let button_text = ~[&back_text, &last_text, &next_text];
				show_all(&mut window, &all_cards[card_counter], &all_cards_desc[card_counter], buttons, button_text);
			}
			// 3 Card Reading
			3	=>	{
				let (back_button, back_text) = ::button::new(jura_bold, "Back to Title", 200.0,window_x/2.0, 0.0, 50.0, window_y*5.0/6.0, 0.0);
				let (back_clicked, is_back) = ::control::button(&mut window, back_button.get_global_bounds(),3,1);

				if is_set == false {
					// Generate three cards
					card_one_rand = rng.gen_range(0, 77);
					card_two_rand = rng.gen_range(0, 77);
					if card_one_rand != card_two_rand {} else {card_two_rand = rng.gen_range(0, 77);}
					card_three_rand = rng.gen_range(0, 77);
					if (card_three_rand != card_two_rand) || (card_three_rand != card_one_rand) {} else {card_three_rand = rng.gen_range(0, 77);}
					is_set = true;
				} else if is_set == true{
					let mut card_one = match all_cards[card_one_rand].clone() {
						Some(card_one)	=>	card_one,
						None()			=>	fail!(~"Error, card_one created.")
					};
					let mut card_two = match all_cards[card_two_rand].clone() {
						Some(card_two)	=>	card_two,
						None()			=>	fail!(~"Error, card_two created.")
					};
					let mut card_three = match all_cards[card_three_rand].clone() {
						Some(card_three)	=>	card_three,
						None()			=>	fail!(~"Error, card_three created.")
					};
					&card_one.set_position2f(window_x/6.0, window_y/3.0);&card_one.set_scale2f(0.60, 0.60);
					&card_two.set_position2f(window_x/2.0, window_y/3.0);&card_two.set_scale2f(0.60, 0.60);
					&card_three.set_position2f(window_x*5.0/6.0, window_y/3.0);&card_three.set_scale2f(0.60, 0.60);
					let mut cards = ~[card_one, card_two, card_three];
					cards.shrink_to_fit();
					show_reading(&mut window, cards, &back_button, &back_text);
				}

				screen = back_clicked;
			}
			// 5 Card Spread
			4	=> {
				let (back_button, back_text) = ::button::new(jura_bold, "Back to Title", 200.0,window_x/2.0, 0.0, 50.0, window_y*5.0/6.0, 0.0);
				let (back_clicked, is_back) = ::control::button(&mut window, back_button.get_global_bounds(),4,1);

				if is_set == false {
					card_one_rand = rng.gen_range(0, 77);
					card_two_rand = rng.gen_range(0, 77);
					if card_one_rand != card_two_rand {} else {card_two_rand = rng.gen_range(0, 77);}
					card_three_rand = rng.gen_range(0, 77);
					if (card_three_rand != card_two_rand) || (card_three_rand != card_one_rand) {} else {card_three_rand = rng.gen_range(0, 77);}
					card_four_rand = rng.gen_range(0, 77);
					if (card_four_rand != card_two_rand) || (card_four_rand != card_one_rand) || (card_four_rand != card_three_rand) {} else {card_three_rand = rng.gen_range(0, 77);}
					card_five_rand = rng.gen_range(0, 77);
					if (card_five_rand != card_two_rand) || (card_five_rand != card_one_rand) || (card_five_rand != card_four_rand) || (card_five_rand != card_three_rand) {} else {card_three_rand = rng.gen_range(0, 77);}
					is_set = true;
				} else if is_set == true{
					let mut card_one = match all_cards[card_one_rand].clone() {
						Some(card_one)	=>	card_one,
						None()			=>	fail!(~"Error, card_one created.")
					};
					let mut card_two = match all_cards[card_two_rand].clone() {
						Some(card_two)	=>	card_two,
						None()			=>	fail!(~"Error, card_two created.")
					};
					let mut card_three = match all_cards[card_three_rand].clone() {
						Some(card_three)	=>	card_three,
						None()			=>	fail!(~"Error, card_three created.")
					};
					let mut card_four = match all_cards[card_four_rand].clone() {
						Some(card_four)	=>	card_four,
						None()			=>	fail!(~"Error, card_four created.")
					};
					let mut card_five = match all_cards[card_five_rand].clone() {
						Some(card_five)	=>	card_five,
						None()			=>	fail!(~"Error, card_five created.")
					};

					&card_one.set_position2f(window_x/6.0, window_y/4.0);&card_one.set_scale2f(0.45, 0.45);
					&card_two.set_position2f(window_x/2.0, window_y/4.0);&card_two.set_scale2f(0.45, 0.45);
					&card_three.set_position2f(window_x*5.0/6.0, window_y/4.0);&card_three.set_scale2f(0.45, 0.45);
					&card_four.set_position2f(window_x/6.0, window_y*3.0/4.0);&card_four.set_scale2f(0.45, 0.45);
					&card_five.set_position2f(window_x*5.0/6.0, window_y*3.0/4.0);&card_five.set_scale2f(0.45, 0.45);
					let mut cards = ~[card_one, card_two, card_three, card_four, card_five];
					cards.shrink_to_fit();

					show_reading(&mut window, cards, &back_button, &back_text);
				}
				screen = back_clicked;

			}
			5	=> {
				show_blank(&mut window);
				screen = 1;
			}
			_		=>	{fail!(~"Error, could not figure out screen to be on.");}
		}
	}
}
fn show_blank(window: &mut RenderWindow) {
	window.clear(&Color::white());
}

fn show_title(window: &mut RenderWindow, title_text: &Text, main_card:&Sprite, buttons:~[&RectangleShape], button_text:~[&Text]) {
	window.clear(&Color::white());
	window.draw(title_text);
	for contents in buttons.iter() {
		window.draw(*contents);
	}
	for contents in button_text.iter() {
		window.draw(*contents);
	}
	window.draw(main_card);
	window.display()
}
fn show_all(window: &mut RenderWindow, current_card:&Sprite, current_description:&Text, buttons:~[&RectangleShape], button_text:~[&Text]) {
	window.clear(&Color::white());
	window.draw(current_card); window.draw(current_description);
	for contents in buttons.iter() {
		window.draw(*contents);
	}
	for contents in button_text.iter() {
		window.draw(*contents);
	}
	window.display()
}
fn show_reading(window:&mut RenderWindow, cards:~[Sprite], back_button:&RectangleShape, back_text:&Text) {
	window.clear(&Color::white());
	for card_layout in cards.iter() {
		window.draw(card_layout);
	}
	window.draw(back_button);
	window.draw(back_text);
	window.display()
}
<|endoftext|>


<commit_before>/// Macro for implementing `Entrypoint` or `DecodedEntryPoint` boilerplate in an algorithm
///
/// Algorithmia support for Rust algorithms is hard-coded to call `Algo::apply(AlgoInput)`
///   but for the sake of convenience the `EntryPoint` trait provides a default implementation
///   of `apply` that delegates to `apply_str`, `apply_bytes`, or `apply_json` depending on
///   the variant of `AlgoInput`. The `DecodedEntryPoint` trait overrides the default `apply`
///   to provide a method that uses a deserialized associated type when calling `apply_decoded`.
///   This pattern is incredibly flexible, but adds boilerplate and still requires
///   converting output and error types back.
///
/// The `algo_entrypoint!` macro hides all that boilerplate code behind a single macro invocation.
///   `algo_entrypoint(type => your_fn)` wires up the boilerplate for calling `your_fn(type)`.
///   Additionally, you can use the macro as `algo_entrypoint(type)` which is equivalent to
///   `algo_entrypoint!(type => apply)`.
///
/// Use the following types:
///
/// - `&str` if your algorithm accepts text input
/// - `&[u8]` if your algorithm accepts binary input
/// - Any deserializeable type if your algorithm accepts JSON input
/// - `&JsonValue` is you want your algorithm to work directly with the typed JSON input
/// - `AlgoInput` if you want to work with the full enum of possible input types
///
/// In all cases, the return value of `your_fn` should be `Result<T, E>` where:
///
/// - `T` implements `Into<AlgoOutput>` which includes `String`, `Vec<u8>`, `JsonValue`, and boxed* serializeable types
/// - `E` implements `Into<Box<::std::error::Error>>` which includes `String` and all `Error` types
///
/// ** support for unboxed serializeable depends on specialization implemented behind the 'nightly' feature.*
///
/// # Examples
///
/// ## Text Input/Output
/// To set the entrypoint to a function that receives and returns text:
///
/// ```no_run
/// # #[macro_use] extern crate algorithmia;
/// # fn main() {}
/// # use algorithmia::prelude::*;
/// algo_entrypoint!(&str);
///
/// fn apply(input: &str) -> Result<String, String> {
///     unimplemented!()
/// }
/// ```
///
/// which generates:
///
/// ```ignore
/// #[derive(Default)]
/// pub struct Algo;
///
/// impl EntryPoint for Algo {
///     fn apply_str(&self, input: &str) -> Result<AlgoOutput, Box<::std::error::Error>> {
///         apply(input).map(AlgoOutput::from).map_err(|err| err.into())
///     }
/// }
///
/// fn apply(input: &str) -> Result<String, String> {
///     unimplemented!()
/// }
/// ```
///
/// ## Binary Input/Output
/// To set the entrypoint to a function that receives and returns binary data:
///
/// ```no_run
/// # #[macro_use] extern crate algorithmia;
/// # fn main() {}
/// # use algorithmia::prelude::*;
/// algo_entrypoint!(&[u8]);
///
/// fn apply(input: &[u8]) -> Result<Vec<u8>, String> {
///     unimplemented!()
/// }
/// ```
///
/// ## JSON Input/Output
/// To set the entrypoint to a function that receives and returns JSON data,
///   you can work directly with the `JsonValue`:
///
/// ```no_run
/// # #[macro_use] extern crate algorithmia;
/// # fn main() {}
/// # use algorithmia::prelude::*;
/// algo_entrypoint!(&JsonValue);
///
/// fn apply(input: &JsonValue) -> Result<JsonValue, String> {
///     unimplemented!()
/// }
/// ```
///
/// Although, often the preferred way to work with JSON is to automatically
///   deserialize into and serialize from a custom type.
///
/// ```ignore
/// # #[macro_use] extern crate algorithmia;
/// # fn main() {}
/// # use algorithmia::prelude::*;
/// #[derive(Deserialize)]
/// pub struct MyInput { corpus: String, msg: String }
///
/// #[derive(Serialize)]
/// pub struct MyOutput { probabilities: Vec<(String, f32)> }
///
/// algo_entrypoint!(MyInput);
///
/// fn apply(input: MyInput) -> Result<Box<MyOutput>, String> {
///     unimplemented!()
/// }
/// ```
///
/// Note: `Box` for serializeable output is currently required for lack of specialization.
///   The specialization implementation already exists behind the `nightly` feature.
///   Alternatively, you can return `AlgoOutput` via `AlgoOutput::from(&myOutput)`
///
/// The previous example expands into:
///
/// ```ignore
/// #[derive(Deserialize)]
/// pub struct MyInput { corpus: String, msg: String };
///
/// #[derive(Serialize)]
/// pub struct MyOutput { probabilities: Vec<(String, f32)> };
///
/// #[derive(Default)]
/// pub struct Algo;
///
/// impl DecodedEntryPoint for Algo {
///     type Input (String, String);
///     fn apply_decoded(&self, input: MyInput) -> Result<AlgoOutput, Box<::std::error::Error>> {
///         apply(input).map(AlgoOutput::from).map_err(|err| err.into())
///     }
/// }
///
/// fn apply(input: MyInput) -> Result<Box<MyOutput>, String> {
///     unimplemented!()
/// }
/// ```
///
/// ## Customizing `Default`
/// And finally, it is possible to provide a custom `Default` implementation
///   and pass that state into your method by prefixing `your_fn` with
///   the `Algo::` namespace.
///
/// ```no_run
/// # #[macro_use] extern crate algorithmia;
/// # fn main() {}
/// # use algorithmia::prelude::*;
/// pub struct Algo{ init_id: String }
///
/// algo_entrypoint!(&str => Algo::hello_text);
///
/// impl Algo {
///     fn hello_text(&self, input: &str) -> Result<String, String> {
///         unimplemented!()
///     }
/// }
///
/// impl Default for Algo {
///     fn default() -> Algo {
///         Algo { init_id: "foo".into() }
///     }
/// }
/// ```
#[macro_export]
macro_rules! algo_entrypoint {
    // Helpers for recursively implementing text/bytes/JsonValue/AlgoInput
    ($t:ty, $apply:ident, Algo::$method:ident) => {
        impl EntryPoint for Algo {
            fn $apply(&self, input: $t) -> ::std::result::Result<AlgoOutput, Box<::std::error::Error>> {
                self.$method(input).map(AlgoOutput::from).map_err(|err| err.into())
            }
        }
    };
    ($t:ty, $apply:ident, $p:path) => {
        #[derive(Default)] pub struct Algo;
        impl EntryPoint for Algo {
            fn $apply(&self, input: $t) -> ::std::result::Result<AlgoOutput, Box<::std::error::Error>> {
                $p(input).map(AlgoOutput::from).map_err(|err| err.into())
            }
        }
    };
    // Implement short-hand variants using free apply function
    (&str) => {
        algo_entrypoint!(&str => apply);
    };
    (&[u8]) => {
        algo_entrypoint!(&[u8] => apply);
    };
    (&JsonValue) => {
        algo_entrypoint!(&JsonValue => apply);
    };
    (AlgoInput) => {
        algo_entrypoint!(AlgoInput => apply);
    };
    ($t:ty) => {
        algo_entrypoint!($t => apply);
    };

    // Implement EntryPoint to call methods on `Algo`
    (&str => Algo::$i:ident) => {
        algo_entrypoint!(&str, apply_str, Algo::$i);
    };
    (&[u8] => Algo::$i:ident) => {
        algo_entrypoint!(&[u8], apply_bytes, Algo::$i);
    };
    (&JsonValue => Algo::$i:ident) => {
        algo_entrypoint!(&JsonValue, apply_json, Algo::$i);
    };
    (AlgoInput => Algo::$i:ident) => {
        algo_entrypoint!(AlgoInput, apply, Algo::$i);
    };
    ($t:ty => Algo::$i:ident) => {
        impl DecodedEntryPoint for Algo {
            type Input = $t;
            fn apply_bytes(&self, input: $t) -> ::std::result::Result<AlgoOutput, Box<::std::error::Error>> {
                self.$i(input).map(AlgoOutput::from).map_err(|err| err.into())
            }
        }
    };

    // Implement EntryPoint to call free functions
    (&str => $p:path) => {
        algo_entrypoint!(&str, apply_str, $p);
    };
    (&[u8] => $p:path) => {
        algo_entrypoint!(&[u8], apply_bytes, $p);
    };
    (&JsonValue => $p:path) => {
        algo_entrypoint!(&JsonValue, apply_json, $p);
    };
    (AlgoInput => $p:path) => {
        algo_entrypoint!(AlgoInput, apply, $p);
    };

    ($t:ty => $p:path) => {
        #[derive(Default)] pub struct Algo;
        impl DecodedEntryPoint for Algo {
            type Input = $t;
            fn apply_decoded(&self, input: $t) -> ::std::result::Result<AlgoOutput, Box<::std::error::Error>> {
                $p(input).map(AlgoOutput::from).map_err(|err| err.into())
            }
        }
    };
}

// Testing all the variants with unused code
mod test_str {
    use prelude::*;
    algo_entrypoint!(&str => hello_text);
    fn hello_text(_input: &str) -> Result<String, String> {
        unimplemented!()
    }
}

mod test_bytes {
    use prelude::*;
    algo_entrypoint!(&[u8] => hello_bytes);
    fn hello_bytes(_input: &[u8]) -> Result<Vec<u8>, String> {
        unimplemented!()
    }
}

mod test_json {
    use prelude::*;
    algo_entrypoint!(&JsonValue => hello_json);
    fn hello_json(_input: &JsonValue) -> Result<JsonValue, String> {
        unimplemented!()
    }
}

mod test_enum {
    use prelude::*;
    algo_entrypoint!(AlgoInput => hello_enum);
    fn hello_enum(_input: AlgoInput) -> Result<AlgoOutput, String> {
        unimplemented!()
    }
}

mod test_decode {
    use prelude::*;

    #[cfg_attr(feature="with-rustc-serialize", derive(RustcDecodable, RustcEncodable))]
    #[cfg_attr(feature="with-serde", derive(Deserialize, Serialize))]
    pub struct Custom {
        foo: String,
        bar: Vec<u32>,
        baz: bool,
    }
    algo_entrypoint!(Custom => hello_decoded);
    fn hello_decoded(_input: Custom) -> Result<Box<Custom>, String> {
        unimplemented!()
    }
}

mod test_shorthand_str {
    use prelude::*;
    algo_entrypoint!(&str => apply);
    fn apply(_input: &str) -> Result<String, String> {
        unimplemented!()
    }
}

mod test_shorthand_bytes {
    use prelude::*;
    algo_entrypoint!(&[u8]);
    fn apply(_input: &[u8]) -> Result<Vec<u8>, String> {
        unimplemented!()
    }
}

mod test_shorthand_json {
    use prelude::*;
    algo_entrypoint!(&JsonValue);
    fn apply(_input: &JsonValue) -> Result<JsonValue, String> {
        unimplemented!()
    }
}

mod test_shorthand_enum {
    use prelude::*;
    algo_entrypoint!(AlgoInput);
    fn apply(_input: AlgoInput) -> Result<AlgoOutput, String> {
        unimplemented!()
    }
}

mod test_shorthand_decode {
    use prelude::*;

    #[cfg_attr(feature="with-rustc-serialize", derive(RustcDecodable, RustcEncodable))]
    #[cfg_attr(feature="with-serde", derive(Deserialize, Serialize))]
    pub struct Custom {
        foo: String,
        bar: Vec<u32>,
        baz: bool,
    }
    algo_entrypoint!(Custom);
    fn apply(_input: Custom) -> Result<Box<Custom>, String> {
        unimplemented!()
    }
}
<commit_msg>Fix custom-default use of macro for decoded input<commit_after>/// Macro for implementing `Entrypoint` or `DecodedEntryPoint` boilerplate in an algorithm
///
/// Algorithmia support for Rust algorithms is hard-coded to call `Algo::apply(AlgoInput)`
///   but for the sake of convenience the `EntryPoint` trait provides a default implementation
///   of `apply` that delegates to `apply_str`, `apply_bytes`, or `apply_json` depending on
///   the variant of `AlgoInput`. The `DecodedEntryPoint` trait overrides the default `apply`
///   to provide a method that uses a deserialized associated type when calling `apply_decoded`.
///   This pattern is incredibly flexible, but adds boilerplate and still requires
///   converting output and error types back.
///
/// The `algo_entrypoint!` macro hides all that boilerplate code behind a single macro invocation.
///   `algo_entrypoint(type => your_fn)` wires up the boilerplate for calling `your_fn(type)`.
///   Additionally, you can use the macro as `algo_entrypoint(type)` which is equivalent to
///   `algo_entrypoint!(type => apply)`.
///
/// Use the following types:
///
/// - `&str` if your algorithm accepts text input
/// - `&[u8]` if your algorithm accepts binary input
/// - Any deserializeable type if your algorithm accepts JSON input
/// - `&JsonValue` is you want your algorithm to work directly with the typed JSON input
/// - `AlgoInput` if you want to work with the full enum of possible input types
///
/// In all cases, the return value of `your_fn` should be `Result<T, E>` where:
///
/// - `T` implements `Into<AlgoOutput>` which includes `String`, `Vec<u8>`, `JsonValue`, and boxed* serializeable types
/// - `E` implements `Into<Box<::std::error::Error>>` which includes `String` and all `Error` types
///
/// ** support for unboxed serializeable depends on specialization implemented behind the 'nightly' feature.*
///
/// # Examples
///
/// ## Text Input/Output
/// To set the entrypoint to a function that receives and returns text:
///
/// ```no_run
/// # #[macro_use] extern crate algorithmia;
/// # fn main() {}
/// # use algorithmia::prelude::*;
/// algo_entrypoint!(&str);
///
/// fn apply(input: &str) -> Result<String, String> {
///     unimplemented!()
/// }
/// ```
///
/// which generates:
///
/// ```ignore
/// #[derive(Default)]
/// pub struct Algo;
///
/// impl EntryPoint for Algo {
///     fn apply_str(&self, input: &str) -> Result<AlgoOutput, Box<::std::error::Error>> {
///         apply(input).map(AlgoOutput::from).map_err(|err| err.into())
///     }
/// }
///
/// fn apply(input: &str) -> Result<String, String> {
///     unimplemented!()
/// }
/// ```
///
/// ## Binary Input/Output
/// To set the entrypoint to a function that receives and returns binary data:
///
/// ```no_run
/// # #[macro_use] extern crate algorithmia;
/// # fn main() {}
/// # use algorithmia::prelude::*;
/// algo_entrypoint!(&[u8]);
///
/// fn apply(input: &[u8]) -> Result<Vec<u8>, String> {
///     unimplemented!()
/// }
/// ```
///
/// ## JSON Input/Output
/// To set the entrypoint to a function that receives and returns JSON data,
///   you can work directly with the `JsonValue`:
///
/// ```no_run
/// # #[macro_use] extern crate algorithmia;
/// # fn main() {}
/// # use algorithmia::prelude::*;
/// algo_entrypoint!(&JsonValue);
///
/// fn apply(input: &JsonValue) -> Result<JsonValue, String> {
///     unimplemented!()
/// }
/// ```
///
/// Although, often the preferred way to work with JSON is to automatically
///   deserialize into and serialize from a custom type.
///
/// ```ignore
/// # #[macro_use] extern crate algorithmia;
/// # fn main() {}
/// # use algorithmia::prelude::*;
/// #[derive(Deserialize)]
/// pub struct MyInput { corpus: String, msg: String }
///
/// #[derive(Serialize)]
/// pub struct MyOutput { probabilities: Vec<(String, f32)> }
///
/// algo_entrypoint!(MyInput);
///
/// fn apply(input: MyInput) -> Result<Box<MyOutput>, String> {
///     unimplemented!()
/// }
/// ```
///
/// Note: `Box` for serializeable output is currently required for lack of specialization.
///   The specialization implementation already exists behind the `nightly` feature.
///   Alternatively, you can return `AlgoOutput` via `AlgoOutput::from(&myOutput)`
///
/// The previous example expands into:
///
/// ```ignore
/// #[derive(Deserialize)]
/// pub struct MyInput { corpus: String, msg: String };
///
/// #[derive(Serialize)]
/// pub struct MyOutput { probabilities: Vec<(String, f32)> };
///
/// #[derive(Default)]
/// pub struct Algo;
///
/// impl DecodedEntryPoint for Algo {
///     type Input (String, String);
///     fn apply_decoded(&self, input: MyInput) -> Result<AlgoOutput, Box<::std::error::Error>> {
///         apply(input).map(AlgoOutput::from).map_err(|err| err.into())
///     }
/// }
///
/// fn apply(input: MyInput) -> Result<Box<MyOutput>, String> {
///     unimplemented!()
/// }
/// ```
///
/// ## Customizing `Default`
/// And finally, it is possible to provide a custom `Default` implementation
///   and pass that state into your method by prefixing `your_fn` with
///   the `Algo::` namespace.
///
/// ```no_run
/// # #[macro_use] extern crate algorithmia;
/// # fn main() {}
/// # use algorithmia::prelude::*;
/// pub struct Algo{ init_id: String }
///
/// algo_entrypoint!(&str => Algo::hello_text);
///
/// impl Algo {
///     fn hello_text(&self, input: &str) -> Result<String, String> {
///         unimplemented!()
///     }
/// }
///
/// impl Default for Algo {
///     fn default() -> Algo {
///         Algo { init_id: "foo".into() }
///     }
/// }
/// ```
#[macro_export]
macro_rules! algo_entrypoint {
    // Helpers for recursively implementing text/bytes/JsonValue/AlgoInput
    ($t:ty, $apply:ident, Algo::$method:ident) => {
        impl EntryPoint for Algo {
            fn $apply(&self, input: $t) -> ::std::result::Result<AlgoOutput, Box<::std::error::Error>> {
                self.$method(input).map(AlgoOutput::from).map_err(|err| err.into())
            }
        }
    };
    ($t:ty, $apply:ident, $p:path) => {
        #[derive(Default)] pub struct Algo;
        impl EntryPoint for Algo {
            fn $apply(&self, input: $t) -> ::std::result::Result<AlgoOutput, Box<::std::error::Error>> {
                $p(input).map(AlgoOutput::from).map_err(|err| err.into())
            }
        }
    };
    // Implement short-hand variants using free apply function
    (&str) => {
        algo_entrypoint!(&str => apply);
    };
    (&[u8]) => {
        algo_entrypoint!(&[u8] => apply);
    };
    (&JsonValue) => {
        algo_entrypoint!(&JsonValue => apply);
    };
    (AlgoInput) => {
        algo_entrypoint!(AlgoInput => apply);
    };
    ($t:ty) => {
        algo_entrypoint!($t => apply);
    };

    // Implement EntryPoint to call methods on `Algo`
    (&str => Algo::$i:ident) => {
        algo_entrypoint!(&str, apply_str, Algo::$i);
    };
    (&[u8] => Algo::$i:ident) => {
        algo_entrypoint!(&[u8], apply_bytes, Algo::$i);
    };
    (&JsonValue => Algo::$i:ident) => {
        algo_entrypoint!(&JsonValue, apply_json, Algo::$i);
    };
    (AlgoInput => Algo::$i:ident) => {
        algo_entrypoint!(AlgoInput, apply, Algo::$i);
    };
    ($t:ty => Algo::$i:ident) => {
        impl DecodedEntryPoint for Algo {
            type Input = $t;
            fn apply_decoded(&self, input: $t) -> ::std::result::Result<AlgoOutput, Box<::std::error::Error>> {
                self.$i(input).map(AlgoOutput::from).map_err(|err| err.into())
            }
        }
    };

    // Implement EntryPoint to call free functions
    (&str => $p:path) => {
        algo_entrypoint!(&str, apply_str, $p);
    };
    (&[u8] => $p:path) => {
        algo_entrypoint!(&[u8], apply_bytes, $p);
    };
    (&JsonValue => $p:path) => {
        algo_entrypoint!(&JsonValue, apply_json, $p);
    };
    (AlgoInput => $p:path) => {
        algo_entrypoint!(AlgoInput, apply, $p);
    };

    ($t:ty => $p:path) => {
        #[derive(Default)] pub struct Algo;
        impl DecodedEntryPoint for Algo {
            type Input = $t;
            fn apply_decoded(&self, input: $t) -> ::std::result::Result<AlgoOutput, Box<::std::error::Error>> {
                $p(input).map(AlgoOutput::from).map_err(|err| err.into())
            }
        }
    };
}

// Testing all the variants with unused code
mod test_str {
    use prelude::*;
    algo_entrypoint!(&str => hello_text);
    fn hello_text(_input: &str) -> Result<String, String> {
        unimplemented!()
    }
}

mod test_bytes {
    use prelude::*;
    algo_entrypoint!(&[u8] => hello_bytes);
    fn hello_bytes(_input: &[u8]) -> Result<Vec<u8>, String> {
        unimplemented!()
    }
}

mod test_json {
    use prelude::*;
    algo_entrypoint!(&JsonValue => hello_json);
    fn hello_json(_input: &JsonValue) -> Result<JsonValue, String> {
        unimplemented!()
    }
}

mod test_enum {
    use prelude::*;
    algo_entrypoint!(AlgoInput => hello_enum);
    fn hello_enum(_input: AlgoInput) -> Result<AlgoOutput, String> {
        unimplemented!()
    }
}

mod test_decode {
    use prelude::*;

    #[cfg_attr(feature="with-rustc-serialize", derive(RustcDecodable, RustcEncodable))]
    #[cfg_attr(feature="with-serde", derive(Deserialize, Serialize))]
    pub struct Custom {
        foo: String,
        bar: Vec<u32>,
        baz: bool,
    }
    algo_entrypoint!(Custom => hello_decoded);
    fn hello_decoded(_input: Custom) -> Result<Box<Custom>, String> {
        unimplemented!()
    }
}

mod test_decode_with_default {
    use prelude::*;

    pub struct Algo { _magic: u32 }

    #[cfg_attr(feature="with-rustc-serialize", derive(RustcDecodable, RustcEncodable))]
    #[cfg_attr(feature="with-serde", derive(Deserialize, Serialize))]
    pub struct Custom {
        foo: String,
        bar: Vec<u32>,
        baz: bool,
    }
    algo_entrypoint!(Custom => Algo::hello_decoded);
    impl Algo {
        fn hello_decoded(&self, _input: Custom) -> Result<Box<Custom>, String> {
            unimplemented!()
        }
    }

    impl Default for Algo {
        fn default() -> Self {
            Algo { _magic: 42 }
        }
    }
}

mod test_shorthand_str {
    use prelude::*;
    algo_entrypoint!(&str => apply);
    fn apply(_input: &str) -> Result<String, String> {
        unimplemented!()
    }
}

mod test_shorthand_bytes {
    use prelude::*;
    algo_entrypoint!(&[u8]);
    fn apply(_input: &[u8]) -> Result<Vec<u8>, String> {
        unimplemented!()
    }
}

mod test_shorthand_json {
    use prelude::*;
    algo_entrypoint!(&JsonValue);
    fn apply(_input: &JsonValue) -> Result<JsonValue, String> {
        unimplemented!()
    }
}

mod test_shorthand_enum {
    use prelude::*;
    algo_entrypoint!(AlgoInput);
    fn apply(_input: AlgoInput) -> Result<AlgoOutput, String> {
        unimplemented!()
    }
}

mod test_shorthand_decode {
    use prelude::*;

    #[cfg_attr(feature="with-rustc-serialize", derive(RustcDecodable, RustcEncodable))]
    #[cfg_attr(feature="with-serde", derive(Deserialize, Serialize))]
    pub struct Custom {
        foo: String,
        bar: Vec<u32>,
        baz: bool,
    }
    algo_entrypoint!(Custom);
    fn apply(_input: Custom) -> Result<Box<Custom>, String> {
        unimplemented!()
    }
}
<|endoftext|>


<commit_before>//#![feature(trace_macros)]
#![feature(test)]
extern crate test;

#[macro_use]
extern crate nom;

use nom::{alphanumeric, recognize_float};

use test::Bencher;

use std::str;
use std::collections::HashMap;

#[derive(Debug, PartialEq)]
pub enum JsonValue {
  Str(String),
  Boolean(bool),
  Num(f32),
  Array(Vec<JsonValue>),
  Object(HashMap<String, JsonValue>),
}

named!(float<f32>, flat_map!(recognize_float, parse_to!(f32)));

//FIXME: verify how json strings are formatted
named!(
  string<&str>,
  delimited!(
    char!('\"'),
    map_res!(
      escaped!(call!(alphanumeric), '\\', one_of!("\"n\\")),
      str::from_utf8
    ),
    //map_res!(escaped!(take_while1!(is_alphanumeric), '\\', one_of!("\"n\\")), str::from_utf8),
    char!('\"')
  )
);

named!(boolean<bool>,
  alt!(
    value!(false, tag!("false")) |
    value!(true, tag!("true"))
  )
);

named!(
  array<Vec<JsonValue>>,
  ws!(delimited!(
    char!('['),
    separated_list!(char!(','), value),
    char!(']')
  ))
);

named!(
  key_value<(&str, JsonValue)>,
  ws!(separated_pair!(string, char!(':'), value))
);

named!(
  hash<HashMap<String, JsonValue>>,
  ws!(map!(
    delimited!(
      char!('{'),
      separated_list!(char!(','), key_value),
      char!('}')
    ),
    |tuple_vec| tuple_vec
      .into_iter()
      .map(|(k, v)| (String::from(k), v))
      .collect()
  ))
);

named!(
  value<JsonValue>,
  ws!(alt!(
      hash    => { |h| JsonValue::Object(h)            } |
      array   => { |v| JsonValue::Array(v)             } |
      string  => { |s| JsonValue::Str(String::from(s)) } |
      float   => { |f| JsonValue::Num(f)               } |
      boolean => { |b| JsonValue::Boolean(b)           }
    ))
);

#[bench]
fn json_bench(b: &mut Bencher) {
  let data = &b"  { \"a\"\t: 42,
  \"b\": [ \"x\", \"y\", 12 ] ,
  \"c\": { \"hello\" : \"world\"
  }
  }  \0";

  //println!("data:\n{:?}", value(&data[..]));
  b.iter(|| value(&data[..]).unwrap());
}

#[bench]
fn recognize_float_bytes(b: &mut Bencher) {
  use nom::recognize_float;
  b.iter(|| recognize_float(&b"-1.234E-12"[..]));
}

#[bench]
fn recognize_float_str(b: &mut Bencher) {
  use nom::recognize_float;
  b.iter(|| recognize_float("-1.234E-12"));
}

#[bench]
fn float_bytes(b: &mut Bencher) {
  use nom::float;
  b.iter(|| float(&b"-1.234E-12"[..]));
}

#[bench]
fn float_str(b: &mut Bencher) {
  use nom::float_s;
  b.iter(|| float_s("-1.234E-12"));
}
<commit_msg>Format JSON benchmark code<commit_after>//#![feature(trace_macros)]
#![feature(test)]
extern crate test;

#[macro_use]
extern crate nom;

use nom::{alphanumeric, recognize_float};

use test::Bencher;

use std::str;
use std::collections::HashMap;

#[derive(Debug, PartialEq)]
pub enum JsonValue {
  Str(String),
  Boolean(bool),
  Num(f32),
  Array(Vec<JsonValue>),
  Object(HashMap<String, JsonValue>),
}

named!(float<f32>, flat_map!(recognize_float, parse_to!(f32)));

//FIXME: verify how json strings are formatted
named!(
  string<&str>,
  delimited!(
    char!('\"'),
    map_res!(
      escaped!(call!(alphanumeric), '\\', one_of!("\"n\\")),
      str::from_utf8
    ),
    //map_res!(escaped!(take_while1!(is_alphanumeric), '\\', one_of!("\"n\\")), str::from_utf8),
    char!('\"')
  )
);

named!(
  boolean<bool>,
  alt!(value!(false, tag!("false")) | value!(true, tag!("true")))
);

named!(
  array<Vec<JsonValue>>,
  ws!(delimited!(
    char!('['),
    separated_list!(char!(','), value),
    char!(']')
  ))
);

named!(
  key_value<(&str, JsonValue)>,
  ws!(separated_pair!(string, char!(':'), value))
);

named!(
  hash<HashMap<String, JsonValue>>,
  ws!(map!(
    delimited!(
      char!('{'),
      separated_list!(char!(','), key_value),
      char!('}')
    ),
    |tuple_vec| tuple_vec
      .into_iter()
      .map(|(k, v)| (String::from(k), v))
      .collect()
  ))
);

named!(
  value<JsonValue>,
  ws!(alt!(
      hash    => { |h| JsonValue::Object(h)            } |
      array   => { |v| JsonValue::Array(v)             } |
      string  => { |s| JsonValue::Str(String::from(s)) } |
      float   => { |f| JsonValue::Num(f)               } |
      boolean => { |b| JsonValue::Boolean(b)           }
    ))
);

#[bench]
fn json_bench(b: &mut Bencher) {
  let data = &b"  { \"a\"\t: 42,
  \"b\": [ \"x\", \"y\", 12 ] ,
  \"c\": { \"hello\" : \"world\"
  }
  }  \0";

  //println!("data:\n{:?}", value(&data[..]));
  b.iter(|| value(&data[..]).unwrap());
}

#[bench]
fn recognize_float_bytes(b: &mut Bencher) {
  use nom::recognize_float;
  b.iter(|| recognize_float(&b"-1.234E-12"[..]));
}

#[bench]
fn recognize_float_str(b: &mut Bencher) {
  use nom::recognize_float;
  b.iter(|| recognize_float("-1.234E-12"));
}

#[bench]
fn float_bytes(b: &mut Bencher) {
  use nom::float;
  b.iter(|| float(&b"-1.234E-12"[..]));
}

#[bench]
fn float_str(b: &mut Bencher) {
  use nom::float_s;
  b.iter(|| float_s("-1.234E-12"));
}
<|endoftext|>


<commit_before>
use {
    AddColor,
    AddEllipse,
    AddImage,
    AddPolygon,
    AddRectangle,
    AddTween,
    Borrowed,
    ColorContext,
    EllipseContext,
    Field,
    Image,
    ImageRectangleContext,
    Matrix2d,
    PolygonContext,
    RectangleContext,
    TweenContext,
    Value,
    View,
};
use vecmath::{
    identity,
};
use internal::{
    CanTransform,
    HasTransform,
};

/// Drawing 2d context.
pub struct Context<'a> {
    /// Base/original transformation.
    pub base: Field<'a, Matrix2d>,
    /// Current transformation.
    pub transform: Field<'a, Matrix2d>,
}

impl<'a> HasTransform<'a, Matrix2d> for Context<'a> {
    #[inline(always)]
    fn get_transform(&'a self) -> &'a Matrix2d {
        self.transform.get()
    }
}

impl<'a> CanTransform<'a, Context<'a>, Matrix2d> for Context<'a> {
    #[inline(always)]
    fn transform(&'a self, value: Matrix2d) -> Context<'a> {
        Context {
            base: Borrowed(self.base.get()),
            transform: Value(value),
        }
    }
}

impl<'a> Context<'a> {
    /// Creates a new drawing context.
    pub fn new() -> Context {
        Context {
            base:  Value([1.0, 0.0, 0.0,
                          0.0, 1.0, 0.0]),
            transform: Value([1.0, 0.0, 0.0,
                          0.0, 1.0, 0.0]),
        }
    }
}

#[test]
fn test_context() {
    let c = Context::new();
    {
        let d = c.trans(20.0, 40.0);
        let d = d.trans(10.0, 10.0);
        assert_eq!(d.transform.get()[2], 30.0);
        assert_eq!(d.transform.get()[5], 50.0);
    }
    assert_eq!(c.transform.get()[2], 0.0);
    assert_eq!(c.transform.get()[5], 0.0);

    let c = c.rot_deg(90.0);
    assert!((c.transform.get()[0] - 0.0).abs() < 0.00001);
    assert!((c.transform.get()[1] - 1.0).abs() < 0.00001);
}

#[test]
fn test_scale() {
    let c = Context::new();
    let c = c.scale(2.0, 3.0);
    assert!((c.transform.get()[0] - 2.0).abs() < 0.00001);
    assert!((c.transform.get()[4] - 3.0).abs() < 0.00001);
}

impl<'a> AddRectangle<'a, RectangleContext<'a>> for Context<'a> {
    #[inline(always)]
    fn rect(&'a self, x: f64, y: f64, w: f64, h: f64) -> RectangleContext<'a> {
        RectangleContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            rect: Value([x, y, w, h]),
        }
    }
}

#[test]
fn test_rect() {
    let c = Context::new();
    let d = c.rect(0.0, 0.0, 100.0, 50.0);
    assert_eq!(d.rect.get()[2], 100.0);
}

impl<'a> AddColor<'a, ColorContext<'a>> for Context<'a> {
    #[inline(always)]
    fn rgba(&'a self, r: f32, g: f32, b: f32, a: f32) -> ColorContext<'a> {
        ColorContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            color: Value([r, g, b, a]),
        }
    }
}

#[test]
fn test_rgba() {
    let c = Context::new();
    let d: ColorContext = c.rgba(1.0, 0.0, 0.0, 1.0);
    assert_eq!(d.color.get()[0], 1.0);
}

impl<'a> AddEllipse<'a, EllipseContext<'a>> for Context<'a> {
    #[inline(always)]
    fn ellipse(&'a self, x: f64, y: f64, w: f64, h: f64) -> EllipseContext<'a> {
        EllipseContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            rect: Value([x, y, w, h]),
        }
    }
}

#[test]
fn test_ellipse() {
    let c = Context::new();
    let d: EllipseContext = c.ellipse(0.0, 0.0, 100.0, 100.0);
    assert_eq!(d.rect.get()[2], 100.0);
}

impl<'a> AddPolygon<'a, PolygonContext<'a>> for Context<'a> {
    #[inline(always)]
    fn polygon(&'a self, polygon: &'a [f64]) -> PolygonContext<'a> {
        PolygonContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            polygon: Value(polygon),
        }
    }
}

impl<'a> View<'a> for Context<'a> {
    #[inline(always)]
    fn view(&'a self) -> Context<'a> {
        Context {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.base.get()),
        }
    }

    #[inline(always)]
    fn reset(&'a self) -> Context<'a> {
        Context {
            base: Borrowed(self.base.get()),
            transform: Value(identity()),
        }
    }

    #[inline(always)]
    fn store_view(&'a self) -> Context<'a> {
        Context {
            base: Borrowed(self.transform.get()),
            transform: Borrowed(self.transform.get()),
        }
    }
}

impl<'a> AddImage<'a, ImageRectangleContext<'a>> for Context<'a> {
    #[inline(always)]
    fn image(&'a self, image: Image) -> ImageRectangleContext<'a> {
        ImageRectangleContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            rect: Value([0.0, 0.0, image.source_rect[2] as f64, image.source_rect[3] as f64]),
            image: Value(image),
        }
    }
}

impl<'a> AddTween<'a, TweenContext<'a>> for Context<'a> {
    #[inline(always)]
    fn lerp(&'a self, tween_factor: f64) -> TweenContext<'a> {
        TweenContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            tween_factor: Value(tween_factor),
        }
    }
}

<commit_msg>Repaired test cases.<commit_after>
use {
    AddColor,
    AddEllipse,
    AddImage,
    AddPolygon,
    AddRectangle,
    AddTween,
    Borrowed,
    ColorContext,
    EllipseContext,
    Field,
    Image,
    ImageRectangleContext,
    Matrix2d,
    PolygonContext,
    RectangleContext,
    TweenContext,
    Value,
    View,
};
use vecmath::{
    identity,
};
use internal::{
    CanTransform,
    HasTransform,
};

/// Drawing 2d context.
pub struct Context<'a> {
    /// Base/original transformation.
    pub base: Field<'a, Matrix2d>,
    /// Current transformation.
    pub transform: Field<'a, Matrix2d>,
}

impl<'a> HasTransform<'a, Matrix2d> for Context<'a> {
    #[inline(always)]
    fn get_transform(&'a self) -> &'a Matrix2d {
        self.transform.get()
    }
}

impl<'a> CanTransform<'a, Context<'a>, Matrix2d> for Context<'a> {
    #[inline(always)]
    fn transform(&'a self, value: Matrix2d) -> Context<'a> {
        Context {
            base: Borrowed(self.base.get()),
            transform: Value(value),
        }
    }
}

impl<'a> Context<'a> {
    /// Creates a new drawing context.
    pub fn new() -> Context {
        Context {
            base:  Value([1.0, 0.0, 0.0,
                          0.0, 1.0, 0.0]),
            transform: Value([1.0, 0.0, 0.0,
                          0.0, 1.0, 0.0]),
        }
    }
}

#[test]
fn test_context() {
    use RelativeTransform2d;

    let c = Context::new();
    {
        let d = c.trans(20.0, 40.0);
        let d = d.trans(10.0, 10.0);
        assert_eq!(d.transform.get()[2], 30.0);
        assert_eq!(d.transform.get()[5], 50.0);
    }
    assert_eq!(c.transform.get()[2], 0.0);
    assert_eq!(c.transform.get()[5], 0.0);

    let c = c.rot_deg(90.0);
    assert!((c.transform.get()[0] - 0.0).abs() < 0.00001);
    assert!((c.transform.get()[1] + 1.0).abs() < 0.00001);
}

#[test]
fn test_scale() {
    use RelativeTransform2d;

    let c = Context::new();
    let c = c.scale(2.0, 3.0);
    assert!((c.transform.get()[0] - 2.0).abs() < 0.00001);
    assert!((c.transform.get()[4] - 3.0).abs() < 0.00001);
}

impl<'a> AddRectangle<'a, RectangleContext<'a>> for Context<'a> {
    #[inline(always)]
    fn rect(&'a self, x: f64, y: f64, w: f64, h: f64) -> RectangleContext<'a> {
        RectangleContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            rect: Value([x, y, w, h]),
        }
    }
}

#[test]
fn test_rect() {
    let c = Context::new();
    let d = c.rect(0.0, 0.0, 100.0, 50.0);
    assert_eq!(d.rect.get()[2], 100.0);
}

impl<'a> AddColor<'a, ColorContext<'a>> for Context<'a> {
    #[inline(always)]
    fn rgba(&'a self, r: f32, g: f32, b: f32, a: f32) -> ColorContext<'a> {
        ColorContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            color: Value([r, g, b, a]),
        }
    }
}

#[test]
fn test_rgba() {
    let c = Context::new();
    let d: ColorContext = c.rgba(1.0, 0.0, 0.0, 1.0);
    assert_eq!(d.color.get()[0], 1.0);
}

impl<'a> AddEllipse<'a, EllipseContext<'a>> for Context<'a> {
    #[inline(always)]
    fn ellipse(&'a self, x: f64, y: f64, w: f64, h: f64) -> EllipseContext<'a> {
        EllipseContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            rect: Value([x, y, w, h]),
        }
    }
}

#[test]
fn test_ellipse() {
    let c = Context::new();
    let d: EllipseContext = c.ellipse(0.0, 0.0, 100.0, 100.0);
    assert_eq!(d.rect.get()[2], 100.0);
}

impl<'a> AddPolygon<'a, PolygonContext<'a>> for Context<'a> {
    #[inline(always)]
    fn polygon(&'a self, polygon: &'a [f64]) -> PolygonContext<'a> {
        PolygonContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            polygon: Value(polygon),
        }
    }
}

impl<'a> View<'a> for Context<'a> {
    #[inline(always)]
    fn view(&'a self) -> Context<'a> {
        Context {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.base.get()),
        }
    }

    #[inline(always)]
    fn reset(&'a self) -> Context<'a> {
        Context {
            base: Borrowed(self.base.get()),
            transform: Value(identity()),
        }
    }

    #[inline(always)]
    fn store_view(&'a self) -> Context<'a> {
        Context {
            base: Borrowed(self.transform.get()),
            transform: Borrowed(self.transform.get()),
        }
    }
}

impl<'a> AddImage<'a, ImageRectangleContext<'a>> for Context<'a> {
    #[inline(always)]
    fn image(&'a self, image: Image) -> ImageRectangleContext<'a> {
        ImageRectangleContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            rect: Value([0.0, 0.0, image.source_rect[2] as f64, image.source_rect[3] as f64]),
            image: Value(image),
        }
    }
}

impl<'a> AddTween<'a, TweenContext<'a>> for Context<'a> {
    #[inline(always)]
    fn lerp(&'a self, tween_factor: f64) -> TweenContext<'a> {
        TweenContext {
            base: Borrowed(self.base.get()),
            transform: Borrowed(self.transform.get()),
            tween_factor: Value(tween_factor),
        }
    }
}

<|endoftext|>


<commit_before>use gl;
use gl::types::*;
use types::{Color, Viewport, GLError};
use buffer::{ArrayBufferBinder, ElementArrayBufferBinder};
use program::{ProgramBinder, ProgramAttrib};
use framebuffer::FramebufferBinder;
use renderbuffer::RenderbufferBinder;
use texture_units::{TextureUnits};

pub struct Context {
    pub array_buffer: ArrayBufferBinder,
    pub element_array_buffer: ElementArrayBufferBinder,
    pub program: ProgramBinder,
    pub framebuffer: FramebufferBinder,
    pub renderbuffer: RenderbufferBinder,
    pub tex_units: TextureUnits
}

impl Context {
    pub unsafe fn current_context() -> Self {
        Context {
            array_buffer: ArrayBufferBinder,
            element_array_buffer: ElementArrayBufferBinder,
            program: ProgramBinder,
            framebuffer: FramebufferBinder,
            renderbuffer: RenderbufferBinder,
            tex_units: TextureUnits::current()
        }
    }

    pub fn clear_color(&mut self, color: Color) {
        unsafe {
            gl::ClearColor(color.r, color.g, color.b, color.a);
        }
    }

    pub fn enable_vertex_attrib_array(&self, attrib: ProgramAttrib) {
        unsafe {
            gl::EnableVertexAttribArray(attrib.gl_index);
            dbg_gl_error! {
                GLError::InvalidValue => "`index` is >= GL_MAX_VERTEX_ATTRIBS",
                _ => "Unknown error"
            }
        }
    }

    pub fn viewport(&self, viewport: Viewport) {
        unsafe {
            gl::Viewport(viewport.x as GLint,
                         viewport.y as GLint,
                         viewport.width as GLsizei,
                         viewport.height as GLsizei);
            dbg_gl_sanity_check! {
                GLError::InvalidValue => "`width` or `height` is negative",
                _ => "Unknown error"
            }
        }
    }

    pub fn get_error() -> Option<GLError> {
        unsafe {
            match gl::GetError() {
                gl::INVALID_ENUM =>
                    Some(GLError::InvalidEnum),
                gl::INVALID_VALUE =>
                    Some(GLError::InvalidValue),
                gl::INVALID_OPERATION =>
                    Some(GLError::InvalidOperation),
                gl::INVALID_FRAMEBUFFER_OPERATION =>
                    Some(GLError::InvalidFramebufferOperation),
                gl::OUT_OF_MEMORY =>
                    Some(GLError::OutOfMemory),
                _ =>
                    None
            }
        }
    }
}

#[macro_export]
macro_rules! bind_array_buffer {
    ($gl:expr, $buffer:expr) => {
        $gl.array_buffer.bind($buffer)
    }
}

#[macro_export]
macro_rules! bind_element_array_buffer {
    ($gl:expr, $buffer:expr) => {
        $gl.element_array_buffer.bind($buffer)
    }
}

#[macro_export]
macro_rules! use_program {
    ($gl:expr, $program:expr) => {
        $gl.program.bind($program)
    }
}

#[macro_export]
macro_rules! bind_framebuffer {
    ($gl:expr, $fbo:expr) => {
        $gl.framebuffer.bind($fbo)
    }
}

// HACK: Workaround for issue described here:
// https://www.reddit.com/r/rust/comments/339yj3/tuple_indexing_in_a_macro/cqiyv4n
#[macro_export]
macro_rules! _glitter_expr {
    ($x:expr) => ($x)
}

#[macro_export]
macro_rules! active_texture {
    ($gl:expr, $idx:tt) => {
        _glitter_expr!($gl.tex_units.$idx.active())
    }
}

#[macro_export]
macro_rules! active_texture_n {
    ($gl:expr, $idx:expr) => {
        $gl.tex_units.nth_unit($idx).active()
    }
}
<commit_msg>Add `bind_renderbuffer!` macro<commit_after>use gl;
use gl::types::*;
use types::{Color, Viewport, GLError};
use buffer::{ArrayBufferBinder, ElementArrayBufferBinder};
use program::{ProgramBinder, ProgramAttrib};
use framebuffer::FramebufferBinder;
use renderbuffer::RenderbufferBinder;
use texture_units::{TextureUnits};

pub struct Context {
    pub array_buffer: ArrayBufferBinder,
    pub element_array_buffer: ElementArrayBufferBinder,
    pub program: ProgramBinder,
    pub framebuffer: FramebufferBinder,
    pub renderbuffer: RenderbufferBinder,
    pub tex_units: TextureUnits
}

impl Context {
    pub unsafe fn current_context() -> Self {
        Context {
            array_buffer: ArrayBufferBinder,
            element_array_buffer: ElementArrayBufferBinder,
            program: ProgramBinder,
            framebuffer: FramebufferBinder,
            renderbuffer: RenderbufferBinder,
            tex_units: TextureUnits::current()
        }
    }

    pub fn clear_color(&mut self, color: Color) {
        unsafe {
            gl::ClearColor(color.r, color.g, color.b, color.a);
        }
    }

    pub fn enable_vertex_attrib_array(&self, attrib: ProgramAttrib) {
        unsafe {
            gl::EnableVertexAttribArray(attrib.gl_index);
            dbg_gl_error! {
                GLError::InvalidValue => "`index` is >= GL_MAX_VERTEX_ATTRIBS",
                _ => "Unknown error"
            }
        }
    }

    pub fn viewport(&self, viewport: Viewport) {
        unsafe {
            gl::Viewport(viewport.x as GLint,
                         viewport.y as GLint,
                         viewport.width as GLsizei,
                         viewport.height as GLsizei);
            dbg_gl_sanity_check! {
                GLError::InvalidValue => "`width` or `height` is negative",
                _ => "Unknown error"
            }
        }
    }

    pub fn get_error() -> Option<GLError> {
        unsafe {
            match gl::GetError() {
                gl::INVALID_ENUM =>
                    Some(GLError::InvalidEnum),
                gl::INVALID_VALUE =>
                    Some(GLError::InvalidValue),
                gl::INVALID_OPERATION =>
                    Some(GLError::InvalidOperation),
                gl::INVALID_FRAMEBUFFER_OPERATION =>
                    Some(GLError::InvalidFramebufferOperation),
                gl::OUT_OF_MEMORY =>
                    Some(GLError::OutOfMemory),
                _ =>
                    None
            }
        }
    }
}

#[macro_export]
macro_rules! bind_array_buffer {
    ($gl:expr, $buffer:expr) => {
        $gl.array_buffer.bind($buffer)
    }
}

#[macro_export]
macro_rules! bind_element_array_buffer {
    ($gl:expr, $buffer:expr) => {
        $gl.element_array_buffer.bind($buffer)
    }
}

#[macro_export]
macro_rules! use_program {
    ($gl:expr, $program:expr) => {
        $gl.program.bind($program)
    }
}

#[macro_export]
macro_rules! bind_framebuffer {
    ($gl:expr, $fbo:expr) => {
        $gl.framebuffer.bind($fbo)
    }
}

#[macro_export]
macro_rules! bind_renderbuffer {
    ($gl:expr, $renderbuffer:expr) => {
        $gl.renderbuffer.bind($renderbuffer)
    }
}

// HACK: Workaround for issue described here:
// https://www.reddit.com/r/rust/comments/339yj3/tuple_indexing_in_a_macro/cqiyv4n
#[macro_export]
macro_rules! _glitter_expr {
    ($x:expr) => ($x)
}

#[macro_export]
macro_rules! active_texture {
    ($gl:expr, $idx:tt) => {
        _glitter_expr!($gl.tex_units.$idx.active())
    }
}

#[macro_export]
macro_rules! active_texture_n {
    ($gl:expr, $idx:expr) => {
        $gl.tex_units.nth_unit($idx).active()
    }
}
<|endoftext|>


<commit_before>// Copyright:: Copyright (c) 2015-2016 The Habitat Maintainers
//
// The terms of the Evaluation Agreement (Habitat) between Chef Software Inc.
// and the party accessing this file ("Licensee") apply to Licensee's use of
// the Software until such time that the Software is made available under an
// open source license such as the Apache 2.0 License.

/// Default Depot URL
pub const DEFAULT_DEPOT_URL: &'static str = "http://willem.habitat.sh:9636/v1/depot";

/// Default Depot URL environment variable
pub const DEPOT_URL_ENVVAR: &'static str = "HAB_DEPOT_URL";
<commit_msg>[hab] Add `hab studio` subcommand.<commit_after>// Copyright:: Copyright (c) 2015-2016 The Habitat Maintainers
//
// The terms of the Evaluation Agreement (Habitat) between Chef Software Inc.
// and the party accessing this file ("Licensee") apply to Licensee's use of
// the Software until such time that the Software is made available under an
// open source license such as the Apache 2.0 License.

use env as henv;

/// Default Depot URL
pub const DEFAULT_DEPOT_URL: &'static str = "http://willem.habitat.sh:9636/v1/depot";

/// Default Depot URL environment variable
pub const DEPOT_URL_ENVVAR: &'static str = "HAB_DEPOT_URL";

pub fn default_depot_url() -> String {
    match henv::var(DEPOT_URL_ENVVAR) {
        Ok(val) => val,
        Err(_) => DEFAULT_DEPOT_URL.to_string(),
    }
}
<|endoftext|>


<commit_before>use base::{
    AbstractCFTypeRef,
    Boolean,
    CFAllocatorRef,
    CFIndex,
    CFTypeID,
    CFTypeRef,
    CFWrapper,
    kCFAllocatorDefault
};
use libc::{c_int, c_void};

pub type CFNumberType = u32;

// members of enum CFNumberType
const kCFNumberSInt8Type:     CFNumberType = 1;
const kCFNumberSInt16Type:    CFNumberType = 2;
const kCFNumberSInt32Type:    CFNumberType = 3;
const kCFNumberSInt64Type:    CFNumberType = 4;
const kCFNumberFloat32Type:   CFNumberType = 5;
const kCFNumberFloat64Type:   CFNumberType = 6;
const kCFNumberCharType:      CFNumberType = 7;
const kCFNumberShortType:     CFNumberType = 8;
const kCFNumberIntType:       CFNumberType = 9;
const kCFNumberLongType:      CFNumberType = 10;
const kCFNumberLongLongType:  CFNumberType = 11;
const kCFNumberFloatType:     CFNumberType = 12;
const kCFNumberDoubleType:    CFNumberType = 13;
const kCFNumberCFIndexType:   CFNumberType = 14;
const kCFNumberNSIntegerType: CFNumberType = 15;
const kCFNumberCGFloatType:   CFNumberType = 16;
const kCFNumberMaxType:       CFNumberType = 16;

struct __CFNumber { private: () }
pub type CFNumberRef = *__CFNumber;

pub impl CFNumberRef : AbstractCFTypeRef {
    pure fn as_type_ref(&self) -> CFTypeRef { *self as CFTypeRef }

    static pure fn type_id() -> CFTypeID {
        unsafe {
            CFNumberGetTypeID()
        }
    }
}

pub type CFNumber = CFWrapper<CFNumberRef, (), ()>;

pub impl CFNumber {
    static fn new<T:Copy ConvertibleToCFNumber>(n: T) -> CFNumber {
        unsafe {
            let objref = CFNumberCreate(kCFAllocatorDefault,
                                        n.cf_number_type(),
                                        cast::transmute(&n));
            CFWrapper::wrap_owned(objref)
        }
    }

    pure fn to_i8() -> i8 {
        let ty = kCFNumberSInt8Type;
        assert self.has_number_type(ty);
        unsafe {
            let val: i8 = 0i8;
            if !CFNumberGetValue(self.obj, ty, cast::transmute(&val)) {
                fail!(~"Error in unwrapping CFNumber to i8");
            }
            return val;
        }
    }

    pure fn to_i16() -> i16 {
        let ty = kCFNumberSInt16Type;
        assert self.has_number_type(ty);
        unsafe {
            let val: i16 = 0i16;
            if !CFNumberGetValue(self.obj, ty, cast::transmute(&val)) {
                fail!(~"Error in unwrapping CFNumber to i16");
            }
            return val;
        }
    }

    pure fn to_i32() -> i32 {
        let ty = kCFNumberSInt32Type;
        assert self.has_number_type(ty);
        unsafe {
            let val: i32 = 0i32;
            if !CFNumberGetValue(self.obj, ty, cast::transmute(&val)) {
                fail!(~"Error in unwrapping CFNumber to i32");
            }
            return val;
        }
    }

    pure fn to_float() -> float {
        unsafe {
            assert self.has_float_type();
            let ty = CFNumberGetType(self.obj);
            if ty == kCFNumberFloat32Type || ty == kCFNumberFloatType {
                let mut val: libc::c_float = 0.0f as libc::c_float;
                if !CFNumberGetValue(self.obj, ty, cast::transmute(&val)) {
                    fail!(~"Error in unwrapping CFNumber to libc::c_float");
                }
                return val as float;
            }
            else if ty == kCFNumberFloat64Type || ty == kCFNumberDoubleType {
                let mut val: libc::c_double = 0.0f as libc::c_double;
                if !CFNumberGetValue(self.obj, ty, cast::transmute(&val)) {
                        fail!(~"Error in unwrapping CFNumber to libc::c_double");
                    }
                return val as float;
            }

            fail!(fmt!("Unable to wrap CFNumber into float: with type tag=%?", ty))
        }
    }

    priv pure fn has_float_type() -> bool {
        unsafe {
            CFNumberIsFloatType(self.obj) as bool
        }
    }

    priv pure fn has_number_type(ty: CFNumberType) -> bool {
        unsafe {
            CFNumberGetType(self.obj) == ty
        }
    }
}

pub trait ConvertibleToCFNumber {
    // FIXME: Should be static, but that breaks.
    pure fn cf_number_type(&self) -> CFNumberType;
}

impl i8 : ConvertibleToCFNumber {
    pure fn cf_number_type(&self) -> CFNumberType { kCFNumberSInt8Type as CFNumberType }
}

impl i16 : ConvertibleToCFNumber {
    pure fn cf_number_type(&self) -> CFNumberType { kCFNumberSInt16Type as CFNumberType }
}

impl i32 : ConvertibleToCFNumber {
    pure fn cf_number_type(&self) -> CFNumberType { kCFNumberSInt32Type as CFNumberType }
}

impl i64 : ConvertibleToCFNumber {
    pure fn cf_number_type(&self) -> CFNumberType { kCFNumberSInt64Type as CFNumberType }
}

impl float : ConvertibleToCFNumber {
    pure fn cf_number_type(&self) -> CFNumberType { kCFNumberFloatType as CFNumberType }
}

#[link_args="-framework CoreFoundation"]
#[nolink]
extern {
    /*
     * CFNumber.h
     */

    const kCFNumberNaN: CFNumberRef;
    const kCFNumberNegativeInfinity: CFNumberRef;
    const kCFNumberPositiveInfinity: CFNumberRef;

    fn CFNumberCreate(allocator: CFAllocatorRef, theType: CFNumberType, valuePtr: *c_void)
                   -> CFNumberRef;
    //fn CFNumberGetByteSize
    fn CFNumberGetType(number: CFNumberRef) -> CFNumberType;
    fn CFNumberGetValue(number: CFNumberRef, theType: CFNumberType, valuePtr: *c_void) -> bool;
    fn CFNumberIsFloatType(number: CFNumberRef) -> Boolean;
    //fn CFNumberCompare
    fn CFNumberGetTypeID() -> CFTypeID;
}

fn should_fail_on_bad_downcast() {
    #[test];
    #[should_fail];

    use boolean::CFBooleanRef;

    let one = CFWrapper::to_CFType(CFNumber::new(1_i32));
    let casted = base::downcast::<CFBooleanRef>(*one.borrow_ref());
}
<commit_msg>Update tests for language changes<commit_after>use base::{
    AbstractCFTypeRef,
    Boolean,
    CFAllocatorRef,
    CFIndex,
    CFTypeID,
    CFTypeRef,
    CFWrapper,
    kCFAllocatorDefault
};
use base;
use libc::{c_int, c_void};

pub type CFNumberType = u32;

// members of enum CFNumberType
const kCFNumberSInt8Type:     CFNumberType = 1;
const kCFNumberSInt16Type:    CFNumberType = 2;
const kCFNumberSInt32Type:    CFNumberType = 3;
const kCFNumberSInt64Type:    CFNumberType = 4;
const kCFNumberFloat32Type:   CFNumberType = 5;
const kCFNumberFloat64Type:   CFNumberType = 6;
const kCFNumberCharType:      CFNumberType = 7;
const kCFNumberShortType:     CFNumberType = 8;
const kCFNumberIntType:       CFNumberType = 9;
const kCFNumberLongType:      CFNumberType = 10;
const kCFNumberLongLongType:  CFNumberType = 11;
const kCFNumberFloatType:     CFNumberType = 12;
const kCFNumberDoubleType:    CFNumberType = 13;
const kCFNumberCFIndexType:   CFNumberType = 14;
const kCFNumberNSIntegerType: CFNumberType = 15;
const kCFNumberCGFloatType:   CFNumberType = 16;
const kCFNumberMaxType:       CFNumberType = 16;

struct __CFNumber { private: () }
pub type CFNumberRef = *__CFNumber;

pub impl CFNumberRef : AbstractCFTypeRef {
    pure fn as_type_ref(&self) -> CFTypeRef { *self as CFTypeRef }

    static pure fn type_id() -> CFTypeID {
        unsafe {
            CFNumberGetTypeID()
        }
    }
}

pub type CFNumber = CFWrapper<CFNumberRef, (), ()>;

pub impl CFNumber {
    static fn new<T:Copy ConvertibleToCFNumber>(n: T) -> CFNumber {
        unsafe {
            let objref = CFNumberCreate(kCFAllocatorDefault,
                                        n.cf_number_type(),
                                        cast::transmute(&n));
            CFWrapper::wrap_owned(objref)
        }
    }

    pure fn to_i8() -> i8 {
        let ty = kCFNumberSInt8Type;
        assert self.has_number_type(ty);
        unsafe {
            let val: i8 = 0i8;
            if !CFNumberGetValue(self.obj, ty, cast::transmute(&val)) {
                fail!(~"Error in unwrapping CFNumber to i8");
            }
            return val;
        }
    }

    pure fn to_i16() -> i16 {
        let ty = kCFNumberSInt16Type;
        assert self.has_number_type(ty);
        unsafe {
            let val: i16 = 0i16;
            if !CFNumberGetValue(self.obj, ty, cast::transmute(&val)) {
                fail!(~"Error in unwrapping CFNumber to i16");
            }
            return val;
        }
    }

    pure fn to_i32() -> i32 {
        let ty = kCFNumberSInt32Type;
        assert self.has_number_type(ty);
        unsafe {
            let val: i32 = 0i32;
            if !CFNumberGetValue(self.obj, ty, cast::transmute(&val)) {
                fail!(~"Error in unwrapping CFNumber to i32");
            }
            return val;
        }
    }

    pure fn to_float() -> float {
        unsafe {
            assert self.has_float_type();
            let ty = CFNumberGetType(self.obj);
            if ty == kCFNumberFloat32Type || ty == kCFNumberFloatType {
                let mut val: libc::c_float = 0.0f as libc::c_float;
                if !CFNumberGetValue(self.obj, ty, cast::transmute(&val)) {
                    fail!(~"Error in unwrapping CFNumber to libc::c_float");
                }
                return val as float;
            }
            else if ty == kCFNumberFloat64Type || ty == kCFNumberDoubleType {
                let mut val: libc::c_double = 0.0f as libc::c_double;
                if !CFNumberGetValue(self.obj, ty, cast::transmute(&val)) {
                        fail!(~"Error in unwrapping CFNumber to libc::c_double");
                    }
                return val as float;
            }

            fail!(fmt!("Unable to wrap CFNumber into float: with type tag=%?", ty))
        }
    }

    priv pure fn has_float_type() -> bool {
        unsafe {
            CFNumberIsFloatType(self.obj) as bool
        }
    }

    priv pure fn has_number_type(ty: CFNumberType) -> bool {
        unsafe {
            CFNumberGetType(self.obj) == ty
        }
    }
}

pub trait ConvertibleToCFNumber {
    // FIXME: Should be static, but that breaks.
    pure fn cf_number_type(&self) -> CFNumberType;
}

impl i8 : ConvertibleToCFNumber {
    pure fn cf_number_type(&self) -> CFNumberType { kCFNumberSInt8Type as CFNumberType }
}

impl i16 : ConvertibleToCFNumber {
    pure fn cf_number_type(&self) -> CFNumberType { kCFNumberSInt16Type as CFNumberType }
}

impl i32 : ConvertibleToCFNumber {
    pure fn cf_number_type(&self) -> CFNumberType { kCFNumberSInt32Type as CFNumberType }
}

impl i64 : ConvertibleToCFNumber {
    pure fn cf_number_type(&self) -> CFNumberType { kCFNumberSInt64Type as CFNumberType }
}

impl float : ConvertibleToCFNumber {
    pure fn cf_number_type(&self) -> CFNumberType { kCFNumberFloatType as CFNumberType }
}

#[link_args="-framework CoreFoundation"]
#[nolink]
extern {
    /*
     * CFNumber.h
     */

    const kCFNumberNaN: CFNumberRef;
    const kCFNumberNegativeInfinity: CFNumberRef;
    const kCFNumberPositiveInfinity: CFNumberRef;

    fn CFNumberCreate(allocator: CFAllocatorRef, theType: CFNumberType, valuePtr: *c_void)
                   -> CFNumberRef;
    //fn CFNumberGetByteSize
    fn CFNumberGetType(number: CFNumberRef) -> CFNumberType;
    fn CFNumberGetValue(number: CFNumberRef, theType: CFNumberType, valuePtr: *c_void) -> bool;
    fn CFNumberIsFloatType(number: CFNumberRef) -> Boolean;
    //fn CFNumberCompare
    fn CFNumberGetTypeID() -> CFTypeID;
}

fn should_fail_on_bad_downcast() {
    #[test];
    #[should_fail];

    use boolean::CFBooleanRef;

    let one = CFWrapper::to_CFType(CFNumber::new(1_i32));
    let casted = base::downcast::<CFBooleanRef>(*one.borrow_ref());
}
<|endoftext|>