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 |
---|---|---|---|---|
levenshtein.rs
|
// Copyright (c) 2016. See AUTHORS file.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use utils;
/// Calculates the Levenshtein distance between two strings.
///
/// # Levenshtein distance
/// The [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) is the number of per-character changes (insertion, deletion & substitution)
/// that are neccessary to convert one string into annother.
/// This implementation does fully support unicode strings.
///
/// ## Complexity
/// m := len(s) + 1
/// n := len(t) + 1
///
/// Time complexity: O(mn)
/// Space complexity: O(mn)
///
/// ## Examples
/// ```
/// use distance::*;
///
/// // Levenshtein distance
/// let distance = levenshtein("hannah", "hanna");
/// assert_eq!(1, distance);
/// ```
///
pub fn levenshtein(s: &str, t: &str) -> usize {
// get length of unicode chars
let len_s = s.chars().count();
let len_t = t.chars().count();
// initialize the matrix
let mut mat: Vec<Vec<usize>> = vec![vec![0; len_t + 1]; len_s + 1];
for i in 1..(len_s + 1) {
mat[i][0] = i;
}
for i in 1..(len_t + 1) {
mat[0][i] = i;
}
// apply edit operations
for (i, s_char) in s.chars().enumerate() {
for (j, t_char) in t.chars().enumerate() {
let substitution = if s_char == t_char {0} else {1};
mat[i+1][j+1] = utils::min3(
mat[i][j+1] + 1, // deletion
mat[i+1][j] + 1, // insertion
mat[i][j] + substitution // substitution
);
}
}
return mat[len_s][len_t];
}
#[cfg(test)]
mod tests {
use super::levenshtein;
#[test]
fn basic() {
assert_eq!(3, levenshtein("kitten", "sitting"));
assert_eq!(2, levenshtein("book", "back"));
assert_eq!(5, levenshtein("table", "dinner"));
assert_eq!(2, levenshtein("person", "pardon"));
assert_eq!(1, levenshtein("person", "persons"));
}
#[test]
fn equal() {
assert_eq!(0, levenshtein("kitten", "kitten"));
assert_eq!(0, levenshtein("a", "a"));
}
#[test]
fn cases() {
assert_eq!(1, levenshtein("Hello", "hello"));
assert_eq!(1, levenshtein("World", "world"));
}
#[test]
fn empty()
|
#[test]
fn unicode() {
assert_eq!(2, levenshtein("SpΓ€Γe", "SpaΓ"));
assert_eq!(5, levenshtein("γγγγͺγ", "γγγ«γ‘γ―"));
assert_eq!(1, levenshtein("γγγγͺγ", "γγγγͺγ"));
assert_eq!(4, levenshtein("γγγ«γ‘γ―", "γγγ«γ‘γ― abc"));
assert_eq!(1, levenshtein("ΰΌΰΌΚ", "ΰΌΛ₯Κ"));
}
}
|
{
assert_eq!(4, levenshtein("book", ""));
assert_eq!(4, levenshtein("", "book"));
assert_eq!(0, levenshtein("", ""));
}
|
identifier_body
|
levenshtein.rs
|
// Copyright (c) 2016. See AUTHORS file.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use utils;
/// Calculates the Levenshtein distance between two strings.
///
/// # Levenshtein distance
/// The [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) is the number of per-character changes (insertion, deletion & substitution)
/// that are neccessary to convert one string into annother.
/// This implementation does fully support unicode strings.
///
/// ## Complexity
/// m := len(s) + 1
/// n := len(t) + 1
///
/// Time complexity: O(mn)
/// Space complexity: O(mn)
///
/// ## Examples
/// ```
/// use distance::*;
///
/// // Levenshtein distance
/// let distance = levenshtein("hannah", "hanna");
/// assert_eq!(1, distance);
/// ```
///
pub fn levenshtein(s: &str, t: &str) -> usize {
// get length of unicode chars
let len_s = s.chars().count();
let len_t = t.chars().count();
// initialize the matrix
let mut mat: Vec<Vec<usize>> = vec![vec![0; len_t + 1]; len_s + 1];
for i in 1..(len_s + 1) {
mat[i][0] = i;
}
for i in 1..(len_t + 1) {
mat[0][i] = i;
}
// apply edit operations
for (i, s_char) in s.chars().enumerate() {
for (j, t_char) in t.chars().enumerate() {
let substitution = if s_char == t_char
|
else {1};
mat[i+1][j+1] = utils::min3(
mat[i][j+1] + 1, // deletion
mat[i+1][j] + 1, // insertion
mat[i][j] + substitution // substitution
);
}
}
return mat[len_s][len_t];
}
#[cfg(test)]
mod tests {
use super::levenshtein;
#[test]
fn basic() {
assert_eq!(3, levenshtein("kitten", "sitting"));
assert_eq!(2, levenshtein("book", "back"));
assert_eq!(5, levenshtein("table", "dinner"));
assert_eq!(2, levenshtein("person", "pardon"));
assert_eq!(1, levenshtein("person", "persons"));
}
#[test]
fn equal() {
assert_eq!(0, levenshtein("kitten", "kitten"));
assert_eq!(0, levenshtein("a", "a"));
}
#[test]
fn cases() {
assert_eq!(1, levenshtein("Hello", "hello"));
assert_eq!(1, levenshtein("World", "world"));
}
#[test]
fn empty() {
assert_eq!(4, levenshtein("book", ""));
assert_eq!(4, levenshtein("", "book"));
assert_eq!(0, levenshtein("", ""));
}
#[test]
fn unicode() {
assert_eq!(2, levenshtein("SpΓ€Γe", "SpaΓ"));
assert_eq!(5, levenshtein("γγγγͺγ", "γγγ«γ‘γ―"));
assert_eq!(1, levenshtein("γγγγͺγ", "γγγγͺγ"));
assert_eq!(4, levenshtein("γγγ«γ‘γ―", "γγγ«γ‘γ― abc"));
assert_eq!(1, levenshtein("ΰΌΰΌΚ", "ΰΌΛ₯Κ"));
}
}
|
{0}
|
conditional_block
|
levenshtein.rs
|
// Copyright (c) 2016. See AUTHORS file.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use utils;
/// Calculates the Levenshtein distance between two strings.
///
/// # Levenshtein distance
/// The [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) is the number of per-character changes (insertion, deletion & substitution)
/// that are neccessary to convert one string into annother.
/// This implementation does fully support unicode strings.
///
/// ## Complexity
/// m := len(s) + 1
/// n := len(t) + 1
///
/// Time complexity: O(mn)
/// Space complexity: O(mn)
///
/// ## Examples
/// ```
/// use distance::*;
///
/// // Levenshtein distance
/// let distance = levenshtein("hannah", "hanna");
/// assert_eq!(1, distance);
/// ```
///
pub fn levenshtein(s: &str, t: &str) -> usize {
// get length of unicode chars
let len_s = s.chars().count();
let len_t = t.chars().count();
// initialize the matrix
let mut mat: Vec<Vec<usize>> = vec![vec![0; len_t + 1]; len_s + 1];
for i in 1..(len_s + 1) {
mat[i][0] = i;
}
for i in 1..(len_t + 1) {
mat[0][i] = i;
}
// apply edit operations
for (i, s_char) in s.chars().enumerate() {
for (j, t_char) in t.chars().enumerate() {
let substitution = if s_char == t_char {0} else {1};
mat[i+1][j+1] = utils::min3(
mat[i][j+1] + 1, // deletion
mat[i+1][j] + 1, // insertion
mat[i][j] + substitution // substitution
);
}
}
return mat[len_s][len_t];
}
#[cfg(test)]
mod tests {
use super::levenshtein;
#[test]
fn basic() {
assert_eq!(3, levenshtein("kitten", "sitting"));
assert_eq!(2, levenshtein("book", "back"));
assert_eq!(5, levenshtein("table", "dinner"));
assert_eq!(2, levenshtein("person", "pardon"));
assert_eq!(1, levenshtein("person", "persons"));
}
#[test]
fn
|
() {
assert_eq!(0, levenshtein("kitten", "kitten"));
assert_eq!(0, levenshtein("a", "a"));
}
#[test]
fn cases() {
assert_eq!(1, levenshtein("Hello", "hello"));
assert_eq!(1, levenshtein("World", "world"));
}
#[test]
fn empty() {
assert_eq!(4, levenshtein("book", ""));
assert_eq!(4, levenshtein("", "book"));
assert_eq!(0, levenshtein("", ""));
}
#[test]
fn unicode() {
assert_eq!(2, levenshtein("SpΓ€Γe", "SpaΓ"));
assert_eq!(5, levenshtein("γγγγͺγ", "γγγ«γ‘γ―"));
assert_eq!(1, levenshtein("γγγγͺγ", "γγγγͺγ"));
assert_eq!(4, levenshtein("γγγ«γ‘γ―", "γγγ«γ‘γ― abc"));
assert_eq!(1, levenshtein("ΰΌΰΌΚ", "ΰΌΛ₯Κ"));
}
}
|
equal
|
identifier_name
|
mod.rs
|
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Tracks rumors for distribution.
//!
//! Each rumor is represented by a `RumorKey`, which has a unique key and a "kind", which
//! represents what "kind" of rumor it is (for example, a "member").
//!
//! New rumors need to implement the `From` trait for `RumorKey`, and then can track the arrival of
//! new rumors, and dispatch them according to their `kind`.
pub mod dat_file;
pub mod departure;
pub mod heat;
pub mod election;
pub mod service;
pub mod service_config;
pub mod service_file;
pub use self::election::{Election, ElectionUpdate};
pub use self::service::Service;
pub use self::service_config::ServiceConfig;
pub use self::service_file::ServiceFile;
pub use self::departure::Departure;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::default::Default;
use std::ops::Deref;
use std::result;
use std::sync::{Arc, RwLock};
use std::sync::atomic::{AtomicUsize, Ordering};
use serde::{Serialize, Serializer};
use serde::ser::SerializeStruct;
use message::swim::Rumor_Type;
use error::{Error, Result};
/// The description of a `RumorKey`.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct RumorKey {
pub kind: Rumor_Type,
pub id: String,
pub key: String,
}
impl RumorKey {
pub fn new<A, B>(kind: Rumor_Type, id: A, key: B) -> RumorKey
where
A: ToString,
B: ToString,
{
RumorKey {
kind: kind,
id: id.to_string(),
key: key.to_string(),
}
}
pub fn key(&self) -> String {
if self.key.len() > 0 {
format!("{}-{}", self.id, self.key)
} else {
format!("{}", self.id)
}
}
}
/// A representation of a Rumor; implemented by all the concrete types we share as rumors. The
/// exception is the Membership rumor, since it's not actually a rumor in the same vein.
pub trait Rumor: Serialize + Sized {
fn from_bytes(&[u8]) -> Result<Self>;
fn kind(&self) -> Rumor_Type;
fn key(&self) -> &str;
fn id(&self) -> &str;
fn merge(&mut self, other: Self) -> bool;
fn write_to_bytes(&self) -> Result<Vec<u8>>;
}
impl<'a, T: Rumor> From<&'a T> for RumorKey {
fn from(rumor: &'a T) -> RumorKey {
RumorKey::new(rumor.kind(), rumor.id(), rumor.key())
}
}
/// Storage for Rumors. It takes a rumor and stores it according to the member that produced it,
/// and the service group it is related to.
///
/// Generic over the type of rumor it stores.
#[derive(Debug, Clone)]
pub struct RumorStore<T: Rumor> {
pub list: Arc<RwLock<HashMap<String, HashMap<String, T>>>>,
update_counter: Arc<AtomicUsize>,
}
impl<T: Rumor> Default for RumorStore<T> {
fn default() -> RumorStore<T> {
RumorStore {
list: Arc::new(RwLock::new(HashMap::new())),
update_counter: Arc::new(AtomicUsize::new(0)),
}
}
}
impl<T: Rumor> Deref for RumorStore<T> {
type Target = RwLock<HashMap<String, HashMap<String, T>>>;
fn deref(&self) -> &Self::Target {
&*self.list
}
}
impl<T: Rumor> Serialize for RumorStore<T> {
fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut strukt = serializer.serialize_struct("rumor_store", 2)?;
strukt.serialize_field("list", &*(self.list.read().unwrap()))?;
strukt.serialize_field("update_counter", &self.get_update_counter())?;
strukt.end()
}
}
impl<T: Rumor> RumorStore<T> {
/// Create a new RumorStore for the given type. Allows you to initialize the counter to a
/// pre-set value. Useful mainly in testing.
pub fn new(counter: usize) -> RumorStore<T> {
RumorStore {
update_counter: Arc::new(AtomicUsize::new(counter)),
..Default::default()
}
}
/// Clear all rumors and reset update counter of RumorStore.
pub fn clear(&self) -> usize {
let mut list = self.list.write().expect("Rumor store lock poisoned");
list.clear();
self.update_counter.swap(0, Ordering::Relaxed)
}
pub fn get_update_counter(&self) -> usize {
self.update_counter.load(Ordering::Relaxed)
}
/// Returns the count of all rumors in this RumorStore.
pub fn len(&self) -> usize {
self.list
.read()
.expect("Rumor store lock poisoned")
.values()
.map(|member| member.len())
.sum()
}
/// Returns the count of all rumors in the rumor store for the given member's key.
pub fn len_for_key(&self, key: &str) -> usize {
let list = self.list.read().expect("Rumor store lock poisoned");
list.get(key).map_or(0, |r| r.len())
}
/// Insert a rumor into the Rumor Store. Returns true if the value didn't exist or if it was
/// mutated; if nothing changed, returns false.
pub fn insert(&self, rumor: T) -> bool {
let mut list = self.list.write().expect("Rumor store lock poisoned");
let rumors = list.entry(String::from(rumor.key()))
.or_insert(HashMap::new());
// Result reveals if there was a change so we can increment the counter if needed.
let result = match rumors.entry(rumor.id().into()) {
Entry::Occupied(mut entry) => entry.get_mut().merge(rumor),
Entry::Vacant(entry) => {
entry.insert(rumor);
true
}
};
if result {
self.increment_update_counter();
}
result
}
pub fn remove(&self, key: &str, id: &str) {
|
pub fn with_keys<F>(&self, mut with_closure: F)
where
F: FnMut((&String, &HashMap<String, T>)),
{
let list = self.list.read().expect("Rumor store lock poisoned");
for x in list.iter() {
with_closure(x);
}
}
pub fn with_rumors<F>(&self, key: &str, mut with_closure: F)
where
F: FnMut(&T),
{
let list = self.list.read().expect("Rumor store lock poisoned");
if list.contains_key(key) {
for x in list.get(key).unwrap().values() {
with_closure(x);
}
}
}
pub fn with_rumor<F>(&self, key: &str, member_id: &str, mut with_closure: F)
where
F: FnMut(Option<&T>),
{
let list = self.list.read().expect("Rumor store lock poisoned");
with_closure(list.get(key).and_then(|r| r.get(member_id)));
}
pub fn write_to_bytes(&self, key: &str, member_id: &str) -> Result<Vec<u8>> {
let list = self.list.read().expect("Rumor store lock poisoned");
match list.get(key).and_then(|l| l.get(member_id)) {
Some(rumor) => rumor.write_to_bytes(),
None => Err(Error::NonExistentRumor(
String::from(member_id),
String::from(key),
)),
}
}
pub fn contains_rumor(&self, key: &str, id: &str) -> bool {
let list = self.list.read().expect("Rumor store lock poisoned");
match list.get(key).and_then(|l| l.get(id)) {
Some(_) => true,
None => false,
}
}
/// Increment the update counter for this store.
///
/// We don't care if this repeats - it just needs to be unique for any given two states, which
/// it will be.
fn increment_update_counter(&self) {
self.update_counter.fetch_add(1, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use uuid::Uuid;
use rumor::Rumor;
use message::swim::Rumor_Type;
use error::Result;
#[derive(Clone, Debug, Serialize)]
struct FakeRumor {
pub id: String,
pub key: String,
}
impl Default for FakeRumor {
fn default() -> FakeRumor {
FakeRumor {
id: format!("{}", Uuid::new_v4().simple()),
key: String::from("fakerton"),
}
}
}
#[derive(Clone, Debug, Serialize)]
struct TrumpRumor {
pub id: String,
pub key: String,
}
impl Rumor for FakeRumor {
fn from_bytes(_bytes: &[u8]) -> Result<Self> {
Ok(FakeRumor::default())
}
fn kind(&self) -> Rumor_Type {
Rumor_Type::Fake
}
fn key(&self) -> &str {
&self.key
}
fn id(&self) -> &str {
&self.id
}
fn merge(&mut self, mut _other: FakeRumor) -> bool {
false
}
fn write_to_bytes(&self) -> Result<Vec<u8>> {
Ok(Vec::from(format!("{}-{}", self.id, self.key).as_bytes()))
}
}
impl Default for TrumpRumor {
fn default() -> TrumpRumor {
TrumpRumor {
id: format!("{}", Uuid::new_v4().simple()),
key: String::from("fakerton"),
}
}
}
impl Rumor for TrumpRumor {
fn from_bytes(_bytes: &[u8]) -> Result<Self> {
Ok(TrumpRumor::default())
}
fn kind(&self) -> Rumor_Type {
Rumor_Type::Fake2
}
fn key(&self) -> &str {
&self.key
}
fn id(&self) -> &str {
&self.id
}
fn merge(&mut self, mut _other: TrumpRumor) -> bool {
false
}
fn write_to_bytes(&self) -> Result<Vec<u8>> {
Ok(Vec::from(format!("{}-{}", self.id, self.key).as_bytes()))
}
}
mod rumor_store {
use super::FakeRumor;
use rumor::RumorStore;
use rumor::Rumor;
use std::usize;
fn create_rumor_store() -> RumorStore<FakeRumor> {
RumorStore::default()
}
#[test]
fn update_counter() {
let rs = create_rumor_store();
rs.increment_update_counter();
assert_eq!(rs.get_update_counter(), 1);
}
#[test]
fn update_counter_overflows_safely() {
let rs: RumorStore<FakeRumor> = RumorStore::new(usize::MAX);
rs.increment_update_counter();
assert_eq!(rs.get_update_counter(), 0);
}
#[test]
fn insert_adds_rumor_when_empty() {
let rs = create_rumor_store();
let f = FakeRumor::default();
assert!(rs.insert(f));
assert_eq!(rs.get_update_counter(), 1);
}
#[test]
fn insert_adds_multiple_rumors_for_same_key() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let key = String::from(f1.key());
let f1_id = String::from(f1.id());
let f2 = FakeRumor::default();
let f2_id = String::from(f2.id());
assert!(rs.insert(f1));
assert!(rs.insert(f2));
assert_eq!(rs.list.read().unwrap().len(), 1);
assert_eq!(
rs.list
.read()
.unwrap()
.get(&key)
.unwrap()
.get(&f1_id)
.unwrap()
.id,
f1_id
);
assert_eq!(
rs.list
.read()
.unwrap()
.get(&key)
.unwrap()
.get(&f2_id)
.unwrap()
.id,
f2_id
);
}
#[test]
fn insert_adds_multiple_members() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let key = String::from(f1.key());
let f2 = FakeRumor::default();
assert!(rs.insert(f1));
assert!(rs.insert(f2));
assert_eq!(rs.list.read().unwrap().get(&key).unwrap().len(), 2);
}
#[test]
fn insert_returns_false_on_no_changes() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let f2 = f1.clone();
assert!(rs.insert(f1));
assert_eq!(rs.insert(f2), false);
}
#[test]
fn with_rumor_calls_closure_with_rumor() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let member_id = f1.id.clone();
let key = f1.key.clone();
rs.insert(f1);
rs.with_rumor(&key, &member_id, |o| assert_eq!(o.unwrap().id, member_id));
}
#[test]
fn with_rumor_calls_closure_with_none_if_rumor_missing() {
let rs = create_rumor_store();
rs.with_rumor("bar", "foo", |o| assert!(o.is_none()));
}
}
}
|
let mut list = self.list.write().expect("Rumor store lock poisoned");
list.get_mut(key).and_then(|r| r.remove(id));
}
|
random_line_split
|
mod.rs
|
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Tracks rumors for distribution.
//!
//! Each rumor is represented by a `RumorKey`, which has a unique key and a "kind", which
//! represents what "kind" of rumor it is (for example, a "member").
//!
//! New rumors need to implement the `From` trait for `RumorKey`, and then can track the arrival of
//! new rumors, and dispatch them according to their `kind`.
pub mod dat_file;
pub mod departure;
pub mod heat;
pub mod election;
pub mod service;
pub mod service_config;
pub mod service_file;
pub use self::election::{Election, ElectionUpdate};
pub use self::service::Service;
pub use self::service_config::ServiceConfig;
pub use self::service_file::ServiceFile;
pub use self::departure::Departure;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::default::Default;
use std::ops::Deref;
use std::result;
use std::sync::{Arc, RwLock};
use std::sync::atomic::{AtomicUsize, Ordering};
use serde::{Serialize, Serializer};
use serde::ser::SerializeStruct;
use message::swim::Rumor_Type;
use error::{Error, Result};
/// The description of a `RumorKey`.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct RumorKey {
pub kind: Rumor_Type,
pub id: String,
pub key: String,
}
impl RumorKey {
pub fn new<A, B>(kind: Rumor_Type, id: A, key: B) -> RumorKey
where
A: ToString,
B: ToString,
{
RumorKey {
kind: kind,
id: id.to_string(),
key: key.to_string(),
}
}
pub fn key(&self) -> String {
if self.key.len() > 0 {
format!("{}-{}", self.id, self.key)
} else {
format!("{}", self.id)
}
}
}
/// A representation of a Rumor; implemented by all the concrete types we share as rumors. The
/// exception is the Membership rumor, since it's not actually a rumor in the same vein.
pub trait Rumor: Serialize + Sized {
fn from_bytes(&[u8]) -> Result<Self>;
fn kind(&self) -> Rumor_Type;
fn key(&self) -> &str;
fn id(&self) -> &str;
fn merge(&mut self, other: Self) -> bool;
fn write_to_bytes(&self) -> Result<Vec<u8>>;
}
impl<'a, T: Rumor> From<&'a T> for RumorKey {
fn from(rumor: &'a T) -> RumorKey {
RumorKey::new(rumor.kind(), rumor.id(), rumor.key())
}
}
/// Storage for Rumors. It takes a rumor and stores it according to the member that produced it,
/// and the service group it is related to.
///
/// Generic over the type of rumor it stores.
#[derive(Debug, Clone)]
pub struct RumorStore<T: Rumor> {
pub list: Arc<RwLock<HashMap<String, HashMap<String, T>>>>,
update_counter: Arc<AtomicUsize>,
}
impl<T: Rumor> Default for RumorStore<T> {
fn default() -> RumorStore<T> {
RumorStore {
list: Arc::new(RwLock::new(HashMap::new())),
update_counter: Arc::new(AtomicUsize::new(0)),
}
}
}
impl<T: Rumor> Deref for RumorStore<T> {
type Target = RwLock<HashMap<String, HashMap<String, T>>>;
fn deref(&self) -> &Self::Target {
&*self.list
}
}
impl<T: Rumor> Serialize for RumorStore<T> {
fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut strukt = serializer.serialize_struct("rumor_store", 2)?;
strukt.serialize_field("list", &*(self.list.read().unwrap()))?;
strukt.serialize_field("update_counter", &self.get_update_counter())?;
strukt.end()
}
}
impl<T: Rumor> RumorStore<T> {
/// Create a new RumorStore for the given type. Allows you to initialize the counter to a
/// pre-set value. Useful mainly in testing.
pub fn new(counter: usize) -> RumorStore<T> {
RumorStore {
update_counter: Arc::new(AtomicUsize::new(counter)),
..Default::default()
}
}
/// Clear all rumors and reset update counter of RumorStore.
pub fn clear(&self) -> usize {
let mut list = self.list.write().expect("Rumor store lock poisoned");
list.clear();
self.update_counter.swap(0, Ordering::Relaxed)
}
pub fn get_update_counter(&self) -> usize {
self.update_counter.load(Ordering::Relaxed)
}
/// Returns the count of all rumors in this RumorStore.
pub fn len(&self) -> usize {
self.list
.read()
.expect("Rumor store lock poisoned")
.values()
.map(|member| member.len())
.sum()
}
/// Returns the count of all rumors in the rumor store for the given member's key.
pub fn len_for_key(&self, key: &str) -> usize {
let list = self.list.read().expect("Rumor store lock poisoned");
list.get(key).map_or(0, |r| r.len())
}
/// Insert a rumor into the Rumor Store. Returns true if the value didn't exist or if it was
/// mutated; if nothing changed, returns false.
pub fn insert(&self, rumor: T) -> bool {
let mut list = self.list.write().expect("Rumor store lock poisoned");
let rumors = list.entry(String::from(rumor.key()))
.or_insert(HashMap::new());
// Result reveals if there was a change so we can increment the counter if needed.
let result = match rumors.entry(rumor.id().into()) {
Entry::Occupied(mut entry) => entry.get_mut().merge(rumor),
Entry::Vacant(entry) => {
entry.insert(rumor);
true
}
};
if result {
self.increment_update_counter();
}
result
}
pub fn remove(&self, key: &str, id: &str) {
let mut list = self.list.write().expect("Rumor store lock poisoned");
list.get_mut(key).and_then(|r| r.remove(id));
}
pub fn with_keys<F>(&self, mut with_closure: F)
where
F: FnMut((&String, &HashMap<String, T>)),
{
let list = self.list.read().expect("Rumor store lock poisoned");
for x in list.iter() {
with_closure(x);
}
}
pub fn with_rumors<F>(&self, key: &str, mut with_closure: F)
where
F: FnMut(&T),
{
let list = self.list.read().expect("Rumor store lock poisoned");
if list.contains_key(key) {
for x in list.get(key).unwrap().values() {
with_closure(x);
}
}
}
pub fn
|
<F>(&self, key: &str, member_id: &str, mut with_closure: F)
where
F: FnMut(Option<&T>),
{
let list = self.list.read().expect("Rumor store lock poisoned");
with_closure(list.get(key).and_then(|r| r.get(member_id)));
}
pub fn write_to_bytes(&self, key: &str, member_id: &str) -> Result<Vec<u8>> {
let list = self.list.read().expect("Rumor store lock poisoned");
match list.get(key).and_then(|l| l.get(member_id)) {
Some(rumor) => rumor.write_to_bytes(),
None => Err(Error::NonExistentRumor(
String::from(member_id),
String::from(key),
)),
}
}
pub fn contains_rumor(&self, key: &str, id: &str) -> bool {
let list = self.list.read().expect("Rumor store lock poisoned");
match list.get(key).and_then(|l| l.get(id)) {
Some(_) => true,
None => false,
}
}
/// Increment the update counter for this store.
///
/// We don't care if this repeats - it just needs to be unique for any given two states, which
/// it will be.
fn increment_update_counter(&self) {
self.update_counter.fetch_add(1, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use uuid::Uuid;
use rumor::Rumor;
use message::swim::Rumor_Type;
use error::Result;
#[derive(Clone, Debug, Serialize)]
struct FakeRumor {
pub id: String,
pub key: String,
}
impl Default for FakeRumor {
fn default() -> FakeRumor {
FakeRumor {
id: format!("{}", Uuid::new_v4().simple()),
key: String::from("fakerton"),
}
}
}
#[derive(Clone, Debug, Serialize)]
struct TrumpRumor {
pub id: String,
pub key: String,
}
impl Rumor for FakeRumor {
fn from_bytes(_bytes: &[u8]) -> Result<Self> {
Ok(FakeRumor::default())
}
fn kind(&self) -> Rumor_Type {
Rumor_Type::Fake
}
fn key(&self) -> &str {
&self.key
}
fn id(&self) -> &str {
&self.id
}
fn merge(&mut self, mut _other: FakeRumor) -> bool {
false
}
fn write_to_bytes(&self) -> Result<Vec<u8>> {
Ok(Vec::from(format!("{}-{}", self.id, self.key).as_bytes()))
}
}
impl Default for TrumpRumor {
fn default() -> TrumpRumor {
TrumpRumor {
id: format!("{}", Uuid::new_v4().simple()),
key: String::from("fakerton"),
}
}
}
impl Rumor for TrumpRumor {
fn from_bytes(_bytes: &[u8]) -> Result<Self> {
Ok(TrumpRumor::default())
}
fn kind(&self) -> Rumor_Type {
Rumor_Type::Fake2
}
fn key(&self) -> &str {
&self.key
}
fn id(&self) -> &str {
&self.id
}
fn merge(&mut self, mut _other: TrumpRumor) -> bool {
false
}
fn write_to_bytes(&self) -> Result<Vec<u8>> {
Ok(Vec::from(format!("{}-{}", self.id, self.key).as_bytes()))
}
}
mod rumor_store {
use super::FakeRumor;
use rumor::RumorStore;
use rumor::Rumor;
use std::usize;
fn create_rumor_store() -> RumorStore<FakeRumor> {
RumorStore::default()
}
#[test]
fn update_counter() {
let rs = create_rumor_store();
rs.increment_update_counter();
assert_eq!(rs.get_update_counter(), 1);
}
#[test]
fn update_counter_overflows_safely() {
let rs: RumorStore<FakeRumor> = RumorStore::new(usize::MAX);
rs.increment_update_counter();
assert_eq!(rs.get_update_counter(), 0);
}
#[test]
fn insert_adds_rumor_when_empty() {
let rs = create_rumor_store();
let f = FakeRumor::default();
assert!(rs.insert(f));
assert_eq!(rs.get_update_counter(), 1);
}
#[test]
fn insert_adds_multiple_rumors_for_same_key() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let key = String::from(f1.key());
let f1_id = String::from(f1.id());
let f2 = FakeRumor::default();
let f2_id = String::from(f2.id());
assert!(rs.insert(f1));
assert!(rs.insert(f2));
assert_eq!(rs.list.read().unwrap().len(), 1);
assert_eq!(
rs.list
.read()
.unwrap()
.get(&key)
.unwrap()
.get(&f1_id)
.unwrap()
.id,
f1_id
);
assert_eq!(
rs.list
.read()
.unwrap()
.get(&key)
.unwrap()
.get(&f2_id)
.unwrap()
.id,
f2_id
);
}
#[test]
fn insert_adds_multiple_members() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let key = String::from(f1.key());
let f2 = FakeRumor::default();
assert!(rs.insert(f1));
assert!(rs.insert(f2));
assert_eq!(rs.list.read().unwrap().get(&key).unwrap().len(), 2);
}
#[test]
fn insert_returns_false_on_no_changes() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let f2 = f1.clone();
assert!(rs.insert(f1));
assert_eq!(rs.insert(f2), false);
}
#[test]
fn with_rumor_calls_closure_with_rumor() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let member_id = f1.id.clone();
let key = f1.key.clone();
rs.insert(f1);
rs.with_rumor(&key, &member_id, |o| assert_eq!(o.unwrap().id, member_id));
}
#[test]
fn with_rumor_calls_closure_with_none_if_rumor_missing() {
let rs = create_rumor_store();
rs.with_rumor("bar", "foo", |o| assert!(o.is_none()));
}
}
}
|
with_rumor
|
identifier_name
|
mod.rs
|
// Copyright (c) 2016-2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Tracks rumors for distribution.
//!
//! Each rumor is represented by a `RumorKey`, which has a unique key and a "kind", which
//! represents what "kind" of rumor it is (for example, a "member").
//!
//! New rumors need to implement the `From` trait for `RumorKey`, and then can track the arrival of
//! new rumors, and dispatch them according to their `kind`.
pub mod dat_file;
pub mod departure;
pub mod heat;
pub mod election;
pub mod service;
pub mod service_config;
pub mod service_file;
pub use self::election::{Election, ElectionUpdate};
pub use self::service::Service;
pub use self::service_config::ServiceConfig;
pub use self::service_file::ServiceFile;
pub use self::departure::Departure;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::default::Default;
use std::ops::Deref;
use std::result;
use std::sync::{Arc, RwLock};
use std::sync::atomic::{AtomicUsize, Ordering};
use serde::{Serialize, Serializer};
use serde::ser::SerializeStruct;
use message::swim::Rumor_Type;
use error::{Error, Result};
/// The description of a `RumorKey`.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct RumorKey {
pub kind: Rumor_Type,
pub id: String,
pub key: String,
}
impl RumorKey {
pub fn new<A, B>(kind: Rumor_Type, id: A, key: B) -> RumorKey
where
A: ToString,
B: ToString,
{
RumorKey {
kind: kind,
id: id.to_string(),
key: key.to_string(),
}
}
pub fn key(&self) -> String {
if self.key.len() > 0 {
format!("{}-{}", self.id, self.key)
} else {
format!("{}", self.id)
}
}
}
/// A representation of a Rumor; implemented by all the concrete types we share as rumors. The
/// exception is the Membership rumor, since it's not actually a rumor in the same vein.
pub trait Rumor: Serialize + Sized {
fn from_bytes(&[u8]) -> Result<Self>;
fn kind(&self) -> Rumor_Type;
fn key(&self) -> &str;
fn id(&self) -> &str;
fn merge(&mut self, other: Self) -> bool;
fn write_to_bytes(&self) -> Result<Vec<u8>>;
}
impl<'a, T: Rumor> From<&'a T> for RumorKey {
fn from(rumor: &'a T) -> RumorKey {
RumorKey::new(rumor.kind(), rumor.id(), rumor.key())
}
}
/// Storage for Rumors. It takes a rumor and stores it according to the member that produced it,
/// and the service group it is related to.
///
/// Generic over the type of rumor it stores.
#[derive(Debug, Clone)]
pub struct RumorStore<T: Rumor> {
pub list: Arc<RwLock<HashMap<String, HashMap<String, T>>>>,
update_counter: Arc<AtomicUsize>,
}
impl<T: Rumor> Default for RumorStore<T> {
fn default() -> RumorStore<T> {
RumorStore {
list: Arc::new(RwLock::new(HashMap::new())),
update_counter: Arc::new(AtomicUsize::new(0)),
}
}
}
impl<T: Rumor> Deref for RumorStore<T> {
type Target = RwLock<HashMap<String, HashMap<String, T>>>;
fn deref(&self) -> &Self::Target {
&*self.list
}
}
impl<T: Rumor> Serialize for RumorStore<T> {
fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut strukt = serializer.serialize_struct("rumor_store", 2)?;
strukt.serialize_field("list", &*(self.list.read().unwrap()))?;
strukt.serialize_field("update_counter", &self.get_update_counter())?;
strukt.end()
}
}
impl<T: Rumor> RumorStore<T> {
/// Create a new RumorStore for the given type. Allows you to initialize the counter to a
/// pre-set value. Useful mainly in testing.
pub fn new(counter: usize) -> RumorStore<T> {
RumorStore {
update_counter: Arc::new(AtomicUsize::new(counter)),
..Default::default()
}
}
/// Clear all rumors and reset update counter of RumorStore.
pub fn clear(&self) -> usize {
let mut list = self.list.write().expect("Rumor store lock poisoned");
list.clear();
self.update_counter.swap(0, Ordering::Relaxed)
}
pub fn get_update_counter(&self) -> usize {
self.update_counter.load(Ordering::Relaxed)
}
/// Returns the count of all rumors in this RumorStore.
pub fn len(&self) -> usize {
self.list
.read()
.expect("Rumor store lock poisoned")
.values()
.map(|member| member.len())
.sum()
}
/// Returns the count of all rumors in the rumor store for the given member's key.
pub fn len_for_key(&self, key: &str) -> usize {
let list = self.list.read().expect("Rumor store lock poisoned");
list.get(key).map_or(0, |r| r.len())
}
/// Insert a rumor into the Rumor Store. Returns true if the value didn't exist or if it was
/// mutated; if nothing changed, returns false.
pub fn insert(&self, rumor: T) -> bool {
let mut list = self.list.write().expect("Rumor store lock poisoned");
let rumors = list.entry(String::from(rumor.key()))
.or_insert(HashMap::new());
// Result reveals if there was a change so we can increment the counter if needed.
let result = match rumors.entry(rumor.id().into()) {
Entry::Occupied(mut entry) => entry.get_mut().merge(rumor),
Entry::Vacant(entry) => {
entry.insert(rumor);
true
}
};
if result {
self.increment_update_counter();
}
result
}
pub fn remove(&self, key: &str, id: &str) {
let mut list = self.list.write().expect("Rumor store lock poisoned");
list.get_mut(key).and_then(|r| r.remove(id));
}
pub fn with_keys<F>(&self, mut with_closure: F)
where
F: FnMut((&String, &HashMap<String, T>)),
{
let list = self.list.read().expect("Rumor store lock poisoned");
for x in list.iter() {
with_closure(x);
}
}
pub fn with_rumors<F>(&self, key: &str, mut with_closure: F)
where
F: FnMut(&T),
{
let list = self.list.read().expect("Rumor store lock poisoned");
if list.contains_key(key) {
for x in list.get(key).unwrap().values() {
with_closure(x);
}
}
}
pub fn with_rumor<F>(&self, key: &str, member_id: &str, mut with_closure: F)
where
F: FnMut(Option<&T>),
{
let list = self.list.read().expect("Rumor store lock poisoned");
with_closure(list.get(key).and_then(|r| r.get(member_id)));
}
pub fn write_to_bytes(&self, key: &str, member_id: &str) -> Result<Vec<u8>> {
let list = self.list.read().expect("Rumor store lock poisoned");
match list.get(key).and_then(|l| l.get(member_id)) {
Some(rumor) => rumor.write_to_bytes(),
None => Err(Error::NonExistentRumor(
String::from(member_id),
String::from(key),
)),
}
}
pub fn contains_rumor(&self, key: &str, id: &str) -> bool {
let list = self.list.read().expect("Rumor store lock poisoned");
match list.get(key).and_then(|l| l.get(id)) {
Some(_) => true,
None => false,
}
}
/// Increment the update counter for this store.
///
/// We don't care if this repeats - it just needs to be unique for any given two states, which
/// it will be.
fn increment_update_counter(&self) {
self.update_counter.fetch_add(1, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use uuid::Uuid;
use rumor::Rumor;
use message::swim::Rumor_Type;
use error::Result;
#[derive(Clone, Debug, Serialize)]
struct FakeRumor {
pub id: String,
pub key: String,
}
impl Default for FakeRumor {
fn default() -> FakeRumor {
FakeRumor {
id: format!("{}", Uuid::new_v4().simple()),
key: String::from("fakerton"),
}
}
}
#[derive(Clone, Debug, Serialize)]
struct TrumpRumor {
pub id: String,
pub key: String,
}
impl Rumor for FakeRumor {
fn from_bytes(_bytes: &[u8]) -> Result<Self> {
Ok(FakeRumor::default())
}
fn kind(&self) -> Rumor_Type
|
fn key(&self) -> &str {
&self.key
}
fn id(&self) -> &str {
&self.id
}
fn merge(&mut self, mut _other: FakeRumor) -> bool {
false
}
fn write_to_bytes(&self) -> Result<Vec<u8>> {
Ok(Vec::from(format!("{}-{}", self.id, self.key).as_bytes()))
}
}
impl Default for TrumpRumor {
fn default() -> TrumpRumor {
TrumpRumor {
id: format!("{}", Uuid::new_v4().simple()),
key: String::from("fakerton"),
}
}
}
impl Rumor for TrumpRumor {
fn from_bytes(_bytes: &[u8]) -> Result<Self> {
Ok(TrumpRumor::default())
}
fn kind(&self) -> Rumor_Type {
Rumor_Type::Fake2
}
fn key(&self) -> &str {
&self.key
}
fn id(&self) -> &str {
&self.id
}
fn merge(&mut self, mut _other: TrumpRumor) -> bool {
false
}
fn write_to_bytes(&self) -> Result<Vec<u8>> {
Ok(Vec::from(format!("{}-{}", self.id, self.key).as_bytes()))
}
}
mod rumor_store {
use super::FakeRumor;
use rumor::RumorStore;
use rumor::Rumor;
use std::usize;
fn create_rumor_store() -> RumorStore<FakeRumor> {
RumorStore::default()
}
#[test]
fn update_counter() {
let rs = create_rumor_store();
rs.increment_update_counter();
assert_eq!(rs.get_update_counter(), 1);
}
#[test]
fn update_counter_overflows_safely() {
let rs: RumorStore<FakeRumor> = RumorStore::new(usize::MAX);
rs.increment_update_counter();
assert_eq!(rs.get_update_counter(), 0);
}
#[test]
fn insert_adds_rumor_when_empty() {
let rs = create_rumor_store();
let f = FakeRumor::default();
assert!(rs.insert(f));
assert_eq!(rs.get_update_counter(), 1);
}
#[test]
fn insert_adds_multiple_rumors_for_same_key() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let key = String::from(f1.key());
let f1_id = String::from(f1.id());
let f2 = FakeRumor::default();
let f2_id = String::from(f2.id());
assert!(rs.insert(f1));
assert!(rs.insert(f2));
assert_eq!(rs.list.read().unwrap().len(), 1);
assert_eq!(
rs.list
.read()
.unwrap()
.get(&key)
.unwrap()
.get(&f1_id)
.unwrap()
.id,
f1_id
);
assert_eq!(
rs.list
.read()
.unwrap()
.get(&key)
.unwrap()
.get(&f2_id)
.unwrap()
.id,
f2_id
);
}
#[test]
fn insert_adds_multiple_members() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let key = String::from(f1.key());
let f2 = FakeRumor::default();
assert!(rs.insert(f1));
assert!(rs.insert(f2));
assert_eq!(rs.list.read().unwrap().get(&key).unwrap().len(), 2);
}
#[test]
fn insert_returns_false_on_no_changes() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let f2 = f1.clone();
assert!(rs.insert(f1));
assert_eq!(rs.insert(f2), false);
}
#[test]
fn with_rumor_calls_closure_with_rumor() {
let rs = create_rumor_store();
let f1 = FakeRumor::default();
let member_id = f1.id.clone();
let key = f1.key.clone();
rs.insert(f1);
rs.with_rumor(&key, &member_id, |o| assert_eq!(o.unwrap().id, member_id));
}
#[test]
fn with_rumor_calls_closure_with_none_if_rumor_missing() {
let rs = create_rumor_store();
rs.with_rumor("bar", "foo", |o| assert!(o.is_none()));
}
}
}
|
{
Rumor_Type::Fake
}
|
identifier_body
|
print_iter.rs
|
use cw::{BLOCK, Crosswords, Dir, Point};
/// An element representing a part of a crosswords grid: an element of the cell's borders, a cell
/// and its contents or a line break. It should be converted to a textual or graphical
/// representation.
///
/// The variants specifying borders contain a boolean value specifying whether the border should be
/// displayed as thick or thin, i. e. whether it separates different words or letters of a single
/// word.
pub enum PrintItem {
/// A vertical border.
VertBorder(bool),
/// A horizontal border.
HorizBorder(bool),
/// A crossing point of borders. It is considered thick (value `true`) if at least two of the
/// four lines crossing here are thick.
Cross(bool),
/// A solid block that is left empty in the crossword's solution. It does not belong to a word.
Block,
/// A cell that belongs to one or two words and contains the given character. If one or two
/// words begin in this cell, the second value will be `n`, where this is the `n`-th cell
/// containing the beginning of a word.
CharHint(char, Option<u32>),
/// A line break. This follows after every row of borders or cells.
LineBreak,
}
/// An iterator over all `PrintItem`s representing a crosswords grid.
pub struct
|
<'a> {
point: Point,
between_lines: bool,
between_chars: bool,
cw: &'a Crosswords,
hint_count: u32,
}
impl<'a> PrintIter<'a> {
pub fn new(cw: &'a Crosswords) -> Self {
PrintIter {
point: Point::new(-1, -1),
between_lines: true,
between_chars: true,
cw: cw,
hint_count: 0,
}
}
}
impl<'a> Iterator for PrintIter<'a> {
type Item = PrintItem;
fn next(&mut self) -> Option<PrintItem> {
if self.point.y >= self.cw.height as i32 {
return None;
}
let result;
if self.point.x >= self.cw.width as i32 {
result = PrintItem::LineBreak;
self.point.x = -1;
if self.between_lines {
self.point.y += 1;
}
self.between_chars = true;
self.between_lines =!self.between_lines;
} else if self.between_chars {
if self.between_lines {
let mut count = 0;
if self.cw.get_border(self.point, Dir::Down) {
count += 1
}
if self.cw.get_border(self.point, Dir::Right) {
count += 1
}
if self.cw
.get_border(self.point + Point::new(1, 0), Dir::Down) {
count += 1
}
if self.cw
.get_border(self.point + Point::new(0, 1), Dir::Right) {
count += 1
}
result = PrintItem::Cross(count > 1);
} else {
result = PrintItem::VertBorder(self.cw.get_border(self.point, Dir::Right));
}
self.point.x += 1;
self.between_chars = false;
} else {
if self.between_lines {
result = PrintItem::HorizBorder(self.cw.get_border(self.point, Dir::Down));
} else {
result = match self.cw.get_char(self.point).unwrap() {
BLOCK => PrintItem::Block,
c => {
PrintItem::CharHint(c,
if self.cw.has_hint_at(self.point) {
self.hint_count += 1;
Some(self.hint_count)
} else {
None
})
}
};
}
self.between_chars = true;
}
Some(result)
}
}
|
PrintIter
|
identifier_name
|
print_iter.rs
|
use cw::{BLOCK, Crosswords, Dir, Point};
/// An element representing a part of a crosswords grid: an element of the cell's borders, a cell
/// and its contents or a line break. It should be converted to a textual or graphical
/// representation.
///
/// The variants specifying borders contain a boolean value specifying whether the border should be
/// displayed as thick or thin, i. e. whether it separates different words or letters of a single
/// word.
pub enum PrintItem {
/// A vertical border.
VertBorder(bool),
/// A horizontal border.
HorizBorder(bool),
/// A crossing point of borders. It is considered thick (value `true`) if at least two of the
/// four lines crossing here are thick.
Cross(bool),
/// A solid block that is left empty in the crossword's solution. It does not belong to a word.
Block,
/// A cell that belongs to one or two words and contains the given character. If one or two
/// words begin in this cell, the second value will be `n`, where this is the `n`-th cell
/// containing the beginning of a word.
CharHint(char, Option<u32>),
/// A line break. This follows after every row of borders or cells.
LineBreak,
}
/// An iterator over all `PrintItem`s representing a crosswords grid.
pub struct PrintIter<'a> {
point: Point,
between_lines: bool,
between_chars: bool,
cw: &'a Crosswords,
hint_count: u32,
|
pub fn new(cw: &'a Crosswords) -> Self {
PrintIter {
point: Point::new(-1, -1),
between_lines: true,
between_chars: true,
cw: cw,
hint_count: 0,
}
}
}
impl<'a> Iterator for PrintIter<'a> {
type Item = PrintItem;
fn next(&mut self) -> Option<PrintItem> {
if self.point.y >= self.cw.height as i32 {
return None;
}
let result;
if self.point.x >= self.cw.width as i32 {
result = PrintItem::LineBreak;
self.point.x = -1;
if self.between_lines {
self.point.y += 1;
}
self.between_chars = true;
self.between_lines =!self.between_lines;
} else if self.between_chars {
if self.between_lines {
let mut count = 0;
if self.cw.get_border(self.point, Dir::Down) {
count += 1
}
if self.cw.get_border(self.point, Dir::Right) {
count += 1
}
if self.cw
.get_border(self.point + Point::new(1, 0), Dir::Down) {
count += 1
}
if self.cw
.get_border(self.point + Point::new(0, 1), Dir::Right) {
count += 1
}
result = PrintItem::Cross(count > 1);
} else {
result = PrintItem::VertBorder(self.cw.get_border(self.point, Dir::Right));
}
self.point.x += 1;
self.between_chars = false;
} else {
if self.between_lines {
result = PrintItem::HorizBorder(self.cw.get_border(self.point, Dir::Down));
} else {
result = match self.cw.get_char(self.point).unwrap() {
BLOCK => PrintItem::Block,
c => {
PrintItem::CharHint(c,
if self.cw.has_hint_at(self.point) {
self.hint_count += 1;
Some(self.hint_count)
} else {
None
})
}
};
}
self.between_chars = true;
}
Some(result)
}
}
|
}
impl<'a> PrintIter<'a> {
|
random_line_split
|
print_iter.rs
|
use cw::{BLOCK, Crosswords, Dir, Point};
/// An element representing a part of a crosswords grid: an element of the cell's borders, a cell
/// and its contents or a line break. It should be converted to a textual or graphical
/// representation.
///
/// The variants specifying borders contain a boolean value specifying whether the border should be
/// displayed as thick or thin, i. e. whether it separates different words or letters of a single
/// word.
pub enum PrintItem {
/// A vertical border.
VertBorder(bool),
/// A horizontal border.
HorizBorder(bool),
/// A crossing point of borders. It is considered thick (value `true`) if at least two of the
/// four lines crossing here are thick.
Cross(bool),
/// A solid block that is left empty in the crossword's solution. It does not belong to a word.
Block,
/// A cell that belongs to one or two words and contains the given character. If one or two
/// words begin in this cell, the second value will be `n`, where this is the `n`-th cell
/// containing the beginning of a word.
CharHint(char, Option<u32>),
/// A line break. This follows after every row of borders or cells.
LineBreak,
}
/// An iterator over all `PrintItem`s representing a crosswords grid.
pub struct PrintIter<'a> {
point: Point,
between_lines: bool,
between_chars: bool,
cw: &'a Crosswords,
hint_count: u32,
}
impl<'a> PrintIter<'a> {
pub fn new(cw: &'a Crosswords) -> Self {
PrintIter {
point: Point::new(-1, -1),
between_lines: true,
between_chars: true,
cw: cw,
hint_count: 0,
}
}
}
impl<'a> Iterator for PrintIter<'a> {
type Item = PrintItem;
fn next(&mut self) -> Option<PrintItem> {
if self.point.y >= self.cw.height as i32 {
return None;
}
let result;
if self.point.x >= self.cw.width as i32 {
result = PrintItem::LineBreak;
self.point.x = -1;
if self.between_lines {
self.point.y += 1;
}
self.between_chars = true;
self.between_lines =!self.between_lines;
} else if self.between_chars {
if self.between_lines {
let mut count = 0;
if self.cw.get_border(self.point, Dir::Down) {
count += 1
}
if self.cw.get_border(self.point, Dir::Right) {
count += 1
}
if self.cw
.get_border(self.point + Point::new(1, 0), Dir::Down) {
count += 1
}
if self.cw
.get_border(self.point + Point::new(0, 1), Dir::Right) {
count += 1
}
result = PrintItem::Cross(count > 1);
} else {
result = PrintItem::VertBorder(self.cw.get_border(self.point, Dir::Right));
}
self.point.x += 1;
self.between_chars = false;
} else
|
Some(result)
}
}
|
{
if self.between_lines {
result = PrintItem::HorizBorder(self.cw.get_border(self.point, Dir::Down));
} else {
result = match self.cw.get_char(self.point).unwrap() {
BLOCK => PrintItem::Block,
c => {
PrintItem::CharHint(c,
if self.cw.has_hint_at(self.point) {
self.hint_count += 1;
Some(self.hint_count)
} else {
None
})
}
};
}
self.between_chars = true;
}
|
conditional_block
|
issue-35609.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
enum Enum {
A, B, C, D, E, F
}
use Enum::*;
struct S(Enum, ());
|
fn main() {
match (A, ()) { //~ ERROR non-exhaustive
(A, _) => {}
}
match (A, A) { //~ ERROR non-exhaustive
(_, A) => {}
}
match ((A, ()), ()) { //~ ERROR non-exhaustive
((A, ()), _) => {}
}
match ((A, ()), A) { //~ ERROR non-exhaustive
((A, ()), _) => {}
}
match ((A, ()), ()) { //~ ERROR non-exhaustive
((A, _), _) => {}
}
match S(A, ()) { //~ ERROR non-exhaustive
S(A, _) => {}
}
match (Sd { x: A, y: () }) { //~ ERROR non-exhaustive
Sd { x: A, y: _ } => {}
}
match Some(A) { //~ ERROR non-exhaustive
Some(A) => (),
None => ()
}
}
|
struct Sd { x: Enum, y: () }
|
random_line_split
|
issue-35609.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
enum
|
{
A, B, C, D, E, F
}
use Enum::*;
struct S(Enum, ());
struct Sd { x: Enum, y: () }
fn main() {
match (A, ()) { //~ ERROR non-exhaustive
(A, _) => {}
}
match (A, A) { //~ ERROR non-exhaustive
(_, A) => {}
}
match ((A, ()), ()) { //~ ERROR non-exhaustive
((A, ()), _) => {}
}
match ((A, ()), A) { //~ ERROR non-exhaustive
((A, ()), _) => {}
}
match ((A, ()), ()) { //~ ERROR non-exhaustive
((A, _), _) => {}
}
match S(A, ()) { //~ ERROR non-exhaustive
S(A, _) => {}
}
match (Sd { x: A, y: () }) { //~ ERROR non-exhaustive
Sd { x: A, y: _ } => {}
}
match Some(A) { //~ ERROR non-exhaustive
Some(A) => (),
None => ()
}
}
|
Enum
|
identifier_name
|
coherence_inherent_cc.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.
// ignore-fast
// aux-build:coherence_inherent_cc_lib.rs
// Tests that methods that implement a trait cannot be invoked
// unless the trait is imported.
extern crate coherence_inherent_cc_lib;
mod Import {
// Trait is in scope here:
use coherence_inherent_cc_lib::TheStruct;
use coherence_inherent_cc_lib::TheTrait;
fn call_the_fn(s: &TheStruct) {
s.the_fn();
}
}
mod NoImport {
// Trait is not in scope here:
use coherence_inherent_cc_lib::TheStruct;
fn call_the_fn(s: &TheStruct) {
s.the_fn(); //~ ERROR does not implement any method in scope named `the_fn`
}
}
fn
|
() {}
|
main
|
identifier_name
|
coherence_inherent_cc.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.
// ignore-fast
// aux-build:coherence_inherent_cc_lib.rs
// Tests that methods that implement a trait cannot be invoked
// unless the trait is imported.
extern crate coherence_inherent_cc_lib;
mod Import {
// Trait is in scope here:
use coherence_inherent_cc_lib::TheStruct;
use coherence_inherent_cc_lib::TheTrait;
fn call_the_fn(s: &TheStruct) {
s.the_fn();
}
}
mod NoImport {
// Trait is not in scope here:
use coherence_inherent_cc_lib::TheStruct;
fn call_the_fn(s: &TheStruct) {
s.the_fn(); //~ ERROR does not implement any method in scope named `the_fn`
}
}
fn main() {}
|
random_line_split
|
|
coherence_inherent_cc.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.
// ignore-fast
// aux-build:coherence_inherent_cc_lib.rs
// Tests that methods that implement a trait cannot be invoked
// unless the trait is imported.
extern crate coherence_inherent_cc_lib;
mod Import {
// Trait is in scope here:
use coherence_inherent_cc_lib::TheStruct;
use coherence_inherent_cc_lib::TheTrait;
fn call_the_fn(s: &TheStruct) {
s.the_fn();
}
}
mod NoImport {
// Trait is not in scope here:
use coherence_inherent_cc_lib::TheStruct;
fn call_the_fn(s: &TheStruct) {
s.the_fn(); //~ ERROR does not implement any method in scope named `the_fn`
}
}
fn main()
|
{}
|
identifier_body
|
|
main.rs
|
#![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn main()
|
print!(".");
}
}
println!("\nTotal elapsed time: {:?}", start.elapsed());
}
|
{
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zmq::PULL).unwrap();
assert!(receiver.bind("tcp://*:5558").is_ok());
// Wait for start of batch
let mut msg = zmq::Message::new().unwrap();
receiver.recv(&mut msg, 0).unwrap();
// Start our clock now
let start = Instant::now();
for i in 1..101 {
receiver.recv(&mut msg, 0).unwrap();
if i % 10 == 0 {
print!(":");
} else {
|
identifier_body
|
main.rs
|
#![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn main() {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zmq::PULL).unwrap();
assert!(receiver.bind("tcp://*:5558").is_ok());
// Wait for start of batch
|
receiver.recv(&mut msg, 0).unwrap();
// Start our clock now
let start = Instant::now();
for i in 1..101 {
receiver.recv(&mut msg, 0).unwrap();
if i % 10 == 0 {
print!(":");
} else {
print!(".");
}
}
println!("\nTotal elapsed time: {:?}", start.elapsed());
}
|
let mut msg = zmq::Message::new().unwrap();
|
random_line_split
|
main.rs
|
#![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn main() {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zmq::PULL).unwrap();
assert!(receiver.bind("tcp://*:5558").is_ok());
// Wait for start of batch
let mut msg = zmq::Message::new().unwrap();
receiver.recv(&mut msg, 0).unwrap();
// Start our clock now
let start = Instant::now();
for i in 1..101 {
receiver.recv(&mut msg, 0).unwrap();
if i % 10 == 0 {
print!(":");
} else
|
}
println!("\nTotal elapsed time: {:?}", start.elapsed());
}
|
{
print!(".");
}
|
conditional_block
|
main.rs
|
#![crate_name = "tasksink"]
/// Task sink
/// Binds PULL socket to tcp://localhost:5558
/// Collects results from workers via that socket
extern crate zmq;
use std::time::Instant;
fn
|
() {
// Prepare our context and socket
let mut context = zmq::Context::new();
let mut receiver = context.socket(zmq::PULL).unwrap();
assert!(receiver.bind("tcp://*:5558").is_ok());
// Wait for start of batch
let mut msg = zmq::Message::new().unwrap();
receiver.recv(&mut msg, 0).unwrap();
// Start our clock now
let start = Instant::now();
for i in 1..101 {
receiver.recv(&mut msg, 0).unwrap();
if i % 10 == 0 {
print!(":");
} else {
print!(".");
}
}
println!("\nTotal elapsed time: {:?}", start.elapsed());
}
|
main
|
identifier_name
|
display.rs
|
//! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display for DisplayCausesAndBacktrace<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
for cause in self.err.causes() {
if first {
first = false;
writeln!(f, "Error: {}", cause)?;
} else {
writeln!(f, " caused by: {}", cause)?;
}
}
if self.include_backtrace {
write!(f, "{}", self.err.backtrace())?;
}
Ok(())
}
}
/// Extensions to standard `failure::Error` trait.
pub trait DisplayCausesAndBacktraceExt {
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes, plus an optional
/// backtrace.
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace;
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes. However, the
/// backtrace will be omitted even if `RUST_BACKTRACE` is set. This is
/// intended to be used in situations where the backtrace needed to be
/// handled separately, as with APIs like Rollbar's.
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace;
}
impl DisplayCausesAndBacktraceExt for failure::Error {
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace
|
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: false }
}
}
|
{
DisplayCausesAndBacktrace { err: self, include_backtrace: true }
}
|
identifier_body
|
display.rs
|
//! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display for DisplayCausesAndBacktrace<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
for cause in self.err.causes() {
if first {
first = false;
writeln!(f, "Error: {}", cause)?;
} else
|
}
if self.include_backtrace {
write!(f, "{}", self.err.backtrace())?;
}
Ok(())
}
}
/// Extensions to standard `failure::Error` trait.
pub trait DisplayCausesAndBacktraceExt {
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes, plus an optional
/// backtrace.
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace;
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes. However, the
/// backtrace will be omitted even if `RUST_BACKTRACE` is set. This is
/// intended to be used in situations where the backtrace needed to be
/// handled separately, as with APIs like Rollbar's.
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace;
}
impl DisplayCausesAndBacktraceExt for failure::Error {
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: true }
}
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: false }
}
}
|
{
writeln!(f, " caused by: {}", cause)?;
}
|
conditional_block
|
display.rs
|
//! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display for DisplayCausesAndBacktrace<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
for cause in self.err.causes() {
if first {
first = false;
writeln!(f, "Error: {}", cause)?;
} else {
writeln!(f, " caused by: {}", cause)?;
}
}
if self.include_backtrace {
write!(f, "{}", self.err.backtrace())?;
}
Ok(())
}
}
/// Extensions to standard `failure::Error` trait.
pub trait DisplayCausesAndBacktraceExt {
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes, plus an optional
/// backtrace.
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace;
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes. However, the
/// backtrace will be omitted even if `RUST_BACKTRACE` is set. This is
/// intended to be used in situations where the backtrace needed to be
/// handled separately, as with APIs like Rollbar's.
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace;
}
impl DisplayCausesAndBacktraceExt for failure::Error {
fn
|
(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: true }
}
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: false }
}
}
|
display_causes_and_backtrace
|
identifier_name
|
display.rs
|
//! Utilities for formatting and displaying errors.
use failure;
use std::fmt;
use Error;
/// A wrapper which prints a human-readable list of the causes of an error, plus
/// a backtrace if present.
pub struct DisplayCausesAndBacktrace<'a> {
err: &'a Error,
include_backtrace: bool,
}
impl<'a> fmt::Display for DisplayCausesAndBacktrace<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut first = true;
for cause in self.err.causes() {
if first {
first = false;
writeln!(f, "Error: {}", cause)?;
} else {
writeln!(f, " caused by: {}", cause)?;
}
}
if self.include_backtrace {
write!(f, "{}", self.err.backtrace())?;
}
Ok(())
}
|
pub trait DisplayCausesAndBacktraceExt {
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes, plus an optional
/// backtrace.
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace;
/// Wrap the error in `DisplayCausesAndBacktrace`, causing it to be
/// formatted with a human-readable list of all causes. However, the
/// backtrace will be omitted even if `RUST_BACKTRACE` is set. This is
/// intended to be used in situations where the backtrace needed to be
/// handled separately, as with APIs like Rollbar's.
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace;
}
impl DisplayCausesAndBacktraceExt for failure::Error {
fn display_causes_and_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: true }
}
fn display_causes_without_backtrace(&self) -> DisplayCausesAndBacktrace {
DisplayCausesAndBacktrace { err: self, include_backtrace: false }
}
}
|
}
/// Extensions to standard `failure::Error` trait.
|
random_line_split
|
util.rs
|
use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn get_hash<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [0; 4];
{
let mut hasher = <H as Default>::default();
data.hash(&mut hasher);
let _ = (&mut result[..]).write_u32::<BigEndian>(hasher.finish() as u32);
}
result
}
pub fn get_alt_index<H: Hasher + Default>(fp: Fingerprint, i: usize) -> usize
|
impl FaI {
fn from_data<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
let mut hash_arr: [u8; FINGERPRINT_SIZE] = [0; FINGERPRINT_SIZE];
let hash = get_hash::<_, H>(data);
let mut n = 0;
let fp;
loop {
for i in 0..FINGERPRINT_SIZE {
hash_arr[i] = hash[i] + n;
}
if let Some(val) = Fingerprint::from_data(hash_arr) {
fp = val;
break;
}
n += 1;
}
let i1 = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
let i2 = get_alt_index::<H>(fp, i1);
FaI {
fp: fp, i1: i1, i2: i2
}
}
pub fn random_index<R: ::rand::Rng>(&self, r: &mut R) -> usize {
if r.gen() {
self.i1
} else {
self.i2
}
}
}
pub fn get_fai<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
FaI::from_data::<_, H>(data)
}
#[test]
fn test_fp_and_index() {
use std::hash::SipHasher;
let data = "seif";
let fai = get_fai::<_, SipHasher>(data);
let fp = fai.fp;
let i1 = fai.i1;
let i2 = fai.i2;
let i11 = get_alt_index::<SipHasher>(fp, i2);
assert_eq!(i11, i1);
let i22 = get_alt_index::<SipHasher>(fp, i11);
assert_eq!(i22, i2);
}
|
{
let hash = get_hash::<_, H>(&fp.data);
let alt_i = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
(i ^ alt_i) as usize
}
|
identifier_body
|
util.rs
|
use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn get_hash<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [0; 4];
{
let mut hasher = <H as Default>::default();
data.hash(&mut hasher);
let _ = (&mut result[..]).write_u32::<BigEndian>(hasher.finish() as u32);
}
result
}
pub fn get_alt_index<H: Hasher + Default>(fp: Fingerprint, i: usize) -> usize {
let hash = get_hash::<_, H>(&fp.data);
let alt_i = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
(i ^ alt_i) as usize
}
impl FaI {
fn from_data<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
let mut hash_arr: [u8; FINGERPRINT_SIZE] = [0; FINGERPRINT_SIZE];
let hash = get_hash::<_, H>(data);
let mut n = 0;
let fp;
loop {
for i in 0..FINGERPRINT_SIZE {
hash_arr[i] = hash[i] + n;
}
if let Some(val) = Fingerprint::from_data(hash_arr)
|
n += 1;
}
let i1 = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
let i2 = get_alt_index::<H>(fp, i1);
FaI {
fp: fp, i1: i1, i2: i2
}
}
pub fn random_index<R: ::rand::Rng>(&self, r: &mut R) -> usize {
if r.gen() {
self.i1
} else {
self.i2
}
}
}
pub fn get_fai<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
FaI::from_data::<_, H>(data)
}
#[test]
fn test_fp_and_index() {
use std::hash::SipHasher;
let data = "seif";
let fai = get_fai::<_, SipHasher>(data);
let fp = fai.fp;
let i1 = fai.i1;
let i2 = fai.i2;
let i11 = get_alt_index::<SipHasher>(fp, i2);
assert_eq!(i11, i1);
let i22 = get_alt_index::<SipHasher>(fp, i11);
assert_eq!(i22, i2);
}
|
{
fp = val;
break;
}
|
conditional_block
|
util.rs
|
use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn get_hash<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [0; 4];
{
let mut hasher = <H as Default>::default();
data.hash(&mut hasher);
let _ = (&mut result[..]).write_u32::<BigEndian>(hasher.finish() as u32);
}
result
}
pub fn get_alt_index<H: Hasher + Default>(fp: Fingerprint, i: usize) -> usize {
let hash = get_hash::<_, H>(&fp.data);
let alt_i = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
(i ^ alt_i) as usize
}
impl FaI {
fn from_data<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
let mut hash_arr: [u8; FINGERPRINT_SIZE] = [0; FINGERPRINT_SIZE];
let hash = get_hash::<_, H>(data);
let mut n = 0;
let fp;
loop {
for i in 0..FINGERPRINT_SIZE {
hash_arr[i] = hash[i] + n;
}
if let Some(val) = Fingerprint::from_data(hash_arr) {
fp = val;
break;
}
n += 1;
}
|
FaI {
fp: fp, i1: i1, i2: i2
}
}
pub fn random_index<R: ::rand::Rng>(&self, r: &mut R) -> usize {
if r.gen() {
self.i1
} else {
self.i2
}
}
}
pub fn get_fai<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
FaI::from_data::<_, H>(data)
}
#[test]
fn test_fp_and_index() {
use std::hash::SipHasher;
let data = "seif";
let fai = get_fai::<_, SipHasher>(data);
let fp = fai.fp;
let i1 = fai.i1;
let i2 = fai.i2;
let i11 = get_alt_index::<SipHasher>(fp, i2);
assert_eq!(i11, i1);
let i22 = get_alt_index::<SipHasher>(fp, i11);
assert_eq!(i22, i2);
}
|
let i1 = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
let i2 = get_alt_index::<H>(fp, i1);
|
random_line_split
|
util.rs
|
use std::hash::{Hasher, Hash, hash};
use ::byteorder::{BigEndian, WriteBytesExt, ReadBytesExt};
use ::bucket::{Fingerprint, FINGERPRINT_SIZE};
pub struct FaI {
pub fp: Fingerprint,
pub i1: usize,
pub i2: usize
}
fn
|
<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> [u8; 4] {
let mut result = [0; 4];
{
let mut hasher = <H as Default>::default();
data.hash(&mut hasher);
let _ = (&mut result[..]).write_u32::<BigEndian>(hasher.finish() as u32);
}
result
}
pub fn get_alt_index<H: Hasher + Default>(fp: Fingerprint, i: usize) -> usize {
let hash = get_hash::<_, H>(&fp.data);
let alt_i = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
(i ^ alt_i) as usize
}
impl FaI {
fn from_data<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
let mut hash_arr: [u8; FINGERPRINT_SIZE] = [0; FINGERPRINT_SIZE];
let hash = get_hash::<_, H>(data);
let mut n = 0;
let fp;
loop {
for i in 0..FINGERPRINT_SIZE {
hash_arr[i] = hash[i] + n;
}
if let Some(val) = Fingerprint::from_data(hash_arr) {
fp = val;
break;
}
n += 1;
}
let i1 = (&hash[..]).read_u32::<BigEndian>().unwrap() as usize;
let i2 = get_alt_index::<H>(fp, i1);
FaI {
fp: fp, i1: i1, i2: i2
}
}
pub fn random_index<R: ::rand::Rng>(&self, r: &mut R) -> usize {
if r.gen() {
self.i1
} else {
self.i2
}
}
}
pub fn get_fai<T:?Sized + Hash, H: Hasher + Default>(data: &T) -> FaI {
FaI::from_data::<_, H>(data)
}
#[test]
fn test_fp_and_index() {
use std::hash::SipHasher;
let data = "seif";
let fai = get_fai::<_, SipHasher>(data);
let fp = fai.fp;
let i1 = fai.i1;
let i2 = fai.i2;
let i11 = get_alt_index::<SipHasher>(fp, i2);
assert_eq!(i11, i1);
let i22 = get_alt_index::<SipHasher>(fp, i11);
assert_eq!(i22, i2);
}
|
get_hash
|
identifier_name
|
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::node::Node;
use dom::svggraphicselement::SVGGraphicsElement;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use script_layout_interface::SVGSVGData;
use style::attr::AttrValue;
const DEFAULT_WIDTH: u32 = 300;
const DEFAULT_HEIGHT: u32 = 150;
#[dom_struct]
pub struct SVGSVGElement {
svggraphicselement: SVGGraphicsElement
}
impl SVGSVGElement {
fn new_inherited(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> SVGSVGElement
|
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> Root<SVGSVGElement> {
Node::reflect_node(box SVGSVGElement::new_inherited(local_name, prefix, document),
document,
SVGSVGElementBinding::Wrap)
}
}
pub trait LayoutSVGSVGElementHelpers {
fn data(&self) -> SVGSVGData;
}
impl LayoutSVGSVGElementHelpers for LayoutJS<SVGSVGElement> {
#[allow(unsafe_code)]
fn data(&self) -> SVGSVGData {
unsafe {
let SVG = &*self.unsafe_get();
let width_attr = SVG.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width"));
let height_attr = SVG.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height"));
SVGSVGData {
width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()),
height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()),
}
}
}
}
impl VirtualMethods for SVGSVGElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<SVGGraphicsElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
&local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
|
{
SVGSVGElement {
svggraphicselement:
SVGGraphicsElement::new_inherited(local_name, prefix, document)
}
}
|
identifier_body
|
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::node::Node;
use dom::svggraphicselement::SVGGraphicsElement;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use script_layout_interface::SVGSVGData;
use style::attr::AttrValue;
const DEFAULT_WIDTH: u32 = 300;
const DEFAULT_HEIGHT: u32 = 150;
#[dom_struct]
pub struct
|
{
svggraphicselement: SVGGraphicsElement
}
impl SVGSVGElement {
fn new_inherited(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> SVGSVGElement {
SVGSVGElement {
svggraphicselement:
SVGGraphicsElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> Root<SVGSVGElement> {
Node::reflect_node(box SVGSVGElement::new_inherited(local_name, prefix, document),
document,
SVGSVGElementBinding::Wrap)
}
}
pub trait LayoutSVGSVGElementHelpers {
fn data(&self) -> SVGSVGData;
}
impl LayoutSVGSVGElementHelpers for LayoutJS<SVGSVGElement> {
#[allow(unsafe_code)]
fn data(&self) -> SVGSVGData {
unsafe {
let SVG = &*self.unsafe_get();
let width_attr = SVG.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width"));
let height_attr = SVG.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height"));
SVGSVGData {
width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()),
height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()),
}
}
}
}
impl VirtualMethods for SVGSVGElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<SVGGraphicsElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
&local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
|
SVGSVGElement
|
identifier_name
|
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::node::Node;
use dom::svggraphicselement::SVGGraphicsElement;
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use script_layout_interface::SVGSVGData;
use style::attr::AttrValue;
const DEFAULT_WIDTH: u32 = 300;
const DEFAULT_HEIGHT: u32 = 150;
#[dom_struct]
pub struct SVGSVGElement {
svggraphicselement: SVGGraphicsElement
}
impl SVGSVGElement {
fn new_inherited(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> SVGSVGElement {
SVGSVGElement {
svggraphicselement:
SVGGraphicsElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<Prefix>,
document: &Document) -> Root<SVGSVGElement> {
Node::reflect_node(box SVGSVGElement::new_inherited(local_name, prefix, document),
document,
SVGSVGElementBinding::Wrap)
}
|
}
pub trait LayoutSVGSVGElementHelpers {
fn data(&self) -> SVGSVGData;
}
impl LayoutSVGSVGElementHelpers for LayoutJS<SVGSVGElement> {
#[allow(unsafe_code)]
fn data(&self) -> SVGSVGData {
unsafe {
let SVG = &*self.unsafe_get();
let width_attr = SVG.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width"));
let height_attr = SVG.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height"));
SVGSVGData {
width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()),
height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()),
}
}
}
}
impl VirtualMethods for SVGSVGElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<SVGGraphicsElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
&local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
|
random_line_split
|
|
multiple_files.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.
extern crate rand;
use rand::{task_rng, Rng};
use std::{char, os, str};
use std::io::{File, Process};
// creates unicode_input_multiple_files_{main,chars}.rs, where the
// former imports the latter. `_chars` just contains an indentifier
// made up of random characters, because will emit an error message
// about the ident being in the wrong place, with a span (and creating
// this span used to upset the compiler).
fn random_char() -> char {
let mut rng = task_rng();
// a subset of the XID_start unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1, 4 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
_ => (0x10400, 0x1044f)
};
char::from_u32(rng.gen_range(lo, hi + 1)).unwrap()
}
fn
|
() {
let args = os::args();
let rustc = args.get(1).as_slice();
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
let main_file_str = main_file.as_str().unwrap();
{
let _ = File::create(&main_file).unwrap()
.write_str("mod unicode_input_multiple_files_chars;");
}
for _ in range(0, 100) {
{
let randoms = tmpdir.join("unicode_input_multiple_files_chars.rs");
let mut w = File::create(&randoms).unwrap();
for _ in range(0, 30) {
let _ = w.write_char(random_char());
}
}
// rustc is passed to us with --out-dir and -L etc., so we
// can't exec it directly
let result = Process::output("sh", ["-c".to_owned(), rustc + " " + main_file_str]).unwrap();
let err = str::from_utf8_lossy(result.error.as_slice());
// positive test so that this test will be updated when the
// compiler changes.
assert!(err.as_slice().contains("expected item but found"))
}
}
|
main
|
identifier_name
|
multiple_files.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.
extern crate rand;
use rand::{task_rng, Rng};
use std::{char, os, str};
use std::io::{File, Process};
// creates unicode_input_multiple_files_{main,chars}.rs, where the
// former imports the latter. `_chars` just contains an indentifier
// made up of random characters, because will emit an error message
// about the ident being in the wrong place, with a span (and creating
// this span used to upset the compiler).
fn random_char() -> char
|
fn main() {
let args = os::args();
let rustc = args.get(1).as_slice();
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
let main_file_str = main_file.as_str().unwrap();
{
let _ = File::create(&main_file).unwrap()
.write_str("mod unicode_input_multiple_files_chars;");
}
for _ in range(0, 100) {
{
let randoms = tmpdir.join("unicode_input_multiple_files_chars.rs");
let mut w = File::create(&randoms).unwrap();
for _ in range(0, 30) {
let _ = w.write_char(random_char());
}
}
// rustc is passed to us with --out-dir and -L etc., so we
// can't exec it directly
let result = Process::output("sh", ["-c".to_owned(), rustc + " " + main_file_str]).unwrap();
let err = str::from_utf8_lossy(result.error.as_slice());
// positive test so that this test will be updated when the
// compiler changes.
assert!(err.as_slice().contains("expected item but found"))
}
}
|
{
let mut rng = task_rng();
// a subset of the XID_start unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1, 4 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
_ => (0x10400, 0x1044f)
};
char::from_u32(rng.gen_range(lo, hi + 1)).unwrap()
}
|
identifier_body
|
multiple_files.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.
extern crate rand;
use rand::{task_rng, Rng};
use std::{char, os, str};
use std::io::{File, Process};
// creates unicode_input_multiple_files_{main,chars}.rs, where the
// former imports the latter. `_chars` just contains an indentifier
// made up of random characters, because will emit an error message
// about the ident being in the wrong place, with a span (and creating
// this span used to upset the compiler).
fn random_char() -> char {
let mut rng = task_rng();
// a subset of the XID_start unicode table (ensuring that the
// compiler doesn't fail with an "unrecognised token" error)
let (lo, hi): (u32, u32) = match rng.gen_range(1, 4 + 1) {
1 => (0x41, 0x5a),
2 => (0xf8, 0x1ba),
3 => (0x1401, 0x166c),
_ => (0x10400, 0x1044f)
};
char::from_u32(rng.gen_range(lo, hi + 1)).unwrap()
}
fn main() {
let args = os::args();
let rustc = args.get(1).as_slice();
let tmpdir = Path::new(args.get(2).as_slice());
let main_file = tmpdir.join("unicode_input_multiple_files_main.rs");
let main_file_str = main_file.as_str().unwrap();
{
let _ = File::create(&main_file).unwrap()
.write_str("mod unicode_input_multiple_files_chars;");
}
for _ in range(0, 100) {
{
let randoms = tmpdir.join("unicode_input_multiple_files_chars.rs");
let mut w = File::create(&randoms).unwrap();
for _ in range(0, 30) {
let _ = w.write_char(random_char());
}
}
// rustc is passed to us with --out-dir and -L etc., so we
|
// compiler changes.
assert!(err.as_slice().contains("expected item but found"))
}
}
|
// can't exec it directly
let result = Process::output("sh", ["-c".to_owned(), rustc + " " + main_file_str]).unwrap();
let err = str::from_utf8_lossy(result.error.as_slice());
// positive test so that this test will be updated when the
|
random_line_split
|
aes_ecb_decrypter.rs
|
/* AES-128 ECB mode decrypter
*
* Dmitry Vasiliev <[email protected]>
*/
extern crate serialize;
extern crate aes_lib;
use std::path::Path;
use std::io::fs::File;
use serialize::base64::FromBase64;
use aes_lib::decrypt_aes_ecb;
fn
|
(mut file: File, key: &[u8]) -> Vec<u8> {
let data = file.read_to_end().unwrap();
let text = String::from_utf8(data).unwrap();
let encrypted = text.from_base64().unwrap();
decrypt_aes_ecb(encrypted.as_slice(), key)
}
/*
* Main entry point
*/
fn main() {
let key = b"YELLOW SUBMARINE";
let path = Path::new("aes_ecb_encrypted.txt");
let decrypted = match File::open(&path) {
Ok(file) => decrypt_aes_ecb_file(file, key),
Err(err) => panic!("Unable to open aes_ecb_encrypted.txt: {}", err)
};
println!("Decrypted => \"{}\"", String::from_utf8(decrypted).unwrap());
}
|
decrypt_aes_ecb_file
|
identifier_name
|
aes_ecb_decrypter.rs
|
/* AES-128 ECB mode decrypter
*
* Dmitry Vasiliev <[email protected]>
*/
extern crate serialize;
extern crate aes_lib;
use std::path::Path;
use std::io::fs::File;
use serialize::base64::FromBase64;
use aes_lib::decrypt_aes_ecb;
fn decrypt_aes_ecb_file(mut file: File, key: &[u8]) -> Vec<u8>
|
/*
* Main entry point
*/
fn main() {
let key = b"YELLOW SUBMARINE";
let path = Path::new("aes_ecb_encrypted.txt");
let decrypted = match File::open(&path) {
Ok(file) => decrypt_aes_ecb_file(file, key),
Err(err) => panic!("Unable to open aes_ecb_encrypted.txt: {}", err)
};
println!("Decrypted => \"{}\"", String::from_utf8(decrypted).unwrap());
}
|
{
let data = file.read_to_end().unwrap();
let text = String::from_utf8(data).unwrap();
let encrypted = text.from_base64().unwrap();
decrypt_aes_ecb(encrypted.as_slice(), key)
}
|
identifier_body
|
aes_ecb_decrypter.rs
|
/* AES-128 ECB mode decrypter
*
* Dmitry Vasiliev <[email protected]>
*/
|
use std::path::Path;
use std::io::fs::File;
use serialize::base64::FromBase64;
use aes_lib::decrypt_aes_ecb;
fn decrypt_aes_ecb_file(mut file: File, key: &[u8]) -> Vec<u8> {
let data = file.read_to_end().unwrap();
let text = String::from_utf8(data).unwrap();
let encrypted = text.from_base64().unwrap();
decrypt_aes_ecb(encrypted.as_slice(), key)
}
/*
* Main entry point
*/
fn main() {
let key = b"YELLOW SUBMARINE";
let path = Path::new("aes_ecb_encrypted.txt");
let decrypted = match File::open(&path) {
Ok(file) => decrypt_aes_ecb_file(file, key),
Err(err) => panic!("Unable to open aes_ecb_encrypted.txt: {}", err)
};
println!("Decrypted => \"{}\"", String::from_utf8(decrypted).unwrap());
}
|
extern crate serialize;
extern crate aes_lib;
|
random_line_split
|
issue-19358.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 {}
#[derive(Show)]
struct Foo<T: Trait> {
foo: T,
}
#[derive(Show)]
|
struct Bar<T> where T: Trait {
bar: T,
}
impl Trait for int {}
fn main() {
let a = Foo { foo: 12i };
let b = Bar { bar: 12i };
println!("{:?} {:?}", a, b);
}
|
random_line_split
|
|
issue-19358.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 {}
#[derive(Show)]
struct Foo<T: Trait> {
foo: T,
}
#[derive(Show)]
struct Bar<T> where T: Trait {
bar: T,
}
impl Trait for int {}
fn
|
() {
let a = Foo { foo: 12i };
let b = Bar { bar: 12i };
println!("{:?} {:?}", a, b);
}
|
main
|
identifier_name
|
miner_service.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Test implementation of miner service.
use util::{Address, H256, Bytes, U256, FixedHash, Uint};
use util::standard::*;
use ethcore::error::{Error, CallError};
use ethcore::client::{MiningBlockChainClient, Executed, CallAnalytics};
use ethcore::block::{ClosedBlock, IsBlock};
use ethcore::header::BlockNumber;
use ethcore::transaction::SignedTransaction;
use ethcore::receipt::{Receipt, RichReceipt};
use ethcore::miner::{MinerService, MinerStatus, TransactionImportResult};
/// Test miner service.
pub struct TestMinerService {
/// Imported transactions.
pub imported_transactions: Mutex<Vec<SignedTransaction>>,
/// Latest closed block.
pub latest_closed_block: Mutex<Option<ClosedBlock>>,
/// Pre-existed pending transactions
pub pending_transactions: Mutex<HashMap<H256, SignedTransaction>>,
/// Pre-existed pending receipts
pub pending_receipts: Mutex<BTreeMap<H256, Receipt>>,
/// Last nonces.
pub last_nonces: RwLock<HashMap<Address, U256>>,
min_gas_price: RwLock<U256>,
gas_range_target: RwLock<(U256, U256)>,
author: RwLock<Address>,
extra_data: RwLock<Bytes>,
limit: RwLock<usize>,
tx_gas_limit: RwLock<U256>,
}
impl Default for TestMinerService {
fn default() -> TestMinerService {
TestMinerService {
imported_transactions: Mutex::new(Vec::new()),
latest_closed_block: Mutex::new(None),
pending_transactions: Mutex::new(HashMap::new()),
pending_receipts: Mutex::new(BTreeMap::new()),
last_nonces: RwLock::new(HashMap::new()),
min_gas_price: RwLock::new(U256::from(20_000_000)),
gas_range_target: RwLock::new((U256::from(12345), U256::from(54321))),
author: RwLock::new(Address::zero()),
extra_data: RwLock::new(vec![1, 2, 3, 4]),
limit: RwLock::new(1024),
tx_gas_limit: RwLock::new(!U256::zero()),
}
}
}
impl MinerService for TestMinerService {
/// Returns miner's status.
fn status(&self) -> MinerStatus {
MinerStatus {
transactions_in_pending_queue: 0,
transactions_in_future_queue: 0,
transactions_in_pending_block: 1
}
}
fn set_author(&self, author: Address) {
*self.author.write() = author;
}
fn set_extra_data(&self, extra_data: Bytes)
|
/// Set the lower gas limit we wish to target when sealing a new block.
fn set_gas_floor_target(&self, target: U256) {
self.gas_range_target.write().0 = target;
}
/// Set the upper gas limit we wish to target when sealing a new block.
fn set_gas_ceil_target(&self, target: U256) {
self.gas_range_target.write().1 = target;
}
fn set_minimal_gas_price(&self, min_gas_price: U256) {
*self.min_gas_price.write() = min_gas_price;
}
fn set_transactions_limit(&self, limit: usize) {
*self.limit.write() = limit;
}
fn set_tx_gas_limit(&self, limit: U256) {
*self.tx_gas_limit.write() = limit;
}
fn transactions_limit(&self) -> usize {
*self.limit.read()
}
fn author(&self) -> Address {
*self.author.read()
}
fn minimal_gas_price(&self) -> U256 {
*self.min_gas_price.read()
}
fn extra_data(&self) -> Bytes {
self.extra_data.read().clone()
}
fn gas_floor_target(&self) -> U256 {
self.gas_range_target.read().0
}
fn gas_ceil_target(&self) -> U256 {
self.gas_range_target.read().1
}
/// Imports transactions to transaction queue.
fn import_external_transactions(&self, _chain: &MiningBlockChainClient, transactions: Vec<SignedTransaction>) ->
Vec<Result<TransactionImportResult, Error>> {
// lets assume that all txs are valid
self.imported_transactions.lock().extend_from_slice(&transactions);
for sender in transactions.iter().filter_map(|t| t.sender().ok()) {
let nonce = self.last_nonce(&sender).expect("last_nonce must be populated in tests");
self.last_nonces.write().insert(sender, nonce + U256::from(1));
}
transactions
.iter()
.map(|_| Ok(TransactionImportResult::Current))
.collect()
}
/// Imports transactions to transaction queue.
fn import_own_transaction(&self, chain: &MiningBlockChainClient, transaction: SignedTransaction) ->
Result<TransactionImportResult, Error> {
// keep the pending nonces up to date
if let Ok(ref sender) = transaction.sender() {
let nonce = self.last_nonce(sender).unwrap_or(chain.latest_nonce(sender));
self.last_nonces.write().insert(sender.clone(), nonce + U256::from(1));
}
// lets assume that all txs are valid
self.imported_transactions.lock().push(transaction);
Ok(TransactionImportResult::Current)
}
/// Returns hashes of transactions currently in pending
fn pending_transactions_hashes(&self, _best_block: BlockNumber) -> Vec<H256> {
vec![]
}
/// Removes all transactions from the queue and restart mining operation.
fn clear_and_reset(&self, _chain: &MiningBlockChainClient) {
unimplemented!();
}
/// Called when blocks are imported to chain, updates transactions queue.
fn chain_new_blocks(&self, _chain: &MiningBlockChainClient, _imported: &[H256], _invalid: &[H256], _enacted: &[H256], _retracted: &[H256]) {
unimplemented!();
}
/// New chain head event. Restart mining operation.
fn update_sealing(&self, _chain: &MiningBlockChainClient) {
unimplemented!();
}
fn map_sealing_work<F, T>(&self, chain: &MiningBlockChainClient, f: F) -> Option<T> where F: FnOnce(&ClosedBlock) -> T {
let open_block = chain.prepare_open_block(self.author(), *self.gas_range_target.write(), self.extra_data());
Some(f(&open_block.close()))
}
fn transaction(&self, _best_block: BlockNumber, hash: &H256) -> Option<SignedTransaction> {
self.pending_transactions.lock().get(hash).cloned()
}
fn all_transactions(&self) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_transactions(&self, _best_block: BlockNumber) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_receipt(&self, _best_block: BlockNumber, hash: &H256) -> Option<RichReceipt> {
// Not much point implementing this since the logic is complex and the only thing it relies on is pending_receipts, which is already tested.
self.pending_receipts(0).get(hash).map(|r|
RichReceipt {
transaction_hash: Default::default(),
transaction_index: Default::default(),
cumulative_gas_used: r.gas_used.clone(),
gas_used: r.gas_used.clone(),
contract_address: None,
logs: r.logs.clone(),
}
)
}
fn pending_receipts(&self, _best_block: BlockNumber) -> BTreeMap<H256, Receipt> {
self.pending_receipts.lock().clone()
}
fn last_nonce(&self, address: &Address) -> Option<U256> {
self.last_nonces.read().get(address).cloned()
}
fn is_sealing(&self) -> bool {
false
}
/// Submit `seal` as a valid solution for the header of `pow_hash`.
/// Will check the seal, but not actually insert the block into the chain.
fn submit_seal(&self, _chain: &MiningBlockChainClient, _pow_hash: H256, _seal: Vec<Bytes>) -> Result<(), Error> {
unimplemented!();
}
fn balance(&self, _chain: &MiningBlockChainClient, address: &Address) -> U256 {
self.latest_closed_block.lock().as_ref().map_or_else(U256::zero, |b| b.block().fields().state.balance(address).clone())
}
fn call(&self, _chain: &MiningBlockChainClient, _t: &SignedTransaction, _analytics: CallAnalytics) -> Result<Executed, CallError> {
unimplemented!();
}
fn storage_at(&self, _chain: &MiningBlockChainClient, address: &Address, position: &H256) -> H256 {
self.latest_closed_block.lock().as_ref().map_or_else(H256::default, |b| b.block().fields().state.storage_at(address, position).clone())
}
fn nonce(&self, _chain: &MiningBlockChainClient, address: &Address) -> U256 {
// we assume all transactions are in a pending block, ignoring the
// reality of gas limits.
self.last_nonce(address).unwrap_or(U256::zero())
}
fn code(&self, _chain: &MiningBlockChainClient, address: &Address) -> Option<Bytes> {
self.latest_closed_block.lock().as_ref().map_or(None, |b| b.block().fields().state.code(address).map(|c| (*c).clone()))
}
}
|
{
*self.extra_data.write() = extra_data;
}
|
identifier_body
|
miner_service.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Test implementation of miner service.
use util::{Address, H256, Bytes, U256, FixedHash, Uint};
use util::standard::*;
use ethcore::error::{Error, CallError};
use ethcore::client::{MiningBlockChainClient, Executed, CallAnalytics};
use ethcore::block::{ClosedBlock, IsBlock};
use ethcore::header::BlockNumber;
use ethcore::transaction::SignedTransaction;
use ethcore::receipt::{Receipt, RichReceipt};
use ethcore::miner::{MinerService, MinerStatus, TransactionImportResult};
/// Test miner service.
pub struct TestMinerService {
/// Imported transactions.
pub imported_transactions: Mutex<Vec<SignedTransaction>>,
/// Latest closed block.
pub latest_closed_block: Mutex<Option<ClosedBlock>>,
/// Pre-existed pending transactions
pub pending_transactions: Mutex<HashMap<H256, SignedTransaction>>,
/// Pre-existed pending receipts
pub pending_receipts: Mutex<BTreeMap<H256, Receipt>>,
/// Last nonces.
pub last_nonces: RwLock<HashMap<Address, U256>>,
min_gas_price: RwLock<U256>,
gas_range_target: RwLock<(U256, U256)>,
author: RwLock<Address>,
extra_data: RwLock<Bytes>,
limit: RwLock<usize>,
tx_gas_limit: RwLock<U256>,
}
impl Default for TestMinerService {
fn default() -> TestMinerService {
TestMinerService {
imported_transactions: Mutex::new(Vec::new()),
latest_closed_block: Mutex::new(None),
pending_transactions: Mutex::new(HashMap::new()),
pending_receipts: Mutex::new(BTreeMap::new()),
last_nonces: RwLock::new(HashMap::new()),
min_gas_price: RwLock::new(U256::from(20_000_000)),
gas_range_target: RwLock::new((U256::from(12345), U256::from(54321))),
author: RwLock::new(Address::zero()),
extra_data: RwLock::new(vec![1, 2, 3, 4]),
limit: RwLock::new(1024),
tx_gas_limit: RwLock::new(!U256::zero()),
}
}
}
impl MinerService for TestMinerService {
/// Returns miner's status.
fn status(&self) -> MinerStatus {
MinerStatus {
transactions_in_pending_queue: 0,
transactions_in_future_queue: 0,
transactions_in_pending_block: 1
}
}
fn set_author(&self, author: Address) {
*self.author.write() = author;
}
fn set_extra_data(&self, extra_data: Bytes) {
*self.extra_data.write() = extra_data;
}
/// Set the lower gas limit we wish to target when sealing a new block.
fn set_gas_floor_target(&self, target: U256) {
self.gas_range_target.write().0 = target;
}
/// Set the upper gas limit we wish to target when sealing a new block.
fn set_gas_ceil_target(&self, target: U256) {
self.gas_range_target.write().1 = target;
}
fn set_minimal_gas_price(&self, min_gas_price: U256) {
*self.min_gas_price.write() = min_gas_price;
}
fn set_transactions_limit(&self, limit: usize) {
*self.limit.write() = limit;
}
fn set_tx_gas_limit(&self, limit: U256) {
*self.tx_gas_limit.write() = limit;
}
fn transactions_limit(&self) -> usize {
*self.limit.read()
}
fn author(&self) -> Address {
*self.author.read()
}
fn minimal_gas_price(&self) -> U256 {
*self.min_gas_price.read()
}
fn extra_data(&self) -> Bytes {
self.extra_data.read().clone()
}
fn gas_floor_target(&self) -> U256 {
self.gas_range_target.read().0
}
fn gas_ceil_target(&self) -> U256 {
self.gas_range_target.read().1
}
/// Imports transactions to transaction queue.
fn import_external_transactions(&self, _chain: &MiningBlockChainClient, transactions: Vec<SignedTransaction>) ->
Vec<Result<TransactionImportResult, Error>> {
// lets assume that all txs are valid
self.imported_transactions.lock().extend_from_slice(&transactions);
for sender in transactions.iter().filter_map(|t| t.sender().ok()) {
let nonce = self.last_nonce(&sender).expect("last_nonce must be populated in tests");
self.last_nonces.write().insert(sender, nonce + U256::from(1));
}
transactions
.iter()
.map(|_| Ok(TransactionImportResult::Current))
.collect()
}
/// Imports transactions to transaction queue.
fn import_own_transaction(&self, chain: &MiningBlockChainClient, transaction: SignedTransaction) ->
Result<TransactionImportResult, Error> {
// keep the pending nonces up to date
if let Ok(ref sender) = transaction.sender() {
let nonce = self.last_nonce(sender).unwrap_or(chain.latest_nonce(sender));
self.last_nonces.write().insert(sender.clone(), nonce + U256::from(1));
}
// lets assume that all txs are valid
self.imported_transactions.lock().push(transaction);
Ok(TransactionImportResult::Current)
}
/// Returns hashes of transactions currently in pending
fn pending_transactions_hashes(&self, _best_block: BlockNumber) -> Vec<H256> {
vec![]
}
/// Removes all transactions from the queue and restart mining operation.
fn clear_and_reset(&self, _chain: &MiningBlockChainClient) {
unimplemented!();
}
/// Called when blocks are imported to chain, updates transactions queue.
fn chain_new_blocks(&self, _chain: &MiningBlockChainClient, _imported: &[H256], _invalid: &[H256], _enacted: &[H256], _retracted: &[H256]) {
unimplemented!();
}
/// New chain head event. Restart mining operation.
fn update_sealing(&self, _chain: &MiningBlockChainClient) {
unimplemented!();
}
fn map_sealing_work<F, T>(&self, chain: &MiningBlockChainClient, f: F) -> Option<T> where F: FnOnce(&ClosedBlock) -> T {
let open_block = chain.prepare_open_block(self.author(), *self.gas_range_target.write(), self.extra_data());
Some(f(&open_block.close()))
}
|
fn all_transactions(&self) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_transactions(&self, _best_block: BlockNumber) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_receipt(&self, _best_block: BlockNumber, hash: &H256) -> Option<RichReceipt> {
// Not much point implementing this since the logic is complex and the only thing it relies on is pending_receipts, which is already tested.
self.pending_receipts(0).get(hash).map(|r|
RichReceipt {
transaction_hash: Default::default(),
transaction_index: Default::default(),
cumulative_gas_used: r.gas_used.clone(),
gas_used: r.gas_used.clone(),
contract_address: None,
logs: r.logs.clone(),
}
)
}
fn pending_receipts(&self, _best_block: BlockNumber) -> BTreeMap<H256, Receipt> {
self.pending_receipts.lock().clone()
}
fn last_nonce(&self, address: &Address) -> Option<U256> {
self.last_nonces.read().get(address).cloned()
}
fn is_sealing(&self) -> bool {
false
}
/// Submit `seal` as a valid solution for the header of `pow_hash`.
/// Will check the seal, but not actually insert the block into the chain.
fn submit_seal(&self, _chain: &MiningBlockChainClient, _pow_hash: H256, _seal: Vec<Bytes>) -> Result<(), Error> {
unimplemented!();
}
fn balance(&self, _chain: &MiningBlockChainClient, address: &Address) -> U256 {
self.latest_closed_block.lock().as_ref().map_or_else(U256::zero, |b| b.block().fields().state.balance(address).clone())
}
fn call(&self, _chain: &MiningBlockChainClient, _t: &SignedTransaction, _analytics: CallAnalytics) -> Result<Executed, CallError> {
unimplemented!();
}
fn storage_at(&self, _chain: &MiningBlockChainClient, address: &Address, position: &H256) -> H256 {
self.latest_closed_block.lock().as_ref().map_or_else(H256::default, |b| b.block().fields().state.storage_at(address, position).clone())
}
fn nonce(&self, _chain: &MiningBlockChainClient, address: &Address) -> U256 {
// we assume all transactions are in a pending block, ignoring the
// reality of gas limits.
self.last_nonce(address).unwrap_or(U256::zero())
}
fn code(&self, _chain: &MiningBlockChainClient, address: &Address) -> Option<Bytes> {
self.latest_closed_block.lock().as_ref().map_or(None, |b| b.block().fields().state.code(address).map(|c| (*c).clone()))
}
}
|
fn transaction(&self, _best_block: BlockNumber, hash: &H256) -> Option<SignedTransaction> {
self.pending_transactions.lock().get(hash).cloned()
}
|
random_line_split
|
miner_service.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Test implementation of miner service.
use util::{Address, H256, Bytes, U256, FixedHash, Uint};
use util::standard::*;
use ethcore::error::{Error, CallError};
use ethcore::client::{MiningBlockChainClient, Executed, CallAnalytics};
use ethcore::block::{ClosedBlock, IsBlock};
use ethcore::header::BlockNumber;
use ethcore::transaction::SignedTransaction;
use ethcore::receipt::{Receipt, RichReceipt};
use ethcore::miner::{MinerService, MinerStatus, TransactionImportResult};
/// Test miner service.
pub struct TestMinerService {
/// Imported transactions.
pub imported_transactions: Mutex<Vec<SignedTransaction>>,
/// Latest closed block.
pub latest_closed_block: Mutex<Option<ClosedBlock>>,
/// Pre-existed pending transactions
pub pending_transactions: Mutex<HashMap<H256, SignedTransaction>>,
/// Pre-existed pending receipts
pub pending_receipts: Mutex<BTreeMap<H256, Receipt>>,
/// Last nonces.
pub last_nonces: RwLock<HashMap<Address, U256>>,
min_gas_price: RwLock<U256>,
gas_range_target: RwLock<(U256, U256)>,
author: RwLock<Address>,
extra_data: RwLock<Bytes>,
limit: RwLock<usize>,
tx_gas_limit: RwLock<U256>,
}
impl Default for TestMinerService {
fn default() -> TestMinerService {
TestMinerService {
imported_transactions: Mutex::new(Vec::new()),
latest_closed_block: Mutex::new(None),
pending_transactions: Mutex::new(HashMap::new()),
pending_receipts: Mutex::new(BTreeMap::new()),
last_nonces: RwLock::new(HashMap::new()),
min_gas_price: RwLock::new(U256::from(20_000_000)),
gas_range_target: RwLock::new((U256::from(12345), U256::from(54321))),
author: RwLock::new(Address::zero()),
extra_data: RwLock::new(vec![1, 2, 3, 4]),
limit: RwLock::new(1024),
tx_gas_limit: RwLock::new(!U256::zero()),
}
}
}
impl MinerService for TestMinerService {
/// Returns miner's status.
fn status(&self) -> MinerStatus {
MinerStatus {
transactions_in_pending_queue: 0,
transactions_in_future_queue: 0,
transactions_in_pending_block: 1
}
}
fn set_author(&self, author: Address) {
*self.author.write() = author;
}
fn set_extra_data(&self, extra_data: Bytes) {
*self.extra_data.write() = extra_data;
}
/// Set the lower gas limit we wish to target when sealing a new block.
fn set_gas_floor_target(&self, target: U256) {
self.gas_range_target.write().0 = target;
}
/// Set the upper gas limit we wish to target when sealing a new block.
fn set_gas_ceil_target(&self, target: U256) {
self.gas_range_target.write().1 = target;
}
fn set_minimal_gas_price(&self, min_gas_price: U256) {
*self.min_gas_price.write() = min_gas_price;
}
fn set_transactions_limit(&self, limit: usize) {
*self.limit.write() = limit;
}
fn set_tx_gas_limit(&self, limit: U256) {
*self.tx_gas_limit.write() = limit;
}
fn transactions_limit(&self) -> usize {
*self.limit.read()
}
fn author(&self) -> Address {
*self.author.read()
}
fn minimal_gas_price(&self) -> U256 {
*self.min_gas_price.read()
}
fn extra_data(&self) -> Bytes {
self.extra_data.read().clone()
}
fn gas_floor_target(&self) -> U256 {
self.gas_range_target.read().0
}
fn gas_ceil_target(&self) -> U256 {
self.gas_range_target.read().1
}
/// Imports transactions to transaction queue.
fn import_external_transactions(&self, _chain: &MiningBlockChainClient, transactions: Vec<SignedTransaction>) ->
Vec<Result<TransactionImportResult, Error>> {
// lets assume that all txs are valid
self.imported_transactions.lock().extend_from_slice(&transactions);
for sender in transactions.iter().filter_map(|t| t.sender().ok()) {
let nonce = self.last_nonce(&sender).expect("last_nonce must be populated in tests");
self.last_nonces.write().insert(sender, nonce + U256::from(1));
}
transactions
.iter()
.map(|_| Ok(TransactionImportResult::Current))
.collect()
}
/// Imports transactions to transaction queue.
fn import_own_transaction(&self, chain: &MiningBlockChainClient, transaction: SignedTransaction) ->
Result<TransactionImportResult, Error> {
// keep the pending nonces up to date
if let Ok(ref sender) = transaction.sender()
|
// lets assume that all txs are valid
self.imported_transactions.lock().push(transaction);
Ok(TransactionImportResult::Current)
}
/// Returns hashes of transactions currently in pending
fn pending_transactions_hashes(&self, _best_block: BlockNumber) -> Vec<H256> {
vec![]
}
/// Removes all transactions from the queue and restart mining operation.
fn clear_and_reset(&self, _chain: &MiningBlockChainClient) {
unimplemented!();
}
/// Called when blocks are imported to chain, updates transactions queue.
fn chain_new_blocks(&self, _chain: &MiningBlockChainClient, _imported: &[H256], _invalid: &[H256], _enacted: &[H256], _retracted: &[H256]) {
unimplemented!();
}
/// New chain head event. Restart mining operation.
fn update_sealing(&self, _chain: &MiningBlockChainClient) {
unimplemented!();
}
fn map_sealing_work<F, T>(&self, chain: &MiningBlockChainClient, f: F) -> Option<T> where F: FnOnce(&ClosedBlock) -> T {
let open_block = chain.prepare_open_block(self.author(), *self.gas_range_target.write(), self.extra_data());
Some(f(&open_block.close()))
}
fn transaction(&self, _best_block: BlockNumber, hash: &H256) -> Option<SignedTransaction> {
self.pending_transactions.lock().get(hash).cloned()
}
fn all_transactions(&self) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_transactions(&self, _best_block: BlockNumber) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_receipt(&self, _best_block: BlockNumber, hash: &H256) -> Option<RichReceipt> {
// Not much point implementing this since the logic is complex and the only thing it relies on is pending_receipts, which is already tested.
self.pending_receipts(0).get(hash).map(|r|
RichReceipt {
transaction_hash: Default::default(),
transaction_index: Default::default(),
cumulative_gas_used: r.gas_used.clone(),
gas_used: r.gas_used.clone(),
contract_address: None,
logs: r.logs.clone(),
}
)
}
fn pending_receipts(&self, _best_block: BlockNumber) -> BTreeMap<H256, Receipt> {
self.pending_receipts.lock().clone()
}
fn last_nonce(&self, address: &Address) -> Option<U256> {
self.last_nonces.read().get(address).cloned()
}
fn is_sealing(&self) -> bool {
false
}
/// Submit `seal` as a valid solution for the header of `pow_hash`.
/// Will check the seal, but not actually insert the block into the chain.
fn submit_seal(&self, _chain: &MiningBlockChainClient, _pow_hash: H256, _seal: Vec<Bytes>) -> Result<(), Error> {
unimplemented!();
}
fn balance(&self, _chain: &MiningBlockChainClient, address: &Address) -> U256 {
self.latest_closed_block.lock().as_ref().map_or_else(U256::zero, |b| b.block().fields().state.balance(address).clone())
}
fn call(&self, _chain: &MiningBlockChainClient, _t: &SignedTransaction, _analytics: CallAnalytics) -> Result<Executed, CallError> {
unimplemented!();
}
fn storage_at(&self, _chain: &MiningBlockChainClient, address: &Address, position: &H256) -> H256 {
self.latest_closed_block.lock().as_ref().map_or_else(H256::default, |b| b.block().fields().state.storage_at(address, position).clone())
}
fn nonce(&self, _chain: &MiningBlockChainClient, address: &Address) -> U256 {
// we assume all transactions are in a pending block, ignoring the
// reality of gas limits.
self.last_nonce(address).unwrap_or(U256::zero())
}
fn code(&self, _chain: &MiningBlockChainClient, address: &Address) -> Option<Bytes> {
self.latest_closed_block.lock().as_ref().map_or(None, |b| b.block().fields().state.code(address).map(|c| (*c).clone()))
}
}
|
{
let nonce = self.last_nonce(sender).unwrap_or(chain.latest_nonce(sender));
self.last_nonces.write().insert(sender.clone(), nonce + U256::from(1));
}
|
conditional_block
|
miner_service.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
//! Test implementation of miner service.
use util::{Address, H256, Bytes, U256, FixedHash, Uint};
use util::standard::*;
use ethcore::error::{Error, CallError};
use ethcore::client::{MiningBlockChainClient, Executed, CallAnalytics};
use ethcore::block::{ClosedBlock, IsBlock};
use ethcore::header::BlockNumber;
use ethcore::transaction::SignedTransaction;
use ethcore::receipt::{Receipt, RichReceipt};
use ethcore::miner::{MinerService, MinerStatus, TransactionImportResult};
/// Test miner service.
pub struct TestMinerService {
/// Imported transactions.
pub imported_transactions: Mutex<Vec<SignedTransaction>>,
/// Latest closed block.
pub latest_closed_block: Mutex<Option<ClosedBlock>>,
/// Pre-existed pending transactions
pub pending_transactions: Mutex<HashMap<H256, SignedTransaction>>,
/// Pre-existed pending receipts
pub pending_receipts: Mutex<BTreeMap<H256, Receipt>>,
/// Last nonces.
pub last_nonces: RwLock<HashMap<Address, U256>>,
min_gas_price: RwLock<U256>,
gas_range_target: RwLock<(U256, U256)>,
author: RwLock<Address>,
extra_data: RwLock<Bytes>,
limit: RwLock<usize>,
tx_gas_limit: RwLock<U256>,
}
impl Default for TestMinerService {
fn default() -> TestMinerService {
TestMinerService {
imported_transactions: Mutex::new(Vec::new()),
latest_closed_block: Mutex::new(None),
pending_transactions: Mutex::new(HashMap::new()),
pending_receipts: Mutex::new(BTreeMap::new()),
last_nonces: RwLock::new(HashMap::new()),
min_gas_price: RwLock::new(U256::from(20_000_000)),
gas_range_target: RwLock::new((U256::from(12345), U256::from(54321))),
author: RwLock::new(Address::zero()),
extra_data: RwLock::new(vec![1, 2, 3, 4]),
limit: RwLock::new(1024),
tx_gas_limit: RwLock::new(!U256::zero()),
}
}
}
impl MinerService for TestMinerService {
/// Returns miner's status.
fn status(&self) -> MinerStatus {
MinerStatus {
transactions_in_pending_queue: 0,
transactions_in_future_queue: 0,
transactions_in_pending_block: 1
}
}
fn set_author(&self, author: Address) {
*self.author.write() = author;
}
fn
|
(&self, extra_data: Bytes) {
*self.extra_data.write() = extra_data;
}
/// Set the lower gas limit we wish to target when sealing a new block.
fn set_gas_floor_target(&self, target: U256) {
self.gas_range_target.write().0 = target;
}
/// Set the upper gas limit we wish to target when sealing a new block.
fn set_gas_ceil_target(&self, target: U256) {
self.gas_range_target.write().1 = target;
}
fn set_minimal_gas_price(&self, min_gas_price: U256) {
*self.min_gas_price.write() = min_gas_price;
}
fn set_transactions_limit(&self, limit: usize) {
*self.limit.write() = limit;
}
fn set_tx_gas_limit(&self, limit: U256) {
*self.tx_gas_limit.write() = limit;
}
fn transactions_limit(&self) -> usize {
*self.limit.read()
}
fn author(&self) -> Address {
*self.author.read()
}
fn minimal_gas_price(&self) -> U256 {
*self.min_gas_price.read()
}
fn extra_data(&self) -> Bytes {
self.extra_data.read().clone()
}
fn gas_floor_target(&self) -> U256 {
self.gas_range_target.read().0
}
fn gas_ceil_target(&self) -> U256 {
self.gas_range_target.read().1
}
/// Imports transactions to transaction queue.
fn import_external_transactions(&self, _chain: &MiningBlockChainClient, transactions: Vec<SignedTransaction>) ->
Vec<Result<TransactionImportResult, Error>> {
// lets assume that all txs are valid
self.imported_transactions.lock().extend_from_slice(&transactions);
for sender in transactions.iter().filter_map(|t| t.sender().ok()) {
let nonce = self.last_nonce(&sender).expect("last_nonce must be populated in tests");
self.last_nonces.write().insert(sender, nonce + U256::from(1));
}
transactions
.iter()
.map(|_| Ok(TransactionImportResult::Current))
.collect()
}
/// Imports transactions to transaction queue.
fn import_own_transaction(&self, chain: &MiningBlockChainClient, transaction: SignedTransaction) ->
Result<TransactionImportResult, Error> {
// keep the pending nonces up to date
if let Ok(ref sender) = transaction.sender() {
let nonce = self.last_nonce(sender).unwrap_or(chain.latest_nonce(sender));
self.last_nonces.write().insert(sender.clone(), nonce + U256::from(1));
}
// lets assume that all txs are valid
self.imported_transactions.lock().push(transaction);
Ok(TransactionImportResult::Current)
}
/// Returns hashes of transactions currently in pending
fn pending_transactions_hashes(&self, _best_block: BlockNumber) -> Vec<H256> {
vec![]
}
/// Removes all transactions from the queue and restart mining operation.
fn clear_and_reset(&self, _chain: &MiningBlockChainClient) {
unimplemented!();
}
/// Called when blocks are imported to chain, updates transactions queue.
fn chain_new_blocks(&self, _chain: &MiningBlockChainClient, _imported: &[H256], _invalid: &[H256], _enacted: &[H256], _retracted: &[H256]) {
unimplemented!();
}
/// New chain head event. Restart mining operation.
fn update_sealing(&self, _chain: &MiningBlockChainClient) {
unimplemented!();
}
fn map_sealing_work<F, T>(&self, chain: &MiningBlockChainClient, f: F) -> Option<T> where F: FnOnce(&ClosedBlock) -> T {
let open_block = chain.prepare_open_block(self.author(), *self.gas_range_target.write(), self.extra_data());
Some(f(&open_block.close()))
}
fn transaction(&self, _best_block: BlockNumber, hash: &H256) -> Option<SignedTransaction> {
self.pending_transactions.lock().get(hash).cloned()
}
fn all_transactions(&self) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_transactions(&self, _best_block: BlockNumber) -> Vec<SignedTransaction> {
self.pending_transactions.lock().values().cloned().collect()
}
fn pending_receipt(&self, _best_block: BlockNumber, hash: &H256) -> Option<RichReceipt> {
// Not much point implementing this since the logic is complex and the only thing it relies on is pending_receipts, which is already tested.
self.pending_receipts(0).get(hash).map(|r|
RichReceipt {
transaction_hash: Default::default(),
transaction_index: Default::default(),
cumulative_gas_used: r.gas_used.clone(),
gas_used: r.gas_used.clone(),
contract_address: None,
logs: r.logs.clone(),
}
)
}
fn pending_receipts(&self, _best_block: BlockNumber) -> BTreeMap<H256, Receipt> {
self.pending_receipts.lock().clone()
}
fn last_nonce(&self, address: &Address) -> Option<U256> {
self.last_nonces.read().get(address).cloned()
}
fn is_sealing(&self) -> bool {
false
}
/// Submit `seal` as a valid solution for the header of `pow_hash`.
/// Will check the seal, but not actually insert the block into the chain.
fn submit_seal(&self, _chain: &MiningBlockChainClient, _pow_hash: H256, _seal: Vec<Bytes>) -> Result<(), Error> {
unimplemented!();
}
fn balance(&self, _chain: &MiningBlockChainClient, address: &Address) -> U256 {
self.latest_closed_block.lock().as_ref().map_or_else(U256::zero, |b| b.block().fields().state.balance(address).clone())
}
fn call(&self, _chain: &MiningBlockChainClient, _t: &SignedTransaction, _analytics: CallAnalytics) -> Result<Executed, CallError> {
unimplemented!();
}
fn storage_at(&self, _chain: &MiningBlockChainClient, address: &Address, position: &H256) -> H256 {
self.latest_closed_block.lock().as_ref().map_or_else(H256::default, |b| b.block().fields().state.storage_at(address, position).clone())
}
fn nonce(&self, _chain: &MiningBlockChainClient, address: &Address) -> U256 {
// we assume all transactions are in a pending block, ignoring the
// reality of gas limits.
self.last_nonce(address).unwrap_or(U256::zero())
}
fn code(&self, _chain: &MiningBlockChainClient, address: &Address) -> Option<Bytes> {
self.latest_closed_block.lock().as_ref().map_or(None, |b| b.block().fields().state.code(address).map(|c| (*c).clone()))
}
}
|
set_extra_data
|
identifier_name
|
windows.rs
|
);
1
}
winapi::CTRL_BREAK_EVENT => {
write_fake_key(SIGQUIT_KEY);
1
}
winapi::CTRL_CLOSE_EVENT => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
0
}
_ => 0,
}
}
match unsafe { kernel32::SetConsoleCtrlHandler(Some(handler), 1) } {
0 => Error::ffi_err("SetConsoleCtrlHandler failed"),
_ => Ok(()),
}
}
// winapi-rs omits this.
#[allow(non_snake_case)]
#[repr(C)]
struct WNDCLASS {
pub style: winapi::UINT,
pub lpfnWndProc: winapi::WNDPROC,
pub cbClsExtra: winapi::c_int,
pub cbWndExtra: winapi::c_int,
pub instance: winapi::HINSTANCE,
pub hIcon: winapi::HICON,
pub hCursor: winapi::HCURSOR,
pub hbrBackground: winapi::HBRUSH,
pub lpszMenuName: winapi::LPCSTR,
pub lpszClassName: winapi::LPCSTR,
}
// winapi-rs omits this.
extern "system" {
fn RegisterClassA(lpWndClass: *const WNDCLASS) -> winapi::ATOM;
}
unsafe fn create_session_wnd() -> Result<()> {
extern "system" fn wnd_proc(
hwnd: winapi::HWND,
msg: winapi::UINT,
wparam: winapi::WPARAM,
lparam: winapi::LPARAM,
) -> winapi::LRESULT {
match msg {
winapi::WM_ENDSESSION => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
0
}
_ => unsafe {
user32::DefWindowProcA(hwnd, msg, wparam, lparam)
},
}
}
let mut wnd_class: WNDCLASS = ::std::mem::zeroed();
wnd_class.lpfnWndProc = Some(wnd_proc);
wnd_class.instance = kernel32::GetModuleHandleA(ptr::null());
if wnd_class.instance.is_null() {
return Error::ffi_err("GetModuleHandle failed");
}
wnd_class.lpszClassName =
"HiddenShutdownClass\x00".as_ptr() as *const _ as winapi::LPCSTR;
if 0 == RegisterClassA(&wnd_class) {
return Error::ffi_err("RegisterClass failed");
}
let hwnd = user32::CreateWindowExA(
0,
"HiddenShutdownClass\x00".as_ptr() as *const _ as winapi::LPCSTR,
ptr::null(),
0,
0,
0,
0,
0,
ptr::null_mut(),
ptr::null_mut(),
kernel32::GetModuleHandleA(ptr::null()),
ptr::null_mut(),
);
if hwnd.is_null() {
return Error::ffi_err("CreateWindowEx failed");
}
Ok(())
}
fn register_layout_hook() -> Result<()> {
extern "system" fn layout_hook(
_: winapi::HWINEVENTHOOK,
_: winapi::DWORD,
hwnd: winapi::HWND,
_: winapi::LONG,
_: winapi::LONG,
_: winapi::DWORD,
_: winapi::DWORD,
) {
// Filter out events from consoles in other processes.
if hwnd!= unsafe { kernel32::GetConsoleWindow() } {
return;
}
// Use an "empty" window buffer size event as a resize
// notification.
let mut ir: winapi::INPUT_RECORD =
unsafe { ::std::mem::uninitialized() };
ir.EventType = winapi::WINDOW_BUFFER_SIZE_EVENT;
{
let ir = unsafe { ir.WindowBufferSizeEvent_mut() };
ir.dwSize.X = 0;
ir.dwSize.Y = 0;
}
let con_hndl = Handle::Stdin.win_handle();
let mut write_count: winapi::DWORD = 0;
unsafe {
kernel32::WriteConsoleInputW(con_hndl, &ir, 1, &mut write_count);
}
}
let hook = unsafe {
user32::SetWinEventHook(
EVENT_CONSOLE_LAYOUT,
EVENT_CONSOLE_LAYOUT,
ptr::null_mut(),
Some(layout_hook),
// Listen for events from all threads/processes and filter
// in the callback, because there doesn't seem to be a way
// to get the id for the thread that actually delivers
// WinEvents for the console (it's not the thread returned
// by GetWindowThreadProcessId(GetConsoleWindow())).
0,
0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNTHREAD,
)
};
if hook.is_null() {
return Error::ffi_err("SetWinEventHook failed");
}
Ok(())
}
// Windows events and WinEvents require a thread with a message pump.
unsafe fn run_message_pump() {
let mut msg: winapi::MSG = ::std::mem::uninitialized();
while 0!= user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) {
user32::TranslateMessage(&msg);
user32::DispatchMessageW(&msg);
}
}
fn write_fake_key(key_code: u16) -> winapi::BOOL {
let mut key: winapi::INPUT_RECORD =
unsafe { ::std::mem::uninitialized() };
key.EventType = winapi::KEY_EVENT;
{
let key = unsafe { key.KeyEvent_mut() };
key.bKeyDown = 1;
key.wVirtualKeyCode = key_code;
}
let con_hndl = Handle::Stdin.win_handle();
let mut write_count: winapi::DWORD = 0;
unsafe {
kernel32::WriteConsoleInputW(con_hndl, &key, 1, &mut write_count)
}
}
fn raw_event_loop(tx: Sender<Box<Event>>) {
// TODO: Handle FFI errors/channel send errors (until then, just
// exit when the event loop exits).
let _ = event_loop(tx);
}
#[cfg_attr(feature = "cargo-clippy",
allow(needless_range_loop, needless_pass_by_value))]
fn event_loop(tx: Sender<Box<Event>>) -> Result<()> {
let mut resizer = Resizer::from_conout()?;
let in_hndl = Handle::Stdin.win_handle();
let mut buffer: [winapi::INPUT_RECORD; 128] =
unsafe { ::std::mem::uninitialized() };
let mut key_reader = KeyReader::new(tx.clone());
let mut mouse_reader = MouseReader::new(tx.clone());
loop {
let mut read_count: winapi::DWORD = 0;
unsafe {
if kernel32::ReadConsoleInputW(
in_hndl,
buffer.as_mut_ptr(),
128,
&mut read_count,
) == 0
{
return Error::ffi_err("ReadConsoleInputW failed");
}
}
for i in 0..read_count as usize {
let input = buffer[i];
if input.EventType == winapi::FOCUS_EVENT
|| input.EventType == winapi::MENU_EVENT
{
continue;
}
match input.EventType {
winapi::MOUSE_EVENT => {
let mevt = unsafe { input.MouseEvent() };
mouse_reader.read(mevt)?
}
winapi::KEY_EVENT => {
let kevt = unsafe { input.KeyEvent() };
match kevt.wVirtualKeyCode {
SHUTDOWN_KEY => return Ok(()),
SIGINT_KEY => tx.send(Box::new(InputEvent::Interrupt))?,
SIGQUIT_KEY => tx.send(Box::new(InputEvent::Break))?,
_ => key_reader.read(kevt)?,
}
}
winapi::WINDOW_BUFFER_SIZE_EVENT => if resizer.update()? {
tx.send(Box::new(InputEvent::Repaint))?;
},
_ => unreachable!(),
};
}
}
}
struct KeyReader {
surrogate: Option<u16>,
tx: Sender<Box<Event>>,
}
impl KeyReader {
fn new(tx: Sender<Box<Event>>) -> KeyReader {
KeyReader {
surrogate: None,
tx,
}
}
fn send(&self, event: InputEvent) -> Result<()> {
self.tx.send(Box::new(event))?;
Ok(())
}
fn read(&mut self, evt: &KEY_EVENT_RECORD) -> Result<()> {
if self.surrogate_pair(evt)? {
return Ok(());
}
if evt.bKeyDown == 0 {
return Ok(());
}
if self.special_key(evt)? {
return Ok(());
}
self.key(evt)
}
fn surrogate_pair(&mut self, evt: &KEY_EVENT_RECORD) -> Result<bool> {
let s2 = u32::from(evt.UnicodeChar);
if let Some(s1) = self.surrogate.take() {
if s2 >= 0xdc00 && s2 <= 0xdfff {
let s1 = u32::from(s1);
let mut utf8 = [0u8; 4];
let c: u32 = 0x1_0000 | ((s1 - 0xd800) << 10) | (s2 - 0xdc00);
let c = ::std::char::from_u32(c).unwrap();
let len = c.encode_utf8(&mut utf8).len();
let kevt = InputEvent::Key(
Key::Char(c, utf8, len),
Mods::win32(evt.dwControlKeyState),
);
self.send(kevt)?;
return Ok(true);
} else {
let err = Key::Err(
[
0xe0 | (s2 >> 12) as u8,
0x80 | ((s2 >> 6) & 0x3f) as u8,
0x80 | (s2 & 0x3f) as u8,
0,
],
3,
);
self.send(InputEvent::Key(err, Mods::empty()))?;
}
}
if s2 >= 0xd800 && s2 <= 0xdbff {
self.surrogate = Some(s2 as u16);
return Ok(true);
}
Ok(false)
}
fn special_key(&self, evt: &KEY_EVENT_RECORD) -> Result<bool> {
let skey = match evt.wVirtualKeyCode {
0x08 => Key::BS,
0x09 => Key::Tab,
0x0d => Key::Enter,
0x1b => Key::Esc,
0x21 => Key::PgUp,
0x22 => Key::PgDn,
0x23 => Key::End,
0x24 => Key::Home,
0x25 => Key::Left,
0x26 => Key::Up,
0x27 => Key::Right,
0x28 => Key::Down,
0x2d => Key::Ins,
0x2e => Key::Del,
0x70 => Key::F1,
0x71 => Key::F2,
0x72 => Key::F3,
0x73 => Key::F4,
0x74 => Key::F5,
0x75 => Key::F6,
0x76 => Key::F7,
0x77 => Key::F8,
0x78 => Key::F9,
0x79 => Key::F10,
0x7a => Key::F11,
0x7b => Key::F12,
_ => return Ok(false),
};
self.send(InputEvent::Key(skey, Mods::win32(evt.dwControlKeyState)))?;
Ok(true)
}
fn key(&self, evt: &KEY_EVENT_RECORD) -> Result<()> {
use std::char;
use input::Mods;
let uc = evt.UnicodeChar;
let mods = Mods::win32(evt.dwControlKeyState);
let (key, mods) = if uc == 0 {
return Ok(());
} else if uc < 0x80 {
match uc {
3 => return self.send(InputEvent::Interrupt),
8 => (Key::BS, mods - Mods::CTRL),
9 => (Key::Tab, mods - Mods::CTRL),
13 => (Key::Enter, mods - Mods::CTRL),
27 => (Key::Esc, mods - Mods::CTRL),
b if b < 32 => (Key::ascii(b as u8 + 64), mods | Mods::CTRL),
_ => (Key::ascii(uc as u8), mods),
}
} else if uc < 0x800 {
(
Key::Char(
unsafe { char::from_u32_unchecked(uc as u32) },
[0xc0 | (uc >> 6) as u8, 0x80 | (uc & 0x3f) as u8, 0, 0],
2,
),
mods,
)
} else {
// Surrogate pairs have already been handled.
(
Key::Char(
unsafe { char::from_u32_unchecked(uc as u32) },
[
0xe0 | (uc >> 12) as u8,
0x80 | ((uc >> 6) & 0x3f) as u8,
0x80 | (uc & 0x3f) as u8,
0,
],
3,
),
mods,
)
};
self.send(InputEvent::Key(key, mods))?;
Ok(())
}
}
bitflags! {
#[derive(Default)]
pub struct Btn: u32 {
const LEFT = 0x01;
const RIGHT = 0x02;
const MIDDLE = 0x04;
}
}
pub struct MouseReader {
tx: Sender<Box<Event>>,
coords: (i32, i32),
btns: Btn,
}
impl MouseReader {
fn new(tx: Sender<Box<Event>>) -> MouseReader {
MouseReader {
tx,
coords: (-1, -1),
btns: Btn::empty(),
}
}
fn send(&self, event: InputEvent) -> Result<()> {
self.tx.send(Box::new(event))?;
Ok(())
}
fn read(&mut self, evt: &winapi::MOUSE_EVENT_RECORD) -> Result<()> {
use input::ButtonMotion::*;
use input::MouseButton::*;
use input::WheelMotion::*;
let coords = (
(evt.dwMousePosition.X as u16),
(evt.dwMousePosition.Y as u16),
);
let mods = Mods::win32(evt.dwControlKeyState);
match evt.dwEventFlags {
0 | 2 => {
let new_btns = Btn::from_bits(evt.dwButtonState & 0x7).unwrap();
let presses = new_btns - self.btns;
let releases = self.btns - new_btns;
self.btns = new_btns;
if presses.contains(Btn::LEFT) {
let mevt = InputEvent::Mouse(Press, Left, mods, coords);
self.send(mevt)?;
}
if presses.contains(Btn::MIDDLE) {
let mevt = InputEvent::Mouse(Press, Middle, mods, coords);
self.send(mevt)?;
}
if presses.contains(Btn::RIGHT) {
let mevt = InputEvent::Mouse(Press, Right, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::LEFT) {
let mevt = InputEvent::Mouse(Release, Left, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::MIDDLE) {
let mevt = InputEvent::Mouse(Release, Middle, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::RIGHT) {
let mevt = InputEvent::Mouse(Release, Right, mods, coords);
self.send(mevt)?;
}
}
1 => if (i32::from(coords.0), i32::from(coords.1))!= self.coords {
let mevt = InputEvent::MouseMove(mods, coords);
self.send(mevt)?;
},
4 => {
let mevt = if (evt.dwButtonState >> 16) < 0x8000 {
InputEvent::MouseWheel(Up, mods, coords)
} else {
InputEvent::MouseWheel(Down, mods, coords)
};
self.send(mevt)?;
}
_ => (),
}
self.coords = (i32::from(coords.0), i32::from(coords.1));
Ok(())
}
}
pub(crate) struct
|
{
hndl: winapi::HANDLE,
size: winapi::COORD,
}
impl Resizer {
fn from_conout() -> Result<Resizer> {
let hndl = unsafe {
kernel32::CreateFileA(
"CONOUT$\x00".as_ptr() as *const _ as winapi::LPCSTR,
winapi::GENERIC_READ | winapi::GENERIC_WRITE,
winapi::FILE_SHARE_READ | winapi::FILE_SHARE_WRITE,
ptr::null_mut(),
|
Resizer
|
identifier_name
|
windows.rs
|
_KEY);
1
}
winapi::CTRL_BREAK_EVENT => {
write_fake_key(SIGQUIT_KEY);
1
}
winapi::CTRL_CLOSE_EVENT => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
0
}
_ => 0,
}
}
match unsafe { kernel32::SetConsoleCtrlHandler(Some(handler), 1) } {
0 => Error::ffi_err("SetConsoleCtrlHandler failed"),
_ => Ok(()),
}
}
// winapi-rs omits this.
#[allow(non_snake_case)]
#[repr(C)]
struct WNDCLASS {
pub style: winapi::UINT,
pub lpfnWndProc: winapi::WNDPROC,
pub cbClsExtra: winapi::c_int,
pub cbWndExtra: winapi::c_int,
pub instance: winapi::HINSTANCE,
pub hIcon: winapi::HICON,
pub hCursor: winapi::HCURSOR,
pub hbrBackground: winapi::HBRUSH,
pub lpszMenuName: winapi::LPCSTR,
pub lpszClassName: winapi::LPCSTR,
}
// winapi-rs omits this.
extern "system" {
fn RegisterClassA(lpWndClass: *const WNDCLASS) -> winapi::ATOM;
}
unsafe fn create_session_wnd() -> Result<()> {
extern "system" fn wnd_proc(
hwnd: winapi::HWND,
msg: winapi::UINT,
wparam: winapi::WPARAM,
lparam: winapi::LPARAM,
) -> winapi::LRESULT {
match msg {
winapi::WM_ENDSESSION => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
0
}
_ => unsafe {
user32::DefWindowProcA(hwnd, msg, wparam, lparam)
},
}
}
let mut wnd_class: WNDCLASS = ::std::mem::zeroed();
wnd_class.lpfnWndProc = Some(wnd_proc);
wnd_class.instance = kernel32::GetModuleHandleA(ptr::null());
if wnd_class.instance.is_null() {
return Error::ffi_err("GetModuleHandle failed");
}
wnd_class.lpszClassName =
"HiddenShutdownClass\x00".as_ptr() as *const _ as winapi::LPCSTR;
if 0 == RegisterClassA(&wnd_class) {
return Error::ffi_err("RegisterClass failed");
}
let hwnd = user32::CreateWindowExA(
0,
"HiddenShutdownClass\x00".as_ptr() as *const _ as winapi::LPCSTR,
ptr::null(),
0,
0,
0,
0,
0,
ptr::null_mut(),
ptr::null_mut(),
kernel32::GetModuleHandleA(ptr::null()),
ptr::null_mut(),
);
if hwnd.is_null() {
return Error::ffi_err("CreateWindowEx failed");
}
Ok(())
}
fn register_layout_hook() -> Result<()> {
extern "system" fn layout_hook(
_: winapi::HWINEVENTHOOK,
_: winapi::DWORD,
hwnd: winapi::HWND,
_: winapi::LONG,
_: winapi::LONG,
_: winapi::DWORD,
_: winapi::DWORD,
) {
// Filter out events from consoles in other processes.
if hwnd!= unsafe { kernel32::GetConsoleWindow() } {
return;
}
// Use an "empty" window buffer size event as a resize
// notification.
let mut ir: winapi::INPUT_RECORD =
unsafe { ::std::mem::uninitialized() };
ir.EventType = winapi::WINDOW_BUFFER_SIZE_EVENT;
{
let ir = unsafe { ir.WindowBufferSizeEvent_mut() };
ir.dwSize.X = 0;
ir.dwSize.Y = 0;
}
let con_hndl = Handle::Stdin.win_handle();
let mut write_count: winapi::DWORD = 0;
unsafe {
kernel32::WriteConsoleInputW(con_hndl, &ir, 1, &mut write_count);
}
}
let hook = unsafe {
user32::SetWinEventHook(
EVENT_CONSOLE_LAYOUT,
EVENT_CONSOLE_LAYOUT,
ptr::null_mut(),
Some(layout_hook),
// Listen for events from all threads/processes and filter
// in the callback, because there doesn't seem to be a way
// to get the id for the thread that actually delivers
// WinEvents for the console (it's not the thread returned
// by GetWindowThreadProcessId(GetConsoleWindow())).
0,
0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNTHREAD,
)
};
if hook.is_null() {
return Error::ffi_err("SetWinEventHook failed");
}
Ok(())
}
// Windows events and WinEvents require a thread with a message pump.
unsafe fn run_message_pump() {
let mut msg: winapi::MSG = ::std::mem::uninitialized();
while 0!= user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) {
user32::TranslateMessage(&msg);
user32::DispatchMessageW(&msg);
}
}
fn write_fake_key(key_code: u16) -> winapi::BOOL {
let mut key: winapi::INPUT_RECORD =
unsafe { ::std::mem::uninitialized() };
key.EventType = winapi::KEY_EVENT;
{
let key = unsafe { key.KeyEvent_mut() };
key.bKeyDown = 1;
key.wVirtualKeyCode = key_code;
}
let con_hndl = Handle::Stdin.win_handle();
let mut write_count: winapi::DWORD = 0;
unsafe {
kernel32::WriteConsoleInputW(con_hndl, &key, 1, &mut write_count)
}
}
fn raw_event_loop(tx: Sender<Box<Event>>) {
// TODO: Handle FFI errors/channel send errors (until then, just
// exit when the event loop exits).
let _ = event_loop(tx);
}
#[cfg_attr(feature = "cargo-clippy",
allow(needless_range_loop, needless_pass_by_value))]
fn event_loop(tx: Sender<Box<Event>>) -> Result<()> {
let mut resizer = Resizer::from_conout()?;
let in_hndl = Handle::Stdin.win_handle();
let mut buffer: [winapi::INPUT_RECORD; 128] =
unsafe { ::std::mem::uninitialized() };
let mut key_reader = KeyReader::new(tx.clone());
let mut mouse_reader = MouseReader::new(tx.clone());
loop {
let mut read_count: winapi::DWORD = 0;
unsafe {
if kernel32::ReadConsoleInputW(
in_hndl,
buffer.as_mut_ptr(),
128,
&mut read_count,
) == 0
{
return Error::ffi_err("ReadConsoleInputW failed");
}
}
for i in 0..read_count as usize {
let input = buffer[i];
if input.EventType == winapi::FOCUS_EVENT
|| input.EventType == winapi::MENU_EVENT
{
continue;
}
match input.EventType {
winapi::MOUSE_EVENT => {
let mevt = unsafe { input.MouseEvent() };
mouse_reader.read(mevt)?
}
winapi::KEY_EVENT => {
let kevt = unsafe { input.KeyEvent() };
match kevt.wVirtualKeyCode {
SHUTDOWN_KEY => return Ok(()),
SIGINT_KEY => tx.send(Box::new(InputEvent::Interrupt))?,
SIGQUIT_KEY => tx.send(Box::new(InputEvent::Break))?,
_ => key_reader.read(kevt)?,
}
}
winapi::WINDOW_BUFFER_SIZE_EVENT => if resizer.update()? {
tx.send(Box::new(InputEvent::Repaint))?;
},
_ => unreachable!(),
};
}
}
}
struct KeyReader {
surrogate: Option<u16>,
tx: Sender<Box<Event>>,
}
impl KeyReader {
fn new(tx: Sender<Box<Event>>) -> KeyReader {
KeyReader {
surrogate: None,
tx,
}
}
fn send(&self, event: InputEvent) -> Result<()> {
self.tx.send(Box::new(event))?;
Ok(())
}
fn read(&mut self, evt: &KEY_EVENT_RECORD) -> Result<()> {
if self.surrogate_pair(evt)? {
return Ok(());
}
if evt.bKeyDown == 0 {
return Ok(());
}
if self.special_key(evt)? {
return Ok(());
}
self.key(evt)
}
fn surrogate_pair(&mut self, evt: &KEY_EVENT_RECORD) -> Result<bool> {
let s2 = u32::from(evt.UnicodeChar);
if let Some(s1) = self.surrogate.take() {
if s2 >= 0xdc00 && s2 <= 0xdfff {
let s1 = u32::from(s1);
let mut utf8 = [0u8; 4];
let c: u32 = 0x1_0000 | ((s1 - 0xd800) << 10) | (s2 - 0xdc00);
let c = ::std::char::from_u32(c).unwrap();
let len = c.encode_utf8(&mut utf8).len();
let kevt = InputEvent::Key(
Key::Char(c, utf8, len),
Mods::win32(evt.dwControlKeyState),
);
self.send(kevt)?;
return Ok(true);
} else {
let err = Key::Err(
[
0xe0 | (s2 >> 12) as u8,
0x80 | ((s2 >> 6) & 0x3f) as u8,
0x80 | (s2 & 0x3f) as u8,
0,
],
3,
);
self.send(InputEvent::Key(err, Mods::empty()))?;
}
}
if s2 >= 0xd800 && s2 <= 0xdbff {
self.surrogate = Some(s2 as u16);
return Ok(true);
}
Ok(false)
}
fn special_key(&self, evt: &KEY_EVENT_RECORD) -> Result<bool> {
let skey = match evt.wVirtualKeyCode {
0x08 => Key::BS,
0x09 => Key::Tab,
0x0d => Key::Enter,
0x1b => Key::Esc,
0x21 => Key::PgUp,
0x22 => Key::PgDn,
0x23 => Key::End,
0x24 => Key::Home,
0x25 => Key::Left,
0x26 => Key::Up,
0x27 => Key::Right,
0x28 => Key::Down,
0x2d => Key::Ins,
0x2e => Key::Del,
0x70 => Key::F1,
0x71 => Key::F2,
0x72 => Key::F3,
0x73 => Key::F4,
0x74 => Key::F5,
0x75 => Key::F6,
0x76 => Key::F7,
0x77 => Key::F8,
0x78 => Key::F9,
0x79 => Key::F10,
0x7a => Key::F11,
0x7b => Key::F12,
_ => return Ok(false),
};
self.send(InputEvent::Key(skey, Mods::win32(evt.dwControlKeyState)))?;
Ok(true)
}
fn key(&self, evt: &KEY_EVENT_RECORD) -> Result<()> {
use std::char;
use input::Mods;
let uc = evt.UnicodeChar;
let mods = Mods::win32(evt.dwControlKeyState);
let (key, mods) = if uc == 0 {
return Ok(());
} else if uc < 0x80 {
match uc {
3 => return self.send(InputEvent::Interrupt),
8 => (Key::BS, mods - Mods::CTRL),
9 => (Key::Tab, mods - Mods::CTRL),
13 => (Key::Enter, mods - Mods::CTRL),
27 => (Key::Esc, mods - Mods::CTRL),
b if b < 32 => (Key::ascii(b as u8 + 64), mods | Mods::CTRL),
_ => (Key::ascii(uc as u8), mods),
}
} else if uc < 0x800 {
(
Key::Char(
unsafe { char::from_u32_unchecked(uc as u32) },
[0xc0 | (uc >> 6) as u8, 0x80 | (uc & 0x3f) as u8, 0, 0],
2,
),
mods,
)
} else {
// Surrogate pairs have already been handled.
(
Key::Char(
unsafe { char::from_u32_unchecked(uc as u32) },
[
0xe0 | (uc >> 12) as u8,
0x80 | ((uc >> 6) & 0x3f) as u8,
0x80 | (uc & 0x3f) as u8,
0,
],
3,
),
mods,
)
};
self.send(InputEvent::Key(key, mods))?;
Ok(())
}
}
bitflags! {
#[derive(Default)]
pub struct Btn: u32 {
const LEFT = 0x01;
const RIGHT = 0x02;
const MIDDLE = 0x04;
}
}
pub struct MouseReader {
tx: Sender<Box<Event>>,
coords: (i32, i32),
btns: Btn,
}
impl MouseReader {
fn new(tx: Sender<Box<Event>>) -> MouseReader {
MouseReader {
tx,
coords: (-1, -1),
btns: Btn::empty(),
}
}
fn send(&self, event: InputEvent) -> Result<()> {
self.tx.send(Box::new(event))?;
Ok(())
}
fn read(&mut self, evt: &winapi::MOUSE_EVENT_RECORD) -> Result<()> {
use input::ButtonMotion::*;
use input::MouseButton::*;
use input::WheelMotion::*;
let coords = (
(evt.dwMousePosition.X as u16),
(evt.dwMousePosition.Y as u16),
);
let mods = Mods::win32(evt.dwControlKeyState);
match evt.dwEventFlags {
|
let presses = new_btns - self.btns;
let releases = self.btns - new_btns;
self.btns = new_btns;
if presses.contains(Btn::LEFT) {
let mevt = InputEvent::Mouse(Press, Left, mods, coords);
self.send(mevt)?;
}
if presses.contains(Btn::MIDDLE) {
let mevt = InputEvent::Mouse(Press, Middle, mods, coords);
self.send(mevt)?;
}
if presses.contains(Btn::RIGHT) {
let mevt = InputEvent::Mouse(Press, Right, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::LEFT) {
let mevt = InputEvent::Mouse(Release, Left, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::MIDDLE) {
let mevt = InputEvent::Mouse(Release, Middle, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::RIGHT) {
let mevt = InputEvent::Mouse(Release, Right, mods, coords);
self.send(mevt)?;
}
}
1 => if (i32::from(coords.0), i32::from(coords.1))!= self.coords {
let mevt = InputEvent::MouseMove(mods, coords);
self.send(mevt)?;
},
4 => {
let mevt = if (evt.dwButtonState >> 16) < 0x8000 {
InputEvent::MouseWheel(Up, mods, coords)
} else {
InputEvent::MouseWheel(Down, mods, coords)
};
self.send(mevt)?;
}
_ => (),
}
self.coords = (i32::from(coords.0), i32::from(coords.1));
Ok(())
}
}
pub(crate) struct Resizer {
hndl: winapi::HANDLE,
size: winapi::COORD,
}
impl Resizer {
fn from_conout() -> Result<Resizer> {
let hndl = unsafe {
kernel32::CreateFileA(
"CONOUT$\x00".as_ptr() as *const _ as winapi::LPCSTR,
winapi::GENERIC_READ | winapi::GENERIC_WRITE,
winapi::FILE_SHARE_READ | winapi::FILE_SHARE_WRITE,
ptr::null_mut(),
|
0 | 2 => {
let new_btns = Btn::from_bits(evt.dwButtonState & 0x7).unwrap();
|
random_line_split
|
windows.rs
|
);
1
}
winapi::CTRL_BREAK_EVENT => {
write_fake_key(SIGQUIT_KEY);
1
}
winapi::CTRL_CLOSE_EVENT => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
0
}
_ => 0,
}
}
match unsafe { kernel32::SetConsoleCtrlHandler(Some(handler), 1) } {
0 => Error::ffi_err("SetConsoleCtrlHandler failed"),
_ => Ok(()),
}
}
// winapi-rs omits this.
#[allow(non_snake_case)]
#[repr(C)]
struct WNDCLASS {
pub style: winapi::UINT,
pub lpfnWndProc: winapi::WNDPROC,
pub cbClsExtra: winapi::c_int,
pub cbWndExtra: winapi::c_int,
pub instance: winapi::HINSTANCE,
pub hIcon: winapi::HICON,
pub hCursor: winapi::HCURSOR,
pub hbrBackground: winapi::HBRUSH,
pub lpszMenuName: winapi::LPCSTR,
pub lpszClassName: winapi::LPCSTR,
}
// winapi-rs omits this.
extern "system" {
fn RegisterClassA(lpWndClass: *const WNDCLASS) -> winapi::ATOM;
}
unsafe fn create_session_wnd() -> Result<()> {
extern "system" fn wnd_proc(
hwnd: winapi::HWND,
msg: winapi::UINT,
wparam: winapi::WPARAM,
lparam: winapi::LPARAM,
) -> winapi::LRESULT {
match msg {
winapi::WM_ENDSESSION => {
write_fake_key(SHUTDOWN_KEY);
thread::sleep(time::Duration::from_secs(5));
0
}
_ => unsafe {
user32::DefWindowProcA(hwnd, msg, wparam, lparam)
},
}
}
let mut wnd_class: WNDCLASS = ::std::mem::zeroed();
wnd_class.lpfnWndProc = Some(wnd_proc);
wnd_class.instance = kernel32::GetModuleHandleA(ptr::null());
if wnd_class.instance.is_null() {
return Error::ffi_err("GetModuleHandle failed");
}
wnd_class.lpszClassName =
"HiddenShutdownClass\x00".as_ptr() as *const _ as winapi::LPCSTR;
if 0 == RegisterClassA(&wnd_class) {
return Error::ffi_err("RegisterClass failed");
}
let hwnd = user32::CreateWindowExA(
0,
"HiddenShutdownClass\x00".as_ptr() as *const _ as winapi::LPCSTR,
ptr::null(),
0,
0,
0,
0,
0,
ptr::null_mut(),
ptr::null_mut(),
kernel32::GetModuleHandleA(ptr::null()),
ptr::null_mut(),
);
if hwnd.is_null() {
return Error::ffi_err("CreateWindowEx failed");
}
Ok(())
}
fn register_layout_hook() -> Result<()> {
extern "system" fn layout_hook(
_: winapi::HWINEVENTHOOK,
_: winapi::DWORD,
hwnd: winapi::HWND,
_: winapi::LONG,
_: winapi::LONG,
_: winapi::DWORD,
_: winapi::DWORD,
) {
// Filter out events from consoles in other processes.
if hwnd!= unsafe { kernel32::GetConsoleWindow() } {
return;
}
// Use an "empty" window buffer size event as a resize
// notification.
let mut ir: winapi::INPUT_RECORD =
unsafe { ::std::mem::uninitialized() };
ir.EventType = winapi::WINDOW_BUFFER_SIZE_EVENT;
{
let ir = unsafe { ir.WindowBufferSizeEvent_mut() };
ir.dwSize.X = 0;
ir.dwSize.Y = 0;
}
let con_hndl = Handle::Stdin.win_handle();
let mut write_count: winapi::DWORD = 0;
unsafe {
kernel32::WriteConsoleInputW(con_hndl, &ir, 1, &mut write_count);
}
}
let hook = unsafe {
user32::SetWinEventHook(
EVENT_CONSOLE_LAYOUT,
EVENT_CONSOLE_LAYOUT,
ptr::null_mut(),
Some(layout_hook),
// Listen for events from all threads/processes and filter
// in the callback, because there doesn't seem to be a way
// to get the id for the thread that actually delivers
// WinEvents for the console (it's not the thread returned
// by GetWindowThreadProcessId(GetConsoleWindow())).
0,
0,
WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNTHREAD,
)
};
if hook.is_null() {
return Error::ffi_err("SetWinEventHook failed");
}
Ok(())
}
// Windows events and WinEvents require a thread with a message pump.
unsafe fn run_message_pump() {
let mut msg: winapi::MSG = ::std::mem::uninitialized();
while 0!= user32::GetMessageW(&mut msg, ptr::null_mut(), 0, 0) {
user32::TranslateMessage(&msg);
user32::DispatchMessageW(&msg);
}
}
fn write_fake_key(key_code: u16) -> winapi::BOOL {
let mut key: winapi::INPUT_RECORD =
unsafe { ::std::mem::uninitialized() };
key.EventType = winapi::KEY_EVENT;
{
let key = unsafe { key.KeyEvent_mut() };
key.bKeyDown = 1;
key.wVirtualKeyCode = key_code;
}
let con_hndl = Handle::Stdin.win_handle();
let mut write_count: winapi::DWORD = 0;
unsafe {
kernel32::WriteConsoleInputW(con_hndl, &key, 1, &mut write_count)
}
}
fn raw_event_loop(tx: Sender<Box<Event>>) {
// TODO: Handle FFI errors/channel send errors (until then, just
// exit when the event loop exits).
let _ = event_loop(tx);
}
#[cfg_attr(feature = "cargo-clippy",
allow(needless_range_loop, needless_pass_by_value))]
fn event_loop(tx: Sender<Box<Event>>) -> Result<()> {
let mut resizer = Resizer::from_conout()?;
let in_hndl = Handle::Stdin.win_handle();
let mut buffer: [winapi::INPUT_RECORD; 128] =
unsafe { ::std::mem::uninitialized() };
let mut key_reader = KeyReader::new(tx.clone());
let mut mouse_reader = MouseReader::new(tx.clone());
loop {
let mut read_count: winapi::DWORD = 0;
unsafe {
if kernel32::ReadConsoleInputW(
in_hndl,
buffer.as_mut_ptr(),
128,
&mut read_count,
) == 0
{
return Error::ffi_err("ReadConsoleInputW failed");
}
}
for i in 0..read_count as usize {
let input = buffer[i];
if input.EventType == winapi::FOCUS_EVENT
|| input.EventType == winapi::MENU_EVENT
{
continue;
}
match input.EventType {
winapi::MOUSE_EVENT => {
let mevt = unsafe { input.MouseEvent() };
mouse_reader.read(mevt)?
}
winapi::KEY_EVENT => {
let kevt = unsafe { input.KeyEvent() };
match kevt.wVirtualKeyCode {
SHUTDOWN_KEY => return Ok(()),
SIGINT_KEY => tx.send(Box::new(InputEvent::Interrupt))?,
SIGQUIT_KEY => tx.send(Box::new(InputEvent::Break))?,
_ => key_reader.read(kevt)?,
}
}
winapi::WINDOW_BUFFER_SIZE_EVENT => if resizer.update()? {
tx.send(Box::new(InputEvent::Repaint))?;
},
_ => unreachable!(),
};
}
}
}
struct KeyReader {
surrogate: Option<u16>,
tx: Sender<Box<Event>>,
}
impl KeyReader {
fn new(tx: Sender<Box<Event>>) -> KeyReader {
KeyReader {
surrogate: None,
tx,
}
}
fn send(&self, event: InputEvent) -> Result<()> {
self.tx.send(Box::new(event))?;
Ok(())
}
fn read(&mut self, evt: &KEY_EVENT_RECORD) -> Result<()> {
if self.surrogate_pair(evt)? {
return Ok(());
}
if evt.bKeyDown == 0 {
return Ok(());
}
if self.special_key(evt)? {
return Ok(());
}
self.key(evt)
}
fn surrogate_pair(&mut self, evt: &KEY_EVENT_RECORD) -> Result<bool> {
let s2 = u32::from(evt.UnicodeChar);
if let Some(s1) = self.surrogate.take() {
if s2 >= 0xdc00 && s2 <= 0xdfff {
let s1 = u32::from(s1);
let mut utf8 = [0u8; 4];
let c: u32 = 0x1_0000 | ((s1 - 0xd800) << 10) | (s2 - 0xdc00);
let c = ::std::char::from_u32(c).unwrap();
let len = c.encode_utf8(&mut utf8).len();
let kevt = InputEvent::Key(
Key::Char(c, utf8, len),
Mods::win32(evt.dwControlKeyState),
);
self.send(kevt)?;
return Ok(true);
} else {
let err = Key::Err(
[
0xe0 | (s2 >> 12) as u8,
0x80 | ((s2 >> 6) & 0x3f) as u8,
0x80 | (s2 & 0x3f) as u8,
0,
],
3,
);
self.send(InputEvent::Key(err, Mods::empty()))?;
}
}
if s2 >= 0xd800 && s2 <= 0xdbff {
self.surrogate = Some(s2 as u16);
return Ok(true);
}
Ok(false)
}
fn special_key(&self, evt: &KEY_EVENT_RECORD) -> Result<bool> {
let skey = match evt.wVirtualKeyCode {
0x08 => Key::BS,
0x09 => Key::Tab,
0x0d => Key::Enter,
0x1b => Key::Esc,
0x21 => Key::PgUp,
0x22 => Key::PgDn,
0x23 => Key::End,
0x24 => Key::Home,
0x25 => Key::Left,
0x26 => Key::Up,
0x27 => Key::Right,
0x28 => Key::Down,
0x2d => Key::Ins,
0x2e => Key::Del,
0x70 => Key::F1,
0x71 => Key::F2,
0x72 => Key::F3,
0x73 => Key::F4,
0x74 => Key::F5,
0x75 => Key::F6,
0x76 => Key::F7,
0x77 => Key::F8,
0x78 => Key::F9,
0x79 => Key::F10,
0x7a => Key::F11,
0x7b => Key::F12,
_ => return Ok(false),
};
self.send(InputEvent::Key(skey, Mods::win32(evt.dwControlKeyState)))?;
Ok(true)
}
fn key(&self, evt: &KEY_EVENT_RECORD) -> Result<()> {
use std::char;
use input::Mods;
let uc = evt.UnicodeChar;
let mods = Mods::win32(evt.dwControlKeyState);
let (key, mods) = if uc == 0 {
return Ok(());
} else if uc < 0x80 {
match uc {
3 => return self.send(InputEvent::Interrupt),
8 => (Key::BS, mods - Mods::CTRL),
9 => (Key::Tab, mods - Mods::CTRL),
13 => (Key::Enter, mods - Mods::CTRL),
27 => (Key::Esc, mods - Mods::CTRL),
b if b < 32 => (Key::ascii(b as u8 + 64), mods | Mods::CTRL),
_ => (Key::ascii(uc as u8), mods),
}
} else if uc < 0x800 {
(
Key::Char(
unsafe { char::from_u32_unchecked(uc as u32) },
[0xc0 | (uc >> 6) as u8, 0x80 | (uc & 0x3f) as u8, 0, 0],
2,
),
mods,
)
} else {
// Surrogate pairs have already been handled.
(
Key::Char(
unsafe { char::from_u32_unchecked(uc as u32) },
[
0xe0 | (uc >> 12) as u8,
0x80 | ((uc >> 6) & 0x3f) as u8,
0x80 | (uc & 0x3f) as u8,
0,
],
3,
),
mods,
)
};
self.send(InputEvent::Key(key, mods))?;
Ok(())
}
}
bitflags! {
#[derive(Default)]
pub struct Btn: u32 {
const LEFT = 0x01;
const RIGHT = 0x02;
const MIDDLE = 0x04;
}
}
pub struct MouseReader {
tx: Sender<Box<Event>>,
coords: (i32, i32),
btns: Btn,
}
impl MouseReader {
fn new(tx: Sender<Box<Event>>) -> MouseReader {
MouseReader {
tx,
coords: (-1, -1),
btns: Btn::empty(),
}
}
fn send(&self, event: InputEvent) -> Result<()> {
self.tx.send(Box::new(event))?;
Ok(())
}
fn read(&mut self, evt: &winapi::MOUSE_EVENT_RECORD) -> Result<()>
|
if presses.contains(Btn::MIDDLE) {
let mevt = InputEvent::Mouse(Press, Middle, mods, coords);
self.send(mevt)?;
}
if presses.contains(Btn::RIGHT) {
let mevt = InputEvent::Mouse(Press, Right, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::LEFT) {
let mevt = InputEvent::Mouse(Release, Left, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::MIDDLE) {
let mevt = InputEvent::Mouse(Release, Middle, mods, coords);
self.send(mevt)?;
}
if releases.contains(Btn::RIGHT) {
let mevt = InputEvent::Mouse(Release, Right, mods, coords);
self.send(mevt)?;
}
}
1 => if (i32::from(coords.0), i32::from(coords.1))!= self.coords {
let mevt = InputEvent::MouseMove(mods, coords);
self.send(mevt)?;
},
4 => {
let mevt = if (evt.dwButtonState >> 16) < 0x8000 {
InputEvent::MouseWheel(Up, mods, coords)
} else {
InputEvent::MouseWheel(Down, mods, coords)
};
self.send(mevt)?;
}
_ => (),
}
self.coords = (i32::from(coords.0), i32::from(coords.1));
Ok(())
}
}
pub(crate) struct Resizer {
hndl: winapi::HANDLE,
size: winapi::COORD,
}
impl Resizer {
fn from_conout() -> Result<Resizer> {
let hndl = unsafe {
kernel32::CreateFileA(
"CONOUT$\x00".as_ptr() as *const _ as winapi::LPCSTR,
winapi::GENERIC_READ | winapi::GENERIC_WRITE,
winapi::FILE_SHARE_READ | winapi::FILE_SHARE_WRITE,
ptr::null_mut(),
|
{
use input::ButtonMotion::*;
use input::MouseButton::*;
use input::WheelMotion::*;
let coords = (
(evt.dwMousePosition.X as u16),
(evt.dwMousePosition.Y as u16),
);
let mods = Mods::win32(evt.dwControlKeyState);
match evt.dwEventFlags {
0 | 2 => {
let new_btns = Btn::from_bits(evt.dwButtonState & 0x7).unwrap();
let presses = new_btns - self.btns;
let releases = self.btns - new_btns;
self.btns = new_btns;
if presses.contains(Btn::LEFT) {
let mevt = InputEvent::Mouse(Press, Left, mods, coords);
self.send(mevt)?;
}
|
identifier_body
|
dj.rs
|
extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "!dj quit" will quit the voice channel.
// The bot will quit any voice channel it is the last user in.
pub fn
|
() {
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(&env::var("DISCORD_TOKEN").expect("Expected token"))
.expect("login failed");
// establish websocket and voice connection
let (mut connection, ready) = discord.connect().expect("connect failed");
println!(
"[Ready] {} is serving {} servers",
ready.user.username,
ready.servers.len()
);
let mut state = State::new(ready);
connection.sync_calls(&state.all_private_channels());
// receive events forever
loop {
let event = match connection.recv_event() {
Ok(event) => event,
Err(err) => {
println!("[Warning] Receive error: {:?}", err);
if let discord::Error::WebSocket(..) = err {
// Handle the websocket connection being dropped
let (new_connection, ready) = discord.connect().expect("connect failed");
connection = new_connection;
state = State::new(ready);
println!("[Ready] Reconnected successfully.");
}
if let discord::Error::Closed(..) = err {
break;
}
continue;
}
};
state.update(&event);
match event {
Event::MessageCreate(message) => {
// safeguard: stop if the message is from us
if message.author.id == state.user().id {
continue;
}
// reply to a command if there was one
let mut split = message.content.split(' ');
let first_word = split.next().unwrap_or("");
let argument = split.next().unwrap_or("");
if first_word.eq_ignore_ascii_case("!dj") {
let vchan = state.find_voice_user(message.author.id);
if argument.eq_ignore_ascii_case("stop") {
vchan.map(|(sid, _)| connection.voice(sid).stop());
} else if argument.eq_ignore_ascii_case("quit") {
vchan.map(|(sid, _)| connection.drop_voice(sid));
} else {
let output = if let Some((server_id, channel_id)) = vchan {
match discord::voice::open_ytdl_stream(argument) {
Ok(stream) => {
let voice = connection.voice(server_id);
voice.set_deaf(true);
voice.connect(channel_id);
voice.play(stream);
String::new()
}
Err(error) => format!("Error: {}", error),
}
} else {
"You must be in a voice channel to DJ".to_owned()
};
if!output.is_empty() {
warn(discord.send_message(message.channel_id, &output, "", false));
}
}
}
}
Event::VoiceStateUpdate(server_id, _) => {
// If someone moves/hangs up, and we are in a voice channel,
if let Some(cur_channel) = connection.voice(server_id).current_channel() {
// and our current voice channel is empty, disconnect from voice
match server_id {
Some(server_id) => {
if let Some(srv) =
state.servers().iter().find(|srv| srv.id == server_id)
{
if srv
.voice_states
.iter()
.filter(|vs| vs.channel_id == Some(cur_channel))
.count() <= 1
{
connection.voice(Some(server_id)).disconnect();
}
}
}
None => {
if let Some(call) = state.calls().get(&cur_channel) {
if call.voice_states.len() <= 1 {
connection.voice(server_id).disconnect();
}
}
}
}
}
}
_ => {} // discard other events
}
}
}
fn warn<T, E: ::std::fmt::Debug>(result: Result<T, E>) {
match result {
Ok(_) => {}
Err(err) => println!("[Warning] {:?}", err),
}
}
|
main
|
identifier_name
|
dj.rs
|
extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "!dj quit" will quit the voice channel.
// The bot will quit any voice channel it is the last user in.
pub fn main() {
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(&env::var("DISCORD_TOKEN").expect("Expected token"))
.expect("login failed");
// establish websocket and voice connection
let (mut connection, ready) = discord.connect().expect("connect failed");
println!(
"[Ready] {} is serving {} servers",
ready.user.username,
ready.servers.len()
);
let mut state = State::new(ready);
connection.sync_calls(&state.all_private_channels());
// receive events forever
loop {
let event = match connection.recv_event() {
Ok(event) => event,
Err(err) => {
println!("[Warning] Receive error: {:?}", err);
if let discord::Error::WebSocket(..) = err
|
if let discord::Error::Closed(..) = err {
break;
}
continue;
}
};
state.update(&event);
match event {
Event::MessageCreate(message) => {
// safeguard: stop if the message is from us
if message.author.id == state.user().id {
continue;
}
// reply to a command if there was one
let mut split = message.content.split(' ');
let first_word = split.next().unwrap_or("");
let argument = split.next().unwrap_or("");
if first_word.eq_ignore_ascii_case("!dj") {
let vchan = state.find_voice_user(message.author.id);
if argument.eq_ignore_ascii_case("stop") {
vchan.map(|(sid, _)| connection.voice(sid).stop());
} else if argument.eq_ignore_ascii_case("quit") {
vchan.map(|(sid, _)| connection.drop_voice(sid));
} else {
let output = if let Some((server_id, channel_id)) = vchan {
match discord::voice::open_ytdl_stream(argument) {
Ok(stream) => {
let voice = connection.voice(server_id);
voice.set_deaf(true);
voice.connect(channel_id);
voice.play(stream);
String::new()
}
Err(error) => format!("Error: {}", error),
}
} else {
"You must be in a voice channel to DJ".to_owned()
};
if!output.is_empty() {
warn(discord.send_message(message.channel_id, &output, "", false));
}
}
}
}
Event::VoiceStateUpdate(server_id, _) => {
// If someone moves/hangs up, and we are in a voice channel,
if let Some(cur_channel) = connection.voice(server_id).current_channel() {
// and our current voice channel is empty, disconnect from voice
match server_id {
Some(server_id) => {
if let Some(srv) =
state.servers().iter().find(|srv| srv.id == server_id)
{
if srv
.voice_states
.iter()
.filter(|vs| vs.channel_id == Some(cur_channel))
.count() <= 1
{
connection.voice(Some(server_id)).disconnect();
}
}
}
None => {
if let Some(call) = state.calls().get(&cur_channel) {
if call.voice_states.len() <= 1 {
connection.voice(server_id).disconnect();
}
}
}
}
}
}
_ => {} // discard other events
}
}
}
fn warn<T, E: ::std::fmt::Debug>(result: Result<T, E>) {
match result {
Ok(_) => {}
Err(err) => println!("[Warning] {:?}", err),
}
}
|
{
// Handle the websocket connection being dropped
let (new_connection, ready) = discord.connect().expect("connect failed");
connection = new_connection;
state = State::new(ready);
println!("[Ready] Reconnected successfully.");
}
|
conditional_block
|
dj.rs
|
extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "!dj quit" will quit the voice channel.
// The bot will quit any voice channel it is the last user in.
pub fn main()
|
println!("[Warning] Receive error: {:?}", err);
if let discord::Error::WebSocket(..) = err {
// Handle the websocket connection being dropped
let (new_connection, ready) = discord.connect().expect("connect failed");
connection = new_connection;
state = State::new(ready);
println!("[Ready] Reconnected successfully.");
}
if let discord::Error::Closed(..) = err {
break;
}
continue;
}
};
state.update(&event);
match event {
Event::MessageCreate(message) => {
// safeguard: stop if the message is from us
if message.author.id == state.user().id {
continue;
}
// reply to a command if there was one
let mut split = message.content.split(' ');
let first_word = split.next().unwrap_or("");
let argument = split.next().unwrap_or("");
if first_word.eq_ignore_ascii_case("!dj") {
let vchan = state.find_voice_user(message.author.id);
if argument.eq_ignore_ascii_case("stop") {
vchan.map(|(sid, _)| connection.voice(sid).stop());
} else if argument.eq_ignore_ascii_case("quit") {
vchan.map(|(sid, _)| connection.drop_voice(sid));
} else {
let output = if let Some((server_id, channel_id)) = vchan {
match discord::voice::open_ytdl_stream(argument) {
Ok(stream) => {
let voice = connection.voice(server_id);
voice.set_deaf(true);
voice.connect(channel_id);
voice.play(stream);
String::new()
}
Err(error) => format!("Error: {}", error),
}
} else {
"You must be in a voice channel to DJ".to_owned()
};
if!output.is_empty() {
warn(discord.send_message(message.channel_id, &output, "", false));
}
}
}
}
Event::VoiceStateUpdate(server_id, _) => {
// If someone moves/hangs up, and we are in a voice channel,
if let Some(cur_channel) = connection.voice(server_id).current_channel() {
// and our current voice channel is empty, disconnect from voice
match server_id {
Some(server_id) => {
if let Some(srv) =
state.servers().iter().find(|srv| srv.id == server_id)
{
if srv
.voice_states
.iter()
.filter(|vs| vs.channel_id == Some(cur_channel))
.count() <= 1
{
connection.voice(Some(server_id)).disconnect();
}
}
}
None => {
if let Some(call) = state.calls().get(&cur_channel) {
if call.voice_states.len() <= 1 {
connection.voice(server_id).disconnect();
}
}
}
}
}
}
_ => {} // discard other events
}
}
}
fn warn<T, E: ::std::fmt::Debug>(result: Result<T, E>) {
match result {
Ok(_) => {}
Err(err) => println!("[Warning] {:?}", err),
}
}
|
{
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(&env::var("DISCORD_TOKEN").expect("Expected token"))
.expect("login failed");
// establish websocket and voice connection
let (mut connection, ready) = discord.connect().expect("connect failed");
println!(
"[Ready] {} is serving {} servers",
ready.user.username,
ready.servers.len()
);
let mut state = State::new(ready);
connection.sync_calls(&state.all_private_channels());
// receive events forever
loop {
let event = match connection.recv_event() {
Ok(event) => event,
Err(err) => {
|
identifier_body
|
dj.rs
|
extern crate discord;
use discord::model::Event;
use discord::{Discord, State};
use std::env;
// A simple DJ bot example.
// Use by issuing the command "!dj <youtube-link>" in PM or a visible text channel.
// The bot will join the voice channel of the person issuing the command.
// "!dj stop" will stop playing, and "!dj quit" will quit the voice channel.
// The bot will quit any voice channel it is the last user in.
pub fn main() {
// Log in to Discord using a bot token from the environment
let discord = Discord::from_bot_token(&env::var("DISCORD_TOKEN").expect("Expected token"))
.expect("login failed");
// establish websocket and voice connection
let (mut connection, ready) = discord.connect().expect("connect failed");
println!(
"[Ready] {} is serving {} servers",
ready.user.username,
ready.servers.len()
);
let mut state = State::new(ready);
connection.sync_calls(&state.all_private_channels());
// receive events forever
loop {
let event = match connection.recv_event() {
Ok(event) => event,
Err(err) => {
println!("[Warning] Receive error: {:?}", err);
if let discord::Error::WebSocket(..) = err {
// Handle the websocket connection being dropped
let (new_connection, ready) = discord.connect().expect("connect failed");
connection = new_connection;
state = State::new(ready);
println!("[Ready] Reconnected successfully.");
}
if let discord::Error::Closed(..) = err {
break;
}
continue;
}
};
state.update(&event);
match event {
Event::MessageCreate(message) => {
// safeguard: stop if the message is from us
if message.author.id == state.user().id {
continue;
}
// reply to a command if there was one
let mut split = message.content.split(' ');
let first_word = split.next().unwrap_or("");
let argument = split.next().unwrap_or("");
if first_word.eq_ignore_ascii_case("!dj") {
let vchan = state.find_voice_user(message.author.id);
if argument.eq_ignore_ascii_case("stop") {
vchan.map(|(sid, _)| connection.voice(sid).stop());
} else if argument.eq_ignore_ascii_case("quit") {
vchan.map(|(sid, _)| connection.drop_voice(sid));
} else {
let output = if let Some((server_id, channel_id)) = vchan {
match discord::voice::open_ytdl_stream(argument) {
Ok(stream) => {
let voice = connection.voice(server_id);
voice.set_deaf(true);
voice.connect(channel_id);
voice.play(stream);
String::new()
}
Err(error) => format!("Error: {}", error),
}
} else {
"You must be in a voice channel to DJ".to_owned()
};
if!output.is_empty() {
warn(discord.send_message(message.channel_id, &output, "", false));
}
}
}
}
Event::VoiceStateUpdate(server_id, _) => {
// If someone moves/hangs up, and we are in a voice channel,
if let Some(cur_channel) = connection.voice(server_id).current_channel() {
// and our current voice channel is empty, disconnect from voice
match server_id {
Some(server_id) => {
if let Some(srv) =
state.servers().iter().find(|srv| srv.id == server_id)
{
if srv
.voice_states
.iter()
.filter(|vs| vs.channel_id == Some(cur_channel))
.count() <= 1
{
connection.voice(Some(server_id)).disconnect();
}
}
}
None => {
if let Some(call) = state.calls().get(&cur_channel) {
if call.voice_states.len() <= 1 {
|
}
}
}
_ => {} // discard other events
}
}
}
fn warn<T, E: ::std::fmt::Debug>(result: Result<T, E>) {
match result {
Ok(_) => {}
Err(err) => println!("[Warning] {:?}", err),
}
}
|
connection.voice(server_id).disconnect();
}
}
}
|
random_line_split
|
lib.rs
|
#[allow(unused_variables)]
// Because these are passed without & to some functions,
// it will probably be necessary for these two types to be Copy.
pub type CellID = ();
pub type CallbackID = ();
pub struct Reactor<T> {
// Just so that the compiler doesn't complain about an unused type parameter.
// You probably want to delete this field.
dummy: T,
}
// You are guaranteed that Reactor will only be tested against types that are Copy + PartialEq.
impl <T: Copy + PartialEq> Reactor<T> {
pub fn new() -> Self {
unimplemented!()
}
// Creates an input cell with the specified initial value, returning its ID.
pub fn create_input(&mut self, initial: T) -> CellID {
unimplemented!()
}
// Creates a compute cell with the specified dependencies and compute function.
// The compute function is expected to take in its arguments in the same order as specified in
// `dependencies`.
// You do not need to reject compute functions that expect more arguments than there are
// dependencies (how would you check for this, anyway?).
//
// Return an Err (and you can change the error type) if any dependency doesn't exist.
//
// Notice that there is no way to *remove* a cell.
// This means that you may assume, without checking, that if the dependencies exist at creation
// time they will continue to exist as long as the Reactor exists.
pub fn create_compute<F: Fn(&[T]) -> T>(&mut self, dependencies: &[CellID], compute_func: F) -> Result<CellID, ()> {
unimplemented!()
}
// Retrieves the current value of the cell, or None if the cell does not exist.
//
// You may wonder whether it is possible to implement `get(&self, id: CellID) -> Option<&Cell>`
// and have a `value(&self)` method on `Cell`.
//
// It turns out this introduces a significant amount of extra complexity to this exercise.
// We chose not to cover this here, since this exercise is probably enough work as-is.
pub fn value(&self, id: CellID) -> Option<T> {
unimplemented!()
}
// Sets the value of the specified input cell.
//
// Return an Err (and you can change the error type) if the cell does not exist, or the
// specified cell is a compute cell, since compute cells cannot have their values directly set.
//
// Similarly, you may wonder about `get_mut(&mut self, id: CellID) -> Option<&mut Cell>`, with
// a `set_value(&mut self, new_value: T)` method on `Cell`.
//
// As before, that turned out to add too much extra complexity.
pub fn set_value(&mut self, id: CellID, new_value: T) -> Result<(), ()> {
unimplemented!()
}
// Adds a callback to the specified compute cell.
//
// Return an Err (and you can change the error type) if the cell does not exist.
//
// Callbacks on input cells will not be tested.
//
// The semantics of callbacks (as will be tested):
// For a single set_value call, each compute cell's callbacks should each be called:
// * Zero times if the compute cell's value did not change as a result of the set_value call.
// * Exactly once if the compute cell's value changed as a result of the set_value call.
// The value passed to the callback should be the final value of the compute cell after the
// set_value call.
pub fn add_callback<F: FnMut(T) -> ()>(&mut self, id: CellID, callback: F) -> Result<CallbackID, ()> {
unimplemented!()
}
// Removes the specified callback, using an ID returned from add_callback.
//
// Return an Err (and you can change the error type) if either the cell or callback
// does not exist.
//
// A removed callback should no longer be called.
pub fn remove_callback(&mut self, cell: CellID, callback: CallbackID) -> Result<(), ()> {
|
unimplemented!()
}
}
|
random_line_split
|
|
lib.rs
|
#[allow(unused_variables)]
// Because these are passed without & to some functions,
// it will probably be necessary for these two types to be Copy.
pub type CellID = ();
pub type CallbackID = ();
pub struct Reactor<T> {
// Just so that the compiler doesn't complain about an unused type parameter.
// You probably want to delete this field.
dummy: T,
}
// You are guaranteed that Reactor will only be tested against types that are Copy + PartialEq.
impl <T: Copy + PartialEq> Reactor<T> {
pub fn new() -> Self {
unimplemented!()
}
// Creates an input cell with the specified initial value, returning its ID.
pub fn create_input(&mut self, initial: T) -> CellID {
unimplemented!()
}
// Creates a compute cell with the specified dependencies and compute function.
// The compute function is expected to take in its arguments in the same order as specified in
// `dependencies`.
// You do not need to reject compute functions that expect more arguments than there are
// dependencies (how would you check for this, anyway?).
//
// Return an Err (and you can change the error type) if any dependency doesn't exist.
//
// Notice that there is no way to *remove* a cell.
// This means that you may assume, without checking, that if the dependencies exist at creation
// time they will continue to exist as long as the Reactor exists.
pub fn create_compute<F: Fn(&[T]) -> T>(&mut self, dependencies: &[CellID], compute_func: F) -> Result<CellID, ()> {
unimplemented!()
}
// Retrieves the current value of the cell, or None if the cell does not exist.
//
// You may wonder whether it is possible to implement `get(&self, id: CellID) -> Option<&Cell>`
// and have a `value(&self)` method on `Cell`.
//
// It turns out this introduces a significant amount of extra complexity to this exercise.
// We chose not to cover this here, since this exercise is probably enough work as-is.
pub fn value(&self, id: CellID) -> Option<T> {
unimplemented!()
}
// Sets the value of the specified input cell.
//
// Return an Err (and you can change the error type) if the cell does not exist, or the
// specified cell is a compute cell, since compute cells cannot have their values directly set.
//
// Similarly, you may wonder about `get_mut(&mut self, id: CellID) -> Option<&mut Cell>`, with
// a `set_value(&mut self, new_value: T)` method on `Cell`.
//
// As before, that turned out to add too much extra complexity.
pub fn
|
(&mut self, id: CellID, new_value: T) -> Result<(), ()> {
unimplemented!()
}
// Adds a callback to the specified compute cell.
//
// Return an Err (and you can change the error type) if the cell does not exist.
//
// Callbacks on input cells will not be tested.
//
// The semantics of callbacks (as will be tested):
// For a single set_value call, each compute cell's callbacks should each be called:
// * Zero times if the compute cell's value did not change as a result of the set_value call.
// * Exactly once if the compute cell's value changed as a result of the set_value call.
// The value passed to the callback should be the final value of the compute cell after the
// set_value call.
pub fn add_callback<F: FnMut(T) -> ()>(&mut self, id: CellID, callback: F) -> Result<CallbackID, ()> {
unimplemented!()
}
// Removes the specified callback, using an ID returned from add_callback.
//
// Return an Err (and you can change the error type) if either the cell or callback
// does not exist.
//
// A removed callback should no longer be called.
pub fn remove_callback(&mut self, cell: CellID, callback: CallbackID) -> Result<(), ()> {
unimplemented!()
}
}
|
set_value
|
identifier_name
|
lib.rs
|
#[allow(unused_variables)]
// Because these are passed without & to some functions,
// it will probably be necessary for these two types to be Copy.
pub type CellID = ();
pub type CallbackID = ();
pub struct Reactor<T> {
// Just so that the compiler doesn't complain about an unused type parameter.
// You probably want to delete this field.
dummy: T,
}
// You are guaranteed that Reactor will only be tested against types that are Copy + PartialEq.
impl <T: Copy + PartialEq> Reactor<T> {
pub fn new() -> Self {
unimplemented!()
}
// Creates an input cell with the specified initial value, returning its ID.
pub fn create_input(&mut self, initial: T) -> CellID {
unimplemented!()
}
// Creates a compute cell with the specified dependencies and compute function.
// The compute function is expected to take in its arguments in the same order as specified in
// `dependencies`.
// You do not need to reject compute functions that expect more arguments than there are
// dependencies (how would you check for this, anyway?).
//
// Return an Err (and you can change the error type) if any dependency doesn't exist.
//
// Notice that there is no way to *remove* a cell.
// This means that you may assume, without checking, that if the dependencies exist at creation
// time they will continue to exist as long as the Reactor exists.
pub fn create_compute<F: Fn(&[T]) -> T>(&mut self, dependencies: &[CellID], compute_func: F) -> Result<CellID, ()> {
unimplemented!()
}
// Retrieves the current value of the cell, or None if the cell does not exist.
//
// You may wonder whether it is possible to implement `get(&self, id: CellID) -> Option<&Cell>`
// and have a `value(&self)` method on `Cell`.
//
// It turns out this introduces a significant amount of extra complexity to this exercise.
// We chose not to cover this here, since this exercise is probably enough work as-is.
pub fn value(&self, id: CellID) -> Option<T> {
unimplemented!()
}
// Sets the value of the specified input cell.
//
// Return an Err (and you can change the error type) if the cell does not exist, or the
// specified cell is a compute cell, since compute cells cannot have their values directly set.
//
// Similarly, you may wonder about `get_mut(&mut self, id: CellID) -> Option<&mut Cell>`, with
// a `set_value(&mut self, new_value: T)` method on `Cell`.
//
// As before, that turned out to add too much extra complexity.
pub fn set_value(&mut self, id: CellID, new_value: T) -> Result<(), ()> {
unimplemented!()
}
// Adds a callback to the specified compute cell.
//
// Return an Err (and you can change the error type) if the cell does not exist.
//
// Callbacks on input cells will not be tested.
//
// The semantics of callbacks (as will be tested):
// For a single set_value call, each compute cell's callbacks should each be called:
// * Zero times if the compute cell's value did not change as a result of the set_value call.
// * Exactly once if the compute cell's value changed as a result of the set_value call.
// The value passed to the callback should be the final value of the compute cell after the
// set_value call.
pub fn add_callback<F: FnMut(T) -> ()>(&mut self, id: CellID, callback: F) -> Result<CallbackID, ()>
|
// Removes the specified callback, using an ID returned from add_callback.
//
// Return an Err (and you can change the error type) if either the cell or callback
// does not exist.
//
// A removed callback should no longer be called.
pub fn remove_callback(&mut self, cell: CellID, callback: CallbackID) -> Result<(), ()> {
unimplemented!()
}
}
|
{
unimplemented!()
}
|
identifier_body
|
direct_irq.rs
|
// Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;
use std::mem::size_of;
use remain::sorted;
use thiserror::Error;
use vfio_sys::*;
#[sorted]
#[derive(Error, Debug)]
pub enum DirectIrqError {
#[error("failed to enable direct irq")]
Enable,
#[error("failed to open /dev/plat-irq-forward: {0}")]
Open(io::Error),
}
pub struct DirectIrq {
dev: File,
trigger: Event,
resample: Option<Event>,
}
impl DirectIrq {
/// Create DirectIrq object to access hardware triggered interrupts.
pub fn new(trigger: Event, resample: Option<Event>) -> Result<Self, DirectIrqError> {
let dev = OpenOptions::new()
.read(true)
.write(true)
.open("/dev/plat-irq-forward")
.map_err(DirectIrqError::Open)?;
Ok(DirectIrq {
dev,
trigger,
resample,
})
}
/// Enable hardware triggered interrupt handling.
|
/// Note: this feature is not part of VFIO, but provides
/// missing IRQ forwarding functionality.
///
/// # Arguments
///
/// * `irq_num` - host interrupt number (GSI).
///
pub fn irq_enable(&self, irq_num: u32) -> Result<(), DirectIrqError> {
if let Some(resample) = &self.resample {
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_LEVEL_TRIGGER_EVENTFD,
self.trigger.as_raw_descriptor(),
)?;
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_LEVEL_UNMASK_EVENTFD,
resample.as_raw_descriptor(),
)?;
} else {
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_EDGE_TRIGGER,
self.trigger.as_raw_descriptor(),
)?;
};
Ok(())
}
fn plat_irq_ioctl(
&self,
irq_num: u32,
action: u32,
fd: RawDescriptor,
) -> Result<(), DirectIrqError> {
let count = 1;
let u32_size = size_of::<u32>();
let mut irq_set = vec_with_array_field::<plat_irq_forward_set, u32>(count);
irq_set[0].argsz = (size_of::<plat_irq_forward_set>() + count * u32_size) as u32;
irq_set[0].action_flags = action;
irq_set[0].count = count as u32;
irq_set[0].irq_number_host = irq_num;
// Safe as we are the owner of irq_set and allocation provides enough space for
// eventfd array.
let data = unsafe { irq_set[0].eventfd.as_mut_slice(count * u32_size) };
let (left, _right) = data.split_at_mut(u32_size);
left.copy_from_slice(&fd.to_ne_bytes()[..]);
// Safe as we are the owner of plat_irq_forward and irq_set which are valid value
let ret = unsafe { ioctl_with_ref(self, PLAT_IRQ_FORWARD_SET(), &irq_set[0]) };
if ret < 0 {
Err(DirectIrqError::Enable)
} else {
Ok(())
}
}
}
impl AsRawDescriptor for DirectIrq {
fn as_raw_descriptor(&self) -> i32 {
self.dev.as_raw_descriptor()
}
}
|
///
|
random_line_split
|
direct_irq.rs
|
// Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;
use std::mem::size_of;
use remain::sorted;
use thiserror::Error;
use vfio_sys::*;
#[sorted]
#[derive(Error, Debug)]
pub enum DirectIrqError {
#[error("failed to enable direct irq")]
Enable,
#[error("failed to open /dev/plat-irq-forward: {0}")]
Open(io::Error),
}
pub struct DirectIrq {
dev: File,
trigger: Event,
resample: Option<Event>,
}
impl DirectIrq {
/// Create DirectIrq object to access hardware triggered interrupts.
pub fn new(trigger: Event, resample: Option<Event>) -> Result<Self, DirectIrqError>
|
/// Enable hardware triggered interrupt handling.
///
/// Note: this feature is not part of VFIO, but provides
/// missing IRQ forwarding functionality.
///
/// # Arguments
///
/// * `irq_num` - host interrupt number (GSI).
///
pub fn irq_enable(&self, irq_num: u32) -> Result<(), DirectIrqError> {
if let Some(resample) = &self.resample {
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_LEVEL_TRIGGER_EVENTFD,
self.trigger.as_raw_descriptor(),
)?;
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_LEVEL_UNMASK_EVENTFD,
resample.as_raw_descriptor(),
)?;
} else {
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_EDGE_TRIGGER,
self.trigger.as_raw_descriptor(),
)?;
};
Ok(())
}
fn plat_irq_ioctl(
&self,
irq_num: u32,
action: u32,
fd: RawDescriptor,
) -> Result<(), DirectIrqError> {
let count = 1;
let u32_size = size_of::<u32>();
let mut irq_set = vec_with_array_field::<plat_irq_forward_set, u32>(count);
irq_set[0].argsz = (size_of::<plat_irq_forward_set>() + count * u32_size) as u32;
irq_set[0].action_flags = action;
irq_set[0].count = count as u32;
irq_set[0].irq_number_host = irq_num;
// Safe as we are the owner of irq_set and allocation provides enough space for
// eventfd array.
let data = unsafe { irq_set[0].eventfd.as_mut_slice(count * u32_size) };
let (left, _right) = data.split_at_mut(u32_size);
left.copy_from_slice(&fd.to_ne_bytes()[..]);
// Safe as we are the owner of plat_irq_forward and irq_set which are valid value
let ret = unsafe { ioctl_with_ref(self, PLAT_IRQ_FORWARD_SET(), &irq_set[0]) };
if ret < 0 {
Err(DirectIrqError::Enable)
} else {
Ok(())
}
}
}
impl AsRawDescriptor for DirectIrq {
fn as_raw_descriptor(&self) -> i32 {
self.dev.as_raw_descriptor()
}
}
|
{
let dev = OpenOptions::new()
.read(true)
.write(true)
.open("/dev/plat-irq-forward")
.map_err(DirectIrqError::Open)?;
Ok(DirectIrq {
dev,
trigger,
resample,
})
}
|
identifier_body
|
direct_irq.rs
|
// Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;
use std::mem::size_of;
use remain::sorted;
use thiserror::Error;
use vfio_sys::*;
#[sorted]
#[derive(Error, Debug)]
pub enum DirectIrqError {
#[error("failed to enable direct irq")]
Enable,
#[error("failed to open /dev/plat-irq-forward: {0}")]
Open(io::Error),
}
pub struct DirectIrq {
dev: File,
trigger: Event,
resample: Option<Event>,
}
impl DirectIrq {
/// Create DirectIrq object to access hardware triggered interrupts.
pub fn new(trigger: Event, resample: Option<Event>) -> Result<Self, DirectIrqError> {
let dev = OpenOptions::new()
.read(true)
.write(true)
.open("/dev/plat-irq-forward")
.map_err(DirectIrqError::Open)?;
Ok(DirectIrq {
dev,
trigger,
resample,
})
}
/// Enable hardware triggered interrupt handling.
///
/// Note: this feature is not part of VFIO, but provides
/// missing IRQ forwarding functionality.
///
/// # Arguments
///
/// * `irq_num` - host interrupt number (GSI).
///
pub fn irq_enable(&self, irq_num: u32) -> Result<(), DirectIrqError> {
if let Some(resample) = &self.resample {
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_LEVEL_TRIGGER_EVENTFD,
self.trigger.as_raw_descriptor(),
)?;
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_LEVEL_UNMASK_EVENTFD,
resample.as_raw_descriptor(),
)?;
} else {
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_EDGE_TRIGGER,
self.trigger.as_raw_descriptor(),
)?;
};
Ok(())
}
fn plat_irq_ioctl(
&self,
irq_num: u32,
action: u32,
fd: RawDescriptor,
) -> Result<(), DirectIrqError> {
let count = 1;
let u32_size = size_of::<u32>();
let mut irq_set = vec_with_array_field::<plat_irq_forward_set, u32>(count);
irq_set[0].argsz = (size_of::<plat_irq_forward_set>() + count * u32_size) as u32;
irq_set[0].action_flags = action;
irq_set[0].count = count as u32;
irq_set[0].irq_number_host = irq_num;
// Safe as we are the owner of irq_set and allocation provides enough space for
// eventfd array.
let data = unsafe { irq_set[0].eventfd.as_mut_slice(count * u32_size) };
let (left, _right) = data.split_at_mut(u32_size);
left.copy_from_slice(&fd.to_ne_bytes()[..]);
// Safe as we are the owner of plat_irq_forward and irq_set which are valid value
let ret = unsafe { ioctl_with_ref(self, PLAT_IRQ_FORWARD_SET(), &irq_set[0]) };
if ret < 0
|
else {
Ok(())
}
}
}
impl AsRawDescriptor for DirectIrq {
fn as_raw_descriptor(&self) -> i32 {
self.dev.as_raw_descriptor()
}
}
|
{
Err(DirectIrqError::Enable)
}
|
conditional_block
|
direct_irq.rs
|
// Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use base::{ioctl_with_ref, AsRawDescriptor, Event, RawDescriptor};
use data_model::vec_with_array_field;
use std::fs::{File, OpenOptions};
use std::io;
use std::mem::size_of;
use remain::sorted;
use thiserror::Error;
use vfio_sys::*;
#[sorted]
#[derive(Error, Debug)]
pub enum DirectIrqError {
#[error("failed to enable direct irq")]
Enable,
#[error("failed to open /dev/plat-irq-forward: {0}")]
Open(io::Error),
}
pub struct DirectIrq {
dev: File,
trigger: Event,
resample: Option<Event>,
}
impl DirectIrq {
/// Create DirectIrq object to access hardware triggered interrupts.
pub fn new(trigger: Event, resample: Option<Event>) -> Result<Self, DirectIrqError> {
let dev = OpenOptions::new()
.read(true)
.write(true)
.open("/dev/plat-irq-forward")
.map_err(DirectIrqError::Open)?;
Ok(DirectIrq {
dev,
trigger,
resample,
})
}
/// Enable hardware triggered interrupt handling.
///
/// Note: this feature is not part of VFIO, but provides
/// missing IRQ forwarding functionality.
///
/// # Arguments
///
/// * `irq_num` - host interrupt number (GSI).
///
pub fn
|
(&self, irq_num: u32) -> Result<(), DirectIrqError> {
if let Some(resample) = &self.resample {
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_LEVEL_TRIGGER_EVENTFD,
self.trigger.as_raw_descriptor(),
)?;
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_LEVEL_UNMASK_EVENTFD,
resample.as_raw_descriptor(),
)?;
} else {
self.plat_irq_ioctl(
irq_num,
PLAT_IRQ_FORWARD_SET_EDGE_TRIGGER,
self.trigger.as_raw_descriptor(),
)?;
};
Ok(())
}
fn plat_irq_ioctl(
&self,
irq_num: u32,
action: u32,
fd: RawDescriptor,
) -> Result<(), DirectIrqError> {
let count = 1;
let u32_size = size_of::<u32>();
let mut irq_set = vec_with_array_field::<plat_irq_forward_set, u32>(count);
irq_set[0].argsz = (size_of::<plat_irq_forward_set>() + count * u32_size) as u32;
irq_set[0].action_flags = action;
irq_set[0].count = count as u32;
irq_set[0].irq_number_host = irq_num;
// Safe as we are the owner of irq_set and allocation provides enough space for
// eventfd array.
let data = unsafe { irq_set[0].eventfd.as_mut_slice(count * u32_size) };
let (left, _right) = data.split_at_mut(u32_size);
left.copy_from_slice(&fd.to_ne_bytes()[..]);
// Safe as we are the owner of plat_irq_forward and irq_set which are valid value
let ret = unsafe { ioctl_with_ref(self, PLAT_IRQ_FORWARD_SET(), &irq_set[0]) };
if ret < 0 {
Err(DirectIrqError::Enable)
} else {
Ok(())
}
}
}
impl AsRawDescriptor for DirectIrq {
fn as_raw_descriptor(&self) -> i32 {
self.dev.as_raw_descriptor()
}
}
|
irq_enable
|
identifier_name
|
query_result.rs
|
use std::marker::PhantomData;
use serde::{de, Deserialize, Deserializer};
use uuid::Uuid;
/// A report about the outcome of a write.
#[derive(Debug)]
pub struct WriteStatus<T> {
/// The number of new documents inserted. This counter is zero in case of an update or delete
/// operation. In case of a replace operation you can have new documents inserted if you do a
/// point-replace on a key that isn't in the table or you do a replace on a selection and one of
/// the documents you are replacing has been deleted.
pub inserted: u32,
/// The number of documents that were updated or replaced. This counter is zero in case of a
/// delete operation or an insert operation where `conflict` isn't set to "replace" or "update".
pub replaced: u32,
/// The number of documents that would have been modified except the new value was the same as
/// the old value. This counter is zero in case of a delete operation or an insert operation
/// where `confict` is set to "error".
pub unchanged: u32,
/// The number of documents that were skipped because the document didn't exist. This counter is
/// zero in case of an insert or replace operation.
pub skipped: u32,
/// The number of documents that were deleted. This counter is zero in case of an insert or
/// update operation.
///
/// A replace with `None` increases this counter.
pub deleted: u32,
/// The number of errors encountered while performing the operation.
pub errors: u32,
/// If errors where encountered, contains the text of the first error.
pub first_error: String,
/// A list of generated primary keys for inserted documents whose primary keys were not
/// specified (capped to 100,000).
pub generated_keys: Vec<Uuid>,
/// If the field `generated_keys` is truncated, you will get the warning "Too many generated
/// keys (<X>), array truncated to 100000".
pub warnings: String,
/// If `return_changes` is set to `true`, this will be an array of objects, one for each
/// object affected by the `insert` operation.
pub changes: Option<Vec<(T, T)>>,
}
impl<T: Deserialize> Deserialize for WriteStatus<T> {
fn deserialize<D: Deserializer>(deserializer: &mut D) -> Result<Self, D::Error> {
field_visitor!(
enum Field {
"inserted" => Inserted,
"replaced" => Replaced,
"unchanged" => Unchanged,
"skipped" => Skipped,
"deleted" => Deleted,
"errors" => Errors,
"first_error" => FirstError,
"generated_keys" => GeneratedKeys,
"warnings" => Warnings,
"changes" => Changes,
},
FieldVisitor
);
struct WriteStatusVisitor<T>(PhantomData<T>);
impl<T> de::Visitor for WriteStatusVisitor<T>
where T: Deserialize
{
type Value = WriteStatus<T>;
fn
|
<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error>
where V: de::MapVisitor
{
let mut inserted = None;
let mut replaced = None;
let mut unchanged = None;
let mut skipped = None;
let mut deleted = None;
let mut errors = None;
let mut first_error = None;
let mut generated_keys = None;
let mut warnings = None;
let mut changes = None;
while let Some(key) = try!(visitor.visit_key()) {
match key {
Field::Inserted => inserted = Some(try!(visitor.visit_value())),
Field::Replaced => replaced = Some(try!(visitor.visit_value())),
Field::Unchanged => unchanged = Some(try!(visitor.visit_value())),
Field::Skipped => skipped = Some(try!(visitor.visit_value())),
Field::Deleted => deleted = Some(try!(visitor.visit_value())),
Field::Errors => errors = Some(try!(visitor.visit_value())),
Field::FirstError => first_error = Some(try!(visitor.visit_value())),
Field::GeneratedKeys => generated_keys = Some(try!(visitor.visit_value())),
Field::Warnings => warnings = Some(try!(visitor.visit_value())),
Field::Changes => changes = Some(try!(visitor.visit_value())),
}
}
try!(visitor.end());
let inserted = inserted.unwrap_or(0);
let replaced = replaced.unwrap_or(0);
let unchanged = unchanged.unwrap_or(0);
let skipped = skipped.unwrap_or(0);
let deleted = deleted.unwrap_or(0);
let errors = errors.unwrap_or(0);
let first_error = first_error.unwrap_or_default();
let generated_keys = generated_keys.unwrap_or_default();
let warnings = warnings.unwrap_or_default();
Ok(WriteStatus {
inserted: inserted,
replaced: replaced,
unchanged: unchanged,
skipped: skipped,
deleted: deleted,
errors: errors,
first_error: first_error,
generated_keys: generated_keys,
warnings: warnings,
changes: changes,
})
}
}
deserializer.deserialize(WriteStatusVisitor(PhantomData))
}
}
|
visit_map
|
identifier_name
|
query_result.rs
|
use std::marker::PhantomData;
use serde::{de, Deserialize, Deserializer};
use uuid::Uuid;
/// A report about the outcome of a write.
#[derive(Debug)]
pub struct WriteStatus<T> {
/// The number of new documents inserted. This counter is zero in case of an update or delete
/// operation. In case of a replace operation you can have new documents inserted if you do a
/// point-replace on a key that isn't in the table or you do a replace on a selection and one of
/// the documents you are replacing has been deleted.
pub inserted: u32,
/// The number of documents that were updated or replaced. This counter is zero in case of a
/// delete operation or an insert operation where `conflict` isn't set to "replace" or "update".
pub replaced: u32,
/// The number of documents that would have been modified except the new value was the same as
/// the old value. This counter is zero in case of a delete operation or an insert operation
/// where `confict` is set to "error".
pub unchanged: u32,
/// The number of documents that were skipped because the document didn't exist. This counter is
/// zero in case of an insert or replace operation.
pub skipped: u32,
/// The number of documents that were deleted. This counter is zero in case of an insert or
/// update operation.
///
/// A replace with `None` increases this counter.
pub deleted: u32,
/// The number of errors encountered while performing the operation.
pub errors: u32,
/// If errors where encountered, contains the text of the first error.
pub first_error: String,
/// A list of generated primary keys for inserted documents whose primary keys were not
/// specified (capped to 100,000).
pub generated_keys: Vec<Uuid>,
/// If the field `generated_keys` is truncated, you will get the warning "Too many generated
/// keys (<X>), array truncated to 100000".
pub warnings: String,
/// If `return_changes` is set to `true`, this will be an array of objects, one for each
/// object affected by the `insert` operation.
pub changes: Option<Vec<(T, T)>>,
}
impl<T: Deserialize> Deserialize for WriteStatus<T> {
fn deserialize<D: Deserializer>(deserializer: &mut D) -> Result<Self, D::Error> {
field_visitor!(
enum Field {
"inserted" => Inserted,
"replaced" => Replaced,
"unchanged" => Unchanged,
"skipped" => Skipped,
"deleted" => Deleted,
"errors" => Errors,
"first_error" => FirstError,
"generated_keys" => GeneratedKeys,
"warnings" => Warnings,
"changes" => Changes,
},
FieldVisitor
);
struct WriteStatusVisitor<T>(PhantomData<T>);
impl<T> de::Visitor for WriteStatusVisitor<T>
where T: Deserialize
{
type Value = WriteStatus<T>;
fn visit_map<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error>
where V: de::MapVisitor
|
Field::FirstError => first_error = Some(try!(visitor.visit_value())),
Field::GeneratedKeys => generated_keys = Some(try!(visitor.visit_value())),
Field::Warnings => warnings = Some(try!(visitor.visit_value())),
Field::Changes => changes = Some(try!(visitor.visit_value())),
}
}
try!(visitor.end());
let inserted = inserted.unwrap_or(0);
let replaced = replaced.unwrap_or(0);
let unchanged = unchanged.unwrap_or(0);
let skipped = skipped.unwrap_or(0);
let deleted = deleted.unwrap_or(0);
let errors = errors.unwrap_or(0);
let first_error = first_error.unwrap_or_default();
let generated_keys = generated_keys.unwrap_or_default();
let warnings = warnings.unwrap_or_default();
Ok(WriteStatus {
inserted: inserted,
replaced: replaced,
unchanged: unchanged,
skipped: skipped,
deleted: deleted,
errors: errors,
first_error: first_error,
generated_keys: generated_keys,
warnings: warnings,
changes: changes,
})
}
}
deserializer.deserialize(WriteStatusVisitor(PhantomData))
}
}
|
{
let mut inserted = None;
let mut replaced = None;
let mut unchanged = None;
let mut skipped = None;
let mut deleted = None;
let mut errors = None;
let mut first_error = None;
let mut generated_keys = None;
let mut warnings = None;
let mut changes = None;
while let Some(key) = try!(visitor.visit_key()) {
match key {
Field::Inserted => inserted = Some(try!(visitor.visit_value())),
Field::Replaced => replaced = Some(try!(visitor.visit_value())),
Field::Unchanged => unchanged = Some(try!(visitor.visit_value())),
Field::Skipped => skipped = Some(try!(visitor.visit_value())),
Field::Deleted => deleted = Some(try!(visitor.visit_value())),
Field::Errors => errors = Some(try!(visitor.visit_value())),
|
identifier_body
|
query_result.rs
|
use std::marker::PhantomData;
use serde::{de, Deserialize, Deserializer};
use uuid::Uuid;
/// A report about the outcome of a write.
#[derive(Debug)]
pub struct WriteStatus<T> {
/// The number of new documents inserted. This counter is zero in case of an update or delete
/// operation. In case of a replace operation you can have new documents inserted if you do a
/// point-replace on a key that isn't in the table or you do a replace on a selection and one of
/// the documents you are replacing has been deleted.
pub inserted: u32,
|
/// The number of documents that would have been modified except the new value was the same as
/// the old value. This counter is zero in case of a delete operation or an insert operation
/// where `confict` is set to "error".
pub unchanged: u32,
/// The number of documents that were skipped because the document didn't exist. This counter is
/// zero in case of an insert or replace operation.
pub skipped: u32,
/// The number of documents that were deleted. This counter is zero in case of an insert or
/// update operation.
///
/// A replace with `None` increases this counter.
pub deleted: u32,
/// The number of errors encountered while performing the operation.
pub errors: u32,
/// If errors where encountered, contains the text of the first error.
pub first_error: String,
/// A list of generated primary keys for inserted documents whose primary keys were not
/// specified (capped to 100,000).
pub generated_keys: Vec<Uuid>,
/// If the field `generated_keys` is truncated, you will get the warning "Too many generated
/// keys (<X>), array truncated to 100000".
pub warnings: String,
/// If `return_changes` is set to `true`, this will be an array of objects, one for each
/// object affected by the `insert` operation.
pub changes: Option<Vec<(T, T)>>,
}
impl<T: Deserialize> Deserialize for WriteStatus<T> {
fn deserialize<D: Deserializer>(deserializer: &mut D) -> Result<Self, D::Error> {
field_visitor!(
enum Field {
"inserted" => Inserted,
"replaced" => Replaced,
"unchanged" => Unchanged,
"skipped" => Skipped,
"deleted" => Deleted,
"errors" => Errors,
"first_error" => FirstError,
"generated_keys" => GeneratedKeys,
"warnings" => Warnings,
"changes" => Changes,
},
FieldVisitor
);
struct WriteStatusVisitor<T>(PhantomData<T>);
impl<T> de::Visitor for WriteStatusVisitor<T>
where T: Deserialize
{
type Value = WriteStatus<T>;
fn visit_map<V>(&mut self, mut visitor: V) -> Result<Self::Value, V::Error>
where V: de::MapVisitor
{
let mut inserted = None;
let mut replaced = None;
let mut unchanged = None;
let mut skipped = None;
let mut deleted = None;
let mut errors = None;
let mut first_error = None;
let mut generated_keys = None;
let mut warnings = None;
let mut changes = None;
while let Some(key) = try!(visitor.visit_key()) {
match key {
Field::Inserted => inserted = Some(try!(visitor.visit_value())),
Field::Replaced => replaced = Some(try!(visitor.visit_value())),
Field::Unchanged => unchanged = Some(try!(visitor.visit_value())),
Field::Skipped => skipped = Some(try!(visitor.visit_value())),
Field::Deleted => deleted = Some(try!(visitor.visit_value())),
Field::Errors => errors = Some(try!(visitor.visit_value())),
Field::FirstError => first_error = Some(try!(visitor.visit_value())),
Field::GeneratedKeys => generated_keys = Some(try!(visitor.visit_value())),
Field::Warnings => warnings = Some(try!(visitor.visit_value())),
Field::Changes => changes = Some(try!(visitor.visit_value())),
}
}
try!(visitor.end());
let inserted = inserted.unwrap_or(0);
let replaced = replaced.unwrap_or(0);
let unchanged = unchanged.unwrap_or(0);
let skipped = skipped.unwrap_or(0);
let deleted = deleted.unwrap_or(0);
let errors = errors.unwrap_or(0);
let first_error = first_error.unwrap_or_default();
let generated_keys = generated_keys.unwrap_or_default();
let warnings = warnings.unwrap_or_default();
Ok(WriteStatus {
inserted: inserted,
replaced: replaced,
unchanged: unchanged,
skipped: skipped,
deleted: deleted,
errors: errors,
first_error: first_error,
generated_keys: generated_keys,
warnings: warnings,
changes: changes,
})
}
}
deserializer.deserialize(WriteStatusVisitor(PhantomData))
}
}
|
/// The number of documents that were updated or replaced. This counter is zero in case of a
/// delete operation or an insert operation where `conflict` isn't set to "replace" or "update".
pub replaced: u32,
|
random_line_split
|
mq_handler.rs
|
// Copyright Cryptape Technologies LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::helper::{RpcMap, TransferType};
use jsonrpc_proto::response::OutputExt;
use jsonrpc_types::rpc_response::Output;
use libproto::router::{MsgType, RoutingKey, SubModules};
use libproto::Message;
use libproto::TryFrom;
use serde_json;
#[derive(Default)]
pub struct
|
{
responses: RpcMap,
}
impl MqHandler {
pub fn new(responses: RpcMap) -> Self {
MqHandler { responses }
}
pub fn handle(&mut self, key: &str, body: &[u8]) -> Result<(), ()> {
trace!("get msg from routing_key {}", key);
let mut msg = Message::try_from(body).map_err(|e| {
error!("try_from: {:?}", e);
})?;
match RoutingKey::from(key) {
routing_key!(Auth >> Response)
| routing_key!(Chain >> Response)
| routing_key!(Executor >> Response)
| routing_key!(Jsonrpc >> Response)
| routing_key!(Net >> Response) => {
let content = msg.take_response().ok_or_else(|| {
error!("empty response message");
})?;
let resp = {
let request_id = &content.request_id;
trace!("from response request_id {:?}", request_id);
self.responses.lock().remove(request_id).ok_or_else(|| {
warn!("receive lost request_id {:?}", request_id);
})?
};
match resp {
TransferType::HTTP((req_info, sender)) => {
sender
.send(Output::from_res_info(content, req_info))
.map_err(|e| {
error!("http: {:?}", e);
})?;
}
TransferType::WEBSOCKET((req_info, sender)) => {
let json_body =
serde_json::to_string(&Output::from_res_info(content, req_info))
.map_err(|e| {
error!("ws: {:?}", e);
})?;
sender.send(json_body).map_err(|e| {
error!("ws: {:?}", e);
})?;
}
};
}
_ => {
warn!("receive unexpect key {}", key);
}
};
Ok(())
}
}
|
MqHandler
|
identifier_name
|
mq_handler.rs
|
// Copyright Cryptape Technologies LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::helper::{RpcMap, TransferType};
use jsonrpc_proto::response::OutputExt;
use jsonrpc_types::rpc_response::Output;
use libproto::router::{MsgType, RoutingKey, SubModules};
use libproto::Message;
use libproto::TryFrom;
use serde_json;
#[derive(Default)]
pub struct MqHandler {
responses: RpcMap,
}
impl MqHandler {
pub fn new(responses: RpcMap) -> Self {
MqHandler { responses }
}
pub fn handle(&mut self, key: &str, body: &[u8]) -> Result<(), ()> {
trace!("get msg from routing_key {}", key);
let mut msg = Message::try_from(body).map_err(|e| {
error!("try_from: {:?}", e);
})?;
match RoutingKey::from(key) {
routing_key!(Auth >> Response)
| routing_key!(Chain >> Response)
| routing_key!(Executor >> Response)
| routing_key!(Jsonrpc >> Response)
| routing_key!(Net >> Response) => {
let content = msg.take_response().ok_or_else(|| {
error!("empty response message");
})?;
let resp = {
let request_id = &content.request_id;
trace!("from response request_id {:?}", request_id);
self.responses.lock().remove(request_id).ok_or_else(|| {
warn!("receive lost request_id {:?}", request_id);
})?
};
match resp {
TransferType::HTTP((req_info, sender)) => {
sender
.send(Output::from_res_info(content, req_info))
.map_err(|e| {
error!("http: {:?}", e);
})?;
}
TransferType::WEBSOCKET((req_info, sender)) => {
let json_body =
serde_json::to_string(&Output::from_res_info(content, req_info))
.map_err(|e| {
error!("ws: {:?}", e);
})?;
sender.send(json_body).map_err(|e| {
error!("ws: {:?}", e);
})?;
}
};
}
_ => {
warn!("receive unexpect key {}", key);
}
};
Ok(())
}
}
|
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
|
random_line_split
|
reader.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.
//! A wrapper around any Reader to treat it as an RNG.
use option::{Some, None};
use rt::io::Reader;
use rt::io::ReaderByteConversions;
use rand::Rng;
/// An RNG that reads random bytes straight from a `Reader`. This will
/// work best with an infinite reader, but this is not required.
///
/// It will fail if it there is insufficient data to fulfill a request.
///
/// # Example
///
/// ```rust
/// use std::rand::{reader, Rng};
/// use std::rt::io::mem;
///
/// fn main() {
/// let mut rng = reader::ReaderRng::new(mem::MemReader::new(~[1,2,3,4,5,6,7,8]));
/// println!("{:x}", rng.gen::<uint>());
/// }
/// ```
pub struct ReaderRng<R> {
priv reader: R
}
impl<R: Reader> ReaderRng<R> {
/// Create a new `ReaderRng` from a `Reader`.
pub fn new(r: R) -> ReaderRng<R>
|
}
impl<R: Reader> Rng for ReaderRng<R> {
fn next_u32(&mut self) -> u32 {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
if cfg!(target_endian="little") {
self.reader.read_le_u32_()
} else {
self.reader.read_be_u32_()
}
}
fn next_u64(&mut self) -> u64 {
// see above for explanation.
if cfg!(target_endian="little") {
self.reader.read_le_u64_()
} else {
self.reader.read_be_u64_()
}
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
match self.reader.read(v) {
Some(n) if n == v.len() => return,
Some(n) => fail2!("ReaderRng.fill_bytes could not fill buffer: \
read {} out of {} bytes.", n, v.len()),
None => fail2!("ReaderRng.fill_bytes reached eof.")
}
}
}
#[cfg(test)]
mod test {
use super::*;
use rt::io::mem::MemReader;
use cast;
#[test]
fn test_reader_rng_u64() {
// transmute from the target to avoid endianness concerns.
let v = ~[1u64, 2u64, 3u64];
let bytes: ~[u8] = unsafe {cast::transmute(v)};
let mut rng = ReaderRng::new(MemReader::new(bytes));
assert_eq!(rng.next_u64(), 1);
assert_eq!(rng.next_u64(), 2);
assert_eq!(rng.next_u64(), 3);
}
#[test]
fn test_reader_rng_u32() {
// transmute from the target to avoid endianness concerns.
let v = ~[1u32, 2u32, 3u32];
let bytes: ~[u8] = unsafe {cast::transmute(v)};
let mut rng = ReaderRng::new(MemReader::new(bytes));
assert_eq!(rng.next_u32(), 1);
assert_eq!(rng.next_u32(), 2);
assert_eq!(rng.next_u32(), 3);
}
#[test]
fn test_reader_rng_fill_bytes() {
let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
let mut w = [0u8,.. 8];
let mut rng = ReaderRng::new(MemReader::new(v.to_owned()));
rng.fill_bytes(w);
assert_eq!(v, w);
}
#[test]
#[should_fail]
fn test_reader_rng_insufficient_bytes() {
let mut rng = ReaderRng::new(MemReader::new(~[]));
let mut v = [0u8,.. 3];
rng.fill_bytes(v);
}
}
|
{
ReaderRng {
reader: r
}
}
|
identifier_body
|
reader.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.
//! A wrapper around any Reader to treat it as an RNG.
use option::{Some, None};
use rt::io::Reader;
use rt::io::ReaderByteConversions;
use rand::Rng;
/// An RNG that reads random bytes straight from a `Reader`. This will
/// work best with an infinite reader, but this is not required.
///
/// It will fail if it there is insufficient data to fulfill a request.
///
/// # Example
///
/// ```rust
/// use std::rand::{reader, Rng};
/// use std::rt::io::mem;
///
/// fn main() {
/// let mut rng = reader::ReaderRng::new(mem::MemReader::new(~[1,2,3,4,5,6,7,8]));
/// println!("{:x}", rng.gen::<uint>());
/// }
/// ```
pub struct ReaderRng<R> {
priv reader: R
}
impl<R: Reader> ReaderRng<R> {
/// Create a new `ReaderRng` from a `Reader`.
pub fn new(r: R) -> ReaderRng<R> {
ReaderRng {
reader: r
}
}
}
impl<R: Reader> Rng for ReaderRng<R> {
fn
|
(&mut self) -> u32 {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
if cfg!(target_endian="little") {
self.reader.read_le_u32_()
} else {
self.reader.read_be_u32_()
}
}
fn next_u64(&mut self) -> u64 {
// see above for explanation.
if cfg!(target_endian="little") {
self.reader.read_le_u64_()
} else {
self.reader.read_be_u64_()
}
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
match self.reader.read(v) {
Some(n) if n == v.len() => return,
Some(n) => fail2!("ReaderRng.fill_bytes could not fill buffer: \
read {} out of {} bytes.", n, v.len()),
None => fail2!("ReaderRng.fill_bytes reached eof.")
}
}
}
#[cfg(test)]
mod test {
use super::*;
use rt::io::mem::MemReader;
use cast;
#[test]
fn test_reader_rng_u64() {
// transmute from the target to avoid endianness concerns.
let v = ~[1u64, 2u64, 3u64];
let bytes: ~[u8] = unsafe {cast::transmute(v)};
let mut rng = ReaderRng::new(MemReader::new(bytes));
assert_eq!(rng.next_u64(), 1);
assert_eq!(rng.next_u64(), 2);
assert_eq!(rng.next_u64(), 3);
}
#[test]
fn test_reader_rng_u32() {
// transmute from the target to avoid endianness concerns.
let v = ~[1u32, 2u32, 3u32];
let bytes: ~[u8] = unsafe {cast::transmute(v)};
let mut rng = ReaderRng::new(MemReader::new(bytes));
assert_eq!(rng.next_u32(), 1);
assert_eq!(rng.next_u32(), 2);
assert_eq!(rng.next_u32(), 3);
}
#[test]
fn test_reader_rng_fill_bytes() {
let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
let mut w = [0u8,.. 8];
let mut rng = ReaderRng::new(MemReader::new(v.to_owned()));
rng.fill_bytes(w);
assert_eq!(v, w);
}
#[test]
#[should_fail]
fn test_reader_rng_insufficient_bytes() {
let mut rng = ReaderRng::new(MemReader::new(~[]));
let mut v = [0u8,.. 3];
rng.fill_bytes(v);
}
}
|
next_u32
|
identifier_name
|
reader.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.
//! A wrapper around any Reader to treat it as an RNG.
use option::{Some, None};
use rt::io::Reader;
use rt::io::ReaderByteConversions;
use rand::Rng;
/// An RNG that reads random bytes straight from a `Reader`. This will
/// work best with an infinite reader, but this is not required.
///
/// It will fail if it there is insufficient data to fulfill a request.
///
/// # Example
///
/// ```rust
/// use std::rand::{reader, Rng};
/// use std::rt::io::mem;
///
/// fn main() {
/// let mut rng = reader::ReaderRng::new(mem::MemReader::new(~[1,2,3,4,5,6,7,8]));
/// println!("{:x}", rng.gen::<uint>());
/// }
/// ```
pub struct ReaderRng<R> {
priv reader: R
}
impl<R: Reader> ReaderRng<R> {
/// Create a new `ReaderRng` from a `Reader`.
pub fn new(r: R) -> ReaderRng<R> {
ReaderRng {
reader: r
}
}
}
impl<R: Reader> Rng for ReaderRng<R> {
fn next_u32(&mut self) -> u32 {
// This is designed for speed: reading a LE integer on a LE
// platform just involves blitting the bytes into the memory
// of the u32, similarly for BE on BE; avoiding byteswapping.
if cfg!(target_endian="little") {
self.reader.read_le_u32_()
} else {
self.reader.read_be_u32_()
}
}
fn next_u64(&mut self) -> u64 {
// see above for explanation.
if cfg!(target_endian="little") {
self.reader.read_le_u64_()
} else {
self.reader.read_be_u64_()
}
}
fn fill_bytes(&mut self, v: &mut [u8]) {
if v.len() == 0 { return }
match self.reader.read(v) {
Some(n) if n == v.len() => return,
Some(n) => fail2!("ReaderRng.fill_bytes could not fill buffer: \
read {} out of {} bytes.", n, v.len()),
None => fail2!("ReaderRng.fill_bytes reached eof.")
}
}
}
|
mod test {
use super::*;
use rt::io::mem::MemReader;
use cast;
#[test]
fn test_reader_rng_u64() {
// transmute from the target to avoid endianness concerns.
let v = ~[1u64, 2u64, 3u64];
let bytes: ~[u8] = unsafe {cast::transmute(v)};
let mut rng = ReaderRng::new(MemReader::new(bytes));
assert_eq!(rng.next_u64(), 1);
assert_eq!(rng.next_u64(), 2);
assert_eq!(rng.next_u64(), 3);
}
#[test]
fn test_reader_rng_u32() {
// transmute from the target to avoid endianness concerns.
let v = ~[1u32, 2u32, 3u32];
let bytes: ~[u8] = unsafe {cast::transmute(v)};
let mut rng = ReaderRng::new(MemReader::new(bytes));
assert_eq!(rng.next_u32(), 1);
assert_eq!(rng.next_u32(), 2);
assert_eq!(rng.next_u32(), 3);
}
#[test]
fn test_reader_rng_fill_bytes() {
let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
let mut w = [0u8,.. 8];
let mut rng = ReaderRng::new(MemReader::new(v.to_owned()));
rng.fill_bytes(w);
assert_eq!(v, w);
}
#[test]
#[should_fail]
fn test_reader_rng_insufficient_bytes() {
let mut rng = ReaderRng::new(MemReader::new(~[]));
let mut v = [0u8,.. 3];
rng.fill_bytes(v);
}
}
|
#[cfg(test)]
|
random_line_split
|
segment_stats.rs
|
use search::segment::Segment;
|
pub struct SegmentStatistics {
total_docs: i64,
deleted_docs: i64,
}
impl SegmentStatistics {
fn read<S: Segment>(segment: &S) -> Result<SegmentStatistics, String> {
let total_docs = try!(segment.load_statistic(b"total_docs")).unwrap_or(0);
let deleted_docs = try!(segment.load_statistic(b"deleted_docs")).unwrap_or(0);
Ok(SegmentStatistics {
total_docs: total_docs,
deleted_docs: deleted_docs,
})
}
#[inline]
pub fn total_docs(&self) -> i64 {
self.total_docs
}
#[inline]
pub fn deleted_docs(&self) -> i64 {
self.deleted_docs
}
}
impl RocksDBStore {
pub fn get_segment_statistics(&self) -> Result<Vec<(u32, SegmentStatistics)>, String> {
let mut segment_stats = Vec::new();
let reader = self.reader();
for segment in self.segments.iter_active(&reader) {
let stats = try!(SegmentStatistics::read(&segment));
segment_stats.push((segment.id().0, stats));
}
Ok(segment_stats)
}
}
|
use super::RocksDBStore;
#[derive(Debug)]
|
random_line_split
|
segment_stats.rs
|
use search::segment::Segment;
use super::RocksDBStore;
#[derive(Debug)]
pub struct SegmentStatistics {
total_docs: i64,
deleted_docs: i64,
}
impl SegmentStatistics {
fn read<S: Segment>(segment: &S) -> Result<SegmentStatistics, String> {
let total_docs = try!(segment.load_statistic(b"total_docs")).unwrap_or(0);
let deleted_docs = try!(segment.load_statistic(b"deleted_docs")).unwrap_or(0);
Ok(SegmentStatistics {
total_docs: total_docs,
deleted_docs: deleted_docs,
})
}
#[inline]
pub fn total_docs(&self) -> i64 {
self.total_docs
}
#[inline]
pub fn deleted_docs(&self) -> i64
|
}
impl RocksDBStore {
pub fn get_segment_statistics(&self) -> Result<Vec<(u32, SegmentStatistics)>, String> {
let mut segment_stats = Vec::new();
let reader = self.reader();
for segment in self.segments.iter_active(&reader) {
let stats = try!(SegmentStatistics::read(&segment));
segment_stats.push((segment.id().0, stats));
}
Ok(segment_stats)
}
}
|
{
self.deleted_docs
}
|
identifier_body
|
segment_stats.rs
|
use search::segment::Segment;
use super::RocksDBStore;
#[derive(Debug)]
pub struct SegmentStatistics {
total_docs: i64,
deleted_docs: i64,
}
impl SegmentStatistics {
fn read<S: Segment>(segment: &S) -> Result<SegmentStatistics, String> {
let total_docs = try!(segment.load_statistic(b"total_docs")).unwrap_or(0);
let deleted_docs = try!(segment.load_statistic(b"deleted_docs")).unwrap_or(0);
Ok(SegmentStatistics {
total_docs: total_docs,
deleted_docs: deleted_docs,
})
}
#[inline]
pub fn
|
(&self) -> i64 {
self.total_docs
}
#[inline]
pub fn deleted_docs(&self) -> i64 {
self.deleted_docs
}
}
impl RocksDBStore {
pub fn get_segment_statistics(&self) -> Result<Vec<(u32, SegmentStatistics)>, String> {
let mut segment_stats = Vec::new();
let reader = self.reader();
for segment in self.segments.iter_active(&reader) {
let stats = try!(SegmentStatistics::read(&segment));
segment_stats.push((segment.id().0, stats));
}
Ok(segment_stats)
}
}
|
total_docs
|
identifier_name
|
ip2_convolve3x3.rs
|
/*
* Copyright (C) 2012 The Android Open Source Project
*
|
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ip.rsh"
int32_t gWidth;
int32_t gHeight;
rs_allocation gIn;
float gCoeffs[9];
uchar4 RS_KERNEL root(uint32_t x, uint32_t y) {
uint32_t x1 = min((int32_t)x+1, gWidth-1);
uint32_t x2 = max((int32_t)x-1, 0);
uint32_t y1 = min((int32_t)y+1, gHeight-1);
uint32_t y2 = max((int32_t)y-1, 0);
float4 p00 = convert_float4(rsGetElementAt_uchar4(gIn, x1, y1));
float4 p01 = convert_float4(rsGetElementAt_uchar4(gIn, x, y1));
float4 p02 = convert_float4(rsGetElementAt_uchar4(gIn, x2, y1));
float4 p10 = convert_float4(rsGetElementAt_uchar4(gIn, x1, y));
float4 p11 = convert_float4(rsGetElementAt_uchar4(gIn, x, y));
float4 p12 = convert_float4(rsGetElementAt_uchar4(gIn, x2, y));
float4 p20 = convert_float4(rsGetElementAt_uchar4(gIn, x1, y2));
float4 p21 = convert_float4(rsGetElementAt_uchar4(gIn, x, y2));
float4 p22 = convert_float4(rsGetElementAt_uchar4(gIn, x2, y2));
p00 *= gCoeffs[0];
p01 *= gCoeffs[1];
p02 *= gCoeffs[2];
p10 *= gCoeffs[3];
p11 *= gCoeffs[4];
p12 *= gCoeffs[5];
p20 *= gCoeffs[6];
p21 *= gCoeffs[7];
p22 *= gCoeffs[8];
p00 += p01;
p02 += p10;
p11 += p12;
p20 += p21;
p22 += p00;
p02 += p11;
p20 += p22;
p20 += p02;
p20 = clamp(p20, 0.f, 255.f);
return convert_uchar4(p20);
}
|
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
|
random_line_split
|
client.rs
|
use std;
import core::result::*;
import socket::*;
fn from_bytes_n(bytes: [const u8], count: uint) -> str
|
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet_addr(host);
let sockaddr = new_sockaddr_in(af_inet, addr, port);
let r = connect(sock, sockaddr);
if failure(r) {
fail #fmt("cannot connect to %s:%u", host, port as uint);
}
send_str(sock, "HELLO", 0u);
let buf = vec::init_elt_mut(1024u, 0u8);
let size = recv(sock, buf, 0u);
let s = from_bytes_n(buf, size as uint);
std::io::println(s);
}
|
{
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
}
|
identifier_body
|
client.rs
|
use std;
import core::result::*;
import socket::*;
fn
|
(bytes: [const u8], count: uint) -> str {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
}
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet_addr(host);
let sockaddr = new_sockaddr_in(af_inet, addr, port);
let r = connect(sock, sockaddr);
if failure(r) {
fail #fmt("cannot connect to %s:%u", host, port as uint);
}
send_str(sock, "HELLO", 0u);
let buf = vec::init_elt_mut(1024u, 0u8);
let size = recv(sock, buf, 0u);
let s = from_bytes_n(buf, size as uint);
std::io::println(s);
}
|
from_bytes_n
|
identifier_name
|
client.rs
|
import socket::*;
fn from_bytes_n(bytes: [const u8], count: uint) -> str {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
}
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet_addr(host);
let sockaddr = new_sockaddr_in(af_inet, addr, port);
let r = connect(sock, sockaddr);
if failure(r) {
fail #fmt("cannot connect to %s:%u", host, port as uint);
}
send_str(sock, "HELLO", 0u);
let buf = vec::init_elt_mut(1024u, 0u8);
let size = recv(sock, buf, 0u);
let s = from_bytes_n(buf, size as uint);
std::io::println(s);
}
|
use std;
import core::result::*;
|
random_line_split
|
|
client.rs
|
use std;
import core::result::*;
import socket::*;
fn from_bytes_n(bytes: [const u8], count: uint) -> str {
assert count <= vec::len(bytes);
ret str::from_bytes(vec::slice(bytes, 0u, count));
}
fn main() {
let host = "0.0.0.0";
let port = 12345u16;
let sock = new_tcp_socket();
let addr = inet_addr(host);
let sockaddr = new_sockaddr_in(af_inet, addr, port);
let r = connect(sock, sockaddr);
if failure(r)
|
send_str(sock, "HELLO", 0u);
let buf = vec::init_elt_mut(1024u, 0u8);
let size = recv(sock, buf, 0u);
let s = from_bytes_n(buf, size as uint);
std::io::println(s);
}
|
{
fail #fmt("cannot connect to %s:%u", host, port as uint);
}
|
conditional_block
|
position.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Position", inherited=False) %>
% for side in ["top", "right", "bottom", "left"]:
${helpers.predefined_type(side, "LengthOrPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto")}
% endfor
<%helpers:longhand name="z-index">
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
pub type SpecifiedValue = computed_value::T;
pub mod computed_value {
use cssparser::ToCss;
use std::fmt;
#[derive(PartialEq, Clone, Eq, Copy, Debug, HeapSizeOf)]
pub enum T {
Auto,
Number(i32),
}
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
T::Auto => dest.write_str("auto"),
T::Number(number) => write!(dest, "{}", number),
}
}
}
impl T {
pub fn number_or_zero(self) -> i32 {
match self {
T::Auto => 0,
T::Number(value) => value,
}
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::Auto
}
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if input.try(|input| input.expect_ident_matching("auto")).is_ok() {
Ok(computed_value::T::Auto)
} else {
specified::parse_integer(input).map(computed_value::T::Number)
}
}
</%helpers:longhand>
// CSS Flexible Box Layout Module Level 1
// http://www.w3.org/TR/css3-flexbox/
// Flex container properties
${helpers.single_keyword("flex-direction", "row row-reverse column column-reverse", experimental=True)}
${helpers.single_keyword("flex-wrap", "nowrap wrap wrap-reverse", experimental=True)}
// FIXME(stshine): The type of 'justify-content' and 'align-content' is uint16_t in gecko
// FIXME(stshine): Its higher bytes are used to store fallback value. Disable them in geckolib for now
${helpers.single_keyword("justify-content", "flex-start flex-end center space-between space-around",
experimental=True,
gecko_constant_prefix="NS_STYLE_JUSTIFY",
products="servo")}
${helpers.single_keyword("align-items", "stretch flex-start flex-end center baseline",
experimental=True,
need_clone=True,
gecko_constant_prefix="NS_STYLE_ALIGN")}
${helpers.single_keyword("align-content", "stretch flex-start flex-end center space-between space-around",
experimental=True,
gecko_constant_prefix="NS_STYLE_ALIGN",
products="servo")}
// Flex item properties
${helpers.predefined_type("flex-grow", "Number", "0.0", "parse_non_negative", experimental=True)}
${helpers.predefined_type("flex-shrink", "Number", "1.0", "parse_non_negative", experimental=True)}
${helpers.single_keyword("align-self", "auto stretch flex-start flex-end center baseline",
experimental=True,
need_clone=True,
gecko_constant_prefix="NS_STYLE_ALIGN")}
// https://drafts.csswg.org/css-flexbox/#propdef-order
<%helpers:longhand name="order">
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
pub type SpecifiedValue = computed_value::T;
pub mod computed_value {
pub type T = i32;
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
0
}
fn
|
(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
specified::parse_integer(input)
}
</%helpers:longhand>
${helpers.predefined_type("flex-basis",
"LengthOrPercentageOrAutoOrContent",
"computed::LengthOrPercentageOrAutoOrContent::Auto")}
${helpers.predefined_type("width",
"LengthOrPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto",
"parse_non_negative")}
${helpers.predefined_type("height",
"LengthOrPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto",
"parse_non_negative")}
${helpers.predefined_type("min-width",
"LengthOrPercentage",
"computed::LengthOrPercentage::Length(Au(0))",
"parse_non_negative")}
${helpers.predefined_type("max-width",
"LengthOrPercentageOrNone",
"computed::LengthOrPercentageOrNone::None",
"parse_non_negative")}
${helpers.predefined_type("min-height",
"LengthOrPercentage",
"computed::LengthOrPercentage::Length(Au(0))",
"parse_non_negative")}
${helpers.predefined_type("max-height",
"LengthOrPercentageOrNone",
"computed::LengthOrPercentageOrNone::None",
"parse_non_negative")}
${helpers.single_keyword("box-sizing",
"content-box border-box")}
// CSS Image Values and Replaced Content Module Level 3
// https://drafts.csswg.org/css-images-3/
${helpers.single_keyword("object-fit", "fill contain cover none scale-down", products="gecko")}
|
parse
|
identifier_name
|
position.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("Position", inherited=False) %>
% for side in ["top", "right", "bottom", "left"]:
${helpers.predefined_type(side, "LengthOrPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto")}
% endfor
<%helpers:longhand name="z-index">
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
pub type SpecifiedValue = computed_value::T;
pub mod computed_value {
use cssparser::ToCss;
use std::fmt;
#[derive(PartialEq, Clone, Eq, Copy, Debug, HeapSizeOf)]
pub enum T {
Auto,
Number(i32),
}
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
T::Auto => dest.write_str("auto"),
T::Number(number) => write!(dest, "{}", number),
}
}
}
impl T {
pub fn number_or_zero(self) -> i32 {
match self {
T::Auto => 0,
T::Number(value) => value,
}
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::Auto
}
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if input.try(|input| input.expect_ident_matching("auto")).is_ok() {
Ok(computed_value::T::Auto)
} else {
specified::parse_integer(input).map(computed_value::T::Number)
}
}
</%helpers:longhand>
// CSS Flexible Box Layout Module Level 1
// http://www.w3.org/TR/css3-flexbox/
// Flex container properties
${helpers.single_keyword("flex-direction", "row row-reverse column column-reverse", experimental=True)}
${helpers.single_keyword("flex-wrap", "nowrap wrap wrap-reverse", experimental=True)}
// FIXME(stshine): The type of 'justify-content' and 'align-content' is uint16_t in gecko
// FIXME(stshine): Its higher bytes are used to store fallback value. Disable them in geckolib for now
${helpers.single_keyword("justify-content", "flex-start flex-end center space-between space-around",
experimental=True,
gecko_constant_prefix="NS_STYLE_JUSTIFY",
products="servo")}
${helpers.single_keyword("align-items", "stretch flex-start flex-end center baseline",
experimental=True,
need_clone=True,
gecko_constant_prefix="NS_STYLE_ALIGN")}
${helpers.single_keyword("align-content", "stretch flex-start flex-end center space-between space-around",
experimental=True,
gecko_constant_prefix="NS_STYLE_ALIGN",
products="servo")}
|
${helpers.predefined_type("flex-grow", "Number", "0.0", "parse_non_negative", experimental=True)}
${helpers.predefined_type("flex-shrink", "Number", "1.0", "parse_non_negative", experimental=True)}
${helpers.single_keyword("align-self", "auto stretch flex-start flex-end center baseline",
experimental=True,
need_clone=True,
gecko_constant_prefix="NS_STYLE_ALIGN")}
// https://drafts.csswg.org/css-flexbox/#propdef-order
<%helpers:longhand name="order">
use values::computed::ComputedValueAsSpecified;
impl ComputedValueAsSpecified for SpecifiedValue {}
pub type SpecifiedValue = computed_value::T;
pub mod computed_value {
pub type T = i32;
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
0
}
fn parse(_context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
specified::parse_integer(input)
}
</%helpers:longhand>
${helpers.predefined_type("flex-basis",
"LengthOrPercentageOrAutoOrContent",
"computed::LengthOrPercentageOrAutoOrContent::Auto")}
${helpers.predefined_type("width",
"LengthOrPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto",
"parse_non_negative")}
${helpers.predefined_type("height",
"LengthOrPercentageOrAuto",
"computed::LengthOrPercentageOrAuto::Auto",
"parse_non_negative")}
${helpers.predefined_type("min-width",
"LengthOrPercentage",
"computed::LengthOrPercentage::Length(Au(0))",
"parse_non_negative")}
${helpers.predefined_type("max-width",
"LengthOrPercentageOrNone",
"computed::LengthOrPercentageOrNone::None",
"parse_non_negative")}
${helpers.predefined_type("min-height",
"LengthOrPercentage",
"computed::LengthOrPercentage::Length(Au(0))",
"parse_non_negative")}
${helpers.predefined_type("max-height",
"LengthOrPercentageOrNone",
"computed::LengthOrPercentageOrNone::None",
"parse_non_negative")}
${helpers.single_keyword("box-sizing",
"content-box border-box")}
// CSS Image Values and Replaced Content Module Level 3
// https://drafts.csswg.org/css-images-3/
${helpers.single_keyword("object-fit", "fill contain cover none scale-down", products="gecko")}
|
// Flex item properties
|
random_line_split
|
method-ambig-one-trait-unknown-int-type.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 that we invoking `foo()` successfully resolves to the trait `foo`
// (prompting the mismatched types error) but does not influence the choice
// of what kind of `Vec` we have, eventually leading to a type error.
trait foo {
fn foo(&self) -> isize;
}
impl foo for Vec<usize> {
fn foo(&self) -> isize {1}
}
impl foo for Vec<isize> {
fn foo(&self) -> isize {2}
|
// distinct functions, in this order, causes us to print out both
// errors I'd like to see.
fn m1() {
// we couldn't infer the type of the vector just based on calling foo()...
let mut x = Vec::new(); //~ ERROR type annotations required
x.foo();
}
fn m2() {
let mut x = Vec::new();
//...but we still resolved `foo()` to the trait and hence know the return type.
let y: usize = x.foo(); //~ ERROR mismatched types
}
fn main() { }
|
}
// This is very hokey: we have heuristics to suppress messages about
// type annotations required. But placing these two bits of code into
|
random_line_split
|
method-ambig-one-trait-unknown-int-type.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 that we invoking `foo()` successfully resolves to the trait `foo`
// (prompting the mismatched types error) but does not influence the choice
// of what kind of `Vec` we have, eventually leading to a type error.
trait foo {
fn foo(&self) -> isize;
}
impl foo for Vec<usize> {
fn foo(&self) -> isize {1}
}
impl foo for Vec<isize> {
fn foo(&self) -> isize {2}
}
// This is very hokey: we have heuristics to suppress messages about
// type annotations required. But placing these two bits of code into
// distinct functions, in this order, causes us to print out both
// errors I'd like to see.
fn m1() {
// we couldn't infer the type of the vector just based on calling foo()...
let mut x = Vec::new(); //~ ERROR type annotations required
x.foo();
}
fn m2() {
let mut x = Vec::new();
//...but we still resolved `foo()` to the trait and hence know the return type.
let y: usize = x.foo(); //~ ERROR mismatched types
}
fn
|
() { }
|
main
|
identifier_name
|
method-ambig-one-trait-unknown-int-type.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 that we invoking `foo()` successfully resolves to the trait `foo`
// (prompting the mismatched types error) but does not influence the choice
// of what kind of `Vec` we have, eventually leading to a type error.
trait foo {
fn foo(&self) -> isize;
}
impl foo for Vec<usize> {
fn foo(&self) -> isize
|
}
impl foo for Vec<isize> {
fn foo(&self) -> isize {2}
}
// This is very hokey: we have heuristics to suppress messages about
// type annotations required. But placing these two bits of code into
// distinct functions, in this order, causes us to print out both
// errors I'd like to see.
fn m1() {
// we couldn't infer the type of the vector just based on calling foo()...
let mut x = Vec::new(); //~ ERROR type annotations required
x.foo();
}
fn m2() {
let mut x = Vec::new();
//...but we still resolved `foo()` to the trait and hence know the return type.
let y: usize = x.foo(); //~ ERROR mismatched types
}
fn main() { }
|
{1}
|
identifier_body
|
union-derive-rpass.rs
|
// run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![allow(dead_code)]
#![allow(unused_variables)]
// Some traits can be derived for unions.
|
)]
union U {
a: u8,
b: u16,
}
impl PartialEq for U { fn eq(&self, rhs: &Self) -> bool { true } }
#[derive(
Clone,
Copy,
Eq
)]
union W<T: Copy> {
a: T,
}
impl<T: Copy> PartialEq for W<T> { fn eq(&self, rhs: &Self) -> bool { true } }
fn main() {
let u = U { b: 0 };
let u1 = u;
let u2 = u.clone();
assert!(u1 == u2);
let w = W { a: 0 };
let w1 = w.clone();
assert!(w == w1);
}
|
#[derive(
Copy,
Clone,
Eq,
|
random_line_split
|
union-derive-rpass.rs
|
// run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![allow(dead_code)]
#![allow(unused_variables)]
// Some traits can be derived for unions.
#[derive(
Copy,
Clone,
Eq,
)]
union U {
a: u8,
b: u16,
}
impl PartialEq for U { fn eq(&self, rhs: &Self) -> bool { true } }
#[derive(
Clone,
Copy,
Eq
)]
union W<T: Copy> {
a: T,
}
impl<T: Copy> PartialEq for W<T> { fn eq(&self, rhs: &Self) -> bool { true } }
fn main()
|
{
let u = U { b: 0 };
let u1 = u;
let u2 = u.clone();
assert!(u1 == u2);
let w = W { a: 0 };
let w1 = w.clone();
assert!(w == w1);
}
|
identifier_body
|
|
union-derive-rpass.rs
|
// run-pass
// revisions: mirunsafeck thirunsafeck
// [thirunsafeck]compile-flags: -Z thir-unsafeck
#![allow(dead_code)]
#![allow(unused_variables)]
// Some traits can be derived for unions.
#[derive(
Copy,
Clone,
Eq,
)]
union U {
a: u8,
b: u16,
}
impl PartialEq for U { fn
|
(&self, rhs: &Self) -> bool { true } }
#[derive(
Clone,
Copy,
Eq
)]
union W<T: Copy> {
a: T,
}
impl<T: Copy> PartialEq for W<T> { fn eq(&self, rhs: &Self) -> bool { true } }
fn main() {
let u = U { b: 0 };
let u1 = u;
let u2 = u.clone();
assert!(u1 == u2);
let w = W { a: 0 };
let w1 = w.clone();
assert!(w == w1);
}
|
eq
|
identifier_name
|
mod.rs
|
// Copyright 2012-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.
//! The compiler code necessary to implement the `#[derive]` extensions.
//!
//! FIXME (#2810): hygiene. Search for "__" strings (in other files too). We also assume "extra" is
//! the standard library, and "std" is the core library.
use ast::{MetaItem, MetaWord};
use attr::AttrMetaMethods;
use ext::base::{ExtCtxt, SyntaxEnv, MultiDecorator, MultiItemDecorator, MultiModifier, Annotatable};
use ext::build::AstBuilder;
use feature_gate;
use codemap::Span;
use parse::token::{intern, intern_and_get_ident};
macro_rules! pathvec {
($($x:ident)::+) => (
vec![ $( stringify!($x) ),+ ]
)
}
macro_rules! path {
($($x:tt)*) => (
::ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) )
)
}
macro_rules! path_local {
($x:ident) => (
::ext::deriving::generic::ty::Path::new_local(stringify!($x))
)
}
macro_rules! pathvec_std {
($cx:expr, $first:ident :: $($rest:ident)::+) => ({
let mut v = pathvec!($($rest)::+);
if let Some(s) = $cx.crate_root {
v.insert(0, s);
}
v
})
}
macro_rules! path_std {
($($x:tt)*) => (
::ext::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
)
}
pub mod bounds;
pub mod clone;
pub mod encodable;
pub mod decodable;
pub mod hash;
pub mod show;
pub mod default;
pub mod primitive;
#[path="cmp/partial_eq.rs"]
pub mod partial_eq;
#[path="cmp/eq.rs"]
pub mod eq;
#[path="cmp/partial_ord.rs"]
pub mod partial_ord;
#[path="cmp/ord.rs"]
pub mod ord;
pub mod generic;
fn
|
(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
annotatable: Annotatable)
-> Annotatable {
annotatable.map_item_or(|item| {
item.map(|mut item| {
if mitem.value_str().is_some() {
cx.span_err(mitem.span, "unexpected value in `derive`");
}
let traits = mitem.meta_item_list().unwrap_or(&[]);
if traits.is_empty() {
cx.span_warn(mitem.span, "empty trait list in `derive`");
}
for titem in traits.iter().rev() {
let tname = match titem.node {
MetaWord(ref tname) => tname,
_ => {
cx.span_err(titem.span, "malformed `derive` entry");
continue;
}
};
if!(is_builtin_trait(tname) || cx.ecfg.enable_custom_derive()) {
feature_gate::emit_feature_err(&cx.parse_sess.span_diagnostic,
"custom_derive",
titem.span,
feature_gate::EXPLAIN_CUSTOM_DERIVE);
continue;
}
// #[derive(Foo, Bar)] expands to #[derive_Foo] #[derive_Bar]
item.attrs.push(cx.attribute(titem.span, cx.meta_word(titem.span,
intern_and_get_ident(&format!("derive_{}", tname)))));
}
item
})
}, |a| {
cx.span_err(span, "`derive` can only be applied to items");
a
})
}
macro_rules! derive_traits {
($( $name:expr => $func:path, )+) => {
pub fn register_all(env: &mut SyntaxEnv) {
// Define the #[derive_*] extensions.
$({
struct DeriveExtension;
impl MultiItemDecorator for DeriveExtension {
fn expand(&self,
ecx: &mut ExtCtxt,
sp: Span,
mitem: &MetaItem,
annotatable: &Annotatable,
push: &mut FnMut(Annotatable)) {
warn_if_deprecated(ecx, sp, $name);
$func(ecx, sp, mitem, annotatable, push);
}
}
env.insert(intern(concat!("derive_", $name)),
MultiDecorator(Box::new(DeriveExtension)));
})+
env.insert(intern("derive"),
MultiModifier(Box::new(expand_derive)));
}
fn is_builtin_trait(name: &str) -> bool {
match name {
$( $name )|+ => true,
_ => false,
}
}
}
}
derive_traits! {
"Clone" => clone::expand_deriving_clone,
"Hash" => hash::expand_deriving_hash,
"RustcEncodable" => encodable::expand_deriving_rustc_encodable,
"RustcDecodable" => decodable::expand_deriving_rustc_decodable,
"PartialEq" => partial_eq::expand_deriving_partial_eq,
"Eq" => eq::expand_deriving_eq,
"PartialOrd" => partial_ord::expand_deriving_partial_ord,
"Ord" => ord::expand_deriving_ord,
"Debug" => show::expand_deriving_show,
"Default" => default::expand_deriving_default,
"FromPrimitive" => primitive::expand_deriving_from_primitive,
"Send" => bounds::expand_deriving_unsafe_bound,
"Sync" => bounds::expand_deriving_unsafe_bound,
"Copy" => bounds::expand_deriving_copy,
// deprecated
"Show" => show::expand_deriving_show,
"Encodable" => encodable::expand_deriving_encodable,
"Decodable" => decodable::expand_deriving_decodable,
}
#[inline] // because `name` is a compile-time constant
fn warn_if_deprecated(ecx: &mut ExtCtxt, sp: Span, name: &str) {
if let Some(replacement) = match name {
"Show" => Some("Debug"),
"Encodable" => Some("RustcEncodable"),
"Decodable" => Some("RustcDecodable"),
_ => None,
} {
ecx.span_warn(sp, &format!("derive({}) is deprecated in favor of derive({})",
name, replacement));
}
}
|
expand_derive
|
identifier_name
|
mod.rs
|
// Copyright 2012-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.
//! The compiler code necessary to implement the `#[derive]` extensions.
//!
//! FIXME (#2810): hygiene. Search for "__" strings (in other files too). We also assume "extra" is
//! the standard library, and "std" is the core library.
use ast::{MetaItem, MetaWord};
use attr::AttrMetaMethods;
use ext::base::{ExtCtxt, SyntaxEnv, MultiDecorator, MultiItemDecorator, MultiModifier, Annotatable};
use ext::build::AstBuilder;
use feature_gate;
use codemap::Span;
use parse::token::{intern, intern_and_get_ident};
macro_rules! pathvec {
($($x:ident)::+) => (
vec![ $( stringify!($x) ),+ ]
)
}
macro_rules! path {
($($x:tt)*) => (
::ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) )
)
}
macro_rules! path_local {
($x:ident) => (
::ext::deriving::generic::ty::Path::new_local(stringify!($x))
)
}
macro_rules! pathvec_std {
($cx:expr, $first:ident :: $($rest:ident)::+) => ({
let mut v = pathvec!($($rest)::+);
if let Some(s) = $cx.crate_root {
v.insert(0, s);
}
v
})
}
macro_rules! path_std {
($($x:tt)*) => (
::ext::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
)
}
pub mod bounds;
pub mod clone;
pub mod encodable;
pub mod decodable;
pub mod hash;
pub mod show;
pub mod default;
pub mod primitive;
#[path="cmp/partial_eq.rs"]
pub mod partial_eq;
#[path="cmp/eq.rs"]
pub mod eq;
#[path="cmp/partial_ord.rs"]
pub mod partial_ord;
#[path="cmp/ord.rs"]
pub mod ord;
pub mod generic;
fn expand_derive(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
annotatable: Annotatable)
-> Annotatable
|
if!(is_builtin_trait(tname) || cx.ecfg.enable_custom_derive()) {
feature_gate::emit_feature_err(&cx.parse_sess.span_diagnostic,
"custom_derive",
titem.span,
feature_gate::EXPLAIN_CUSTOM_DERIVE);
continue;
}
// #[derive(Foo, Bar)] expands to #[derive_Foo] #[derive_Bar]
item.attrs.push(cx.attribute(titem.span, cx.meta_word(titem.span,
intern_and_get_ident(&format!("derive_{}", tname)))));
}
item
})
}, |a| {
cx.span_err(span, "`derive` can only be applied to items");
a
})
}
macro_rules! derive_traits {
($( $name:expr => $func:path, )+) => {
pub fn register_all(env: &mut SyntaxEnv) {
// Define the #[derive_*] extensions.
$({
struct DeriveExtension;
impl MultiItemDecorator for DeriveExtension {
fn expand(&self,
ecx: &mut ExtCtxt,
sp: Span,
mitem: &MetaItem,
annotatable: &Annotatable,
push: &mut FnMut(Annotatable)) {
warn_if_deprecated(ecx, sp, $name);
$func(ecx, sp, mitem, annotatable, push);
}
}
env.insert(intern(concat!("derive_", $name)),
MultiDecorator(Box::new(DeriveExtension)));
})+
env.insert(intern("derive"),
MultiModifier(Box::new(expand_derive)));
}
fn is_builtin_trait(name: &str) -> bool {
match name {
$( $name )|+ => true,
_ => false,
}
}
}
}
derive_traits! {
"Clone" => clone::expand_deriving_clone,
"Hash" => hash::expand_deriving_hash,
"RustcEncodable" => encodable::expand_deriving_rustc_encodable,
"RustcDecodable" => decodable::expand_deriving_rustc_decodable,
"PartialEq" => partial_eq::expand_deriving_partial_eq,
"Eq" => eq::expand_deriving_eq,
"PartialOrd" => partial_ord::expand_deriving_partial_ord,
"Ord" => ord::expand_deriving_ord,
"Debug" => show::expand_deriving_show,
"Default" => default::expand_deriving_default,
"FromPrimitive" => primitive::expand_deriving_from_primitive,
"Send" => bounds::expand_deriving_unsafe_bound,
"Sync" => bounds::expand_deriving_unsafe_bound,
"Copy" => bounds::expand_deriving_copy,
// deprecated
"Show" => show::expand_deriving_show,
"Encodable" => encodable::expand_deriving_encodable,
"Decodable" => decodable::expand_deriving_decodable,
}
#[inline] // because `name` is a compile-time constant
fn warn_if_deprecated(ecx: &mut ExtCtxt, sp: Span, name: &str) {
if let Some(replacement) = match name {
"Show" => Some("Debug"),
"Encodable" => Some("RustcEncodable"),
"Decodable" => Some("RustcDecodable"),
_ => None,
} {
ecx.span_warn(sp, &format!("derive({}) is deprecated in favor of derive({})",
name, replacement));
}
}
|
{
annotatable.map_item_or(|item| {
item.map(|mut item| {
if mitem.value_str().is_some() {
cx.span_err(mitem.span, "unexpected value in `derive`");
}
let traits = mitem.meta_item_list().unwrap_or(&[]);
if traits.is_empty() {
cx.span_warn(mitem.span, "empty trait list in `derive`");
}
for titem in traits.iter().rev() {
let tname = match titem.node {
MetaWord(ref tname) => tname,
_ => {
cx.span_err(titem.span, "malformed `derive` entry");
continue;
}
};
|
identifier_body
|
mod.rs
|
// Copyright 2012-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.
//! The compiler code necessary to implement the `#[derive]` extensions.
//!
//! FIXME (#2810): hygiene. Search for "__" strings (in other files too). We also assume "extra" is
//! the standard library, and "std" is the core library.
use ast::{MetaItem, MetaWord};
use attr::AttrMetaMethods;
use ext::base::{ExtCtxt, SyntaxEnv, MultiDecorator, MultiItemDecorator, MultiModifier, Annotatable};
use ext::build::AstBuilder;
use feature_gate;
use codemap::Span;
use parse::token::{intern, intern_and_get_ident};
macro_rules! pathvec {
($($x:ident)::+) => (
vec![ $( stringify!($x) ),+ ]
)
}
macro_rules! path {
($($x:tt)*) => (
::ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) )
)
}
macro_rules! path_local {
($x:ident) => (
::ext::deriving::generic::ty::Path::new_local(stringify!($x))
)
}
macro_rules! pathvec_std {
($cx:expr, $first:ident :: $($rest:ident)::+) => ({
let mut v = pathvec!($($rest)::+);
if let Some(s) = $cx.crate_root {
v.insert(0, s);
}
v
})
}
macro_rules! path_std {
($($x:tt)*) => (
::ext::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
)
}
pub mod bounds;
pub mod clone;
pub mod encodable;
pub mod decodable;
pub mod hash;
pub mod show;
pub mod default;
pub mod primitive;
#[path="cmp/partial_eq.rs"]
pub mod partial_eq;
#[path="cmp/eq.rs"]
pub mod eq;
#[path="cmp/partial_ord.rs"]
pub mod partial_ord;
#[path="cmp/ord.rs"]
pub mod ord;
pub mod generic;
fn expand_derive(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
annotatable: Annotatable)
-> Annotatable {
annotatable.map_item_or(|item| {
item.map(|mut item| {
if mitem.value_str().is_some() {
cx.span_err(mitem.span, "unexpected value in `derive`");
}
let traits = mitem.meta_item_list().unwrap_or(&[]);
if traits.is_empty()
|
for titem in traits.iter().rev() {
let tname = match titem.node {
MetaWord(ref tname) => tname,
_ => {
cx.span_err(titem.span, "malformed `derive` entry");
continue;
}
};
if!(is_builtin_trait(tname) || cx.ecfg.enable_custom_derive()) {
feature_gate::emit_feature_err(&cx.parse_sess.span_diagnostic,
"custom_derive",
titem.span,
feature_gate::EXPLAIN_CUSTOM_DERIVE);
continue;
}
// #[derive(Foo, Bar)] expands to #[derive_Foo] #[derive_Bar]
item.attrs.push(cx.attribute(titem.span, cx.meta_word(titem.span,
intern_and_get_ident(&format!("derive_{}", tname)))));
}
item
})
}, |a| {
cx.span_err(span, "`derive` can only be applied to items");
a
})
}
macro_rules! derive_traits {
($( $name:expr => $func:path, )+) => {
pub fn register_all(env: &mut SyntaxEnv) {
// Define the #[derive_*] extensions.
$({
struct DeriveExtension;
impl MultiItemDecorator for DeriveExtension {
fn expand(&self,
ecx: &mut ExtCtxt,
sp: Span,
mitem: &MetaItem,
annotatable: &Annotatable,
push: &mut FnMut(Annotatable)) {
warn_if_deprecated(ecx, sp, $name);
$func(ecx, sp, mitem, annotatable, push);
}
}
env.insert(intern(concat!("derive_", $name)),
MultiDecorator(Box::new(DeriveExtension)));
})+
env.insert(intern("derive"),
MultiModifier(Box::new(expand_derive)));
}
fn is_builtin_trait(name: &str) -> bool {
match name {
$( $name )|+ => true,
_ => false,
}
}
}
}
derive_traits! {
"Clone" => clone::expand_deriving_clone,
"Hash" => hash::expand_deriving_hash,
"RustcEncodable" => encodable::expand_deriving_rustc_encodable,
"RustcDecodable" => decodable::expand_deriving_rustc_decodable,
"PartialEq" => partial_eq::expand_deriving_partial_eq,
"Eq" => eq::expand_deriving_eq,
"PartialOrd" => partial_ord::expand_deriving_partial_ord,
"Ord" => ord::expand_deriving_ord,
"Debug" => show::expand_deriving_show,
"Default" => default::expand_deriving_default,
"FromPrimitive" => primitive::expand_deriving_from_primitive,
"Send" => bounds::expand_deriving_unsafe_bound,
"Sync" => bounds::expand_deriving_unsafe_bound,
"Copy" => bounds::expand_deriving_copy,
// deprecated
"Show" => show::expand_deriving_show,
"Encodable" => encodable::expand_deriving_encodable,
"Decodable" => decodable::expand_deriving_decodable,
}
#[inline] // because `name` is a compile-time constant
fn warn_if_deprecated(ecx: &mut ExtCtxt, sp: Span, name: &str) {
if let Some(replacement) = match name {
"Show" => Some("Debug"),
"Encodable" => Some("RustcEncodable"),
"Decodable" => Some("RustcDecodable"),
_ => None,
} {
ecx.span_warn(sp, &format!("derive({}) is deprecated in favor of derive({})",
name, replacement));
}
}
|
{
cx.span_warn(mitem.span, "empty trait list in `derive`");
}
|
conditional_block
|
mod.rs
|
// Copyright 2012-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
|
//! The compiler code necessary to implement the `#[derive]` extensions.
//!
//! FIXME (#2810): hygiene. Search for "__" strings (in other files too). We also assume "extra" is
//! the standard library, and "std" is the core library.
use ast::{MetaItem, MetaWord};
use attr::AttrMetaMethods;
use ext::base::{ExtCtxt, SyntaxEnv, MultiDecorator, MultiItemDecorator, MultiModifier, Annotatable};
use ext::build::AstBuilder;
use feature_gate;
use codemap::Span;
use parse::token::{intern, intern_and_get_ident};
macro_rules! pathvec {
($($x:ident)::+) => (
vec![ $( stringify!($x) ),+ ]
)
}
macro_rules! path {
($($x:tt)*) => (
::ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) )
)
}
macro_rules! path_local {
($x:ident) => (
::ext::deriving::generic::ty::Path::new_local(stringify!($x))
)
}
macro_rules! pathvec_std {
($cx:expr, $first:ident :: $($rest:ident)::+) => ({
let mut v = pathvec!($($rest)::+);
if let Some(s) = $cx.crate_root {
v.insert(0, s);
}
v
})
}
macro_rules! path_std {
($($x:tt)*) => (
::ext::deriving::generic::ty::Path::new( pathvec_std!( $($x)* ) )
)
}
pub mod bounds;
pub mod clone;
pub mod encodable;
pub mod decodable;
pub mod hash;
pub mod show;
pub mod default;
pub mod primitive;
#[path="cmp/partial_eq.rs"]
pub mod partial_eq;
#[path="cmp/eq.rs"]
pub mod eq;
#[path="cmp/partial_ord.rs"]
pub mod partial_ord;
#[path="cmp/ord.rs"]
pub mod ord;
pub mod generic;
fn expand_derive(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
annotatable: Annotatable)
-> Annotatable {
annotatable.map_item_or(|item| {
item.map(|mut item| {
if mitem.value_str().is_some() {
cx.span_err(mitem.span, "unexpected value in `derive`");
}
let traits = mitem.meta_item_list().unwrap_or(&[]);
if traits.is_empty() {
cx.span_warn(mitem.span, "empty trait list in `derive`");
}
for titem in traits.iter().rev() {
let tname = match titem.node {
MetaWord(ref tname) => tname,
_ => {
cx.span_err(titem.span, "malformed `derive` entry");
continue;
}
};
if!(is_builtin_trait(tname) || cx.ecfg.enable_custom_derive()) {
feature_gate::emit_feature_err(&cx.parse_sess.span_diagnostic,
"custom_derive",
titem.span,
feature_gate::EXPLAIN_CUSTOM_DERIVE);
continue;
}
// #[derive(Foo, Bar)] expands to #[derive_Foo] #[derive_Bar]
item.attrs.push(cx.attribute(titem.span, cx.meta_word(titem.span,
intern_and_get_ident(&format!("derive_{}", tname)))));
}
item
})
}, |a| {
cx.span_err(span, "`derive` can only be applied to items");
a
})
}
macro_rules! derive_traits {
($( $name:expr => $func:path, )+) => {
pub fn register_all(env: &mut SyntaxEnv) {
// Define the #[derive_*] extensions.
$({
struct DeriveExtension;
impl MultiItemDecorator for DeriveExtension {
fn expand(&self,
ecx: &mut ExtCtxt,
sp: Span,
mitem: &MetaItem,
annotatable: &Annotatable,
push: &mut FnMut(Annotatable)) {
warn_if_deprecated(ecx, sp, $name);
$func(ecx, sp, mitem, annotatable, push);
}
}
env.insert(intern(concat!("derive_", $name)),
MultiDecorator(Box::new(DeriveExtension)));
})+
env.insert(intern("derive"),
MultiModifier(Box::new(expand_derive)));
}
fn is_builtin_trait(name: &str) -> bool {
match name {
$( $name )|+ => true,
_ => false,
}
}
}
}
derive_traits! {
"Clone" => clone::expand_deriving_clone,
"Hash" => hash::expand_deriving_hash,
"RustcEncodable" => encodable::expand_deriving_rustc_encodable,
"RustcDecodable" => decodable::expand_deriving_rustc_decodable,
"PartialEq" => partial_eq::expand_deriving_partial_eq,
"Eq" => eq::expand_deriving_eq,
"PartialOrd" => partial_ord::expand_deriving_partial_ord,
"Ord" => ord::expand_deriving_ord,
"Debug" => show::expand_deriving_show,
"Default" => default::expand_deriving_default,
"FromPrimitive" => primitive::expand_deriving_from_primitive,
"Send" => bounds::expand_deriving_unsafe_bound,
"Sync" => bounds::expand_deriving_unsafe_bound,
"Copy" => bounds::expand_deriving_copy,
// deprecated
"Show" => show::expand_deriving_show,
"Encodable" => encodable::expand_deriving_encodable,
"Decodable" => decodable::expand_deriving_decodable,
}
#[inline] // because `name` is a compile-time constant
fn warn_if_deprecated(ecx: &mut ExtCtxt, sp: Span, name: &str) {
if let Some(replacement) = match name {
"Show" => Some("Debug"),
"Encodable" => Some("RustcEncodable"),
"Decodable" => Some("RustcDecodable"),
_ => None,
} {
ecx.span_warn(sp, &format!("derive({}) is deprecated in favor of derive({})",
name, replacement));
}
}
|
// except according to those terms.
|
random_line_split
|
lib.rs
|
// Copyright 2016 Nathan Sizemore <[email protected]>
//
// 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/.
//! Fast and lightweight Slab Allocator.
extern crate libc;
use std::iter::{IntoIterator, Iterator};
use std::ops::{Drop, Index};
use std::{mem, ptr};
pub struct Slab<T> {
capacity: usize,
len: usize,
mem: *mut T,
}
pub struct SlabIter<'a, T: 'a> {
slab: &'a Slab<T>,
current_offset: usize,
}
pub struct SlabMutIter<'a, T: 'a> {
iter: SlabIter<'a, T>,
}
impl<T> Slab<T> {
/// Creates a new Slab
pub fn new() -> Slab<T> {
Slab::with_capacity(1)
}
/// Creates a new, empty Slab with room for `capacity` elems
///
/// # Panics
///
/// * If the host system is out of memory
pub fn with_capacity(capacity: usize) -> Slab<T> {
let maybe_ptr =
unsafe { libc::malloc(mem::size_of::<T>() * capacity) as *mut T };
// malloc will return NULL if called with zero
if maybe_ptr.is_null() && capacity!= 0 {
panic!("Unable to allocate requested capacity")
}
return Slab {
capacity: capacity,
len: 0,
mem: maybe_ptr,
};
}
/// Inserts a new element into the slab, re-allocating if neccessary.
///
/// # Panics
///
/// * If the host system is out of memory.
#[inline]
pub fn insert(&mut self, elem: T) {
if self.len == self.capacity {
self.reallocate();
}
unsafe {
let ptr = self.mem.offset(self.len as isize);
ptr::write(ptr, elem);
}
self.len += 1;
}
/// Removes the element at `offset`.
///
/// # Panics
///
/// * If `offset` is out of bounds.
#[inline]
pub fn remove(&mut self, offset: usize) -> T {
assert!(offset < self.len, "Offset out of bounds");
let elem: T;
let last_elem: T;
let elem_ptr: *mut T;
let last_elem_ptr: *mut T;
unsafe {
elem_ptr = self.mem.offset(offset as isize);
last_elem_ptr = self.mem.offset((self.len - 1) as isize);
elem = ptr::read(elem_ptr);
last_elem = ptr::read(last_elem_ptr);
ptr::write(elem_ptr, last_elem);
}
self.len -= 1;
return elem;
}
/// Returns the number of elements in the slab
#[inline]
pub fn len(&self) -> usize {
self.len
}
/// Returns an iterator over the slab
#[inline]
pub fn iter(&self) -> SlabIter<T> {
SlabIter {
slab: self,
current_offset: 0,
}
}
/// Returns a mutable iterator over the slab
#[inline]
pub fn iter_mut(&mut self) -> SlabMutIter<T> {
SlabMutIter { iter: self.iter() }
}
/// Reserves capacity * 2 extra space in this slab
///
/// # Panics
///
/// Panics if the host system is out of memory
#[inline]
fn reallocate(&mut self) {
let new_capacity = if self.capacity!= 0 {
self.capacity * 2
} else {
1
};
let maybe_ptr = unsafe {
libc::realloc(
self.mem as *mut libc::c_void,
mem::size_of::<T>() * new_capacity,
) as *mut T
};
assert!(!maybe_ptr.is_null(), "Out of Memory");
self.capacity = new_capacity;
self.mem = maybe_ptr;
}
}
impl<T> Drop for Slab<T> {
fn drop(&mut self) {
|
unsafe {
let elem_ptr = self.mem.offset(x as isize);
ptr::drop_in_place(elem_ptr);
}
}
unsafe { libc::free(self.mem as *mut _ as *mut libc::c_void) };
}
}
impl<T> Index<usize> for Slab<T> {
type Output = T;
fn index(&self, index: usize) -> &Self::Output {
assert!(index < self.len, "Index out of bounds");
unsafe { &(*(self.mem.offset(index as isize))) }
}
}
impl<'a, T> Iterator for SlabIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
while self.current_offset < self.slab.len() {
let offset = self.current_offset;
self.current_offset += 1;
unsafe {
return Some(&(*self.slab.mem.offset(offset as isize)));
}
}
None
}
}
impl<'a, T> Iterator for SlabMutIter<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<&'a mut T> {
unsafe { mem::transmute(self.iter.next()) }
}
}
impl<'a, T> IntoIterator for &'a Slab<T> {
type Item = &'a T;
type IntoIter = SlabIter<'a, T>;
fn into_iter(self) -> SlabIter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut Slab<T> {
type Item = &'a mut T;
type IntoIter = SlabMutIter<'a, T>;
fn into_iter(self) -> SlabMutIter<'a, T> {
self.iter_mut()
}
}
|
for x in 0..self.len() {
|
random_line_split
|
lib.rs
|
// Copyright 2016 Nathan Sizemore <[email protected]>
//
// 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/.
//! Fast and lightweight Slab Allocator.
extern crate libc;
use std::iter::{IntoIterator, Iterator};
use std::ops::{Drop, Index};
use std::{mem, ptr};
pub struct Slab<T> {
capacity: usize,
len: usize,
mem: *mut T,
}
pub struct SlabIter<'a, T: 'a> {
slab: &'a Slab<T>,
current_offset: usize,
}
pub struct SlabMutIter<'a, T: 'a> {
iter: SlabIter<'a, T>,
}
impl<T> Slab<T> {
/// Creates a new Slab
pub fn new() -> Slab<T> {
Slab::with_capacity(1)
}
/// Creates a new, empty Slab with room for `capacity` elems
///
/// # Panics
///
/// * If the host system is out of memory
pub fn with_capacity(capacity: usize) -> Slab<T> {
let maybe_ptr =
unsafe { libc::malloc(mem::size_of::<T>() * capacity) as *mut T };
// malloc will return NULL if called with zero
if maybe_ptr.is_null() && capacity!= 0 {
panic!("Unable to allocate requested capacity")
}
return Slab {
capacity: capacity,
len: 0,
mem: maybe_ptr,
};
}
/// Inserts a new element into the slab, re-allocating if neccessary.
///
/// # Panics
///
/// * If the host system is out of memory.
#[inline]
pub fn insert(&mut self, elem: T)
|
/// Removes the element at `offset`.
///
/// # Panics
///
/// * If `offset` is out of bounds.
#[inline]
pub fn remove(&mut self, offset: usize) -> T {
assert!(offset < self.len, "Offset out of bounds");
let elem: T;
let last_elem: T;
let elem_ptr: *mut T;
let last_elem_ptr: *mut T;
unsafe {
elem_ptr = self.mem.offset(offset as isize);
last_elem_ptr = self.mem.offset((self.len - 1) as isize);
elem = ptr::read(elem_ptr);
last_elem = ptr::read(last_elem_ptr);
ptr::write(elem_ptr, last_elem);
}
self.len -= 1;
return elem;
}
/// Returns the number of elements in the slab
#[inline]
pub fn len(&self) -> usize {
self.len
}
/// Returns an iterator over the slab
#[inline]
pub fn iter(&self) -> SlabIter<T> {
SlabIter {
slab: self,
current_offset: 0,
}
}
/// Returns a mutable iterator over the slab
#[inline]
pub fn iter_mut(&mut self) -> SlabMutIter<T> {
SlabMutIter { iter: self.iter() }
}
/// Reserves capacity * 2 extra space in this slab
///
/// # Panics
///
/// Panics if the host system is out of memory
#[inline]
fn reallocate(&mut self) {
let new_capacity = if self.capacity!= 0 {
self.capacity * 2
} else {
1
};
let maybe_ptr = unsafe {
libc::realloc(
self.mem as *mut libc::c_void,
mem::size_of::<T>() * new_capacity,
) as *mut T
};
assert!(!maybe_ptr.is_null(), "Out of Memory");
self.capacity = new_capacity;
self.mem = maybe_ptr;
}
}
impl<T> Drop for Slab<T> {
fn drop(&mut self) {
for x in 0..self.len() {
unsafe {
let elem_ptr = self.mem.offset(x as isize);
ptr::drop_in_place(elem_ptr);
}
}
unsafe { libc::free(self.mem as *mut _ as *mut libc::c_void) };
}
}
impl<T> Index<usize> for Slab<T> {
type Output = T;
fn index(&self, index: usize) -> &Self::Output {
assert!(index < self.len, "Index out of bounds");
unsafe { &(*(self.mem.offset(index as isize))) }
}
}
impl<'a, T> Iterator for SlabIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
while self.current_offset < self.slab.len() {
let offset = self.current_offset;
self.current_offset += 1;
unsafe {
return Some(&(*self.slab.mem.offset(offset as isize)));
}
}
None
}
}
impl<'a, T> Iterator for SlabMutIter<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<&'a mut T> {
unsafe { mem::transmute(self.iter.next()) }
}
}
impl<'a, T> IntoIterator for &'a Slab<T> {
type Item = &'a T;
type IntoIter = SlabIter<'a, T>;
fn into_iter(self) -> SlabIter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut Slab<T> {
type Item = &'a mut T;
type IntoIter = SlabMutIter<'a, T>;
fn into_iter(self) -> SlabMutIter<'a, T> {
self.iter_mut()
}
}
|
{
if self.len == self.capacity {
self.reallocate();
}
unsafe {
let ptr = self.mem.offset(self.len as isize);
ptr::write(ptr, elem);
}
self.len += 1;
}
|
identifier_body
|
lib.rs
|
// Copyright 2016 Nathan Sizemore <[email protected]>
//
// 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/.
//! Fast and lightweight Slab Allocator.
extern crate libc;
use std::iter::{IntoIterator, Iterator};
use std::ops::{Drop, Index};
use std::{mem, ptr};
pub struct Slab<T> {
capacity: usize,
len: usize,
mem: *mut T,
}
pub struct SlabIter<'a, T: 'a> {
slab: &'a Slab<T>,
current_offset: usize,
}
pub struct SlabMutIter<'a, T: 'a> {
iter: SlabIter<'a, T>,
}
impl<T> Slab<T> {
/// Creates a new Slab
pub fn new() -> Slab<T> {
Slab::with_capacity(1)
}
/// Creates a new, empty Slab with room for `capacity` elems
///
/// # Panics
///
/// * If the host system is out of memory
pub fn with_capacity(capacity: usize) -> Slab<T> {
let maybe_ptr =
unsafe { libc::malloc(mem::size_of::<T>() * capacity) as *mut T };
// malloc will return NULL if called with zero
if maybe_ptr.is_null() && capacity!= 0 {
panic!("Unable to allocate requested capacity")
}
return Slab {
capacity: capacity,
len: 0,
mem: maybe_ptr,
};
}
/// Inserts a new element into the slab, re-allocating if neccessary.
///
/// # Panics
///
/// * If the host system is out of memory.
#[inline]
pub fn insert(&mut self, elem: T) {
if self.len == self.capacity {
self.reallocate();
}
unsafe {
let ptr = self.mem.offset(self.len as isize);
ptr::write(ptr, elem);
}
self.len += 1;
}
/// Removes the element at `offset`.
///
/// # Panics
///
/// * If `offset` is out of bounds.
#[inline]
pub fn remove(&mut self, offset: usize) -> T {
assert!(offset < self.len, "Offset out of bounds");
let elem: T;
let last_elem: T;
let elem_ptr: *mut T;
let last_elem_ptr: *mut T;
unsafe {
elem_ptr = self.mem.offset(offset as isize);
last_elem_ptr = self.mem.offset((self.len - 1) as isize);
elem = ptr::read(elem_ptr);
last_elem = ptr::read(last_elem_ptr);
ptr::write(elem_ptr, last_elem);
}
self.len -= 1;
return elem;
}
/// Returns the number of elements in the slab
#[inline]
pub fn len(&self) -> usize {
self.len
}
/// Returns an iterator over the slab
#[inline]
pub fn iter(&self) -> SlabIter<T> {
SlabIter {
slab: self,
current_offset: 0,
}
}
/// Returns a mutable iterator over the slab
#[inline]
pub fn iter_mut(&mut self) -> SlabMutIter<T> {
SlabMutIter { iter: self.iter() }
}
/// Reserves capacity * 2 extra space in this slab
///
/// # Panics
///
/// Panics if the host system is out of memory
#[inline]
fn reallocate(&mut self) {
let new_capacity = if self.capacity!= 0 {
self.capacity * 2
} else {
1
};
let maybe_ptr = unsafe {
libc::realloc(
self.mem as *mut libc::c_void,
mem::size_of::<T>() * new_capacity,
) as *mut T
};
assert!(!maybe_ptr.is_null(), "Out of Memory");
self.capacity = new_capacity;
self.mem = maybe_ptr;
}
}
impl<T> Drop for Slab<T> {
fn drop(&mut self) {
for x in 0..self.len() {
unsafe {
let elem_ptr = self.mem.offset(x as isize);
ptr::drop_in_place(elem_ptr);
}
}
unsafe { libc::free(self.mem as *mut _ as *mut libc::c_void) };
}
}
impl<T> Index<usize> for Slab<T> {
type Output = T;
fn
|
(&self, index: usize) -> &Self::Output {
assert!(index < self.len, "Index out of bounds");
unsafe { &(*(self.mem.offset(index as isize))) }
}
}
impl<'a, T> Iterator for SlabIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
while self.current_offset < self.slab.len() {
let offset = self.current_offset;
self.current_offset += 1;
unsafe {
return Some(&(*self.slab.mem.offset(offset as isize)));
}
}
None
}
}
impl<'a, T> Iterator for SlabMutIter<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<&'a mut T> {
unsafe { mem::transmute(self.iter.next()) }
}
}
impl<'a, T> IntoIterator for &'a Slab<T> {
type Item = &'a T;
type IntoIter = SlabIter<'a, T>;
fn into_iter(self) -> SlabIter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut Slab<T> {
type Item = &'a mut T;
type IntoIter = SlabMutIter<'a, T>;
fn into_iter(self) -> SlabMutIter<'a, T> {
self.iter_mut()
}
}
|
index
|
identifier_name
|
lib.rs
|
// Copyright 2016 Nathan Sizemore <[email protected]>
//
// 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/.
//! Fast and lightweight Slab Allocator.
extern crate libc;
use std::iter::{IntoIterator, Iterator};
use std::ops::{Drop, Index};
use std::{mem, ptr};
pub struct Slab<T> {
capacity: usize,
len: usize,
mem: *mut T,
}
pub struct SlabIter<'a, T: 'a> {
slab: &'a Slab<T>,
current_offset: usize,
}
pub struct SlabMutIter<'a, T: 'a> {
iter: SlabIter<'a, T>,
}
impl<T> Slab<T> {
/// Creates a new Slab
pub fn new() -> Slab<T> {
Slab::with_capacity(1)
}
/// Creates a new, empty Slab with room for `capacity` elems
///
/// # Panics
///
/// * If the host system is out of memory
pub fn with_capacity(capacity: usize) -> Slab<T> {
let maybe_ptr =
unsafe { libc::malloc(mem::size_of::<T>() * capacity) as *mut T };
// malloc will return NULL if called with zero
if maybe_ptr.is_null() && capacity!= 0 {
panic!("Unable to allocate requested capacity")
}
return Slab {
capacity: capacity,
len: 0,
mem: maybe_ptr,
};
}
/// Inserts a new element into the slab, re-allocating if neccessary.
///
/// # Panics
///
/// * If the host system is out of memory.
#[inline]
pub fn insert(&mut self, elem: T) {
if self.len == self.capacity
|
unsafe {
let ptr = self.mem.offset(self.len as isize);
ptr::write(ptr, elem);
}
self.len += 1;
}
/// Removes the element at `offset`.
///
/// # Panics
///
/// * If `offset` is out of bounds.
#[inline]
pub fn remove(&mut self, offset: usize) -> T {
assert!(offset < self.len, "Offset out of bounds");
let elem: T;
let last_elem: T;
let elem_ptr: *mut T;
let last_elem_ptr: *mut T;
unsafe {
elem_ptr = self.mem.offset(offset as isize);
last_elem_ptr = self.mem.offset((self.len - 1) as isize);
elem = ptr::read(elem_ptr);
last_elem = ptr::read(last_elem_ptr);
ptr::write(elem_ptr, last_elem);
}
self.len -= 1;
return elem;
}
/// Returns the number of elements in the slab
#[inline]
pub fn len(&self) -> usize {
self.len
}
/// Returns an iterator over the slab
#[inline]
pub fn iter(&self) -> SlabIter<T> {
SlabIter {
slab: self,
current_offset: 0,
}
}
/// Returns a mutable iterator over the slab
#[inline]
pub fn iter_mut(&mut self) -> SlabMutIter<T> {
SlabMutIter { iter: self.iter() }
}
/// Reserves capacity * 2 extra space in this slab
///
/// # Panics
///
/// Panics if the host system is out of memory
#[inline]
fn reallocate(&mut self) {
let new_capacity = if self.capacity!= 0 {
self.capacity * 2
} else {
1
};
let maybe_ptr = unsafe {
libc::realloc(
self.mem as *mut libc::c_void,
mem::size_of::<T>() * new_capacity,
) as *mut T
};
assert!(!maybe_ptr.is_null(), "Out of Memory");
self.capacity = new_capacity;
self.mem = maybe_ptr;
}
}
impl<T> Drop for Slab<T> {
fn drop(&mut self) {
for x in 0..self.len() {
unsafe {
let elem_ptr = self.mem.offset(x as isize);
ptr::drop_in_place(elem_ptr);
}
}
unsafe { libc::free(self.mem as *mut _ as *mut libc::c_void) };
}
}
impl<T> Index<usize> for Slab<T> {
type Output = T;
fn index(&self, index: usize) -> &Self::Output {
assert!(index < self.len, "Index out of bounds");
unsafe { &(*(self.mem.offset(index as isize))) }
}
}
impl<'a, T> Iterator for SlabIter<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
while self.current_offset < self.slab.len() {
let offset = self.current_offset;
self.current_offset += 1;
unsafe {
return Some(&(*self.slab.mem.offset(offset as isize)));
}
}
None
}
}
impl<'a, T> Iterator for SlabMutIter<'a, T> {
type Item = &'a mut T;
fn next(&mut self) -> Option<&'a mut T> {
unsafe { mem::transmute(self.iter.next()) }
}
}
impl<'a, T> IntoIterator for &'a Slab<T> {
type Item = &'a T;
type IntoIter = SlabIter<'a, T>;
fn into_iter(self) -> SlabIter<'a, T> {
self.iter()
}
}
impl<'a, T> IntoIterator for &'a mut Slab<T> {
type Item = &'a mut T;
type IntoIter = SlabMutIter<'a, T>;
fn into_iter(self) -> SlabMutIter<'a, T> {
self.iter_mut()
}
}
|
{
self.reallocate();
}
|
conditional_block
|
trait-inheritance-auto.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.
// Testing that this impl turns A into a Quux, because
// A is already a Foo Bar Baz
impl<T:Foo + Bar + Baz> Quux for T { }
trait Foo { fn f(&self) -> int; }
trait Bar { fn g(&self) -> int; }
trait Baz { fn h(&self) -> int; }
trait Quux: Foo + Bar + Baz { }
struct A { x: int }
impl Foo for A { fn f(&self) -> int { 10 } }
impl Bar for A { fn g(&self) -> int { 20 } }
impl Baz for A { fn h(&self) -> int
|
}
fn f<T:Quux>(a: &T) {
assert!(a.f() == 10);
assert!(a.g() == 20);
assert!(a.h() == 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
|
{ 30 }
|
identifier_body
|
trait-inheritance-auto.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.
// Testing that this impl turns A into a Quux, because
// A is already a Foo Bar Baz
impl<T:Foo + Bar + Baz> Quux for T { }
trait Foo { fn f(&self) -> int; }
trait Bar { fn g(&self) -> int; }
trait Baz { fn h(&self) -> int; }
trait Quux: Foo + Bar + Baz { }
struct A { x: int }
impl Foo for A { fn f(&self) -> int { 10 } }
|
assert!(a.f() == 10);
assert!(a.g() == 20);
assert!(a.h() == 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
|
impl Bar for A { fn g(&self) -> int { 20 } }
impl Baz for A { fn h(&self) -> int { 30 } }
fn f<T:Quux>(a: &T) {
|
random_line_split
|
trait-inheritance-auto.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.
// Testing that this impl turns A into a Quux, because
// A is already a Foo Bar Baz
impl<T:Foo + Bar + Baz> Quux for T { }
trait Foo { fn f(&self) -> int; }
trait Bar { fn g(&self) -> int; }
trait Baz { fn h(&self) -> int; }
trait Quux: Foo + Bar + Baz { }
struct A { x: int }
impl Foo for A { fn f(&self) -> int { 10 } }
impl Bar for A { fn g(&self) -> int { 20 } }
impl Baz for A { fn
|
(&self) -> int { 30 } }
fn f<T:Quux>(a: &T) {
assert!(a.f() == 10);
assert!(a.g() == 20);
assert!(a.h() == 30);
}
pub fn main() {
let a = &A { x: 3 };
f(a);
}
|
h
|
identifier_name
|
app_blink_stm32f4.rs
|
#![feature(phase)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[no_mangle]
#[no_split_stack]
#[allow(unused_variable)]
#[allow(dead_code)]
|
zinc::hal::mem_init::init_data();
let led1 = pin::PinConf{
port: pin::PortG,
pin: 13u8,
function: pin::GPIOOut
};
let led2 = pin::PinConf{
port: pin::PortG,
pin: 14u8,
function: pin::GPIOOut
};
led1.setup();
led2.setup();
let timer = timer::Timer::new(timer::Timer2, 25u32);
loop {
led1.set_high();
led2.set_low();
timer.wait_ms(300);
led1.set_low();
led2.set_high();
timer.wait_ms(300);
}
}
|
pub unsafe fn main() {
use zinc::hal::timer::Timer;
use zinc::hal::stm32f4::{pin, timer};
zinc::hal::mem_init::init_stack();
|
random_line_split
|
app_blink_stm32f4.rs
|
#![feature(phase)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[no_mangle]
#[no_split_stack]
#[allow(unused_variable)]
#[allow(dead_code)]
pub unsafe fn
|
() {
use zinc::hal::timer::Timer;
use zinc::hal::stm32f4::{pin, timer};
zinc::hal::mem_init::init_stack();
zinc::hal::mem_init::init_data();
let led1 = pin::PinConf{
port: pin::PortG,
pin: 13u8,
function: pin::GPIOOut
};
let led2 = pin::PinConf{
port: pin::PortG,
pin: 14u8,
function: pin::GPIOOut
};
led1.setup();
led2.setup();
let timer = timer::Timer::new(timer::Timer2, 25u32);
loop {
led1.set_high();
led2.set_low();
timer.wait_ms(300);
led1.set_low();
led2.set_high();
timer.wait_ms(300);
}
}
|
main
|
identifier_name
|
app_blink_stm32f4.rs
|
#![feature(phase)]
#![crate_type="staticlib"]
#![no_std]
extern crate core;
extern crate zinc;
#[no_mangle]
#[no_split_stack]
#[allow(unused_variable)]
#[allow(dead_code)]
pub unsafe fn main()
|
loop {
led1.set_high();
led2.set_low();
timer.wait_ms(300);
led1.set_low();
led2.set_high();
timer.wait_ms(300);
}
}
|
{
use zinc::hal::timer::Timer;
use zinc::hal::stm32f4::{pin, timer};
zinc::hal::mem_init::init_stack();
zinc::hal::mem_init::init_data();
let led1 = pin::PinConf{
port: pin::PortG,
pin: 13u8,
function: pin::GPIOOut
};
let led2 = pin::PinConf{
port: pin::PortG,
pin: 14u8,
function: pin::GPIOOut
};
led1.setup();
led2.setup();
let timer = timer::Timer::new(timer::Timer2, 25u32);
|
identifier_body
|
adsr.rs
|
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Attack, decay, sustain, release.
use module::{Module, Buffer};
pub struct Adsr {
value: f32,
state: State,
}
enum State {
Quiet,
Attack, // note is on, rising
Decay, // note is on, falling
Sustain, // note is on, steady
Release, // note is off, falling
}
use self::State::*;
impl Adsr {
|
Adsr {
value: -24.0,
state: Quiet,
}
}
}
impl Module for Adsr {
fn n_ctrl_out(&self) -> usize { 1 }
fn handle_note(&mut self, _midi_num: f32, _velocity: f32, on: bool) {
if on {
self.state = Attack;
} else {
self.state = Release;
}
}
fn process(&mut self, control_in: &[f32], control_out: &mut [f32],
_buf_in: &[&Buffer], _buf_out: &mut [Buffer])
{
match self.state {
Quiet => (),
Attack => {
let mut l = self.value.exp2();
l += (-control_in[0]).exp2();
if l >= 1.0 {
l = 1.0;
self.state = Decay;
}
self.value = l.log2();
}
Decay => {
let sustain = control_in[2] - 6.0;
self.value -= (-control_in[1]).exp2();
if self.value < sustain {
self.value = sustain;
self.state = Sustain;
}
}
Sustain => {
let sustain = control_in[2] - 6.0;
self.value = sustain;
}
Release => {
self.value -= (-control_in[3]).exp2();
if self.value < -24.0 {
self.value = -24.0;
self.state = Quiet;
}
}
}
control_out[0] = self.value;
}
}
|
pub fn new() -> Adsr {
|
random_line_split
|
adsr.rs
|
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Attack, decay, sustain, release.
use module::{Module, Buffer};
pub struct Adsr {
value: f32,
state: State,
}
enum State {
Quiet,
Attack, // note is on, rising
Decay, // note is on, falling
Sustain, // note is on, steady
Release, // note is off, falling
}
use self::State::*;
impl Adsr {
pub fn
|
() -> Adsr {
Adsr {
value: -24.0,
state: Quiet,
}
}
}
impl Module for Adsr {
fn n_ctrl_out(&self) -> usize { 1 }
fn handle_note(&mut self, _midi_num: f32, _velocity: f32, on: bool) {
if on {
self.state = Attack;
} else {
self.state = Release;
}
}
fn process(&mut self, control_in: &[f32], control_out: &mut [f32],
_buf_in: &[&Buffer], _buf_out: &mut [Buffer])
{
match self.state {
Quiet => (),
Attack => {
let mut l = self.value.exp2();
l += (-control_in[0]).exp2();
if l >= 1.0 {
l = 1.0;
self.state = Decay;
}
self.value = l.log2();
}
Decay => {
let sustain = control_in[2] - 6.0;
self.value -= (-control_in[1]).exp2();
if self.value < sustain {
self.value = sustain;
self.state = Sustain;
}
}
Sustain => {
let sustain = control_in[2] - 6.0;
self.value = sustain;
}
Release => {
self.value -= (-control_in[3]).exp2();
if self.value < -24.0 {
self.value = -24.0;
self.state = Quiet;
}
}
}
control_out[0] = self.value;
}
}
|
new
|
identifier_name
|
console.rs
|
use super::super::backend::Backend;
use super::super::buckets::Buckets;
use time;
#[derive(Debug)]
pub struct Console;
impl Console {
/// Create a Console formatter that prints to stdout
///
/// # Examples
///
/// ```
/// let cons = Console::new();
/// ```
pub fn new() -> Console {
Console
}
}
/// Print a single stats line.
fn fmt_line(key: &str, value: &f64) {
println!(" {}: {}", key, value)
}
impl Backend for Console {
fn flush_buckets(&mut self, buckets: &Buckets)
|
}
println!(" timer_data:");
for (key, values) in buckets.timer_data().iter() {
println!(" {}: {:?}", key, values);
}
}
}
|
{
let now = time::get_time();
println!("Flushing metrics: {}", time::at(now).rfc822().to_string());
println!(" bad_messages: {}", buckets.bad_messages());
println!(" total_messages: {}", buckets.total_messages());
println!(" counters:");
for (key, value) in buckets.counters().iter() {
fmt_line(&key, &value);
}
println!(" gauges:");
for (key, value) in buckets.gauges().iter() {
fmt_line(&key, &value);
}
println!(" timers:");
for (key, values) in buckets.timers().iter() {
println!(" {}: {:?}", key, values);
|
identifier_body
|
console.rs
|
use super::super::backend::Backend;
use super::super::buckets::Buckets;
use time;
#[derive(Debug)]
pub struct Console;
|
impl Console {
/// Create a Console formatter that prints to stdout
///
/// # Examples
///
/// ```
/// let cons = Console::new();
/// ```
pub fn new() -> Console {
Console
}
}
/// Print a single stats line.
fn fmt_line(key: &str, value: &f64) {
println!(" {}: {}", key, value)
}
impl Backend for Console {
fn flush_buckets(&mut self, buckets: &Buckets) {
let now = time::get_time();
println!("Flushing metrics: {}", time::at(now).rfc822().to_string());
println!(" bad_messages: {}", buckets.bad_messages());
println!(" total_messages: {}", buckets.total_messages());
println!(" counters:");
for (key, value) in buckets.counters().iter() {
fmt_line(&key, &value);
}
println!(" gauges:");
for (key, value) in buckets.gauges().iter() {
fmt_line(&key, &value);
}
println!(" timers:");
for (key, values) in buckets.timers().iter() {
println!(" {}: {:?}", key, values);
}
println!(" timer_data:");
for (key, values) in buckets.timer_data().iter() {
println!(" {}: {:?}", key, values);
}
}
}
|
random_line_split
|
|
console.rs
|
use super::super::backend::Backend;
use super::super::buckets::Buckets;
use time;
#[derive(Debug)]
pub struct Console;
impl Console {
/// Create a Console formatter that prints to stdout
///
/// # Examples
///
/// ```
/// let cons = Console::new();
/// ```
pub fn
|
() -> Console {
Console
}
}
/// Print a single stats line.
fn fmt_line(key: &str, value: &f64) {
println!(" {}: {}", key, value)
}
impl Backend for Console {
fn flush_buckets(&mut self, buckets: &Buckets) {
let now = time::get_time();
println!("Flushing metrics: {}", time::at(now).rfc822().to_string());
println!(" bad_messages: {}", buckets.bad_messages());
println!(" total_messages: {}", buckets.total_messages());
println!(" counters:");
for (key, value) in buckets.counters().iter() {
fmt_line(&key, &value);
}
println!(" gauges:");
for (key, value) in buckets.gauges().iter() {
fmt_line(&key, &value);
}
println!(" timers:");
for (key, values) in buckets.timers().iter() {
println!(" {}: {:?}", key, values);
}
println!(" timer_data:");
for (key, values) in buckets.timer_data().iter() {
println!(" {}: {:?}", key, values);
}
}
}
|
new
|
identifier_name
|
messageevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEventBinding;
use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods;
use dom::bindings::codegen::InheritTypes::{EventCast, MessageEventDerived};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::utils::reflect_dom_object;
use dom::event::{Event, EventTypeId};
use dom::eventtarget::EventTarget;
use js::jsapi::{JSContext, Heap, HandleValue};
use js::jsval::JSVal;
use std::borrow::ToOwned;
use std::default::Default;
use util::str::DOMString;
#[dom_struct]
pub struct MessageEvent {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEventDerived for Event {
fn is_messageevent(&self) -> bool {
*self.type_id() == EventTypeId::MessageEvent
}
}
impl MessageEvent {
pub fn new_uninitialized(global: GlobalRef) -> Root<MessageEvent> {
MessageEvent::new_initialized(global, HandleValue::undefined(), "".to_owned(), "".to_owned())
}
pub fn new_initialized(global: GlobalRef,
data: HandleValue,
origin: DOMString,
lastEventId: DOMString) -> Root<MessageEvent> {
let mut ev = box MessageEvent {
event: Event::new_inherited(EventTypeId::MessageEvent),
data: Heap::default(),
origin: origin,
lastEventId: lastEventId,
};
ev.data.set(data.get());
reflect_dom_object(ev, global, MessageEventBinding::Wrap)
}
pub fn new(global: GlobalRef, type_: DOMString,
bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId);
{
let event = EventCast::from_ref(ev.r());
event.InitEvent(type_, bubbles, cancelable);
}
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &MessageEventBinding::MessageEventInit)
-> Fallible<Root<MessageEvent>> {
let ev = MessageEvent::new(global, type_, init.parent.bubbles, init.parent.cancelable,
HandleValue { ptr: &init.data },
init.origin.clone(), init.lastEventId.clone());
Ok(ev)
}
}
impl MessageEvent {
pub fn dispatch_jsval(target: &EventTarget,
scope: GlobalRef,
message: HandleValue) {
let messageevent = MessageEvent::new(
scope, "message".to_owned(), false, false, message,
"".to_owned(), "".to_owned());
let event = EventCast::from_ref(messageevent.r());
event.fire(target);
}
}
impl MessageEventMethods for MessageEvent {
// https://html.spec.whatwg.org/multipage/#dom-messageevent-data
fn
|
(&self, _cx: *mut JSContext) -> JSVal {
self.data.get()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DOMString {
self.lastEventId.clone()
}
}
|
Data
|
identifier_name
|
messageevent.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::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::MessageEventBinding;
use dom::bindings::codegen::Bindings::MessageEventBinding::MessageEventMethods;
use dom::bindings::codegen::InheritTypes::{EventCast, MessageEventDerived};
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root;
use dom::bindings::utils::reflect_dom_object;
use dom::event::{Event, EventTypeId};
use dom::eventtarget::EventTarget;
use js::jsapi::{JSContext, Heap, HandleValue};
use js::jsval::JSVal;
use std::borrow::ToOwned;
use std::default::Default;
use util::str::DOMString;
#[dom_struct]
pub struct MessageEvent {
event: Event,
data: Heap<JSVal>,
origin: DOMString,
lastEventId: DOMString,
}
impl MessageEventDerived for Event {
fn is_messageevent(&self) -> bool {
*self.type_id() == EventTypeId::MessageEvent
}
}
impl MessageEvent {
pub fn new_uninitialized(global: GlobalRef) -> Root<MessageEvent> {
MessageEvent::new_initialized(global, HandleValue::undefined(), "".to_owned(), "".to_owned())
}
pub fn new_initialized(global: GlobalRef,
data: HandleValue,
origin: DOMString,
lastEventId: DOMString) -> Root<MessageEvent> {
let mut ev = box MessageEvent {
event: Event::new_inherited(EventTypeId::MessageEvent),
data: Heap::default(),
origin: origin,
lastEventId: lastEventId,
};
ev.data.set(data.get());
reflect_dom_object(ev, global, MessageEventBinding::Wrap)
}
pub fn new(global: GlobalRef, type_: DOMString,
bubbles: bool, cancelable: bool,
data: HandleValue, origin: DOMString, lastEventId: DOMString)
-> Root<MessageEvent> {
let ev = MessageEvent::new_initialized(global, data, origin, lastEventId);
{
let event = EventCast::from_ref(ev.r());
event.InitEvent(type_, bubbles, cancelable);
}
ev
}
pub fn Constructor(global: GlobalRef,
type_: DOMString,
init: &MessageEventBinding::MessageEventInit)
-> Fallible<Root<MessageEvent>> {
let ev = MessageEvent::new(global, type_, init.parent.bubbles, init.parent.cancelable,
HandleValue { ptr: &init.data },
init.origin.clone(), init.lastEventId.clone());
Ok(ev)
}
}
impl MessageEvent {
pub fn dispatch_jsval(target: &EventTarget,
scope: GlobalRef,
message: HandleValue) {
let messageevent = MessageEvent::new(
scope, "message".to_owned(), false, false, message,
"".to_owned(), "".to_owned());
let event = EventCast::from_ref(messageevent.r());
event.fire(target);
}
}
impl MessageEventMethods for MessageEvent {
// https://html.spec.whatwg.org/multipage/#dom-messageevent-data
fn Data(&self, _cx: *mut JSContext) -> JSVal {
self.data.get()
|
// https://html.spec.whatwg.org/multipage/#dom-messageevent-origin
fn Origin(&self) -> DOMString {
self.origin.clone()
}
// https://html.spec.whatwg.org/multipage/#dom-messageevent-lasteventid
fn LastEventId(&self) -> DOMString {
self.lastEventId.clone()
}
}
|
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.