<commit_before>#![feature(phase, globs)]
extern crate regex;
#[phase(plugin)] extern crate regex_macros;
extern crate ansi_term;
extern crate users;
extern crate unicode;

use std::io::FileType;
use std::io::fs;
use std::iter::AdditiveIterator;
use std::os;
use std::cmp::max;

use column::Alignment::Left;
use column::Column;
use dir::Dir;
use file::File;
use options::{Options, View};

use ansi_term::Style::Plain;
use ansi_term::strip_formatting;

use users::OSUsers;

pub mod column;
pub mod dir;
pub mod format;
pub mod file;
pub mod filetype;
pub mod options;
pub mod term;

fn main() {
    let args: Vec<String> = os::args();

    match Options::getopts(args) {
        Err(error_code) => os::set_exit_status(error_code),
        Ok(options) => exa(&options),
    };
}

fn exa(opts: &Options) {
    let mut dirs: Vec<String> = vec![];
    let mut files: Vec<File> = vec![];

    // Separate the user-supplied paths into directories and files.
    // Files are shown first, and then each directory is expanded
    // and listed second.
    for file in opts.path_strs.iter() {
        let path = Path::new(file);
        match fs::stat(&path) {
            Ok(stat) => {
                if !opts.list_dirs && stat.kind == FileType::Directory {
                    dirs.push(file.clone());
                }
                else {
                    // May as well reuse the stat result from earlier
                    // instead of just using File::from_path().
                    files.push(File::with_stat(stat, &path, None));
                }
            }
            Err(e) => println!("{}: {}", file, e),
        }
    }

    // It's only worth printing out directory names if the user supplied
    // more than one of them.
    let print_dir_names = opts.path_strs.len() > 1;
    let mut first = files.is_empty();

    if !files.is_empty() {
        view(opts, files);
    }

    for dir_name in dirs.iter() {
        if first {
            first = false;
        }
        else {
            print!("\n");
        }

        match Dir::readdir(Path::new(dir_name.clone())) {
            Ok(dir) => {
                let unsorted_files = dir.files();
                let files: Vec<File> = opts.transform_files(unsorted_files);

                if print_dir_names {
                    println!("{}:", dir_name);
                }

                view(opts, files);
            }
            Err(e) => {
                println!("{}: {}", dir_name, e);
                return;
            }
        };
    }
}

fn view(options: &Options, files: Vec<File>) {
    match options.view {
        View::Details(ref cols) => details_view(options, cols, files),
        View::Lines => lines_view(files),
        View::Grid(across, width) => grid_view(across, width, files),
    }
}

fn lines_view(files: Vec<File>) {
    for file in files.iter() {
        println!("{}", file.file_name());
    }
}

fn fit_into_grid(across: bool, console_width: uint, files: &Vec<File>) -> Option<(uint, Vec<uint>)> {
    // TODO: this function could almost certainly be optimised...
    // surely not *all* of the numbers of lines are worth searching through!

    // Instead of numbers of columns, try to find the fewest number of *lines*
    // that the output will fit in.
    for num_lines in range(1, files.len()) {

        // The number of columns is the number of files divided by the number
        // of lines, *rounded up*.
        let mut num_columns = files.len() / num_lines;
        if files.len() % num_lines != 0 {
            num_columns += 1;
        }

        // Early abort: if there are so many columns that the width of the
        // *column separators* is bigger than the width of the screen, then
        // don't even try to tabulate it.
        // This is actually a necessary check, because the width is stored as
        // a uint, and making it go negative makes it huge instead, but it
        // also serves as a speed-up.
        if console_width < (num_columns - 1) * 2 {
            continue;
        }

        // Remove the separator width from the available space.
        let adjusted_width = console_width - (num_columns - 1) * 2;

        // Find the width of each column by adding the lengths of the file
        // names in that column up.
        let mut column_widths = Vec::from_fn(num_columns, |_| 0u);
        for (index, file) in files.iter().enumerate() {
            let index = if across {
                index % num_columns
            }
            else {
                index / num_lines
            };
            column_widths[index] = max(column_widths[index], file.name.len());
        }

        // If they all fit in the terminal, combined, then success!
        if column_widths.iter().map(|&x| x).sum() < adjusted_width {
            return Some((num_lines, column_widths));
        }
    }

    // If you get here you have really long file names.
    return None;
}

fn grid_view(across: bool, console_width: uint, files: Vec<File>) {
    if let Some((num_lines, widths)) = fit_into_grid(across, console_width, &files) {
        for y in range(0, num_lines) {
            for x in range(0, widths.len()) {
                let num = if across {
                    y * widths.len() + x
                }
                else {
                    y + num_lines * x
                };

                // Show whitespace in the place of trailing files
                if num >= files.len() {
                    continue;
                }

                let ref file = files[num];
                let styled_name = file.file_colour().paint(file.name.as_slice()).to_string();
                if x == widths.len() - 1 {
                    // The final column doesn't need to have trailing spaces
                    print!("{}", styled_name);
                }
                else {
                    assert!(widths[x] >= file.name.len());
                    print!("{}", Left.pad_string(&styled_name, widths[x] - file.name.len() + 2));
                }
            }
            print!("\n");
        }
    }
    else {
        // Drop down to lines view if the file names are too big for a grid
        lines_view(files);
    }
}

fn details_view(options: &Options, columns: &Vec<Column>, files: Vec<File>) {
    // The output gets formatted into columns, which looks nicer. To
    // do this, we have to write the results into a table, instead of
    // displaying each file immediately, then calculating the maximum
    // width of each column based on the length of the results and
    // padding the fields during output.

    let mut cache = OSUsers::empty_cache();

    let mut table: Vec<Vec<String>> = files.iter()
        .map(|f| columns.iter().map(|c| f.display(c, &mut cache)).collect())
        .collect();

    if options.header {
        table.insert(0, columns.iter().map(|c| Plain.underline().paint(c.header()).to_string()).collect());
    }

    // Each column needs to have its invisible colour-formatting
    // characters stripped before it has its width calculated, or the
    // width will be incorrect and the columns won't line up properly.
    // This is fairly expensive to do (it uses a regex), so the
    // results are cached.

    let lengths: Vec<Vec<uint>> = table.iter()
        .map(|row| row.iter().map(|col| strip_formatting(col.as_slice()).len()).collect())
        .collect();

    let column_widths: Vec<uint> = range(0, columns.len())
        .map(|n| lengths.iter().map(|row| row[n]).max().unwrap_or(0))
        .collect();

    for (field_widths, row) in lengths.iter().zip(table.iter()) {
        for (num, column) in columns.iter().enumerate() {
            if num != 0 {
                print!(" ");  // Separator
            }

            if num == columns.len() - 1 {
                // The final column doesn't need to have trailing spaces
                print!("{}", row[num]);
            }
            else {
                let padding = column_widths[num] - field_widths[num];
                print!("{}", column.alignment().pad_string(&row[num], padding));
            }
        }
        print!("\n");
    }
}
<commit_msg>Extract separator_width variable<commit_after>#![feature(phase, globs)]
extern crate regex;
#[phase(plugin)] extern crate regex_macros;
extern crate ansi_term;
extern crate users;
extern crate unicode;

use std::io::FileType;
use std::io::fs;
use std::iter::AdditiveIterator;
use std::os;
use std::cmp::max;

use column::Alignment::Left;
use column::Column;
use dir::Dir;
use file::File;
use options::{Options, View};

use ansi_term::Style::Plain;
use ansi_term::strip_formatting;

use users::OSUsers;

pub mod column;
pub mod dir;
pub mod format;
pub mod file;
pub mod filetype;
pub mod options;
pub mod term;

fn main() {
    let args: Vec<String> = os::args();

    match Options::getopts(args) {
        Err(error_code) => os::set_exit_status(error_code),
        Ok(options) => exa(&options),
    };
}

fn exa(opts: &Options) {
    let mut dirs: Vec<String> = vec![];
    let mut files: Vec<File> = vec![];

    // Separate the user-supplied paths into directories and files.
    // Files are shown first, and then each directory is expanded
    // and listed second.
    for file in opts.path_strs.iter() {
        let path = Path::new(file);
        match fs::stat(&path) {
            Ok(stat) => {
                if !opts.list_dirs && stat.kind == FileType::Directory {
                    dirs.push(file.clone());
                }
                else {
                    // May as well reuse the stat result from earlier
                    // instead of just using File::from_path().
                    files.push(File::with_stat(stat, &path, None));
                }
            }
            Err(e) => println!("{}: {}", file, e),
        }
    }

    // It's only worth printing out directory names if the user supplied
    // more than one of them.
    let print_dir_names = opts.path_strs.len() > 1;
    let mut first = files.is_empty();

    if !files.is_empty() {
        view(opts, files);
    }

    for dir_name in dirs.iter() {
        if first {
            first = false;
        }
        else {
            print!("\n");
        }

        match Dir::readdir(Path::new(dir_name.clone())) {
            Ok(dir) => {
                let unsorted_files = dir.files();
                let files: Vec<File> = opts.transform_files(unsorted_files);

                if print_dir_names {
                    println!("{}:", dir_name);
                }

                view(opts, files);
            }
            Err(e) => {
                println!("{}: {}", dir_name, e);
                return;
            }
        };
    }
}

fn view(options: &Options, files: Vec<File>) {
    match options.view {
        View::Details(ref cols) => details_view(options, cols, files),
        View::Lines => lines_view(files),
        View::Grid(across, width) => grid_view(across, width, files),
    }
}

fn lines_view(files: Vec<File>) {
    for file in files.iter() {
        println!("{}", file.file_name());
    }
}

fn fit_into_grid(across: bool, console_width: uint, files: &Vec<File>) -> Option<(uint, Vec<uint>)> {
    // TODO: this function could almost certainly be optimised...
    // surely not *all* of the numbers of lines are worth searching through!

    // Instead of numbers of columns, try to find the fewest number of *lines*
    // that the output will fit in.
    for num_lines in range(1, files.len()) {

        // The number of columns is the number of files divided by the number
        // of lines, *rounded up*.
        let mut num_columns = files.len() / num_lines;
        if files.len() % num_lines != 0 {
            num_columns += 1;
        }

        // Early abort: if there are so many columns that the width of the
        // *column separators* is bigger than the width of the screen, then
        // don't even try to tabulate it.
        // This is actually a necessary check, because the width is stored as
        // a uint, and making it go negative makes it huge instead, but it
        // also serves as a speed-up.
        let separator_width = (num_columns - 1) * 2;
        if console_width < separator_width {
            continue;
        }

        // Remove the separator width from the available space.
        let adjusted_width = console_width - separator_width;

        // Find the width of each column by adding the lengths of the file
        // names in that column up.
        let mut column_widths = Vec::from_fn(num_columns, |_| 0u);
        for (index, file) in files.iter().enumerate() {
            let index = if across {
                index % num_columns
            }
            else {
                index / num_lines
            };
            column_widths[index] = max(column_widths[index], file.name.len());
        }

        // If they all fit in the terminal, combined, then success!
        if column_widths.iter().map(|&x| x).sum() < adjusted_width {
            return Some((num_lines, column_widths));
        }
    }

    // If you get here you have really long file names.
    return None;
}

fn grid_view(across: bool, console_width: uint, files: Vec<File>) {
    if let Some((num_lines, widths)) = fit_into_grid(across, console_width, &files) {
        for y in range(0, num_lines) {
            for x in range(0, widths.len()) {
                let num = if across {
                    y * widths.len() + x
                }
                else {
                    y + num_lines * x
                };

                // Show whitespace in the place of trailing files
                if num >= files.len() {
                    continue;
                }

                let ref file = files[num];
                let styled_name = file.file_colour().paint(file.name.as_slice()).to_string();
                if x == widths.len() - 1 {
                    // The final column doesn't need to have trailing spaces
                    print!("{}", styled_name);
                }
                else {
                    assert!(widths[x] >= file.name.len());
                    print!("{}", Left.pad_string(&styled_name, widths[x] - file.name.len() + 2));
                }
            }
            print!("\n");
        }
    }
    else {
        // Drop down to lines view if the file names are too big for a grid
        lines_view(files);
    }
}

fn details_view(options: &Options, columns: &Vec<Column>, files: Vec<File>) {
    // The output gets formatted into columns, which looks nicer. To
    // do this, we have to write the results into a table, instead of
    // displaying each file immediately, then calculating the maximum
    // width of each column based on the length of the results and
    // padding the fields during output.

    let mut cache = OSUsers::empty_cache();

    let mut table: Vec<Vec<String>> = files.iter()
        .map(|f| columns.iter().map(|c| f.display(c, &mut cache)).collect())
        .collect();

    if options.header {
        table.insert(0, columns.iter().map(|c| Plain.underline().paint(c.header()).to_string()).collect());
    }

    // Each column needs to have its invisible colour-formatting
    // characters stripped before it has its width calculated, or the
    // width will be incorrect and the columns won't line up properly.
    // This is fairly expensive to do (it uses a regex), so the
    // results are cached.

    let lengths: Vec<Vec<uint>> = table.iter()
        .map(|row| row.iter().map(|col| strip_formatting(col.as_slice()).len()).collect())
        .collect();

    let column_widths: Vec<uint> = range(0, columns.len())
        .map(|n| lengths.iter().map(|row| row[n]).max().unwrap_or(0))
        .collect();

    for (field_widths, row) in lengths.iter().zip(table.iter()) {
        for (num, column) in columns.iter().enumerate() {
            if num != 0 {
                print!(" ");  // Separator
            }

            if num == columns.len() - 1 {
                // The final column doesn't need to have trailing spaces
                print!("{}", row[num]);
            }
            else {
                let padding = column_widths[num] - field_widths[num];
                print!("{}", column.alignment().pad_string(&row[num], padding));
            }
        }
        print!("\n");
    }
}
<|endoftext|>


<commit_before><commit_msg>Add TYPE command<commit_after><|endoftext|>


<commit_before>// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[deny(missing_docs)]

extern crate gfx;
extern crate gfx_device_gl;
extern crate glfw;

use gfx::tex::Size;
use glfw::Context;

/// A wrapper around the window that implements `Output`.
pub struct Wrap<R: gfx::Resources> {
    /// Glutin window in the open.
    pub window: glfw::Window,
    frame: gfx::FrameBufferHandle<R>,
    mask: gfx::Mask,
    gamma: gfx::Gamma,
}

impl<R: gfx::Resources> gfx::Output<R> for Wrap<R> {
    fn get_handle(&self) -> Option<&gfx::FrameBufferHandle<R>> {
        Some(&self.frame)
    }

    fn get_size(&self) -> (Size, Size) {
        let (w, h) = self.window.get_framebuffer_size();
        (w as Size, h as Size)
    }

    fn get_mask(&self) -> gfx::Mask {
        self.mask
    }

    fn get_gamma(&self) -> gfx::Gamma {
        self.gamma
    }
}

impl<R: gfx::Resources> gfx::Window<R> for Wrap<R> {
    fn swap_buffers(&mut self) {
        self.window.swap_buffers();
    }
}

/// Result of successful context initialization.
pub type Success = (
    Wrap<gfx_device_gl::Resources>,
    gfx_device_gl::Device,
    gfx_device_gl::Factory,
);

/// Initialize with a window.
pub fn init(mut window: glfw::Window) -> Success {
    window.make_current();
    let (device, factory) = gfx_device_gl::create(|s| window.get_proc_address(s));
    let wrap = Wrap {
        window: window,
        frame: factory.get_main_frame_buffer(),
        mask: gfx::COLOR | gfx::DEPTH | gfx::STENCIL, //TODO
        gamma: gfx::Gamma::Original, //TODO
    };
    (wrap, device, factory)
}
<commit_msg>Remove use of removed handle typedefs<commit_after>// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[deny(missing_docs)]

extern crate gfx;
extern crate gfx_device_gl;
extern crate glfw;

use gfx::tex::Size;

use glfw::Context;

/// A wrapper around the window that implements `Output`.
pub struct Wrap<R: gfx::Resources> {
    /// Glutin window in the open.
    pub window: glfw::Window,
    frame: gfx::handle::FrameBuffer<R>,
    mask: gfx::Mask,
    gamma: gfx::Gamma,
}

impl<R: gfx::Resources> gfx::Output<R> for Wrap<R> {
    fn get_handle(&self) -> Option<&gfx::handle::FrameBuffer<R>> {
        Some(&self.frame)
    }

    fn get_size(&self) -> (Size, Size) {
        let (w, h) = self.window.get_framebuffer_size();
        (w as Size, h as Size)
    }

    fn get_mask(&self) -> gfx::Mask {
        self.mask
    }

    fn get_gamma(&self) -> gfx::Gamma {
        self.gamma
    }
}

impl<R: gfx::Resources> gfx::Window<R> for Wrap<R> {
    fn swap_buffers(&mut self) {
        self.window.swap_buffers();
    }
}

/// Result of successful context initialization.
pub type Success = (
    Wrap<gfx_device_gl::Resources>,
    gfx_device_gl::Device,
    gfx_device_gl::Factory,
);

/// Initialize with a window.
pub fn init(mut window: glfw::Window) -> Success {
    window.make_current();
    let (device, factory) = gfx_device_gl::create(|s| window.get_proc_address(s));
    let wrap = Wrap {
        window: window,
        frame: factory.get_main_frame_buffer(),
        mask: gfx::COLOR | gfx::DEPTH | gfx::STENCIL, //TODO
        gamma: gfx::Gamma::Original, //TODO
    };
    (wrap, device, factory)
}
<|endoftext|>


<commit_before><commit_msg>rub updates<commit_after><|endoftext|>


<commit_before><commit_msg>Remove #![deny(warnings)]<commit_after><|endoftext|>


<commit_before><commit_msg>Implement Encodable and Decodable for Url. See #27.<commit_after><|endoftext|>


<commit_before><commit_msg>Add todos for test cleanup, etc<commit_after><|endoftext|>


<commit_before><commit_msg>add Vec::relinquish<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing file<commit_after>use Vector2f;
use paramset::ParamSet;
use super::Filter;

pub struct GaussianFilter {
    radius: (f32, f32),
    inv_radius: (f32, f32),
    alpha: f32,
    expx: f32,
    expy: f32,
}

impl GaussianFilter {
    pub fn new(radius: &Vector2f, alpha: f32) -> GaussianFilter {
        GaussianFilter {
            radius: (radius.x, radius.y),
            inv_radius: (1.0 / radius.x, 1.0 / radius.y),
            alpha: alpha,
            expx: (-alpha * radius.x * radius.x).exp(),
            expy: (-alpha * radius.y * radius.y).exp(),
        }
    }

    fn gaussian(&self, d: f32, expv: f32) -> f32 {
        ((-self.alpha * d * d).exp() - expv).max(0f32)
    }

    pub fn create(ps: &mut ParamSet) -> Box<Filter + Send + Sync> {
        let xw = ps.find_one_float("xwidth", 2.0);
        let yw = ps.find_one_float("ywidth", 2.0);
        let alpha = ps.find_one_float("alpha", 2.0);
        Box::new(GaussianFilter::new(&Vector2f::new(xw, yw), alpha))
    }
}

impl Filter for GaussianFilter {
    fn evaluate(&self, x: f32, y: f32) -> f32 {
        self.gaussian(x, self.expx) * self.gaussian(y, self.expy)
    }

    fn width(&self) -> (f32, f32) {
        self.radius
    }

    fn inv_width(&self) -> (f32, f32) {
        self.inv_radius
    }
}
<|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.

#![allow(dead_code)]

fn non_elidable<'a, 'b>(a: &'a u8, b: &'b u8) -> &'a u8 { a }

// the boundaries of elision
static NON_ELIDABLE_FN : &fn(&u8, &u8) -> &u8 = non_elidable;
//~^ERROR: missing lifetime specifier

fn main() {
    // nothing to do here
}
<commit_msg>fixed compile-fail test<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.

#![allow(dead_code)]

fn non_elidable<'a, 'b>(a: &'a u8, b: &'b u8) -> &'a u8 { a }

// the boundaries of elision
static NON_ELIDABLE_FN : &fn(&u8, &u8) -> &u8 =
//~^ERROR: missing lifetime specifier
        &(non_elidable as fn(&u8, &u8) -> &u8);

fn main() {
    // nothing to do here
}
<|endoftext|>


<commit_before><commit_msg>Auto merge of #37616 - jneem:master, r=alexcrichton<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.

// Regression test for #18060: match arms were matching in the wrong order.

fn main() {
    assert_eq!(2, match (1, 3) { (0, 2...5) => 1, (1, 3) => 2, (_, 2...5) => 3, (_, _) => 4 });
    assert_eq!(2, match (1, 3) {                  (1, 3) => 2, (_, 2...5) => 3, (_, _) => 4 });
    assert_eq!(2, match (1, 7) { (0, 2...5) => 1, (1, 7) => 2, (_, 2...5) => 3, (_, _) => 4 });
}
<|endoftext|>


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

pub type Session = i32;
pub struct StreamParser<'a, T> {
    _tokens: T,
    _session: &'a mut Session,
}

impl<'a, T> StreamParser<'a, T> {
    pub fn thing(&mut self) -> bool { true }
}

pub fn parse_stream<T: Iterator<Item=i32>, U, F>(
        _session: &mut Session, _tokens: T, _f: F) -> U
    where F: Fn(&mut StreamParser<T>) -> U { panic!(); }

pub fn thing(session: &mut Session) {
    let mut stream = vec!(1, 2, 3).into_iter();

    let _b = parse_stream(session,
                          stream.by_ref(),
                          // replacing the above with the following fixes it
                          //&mut stream,
                          |p| p.thing());

}

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Add test for #55809.<commit_after>// edition:2018
// run-pass

#![feature(async_await, await_macro, futures_api)]

trait Foo { }

impl Foo for () { }

impl<'a, T> Foo for &'a mut T where T: Foo { }

async fn foo_async<T>(_v: T) -> u8 where T: Foo {
    0
}

async fn bad<T>(v: T) -> u8 where T: Foo {
    await!(foo_async(v))
}

async fn async_main() {
    let mut v = ();

    let _ = await!(bad(&mut v));
    let _ = await!(foo_async(&mut v));
    let _ = await!(bad(v));
}

fn main() {
    let _ = async_main();
}
<|endoftext|>


<commit_before><commit_msg>Added client implementation<commit_after>extern crate collatz_multiplexed as collatz;

extern crate futures;
extern crate tokio_core;
extern crate tokio_service;

pub fn main () {
    let addr = "127.0.0.1:9999".parse().unwrap();
    let mut core = Core::new().unwrap();
    let handle = core.handle();
    core.run(
            collatz::Client::connect(&addr, &handle).and_then(
                |client| {
                    client.call("110".to_string())
                        .and_then( move |response| {
                                println!("We got back: {:?}", response);
                                Ok(())
                            })
                })
        ).unwrap();
}

<|endoftext|>


<commit_before><commit_msg>desc: use fakeroot<commit_after><|endoftext|>


<commit_before><commit_msg>Always update window, not just when frames are produced<commit_after><|endoftext|>


<commit_before><commit_msg>chore: existential type<commit_after><|endoftext|>


<commit_before>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use libimagstore::store::Entry;
use libimagstore::store::Store;
use libimagentrylink::internal::InternalLinker;
use libimagnotes::note::Note;
use libimagnotes::note::NoteIterator;
use libimagstore::storeid::StoreIdIterator;

use error::Result;
use error::AnnotationErrorKind as AEK;
use error::ResultExt;

use self::iter::*;

pub trait AnnotationFetcher<'a> {

    fn all_annotations(&'a self) -> Result<AnnotationIter<'a>>;

    fn annotations_for_entry(&'a self, entry: &Entry) -> Result<AnnotationIter<'a>>;

}

impl<'a> AnnotationFetcher<'a> for Store {

    /// Wrapper around `Note::all_notes()` of `libimagnotes` which filters out normal notes and
    /// leaves only annotations in the iterator.
    fn all_annotations(&'a self) -> Result<AnnotationIter<'a>> {
        Note::all_notes(self)
            .map(|iter| AnnotationIter::new(iter))
            .chain_err(|| AEK::StoreReadError)
    }

    /// Get all annotations (in an iterator) for an entry
    ///
    /// Internally, this fetches the links of the entry, fetches all the entries behind the links
    /// and filters them for annotations.
    ///
    /// This might result in some heavy IO operations if a lot of stuff is linked to a single
    /// entry, but should normally be not that heavy.
    fn annotations_for_entry(&'a self, entry: &Entry) -> Result<AnnotationIter<'a>> {
        entry.get_internal_links()
            .chain_err(|| AEK::StoreReadError)
            .map(|iter| StoreIdIterator::new(Box::new(iter.map(|e| e.get_store_id().clone()))))
            .map(|iter| NoteIterator::new(self, iter))
            .map(|iter| AnnotationIter::new(iter))
    }

}

pub mod iter {
    use toml::Value;

    use toml_query::read::TomlValueReadExt;

    use libimagnotes::note::Note;
    use libimagnotes::note::NoteIterator;

    use error::Result;
    use error::AnnotationErrorKind as AEK;
    use error::AnnotationError as AE;
    use error::ResultExt;

    #[derive(Debug)]
    pub struct AnnotationIter<'a>(NoteIterator<'a>);

    impl<'a> AnnotationIter<'a> {

        pub fn new(noteiter: NoteIterator<'a>) -> AnnotationIter<'a> {
            AnnotationIter(noteiter)
        }

    }

    impl<'a> Iterator for AnnotationIter<'a> {
        type Item = Result<Note<'a>>;

        fn next(&mut self) -> Option<Result<Note<'a>>> {
            loop {
                match self.0.next() {
                    Some(Ok(note)) => {
                        match note.get_header().read("annotation.is_annotation") {
                            Ok(None) => continue, // not an annotation
                            Ok(Some(&Value::Boolean(true))) => return Some(Ok(note)),
                            Ok(Some(_)) => return Some(Err(AE::from_kind(AEK::HeaderTypeError))),
                            Err(e) => return Some(Err(e).chain_err(|| AEK::HeaderReadError)),
                        }
                    },
                    Some(Err(e)) => return Some(Err(e).chain_err(|| AEK::StoreReadError)),
                    None => return None, // iterator consumed
                }
            }
        }

    }

}

<commit_msg>Fix libimagentryannotation for changes in libimagnotes<commit_after>//
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
//

use libimagstore::store::Entry;
use libimagstore::store::Store;
use libimagentrylink::internal::InternalLinker;
use libimagnotes::notestore::NoteStore;
use libimagnotes::iter::NoteIterator;
use libimagstore::storeid::StoreIdIterator;

use error::Result;
use error::AnnotationErrorKind as AEK;
use error::ResultExt;

use self::iter::*;

pub trait AnnotationFetcher<'a> {

    fn all_annotations(&'a self) -> Result<AnnotationIter<'a>>;

    fn annotations_for_entry(&'a self, entry: &Entry) -> Result<AnnotationIter<'a>>;

}

impl<'a> AnnotationFetcher<'a> for Store {

    /// Wrapper around `Note::all_notes()` of `libimagnotes` which filters out normal notes and
    /// leaves only annotations in the iterator.
    fn all_annotations(&'a self) -> Result<AnnotationIter<'a>> {
        NoteStore::all_notes(self)
            .map(|iter| AnnotationIter::new(iter, self))
            .chain_err(|| AEK::StoreReadError)
    }

    /// Get all annotations (in an iterator) for an entry
    ///
    /// Internally, this fetches the links of the entry, fetches all the entries behind the links
    /// and filters them for annotations.
    ///
    /// This might result in some heavy IO operations if a lot of stuff is linked to a single
    /// entry, but should normally be not that heavy.
    fn annotations_for_entry(&'a self, entry: &Entry) -> Result<AnnotationIter<'a>> {
        entry.get_internal_links()
            .chain_err(|| AEK::StoreReadError)
            .map(|iter| StoreIdIterator::new(Box::new(iter.map(|e| e.get_store_id().clone()))))
            .map(NoteIterator::new)
            .map(|i| AnnotationIter::new(i, self))
    }

}

pub mod iter {
    use toml::Value;

    use toml_query::read::TomlValueReadExt;

    use libimagnotes::iter::NoteIterator;
    use libimagstore::store::Store;
    use libimagstore::store::FileLockEntry;

    use error::Result;
    use error::AnnotationErrorKind as AEK;
    use error::AnnotationError as AE;
    use error::ResultExt;

    #[derive(Debug)]
    pub struct AnnotationIter<'a>(NoteIterator, &'a Store);

    impl<'a> AnnotationIter<'a> {

        pub fn new(noteiter: NoteIterator, store: &'a Store) -> AnnotationIter<'a> {
            AnnotationIter(noteiter, store)
        }

    }

    impl<'a> Iterator for AnnotationIter<'a> {
        type Item = Result<FileLockEntry<'a>>;

        fn next(&mut self) -> Option<Self::Item> {
            loop {
                match self.0.next().map(|id| self.1.get(id)) {
                    Some(Ok(Some(note))) => {
                        match note.get_header().read("annotation.is_annotation") {
                            Ok(None) => continue, // not an annotation
                            Ok(Some(&Value::Boolean(true))) => return Some(Ok(note)),
                            Ok(Some(_)) => return Some(Err(AE::from_kind(AEK::HeaderTypeError))),
                            Err(e) => return Some(Err(e).chain_err(|| AEK::HeaderReadError)),
                        }
                    },
                    Some(Ok(None)) => continue,
                    Some(Err(e))   => return Some(Err(e).chain_err(|| AEK::StoreReadError)),
                    None           => return None, // iterator consumed
                }
            }
        }

    }

}

<|endoftext|>


<commit_before><commit_msg> Adds Rust solution for #009<commit_after><|endoftext|>


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

use crate::body::{consume_body, consume_body_with_promise, BodyOperations, BodyType};
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods};
use crate::dom::bindings::codegen::Bindings::ResponseBinding;
use crate::dom::bindings::codegen::Bindings::ResponseBinding::{
    ResponseMethods, ResponseType as DOMResponseType,
};
use crate::dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit;
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{DomRoot, MutNullableDom};
use crate::dom::bindings::str::{ByteString, USVString};
use crate::dom::globalscope::GlobalScope;
use crate::dom::headers::{is_obs_text, is_vchar};
use crate::dom::headers::{Guard, Headers};
use crate::dom::promise::Promise;
use crate::dom::xmlhttprequest::Extractable;
use dom_struct::dom_struct;
use http::header::HeaderMap as HyperHeaders;
use hyper::StatusCode;
use hyper_serde::Serde;
use net_traits::response::ResponseBody as NetTraitsResponseBody;
use servo_url::ServoUrl;
use std::cell::{Cell, Ref};
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use url::Position;

#[dom_struct]
pub struct Response {
    reflector_: Reflector,
    headers_reflector: MutNullableDom<Headers>,
    mime_type: DomRefCell<Vec<u8>>,
    body_used: Cell<bool>,
    /// `None` can be considered a StatusCode of `0`.
    #[ignore_malloc_size_of = "Defined in hyper"]
    status: DomRefCell<Option<StatusCode>>,
    raw_status: DomRefCell<Option<(u16, Vec<u8>)>>,
    response_type: DomRefCell<DOMResponseType>,
    url: DomRefCell<Option<ServoUrl>>,
    url_list: DomRefCell<Vec<ServoUrl>>,
    // For now use the existing NetTraitsResponseBody enum
    body: DomRefCell<NetTraitsResponseBody>,
    #[ignore_malloc_size_of = "Rc"]
    body_promise: DomRefCell<Option<(Rc<Promise>, BodyType)>>,
}

impl Response {
    pub fn new_inherited() -> Response {
        Response {
            reflector_: Reflector::new(),
            headers_reflector: Default::default(),
            mime_type: DomRefCell::new("".to_string().into_bytes()),
            body_used: Cell::new(false),
            status: DomRefCell::new(Some(StatusCode::OK)),
            raw_status: DomRefCell::new(Some((200, b"OK".to_vec()))),
            response_type: DomRefCell::new(DOMResponseType::Default),
            url: DomRefCell::new(None),
            url_list: DomRefCell::new(vec![]),
            body: DomRefCell::new(NetTraitsResponseBody::Empty),
            body_promise: DomRefCell::new(None),
        }
    }

    // https://fetch.spec.whatwg.org/#dom-response
    pub fn new(global: &GlobalScope) -> DomRoot<Response> {
        reflect_dom_object(
            Box::new(Response::new_inherited()),
            global,
            ResponseBinding::Wrap,
        )
    }

    pub fn Constructor(
        global: &GlobalScope,
        body: Option<BodyInit>,
        init: &ResponseBinding::ResponseInit,
    ) -> Fallible<DomRoot<Response>> {
        // Step 1
        if init.status < 200 || init.status > 599 {
            return Err(Error::Range(format!(
                "init's status member should be in the range 200 to 599, inclusive, but is {}",
                init.status
            )));
        }

        // Step 2
        if !is_valid_status_text(&init.statusText) {
            return Err(Error::Type(
                "init's statusText member does not match the reason-phrase token production"
                    .to_string(),
            ));
        }

        // Step 3
        let r = Response::new(global);

        // Step 4
        *r.status.borrow_mut() = Some(StatusCode::from_u16(init.status).unwrap());

        // Step 5
        *r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into()));

        // Step 6
        if let Some(ref headers_member) = init.headers {
            // Step 6.1
            r.Headers().empty_header_list();

            // Step 6.2
            r.Headers().fill(Some(headers_member.clone()))?;
        }

        // Step 7
        if let Some(ref body) = body {
            // Step 7.1
            if is_null_body_status(init.status) {
                return Err(Error::Type(
                    "Body is non-null but init's status member is a null body status".to_string(),
                ));
            };

            // Step 7.3
            let (extracted_body, content_type) = body.extract();
            *r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body);

            // Step 7.4
            if let Some(content_type_contents) = content_type {
                if !r
                    .Headers()
                    .Has(ByteString::new(b"Content-Type".to_vec()))
                    .unwrap()
                {
                    r.Headers().Append(
                        ByteString::new(b"Content-Type".to_vec()),
                        ByteString::new(content_type_contents.as_bytes().to_vec()),
                    )?;
                }
            };
        }

        // Step 8
        *r.mime_type.borrow_mut() = r.Headers().extract_mime_type();

        // Step 9
        // TODO: `entry settings object` is not implemented in Servo yet.

        // Step 10
        // TODO: Write this step once Promises are merged in

        // Step 11
        Ok(r)
    }

    // https://fetch.spec.whatwg.org/#dom-response-error
    pub fn Error(global: &GlobalScope) -> DomRoot<Response> {
        let r = Response::new(global);
        *r.response_type.borrow_mut() = DOMResponseType::Error;
        r.Headers().set_guard(Guard::Immutable);
        *r.raw_status.borrow_mut() = Some((0, b"".to_vec()));
        r
    }

    // https://fetch.spec.whatwg.org/#dom-response-redirect
    pub fn Redirect(
        global: &GlobalScope,
        url: USVString,
        status: u16,
    ) -> Fallible<DomRoot<Response>> {
        // Step 1
        let base_url = global.api_base_url();
        let parsed_url = base_url.join(&url.0);

        // Step 2
        let url = match parsed_url {
            Ok(url) => url,
            Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())),
        };

        // Step 3
        if !is_redirect_status(status) {
            return Err(Error::Range("status is not a redirect status".to_string()));
        }

        // Step 4
        // see Step 4 continued
        let r = Response::new(global);

        // Step 5
        *r.status.borrow_mut() = Some(StatusCode::from_u16(status).unwrap());
        *r.raw_status.borrow_mut() = Some((status, b"".to_vec()));

        // Step 6
        let url_bytestring =
            ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec()));
        r.Headers()
            .Set(ByteString::new(b"Location".to_vec()), url_bytestring)?;

        // Step 4 continued
        // Headers Guard is set to Immutable here to prevent error in Step 6
        r.Headers().set_guard(Guard::Immutable);

        // Step 7
        Ok(r)
    }

    // https://fetch.spec.whatwg.org/#concept-body-locked
    fn locked(&self) -> bool {
        // TODO: ReadableStream is unimplemented. Just return false
        // for now.
        false
    }
}

impl BodyOperations for Response {
    fn get_body_used(&self) -> bool {
        self.BodyUsed()
    }

    fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) {
        assert!(self.body_promise.borrow().is_none());
        self.body_used.set(true);
        *self.body_promise.borrow_mut() = Some((p.clone(), body_type));
    }

    fn is_locked(&self) -> bool {
        self.locked()
    }

    fn take_body(&self) -> Option<Vec<u8>> {
        let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty);
        match body {
            NetTraitsResponseBody::Done(bytes) => Some(bytes),
            body => {
                mem::replace(&mut *self.body.borrow_mut(), body);
                None
            },
        }
    }

    fn get_mime_type(&self) -> Ref<Vec<u8>> {
        self.mime_type.borrow()
    }
}

// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
    status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}

// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_status_text(status_text: &ByteString) -> bool {
    // reason-phrase  = *( HTAB / SP / VCHAR / obs-text )
    for byte in status_text.iter() {
        if !(*byte == b'\t' || *byte == b' ' || is_vchar(*byte) || is_obs_text(*byte)) {
            return false;
        }
    }
    true
}

// https://fetch.spec.whatwg.org/#null-body-status
fn is_null_body_status(status: u16) -> bool {
    status == 101 || status == 204 || status == 205 || status == 304
}

impl ResponseMethods for Response {
    // https://fetch.spec.whatwg.org/#dom-response-type
    fn Type(&self) -> DOMResponseType {
        *self.response_type.borrow() //into()
    }

    // https://fetch.spec.whatwg.org/#dom-response-url
    fn Url(&self) -> USVString {
        USVString(String::from(
            (*self.url.borrow())
                .as_ref()
                .map(|u| serialize_without_fragment(u))
                .unwrap_or(""),
        ))
    }

    // https://fetch.spec.whatwg.org/#dom-response-redirected
    fn Redirected(&self) -> bool {
        let url_list_len = self.url_list.borrow().len();
        url_list_len > 1
    }

    // https://fetch.spec.whatwg.org/#dom-response-status
    fn Status(&self) -> u16 {
        match *self.raw_status.borrow() {
            Some((s, _)) => s,
            None => 0,
        }
    }

    // https://fetch.spec.whatwg.org/#dom-response-ok
    fn Ok(&self) -> bool {
        match *self.status.borrow() {
            Some(s) => {
                let status_num = s.as_u16();
                return status_num >= 200 && status_num <= 299;
            },
            None => false,
        }
    }

    // https://fetch.spec.whatwg.org/#dom-response-statustext
    fn StatusText(&self) -> ByteString {
        match *self.raw_status.borrow() {
            Some((_, ref st)) => ByteString::new(st.clone()),
            None => ByteString::new(b"OK".to_vec()),
        }
    }

    // https://fetch.spec.whatwg.org/#dom-response-headers
    fn Headers(&self) -> DomRoot<Headers> {
        self.headers_reflector
            .or_init(|| Headers::for_response(&self.global()))
    }

    // https://fetch.spec.whatwg.org/#dom-response-clone
    fn Clone(&self) -> Fallible<DomRoot<Response>> {
        // Step 1
        if self.is_locked() || self.body_used.get() {
            return Err(Error::Type("cannot clone a disturbed response".to_string()));
        }

        // Step 2
        let new_response = Response::new(&self.global());
        new_response.Headers().set_guard(self.Headers().get_guard());
        new_response
            .Headers()
            .fill(Some(HeadersInit::Headers(self.Headers())))?;

        // https://fetch.spec.whatwg.org/#concept-response-clone
        // Instead of storing a net_traits::Response internally, we
        // only store the relevant fields, and only clone them here
        *new_response.response_type.borrow_mut() = self.response_type.borrow().clone();
        *new_response.status.borrow_mut() = self.status.borrow().clone();
        *new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone();
        *new_response.url.borrow_mut() = self.url.borrow().clone();
        *new_response.url_list.borrow_mut() = self.url_list.borrow().clone();

        if *self.body.borrow() != NetTraitsResponseBody::Empty {
            *new_response.body.borrow_mut() = self.body.borrow().clone();
        }

        // Step 3
        // TODO: This step relies on promises, which are still unimplemented.

        // Step 4
        Ok(new_response)
    }

    // https://fetch.spec.whatwg.org/#dom-body-bodyused
    fn BodyUsed(&self) -> bool {
        self.body_used.get()
    }

    // https://fetch.spec.whatwg.org/#dom-body-text
    fn Text(&self) -> Rc<Promise> {
        consume_body(self, BodyType::Text)
    }

    // https://fetch.spec.whatwg.org/#dom-body-blob
    fn Blob(&self) -> Rc<Promise> {
        consume_body(self, BodyType::Blob)
    }

    // https://fetch.spec.whatwg.org/#dom-body-formdata
    fn FormData(&self) -> Rc<Promise> {
        consume_body(self, BodyType::FormData)
    }

    // https://fetch.spec.whatwg.org/#dom-body-json
    fn Json(&self) -> Rc<Promise> {
        consume_body(self, BodyType::Json)
    }

    // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
    fn ArrayBuffer(&self) -> Rc<Promise> {
        consume_body(self, BodyType::ArrayBuffer)
    }
}

fn serialize_without_fragment(url: &ServoUrl) -> &str {
    &url[..Position::AfterQuery]
}

impl Response {
    pub fn set_type(&self, new_response_type: DOMResponseType) {
        *self.response_type.borrow_mut() = new_response_type;
    }

    pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) {
        self.Headers().set_headers(match option_hyper_headers {
            Some(hyper_headers) => hyper_headers.into_inner(),
            None => HyperHeaders::new(),
        });
    }

    pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) {
        *self.raw_status.borrow_mut() = status;
    }

    pub fn set_final_url(&self, final_url: ServoUrl) {
        *self.url.borrow_mut() = Some(final_url);
    }

    #[allow(unrooted_must_root)]
    pub fn finish(&self, body: Vec<u8>) {
        *self.body.borrow_mut() = NetTraitsResponseBody::Done(body);
        if let Some((p, body_type)) = self.body_promise.borrow_mut().take() {
            consume_body_with_promise(self, body_type, &p);
        }
    }
}
<commit_msg>Auto merge of #24378 - otaviopace:fix/responses-status-code-text, r=jdm<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::body::{consume_body, consume_body_with_promise, BodyOperations, BodyType};
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods};
use crate::dom::bindings::codegen::Bindings::ResponseBinding;
use crate::dom::bindings::codegen::Bindings::ResponseBinding::{
    ResponseMethods, ResponseType as DOMResponseType,
};
use crate::dom::bindings::codegen::Bindings::XMLHttpRequestBinding::BodyInit;
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{DomRoot, MutNullableDom};
use crate::dom::bindings::str::{ByteString, USVString};
use crate::dom::globalscope::GlobalScope;
use crate::dom::headers::{is_obs_text, is_vchar};
use crate::dom::headers::{Guard, Headers};
use crate::dom::promise::Promise;
use crate::dom::xmlhttprequest::Extractable;
use dom_struct::dom_struct;
use http::header::HeaderMap as HyperHeaders;
use hyper::StatusCode;
use hyper_serde::Serde;
use net_traits::response::ResponseBody as NetTraitsResponseBody;
use servo_url::ServoUrl;
use std::cell::{Cell, Ref};
use std::mem;
use std::rc::Rc;
use std::str::FromStr;
use url::Position;

#[dom_struct]
pub struct Response {
    reflector_: Reflector,
    headers_reflector: MutNullableDom<Headers>,
    mime_type: DomRefCell<Vec<u8>>,
    body_used: Cell<bool>,
    /// `None` can be considered a StatusCode of `0`.
    #[ignore_malloc_size_of = "Defined in hyper"]
    status: DomRefCell<Option<StatusCode>>,
    raw_status: DomRefCell<Option<(u16, Vec<u8>)>>,
    response_type: DomRefCell<DOMResponseType>,
    url: DomRefCell<Option<ServoUrl>>,
    url_list: DomRefCell<Vec<ServoUrl>>,
    // For now use the existing NetTraitsResponseBody enum
    body: DomRefCell<NetTraitsResponseBody>,
    #[ignore_malloc_size_of = "Rc"]
    body_promise: DomRefCell<Option<(Rc<Promise>, BodyType)>>,
}

impl Response {
    pub fn new_inherited() -> Response {
        Response {
            reflector_: Reflector::new(),
            headers_reflector: Default::default(),
            mime_type: DomRefCell::new("".to_string().into_bytes()),
            body_used: Cell::new(false),
            status: DomRefCell::new(Some(StatusCode::OK)),
            raw_status: DomRefCell::new(Some((200, b"".to_vec()))),
            response_type: DomRefCell::new(DOMResponseType::Default),
            url: DomRefCell::new(None),
            url_list: DomRefCell::new(vec![]),
            body: DomRefCell::new(NetTraitsResponseBody::Empty),
            body_promise: DomRefCell::new(None),
        }
    }

    // https://fetch.spec.whatwg.org/#dom-response
    pub fn new(global: &GlobalScope) -> DomRoot<Response> {
        reflect_dom_object(
            Box::new(Response::new_inherited()),
            global,
            ResponseBinding::Wrap,
        )
    }

    pub fn Constructor(
        global: &GlobalScope,
        body: Option<BodyInit>,
        init: &ResponseBinding::ResponseInit,
    ) -> Fallible<DomRoot<Response>> {
        // Step 1
        if init.status < 200 || init.status > 599 {
            return Err(Error::Range(format!(
                "init's status member should be in the range 200 to 599, inclusive, but is {}",
                init.status
            )));
        }

        // Step 2
        if !is_valid_status_text(&init.statusText) {
            return Err(Error::Type(
                "init's statusText member does not match the reason-phrase token production"
                    .to_string(),
            ));
        }

        // Step 3
        let r = Response::new(global);

        // Step 4
        *r.status.borrow_mut() = Some(StatusCode::from_u16(init.status).unwrap());

        // Step 5
        *r.raw_status.borrow_mut() = Some((init.status, init.statusText.clone().into()));

        // Step 6
        if let Some(ref headers_member) = init.headers {
            // Step 6.1
            r.Headers().empty_header_list();

            // Step 6.2
            r.Headers().fill(Some(headers_member.clone()))?;
        }

        // Step 7
        if let Some(ref body) = body {
            // Step 7.1
            if is_null_body_status(init.status) {
                return Err(Error::Type(
                    "Body is non-null but init's status member is a null body status".to_string(),
                ));
            };

            // Step 7.3
            let (extracted_body, content_type) = body.extract();
            *r.body.borrow_mut() = NetTraitsResponseBody::Done(extracted_body);

            // Step 7.4
            if let Some(content_type_contents) = content_type {
                if !r
                    .Headers()
                    .Has(ByteString::new(b"Content-Type".to_vec()))
                    .unwrap()
                {
                    r.Headers().Append(
                        ByteString::new(b"Content-Type".to_vec()),
                        ByteString::new(content_type_contents.as_bytes().to_vec()),
                    )?;
                }
            };
        }

        // Step 8
        *r.mime_type.borrow_mut() = r.Headers().extract_mime_type();

        // Step 9
        // TODO: `entry settings object` is not implemented in Servo yet.

        // Step 10
        // TODO: Write this step once Promises are merged in

        // Step 11
        Ok(r)
    }

    // https://fetch.spec.whatwg.org/#dom-response-error
    pub fn Error(global: &GlobalScope) -> DomRoot<Response> {
        let r = Response::new(global);
        *r.response_type.borrow_mut() = DOMResponseType::Error;
        r.Headers().set_guard(Guard::Immutable);
        *r.raw_status.borrow_mut() = Some((0, b"".to_vec()));
        r
    }

    // https://fetch.spec.whatwg.org/#dom-response-redirect
    pub fn Redirect(
        global: &GlobalScope,
        url: USVString,
        status: u16,
    ) -> Fallible<DomRoot<Response>> {
        // Step 1
        let base_url = global.api_base_url();
        let parsed_url = base_url.join(&url.0);

        // Step 2
        let url = match parsed_url {
            Ok(url) => url,
            Err(_) => return Err(Error::Type("ServoUrl could not be parsed".to_string())),
        };

        // Step 3
        if !is_redirect_status(status) {
            return Err(Error::Range("status is not a redirect status".to_string()));
        }

        // Step 4
        // see Step 4 continued
        let r = Response::new(global);

        // Step 5
        *r.status.borrow_mut() = Some(StatusCode::from_u16(status).unwrap());
        *r.raw_status.borrow_mut() = Some((status, b"".to_vec()));

        // Step 6
        let url_bytestring =
            ByteString::from_str(url.as_str()).unwrap_or(ByteString::new(b"".to_vec()));
        r.Headers()
            .Set(ByteString::new(b"Location".to_vec()), url_bytestring)?;

        // Step 4 continued
        // Headers Guard is set to Immutable here to prevent error in Step 6
        r.Headers().set_guard(Guard::Immutable);

        // Step 7
        Ok(r)
    }

    // https://fetch.spec.whatwg.org/#concept-body-locked
    fn locked(&self) -> bool {
        // TODO: ReadableStream is unimplemented. Just return false
        // for now.
        false
    }
}

impl BodyOperations for Response {
    fn get_body_used(&self) -> bool {
        self.BodyUsed()
    }

    fn set_body_promise(&self, p: &Rc<Promise>, body_type: BodyType) {
        assert!(self.body_promise.borrow().is_none());
        self.body_used.set(true);
        *self.body_promise.borrow_mut() = Some((p.clone(), body_type));
    }

    fn is_locked(&self) -> bool {
        self.locked()
    }

    fn take_body(&self) -> Option<Vec<u8>> {
        let body = mem::replace(&mut *self.body.borrow_mut(), NetTraitsResponseBody::Empty);
        match body {
            NetTraitsResponseBody::Done(bytes) => Some(bytes),
            body => {
                mem::replace(&mut *self.body.borrow_mut(), body);
                None
            },
        }
    }

    fn get_mime_type(&self) -> Ref<Vec<u8>> {
        self.mime_type.borrow()
    }
}

// https://fetch.spec.whatwg.org/#redirect-status
fn is_redirect_status(status: u16) -> bool {
    status == 301 || status == 302 || status == 303 || status == 307 || status == 308
}

// https://tools.ietf.org/html/rfc7230#section-3.1.2
fn is_valid_status_text(status_text: &ByteString) -> bool {
    // reason-phrase  = *( HTAB / SP / VCHAR / obs-text )
    for byte in status_text.iter() {
        if !(*byte == b'\t' || *byte == b' ' || is_vchar(*byte) || is_obs_text(*byte)) {
            return false;
        }
    }
    true
}

// https://fetch.spec.whatwg.org/#null-body-status
fn is_null_body_status(status: u16) -> bool {
    status == 101 || status == 204 || status == 205 || status == 304
}

impl ResponseMethods for Response {
    // https://fetch.spec.whatwg.org/#dom-response-type
    fn Type(&self) -> DOMResponseType {
        *self.response_type.borrow() //into()
    }

    // https://fetch.spec.whatwg.org/#dom-response-url
    fn Url(&self) -> USVString {
        USVString(String::from(
            (*self.url.borrow())
                .as_ref()
                .map(|u| serialize_without_fragment(u))
                .unwrap_or(""),
        ))
    }

    // https://fetch.spec.whatwg.org/#dom-response-redirected
    fn Redirected(&self) -> bool {
        let url_list_len = self.url_list.borrow().len();
        url_list_len > 1
    }

    // https://fetch.spec.whatwg.org/#dom-response-status
    fn Status(&self) -> u16 {
        match *self.raw_status.borrow() {
            Some((s, _)) => s,
            None => 0,
        }
    }

    // https://fetch.spec.whatwg.org/#dom-response-ok
    fn Ok(&self) -> bool {
        match *self.status.borrow() {
            Some(s) => {
                let status_num = s.as_u16();
                return status_num >= 200 && status_num <= 299;
            },
            None => false,
        }
    }

    // https://fetch.spec.whatwg.org/#dom-response-statustext
    fn StatusText(&self) -> ByteString {
        match *self.raw_status.borrow() {
            Some((_, ref st)) => ByteString::new(st.clone()),
            None => ByteString::new(b"".to_vec()),
        }
    }

    // https://fetch.spec.whatwg.org/#dom-response-headers
    fn Headers(&self) -> DomRoot<Headers> {
        self.headers_reflector
            .or_init(|| Headers::for_response(&self.global()))
    }

    // https://fetch.spec.whatwg.org/#dom-response-clone
    fn Clone(&self) -> Fallible<DomRoot<Response>> {
        // Step 1
        if self.is_locked() || self.body_used.get() {
            return Err(Error::Type("cannot clone a disturbed response".to_string()));
        }

        // Step 2
        let new_response = Response::new(&self.global());
        new_response.Headers().set_guard(self.Headers().get_guard());
        new_response
            .Headers()
            .fill(Some(HeadersInit::Headers(self.Headers())))?;

        // https://fetch.spec.whatwg.org/#concept-response-clone
        // Instead of storing a net_traits::Response internally, we
        // only store the relevant fields, and only clone them here
        *new_response.response_type.borrow_mut() = self.response_type.borrow().clone();
        *new_response.status.borrow_mut() = self.status.borrow().clone();
        *new_response.raw_status.borrow_mut() = self.raw_status.borrow().clone();
        *new_response.url.borrow_mut() = self.url.borrow().clone();
        *new_response.url_list.borrow_mut() = self.url_list.borrow().clone();

        if *self.body.borrow() != NetTraitsResponseBody::Empty {
            *new_response.body.borrow_mut() = self.body.borrow().clone();
        }

        // Step 3
        // TODO: This step relies on promises, which are still unimplemented.

        // Step 4
        Ok(new_response)
    }

    // https://fetch.spec.whatwg.org/#dom-body-bodyused
    fn BodyUsed(&self) -> bool {
        self.body_used.get()
    }

    // https://fetch.spec.whatwg.org/#dom-body-text
    fn Text(&self) -> Rc<Promise> {
        consume_body(self, BodyType::Text)
    }

    // https://fetch.spec.whatwg.org/#dom-body-blob
    fn Blob(&self) -> Rc<Promise> {
        consume_body(self, BodyType::Blob)
    }

    // https://fetch.spec.whatwg.org/#dom-body-formdata
    fn FormData(&self) -> Rc<Promise> {
        consume_body(self, BodyType::FormData)
    }

    // https://fetch.spec.whatwg.org/#dom-body-json
    fn Json(&self) -> Rc<Promise> {
        consume_body(self, BodyType::Json)
    }

    // https://fetch.spec.whatwg.org/#dom-body-arraybuffer
    fn ArrayBuffer(&self) -> Rc<Promise> {
        consume_body(self, BodyType::ArrayBuffer)
    }
}

fn serialize_without_fragment(url: &ServoUrl) -> &str {
    &url[..Position::AfterQuery]
}

impl Response {
    pub fn set_type(&self, new_response_type: DOMResponseType) {
        *self.response_type.borrow_mut() = new_response_type;
    }

    pub fn set_headers(&self, option_hyper_headers: Option<Serde<HyperHeaders>>) {
        self.Headers().set_headers(match option_hyper_headers {
            Some(hyper_headers) => hyper_headers.into_inner(),
            None => HyperHeaders::new(),
        });
    }

    pub fn set_raw_status(&self, status: Option<(u16, Vec<u8>)>) {
        *self.raw_status.borrow_mut() = status;
    }

    pub fn set_final_url(&self, final_url: ServoUrl) {
        *self.url.borrow_mut() = Some(final_url);
    }

    #[allow(unrooted_must_root)]
    pub fn finish(&self, body: Vec<u8>) {
        *self.body.borrow_mut() = NetTraitsResponseBody::Done(body);
        if let Some((p, body_type)) = self.body_promise.borrow_mut().take() {
            consume_body_with_promise(self, body_type, &p);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove a debugging print.<commit_after><|endoftext|>


<commit_before><commit_msg>Updated to work on Windows<commit_after><|endoftext|>


<commit_before><commit_msg>initial<commit_after>pub mod num;

#[cfg(test)]
mod tests;
<|endoftext|>


<commit_before><commit_msg>Add conversion of formatted char to normal char<commit_after><|endoftext|>


<commit_before><commit_msg>Add a test demonstrating the limitations of our lfietime resolution<commit_after>trait Id {
    type Out;

    fn id(self) -> Self::Out;
}

impl<'a> Id for &'a mut i32 {
    type Out = &'a mut i32;

    fn id(self) -> Self { self }
}

impl<'a> Id for &'a mut u32 {
    type Out = &'a mut u32;

    fn id(self) -> Self { self }
}

fn foo<T>(mut x: T) where for<'a> &'a mut T: Id
{
    let x = &mut x;
    let _y = x.id();
    // Inspecting the trace should show that _y has a type involving a local lifetime, when it gets validated.
    // Unfortunately, there doesn't seem to be a way to actually have a test fail if it does not have the right
    // type.  Currently, this is NOT working correctly; see <https://github.com/solson/miri/issues/298>.
}

fn main() {
    foo(3)
}
<|endoftext|>


<commit_before><commit_msg>Add Runtime::input_is_pipe()<commit_after><|endoftext|>


<commit_before><commit_msg>Using big endian now<commit_after><|endoftext|>


<commit_before><commit_msg>add examples/airspyrx.rs<commit_after>
extern crate airspy;
use airspy::AirspySamplerate;

#[macro_use]
extern crate log;
extern crate fern;
extern crate time;

fn main() {
    // setup fern logger
    let logger_config = fern::DispatchConfig {
        format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| {
            let t = time::now();
            let ms = t.tm_nsec/1000_000;
            format!("{}.{:3} [{}] {}", t.strftime("%Y-%m-%dT%H:%M:%S").unwrap(), ms, level, msg)
        }),
        output: vec![fern::OutputConfig::stderr()],
        level: log::LogLevelFilter::Trace,
    };

    if let Err(e) = fern::init_global_logger(logger_config, log::LogLevelFilter::Trace) {
        panic!("Failed to initialize global logger: {}", e);
    }

    match airspy::Airspy::new() {
        Ok(mut device) => {
            info!("device opened sucessfully");
            device.set_samplerate(AirspySamplerate::Sps10000000).unwrap();
        }
        Err(e) => {
            error!("error {:?}", e);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Refactor to use Iterator::fold()<commit_after><|endoftext|>


<commit_before><commit_msg>Add BCH decoding based on PGZ<commit_after>use std;

const GEN: &'static [u16] = &[
    0b1000000000000000,
    0b0100000000000000,
    0b0010000000000000,
    0b0001000000000000,
    0b0000100000000000,
    0b0000010000000000,
    0b0000001000000000,
    0b0000000100000000,
    0b0000000010000000,
    0b0000000001000000,
    0b0000000000100000,
    0b0000000000010000,
    0b0000000000001000,
    0b0000000000000100,
    0b0000000000000010,
    0b0000000000000001,
    0b1110110001000111,
    0b1001101001100100,
    0b0100110100110010,
    0b0010011010011001,
    0b1111111100001011,
    0b1001001111000010,
    0b0100100111100001,
    0b1100100010110111,
    0b1000100000011100,
    0b0100010000001110,
    0b0010001000000111,
    0b1111110101000100,
    0b0111111010100010,
    0b0011111101010001,
    0b1111001111101111,
    0b1001010110110000,
    0b0100101011011000,
    0b0010010101101100,
    0b0001001010110110,
    0b0000100101011011,
    0b1110100011101010,
    0b0111010001110101,
    0b1101011001111101,
    0b1000011101111001,
    0b1010111111111011,
    0b1011101110111010,
    0b0101110111011101,
    0b1100001010101001,
    0b1000110100010011,
    0b1010101011001110,
    0b0101010101100111,
    0b1100011011110100,
    0b0110001101111010,
    0b0011000110111101,
    0b1111010010011001,
    0b1001011000001011,
    0b1010011101000010,
    0b0101001110100001,
    0b1100010110010111,
    0b1000111010001100,
    0b0100011101000110,
    0b0010001110100011,
    0b1111110110010110,
    0b0111111011001011,
    0b1101001100100010,
    0b0110100110010001,
    0b1101100010001111,
    0b0000000000000011,
];

pub fn encode(word: u16) -> u64 {
    GEN.iter().fold(0, |accum, row| {
        accum << 1 | ((word & row).count_ones() % 2) as u64
    })
}

pub fn decode(mut word: u64) -> Option<(u64, usize)> {
    let syns = syndromes(word);

    // 2t+1 = 23 => t = 11
    for err in (1..12).rev() {
        let matrix = match SyndromeMatrix::new(&syns, err).invert() {
            Some(m) => m,
            None => continue,
        };

        let coefs = ErrorCoefs::new(matrix, err).solve(&syns);
        let locs = ErrorLocations::new(coefs.iter().cloned().rev());

        for loc in locs.take(err) {
            word ^= 1 << loc.power().unwrap();
        }

        return Some((word, err));
    }

    Some((word, 0))
}

// word has r_{n-1} as MSB and r_0 as LSB
fn syndromes(word: u64) -> Vec<Codeword> {
    (1..23).map(|t| {
        (0..63).fold(Codeword::new(0), |s, b| {
            if word >> b & 1 == 0 {
                s
            } else {
                s + Codeword::for_power(b * t)
            }
        })
    }).collect()
}

struct SyndromeMatrix {
    cells: Vec<Vec<Codeword>>,
    rows: usize,
    cols: usize,
}

impl SyndromeMatrix {
    pub fn new(syndromes: &[Codeword], dim: usize) -> SyndromeMatrix {
        assert!(syndromes.len() >= dim * 2 - 2);

        SyndromeMatrix {
            cells: Self::build(syndromes, dim),
            rows: dim,
            cols: dim * 2,
        }
    }

    fn build(syndromes: &[Codeword], dim: usize) -> Vec<Vec<Codeword>> {
        (0..dim).map(|row| {
            (0..dim).map(|col| {
                syndromes[row + col]
            }).chain((0..dim).map(|col| {
                if col == row {
                    Codeword::for_power(0)
                } else {
                    Codeword::new(0)
                }
            })).collect()
        }).collect()
    }

    pub fn invert(mut self) -> Option<Vec<Vec<Codeword>>> {
        let rows = self.rows;
        let cols = self.cols;

        for pos in 0..rows {
            let max = (pos..rows).fold(pos, |max, next| {
                if self.cells[next][pos] > self.cells[max][pos] {
                    next
                } else {
                    max
                }
            });

            if self.cells[max][pos].zero() {
                return None;
            }

            self.cells.swap(pos, max);
            self.reduce((pos+1)..rows, pos);
        }

        for pos in (0..rows).rev() {
            self.reduce(0..pos, pos);
            let div = self.cells[pos][pos];

            for col in 0..cols {
                self.cells[pos][col] = self.cells[pos][col] / div;
            }
        }

        Some(self.cells)
    }

    fn reduce(&mut self, rows: std::ops::Range<usize>, target: usize) {
        for row in rows {
            let ratio = self.cells[row][target] / self.cells[target][target];

            for col in target..self.cols {
                self.cells[row][col] = self.cells[row][col] -
                    self.cells[target][col] * ratio;
            }
        }
    }
}

#[derive(Debug)]
struct ErrorCoefs {
    cells: Vec<Vec<Codeword>>,
    dim: usize,
}

impl ErrorCoefs {
    fn new(cells: Vec<Vec<Codeword>>, dim: usize) -> Self {
        ErrorCoefs {
            cells: cells,
            dim: dim,
        }
    }

    pub fn solve(self, syndromes: &[Codeword]) -> Vec<Codeword> {
        let rhs = &syndromes[self.dim..];

        self.cells.iter().map(|row| {
            row.iter()
                .skip(self.dim)
                .zip(rhs)
                .fold(Codeword::new(0), |s, (&a, &b)| {
                    s + a * b
                })
        }).collect()
    }
}

struct ErrorLocations {
    terms: Vec<Codeword>,
    pow: usize,
}

impl ErrorLocations {
    // Λ(x) = coefs[0]*x + coefs[1]*x^2 + ...
    pub fn new<T: Iterator<Item = Codeword>>(coefs: T) -> ErrorLocations {
        ErrorLocations {
            terms: coefs.enumerate().map(|(p, c)| {
                c / Codeword::for_power(p + 1)
            }).collect(),
            pow: 0,
        }
    }

    fn update_terms(&mut self) {
        for (j, term) in self.terms.iter_mut().enumerate() {
            *term = *term * Codeword::for_power(j + 1);
        }
    }

    fn eval(&self) -> Codeword {
        self.terms.iter().fold(Codeword::for_power(0), |s, &x| {
            s + x

        })
    }
}

impl Iterator for ErrorLocations {
    type Item = Codeword;

    fn next(&mut self) -> Option<Self::Item> {
        while self.pow < POWERS.len() {
            let pow = self.pow;
            self.pow += 1;

            self.update_terms();

            if self.eval().zero() {
                return Some(Codeword::for_power(0) / Codeword::for_power(pow));
            }
        }

        None
    }
}

#[derive(Copy, Clone)]
struct Codeword(u8);

impl std::fmt::Debug for Codeword {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "Codeword({:?})", self.power())
    }
}

impl Codeword {
    pub fn new(codeword: u8) -> Codeword {
        Codeword(codeword)
    }

    pub fn zero(&self) -> bool { self.0 == 0 }

    pub fn power(&self) -> Option<usize> {
        if self.zero() {
            None
        } else {
            Some(POWERS[self.0 as usize - 1])
        }
    }

    fn for_power(power: usize) -> Codeword {
        Codeword::new(CODEWORDS[power % POWERS.len()])
    }
}

impl std::ops::Mul for Codeword {
    type Output = Codeword;

    fn mul(self, rhs: Codeword) -> Self::Output {
        match (self.power(), rhs.power()) {
            (Some(p), Some(q)) => Codeword::for_power(p + q),
            _ => Codeword::new(0),
        }
    }
}

impl std::ops::Div for Codeword {
    type Output = Codeword;

    fn div(self, rhs: Codeword) -> Self::Output {
        match (self.power(), rhs.power()) {
            // min(power) = -62 => 63+min(power) > 0
            (Some(p), Some(q)) => Codeword::for_power(p + POWERS.len() - q),
            (None, Some(_)) => Codeword::new(0),
            (_, None) => panic!("divide by zero"),
        }
    }
}

impl std::ops::Add for Codeword {
    type Output = Codeword;

    fn add(self, rhs: Codeword) -> Self::Output {
        Codeword::new(self.0 ^ rhs.0)
    }
}

impl std::ops::Sub for Codeword {
    type Output = Codeword;

    fn sub(self, rhs: Codeword) -> Self::Output {
        self + rhs
    }
}

impl std::cmp::PartialEq for Codeword {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl std::cmp::Eq for Codeword {}

impl std::cmp::PartialOrd for Codeword {
    fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> {
        use std::cmp::Ordering::*;

        match (self.power(), rhs.power()) {
            (Some(p), Some(q)) => Some(p.cmp(&q)),
            (Some(_), None) => Some(Greater),
            (None, Some(_)) => Some(Less),
            (None, None) => Some(Equal),
        }
    }
}

impl std::cmp::Ord for Codeword {
    fn cmp(&self, rhs: &Self) -> std::cmp::Ordering {
        self.partial_cmp(rhs).unwrap()
    }
}

// Maps α^i to codewords.
const CODEWORDS: &'static [u8] = &[
    0b100000,
    0b010000,
    0b001000,
    0b000100,
    0b000010,
    0b000001,
    0b110000,
    0b011000,
    0b001100,
    0b000110,
    0b000011,
    0b110001,
    0b101000,
    0b010100,
    0b001010,
    0b000101,
    0b110010,
    0b011001,
    0b111100,
    0b011110,
    0b001111,
    0b110111,
    0b101011,
    0b100101,
    0b100010,
    0b010001,
    0b111000,
    0b011100,
    0b001110,
    0b000111,
    0b110011,
    0b101001,
    0b100100,
    0b010010,
    0b001001,
    0b110100,
    0b011010,
    0b001101,
    0b110110,
    0b011011,
    0b111101,
    0b101110,
    0b010111,
    0b111011,
    0b101101,
    0b100110,
    0b010011,
    0b111001,
    0b101100,
    0b010110,
    0b001011,
    0b110101,
    0b101010,
    0b010101,
    0b111010,
    0b011101,
    0b111110,
    0b011111,
    0b111111,
    0b101111,
    0b100111,
    0b100011,
    0b100001
];

// Maps codewords to α^i.
const POWERS: &'static [usize] = &[
    5,
    4,
    10,
    3,
    15,
    9,
    29,
    2,
    34,
    14,
    50,
    8,
    37,
    28,
    20,
    1,
    25,
    33,
    46,
    13,
    53,
    49,
    42,
    7,
    17,
    36,
    39,
    27,
    55,
    19,
    57,
    0,
    62,
    24,
    61,
    32,
    23,
    45,
    60,
    12,
    31,
    52,
    22,
    48,
    44,
    41,
    59,
    6,
    11,
    16,
    30,
    35,
    51,
    38,
    21,
    26,
    47,
    54,
    43,
    18,
    40,
    56,
    58,
];

#[cfg(test)]
mod test {
    use super::{encode, decode, syndromes, Codeword};

    #[test]
    fn test_for_power() {
        assert_eq!(Codeword::for_power(0).0, 0b100000);
        assert_eq!(Codeword::for_power(62).0, 0b100001);
        assert_eq!(Codeword::for_power(63).0, 0b100000);
    }

    #[test]
    fn test_add_sub() {
        assert_eq!((Codeword::new(0b100000) + Codeword::new(0b010000)).0, 0b110000);
        assert_eq!((Codeword::new(0b100000) - Codeword::new(0b010000)).0, 0b110000);
        assert_eq!((Codeword::new(0b100001) + Codeword::new(0b100001)).0, 0b000000);
        assert_eq!((Codeword::new(0b100001) - Codeword::new(0b100001)).0, 0b000000);
        assert_eq!((Codeword::new(0b100001) + Codeword::new(0b110100)).0, 0b010101);
        assert_eq!((Codeword::new(0b100001) - Codeword::new(0b110100)).0, 0b010101);
    }

    #[test]
    fn test_mul() {
        assert_eq!((Codeword::new(0b011000) * Codeword::new(0b101000)).0, 0b011110);
        assert_eq!((Codeword::new(0b000000) * Codeword::new(0b101000)).0, 0b000000);
        assert_eq!((Codeword::new(0b011000) * Codeword::new(0b000000)).0, 0b000000);
        assert_eq!((Codeword::new(0b000000) * Codeword::new(0b000000)).0, 0b000000);
        assert_eq!((Codeword::new(0b100001) * Codeword::new(0b100000)).0, 0b100001);
        assert_eq!((Codeword::new(0b100001) * Codeword::new(0b010000)).0, 0b100000);
        assert_eq!((Codeword::new(0b110011) * Codeword::new(0b110011)).0, 0b100111);
        assert_eq!((Codeword::new(0b111101) * Codeword::new(0b111101)).0, 0b011001);
    }

    #[test]
    fn test_div() {
        assert_eq!((Codeword::new(0b000100) / Codeword::new(0b101000)).0, 0b111010);
        assert_eq!((Codeword::new(0b000000) / Codeword::new(0b101000)).0, 0b000000);
        assert_eq!((Codeword::new(0b011110) / Codeword::new(0b100000)).0, 0b011110);
        assert_eq!((Codeword::new(0b011110) / Codeword::new(0b011110)).0, 0b100000);
    }

    #[test]
    fn test_cmp() {
        assert!(Codeword::new(0b100000) > Codeword::new(0b000000));
        assert!(Codeword::new(0b000000) == Codeword::new(0b000000));
        assert!(Codeword::new(0b010000) > Codeword::new(0b100000));
        assert!(Codeword::new(0b100001) > Codeword::new(0b100000));
    }

    #[test]
    fn test_encode() {
        assert_eq!(encode(0b1111111100000000), 0b1111111100000000100100110001000011000010001100000110100001101000);
        assert_eq!(encode(0b0011)&1, 0);
        assert_eq!(encode(0b0101)&1, 1);
        assert_eq!(encode(0b1010)&1, 1);
        assert_eq!(encode(0b1100)&1, 0);
        assert_eq!(encode(0b1111)&1, 0);
    }

    #[test]
    fn test_syndromes() {
        let w = encode(0b1111111100000000)>>1;

        assert!(syndromes(w).iter().all(|s| s.zero()));
        assert!(!syndromes(w ^ 1<<60).iter().all(|s| s.zero()));
    }
}
<|endoftext|>


<commit_before><commit_msg>Return a 404 when a file isn't found.<commit_after><|endoftext|>


<commit_before><commit_msg>Add tee<commit_after>extern mod extra;
use extra::getopts::groups::{getopts,optflag};
use std::io::fs::File;
use std::path::Path;
mod common;
fn main() {
    let opts = ~[
        optflag("a", "", "Append the output to the files rather than overwriting them."),
    ];
    let args = std::os::args();
    let mut stderr = std::io::stderr();
    let matches = match getopts(args.tail(), opts) {
        Err(f) => {
            stderr.write_line(f.to_err_msg());
            common::print_usage("usage: tee [-a] [file ...]", opts);
            fail!();
        }
        Ok(m) => { m }
    };
    let is_append = matches.opt_present("a");
    let mut files = ~[~std::io::stdout() as ~Writer];

    // open files
    for filename in matches.free.iter() {
        match std::io::result(|| {
            match File::open_mode(&Path::new(filename.as_slice()), if is_append { std::io::Append } else { std::io::Truncate }, std::io::Write) {
                Some(f) => {files.push(~f as ~Writer);}
                None => {}
            }
        }) {
            Err(e) => {
                std::io::stderr().write_line(format!("tee: {:s}: {:s}", *filename, e.desc));
            }
            _ => {}
        };
    }

    // wait from stdin and write to files
    let mut buf = [0u8, ..1024];
    let mut stdin = std::io::stdin();
    while !stdin.eof() {
        match std::io::result(|| {
            let len = stdin.read(buf);
            if len.is_some() {
                for f in files.mut_iter() {
                    f.write(buf.slice(0, len.unwrap()))
                }
            }
        }) {
            Err(e) => {
                if e.kind != std::io::EndOfFile {
                    std::io::stderr().write_line(format!("tee: {:s}", e.desc));
                } else {
                    break;
                }
            }
            _ => {}
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Renaming<commit_after><|endoftext|>


<commit_before><commit_msg>Add ToError implementation for Spanned<commit_after><|endoftext|>


<commit_before><commit_msg>Add test case for omitting dllimport during cross-lang LTO.<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.

// This test makes sure that functions get annotated with the proper
// "target-cpu" attribute in LLVM.

// no-prefer-dynamic
// only-msvc
// compile-flags: -C no-prepopulate-passes -Z cross-lang-lto

#![crate_type = "rlib"]

// CHECK-NOT: @{{.*}}__imp_{{.*}}GLOBAL{{.*}} = global i8*

pub static GLOBAL: u32 = 0;
pub static mut GLOBAL2: u32 = 0;
<|endoftext|>


<commit_before><commit_msg>Added a test for #[cfg] on non-optional positions<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

fn main() {
    let _ = #[cfg(unset)] ();
    //~^ ERROR removing an expression is not supported in this position
    let _ = 1 + 2 + #[cfg(unset)] 3;
    //~^ ERROR removing an expression is not supported in this position
    let _ = [1, 2, 3][#[cfg(unset)] 1];
    //~^ ERROR removing an expression is not supported in this position
}
<|endoftext|>


<commit_before><commit_msg>Add test case for Self:: links<commit_after>#![crate_name = "foo"]
// @has foo/enum.E1.html '//a/@href' '../foo/enum.E1.html#variant.A'

/// [Self::A::b]
pub enum E1 {
    A { b: usize }
}

// @has foo/enum.E2.html '//a/@href' '../foo/enum.E2.html#variant.A'

/// [Self::A::b]
pub enum E2 {
    A { b: usize }
}
<|endoftext|>


<commit_before><commit_msg>blink_k20: Initial commit<commit_after>#![feature(phase)]
#![crate_type="staticlib"]
#![no_std]

extern crate core;
extern crate zinc;

use core::option::Some;
use zinc::hal::k20::pin;
use zinc::hal::pin::GPIO;
use zinc::hal::cortex_m4::systick;

/// Wait the given number of SysTick ticks
pub fn wait(ticks: u32) {
  let mut n = ticks;
  let mut t = systick::reg::SYSTICK.CURRENT();
  loop {
    if systick::reg::SYSTICK.CURRENT() > t {
      t = systick::reg::SYSTICK.CURRENT();
      n -= 1;
      if n == 0 {
        break;
      }
    }
  }
}

#[no_mangle]
#[no_split_stack]
#[allow(unused_variable)]
#[allow(dead_code)]
pub unsafe fn main() {
  zinc::hal::mem_init::init_stack();
  zinc::hal::mem_init::init_data();

  // Pins for MC HCK (http://www.mchck.org/)
  let led1 = pin::Pin::new(pin::PortB, 16, pin::GPIO, Some(zinc::hal::pin::Out));

  systick::setup(480000, false);
  systick::enable();
  loop {
    led1.set_high();
    wait(10);
    led1.set_low();
    wait(10);
  }
}
<|endoftext|>


<commit_before><commit_msg>Improve block comment test<commit_after><|endoftext|>