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

//! Code to convert a DefId into a DefPath (when serializing) and then
//! back again (when deserializing). Note that the new DefId
//! necessarily will not be the same as the old (and of course the
//! item might even be removed in the meantime).

use rustc::dep_graph::DepNode;
use rustc::hir::map::DefPath;
use rustc::hir::def_id::DefId;
use rustc::middle::cstore::LOCAL_CRATE;
use rustc::ty::TyCtxt;
use rustc::util::nodemap::DefIdMap;
use std::fmt::{self, Debug};
use std::iter::once;
use syntax::ast;

/// Index into the DefIdDirectory
#[derive(Copy, Clone, Debug, PartialOrd, Ord, Hash, PartialEq, Eq,
         RustcEncodable, RustcDecodable)]
pub struct DefPathIndex {
    index: u32
}

#[derive(RustcEncodable, RustcDecodable)]
pub struct DefIdDirectory {
    // N.B. don't use Removable here because these def-ids are loaded
    // directly without remapping, so loading them should not fail.
    paths: Vec<DefPath>,

    // For each crate, saves the crate-name/disambiguator so that
    // later we can match crate-numbers up again.
    krates: Vec<KrateInfo>,
}

#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct KrateInfo {
    krate: ast::CrateNum,
    name: String,
    disambiguator: String,
}

impl DefIdDirectory {
    pub fn new(krates: Vec<KrateInfo>) -> DefIdDirectory {
        DefIdDirectory { paths: vec![], krates: krates }
    }

    fn max_current_crate(&self, tcx: TyCtxt) -> ast::CrateNum {
        tcx.sess.cstore.crates()
                       .into_iter()
                       .max()
                       .unwrap_or(LOCAL_CRATE)
    }

    /// Returns a string form for `index`; useful for debugging
    pub fn def_path_string(&self, tcx: TyCtxt, index: DefPathIndex) -> String {
        let path = &self.paths[index.index as usize];
        if self.krate_still_valid(tcx, self.max_current_crate(tcx), path.krate) {
            path.to_string(tcx)
        } else {
            format!("<crate {} changed>", path.krate)
        }
    }

    pub fn krate_still_valid(&self,
                             tcx: TyCtxt,
                             max_current_crate: ast::CrateNum,
                             krate: ast::CrateNum) -> bool {
        // Check that the crate-number still matches. For now, if it
        // doesn't, just return None. We could do better, such as
        // finding the new number.

        if krate > max_current_crate {
            false
        } else {
            let old_info = &self.krates[krate as usize];
            assert_eq!(old_info.krate, krate);
            let old_name: &str = &old_info.name;
            let old_disambiguator: &str = &old_info.disambiguator;
            let new_name: &str = &tcx.crate_name(krate);
            let new_disambiguator: &str = &tcx.crate_disambiguator(krate);
            old_name == new_name && old_disambiguator == new_disambiguator
        }
    }

    pub fn retrace(&self, tcx: TyCtxt) -> RetracedDefIdDirectory {
        let max_current_crate = self.max_current_crate(tcx);

        let ids = self.paths.iter()
                            .map(|path| {
                                if self.krate_still_valid(tcx, max_current_crate, path.krate) {
                                    tcx.retrace_path(path)
                                } else {
                                    debug!("crate {} changed from {:?} to {:?}/{:?}",
                                           path.krate,
                                           self.krates[path.krate as usize],
                                           tcx.crate_name(path.krate),
                                           tcx.crate_disambiguator(path.krate));
                                    None
                                }
                            })
                            .collect();
        RetracedDefIdDirectory { ids: ids }
    }
}

#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct RetracedDefIdDirectory {
    ids: Vec<Option<DefId>>
}

impl RetracedDefIdDirectory {
    pub fn def_id(&self, index: DefPathIndex) -> Option<DefId> {
        self.ids[index.index as usize]
    }

    pub fn map(&self, node: &DepNode<DefPathIndex>) -> Option<DepNode<DefId>> {
        node.map_def(|&index| self.def_id(index))
    }
}

pub struct DefIdDirectoryBuilder<'a,'tcx:'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    hash: DefIdMap<DefPathIndex>,
    directory: DefIdDirectory,
}

impl<'a,'tcx> DefIdDirectoryBuilder<'a,'tcx> {
    pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefIdDirectoryBuilder<'a, 'tcx> {
        let mut krates: Vec<_> =
            once(LOCAL_CRATE)
            .chain(tcx.sess.cstore.crates())
            .map(|krate| {
                KrateInfo {
                    krate: krate,
                    name: tcx.crate_name(krate).to_string(),
                    disambiguator: tcx.crate_disambiguator(krate).to_string()
                }
            })
            .collect();

        // the result of crates() is not in order, so sort list of
        // crates so that we can just index it later
        krates.sort_by_key(|k| k.krate);

        DefIdDirectoryBuilder {
            tcx: tcx,
            hash: DefIdMap(),
            directory: DefIdDirectory::new(krates),
        }
    }

    pub fn add(&mut self, def_id: DefId) -> DefPathIndex {
        debug!("DefIdDirectoryBuilder: def_id={:?}", def_id);
        let tcx = self.tcx;
        let paths = &mut self.directory.paths;
        self.hash.entry(def_id)
                 .or_insert_with(|| {
                     let def_path = tcx.def_path(def_id);
                     let index = paths.len() as u32;
                     paths.push(def_path);
                     DefPathIndex { index: index }
                 })
                 .clone()
    }

    pub fn lookup_def_path(&self, id: DefPathIndex) -> &DefPath {
        &self.directory.paths[id.index as usize]
    }

    pub fn map(&mut self, node: &DepNode<DefId>) -> DepNode<DefPathIndex> {
        node.map_def(|&def_id| Some(self.add(def_id))).unwrap()
    }

    pub fn directory(&self) -> &DefIdDirectory {
        &self.directory
    }
}

impl Debug for DefIdDirectory {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        fmt.debug_list()
           .entries(self.paths.iter().enumerate())
           .finish()
    }
}
<commit_msg>rename KrateInfo to CrateInfo<commit_after>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Code to convert a DefId into a DefPath (when serializing) and then
//! back again (when deserializing). Note that the new DefId
//! necessarily will not be the same as the old (and of course the
//! item might even be removed in the meantime).

use rustc::dep_graph::DepNode;
use rustc::hir::map::DefPath;
use rustc::hir::def_id::DefId;
use rustc::middle::cstore::LOCAL_CRATE;
use rustc::ty::TyCtxt;
use rustc::util::nodemap::DefIdMap;
use std::fmt::{self, Debug};
use std::iter::once;
use syntax::ast;

/// Index into the DefIdDirectory
#[derive(Copy, Clone, Debug, PartialOrd, Ord, Hash, PartialEq, Eq,
         RustcEncodable, RustcDecodable)]
pub struct DefPathIndex {
    index: u32
}

#[derive(RustcEncodable, RustcDecodable)]
pub struct DefIdDirectory {
    // N.B. don't use Removable here because these def-ids are loaded
    // directly without remapping, so loading them should not fail.
    paths: Vec<DefPath>,

    // For each crate, saves the crate-name/disambiguator so that
    // later we can match crate-numbers up again.
    krates: Vec<CrateInfo>,
}

#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct CrateInfo {
    krate: ast::CrateNum,
    name: String,
    disambiguator: String,
}

impl DefIdDirectory {
    pub fn new(krates: Vec<CrateInfo>) -> DefIdDirectory {
        DefIdDirectory { paths: vec![], krates: krates }
    }

    fn max_current_crate(&self, tcx: TyCtxt) -> ast::CrateNum {
        tcx.sess.cstore.crates()
                       .into_iter()
                       .max()
                       .unwrap_or(LOCAL_CRATE)
    }

    /// Returns a string form for `index`; useful for debugging
    pub fn def_path_string(&self, tcx: TyCtxt, index: DefPathIndex) -> String {
        let path = &self.paths[index.index as usize];
        if self.krate_still_valid(tcx, self.max_current_crate(tcx), path.krate) {
            path.to_string(tcx)
        } else {
            format!("<crate {} changed>", path.krate)
        }
    }

    pub fn krate_still_valid(&self,
                             tcx: TyCtxt,
                             max_current_crate: ast::CrateNum,
                             krate: ast::CrateNum) -> bool {
        // Check that the crate-number still matches. For now, if it
        // doesn't, just return None. We could do better, such as
        // finding the new number.

        if krate > max_current_crate {
            false
        } else {
            let old_info = &self.krates[krate as usize];
            assert_eq!(old_info.krate, krate);
            let old_name: &str = &old_info.name;
            let old_disambiguator: &str = &old_info.disambiguator;
            let new_name: &str = &tcx.crate_name(krate);
            let new_disambiguator: &str = &tcx.crate_disambiguator(krate);
            old_name == new_name && old_disambiguator == new_disambiguator
        }
    }

    pub fn retrace(&self, tcx: TyCtxt) -> RetracedDefIdDirectory {
        let max_current_crate = self.max_current_crate(tcx);

        let ids = self.paths.iter()
                            .map(|path| {
                                if self.krate_still_valid(tcx, max_current_crate, path.krate) {
                                    tcx.retrace_path(path)
                                } else {
                                    debug!("crate {} changed from {:?} to {:?}/{:?}",
                                           path.krate,
                                           self.krates[path.krate as usize],
                                           tcx.crate_name(path.krate),
                                           tcx.crate_disambiguator(path.krate));
                                    None
                                }
                            })
                            .collect();
        RetracedDefIdDirectory { ids: ids }
    }
}

#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct RetracedDefIdDirectory {
    ids: Vec<Option<DefId>>
}

impl RetracedDefIdDirectory {
    pub fn def_id(&self, index: DefPathIndex) -> Option<DefId> {
        self.ids[index.index as usize]
    }

    pub fn map(&self, node: &DepNode<DefPathIndex>) -> Option<DepNode<DefId>> {
        node.map_def(|&index| self.def_id(index))
    }
}

pub struct DefIdDirectoryBuilder<'a,'tcx:'a> {
    tcx: TyCtxt<'a, 'tcx, 'tcx>,
    hash: DefIdMap<DefPathIndex>,
    directory: DefIdDirectory,
}

impl<'a,'tcx> DefIdDirectoryBuilder<'a,'tcx> {
    pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> DefIdDirectoryBuilder<'a, 'tcx> {
        let mut krates: Vec<_> =
            once(LOCAL_CRATE)
            .chain(tcx.sess.cstore.crates())
            .map(|krate| {
                CrateInfo {
                    krate: krate,
                    name: tcx.crate_name(krate).to_string(),
                    disambiguator: tcx.crate_disambiguator(krate).to_string()
                }
            })
            .collect();

        // the result of crates() is not in order, so sort list of
        // crates so that we can just index it later
        krates.sort_by_key(|k| k.krate);

        DefIdDirectoryBuilder {
            tcx: tcx,
            hash: DefIdMap(),
            directory: DefIdDirectory::new(krates),
        }
    }

    pub fn add(&mut self, def_id: DefId) -> DefPathIndex {
        debug!("DefIdDirectoryBuilder: def_id={:?}", def_id);
        let tcx = self.tcx;
        let paths = &mut self.directory.paths;
        self.hash.entry(def_id)
                 .or_insert_with(|| {
                     let def_path = tcx.def_path(def_id);
                     let index = paths.len() as u32;
                     paths.push(def_path);
                     DefPathIndex { index: index }
                 })
                 .clone()
    }

    pub fn lookup_def_path(&self, id: DefPathIndex) -> &DefPath {
        &self.directory.paths[id.index as usize]
    }

    pub fn map(&mut self, node: &DepNode<DefId>) -> DepNode<DefPathIndex> {
        node.map_def(|&def_id| Some(self.add(def_id))).unwrap()
    }

    pub fn directory(&self) -> &DefIdDirectory {
        &self.directory
    }
}

impl Debug for DefIdDirectory {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        fmt.debug_list()
           .entries(self.paths.iter().enumerate())
           .finish()
    }
}
<|endoftext|>


<commit_before><commit_msg>Remove println call<commit_after><|endoftext|>


<commit_before><commit_msg>Add test whether adding an URL works<commit_after><|endoftext|>


<commit_before><commit_msg>Forgot to add packets.rs<commit_after>use byteorder::{BigEndian, ByteOrder, ReadBytesExt, WriteBytesExt};
use std::io::{Write};

pub enum Packet {
    //Status request and response (channel -1)
    StatusRequest(StatusRequest),
    StatusResponse(StatusResponse),

    //Connection handshake (also channel -1).
    Connect,
    Aborted(String),
    Connected(u32),

    //Heartbeat (channel -2).
    Heartbeat(i16),

    //MTU estimation (-3 and -4)
    //These have to record the channel.
    ResetMTUCount {channel: i16},
    MTUCountWasReset {channel: i16},
    MTUEstimate {channel: i16, payload: Vec<u8>},
    MTUResponse {channel: i16, count: u32},
}

pub enum StatusRequest {
    FastnetQuery,
    VersionQuery,
    ExtensionQuery(String),
}

pub enum StatusResponse {
    FastnetResponse(u8),
    VersionResponse(String),
    ExtensionResponse {name: String, supported: u8},
}

pub enum PacketEncodingError {
    //We need to write over 500 bytes to decode.
    TooLarge,
}

pub enum PacketDecodingError {
    //We need more bytes than what we got.
    TooSmall,
    //The packet has a checksum, but we didn't match it.
    ChecksumMismatch,
    UnknownChannel,
    InvalidFormat,
}

//These are the channel constants.

//Status query and connection handshake channel.
const CONNECTION_CHANNEL: i16 = -1;

//Heartbeat channel.
const HEARTBEAT_CHANNEL: i16 = -2;

//Client and server MTU channels.
//These are named for the entity executing the MTU estimation algorithm, not for the entity receiving.
const SERVER_MTU_ESTIMATION_CHANNEL: i16 = -3;
const CLIENT_MTU_ESTIMATION_CHANNEL: i16 = -4;

//Specification mandates that we never send a packet over the maximum size of 500 bytes.
const MAXIMUM_PACKET_SIZE: usize = 500;

//This function writes over the buffer even if it fails.
pub fn encode_packet(packet: &Packet, destination: &mut [u8; MAXIMUM_PACKET_SIZE])->Result<usize, PacketEncodingError> {
    let destinationLen = destination.len();
    let mut writingTo = &mut destination[..];
    match *packet {
        Packet::StatusRequest(ref req) => {
            writingTo.write_i16::<BigEndian>(-1).unwrap();
            writingTo.write_i16::<BigEndian>(0).unwrap();
            match *req {
                StatusRequest::FastnetQuery => {
                    writingTo.write_u8(0).unwrap();
                },
                StatusRequest::VersionQuery => {
                    writingTo.write_u8(1).unwrap();
                },
                StatusRequest::ExtensionQuery(ref name) => {
                    writingTo.write_u8(2).unwrap();
                    let nameAsBytes = name.as_bytes();
                    if nameAsBytes.len() < writingTo.len()-1 {return Err(PacketEncodingError::TooLarge);};
                    writingTo.write(nameAsBytes).unwrap();
                },
            }
        },
        Packet::StatusResponse(ref resp) => {
            writingTo.write_i16::<BigEndian>(-1);
            writingTo.write_u8(1);
            match* resp {
                StatusResponse::FastnetResponse(value) => {
                    writingTo.write_u8(0).unwrap();
                    writingTo.write_u8(value);
                },
                StatusResponse::VersionResponse(ref version) => {
                    writingTo.write_u8(1);
                    let versionAsBytes = version.as_bytes();
                    if writingTo.len() < versionAsBytes.len() {return Err(PacketEncodingError:: TooLarge)};
                    writingTo.write(versionAsBytes).unwrap();
                },
                StatusResponse::ExtensionResponse{name: ref name, supported: supported} => {
                    writingTo.write_u8(2).unwrap();
                    let nameAsBytes = name.as_bytes();
                    //name plus the boolean.
                    if writingTo.len() < nameAsBytes.len()-1 {return Err(PacketEncodingError::TooLarge)};
                    writingTo.write(nameAsBytes).unwrap();
                    writingTo.write_u8(supported);
                },
            }
        },
        Packet::Connect => {
            writingTo.write_i16::<BigEndian>(-1);
            writingTo.write_u8(2);
        },
        Packet::Connected(id) => {
            writingTo.write_i16::<BigEndian>(-1);
            writingTo.write_u8(3);
            writingTo.write_u32::<BigEndian>(id);
        },
        Packet::Aborted(ref msg) => {
            writingTo.write_i16::<BigEndian>(-1);
            writingTo.write_u8(4);
            let msgAsBytes = msg.as_bytes();
            if writingTo.len() < msgAsBytes.len() {return Err(PacketEncodingError::TooLarge)};
            writingTo.write(msgAsBytes).unwrap();
        },
        Packet::Heartbeat(value) => {
            writingTo.write_i16::<BigEndian>(-2);
            writingTo.write_i16::<BigEndian>(value);
        },
        Packet::ResetMTUCount{channel: chan} => {
            writingTo.write_i16::<BigEndian>(chan);
            writingTo.write_u8(0);
        },
        Packet::MTUCountWasReset{channel: chan} => {
            writingTo.write_i16::<BigEndian>(chan).unwrap();
            writingTo.write_u8(1).unwrap();
        },
        Packet::MTUEstimate{channel: chan, payload: ref p} => {
            writingTo.write_i16::<BigEndian>(chan).unwrap();
            writingTo.write_u8(3).unwrap();
            if writingTo.len() < p.len() {return Err(PacketEncodingError::TooLarge)};
            writingTo.write(p).unwrap();
        },
        Packet::MTUResponse{channel: chan, count: c} => {
            writingTo.write_i16::<BigEndian>(chan);
            writingTo.write_u8(4).unwrap();
            writingTo.write_u32::<BigEndian>(c).unwrap();
        },
    }
    Ok(destinationLen-writingTo.len())
}
<|endoftext|>


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

// compile-flags: -Z parse-only

// ignore-test: this is an auxiliary file for circular-modules-main.rs

mod circular_modules_main;

pub fn say_hello() {
    println!("{}", circular_modules_main::hi_str());
}
<commit_msg>Fix fallout in tests.<commit_after>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

// compile-flags: -Z parse-only

// ignore-test: this is an auxiliary file for circular-modules-main.rs

#[path = "circular_modules_main.rs"]
mod circular_modules_main;

pub fn say_hello() {
    println!("{}", circular_modules_main::hi_str());
}
<|endoftext|>


<commit_before><commit_msg>Implement window X, Y attribs, clipping, and 0-pixel transparency<commit_after><|endoftext|>


<commit_before><commit_msg>Add missing ec_public_key.rs file.<commit_after>// Copyright 2017 Brian Smith <brian@briansmith.org>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://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 error::*;
use super::Algorithm;

pub struct ECPublicKey {
    buf: [u8; MAX_LEN],
    len: usize,
}

// The length of the longest supported EC public key (P-384).
const MAX_LEN: usize = 1 + (2 * 48);

impl ECPublicKey {
    // DNSSEC encodes uncompressed EC public keys without the standard 0x04
    // prefix that indicates they are uncompressed, but crypto libraries
    // require that prefix.
    pub fn from_unprefixed(without_prefix: &[u8], algorithm: Algorithm)
                           -> DnsSecResult<Self> {
        let field_len = match algorithm {
            Algorithm::ECDSAP256SHA256 => 32,
            Algorithm::ECDSAP384SHA384 => 48,
            _ => return Err("only ECDSAP256SHA256 and ECDSAP384SHA384 are supported by Ec".into()),
        };
        let len = 1 + (2 * field_len);
        if len - 1 != without_prefix.len() {
            return Err("EC public key is the wrong length".into());
        }
        let mut buf = [0x04u8; MAX_LEN];
        buf[1..len].copy_from_slice(without_prefix);
        Ok( ECPublicKey { buf, len })
    }

    pub fn prefixed_bytes(&self) -> &[u8] {
        &self.buf[..self.len]
    }

    #[cfg(feature = "ring")]
    pub fn unprefixed_bytes(&self) -> &[u8] {
        &self.buf[1..self.len]
    }
}
<|endoftext|>


<commit_before><commit_msg>Avoid deadlocking by ensuring we ack pending messages every so often.<commit_after><|endoftext|>


<commit_before>// TODO: FIXME: It must be removed after code layout stabilization!
#![allow(dead_code)]
extern crate sovrin;

#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate rust_base58;
#[macro_use]
extern crate serde_derive;
extern crate zmq;

use std::thread;

#[macro_use]
#[path = "utils/mod.rs"]
mod utils;

use utils::agent::AgentUtils;
use utils::logger::LoggerUtils;
use utils::signus::SignusUtils;
use utils::test::TestUtils;
use utils::wallet::WalletUtils;

mod high_cases {
    use super::*;

    mod sovrin_agent_connect {
        use super::*;
        use rust_base58::FromBase58;

        #[test]
        fn sovrin_agent_connect_works_for_all_data_in_wallet_present() {
            LoggerUtils::init();
            TestUtils::cleanup_storage();

            let wallet_handle = WalletUtils::create_and_open_wallet("pool1", "wallet1", "default").expect("create wallet");

            let seed: Option<String> = Some("sovrin_agent_connect_works_for_a".to_string());
            let (did, ver_key, pub_key) = SignusUtils::create_and_store_my_did(wallet_handle, seed).unwrap();
            let endpoint = "tcp://127.0.0.1:9700";

            SignusUtils::store_their_did_from_parts(wallet_handle, did.as_str(), pub_key.as_str(), ver_key.as_str(), endpoint).unwrap();

            //FIXME temporary code: replace by sovrin_agent_listen
            thread::spawn(move || {
                let secret_key = zmq::z85_encode("6wBM7yEYWD7wGd3ZtNQX5r31uWuC8NoZS2Lr6HZvRTY4".from_base58().unwrap().as_slice()).unwrap();
                let public_key = zmq::z85_encode("2vTqP9QfNdvPr397QaFKtbVUPbhgqmAum2oDVkYsk4p9".from_base58().unwrap().as_slice()).unwrap();
                let socket: zmq::Socket = zmq::Context::new().socket(zmq::SocketType::ROUTER).unwrap();
                socket.set_curve_publickey(public_key.as_str()).unwrap();
                socket.set_curve_secretkey(secret_key.as_str()).unwrap();
                socket.set_curve_server(true).unwrap();
                socket.bind(endpoint).unwrap();
                socket.poll(zmq::POLLIN, -1).unwrap();
                let identity = socket.recv_string(zmq::DONTWAIT).unwrap().unwrap();
                let msg = socket.recv_string(zmq::DONTWAIT).unwrap().unwrap();
                info!("Fake agent socket - recv - from {}, msg {}", identity, msg);
                if msg.eq("DID") {
                    info!("Fake agent socket send ACK");
                    socket.send_multipart(&[identity.as_bytes(), "DID_ACK".as_bytes()], zmq::DONTWAIT).unwrap();
                }
            });
            //FIXME /temporary code

            AgentUtils::connect(wallet_handle, did.as_str(), did.as_str()).unwrap();

            TestUtils::cleanup_storage();
        }
    }

    mod sovrin_agent_listen {
        use super::*;

        #[test]
        fn sovrin_agent_listen_works_for_all_data_in_wallet_present() {
            LoggerUtils::init();
            TestUtils::cleanup_storage();

            let wallet_handle = WalletUtils::create_and_open_wallet("pool2", "wallet2", "default").expect("create wallet");

            let seed: Option<String> = Some("sovrin_agent_listen_works_for_al".to_string());
            let (did, ver_key, pub_key) = SignusUtils::create_and_store_my_did(wallet_handle, seed).unwrap();
            let endpoint = "tcp://127.0.0.1:9700";
            SignusUtils::store_their_did_from_parts(wallet_handle, did.as_str(), pub_key.as_str(), ver_key.as_str(), endpoint).unwrap();

            AgentUtils::listen(wallet_handle).unwrap();

            TestUtils::cleanup_storage();
        }
    }
}<commit_msg>Add draft of integration test for compatibility of sovrin_agent_listen and sovrin_agent_connect.<commit_after>// TODO: FIXME: It must be removed after code layout stabilization!
#![allow(dead_code)]
extern crate sovrin;

#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate rust_base58;
#[macro_use]
extern crate serde_derive;
extern crate zmq;

use std::thread;

#[macro_use]
#[path = "utils/mod.rs"]
mod utils;

use utils::agent::AgentUtils;
use utils::logger::LoggerUtils;
use utils::signus::SignusUtils;
use utils::test::TestUtils;
use utils::wallet::WalletUtils;

mod high_cases {
    use super::*;

    #[test]
    fn sovrin_agent_listen_works_with_sovrin_agent_connect() {
        LoggerUtils::init();
        TestUtils::cleanup_storage();
        let wallet_handle = WalletUtils::create_and_open_wallet("pool3", "wallet3", "default").unwrap();
        let seed: Option<String> = Some("fixed_seed_for_agent_tests______".to_string());
        let (did, ver_key, pub_key): (String, String, String) = SignusUtils::create_and_store_my_did(wallet_handle, seed).unwrap();

        let (_, endpoint): (i32, String) = AgentUtils::listen(wallet_handle).unwrap();

        let endpoint = endpoint.replace("0.0.0.0", "127.0.0.1");
        SignusUtils::store_their_did_from_parts(wallet_handle, did.as_str(), pub_key.as_str(), ver_key.as_str(), endpoint.as_str()).unwrap();

        AgentUtils::connect(wallet_handle, did.as_str(), did.as_str()).unwrap();

    }

    mod sovrin_agent_connect {
        use super::*;
        use rust_base58::FromBase58;

        #[test]
        fn sovrin_agent_connect_works_for_all_data_in_wallet_present() {
            LoggerUtils::init();
            TestUtils::cleanup_storage();

            let wallet_handle = WalletUtils::create_and_open_wallet("pool1", "wallet1", "default").expect("create wallet");

            let seed: Option<String> = Some("sovrin_agent_connect_works_for_a".to_string());
            let (did, ver_key, pub_key) = SignusUtils::create_and_store_my_did(wallet_handle, seed).unwrap();
            let endpoint = "tcp://127.0.0.1:9700";

            SignusUtils::store_their_did_from_parts(wallet_handle, did.as_str(), pub_key.as_str(), ver_key.as_str(), endpoint).unwrap();

            //FIXME temporary code: replace by sovrin_agent_listen
            thread::spawn(move || {
                let secret_key = zmq::z85_encode("6wBM7yEYWD7wGd3ZtNQX5r31uWuC8NoZS2Lr6HZvRTY4".from_base58().unwrap().as_slice()).unwrap();
                let public_key = zmq::z85_encode("2vTqP9QfNdvPr397QaFKtbVUPbhgqmAum2oDVkYsk4p9".from_base58().unwrap().as_slice()).unwrap();
                let socket: zmq::Socket = zmq::Context::new().socket(zmq::SocketType::ROUTER).unwrap();
                socket.set_curve_publickey(public_key.as_str()).unwrap();
                socket.set_curve_secretkey(secret_key.as_str()).unwrap();
                socket.set_curve_server(true).unwrap();
                socket.bind(endpoint).unwrap();
                socket.poll(zmq::POLLIN, -1).unwrap();
                let identity = socket.recv_string(zmq::DONTWAIT).unwrap().unwrap();
                let msg = socket.recv_string(zmq::DONTWAIT).unwrap().unwrap();
                info!("Fake agent socket - recv - from {}, msg {}", identity, msg);
                if msg.eq("DID") {
                    info!("Fake agent socket send ACK");
                    socket.send_multipart(&[identity.as_bytes(), "DID_ACK".as_bytes()], zmq::DONTWAIT).unwrap();
                }
            });
            //FIXME /temporary code

            AgentUtils::connect(wallet_handle, did.as_str(), did.as_str()).unwrap();

            TestUtils::cleanup_storage();
        }
    }

    mod sovrin_agent_listen {
        use super::*;

        #[test]
        fn sovrin_agent_listen_works_for_all_data_in_wallet_present() {
            LoggerUtils::init();
            TestUtils::cleanup_storage();

            let wallet_handle = WalletUtils::create_and_open_wallet("pool2", "wallet2", "default").expect("create wallet");

            let seed: Option<String> = Some("sovrin_agent_listen_works_for_al".to_string());
            let (did, ver_key, pub_key) = SignusUtils::create_and_store_my_did(wallet_handle, seed).unwrap();
            let endpoint = "tcp://127.0.0.1:9700";
            SignusUtils::store_their_did_from_parts(wallet_handle, did.as_str(), pub_key.as_str(), ver_key.as_str(), endpoint).unwrap();

            AgentUtils::listen(wallet_handle).unwrap();

            TestUtils::cleanup_storage();
        }
    }
}<|endoftext|>


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

use geom::length::Length;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;

use std::default::Default;
use std::num::{NumCast, One, Zero};
use std::fmt;

// Units for use with geom::length and geom::scale_factor.

/// One hardware pixel.
///
/// This unit corresponds to the smallest addressable element of the display hardware.
#[deriving(Encodable)]
pub enum DevicePixel {}

/// A normalized "pixel" at the default resolution for the display.
///
/// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it
/// should approximate a device-independent reference length.  This unit corresponds to Android's
/// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel."
///
/// The relationship between DevicePixel and ScreenPx is defined by the OS.  On most low-dpi
/// screens, one ScreenPx is equal to one DevicePixel.  But on high-density screens it can be
/// some larger number.  For example, by default on Apple "retina" displays, one ScreenPx equals
/// two DevicePixels.  On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels.
///
/// The ratio between ScreenPx and DevicePixel for a given display be found by calling
/// `servo::windowing::WindowMethods::hidpi_factor`.
pub enum ScreenPx {}

/// One CSS "px" in the coordinate system of the "initial viewport":
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
///
/// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user.  This is
/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
/// so it still exactly fits the visible area.
///
/// At the default zoom level of 100%, one PagePx is equal to one ScreenPx.  However, if the
/// document is zoomed in or out then this scale may be larger or smaller.
#[deriving(Encodable)]
pub enum ViewportPx {}

/// One CSS "px" in the root coordinate system for the content document.
///
/// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user.
/// This is the mobile-style "pinch zoom" that enlarges content without reflowing it.  When the
/// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size
/// as the viewable area.
#[deriving(Encodable)]
pub enum PagePx {}

// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
//   / hidpi_ratio => ScreenPx
//     / desktop_zoom => ViewportPx
//       / pinch_zoom => PagePx

// An Au is an "App Unit" and represents 1/60th of a CSS pixel.  It was
// originally proposed in 2002 as a standard unit of measure in Gecko.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info.
//
// FIXME: Implement Au using Length and ScaleFactor instead of a custom type.
#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Zero)]
pub struct Au(pub i32);

impl Default for Au {
    #[inline]
    fn default() -> Au {
        Au(0)
    }
}

impl fmt::Show for Au {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let Au(n) = *self;
        write!(f, "Au(au={} px={})", n, to_frac_px(*self))
    }}

impl Add<Au,Au> for Au {
    #[inline]
    fn add(&self, other: &Au) -> Au {
        let Au(s) = *self;
        let Au(o) = *other;
        Au(s + o)
    }
}

impl Sub<Au,Au> for Au {
    #[inline]
    fn sub(&self, other: &Au) -> Au {
        let Au(s) = *self;
        let Au(o) = *other;
        Au(s - o)
    }

}

impl Mul<Au,Au> for Au {
    #[inline]
    fn mul(&self, other: &Au) -> Au {
        let Au(s) = *self;
        let Au(o) = *other;
        Au(s * o)
    }
}

impl Div<Au,Au> for Au {
    #[inline]
    fn div(&self, other: &Au) -> Au {
        let Au(s) = *self;
        let Au(o) = *other;
        Au(s / o)
    }
}

impl Rem<Au,Au> for Au {
    #[inline]
    fn rem(&self, other: &Au) -> Au {
        let Au(s) = *self;
        let Au(o) = *other;
        Au(s % o)
    }
}

impl Neg<Au> for Au {
    #[inline]
    fn neg(&self) -> Au {
        let Au(s) = *self;
        Au(-s)
    }
}

impl One for Au {
    #[inline]
    fn one() -> Au { Au(1) }
}

impl Num for Au {}

#[inline]
pub fn min(x: Au, y: Au) -> Au { if x < y { x } else { y } }
#[inline]
pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } }

impl NumCast for Au {
    #[inline]
    fn from<T:ToPrimitive>(n: T) -> Option<Au> {
        Some(Au(n.to_i32().unwrap()))
    }
}

impl ToPrimitive for Au {
    #[inline]
    fn to_i64(&self) -> Option<i64> {
        let Au(s) = *self;
        Some(s as i64)
    }

    #[inline]
    fn to_u64(&self) -> Option<u64> {
        let Au(s) = *self;
        Some(s as u64)
    }

    #[inline]
    fn to_f32(&self) -> Option<f32> {
        let Au(s) = *self;
        s.to_f32()
    }

    #[inline]
    fn to_f64(&self) -> Option<f64> {
        let Au(s) = *self;
        s.to_f64()
    }
}

impl Au {
    /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
    #[inline]
    pub fn new(value: i32) -> Au {
        Au(value)
    }

    #[inline]
    pub fn scale_by(self, factor: f64) -> Au {
        let Au(s) = self;
        Au(((s as f64) * factor) as i32)
    }

    #[inline]
    pub fn from_px(px: int) -> Au {
        NumCast::from(px * 60).unwrap()
    }

    #[inline]
    pub fn from_page_px(px: Length<PagePx, f32>) -> Au {
        NumCast::from(px.get() * 60f32).unwrap()
    }

    #[inline]
    pub fn to_nearest_px(&self) -> int {
        let Au(s) = *self;
        ((s as f64) / 60f64).round() as int
    }

    #[inline]
    pub fn to_snapped(&self) -> Au {
        let Au(s) = *self;
        let res = s % 60i32;
        return if res >= 30i32 { return Au(s - res + 60i32) }
                       else { return Au(s - res) };
    }

    #[inline]
    pub fn from_frac32_px(px: f32) -> Au {
        Au((px * 60f32) as i32)
    }

    #[inline]
    pub fn from_pt(pt: f64) -> Au {
        from_px(pt_to_px(pt) as int)
    }

    #[inline]
    pub fn from_frac_px(px: f64) -> Au {
        Au((px * 60f64) as i32)
    }

    #[inline]
    pub fn min(x: Au, y: Au) -> Au {
        let Au(xi) = x;
        let Au(yi) = y;
        if xi < yi { x } else { y }
    }

    #[inline]
    pub fn max(x: Au, y: Au) -> Au {
        let Au(xi) = x;
        let Au(yi) = y;
        if xi > yi { x } else { y }
    }
}

// assumes 72 points per inch, and 96 px per inch
pub fn pt_to_px(pt: f64) -> f64 {
    pt / 72f64 * 96f64
}

// assumes 72 points per inch, and 96 px per inch
pub fn px_to_pt(px: f64) -> f64 {
    px / 96f64 * 72f64
}

pub fn from_frac_px(px: f64) -> Au {
    Au((px * 60f64) as i32)
}

pub fn from_px(px: int) -> Au {
    NumCast::from(px * 60).unwrap()
}

pub fn to_px(au: Au) -> int {
    let Au(a) = au;
    (a / 60) as int
}

pub fn to_frac_px(au: Au) -> f64 {
    let Au(a) = au;
    (a as f64) / 60f64
}

// assumes 72 points per inch, and 96 px per inch
pub fn from_pt(pt: f64) -> Au {
    from_px((pt / 72f64 * 96f64) as int)
}

// assumes 72 points per inch, and 96 px per inch
pub fn to_pt(au: Au) -> f64 {
    let Au(a) = au;
    (a as f64) / 60f64 * 72f64 / 96f64
}

/// Returns true if the rect contains the given point. Points on the top or left sides of the rect
/// are considered inside the rectangle, while points on the right or bottom sides of the rect are
/// not considered inside the rectangle.
pub fn rect_contains_point<T:PartialOrd + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool {
    point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width &&
        point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height
}

/// A helper function to convert a rect of `f32` pixels to a rect of app units.
pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> {
    Rect(Point2D(Au::from_frac32_px(rect.origin.x), Au::from_frac32_px(rect.origin.y)),
         Size2D(Au::from_frac32_px(rect.size.width), Au::from_frac32_px(rect.size.height)))
}

<commit_msg>Only write the px value in Show for Au<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use geom::length::Length;
use geom::point::Point2D;
use geom::rect::Rect;
use geom::size::Size2D;

use std::default::Default;
use std::num::{NumCast, One, Zero};
use std::fmt;

// Units for use with geom::length and geom::scale_factor.

/// One hardware pixel.
///
/// This unit corresponds to the smallest addressable element of the display hardware.
#[deriving(Encodable)]
pub enum DevicePixel {}

/// A normalized "pixel" at the default resolution for the display.
///
/// Like the CSS "px" unit, the exact physical size of this unit may vary between devices, but it
/// should approximate a device-independent reference length.  This unit corresponds to Android's
/// "density-independent pixel" (dip), Mac OS X's "point", and Windows "device-independent pixel."
///
/// The relationship between DevicePixel and ScreenPx is defined by the OS.  On most low-dpi
/// screens, one ScreenPx is equal to one DevicePixel.  But on high-density screens it can be
/// some larger number.  For example, by default on Apple "retina" displays, one ScreenPx equals
/// two DevicePixels.  On Android "MDPI" displays, one ScreenPx equals 1.5 device pixels.
///
/// The ratio between ScreenPx and DevicePixel for a given display be found by calling
/// `servo::windowing::WindowMethods::hidpi_factor`.
pub enum ScreenPx {}

/// One CSS "px" in the coordinate system of the "initial viewport":
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
///
/// ViewportPx is equal to ScreenPx times a "page zoom" factor controlled by the user.  This is
/// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport
/// so it still exactly fits the visible area.
///
/// At the default zoom level of 100%, one PagePx is equal to one ScreenPx.  However, if the
/// document is zoomed in or out then this scale may be larger or smaller.
#[deriving(Encodable)]
pub enum ViewportPx {}

/// One CSS "px" in the root coordinate system for the content document.
///
/// PagePx is equal to ViewportPx multiplied by a "viewport zoom" factor controlled by the user.
/// This is the mobile-style "pinch zoom" that enlarges content without reflowing it.  When the
/// viewport zoom is not equal to 1.0, then the layout viewport is no longer the same physical size
/// as the viewable area.
#[deriving(Encodable)]
pub enum PagePx {}

// In summary, the hierarchy of pixel units and the factors to convert from one to the next:
//
// DevicePixel
//   / hidpi_ratio => ScreenPx
//     / desktop_zoom => ViewportPx
//       / pinch_zoom => PagePx

// An Au is an "App Unit" and represents 1/60th of a CSS pixel.  It was
// originally proposed in 2002 as a standard unit of measure in Gecko.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=177805 for more info.
//
// FIXME: Implement Au using Length and ScaleFactor instead of a custom type.
#[deriving(Clone, PartialEq, PartialOrd, Eq, Ord, Zero)]
pub struct Au(pub i32);

impl Default for Au {
    #[inline]
    fn default() -> Au {
        Au(0)
    }
}

impl fmt::Show for Au {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}px", to_frac_px(*self))
    }}

impl Add<Au,Au> for Au {
    #[inline]
    fn add(&self, other: &Au) -> Au {
        let Au(s) = *self;
        let Au(o) = *other;
        Au(s + o)
    }
}

impl Sub<Au,Au> for Au {
    #[inline]
    fn sub(&self, other: &Au) -> Au {
        let Au(s) = *self;
        let Au(o) = *other;
        Au(s - o)
    }

}

impl Mul<Au,Au> for Au {
    #[inline]
    fn mul(&self, other: &Au) -> Au {
        let Au(s) = *self;
        let Au(o) = *other;
        Au(s * o)
    }
}

impl Div<Au,Au> for Au {
    #[inline]
    fn div(&self, other: &Au) -> Au {
        let Au(s) = *self;
        let Au(o) = *other;
        Au(s / o)
    }
}

impl Rem<Au,Au> for Au {
    #[inline]
    fn rem(&self, other: &Au) -> Au {
        let Au(s) = *self;
        let Au(o) = *other;
        Au(s % o)
    }
}

impl Neg<Au> for Au {
    #[inline]
    fn neg(&self) -> Au {
        let Au(s) = *self;
        Au(-s)
    }
}

impl One for Au {
    #[inline]
    fn one() -> Au { Au(1) }
}

impl Num for Au {}

#[inline]
pub fn min(x: Au, y: Au) -> Au { if x < y { x } else { y } }
#[inline]
pub fn max(x: Au, y: Au) -> Au { if x > y { x } else { y } }

impl NumCast for Au {
    #[inline]
    fn from<T:ToPrimitive>(n: T) -> Option<Au> {
        Some(Au(n.to_i32().unwrap()))
    }
}

impl ToPrimitive for Au {
    #[inline]
    fn to_i64(&self) -> Option<i64> {
        let Au(s) = *self;
        Some(s as i64)
    }

    #[inline]
    fn to_u64(&self) -> Option<u64> {
        let Au(s) = *self;
        Some(s as u64)
    }

    #[inline]
    fn to_f32(&self) -> Option<f32> {
        let Au(s) = *self;
        s.to_f32()
    }

    #[inline]
    fn to_f64(&self) -> Option<f64> {
        let Au(s) = *self;
        s.to_f64()
    }
}

impl Au {
    /// FIXME(pcwalton): Workaround for lack of cross crate inlining of newtype structs!
    #[inline]
    pub fn new(value: i32) -> Au {
        Au(value)
    }

    #[inline]
    pub fn scale_by(self, factor: f64) -> Au {
        let Au(s) = self;
        Au(((s as f64) * factor) as i32)
    }

    #[inline]
    pub fn from_px(px: int) -> Au {
        NumCast::from(px * 60).unwrap()
    }

    #[inline]
    pub fn from_page_px(px: Length<PagePx, f32>) -> Au {
        NumCast::from(px.get() * 60f32).unwrap()
    }

    #[inline]
    pub fn to_nearest_px(&self) -> int {
        let Au(s) = *self;
        ((s as f64) / 60f64).round() as int
    }

    #[inline]
    pub fn to_snapped(&self) -> Au {
        let Au(s) = *self;
        let res = s % 60i32;
        return if res >= 30i32 { return Au(s - res + 60i32) }
                       else { return Au(s - res) };
    }

    #[inline]
    pub fn from_frac32_px(px: f32) -> Au {
        Au((px * 60f32) as i32)
    }

    #[inline]
    pub fn from_pt(pt: f64) -> Au {
        from_px(pt_to_px(pt) as int)
    }

    #[inline]
    pub fn from_frac_px(px: f64) -> Au {
        Au((px * 60f64) as i32)
    }

    #[inline]
    pub fn min(x: Au, y: Au) -> Au {
        let Au(xi) = x;
        let Au(yi) = y;
        if xi < yi { x } else { y }
    }

    #[inline]
    pub fn max(x: Au, y: Au) -> Au {
        let Au(xi) = x;
        let Au(yi) = y;
        if xi > yi { x } else { y }
    }
}

// assumes 72 points per inch, and 96 px per inch
pub fn pt_to_px(pt: f64) -> f64 {
    pt / 72f64 * 96f64
}

// assumes 72 points per inch, and 96 px per inch
pub fn px_to_pt(px: f64) -> f64 {
    px / 96f64 * 72f64
}

pub fn from_frac_px(px: f64) -> Au {
    Au((px * 60f64) as i32)
}

pub fn from_px(px: int) -> Au {
    NumCast::from(px * 60).unwrap()
}

pub fn to_px(au: Au) -> int {
    let Au(a) = au;
    (a / 60) as int
}

pub fn to_frac_px(au: Au) -> f64 {
    let Au(a) = au;
    (a as f64) / 60f64
}

// assumes 72 points per inch, and 96 px per inch
pub fn from_pt(pt: f64) -> Au {
    from_px((pt / 72f64 * 96f64) as int)
}

// assumes 72 points per inch, and 96 px per inch
pub fn to_pt(au: Au) -> f64 {
    let Au(a) = au;
    (a as f64) / 60f64 * 72f64 / 96f64
}

/// Returns true if the rect contains the given point. Points on the top or left sides of the rect
/// are considered inside the rectangle, while points on the right or bottom sides of the rect are
/// not considered inside the rectangle.
pub fn rect_contains_point<T:PartialOrd + Add<T,T>>(rect: Rect<T>, point: Point2D<T>) -> bool {
    point.x >= rect.origin.x && point.x < rect.origin.x + rect.size.width &&
        point.y >= rect.origin.y && point.y < rect.origin.y + rect.size.height
}

/// A helper function to convert a rect of `f32` pixels to a rect of app units.
pub fn f32_rect_to_au_rect(rect: Rect<f32>) -> Rect<Au> {
    Rect(Point2D(Au::from_frac32_px(rect.origin.x), Au::from_frac32_px(rect.origin.y)),
         Size2D(Au::from_frac32_px(rect.size.width), Au::from_frac32_px(rect.size.height)))
}

<|endoftext|>


<commit_before><commit_msg>Whenenv environments must be stored in the database<commit_after>use rusqlite::Connection;
use std::result;

#[derive(Debug)]
pub struct WhenenvEnviroment {
    id: i32,
    fk_job: i32,
    fk_variable: i32,
}

pub fn table_create_enviroment(conn: &Connection)  {
    conn.execute("CREATE TABLE WHENENV_ENVIROMENT (
                  id                    INTEGER PRIMARY KEY ASC,
                  fk_session            INTEGER NOT NULL,
                  fk_variable_name           INTEGER NOT NULL,
                  FOREIGN KEY(fk_session) REFERENCES WHENENV_SESSION(id) ON UPDATE CASCADE
                  FOREIGN KEY(fk_variable) REFERENCES VARIABLE_NAME(id) ON UPDATE CASCADE
                  )", &[]).unwrap();
}

pub fn insert_enviroment(conn: &Connection, job: &i32, variable: &i32) -> Result<i32, &'static str> {
    let me = WhenenvEnviroment {
        id: 0,
        fk_job: *job,
        fk_variable: *variable,

    };
    let enviroment_instance = conn.execute("INSERT INTO WHENENV_ENVIROMENT (fk_job, fk_variable)
                  VALUES (?1, ?2)",
                 &[&me.fk_job, &me.fk_variable]);
    if enviroment_instance.is_err() {
        return Err("Insert failed");
    }
    enviroment_instance.unwrap();
    return Ok(0);
}

pub fn list_enviroment(conn: &Connection)-> Vec<WhenenvEnviroment> {
    let mut stmt = conn.prepare("SELECT id, fk_job, fk_variable  FROM WHENENV_ENVIROMENT").unwrap();
    let wraped_fs_file_iter = stmt.query_map(&[], |row| {
        WhenenvEnviroment {
            id: row.get(0),
            fk_job: row.get(1),
            fk_variable: row.get(2),
        }
    });
    let mut items = Vec::<WhenenvEnviroment>::new();
    if wraped_fs_file_iter.is_err() {
        return items;

    }
    let fs_file_iter = wraped_fs_file_iter.unwrap();
    for person in fs_file_iter {

        items.push(person.unwrap());
    }
    return items;
}

pub fn enviroment_list(conn: &Connection) {
    let mut stmt = conn.prepare("SELECT id, fk_job, fk_variable  FROM WHENENV_ENVIROMENT").unwrap();
    let person_iter = stmt.query_map(&[], |row| {
        WhenenvEnviroment {
            id: row.get(0),
            fk_job: row.get(1),
            fk_variable: row.get(2),
        }
    }).unwrap();

    for person in person_iter {
        println!("Found enviroment {:?}", person.unwrap());
    }
}

pub fn pk_enviroment_by_name(conn: &Connection, job: &i32, variable: &i32, pk: &mut i32) -> Result<i32, &'static str>{
    let mut stmt = conn.prepare("SELECT id, fk_job, fk_variable  FROM WHENENV_ENVIROMENT WHERE fk_job = ?1 AND fk_variable = ?2").unwrap();
    let enviroment_iter = stmt.query_map(&[job, variable], |row| {
        WhenenvEnviroment {
            id: row.get(0),
            fk_job: row.get(1),
            fk_variable: row.get(2),
        }
    });
    if enviroment_iter.is_err() {
        return Err("Insert failed dfdf");
    }
    let result = enviroment_iter.unwrap();
    let mut found = 0;
    let mut items = Vec::<i32>::new();
    for person in result {
        let bill= person.unwrap();
        *pk = bill.id;
        found = 1;
    }
    if found != 0 {
        return Ok(found);
    }
    return Err("None found");
}

<|endoftext|>


<commit_before><commit_msg>Add function to check for a valid HTTP version<commit_after>use hyper::version::HttpVersion;

pub fn is_valid_http_version(v: HttpVersion) -> bool {
    v >= HttpVersion::Http11
}
<|endoftext|>


<commit_before><commit_msg>Ask to overwrite recipient<commit_after><|endoftext|>


<commit_before><commit_msg>Clean up main.rs<commit_after><|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.

#![feature(optin_builtin_traits)]

trait MyTrait {}

impl MyTrait for .. {}

impl MyTrait for .. {}
//~^ ERROR conflicting implementations of trait `MyTrait`

trait MySafeTrait {}

unsafe impl MySafeTrait for .. {}
//~^ ERROR implementing the trait `MySafeTrait` is not unsafe

unsafe trait MyUnsafeTrait {}

impl MyUnsafeTrait for .. {}
//~^ ERROR the trait `MyUnsafeTrait` requires an `unsafe impl` declaration

fn main() {}
<commit_msg>Adjust test for new overlap message on default trait impls<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.

#![feature(optin_builtin_traits)]

trait MyTrait {}

impl MyTrait for .. {}

impl MyTrait for .. {}
//~^ ERROR redundant default implementations of trait `MyTrait`

trait MySafeTrait {}

unsafe impl MySafeTrait for .. {}
//~^ ERROR implementing the trait `MySafeTrait` is not unsafe

unsafe trait MyUnsafeTrait {}

impl MyUnsafeTrait for .. {}
//~^ ERROR the trait `MyUnsafeTrait` requires an `unsafe impl` declaration

fn main() {}
<|endoftext|>


<commit_before><commit_msg>Remove unused imports in main.rs to reduce warnings<commit_after><|endoftext|>


<commit_before><commit_msg>less results<commit_after><|endoftext|>


<commit_before><commit_msg>Fix sphinx_packet_unwrap doc strings<commit_after><|endoftext|>


<commit_before><commit_msg>Make default UnwrappedPacketType be MixHop<commit_after><|endoftext|>


<commit_before><commit_msg>More informative error messages<commit_after><|endoftext|>


<commit_before><commit_msg>sha1 implementation<commit_after>// Implements http://rosettacode.org/wiki/SHA-1
// straight port from golang crypto/sha1
// library implementation

use std::io::IoResult;
use std::slice::bytes::copy_memory;

// The size of a SHA1 checksum in bytes.
static size: uint = 20;

// The blocksize of SHA1 in bytes.
static chunk:uint = 64;
static init:[u32,..5] = [0x67452301,0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];

#[cfg(not(test))]
fn main() {
	let mut d = Digest::new();
	d.write(bytes!("The quick brown fox jumps over the lazy dog")).unwrap();
    let sha1=d.sha1();

    for h in sha1.iter() {
        print!("{:x} ", *h);
    }
 }

// digest represents the partial evaluation of a checksum.
struct Digest {
	h:      [u32, ..5],
	x:      [u8, ..chunk],
	nx:     uint,
	len:    u64
}

impl Digest {
    fn new() -> Digest {
        Digest {
            h:  init,
            x:  [0u8, ..chunk],
            nx: 0u,
            len:0u64
        }
    }

    fn sha1(&mut self) -> [u8,..size] {
        let mut len = self.len;
        // Padding.  Add a 1 bit and 0 bits until 56 bytes mod 64.
        let mut tmp : [u8,..64] = [0u8,..64];
        tmp[0] = 0x80u8;

        let m:uint=(len%64u64) as uint;
        if m < 56 {
            self.write(tmp.slice(0u, 56-m)).unwrap();
        } else {
            self.write(tmp.slice(0u, 64+56-m)).unwrap();
        }

        // Length in bits (=lengh in bytes*8=shift 3 bits to the right).
        len = len << 3;
        for i in range (0u, 8) {
            tmp[i] = (len >> (56u - 8*i)) as u8;
        }
        self.write(tmp.slice(0,8)).unwrap();

        assert!(self.nx == 0);

        let mut digest : [u8,..size]=[0u8,..size];
        for (i, s) in self.h.iter().enumerate() {
            digest[i*4] = (*s >> 24) as u8;
            digest[i*4+1] = (*s >> 16) as u8;
            digest[i*4+2] = (*s >> 8) as u8;
            digest[i*4+3] = *s as u8;
        }
        digest
    }

    fn process_block(&self, data:&[u8]) ->  [u32, ..5]{
        let k:[u32,..4] = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6];

        #[inline]
        fn part(a: u32, b: u32) -> (u32, u32) {
            (a<<5 | a>>(32-5), b<<30 | b>>(32-30))
        }

        let mut w :[u32, ..16] = [0u32, ..16];

        let (mut h0, mut h1, mut h2, mut h3, mut h4) =
            (self.h[0], self.h[1], self.h[2], self.h[3], self.h[4]);

        let mut p = data;

        while p.len() >= chunk {
            for i in range(0u, 16) {
                let j = i * 4;
                w[i] =  (p[j]   as u32)<<24 |
                        (p[j+1] as u32)<<16 |
                        (p[j+2] as u32) <<8 |
                         p[j+3] as u32;
            }

            let (mut a, mut b, mut c, mut d, mut e) = (h0, h1, h2, h3, h4);

            for i in range(0u, 16) {
                let f = b & c | (!b) & d;
                let (a5, b30) = part(a, b);
                let t = a5 + f + e + w[i&0xf] + k[0];
                 b=a; a=t; e=d; d=c; c=b30;
            }
            for i in range(16u, 20) {
                let tmp = w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf];
                w[i&0xf] = tmp<<1 | tmp>>(32-1);
                let f = b & c | (!b) & d;
                let (a5, b30) = part(a, b);
                let t = a5 + f + e + w[i&0xf] + k[0];
                b=a; a=t; e=d; d=c; c=b30;
            }
            for i in range(20u, 40) {
                let tmp = w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf];
                w[i&0xf] = tmp<<1 | tmp>>(32-1);
                let f = b ^ c ^ d;
                let (a5, b30) = part(a, b);
                let t = a5 + f + e + w[i&0xf] + k[1];
                b=a; a=t; e=d; d=c; c=b30;
            }
            for i in range(40u, 60) {
                let tmp = w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf];
                w[i&0xf] = tmp<<1 | tmp>>(32-1);
                let f = ((b | c) & d) | (b & c);
                let (a5, b30) = part(a, b);
                let t = a5 + f + e + w[i&0xf] + k[2];
                b=a; a=t; e=d; d=c; c=b30;
            }
            for i in range(60u, 80) {
                let tmp = w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf];
                w[i&0xf] = tmp<<1 | tmp>>(32-1);
                let f = b ^ c ^ d;
                let (a5, b30) = part(a, b);
                let t = a5 + f + e + w[i&0xf] + k[3];
                b=a; a=t; e=d; d=c; c=b30;
            }
            h0 += a;
            h1 += b;
            h2 += c;
            h3 += d;
            h4 += e;

            p = p.tailn(chunk);
        }
        [h0, h1, h2, h3, h4]
    }
}

impl Writer for Digest {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> IoResult<()> {
        let mut buf_m = buf;

        self.len += buf_m.len() as u64;

        if self.nx > 0 {
            let mut n = buf_m.len();
            if n > chunk - self.nx {
                n = chunk - self.nx;
            }
            for i in range(0,n) {
                self.x[self.nx + i] = *buf_m.get(i).unwrap();
            }
            self.nx += n;
            if self.nx == chunk {
                let x = self.x.as_slice();
                self.h=self.process_block(x);
                self.nx = 0;
            }
            buf_m = buf_m.tailn(n);
        }
        if buf_m.len() >= chunk {
            let n = buf_m.len() &!(chunk - 1);
            let x = self.x.slice_from(n);
            self.h=self.process_block(x);
            buf_m = buf_m.tailn(n);
        }
        let ln=buf_m.len();
        if ln > 0 {
            assert!(self.x.len() >= ln);
            copy_memory(self.x, buf_m);
            self.nx = ln;
        }
        Ok(())
    }
}

#[test]
fn known_sha1s() {
   let input_output = vec![
        (
            "His money is twice tainted: 'taint yours and 'taint mine.",
            vec!(0x59u8, 0x7f, 0x6a, 0x54, 0x0, 0x10, 0xf9, 0x4c,
                0x15, 0xd7, 0x18, 0x6, 0xa9, 0x9a, 0x2c, 0x87, 0x10,
                0xe7, 0x47, 0xbd)
         ),
        (
            "The quick brown fox jumps over the lazy dog",
            vec!(0x2fu8, 0xd4, 0xe1, 0xc6, 0x7a, 0x2d,
            0x28, 0xfc, 0xed, 0x84, 0x9e, 0xe1, 0xbb, 0x76
            , 0xe7, 0x39, 0x1b, 0x93, 0xeb, 0x12)
         ),
        (
            "The quick brown fox jumps over the lazy cog",
            vec!(0xdeu8 ,0x9f ,0x2c ,0x7f ,0xd2 ,0x5e ,0x1b ,0x3a
            ,0xfa ,0xd3 ,0xe8 ,0x5a ,0x0b ,0xd1 ,0x7d ,0x9b
            ,0x10 ,0x0d ,0xb4,0xb3)
         )];

    for &(ref i, ref o) in input_output.iter() {
        let i = i.as_slice();
        let o = o.as_slice();

        let mut d = Digest::new();
        d.write_str(i).unwrap();
        let sha1=d.sha1();

        assert_eq!(sha1.as_slice(), o);
    }
}
<|endoftext|>


<commit_before><commit_msg>Documentation of song<commit_after><|endoftext|>


<commit_before>use core::clone::Clone;
use core::cmp::PartialEq;
use core::iter::Iterator;
use core::mem::size_of;
use core::ops::Add;
use core::ops::Drop;
use core::ops::Index;
use core::option::Option;
use core::ptr;
use core::slice::SliceExt;
use core::str::StrExt;

use common::debug::*;
use common::memory::*;
use common::vec::*;

pub trait ToString {
    fn to_string(&self) -> String;
}

impl ToString for &'static str {
    fn to_string(&self) -> String {
        String::from_str(self)
    }
}

struct Chars<'a> {
    string: &'a String,
    offset: usize
}

impl <'a> Iterator for Chars<'a> {
    type Item = char;
    fn next(&mut self) -> Option<Self::Item>{
        if self.offset < self.string.len() {
            let ret = Option::Some(self.string[self.offset]);
            self.offset += 1;
            return ret;
        }else{
            return Option::None;
        }
    }
}

struct Split<'a> {
    string: &'a String,
    offset: usize,
    seperator: String
}

impl <'a> Iterator for Split<'a> {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item>{
        if self.offset < self.string.len() {
            let start = self.offset;
            let mut len = 0;
            for i in start..self.string.len(){
                if self.seperator == self.string.substr(i, self.seperator.len()){
                    self.offset += self.seperator.len();
                    break;
                }else{
                    self.offset += 1;
                    len += 1;
                }
            }
            return Option::Some(self.string.substr(start, len));
        }else{
            return Option::None;
        }
    }
}

pub struct String {
    pub data: *const char,
    pub length: usize
}

impl String {
    pub fn new() -> String {
        String {
            data: 0 as *const char,
            length: 0
        }
    }

    // TODO FromStr trait
    pub fn from_str(s: &str) -> String {
        let length = s.chars().count();

        if length == 0 {
            return String::new();
        }

        unsafe {
            let data = alloc(length * size_of::<char>()) as *mut char;

            let mut i = 0;
            for c in s.chars() {
                ptr::write(data.offset(i), c);
                i += 1;
            }

            String {
                data: data,
                length: length
            }
        }
    }

    pub fn from_c_slice(s: &[u8]) -> String {
        let mut length = 0;
        for c in s {
            if *c == 0 {
                break;
            }
            length += 1;
        }

        if length == 0 {
            return String::new();
        }

        unsafe {
            let data = alloc(length * size_of::<char>()) as *mut char;

            let mut i = 0;
            for c in s {
                if i >= length {
                    break;
                }
                ptr::write(data.offset(i as isize), ptr::read(c) as char);
                i += 1;
            }

            String {
                data: data,
                length: length
            }
        }
    }

    pub fn from_utf8(vec: &Vec<u8>) -> String {
        // TODO
        return String::from_c_slice(vec.as_slice());
    }

    pub unsafe fn from_c_str(s: *const u8) -> String {
        let mut length = 0;
        loop {
            if ptr::read(((s as usize) + length) as *const u8) == 0 {
                break;
            }
            length += 1;
        }

        if length == 0 {
            return String::new();
        }

        let data = alloc(length * size_of::<char>());

        for i in 0..length {
            ptr::write(((data + i * size_of::<char>()) as *mut char), ptr::read((((s as usize) + i) as *const u8)) as char);
        }

        String {
            data: data as *const char,
            length: length
        }
    }

    pub fn from_num_radix(num: usize, radix: usize) -> String {
        if radix == 0 {
            return String::new();
        }

        let mut length = 1;
        let mut length_num = num;
        while length_num >= radix {
            length_num /= radix;
            length += 1;
        }

        unsafe {
            let data = alloc(length * size_of::<char>()) as *mut char;

            let mut digit_num = num;
            for i in 0..length {
                let mut digit = (digit_num % radix) as u8;
                if digit > 9 {
                    digit += 'A' as u8 - 10;
                }else{
                    digit += '0' as u8;
                }

                ptr::write(data.offset((length - 1 - i) as isize), digit as char);
                digit_num /= radix;
            }

            String {
                data: data,
                length: length
            }
        }
    }

    pub fn from_num_radix_signed(num: isize, radix: usize) -> String {
        if num >= 0 {
            return String::from_num_radix(num as usize, radix);
        }else{
            return "-".to_string() + String::from_num_radix((-num) as usize, radix);
        }
    }

    pub fn from_char(c: char) -> String {
        if c == '\0' {
            return String::new();
        }

        unsafe{
            let data = alloc(size_of::<char>()) as *mut char;
            ptr::write(data, c);

            String {
                data: data,
                length: 1
            }
        }
    }

    pub fn from_num(num: usize) -> String {
        String::from_num_radix(num, 10)
    }

    pub fn from_num_signed(num: isize) -> String {
        String::from_num_radix_signed(num, 10)
    }

    pub fn substr(&self, start: usize, len: usize) -> String {
        let mut i = start;
        if i > self.len() {
            i = self.len();
        }

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

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

        unsafe {
            let data = alloc(length * size_of::<char>()) as *mut char;

            for k in i..j {
                ptr::write(data.offset((k - i) as isize), ptr::read(self.data.offset(k as isize)));
            }

            String {
                data: data,
                length: length
            }
        }
    }

    pub fn find(&self, other: String) -> Option<usize> {
        if self.len() >= other.len() {
            for i in 0..self.len() + 1 - other.len() {
                if self.substr(i, other.len()) == other {
                    return Option::Some(i);
                }
            }
        }
        return Option::None;
    }

    pub fn starts_with(&self, other: String) -> bool {
        if self.len() >= other.len() {
            return self.substr(0, other.len()) == other;
        }else{
            return false;
        }
    }

    pub fn ends_with(&self, other: String) -> bool {
        if self.len() >= other.len() {
            return self.substr(self.len() - other.len(), other.len()) == other;
        }else{
            return false;
        }
    }

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

    pub fn chars(&self) -> Chars {
        Chars {
            string: &self,
            offset: 0
        }
    }

    pub fn split(&self, seperator: String) -> Split {
        Split {
            string: &self,
            offset: 0,
            seperator: seperator
        }
    }

    pub fn to_utf8(&self) -> Vec<u8> {
        let mut vec: Vec<u8> = Vec::new();

        for c in self.chars() {
            let u = c as usize;
            if u < 0x80 {
                vec.push(u as u8);
            }else if u < 0x800 {
                vec.push(0b11000000 | ((u >> 6) as u8 & 0b00011111));
                vec.push(0b10000000 | (u as u8 & 0b00111111));
            }else if u < 0x10000 {
                vec.push(0b11100000 | ((u >> 12) as u8 & 0b00001111));
                vec.push(0b10000000 | ((u >> 6) as u8 & 0b00111111));
                vec.push(0b10000000 | (u as u8 & 0b00111111));
            }else{
                d("Unhandled to_utf8 code ");
                dh(u);
                dl();
            }
        }

        return vec;
    }

    pub unsafe fn to_c_str(&self) -> *const u8 {
        let length = self.len() + 1;

        let data = alloc(length);

        for i in 0..self.len() {
            ptr::write((data + i) as *mut u8, ptr::read(((self.data as usize) + i * size_of::<char>()) as *const char) as u8);
        }
        ptr::write((data + self.len()) as *mut u8, 0);

        data as *const u8
    }

    pub fn to_num_radix(&self, radix: usize) -> usize {
        if radix == 0 {
            return 0;
        }

        let mut num = 0;
        for c in self.chars(){
            let digit;
            if c >= '0' && c <= '9' {
                digit = c as usize - '0' as usize
            } else if c >= 'A' && c <= 'Z' {
                digit = c as usize - 'A' as usize + 10
            } else if c >= 'a' && c <= 'z' {
                digit = c as usize - 'a' as usize + 10
            } else {
                break;
            }

            if digit >= radix {
                break;
            }

            num *= radix;
            num += digit;
        }

        num
    }

    pub fn to_num_radix_signed(&self, radix: usize) -> isize {
        if self[0] == '-' {
            return -(self.substr(1, self.len() - 1).to_num_radix(radix) as isize);
        }else{
            return self.to_num_radix(radix) as isize;
        }
    }

    pub fn to_num(&self) -> usize {
        self.to_num_radix(10)
    }

    pub fn to_num_signed(&self) -> isize {
        self.to_num_radix_signed(10)
    }

    pub fn d(&self){
        for c in self.chars() {
            dc(c);
        }
    }
}

static NULL_CHAR: char = '\0';

impl Index<usize> for String {
    type Output = char;
    fn index<'a>(&'a self, i: usize) -> &'a Self::Output {
        if i >= self.len() {
            // Failure condition
            return &NULL_CHAR;
        }else{
            unsafe{
                return &*(((self.data as usize) + i * size_of::<char>()) as *const char);
            }
        }
    }
}

impl PartialEq for String {
    fn eq(&self, other: &Self) -> bool{
        if self.len() == other.len() {
            for i in 0..self.len() {
                if self[i] != other[i] {
                    return false;
                }
            }

            return true;
        }else{
            return false;
        }
    }
}

impl Clone for String {
    fn clone(&self) -> Self{
        return self.substr(0, self.len());
    }
}

impl Drop for String {
    fn drop(&mut self){
        unsafe {
            unalloc(self.data as usize);
            self.data = 0 as *const char;
            self.length = 0;
        }
    }
}

impl Add for String {
    type Output = String;
    fn add(self, other: String) -> String {
        let length = self.length + other.length;

        if length == 0 {
            return String::new();
        }

        unsafe {
            let data = alloc(length * size_of::<char>()) as *mut char;

            let mut i = 0;
            for c in self.chars() {
                ptr::write(data.offset(i), c);
                i += 1;
            }
            for c in other.chars() {
                ptr::write(data.offset(i), c);
                i += 1;
            }

            String {
                data: data,
                length: length
            }
        }
    }
}

impl<'a> Add<&'a String> for String {
    type Output = String;
    fn add(self, other: &'a String) -> String {
        self + other.clone()
    }
}

impl<'a> Add<&'a str> for String {
    type Output = String;
    fn add(self, other: &'a str) -> String {
        self + String::from_str(other)
    }
}

impl Add<char> for String {
    type Output = String;
    fn add(self, other: char) -> String {
        self + String::from_char(other)
    }
}

impl Add<usize> for String {
    type Output = String;
    fn add(self, other: usize) -> String {
        self + String::from_num(other)
    }
}

impl Add<isize> for String {
    type Output = String;
    fn add(self, other: isize) -> String {
        self + String::from_num_signed(other)
    }
}
<commit_msg>Use Vec as inner string buffer<commit_after>use core::clone::Clone;
use core::cmp::PartialEq;
use core::iter::Iterator;
use core::ops::Add;
use core::ops::Index;
use core::option::Option;
use core::ptr;
use core::slice::SliceExt;
use core::str::StrExt;

use common::debug::*;
use common::memory::*;
use common::vec::*;

pub trait ToString {
    fn to_string(&self) -> String;
}

impl ToString for &'static str {
    fn to_string(&self) -> String {
        String::from_str(self)
    }
}

struct Chars<'a> {
    string: &'a String,
    offset: usize
}

impl <'a> Iterator for Chars<'a> {
    type Item = char;
    fn next(&mut self) -> Option<Self::Item>{
        if self.offset < self.string.len() {
            let ret = Option::Some(self.string[self.offset]);
            self.offset += 1;
            return ret;
        }else{
            return Option::None;
        }
    }
}

struct Split<'a> {
    string: &'a String,
    offset: usize,
    seperator: String
}

impl <'a> Iterator for Split<'a> {
    type Item = String;
    fn next(&mut self) -> Option<Self::Item>{
        if self.offset < self.string.len() {
            let start = self.offset;
            let mut len = 0;
            for i in start..self.string.len(){
                if self.seperator == self.string.substr(i, self.seperator.len()){
                    self.offset += self.seperator.len();
                    break;
                }else{
                    self.offset += 1;
                    len += 1;
                }
            }
            return Option::Some(self.string.substr(start, len));
        }else{
            return Option::None;
        }
    }
}

pub struct String {
    pub vec: Vec<char>
}

impl String {
    pub fn new() -> String {
        String {
            vec: Vec::new()
        }
    }

    // TODO FromStr trait
    pub fn from_str(s: &str) -> String {
        let mut vec: Vec<char> = Vec::new();

        for c in s.chars() {
            vec.push(c);
        }

        String {
            vec: vec
        }
    }

    pub fn from_c_slice(s: &[u8]) -> String {
        let mut vec: Vec<char> = Vec::new();

        for b in s {
            let c = *b as char;
            if c == '\0' {
                break;
            }
            vec.push(c);
        }

        String {
            vec: vec
        }
    }

    pub fn from_utf8(vec: &Vec<u8>) -> String {
        // TODO
        return String::from_c_slice(vec.as_slice());
    }

    pub unsafe fn from_c_str(s: *const u8) -> String {
        let mut vec: Vec<char> = Vec::new();

        let mut i = 0;
        loop {
            let c = ptr::read(s.offset(i)) as char;
            if c == '\0' {
                break;
            }
            vec.push(c);
            i += 1;
        }

        String {
            vec: vec
        }
    }

    pub fn from_num_radix(num: usize, radix: usize) -> String {
        if radix == 0 {
            return String::new();
        }

        let mut length = 1;
        let mut length_num = num;
        while length_num >= radix {
            length_num /= radix;
            length += 1;
        }

        let mut vec: Vec<char> = Vec::new();

        let mut digit_num = num;
        for i in 0..length {
            let mut digit = (digit_num % radix) as u8;
            if digit > 9 {
                digit += 'A' as u8 - 10;
            }else{
                digit += '0' as u8;
            }

            vec.insert(0, digit as char);
            digit_num /= radix;
        }

        String {
            vec: vec
        }
    }

    pub fn from_num_radix_signed(num: isize, radix: usize) -> String {
        if num >= 0 {
            return String::from_num_radix(num as usize, radix);
        }else{
            return "-".to_string() + String::from_num_radix((-num) as usize, radix);
        }
    }

    pub fn from_char(c: char) -> String {
        if c == '\0' {
            return String::new();
        }

        unsafe{
            let mut vec: Vec<char> = Vec::new();
            vec.push(c);

            String {
                vec: vec
            }
        }
    }

    pub fn from_num(num: usize) -> String {
        String::from_num_radix(num, 10)
    }

    pub fn from_num_signed(num: isize) -> String {
        String::from_num_radix_signed(num, 10)
    }

    pub fn substr(&self, start: usize, len: usize) -> String {
        let mut i = start;
        if i > self.len() {
            i = self.len();
        }

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

        let mut vec: Vec<char> = Vec::new();

        for k in i..j {
            vec.push(self[k]);
        }

        String {
            vec: vec
        }
    }

    pub fn find(&self, other: String) -> Option<usize> {
        if self.len() >= other.len() {
            for i in 0..self.len() + 1 - other.len() {
                if self.substr(i, other.len()) == other {
                    return Option::Some(i);
                }
            }
        }
        return Option::None;
    }

    pub fn starts_with(&self, other: String) -> bool {
        if self.len() >= other.len() {
            return self.substr(0, other.len()) == other;
        }else{
            return false;
        }
    }

    pub fn ends_with(&self, other: String) -> bool {
        if self.len() >= other.len() {
            return self.substr(self.len() - other.len(), other.len()) == other;
        }else{
            return false;
        }
    }

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

    pub fn chars(&self) -> Chars {
        Chars {
            string: &self,
            offset: 0
        }
    }

    pub fn split(&self, seperator: String) -> Split {
        Split {
            string: &self,
            offset: 0,
            seperator: seperator
        }
    }

    pub fn to_utf8(&self) -> Vec<u8> {
        let mut vec: Vec<u8> = Vec::new();

        for c in self.chars() {
            let u = c as usize;
            if u < 0x80 {
                vec.push(u as u8);
            }else if u < 0x800 {
                vec.push(0b11000000 | ((u >> 6) as u8 & 0b00011111));
                vec.push(0b10000000 | (u as u8 & 0b00111111));
            }else if u < 0x10000 {
                vec.push(0b11100000 | ((u >> 12) as u8 & 0b00001111));
                vec.push(0b10000000 | ((u >> 6) as u8 & 0b00111111));
                vec.push(0b10000000 | (u as u8 & 0b00111111));
            }else{
                d("Unhandled to_utf8 code ");
                dh(u);
                dl();
            }
        }

        return vec;
    }

    pub unsafe fn to_c_str(&self) -> *const u8 {
        let length = self.len() + 1;

        let data = alloc(length) as *mut u8;

        for i in 0..self.len() {
            ptr::write(data.offset(i as isize), self[i] as u8);
        }
        ptr::write(data.offset(self.len() as isize), 0);

        data as *const u8
    }

    pub fn to_num_radix(&self, radix: usize) -> usize {
        if radix == 0 {
            return 0;
        }

        let mut num = 0;
        for c in self.chars(){
            let digit;
            if c >= '0' && c <= '9' {
                digit = c as usize - '0' as usize
            } else if c >= 'A' && c <= 'Z' {
                digit = c as usize - 'A' as usize + 10
            } else if c >= 'a' && c <= 'z' {
                digit = c as usize - 'a' as usize + 10
            } else {
                break;
            }

            if digit >= radix {
                break;
            }

            num *= radix;
            num += digit;
        }

        num
    }

    pub fn to_num_radix_signed(&self, radix: usize) -> isize {
        if self[0] == '-' {
            return -(self.substr(1, self.len() - 1).to_num_radix(radix) as isize);
        }else{
            return self.to_num_radix(radix) as isize;
        }
    }

    pub fn to_num(&self) -> usize {
        self.to_num_radix(10)
    }

    pub fn to_num_signed(&self) -> isize {
        self.to_num_radix_signed(10)
    }

    pub fn d(&self){
        for c in self.chars() {
            dc(c);
        }
    }
}

static NULL_CHAR: char = '\0';

impl Index<usize> for String {
    type Output = char;
    fn index<'a>(&'a self, i: usize) -> &'a Self::Output {
        match self.vec.get(i) {
            Option::Some(c) => return c,
            Option::None => return &NULL_CHAR
        }
    }
}

impl PartialEq for String {
    fn eq(&self, other: &Self) -> bool{
        if self.len() == other.len() {
            for i in 0..self.len() {
                if self[i] != other[i] {
                    return false;
                }
            }

            return true;
        }else{
            return false;
        }
    }
}

impl Clone for String {
    fn clone(&self) -> Self{
        return self.substr(0, self.len());
    }
}

impl Add for String {
    type Output = String;
    fn add(self, other: String) -> String {
        let mut vec: Vec<char> = self.vec.clone();

        let mut i = 0;
        for c in other.chars() {
            vec.push(c);
        }

        String {
            vec: vec
        }
    }
}

impl<'a> Add<&'a String> for String {
    type Output = String;
    fn add(self, other: &'a String) -> String {
        self + other.clone()
    }
}

impl<'a> Add<&'a str> for String {
    type Output = String;
    fn add(self, other: &'a str) -> String {
        self + String::from_str(other)
    }
}

impl Add<char> for String {
    type Output = String;
    fn add(self, other: char) -> String {
        self + String::from_char(other)
    }
}

impl Add<usize> for String {
    type Output = String;
    fn add(self, other: usize) -> String {
        self + String::from_num(other)
    }
}

impl Add<isize> for String {
    type Output = String;
    fn add(self, other: isize) -> String {
        self + String::from_num_signed(other)
    }
}
<|endoftext|>