<commit_before><commit_msg>[State Sync] Add simple tests for the storage service.<commit_after>// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

#![forbid(unsafe_code)]

use crate::{StorageReader, StorageServiceServer};
use anyhow::Result;
use claim::{assert_none, assert_some};
use diem_crypto::{ed25519::Ed25519PrivateKey, HashValue, PrivateKey, SigningKey, Uniform};
use diem_infallible::RwLock;
use diem_types::{
    account_address::AccountAddress,
    account_state_blob::{AccountStateBlob, AccountStateWithProof},
    block_info::BlockInfo,
    chain_id::ChainId,
    contract_event::{ContractEvent, EventByVersionWithProof, EventWithProof},
    epoch_change::EpochChangeProof,
    event::EventKey,
    ledger_info::{LedgerInfo, LedgerInfoWithSignatures},
    proof::{SparseMerkleProof, TransactionListProof},
    state_proof::StateProof,
    transaction::{
        AccountTransactionsWithProof, RawTransaction, Script, SignedTransaction, Transaction,
        TransactionListWithProof, TransactionPayload, TransactionToCommit, TransactionWithProof,
        Version,
    },
};
use move_core_types::language_storage::TypeTag;
use std::{collections::BTreeMap, sync::Arc};
use storage_interface::{DbReader, DbReaderWriter, DbWriter, Order, StartupInfo, TreeState};
use storage_service_types::{
    DataSummary, EpochEndingLedgerInfoRequest, ProtocolMetadata, ServerProtocolVersion,
    StorageServerSummary, StorageServiceRequest, StorageServiceResponse,
    TransactionsWithProofRequest,
};

// TODO(joshlind): Expand these test cases to better test storage interaction
// and functionality. This will likely require a better mock db abstraction.

#[test]
fn test_get_server_protocol_version() {
    // Create a storage service server
    let storage_server = create_storage_server();

    // Process a request to fetch the protocol version
    let version_request = StorageServiceRequest::GetServerProtocolVersion;
    let version_response = storage_server.handle_request(version_request).unwrap();

    // Verify the response is correct
    let expected_protocol_version = ServerProtocolVersion {
        protocol_version: 1,
    };
    assert_eq!(
        version_response,
        StorageServiceResponse::ServerProtocolVersion(expected_protocol_version)
    );
}

#[test]
fn test_get_storage_server_summary() {
    // Create a storage service server
    let storage_server = create_storage_server();

    // Process a request to fetch the storage summary
    let summary_request = StorageServiceRequest::GetStorageServerSummary;
    let summary_response = storage_server.handle_request(summary_request).unwrap();

    // Verify the response is correct
    let expected_server_summary = StorageServerSummary {
        protocol_metadata: ProtocolMetadata {
            max_transaction_chunk_size: 1000,
        },
        data_summary: DataSummary {
            highest_transaction_version: 100,
            lowest_transaction_version: 0,
            highest_epoch: 10,
            lowest_epoch: 0,
        },
    };
    assert_eq!(
        summary_response,
        StorageServiceResponse::StorageServerSummary(expected_server_summary)
    );
}

#[test]
fn test_get_transactions_with_proof_events() {
    // Create a storage service server
    let storage_server = create_storage_server();

    // Create a request to fetch transactions with a proof
    let start_version = 0;
    let expected_num_transactions = 10;
    let transactions_proof_request =
        StorageServiceRequest::GetTransactionsWithProof(TransactionsWithProofRequest {
            proof_version: 100,
            start_version,
            expected_num_transactions,
            include_events: true,
        });

    // Process the request
    let transactions_proof_response = storage_server
        .handle_request(transactions_proof_request)
        .unwrap();

    // Verify the response is correct
    match transactions_proof_response {
        StorageServiceResponse::TransactionsWithProof(transactions_with_proof) => {
            assert_eq!(
                transactions_with_proof.transactions.len(),
                expected_num_transactions as usize
            );
            assert_eq!(
                transactions_with_proof.first_transaction_version,
                Some(start_version)
            );
            assert_some!(transactions_with_proof.events);
        }
        result => {
            panic!("Expected transactions with proof but got: {:?}", result);
        }
    };
}

#[test]
fn test_get_transactions_with_proof_no_events() {
    // Create a storage service server
    let storage_server = create_storage_server();

    // Create a request to fetch transactions with a proof (excluding events)
    let start_version = 10;
    let expected_num_transactions = 20;
    let transactions_proof_request =
        StorageServiceRequest::GetTransactionsWithProof(TransactionsWithProofRequest {
            proof_version: 1000,
            start_version,
            expected_num_transactions,
            include_events: false,
        });

    // Process the request
    let transactions_proof_response = storage_server
        .handle_request(transactions_proof_request)
        .unwrap();

    // Verify the response is correct
    match transactions_proof_response {
        StorageServiceResponse::TransactionsWithProof(transactions_with_proof) => {
            assert_eq!(
                transactions_with_proof.transactions.len(),
                expected_num_transactions as usize
            );
            assert_eq!(
                transactions_with_proof.first_transaction_version,
                Some(start_version)
            );
            assert_none!(transactions_with_proof.events);
        }
        result => {
            panic!("Expected transactions with proof but got: {:?}", result);
        }
    };
}

#[test]
fn test_get_epoch_ending_ledger_infos() {
    // Create a storage service server
    let storage_server = create_storage_server();

    // Create a request to fetch transactions with a proof (excluding events)
    let start_epoch = 11;
    let expected_end_epoch = 21;
    let epoch_ending_li_request =
        StorageServiceRequest::GetEpochEndingLedgerInfos(EpochEndingLedgerInfoRequest {
            start_epoch,
            expected_end_epoch,
        });

    // Process the request
    let epoch_ending_li_response = storage_server
        .handle_request(epoch_ending_li_request)
        .unwrap();

    // Verify the response is correct
    match epoch_ending_li_response {
        StorageServiceResponse::EpochEndingLedgerInfos(epoch_change_proof) => {
            assert_eq!(
                epoch_change_proof.ledger_info_with_sigs.len(),
                (expected_end_epoch - start_epoch + 1) as usize
            );
            assert_eq!(epoch_change_proof.more, false);

            for (i, epoch_ending_li) in epoch_change_proof.ledger_info_with_sigs.iter().enumerate()
            {
                assert_eq!(
                    epoch_ending_li.ledger_info().epoch(),
                    (i as u64) + start_epoch
                );
            }
        }
        result => {
            panic!("Expected epoch ending ledger infos but got: {:?}", result);
        }
    };
}

fn create_storage_server() -> StorageServiceServer<StorageReader> {
    let storage = Arc::new(RwLock::new(DbReaderWriter::new(MockDbReaderWriter)));
    let storage_reader = StorageReader::new(storage);
    StorageServiceServer::new(storage_reader)
}

fn create_test_event(sequence_number: u64) -> ContractEvent {
    ContractEvent::new(
        EventKey::new_from_address(&AccountAddress::random(), 0),
        sequence_number,
        TypeTag::Bool,
        bcs::to_bytes(&0).unwrap(),
    )
}

fn create_test_transaction(sequence_number: u64) -> Transaction {
    let private_key = Ed25519PrivateKey::generate_for_testing();
    let public_key = private_key.public_key();

    let transaction_payload = TransactionPayload::Script(Script::new(vec![], vec![], vec![]));
    let raw_transaction = RawTransaction::new(
        AccountAddress::random(),
        sequence_number,
        transaction_payload,
        0,
        0,
        "".into(),
        0,
        ChainId::new(10),
    );
    let signed_transaction = SignedTransaction::new(
        raw_transaction.clone(),
        public_key,
        private_key.sign(&raw_transaction),
    );

    Transaction::UserTransaction(signed_transaction)
}

fn create_test_ledger_info_with_sigs(epoch: u64, version: u64) -> LedgerInfoWithSignatures {
    // Create a mock ledger info with signatures
    let ledger_info = LedgerInfo::new(
        BlockInfo::new(
            epoch,
            0,
            HashValue::zero(),
            HashValue::zero(),
            version,
            0,
            None,
        ),
        HashValue::zero(),
    );
    LedgerInfoWithSignatures::new(ledger_info, BTreeMap::new())
}

/// This is a mock of the DbReader and DbWriter for unit testing.
struct MockDbReaderWriter;

impl DbReader for MockDbReaderWriter {
    fn get_epoch_ending_ledger_infos(
        &self,
        start_epoch: u64,
        end_epoch: u64,
    ) -> Result<EpochChangeProof> {
        let mut ledger_info_with_sigs = vec![];
        for epoch in start_epoch..end_epoch + 1 {
            ledger_info_with_sigs.push(create_test_ledger_info_with_sigs(epoch, 0));
        }

        Ok(EpochChangeProof {
            ledger_info_with_sigs,
            more: false,
        })
    }

    fn get_transactions(
        &self,
        start_version: Version,
        batch_size: u64,
        _ledger_version: Version,
        fetch_events: bool,
    ) -> Result<TransactionListWithProof> {
        // Create mock events
        let events = if fetch_events {
            let mut events = vec![];
            for i in 0..batch_size {
                events.push(vec![create_test_event(i)]);
            }
            Some(events)
        } else {
            None
        };

        // Create mock transactions
        let mut transactions = vec![];
        for i in 0..batch_size {
            transactions.push(create_test_transaction(i))
        }

        Ok(TransactionListWithProof {
            transactions,
            events,
            first_transaction_version: Some(start_version),
            proof: TransactionListProof::new_empty(),
        })
    }

    /// Returns events by given event key
    fn get_events(
        &self,
        _event_key: &EventKey,
        _start: u64,
        _order: Order,
        _limit: u64,
    ) -> Result<Vec<(u64, ContractEvent)>> {
        unimplemented!()
    }

    /// Returns events by given event key
    fn get_events_with_proofs(
        &self,
        _event_key: &EventKey,
        _start: u64,
        _order: Order,
        _limit: u64,
        _known_version: Option<u64>,
    ) -> Result<Vec<EventWithProof>> {
        unimplemented!()
    }

    fn get_block_timestamp(&self, _version: u64) -> Result<u64> {
        unimplemented!()
    }

    fn get_event_by_version_with_proof(
        &self,
        _event_key: &EventKey,
        _version: u64,
        _proof_version: u64,
    ) -> Result<EventByVersionWithProof> {
        unimplemented!()
    }

    fn get_latest_account_state(
        &self,
        _address: AccountAddress,
    ) -> Result<Option<AccountStateBlob>> {
        unimplemented!()
    }

    /// Returns the latest ledger info.
    fn get_latest_ledger_info(&self) -> Result<LedgerInfoWithSignatures> {
        Ok(create_test_ledger_info_with_sigs(10, 100))
    }

    fn get_startup_info(&self) -> Result<Option<StartupInfo>> {
        unimplemented!()
    }

    fn get_account_transaction(
        &self,
        _address: AccountAddress,
        _seq_num: u64,
        _include_events: bool,
        _ledger_version: Version,
    ) -> Result<Option<TransactionWithProof>> {
        unimplemented!()
    }

    fn get_account_transactions(
        &self,
        _address: AccountAddress,
        _start_seq_num: u64,
        _limit: u64,
        _include_events: bool,
        _ledger_version: Version,
    ) -> Result<AccountTransactionsWithProof> {
        unimplemented!()
    }

    fn get_state_proof_with_ledger_info(
        &self,
        _known_version: u64,
        _ledger_info: LedgerInfoWithSignatures,
    ) -> Result<StateProof> {
        unimplemented!()
    }

    fn get_state_proof(&self, _known_version: u64) -> Result<StateProof> {
        unimplemented!()
    }

    fn get_account_state_with_proof(
        &self,
        _address: AccountAddress,
        _version: Version,
        _ledger_version: Version,
    ) -> Result<AccountStateWithProof> {
        unimplemented!()
    }

    fn get_account_state_with_proof_by_version(
        &self,
        _address: AccountAddress,
        _version: Version,
    ) -> Result<(
        Option<AccountStateBlob>,
        SparseMerkleProof<AccountStateBlob>,
    )> {
        unimplemented!()
    }

    fn get_latest_state_root(&self) -> Result<(Version, HashValue)> {
        unimplemented!()
    }

    fn get_latest_tree_state(&self) -> Result<TreeState> {
        unimplemented!()
    }

    fn get_epoch_ending_ledger_info(
        &self,
        _known_version: u64,
    ) -> Result<LedgerInfoWithSignatures> {
        unimplemented!()
    }
}

impl DbWriter for MockDbReaderWriter {
    fn save_transactions(
        &self,
        _txns_to_commit: &[TransactionToCommit],
        _first_version: Version,
        _ledger_info_with_sigs: Option<&LedgerInfoWithSignatures>,
    ) -> Result<()> {
        unimplemented!()
    }
}
<|endoftext|>


<commit_before><commit_msg>Implemented .get_property but it does not work<commit_after><|endoftext|>


<commit_before><commit_msg>Add blank longnam file<commit_after>/*
ffclos
ffcopy
ffcrim
ffcrtb
ffdcol
ffdhdu
ffflmd
ffgbcl
ffgcdw
ffgcno
ffgcvs
ffghdn
ffghdt
ffgidm
ffgiet
ffgisz
ffgkys
ffgncl
ffgnrw
ffgpv
ffgsv
fficol
ffinit
ffmahd
ffmnhd
ffopen
ffpcl
ffpcls
ffphps
ffpkyj
ffpkys
ffppr
ffpss
ffrsim
ffthdu
*/
<|endoftext|>


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

#![feature(fn_traits)]

use std::ops::Fn;

fn say(x: u32, y: u32) {
    println!("{} {}", x, y);
}

fn main() {
    Fn::call(&say, (1, 2));
}
<|endoftext|>


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

#[deriving(Clone, Eq)]
pub struct PkgId {
    path: ~str,
    name: ~str,
    version: Option<~str>,
}

impl ToStr for PkgId {
    fn to_str(&self) -> ~str {
        let version = match self.version {
            None => "0.0",
            Some(ref version) => version.as_slice(),
        };
        if self.path.is_empty() {
            format!("{}\\#{}", self.name, version)
        } else {
            format!("{}/{}\\#{}", self.path, self.name, version)
        }
    }
}

impl FromStr for PkgId {
    fn from_str(s: &str) -> Option<PkgId> {
        let hash_idx = match s.find('#') {
            None => s.len(),
            Some(idx) => idx,
        };
        let prefix = s.slice_to(hash_idx);
        let name_idx = match prefix.rfind('/') {
            None => 0,
            Some(idx) => idx + 1,
        };
        if name_idx >= prefix.len() {
            return None;
        }
        let name = prefix.slice_from(name_idx);
        if name.len() <= 0 {
            return None;
        }

        let path = if name_idx == 0 {
            ""
        } else {
            prefix.slice_to(name_idx - 1)
        };
        let check_path = Path::new(path);
        if !check_path.is_relative() {
            return None;
        }

        let version = match s.find('#') {
            None => None,
            Some(idx) => {
                if idx >= s.len() {
                    None
                } else {
                    let v = s.slice_from(idx + 1);
                    if v.is_empty() {
                        None
                    } else {
                        Some(v.to_owned())
                    }
                }
            }
        };

        Some(PkgId{
            path: path.to_owned(),
            name: name.to_owned(),
            version: version,
        })
    }
}

impl PkgId {
    pub fn version_or_default<'a>(&'a self) -> &'a str {
        match self.version {
            None => "0.0",
            Some(ref version) => version.as_slice(),
        }
    }
}

#[test]
fn bare_name() {
    let pkgid: PkgId = from_str("foo").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"foo");
    assert_eq!(pkgid.version, None);
    assert_eq!(pkgid.path, ~"");
}

#[test]
fn bare_name_single_char() {
    let pkgid: PkgId = from_str("f").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"f");
    assert_eq!(pkgid.version, None);
    assert_eq!(pkgid.path, ~"");
}

#[test]
fn empty_pkgid() {
    let pkgid: Option<PkgId> = from_str("");
    assert!(pkgid.is_none());
}

#[test]
fn simple_path() {
    let pkgid: PkgId = from_str("example.com/foo/bar").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"bar");
    assert_eq!(pkgid.version, None);
    assert_eq!(pkgid.path, ~"example.com/foo");
}

#[test]
fn simple_version() {
    let pkgid: PkgId = from_str("foo#1.0").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"foo");
    assert_eq!(pkgid.version, Some(~"1.0"));
    assert_eq!(pkgid.path, ~"");
}

#[test]
fn absolute_path() {
    let pkgid: Option<PkgId> = from_str("/foo/bar");
    assert!(pkgid.is_none());
}

#[test]
fn path_and_version() {
    let pkgid: PkgId = from_str("example.com/foo/bar#1.0").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"bar");
    assert_eq!(pkgid.version, Some(~"1.0"));
    assert_eq!(pkgid.path, ~"example.com/foo");
}

#[test]
fn single_chars() {
    let pkgid: PkgId = from_str("a/b#1").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"b");
    assert_eq!(pkgid.version, Some(~"1"));
    assert_eq!(pkgid.path, ~"a");
}

#[test]
fn missing_version() {
    let pkgid: PkgId = from_str("foo#").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"foo");
    assert_eq!(pkgid.version, None);
    assert_eq!(pkgid.path, ~"");
}<commit_msg>Change pkgid parser to allow overriding the inferred crate name.<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.

/// PkgIds identify crates and include the crate name and optionall a path and
/// version. In the full form, they look like relative URLs. Example:
/// `github.com/mozilla/rust#std:1.0` would be a package ID with a path of
/// `gitub.com/mozilla/rust` and a crate name of `std` with a version of
/// `1.0`. If no crate name is given after the hash, the name is inferred to
/// be the last component of the path. If no version is given, it is inferred
/// to be `0.0`.
#[deriving(Clone, Eq)]
pub struct PkgId {
    /// A path which represents the codes origin. By convention this is the
    /// URL, without `http://` or `https://` prefix, to the crate's repository
    path: ~str,
    /// The name of the crate.
    name: ~str,
    /// The version of the crate.
    version: Option<~str>,
}

impl ToStr for PkgId {
    fn to_str(&self) -> ~str {
        let version = match self.version {
            None => "0.0",
            Some(ref version) => version.as_slice(),
        };
        if self.path == self.name || self.path.ends_with(format!("/{}", self.name)) {
            format!("{}\\#{}", self.path, version)
        } else {
            format!("{}\\#{}:{}", self.path, self.name, version)
        }
    }
}

impl FromStr for PkgId {
    fn from_str(s: &str) -> Option<PkgId> {
        let pieces: ~[&str] = s.splitn('#', 1).collect();
        let path = pieces[0].to_owned();

        if path.starts_with("/") || path.ends_with("/") ||
            path.starts_with(".") || path.is_empty() {
            return None;
        }

        let path_pieces: ~[&str] = path.rsplitn('/', 1).collect();
        let inferred_name = path_pieces[0];

        let (name, version) = if pieces.len() == 1 {
            (inferred_name.to_owned(), None)
        } else {
            let hash_pieces: ~[&str] = pieces[1].splitn(':', 1).collect();
            let (hash_name, hash_version) = if hash_pieces.len() == 1 {
                ("", hash_pieces[0])
            } else {
                (hash_pieces[0], hash_pieces[1])
            };

            let name = if !hash_name.is_empty() {
                hash_name.to_owned()
            } else {
                inferred_name.to_owned()
            };

            let version = if !hash_version.is_empty() {
                Some(hash_version.to_owned())
            } else {
                None
            };

            (name, version)
        };

        Some(PkgId {
            path: path,
            name: name,
            version: version,
        })
    }
}

impl PkgId {
    pub fn version_or_default<'a>(&'a self) -> &'a str {
        match self.version {
            None => "0.0",
            Some(ref version) => version.as_slice(),
        }
    }
}

#[test]
fn bare_name() {
    let pkgid: PkgId = from_str("foo").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"foo");
    assert_eq!(pkgid.version, None);
    assert_eq!(pkgid.path, ~"foo");
}

#[test]
fn bare_name_single_char() {
    let pkgid: PkgId = from_str("f").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"f");
    assert_eq!(pkgid.version, None);
    assert_eq!(pkgid.path, ~"f");
}

#[test]
fn empty_pkgid() {
    let pkgid: Option<PkgId> = from_str("");
    assert!(pkgid.is_none());
}

#[test]
fn simple_path() {
    let pkgid: PkgId = from_str("example.com/foo/bar").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"bar");
    assert_eq!(pkgid.version, None);
    assert_eq!(pkgid.path, ~"example.com/foo/bar");
}

#[test]
fn simple_version() {
    let pkgid: PkgId = from_str("foo#1.0").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"foo");
    assert_eq!(pkgid.version, Some(~"1.0"));
    assert_eq!(pkgid.path, ~"foo");
}

#[test]
fn absolute_path() {
    let pkgid: Option<PkgId> = from_str("/foo/bar");
    assert!(pkgid.is_none());
}

#[test]
fn path_ends_with_slash() {
    let pkgid: Option<PkgId> = from_str("foo/bar/");
    assert!(pkgid.is_none());
}

#[test]
fn path_and_version() {
    let pkgid: PkgId = from_str("example.com/foo/bar#1.0").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"bar");
    assert_eq!(pkgid.version, Some(~"1.0"));
    assert_eq!(pkgid.path, ~"example.com/foo/bar");
}

#[test]
fn single_chars() {
    let pkgid: PkgId = from_str("a/b#1").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"b");
    assert_eq!(pkgid.version, Some(~"1"));
    assert_eq!(pkgid.path, ~"a/b");
}

#[test]
fn missing_version() {
    let pkgid: PkgId = from_str("foo#").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"foo");
    assert_eq!(pkgid.version, None);
    assert_eq!(pkgid.path, ~"foo");
}

#[test]
fn path_and_name() {
    let pkgid: PkgId = from_str("foo/rust-bar#bar:1.0").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"bar");
    assert_eq!(pkgid.version, Some(~"1.0"));
    assert_eq!(pkgid.path, ~"foo/rust-bar");
}

#[test]
fn empty_name() {
    let pkgid: PkgId = from_str("foo/bar#:1.0").expect("valid pkgid");
    assert_eq!(pkgid.name, ~"bar");
    assert_eq!(pkgid.version, Some(~"1.0"));
    assert_eq!(pkgid.path, ~"foo/bar");
}
<|endoftext|>


<commit_before><commit_msg>(feat) Chain trait and DefaultChain implementation.<commit_after><|endoftext|>


<commit_before><commit_msg>remove bttv emotes that are not actually global on the global endpoint<commit_after><|endoftext|>


<commit_before><commit_msg>Refactor(core test): reorg test, no functional changes<commit_after><|endoftext|>


<commit_before><commit_msg>Add pubsub_channel.<commit_after>use std::sync::mpsc::{channel, Sender, SendError, Receiver};
use std::error::Error;

pub struct Publisher<T> {
    senders: Vec<Sender<T>>
}

pub type Subscriber<T> = Receiver<T>;

impl<T: Clone> Publisher<T> {
    pub fn new() -> Publisher<T> {
        Publisher {
            senders: Vec::new(),
        }
    }

    pub fn subscribe(&mut self, sub: Sender<T>) {
        self.senders.push(sub);
    }

    pub fn publish(&mut self, sub: T) -> Result<(), SendError<T>> {
        for s in self.senders.iter() {
            let res = s.send(sub.clone());
            if res.is_err() {
                return res
            }
        }
        Ok(())
    }
}

pub fn pubsub_channel<T: Clone>(num_subs: usize) -> (Publisher<T>, Vec<Subscriber<T>>) {
        let mut p = Publisher::new();
        let mut vec = Vec::new();

        for _a in 0..num_subs {
            let (sender, sub) = channel();
            p.subscribe(sender);
            vec.push(sub);
        }
        (p, vec)
}

#[cfg(test)]
mod test {
    use super::{Publisher, Subscriber, pubsub_channel};
    use std::sync::mpsc::{channel};

    #[test]
    fn test_pubsub() {
        let (sn1, s1) = channel::<usize>();
        let (sn2, s2) = channel::<usize>();
        let mut p = Publisher::new();
        p.subscribe(sn1);
        p.subscribe(sn2);

        let res = p.publish(9);
        assert!(res.is_ok());

        let res = s1.recv();
        assert!(res.ok().unwrap() == 9);
        let res = s2.recv();
        assert!(res.ok().unwrap() == 9);
    }

    #[test]
    fn test_pubsub_channel() {
        let (mut p, subs) = pubsub_channel::<usize>(3);

        let res = p.publish(9);
        assert!(res.is_ok());
        assert!(subs.len() == 3);

        for s in subs.iter() {
            let res = s.recv();
            assert!(res.ok().unwrap() == 9);
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>trying out the key press constants<commit_after><|endoftext|>


<commit_before><commit_msg>	modified:   src/main.rs<commit_after><|endoftext|>


<commit_before><commit_msg>progress on the prompt<commit_after><|endoftext|>


<commit_before><commit_msg>Fixed multi-monitor issue<commit_after><|endoftext|>


<commit_before><commit_msg>getopts: add skeleton<commit_after><|endoftext|>


<commit_before><commit_msg>Improve test file opening<commit_after><|endoftext|>


<commit_before><commit_msg>Added fairness to simulation<commit_after><|endoftext|>


<commit_before><commit_msg>Build PostgreSQL connection string<commit_after><|endoftext|>


<commit_before><commit_msg>render equipped working<commit_after><|endoftext|>


<commit_before>use std::num::SignedInt;

#[derive(FromPrimitive, Debug)]
pub enum FilterType {
    NoFilter = 0,
    Sub = 1,
    Up = 2,
    Avg = 3,
    Paeth = 4
}

fn filter_paeth(a: u8, b: u8, c: u8) -> u8 {
    let ia = a as i16;
    let ib = b as i16;
    let ic = c as i16;

    let p = ia + ib - ic;

    let pa = (p - ia).abs();
    let pb = (p - ib).abs();
    let pc = (p - ic).abs();

    if pa <= pb && pa <= pc {
        a
    } else if pb <= pc {
        b
    } else {
        c
    }
}

pub fn unfilter(filter: FilterType, bpp: usize, previous: &[u8], current: &mut [u8]) {
    let len = current.len();

    match filter {
        FilterType::NoFilter => (),
        FilterType::Sub => {
            for i in (bpp..len) {
                current[i] += current[i - bpp];
            }
        }
        FilterType::Up => {
            for i in (0..len) {
                current[i] += previous[i];
            }
        }
        FilterType::Avg => {
            for i in (0..bpp) {
                current[i] += previous[i] / 2;
            }

            for i in (bpp..len) {
                current[i] += ((current[i - bpp] as i16 + previous[i] as i16) / 2) as u8;
            }
        }
        FilterType::Paeth => {
            for i in (0..bpp) {
                current[i] += filter_paeth(0, previous[i], 0);
            }

            for i in (bpp..len) {
                current[i] += filter_paeth(current[i - bpp], previous[i], previous[i - bpp]);
            }
        }
    }
}

pub fn filter(method: FilterType, bpp: usize, previous: &[u8], current: &mut [u8]) {
    let len  = current.len();
    let orig: Vec<u8> = (0..len).map(| i | current[i]).collect();

    match method {
        FilterType::NoFilter => (),
        FilterType::Sub      => {
            for i in (bpp..len) {
                current[i] = orig[i] - orig[i - bpp];
            }
        }
        FilterType::Up       => {
            for i in (0..len) {
                current[i] = orig[i] - previous[i];
            }
        }
        FilterType::Avg  => {
            for i in (0..bpp) {
                current[i] = orig[i] - previous[i] / 2;
            }

            for i in (bpp..len) {
                current[i] = orig[i] - ((orig[i - bpp] as i16 + previous[i] as i16) / 2) as u8;
            }
        }
        FilterType::Paeth    => {
            for i in (0..bpp) {
                current[i] = orig[i] - filter_paeth(0, previous[i], 0);
            }

            for i in (bpp..len) {
                current[i] = orig[i] - filter_paeth(orig[i - bpp], previous[i], previous[i - bpp]);
            }
        }
    }
}
<commit_msg>Save one allocation per line in the PNG encoder<commit_after>use std::num::SignedInt;
use std::iter::range_step_inclusive;

#[derive(FromPrimitive, Debug)]
pub enum FilterType {
    NoFilter = 0,
    Sub = 1,
    Up = 2,
    Avg = 3,
    Paeth = 4
}

fn filter_paeth(a: u8, b: u8, c: u8) -> u8 {
    let ia = a as i16;
    let ib = b as i16;
    let ic = c as i16;

    let p = ia + ib - ic;

    let pa = (p - ia).abs();
    let pb = (p - ib).abs();
    let pc = (p - ic).abs();

    if pa <= pb && pa <= pc {
        a
    } else if pb <= pc {
        b
    } else {
        c
    }
}

pub fn unfilter(filter: FilterType, bpp: usize, previous: &[u8], current: &mut [u8]) {
    let len = current.len();

    match filter {
        FilterType::NoFilter => (),
        FilterType::Sub => {
            for i in (bpp..len) {
                current[i] += current[i - bpp];
            }
        }
        FilterType::Up => {
            for i in (0..len) {
                current[i] += previous[i];
            }
        }
        FilterType::Avg => {
            for i in (0..bpp) {
                current[i] += previous[i] / 2;
            }

            for i in (bpp..len) {
                current[i] += ((current[i - bpp] as i16 + previous[i] as i16) / 2) as u8;
            }
        }
        FilterType::Paeth => {
            for i in (0..bpp) {
                current[i] += filter_paeth(0, previous[i], 0);
            }

            for i in (bpp..len) {
                current[i] += filter_paeth(current[i - bpp], previous[i], previous[i - bpp]);
            }
        }
    }
}

pub fn filter(method: FilterType, bpp: usize, previous: &[u8], current: &mut [u8]) {
    let len  = current.len();

    match method {
        FilterType::NoFilter => (),
        FilterType::Sub      => {
            for i in range_step_inclusive(len-1, bpp, -1) {
                current[i] = current[i] - current[i - bpp];
            }
        }
        FilterType::Up       => {
            for i in (0..len) {
                current[i] = current[i] - previous[i];
            }
        }
        FilterType::Avg  => {
            for i in (0..bpp) {
                current[i] = current[i] - previous[i] / 2;
            }

            for i in range_step_inclusive(len-1, bpp, -1) {
                current[i] = current[i] - ((current[i - bpp] as i16 + previous[i] as i16) / 2) as u8;
            }
        }
        FilterType::Paeth    => {
            for i in (0..bpp) {
                current[i] = current[i] - filter_paeth(0, previous[i], 0);
            }

            for i in range_step_inclusive(len-1, bpp, -1) {
                current[i] = current[i] - filter_paeth(current[i - bpp], previous[i], previous[i - bpp]);
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Reformat some test data.<commit_after><|endoftext|>


<commit_before>use std::iter::Peekable;
use std::num::ParseIntError;
use xml::reader::events::*;
use xml::reader::Events;
use hyper::client::response::*;
use std::collections::HashMap;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use std::path::Path;
use std::fs;
use std::error::Error;
use xml::reader::EventReader;

/// generic Error for XML parsing
#[derive(Debug)]
pub struct XmlParseError(pub String);

impl XmlParseError {
	pub fn new(msg: &str) -> XmlParseError {
		XmlParseError(msg.to_string())
	}
}

/// syntactic sugar for the XML event stack we pass around
pub type XmlStack<'a> = Peekable<Events<'a, Response>>;

pub trait Peek {
    fn peek(&mut self) -> Option<&XmlEvent>;
}

pub trait Next {
	fn next(&mut self) -> Option<XmlEvent>;
}

// Wraps the Hyper Response type
pub struct XmlResponseFromAws<'b> {
	xml_stack: Peekable<Events<'b, Response>> // refactor to use XmlStack type?
}

// I cannot explain how these lifetimes work to a child, therefore I need to understand them better:
impl <'b>XmlResponseFromAws<'b> {
	pub fn new<'c>(stack: Peekable<Events<'b, Response>>) -> XmlResponseFromAws {
		XmlResponseFromAws {
			xml_stack: stack,
		}
	}
}

// Need peek and next implemented.
impl <'b>Peek for XmlResponseFromAws<'b> {
	fn peek(&mut self) -> Option<&XmlEvent> {
		return self.xml_stack.peek();
	}
}

impl <'b> Next for XmlResponseFromAws<'b> {
	fn next(&mut self) -> Option<XmlEvent> {
		return self.xml_stack.next();
	}
}

// TODO: move to tests/xmlutils.rs
pub struct XmlResponseFromFile<'a> {
	xml_stack: Peekable<Events<'a, BufReader<File>>>,
}

// I cannot explain how these lifetimes work to a child, therefore I need to understand them better:
impl <'b>XmlResponseFromFile<'b> {
	// TODO: refactor to have caller supply the xml_stack not just location.
	pub fn new<'c>(file_location: &str) -> XmlResponseFromFile {
		let file = File::open("file.xml").unwrap();
	    let file = BufReader::new(file);

	    let mut parser = EventReader::new(file);
		XmlResponseFromFile {
			xml_stack: parser.events().peekable(),
		}

	}
}

// Need peek and next implemented.
impl <'b> Peek for XmlResponseFromFile <'b> {
	fn peek(&mut self) -> Option<&XmlEvent> {
		return self.xml_stack.peek();
	}
}

impl <'b> Next for XmlResponseFromFile <'b> {
	fn next(&mut self) -> Option<XmlEvent> {
		return self.xml_stack.next();
	}
}

// /move to tests/xmlutils.rs

impl From<ParseIntError> for XmlParseError{
        fn from(_e:ParseIntError) -> XmlParseError { XmlParseError::new("ParseIntError") }
}

/// parse Some(String) if the next tag has the right name, otherwise None
pub fn optional_string_field<T: Peek + Next>(field_name: &str, stack: &mut T) -> Result<Option<String>, XmlParseError> {
	if try!(peek_at_name(stack)) == field_name {
		let val = try!(string_field(field_name, stack));
		Ok(Some(val))
	} else {
		Ok(None)
	}
}

/// return a string field with the right name or throw a parse error
pub fn string_field<T: Peek + Next>(name: &str, stack: &mut T) -> Result<String, XmlParseError> {
	try!(start_element(name, stack));
	let value = try!(characters(stack));
	try!(end_element(name, stack));
	Ok(value)
}

/// return some XML Characters
pub fn characters<T: Peek + Next>(stack: &mut T) -> Result<String, XmlParseError> {
	if let Some(XmlEvent::Characters(data)) = stack.next() {
		Ok(data.to_string())
	} else {
		Err(XmlParseError::new("Expected characters"))
	}
}

/// get the name of the current element in the stack.  throw a parse error if it's not a StartElement
pub fn peek_at_name<T: Peek + Next>(stack: &mut T) -> Result<String, XmlParseError> {
	let current = stack.peek();
	if let Some(&XmlEvent::StartElement{ref name, ..}) = current {
		Ok(name.local_name.to_string())
	} else {
		Ok("".to_string())
	}
}

/// consume a StartElement with a specific name or throw an XmlParseError
pub fn start_element<T: Peek + Next>(element_name: &str, stack: &mut T)  -> Result<HashMap<String, String>, XmlParseError> {
	let next = stack.next();
	if let Some(XmlEvent::StartElement { name, attributes, .. }) = next {
		if name.local_name != element_name {
			Err(XmlParseError::new(&format!("Expected {} got {}", element_name, name.local_name)))
		} else {
			let mut attr_map = HashMap::new();
			for attr in attributes {
				attr_map.insert(attr.name.local_name, attr.value);
			}
			Ok(attr_map)
		}
	}else {

    //  	println!("{:#?}", next);
		Err(XmlParseError::new(&format!("Expected StartElement {}", element_name)))
	}
}

/// consume an EndElement with a specific name or throw an XmlParseError
pub fn end_element<T: Peek + Next>(element_name: &str, stack: &mut T)  -> Result<(), XmlParseError> {
	let next = stack.next();
	if let Some(XmlEvent::EndElement { name, .. }) = next {
		if name.local_name != element_name {
			Err(XmlParseError::new(&format!("Expected {} got {}", element_name, name.local_name)))
		} else {
			Ok(())
		}
	}else {
		Err(XmlParseError::new(&format!("Expected EndElement {} got {:?}", element_name, next)))
	}
}
<commit_msg>Slight refactor, still checkpoint-y but compiles.<commit_after>use std::iter::Peekable;
use std::num::ParseIntError;
use xml::reader::events::*;
use xml::reader::Events;
use hyper::client::response::*;
use std::collections::HashMap;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
use std::path::Path;
use std::fs;
use std::error::Error;
use xml::reader::EventReader;

/// generic Error for XML parsing
#[derive(Debug)]
pub struct XmlParseError(pub String);

impl XmlParseError {
	pub fn new(msg: &str) -> XmlParseError {
		XmlParseError(msg.to_string())
	}
}

/// syntactic sugar for the XML event stack we pass around
pub type XmlStack<'a> = Peekable<Events<'a, Response>>;

pub trait Peek {
    fn peek(&mut self) -> Option<&XmlEvent>;
}

pub trait Next {
	fn next(&mut self) -> Option<XmlEvent>;
}

// Wraps the Hyper Response type
pub struct XmlResponseFromAws<'b> {
	xml_stack: Peekable<Events<'b, Response>> // refactor to use XmlStack type?
}

// I cannot explain how these lifetimes work to a child, therefore I need to understand them better:
impl <'b>XmlResponseFromAws<'b> {
	pub fn new<'c>(stack: Peekable<Events<'b, Response>>) -> XmlResponseFromAws {
		XmlResponseFromAws {
			xml_stack: stack,
		}
	}
}

// Need peek and next implemented.
impl <'b>Peek for XmlResponseFromAws<'b> {
	fn peek(&mut self) -> Option<&XmlEvent> {
		return self.xml_stack.peek();
	}
}

impl <'b> Next for XmlResponseFromAws<'b> {
	fn next(&mut self) -> Option<XmlEvent> {
		return self.xml_stack.next();
	}
}

// TODO: move to tests/xmlutils.rs
pub struct XmlResponseFromFile<'a> {
	xml_stack: Peekable<Events<'a, BufReader<File>>>,
}

// I cannot explain how these lifetimes work to a child, therefore I need to understand them better:
impl <'a>XmlResponseFromFile<'a> {
	// TODO: refactor to have caller supply the xml_stack not just location.
	pub fn new<'c>(stack: Peekable<Events<'a, BufReader<File>>>) -> XmlResponseFromFile {

		XmlResponseFromFile {
			xml_stack: stack,
		}

	}
}

// Need peek and next implemented.
impl <'b> Peek for XmlResponseFromFile <'b> {
	fn peek(&mut self) -> Option<&XmlEvent> {
		return self.xml_stack.peek();
	}
}

impl <'b> Next for XmlResponseFromFile <'b> {
	fn next(&mut self) -> Option<XmlEvent> {
		return self.xml_stack.next();
	}
}

// /move to tests/xmlutils.rs

impl From<ParseIntError> for XmlParseError{
        fn from(_e:ParseIntError) -> XmlParseError { XmlParseError::new("ParseIntError") }
}

/// parse Some(String) if the next tag has the right name, otherwise None
pub fn optional_string_field<T: Peek + Next>(field_name: &str, stack: &mut T) -> Result<Option<String>, XmlParseError> {
	if try!(peek_at_name(stack)) == field_name {
		let val = try!(string_field(field_name, stack));
		Ok(Some(val))
	} else {
		Ok(None)
	}
}

/// return a string field with the right name or throw a parse error
pub fn string_field<T: Peek + Next>(name: &str, stack: &mut T) -> Result<String, XmlParseError> {
	try!(start_element(name, stack));
	let value = try!(characters(stack));
	try!(end_element(name, stack));
	Ok(value)
}

/// return some XML Characters
pub fn characters<T: Peek + Next>(stack: &mut T) -> Result<String, XmlParseError> {
	if let Some(XmlEvent::Characters(data)) = stack.next() {
		Ok(data.to_string())
	} else {
		Err(XmlParseError::new("Expected characters"))
	}
}

/// get the name of the current element in the stack.  throw a parse error if it's not a StartElement
pub fn peek_at_name<T: Peek + Next>(stack: &mut T) -> Result<String, XmlParseError> {
	let current = stack.peek();
	if let Some(&XmlEvent::StartElement{ref name, ..}) = current {
		Ok(name.local_name.to_string())
	} else {
		Ok("".to_string())
	}
}

/// consume a StartElement with a specific name or throw an XmlParseError
pub fn start_element<T: Peek + Next>(element_name: &str, stack: &mut T)  -> Result<HashMap<String, String>, XmlParseError> {
	let next = stack.next();
	if let Some(XmlEvent::StartElement { name, attributes, .. }) = next {
		if name.local_name != element_name {
			Err(XmlParseError::new(&format!("Expected {} got {}", element_name, name.local_name)))
		} else {
			let mut attr_map = HashMap::new();
			for attr in attributes {
				attr_map.insert(attr.name.local_name, attr.value);
			}
			Ok(attr_map)
		}
	}else {

    //  	println!("{:#?}", next);
		Err(XmlParseError::new(&format!("Expected StartElement {}", element_name)))
	}
}

/// consume an EndElement with a specific name or throw an XmlParseError
pub fn end_element<T: Peek + Next>(element_name: &str, stack: &mut T)  -> Result<(), XmlParseError> {
	let next = stack.next();
	if let Some(XmlEvent::EndElement { name, .. }) = next {
		if name.local_name != element_name {
			Err(XmlParseError::new(&format!("Expected {} got {}", element_name, name.local_name)))
		} else {
			Ok(())
		}
	}else {
		Err(XmlParseError::new(&format!("Expected EndElement {} got {:?}", element_name, next)))
	}
}
<|endoftext|>


<commit_before><commit_msg>Add rust code for luhn-from case<commit_after>pub struct Luhn {
    result: Option<String>,
}

fn is_valid(id: &str) -> bool {
    if id.len() < 2 {
        return false;
    }

    let mut index: u32 = 0;
    let mut sum: u32 = 0;

    for c in id.chars().rev() {
        if c.is_whitespace() {
            continue;
        }

        let mut v: u32;

        if let Some(d) = c.to_digit(10) {
            v = d;
        } else {
            return false;
        }

        if index % 2 != 0 {
            v *= 2;

            if v > 9 {
                v -= 9;
            }
        }

        index += 1;
        sum += v;
    }

    if index < 2 {
        return false;
    }

    (sum % 10) == 0
}

impl<T> From<T> for Luhn
where
    T: ToString,
{
    fn from(id: T) -> Self {
        let string = id.to_string();

        if is_valid(&string) {
            return Luhn {
                result: Some(string),
            };
        }

        Luhn { result: None }
    }
}

impl Luhn {
    pub fn is_valid(&self) -> bool {
        self.result.is_some()
    }
}
<|endoftext|>


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

use collections::string::String;

use scheduler::context;

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

pub struct TestScheme;

impl KScheme for TestScheme {
    fn scheme(&self) -> &str {
        "test"
    }

    fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> {
        let mut string = String::new();

        macro_rules! test {
            ($ cond : expr) => (
                if ! string.is_empty() {
                    string.push('\n');
                }
                if $ cond {
                    string.push_str(&format!(concat!("\x1B[32mSUCCESS: ", stringify!($ cond), "\x1B[0m")));
                } else {
                    string.push_str(&format!(concat!("\x1B[31mFAILURE: ", stringify!($ cond), "\x1B[0m")));
                }
            );
            ($ cond : expr , $ ($ arg : tt) +) => (
                if ! string.is_empty() {
                    string.push('\n');
                }
                if $ cond {
                    string.push_str(&format!(concat!("\x1B[32mSUCCESS: ", stringify!($ cond), "\x1B[0m")));
                } else {
                    string.push_str(&format!(concat!("\x1B[31mFAILURE: ", stringify!($ cond), "\x1B[0m")));
                }
            );
        }

        {
            test!(true == true);
            test!(true == false);
        }

        Ok(box VecResource::new(Url::from_str("test:"), string.into_bytes()))
    }
}
<commit_msg>Fix format<commit_after>use alloc::boxed::Box;

use collections::string::String;

use scheduler::context;

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

pub struct TestScheme;

impl KScheme for TestScheme {
    fn scheme(&self) -> &str {
        "test"
    }

    fn open(&mut self, _: &Url, _: usize) -> Result<Box<Resource>> {
        let mut string = String::new();

        macro_rules! test {
            ($cond:expr) => (
                if ! string.is_empty() {
                    string.push('\n');
                }
                if $ cond {
                    string.push_str("\x1B[32mSUCCESS: ");
                } else {
                    string.push_str("\x1B[31mFAILURE: ");
                }
                string.push_str(stringify!($cond));
                string.push_str("\x1B[0m");
            );
            ($cond:expr, $($arg:tt)*) => (
                if ! string.is_empty() {
                    string.push('\n');
                }
                if $ cond {
                    string.push_str("\x1B[32mSUCCESS: ");
                } else {
                    string.push_str("\x1B[31mFAILURE: ");
                }
                string.push_str(stringify!($cond));
                string.push_str(": ");
                string.push_str(&format!($($arg)*));
                string.push_str("\x1B[0m");
            );
        }

        {
            test!(true == true);
            test!(true == false);
            test!(false, "Failing test with description");
            test!(true, "Passing test with format {:X}", 0x12345678);
        }

        Ok(box VecResource::new(Url::from_str("test:"), string.into_bytes()))
    }
}
<|endoftext|>


<commit_before><commit_msg>testsuite: Add working test for #5550<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.

fn main() {
    let s: ~str = ~"foobar";
    let mut t: &str = s;
    t = t.slice(0, 3); // for master: str::view(t, 0, 3) maybe
}
<|endoftext|>


<commit_before><commit_msg>Add long-while.rs to check on frame growth.<commit_after>fn main() {
  let int i = 0;
  while (i < 1000000) {
    i += 1;
    auto x = 3;
  }
}

<|endoftext|>


<commit_before><commit_msg>Trivial linear congruential generator implementation<commit_after>use std::rand::{Rng, SeedableRng};
use std::num;

static LCG_MULTIPLIER: u32 = 1103515245;
static LCG_INCREMENT: u32 = 12345;
static LCG_MODULOUS: u32 = 2147483647; // 2 ** 31 - 1
static LCG_DEFAULT_SEED: u32 = 1;

struct LinearCongruentialPRNG {
    seed: u32,
    rand_state: u32
}

impl LinearCongruentialPRNG {
    fn new_unseeded() -> LinearCongruentialPRNG {
        LinearCongruentialPRNG { seed: LCG_DEFAULT_SEED, rand_state: LCG_DEFAULT_SEED }
    }
}

impl Rng for LinearCongruentialPRNG {
    fn next_u32(&mut self) -> u32 {
        let next_rand = ((self.rand_state * LCG_MULTIPLIER) + LCG_INCREMENT) & LCG_MODULOUS;
        self.rand_state = next_rand;
        next_rand
    }
}

impl SeedableRng<u32> for LinearCongruentialPRNG {
    fn reseed(&mut self, seed: u32) {
        self.seed =
            if seed == 0 {
                1
            } else {
                seed
            }
    }

    fn from_seed(seed: u32) -> LinearCongruentialPRNG {
        LinearCongruentialPRNG { seed: seed, rand_state: seed }
    }
}

enum PRNG {
    LinearCongruentialPRNG,
}

fn main() {
    let mut rng = LinearCongruentialPRNG::new_unseeded();
    for _ in range(0u, 20) {
        println!("Rand num {}", rng.next_u32() % 100);
    }
}

#[test]
fn LCG_test() {
}
<|endoftext|>


<commit_before><commit_msg>Add test for issue #4448<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.

fn main() {
    let (port, chan) = comm::stream::<&static/str>();

    do task::spawn {
        assert port.recv() == "hello, world";
    }

    chan.send("hello, world");
}
<|endoftext|>


<commit_before><commit_msg>add hello_world/main.rs<commit_after>fn main() {
    println!("Hello, world!")
}
<|endoftext|>


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

use std::fs::{File, OpenOptions, create_dir, remove_file};
use std::io::{Read, Write};
use std::path::Path;

extern crate stripper_lib;

const TEST_FILE_DIR : &'static str = "tests/files";

const BASIC : &'static str = r#"/// struct Foo comment
struct Foo {
    /// Foo comment
    /// fn some_func(a: u32,
    ///              b: u32) {}
    A: u32,
}

mod Bar {
    test! {
        /// struct inside macro
        struct SuperFoo;
        sub_test! {
            /// and another one!
            struct FooFoo {
                x: u32,
            }
        }
    }
}
"#;

const BASIC_STRIPPED : &'static str = r#"struct Foo {
    A: u32,
}

mod Bar {
    test! {
        struct SuperFoo;
        sub_test! {
            struct FooFoo {
                x: u32,
            }
        }
    }
}
"#;

fn get_basic_cmt(file: &str) -> String {
    format!(r#"<!-- file {} -->
<!-- struct Foo -->
 struct Foo comment
<!-- struct Foo§variant A -->
 Foo comment
 fn some_func(a: u32,
              b: u32) {}
<!-- mod Bar§macro test!§struct SuperFoo -->
 struct inside macro
<!-- mod Bar§macro test!§macro sub_test!§struct FooFoo -->
 and another one!
"#, file, "{}")
}

fn gen_file(filename: &str, content: &str) -> File {
    match OpenOptions::new().write(true).create(true).truncate(true).open(&format!("{}/{}", TEST_FILE_DIR, filename)) {
        Ok(mut f) => {
            write!(f, "{}", content).unwrap();
            f
        },
        Err(e) => {
            panic!("gen_file: {}", e)
        },
    }
}

fn compare_files(expected_content: &str, file: &str) {
    match File::open(file) {
        Ok(mut f) => {
            let mut buf = String::new();
            f.read_to_string(&mut buf).unwrap();
            assert_eq!(expected_content, &buf);
        },
        Err(e) => panic!("compare_files '{}': {}", file, e),
    }
}

#[allow(unused_must_use)]
fn clean_test(files_to_remove: &[&str]) {
    for file in files_to_remove {
        remove_file(file);
    }
}

#[allow(unused_must_use)]
#[test]
fn test_strip() {
    let test_file = "basic.rs";
    let comment_file = "basic.cmts";
    create_dir(TEST_FILE_DIR);
    {
        gen_file(test_file, BASIC);
        let mut f = gen_file(comment_file, "");
        stripper_lib::strip_comments(Path::new(TEST_FILE_DIR), test_file, &mut f, false);
    }
    compare_files(&get_basic_cmt(test_file), &format!("{}/{}", TEST_FILE_DIR, comment_file));
    compare_files(BASIC_STRIPPED, &format!("{}/{}", TEST_FILE_DIR, test_file));
    clean_test(&vec!(test_file, comment_file));
}

#[allow(unused_must_use)]
#[test]
fn test_regeneration() {
    let test_file = "regen.rs";
    let comment_file = "regen.cmts";
    create_dir(TEST_FILE_DIR);
    {
        gen_file(test_file, BASIC);
        let mut f = gen_file(comment_file, "");
        stripper_lib::strip_comments(Path::new(TEST_FILE_DIR), test_file, &mut f, false);
        stripper_lib::regenerate_doc_comments(TEST_FILE_DIR, false,
                                              &format!("{}/{}", TEST_FILE_DIR, comment_file),
                                              false);
    }
    compare_files(BASIC, &format!("{}/{}", TEST_FILE_DIR, test_file));
    clean_test(&vec!(test_file, comment_file));
}
<|endoftext|>


<commit_before><commit_msg>Make HabitBuilder derive Debug<commit_after><|endoftext|>


<commit_before>use super::from_bytes::FromBytes;

const SPACE_MAP_HISTOGRAM_SIZE: usize = 32;

#[derive(Debug)]
pub struct SpaceMapPhys {
    object: u64,   // on-disk space map object
    objsize: u64,  // size of the object
    alloc: u64,    // space allocated from the map
    pad: [u64; 5], // reserved

    /*
     * The smp_histogram maintains a histogram of free regions. Each
     * bucket, smp_histogram[i], contains the number of free regions
     * whose size is:
     * 2^(i+sm_shift) <= size of free region in bytes < 2^(i+sm_shift+1)
     */
    histogram: [u64; SPACE_MAP_HISTOGRAM_SIZE],
}

impl FromBytes for SpaceMapPhys { }
<commit_msg>Documentation for SpaceMapPhys<commit_after>use super::from_bytes::FromBytes;

const SPACE_MAP_HISTOGRAM_SIZE: usize = 32;

/// The `SpaceMapPhys` is the on-disk representation of the space map.
/// Consumers of space maps should never reference any of the members of this
/// structure directly. These members may only be updated in syncing context.
///
/// Note the smp_object is no longer used but remains in the structure
/// for backward compatibility.
///
/// The smp_histogram maintains a histogram of free regions. Each
/// bucket, smp_histogram[i], contains the number of free regions
/// whose size is:
/// 2^(i+sm_shift) <= size of free region in bytes < 2^(i+sm_shift+1)

#[derive(Debug)]
pub struct SpaceMapPhys {
    object: u64,   // on-disk space map object
    objsize: u64,  // size of the object
    alloc: u64,    // space allocated from the map
    pad: [u64; 5], // reserved
    histogram: [u64; SPACE_MAP_HISTOGRAM_SIZE],
}

impl FromBytes for SpaceMapPhys { }
<|endoftext|>


<commit_before>use redox::*;
use common::*;
mod crypto;
use crypto::{Sha512, PubKey, RsaSignature};

/// Version
#[derive(Hash, Clone)]
pub enum Version {
    NewerThan(u64),
    OlderThan(u64),
    Between(u64, u64),
    Excatly(u64),
    Newest,
}

// TODO: Implement format

#[derive(Hash, Clone)]
/// A package developer
pub struct Developer {
    /// The name of the developer
    pub name: String,
    /// The public key of the developer
    pub key: PubKey,
}

#[derive(Hash, Clone)]
/// An installable package for Oxide
pub struct Package {
    /// The id of this package
    pub id: Id,
    /// Description
    pub desc: String,
    /// The developer of the package
    pub dev: Developer,
    /// The developer's signature of this package's content (tarball)
    pub dev_sign: RsaSignature,
    /// The signatures of this package
    pub sign: Vec<RsaSignature>,
    /// The files this package will create on the computer.
    pub files: Vec<String>,
    /// Dependencies of this package
    pub deps: Vec<Id>,
}

impl Package {
    /// Get content
    pub fn get_content(&self) -> Tarball {

    }

    /// Get package from string
    pub fn from_string(s: String) -> Option<Package> {

        // TODO

        for i in resp {
            let data = i.substr(5, i.len() - 5);
            let key = i.substr(0, 4);

            if key == "name" {
                name = data;
            } else if key == "desc" {
                desc = data;
            } else if key == "host" {
                host = data;
            } else if key == "file" {
                files = data;
            } else if key == "vers" {
                version = data;
            }
        }

        Package {
            host: host,
            name: name,
            desc: desc,
            files: files.split(",".to_string()).collect::<Vec<_>>(),
            version: version,
        }
    }

    /// Install package
    pub fn install(&self, col: &Collection) -> Result<(), InstallError> {
        // Install deps
        for d in self.deps {
            d.install();
        }

        // TODO install + add to local package list
    }

    /// Check validity
    pub fn check(&self, col: &Collection) -> TrustLevel {
        let con = self.get_content();

        for s in self.sign {
            if s.check(con) && col.keys.contains(s) {
                return TrustLevel::TrustedPackage
            } else if !s.check(con) {
                return TrustLevel::InvalidSignature
            }
        }

        if !self.dev_sign.check(con) {
            TrustLevel::InvalidSignature
        } else if !col.devs.contains(self.dev_sign) {
            TrustLevel::UntrustedSignature
        } else {
            TrustLevel::TrustedDev
        }
    }

}

/// Trust level
pub enum TrustLevel {
    /// 0
    InvalidSignature,
    /// 1
    UntrustedSignature,
    /// 2
    TrustedDeveloper,
    /// 3
    TrustedPackage,
}

impl TrustLevel {
    /// Is this package trusted?
    pub fn is_trusted(&self) -> bool {
        match self {
            &TrustLevel::TrustedDeveloper | TrustLevel::TrustedPackage => true,
            _ => false,
        }
    }
}

/// An error
pub enum PackageError {
    InvalidSyntax,
    InvalidSignature,
    UntrustedSignature,
    UntrustedDev,
    NotFound,
    E404,
    InfiniteDeps,
    Unknown,
}

#[derive(Hash, Clone)]
/// An package descriptor
pub struct Id {
    pub name: String,
    pub version: Version,
}

impl Id {
    pub fn to_string(&self) -> String {
        format!("{}-{}", self.name, self.version)
    }
}

/// Database of trusted developers
#[derive(Hash, Clone)]
pub struct DevDb {
    pub data: HashSet<Developer>,
}

/// Database of trusted keys
#[derive(Hash, Clone)]
pub struct KeyDb {
    pub data: HashSet<PubKey>,
}

/// An index of packages
#[derive(Hash, Clone)]
pub struct Index {
    /// Where the search queries can be send to
    pub host: String,
}

impl Index {
    /// Get a given package
    pub fn get(&self, id: Id) -> Result<Package, PackageError> {
        let con = File::open("tcp://".to_string() + self.host);

        con.write("GET /ox/".to_string() + id.to_string() + " HTTP/1.1".to_string());

        let res = Vec::new();
        con.read_to_end(&mut res);

        Package::from_string(String::from_utf8(&res))
    }
}

/// A collection of indexes, trusted keys, and trusted developers (all stored on the users
/// computer)
#[derive(Hash, Clone)]
pub struct Collection {
    /// Indexes
    pub index: Vec<Index>,
    /// The trusted devs
    pub devs: DevDb,
    /// The trusted keys
    pub keys: KeyDb,
    /// The installed packages
    pub installed: Vec<LocalPackage>,
}

/// A package installed locally
pub struct LocalPackage {
    /// Files it owns
    pub owns: Vec<String>,
    /// Is this package installed as root (i.e. isnt just installed as a dep for another package)?
    pub root: bool,
    /// The package
    pub package: Package,
}

impl LocalPackage {
    pub fn uninstall(&self) -> bool {

    }
}

impl Collection {
    /// Get a given package (guaranteed to be valid)
    pub fn get(&self, id: Id) -> Result<Package, PackageError> {
        for i in self.index {
            if let Ok(p) = i.get(id) {
                if p.check().is_trusted() {
                    return Ok(p);
                }
            }
        }
        None
    }
}

<commit_msg>Add cyclic dep check<commit_after>use redox::*;
use common::*;
mod crypto;
use crypto::{Sha512, PubKey, RsaSignature};

/// Version
#[derive(Hash, Clone)]
pub enum Version {
    NewerThan(u64),
    OlderThan(u64),
    Between(u64, u64),
    Excatly(u64),
    Newest,
}

// TODO: Implement format

#[derive(Hash, Clone)]
/// A package developer
pub struct Developer {
    /// The name of the developer
    pub name: String,
    /// The public key of the developer
    pub key: PubKey,
}

#[derive(Hash, Clone)]
/// An installable package for Oxide
pub struct Package {
    /// The id of this package
    pub id: Id,
    /// Description
    pub desc: String,
    /// The developer of the package
    pub dev: Developer,
    /// The developer's signature of this package's content (tarball)
    pub dev_sign: RsaSignature,
    /// The signatures of this package
    pub sign: Vec<RsaSignature>,
    /// The files this package will create on the computer.
    pub files: Vec<String>,
    /// Dependencies of this package
    pub deps: Vec<Id>,
}

impl Package {
    /// Get content
    pub fn get_content(&self) -> Tarball {

    }

    /// Get package from string
    pub fn from_string(s: String) -> Option<Package> {

        // TODO

        for i in resp {
            let data = i.substr(5, i.len() - 5);
            let key = i.substr(0, 4);

            if key == "name" {
                name = data;
            } else if key == "desc" {
                desc = data;
            } else if key == "host" {
                host = data;
            } else if key == "file" {
                files = data;
            } else if key == "vers" {
                version = data;
            }
        }

        Package {
            host: host,
            name: name,
            desc: desc,
            files: files.split(",".to_string()).collect::<Vec<_>>(),
            version: version,
        }
    }

    /// Install package
    pub fn install(&self, col: &Collection) -> Result<u64, InstallError> {
        // Install deps
        let mut installed = 0;
        for d in self.deps {
            let pkg = d.install();
            if let Err(n) = pkg {
                installed += n;
                if n > 10000 {
                    println!("Warning: Potential infinite recursion (cyclic dependencies)");
                }
            } else {
                return pkg;
            }

        }

        // TODO install + add to local package list
    }

    /// Check validity
    pub fn check(&self, col: &Collection) -> TrustLevel {
        let con = self.get_content();

        for s in self.sign {
            if s.check(con) && col.keys.contains(s) {
                return TrustLevel::TrustedPackage
            } else if !s.check(con) {
                return TrustLevel::InvalidSignature
            }
        }

        if !self.dev_sign.check(con) {
            TrustLevel::InvalidSignature
        } else if !col.devs.contains(self.dev_sign) {
            TrustLevel::UntrustedSignature
        } else {
            TrustLevel::TrustedDev
        }
    }

}

/// Trust level
pub enum TrustLevel {
    /// 0
    InvalidSignature,
    /// 1
    UntrustedSignature,
    /// 2
    TrustedDeveloper,
    /// 3
    TrustedPackage,
}

impl TrustLevel {
    /// Is this package trusted?
    pub fn is_trusted(&self) -> bool {
        match self {
            &TrustLevel::TrustedDeveloper | TrustLevel::TrustedPackage => true,
            _ => false,
        }
    }
}

/// An error
pub enum PackageError {
    InvalidSyntax,
    InvalidSignature,
    UntrustedSignature,
    UntrustedDev,
    NotFound,
    E404,
    InfiniteDeps,
    Unknown,
}

#[derive(Hash, Clone)]
/// An package descriptor
pub struct Id {
    pub name: String,
    pub version: Version,
    pub dist_type: DistType,
}

/// Distribution type
pub enum DistType {
    Binary,
    Source,
    Other,
}

impl Id {
    pub fn to_string(&self) -> String {
        format!("{}-{}-{}", self.name, self.dist_type, self.version)
    }
}

/// Database of trusted developers
#[derive(Hash, Clone)]
pub struct DevDb {
    pub data: HashSet<Developer>,
}

/// Database of trusted keys
#[derive(Hash, Clone)]
pub struct KeyDb {
    pub data: HashSet<PubKey>,
}

/// An index of packages
#[derive(Hash, Clone)]
pub struct Index {
    /// Where the search queries can be send to
    pub host: String,
}

impl Index {
    /// Get a given package
    pub fn get(&self, id: Id) -> Result<Package, PackageError> {
        let con = File::open("tcp://".to_string() + self.host);

        con.write("GET /ox/".to_string() + id.to_string() + " HTTP/1.1".to_string());

        let res = Vec::new();
        con.read_to_end(&mut res);

        Package::from_string(String::from_utf8(&res))
    }
}

/// A collection of indexes, trusted keys, and trusted developers (all stored on the users
/// computer)
#[derive(Hash, Clone)]
pub struct Collection {
    /// Indexes
    pub index: Vec<Index>,
    /// The trusted devs
    pub devs: DevDb,
    /// The trusted keys
    pub keys: KeyDb,
    /// The installed packages
    pub installed: Vec<LocalPackage>,
}

/// A package installed locally
pub struct LocalPackage {
    /// Files it owns
    pub owns: Vec<String>,
    /// Is this package installed as root (i.e. isnt just installed as a dep for another package)?
    pub root: bool,
    /// The package
    pub package: Package,
}

impl LocalPackage {
    pub fn uninstall(&self) -> bool {

    }
}

impl Collection {
    /// Get a given package (guaranteed to be valid)
    pub fn get(&self, id: Id) -> Result<Package, PackageError> {
        for i in self.index {
            if let Ok(p) = i.get(id) {
                if p.check().is_trusted() {
                    return Ok(p);
                }
            }
        }
        None
    }
}

<|endoftext|>


<commit_before><commit_msg>Add a very basic example<commit_after>extern crate ansi_term;
use ansi_term::Colour::*;

fn main() {
    println!("{}", Black.paint("Black"));
    println!("{}", Red.paint("Red"));
    println!("{}", Green.paint("Green"));
    println!("{}", Yellow.paint("Yellow"));
    println!("{}", Blue.paint("Blue"));
    println!("{}", Purple.paint("Purple"));
    println!("{}", Cyan.paint("Cyan"));
    println!("{}", White.paint("White"));
}
<|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.

// Resolution is the process of removing type variables and replacing
// them with their inferred values.  Unfortunately our inference has
// become fairly complex and so there are a number of options to
// control *just how much* you want to resolve and how you want to do
// it.
//
// # Controlling the scope of resolution
//
// The options resolve_* determine what kinds of variables get
// resolved.  Generally resolution starts with a top-level type
// variable; we will always resolve this.  However, once we have
// resolved that variable, we may end up with a type that still
// contains type variables.  For example, if we resolve `<T0>` we may
// end up with something like `[<T1>]`.  If the option
// `resolve_nested_tvar` is passed, we will then go and recursively
// resolve `<T1>`.
//
// The options `resolve_rvar` controls whether we resolve region
// variables. The options `resolve_fvar` and `resolve_ivar` control
// whether we resolve floating point and integral variables,
// respectively.
//
// # What do if things are unconstrained
//
// Sometimes we will encounter a variable that has no constraints, and
// therefore cannot sensibly be mapped to any particular result.  By
// default, we will leave such variables as is (so you will get back a
// variable in your result).  The options force_* will cause the
// resolution to fail in this case intead, except for the case of
// integral variables, which resolve to `int` if forced.
//
// # resolve_all and force_all
//
// The options are a bit set, so you can use the *_all to resolve or
// force all kinds of variables (including those we may add in the
// future).  If you want to resolve everything but one type, you are
// probably better off writing `resolve_all - resolve_ivar`.

use middle::ty::{FloatVar, FloatVid, IntVar, IntVid, RegionVid, TyVar, TyVid};
use middle::ty::{type_is_bot, IntType, UintType};
use middle::ty;
use middle::ty_fold;
use middle::typeck::infer::{Bounds, cyclic_ty, fixup_err, fres, InferCtxt};
use middle::typeck::infer::{region_var_bound_by_region_var, unresolved_ty};
use middle::typeck::infer::to_str::InferStr;
use middle::typeck::infer::unify::{Root, UnifyInferCtxtMethods};
use util::common::{indent, indenter};
use util::ppaux::ty_to_str;

use syntax::ast;

pub static resolve_nested_tvar: uint = 0b0000000001;
pub static resolve_rvar: uint        = 0b0000000010;
pub static resolve_ivar: uint        = 0b0000000100;
pub static resolve_fvar: uint        = 0b0000001000;
pub static resolve_fnvar: uint       = 0b0000010000;
pub static resolve_all: uint         = 0b0000011111;
pub static force_tvar: uint          = 0b0000100000;
pub static force_rvar: uint          = 0b0001000000;
pub static force_ivar: uint          = 0b0010000000;
pub static force_fvar: uint          = 0b0100000000;
pub static force_fnvar: uint         = 0b1000000000;
pub static force_all: uint           = 0b1111100000;

pub static not_regions: uint         = !(force_rvar | resolve_rvar);

pub static try_resolve_tvar_shallow: uint = 0;
pub static resolve_and_force_all_but_regions: uint =
    (resolve_all | force_all) & not_regions;

pub struct ResolveState<'a> {
    infcx: &'a InferCtxt<'a>,
    modes: uint,
    err: Option<fixup_err>,
    v_seen: Vec<TyVid> ,
    type_depth: uint
}

pub fn resolver<'a>(infcx: &'a InferCtxt, modes: uint) -> ResolveState<'a> {
    ResolveState {
        infcx: infcx,
        modes: modes,
        err: None,
        v_seen: Vec::new(),
        type_depth: 0
    }
}

impl<'a> ty_fold::TypeFolder for ResolveState<'a> {
    fn tcx<'a>(&'a self) -> &'a ty::ctxt {
        self.infcx.tcx
    }

    fn fold_ty(&mut self, t: ty::t) -> ty::t {
        self.resolve_type(t)
    }

    fn fold_region(&mut self, r: ty::Region) -> ty::Region {
        self.resolve_region(r)
    }
}

impl<'a> ResolveState<'a> {
    pub fn should(&mut self, mode: uint) -> bool {
        (self.modes & mode) == mode
    }

    pub fn resolve_type_chk(&mut self, typ: ty::t) -> fres<ty::t> {
        self.err = None;

        debug!("Resolving {} (modes={:x})",
               ty_to_str(self.infcx.tcx, typ),
               self.modes);

        // n.b. This is a hokey mess because the current fold doesn't
        // allow us to pass back errors in any useful way.

        assert!(self.v_seen.is_empty());
        let rty = indent(|| self.resolve_type(typ) );
        assert!(self.v_seen.is_empty());
        match self.err {
          None => {
            debug!("Resolved to {} + {} (modes={:x})",
                   ty_to_str(self.infcx.tcx, rty),
                   ty_to_str(self.infcx.tcx, rty),
                   self.modes);
            return Ok(rty);
          }
          Some(e) => return Err(e)
        }
    }

    pub fn resolve_region_chk(&mut self, orig: ty::Region)
                              -> fres<ty::Region> {
        self.err = None;
        let resolved = indent(|| self.resolve_region(orig) );
        match self.err {
          None => Ok(resolved),
          Some(e) => Err(e)
        }
    }

    pub fn resolve_type(&mut self, typ: ty::t) -> ty::t {
        debug!("resolve_type({})", typ.inf_str(self.infcx));
        let _i = indenter();

        if !ty::type_needs_infer(typ) {
            return typ;
        }

        if self.type_depth > 0 && !self.should(resolve_nested_tvar) {
            return typ;
        }

        match ty::get(typ).sty {
            ty::ty_infer(TyVar(vid)) => {
                self.resolve_ty_var(vid)
            }
            ty::ty_infer(IntVar(vid)) => {
                self.resolve_int_var(vid)
            }
            ty::ty_infer(FloatVar(vid)) => {
                self.resolve_float_var(vid)
            }
            _ => {
                if self.modes & resolve_all == 0 {
                    // if we are only resolving top-level type
                    // variables, and this is not a top-level type
                    // variable, then shortcircuit for efficiency
                    typ
                } else {
                    self.type_depth += 1;
                    let result = ty_fold::super_fold_ty(self, typ);
                    self.type_depth -= 1;
                    result
                }
            }
        }
    }

    pub fn resolve_region(&mut self, orig: ty::Region) -> ty::Region {
        debug!("Resolve_region({})", orig.inf_str(self.infcx));
        match orig {
          ty::ReInfer(ty::ReVar(rid)) => self.resolve_region_var(rid),
          _ => orig
        }
    }

    pub fn resolve_region_var(&mut self, rid: RegionVid) -> ty::Region {
        if !self.should(resolve_rvar) {
            return ty::ReInfer(ty::ReVar(rid));
        }
        self.infcx.region_vars.resolve_var(rid)
    }

    pub fn assert_not_rvar(&mut self, rid: RegionVid, r: ty::Region) {
        match r {
          ty::ReInfer(ty::ReVar(rid2)) => {
            self.err = Some(region_var_bound_by_region_var(rid, rid2));
          }
          _ => { }
        }
    }

    pub fn resolve_ty_var(&mut self, vid: TyVid) -> ty::t {
        if self.v_seen.contains(&vid) {
            self.err = Some(cyclic_ty(vid));
            return ty::mk_var(self.infcx.tcx, vid);
        } else {
            self.v_seen.push(vid);
            let tcx = self.infcx.tcx;

            // Nonobvious: prefer the most specific type
            // (i.e., the lower bound) to the more general
            // one.  More general types in Rust (e.g., fn())
            // tend to carry more restrictions or higher
            // perf. penalties, so it pays to know more.

            let nde = self.infcx.get(vid);
            let bounds = nde.possible_types;

            let t1 = match bounds {
              Bounds { ub:_, lb:Some(t) } if !type_is_bot(t)
                => self.resolve_type(t),
              Bounds { ub:Some(t), lb:_ } => self.resolve_type(t),
              Bounds { ub:_, lb:Some(t) } => self.resolve_type(t),
              Bounds { ub:None, lb:None } => {
                if self.should(force_tvar) {
                    self.err = Some(unresolved_ty(vid));
                }
                ty::mk_var(tcx, vid)
              }
            };
            self.v_seen.pop().unwrap();
            return t1;
        }
    }

    pub fn resolve_int_var(&mut self, vid: IntVid) -> ty::t {
        if !self.should(resolve_ivar) {
            return ty::mk_int_var(self.infcx.tcx, vid);
        }

        let node = self.infcx.get(vid);
        match node.possible_types {
          Some(IntType(t)) => ty::mk_mach_int(t),
          Some(UintType(t)) => ty::mk_mach_uint(t),
          None => {
            if self.should(force_ivar) {
                // As a last resort, default to int.
                let ty = ty::mk_int();
                self.infcx.set(vid, Root(Some(IntType(ast::TyI)), node.rank));
                ty
            } else {
                ty::mk_int_var(self.infcx.tcx, vid)
            }
          }
        }
    }

    pub fn resolve_float_var(&mut self, vid: FloatVid) -> ty::t {
        if !self.should(resolve_fvar) {
            return ty::mk_float_var(self.infcx.tcx, vid);
        }

        let node = self.infcx.get(vid);
        match node.possible_types {
          Some(t) => ty::mk_mach_float(t),
          None => {
            if self.should(force_fvar) {
                // As a last resort, default to f64.
                let ty = ty::mk_f64();
                self.infcx.set(vid, Root(Some(ast::TyF64), node.rank));
                ty
            } else {
                ty::mk_float_var(self.infcx.tcx, vid)
            }
          }
        }
    }
}
<commit_msg>middle: typeck: infer: resolve: remove dead code<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.

// Resolution is the process of removing type variables and replacing
// them with their inferred values.  Unfortunately our inference has
// become fairly complex and so there are a number of options to
// control *just how much* you want to resolve and how you want to do
// it.
//
// # Controlling the scope of resolution
//
// The options resolve_* determine what kinds of variables get
// resolved.  Generally resolution starts with a top-level type
// variable; we will always resolve this.  However, once we have
// resolved that variable, we may end up with a type that still
// contains type variables.  For example, if we resolve `<T0>` we may
// end up with something like `[<T1>]`.  If the option
// `resolve_nested_tvar` is passed, we will then go and recursively
// resolve `<T1>`.
//
// The options `resolve_rvar` controls whether we resolve region
// variables. The options `resolve_fvar` and `resolve_ivar` control
// whether we resolve floating point and integral variables,
// respectively.
//
// # What do if things are unconstrained
//
// Sometimes we will encounter a variable that has no constraints, and
// therefore cannot sensibly be mapped to any particular result.  By
// default, we will leave such variables as is (so you will get back a
// variable in your result).  The options force_* will cause the
// resolution to fail in this case intead, except for the case of
// integral variables, which resolve to `int` if forced.
//
// # resolve_all and force_all
//
// The options are a bit set, so you can use the *_all to resolve or
// force all kinds of variables (including those we may add in the
// future).  If you want to resolve everything but one type, you are
// probably better off writing `resolve_all - resolve_ivar`.

use middle::ty::{FloatVar, FloatVid, IntVar, IntVid, RegionVid, TyVar, TyVid};
use middle::ty::{type_is_bot, IntType, UintType};
use middle::ty;
use middle::ty_fold;
use middle::typeck::infer::{Bounds, cyclic_ty, fixup_err, fres, InferCtxt};
use middle::typeck::infer::unresolved_ty;
use middle::typeck::infer::to_str::InferStr;
use middle::typeck::infer::unify::{Root, UnifyInferCtxtMethods};
use util::common::{indent, indenter};
use util::ppaux::ty_to_str;

use syntax::ast;

pub static resolve_nested_tvar: uint = 0b0000000001;
pub static resolve_rvar: uint        = 0b0000000010;
pub static resolve_ivar: uint        = 0b0000000100;
pub static resolve_fvar: uint        = 0b0000001000;
pub static resolve_all: uint         = 0b0000001111;
pub static force_tvar: uint          = 0b0000100000;
pub static force_rvar: uint          = 0b0001000000;
pub static force_ivar: uint          = 0b0010000000;
pub static force_fvar: uint          = 0b0100000000;
pub static force_all: uint           = 0b0111100000;

pub static not_regions: uint         = !(force_rvar | resolve_rvar);

pub static try_resolve_tvar_shallow: uint = 0;
pub static resolve_and_force_all_but_regions: uint =
    (resolve_all | force_all) & not_regions;

pub struct ResolveState<'a> {
    infcx: &'a InferCtxt<'a>,
    modes: uint,
    err: Option<fixup_err>,
    v_seen: Vec<TyVid> ,
    type_depth: uint
}

pub fn resolver<'a>(infcx: &'a InferCtxt, modes: uint) -> ResolveState<'a> {
    ResolveState {
        infcx: infcx,
        modes: modes,
        err: None,
        v_seen: Vec::new(),
        type_depth: 0
    }
}

impl<'a> ty_fold::TypeFolder for ResolveState<'a> {
    fn tcx<'a>(&'a self) -> &'a ty::ctxt {
        self.infcx.tcx
    }

    fn fold_ty(&mut self, t: ty::t) -> ty::t {
        self.resolve_type(t)
    }

    fn fold_region(&mut self, r: ty::Region) -> ty::Region {
        self.resolve_region(r)
    }
}

impl<'a> ResolveState<'a> {
    pub fn should(&mut self, mode: uint) -> bool {
        (self.modes & mode) == mode
    }

    pub fn resolve_type_chk(&mut self, typ: ty::t) -> fres<ty::t> {
        self.err = None;

        debug!("Resolving {} (modes={:x})",
               ty_to_str(self.infcx.tcx, typ),
               self.modes);

        // n.b. This is a hokey mess because the current fold doesn't
        // allow us to pass back errors in any useful way.

        assert!(self.v_seen.is_empty());
        let rty = indent(|| self.resolve_type(typ) );
        assert!(self.v_seen.is_empty());
        match self.err {
          None => {
            debug!("Resolved to {} + {} (modes={:x})",
                   ty_to_str(self.infcx.tcx, rty),
                   ty_to_str(self.infcx.tcx, rty),
                   self.modes);
            return Ok(rty);
          }
          Some(e) => return Err(e)
        }
    }

    pub fn resolve_region_chk(&mut self, orig: ty::Region)
                              -> fres<ty::Region> {
        self.err = None;
        let resolved = indent(|| self.resolve_region(orig) );
        match self.err {
          None => Ok(resolved),
          Some(e) => Err(e)
        }
    }

    pub fn resolve_type(&mut self, typ: ty::t) -> ty::t {
        debug!("resolve_type({})", typ.inf_str(self.infcx));
        let _i = indenter();

        if !ty::type_needs_infer(typ) {
            return typ;
        }

        if self.type_depth > 0 && !self.should(resolve_nested_tvar) {
            return typ;
        }

        match ty::get(typ).sty {
            ty::ty_infer(TyVar(vid)) => {
                self.resolve_ty_var(vid)
            }
            ty::ty_infer(IntVar(vid)) => {
                self.resolve_int_var(vid)
            }
            ty::ty_infer(FloatVar(vid)) => {
                self.resolve_float_var(vid)
            }
            _ => {
                if self.modes & resolve_all == 0 {
                    // if we are only resolving top-level type
                    // variables, and this is not a top-level type
                    // variable, then shortcircuit for efficiency
                    typ
                } else {
                    self.type_depth += 1;
                    let result = ty_fold::super_fold_ty(self, typ);
                    self.type_depth -= 1;
                    result
                }
            }
        }
    }

    pub fn resolve_region(&mut self, orig: ty::Region) -> ty::Region {
        debug!("Resolve_region({})", orig.inf_str(self.infcx));
        match orig {
          ty::ReInfer(ty::ReVar(rid)) => self.resolve_region_var(rid),
          _ => orig
        }
    }

    pub fn resolve_region_var(&mut self, rid: RegionVid) -> ty::Region {
        if !self.should(resolve_rvar) {
            return ty::ReInfer(ty::ReVar(rid));
        }
        self.infcx.region_vars.resolve_var(rid)
    }

    pub fn resolve_ty_var(&mut self, vid: TyVid) -> ty::t {
        if self.v_seen.contains(&vid) {
            self.err = Some(cyclic_ty(vid));
            return ty::mk_var(self.infcx.tcx, vid);
        } else {
            self.v_seen.push(vid);
            let tcx = self.infcx.tcx;

            // Nonobvious: prefer the most specific type
            // (i.e., the lower bound) to the more general
            // one.  More general types in Rust (e.g., fn())
            // tend to carry more restrictions or higher
            // perf. penalties, so it pays to know more.

            let nde = self.infcx.get(vid);
            let bounds = nde.possible_types;

            let t1 = match bounds {
              Bounds { ub:_, lb:Some(t) } if !type_is_bot(t)
                => self.resolve_type(t),
              Bounds { ub:Some(t), lb:_ } => self.resolve_type(t),
              Bounds { ub:_, lb:Some(t) } => self.resolve_type(t),
              Bounds { ub:None, lb:None } => {
                if self.should(force_tvar) {
                    self.err = Some(unresolved_ty(vid));
                }
                ty::mk_var(tcx, vid)
              }
            };
            self.v_seen.pop().unwrap();
            return t1;
        }
    }

    pub fn resolve_int_var(&mut self, vid: IntVid) -> ty::t {
        if !self.should(resolve_ivar) {
            return ty::mk_int_var(self.infcx.tcx, vid);
        }

        let node = self.infcx.get(vid);
        match node.possible_types {
          Some(IntType(t)) => ty::mk_mach_int(t),
          Some(UintType(t)) => ty::mk_mach_uint(t),
          None => {
            if self.should(force_ivar) {
                // As a last resort, default to int.
                let ty = ty::mk_int();
                self.infcx.set(vid, Root(Some(IntType(ast::TyI)), node.rank));
                ty
            } else {
                ty::mk_int_var(self.infcx.tcx, vid)
            }
          }
        }
    }

    pub fn resolve_float_var(&mut self, vid: FloatVid) -> ty::t {
        if !self.should(resolve_fvar) {
            return ty::mk_float_var(self.infcx.tcx, vid);
        }

        let node = self.infcx.get(vid);
        match node.possible_types {
          Some(t) => ty::mk_mach_float(t),
          None => {
            if self.should(force_fvar) {
                // As a last resort, default to f64.
                let ty = ty::mk_f64();
                self.infcx.set(vid, Root(Some(ast::TyF64), node.rank));
                ty
            } else {
                ty::mk_float_var(self.infcx.tcx, vid)
            }
          }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>added file again<commit_after>use rustc::lint::*;
use rustc::hir::*;
use utils::{paths, method_chain_args, span_help_and_lint, match_type};

/// **What it does:*** Checks for unnecessary `ok()` in if let.
///
/// **Why is this bad?** Calling `ok()` in if let is unnecessary, instead match on `Ok(x`
///
/// **Known problems:** None.
///
/// **Example:**
/// ```rustc
/// for result in iter {
///     if let Some(bench) = try!(result).parse().ok() {
///         vec.push(bench)
///     }
/// }
/// ```
declare_lint! {
    pub IF_LET_SOME_RESULT,
    Warn,
    "usage of `ok()` in `if let Some(x)` statements is unnecessary, match on `Ok(expr)` instead"
}

#[derive(Copy, Clone)]
pub struct OkIfLetPass;

impl LintPass for OkIfLetPass {
    fn get_lints(&self) -> LintArray {
        lint_array!(IF_LET_SOME_RESULT)
    }
}

impl LateLintPass for OkIfLetPass {
    fn check_expr(&mut self, cx: &LateContext, expr: &Expr) {
        if_let_chain! {[ //begin checking variables
            let ExprMatch(ref op, ref body, ref source) = expr.node, //test if expr is a match
            let MatchSource::IfLetDesugar { contains_else_clause: _ } = *source, //test if it is an If Let
            let ExprMethodCall(_, _, ref result_types) = op.node, //check is expr.ok() has type Result<T,E>.ok()
            let PatKind::TupleStruct(ref x, ref y, _)  = body[0].pats[0].node, //get operation
            let Some(_) = method_chain_args(op, &["ok"]) //test to see if using ok() methoduse std::marker::Sized;

        ], {
            let is_result_type = match_type(cx, cx.tcx.expr_ty(&result_types[0]), &paths::RESULT);
            let some_expr_string = print::pat_to_string(&y[0]);
            if print::path_to_string(x) == "Some" && is_result_type {
                span_help_and_lint(cx, IF_LET_SOME_RESULT, expr.span,
                "Matching on `Some` with `ok()` is redundant",
                &format!("Consider matching on `Ok({})` and removing the call to `ok` instead", some_expr_string));
            }
        }}
    }
}
<|endoftext|>