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

use to_str::{ToStr,ToStrConsume};
use str;
use cast;

#[cfg(test)]
pub struct Ascii { priv chr: u8 }

/// Datatype to hold one ascii character. It is 8 bit long.
#[cfg(notest)]
#[deriving(Clone, Eq, Ord)]
pub struct Ascii { priv chr: u8 }

pub impl Ascii {
    /// Converts a ascii character into a `u8`.
    fn to_byte(self) -> u8 {
        self.chr
    }

    /// Converts a ascii character into a `char`.
    fn to_char(self) -> char {
        self.chr as char
    }
}

impl ToStr for Ascii {
    fn to_str(&self) -> ~str { str::from_bytes(['\'' as u8, self.chr, '\'' as u8]) }
}

/// Trait for converting into an ascii type.
pub trait AsciiCast<T> {
    /// Convert to an ascii type
    fn to_ascii(&self) -> T;

    /// Check if convertible to ascii
    fn is_ascii(&self) -> bool;
}

impl<'self> AsciiCast<&'self[Ascii]> for &'self [u8] {
    fn to_ascii(&self) -> &'self[Ascii] {
        assert!(self.is_ascii());

        unsafe{ cast::transmute(*self) }
    }

    fn is_ascii(&self) -> bool {
        for self.each |b| {
            if !b.is_ascii() { return false; }
        }
        true
    }
}

impl<'self> AsciiCast<&'self[Ascii]> for &'self str {
    fn to_ascii(&self) -> &'self[Ascii] {
        assert!(self.is_ascii());

        let (p,len): (*u8, uint) = unsafe{ cast::transmute(*self) };
        unsafe{ cast::transmute((p, len - 1))}
    }

    fn is_ascii(&self) -> bool {
        for self.each |b| {
            if !b.is_ascii() { return false; }
        }
        true
    }
}

impl AsciiCast<Ascii> for u8 {
    fn to_ascii(&self) -> Ascii {
        assert!(self.is_ascii());
        Ascii{ chr: *self }
    }

    fn is_ascii(&self) -> bool {
        *self & 128 == 0u8
    }
}

impl AsciiCast<Ascii> for char {
    fn to_ascii(&self) -> Ascii {
        assert!(self.is_ascii());
        Ascii{ chr: *self as u8 }
    }

    fn is_ascii(&self) -> bool {
        *self - ('\x7F' & *self) == '\x00'
    }
}

/// Trait for copyless casting to an ascii vector.
pub trait OwnedAsciiCast {
    /// Take ownership and cast to an ascii vector without trailing zero element.
    fn to_ascii_consume(self) -> ~[Ascii];
}

impl OwnedAsciiCast for ~[u8] {
    fn to_ascii_consume(self) -> ~[Ascii] {
        assert!(self.is_ascii());

        unsafe {cast::transmute(self)}
    }
}

impl OwnedAsciiCast for ~str {
    fn to_ascii_consume(self) -> ~[Ascii] {
        let mut s = self;
        unsafe {
            str::raw::pop_byte(&mut s);
            cast::transmute(s)
        }
    }
}

/// Trait for converting an ascii type to a string. Needed to convert `&[Ascii]` to `~str`
pub trait ToStrAscii {
    /// Convert to a string.
    fn to_str_ascii(&self) -> ~str;
}

impl<'self> ToStrAscii for &'self [Ascii] {
    fn to_str_ascii(&self) -> ~str {
        let mut cpy = self.to_owned();
        cpy.push(0u8.to_ascii());
        unsafe {cast::transmute(cpy)}
    }
}

impl ToStrConsume for ~[Ascii] {
    fn to_str_consume(self) -> ~str {
        let mut cpy = self;
        cpy.push(0u8.to_ascii());
        unsafe {cast::transmute(cpy)}
    }
}

// NOTE: Remove stage0 marker after snapshot
#[cfg(and(test, not(stage0)))]
mod tests {
    use super::*;
    use to_str::{ToStr,ToStrConsume};
    use str;
    use cast;

    macro_rules! v2ascii (
        ( [$($e:expr),*]) => ( [$(Ascii{chr:$e}),*]);
        (~[$($e:expr),*]) => (~[$(Ascii{chr:$e}),*]);
    )

    #[test]
    fn test_ascii() {
        assert_eq!(65u8.to_ascii().to_byte(), 65u8);
        assert_eq!(65u8.to_ascii().to_char(), 'A');
        assert_eq!('A'.to_ascii().to_char(), 'A');
        assert_eq!('A'.to_ascii().to_byte(), 65u8);
    }

    #[test]
    fn test_ascii_vec() {
        assert_eq!((&[40u8, 32u8, 59u8]).to_ascii(), v2ascii!([40, 32, 59]));
        assert_eq!("( ;".to_ascii(),                 v2ascii!([40, 32, 59]));
        // FIXME: #5475 borrowchk error, owned vectors do not live long enough
        // if chained-from directly
        let v = ~[40u8, 32u8, 59u8]; assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59]));
        let v = ~"( ;";              assert_eq!(v.to_ascii(), v2ascii!([40, 32, 59]));
    }

    #[test]
    fn test_owned_ascii_vec() {
        // FIXME: #4318 Compiler crashes on moving self
        //assert_eq!(~"( ;".to_ascii_consume(), v2ascii!(~[40, 32, 59]));
        //assert_eq!(~[40u8, 32u8, 59u8].to_ascii_consume(), v2ascii!(~[40, 32, 59]));
        //assert_eq!(~"( ;".to_ascii_consume_with_null(), v2ascii!(~[40, 32, 59, 0]));
        //assert_eq!(~[40u8, 32u8, 59u8].to_ascii_consume_with_null(),
        //           v2ascii!(~[40, 32, 59, 0]));
    }

    #[test]
    fn test_ascii_to_str() { assert_eq!(v2ascii!([40, 32, 59]).to_str_ascii(), ~"( ;"); }

    #[test]
    fn test_ascii_to_str_consume() {
        // FIXME: #4318 Compiler crashes on moving self
        //assert_eq!(v2ascii!(~[40, 32, 59]).to_str_consume(), ~"( ;");
    }

    #[test] #[should_fail]
    fn test_ascii_vec_fail_u8_slice()  { (&[127u8, 128u8, 255u8]).to_ascii(); }

    #[test] #[should_fail]
    fn test_ascii_vec_fail_str_slice() { "zoä华".to_ascii(); }

    #[test] #[should_fail]
    fn test_ascii_fail_u8_slice() { 255u8.to_ascii(); }

    #[test] #[should_fail]
    fn test_ascii_fail_char_slice() { 'λ'.to_ascii(); }
}

<|endoftext|>


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

use std::str;

mod libc {
    #[abi = "cdecl"]
    #[nolink]
    extern {
        pub fn atol(x: *u8) -> int;
        pub fn atoll(x: *u8) -> i64;
    }
}

fn atol(s: ~str) -> int {
    s.as_imm_buf(|x, _len| unsafe { libc::atol(x) })
}

fn atoll(s: ~str) -> i64 {
    s.as_imm_buf(|x, _len| unsafe { libc::atoll(x) })
}

pub fn main() {
    unsafe {
        assert_eq!(atol(~"1024") * 10, atol(~"10240"));
        assert!((atoll(~"11111111111111111") * 10i64)
            == atoll(~"111111111111111110"));
    }
}
<commit_msg>Fix a stack to use the new .to_c_str() api<commit_after>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::str;

mod libc {
    #[abi = "cdecl"]
    #[nolink]
    extern {
        pub fn atol(x: *u8) -> int;
        pub fn atoll(x: *u8) -> i64;
    }
}

fn atol(s: ~str) -> int {
    s.to_c_str().with_ref(|x| unsafe { libc::atol(x as *u8) })
}

fn atoll(s: ~str) -> i64 {
    s.to_c_str().with_ref(|x| unsafe { libc::atoll(x as *u8) })
}

pub fn main() {
    unsafe {
        assert_eq!(atol(~"1024") * 10, atol(~"10240"));
        assert!((atoll(~"11111111111111111") * 10i64)
            == atoll(~"111111111111111110"));
    }
}
<|endoftext|>


<commit_before><commit_msg>Test bundle decoding (works)<commit_after>#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_osc;

use std::io::Cursor;
use serde::Deserialize;
use serde_osc::de::PktDeserializer;

#[test]
fn bundle() {
    #[derive(Debug, PartialEq, Deserialize)]
    struct Msg1 {
        address: String,
        arg_0: i32,
    }
    #[derive(Debug, PartialEq, Deserialize)]
    struct Msg2 {
        address: String,
        arg_0: f32,
    }
    #[derive(Debug, PartialEq, Deserialize)]
    struct Bundle {
        timestamp: u64,
        msg1: Msg1,
        msg2: Msg2,
    }
    let expected = Bundle {
        timestamp: 0x0102030405060708,
        msg1: Msg1 {
            address: "/m1".to_owned(),
            arg_0: 0x5eeeeeed,
        },
        msg2: Msg2 {
            address: "/m2".to_owned(),
            arg_0: 440.0,
        }
    };

    // Note: 0x43dc0000 is 440.0 in f32.
    let test_input = b"\x00\x00\x00\x30#bundle\0\x01\x02\x03\x04\x05\x06\x07\x08\x00\x00\x00\x0C/m1\0,i\0\0\x5E\xEE\xEE\xED\x00\x00\x00\x0C/m2\0,f\0\0\x43\xdc\x00\x00";

    let rd = Cursor::new(&test_input[..]);
    let mut test_de = PktDeserializer::new(rd);
    let deserialized = Bundle::deserialize(&mut test_de).unwrap();
    assert_eq!(deserialized, expected);
}
<|endoftext|>


<commit_before><commit_msg>Small cleanup<commit_after><|endoftext|>


<commit_before>/*
Module: int
*/

/*
Function: max_value

The maximum value of an integer
*/
fn max_value() -> int {
  ret min_value() - 1;
}

/*
Function: min_value

The minumum value of an integer
*/
fn min_value() -> int {
  ret (-1 << (sys::size_of::<int>()  * 8u as int - 1)) as int;
}

/* Function: add */
pure fn add(x: int, y: int) -> int { ret x + y; }

/* Function: sub */
pure fn sub(x: int, y: int) -> int { ret x - y; }

/* Function: mul */
pure fn mul(x: int, y: int) -> int { ret x * y; }

/* Function: div */
pure fn div(x: int, y: int) -> int { ret x / y; }

/* Function: rem */
pure fn rem(x: int, y: int) -> int { ret x % y; }

/* Predicate: lt */
pure fn lt(x: int, y: int) -> bool { ret x < y; }

/* Predicate: le */
pure fn le(x: int, y: int) -> bool { ret x <= y; }

/* Predicate: eq */
pure fn eq(x: int, y: int) -> bool { ret x == y; }

/* Predicate: ne */
pure fn ne(x: int, y: int) -> bool { ret x != y; }

/* Predicate: ge */
pure fn ge(x: int, y: int) -> bool { ret x >= y; }

/* Predicate: gt */
pure fn gt(x: int, y: int) -> bool { ret x > y; }

/* Predicate: positive */
pure fn positive(x: int) -> bool { ret x > 0; }

/* Predicate: negative */
pure fn negative(x: int) -> bool { ret x < 0; }

/* Predicate: nonpositive */
pure fn nonpositive(x: int) -> bool { ret x <= 0; }

/* Predicate: nonnegative */
pure fn nonnegative(x: int) -> bool { ret x >= 0; }

// FIXME: Make sure this works with negative integers.
/*
Function: hash

Produce a uint suitable for use in a hash table
*/
fn hash(x: int) -> uint { ret x as uint; }

// FIXME: This is redundant
fn eq_alias(x: int, y: int) -> bool { ret x == y; }

/*
Function: range

Iterate over the range [`lo`..`hi`)
*/
fn range(lo: int, hi: int, it: block(int)) {
    while lo < hi { it(lo); lo += 1; }
}

/*
Function: parse_buf

Parse a buffer of bytes

Parameters:

buf - A byte buffer
radix - The base of the number

Failure:

buf must not be empty
*/
fn parse_buf(buf: [u8], radix: uint) -> int {
    if vec::len::<u8>(buf) == 0u {
        log_err "parse_buf(): buf is empty";
        fail;
    }
    let i = vec::len::<u8>(buf) - 1u;
    let power = 1;
    if buf[0] == ('-' as u8) {
        power = -1;
        i -= 1u;
    }
    let n = 0;
    while true {
        n += (buf[i] - ('0' as u8) as int) * power;
        power *= radix as int;
        if i == 0u { ret n; }
        i -= 1u;
    }
    fail;
}

/*
Function: from_str

Parse a string to an int

Failure:

s must not be empty
*/
fn from_str(s: str) -> int { parse_buf(str::bytes(s), 10u) }

/*
Function: to_str

Convert to a string in a given base
*/
fn to_str(n: int, radix: uint) -> str {
    assert (0u < radix && radix <= 16u);
    ret if n < 0 {
            "-" + uint::to_str(-n as uint, radix)
        } else { uint::to_str(n as uint, radix) };
}

/*
Function: str

Convert to a string
*/
fn str(i: int) -> str { ret to_str(i, 10u); }

/*
Function: pow

Returns `base` raised to the power of `exponent`
*/
fn pow(base: int, exponent: uint) -> int {
    if exponent == 0u { ret 1; } //Not mathemtically true if [base == 0]
    if base     == 0  { ret 0; }
    let my_pow  = exponent;
    let acc     = 1;
    let multiplier = base;
    while(my_pow > 0u) {
      if my_pow % 2u == 1u {
         acc *= multiplier;
      }
      my_pow     /= 2u;
      multiplier *= multiplier;
    }
    ret acc;
}
// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<commit_msg>Remove std::int::eq_alias<commit_after>/*
Module: int
*/

/*
Function: max_value

The maximum value of an integer
*/
fn max_value() -> int {
  ret min_value() - 1;
}

/*
Function: min_value

The minumum value of an integer
*/
fn min_value() -> int {
  ret (-1 << (sys::size_of::<int>()  * 8u as int - 1)) as int;
}

/* Function: add */
pure fn add(x: int, y: int) -> int { ret x + y; }

/* Function: sub */
pure fn sub(x: int, y: int) -> int { ret x - y; }

/* Function: mul */
pure fn mul(x: int, y: int) -> int { ret x * y; }

/* Function: div */
pure fn div(x: int, y: int) -> int { ret x / y; }

/* Function: rem */
pure fn rem(x: int, y: int) -> int { ret x % y; }

/* Predicate: lt */
pure fn lt(x: int, y: int) -> bool { ret x < y; }

/* Predicate: le */
pure fn le(x: int, y: int) -> bool { ret x <= y; }

/* Predicate: eq */
pure fn eq(x: int, y: int) -> bool { ret x == y; }

/* Predicate: ne */
pure fn ne(x: int, y: int) -> bool { ret x != y; }

/* Predicate: ge */
pure fn ge(x: int, y: int) -> bool { ret x >= y; }

/* Predicate: gt */
pure fn gt(x: int, y: int) -> bool { ret x > y; }

/* Predicate: positive */
pure fn positive(x: int) -> bool { ret x > 0; }

/* Predicate: negative */
pure fn negative(x: int) -> bool { ret x < 0; }

/* Predicate: nonpositive */
pure fn nonpositive(x: int) -> bool { ret x <= 0; }

/* Predicate: nonnegative */
pure fn nonnegative(x: int) -> bool { ret x >= 0; }

// FIXME: Make sure this works with negative integers.
/*
Function: hash

Produce a uint suitable for use in a hash table
*/
fn hash(x: int) -> uint { ret x as uint; }

/*
Function: range

Iterate over the range [`lo`..`hi`)
*/
fn range(lo: int, hi: int, it: block(int)) {
    while lo < hi { it(lo); lo += 1; }
}

/*
Function: parse_buf

Parse a buffer of bytes

Parameters:

buf - A byte buffer
radix - The base of the number

Failure:

buf must not be empty
*/
fn parse_buf(buf: [u8], radix: uint) -> int {
    if vec::len::<u8>(buf) == 0u {
        log_err "parse_buf(): buf is empty";
        fail;
    }
    let i = vec::len::<u8>(buf) - 1u;
    let power = 1;
    if buf[0] == ('-' as u8) {
        power = -1;
        i -= 1u;
    }
    let n = 0;
    while true {
        n += (buf[i] - ('0' as u8) as int) * power;
        power *= radix as int;
        if i == 0u { ret n; }
        i -= 1u;
    }
    fail;
}

/*
Function: from_str

Parse a string to an int

Failure:

s must not be empty
*/
fn from_str(s: str) -> int { parse_buf(str::bytes(s), 10u) }

/*
Function: to_str

Convert to a string in a given base
*/
fn to_str(n: int, radix: uint) -> str {
    assert (0u < radix && radix <= 16u);
    ret if n < 0 {
            "-" + uint::to_str(-n as uint, radix)
        } else { uint::to_str(n as uint, radix) };
}

/*
Function: str

Convert to a string
*/
fn str(i: int) -> str { ret to_str(i, 10u); }

/*
Function: pow

Returns `base` raised to the power of `exponent`
*/
fn pow(base: int, exponent: uint) -> int {
    if exponent == 0u { ret 1; } //Not mathemtically true if [base == 0]
    if base     == 0  { ret 0; }
    let my_pow  = exponent;
    let acc     = 1;
    let multiplier = base;
    while(my_pow > 0u) {
      if my_pow % 2u == 1u {
         acc *= multiplier;
      }
      my_pow     /= 2u;
      multiplier *= multiplier;
    }
    ret acc;
}
// Local Variables:
// mode: rust;
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// compile-command: "make -k -C $RBUILD 2>&1 | sed -e 's/\\/x\\//x:\\//g'";
// End:
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use CompositorProxy;
use layout_traits::{LayoutTaskFactory, LayoutControlChan};
use script_traits::{LayoutControlMsg, ScriptControlChan, ScriptTaskFactory};
use script_traits::{NewLayoutInfo, ConstellationControlMsg};

use compositor_task;
use devtools_traits::DevtoolsControlChan;
use euclid::rect::{TypedRect};
use euclid::scale_factor::ScaleFactor;
use gfx::paint_task::Msg as PaintMsg;
use gfx::paint_task::{PaintChan, PaintTask};
use gfx::font_cache_task::FontCacheTask;
use ipc_channel::ipc::{self, IpcReceiver};
use layers::geometry::DevicePixel;
use msg::compositor_msg::ScriptListener;
use msg::constellation_msg::{ConstellationChan, Failure, FrameId, PipelineId, SubpageId};
use msg::constellation_msg::{LoadData, WindowSizeData, PipelineExitType, MozBrowserEvent};
use profile_traits::mem as profile_mem;
use profile_traits::time;
use net_traits::ResourceTask;
use net_traits::image_cache_task::ImageCacheTask;
use net_traits::storage_task::StorageTask;
use std::any::Any;
use std::mem;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::thread;
use url::Url;
use util::geometry::{PagePx, ViewportPx};
use util::opts;

/// A uniquely-identifiable pipeline of script task, layout task, and paint task.
pub struct Pipeline {
    pub id: PipelineId,
    pub parent_info: Option<(PipelineId, SubpageId)>,
    pub script_chan: ScriptControlChan,
    /// A channel to layout, for performing reflows and shutdown.
    pub layout_chan: LayoutControlChan,
    pub paint_chan: PaintChan,
    pub layout_shutdown_port: Receiver<()>,
    pub paint_shutdown_port: Receiver<()>,
    /// URL corresponding to the most recently-loaded page.
    pub url: Url,
    /// The title of the most recently-loaded page.
    pub title: Option<String>,
    pub rect: Option<TypedRect<PagePx, f32>>,
    /// Whether this pipeline is currently running animations. Pipelines that are running
    /// animations cause composites to be continually scheduled.
    pub running_animations: bool,
    pub children: Vec<FrameId>,
}

/// The subset of the pipeline that is needed for layer composition.
#[derive(Clone)]
pub struct CompositionPipeline {
    pub id: PipelineId,
    pub script_chan: ScriptControlChan,
    pub layout_chan: LayoutControlChan,
    pub paint_chan: PaintChan,
}

impl Pipeline {
    /// Starts a paint task, layout task, and possibly a script task.
    /// Returns the channels wrapped in a struct.
    /// If script_pipeline is not None, then subpage_id must also be not None.
    pub fn create<LTF,STF>(id: PipelineId,
                           parent_info: Option<(PipelineId, SubpageId)>,
                           constellation_chan: ConstellationChan,
                           compositor_proxy: Box<CompositorProxy+'static+Send>,
                           devtools_chan: Option<DevtoolsControlChan>,
                           image_cache_task: ImageCacheTask,
                           font_cache_task: FontCacheTask,
                           resource_task: ResourceTask,
                           storage_task: StorageTask,
                           time_profiler_chan: time::ProfilerChan,
                           mem_profiler_chan: profile_mem::ProfilerChan,
                           window_rect: Option<TypedRect<PagePx, f32>>,
                           script_chan: Option<ScriptControlChan>,
                           load_data: LoadData,
                           device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>)
                           -> (Pipeline, PipelineContent)
                           where LTF: LayoutTaskFactory, STF:ScriptTaskFactory {
        let (paint_port, paint_chan) = PaintChan::new();
        let (paint_shutdown_chan, paint_shutdown_port) = channel();
        let (layout_shutdown_chan, layout_shutdown_port) = channel();
        let (pipeline_chan, pipeline_port) = ipc::channel().unwrap();
        let mut pipeline_port = Some(pipeline_port);

        let failure = Failure {
            pipeline_id: id,
            parent_info: parent_info,
        };

        let window_size = window_rect.map(|rect| {
            WindowSizeData {
                visible_viewport: rect.size,
                initial_viewport: rect.size * ScaleFactor::new(1.0),
                device_pixel_ratio: device_pixel_ratio,
            }
        });

        if let Some(ref script_chan) = script_chan {
            let (containing_pipeline_id, subpage_id) =
                parent_info.expect("script_pipeline != None but subpage_id == None");
            let new_layout_info = NewLayoutInfo {
                containing_pipeline_id: containing_pipeline_id,
                new_pipeline_id: id,
                subpage_id: subpage_id,
                load_data: load_data.clone(),
                paint_chan: box() (paint_chan.clone()) as Box<Any + Send>,
                failure: failure,
                pipeline_port: mem::replace(&mut pipeline_port, None).unwrap(),
                layout_shutdown_chan: layout_shutdown_chan.clone(),
            };

            script_chan.0.send(ConstellationControlMsg::AttachLayout(new_layout_info)).unwrap();
        }

        let (script_chan, script_port) = channel();
        let pipeline = Pipeline::new(id,
                                     parent_info,
                                     ScriptControlChan(script_chan.clone()),
                                     LayoutControlChan(pipeline_chan),
                                     paint_chan.clone(),
                                     layout_shutdown_port,
                                     paint_shutdown_port,
                                     load_data.url.clone(),
                                     window_rect);

        let pipeline_content = PipelineContent {
            id: id,
            parent_info: parent_info,
            constellation_chan: constellation_chan,
            compositor_proxy: compositor_proxy,
            devtools_chan: devtools_chan,
            image_cache_task: image_cache_task,
            font_cache_task: font_cache_task,
            resource_task: resource_task,
            storage_task: storage_task,
            time_profiler_chan: time_profiler_chan,
            mem_profiler_chan: mem_profiler_chan,
            window_size: window_size,
            script_chan: script_chan,
            load_data: load_data,
            failure: failure,
            script_port: script_port,
            paint_chan: paint_chan,
            paint_port: Some(paint_port),
            pipeline_port: pipeline_port,
            paint_shutdown_chan: paint_shutdown_chan,
            layout_shutdown_chan: layout_shutdown_chan,
        };

        (pipeline, pipeline_content)
    }

    pub fn new(id: PipelineId,
               parent_info: Option<(PipelineId, SubpageId)>,
               script_chan: ScriptControlChan,
               layout_chan: LayoutControlChan,
               paint_chan: PaintChan,
               layout_shutdown_port: Receiver<()>,
               paint_shutdown_port: Receiver<()>,
               url: Url,
               rect: Option<TypedRect<PagePx, f32>>)
               -> Pipeline {
        Pipeline {
            id: id,
            parent_info: parent_info,
            script_chan: script_chan,
            layout_chan: layout_chan,
            paint_chan: paint_chan,
            layout_shutdown_port: layout_shutdown_port,
            paint_shutdown_port: paint_shutdown_port,
            url: url,
            title: None,
            children: vec!(),
            rect: rect,
            running_animations: false,
        }
    }

    pub fn grant_paint_permission(&self) {
        let _ = self.paint_chan.send(PaintMsg::PaintPermissionGranted);
    }

    pub fn revoke_paint_permission(&self) {
        debug!("pipeline revoking paint channel paint permission");
        let _ = self.paint_chan.send(PaintMsg::PaintPermissionRevoked);
    }

    pub fn exit(&self, exit_type: PipelineExitType) {
        debug!("pipeline {:?} exiting", self.id);

        // Script task handles shutting down layout, and layout handles shutting down the painter.
        // For now, if the script task has failed, we give up on clean shutdown.
        let ScriptControlChan(ref chan) = self.script_chan;
        if chan.send(ConstellationControlMsg::ExitPipeline(self.id, exit_type)).is_ok() {
            // Wait until all slave tasks have terminated and run destructors
            // NOTE: We don't wait for script task as we don't always own it
            let _ = self.paint_shutdown_port.recv();
            let _ = self.layout_shutdown_port.recv();
        }

    }

    pub fn freeze(&self) {
        let ScriptControlChan(ref script_channel) = self.script_chan;
        let _ = script_channel.send(ConstellationControlMsg::Freeze(self.id)).unwrap();
    }

    pub fn thaw(&self) {
        let ScriptControlChan(ref script_channel) = self.script_chan;
        let _ = script_channel.send(ConstellationControlMsg::Thaw(self.id)).unwrap();
    }

    pub fn force_exit(&self) {
        let ScriptControlChan(ref script_channel) = self.script_chan;
        let _ = script_channel.send(
            ConstellationControlMsg::ExitPipeline(self.id,
                                                  PipelineExitType::PipelineOnly)).unwrap();
        let _ = self.paint_chan.send(PaintMsg::Exit(None, PipelineExitType::PipelineOnly));
        let LayoutControlChan(ref layout_channel) = self.layout_chan;
        let _ = layout_channel.send(
            LayoutControlMsg::ExitNow(PipelineExitType::PipelineOnly)).unwrap();
    }

    pub fn to_sendable(&self) -> CompositionPipeline {
        CompositionPipeline {
            id: self.id.clone(),
            script_chan: self.script_chan.clone(),
            layout_chan: self.layout_chan.clone(),
            paint_chan: self.paint_chan.clone(),
        }
    }

    pub fn add_child(&mut self, frame_id: FrameId) {
        self.children.push(frame_id);
    }

    pub fn remove_child(&mut self, frame_id: FrameId) {
        let index = self.children.iter().position(|id| *id == frame_id).unwrap();
        self.children.remove(index);
    }

    pub fn trigger_mozbrowser_event(&self,
                                     subpage_id: SubpageId,
                                     event: MozBrowserEvent) {
        assert!(opts::experimental_enabled());

        let ScriptControlChan(ref script_channel) = self.script_chan;
        let event = ConstellationControlMsg::MozBrowserEvent(self.id,
                                                             subpage_id,
                                                             event);
        script_channel.send(event).unwrap();
    }
}

pub struct PipelineContent {
    id: PipelineId,
    parent_info: Option<(PipelineId, SubpageId)>,
    constellation_chan: ConstellationChan,
    compositor_proxy: Box<CompositorProxy + Send + 'static>,
    devtools_chan: Option<DevtoolsControlChan>,
    image_cache_task: ImageCacheTask,
    font_cache_task: FontCacheTask,
    resource_task: ResourceTask,
    storage_task: StorageTask,
    time_profiler_chan: time::ProfilerChan,
    mem_profiler_chan: profile_mem::ProfilerChan,
    window_size: Option<WindowSizeData>,
    script_chan: Sender<ConstellationControlMsg>,
    load_data: LoadData,
    failure: Failure,
    script_port: Receiver<ConstellationControlMsg>,
    paint_chan: PaintChan,
    paint_port: Option<Receiver<PaintMsg>>,
    paint_shutdown_chan: Sender<()>,
    pipeline_port: Option<IpcReceiver<LayoutControlMsg>>,
    layout_shutdown_chan: Sender<()>,
}

impl PipelineContent {
    pub fn start_all<LTF,STF>(mut self) where LTF: LayoutTaskFactory, STF: ScriptTaskFactory {
        let layout_pair = ScriptTaskFactory::create_layout_channel(None::<&mut STF>);
        let (script_to_compositor_chan, script_to_compositor_port) = ipc::channel().unwrap();

        self.start_paint_task();

        let compositor_proxy_for_script_listener_thread =
            self.compositor_proxy.clone_compositor_proxy();
        thread::spawn(move || {
            compositor_task::run_script_listener_thread(
                compositor_proxy_for_script_listener_thread,
                script_to_compositor_port)
        });

        ScriptTaskFactory::create(None::<&mut STF>,
                                  self.id,
                                  self.parent_info,
                                  ScriptListener::new(script_to_compositor_chan),
                                  &layout_pair,
                                  ScriptControlChan(self.script_chan.clone()),
                                  self.script_port,
                                  self.constellation_chan.clone(),
                                  self.failure.clone(),
                                  self.resource_task,
                                  self.storage_task.clone(),
                                  self.image_cache_task.clone(),
                                  self.devtools_chan,
                                  self.window_size,
                                  self.load_data.clone());

        LayoutTaskFactory::create(None::<&mut LTF>,
                                  self.id,
                                  self.load_data.url.clone(),
                                  self.parent_info.is_some(),
                                  layout_pair,
                                  self.pipeline_port.unwrap(),
                                  self.constellation_chan,
                                  self.failure,
                                  ScriptControlChan(self.script_chan.clone()),
                                  self.paint_chan.clone(),
                                  self.image_cache_task,
                                  self.font_cache_task,
                                  self.time_profiler_chan,
                                  self.mem_profiler_chan,
                                  self.layout_shutdown_chan);
    }

    pub fn start_paint_task(&mut self) {
        PaintTask::create(self.id,
                          self.load_data.url.clone(),
                          self.paint_chan.clone(),
                          mem::replace(&mut self.paint_port, None).unwrap(),
                          self.compositor_proxy.clone_compositor_proxy(),
                          self.constellation_chan.clone(),
                          self.font_cache_task.clone(),
                          self.failure.clone(),
                          self.time_profiler_chan.clone(),
                          self.mem_profiler_chan.clone(),
                          self.paint_shutdown_chan.clone());

    }
}

<commit_msg>compositing: Use the pre-existing script channel in the same-domain iframe case instead of creating a new one.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use CompositorProxy;
use layout_traits::{LayoutTaskFactory, LayoutControlChan};
use script_traits::{LayoutControlMsg, ScriptControlChan, ScriptTaskFactory};
use script_traits::{NewLayoutInfo, ConstellationControlMsg};

use compositor_task;
use devtools_traits::DevtoolsControlChan;
use euclid::rect::{TypedRect};
use euclid::scale_factor::ScaleFactor;
use gfx::paint_task::Msg as PaintMsg;
use gfx::paint_task::{PaintChan, PaintTask};
use gfx::font_cache_task::FontCacheTask;
use ipc_channel::ipc::{self, IpcReceiver};
use layers::geometry::DevicePixel;
use msg::compositor_msg::ScriptListener;
use msg::constellation_msg::{ConstellationChan, Failure, FrameId, PipelineId, SubpageId};
use msg::constellation_msg::{LoadData, WindowSizeData, PipelineExitType, MozBrowserEvent};
use profile_traits::mem as profile_mem;
use profile_traits::time;
use net_traits::ResourceTask;
use net_traits::image_cache_task::ImageCacheTask;
use net_traits::storage_task::StorageTask;
use std::any::Any;
use std::mem;
use std::sync::mpsc::{Receiver, Sender, channel};
use std::thread;
use url::Url;
use util::geometry::{PagePx, ViewportPx};
use util::opts;

/// A uniquely-identifiable pipeline of script task, layout task, and paint task.
pub struct Pipeline {
    pub id: PipelineId,
    pub parent_info: Option<(PipelineId, SubpageId)>,
    pub script_chan: ScriptControlChan,
    /// A channel to layout, for performing reflows and shutdown.
    pub layout_chan: LayoutControlChan,
    pub paint_chan: PaintChan,
    pub layout_shutdown_port: Receiver<()>,
    pub paint_shutdown_port: Receiver<()>,
    /// URL corresponding to the most recently-loaded page.
    pub url: Url,
    /// The title of the most recently-loaded page.
    pub title: Option<String>,
    pub rect: Option<TypedRect<PagePx, f32>>,
    /// Whether this pipeline is currently running animations. Pipelines that are running
    /// animations cause composites to be continually scheduled.
    pub running_animations: bool,
    pub children: Vec<FrameId>,
}

/// The subset of the pipeline that is needed for layer composition.
#[derive(Clone)]
pub struct CompositionPipeline {
    pub id: PipelineId,
    pub script_chan: ScriptControlChan,
    pub layout_chan: LayoutControlChan,
    pub paint_chan: PaintChan,
}

impl Pipeline {
    /// Starts a paint task, layout task, and possibly a script task.
    /// Returns the channels wrapped in a struct.
    /// If script_pipeline is not None, then subpage_id must also be not None.
    pub fn create<LTF,STF>(id: PipelineId,
                           parent_info: Option<(PipelineId, SubpageId)>,
                           constellation_chan: ConstellationChan,
                           compositor_proxy: Box<CompositorProxy+'static+Send>,
                           devtools_chan: Option<DevtoolsControlChan>,
                           image_cache_task: ImageCacheTask,
                           font_cache_task: FontCacheTask,
                           resource_task: ResourceTask,
                           storage_task: StorageTask,
                           time_profiler_chan: time::ProfilerChan,
                           mem_profiler_chan: profile_mem::ProfilerChan,
                           window_rect: Option<TypedRect<PagePx, f32>>,
                           script_chan: Option<ScriptControlChan>,
                           load_data: LoadData,
                           device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>)
                           -> (Pipeline, PipelineContent)
                           where LTF: LayoutTaskFactory, STF:ScriptTaskFactory {
        let (paint_port, paint_chan) = PaintChan::new();
        let (paint_shutdown_chan, paint_shutdown_port) = channel();
        let (layout_shutdown_chan, layout_shutdown_port) = channel();
        let (pipeline_chan, pipeline_port) = ipc::channel().unwrap();
        let mut pipeline_port = Some(pipeline_port);

        let failure = Failure {
            pipeline_id: id,
            parent_info: parent_info,
        };

        let window_size = window_rect.map(|rect| {
            WindowSizeData {
                visible_viewport: rect.size,
                initial_viewport: rect.size * ScaleFactor::new(1.0),
                device_pixel_ratio: device_pixel_ratio,
            }
        });

        let (script_chan, script_port) = match script_chan {
            Some(script_chan) => {
                let (containing_pipeline_id, subpage_id) =
                    parent_info.expect("script_pipeline != None but subpage_id == None");
                let new_layout_info = NewLayoutInfo {
                    containing_pipeline_id: containing_pipeline_id,
                    new_pipeline_id: id,
                    subpage_id: subpage_id,
                    load_data: load_data.clone(),
                    paint_chan: box() (paint_chan.clone()) as Box<Any + Send>,
                    failure: failure,
                    pipeline_port: mem::replace(&mut pipeline_port, None).unwrap(),
                    layout_shutdown_chan: layout_shutdown_chan.clone(),
                };

                script_chan.0
                           .send(ConstellationControlMsg::AttachLayout(new_layout_info))
                           .unwrap();
                (script_chan, None)
            }
            None => {
                let (script_chan, script_port) = channel();
                (ScriptControlChan(script_chan), Some(script_port))
            }
        };

        let pipeline = Pipeline::new(id,
                                     parent_info,
                                     script_chan.clone(),
                                     LayoutControlChan(pipeline_chan),
                                     paint_chan.clone(),
                                     layout_shutdown_port,
                                     paint_shutdown_port,
                                     load_data.url.clone(),
                                     window_rect);

        let pipeline_content = PipelineContent {
            id: id,
            parent_info: parent_info,
            constellation_chan: constellation_chan,
            compositor_proxy: compositor_proxy,
            devtools_chan: devtools_chan,
            image_cache_task: image_cache_task,
            font_cache_task: font_cache_task,
            resource_task: resource_task,
            storage_task: storage_task,
            time_profiler_chan: time_profiler_chan,
            mem_profiler_chan: mem_profiler_chan,
            window_size: window_size,
            script_chan: script_chan,
            load_data: load_data,
            failure: failure,
            script_port: script_port,
            paint_chan: paint_chan,
            paint_port: Some(paint_port),
            pipeline_port: pipeline_port,
            paint_shutdown_chan: paint_shutdown_chan,
            layout_shutdown_chan: layout_shutdown_chan,
        };

        (pipeline, pipeline_content)
    }

    pub fn new(id: PipelineId,
               parent_info: Option<(PipelineId, SubpageId)>,
               script_chan: ScriptControlChan,
               layout_chan: LayoutControlChan,
               paint_chan: PaintChan,
               layout_shutdown_port: Receiver<()>,
               paint_shutdown_port: Receiver<()>,
               url: Url,
               rect: Option<TypedRect<PagePx, f32>>)
               -> Pipeline {
        Pipeline {
            id: id,
            parent_info: parent_info,
            script_chan: script_chan,
            layout_chan: layout_chan,
            paint_chan: paint_chan,
            layout_shutdown_port: layout_shutdown_port,
            paint_shutdown_port: paint_shutdown_port,
            url: url,
            title: None,
            children: vec!(),
            rect: rect,
            running_animations: false,
        }
    }

    pub fn grant_paint_permission(&self) {
        let _ = self.paint_chan.send(PaintMsg::PaintPermissionGranted);
    }

    pub fn revoke_paint_permission(&self) {
        debug!("pipeline revoking paint channel paint permission");
        let _ = self.paint_chan.send(PaintMsg::PaintPermissionRevoked);
    }

    pub fn exit(&self, exit_type: PipelineExitType) {
        debug!("pipeline {:?} exiting", self.id);

        // Script task handles shutting down layout, and layout handles shutting down the painter.
        // For now, if the script task has failed, we give up on clean shutdown.
        let ScriptControlChan(ref chan) = self.script_chan;
        if chan.send(ConstellationControlMsg::ExitPipeline(self.id, exit_type)).is_ok() {
            // Wait until all slave tasks have terminated and run destructors
            // NOTE: We don't wait for script task as we don't always own it
            let _ = self.paint_shutdown_port.recv();
            let _ = self.layout_shutdown_port.recv();
        }

    }

    pub fn freeze(&self) {
        let ScriptControlChan(ref script_channel) = self.script_chan;
        let _ = script_channel.send(ConstellationControlMsg::Freeze(self.id)).unwrap();
    }

    pub fn thaw(&self) {
        let ScriptControlChan(ref script_channel) = self.script_chan;
        let _ = script_channel.send(ConstellationControlMsg::Thaw(self.id)).unwrap();
    }

    pub fn force_exit(&self) {
        let ScriptControlChan(ref script_channel) = self.script_chan;
        let _ = script_channel.send(
            ConstellationControlMsg::ExitPipeline(self.id,
                                                  PipelineExitType::PipelineOnly)).unwrap();
        let _ = self.paint_chan.send(PaintMsg::Exit(None, PipelineExitType::PipelineOnly));
        let LayoutControlChan(ref layout_channel) = self.layout_chan;
        let _ = layout_channel.send(
            LayoutControlMsg::ExitNow(PipelineExitType::PipelineOnly)).unwrap();
    }

    pub fn to_sendable(&self) -> CompositionPipeline {
        CompositionPipeline {
            id: self.id.clone(),
            script_chan: self.script_chan.clone(),
            layout_chan: self.layout_chan.clone(),
            paint_chan: self.paint_chan.clone(),
        }
    }

    pub fn add_child(&mut self, frame_id: FrameId) {
        self.children.push(frame_id);
    }

    pub fn remove_child(&mut self, frame_id: FrameId) {
        let index = self.children.iter().position(|id| *id == frame_id).unwrap();
        self.children.remove(index);
    }

    pub fn trigger_mozbrowser_event(&self,
                                     subpage_id: SubpageId,
                                     event: MozBrowserEvent) {
        assert!(opts::experimental_enabled());

        let ScriptControlChan(ref script_channel) = self.script_chan;
        let event = ConstellationControlMsg::MozBrowserEvent(self.id,
                                                             subpage_id,
                                                             event);
        script_channel.send(event).unwrap();
    }
}

pub struct PipelineContent {
    id: PipelineId,
    parent_info: Option<(PipelineId, SubpageId)>,
    constellation_chan: ConstellationChan,
    compositor_proxy: Box<CompositorProxy + Send + 'static>,
    devtools_chan: Option<DevtoolsControlChan>,
    image_cache_task: ImageCacheTask,
    font_cache_task: FontCacheTask,
    resource_task: ResourceTask,
    storage_task: StorageTask,
    time_profiler_chan: time::ProfilerChan,
    mem_profiler_chan: profile_mem::ProfilerChan,
    window_size: Option<WindowSizeData>,
    script_chan: ScriptControlChan,
    load_data: LoadData,
    failure: Failure,
    script_port: Option<Receiver<ConstellationControlMsg>>,
    paint_chan: PaintChan,
    paint_port: Option<Receiver<PaintMsg>>,
    paint_shutdown_chan: Sender<()>,
    pipeline_port: Option<IpcReceiver<LayoutControlMsg>>,
    layout_shutdown_chan: Sender<()>,
}

impl PipelineContent {
    pub fn start_all<LTF,STF>(mut self) where LTF: LayoutTaskFactory, STF: ScriptTaskFactory {
        let layout_pair = ScriptTaskFactory::create_layout_channel(None::<&mut STF>);
        let (script_to_compositor_chan, script_to_compositor_port) = ipc::channel().unwrap();

        self.start_paint_task();

        let compositor_proxy_for_script_listener_thread =
            self.compositor_proxy.clone_compositor_proxy();
        thread::spawn(move || {
            compositor_task::run_script_listener_thread(
                compositor_proxy_for_script_listener_thread,
                script_to_compositor_port)
        });

        ScriptTaskFactory::create(None::<&mut STF>,
                                  self.id,
                                  self.parent_info,
                                  ScriptListener::new(script_to_compositor_chan),
                                  &layout_pair,
                                  self.script_chan.clone(),
                                  mem::replace(&mut self.script_port, None).unwrap(),
                                  self.constellation_chan.clone(),
                                  self.failure.clone(),
                                  self.resource_task,
                                  self.storage_task.clone(),
                                  self.image_cache_task.clone(),
                                  self.devtools_chan,
                                  self.window_size,
                                  self.load_data.clone());

        LayoutTaskFactory::create(None::<&mut LTF>,
                                  self.id,
                                  self.load_data.url.clone(),
                                  self.parent_info.is_some(),
                                  layout_pair,
                                  self.pipeline_port.unwrap(),
                                  self.constellation_chan,
                                  self.failure,
                                  self.script_chan.clone(),
                                  self.paint_chan.clone(),
                                  self.image_cache_task,
                                  self.font_cache_task,
                                  self.time_profiler_chan,
                                  self.mem_profiler_chan,
                                  self.layout_shutdown_chan);
    }

    pub fn start_paint_task(&mut self) {
        PaintTask::create(self.id,
                          self.load_data.url.clone(),
                          self.paint_chan.clone(),
                          mem::replace(&mut self.paint_port, None).unwrap(),
                          self.compositor_proxy.clone_compositor_proxy(),
                          self.constellation_chan.clone(),
                          self.font_cache_task.clone(),
                          self.failure.clone(),
                          self.time_profiler_chan.clone(),
                          self.mem_profiler_chan.clone(),
                          self.paint_shutdown_chan.clone());

    }
}

<|endoftext|>


<commit_before>use toml::Value;

use libimagerror::into::IntoError;

use vcs::git::error::GitHookErrorKind as GHEK;
use vcs::git::error::MapErrInto;
use vcs::git::result::Result;

use vcs::git::action::StoreAction;

pub fn author_name(config: &Value) -> Result<&str> {
    unimplemented!()
}

pub fn author_mail(config: &Value) -> Result<&str> {
    unimplemented!()
}

pub fn committer_name(config: &Value) -> Result<&str> {
    unimplemented!()
}

pub fn committer_mail(config: &Value) -> Result<&str> {
    unimplemented!()
}

pub fn commit_interactive(config: &Value) -> bool {
    unimplemented!()
}

pub fn commit_message(config: &Value, action: StoreAction) -> Option<String> {
    if commit_interactive(config) {
        unimplemented!()
    } else {
        unimplemented!()
    }
}

pub fn abort_on_repo_init_err(cfg: Option<&Value>) -> bool {
    get_bool_cfg(cfg, "abort_on_repo_init_failure", true, true)
}

pub fn ensure_branch(cfg: Option<&Value>) -> Result<Option<String>> {
    match cfg {
        Some(cfg) => {
            match cfg.lookup("ensure_branch") {
                Some(&Value::String(ref s)) => Ok(Some(s.clone())),
                Some(_) => {
                    warn!("Configuration error, 'ensure_branch' must be a String.");
                    Err(GHEK::ConfigTypeError.into_error())
                        .map_err_into(GHEK::ConfigTypeError)
                },
                None => {
                    debug!("No key `ensure_branch'");
                    Ok(None)
                },
            }
        },
        None => Ok(None),
    }
}

pub fn do_checkout_ensure_branch(cfg: Option<&Value>) -> bool {
    get_bool_cfg(cfg, "try_checkout_ensure_branch", true, true)
}

fn get_bool_cfg(cfg: Option<&Value>, name: &str, on_fail: bool, on_unavail: bool) -> bool {
    cfg.map(|cfg| {
        match cfg.lookup(name) {
            Some(&Value::Boolean(b)) => b,
            Some(_) => {
                warn!("Configuration error, '{}' must be a Boolean (true|false).", name);
                warn!("Assuming 'true' now.");
                on_fail
            },
            None => {
                debug!("No key '{}' - Assuming 'true'", name);
                on_fail
            },
        }
    })
    .unwrap_or(on_unavail)
}

<commit_msg>Revert "Add stubs for getting information from the config"<commit_after>use toml::Value;

use libimagerror::into::IntoError;

use vcs::git::error::GitHookErrorKind as GHEK;
use vcs::git::error::MapErrInto;
use vcs::git::result::Result;

use vcs::git::action::StoreAction;

pub fn commit_interactive(config: &Value) -> bool {
    unimplemented!()
}

pub fn commit_message(config: &Value, action: StoreAction) -> Option<String> {
    if commit_interactive(config) {
        unimplemented!()
    } else {
        unimplemented!()
    }
}

pub fn abort_on_repo_init_err(cfg: Option<&Value>) -> bool {
    get_bool_cfg(cfg, "abort_on_repo_init_failure", true, true)
}

pub fn ensure_branch(cfg: Option<&Value>) -> Result<Option<String>> {
    match cfg {
        Some(cfg) => {
            match cfg.lookup("ensure_branch") {
                Some(&Value::String(ref s)) => Ok(Some(s.clone())),
                Some(_) => {
                    warn!("Configuration error, 'ensure_branch' must be a String.");
                    Err(GHEK::ConfigTypeError.into_error())
                        .map_err_into(GHEK::ConfigTypeError)
                },
                None => {
                    debug!("No key `ensure_branch'");
                    Ok(None)
                },
            }
        },
        None => Ok(None),
    }
}

pub fn do_checkout_ensure_branch(cfg: Option<&Value>) -> bool {
    get_bool_cfg(cfg, "try_checkout_ensure_branch", true, true)
}

fn get_bool_cfg(cfg: Option<&Value>, name: &str, on_fail: bool, on_unavail: bool) -> bool {
    cfg.map(|cfg| {
        match cfg.lookup(name) {
            Some(&Value::Boolean(b)) => b,
            Some(_) => {
                warn!("Configuration error, '{}' must be a Boolean (true|false).", name);
                warn!("Assuming 'true' now.");
                on_fail
            },
            None => {
                debug!("No key '{}' - Assuming 'true'", name);
                on_fail
            },
        }
    })
    .unwrap_or(on_unavail)
}

<|endoftext|>


<commit_before>//! AWS API requests.
//!
//! Wraps the Hyper library to send PUT, POST, DELETE and GET requests.

use std::io::Read;
use std::io::Error as IoError;
use std::error::Error;
use std::fmt;
use std::collections::HashMap;

use hyper::Client;
use hyper::Error as HyperError;
use hyper::header::Headers;
use hyper::method::Method;

use log::LogLevel::Debug;

use signature::SignedRequest;

pub struct HttpResponse {
    pub status: u16,
    pub body: String,
    pub headers: HashMap<String, String>
}

#[derive(Debug, PartialEq)]
pub struct HttpDispatchError {
    message: String
}

impl Error for HttpDispatchError {
    fn description(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for HttpDispatchError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl From<HyperError> for HttpDispatchError {
    fn from(err: HyperError) -> HttpDispatchError {
        HttpDispatchError { message: err.description().to_string() }
    }
}

impl From<IoError> for HttpDispatchError {
    fn from(err: IoError) -> HttpDispatchError {
        HttpDispatchError { message: err.description().to_string() }
    }
}

pub trait DispatchSignedRequest {
    fn dispatch(&self, request: &SignedRequest) -> Result<HttpResponse, HttpDispatchError>;
}

impl DispatchSignedRequest for Client {
    fn dispatch(&self, request: &SignedRequest) -> Result<HttpResponse, HttpDispatchError> {
        let hyper_method = match request.method().as_ref() {
            "POST" => Method::Post,
            "PUT" => Method::Put,
            "DELETE" => Method::Delete,
            "GET" => Method::Get,
            v @ _ => return Err(HttpDispatchError { message: format!("Unsupported HTTP verb {}", v) })

        };

        // translate the headers map to a format Hyper likes
        let mut hyper_headers = Headers::new();
        for h in request.headers().iter() {
            hyper_headers.set_raw(h.0.to_owned(), h.1.to_owned());
        }

        let mut final_uri = format!("https://{}{}", request.hostname(), request.path());
        if !request.canonical_query_string().is_empty() {
            final_uri = final_uri + &format!("?{}", request.canonical_query_string());
        }

        if log_enabled!(Debug) {
            let payload = request.payload().map(|mut payload_bytes| {
                let mut payload_string = String::new();

                payload_bytes.read_to_string(&mut payload_string).expect("Failed to read payload to string");

                payload_string
            });

            debug!("Full request: \n method: {}\n final_uri: {}\n payload: {:?}\nHeaders:\n", hyper_method, final_uri, payload);
            for h in hyper_headers.iter() {
                debug!("{}:{}", h.name(), h.value_string());
            }
        }

        let mut hyper_response = match request.payload() {
            None => try!(self.request(hyper_method, &final_uri).headers(hyper_headers).body("").send()),
            Some(payload_contents) => try!(self.request(hyper_method, &final_uri).headers(hyper_headers).body(payload_contents).send()),
        };

        let mut body = String::new();
        try!(hyper_response.read_to_string(&mut body));

        if log_enabled!(Debug) {
            debug!("Response body:\n{}", body);
        }

        let mut headers: HashMap<String, String> = HashMap::new();

        for header in hyper_response.headers.iter() {
            headers.insert(header.name().to_string(), header.value_string());
        }

        Ok(HttpResponse {
            status: hyper_response.status.to_u16(),
            body: body,
            headers: headers
        })

    }
}
<commit_msg>Fix request logging with a non-UTF-8 request body Fixes #331<commit_after>//! AWS API requests.
//!
//! Wraps the Hyper library to send PUT, POST, DELETE and GET requests.

use std::io::Read;
use std::io::Error as IoError;
use std::error::Error;
use std::fmt;
use std::collections::HashMap;

use hyper::Client;
use hyper::Error as HyperError;
use hyper::header::Headers;
use hyper::method::Method;

use log::LogLevel::Debug;

use signature::SignedRequest;

pub struct HttpResponse {
    pub status: u16,
    pub body: String,
    pub headers: HashMap<String, String>
}

#[derive(Debug, PartialEq)]
pub struct HttpDispatchError {
    message: String
}

impl Error for HttpDispatchError {
    fn description(&self) -> &str {
        &self.message
    }
}

impl fmt::Display for HttpDispatchError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl From<HyperError> for HttpDispatchError {
    fn from(err: HyperError) -> HttpDispatchError {
        HttpDispatchError { message: err.description().to_string() }
    }
}

impl From<IoError> for HttpDispatchError {
    fn from(err: IoError) -> HttpDispatchError {
        HttpDispatchError { message: err.description().to_string() }
    }
}

pub trait DispatchSignedRequest {
    fn dispatch(&self, request: &SignedRequest) -> Result<HttpResponse, HttpDispatchError>;
}

impl DispatchSignedRequest for Client {
    fn dispatch(&self, request: &SignedRequest) -> Result<HttpResponse, HttpDispatchError> {
        let hyper_method = match request.method().as_ref() {
            "POST" => Method::Post,
            "PUT" => Method::Put,
            "DELETE" => Method::Delete,
            "GET" => Method::Get,
            v @ _ => return Err(HttpDispatchError { message: format!("Unsupported HTTP verb {}", v) })

        };

        // translate the headers map to a format Hyper likes
        let mut hyper_headers = Headers::new();
        for h in request.headers().iter() {
            hyper_headers.set_raw(h.0.to_owned(), h.1.to_owned());
        }

        let mut final_uri = format!("https://{}{}", request.hostname(), request.path());
        if !request.canonical_query_string().is_empty() {
            final_uri = final_uri + &format!("?{}", request.canonical_query_string());
        }

        if log_enabled!(Debug) {
            let payload = request.payload().map(|mut payload_bytes| {
                let mut payload_string = String::new();

                payload_bytes.read_to_string(&mut payload_string)
                    .map(|_| payload_string)
                    .unwrap_or_else(|_| String::from("<non-UTF-8 data>"))
            });

            debug!("Full request: \n method: {}\n final_uri: {}\n payload: {:?}\nHeaders:\n", hyper_method, final_uri, payload);
            for h in hyper_headers.iter() {
                debug!("{}:{}", h.name(), h.value_string());
            }
        }

        let mut hyper_response = match request.payload() {
            None => try!(self.request(hyper_method, &final_uri).headers(hyper_headers).body("").send()),
            Some(payload_contents) => try!(self.request(hyper_method, &final_uri).headers(hyper_headers).body(payload_contents).send()),
        };

        let mut body = String::new();
        try!(hyper_response.read_to_string(&mut body));

        if log_enabled!(Debug) {
            debug!("Response body:\n{}", body);
        }

        let mut headers: HashMap<String, String> = HashMap::new();

        for header in hyper_response.headers.iter() {
            headers.insert(header.name().to_string(), header.value_string());
        }

        Ok(HttpResponse {
            status: hyper_response.status.to_u16(),
            body: body,
            headers: headers
        })

    }
}
<|endoftext|>


<commit_before><commit_msg>Invalid error mesage for incorect passphrase Fixed<commit_after><|endoftext|>


<commit_before><commit_msg>clean up redis handler<commit_after><|endoftext|>


<commit_before><commit_msg>chore: unit test<commit_after><|endoftext|>


<commit_before><commit_msg>Early-out for stop world before draw<commit_after><|endoftext|>


<commit_before><commit_msg>Reset env counter and noise shift on play control enable<commit_after><|endoftext|>


<commit_before><commit_msg>Add weak and SC operations<commit_after><|endoftext|>


<commit_before><commit_msg>rust: solved the borrowing/moving problem in using_trait snippet<commit_after><|endoftext|>


<commit_before><commit_msg>Test that multiple wrappers created from a handle share a ref count<commit_after>/* Copyright 2015 Jordan Miner
 *
 * Licensed under the MIT license <LICENSE or
 * http://opensource.org/licenses/MIT>. This file may not be copied,
 * modified, or distributed except according to those terms.
 */

extern crate clear_coat;

use std::ptr;
use std::rc::Rc;
use clear_coat::*;
use clear_coat::common_attrs_cbs::*;

// Tests that creating multiple control wrappers from the same *mut Ihandle will share
// a reference count.

#[test]
fn test_deduplication() {
    let x = Rc::new(5);
    let x2 = x.clone();
    let dialog = Dialog::new(None);
    dialog.enter_window().add_callback(move || println!("{}", *x2));
    let handle = dialog.handle();
    let dialog2 = unsafe { Dialog::from_handle(handle) };
    let dialog3 = unsafe { Dialog::from_handle(handle) };
    let x = Rc::try_unwrap(x).unwrap_err();
    drop(dialog);
    let x = Rc::try_unwrap(x).unwrap_err();
    drop(dialog3);
    let x = Rc::try_unwrap(x).unwrap_err();
    drop(dialog2);
    let _ = Rc::try_unwrap(x).unwrap();
}
<|endoftext|>


<commit_before><commit_msg>Inline 'Method::supports_payload()'.<commit_after><|endoftext|>


<commit_before><commit_msg>add a lib.rs template<commit_after>#![crate_name = "NAME"]

#![license = "MIT"]
// #![crate_type = "dylib"]
#![crate_type = "rlib"]

// #![feature(macro_rules)]

// use whatever;
// pub mod whatever;
<|endoftext|>


<commit_before>pub use alloc::arc::{Arc, Weak};
pub use core::sync::atomic;
pub use self::mutex::{Mutex, MutexGuard, StaticMutex};
pub use self::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
pub use self::once::Once;

mod mpsc;
mod mutex;
mod once;
mod rwlock;
<commit_msg>Public mpsc<commit_after>pub use alloc::arc::{Arc, Weak};
pub use core::sync::atomic;
pub use self::mutex::{Mutex, MutexGuard, StaticMutex};
pub use self::rwlock::{RwLock, RwLockReadGuard, RwLockWriteGuard};
pub use self::once::Once;

pub mod mpsc;
mod mutex;
mod once;
mod rwlock;
<|endoftext|>


<commit_before><commit_msg>Use thread-local-storage to avoid lots of parameter passing in the renderer framework and application<commit_after><|endoftext|>


<commit_before><commit_msg>Add tests for checking for extraneous leading newlines (or lack thereof)<commit_after>extern crate rustc_serialize;
extern crate toml;
use toml::encode_str;

#[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
struct User {
    pub name: String,
    pub surname: String,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
struct Users {
    pub user: Vec<User>,
}

#[derive(Debug, Clone, Hash, PartialEq, Eq, RustcEncodable, RustcDecodable)]
struct TwoUsers {
    pub user0: User,
    pub user1: User,
}

#[test]
fn no_unnecessary_newlines_array() {
    assert!(!encode_str(&Users {
            user: vec![
                    User {
                        name: "John".to_string(),
                        surname: "Doe".to_string(),
                    },
                    User {
                        name: "Jane".to_string(),
                        surname: "Dough".to_string(),
                    },
                ],
        })
        .starts_with("\n"));
}

#[test]
fn no_unnecessary_newlines_table() {
    assert!(!encode_str(&TwoUsers {
            user0: User {
                name: "John".to_string(),
                surname: "Doe".to_string(),
            },
            user1: User {
                name: "Jane".to_string(),
                surname: "Dough".to_string(),
            },
        })
        .starts_with("\n"));
}
<|endoftext|>


<commit_before><commit_msg>file/open,create<commit_after>use std::path::Path;
use std::fs::File;

use std::io::prelude::*;

static LICENSE: & 'static str= "/home/anoop/Work/github/rustbyexample/LICENSE";

fn main() {

    //path
    let path = Path::new(LICENSE);

    // open
    let mut file = match File::open(&path) { // File::create(&path) // for writing

        Err(e) => panic!("Failed to open: {:?}", path),

        Ok(file) => file
    };

    // read
    let mut cont = String::new();
    // match file.write_all(str.as_bytes) // for writing
    match file.read_to_string(&mut cont) {

        Err(e) => panic!("Unable to read: {:?}", path),

        Ok(_) => println!("")
    };

    //display
    println!("File contents: {:?}", cont);
}<|endoftext|>


<commit_before><commit_msg>chore: multiple segments<commit_after><|endoftext|>


<commit_before><commit_msg>test for troublesome case where preserve was freeing uninitialized memory<commit_after>// xfail-fast   (compile-flags unsupported on windows)
// compile-flags:--borrowck=err
// exec-env:RUST_POISON_ON_FREE=1

fn switcher(x: option<@int>) {
    let mut x = x;
    alt x {
      some(@y) { copy y; x = none; }
      none { }
    }
}

fn main() {
    switcher(none);
    switcher(some(@3));
}<|endoftext|>


<commit_before><commit_msg>Add initial PluginServer request processing methods.<commit_after><|endoftext|>


<commit_before><commit_msg>Add problem #69<commit_after>use common::prime::{ Prime };
use common::problem::{ Problem };

pub static problem: Problem<'static> = Problem {
    id: 69,
    answer: "510510",
    solver: solve
};

fn solve() -> ~str {
    let limit = 1000000;

    let mut ps = Prime::new();
    let mut n   = 1;
    let mut val = 1f;
    for ps.each |p| {
        if n * p > limit { break; }
        n   *= p;
        val *= (p as float) * (p as float - 1f);
    }

    return n.to_str();
}
<|endoftext|>


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

#![allow(missing_doc)]

use char;
use container::Container;
use fmt;
use iter::{Iterator, range, DoubleEndedIterator};
use num::{Float, FPNaN, FPInfinite, ToPrimitive, Primitive};
use num::{Zero, One, cast};
use option::{None, Some};
use result::Ok;
use slice::{ImmutableVector, MutableVector};
use slice;
use str::StrSlice;

/// A flag that specifies whether to use exponential (scientific) notation.
pub enum ExponentFormat {
    /// Do not use exponential notation.
    ExpNone,
    /// Use exponential notation with the exponent having a base of 10 and the
    /// exponent sign being `e` or `E`. For example, 1000 would be printed
    /// 1e3.
    ExpDec,
    /// Use exponential notation with the exponent having a base of 2 and the
    /// exponent sign being `p` or `P`. For example, 8 would be printed 1p3.
    ExpBin,
}

/// The number of digits used for emitting the fractional part of a number, if
/// any.
pub enum SignificantDigits {
    /// All calculable digits will be printed.
    ///
    /// Note that bignums or fractions may cause a surprisingly large number
    /// of digits to be printed.
    DigAll,

    /// At most the given number of digits will be printed, truncating any
    /// trailing zeroes.
    DigMax(uint),

    /// Precisely the given number of digits will be printed.
    DigExact(uint)
}

/// How to emit the sign of a number.
pub enum SignFormat {
    /// No sign will be printed. The exponent sign will also be emitted.
    SignNone,
    /// `-` will be printed for negative values, but no sign will be emitted
    /// for positive numbers.
    SignNeg,
    /// `+` will be printed for positive values, and `-` will be printed for
    /// negative values.
    SignAll,
}

static DIGIT_P_RADIX: uint = ('p' as uint) - ('a' as uint) + 11u;
static DIGIT_E_RADIX: uint = ('e' as uint) - ('a' as uint) + 11u;

/**
 * Converts a number to its string representation as a byte vector.
 * This is meant to be a common base implementation for all numeric string
 * conversion functions like `to_str()` or `to_str_radix()`.
 *
 * # Arguments
 * - `num`           - The number to convert. Accepts any number that
 *                     implements the numeric traits.
 * - `radix`         - Base to use. Accepts only the values 2-36. If the exponential notation
 *                     is used, then this base is only used for the significand. The exponent
 *                     itself always printed using a base of 10.
 * - `negative_zero` - Whether to treat the special value `-0` as
 *                     `-0` or as `+0`.
 * - `sign`          - How to emit the sign. See `SignFormat`.
 * - `digits`        - The amount of digits to use for emitting the fractional
 *                     part, if any. See `SignificantDigits`.
 * - `exp_format`   - Whether or not to use the exponential (scientific) notation.
 *                    See `ExponentFormat`.
 * - `exp_capital`   - Whether or not to use a capital letter for the exponent sign, if
 *                     exponential notation is desired.
 * - `f`             - A closure to invoke with the bytes representing the
 *                     float.
 *
 * # Failure
 * - Fails if `radix` < 2 or `radix` > 36.
 * - Fails if `radix` > 14 and `exp_format` is `ExpDec` due to conflict
 *   between digit and exponent sign `'e'`.
 * - Fails if `radix` > 25 and `exp_format` is `ExpBin` due to conflict
 *   between digit and exponent sign `'p'`.
 */
pub fn float_to_str_bytes_common<T: Primitive + Float, U>(
    num: T,
    radix: uint,
    negative_zero: bool,
    sign: SignFormat,
    digits: SignificantDigits,
    exp_format: ExponentFormat,
    exp_upper: bool,
    f: |&[u8]| -> U
) -> U {
    assert!(2 <= radix && radix <= 36);
    match exp_format {
        ExpDec if radix >= DIGIT_E_RADIX       // decimal exponent 'e'
          => fail!("float_to_str_bytes_common: radix {} incompatible with \
                    use of 'e' as decimal exponent", radix),
        ExpBin if radix >= DIGIT_P_RADIX       // binary exponent 'p'
          => fail!("float_to_str_bytes_common: radix {} incompatible with \
                    use of 'p' as binary exponent", radix),
        _ => ()
    }

    let _0: T = Zero::zero();
    let _1: T = One::one();

    match num.classify() {
        FPNaN => return f("NaN".as_bytes()),
        FPInfinite if num > _0 => {
            return match sign {
                SignAll => return f("+inf".as_bytes()),
                _       => return f("inf".as_bytes()),
            };
        }
        FPInfinite if num < _0 => {
            return match sign {
                SignNone => return f("inf".as_bytes()),
                _        => return f("-inf".as_bytes()),
            };
        }
        _ => {}
    }

    let neg = num < _0 || (negative_zero && _1 / num == Float::neg_infinity());
    // For an f64 the exponent is in the range of [-1022, 1023] for base 2, so
    // we may have up to that many digits. Give ourselves some extra wiggle room
    // otherwise as well.
    let mut buf = [0u8, ..1536];
    let mut end = 0;
    let radix_gen: T = cast(radix as int).unwrap();

    let (num, exp) = match exp_format {
        ExpNone => (num, 0i32),
        ExpDec | ExpBin if num == _0 => (num, 0i32),
        ExpDec | ExpBin => {
            let (exp, exp_base) = match exp_format {
                ExpDec => (num.abs().log10().floor(), cast::<f64, T>(10.0f64).unwrap()),
                ExpBin => (num.abs().log2().floor(), cast::<f64, T>(2.0f64).unwrap()),
                ExpNone => fail!("unreachable"),
            };

            (num / exp_base.powf(exp), cast::<T, i32>(exp).unwrap())
        }
    };

    // First emit the non-fractional part, looping at least once to make
    // sure at least a `0` gets emitted.
    let mut deccum = num.trunc();
    loop {
        // Calculate the absolute value of each digit instead of only
        // doing it once for the whole number because a
        // representable negative number doesn't necessary have an
        // representable additive inverse of the same type
        // (See twos complement). But we assume that for the
        // numbers [-35 .. 0] we always have [0 .. 35].
        let current_digit = (deccum % radix_gen).abs();

        // Decrease the deccumulator one digit at a time
        deccum = deccum / radix_gen;
        deccum = deccum.trunc();

        let c = char::from_digit(current_digit.to_int().unwrap() as uint, radix);
        buf[end] = c.unwrap() as u8;
        end += 1;

        // No more digits to calculate for the non-fractional part -> break
        if deccum == _0 { break; }
    }

    // If limited digits, calculate one digit more for rounding.
    let (limit_digits, digit_count, exact) = match digits {
        DigAll          => (false, 0u,      false),
        DigMax(count)   => (true,  count+1, false),
        DigExact(count) => (true,  count+1, true)
    };

    // Decide what sign to put in front
    match sign {
        SignNeg | SignAll if neg => {
            buf[end] = '-' as u8;
            end += 1;
        }
        SignAll => {
            buf[end] = '+' as u8;
            end += 1;
        }
        _ => ()
    }

    buf.mut_slice_to(end).reverse();

    // Remember start of the fractional digits.
    // Points one beyond end of buf if none get generated,
    // or at the '.' otherwise.
    let start_fractional_digits = end;

    // Now emit the fractional part, if any
    deccum = num.fract();
    if deccum != _0 || (limit_digits && exact && digit_count > 0) {
        buf[end] = '.' as u8;
        end += 1;
        let mut dig = 0u;

        // calculate new digits while
        // - there is no limit and there are digits left
        // - or there is a limit, it's not reached yet and
        //   - it's exact
        //   - or it's a maximum, and there are still digits left
        while (!limit_digits && deccum != _0)
           || (limit_digits && dig < digit_count && (
                   exact
                || (!exact && deccum != _0)
              )
        ) {
            // Shift first fractional digit into the integer part
            deccum = deccum * radix_gen;

            // Calculate the absolute value of each digit.
            // See note in first loop.
            let current_digit = deccum.trunc().abs();

            let c = char::from_digit(current_digit.to_int().unwrap() as uint,
                                     radix);
            buf[end] = c.unwrap() as u8;
            end += 1;

            // Decrease the deccumulator one fractional digit at a time
            deccum = deccum.fract();
            dig += 1u;
        }

        // If digits are limited, and that limit has been reached,
        // cut off the one extra digit, and depending on its value
        // round the remaining ones.
        if limit_digits && dig == digit_count {
            let ascii2value = |chr: u8| {
                char::to_digit(chr as char, radix).unwrap()
            };
            let value2ascii = |val: uint| {
                char::from_digit(val, radix).unwrap() as u8
            };

            let extra_digit = ascii2value(buf[end - 1]);
            end -= 1;
            if extra_digit >= radix / 2 { // -> need to round
                let mut i: int = end as int - 1;
                loop {
                    // If reached left end of number, have to
                    // insert additional digit:
                    if i < 0
                    || buf[i as uint] == '-' as u8
                    || buf[i as uint] == '+' as u8 {
                        for j in range(i as uint + 1, end).rev() {
                            buf[j + 1] = buf[j];
                        }
                        buf[(i + 1) as uint] = value2ascii(1);
                        end += 1;
                        break;
                    }

                    // Skip the '.'
                    if buf[i as uint] == '.' as u8 { i -= 1; continue; }

                    // Either increment the digit,
                    // or set to 0 if max and carry the 1.
                    let current_digit = ascii2value(buf[i as uint]);
                    if current_digit < (radix - 1) {
                        buf[i as uint] = value2ascii(current_digit+1);
                        break;
                    } else {
                        buf[i as uint] = value2ascii(0);
                        i -= 1;
                    }
                }
            }
        }
    }

    // if number of digits is not exact, remove all trailing '0's up to
    // and including the '.'
    if !exact {
        let buf_max_i = end - 1;

        // index to truncate from
        let mut i = buf_max_i;

        // discover trailing zeros of fractional part
        while i > start_fractional_digits && buf[i] == '0' as u8 {
            i -= 1;
        }

        // Only attempt to truncate digits if buf has fractional digits
        if i >= start_fractional_digits {
            // If buf ends with '.', cut that too.
            if buf[i] == '.' as u8 { i -= 1 }

            // only resize buf if we actually remove digits
            if i < buf_max_i {
                end = i + 1;
            }
        }
    } // If exact and trailing '.', just cut that
    else {
        let max_i = end - 1;
        if buf[max_i] == '.' as u8 {
            end = max_i;
        }
    }

    match exp_format {
        ExpNone => {},
        _ => {
            buf[end] = match exp_format {
                ExpDec if exp_upper => 'E',
                ExpDec if !exp_upper => 'e',
                ExpBin if exp_upper => 'P',
                ExpBin if !exp_upper => 'p',
                _ => fail!("unreachable"),
            } as u8;
            end += 1;

            struct Filler<'a> {
                buf: &'a mut [u8],
                end: &'a mut uint,
            }

            impl<'a> fmt::FormatWriter for Filler<'a> {
                fn write(&mut self, bytes: &[u8]) -> fmt::Result {
                    slice::bytes::copy_memory(self.buf.mut_slice_from(*self.end),
                                              bytes);
                    *self.end += bytes.len();
                    Ok(())
                }
            }

            let mut filler = Filler { buf: buf, end: &mut end };
            match sign {
                SignNeg => { let _ = write!(&mut filler, "{:-}", exp); }
                SignNone | SignAll => { let _ = write!(&mut filler, "{}", exp); }
            }
        }
    }

    f(buf.slice_to(end))
}
<|endoftext|>


<commit_before><commit_msg>Added files via upload<commit_after>fn main () {
println!("Hello");
}

/*

#[macro_use] extern crate nickel;
//extern crate hyper;

use nickel::{Nickel, HttpRouter};
//use hyper::method::Method;

fn main() {
    let mut server = Nickel::new();

    // Nickel provides a default router on the server for getting
    // up and running quickly. If you want to partition out your app
    // you might want to use an explicit router though.
    server.utilize(explicit_router());

    // Most common HTTP verbs are extension methods added from the HttpRouter trait.
    // You can see other examples such as 'json' to see other verbs in use.
    // For other HTTP verbs, you can use the `add_route` method.

    // go to http://localhost:6767/bar to see this route in action
    server.add_route(Method::Get, "/bar", middleware! {
        "This is the /bar handler"
    });

    // go to http://localhost:6767/foo to see this route in action
    server.get("/:foo", middleware! { |request|
        let foo = request.param("foo").unwrap();
        let format = request.param("format").unwrap();
        format!("Foo is '{}'. The requested format is '{}'", foo, format)
    });

    server.listen("127.0.0.1:6767");
}

fn explicit_router() -> nickel::Router {
    let mut router = Nickel::router();

    // Wildcard '*' routes are supported
    // - '*' will match a single directories seperated by '/'
    // - '**' will match potentially many directories

    // Single wildcard:
    // go to http://localhost:6767/some/crazy/route to see this route in action
    router.get("/some/*/route", middleware! {
        "This matches /some/crazy/route but not /some/super/crazy/route"
    });

    // Double wildcards:
    // go to http://localhost:6767/a/nice/route
    // or http://localhost:6767/a/super/nice/route to see this route in action
    router.get("/a/**/route", middleware! {
        "This matches /a/crazy/route and also /a/super/crazy/route"
    });

    router
}
*/
<|endoftext|>