file_name
large_stringlengths 4
69
| prefix
large_stringlengths 0
26.7k
| suffix
large_stringlengths 0
24.8k
| middle
large_stringlengths 0
2.12k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
round_manager_fuzzing.rs
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
block_storage::BlockStore,
liveness::{
proposal_generator::ProposalGenerator,
rotating_proposer_election::RotatingProposer,
round_state::{ExponentialTimeInterval, NewRoundEvent, NewRoundReason, RoundState},
},
metrics_safety_rules::MetricsSafetyRules,
network::NetworkSender,
network_interface::ConsensusNetworkSender,
persistent_liveness_storage::{PersistentLivenessStorage, RecoveryData},
round_manager::RoundManager,
test_utils::{EmptyStateComputer, MockStorage, MockTransactionManager},
util::{mock_time_service::SimulatedTimeService, time_service::TimeService},
};
use channel::{self, diem_channel, message_queues::QueueStyle};
use consensus_types::proposal_msg::ProposalMsg;
use diem_types::{
epoch_change::EpochChangeProof,
epoch_state::EpochState,
ledger_info::{LedgerInfo, LedgerInfoWithSignatures},
on_chain_config::ValidatorSet,
validator_info::ValidatorInfo,
validator_signer::ValidatorSigner,
validator_verifier::ValidatorVerifier,
};
use futures::{channel::mpsc, executor::block_on};
use network::{
peer_manager::{ConnectionRequestSender, PeerManagerRequestSender},
protocols::network::NewNetworkSender,
};
use once_cell::sync::Lazy;
use safety_rules::{test_utils, SafetyRules, TSafetyRules};
use std::{collections::BTreeMap, sync::Arc, time::Duration};
use tokio::runtime::Runtime;
// This generates a proposal for round 1
pub fn generate_corpus_proposal() -> Vec<u8> {
let mut round_manager = create_node_for_fuzzing();
block_on(async {
let proposal = round_manager
.generate_proposal(NewRoundEvent {
round: 1,
reason: NewRoundReason::QCReady,
timeout: std::time::Duration::new(5, 0),
})
.await;
// serialize and return proposal
bcs::to_bytes(&proposal.unwrap()).unwrap()
})
}
// optimization for the fuzzer
static STATIC_RUNTIME: Lazy<Runtime> = Lazy::new(|| Runtime::new().unwrap());
static FUZZING_SIGNER: Lazy<ValidatorSigner> = Lazy::new(|| ValidatorSigner::from_int(1));
// helpers
fn build_empty_store(
storage: Arc<dyn PersistentLivenessStorage>,
initial_data: RecoveryData,
) -> Arc<BlockStore> {
let (_commit_cb_sender, _commit_cb_receiver) = mpsc::unbounded::<LedgerInfoWithSignatures>();
Arc::new(BlockStore::new(
storage,
initial_data,
Arc::new(EmptyStateComputer),
10, // max pruned blocks in mem
Arc::new(SimulatedTimeService::new()),
))
}
// helpers for safety rule initialization
fn make_initial_epoch_change_proof(signer: &ValidatorSigner) -> EpochChangeProof {
let validator_info =
ValidatorInfo::new_with_test_network_keys(signer.author(), signer.public_key(), 1);
let validator_set = ValidatorSet::new(vec![validator_info]);
let li = LedgerInfo::mock_genesis(Some(validator_set));
let lis = LedgerInfoWithSignatures::new(li, BTreeMap::new());
EpochChangeProof::new(vec![lis], false)
}
// TODO: MockStorage -> EmptyStorage
fn create_round_state() -> RoundState {
let base_timeout = std::time::Duration::new(60, 0);
let time_interval = Box::new(ExponentialTimeInterval::fixed(base_timeout));
let (round_timeout_sender, _) = channel::new_test(1_024);
let time_service = Arc::new(SimulatedTimeService::new());
RoundState::new(time_interval, time_service, round_timeout_sender)
}
// Creates an RoundManager for fuzzing
fn create_node_for_fuzzing() -> RoundManager {
// signer is re-used accross fuzzing runs
let signer = FUZZING_SIGNER.clone();
// TODO: remove
let validator = ValidatorVerifier::new_single(signer.author(), signer.public_key());
let validator_set = (&validator).into();
// TODO: EmptyStorage
let (initial_data, storage) = MockStorage::start_for_testing(validator_set);
// TODO: remove
let proof = make_initial_epoch_change_proof(&signer);
let mut safety_rules = SafetyRules::new(test_utils::test_storage(&signer), false, false);
safety_rules.initialize(&proof).unwrap();
// TODO: mock channels
let (network_reqs_tx, _network_reqs_rx) = diem_channel::new(QueueStyle::FIFO, 8, None);
let (connection_reqs_tx, _) = diem_channel::new(QueueStyle::FIFO, 8, None);
let network_sender = ConsensusNetworkSender::new(
PeerManagerRequestSender::new(network_reqs_tx),
ConnectionRequestSender::new(connection_reqs_tx),
);
let (self_sender, _self_receiver) = channel::new_test(8);
let epoch_state = EpochState {
epoch: 1,
verifier: storage.get_validator_set().into(),
};
let network = NetworkSender::new(
signer.author(),
network_sender,
self_sender,
epoch_state.verifier.clone(),
);
// TODO: mock
let block_store = build_empty_store(storage.clone(), initial_data);
// TODO: remove
let time_service = Arc::new(SimulatedTimeService::new());
time_service.sleep(Duration::from_millis(1));
// TODO: remove
let proposal_generator = ProposalGenerator::new(
signer.author(),
block_store.clone(),
Arc::new(MockTransactionManager::new(None)),
time_service,
1,
);
//
let round_state = create_round_state();
// TODO: have two different nodes, one for proposing, one for accepting a proposal
let proposer_election = Box::new(RotatingProposer::new(vec![signer.author()], 1));
// event processor
RoundManager::new(
epoch_state,
Arc::clone(&block_store),
round_state,
proposer_election,
proposal_generator,
MetricsSafetyRules::new(Box::new(safety_rules), storage.clone()),
network,
Arc::new(MockTransactionManager::new(None)),
storage,
false,
)
}
// This functions fuzzes a Proposal protobuffer (not a ConsensusMsg)
pub fn fuzz_proposal(data: &[u8]) {
// create node
let mut round_manager = create_node_for_fuzzing();
let proposal: ProposalMsg = match bcs::from_bytes(data) {
Ok(xx) => xx,
Err(_) => {
if cfg!(test) {
panic!();
}
return;
}
};
let proposal = match proposal.verify_well_formed() {
Ok(_) => proposal,
Err(e) => {
println!("{:?}", e);
if cfg!(test) {
panic!();
}
return;
}
};
block_on(async move {
// TODO: make sure this obtains a vote when testing
// TODO: make sure that if this obtains a vote, it's for round 1, etc.
let _ = round_manager.process_proposal_msg(proposal).await;
});
}
// This test is here so that the fuzzer can be maintained
#[test]
fn test_consensus_proposal_fuzzer()
|
{
// generate a proposal
let proposal = generate_corpus_proposal();
// successfully parse it
fuzz_proposal(&proposal);
}
|
identifier_body
|
|
round_manager_fuzzing.rs
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
block_storage::BlockStore,
liveness::{
proposal_generator::ProposalGenerator,
rotating_proposer_election::RotatingProposer,
round_state::{ExponentialTimeInterval, NewRoundEvent, NewRoundReason, RoundState},
},
metrics_safety_rules::MetricsSafetyRules,
network::NetworkSender,
network_interface::ConsensusNetworkSender,
persistent_liveness_storage::{PersistentLivenessStorage, RecoveryData},
round_manager::RoundManager,
test_utils::{EmptyStateComputer, MockStorage, MockTransactionManager},
util::{mock_time_service::SimulatedTimeService, time_service::TimeService},
};
use channel::{self, diem_channel, message_queues::QueueStyle};
use consensus_types::proposal_msg::ProposalMsg;
use diem_types::{
epoch_change::EpochChangeProof,
epoch_state::EpochState,
|
};
use futures::{channel::mpsc, executor::block_on};
use network::{
peer_manager::{ConnectionRequestSender, PeerManagerRequestSender},
protocols::network::NewNetworkSender,
};
use once_cell::sync::Lazy;
use safety_rules::{test_utils, SafetyRules, TSafetyRules};
use std::{collections::BTreeMap, sync::Arc, time::Duration};
use tokio::runtime::Runtime;
// This generates a proposal for round 1
pub fn generate_corpus_proposal() -> Vec<u8> {
let mut round_manager = create_node_for_fuzzing();
block_on(async {
let proposal = round_manager
.generate_proposal(NewRoundEvent {
round: 1,
reason: NewRoundReason::QCReady,
timeout: std::time::Duration::new(5, 0),
})
.await;
// serialize and return proposal
bcs::to_bytes(&proposal.unwrap()).unwrap()
})
}
// optimization for the fuzzer
static STATIC_RUNTIME: Lazy<Runtime> = Lazy::new(|| Runtime::new().unwrap());
static FUZZING_SIGNER: Lazy<ValidatorSigner> = Lazy::new(|| ValidatorSigner::from_int(1));
// helpers
fn build_empty_store(
storage: Arc<dyn PersistentLivenessStorage>,
initial_data: RecoveryData,
) -> Arc<BlockStore> {
let (_commit_cb_sender, _commit_cb_receiver) = mpsc::unbounded::<LedgerInfoWithSignatures>();
Arc::new(BlockStore::new(
storage,
initial_data,
Arc::new(EmptyStateComputer),
10, // max pruned blocks in mem
Arc::new(SimulatedTimeService::new()),
))
}
// helpers for safety rule initialization
fn make_initial_epoch_change_proof(signer: &ValidatorSigner) -> EpochChangeProof {
let validator_info =
ValidatorInfo::new_with_test_network_keys(signer.author(), signer.public_key(), 1);
let validator_set = ValidatorSet::new(vec![validator_info]);
let li = LedgerInfo::mock_genesis(Some(validator_set));
let lis = LedgerInfoWithSignatures::new(li, BTreeMap::new());
EpochChangeProof::new(vec![lis], false)
}
// TODO: MockStorage -> EmptyStorage
fn create_round_state() -> RoundState {
let base_timeout = std::time::Duration::new(60, 0);
let time_interval = Box::new(ExponentialTimeInterval::fixed(base_timeout));
let (round_timeout_sender, _) = channel::new_test(1_024);
let time_service = Arc::new(SimulatedTimeService::new());
RoundState::new(time_interval, time_service, round_timeout_sender)
}
// Creates an RoundManager for fuzzing
fn create_node_for_fuzzing() -> RoundManager {
// signer is re-used accross fuzzing runs
let signer = FUZZING_SIGNER.clone();
// TODO: remove
let validator = ValidatorVerifier::new_single(signer.author(), signer.public_key());
let validator_set = (&validator).into();
// TODO: EmptyStorage
let (initial_data, storage) = MockStorage::start_for_testing(validator_set);
// TODO: remove
let proof = make_initial_epoch_change_proof(&signer);
let mut safety_rules = SafetyRules::new(test_utils::test_storage(&signer), false, false);
safety_rules.initialize(&proof).unwrap();
// TODO: mock channels
let (network_reqs_tx, _network_reqs_rx) = diem_channel::new(QueueStyle::FIFO, 8, None);
let (connection_reqs_tx, _) = diem_channel::new(QueueStyle::FIFO, 8, None);
let network_sender = ConsensusNetworkSender::new(
PeerManagerRequestSender::new(network_reqs_tx),
ConnectionRequestSender::new(connection_reqs_tx),
);
let (self_sender, _self_receiver) = channel::new_test(8);
let epoch_state = EpochState {
epoch: 1,
verifier: storage.get_validator_set().into(),
};
let network = NetworkSender::new(
signer.author(),
network_sender,
self_sender,
epoch_state.verifier.clone(),
);
// TODO: mock
let block_store = build_empty_store(storage.clone(), initial_data);
// TODO: remove
let time_service = Arc::new(SimulatedTimeService::new());
time_service.sleep(Duration::from_millis(1));
// TODO: remove
let proposal_generator = ProposalGenerator::new(
signer.author(),
block_store.clone(),
Arc::new(MockTransactionManager::new(None)),
time_service,
1,
);
//
let round_state = create_round_state();
// TODO: have two different nodes, one for proposing, one for accepting a proposal
let proposer_election = Box::new(RotatingProposer::new(vec![signer.author()], 1));
// event processor
RoundManager::new(
epoch_state,
Arc::clone(&block_store),
round_state,
proposer_election,
proposal_generator,
MetricsSafetyRules::new(Box::new(safety_rules), storage.clone()),
network,
Arc::new(MockTransactionManager::new(None)),
storage,
false,
)
}
// This functions fuzzes a Proposal protobuffer (not a ConsensusMsg)
pub fn fuzz_proposal(data: &[u8]) {
// create node
let mut round_manager = create_node_for_fuzzing();
let proposal: ProposalMsg = match bcs::from_bytes(data) {
Ok(xx) => xx,
Err(_) => {
if cfg!(test) {
panic!();
}
return;
}
};
let proposal = match proposal.verify_well_formed() {
Ok(_) => proposal,
Err(e) => {
println!("{:?}", e);
if cfg!(test) {
panic!();
}
return;
}
};
block_on(async move {
// TODO: make sure this obtains a vote when testing
// TODO: make sure that if this obtains a vote, it's for round 1, etc.
let _ = round_manager.process_proposal_msg(proposal).await;
});
}
// This test is here so that the fuzzer can be maintained
#[test]
fn test_consensus_proposal_fuzzer() {
// generate a proposal
let proposal = generate_corpus_proposal();
// successfully parse it
fuzz_proposal(&proposal);
}
|
ledger_info::{LedgerInfo, LedgerInfoWithSignatures},
on_chain_config::ValidatorSet,
validator_info::ValidatorInfo,
validator_signer::ValidatorSigner,
validator_verifier::ValidatorVerifier,
|
random_line_split
|
round_manager_fuzzing.rs
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
block_storage::BlockStore,
liveness::{
proposal_generator::ProposalGenerator,
rotating_proposer_election::RotatingProposer,
round_state::{ExponentialTimeInterval, NewRoundEvent, NewRoundReason, RoundState},
},
metrics_safety_rules::MetricsSafetyRules,
network::NetworkSender,
network_interface::ConsensusNetworkSender,
persistent_liveness_storage::{PersistentLivenessStorage, RecoveryData},
round_manager::RoundManager,
test_utils::{EmptyStateComputer, MockStorage, MockTransactionManager},
util::{mock_time_service::SimulatedTimeService, time_service::TimeService},
};
use channel::{self, diem_channel, message_queues::QueueStyle};
use consensus_types::proposal_msg::ProposalMsg;
use diem_types::{
epoch_change::EpochChangeProof,
epoch_state::EpochState,
ledger_info::{LedgerInfo, LedgerInfoWithSignatures},
on_chain_config::ValidatorSet,
validator_info::ValidatorInfo,
validator_signer::ValidatorSigner,
validator_verifier::ValidatorVerifier,
};
use futures::{channel::mpsc, executor::block_on};
use network::{
peer_manager::{ConnectionRequestSender, PeerManagerRequestSender},
protocols::network::NewNetworkSender,
};
use once_cell::sync::Lazy;
use safety_rules::{test_utils, SafetyRules, TSafetyRules};
use std::{collections::BTreeMap, sync::Arc, time::Duration};
use tokio::runtime::Runtime;
// This generates a proposal for round 1
pub fn generate_corpus_proposal() -> Vec<u8> {
let mut round_manager = create_node_for_fuzzing();
block_on(async {
let proposal = round_manager
.generate_proposal(NewRoundEvent {
round: 1,
reason: NewRoundReason::QCReady,
timeout: std::time::Duration::new(5, 0),
})
.await;
// serialize and return proposal
bcs::to_bytes(&proposal.unwrap()).unwrap()
})
}
// optimization for the fuzzer
static STATIC_RUNTIME: Lazy<Runtime> = Lazy::new(|| Runtime::new().unwrap());
static FUZZING_SIGNER: Lazy<ValidatorSigner> = Lazy::new(|| ValidatorSigner::from_int(1));
// helpers
fn
|
(
storage: Arc<dyn PersistentLivenessStorage>,
initial_data: RecoveryData,
) -> Arc<BlockStore> {
let (_commit_cb_sender, _commit_cb_receiver) = mpsc::unbounded::<LedgerInfoWithSignatures>();
Arc::new(BlockStore::new(
storage,
initial_data,
Arc::new(EmptyStateComputer),
10, // max pruned blocks in mem
Arc::new(SimulatedTimeService::new()),
))
}
// helpers for safety rule initialization
fn make_initial_epoch_change_proof(signer: &ValidatorSigner) -> EpochChangeProof {
let validator_info =
ValidatorInfo::new_with_test_network_keys(signer.author(), signer.public_key(), 1);
let validator_set = ValidatorSet::new(vec![validator_info]);
let li = LedgerInfo::mock_genesis(Some(validator_set));
let lis = LedgerInfoWithSignatures::new(li, BTreeMap::new());
EpochChangeProof::new(vec![lis], false)
}
// TODO: MockStorage -> EmptyStorage
fn create_round_state() -> RoundState {
let base_timeout = std::time::Duration::new(60, 0);
let time_interval = Box::new(ExponentialTimeInterval::fixed(base_timeout));
let (round_timeout_sender, _) = channel::new_test(1_024);
let time_service = Arc::new(SimulatedTimeService::new());
RoundState::new(time_interval, time_service, round_timeout_sender)
}
// Creates an RoundManager for fuzzing
fn create_node_for_fuzzing() -> RoundManager {
// signer is re-used accross fuzzing runs
let signer = FUZZING_SIGNER.clone();
// TODO: remove
let validator = ValidatorVerifier::new_single(signer.author(), signer.public_key());
let validator_set = (&validator).into();
// TODO: EmptyStorage
let (initial_data, storage) = MockStorage::start_for_testing(validator_set);
// TODO: remove
let proof = make_initial_epoch_change_proof(&signer);
let mut safety_rules = SafetyRules::new(test_utils::test_storage(&signer), false, false);
safety_rules.initialize(&proof).unwrap();
// TODO: mock channels
let (network_reqs_tx, _network_reqs_rx) = diem_channel::new(QueueStyle::FIFO, 8, None);
let (connection_reqs_tx, _) = diem_channel::new(QueueStyle::FIFO, 8, None);
let network_sender = ConsensusNetworkSender::new(
PeerManagerRequestSender::new(network_reqs_tx),
ConnectionRequestSender::new(connection_reqs_tx),
);
let (self_sender, _self_receiver) = channel::new_test(8);
let epoch_state = EpochState {
epoch: 1,
verifier: storage.get_validator_set().into(),
};
let network = NetworkSender::new(
signer.author(),
network_sender,
self_sender,
epoch_state.verifier.clone(),
);
// TODO: mock
let block_store = build_empty_store(storage.clone(), initial_data);
// TODO: remove
let time_service = Arc::new(SimulatedTimeService::new());
time_service.sleep(Duration::from_millis(1));
// TODO: remove
let proposal_generator = ProposalGenerator::new(
signer.author(),
block_store.clone(),
Arc::new(MockTransactionManager::new(None)),
time_service,
1,
);
//
let round_state = create_round_state();
// TODO: have two different nodes, one for proposing, one for accepting a proposal
let proposer_election = Box::new(RotatingProposer::new(vec![signer.author()], 1));
// event processor
RoundManager::new(
epoch_state,
Arc::clone(&block_store),
round_state,
proposer_election,
proposal_generator,
MetricsSafetyRules::new(Box::new(safety_rules), storage.clone()),
network,
Arc::new(MockTransactionManager::new(None)),
storage,
false,
)
}
// This functions fuzzes a Proposal protobuffer (not a ConsensusMsg)
pub fn fuzz_proposal(data: &[u8]) {
// create node
let mut round_manager = create_node_for_fuzzing();
let proposal: ProposalMsg = match bcs::from_bytes(data) {
Ok(xx) => xx,
Err(_) => {
if cfg!(test) {
panic!();
}
return;
}
};
let proposal = match proposal.verify_well_formed() {
Ok(_) => proposal,
Err(e) => {
println!("{:?}", e);
if cfg!(test) {
panic!();
}
return;
}
};
block_on(async move {
// TODO: make sure this obtains a vote when testing
// TODO: make sure that if this obtains a vote, it's for round 1, etc.
let _ = round_manager.process_proposal_msg(proposal).await;
});
}
// This test is here so that the fuzzer can be maintained
#[test]
fn test_consensus_proposal_fuzzer() {
// generate a proposal
let proposal = generate_corpus_proposal();
// successfully parse it
fuzz_proposal(&proposal);
}
|
build_empty_store
|
identifier_name
|
mod.rs
|
// Copyleft (ↄ) meh. <[email protected]> | http://meh.schizofreni.co
//
// This file is part of cancer.
//
// cancer is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// cancer is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with cancer. If not, see <http://www.gnu.org/licenses/>.
mod window;
pub use self::window::{Window, Request};
mod keyboard;
pub use self::keyboard::Keyboard;
mod proxy;
|
pub use self::proxy::Proxy;
|
random_line_split
|
|
shadow.rs
|
// 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
|
(c: Vec<int> ) {
let a: int = 5;
let mut b: Vec<int> = Vec::new();
match t::none::<int> {
t::some::<int>(_) => {
for _i in c.iter() {
println!("{}", a);
let a = 17i;
b.push(a);
}
}
_ => { }
}
}
enum t<T> { none, some(T), }
pub fn main() { let x = 10i; let x = x + 20; assert!((x == 30)); foo(Vec::new()); }
|
foo
|
identifier_name
|
shadow.rs
|
// 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 foo(c: Vec<int> ) {
let a: int = 5;
let mut b: Vec<int> = Vec::new();
match t::none::<int> {
t::some::<int>(_) => {
for _i in c.iter() {
println!("{}", a);
let a = 17i;
b.push(a);
}
}
_ => { }
}
}
enum t<T> { none, some(T), }
pub fn main() { let x = 10i; let x = x + 20; assert!((x == 30)); foo(Vec::new()); }
|
random_line_split
|
|
console.rs
|
/* 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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::codegen::Bindings::ConsoleBinding;
use dom::bindings::codegen::Bindings::ConsoleBinding::ConsoleMethods;
use dom::bindings::global::{GlobalField, GlobalRef};
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use util::str::DOMString;
// https://developer.mozilla.org/en-US/docs/Web/API/Console
#[dom_struct]
pub struct Console {
reflector_: Reflector,
global: GlobalField,
}
impl Console {
fn new_inherited(global: GlobalRef) -> Console {
Console {
reflector_: Reflector::new(),
global: GlobalField::from_rooted(&global),
}
}
pub fn new(global: GlobalRef) -> Root<Console> {
reflect_dom_object(box Console::new_inherited(global),
global,
ConsoleBinding::Wrap)
}
}
impl ConsoleMethods for Console {
// https://developer.mozilla.org/en-US/docs/Web/API/Console/log
fn Log(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Log, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console
fn Debug(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Debug, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/info
fn Info(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Info, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/warn
fn Warn(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Warn, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/error
fn Error(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/assert
fn Assert(&self, condition: bool, message: Option<DOMString>) {
if!condition
|
}
}
fn prepare_message(logLevel: LogLevel, message: DOMString) -> ConsoleMessage {
// TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later
ConsoleMessage {
message: String::from(message),
logLevel: logLevel,
filename: "test".to_owned(),
lineNumber: 1,
columnNumber: 1,
}
}
fn propagate_console_msg(console: &&Console, console_message: ConsoleMessage) {
let global = console.global.root();
let pipelineId = global.r().pipeline();
global.r().devtools_chan().as_ref().map(|chan| {
chan.send(ScriptToDevtoolsControlMsg::ConsoleAPI(pipelineId,
console_message.clone(),
global.r().get_worker_id()))
.unwrap();
});
}
|
{
let message = message.unwrap_or_else(|| DOMString::from("no message"));
println!("Assertion failed: {}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
}
|
conditional_block
|
console.rs
|
/* 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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::codegen::Bindings::ConsoleBinding;
use dom::bindings::codegen::Bindings::ConsoleBinding::ConsoleMethods;
use dom::bindings::global::{GlobalField, GlobalRef};
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use util::str::DOMString;
// https://developer.mozilla.org/en-US/docs/Web/API/Console
#[dom_struct]
pub struct
|
{
reflector_: Reflector,
global: GlobalField,
}
impl Console {
fn new_inherited(global: GlobalRef) -> Console {
Console {
reflector_: Reflector::new(),
global: GlobalField::from_rooted(&global),
}
}
pub fn new(global: GlobalRef) -> Root<Console> {
reflect_dom_object(box Console::new_inherited(global),
global,
ConsoleBinding::Wrap)
}
}
impl ConsoleMethods for Console {
// https://developer.mozilla.org/en-US/docs/Web/API/Console/log
fn Log(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Log, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console
fn Debug(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Debug, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/info
fn Info(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Info, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/warn
fn Warn(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Warn, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/error
fn Error(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/assert
fn Assert(&self, condition: bool, message: Option<DOMString>) {
if!condition {
let message = message.unwrap_or_else(|| DOMString::from("no message"));
println!("Assertion failed: {}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
}
}
}
fn prepare_message(logLevel: LogLevel, message: DOMString) -> ConsoleMessage {
// TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later
ConsoleMessage {
message: String::from(message),
logLevel: logLevel,
filename: "test".to_owned(),
lineNumber: 1,
columnNumber: 1,
}
}
fn propagate_console_msg(console: &&Console, console_message: ConsoleMessage) {
let global = console.global.root();
let pipelineId = global.r().pipeline();
global.r().devtools_chan().as_ref().map(|chan| {
chan.send(ScriptToDevtoolsControlMsg::ConsoleAPI(pipelineId,
console_message.clone(),
global.r().get_worker_id()))
.unwrap();
});
}
|
Console
|
identifier_name
|
console.rs
|
/* 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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::codegen::Bindings::ConsoleBinding;
use dom::bindings::codegen::Bindings::ConsoleBinding::ConsoleMethods;
use dom::bindings::global::{GlobalField, GlobalRef};
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use util::str::DOMString;
// https://developer.mozilla.org/en-US/docs/Web/API/Console
#[dom_struct]
pub struct Console {
reflector_: Reflector,
global: GlobalField,
}
impl Console {
fn new_inherited(global: GlobalRef) -> Console {
Console {
reflector_: Reflector::new(),
global: GlobalField::from_rooted(&global),
}
}
pub fn new(global: GlobalRef) -> Root<Console> {
reflect_dom_object(box Console::new_inherited(global),
global,
ConsoleBinding::Wrap)
}
}
impl ConsoleMethods for Console {
// https://developer.mozilla.org/en-US/docs/Web/API/Console/log
fn Log(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Log, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console
fn Debug(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Debug, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/info
fn Info(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Info, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/warn
fn Warn(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Warn, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/error
fn Error(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/assert
|
println!("Assertion failed: {}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
}
}
}
fn prepare_message(logLevel: LogLevel, message: DOMString) -> ConsoleMessage {
// TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later
ConsoleMessage {
message: String::from(message),
logLevel: logLevel,
filename: "test".to_owned(),
lineNumber: 1,
columnNumber: 1,
}
}
fn propagate_console_msg(console: &&Console, console_message: ConsoleMessage) {
let global = console.global.root();
let pipelineId = global.r().pipeline();
global.r().devtools_chan().as_ref().map(|chan| {
chan.send(ScriptToDevtoolsControlMsg::ConsoleAPI(pipelineId,
console_message.clone(),
global.r().get_worker_id()))
.unwrap();
});
}
|
fn Assert(&self, condition: bool, message: Option<DOMString>) {
if !condition {
let message = message.unwrap_or_else(|| DOMString::from("no message"));
|
random_line_split
|
console.rs
|
/* 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 devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg};
use dom::bindings::codegen::Bindings::ConsoleBinding;
use dom::bindings::codegen::Bindings::ConsoleBinding::ConsoleMethods;
use dom::bindings::global::{GlobalField, GlobalRef};
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use util::str::DOMString;
// https://developer.mozilla.org/en-US/docs/Web/API/Console
#[dom_struct]
pub struct Console {
reflector_: Reflector,
global: GlobalField,
}
impl Console {
fn new_inherited(global: GlobalRef) -> Console
|
pub fn new(global: GlobalRef) -> Root<Console> {
reflect_dom_object(box Console::new_inherited(global),
global,
ConsoleBinding::Wrap)
}
}
impl ConsoleMethods for Console {
// https://developer.mozilla.org/en-US/docs/Web/API/Console/log
fn Log(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Log, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console
fn Debug(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Debug, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/info
fn Info(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Info, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/warn
fn Warn(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Warn, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/error
fn Error(&self, messages: Vec<DOMString>) {
for message in messages {
println!("{}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
}
}
// https://developer.mozilla.org/en-US/docs/Web/API/Console/assert
fn Assert(&self, condition: bool, message: Option<DOMString>) {
if!condition {
let message = message.unwrap_or_else(|| DOMString::from("no message"));
println!("Assertion failed: {}", message);
propagate_console_msg(&self, prepare_message(LogLevel::Error, message));
}
}
}
fn prepare_message(logLevel: LogLevel, message: DOMString) -> ConsoleMessage {
// TODO: Sending fake values for filename, lineNumber and columnNumber in LogMessage; adjust later
ConsoleMessage {
message: String::from(message),
logLevel: logLevel,
filename: "test".to_owned(),
lineNumber: 1,
columnNumber: 1,
}
}
fn propagate_console_msg(console: &&Console, console_message: ConsoleMessage) {
let global = console.global.root();
let pipelineId = global.r().pipeline();
global.r().devtools_chan().as_ref().map(|chan| {
chan.send(ScriptToDevtoolsControlMsg::ConsoleAPI(pipelineId,
console_message.clone(),
global.r().get_worker_id()))
.unwrap();
});
}
|
{
Console {
reflector_: Reflector::new(),
global: GlobalField::from_rooted(&global),
}
}
|
identifier_body
|
thread.rs
|
// 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.
//! Unix-specific extensions to primitives in the `std::thread` module.
#![stable(feature = "thread_extensions", since = "1.9.0")]
use sys_common::{AsInner, IntoInner};
use thread::JoinHandle;
#[stable(feature = "thread_extensions", since = "1.9.0")]
#[allow(deprecated)]
pub type RawPthread = usize;
/// Unix-specific extensions to `std::thread::JoinHandle`
#[stable(feature = "thread_extensions", since = "1.9.0")]
pub trait JoinHandleExt {
/// Extracts the raw pthread_t without taking ownership
#[stable(feature = "thread_extensions", since = "1.9.0")]
fn as_pthread_t(&self) -> RawPthread;
/// Consumes the thread, returning the raw pthread_t
///
/// This function **transfers ownership** of the underlying pthread_t to
/// the caller. Callers are then the unique owners of the pthread_t and
/// must either detach or join the pthread_t once it's no longer needed.
#[stable(feature = "thread_extensions", since = "1.9.0")]
fn into_pthread_t(self) -> RawPthread;
}
#[stable(feature = "thread_extensions", since = "1.9.0")]
impl<T> JoinHandleExt for JoinHandle<T> {
fn
|
(&self) -> RawPthread {
self.as_inner().id() as RawPthread
}
fn into_pthread_t(self) -> RawPthread {
self.into_inner().into_id() as RawPthread
}
}
|
as_pthread_t
|
identifier_name
|
thread.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
|
// 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.
//! Unix-specific extensions to primitives in the `std::thread` module.
#![stable(feature = "thread_extensions", since = "1.9.0")]
use sys_common::{AsInner, IntoInner};
use thread::JoinHandle;
#[stable(feature = "thread_extensions", since = "1.9.0")]
#[allow(deprecated)]
pub type RawPthread = usize;
/// Unix-specific extensions to `std::thread::JoinHandle`
#[stable(feature = "thread_extensions", since = "1.9.0")]
pub trait JoinHandleExt {
/// Extracts the raw pthread_t without taking ownership
#[stable(feature = "thread_extensions", since = "1.9.0")]
fn as_pthread_t(&self) -> RawPthread;
/// Consumes the thread, returning the raw pthread_t
///
/// This function **transfers ownership** of the underlying pthread_t to
/// the caller. Callers are then the unique owners of the pthread_t and
/// must either detach or join the pthread_t once it's no longer needed.
#[stable(feature = "thread_extensions", since = "1.9.0")]
fn into_pthread_t(self) -> RawPthread;
}
#[stable(feature = "thread_extensions", since = "1.9.0")]
impl<T> JoinHandleExt for JoinHandle<T> {
fn as_pthread_t(&self) -> RawPthread {
self.as_inner().id() as RawPthread
}
fn into_pthread_t(self) -> RawPthread {
self.into_inner().into_id() as RawPthread
}
}
|
// http://rust-lang.org/COPYRIGHT.
//
|
random_line_split
|
thread.rs
|
// 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.
//! Unix-specific extensions to primitives in the `std::thread` module.
#![stable(feature = "thread_extensions", since = "1.9.0")]
use sys_common::{AsInner, IntoInner};
use thread::JoinHandle;
#[stable(feature = "thread_extensions", since = "1.9.0")]
#[allow(deprecated)]
pub type RawPthread = usize;
/// Unix-specific extensions to `std::thread::JoinHandle`
#[stable(feature = "thread_extensions", since = "1.9.0")]
pub trait JoinHandleExt {
/// Extracts the raw pthread_t without taking ownership
#[stable(feature = "thread_extensions", since = "1.9.0")]
fn as_pthread_t(&self) -> RawPthread;
/// Consumes the thread, returning the raw pthread_t
///
/// This function **transfers ownership** of the underlying pthread_t to
/// the caller. Callers are then the unique owners of the pthread_t and
/// must either detach or join the pthread_t once it's no longer needed.
#[stable(feature = "thread_extensions", since = "1.9.0")]
fn into_pthread_t(self) -> RawPthread;
}
#[stable(feature = "thread_extensions", since = "1.9.0")]
impl<T> JoinHandleExt for JoinHandle<T> {
fn as_pthread_t(&self) -> RawPthread {
self.as_inner().id() as RawPthread
}
fn into_pthread_t(self) -> RawPthread
|
}
|
{
self.into_inner().into_id() as RawPthread
}
|
identifier_body
|
lib.rs
|
//! A generic filesystem with disk and in-memory implementations.
//!
//! # Reason for existence
//!
//! The [`std::fs`] module provides functions to manipulate the filesytem, and these functions are
//! good. However, if you have code that uses `std::fs`, it is difficult to ensure that your code
//! handles errors properly because generally, you are not testing on an already broken machine.
//! You could attempt to set up FUSE, which, although doable, is involved.
//!
//! This crate provides a generic filesystem with various implementations. At the moment, only
//! normal (non-injectable) disk and in-memory implementations are provided. In the future, an
//! error-injectable shim around the in-memory file system will be provided to help trigger
//! filesystem errors in unit tests.
//!
//! The intent of this crate is for you to use the generic [`rsfs::GenFS`] everywhere where you use
//! `std::fs` in your code. Your `main.rs` can use [`rsfs::disk::FS`] to get default disk behavior
//! while your tests use `rsfs::mem::test::FS` (once it exists) to get an in-memory filesystem that
//! can have errors injected.
//!
//! # An in-memory filesystem
//!
//! There existed no complete in-process in-memory filesystem when I wrote this crate; the
//! implementation in [`rsfs::mem`] should suffice most needs.
//!
//! `rsfs::mem` is a platform specific module that `pub use`s the proper module based off the
//! builder's platform. To get a platform agnostic module, you need to use the in-memory platform
//! you desire. Thus, if you use [`rsfs::mem::unix`], you will get an in-memory system that follows
//! Unix semantics. If you use `rsfs::mem::windows`, you will get an in-memory system that follows
//! Windows semantics (however, you would have to write that module first).
//!
//! This means that `rsfs::mem` aims to essentially be an in-memory drop in for `std::fs` and
//! forces you to structure your code in a cross-platform way. `rsfs::mem::unix` aims to be a Unix
//! specific drop in that buys you Unix semantics on all platforms.
//!
//! # Caveats
//!
//! The current in-memory filesystems are only implemented for Unix. This means that the only
//! cross-platform in-memory filesystem is specifically `rsfs::mem::unix`. Window's users can help
//! by implementing the in-memory analog for Windows.
//!
//! The in-memory filesystem is implemented using some unsafe code. I deemed this necessary after
//! working with the recursive data structure that is a filesystem through an `Arc`/`RwLock` for
//! too long. The code is pretty well tested; there should be no problems. The usage of unsafe, in
//! my opinion, makes the code much clearer, but it did require special care in some functions.
//!
//! # Documentation credit
//!
//! This crate copies _a lot_ of the documentation and examples that currently exist in `std::fs`.
//! It not only makes it easier for people to migrate straight to this crate, but makes this crate
//! much more understandable. This crate includes Rust's MIT license in its repo for further
//! attribution purposes.
//!
//! [`std::fs`]: https://doc.rust-lang.org/std/fs/
//! [`rsfs::GenFS`]: trait.GenFS.html
//! [`rsfs::disk::FS`]: disk/struct.FS.html
//! [`rsfs::mem`]: mem/index.html
//! [`rsfs::mem::unix`]: mem/unix/index.html
mod fs;
pub use fs::*;
|
mod errors;
mod path_parts;
mod ptr;
|
pub mod disk;
pub mod mem;
pub mod unix_ext;
|
random_line_split
|
sleep.rs
|
#[cfg(all(target_os = "polymorphos", target_arch = "x86_64"))]
pub fn sleep_for_ms(count: u32) {
use crate::timer::Timer;
use crate::TIMER;
let must_reach: Timer = x86_64::instructions::interrupts::without_interrupts(|| {
let timer = TIMER.get();
let mut must_reach = timer.clone();
must_reach.increment_ms(count);
must_reach
});
loop {
let mut reached = false;
x86_64::instructions::interrupts::without_interrupts(|| {
let current = TIMER.get();
reached = *current >= must_reach;
});
if reached {
break;
}
x86_64::instructions::hlt();
}
}
#[cfg(any(test, rustdoc))]
pub fn
|
(count: u32) {
let duration = std::time::Duration::from_millis(u64::from(count));
std::thread::sleep(duration);
}
|
sleep_for_ms
|
identifier_name
|
sleep.rs
|
#[cfg(all(target_os = "polymorphos", target_arch = "x86_64"))]
pub fn sleep_for_ms(count: u32)
|
break;
}
x86_64::instructions::hlt();
}
}
#[cfg(any(test, rustdoc))]
pub fn sleep_for_ms(count: u32) {
let duration = std::time::Duration::from_millis(u64::from(count));
std::thread::sleep(duration);
}
|
{
use crate::timer::Timer;
use crate::TIMER;
let must_reach: Timer = x86_64::instructions::interrupts::without_interrupts(|| {
let timer = TIMER.get();
let mut must_reach = timer.clone();
must_reach.increment_ms(count);
must_reach
});
loop {
let mut reached = false;
x86_64::instructions::interrupts::without_interrupts(|| {
let current = TIMER.get();
reached = *current >= must_reach;
});
if reached {
|
identifier_body
|
sleep.rs
|
#[cfg(all(target_os = "polymorphos", target_arch = "x86_64"))]
pub fn sleep_for_ms(count: u32) {
use crate::timer::Timer;
use crate::TIMER;
let must_reach: Timer = x86_64::instructions::interrupts::without_interrupts(|| {
let timer = TIMER.get();
let mut must_reach = timer.clone();
must_reach.increment_ms(count);
must_reach
});
|
let mut reached = false;
x86_64::instructions::interrupts::without_interrupts(|| {
let current = TIMER.get();
reached = *current >= must_reach;
});
if reached {
break;
}
x86_64::instructions::hlt();
}
}
#[cfg(any(test, rustdoc))]
pub fn sleep_for_ms(count: u32) {
let duration = std::time::Duration::from_millis(u64::from(count));
std::thread::sleep(duration);
}
|
loop {
|
random_line_split
|
sleep.rs
|
#[cfg(all(target_os = "polymorphos", target_arch = "x86_64"))]
pub fn sleep_for_ms(count: u32) {
use crate::timer::Timer;
use crate::TIMER;
let must_reach: Timer = x86_64::instructions::interrupts::without_interrupts(|| {
let timer = TIMER.get();
let mut must_reach = timer.clone();
must_reach.increment_ms(count);
must_reach
});
loop {
let mut reached = false;
x86_64::instructions::interrupts::without_interrupts(|| {
let current = TIMER.get();
reached = *current >= must_reach;
});
if reached
|
x86_64::instructions::hlt();
}
}
#[cfg(any(test, rustdoc))]
pub fn sleep_for_ms(count: u32) {
let duration = std::time::Duration::from_millis(u64::from(count));
std::thread::sleep(duration);
}
|
{
break;
}
|
conditional_block
|
vfixupimmsd.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vfixupimmsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(Direct(XMM7)), operand4: Some(Literal8(115)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K2), broadcast: None }, &[98, 243, 237, 154, 85, 239, 115], OperandSize::Dword)
}
fn vfixupimmsd_2() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(IndirectScaledIndexedDisplaced(EDX, EBX, Two, 1540894690, Some(OperandSize::Qword), None)), operand4: Some(Literal8(71)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98, 243, 237, 142, 85, 172, 90, 226, 47, 216, 91, 71], OperandSize::Dword)
}
fn vfixupimmsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM23)), operand3: Some(Direct(XMM24)), operand4: Some(Literal8(91)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K7), broadcast: None }, &[98, 147, 197, 151, 85, 216, 91], OperandSize::Qword)
}
fn vfixupimmsd_4()
|
{
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM21)), operand2: Some(Direct(XMM27)), operand3: Some(IndirectDisplaced(RAX, 1072326570, Some(OperandSize::Qword), None)), operand4: Some(Literal8(108)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None }, &[98, 227, 165, 133, 85, 168, 170, 103, 234, 63, 108], OperandSize::Qword)
}
|
identifier_body
|
|
vfixupimmsd.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
|
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(IndirectScaledIndexedDisplaced(EDX, EBX, Two, 1540894690, Some(OperandSize::Qword), None)), operand4: Some(Literal8(71)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98, 243, 237, 142, 85, 172, 90, 226, 47, 216, 91, 71], OperandSize::Dword)
}
fn vfixupimmsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM23)), operand3: Some(Direct(XMM24)), operand4: Some(Literal8(91)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K7), broadcast: None }, &[98, 147, 197, 151, 85, 216, 91], OperandSize::Qword)
}
fn vfixupimmsd_4() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM21)), operand2: Some(Direct(XMM27)), operand3: Some(IndirectDisplaced(RAX, 1072326570, Some(OperandSize::Qword), None)), operand4: Some(Literal8(108)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None }, &[98, 227, 165, 133, 85, 168, 170, 103, 234, 63, 108], OperandSize::Qword)
}
|
fn vfixupimmsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(Direct(XMM7)), operand4: Some(Literal8(115)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K2), broadcast: None }, &[98, 243, 237, 154, 85, 239, 115], OperandSize::Dword)
}
fn vfixupimmsd_2() {
|
random_line_split
|
vfixupimmsd.rs
|
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vfixupimmsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(Direct(XMM7)), operand4: Some(Literal8(115)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K2), broadcast: None }, &[98, 243, 237, 154, 85, 239, 115], OperandSize::Dword)
}
fn
|
() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(IndirectScaledIndexedDisplaced(EDX, EBX, Two, 1540894690, Some(OperandSize::Qword), None)), operand4: Some(Literal8(71)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K6), broadcast: None }, &[98, 243, 237, 142, 85, 172, 90, 226, 47, 216, 91, 71], OperandSize::Dword)
}
fn vfixupimmsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM3)), operand2: Some(Direct(XMM23)), operand3: Some(Direct(XMM24)), operand4: Some(Literal8(91)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: true, mask: Some(MaskReg::K7), broadcast: None }, &[98, 147, 197, 151, 85, 216, 91], OperandSize::Qword)
}
fn vfixupimmsd_4() {
run_test(&Instruction { mnemonic: Mnemonic::VFIXUPIMMSD, operand1: Some(Direct(XMM21)), operand2: Some(Direct(XMM27)), operand3: Some(IndirectDisplaced(RAX, 1072326570, Some(OperandSize::Qword), None)), operand4: Some(Literal8(108)), lock: false, rounding_mode: None, merge_mode: Some(MergeMode::Zero), sae: false, mask: Some(MaskReg::K5), broadcast: None }, &[98, 227, 165, 133, 85, 168, 170, 103, 234, 63, 108], OperandSize::Qword)
}
|
vfixupimmsd_2
|
identifier_name
|
workspace_folders.rs
|
use serde::{Deserialize, Serialize};
use url::Url;
use crate::OneOf;
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceFoldersServerCapabilities {
/// The server has support for workspace folders
#[serde(skip_serializing_if = "Option::is_none")]
pub supported: Option<bool>,
/// Whether the server wants to receive workspace folder
/// change notifications.
///
/// If a string is provided, the string is treated as an ID
/// under which the notification is registered on the client
|
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceFolder {
/// The associated URI for this workspace folder.
pub uri: Url,
/// The name of the workspace folder. Defaults to the uri's basename.
pub name: String,
}
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DidChangeWorkspaceFoldersParams {
/// The actual workspace folder change event.
pub event: WorkspaceFoldersChangeEvent,
}
/// The workspace folder change event.
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceFoldersChangeEvent {
/// The array of added workspace folders
pub added: Vec<WorkspaceFolder>,
/// The array of the removed workspace folders
pub removed: Vec<WorkspaceFolder>,
}
|
/// side. The ID can be used to unregister for these events
/// using the `client/unregisterCapability` request.
#[serde(skip_serializing_if = "Option::is_none")]
pub change_notifications: Option<OneOf<bool, String>>,
}
|
random_line_split
|
workspace_folders.rs
|
use serde::{Deserialize, Serialize};
use url::Url;
use crate::OneOf;
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceFoldersServerCapabilities {
/// The server has support for workspace folders
#[serde(skip_serializing_if = "Option::is_none")]
pub supported: Option<bool>,
/// Whether the server wants to receive workspace folder
/// change notifications.
///
/// If a string is provided, the string is treated as an ID
/// under which the notification is registered on the client
/// side. The ID can be used to unregister for these events
/// using the `client/unregisterCapability` request.
#[serde(skip_serializing_if = "Option::is_none")]
pub change_notifications: Option<OneOf<bool, String>>,
}
#[derive(Debug, Eq, PartialEq, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceFolder {
/// The associated URI for this workspace folder.
pub uri: Url,
/// The name of the workspace folder. Defaults to the uri's basename.
pub name: String,
}
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct
|
{
/// The actual workspace folder change event.
pub event: WorkspaceFoldersChangeEvent,
}
/// The workspace folder change event.
#[derive(Debug, Eq, PartialEq, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WorkspaceFoldersChangeEvent {
/// The array of added workspace folders
pub added: Vec<WorkspaceFolder>,
/// The array of the removed workspace folders
pub removed: Vec<WorkspaceFolder>,
}
|
DidChangeWorkspaceFoldersParams
|
identifier_name
|
error.rs
|
// Copyright (c) 2016 Tibor Benke <[email protected]>
//
// 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. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use serde_json;
use serde_yaml;
use std::io;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
SerdeJson(serde_json::error::Error),
SerdeYaml(serde_yaml::error::Error),
UnsupportedFileExtension,
NotUtf8FileName
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error::Io(error)
}
}
impl From<serde_json::error::Error> for Error {
fn from(error: serde_json::error::Error) -> Error {
Error::SerdeJson(error)
}
}
impl From<serde_yaml::error::Error> for Error {
fn from(error: serde_yaml::error::Error) -> Error
|
}
|
{
Error::SerdeYaml(error)
}
|
identifier_body
|
error.rs
|
// Copyright (c) 2016 Tibor Benke <[email protected]>
//
// 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. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use serde_json;
use serde_yaml;
use std::io;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
SerdeJson(serde_json::error::Error),
SerdeYaml(serde_yaml::error::Error),
UnsupportedFileExtension,
NotUtf8FileName
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error::Io(error)
|
fn from(error: serde_json::error::Error) -> Error {
Error::SerdeJson(error)
}
}
impl From<serde_yaml::error::Error> for Error {
fn from(error: serde_yaml::error::Error) -> Error {
Error::SerdeYaml(error)
}
}
|
}
}
impl From<serde_json::error::Error> for Error {
|
random_line_split
|
error.rs
|
// Copyright (c) 2016 Tibor Benke <[email protected]>
//
// 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. All files in the project carrying such notice may not be copied,
// modified, or distributed except according to those terms.
use serde_json;
use serde_yaml;
use std::io;
#[derive(Debug)]
pub enum Error {
Io(io::Error),
SerdeJson(serde_json::error::Error),
SerdeYaml(serde_yaml::error::Error),
UnsupportedFileExtension,
NotUtf8FileName
}
impl From<io::Error> for Error {
fn from(error: io::Error) -> Error {
Error::Io(error)
}
}
impl From<serde_json::error::Error> for Error {
fn
|
(error: serde_json::error::Error) -> Error {
Error::SerdeJson(error)
}
}
impl From<serde_yaml::error::Error> for Error {
fn from(error: serde_yaml::error::Error) -> Error {
Error::SerdeYaml(error)
}
}
|
from
|
identifier_name
|
hosts.rs
|
/* 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 parse_hosts::HostsFile;
use std::borrow::Cow;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{BufReader, Read};
use std::net::IpAddr;
use std::sync::Mutex;
lazy_static! {
static ref HOST_TABLE: Mutex<Option<HashMap<String, IpAddr>>> = Mutex::new(create_host_table());
}
fn
|
() -> Option<HashMap<String, IpAddr>> {
let path = env::var_os("HOST_FILE")?;
let file = File::open(&path).ok()?;
let mut reader = BufReader::new(file);
let mut lines = String::new();
reader.read_to_string(&mut lines).ok()?;
Some(parse_hostsfile(&lines))
}
pub fn replace_host_table(table: HashMap<String, IpAddr>) {
*HOST_TABLE.lock().unwrap() = Some(table);
}
pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
HostsFile::read_buffered(hostsfile_content.as_bytes())
.pairs()
.filter_map(Result::ok)
.collect()
}
pub fn replace_host(host: &str) -> Cow<str> {
HOST_TABLE.lock().unwrap().as_ref()
.and_then(|table| table.get(host))
.map_or(host.into(), |replaced_host| replaced_host.to_string().into())
}
|
create_host_table
|
identifier_name
|
hosts.rs
|
/* 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 parse_hosts::HostsFile;
use std::borrow::Cow;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{BufReader, Read};
use std::net::IpAddr;
use std::sync::Mutex;
lazy_static! {
static ref HOST_TABLE: Mutex<Option<HashMap<String, IpAddr>>> = Mutex::new(create_host_table());
}
fn create_host_table() -> Option<HashMap<String, IpAddr>> {
let path = env::var_os("HOST_FILE")?;
let file = File::open(&path).ok()?;
let mut reader = BufReader::new(file);
let mut lines = String::new();
reader.read_to_string(&mut lines).ok()?;
Some(parse_hostsfile(&lines))
}
pub fn replace_host_table(table: HashMap<String, IpAddr>)
|
pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
HostsFile::read_buffered(hostsfile_content.as_bytes())
.pairs()
.filter_map(Result::ok)
.collect()
}
pub fn replace_host(host: &str) -> Cow<str> {
HOST_TABLE.lock().unwrap().as_ref()
.and_then(|table| table.get(host))
.map_or(host.into(), |replaced_host| replaced_host.to_string().into())
}
|
{
*HOST_TABLE.lock().unwrap() = Some(table);
}
|
identifier_body
|
hosts.rs
|
/* 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 parse_hosts::HostsFile;
use std::borrow::Cow;
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{BufReader, Read};
use std::net::IpAddr;
use std::sync::Mutex;
lazy_static! {
static ref HOST_TABLE: Mutex<Option<HashMap<String, IpAddr>>> = Mutex::new(create_host_table());
}
fn create_host_table() -> Option<HashMap<String, IpAddr>> {
let path = env::var_os("HOST_FILE")?;
let file = File::open(&path).ok()?;
let mut reader = BufReader::new(file);
let mut lines = String::new();
reader.read_to_string(&mut lines).ok()?;
Some(parse_hostsfile(&lines))
}
|
pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
HostsFile::read_buffered(hostsfile_content.as_bytes())
.pairs()
.filter_map(Result::ok)
.collect()
}
pub fn replace_host(host: &str) -> Cow<str> {
HOST_TABLE.lock().unwrap().as_ref()
.and_then(|table| table.get(host))
.map_or(host.into(), |replaced_host| replaced_host.to_string().into())
}
|
pub fn replace_host_table(table: HashMap<String, IpAddr>) {
*HOST_TABLE.lock().unwrap() = Some(table);
}
|
random_line_split
|
mod.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
// Containers for Mercurial data, stored in the blob store.
mod changeset_envelope;
mod file_envelope;
mod manifest_envelope;
pub use self::changeset_envelope::{HgChangesetEnvelope, HgChangesetEnvelopeMut};
pub use self::file_envelope::{HgFileEnvelope, HgFileEnvelopeMut};
pub use self::manifest_envelope::{HgManifestEnvelope, HgManifestEnvelopeMut};
use blobstore::BlobstoreGetData;
use mononoke_types::BlobstoreBytes;
use bytes::Bytes;
#[derive(Clone, Debug)]
pub struct
|
(Bytes);
impl From<BlobstoreBytes> for HgEnvelopeBlob {
#[inline]
fn from(bytes: BlobstoreBytes) -> HgEnvelopeBlob {
HgEnvelopeBlob(bytes.into_bytes())
}
}
impl From<HgEnvelopeBlob> for BlobstoreBytes {
#[inline]
fn from(blob: HgEnvelopeBlob) -> BlobstoreBytes {
BlobstoreBytes::from_bytes(blob.0)
}
}
impl From<BlobstoreGetData> for HgEnvelopeBlob {
#[inline]
fn from(blob_val: BlobstoreGetData) -> HgEnvelopeBlob {
HgEnvelopeBlob(blob_val.into_raw_bytes())
}
}
impl From<HgEnvelopeBlob> for BlobstoreGetData {
#[inline]
fn from(blob: HgEnvelopeBlob) -> BlobstoreGetData {
BlobstoreBytes::from(blob).into()
}
}
|
HgEnvelopeBlob
|
identifier_name
|
mod.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
// Containers for Mercurial data, stored in the blob store.
mod changeset_envelope;
mod file_envelope;
mod manifest_envelope;
pub use self::changeset_envelope::{HgChangesetEnvelope, HgChangesetEnvelopeMut};
pub use self::file_envelope::{HgFileEnvelope, HgFileEnvelopeMut};
pub use self::manifest_envelope::{HgManifestEnvelope, HgManifestEnvelopeMut};
use blobstore::BlobstoreGetData;
use mononoke_types::BlobstoreBytes;
use bytes::Bytes;
#[derive(Clone, Debug)]
pub struct HgEnvelopeBlob(Bytes);
impl From<BlobstoreBytes> for HgEnvelopeBlob {
#[inline]
fn from(bytes: BlobstoreBytes) -> HgEnvelopeBlob {
HgEnvelopeBlob(bytes.into_bytes())
}
}
|
#[inline]
fn from(blob: HgEnvelopeBlob) -> BlobstoreBytes {
BlobstoreBytes::from_bytes(blob.0)
}
}
impl From<BlobstoreGetData> for HgEnvelopeBlob {
#[inline]
fn from(blob_val: BlobstoreGetData) -> HgEnvelopeBlob {
HgEnvelopeBlob(blob_val.into_raw_bytes())
}
}
impl From<HgEnvelopeBlob> for BlobstoreGetData {
#[inline]
fn from(blob: HgEnvelopeBlob) -> BlobstoreGetData {
BlobstoreBytes::from(blob).into()
}
}
|
impl From<HgEnvelopeBlob> for BlobstoreBytes {
|
random_line_split
|
overload-index-operator.rs
|
// 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.
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
use core::ops::Index;
struct AssociationList<K,V> {
pairs: ~[AssociationPair<K,V>]
}
struct AssociationPair<K,V> {
key: K,
value: V
}
impl<K,V> AssociationList<K,V> {
fn push(&mut self, key: K, value: V) {
self.pairs.push(AssociationPair {key: key, value: value});
}
}
impl<K:Eq,V:Copy> Index<K,V> for AssociationList<K,V> {
fn index(&self, index: &K) -> V {
for self.pairs.each |pair| {
if pair.key == *index {
return copy pair.value;
}
}
fail!(fmt!("No value found for key: %?", index));
}
}
pub fn main()
|
{
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: ~[]};
list.push(copy foo, 22);
list.push(copy bar, 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(list[foo] == 22)
assert!(list[bar] == 44)
}
|
identifier_body
|
|
overload-index-operator.rs
|
// 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.
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
use core::ops::Index;
struct AssociationList<K,V> {
pairs: ~[AssociationPair<K,V>]
}
struct AssociationPair<K,V> {
key: K,
value: V
}
impl<K,V> AssociationList<K,V> {
fn push(&mut self, key: K, value: V) {
self.pairs.push(AssociationPair {key: key, value: value});
}
}
impl<K:Eq,V:Copy> Index<K,V> for AssociationList<K,V> {
fn index(&self, index: &K) -> V {
for self.pairs.each |pair| {
if pair.key == *index {
return copy pair.value;
}
}
fail!(fmt!("No value found for key: %?", index));
}
}
|
pub fn main() {
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: ~[]};
list.push(copy foo, 22);
list.push(copy bar, 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(list[foo] == 22)
assert!(list[bar] == 44)
}
|
random_line_split
|
|
overload-index-operator.rs
|
// 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.
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
use core::ops::Index;
struct AssociationList<K,V> {
pairs: ~[AssociationPair<K,V>]
}
struct AssociationPair<K,V> {
key: K,
value: V
}
impl<K,V> AssociationList<K,V> {
fn push(&mut self, key: K, value: V) {
self.pairs.push(AssociationPair {key: key, value: value});
}
}
impl<K:Eq,V:Copy> Index<K,V> for AssociationList<K,V> {
fn index(&self, index: &K) -> V {
for self.pairs.each |pair| {
if pair.key == *index
|
}
fail!(fmt!("No value found for key: %?", index));
}
}
pub fn main() {
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: ~[]};
list.push(copy foo, 22);
list.push(copy bar, 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(list[foo] == 22)
assert!(list[bar] == 44)
}
|
{
return copy pair.value;
}
|
conditional_block
|
overload-index-operator.rs
|
// 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.
// Test overloading of the `[]` operator. In particular test that it
// takes its argument *by reference*.
use core::ops::Index;
struct AssociationList<K,V> {
pairs: ~[AssociationPair<K,V>]
}
struct AssociationPair<K,V> {
key: K,
value: V
}
impl<K,V> AssociationList<K,V> {
fn
|
(&mut self, key: K, value: V) {
self.pairs.push(AssociationPair {key: key, value: value});
}
}
impl<K:Eq,V:Copy> Index<K,V> for AssociationList<K,V> {
fn index(&self, index: &K) -> V {
for self.pairs.each |pair| {
if pair.key == *index {
return copy pair.value;
}
}
fail!(fmt!("No value found for key: %?", index));
}
}
pub fn main() {
let foo = ~"foo";
let bar = ~"bar";
let mut list = AssociationList {pairs: ~[]};
list.push(copy foo, 22);
list.push(copy bar, 44);
assert!(list[foo] == 22)
assert!(list[bar] == 44)
assert!(list[foo] == 22)
assert!(list[bar] == 44)
}
|
push
|
identifier_name
|
check_cfg.rs
|
use super::CFG;
use super::{Adjacency};
use crate::common::{
function_attributes::FunctionAttribute,
types::Type,
tac_code::{Function, Statement},
error_reporter::{ErrorReporter, ReportKind},
};
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
pub fn check_cfg(
mut functions: Vec<Function>,
cfg: &mut HashMap<Rc<String>, CFG>,
error_reporter: Rc<RefCell<dyn ErrorReporter>>) -> Vec<Function> {
for f in functions.iter_mut() {
check_function(f, cfg.get_mut(&f.function_info.name).unwrap(), error_reporter.clone());
}
functions
}
/*
For non-void functions, check that value is returned in all basic blocks that connect to end block,
For void functions, insert returns if end block does not contain return
*/
fn check_function(
function: &mut Function,
cfg: &mut CFG,
error_reporter: Rc<RefCell<dyn ErrorReporter>>) {
if function.has_attribute(FunctionAttribute::External) {
return;
}
let mut insert_positions = vec![];
for (pos, adjacencies) in cfg.adjacency_list.iter().enumerate() {
if adjacencies.contains(&Adjacency::End) {
let bb = &cfg.basic_blocks[pos];
match function.statements[bb.end-1] {
Statement::Return(_) => (), // OK
_ => {
if function.function_info.return_type!= Type::Void {
error_reporter.borrow_mut().report_error(
ReportKind::DataFlowError,
function.function_info.span.clone(),
format!("Function '{}': Not all control flow paths return a value", function.function_info.name)
)
|
let end = cfg.basic_blocks[pos].end;
insert_positions.push(end);
}
}
}
}
}
for pos in insert_positions.iter() {
cfg.insert_statement(function, *pos, Statement::Return(None));
}
}
|
} else {
|
random_line_split
|
check_cfg.rs
|
use super::CFG;
use super::{Adjacency};
use crate::common::{
function_attributes::FunctionAttribute,
types::Type,
tac_code::{Function, Statement},
error_reporter::{ErrorReporter, ReportKind},
};
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
pub fn check_cfg(
mut functions: Vec<Function>,
cfg: &mut HashMap<Rc<String>, CFG>,
error_reporter: Rc<RefCell<dyn ErrorReporter>>) -> Vec<Function> {
for f in functions.iter_mut() {
check_function(f, cfg.get_mut(&f.function_info.name).unwrap(), error_reporter.clone());
}
functions
}
/*
For non-void functions, check that value is returned in all basic blocks that connect to end block,
For void functions, insert returns if end block does not contain return
*/
fn check_function(
function: &mut Function,
cfg: &mut CFG,
error_reporter: Rc<RefCell<dyn ErrorReporter>>)
|
)
} else {
let end = cfg.basic_blocks[pos].end;
insert_positions.push(end);
}
}
}
}
}
for pos in insert_positions.iter() {
cfg.insert_statement(function, *pos, Statement::Return(None));
}
}
|
{
if function.has_attribute(FunctionAttribute::External) {
return;
}
let mut insert_positions = vec![];
for (pos, adjacencies) in cfg.adjacency_list.iter().enumerate() {
if adjacencies.contains(&Adjacency::End) {
let bb = &cfg.basic_blocks[pos];
match function.statements[bb.end-1] {
Statement::Return(_) => (), // OK
_ => {
if function.function_info.return_type != Type::Void {
error_reporter.borrow_mut().report_error(
ReportKind::DataFlowError,
function.function_info.span.clone(),
format!("Function '{}': Not all control flow paths return a value", function.function_info.name)
|
identifier_body
|
check_cfg.rs
|
use super::CFG;
use super::{Adjacency};
use crate::common::{
function_attributes::FunctionAttribute,
types::Type,
tac_code::{Function, Statement},
error_reporter::{ErrorReporter, ReportKind},
};
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
pub fn check_cfg(
mut functions: Vec<Function>,
cfg: &mut HashMap<Rc<String>, CFG>,
error_reporter: Rc<RefCell<dyn ErrorReporter>>) -> Vec<Function> {
for f in functions.iter_mut() {
check_function(f, cfg.get_mut(&f.function_info.name).unwrap(), error_reporter.clone());
}
functions
}
/*
For non-void functions, check that value is returned in all basic blocks that connect to end block,
For void functions, insert returns if end block does not contain return
*/
fn check_function(
function: &mut Function,
cfg: &mut CFG,
error_reporter: Rc<RefCell<dyn ErrorReporter>>) {
if function.has_attribute(FunctionAttribute::External)
|
let mut insert_positions = vec![];
for (pos, adjacencies) in cfg.adjacency_list.iter().enumerate() {
if adjacencies.contains(&Adjacency::End) {
let bb = &cfg.basic_blocks[pos];
match function.statements[bb.end-1] {
Statement::Return(_) => (), // OK
_ => {
if function.function_info.return_type!= Type::Void {
error_reporter.borrow_mut().report_error(
ReportKind::DataFlowError,
function.function_info.span.clone(),
format!("Function '{}': Not all control flow paths return a value", function.function_info.name)
)
} else {
let end = cfg.basic_blocks[pos].end;
insert_positions.push(end);
}
}
}
}
}
for pos in insert_positions.iter() {
cfg.insert_statement(function, *pos, Statement::Return(None));
}
}
|
{
return;
}
|
conditional_block
|
check_cfg.rs
|
use super::CFG;
use super::{Adjacency};
use crate::common::{
function_attributes::FunctionAttribute,
types::Type,
tac_code::{Function, Statement},
error_reporter::{ErrorReporter, ReportKind},
};
use std::collections::HashMap;
use std::rc::Rc;
use std::cell::RefCell;
pub fn check_cfg(
mut functions: Vec<Function>,
cfg: &mut HashMap<Rc<String>, CFG>,
error_reporter: Rc<RefCell<dyn ErrorReporter>>) -> Vec<Function> {
for f in functions.iter_mut() {
check_function(f, cfg.get_mut(&f.function_info.name).unwrap(), error_reporter.clone());
}
functions
}
/*
For non-void functions, check that value is returned in all basic blocks that connect to end block,
For void functions, insert returns if end block does not contain return
*/
fn
|
(
function: &mut Function,
cfg: &mut CFG,
error_reporter: Rc<RefCell<dyn ErrorReporter>>) {
if function.has_attribute(FunctionAttribute::External) {
return;
}
let mut insert_positions = vec![];
for (pos, adjacencies) in cfg.adjacency_list.iter().enumerate() {
if adjacencies.contains(&Adjacency::End) {
let bb = &cfg.basic_blocks[pos];
match function.statements[bb.end-1] {
Statement::Return(_) => (), // OK
_ => {
if function.function_info.return_type!= Type::Void {
error_reporter.borrow_mut().report_error(
ReportKind::DataFlowError,
function.function_info.span.clone(),
format!("Function '{}': Not all control flow paths return a value", function.function_info.name)
)
} else {
let end = cfg.basic_blocks[pos].end;
insert_positions.push(end);
}
}
}
}
}
for pos in insert_positions.iter() {
cfg.insert_statement(function, *pos, Statement::Return(None));
}
}
|
check_function
|
identifier_name
|
trait-bounds-on-structs-and-enums.rs
|
// 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.
trait Trait {}
struct Foo<T:Trait> {
x: T,
}
enum Bar<T:Trait> {
ABar(isize),
BBar(T),
CBar(usize),
}
fn explode(x: Foo<u32>) {}
//~^ ERROR not implemented
fn kaboom(y: Bar<f32>) {}
//~^ ERROR not implemented
impl<T> Foo<T> {
|
//~^ ERROR not implemented
a: Foo<isize>,
}
enum Boo {
//~^ ERROR not implemented
Quux(Bar<usize>),
}
struct Badness<U> {
//~^ ERROR not implemented
b: Foo<U>,
}
enum MoreBadness<V> {
//~^ ERROR not implemented
EvenMoreBadness(Bar<V>),
}
trait PolyTrait<T> {
fn whatever() {}
}
struct Struct;
impl PolyTrait<Foo<usize>> for Struct {
//~^ ERROR not implemented
fn whatever() {}
}
fn main() {
}
|
//~^ ERROR the trait `Trait` is not implemented
fn uhoh() {}
}
struct Baz {
|
random_line_split
|
trait-bounds-on-structs-and-enums.rs
|
// 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.
trait Trait {}
struct Foo<T:Trait> {
x: T,
}
enum Bar<T:Trait> {
ABar(isize),
BBar(T),
CBar(usize),
}
fn explode(x: Foo<u32>) {}
//~^ ERROR not implemented
fn kaboom(y: Bar<f32>) {}
//~^ ERROR not implemented
impl<T> Foo<T> {
//~^ ERROR the trait `Trait` is not implemented
fn uhoh() {}
}
struct Baz {
//~^ ERROR not implemented
a: Foo<isize>,
}
enum Boo {
//~^ ERROR not implemented
Quux(Bar<usize>),
}
struct Badness<U> {
//~^ ERROR not implemented
b: Foo<U>,
}
enum MoreBadness<V> {
//~^ ERROR not implemented
EvenMoreBadness(Bar<V>),
}
trait PolyTrait<T> {
fn whatever() {}
}
struct Struct;
impl PolyTrait<Foo<usize>> for Struct {
//~^ ERROR not implemented
fn
|
() {}
}
fn main() {
}
|
whatever
|
identifier_name
|
borrowck-move-out-of-vec-tail.rs
|
// 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.
// Test that we do not permit moves from &[] matched by a vec pattern.
extern crate debug;
|
}
pub fn main() {
let x = vec!(
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
);
let x: &[Foo] = x.as_slice();
match x {
[_, tail..] => {
match tail {
[Foo { string: a }, //~ ERROR cannot move out of dereference of `&`-pointer
Foo { string: b }] => {
//~^^ NOTE attempting to move value to here
//~^^ NOTE and here
}
_ => {
unreachable!();
}
}
let z = tail[0].clone();
println!("{:?}", z);
}
_ => {
unreachable!();
}
}
}
|
#[deriving(Clone)]
struct Foo {
string: String
|
random_line_split
|
borrowck-move-out-of-vec-tail.rs
|
// 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.
// Test that we do not permit moves from &[] matched by a vec pattern.
extern crate debug;
#[deriving(Clone)]
struct
|
{
string: String
}
pub fn main() {
let x = vec!(
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
);
let x: &[Foo] = x.as_slice();
match x {
[_, tail..] => {
match tail {
[Foo { string: a }, //~ ERROR cannot move out of dereference of `&`-pointer
Foo { string: b }] => {
//~^^ NOTE attempting to move value to here
//~^^ NOTE and here
}
_ => {
unreachable!();
}
}
let z = tail[0].clone();
println!("{:?}", z);
}
_ => {
unreachable!();
}
}
}
|
Foo
|
identifier_name
|
borrowck-move-out-of-vec-tail.rs
|
// 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.
// Test that we do not permit moves from &[] matched by a vec pattern.
extern crate debug;
#[deriving(Clone)]
struct Foo {
string: String
}
pub fn main()
|
println!("{:?}", z);
}
_ => {
unreachable!();
}
}
}
|
{
let x = vec!(
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
);
let x: &[Foo] = x.as_slice();
match x {
[_, tail..] => {
match tail {
[Foo { string: a }, //~ ERROR cannot move out of dereference of `&`-pointer
Foo { string: b }] => {
//~^^ NOTE attempting to move value to here
//~^^ NOTE and here
}
_ => {
unreachable!();
}
}
let z = tail[0].clone();
|
identifier_body
|
borrowck-move-out-of-vec-tail.rs
|
// 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.
// Test that we do not permit moves from &[] matched by a vec pattern.
extern crate debug;
#[deriving(Clone)]
struct Foo {
string: String
}
pub fn main() {
let x = vec!(
Foo { string: "foo".to_string() },
Foo { string: "bar".to_string() },
Foo { string: "baz".to_string() }
);
let x: &[Foo] = x.as_slice();
match x {
[_, tail..] =>
|
_ => {
unreachable!();
}
}
}
|
{
match tail {
[Foo { string: a }, //~ ERROR cannot move out of dereference of `&`-pointer
Foo { string: b }] => {
//~^^ NOTE attempting to move value to here
//~^^ NOTE and here
}
_ => {
unreachable!();
}
}
let z = tail[0].clone();
println!("{:?}", z);
}
|
conditional_block
|
mod.rs
|
pub type c_long = i32;
pub type c_ulong = u32;
pub type nlink_t = u32;
s! {
pub struct pthread_attr_t {
__size: [u32; 9]
}
pub struct sigset_t {
__val: [::c_ulong; 32],
}
pub struct msghdr {
pub msg_name: *mut ::c_void,
pub msg_namelen: ::socklen_t,
pub msg_iov: *mut ::iovec,
pub msg_iovlen: ::c_int,
pub msg_control: *mut ::c_void,
pub msg_controllen: ::socklen_t,
pub msg_flags: ::c_int,
}
pub struct cmsghdr {
pub cmsg_len: ::socklen_t,
pub cmsg_level: ::c_int,
pub cmsg_type: ::c_int,
}
pub struct sem_t {
__val: [::c_int; 4],
}
}
pub const __SIZEOF_PTHREAD_RWLOCK_T: usize = 32;
pub const __SIZEOF_PTHREAD_MUTEX_T: usize = 24;
cfg_if! {
if #[cfg(any(target_arch = "x86"))] {
mod x86;
pub use self::x86::*;
} else if #[cfg(any(target_arch = "mips"))] {
mod mips;
pub use self::mips::*;
|
} else if #[cfg(any(target_arch = "arm"))] {
mod arm;
pub use self::arm::*;
} else if #[cfg(any(target_arch = "asmjs", target_arch = "wasm32"))] {
// For the time being asmjs and wasm32 are the same, and both
// backed by identical emscripten runtimes
mod asmjs;
pub use self::asmjs::*;
} else {
// Unknown target_arch
}
}
|
random_line_split
|
|
class-method-cross-crate.rs
|
// Copyright 2012-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.
// aux-build:cci_class_2.rs
extern crate cci_class_2;
use cci_class_2::kitties::cat;
pub fn main()
|
{
let nyan : cat = cat(52u, 99);
let kitty = cat(1000u, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak();
}
|
identifier_body
|
|
class-method-cross-crate.rs
|
// Copyright 2012-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.
// aux-build:cci_class_2.rs
extern crate cci_class_2;
use cci_class_2::kitties::cat;
pub fn
|
() {
let nyan : cat = cat(52u, 99);
let kitty = cat(1000u, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
nyan.speak();
}
|
main
|
identifier_name
|
class-method-cross-crate.rs
|
// Copyright 2012-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.
// aux-build:cci_class_2.rs
extern crate cci_class_2;
use cci_class_2::kitties::cat;
pub fn main() {
let nyan : cat = cat(52u, 99);
let kitty = cat(1000u, 2);
assert_eq!(nyan.how_hungry, 99);
assert_eq!(kitty.how_hungry, 2);
|
nyan.speak();
}
|
random_line_split
|
|
lib.rs
|
//! The runtime for writing applications for [Ice](https://github.com/losfair/IceCore),
//! an efficient, reliable and asynchronous platform for building modern backend applications
//! in WebAssembly.
//!
//! At a high level, `ia` (which stands for "Ice App") provides a few major components (based on
//! the underlying Ice Core engine):
//!
//! - Asynchronous TCP server and client
//! - File I/O
//! - Timer (not working for now due to an Ice bug)
//!
//! The asynchronous APIs are based on `futures`, while low-level callback-based APIs
//! are also provided.
//!
//! # Examples
//! A simple TCP proxy that forwards `127.0.0.1:1111` to `127.0.0.1:80`:
|
//! extern crate ia;
//! extern crate futures_await as futures;
//!
//! use futures::prelude::*;
//! use ia::net::{TcpListener, TcpConnection};
//! use ia::error::IoResult;
//!
//! #[async]
//! fn handle_connection(incoming: TcpConnection) -> IoResult<()> {
//! #[async]
//! fn forward(from: TcpConnection, to: TcpConnection) -> IoResult<()> {
//! while let Ok(v) = await!(from.read(4096)) {
//! if v.len() == 0 {
//! break;
//! }
//! await!(to.write(v))?;
//! }
//! Ok(())
//! }
//! let proxied = await!(TcpConnection::connect("127.0.0.1:80"))?;
//! ia::spawn(forward(proxied.clone(), incoming.clone()));
//! await!(forward(incoming, proxied))?;
//!
//! Ok(())
//! }
//!
//! #[async]
//! fn run_proxy() -> IoResult<()> {
//! static LISTEN_ADDR: &'static str = "127.0.0.1:1111";
//! let listener = TcpListener::new(LISTEN_ADDR);
//! println!("Listening on {}", LISTEN_ADDR);
//!
//! #[async]
//! for incoming in listener {
//! ia::spawn(handle_connection(incoming));
//! }
//!
//! Ok(())
//! }
//!
//! app_init!({
//! ia::spawn(run_proxy());
//! 0
//! });
//!
//! ```
//!
//! See [simpleproxy](https://github.com/losfair/IceCore/tree/master/ia/examples/simpleproxy) for the
//! full code & project layout.
#![feature(fnbox)]
#![feature(never_type)]
pub extern crate futures;
pub extern crate cwa;
#[macro_use]
pub mod log;
pub mod raw;
pub mod executor;
pub mod utils;
pub mod error;
pub mod net;
pub mod fs;
pub use executor::spawn;
|
//! ```no_run
//! #![feature(proc_macro, generators)]
//!
//! #[macro_use]
|
random_line_split
|
config.rs
|
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::option::Option;
use std::path::{Path, PathBuf};
use std::result::Result;
use std::thread;
use git2::Repository;
use rustc_serialize::{Decodable, Decoder};
use toml;
use ::Args;
#[derive(RustcDecodable)]
pub struct RepoConfig {
url: String,
path: Option<String>,
}
#[derive(RustcDecodable)]
pub struct
|
{
basedir: Option<String>,
repos: Option<HashMap<String, RepoConfig>>,
}
impl Config {
pub fn from_args(args: &Args) -> Config {
let path = Path::new(&args.flag_config);
// opening file
let mut file = match File::open(&path) {
Ok(file) => file,
Err(why) => panic!("couldn't open {}: {}",
args.flag_config, Error::description(&why)),
};
// reading file contents
let mut toml_string: String = String::new();
match file.read_to_string(&mut toml_string) {
Ok(_) => (),
Err(why) => panic!("couldn't read {}: {}",
args.flag_config, Error::description(&why)),
};
let toml_str = toml_string.as_ref();
// parsing TOML
let toml_tree = match toml::Parser::new(toml_str).parse() {
Some(value) => value,
None => panic!("Invalid TOML file {}", args.flag_config)
};
// decoding TOML to Config instance
let mut d = toml::Decoder::new(toml::Value::Table(toml_tree));
let config: Config = match Decodable::decode(&mut d) {
Ok(config) => config,
Err(why) => panic!("Failed to decode {}: {}",
args.flag_config, Error::description(&why)),
};
return config;
}
pub fn get_repositories(&self) -> Vec<(String, Repository)> {
let mut repositories = Vec::new();
let default_basedir = "/tmp".to_string();
let basedir = match self.basedir {
Some(ref basedir) => basedir,
None => &default_basedir,
};
let repos_map = match self.repos {
Some(ref repos) => repos,
None => return repositories,
};
// spawning threads
let mut guards = Vec::new();
for (repo_name, repo_config) in repos_map.iter() {
let path_buf = {
let mut path_buf = PathBuf::from(&basedir);
let path_tail = match repo_config.path {
Some(ref path) => path,
None => repo_name,
};
path_buf.push(path_tail);
path_buf
};
let url = repo_config.url.clone();
let join_guard = thread::scoped(|| { open_or_clone_repo(url, path_buf) });
guards.push((repo_name.clone(), join_guard));
}
// joining results
for (repo_name, guard) in guards.drain() {
match guard.join() {
Ok(repository) => repositories.push((repo_name, repository)),
Err(e) => println!("Error cloning repo {} {:?}", repo_name, e),
};
}
return repositories;
}
}
fn open_or_clone_repo(url: String, path: PathBuf) -> Result<Repository, ::git2::Error> {
match Repository::open(&path) {
Ok(repository) => Ok(repository),
Err(_) => Repository::clone(&url, &path),
}
}
|
Config
|
identifier_name
|
config.rs
|
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::option::Option;
use std::path::{Path, PathBuf};
use std::result::Result;
use std::thread;
use git2::Repository;
use rustc_serialize::{Decodable, Decoder};
use toml;
use ::Args;
#[derive(RustcDecodable)]
pub struct RepoConfig {
url: String,
path: Option<String>,
}
#[derive(RustcDecodable)]
pub struct Config {
basedir: Option<String>,
repos: Option<HashMap<String, RepoConfig>>,
}
impl Config {
pub fn from_args(args: &Args) -> Config {
let path = Path::new(&args.flag_config);
// opening file
let mut file = match File::open(&path) {
Ok(file) => file,
Err(why) => panic!("couldn't open {}: {}",
args.flag_config, Error::description(&why)),
};
// reading file contents
let mut toml_string: String = String::new();
match file.read_to_string(&mut toml_string) {
Ok(_) => (),
Err(why) => panic!("couldn't read {}: {}",
args.flag_config, Error::description(&why)),
};
let toml_str = toml_string.as_ref();
// parsing TOML
let toml_tree = match toml::Parser::new(toml_str).parse() {
Some(value) => value,
None => panic!("Invalid TOML file {}", args.flag_config)
};
// decoding TOML to Config instance
let mut d = toml::Decoder::new(toml::Value::Table(toml_tree));
let config: Config = match Decodable::decode(&mut d) {
Ok(config) => config,
Err(why) => panic!("Failed to decode {}: {}",
args.flag_config, Error::description(&why)),
};
return config;
}
pub fn get_repositories(&self) -> Vec<(String, Repository)> {
let mut repositories = Vec::new();
let default_basedir = "/tmp".to_string();
let basedir = match self.basedir {
Some(ref basedir) => basedir,
None => &default_basedir,
};
let repos_map = match self.repos {
Some(ref repos) => repos,
None => return repositories,
};
// spawning threads
let mut guards = Vec::new();
for (repo_name, repo_config) in repos_map.iter() {
let path_buf = {
let mut path_buf = PathBuf::from(&basedir);
let path_tail = match repo_config.path {
Some(ref path) => path,
None => repo_name,
};
path_buf.push(path_tail);
path_buf
};
let url = repo_config.url.clone();
let join_guard = thread::scoped(|| { open_or_clone_repo(url, path_buf) });
guards.push((repo_name.clone(), join_guard));
}
// joining results
for (repo_name, guard) in guards.drain() {
match guard.join() {
Ok(repository) => repositories.push((repo_name, repository)),
Err(e) => println!("Error cloning repo {} {:?}", repo_name, e),
};
}
return repositories;
}
}
fn open_or_clone_repo(url: String, path: PathBuf) -> Result<Repository, ::git2::Error> {
match Repository::open(&path) {
Ok(repository) => Ok(repository),
|
}
}
|
Err(_) => Repository::clone(&url, &path),
|
random_line_split
|
ranges.rs
|
/*
* This file is part of the uutils coreutils package.
*
* (c) Rolf Morel <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use std;
#[deriving(PartialEq,Eq,PartialOrd,Ord,Show)]
pub struct
|
{
pub low: uint,
pub high: uint,
}
impl std::str::FromStr for Range {
fn from_str(s: &str) -> Option<Range> {
use std::uint::MAX;
let mut parts = s.splitn(1, '-');
match (parts.next(), parts.next()) {
(Some(nm), None) => {
from_str::<uint>(nm).and_then(|nm| if nm > 0 { Some(nm) } else { None })
.map(|nm| Range { low: nm, high: nm })
}
(Some(n), Some(m)) if m.len() == 0 => {
from_str::<uint>(n).and_then(|low| if low > 0 { Some(low) } else { None })
.map(|low| Range { low: low, high: MAX })
}
(Some(n), Some(m)) if n.len() == 0 => {
from_str::<uint>(m).and_then(|high| if high >= 1 { Some(high) } else { None })
.map(|high| Range { low: 1, high: high })
}
(Some(n), Some(m)) => {
match (from_str::<uint>(n), from_str::<uint>(m)) {
(Some(low), Some(high)) if low > 0 && low <= high => {
Some(Range { low: low, high: high })
}
_ => None
}
}
_ => unreachable!()
}
}
}
impl Range {
pub fn from_list(list: &str) -> Result<Vec<Range>, String> {
use std::cmp::max;
let mut ranges = vec!();
for item in list.split(',') {
match from_str::<Range>(item) {
Some(range_item) => ranges.push(range_item),
None => return Err(format!("range '{}' was invalid", item))
}
}
ranges.sort();
// merge overlapping ranges
for i in range(0, ranges.len()) {
let j = i + 1;
while j < ranges.len() && ranges[j].low <= ranges[i].high {
let j_high = ranges.remove(j).unwrap().high;
ranges[i].high = max(ranges[i].high, j_high);
}
}
Ok(ranges)
}
}
pub fn complement(ranges: &Vec<Range>) -> Vec<Range> {
use std::uint;
let mut complements = Vec::with_capacity(ranges.len() + 1);
if ranges.len() > 0 && ranges[0].low > 1 {
complements.push(Range { low: 1, high: ranges[0].low - 1 });
}
let mut ranges_iter = ranges.iter().peekable();
loop {
match (ranges_iter.next(), ranges_iter.peek()) {
(Some(left), Some(right)) => {
if left.high + 1!= right.low {
complements.push(Range {
low: left.high + 1,
high: right.low - 1
});
}
}
(Some(last), None) => {
if last.high < uint::MAX {
complements.push(Range {
low: last.high + 1,
high: uint::MAX
});
}
}
_ => break
}
}
complements
}
|
Range
|
identifier_name
|
ranges.rs
|
/*
* This file is part of the uutils coreutils package.
*
* (c) Rolf Morel <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use std;
#[deriving(PartialEq,Eq,PartialOrd,Ord,Show)]
pub struct Range {
pub low: uint,
pub high: uint,
}
impl std::str::FromStr for Range {
fn from_str(s: &str) -> Option<Range> {
use std::uint::MAX;
let mut parts = s.splitn(1, '-');
match (parts.next(), parts.next()) {
(Some(nm), None) => {
from_str::<uint>(nm).and_then(|nm| if nm > 0 { Some(nm) } else { None })
.map(|nm| Range { low: nm, high: nm })
}
(Some(n), Some(m)) if m.len() == 0 => {
from_str::<uint>(n).and_then(|low| if low > 0 { Some(low) } else { None })
.map(|low| Range { low: low, high: MAX })
}
(Some(n), Some(m)) if n.len() == 0 =>
|
(Some(n), Some(m)) => {
match (from_str::<uint>(n), from_str::<uint>(m)) {
(Some(low), Some(high)) if low > 0 && low <= high => {
Some(Range { low: low, high: high })
}
_ => None
}
}
_ => unreachable!()
}
}
}
impl Range {
pub fn from_list(list: &str) -> Result<Vec<Range>, String> {
use std::cmp::max;
let mut ranges = vec!();
for item in list.split(',') {
match from_str::<Range>(item) {
Some(range_item) => ranges.push(range_item),
None => return Err(format!("range '{}' was invalid", item))
}
}
ranges.sort();
// merge overlapping ranges
for i in range(0, ranges.len()) {
let j = i + 1;
while j < ranges.len() && ranges[j].low <= ranges[i].high {
let j_high = ranges.remove(j).unwrap().high;
ranges[i].high = max(ranges[i].high, j_high);
}
}
Ok(ranges)
}
}
pub fn complement(ranges: &Vec<Range>) -> Vec<Range> {
use std::uint;
let mut complements = Vec::with_capacity(ranges.len() + 1);
if ranges.len() > 0 && ranges[0].low > 1 {
complements.push(Range { low: 1, high: ranges[0].low - 1 });
}
let mut ranges_iter = ranges.iter().peekable();
loop {
match (ranges_iter.next(), ranges_iter.peek()) {
(Some(left), Some(right)) => {
if left.high + 1!= right.low {
complements.push(Range {
low: left.high + 1,
high: right.low - 1
});
}
}
(Some(last), None) => {
if last.high < uint::MAX {
complements.push(Range {
low: last.high + 1,
high: uint::MAX
});
}
}
_ => break
}
}
complements
}
|
{
from_str::<uint>(m).and_then(|high| if high >= 1 { Some(high) } else { None })
.map(|high| Range { low: 1, high: high })
}
|
conditional_block
|
ranges.rs
|
/*
* This file is part of the uutils coreutils package.
*
* (c) Rolf Morel <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use std;
#[deriving(PartialEq,Eq,PartialOrd,Ord,Show)]
pub struct Range {
pub low: uint,
pub high: uint,
}
impl std::str::FromStr for Range {
fn from_str(s: &str) -> Option<Range>
|
(Some(low), Some(high)) if low > 0 && low <= high => {
Some(Range { low: low, high: high })
}
_ => None
}
}
_ => unreachable!()
}
}
}
impl Range {
pub fn from_list(list: &str) -> Result<Vec<Range>, String> {
use std::cmp::max;
let mut ranges = vec!();
for item in list.split(',') {
match from_str::<Range>(item) {
Some(range_item) => ranges.push(range_item),
None => return Err(format!("range '{}' was invalid", item))
}
}
ranges.sort();
// merge overlapping ranges
for i in range(0, ranges.len()) {
let j = i + 1;
while j < ranges.len() && ranges[j].low <= ranges[i].high {
let j_high = ranges.remove(j).unwrap().high;
ranges[i].high = max(ranges[i].high, j_high);
}
}
Ok(ranges)
}
}
pub fn complement(ranges: &Vec<Range>) -> Vec<Range> {
use std::uint;
let mut complements = Vec::with_capacity(ranges.len() + 1);
if ranges.len() > 0 && ranges[0].low > 1 {
complements.push(Range { low: 1, high: ranges[0].low - 1 });
}
let mut ranges_iter = ranges.iter().peekable();
loop {
match (ranges_iter.next(), ranges_iter.peek()) {
(Some(left), Some(right)) => {
if left.high + 1!= right.low {
complements.push(Range {
low: left.high + 1,
high: right.low - 1
});
}
}
(Some(last), None) => {
if last.high < uint::MAX {
complements.push(Range {
low: last.high + 1,
high: uint::MAX
});
}
}
_ => break
}
}
complements
}
|
{
use std::uint::MAX;
let mut parts = s.splitn(1, '-');
match (parts.next(), parts.next()) {
(Some(nm), None) => {
from_str::<uint>(nm).and_then(|nm| if nm > 0 { Some(nm) } else { None })
.map(|nm| Range { low: nm, high: nm })
}
(Some(n), Some(m)) if m.len() == 0 => {
from_str::<uint>(n).and_then(|low| if low > 0 { Some(low) } else { None })
.map(|low| Range { low: low, high: MAX })
}
(Some(n), Some(m)) if n.len() == 0 => {
from_str::<uint>(m).and_then(|high| if high >= 1 { Some(high) } else { None })
.map(|high| Range { low: 1, high: high })
}
(Some(n), Some(m)) => {
match (from_str::<uint>(n), from_str::<uint>(m)) {
|
identifier_body
|
ranges.rs
|
/*
* This file is part of the uutils coreutils package.
*
* (c) Rolf Morel <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use std;
#[deriving(PartialEq,Eq,PartialOrd,Ord,Show)]
pub struct Range {
pub low: uint,
pub high: uint,
|
let mut parts = s.splitn(1, '-');
match (parts.next(), parts.next()) {
(Some(nm), None) => {
from_str::<uint>(nm).and_then(|nm| if nm > 0 { Some(nm) } else { None })
.map(|nm| Range { low: nm, high: nm })
}
(Some(n), Some(m)) if m.len() == 0 => {
from_str::<uint>(n).and_then(|low| if low > 0 { Some(low) } else { None })
.map(|low| Range { low: low, high: MAX })
}
(Some(n), Some(m)) if n.len() == 0 => {
from_str::<uint>(m).and_then(|high| if high >= 1 { Some(high) } else { None })
.map(|high| Range { low: 1, high: high })
}
(Some(n), Some(m)) => {
match (from_str::<uint>(n), from_str::<uint>(m)) {
(Some(low), Some(high)) if low > 0 && low <= high => {
Some(Range { low: low, high: high })
}
_ => None
}
}
_ => unreachable!()
}
}
}
impl Range {
pub fn from_list(list: &str) -> Result<Vec<Range>, String> {
use std::cmp::max;
let mut ranges = vec!();
for item in list.split(',') {
match from_str::<Range>(item) {
Some(range_item) => ranges.push(range_item),
None => return Err(format!("range '{}' was invalid", item))
}
}
ranges.sort();
// merge overlapping ranges
for i in range(0, ranges.len()) {
let j = i + 1;
while j < ranges.len() && ranges[j].low <= ranges[i].high {
let j_high = ranges.remove(j).unwrap().high;
ranges[i].high = max(ranges[i].high, j_high);
}
}
Ok(ranges)
}
}
pub fn complement(ranges: &Vec<Range>) -> Vec<Range> {
use std::uint;
let mut complements = Vec::with_capacity(ranges.len() + 1);
if ranges.len() > 0 && ranges[0].low > 1 {
complements.push(Range { low: 1, high: ranges[0].low - 1 });
}
let mut ranges_iter = ranges.iter().peekable();
loop {
match (ranges_iter.next(), ranges_iter.peek()) {
(Some(left), Some(right)) => {
if left.high + 1!= right.low {
complements.push(Range {
low: left.high + 1,
high: right.low - 1
});
}
}
(Some(last), None) => {
if last.high < uint::MAX {
complements.push(Range {
low: last.high + 1,
high: uint::MAX
});
}
}
_ => break
}
}
complements
}
|
}
impl std::str::FromStr for Range {
fn from_str(s: &str) -> Option<Range> {
use std::uint::MAX;
|
random_line_split
|
inits-1.rs
|
// General test of maybe_inits state computed by MIR dataflow.
#![feature(core_intrinsics, rustc_attrs)]
use std::intrinsics::rustc_peek;
use std::mem::{drop, replace};
struct S(i32);
#[rustc_mir(rustc_peek_maybe_init,stop_after_dataflow)]
fn foo(test: bool, x: &mut S, y: S, mut z: S) -> S {
let ret;
// `ret` starts off uninitialized, so we get an error report here.
rustc_peek(&ret); //~ ERROR rustc_peek: bit not set
// All function formal parameters start off initialized.
rustc_peek(&x);
rustc_peek(&y);
rustc_peek(&z);
ret = if test {
::std::mem::replace(x, y)
} else
|
;
// `z` may be initialized here.
rustc_peek(&z);
// `y` is definitely uninitialized here.
rustc_peek(&y); //~ ERROR rustc_peek: bit not set
// `x` is still (definitely) initialized (replace above is a reborrow).
rustc_peek(&x);
::std::mem::drop(x);
// `x` is *definitely* uninitialized here
rustc_peek(&x); //~ ERROR rustc_peek: bit not set
// `ret` is now definitely initialized (via `if` above).
rustc_peek(&ret);
ret
}
fn main() {
foo(true, &mut S(13), S(14), S(15));
foo(false, &mut S(13), S(14), S(15));
}
|
{
z = y;
z
}
|
conditional_block
|
inits-1.rs
|
// General test of maybe_inits state computed by MIR dataflow.
#![feature(core_intrinsics, rustc_attrs)]
use std::intrinsics::rustc_peek;
use std::mem::{drop, replace};
struct S(i32);
#[rustc_mir(rustc_peek_maybe_init,stop_after_dataflow)]
fn
|
(test: bool, x: &mut S, y: S, mut z: S) -> S {
let ret;
// `ret` starts off uninitialized, so we get an error report here.
rustc_peek(&ret); //~ ERROR rustc_peek: bit not set
// All function formal parameters start off initialized.
rustc_peek(&x);
rustc_peek(&y);
rustc_peek(&z);
ret = if test {
::std::mem::replace(x, y)
} else {
z = y;
z
};
// `z` may be initialized here.
rustc_peek(&z);
// `y` is definitely uninitialized here.
rustc_peek(&y); //~ ERROR rustc_peek: bit not set
// `x` is still (definitely) initialized (replace above is a reborrow).
rustc_peek(&x);
::std::mem::drop(x);
// `x` is *definitely* uninitialized here
rustc_peek(&x); //~ ERROR rustc_peek: bit not set
// `ret` is now definitely initialized (via `if` above).
rustc_peek(&ret);
ret
}
fn main() {
foo(true, &mut S(13), S(14), S(15));
foo(false, &mut S(13), S(14), S(15));
}
|
foo
|
identifier_name
|
inits-1.rs
|
// General test of maybe_inits state computed by MIR dataflow.
#![feature(core_intrinsics, rustc_attrs)]
use std::intrinsics::rustc_peek;
use std::mem::{drop, replace};
struct S(i32);
#[rustc_mir(rustc_peek_maybe_init,stop_after_dataflow)]
fn foo(test: bool, x: &mut S, y: S, mut z: S) -> S {
let ret;
// `ret` starts off uninitialized, so we get an error report here.
rustc_peek(&ret); //~ ERROR rustc_peek: bit not set
// All function formal parameters start off initialized.
rustc_peek(&x);
rustc_peek(&y);
rustc_peek(&z);
ret = if test {
::std::mem::replace(x, y)
} else {
z = y;
z
};
// `z` may be initialized here.
rustc_peek(&z);
// `y` is definitely uninitialized here.
rustc_peek(&y); //~ ERROR rustc_peek: bit not set
// `x` is still (definitely) initialized (replace above is a reborrow).
rustc_peek(&x);
::std::mem::drop(x);
// `x` is *definitely* uninitialized here
rustc_peek(&x); //~ ERROR rustc_peek: bit not set
// `ret` is now definitely initialized (via `if` above).
rustc_peek(&ret);
ret
}
|
fn main() {
foo(true, &mut S(13), S(14), S(15));
foo(false, &mut S(13), S(14), S(15));
}
|
random_line_split
|
|
borrowck-loan-rcvr-overloaded-op.rs
|
// 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.
struct Point {
x: int,
y: int,
}
impl ops::Add<int,int> for Point {
fn add(&self, z: &int) -> int {
self.x + self.y + (*z)
}
}
pub impl Point {
fn times(&self, z: int) -> int
|
}
fn a() {
let mut p = Point {x: 3, y: 4};
// ok (we can loan out rcvr)
p + 3;
p.times(3);
}
fn b() {
let mut p = Point {x: 3, y: 4};
// Here I create an outstanding loan and check that we get conflicts:
let q = &mut p; //~ NOTE prior loan as mutable granted here
p + 3; // ok for pure fns
p.times(3); //~ ERROR loan of mutable local variable as immutable conflicts with prior loan
q.x += 1;
}
fn c() {
// Here the receiver is in aliased memory but due to write
// barriers we can still consider it immutable.
let q = @mut Point {x: 3, y: 4};
*q + 3;
q.times(3);
}
fn main() {
}
|
{
self.x * self.y * z
}
|
identifier_body
|
borrowck-loan-rcvr-overloaded-op.rs
|
// 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.
struct Point {
x: int,
y: int,
}
impl ops::Add<int,int> for Point {
fn
|
(&self, z: &int) -> int {
self.x + self.y + (*z)
}
}
pub impl Point {
fn times(&self, z: int) -> int {
self.x * self.y * z
}
}
fn a() {
let mut p = Point {x: 3, y: 4};
// ok (we can loan out rcvr)
p + 3;
p.times(3);
}
fn b() {
let mut p = Point {x: 3, y: 4};
// Here I create an outstanding loan and check that we get conflicts:
let q = &mut p; //~ NOTE prior loan as mutable granted here
p + 3; // ok for pure fns
p.times(3); //~ ERROR loan of mutable local variable as immutable conflicts with prior loan
q.x += 1;
}
fn c() {
// Here the receiver is in aliased memory but due to write
// barriers we can still consider it immutable.
let q = @mut Point {x: 3, y: 4};
*q + 3;
q.times(3);
}
fn main() {
}
|
add
|
identifier_name
|
borrowck-loan-rcvr-overloaded-op.rs
|
// 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.
struct Point {
x: int,
y: int,
}
impl ops::Add<int,int> for Point {
fn add(&self, z: &int) -> int {
self.x + self.y + (*z)
}
}
pub impl Point {
fn times(&self, z: int) -> int {
self.x * self.y * z
}
}
fn a() {
let mut p = Point {x: 3, y: 4};
// ok (we can loan out rcvr)
p + 3;
|
fn b() {
let mut p = Point {x: 3, y: 4};
// Here I create an outstanding loan and check that we get conflicts:
let q = &mut p; //~ NOTE prior loan as mutable granted here
p + 3; // ok for pure fns
p.times(3); //~ ERROR loan of mutable local variable as immutable conflicts with prior loan
q.x += 1;
}
fn c() {
// Here the receiver is in aliased memory but due to write
// barriers we can still consider it immutable.
let q = @mut Point {x: 3, y: 4};
*q + 3;
q.times(3);
}
fn main() {
}
|
p.times(3);
}
|
random_line_split
|
tokio_server.rs
|
/* This example creates a D-Bus server with the following functionality:
It registers the "com.example.dbustest" name, creates a "/hello" object path,
which has an "com.example.dbustest" interface.
The interface has a "Hello" method (which takes no arguments and returns a string),
and a "HelloHappened" signal (with a string argument) which is sent every time
someone calls the "Hello" method.
*/
extern crate dbus;
extern crate futures;
extern crate tokio_timer;
extern crate dbus_tokio;
extern crate tokio_core;
use std::time::Duration;
use std::sync::Arc;
use std::rc::Rc;
use dbus::{Connection, BusType, NameFlag};
use dbus::tree::MethodErr;
use dbus_tokio::tree::{AFactory, ATree, ATreeServer};
use dbus_tokio::AConnection;
use tokio_timer::*;
use tokio_core::reactor::Core;
use futures::{Future, Stream};
fn main()
|
//...and a method inside the interface.
f.amethod("Hello", (), move |m| {
// This is the callback that will be called when another peer on the bus calls our method.
// the callback receives "MethodInfo" struct and can return either an error, or a list of
// messages to send back.
let timer = Timer::default();
let t = m.msg.get1().unwrap();
let sleep_future = timer.sleep(Duration::from_millis(t));
// These are the variables we need after the timeout period. We need to
// clone all strings now, because the tree might get destroyed during the sleep.
let sender = m.msg.sender().unwrap().into_static();
let (pname, iname) = (m.path.get_name().clone(), m.iface.get_name().clone());
let mret = m.msg.method_return();
let signal3 = signal.clone();
sleep_future.and_then(move |_| {
let s = format!("Hello {}!", sender);
let mret = mret.append1(s);
let sig = signal3.msg(&pname, &iname).append1(&*sender);
// Two messages will be returned - one is the method return (and should always be there),
// and in our case we also have a signal we want to send at the same time.
Ok(vec!(mret, sig))
}).map_err(|e| MethodErr::failed(&e))
// Our method has one output argument, no input arguments.
}).inarg::<u32,_>("sleep_millis")
.outarg::<&str,_>("reply")
// We also add the signal to the interface. This is mainly for introspection.
).add_s(signal2)
));
// We register all object paths in the tree.
tree.set_registered(&c, true).unwrap();
// Setup Tokio
let mut core = Core::new().unwrap();
let aconn = AConnection::new(c.clone(), core.handle()).unwrap();
let server = ATreeServer::new(c.clone(), &tree, aconn.messages().unwrap());
// Make the server run forever
let server = server.for_each(|m| { println!("Unhandled message: {:?}", m); Ok(()) });
core.run(server).unwrap();
}
|
{
// Let's start by starting up a connection to the session bus and register a name.
let c = Rc::new(Connection::get_private(BusType::Session).unwrap());
c.register_name("com.example.dbustest", NameFlag::ReplaceExisting as u32).unwrap();
// The choice of factory tells us what type of tree we want,
// and if we want any extra data inside. We pick the simplest variant.
let f = AFactory::new_afn::<()>();
// We create the signal first, since we'll need it in both inside the method callback
// and when creating the tree.
let signal = Arc::new(f.signal("HelloHappened", ()).sarg::<&str,_>("sender"));
let signal2 = signal.clone();
// We create a tree with one object path inside and make that path introspectable.
let tree = f.tree(ATree::new()).add(f.object_path("/hello", ()).introspectable().add(
// We add an interface to the object path...
f.interface("com.example.dbustest", ()).add_m(
|
identifier_body
|
tokio_server.rs
|
/* This example creates a D-Bus server with the following functionality:
It registers the "com.example.dbustest" name, creates a "/hello" object path,
which has an "com.example.dbustest" interface.
The interface has a "Hello" method (which takes no arguments and returns a string),
and a "HelloHappened" signal (with a string argument) which is sent every time
someone calls the "Hello" method.
*/
extern crate dbus;
extern crate futures;
extern crate tokio_timer;
extern crate dbus_tokio;
extern crate tokio_core;
use std::time::Duration;
use std::sync::Arc;
use std::rc::Rc;
use dbus::{Connection, BusType, NameFlag};
use dbus::tree::MethodErr;
use dbus_tokio::tree::{AFactory, ATree, ATreeServer};
use dbus_tokio::AConnection;
use tokio_timer::*;
use tokio_core::reactor::Core;
use futures::{Future, Stream};
fn
|
() {
// Let's start by starting up a connection to the session bus and register a name.
let c = Rc::new(Connection::get_private(BusType::Session).unwrap());
c.register_name("com.example.dbustest", NameFlag::ReplaceExisting as u32).unwrap();
// The choice of factory tells us what type of tree we want,
// and if we want any extra data inside. We pick the simplest variant.
let f = AFactory::new_afn::<()>();
// We create the signal first, since we'll need it in both inside the method callback
// and when creating the tree.
let signal = Arc::new(f.signal("HelloHappened", ()).sarg::<&str,_>("sender"));
let signal2 = signal.clone();
// We create a tree with one object path inside and make that path introspectable.
let tree = f.tree(ATree::new()).add(f.object_path("/hello", ()).introspectable().add(
// We add an interface to the object path...
f.interface("com.example.dbustest", ()).add_m(
//...and a method inside the interface.
f.amethod("Hello", (), move |m| {
// This is the callback that will be called when another peer on the bus calls our method.
// the callback receives "MethodInfo" struct and can return either an error, or a list of
// messages to send back.
let timer = Timer::default();
let t = m.msg.get1().unwrap();
let sleep_future = timer.sleep(Duration::from_millis(t));
// These are the variables we need after the timeout period. We need to
// clone all strings now, because the tree might get destroyed during the sleep.
let sender = m.msg.sender().unwrap().into_static();
let (pname, iname) = (m.path.get_name().clone(), m.iface.get_name().clone());
let mret = m.msg.method_return();
let signal3 = signal.clone();
sleep_future.and_then(move |_| {
let s = format!("Hello {}!", sender);
let mret = mret.append1(s);
let sig = signal3.msg(&pname, &iname).append1(&*sender);
// Two messages will be returned - one is the method return (and should always be there),
// and in our case we also have a signal we want to send at the same time.
Ok(vec!(mret, sig))
}).map_err(|e| MethodErr::failed(&e))
// Our method has one output argument, no input arguments.
}).inarg::<u32,_>("sleep_millis")
.outarg::<&str,_>("reply")
// We also add the signal to the interface. This is mainly for introspection.
).add_s(signal2)
));
// We register all object paths in the tree.
tree.set_registered(&c, true).unwrap();
// Setup Tokio
let mut core = Core::new().unwrap();
let aconn = AConnection::new(c.clone(), core.handle()).unwrap();
let server = ATreeServer::new(c.clone(), &tree, aconn.messages().unwrap());
// Make the server run forever
let server = server.for_each(|m| { println!("Unhandled message: {:?}", m); Ok(()) });
core.run(server).unwrap();
}
|
main
|
identifier_name
|
tokio_server.rs
|
/* This example creates a D-Bus server with the following functionality:
It registers the "com.example.dbustest" name, creates a "/hello" object path,
which has an "com.example.dbustest" interface.
The interface has a "Hello" method (which takes no arguments and returns a string),
and a "HelloHappened" signal (with a string argument) which is sent every time
someone calls the "Hello" method.
*/
extern crate dbus;
extern crate futures;
extern crate tokio_timer;
extern crate dbus_tokio;
extern crate tokio_core;
use std::time::Duration;
use std::sync::Arc;
use std::rc::Rc;
use dbus::{Connection, BusType, NameFlag};
use dbus::tree::MethodErr;
use dbus_tokio::tree::{AFactory, ATree, ATreeServer};
use dbus_tokio::AConnection;
use tokio_timer::*;
use tokio_core::reactor::Core;
use futures::{Future, Stream};
fn main() {
// Let's start by starting up a connection to the session bus and register a name.
let c = Rc::new(Connection::get_private(BusType::Session).unwrap());
c.register_name("com.example.dbustest", NameFlag::ReplaceExisting as u32).unwrap();
// The choice of factory tells us what type of tree we want,
// and if we want any extra data inside. We pick the simplest variant.
let f = AFactory::new_afn::<()>();
// We create the signal first, since we'll need it in both inside the method callback
// and when creating the tree.
let signal = Arc::new(f.signal("HelloHappened", ()).sarg::<&str,_>("sender"));
let signal2 = signal.clone();
// We create a tree with one object path inside and make that path introspectable.
let tree = f.tree(ATree::new()).add(f.object_path("/hello", ()).introspectable().add(
// We add an interface to the object path...
f.interface("com.example.dbustest", ()).add_m(
//...and a method inside the interface.
f.amethod("Hello", (), move |m| {
// This is the callback that will be called when another peer on the bus calls our method.
// the callback receives "MethodInfo" struct and can return either an error, or a list of
// messages to send back.
let timer = Timer::default();
let t = m.msg.get1().unwrap();
let sleep_future = timer.sleep(Duration::from_millis(t));
// These are the variables we need after the timeout period. We need to
// clone all strings now, because the tree might get destroyed during the sleep.
let sender = m.msg.sender().unwrap().into_static();
let (pname, iname) = (m.path.get_name().clone(), m.iface.get_name().clone());
let mret = m.msg.method_return();
let signal3 = signal.clone();
sleep_future.and_then(move |_| {
let s = format!("Hello {}!", sender);
let mret = mret.append1(s);
let sig = signal3.msg(&pname, &iname).append1(&*sender);
// Two messages will be returned - one is the method return (and should always be there),
// and in our case we also have a signal we want to send at the same time.
Ok(vec!(mret, sig))
}).map_err(|e| MethodErr::failed(&e))
// Our method has one output argument, no input arguments.
}).inarg::<u32,_>("sleep_millis")
.outarg::<&str,_>("reply")
// We also add the signal to the interface. This is mainly for introspection.
).add_s(signal2)
));
// We register all object paths in the tree.
tree.set_registered(&c, true).unwrap();
// Setup Tokio
let mut core = Core::new().unwrap();
let aconn = AConnection::new(c.clone(), core.handle()).unwrap();
let server = ATreeServer::new(c.clone(), &tree, aconn.messages().unwrap());
|
core.run(server).unwrap();
}
|
// Make the server run forever
let server = server.for_each(|m| { println!("Unhandled message: {:?}", m); Ok(()) });
|
random_line_split
|
style.rs
|
// Copyright (C) 2017 Élisabeth HENRY.
//
// This file is part of Crowbook.
//
// Crowbook is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any later version.
//
// Crowbook is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Crowbook. If not, see <http://www.gnu.org/licenses/>.
//! Functions for setting styles on text, using console to make it look prettier.
use console::{style, StyledObject, Term};
use textwrap::Wrapper;
/// Displays a string as some header
pub fn header(msg: &str) -> StyledObject<&str> {
style(msg).magenta().bold()
}
/// Displays a string as some element
pub fn element(msg: &str) -> StyledObject<&str> {
style(msg).yellow().bold()
}
pub fn field(msg: &str) -> StyledObject<&str> {
style(msg).cyan().bold()
}
pub fn tipe(msg: &str) -> StyledObject<&str> {
style(msg).cyan()
}
pub fn value(msg: &str) -> StyledObject<&str> {
style(msg).yellow()
}
pub fn fill(msg: &str, indent: &str) -> String {
|
let (_, width) = Term::stdout().size();
let wrapper = Wrapper::new(width as usize)
.initial_indent(indent)
.subsequent_indent(indent);
wrapper.fill(msg)
}
|
identifier_body
|
|
style.rs
|
// Copyright (C) 2017 Élisabeth HENRY.
//
// This file is part of Crowbook.
//
// Crowbook is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any later version.
//
|
//
// You should have received a copy of the GNU Lesser General Public License
// along with Crowbook. If not, see <http://www.gnu.org/licenses/>.
//! Functions for setting styles on text, using console to make it look prettier.
use console::{style, StyledObject, Term};
use textwrap::Wrapper;
/// Displays a string as some header
pub fn header(msg: &str) -> StyledObject<&str> {
style(msg).magenta().bold()
}
/// Displays a string as some element
pub fn element(msg: &str) -> StyledObject<&str> {
style(msg).yellow().bold()
}
pub fn field(msg: &str) -> StyledObject<&str> {
style(msg).cyan().bold()
}
pub fn tipe(msg: &str) -> StyledObject<&str> {
style(msg).cyan()
}
pub fn value(msg: &str) -> StyledObject<&str> {
style(msg).yellow()
}
pub fn fill(msg: &str, indent: &str) -> String {
let (_, width) = Term::stdout().size();
let wrapper = Wrapper::new(width as usize)
.initial_indent(indent)
.subsequent_indent(indent);
wrapper.fill(msg)
}
|
// Crowbook is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
|
random_line_split
|
style.rs
|
// Copyright (C) 2017 Élisabeth HENRY.
//
// This file is part of Crowbook.
//
// Crowbook is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation, either version 2.1 of the License, or
// (at your option) any later version.
//
// Crowbook is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Crowbook. If not, see <http://www.gnu.org/licenses/>.
//! Functions for setting styles on text, using console to make it look prettier.
use console::{style, StyledObject, Term};
use textwrap::Wrapper;
/// Displays a string as some header
pub fn header(msg: &str) -> StyledObject<&str> {
style(msg).magenta().bold()
}
/// Displays a string as some element
pub fn element(msg: &str) -> StyledObject<&str> {
style(msg).yellow().bold()
}
pub fn field(msg: &str) -> StyledObject<&str> {
style(msg).cyan().bold()
}
pub fn t
|
msg: &str) -> StyledObject<&str> {
style(msg).cyan()
}
pub fn value(msg: &str) -> StyledObject<&str> {
style(msg).yellow()
}
pub fn fill(msg: &str, indent: &str) -> String {
let (_, width) = Term::stdout().size();
let wrapper = Wrapper::new(width as usize)
.initial_indent(indent)
.subsequent_indent(indent);
wrapper.fill(msg)
}
|
ipe(
|
identifier_name
|
tuple.rs
|
use std::rc::Rc;
use std::any::Any;
use crate::object::{Object, Exception, Interface, FnResult, downcast};
use crate::vm::{Env, op_eq};
pub struct Tuple {
pub v: Vec<Object>
}
impl Tuple {
pub fn new_object(v: Vec<Object>) -> Object {
Object::Interface(Rc::new(Tuple {v}))
}
}
impl Interface for Tuple {
fn as_any(&self) -> &dyn Any {self}
fn type_name(&self, _env: &mut Env) -> String {
"Tuple".to_string()
}
fn to_string(self: Rc<Self>, env: &mut Env) -> Result<String,Box<Exception>> {
let mut acc = String::from("(");
let mut first = true;
for x in &self.v {
if first {first = false;} else {acc.push_str(", ");}
acc.push_str(&x.string(env)?);
}
acc.push(')');
Ok(acc)
}
fn index(self: Rc<Self>, indices: &[Object], env: &mut Env) -> FnResult {
match indices.len() {
1 => {}, n => return env.argc_error(n,1,1,"tuple indexing")
}
let i = match indices[0] {
Object::Int(i) => if i<0 {0} else {i as usize},
ref i => return env.type_error1(
"Type error in t[i]: i is not an integer.",
"i", i)
};
if i < self.v.len() {
Ok(self.v[i].clone())
} else {
env.index_error("Index error in t[i]: i is out of upper bound.")
}
}
fn eq_plain(&self, b: &Object) -> bool {
if let Some(b) = downcast::<Tuple>(b) {
if self.v.len() == b.v.len() {
for i in 0..self.v.len() {
if self.v[i]!= b.v[i] {return false;}
}
true
} else
|
} else {
false
}
}
fn eq(self: Rc<Self>, b: &Object, env: &mut Env) -> FnResult {
if let Some(b) = downcast::<Tuple>(b) {
let len = self.v.len();
if len == b.v.len() {
for i in 0..len {
let y = op_eq(env,&self.v[i],&b.v[i])?;
if let Object::Bool(y) = y {
if!y {return Ok(Object::Bool(false));}
} else {
return env.type_error(
"Type error in t1==t2: t[i]==t[i] is not a boolean.");
}
}
Ok(Object::Bool(true))
} else {
Ok(Object::Bool(false))
}
} else {
Ok(Object::Bool(false))
}
}
}
|
{
false
}
|
conditional_block
|
tuple.rs
|
use std::rc::Rc;
use std::any::Any;
use crate::object::{Object, Exception, Interface, FnResult, downcast};
use crate::vm::{Env, op_eq};
pub struct Tuple {
pub v: Vec<Object>
}
impl Tuple {
pub fn new_object(v: Vec<Object>) -> Object {
Object::Interface(Rc::new(Tuple {v}))
}
}
impl Interface for Tuple {
fn as_any(&self) -> &dyn Any {self}
fn type_name(&self, _env: &mut Env) -> String {
"Tuple".to_string()
}
fn to_string(self: Rc<Self>, env: &mut Env) -> Result<String,Box<Exception>> {
let mut acc = String::from("(");
let mut first = true;
for x in &self.v {
if first {first = false;} else {acc.push_str(", ");}
acc.push_str(&x.string(env)?);
}
acc.push(')');
Ok(acc)
}
fn index(self: Rc<Self>, indices: &[Object], env: &mut Env) -> FnResult {
match indices.len() {
1 => {}, n => return env.argc_error(n,1,1,"tuple indexing")
}
let i = match indices[0] {
Object::Int(i) => if i<0 {0} else {i as usize},
ref i => return env.type_error1(
"Type error in t[i]: i is not an integer.",
"i", i)
};
if i < self.v.len() {
Ok(self.v[i].clone())
} else {
env.index_error("Index error in t[i]: i is out of upper bound.")
}
}
fn eq_plain(&self, b: &Object) -> bool {
|
if self.v[i]!= b.v[i] {return false;}
}
true
} else {
false
}
} else {
false
}
}
fn eq(self: Rc<Self>, b: &Object, env: &mut Env) -> FnResult {
if let Some(b) = downcast::<Tuple>(b) {
let len = self.v.len();
if len == b.v.len() {
for i in 0..len {
let y = op_eq(env,&self.v[i],&b.v[i])?;
if let Object::Bool(y) = y {
if!y {return Ok(Object::Bool(false));}
} else {
return env.type_error(
"Type error in t1==t2: t[i]==t[i] is not a boolean.");
}
}
Ok(Object::Bool(true))
} else {
Ok(Object::Bool(false))
}
} else {
Ok(Object::Bool(false))
}
}
}
|
if let Some(b) = downcast::<Tuple>(b) {
if self.v.len() == b.v.len() {
for i in 0..self.v.len() {
|
random_line_split
|
tuple.rs
|
use std::rc::Rc;
use std::any::Any;
use crate::object::{Object, Exception, Interface, FnResult, downcast};
use crate::vm::{Env, op_eq};
pub struct
|
{
pub v: Vec<Object>
}
impl Tuple {
pub fn new_object(v: Vec<Object>) -> Object {
Object::Interface(Rc::new(Tuple {v}))
}
}
impl Interface for Tuple {
fn as_any(&self) -> &dyn Any {self}
fn type_name(&self, _env: &mut Env) -> String {
"Tuple".to_string()
}
fn to_string(self: Rc<Self>, env: &mut Env) -> Result<String,Box<Exception>> {
let mut acc = String::from("(");
let mut first = true;
for x in &self.v {
if first {first = false;} else {acc.push_str(", ");}
acc.push_str(&x.string(env)?);
}
acc.push(')');
Ok(acc)
}
fn index(self: Rc<Self>, indices: &[Object], env: &mut Env) -> FnResult {
match indices.len() {
1 => {}, n => return env.argc_error(n,1,1,"tuple indexing")
}
let i = match indices[0] {
Object::Int(i) => if i<0 {0} else {i as usize},
ref i => return env.type_error1(
"Type error in t[i]: i is not an integer.",
"i", i)
};
if i < self.v.len() {
Ok(self.v[i].clone())
} else {
env.index_error("Index error in t[i]: i is out of upper bound.")
}
}
fn eq_plain(&self, b: &Object) -> bool {
if let Some(b) = downcast::<Tuple>(b) {
if self.v.len() == b.v.len() {
for i in 0..self.v.len() {
if self.v[i]!= b.v[i] {return false;}
}
true
} else {
false
}
} else {
false
}
}
fn eq(self: Rc<Self>, b: &Object, env: &mut Env) -> FnResult {
if let Some(b) = downcast::<Tuple>(b) {
let len = self.v.len();
if len == b.v.len() {
for i in 0..len {
let y = op_eq(env,&self.v[i],&b.v[i])?;
if let Object::Bool(y) = y {
if!y {return Ok(Object::Bool(false));}
} else {
return env.type_error(
"Type error in t1==t2: t[i]==t[i] is not a boolean.");
}
}
Ok(Object::Bool(true))
} else {
Ok(Object::Bool(false))
}
} else {
Ok(Object::Bool(false))
}
}
}
|
Tuple
|
identifier_name
|
tuple.rs
|
use std::rc::Rc;
use std::any::Any;
use crate::object::{Object, Exception, Interface, FnResult, downcast};
use crate::vm::{Env, op_eq};
pub struct Tuple {
pub v: Vec<Object>
}
impl Tuple {
pub fn new_object(v: Vec<Object>) -> Object {
Object::Interface(Rc::new(Tuple {v}))
}
}
impl Interface for Tuple {
fn as_any(&self) -> &dyn Any {self}
fn type_name(&self, _env: &mut Env) -> String {
"Tuple".to_string()
}
fn to_string(self: Rc<Self>, env: &mut Env) -> Result<String,Box<Exception>> {
let mut acc = String::from("(");
let mut first = true;
for x in &self.v {
if first {first = false;} else {acc.push_str(", ");}
acc.push_str(&x.string(env)?);
}
acc.push(')');
Ok(acc)
}
fn index(self: Rc<Self>, indices: &[Object], env: &mut Env) -> FnResult
|
fn eq_plain(&self, b: &Object) -> bool {
if let Some(b) = downcast::<Tuple>(b) {
if self.v.len() == b.v.len() {
for i in 0..self.v.len() {
if self.v[i]!= b.v[i] {return false;}
}
true
} else {
false
}
} else {
false
}
}
fn eq(self: Rc<Self>, b: &Object, env: &mut Env) -> FnResult {
if let Some(b) = downcast::<Tuple>(b) {
let len = self.v.len();
if len == b.v.len() {
for i in 0..len {
let y = op_eq(env,&self.v[i],&b.v[i])?;
if let Object::Bool(y) = y {
if!y {return Ok(Object::Bool(false));}
} else {
return env.type_error(
"Type error in t1==t2: t[i]==t[i] is not a boolean.");
}
}
Ok(Object::Bool(true))
} else {
Ok(Object::Bool(false))
}
} else {
Ok(Object::Bool(false))
}
}
}
|
{
match indices.len() {
1 => {}, n => return env.argc_error(n,1,1,"tuple indexing")
}
let i = match indices[0] {
Object::Int(i) => if i<0 {0} else {i as usize},
ref i => return env.type_error1(
"Type error in t[i]: i is not an integer.",
"i", i)
};
if i < self.v.len() {
Ok(self.v[i].clone())
} else {
env.index_error("Index error in t[i]: i is out of upper bound.")
}
}
|
identifier_body
|
uuid.rs
|
//! MC Protocol UUID data type.
use std::io::ErrorKind::InvalidInput;
use std::io::prelude::*;
use std::io;
use std::str::FromStr;
use packet::Protocol;
use util::ReadExactly;
use uuid::{ParseError, Uuid};
/// UUID read/write wrapper.
impl Protocol for Uuid {
type Clean = Uuid;
fn proto_len(_: &Uuid) -> usize { 16 }
fn proto_encode(value: &Uuid, dst: &mut Write) -> io::Result<()> {
dst.write_all(value.as_bytes())
}
/// Reads 16 bytes from `src` and returns a `Uuid`
fn proto_decode(mut src: &mut Read) -> io::Result<Uuid> {
let v = try!(src.read_exactly(16));
Uuid::from_bytes(&v).ok_or(io::Error::new(io::ErrorKind::InvalidInput, &format!("Invalid UUID value: {:?} can't be used to create UUID", v)[..]))
}
}
pub struct UuidString;
impl Protocol for UuidString {
type Clean = Uuid;
fn proto_len(value: &Uuid) -> usize {
<String as Protocol>::proto_len(&value.to_hyphenated_string())
}
fn
|
(value: &Uuid, dst: &mut Write) -> io::Result<()> {
<String as Protocol>::proto_encode(&value.to_hyphenated_string(), dst)
}
fn proto_decode(src: &mut Read) -> io::Result<Uuid> {
// Unfortunately we can't implement `impl FromError<ParseError> for io::Error`
let s = try!(<String as Protocol>::proto_decode(src));
Uuid::from_str(&s).map_err(|err| match err {
ParseError::InvalidLength(length) => io::Error::new(InvalidInput, &format!("Invalid length: {}", length)[..]),
ParseError::InvalidCharacter(_, _) => io::Error::new(InvalidInput, "invalid character"),
ParseError::InvalidGroups(_) => io::Error::new(InvalidInput, "invalid groups"),
ParseError::InvalidGroupLength(_, _, _) => io::Error::new(InvalidInput, "invalid group length"),
})
}
}
|
proto_encode
|
identifier_name
|
uuid.rs
|
//! MC Protocol UUID data type.
use std::io::ErrorKind::InvalidInput;
use std::io::prelude::*;
use std::io;
use std::str::FromStr;
use packet::Protocol;
use util::ReadExactly;
use uuid::{ParseError, Uuid};
/// UUID read/write wrapper.
impl Protocol for Uuid {
type Clean = Uuid;
fn proto_len(_: &Uuid) -> usize { 16 }
fn proto_encode(value: &Uuid, dst: &mut Write) -> io::Result<()> {
dst.write_all(value.as_bytes())
}
/// Reads 16 bytes from `src` and returns a `Uuid`
fn proto_decode(mut src: &mut Read) -> io::Result<Uuid> {
let v = try!(src.read_exactly(16));
Uuid::from_bytes(&v).ok_or(io::Error::new(io::ErrorKind::InvalidInput, &format!("Invalid UUID value: {:?} can't be used to create UUID", v)[..]))
}
}
pub struct UuidString;
impl Protocol for UuidString {
type Clean = Uuid;
fn proto_len(value: &Uuid) -> usize {
<String as Protocol>::proto_len(&value.to_hyphenated_string())
}
fn proto_encode(value: &Uuid, dst: &mut Write) -> io::Result<()> {
<String as Protocol>::proto_encode(&value.to_hyphenated_string(), dst)
}
|
let s = try!(<String as Protocol>::proto_decode(src));
Uuid::from_str(&s).map_err(|err| match err {
ParseError::InvalidLength(length) => io::Error::new(InvalidInput, &format!("Invalid length: {}", length)[..]),
ParseError::InvalidCharacter(_, _) => io::Error::new(InvalidInput, "invalid character"),
ParseError::InvalidGroups(_) => io::Error::new(InvalidInput, "invalid groups"),
ParseError::InvalidGroupLength(_, _, _) => io::Error::new(InvalidInput, "invalid group length"),
})
}
}
|
fn proto_decode(src: &mut Read) -> io::Result<Uuid> {
// Unfortunately we can't implement `impl FromError<ParseError> for io::Error`
|
random_line_split
|
uuid.rs
|
//! MC Protocol UUID data type.
use std::io::ErrorKind::InvalidInput;
use std::io::prelude::*;
use std::io;
use std::str::FromStr;
use packet::Protocol;
use util::ReadExactly;
use uuid::{ParseError, Uuid};
/// UUID read/write wrapper.
impl Protocol for Uuid {
type Clean = Uuid;
fn proto_len(_: &Uuid) -> usize { 16 }
fn proto_encode(value: &Uuid, dst: &mut Write) -> io::Result<()> {
dst.write_all(value.as_bytes())
}
/// Reads 16 bytes from `src` and returns a `Uuid`
fn proto_decode(mut src: &mut Read) -> io::Result<Uuid>
|
}
pub struct UuidString;
impl Protocol for UuidString {
type Clean = Uuid;
fn proto_len(value: &Uuid) -> usize {
<String as Protocol>::proto_len(&value.to_hyphenated_string())
}
fn proto_encode(value: &Uuid, dst: &mut Write) -> io::Result<()> {
<String as Protocol>::proto_encode(&value.to_hyphenated_string(), dst)
}
fn proto_decode(src: &mut Read) -> io::Result<Uuid> {
// Unfortunately we can't implement `impl FromError<ParseError> for io::Error`
let s = try!(<String as Protocol>::proto_decode(src));
Uuid::from_str(&s).map_err(|err| match err {
ParseError::InvalidLength(length) => io::Error::new(InvalidInput, &format!("Invalid length: {}", length)[..]),
ParseError::InvalidCharacter(_, _) => io::Error::new(InvalidInput, "invalid character"),
ParseError::InvalidGroups(_) => io::Error::new(InvalidInput, "invalid groups"),
ParseError::InvalidGroupLength(_, _, _) => io::Error::new(InvalidInput, "invalid group length"),
})
}
}
|
{
let v = try!(src.read_exactly(16));
Uuid::from_bytes(&v).ok_or(io::Error::new(io::ErrorKind::InvalidInput, &format!("Invalid UUID value: {:?} can't be used to create UUID", v)[..]))
}
|
identifier_body
|
lib.rs
|
//! Internal library for data-encoding-macro
//!
//! Do **not** use this library. Use [data-encoding-macro] instead.
//!
//! This library is for internal use by data-encoding-macro because procedural
//! macros require a separate crate.
//!
//! [data-encoding-macro]: https://crates.io/crates/data-encoding-macro
#![warn(unused_results)]
use proc_macro::token_stream::IntoIter;
use proc_macro::{TokenStream, TokenTree};
use std::collections::HashMap;
use data_encoding::{BitOrder, Encoding, Specification, Translate, Wrap};
fn parse_op(tokens: &mut IntoIter, op: char, key: &str) {
match tokens.next() {
Some(TokenTree::Punct(ref x)) if x.as_char() == op => (),
_ => panic!("expected {:?} after {}", op, key),
}
}
fn parse_map(mut tokens: IntoIter) -> HashMap<String, TokenTree> {
let mut map = HashMap::new();
while let Some(key) = tokens.next() {
let key = match key {
TokenTree::Ident(ident) => format!("{}", ident),
_ => panic!("expected key got {}", key),
};
parse_op(&mut tokens, ':', &key);
let value = match tokens.next() {
None => panic!("expected value for {}", key),
Some(value) => value,
};
parse_op(&mut tokens, ',', &key);
let _ = map.insert(key, value);
}
map
}
fn get_string(map: &mut HashMap<String, TokenTree>, key: &str) -> String {
let node = match map.remove(key) {
None => return String::new(),
Some(node) => node,
};
match syn::parse::<syn::LitStr>(node.into()) {
Ok(result) => result.value(),
_ => panic!("expected string for {}", key),
}
}
fn get_usize(map: &mut HashMap<String, TokenTree>, key: &str) -> usize {
let node = match map.remove(key) {
None => return 0,
Some(node) => node,
};
let literal = match node {
TokenTree::Literal(literal) => literal,
_ => panic!("expected literal for {}", key),
};
match literal.to_string().parse() {
Ok(result) => result,
Err(error) => panic!("expected usize for {}: {}", key, error),
}
}
fn get_padding(map: &mut HashMap<String, TokenTree>) -> Option<char> {
let node = match map.remove("padding") {
None => return None,
Some(node) => node,
};
if let Ok(result) = syn::parse::<syn::LitChar>(node.clone().into()) {
return Some(result.value());
}
match syn::parse::<syn::Ident>(node.into()) {
Ok(ref result) if result == "None" => None,
_ => panic!("expected None or char for padding"),
}
}
fn get_bool(map: &mut HashMap<String, TokenTree>, key: &str) -> Option<bool> {
let node = match map.remove(key) {
None => return None,
Some(node) => node,
};
match syn::parse::<syn::LitBool>(node.into()) {
Ok(result) => Some(result.value),
_ => panic!("expected bool for padding"),
}
}
fn get_bit_order(map: &mut HashMap<String, TokenTree>) -> BitOrder {
let node = match map.remove("bit_order") {
None => return BitOrder::MostSignificantFirst,
Some(node) => node,
};
let msb = "MostSignificantFirst";
let lsb = "LeastSignificantFirst";
match node {
TokenTree::Ident(ref ident) if format!("{}", ident) == msb => {
BitOrder::MostSignificantFirst
}
TokenTree::Ident(ref ident) if format!("{}", ident) == lsb => {
BitOrder::LeastSignificantFirst
}
_ => panic!("expected {} or {} for bit_order", msb, lsb),
}
}
fn check_present<T>(hash_map: &HashMap<String, T>, key: &str) {
assert!(hash_map.contains_key(key), "{} is required", key);
}
fn get_encoding(hash_map: &mut HashMap<String, TokenTree>) -> Encoding {
check_present(hash_map, "symbols");
let spec = Specification {
symbols: get_string(hash_map, "symbols"),
bit_order: get_bit_order(hash_map),
check_trailing_bits: get_bool(hash_map, "check_trailing_bits").unwrap_or(true),
padding: get_padding(hash_map),
ignore: get_string(hash_map, "ignore"),
wrap: Wrap {
width: get_usize(hash_map, "wrap_width"),
separator: get_string(hash_map, "wrap_separator"),
},
translate: Translate {
from: get_string(hash_map, "translate_from"),
to: get_string(hash_map, "translate_to"),
},
};
spec.encoding().unwrap()
}
fn check_empty<T>(hash_map: HashMap<String, T>) {
assert!(hash_map.is_empty(), "Unexpected keys {:?}", hash_map.keys());
}
#[proc_macro]
#[doc(hidden)]
pub fn internal_new_encoding(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_empty(hash_map);
format!("{:?}", encoding.internal_implementation()).parse().unwrap()
}
#[proc_macro]
#[doc(hidden)]
pub fn internal_decode_array(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_present(&hash_map, "name");
let name = get_string(&mut hash_map, "name");
check_present(&hash_map, "input");
let input = get_string(&mut hash_map, "input");
check_empty(hash_map);
let output = encoding.decode(input.as_bytes()).unwrap();
format!("{}: [u8; {}] = {:?};", name, output.len(), output).parse().unwrap()
}
#[proc_macro]
#[doc(hidden)]
pub fn internal_decode_slice(input: TokenStream) -> TokenStream
|
{
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_present(&hash_map, "input");
let input = get_string(&mut hash_map, "input");
check_empty(hash_map);
format!("{:?}", encoding.decode(input.as_bytes()).unwrap()).parse().unwrap()
}
|
identifier_body
|
|
lib.rs
|
//! Internal library for data-encoding-macro
//!
//! Do **not** use this library. Use [data-encoding-macro] instead.
//!
//! This library is for internal use by data-encoding-macro because procedural
//! macros require a separate crate.
//!
//! [data-encoding-macro]: https://crates.io/crates/data-encoding-macro
#![warn(unused_results)]
use proc_macro::token_stream::IntoIter;
use proc_macro::{TokenStream, TokenTree};
use std::collections::HashMap;
use data_encoding::{BitOrder, Encoding, Specification, Translate, Wrap};
fn parse_op(tokens: &mut IntoIter, op: char, key: &str) {
match tokens.next() {
Some(TokenTree::Punct(ref x)) if x.as_char() == op => (),
_ => panic!("expected {:?} after {}", op, key),
}
}
fn parse_map(mut tokens: IntoIter) -> HashMap<String, TokenTree> {
let mut map = HashMap::new();
while let Some(key) = tokens.next() {
let key = match key {
TokenTree::Ident(ident) => format!("{}", ident),
_ => panic!("expected key got {}", key),
};
parse_op(&mut tokens, ':', &key);
let value = match tokens.next() {
None => panic!("expected value for {}", key),
Some(value) => value,
};
parse_op(&mut tokens, ',', &key);
let _ = map.insert(key, value);
}
map
}
fn get_string(map: &mut HashMap<String, TokenTree>, key: &str) -> String {
let node = match map.remove(key) {
None => return String::new(),
Some(node) => node,
};
match syn::parse::<syn::LitStr>(node.into()) {
Ok(result) => result.value(),
_ => panic!("expected string for {}", key),
}
}
fn get_usize(map: &mut HashMap<String, TokenTree>, key: &str) -> usize {
let node = match map.remove(key) {
None => return 0,
Some(node) => node,
};
let literal = match node {
TokenTree::Literal(literal) => literal,
_ => panic!("expected literal for {}", key),
};
match literal.to_string().parse() {
Ok(result) => result,
Err(error) => panic!("expected usize for {}: {}", key, error),
}
}
fn get_padding(map: &mut HashMap<String, TokenTree>) -> Option<char> {
let node = match map.remove("padding") {
None => return None,
Some(node) => node,
};
if let Ok(result) = syn::parse::<syn::LitChar>(node.clone().into()) {
return Some(result.value());
}
match syn::parse::<syn::Ident>(node.into()) {
Ok(ref result) if result == "None" => None,
_ => panic!("expected None or char for padding"),
}
}
fn get_bool(map: &mut HashMap<String, TokenTree>, key: &str) -> Option<bool> {
let node = match map.remove(key) {
None => return None,
Some(node) => node,
};
match syn::parse::<syn::LitBool>(node.into()) {
Ok(result) => Some(result.value),
_ => panic!("expected bool for padding"),
}
}
fn get_bit_order(map: &mut HashMap<String, TokenTree>) -> BitOrder {
let node = match map.remove("bit_order") {
None => return BitOrder::MostSignificantFirst,
Some(node) => node,
};
let msb = "MostSignificantFirst";
let lsb = "LeastSignificantFirst";
match node {
TokenTree::Ident(ref ident) if format!("{}", ident) == msb => {
BitOrder::MostSignificantFirst
}
TokenTree::Ident(ref ident) if format!("{}", ident) == lsb => {
BitOrder::LeastSignificantFirst
}
_ => panic!("expected {} or {} for bit_order", msb, lsb),
}
}
fn check_present<T>(hash_map: &HashMap<String, T>, key: &str) {
assert!(hash_map.contains_key(key), "{} is required", key);
}
fn get_encoding(hash_map: &mut HashMap<String, TokenTree>) -> Encoding {
check_present(hash_map, "symbols");
let spec = Specification {
symbols: get_string(hash_map, "symbols"),
bit_order: get_bit_order(hash_map),
check_trailing_bits: get_bool(hash_map, "check_trailing_bits").unwrap_or(true),
padding: get_padding(hash_map),
ignore: get_string(hash_map, "ignore"),
wrap: Wrap {
width: get_usize(hash_map, "wrap_width"),
separator: get_string(hash_map, "wrap_separator"),
},
translate: Translate {
from: get_string(hash_map, "translate_from"),
to: get_string(hash_map, "translate_to"),
},
};
spec.encoding().unwrap()
}
fn check_empty<T>(hash_map: HashMap<String, T>) {
assert!(hash_map.is_empty(), "Unexpected keys {:?}", hash_map.keys());
}
#[proc_macro]
#[doc(hidden)]
pub fn
|
(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_empty(hash_map);
format!("{:?}", encoding.internal_implementation()).parse().unwrap()
}
#[proc_macro]
#[doc(hidden)]
pub fn internal_decode_array(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_present(&hash_map, "name");
let name = get_string(&mut hash_map, "name");
check_present(&hash_map, "input");
let input = get_string(&mut hash_map, "input");
check_empty(hash_map);
let output = encoding.decode(input.as_bytes()).unwrap();
format!("{}: [u8; {}] = {:?};", name, output.len(), output).parse().unwrap()
}
#[proc_macro]
#[doc(hidden)]
pub fn internal_decode_slice(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_present(&hash_map, "input");
let input = get_string(&mut hash_map, "input");
check_empty(hash_map);
format!("{:?}", encoding.decode(input.as_bytes()).unwrap()).parse().unwrap()
}
|
internal_new_encoding
|
identifier_name
|
lib.rs
|
//! Internal library for data-encoding-macro
//!
//! Do **not** use this library. Use [data-encoding-macro] instead.
//!
//! This library is for internal use by data-encoding-macro because procedural
//! macros require a separate crate.
//!
//! [data-encoding-macro]: https://crates.io/crates/data-encoding-macro
#![warn(unused_results)]
use proc_macro::token_stream::IntoIter;
use proc_macro::{TokenStream, TokenTree};
use std::collections::HashMap;
use data_encoding::{BitOrder, Encoding, Specification, Translate, Wrap};
fn parse_op(tokens: &mut IntoIter, op: char, key: &str) {
match tokens.next() {
Some(TokenTree::Punct(ref x)) if x.as_char() == op => (),
_ => panic!("expected {:?} after {}", op, key),
}
}
fn parse_map(mut tokens: IntoIter) -> HashMap<String, TokenTree> {
let mut map = HashMap::new();
while let Some(key) = tokens.next() {
let key = match key {
TokenTree::Ident(ident) => format!("{}", ident),
_ => panic!("expected key got {}", key),
};
parse_op(&mut tokens, ':', &key);
let value = match tokens.next() {
None => panic!("expected value for {}", key),
Some(value) => value,
};
parse_op(&mut tokens, ',', &key);
let _ = map.insert(key, value);
}
map
}
fn get_string(map: &mut HashMap<String, TokenTree>, key: &str) -> String {
let node = match map.remove(key) {
None => return String::new(),
Some(node) => node,
};
match syn::parse::<syn::LitStr>(node.into()) {
Ok(result) => result.value(),
_ => panic!("expected string for {}", key),
}
}
fn get_usize(map: &mut HashMap<String, TokenTree>, key: &str) -> usize {
let node = match map.remove(key) {
None => return 0,
Some(node) => node,
};
let literal = match node {
TokenTree::Literal(literal) => literal,
_ => panic!("expected literal for {}", key),
};
match literal.to_string().parse() {
Ok(result) => result,
Err(error) => panic!("expected usize for {}: {}", key, error),
}
}
fn get_padding(map: &mut HashMap<String, TokenTree>) -> Option<char> {
let node = match map.remove("padding") {
None => return None,
Some(node) => node,
};
if let Ok(result) = syn::parse::<syn::LitChar>(node.clone().into()) {
return Some(result.value());
}
match syn::parse::<syn::Ident>(node.into()) {
Ok(ref result) if result == "None" => None,
_ => panic!("expected None or char for padding"),
}
}
fn get_bool(map: &mut HashMap<String, TokenTree>, key: &str) -> Option<bool> {
let node = match map.remove(key) {
None => return None,
Some(node) => node,
};
match syn::parse::<syn::LitBool>(node.into()) {
Ok(result) => Some(result.value),
_ => panic!("expected bool for padding"),
}
}
fn get_bit_order(map: &mut HashMap<String, TokenTree>) -> BitOrder {
let node = match map.remove("bit_order") {
None => return BitOrder::MostSignificantFirst,
Some(node) => node,
};
let msb = "MostSignificantFirst";
let lsb = "LeastSignificantFirst";
match node {
TokenTree::Ident(ref ident) if format!("{}", ident) == msb => {
BitOrder::MostSignificantFirst
}
TokenTree::Ident(ref ident) if format!("{}", ident) == lsb => {
BitOrder::LeastSignificantFirst
}
_ => panic!("expected {} or {} for bit_order", msb, lsb),
}
}
fn check_present<T>(hash_map: &HashMap<String, T>, key: &str) {
assert!(hash_map.contains_key(key), "{} is required", key);
}
fn get_encoding(hash_map: &mut HashMap<String, TokenTree>) -> Encoding {
check_present(hash_map, "symbols");
let spec = Specification {
symbols: get_string(hash_map, "symbols"),
bit_order: get_bit_order(hash_map),
check_trailing_bits: get_bool(hash_map, "check_trailing_bits").unwrap_or(true),
padding: get_padding(hash_map),
ignore: get_string(hash_map, "ignore"),
wrap: Wrap {
width: get_usize(hash_map, "wrap_width"),
separator: get_string(hash_map, "wrap_separator"),
},
translate: Translate {
from: get_string(hash_map, "translate_from"),
to: get_string(hash_map, "translate_to"),
},
};
spec.encoding().unwrap()
}
fn check_empty<T>(hash_map: HashMap<String, T>) {
assert!(hash_map.is_empty(), "Unexpected keys {:?}", hash_map.keys());
|
pub fn internal_new_encoding(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_empty(hash_map);
format!("{:?}", encoding.internal_implementation()).parse().unwrap()
}
#[proc_macro]
#[doc(hidden)]
pub fn internal_decode_array(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_present(&hash_map, "name");
let name = get_string(&mut hash_map, "name");
check_present(&hash_map, "input");
let input = get_string(&mut hash_map, "input");
check_empty(hash_map);
let output = encoding.decode(input.as_bytes()).unwrap();
format!("{}: [u8; {}] = {:?};", name, output.len(), output).parse().unwrap()
}
#[proc_macro]
#[doc(hidden)]
pub fn internal_decode_slice(input: TokenStream) -> TokenStream {
let mut hash_map = parse_map(input.into_iter());
let encoding = get_encoding(&mut hash_map);
check_present(&hash_map, "input");
let input = get_string(&mut hash_map, "input");
check_empty(hash_map);
format!("{:?}", encoding.decode(input.as_bytes()).unwrap()).parse().unwrap()
}
|
}
#[proc_macro]
#[doc(hidden)]
|
random_line_split
|
simple.rs
|
#![feature(plugin)]
#![plugin(must_assert)]
extern crate must;
use must::COLOR_ENV;
use std::env;
#[test]
fn str_contains()
|
#[test]
fn simple() {
assume!("" == "");
assume!("" == "" || "" == "");
assume!("" == "" && "" == "");
}
#[test]
#[should_panic(expected = "Diff:
foo
-bar
baz
+bar
quux")]
fn str_fail_diff() {
env::set_var(COLOR_ENV, "none");
assume!("foo
bar
baz
quux" ==
"foo
baz
bar
quux");
env::remove_var(COLOR_ENV);
}
#[test]
#[should_panic(expected ="Diff:
| Index | Got | Expected |
|-------|------|----------|
| 0 | 1111 | 11 |
| 2 | 3333 | 3 |")]
fn array_failure() {
env::set_var(COLOR_ENV, "none");
assume!([1111, 2222, 3333, 4444] == [11, 2222, 3, 4444]);
}
/// See: https://github.com/rust-lang/rust/issues/38259
#[test]
#[should_panic(expected = r#"Diff:
| Index | Got | Expected |
|-------|-------|----------|
| 1 | "\na" | "b\n" |"#)]
fn vec_failure() {
env::set_var(COLOR_ENV, "none");
assume!(vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "\na"] == vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "b\n"]);
}
|
{
assume!("Banana".contains("nana"));
}
|
identifier_body
|
simple.rs
|
#![feature(plugin)]
#![plugin(must_assert)]
extern crate must;
use must::COLOR_ENV;
use std::env;
#[test]
fn
|
() {
assume!("Banana".contains("nana"));
}
#[test]
fn simple() {
assume!("" == "");
assume!("" == "" || "" == "");
assume!("" == "" && "" == "");
}
#[test]
#[should_panic(expected = "Diff:
foo
-bar
baz
+bar
quux")]
fn str_fail_diff() {
env::set_var(COLOR_ENV, "none");
assume!("foo
bar
baz
quux" ==
"foo
baz
bar
quux");
env::remove_var(COLOR_ENV);
}
#[test]
#[should_panic(expected ="Diff:
| Index | Got | Expected |
|-------|------|----------|
| 0 | 1111 | 11 |
| 2 | 3333 | 3 |")]
fn array_failure() {
env::set_var(COLOR_ENV, "none");
assume!([1111, 2222, 3333, 4444] == [11, 2222, 3, 4444]);
}
/// See: https://github.com/rust-lang/rust/issues/38259
#[test]
#[should_panic(expected = r#"Diff:
| Index | Got | Expected |
|-------|-------|----------|
| 1 | "\na" | "b\n" |"#)]
fn vec_failure() {
env::set_var(COLOR_ENV, "none");
assume!(vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "\na"] == vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "b\n"]);
}
|
str_contains
|
identifier_name
|
simple.rs
|
#![feature(plugin)]
#![plugin(must_assert)]
extern crate must;
use must::COLOR_ENV;
use std::env;
#[test]
fn str_contains() {
assume!("Banana".contains("nana"));
}
#[test]
fn simple() {
assume!("" == "");
assume!("" == "" || "" == "");
assume!("" == "" && "" == "");
}
#[test]
#[should_panic(expected = "Diff:
foo
-bar
baz
+bar
quux")]
fn str_fail_diff() {
env::set_var(COLOR_ENV, "none");
assume!("foo
bar
baz
quux" ==
"foo
baz
bar
quux");
env::remove_var(COLOR_ENV);
}
#[test]
#[should_panic(expected ="Diff:
| Index | Got | Expected |
|-------|------|----------|
| 0 | 1111 | 11 |
| 2 | 3333 | 3 |")]
fn array_failure() {
env::set_var(COLOR_ENV, "none");
assume!([1111, 2222, 3333, 4444] == [11, 2222, 3, 4444]);
}
/// See: https://github.com/rust-lang/rust/issues/38259
|
| 1 | "\na" | "b\n" |"#)]
fn vec_failure() {
env::set_var(COLOR_ENV, "none");
assume!(vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "\na"] == vec!["ABCDEFGHIZKLMNOPQRSTUVWXYZ", "b\n"]);
}
|
#[test]
#[should_panic(expected = r#"Diff:
| Index | Got | Expected |
|-------|-------|----------|
|
random_line_split
|
htmltrackelement.rs
|
/* 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 dom::bindings::codegen::Bindings::HTMLTrackElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTrackElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::ElementTypeId;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLTrackElement {
htmlelement: HTMLElement,
}
impl HTMLTrackElementDerived for EventTarget {
fn is_htmltrackelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(
NodeTypeId::Element(
ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTrackElement)))
}
}
impl HTMLTrackElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLTrackElement {
HTMLTrackElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTrackElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
|
document: &Document) -> Root<HTMLTrackElement> {
let element = HTMLTrackElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTrackElementBinding::Wrap)
}
}
|
prefix: Option<DOMString>,
|
random_line_split
|
htmltrackelement.rs
|
/* 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 dom::bindings::codegen::Bindings::HTMLTrackElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTrackElementDerived;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::ElementTypeId;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLTrackElement {
htmlelement: HTMLElement,
}
impl HTMLTrackElementDerived for EventTarget {
fn is_htmltrackelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(
NodeTypeId::Element(
ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTrackElement)))
}
}
impl HTMLTrackElement {
fn
|
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLTrackElement {
HTMLTrackElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTrackElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLTrackElement> {
let element = HTMLTrackElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTrackElementBinding::Wrap)
}
}
|
new_inherited
|
identifier_name
|
boot-delay.rs
|
use std::fs::File;
use std::io::Read;
use std::mem::transmute;
use std::thread::sleep;
use std::env;
use std::time::Duration;
fn
|
() {
let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) {
Some(d) => 60.0 * d,
None => {
println!("Usage: boot-delay <minutes>");
return;
}
};
let mut buf = [0u8; 1024];
let uptime = File::open("/proc/uptime")
.and_then(|ref mut file| file.read(&mut buf))
.map(|sz| {
buf.iter()
.position(|&c| c == 0x20)
.and_then(|p| if p < sz { unsafe { transmute::<_, &str>(&buf[..p]) }.parse::<f32>().ok() } else { None })
.unwrap()
})
.unwrap();
if delay > uptime {
sleep(Duration::from_secs((delay - uptime) as u64));
}
}
|
main
|
identifier_name
|
boot-delay.rs
|
use std::fs::File;
use std::io::Read;
use std::mem::transmute;
use std::thread::sleep;
use std::env;
use std::time::Duration;
fn main() {
let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) {
Some(d) => 60.0 * d,
None => {
println!("Usage: boot-delay <minutes>");
return;
}
};
let mut buf = [0u8; 1024];
let uptime = File::open("/proc/uptime")
.and_then(|ref mut file| file.read(&mut buf))
.map(|sz| {
|
})
.unwrap();
if delay > uptime {
sleep(Duration::from_secs((delay - uptime) as u64));
}
}
|
buf.iter()
.position(|&c| c == 0x20)
.and_then(|p| if p < sz { unsafe { transmute::<_, &str>(&buf[..p]) }.parse::<f32>().ok() } else { None })
.unwrap()
|
random_line_split
|
boot-delay.rs
|
use std::fs::File;
use std::io::Read;
use std::mem::transmute;
use std::thread::sleep;
use std::env;
use std::time::Duration;
fn main() {
let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) {
Some(d) => 60.0 * d,
None => {
println!("Usage: boot-delay <minutes>");
return;
}
};
let mut buf = [0u8; 1024];
let uptime = File::open("/proc/uptime")
.and_then(|ref mut file| file.read(&mut buf))
.map(|sz| {
buf.iter()
.position(|&c| c == 0x20)
.and_then(|p| if p < sz { unsafe { transmute::<_, &str>(&buf[..p]) }.parse::<f32>().ok() } else
|
)
.unwrap()
})
.unwrap();
if delay > uptime {
sleep(Duration::from_secs((delay - uptime) as u64));
}
}
|
{ None }
|
conditional_block
|
boot-delay.rs
|
use std::fs::File;
use std::io::Read;
use std::mem::transmute;
use std::thread::sleep;
use std::env;
use std::time::Duration;
fn main()
|
if delay > uptime {
sleep(Duration::from_secs((delay - uptime) as u64));
}
}
|
{
let delay = match env::args().nth(1).and_then(|s| s.parse::<f32>().ok()) {
Some(d) => 60.0 * d,
None => {
println!("Usage: boot-delay <minutes>");
return;
}
};
let mut buf = [0u8; 1024];
let uptime = File::open("/proc/uptime")
.and_then(|ref mut file| file.read(&mut buf))
.map(|sz| {
buf.iter()
.position(|&c| c == 0x20)
.and_then(|p| if p < sz { unsafe { transmute::<_, &str>(&buf[..p]) }.parse::<f32>().ok() } else { None })
.unwrap()
})
.unwrap();
|
identifier_body
|
lifetime-elision-return-type-requires-explicit-lifetime.rs
|
// 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.
// Lifetime annotation needed because we have no arguments.
fn f() -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP there is no value for it to be borrowed from
panic!()
}
// Lifetime annotation needed because we have two by-reference parameters.
fn g(_x: &isize, _y: &isize) -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP the signature does not say whether it is borrowed from `_x` or `_y`
panic!()
}
struct Foo<'a> {
x: &'a isize,
}
// Lifetime annotation needed because we have two lifetimes: one as a parameter
// and one on the reference.
fn
|
(_x: &Foo) -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP the signature does not say which one of `_x`'s 2 elided lifetimes it is borrowed from
panic!()
}
fn i(_x: isize) -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP this function's return type contains a borrowed value
panic!()
}
fn main() {}
|
h
|
identifier_name
|
lifetime-elision-return-type-requires-explicit-lifetime.rs
|
// 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.
// Lifetime annotation needed because we have no arguments.
fn f() -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP there is no value for it to be borrowed from
panic!()
}
// Lifetime annotation needed because we have two by-reference parameters.
fn g(_x: &isize, _y: &isize) -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP the signature does not say whether it is borrowed from `_x` or `_y`
panic!()
}
struct Foo<'a> {
x: &'a isize,
}
// Lifetime annotation needed because we have two lifetimes: one as a parameter
// and one on the reference.
fn h(_x: &Foo) -> &isize
|
fn i(_x: isize) -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP this function's return type contains a borrowed value
panic!()
}
fn main() {}
|
{ //~ ERROR missing lifetime specifier
//~^ HELP the signature does not say which one of `_x`'s 2 elided lifetimes it is borrowed from
panic!()
}
|
identifier_body
|
lifetime-elision-return-type-requires-explicit-lifetime.rs
|
// 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.
// Lifetime annotation needed because we have no arguments.
fn f() -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP there is no value for it to be borrowed from
panic!()
}
// Lifetime annotation needed because we have two by-reference parameters.
fn g(_x: &isize, _y: &isize) -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP the signature does not say whether it is borrowed from `_x` or `_y`
panic!()
}
struct Foo<'a> {
x: &'a isize,
}
// Lifetime annotation needed because we have two lifetimes: one as a parameter
// and one on the reference.
fn h(_x: &Foo) -> &isize { //~ ERROR missing lifetime specifier
//~^ HELP the signature does not say which one of `_x`'s 2 elided lifetimes it is borrowed from
panic!()
}
|
//~^ HELP this function's return type contains a borrowed value
panic!()
}
fn main() {}
|
fn i(_x: isize) -> &isize { //~ ERROR missing lifetime specifier
|
random_line_split
|
heap.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![unstable(feature = "heap_api",
reason = "the precise API and guarantees it provides may be tweaked \
slightly, especially to possibly take into account the \
types being stored to make room for a future \
tracing garbage collector",
issue = "27700")]
use core::{isize, usize};
#[allow(improper_ctypes)]
extern {
#[allocator]
fn __rust_allocate(size: usize, align: usize) -> *mut u8;
fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize);
fn __rust_reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8;
fn __rust_reallocate_inplace(ptr: *mut u8,
old_size: usize,
size: usize,
align: usize)
-> usize;
fn __rust_usable_size(size: usize, align: usize) -> usize;
}
#[inline(always)]
fn check_size_and_alignment(size: usize, align: usize) {
debug_assert!(size!= 0);
debug_assert!(size <= isize::MAX as usize,
"Tried to allocate too much: {} bytes",
size);
debug_assert!(usize::is_power_of_two(align),
"Invalid alignment of allocation: {}",
align);
}
// FIXME: #13996: mark the `allocate` and `reallocate` return value as `noalias`
/// Return a pointer to `size` bytes of memory aligned to `align`.
///
/// On failure, return a null pointer.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
#[inline]
pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
check_size_and_alignment(size, align);
__rust_allocate(size, align)
}
/// Resize the allocation referenced by `ptr` to `size` bytes.
///
/// On failure, return a null pointer and leave the original allocation intact.
///
/// If the allocation was relocated, the memory at the passed-in pointer is
/// undefined after the call.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
check_size_and_alignment(size, align);
__rust_reallocate(ptr, old_size, size, align)
}
/// Resize the allocation referenced by `ptr` to `size` bytes.
///
/// If the operation succeeds, it returns `usable_size(size, align)` and if it
/// fails (or is a no-op) it returns `usable_size(old_size, align)`.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn reallocate_inplace(ptr: *mut u8,
old_size: usize,
size: usize,
align: usize)
-> usize {
check_size_and_alignment(size, align);
__rust_reallocate_inplace(ptr, old_size, size, align)
}
/// Deallocates the memory referenced by `ptr`.
///
/// The `ptr` parameter must not be null.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn deallocate(ptr: *mut u8, old_size: usize, align: usize) {
__rust_deallocate(ptr, old_size, align)
}
/// Returns the usable size of an allocation created with the specified the
/// `size` and `align`.
#[inline]
pub fn usable_size(size: usize, align: usize) -> usize {
unsafe { __rust_usable_size(size, align) }
}
/// An arbitrary non-null address to represent zero-size allocations.
///
/// This preserves the non-null invariant for types like `Box<T>`. The address
/// may overlap with non-zero-size memory allocations.
pub const EMPTY: *mut () = 0x1 as *mut ();
/// The allocator for unique pointers.
#[cfg(not(test))]
#[lang = "exchange_malloc"]
#[inline]
unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
if size == 0 {
EMPTY as *mut u8
} else
|
}
#[cfg(not(test))]
#[lang = "exchange_free"]
#[inline]
unsafe fn exchange_free(ptr: *mut u8, old_size: usize, align: usize) {
deallocate(ptr, old_size, align);
}
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use boxed::Box;
use heap;
#[test]
fn basic_reallocate_inplace_noop() {
unsafe {
let size = 4000;
let ptr = heap::allocate(size, 8);
if ptr.is_null() {
::oom()
}
let ret = heap::reallocate_inplace(ptr, size, size, 8);
heap::deallocate(ptr, size, 8);
assert_eq!(ret, heap::usable_size(size, 8));
}
}
#[bench]
fn alloc_owned_small(b: &mut Bencher) {
b.iter(|| {
let _: Box<_> = box 10;
})
}
}
|
{
let ptr = allocate(size, align);
if ptr.is_null() {
::oom()
}
ptr
}
|
conditional_block
|
heap.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![unstable(feature = "heap_api",
reason = "the precise API and guarantees it provides may be tweaked \
slightly, especially to possibly take into account the \
types being stored to make room for a future \
tracing garbage collector",
issue = "27700")]
use core::{isize, usize};
#[allow(improper_ctypes)]
extern {
#[allocator]
fn __rust_allocate(size: usize, align: usize) -> *mut u8;
fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize);
fn __rust_reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8;
fn __rust_reallocate_inplace(ptr: *mut u8,
old_size: usize,
size: usize,
align: usize)
-> usize;
fn __rust_usable_size(size: usize, align: usize) -> usize;
}
#[inline(always)]
fn check_size_and_alignment(size: usize, align: usize) {
debug_assert!(size!= 0);
debug_assert!(size <= isize::MAX as usize,
"Tried to allocate too much: {} bytes",
size);
debug_assert!(usize::is_power_of_two(align),
"Invalid alignment of allocation: {}",
align);
}
// FIXME: #13996: mark the `allocate` and `reallocate` return value as `noalias`
/// Return a pointer to `size` bytes of memory aligned to `align`.
///
/// On failure, return a null pointer.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
#[inline]
pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
check_size_and_alignment(size, align);
__rust_allocate(size, align)
}
/// Resize the allocation referenced by `ptr` to `size` bytes.
///
/// On failure, return a null pointer and leave the original allocation intact.
///
/// If the allocation was relocated, the memory at the passed-in pointer is
/// undefined after the call.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
check_size_and_alignment(size, align);
__rust_reallocate(ptr, old_size, size, align)
}
/// Resize the allocation referenced by `ptr` to `size` bytes.
///
/// If the operation succeeds, it returns `usable_size(size, align)` and if it
/// fails (or is a no-op) it returns `usable_size(old_size, align)`.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn reallocate_inplace(ptr: *mut u8,
old_size: usize,
size: usize,
align: usize)
-> usize {
check_size_and_alignment(size, align);
__rust_reallocate_inplace(ptr, old_size, size, align)
}
/// Deallocates the memory referenced by `ptr`.
///
/// The `ptr` parameter must not be null.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn deallocate(ptr: *mut u8, old_size: usize, align: usize) {
__rust_deallocate(ptr, old_size, align)
}
/// Returns the usable size of an allocation created with the specified the
/// `size` and `align`.
#[inline]
pub fn usable_size(size: usize, align: usize) -> usize {
unsafe { __rust_usable_size(size, align) }
}
/// An arbitrary non-null address to represent zero-size allocations.
///
/// This preserves the non-null invariant for types like `Box<T>`. The address
/// may overlap with non-zero-size memory allocations.
pub const EMPTY: *mut () = 0x1 as *mut ();
/// The allocator for unique pointers.
#[cfg(not(test))]
#[lang = "exchange_malloc"]
#[inline]
unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
if size == 0 {
EMPTY as *mut u8
} else {
let ptr = allocate(size, align);
if ptr.is_null() {
::oom()
}
ptr
}
}
#[cfg(not(test))]
#[lang = "exchange_free"]
#[inline]
unsafe fn exchange_free(ptr: *mut u8, old_size: usize, align: usize) {
deallocate(ptr, old_size, align);
}
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use boxed::Box;
use heap;
#[test]
fn basic_reallocate_inplace_noop() {
unsafe {
let size = 4000;
let ptr = heap::allocate(size, 8);
if ptr.is_null() {
::oom()
}
|
}
}
#[bench]
fn alloc_owned_small(b: &mut Bencher) {
b.iter(|| {
let _: Box<_> = box 10;
})
}
}
|
let ret = heap::reallocate_inplace(ptr, size, size, 8);
heap::deallocate(ptr, size, 8);
assert_eq!(ret, heap::usable_size(size, 8));
|
random_line_split
|
heap.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![unstable(feature = "heap_api",
reason = "the precise API and guarantees it provides may be tweaked \
slightly, especially to possibly take into account the \
types being stored to make room for a future \
tracing garbage collector",
issue = "27700")]
use core::{isize, usize};
#[allow(improper_ctypes)]
extern {
#[allocator]
fn __rust_allocate(size: usize, align: usize) -> *mut u8;
fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize);
fn __rust_reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8;
fn __rust_reallocate_inplace(ptr: *mut u8,
old_size: usize,
size: usize,
align: usize)
-> usize;
fn __rust_usable_size(size: usize, align: usize) -> usize;
}
#[inline(always)]
fn check_size_and_alignment(size: usize, align: usize) {
debug_assert!(size!= 0);
debug_assert!(size <= isize::MAX as usize,
"Tried to allocate too much: {} bytes",
size);
debug_assert!(usize::is_power_of_two(align),
"Invalid alignment of allocation: {}",
align);
}
// FIXME: #13996: mark the `allocate` and `reallocate` return value as `noalias`
/// Return a pointer to `size` bytes of memory aligned to `align`.
///
/// On failure, return a null pointer.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
#[inline]
pub unsafe fn allocate(size: usize, align: usize) -> *mut u8
|
/// Resize the allocation referenced by `ptr` to `size` bytes.
///
/// On failure, return a null pointer and leave the original allocation intact.
///
/// If the allocation was relocated, the memory at the passed-in pointer is
/// undefined after the call.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
check_size_and_alignment(size, align);
__rust_reallocate(ptr, old_size, size, align)
}
/// Resize the allocation referenced by `ptr` to `size` bytes.
///
/// If the operation succeeds, it returns `usable_size(size, align)` and if it
/// fails (or is a no-op) it returns `usable_size(old_size, align)`.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn reallocate_inplace(ptr: *mut u8,
old_size: usize,
size: usize,
align: usize)
-> usize {
check_size_and_alignment(size, align);
__rust_reallocate_inplace(ptr, old_size, size, align)
}
/// Deallocates the memory referenced by `ptr`.
///
/// The `ptr` parameter must not be null.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn deallocate(ptr: *mut u8, old_size: usize, align: usize) {
__rust_deallocate(ptr, old_size, align)
}
/// Returns the usable size of an allocation created with the specified the
/// `size` and `align`.
#[inline]
pub fn usable_size(size: usize, align: usize) -> usize {
unsafe { __rust_usable_size(size, align) }
}
/// An arbitrary non-null address to represent zero-size allocations.
///
/// This preserves the non-null invariant for types like `Box<T>`. The address
/// may overlap with non-zero-size memory allocations.
pub const EMPTY: *mut () = 0x1 as *mut ();
/// The allocator for unique pointers.
#[cfg(not(test))]
#[lang = "exchange_malloc"]
#[inline]
unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
if size == 0 {
EMPTY as *mut u8
} else {
let ptr = allocate(size, align);
if ptr.is_null() {
::oom()
}
ptr
}
}
#[cfg(not(test))]
#[lang = "exchange_free"]
#[inline]
unsafe fn exchange_free(ptr: *mut u8, old_size: usize, align: usize) {
deallocate(ptr, old_size, align);
}
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use boxed::Box;
use heap;
#[test]
fn basic_reallocate_inplace_noop() {
unsafe {
let size = 4000;
let ptr = heap::allocate(size, 8);
if ptr.is_null() {
::oom()
}
let ret = heap::reallocate_inplace(ptr, size, size, 8);
heap::deallocate(ptr, size, 8);
assert_eq!(ret, heap::usable_size(size, 8));
}
}
#[bench]
fn alloc_owned_small(b: &mut Bencher) {
b.iter(|| {
let _: Box<_> = box 10;
})
}
}
|
{
check_size_and_alignment(size, align);
__rust_allocate(size, align)
}
|
identifier_body
|
heap.rs
|
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![unstable(feature = "heap_api",
reason = "the precise API and guarantees it provides may be tweaked \
slightly, especially to possibly take into account the \
types being stored to make room for a future \
tracing garbage collector",
issue = "27700")]
use core::{isize, usize};
#[allow(improper_ctypes)]
extern {
#[allocator]
fn __rust_allocate(size: usize, align: usize) -> *mut u8;
fn __rust_deallocate(ptr: *mut u8, old_size: usize, align: usize);
fn __rust_reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8;
fn __rust_reallocate_inplace(ptr: *mut u8,
old_size: usize,
size: usize,
align: usize)
-> usize;
fn __rust_usable_size(size: usize, align: usize) -> usize;
}
#[inline(always)]
fn check_size_and_alignment(size: usize, align: usize) {
debug_assert!(size!= 0);
debug_assert!(size <= isize::MAX as usize,
"Tried to allocate too much: {} bytes",
size);
debug_assert!(usize::is_power_of_two(align),
"Invalid alignment of allocation: {}",
align);
}
// FIXME: #13996: mark the `allocate` and `reallocate` return value as `noalias`
/// Return a pointer to `size` bytes of memory aligned to `align`.
///
/// On failure, return a null pointer.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
#[inline]
pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
check_size_and_alignment(size, align);
__rust_allocate(size, align)
}
/// Resize the allocation referenced by `ptr` to `size` bytes.
///
/// On failure, return a null pointer and leave the original allocation intact.
///
/// If the allocation was relocated, the memory at the passed-in pointer is
/// undefined after the call.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
check_size_and_alignment(size, align);
__rust_reallocate(ptr, old_size, size, align)
}
/// Resize the allocation referenced by `ptr` to `size` bytes.
///
/// If the operation succeeds, it returns `usable_size(size, align)` and if it
/// fails (or is a no-op) it returns `usable_size(old_size, align)`.
///
/// Behavior is undefined if the requested size is 0 or the alignment is not a
/// power of 2. The alignment must be no larger than the largest supported page
/// size on the platform.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn reallocate_inplace(ptr: *mut u8,
old_size: usize,
size: usize,
align: usize)
-> usize {
check_size_and_alignment(size, align);
__rust_reallocate_inplace(ptr, old_size, size, align)
}
/// Deallocates the memory referenced by `ptr`.
///
/// The `ptr` parameter must not be null.
///
/// The `old_size` and `align` parameters are the parameters that were used to
/// create the allocation referenced by `ptr`. The `old_size` parameter may be
/// any value in range_inclusive(requested_size, usable_size).
#[inline]
pub unsafe fn deallocate(ptr: *mut u8, old_size: usize, align: usize) {
__rust_deallocate(ptr, old_size, align)
}
/// Returns the usable size of an allocation created with the specified the
/// `size` and `align`.
#[inline]
pub fn usable_size(size: usize, align: usize) -> usize {
unsafe { __rust_usable_size(size, align) }
}
/// An arbitrary non-null address to represent zero-size allocations.
///
/// This preserves the non-null invariant for types like `Box<T>`. The address
/// may overlap with non-zero-size memory allocations.
pub const EMPTY: *mut () = 0x1 as *mut ();
/// The allocator for unique pointers.
#[cfg(not(test))]
#[lang = "exchange_malloc"]
#[inline]
unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
if size == 0 {
EMPTY as *mut u8
} else {
let ptr = allocate(size, align);
if ptr.is_null() {
::oom()
}
ptr
}
}
#[cfg(not(test))]
#[lang = "exchange_free"]
#[inline]
unsafe fn exchange_free(ptr: *mut u8, old_size: usize, align: usize) {
deallocate(ptr, old_size, align);
}
#[cfg(test)]
mod tests {
extern crate test;
use self::test::Bencher;
use boxed::Box;
use heap;
#[test]
fn
|
() {
unsafe {
let size = 4000;
let ptr = heap::allocate(size, 8);
if ptr.is_null() {
::oom()
}
let ret = heap::reallocate_inplace(ptr, size, size, 8);
heap::deallocate(ptr, size, 8);
assert_eq!(ret, heap::usable_size(size, 8));
}
}
#[bench]
fn alloc_owned_small(b: &mut Bencher) {
b.iter(|| {
let _: Box<_> = box 10;
})
}
}
|
basic_reallocate_inplace_noop
|
identifier_name
|
generic-struct.rs
|
// 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.
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print int_int
// check:$1 = {key = 0, value = 1}
// debugger:print int_float
// check:$2 = {key = 2, value = 3.5}
// debugger:print float_int
// check:$3 = {key = 4.5, value = 5}
// debugger:print float_int_float
// check:$4 = {key = 6.5, value = {key = 7, value = 8.5}}
struct
|
<TKey, TValue> {
key: TKey,
value: TValue
}
fn main() {
let int_int = AGenericStruct { key: 0, value: 1 };
let int_float = AGenericStruct { key: 2, value: 3.5 };
let float_int = AGenericStruct { key: 4.5, value: 5 };
let float_int_float = AGenericStruct { key: 6.5, value: AGenericStruct { key: 7, value: 8.5 } };
zzz();
}
fn zzz() {()}
|
AGenericStruct
|
identifier_name
|
generic-struct.rs
|
// 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.
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print int_int
// check:$1 = {key = 0, value = 1}
// debugger:print int_float
// check:$2 = {key = 2, value = 3.5}
// debugger:print float_int
// check:$3 = {key = 4.5, value = 5}
// debugger:print float_int_float
// check:$4 = {key = 6.5, value = {key = 7, value = 8.5}}
struct AGenericStruct<TKey, TValue> {
key: TKey,
value: TValue
}
fn main()
|
fn zzz() {()}
|
{
let int_int = AGenericStruct { key: 0, value: 1 };
let int_float = AGenericStruct { key: 2, value: 3.5 };
let float_int = AGenericStruct { key: 4.5, value: 5 };
let float_int_float = AGenericStruct { key: 6.5, value: AGenericStruct { key: 7, value: 8.5 } };
zzz();
}
|
identifier_body
|
generic-struct.rs
|
// 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
|
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print int_int
// check:$1 = {key = 0, value = 1}
// debugger:print int_float
// check:$2 = {key = 2, value = 3.5}
// debugger:print float_int
// check:$3 = {key = 4.5, value = 5}
// debugger:print float_int_float
// check:$4 = {key = 6.5, value = {key = 7, value = 8.5}}
struct AGenericStruct<TKey, TValue> {
key: TKey,
value: TValue
}
fn main() {
let int_int = AGenericStruct { key: 0, value: 1 };
let int_float = AGenericStruct { key: 2, value: 3.5 };
let float_int = AGenericStruct { key: 4.5, value: 5 };
let float_int_float = AGenericStruct { key: 6.5, value: AGenericStruct { key: 7, value: 8.5 } };
zzz();
}
fn zzz() {()}
|
// except according to those terms.
|
random_line_split
|
any.rs
|
// 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.
//! Traits for dynamic typing of any type (through runtime reflection)
//!
//! This module implements the `Any` trait, which enables dynamic typing
//! of any type, through runtime reflection.
//!
//! `Any` itself can be used to get a `TypeId`, and has more features when used as a trait object.
//! As `&Any` (a borrowed trait object), it has the `is` and `as_ref` methods, to test if the
//! contained value is of a given type, and to get a reference to the inner value as a type. As
//! `&mut Any`, there is also the `as_mut` method, for getting a mutable reference to the inner
//! value. `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the object. See
//! the extension traits (`*Ext`) for the full details.
use cast::{transmute, transmute_copy};
use option::{Option, Some, None};
use owned::Box;
use raw::TraitObject;
use result::{Result, Ok, Err};
use intrinsics::TypeId;
use intrinsics;
/// A type with no inhabitants
pub enum Void { }
///////////////////////////////////////////////////////////////////////////////
// Any trait
///////////////////////////////////////////////////////////////////////////////
/// The `Any` trait is implemented by all types, and can be used as a trait object
/// for dynamic typing
pub trait Any {
/// Get the `TypeId` of `self`
fn get_type_id(&self) -> TypeId;
}
impl<T:'static> Any for T {
/// Get the `TypeId` of `self`
fn get_type_id(&self) -> TypeId {
TypeId::of::<T>()
}
}
///////////////////////////////////////////////////////////////////////////////
// Extension methods for Any trait objects.
// Implemented as three extension traits so that the methods can be generic.
///////////////////////////////////////////////////////////////////////////////
/// Extension methods for a referenced `Any` trait object
pub trait AnyRefExt<'a> {
/// Returns true if the boxed type is the same as `T`
fn is<T:'static>(self) -> bool;
/// Returns some reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
fn as_ref<T:'static>(self) -> Option<&'a T>;
}
impl<'a> AnyRefExt<'a> for &'a Any {
#[inline]
fn is<T:'static>(self) -> bool {
// Get TypeId of the type this function is instantiated with
let t = TypeId::of::<T>();
// Get TypeId of the type in the trait object
let boxed = self.get_type_id();
// Compare both TypeIds on equality
t == boxed
}
#[inline]
fn as_ref<T:'static>(self) -> Option<&'a T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
}
/// Extension methods for a mutable referenced `Any` trait object
pub trait AnyMutRefExt<'a> {
/// Returns some mutable reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
fn as_mut<T:'static>(self) -> Option<&'a mut T>;
}
impl<'a> AnyMutRefExt<'a> for &'a mut Any {
#[inline]
fn as_mut<T:'static>(self) -> Option<&'a mut T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
}
/// Extension methods for an owning `Any` trait object
pub trait AnyOwnExt {
/// Returns the boxed value if it is of type `T`, or
/// `Err(Self)` if it isn't.
fn move<T:'static>(self) -> Result<Box<T>, Self>;
}
impl AnyOwnExt for Box<Any> {
#[inline]
fn move<T:'static>(self) -> Result<Box<T>, Box<Any>>
|
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::*;
use owned::Box;
use realstd::str::StrAllocating;
#[deriving(Eq, Show)]
struct Test;
static TEST: &'static str = "Test";
#[test]
fn any_referenced() {
let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any);
assert!(a.is::<uint>());
assert!(!b.is::<uint>());
assert!(!c.is::<uint>());
assert!(!a.is::<&'static str>());
assert!(b.is::<&'static str>());
assert!(!c.is::<&'static str>());
assert!(!a.is::<Test>());
assert!(!b.is::<Test>());
assert!(c.is::<Test>());
}
#[test]
fn any_owning() {
let (a, b, c) = (box 5u as Box<Any>, box TEST as Box<Any>, box Test as Box<Any>);
assert!(a.is::<uint>());
assert!(!b.is::<uint>());
assert!(!c.is::<uint>());
assert!(!a.is::<&'static str>());
assert!(b.is::<&'static str>());
assert!(!c.is::<&'static str>());
assert!(!a.is::<Test>());
assert!(!b.is::<Test>());
assert!(c.is::<Test>());
}
#[test]
fn any_as_ref() {
let a = &5u as &Any;
match a.as_ref::<uint>() {
Some(&5) => {}
x => fail!("Unexpected value {:?}", x)
}
match a.as_ref::<Test>() {
None => {}
x => fail!("Unexpected value {:?}", x)
}
}
#[test]
fn any_as_mut() {
let mut a = 5u;
let mut b = box 7u;
let a_r = &mut a as &mut Any;
let tmp: &mut uint = b;
let b_r = tmp as &mut Any;
match a_r.as_mut::<uint>() {
Some(x) => {
assert_eq!(*x, 5u);
*x = 612;
}
x => fail!("Unexpected value {:?}", x)
}
match b_r.as_mut::<uint>() {
Some(x) => {
assert_eq!(*x, 7u);
*x = 413;
}
x => fail!("Unexpected value {:?}", x)
}
match a_r.as_mut::<Test>() {
None => (),
x => fail!("Unexpected value {:?}", x)
}
match b_r.as_mut::<Test>() {
None => (),
x => fail!("Unexpected value {:?}", x)
}
match a_r.as_mut::<uint>() {
Some(&612) => {}
x => fail!("Unexpected value {:?}", x)
}
match b_r.as_mut::<uint>() {
Some(&413) => {}
x => fail!("Unexpected value {:?}", x)
}
}
#[test]
fn any_move() {
let a = box 8u as Box<Any>;
let b = box Test as Box<Any>;
match a.move::<uint>() {
Ok(a) => { assert_eq!(a, box 8u); }
Err(..) => fail!()
}
match b.move::<Test>() {
Ok(a) => { assert_eq!(a, box Test); }
Err(..) => fail!()
}
let a = box 8u as Box<Any>;
let b = box Test as Box<Any>;
assert!(a.move::<Box<Test>>().is_err());
assert!(b.move::<Box<uint>>().is_err());
}
#[test]
fn test_show() {
let a = box 8u as Box<::realcore::any::Any>;
let b = box Test as Box<::realcore::any::Any>;
assert_eq!(format!("{}", a), "Box<Any>".to_owned());
assert_eq!(format!("{}", b), "Box<Any>".to_owned());
let a = &8u as &::realcore::any::Any;
let b = &Test as &::realcore::any::Any;
assert_eq!(format!("{}", a), "&Any".to_owned());
assert_eq!(format!("{}", b), "&Any".to_owned());
}
}
#[cfg(test)]
mod bench {
extern crate test;
use any::{Any, AnyRefExt};
use option::Some;
use self::test::Bencher;
#[bench]
fn bench_as_ref(b: &mut Bencher) {
b.iter(|| {
let mut x = 0; let mut y = &mut x as &mut Any;
test::black_box(&mut y);
test::black_box(y.as_ref::<int>() == Some(&0));
});
}
}
|
{
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Prevent destructor on self being run
intrinsics::forget(self);
// Extract the data pointer
Ok(transmute(to.data))
}
} else {
Err(self)
}
}
|
identifier_body
|
any.rs
|
// 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.
//! Traits for dynamic typing of any type (through runtime reflection)
//!
//! This module implements the `Any` trait, which enables dynamic typing
//! of any type, through runtime reflection.
//!
//! `Any` itself can be used to get a `TypeId`, and has more features when used as a trait object.
//! As `&Any` (a borrowed trait object), it has the `is` and `as_ref` methods, to test if the
//! contained value is of a given type, and to get a reference to the inner value as a type. As
//! `&mut Any`, there is also the `as_mut` method, for getting a mutable reference to the inner
//! value. `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the object. See
//! the extension traits (`*Ext`) for the full details.
use cast::{transmute, transmute_copy};
use option::{Option, Some, None};
use owned::Box;
use raw::TraitObject;
use result::{Result, Ok, Err};
use intrinsics::TypeId;
use intrinsics;
/// A type with no inhabitants
pub enum Void { }
///////////////////////////////////////////////////////////////////////////////
// Any trait
///////////////////////////////////////////////////////////////////////////////
/// The `Any` trait is implemented by all types, and can be used as a trait object
/// for dynamic typing
pub trait Any {
/// Get the `TypeId` of `self`
fn get_type_id(&self) -> TypeId;
}
|
TypeId::of::<T>()
}
}
///////////////////////////////////////////////////////////////////////////////
// Extension methods for Any trait objects.
// Implemented as three extension traits so that the methods can be generic.
///////////////////////////////////////////////////////////////////////////////
/// Extension methods for a referenced `Any` trait object
pub trait AnyRefExt<'a> {
/// Returns true if the boxed type is the same as `T`
fn is<T:'static>(self) -> bool;
/// Returns some reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
fn as_ref<T:'static>(self) -> Option<&'a T>;
}
impl<'a> AnyRefExt<'a> for &'a Any {
#[inline]
fn is<T:'static>(self) -> bool {
// Get TypeId of the type this function is instantiated with
let t = TypeId::of::<T>();
// Get TypeId of the type in the trait object
let boxed = self.get_type_id();
// Compare both TypeIds on equality
t == boxed
}
#[inline]
fn as_ref<T:'static>(self) -> Option<&'a T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
}
/// Extension methods for a mutable referenced `Any` trait object
pub trait AnyMutRefExt<'a> {
/// Returns some mutable reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
fn as_mut<T:'static>(self) -> Option<&'a mut T>;
}
impl<'a> AnyMutRefExt<'a> for &'a mut Any {
#[inline]
fn as_mut<T:'static>(self) -> Option<&'a mut T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
}
/// Extension methods for an owning `Any` trait object
pub trait AnyOwnExt {
/// Returns the boxed value if it is of type `T`, or
/// `Err(Self)` if it isn't.
fn move<T:'static>(self) -> Result<Box<T>, Self>;
}
impl AnyOwnExt for Box<Any> {
#[inline]
fn move<T:'static>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Prevent destructor on self being run
intrinsics::forget(self);
// Extract the data pointer
Ok(transmute(to.data))
}
} else {
Err(self)
}
}
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::*;
use owned::Box;
use realstd::str::StrAllocating;
#[deriving(Eq, Show)]
struct Test;
static TEST: &'static str = "Test";
#[test]
fn any_referenced() {
let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any);
assert!(a.is::<uint>());
assert!(!b.is::<uint>());
assert!(!c.is::<uint>());
assert!(!a.is::<&'static str>());
assert!(b.is::<&'static str>());
assert!(!c.is::<&'static str>());
assert!(!a.is::<Test>());
assert!(!b.is::<Test>());
assert!(c.is::<Test>());
}
#[test]
fn any_owning() {
let (a, b, c) = (box 5u as Box<Any>, box TEST as Box<Any>, box Test as Box<Any>);
assert!(a.is::<uint>());
assert!(!b.is::<uint>());
assert!(!c.is::<uint>());
assert!(!a.is::<&'static str>());
assert!(b.is::<&'static str>());
assert!(!c.is::<&'static str>());
assert!(!a.is::<Test>());
assert!(!b.is::<Test>());
assert!(c.is::<Test>());
}
#[test]
fn any_as_ref() {
let a = &5u as &Any;
match a.as_ref::<uint>() {
Some(&5) => {}
x => fail!("Unexpected value {:?}", x)
}
match a.as_ref::<Test>() {
None => {}
x => fail!("Unexpected value {:?}", x)
}
}
#[test]
fn any_as_mut() {
let mut a = 5u;
let mut b = box 7u;
let a_r = &mut a as &mut Any;
let tmp: &mut uint = b;
let b_r = tmp as &mut Any;
match a_r.as_mut::<uint>() {
Some(x) => {
assert_eq!(*x, 5u);
*x = 612;
}
x => fail!("Unexpected value {:?}", x)
}
match b_r.as_mut::<uint>() {
Some(x) => {
assert_eq!(*x, 7u);
*x = 413;
}
x => fail!("Unexpected value {:?}", x)
}
match a_r.as_mut::<Test>() {
None => (),
x => fail!("Unexpected value {:?}", x)
}
match b_r.as_mut::<Test>() {
None => (),
x => fail!("Unexpected value {:?}", x)
}
match a_r.as_mut::<uint>() {
Some(&612) => {}
x => fail!("Unexpected value {:?}", x)
}
match b_r.as_mut::<uint>() {
Some(&413) => {}
x => fail!("Unexpected value {:?}", x)
}
}
#[test]
fn any_move() {
let a = box 8u as Box<Any>;
let b = box Test as Box<Any>;
match a.move::<uint>() {
Ok(a) => { assert_eq!(a, box 8u); }
Err(..) => fail!()
}
match b.move::<Test>() {
Ok(a) => { assert_eq!(a, box Test); }
Err(..) => fail!()
}
let a = box 8u as Box<Any>;
let b = box Test as Box<Any>;
assert!(a.move::<Box<Test>>().is_err());
assert!(b.move::<Box<uint>>().is_err());
}
#[test]
fn test_show() {
let a = box 8u as Box<::realcore::any::Any>;
let b = box Test as Box<::realcore::any::Any>;
assert_eq!(format!("{}", a), "Box<Any>".to_owned());
assert_eq!(format!("{}", b), "Box<Any>".to_owned());
let a = &8u as &::realcore::any::Any;
let b = &Test as &::realcore::any::Any;
assert_eq!(format!("{}", a), "&Any".to_owned());
assert_eq!(format!("{}", b), "&Any".to_owned());
}
}
#[cfg(test)]
mod bench {
extern crate test;
use any::{Any, AnyRefExt};
use option::Some;
use self::test::Bencher;
#[bench]
fn bench_as_ref(b: &mut Bencher) {
b.iter(|| {
let mut x = 0; let mut y = &mut x as &mut Any;
test::black_box(&mut y);
test::black_box(y.as_ref::<int>() == Some(&0));
});
}
}
|
impl<T: 'static> Any for T {
/// Get the `TypeId` of `self`
fn get_type_id(&self) -> TypeId {
|
random_line_split
|
any.rs
|
// 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.
//! Traits for dynamic typing of any type (through runtime reflection)
//!
//! This module implements the `Any` trait, which enables dynamic typing
//! of any type, through runtime reflection.
//!
//! `Any` itself can be used to get a `TypeId`, and has more features when used as a trait object.
//! As `&Any` (a borrowed trait object), it has the `is` and `as_ref` methods, to test if the
//! contained value is of a given type, and to get a reference to the inner value as a type. As
//! `&mut Any`, there is also the `as_mut` method, for getting a mutable reference to the inner
//! value. `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the object. See
//! the extension traits (`*Ext`) for the full details.
use cast::{transmute, transmute_copy};
use option::{Option, Some, None};
use owned::Box;
use raw::TraitObject;
use result::{Result, Ok, Err};
use intrinsics::TypeId;
use intrinsics;
/// A type with no inhabitants
pub enum
|
{ }
///////////////////////////////////////////////////////////////////////////////
// Any trait
///////////////////////////////////////////////////////////////////////////////
/// The `Any` trait is implemented by all types, and can be used as a trait object
/// for dynamic typing
pub trait Any {
/// Get the `TypeId` of `self`
fn get_type_id(&self) -> TypeId;
}
impl<T:'static> Any for T {
/// Get the `TypeId` of `self`
fn get_type_id(&self) -> TypeId {
TypeId::of::<T>()
}
}
///////////////////////////////////////////////////////////////////////////////
// Extension methods for Any trait objects.
// Implemented as three extension traits so that the methods can be generic.
///////////////////////////////////////////////////////////////////////////////
/// Extension methods for a referenced `Any` trait object
pub trait AnyRefExt<'a> {
/// Returns true if the boxed type is the same as `T`
fn is<T:'static>(self) -> bool;
/// Returns some reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
fn as_ref<T:'static>(self) -> Option<&'a T>;
}
impl<'a> AnyRefExt<'a> for &'a Any {
#[inline]
fn is<T:'static>(self) -> bool {
// Get TypeId of the type this function is instantiated with
let t = TypeId::of::<T>();
// Get TypeId of the type in the trait object
let boxed = self.get_type_id();
// Compare both TypeIds on equality
t == boxed
}
#[inline]
fn as_ref<T:'static>(self) -> Option<&'a T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
}
/// Extension methods for a mutable referenced `Any` trait object
pub trait AnyMutRefExt<'a> {
/// Returns some mutable reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
fn as_mut<T:'static>(self) -> Option<&'a mut T>;
}
impl<'a> AnyMutRefExt<'a> for &'a mut Any {
#[inline]
fn as_mut<T:'static>(self) -> Option<&'a mut T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
}
/// Extension methods for an owning `Any` trait object
pub trait AnyOwnExt {
/// Returns the boxed value if it is of type `T`, or
/// `Err(Self)` if it isn't.
fn move<T:'static>(self) -> Result<Box<T>, Self>;
}
impl AnyOwnExt for Box<Any> {
#[inline]
fn move<T:'static>(self) -> Result<Box<T>, Box<Any>> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute_copy(&self);
// Prevent destructor on self being run
intrinsics::forget(self);
// Extract the data pointer
Ok(transmute(to.data))
}
} else {
Err(self)
}
}
}
#[cfg(test)]
mod tests {
use prelude::*;
use super::*;
use owned::Box;
use realstd::str::StrAllocating;
#[deriving(Eq, Show)]
struct Test;
static TEST: &'static str = "Test";
#[test]
fn any_referenced() {
let (a, b, c) = (&5u as &Any, &TEST as &Any, &Test as &Any);
assert!(a.is::<uint>());
assert!(!b.is::<uint>());
assert!(!c.is::<uint>());
assert!(!a.is::<&'static str>());
assert!(b.is::<&'static str>());
assert!(!c.is::<&'static str>());
assert!(!a.is::<Test>());
assert!(!b.is::<Test>());
assert!(c.is::<Test>());
}
#[test]
fn any_owning() {
let (a, b, c) = (box 5u as Box<Any>, box TEST as Box<Any>, box Test as Box<Any>);
assert!(a.is::<uint>());
assert!(!b.is::<uint>());
assert!(!c.is::<uint>());
assert!(!a.is::<&'static str>());
assert!(b.is::<&'static str>());
assert!(!c.is::<&'static str>());
assert!(!a.is::<Test>());
assert!(!b.is::<Test>());
assert!(c.is::<Test>());
}
#[test]
fn any_as_ref() {
let a = &5u as &Any;
match a.as_ref::<uint>() {
Some(&5) => {}
x => fail!("Unexpected value {:?}", x)
}
match a.as_ref::<Test>() {
None => {}
x => fail!("Unexpected value {:?}", x)
}
}
#[test]
fn any_as_mut() {
let mut a = 5u;
let mut b = box 7u;
let a_r = &mut a as &mut Any;
let tmp: &mut uint = b;
let b_r = tmp as &mut Any;
match a_r.as_mut::<uint>() {
Some(x) => {
assert_eq!(*x, 5u);
*x = 612;
}
x => fail!("Unexpected value {:?}", x)
}
match b_r.as_mut::<uint>() {
Some(x) => {
assert_eq!(*x, 7u);
*x = 413;
}
x => fail!("Unexpected value {:?}", x)
}
match a_r.as_mut::<Test>() {
None => (),
x => fail!("Unexpected value {:?}", x)
}
match b_r.as_mut::<Test>() {
None => (),
x => fail!("Unexpected value {:?}", x)
}
match a_r.as_mut::<uint>() {
Some(&612) => {}
x => fail!("Unexpected value {:?}", x)
}
match b_r.as_mut::<uint>() {
Some(&413) => {}
x => fail!("Unexpected value {:?}", x)
}
}
#[test]
fn any_move() {
let a = box 8u as Box<Any>;
let b = box Test as Box<Any>;
match a.move::<uint>() {
Ok(a) => { assert_eq!(a, box 8u); }
Err(..) => fail!()
}
match b.move::<Test>() {
Ok(a) => { assert_eq!(a, box Test); }
Err(..) => fail!()
}
let a = box 8u as Box<Any>;
let b = box Test as Box<Any>;
assert!(a.move::<Box<Test>>().is_err());
assert!(b.move::<Box<uint>>().is_err());
}
#[test]
fn test_show() {
let a = box 8u as Box<::realcore::any::Any>;
let b = box Test as Box<::realcore::any::Any>;
assert_eq!(format!("{}", a), "Box<Any>".to_owned());
assert_eq!(format!("{}", b), "Box<Any>".to_owned());
let a = &8u as &::realcore::any::Any;
let b = &Test as &::realcore::any::Any;
assert_eq!(format!("{}", a), "&Any".to_owned());
assert_eq!(format!("{}", b), "&Any".to_owned());
}
}
#[cfg(test)]
mod bench {
extern crate test;
use any::{Any, AnyRefExt};
use option::Some;
use self::test::Bencher;
#[bench]
fn bench_as_ref(b: &mut Bencher) {
b.iter(|| {
let mut x = 0; let mut y = &mut x as &mut Any;
test::black_box(&mut y);
test::black_box(y.as_ref::<int>() == Some(&0));
});
}
}
|
Void
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.