<commit_before><commit_msg>Initial Commit<commit_after>use std::util::swap;
use std::io;
use std::rand;
use std::os;
use std::uint;
use std::hashmap;
use std::num;
use std::util;

Trait Bitable {
	//Get the Nth logical byte
	fn getb(&self, off: uint) -> u8;
}

/*
Trait Zero {
	fn zero() -> Self;
}

impl Bitable for ~str {
	fn getb(&self, off: uint) {
		let bytes = s.as_bytes();
		if(off  >= bytes.len()) {
			0x00
		}
		else {
			//str::as_bytes(s) {|bytes| bytes[off]}
			bytes[off]
		}
	}
}

impl Zero for ~str {
	fn zero() -> ~str {
		~""
	}
}
*/

struct ExternalNode {
    key: ~str,
    value: ~str
}

struct InternalNode {
    left: Node,
    right: Node,
    len: uint
}

struct CritbitTree {
    root: Option<Node>,
    size: uint,
}

enum Node {
    internalNode(~InternalNode),
    externalNode(~ExternalNode)
}

impl InternalNode {
    fn pop_left(&mut self ,replace : Node)  -> Node {
        util::replace(&mut self.left,replace)
    }
    fn pop_right(&mut self, replace : Node) -> Node {
        util::replace(&mut self.right,replace)
        }
}

pub struct NodeIterator {
    priv cur: Option<Node>,
}

impl Iterator<uint> for NodeIterator {
    fn next(&mut self) -> Option<uint> {
        match self.cur.take() {
            Some(externalNode(_)) => None,
            None => None,
            Some(internalNode(cur)) => {
                let mut cur = cur;
                loop {
                    let dummy = externalNode(~ExternalNode {key: ~"",
                                              value :~""});
                    match cur.pop_left(dummy) {
                        internalNode(node) => {
                            let mut node = node;
                            let dummy = externalNode(~ExternalNode {key : ~"",
                                              value :~""});
                            cur.left = node.pop_right(dummy);
                            node.right = internalNode(cur);
                            cur = node;
                        }

                        externalNode(n) => {
                            self.cur = Some(cur.pop_right(externalNode(n)));
                            // left and right fields are both None
                            return Some(1);
                        }
                    }
                }
            },
        }
    }

}

impl Container for CritbitTree {
    fn len(&self) -> uint {self.size}
    fn is_empty(&self) -> bool {self.len() == 0}
}

impl Mutable for CritbitTree {
    fn clear(&mut self) {
        let mut iter = NodeIterator { cur: self.root.take()} ;
        for _ in iter {
            //ignore
        }
    }
}

fn lenToMask(len: uint) -> u8 {
    (len & 0xff) as u8
}

fn lenToOffset(len: uint) -> uint {
    len >> 8
}

fn getb(s: &str, off: uint) -> u8{
    let bytes = s.as_bytes();
    if(off  >= bytes.len()) {
        0x00
    }
    else {
        //str::as_bytes(s) {|bytes| bytes[off]}
        bytes[off]
    }
}

fn mismatch (s1:&str,s2:&str) -> Option<(uint,u8,u8)> {
    let s1b = s1.as_bytes();
    let s2b = s2.as_bytes();
    let mut it = s1b.iter().zip(s2b.iter()).enumerate();
    loop
    {
        match it.next() {
            Some((count,(c1,c2))) => if(c1 != c2) {
            //io::print(fmt!("Mismatch: %u,%u,%u\n",count,*c1 as uint, *c2 as uint));
            return Some((count,*c1,*c2)) },
            None() =>
                return
                if(s1.len() > s2.len()) { Some((s2.len(),s1[s2.len()],0))}
                else if(s2.len() > s1.len()) { Some((s1.len(),0,s2[s1.len()]))}
                else { None }
        }
    }
}

fn goleft (key: &str, off: uint, mask: u8) -> bool{
  //io::print(fmt!("goleft %s,%u,%ux->%ux\n",key,off,mask as uint,(getb(key, off) & mask) as uint));
  getb(key, off) & mask == 0
}

fn findbest(mut cb: &Node, key :&str) -> (~str,~str) {
    loop {
        let tmp = cb;
        match tmp {
            &internalNode(ref n) =>{
                //{left : left, right : right, length : length})=> {
                if (goleft(key,lenToOffset(n.len),lenToMask(n.len))) {
                    cb = &n.left;
                }
                else {
                    cb = &n.right;
                }
            }
            &externalNode(ref n) => {
                return (n.key.clone(),n.value.clone())
            }
            }
    }
}
//TODO convert to loop
fn findbestR(cb: &~Node, key :&str) -> (~str,~str) {
    match cb {
        &~internalNode(ref n) =>{
        //{left : left, right : right, length : length})=> {
            if (goleft(key,lenToOffset(n.len),lenToMask(n.len))) {
                findbest(&n.left,key)
            }
            else {
                findbest(&n.right,key)
            }
        }
        &~externalNode(ref n) => {
            (n.key.clone(),n.value.clone())
        }
    }
}

fn replace(mut cb: &mut Node, key :&str, value : ~str) {
    loop {
        let tmp = cb;
    match tmp {
        &internalNode(ref mut n) =>{
            //{left : left, right : right, length : length})=> {
            if (goleft(key,lenToOffset(n.len),lenToMask(n.len))) {
                cb = &mut n.left
                //replace(&mut n.left,key,value)
            }
            else {
                //replace(&mut n.right,key,value)
                cb = &mut n.right;
            }
        }
        &externalNode(ref mut n) => {
            n.value = value;
            return;
        }
    }
    }
}

fn replaceR(cb: &mut ~Node, key :&str, value : ~str) {
    match cb {
        &~internalNode(ref mut n) =>{
            //{left : left, right : right, length : length})=> {
            if (goleft(key,lenToOffset(n.len),lenToMask(n.len))) {
                replace(&mut n.left,key,value)
            }
            else {
                replace(&mut n.right,key,value)
            }
        }
        &~externalNode(ref mut n) => {
            n.value = value
        }
    }
}

fn insertAtPoint<'a>(cb : &'a mut Node, key : ~str, value : ~str,
                     count: uint, mask :u8)
{
    let direction = goleft(key,count,mask);
    let newExtNode = externalNode(~ExternalNode { key: key, value : value });
    let mut tmp = externalNode(~ExternalNode { key : ~"", value : ~""});
    swap(&mut tmp,cb);
    let mut newIntNode =
        if(direction) {
            internalNode(~InternalNode {left: newExtNode,
                    right: tmp,
                    len: (count << 8) | mask as uint})
        }
        else {
            internalNode(~InternalNode { left: tmp,
                    right: newExtNode,
                    len: (count << 8) | mask as uint})
        };
    swap(&mut newIntNode,cb);
}

fn findInsertionPoint<'a>(cb : &mut Node, key : ~str, value: ~str, bestMatch: &str,
        count : uint, mask : u8)
{
        match *cb {
            externalNode(_) =>
            insertAtPoint(cb,key,value,count,mask),

            internalNode(~InternalNode { left : _, right : _, len: len})
                if(lenToOffset(len) > count ||
                (lenToOffset(len) == count &&
                        lenToMask(len) < mask))
            =>
                    insertAtPoint(cb,key,value,count,mask),
            internalNode(~InternalNode{ left : _, right : _, len: len}) =>
                {
                    let direction = goleft(key,lenToOffset(len),lenToMask(len));
                    findInsertionPointInternal(cb,key,value,bestMatch,count,mask,direction)
                }
        }
}

fn isInsertionPoint<'n>(cb: &Node, count : uint, direction : bool, mask : u8) -> bool {
    match cb{
        &externalNode(_) => fail!(),
        &internalNode(ref cb) =>
            match if (direction) { &'n cb.left } else {&'n cb.right} {
                &externalNode(_) => true,
                &internalNode(ref n)
                    if(lenToOffset(n.len) > count) ||
                        (lenToOffset(n.len) == count &&
                         lenToMask(n.len) < mask) => true,
                            _ => false
            }
    }
}

fn findInsertionPointInternal(mut cb : &mut Node, key : ~str,
        value: ~str, bestMatch: &str,
        count : uint, mask : u8, mut direction : bool)
{
    loop {
        let tmp = cb;
        if(isInsertionPoint(tmp,count,direction,mask)) {
            return insertAtPoint(tmp,key,value,count,mask)
        }
        else {
            match tmp {
                &externalNode(_) => {
                    fail!();
                }
                &internalNode(ref mut cbi) =>
                {
                    let child = if (direction) { &mut cbi.left }
                    else { &mut cbi.right };
                    match child {
                        &internalNode(~InternalNode { left: _, right: _, len: len}) => {
                            let newDirection = goleft(key,lenToOffset(len),lenToMask(len));
                            cb = child;
                            direction = newDirection;
                        }
                        _ => fail!()
                    }
                }
            }
        }
    }
}

fn addnew(cb : &mut Node,key : ~str,value : ~str,bestMatch : ~str) {
/*
    io::print("addnew ");
    io::print(key);
    io::print(" ");
    io::print(bestMatch);
    io::print("\n");
    */
    match(mismatch(key,bestMatch)) {
        Some((count,b1,b2)) => {
            let mut x = b1^b2;
            while (x & (x - 1) != 0) {
                x &= (x - 1);
            }
            findInsertionPoint(cb,key,value,bestMatch,count,x)
        },
    None => fail!()
    }
}

fn cbset(cb: &mut~CritbitTree, key : ~str, value : ~str)
{
    match cb.root {
        Some(ref mut node) =>
        {
            let (bestkey,_) = findbest(node, key);
            //io::print(fmt!("Bestkey: %s,%s\n",key,bestkey));
            if(bestkey == key) { replace(node,key,value) } //TODO handle this
            else {
                cb.size+=1;
                addnew(node,key,value,bestkey)
            }
        },
            None => cb.root = Some(externalNode(~ExternalNode {key: key, value : value}))
    }
}

fn cbsetR(cb: &mut~CritbitTree, key : ~str, value : ~str)
{
    match cb.root {
        Some(ref mut node) =>
        {
            let (bestkey,_) = findbest(node, key);
            //io::print(fmt!("Bestkey: %s,%s\n",key,bestkey));
            if(bestkey == key) { replace(node,key,value) } //TODO handle this
            else {
                addnew(node,key,value,bestkey)
            }
        },
            None => cb.root = Some(externalNode(~ExternalNode {key: key, value : value}))
    }
}

fn cbget(cb: &~CritbitTree, key : &str) -> Option<~str> {
    match cb.root {
        Some(ref node) => {
            let (bk,bv) = findbest(node,key.to_str());
            if(bk.equiv(&key)) {
                Some(bv.clone())
            }
            else {
                None
            }
        },
        _ => None
    }
}

fn printTree (c : &~CritbitTree) {
    match c.root {
        Some(ref x) =>
            printTreeInternal(x,0),
        None => io::print("(Empty)\n")
    }
}

fn spaces(n : uint) {
    let mut i = n;
    while (i > 0) {
        io::print(" ");
        i-=1;
    }
}
fn printTreeInternal(n : &Node, indent : uint) {
    spaces(indent);
    match n {
        &internalNode(ref n) => {
            io::print(format!("Internal {:x}\n",n.len));
            printTreeInternal(&n.left,indent+1);
            printTreeInternal(&n.right,indent+1);
        },
        &externalNode(ref n) => {
            io::print("External ");
            io::print(n.key);
            io::print(":");
            io::print(n.value);
            io::print("\n");
        }
    }
}

fn test()
{
    let mut tree = ~CritbitTree {root : None, size : 0};
    assert!(cbget(&tree,&"test")==None);
    cbset(&mut tree,~"test",~"value");
    assert!(cbget(&tree,&"test") == Some(~"value"));
    cbset(&mut tree,~"test2",~"value2");
    assert!(cbget(&tree,&"test2") == Some(~"value2"));
    assert!(cbget(&tree,&"test") == Some(~"value"));
    cbset(&mut tree,~"tes33",~"value3");
    assert!(cbget(&tree,&"tes33") == Some(~"value3"));
    assert!(cbget(&tree,&"test2") == Some(~"value2"));
    assert!(cbget(&tree,&"test") == Some(~"value"));
    cbset(&mut tree,~"aes33",~"value3");
    assert!(cbget(&tree,&"aes33") == Some(~"value3"));
    assert!(cbget(&tree,&"tes33") == Some(~"value3"));
    assert!(cbget(&tree,&"test2") == Some(~"value2"));
    assert!(cbget(&tree,&"test") == Some(~"value"));
    cbset(&mut tree,~"test",~"value2");
    assert!(cbget(&tree,&"aes33") == Some(~"value3"));
    assert!(cbget(&tree,&"tes33") == Some(~"value3"));
    assert!(cbget(&tree,&"test2") == Some(~"value2"));
    assert!(cbget(&tree,&"test") == Some(~"value2"));
}

fn benchmarkCb(count : uint) {
    let mut tree = ~CritbitTree {root : None, size : 0};
    let mut i = 0;
    while(i<count) {
        cbset(&mut tree, format!("{:u},",rand::random::<uint>()),
                format!("{:u},",rand::random::<uint>()));
        i+=1;
    }
    tree.clear();
}

fn benchmarkBare(count : uint) {
    let mut i = 0;
    while(i<count) {
        format!("{:u},",rand::random::<uint>());
        format!("{:u},",rand::random::<uint>());
        i+=1;
    }
}

fn benchmarkHash(count : uint) {
    let mut hash : hashmap::HashMap<~str,~str> = hashmap::HashMap::new();
    let mut i = 0;
    while(i<count) {
        hash.insert(format!("{:u},",rand::random::<uint>()),
                format!("{:u},",rand::random::<uint>()));
        i+=1;
    }
}

fn main() {
    let args : ~[~str] = os::args();
    let countO : Option<uint> = num::from_str_radix(args[1],10);
    match countO {
        Some(count) => {
            test();
            match args[2] {
                ~"critbit" => benchmarkCb(count),
                    ~"bare" => benchmarkBare(count),
                    ~"hash" => benchmarkHash(count),
                    _ => fail!()
            }
        },
        None() => fail!()
    }
}
<|endoftext|>


<commit_before><commit_msg>Add CrystallizedState<commit_after>use super::utils::types::Sha256Digest;
use super::validator_record::ValidatorRecord;
use super::crosslink_record::CrosslinkRecord;
use super::ethereum_types::U256;

pub struct CrystallizedState {
    pub active_validators: Vec<ValidatorRecord>,
    pub queued_validators: Vec<ValidatorRecord>,
    pub exited_validators: Vec<ValidatorRecord>,
    pub current_shuffling: Vec<u32>,  // TODO: should be u24
    pub current_epoch: u64,
    pub last_justified_epoch: u64,
    pub last_finalized_epoch: u64,
    pub dynasty: u64,
    pub next_shard: u16,
    pub current_checkpoint: Sha256Digest,
    pub crosslink_records: Vec<CrosslinkRecord>,
    pub total_deposits: U256,
}

impl CrystallizedState {
    pub fn num_active_validators(&self) -> usize {
        self.active_validators.len()
    }

    pub fn num_queued_validators(&self) -> usize {
        self.queued_validators.len()
    }

    pub fn num_exited_validators(&self) -> usize {
        self.exited_validators.len()
    }

    pub fn num_crosslink_records(&self) -> usize {
        self.crosslink_records.len()

    }
}
<|endoftext|>


<commit_before><commit_msg>ExprInference is a helper to retreive the underlying type hold by the view. Related to #5.<commit_after>// Copyright 2015 Pierre Talbot (IRCAM)

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//     http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub trait ExprInference
{
  type Output;
}
<|endoftext|>


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

use eutil::slice_to_str;
use libc::{c_int};
use std::collections::TreeMap;
use std::mem;
use std::string::String;
use string::{cef_string_userfree_utf8_alloc,cef_string_userfree_utf8_free,cef_string_utf8_set};
use types::{cef_string_multimap_t,cef_string_t};

fn string_multimap_to_treemap(smm: *mut cef_string_multimap_t) -> *mut TreeMap<String, Vec<*mut cef_string_t>> {
    smm as *mut TreeMap<String, Vec<*mut cef_string_t>>
}

//cef_string_multimap

#[no_mangle]
pub extern "C" fn cef_string_multimap_alloc() -> *mut cef_string_multimap_t {
    unsafe {
         let smm: Box<TreeMap<String, Vec<*mut cef_string_t>>> = box TreeMap::new();
         mem::transmute(smm)
    }
}

#[no_mangle]
pub extern "C" fn cef_string_multimap_size(smm: *mut cef_string_multimap_t) -> c_int {
    unsafe {
        if smm.is_null() { return 0; }
        let mut c: c_int = 0;
        let v = string_multimap_to_treemap(smm);
        for (_, val) in (*v).iter() {
            c = c + (*val).len() as c_int;
        }
        c
    }
}

#[no_mangle]
pub extern "C" fn cef_string_multimap_find_count(smm: *mut cef_string_multimap_t, key: *const cef_string_t) -> c_int {
    unsafe {
        if smm.is_null() { return 0; }
        let v = string_multimap_to_treemap(smm);
        slice_to_str((*key).str as *const u8, (*key).length as uint, |result| {
            match (*v).find(&String::from_str(result)) {
                Some(s) => {
                    s.len() as c_int
                }
                None => 0
            }
        })
    }
}

#[no_mangle]
pub extern "C" fn cef_string_multimap_append(smm: *mut cef_string_multimap_t, key: *const cef_string_t, value: *const cef_string_t) -> c_int {
    unsafe {
        if smm.is_null() { return 0; }
        let v = string_multimap_to_treemap(smm);
        slice_to_str((*key).str as *const u8, (*key).length as uint, |result| {
            let s = String::from_str(result);
            let csv = cef_string_userfree_utf8_alloc();
            cef_string_utf8_set((*value).str as *const u8, (*value).length, csv, 1);
            match (*v).find_mut(&s) {
                Some(vc) => {
                    (*vc).push(csv);
                    1
                }
                None => {
                    let vc = vec!(csv);
                    (*v).insert(s, vc);
                    1
                }
            }
        })
    }
}
<commit_msg>embedding: cef_string_multimap_enumerate()<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use eutil::slice_to_str;
use libc::{c_int};
use std::collections::TreeMap;
use std::mem;
use std::string::String;
use string::{cef_string_userfree_utf8_alloc,cef_string_userfree_utf8_free,cef_string_utf8_set};
use types::{cef_string_multimap_t,cef_string_t};

fn string_multimap_to_treemap(smm: *mut cef_string_multimap_t) -> *mut TreeMap<String, Vec<*mut cef_string_t>> {
    smm as *mut TreeMap<String, Vec<*mut cef_string_t>>
}

//cef_string_multimap

#[no_mangle]
pub extern "C" fn cef_string_multimap_alloc() -> *mut cef_string_multimap_t {
    unsafe {
         let smm: Box<TreeMap<String, Vec<*mut cef_string_t>>> = box TreeMap::new();
         mem::transmute(smm)
    }
}

#[no_mangle]
pub extern "C" fn cef_string_multimap_size(smm: *mut cef_string_multimap_t) -> c_int {
    unsafe {
        if smm.is_null() { return 0; }
        let mut c: c_int = 0;
        let v = string_multimap_to_treemap(smm);
        for (_, val) in (*v).iter() {
            c = c + (*val).len() as c_int;
        }
        c
    }
}

#[no_mangle]
pub extern "C" fn cef_string_multimap_find_count(smm: *mut cef_string_multimap_t, key: *const cef_string_t) -> c_int {
    unsafe {
        if smm.is_null() { return 0; }
        let v = string_multimap_to_treemap(smm);
        slice_to_str((*key).str as *const u8, (*key).length as uint, |result| {
            match (*v).find(&String::from_str(result)) {
                Some(s) => {
                    s.len() as c_int
                }
                None => 0
            }
        })
    }
}

#[no_mangle]
pub extern "C" fn cef_string_multimap_append(smm: *mut cef_string_multimap_t, key: *const cef_string_t, value: *const cef_string_t) -> c_int {
    unsafe {
        if smm.is_null() { return 0; }
        let v = string_multimap_to_treemap(smm);
        slice_to_str((*key).str as *const u8, (*key).length as uint, |result| {
            let s = String::from_str(result);
            let csv = cef_string_userfree_utf8_alloc();
            cef_string_utf8_set((*value).str as *const u8, (*value).length, csv, 1);
            match (*v).find_mut(&s) {
                Some(vc) => {
                    (*vc).push(csv);
                    1
                }
                None => {
                    let vc = vec!(csv);
                    (*v).insert(s, vc);
                    1
                }
            }
        })
    }
}

#[no_mangle]
pub extern "C" fn cef_string_multimap_enumerate(smm: *mut cef_string_multimap_t, key: *const cef_string_t, index: c_int, value: *mut cef_string_t) -> c_int {
    unsafe {
        if smm.is_null() { return 0; }
        let v = string_multimap_to_treemap(smm);
        slice_to_str((*key).str as *const u8, (*key).length as uint, |result| {
            match (*v).find(&String::from_str(result)) {
                Some(s) => {
                    if (*s).len() <= index as uint {
                        return 0;
                    }
                    let cs = (*s)[index as uint];
                    cef_string_utf8_set((*cs).str as *const u8, (*cs).length, value, 1)
                }
                None => 0
            }
        })
    }
}
<|endoftext|>


<commit_before><commit_msg>Added cost return.<commit_after>
fn calculate_return(cost :f64, given :f64) -> f64 {
    return given - cost
}

#[test]
fn calculate_return_test(){
    assert!(calculate_return(13.23f64, 15.00f64) == 1.77f64, "expected {:?} is {:?}", 1.77f64, calculate_return(13.23f64, 15.00f64));
}

#[test]
fn calculate_return_test2(){
    assert!(calculate_return(132.23f64, 150.00f64) == 17.77f64, "expected {:?} is {:?}", 17.77f64, calculate_return(132.23f64, 150.00f64));
}

fn main() {
    println!("{}",calculate_return(123.45, 130.00));
}
<|endoftext|>


<commit_before><commit_msg>Add implementation of shortened cyclic code<commit_after>//! Encoding and decoding of the (16, 8, 5) shortened cyclic code described by P25.
//!
//! The parity-check matrix construction was sourced from \[1] and the decoding algorithm
//! was derived from \[2]. The key information that this code is shortened from a (17, 8,
//! 5) code came from \[3].
//!
//! \[1]: "Coding Theory and Cryptography: The Essentials", 2nd ed, Hankerson, Hoffman, et
//! al, 2000
//! \[2]: "Error Control Coding", Lin and Costello, 1983
//! \[3]: "Standard APCO25 Physical Layer of the Radio Transmission Chain", Simon, 2014

/// Encode the 8 data bits into a 16-bit codeword.
pub fn encode(data: u8) -> u16 {
    matrix_mul_systematic!(data, GEN, u16)
}

/// Try to decode the 16-bit word to the nearest codeword, correcting up to 2 errors.
/// Return `Some((data, err))`, where `data` are the 12 data bits and `err` is the number
/// of errors corrected, on success and `None` on a detected unrecoverable error.
pub fn decode(word: u16) -> Option<(u8, usize)> {
    // Go through a full cycle of the codeword, so the data bits end up in their original
    // position. The word is expanded to 32 bits so it can be treated as the 17-bit word
    // the shortened code is derived from.
    let (fixed, word) = (0..17).fold((Some(0), word as u32), |(fixed, word), _| {
        let syn = syndrome(word);

        if syn == 0 {
            return (fixed, rotate_17(word));
        }

        match pattern(syn) {
            Some(pat) => (Some(pat.count_ones()), rotate_17(word ^ pat)),
            None => (None, rotate_17(word)),
        }
    });

    match fixed {
        Some(err) => Some(((word >> 8) as u8, err as usize)),
        None => None,
    }
}

/// Transposed generator matrix.
const GEN: [u8; 8] = [
    0b00111100,
    0b10011110,
    0b01001111,
    0b00011011,
    0b10110001,
    0b11100100,
    0b11110010,
    0b01111001,
];

/// Transposed parity-check matrix, where the rows of the original are generated from x^i
/// mod g(x).
const PAR: [u32; 8] = [
    0b10000000100111100,
    0b01000000010011110,
    0b00100000001001111,
    0b00010000100011011,
    0b00001000110110001,
    0b00000100111100100,
    0b00000010011110010,
    0b00000001001111001,
];

/// Calculate the syndrome of the given word.
fn syndrome(word: u32) -> u8 {
    matrix_mul!(word, PAR, u8)
}

/// Find the error pattern associated with the syndrome.
///
/// One of the benefits of the cyclic algorithm is we only have to store error patters
/// with the LSB set.
fn pattern(syn: u8) -> Option<u32> {
    match syn {
        0b00011001 => Some(0b00100000000000001),
        0b00011110 => Some(0b00000000001000001),
        0b00101001 => Some(0b00010000000000001),
        0b00110001 => Some(0b00001000000000001),
        0b00111000 => Some(0b00000001000000001),
        0b00111001 => Some(0b00000000000000001),
        0b00111011 => Some(0b00000010000000001),
        0b00111101 => Some(0b00000100000000001),
        0b01001011 => Some(0b00000000000000011),
        0b01110111 => Some(0b00000000010000001),
        0b01111001 => Some(0b01000000000000001),
        0b10100101 => Some(0b00000000100000001),
        0b10110110 => Some(0b00000000000100001),
        0b10111001 => Some(0b10000000000000001),
        0b11001000 => Some(0b00000000000001001),
        0b11011101 => Some(0b00000000000000101),
        0b11100010 => Some(0b00000000000010001),
        _ => None,
    }
}

/// Cyclically rotate the word as if it was 17 bits long.
fn rotate_17(word: u32) -> u32 {
    let lsb = word & 1;
    word >> 1 | lsb << 16
}

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

    #[test]
    fn test_decode() {
        let w = 0b10101011;
        let e = encode(w);

        assert_eq!(Some((w, 0)), decode(e^0b0000000000000000));
        assert_eq!(Some((w, 2)), decode(e^0b1000000000000001));
        assert_eq!(Some((w, 1)), decode(e^0b0001000000000000));
        assert_eq!(Some((w, 2)), decode(e^0b0011000000000000));

        assert_eq!(Some((w, 1)), decode(e^0b1000000000000000));
        assert_eq!(Some((w, 1)), decode(e^0b0100000000000000));
        assert_eq!(Some((w, 2)), decode(e^0b0010000000000001));
        assert_eq!(Some((w, 2)), decode(e^0b0001000000000010));
        assert_eq!(Some((w, 2)), decode(e^0b0000100000000100));
        assert_eq!(Some((w, 2)), decode(e^0b0000010000001000));
        assert_eq!(Some((w, 2)), decode(e^0b0000001000010000));
        assert_eq!(Some((w, 2)), decode(e^0b0000000100100000));
        assert_eq!(Some((w, 2)), decode(e^0b0000000011000000));
        assert_eq!(Some((w, 2)), decode(e^0b0000000001010000));
        assert_eq!(Some((w, 2)), decode(e^0b0000000010001000));
        assert_eq!(Some((w, 2)), decode(e^0b0000000100000100));
        assert_eq!(Some((w, 2)), decode(e^0b0000001000000010));
        assert_eq!(Some((w, 2)), decode(e^0b0000010000000001));
        assert_eq!(Some((w, 1)), decode(e^0b0000100000000000));
        assert_eq!(Some((w, 1)), decode(e^0b0001000000000000));
        assert_eq!(Some((w, 2)), decode(e^0b0010000000000001));
        assert_eq!(Some((w, 2)), decode(e^0b0100000000000100));
        assert_eq!(Some((w, 2)), decode(e^0b1000000000001000));
    }
}
<|endoftext|>


<commit_before><commit_msg>add regression test for #71348<commit_after>// run-pass
#![feature(const_generics)]
#![allow(incomplete_features)]

struct Foo {
    i: i32,
}

trait Get<'a, const N: &'static str> {
    type Target: 'a;

    fn get(&'a self) -> &'a Self::Target;
}

impl Foo {
    fn ask<'a, const N: &'static str>(&'a self) -> &'a <Self as Get<N>>::Target
    where
        Self: Get<'a, N>,
    {
        self.get()
    }
}

impl<'a> Get<'a, "int"> for Foo {
    type Target = i32;

    fn get(&'a self) -> &'a Self::Target {
        &self.i
    }
}

fn main() {
    let foo = Foo { i: 123 };
    assert_eq!(foo.ask::<"int">(), &123);
}
<|endoftext|>


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

#![feature(rustc_attrs)]

macro_rules! mac {
    {} => {
        #[cfg(attr)]
        mod m {
            #[lang_item]
            fn f() {}
        }
    }
}

mac! {}

#[rustc_error]
fn main() {} //~ ERROR compilation successful
<commit_msg>Test that a feature gated cfg variable in a `cfg_attr` on an unconfigured item is allowed<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.

#![feature(custom_attribute, rustc_attrs)]

macro_rules! mac {
    {} => {
        #[cfg(attr)]
        mod m {
            #[lang_item]
            fn f() {}

            #[cfg_attr(target_thread_local, custom)]
            fn g() {}
        }
    }
}

mac! {}

#[rustc_error]
fn main() {} //~ ERROR compilation successful
<|endoftext|>


<commit_before>import driver::session::session;
import middle::ty;
import syntax::{ast, visit};
import syntax::attr;
import syntax::codemap::span;
import std::map::{map,hashmap,hash_from_strs};
import io::writer_util;

export lint, ctypes, unused_imports;
export level, ignore, warn, error;
export lookup_lint, lint_dict, get_lint_dict, check_crate;

#[doc="

A 'lint' check is a kind of miscallaneous constraint that a user _might_ want
to enforce, but might reasonably want to permit as well, on a module-by-module
basis. They contrast with static constraints enforced by other phases of the
compiler, which are generally required to hold in order to compile the program
correctly at all.

"]

enum lint {
    ctypes,
    unused_imports,
}

enum level {
    ignore, warn, error
}

type lint_spec = @{lint: lint,
                   desc: str,
                   default: level};

type lint_dict = hashmap<str,lint_spec>;

fn get_lint_dict() -> lint_dict {
    let v = [
        ("ctypes",
         @{lint: ctypes,
           desc: "proper use of core::libc types in native modules",
           default: warn}),

        ("unused-imports",
         @{lint: unused_imports,
           desc: "imports that are never used",
           default: ignore})
    ];
    hash_from_strs(v)
}

type ctxt = @{dict: lint_dict,
              curr: hashmap<lint, level>,
              tcx: ty::ctxt};

impl methods for ctxt {
    fn get_level(lint: lint) -> level {
        alt self.curr.find(lint) {
          some(c) { c }
          none { ignore }
        }
    }

    fn set_level(lint: lint, level: level) {
        if level == ignore {
            self.curr.remove(lint);
        } else {
            self.curr.insert(lint, level);
        }
    }

    fn span_lint(level: level, span: span, msg: str) {
        alt level {
          ignore { }
          warn { self.tcx.sess.span_warn(span, msg); }
          error { self.tcx.sess.span_err(span, msg); }
        }
    }

    #[doc="
          Merge the warnings specified by any `warn(...)` attributes into the
          current lint context, call the provided function, then reset the
          warnings in effect to their previous state.
    "]
    fn with_warn_attrs(attrs: [ast::attribute], f: fn(ctxt)) {

        let mut undo = [];

        let metas = attr::attr_metas(attr::find_attrs_by_name(attrs, "warn"));
        for metas.each {|meta|
            alt meta.node {
              ast::meta_list(_, metas) {
                for metas.each {|meta|
                    alt meta.node {
                      ast::meta_word(lintname) {
                        alt lookup_lint(self.dict, lintname) {
                          none {
                            self.tcx.sess.span_err(
                                meta.span,
                                #fmt("unknown warning: '%s'", lintname));
                          }
                          some((lint, new_level)) {
                            let old_level = self.get_level(lint);
                            self.set_level(lint, new_level);
                            undo += [(lint, old_level)]
                          }
                        }
                      }
                      _ {
                        self.tcx.sess.span_err(
                            meta.span,
                            "malformed warning attribute");
                      }
                    }
                }
              }
              _ {
                self.tcx.sess.span_err(meta.span,
                                       "malformed warning attribute");
              }
            }
        }

        f(self);

        for undo.each {|pair|
            let (lint,old_level) = pair;
            self.set_level(lint, old_level);
        }
    }
}

fn lookup_lint(dict: lint_dict, s: str)
    -> option<(lint, level)> {
    let s = str::replace(s, "-", "_");
    let (name, level) = if s.starts_with("no_") {
        (s.substr(3u, s.len() - 3u), ignore)
    } else if s.starts_with("err_") {
        (s.substr(4u, s.len() - 4u), error)
    } else {
        (s, warn)
    };
    alt dict.find(name) {
      none { none }
      some(spec) { some((spec.lint, level)) }
    }
}

// FIXME: Copied from driver.rs, to work around a bug(#1566)
fn time(do_it: bool, what: str, thunk: fn()) {
    if !do_it{ ret thunk(); }
    let start = std::time::precise_time_s();
    thunk();
    let end = std::time::precise_time_s();
    io::stdout().write_str(#fmt("time: %3.3f s\t%s\n",
                                end - start, what));
}

fn check_item(cx: ctxt, i: @ast::item) {
    cx.with_warn_attrs(i.attrs) {|cx|
        cx.curr.items {|lint, level|
            alt lint {
              ctypes { check_item_ctypes(cx, level, i); }
              unused_imports { check_item_unused_imports(cx, level, i); }
            }
        }
    }
}

fn check_item_unused_imports(_cx: ctxt, _level: level, _it: @ast::item) {
    // FIXME: Don't know how to check this in lint yet, it's currently being
    // done over in resolve. When resolve is rewritten, do it here instead.
}

fn check_item_ctypes(cx: ctxt, level: level, it: @ast::item) {

    fn check_native_fn(cx: ctxt, level: level, decl: ast::fn_decl) {
        let tys = vec::map(decl.inputs) {|a| a.ty };
        for vec::each(tys + [decl.output]) {|ty|
            alt ty.node {
              ast::ty_path(_, id) {
                alt cx.tcx.def_map.get(id) {
                  ast::def_prim_ty(ast::ty_int(ast::ty_i)) {
                    cx.span_lint(
                        level, ty.span,
                        "found rust type `int` in native module, while \
                         libc::c_int or libc::c_long should be used");
                  }
                  ast::def_prim_ty(ast::ty_uint(ast::ty_u)) {
                    cx.span_lint(
                        level, ty.span,
                        "found rust type `uint` in native module, while \
                         libc::c_uint or libc::c_ulong should be used");
                  }
                  _ { }
                }
              }
              _ { }
            }
        }
    }

    alt it.node {
      ast::item_native_mod(nmod) if attr::native_abi(it.attrs) !=
      either::right(ast::native_abi_rust_intrinsic) {
        for nmod.items.each {|ni|
            alt ni.node {
              ast::native_item_fn(decl, tps) {
                check_native_fn(cx, level, decl);
              }
              _ { }
            }
        }
      }
      _ {/* nothing to do */ }
    }
}

fn check_crate(tcx: ty::ctxt, crate: @ast::crate,
               lint_opts: [(lint, level)], time_pass: bool) {

    fn hash_lint(&&lint: lint) -> uint { lint as uint }
    fn eq_lint(&&a: lint, &&b: lint) -> bool { a == b }

    let cx = @{dict: get_lint_dict(),
               curr: hashmap(hash_lint, eq_lint),
               tcx: tcx};

    // Install defaults.
    cx.dict.items {|_k, spec| cx.set_level(spec.lint, spec.default); }

    // Install command-line options, overriding defaults.
    for lint_opts.each {|pair|
        let (lint,level) = pair;
        cx.set_level(lint, level);
    }

    time(time_pass, "lint checking") {||
        cx.with_warn_attrs(crate.node.attrs) {|cx|
            let visit = visit::mk_simple_visitor(@{
                visit_item: fn@(i: @ast::item) { check_item(cx, i); }
                with *visit::default_simple_visitor()
            });
            visit::visit_crate(*crate, (), visit);
        }
    }

    tcx.sess.abort_if_errors();
}

//
// 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>rustc: Fix handling of - and _ in lint pass<commit_after>import driver::session::session;
import middle::ty;
import syntax::{ast, visit};
import syntax::attr;
import syntax::codemap::span;
import std::map::{map,hashmap,hash_from_strs};
import io::writer_util;

export lint, ctypes, unused_imports;
export level, ignore, warn, error;
export lookup_lint, lint_dict, get_lint_dict, check_crate;

#[doc="

A 'lint' check is a kind of miscallaneous constraint that a user _might_ want
to enforce, but might reasonably want to permit as well, on a module-by-module
basis. They contrast with static constraints enforced by other phases of the
compiler, which are generally required to hold in order to compile the program
correctly at all.

"]

enum lint {
    ctypes,
    unused_imports,
}

enum level {
    ignore, warn, error
}

type lint_spec = @{lint: lint,
                   desc: str,
                   default: level};

type lint_dict = hashmap<str,lint_spec>;

fn get_lint_dict() -> lint_dict {
    let v = [
        ("ctypes",
         @{lint: ctypes,
           desc: "proper use of core::libc types in native modules",
           default: warn}),

        ("unused_imports",
         @{lint: unused_imports,
           desc: "imports that are never used",
           default: ignore})
    ];
    hash_from_strs(v)
}

type ctxt = @{dict: lint_dict,
              curr: hashmap<lint, level>,
              tcx: ty::ctxt};

impl methods for ctxt {
    fn get_level(lint: lint) -> level {
        alt self.curr.find(lint) {
          some(c) { c }
          none { ignore }
        }
    }

    fn set_level(lint: lint, level: level) {
        if level == ignore {
            self.curr.remove(lint);
        } else {
            self.curr.insert(lint, level);
        }
    }

    fn span_lint(level: level, span: span, msg: str) {
        alt level {
          ignore { }
          warn { self.tcx.sess.span_warn(span, msg); }
          error { self.tcx.sess.span_err(span, msg); }
        }
    }

    #[doc="
          Merge the warnings specified by any `warn(...)` attributes into the
          current lint context, call the provided function, then reset the
          warnings in effect to their previous state.
    "]
    fn with_warn_attrs(attrs: [ast::attribute], f: fn(ctxt)) {

        let mut undo = [];

        let metas = attr::attr_metas(attr::find_attrs_by_name(attrs, "warn"));
        for metas.each {|meta|
            alt meta.node {
              ast::meta_list(_, metas) {
                for metas.each {|meta|
                    alt meta.node {
                      ast::meta_word(lintname) {
                        alt lookup_lint(self.dict, lintname) {
                          none {
                            self.tcx.sess.span_err(
                                meta.span,
                                #fmt("unknown warning: '%s'", lintname));
                          }
                          some((lint, new_level)) {
                            let old_level = self.get_level(lint);
                            self.set_level(lint, new_level);
                            undo += [(lint, old_level)]
                          }
                        }
                      }
                      _ {
                        self.tcx.sess.span_err(
                            meta.span,
                            "malformed warning attribute");
                      }
                    }
                }
              }
              _ {
                self.tcx.sess.span_err(meta.span,
                                       "malformed warning attribute");
              }
            }
        }

        f(self);

        for undo.each {|pair|
            let (lint,old_level) = pair;
            self.set_level(lint, old_level);
        }
    }
}

fn lookup_lint(dict: lint_dict, s: str)
    -> option<(lint, level)> {
    let s = str::replace(s, "-", "_");
    let (name, level) = if s.starts_with("no_") {
        (s.substr(3u, s.len() - 3u), ignore)
    } else if s.starts_with("err_") {
        (s.substr(4u, s.len() - 4u), error)
    } else {
        (s, warn)
    };
    alt dict.find(name) {
      none { none }
      some(spec) { some((spec.lint, level)) }
    }
}

// FIXME: Copied from driver.rs, to work around a bug(#1566)
fn time(do_it: bool, what: str, thunk: fn()) {
    if !do_it{ ret thunk(); }
    let start = std::time::precise_time_s();
    thunk();
    let end = std::time::precise_time_s();
    io::stdout().write_str(#fmt("time: %3.3f s\t%s\n",
                                end - start, what));
}

fn check_item(cx: ctxt, i: @ast::item) {
    cx.with_warn_attrs(i.attrs) {|cx|
        cx.curr.items {|lint, level|
            alt lint {
              ctypes { check_item_ctypes(cx, level, i); }
              unused_imports { check_item_unused_imports(cx, level, i); }
            }
        }
    }
}

fn check_item_unused_imports(_cx: ctxt, _level: level, _it: @ast::item) {
    // FIXME: Don't know how to check this in lint yet, it's currently being
    // done over in resolve. When resolve is rewritten, do it here instead.
}

fn check_item_ctypes(cx: ctxt, level: level, it: @ast::item) {

    fn check_native_fn(cx: ctxt, level: level, decl: ast::fn_decl) {
        let tys = vec::map(decl.inputs) {|a| a.ty };
        for vec::each(tys + [decl.output]) {|ty|
            alt ty.node {
              ast::ty_path(_, id) {
                alt cx.tcx.def_map.get(id) {
                  ast::def_prim_ty(ast::ty_int(ast::ty_i)) {
                    cx.span_lint(
                        level, ty.span,
                        "found rust type `int` in native module, while \
                         libc::c_int or libc::c_long should be used");
                  }
                  ast::def_prim_ty(ast::ty_uint(ast::ty_u)) {
                    cx.span_lint(
                        level, ty.span,
                        "found rust type `uint` in native module, while \
                         libc::c_uint or libc::c_ulong should be used");
                  }
                  _ { }
                }
              }
              _ { }
            }
        }
    }

    alt it.node {
      ast::item_native_mod(nmod) if attr::native_abi(it.attrs) !=
      either::right(ast::native_abi_rust_intrinsic) {
        for nmod.items.each {|ni|
            alt ni.node {
              ast::native_item_fn(decl, tps) {
                check_native_fn(cx, level, decl);
              }
              _ { }
            }
        }
      }
      _ {/* nothing to do */ }
    }
}

fn check_crate(tcx: ty::ctxt, crate: @ast::crate,
               lint_opts: [(lint, level)], time_pass: bool) {

    fn hash_lint(&&lint: lint) -> uint { lint as uint }
    fn eq_lint(&&a: lint, &&b: lint) -> bool { a == b }

    let cx = @{dict: get_lint_dict(),
               curr: hashmap(hash_lint, eq_lint),
               tcx: tcx};

    // Install defaults.
    cx.dict.items {|_k, spec| cx.set_level(spec.lint, spec.default); }

    // Install command-line options, overriding defaults.
    for lint_opts.each {|pair|
        let (lint,level) = pair;
        cx.set_level(lint, level);
    }

    time(time_pass, "lint checking") {||
        cx.with_warn_attrs(crate.node.attrs) {|cx|
            let visit = visit::mk_simple_visitor(@{
                visit_item: fn@(i: @ast::item) { check_item(cx, i); }
                with *visit::default_simple_visitor()
            });
            visit::visit_crate(*crate, (), visit);
        }
    }

    tcx.sess.abort_if_errors();
}

//
// 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>TreeMap is removed from the stdlib collections<commit_after><|endoftext|>


<commit_before><commit_msg>events module<commit_after>
pub struct Events {
    up: bool,
    down: bool,
    left: bool,
    right: bool,
}

impl Events {
    fn is_up() -> bool {
        self.up
    }

    fn is_down() -> bool {
        self.down
    }

    fn is_left() -> bool {
        self.left
    }

    fn is_right() -> bool {
        self.right
    }
}

<|endoftext|>


<commit_before><commit_msg>Add len fn<commit_after><|endoftext|>


<commit_before><commit_msg>Only accept some git commands<commit_after><|endoftext|>


<commit_before><commit_msg>Implement more chunk neighboring<commit_after><|endoftext|>


<commit_before><commit_msg>Added a new example.<commit_after>extern crate resvg;

use std::path::Path;

use resvg::{
    utils,
    Options,
};
use resvg::tree::prelude::*;
use resvg::geom::*;

// TODO: write doc

fn main() {
    let _resvg = resvg::init();
    let backend = resvg::default_backend();

    let opt = Options::default();

    let size = Size::new(200.0, 200.0);
    let view_box = tree::ViewBox {
        rect: Rect::new(Point::new(0.0, 0.0), size),
        aspect: tree::AspectRatio::default(),
    };

    let mut rtree = tree::Tree::create(tree::Svg {
        size,
        view_box,
    });

    let mut grad = rtree.append_to_defs(tree::NodeKind::LinearGradient(tree::LinearGradient {
        id: "lg1".into(),
        x1: 0.0,
        y1: 0.0,
        x2: 1.0,
        y2: 0.0,
        d: tree::BaseGradient {
            units: tree::Units::ObjectBoundingBox,
            transform: tree::Transform::default(),
            spread_method: tree::SpreadMethod::Pad,
        },
    }));

    grad.append_kind(tree::NodeKind::Stop(tree::Stop {
        offset: tree::StopOffset::new(0.0),
        color: tree::Color::new(0, 255, 0),
        opacity: tree::Opacity::new(1.0),
    }));

    grad.append_kind(tree::NodeKind::Stop(tree::Stop {
        offset: tree::StopOffset::new(1.0),
        color: tree::Color::new(0, 255, 0),
        opacity: tree::Opacity::new(0.0),
    }));

    let fill = Some(tree::Fill {
        paint: tree::Paint::Link("lg1".into()),
        .. tree::Fill::default()
    });

    rtree.root().append_kind(tree::NodeKind::Path(tree::Path {
        id: String::new(),
        transform: tree::Transform::default(),
        fill,
        stroke: None,
        segments: utils::rect_to_path(Rect::from_xywh(20.0, 20.0, 160.0, 160.0)),
    }));

    println!("{}", rtree.to_svgdom());

    let img = backend.render_to_image(&rtree, &opt).unwrap();
    img.save(Path::new("out.png"));
}
<|endoftext|>


<commit_before>pub type c_char = i8;
pub type c_long = i64;
pub type c_ulong = u64;

pub type wchar_t = i16;

pub type off_t = usize;
pub type mode_t = u16;
pub type time_t = i64;
pub type pid_t = usize;
pub type gid_t = usize;
pub type uid_t = usize;

pub type in_addr_t = u32;
pub type in_port_t = u16;

pub type socklen_t = u32;
pub type sa_family_t = u16;

s! {
    pub struct in_addr {
        pub s_addr: in_addr_t,
    }

    pub struct in6_addr {
        pub s6_addr: [u8; 16],
        __align: [u32; 0],
    }

    pub struct sockaddr {
        pub sa_family: sa_family_t,
        pub sa_data: [::c_char; 14],
    }

    pub struct sockaddr_in {
        pub sin_family: sa_family_t,
        pub sin_port: ::in_port_t,
        pub sin_addr: ::in_addr,
        pub sin_zero: [u8; 8],
    }

    pub struct sockaddr_in6 {
        pub sin6_family: sa_family_t,
        pub sin6_port: in_port_t,
        pub sin6_flowinfo: u32,
        pub sin6_addr: ::in6_addr,
        pub sin6_scope_id: u32,
    }
}

extern {
    pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void;
}

#[link(name = "c")]
#[link(name = "m")]
extern {}
<commit_msg>Auto merge of #653 - redox-os:redox, r=alexcrichton<commit_after>pub type c_char = i8;
pub type c_long = i64;
pub type c_ulong = u64;

pub type wchar_t = i16;

pub type off_t = usize;
pub type mode_t = u16;
pub type time_t = i64;
pub type pid_t = usize;
pub type gid_t = usize;
pub type uid_t = usize;

pub type in_addr_t = u32;
pub type in_port_t = u16;

pub type socklen_t = u32;
pub type sa_family_t = u16;

s! {
    pub struct in_addr {
        pub s_addr: in_addr_t,
    }

    pub struct in6_addr {
        pub s6_addr: [u8; 16],
        __align: [u32; 0],
    }

    pub struct sockaddr {
        pub sa_family: sa_family_t,
        pub sa_data: [::c_char; 14],
    }

    pub struct sockaddr_in {
        pub sin_family: sa_family_t,
        pub sin_port: ::in_port_t,
        pub sin_addr: ::in_addr,
        pub sin_zero: [u8; 8],
    }

    pub struct sockaddr_in6 {
        pub sin6_family: sa_family_t,
        pub sin6_port: in_port_t,
        pub sin6_flowinfo: u32,
        pub sin6_addr: ::in6_addr,
        pub sin6_scope_id: u32,
    }
}

pub const STDIN_FILENO: ::c_int = 0;
pub const STDOUT_FILENO: ::c_int = 1;
pub const STDERR_FILENO: ::c_int = 2;

extern {
    pub fn memalign(align: ::size_t, size: ::size_t) -> *mut ::c_void;
    pub fn read(fd: ::c_int, buf: *mut ::c_void, count: ::size_t)
                -> ::ssize_t;
    pub fn write(fd: ::c_int, buf: *const ::c_void, count: ::size_t)
                 -> ::ssize_t;
}

#[link(name = "c")]
#[link(name = "m")]
extern {}
<|endoftext|>


<commit_before><commit_msg>Add skeleton code for FilterExec.<commit_after>use common::types::Ty;
use driver::DriverContext;
use super::{Executor, ExecutorFactory};

pub struct FilterExecFactory
{
	types: Vec<Ty>
}

impl FilterExecFactory
{
	pub fn new(f: Box<ExecutorFactory>) -> FilterExecFactory
	{
		FilterExecFactory {
			types: Vec::new()
		}
	}
}

impl ExecutorFactory for FilterExecFactory
{
	fn create(&self, ctx: &DriverContext) -> Option<Box<Executor>>
	{
		None
	}

	fn types(&self) -> &Vec<Ty>
	{
		&self.types
	}
}

pub struct FilterExec;

<|endoftext|>


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

use liquid::ffiliquid;
use liquid::{Complex32};

pub struct Freqdem {
     object: ffiliquid::freqdem,
}

impl Freqdem {

    /// create freqdem object (frequency demodulator)
    ///  _kf      :   modulation factor
    pub fn new(_kf: f32) -> Freqdem {
        let demod: ffiliquid::freqdem = unsafe{ffiliquid::freqdem_create(_kf)};
        Freqdem{object: demod}
    }

    /// demodulate sample
    ///  _q      :   frequency modulator object
    ///  _r      :   received signal r(t)
    ///  _m      :   output message signal m(t)
    pub fn demodulate(&self, _r: Complex32, _m: *mut f32) {
        unsafe{ffiliquid::freqdem_demodulate(self.object, _r, _m)};
    }

    /// demodulate block of samples
    ///  _q      :   frequency demodulator object
    ///  _r      :   received signal r(t) [size: _n x 1]
    ///  _n      :   number of input, output samples
    ///  _m      :   message signal m(t), [size: _n x 1]
    pub fn demodulate_block(&self, _r: *mut Complex32, _n: u32, _m: *mut f32) {
        unsafe{ffiliquid::freqdem_demodulate_block(self.object, _r, _n, _m)};
    }
}

impl Drop for Freqdem {
    fn drop(&mut self) {
        unsafe{ffiliquid::freqdem_destroy(self.object)};
    }
}
<|endoftext|>


<commit_before><commit_msg>Regression test<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.

// Tests that we forbid coercion from `[T, ..n]` to `&[T]`

fn main() {
    let _: &[int] = [0i]; //~ERROR: mismatched types: expected `&[int]`, found `[int, ..1]`
}
<|endoftext|>


<commit_before><commit_msg>Implements integration testing framework<commit_after>extern crate radeco;

#[cfg(test)]
pub mod esil_to_ssa {

	use radeco::frontend::{parser, r2, esilssa};
	use radeco::middle::{cfg};
	use radeco::middle::dot;
	use radeco::middle::ssastorage::SSAStorage;

	use std::env;
	use std;
	use std::io::prelude::*;
	use std::fs::{File, create_dir};

	fn write_file(fname: &str, res: String) {
		let mut file = File::create(fname).ok().expect("Error. Cannot create file!\n");
		file.write_all(res.as_bytes()).ok().expect("Error. Cannot write file!\n");
	}

	pub enum Analysis {
		ConstProp,
	}

	pub enum Pipeline {
		ReadFromR2,
		ParseEsil,
		CFG,
		SSA,
		AnalyzeSSA(Analysis),
		CWriter,
	}

	impl Pipeline {
		fn to_string(&self) -> String {
			let s = match *self {
				Pipeline::ReadFromR2 => "r2",
				Pipeline::ParseEsil => "radecoIR",
				Pipeline::CFG => "cfg",
				Pipeline::SSA => "ssa",
				Pipeline::AnalyzeSSA(a) => unimplemented!(),
				Pipeline::CWriter => unimplemented!(),
			};
			s.to_string()
		}
	}

	// Enum that represents the output of a stage in the Pipeline.
	pub enum Pipeout {
		Foo,
	}

	// Bundles all the vars important to various stages of the pipeline together.
	// Also acts as the result struct.
	pub struct Bundle {
		r2: Option<R2>,
		esil: Option<Vec<String>>,
		p: Option<Parser>,
		cfg: Option<CFG>,
		ssa: Option<SSAStorage>,
		pipeout: Option<Pipeout>,
	}

	impl Bundle {
		fn new() -> Bundle {
			Bundle {
				r2: None,
				esil: None,
				p: None,
				cfg: None,
				ssa: None,
			}
		}
	}

	// TODO: Improve this result struct.
	// Right now: `f` -> Filename to write out `res` to.
	pub struct Results {
		f: String,
		res: String,
	}

	// Function to initialize all your vars to sane defaults.
	fn init_vars() {
	}

	// Function to run the integration test.
	// The common pipeline is esil -> cfg -> ssa.
	// Returns a result struct which can be used to assert! the results.
	fn run_test(pipeline: &Vec<Pipeline>, bundle: &mut Bundle) -> Results {
		for stage in pipeline.iter() {
			match stage {
				Pipeline::ReadFromR2 => { },
				Pipeline::ParseEsil => { },
				Pipeline::CFG => { },
				Pipeline::SSA => { },
				Pipeline::AnalyzeSSA(a) => unimplemented!(),
				Pipeline::CWriter => unimplemented!(),
			}
		}
	}

	#[test]
	fn test1() {
		let bin_name = "./ex-bins/simple2";
		let mut r2 = r2::R2::new(bin_name);
		r2.init();

		let reg_info = r2.get_reg_info().unwrap();

		// Make a manual esil string for this small test.
		let esil = "4,5,+,6,*";

		let mut p = parser::Parser::new(None);
		println!("[*] Begin Parse.");
		println!("    > {} ", esil);
		p.set_register_profile(&reg_info);

		p.parse_str(esil);
		let mut cfg = cfg::CFG::new();
		cfg.build(&mut (p.emit_insts()));
		let mut ssa = SSAStorage::new();

		{
			let mut con = esilssa::SSAConstruction::new(&mut ssa, &reg_info);
			con.run(&cfg);
		}

		let res_cfg = dot::emit_dot(&cfg);
		let res_ssa = dot::emit_dot(&ssa);

		std::fs::create_dir("outputs").ok();

		let outfile = "outputs/ex5-cfg.dot";
		write_file(outfile, res_cfg);
		println!("[*] Run `./scripts/genpng.sh {}` to generate the cfg-graph.", outfile);

		let outfile = "outputs/ex5-ssa.dot";
		write_file(outfile, res_ssa);
		println!("[*] Run `./scripts/genpng.sh {}` to generate the ssa-graph.", outfile);
	}
}
<|endoftext|>


<commit_before><commit_msg>audio.reorder method<commit_after><|endoftext|>


<commit_before><commit_msg>Do-over the universe struct<commit_after>// extern crate euclid;

pub use itertools::Itertools;
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};

pub use euclid::{Point2D, TypedRect, TypedVector2D};
pub use num::Integer as IntegerTrait;
pub use rug::Integer;

use defs::*;
use delta::*;
use math;
use math::Direction;
use polyomino::*;

#[derive(Debug)]
pub struct Shape {
    pub polyomino: Polyomino,

    // Drawing:
    pub fill_color: [f32; 3],
    pub outline_color: [f32; 3],
}

impl PartialEq for Shape {
    fn eq(&self, other: &Shape) -> bool {
        self.polyomino == other.polyomino
    }
}

impl Eq for Shape {}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ChunkId(pub u32);

#[derive(PartialEq, Eq, Debug)]
pub struct Chunk {
    // Gameplay:
    pub id: ChunkId,
    pub parent_id: ChunkId,
    pub position_on_parent: ChildPoint,

    pub shapes: Vec<(Shape, UPoint)>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Square {
    pub shape_id: ChunkId,
    pub position: UPoint,
}

impl Square {
    fn location(&self, universe: &Universe) -> Location {
        unimplemented!();
        // let mut locations: Vec<Location> = universe.shapes[&self.shape_id]
        //     .parent_ids
        //     .keys()
        //     .filter_map(|s| self.location_on(universe, *s))
        //     .collect();

        // match locations.len() {
        //     0 => panic!("A square is not sitting on a location!"),
        //     1 => locations.pop().unwrap(),
        //     _ => panic!("A square is sitting on multiple locations!"),
        // }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Location {
    pub square: Square,
    pub subposition: ChildVec,
}

#[derive(PartialEq, Eq, Debug)]
pub struct Universe {
    pub chunks: BTreeMap<ChunkId, Chunk>, // Should maybe just be a Vec
}

impl Universe {
    pub fn minimal() -> Universe {
        let id1 = ChunkId(1);
        let id2 = ChunkId(2);
        let chunk1 = Chunk {
            id: id1,
            parent_id: id2,
            position_on_parent: ChildPoint::new(0, 0),
            shapes: vec![(
                Shape {
                    polyomino: Polyomino::monomino(),
                    fill_color: [0.5, 0.5, 1.0],
                    outline_color: [0.5, 0.5, 0.5],
                },
                UPoint::new(0, 0),
            )],
        };

        let chunk2 = Chunk {
            id: id2,
            parent_id: id1,
            position_on_parent: ChildPoint::new(0, 0),
            shapes: vec![(
                Shape {
                    polyomino: Polyomino::monomino(),
                    fill_color: [1.0, 0.5, 0.5],
                    outline_color: [0.5, 0.25, 0.25],
                },
                UPoint::new(0, 0),
            )],
        };

        let mut chunks = BTreeMap::new();
        chunks.insert(id1, chunk1);
        chunks.insert(id2, chunk2);

        Universe { chunks: chunks }
    }
}
<|endoftext|>


<commit_before><commit_msg>Add multitarget test<commit_after><|endoftext|>


<commit_before><commit_msg>Make it slightly easier to match forward + reverse routes.<commit_after><|endoftext|>


<commit_before><commit_msg>fixup! Slightly reduce coupling between journey and filtering.<commit_after><|endoftext|>


<commit_before><commit_msg>Fix NbtBlob Index impl<commit_after><|endoftext|>


<commit_before><commit_msg>Fix typo in comment.<commit_after><|endoftext|>


<commit_before><commit_msg>Tickrate measurement.<commit_after><|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.

use spec::{LinkerFlavor, PanicStrategy, Target, TargetOptions, TargetResult};
use spec::abi::{Abi};

pub fn target() -> TargetResult {
    Ok(Target {
        data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(),
        llvm_target: "riscv32".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "32".to_string(),
        target_c_int_width: "32".to_string(),
        target_os: "none".to_string(),
        target_env: String::new(),
        target_vendor: "unknown".to_string(),
        arch: "riscv32".to_string(),
        linker_flavor: LinkerFlavor::Ld,

        options: TargetOptions {
            linker: Some("riscv32-unknown-elf-ld".to_string()),
            cpu: "generic-rv32".to_string(),
            max_atomic_width: Some(32),
            atomic_cas: false, // incomplete +a extension
            features: "+m,+a".to_string(), // disable +c extension
            executables: true,
            panic_strategy: PanicStrategy::Abort,
            relocation_model: "static".to_string(),
            emit_debug_gdb_scripts: false,
            abi_blacklist: vec![
                Abi::Cdecl,
                Abi::Stdcall,
                Abi::Fastcall,
                Abi::Vectorcall,
                Abi::Thiscall,
                Abi::Aapcs,
                Abi::Win64,
                Abi::SysV64,
                Abi::PtxKernel,
                Abi::Msp430Interrupt,
                Abi::X86Interrupt,
            ],
            .. Default::default()
        },
    })
}
<commit_msg>[RISCV] Use lld as the default linker.<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.

use spec::{LinkerFlavor, LldFlavor, PanicStrategy,
           Target, TargetOptions, TargetResult};
use spec::abi::{Abi};

pub fn target() -> TargetResult {
    Ok(Target {
        data_layout: "e-m:e-p:32:32-i64:64-n32-S128".to_string(),
        llvm_target: "riscv32".to_string(),
        target_endian: "little".to_string(),
        target_pointer_width: "32".to_string(),
        target_c_int_width: "32".to_string(),
        target_os: "none".to_string(),
        target_env: String::new(),
        target_vendor: "unknown".to_string(),
        arch: "riscv32".to_string(),
        linker_flavor: LinkerFlavor::Lld(LldFlavor::Ld),

        options: TargetOptions {
            linker: Some("rust-lld".to_string()),
            cpu: "generic-rv32".to_string(),
            max_atomic_width: Some(32),
            atomic_cas: false, // incomplete +a extension
            features: "+m,+a".to_string(), // disable +c extension
            executables: true,
            panic_strategy: PanicStrategy::Abort,
            relocation_model: "static".to_string(),
            emit_debug_gdb_scripts: false,
            abi_blacklist: vec![
                Abi::Cdecl,
                Abi::Stdcall,
                Abi::Fastcall,
                Abi::Vectorcall,
                Abi::Thiscall,
                Abi::Aapcs,
                Abi::Win64,
                Abi::SysV64,
                Abi::PtxKernel,
                Abi::Msp430Interrupt,
                Abi::X86Interrupt,
            ],
            .. Default::default()
        },
    })
}
<|endoftext|>


<commit_before><commit_msg>json handshake<commit_after><|endoftext|>


<commit_before><commit_msg>Add example for Abandon<commit_after>extern crate ldap3;

use ldap3::{LdapConn, Scope};

const ENTRIES_BEFORE_ABANDON: usize = 20;

fn main() {
    let ldap = LdapConn::new("ldap://localhost:2389").expect("ldap handle");
    let mut count = 0;
    let mut strm = ldap.streaming_search(
        "ou=Places,dc=example,dc=org",
        Scope::Subtree,
        "objectClass=locality",
        vec!["l"]
    ).expect("stream");
    while let Ok(Some(_r)) = strm.next() {
        count += 1;
        if count == ENTRIES_BEFORE_ABANDON {
            ldap.abandon(strm.id().expect("id")).expect("abandon");
            continue;
        }
    }
    let (res, _ctrls) = strm.result().expect("result");
    println!("Result: {:?}", res);
}
<|endoftext|>


<commit_before>use redox::Vec;

pub struct AvlNode<T> {
    value: T,
    left: Option<AvlNodeId>, // ID for left node
    right: Option<AvlNodeId>, // ID for right node
}

#[derive(Copy, Clone)]
pub struct AvlNodeId {
    index: usize,
    time_stamp: u64,
}

impl AvlNodeId {
    pub fn get<'a, T>(&self, avl: &'a Avl<T>) -> Option<&'a AvlNode<T>> {
        avl.nodes
           .get(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_ref()
               } else {
                   None
               }
           })
    }

    pub fn get_mut<'a, T>(&self, avl: &'a mut Avl<T>) -> Option<&'a mut AvlNode<T>> {
        avl.nodes
           .get_mut(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_mut()
               } else {
                   None
               }
           })
    }
}

pub struct Avl<T> {
    root: usize, // Index of the root node
    nodes: Vec<AvlSlot<T>>,
    free_list: Vec<usize>,
}

impl<T> Avl<T> {
    pub fn new() -> Self {
        Avl {
            root: 0,
            nodes: Vec::new(),
            free_list: Vec::new(),
        }
    }

    pub fn insert(&mut self, value: T) -> AvlNodeId {
        // TODO this is just a placeholder, we need to deal with all the fancy rotation stuff that
        // AVL trees do
        self.allocate_node(value)
    }

    // Performs a left rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_left(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate left, the right child node must exist
        let r = node.get(self).unwrap().right.unwrap();
        let rl = r.get(self).unwrap().left;

        let ret = r;
        node.get_mut(self).unwrap().right = rl;
        ret.get_mut(self).unwrap().left = Some(node);

        ret
    }

    // Performs a right rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_right(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate right, the left child node must exist
        let l = node.get(self).unwrap().left.unwrap();
        let lr = l.get(self).unwrap().right;

        let ret = l;
        node.get_mut(self).unwrap().left = lr;
        ret.get_mut(self).unwrap().right = Some(node);

        ret
    }

    // performs a left-right double rotation on a tree/subtree.
    fn rotate_leftright(&mut self, node: AvlNodeId) -> AvlNodeId {
        let l = node.get(self).unwrap().left.unwrap();
        let new_l = self.rotate_left(l); // Left node needs to exist
        node.get_mut(self).unwrap().left = Some(new_l);
        self.rotate_right(node)
    }

    // performs a right-left double rotation on a tree/subtree.
    fn rotate_rightleft(&mut self, node: AvlNodeId) -> AvlNodeId {
        let r = node.get(self).unwrap().right.unwrap();
        let new_r = self.rotate_right(r); // Right node needs to exist
        node.get_mut(self).unwrap().right = Some(new_r);
        self.rotate_left(node)
    }

    // _ins is the implementation of the binary tree insert function. Lesser values will be stored on
    // the left, while greater values will be stored on the right. No duplicates are allowed.
    /*fn _ins(&mut self, node_index: Option<AvlNodeId>, value: T) -> AvlNodeId {
        let node =
            match node_index {
                Some(node) => {
                    // Node exists, check which way to branch.
                    if n == node->val {
                        return node;
                    else if (n < node->val)
                        _ins(n, node->left);
                    else if (n > node->val)
                        _ins(n, node->right);
                },
                None => {
                    // The node doesn't exist, create it here.
                    self.allocate_node(value)
                },
            };

        rebalance(node);
    }*/

    // _rebalance rebalances the provided node
    /*fn rebalance(Node*& node) {
        if (!node)
        {
            return;
        }

        int balance = _height(node->left) - _height(node->right);
        if (balance == 2) // left
        {
            int lbalance = _height(node->left->left) - _height(node->left->right);
            if (lbalance == 0 || lbalance == 1) // left left - need to rotate right
            {
                rotate_right(node);
            }
            else if (lbalance == -1) // left right
            {
                rotate_leftright(node); // function name is just a coincidence
            }
        }
        else if (balance == -2) // right
        {
            int rbalance = _height(node->right->left) - _height(node->right->right);
            if (rbalance == 1) // right left
            {
                rotate_rightleft(node); // function name is just a coincidence
            }
            else if (rbalance == 0 || rbalance == -1) // right right - need to rotate left
            {
                rotate_left(node);
            }
        }
    }

    // _height gets the height of a tree or subtree
    fn _height(node: AvlNodeId) -> usize {
        if (!node)
            return -1;

        int left_height = _height(node->left);
        int right_height = _height(node->right);

        if (left_height > right_height)
            return left_height+1;
        else
            return right_height+1;
    }*/

    fn allocate_node(&mut self, value: T) -> AvlNodeId {
        match self.free_list.pop() {
            Some(index) => {
                AvlNodeId { time_stamp: self.nodes[index].time_stamp+1, index: index }
            },
            None => {
                // No free slots, create a new one
                let id = AvlNodeId { index: self.nodes.len(), time_stamp: 0 };
                self.nodes.push(AvlSlot { time_stamp: 0,
                                          node: Some(AvlNode { value: value, left: None, right: None }) });
                id
            },
        }
    }

    fn free_node(&mut self, id: AvlNodeId) -> AvlNode<T> {
        self.free_list.push(id.index);

        // NOTE: We unwrap here, because we trust that `id` points to a valid node, because
        // only we can create and free AvlNodes and their AvlNodeIds
        self.nodes[id.index].node.take().unwrap()
    }
}

struct AvlSlot<T> {
    time_stamp: u64,
    node: Option<AvlNode<T>>,
}
<commit_msg>avl tree height method<commit_after>use redox::Vec;

pub struct AvlNode<T> {
    value: T,
    left: Option<AvlNodeId>, // ID for left node
    right: Option<AvlNodeId>, // ID for right node
}

#[derive(Copy, Clone)]
pub struct AvlNodeId {
    index: usize,
    time_stamp: u64,
}

impl AvlNodeId {
    pub fn get<'a, T>(&self, avl: &'a Avl<T>) -> Option<&'a AvlNode<T>> {
        avl.nodes
           .get(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_ref()
               } else {
                   None
               }
           })
    }

    pub fn get_mut<'a, T>(&self, avl: &'a mut Avl<T>) -> Option<&'a mut AvlNode<T>> {
        avl.nodes
           .get_mut(self.index)
           .and_then(|slot| {
               if slot.time_stamp == self.time_stamp {
                   slot.node.as_mut()
               } else {
                   None
               }
           })
    }
}

pub struct Avl<T> {
    root: usize, // Index of the root node
    nodes: Vec<AvlSlot<T>>,
    free_list: Vec<usize>,
}

impl<T> Avl<T> {
    pub fn new() -> Self {
        Avl {
            root: 0,
            nodes: Vec::new(),
            free_list: Vec::new(),
        }
    }

    pub fn insert(&mut self, value: T) -> AvlNodeId {
        // TODO this is just a placeholder, we need to deal with all the fancy rotation stuff that
        // AVL trees do
        self.allocate_node(value)
    }

    // Performs a left rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_left(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate left, the right child node must exist
        let r = node.get(self).unwrap().right.unwrap();
        let rl = r.get(self).unwrap().left;

        let ret = r;
        node.get_mut(self).unwrap().right = rl;
        ret.get_mut(self).unwrap().left = Some(node);

        ret
    }

    // Performs a right rotation on a tree/subtree.
    // Returns the replace the specified node with
    fn rotate_right(&mut self, node: AvlNodeId) -> AvlNodeId {
        // Keep track of the original node positions
        // For a rotate right, the left child node must exist
        let l = node.get(self).unwrap().left.unwrap();
        let lr = l.get(self).unwrap().right;

        let ret = l;
        node.get_mut(self).unwrap().left = lr;
        ret.get_mut(self).unwrap().right = Some(node);

        ret
    }

    // performs a left-right double rotation on a tree/subtree.
    fn rotate_leftright(&mut self, node: AvlNodeId) -> AvlNodeId {
        let l = node.get(self).unwrap().left.unwrap();
        let new_l = self.rotate_left(l); // Left node needs to exist
        node.get_mut(self).unwrap().left = Some(new_l);
        self.rotate_right(node)
    }

    // performs a right-left double rotation on a tree/subtree.
    fn rotate_rightleft(&mut self, node: AvlNodeId) -> AvlNodeId {
        let r = node.get(self).unwrap().right.unwrap();
        let new_r = self.rotate_right(r); // Right node needs to exist
        node.get_mut(self).unwrap().right = Some(new_r);
        self.rotate_left(node)
    }

    // _ins is the implementation of the binary tree insert function. Lesser values will be stored on
    // the left, while greater values will be stored on the right. No duplicates are allowed.
    /*fn _ins(&mut self, node_index: Option<AvlNodeId>, value: T) -> AvlNodeId {
        let node =
            match node_index {
                Some(node) => {
                    // Node exists, check which way to branch.
                    if n == node->val {
                        return node;
                    else if (n < node->val)
                        _ins(n, node->left);
                    else if (n > node->val)
                        _ins(n, node->right);
                },
                None => {
                    // The node doesn't exist, create it here.
                    self.allocate_node(value)
                },
            };

        rebalance(node);
    }*/

    // _rebalance rebalances the provided node
    /*fn rebalance(Node*& node) {
        if (!node)
        {
            return;
        }

        int balance = _height(node->left) - _height(node->right);
        if (balance == 2) // left
        {
            int lbalance = _height(node->left->left) - _height(node->left->right);
            if (lbalance == 0 || lbalance == 1) // left left - need to rotate right
            {
                rotate_right(node);
            }
            else if (lbalance == -1) // left right
            {
                rotate_leftright(node); // function name is just a coincidence
            }
        }
        else if (balance == -2) // right
        {
            int rbalance = _height(node->right->left) - _height(node->right->right);
            if (rbalance == 1) // right left
            {
                rotate_rightleft(node); // function name is just a coincidence
            }
            else if (rbalance == 0 || rbalance == -1) // right right - need to rotate left
            {
                rotate_left(node);
            }
        }
    }*/

    // height gets the height of a tree or subtree
    fn height(&self, node: Option<AvlNodeId>) -> i64 {
        match node {
            Some(node) => {
                let left_height = self.height(node.get(self).unwrap().left);
                let right_height = self.height(node.get(self).unwrap().right);

                if left_height > right_height {
                    left_height+1
                } else {
                    right_height+1
                }
            },
            None => { -1 },
        }
    }

    fn allocate_node(&mut self, value: T) -> AvlNodeId {
        match self.free_list.pop() {
            Some(index) => {
                AvlNodeId { time_stamp: self.nodes[index].time_stamp+1, index: index }
            },
            None => {
                // No free slots, create a new one
                let id = AvlNodeId { index: self.nodes.len(), time_stamp: 0 };
                self.nodes.push(AvlSlot { time_stamp: 0,
                                          node: Some(AvlNode { value: value, left: None, right: None }) });
                id
            },
        }
    }

    fn free_node(&mut self, id: AvlNodeId) -> AvlNode<T> {
        self.free_list.push(id.index);

        // NOTE: We unwrap here, because we trust that `id` points to a valid node, because
        // only we can create and free AvlNodes and their AvlNodeIds
        self.nodes[id.index].node.take().unwrap()
    }
}

struct AvlSlot<T> {
    time_stamp: u64,
    node: Option<AvlNode<T>>,
}
<|endoftext|>


<commit_before><commit_msg>Add problem #61<commit_after>use common::problem::{ Problem };

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

fn create_map(f: &fn(uint) -> uint) -> ~[~[uint]] {
    let mut result = vec::from_elem(100, ~[]);
    let mut i = 1;
    loop {
        let n = f(i);
        if n >= 10000 { break; }
        result[n / 100].push(n % 100);
        i += 1;
    }
    return result;
}

fn solve() -> ~str {
    let mut map = ~[
        create_map(|n| n * (n + 1) / 2),
        create_map(|n| n * n),
        create_map(|n| n * (3 * n - 1) / 2),
        create_map(|n| n * (2 * n - 1)),
        create_map(|n| n * (5 * n - 3) / 2),
        create_map(|n| n * (3 * n - 2))
    ];

    let mut result = ~[];
    for vec::each_permutation([0u, 1u, 2u, 3u, 4u]) |idx| {
        for map[5].eachi |i, v5| {
            if i < 10 { loop; }
            for v5.each_val |n5| {
                if n5 < 10 { loop; }
                for map[idx[0]][n5].each_val |n0| {
                    if n0 < 10 { loop; }
                    for map[idx[1]][n0].each_val |n1| {
                        if n1 < 10 { loop; }
                        for map[idx[2]][n1].each_val |n2| {
                            if n2 < 10 { loop; }
                            for map[idx[3]][n2].each_val |n3| {
                                if n3 < 10 { loop; }
                                for map[idx[4]][n3].each_val |n4| {
                                    if n4 < 10 { loop; }
                                    if n4 == i {
                                        result.push(~[
                                            n5 * 100 + n0,
                                            n0 * 100 + n1,
                                            n1 * 100 + n2,
                                            n2 * 100 + n3,
                                            n3 * 100 + n4,
                                            n4 * 100 + n5
                                        ]);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    let mut sum = result.foldl(0u, |s, vs| s + vs.foldl(0u, |s, &n| s + n));
    return sum.to_str();
}

<|endoftext|>


<commit_before><commit_msg>Create short_number_info.rs<commit_after><|endoftext|>