<commit_before>use alloc::boxed::Box;

use collections::slice;
use collections::vec::Vec;
use collections::vec_deque::VecDeque;

use core::ptr;

use common::{debug, memory};

use drivers::pciconfig::PciConfig;

use network::common::*;
use network::scheme::*;

use schemes::{Result, KScheme, Resource, Url};

use sync::Intex;

const CTRL: u32 = 0x00;
const CTRL_LRST: u32 = 1 << 3;
const CTRL_ASDE: u32 = 1 << 5;
const CTRL_SLU: u32 = 1 << 6;
const CTRL_ILOS: u32 = 1 << 7;
const CTRL_VME: u32 = 1 << 30;
const CTRL_PHY_RST: u32 = 1 << 31;

const STATUS: u32 = 0x08;

const FCAL: u32 = 0x28;
const FCAH: u32 = 0x2C;
const FCT: u32 = 0x30;
const FCTTV: u32 = 0x170;

const ICR: u32 = 0xC0;

const IMS: u32 = 0xD0;
const IMS_TXDW: u32 = 1;
const IMS_TXQE: u32 = 1 << 1;
const IMS_LSC: u32 = 1 << 2;
const IMS_RXSEQ: u32 = 1 << 3;
const IMS_RXDMT: u32 = 1 << 4;
const IMS_RX: u32 = 1 << 6;
const IMS_RXT: u32 = 1 << 7;

const RCTL: u32 = 0x100;
const RCTL_EN: u32 = 1 << 1;
const RCTL_UPE: u32 = 1 << 3;
const RCTL_MPE: u32 = 1 << 4;
const RCTL_LPE: u32 = 1 << 5;
const RCTL_LBM: u32 = 1 << 6 | 1 << 7;
const RCTL_BAM: u32 = 1 << 15;
const RCTL_BSIZE1: u32 = 1 << 16;
const RCTL_BSIZE2: u32 = 1 << 17;
const RCTL_BSEX: u32 = 1 << 25;
const RCTL_SECRC: u32 = 1 << 26;

const RDBAL: u32 = 0x2800;
const RDBAH: u32 = 0x2804;
const RDLEN: u32 = 0x2808;
const RDH: u32 = 0x2810;
const RDT: u32 = 0x2818;

const RAL0: u32 = 0x5400;
const RAH0: u32 = 0x5404;

#[repr(packed)]
struct Rd {
    buffer: u64,
    length: u16,
    checksum: u16,
    status: u8,
    error: u8,
    special: u16,
}
const RD_DD: u8 = 1;
const RD_EOP: u8 = 1 << 1;

const TCTL: u32 = 0x400;
const TCTL_EN: u32 = 1 << 1;
const TCTL_PSP: u32 = 1 << 3;

const TDBAL: u32 = 0x3800;
const TDBAH: u32 = 0x3804;
const TDLEN: u32 = 0x3808;
const TDH: u32 = 0x3810;
const TDT: u32 = 0x3818;

#[repr(packed)]
struct Td {
    buffer: u64,
    length: u16,
    cso: u8,
    command: u8,
    status: u8,
    css: u8,
    special: u16,
}
const TD_CMD_EOP: u8 = 1;
const TD_CMD_IFCS: u8 = 1 << 1;
const TD_CMD_RS: u8 = 1 << 3;
const TD_DD: u8 = 1;

pub struct Intel8254x {
    pub pci: PciConfig,
    pub base: usize,
    pub memory_mapped: bool,
    pub irq: u8,
    pub resources: Intex<Vec<*mut NetworkResource>>,
    pub inbound: VecDeque<Vec<u8>>,
    pub outbound: VecDeque<Vec<u8>>,
}

impl KScheme for Intel8254x {
    fn scheme(&self) -> &str {
        "network"
    }

    fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> {
        Ok(NetworkResource::new(self))
    }

    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            unsafe {
                debug::dh(self.read(ICR) as usize);
                debug::dl();
            }

            self.sync();
        }
    }

    fn on_poll(&mut self) {
        self.sync();
    }
}

impl NetworkScheme for Intel8254x {
    fn add(&mut self, resource: *mut NetworkResource) {
        self.resources.lock().push(resource);
    }

    fn remove(&mut self, resource: *mut NetworkResource) {
        let mut resources = self.resources.lock();

        let mut i = 0;
        while i < resources.len() {
            let mut remove = false;

            match resources.get(i) {
                Some(ptr) => if *ptr == resource {
                    remove = true;
                } else {
                    i += 1;
                },
                None => break,
            }

            if remove {
                resources.remove(i);
            }
        }
    }

    fn sync(&mut self) {
        unsafe {
            {
                let resources = self.resources.lock();

                for resource in resources.iter() {
                    while let Some(bytes) = (**resource).outbound.lock().pop_front() {
                        self.outbound.push_back(bytes);
                    }
                }
            }

            self.send_outbound();

            self.receive_inbound();

            {
                let resources = self.resources.lock();

                while let Some(bytes) = self.inbound.pop_front() {
                    for resource in resources.iter() {
                        (**resource).inbound.lock().push_back(bytes.clone());
                    }
                }
            }
        }
    }
}

impl Intel8254x {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        let base = pci.read(0x10) as usize;

        let mut module = box Intel8254x {
            pci: pci,
            base: base & 0xFFFFFFF0,
            memory_mapped: base & 1 == 0,
            irq: pci.read(0x3C) as u8 & 0xF,
            resources: Intex::new(Vec::new()),
            inbound: VecDeque::new(),
            outbound: VecDeque::new(),
        };

        module.init();

        module
    }

    pub unsafe fn receive_inbound(&mut self) {
        let receive_ring = self.read(RDBAL) as *mut Rd;
        let length = self.read(RDLEN);

        for tail in 0..length / 16 {
            let rd = &mut *receive_ring.offset(tail as isize);
            if rd.status & RD_DD == RD_DD {
                debug::d("Recv ");
                debug::dh(rd as *mut Rd as usize);
                debug::d(" ");
                debug::dh(rd.status as usize);
                debug::d(" ");
                debug::dh(rd.buffer as usize);
                debug::d(" ");
                debug::dh(rd.length as usize);
                debug::dl();

                self.inbound.push_back(Vec::from(slice::from_raw_parts(rd.buffer as *const u8,
                                                                       rd.length as usize)));

                rd.status = 0;
            }
        }
    }

    pub unsafe fn send_outbound(&mut self) {
        while let Some(bytes) = self.outbound.pop_front() {
            let transmit_ring = self.read(TDBAL) as *mut Td;
            let length = self.read(TDLEN);

            loop {
                let head = self.read(TDH);
                let mut tail = self.read(TDT);
                let old_tail = tail;

                tail += 1;
                if tail >= length / 16 {
                    tail = 0;
                }

                if tail != head {
                    if bytes.len() < 16384 {
                        let td = &mut *transmit_ring.offset(old_tail as isize);

                        debug::d("Send ");
                        debug::dh(old_tail as usize);
                        debug::d(" ");
                        debug::dh(td.status as usize);
                        debug::d(" ");
                        debug::dh(td.buffer as usize);
                        debug::d(" ");
                        debug::dh(bytes.len() & 0x3FFF);
                        debug::dl();

                        ::memcpy(td.buffer as *mut u8, bytes.as_ptr(), bytes.len());
                        td.length = (bytes.len() & 0x3FFF) as u16;
                        td.cso = 0;
                        td.command = TD_CMD_EOP | TD_CMD_IFCS | TD_CMD_RS;
                        td.status = 0;
                        td.css = 0;
                        td.special = 0;

                        self.write(TDT, tail);
                    } else {
                        // TODO: More than one TD
                        debug::dl();
                        debug::d("Intel 8254x: Frame too long for transmit: ");
                        debug::dd(bytes.len());
                        debug::dl();
                    }

                    break;
                }
            }
        }
    }

    pub unsafe fn read(&self, register: u32) -> u32 {
        if self.memory_mapped {
            ptr::read((self.base + register as usize) as *mut u32)
        } else {
            0
        }
    }

    pub unsafe fn write(&self, register: u32, data: u32) -> u32 {
        if self.memory_mapped {
            ptr::write((self.base + register as usize) as *mut u32, data);
            ptr::read((self.base + register as usize) as *mut u32)
        } else {
            0
        }
    }

    pub unsafe fn flag(&self, register: u32, flag: u32, value: bool) {
        if value {
            self.write(register, self.read(register) | flag);
        } else {
            self.write(register, self.read(register) & (0xFFFFFFFF - flag));
        }
    }

    pub unsafe fn init(&mut self) {
        debug::d("Intel 8254x on: ");
        debug::dh(self.base);
        if self.memory_mapped {
            debug::d(" memory mapped");
        } else {
            debug::d(" port mapped");
        }
        debug::d(", IRQ: ");
        debug::dbh(self.irq);

        self.pci.flag(4, 4, true); // Bus mastering

        // Enable auto negotiate, link, clear reset, do not Invert Loss-Of Signal
        self.flag(CTRL, CTRL_ASDE | CTRL_SLU, true);
        self.flag(CTRL, CTRL_LRST, false);
        self.flag(CTRL, CTRL_PHY_RST, false);
        self.flag(CTRL, CTRL_ILOS, false);

        // No flow control
        self.write(FCAH, 0);
        self.write(FCAL, 0);
        self.write(FCT, 0);
        self.write(FCTTV, 0);

        // Do not use VLANs
        self.flag(CTRL, CTRL_VME, false);

        debug::d(" CTRL ");
        debug::dh(self.read(CTRL) as usize);

        // TODO: Clear statistical counters

        debug::d(" MAC: ");
        let mac_low = self.read(RAL0);
        let mac_high = self.read(RAH0);
        MAC_ADDR = MacAddr {
            bytes: [mac_low as u8,
                    (mac_low >> 8) as u8,
                    (mac_low >> 16) as u8,
                    (mac_low >> 24) as u8,
                    mac_high as u8,
                    (mac_high >> 8) as u8],
        };
        debug::d(&MAC_ADDR.to_string());

        //
        // MTA => 0;
        //

        // Receive Buffer
        let receive_ring_length = 1024;
        let receive_ring = memory::alloc(receive_ring_length * 16) as *mut Rd;
        for i in 0..receive_ring_length {
            let receive_buffer = memory::alloc(16384);
            ptr::write(receive_ring.offset(i as isize),
                       Rd {
                           buffer: receive_buffer as u64,
                           length: 0,
                           checksum: 0,
                           status: 0,
                           error: 0,
                           special: 0,
                       });
        }

        self.write(RDBAH, 0);
        self.write(RDBAL, receive_ring as u32);
        self.write(RDLEN, (receive_ring_length * 16) as u32);
        self.write(RDH, 0);
        self.write(RDT, receive_ring_length as u32 - 1);

        // Transmit Buffer
        let transmit_ring_length = 64;
        let transmit_ring = memory::alloc(transmit_ring_length * 16) as *mut Td;
        for i in 0..transmit_ring_length {
            let transmit_buffer = memory::alloc(16384);
            ptr::write(transmit_ring.offset(i as isize),
                       Td {
                           buffer: transmit_buffer as u64,
                           length: 0,
                           cso: 0,
                           command: 0,
                           status: 0,
                           css: 0,
                           special: 0,
                       });
        }

        self.write(TDBAH, 0);
        self.write(TDBAL, transmit_ring as u32);
        self.write(TDLEN, (transmit_ring_length * 16) as u32);
        self.write(TDH, 0);
        self.write(TDT, 0);

        self.write(IMS,
                   IMS_RXT | IMS_RX | IMS_RXDMT | IMS_RXSEQ | IMS_LSC | IMS_TXQE | IMS_TXDW);

        debug::d(" IMS ");
        debug::dh(self.read(IMS) as usize);

        self.flag(RCTL, RCTL_EN, true);
        self.flag(RCTL, RCTL_UPE, true);
        // self.flag(RCTL, RCTL_MPE, true);
        self.flag(RCTL, RCTL_LPE, true);
        self.flag(RCTL, RCTL_LBM, false);
        // RCTL.RDMTS = Minimum threshold size ???
        // RCTL.MO = Multicast offset
        self.flag(RCTL, RCTL_BAM, true);
        self.flag(RCTL, RCTL_BSIZE1, true);
        self.flag(RCTL, RCTL_BSIZE2, false);
        self.flag(RCTL, RCTL_BSEX, true);
        self.flag(RCTL, RCTL_SECRC, true);

        debug::d(" RCTL ");
        debug::dh(self.read(RCTL) as usize);

        self.flag(TCTL, TCTL_EN, true);
        self.flag(TCTL, TCTL_PSP, true);
        // TCTL.CT = Collition threshold
        // TCTL.COLD = Collision distance
        // TIPG Packet Gap
        // TODO ...

        debug::d(" TCTL ");
        debug::dh(self.read(TCTL) as usize);

        debug::dl();
    }
}
<commit_msg>Remove debugging output from intel network driver<commit_after>use alloc::boxed::Box;

use collections::slice;
use collections::vec::Vec;
use collections::vec_deque::VecDeque;

use core::ptr;

use common::{debug, memory};

use drivers::pciconfig::PciConfig;

use network::common::*;
use network::scheme::*;

use schemes::{Result, KScheme, Resource, Url};

use sync::Intex;

const CTRL: u32 = 0x00;
const CTRL_LRST: u32 = 1 << 3;
const CTRL_ASDE: u32 = 1 << 5;
const CTRL_SLU: u32 = 1 << 6;
const CTRL_ILOS: u32 = 1 << 7;
const CTRL_VME: u32 = 1 << 30;
const CTRL_PHY_RST: u32 = 1 << 31;

const STATUS: u32 = 0x08;

const FCAL: u32 = 0x28;
const FCAH: u32 = 0x2C;
const FCT: u32 = 0x30;
const FCTTV: u32 = 0x170;

const ICR: u32 = 0xC0;

const IMS: u32 = 0xD0;
const IMS_TXDW: u32 = 1;
const IMS_TXQE: u32 = 1 << 1;
const IMS_LSC: u32 = 1 << 2;
const IMS_RXSEQ: u32 = 1 << 3;
const IMS_RXDMT: u32 = 1 << 4;
const IMS_RX: u32 = 1 << 6;
const IMS_RXT: u32 = 1 << 7;

const RCTL: u32 = 0x100;
const RCTL_EN: u32 = 1 << 1;
const RCTL_UPE: u32 = 1 << 3;
const RCTL_MPE: u32 = 1 << 4;
const RCTL_LPE: u32 = 1 << 5;
const RCTL_LBM: u32 = 1 << 6 | 1 << 7;
const RCTL_BAM: u32 = 1 << 15;
const RCTL_BSIZE1: u32 = 1 << 16;
const RCTL_BSIZE2: u32 = 1 << 17;
const RCTL_BSEX: u32 = 1 << 25;
const RCTL_SECRC: u32 = 1 << 26;

const RDBAL: u32 = 0x2800;
const RDBAH: u32 = 0x2804;
const RDLEN: u32 = 0x2808;
const RDH: u32 = 0x2810;
const RDT: u32 = 0x2818;

const RAL0: u32 = 0x5400;
const RAH0: u32 = 0x5404;

#[repr(packed)]
struct Rd {
    buffer: u64,
    length: u16,
    checksum: u16,
    status: u8,
    error: u8,
    special: u16,
}
const RD_DD: u8 = 1;
const RD_EOP: u8 = 1 << 1;

const TCTL: u32 = 0x400;
const TCTL_EN: u32 = 1 << 1;
const TCTL_PSP: u32 = 1 << 3;

const TDBAL: u32 = 0x3800;
const TDBAH: u32 = 0x3804;
const TDLEN: u32 = 0x3808;
const TDH: u32 = 0x3810;
const TDT: u32 = 0x3818;

#[repr(packed)]
struct Td {
    buffer: u64,
    length: u16,
    cso: u8,
    command: u8,
    status: u8,
    css: u8,
    special: u16,
}
const TD_CMD_EOP: u8 = 1;
const TD_CMD_IFCS: u8 = 1 << 1;
const TD_CMD_RS: u8 = 1 << 3;
const TD_DD: u8 = 1;

pub struct Intel8254x {
    pub pci: PciConfig,
    pub base: usize,
    pub memory_mapped: bool,
    pub irq: u8,
    pub resources: Intex<Vec<*mut NetworkResource>>,
    pub inbound: VecDeque<Vec<u8>>,
    pub outbound: VecDeque<Vec<u8>>,
}

impl KScheme for Intel8254x {
    fn scheme(&self) -> &str {
        "network"
    }

    fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> {
        Ok(NetworkResource::new(self))
    }

    fn on_irq(&mut self, irq: u8) {
        if irq == self.irq {
            unsafe { self.read(ICR) };

            self.sync();
        }
    }

    fn on_poll(&mut self) {
        self.sync();
    }
}

impl NetworkScheme for Intel8254x {
    fn add(&mut self, resource: *mut NetworkResource) {
        self.resources.lock().push(resource);
    }

    fn remove(&mut self, resource: *mut NetworkResource) {
        let mut resources = self.resources.lock();

        let mut i = 0;
        while i < resources.len() {
            let mut remove = false;

            match resources.get(i) {
                Some(ptr) => if *ptr == resource {
                    remove = true;
                } else {
                    i += 1;
                },
                None => break,
            }

            if remove {
                resources.remove(i);
            }
        }
    }

    fn sync(&mut self) {
        unsafe {
            {
                let resources = self.resources.lock();

                for resource in resources.iter() {
                    while let Some(bytes) = (**resource).outbound.lock().pop_front() {
                        self.outbound.push_back(bytes);
                    }
                }
            }

            self.send_outbound();

            self.receive_inbound();

            {
                let resources = self.resources.lock();

                while let Some(bytes) = self.inbound.pop_front() {
                    for resource in resources.iter() {
                        (**resource).inbound.lock().push_back(bytes.clone());
                    }
                }
            }
        }
    }
}

impl Intel8254x {
    pub unsafe fn new(mut pci: PciConfig) -> Box<Self> {
        let base = pci.read(0x10) as usize;

        let mut module = box Intel8254x {
            pci: pci,
            base: base & 0xFFFFFFF0,
            memory_mapped: base & 1 == 0,
            irq: pci.read(0x3C) as u8 & 0xF,
            resources: Intex::new(Vec::new()),
            inbound: VecDeque::new(),
            outbound: VecDeque::new(),
        };

        module.init();

        module
    }

    pub unsafe fn receive_inbound(&mut self) {
        let receive_ring = self.read(RDBAL) as *mut Rd;
        let length = self.read(RDLEN);

        for tail in 0..length / 16 {
            let rd = &mut *receive_ring.offset(tail as isize);
            if rd.status & RD_DD == RD_DD {
                debug::d("Recv ");
                debug::dh(rd as *mut Rd as usize);
                debug::d(" ");
                debug::dh(rd.status as usize);
                debug::d(" ");
                debug::dh(rd.buffer as usize);
                debug::d(" ");
                debug::dh(rd.length as usize);
                debug::dl();

                self.inbound.push_back(Vec::from(slice::from_raw_parts(rd.buffer as *const u8,
                                                                       rd.length as usize)));

                rd.status = 0;
            }
        }
    }

    pub unsafe fn send_outbound(&mut self) {
        while let Some(bytes) = self.outbound.pop_front() {
            let transmit_ring = self.read(TDBAL) as *mut Td;
            let length = self.read(TDLEN);

            loop {
                let head = self.read(TDH);
                let mut tail = self.read(TDT);
                let old_tail = tail;

                tail += 1;
                if tail >= length / 16 {
                    tail = 0;
                }

                if tail != head {
                    if bytes.len() < 16384 {
                        let td = &mut *transmit_ring.offset(old_tail as isize);

                        debug::d("Send ");
                        debug::dh(old_tail as usize);
                        debug::d(" ");
                        debug::dh(td.status as usize);
                        debug::d(" ");
                        debug::dh(td.buffer as usize);
                        debug::d(" ");
                        debug::dh(bytes.len() & 0x3FFF);
                        debug::dl();

                        ::memcpy(td.buffer as *mut u8, bytes.as_ptr(), bytes.len());
                        td.length = (bytes.len() & 0x3FFF) as u16;
                        td.cso = 0;
                        td.command = TD_CMD_EOP | TD_CMD_IFCS | TD_CMD_RS;
                        td.status = 0;
                        td.css = 0;
                        td.special = 0;

                        self.write(TDT, tail);
                    } else {
                        // TODO: More than one TD
                        debug::dl();
                        debug::d("Intel 8254x: Frame too long for transmit: ");
                        debug::dd(bytes.len());
                        debug::dl();
                    }

                    break;
                }
            }
        }
    }

    pub unsafe fn read(&self, register: u32) -> u32 {
        if self.memory_mapped {
            ptr::read((self.base + register as usize) as *mut u32)
        } else {
            0
        }
    }

    pub unsafe fn write(&self, register: u32, data: u32) -> u32 {
        if self.memory_mapped {
            ptr::write((self.base + register as usize) as *mut u32, data);
            ptr::read((self.base + register as usize) as *mut u32)
        } else {
            0
        }
    }

    pub unsafe fn flag(&self, register: u32, flag: u32, value: bool) {
        if value {
            self.write(register, self.read(register) | flag);
        } else {
            self.write(register, self.read(register) & (0xFFFFFFFF - flag));
        }
    }

    pub unsafe fn init(&mut self) {
        debug::d("Intel 8254x on: ");
        debug::dh(self.base);
        if self.memory_mapped {
            debug::d(" memory mapped");
        } else {
            debug::d(" port mapped");
        }
        debug::d(", IRQ: ");
        debug::dbh(self.irq);

        self.pci.flag(4, 4, true); // Bus mastering

        // Enable auto negotiate, link, clear reset, do not Invert Loss-Of Signal
        self.flag(CTRL, CTRL_ASDE | CTRL_SLU, true);
        self.flag(CTRL, CTRL_LRST, false);
        self.flag(CTRL, CTRL_PHY_RST, false);
        self.flag(CTRL, CTRL_ILOS, false);

        // No flow control
        self.write(FCAH, 0);
        self.write(FCAL, 0);
        self.write(FCT, 0);
        self.write(FCTTV, 0);

        // Do not use VLANs
        self.flag(CTRL, CTRL_VME, false);

        debug::d(" CTRL ");
        debug::dh(self.read(CTRL) as usize);

        // TODO: Clear statistical counters

        debug::d(" MAC: ");
        let mac_low = self.read(RAL0);
        let mac_high = self.read(RAH0);
        MAC_ADDR = MacAddr {
            bytes: [mac_low as u8,
                    (mac_low >> 8) as u8,
                    (mac_low >> 16) as u8,
                    (mac_low >> 24) as u8,
                    mac_high as u8,
                    (mac_high >> 8) as u8],
        };
        debug::d(&MAC_ADDR.to_string());

        //
        // MTA => 0;
        //

        // Receive Buffer
        let receive_ring_length = 1024;
        let receive_ring = memory::alloc(receive_ring_length * 16) as *mut Rd;
        for i in 0..receive_ring_length {
            let receive_buffer = memory::alloc(16384);
            ptr::write(receive_ring.offset(i as isize),
                       Rd {
                           buffer: receive_buffer as u64,
                           length: 0,
                           checksum: 0,
                           status: 0,
                           error: 0,
                           special: 0,
                       });
        }

        self.write(RDBAH, 0);
        self.write(RDBAL, receive_ring as u32);
        self.write(RDLEN, (receive_ring_length * 16) as u32);
        self.write(RDH, 0);
        self.write(RDT, receive_ring_length as u32 - 1);

        // Transmit Buffer
        let transmit_ring_length = 64;
        let transmit_ring = memory::alloc(transmit_ring_length * 16) as *mut Td;
        for i in 0..transmit_ring_length {
            let transmit_buffer = memory::alloc(16384);
            ptr::write(transmit_ring.offset(i as isize),
                       Td {
                           buffer: transmit_buffer as u64,
                           length: 0,
                           cso: 0,
                           command: 0,
                           status: 0,
                           css: 0,
                           special: 0,
                       });
        }

        self.write(TDBAH, 0);
        self.write(TDBAL, transmit_ring as u32);
        self.write(TDLEN, (transmit_ring_length * 16) as u32);
        self.write(TDH, 0);
        self.write(TDT, 0);

        self.write(IMS,
                   IMS_RXT | IMS_RX | IMS_RXDMT | IMS_RXSEQ | IMS_LSC | IMS_TXQE | IMS_TXDW);

        debug::d(" IMS ");
        debug::dh(self.read(IMS) as usize);

        self.flag(RCTL, RCTL_EN, true);
        self.flag(RCTL, RCTL_UPE, true);
        // self.flag(RCTL, RCTL_MPE, true);
        self.flag(RCTL, RCTL_LPE, true);
        self.flag(RCTL, RCTL_LBM, false);
        // RCTL.RDMTS = Minimum threshold size ???
        // RCTL.MO = Multicast offset
        self.flag(RCTL, RCTL_BAM, true);
        self.flag(RCTL, RCTL_BSIZE1, true);
        self.flag(RCTL, RCTL_BSIZE2, false);
        self.flag(RCTL, RCTL_BSEX, true);
        self.flag(RCTL, RCTL_SECRC, true);

        debug::d(" RCTL ");
        debug::dh(self.read(RCTL) as usize);

        self.flag(TCTL, TCTL_EN, true);
        self.flag(TCTL, TCTL_PSP, true);
        // TCTL.CT = Collition threshold
        // TCTL.COLD = Collision distance
        // TIPG Packet Gap
        // TODO ...

        debug::d(" TCTL ");
        debug::dh(self.read(TCTL) as usize);

        debug::dl();
    }
}
<|endoftext|>


<commit_before><commit_msg>Player's ATK value is now displayed.<commit_after><|endoftext|>


<commit_before>use std::io::{Read};

use getopts;

use hyper::{Client};
use hyper::status::{StatusCode};

use rustc_serialize::{json};

use super::{CreateServiceResult, Service, ServiceFactory, ServiceResult, User};

#[derive(RustcDecodable)]
struct SlackUserListResponse {
    ok: bool,
    members: Vec<SlackUser>,
}

#[derive(RustcDecodable)]
struct SlackUser {
    name: String,
    deleted: bool,
    is_bot: bool,
    has_2fa: Option<bool>,
    profile: SlackProfile,
    is_owner: Option<bool>,
    is_admin: Option<bool>,
}

#[derive(RustcDecodable)]
struct SlackProfile {
    email: Option<String>,
}

pub struct SlackServiceFactory;

impl ServiceFactory for SlackServiceFactory {
    fn add_options(&self, opts: &mut getopts::Options) {
        opts.optopt(
            "", "slack-token", "Slack token (https://api.slack.com/web#authentication)", "token"
        );
    }

    fn create_service(&self, matches: &getopts::Matches) -> CreateServiceResult {
        match matches.opt_str("slack-token") {
            Some(token) => CreateServiceResult::Service(Box::new(SlackService{
                token: token
            })),
            None => CreateServiceResult::None,
        }
    }
}

struct SlackService {
    token: String,
}

impl Service for SlackService {
    fn get_users(&self) -> ServiceResult {
        let client = Client::new();

        let mut response = client.get(
            &format!("https://slack.com/api/users.list?token={}", self.token)
        ).send().unwrap();
        assert_eq!(response.status, StatusCode::Ok);
        let mut body = String::new();
        response.read_to_string(&mut body).unwrap();

        let result = json::decode::<SlackUserListResponse>(&body).unwrap();
        assert!(result.ok);
        let users = result.members.iter().filter(|user| {
            match (user.deleted, user.is_bot, user.has_2fa) {
                (true, _, _) => false,
                (false, true, _) => false,
                (false, false, None) => true,
                (false, false, Some(true)) => false,
                (false, false, Some(false)) => true,
            }
        }).map(|user|
            User{
                name: user.name.to_string(),
                email: Some(user.profile.email.clone().unwrap()),
                details: match (user.is_owner.unwrap(), user.is_admin.unwrap()) {
                    (true, true) => Some("Owner/Admin".to_string()),
                    (true, false) => Some("Owner".to_string()),
                    (false, true) => Some("Admin".to_string()),
                    (false, false) => None
                }
            }
        ).collect();

        return ServiceResult{
            service_name: "Slack".to_string(),
            users: users,
        }
    }
}
<commit_msg>fix for deleted users<commit_after>use std::io::{Read};

use getopts;

use hyper::{Client};
use hyper::status::{StatusCode};

use rustc_serialize::{json};

use super::{CreateServiceResult, Service, ServiceFactory, ServiceResult, User};

#[derive(RustcDecodable)]
struct SlackUserListResponse {
    ok: bool,
    members: Vec<SlackUser>,
}

#[derive(RustcDecodable)]
struct SlackUser {
    name: String,
    deleted: bool,
    is_bot: Option<bool>,
    has_2fa: Option<bool>,
    profile: SlackProfile,
    is_owner: Option<bool>,
    is_admin: Option<bool>,
}

#[derive(RustcDecodable)]
struct SlackProfile {
    email: Option<String>,
}

pub struct SlackServiceFactory;

impl ServiceFactory for SlackServiceFactory {
    fn add_options(&self, opts: &mut getopts::Options) {
        opts.optopt(
            "", "slack-token", "Slack token (https://api.slack.com/web#authentication)", "token"
        );
    }

    fn create_service(&self, matches: &getopts::Matches) -> CreateServiceResult {
        match matches.opt_str("slack-token") {
            Some(token) => CreateServiceResult::Service(Box::new(SlackService{
                token: token
            })),
            None => CreateServiceResult::None,
        }
    }
}

struct SlackService {
    token: String,
}

impl Service for SlackService {
    fn get_users(&self) -> ServiceResult {
        let client = Client::new();

        let mut response = client.get(
            &format!("https://slack.com/api/users.list?token={}", self.token)
        ).send().unwrap();
        assert_eq!(response.status, StatusCode::Ok);
        let mut body = String::new();
        response.read_to_string(&mut body).unwrap();

        let result = json::decode::<SlackUserListResponse>(&body).unwrap();
        assert!(result.ok);
        let users = result.members.iter().filter(|user| {
            match (user.deleted, user.is_bot, user.has_2fa) {
                (true, _, _) => false,
                (false, Some(true), _) => false,
                (false, _, None) => true,
                (false, _, Some(true)) => false,
                (false, _, Some(false)) => true,
            }
        }).map(|user|
            User{
                name: user.name.to_string(),
                email: Some(user.profile.email.clone().unwrap()),
                details: match (user.is_owner.unwrap(), user.is_admin.unwrap()) {
                    (true, true) => Some("Owner/Admin".to_string()),
                    (true, false) => Some("Owner".to_string()),
                    (false, true) => Some("Admin".to_string()),
                    (false, false) => None
                }
            }
        ).collect();

        return ServiceResult{
            service_name: "Slack".to_string(),
            users: users,
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Minor reformat of entry.value reassignment.<commit_after><|endoftext|>


<commit_before>//! The HTTP request method
use std::fmt;
use std::str::FromStr;

use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch,
                   Extension};

/// The Request Method (VERB)
///
/// Currently includes 8 variants representing the 8 methods defined in
/// [RFC 7230](https://tools.ietf.org/html/rfc7231#section-4.1), plus PATCH,
/// and an Extension variant for all extensions.
///
/// It may make sense to grow this to include all variants currently
/// registered with IANA, if they are at all common to use.
#[deriving(Clone, PartialEq)]
pub enum Method {
    /// OPTIONS
    Options,
    /// GET
    Get,
    /// POST
    Post,
    /// PUT
    Put,
    /// DELETE
    Delete,
    /// HEAD
    Head,
    /// TRACE
    Trace,
    /// CONNECT
    Connect,
    /// PATCH
    Patch,
    /// Method extentions. An example would be `let m = Extension("FOO".to_string())`.
    Extension(String)
}

impl Method {
    /// Whether a method is considered "safe", meaning the request is
    /// essentially read-only.
    ///
    /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.1)
    /// for more words.
    pub fn safe(&self) -> bool {
        match *self {
            Get | Head | Options | Trace => true,
            _ => false
        }
    }

    /// Whether a method is considered "idempotent", meaning the request has
    /// the same result is executed multiple times.
    ///
    /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.2) for
    /// more words.
    pub fn idempotent(&self) -> bool {
        if self.safe() {
            true
        } else {
            match *self {
                Put | Delete => true,
                _ => false
            }
        }
    }
}

impl FromStr for Method {
    fn from_str(s: &str) -> Option<Method> {
        Some(match s {
            "OPTIONS" => Options,
            "GET" => Get,
            "POST" => Post,
            "PUT" => Put,
            "DELETE" => Delete,
            "HEAD" => Head,
            "TRACE" => Trace,
            "CONNECT" => Connect,
            "PATCH" => Patch,
            _ => Extension(s.to_string())
        })
    }
}

impl fmt::Show for Method {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Options => "OPTIONS",
            Get => "GET",
            Post => "POST",
            Put => "PUT",
            Delete => "DELETE",
            Head => "HEAD",
            Trace => "TRACE",
            Connect => "CONNECT",
            Patch => "PATCH",
            Extension(ref s) => s.as_slice()
        }.fmt(fmt)
    }
}
<commit_msg>Allow hyper::method::Method to be put in HashMap<commit_after>//! The HTTP request method
use std::fmt;
use std::str::FromStr;

use self::Method::{Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch,
                   Extension};

/// The Request Method (VERB)
///
/// Currently includes 8 variants representing the 8 methods defined in
/// [RFC 7230](https://tools.ietf.org/html/rfc7231#section-4.1), plus PATCH,
/// and an Extension variant for all extensions.
///
/// It may make sense to grow this to include all variants currently
/// registered with IANA, if they are at all common to use.
#[deriving(Clone, PartialEq, Eq, Hash)]
pub enum Method {
    /// OPTIONS
    Options,
    /// GET
    Get,
    /// POST
    Post,
    /// PUT
    Put,
    /// DELETE
    Delete,
    /// HEAD
    Head,
    /// TRACE
    Trace,
    /// CONNECT
    Connect,
    /// PATCH
    Patch,
    /// Method extentions. An example would be `let m = Extension("FOO".to_string())`.
    Extension(String)
}

impl Method {
    /// Whether a method is considered "safe", meaning the request is
    /// essentially read-only.
    ///
    /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.1)
    /// for more words.
    pub fn safe(&self) -> bool {
        match *self {
            Get | Head | Options | Trace => true,
            _ => false
        }
    }

    /// Whether a method is considered "idempotent", meaning the request has
    /// the same result is executed multiple times.
    ///
    /// See [the spec](https://tools.ietf.org/html/rfc7231#section-4.2.2) for
    /// more words.
    pub fn idempotent(&self) -> bool {
        if self.safe() {
            true
        } else {
            match *self {
                Put | Delete => true,
                _ => false
            }
        }
    }
}

impl FromStr for Method {
    fn from_str(s: &str) -> Option<Method> {
        Some(match s {
            "OPTIONS" => Options,
            "GET" => Get,
            "POST" => Post,
            "PUT" => Put,
            "DELETE" => Delete,
            "HEAD" => Head,
            "TRACE" => Trace,
            "CONNECT" => Connect,
            "PATCH" => Patch,
            _ => Extension(s.to_string())
        })
    }
}

impl fmt::Show for Method {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Options => "OPTIONS",
            Get => "GET",
            Post => "POST",
            Put => "PUT",
            Delete => "DELETE",
            Head => "HEAD",
            Trace => "TRACE",
            Connect => "CONNECT",
            Patch => "PATCH",
            Extension(ref s) => s.as_slice()
        }.fmt(fmt)
    }
}
<|endoftext|>


<commit_before>use std::sys;
use std::libc;
use std::num::{One, Zero};
use std::ptr;
use std::cast;
use std::vec;
use glcore::types::GL_VERSION_1_0::*;
use glcore::types::GL_VERSION_1_5::*;
use glcore::functions::GL_VERSION_1_1::*;
use glcore::functions::GL_VERSION_1_5::*;
use glcore::functions::GL_VERSION_2_0::*;
use glcore::consts::GL_VERSION_1_1::*;
use glcore::consts::GL_VERSION_1_5::*;
use nalgebra::traits::scalar_op::ScalarDiv;
use nalgebra::traits::homogeneous::ToHomogeneous;
use nalgebra::traits::indexable::Indexable;
use nalgebra::traits::cross::Cross;
use nalgebra::traits::norm::Norm;
use nalgebra::adaptors::transform::Transform;
use nalgebra::adaptors::rotmat::Rotmat;
use nalgebra::mat::{Mat3, Mat4};
use nalgebra::vec::Vec3;
use window::Window;

type Transform3d = Transform<Rotmat<Mat3<f64>>, Vec3<f64>>;
type Scale3d     = Mat3<GLfloat>;

pub enum Geometry
{
  VerticesNormalsTriangles(~[Vec3<f32>], ~[Vec3<f32>], ~[(GLuint, GLuint, GLuint)]),
  Deleted
}

#[doc(hidden)]
pub struct GeometryIndices
{
  priv offset:         uint,
  priv size:           i32,
  priv element_buffer: GLuint,
  priv normal_buffer:  GLuint,
  priv vertex_buffer:  GLuint,
  priv texture_buffer: GLuint
}

impl GeometryIndices
{
  #[doc(hidden)]
  pub fn new(offset:         uint,
             size:           i32,
             element_buffer: GLuint,
             normal_buffer:  GLuint,
             vertex_buffer:  GLuint,
             texture_buffer: GLuint) -> GeometryIndices
  {
    GeometryIndices {
      offset:         offset,
      size:           size,
      element_buffer: element_buffer,
      normal_buffer:  normal_buffer,
      vertex_buffer:  vertex_buffer,
      texture_buffer: texture_buffer
    }
  }
}

/// Structure of all 3d objects on the scene. This is the only interface to manipulate the object
/// position, color, vertices and texture.
pub struct Object
{
  priv parent:      @mut Window,
  priv texture:     GLuint,
  priv scale:       Scale3d,
  priv transform:   Transform3d,
  priv color:       Vec3<f32>,
  priv igeometry:   GeometryIndices,
  priv geometry:    Geometry
}

impl Object
{
  #[doc(hidden)]
  pub fn new(parent:      @mut Window,
             igeometry:   GeometryIndices,
             r:           f32,
             g:           f32,
             b:           f32,
             texture:     GLuint,
             sx:          GLfloat,
             sy:          GLfloat,
             sz:          GLfloat,
             geometry:    Geometry) -> Object
  {
    Object {
      parent:    parent,
      scale:     Mat3::new(sx, 0.0, 0.0,
                           0.0, sy, 0.0,
                           0.0, 0.0, sz),
      transform:   One::one(),
      igeometry:   igeometry,
      geometry:    geometry,
      color:       Vec3::new(r, g, b),
      texture:     texture
    }
  }

  #[doc(hidden)]
  pub fn upload_geometry(&mut self)
  {
    match self.geometry
    {
      VerticesNormalsTriangles(ref v, ref n, _) =>
      unsafe {
        glBindBuffer(GL_ARRAY_BUFFER, self.igeometry.vertex_buffer);
        glBufferSubData(GL_ARRAY_BUFFER,
                        0,
                        (v.len() * 3 * sys::size_of::<GLfloat>()) as GLsizeiptr,
                        cast::transmute(&v[0]));

        glBindBuffer(GL_ARRAY_BUFFER, self.igeometry.normal_buffer);
        glBufferSubData(GL_ARRAY_BUFFER,
                        0,
                        (n.len() * 3 * sys::size_of::<GLfloat>()) as GLsizeiptr,
                        cast::transmute(&n[0]));
      },
      Deleted => { }
    }
  }

  #[doc(hidden)]
  pub fn upload(&self,
                pos_attrib:                u32,
                normal_attrib:             u32,
                texture_attrib:            u32,
                color_location:            i32,
                transform_location:        i32,
                scale_location:            i32,
                normal_transform_location: i32)
  {
    let formated_transform:  Mat4<f64> = self.transform.to_homogeneous();
    let formated_ntransform: Mat3<f64> = self.transform.submat().submat();

    // we convert the matrix elements and do the transposition at the same time
    let transform_glf = Mat4::new(
      formated_transform.at((0, 0)) as GLfloat,
      formated_transform.at((1, 0)) as GLfloat,
      formated_transform.at((2, 0)) as GLfloat,
      formated_transform.at((3, 0)) as GLfloat,

      formated_transform.at((0, 1)) as GLfloat,
      formated_transform.at((1, 1)) as GLfloat,
      formated_transform.at((2, 1)) as GLfloat,
      formated_transform.at((3, 1)) as GLfloat,

      formated_transform.at((0, 2)) as GLfloat,
      formated_transform.at((1, 2)) as GLfloat,
      formated_transform.at((2, 2)) as GLfloat,
      formated_transform.at((3, 2)) as GLfloat,

      formated_transform.at((0, 3)) as GLfloat,
      formated_transform.at((1, 3)) as GLfloat,
      formated_transform.at((2, 3)) as GLfloat,
      formated_transform.at((3, 3)) as GLfloat
    );

    let ntransform_glf = Mat3::new(
      formated_ntransform.at((0, 0)) as GLfloat,
      formated_ntransform.at((1, 0)) as GLfloat,
      formated_ntransform.at((2, 0)) as GLfloat,
      formated_ntransform.at((0, 1)) as GLfloat,
      formated_ntransform.at((1, 1)) as GLfloat,
      formated_ntransform.at((2, 1)) as GLfloat,
      formated_ntransform.at((0, 2)) as GLfloat,
      formated_ntransform.at((1, 2)) as GLfloat,
      formated_ntransform.at((2, 2)) as GLfloat
    );

    unsafe {
      glUniformMatrix4fv(transform_location,
                         1,
                         GL_FALSE,
                         cast::transmute(&transform_glf));

      glUniformMatrix3fv(normal_transform_location,
                         1,
                         GL_FALSE,
                         cast::transmute(&ntransform_glf));

      glUniformMatrix3fv(scale_location,
                         1,
                         GL_FALSE,
                         cast::transmute(&self.scale));

      glUniform3f(color_location, self.color.x, self.color.y, self.color.z);

      // FIXME: we should not switch the buffers if the last drawn shape uses the same.
      glBindBuffer(GL_ARRAY_BUFFER, self.igeometry.vertex_buffer);
      glVertexAttribPointer(pos_attrib,
                            3,
                            GL_FLOAT,
                            GL_FALSE,
                            3 * sys::size_of::<GLfloat>() as GLsizei,
                            ptr::null());

      glBindBuffer(GL_ARRAY_BUFFER, self.igeometry.normal_buffer);
      glVertexAttribPointer(normal_attrib,
                            3,
                            GL_FLOAT,
                            GL_FALSE,
                            3 * sys::size_of::<GLfloat>() as GLsizei,
                            ptr::null());

      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.igeometry.element_buffer);

      glBindTexture(GL_TEXTURE_2D, self.texture);

      glBindBuffer(GL_ARRAY_BUFFER, self.igeometry.texture_buffer);
      glVertexAttribPointer(texture_attrib,
                            2,
                            GL_FLOAT,
                            GL_FALSE,
                            2 * sys::size_of::<GLfloat>() as GLsizei,
                            ptr::null());

      glDrawElements(GL_TRIANGLES,
                     self.igeometry.size,
                     GL_UNSIGNED_INT,
                     self.igeometry.offset * sys::size_of::<GLuint>() as *libc::c_void);
    }
  }

  /// The 3d transformation of the object. This is an isometric transformation (i-e no scaling).
  pub fn transformation<'r>(&'r mut self) -> &'r mut Transform3d
  { &mut self.transform }

  /// Applies a user-defined callback on the object geometry. Some geometries might not be
  /// available (because they are only loaded on graphics memory); in this case this is a no-op.
  ///
  /// # Arguments
  ///   * `f` - A user-defined callback called on the object geometry. If it returns `true`, the
  ///   geometry will be updated on graphics memory too. Otherwise, the modification will not have
  ///   any effect on the 3d display.
  pub fn modify_geometry(&mut self,
                         f: &fn(vertices:  &mut ~[Vec3<f32>],
                                normals:   &mut ~[Vec3<f32>],
                                triangles: &mut ~[(GLuint, GLuint, GLuint)]) -> bool)
  {
    if match self.geometry
    {
      VerticesNormalsTriangles(ref mut v, ref mut n, ref mut t) => f(v, n, t),
      Deleted => false
    }
    { self.upload_geometry() }
  }

  /// Applies a user-defined callback on the object vertices. Some geometries might not be
  /// available (because they are only loaded on graphics memory); in this case this is a no-op.
  ///
  /// # Arguments
  ///   * `f` - A user-defined callback called on the object vertice. The normals are automatically
  ///   recomputed. If it returns `true`, the the geometry will be updated on graphics memory too.
  ///   Otherwise, the modifications will not have any effect on the 3d display.
  pub fn modify_vertices(&mut self, f: &fn(&mut ~[Vec3<f32>]) -> bool)
  {
    let (update, normals) = match self.geometry
    {
      VerticesNormalsTriangles(ref mut v, _, _) => (f(v), true),
      Deleted => (false, false)
    };

    if normals
    { self.recompute_normals() }

    if update
    { self.upload_geometry() }
  }

  fn recompute_normals(&mut self)
  {
    match self.geometry
    {
      VerticesNormalsTriangles(ref vs, ref mut ns, ref ts) =>
      {
        let mut divisor = vec::from_elem(vs.len(), 0f32);

        // ... and compute the mean
        for ns.mut_iter().advance |n|
        { *n = Zero::zero() }

        // accumulate normals...
        for ts.iter().advance |&(v1, v2, v3)|
        {
          let edge1 = vs[v2] - vs[v1];
          let edge2 = vs[v3] - vs[v1];
          let normal = edge1.cross(&edge2).normalized();

          ns[v1] = ns[v1] + normal;
          ns[v2] = ns[v2] + normal;
          ns[v3] = ns[v3] + normal;

          divisor[v1] = divisor[v1] + 1.0;
          divisor[v2] = divisor[v2] + 1.0;
          divisor[v3] = divisor[v3] + 1.0;
        }

        // ... and compute the mean
        for ns.mut_iter().zip(divisor.iter()).advance |(n, divisor)|
        { n.scalar_div_inplace(divisor) }
      },
      Deleted => { }
    }
  }

  fn geometry<'r>(&'r self) -> &'r Geometry
  { &'r self.geometry }

  /// Sets the color of the object. Colors components must be on the range `[0.0, 1.0]`.
  pub fn set_color(@mut self, r: f32, g: f32, b: f32) -> @mut Object
  {
    self.color.x = r;
    self.color.y = g;
    self.color.z = b;

    self
  }

  /// Sets the texture of the object.
  ///
  /// # Arguments
  ///   * `path` - relative path of the texture on the disk
  pub fn set_texture(@mut self, path: ~str) -> @mut Object
  {
    self.texture = self.parent.add_texture(path);

    self
  }
}
<commit_msg>Object function  is now public.<commit_after>use std::sys;
use std::libc;
use std::num::{One, Zero};
use std::ptr;
use std::cast;
use std::vec;
use glcore::types::GL_VERSION_1_0::*;
use glcore::types::GL_VERSION_1_5::*;
use glcore::functions::GL_VERSION_1_1::*;
use glcore::functions::GL_VERSION_1_5::*;
use glcore::functions::GL_VERSION_2_0::*;
use glcore::consts::GL_VERSION_1_1::*;
use glcore::consts::GL_VERSION_1_5::*;
use nalgebra::traits::scalar_op::ScalarDiv;
use nalgebra::traits::homogeneous::ToHomogeneous;
use nalgebra::traits::indexable::Indexable;
use nalgebra::traits::cross::Cross;
use nalgebra::traits::norm::Norm;
use nalgebra::adaptors::transform::Transform;
use nalgebra::adaptors::rotmat::Rotmat;
use nalgebra::mat::{Mat3, Mat4};
use nalgebra::vec::Vec3;
use window::Window;

type Transform3d = Transform<Rotmat<Mat3<f64>>, Vec3<f64>>;
type Scale3d     = Mat3<GLfloat>;

pub enum Geometry
{
  VerticesNormalsTriangles(~[Vec3<f32>], ~[Vec3<f32>], ~[(GLuint, GLuint, GLuint)]),
  Deleted
}

#[doc(hidden)]
pub struct GeometryIndices
{
  priv offset:         uint,
  priv size:           i32,
  priv element_buffer: GLuint,
  priv normal_buffer:  GLuint,
  priv vertex_buffer:  GLuint,
  priv texture_buffer: GLuint
}

impl GeometryIndices
{
  #[doc(hidden)]
  pub fn new(offset:         uint,
             size:           i32,
             element_buffer: GLuint,
             normal_buffer:  GLuint,
             vertex_buffer:  GLuint,
             texture_buffer: GLuint) -> GeometryIndices
  {
    GeometryIndices {
      offset:         offset,
      size:           size,
      element_buffer: element_buffer,
      normal_buffer:  normal_buffer,
      vertex_buffer:  vertex_buffer,
      texture_buffer: texture_buffer
    }
  }
}

/// Structure of all 3d objects on the scene. This is the only interface to manipulate the object
/// position, color, vertices and texture.
pub struct Object
{
  priv parent:      @mut Window,
  priv texture:     GLuint,
  priv scale:       Scale3d,
  priv transform:   Transform3d,
  priv color:       Vec3<f32>,
  priv igeometry:   GeometryIndices,
  priv geometry:    Geometry
}

impl Object
{
  #[doc(hidden)]
  pub fn new(parent:      @mut Window,
             igeometry:   GeometryIndices,
             r:           f32,
             g:           f32,
             b:           f32,
             texture:     GLuint,
             sx:          GLfloat,
             sy:          GLfloat,
             sz:          GLfloat,
             geometry:    Geometry) -> Object
  {
    Object {
      parent:    parent,
      scale:     Mat3::new(sx, 0.0, 0.0,
                           0.0, sy, 0.0,
                           0.0, 0.0, sz),
      transform:   One::one(),
      igeometry:   igeometry,
      geometry:    geometry,
      color:       Vec3::new(r, g, b),
      texture:     texture
    }
  }

  #[doc(hidden)]
  pub fn upload_geometry(&mut self)
  {
    match self.geometry
    {
      VerticesNormalsTriangles(ref v, ref n, _) =>
      unsafe {
        glBindBuffer(GL_ARRAY_BUFFER, self.igeometry.vertex_buffer);
        glBufferSubData(GL_ARRAY_BUFFER,
                        0,
                        (v.len() * 3 * sys::size_of::<GLfloat>()) as GLsizeiptr,
                        cast::transmute(&v[0]));

        glBindBuffer(GL_ARRAY_BUFFER, self.igeometry.normal_buffer);
        glBufferSubData(GL_ARRAY_BUFFER,
                        0,
                        (n.len() * 3 * sys::size_of::<GLfloat>()) as GLsizeiptr,
                        cast::transmute(&n[0]));
      },
      Deleted => { }
    }
  }

  #[doc(hidden)]
  pub fn upload(&self,
                pos_attrib:                u32,
                normal_attrib:             u32,
                texture_attrib:            u32,
                color_location:            i32,
                transform_location:        i32,
                scale_location:            i32,
                normal_transform_location: i32)
  {
    let formated_transform:  Mat4<f64> = self.transform.to_homogeneous();
    let formated_ntransform: Mat3<f64> = self.transform.submat().submat();

    // we convert the matrix elements and do the transposition at the same time
    let transform_glf = Mat4::new(
      formated_transform.at((0, 0)) as GLfloat,
      formated_transform.at((1, 0)) as GLfloat,
      formated_transform.at((2, 0)) as GLfloat,
      formated_transform.at((3, 0)) as GLfloat,

      formated_transform.at((0, 1)) as GLfloat,
      formated_transform.at((1, 1)) as GLfloat,
      formated_transform.at((2, 1)) as GLfloat,
      formated_transform.at((3, 1)) as GLfloat,

      formated_transform.at((0, 2)) as GLfloat,
      formated_transform.at((1, 2)) as GLfloat,
      formated_transform.at((2, 2)) as GLfloat,
      formated_transform.at((3, 2)) as GLfloat,

      formated_transform.at((0, 3)) as GLfloat,
      formated_transform.at((1, 3)) as GLfloat,
      formated_transform.at((2, 3)) as GLfloat,
      formated_transform.at((3, 3)) as GLfloat
    );

    let ntransform_glf = Mat3::new(
      formated_ntransform.at((0, 0)) as GLfloat,
      formated_ntransform.at((1, 0)) as GLfloat,
      formated_ntransform.at((2, 0)) as GLfloat,
      formated_ntransform.at((0, 1)) as GLfloat,
      formated_ntransform.at((1, 1)) as GLfloat,
      formated_ntransform.at((2, 1)) as GLfloat,
      formated_ntransform.at((0, 2)) as GLfloat,
      formated_ntransform.at((1, 2)) as GLfloat,
      formated_ntransform.at((2, 2)) as GLfloat
    );

    unsafe {
      glUniformMatrix4fv(transform_location,
                         1,
                         GL_FALSE,
                         cast::transmute(&transform_glf));

      glUniformMatrix3fv(normal_transform_location,
                         1,
                         GL_FALSE,
                         cast::transmute(&ntransform_glf));

      glUniformMatrix3fv(scale_location,
                         1,
                         GL_FALSE,
                         cast::transmute(&self.scale));

      glUniform3f(color_location, self.color.x, self.color.y, self.color.z);

      // FIXME: we should not switch the buffers if the last drawn shape uses the same.
      glBindBuffer(GL_ARRAY_BUFFER, self.igeometry.vertex_buffer);
      glVertexAttribPointer(pos_attrib,
                            3,
                            GL_FLOAT,
                            GL_FALSE,
                            3 * sys::size_of::<GLfloat>() as GLsizei,
                            ptr::null());

      glBindBuffer(GL_ARRAY_BUFFER, self.igeometry.normal_buffer);
      glVertexAttribPointer(normal_attrib,
                            3,
                            GL_FLOAT,
                            GL_FALSE,
                            3 * sys::size_of::<GLfloat>() as GLsizei,
                            ptr::null());

      glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.igeometry.element_buffer);

      glBindTexture(GL_TEXTURE_2D, self.texture);

      glBindBuffer(GL_ARRAY_BUFFER, self.igeometry.texture_buffer);
      glVertexAttribPointer(texture_attrib,
                            2,
                            GL_FLOAT,
                            GL_FALSE,
                            2 * sys::size_of::<GLfloat>() as GLsizei,
                            ptr::null());

      glDrawElements(GL_TRIANGLES,
                     self.igeometry.size,
                     GL_UNSIGNED_INT,
                     self.igeometry.offset * sys::size_of::<GLuint>() as *libc::c_void);
    }
  }

  /// The 3d transformation of the object. This is an isometric transformation (i-e no scaling).
  pub fn transformation<'r>(&'r mut self) -> &'r mut Transform3d
  { &mut self.transform }

  /// The object geometry. Some geometries might not be
  /// available (because they are only loaded on graphics memory); in this case this is a no-op.
  pub fn geometry<'r>(&'r self) -> &'r Geometry
  { &'r self.geometry }

  /// Applies a user-defined callback on the object geometry. Some geometries might not be
  /// available (because they are only loaded on graphics memory); in this case this is a no-op.
  ///
  /// # Arguments
  ///   * `f` - A user-defined callback called on the object geometry. If it returns `true`, the
  ///   geometry will be updated on graphics memory too. Otherwise, the modification will not have
  ///   any effect on the 3d display.
  pub fn modify_geometry(&mut self,
                         f: &fn(vertices:  &mut ~[Vec3<f32>],
                                normals:   &mut ~[Vec3<f32>],
                                triangles: &mut ~[(GLuint, GLuint, GLuint)]) -> bool)
  {
    if match self.geometry
    {
      VerticesNormalsTriangles(ref mut v, ref mut n, ref mut t) => f(v, n, t),
      Deleted => false
    }
    { self.upload_geometry() }
  }

  /// Applies a user-defined callback on the object vertices. Some geometries might not be
  /// available (because they are only loaded on graphics memory); in this case this is a no-op.
  ///
  /// # Arguments
  ///   * `f` - A user-defined callback called on the object vertice. The normals are automatically
  ///   recomputed. If it returns `true`, the the geometry will be updated on graphics memory too.
  ///   Otherwise, the modifications will not have any effect on the 3d display.
  pub fn modify_vertices(&mut self, f: &fn(&mut ~[Vec3<f32>]) -> bool)
  {
    let (update, normals) = match self.geometry
    {
      VerticesNormalsTriangles(ref mut v, _, _) => (f(v), true),
      Deleted => (false, false)
    };

    if normals
    { self.recompute_normals() }

    if update
    { self.upload_geometry() }
  }

  fn recompute_normals(&mut self)
  {
    match self.geometry
    {
      VerticesNormalsTriangles(ref vs, ref mut ns, ref ts) =>
      {
        let mut divisor = vec::from_elem(vs.len(), 0f32);

        // ... and compute the mean
        for ns.mut_iter().advance |n|
        { *n = Zero::zero() }

        // accumulate normals...
        for ts.iter().advance |&(v1, v2, v3)|
        {
          let edge1 = vs[v2] - vs[v1];
          let edge2 = vs[v3] - vs[v1];
          let normal = edge1.cross(&edge2).normalized();

          ns[v1] = ns[v1] + normal;
          ns[v2] = ns[v2] + normal;
          ns[v3] = ns[v3] + normal;

          divisor[v1] = divisor[v1] + 1.0;
          divisor[v2] = divisor[v2] + 1.0;
          divisor[v3] = divisor[v3] + 1.0;
        }

        // ... and compute the mean
        for ns.mut_iter().zip(divisor.iter()).advance |(n, divisor)|
        { n.scalar_div_inplace(divisor) }
      },
      Deleted => { }
    }
  }

  /// Sets the color of the object. Colors components must be on the range `[0.0, 1.0]`.
  pub fn set_color(@mut self, r: f32, g: f32, b: f32) -> @mut Object
  {
    self.color.x = r;
    self.color.y = g;
    self.color.z = b;

    self
  }

  /// Sets the texture of the object.
  ///
  /// # Arguments
  ///   * `path` - relative path of the texture on the disk
  pub fn set_texture(@mut self, path: ~str) -> @mut Object
  {
    self.texture = self.parent.add_texture(path);

    self
  }
}
<|endoftext|>


<commit_before>use std::io::net::ip::{SocketAddr, Ipv4Addr, Port};
use std::collections::hashmap::HashMap;

use http;
use http::server::request::{AbsolutePath};
use http::server::{Config, Server, Request, ResponseWriter};

use router::Router;
use middleware::Middleware;
use request;
use response;

#[deriving(Clone)]
pub struct Server {
    router: Router,
    middleware: Middleware,
    port: Port
}

impl http::server::Server for Server {
    fn get_config(&self) -> Config {
        Config { bind_address: SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: self.port } }
    }

    fn handle_request(&self, req: &Request, res: &mut ResponseWriter) {

        let floor_req = &mut request::Request{
            origin: req,
            params: HashMap::new()
        };

        let floor_res = &mut response::Response{
            origin: res
        };

        self.middleware.invoke(floor_req, floor_res);

        match &req.request_uri {
            &AbsolutePath(ref url) => {
                match self.router.match_route(req.method.clone(), url.clone()) {
                    Some(route_result) => {
                        floor_req.params = route_result.params.clone();
                        (route_result.route.handler)(floor_req, floor_res);
                    },
                    None => {}
                }
            },
            // TODO: Return 404
            _ => {}
        }
    }
}

impl Server {
    pub fn new(router: Router, middleware: Middleware, port: Port) -> Server {
        Server {
            router: router,
            middleware: middleware,
            port: port
        }
    }

    // why do we need this? Is the http::Server.serve_forever method protected in C# terms?
    pub fn serve (self) {
        self.serve_forever();
    }
}
<commit_msg>fix(server): adjust to upstream changes<commit_after>use std::io::net::ip::{SocketAddr, Ipv4Addr, Port};
use std::collections::hashmap::HashMap;

use http;
use http::server::request::{AbsolutePath};
use http::server::{Config, Server, Request, ResponseWriter};

use router::Router;
use middleware::Middleware;
use request;
use response;

#[deriving(Clone)]
pub struct Server {
    router: Router,
    middleware: Middleware,
    port: Port
}

impl http::server::Server for Server {
    fn get_config(&self) -> Config {
        Config { bind_address: SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: self.port } }
    }

    fn handle_request(&self, req: Request, res: &mut ResponseWriter) {

        let floor_req = &mut request::Request{
            origin: &req,
            params: HashMap::new()
        };

        let floor_res = &mut response::Response{
            origin: res
        };

        self.middleware.invoke(floor_req, floor_res);

        match &req.request_uri {
            &AbsolutePath(ref url) => {
                match self.router.match_route(req.method.clone(), url.clone()) {
                    Some(route_result) => {
                        floor_req.params = route_result.params.clone();
                        (route_result.route.handler)(floor_req, floor_res);
                    },
                    None => {}
                }
            },
            // TODO: Return 404
            _ => {}
        }
    }
}

impl Server {
    pub fn new(router: Router, middleware: Middleware, port: Port) -> Server {
        Server {
            router: router,
            middleware: middleware,
            port: port
        }
    }

    // why do we need this? Is the http::Server.serve_forever method protected in C# terms?
    pub fn serve (self) {
        self.serve_forever();
    }
}
<|endoftext|>


<commit_before><commit_msg>Add DepMethod to make DepFn::call more convenient<commit_after><|endoftext|>


<commit_before><commit_msg>Adjust small timer interval again<commit_after><|endoftext|>


<commit_before><commit_msg>video.restore method<commit_after><|endoftext|>


<commit_before><commit_msg>work work work<commit_after><|endoftext|>


<commit_before><commit_msg>Made the object's bounds a public field<commit_after><|endoftext|>


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

//! A structure for holding a set of enum variants.
//!
//! This module defines a container which uses an efficient bit mask
//! representation to hold C-like enum variants.

use core::prelude::*;
use core::fmt;

// FIXME(contentions): implement union family of methods? (general design may be wrong here)
// FIXME(conventions): implement len

#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A specialized `Set` implementation to use enum types.
pub struct EnumSet<E> {
    // We must maintain the invariant that no bits are set
    // for which no variant exists
    bits: uint
}

impl<E:CLike+fmt::Show> fmt::Show for EnumSet<E> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(fmt, "{{"));
        let mut first = true;
        for e in self.iter() {
            if !first {
                try!(write!(fmt, ", "));
            }
            try!(write!(fmt, "{}", e));
            first = false;
        }
        write!(fmt, "}}")
    }
}

/**
An interface for casting C-like enum to uint and back.
A typically implementation is as below.

```{rust,ignore}
#[repr(uint)]
enum Foo {
    A, B, C
}

impl CLike for Foo {
    fn to_uint(&self) -> uint {
        *self as uint
    }

    fn from_uint(v: uint) -> Foo {
        unsafe { mem::transmute(v) }
    }
}
```
*/
pub trait CLike {
    /// Converts a C-like enum to a `uint`.
    fn to_uint(&self) -> uint;
    /// Converts a `uint` to a C-like enum.
    fn from_uint(uint) -> Self;
}

fn bit<E:CLike>(e: &E) -> uint {
    use core::uint;
    let value = e.to_uint();
    assert!(value < uint::BITS,
            "EnumSet only supports up to {} variants.", uint::BITS - 1);
    1 << value
}

impl<E:CLike> EnumSet<E> {
    /// Deprecated: Renamed to `new`.
    #[deprecated = "Renamed to `new`"]
    pub fn empty() -> EnumSet<E> {
        EnumSet::new()
    }

    /// Returns an empty `EnumSet`.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn new() -> EnumSet<E> {
        EnumSet {bits: 0}
    }

    /// Returns true if the `EnumSet` is empty.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn is_empty(&self) -> bool {
        self.bits == 0
    }

    pub fn clear(&mut self) {
        self.bits = 0;
    }

    /// Returns `true` if the `EnumSet` contains any enum of the given `EnumSet`.
    /// Deprecated: Use `is_disjoint`.
    #[deprecated = "Use `is_disjoint`"]
    pub fn intersects(&self, e: EnumSet<E>) -> bool {
        !self.is_disjoint(&e)
    }

    /// Returns `false` if the `EnumSet` contains any enum of the given `EnumSet`.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn is_disjoint(&self, other: &EnumSet<E>) -> bool {
        (self.bits & other.bits) == 0
    }

    /// Returns `true` if a given `EnumSet` is included in this `EnumSet`.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn is_superset(&self, other: &EnumSet<E>) -> bool {
        (self.bits & other.bits) == other.bits
    }

    /// Returns `true` if this `EnumSet` is included in the given `EnumSet`.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn is_subset(&self, other: &EnumSet<E>) -> bool {
        other.is_superset(self)
    }

    /// Returns the union of both `EnumSets`.
    pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits | e.bits}
    }

    /// Returns the intersection of both `EnumSets`.
    pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & e.bits}
    }

    /// Deprecated: Use `insert`.
    #[deprecated = "Use `insert`"]
    pub fn add(&mut self, e: E) {
        self.insert(e);
    }

    /// Adds an enum to the `EnumSet`, and returns `true` if it wasn't there before
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn insert(&mut self, e: E) -> bool {
        let result = !self.contains(&e);
        self.bits |= bit(&e);
        result
    }

    /// Removes an enum from the EnumSet
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn remove(&mut self, e: &E) -> bool {
        let result = self.contains(e);
        self.bits &= !bit(e);
        result
    }

    /// Deprecated: use `contains`.
    #[deprecated = "use `contains"]
    pub fn contains_elem(&self, e: E) -> bool {
        self.contains(&e)
    }

    /// Returns `true` if an `EnumSet` contains a given enum.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn contains(&self, e: &E) -> bool {
        (self.bits & bit(e)) != 0
    }

    /// Returns an iterator over an `EnumSet`.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn iter(&self) -> Items<E> {
        Items::new(self.bits)
    }
}

impl<E:CLike> Sub<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn sub(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & !e.bits}
    }
}

impl<E:CLike> BitOr<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn bitor(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits | e.bits}
    }
}

impl<E:CLike> BitAnd<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn bitand(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & e.bits}
    }
}

impl<E:CLike> BitXor<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn bitxor(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits ^ e.bits}
    }
}

/// An iterator over an EnumSet
pub struct Items<E> {
    index: uint,
    bits: uint,
}

impl<E:CLike> Items<E> {
    fn new(bits: uint) -> Items<E> {
        Items { index: 0, bits: bits }
    }
}

impl<E:CLike> Iterator<E> for Items<E> {
    fn next(&mut self) -> Option<E> {
        if self.bits == 0 {
            return None;
        }

        while (self.bits & 1) == 0 {
            self.index += 1;
            self.bits >>= 1;
        }
        let elem = CLike::from_uint(self.index);
        self.index += 1;
        self.bits >>= 1;
        Some(elem)
    }

    fn size_hint(&self) -> (uint, Option<uint>) {
        let exact = self.bits.count_ones();
        (exact, Some(exact))
    }
}

#[cfg(test)]
mod test {
    use std::prelude::*;
    use std::mem;

    use super::{EnumSet, CLike};

    #[deriving(PartialEq, Show)]
    #[repr(uint)]
    enum Foo {
        A, B, C
    }

    impl CLike for Foo {
        fn to_uint(&self) -> uint {
            *self as uint
        }

        fn from_uint(v: uint) -> Foo {
            unsafe { mem::transmute(v) }
        }
    }

    #[test]
    fn test_new() {
        let e: EnumSet<Foo> = EnumSet::new();
        assert!(e.is_empty());
    }

    #[test]
    fn test_show() {
        let mut e = EnumSet::new();
        assert_eq!("{}", e.to_string().as_slice());
        e.insert(A);
        assert_eq!("{A}", e.to_string().as_slice());
        e.insert(C);
        assert_eq!("{A, C}", e.to_string().as_slice());
    }

    ///////////////////////////////////////////////////////////////////////////
    // intersect

    #[test]
    fn test_two_empties_do_not_intersect() {
        let e1: EnumSet<Foo> = EnumSet::new();
        let e2: EnumSet<Foo> = EnumSet::new();
        assert!(e1.is_disjoint(&e2));
    }

    #[test]
    fn test_empty_does_not_intersect_with_full() {
        let e1: EnumSet<Foo> = EnumSet::new();

        let mut e2: EnumSet<Foo> = EnumSet::new();
        e2.insert(A);
        e2.insert(B);
        e2.insert(C);

        assert!(e1.is_disjoint(&e2));
    }

    #[test]
    fn test_disjoint_intersects() {
        let mut e1: EnumSet<Foo> = EnumSet::new();
        e1.insert(A);

        let mut e2: EnumSet<Foo> = EnumSet::new();
        e2.insert(B);

        assert!(e1.is_disjoint(&e2));
    }

    #[test]
    fn test_overlapping_intersects() {
        let mut e1: EnumSet<Foo> = EnumSet::new();
        e1.insert(A);

        let mut e2: EnumSet<Foo> = EnumSet::new();
        e2.insert(A);
        e2.insert(B);

        assert!(!e1.is_disjoint(&e2));
    }

    ///////////////////////////////////////////////////////////////////////////
    // contains and contains_elem

    #[test]
    fn test_superset() {
        let mut e1: EnumSet<Foo> = EnumSet::new();
        e1.insert(A);

        let mut e2: EnumSet<Foo> = EnumSet::new();
        e2.insert(A);
        e2.insert(B);

        let mut e3: EnumSet<Foo> = EnumSet::new();
        e3.insert(C);

        assert!(e1.is_subset(&e2));
        assert!(e2.is_superset(&e1));
        assert!(!e3.is_superset(&e2))
        assert!(!e2.is_superset(&e3))
    }

    #[test]
    fn test_contains() {
        let mut e1: EnumSet<Foo> = EnumSet::new();
        e1.insert(A);
        assert!(e1.contains(&A));
        assert!(!e1.contains(&B));
        assert!(!e1.contains(&C));

        e1.insert(A);
        e1.insert(B);
        assert!(e1.contains(&A));
        assert!(e1.contains(&B));
        assert!(!e1.contains(&C));
    }

    ///////////////////////////////////////////////////////////////////////////
    // iter

    #[test]
    fn test_iterator() {
        let mut e1: EnumSet<Foo> = EnumSet::new();

        let elems: Vec<Foo> = e1.iter().collect();
        assert!(elems.is_empty())

        e1.insert(A);
        let elems = e1.iter().collect();
        assert_eq!(vec![A], elems)

        e1.insert(C);
        let elems = e1.iter().collect();
        assert_eq!(vec![A,C], elems)

        e1.insert(C);
        let elems = e1.iter().collect();
        assert_eq!(vec![A,C], elems)

        e1.insert(B);
        let elems = e1.iter().collect();
        assert_eq!(vec![A,B,C], elems)
    }

    ///////////////////////////////////////////////////////////////////////////
    // operators

    #[test]
    fn test_operators() {
        let mut e1: EnumSet<Foo> = EnumSet::new();
        e1.insert(A);
        e1.insert(C);

        let mut e2: EnumSet<Foo> = EnumSet::new();
        e2.insert(B);
        e2.insert(C);

        let e_union = e1 | e2;
        let elems = e_union.iter().collect();
        assert_eq!(vec![A,B,C], elems)

        let e_intersection = e1 & e2;
        let elems = e_intersection.iter().collect();
        assert_eq!(vec![C], elems)

        let e_subtract = e1 - e2;
        let elems = e_subtract.iter().collect();
        assert_eq!(vec![A], elems)
    }

    #[test]
    #[should_fail]
    fn test_overflow() {
        #[allow(dead_code)]
        #[repr(uint)]
        enum Bar {
            V00, V01, V02, V03, V04, V05, V06, V07, V08, V09,
            V10, V11, V12, V13, V14, V15, V16, V17, V18, V19,
            V20, V21, V22, V23, V24, V25, V26, V27, V28, V29,
            V30, V31, V32, V33, V34, V35, V36, V37, V38, V39,
            V40, V41, V42, V43, V44, V45, V46, V47, V48, V49,
            V50, V51, V52, V53, V54, V55, V56, V57, V58, V59,
            V60, V61, V62, V63, V64, V65, V66, V67, V68, V69,
        }
        impl CLike for Bar {
            fn to_uint(&self) -> uint {
                *self as uint
            }

            fn from_uint(v: uint) -> Bar {
                unsafe { mem::transmute(v) }
            }
        }
        let mut set = EnumSet::empty();
        set.add(V64);
    }
}
<commit_msg>Add tests for BitAnd and BitXor.<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.

//! A structure for holding a set of enum variants.
//!
//! This module defines a container which uses an efficient bit mask
//! representation to hold C-like enum variants.

use core::prelude::*;
use core::fmt;

// FIXME(contentions): implement union family of methods? (general design may be wrong here)
// FIXME(conventions): implement len

#[deriving(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A specialized `Set` implementation to use enum types.
pub struct EnumSet<E> {
    // We must maintain the invariant that no bits are set
    // for which no variant exists
    bits: uint
}

impl<E:CLike+fmt::Show> fmt::Show for EnumSet<E> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        try!(write!(fmt, "{{"));
        let mut first = true;
        for e in self.iter() {
            if !first {
                try!(write!(fmt, ", "));
            }
            try!(write!(fmt, "{}", e));
            first = false;
        }
        write!(fmt, "}}")
    }
}

/**
An interface for casting C-like enum to uint and back.
A typically implementation is as below.

```{rust,ignore}
#[repr(uint)]
enum Foo {
    A, B, C
}

impl CLike for Foo {
    fn to_uint(&self) -> uint {
        *self as uint
    }

    fn from_uint(v: uint) -> Foo {
        unsafe { mem::transmute(v) }
    }
}
```
*/
pub trait CLike {
    /// Converts a C-like enum to a `uint`.
    fn to_uint(&self) -> uint;
    /// Converts a `uint` to a C-like enum.
    fn from_uint(uint) -> Self;
}

fn bit<E:CLike>(e: &E) -> uint {
    use core::uint;
    let value = e.to_uint();
    assert!(value < uint::BITS,
            "EnumSet only supports up to {} variants.", uint::BITS - 1);
    1 << value
}

impl<E:CLike> EnumSet<E> {
    /// Deprecated: Renamed to `new`.
    #[deprecated = "Renamed to `new`"]
    pub fn empty() -> EnumSet<E> {
        EnumSet::new()
    }

    /// Returns an empty `EnumSet`.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn new() -> EnumSet<E> {
        EnumSet {bits: 0}
    }

    /// Returns true if the `EnumSet` is empty.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn is_empty(&self) -> bool {
        self.bits == 0
    }

    pub fn clear(&mut self) {
        self.bits = 0;
    }

    /// Returns `true` if the `EnumSet` contains any enum of the given `EnumSet`.
    /// Deprecated: Use `is_disjoint`.
    #[deprecated = "Use `is_disjoint`"]
    pub fn intersects(&self, e: EnumSet<E>) -> bool {
        !self.is_disjoint(&e)
    }

    /// Returns `false` if the `EnumSet` contains any enum of the given `EnumSet`.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn is_disjoint(&self, other: &EnumSet<E>) -> bool {
        (self.bits & other.bits) == 0
    }

    /// Returns `true` if a given `EnumSet` is included in this `EnumSet`.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn is_superset(&self, other: &EnumSet<E>) -> bool {
        (self.bits & other.bits) == other.bits
    }

    /// Returns `true` if this `EnumSet` is included in the given `EnumSet`.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn is_subset(&self, other: &EnumSet<E>) -> bool {
        other.is_superset(self)
    }

    /// Returns the union of both `EnumSets`.
    pub fn union(&self, e: EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits | e.bits}
    }

    /// Returns the intersection of both `EnumSets`.
    pub fn intersection(&self, e: EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & e.bits}
    }

    /// Deprecated: Use `insert`.
    #[deprecated = "Use `insert`"]
    pub fn add(&mut self, e: E) {
        self.insert(e);
    }

    /// Adds an enum to the `EnumSet`, and returns `true` if it wasn't there before
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn insert(&mut self, e: E) -> bool {
        let result = !self.contains(&e);
        self.bits |= bit(&e);
        result
    }

    /// Removes an enum from the EnumSet
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn remove(&mut self, e: &E) -> bool {
        let result = self.contains(e);
        self.bits &= !bit(e);
        result
    }

    /// Deprecated: use `contains`.
    #[deprecated = "use `contains"]
    pub fn contains_elem(&self, e: E) -> bool {
        self.contains(&e)
    }

    /// Returns `true` if an `EnumSet` contains a given enum.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn contains(&self, e: &E) -> bool {
        (self.bits & bit(e)) != 0
    }

    /// Returns an iterator over an `EnumSet`.
    #[unstable = "matches collection reform specification, waiting for dust to settle"]
    pub fn iter(&self) -> Items<E> {
        Items::new(self.bits)
    }
}

impl<E:CLike> Sub<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn sub(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & !e.bits}
    }
}

impl<E:CLike> BitOr<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn bitor(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits | e.bits}
    }
}

impl<E:CLike> BitAnd<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn bitand(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits & e.bits}
    }
}

impl<E:CLike> BitXor<EnumSet<E>, EnumSet<E>> for EnumSet<E> {
    fn bitxor(&self, e: &EnumSet<E>) -> EnumSet<E> {
        EnumSet {bits: self.bits ^ e.bits}
    }
}

/// An iterator over an EnumSet
pub struct Items<E> {
    index: uint,
    bits: uint,
}

impl<E:CLike> Items<E> {
    fn new(bits: uint) -> Items<E> {
        Items { index: 0, bits: bits }
    }
}

impl<E:CLike> Iterator<E> for Items<E> {
    fn next(&mut self) -> Option<E> {
        if self.bits == 0 {
            return None;
        }

        while (self.bits & 1) == 0 {
            self.index += 1;
            self.bits >>= 1;
        }
        let elem = CLike::from_uint(self.index);
        self.index += 1;
        self.bits >>= 1;
        Some(elem)
    }

    fn size_hint(&self) -> (uint, Option<uint>) {
        let exact = self.bits.count_ones();
        (exact, Some(exact))
    }
}

#[cfg(test)]
mod test {
    use std::prelude::*;
    use std::mem;

    use super::{EnumSet, CLike};

    #[deriving(PartialEq, Show)]
    #[repr(uint)]
    enum Foo {
        A, B, C
    }

    impl CLike for Foo {
        fn to_uint(&self) -> uint {
            *self as uint
        }

        fn from_uint(v: uint) -> Foo {
            unsafe { mem::transmute(v) }
        }
    }

    #[test]
    fn test_new() {
        let e: EnumSet<Foo> = EnumSet::new();
        assert!(e.is_empty());
    }

    #[test]
    fn test_show() {
        let mut e = EnumSet::new();
        assert_eq!("{}", e.to_string().as_slice());
        e.insert(A);
        assert_eq!("{A}", e.to_string().as_slice());
        e.insert(C);
        assert_eq!("{A, C}", e.to_string().as_slice());
    }

    ///////////////////////////////////////////////////////////////////////////
    // intersect

    #[test]
    fn test_two_empties_do_not_intersect() {
        let e1: EnumSet<Foo> = EnumSet::new();
        let e2: EnumSet<Foo> = EnumSet::new();
        assert!(e1.is_disjoint(&e2));
    }

    #[test]
    fn test_empty_does_not_intersect_with_full() {
        let e1: EnumSet<Foo> = EnumSet::new();

        let mut e2: EnumSet<Foo> = EnumSet::new();
        e2.insert(A);
        e2.insert(B);
        e2.insert(C);

        assert!(e1.is_disjoint(&e2));
    }

    #[test]
    fn test_disjoint_intersects() {
        let mut e1: EnumSet<Foo> = EnumSet::new();
        e1.insert(A);

        let mut e2: EnumSet<Foo> = EnumSet::new();
        e2.insert(B);

        assert!(e1.is_disjoint(&e2));
    }

    #[test]
    fn test_overlapping_intersects() {
        let mut e1: EnumSet<Foo> = EnumSet::new();
        e1.insert(A);

        let mut e2: EnumSet<Foo> = EnumSet::new();
        e2.insert(A);
        e2.insert(B);

        assert!(!e1.is_disjoint(&e2));
    }

    ///////////////////////////////////////////////////////////////////////////
    // contains and contains_elem

    #[test]
    fn test_superset() {
        let mut e1: EnumSet<Foo> = EnumSet::new();
        e1.insert(A);

        let mut e2: EnumSet<Foo> = EnumSet::new();
        e2.insert(A);
        e2.insert(B);

        let mut e3: EnumSet<Foo> = EnumSet::new();
        e3.insert(C);

        assert!(e1.is_subset(&e2));
        assert!(e2.is_superset(&e1));
        assert!(!e3.is_superset(&e2))
        assert!(!e2.is_superset(&e3))
    }

    #[test]
    fn test_contains() {
        let mut e1: EnumSet<Foo> = EnumSet::new();
        e1.insert(A);
        assert!(e1.contains(&A));
        assert!(!e1.contains(&B));
        assert!(!e1.contains(&C));

        e1.insert(A);
        e1.insert(B);
        assert!(e1.contains(&A));
        assert!(e1.contains(&B));
        assert!(!e1.contains(&C));
    }

    ///////////////////////////////////////////////////////////////////////////
    // iter

    #[test]
    fn test_iterator() {
        let mut e1: EnumSet<Foo> = EnumSet::new();

        let elems: Vec<Foo> = e1.iter().collect();
        assert!(elems.is_empty())

        e1.insert(A);
        let elems = e1.iter().collect();
        assert_eq!(vec![A], elems)

        e1.insert(C);
        let elems = e1.iter().collect();
        assert_eq!(vec![A,C], elems)

        e1.insert(C);
        let elems = e1.iter().collect();
        assert_eq!(vec![A,C], elems)

        e1.insert(B);
        let elems = e1.iter().collect();
        assert_eq!(vec![A,B,C], elems)
    }

    ///////////////////////////////////////////////////////////////////////////
    // operators

    #[test]
    fn test_operators() {
        let mut e1: EnumSet<Foo> = EnumSet::new();
        e1.insert(A);
        e1.insert(C);

        let mut e2: EnumSet<Foo> = EnumSet::new();
        e2.insert(B);
        e2.insert(C);

        let e_union = e1 | e2;
        let elems = e_union.iter().collect();
        assert_eq!(vec![A,B,C], elems)

        let e_intersection = e1 & e2;
        let elems = e_intersection.iter().collect();
        assert_eq!(vec![C], elems)

        // Another way to express intersection
        let e_intersection = e1 - (e1 - e2);
        let elems = e_intersection.iter().collect();
        assert_eq!(vec![C], elems)

        let e_subtract = e1 - e2;
        let elems = e_subtract.iter().collect();
        assert_eq!(vec![A], elems)

        // Bitwise XOR of two sets, aka symmetric difference
        let e_symmetric_diff = e1 ^ e2;
        let elems = e_symmetric_diff.iter().collect();
        assert_eq!(vec![A,B], elems)

        // Another way to express symmetric difference
        let e_symmetric_diff = (e1 - e2) | (e2 - e1);
        let elems = e_symmetric_diff.iter().collect();
        assert_eq!(vec![A,B], elems)

        // Yet another way to express symmetric difference
        let e_symmetric_diff = (e1 | e2) - (e1 & e2);
        let elems = e_symmetric_diff.iter().collect();
        assert_eq!(vec![A,B], elems)
    }

    #[test]
    #[should_fail]
    fn test_overflow() {
        #[allow(dead_code)]
        #[repr(uint)]
        enum Bar {
            V00, V01, V02, V03, V04, V05, V06, V07, V08, V09,
            V10, V11, V12, V13, V14, V15, V16, V17, V18, V19,
            V20, V21, V22, V23, V24, V25, V26, V27, V28, V29,
            V30, V31, V32, V33, V34, V35, V36, V37, V38, V39,
            V40, V41, V42, V43, V44, V45, V46, V47, V48, V49,
            V50, V51, V52, V53, V54, V55, V56, V57, V58, V59,
            V60, V61, V62, V63, V64, V65, V66, V67, V68, V69,
        }
        impl CLike for Bar {
            fn to_uint(&self) -> uint {
                *self as uint
            }

            fn from_uint(v: uint) -> Bar {
                unsafe { mem::transmute(v) }
            }
        }
        let mut set = EnumSet::empty();
        set.add(V64);
    }
}
<|endoftext|>


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

use schema::*;

use rustc::hir::def_id::{DefId, DefIndex};
use std::io::{Cursor, Write};
use std::slice;
use std::u32;

/// While we are generating the metadata, we also track the position
/// of each DefIndex. It is not required that all definitions appear
/// in the metadata, nor that they are serialized in order, and
/// therefore we first allocate the vector here and fill it with
/// `u32::MAX`. Whenever an index is visited, we fill in the
/// appropriate spot by calling `record_position`. We should never
/// visit the same index twice.
pub struct Index {
    positions: Vec<u32>,
}

impl Index {
    pub fn new(max_index: usize) -> Index {
        Index { positions: vec![u32::MAX; max_index] }
    }

    pub fn record(&mut self, def_id: DefId, entry: Lazy<Entry>) {
        assert!(def_id.is_local());
        self.record_index(def_id.index, entry);
    }

    pub fn record_index(&mut self, item: DefIndex, entry: Lazy<Entry>) {
        let item = item.as_usize();

        assert!(entry.position < (u32::MAX as usize));
        let position = entry.position as u32;

        assert!(self.positions[item] == u32::MAX,
                "recorded position for item {:?} twice, first at {:?} and now at {:?}",
                item,
                self.positions[item],
                position);

        self.positions[item] = position.to_le();
    }

    pub fn write_index(&self, buf: &mut Cursor<Vec<u8>>) -> LazySeq<Index> {
        let pos = buf.position();
        buf.write_all(words_to_bytes(&self.positions)).unwrap();
        LazySeq::with_position_and_length(pos as usize, self.positions.len())
    }
}

impl<'tcx> LazySeq<Index> {
    /// Given the metadata, extract out the offset of a particular
    /// DefIndex (if any).
    #[inline(never)]
    pub fn lookup(&self, bytes: &[u8], def_index: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
        let words = &bytes_to_words(&bytes[self.position..])[..self.len];
        let index = def_index.as_usize();

        debug!("Index::lookup: index={:?} words.len={:?}",
               index,
               words.len());

        let position = u32::from_le(words[index]);
        if position == u32::MAX {
            debug!("Index::lookup: position=u32::MAX");
            None
        } else {
            debug!("Index::lookup: position={:?}", position);
            Some(Lazy::with_position(position as usize))
        }
    }

    pub fn iter_enumerated<'a>(&self,
                               bytes: &'a [u8])
                               -> impl Iterator<Item = (DefIndex, Lazy<Entry<'tcx>>)> + 'a {
        let words = &bytes_to_words(&bytes[self.position..])[..self.len];
        words.iter().enumerate().filter_map(|(index, &position)| {
            if position == u32::MAX {
                None
            } else {
                let position = u32::from_le(position) as usize;
                Some((DefIndex::new(index), Lazy::with_position(position)))
            }
        })
    }
}

fn bytes_to_words(b: &[u8]) -> &[u32] {
    unsafe { slice::from_raw_parts(b.as_ptr() as *const u32, b.len() / 4) }
}

fn words_to_bytes(w: &[u32]) -> &[u8] {
    unsafe { slice::from_raw_parts(w.as_ptr() as *const u8, w.len() * 4) }
}
<commit_msg>rustc_metadata: Fix unaligned loads<commit_after>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use schema::*;

use rustc::hir::def_id::{DefId, DefIndex};
use std::io::{Cursor, Write};
use std::slice;
use std::u32;

/// While we are generating the metadata, we also track the position
/// of each DefIndex. It is not required that all definitions appear
/// in the metadata, nor that they are serialized in order, and
/// therefore we first allocate the vector here and fill it with
/// `u32::MAX`. Whenever an index is visited, we fill in the
/// appropriate spot by calling `record_position`. We should never
/// visit the same index twice.
pub struct Index {
    positions: Vec<u32>,
}

impl Index {
    pub fn new(max_index: usize) -> Index {
        Index { positions: vec![u32::MAX; max_index] }
    }

    pub fn record(&mut self, def_id: DefId, entry: Lazy<Entry>) {
        assert!(def_id.is_local());
        self.record_index(def_id.index, entry);
    }

    pub fn record_index(&mut self, item: DefIndex, entry: Lazy<Entry>) {
        let item = item.as_usize();

        assert!(entry.position < (u32::MAX as usize));
        let position = entry.position as u32;

        assert!(self.positions[item] == u32::MAX,
                "recorded position for item {:?} twice, first at {:?} and now at {:?}",
                item,
                self.positions[item],
                position);

        self.positions[item] = position.to_le();
    }

    pub fn write_index(&self, buf: &mut Cursor<Vec<u8>>) -> LazySeq<Index> {
        let pos = buf.position();
        buf.write_all(words_to_bytes(&self.positions)).unwrap();
        LazySeq::with_position_and_length(pos as usize, self.positions.len())
    }
}

impl<'tcx> LazySeq<Index> {
    /// Given the metadata, extract out the offset of a particular
    /// DefIndex (if any).
    #[inline(never)]
    pub fn lookup(&self, bytes: &[u8], def_index: DefIndex) -> Option<Lazy<Entry<'tcx>>> {
        let words = &bytes_to_words(&bytes[self.position..])[..self.len];
        let index = def_index.as_usize();

        debug!("Index::lookup: index={:?} words.len={:?}",
               index,
               words.len());

        let position = u32::from_le(words[index].get());
        if position == u32::MAX {
            debug!("Index::lookup: position=u32::MAX");
            None
        } else {
            debug!("Index::lookup: position={:?}", position);
            Some(Lazy::with_position(position as usize))
        }
    }

    pub fn iter_enumerated<'a>(&self,
                               bytes: &'a [u8])
                               -> impl Iterator<Item = (DefIndex, Lazy<Entry<'tcx>>)> + 'a {
        let words = &bytes_to_words(&bytes[self.position..])[..self.len];
        words.iter().map(|word| word.get()).enumerate().filter_map(|(index, position)| {
            if position == u32::MAX {
                None
            } else {
                let position = u32::from_le(position) as usize;
                Some((DefIndex::new(index), Lazy::with_position(position)))
            }
        })
    }
}

#[repr(packed)]
#[derive(Copy, Clone)]
struct Unaligned<T>(T);

impl<T> Unaligned<T> {
    fn get(self) -> T { self.0 }
}

fn bytes_to_words(b: &[u8]) -> &[Unaligned<u32>] {
    unsafe { slice::from_raw_parts(b.as_ptr() as *const Unaligned<u32>, b.len() / 4) }
}

fn words_to_bytes(w: &[u32]) -> &[u8] {
    unsafe { slice::from_raw_parts(w.as_ptr() as *const u8, w.len() * 4) }
}
<|endoftext|>


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

// xfail-fast
// compile-flags:--cfg ndebug
// exec-env:RUST_LOG=logging-enabled-debug=debug

use std::logging;

fn main() {
    if log_enabled!(logging::DEBUG) {
        fail!("what?! debugging?");
    }
}
<|endoftext|>


<commit_before><commit_msg>Problem 0 - Joiner.rs<commit_after>use std::rand::random;
use std::os;
use std::io::File;

fn main() {
    let args: ~[~str] = os::args();
    if args.len() != 3 {
        println!("Usage: {:s} <inputfile1> <inputfile2>", args[0]);
    } else {
        let fname1 = args[1];
	let args2: ~[~str] = os::args();
	let fname2 = args2[1];
        let path1 = Path::new(fname1.clone());
        let path2 = Path::new(fname2.clone());
        let msg_file1 = File::open(&path1);
        let msg_file2 = File::open(&path2);

        match (msg_file1) {
            Some(mut msg1) => {
		match (msg_file2) {
		    Some(mut msg2) => {
                        let msg_bytes1: ~[u8] = msg1.read_to_end();
		        let msg_bytes2: ~[u8] = msg2.read_to_end();
                        let share_file = File::create(&Path::new("msg.share"));

                        match (share_file) {
                            Some(share) => {
                                join(msg_bytes1, msg_bytes2, share);
                                } ,
                            None => fail!("Error opening output files!"),
                        }
		    } ,
		    None => fail!("Error opening message file: {:s}", fname2)
		}
            } ,
            None => fail!("Error opening message file: {:s}", fname1)
        }
    }
}

fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
    let mut ret = ~[];
    for i in range(0, a.len()) {
	ret.push(a[i] ^ b[i]);
    }
    ret
}

fn join(msg_bytes1: &[u8], msg_bytes2: &[u8], mut share: File) {
    //let mut random_bytes: ~[u8] = ~[];
    // This is not cryptographically strong randomness!
    // (For entertainment purposes only.)
    //for _ in range(0, msg_bytes.len()) {
    //	let random_byte = random();
    //	random_bytes.push(random_byte);
    //}

    let msg = xor(msg_bytes1, msg_bytes2);
    share.write(msg);
}
<|endoftext|>


<commit_before><commit_msg>added a simple test<commit_after>extern crate rustyham;
use rustyham::rustyham::*;

#[test]
fn testfoobar() {
    assert!(hamming(Hamming::Encode, "a".to_string()) == "101110010010000".to_string());
}
<|endoftext|>