<commit_before>// TODO: Refactor using a matrix for performance

use redox::*;

mod cmd;

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
        if self.offset > 0 {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset - 1].to_string() +
                &self.string[self.offset .. self.string.len()];
            self.offset -= 1;
        }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset].to_string() +
                &self.string[self.offset + 1 .. self.string.len()];
        }
    }

    // TODO: Add methods for multiple movements
    fn up(&mut self) {
        let mut new_offset = 0;
        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let mut new_offset = self.string.len();
        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
    }

    fn cur(&self) -> char {
        self.string.chars().nth(self.offset).unwrap_or('\0')
    }

    fn insert(&mut self, c: char, window: &mut Window) {
        window.set_title(&format!("{}{}{}","self (", &self.url, ") Changed"));
        self.string = self.string[0 .. self.offset].to_string() +
            &c.to_string() +
            &self.string[self.offset .. self.string.len()];
        self.offset += 1;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
        (rand() % 300 + 50) as isize,
        576,
        400,
        &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;
        let mut swap = 0;
        let mut period = String::new();
        let mut is_recording = false;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        cmd::exec(self, &mut mode, &mut multiplier, &mut last_change, key_event, &mut window, &mut swap, &mut period, &mut is_recording);

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<commit_msg>Make movement more logical<commit_after>// TODO: Refactor using a matrix for performance

use redox::*;

mod cmd;

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Mode {
    Insert,
    Normal,
}

pub struct Editor {
    url: String,
    file: Option<File>,
    string: String,
    offset: usize,
    scroll_x: isize,
    scroll_y: isize,
}

impl Editor {
    #[inline(never)]
    pub fn new() -> Self {
        Editor {
            url: String::new(),
            file: Option::None,
            string: String::new(),
            offset: 0,
            scroll_x: 0,
            scroll_y: 0,
        }
    }

    fn backspace(&mut self, window: &mut Window) {
        if self.offset > 0 {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset - 1].to_string() +
                &self.string[self.offset .. self.string.len()];
            self.offset -= 1;
        }
    }

    fn delete(&mut self, window: &mut Window) {
        if self.offset < self.string.len() {
            window.set_title(&format!("{}{}{}","Editor (", &self.url, ") Changed"));
            self.string = self.string[0 .. self.offset].to_string() +
                &self.string[self.offset + 1 .. self.string.len()];
        }
    }

    // TODO: Add methods for multiple movements
    fn up(&mut self) {
        let x = self.get_x() - if self.cur() == '\n' { 1 } else { 0 };
        while self.cur() != '\n' {
            self.left();
        }
        self.right();
        let mut new_offset = 0;

        for i in 2..self.offset {
            match self.string.as_bytes()[self.offset - i] {
                0 => break,
                10 => {
                    new_offset = self.offset - i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
        for _ in 1..x {
            if self.cur() != '\n' {
                self.right();
            } else {
                break;
            }
        }
    }

    fn left(&mut self) {
        if self.offset > 0 {
            self.offset -= 1;
        }
    }

    fn right(&mut self) {
        if self.offset < self.string.len() {
            self.offset += 1;
        }
    }

    fn down(&mut self) {
        let x = self.get_x() - if self.cur() == '\n' { 1 } else { 0 };
        let mut new_offset = self.string.len();

        for i in self.offset..self.string.len() {
            match self.string.as_bytes()[i] {
                0 => break,
                10 => {
                    new_offset = i + 1;
                    break;
                }
                _ => (),
            }
        }
        self.offset = new_offset;
        for _ in 1..x {
            if self.cur() != '\n' {
                self.right();
            } else {
                break;
            }
        }
    }

    fn cur(&self) -> char {
        self.string.chars().nth(self.offset).unwrap_or('\0')
    }

    fn insert(&mut self, c: char, window: &mut Window) {
        window.set_title(&format!("{}{}{}","self (", &self.url, ") Changed"));
        self.string = self.string[0 .. self.offset].to_string() +
            &c.to_string() +
            &self.string[self.offset .. self.string.len()];
        self.offset += 1;
    }

    fn reload(&mut self, window: &mut Window) {
        window.set_title(&("Editor (".to_string() + &self.url + ")"));
        self.offset = 0;
        self.scroll_x = 0;
        self.scroll_y = 0;

        match self.file {
            Option::Some(ref mut file) => {
                file.seek(Seek::Start(0));
                let mut vec: Vec<u8> = Vec::new();
                file.read_to_end(&mut vec);
                self.string = unsafe { String::from_utf8_unchecked(vec) };
            },
            Option::None => self.string = String::new(),
        }
    }

    fn save(&mut self, window: &mut Window) {
        match self.file {
            Option::Some(ref mut file) => {
                window.set_title(&("Editor (".to_string() + &self.url + ") Saved"));
                file.seek(Seek::Start(0));
                file.write(&self.string.as_bytes());
                file.sync();
            }
            Option::None => {
                //TODO: Ask for file to save to
                window.set_title(&("Editor (".to_string() + &self.url + ") No Open File"));
            }
        }
    }

    fn get_x(&self) -> usize {
        let mut x = 0;
        for (n, c) in self.string.chars().enumerate() {
            if c == '\n' {
                x = 0;
            } else {
                x += 1;
            }
            if n >= self.offset {
                break;
            }
        }
        x
    }

    fn draw_content(&mut self, window: &mut Window) {
        let mut redraw = false;

        {
            window.set([255, 255, 255, 255]);

            let scroll_x = self.scroll_x;
            let scroll_y = self.scroll_y;

            let mut offset = 0;

            let mut col = -scroll_x;
            let cols = window.width() as isize / 8;

            let mut row = -scroll_y;
            let rows = window.height() as isize / 16;

            for c in self.string.chars() {
                if offset == self.offset {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                    } else {
                        if col < 0 { //Too far to the left
                            self.scroll_x += col;
                        } else if col >= cols { //Too far to the right
                            self.scroll_x += cols - col + 1;
                        }
                        if row < 0 { //Too far up
                            self.scroll_y += row;
                        } else if row >= rows { //Too far down
                            self.scroll_y += rows - row + 1;
                        }

                        redraw = true;
                    }
                }

                if c == '\n' {
                    col = -scroll_x;
                    row += 1;
                } else if c == '\t' {
                    col += 8 - col % 8;
                } else {
                    if col >= 0 && col < cols && row >= 0 && row < rows {
                        window.char(8 * col, 16 * row, c, [0, 0, 0, 255]);
                    }
                    col += 1;
                }

                offset += 1;
            }

            if offset == self.offset {
                if col >= 0 && col < cols && row >= 0 && row < rows {
                    window.char(8 * col, 16 * row, '_', [128, 128, 128, 255]);
                } else {
                    if col < 0 { //Too far to the left
                        self.scroll_x += col;
                    } else if col >= cols { //Too far to the right
                        self.scroll_x += cols - col + 1;
                    }
                    if row < 0 { //Too far up
                        self.scroll_y += row;
                    } else if row >= rows { //Too far down
                        self.scroll_y += rows - row + 1;
                    }

                    redraw = true;
                }
            }

            window.sync();
        }

        if redraw {
            self.draw_content(window);
        }
    }

    fn main(&mut self, url: &str) {
        let mut window = Window::new((rand() % 400 + 50) as isize,
        (rand() % 300 + 50) as isize,
        576,
        400,
        &("Editor (".to_string() + url + ")"));

        self.url = url.to_string();
        self.file = Option::Some(File::open(&self.url));

        self.reload(&mut window);
        self.draw_content(&mut window);

        let mut mode = Mode::Normal;

        let mut last_change = String::new();
        let mut multiplier: Option<u32> = None;
        let mut swap = 0;
        let mut period = String::new();
        let mut is_recording = false;

        while let Option::Some(event) = window.poll() {
            match event.to_option() {
                EventOption::Key(key_event) => {
                    if key_event.pressed {
                        cmd::exec(self, &mut mode, &mut multiplier, &mut last_change, key_event, &mut window, &mut swap, &mut period, &mut is_recording);

                        self.draw_content(&mut window);
                    }
                }
                _ => (),
            }
        }
    }
}

pub fn main() {
    match args().get(1) {
        Option::Some(arg) => Editor::new().main(&arg),
        Option::None => Editor::new().main("none://"),
    }
}
<|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.

use syntax::abi::{Abi};
use syntax::ast;

use rustc::ty::{self, TyCtxt};
use rustc::mir::repr::{self, Mir};

use bitslice::BitSlice;

use super::super::gather_moves::MovePath;
use super::{bitwise, Union, Subtract};
use super::BitDenotation;
use super::DataflowResults;
use super::HasMoveData;

/// This function scans `mir` for all calls to the intrinsic
/// `rustc_peek` that have the expression form `rustc_peek(&expr)`.
///
/// For each such call, determines what the dataflow bit-state is for
/// the L-value corresponding to `expr`; if the bit-state is a 1, then
/// that call to `rustc_peek` is ignored by the sanity check. If the
/// bit-state is a 0, then this pass emits a error message saying
/// "rustc_peek: bit not set".
///
/// The intention is that one can write unit tests for dataflow by
/// putting code into a compile-fail test and using `rustc_peek` to
/// make observations about the results of dataflow static analyses.
///
/// (If there are any calls to `rustc_peek` that do not match the
/// expression form above, then that emits an error as well, but those
/// errors are not intended to be used for unit tests.)
pub fn sanity_check_via_rustc_peek<'a, 'tcx, O>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                                mir: &Mir<'tcx>,
                                                id: ast::NodeId,
                                                _attributes: &[ast::Attribute],
                                                flow_ctxt: &O::Ctxt,
                                                results: &DataflowResults<O>)
    where O: BitDenotation<Bit=MovePath<'tcx>>, O::Ctxt: HasMoveData<'tcx>
{
    debug!("sanity_check_via_rustc_peek id: {:?}", id);
    // FIXME: this is not DRY. Figure out way to abstract this and
    // `dataflow::build_sets`. (But note it is doing non-standard
    // stuff, so such generalization may not be realistic.)

    let blocks = mir.all_basic_blocks();
    'next_block: for bb in blocks {
        let bb_data = mir.basic_block_data(bb);
        let &repr::BasicBlockData { ref statements,
                                    ref terminator,
                                    is_cleanup: _ } = bb_data;

        let (args, span) = if let Some(repr::Terminator { ref kind, span, .. }) = *terminator {
            if let repr::TerminatorKind::Call { func: ref oper, ref args, .. } = *kind
            {
                if let repr::Operand::Constant(ref func) = *oper
                {
                    if let ty::TyFnDef(def_id, _, &ty::BareFnTy { abi, .. }) = func.ty.sty
                    {
                        let name = tcx.item_name(def_id);
                        if abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
                            if name.as_str() == "rustc_peek" {
                                (args, span)
                            } else {
                                continue;
                            }
                        } else {
                            continue;
                        }
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }
            } else {
                continue;
            }
        } else {
            continue;
        };
        assert!(args.len() == 1);
        let peek_arg_lval = match args[0] {
            repr::Operand::Consume(ref lval @ repr::Lvalue::Temp(_)) => {
                lval
            }
            repr::Operand::Consume(_) => {
                bug!("dataflow::sanity_check cannot feed a non-temp to rustc_peek.");
            }
            repr::Operand::Constant(_) => {
                bug!("dataflow::sanity_check cannot feed a constant to rustc_peek.");
            }
        };

        let mut entry = results.0.sets.on_entry_set_for(bb.index()).to_owned();
        let mut gen = results.0.sets.gen_set_for(bb.index()).to_owned();
        let mut kill = results.0.sets.kill_set_for(bb.index()).to_owned();

        let move_data = flow_ctxt.move_data();

        // Emulate effect of all statements in the block up to (but
        // not including) the assignment to `peek_arg_lval`. Do *not*
        // include terminator (since we are peeking the state of the
        // argument at time immediate preceding Call to `rustc_peek`).

        let mut sets = super::BlockSets { on_entry: &mut entry[..],
                                          gen_set: &mut gen[..],
                                          kill_set: &mut kill[..] };

        for (j, stmt) in statements.iter().enumerate() {
            debug!("rustc_peek: ({:?},{}) {:?}", bb, j, stmt);
            let (lvalue, rvalue) = match stmt.kind {
                repr::StatementKind::Assign(ref lvalue, ref rvalue) => {
                    (lvalue, rvalue)
                }
            };

            if lvalue == peek_arg_lval {
                if let repr::Rvalue::Ref(_,
                                         repr::BorrowKind::Shared,
                                         ref peeking_at_lval) = *rvalue {
                    // Okay, our search is over.
                    let peek_mpi = move_data.rev_lookup.find(peeking_at_lval);
                    let bit_state = sets.on_entry.get_bit(peek_mpi.idx());
                    debug!("rustc_peek({:?} = &{:?}) bit_state: {}",
                           lvalue, peeking_at_lval, bit_state);
                    if !bit_state {
                        tcx.sess.span_err(span, &format!("rustc_peek: bit not set"));
                    }
                    continue 'next_block;
                } else {
                    // Our search should have been over, but the input
                    // does not match expectations of `rustc_peek` for
                    // this sanity_check.
                    tcx.sess.span_err(span, &format!("rustc_peek: argument expression \
                                                      must be immediate borrow of form `&expr`"));
                }
            }

            let lhs_mpi = move_data.rev_lookup.find(lvalue);

            debug!("rustc_peek: computing effect on lvalue: {:?} ({:?}) in stmt: {:?}",
                   lvalue, lhs_mpi, stmt);
            // reset GEN and KILL sets before emulating their effect.
            for e in &mut sets.gen_set[..] { *e = 0; }
            for e in &mut sets.kill_set[..] { *e = 0; }
            results.0.operator.statement_effect(flow_ctxt, &mut sets, bb, j);
            bitwise(sets.on_entry, sets.gen_set, &Union);
            bitwise(sets.on_entry, sets.kill_set, &Subtract);
        }

        tcx.sess.span_err(span, &format!("rustc_peek: MIR did not match \
                                          anticipated pattern; note that \
                                          rustc_peek expects input of \
                                          form `&expr`"));
    }
}
<commit_msg>`mir::dataflow::sanity_check`: Factor out `fn is_rustc_peek` helper routine.<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.

use syntax::abi::{Abi};
use syntax::ast;
use syntax::codemap::Span;

use rustc::ty::{self, TyCtxt};
use rustc::mir::repr::{self, Mir};

use bitslice::BitSlice;

use super::super::gather_moves::MovePath;
use super::{bitwise, Union, Subtract};
use super::BitDenotation;
use super::DataflowResults;
use super::HasMoveData;

/// This function scans `mir` for all calls to the intrinsic
/// `rustc_peek` that have the expression form `rustc_peek(&expr)`.
///
/// For each such call, determines what the dataflow bit-state is for
/// the L-value corresponding to `expr`; if the bit-state is a 1, then
/// that call to `rustc_peek` is ignored by the sanity check. If the
/// bit-state is a 0, then this pass emits a error message saying
/// "rustc_peek: bit not set".
///
/// The intention is that one can write unit tests for dataflow by
/// putting code into a compile-fail test and using `rustc_peek` to
/// make observations about the results of dataflow static analyses.
///
/// (If there are any calls to `rustc_peek` that do not match the
/// expression form above, then that emits an error as well, but those
/// errors are not intended to be used for unit tests.)
pub fn sanity_check_via_rustc_peek<'a, 'tcx, O>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                                                mir: &Mir<'tcx>,
                                                id: ast::NodeId,
                                                _attributes: &[ast::Attribute],
                                                flow_ctxt: &O::Ctxt,
                                                results: &DataflowResults<O>)
    where O: BitDenotation<Bit=MovePath<'tcx>>, O::Ctxt: HasMoveData<'tcx>
{
    debug!("sanity_check_via_rustc_peek id: {:?}", id);
    // FIXME: this is not DRY. Figure out way to abstract this and
    // `dataflow::build_sets`. (But note it is doing non-standard
    // stuff, so such generalization may not be realistic.)

    let blocks = mir.all_basic_blocks();
    'next_block: for bb in blocks {
        let bb_data = mir.basic_block_data(bb);
        let &repr::BasicBlockData { ref statements,
                                    ref terminator,
                                    is_cleanup: _ } = bb_data;

        let (args, span) = match is_rustc_peek(tcx, terminator) {
            Some(args_and_span) => args_and_span,
            None => continue,
        };
        assert!(args.len() == 1);
        let peek_arg_lval = match args[0] {
            repr::Operand::Consume(ref lval @ repr::Lvalue::Temp(_)) => {
                lval
            }
            repr::Operand::Consume(_) => {
                bug!("dataflow::sanity_check cannot feed a non-temp to rustc_peek.");
            }
            repr::Operand::Constant(_) => {
                bug!("dataflow::sanity_check cannot feed a constant to rustc_peek.");
            }
        };

        let mut entry = results.0.sets.on_entry_set_for(bb.index()).to_owned();
        let mut gen = results.0.sets.gen_set_for(bb.index()).to_owned();
        let mut kill = results.0.sets.kill_set_for(bb.index()).to_owned();

        let move_data = flow_ctxt.move_data();

        // Emulate effect of all statements in the block up to (but
        // not including) the assignment to `peek_arg_lval`. Do *not*
        // include terminator (since we are peeking the state of the
        // argument at time immediate preceding Call to `rustc_peek`).

        let mut sets = super::BlockSets { on_entry: &mut entry[..],
                                          gen_set: &mut gen[..],
                                          kill_set: &mut kill[..] };

        for (j, stmt) in statements.iter().enumerate() {
            debug!("rustc_peek: ({:?},{}) {:?}", bb, j, stmt);
            let (lvalue, rvalue) = match stmt.kind {
                repr::StatementKind::Assign(ref lvalue, ref rvalue) => {
                    (lvalue, rvalue)
                }
            };

            if lvalue == peek_arg_lval {
                if let repr::Rvalue::Ref(_,
                                         repr::BorrowKind::Shared,
                                         ref peeking_at_lval) = *rvalue {
                    // Okay, our search is over.
                    let peek_mpi = move_data.rev_lookup.find(peeking_at_lval);
                    let bit_state = sets.on_entry.get_bit(peek_mpi.idx());
                    debug!("rustc_peek({:?} = &{:?}) bit_state: {}",
                           lvalue, peeking_at_lval, bit_state);
                    if !bit_state {
                        tcx.sess.span_err(span, &format!("rustc_peek: bit not set"));
                    }
                    continue 'next_block;
                } else {
                    // Our search should have been over, but the input
                    // does not match expectations of `rustc_peek` for
                    // this sanity_check.
                    tcx.sess.span_err(span, &format!("rustc_peek: argument expression \
                                                      must be immediate borrow of form `&expr`"));
                }
            }

            let lhs_mpi = move_data.rev_lookup.find(lvalue);

            debug!("rustc_peek: computing effect on lvalue: {:?} ({:?}) in stmt: {:?}",
                   lvalue, lhs_mpi, stmt);
            // reset GEN and KILL sets before emulating their effect.
            for e in &mut sets.gen_set[..] { *e = 0; }
            for e in &mut sets.kill_set[..] { *e = 0; }
            results.0.operator.statement_effect(flow_ctxt, &mut sets, bb, j);
            bitwise(sets.on_entry, sets.gen_set, &Union);
            bitwise(sets.on_entry, sets.kill_set, &Subtract);
        }

        tcx.sess.span_err(span, &format!("rustc_peek: MIR did not match \
                                          anticipated pattern; note that \
                                          rustc_peek expects input of \
                                          form `&expr`"));
    }

}

fn is_rustc_peek<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
                           terminator: &'a Option<repr::Terminator<'tcx>>)
                           -> Option<(&'a [repr::Operand<'tcx>], Span)> {
    if let Some(repr::Terminator { ref kind, span, .. }) = *terminator {
        if let repr::TerminatorKind::Call { func: ref oper, ref args, .. } = *kind
        {
            if let repr::Operand::Constant(ref func) = *oper
            {
                if let ty::TyFnDef(def_id, _, &ty::BareFnTy { abi, .. }) = func.ty.sty
                {
                    let name = tcx.item_name(def_id);
                    if abi == Abi::RustIntrinsic || abi == Abi::PlatformIntrinsic {
                        if name.as_str() == "rustc_peek" {
                            return Some((args, span));
                        }
                    }
                }
            }
        }
    }
    return None;
}
<|endoftext|>


<commit_before><commit_msg>Use str and lifetimes instead of String in the solution for Day 13<commit_after><|endoftext|>


<commit_before>// xfail-stage0
// xfail-stage1
// xfail-stage2
// xfail-stage3

// error-pattern:3:13:3:14
fn main() -> () {
  auto foo = [];
}
// this checks that span_err gets used
<commit_msg>Un-XFAIL vector-no-ann<commit_after>// xfail-stage0

// error-pattern:Ambiguous type
fn main() -> () {
  auto foo = [];
}
<|endoftext|>


<commit_before><commit_msg>tcp: fix a buffer overrun in the option parsing<commit_after><|endoftext|>


<commit_before><commit_msg>ensure we catch incorrectly unwinding calls<commit_after>// error-pattern: calling a function with ABI C-unwind using caller ABI C
#![feature(c_unwind)]

//! Unwinding when the caller ABI is "C" (without "-unwind") is UB.
//! Currently we detect the ABI mismatch; we could probably allow such calls in principle one day
//! but then we have to detect the unexpected unwinding.

extern "C-unwind" fn unwind() {
    panic!();
}

fn main() {
    let unwind: extern "C-unwind" fn() = unwind;
    let unwind: extern "C" fn() = unsafe { std::mem::transmute(unwind) };
    std::panic::catch_unwind(|| unwind()).unwrap_err();
}
<|endoftext|>


<commit_before><commit_msg>Add ICH test case for consts<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.

// This test case tests the incremental compilation hash (ICH) implementation
// for consts.

// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.

// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph

#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]

// Change const visibility ---------------------------------------------------
#[cfg(cfail1)]
const CONST_VISIBILITY: u8 = 0;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub const CONST_VISIBILITY: u8 = 0;

// Change type from i32 to u32 ------------------------------------------------
#[cfg(cfail1)]
const CONST_CHANGE_TYPE_1: i32 = 0;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
const CONST_CHANGE_TYPE_1: u32 = 0;

// Change type from Option<u32> to Option<u64> --------------------------------
#[cfg(cfail1)]
const CONST_CHANGE_TYPE_2: Option<u32> = None;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
const CONST_CHANGE_TYPE_2: Option<u64> = None;

// Change value between simple literals ---------------------------------------
#[cfg(cfail1)]
const CONST_CHANGE_VALUE_1: i16 = 1;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
const CONST_CHANGE_VALUE_1: i16 = 2;

// Change value between expressions -------------------------------------------
#[cfg(cfail1)]
const CONST_CHANGE_VALUE_2: i16 = 1 + 1;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
const CONST_CHANGE_VALUE_2: i16 = 1 + 2;

#[cfg(cfail1)]
const CONST_CHANGE_VALUE_3: i16 = 2 + 3;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
const CONST_CHANGE_VALUE_3: i16 = 2 * 3;

#[cfg(cfail1)]
const CONST_CHANGE_VALUE_4: i16 = 1 + 2 * 3;

#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
const CONST_CHANGE_VALUE_4: i16 = 1 + 2 * 4;

// Change type indirectly -----------------------------------------------------
struct ReferencedType1;
struct ReferencedType2;

mod const_change_type_indirectly {
    #[cfg(cfail1)]
    use super::ReferencedType1 as Type;

    #[cfg(not(cfail1))]
    use super::ReferencedType2 as Type;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    const CONST_CHANGE_TYPE_INDIRECTLY_1: Type = Type;

    #[rustc_dirty(label="Hir", cfg="cfail2")]
    #[rustc_clean(label="Hir", cfg="cfail3")]
    #[rustc_metadata_dirty(cfg="cfail2")]
    #[rustc_metadata_clean(cfg="cfail3")]
    const CONST_CHANGE_TYPE_INDIRECTLY_2: Option<Type> = None;
}
<|endoftext|>


<commit_before><commit_msg>Add regression test for #25954 (cyclic closure type), which is now impossible.<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.

// Regression test for #25954: detect and reject a closure type that
// references itself.

use std::cell::{Cell, RefCell};

struct A<T: Fn()> {
    x: RefCell<Option<T>>,
    b: Cell<i32>,
}

fn main() {
    let mut p = A{x: RefCell::new(None), b: Cell::new(4i32)};

    // This is an error about types of infinite size:
    let q = || p.b.set(5i32); //~ ERROR mismatched types

    *(p.x.borrow_mut()) = Some(q);
}
<|endoftext|>


<commit_before><commit_msg>Formating changes<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed bug with response in daemon<commit_after><|endoftext|>


<commit_before><commit_msg>Bind Vulkan descriptor sets when rendering<commit_after><|endoftext|>


<commit_before><commit_msg>genet-abi: fix Decoder test<commit_after><|endoftext|>


<commit_before><commit_msg>style: Use MaybeUninit in style struct clone impls / constructors.<commit_after><|endoftext|>


<commit_before><commit_msg>Add comments about functionality, increase verbosity of some variables<commit_after><|endoftext|>


<commit_before><commit_msg>account.getBanned method<commit_after><|endoftext|>


<commit_before><commit_msg>randomly generated mobs<commit_after><|endoftext|>


<commit_before><commit_msg>Committing some env logic stuff<commit_after><|endoftext|>


<commit_before><commit_msg>Remove clone() calls<commit_after><|endoftext|>


<commit_before><commit_msg>Add never tests<commit_after>//! Tests for the tick channel flavor.

// TODO: update this file

extern crate crossbeam;
#[macro_use]
extern crate crossbeam_channel;
extern crate rand;

use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::thread;
use std::time::{Duration, Instant};

use crossbeam_channel::{never, unbounded, TryRecvError};

fn ms(ms: u64) -> Duration {
    Duration::from_millis(ms)
}

#[test]
fn foo() {
    let (s, r) = unbounded::<i32>();
    let r = Some(&r);

    select! {
        recv(r.unwrap_or(&never())) -> _ => panic!(),
        default => {}
    }
}

#[test]
fn bar() {
    let (s, r) = unbounded::<i32>();
    let r = Some(r);

    select! {
        recv(r.unwrap_or(never())) -> _ => panic!(),
        default => {}
    }
}

// #[test]
// fn fire() {
//     let start = Instant::now();
//     let r = tick(ms(50));
//
//     assert_eq!(r.try_recv(), Err(TryRecvError::Empty));
//     thread::sleep(ms(100));
//
//     let fired = r.try_recv().unwrap();
//     assert!(start < fired);
//     assert!(fired - start >= ms(50));
//
//     let now = Instant::now();
//     assert!(fired < now);
//     assert!(now - fired >= ms(50));
//
//     assert_eq!(r.try_recv(), Err(TryRecvError::Empty));
//
//     select! {
//         recv(r) -> _ => panic!(),
//         default => {}
//     }
//
//     select! {
//         recv(r) -> _ => {}
//         recv(tick(ms(200))) -> _ => panic!(),
//     }
// }

#[test]
fn capacity() {
    let r = never::<i32>();
    assert_eq!(r.capacity(), Some(1));
}

#[test]
fn len_empty_full() {
    let r = never::<i32>();
    assert_eq!(r.capacity(), Some(1));
    assert_eq!(r.len(), 0);
    assert_eq!(r.is_empty(), true);
    assert_eq!(r.is_full(), false);
}

// #[test]
// fn try_recv() {
//     let r = tick(ms(200));
//     assert!(r.try_recv().is_err());
//
//     thread::sleep(ms(100));
//     assert!(r.try_recv().is_err());
//
//     thread::sleep(ms(200));
//     assert!(r.try_recv().is_ok());
//     assert!(r.try_recv().is_err());
//
//     thread::sleep(ms(200));
//     assert!(r.try_recv().is_ok());
//     assert!(r.try_recv().is_err());
// }
//
// #[test]
// fn recv() {
//     let start = Instant::now();
//     let r = tick(ms(50));
//
//     let fired = r.recv().unwrap();
//     assert!(start < fired);
//     assert!(fired - start >= ms(50));
//
//     let now = Instant::now();
//     assert!(fired < now);
//     assert!(now - fired < fired - start);
//
//     assert_eq!(r.try_recv(), Err(TryRecvError::Empty));
// }
//
// #[test]
// fn recv_timeout() {
//     let start = Instant::now();
//     let r = tick(ms(200));
//
//     assert!(r.recv_timeout(ms(100)).is_err());
//     let now = Instant::now();
//     assert!(now - start >= ms(100));
//     assert!(now - start <= ms(150));
//
//     let fired = r.recv_timeout(ms(200)).unwrap();
//     assert!(fired - start >= ms(200));
//     assert!(fired - start <= ms(250));
//
//     assert!(r.recv_timeout(ms(100)).is_err());
//     let now = Instant::now();
//     assert!(now - start >= ms(300));
//     assert!(now - start <= ms(350));
//
//     let fired = r.recv_timeout(ms(200)).unwrap();
//     assert!(fired - start >= ms(400));
//     assert!(fired - start <= ms(450));
// }
<|endoftext|>


<commit_before>use core::clone::Clone;
use core::iter::Iterator;
use core::mem::size_of;
use core::ops::Drop;
use core::option::Option;
use core::ptr;
use core::slice;
use core::slice::SliceExt;

use common::memory::*;

#[macro_export]
macro_rules! kvec {
    ($($x:expr),*) => (
        KVec::from_slice(&[$($x),*])
    );
    ($($x:expr,)*) => (kvec![$($x),*])
}

/// An iterator over a kvec
pub struct KVecIterator<'a, T: 'a> {
    kvec: &'a KVec<T>,
    offset: usize,
}

impl <'a, T> Iterator for KVecIterator<'a, T> {
    type Item = &'a mut T;
    fn next(&mut self) -> Option<Self::Item> {
        match self.kvec.get(self.offset) {
            Option::Some(item) => {
                self.offset += 1;
                Option::Some(item)
            }
            Option::None => {
                Option::None
            }
        }
    }
}

/// A owned, heap allocated list of elements
pub struct KVec<T> {
    pub mem: Option<Memory<T>>,
    pub length: usize,
}

impl <T> KVec<T> {
    /// Create a empty kvector
    pub fn new() -> KVec<T> {
        KVec {
            mem: Option::None,
            length: 0,
        }
    }

    /// Convert to pointer
    pub unsafe fn as_ptr(&self) -> *const T {
        self.mem.ptr
    }

    /// Convert from a raw (unsafe) buffer
    pub unsafe fn from_raw_buf(ptr: *const T, len: usize) -> KVec<T> {
        match Memory::new(len) {
            Option::Some(mem) => {
                ptr::copy(ptr, mem.ptr, len);

                return KVec {
                    mem: mem,
                    length: len,
                };
            },
            Option::None => {
                return KVec::new();
            }
        }
    }

    pub fn from_slice(slice: &[T]) -> KVec<T> {
        match Memory::new(slice.len()) {
            Option::Some(mem) => {
                unsafe { ptr::copy(slice.as_ptr(), mem.ptr, slice.len()) };

                return KVec {
                    mem: mem,
                    length: slice.len(),
                };
            },
            Option::None => {
                return KVec::new();
            }
        }
    }

    /// Get the nth element. Returns None if out of bounds.
    pub fn get(&self, i: usize) -> Option<&mut T> {
        if i >= self.length {
            Option::None
        } else {
            unsafe { Option::Some(&mut *self.mem.ptr.offset(i as isize)) }
        }
    }

    /// Set the nth element
    pub fn set(&self, i: usize, value: T) {
        if i <= self.length {
            unsafe { ptr::write(self.mem.ptr.offset(i as isize), value) };
        }
    }

    /// Insert element at a given position
    pub fn insert(&mut self, i: usize, value: T) {
        if i <= self.length {
            let new_length = self.length + 1;
            if self.mem.renew(new_length) {
                self.length = new_length;

                //Move all things ahead of insert forward one
                let mut j = self.length - 1;
                while j > i {
                    unsafe {
                        ptr::write(self.mem.ptr.offset(j as isize), ptr::read(self.mem.ptr.offset(j as isize - 1)));
                    }
                    j -= 1;
                }

                unsafe { ptr::write(self.mem.ptr.offset(i as isize), value) };
            }
        }
    }

    /// Remove a element and return it as a Option
    pub fn remove(&mut self, i: usize) -> Option<T> {
        if i < self.length {
            self.length -= 1;

            let item = unsafe { ptr::read(self.mem.ptr.offset(i as isize)) };

            //Move all things ahead of remove back one
            let mut j = i;
            while j < self.length {
                unsafe {
                    ptr::write(self.mem.ptr.offset(j as isize), ptr::read(self.mem.ptr.offset(j as isize + 1)));
                }
                j += 1;
            }

            self.mem.renew(self.length);

            Option::Some(item)
        } else {
            Option::None
        }
    }

    /// Push an element to a kvector
    pub fn push(&mut self, value: T) {
        let new_length = self.length + 1;
        if self.mem.renew(new_length) {
            self.length = new_length;

            unsafe { ptr::write(self.mem.ptr.offset(self.length as isize - 1), value) };
        }
    }

    /// Pop the last element
    pub fn pop(&mut self) -> Option<T> {
        if self.length > 0 {
            self.length -= 1;

            let item = unsafe { ptr::read(self.mem.ptr.offset(self.length as isize)) };

            self.mem.renew(self.length);

            return Option::Some(item);
        }

        Option::None
    }

    /// Get the length of the kvector
    pub fn len(&self) -> usize {
        self.length
    }

    /// Create an iterator
    pub fn iter(&self) -> KVecIterator<T> {
        KVecIterator {
            kvec: self,
            offset: 0,
        }
    }

    // TODO: Consider returning a slice instead
    pub fn sub(&self, start: usize, count: usize) -> KVec<T> {
        let mut i = start;
        if i > self.len() {
            i = self.len();
        }

        let mut j = i + count;
        if j > self.len() {
            j = self.len();
        }

        let length = j - i;
        if length == 0 {
            return KVec::new();
        }

        match Memory::new(length) {
            Option::Some(mem) => {
                for k in i..j {
                    ptr::write(mem.ptr.offset((k - i) as isize),
                               ptr::read(self.mem.ptr.offset(k as isize)));
                }

                return KVec {
                    mem: mem,
                    length: length,
                };
            },
            Option::None => {
                return KVec::new();
            }
        }
    }

    pub fn as_slice(&self) -> &[T] {
        if self.data as usize > 0 && self.length > 0 {
            unsafe { slice::from_raw_parts(self.mem.ptr, self.length) }
        } else {
            &[]
        }
    }
}

impl<T> KVec<T> where T: Clone {
    /// Append a kvector to another kvector
    pub fn push_all(&mut self, kvec: &KVec<T>) {
        let mut i = self.length as isize;
        let new_length = self.length + kvec.len();
        if self.mem.renew(new_length) {
            self.length = new_length;

            for value in kvec.iter() {
                unsafe { ptr::write(self.mem.ptr.offset(i), value.clone()) };
                i += 1;
            }
        }
    }
}

impl<T> Clone for KVec<T> where T: Clone {
    fn clone(&self) -> KVec<T> {
        let mut ret = KVec::new();
        ret.push_all(self);
        ret
    }
}

impl<T> Drop for KVec<T> {
    fn drop(&mut self) {
        unsafe {
            for i in 0..self.len() {
                ptr::read(self.mem.ptr.offset(i as isize));
            }
        }
    }
}
<commit_msg>KVec build fixed<commit_after>use core::clone::Clone;
use core::iter::Iterator;
use core::mem::size_of;
use core::ops::Drop;
use core::option::Option;
use core::ptr;
use core::slice;
use core::slice::SliceExt;

use common::memory::*;

#[macro_export]
macro_rules! kvec {
    ($($x:expr),*) => (
        KVec::from_slice(&[$($x),*])
    );
    ($($x:expr,)*) => (kvec![$($x),*])
}

/// An iterator over a kvec
pub struct KVecIterator<'a, T: 'a> {
    kvec: &'a KVec<T>,
    offset: usize,
}

impl <'a, T> Iterator for KVecIterator<'a, T> {
    type Item = &'a mut T;
    fn next(&mut self) -> Option<Self::Item> {
        match self.kvec.get(self.offset) {
            Option::Some(item) => {
                self.offset += 1;
                Option::Some(item)
            }
            Option::None => {
                Option::None
            }
        }
    }
}

/// A owned, heap allocated list of elements
pub struct KVec<T> {
    pub mem: Memory<T>, //TODO: Option<Memory>
    pub length: usize,
}

impl <T> KVec<T> {
    /// Create a empty kvector
    pub fn new() -> KVec<T> {
        KVec {
            mem: Memory {
                ptr: 0 as *mut T //TODO: Option::None
            },
            length: 0,
        }
    }

    /// Convert to pointer
    pub unsafe fn as_ptr(&self) -> *const T {
        self.mem.ptr
    }

    /// Convert from a raw (unsafe) buffer
    pub unsafe fn from_raw_buf(ptr: *const T, len: usize) -> KVec<T> {
        match Memory::new(len) {
            Option::Some(mem) => {
                ptr::copy(ptr, mem.ptr, len);

                return KVec {
                    mem: mem,
                    length: len,
                };
            },
            Option::None => {
                return KVec::new();
            }
        }
    }

    pub fn from_slice(slice: &[T]) -> KVec<T> {
        match Memory::new(slice.len()) {
            Option::Some(mem) => {
                unsafe { ptr::copy(slice.as_ptr(), mem.ptr, slice.len()) };

                return KVec {
                    mem: mem,
                    length: slice.len(),
                };
            },
            Option::None => {
                return KVec::new();
            }
        }
    }

    /// Get the nth element. Returns None if out of bounds.
    pub fn get(&self, i: usize) -> Option<&mut T> {
        if i >= self.length {
            Option::None
        } else {
            unsafe { Option::Some(&mut *self.mem.ptr.offset(i as isize)) }
        }
    }

    /// Set the nth element
    pub fn set(&self, i: usize, value: T) {
        if i <= self.length {
            unsafe { ptr::write(self.mem.ptr.offset(i as isize), value) };
        }
    }

    /// Insert element at a given position
    pub fn insert(&mut self, i: usize, value: T) {
        if i <= self.length {
            let new_length = self.length + 1;
            if self.mem.renew(new_length) {
                self.length = new_length;

                //Move all things ahead of insert forward one
                let mut j = self.length - 1;
                while j > i {
                    unsafe {
                        ptr::write(self.mem.ptr.offset(j as isize), ptr::read(self.mem.ptr.offset(j as isize - 1)));
                    }
                    j -= 1;
                }

                unsafe { ptr::write(self.mem.ptr.offset(i as isize), value) };
            }
        }
    }

    /// Remove a element and return it as a Option
    pub fn remove(&mut self, i: usize) -> Option<T> {
        if i < self.length {
            self.length -= 1;

            let item = unsafe { ptr::read(self.mem.ptr.offset(i as isize)) };

            //Move all things ahead of remove back one
            let mut j = i;
            while j < self.length {
                unsafe {
                    ptr::write(self.mem.ptr.offset(j as isize), ptr::read(self.mem.ptr.offset(j as isize + 1)));
                }
                j += 1;
            }

            self.mem.renew(self.length);

            Option::Some(item)
        } else {
            Option::None
        }
    }

    /// Push an element to a kvector
    pub fn push(&mut self, value: T) {
        let new_length = self.length + 1;
        if self.mem.renew(new_length) {
            self.length = new_length;

            unsafe { ptr::write(self.mem.ptr.offset(self.length as isize - 1), value) };
        }
    }

    /// Pop the last element
    pub fn pop(&mut self) -> Option<T> {
        if self.length > 0 {
            self.length -= 1;

            let item = unsafe { ptr::read(self.mem.ptr.offset(self.length as isize)) };

            self.mem.renew(self.length);

            return Option::Some(item);
        }

        Option::None
    }

    /// Get the length of the kvector
    pub fn len(&self) -> usize {
        self.length
    }

    /// Create an iterator
    pub fn iter(&self) -> KVecIterator<T> {
        KVecIterator {
            kvec: self,
            offset: 0,
        }
    }

    // TODO: Consider returning a slice instead
    pub fn sub(&self, start: usize, count: usize) -> KVec<T> {
        let mut i = start;
        if i > self.len() {
            i = self.len();
        }

        let mut j = i + count;
        if j > self.len() {
            j = self.len();
        }

        let length = j - i;
        if length == 0 {
            return KVec::new();
        }

        match Memory::new(length) {
            Option::Some(mem) => {
                for k in i..j {
                    unsafe { ptr::write(mem.ptr.offset((k - i) as isize), ptr::read(self.mem.ptr.offset(k as isize))) };
                }

                return KVec {
                    mem: mem,
                    length: length,
                };
            },
            Option::None => {
                return KVec::new();
            }
        }
    }

    pub fn as_slice(&self) -> &[T] {
        if self.length > 0 {
            unsafe { slice::from_raw_parts(self.mem.ptr, self.length) }
        } else {
            &[]
        }
    }
}

impl<T> KVec<T> where T: Clone {
    /// Append a kvector to another kvector
    pub fn push_all(&mut self, kvec: &KVec<T>) {
        let mut i = self.length as isize;
        let new_length = self.length + kvec.len();
        if self.mem.renew(new_length) {
            self.length = new_length;

            for value in kvec.iter() {
                unsafe { ptr::write(self.mem.ptr.offset(i), value.clone()) };
                i += 1;
            }
        }
    }
}

impl<T> Clone for KVec<T> where T: Clone {
    fn clone(&self) -> KVec<T> {
        let mut ret = KVec::new();
        ret.push_all(self);
        ret
    }
}

impl<T> Drop for KVec<T> {
    fn drop(&mut self) {
        unsafe {
            for i in 0..self.len() {
                ptr::read(self.mem.ptr.offset(i as isize));
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>adding tests<commit_after>extern crate tfidf;

#[cfg(test)]
mod tests {
    use tfidf::tfidf::TfIdf;
    use tfidf::tfidf::Term;

    fn setup<'a>() -> TfIdf<'a> {
        let mut tfidf = TfIdf::new();
        tfidf.add("hello hello hello world");
        tfidf.add("soft kitty warm kitty");
        tfidf.add("we have to find a leader for this world");

        tfidf
    }

    #[test]
    fn test_tf() {
        let tfidf = setup();

        assert_eq!(tfidf.tf(&Term("hello"), 0), 1.4771212f32);
        assert_eq!(tfidf.tf(&Term("world"), 0), 1f32);
        assert_eq!(tfidf.tf(&Term("nothing"), 0), 0f32);
        assert_eq!(tfidf.tf(&Term("warm"), 0), 0f32);
    }

    #[test]
    fn test_count() {
        let tfidf = setup();

        assert_eq!(tfidf.count(&Term("hello")), 1);
        assert_eq!(tfidf.count(&Term("world")), 2);
        assert_eq!(tfidf.count(&Term("kitty")), 1);
        assert_eq!(tfidf.count(&Term("nothing")), 0);
    }

    #[test]
    fn test_idf() {
        let tfidf = setup();

        assert_eq!(tfidf.idf(&Term("soft")), 0.17609125f32);
        assert_eq!(tfidf.idf(&Term("hello")), 0.17609125f32);
        assert_eq!(tfidf.idf(&Term("nothing")), 0.47712126f32);
    }

    #[test]
    fn test_tfidf() {
        let tfidf = setup();

        assert_eq!(tfidf.tfidf(&Term("soft"), 0), 0f32);
        assert_eq!(tfidf.tfidf(&Term("soft"), 1), 0.17609125f32);
        assert_eq!(tfidf.tfidf(&Term("hello"), 0), 0.26010814f32);
        assert_eq!(tfidf.tfidf(&Term("nothing"), 1), 0f32);
    }
}
<|endoftext|>


<commit_before><commit_msg>implement<commit_after><|endoftext|>


<commit_before><commit_msg>For over an array<commit_after><|endoftext|>


<commit_before>import driver::session;

import option::{none, some};

import syntax::ast::{crate, expr_, expr_mac, mac_invoc, mac_qq};
import syntax::fold::*;
import syntax::ext::base::*;
import syntax::ext::build::*;
import syntax::parse::parser::parse_expr_from_source_str;

import codemap::span;

fn expand_qquote(cx: ext_ctxt, sp: span, _e: @ast::expr) -> ast::expr_ {
    let str = codemap::span_to_snippet(sp, cx.session().parse_sess.cm);
    let session_call = bind mk_call_(cx,sp,
                                     mk_access(cx,sp,["ext_cx"], "session"),
                                     []);
    let call = mk_call(cx,sp,
                       ["syntax", "parse", "parser",
                        "parse_expr_from_source_str"],
                       [mk_str(cx,sp, "<anon>"),
                        mk_unary(cx,sp, ast::box(ast::imm),
                                 mk_str(cx,sp, str)),
                        mk_access_(cx,sp,
                                   mk_access_(cx,sp, session_call(), "opts"),
                                   "cfg"),
                        mk_access_(cx,sp, session_call(), "parse_sess")]
                      );
    ret call.node;
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<commit_msg>Implement "replace" function.<commit_after>import driver::session;

import option::{none, some};

import syntax::ast::{crate, expr_, expr_mac, mac_invoc, mac_qq, mac_var};
import syntax::fold::*;
import syntax::ext::base::*;
import syntax::ext::build::*;
import syntax::parse::parser::parse_expr_from_source_str;

import codemap::span;

fn expand_qquote(cx: ext_ctxt, sp: span, _e: @ast::expr) -> ast::expr_ {
    let str = codemap::span_to_snippet(sp, cx.session().parse_sess.cm);
    let session_call = bind mk_call_(cx,sp,
                                     mk_access(cx,sp,["ext_cx"], "session"),
                                     []);
    let call = mk_call(cx,sp,
                       ["syntax", "parse", "parser",
                        "parse_expr_from_source_str"],
                       [mk_str(cx,sp, "<anon>"),
                        mk_unary(cx,sp, ast::box(ast::imm),
                                 mk_str(cx,sp, str)),
                        mk_access_(cx,sp,
                                   mk_access_(cx,sp, session_call(), "opts"),
                                   "cfg"),
                        mk_access_(cx,sp, session_call(), "parse_sess")]
                      );
    ret call.node;
}

fn replace(e: @ast::expr, repls: [@ast::expr]) -> @ast::expr {
    let aft = default_ast_fold();
    let f_pre = {fold_expr: bind replace_expr(repls, _, _, _,
                                              aft.fold_expr)
                 with *aft};
    let f = make_fold(f_pre);
    ret f.fold_expr(e);
}

fn replace_expr(repls: [@ast::expr],
                e: ast::expr_, s: span, fld: ast_fold,
                orig: fn@(ast::expr_, span, ast_fold)->(ast::expr_, span))
    -> (ast::expr_, span)
{
    // note: nested enum matching will be really nice here so I can jusy say
    //       expr_mac(mac_var(i))
    alt e {
      expr_mac({node: mac_var(i), _}) {let r = repls[i]; (r.node, r.span)}
      _ {orig(e,s,fld)}
    }
}

// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
<|endoftext|>


<commit_before><commit_msg>Make I/O and parsing TLS file errors distinct.<commit_after><|endoftext|>


<commit_before>// Copyright 2014-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.
use core::mem::*;
use test::Bencher;

#[test]
fn size_of_basic() {
    assert_eq!(size_of::<u8>(), 1u);
    assert_eq!(size_of::<u16>(), 2u);
    assert_eq!(size_of::<u32>(), 4u);
    assert_eq!(size_of::<u64>(), 8u);
}

#[test]
#[cfg(any(target_arch = "x86",
          target_arch = "arm",
          target_arch = "mips",
          target_arch = "mipsel",
          target_arch = "powerpc"))]
fn size_of_32() {
    assert_eq!(size_of::<uint>(), 4u);
    assert_eq!(size_of::<*const uint>(), 4u);
}

#[test]
#[cfg(any(target_arch = "x86_64",
          target_arch = "aarch64"))]
fn size_of_64() {
    assert_eq!(size_of::<uint>(), 8u);
    assert_eq!(size_of::<*const uint>(), 8u);
}

#[test]
fn size_of_val_basic() {
    assert_eq!(size_of_val(&1u8), 1);
    assert_eq!(size_of_val(&1u16), 2);
    assert_eq!(size_of_val(&1u32), 4);
    assert_eq!(size_of_val(&1u64), 8);
}

#[test]
fn align_of_basic() {
    assert_eq!(align_of::<u8>(), 1u);
    assert_eq!(align_of::<u16>(), 2u);
    assert_eq!(align_of::<u32>(), 4u);
}

#[test]
#[cfg(any(target_arch = "x86",
          target_arch = "arm",
          target_arch = "mips",
          target_arch = "mipsel",
          target_arch = "powerpc"))]
fn align_of_32() {
    assert_eq!(align_of::<uint>(), 4u);
    assert_eq!(align_of::<*const uint>(), 4u);
}

#[test]
#[cfg(any(target_arch = "x86_64",
          target_arch = "aarch64"))]
fn align_of_64() {
    assert_eq!(align_of::<uint>(), 8u);
    assert_eq!(align_of::<*const uint>(), 8u);
}

#[test]
fn align_of_val_basic() {
    assert_eq!(align_of_val(&1u8), 1u);
    assert_eq!(align_of_val(&1u16), 2u);
    assert_eq!(align_of_val(&1u32), 4u);
}

#[test]
fn test_swap() {
    let mut x = 31337i;
    let mut y = 42i;
    swap(&mut x, &mut y);
    assert_eq!(x, 42);
    assert_eq!(y, 31337);
}

#[test]
fn test_replace() {
    let mut x = Some("test".to_string());
    let y = replace(&mut x, None);
    assert!(x.is_none());
    assert!(y.is_some());
}

#[test]
fn test_transmute_copy() {
    assert_eq!(1u, unsafe { transmute_copy(&1i) });
}

#[test]
fn test_transmute() {
    trait Foo {}
    impl Foo for int {}

    let a = box 100i as Box<Foo>;
    unsafe {
        let x: ::core::raw::TraitObject = transmute(a);
        assert!(*(x.data as *const int) == 100);
        let _x: Box<Foo> = transmute(x);
    }

    unsafe {
        assert!(vec![76u8] == transmute::<_, Vec<u8>>("L".to_string()));
    }
}

// FIXME #13642 (these benchmarks should be in another place)
/// Completely miscellaneous language-construct benchmarks.
// Static/dynamic method dispatch

struct Struct {
    field: int
}

trait Trait {
    fn method(&self) -> int;
}

impl Trait for Struct {
    fn method(&self) -> int {
        self.field
    }
}

#[bench]
fn trait_vtable_method_call(b: &mut Bencher) {
    let s = Struct { field: 10 };
    let t = &s as &Trait;
    b.iter(|| {
        t.method()
    });
}

#[bench]
fn trait_static_method_call(b: &mut Bencher) {
    let s = Struct { field: 10 };
    b.iter(|| {
        s.method()
    });
}

// Overhead of various match forms

#[bench]
fn match_option_some(b: &mut Bencher) {
    let x = Some(10i);
    b.iter(|| {
        match x {
            Some(y) => y,
            None => 11
        }
    });
}

#[bench]
fn match_vec_pattern(b: &mut Bencher) {
    let x = [1i,2,3,4,5,6];
    b.iter(|| {
        match x {
            [1,2,3,..] => 10i,
            _ => 11i,
        }
    });
}
<commit_msg>Generalise pointer width tests using pointer_width<commit_after>// Copyright 2014-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.
use core::mem::*;
use test::Bencher;

#[test]
fn size_of_basic() {
    assert_eq!(size_of::<u8>(), 1u);
    assert_eq!(size_of::<u16>(), 2u);
    assert_eq!(size_of::<u32>(), 4u);
    assert_eq!(size_of::<u64>(), 8u);
}

#[test]
#[cfg(target_pointer_width = "32")]
fn size_of_32() {
    assert_eq!(size_of::<uint>(), 4u);
    assert_eq!(size_of::<*const uint>(), 4u);
}

#[test]
#[cfg(target_pointer_width = "64")]
fn size_of_64() {
    assert_eq!(size_of::<uint>(), 8u);
    assert_eq!(size_of::<*const uint>(), 8u);
}

#[test]
fn size_of_val_basic() {
    assert_eq!(size_of_val(&1u8), 1);
    assert_eq!(size_of_val(&1u16), 2);
    assert_eq!(size_of_val(&1u32), 4);
    assert_eq!(size_of_val(&1u64), 8);
}

#[test]
fn align_of_basic() {
    assert_eq!(align_of::<u8>(), 1u);
    assert_eq!(align_of::<u16>(), 2u);
    assert_eq!(align_of::<u32>(), 4u);
}

#[test]
#[cfg(target_pointer_width = "32")]
fn align_of_32() {
    assert_eq!(align_of::<uint>(), 4u);
    assert_eq!(align_of::<*const uint>(), 4u);
}

#[test]
#[cfg(target_pointer_width = "64")]
fn align_of_64() {
    assert_eq!(align_of::<uint>(), 8u);
    assert_eq!(align_of::<*const uint>(), 8u);
}

#[test]
fn align_of_val_basic() {
    assert_eq!(align_of_val(&1u8), 1u);
    assert_eq!(align_of_val(&1u16), 2u);
    assert_eq!(align_of_val(&1u32), 4u);
}

#[test]
fn test_swap() {
    let mut x = 31337i;
    let mut y = 42i;
    swap(&mut x, &mut y);
    assert_eq!(x, 42);
    assert_eq!(y, 31337);
}

#[test]
fn test_replace() {
    let mut x = Some("test".to_string());
    let y = replace(&mut x, None);
    assert!(x.is_none());
    assert!(y.is_some());
}

#[test]
fn test_transmute_copy() {
    assert_eq!(1u, unsafe { transmute_copy(&1i) });
}

#[test]
fn test_transmute() {
    trait Foo {}
    impl Foo for int {}

    let a = box 100i as Box<Foo>;
    unsafe {
        let x: ::core::raw::TraitObject = transmute(a);
        assert!(*(x.data as *const int) == 100);
        let _x: Box<Foo> = transmute(x);
    }

    unsafe {
        assert!(vec![76u8] == transmute::<_, Vec<u8>>("L".to_string()));
    }
}

// FIXME #13642 (these benchmarks should be in another place)
/// Completely miscellaneous language-construct benchmarks.
// Static/dynamic method dispatch

struct Struct {
    field: int
}

trait Trait {
    fn method(&self) -> int;
}

impl Trait for Struct {
    fn method(&self) -> int {
        self.field
    }
}

#[bench]
fn trait_vtable_method_call(b: &mut Bencher) {
    let s = Struct { field: 10 };
    let t = &s as &Trait;
    b.iter(|| {
        t.method()
    });
}

#[bench]
fn trait_static_method_call(b: &mut Bencher) {
    let s = Struct { field: 10 };
    b.iter(|| {
        s.method()
    });
}

// Overhead of various match forms

#[bench]
fn match_option_some(b: &mut Bencher) {
    let x = Some(10i);
    b.iter(|| {
        match x {
            Some(y) => y,
            None => 11
        }
    });
}

#[bench]
fn match_vec_pattern(b: &mut Bencher) {
    let x = [1i,2,3,4,5,6];
    b.iter(|| {
        match x {
            [1,2,3,..] => 10i,
            _ => 11i,
        }
    });
}
<|endoftext|>


<commit_before><commit_msg>add proxy table config<commit_after>
#[crate_type="lib"]
use std::collections::{HashMap};

enum PartType {
    DIV, // divide to int
    MOD // remainder
}

struct TableCfg {
    ptype:PartType,
    num:uint,
    col:String
}

struct Table {
    pri : Vec<String>, // primary keys
    name : String,
    cfg : TableCfg
}

struct Conf {
    tbls : HashMap<String,Table>,
    db:String
}

pub fn new(dbname:& str) -> Conf {
    Conf{tbls:HashMap::new(),db:String::from_str(dbname)}
}

impl Conf {
    fn add_tbl(&self,tb:&str,col:&str,t:PartType,num:uint) {
        let cfg = TableCfg{ptype:t,num:num,col:String::from_str(col)};
        let t = Table { pri:Vec::new(),name:String::from_str(tb),cfg:cfg};
        self.tbls.insert(String::from_str(tb),t);
    }
}

#[cfg(test)]
fn test() {
    let c = new("pirate");
    c.add_tbl("bag","uid",MOD,10);
}
<|endoftext|>


<commit_before><commit_msg>Initial commit<commit_after>#[macro_export]
macro_rules! make_int_type {
    ($n:ident, $t:ty) => {
        #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
        pub struct $n(pub $t);

        impl $n {
            pub fn raw_int(self) -> $t { self.0 }
        }

        impl BitAnd for $n {
            type Output = Self;

            fn bitand(self, rhs: Self) -> Self {
                $n(self.0 & rhs.0)
            }
        }

        impl BitAndAssign for $n {
            fn bitand_assign(&mut self, rhs: Self) {
                *self = $n(self.0 & rhs.0)
            }
        }

        impl BitOr for $n {
            type Output = Self;

            fn bitor(self, rhs: Self) -> Self {
                $n(self.0 | rhs.0)
            }
        }

        impl BitOrAssign for $n {
            fn bitor_assign(&mut self, rhs: Self) {
                *self = $n(self.0 | rhs.0)
            }
        }

        impl Add for $n {
            type Output = Self;

            fn add(self, rhs: Self) -> Self {
                $n(self.0 + rhs.0)
            }
        }

        impl AddAssign for $n {
            fn add_assign(&mut self, rhs: Self) {
                *self = $n(self.0 + rhs.0)
            }
        }

        impl Sub for $n {
            type Output = Self;

            fn sub(self, rhs:Self) -> Self {
                $n(self.0 - rhs.0)
            }
        }

        impl SubAssign for $n {
            fn sub_assign(&mut self, rhs: Self) {
                *self = $n(self.0 - rhs.0)
            }
        }

        impl Mul for $n {
            type Output = Self;

            fn mul(self, rhs: Self) -> Self {
                $n(self.0 * rhs.0)
            }
        }

        impl MulAssign for $n {
            fn mul_assign(&mut self, rhs: Self) {
                *self = $n(self.0 * rhs.0)
            }
        }

        impl Div for $n {
            type Output = Self;

            fn div(self, rhs: Self) -> Self {
                $n(self.0 / rhs.0)
            }
        }

        impl DivAssign for $n {
            fn div_assign(&mut self, rhs: Self) {
                *self = $n(self.0 / rhs.0)
            }
        }

        impl Rem for $n {
            type Output = Self;

            fn rem(self, rhs: Self) -> Self {
                $n(self.0 % rhs.0)
            }
        }

        impl RemAssign for $n {
            fn rem_assign(&mut self, rhs: Self) {
                *self = $n(self.0 % rhs.0)
            }
        }

        impl Ord for $n {
            fn cmp(&self, rhs: &Self) -> Ordering {
                self.0.cmp(&rhs.0)
            }
        }

        impl PartialOrd for $n {
            fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
                Some(self.cmp(rhs))
            }
        }
    }
}
<|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.

//! Traits for conversions between types.
//!
//! The traits in this module provide a general way to talk about conversions
//! from one type to another. They follow the standard Rust conventions of
//! `as`/`into`/`from`.
//!
//! Like many traits, these are often used as bounds for generic functions, to
//! support arguments of multiple types.
//!
//! See each trait for usage examples.

#![stable(feature = "rust1", since = "1.0.0")]

use marker::Sized;

/// A cheap, reference-to-reference conversion.
///
/// `AsRef` is very similar to, but different than, `Borrow`. See
/// [the book][book] for more.
///
/// [book]: ../../book/borrow-and-asref.html
///
/// # Examples
///
/// Both `String` and `&str` implement `AsRef<str>`:
///
/// ```
/// fn is_hello<T: AsRef<str>>(s: T) {
///    assert_eq!("hello", s.as_ref());
/// }
///
/// let s = "hello";
/// is_hello(s);
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRef<T: ?Sized> {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_ref(&self) -> &T;
}

/// A cheap, mutable reference-to-mutable reference conversion.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsMut<T: ?Sized> {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_mut(&mut self) -> &mut T;
}

/// A conversion that consumes `self`, which may or may not be expensive.
///
/// # Examples
///
/// `String` implements `Into<Vec<u8>>`:
///
/// ```
/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
///    let bytes = b"hello".to_vec();
///    assert_eq!(bytes, s.into());
/// }
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Into<T>: Sized {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn into(self) -> T;
}

/// Construct `Self` via a conversion.
///
/// # Examples
///
/// `String` implements `From<&str>`:
///
/// ```
/// let string = "hello".to_string();
/// let other_string = String::from("hello");
///
/// assert_eq!(string, other_string);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub trait From<T>: Sized {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn from(T) -> Self;
}

////////////////////////////////////////////////////////////////////////////////
// GENERIC IMPLS
////////////////////////////////////////////////////////////////////////////////

// As lifts over &
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
    fn as_ref(&self) -> &U {
        <T as AsRef<U>>::as_ref(*self)
    }
}

// As lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
    fn as_ref(&self) -> &U {
        <T as AsRef<U>>::as_ref(*self)
    }
}

// FIXME (#23442): replace the above impls for &/&mut with the following more general one:
// // As lifts over Deref
// impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
//     fn as_ref(&self) -> &U {
//         self.deref().as_ref()
//     }
// }

// AsMut lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
    fn as_mut(&mut self) -> &mut U {
        (*self).as_mut()
    }
}

// FIXME (#23442): replace the above impl for &mut with the following more general one:
// // AsMut lifts over DerefMut
// impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
//     fn as_mut(&mut self) -> &mut U {
//         self.deref_mut().as_mut()
//     }
// }

// From implies Into
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T where U: From<T> {
    fn into(self) -> U {
        U::from(self)
    }
}

// From (and thus Into) is reflexive
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> From<T> for T {
    fn from(t: T) -> T { t }
}

////////////////////////////////////////////////////////////////////////////////
// CONCRETE IMPLS
////////////////////////////////////////////////////////////////////////////////

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsRef<[T]> for [T] {
    fn as_ref(&self) -> &[T] {
        self
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsMut<[T]> for [T] {
    fn as_mut(&mut self) -> &mut [T] {
        self
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<str> for str {
    #[inline]
    fn as_ref(&self) -> &str {
        self
    }
}
<commit_msg>Auto merge of #30901 - mackwic:doc-core-convert, r=steveklabnik<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.

//! Traits for conversions between types.
//!
//! The traits in this module provide a general way to talk about conversions
//! from one type to another. They follow the standard Rust conventions of
//! `as`/`into`/`from`.
//!
//! Like many traits, these are often used as bounds for generic functions, to
//! support arguments of multiple types.
//!
//! - Impl the `As*` traits for reference-to-reference conversions
//! - Impl the `Into` trait when you want to consume the value in the conversion
//! - The `From` trait is the most flexible, usefull for values _and_ references conversions
//!
//! As a library writer, you should prefer implementing `From<T>` rather than
//! `Into<U>`, as `From` provides greater flexibility and offer the equivalent `Into`
//! implementation for free, thanks to a blanket implementation in the standard library.
//!
//! **Note: these traits must not fail**. If the conversion can fail, you must use a dedicated
//! method which return an `Option<T>` or a `Result<T, E>`.
//!
//! # Generic impl
//!
//! - `AsRef` and `AsMut` auto-dereference if the inner type is a reference
//! - `From<U> for T` implies `Into<T> for U`
//! - `From` and `Into` are reflexive, which means that all types can `into()`
//!   themselves and `from()` themselves
//!
//! See each trait for usage examples.

#![stable(feature = "rust1", since = "1.0.0")]

use marker::Sized;

/// A cheap, reference-to-reference conversion.
///
/// `AsRef` is very similar to, but different than, `Borrow`. See
/// [the book][book] for more.
///
/// [book]: ../../book/borrow-and-asref.html
///
/// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
/// return an `Option<T>` or a `Result<T, E>`.
///
/// # Examples
///
/// Both `String` and `&str` implement `AsRef<str>`:
///
/// ```
/// fn is_hello<T: AsRef<str>>(s: T) {
///    assert_eq!("hello", s.as_ref());
/// }
///
/// let s = "hello";
/// is_hello(s);
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
///
/// # Generic Impls
///
/// - `AsRef` auto-dereference if the inner type is a reference or a mutable
/// reference (eg: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`)
///
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRef<T: ?Sized> {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_ref(&self) -> &T;
}

/// A cheap, mutable reference-to-mutable reference conversion.
///
/// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
/// return an `Option<T>` or a `Result<T, E>`.
///
/// # Generic Impls
///
/// - `AsMut` auto-dereference if the inner type is a reference or a mutable
/// reference (eg: `foo.as_ref()` will work the same if `foo` has type `&mut Foo` or `&&mut Foo`)
///
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsMut<T: ?Sized> {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn as_mut(&mut self) -> &mut T;
}

/// A conversion that consumes `self`, which may or may not be expensive.
///
/// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
/// return an `Option<T>` or a `Result<T, E>`.
///
/// Library writer should not implement directly this trait, but should prefer the implementation
/// of the `From` trait, which offer greater flexibility and provide the equivalent `Into`
/// implementation for free, thanks to a blanket implementation in the standard library.
///
/// # Examples
///
/// `String` implements `Into<Vec<u8>>`:
///
/// ```
/// fn is_hello<T: Into<Vec<u8>>>(s: T) {
///    let bytes = b"hello".to_vec();
///    assert_eq!(bytes, s.into());
/// }
///
/// let s = "hello".to_string();
/// is_hello(s);
/// ```
///
/// # Generic Impls
///
/// - `From<T> for U` implies `Into<U> for T`
/// - `into()` is reflexive, which means that `Into<T> for T` is implemented
///
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Into<T>: Sized {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn into(self) -> T;
}

/// Construct `Self` via a conversion.
///
/// **Note: this trait must not fail**. If the conversion can fail, use a dedicated method which
/// return an `Option<T>` or a `Result<T, E>`.
///
/// # Examples
///
/// `String` implements `From<&str>`:
///
/// ```
/// let string = "hello".to_string();
/// let other_string = String::from("hello");
///
/// assert_eq!(string, other_string);
/// ```
/// # Generic impls
///
/// - `From<T> for U` implies `Into<U> for T`
/// - `from()` is reflexive, which means that `From<T> for T` is implemented
///
#[stable(feature = "rust1", since = "1.0.0")]
pub trait From<T>: Sized {
    /// Performs the conversion.
    #[stable(feature = "rust1", since = "1.0.0")]
    fn from(T) -> Self;
}

////////////////////////////////////////////////////////////////////////////////
// GENERIC IMPLS
////////////////////////////////////////////////////////////////////////////////

// As lifts over &
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U> {
    fn as_ref(&self) -> &U {
        <T as AsRef<U>>::as_ref(*self)
    }
}

// As lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a mut T where T: AsRef<U> {
    fn as_ref(&self) -> &U {
        <T as AsRef<U>>::as_ref(*self)
    }
}

// FIXME (#23442): replace the above impls for &/&mut with the following more general one:
// // As lifts over Deref
// impl<D: ?Sized + Deref, U: ?Sized> AsRef<U> for D where D::Target: AsRef<U> {
//     fn as_ref(&self) -> &U {
//         self.deref().as_ref()
//     }
// }

// AsMut lifts over &mut
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: ?Sized, U: ?Sized> AsMut<U> for &'a mut T where T: AsMut<U> {
    fn as_mut(&mut self) -> &mut U {
        (*self).as_mut()
    }
}

// FIXME (#23442): replace the above impl for &mut with the following more general one:
// // AsMut lifts over DerefMut
// impl<D: ?Sized + Deref, U: ?Sized> AsMut<U> for D where D::Target: AsMut<U> {
//     fn as_mut(&mut self) -> &mut U {
//         self.deref_mut().as_mut()
//     }
// }

// From implies Into
#[stable(feature = "rust1", since = "1.0.0")]
impl<T, U> Into<U> for T where U: From<T> {
    fn into(self) -> U {
        U::from(self)
    }
}

// From (and thus Into) is reflexive
#[stable(feature = "rust1", since = "1.0.0")]
impl<T> From<T> for T {
    fn from(t: T) -> T { t }
}

////////////////////////////////////////////////////////////////////////////////
// CONCRETE IMPLS
////////////////////////////////////////////////////////////////////////////////

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsRef<[T]> for [T] {
    fn as_ref(&self) -> &[T] {
        self
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl<T> AsMut<[T]> for [T] {
    fn as_mut(&mut self) -> &mut [T] {
        self
    }
}

#[stable(feature = "rust1", since = "1.0.0")]
impl AsRef<str> for str {
    #[inline]
    fn as_ref(&self) -> &str {
        self
    }
}
<|endoftext|>


<commit_before><commit_msg>Add some comments<commit_after><|endoftext|>


<commit_before><commit_msg>empty message<commit_after><|endoftext|>


<commit_before><commit_msg>Test for #39<commit_after>#[macro_use]
extern crate derive_builder;

type Result = ();

#[allow(dead_code)]
#[derive(Builder)]
struct IgnoreEmptyStruct {}

#[test]
fn empty_struct() {
    // this is just a compile-test - no run time checks required.
}
<|endoftext|>


<commit_before><commit_msg>autocommit 2015-06-15 12:59:35 CEST<commit_after>// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#![feature(plugin, no_std)]
#![plugin(lrs_core_plugin)]
#![no_std]

#[macro_use] extern crate lrs;
mod core { pub use lrs::core::*; }
#[prelude_import] use lrs::prelude::*;

use lrs::file::{real_path};

fn main() {
    println!("{:?}", real_path("."));
}
<|endoftext|>


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

//! A singly-linked list.
//!
//! Using this data structure only makes sense under very specific
//! circumstances:
//!
//! - If you have a list that rarely stores more than one element, then this
//!   data-structure can store the element without allocating and only uses as
//!   much space as a `Option<(T, usize)>`. If T can double as the `Option`
//!   discriminant, it will even only be as large as `T, usize`.
//!
//! If you expect to store more than 1 element in the common case, steer clear
//! and use a `Vec<T>`, `Box<[T]>`, or a `SmallVec<T>`.

use std::mem;

#[derive(Clone, Hash, Debug, PartialEq)]
pub struct TinyList<T: PartialEq> {
    head: Option<Element<T>>
}

impl<T: PartialEq> TinyList<T> {

    #[inline]
    pub fn new() -> TinyList<T> {
        TinyList {
            head: None
        }
    }

    #[inline]
    pub fn new_single(data: T) -> TinyList<T> {
        TinyList {
            head: Some(Element {
                data,
                next: None,
            })
        }
    }

    #[inline]
    pub fn insert(&mut self, data: T) {
        let current_head = mem::replace(&mut self.head, None);

        if let Some(current_head) = current_head {
            let current_head = Box::new(current_head);
            self.head = Some(Element {
                data,
                next: Some(current_head)
            });
        } else {
            self.head = Some(Element {
                data,
                next: None,
            })
        }
    }

    #[inline]
    pub fn remove(&mut self, data: &T) -> bool {
        let remove_head = if let Some(ref mut head) = self.head {
            if head.data == *data {
                Some(mem::replace(&mut head.next, None))
            } else {
                None
            }
        } else {
            return false
        };

        if let Some(remove_head) = remove_head {
            if let Some(next) = remove_head {
                self.head = Some(*next);
            } else {
                self.head = None;
            }
            return true
        }

        self.head.as_mut().unwrap().remove_next(data)
    }

    #[inline]
    pub fn contains(&self, data: &T) -> bool {
        if let Some(ref head) = self.head {
            head.contains(data)
        } else {
            false
        }
    }

    #[inline]
    pub fn len(&self) -> usize {
        if let Some(ref head) = self.head {
            head.len()
        } else {
            0
        }
    }
}

#[derive(Clone, Hash, Debug, PartialEq)]
struct Element<T: PartialEq> {
    data: T,
    next: Option<Box<Element<T>>>,
}

impl<T: PartialEq> Element<T> {

    fn remove_next(&mut self, data: &T) -> bool {
        let new_next = if let Some(ref mut next) = self.next {
            if next.data != *data {
                return next.remove_next(data)
            } else {
                mem::replace(&mut next.next, None)
            }
        } else {
            return false
        };

        self.next = new_next;
        return true
    }

    fn len(&self) -> usize {
        if let Some(ref next) = self.next {
            1 + next.len()
        } else {
            1
        }
    }

    fn contains(&self, data: &T) -> bool {
        if self.data == *data {
            return true
        }

        if let Some(ref next) = self.next {
            next.contains(data)
        } else {
            false
        }
    }
}

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

    #[test]
    fn test_contains_and_insert() {
        fn do_insert(i : u32) -> bool {
            i % 2 == 0
        }

        let mut list = TinyList::new();

        for i in 0 .. 10 {
            for j in 0 .. i {
                if do_insert(j) {
                    assert!(list.contains(&j));
                } else {
                    assert!(!list.contains(&j));
                }
            }

            assert!(!list.contains(&i));

            if do_insert(i) {
                list.insert(i);
                assert!(list.contains(&i));
            }
        }
    }

    #[test]
    fn test_remove_first() {
        let mut list = TinyList::new();
        list.insert(1);
        list.insert(2);
        list.insert(3);
        list.insert(4);
        assert_eq!(list.len(), 4);

        assert!(list.remove(&4));
        assert!(!list.contains(&4));

        assert_eq!(list.len(), 3);
        assert!(list.contains(&1));
        assert!(list.contains(&2));
        assert!(list.contains(&3));
    }

    #[test]
    fn test_remove_last() {
        let mut list = TinyList::new();
        list.insert(1);
        list.insert(2);
        list.insert(3);
        list.insert(4);
        assert_eq!(list.len(), 4);

        assert!(list.remove(&1));
        assert!(!list.contains(&1));

        assert_eq!(list.len(), 3);
        assert!(list.contains(&2));
        assert!(list.contains(&3));
        assert!(list.contains(&4));
    }

    #[test]
    fn test_remove_middle() {
        let mut list = TinyList::new();
        list.insert(1);
        list.insert(2);
        list.insert(3);
        list.insert(4);
        assert_eq!(list.len(), 4);

        assert!(list.remove(&2));
        assert!(!list.contains(&2));

        assert_eq!(list.len(), 3);
        assert!(list.contains(&1));
        assert!(list.contains(&3));
        assert!(list.contains(&4));
    }

    #[test]
    fn test_remove_single() {
        let mut list = TinyList::new();
        list.insert(1);
        assert_eq!(list.len(), 1);

        assert!(list.remove(&1));
        assert!(!list.contains(&1));

        assert_eq!(list.len(), 0);
    }
}
<commit_msg>make TinyList more readable and optimize remove(_)<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.

//! A singly-linked list.
//!
//! Using this data structure only makes sense under very specific
//! circumstances:
//!
//! - If you have a list that rarely stores more than one element, then this
//!   data-structure can store the element without allocating and only uses as
//!   much space as a `Option<(T, usize)>`. If T can double as the `Option`
//!   discriminant, it will even only be as large as `T, usize`.
//!
//! If you expect to store more than 1 element in the common case, steer clear
//! and use a `Vec<T>`, `Box<[T]>`, or a `SmallVec<T>`.

use std::mem;

#[derive(Clone, Hash, Debug, PartialEq)]
pub struct TinyList<T: PartialEq> {
    head: Option<Element<T>>
}

impl<T: PartialEq> TinyList<T> {

    #[inline]
    pub fn new() -> TinyList<T> {
        TinyList {
            head: None
        }
    }

    #[inline]
    pub fn new_single(data: T) -> TinyList<T> {
        TinyList {
            head: Some(Element {
                data,
                next: None,
            })
        }
    }

    #[inline]
    pub fn insert(&mut self, data: T) {
        self.head = Some(Element {
            data,
            next: mem::replace(&mut self.head, None).map(Box::new),
        });
    }

    #[inline]
    pub fn remove(&mut self, data: &T) -> bool {
        self.head = match self.head {
            Some(ref mut head) if head.data == *data => {
                mem::replace(&mut head.next, None).map(|x| *x)
            }
            Some(ref mut head) => return head.remove_next(data),
            None => return false,
        };
        true
    }

    #[inline]
    pub fn contains(&self, data: &T) -> bool {
        if let Some(ref head) = self.head {
            head.contains(data)
        } else {
            false
        }
    }

    #[inline]
    pub fn len(&self) -> usize {
        if let Some(ref head) = self.head {
            head.len()
        } else {
            0
        }
    }
}

#[derive(Clone, Hash, Debug, PartialEq)]
struct Element<T: PartialEq> {
    data: T,
    next: Option<Box<Element<T>>>,
}

impl<T: PartialEq> Element<T> {

    fn remove_next(&mut self, data: &T) -> bool {
        let new_next = if let Some(ref mut next) = self.next {
            if next.data != *data {
                return next.remove_next(data)
            } else {
                mem::replace(&mut next.next, None)
            }
        } else {
            return false
        };

        self.next = new_next;
        return true
    }

    fn len(&self) -> usize {
        if let Some(ref next) = self.next {
            1 + next.len()
        } else {
            1
        }
    }

    fn contains(&self, data: &T) -> bool {
        if self.data == *data {
            return true
        }

        if let Some(ref next) = self.next {
            next.contains(data)
        } else {
            false
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    extern crate test;
    use self::test::Bencher;

    #[test]
    fn test_contains_and_insert() {
        fn do_insert(i : u32) -> bool {
            i % 2 == 0
        }

        let mut list = TinyList::new();

        for i in 0 .. 10 {
            for j in 0 .. i {
                if do_insert(j) {
                    assert!(list.contains(&j));
                } else {
                    assert!(!list.contains(&j));
                }
            }

            assert!(!list.contains(&i));

            if do_insert(i) {
                list.insert(i);
                assert!(list.contains(&i));
            }
        }
    }

    #[test]
    fn test_remove_first() {
        let mut list = TinyList::new();
        list.insert(1);
        list.insert(2);
        list.insert(3);
        list.insert(4);
        assert_eq!(list.len(), 4);

        assert!(list.remove(&4));
        assert!(!list.contains(&4));

        assert_eq!(list.len(), 3);
        assert!(list.contains(&1));
        assert!(list.contains(&2));
        assert!(list.contains(&3));
    }

    #[test]
    fn test_remove_last() {
        let mut list = TinyList::new();
        list.insert(1);
        list.insert(2);
        list.insert(3);
        list.insert(4);
        assert_eq!(list.len(), 4);

        assert!(list.remove(&1));
        assert!(!list.contains(&1));

        assert_eq!(list.len(), 3);
        assert!(list.contains(&2));
        assert!(list.contains(&3));
        assert!(list.contains(&4));
    }

    #[test]
    fn test_remove_middle() {
        let mut list = TinyList::new();
        list.insert(1);
        list.insert(2);
        list.insert(3);
        list.insert(4);
        assert_eq!(list.len(), 4);

        assert!(list.remove(&2));
        assert!(!list.contains(&2));

        assert_eq!(list.len(), 3);
        assert!(list.contains(&1));
        assert!(list.contains(&3));
        assert!(list.contains(&4));
    }

    #[test]
    fn test_remove_single() {
        let mut list = TinyList::new();
        list.insert(1);
        assert_eq!(list.len(), 1);

        assert!(list.remove(&1));
        assert!(!list.contains(&1));

        assert_eq!(list.len(), 0);
    }

    #[bench]
    fn bench_insert_empty(b: &mut Bencher) {
        b.iter(|| {
            let mut list = TinyList::new();
            list.insert(1);
        })
    }

    #[bench]
    fn bench_insert_one(b: &mut Bencher) {
        b.iter(|| {
            let mut list = TinyList::new_single(0);
            list.insert(1);
        })
    }

    #[bench]
    fn bench_remove_empty(b: &mut Bencher) {
        b.iter(|| {
            TinyList::new().remove(&1)
        });
    }

    #[bench]
    fn bench_remove_unknown(b: &mut Bencher) {
        b.iter(|| {
            TinyList::new_single(0).remove(&1)
        });
    }

    #[bench]
    fn bench_remove_one(b: &mut Bencher) {
        b.iter(|| {
            TinyList::new_single(1).remove(&1)
        });
    }
}
<|endoftext|>


<commit_before><commit_msg>Use Backoff in actor.rs<commit_after><|endoftext|>


<commit_before><commit_msg>Added hello world!<commit_after>fn main() {
  println!("Hello, rust!");
}<|endoftext|>


<commit_before><commit_msg>Add a regression test for #76281<commit_after>// only-wasm32
// compile-flags: -C opt-level=2
// build-pass

// Regression test for #76281.
// This seems like an issue related to LLVM rather than
// libs-impl so place here.

fn main() {
    let mut v: Vec<&()> = Vec::new();
    v.sort_by_key(|&r| r as *const ());
}
<|endoftext|>


<commit_before><commit_msg>Formatting.<commit_after><|endoftext|>


<commit_before><commit_msg>docs: fixes panic in 14_groups example<commit_after><|endoftext|>


<commit_before><commit_msg>Start range encoder.<commit_after>

type Symbol = u16;

const EOF: Symbol = 256;
const ESC: Symbol = 257;
const FLUSH: Symbol = 258;

pub fn encode(input: &[u8], output: Vec<u8>) {
    let ranges =
        [
            (EOF,         0,  500_000),
            (ESC,   500_000,  750_000),
            (FLUSH, 750_000, 1_000_000)
        ];

}
<|endoftext|>


<commit_before><commit_msg>more derives<commit_after><|endoftext|>