<commit_before>generate_error_imports!();
use std::convert::From;

#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)]
pub struct CustomErrorData {}

generate_custom_error_types!(StoreError, StoreErrorKind, CustomErrorData,
    ConfigurationError      => "Store Configuration Error",
    CreateStoreDirDenied    => "Creating store directory implicitely denied",
    FileError               => "File Error",
    IoError                 => "IO Error",
    IdLocked                => "ID locked",
    IdNotFound              => "ID not found",
    OutOfMemory             => "Out of Memory",
    FileNotFound            => "File corresponding to ID not found",
    FileNotCreated          => "File corresponding to ID could not be created",
    StorePathExists         => "Store path exists",
    StorePathCreate         => "Store path create",
    LockError               => "Error locking datastructure",
    LockPoisoned            => "The internal Store Lock has been poisoned",
    EntryAlreadyBorrowed    => "Entry is already borrowed",
    EntryAlreadyExists      => "Entry already exists",
    MalformedEntry          => "Entry has invalid formatting, missing header",
    HeaderPathSyntaxError   => "Syntax error in accessor string",
    HeaderPathTypeFailure   => "Header has wrong type for path",
    HeaderKeyNotFound       => "Header Key not found",
    HeaderTypeFailure       => "Header type is wrong",
    HookRegisterError       => "Hook register error",
    AspectNameNotFoundError => "Aspect name not found",
    HookExecutionError      => "Hook execution error",
    PreHookExecuteError     => "Pre-Hook execution error",
    PostHookExecuteError    => "Post-Hook execution error",
    StorePathLacksVersion   => "The supplied store path has no version part",
    GlobError               => "glob() error",
    EncodingError           => "Encoding error",
    StorePathError          => "Store Path error",
    EntryRenameError        => "Entry rename error",
    StoreIdHandlingError    => "StoreId handling error",

    CreateCallError            => "Error when calling create()",
    RetrieveCallError          => "Error when calling retrieve()",
    GetCallError               => "Error when calling get()",
    GetAllVersionsCallError    => "Error when calling get_all_versions()",
    RetrieveForModuleCallError => "Error when calling retrieve_for_module()",
    UpdateCallError            => "Error when calling update()",
    RetrieveCopyCallError      => "Error when calling retrieve_copy()",
    DeleteCallError            => "Error when calling delete()",
    MoveCallError              => "Error when calling move()",
    MoveByIdCallError          => "Error when calling move_by_id()"
);

generate_result_helper!(StoreError, StoreErrorKind);
generate_option_helper!(StoreError, StoreErrorKind);

generate_custom_error_types!(ParserError, ParserErrorKind, CustomErrorData,
    TOMLParserErrors    => "Several TOML-Parser-Errors",
    MissingMainSection  => "Missing main section",
    MissingVersionInfo  => "Missing version information in main section",
    NonTableInBaseTable => "A non-table was found in the base table",
    HeaderInconsistency => "The header is inconsistent"
);

impl From<ParserError> for StoreError {
    fn from(ps: ParserError) -> StoreError {
        StoreError {
            err_type: StoreErrorKind::MalformedEntry,
            cause: Some(Box::new(ps)),
            custom_data: None,
        }
    }
}

impl From<::std::io::Error> for StoreError {
    fn from(ps: ::std::io::Error) -> StoreError {
        StoreError {
            err_type: StoreErrorKind::IoError,
            cause: Some(Box::new(ps)),
            custom_data: None,
        }
    }
}

<commit_msg>Add FileNot{Written,Seeked} errors<commit_after>generate_error_imports!();
use std::convert::From;

#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Copy)]
pub struct CustomErrorData {}

generate_custom_error_types!(StoreError, StoreErrorKind, CustomErrorData,
    ConfigurationError      => "Store Configuration Error",
    CreateStoreDirDenied    => "Creating store directory implicitely denied",
    FileError               => "File Error",
    IoError                 => "IO Error",
    IdLocked                => "ID locked",
    IdNotFound              => "ID not found",
    OutOfMemory             => "Out of Memory",
    FileNotFound            => "File corresponding to ID not found",
    FileNotCreated          => "File corresponding to ID could not be created",
    FileNotWritten          => "File corresponding to ID could not be written to",
    FileNotSeeked           => "File corresponding to ID could not be seeked",
    StorePathExists         => "Store path exists",
    StorePathCreate         => "Store path create",
    LockError               => "Error locking datastructure",
    LockPoisoned            => "The internal Store Lock has been poisoned",
    EntryAlreadyBorrowed    => "Entry is already borrowed",
    EntryAlreadyExists      => "Entry already exists",
    MalformedEntry          => "Entry has invalid formatting, missing header",
    HeaderPathSyntaxError   => "Syntax error in accessor string",
    HeaderPathTypeFailure   => "Header has wrong type for path",
    HeaderKeyNotFound       => "Header Key not found",
    HeaderTypeFailure       => "Header type is wrong",
    HookRegisterError       => "Hook register error",
    AspectNameNotFoundError => "Aspect name not found",
    HookExecutionError      => "Hook execution error",
    PreHookExecuteError     => "Pre-Hook execution error",
    PostHookExecuteError    => "Post-Hook execution error",
    StorePathLacksVersion   => "The supplied store path has no version part",
    GlobError               => "glob() error",
    EncodingError           => "Encoding error",
    StorePathError          => "Store Path error",
    EntryRenameError        => "Entry rename error",
    StoreIdHandlingError    => "StoreId handling error",

    CreateCallError            => "Error when calling create()",
    RetrieveCallError          => "Error when calling retrieve()",
    GetCallError               => "Error when calling get()",
    GetAllVersionsCallError    => "Error when calling get_all_versions()",
    RetrieveForModuleCallError => "Error when calling retrieve_for_module()",
    UpdateCallError            => "Error when calling update()",
    RetrieveCopyCallError      => "Error when calling retrieve_copy()",
    DeleteCallError            => "Error when calling delete()",
    MoveCallError              => "Error when calling move()",
    MoveByIdCallError          => "Error when calling move_by_id()"
);

generate_result_helper!(StoreError, StoreErrorKind);
generate_option_helper!(StoreError, StoreErrorKind);

generate_custom_error_types!(ParserError, ParserErrorKind, CustomErrorData,
    TOMLParserErrors    => "Several TOML-Parser-Errors",
    MissingMainSection  => "Missing main section",
    MissingVersionInfo  => "Missing version information in main section",
    NonTableInBaseTable => "A non-table was found in the base table",
    HeaderInconsistency => "The header is inconsistent"
);

impl From<ParserError> for StoreError {
    fn from(ps: ParserError) -> StoreError {
        StoreError {
            err_type: StoreErrorKind::MalformedEntry,
            cause: Some(Box::new(ps)),
            custom_data: None,
        }
    }
}

impl From<::std::io::Error> for StoreError {
    fn from(ps: ::std::io::Error) -> StoreError {
        StoreError {
            err_type: StoreErrorKind::IoError,
            cause: Some(Box::new(ps)),
            custom_data: None,
        }
    }
}

<|endoftext|>


<commit_before><commit_msg>Improve check_flush_st documentation<commit_after><|endoftext|>


<commit_before><commit_msg>style: Report missing include filename in ServoBindings.toml.<commit_after><|endoftext|>


<commit_before><commit_msg>vec: reduce capacity in `shrink_to_fit`<commit_after><|endoftext|>


<commit_before><commit_msg>Add regression test for thread local static mut borrows<commit_after>// Copyright 2016 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.
//
// run-pass
//
// FIXME(#54366) - We probably shouldn't allow #[thread_local] static mut to get a 'static lifetime.

#![feature(nll)]
#![feature(thread_local)]

#[thread_local]
static mut X1: u64 = 0;

struct S1 {
    a: &'static mut u64,
}

impl S1 {
    fn new(_x: u64) -> S1 {
        S1 {
            a: unsafe { &mut X1 },
        }
    }
}

fn main() {
    S1::new(0).a;
}
<|endoftext|>


<commit_before><commit_msg>Prettify error messages<commit_after><|endoftext|>


<commit_before><commit_msg>archive.rs<commit_after>// extern crate csv;
// extern crate diesel;
// #[macro_use]
// extern crate serde_derive;

// #[derive(Debug, Serialize)]
// struct Record {
//     pub id: String,
//     pub html: String,
//     pub political: i32,
//     pub not_political: i32,
//     pub title: String,
//     pub message: String,
//     pub thumbnail: String,
//     pub created_at: DateTime<Utc>,
//     pub updated_at: DateTime<Utc>,
//     pub lang: String,
//     pub images: Vec<String>,
//     pub impressions: i32,
//     pub political_probability: f64,
//     pub targeting: Option<String>,
//     #[serde(skip_serializing)]
//     pub suppressed: bool,
//     pub targets: Option<String>,
//     pub advertiser: Option<String>,
//     pub entities: Option<String>,
//     pub page: Option<String>,
// }
fn main() {}
<|endoftext|>


<commit_before>use emulator::Emulator;
use emulator::AvrDataMemory;
use emulator::get_register_index;
use emulator::hex_to_int;

pub fn perform<'a>(emulator: &Emulator<'a>, a: &str, rd: &str) -> Emulator<'a> {
    let rd_index = get_register_index(rd);
    let io_address = hex_to_int(a);

    ///////////////////////////////////////////////////
    // Update IO Address //////////////////////////////
    ///////////////////////////////////////////////////

    let registers = &emulator.data_memory.registers;
    let mut new_io = emulator.data_memory.io.to_vec();
    println!("IO Adress: {}", io_address);
    new_io[io_address as usize] = registers[rd_index];

    ///////////////////////////////////////////////////
    // Build and return new emulator state ////////////
    ///////////////////////////////////////////////////
    let data_memory = &emulator.data_memory;
    Emulator {
        data_memory: AvrDataMemory {
            registers: data_memory.registers.to_vec(),
            io: new_io,
            ram: data_memory.ram.to_vec()
        },
        program_pointer: &emulator.program_pointer+1,
        machine_code: emulator.machine_code.clone()
    }

}

#[cfg(test)]
mod tests {
  use avr_bit_vec;
  use emulator::Emulator;

  use super::*;

  #[test]
  fn can_perform() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 8;
      emulator = perform(&emulator, "$18", "r1");
      let portb = avr_bit_vec::from_u8(emulator.data_memory.io[0x18]);
      assert_eq!(8, avr_bit_vec::to_u8(portb));
  }

  #[test]
  fn updates_program_pointer() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 8;
      emulator = perform(&emulator, "$18", "r1");
      assert_eq!(1, emulator.program_pointer);
      emulator = perform(&emulator, "$18", "r1");
      assert_eq!(2, emulator.program_pointer);
  }
}
<commit_msg>remove println<commit_after>use emulator::Emulator;
use emulator::AvrDataMemory;
use emulator::get_register_index;
use emulator::hex_to_int;

pub fn perform<'a>(emulator: &Emulator<'a>, a: &str, rd: &str) -> Emulator<'a> {
    let rd_index = get_register_index(rd);
    let io_address = hex_to_int(a);

    ///////////////////////////////////////////////////
    // Update IO Address //////////////////////////////
    ///////////////////////////////////////////////////

    let registers = &emulator.data_memory.registers;
    let mut new_io = emulator.data_memory.io.to_vec();
    new_io[io_address as usize] = registers[rd_index];

    ///////////////////////////////////////////////////
    // Build and return new emulator state ////////////
    ///////////////////////////////////////////////////
    let data_memory = &emulator.data_memory;
    Emulator {
        data_memory: AvrDataMemory {
            registers: data_memory.registers.to_vec(),
            io: new_io,
            ram: data_memory.ram.to_vec()
        },
        program_pointer: &emulator.program_pointer+1,
        machine_code: emulator.machine_code.clone()
    }

}

#[cfg(test)]
mod tests {
  use avr_bit_vec;
  use emulator::Emulator;

  use super::*;

  #[test]
  fn can_perform() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 8;
      emulator = perform(&emulator, "$18", "r1");
      let portb = avr_bit_vec::from_u8(emulator.data_memory.io[0x18]);
      assert_eq!(8, avr_bit_vec::to_u8(portb));
  }

  #[test]
  fn updates_program_pointer() {
      let program = "add r0,r0";
      let mut emulator = Emulator::new(program);

      emulator.data_memory.registers[1] = 8;
      emulator = perform(&emulator, "$18", "r1");
      assert_eq!(1, emulator.program_pointer);
      emulator = perform(&emulator, "$18", "r1");
      assert_eq!(2, emulator.program_pointer);
  }
}
<|endoftext|>


<commit_before><commit_msg>examples: add a new example list-pods<commit_after>extern crate kubeclient;
use kubeclient::prelude::*;
use kubeclient::errors::*;
use std::env;

fn run_list_pods() -> Result<i32> {
    // filename is set to $KUBECONFIG if the env var is available.
    // Otherwise it falls back to "admin.conf".
    let filename = env::var("KUBECONFIG").ok();
    let filename = filename
        .as_ref()
        .map(String::as_str)
        .and_then(|s| if s.is_empty() { None } else { Some(s) })
        .unwrap_or("admin.conf");
    let kube = Kubernetes::load_conf(filename)?;

    if kube.healthy()? {
        for pod in kube.pods().namespace("default").list(None)? {
            println!("found pod: {:?}", pod);
        }
    }

    Ok(0)
}

fn main() {
    match run_list_pods() {
        Ok(n) => println!("Success error code is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}
<|endoftext|>


<commit_before><commit_msg>Add glyph module (oops)<commit_after>// Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
// BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

use client::render::{self, Palette, Vertex2d};
use client::render::pipeline2d;
use common::wad::QPic;

use cgmath::Matrix4;
use failure::Error;
use gfx::{CommandBuffer, Encoder, Factory, IndexBuffer, Slice};
use gfx::handle::{Buffer, ShaderResourceView, Texture};
use gfx::pso::{PipelineData, PipelineState};
use gfx_device_gl::Resources;

const GLYPH_WIDTH: usize = 8;
const GLYPH_HEIGHT: usize = 8;
const GLYPH_COLS: usize = 16;
const GLYPH_ROWS: usize = 16;
const GLYPH_COUNT: usize = GLYPH_ROWS * GLYPH_COLS;
const GLYPH_TEXTURE_WIDTH: usize = GLYPH_WIDTH * GLYPH_COLS;
const GLYPH_TEXTURE_HEIGHT: usize = GLYPH_HEIGHT * GLYPH_ROWS;
const GLYPH_WIDTH_TEXCOORD: f32 = 1.0 / GLYPH_COLS as f32;
const GLYPH_HEIGHT_TEXCOORD: f32 = 1.0 / GLYPH_ROWS as f32;

#[derive(Debug)]
pub struct GlyphRenderer {
    vertex_buffer: Buffer<Resources, Vertex2d>,
    view: ShaderResourceView<Resources, [f32; 4]>,
}

impl GlyphRenderer {
    pub fn new<F>(factory: &mut F, qpic: &QPic, palette: &Palette) -> Result<GlyphRenderer, Error>
    where
        F: Factory<Resources>
    {
        ensure!(qpic.width() as usize == GLYPH_COLS * GLYPH_WIDTH, "bad width for glyph atlas ({})", qpic.width());
        ensure!(qpic.height() as usize == GLYPH_ROWS * GLYPH_HEIGHT, "bad height for glyph atlas ({})", qpic.height());

        // conchars use index 0 (black) for transparency, so substitute index 0xFF
        let indices: Vec<u8> = qpic.indices()
            .iter()
            .map(|i| if *i == 0 { 0xFF } else { *i })
            .collect();

        let (rgba, _fullbright) = palette.translate(&indices);

        let (_handle, view) = render::create_texture(
            factory,
            GLYPH_TEXTURE_WIDTH as u32,
            GLYPH_TEXTURE_HEIGHT as u32,
            &rgba,
        )?;

        // create a quad for each glyph
        // TODO: these could be indexed to save space and maybe get slightly better cache coherence
        let mut vertices = Vec::new();
        for row in 0..GLYPH_ROWS {
            for col in 0..GLYPH_COLS {
                for vert in &render::QUAD_VERTICES {
                    vertices.push(Vertex2d {
                        pos: vert.pos,
                        texcoord: [
                            (col as f32 + vert.texcoord[0]) * GLYPH_WIDTH_TEXCOORD,
                            (row as f32 + vert.texcoord[1]) * GLYPH_HEIGHT_TEXCOORD,
                        ],
                    });
                }
            }
        }

        use gfx::traits::FactoryExt;
        let vertex_buffer = factory.create_vertex_buffer(&vertices);

        Ok(GlyphRenderer {
            vertex_buffer,
            view,
        })
    }

    fn slice_for_glyph(&self, glyph_id: u8) -> Slice<Resources> {
        Slice {
            start: 0,
            end: 6,
            base_vertex: 6 * glyph_id as u32,
            instances: None,
            buffer: IndexBuffer::Auto,
        }
    }

    pub fn render_glyph<C>(
        &self,
        encoder: &mut Encoder<Resources, C>,
        pso: &PipelineState<Resources, <pipeline2d::Data<Resources> as PipelineData<Resources>>::Meta>,
        user_data: &mut pipeline2d::Data<Resources>,
        glyph_id: u8,
        display_width: u32,
        display_height: u32,
        position_x: i32,
        position_y: i32,
    ) -> Result<(), Error>
    where
        C: CommandBuffer<Resources>
    {
        user_data.vertex_buffer = self.vertex_buffer.clone();
        user_data.transform = render::screen_space_vertex_transform(
            display_width,
            display_height,
            GLYPH_WIDTH as u32,
            GLYPH_HEIGHT as u32,
            position_x,
            position_y,
        ).into();
        user_data.sampler.0 = self.view.clone();

        let slice = self.slice_for_glyph(glyph_id);

        encoder.draw(&slice, pso, user_data);

        Ok(())
    }
}
<|endoftext|>


<commit_before><commit_msg>Implement an ad-hoc case folding pass<commit_after>/*! Special casing for the purpose of hyphenation

Implemented here is a "refolding" pass which covers complementary case
mappings (rarely) required for the correct hyphenation of uppercase or
mixed-case words.

Patterns maintained by the TeX project are not generated in strict accordance
with Unicode case folding; rather, they include multiple concrete sequences
at the discretion of the pattern developer, under the assumption that words
may be lowercased with varying degrees of Unicode awareness.

Although the approach works quite well when matching against `str`, two
discrepancies remain:

- Firstly, folding may shift character boundaries, invalidating the indices
of opportunities found by our dictionaries, which are byte-based and have
no notion of `char`. Thus, any opportunity found in a folded word must be
mapped back to its correct position in the original, unfolded word.
- Secondly, patterns may not account for all concrete sequences that occur
when using `str::to_lowercase` as a loose folding pass.

A zealous solution would be to adopt proper caseless matching, and pre-fold
the bundled patterns. Presently, however, we rely on an ad-hoc remedy based
on supplementary case mappings.

# Supplementary case mappings

| uppercase            | lowercase            | refold
|----------------------|----------------------|----------------
|'İ' \u{130}, length 2 | "i\u{307}", length 3 | "i", length 1

The Turkish `İ` in its recomposed form is – to the author's knowledge –
the only codepoint which changes size when lowercased without normalization
or tailoring. It is thus necessary to fold it regardless of language or
context, because the equivalence-preserving lowercase "i\u{307}" not only
disrupts pattern matching – be it byte-based or char-based – but also
shifts and invalidates any opportunity arising after it.
*/

use std::borrow::Cow;
use std::borrow::Cow::*;

#[derive(Copy, Clone, Debug)]
pub struct Shift {
    index : usize,
    delta : isize
}

/// The opportunity `i`, index-corrected for use in the original string.
pub fn realign(i : usize, shifts : &[Shift]) -> usize {
    (i as isize - shift_at(i, shifts)) as usize
}

/// The shift at index `i` in the refolded string.
fn shift_at(i : usize, shifts : &[Shift]) -> isize {
    shifts.iter().rev()
        .find(|&&shift| i > shift.index)
        .map_or(0, |&shift| shift.delta)
}

fn shifts(word : &str) -> Vec<Shift> {
    word.match_indices("İ")
        .map(|(i, _)| (i, -1))
        .scan(0, |delta, (i, d)| {
            let index = i as isize + *delta;
            *delta += d;
            Some(Shift { index : index as usize, delta : *delta })
        }).collect()
}

/// Should the original string contain special-cased codepoints, refold it
/// for hyphenation and provide the induced index shifts. Otherwise, merely
/// ensure that it is lowercase.
pub fn refold(original : &str) -> (Cow<str>, Vec<Shift>) {
    if original.chars().any(|c| c.is_uppercase()) {
        let lowercase = original.to_lowercase();
        // There is only one code point which changes size when lowercased,
        // thus comparing string lengths is sufficient to determine whether
        // it was present in the original word.
        if original.len() != lowercase.len() {
            (Owned(refold_lowercase(&lowercase)), shifts(original))
        } else { (Owned(lowercase), vec![]) }
    } else { (Borrowed(original), vec![]) }
}

/// Substitute lowercase sequences that would interfere with hyphenation.
/// Canonical equivalence is not necessarily preserved.
fn refold_lowercase(lowercase : &str) -> String {
    lowercase.replace("i\u{307}", "i")
}
<|endoftext|>


<commit_before>use geom::point::Point2D;
use geom::size::Size2D;
use gfx::geometry::{au, px_to_au};
use libc::{c_void};
use font_library::FontLibrary;
use font::Font;
use glyph::Glyph;
use shaper::shape_text;

/// A single, unbroken line of text
struct TextRun {
    priv text: ~str,
    priv glyphs: ~[Glyph],
    priv size_: Size2D<au>,
    priv min_break_width_: au,
}

impl TextRun {
    /// The size of the entire TextRun
    fn size() -> Size2D<au> { self.size_ }
    fn min_break_width() -> au { self.min_break_width_ }

    // FIXME: Should be storing a reference to the Font inside
    // of the TextRun, but I'm hitting cycle collector bugs
    fn break_text(font: &Font, h_offset: au) -> ~[TextRun] {
        assert h_offset >= self.min_break_width();

        let mut runs = ~[];
        let mut curr_run = ~"";

        do iter_indivisible_slices(font, self.text) |slice| {
            let mut candidate = curr_run;

            if candidate.is_not_empty() {
                candidate += " "; // FIXME: just inserting spaces between words can't be right
            }

            candidate += slice;

            let glyphs = shape_text(font, candidate);
            let size = glyph_run_size(glyphs);
            if size.width <= self.min_break_width() {
                curr_run = candidate;
            } else {
                runs += [TextRun(font, curr_run)];
                curr_run = slice.to_str();
            }
        }

        if curr_run.is_not_empty() {
            runs += [TextRun(font, curr_run)];
        }

        return runs;
    }
}

fn TextRun(font: &Font, +text: ~str) -> TextRun {
    let glyphs = shape_text(font, text);
    let size = glyph_run_size(glyphs);
    let min_break_width = calc_min_break_width(font, text);

    TextRun {
        text: text,
        glyphs: shape_text(font, text),
        size_: size,
        min_break_width_: min_break_width
    }
}

fn glyph_run_size(glyphs: &[Glyph]) -> Size2D<au> {
    let height = px_to_au(20);
    let pen_start_x = px_to_au(0);
    let pen_start_y = height;
    let pen_start = Point2D(pen_start_x, pen_start_y);
    let pen_end = glyphs.foldl(pen_start, |cur, glyph| {
        Point2D(cur.x.add(glyph.pos.offset.x).add(glyph.pos.advance.x),
                cur.y.add(glyph.pos.offset.y).add(glyph.pos.advance.y))
    });
    return Size2D(pen_end.x, pen_end.y);
}

/// Discovers the width of the largest indivisible substring
fn calc_min_break_width(font: &Font, text: &str) -> au {
    let mut max_piece_width = au(0);
    do iter_indivisible_slices(font, text) |slice| {
        let glyphs = shape_text(font, slice);
        let size = glyph_run_size(glyphs);
        if size.width > max_piece_width {
            max_piece_width = size.width
        }
    }
    return max_piece_width;
}

/// Iterates over all the indivisible substrings
fn iter_indivisible_slices(font: &Font, text: &r/str,
                           f: fn((&r/str))) {

    let mut curr = text;
    loop {
        match str::find(curr, |c| !char::is_whitespace(c) ) {
          Some(idx) => {
            curr = str::view(curr, idx, curr.len());
          }
          None => {
            // Everything else is whitespace
            break
          }
        }

        match str::find(curr, |c| char::is_whitespace(c) ) {
          Some(idx) => {
            let piece = str::view(curr, 0, idx);
            f(piece);
            curr = str::view(curr, idx, curr.len());
          }
          None => {
            assert curr.is_not_empty();
            f(curr);
            // This is the end of the string
            break;
          }
        }
    }
}

#[test]
fn test_calc_min_break_width1() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let actual = calc_min_break_width(font, ~"firecracker");
    let expected = px_to_au(84);
    assert expected == actual;
}

#[test]
fn test_calc_min_break_width2() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let actual = calc_min_break_width(font, ~"firecracker yumyum");
    let expected = px_to_au(84);
    assert expected == actual;
}

#[test]
fn test_calc_min_break_width3() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let actual = calc_min_break_width(font, ~"yumyum firecracker");
    let expected = px_to_au(84);
    assert expected == actual;
}

#[test]
fn test_calc_min_break_width4() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let actual = calc_min_break_width(font, ~"yumyum firecracker yumyum");
    let expected = px_to_au(84);
    assert expected == actual;
}

#[test]
fn test_iter_indivisible_slices() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let mut slices = ~[];
    do iter_indivisible_slices(font, "firecracker yumyum woopwoop") |slice| {
        slices += [slice];
    }
    assert slices == ~["firecracker", "yumyum", "woopwoop"];
}

#[test]
fn test_iter_indivisible_slices_trailing_whitespace() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let mut slices = ~[];
    do iter_indivisible_slices(font, "firecracker  ") |slice| {
        slices += [slice];
    }
    assert slices == ~["firecracker"];
}

#[test]
fn test_iter_indivisible_slices_leading_whitespace() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let mut slices = ~[];
    do iter_indivisible_slices(font, "  firecracker") |slice| {
        slices += [slice];
    }
    assert slices == ~["firecracker"];
}

#[test]
fn test_iter_indivisible_slices_empty() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let mut slices = ~[];
    do iter_indivisible_slices(font, "") |slice| {
        slices += [slice];
    }
    assert slices == ~[];
}

#[test]
fn test_break_text_simple() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let run = TextRun(font, ~"firecracker yumyum");
    let break_runs = run.break_text(font, run.min_break_width());
    assert break_runs[0].text == ~"firecracker";
    assert break_runs[1].text == ~"yumyum";
}

#[test]
fn test_break_text2() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let run = TextRun(font, ~"firecracker yum yum");
    let break_runs = run.break_text(font, run.min_break_width());
    assert break_runs[0].text == ~"firecracker";
    assert break_runs[1].text == ~"yum yum";
}

fn should_calculate_the_total_size() {
    #[test];
    #[ignore(cfg(target_os = "macos"))];

    let flib = FontLibrary();
    let font = flib.get_test_font();
    let run = TextRun(font, ~"firecracker");
    let expected = Size2D(px_to_au(84), px_to_au(20));
    assert run.size() == expected;
}

<commit_msg>Change TextRun.break_text to TextRun.split<commit_after>use geom::point::Point2D;
use geom::size::Size2D;
use gfx::geometry::{au, px_to_au};
use libc::{c_void};
use font_library::FontLibrary;
use font::Font;
use glyph::Glyph;
use shaper::shape_text;

/// A single, unbroken line of text
struct TextRun {
    priv text: ~str,
    priv glyphs: ~[Glyph],
    priv size_: Size2D<au>,
    priv min_break_width_: au,
}

impl TextRun {
    /// The size of the entire TextRun
    fn size() -> Size2D<au> { self.size_ }
    fn min_break_width() -> au { self.min_break_width_ }

    /// Split a run of text in two
    // FIXME: Should be storing a reference to the Font inside
    // of the TextRun, but I'm hitting cycle collector bugs
    fn split(font: &Font, h_offset: au) -> (TextRun, TextRun) {
        assert h_offset >= self.min_break_width();
        assert h_offset <= self.size_.width;

        let mut curr_run = ~"";

        for iter_indivisible_slices(font, self.text) |slice| {
            let mut candidate = curr_run;

            if candidate.is_not_empty() {
                candidate += " "; // FIXME: just inserting spaces between words can't be right
            }

            candidate += slice;

            let glyphs = shape_text(font, candidate);
            let size = glyph_run_size(glyphs);
            if size.width <= h_offset {
                curr_run = candidate;
            } else {
                break;
            }
        }

        assert curr_run.is_not_empty();

        let first = move curr_run;
        let second = str::slice(self.text, first.len(), self.text.len());
        let second = second.trim_left();
        return (TextRun(font, first), TextRun(font, second));
    }
}

fn TextRun(font: &Font, +text: ~str) -> TextRun {
    let glyphs = shape_text(font, text);
    let size = glyph_run_size(glyphs);
    let min_break_width = calc_min_break_width(font, text);

    TextRun {
        text: text,
        glyphs: shape_text(font, text),
        size_: size,
        min_break_width_: min_break_width
    }
}

fn glyph_run_size(glyphs: &[Glyph]) -> Size2D<au> {
    let height = px_to_au(20);
    let pen_start_x = px_to_au(0);
    let pen_start_y = height;
    let pen_start = Point2D(pen_start_x, pen_start_y);
    let pen_end = glyphs.foldl(pen_start, |cur, glyph| {
        Point2D(cur.x.add(glyph.pos.offset.x).add(glyph.pos.advance.x),
                cur.y.add(glyph.pos.offset.y).add(glyph.pos.advance.y))
    });
    return Size2D(pen_end.x, pen_end.y);
}

/// Discovers the width of the largest indivisible substring
fn calc_min_break_width(font: &Font, text: &str) -> au {
    let mut max_piece_width = au(0);
    for iter_indivisible_slices(font, text) |slice| {
        let glyphs = shape_text(font, slice);
        let size = glyph_run_size(glyphs);
        if size.width > max_piece_width {
            max_piece_width = size.width
        }
    }
    return max_piece_width;
}

/// Iterates over all the indivisible substrings
fn iter_indivisible_slices(font: &Font, text: &r/str,
                           f: fn((&r/str)) -> bool) {

    let mut curr = text;
    loop {
        match str::find(curr, |c| !char::is_whitespace(c) ) {
          Some(idx) => {
            curr = str::view(curr, idx, curr.len());
          }
          None => {
            // Everything else is whitespace
            break
          }
        }

        match str::find(curr, |c| char::is_whitespace(c) ) {
          Some(idx) => {
            let piece = str::view(curr, 0, idx);
            if !f(piece) { break }
            curr = str::view(curr, idx, curr.len());
          }
          None => {
            assert curr.is_not_empty();
            if !f(curr) { break }
            // This is the end of the string
            break;
          }
        }
    }
}

#[test]
fn test_calc_min_break_width1() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let actual = calc_min_break_width(font, ~"firecracker");
    let expected = px_to_au(84);
    assert expected == actual;
}

#[test]
fn test_calc_min_break_width2() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let actual = calc_min_break_width(font, ~"firecracker yumyum");
    let expected = px_to_au(84);
    assert expected == actual;
}

#[test]
fn test_calc_min_break_width3() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let actual = calc_min_break_width(font, ~"yumyum firecracker");
    let expected = px_to_au(84);
    assert expected == actual;
}

#[test]
fn test_calc_min_break_width4() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let actual = calc_min_break_width(font, ~"yumyum firecracker yumyum");
    let expected = px_to_au(84);
    assert expected == actual;
}

#[test]
fn test_iter_indivisible_slices() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let mut slices = ~[];
    for iter_indivisible_slices(font, "firecracker yumyum woopwoop") |slice| {
        slices += [slice];
    }
    assert slices == ~["firecracker", "yumyum", "woopwoop"];
}

#[test]
fn test_iter_indivisible_slices_trailing_whitespace() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let mut slices = ~[];
    for iter_indivisible_slices(font, "firecracker  ") |slice| {
        slices += [slice];
    }
    assert slices == ~["firecracker"];
}

#[test]
fn test_iter_indivisible_slices_leading_whitespace() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let mut slices = ~[];
    for iter_indivisible_slices(font, "  firecracker") |slice| {
        slices += [slice];
    }
    assert slices == ~["firecracker"];
}

#[test]
fn test_iter_indivisible_slices_empty() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let mut slices = ~[];
    for iter_indivisible_slices(font, "") |slice| {
        slices += [slice];
    }
    assert slices == ~[];
}

#[test]
fn test_split() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let run = TextRun(font, ~"firecracker yumyum");
    let break_runs = run.split(font, run.min_break_width());
    assert break_runs.first().text == ~"firecracker";
    assert break_runs.second().text == ~"yumyum";
}

#[test]
fn test_split2() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let run = TextRun(font, ~"firecracker yum yum yum yum yum");
    let break_runs = run.split(font, run.min_break_width());
    assert break_runs.first().text == ~"firecracker";
    assert break_runs.second().text == ~"yum yum yum yum yum";
}

#[test]
fn test_split3() {
    let flib = FontLibrary();
    let font = flib.get_test_font();
    let run = TextRun(font, ~"firecracker firecracker");
    let break_runs = run.split(font, run.min_break_width() + px_to_au(10));
    assert break_runs.first().text == ~"firecracker";
    assert break_runs.second().text == ~"firecracker";

}

fn should_calculate_the_total_size() {
    #[test];
    #[ignore(cfg(target_os = "macos"))];

    let flib = FontLibrary();
    let font = flib.get_test_font();
    let run = TextRun(font, ~"firecracker");
    let expected = Size2D(px_to_au(84), px_to_au(20));
    assert run.size() == expected;
}

<|endoftext|>


<commit_before><commit_msg>GH-ISSUE: #68 Put the packages part of the package_manager_command() fuction as an option<commit_after><|endoftext|>


<commit_before><commit_msg>refactor(mod): use to_owned instead of clone<commit_after><|endoftext|>


<commit_before><commit_msg>Modify `parse_tts_helper()` to avoid using auxiliary macro `match_slice`. Add some comments.<commit_after><|endoftext|>


<commit_before><commit_msg>fix unix process mutex harder<commit_after><|endoftext|>


<commit_before><commit_msg>style(scanner): rustfmt<commit_after><|endoftext|>


<commit_before><commit_msg>Add example to test fuzzingclient in Autobahn<commit_after>
extern crate mio_websocket;

use std::net::SocketAddr;

use mio_websocket::interface::*;

fn main() {
    let mut ws = WebSocket::new("127.0.0.1:9002".parse::<SocketAddr>().unwrap());

    loop {
        match ws.next() {
            event @ WebSocketEvent::TextMessage(_, _) |
            event @ WebSocketEvent::BinaryMessage(_, _) => {
                // Echo back the message that we have received.
                ws.send(event);
            },
            _ => {}
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>reserved_ids moqt test<commit_after>use moqt_core::{impl_, unsafe_, self_};

#[test]
fn reserved_ids() {
    let x: impl_ = impl_::trait_;
    assert_eq!(x.to_int(), 0);
    assert_eq!(impl_::use_.to_int(), 1);
    assert_eq!(impl_::crate_.to_int(), 1);
    assert_eq!(impl_::last.to_int(), -1);

    unsafe {
        let mut obj = unsafe_::new();
        assert_eq!(obj.loop_(), 1);
        obj.yield_(1);
        assert_eq!(obj.pub_().loop_(), 1);

        obj.set_super(2.4);
        assert_eq!(obj.super_(), 2.4);

        self_::box_(22);
    }
}
<|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.

pub static rc_base_field_refcnt: uint = 0u;

pub static task_field_refcnt: uint = 0u;

pub static task_field_stk: uint = 2u;

pub static task_field_runtime_sp: uint = 3u;

pub static task_field_rust_sp: uint = 4u;

pub static task_field_gc_alloc_chain: uint = 5u;

pub static task_field_dom: uint = 6u;

pub static n_visible_task_fields: uint = 7u;

pub static dom_field_interrupt_flag: uint = 1u;

pub static frame_glue_fns_field_mark: uint = 0u;

pub static frame_glue_fns_field_drop: uint = 1u;

pub static frame_glue_fns_field_reloc: uint = 2u;

pub static box_field_refcnt: uint = 0u;
pub static box_field_tydesc: uint = 1u;
pub static box_field_prev: uint = 2u;
pub static box_field_next: uint = 3u;
pub static box_field_body: uint = 4u;

pub static general_code_alignment: uint = 16u;

pub static tydesc_field_size: uint = 0u;
pub static tydesc_field_align: uint = 1u;
pub static tydesc_field_take_glue: uint = 2u;
pub static tydesc_field_drop_glue: uint = 3u;
pub static tydesc_field_free_glue: uint = 4u;
pub static tydesc_field_visit_glue: uint = 5u;
pub static tydesc_field_shape: uint = 6u;
pub static tydesc_field_shape_tables: uint = 7u;
pub static n_tydesc_fields: uint = 8u;

// The two halves of a closure: code and environment.
pub static fn_field_code: uint = 0u;
pub static fn_field_box: uint = 1u;

// The two fields of a trait object/trait instance: vtable and box.
// The vtable contains the type descriptor as first element.
pub static trt_field_vtable: uint = 0u;
pub static trt_field_box: uint = 1u;

pub static vec_elt_fill: uint = 0u;

pub static vec_elt_alloc: uint = 1u;

pub static vec_elt_elems: uint = 2u;

pub static slice_elt_base: uint = 0u;
pub static slice_elt_len: uint = 1u;

pub static worst_case_glue_call_args: uint = 7u;

pub static abi_version: uint = 1u;

pub fn memcpy_glue_name() -> ~str { return ~"rust_memcpy_glue"; }

pub fn bzero_glue_name() -> ~str { return ~"rust_bzero_glue"; }

pub fn yield_glue_name() -> ~str { return ~"rust_yield_glue"; }

pub fn no_op_type_glue_name() -> ~str { return ~"rust_no_op_type_glue"; }
<commit_msg>abi: remove dead code<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.

pub static rc_base_field_refcnt: uint = 0u;

pub static task_field_refcnt: uint = 0u;

pub static task_field_stk: uint = 2u;

pub static task_field_runtime_sp: uint = 3u;

pub static task_field_rust_sp: uint = 4u;

pub static task_field_gc_alloc_chain: uint = 5u;

pub static task_field_dom: uint = 6u;

pub static n_visible_task_fields: uint = 7u;

pub static dom_field_interrupt_flag: uint = 1u;

pub static frame_glue_fns_field_mark: uint = 0u;

pub static frame_glue_fns_field_drop: uint = 1u;

pub static frame_glue_fns_field_reloc: uint = 2u;

pub static box_field_refcnt: uint = 0u;
pub static box_field_tydesc: uint = 1u;
pub static box_field_prev: uint = 2u;
pub static box_field_next: uint = 3u;
pub static box_field_body: uint = 4u;

pub static general_code_alignment: uint = 16u;

pub static tydesc_field_size: uint = 0u;
pub static tydesc_field_align: uint = 1u;
pub static tydesc_field_take_glue: uint = 2u;
pub static tydesc_field_drop_glue: uint = 3u;
pub static tydesc_field_free_glue: uint = 4u;
pub static tydesc_field_visit_glue: uint = 5u;
pub static tydesc_field_shape: uint = 6u;
pub static tydesc_field_shape_tables: uint = 7u;
pub static n_tydesc_fields: uint = 8u;

// The two halves of a closure: code and environment.
pub static fn_field_code: uint = 0u;
pub static fn_field_box: uint = 1u;

// The two fields of a trait object/trait instance: vtable and box.
// The vtable contains the type descriptor as first element.
pub static trt_field_vtable: uint = 0u;
pub static trt_field_box: uint = 1u;

pub static vec_elt_fill: uint = 0u;

pub static vec_elt_alloc: uint = 1u;

pub static vec_elt_elems: uint = 2u;

pub static slice_elt_base: uint = 0u;
pub static slice_elt_len: uint = 1u;

pub static worst_case_glue_call_args: uint = 7u;

pub static abi_version: uint = 1u;
<|endoftext|>


<commit_before><commit_msg>Remove NotificationPowerLevels::is_default<commit_after><|endoftext|>


<commit_before>use std;
import std::task;

#[test]
#[ignore]
fn test_sleep() { task::sleep(1000000u); }

#[test]
fn test_unsupervise() {
  fn f() {
    task::unsupervise();
    fail;
  }
  spawn f();
}

#[test]
fn test_join() {
  fn winner() {
  }

  auto wintask = spawn winner();

  assert task::join(wintask) == task::tr_success;

  fn failer() {
    task::unsupervise();
    fail;
  }

  auto failtask = spawn failer();

  assert task::join(failtask) == task::tr_failure;
}
<commit_msg>Reindent lib-task.rs<commit_after>use std;
import std::task;

#[test]
#[ignore]
fn test_sleep() { task::sleep(1000000u); }

#[test]
fn test_unsupervise() {
    fn f() {
        task::unsupervise();
        fail;
    }
    spawn f();
}

#[test]
fn test_join() {
    fn winner() {
    }

    auto wintask = spawn winner();

    assert task::join(wintask) == task::tr_success;

    fn failer() {
        task::unsupervise();
        fail;
    }

    auto failtask = spawn failer();

    assert task::join(failtask) == task::tr_failure;
}
<|endoftext|>


<commit_before><commit_msg>Add imag-tag tests<commit_after><|endoftext|>


<commit_before><commit_msg>init: write template file<commit_after><|endoftext|>


<commit_before>// Dynamic Vector
//
// A growable vector that makes use of unique pointers so that the
// result can be sent between tasks and so forth.
//
// Note that recursive use is not permitted.

import dvec_iter::extensions;
import unsafe::reinterpret_cast;
import ptr::{null, extensions};

export dvec;
export from_vec;
export extensions;
export unwrap;

#[doc = "

A growable, modifiable vector type that accumulates elements into a
unique vector.

# Limitations on recursive use

This class works by swapping the unique vector out of the data
structure whenever it is to be used.  Therefore, recursive use is not
permitted.  That is, while iterating through a vector, you cannot
access the vector in any other way or else the program will fail.  If
you wish, you can use the `swap()` method to gain access to the raw
vector and transform it or use it any way you like.  Eventually, we
may permit read-only access during iteration or other use.

# WARNING

For maximum performance, this type is implemented using some rather
unsafe code.  In particular, this innocent looking `[mut A]/~` pointer
*may be null!*  Therefore, it is important you not reach into the
data structure manually but instead use the provided extensions.

The reason that I did not use an unsafe pointer in the structure
itself is that I wanted to ensure that the vector would be freed when
the dvec is dropped.  The reason that I did not use an `option<T>`
instead of a nullable pointer is that I found experimentally that it
becomes approximately 50% slower. This can probably be improved
through optimization.  You can run your own experiments using
`src/test/bench/vec-append.rs`. My own tests found that using null
pointers achieved about 103 million pushes/second.  Using an option
type could only produce 47 million pushes/second.

"]
type dvec<A> = {
    mut data: ~[mut A]
};

#[doc = "Creates a new, empty dvec"]
fn dvec<A>() -> dvec<A> {
    {mut data: ~[mut]}
}

#[doc = "Creates a new dvec with a single element"]
fn from_elt<A>(+e: A) -> dvec<A> {
    {mut data: ~[mut e]}
}

#[doc = "Creates a new dvec with the contents of a vector"]
fn from_vec<A>(+v: ~[mut A]) -> dvec<A> {
    {mut data: v}
}

#[doc = "Consumes the vector and returns its contents"]
fn unwrap<A>(-d: dvec<A>) -> ~[mut A] {
    let {data: v} <- d;
    ret v;
}

impl private_methods<A> for dvec<A> {
    fn check_not_borrowed() {
        unsafe {
            let data: *() = unsafe::reinterpret_cast(self.data);
            if data.is_null() {
                fail "Recursive use of dvec";
            }
        }
    }

    #[inline(always)]
    fn borrow<B>(f: fn(-~[mut A]) -> B) -> B {
        unsafe {
            let mut data = unsafe::reinterpret_cast(null::<()>());
            data <-> self.data;
            let data_ptr: *() = unsafe::reinterpret_cast(data);
            if data_ptr.is_null() { fail "Recursive use of dvec"; }
            ret f(data);
        }
    }

    #[inline(always)]
    fn return(-data: ~[mut A]) {
        unsafe {
            self.data <- data;
        }
    }
}

// In theory, most everything should work with any A, but in practice
// almost nothing works without the copy bound due to limitations
// around closures.
impl extensions<A> for dvec<A> {
    #[doc = "

    Swaps out the current vector and hands it off to a user-provided
    function `f`.  The function should transform it however is desired
    and return a new vector to replace it with.

    "]
    #[inline(always)]
    fn swap(f: fn(-~[mut A]) -> ~[mut A]) {
        self.borrow(|v| self.return(f(v)))
    }

    #[doc = "Returns the number of elements currently in the dvec"]
    fn len() -> uint {
        do self.borrow |v| {
            let l = v.len();
            self.return(v);
            l
        }
    }

    #[doc = "Overwrite the current contents"]
    fn set(+w: ~[mut A]) {
        self.check_not_borrowed();
        self.data <- w;
    }

    #[doc = "Remove and return the last element"]
    fn pop() -> A {
        do self.borrow |v| {
            let mut v <- v;
            let result = vec::pop(v);
            self.return(v);
            result
        }
    }

    #[doc = "Insert a single item at the front of the list"]
    fn unshift(-t: A) {
        unsafe {
            let mut data = unsafe::reinterpret_cast(null::<()>());
            data <-> self.data;
            let data_ptr: *() = unsafe::reinterpret_cast(data);
            if data_ptr.is_null() { fail "Recursive use of dvec"; }
            log(error, "a");
            self.data <- ~[mut t];
            vec::push_all_move(self.data, data);
            log(error, "b");
        }
    }

    #[doc = "Append a single item to the end of the list"]
    fn push(+t: A) {
        self.check_not_borrowed();
        vec::push(self.data, t);
    }

    #[doc = "Remove and return the first element"]
    fn shift() -> A {
        do self.borrow |v| {
            let mut v = vec::from_mut(v);
            let result = vec::shift(v);
            self.return(vec::to_mut(v));
            result
        }
    }
}

impl extensions<A:copy> for dvec<A> {
    #[doc = "
        Append all elements of a vector to the end of the list

        Equivalent to `append_iter()` but potentially more efficient.
    "]
    fn push_all(ts: &[const A]) {
        self.push_slice(ts, 0u, vec::len(ts));
    }

    #[doc = "
        Appends elements from `from_idx` to `to_idx` (exclusive)
    "]
    fn push_slice(ts: &[const A], from_idx: uint, to_idx: uint) {
        do self.swap |v| {
            let mut v <- v;
            let new_len = vec::len(v) + to_idx - from_idx;
            vec::reserve(v, new_len);
            let mut i = from_idx;
            while i < to_idx {
                vec::push(v, ts[i]);
                i += 1u;
            }
            v
        }
    }

    /*
    #[doc = "
        Append all elements of an iterable.

        Failure will occur if the iterable's `each()` method
        attempts to access this vector.
    "]
    fn append_iter<A, I:iter::base_iter<A>>(ts: I) {
        do self.swap |v| {
           let mut v = alt ts.size_hint() {
             none { v }
             some(h) {
               let len = v.len() + h;
               let mut v <- v;
               vec::reserve(v, len);
               v
            }
           };

        for ts.each |t| { vec::push(v, t) };
           v
        }
    }
    */

    #[doc = "
        Gets a copy of the current contents.

        See `unwrap()` if you do not wish to copy the contents.
    "]
    fn get() -> ~[A] {
        do self.borrow |v| {
            let w = vec::from_mut(copy v);
            self.return(v);
            w
        }
    }

    #[doc = "Copy out an individual element"]
    #[inline(always)]
    fn [](idx: uint) -> A {
        self.get_elt(idx)
    }

    #[doc = "Copy out an individual element"]
    #[inline(always)]
    fn get_elt(idx: uint) -> A {
        self.check_not_borrowed();
        ret self.data[idx];
    }

    #[doc = "Overwrites the contents of the element at `idx` with `a`"]
    fn set_elt(idx: uint, a: A) {
        self.check_not_borrowed();
        self.data[idx] = a;
    }

    #[doc = "Overwrites the contents of the element at `idx` with `a`,
    growing the vector if necessary.  New elements will be initialized
    with `initval`"]
    fn grow_set_elt(idx: uint, initval: A, val: A) {
        do self.swap |v| {
            let mut v <- v;
            vec::grow_set(v, idx, initval, val);
            v
        }
    }

    #[doc = "Returns the last element, failing if the vector is empty"]
    #[inline(always)]
    fn last() -> A {
        self.check_not_borrowed();

        let length = self.len();
        if length == 0u {
            fail "attempt to retrieve the last element of an empty vector";
        }

        ret self.data[length - 1u];
    }

    #[doc="Iterates over the elements in reverse order"]
    #[inline(always)]
    fn reach(f: fn(A) -> bool) {
        let length = self.len();
        let mut i = 0u;
        while i < length {
            if !f(self.get_elt(i)) {
                break;
            }
            i += 1u;
        }
    }
}
<commit_msg>Export dvec::from_elt.<commit_after>// Dynamic Vector
//
// A growable vector that makes use of unique pointers so that the
// result can be sent between tasks and so forth.
//
// Note that recursive use is not permitted.

import dvec_iter::extensions;
import unsafe::reinterpret_cast;
import ptr::{null, extensions};

export dvec;
export from_elt;
export from_vec;
export extensions;
export unwrap;

#[doc = "

A growable, modifiable vector type that accumulates elements into a
unique vector.

# Limitations on recursive use

This class works by swapping the unique vector out of the data
structure whenever it is to be used.  Therefore, recursive use is not
permitted.  That is, while iterating through a vector, you cannot
access the vector in any other way or else the program will fail.  If
you wish, you can use the `swap()` method to gain access to the raw
vector and transform it or use it any way you like.  Eventually, we
may permit read-only access during iteration or other use.

# WARNING

For maximum performance, this type is implemented using some rather
unsafe code.  In particular, this innocent looking `[mut A]/~` pointer
*may be null!*  Therefore, it is important you not reach into the
data structure manually but instead use the provided extensions.

The reason that I did not use an unsafe pointer in the structure
itself is that I wanted to ensure that the vector would be freed when
the dvec is dropped.  The reason that I did not use an `option<T>`
instead of a nullable pointer is that I found experimentally that it
becomes approximately 50% slower. This can probably be improved
through optimization.  You can run your own experiments using
`src/test/bench/vec-append.rs`. My own tests found that using null
pointers achieved about 103 million pushes/second.  Using an option
type could only produce 47 million pushes/second.

"]
type dvec<A> = {
    mut data: ~[mut A]
};

#[doc = "Creates a new, empty dvec"]
fn dvec<A>() -> dvec<A> {
    {mut data: ~[mut]}
}

#[doc = "Creates a new dvec with a single element"]
fn from_elt<A>(+e: A) -> dvec<A> {
    {mut data: ~[mut e]}
}

#[doc = "Creates a new dvec with the contents of a vector"]
fn from_vec<A>(+v: ~[mut A]) -> dvec<A> {
    {mut data: v}
}

#[doc = "Consumes the vector and returns its contents"]
fn unwrap<A>(-d: dvec<A>) -> ~[mut A] {
    let {data: v} <- d;
    ret v;
}

impl private_methods<A> for dvec<A> {
    fn check_not_borrowed() {
        unsafe {
            let data: *() = unsafe::reinterpret_cast(self.data);
            if data.is_null() {
                fail "Recursive use of dvec";
            }
        }
    }

    #[inline(always)]
    fn borrow<B>(f: fn(-~[mut A]) -> B) -> B {
        unsafe {
            let mut data = unsafe::reinterpret_cast(null::<()>());
            data <-> self.data;
            let data_ptr: *() = unsafe::reinterpret_cast(data);
            if data_ptr.is_null() { fail "Recursive use of dvec"; }
            ret f(data);
        }
    }

    #[inline(always)]
    fn return(-data: ~[mut A]) {
        unsafe {
            self.data <- data;
        }
    }
}

// In theory, most everything should work with any A, but in practice
// almost nothing works without the copy bound due to limitations
// around closures.
impl extensions<A> for dvec<A> {
    #[doc = "

    Swaps out the current vector and hands it off to a user-provided
    function `f`.  The function should transform it however is desired
    and return a new vector to replace it with.

    "]
    #[inline(always)]
    fn swap(f: fn(-~[mut A]) -> ~[mut A]) {
        self.borrow(|v| self.return(f(v)))
    }

    #[doc = "Returns the number of elements currently in the dvec"]
    fn len() -> uint {
        do self.borrow |v| {
            let l = v.len();
            self.return(v);
            l
        }
    }

    #[doc = "Overwrite the current contents"]
    fn set(+w: ~[mut A]) {
        self.check_not_borrowed();
        self.data <- w;
    }

    #[doc = "Remove and return the last element"]
    fn pop() -> A {
        do self.borrow |v| {
            let mut v <- v;
            let result = vec::pop(v);
            self.return(v);
            result
        }
    }

    #[doc = "Insert a single item at the front of the list"]
    fn unshift(-t: A) {
        unsafe {
            let mut data = unsafe::reinterpret_cast(null::<()>());
            data <-> self.data;
            let data_ptr: *() = unsafe::reinterpret_cast(data);
            if data_ptr.is_null() { fail "Recursive use of dvec"; }
            log(error, "a");
            self.data <- ~[mut t];
            vec::push_all_move(self.data, data);
            log(error, "b");
        }
    }

    #[doc = "Append a single item to the end of the list"]
    fn push(+t: A) {
        self.check_not_borrowed();
        vec::push(self.data, t);
    }

    #[doc = "Remove and return the first element"]
    fn shift() -> A {
        do self.borrow |v| {
            let mut v = vec::from_mut(v);
            let result = vec::shift(v);
            self.return(vec::to_mut(v));
            result
        }
    }
}

impl extensions<A:copy> for dvec<A> {
    #[doc = "
        Append all elements of a vector to the end of the list

        Equivalent to `append_iter()` but potentially more efficient.
    "]
    fn push_all(ts: &[const A]) {
        self.push_slice(ts, 0u, vec::len(ts));
    }

    #[doc = "
        Appends elements from `from_idx` to `to_idx` (exclusive)
    "]
    fn push_slice(ts: &[const A], from_idx: uint, to_idx: uint) {
        do self.swap |v| {
            let mut v <- v;
            let new_len = vec::len(v) + to_idx - from_idx;
            vec::reserve(v, new_len);
            let mut i = from_idx;
            while i < to_idx {
                vec::push(v, ts[i]);
                i += 1u;
            }
            v
        }
    }

    /*
    #[doc = "
        Append all elements of an iterable.

        Failure will occur if the iterable's `each()` method
        attempts to access this vector.
    "]
    fn append_iter<A, I:iter::base_iter<A>>(ts: I) {
        do self.swap |v| {
           let mut v = alt ts.size_hint() {
             none { v }
             some(h) {
               let len = v.len() + h;
               let mut v <- v;
               vec::reserve(v, len);
               v
            }
           };

        for ts.each |t| { vec::push(v, t) };
           v
        }
    }
    */

    #[doc = "
        Gets a copy of the current contents.

        See `unwrap()` if you do not wish to copy the contents.
    "]
    fn get() -> ~[A] {
        do self.borrow |v| {
            let w = vec::from_mut(copy v);
            self.return(v);
            w
        }
    }

    #[doc = "Copy out an individual element"]
    #[inline(always)]
    fn [](idx: uint) -> A {
        self.get_elt(idx)
    }

    #[doc = "Copy out an individual element"]
    #[inline(always)]
    fn get_elt(idx: uint) -> A {
        self.check_not_borrowed();
        ret self.data[idx];
    }

    #[doc = "Overwrites the contents of the element at `idx` with `a`"]
    fn set_elt(idx: uint, a: A) {
        self.check_not_borrowed();
        self.data[idx] = a;
    }

    #[doc = "Overwrites the contents of the element at `idx` with `a`,
    growing the vector if necessary.  New elements will be initialized
    with `initval`"]
    fn grow_set_elt(idx: uint, initval: A, val: A) {
        do self.swap |v| {
            let mut v <- v;
            vec::grow_set(v, idx, initval, val);
            v
        }
    }

    #[doc = "Returns the last element, failing if the vector is empty"]
    #[inline(always)]
    fn last() -> A {
        self.check_not_borrowed();

        let length = self.len();
        if length == 0u {
            fail "attempt to retrieve the last element of an empty vector";
        }

        ret self.data[length - 1u];
    }

    #[doc="Iterates over the elements in reverse order"]
    #[inline(always)]
    fn reach(f: fn(A) -> bool) {
        let length = self.len();
        let mut i = 0u;
        while i < length {
            if !f(self.get_elt(i)) {
                break;
            }
            i += 1u;
        }
    }
}
<|endoftext|>


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

/*!

Miscellaneous helpers for common patterns.

*/

use prelude::*;
use unstable::intrinsics;

/// The identity function.
#[inline(always)]
pub fn id<T>(x: T) -> T { x }

/// Ignores a value.
#[inline(always)]
pub fn ignore<T>(_x: T) { }

/// Sets `*ptr` to `new_value`, invokes `op()`, and then restores the
/// original value of `*ptr`.
///
/// NB: This function accepts `@mut T` and not `&mut T` to avoid
/// an obvious borrowck hazard. Typically passing in `&mut T` will
/// cause borrow check errors because it freezes whatever location
/// that `&mut T` is stored in (either statically or dynamically).
#[inline(always)]
pub fn with<T,R>(
    ptr: @mut T,
    value: T,
    op: &fn() -> R) -> R
{
    let prev = replace(ptr, value);
    let result = op();
    *ptr = prev;
    return result;
}

/**
 * Swap the values at two mutable locations of the same type, without
 * deinitialising or copying either one.
 */
#[inline(always)]
pub fn swap<T>(x: &mut T, y: &mut T) {
    unsafe {
        swap_ptr(ptr::to_mut_unsafe_ptr(x), ptr::to_mut_unsafe_ptr(y));
    }
}

/**
 * Swap the values at two mutable locations of the same type, without
 * deinitialising or copying either one.
 */
#[inline]
#[cfg(not(stage0))]
pub unsafe fn swap_ptr<T>(x: *mut T, y: *mut T) {
    if x == y { return }

    // Give ourselves some scratch space to work with
    let mut tmp: T = intrinsics::uninit();
    let t = ptr::to_mut_unsafe_ptr(&mut tmp);

    // Perform the swap
    ptr::copy_memory(t, x, 1);
    ptr::copy_memory(x, y, 1);
    ptr::copy_memory(y, t, 1);

    // y and t now point to the same thing, but we need to completely forget t
    // because it's no longer relevant.
    cast::forget(tmp);
}

/**
 * Swap the values at two mutable locations of the same type, without
 * deinitialising or copying either one.
 */
#[inline]
#[cfg(stage0)]
pub unsafe fn swap_ptr<T>(x: *mut T, y: *mut T) {
    if x == y { return }

    // Give ourselves some scratch space to work with
    let mut tmp: T = intrinsics::init();
    let t = ptr::to_mut_unsafe_ptr(&mut tmp);

    // Perform the swap
    ptr::copy_memory(t, x, 1);
    ptr::copy_memory(x, y, 1);
    ptr::copy_memory(y, t, 1);

    // y and t now point to the same thing, but we need to completely forget t
    // because it's no longer relevant.
    cast::forget(tmp);
}

/**
 * Replace the value at a mutable location with a new one, returning the old
 * value, without deinitialising or copying either one.
 */
#[inline(always)]
pub fn replace<T>(dest: &mut T, mut src: T) -> T {
    swap(dest, &mut src);
    src
}

/**
 * Replace the value at a mutable location with a new one, returning the old
 * value, without deinitialising or copying either one.
 */
#[inline(always)]
pub unsafe fn replace_ptr<T>(dest: *mut T, mut src: T) -> T {
    swap_ptr(dest, ptr::to_mut_unsafe_ptr(&mut src));
    src
}

/// A non-copyable dummy type.
pub struct NonCopyable {
    i: (),
}

impl Drop for NonCopyable {
    fn finalize(&self) { }
}

pub fn NonCopyable() -> NonCopyable { NonCopyable { i: () } }

/// A type with no inhabitants
pub enum Void { }

pub impl Void {
    /// A utility function for ignoring this uninhabited type
    fn uninhabited(&self) -> ! {
        match *self {
            // Nothing to match on
        }
    }
}

/**
A utility function for indicating unreachable code. It will fail if
executed. This is occasionally useful to put after loops that never
terminate normally, but instead directly return from a function.

# Example

~~~
fn choose_weighted_item(v: &[Item]) -> Item {
    assert!(!v.is_empty());
    let mut so_far = 0u;
    for v.each |item| {
        so_far += item.weight;
        if so_far > 100 {
            return item;
        }
    }
    // The above loop always returns, so we must hint to the
    // type checker that it isn't possible to get down here
    util::unreachable();
}
~~~

*/
pub fn unreachable() -> ! {
    fail!("internal error: entered unreachable code");
}

#[cfg(test)]
mod tests {
    use option::{None, Some};
    use util::{NonCopyable, id, replace, swap};

    #[test]
    pub fn identity_crisis() {
        // Writing a test for the identity function. How did it come to this?
        let x = ~[(5, false)];
        //FIXME #3387 assert!(x.eq(id(copy x)));
        let y = copy x;
        assert!(x.eq(&id(y)));
    }
    #[test]
    pub fn test_swap() {
        let mut x = 31337;
        let mut y = 42;
        swap(&mut x, &mut y);
        assert!(x == 42);
        assert!(y == 31337);
    }
    #[test]
    pub fn test_replace() {
        let mut x = Some(NonCopyable());
        let y = replace(&mut x, None);
        assert!(x.is_none());
        assert!(y.is_some());
    }
}
<commit_msg>auto merge of #6442 : sstewartgallus/rust/incoming, r=pcwalton<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.

/*!

Miscellaneous helpers for common patterns.

*/

use prelude::*;
use unstable::intrinsics;

/// The identity function.
#[inline(always)]
pub fn id<T>(x: T) -> T { x }

/// Ignores a value.
#[inline(always)]
pub fn ignore<T>(_x: T) { }

/// Sets `*ptr` to `new_value`, invokes `op()`, and then restores the
/// original value of `*ptr`.
///
/// NB: This function accepts `@mut T` and not `&mut T` to avoid
/// an obvious borrowck hazard. Typically passing in `&mut T` will
/// cause borrow check errors because it freezes whatever location
/// that `&mut T` is stored in (either statically or dynamically).
#[inline(always)]
pub fn with<T,R>(
    ptr: @mut T,
    value: T,
    op: &fn() -> R) -> R
{
    let prev = replace(ptr, value);
    let result = op();
    *ptr = prev;
    return result;
}

/**
 * Swap the values at two mutable locations of the same type, without
 * deinitialising or copying either one.
 */
#[inline(always)]
pub fn swap<T>(x: &mut T, y: &mut T) {
    unsafe {
        swap_ptr(ptr::to_mut_unsafe_ptr(x), ptr::to_mut_unsafe_ptr(y));
    }
}

/**
 * Swap the values at two mutable locations of the same type, without
 * deinitialising or copying either one.
 */
#[inline]
#[cfg(not(stage0))]
pub unsafe fn swap_ptr<T>(x: *mut T, y: *mut T) {
    if x == y { return }

    // Give ourselves some scratch space to work with
    let mut tmp: T = intrinsics::uninit();
    let t = ptr::to_mut_unsafe_ptr(&mut tmp);

    // Perform the swap
    ptr::copy_memory(t, x, 1);
    ptr::copy_memory(x, y, 1);
    ptr::copy_memory(y, t, 1);

    // y and t now point to the same thing, but we need to completely forget t
    // because it's no longer relevant.
    cast::forget(tmp);
}

/**
 * Swap the values at two mutable locations of the same type, without
 * deinitialising or copying either one.
 */
#[inline]
#[cfg(stage0)]
pub unsafe fn swap_ptr<T>(x: *mut T, y: *mut T) {
    if x == y { return }

    // Give ourselves some scratch space to work with
    let mut tmp: T = intrinsics::init();
    let t = ptr::to_mut_unsafe_ptr(&mut tmp);

    // Perform the swap
    ptr::copy_memory(t, x, 1);
    ptr::copy_memory(x, y, 1);
    ptr::copy_memory(y, t, 1);

    // y and t now point to the same thing, but we need to completely forget t
    // because it's no longer relevant.
    cast::forget(tmp);
}

/**
 * Replace the value at a mutable location with a new one, returning the old
 * value, without deinitialising or copying either one.
 */
#[inline(always)]
pub fn replace<T>(dest: &mut T, mut src: T) -> T {
    swap(dest, &mut src);
    src
}

/**
 * Replace the value at a mutable location with a new one, returning the old
 * value, without deinitialising or copying either one.
 */
#[inline(always)]
pub unsafe fn replace_ptr<T>(dest: *mut T, mut src: T) -> T {
    swap_ptr(dest, ptr::to_mut_unsafe_ptr(&mut src));
    src
}

/// A non-copyable dummy type.
pub struct NonCopyable {
    i: (),
}

impl Drop for NonCopyable {
    fn finalize(&self) { }
}

pub fn NonCopyable() -> NonCopyable { NonCopyable { i: () } }

/// A type with no inhabitants
pub enum Void { }

pub impl Void {
    /// A utility function for ignoring this uninhabited type
    fn uninhabited(self) -> ! {
        match self {
            // Nothing to match on
        }
    }
}

/**
A utility function for indicating unreachable code. It will fail if
executed. This is occasionally useful to put after loops that never
terminate normally, but instead directly return from a function.

# Example

~~~
fn choose_weighted_item(v: &[Item]) -> Item {
    assert!(!v.is_empty());
    let mut so_far = 0u;
    for v.each |item| {
        so_far += item.weight;
        if so_far > 100 {
            return item;
        }
    }
    // The above loop always returns, so we must hint to the
    // type checker that it isn't possible to get down here
    util::unreachable();
}
~~~

*/
pub fn unreachable() -> ! {
    fail!("internal error: entered unreachable code");
}

#[cfg(test)]
mod tests {
    use option::{None, Some};
    use util::{Void, NonCopyable, id, replace, swap};
    use either::{Either, Left, Right};

    #[test]
    pub fn identity_crisis() {
        // Writing a test for the identity function. How did it come to this?
        let x = ~[(5, false)];
        //FIXME #3387 assert!(x.eq(id(copy x)));
        let y = copy x;
        assert!(x.eq(&id(y)));
    }
    #[test]
    pub fn test_swap() {
        let mut x = 31337;
        let mut y = 42;
        swap(&mut x, &mut y);
        assert!(x == 42);
        assert!(y == 31337);
    }
    #[test]
    pub fn test_replace() {
        let mut x = Some(NonCopyable());
        let y = replace(&mut x, None);
        assert!(x.is_none());
        assert!(y.is_some());
    }
    #[test]
    pub fn test_uninhabited() {
        let could_only_be_coin : Either <Void, ()> = Right (());
        match could_only_be_coin {
            Right (coin) => coin,
            Left (is_void) => is_void.uninhabited ()
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Move packet structure documentation to the relevant struct definitions<commit_after><|endoftext|>


<commit_before>

// Simple ANSI color library.
//
// TODO: Windows support.
const u8 color_black = 0u8;

const u8 color_red = 1u8;

const u8 color_green = 2u8;

const u8 color_yellow = 3u8;

const u8 color_blue = 4u8;

const u8 color_magenta = 5u8;

const u8 color_cyan = 6u8;

const u8 color_light_gray = 7u8;

const u8 color_light_grey = 7u8;

const u8 color_dark_gray = 8u8;

const u8 color_dark_grey = 8u8;

const u8 color_bright_red = 9u8;

const u8 color_bright_green = 10u8;

const u8 color_bright_yellow = 11u8;

const u8 color_bright_blue = 12u8;

const u8 color_bright_magenta = 13u8;

const u8 color_bright_cyan = 14u8;

const u8 color_bright_white = 15u8;

fn esc(io::buf_writer writer) { writer.write([0x1bu8, '[' as u8]); }

fn reset(io::buf_writer writer) {
    esc(writer);
    writer.write(['0' as u8, 'm' as u8]);
}

fn color_supported() -> bool {
    auto supported_terms = ["xterm-color",
                            "screen-bce"];
    ret alt (generic_os::getenv("TERM")) {
        case (option::some(?env)) {
            vec::member(env, supported_terms)
        }
        case (option::none) {
            false
        }
    };
}

fn set_color(io::buf_writer writer, u8 first_char, u8 color) {
    assert (color < 16u8);
    esc(writer);
    if (color >= 8u8) { writer.write(['1' as u8, ';' as u8]); color -= 8u8; }
    writer.write([first_char, ('0' as u8) + color, 'm' as u8]);
}

fn fg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '3' as u8, color);
}

fn bg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '4' as u8, color);
}
// export fg;
// export bg;

// Local Variables:
// 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>Add xterm to the term lib's list of supported terms.<commit_after>

// Simple ANSI color library.
//
// TODO: Windows support.
const u8 color_black = 0u8;

const u8 color_red = 1u8;

const u8 color_green = 2u8;

const u8 color_yellow = 3u8;

const u8 color_blue = 4u8;

const u8 color_magenta = 5u8;

const u8 color_cyan = 6u8;

const u8 color_light_gray = 7u8;

const u8 color_light_grey = 7u8;

const u8 color_dark_gray = 8u8;

const u8 color_dark_grey = 8u8;

const u8 color_bright_red = 9u8;

const u8 color_bright_green = 10u8;

const u8 color_bright_yellow = 11u8;

const u8 color_bright_blue = 12u8;

const u8 color_bright_magenta = 13u8;

const u8 color_bright_cyan = 14u8;

const u8 color_bright_white = 15u8;

fn esc(io::buf_writer writer) { writer.write([0x1bu8, '[' as u8]); }

fn reset(io::buf_writer writer) {
    esc(writer);
    writer.write(['0' as u8, 'm' as u8]);
}

fn color_supported() -> bool {
    auto supported_terms = ["xterm-color",
                            "xterm",
                            "screen-bce"];
    ret alt (generic_os::getenv("TERM")) {
        case (option::some(?env)) {
            vec::member(env, supported_terms)
        }
        case (option::none) {
            false
        }
    };
}

fn set_color(io::buf_writer writer, u8 first_char, u8 color) {
    assert (color < 16u8);
    esc(writer);
    if (color >= 8u8) { writer.write(['1' as u8, ';' as u8]); color -= 8u8; }
    writer.write([first_char, ('0' as u8) + color, 'm' as u8]);
}

fn fg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '3' as u8, color);
}

fn bg(io::buf_writer writer, u8 color) {
    ret set_color(writer, '4' as u8, color);
}
// export fg;
// export bg;

// Local Variables:
// 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><commit_msg>stacks_and_queues: partially implement LinkedDeque<commit_after>use std::mem;
use std::ptr;
use super::Deque;

struct Rawlink<T> {
    p: *mut T
}

impl<T> Rawlink<T> {
    fn none() -> Rawlink<T> {
        Rawlink { p: ptr::null_mut() }
    }

    fn some(n: &mut T) -> Rawlink<T> {
        Rawlink { p: n }
    }

    fn take(&mut self) -> Rawlink<T> {
        mem::replace(self, Rawlink::none())
    }
}

struct Node<T> {
    item: T,
    next: Option<Box<Node<T>>>,
    prev: Rawlink<Node<T>>

}

impl<T> Node<T> {
    /// work around for moved value
    fn into_item_and_pointers(self) -> (T, Option<Box<Node<T>>>, Rawlink<Node<T>>) {
        (self.item, self.next, self.prev)
    }

    fn size(&self) -> usize {
        let mut p = self.next.as_ref();
        let mut sz = 0;
        while p.is_some() {
            p = p.unwrap().next.as_ref();
            sz += 1;
        }
        sz
    }
}

pub struct LinkedDeque<T> {
    first: Option<Box<Node<T>>>,
    last: Rawlink<Node<T>>
}

impl<T> Deque<T> for LinkedDeque<T> {
    fn new() -> LinkedDeque<T> {
        LinkedDeque {
            first: None,
            last: Rawlink::none()
        }
    }
    fn is_empty(&self) -> bool {
        true
    }
    fn size(&self) -> usize {
        match self.first {
            None    => 0,
            Some(ref l) => l.size()
        }
    }
    fn add_first(&mut self, item: T) {
        let mut old_first = self.first.take();
        let mut first = Box::new(Node {
            item: item,
            next: None,
            prev: Rawlink::none()
        });

        if old_first.is_some() {
            old_first.as_mut().unwrap().prev = Rawlink::some(&mut first);
        }
        // move in
        first.next = old_first;

        self.first = Some(first)
    }

    fn add_last(&mut self, item: T) {
        unimplemented!()
    }

    fn remove_first(&mut self) -> Option<T> {
        let old_first = self.first.take();
        let (item, first, _) = old_first.unwrap().into_item_and_pointers();
        self.first = first;
        if self.is_empty() {
            self.last = Rawlink::none()
        }
        Some(item)
    }

    fn remove_last(&mut self) -> Option<T> {
        let old_last = self.last.take();
        if old_last.p.is_null() {
            return None;
        }
        let last_but_one = unsafe { mem::transmute::<_, &mut Node<T>>(old_last.p) };

        let last: Node<T> = mem::replace(last_but_one, unsafe { mem::zeroed() });

        unsafe {
            (*last.prev.p).next = None;
        }

        Some(last.item)

    }
    // fn iter(&self) -> Iterator<Item=&T> {
    //     unimplemented!()
    // }

}

#[test]
fn test_linked_deque() {
    let mut deque: LinkedDeque<String> = Deque::new();

    let mut result = "to be not that or be".split(' ');

    for s in "to be or not to - be - - that - - - is".split(' ') {
        if s == "-" {
            assert_eq!(deque.remove_first(), Some(result.next().unwrap().into()))
        } else {
            deque.add_first(s.into())
        }
    }
}
<|endoftext|>


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

// compile-flags: -Z emit-end-regions -Z borrowck-mir

fn guard() -> bool {
    false
}

fn guard2(_:i32) -> bool {
    true
}

fn full_tested_match() {
    let _ = match Some(42) {
        Some(x) if guard() => 1 + x,
        Some(y) => 2 + y,
        None => 3,
    };
}

fn full_tested_match2() {
    let _ = match Some(42) {
        Some(x) if guard() => 1 + x,
        None => 3,
        Some(y) => 2 + y,
    };
}

fn main() {
    let _ = match Some(1) {
        Some(_w) if guard() => 1,
        _x => 2,
        Some(y) if guard2(y) => 3,
        _z => 4,
    };
}

// END RUST SOURCE
//
// START rustc.node17.SimplifyBranches-initial.before.mir
//  bb0: {
//      ...
//      _2 = std::option::Option<i32>::Some(const 42i32,);
//      _5 = discriminant(_2);
//      switchInt(_5) -> [0isize: bb5, otherwise: bb3];
//  }
//  bb1: { // arm1
//      StorageLive(_7);
//      _7 = _3;
//      _1 = Add(const 1i32, _7);
//      ...
//      goto -> bb11;
//  }
//  bb2: { // binding3(empty) and arm3
//      _1 = const 3i32;
//      goto -> bb11;
//  }
//  bb3: {
//      falseEdges -> [real: bb7, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb10, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb2, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      unreachable;
//  }
//  bb7: { // binding1 and guard
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_6);
//      _6 = const guard() -> bb8;
//  }
//  bb8: { // end of guard
//      switchInt(_6) -> [0u8: bb9, otherwise: bb1];
//  }
//  bb9: { // to pre_binding2
//      falseEdges -> [real: bb4, imaginary: bb4];
//  }
//  bb10: { // bindingNoLandingPads.before.mir2 and arm2
//      StorageLive(_4);
//      _4 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = _4;
//      _1 = Add(const 2i32, _8);
//      StorageDead(_8);
//      goto -> bb11;
//  }
//  bb11: {
//      ...
//      return;
//  }
// END rustc.node17.SimplifyBranches-initial.before.mir
//
// START rustc.node40.SimplifyBranches-initial.before.mir
//  bb0: {
//      ...
//      _2 = std::option::Option<i32>::Some(const 42i32,);
//      _5 = discriminant(_2);
//      switchInt(_5) -> [0isize: bb4, otherwise: bb3];
//  }
//  bb1: { // arm1
//      StorageLive(_7);
//      _7 = _3;
//      _1 = Add(const 1i32, _7);
//      ...
//      goto -> bb11;
//  }
//  bb2: { // binding3(empty) and arm3
//      _1 = const 3i32;
//      goto -> bb11;
//  }
//  bb3: {
//      falseEdges -> [real: bb7, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb2, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb10, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      unreachable;
//  }
//  bb7: { // binding1 and guard
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_6);
//      _6 = const guard() -> bb8;
//  }
//  bb8: { // end of guard
//      switchInt(_6) -> [0u8: bb9, otherwise: bb1];
//  }
//  bb9: { // to pre_binding2
//      falseEdges -> [real: bb5, imaginary: bb4];
//  }
//  bb10: { // binding2 and arm2
//      StorageLive(_4);
//      _4 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = _4;
//      _1 = Add(const 2i32, _8);
//      StorageDead(_8);
//      goto -> bb11;
//  }
//  bb11: {
//      ...
//      return;
//  }
// END rustc.node40.SimplifyBranches-initial.before.mir
//
// START rustc.node63.SimplifyBranches-initial.before.mir
// bb0: {
//     ...
//     _2 = std::option::Option<i32>::Some(const 1i32,);
//     _7 = discriminant(_2);
//     switchInt(_7) -> [1isize: bb3, otherwise: bb4];
// }
// bb1: { // arm1
//      _1 = const 1i32;
//      goto -> bb16;
// }
// bb2: { // arm3
//     _1 = const 3i32;
//      goto -> bb16;
// }
//
//  bb3: {
//      falseEdges -> [real: bb8, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb11, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb12, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      falseEdges -> [real: bb15, imaginary: bb7]; //pre_binding4
//  }
//  bb7: {
//      unreachable;
//  }
//  bb8: { // binding1: Some(w) if guard()
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = const guard() -> bb9;
//  }
//  bb9: { //end of guard
//      switchInt(_8) -> [0u8: bb10, otherwise: bb1];
//  }
//  bb10: { // to pre_binding2
//      falseEdges -> [real: bb4, imaginary: bb4];
//  }
//  bb11: { // binding2 & arm2
//      StorageLive(_4);
//      _4 = _2;
//      _1 = const 2i32;
//      goto -> bb16;
//  }
//  bb12: { // binding3: Some(y) if guard2(y)
//      StorageLive(_5);
//      _5 = ((_2 as Some).0: i32);
//      StorageLive(_10);
//      StorageLive(_11);
//      _11 = _5;
//      _10 = const guard2(_11) -> bb13;
//  }
//  bb13: { // end of guard2
//      StorageDead(_11);
//      switchInt(_10) -> [0u8: bb14, otherwise: bb2];
//  }
//  bb14: { // to pre_binding4
//      falseEdges -> [real: bb6, imaginary: bb6];
//  }
//  bb15: { // binding4 & arm4
//      StorageLive(_6);
//      _6 = _2;
//      _1 = const 4i32;
//      goto -> bb16;
//  }
// bb16: {
//     ...
//     return;
// }
// END rustc.node63.SimplifyBranches-initial.before.mir
<commit_msg>replace Add by tuple<commit_after>// Copyright 2012-2016 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.

// compile-flags: -Z emit-end-regions -Z borrowck-mir

fn guard() -> bool {
    false
}

fn guard2(_:i32) -> bool {
    true
}

fn full_tested_match() {
    let _ = match Some(42) {
        Some(x) if guard() => (1, x),
        Some(y) => (2, y),
        None => (3, 3),
    };
}

fn full_tested_match2() {
    let _ = match Some(42) {
        Some(x) if guard() => (1, x),
        None => (3, 3),
        Some(y) => (2, y),
    };
}

fn main() {
    let _ = match Some(1) {
        Some(_w) if guard() => 1,
        _x => 2,
        Some(y) if guard2(y) => 3,
        _z => 4,
    };
}

// END RUST SOURCE
//
// START rustc.node17.SimplifyBranches-initial.before.mir
//  bb0: {
//      ...
//      _2 = std::option::Option<i32>::Some(const 42i32,);
//      _5 = discriminant(_2);
//      switchInt(_5) -> [0isize: bb5, otherwise: bb3];
//  }
//  bb1: { // arm1
//      StorageLive(_7);
//      _7 = _3;
//      _1 = (const 1i32, _7);
//      StorageDead(_7);
//      goto -> bb11;
//  }
//  bb2: { // binding3(empty) and arm3
//      _1 = (const 3i32, const 3i32);
//      goto -> bb11;
//  }
//  bb3: {
//      falseEdges -> [real: bb7, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb10, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb2, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      unreachable;
//  }
//  bb7: { // binding1 and guard
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_6);
//      _6 = const guard() -> bb8;
//  }
//  bb8: { // end of guard
//      switchInt(_6) -> [0u8: bb9, otherwise: bb1];
//  }
//  bb9: { // to pre_binding2
//      falseEdges -> [real: bb4, imaginary: bb4];
//  }
//  bb10: { // bindingNoLandingPads.before.mir2 and arm2
//      StorageLive(_4);
//      _4 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = _4;
//      _1 = (const 2i32, _8);
//      StorageDead(_8);
//      goto -> bb11;
//  }
//  bb11: {
//      ...
//      return;
//  }
// END rustc.node17.SimplifyBranches-initial.before.mir
//
// START rustc.node42.SimplifyBranches-initial.before.mir
//  bb0: {
//      ...
//      _2 = std::option::Option<i32>::Some(const 42i32,);
//      _5 = discriminant(_2);
//      switchInt(_5) -> [0isize: bb4, otherwise: bb3];
//  }
//  bb1: { // arm1
//      StorageLive(_7);
//      _7 = _3;
//      _1 = (const 1i32, _7);
//      StorageDead(_7);
//      goto -> bb11;
//  }
//  bb2: { // binding3(empty) and arm3
//      _1 = (const 3i32, const 3i32);
//      goto -> bb11;
//  }
//  bb3: {
//      falseEdges -> [real: bb7, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb2, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb10, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      unreachable;
//  }
//  bb7: { // binding1 and guard
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_6);
//      _6 = const guard() -> bb8;
//  }
//  bb8: { // end of guard
//      switchInt(_6) -> [0u8: bb9, otherwise: bb1];
//  }
//  bb9: { // to pre_binding2
//      falseEdges -> [real: bb5, imaginary: bb4];
//  }
//  bb10: { // binding2 and arm2
//      StorageLive(_4);
//      _4 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = _4;
//      _1 = (const 2i32, _8);
//      StorageDead(_8);
//      goto -> bb11;
//  }
//  bb11: {
//      ...
//      return;
//  }
// END rustc.node42.SimplifyBranches-initial.before.mir
//
// START rustc.node67.SimplifyBranches-initial.before.mir
// bb0: {
//     ...
//     _2 = std::option::Option<i32>::Some(const 1i32,);
//     _7 = discriminant(_2);
//     switchInt(_7) -> [1isize: bb3, otherwise: bb4];
// }
// bb1: { // arm1
//      _1 = const 1i32;
//      goto -> bb16;
// }
// bb2: { // arm3
//     _1 = const 3i32;
//      goto -> bb16;
// }
//
//  bb3: {
//      falseEdges -> [real: bb8, imaginary: bb4]; //pre_binding1
//  }
//  bb4: {
//      falseEdges -> [real: bb11, imaginary: bb5]; //pre_binding2
//  }
//  bb5: {
//      falseEdges -> [real: bb12, imaginary: bb6]; //pre_binding3
//  }
//  bb6: {
//      falseEdges -> [real: bb15, imaginary: bb7]; //pre_binding4
//  }
//  bb7: {
//      unreachable;
//  }
//  bb8: { // binding1: Some(w) if guard()
//      StorageLive(_3);
//      _3 = ((_2 as Some).0: i32);
//      StorageLive(_8);
//      _8 = const guard() -> bb9;
//  }
//  bb9: { //end of guard
//      switchInt(_8) -> [0u8: bb10, otherwise: bb1];
//  }
//  bb10: { // to pre_binding2
//      falseEdges -> [real: bb4, imaginary: bb4];
//  }
//  bb11: { // binding2 & arm2
//      StorageLive(_4);
//      _4 = _2;
//      _1 = const 2i32;
//      goto -> bb16;
//  }
//  bb12: { // binding3: Some(y) if guard2(y)
//      StorageLive(_5);
//      _5 = ((_2 as Some).0: i32);
//      StorageLive(_10);
//      StorageLive(_11);
//      _11 = _5;
//      _10 = const guard2(_11) -> bb13;
//  }
//  bb13: { // end of guard2
//      StorageDead(_11);
//      switchInt(_10) -> [0u8: bb14, otherwise: bb2];
//  }
//  bb14: { // to pre_binding4
//      falseEdges -> [real: bb6, imaginary: bb6];
//  }
//  bb15: { // binding4 & arm4
//      StorageLive(_6);
//      _6 = _2;
//      _1 = const 4i32;
//      goto -> bb16;
//  }
// bb16: {
//     ...
//     return;
// }
// END rustc.node67.SimplifyBranches-initial.before.mir
<|endoftext|>


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

#![feature(lang_items, start, libc, alloc)]
#![no_std]

extern crate std as other;

extern crate libc;

#[macro_use]
extern crate alloc;

use alloc::vec::Vec;

// Issue #16806

#[start]
fn start(_argc: isize, _argv: *const *const u8) -> isize {
    let x: Vec<u8> = vec![0, 1, 2];
    match x.last() {
        Some(&2) => (),
        _ => panic!(),
    }
    0
}
<commit_msg>Ignore a spuriously failing test on asmjs<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// ignore-emscripten missing rust_begin_unwind

#![feature(lang_items, start, libc, alloc)]
#![no_std]

extern crate std as other;

extern crate libc;

#[macro_use]
extern crate alloc;

use alloc::vec::Vec;

// Issue #16806

#[start]
fn start(_argc: isize, _argv: *const *const u8) -> isize {
    let x: Vec<u8> = vec![0, 1, 2];
    match x.last() {
        Some(&2) => (),
        _ => panic!(),
    }
    0
}
<|endoftext|>


<commit_before><commit_msg>Added tests.<commit_after>// Copyright 2018 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.

#![feature(self_in_typedefs)]
#![feature(untagged_unions)]

#![allow(dead_code)]

enum A<'a, T: 'a>
where
    Self: Send, T: PartialEq<Self>
{
    Foo(&'a Self),
    Bar(T),
}

struct B<'a, T: 'a>
where
    Self: Send, T: PartialEq<Self>
{
    foo: &'a Self,
    bar: T,
}

union C<'a, T: 'a>
where
    Self: Send, T: PartialEq<Self>
{
    foo: &'a Self,
    bar: T,
}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Rollup merge of #63577 - meffij:test-hrtb, r=alexcrichton<commit_after>// Tests that HRTBs are correctly accepted -- https://github.com/rust-lang/rust/issues/50301
// check-pass
trait Trait
where
    for<'a> &'a Self::IntoIter: IntoIterator<Item = u32>,
{
    type IntoIter;
    fn get(&self) -> Self::IntoIter;
}

struct Impl(Vec<u32>);

impl Trait for Impl {
    type IntoIter = ImplIntoIter;
    fn get(&self) -> Self::IntoIter {
        ImplIntoIter(self.0.clone())
    }
}

struct ImplIntoIter(Vec<u32>);

impl<'a> IntoIterator for &'a ImplIntoIter {
    type Item = <Self::IntoIter as Iterator>::Item;
    type IntoIter = std::iter::Cloned<std::slice::Iter<'a, u32>>;
    fn into_iter(self) -> Self::IntoIter {
        (&self.0).into_iter().cloned()
    }
}

fn main() {
}
<|endoftext|>


<commit_before><commit_msg>Add a test for #57781<commit_after>// run-pass

use std::cell::UnsafeCell;
use std::collections::HashMap;

struct OnceCell<T> {
    _value: UnsafeCell<Option<T>>,
}

impl<T> OnceCell<T> {
    const INIT: OnceCell<T> = OnceCell {
        _value: UnsafeCell::new(None),
    };
}

pub fn crash<K, T>() {
    let _ = OnceCell::<HashMap<K, T>>::INIT;
}

fn main() {}
<|endoftext|>


<commit_before>use std::io::Writer;
use std::io::Reader;
use std::vec;

pub struct VecWriter {
    vec: ~[u8],
}

impl VecWriter {
    pub fn new() -> VecWriter {
        VecWriter {
            vec: ~[],
        }
    }
}

impl Writer for VecWriter {
    fn write(&mut self, v: &[u8]) {
        self.vec.push_all(v);
    }

    fn flush(&mut self) {
        fail!();
    }
}

pub struct VecReader {
    vec: ~[u8],
    pos: uint,
}

impl VecReader {
    pub fn new(bytes: ~[u8]) -> VecReader {
        VecReader {
            vec: bytes,
            pos: 0,
        }
    }

    fn remaining(&self) -> uint {
        self.vec.len() - self.pos
    }
}

impl Reader for VecReader {
    fn read(&mut self, bytes: &mut [u8]) -> Option<uint> {
        let n = if bytes.len() < self.remaining() { bytes.len() } else { self.remaining() };
        vec::bytes::copy_memory(bytes, self.vec.slice(self.pos, self.pos + n));
        self.pos += n;
        Some(n)
    }

    fn eof(&mut self) -> bool {
        fail!();
    }
}

pub struct CountWriter {
    count: uint,
}

impl CountWriter {
    pub fn new() -> CountWriter {
        CountWriter {
            count: 0,
        }
    }
}

impl Writer for CountWriter {
    fn write(&mut self, v: &[u8]) {
        self.count += v.len();
    }
}

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

    use std::io::Writer;

    #[test]
    fn test_vec_writer() {
        let mut w = VecWriter::new();
        fn foo(writer: &mut Writer) {
            writer.write("hi".as_bytes());
        }
        foo(&mut w as &mut Writer);
        assert_eq!(~['h' as u8, 'i' as u8], w.vec.to_owned());
    }

    #[test]
    fn test_count_writer() {
        let mut w = CountWriter::new();
        w.write("hi".as_bytes());
        w.write("there".as_bytes());
        assert_eq!(7, w.count);
    }
}
<commit_msg>There is no longer fn eof() in Reader trait<commit_after>use std::io::Writer;
use std::io::Reader;
use std::vec;

pub struct VecWriter {
    vec: ~[u8],
}

impl VecWriter {
    pub fn new() -> VecWriter {
        VecWriter {
            vec: ~[],
        }
    }
}

impl Writer for VecWriter {
    fn write(&mut self, v: &[u8]) {
        self.vec.push_all(v);
    }

    fn flush(&mut self) {
        fail!();
    }
}

pub struct VecReader {
    vec: ~[u8],
    pos: uint,
}

impl VecReader {
    pub fn new(bytes: ~[u8]) -> VecReader {
        VecReader {
            vec: bytes,
            pos: 0,
        }
    }

    fn remaining(&self) -> uint {
        self.vec.len() - self.pos
    }
}

impl Reader for VecReader {
    fn read(&mut self, bytes: &mut [u8]) -> Option<uint> {
        let n = if bytes.len() < self.remaining() { bytes.len() } else { self.remaining() };
        vec::bytes::copy_memory(bytes, self.vec.slice(self.pos, self.pos + n));
        self.pos += n;
        Some(n)
    }
}

pub struct CountWriter {
    count: uint,
}

impl CountWriter {
    pub fn new() -> CountWriter {
        CountWriter {
            count: 0,
        }
    }
}

impl Writer for CountWriter {
    fn write(&mut self, v: &[u8]) {
        self.count += v.len();
    }
}

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

    use std::io::Writer;

    #[test]
    fn test_vec_writer() {
        let mut w = VecWriter::new();
        fn foo(writer: &mut Writer) {
            writer.write("hi".as_bytes());
        }
        foo(&mut w as &mut Writer);
        assert_eq!(~['h' as u8, 'i' as u8], w.vec.to_owned());
    }

    #[test]
    fn test_count_writer() {
        let mut w = CountWriter::new();
        w.write("hi".as_bytes());
        w.write("there".as_bytes());
        assert_eq!(7, w.count);
    }
}
<|endoftext|>