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 |
---|---|---|---|---|
mutated_accounts_tests.rs
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::compiler::{as_module, compile_units};
use move_core_types::{
account_address::AccountAddress,
gas_schedule::{GasAlgebra, GasUnits},
identifier::Identifier,
language_storage::ModuleId,
value::{serialize_values, MoveValue},
};
use move_vm_runtime::{logging::NoContextLog, move_vm::MoveVM};
use move_vm_test_utils::InMemoryStorage;
use move_vm_types::gas_schedule::{zero_cost_schedule, CostStrategy};
const TEST_ADDR: AccountAddress = AccountAddress::new([42; AccountAddress::LENGTH]);
#[test]
fn
|
() {
let code = r#"
module M {
resource struct Foo { a: bool }
public fun get(addr: address): bool acquires Foo {
borrow_global<Foo>(addr).a
}
public fun flip(addr: address) acquires Foo {
let f_ref = borrow_global_mut<Foo>(addr);
f_ref.a =!f_ref.a;
}
public fun publish(addr: &signer) {
move_to(addr, Foo { a: true} )
}
}
"#;
let mut units = compile_units(TEST_ADDR, &code).unwrap();
let m = as_module(units.pop().unwrap());
let mut blob = vec![];
m.serialize(&mut blob).unwrap();
let mut storage = InMemoryStorage::new();
let module_id = ModuleId::new(TEST_ADDR, Identifier::new("M").unwrap());
storage.publish_or_overwrite_module(module_id.clone(), blob);
let vm = MoveVM::new();
let mut sess = vm.new_session(&storage);
let cost_table = zero_cost_schedule();
let mut cost_strategy = CostStrategy::system(&cost_table, GasUnits::new(0));
let context = NoContextLog::new();
let publish = Identifier::new("publish").unwrap();
let flip = Identifier::new("flip").unwrap();
let get = Identifier::new("get").unwrap();
let account1 = AccountAddress::random();
sess.execute_function(
&module_id,
&publish,
vec![],
serialize_values(&vec![MoveValue::Signer(account1)]),
&mut cost_strategy,
&context,
)
.unwrap();
// The resource was published to "account1" and the sender's account
// (TEST_ADDR) is assumed to be mutated as well (e.g., in a subsequent
// transaction epilogue).
assert_eq!(sess.num_mutated_accounts(&TEST_ADDR), 2);
sess.execute_function(
&module_id,
&get,
vec![],
serialize_values(&vec![MoveValue::Address(account1)]),
&mut cost_strategy,
&context,
)
.unwrap();
assert_eq!(sess.num_mutated_accounts(&TEST_ADDR), 2);
sess.execute_function(
&module_id,
&flip,
vec![],
serialize_values(&vec![MoveValue::Address(account1)]),
&mut cost_strategy,
&context,
)
.unwrap();
assert_eq!(sess.num_mutated_accounts(&TEST_ADDR), 2);
let (changes, _) = sess.finish().unwrap();
storage.apply(changes).unwrap();
let mut sess = vm.new_session(&storage);
sess.execute_function(
&module_id,
&get,
vec![],
serialize_values(&vec![MoveValue::Address(account1)]),
&mut cost_strategy,
&context,
)
.unwrap();
// Only the sender's account (TEST_ADDR) should have been modified.
assert_eq!(sess.num_mutated_accounts(&TEST_ADDR), 1);
}
|
mutated_accounts
|
identifier_name
|
mutated_accounts_tests.rs
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::compiler::{as_module, compile_units};
use move_core_types::{
account_address::AccountAddress,
gas_schedule::{GasAlgebra, GasUnits},
identifier::Identifier,
language_storage::ModuleId,
value::{serialize_values, MoveValue},
};
use move_vm_runtime::{logging::NoContextLog, move_vm::MoveVM};
use move_vm_test_utils::InMemoryStorage;
use move_vm_types::gas_schedule::{zero_cost_schedule, CostStrategy};
const TEST_ADDR: AccountAddress = AccountAddress::new([42; AccountAddress::LENGTH]);
#[test]
fn mutated_accounts()
|
m.serialize(&mut blob).unwrap();
let mut storage = InMemoryStorage::new();
let module_id = ModuleId::new(TEST_ADDR, Identifier::new("M").unwrap());
storage.publish_or_overwrite_module(module_id.clone(), blob);
let vm = MoveVM::new();
let mut sess = vm.new_session(&storage);
let cost_table = zero_cost_schedule();
let mut cost_strategy = CostStrategy::system(&cost_table, GasUnits::new(0));
let context = NoContextLog::new();
let publish = Identifier::new("publish").unwrap();
let flip = Identifier::new("flip").unwrap();
let get = Identifier::new("get").unwrap();
let account1 = AccountAddress::random();
sess.execute_function(
&module_id,
&publish,
vec![],
serialize_values(&vec![MoveValue::Signer(account1)]),
&mut cost_strategy,
&context,
)
.unwrap();
// The resource was published to "account1" and the sender's account
// (TEST_ADDR) is assumed to be mutated as well (e.g., in a subsequent
// transaction epilogue).
assert_eq!(sess.num_mutated_accounts(&TEST_ADDR), 2);
sess.execute_function(
&module_id,
&get,
vec![],
serialize_values(&vec![MoveValue::Address(account1)]),
&mut cost_strategy,
&context,
)
.unwrap();
assert_eq!(sess.num_mutated_accounts(&TEST_ADDR), 2);
sess.execute_function(
&module_id,
&flip,
vec![],
serialize_values(&vec![MoveValue::Address(account1)]),
&mut cost_strategy,
&context,
)
.unwrap();
assert_eq!(sess.num_mutated_accounts(&TEST_ADDR), 2);
let (changes, _) = sess.finish().unwrap();
storage.apply(changes).unwrap();
let mut sess = vm.new_session(&storage);
sess.execute_function(
&module_id,
&get,
vec![],
serialize_values(&vec![MoveValue::Address(account1)]),
&mut cost_strategy,
&context,
)
.unwrap();
// Only the sender's account (TEST_ADDR) should have been modified.
assert_eq!(sess.num_mutated_accounts(&TEST_ADDR), 1);
}
|
{
let code = r#"
module M {
resource struct Foo { a: bool }
public fun get(addr: address): bool acquires Foo {
borrow_global<Foo>(addr).a
}
public fun flip(addr: address) acquires Foo {
let f_ref = borrow_global_mut<Foo>(addr);
f_ref.a = !f_ref.a;
}
public fun publish(addr: &signer) {
move_to(addr, Foo { a: true} )
}
}
"#;
let mut units = compile_units(TEST_ADDR, &code).unwrap();
let m = as_module(units.pop().unwrap());
let mut blob = vec![];
|
identifier_body
|
issue-27868.rs
|
// Copyright 2018 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.
// Regression test for issue #27868
#![feature(nll)]
use std::ops::AddAssign;
struct MyVec<T>(Vec<T>);
impl <T> Drop for MyVec<T> {
fn drop(&mut self) {
println!("Being dropped.");
}
}
impl<T> AddAssign<T> for MyVec<T> {
fn
|
(&mut self, _elem: T) {
println!("In add_assign.");
}
}
fn main() {
let mut vec = MyVec(vec![0]);
let mut vecvec = vec![vec];
vecvec[0] += {
vecvec = vec![];
//~^ ERROR cannot assign to `vecvec` because it is borrowed [E0506]
0
};
}
|
add_assign
|
identifier_name
|
issue-27868.rs
|
// Copyright 2018 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.
// Regression test for issue #27868
#![feature(nll)]
use std::ops::AddAssign;
struct MyVec<T>(Vec<T>);
impl <T> Drop for MyVec<T> {
fn drop(&mut self) {
println!("Being dropped.");
}
}
impl<T> AddAssign<T> for MyVec<T> {
fn add_assign(&mut self, _elem: T) {
println!("In add_assign.");
}
}
fn main()
|
{
let mut vec = MyVec(vec![0]);
let mut vecvec = vec![vec];
vecvec[0] += {
vecvec = vec![];
//~^ ERROR cannot assign to `vecvec` because it is borrowed [E0506]
0
};
}
|
identifier_body
|
|
issue-27868.rs
|
// Copyright 2018 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.
// Regression test for issue #27868
#![feature(nll)]
use std::ops::AddAssign;
struct MyVec<T>(Vec<T>);
impl <T> Drop for MyVec<T> {
fn drop(&mut self) {
println!("Being dropped.");
}
}
impl<T> AddAssign<T> for MyVec<T> {
|
fn main() {
let mut vec = MyVec(vec![0]);
let mut vecvec = vec![vec];
vecvec[0] += {
vecvec = vec![];
//~^ ERROR cannot assign to `vecvec` because it is borrowed [E0506]
0
};
}
|
fn add_assign(&mut self, _elem: T) {
println!("In add_assign.");
}
}
|
random_line_split
|
graph.rs
|
///Graph module, contains a simple graph structure which is when typechecking to find
///functions which are mutually recursive
use std::iter::repeat;
|
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct VertexIndex(usize);
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct EdgeIndex(usize);
impl VertexIndex {
fn get(&self) -> usize { let VertexIndex(v) = *self; v }
}
impl EdgeIndex {
fn get(&self) -> usize { let EdgeIndex(v) = *self; v }
}
pub struct Vertex<T> {
pub value: T,
edges: Vec<EdgeIndex>
}
struct Edge {
from: VertexIndex,
to: VertexIndex
}
pub struct Graph<T> {
edges: Vec<Edge>,
vertices: Vec<Vertex<T>>
}
impl <T> Graph<T> {
///Creates a new graph
pub fn new() -> Graph<T> {
Graph { edges: Vec::new(), vertices: Vec::new() }
}
///Creates a new vertex and returns the index which refers to it
pub fn new_vertex(&mut self, value: T) -> VertexIndex {
self.vertices.push(Vertex { edges:Vec::new(), value: value });
VertexIndex(self.vertices.len() - 1)
}
///Connects two vertices with an edge
pub fn connect(&mut self, from: VertexIndex, to: VertexIndex) {
self.vertices[from.get()].edges.push(EdgeIndex(self.edges.len()));
self.edges.push(Edge { from: from, to: to });
}
///Returns the vertex at the index
pub fn get_vertex<'a>(&'a self, v: VertexIndex) -> &'a Vertex<T> {
&self.vertices[v.get()]
}
///Returns the edge at the index
pub fn get_edge<'a>(&'a self, edge: EdgeIndex) -> &'a Edge {
&self.edges[edge.get()]
}
///Returns how many vertices are in the graph
pub fn len(&self) -> usize {
self.vertices.len()
}
}
///Analyzes the graph for strongly connect components.
///Returns a vector of indices where each group is a separte vector
pub fn strongly_connected_components<T>(graph: &Graph<T>) -> Vec<Vec<VertexIndex>> {
let mut tarjan = TarjanComponents { graph: graph, index: 1, stack: Vec::new(), connections: Vec::new(),
valid: repeat(0).take(graph.len()).collect(),
lowlink: repeat(0).take(graph.len()).collect()
};
for vert in 0..graph.len() {
if tarjan.valid[vert] == 0 {
tarjan.strong_connect(VertexIndex(vert));
}
}
tarjan.connections
}
struct TarjanComponents<'a, T: 'a>{
index: usize,
graph: &'a Graph<T>,
valid: Vec<usize>,
lowlink: Vec<usize>,
stack: Vec<VertexIndex>,
connections: Vec<Vec<VertexIndex>>
}
///Implementation of "Tarjan's strongly connected components algorithm"
impl <'a, T> TarjanComponents<'a, T> {
fn strong_connect(&mut self, v: VertexIndex) {
self.valid[v.get()] = self.index;
self.lowlink[v.get()] = self.index;
self.index += 1;
self.stack.push(v);
for edge_index in self.graph.get_vertex(v).edges.iter() {
let edge = self.graph.get_edge(*edge_index);
if self.valid[edge.to.get()] == 0 {
self.strong_connect(edge.to);
self.lowlink[v.get()] = min(self.lowlink[v.get()], self.lowlink[edge.to.get()]);
}
else if self.stack.iter().any(|x| *x == edge.to) {
self.lowlink[v.get()] = min(self.lowlink[v.get()], self.valid[edge.to.get()]);
}
}
if self.lowlink.get(v.get()) == self.valid.get(v.get()) {
let mut connected = Vec::new();
loop {
let w = self.stack.pop().unwrap();
connected.push(w);
if w == v {
break
}
}
self.connections.push(connected);
}
}
}
#[test]
fn test_tarjan() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 2);
assert_eq!(connections[0], vec![v3]);
assert_eq!(connections[1], vec![v2, v1]);
}
#[test]
fn test_tarjan2() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
let v4 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
graph.connect(v3, v4);
graph.connect(v4, v2);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 1);
assert_eq!(connections[0], vec![v4, v3, v2, v1]);
}
#[test]
fn test_tarjan3() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
let v4 = graph.new_vertex(());
let v5 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
graph.connect(v3, v4);
graph.connect(v4, v3);
graph.connect(v3, v5);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 3);
assert_eq!(connections[0], vec![v5]);
assert_eq!(connections[1], vec![v4, v3]);
assert_eq!(connections[2], vec![v2, v1]);
}
|
use std::cmp::min;
|
random_line_split
|
graph.rs
|
///Graph module, contains a simple graph structure which is when typechecking to find
///functions which are mutually recursive
use std::iter::repeat;
use std::cmp::min;
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct VertexIndex(usize);
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct EdgeIndex(usize);
impl VertexIndex {
fn get(&self) -> usize { let VertexIndex(v) = *self; v }
}
impl EdgeIndex {
fn get(&self) -> usize { let EdgeIndex(v) = *self; v }
}
pub struct Vertex<T> {
pub value: T,
edges: Vec<EdgeIndex>
}
struct Edge {
from: VertexIndex,
to: VertexIndex
}
pub struct Graph<T> {
edges: Vec<Edge>,
vertices: Vec<Vertex<T>>
}
impl <T> Graph<T> {
///Creates a new graph
pub fn new() -> Graph<T> {
Graph { edges: Vec::new(), vertices: Vec::new() }
}
///Creates a new vertex and returns the index which refers to it
pub fn new_vertex(&mut self, value: T) -> VertexIndex {
self.vertices.push(Vertex { edges:Vec::new(), value: value });
VertexIndex(self.vertices.len() - 1)
}
///Connects two vertices with an edge
pub fn connect(&mut self, from: VertexIndex, to: VertexIndex) {
self.vertices[from.get()].edges.push(EdgeIndex(self.edges.len()));
self.edges.push(Edge { from: from, to: to });
}
///Returns the vertex at the index
pub fn get_vertex<'a>(&'a self, v: VertexIndex) -> &'a Vertex<T> {
&self.vertices[v.get()]
}
///Returns the edge at the index
pub fn get_edge<'a>(&'a self, edge: EdgeIndex) -> &'a Edge {
&self.edges[edge.get()]
}
///Returns how many vertices are in the graph
pub fn len(&self) -> usize {
self.vertices.len()
}
}
///Analyzes the graph for strongly connect components.
///Returns a vector of indices where each group is a separte vector
pub fn strongly_connected_components<T>(graph: &Graph<T>) -> Vec<Vec<VertexIndex>> {
let mut tarjan = TarjanComponents { graph: graph, index: 1, stack: Vec::new(), connections: Vec::new(),
valid: repeat(0).take(graph.len()).collect(),
lowlink: repeat(0).take(graph.len()).collect()
};
for vert in 0..graph.len() {
if tarjan.valid[vert] == 0 {
tarjan.strong_connect(VertexIndex(vert));
}
}
tarjan.connections
}
struct TarjanComponents<'a, T: 'a>{
index: usize,
graph: &'a Graph<T>,
valid: Vec<usize>,
lowlink: Vec<usize>,
stack: Vec<VertexIndex>,
connections: Vec<Vec<VertexIndex>>
}
///Implementation of "Tarjan's strongly connected components algorithm"
impl <'a, T> TarjanComponents<'a, T> {
fn strong_connect(&mut self, v: VertexIndex) {
self.valid[v.get()] = self.index;
self.lowlink[v.get()] = self.index;
self.index += 1;
self.stack.push(v);
for edge_index in self.graph.get_vertex(v).edges.iter() {
let edge = self.graph.get_edge(*edge_index);
if self.valid[edge.to.get()] == 0 {
self.strong_connect(edge.to);
self.lowlink[v.get()] = min(self.lowlink[v.get()], self.lowlink[edge.to.get()]);
}
else if self.stack.iter().any(|x| *x == edge.to) {
self.lowlink[v.get()] = min(self.lowlink[v.get()], self.valid[edge.to.get()]);
}
}
if self.lowlink.get(v.get()) == self.valid.get(v.get()) {
let mut connected = Vec::new();
loop {
let w = self.stack.pop().unwrap();
connected.push(w);
if w == v {
break
}
}
self.connections.push(connected);
}
}
}
#[test]
fn test_tarjan() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 2);
assert_eq!(connections[0], vec![v3]);
assert_eq!(connections[1], vec![v2, v1]);
}
#[test]
fn test_tarjan2() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
let v4 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
graph.connect(v3, v4);
graph.connect(v4, v2);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 1);
assert_eq!(connections[0], vec![v4, v3, v2, v1]);
}
#[test]
fn test_tarjan3()
|
{
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
let v4 = graph.new_vertex(());
let v5 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
graph.connect(v3, v4);
graph.connect(v4, v3);
graph.connect(v3, v5);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 3);
assert_eq!(connections[0], vec![v5]);
assert_eq!(connections[1], vec![v4, v3]);
assert_eq!(connections[2], vec![v2, v1]);
}
|
identifier_body
|
|
graph.rs
|
///Graph module, contains a simple graph structure which is when typechecking to find
///functions which are mutually recursive
use std::iter::repeat;
use std::cmp::min;
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct VertexIndex(usize);
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct EdgeIndex(usize);
impl VertexIndex {
fn get(&self) -> usize { let VertexIndex(v) = *self; v }
}
impl EdgeIndex {
fn get(&self) -> usize { let EdgeIndex(v) = *self; v }
}
pub struct Vertex<T> {
pub value: T,
edges: Vec<EdgeIndex>
}
struct Edge {
from: VertexIndex,
to: VertexIndex
}
pub struct Graph<T> {
edges: Vec<Edge>,
vertices: Vec<Vertex<T>>
}
impl <T> Graph<T> {
///Creates a new graph
pub fn new() -> Graph<T> {
Graph { edges: Vec::new(), vertices: Vec::new() }
}
///Creates a new vertex and returns the index which refers to it
pub fn new_vertex(&mut self, value: T) -> VertexIndex {
self.vertices.push(Vertex { edges:Vec::new(), value: value });
VertexIndex(self.vertices.len() - 1)
}
///Connects two vertices with an edge
pub fn connect(&mut self, from: VertexIndex, to: VertexIndex) {
self.vertices[from.get()].edges.push(EdgeIndex(self.edges.len()));
self.edges.push(Edge { from: from, to: to });
}
///Returns the vertex at the index
pub fn get_vertex<'a>(&'a self, v: VertexIndex) -> &'a Vertex<T> {
&self.vertices[v.get()]
}
///Returns the edge at the index
pub fn get_edge<'a>(&'a self, edge: EdgeIndex) -> &'a Edge {
&self.edges[edge.get()]
}
///Returns how many vertices are in the graph
pub fn len(&self) -> usize {
self.vertices.len()
}
}
///Analyzes the graph for strongly connect components.
///Returns a vector of indices where each group is a separte vector
pub fn strongly_connected_components<T>(graph: &Graph<T>) -> Vec<Vec<VertexIndex>> {
let mut tarjan = TarjanComponents { graph: graph, index: 1, stack: Vec::new(), connections: Vec::new(),
valid: repeat(0).take(graph.len()).collect(),
lowlink: repeat(0).take(graph.len()).collect()
};
for vert in 0..graph.len() {
if tarjan.valid[vert] == 0 {
tarjan.strong_connect(VertexIndex(vert));
}
}
tarjan.connections
}
struct TarjanComponents<'a, T: 'a>{
index: usize,
graph: &'a Graph<T>,
valid: Vec<usize>,
lowlink: Vec<usize>,
stack: Vec<VertexIndex>,
connections: Vec<Vec<VertexIndex>>
}
///Implementation of "Tarjan's strongly connected components algorithm"
impl <'a, T> TarjanComponents<'a, T> {
fn strong_connect(&mut self, v: VertexIndex) {
self.valid[v.get()] = self.index;
self.lowlink[v.get()] = self.index;
self.index += 1;
self.stack.push(v);
for edge_index in self.graph.get_vertex(v).edges.iter() {
let edge = self.graph.get_edge(*edge_index);
if self.valid[edge.to.get()] == 0 {
self.strong_connect(edge.to);
self.lowlink[v.get()] = min(self.lowlink[v.get()], self.lowlink[edge.to.get()]);
}
else if self.stack.iter().any(|x| *x == edge.to) {
self.lowlink[v.get()] = min(self.lowlink[v.get()], self.valid[edge.to.get()]);
}
}
if self.lowlink.get(v.get()) == self.valid.get(v.get()) {
let mut connected = Vec::new();
loop {
let w = self.stack.pop().unwrap();
connected.push(w);
if w == v
|
}
self.connections.push(connected);
}
}
}
#[test]
fn test_tarjan() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 2);
assert_eq!(connections[0], vec![v3]);
assert_eq!(connections[1], vec![v2, v1]);
}
#[test]
fn test_tarjan2() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
let v4 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
graph.connect(v3, v4);
graph.connect(v4, v2);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 1);
assert_eq!(connections[0], vec![v4, v3, v2, v1]);
}
#[test]
fn test_tarjan3() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
let v4 = graph.new_vertex(());
let v5 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
graph.connect(v3, v4);
graph.connect(v4, v3);
graph.connect(v3, v5);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 3);
assert_eq!(connections[0], vec![v5]);
assert_eq!(connections[1], vec![v4, v3]);
assert_eq!(connections[2], vec![v2, v1]);
}
|
{
break
}
|
conditional_block
|
graph.rs
|
///Graph module, contains a simple graph structure which is when typechecking to find
///functions which are mutually recursive
use std::iter::repeat;
use std::cmp::min;
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct VertexIndex(usize);
#[derive(PartialEq, Copy, Clone, Debug)]
pub struct EdgeIndex(usize);
impl VertexIndex {
fn
|
(&self) -> usize { let VertexIndex(v) = *self; v }
}
impl EdgeIndex {
fn get(&self) -> usize { let EdgeIndex(v) = *self; v }
}
pub struct Vertex<T> {
pub value: T,
edges: Vec<EdgeIndex>
}
struct Edge {
from: VertexIndex,
to: VertexIndex
}
pub struct Graph<T> {
edges: Vec<Edge>,
vertices: Vec<Vertex<T>>
}
impl <T> Graph<T> {
///Creates a new graph
pub fn new() -> Graph<T> {
Graph { edges: Vec::new(), vertices: Vec::new() }
}
///Creates a new vertex and returns the index which refers to it
pub fn new_vertex(&mut self, value: T) -> VertexIndex {
self.vertices.push(Vertex { edges:Vec::new(), value: value });
VertexIndex(self.vertices.len() - 1)
}
///Connects two vertices with an edge
pub fn connect(&mut self, from: VertexIndex, to: VertexIndex) {
self.vertices[from.get()].edges.push(EdgeIndex(self.edges.len()));
self.edges.push(Edge { from: from, to: to });
}
///Returns the vertex at the index
pub fn get_vertex<'a>(&'a self, v: VertexIndex) -> &'a Vertex<T> {
&self.vertices[v.get()]
}
///Returns the edge at the index
pub fn get_edge<'a>(&'a self, edge: EdgeIndex) -> &'a Edge {
&self.edges[edge.get()]
}
///Returns how many vertices are in the graph
pub fn len(&self) -> usize {
self.vertices.len()
}
}
///Analyzes the graph for strongly connect components.
///Returns a vector of indices where each group is a separte vector
pub fn strongly_connected_components<T>(graph: &Graph<T>) -> Vec<Vec<VertexIndex>> {
let mut tarjan = TarjanComponents { graph: graph, index: 1, stack: Vec::new(), connections: Vec::new(),
valid: repeat(0).take(graph.len()).collect(),
lowlink: repeat(0).take(graph.len()).collect()
};
for vert in 0..graph.len() {
if tarjan.valid[vert] == 0 {
tarjan.strong_connect(VertexIndex(vert));
}
}
tarjan.connections
}
struct TarjanComponents<'a, T: 'a>{
index: usize,
graph: &'a Graph<T>,
valid: Vec<usize>,
lowlink: Vec<usize>,
stack: Vec<VertexIndex>,
connections: Vec<Vec<VertexIndex>>
}
///Implementation of "Tarjan's strongly connected components algorithm"
impl <'a, T> TarjanComponents<'a, T> {
fn strong_connect(&mut self, v: VertexIndex) {
self.valid[v.get()] = self.index;
self.lowlink[v.get()] = self.index;
self.index += 1;
self.stack.push(v);
for edge_index in self.graph.get_vertex(v).edges.iter() {
let edge = self.graph.get_edge(*edge_index);
if self.valid[edge.to.get()] == 0 {
self.strong_connect(edge.to);
self.lowlink[v.get()] = min(self.lowlink[v.get()], self.lowlink[edge.to.get()]);
}
else if self.stack.iter().any(|x| *x == edge.to) {
self.lowlink[v.get()] = min(self.lowlink[v.get()], self.valid[edge.to.get()]);
}
}
if self.lowlink.get(v.get()) == self.valid.get(v.get()) {
let mut connected = Vec::new();
loop {
let w = self.stack.pop().unwrap();
connected.push(w);
if w == v {
break
}
}
self.connections.push(connected);
}
}
}
#[test]
fn test_tarjan() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 2);
assert_eq!(connections[0], vec![v3]);
assert_eq!(connections[1], vec![v2, v1]);
}
#[test]
fn test_tarjan2() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
let v4 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
graph.connect(v3, v4);
graph.connect(v4, v2);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 1);
assert_eq!(connections[0], vec![v4, v3, v2, v1]);
}
#[test]
fn test_tarjan3() {
let mut graph = Graph::new();
let v1 = graph.new_vertex(());
let v2 = graph.new_vertex(());
let v3 = graph.new_vertex(());
let v4 = graph.new_vertex(());
let v5 = graph.new_vertex(());
graph.connect(v1, v2);
graph.connect(v2, v1);
graph.connect(v2, v3);
graph.connect(v3, v4);
graph.connect(v4, v3);
graph.connect(v3, v5);
let connections = strongly_connected_components(&graph);
assert_eq!(connections.len(), 3);
assert_eq!(connections[0], vec![v5]);
assert_eq!(connections[1], vec![v4, v3]);
assert_eq!(connections[2], vec![v2, v1]);
}
|
get
|
identifier_name
|
ast.rs
|
pub struct ModuleDecl {
pub name: Ident,
pub endname: Ident,
pub components: Vec<ComponentDecl>,
pub entities: Vec<EntityDecl>
}
pub struct EntityDecl {
pub name: Ident,
pub endname: Ident,
pub generics: Option<Vec<GenericDecl>>,
pub ports: Option<Vec<PortDecl>>,
pub wires: Vec<WireDecl>,
pub insts: Vec<EntityInst>
}
pub struct ComponentDecl {
pub name: Ident,
pub endname: Ident,
pub generics: Option<Vec<GenericDecl>>,
pub ports: Option<Vec<PortDecl>>,
pub attributes: Vec<AttributeDef>
}
pub struct GenericDecl {
pub name: Ident,
pub gentype: Ident,
pub defval: Option<ConstExpr>
}
pub struct
|
{
pub name: Ident,
pub dir: Direction,
pub class: Ident
}
pub struct AttributeDef {
pub name: Ident,
pub typename: Ident,
pub value: ConstExpr
}
pub struct WireDecl {
pub name: Ident,
pub class: Ident
}
pub enum EntityInst {
Short(EntityInstShort),
Long(EntityInstLong)
}
pub struct EntityInstShort {
pub name: Ident,
pub ports: CommaList<Ident>,
pub entity: Ident,
pub generics: Option<CommaList<ConstExpr>>
}
pub struct EntityInstLong {
pub name: Ident,
pub entity: Ident,
pub generics: Option<Vec<GenericAssign>>,
pub ports: Option<Vec<PortAssign>>
}
pub struct GenericAssign {
pub generic: Ident,
pub value: ConstExpr
}
pub struct PortAssign {
pub port: Ident,
pub dir: Direction,
pub wire: Ident
}
pub struct CommaList<T> {
pub head: Vec<T>,
pub tail: T
}
pub enum ConstExpr {
Ident(Ident),
Number(Number),
String(String)
}
// Terminals
pub enum Direction { None, In, Out }
pub struct Number(pub String);
pub struct Ident(pub String);
|
PortDecl
|
identifier_name
|
ast.rs
|
pub struct ModuleDecl {
pub name: Ident,
pub endname: Ident,
pub components: Vec<ComponentDecl>,
pub entities: Vec<EntityDecl>
}
pub struct EntityDecl {
pub name: Ident,
pub endname: Ident,
pub generics: Option<Vec<GenericDecl>>,
pub ports: Option<Vec<PortDecl>>,
pub wires: Vec<WireDecl>,
pub insts: Vec<EntityInst>
}
pub struct ComponentDecl {
pub name: Ident,
pub endname: Ident,
pub generics: Option<Vec<GenericDecl>>,
pub ports: Option<Vec<PortDecl>>,
pub attributes: Vec<AttributeDef>
}
pub struct GenericDecl {
pub name: Ident,
pub gentype: Ident,
pub defval: Option<ConstExpr>
}
pub struct PortDecl {
pub name: Ident,
pub dir: Direction,
pub class: Ident
|
}
pub struct AttributeDef {
pub name: Ident,
pub typename: Ident,
pub value: ConstExpr
}
pub struct WireDecl {
pub name: Ident,
pub class: Ident
}
pub enum EntityInst {
Short(EntityInstShort),
Long(EntityInstLong)
}
pub struct EntityInstShort {
pub name: Ident,
pub ports: CommaList<Ident>,
pub entity: Ident,
pub generics: Option<CommaList<ConstExpr>>
}
pub struct EntityInstLong {
pub name: Ident,
pub entity: Ident,
pub generics: Option<Vec<GenericAssign>>,
pub ports: Option<Vec<PortAssign>>
}
pub struct GenericAssign {
pub generic: Ident,
pub value: ConstExpr
}
pub struct PortAssign {
pub port: Ident,
pub dir: Direction,
pub wire: Ident
}
pub struct CommaList<T> {
pub head: Vec<T>,
pub tail: T
}
pub enum ConstExpr {
Ident(Ident),
Number(Number),
String(String)
}
// Terminals
pub enum Direction { None, In, Out }
pub struct Number(pub String);
pub struct Ident(pub String);
|
random_line_split
|
|
baseline_reinforce.rs
|
use crate::{
domains::Batch,
fa::StateActionUpdate,
policies::Policy,
Function,
Handler,
|
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct BaselineREINFORCE<B, P> {
#[weights]
pub policy: P,
pub baseline: B,
pub alpha: f64,
pub gamma: f64,
}
impl<B, P> BaselineREINFORCE<B, P> {
pub fn new(policy: P, baseline: B, alpha: f64, gamma: f64) -> Self {
BaselineREINFORCE {
policy,
baseline,
alpha,
gamma,
}
}
}
impl<'m, S, B, P> Handler<&'m Batch<S, P::Action>> for BaselineREINFORCE<B, P>
where
P: Policy<S> + Handler<StateActionUpdate<&'m S, &'m <P as Policy<S>>::Action>>,
B: Function<(&'m S, &'m P::Action), Output = f64>,
{
type Response = Vec<P::Response>;
type Error = P::Error;
fn handle(&mut self, batch: &'m Batch<S, P::Action>) -> Result<Self::Response, Self::Error> {
let mut ret = 0.0;
batch.iter().map(|t| {
let s = t.from.state();
let baseline = self.baseline.evaluate((s, &t.action));
ret = t.reward + self.gamma * ret;
self.policy.handle(StateActionUpdate {
state: t.from.state(),
action: &t.action,
error: self.alpha * (ret - baseline),
})
}).collect()
}
}
|
};
|
random_line_split
|
baseline_reinforce.rs
|
use crate::{
domains::Batch,
fa::StateActionUpdate,
policies::Policy,
Function,
Handler,
};
#[derive(Clone, Debug, Parameterised)]
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate")
)]
pub struct BaselineREINFORCE<B, P> {
#[weights]
pub policy: P,
pub baseline: B,
pub alpha: f64,
pub gamma: f64,
}
impl<B, P> BaselineREINFORCE<B, P> {
pub fn new(policy: P, baseline: B, alpha: f64, gamma: f64) -> Self {
BaselineREINFORCE {
policy,
baseline,
alpha,
gamma,
}
}
}
impl<'m, S, B, P> Handler<&'m Batch<S, P::Action>> for BaselineREINFORCE<B, P>
where
P: Policy<S> + Handler<StateActionUpdate<&'m S, &'m <P as Policy<S>>::Action>>,
B: Function<(&'m S, &'m P::Action), Output = f64>,
{
type Response = Vec<P::Response>;
type Error = P::Error;
fn
|
(&mut self, batch: &'m Batch<S, P::Action>) -> Result<Self::Response, Self::Error> {
let mut ret = 0.0;
batch.iter().map(|t| {
let s = t.from.state();
let baseline = self.baseline.evaluate((s, &t.action));
ret = t.reward + self.gamma * ret;
self.policy.handle(StateActionUpdate {
state: t.from.state(),
action: &t.action,
error: self.alpha * (ret - baseline),
})
}).collect()
}
}
|
handle
|
identifier_name
|
binprocess.rs
|
use std::process::exit;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::ffi::CString;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use shell::Shell;
use posix;
use opts;
use posix::ReadPipe;
use posix::WritePipe;
use posix::Pgid;
use exec::Arg;
use exec::Process;
use exec::ProcessInner;
use exec::Child;
pub struct BinProcess {
to_exec: PathBuf,
argv: Vec<*const i8>,
m_args: Vec<CString>,
inner: ProcessInner,
}
fn os2c(s: &OsStr) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| CString::new("<string-with-nul>").unwrap())
}
|
fn str2c(s: String) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| CString::new("<string-with-nul>").unwrap())
}
impl BinProcess {
pub fn new(cmd: &String, b: PathBuf) -> Self {
let cb = str2c(cmd.to_owned());
BinProcess {
argv: vec![cb.as_ptr(), 0 as *const _],
to_exec: b,
m_args: vec![cb],
inner: ProcessInner::new(),
}
}
}
impl Process for BinProcess {
fn exec(self, _sh: &mut Shell, pgid: Option<Pgid>) -> Option<Child> {
match posix::fork(opts::is_set("__tin_inter"), pgid) {
Err(e) => {
// oops. gotta bail.
warn!("Could not fork child: {}", e);
None
}
Ok(None) => {
if let Err(e) = self.inner.redirect(false) {
warn!("Could not redirect: {}", e);
exit(e.raw_os_error().unwrap_or(7));
}
let e = posix::execv(pb2c(self.to_exec).as_ptr(), self.argv.as_ptr());
if e.kind() == ErrorKind::NotFound {
// TODO: custom handler function
warn!("Command '{}' not found.", self.m_args[0].to_str().unwrap());
} else {
warn!("Could not exec: {}", e);
}
exit(e.raw_os_error().unwrap_or(22)); // EINVAL
}
Ok(Some(ch_pid)) => Some(Child::new(ch_pid)),
}
}
// A BinProcess always has at least its first argument -- the executable
// to be run.
fn has_args(&self) -> bool {
true
}
fn push_arg(&mut self, new_arg: Arg) -> &Process {
// downconvert args to Strings as we add them
let mut v = Vec::new();
match new_arg {
Arg::Str(s) => {
v.push(s);
}
Arg::Bl(lines) => {
for l in lines {
v.push(l);
}
}
Arg::Rd(rd) => {
self.inner.rds.push(rd);
}
}
// TODO: this is not a perfect way to do this
for new_arg in v {
let arg = str2c(new_arg);
self.argv[self.m_args.len()] = arg.as_ptr();
self.argv.push(0 as *const _);
// for memory correctness
self.m_args.push(arg);
}
self
}
fn stdin(&mut self, read: ReadPipe) -> &Process {
self.inner.ch_stdin = Some(read);
self
}
fn stdout(&mut self, write: WritePipe) -> &Process {
self.inner.ch_stdout = Some(write);
self
}
}
|
fn pb2c(pb: PathBuf) -> CString {
os2c(pb.as_os_str())
}
|
random_line_split
|
binprocess.rs
|
use std::process::exit;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::ffi::CString;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use shell::Shell;
use posix;
use opts;
use posix::ReadPipe;
use posix::WritePipe;
use posix::Pgid;
use exec::Arg;
use exec::Process;
use exec::ProcessInner;
use exec::Child;
pub struct BinProcess {
to_exec: PathBuf,
argv: Vec<*const i8>,
m_args: Vec<CString>,
inner: ProcessInner,
}
fn os2c(s: &OsStr) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| CString::new("<string-with-nul>").unwrap())
}
fn pb2c(pb: PathBuf) -> CString {
os2c(pb.as_os_str())
}
fn str2c(s: String) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| CString::new("<string-with-nul>").unwrap())
}
impl BinProcess {
pub fn new(cmd: &String, b: PathBuf) -> Self {
let cb = str2c(cmd.to_owned());
BinProcess {
argv: vec![cb.as_ptr(), 0 as *const _],
to_exec: b,
m_args: vec![cb],
inner: ProcessInner::new(),
}
}
}
impl Process for BinProcess {
fn exec(self, _sh: &mut Shell, pgid: Option<Pgid>) -> Option<Child> {
match posix::fork(opts::is_set("__tin_inter"), pgid) {
Err(e) => {
// oops. gotta bail.
warn!("Could not fork child: {}", e);
None
}
Ok(None) => {
if let Err(e) = self.inner.redirect(false) {
warn!("Could not redirect: {}", e);
exit(e.raw_os_error().unwrap_or(7));
}
let e = posix::execv(pb2c(self.to_exec).as_ptr(), self.argv.as_ptr());
if e.kind() == ErrorKind::NotFound {
// TODO: custom handler function
warn!("Command '{}' not found.", self.m_args[0].to_str().unwrap());
} else {
warn!("Could not exec: {}", e);
}
exit(e.raw_os_error().unwrap_or(22)); // EINVAL
}
Ok(Some(ch_pid)) => Some(Child::new(ch_pid)),
}
}
// A BinProcess always has at least its first argument -- the executable
// to be run.
fn has_args(&self) -> bool {
true
}
fn push_arg(&mut self, new_arg: Arg) -> &Process {
// downconvert args to Strings as we add them
let mut v = Vec::new();
match new_arg {
Arg::Str(s) => {
v.push(s);
}
Arg::Bl(lines) => {
for l in lines {
v.push(l);
}
}
Arg::Rd(rd) => {
self.inner.rds.push(rd);
}
}
// TODO: this is not a perfect way to do this
for new_arg in v {
let arg = str2c(new_arg);
self.argv[self.m_args.len()] = arg.as_ptr();
self.argv.push(0 as *const _);
// for memory correctness
self.m_args.push(arg);
}
self
}
fn stdin(&mut self, read: ReadPipe) -> &Process {
self.inner.ch_stdin = Some(read);
self
}
fn stdout(&mut self, write: WritePipe) -> &Process
|
}
|
{
self.inner.ch_stdout = Some(write);
self
}
|
identifier_body
|
binprocess.rs
|
use std::process::exit;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::ffi::CString;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use shell::Shell;
use posix;
use opts;
use posix::ReadPipe;
use posix::WritePipe;
use posix::Pgid;
use exec::Arg;
use exec::Process;
use exec::ProcessInner;
use exec::Child;
pub struct BinProcess {
to_exec: PathBuf,
argv: Vec<*const i8>,
m_args: Vec<CString>,
inner: ProcessInner,
}
fn os2c(s: &OsStr) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| CString::new("<string-with-nul>").unwrap())
}
fn pb2c(pb: PathBuf) -> CString {
os2c(pb.as_os_str())
}
fn str2c(s: String) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| CString::new("<string-with-nul>").unwrap())
}
impl BinProcess {
pub fn new(cmd: &String, b: PathBuf) -> Self {
let cb = str2c(cmd.to_owned());
BinProcess {
argv: vec![cb.as_ptr(), 0 as *const _],
to_exec: b,
m_args: vec![cb],
inner: ProcessInner::new(),
}
}
}
impl Process for BinProcess {
fn exec(self, _sh: &mut Shell, pgid: Option<Pgid>) -> Option<Child> {
match posix::fork(opts::is_set("__tin_inter"), pgid) {
Err(e) => {
// oops. gotta bail.
warn!("Could not fork child: {}", e);
None
}
Ok(None) => {
if let Err(e) = self.inner.redirect(false) {
warn!("Could not redirect: {}", e);
exit(e.raw_os_error().unwrap_or(7));
}
let e = posix::execv(pb2c(self.to_exec).as_ptr(), self.argv.as_ptr());
if e.kind() == ErrorKind::NotFound {
// TODO: custom handler function
warn!("Command '{}' not found.", self.m_args[0].to_str().unwrap());
} else {
warn!("Could not exec: {}", e);
}
exit(e.raw_os_error().unwrap_or(22)); // EINVAL
}
Ok(Some(ch_pid)) => Some(Child::new(ch_pid)),
}
}
// A BinProcess always has at least its first argument -- the executable
// to be run.
fn has_args(&self) -> bool {
true
}
fn push_arg(&mut self, new_arg: Arg) -> &Process {
// downconvert args to Strings as we add them
let mut v = Vec::new();
match new_arg {
Arg::Str(s) => {
v.push(s);
}
Arg::Bl(lines) =>
|
Arg::Rd(rd) => {
self.inner.rds.push(rd);
}
}
// TODO: this is not a perfect way to do this
for new_arg in v {
let arg = str2c(new_arg);
self.argv[self.m_args.len()] = arg.as_ptr();
self.argv.push(0 as *const _);
// for memory correctness
self.m_args.push(arg);
}
self
}
fn stdin(&mut self, read: ReadPipe) -> &Process {
self.inner.ch_stdin = Some(read);
self
}
fn stdout(&mut self, write: WritePipe) -> &Process {
self.inner.ch_stdout = Some(write);
self
}
}
|
{
for l in lines {
v.push(l);
}
}
|
conditional_block
|
binprocess.rs
|
use std::process::exit;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::ffi::CString;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
use shell::Shell;
use posix;
use opts;
use posix::ReadPipe;
use posix::WritePipe;
use posix::Pgid;
use exec::Arg;
use exec::Process;
use exec::ProcessInner;
use exec::Child;
pub struct BinProcess {
to_exec: PathBuf,
argv: Vec<*const i8>,
m_args: Vec<CString>,
inner: ProcessInner,
}
fn os2c(s: &OsStr) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| CString::new("<string-with-nul>").unwrap())
}
fn pb2c(pb: PathBuf) -> CString {
os2c(pb.as_os_str())
}
fn str2c(s: String) -> CString {
CString::new(s.as_bytes()).unwrap_or_else(|_e| CString::new("<string-with-nul>").unwrap())
}
impl BinProcess {
pub fn new(cmd: &String, b: PathBuf) -> Self {
let cb = str2c(cmd.to_owned());
BinProcess {
argv: vec![cb.as_ptr(), 0 as *const _],
to_exec: b,
m_args: vec![cb],
inner: ProcessInner::new(),
}
}
}
impl Process for BinProcess {
fn exec(self, _sh: &mut Shell, pgid: Option<Pgid>) -> Option<Child> {
match posix::fork(opts::is_set("__tin_inter"), pgid) {
Err(e) => {
// oops. gotta bail.
warn!("Could not fork child: {}", e);
None
}
Ok(None) => {
if let Err(e) = self.inner.redirect(false) {
warn!("Could not redirect: {}", e);
exit(e.raw_os_error().unwrap_or(7));
}
let e = posix::execv(pb2c(self.to_exec).as_ptr(), self.argv.as_ptr());
if e.kind() == ErrorKind::NotFound {
// TODO: custom handler function
warn!("Command '{}' not found.", self.m_args[0].to_str().unwrap());
} else {
warn!("Could not exec: {}", e);
}
exit(e.raw_os_error().unwrap_or(22)); // EINVAL
}
Ok(Some(ch_pid)) => Some(Child::new(ch_pid)),
}
}
// A BinProcess always has at least its first argument -- the executable
// to be run.
fn has_args(&self) -> bool {
true
}
fn
|
(&mut self, new_arg: Arg) -> &Process {
// downconvert args to Strings as we add them
let mut v = Vec::new();
match new_arg {
Arg::Str(s) => {
v.push(s);
}
Arg::Bl(lines) => {
for l in lines {
v.push(l);
}
}
Arg::Rd(rd) => {
self.inner.rds.push(rd);
}
}
// TODO: this is not a perfect way to do this
for new_arg in v {
let arg = str2c(new_arg);
self.argv[self.m_args.len()] = arg.as_ptr();
self.argv.push(0 as *const _);
// for memory correctness
self.m_args.push(arg);
}
self
}
fn stdin(&mut self, read: ReadPipe) -> &Process {
self.inner.ch_stdin = Some(read);
self
}
fn stdout(&mut self, write: WritePipe) -> &Process {
self.inner.ch_stdout = Some(write);
self
}
}
|
push_arg
|
identifier_name
|
stdin.rs
|
use std::io::{Read, Result, Error};
use libc::{self, c_void, size_t};
use sync::NotThreadSafe;
use buf::CopyingBufReader;
lazy_static! {
static ref STDIN: NotThreadSafe<CopyingBufReader<Stdin>> = {
NotThreadSafe::new(CopyingBufReader::new(Stdin::new()))
};
}
|
unsafe { STDIN.get().as_mut().unwrap() }
}
pub struct Stdin;
impl Stdin {
fn new() -> Stdin {
Stdin {}
}
}
impl Read for Stdin {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let ret = unsafe {
libc::read(
libc::STDIN_FILENO,
buf.as_mut_ptr() as *mut c_void,
buf.len() as size_t
)
};
if ret == -1 {
Err(Error::last_os_error())
} else {
Ok(ret as usize)
}
}
}
|
pub fn stdin() -> &'static mut CopyingBufReader<Stdin> {
|
random_line_split
|
stdin.rs
|
use std::io::{Read, Result, Error};
use libc::{self, c_void, size_t};
use sync::NotThreadSafe;
use buf::CopyingBufReader;
lazy_static! {
static ref STDIN: NotThreadSafe<CopyingBufReader<Stdin>> = {
NotThreadSafe::new(CopyingBufReader::new(Stdin::new()))
};
}
pub fn stdin() -> &'static mut CopyingBufReader<Stdin> {
unsafe { STDIN.get().as_mut().unwrap() }
}
pub struct Stdin;
impl Stdin {
fn new() -> Stdin {
Stdin {}
}
}
impl Read for Stdin {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let ret = unsafe {
libc::read(
libc::STDIN_FILENO,
buf.as_mut_ptr() as *mut c_void,
buf.len() as size_t
)
};
if ret == -1 {
Err(Error::last_os_error())
} else
|
}
}
|
{
Ok(ret as usize)
}
|
conditional_block
|
stdin.rs
|
use std::io::{Read, Result, Error};
use libc::{self, c_void, size_t};
use sync::NotThreadSafe;
use buf::CopyingBufReader;
lazy_static! {
static ref STDIN: NotThreadSafe<CopyingBufReader<Stdin>> = {
NotThreadSafe::new(CopyingBufReader::new(Stdin::new()))
};
}
pub fn stdin() -> &'static mut CopyingBufReader<Stdin>
|
pub struct Stdin;
impl Stdin {
fn new() -> Stdin {
Stdin {}
}
}
impl Read for Stdin {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let ret = unsafe {
libc::read(
libc::STDIN_FILENO,
buf.as_mut_ptr() as *mut c_void,
buf.len() as size_t
)
};
if ret == -1 {
Err(Error::last_os_error())
} else {
Ok(ret as usize)
}
}
}
|
{
unsafe { STDIN.get().as_mut().unwrap() }
}
|
identifier_body
|
stdin.rs
|
use std::io::{Read, Result, Error};
use libc::{self, c_void, size_t};
use sync::NotThreadSafe;
use buf::CopyingBufReader;
lazy_static! {
static ref STDIN: NotThreadSafe<CopyingBufReader<Stdin>> = {
NotThreadSafe::new(CopyingBufReader::new(Stdin::new()))
};
}
pub fn stdin() -> &'static mut CopyingBufReader<Stdin> {
unsafe { STDIN.get().as_mut().unwrap() }
}
pub struct Stdin;
impl Stdin {
fn new() -> Stdin {
Stdin {}
}
}
impl Read for Stdin {
fn
|
(&mut self, buf: &mut [u8]) -> Result<usize> {
let ret = unsafe {
libc::read(
libc::STDIN_FILENO,
buf.as_mut_ptr() as *mut c_void,
buf.len() as size_t
)
};
if ret == -1 {
Err(Error::last_os_error())
} else {
Ok(ret as usize)
}
}
}
|
read
|
identifier_name
|
trait-generic.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.
trait to_str {
fn to_string_(&self) -> String;
}
impl to_str for int {
fn to_string_(&self) -> String { self.to_string() }
}
impl to_str for String {
fn to_string_(&self) -> String { self.clone() }
}
impl to_str for () {
fn to_string_(&self) -> String { "()".to_string() }
}
trait map<T> {
fn map<U, F>(&self, f: F) -> Vec<U> where F: FnMut(&T) -> U;
}
impl<T> map<T> for Vec<T> {
fn
|
<U, F>(&self, mut f: F) -> Vec<U> where F: FnMut(&T) -> U {
let mut r = Vec::new();
for i in self.iter() {
r.push(f(i));
}
r
}
}
fn foo<U, T: map<U>>(x: T) -> Vec<String> {
x.map(|_e| "hi".to_string() )
}
fn bar<U:to_str,T:map<U>>(x: T) -> Vec<String> {
x.map(|_e| _e.to_string_() )
}
pub fn main() {
assert_eq!(foo(vec!(1i)), vec!("hi".to_string()));
assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("4".to_string(), "5".to_string()));
assert_eq!(bar::<String, Vec<String> >(vec!("x".to_string(), "y".to_string())),
vec!("x".to_string(), "y".to_string()));
assert_eq!(bar::<(), Vec<()>>(vec!(())), vec!("()".to_string()));
}
|
map
|
identifier_name
|
trait-generic.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.
trait to_str {
fn to_string_(&self) -> String;
}
impl to_str for int {
fn to_string_(&self) -> String { self.to_string() }
}
impl to_str for String {
fn to_string_(&self) -> String { self.clone() }
}
impl to_str for () {
fn to_string_(&self) -> String { "()".to_string() }
}
trait map<T> {
fn map<U, F>(&self, f: F) -> Vec<U> where F: FnMut(&T) -> U;
|
for i in self.iter() {
r.push(f(i));
}
r
}
}
fn foo<U, T: map<U>>(x: T) -> Vec<String> {
x.map(|_e| "hi".to_string() )
}
fn bar<U:to_str,T:map<U>>(x: T) -> Vec<String> {
x.map(|_e| _e.to_string_() )
}
pub fn main() {
assert_eq!(foo(vec!(1i)), vec!("hi".to_string()));
assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("4".to_string(), "5".to_string()));
assert_eq!(bar::<String, Vec<String> >(vec!("x".to_string(), "y".to_string())),
vec!("x".to_string(), "y".to_string()));
assert_eq!(bar::<(), Vec<()>>(vec!(())), vec!("()".to_string()));
}
|
}
impl<T> map<T> for Vec<T> {
fn map<U, F>(&self, mut f: F) -> Vec<U> where F: FnMut(&T) -> U {
let mut r = Vec::new();
|
random_line_split
|
trait-generic.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.
trait to_str {
fn to_string_(&self) -> String;
}
impl to_str for int {
fn to_string_(&self) -> String { self.to_string() }
}
impl to_str for String {
fn to_string_(&self) -> String { self.clone() }
}
impl to_str for () {
fn to_string_(&self) -> String { "()".to_string() }
}
trait map<T> {
fn map<U, F>(&self, f: F) -> Vec<U> where F: FnMut(&T) -> U;
}
impl<T> map<T> for Vec<T> {
fn map<U, F>(&self, mut f: F) -> Vec<U> where F: FnMut(&T) -> U {
let mut r = Vec::new();
for i in self.iter() {
r.push(f(i));
}
r
}
}
fn foo<U, T: map<U>>(x: T) -> Vec<String> {
x.map(|_e| "hi".to_string() )
}
fn bar<U:to_str,T:map<U>>(x: T) -> Vec<String> {
x.map(|_e| _e.to_string_() )
}
pub fn main()
|
{
assert_eq!(foo(vec!(1i)), vec!("hi".to_string()));
assert_eq!(bar::<int, Vec<int> >(vec!(4, 5)), vec!("4".to_string(), "5".to_string()));
assert_eq!(bar::<String, Vec<String> >(vec!("x".to_string(), "y".to_string())),
vec!("x".to_string(), "y".to_string()));
assert_eq!(bar::<(), Vec<()>>(vec!(())), vec!("()".to_string()));
}
|
identifier_body
|
|
adjancency_list.rs
|
extern crate fasttrack;
use fasttrack::adjancency_list;
use fasttrack::edge::Edge;
use fasttrack::route_node::RouteNode;
#[test]
fn adjancency_list_is_built_correctly() {
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 0, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weight: 20});
routes.push(RouteNode{from: 1, to: 0, weight: 12});
routes.push(RouteNode{from: 1, to: 2, weight: 25});
routes.push(RouteNode{from: 2, to: 1, weight: 13});
let adj_list = adjancency_list::construct(routes);
assert_eq!(3, adj_list.len());
assert_eq!(2, adj_list[0].len());
assert_eq!(vec![Edge::new(0, 15), Edge::new(1, 20)], adj_list[0]);
assert_eq!(2, adj_list[1].len());
assert_eq!(vec![Edge::new(0, 12), Edge::new(2, 25)], adj_list[1]);
assert_eq!(1, adj_list[2].len());
assert_eq!(vec![Edge::new(1, 13)], adj_list[2]);
}
#[test]
fn
|
() {
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 10, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weight: 20});
routes.push(RouteNode{from: 1, to: 0, weight: 20});
let adj_list = adjancency_list::construct(routes);
assert_eq!(11, adj_list.len());
}
|
list_size_is_correct_even_if_missing_some_nodes
|
identifier_name
|
adjancency_list.rs
|
extern crate fasttrack;
use fasttrack::adjancency_list;
use fasttrack::edge::Edge;
use fasttrack::route_node::RouteNode;
#[test]
fn adjancency_list_is_built_correctly() {
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 0, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weight: 20});
routes.push(RouteNode{from: 1, to: 0, weight: 12});
routes.push(RouteNode{from: 1, to: 2, weight: 25});
routes.push(RouteNode{from: 2, to: 1, weight: 13});
let adj_list = adjancency_list::construct(routes);
assert_eq!(3, adj_list.len());
assert_eq!(2, adj_list[0].len());
assert_eq!(vec![Edge::new(0, 15), Edge::new(1, 20)], adj_list[0]);
assert_eq!(2, adj_list[1].len());
assert_eq!(vec![Edge::new(0, 12), Edge::new(2, 25)], adj_list[1]);
assert_eq!(1, adj_list[2].len());
assert_eq!(vec![Edge::new(1, 13)], adj_list[2]);
}
#[test]
fn list_size_is_correct_even_if_missing_some_nodes()
|
{
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 10, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weight: 20});
routes.push(RouteNode{from: 1, to: 0, weight: 20});
let adj_list = adjancency_list::construct(routes);
assert_eq!(11, adj_list.len());
}
|
identifier_body
|
|
adjancency_list.rs
|
extern crate fasttrack;
use fasttrack::adjancency_list;
use fasttrack::edge::Edge;
use fasttrack::route_node::RouteNode;
#[test]
fn adjancency_list_is_built_correctly() {
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 0, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weight: 20});
routes.push(RouteNode{from: 1, to: 0, weight: 12});
routes.push(RouteNode{from: 1, to: 2, weight: 25});
routes.push(RouteNode{from: 2, to: 1, weight: 13});
let adj_list = adjancency_list::construct(routes);
assert_eq!(3, adj_list.len());
assert_eq!(2, adj_list[0].len());
assert_eq!(vec![Edge::new(0, 15), Edge::new(1, 20)], adj_list[0]);
assert_eq!(2, adj_list[1].len());
assert_eq!(vec![Edge::new(0, 12), Edge::new(2, 25)], adj_list[1]);
assert_eq!(1, adj_list[2].len());
assert_eq!(vec![Edge::new(1, 13)], adj_list[2]);
}
#[test]
fn list_size_is_correct_even_if_missing_some_nodes() {
let mut routes:Vec<RouteNode> = Vec::new();
routes.push(RouteNode{from: 0, to: 10, weight: 15});
routes.push(RouteNode{from: 0, to: 1, weight: 20});
routes.push(RouteNode{from: 1, to: 0, weight: 20});
let adj_list = adjancency_list::construct(routes);
|
assert_eq!(11, adj_list.len());
}
|
random_line_split
|
|
testrunner.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 https://mozilla.org/MPL/2.0/. */
|
use crate::dom::bindings::error::{Error, ErrorResult};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use ipc_channel::ipc::IpcSender;
use profile_traits::ipc;
// https://webbluetoothcg.github.io/web-bluetooth/tests#test-runner
#[dom_struct]
pub struct TestRunner {
reflector_: Reflector,
}
impl TestRunner {
pub fn new_inherited() -> TestRunner {
TestRunner {
reflector_: Reflector::new(),
}
}
pub fn new(global: &GlobalScope) -> DomRoot<TestRunner> {
reflect_dom_object(
Box::new(TestRunner::new_inherited()),
global,
TestRunnerBinding::Wrap,
)
}
fn get_bluetooth_thread(&self) -> IpcSender<BluetoothRequest> {
self.global().as_window().bluetooth_thread()
}
}
impl TestRunnerMethods for TestRunner {
// https://webbluetoothcg.github.io/web-bluetooth/tests#setBluetoothMockDataSet
fn SetBluetoothMockDataSet(&self, dataSetName: DOMString) -> ErrorResult {
let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
self.get_bluetooth_thread()
.send(BluetoothRequest::Test(String::from(dataSetName), sender))
.unwrap();
match receiver.recv().unwrap().into() {
Ok(()) => Ok(()),
Err(error) => Err(Error::from(error)),
}
}
}
|
use bluetooth_traits::BluetoothRequest;
use crate::dom::bindings::codegen::Bindings::TestRunnerBinding;
use crate::dom::bindings::codegen::Bindings::TestRunnerBinding::TestRunnerMethods;
|
random_line_split
|
testrunner.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 https://mozilla.org/MPL/2.0/. */
use bluetooth_traits::BluetoothRequest;
use crate::dom::bindings::codegen::Bindings::TestRunnerBinding;
use crate::dom::bindings::codegen::Bindings::TestRunnerBinding::TestRunnerMethods;
use crate::dom::bindings::error::{Error, ErrorResult};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use ipc_channel::ipc::IpcSender;
use profile_traits::ipc;
// https://webbluetoothcg.github.io/web-bluetooth/tests#test-runner
#[dom_struct]
pub struct TestRunner {
reflector_: Reflector,
}
impl TestRunner {
pub fn new_inherited() -> TestRunner {
TestRunner {
reflector_: Reflector::new(),
}
}
pub fn new(global: &GlobalScope) -> DomRoot<TestRunner>
|
fn get_bluetooth_thread(&self) -> IpcSender<BluetoothRequest> {
self.global().as_window().bluetooth_thread()
}
}
impl TestRunnerMethods for TestRunner {
// https://webbluetoothcg.github.io/web-bluetooth/tests#setBluetoothMockDataSet
fn SetBluetoothMockDataSet(&self, dataSetName: DOMString) -> ErrorResult {
let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
self.get_bluetooth_thread()
.send(BluetoothRequest::Test(String::from(dataSetName), sender))
.unwrap();
match receiver.recv().unwrap().into() {
Ok(()) => Ok(()),
Err(error) => Err(Error::from(error)),
}
}
}
|
{
reflect_dom_object(
Box::new(TestRunner::new_inherited()),
global,
TestRunnerBinding::Wrap,
)
}
|
identifier_body
|
testrunner.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 https://mozilla.org/MPL/2.0/. */
use bluetooth_traits::BluetoothRequest;
use crate::dom::bindings::codegen::Bindings::TestRunnerBinding;
use crate::dom::bindings::codegen::Bindings::TestRunnerBinding::TestRunnerMethods;
use crate::dom::bindings::error::{Error, ErrorResult};
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::DOMString;
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use ipc_channel::ipc::IpcSender;
use profile_traits::ipc;
// https://webbluetoothcg.github.io/web-bluetooth/tests#test-runner
#[dom_struct]
pub struct TestRunner {
reflector_: Reflector,
}
impl TestRunner {
pub fn new_inherited() -> TestRunner {
TestRunner {
reflector_: Reflector::new(),
}
}
pub fn new(global: &GlobalScope) -> DomRoot<TestRunner> {
reflect_dom_object(
Box::new(TestRunner::new_inherited()),
global,
TestRunnerBinding::Wrap,
)
}
fn get_bluetooth_thread(&self) -> IpcSender<BluetoothRequest> {
self.global().as_window().bluetooth_thread()
}
}
impl TestRunnerMethods for TestRunner {
// https://webbluetoothcg.github.io/web-bluetooth/tests#setBluetoothMockDataSet
fn
|
(&self, dataSetName: DOMString) -> ErrorResult {
let (sender, receiver) = ipc::channel(self.global().time_profiler_chan().clone()).unwrap();
self.get_bluetooth_thread()
.send(BluetoothRequest::Test(String::from(dataSetName), sender))
.unwrap();
match receiver.recv().unwrap().into() {
Ok(()) => Ok(()),
Err(error) => Err(Error::from(error)),
}
}
}
|
SetBluetoothMockDataSet
|
identifier_name
|
ascii.rs
|
//! Operations on ASCII `[u8]`.
use crate::ascii;
use crate::fmt::{self, Write};
use crate::iter;
use crate::mem;
use crate::ops;
#[lang = "slice_u8"]
#[cfg(not(test))]
impl [u8] {
/// Checks if all bytes in this slice are within the ASCII range.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn is_ascii(&self) -> bool {
is_ascii(self)
}
/// Checks that two slices are an ASCII case-insensitive match.
///
/// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
/// but without allocating and copying temporaries.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
self.len() == other.len() && iter::zip(self, other).all(|(a, b)| a.eq_ignore_ascii_case(b))
}
/// Converts this slice to its ASCII upper case equivalent in-place.
///
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
/// but non-ASCII letters are unchanged.
///
/// To return a new uppercased value without modifying the existing one, use
/// [`to_ascii_uppercase`].
///
/// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn make_ascii_uppercase(&mut self) {
for byte in self {
byte.make_ascii_uppercase();
}
}
/// Converts this slice to its ASCII lower case equivalent in-place.
///
/// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
/// but non-ASCII letters are unchanged.
///
/// To return a new lowercased value without modifying the existing one, use
/// [`to_ascii_lowercase`].
///
/// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn make_ascii_lowercase(&mut self) {
for byte in self {
byte.make_ascii_lowercase();
}
}
/// Returns an iterator that produces an escaped version of this slice,
/// treating it as an ASCII string.
///
/// # Examples
///
/// ```
/// #![feature(inherent_ascii_escape)]
///
/// let s = b"0\t\r\n'\"\\\x9d";
/// let escaped = s.escape_ascii().to_string();
/// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
/// ```
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
pub fn escape_ascii(&self) -> EscapeAscii<'_> {
EscapeAscii { inner: self.iter().flat_map(EscapeByte) }
}
}
impl_fn_for_zst! {
#[derive(Clone)]
struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
ascii::escape_default(*byte)
};
}
/// An iterator over the escaped version of a byte slice.
///
/// This `struct` is created by the [`slice::escape_ascii`] method. See its
/// documentation for more information.
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
#[derive(Clone)]
pub struct EscapeAscii<'a> {
inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::Iterator for EscapeAscii<'a> {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
self.inner.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
#[inline]
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Fold: FnMut(Acc, Self::Item) -> R,
R: ops::Try<Output = Acc>,
{
self.inner.try_fold(init, fold)
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.inner.fold(init, fold)
}
#[inline]
fn last(mut self) -> Option<u8> {
self.next_back()
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::DoubleEndedIterator for EscapeAscii<'a> {
fn
|
(&mut self) -> Option<u8> {
self.inner.next_back()
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::ExactSizeIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Display for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.clone().try_for_each(|b| f.write_char(b as char))
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Debug for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EscapeAscii").finish_non_exhaustive()
}
}
/// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
/// from `../str/mod.rs`, which does something similar for utf8 validation.
#[inline]
fn contains_nonascii(v: usize) -> bool {
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
(NONASCII_MASK & v)!= 0
}
/// Optimized ASCII test that will use usize-at-a-time operations instead of
/// byte-at-a-time operations (when possible).
///
/// The algorithm we use here is pretty simple. If `s` is too short, we just
/// check each byte and be done with it. Otherwise:
///
/// - Read the first word with an unaligned load.
/// - Align the pointer, read subsequent words until end with aligned loads.
/// - Read the last `usize` from `s` with an unaligned load.
///
/// If any of these loads produces something for which `contains_nonascii`
/// (above) returns true, then we know the answer is false.
#[inline]
fn is_ascii(s: &[u8]) -> bool {
const USIZE_SIZE: usize = mem::size_of::<usize>();
let len = s.len();
let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
// If we wouldn't gain anything from the word-at-a-time implementation, fall
// back to a scalar loop.
//
// We also do this for architectures where `size_of::<usize>()` isn't
// sufficient alignment for `usize`, because it's a weird edge case.
if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>() {
return s.iter().all(|b| b.is_ascii());
}
// We always read the first word unaligned, which means `align_offset` is
// 0, we'd read the same value again for the aligned read.
let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
let start = s.as_ptr();
// SAFETY: We verify `len < USIZE_SIZE` above.
let first_word = unsafe { (start as *const usize).read_unaligned() };
if contains_nonascii(first_word) {
return false;
}
// We checked this above, somewhat implicitly. Note that `offset_to_aligned`
// is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
// above.
debug_assert!(offset_to_aligned <= len);
// SAFETY: word_ptr is the (properly aligned) usize ptr we use to read the
// middle chunk of the slice.
let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
// `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
let mut byte_pos = offset_to_aligned;
// Paranoia check about alignment, since we're about to do a bunch of
// unaligned loads. In practice this should be impossible barring a bug in
// `align_offset` though.
debug_assert_eq!((word_ptr as usize) % mem::align_of::<usize>(), 0);
// Read subsequent words until the last aligned word, excluding the last
// aligned word by itself to be done in tail check later, to ensure that
// tail is always one `usize` at most to extra branch `byte_pos == len`.
while byte_pos < len - USIZE_SIZE {
debug_assert!(
// Sanity check that the read is in bounds
(word_ptr as usize + USIZE_SIZE) <= (start.wrapping_add(len) as usize) &&
// And that our assumptions about `byte_pos` hold.
(word_ptr as usize) - (start as usize) == byte_pos
);
// SAFETY: We know `word_ptr` is properly aligned (because of
// `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
let word = unsafe { word_ptr.read() };
if contains_nonascii(word) {
return false;
}
byte_pos += USIZE_SIZE;
// SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
// after this `add`, `word_ptr` will be at most one-past-the-end.
word_ptr = unsafe { word_ptr.add(1) };
}
// Sanity check to ensure there really is only one `usize` left. This should
// be guaranteed by our loop condition.
debug_assert!(byte_pos <= len && len - byte_pos <= USIZE_SIZE);
// SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
!contains_nonascii(last_word)
}
|
next_back
|
identifier_name
|
ascii.rs
|
//! Operations on ASCII `[u8]`.
use crate::ascii;
use crate::fmt::{self, Write};
use crate::iter;
use crate::mem;
use crate::ops;
#[lang = "slice_u8"]
#[cfg(not(test))]
impl [u8] {
/// Checks if all bytes in this slice are within the ASCII range.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn is_ascii(&self) -> bool {
is_ascii(self)
}
/// Checks that two slices are an ASCII case-insensitive match.
///
/// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
/// but without allocating and copying temporaries.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
self.len() == other.len() && iter::zip(self, other).all(|(a, b)| a.eq_ignore_ascii_case(b))
}
/// Converts this slice to its ASCII upper case equivalent in-place.
///
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
/// but non-ASCII letters are unchanged.
///
/// To return a new uppercased value without modifying the existing one, use
/// [`to_ascii_uppercase`].
///
/// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn make_ascii_uppercase(&mut self) {
for byte in self {
byte.make_ascii_uppercase();
}
}
/// Converts this slice to its ASCII lower case equivalent in-place.
///
/// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
/// but non-ASCII letters are unchanged.
///
/// To return a new lowercased value without modifying the existing one, use
/// [`to_ascii_lowercase`].
///
/// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn make_ascii_lowercase(&mut self) {
for byte in self {
byte.make_ascii_lowercase();
}
}
/// Returns an iterator that produces an escaped version of this slice,
/// treating it as an ASCII string.
///
/// # Examples
///
/// ```
/// #![feature(inherent_ascii_escape)]
///
/// let s = b"0\t\r\n'\"\\\x9d";
/// let escaped = s.escape_ascii().to_string();
/// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
/// ```
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
pub fn escape_ascii(&self) -> EscapeAscii<'_> {
EscapeAscii { inner: self.iter().flat_map(EscapeByte) }
}
}
impl_fn_for_zst! {
#[derive(Clone)]
struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
ascii::escape_default(*byte)
};
}
/// An iterator over the escaped version of a byte slice.
///
/// This `struct` is created by the [`slice::escape_ascii`] method. See its
/// documentation for more information.
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
#[derive(Clone)]
pub struct EscapeAscii<'a> {
inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::Iterator for EscapeAscii<'a> {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
self.inner.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
#[inline]
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Fold: FnMut(Acc, Self::Item) -> R,
R: ops::Try<Output = Acc>,
{
self.inner.try_fold(init, fold)
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.inner.fold(init, fold)
}
#[inline]
fn last(mut self) -> Option<u8> {
self.next_back()
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::DoubleEndedIterator for EscapeAscii<'a> {
fn next_back(&mut self) -> Option<u8> {
self.inner.next_back()
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::ExactSizeIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Display for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.clone().try_for_each(|b| f.write_char(b as char))
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Debug for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EscapeAscii").finish_non_exhaustive()
}
}
/// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
/// from `../str/mod.rs`, which does something similar for utf8 validation.
#[inline]
fn contains_nonascii(v: usize) -> bool {
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
(NONASCII_MASK & v)!= 0
}
/// Optimized ASCII test that will use usize-at-a-time operations instead of
/// byte-at-a-time operations (when possible).
///
/// The algorithm we use here is pretty simple. If `s` is too short, we just
/// check each byte and be done with it. Otherwise:
///
/// - Read the first word with an unaligned load.
/// - Align the pointer, read subsequent words until end with aligned loads.
/// - Read the last `usize` from `s` with an unaligned load.
///
/// If any of these loads produces something for which `contains_nonascii`
/// (above) returns true, then we know the answer is false.
#[inline]
fn is_ascii(s: &[u8]) -> bool {
const USIZE_SIZE: usize = mem::size_of::<usize>();
let len = s.len();
let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
// If we wouldn't gain anything from the word-at-a-time implementation, fall
// back to a scalar loop.
//
// We also do this for architectures where `size_of::<usize>()` isn't
// sufficient alignment for `usize`, because it's a weird edge case.
if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>()
|
// We always read the first word unaligned, which means `align_offset` is
// 0, we'd read the same value again for the aligned read.
let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
let start = s.as_ptr();
// SAFETY: We verify `len < USIZE_SIZE` above.
let first_word = unsafe { (start as *const usize).read_unaligned() };
if contains_nonascii(first_word) {
return false;
}
// We checked this above, somewhat implicitly. Note that `offset_to_aligned`
// is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
// above.
debug_assert!(offset_to_aligned <= len);
// SAFETY: word_ptr is the (properly aligned) usize ptr we use to read the
// middle chunk of the slice.
let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
// `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
let mut byte_pos = offset_to_aligned;
// Paranoia check about alignment, since we're about to do a bunch of
// unaligned loads. In practice this should be impossible barring a bug in
// `align_offset` though.
debug_assert_eq!((word_ptr as usize) % mem::align_of::<usize>(), 0);
// Read subsequent words until the last aligned word, excluding the last
// aligned word by itself to be done in tail check later, to ensure that
// tail is always one `usize` at most to extra branch `byte_pos == len`.
while byte_pos < len - USIZE_SIZE {
debug_assert!(
// Sanity check that the read is in bounds
(word_ptr as usize + USIZE_SIZE) <= (start.wrapping_add(len) as usize) &&
// And that our assumptions about `byte_pos` hold.
(word_ptr as usize) - (start as usize) == byte_pos
);
// SAFETY: We know `word_ptr` is properly aligned (because of
// `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
let word = unsafe { word_ptr.read() };
if contains_nonascii(word) {
return false;
}
byte_pos += USIZE_SIZE;
// SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
// after this `add`, `word_ptr` will be at most one-past-the-end.
word_ptr = unsafe { word_ptr.add(1) };
}
// Sanity check to ensure there really is only one `usize` left. This should
// be guaranteed by our loop condition.
debug_assert!(byte_pos <= len && len - byte_pos <= USIZE_SIZE);
// SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
!contains_nonascii(last_word)
}
|
{
return s.iter().all(|b| b.is_ascii());
}
|
conditional_block
|
ascii.rs
|
//! Operations on ASCII `[u8]`.
use crate::ascii;
use crate::fmt::{self, Write};
use crate::iter;
use crate::mem;
use crate::ops;
#[lang = "slice_u8"]
#[cfg(not(test))]
impl [u8] {
/// Checks if all bytes in this slice are within the ASCII range.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn is_ascii(&self) -> bool {
is_ascii(self)
}
/// Checks that two slices are an ASCII case-insensitive match.
///
/// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
/// but without allocating and copying temporaries.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
self.len() == other.len() && iter::zip(self, other).all(|(a, b)| a.eq_ignore_ascii_case(b))
}
/// Converts this slice to its ASCII upper case equivalent in-place.
///
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
/// but non-ASCII letters are unchanged.
///
/// To return a new uppercased value without modifying the existing one, use
/// [`to_ascii_uppercase`].
///
/// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn make_ascii_uppercase(&mut self) {
for byte in self {
byte.make_ascii_uppercase();
}
}
/// Converts this slice to its ASCII lower case equivalent in-place.
///
/// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
/// but non-ASCII letters are unchanged.
///
/// To return a new lowercased value without modifying the existing one, use
/// [`to_ascii_lowercase`].
///
/// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn make_ascii_lowercase(&mut self) {
for byte in self {
byte.make_ascii_lowercase();
}
}
/// Returns an iterator that produces an escaped version of this slice,
/// treating it as an ASCII string.
///
/// # Examples
///
/// ```
/// #![feature(inherent_ascii_escape)]
///
/// let s = b"0\t\r\n'\"\\\x9d";
/// let escaped = s.escape_ascii().to_string();
/// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
/// ```
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
pub fn escape_ascii(&self) -> EscapeAscii<'_> {
EscapeAscii { inner: self.iter().flat_map(EscapeByte) }
}
}
impl_fn_for_zst! {
#[derive(Clone)]
struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
ascii::escape_default(*byte)
};
}
/// An iterator over the escaped version of a byte slice.
///
/// This `struct` is created by the [`slice::escape_ascii`] method. See its
/// documentation for more information.
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
#[derive(Clone)]
pub struct EscapeAscii<'a> {
inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::Iterator for EscapeAscii<'a> {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
self.inner.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
#[inline]
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Fold: FnMut(Acc, Self::Item) -> R,
R: ops::Try<Output = Acc>,
{
self.inner.try_fold(init, fold)
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.inner.fold(init, fold)
}
#[inline]
fn last(mut self) -> Option<u8> {
self.next_back()
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::DoubleEndedIterator for EscapeAscii<'a> {
fn next_back(&mut self) -> Option<u8>
|
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::ExactSizeIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Display for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.clone().try_for_each(|b| f.write_char(b as char))
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Debug for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EscapeAscii").finish_non_exhaustive()
}
}
/// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
/// from `../str/mod.rs`, which does something similar for utf8 validation.
#[inline]
fn contains_nonascii(v: usize) -> bool {
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
(NONASCII_MASK & v)!= 0
}
/// Optimized ASCII test that will use usize-at-a-time operations instead of
/// byte-at-a-time operations (when possible).
///
/// The algorithm we use here is pretty simple. If `s` is too short, we just
/// check each byte and be done with it. Otherwise:
///
/// - Read the first word with an unaligned load.
/// - Align the pointer, read subsequent words until end with aligned loads.
/// - Read the last `usize` from `s` with an unaligned load.
///
/// If any of these loads produces something for which `contains_nonascii`
/// (above) returns true, then we know the answer is false.
#[inline]
fn is_ascii(s: &[u8]) -> bool {
const USIZE_SIZE: usize = mem::size_of::<usize>();
let len = s.len();
let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
// If we wouldn't gain anything from the word-at-a-time implementation, fall
// back to a scalar loop.
//
// We also do this for architectures where `size_of::<usize>()` isn't
// sufficient alignment for `usize`, because it's a weird edge case.
if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>() {
return s.iter().all(|b| b.is_ascii());
}
// We always read the first word unaligned, which means `align_offset` is
// 0, we'd read the same value again for the aligned read.
let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
let start = s.as_ptr();
// SAFETY: We verify `len < USIZE_SIZE` above.
let first_word = unsafe { (start as *const usize).read_unaligned() };
if contains_nonascii(first_word) {
return false;
}
// We checked this above, somewhat implicitly. Note that `offset_to_aligned`
// is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
// above.
debug_assert!(offset_to_aligned <= len);
// SAFETY: word_ptr is the (properly aligned) usize ptr we use to read the
// middle chunk of the slice.
let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
// `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
let mut byte_pos = offset_to_aligned;
// Paranoia check about alignment, since we're about to do a bunch of
// unaligned loads. In practice this should be impossible barring a bug in
// `align_offset` though.
debug_assert_eq!((word_ptr as usize) % mem::align_of::<usize>(), 0);
// Read subsequent words until the last aligned word, excluding the last
// aligned word by itself to be done in tail check later, to ensure that
// tail is always one `usize` at most to extra branch `byte_pos == len`.
while byte_pos < len - USIZE_SIZE {
debug_assert!(
// Sanity check that the read is in bounds
(word_ptr as usize + USIZE_SIZE) <= (start.wrapping_add(len) as usize) &&
// And that our assumptions about `byte_pos` hold.
(word_ptr as usize) - (start as usize) == byte_pos
);
// SAFETY: We know `word_ptr` is properly aligned (because of
// `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
let word = unsafe { word_ptr.read() };
if contains_nonascii(word) {
return false;
}
byte_pos += USIZE_SIZE;
// SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
// after this `add`, `word_ptr` will be at most one-past-the-end.
word_ptr = unsafe { word_ptr.add(1) };
}
// Sanity check to ensure there really is only one `usize` left. This should
// be guaranteed by our loop condition.
debug_assert!(byte_pos <= len && len - byte_pos <= USIZE_SIZE);
// SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
!contains_nonascii(last_word)
}
|
{
self.inner.next_back()
}
|
identifier_body
|
ascii.rs
|
//! Operations on ASCII `[u8]`.
use crate::ascii;
use crate::fmt::{self, Write};
use crate::iter;
use crate::mem;
use crate::ops;
#[lang = "slice_u8"]
#[cfg(not(test))]
impl [u8] {
/// Checks if all bytes in this slice are within the ASCII range.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn is_ascii(&self) -> bool {
is_ascii(self)
}
/// Checks that two slices are an ASCII case-insensitive match.
///
/// Same as `to_ascii_lowercase(a) == to_ascii_lowercase(b)`,
/// but without allocating and copying temporaries.
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn eq_ignore_ascii_case(&self, other: &[u8]) -> bool {
self.len() == other.len() && iter::zip(self, other).all(|(a, b)| a.eq_ignore_ascii_case(b))
}
/// Converts this slice to its ASCII upper case equivalent in-place.
///
/// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
/// but non-ASCII letters are unchanged.
///
/// To return a new uppercased value without modifying the existing one, use
/// [`to_ascii_uppercase`].
///
/// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn make_ascii_uppercase(&mut self) {
for byte in self {
byte.make_ascii_uppercase();
}
|
/// Converts this slice to its ASCII lower case equivalent in-place.
///
/// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
/// but non-ASCII letters are unchanged.
///
/// To return a new lowercased value without modifying the existing one, use
/// [`to_ascii_lowercase`].
///
/// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
#[inline]
pub fn make_ascii_lowercase(&mut self) {
for byte in self {
byte.make_ascii_lowercase();
}
}
/// Returns an iterator that produces an escaped version of this slice,
/// treating it as an ASCII string.
///
/// # Examples
///
/// ```
/// #![feature(inherent_ascii_escape)]
///
/// let s = b"0\t\r\n'\"\\\x9d";
/// let escaped = s.escape_ascii().to_string();
/// assert_eq!(escaped, "0\\t\\r\\n\\'\\\"\\\\\\x9d");
/// ```
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
pub fn escape_ascii(&self) -> EscapeAscii<'_> {
EscapeAscii { inner: self.iter().flat_map(EscapeByte) }
}
}
impl_fn_for_zst! {
#[derive(Clone)]
struct EscapeByte impl Fn = |byte: &u8| -> ascii::EscapeDefault {
ascii::escape_default(*byte)
};
}
/// An iterator over the escaped version of a byte slice.
///
/// This `struct` is created by the [`slice::escape_ascii`] method. See its
/// documentation for more information.
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
#[derive(Clone)]
pub struct EscapeAscii<'a> {
inner: iter::FlatMap<super::Iter<'a, u8>, ascii::EscapeDefault, EscapeByte>,
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::Iterator for EscapeAscii<'a> {
type Item = u8;
#[inline]
fn next(&mut self) -> Option<u8> {
self.inner.next()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.inner.size_hint()
}
#[inline]
fn try_fold<Acc, Fold, R>(&mut self, init: Acc, fold: Fold) -> R
where
Fold: FnMut(Acc, Self::Item) -> R,
R: ops::Try<Output = Acc>,
{
self.inner.try_fold(init, fold)
}
#[inline]
fn fold<Acc, Fold>(self, init: Acc, fold: Fold) -> Acc
where
Fold: FnMut(Acc, Self::Item) -> Acc,
{
self.inner.fold(init, fold)
}
#[inline]
fn last(mut self) -> Option<u8> {
self.next_back()
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::DoubleEndedIterator for EscapeAscii<'a> {
fn next_back(&mut self) -> Option<u8> {
self.inner.next_back()
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::ExactSizeIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> iter::FusedIterator for EscapeAscii<'a> {}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Display for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.clone().try_for_each(|b| f.write_char(b as char))
}
}
#[unstable(feature = "inherent_ascii_escape", issue = "77174")]
impl<'a> fmt::Debug for EscapeAscii<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("EscapeAscii").finish_non_exhaustive()
}
}
/// Returns `true` if any byte in the word `v` is nonascii (>= 128). Snarfed
/// from `../str/mod.rs`, which does something similar for utf8 validation.
#[inline]
fn contains_nonascii(v: usize) -> bool {
const NONASCII_MASK: usize = 0x80808080_80808080u64 as usize;
(NONASCII_MASK & v)!= 0
}
/// Optimized ASCII test that will use usize-at-a-time operations instead of
/// byte-at-a-time operations (when possible).
///
/// The algorithm we use here is pretty simple. If `s` is too short, we just
/// check each byte and be done with it. Otherwise:
///
/// - Read the first word with an unaligned load.
/// - Align the pointer, read subsequent words until end with aligned loads.
/// - Read the last `usize` from `s` with an unaligned load.
///
/// If any of these loads produces something for which `contains_nonascii`
/// (above) returns true, then we know the answer is false.
#[inline]
fn is_ascii(s: &[u8]) -> bool {
const USIZE_SIZE: usize = mem::size_of::<usize>();
let len = s.len();
let align_offset = s.as_ptr().align_offset(USIZE_SIZE);
// If we wouldn't gain anything from the word-at-a-time implementation, fall
// back to a scalar loop.
//
// We also do this for architectures where `size_of::<usize>()` isn't
// sufficient alignment for `usize`, because it's a weird edge case.
if len < USIZE_SIZE || len < align_offset || USIZE_SIZE < mem::align_of::<usize>() {
return s.iter().all(|b| b.is_ascii());
}
// We always read the first word unaligned, which means `align_offset` is
// 0, we'd read the same value again for the aligned read.
let offset_to_aligned = if align_offset == 0 { USIZE_SIZE } else { align_offset };
let start = s.as_ptr();
// SAFETY: We verify `len < USIZE_SIZE` above.
let first_word = unsafe { (start as *const usize).read_unaligned() };
if contains_nonascii(first_word) {
return false;
}
// We checked this above, somewhat implicitly. Note that `offset_to_aligned`
// is either `align_offset` or `USIZE_SIZE`, both of are explicitly checked
// above.
debug_assert!(offset_to_aligned <= len);
// SAFETY: word_ptr is the (properly aligned) usize ptr we use to read the
// middle chunk of the slice.
let mut word_ptr = unsafe { start.add(offset_to_aligned) as *const usize };
// `byte_pos` is the byte index of `word_ptr`, used for loop end checks.
let mut byte_pos = offset_to_aligned;
// Paranoia check about alignment, since we're about to do a bunch of
// unaligned loads. In practice this should be impossible barring a bug in
// `align_offset` though.
debug_assert_eq!((word_ptr as usize) % mem::align_of::<usize>(), 0);
// Read subsequent words until the last aligned word, excluding the last
// aligned word by itself to be done in tail check later, to ensure that
// tail is always one `usize` at most to extra branch `byte_pos == len`.
while byte_pos < len - USIZE_SIZE {
debug_assert!(
// Sanity check that the read is in bounds
(word_ptr as usize + USIZE_SIZE) <= (start.wrapping_add(len) as usize) &&
// And that our assumptions about `byte_pos` hold.
(word_ptr as usize) - (start as usize) == byte_pos
);
// SAFETY: We know `word_ptr` is properly aligned (because of
// `align_offset`), and we know that we have enough bytes between `word_ptr` and the end
let word = unsafe { word_ptr.read() };
if contains_nonascii(word) {
return false;
}
byte_pos += USIZE_SIZE;
// SAFETY: We know that `byte_pos <= len - USIZE_SIZE`, which means that
// after this `add`, `word_ptr` will be at most one-past-the-end.
word_ptr = unsafe { word_ptr.add(1) };
}
// Sanity check to ensure there really is only one `usize` left. This should
// be guaranteed by our loop condition.
debug_assert!(byte_pos <= len && len - byte_pos <= USIZE_SIZE);
// SAFETY: This relies on `len >= USIZE_SIZE`, which we check at the start.
let last_word = unsafe { (start.add(len - USIZE_SIZE) as *const usize).read_unaligned() };
!contains_nonascii(last_word)
}
|
}
|
random_line_split
|
gamepadevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindings::GamepadEventBinding;
use crate::dom::bindings::codegen::Bindings::GamepadEventBinding::GamepadEventMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::event::Event;
use crate::dom::gamepad::Gamepad;
use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct GamepadEvent {
event: Event,
gamepad: Dom<Gamepad>,
}
pub enum GamepadEventType {
Connected,
Disconnected,
}
impl GamepadEvent {
fn new_inherited(gamepad: &Gamepad) -> GamepadEvent {
GamepadEvent {
event: Event::new_inherited(),
gamepad: Dom::from_ref(gamepad),
}
}
pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: bool,
cancelable: bool,
gamepad: &Gamepad,
) -> DomRoot<GamepadEvent> {
let ev = reflect_dom_object(Box::new(GamepadEvent::new_inherited(&gamepad)), global);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
ev
}
pub fn new_with_type(
global: &GlobalScope,
event_type: GamepadEventType,
gamepad: &Gamepad,
) -> DomRoot<GamepadEvent> {
let name = match event_type {
GamepadEventType::Connected => "gamepadconnected",
GamepadEventType::Disconnected => "gamepaddisconnected",
};
GamepadEvent::new(&global, name.into(), false, false, &gamepad)
}
// https://w3c.github.io/gamepad/#gamepadevent-interface
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
type_: DOMString,
|
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
&init.gamepad,
))
}
}
impl GamepadEventMethods for GamepadEvent {
// https://w3c.github.io/gamepad/#gamepadevent-interface
fn Gamepad(&self) -> DomRoot<Gamepad> {
DomRoot::from_ref(&*self.gamepad)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
|
init: &GamepadEventBinding::GamepadEventInit,
) -> Fallible<DomRoot<GamepadEvent>> {
Ok(GamepadEvent::new(
&window.global(),
|
random_line_split
|
gamepadevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindings::GamepadEventBinding;
use crate::dom::bindings::codegen::Bindings::GamepadEventBinding::GamepadEventMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::event::Event;
use crate::dom::gamepad::Gamepad;
use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct GamepadEvent {
event: Event,
gamepad: Dom<Gamepad>,
}
pub enum GamepadEventType {
Connected,
Disconnected,
}
impl GamepadEvent {
fn
|
(gamepad: &Gamepad) -> GamepadEvent {
GamepadEvent {
event: Event::new_inherited(),
gamepad: Dom::from_ref(gamepad),
}
}
pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: bool,
cancelable: bool,
gamepad: &Gamepad,
) -> DomRoot<GamepadEvent> {
let ev = reflect_dom_object(Box::new(GamepadEvent::new_inherited(&gamepad)), global);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
ev
}
pub fn new_with_type(
global: &GlobalScope,
event_type: GamepadEventType,
gamepad: &Gamepad,
) -> DomRoot<GamepadEvent> {
let name = match event_type {
GamepadEventType::Connected => "gamepadconnected",
GamepadEventType::Disconnected => "gamepaddisconnected",
};
GamepadEvent::new(&global, name.into(), false, false, &gamepad)
}
// https://w3c.github.io/gamepad/#gamepadevent-interface
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
type_: DOMString,
init: &GamepadEventBinding::GamepadEventInit,
) -> Fallible<DomRoot<GamepadEvent>> {
Ok(GamepadEvent::new(
&window.global(),
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
&init.gamepad,
))
}
}
impl GamepadEventMethods for GamepadEvent {
// https://w3c.github.io/gamepad/#gamepadevent-interface
fn Gamepad(&self) -> DomRoot<Gamepad> {
DomRoot::from_ref(&*self.gamepad)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
|
new_inherited
|
identifier_name
|
gamepadevent.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods;
use crate::dom::bindings::codegen::Bindings::GamepadEventBinding;
use crate::dom::bindings::codegen::Bindings::GamepadEventBinding::GamepadEventMethods;
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::event::Event;
use crate::dom::gamepad::Gamepad;
use crate::dom::globalscope::GlobalScope;
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_atoms::Atom;
#[dom_struct]
pub struct GamepadEvent {
event: Event,
gamepad: Dom<Gamepad>,
}
pub enum GamepadEventType {
Connected,
Disconnected,
}
impl GamepadEvent {
fn new_inherited(gamepad: &Gamepad) -> GamepadEvent {
GamepadEvent {
event: Event::new_inherited(),
gamepad: Dom::from_ref(gamepad),
}
}
pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: bool,
cancelable: bool,
gamepad: &Gamepad,
) -> DomRoot<GamepadEvent>
|
pub fn new_with_type(
global: &GlobalScope,
event_type: GamepadEventType,
gamepad: &Gamepad,
) -> DomRoot<GamepadEvent> {
let name = match event_type {
GamepadEventType::Connected => "gamepadconnected",
GamepadEventType::Disconnected => "gamepaddisconnected",
};
GamepadEvent::new(&global, name.into(), false, false, &gamepad)
}
// https://w3c.github.io/gamepad/#gamepadevent-interface
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
type_: DOMString,
init: &GamepadEventBinding::GamepadEventInit,
) -> Fallible<DomRoot<GamepadEvent>> {
Ok(GamepadEvent::new(
&window.global(),
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
&init.gamepad,
))
}
}
impl GamepadEventMethods for GamepadEvent {
// https://w3c.github.io/gamepad/#gamepadevent-interface
fn Gamepad(&self) -> DomRoot<Gamepad> {
DomRoot::from_ref(&*self.gamepad)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
|
{
let ev = reflect_dom_object(Box::new(GamepadEvent::new_inherited(&gamepad)), global);
{
let event = ev.upcast::<Event>();
event.init_event(type_, bubbles, cancelable);
}
ev
}
|
identifier_body
|
htmlstyleelement.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::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLStyleElementDerived, NodeCast};
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node};
use dom::virtualmethods::VirtualMethods;
use layout_interface::{LayoutChan, Msg};
use util::str::DOMString;
use style::stylesheets::{Origin, Stylesheet};
#[dom_struct]
pub struct HTMLStyleElement {
htmlelement: HTMLElement,
}
impl HTMLStyleElementDerived for EventTarget {
fn is_htmlstyleelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLStyleElement)))
}
}
impl HTMLStyleElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLStyleElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn
|
(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLStyleElement> {
let element = HTMLStyleElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLStyleElementBinding::Wrap)
}
}
pub trait StyleElementHelpers {
fn parse_own_css(self);
}
impl<'a> StyleElementHelpers for JSRef<'a, HTMLStyleElement> {
fn parse_own_css(self) {
let node: JSRef<Node> = NodeCast::from_ref(self);
assert!(node.is_in_doc());
let win = window_from_node(node).root();
let win = win.r();
let url = win.page().get_url();
let data = node.GetTextContent().expect("Element.textContent must be a string");
let sheet = Stylesheet::from_str(data.as_slice(), url, Origin::Author);
let LayoutChan(ref layout_chan) = win.page().layout_chan;
layout_chan.send(Msg::AddStylesheet(sheet)).unwrap();
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLStyleElement> {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn child_inserted(&self, child: JSRef<Node>) {
match self.super_type() {
Some(ref s) => s.child_inserted(child),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => ()
}
if tree_in_doc {
self.parse_own_css();
}
}
}
|
new
|
identifier_name
|
htmlstyleelement.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::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLStyleElementDerived, NodeCast};
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node};
use dom::virtualmethods::VirtualMethods;
use layout_interface::{LayoutChan, Msg};
use util::str::DOMString;
use style::stylesheets::{Origin, Stylesheet};
#[dom_struct]
pub struct HTMLStyleElement {
htmlelement: HTMLElement,
}
impl HTMLStyleElementDerived for EventTarget {
fn is_htmlstyleelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLStyleElement)))
}
}
impl HTMLStyleElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLStyleElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLStyleElement> {
let element = HTMLStyleElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLStyleElementBinding::Wrap)
}
}
pub trait StyleElementHelpers {
fn parse_own_css(self);
}
impl<'a> StyleElementHelpers for JSRef<'a, HTMLStyleElement> {
fn parse_own_css(self) {
let node: JSRef<Node> = NodeCast::from_ref(self);
assert!(node.is_in_doc());
let win = window_from_node(node).root();
let win = win.r();
let url = win.page().get_url();
let data = node.GetTextContent().expect("Element.textContent must be a string");
let sheet = Stylesheet::from_str(data.as_slice(), url, Origin::Author);
let LayoutChan(ref layout_chan) = win.page().layout_chan;
layout_chan.send(Msg::AddStylesheet(sheet)).unwrap();
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLStyleElement> {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods>
|
fn child_inserted(&self, child: JSRef<Node>) {
match self.super_type() {
Some(ref s) => s.child_inserted(child),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => ()
}
if tree_in_doc {
self.parse_own_css();
}
}
}
|
{
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
|
identifier_body
|
htmlstyleelement.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::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLStyleElementDerived, NodeCast};
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node};
use dom::virtualmethods::VirtualMethods;
use layout_interface::{LayoutChan, Msg};
use util::str::DOMString;
use style::stylesheets::{Origin, Stylesheet};
#[dom_struct]
pub struct HTMLStyleElement {
htmlelement: HTMLElement,
}
impl HTMLStyleElementDerived for EventTarget {
fn is_htmlstyleelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLStyleElement)))
}
}
impl HTMLStyleElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLStyleElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLStyleElement> {
let element = HTMLStyleElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLStyleElementBinding::Wrap)
}
}
pub trait StyleElementHelpers {
fn parse_own_css(self);
}
impl<'a> StyleElementHelpers for JSRef<'a, HTMLStyleElement> {
fn parse_own_css(self) {
let node: JSRef<Node> = NodeCast::from_ref(self);
assert!(node.is_in_doc());
let win = window_from_node(node).root();
let win = win.r();
let url = win.page().get_url();
let data = node.GetTextContent().expect("Element.textContent must be a string");
let sheet = Stylesheet::from_str(data.as_slice(), url, Origin::Author);
let LayoutChan(ref layout_chan) = win.page().layout_chan;
layout_chan.send(Msg::AddStylesheet(sheet)).unwrap();
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLStyleElement> {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn child_inserted(&self, child: JSRef<Node>) {
match self.super_type() {
Some(ref s) => s.child_inserted(child),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => ()
}
if tree_in_doc
|
}
}
|
{
self.parse_own_css();
}
|
conditional_block
|
htmlstyleelement.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::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLStyleElementDerived, NodeCast};
use dom::bindings::js::{JSRef, Temporary};
use dom::document::Document;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId, window_from_node};
use dom::virtualmethods::VirtualMethods;
use layout_interface::{LayoutChan, Msg};
use util::str::DOMString;
use style::stylesheets::{Origin, Stylesheet};
#[dom_struct]
pub struct HTMLStyleElement {
htmlelement: HTMLElement,
}
impl HTMLStyleElementDerived for EventTarget {
fn is_htmlstyleelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLStyleElement)))
}
}
impl HTMLStyleElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLStyleElement {
|
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLStyleElement> {
let element = HTMLStyleElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLStyleElementBinding::Wrap)
}
}
pub trait StyleElementHelpers {
fn parse_own_css(self);
}
impl<'a> StyleElementHelpers for JSRef<'a, HTMLStyleElement> {
fn parse_own_css(self) {
let node: JSRef<Node> = NodeCast::from_ref(self);
assert!(node.is_in_doc());
let win = window_from_node(node).root();
let win = win.r();
let url = win.page().get_url();
let data = node.GetTextContent().expect("Element.textContent must be a string");
let sheet = Stylesheet::from_str(data.as_slice(), url, Origin::Author);
let LayoutChan(ref layout_chan) = win.page().layout_chan;
layout_chan.send(Msg::AddStylesheet(sheet)).unwrap();
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLStyleElement> {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn child_inserted(&self, child: JSRef<Node>) {
match self.super_type() {
Some(ref s) => s.child_inserted(child),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if node.is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => ()
}
if tree_in_doc {
self.parse_own_css();
}
}
}
|
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLStyleElement, localName, prefix, document)
}
|
random_line_split
|
font_template.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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use servo_atoms::Atom;
use std::fmt::{Debug, Error, Formatter};
use std::io::Error as IoError;
use std::sync::{Arc, Weak};
use std::u32;
use style::computed_values::font_stretch::T as FontStretch;
use style::computed_values::font_style::T as FontStyle;
use style::properties::style_structs::Font as FontStyleStruct;
use style::values::computed::font::FontWeight;
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Serialize)]
pub struct FontTemplateDescriptor {
pub weight: FontWeight,
pub stretch: FontStretch,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: FontWeight, stretch: FontStretch, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
/// Returns a score indicating how far apart visually the two font descriptors are. This is
/// used for fuzzy font selection.
///
/// The smaller the score, the better the fonts match. 0 indicates an exact match. This must
/// be commutative (distance(A, B) == distance(B, A)).
///
/// The policy is to care most about differences in italicness, then weight, then stretch
#[inline]
fn distance_from(&self, other: &FontTemplateDescriptor) -> u32 {
let italic_part = if self.italic == other.italic { 0 } else { 1000 };
// 0 <= weightPart <= 800
let weight_part = ((self.weight.0 as i16) - (other.weight.0 as i16)).abs() as u32;
// 0 <= stretchPart <= 8
let stretch_part = (self.stretch_number() - other.stretch_number()).abs() as u32;
italic_part + weight_part + stretch_part
}
/// Returns a number between 1 and 9 for the stretch property.
/// 1 is ultra_condensed, 5 is normal, and 9 is ultra_expanded
#[inline]
fn stretch_number(&self) -> i32 {
match self.stretch {
FontStretch::UltraCondensed => 1,
FontStretch::ExtraCondensed => 2,
FontStretch::Condensed => 3,
FontStretch::SemiCondensed => 4,
FontStretch::Normal => 5,
FontStretch::SemiExpanded => 6,
FontStretch::Expanded => 7,
FontStretch::ExtraExpanded => 8,
FontStretch::UltraExpanded => 9,
}
}
}
impl<'a> From<&'a FontStyleStruct> for FontTemplateDescriptor {
fn from(style: &'a FontStyleStruct) -> Self {
FontTemplateDescriptor {
weight: style.font_weight,
stretch: style.font_stretch,
italic: style.font_style == FontStyle::Italic || style.font_style == FontStyle::Oblique,
}
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight == other.weight && self.stretch == other.stretch && self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
impl Debug for FontTemplate {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
self.identifier.fmt(f)
}
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> Result<FontTemplate, IoError> {
let maybe_data = match maybe_bytes {
Some(_) => Some(FontTemplateData::new(identifier.clone(), maybe_bytes)?),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(Arc::downgrade(strong_ref)),
None => None,
};
Ok(FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
})
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the descriptor. Returns `None` when instantiating the data fails.
pub fn descriptor(&mut self, font_context: &FontContextHandle) -> Option<FontTemplateDescriptor> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
self.descriptor.or_else(|| {
if self.instantiate(font_context).is_err() {
return None
};
Some(self.descriptor.expect("Instantiation succeeded but no descriptor?"))
})
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn data_for_descriptor(&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> {
self.descriptor(&fctx).and_then(|descriptor| {
if *requested_desc == descriptor {
self.data().ok()
} else {
None
}
})
}
/// Returns the font data along with the distance between this font's descriptor and the given
/// descriptor, if the font can be loaded.
pub fn data_for_approximate_descriptor(&mut self,
font_context: &FontContextHandle,
requested_descriptor: &FontTemplateDescriptor)
-> Option<(Arc<FontTemplateData>, u32)> {
self.descriptor(&font_context).and_then(|descriptor| {
self.data().ok().map(|data| {
(data, descriptor.distance_from(requested_descriptor))
})
})
}
fn instantiate(&mut self, font_context: &FontContextHandle) -> Result<(), ()> {
if!self.is_valid {
return Err(())
}
let data = self.data().map_err(|_| ())?;
let handle: Result<FontHandle, ()> = FontHandleMethods::new_from_template(font_context,
data,
None);
|
handle.is_italic()));
Ok(())
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
self.data().ok()
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn data(&mut self) -> Result<Arc<FontTemplateData>, IoError> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return Ok(data)
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(FontTemplateData::new(self.identifier.clone(), None)?);
self.weak_ref = Some(Arc::downgrade(&template_data));
Ok(template_data)
}
}
|
self.is_valid = handle.is_ok();
let handle = handle?;
self.descriptor = Some(FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
|
random_line_split
|
font_template.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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use servo_atoms::Atom;
use std::fmt::{Debug, Error, Formatter};
use std::io::Error as IoError;
use std::sync::{Arc, Weak};
use std::u32;
use style::computed_values::font_stretch::T as FontStretch;
use style::computed_values::font_style::T as FontStyle;
use style::properties::style_structs::Font as FontStyleStruct;
use style::values::computed::font::FontWeight;
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Serialize)]
pub struct FontTemplateDescriptor {
pub weight: FontWeight,
pub stretch: FontStretch,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: FontWeight, stretch: FontStretch, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
/// Returns a score indicating how far apart visually the two font descriptors are. This is
/// used for fuzzy font selection.
///
/// The smaller the score, the better the fonts match. 0 indicates an exact match. This must
/// be commutative (distance(A, B) == distance(B, A)).
///
/// The policy is to care most about differences in italicness, then weight, then stretch
#[inline]
fn distance_from(&self, other: &FontTemplateDescriptor) -> u32 {
let italic_part = if self.italic == other.italic { 0 } else { 1000 };
// 0 <= weightPart <= 800
let weight_part = ((self.weight.0 as i16) - (other.weight.0 as i16)).abs() as u32;
// 0 <= stretchPart <= 8
let stretch_part = (self.stretch_number() - other.stretch_number()).abs() as u32;
italic_part + weight_part + stretch_part
}
/// Returns a number between 1 and 9 for the stretch property.
/// 1 is ultra_condensed, 5 is normal, and 9 is ultra_expanded
#[inline]
fn stretch_number(&self) -> i32 {
match self.stretch {
FontStretch::UltraCondensed => 1,
FontStretch::ExtraCondensed => 2,
FontStretch::Condensed => 3,
FontStretch::SemiCondensed => 4,
FontStretch::Normal => 5,
FontStretch::SemiExpanded => 6,
FontStretch::Expanded => 7,
FontStretch::ExtraExpanded => 8,
FontStretch::UltraExpanded => 9,
}
}
}
impl<'a> From<&'a FontStyleStruct> for FontTemplateDescriptor {
fn from(style: &'a FontStyleStruct) -> Self {
FontTemplateDescriptor {
weight: style.font_weight,
stretch: style.font_stretch,
italic: style.font_style == FontStyle::Italic || style.font_style == FontStyle::Oblique,
}
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight == other.weight && self.stretch == other.stretch && self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
impl Debug for FontTemplate {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
self.identifier.fmt(f)
}
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> Result<FontTemplate, IoError> {
let maybe_data = match maybe_bytes {
Some(_) => Some(FontTemplateData::new(identifier.clone(), maybe_bytes)?),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(Arc::downgrade(strong_ref)),
None => None,
};
Ok(FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
})
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the descriptor. Returns `None` when instantiating the data fails.
pub fn descriptor(&mut self, font_context: &FontContextHandle) -> Option<FontTemplateDescriptor> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
self.descriptor.or_else(|| {
if self.instantiate(font_context).is_err() {
return None
};
Some(self.descriptor.expect("Instantiation succeeded but no descriptor?"))
})
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn data_for_descriptor(&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> {
self.descriptor(&fctx).and_then(|descriptor| {
if *requested_desc == descriptor {
self.data().ok()
} else
|
})
}
/// Returns the font data along with the distance between this font's descriptor and the given
/// descriptor, if the font can be loaded.
pub fn data_for_approximate_descriptor(&mut self,
font_context: &FontContextHandle,
requested_descriptor: &FontTemplateDescriptor)
-> Option<(Arc<FontTemplateData>, u32)> {
self.descriptor(&font_context).and_then(|descriptor| {
self.data().ok().map(|data| {
(data, descriptor.distance_from(requested_descriptor))
})
})
}
fn instantiate(&mut self, font_context: &FontContextHandle) -> Result<(), ()> {
if!self.is_valid {
return Err(())
}
let data = self.data().map_err(|_| ())?;
let handle: Result<FontHandle, ()> = FontHandleMethods::new_from_template(font_context,
data,
None);
self.is_valid = handle.is_ok();
let handle = handle?;
self.descriptor = Some(FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
handle.is_italic()));
Ok(())
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
self.data().ok()
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn data(&mut self) -> Result<Arc<FontTemplateData>, IoError> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return Ok(data)
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(FontTemplateData::new(self.identifier.clone(), None)?);
self.weak_ref = Some(Arc::downgrade(&template_data));
Ok(template_data)
}
}
|
{
None
}
|
conditional_block
|
font_template.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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use servo_atoms::Atom;
use std::fmt::{Debug, Error, Formatter};
use std::io::Error as IoError;
use std::sync::{Arc, Weak};
use std::u32;
use style::computed_values::font_stretch::T as FontStretch;
use style::computed_values::font_style::T as FontStyle;
use style::properties::style_structs::Font as FontStyleStruct;
use style::values::computed::font::FontWeight;
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Serialize)]
pub struct FontTemplateDescriptor {
pub weight: FontWeight,
pub stretch: FontStretch,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: FontWeight, stretch: FontStretch, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
/// Returns a score indicating how far apart visually the two font descriptors are. This is
/// used for fuzzy font selection.
///
/// The smaller the score, the better the fonts match. 0 indicates an exact match. This must
/// be commutative (distance(A, B) == distance(B, A)).
///
/// The policy is to care most about differences in italicness, then weight, then stretch
#[inline]
fn distance_from(&self, other: &FontTemplateDescriptor) -> u32 {
let italic_part = if self.italic == other.italic { 0 } else { 1000 };
// 0 <= weightPart <= 800
let weight_part = ((self.weight.0 as i16) - (other.weight.0 as i16)).abs() as u32;
// 0 <= stretchPart <= 8
let stretch_part = (self.stretch_number() - other.stretch_number()).abs() as u32;
italic_part + weight_part + stretch_part
}
/// Returns a number between 1 and 9 for the stretch property.
/// 1 is ultra_condensed, 5 is normal, and 9 is ultra_expanded
#[inline]
fn stretch_number(&self) -> i32 {
match self.stretch {
FontStretch::UltraCondensed => 1,
FontStretch::ExtraCondensed => 2,
FontStretch::Condensed => 3,
FontStretch::SemiCondensed => 4,
FontStretch::Normal => 5,
FontStretch::SemiExpanded => 6,
FontStretch::Expanded => 7,
FontStretch::ExtraExpanded => 8,
FontStretch::UltraExpanded => 9,
}
}
}
impl<'a> From<&'a FontStyleStruct> for FontTemplateDescriptor {
fn from(style: &'a FontStyleStruct) -> Self {
FontTemplateDescriptor {
weight: style.font_weight,
stretch: style.font_stretch,
italic: style.font_style == FontStyle::Italic || style.font_style == FontStyle::Oblique,
}
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight == other.weight && self.stretch == other.stretch && self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
impl Debug for FontTemplate {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
self.identifier.fmt(f)
}
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> Result<FontTemplate, IoError> {
let maybe_data = match maybe_bytes {
Some(_) => Some(FontTemplateData::new(identifier.clone(), maybe_bytes)?),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(Arc::downgrade(strong_ref)),
None => None,
};
Ok(FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
})
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the descriptor. Returns `None` when instantiating the data fails.
pub fn descriptor(&mut self, font_context: &FontContextHandle) -> Option<FontTemplateDescriptor> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
self.descriptor.or_else(|| {
if self.instantiate(font_context).is_err() {
return None
};
Some(self.descriptor.expect("Instantiation succeeded but no descriptor?"))
})
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn data_for_descriptor(&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> {
self.descriptor(&fctx).and_then(|descriptor| {
if *requested_desc == descriptor {
self.data().ok()
} else {
None
}
})
}
/// Returns the font data along with the distance between this font's descriptor and the given
/// descriptor, if the font can be loaded.
pub fn data_for_approximate_descriptor(&mut self,
font_context: &FontContextHandle,
requested_descriptor: &FontTemplateDescriptor)
-> Option<(Arc<FontTemplateData>, u32)> {
self.descriptor(&font_context).and_then(|descriptor| {
self.data().ok().map(|data| {
(data, descriptor.distance_from(requested_descriptor))
})
})
}
fn instantiate(&mut self, font_context: &FontContextHandle) -> Result<(), ()> {
if!self.is_valid {
return Err(())
}
let data = self.data().map_err(|_| ())?;
let handle: Result<FontHandle, ()> = FontHandleMethods::new_from_template(font_context,
data,
None);
self.is_valid = handle.is_ok();
let handle = handle?;
self.descriptor = Some(FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
handle.is_italic()));
Ok(())
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
self.data().ok()
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn
|
(&mut self) -> Result<Arc<FontTemplateData>, IoError> {
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return Ok(data)
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(FontTemplateData::new(self.identifier.clone(), None)?);
self.weak_ref = Some(Arc::downgrade(&template_data));
Ok(template_data)
}
}
|
data
|
identifier_name
|
font_template.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 font::FontHandleMethods;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;
use platform::font_template::FontTemplateData;
use servo_atoms::Atom;
use std::fmt::{Debug, Error, Formatter};
use std::io::Error as IoError;
use std::sync::{Arc, Weak};
use std::u32;
use style::computed_values::font_stretch::T as FontStretch;
use style::computed_values::font_style::T as FontStyle;
use style::properties::style_structs::Font as FontStyleStruct;
use style::values::computed::font::FontWeight;
/// Describes how to select a font from a given family. This is very basic at the moment and needs
/// to be expanded or refactored when we support more of the font styling parameters.
///
/// NB: If you change this, you will need to update `style::properties::compute_font_hash()`.
#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Serialize)]
pub struct FontTemplateDescriptor {
pub weight: FontWeight,
pub stretch: FontStretch,
pub italic: bool,
}
impl FontTemplateDescriptor {
#[inline]
pub fn new(weight: FontWeight, stretch: FontStretch, italic: bool)
-> FontTemplateDescriptor {
FontTemplateDescriptor {
weight: weight,
stretch: stretch,
italic: italic,
}
}
/// Returns a score indicating how far apart visually the two font descriptors are. This is
/// used for fuzzy font selection.
///
/// The smaller the score, the better the fonts match. 0 indicates an exact match. This must
/// be commutative (distance(A, B) == distance(B, A)).
///
/// The policy is to care most about differences in italicness, then weight, then stretch
#[inline]
fn distance_from(&self, other: &FontTemplateDescriptor) -> u32 {
let italic_part = if self.italic == other.italic { 0 } else { 1000 };
// 0 <= weightPart <= 800
let weight_part = ((self.weight.0 as i16) - (other.weight.0 as i16)).abs() as u32;
// 0 <= stretchPart <= 8
let stretch_part = (self.stretch_number() - other.stretch_number()).abs() as u32;
italic_part + weight_part + stretch_part
}
/// Returns a number between 1 and 9 for the stretch property.
/// 1 is ultra_condensed, 5 is normal, and 9 is ultra_expanded
#[inline]
fn stretch_number(&self) -> i32 {
match self.stretch {
FontStretch::UltraCondensed => 1,
FontStretch::ExtraCondensed => 2,
FontStretch::Condensed => 3,
FontStretch::SemiCondensed => 4,
FontStretch::Normal => 5,
FontStretch::SemiExpanded => 6,
FontStretch::Expanded => 7,
FontStretch::ExtraExpanded => 8,
FontStretch::UltraExpanded => 9,
}
}
}
impl<'a> From<&'a FontStyleStruct> for FontTemplateDescriptor {
fn from(style: &'a FontStyleStruct) -> Self {
FontTemplateDescriptor {
weight: style.font_weight,
stretch: style.font_stretch,
italic: style.font_style == FontStyle::Italic || style.font_style == FontStyle::Oblique,
}
}
}
impl PartialEq for FontTemplateDescriptor {
fn eq(&self, other: &FontTemplateDescriptor) -> bool {
self.weight == other.weight && self.stretch == other.stretch && self.italic == other.italic
}
}
/// This describes all the information needed to create
/// font instance handles. It contains a unique
/// FontTemplateData structure that is platform specific.
pub struct FontTemplate {
identifier: Atom,
descriptor: Option<FontTemplateDescriptor>,
weak_ref: Option<Weak<FontTemplateData>>,
// GWTODO: Add code path to unset the strong_ref for web fonts!
strong_ref: Option<Arc<FontTemplateData>>,
is_valid: bool,
}
impl Debug for FontTemplate {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
self.identifier.fmt(f)
}
}
/// Holds all of the template information for a font that
/// is common, regardless of the number of instances of
/// this font handle per thread.
impl FontTemplate {
pub fn new(identifier: Atom, maybe_bytes: Option<Vec<u8>>) -> Result<FontTemplate, IoError> {
let maybe_data = match maybe_bytes {
Some(_) => Some(FontTemplateData::new(identifier.clone(), maybe_bytes)?),
None => None,
};
let maybe_strong_ref = match maybe_data {
Some(data) => Some(Arc::new(data)),
None => None,
};
let maybe_weak_ref = match maybe_strong_ref {
Some(ref strong_ref) => Some(Arc::downgrade(strong_ref)),
None => None,
};
Ok(FontTemplate {
identifier: identifier,
descriptor: None,
weak_ref: maybe_weak_ref,
strong_ref: maybe_strong_ref,
is_valid: true,
})
}
pub fn identifier(&self) -> &Atom {
&self.identifier
}
/// Get the descriptor. Returns `None` when instantiating the data fails.
pub fn descriptor(&mut self, font_context: &FontContextHandle) -> Option<FontTemplateDescriptor> {
// The font template data can be unloaded when nothing is referencing
// it (via the Weak reference to the Arc above). However, if we have
// already loaded a font, store the style information about it separately,
// so that we can do font matching against it again in the future
// without having to reload the font (unless it is an actual match).
self.descriptor.or_else(|| {
if self.instantiate(font_context).is_err() {
return None
};
Some(self.descriptor.expect("Instantiation succeeded but no descriptor?"))
})
}
/// Get the data for creating a font if it matches a given descriptor.
pub fn data_for_descriptor(&mut self,
fctx: &FontContextHandle,
requested_desc: &FontTemplateDescriptor)
-> Option<Arc<FontTemplateData>> {
self.descriptor(&fctx).and_then(|descriptor| {
if *requested_desc == descriptor {
self.data().ok()
} else {
None
}
})
}
/// Returns the font data along with the distance between this font's descriptor and the given
/// descriptor, if the font can be loaded.
pub fn data_for_approximate_descriptor(&mut self,
font_context: &FontContextHandle,
requested_descriptor: &FontTemplateDescriptor)
-> Option<(Arc<FontTemplateData>, u32)> {
self.descriptor(&font_context).and_then(|descriptor| {
self.data().ok().map(|data| {
(data, descriptor.distance_from(requested_descriptor))
})
})
}
fn instantiate(&mut self, font_context: &FontContextHandle) -> Result<(), ()> {
if!self.is_valid {
return Err(())
}
let data = self.data().map_err(|_| ())?;
let handle: Result<FontHandle, ()> = FontHandleMethods::new_from_template(font_context,
data,
None);
self.is_valid = handle.is_ok();
let handle = handle?;
self.descriptor = Some(FontTemplateDescriptor::new(handle.boldness(),
handle.stretchiness(),
handle.is_italic()));
Ok(())
}
/// Get the data for creating a font.
pub fn get(&mut self) -> Option<Arc<FontTemplateData>> {
if self.is_valid {
self.data().ok()
} else {
None
}
}
/// Get the font template data. If any strong references still
/// exist, it will return a clone, otherwise it will load the
/// font data and store a weak reference to it internally.
pub fn data(&mut self) -> Result<Arc<FontTemplateData>, IoError>
|
}
|
{
let maybe_data = match self.weak_ref {
Some(ref data) => data.upgrade(),
None => None,
};
if let Some(data) = maybe_data {
return Ok(data)
}
assert!(self.strong_ref.is_none());
let template_data = Arc::new(FontTemplateData::new(self.identifier.clone(), None)?);
self.weak_ref = Some(Arc::downgrade(&template_data));
Ok(template_data)
}
|
identifier_body
|
shootout-k-nucleotide.rs
|
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
|
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// ignore-android see #10393 #13206
#![feature(box_syntax)]
use std::ascii::OwnedAsciiExt;
use std::slice;
use std::sync::Arc;
use std::thread;
static TABLE: [u8;4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str;5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[derive(Copy, PartialEq, PartialOrd, Ord, Eq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn push_char(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn unpack(&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in 0..frame {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
items: Vec<Option<Box<Entry>>>
}
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Iter<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
items: (0..TABLE_SIZE).map(|_| None).collect()
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
}
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
{
if self.items[index as uint].is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
self.items[index as uint] = Some(entry);
return;
}
}
{
let entry = self.items[index as uint].as_mut().unwrap();
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
fn iter(&self) -> Items {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator for Items<'a> {
type Item = &'a Entry;
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8 {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => panic!("{}", c as char),
}
}
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in 0..frame {
code = code.push_char(input[0]);
input = &input[1..];
}
frequencies.lookup(code, BumpCallback);
while input.len()!= 0 && input[0]!= ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = &input[1..];
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.sort();
let mut total_count = 0;
for &(count, _) in &vector {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3}",
key.unpack(frame),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key!= &l[..key.len()]).skip(1)
{
res.push_all(l.trim().as_bytes());
}
res.into_ascii_uppercase()
}
fn main() {
let input = if std::env::var_os("RUST_BENCH").is_some() {
let fd = std::old_io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::old_io::BufferedReader::new(fd), ">THREE")
} else {
let mut stdin = std::old_io::stdin();
let mut stdin = stdin.lock();
get_sequence(&mut *stdin, ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<_> = (1..3).map(|i| {
let input = input.clone();
(i, thread::scoped(move|| generate_frequencies(&input, i)))
}).collect();
let occ_freqs: Vec<_> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
thread::scoped(move|| generate_frequencies(&input, occ.len()))
}).collect();
for (i, freq) in nb_freqs {
print_frequencies(&freq.join(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.into_iter()) {
print_occurrences(&mut freq.join(), occ);
}
}
|
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
|
random_line_split
|
shootout-k-nucleotide.rs
|
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// ignore-android see #10393 #13206
#![feature(box_syntax)]
use std::ascii::OwnedAsciiExt;
use std::slice;
use std::sync::Arc;
use std::thread;
static TABLE: [u8;4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str;5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[derive(Copy, PartialEq, PartialOrd, Ord, Eq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn push_char(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn unpack(&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in 0..frame {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
items: Vec<Option<Box<Entry>>>
}
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Iter<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
items: (0..TABLE_SIZE).map(|_| None).collect()
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
}
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
{
if self.items[index as uint].is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
self.items[index as uint] = Some(entry);
return;
}
}
{
let entry = self.items[index as uint].as_mut().unwrap();
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
fn iter(&self) -> Items {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator for Items<'a> {
type Item = &'a Entry;
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8
|
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in 0..frame {
code = code.push_char(input[0]);
input = &input[1..];
}
frequencies.lookup(code, BumpCallback);
while input.len()!= 0 && input[0]!= ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = &input[1..];
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.sort();
let mut total_count = 0;
for &(count, _) in &vector {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3}",
key.unpack(frame),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key!= &l[..key.len()]).skip(1)
{
res.push_all(l.trim().as_bytes());
}
res.into_ascii_uppercase()
}
fn main() {
let input = if std::env::var_os("RUST_BENCH").is_some() {
let fd = std::old_io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::old_io::BufferedReader::new(fd), ">THREE")
} else {
let mut stdin = std::old_io::stdin();
let mut stdin = stdin.lock();
get_sequence(&mut *stdin, ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<_> = (1..3).map(|i| {
let input = input.clone();
(i, thread::scoped(move|| generate_frequencies(&input, i)))
}).collect();
let occ_freqs: Vec<_> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
thread::scoped(move|| generate_frequencies(&input, occ.len()))
}).collect();
for (i, freq) in nb_freqs {
print_frequencies(&freq.join(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.into_iter()) {
print_occurrences(&mut freq.join(), occ);
}
}
|
{
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => panic!("{}", c as char),
}
}
|
identifier_body
|
shootout-k-nucleotide.rs
|
// The Computer Language Benchmarks Game
// http://benchmarksgame.alioth.debian.org/
//
// contributed by the Rust Project Developers
// Copyright (c) 2014 The Rust Project Developers
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// - Neither the name of "The Computer Language Benchmarks Game" nor
// the name of "The Computer Language Shootout Benchmarks" nor the
// names of its contributors may be used to endorse or promote
// products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
// ignore-android see #10393 #13206
#![feature(box_syntax)]
use std::ascii::OwnedAsciiExt;
use std::slice;
use std::sync::Arc;
use std::thread;
static TABLE: [u8;4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str;5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[derive(Copy, PartialEq, PartialOrd, Ord, Eq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn push_char(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn unpack(&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in 0..frame {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
items: Vec<Option<Box<Entry>>>
}
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Iter<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
items: (0..TABLE_SIZE).map(|_| None).collect()
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
}
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
{
if self.items[index as uint].is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
self.items[index as uint] = Some(entry);
return;
}
}
{
let entry = self.items[index as uint].as_mut().unwrap();
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
fn iter(&self) -> Items {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator for Items<'a> {
type Item = &'a Entry;
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8 {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => panic!("{}", c as char),
}
}
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in 0..frame {
code = code.push_char(input[0]);
input = &input[1..];
}
frequencies.lookup(code, BumpCallback);
while input.len()!= 0 && input[0]!= ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = &input[1..];
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.sort();
let mut total_count = 0;
for &(count, _) in &vector {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3}",
key.unpack(frame),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn
|
<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key!= &l[..key.len()]).skip(1)
{
res.push_all(l.trim().as_bytes());
}
res.into_ascii_uppercase()
}
fn main() {
let input = if std::env::var_os("RUST_BENCH").is_some() {
let fd = std::old_io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::old_io::BufferedReader::new(fd), ">THREE")
} else {
let mut stdin = std::old_io::stdin();
let mut stdin = stdin.lock();
get_sequence(&mut *stdin, ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<_> = (1..3).map(|i| {
let input = input.clone();
(i, thread::scoped(move|| generate_frequencies(&input, i)))
}).collect();
let occ_freqs: Vec<_> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
thread::scoped(move|| generate_frequencies(&input, occ.len()))
}).collect();
for (i, freq) in nb_freqs {
print_frequencies(&freq.join(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.into_iter()) {
print_occurrences(&mut freq.join(), occ);
}
}
|
get_sequence
|
identifier_name
|
extended.rs
|
// Copyright 2015-2017 Parity Technologies (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/>.
//! Extended keys
use secret::Secret;
use Public;
use bigint::hash::H256;
pub use self::derivation::Error as DerivationError;
/// Represents label that can be stored as a part of key derivation
pub trait Label {
/// Length of the data that label occupies
fn len() -> usize;
/// Store label data to the key derivation sequence
/// Must not use more than `len()` bytes from slice
fn store(&self, target: &mut [u8]);
}
impl Label for u32 {
fn len() -> usize { 4 }
fn store(&self, target: &mut [u8]) {
use byteorder::{BigEndian, ByteOrder};
BigEndian::write_u32(&mut target[0..4], *self);
}
}
/// Key derivation over generic label `T`
pub enum Derivation<T: Label> {
/// Soft key derivation (allow proof of parent)
Soft(T),
/// Hard key derivation (does not allow proof of parent)
Hard(T),
}
impl From<u32> for Derivation<u32> {
fn from(index: u32) -> Self {
if index < (2 << 30) {
Derivation::Soft(index)
}
else {
Derivation::Hard(index)
}
}
}
impl Label for H256 {
fn len() -> usize { 32 }
fn store(&self, target: &mut [u8]) {
self.copy_to(&mut target[0..32]);
}
}
/// Extended secret key, allows deterministic derivation of subsequent keys.
pub struct ExtendedSecret {
secret: Secret,
chain_code: H256,
}
impl ExtendedSecret {
/// New extended key from given secret and chain code.
pub fn with_code(secret: Secret, chain_code: H256) -> ExtendedSecret {
ExtendedSecret {
secret: secret,
chain_code: chain_code,
}
}
/// New extended key from given secret with the random chain code.
pub fn new_random(secret: Secret) -> ExtendedSecret {
ExtendedSecret::with_code(secret, H256::random())
}
/// New extended key from given secret.
/// Chain code will be derived from the secret itself (in a deterministic way).
pub fn new(secret: Secret) -> ExtendedSecret {
let chain_code = derivation::chain_code(*secret);
ExtendedSecret::with_code(secret, chain_code)
}
/// Derive new private key
pub fn derive<T>(&self, index: Derivation<T>) -> ExtendedSecret where T: Label {
let (derived_key, next_chain_code) = derivation::private(*self.secret, self.chain_code, index);
let derived_secret = Secret::from_slice(&*derived_key);
ExtendedSecret::with_code(derived_secret, next_chain_code)
}
/// Private key component of the extended key.
pub fn as_raw(&self) -> &Secret {
&self.secret
}
}
/// Extended public key, allows deterministic derivation of subsequent keys.
pub struct ExtendedPublic {
public: Public,
chain_code: H256,
}
impl ExtendedPublic {
/// New extended public key from known parent and chain code
pub fn new(public: Public, chain_code: H256) -> Self {
ExtendedPublic { public: public, chain_code: chain_code }
}
/// Create new extended public key from known secret
pub fn from_secret(secret: &ExtendedSecret) -> Result<Self, DerivationError> {
Ok(
ExtendedPublic::new(
derivation::point(**secret.as_raw())?,
secret.chain_code.clone(),
)
)
}
/// Derive new public key
/// Operation is defined only for index belongs [0..2^31)
pub fn derive<T>(&self, index: Derivation<T>) -> Result<Self, DerivationError> where T: Label {
let (derived_key, next_chain_code) = derivation::public(self.public, self.chain_code, index)?;
Ok(ExtendedPublic::new(derived_key, next_chain_code))
}
pub fn public(&self) -> &Public {
&self.public
}
}
pub struct ExtendedKeyPair {
secret: ExtendedSecret,
public: ExtendedPublic,
}
impl ExtendedKeyPair {
pub fn new(secret: Secret) -> Self {
let extended_secret = ExtendedSecret::new(secret);
let extended_public = ExtendedPublic::from_secret(&extended_secret)
.expect("Valid `Secret` always produces valid public; qed");
ExtendedKeyPair {
secret: extended_secret,
public: extended_public,
}
}
pub fn with_code(secret: Secret, public: Public, chain_code: H256) -> Self {
ExtendedKeyPair {
secret: ExtendedSecret::with_code(secret, chain_code.clone()),
public: ExtendedPublic::new(public, chain_code),
}
}
pub fn with_secret(secret: Secret, chain_code: H256) -> Self {
let extended_secret = ExtendedSecret::with_code(secret, chain_code);
let extended_public = ExtendedPublic::from_secret(&extended_secret)
.expect("Valid `Secret` always produces valid public; qed");
ExtendedKeyPair {
secret: extended_secret,
public: extended_public,
}
}
pub fn with_seed(seed: &[u8]) -> Result<ExtendedKeyPair, DerivationError> {
let (master_key, chain_code) = derivation::seed_pair(seed);
Ok(ExtendedKeyPair::with_secret(
Secret::from_unsafe_slice(&*master_key).map_err(|_| DerivationError::InvalidSeed)?,
chain_code,
))
}
pub fn secret(&self) -> &ExtendedSecret {
&self.secret
}
pub fn public(&self) -> &ExtendedPublic {
&self.public
}
pub fn derive<T>(&self, index: Derivation<T>) -> Result<Self, DerivationError> where T: Label {
let derived = self.secret.derive(index);
Ok(ExtendedKeyPair {
public: ExtendedPublic::from_secret(&derived)?,
secret: derived,
})
}
}
// Derivation functions for private and public keys
// Work is based on BIP0032
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
mod derivation {
use rcrypto::hmac::Hmac;
use rcrypto::mac::Mac;
use rcrypto::sha2::Sha512;
use bigint::hash::{H512, H256};
use bigint::prelude::{U256, U512};
use secp256k1::key::{SecretKey, PublicKey};
use SECP256K1;
use keccak;
use math::curve_order;
use super::{Label, Derivation};
#[derive(Debug)]
pub enum Error {
InvalidHardenedUse,
InvalidPoint,
MissingIndex,
InvalidSeed,
}
// Deterministic derivation of the key using secp256k1 elliptic curve.
// Derivation can be either hardened or not.
// For hardened derivation, pass u32 index at least 2^31 or custom Derivation::Hard(T) enum
//
// Can panic if passed `private_key` is not a valid secp256k1 private key
// (outside of (0..curve_order()]) field
pub fn private<T>(private_key: H256, chain_code: H256, index: Derivation<T>) -> (H256, H256) where T: Label {
match index {
Derivation::Soft(index) => private_soft(private_key, chain_code, index),
Derivation::Hard(index) => private_hard(private_key, chain_code, index),
}
}
fn hmac_pair(data: &[u8], private_key: H256, chain_code: H256) -> (H256, H256) {
let private: U256 = private_key.into();
// produces 512-bit derived hmac (I)
let mut hmac = Hmac::new(Sha512::new(), &*chain_code);
let mut i_512 = [0u8; 64];
hmac.input(&data[..]);
hmac.raw_result(&mut i_512);
// left most 256 bits are later added to original private key
let hmac_key: U256 = H256::from_slice(&i_512[0..32]).into();
// right most 256 bits are new chain code for later derivations
let next_chain_code = H256::from(&i_512[32..64]);
let child_key = private_add(hmac_key, private).into();
(child_key, next_chain_code)
}
// Can panic if passed `private_key` is not a valid secp256k1 private key
// (outside of (0..curve_order()]) field
fn private_soft<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
let mut data = vec![0u8; 33 + T::len()];
let sec_private = SecretKey::from_slice(&SECP256K1, &*private_key)
.expect("Caller should provide valid private key");
let sec_public = PublicKey::from_secret_key(&SECP256K1, &sec_private)
.expect("Caller should provide valid private key");
let public_serialized = sec_public.serialize_vec(&SECP256K1, true);
// curve point (compressed public key) -- index
// 0.33 -- 33..end
data[0..33].copy_from_slice(&public_serialized);
index.store(&mut data[33..]);
hmac_pair(&data, private_key, chain_code)
}
// Deterministic derivation of the key using secp256k1 elliptic curve
// This is hardened derivation and does not allow to associate
// corresponding public keys of the original and derived private keys
fn private_hard<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
let mut data: Vec<u8> = vec![0u8; 33 + T::len()];
let private: U256 = private_key.into();
// 0x00 (padding) -- private_key -- index
// 0 -- 1..33 -- 33..end
private.to_big_endian(&mut data[1..33]);
index.store(&mut data[33..(33 + T::len())]);
hmac_pair(&data, private_key, chain_code)
}
fn private_add(k1: U256, k2: U256) -> U256 {
let sum = U512::from(k1) + U512::from(k2);
modulo(sum, curve_order())
}
// todo: surely can be optimized
fn modulo(u1: U512, u2: U256) -> U256 {
let dv = u1 / U512::from(u2);
let md = u1 - (dv * U512::from(u2));
md.into()
}
pub fn public<T>(public_key: H512, chain_code: H256, derivation: Derivation<T>) -> Result<(H512, H256), Error> where T: Label {
let index = match derivation {
Derivation::Soft(index) => index,
Derivation::Hard(_) => { return Err(Error::InvalidHardenedUse); }
};
let mut public_sec_raw = [0u8; 65];
public_sec_raw[0] = 4;
public_sec_raw[1..65].copy_from_slice(&*public_key);
let public_sec = PublicKey::from_slice(&SECP256K1, &public_sec_raw).map_err(|_| Error::InvalidPoint)?;
let public_serialized = public_sec.serialize_vec(&SECP256K1, true);
let mut data = vec![0u8; 33 + T::len()];
// curve point (compressed public key) -- index
// 0.33 -- 33..end
data[0..33].copy_from_slice(&public_serialized);
index.store(&mut data[33..(33 + T::len())]);
// HMAC512SHA produces [derived private(256); new chain code(256)]
let mut hmac = Hmac::new(Sha512::new(), &*chain_code);
let mut i_512 = [0u8; 64];
hmac.input(&data[..]);
hmac.raw_result(&mut i_512);
let new_private = H256::from(&i_512[0..32]);
let new_chain_code = H256::from(&i_512[32..64]);
// Generated private key can (extremely rarely) be out of secp256k1 key field
if curve_order() <= new_private.clone().into()
|
let new_private_sec = SecretKey::from_slice(&SECP256K1, &*new_private)
.expect("Private key belongs to the field [0..CURVE_ORDER) (checked above); So initializing can never fail; qed");
let mut new_public = PublicKey::from_secret_key(&SECP256K1, &new_private_sec)
.expect("Valid private key produces valid public key");
// Adding two points on the elliptic curves (combining two public keys)
new_public.add_assign(&SECP256K1, &public_sec)
.expect("Addition of two valid points produce valid point");
let serialized = new_public.serialize_vec(&SECP256K1, false);
Ok((
H512::from(&serialized[1..65]),
new_chain_code,
))
}
fn sha3(slc: &[u8]) -> H256 {
keccak::Keccak256::keccak256(slc).into()
}
pub fn chain_code(secret: H256) -> H256 {
// 10,000 rounds of sha3
let mut running_sha3 = sha3(&*secret);
for _ in 0..99999 { running_sha3 = sha3(&*running_sha3); }
running_sha3
}
pub fn point(secret: H256) -> Result<H512, Error> {
let sec = SecretKey::from_slice(&SECP256K1, &*secret)
.map_err(|_| Error::InvalidPoint)?;
let public_sec = PublicKey::from_secret_key(&SECP256K1, &sec)
.map_err(|_| Error::InvalidPoint)?;
let serialized = public_sec.serialize_vec(&SECP256K1, false);
Ok(H512::from(&serialized[1..65]))
}
pub fn seed_pair(seed: &[u8]) -> (H256, H256) {
let mut hmac = Hmac::new(Sha512::new(), b"Bitcoin seed");
let mut i_512 = [0u8; 64];
hmac.input(seed);
hmac.raw_result(&mut i_512);
let master_key = H256::from_slice(&i_512[0..32]);
let chain_code = H256::from_slice(&i_512[32..64]);
(master_key, chain_code)
}
}
#[cfg(test)]
mod tests {
use super::{ExtendedSecret, ExtendedPublic, ExtendedKeyPair};
use secret::Secret;
use std::str::FromStr;
use bigint::hash::{H128, H256};
use super::{derivation, Derivation};
fn master_chain_basic() -> (H256, H256) {
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
.expect("Seed should be valid H128")
.to_vec();
derivation::seed_pair(&*seed)
}
fn test_extended<F>(f: F, test_private: H256) where F: Fn(ExtendedSecret) -> ExtendedSecret {
let (private_seed, chain_code) = master_chain_basic();
let extended_secret = ExtendedSecret::with_code(Secret::from_slice(&*private_seed), chain_code);
let derived = f(extended_secret);
assert_eq!(**derived.as_raw(), test_private);
}
#[test]
fn smoky() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into());
// hardened
assert_eq!(&**extended_secret.as_raw(), &*secret);
assert_eq!(&**extended_secret.derive(2147483648.into()).as_raw(), &"0927453daed47839608e414a3738dfad10aed17c459bbd9ab53f89b026c834b6".into());
assert_eq!(&**extended_secret.derive(2147483649.into()).as_raw(), &"44238b6a29c6dcbe9b401364141ba11e2198c289a5fed243a1c11af35c19dc0f".into());
// normal
assert_eq!(&**extended_secret.derive(0.into()).as_raw(), &"bf6a74e3f7b36fc4c96a1e12f31abc817f9f5904f5a8fc27713163d1f0b713f6".into());
assert_eq!(&**extended_secret.derive(1.into()).as_raw(), &"bd4fca9eb1f9c201e9448c1eecd66e302d68d4d313ce895b8c134f512205c1bc".into());
assert_eq!(&**extended_secret.derive(2.into()).as_raw(), &"86932b542d6cab4d9c65490c7ef502d89ecc0e2a5f4852157649e3251e2a3268".into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_public = extended_public.derive(0.into()).expect("First derivation of public should succeed");
assert_eq!(&*derived_public.public(), &"f7b3244c96688f92372bfd4def26dc4151529747bab9f188a4ad34e141d47bd66522ff048bc6f19a0a4429b04318b1a8796c000265b4fa200dae5f6dda92dd94".into());
let keypair = ExtendedKeyPair::with_secret(
Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap(),
064.into(),
);
assert_eq!(&**keypair.derive(2147483648u32.into()).expect("Derivation of keypair should succeed").secret().as_raw(), &"edef54414c03196557cf73774bc97a645c9a1df2164ed34f0c2a78d1375a930c".into());
}
#[test]
fn h256_soft_match() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_secret0 = extended_secret.derive(Derivation::Soft(derivation_secret));
let derived_public0 = extended_public.derive(Derivation::Soft(derivation_secret)).expect("First derivation of public should succeed");
let public_from_secret0 = ExtendedPublic::from_secret(&derived_secret0).expect("Extended public should be created");
assert_eq!(public_from_secret0.public(), derived_public0.public());
}
#[test]
fn h256_hard() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 1u64.into());
assert_eq!(&**extended_secret.derive(Derivation::Hard(derivation_secret)).as_raw(), &"2bc2d696fb744d77ff813b4a1ef0ad64e1e5188b622c54ba917acc5ebc7c5486".into());
}
#[test]
fn match_() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 1.into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_secret0 = extended_secret.derive(0.into());
let derived_public0 = extended_public.derive(0.into()).expect("First derivation of public should succeed");
let public_from_secret0 = ExtendedPublic::from_secret(&derived_secret0).expect("Extended public should be created");
assert_eq!(public_from_secret0.public(), derived_public0.public());
}
#[test]
fn test_seeds() {
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
.expect("Seed should be valid H128")
.to_vec();
/// private key from bitcoin test vector
/// xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs
let test_private = H256::from_str("e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35")
.expect("Private should be decoded ok");
let (private_seed, _) = derivation::seed_pair(&*seed);
assert_eq!(private_seed, test_private);
}
#[test]
fn test_vector_1() {
/// xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7
/// H(0)
test_extended(
|secret| secret.derive(2147483648.into()),
H256::from_str("edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea")
.expect("Private should be decoded ok")
);
}
#[test]
fn test_vector_2() {
/// xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs
/// H(0)/1
test_extended(
|secret| secret.derive(2147483648.into()).derive(1.into()),
H256::from_str("3c6cb8d0f6a264c91ea8b5030fadaa8e538b020f0a387421a12de9319dc93368")
.expect("Private should be decoded ok")
);
}
}
|
{ return Err(Error::MissingIndex); }
|
conditional_block
|
extended.rs
|
// Copyright 2015-2017 Parity Technologies (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/>.
//! Extended keys
use secret::Secret;
use Public;
use bigint::hash::H256;
pub use self::derivation::Error as DerivationError;
/// Represents label that can be stored as a part of key derivation
pub trait Label {
/// Length of the data that label occupies
fn len() -> usize;
/// Store label data to the key derivation sequence
/// Must not use more than `len()` bytes from slice
fn store(&self, target: &mut [u8]);
}
impl Label for u32 {
fn len() -> usize { 4 }
fn store(&self, target: &mut [u8]) {
use byteorder::{BigEndian, ByteOrder};
BigEndian::write_u32(&mut target[0..4], *self);
}
}
/// Key derivation over generic label `T`
pub enum Derivation<T: Label> {
/// Soft key derivation (allow proof of parent)
Soft(T),
/// Hard key derivation (does not allow proof of parent)
Hard(T),
}
impl From<u32> for Derivation<u32> {
fn from(index: u32) -> Self {
if index < (2 << 30) {
Derivation::Soft(index)
}
else {
Derivation::Hard(index)
}
}
}
impl Label for H256 {
fn len() -> usize { 32 }
fn store(&self, target: &mut [u8]) {
self.copy_to(&mut target[0..32]);
}
}
/// Extended secret key, allows deterministic derivation of subsequent keys.
pub struct ExtendedSecret {
secret: Secret,
chain_code: H256,
}
impl ExtendedSecret {
/// New extended key from given secret and chain code.
pub fn with_code(secret: Secret, chain_code: H256) -> ExtendedSecret {
ExtendedSecret {
secret: secret,
chain_code: chain_code,
}
}
/// New extended key from given secret with the random chain code.
pub fn new_random(secret: Secret) -> ExtendedSecret {
ExtendedSecret::with_code(secret, H256::random())
}
/// New extended key from given secret.
/// Chain code will be derived from the secret itself (in a deterministic way).
pub fn new(secret: Secret) -> ExtendedSecret {
let chain_code = derivation::chain_code(*secret);
ExtendedSecret::with_code(secret, chain_code)
}
/// Derive new private key
pub fn derive<T>(&self, index: Derivation<T>) -> ExtendedSecret where T: Label {
let (derived_key, next_chain_code) = derivation::private(*self.secret, self.chain_code, index);
let derived_secret = Secret::from_slice(&*derived_key);
ExtendedSecret::with_code(derived_secret, next_chain_code)
}
/// Private key component of the extended key.
pub fn as_raw(&self) -> &Secret {
&self.secret
}
}
/// Extended public key, allows deterministic derivation of subsequent keys.
pub struct ExtendedPublic {
public: Public,
chain_code: H256,
}
impl ExtendedPublic {
/// New extended public key from known parent and chain code
pub fn new(public: Public, chain_code: H256) -> Self {
ExtendedPublic { public: public, chain_code: chain_code }
}
/// Create new extended public key from known secret
pub fn from_secret(secret: &ExtendedSecret) -> Result<Self, DerivationError> {
Ok(
ExtendedPublic::new(
derivation::point(**secret.as_raw())?,
secret.chain_code.clone(),
)
)
}
/// Derive new public key
/// Operation is defined only for index belongs [0..2^31)
pub fn derive<T>(&self, index: Derivation<T>) -> Result<Self, DerivationError> where T: Label {
let (derived_key, next_chain_code) = derivation::public(self.public, self.chain_code, index)?;
Ok(ExtendedPublic::new(derived_key, next_chain_code))
}
pub fn public(&self) -> &Public {
&self.public
}
}
pub struct ExtendedKeyPair {
secret: ExtendedSecret,
public: ExtendedPublic,
}
impl ExtendedKeyPair {
pub fn new(secret: Secret) -> Self {
let extended_secret = ExtendedSecret::new(secret);
let extended_public = ExtendedPublic::from_secret(&extended_secret)
.expect("Valid `Secret` always produces valid public; qed");
ExtendedKeyPair {
secret: extended_secret,
public: extended_public,
}
}
pub fn with_code(secret: Secret, public: Public, chain_code: H256) -> Self {
ExtendedKeyPair {
secret: ExtendedSecret::with_code(secret, chain_code.clone()),
public: ExtendedPublic::new(public, chain_code),
}
}
pub fn with_secret(secret: Secret, chain_code: H256) -> Self {
let extended_secret = ExtendedSecret::with_code(secret, chain_code);
let extended_public = ExtendedPublic::from_secret(&extended_secret)
.expect("Valid `Secret` always produces valid public; qed");
ExtendedKeyPair {
secret: extended_secret,
|
let (master_key, chain_code) = derivation::seed_pair(seed);
Ok(ExtendedKeyPair::with_secret(
Secret::from_unsafe_slice(&*master_key).map_err(|_| DerivationError::InvalidSeed)?,
chain_code,
))
}
pub fn secret(&self) -> &ExtendedSecret {
&self.secret
}
pub fn public(&self) -> &ExtendedPublic {
&self.public
}
pub fn derive<T>(&self, index: Derivation<T>) -> Result<Self, DerivationError> where T: Label {
let derived = self.secret.derive(index);
Ok(ExtendedKeyPair {
public: ExtendedPublic::from_secret(&derived)?,
secret: derived,
})
}
}
// Derivation functions for private and public keys
// Work is based on BIP0032
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
mod derivation {
use rcrypto::hmac::Hmac;
use rcrypto::mac::Mac;
use rcrypto::sha2::Sha512;
use bigint::hash::{H512, H256};
use bigint::prelude::{U256, U512};
use secp256k1::key::{SecretKey, PublicKey};
use SECP256K1;
use keccak;
use math::curve_order;
use super::{Label, Derivation};
#[derive(Debug)]
pub enum Error {
InvalidHardenedUse,
InvalidPoint,
MissingIndex,
InvalidSeed,
}
// Deterministic derivation of the key using secp256k1 elliptic curve.
// Derivation can be either hardened or not.
// For hardened derivation, pass u32 index at least 2^31 or custom Derivation::Hard(T) enum
//
// Can panic if passed `private_key` is not a valid secp256k1 private key
// (outside of (0..curve_order()]) field
pub fn private<T>(private_key: H256, chain_code: H256, index: Derivation<T>) -> (H256, H256) where T: Label {
match index {
Derivation::Soft(index) => private_soft(private_key, chain_code, index),
Derivation::Hard(index) => private_hard(private_key, chain_code, index),
}
}
fn hmac_pair(data: &[u8], private_key: H256, chain_code: H256) -> (H256, H256) {
let private: U256 = private_key.into();
// produces 512-bit derived hmac (I)
let mut hmac = Hmac::new(Sha512::new(), &*chain_code);
let mut i_512 = [0u8; 64];
hmac.input(&data[..]);
hmac.raw_result(&mut i_512);
// left most 256 bits are later added to original private key
let hmac_key: U256 = H256::from_slice(&i_512[0..32]).into();
// right most 256 bits are new chain code for later derivations
let next_chain_code = H256::from(&i_512[32..64]);
let child_key = private_add(hmac_key, private).into();
(child_key, next_chain_code)
}
// Can panic if passed `private_key` is not a valid secp256k1 private key
// (outside of (0..curve_order()]) field
fn private_soft<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
let mut data = vec![0u8; 33 + T::len()];
let sec_private = SecretKey::from_slice(&SECP256K1, &*private_key)
.expect("Caller should provide valid private key");
let sec_public = PublicKey::from_secret_key(&SECP256K1, &sec_private)
.expect("Caller should provide valid private key");
let public_serialized = sec_public.serialize_vec(&SECP256K1, true);
// curve point (compressed public key) -- index
// 0.33 -- 33..end
data[0..33].copy_from_slice(&public_serialized);
index.store(&mut data[33..]);
hmac_pair(&data, private_key, chain_code)
}
// Deterministic derivation of the key using secp256k1 elliptic curve
// This is hardened derivation and does not allow to associate
// corresponding public keys of the original and derived private keys
fn private_hard<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
let mut data: Vec<u8> = vec![0u8; 33 + T::len()];
let private: U256 = private_key.into();
// 0x00 (padding) -- private_key -- index
// 0 -- 1..33 -- 33..end
private.to_big_endian(&mut data[1..33]);
index.store(&mut data[33..(33 + T::len())]);
hmac_pair(&data, private_key, chain_code)
}
fn private_add(k1: U256, k2: U256) -> U256 {
let sum = U512::from(k1) + U512::from(k2);
modulo(sum, curve_order())
}
// todo: surely can be optimized
fn modulo(u1: U512, u2: U256) -> U256 {
let dv = u1 / U512::from(u2);
let md = u1 - (dv * U512::from(u2));
md.into()
}
pub fn public<T>(public_key: H512, chain_code: H256, derivation: Derivation<T>) -> Result<(H512, H256), Error> where T: Label {
let index = match derivation {
Derivation::Soft(index) => index,
Derivation::Hard(_) => { return Err(Error::InvalidHardenedUse); }
};
let mut public_sec_raw = [0u8; 65];
public_sec_raw[0] = 4;
public_sec_raw[1..65].copy_from_slice(&*public_key);
let public_sec = PublicKey::from_slice(&SECP256K1, &public_sec_raw).map_err(|_| Error::InvalidPoint)?;
let public_serialized = public_sec.serialize_vec(&SECP256K1, true);
let mut data = vec![0u8; 33 + T::len()];
// curve point (compressed public key) -- index
// 0.33 -- 33..end
data[0..33].copy_from_slice(&public_serialized);
index.store(&mut data[33..(33 + T::len())]);
// HMAC512SHA produces [derived private(256); new chain code(256)]
let mut hmac = Hmac::new(Sha512::new(), &*chain_code);
let mut i_512 = [0u8; 64];
hmac.input(&data[..]);
hmac.raw_result(&mut i_512);
let new_private = H256::from(&i_512[0..32]);
let new_chain_code = H256::from(&i_512[32..64]);
// Generated private key can (extremely rarely) be out of secp256k1 key field
if curve_order() <= new_private.clone().into() { return Err(Error::MissingIndex); }
let new_private_sec = SecretKey::from_slice(&SECP256K1, &*new_private)
.expect("Private key belongs to the field [0..CURVE_ORDER) (checked above); So initializing can never fail; qed");
let mut new_public = PublicKey::from_secret_key(&SECP256K1, &new_private_sec)
.expect("Valid private key produces valid public key");
// Adding two points on the elliptic curves (combining two public keys)
new_public.add_assign(&SECP256K1, &public_sec)
.expect("Addition of two valid points produce valid point");
let serialized = new_public.serialize_vec(&SECP256K1, false);
Ok((
H512::from(&serialized[1..65]),
new_chain_code,
))
}
fn sha3(slc: &[u8]) -> H256 {
keccak::Keccak256::keccak256(slc).into()
}
pub fn chain_code(secret: H256) -> H256 {
// 10,000 rounds of sha3
let mut running_sha3 = sha3(&*secret);
for _ in 0..99999 { running_sha3 = sha3(&*running_sha3); }
running_sha3
}
pub fn point(secret: H256) -> Result<H512, Error> {
let sec = SecretKey::from_slice(&SECP256K1, &*secret)
.map_err(|_| Error::InvalidPoint)?;
let public_sec = PublicKey::from_secret_key(&SECP256K1, &sec)
.map_err(|_| Error::InvalidPoint)?;
let serialized = public_sec.serialize_vec(&SECP256K1, false);
Ok(H512::from(&serialized[1..65]))
}
pub fn seed_pair(seed: &[u8]) -> (H256, H256) {
let mut hmac = Hmac::new(Sha512::new(), b"Bitcoin seed");
let mut i_512 = [0u8; 64];
hmac.input(seed);
hmac.raw_result(&mut i_512);
let master_key = H256::from_slice(&i_512[0..32]);
let chain_code = H256::from_slice(&i_512[32..64]);
(master_key, chain_code)
}
}
#[cfg(test)]
mod tests {
use super::{ExtendedSecret, ExtendedPublic, ExtendedKeyPair};
use secret::Secret;
use std::str::FromStr;
use bigint::hash::{H128, H256};
use super::{derivation, Derivation};
fn master_chain_basic() -> (H256, H256) {
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
.expect("Seed should be valid H128")
.to_vec();
derivation::seed_pair(&*seed)
}
fn test_extended<F>(f: F, test_private: H256) where F: Fn(ExtendedSecret) -> ExtendedSecret {
let (private_seed, chain_code) = master_chain_basic();
let extended_secret = ExtendedSecret::with_code(Secret::from_slice(&*private_seed), chain_code);
let derived = f(extended_secret);
assert_eq!(**derived.as_raw(), test_private);
}
#[test]
fn smoky() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into());
// hardened
assert_eq!(&**extended_secret.as_raw(), &*secret);
assert_eq!(&**extended_secret.derive(2147483648.into()).as_raw(), &"0927453daed47839608e414a3738dfad10aed17c459bbd9ab53f89b026c834b6".into());
assert_eq!(&**extended_secret.derive(2147483649.into()).as_raw(), &"44238b6a29c6dcbe9b401364141ba11e2198c289a5fed243a1c11af35c19dc0f".into());
// normal
assert_eq!(&**extended_secret.derive(0.into()).as_raw(), &"bf6a74e3f7b36fc4c96a1e12f31abc817f9f5904f5a8fc27713163d1f0b713f6".into());
assert_eq!(&**extended_secret.derive(1.into()).as_raw(), &"bd4fca9eb1f9c201e9448c1eecd66e302d68d4d313ce895b8c134f512205c1bc".into());
assert_eq!(&**extended_secret.derive(2.into()).as_raw(), &"86932b542d6cab4d9c65490c7ef502d89ecc0e2a5f4852157649e3251e2a3268".into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_public = extended_public.derive(0.into()).expect("First derivation of public should succeed");
assert_eq!(&*derived_public.public(), &"f7b3244c96688f92372bfd4def26dc4151529747bab9f188a4ad34e141d47bd66522ff048bc6f19a0a4429b04318b1a8796c000265b4fa200dae5f6dda92dd94".into());
let keypair = ExtendedKeyPair::with_secret(
Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap(),
064.into(),
);
assert_eq!(&**keypair.derive(2147483648u32.into()).expect("Derivation of keypair should succeed").secret().as_raw(), &"edef54414c03196557cf73774bc97a645c9a1df2164ed34f0c2a78d1375a930c".into());
}
#[test]
fn h256_soft_match() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_secret0 = extended_secret.derive(Derivation::Soft(derivation_secret));
let derived_public0 = extended_public.derive(Derivation::Soft(derivation_secret)).expect("First derivation of public should succeed");
let public_from_secret0 = ExtendedPublic::from_secret(&derived_secret0).expect("Extended public should be created");
assert_eq!(public_from_secret0.public(), derived_public0.public());
}
#[test]
fn h256_hard() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 1u64.into());
assert_eq!(&**extended_secret.derive(Derivation::Hard(derivation_secret)).as_raw(), &"2bc2d696fb744d77ff813b4a1ef0ad64e1e5188b622c54ba917acc5ebc7c5486".into());
}
#[test]
fn match_() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 1.into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_secret0 = extended_secret.derive(0.into());
let derived_public0 = extended_public.derive(0.into()).expect("First derivation of public should succeed");
let public_from_secret0 = ExtendedPublic::from_secret(&derived_secret0).expect("Extended public should be created");
assert_eq!(public_from_secret0.public(), derived_public0.public());
}
#[test]
fn test_seeds() {
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
.expect("Seed should be valid H128")
.to_vec();
/// private key from bitcoin test vector
/// xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs
let test_private = H256::from_str("e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35")
.expect("Private should be decoded ok");
let (private_seed, _) = derivation::seed_pair(&*seed);
assert_eq!(private_seed, test_private);
}
#[test]
fn test_vector_1() {
/// xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7
/// H(0)
test_extended(
|secret| secret.derive(2147483648.into()),
H256::from_str("edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea")
.expect("Private should be decoded ok")
);
}
#[test]
fn test_vector_2() {
/// xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs
/// H(0)/1
test_extended(
|secret| secret.derive(2147483648.into()).derive(1.into()),
H256::from_str("3c6cb8d0f6a264c91ea8b5030fadaa8e538b020f0a387421a12de9319dc93368")
.expect("Private should be decoded ok")
);
}
}
|
public: extended_public,
}
}
pub fn with_seed(seed: &[u8]) -> Result<ExtendedKeyPair, DerivationError> {
|
random_line_split
|
extended.rs
|
// Copyright 2015-2017 Parity Technologies (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/>.
//! Extended keys
use secret::Secret;
use Public;
use bigint::hash::H256;
pub use self::derivation::Error as DerivationError;
/// Represents label that can be stored as a part of key derivation
pub trait Label {
/// Length of the data that label occupies
fn len() -> usize;
/// Store label data to the key derivation sequence
/// Must not use more than `len()` bytes from slice
fn store(&self, target: &mut [u8]);
}
impl Label for u32 {
fn len() -> usize { 4 }
fn store(&self, target: &mut [u8]) {
use byteorder::{BigEndian, ByteOrder};
BigEndian::write_u32(&mut target[0..4], *self);
}
}
/// Key derivation over generic label `T`
pub enum Derivation<T: Label> {
/// Soft key derivation (allow proof of parent)
Soft(T),
/// Hard key derivation (does not allow proof of parent)
Hard(T),
}
impl From<u32> for Derivation<u32> {
fn from(index: u32) -> Self {
if index < (2 << 30) {
Derivation::Soft(index)
}
else {
Derivation::Hard(index)
}
}
}
impl Label for H256 {
fn len() -> usize { 32 }
fn store(&self, target: &mut [u8]) {
self.copy_to(&mut target[0..32]);
}
}
/// Extended secret key, allows deterministic derivation of subsequent keys.
pub struct ExtendedSecret {
secret: Secret,
chain_code: H256,
}
impl ExtendedSecret {
/// New extended key from given secret and chain code.
pub fn with_code(secret: Secret, chain_code: H256) -> ExtendedSecret {
ExtendedSecret {
secret: secret,
chain_code: chain_code,
}
}
/// New extended key from given secret with the random chain code.
pub fn new_random(secret: Secret) -> ExtendedSecret {
ExtendedSecret::with_code(secret, H256::random())
}
/// New extended key from given secret.
/// Chain code will be derived from the secret itself (in a deterministic way).
pub fn new(secret: Secret) -> ExtendedSecret {
let chain_code = derivation::chain_code(*secret);
ExtendedSecret::with_code(secret, chain_code)
}
/// Derive new private key
pub fn derive<T>(&self, index: Derivation<T>) -> ExtendedSecret where T: Label {
let (derived_key, next_chain_code) = derivation::private(*self.secret, self.chain_code, index);
let derived_secret = Secret::from_slice(&*derived_key);
ExtendedSecret::with_code(derived_secret, next_chain_code)
}
/// Private key component of the extended key.
pub fn as_raw(&self) -> &Secret {
&self.secret
}
}
/// Extended public key, allows deterministic derivation of subsequent keys.
pub struct ExtendedPublic {
public: Public,
chain_code: H256,
}
impl ExtendedPublic {
/// New extended public key from known parent and chain code
pub fn new(public: Public, chain_code: H256) -> Self {
ExtendedPublic { public: public, chain_code: chain_code }
}
/// Create new extended public key from known secret
pub fn from_secret(secret: &ExtendedSecret) -> Result<Self, DerivationError> {
Ok(
ExtendedPublic::new(
derivation::point(**secret.as_raw())?,
secret.chain_code.clone(),
)
)
}
/// Derive new public key
/// Operation is defined only for index belongs [0..2^31)
pub fn derive<T>(&self, index: Derivation<T>) -> Result<Self, DerivationError> where T: Label {
let (derived_key, next_chain_code) = derivation::public(self.public, self.chain_code, index)?;
Ok(ExtendedPublic::new(derived_key, next_chain_code))
}
pub fn public(&self) -> &Public {
&self.public
}
}
pub struct ExtendedKeyPair {
secret: ExtendedSecret,
public: ExtendedPublic,
}
impl ExtendedKeyPair {
pub fn new(secret: Secret) -> Self {
let extended_secret = ExtendedSecret::new(secret);
let extended_public = ExtendedPublic::from_secret(&extended_secret)
.expect("Valid `Secret` always produces valid public; qed");
ExtendedKeyPair {
secret: extended_secret,
public: extended_public,
}
}
pub fn with_code(secret: Secret, public: Public, chain_code: H256) -> Self {
ExtendedKeyPair {
secret: ExtendedSecret::with_code(secret, chain_code.clone()),
public: ExtendedPublic::new(public, chain_code),
}
}
pub fn with_secret(secret: Secret, chain_code: H256) -> Self {
let extended_secret = ExtendedSecret::with_code(secret, chain_code);
let extended_public = ExtendedPublic::from_secret(&extended_secret)
.expect("Valid `Secret` always produces valid public; qed");
ExtendedKeyPair {
secret: extended_secret,
public: extended_public,
}
}
pub fn with_seed(seed: &[u8]) -> Result<ExtendedKeyPair, DerivationError> {
let (master_key, chain_code) = derivation::seed_pair(seed);
Ok(ExtendedKeyPair::with_secret(
Secret::from_unsafe_slice(&*master_key).map_err(|_| DerivationError::InvalidSeed)?,
chain_code,
))
}
pub fn secret(&self) -> &ExtendedSecret {
&self.secret
}
pub fn public(&self) -> &ExtendedPublic {
&self.public
}
pub fn derive<T>(&self, index: Derivation<T>) -> Result<Self, DerivationError> where T: Label {
let derived = self.secret.derive(index);
Ok(ExtendedKeyPair {
public: ExtendedPublic::from_secret(&derived)?,
secret: derived,
})
}
}
// Derivation functions for private and public keys
// Work is based on BIP0032
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
mod derivation {
use rcrypto::hmac::Hmac;
use rcrypto::mac::Mac;
use rcrypto::sha2::Sha512;
use bigint::hash::{H512, H256};
use bigint::prelude::{U256, U512};
use secp256k1::key::{SecretKey, PublicKey};
use SECP256K1;
use keccak;
use math::curve_order;
use super::{Label, Derivation};
#[derive(Debug)]
pub enum Error {
InvalidHardenedUse,
InvalidPoint,
MissingIndex,
InvalidSeed,
}
// Deterministic derivation of the key using secp256k1 elliptic curve.
// Derivation can be either hardened or not.
// For hardened derivation, pass u32 index at least 2^31 or custom Derivation::Hard(T) enum
//
// Can panic if passed `private_key` is not a valid secp256k1 private key
// (outside of (0..curve_order()]) field
pub fn
|
<T>(private_key: H256, chain_code: H256, index: Derivation<T>) -> (H256, H256) where T: Label {
match index {
Derivation::Soft(index) => private_soft(private_key, chain_code, index),
Derivation::Hard(index) => private_hard(private_key, chain_code, index),
}
}
fn hmac_pair(data: &[u8], private_key: H256, chain_code: H256) -> (H256, H256) {
let private: U256 = private_key.into();
// produces 512-bit derived hmac (I)
let mut hmac = Hmac::new(Sha512::new(), &*chain_code);
let mut i_512 = [0u8; 64];
hmac.input(&data[..]);
hmac.raw_result(&mut i_512);
// left most 256 bits are later added to original private key
let hmac_key: U256 = H256::from_slice(&i_512[0..32]).into();
// right most 256 bits are new chain code for later derivations
let next_chain_code = H256::from(&i_512[32..64]);
let child_key = private_add(hmac_key, private).into();
(child_key, next_chain_code)
}
// Can panic if passed `private_key` is not a valid secp256k1 private key
// (outside of (0..curve_order()]) field
fn private_soft<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
let mut data = vec![0u8; 33 + T::len()];
let sec_private = SecretKey::from_slice(&SECP256K1, &*private_key)
.expect("Caller should provide valid private key");
let sec_public = PublicKey::from_secret_key(&SECP256K1, &sec_private)
.expect("Caller should provide valid private key");
let public_serialized = sec_public.serialize_vec(&SECP256K1, true);
// curve point (compressed public key) -- index
// 0.33 -- 33..end
data[0..33].copy_from_slice(&public_serialized);
index.store(&mut data[33..]);
hmac_pair(&data, private_key, chain_code)
}
// Deterministic derivation of the key using secp256k1 elliptic curve
// This is hardened derivation and does not allow to associate
// corresponding public keys of the original and derived private keys
fn private_hard<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
let mut data: Vec<u8> = vec![0u8; 33 + T::len()];
let private: U256 = private_key.into();
// 0x00 (padding) -- private_key -- index
// 0 -- 1..33 -- 33..end
private.to_big_endian(&mut data[1..33]);
index.store(&mut data[33..(33 + T::len())]);
hmac_pair(&data, private_key, chain_code)
}
fn private_add(k1: U256, k2: U256) -> U256 {
let sum = U512::from(k1) + U512::from(k2);
modulo(sum, curve_order())
}
// todo: surely can be optimized
fn modulo(u1: U512, u2: U256) -> U256 {
let dv = u1 / U512::from(u2);
let md = u1 - (dv * U512::from(u2));
md.into()
}
pub fn public<T>(public_key: H512, chain_code: H256, derivation: Derivation<T>) -> Result<(H512, H256), Error> where T: Label {
let index = match derivation {
Derivation::Soft(index) => index,
Derivation::Hard(_) => { return Err(Error::InvalidHardenedUse); }
};
let mut public_sec_raw = [0u8; 65];
public_sec_raw[0] = 4;
public_sec_raw[1..65].copy_from_slice(&*public_key);
let public_sec = PublicKey::from_slice(&SECP256K1, &public_sec_raw).map_err(|_| Error::InvalidPoint)?;
let public_serialized = public_sec.serialize_vec(&SECP256K1, true);
let mut data = vec![0u8; 33 + T::len()];
// curve point (compressed public key) -- index
// 0.33 -- 33..end
data[0..33].copy_from_slice(&public_serialized);
index.store(&mut data[33..(33 + T::len())]);
// HMAC512SHA produces [derived private(256); new chain code(256)]
let mut hmac = Hmac::new(Sha512::new(), &*chain_code);
let mut i_512 = [0u8; 64];
hmac.input(&data[..]);
hmac.raw_result(&mut i_512);
let new_private = H256::from(&i_512[0..32]);
let new_chain_code = H256::from(&i_512[32..64]);
// Generated private key can (extremely rarely) be out of secp256k1 key field
if curve_order() <= new_private.clone().into() { return Err(Error::MissingIndex); }
let new_private_sec = SecretKey::from_slice(&SECP256K1, &*new_private)
.expect("Private key belongs to the field [0..CURVE_ORDER) (checked above); So initializing can never fail; qed");
let mut new_public = PublicKey::from_secret_key(&SECP256K1, &new_private_sec)
.expect("Valid private key produces valid public key");
// Adding two points on the elliptic curves (combining two public keys)
new_public.add_assign(&SECP256K1, &public_sec)
.expect("Addition of two valid points produce valid point");
let serialized = new_public.serialize_vec(&SECP256K1, false);
Ok((
H512::from(&serialized[1..65]),
new_chain_code,
))
}
fn sha3(slc: &[u8]) -> H256 {
keccak::Keccak256::keccak256(slc).into()
}
pub fn chain_code(secret: H256) -> H256 {
// 10,000 rounds of sha3
let mut running_sha3 = sha3(&*secret);
for _ in 0..99999 { running_sha3 = sha3(&*running_sha3); }
running_sha3
}
pub fn point(secret: H256) -> Result<H512, Error> {
let sec = SecretKey::from_slice(&SECP256K1, &*secret)
.map_err(|_| Error::InvalidPoint)?;
let public_sec = PublicKey::from_secret_key(&SECP256K1, &sec)
.map_err(|_| Error::InvalidPoint)?;
let serialized = public_sec.serialize_vec(&SECP256K1, false);
Ok(H512::from(&serialized[1..65]))
}
pub fn seed_pair(seed: &[u8]) -> (H256, H256) {
let mut hmac = Hmac::new(Sha512::new(), b"Bitcoin seed");
let mut i_512 = [0u8; 64];
hmac.input(seed);
hmac.raw_result(&mut i_512);
let master_key = H256::from_slice(&i_512[0..32]);
let chain_code = H256::from_slice(&i_512[32..64]);
(master_key, chain_code)
}
}
#[cfg(test)]
mod tests {
use super::{ExtendedSecret, ExtendedPublic, ExtendedKeyPair};
use secret::Secret;
use std::str::FromStr;
use bigint::hash::{H128, H256};
use super::{derivation, Derivation};
fn master_chain_basic() -> (H256, H256) {
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
.expect("Seed should be valid H128")
.to_vec();
derivation::seed_pair(&*seed)
}
fn test_extended<F>(f: F, test_private: H256) where F: Fn(ExtendedSecret) -> ExtendedSecret {
let (private_seed, chain_code) = master_chain_basic();
let extended_secret = ExtendedSecret::with_code(Secret::from_slice(&*private_seed), chain_code);
let derived = f(extended_secret);
assert_eq!(**derived.as_raw(), test_private);
}
#[test]
fn smoky() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into());
// hardened
assert_eq!(&**extended_secret.as_raw(), &*secret);
assert_eq!(&**extended_secret.derive(2147483648.into()).as_raw(), &"0927453daed47839608e414a3738dfad10aed17c459bbd9ab53f89b026c834b6".into());
assert_eq!(&**extended_secret.derive(2147483649.into()).as_raw(), &"44238b6a29c6dcbe9b401364141ba11e2198c289a5fed243a1c11af35c19dc0f".into());
// normal
assert_eq!(&**extended_secret.derive(0.into()).as_raw(), &"bf6a74e3f7b36fc4c96a1e12f31abc817f9f5904f5a8fc27713163d1f0b713f6".into());
assert_eq!(&**extended_secret.derive(1.into()).as_raw(), &"bd4fca9eb1f9c201e9448c1eecd66e302d68d4d313ce895b8c134f512205c1bc".into());
assert_eq!(&**extended_secret.derive(2.into()).as_raw(), &"86932b542d6cab4d9c65490c7ef502d89ecc0e2a5f4852157649e3251e2a3268".into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_public = extended_public.derive(0.into()).expect("First derivation of public should succeed");
assert_eq!(&*derived_public.public(), &"f7b3244c96688f92372bfd4def26dc4151529747bab9f188a4ad34e141d47bd66522ff048bc6f19a0a4429b04318b1a8796c000265b4fa200dae5f6dda92dd94".into());
let keypair = ExtendedKeyPair::with_secret(
Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap(),
064.into(),
);
assert_eq!(&**keypair.derive(2147483648u32.into()).expect("Derivation of keypair should succeed").secret().as_raw(), &"edef54414c03196557cf73774bc97a645c9a1df2164ed34f0c2a78d1375a930c".into());
}
#[test]
fn h256_soft_match() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_secret0 = extended_secret.derive(Derivation::Soft(derivation_secret));
let derived_public0 = extended_public.derive(Derivation::Soft(derivation_secret)).expect("First derivation of public should succeed");
let public_from_secret0 = ExtendedPublic::from_secret(&derived_secret0).expect("Extended public should be created");
assert_eq!(public_from_secret0.public(), derived_public0.public());
}
#[test]
fn h256_hard() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 1u64.into());
assert_eq!(&**extended_secret.derive(Derivation::Hard(derivation_secret)).as_raw(), &"2bc2d696fb744d77ff813b4a1ef0ad64e1e5188b622c54ba917acc5ebc7c5486".into());
}
#[test]
fn match_() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 1.into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_secret0 = extended_secret.derive(0.into());
let derived_public0 = extended_public.derive(0.into()).expect("First derivation of public should succeed");
let public_from_secret0 = ExtendedPublic::from_secret(&derived_secret0).expect("Extended public should be created");
assert_eq!(public_from_secret0.public(), derived_public0.public());
}
#[test]
fn test_seeds() {
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
.expect("Seed should be valid H128")
.to_vec();
/// private key from bitcoin test vector
/// xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs
let test_private = H256::from_str("e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35")
.expect("Private should be decoded ok");
let (private_seed, _) = derivation::seed_pair(&*seed);
assert_eq!(private_seed, test_private);
}
#[test]
fn test_vector_1() {
/// xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7
/// H(0)
test_extended(
|secret| secret.derive(2147483648.into()),
H256::from_str("edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea")
.expect("Private should be decoded ok")
);
}
#[test]
fn test_vector_2() {
/// xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs
/// H(0)/1
test_extended(
|secret| secret.derive(2147483648.into()).derive(1.into()),
H256::from_str("3c6cb8d0f6a264c91ea8b5030fadaa8e538b020f0a387421a12de9319dc93368")
.expect("Private should be decoded ok")
);
}
}
|
private
|
identifier_name
|
extended.rs
|
// Copyright 2015-2017 Parity Technologies (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/>.
//! Extended keys
use secret::Secret;
use Public;
use bigint::hash::H256;
pub use self::derivation::Error as DerivationError;
/// Represents label that can be stored as a part of key derivation
pub trait Label {
/// Length of the data that label occupies
fn len() -> usize;
/// Store label data to the key derivation sequence
/// Must not use more than `len()` bytes from slice
fn store(&self, target: &mut [u8]);
}
impl Label for u32 {
fn len() -> usize { 4 }
fn store(&self, target: &mut [u8]) {
use byteorder::{BigEndian, ByteOrder};
BigEndian::write_u32(&mut target[0..4], *self);
}
}
/// Key derivation over generic label `T`
pub enum Derivation<T: Label> {
/// Soft key derivation (allow proof of parent)
Soft(T),
/// Hard key derivation (does not allow proof of parent)
Hard(T),
}
impl From<u32> for Derivation<u32> {
fn from(index: u32) -> Self {
if index < (2 << 30) {
Derivation::Soft(index)
}
else {
Derivation::Hard(index)
}
}
}
impl Label for H256 {
fn len() -> usize { 32 }
fn store(&self, target: &mut [u8]) {
self.copy_to(&mut target[0..32]);
}
}
/// Extended secret key, allows deterministic derivation of subsequent keys.
pub struct ExtendedSecret {
secret: Secret,
chain_code: H256,
}
impl ExtendedSecret {
/// New extended key from given secret and chain code.
pub fn with_code(secret: Secret, chain_code: H256) -> ExtendedSecret {
ExtendedSecret {
secret: secret,
chain_code: chain_code,
}
}
/// New extended key from given secret with the random chain code.
pub fn new_random(secret: Secret) -> ExtendedSecret {
ExtendedSecret::with_code(secret, H256::random())
}
/// New extended key from given secret.
/// Chain code will be derived from the secret itself (in a deterministic way).
pub fn new(secret: Secret) -> ExtendedSecret {
let chain_code = derivation::chain_code(*secret);
ExtendedSecret::with_code(secret, chain_code)
}
/// Derive new private key
pub fn derive<T>(&self, index: Derivation<T>) -> ExtendedSecret where T: Label {
let (derived_key, next_chain_code) = derivation::private(*self.secret, self.chain_code, index);
let derived_secret = Secret::from_slice(&*derived_key);
ExtendedSecret::with_code(derived_secret, next_chain_code)
}
/// Private key component of the extended key.
pub fn as_raw(&self) -> &Secret {
&self.secret
}
}
/// Extended public key, allows deterministic derivation of subsequent keys.
pub struct ExtendedPublic {
public: Public,
chain_code: H256,
}
impl ExtendedPublic {
/// New extended public key from known parent and chain code
pub fn new(public: Public, chain_code: H256) -> Self {
ExtendedPublic { public: public, chain_code: chain_code }
}
/// Create new extended public key from known secret
pub fn from_secret(secret: &ExtendedSecret) -> Result<Self, DerivationError> {
Ok(
ExtendedPublic::new(
derivation::point(**secret.as_raw())?,
secret.chain_code.clone(),
)
)
}
/// Derive new public key
/// Operation is defined only for index belongs [0..2^31)
pub fn derive<T>(&self, index: Derivation<T>) -> Result<Self, DerivationError> where T: Label {
let (derived_key, next_chain_code) = derivation::public(self.public, self.chain_code, index)?;
Ok(ExtendedPublic::new(derived_key, next_chain_code))
}
pub fn public(&self) -> &Public {
&self.public
}
}
pub struct ExtendedKeyPair {
secret: ExtendedSecret,
public: ExtendedPublic,
}
impl ExtendedKeyPair {
pub fn new(secret: Secret) -> Self {
let extended_secret = ExtendedSecret::new(secret);
let extended_public = ExtendedPublic::from_secret(&extended_secret)
.expect("Valid `Secret` always produces valid public; qed");
ExtendedKeyPair {
secret: extended_secret,
public: extended_public,
}
}
pub fn with_code(secret: Secret, public: Public, chain_code: H256) -> Self {
ExtendedKeyPair {
secret: ExtendedSecret::with_code(secret, chain_code.clone()),
public: ExtendedPublic::new(public, chain_code),
}
}
pub fn with_secret(secret: Secret, chain_code: H256) -> Self {
let extended_secret = ExtendedSecret::with_code(secret, chain_code);
let extended_public = ExtendedPublic::from_secret(&extended_secret)
.expect("Valid `Secret` always produces valid public; qed");
ExtendedKeyPair {
secret: extended_secret,
public: extended_public,
}
}
pub fn with_seed(seed: &[u8]) -> Result<ExtendedKeyPair, DerivationError> {
let (master_key, chain_code) = derivation::seed_pair(seed);
Ok(ExtendedKeyPair::with_secret(
Secret::from_unsafe_slice(&*master_key).map_err(|_| DerivationError::InvalidSeed)?,
chain_code,
))
}
pub fn secret(&self) -> &ExtendedSecret {
&self.secret
}
pub fn public(&self) -> &ExtendedPublic {
&self.public
}
pub fn derive<T>(&self, index: Derivation<T>) -> Result<Self, DerivationError> where T: Label {
let derived = self.secret.derive(index);
Ok(ExtendedKeyPair {
public: ExtendedPublic::from_secret(&derived)?,
secret: derived,
})
}
}
// Derivation functions for private and public keys
// Work is based on BIP0032
// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
mod derivation {
use rcrypto::hmac::Hmac;
use rcrypto::mac::Mac;
use rcrypto::sha2::Sha512;
use bigint::hash::{H512, H256};
use bigint::prelude::{U256, U512};
use secp256k1::key::{SecretKey, PublicKey};
use SECP256K1;
use keccak;
use math::curve_order;
use super::{Label, Derivation};
#[derive(Debug)]
pub enum Error {
InvalidHardenedUse,
InvalidPoint,
MissingIndex,
InvalidSeed,
}
// Deterministic derivation of the key using secp256k1 elliptic curve.
// Derivation can be either hardened or not.
// For hardened derivation, pass u32 index at least 2^31 or custom Derivation::Hard(T) enum
//
// Can panic if passed `private_key` is not a valid secp256k1 private key
// (outside of (0..curve_order()]) field
pub fn private<T>(private_key: H256, chain_code: H256, index: Derivation<T>) -> (H256, H256) where T: Label {
match index {
Derivation::Soft(index) => private_soft(private_key, chain_code, index),
Derivation::Hard(index) => private_hard(private_key, chain_code, index),
}
}
fn hmac_pair(data: &[u8], private_key: H256, chain_code: H256) -> (H256, H256) {
let private: U256 = private_key.into();
// produces 512-bit derived hmac (I)
let mut hmac = Hmac::new(Sha512::new(), &*chain_code);
let mut i_512 = [0u8; 64];
hmac.input(&data[..]);
hmac.raw_result(&mut i_512);
// left most 256 bits are later added to original private key
let hmac_key: U256 = H256::from_slice(&i_512[0..32]).into();
// right most 256 bits are new chain code for later derivations
let next_chain_code = H256::from(&i_512[32..64]);
let child_key = private_add(hmac_key, private).into();
(child_key, next_chain_code)
}
// Can panic if passed `private_key` is not a valid secp256k1 private key
// (outside of (0..curve_order()]) field
fn private_soft<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
let mut data = vec![0u8; 33 + T::len()];
let sec_private = SecretKey::from_slice(&SECP256K1, &*private_key)
.expect("Caller should provide valid private key");
let sec_public = PublicKey::from_secret_key(&SECP256K1, &sec_private)
.expect("Caller should provide valid private key");
let public_serialized = sec_public.serialize_vec(&SECP256K1, true);
// curve point (compressed public key) -- index
// 0.33 -- 33..end
data[0..33].copy_from_slice(&public_serialized);
index.store(&mut data[33..]);
hmac_pair(&data, private_key, chain_code)
}
// Deterministic derivation of the key using secp256k1 elliptic curve
// This is hardened derivation and does not allow to associate
// corresponding public keys of the original and derived private keys
fn private_hard<T>(private_key: H256, chain_code: H256, index: T) -> (H256, H256) where T: Label {
let mut data: Vec<u8> = vec![0u8; 33 + T::len()];
let private: U256 = private_key.into();
// 0x00 (padding) -- private_key -- index
// 0 -- 1..33 -- 33..end
private.to_big_endian(&mut data[1..33]);
index.store(&mut data[33..(33 + T::len())]);
hmac_pair(&data, private_key, chain_code)
}
fn private_add(k1: U256, k2: U256) -> U256 {
let sum = U512::from(k1) + U512::from(k2);
modulo(sum, curve_order())
}
// todo: surely can be optimized
fn modulo(u1: U512, u2: U256) -> U256 {
let dv = u1 / U512::from(u2);
let md = u1 - (dv * U512::from(u2));
md.into()
}
pub fn public<T>(public_key: H512, chain_code: H256, derivation: Derivation<T>) -> Result<(H512, H256), Error> where T: Label {
let index = match derivation {
Derivation::Soft(index) => index,
Derivation::Hard(_) => { return Err(Error::InvalidHardenedUse); }
};
let mut public_sec_raw = [0u8; 65];
public_sec_raw[0] = 4;
public_sec_raw[1..65].copy_from_slice(&*public_key);
let public_sec = PublicKey::from_slice(&SECP256K1, &public_sec_raw).map_err(|_| Error::InvalidPoint)?;
let public_serialized = public_sec.serialize_vec(&SECP256K1, true);
let mut data = vec![0u8; 33 + T::len()];
// curve point (compressed public key) -- index
// 0.33 -- 33..end
data[0..33].copy_from_slice(&public_serialized);
index.store(&mut data[33..(33 + T::len())]);
// HMAC512SHA produces [derived private(256); new chain code(256)]
let mut hmac = Hmac::new(Sha512::new(), &*chain_code);
let mut i_512 = [0u8; 64];
hmac.input(&data[..]);
hmac.raw_result(&mut i_512);
let new_private = H256::from(&i_512[0..32]);
let new_chain_code = H256::from(&i_512[32..64]);
// Generated private key can (extremely rarely) be out of secp256k1 key field
if curve_order() <= new_private.clone().into() { return Err(Error::MissingIndex); }
let new_private_sec = SecretKey::from_slice(&SECP256K1, &*new_private)
.expect("Private key belongs to the field [0..CURVE_ORDER) (checked above); So initializing can never fail; qed");
let mut new_public = PublicKey::from_secret_key(&SECP256K1, &new_private_sec)
.expect("Valid private key produces valid public key");
// Adding two points on the elliptic curves (combining two public keys)
new_public.add_assign(&SECP256K1, &public_sec)
.expect("Addition of two valid points produce valid point");
let serialized = new_public.serialize_vec(&SECP256K1, false);
Ok((
H512::from(&serialized[1..65]),
new_chain_code,
))
}
fn sha3(slc: &[u8]) -> H256 {
keccak::Keccak256::keccak256(slc).into()
}
pub fn chain_code(secret: H256) -> H256 {
// 10,000 rounds of sha3
let mut running_sha3 = sha3(&*secret);
for _ in 0..99999 { running_sha3 = sha3(&*running_sha3); }
running_sha3
}
pub fn point(secret: H256) -> Result<H512, Error> {
let sec = SecretKey::from_slice(&SECP256K1, &*secret)
.map_err(|_| Error::InvalidPoint)?;
let public_sec = PublicKey::from_secret_key(&SECP256K1, &sec)
.map_err(|_| Error::InvalidPoint)?;
let serialized = public_sec.serialize_vec(&SECP256K1, false);
Ok(H512::from(&serialized[1..65]))
}
pub fn seed_pair(seed: &[u8]) -> (H256, H256) {
let mut hmac = Hmac::new(Sha512::new(), b"Bitcoin seed");
let mut i_512 = [0u8; 64];
hmac.input(seed);
hmac.raw_result(&mut i_512);
let master_key = H256::from_slice(&i_512[0..32]);
let chain_code = H256::from_slice(&i_512[32..64]);
(master_key, chain_code)
}
}
#[cfg(test)]
mod tests {
use super::{ExtendedSecret, ExtendedPublic, ExtendedKeyPair};
use secret::Secret;
use std::str::FromStr;
use bigint::hash::{H128, H256};
use super::{derivation, Derivation};
fn master_chain_basic() -> (H256, H256)
|
fn test_extended<F>(f: F, test_private: H256) where F: Fn(ExtendedSecret) -> ExtendedSecret {
let (private_seed, chain_code) = master_chain_basic();
let extended_secret = ExtendedSecret::with_code(Secret::from_slice(&*private_seed), chain_code);
let derived = f(extended_secret);
assert_eq!(**derived.as_raw(), test_private);
}
#[test]
fn smoky() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into());
// hardened
assert_eq!(&**extended_secret.as_raw(), &*secret);
assert_eq!(&**extended_secret.derive(2147483648.into()).as_raw(), &"0927453daed47839608e414a3738dfad10aed17c459bbd9ab53f89b026c834b6".into());
assert_eq!(&**extended_secret.derive(2147483649.into()).as_raw(), &"44238b6a29c6dcbe9b401364141ba11e2198c289a5fed243a1c11af35c19dc0f".into());
// normal
assert_eq!(&**extended_secret.derive(0.into()).as_raw(), &"bf6a74e3f7b36fc4c96a1e12f31abc817f9f5904f5a8fc27713163d1f0b713f6".into());
assert_eq!(&**extended_secret.derive(1.into()).as_raw(), &"bd4fca9eb1f9c201e9448c1eecd66e302d68d4d313ce895b8c134f512205c1bc".into());
assert_eq!(&**extended_secret.derive(2.into()).as_raw(), &"86932b542d6cab4d9c65490c7ef502d89ecc0e2a5f4852157649e3251e2a3268".into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_public = extended_public.derive(0.into()).expect("First derivation of public should succeed");
assert_eq!(&*derived_public.public(), &"f7b3244c96688f92372bfd4def26dc4151529747bab9f188a4ad34e141d47bd66522ff048bc6f19a0a4429b04318b1a8796c000265b4fa200dae5f6dda92dd94".into());
let keypair = ExtendedKeyPair::with_secret(
Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap(),
064.into(),
);
assert_eq!(&**keypair.derive(2147483648u32.into()).expect("Derivation of keypair should succeed").secret().as_raw(), &"edef54414c03196557cf73774bc97a645c9a1df2164ed34f0c2a78d1375a930c".into());
}
#[test]
fn h256_soft_match() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 0u64.into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_secret0 = extended_secret.derive(Derivation::Soft(derivation_secret));
let derived_public0 = extended_public.derive(Derivation::Soft(derivation_secret)).expect("First derivation of public should succeed");
let public_from_secret0 = ExtendedPublic::from_secret(&derived_secret0).expect("Extended public should be created");
assert_eq!(public_from_secret0.public(), derived_public0.public());
}
#[test]
fn h256_hard() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let derivation_secret = H256::from_str("51eaf04f9dbbc1417dc97e789edd0c37ecda88bac490434e367ea81b71b7b015").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 1u64.into());
assert_eq!(&**extended_secret.derive(Derivation::Hard(derivation_secret)).as_raw(), &"2bc2d696fb744d77ff813b4a1ef0ad64e1e5188b622c54ba917acc5ebc7c5486".into());
}
#[test]
fn match_() {
let secret = Secret::from_str("a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65").unwrap();
let extended_secret = ExtendedSecret::with_code(secret.clone(), 1.into());
let extended_public = ExtendedPublic::from_secret(&extended_secret).expect("Extended public should be created");
let derived_secret0 = extended_secret.derive(0.into());
let derived_public0 = extended_public.derive(0.into()).expect("First derivation of public should succeed");
let public_from_secret0 = ExtendedPublic::from_secret(&derived_secret0).expect("Extended public should be created");
assert_eq!(public_from_secret0.public(), derived_public0.public());
}
#[test]
fn test_seeds() {
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
.expect("Seed should be valid H128")
.to_vec();
/// private key from bitcoin test vector
/// xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs
let test_private = H256::from_str("e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35")
.expect("Private should be decoded ok");
let (private_seed, _) = derivation::seed_pair(&*seed);
assert_eq!(private_seed, test_private);
}
#[test]
fn test_vector_1() {
/// xprv9uHRZZhk6KAJC1avXpDAp4MDc3sQKNxDiPvvkX8Br5ngLNv1TxvUxt4cV1rGL5hj6KCesnDYUhd7oWgT11eZG7XnxHrnYeSvkzY7d2bhkJ7
/// H(0)
test_extended(
|secret| secret.derive(2147483648.into()),
H256::from_str("edb2e14f9ee77d26dd93b4ecede8d16ed408ce149b6cd80b0715a2d911a0afea")
.expect("Private should be decoded ok")
);
}
#[test]
fn test_vector_2() {
/// xprv9wTYmMFdV23N2TdNG573QoEsfRrWKQgWeibmLntzniatZvR9BmLnvSxqu53Kw1UmYPxLgboyZQaXwTCg8MSY3H2EU4pWcQDnRnrVA1xe8fs
/// H(0)/1
test_extended(
|secret| secret.derive(2147483648.into()).derive(1.into()),
H256::from_str("3c6cb8d0f6a264c91ea8b5030fadaa8e538b020f0a387421a12de9319dc93368")
.expect("Private should be decoded ok")
);
}
}
|
{
let seed = H128::from_str("000102030405060708090a0b0c0d0e0f")
.expect("Seed should be valid H128")
.to_vec();
derivation::seed_pair(&*seed)
}
|
identifier_body
|
lib.rs
|
#![crate_name = "abc"]
#![crate_type = "lib"]
#![doc(html_root_url = "https://daviddonna.github.io/abc-rs/")]
#![warn(missing_docs)]
//! Runs Karaboga's Artificial Bee Colony algorithm in parallel.
//!
//! To take advantage of this crate, the user must implement the
//! [`Solution`](trait.Solution.html) trait for a type of their creation.
//! A [`Hive`](struct.Hive.html) of the appropriate type can then be built,
//! which will search the solution space for the fittest candidate.
//!
//! # Examples
//!
//! ```
//! // ABC algorithm with canonical (proportionate) fitness scaling
//! // to minimize the 10-dimensional Rastrigin function.
//!
//! extern crate abc;
//! extern crate rand;
//!
//! use std::f32::consts::PI;
//! use rand::{random, Closed01, thread_rng, Rng};
//! use abc::{Context, Candidate, HiveBuilder};
//!
//! const SIZE: usize = 10;
//!
//! #[derive(Clone, Debug)]
//! struct S([f32;SIZE]);
//!
//! // Not really necessary; we're using this mostly to demonstrate usage.
//! struct SBuilder {
//! min: f32,
//! max: f32,
//! a: f32,
//! p_min: f32,
//! p_max: f32,
//! }
//!
//! impl Context for SBuilder {
//! type Solution = [f32;SIZE];
//!
//! fn make(&self) -> [f32;SIZE] {
//! let mut new = [0.0;SIZE];
//! for i in 0..SIZE {
//! let Closed01(x) = random::<Closed01<f32>>();
//! new[i] = (x * (self.max - self.min)) + self.min;
//! }
//! new
//! }
//!
//! fn evaluate_fitness(&self, solution: &[f32;10]) -> f64 {
//! let sum = solution.iter()
//! .map(|x| x.powf(2.0) - self.a * (*x * 2.0 * PI).cos())
//! .fold(0.0, |total, next| total + next);
//! let rastrigin = ((self.a * SIZE as f32) + sum) as f64;
//!
//! // Minimize.
//! if rastrigin >= 0.0 {
//! 1.0 / (1.0 + rastrigin)
//! } else {
//! 1.0 + rastrigin.abs()
//! }
//! }
//!
//! fn explore(&self, field: &[Candidate<[f32;SIZE]>], index: usize) -> [f32;SIZE] {
//! // new[i] = current[i] + Φ * (current[i] - other[i]), where:
//! // phi_min <= Φ <= phi_max
//! // other is a solution, other than current, chosen at random
//!
//! let ref current = field[index].solution;
//! let mut new = [0_f32;SIZE];
//!
//! for i in 0..SIZE {
//! // Choose a different vector at random.
//! let mut rng = thread_rng();
//! let mut index2 = rng.gen_range(0, current.len() - 1);
//! if index2 >= index { index2 += 1; }
//! let ref other = field[index2].solution;
//!
//! let phi = random::<Closed01<f32>>().0 * (self.p_max - self.p_min) + self.p_min;
//! new[i] = current[i] + (phi * (current[i] - other[i]));
//! }
//!
//! new
//! }
//! }
//!
//! fn main() {
//! let mut builder = SBuilder {
//! min: -5.12,
//! max: 5.12,
//! a: 10.0,
//! p_min: -1.0,
//! p_max: 1.0
//! };
//! let hive_builder = HiveBuilder::new(builder, 10);
//! let hive = hive_builder.build().unwrap();
//!
|
//! // As long as it's run some rounds at a time, you can keep running it.
//! let best_after_20 = hive.run_for_rounds(10).unwrap();
//!
//! // The algorithm doesn't guarantee improvement in any number of rounds,
//! // but it always keeps its all-time best.
//! assert!(best_after_20.fitness >= best_after_10.fitness);
//!
//! // The hive can be consumed to create a Receiver object. This can be
//! // iterated over indefinitely, and will receive successive improvements
//! // on the best candidate so far.
//! let mut current_best_fitness = best_after_20.fitness;
//! for new_best in hive.stream().iter().take(3) {
//! // The iterator will start with the best result so far; after that,
//! // each new candidate will be an improvement.
//! assert!(new_best.fitness >= current_best_fitness);
//! current_best_fitness = new_best.fitness;
//! }
//! }
//! ```
mod result;
mod task;
mod context;
mod candidate;
mod hive;
pub mod scaling;
pub use result::{Error, Result};
pub use context::Context;
pub use candidate::Candidate;
pub use hive::{HiveBuilder, Hive};
|
//! // Once built, the hive can be run for a number of rounds.
//! let best_after_10 = hive.run_for_rounds(10).unwrap();
//!
|
random_line_split
|
no-send-res-ports.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.
#![feature(unsafe_destructor)]
use std::thread::Thread;
use std::rc::Rc;
#[derive(Debug)]
struct Port<T>(Rc<T>);
fn main() {
#[derive(Debug)]
struct foo {
_x: Port<()>,
}
#[unsafe_destructor]
impl Drop for foo {
fn drop(&mut self) {}
}
fn
|
(x: Port<()>) -> foo {
foo {
_x: x
}
}
let x = foo(Port(Rc::new(())));
Thread::spawn(move|| {
//~^ ERROR `core::marker::Send` is not implemented
let y = x;
println!("{:?}", y);
});
}
|
foo
|
identifier_name
|
no-send-res-ports.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.
#![feature(unsafe_destructor)]
use std::thread::Thread;
use std::rc::Rc;
#[derive(Debug)]
struct Port<T>(Rc<T>);
fn main() {
#[derive(Debug)]
struct foo {
_x: Port<()>,
}
#[unsafe_destructor]
impl Drop for foo {
fn drop(&mut self) {}
}
fn foo(x: Port<()>) -> foo {
foo {
_x: x
}
}
let x = foo(Port(Rc::new(())));
Thread::spawn(move|| {
//~^ ERROR `core::marker::Send` is not implemented
|
});
}
|
let y = x;
println!("{:?}", y);
|
random_line_split
|
no-send-res-ports.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.
#![feature(unsafe_destructor)]
use std::thread::Thread;
use std::rc::Rc;
#[derive(Debug)]
struct Port<T>(Rc<T>);
fn main()
|
//~^ ERROR `core::marker::Send` is not implemented
let y = x;
println!("{:?}", y);
});
}
|
{
#[derive(Debug)]
struct foo {
_x: Port<()>,
}
#[unsafe_destructor]
impl Drop for foo {
fn drop(&mut self) {}
}
fn foo(x: Port<()>) -> foo {
foo {
_x: x
}
}
let x = foo(Port(Rc::new(())));
Thread::spawn(move|| {
|
identifier_body
|
mod.rs
|
// Copyright 2015 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
|
// Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
/// FileMetadata
pub mod file_metadata;
/// DirectoryKey
pub mod directory_key;
/// DirectoryMetadata
pub mod directory_metadata;
|
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the
|
random_line_split
|
lib.rs
|
//! `Cask` is a key-value store backed by a log-structured hash table which is inspired by
//! [bitcask](https://github.com/basho/bitcask/).
//!
//! Keys are indexed in a `HashMap` and values are written to an append-only log. To avoid the log
//! from getting filled with stale data (updated/deleted entries) a compaction process runs in the
//! background which rewrites the log by removing dead entries and merging log files.
//!
//! # Examples
//!
//! ```rust,no_run
//! use cask::{CaskOptions, SyncStrategy};
//! use cask::errors::Result;
//!
//! fn example() -> Result<()> {
//! let cask = CaskOptions::default()
//! .compaction_check_frequency(1200)
//! .sync(SyncStrategy::Interval(5000))
//! .max_file_size(1024 * 1024 * 1024)
//! .open("cask.db")?;
//!
//! let key = "hello";
//! let value = "world";
//!
//! cask.put(key, value)?;
//! cask.get(key)?;
//! cask.delete(key)?;
//!
//! Ok(())
//! }
//! ```
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log as logrs;
extern crate byteorder;
extern crate fs2;
extern crate regex;
extern crate time;
extern crate twox_hash;
mod cask;
mod data;
pub mod errors;
mod file_pool;
mod log;
mod stats;
|
mod util;
pub use cask::{Cask, CaskOptions, SyncStrategy};
|
random_line_split
|
|
common.rs
|
use std::ffi::CString;
use std::os::raw::c_char;
pub mod nom7 {
use nom7::bytes::streaming::{tag, take_until};
use nom7::error::{Error, ParseError};
use nom7::ErrorConvert;
use nom7::IResult;
/// Reimplementation of `take_until_and_consume` for nom 7
///
/// `take_until` does not consume the matched tag, and
/// `take_until_and_consume` was removed in nom 7. This function
/// provides an implementation (specialized for `&[u8]`).
pub fn take_until_and_consume<'a, E: ParseError<&'a [u8]>>(t: &'a [u8])
-> impl Fn(&'a [u8]) -> IResult<&'a [u8], &'a [u8], E>
{
move |i: &'a [u8]| {
let (i, res) = take_until(t)(i)?;
let (i, _) = tag(t)(i)?;
Ok((i, res))
}
}
/// Specialized version of the nom 7 `bits` combinator
///
/// The `bits combinator has trouble inferring the transient error type
/// used by the tuple parser, because the function is generic and any
/// error type would be valid.
/// Use an explicit error type (as described in
/// https://docs.rs/nom/7.1.0/nom/bits/fn.bits.html) to solve this problem, and
/// specialize this function for `&[u8]`.
pub fn bits<'a, O, E, P>(parser: P) -> impl FnMut(&'a [u8]) -> IResult<&'a [u8], O, E>
where
E: ParseError<&'a [u8]>,
Error<(&'a [u8], usize)>: ErrorConvert<E>,
P: FnMut((&'a [u8], usize)) -> IResult<(&'a [u8], usize), O, Error<(&'a [u8], usize)>>,
{
// use full path to disambiguate nom `bits` from this current function name
nom7::bits::bits(parser)
}
}
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {
if $item {
panic!("Condition check failed");
}
};
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {
// Wrap in a conditional to prevent unreachable code warning in caller.
if true {
panic!($msg);
}
};
);
/// Convert a String to C-compatible string
///
/// This function will consume the provided data and use the underlying bytes to construct a new
/// string, ensuring that there is a trailing 0 byte. This trailing 0 byte will be appended by this
/// function; the provided data should *not* contain any 0 bytes in it.
///
/// Returns a valid pointer, or NULL
pub fn rust_string_to_c(s: String) -> *mut c_char {
CString::new(s)
.map(|c_str| c_str.into_raw())
.unwrap_or(std::ptr::null_mut())
}
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`)
///
/// # Safety
///
/// s must be allocated by rust, using `CString::new`
#[no_mangle]
pub unsafe extern "C" fn rs_cstring_free(s: *mut c_char) {
if s.is_null()
|
drop(CString::from_raw(s));
}
/// Convert an u8-array of data into a hexadecimal representation
pub fn to_hex(input: &[u8]) -> String {
static CHARS: &'static [u8] = b"0123456789abcdef";
return input.iter().map(
|b| vec![char::from(CHARS[(b >> 4) as usize]), char::from(CHARS[(b & 0xf) as usize])]
).flatten().collect();
}
|
{
return;
}
|
conditional_block
|
common.rs
|
use std::ffi::CString;
use std::os::raw::c_char;
pub mod nom7 {
use nom7::bytes::streaming::{tag, take_until};
use nom7::error::{Error, ParseError};
use nom7::ErrorConvert;
use nom7::IResult;
/// Reimplementation of `take_until_and_consume` for nom 7
///
/// `take_until` does not consume the matched tag, and
/// `take_until_and_consume` was removed in nom 7. This function
/// provides an implementation (specialized for `&[u8]`).
pub fn take_until_and_consume<'a, E: ParseError<&'a [u8]>>(t: &'a [u8])
-> impl Fn(&'a [u8]) -> IResult<&'a [u8], &'a [u8], E>
{
move |i: &'a [u8]| {
let (i, res) = take_until(t)(i)?;
let (i, _) = tag(t)(i)?;
Ok((i, res))
}
}
/// Specialized version of the nom 7 `bits` combinator
///
/// The `bits combinator has trouble inferring the transient error type
/// used by the tuple parser, because the function is generic and any
/// error type would be valid.
/// Use an explicit error type (as described in
/// https://docs.rs/nom/7.1.0/nom/bits/fn.bits.html) to solve this problem, and
/// specialize this function for `&[u8]`.
pub fn bits<'a, O, E, P>(parser: P) -> impl FnMut(&'a [u8]) -> IResult<&'a [u8], O, E>
where
E: ParseError<&'a [u8]>,
Error<(&'a [u8], usize)>: ErrorConvert<E>,
P: FnMut((&'a [u8], usize)) -> IResult<(&'a [u8], usize), O, Error<(&'a [u8], usize)>>,
{
// use full path to disambiguate nom `bits` from this current function name
nom7::bits::bits(parser)
}
}
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {
if $item {
panic!("Condition check failed");
}
};
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {
// Wrap in a conditional to prevent unreachable code warning in caller.
if true {
panic!($msg);
}
};
);
/// Convert a String to C-compatible string
///
/// This function will consume the provided data and use the underlying bytes to construct a new
/// string, ensuring that there is a trailing 0 byte. This trailing 0 byte will be appended by this
/// function; the provided data should *not* contain any 0 bytes in it.
///
/// Returns a valid pointer, or NULL
pub fn rust_string_to_c(s: String) -> *mut c_char {
CString::new(s)
.map(|c_str| c_str.into_raw())
.unwrap_or(std::ptr::null_mut())
}
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`)
///
/// # Safety
///
/// s must be allocated by rust, using `CString::new`
#[no_mangle]
pub unsafe extern "C" fn
|
(s: *mut c_char) {
if s.is_null() {
return;
}
drop(CString::from_raw(s));
}
/// Convert an u8-array of data into a hexadecimal representation
pub fn to_hex(input: &[u8]) -> String {
static CHARS: &'static [u8] = b"0123456789abcdef";
return input.iter().map(
|b| vec![char::from(CHARS[(b >> 4) as usize]), char::from(CHARS[(b & 0xf) as usize])]
).flatten().collect();
}
|
rs_cstring_free
|
identifier_name
|
common.rs
|
use std::ffi::CString;
use std::os::raw::c_char;
pub mod nom7 {
use nom7::bytes::streaming::{tag, take_until};
use nom7::error::{Error, ParseError};
use nom7::ErrorConvert;
use nom7::IResult;
/// Reimplementation of `take_until_and_consume` for nom 7
///
/// `take_until` does not consume the matched tag, and
/// `take_until_and_consume` was removed in nom 7. This function
/// provides an implementation (specialized for `&[u8]`).
pub fn take_until_and_consume<'a, E: ParseError<&'a [u8]>>(t: &'a [u8])
-> impl Fn(&'a [u8]) -> IResult<&'a [u8], &'a [u8], E>
{
move |i: &'a [u8]| {
let (i, res) = take_until(t)(i)?;
let (i, _) = tag(t)(i)?;
Ok((i, res))
}
}
/// Specialized version of the nom 7 `bits` combinator
///
/// The `bits combinator has trouble inferring the transient error type
/// used by the tuple parser, because the function is generic and any
/// error type would be valid.
/// Use an explicit error type (as described in
/// https://docs.rs/nom/7.1.0/nom/bits/fn.bits.html) to solve this problem, and
/// specialize this function for `&[u8]`.
pub fn bits<'a, O, E, P>(parser: P) -> impl FnMut(&'a [u8]) -> IResult<&'a [u8], O, E>
where
E: ParseError<&'a [u8]>,
Error<(&'a [u8], usize)>: ErrorConvert<E>,
P: FnMut((&'a [u8], usize)) -> IResult<(&'a [u8], usize), O, Error<(&'a [u8], usize)>>,
|
}
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {
if $item {
panic!("Condition check failed");
}
};
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {
// Wrap in a conditional to prevent unreachable code warning in caller.
if true {
panic!($msg);
}
};
);
/// Convert a String to C-compatible string
///
/// This function will consume the provided data and use the underlying bytes to construct a new
/// string, ensuring that there is a trailing 0 byte. This trailing 0 byte will be appended by this
/// function; the provided data should *not* contain any 0 bytes in it.
///
/// Returns a valid pointer, or NULL
pub fn rust_string_to_c(s: String) -> *mut c_char {
CString::new(s)
.map(|c_str| c_str.into_raw())
.unwrap_or(std::ptr::null_mut())
}
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`)
///
/// # Safety
///
/// s must be allocated by rust, using `CString::new`
#[no_mangle]
pub unsafe extern "C" fn rs_cstring_free(s: *mut c_char) {
if s.is_null() {
return;
}
drop(CString::from_raw(s));
}
/// Convert an u8-array of data into a hexadecimal representation
pub fn to_hex(input: &[u8]) -> String {
static CHARS: &'static [u8] = b"0123456789abcdef";
return input.iter().map(
|b| vec![char::from(CHARS[(b >> 4) as usize]), char::from(CHARS[(b & 0xf) as usize])]
).flatten().collect();
}
|
{
// use full path to disambiguate nom `bits` from this current function name
nom7::bits::bits(parser)
}
|
identifier_body
|
common.rs
|
use std::ffi::CString;
use std::os::raw::c_char;
pub mod nom7 {
use nom7::bytes::streaming::{tag, take_until};
|
/// Reimplementation of `take_until_and_consume` for nom 7
///
/// `take_until` does not consume the matched tag, and
/// `take_until_and_consume` was removed in nom 7. This function
/// provides an implementation (specialized for `&[u8]`).
pub fn take_until_and_consume<'a, E: ParseError<&'a [u8]>>(t: &'a [u8])
-> impl Fn(&'a [u8]) -> IResult<&'a [u8], &'a [u8], E>
{
move |i: &'a [u8]| {
let (i, res) = take_until(t)(i)?;
let (i, _) = tag(t)(i)?;
Ok((i, res))
}
}
/// Specialized version of the nom 7 `bits` combinator
///
/// The `bits combinator has trouble inferring the transient error type
/// used by the tuple parser, because the function is generic and any
/// error type would be valid.
/// Use an explicit error type (as described in
/// https://docs.rs/nom/7.1.0/nom/bits/fn.bits.html) to solve this problem, and
/// specialize this function for `&[u8]`.
pub fn bits<'a, O, E, P>(parser: P) -> impl FnMut(&'a [u8]) -> IResult<&'a [u8], O, E>
where
E: ParseError<&'a [u8]>,
Error<(&'a [u8], usize)>: ErrorConvert<E>,
P: FnMut((&'a [u8], usize)) -> IResult<(&'a [u8], usize), O, Error<(&'a [u8], usize)>>,
{
// use full path to disambiguate nom `bits` from this current function name
nom7::bits::bits(parser)
}
}
#[macro_export]
macro_rules! take_until_and_consume (
( $i:expr, $needle:expr ) => (
{
let input: &[u8] = $i;
let (rem, res) = ::nom::take_until!(input, $needle)?;
let (rem, _) = ::nom::take!(rem, $needle.len())?;
Ok((rem, res))
}
);
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_bug_on (
($item:expr) => {
if $item {
panic!("Condition check failed");
}
};
);
#[cfg(not(feature = "debug-validate"))]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {};
);
#[cfg(feature = "debug-validate")]
#[macro_export]
macro_rules! debug_validate_fail (
($msg:expr) => {
// Wrap in a conditional to prevent unreachable code warning in caller.
if true {
panic!($msg);
}
};
);
/// Convert a String to C-compatible string
///
/// This function will consume the provided data and use the underlying bytes to construct a new
/// string, ensuring that there is a trailing 0 byte. This trailing 0 byte will be appended by this
/// function; the provided data should *not* contain any 0 bytes in it.
///
/// Returns a valid pointer, or NULL
pub fn rust_string_to_c(s: String) -> *mut c_char {
CString::new(s)
.map(|c_str| c_str.into_raw())
.unwrap_or(std::ptr::null_mut())
}
/// Free a CString allocated by Rust (for ex. using `rust_string_to_c`)
///
/// # Safety
///
/// s must be allocated by rust, using `CString::new`
#[no_mangle]
pub unsafe extern "C" fn rs_cstring_free(s: *mut c_char) {
if s.is_null() {
return;
}
drop(CString::from_raw(s));
}
/// Convert an u8-array of data into a hexadecimal representation
pub fn to_hex(input: &[u8]) -> String {
static CHARS: &'static [u8] = b"0123456789abcdef";
return input.iter().map(
|b| vec![char::from(CHARS[(b >> 4) as usize]), char::from(CHARS[(b & 0xf) as usize])]
).flatten().collect();
}
|
use nom7::error::{Error, ParseError};
use nom7::ErrorConvert;
use nom7::IResult;
|
random_line_split
|
io.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 std::rt::io::{io_error, IoError};
/// Helper for catching an I/O error and wrapping it in a Result object. The
/// return result will be the last I/O error that happened or the result of the
/// closure if no error occurred.
///
/// FIXME: This is a copy of std::rt::io::result which doesn't exist yet in our
/// version of Rust. We should switch after the next Rust upgrade.
pub fn
|
<T>(cb: &fn() -> T) -> Result<T, IoError> {
let mut err = None;
let ret = io_error::cond.trap(|e| err = Some(e)).inside(cb);
match err {
Some(e) => Err(e),
None => Ok(ret),
}
}
|
result
|
identifier_name
|
io.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 std::rt::io::{io_error, IoError};
/// Helper for catching an I/O error and wrapping it in a Result object. The
/// return result will be the last I/O error that happened or the result of the
/// closure if no error occurred.
///
/// FIXME: This is a copy of std::rt::io::result which doesn't exist yet in our
/// version of Rust. We should switch after the next Rust upgrade.
pub fn result<T>(cb: &fn() -> T) -> Result<T, IoError>
|
{
let mut err = None;
let ret = io_error::cond.trap(|e| err = Some(e)).inside(cb);
match err {
Some(e) => Err(e),
None => Ok(ret),
}
}
|
identifier_body
|
|
io.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 std::rt::io::{io_error, IoError};
/// Helper for catching an I/O error and wrapping it in a Result object. The
/// return result will be the last I/O error that happened or the result of the
/// closure if no error occurred.
///
/// FIXME: This is a copy of std::rt::io::result which doesn't exist yet in our
/// version of Rust. We should switch after the next Rust upgrade.
pub fn result<T>(cb: &fn() -> T) -> Result<T, IoError> {
let mut err = None;
let ret = io_error::cond.trap(|e| err = Some(e)).inside(cb);
|
}
|
match err {
Some(e) => Err(e),
None => Ok(ret),
}
|
random_line_split
|
texture.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Texture creation and modification.
//!
//! "Texture" is an overloaded term. In gfx-rs, a texture consists of two
//! separate pieces of information: image storage description (which is
//! immutable for a single texture object), and image data. To actually use a
//! texture, a "sampler" is needed, which provides a way of accessing the
//! image data. Image data consists of an array of "texture elements", or
//! texels.
use std::error::Error;
use std::{fmt, cmp, hash};
use memory::{Bind, Usage};
use {format, state, target, Resources};
pub use target::{Layer, Level};
/// Maximum accessible mipmap level of a texture.
pub const MAX_LEVEL: Level = 15;
/// Untyped texture
#[derive(Debug)]
pub struct Raw<R: Resources> {
resource: R::Texture,
info: Info,
}
impl<R: Resources> Raw<R> {
#[doc(hidden)]
pub fn new(resource: R::Texture, info: Info) -> Self {
Raw {
resource: resource,
info: info,
}
}
#[doc(hidden)]
pub fn resource(&self) -> &R::Texture { &self.resource }
/// Get texture descriptor
pub fn get_info(&self) -> &Info { &self.info }
}
impl<R: Resources + cmp::PartialEq> cmp::PartialEq for Raw<R> {
fn eq(&self, other: &Self) -> bool {
self.resource().eq(other.resource())
}
}
impl<R: Resources + cmp::Eq> cmp::Eq for Raw<R> {}
impl<R: Resources + hash::Hash> hash::Hash for Raw<R> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.resource().hash(state);
}
}
/// Pure texture object creation error.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum CreationError {
/// Failed to map a given format to the device.
Format(format::SurfaceType, Option<format::ChannelType>),
/// The kind doesn't support a particular operation.
Kind,
/// Failed to map a given multisampled kind to the device.
Samples(AaMode),
/// Unsupported size in one of the dimensions.
Size(Size),
/// The given data has a different size than the target texture slice.
Data(usize),
/// The mentioned usage mode is not supported
Usage(Usage),
}
impl fmt::Display for CreationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CreationError::Format(surf, chan) => write!(f, "{}: ({:?}, {:?})",
self.description(), surf, chan),
CreationError::Samples(aa) => write!(f, "{}: {:?}", self.description(), aa),
CreationError::Size(size) => write!(f, "{}: {}", self.description(), size),
CreationError::Data(data) => write!(f, "{}: {}", self.description(), data),
CreationError::Usage(usage) => write!(f, "{}: {:?}", self.description(), usage),
_ => write!(f, "{}", self.description()),
}
}
}
impl Error for CreationError {
fn description(&self) -> &str {
match *self {
CreationError::Format(..) => "Failed to map a given format to the device",
CreationError::Kind => "The kind doesn't support a particular operation",
CreationError::Samples(_) => "Failed to map a given multisampled kind to the device",
CreationError::Size(_) => "Unsupported size in one of the dimensions",
CreationError::Data(_) => "The given data has a different size than the target texture slice",
CreationError::Usage(_) => "The expected texture usage mode is not supported by a graphic API",
}
}
}
/// An error associated with selected texture layer.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum LayerError {
/// The source texture kind doesn't support array slices.
NotExpected(Kind),
/// Selected layer is outside of the provided range.
OutOfBounds(target::Layer, target::Layer),
}
impl fmt::Display for LayerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LayerError::NotExpected(kind) => write!(f, "{}: {:?}", self.description(), kind),
LayerError::OutOfBounds(layer, count) => write!(f, "{}: {}/{}", self.description(), layer, count),
}
}
}
impl Error for LayerError {
fn description(&self) -> &str {
match *self {
LayerError::NotExpected(_) => "The source texture kind doesn't support array slices",
LayerError::OutOfBounds(_, _) => "Selected layer is outside of the provided range",
}
}
}
/// Dimension size
pub type Size = u16;
/// Number of bits per component
pub type Bits = u8;
/// Number of MSAA samples
pub type NumSamples = u8;
/// Number of EQAA fragments
pub type NumFragments = u8;
/// Dimensions: width, height, depth, and samples.
pub type Dimensions = (Size, Size, Size, AaMode);
/// Describes the configuration of samples inside each texel.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum AaMode {
/// No additional sample information
Single,
/// MultiSampled Anti-Aliasing (MSAA)
Multi(NumSamples),
/// Coverage Sampling Anti-Aliasing (CSAA/EQAA)
Coverage(NumSamples, NumFragments),
}
impl From<NumSamples> for AaMode {
fn from(ns: NumSamples) -> AaMode {
if ns > 1 {
AaMode::Multi(ns)
} else {
AaMode::Single
}
}
}
impl AaMode {
/// Return the number of actual data fragments stored per texel.
pub fn get_num_fragments(&self) -> NumFragments {
match *self {
AaMode::Single => 1,
AaMode::Multi(n) => n,
AaMode::Coverage(_, nf) => nf,
}
}
/// Return true if the surface has to be resolved before sampling.
pub fn needs_resolve(&self) -> bool {
self.get_num_fragments() > 1
}
}
/// How to [filter](https://en.wikipedia.org/wiki/Texture_filtering) the
/// texture when sampling. They correspond to increasing levels of quality,
/// but also cost. They "layer" on top of each other: it is not possible to
/// have bilinear filtering without mipmapping, for example.
///
/// These names are somewhat poor, in that "bilinear" is really just doing
/// linear filtering on each axis, and it is only bilinear in the case of 2D
/// textures. Similarly for trilinear, it is really Quadralinear(?) for 3D
/// textures. Alas, these names are simple, and match certain intuitions
/// ingrained by many years of public use of inaccurate terminology.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum FilterMethod {
/// The dumbest filtering possible, nearest-neighbor interpolation.
Scale,
/// Add simple mipmapping.
Mipmap,
/// Sample multiple texels within a single mipmap level to increase
/// quality.
Bilinear,
/// Sample multiple texels across two mipmap levels to increase quality.
Trilinear,
/// Anisotropic filtering with a given "max", must be between 1 and 16,
/// inclusive.
Anisotropic(u8)
}
/// The face of a cube texture to do an operation on.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[allow(missing_docs)]
#[repr(u8)]
pub enum CubeFace {
PosX,
NegX,
PosY,
NegY,
PosZ,
NegZ,
}
/// A constant array of cube faces in the order they map to the hardware.
pub const CUBE_FACES: [CubeFace; 6] = [
CubeFace::PosX, CubeFace::NegX,
CubeFace::PosY, CubeFace::NegY,
CubeFace::PosZ, CubeFace::NegZ,
];
/// Specifies the kind of a texture storage to be allocated.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum Kind {
/// A single row of texels.
D1(Size),
/// An array of rows of texels. Equivalent to Texture2D except that texels
/// in a different row are not sampled.
D1Array(Size, Layer),
/// A traditional 2D texture, with rows arranged contiguously.
D2(Size, Size, AaMode),
/// An array of 2D textures. Equivalent to Texture3D except that texels in
/// a different depth level are not sampled.
D2Array(Size, Size, Layer, AaMode),
/// A volume texture, with each 2D layer arranged contiguously.
D3(Size, Size, Size),
/// A set of 6 2D textures, one for each face of a cube.
Cube(Size),
/// An array of Cube textures.
CubeArray(Size, Layer),
}
impl Kind {
/// Get texture dimensions, with 0 values where not applicable.
pub fn get_dimensions(&self) -> Dimensions {
let s0 = AaMode::Single;
match *self {
Kind::D1(w) => (w, 0, 0, s0),
Kind::D1Array(w, a) => (w, 0, a as Size, s0),
Kind::D2(w, h, s) => (w, h, 0, s),
Kind::D2Array(w, h, a, s) => (w, h, a as Size, s),
Kind::D3(w, h, d) => (w, h, d, s0),
Kind::Cube(w) => (w, w, 6, s0),
Kind::CubeArray(w, a) => (w, w, 6 * (a as Size), s0)
}
}
/// Get the dimensionality of a particular mipmap level.
pub fn get_level_dimensions(&self, level: Level) -> Dimensions {
use std::cmp::{max, min};
// unused dimensions must stay 0, all others must be at least 1
let map = |val| max(min(val, 1), val >> min(level, MAX_LEVEL));
let (w, h, d, _) = self.get_dimensions();
(map(w), map(h), map(d), AaMode::Single)
}
/// Count the number of mipmap levels.
pub fn get_num_levels(&self) -> Level {
use std::cmp::max;
let (w, h, d, aa) = self.get_dimensions();
let dominant = max(max(w, h), d);
if aa == AaMode::Single {
(1..).find(|level| dominant>>level <= 1).unwrap()
}else {
1 // anti-aliased textures can't have mipmaps
}
}
/// Return the number of slices for an array, or None for non-arrays.
pub fn get_num_slices(&self) -> Option<Layer> {
match *self {
Kind::D1(..) | Kind::D2(..) | Kind::D3(..) | Kind::Cube(..) => None,
Kind::D1Array(_, a) => Some(a),
Kind::D2Array(_, _, a, _) => Some(a),
Kind::CubeArray(_, a) => Some(a),
}
}
|
/// Check if it's one of the cube kinds.
pub fn is_cube(&self) -> bool {
match *self {
Kind::Cube(_) | Kind::CubeArray(_, _) => true,
_ => false,
}
}
}
/// Describes a subvolume of a texture, which image data can be uploaded into.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct ImageInfoCommon<F> {
pub xoffset: Size,
pub yoffset: Size,
pub zoffset: Size,
pub width: Size,
pub height: Size,
pub depth: Size,
/// Format of each texel.
pub format: F,
/// Which mipmap to select.
pub mipmap: Level,
}
/// New raw image info based on the universal format spec.
pub type RawImageInfo = ImageInfoCommon<format::Format>;
/// New image info based on the universal format spec.
/// The format is suppsed to come from compile-time information
/// as opposed to run-time enum values.
pub type NewImageInfo = ImageInfoCommon<()>;
impl<F> ImageInfoCommon<F> {
/// Get the total number of texels.
pub fn get_texel_count(&self) -> usize {
use std::cmp::max;
max(1, self.width) as usize *
max(1, self.height) as usize *
max(1, self.depth) as usize
}
/// Convert into a differently typed format.
pub fn convert<T>(&self, new_format: T) -> ImageInfoCommon<T> {
ImageInfoCommon {
xoffset: self.xoffset,
yoffset: self.yoffset,
zoffset: self.zoffset,
width: self.width,
height: self.height,
depth: self.depth,
format: new_format,
mipmap: self.mipmap,
}
}
/// Check if it fits inside given dimensions.
pub fn is_inside(&self, (w, h, d, aa): Dimensions) -> bool {
aa == AaMode::Single &&
self.xoffset + self.width <= w &&
self.yoffset + self.height <= h &&
self.zoffset + self.depth <= d
}
}
impl RawImageInfo {
/// Get the total number of bytes.
pub fn get_byte_count(&self) -> usize {
let texel_bytes = self.format.0.get_total_bits() / 8;
self.get_texel_count() * (texel_bytes as usize)
}
}
/// Specifies how texture coordinates outside the range `[0, 1]` are handled.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum WrapMode {
/// Tile the texture. That is, sample the coordinate modulo `1.0`. This is
/// the default.
Tile,
/// Mirror the texture. Like tile, but uses abs(coord) before the modulo.
Mirror,
/// Clamp the texture to the value at `0.0` or `1.0` respectively.
Clamp,
/// Use border color.
Border,
}
/// A wrapper for the LOD level of a texture.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct Lod(i16);
impl From<f32> for Lod {
fn from(v: f32) -> Lod {
Lod((v * 8.0) as i16)
}
}
impl Into<f32> for Lod {
fn into(self) -> f32 {
self.0 as f32 / 8.0
}
}
/// A wrapper for the 8bpp RGBA color, encoded as u32.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct PackedColor(pub u32);
impl From<[f32; 4]> for PackedColor {
fn from(c: [f32; 4]) -> PackedColor {
PackedColor(c.iter().rev().fold(0, |u, &c| {
(u<<8) + (c * 255.0 + 0.5) as u32
}))
}
}
impl Into<[f32; 4]> for PackedColor {
fn into(self) -> [f32; 4] {
let mut out = [0.0; 4];
for i in 0.. 4 {
let byte = (self.0 >> (i<<3)) & 0xFF;
out[i] = (byte as f32 + 0.5) / 255.0;
}
out
}
}
/// Specifies how to sample from a texture.
// TODO: document the details of sampling.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct SamplerInfo {
/// Filter method to use.
pub filter: FilterMethod,
/// Wrapping mode for each of the U, V, and W axis (S, T, and R in OpenGL
/// speak).
pub wrap_mode: (WrapMode, WrapMode, WrapMode),
/// This bias is added to every computed mipmap level (N + lod_bias). For
/// example, if it would select mipmap level 2 and lod_bias is 1, it will
/// use mipmap level 3.
pub lod_bias: Lod,
/// This range is used to clamp LOD level used for sampling.
pub lod_range: (Lod, Lod),
/// Comparison mode, used primary for a shadow map.
pub comparison: Option<state::Comparison>,
/// Border color is used when one of the wrap modes is set to border.
pub border: PackedColor,
}
impl SamplerInfo {
/// Create a new sampler description with a given filter method and wrapping mode, using no LOD
/// modifications.
pub fn new(filter: FilterMethod, wrap: WrapMode) -> SamplerInfo {
SamplerInfo {
filter: filter,
wrap_mode: (wrap, wrap, wrap),
lod_bias: Lod(0),
lod_range: (Lod(-8000), Lod(8000)),
comparison: None,
border: PackedColor(0),
}
}
}
/// Texture storage descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct Info {
pub kind: Kind,
pub levels: Level,
pub format: format::SurfaceType,
pub bind: Bind,
pub usage: Usage,
}
impl Info {
/// Get image info for a given mip.
pub fn to_image_info(&self, mip: Level) -> NewImageInfo {
let (w, h, d, _) = self.kind.get_level_dimensions(mip);
ImageInfoCommon {
xoffset: 0,
yoffset: 0,
zoffset: 0,
width: w,
height: h,
depth: d,
format: (),
mipmap: mip,
}
}
/// Get the raw image info for a given mip and a channel type.
pub fn to_raw_image_info(&self, cty: format::ChannelType, mip: Level) -> RawImageInfo {
let format = format::Format(self.format, cty.into());
self.to_image_info(mip).convert(format)
}
}
/// Texture resource view descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct ResourceDesc {
pub channel: format::ChannelType,
pub layer: Option<Layer>,
pub min: Level,
pub max: Level,
pub swizzle: format::Swizzle,
}
/// Texture render view descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct RenderDesc {
pub channel: format::ChannelType,
pub level: Level,
pub layer: Option<Layer>,
}
bitflags!(
/// Depth-stencil read-only flags
pub flags DepthStencilFlags: u8 {
/// Depth is read-only in the view.
const RO_DEPTH = 0x1,
/// Stencil is read-only in the view.
const RO_STENCIL = 0x2,
/// Both depth and stencil are read-only.
const RO_DEPTH_STENCIL = 0x3,
}
);
/// Texture depth-stencil view descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct DepthStencilDesc {
pub level: Level,
pub layer: Option<Layer>,
pub flags: DepthStencilFlags,
}
impl From<RenderDesc> for DepthStencilDesc {
fn from(rd: RenderDesc) -> DepthStencilDesc {
DepthStencilDesc {
level: rd.level,
layer: rd.layer,
flags: DepthStencilFlags::empty(),
}
}
}
|
random_line_split
|
|
texture.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Texture creation and modification.
//!
//! "Texture" is an overloaded term. In gfx-rs, a texture consists of two
//! separate pieces of information: image storage description (which is
//! immutable for a single texture object), and image data. To actually use a
//! texture, a "sampler" is needed, which provides a way of accessing the
//! image data. Image data consists of an array of "texture elements", or
//! texels.
use std::error::Error;
use std::{fmt, cmp, hash};
use memory::{Bind, Usage};
use {format, state, target, Resources};
pub use target::{Layer, Level};
/// Maximum accessible mipmap level of a texture.
pub const MAX_LEVEL: Level = 15;
/// Untyped texture
#[derive(Debug)]
pub struct Raw<R: Resources> {
resource: R::Texture,
info: Info,
}
impl<R: Resources> Raw<R> {
#[doc(hidden)]
pub fn new(resource: R::Texture, info: Info) -> Self {
Raw {
resource: resource,
info: info,
}
}
#[doc(hidden)]
pub fn resource(&self) -> &R::Texture { &self.resource }
/// Get texture descriptor
pub fn get_info(&self) -> &Info { &self.info }
}
impl<R: Resources + cmp::PartialEq> cmp::PartialEq for Raw<R> {
fn eq(&self, other: &Self) -> bool {
self.resource().eq(other.resource())
}
}
impl<R: Resources + cmp::Eq> cmp::Eq for Raw<R> {}
impl<R: Resources + hash::Hash> hash::Hash for Raw<R> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.resource().hash(state);
}
}
/// Pure texture object creation error.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum CreationError {
/// Failed to map a given format to the device.
Format(format::SurfaceType, Option<format::ChannelType>),
/// The kind doesn't support a particular operation.
Kind,
/// Failed to map a given multisampled kind to the device.
Samples(AaMode),
/// Unsupported size in one of the dimensions.
Size(Size),
/// The given data has a different size than the target texture slice.
Data(usize),
/// The mentioned usage mode is not supported
Usage(Usage),
}
impl fmt::Display for CreationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CreationError::Format(surf, chan) => write!(f, "{}: ({:?}, {:?})",
self.description(), surf, chan),
CreationError::Samples(aa) => write!(f, "{}: {:?}", self.description(), aa),
CreationError::Size(size) => write!(f, "{}: {}", self.description(), size),
CreationError::Data(data) => write!(f, "{}: {}", self.description(), data),
CreationError::Usage(usage) => write!(f, "{}: {:?}", self.description(), usage),
_ => write!(f, "{}", self.description()),
}
}
}
impl Error for CreationError {
fn description(&self) -> &str {
match *self {
CreationError::Format(..) => "Failed to map a given format to the device",
CreationError::Kind => "The kind doesn't support a particular operation",
CreationError::Samples(_) => "Failed to map a given multisampled kind to the device",
CreationError::Size(_) => "Unsupported size in one of the dimensions",
CreationError::Data(_) => "The given data has a different size than the target texture slice",
CreationError::Usage(_) => "The expected texture usage mode is not supported by a graphic API",
}
}
}
/// An error associated with selected texture layer.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum LayerError {
/// The source texture kind doesn't support array slices.
NotExpected(Kind),
/// Selected layer is outside of the provided range.
OutOfBounds(target::Layer, target::Layer),
}
impl fmt::Display for LayerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LayerError::NotExpected(kind) => write!(f, "{}: {:?}", self.description(), kind),
LayerError::OutOfBounds(layer, count) => write!(f, "{}: {}/{}", self.description(), layer, count),
}
}
}
impl Error for LayerError {
fn description(&self) -> &str {
match *self {
LayerError::NotExpected(_) => "The source texture kind doesn't support array slices",
LayerError::OutOfBounds(_, _) => "Selected layer is outside of the provided range",
}
}
}
/// Dimension size
pub type Size = u16;
/// Number of bits per component
pub type Bits = u8;
/// Number of MSAA samples
pub type NumSamples = u8;
/// Number of EQAA fragments
pub type NumFragments = u8;
/// Dimensions: width, height, depth, and samples.
pub type Dimensions = (Size, Size, Size, AaMode);
/// Describes the configuration of samples inside each texel.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum
|
{
/// No additional sample information
Single,
/// MultiSampled Anti-Aliasing (MSAA)
Multi(NumSamples),
/// Coverage Sampling Anti-Aliasing (CSAA/EQAA)
Coverage(NumSamples, NumFragments),
}
impl From<NumSamples> for AaMode {
fn from(ns: NumSamples) -> AaMode {
if ns > 1 {
AaMode::Multi(ns)
} else {
AaMode::Single
}
}
}
impl AaMode {
/// Return the number of actual data fragments stored per texel.
pub fn get_num_fragments(&self) -> NumFragments {
match *self {
AaMode::Single => 1,
AaMode::Multi(n) => n,
AaMode::Coverage(_, nf) => nf,
}
}
/// Return true if the surface has to be resolved before sampling.
pub fn needs_resolve(&self) -> bool {
self.get_num_fragments() > 1
}
}
/// How to [filter](https://en.wikipedia.org/wiki/Texture_filtering) the
/// texture when sampling. They correspond to increasing levels of quality,
/// but also cost. They "layer" on top of each other: it is not possible to
/// have bilinear filtering without mipmapping, for example.
///
/// These names are somewhat poor, in that "bilinear" is really just doing
/// linear filtering on each axis, and it is only bilinear in the case of 2D
/// textures. Similarly for trilinear, it is really Quadralinear(?) for 3D
/// textures. Alas, these names are simple, and match certain intuitions
/// ingrained by many years of public use of inaccurate terminology.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum FilterMethod {
/// The dumbest filtering possible, nearest-neighbor interpolation.
Scale,
/// Add simple mipmapping.
Mipmap,
/// Sample multiple texels within a single mipmap level to increase
/// quality.
Bilinear,
/// Sample multiple texels across two mipmap levels to increase quality.
Trilinear,
/// Anisotropic filtering with a given "max", must be between 1 and 16,
/// inclusive.
Anisotropic(u8)
}
/// The face of a cube texture to do an operation on.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[allow(missing_docs)]
#[repr(u8)]
pub enum CubeFace {
PosX,
NegX,
PosY,
NegY,
PosZ,
NegZ,
}
/// A constant array of cube faces in the order they map to the hardware.
pub const CUBE_FACES: [CubeFace; 6] = [
CubeFace::PosX, CubeFace::NegX,
CubeFace::PosY, CubeFace::NegY,
CubeFace::PosZ, CubeFace::NegZ,
];
/// Specifies the kind of a texture storage to be allocated.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum Kind {
/// A single row of texels.
D1(Size),
/// An array of rows of texels. Equivalent to Texture2D except that texels
/// in a different row are not sampled.
D1Array(Size, Layer),
/// A traditional 2D texture, with rows arranged contiguously.
D2(Size, Size, AaMode),
/// An array of 2D textures. Equivalent to Texture3D except that texels in
/// a different depth level are not sampled.
D2Array(Size, Size, Layer, AaMode),
/// A volume texture, with each 2D layer arranged contiguously.
D3(Size, Size, Size),
/// A set of 6 2D textures, one for each face of a cube.
Cube(Size),
/// An array of Cube textures.
CubeArray(Size, Layer),
}
impl Kind {
/// Get texture dimensions, with 0 values where not applicable.
pub fn get_dimensions(&self) -> Dimensions {
let s0 = AaMode::Single;
match *self {
Kind::D1(w) => (w, 0, 0, s0),
Kind::D1Array(w, a) => (w, 0, a as Size, s0),
Kind::D2(w, h, s) => (w, h, 0, s),
Kind::D2Array(w, h, a, s) => (w, h, a as Size, s),
Kind::D3(w, h, d) => (w, h, d, s0),
Kind::Cube(w) => (w, w, 6, s0),
Kind::CubeArray(w, a) => (w, w, 6 * (a as Size), s0)
}
}
/// Get the dimensionality of a particular mipmap level.
pub fn get_level_dimensions(&self, level: Level) -> Dimensions {
use std::cmp::{max, min};
// unused dimensions must stay 0, all others must be at least 1
let map = |val| max(min(val, 1), val >> min(level, MAX_LEVEL));
let (w, h, d, _) = self.get_dimensions();
(map(w), map(h), map(d), AaMode::Single)
}
/// Count the number of mipmap levels.
pub fn get_num_levels(&self) -> Level {
use std::cmp::max;
let (w, h, d, aa) = self.get_dimensions();
let dominant = max(max(w, h), d);
if aa == AaMode::Single {
(1..).find(|level| dominant>>level <= 1).unwrap()
}else {
1 // anti-aliased textures can't have mipmaps
}
}
/// Return the number of slices for an array, or None for non-arrays.
pub fn get_num_slices(&self) -> Option<Layer> {
match *self {
Kind::D1(..) | Kind::D2(..) | Kind::D3(..) | Kind::Cube(..) => None,
Kind::D1Array(_, a) => Some(a),
Kind::D2Array(_, _, a, _) => Some(a),
Kind::CubeArray(_, a) => Some(a),
}
}
/// Check if it's one of the cube kinds.
pub fn is_cube(&self) -> bool {
match *self {
Kind::Cube(_) | Kind::CubeArray(_, _) => true,
_ => false,
}
}
}
/// Describes a subvolume of a texture, which image data can be uploaded into.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct ImageInfoCommon<F> {
pub xoffset: Size,
pub yoffset: Size,
pub zoffset: Size,
pub width: Size,
pub height: Size,
pub depth: Size,
/// Format of each texel.
pub format: F,
/// Which mipmap to select.
pub mipmap: Level,
}
/// New raw image info based on the universal format spec.
pub type RawImageInfo = ImageInfoCommon<format::Format>;
/// New image info based on the universal format spec.
/// The format is suppsed to come from compile-time information
/// as opposed to run-time enum values.
pub type NewImageInfo = ImageInfoCommon<()>;
impl<F> ImageInfoCommon<F> {
/// Get the total number of texels.
pub fn get_texel_count(&self) -> usize {
use std::cmp::max;
max(1, self.width) as usize *
max(1, self.height) as usize *
max(1, self.depth) as usize
}
/// Convert into a differently typed format.
pub fn convert<T>(&self, new_format: T) -> ImageInfoCommon<T> {
ImageInfoCommon {
xoffset: self.xoffset,
yoffset: self.yoffset,
zoffset: self.zoffset,
width: self.width,
height: self.height,
depth: self.depth,
format: new_format,
mipmap: self.mipmap,
}
}
/// Check if it fits inside given dimensions.
pub fn is_inside(&self, (w, h, d, aa): Dimensions) -> bool {
aa == AaMode::Single &&
self.xoffset + self.width <= w &&
self.yoffset + self.height <= h &&
self.zoffset + self.depth <= d
}
}
impl RawImageInfo {
/// Get the total number of bytes.
pub fn get_byte_count(&self) -> usize {
let texel_bytes = self.format.0.get_total_bits() / 8;
self.get_texel_count() * (texel_bytes as usize)
}
}
/// Specifies how texture coordinates outside the range `[0, 1]` are handled.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum WrapMode {
/// Tile the texture. That is, sample the coordinate modulo `1.0`. This is
/// the default.
Tile,
/// Mirror the texture. Like tile, but uses abs(coord) before the modulo.
Mirror,
/// Clamp the texture to the value at `0.0` or `1.0` respectively.
Clamp,
/// Use border color.
Border,
}
/// A wrapper for the LOD level of a texture.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct Lod(i16);
impl From<f32> for Lod {
fn from(v: f32) -> Lod {
Lod((v * 8.0) as i16)
}
}
impl Into<f32> for Lod {
fn into(self) -> f32 {
self.0 as f32 / 8.0
}
}
/// A wrapper for the 8bpp RGBA color, encoded as u32.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct PackedColor(pub u32);
impl From<[f32; 4]> for PackedColor {
fn from(c: [f32; 4]) -> PackedColor {
PackedColor(c.iter().rev().fold(0, |u, &c| {
(u<<8) + (c * 255.0 + 0.5) as u32
}))
}
}
impl Into<[f32; 4]> for PackedColor {
fn into(self) -> [f32; 4] {
let mut out = [0.0; 4];
for i in 0.. 4 {
let byte = (self.0 >> (i<<3)) & 0xFF;
out[i] = (byte as f32 + 0.5) / 255.0;
}
out
}
}
/// Specifies how to sample from a texture.
// TODO: document the details of sampling.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct SamplerInfo {
/// Filter method to use.
pub filter: FilterMethod,
/// Wrapping mode for each of the U, V, and W axis (S, T, and R in OpenGL
/// speak).
pub wrap_mode: (WrapMode, WrapMode, WrapMode),
/// This bias is added to every computed mipmap level (N + lod_bias). For
/// example, if it would select mipmap level 2 and lod_bias is 1, it will
/// use mipmap level 3.
pub lod_bias: Lod,
/// This range is used to clamp LOD level used for sampling.
pub lod_range: (Lod, Lod),
/// Comparison mode, used primary for a shadow map.
pub comparison: Option<state::Comparison>,
/// Border color is used when one of the wrap modes is set to border.
pub border: PackedColor,
}
impl SamplerInfo {
/// Create a new sampler description with a given filter method and wrapping mode, using no LOD
/// modifications.
pub fn new(filter: FilterMethod, wrap: WrapMode) -> SamplerInfo {
SamplerInfo {
filter: filter,
wrap_mode: (wrap, wrap, wrap),
lod_bias: Lod(0),
lod_range: (Lod(-8000), Lod(8000)),
comparison: None,
border: PackedColor(0),
}
}
}
/// Texture storage descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct Info {
pub kind: Kind,
pub levels: Level,
pub format: format::SurfaceType,
pub bind: Bind,
pub usage: Usage,
}
impl Info {
/// Get image info for a given mip.
pub fn to_image_info(&self, mip: Level) -> NewImageInfo {
let (w, h, d, _) = self.kind.get_level_dimensions(mip);
ImageInfoCommon {
xoffset: 0,
yoffset: 0,
zoffset: 0,
width: w,
height: h,
depth: d,
format: (),
mipmap: mip,
}
}
/// Get the raw image info for a given mip and a channel type.
pub fn to_raw_image_info(&self, cty: format::ChannelType, mip: Level) -> RawImageInfo {
let format = format::Format(self.format, cty.into());
self.to_image_info(mip).convert(format)
}
}
/// Texture resource view descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct ResourceDesc {
pub channel: format::ChannelType,
pub layer: Option<Layer>,
pub min: Level,
pub max: Level,
pub swizzle: format::Swizzle,
}
/// Texture render view descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct RenderDesc {
pub channel: format::ChannelType,
pub level: Level,
pub layer: Option<Layer>,
}
bitflags!(
/// Depth-stencil read-only flags
pub flags DepthStencilFlags: u8 {
/// Depth is read-only in the view.
const RO_DEPTH = 0x1,
/// Stencil is read-only in the view.
const RO_STENCIL = 0x2,
/// Both depth and stencil are read-only.
const RO_DEPTH_STENCIL = 0x3,
}
);
/// Texture depth-stencil view descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct DepthStencilDesc {
pub level: Level,
pub layer: Option<Layer>,
pub flags: DepthStencilFlags,
}
impl From<RenderDesc> for DepthStencilDesc {
fn from(rd: RenderDesc) -> DepthStencilDesc {
DepthStencilDesc {
level: rd.level,
layer: rd.layer,
flags: DepthStencilFlags::empty(),
}
}
}
|
AaMode
|
identifier_name
|
texture.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// 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.
//! Texture creation and modification.
//!
//! "Texture" is an overloaded term. In gfx-rs, a texture consists of two
//! separate pieces of information: image storage description (which is
//! immutable for a single texture object), and image data. To actually use a
//! texture, a "sampler" is needed, which provides a way of accessing the
//! image data. Image data consists of an array of "texture elements", or
//! texels.
use std::error::Error;
use std::{fmt, cmp, hash};
use memory::{Bind, Usage};
use {format, state, target, Resources};
pub use target::{Layer, Level};
/// Maximum accessible mipmap level of a texture.
pub const MAX_LEVEL: Level = 15;
/// Untyped texture
#[derive(Debug)]
pub struct Raw<R: Resources> {
resource: R::Texture,
info: Info,
}
impl<R: Resources> Raw<R> {
#[doc(hidden)]
pub fn new(resource: R::Texture, info: Info) -> Self {
Raw {
resource: resource,
info: info,
}
}
#[doc(hidden)]
pub fn resource(&self) -> &R::Texture { &self.resource }
/// Get texture descriptor
pub fn get_info(&self) -> &Info { &self.info }
}
impl<R: Resources + cmp::PartialEq> cmp::PartialEq for Raw<R> {
fn eq(&self, other: &Self) -> bool {
self.resource().eq(other.resource())
}
}
impl<R: Resources + cmp::Eq> cmp::Eq for Raw<R> {}
impl<R: Resources + hash::Hash> hash::Hash for Raw<R> {
fn hash<H: hash::Hasher>(&self, state: &mut H) {
self.resource().hash(state);
}
}
/// Pure texture object creation error.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum CreationError {
/// Failed to map a given format to the device.
Format(format::SurfaceType, Option<format::ChannelType>),
/// The kind doesn't support a particular operation.
Kind,
/// Failed to map a given multisampled kind to the device.
Samples(AaMode),
/// Unsupported size in one of the dimensions.
Size(Size),
/// The given data has a different size than the target texture slice.
Data(usize),
/// The mentioned usage mode is not supported
Usage(Usage),
}
impl fmt::Display for CreationError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CreationError::Format(surf, chan) => write!(f, "{}: ({:?}, {:?})",
self.description(), surf, chan),
CreationError::Samples(aa) => write!(f, "{}: {:?}", self.description(), aa),
CreationError::Size(size) => write!(f, "{}: {}", self.description(), size),
CreationError::Data(data) => write!(f, "{}: {}", self.description(), data),
CreationError::Usage(usage) => write!(f, "{}: {:?}", self.description(), usage),
_ => write!(f, "{}", self.description()),
}
}
}
impl Error for CreationError {
fn description(&self) -> &str {
match *self {
CreationError::Format(..) => "Failed to map a given format to the device",
CreationError::Kind => "The kind doesn't support a particular operation",
CreationError::Samples(_) => "Failed to map a given multisampled kind to the device",
CreationError::Size(_) => "Unsupported size in one of the dimensions",
CreationError::Data(_) => "The given data has a different size than the target texture slice",
CreationError::Usage(_) => "The expected texture usage mode is not supported by a graphic API",
}
}
}
/// An error associated with selected texture layer.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum LayerError {
/// The source texture kind doesn't support array slices.
NotExpected(Kind),
/// Selected layer is outside of the provided range.
OutOfBounds(target::Layer, target::Layer),
}
impl fmt::Display for LayerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
LayerError::NotExpected(kind) => write!(f, "{}: {:?}", self.description(), kind),
LayerError::OutOfBounds(layer, count) => write!(f, "{}: {}/{}", self.description(), layer, count),
}
}
}
impl Error for LayerError {
fn description(&self) -> &str {
match *self {
LayerError::NotExpected(_) => "The source texture kind doesn't support array slices",
LayerError::OutOfBounds(_, _) => "Selected layer is outside of the provided range",
}
}
}
/// Dimension size
pub type Size = u16;
/// Number of bits per component
pub type Bits = u8;
/// Number of MSAA samples
pub type NumSamples = u8;
/// Number of EQAA fragments
pub type NumFragments = u8;
/// Dimensions: width, height, depth, and samples.
pub type Dimensions = (Size, Size, Size, AaMode);
/// Describes the configuration of samples inside each texel.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum AaMode {
/// No additional sample information
Single,
/// MultiSampled Anti-Aliasing (MSAA)
Multi(NumSamples),
/// Coverage Sampling Anti-Aliasing (CSAA/EQAA)
Coverage(NumSamples, NumFragments),
}
impl From<NumSamples> for AaMode {
fn from(ns: NumSamples) -> AaMode {
if ns > 1 {
AaMode::Multi(ns)
} else {
AaMode::Single
}
}
}
impl AaMode {
/// Return the number of actual data fragments stored per texel.
pub fn get_num_fragments(&self) -> NumFragments {
match *self {
AaMode::Single => 1,
AaMode::Multi(n) => n,
AaMode::Coverage(_, nf) => nf,
}
}
/// Return true if the surface has to be resolved before sampling.
pub fn needs_resolve(&self) -> bool {
self.get_num_fragments() > 1
}
}
/// How to [filter](https://en.wikipedia.org/wiki/Texture_filtering) the
/// texture when sampling. They correspond to increasing levels of quality,
/// but also cost. They "layer" on top of each other: it is not possible to
/// have bilinear filtering without mipmapping, for example.
///
/// These names are somewhat poor, in that "bilinear" is really just doing
/// linear filtering on each axis, and it is only bilinear in the case of 2D
/// textures. Similarly for trilinear, it is really Quadralinear(?) for 3D
/// textures. Alas, these names are simple, and match certain intuitions
/// ingrained by many years of public use of inaccurate terminology.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum FilterMethod {
/// The dumbest filtering possible, nearest-neighbor interpolation.
Scale,
/// Add simple mipmapping.
Mipmap,
/// Sample multiple texels within a single mipmap level to increase
/// quality.
Bilinear,
/// Sample multiple texels across two mipmap levels to increase quality.
Trilinear,
/// Anisotropic filtering with a given "max", must be between 1 and 16,
/// inclusive.
Anisotropic(u8)
}
/// The face of a cube texture to do an operation on.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
#[allow(missing_docs)]
#[repr(u8)]
pub enum CubeFace {
PosX,
NegX,
PosY,
NegY,
PosZ,
NegZ,
}
/// A constant array of cube faces in the order they map to the hardware.
pub const CUBE_FACES: [CubeFace; 6] = [
CubeFace::PosX, CubeFace::NegX,
CubeFace::PosY, CubeFace::NegY,
CubeFace::PosZ, CubeFace::NegZ,
];
/// Specifies the kind of a texture storage to be allocated.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum Kind {
/// A single row of texels.
D1(Size),
/// An array of rows of texels. Equivalent to Texture2D except that texels
/// in a different row are not sampled.
D1Array(Size, Layer),
/// A traditional 2D texture, with rows arranged contiguously.
D2(Size, Size, AaMode),
/// An array of 2D textures. Equivalent to Texture3D except that texels in
/// a different depth level are not sampled.
D2Array(Size, Size, Layer, AaMode),
/// A volume texture, with each 2D layer arranged contiguously.
D3(Size, Size, Size),
/// A set of 6 2D textures, one for each face of a cube.
Cube(Size),
/// An array of Cube textures.
CubeArray(Size, Layer),
}
impl Kind {
/// Get texture dimensions, with 0 values where not applicable.
pub fn get_dimensions(&self) -> Dimensions {
let s0 = AaMode::Single;
match *self {
Kind::D1(w) => (w, 0, 0, s0),
Kind::D1Array(w, a) => (w, 0, a as Size, s0),
Kind::D2(w, h, s) => (w, h, 0, s),
Kind::D2Array(w, h, a, s) => (w, h, a as Size, s),
Kind::D3(w, h, d) => (w, h, d, s0),
Kind::Cube(w) => (w, w, 6, s0),
Kind::CubeArray(w, a) => (w, w, 6 * (a as Size), s0)
}
}
/// Get the dimensionality of a particular mipmap level.
pub fn get_level_dimensions(&self, level: Level) -> Dimensions {
use std::cmp::{max, min};
// unused dimensions must stay 0, all others must be at least 1
let map = |val| max(min(val, 1), val >> min(level, MAX_LEVEL));
let (w, h, d, _) = self.get_dimensions();
(map(w), map(h), map(d), AaMode::Single)
}
/// Count the number of mipmap levels.
pub fn get_num_levels(&self) -> Level {
use std::cmp::max;
let (w, h, d, aa) = self.get_dimensions();
let dominant = max(max(w, h), d);
if aa == AaMode::Single {
(1..).find(|level| dominant>>level <= 1).unwrap()
}else {
1 // anti-aliased textures can't have mipmaps
}
}
/// Return the number of slices for an array, or None for non-arrays.
pub fn get_num_slices(&self) -> Option<Layer>
|
/// Check if it's one of the cube kinds.
pub fn is_cube(&self) -> bool {
match *self {
Kind::Cube(_) | Kind::CubeArray(_, _) => true,
_ => false,
}
}
}
/// Describes a subvolume of a texture, which image data can be uploaded into.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct ImageInfoCommon<F> {
pub xoffset: Size,
pub yoffset: Size,
pub zoffset: Size,
pub width: Size,
pub height: Size,
pub depth: Size,
/// Format of each texel.
pub format: F,
/// Which mipmap to select.
pub mipmap: Level,
}
/// New raw image info based on the universal format spec.
pub type RawImageInfo = ImageInfoCommon<format::Format>;
/// New image info based on the universal format spec.
/// The format is suppsed to come from compile-time information
/// as opposed to run-time enum values.
pub type NewImageInfo = ImageInfoCommon<()>;
impl<F> ImageInfoCommon<F> {
/// Get the total number of texels.
pub fn get_texel_count(&self) -> usize {
use std::cmp::max;
max(1, self.width) as usize *
max(1, self.height) as usize *
max(1, self.depth) as usize
}
/// Convert into a differently typed format.
pub fn convert<T>(&self, new_format: T) -> ImageInfoCommon<T> {
ImageInfoCommon {
xoffset: self.xoffset,
yoffset: self.yoffset,
zoffset: self.zoffset,
width: self.width,
height: self.height,
depth: self.depth,
format: new_format,
mipmap: self.mipmap,
}
}
/// Check if it fits inside given dimensions.
pub fn is_inside(&self, (w, h, d, aa): Dimensions) -> bool {
aa == AaMode::Single &&
self.xoffset + self.width <= w &&
self.yoffset + self.height <= h &&
self.zoffset + self.depth <= d
}
}
impl RawImageInfo {
/// Get the total number of bytes.
pub fn get_byte_count(&self) -> usize {
let texel_bytes = self.format.0.get_total_bits() / 8;
self.get_texel_count() * (texel_bytes as usize)
}
}
/// Specifies how texture coordinates outside the range `[0, 1]` are handled.
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub enum WrapMode {
/// Tile the texture. That is, sample the coordinate modulo `1.0`. This is
/// the default.
Tile,
/// Mirror the texture. Like tile, but uses abs(coord) before the modulo.
Mirror,
/// Clamp the texture to the value at `0.0` or `1.0` respectively.
Clamp,
/// Use border color.
Border,
}
/// A wrapper for the LOD level of a texture.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct Lod(i16);
impl From<f32> for Lod {
fn from(v: f32) -> Lod {
Lod((v * 8.0) as i16)
}
}
impl Into<f32> for Lod {
fn into(self) -> f32 {
self.0 as f32 / 8.0
}
}
/// A wrapper for the 8bpp RGBA color, encoded as u32.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct PackedColor(pub u32);
impl From<[f32; 4]> for PackedColor {
fn from(c: [f32; 4]) -> PackedColor {
PackedColor(c.iter().rev().fold(0, |u, &c| {
(u<<8) + (c * 255.0 + 0.5) as u32
}))
}
}
impl Into<[f32; 4]> for PackedColor {
fn into(self) -> [f32; 4] {
let mut out = [0.0; 4];
for i in 0.. 4 {
let byte = (self.0 >> (i<<3)) & 0xFF;
out[i] = (byte as f32 + 0.5) / 255.0;
}
out
}
}
/// Specifies how to sample from a texture.
// TODO: document the details of sampling.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
pub struct SamplerInfo {
/// Filter method to use.
pub filter: FilterMethod,
/// Wrapping mode for each of the U, V, and W axis (S, T, and R in OpenGL
/// speak).
pub wrap_mode: (WrapMode, WrapMode, WrapMode),
/// This bias is added to every computed mipmap level (N + lod_bias). For
/// example, if it would select mipmap level 2 and lod_bias is 1, it will
/// use mipmap level 3.
pub lod_bias: Lod,
/// This range is used to clamp LOD level used for sampling.
pub lod_range: (Lod, Lod),
/// Comparison mode, used primary for a shadow map.
pub comparison: Option<state::Comparison>,
/// Border color is used when one of the wrap modes is set to border.
pub border: PackedColor,
}
impl SamplerInfo {
/// Create a new sampler description with a given filter method and wrapping mode, using no LOD
/// modifications.
pub fn new(filter: FilterMethod, wrap: WrapMode) -> SamplerInfo {
SamplerInfo {
filter: filter,
wrap_mode: (wrap, wrap, wrap),
lod_bias: Lod(0),
lod_range: (Lod(-8000), Lod(8000)),
comparison: None,
border: PackedColor(0),
}
}
}
/// Texture storage descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct Info {
pub kind: Kind,
pub levels: Level,
pub format: format::SurfaceType,
pub bind: Bind,
pub usage: Usage,
}
impl Info {
/// Get image info for a given mip.
pub fn to_image_info(&self, mip: Level) -> NewImageInfo {
let (w, h, d, _) = self.kind.get_level_dimensions(mip);
ImageInfoCommon {
xoffset: 0,
yoffset: 0,
zoffset: 0,
width: w,
height: h,
depth: d,
format: (),
mipmap: mip,
}
}
/// Get the raw image info for a given mip and a channel type.
pub fn to_raw_image_info(&self, cty: format::ChannelType, mip: Level) -> RawImageInfo {
let format = format::Format(self.format, cty.into());
self.to_image_info(mip).convert(format)
}
}
/// Texture resource view descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct ResourceDesc {
pub channel: format::ChannelType,
pub layer: Option<Layer>,
pub min: Level,
pub max: Level,
pub swizzle: format::Swizzle,
}
/// Texture render view descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct RenderDesc {
pub channel: format::ChannelType,
pub level: Level,
pub layer: Option<Layer>,
}
bitflags!(
/// Depth-stencil read-only flags
pub flags DepthStencilFlags: u8 {
/// Depth is read-only in the view.
const RO_DEPTH = 0x1,
/// Stencil is read-only in the view.
const RO_STENCIL = 0x2,
/// Both depth and stencil are read-only.
const RO_DEPTH_STENCIL = 0x3,
}
);
/// Texture depth-stencil view descriptor.
#[allow(missing_docs)]
#[derive(Eq, Ord, PartialEq, PartialOrd, Hash, Copy, Clone, Debug)]
pub struct DepthStencilDesc {
pub level: Level,
pub layer: Option<Layer>,
pub flags: DepthStencilFlags,
}
impl From<RenderDesc> for DepthStencilDesc {
fn from(rd: RenderDesc) -> DepthStencilDesc {
DepthStencilDesc {
level: rd.level,
layer: rd.layer,
flags: DepthStencilFlags::empty(),
}
}
}
|
{
match *self {
Kind::D1(..) | Kind::D2(..) | Kind::D3(..) | Kind::Cube(..) => None,
Kind::D1Array(_, a) => Some(a),
Kind::D2Array(_, _, a, _) => Some(a),
Kind::CubeArray(_, a) => Some(a),
}
}
|
identifier_body
|
engine.rs
|
use autocomplete::AutoCompleter;
use autocomplete::Completion;
use runner::Runner;
use externalrunner::ExternalRunner;
use externalautocompleter::ExternalAutoCompleter;
use std::collections::HashMap;
use itertools::Itertools;
use toml;
pub trait Engine {
fn get_completions(&self, query: &str) -> Box<Iterator<Item = Completion>>;
fn run_completion(&self, completion: &Completion, in_background: bool) -> Result<String, String>;
}
pub struct DefaultEngine {
pub completers: Vec<Box<AutoCompleter>>,
pub runners: HashMap<String, Vec<Box<ExternalRunner>>>,
}
impl DefaultEngine {
pub fn new(config: &toml::value::Table) -> DefaultEngine {
DefaultEngine {
completers: DefaultEngine::get_completers(config),
runners: DefaultEngine::get_runners(config),
}
}
pub fn get_completers(config: &toml::value::Table) -> Vec<Box<AutoCompleter>> {
let maybe_completions = config.get("completion").expect("expect completions in config!").as_array().expect("array");
let mut completes: Vec<Box<AutoCompleter>> = Vec::new();
debug!("maybe_completions: {:?}", maybe_completions);
for completion in maybe_completions {
debug!("completion: {:?}", completion);
let this_completer = ExternalAutoCompleter::new(
completion.get("type").and_then(|c| c.as_str()).map(|c| c.to_string()).unwrap(),
completion.get("command").and_then(|c| c.as_str()).map(|c| c.to_string()).unwrap_or("".to_string()),
completion.get("trigger").and_then(|c| c.as_str()).map(|c| c.to_string()).unwrap_or("(.*)".to_string())
);
completes.push(this_completer);
}
completes
|
let runner_configs = config.get("runner").expect("expected runner configs").as_array().expect("array");
let mut runners: Vec<Box<ExternalRunner>> = Vec::new();
for runner in runner_configs {
println!("Runner: {:?}", runner);
runners.push(ExternalRunner::new(
runner.get("type").and_then(|c| c.as_str()).map(|c| c.to_string()).unwrap(),
runner.get("command").and_then(|c| c.as_str()).map(|c| c.to_string()).unwrap()
));
}
let mut runners_by_type = HashMap::with_capacity(runners.len());
for (key, group) in runners.into_iter().group_by(|r| r.get_type()).into_iter() {
runners_by_type.insert(key, group.into_iter().collect_vec());
}
println!("Runners by Type: {:?}", runners_by_type);
runners_by_type
}
}
impl Engine for DefaultEngine {
fn get_completions(&self, query: &str) -> Box<Iterator<Item = Completion>> {
let completions = self.completers
.iter()
.map(|completer| completer.complete(query).collect_vec().into_iter())
.fold1(|c1, c2| c1.chain(c2).collect_vec().into_iter())
.unwrap();
Box::new(completions)
}
fn run_completion(&self, completion: &Completion, in_background: bool) -> Result<String, String> {
let ref runner = match self.runners.get(&completion.tpe) {
Some(values) if values.len() >= 1 => &values[0],
Some(_) => return Err("Runner returned zero sized completions".to_owned()),
None => return Err("Runner returned None".to_owned()),
};
debug!("Running {:?} {:?} with {:?}", completion.tpe, completion, runner);
runner.run(&completion.id, in_background)
}
}
|
}
pub fn get_runners(config: &toml::value::Table) -> HashMap<String, Vec<Box<ExternalRunner>>> {
|
random_line_split
|
engine.rs
|
use autocomplete::AutoCompleter;
use autocomplete::Completion;
use runner::Runner;
use externalrunner::ExternalRunner;
use externalautocompleter::ExternalAutoCompleter;
use std::collections::HashMap;
use itertools::Itertools;
use toml;
pub trait Engine {
fn get_completions(&self, query: &str) -> Box<Iterator<Item = Completion>>;
fn run_completion(&self, completion: &Completion, in_background: bool) -> Result<String, String>;
}
pub struct DefaultEngine {
pub completers: Vec<Box<AutoCompleter>>,
pub runners: HashMap<String, Vec<Box<ExternalRunner>>>,
}
impl DefaultEngine {
pub fn
|
(config: &toml::value::Table) -> DefaultEngine {
DefaultEngine {
completers: DefaultEngine::get_completers(config),
runners: DefaultEngine::get_runners(config),
}
}
pub fn get_completers(config: &toml::value::Table) -> Vec<Box<AutoCompleter>> {
let maybe_completions = config.get("completion").expect("expect completions in config!").as_array().expect("array");
let mut completes: Vec<Box<AutoCompleter>> = Vec::new();
debug!("maybe_completions: {:?}", maybe_completions);
for completion in maybe_completions {
debug!("completion: {:?}", completion);
let this_completer = ExternalAutoCompleter::new(
completion.get("type").and_then(|c| c.as_str()).map(|c| c.to_string()).unwrap(),
completion.get("command").and_then(|c| c.as_str()).map(|c| c.to_string()).unwrap_or("".to_string()),
completion.get("trigger").and_then(|c| c.as_str()).map(|c| c.to_string()).unwrap_or("(.*)".to_string())
);
completes.push(this_completer);
}
completes
}
pub fn get_runners(config: &toml::value::Table) -> HashMap<String, Vec<Box<ExternalRunner>>> {
let runner_configs = config.get("runner").expect("expected runner configs").as_array().expect("array");
let mut runners: Vec<Box<ExternalRunner>> = Vec::new();
for runner in runner_configs {
println!("Runner: {:?}", runner);
runners.push(ExternalRunner::new(
runner.get("type").and_then(|c| c.as_str()).map(|c| c.to_string()).unwrap(),
runner.get("command").and_then(|c| c.as_str()).map(|c| c.to_string()).unwrap()
));
}
let mut runners_by_type = HashMap::with_capacity(runners.len());
for (key, group) in runners.into_iter().group_by(|r| r.get_type()).into_iter() {
runners_by_type.insert(key, group.into_iter().collect_vec());
}
println!("Runners by Type: {:?}", runners_by_type);
runners_by_type
}
}
impl Engine for DefaultEngine {
fn get_completions(&self, query: &str) -> Box<Iterator<Item = Completion>> {
let completions = self.completers
.iter()
.map(|completer| completer.complete(query).collect_vec().into_iter())
.fold1(|c1, c2| c1.chain(c2).collect_vec().into_iter())
.unwrap();
Box::new(completions)
}
fn run_completion(&self, completion: &Completion, in_background: bool) -> Result<String, String> {
let ref runner = match self.runners.get(&completion.tpe) {
Some(values) if values.len() >= 1 => &values[0],
Some(_) => return Err("Runner returned zero sized completions".to_owned()),
None => return Err("Runner returned None".to_owned()),
};
debug!("Running {:?} {:?} with {:?}", completion.tpe, completion, runner);
runner.run(&completion.id, in_background)
}
}
|
new
|
identifier_name
|
node.rs
|
use super::constants::NODE;
use indy_api_types::validation::Validatable;
use super::super::crypto::did::ShortDidValue;
#[derive(Serialize, PartialEq, Debug)]
pub struct
|
{
#[serde(rename = "type")]
pub _type: String,
pub dest: ShortDidValue,
pub data: NodeOperationData
}
impl NodeOperation {
pub fn new(dest: ShortDidValue, data: NodeOperationData) -> NodeOperation {
NodeOperation {
_type: NODE.to_string(),
dest,
data
}
}
}
#[derive(Serialize, PartialEq, Debug, Deserialize)]
pub enum Services {
VALIDATOR,
OBSERVER
}
#[derive(Serialize, PartialEq, Debug, Deserialize)]
pub struct NodeOperationData {
#[serde(skip_serializing_if = "Option::is_none")]
pub node_ip: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub node_port: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_ip: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_port: Option<i32>,
pub alias: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub services: Option<Vec<Services>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blskey: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blskey_pop: Option<String>
}
impl Validatable for NodeOperationData{
fn validate(&self) -> Result<(), String> {
if self.node_ip.is_none() && self.node_port.is_none()
&& self.client_ip.is_none() && self.client_port.is_none()
&& self.services.is_none() && self.blskey.is_none()
&& self.blskey_pop.is_none() {
return Err(String::from("Invalid data json: all fields missed at once"));
}
if (self.node_ip.is_some() || self.node_port.is_some() || self.client_ip.is_some() || self.client_port.is_some()) &&
(self.node_ip.is_none() || self.node_port.is_none() || self.client_ip.is_none() || self.client_port.is_none()) {
return Err(String::from("Invalid data json: Fields node_ip, node_port, client_ip, client_port must be specified together"));
}
Ok(())
}
}
|
NodeOperation
|
identifier_name
|
node.rs
|
use super::constants::NODE;
use indy_api_types::validation::Validatable;
use super::super::crypto::did::ShortDidValue;
#[derive(Serialize, PartialEq, Debug)]
pub struct NodeOperation {
#[serde(rename = "type")]
pub _type: String,
pub dest: ShortDidValue,
pub data: NodeOperationData
}
impl NodeOperation {
pub fn new(dest: ShortDidValue, data: NodeOperationData) -> NodeOperation {
NodeOperation {
_type: NODE.to_string(),
dest,
data
}
}
}
#[derive(Serialize, PartialEq, Debug, Deserialize)]
pub enum Services {
VALIDATOR,
OBSERVER
}
#[derive(Serialize, PartialEq, Debug, Deserialize)]
pub struct NodeOperationData {
#[serde(skip_serializing_if = "Option::is_none")]
pub node_ip: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub node_port: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_ip: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_port: Option<i32>,
pub alias: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub services: Option<Vec<Services>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blskey: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blskey_pop: Option<String>
}
impl Validatable for NodeOperationData{
fn validate(&self) -> Result<(), String> {
if self.node_ip.is_none() && self.node_port.is_none()
&& self.client_ip.is_none() && self.client_port.is_none()
&& self.services.is_none() && self.blskey.is_none()
&& self.blskey_pop.is_none() {
return Err(String::from("Invalid data json: all fields missed at once"));
}
if (self.node_ip.is_some() || self.node_port.is_some() || self.client_ip.is_some() || self.client_port.is_some()) &&
(self.node_ip.is_none() || self.node_port.is_none() || self.client_ip.is_none() || self.client_port.is_none())
|
Ok(())
}
}
|
{
return Err(String::from("Invalid data json: Fields node_ip, node_port, client_ip, client_port must be specified together"));
}
|
conditional_block
|
node.rs
|
use super::constants::NODE;
use indy_api_types::validation::Validatable;
use super::super::crypto::did::ShortDidValue;
#[derive(Serialize, PartialEq, Debug)]
pub struct NodeOperation {
#[serde(rename = "type")]
pub _type: String,
pub dest: ShortDidValue,
pub data: NodeOperationData
}
impl NodeOperation {
pub fn new(dest: ShortDidValue, data: NodeOperationData) -> NodeOperation {
NodeOperation {
_type: NODE.to_string(),
dest,
data
}
}
}
#[derive(Serialize, PartialEq, Debug, Deserialize)]
|
VALIDATOR,
OBSERVER
}
#[derive(Serialize, PartialEq, Debug, Deserialize)]
pub struct NodeOperationData {
#[serde(skip_serializing_if = "Option::is_none")]
pub node_ip: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub node_port: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_ip: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_port: Option<i32>,
pub alias: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub services: Option<Vec<Services>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blskey: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blskey_pop: Option<String>
}
impl Validatable for NodeOperationData{
fn validate(&self) -> Result<(), String> {
if self.node_ip.is_none() && self.node_port.is_none()
&& self.client_ip.is_none() && self.client_port.is_none()
&& self.services.is_none() && self.blskey.is_none()
&& self.blskey_pop.is_none() {
return Err(String::from("Invalid data json: all fields missed at once"));
}
if (self.node_ip.is_some() || self.node_port.is_some() || self.client_ip.is_some() || self.client_port.is_some()) &&
(self.node_ip.is_none() || self.node_port.is_none() || self.client_ip.is_none() || self.client_port.is_none()) {
return Err(String::from("Invalid data json: Fields node_ip, node_port, client_ip, client_port must be specified together"));
}
Ok(())
}
}
|
pub enum Services {
|
random_line_split
|
hash.rs
|
implement `IterBytes`,
* and the implementation of `Hash` below will take care of
* the rest. This is the recommended approach, since constructing
* good keyed hash functions is quite difficult.
*/
pub trait Hash {
/**
* Compute a "keyed" hash of the value implementing the trait,
* taking `k0` and `k1` as "keying" parameters that randomize or
* otherwise perturb the hash function in such a way that a
* hash table built using such "keyed hash functions" cannot
* be made to perform linearly by an attacker controlling the
* hashtable's contents.
*
* In practical terms, we implement this using the SipHash 2-4
* function and require most types to only implement the
* IterBytes trait, that feeds SipHash.
*/
fn hash_keyed(&self, k0: u64, k1: u64) -> u64;
}
// When we have default methods, won't need this.
pub trait HashUtil {
fn hash(&self) -> u64;
}
impl<A:Hash> HashUtil for A {
#[inline(always)]
fn hash(&self) -> u64 { self.hash_keyed(0,0) }
}
/// Streaming hash-functions should implement this.
pub trait Streaming {
fn input(&self, (&const [u8]));
// These can be refactored some when we have default methods.
fn result_bytes(&self) -> ~[u8];
fn result_str(&self) -> ~str;
fn result_u64(&self) -> u64;
fn reset(&self);
}
impl<A:IterBytes> Hash for A {
#[inline(always)]
fn hash_keyed(&self, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for self.iter_bytes(true) |bytes| {
s.input(bytes);
}
s.result_u64()
}
}
}
fn hash_keyed_2<A: IterBytes,
B: IterBytes>(a: &A, b: &B, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_3<A: IterBytes,
B: IterBytes,
C: IterBytes>(a: &A, b: &B, c: &C, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_4<A: IterBytes,
B: IterBytes,
C: IterBytes,
D: IterBytes>(a: &A, b: &B, c: &C, d: &D, k0: u64, k1: u64)
-> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
for d.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_5<A: IterBytes,
B: IterBytes,
C: IterBytes,
D: IterBytes,
E: IterBytes>(a: &A, b: &B, c: &C, d: &D, e: &E,
k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
for d.iter_bytes(true) |bytes| { s.input(bytes); }
for e.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
// Implement State as SipState
pub type State = SipState;
#[inline(always)]
pub fn State(k0: u64, k1: u64) -> State {
SipState(k0, k1)
}
#[inline(always)]
pub fn default_state() -> State {
State(0,0)
}
struct SipState {
k0: u64,
k1: u64,
mut length: uint, // how many bytes we've processed
mut v0: u64, // hash state
mut v1: u64,
mut v2: u64,
mut v3: u64,
mut tail: [u8,..8], // unprocessed bytes
mut ntail: uint, // how many bytes in tail are valid
}
#[inline(always)]
fn SipState(key0: u64, key1: u64) -> SipState {
let state = SipState {
k0 : key0,
k1 : key1,
mut length : 0u,
mut v0 : 0u64,
mut v1 : 0u64,
mut v2 : 0u64,
mut v3 : 0u64,
mut tail : [0u8,0,0,0,0,0,0,0],
mut ntail : 0u,
};
(&state).reset();
state
}
// sadly, these macro definitions can't appear later,
// because they're needed in the following defs;
// this design could be improved.
macro_rules! u8to64_le (
($buf:expr, $i:expr) =>
($buf[0+$i] as u64 |
$buf[1+$i] as u64 << 8 |
$buf[2+$i] as u64 << 16 |
$buf[3+$i] as u64 << 24 |
$buf[4+$i] as u64 << 32 |
$buf[5+$i] as u64 << 40 |
$buf[6+$i] as u64 << 48 |
$buf[7+$i] as u64 << 56)
)
macro_rules! rotl (
($x:expr, $b:expr) =>
(($x << $b) | ($x >> (64 - $b)))
)
macro_rules! compress (
($v0:expr, $v1:expr, $v2:expr, $v3:expr) =>
({
$v0 += $v1; $v1 = rotl!($v1, 13); $v1 ^= $v0;
$v0 = rotl!($v0, 32);
$v2 += $v3; $v3 = rotl!($v3, 16); $v3 ^= $v2;
$v0 += $v3; $v3 = rotl!($v3, 21); $v3 ^= $v0;
$v2 += $v1; $v1 = rotl!($v1, 17); $v1 ^= $v2;
$v2 = rotl!($v2, 32);
})
)
impl io::Writer for SipState {
// Methods for io::writer
#[inline(always)]
fn write(&self, msg: &const [u8]) {
let length = msg.len();
self.length += length;
let mut needed = 0u;
if self.ntail!= 0 {
needed = 8 - self.ntail;
if length < needed {
let mut t = 0;
while t < length {
self.tail[self.ntail+t] = msg[t];
t += 1;
}
self.ntail += length;
return;
}
let mut t = 0;
while t < needed {
self.tail[self.ntail+t] = msg[t];
t += 1;
}
let m = u8to64_le!(self.tail, 0);
self.v3 ^= m;
compress!(self.v0, self.v1, self.v2, self.v3);
compress!(self.v0, self.v1, self.v2, self.v3);
self.v0 ^= m;
self.ntail = 0;
}
// Buffered tail is now flushed, process new input.
let len = length - needed;
let end = len & (!0x7);
let left = len & 0x7;
let mut i = needed;
while i < end {
let mi = u8to64_le!(msg, i);
self.v3 ^= mi;
compress!(self.v0, self.v1, self.v2, self.v3);
compress!(self.v0, self.v1, self.v2, self.v3);
self.v0 ^= mi;
i += 8;
}
let mut t = 0u;
while t < left {
self.tail[t] = msg[i+t];
t += 1
}
self.ntail = left;
}
fn seek(&self, _x: int, _s: io::SeekStyle) {
fail!();
}
fn tell(&self) -> uint {
self.length
}
fn flush(&self) -> int {
0
}
fn get_type(&self) -> io::WriterType {
io::File
}
}
impl Streaming for SipState {
#[inline(always)]
fn input(&self, buf: &const [u8]) {
self.write(buf);
}
#[inline(always)]
fn result_u64(&self) -> u64 {
let mut v0 = self.v0;
let mut v1 = self.v1;
let mut v2 = self.v2;
let mut v3 = self.v3;
let mut b : u64 = (self.length as u64 & 0xff) << 56;
if self.ntail > 0 { b |= self.tail[0] as u64 << 0; }
if self.ntail > 1 { b |= self.tail[1] as u64 << 8; }
if self.ntail > 2 { b |= self.tail[2] as u64 << 16; }
if self.ntail > 3 { b |= self.tail[3] as u64 << 24; }
if self.ntail > 4 { b |= self.tail[4] as u64 << 32; }
if self.ntail > 5 { b |= self.tail[5] as u64 << 40; }
if self.ntail > 6 { b |= self.tail[6] as u64 << 48; }
v3 ^= b;
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
v0 ^= b;
v2 ^= 0xff;
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
return (v0 ^ v1 ^ v2 ^ v3);
}
fn result_bytes(&self) -> ~[u8] {
let h = self.result_u64();
~[(h >> 0) as u8,
(h >> 8) as u8,
(h >> 16) as u8,
(h >> 24) as u8,
(h >> 32) as u8,
(h >> 40) as u8,
(h >> 48) as u8,
(h >> 56) as u8,
]
}
fn result_str(&self) -> ~str {
let r = self.result_bytes();
let mut s = ~"";
for vec::each(r) |b| {
s += uint::to_str_radix(*b as uint, 16u);
}
s
}
#[inline(always)]
fn reset(&self) {
self.length = 0;
self.v0 = self.k0 ^ 0x736f6d6570736575;
self.v1 = self.k1 ^ 0x646f72616e646f6d;
self.v2 = self.k0 ^ 0x6c7967656e657261;
self.v3 = self.k1 ^ 0x7465646279746573;
self.ntail = 0;
}
}
#[test]
pub fn test_siphash() {
let vecs : [[u8,..8],..64] = [
[ 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, ],
[ 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, ],
[ 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, ],
[ 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, ],
[ 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, ],
[ 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, ],
[ 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, ],
[ 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, ],
[ 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, ],
[ 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, ],
[ 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, ],
[ 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, ],
[ 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, ],
[ 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, ],
[ 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, ],
[ 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, ],
[ 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, ],
[ 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, ],
[ 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, ],
[ 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, ],
[ 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, ],
[ 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, ],
[ 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, ],
[ 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, ],
[ 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, ],
[ 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, ],
[ 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, ],
[ 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, ],
[ 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, ],
[ 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, ],
[ 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, ],
[ 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, ],
[ 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, ],
[ 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, ],
[ 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, ],
[ 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, ],
[ 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, ],
[ 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, ],
[ 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, ],
[ 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, ],
[ 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, ],
[ 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, ],
[ 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, ],
[ 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, ],
[ 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, ],
[ 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, ],
[ 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, ],
[ 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, ],
[ 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, ],
[ 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, ],
[ 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, ],
[ 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, ],
[ 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, ],
[ 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, ],
[ 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, ],
[ 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, ],
[ 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, ],
[ 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, ],
[ 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, ],
[ 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, ],
[ 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, ],
[ 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, ],
[ 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, ],
|
[ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, ]
];
let k0 = 0x_07_06_05_04_03_02_01_00_u64;
let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08_u64;
let mut buf : ~[u8] = ~[];
let mut t = 0;
let stream_inc = &State(k0,k1);
let stream_full = &State(k0,k1);
fn to_hex_str(r: &[u8,..8]) -> ~str {
let mut s = ~"";
for vec::each(*r) |b| {
s += uint::to_str_radix(*b as uint, 16u);
}
s
}
while t < 64 {
debug!("siphash test %?", t);
let vec = u8to64_le!(vecs[t], 0);
let out = buf.hash_keyed(k0, k1);
debug!("got %?, expected %?", out, vec);
assert!(vec == out);
stream_full.reset();
stream_full.input(buf);
let f = stream_full.result_str();
let i = stream_inc.result_str();
let v = to_hex_str(&vecs[t]);
debug!("%d: (%s) => inc=%s full=%s", t, v, i, f);
assert!(f == i && f == v);
buf += ~[t as u8];
stream_inc.input(~[t as u8]);
t += 1;
}
}
#[test] #[cfg(target_arch = "arm")]
pub fn test_hash_uint() {
let val = 0xdeadbeef_deadbeef_u64;
assert!((val as u64).hash()!= (val as uint).hash());
assert!((val as u32).hash() == (val as uint).hash());
}
#[test
|
random_line_split
|
|
hash.rs
|
built using such "keyed hash functions" cannot
* be made to perform linearly by an attacker controlling the
* hashtable's contents.
*
* In practical terms, we implement this using the SipHash 2-4
* function and require most types to only implement the
* IterBytes trait, that feeds SipHash.
*/
fn hash_keyed(&self, k0: u64, k1: u64) -> u64;
}
// When we have default methods, won't need this.
pub trait HashUtil {
fn hash(&self) -> u64;
}
impl<A:Hash> HashUtil for A {
#[inline(always)]
fn hash(&self) -> u64 { self.hash_keyed(0,0) }
}
/// Streaming hash-functions should implement this.
pub trait Streaming {
fn input(&self, (&const [u8]));
// These can be refactored some when we have default methods.
fn result_bytes(&self) -> ~[u8];
fn result_str(&self) -> ~str;
fn result_u64(&self) -> u64;
fn reset(&self);
}
impl<A:IterBytes> Hash for A {
#[inline(always)]
fn hash_keyed(&self, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for self.iter_bytes(true) |bytes| {
s.input(bytes);
}
s.result_u64()
}
}
}
fn hash_keyed_2<A: IterBytes,
B: IterBytes>(a: &A, b: &B, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_3<A: IterBytes,
B: IterBytes,
C: IterBytes>(a: &A, b: &B, c: &C, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_4<A: IterBytes,
B: IterBytes,
C: IterBytes,
D: IterBytes>(a: &A, b: &B, c: &C, d: &D, k0: u64, k1: u64)
-> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
for d.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_5<A: IterBytes,
B: IterBytes,
C: IterBytes,
D: IterBytes,
E: IterBytes>(a: &A, b: &B, c: &C, d: &D, e: &E,
k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
for d.iter_bytes(true) |bytes| { s.input(bytes); }
for e.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
// Implement State as SipState
pub type State = SipState;
#[inline(always)]
pub fn State(k0: u64, k1: u64) -> State {
SipState(k0, k1)
}
#[inline(always)]
pub fn default_state() -> State {
State(0,0)
}
struct SipState {
k0: u64,
k1: u64,
mut length: uint, // how many bytes we've processed
mut v0: u64, // hash state
mut v1: u64,
mut v2: u64,
mut v3: u64,
mut tail: [u8,..8], // unprocessed bytes
mut ntail: uint, // how many bytes in tail are valid
}
#[inline(always)]
fn SipState(key0: u64, key1: u64) -> SipState {
let state = SipState {
k0 : key0,
k1 : key1,
mut length : 0u,
mut v0 : 0u64,
mut v1 : 0u64,
mut v2 : 0u64,
mut v3 : 0u64,
mut tail : [0u8,0,0,0,0,0,0,0],
mut ntail : 0u,
};
(&state).reset();
state
}
// sadly, these macro definitions can't appear later,
// because they're needed in the following defs;
// this design could be improved.
macro_rules! u8to64_le (
($buf:expr, $i:expr) =>
($buf[0+$i] as u64 |
$buf[1+$i] as u64 << 8 |
$buf[2+$i] as u64 << 16 |
$buf[3+$i] as u64 << 24 |
$buf[4+$i] as u64 << 32 |
$buf[5+$i] as u64 << 40 |
$buf[6+$i] as u64 << 48 |
$buf[7+$i] as u64 << 56)
)
macro_rules! rotl (
($x:expr, $b:expr) =>
(($x << $b) | ($x >> (64 - $b)))
)
macro_rules! compress (
($v0:expr, $v1:expr, $v2:expr, $v3:expr) =>
({
$v0 += $v1; $v1 = rotl!($v1, 13); $v1 ^= $v0;
$v0 = rotl!($v0, 32);
$v2 += $v3; $v3 = rotl!($v3, 16); $v3 ^= $v2;
$v0 += $v3; $v3 = rotl!($v3, 21); $v3 ^= $v0;
$v2 += $v1; $v1 = rotl!($v1, 17); $v1 ^= $v2;
$v2 = rotl!($v2, 32);
})
)
impl io::Writer for SipState {
// Methods for io::writer
#[inline(always)]
fn write(&self, msg: &const [u8]) {
let length = msg.len();
self.length += length;
let mut needed = 0u;
if self.ntail!= 0 {
needed = 8 - self.ntail;
if length < needed {
let mut t = 0;
while t < length {
self.tail[self.ntail+t] = msg[t];
t += 1;
}
self.ntail += length;
return;
}
let mut t = 0;
while t < needed {
self.tail[self.ntail+t] = msg[t];
t += 1;
}
let m = u8to64_le!(self.tail, 0);
self.v3 ^= m;
compress!(self.v0, self.v1, self.v2, self.v3);
compress!(self.v0, self.v1, self.v2, self.v3);
self.v0 ^= m;
self.ntail = 0;
}
// Buffered tail is now flushed, process new input.
let len = length - needed;
let end = len & (!0x7);
let left = len & 0x7;
let mut i = needed;
while i < end {
let mi = u8to64_le!(msg, i);
self.v3 ^= mi;
compress!(self.v0, self.v1, self.v2, self.v3);
compress!(self.v0, self.v1, self.v2, self.v3);
self.v0 ^= mi;
i += 8;
}
let mut t = 0u;
while t < left {
self.tail[t] = msg[i+t];
t += 1
}
self.ntail = left;
}
fn seek(&self, _x: int, _s: io::SeekStyle) {
fail!();
}
fn tell(&self) -> uint {
self.length
}
fn flush(&self) -> int {
0
}
fn get_type(&self) -> io::WriterType {
io::File
}
}
impl Streaming for SipState {
#[inline(always)]
fn input(&self, buf: &const [u8]) {
self.write(buf);
}
#[inline(always)]
fn result_u64(&self) -> u64 {
let mut v0 = self.v0;
let mut v1 = self.v1;
let mut v2 = self.v2;
let mut v3 = self.v3;
let mut b : u64 = (self.length as u64 & 0xff) << 56;
if self.ntail > 0 { b |= self.tail[0] as u64 << 0; }
if self.ntail > 1 { b |= self.tail[1] as u64 << 8; }
if self.ntail > 2 { b |= self.tail[2] as u64 << 16; }
if self.ntail > 3 { b |= self.tail[3] as u64 << 24; }
if self.ntail > 4 { b |= self.tail[4] as u64 << 32; }
if self.ntail > 5 { b |= self.tail[5] as u64 << 40; }
if self.ntail > 6 { b |= self.tail[6] as u64 << 48; }
v3 ^= b;
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
v0 ^= b;
v2 ^= 0xff;
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
return (v0 ^ v1 ^ v2 ^ v3);
}
fn result_bytes(&self) -> ~[u8] {
let h = self.result_u64();
~[(h >> 0) as u8,
(h >> 8) as u8,
(h >> 16) as u8,
(h >> 24) as u8,
(h >> 32) as u8,
(h >> 40) as u8,
(h >> 48) as u8,
(h >> 56) as u8,
]
}
fn result_str(&self) -> ~str {
let r = self.result_bytes();
let mut s = ~"";
for vec::each(r) |b| {
s += uint::to_str_radix(*b as uint, 16u);
}
s
}
#[inline(always)]
fn reset(&self) {
self.length = 0;
self.v0 = self.k0 ^ 0x736f6d6570736575;
self.v1 = self.k1 ^ 0x646f72616e646f6d;
self.v2 = self.k0 ^ 0x6c7967656e657261;
self.v3 = self.k1 ^ 0x7465646279746573;
self.ntail = 0;
}
}
#[test]
pub fn test_siphash() {
let vecs : [[u8,..8],..64] = [
[ 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, ],
[ 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, ],
[ 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, ],
[ 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, ],
[ 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, ],
[ 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, ],
[ 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, ],
[ 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, ],
[ 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, ],
[ 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, ],
[ 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, ],
[ 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, ],
[ 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, ],
[ 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, ],
[ 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, ],
[ 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, ],
[ 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, ],
[ 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, ],
[ 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, ],
[ 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, ],
[ 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, ],
[ 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, ],
[ 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, ],
[ 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, ],
[ 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, ],
[ 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, ],
[ 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, ],
[ 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, ],
[ 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, ],
[ 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, ],
[ 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, ],
[ 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, ],
[ 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, ],
[ 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, ],
[ 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, ],
[ 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, ],
[ 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, ],
[ 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, ],
[ 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, ],
[ 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, ],
[ 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, ],
[ 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, ],
[ 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, ],
[ 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, ],
[ 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, ],
[ 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, ],
[ 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, ],
[ 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, ],
[ 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, ],
[ 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, ],
[ 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, ],
[ 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, ],
[ 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, ],
[ 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, ],
[ 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, ],
[ 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, ],
[ 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, ],
[ 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, ],
[ 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, ],
[ 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, ],
[ 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, ],
[ 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, ],
[ 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, ],
[ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, ]
];
let k0 = 0x_07_06_05_04_03_02_01_00_u64;
let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08_u64;
let mut buf : ~[u8] = ~[];
let mut t = 0;
let stream_inc = &State(k0,k1);
let stream_full = &State(k0,k1);
fn to_hex_str(r: &[u8,..8]) -> ~str {
let mut s = ~"";
for vec::each(*r) |b| {
s += uint::to_str_radix(*b as uint, 16u);
}
s
}
while t < 64 {
debug!("siphash test %?", t);
let vec = u8to64_le!(vecs[t], 0);
let out = buf.hash_keyed(k0, k1);
debug!("got %?, expected %?", out, vec);
assert!(vec == out);
stream_full.reset();
stream_full.input(buf);
let f = stream_full.result_str();
let i = stream_inc.result_str();
let v = to_hex_str(&vecs[t]);
debug!("%d: (%s) => inc=%s full=%s", t, v, i, f);
assert!(f == i && f == v);
buf += ~[t as u8];
stream_inc.input(~[t as u8]);
t += 1;
}
}
#[test] #[cfg(target_arch = "arm")]
pub fn test_hash_uint() {
let val = 0xdeadbeef_deadbeef_u64;
assert!((val as u64).hash()!= (val as uint).hash());
assert!((val as u32).hash() == (val as uint).hash());
}
#[test] #[cfg(target_arch = "x86_64")]
pub fn test_hash_uint() {
let val = 0xdeadbeef_deadbeef_u64;
assert!((val as u64).hash() == (val as uint).hash());
assert!((val as u32).hash()!= (val as uint).hash());
}
#[test] #[cfg(target_arch = "x86")]
pub fn
|
test_hash_uint
|
identifier_name
|
|
hash.rs
|
`IterBytes`,
* and the implementation of `Hash` below will take care of
* the rest. This is the recommended approach, since constructing
* good keyed hash functions is quite difficult.
*/
pub trait Hash {
/**
* Compute a "keyed" hash of the value implementing the trait,
* taking `k0` and `k1` as "keying" parameters that randomize or
* otherwise perturb the hash function in such a way that a
* hash table built using such "keyed hash functions" cannot
* be made to perform linearly by an attacker controlling the
* hashtable's contents.
*
* In practical terms, we implement this using the SipHash 2-4
* function and require most types to only implement the
* IterBytes trait, that feeds SipHash.
*/
fn hash_keyed(&self, k0: u64, k1: u64) -> u64;
}
// When we have default methods, won't need this.
pub trait HashUtil {
fn hash(&self) -> u64;
}
impl<A:Hash> HashUtil for A {
#[inline(always)]
fn hash(&self) -> u64 { self.hash_keyed(0,0) }
}
/// Streaming hash-functions should implement this.
pub trait Streaming {
fn input(&self, (&const [u8]));
// These can be refactored some when we have default methods.
fn result_bytes(&self) -> ~[u8];
fn result_str(&self) -> ~str;
fn result_u64(&self) -> u64;
fn reset(&self);
}
impl<A:IterBytes> Hash for A {
#[inline(always)]
fn hash_keyed(&self, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for self.iter_bytes(true) |bytes| {
s.input(bytes);
}
s.result_u64()
}
}
}
fn hash_keyed_2<A: IterBytes,
B: IterBytes>(a: &A, b: &B, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_3<A: IterBytes,
B: IterBytes,
C: IterBytes>(a: &A, b: &B, c: &C, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_4<A: IterBytes,
B: IterBytes,
C: IterBytes,
D: IterBytes>(a: &A, b: &B, c: &C, d: &D, k0: u64, k1: u64)
-> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
for d.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_5<A: IterBytes,
B: IterBytes,
C: IterBytes,
D: IterBytes,
E: IterBytes>(a: &A, b: &B, c: &C, d: &D, e: &E,
k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
for d.iter_bytes(true) |bytes| { s.input(bytes); }
for e.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
// Implement State as SipState
pub type State = SipState;
#[inline(always)]
pub fn State(k0: u64, k1: u64) -> State {
SipState(k0, k1)
}
#[inline(always)]
pub fn default_state() -> State {
State(0,0)
}
struct SipState {
k0: u64,
k1: u64,
mut length: uint, // how many bytes we've processed
mut v0: u64, // hash state
mut v1: u64,
mut v2: u64,
mut v3: u64,
mut tail: [u8,..8], // unprocessed bytes
mut ntail: uint, // how many bytes in tail are valid
}
#[inline(always)]
fn SipState(key0: u64, key1: u64) -> SipState {
let state = SipState {
k0 : key0,
k1 : key1,
mut length : 0u,
mut v0 : 0u64,
mut v1 : 0u64,
mut v2 : 0u64,
mut v3 : 0u64,
mut tail : [0u8,0,0,0,0,0,0,0],
mut ntail : 0u,
};
(&state).reset();
state
}
// sadly, these macro definitions can't appear later,
// because they're needed in the following defs;
// this design could be improved.
macro_rules! u8to64_le (
($buf:expr, $i:expr) =>
($buf[0+$i] as u64 |
$buf[1+$i] as u64 << 8 |
$buf[2+$i] as u64 << 16 |
$buf[3+$i] as u64 << 24 |
$buf[4+$i] as u64 << 32 |
$buf[5+$i] as u64 << 40 |
$buf[6+$i] as u64 << 48 |
$buf[7+$i] as u64 << 56)
)
macro_rules! rotl (
($x:expr, $b:expr) =>
(($x << $b) | ($x >> (64 - $b)))
)
macro_rules! compress (
($v0:expr, $v1:expr, $v2:expr, $v3:expr) =>
({
$v0 += $v1; $v1 = rotl!($v1, 13); $v1 ^= $v0;
$v0 = rotl!($v0, 32);
$v2 += $v3; $v3 = rotl!($v3, 16); $v3 ^= $v2;
$v0 += $v3; $v3 = rotl!($v3, 21); $v3 ^= $v0;
$v2 += $v1; $v1 = rotl!($v1, 17); $v1 ^= $v2;
$v2 = rotl!($v2, 32);
})
)
impl io::Writer for SipState {
// Methods for io::writer
#[inline(always)]
fn write(&self, msg: &const [u8]) {
let length = msg.len();
self.length += length;
let mut needed = 0u;
if self.ntail!= 0
|
self.v3 ^= m;
compress!(self.v0, self.v1, self.v2, self.v3);
compress!(self.v0, self.v1, self.v2, self.v3);
self.v0 ^= m;
self.ntail = 0;
}
// Buffered tail is now flushed, process new input.
let len = length - needed;
let end = len & (!0x7);
let left = len & 0x7;
let mut i = needed;
while i < end {
let mi = u8to64_le!(msg, i);
self.v3 ^= mi;
compress!(self.v0, self.v1, self.v2, self.v3);
compress!(self.v0, self.v1, self.v2, self.v3);
self.v0 ^= mi;
i += 8;
}
let mut t = 0u;
while t < left {
self.tail[t] = msg[i+t];
t += 1
}
self.ntail = left;
}
fn seek(&self, _x: int, _s: io::SeekStyle) {
fail!();
}
fn tell(&self) -> uint {
self.length
}
fn flush(&self) -> int {
0
}
fn get_type(&self) -> io::WriterType {
io::File
}
}
impl Streaming for SipState {
#[inline(always)]
fn input(&self, buf: &const [u8]) {
self.write(buf);
}
#[inline(always)]
fn result_u64(&self) -> u64 {
let mut v0 = self.v0;
let mut v1 = self.v1;
let mut v2 = self.v2;
let mut v3 = self.v3;
let mut b : u64 = (self.length as u64 & 0xff) << 56;
if self.ntail > 0 { b |= self.tail[0] as u64 << 0; }
if self.ntail > 1 { b |= self.tail[1] as u64 << 8; }
if self.ntail > 2 { b |= self.tail[2] as u64 << 16; }
if self.ntail > 3 { b |= self.tail[3] as u64 << 24; }
if self.ntail > 4 { b |= self.tail[4] as u64 << 32; }
if self.ntail > 5 { b |= self.tail[5] as u64 << 40; }
if self.ntail > 6 { b |= self.tail[6] as u64 << 48; }
v3 ^= b;
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
v0 ^= b;
v2 ^= 0xff;
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
return (v0 ^ v1 ^ v2 ^ v3);
}
fn result_bytes(&self) -> ~[u8] {
let h = self.result_u64();
~[(h >> 0) as u8,
(h >> 8) as u8,
(h >> 16) as u8,
(h >> 24) as u8,
(h >> 32) as u8,
(h >> 40) as u8,
(h >> 48) as u8,
(h >> 56) as u8,
]
}
fn result_str(&self) -> ~str {
let r = self.result_bytes();
let mut s = ~"";
for vec::each(r) |b| {
s += uint::to_str_radix(*b as uint, 16u);
}
s
}
#[inline(always)]
fn reset(&self) {
self.length = 0;
self.v0 = self.k0 ^ 0x736f6d6570736575;
self.v1 = self.k1 ^ 0x646f72616e646f6d;
self.v2 = self.k0 ^ 0x6c7967656e657261;
self.v3 = self.k1 ^ 0x7465646279746573;
self.ntail = 0;
}
}
#[test]
pub fn test_siphash() {
let vecs : [[u8,..8],..64] = [
[ 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, ],
[ 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, ],
[ 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, ],
[ 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, ],
[ 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, ],
[ 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, ],
[ 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, ],
[ 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, ],
[ 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, ],
[ 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, ],
[ 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, ],
[ 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, ],
[ 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, ],
[ 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, ],
[ 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, ],
[ 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, ],
[ 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, ],
[ 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, ],
[ 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, ],
[ 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, ],
[ 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, ],
[ 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, ],
[ 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, ],
[ 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, ],
[ 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, ],
[ 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, ],
[ 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, ],
[ 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, ],
[ 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, ],
[ 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, ],
[ 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, ],
[ 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, ],
[ 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, ],
[ 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, ],
[ 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, ],
[ 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, ],
[ 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, ],
[ 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, ],
[ 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, ],
[ 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, ],
[ 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, ],
[ 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, ],
[ 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, ],
[ 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, ],
[ 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, ],
[ 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, ],
[ 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, ],
[ 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, ],
[ 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, ],
[ 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, ],
[ 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, ],
[ 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, ],
[ 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, ],
[ 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, ],
[ 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, ],
[ 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, ],
[ 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, ],
[ 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, ],
[ 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, ],
[ 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, ],
[ 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, ],
[ 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, ],
[ 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, ],
[ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, ]
];
let k0 = 0x_07_06_05_04_03_02_01_00_u64;
let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08_u64;
let mut buf : ~[u8] = ~[];
let mut t = 0;
let stream_inc = &State(k0,k1);
let stream_full = &State(k0,k1);
fn to_hex_str(r: &[u8,..8]) -> ~str {
let mut s = ~"";
for vec::each(*r) |b| {
s += uint::to_str_radix(*b as uint, 16u);
}
s
}
while t < 64 {
debug!("siphash test %?", t);
let vec = u8to64_le!(vecs[t], 0);
let out = buf.hash_keyed(k0, k1);
debug!("got %?, expected %?", out, vec);
assert!(vec == out);
stream_full.reset();
stream_full.input(buf);
let f = stream_full.result_str();
let i = stream_inc.result_str();
let v = to_hex_str(&vecs[t]);
debug!("%d: (%s) => inc=%s full=%s", t, v, i, f);
assert!(f == i && f == v);
buf += ~[t as u8];
stream_inc.input(~[t as u8]);
t += 1;
}
}
#[test] #[cfg(target_arch = "arm")]
pub fn test_hash_uint() {
let val = 0xdeadbeef_deadbeef_u64;
assert!((val as u64).hash()!= (val as uint).hash());
assert!((val as u32).hash() == (val as uint).hash());
}
#[tes
|
{
needed = 8 - self.ntail;
if length < needed {
let mut t = 0;
while t < length {
self.tail[self.ntail+t] = msg[t];
t += 1;
}
self.ntail += length;
return;
}
let mut t = 0;
while t < needed {
self.tail[self.ntail+t] = msg[t];
t += 1;
}
let m = u8to64_le!(self.tail, 0);
|
conditional_block
|
hash.rs
|
-> u64;
}
impl<A:Hash> HashUtil for A {
#[inline(always)]
fn hash(&self) -> u64 { self.hash_keyed(0,0) }
}
/// Streaming hash-functions should implement this.
pub trait Streaming {
fn input(&self, (&const [u8]));
// These can be refactored some when we have default methods.
fn result_bytes(&self) -> ~[u8];
fn result_str(&self) -> ~str;
fn result_u64(&self) -> u64;
fn reset(&self);
}
impl<A:IterBytes> Hash for A {
#[inline(always)]
fn hash_keyed(&self, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for self.iter_bytes(true) |bytes| {
s.input(bytes);
}
s.result_u64()
}
}
}
fn hash_keyed_2<A: IterBytes,
B: IterBytes>(a: &A, b: &B, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_3<A: IterBytes,
B: IterBytes,
C: IterBytes>(a: &A, b: &B, c: &C, k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_4<A: IterBytes,
B: IterBytes,
C: IterBytes,
D: IterBytes>(a: &A, b: &B, c: &C, d: &D, k0: u64, k1: u64)
-> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
for d.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
fn hash_keyed_5<A: IterBytes,
B: IterBytes,
C: IterBytes,
D: IterBytes,
E: IterBytes>(a: &A, b: &B, c: &C, d: &D, e: &E,
k0: u64, k1: u64) -> u64 {
unsafe {
let s = &State(k0, k1);
for a.iter_bytes(true) |bytes| { s.input(bytes); }
for b.iter_bytes(true) |bytes| { s.input(bytes); }
for c.iter_bytes(true) |bytes| { s.input(bytes); }
for d.iter_bytes(true) |bytes| { s.input(bytes); }
for e.iter_bytes(true) |bytes| { s.input(bytes); }
s.result_u64()
}
}
// Implement State as SipState
pub type State = SipState;
#[inline(always)]
pub fn State(k0: u64, k1: u64) -> State {
SipState(k0, k1)
}
#[inline(always)]
pub fn default_state() -> State {
State(0,0)
}
struct SipState {
k0: u64,
k1: u64,
mut length: uint, // how many bytes we've processed
mut v0: u64, // hash state
mut v1: u64,
mut v2: u64,
mut v3: u64,
mut tail: [u8,..8], // unprocessed bytes
mut ntail: uint, // how many bytes in tail are valid
}
#[inline(always)]
fn SipState(key0: u64, key1: u64) -> SipState {
let state = SipState {
k0 : key0,
k1 : key1,
mut length : 0u,
mut v0 : 0u64,
mut v1 : 0u64,
mut v2 : 0u64,
mut v3 : 0u64,
mut tail : [0u8,0,0,0,0,0,0,0],
mut ntail : 0u,
};
(&state).reset();
state
}
// sadly, these macro definitions can't appear later,
// because they're needed in the following defs;
// this design could be improved.
macro_rules! u8to64_le (
($buf:expr, $i:expr) =>
($buf[0+$i] as u64 |
$buf[1+$i] as u64 << 8 |
$buf[2+$i] as u64 << 16 |
$buf[3+$i] as u64 << 24 |
$buf[4+$i] as u64 << 32 |
$buf[5+$i] as u64 << 40 |
$buf[6+$i] as u64 << 48 |
$buf[7+$i] as u64 << 56)
)
macro_rules! rotl (
($x:expr, $b:expr) =>
(($x << $b) | ($x >> (64 - $b)))
)
macro_rules! compress (
($v0:expr, $v1:expr, $v2:expr, $v3:expr) =>
({
$v0 += $v1; $v1 = rotl!($v1, 13); $v1 ^= $v0;
$v0 = rotl!($v0, 32);
$v2 += $v3; $v3 = rotl!($v3, 16); $v3 ^= $v2;
$v0 += $v3; $v3 = rotl!($v3, 21); $v3 ^= $v0;
$v2 += $v1; $v1 = rotl!($v1, 17); $v1 ^= $v2;
$v2 = rotl!($v2, 32);
})
)
impl io::Writer for SipState {
// Methods for io::writer
#[inline(always)]
fn write(&self, msg: &const [u8]) {
let length = msg.len();
self.length += length;
let mut needed = 0u;
if self.ntail!= 0 {
needed = 8 - self.ntail;
if length < needed {
let mut t = 0;
while t < length {
self.tail[self.ntail+t] = msg[t];
t += 1;
}
self.ntail += length;
return;
}
let mut t = 0;
while t < needed {
self.tail[self.ntail+t] = msg[t];
t += 1;
}
let m = u8to64_le!(self.tail, 0);
self.v3 ^= m;
compress!(self.v0, self.v1, self.v2, self.v3);
compress!(self.v0, self.v1, self.v2, self.v3);
self.v0 ^= m;
self.ntail = 0;
}
// Buffered tail is now flushed, process new input.
let len = length - needed;
let end = len & (!0x7);
let left = len & 0x7;
let mut i = needed;
while i < end {
let mi = u8to64_le!(msg, i);
self.v3 ^= mi;
compress!(self.v0, self.v1, self.v2, self.v3);
compress!(self.v0, self.v1, self.v2, self.v3);
self.v0 ^= mi;
i += 8;
}
let mut t = 0u;
while t < left {
self.tail[t] = msg[i+t];
t += 1
}
self.ntail = left;
}
fn seek(&self, _x: int, _s: io::SeekStyle) {
fail!();
}
fn tell(&self) -> uint {
self.length
}
fn flush(&self) -> int {
0
}
fn get_type(&self) -> io::WriterType {
io::File
}
}
impl Streaming for SipState {
#[inline(always)]
fn input(&self, buf: &const [u8]) {
self.write(buf);
}
#[inline(always)]
fn result_u64(&self) -> u64 {
let mut v0 = self.v0;
let mut v1 = self.v1;
let mut v2 = self.v2;
let mut v3 = self.v3;
let mut b : u64 = (self.length as u64 & 0xff) << 56;
if self.ntail > 0 { b |= self.tail[0] as u64 << 0; }
if self.ntail > 1 { b |= self.tail[1] as u64 << 8; }
if self.ntail > 2 { b |= self.tail[2] as u64 << 16; }
if self.ntail > 3 { b |= self.tail[3] as u64 << 24; }
if self.ntail > 4 { b |= self.tail[4] as u64 << 32; }
if self.ntail > 5 { b |= self.tail[5] as u64 << 40; }
if self.ntail > 6 { b |= self.tail[6] as u64 << 48; }
v3 ^= b;
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
v0 ^= b;
v2 ^= 0xff;
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
compress!(v0, v1, v2, v3);
return (v0 ^ v1 ^ v2 ^ v3);
}
fn result_bytes(&self) -> ~[u8] {
let h = self.result_u64();
~[(h >> 0) as u8,
(h >> 8) as u8,
(h >> 16) as u8,
(h >> 24) as u8,
(h >> 32) as u8,
(h >> 40) as u8,
(h >> 48) as u8,
(h >> 56) as u8,
]
}
fn result_str(&self) -> ~str {
let r = self.result_bytes();
let mut s = ~"";
for vec::each(r) |b| {
s += uint::to_str_radix(*b as uint, 16u);
}
s
}
#[inline(always)]
fn reset(&self) {
self.length = 0;
self.v0 = self.k0 ^ 0x736f6d6570736575;
self.v1 = self.k1 ^ 0x646f72616e646f6d;
self.v2 = self.k0 ^ 0x6c7967656e657261;
self.v3 = self.k1 ^ 0x7465646279746573;
self.ntail = 0;
}
}
#[test]
pub fn test_siphash() {
let vecs : [[u8,..8],..64] = [
[ 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, ],
[ 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, ],
[ 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, ],
[ 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, ],
[ 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, ],
[ 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, ],
[ 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, ],
[ 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, ],
[ 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, ],
[ 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, ],
[ 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, ],
[ 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, ],
[ 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, ],
[ 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, ],
[ 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, ],
[ 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, ],
[ 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, ],
[ 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, ],
[ 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, ],
[ 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, ],
[ 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, ],
[ 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, ],
[ 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, ],
[ 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, ],
[ 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, ],
[ 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, ],
[ 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, ],
[ 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, ],
[ 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, ],
[ 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, ],
[ 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, ],
[ 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, ],
[ 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, ],
[ 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, ],
[ 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, ],
[ 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, ],
[ 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, ],
[ 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, ],
[ 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, ],
[ 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, ],
[ 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, ],
[ 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, ],
[ 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, ],
[ 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, ],
[ 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, ],
[ 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, ],
[ 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, ],
[ 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, ],
[ 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, ],
[ 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, ],
[ 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, ],
[ 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, ],
[ 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, ],
[ 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, ],
[ 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, ],
[ 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, ],
[ 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, ],
[ 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, ],
[ 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, ],
[ 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, ],
[ 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, ],
[ 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, ],
[ 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, ],
[ 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, ]
];
let k0 = 0x_07_06_05_04_03_02_01_00_u64;
let k1 = 0x_0f_0e_0d_0c_0b_0a_09_08_u64;
let mut buf : ~[u8] = ~[];
let mut t = 0;
let stream_inc = &State(k0,k1);
let stream_full = &State(k0,k1);
fn to_hex_str(r: &[u8,..8]) -> ~str {
let mut s = ~"";
for vec::each(*r) |b| {
s += uint::to_str_radix(*b as uint, 16u);
}
s
}
while t < 64 {
debug!("siphash test %?", t);
let vec = u8to64_le!(vecs[t], 0);
let out = buf.hash_keyed(k0, k1);
debug!("got %?, expected %?", out, vec);
assert!(vec == out);
stream_full.reset();
stream_full.input(buf);
let f = stream_full.result_str();
let i = stream_inc.result_str();
let v = to_hex_str(&vecs[t]);
debug!("%d: (%s) => inc=%s full=%s", t, v, i, f);
assert!(f == i && f == v);
buf += ~[t as u8];
stream_inc.input(~[t as u8]);
t += 1;
}
}
#[test] #[cfg(target_arch = "arm")]
pub fn test_hash_uint() {
let val = 0xdeadbeef_deadbeef_u64;
assert!((val as u64).hash()!= (val as uint).hash());
assert!((val as u32).hash() == (val as uint).hash());
}
#[test] #[cfg(target_arch = "x86_64")]
pub fn test_hash_uint() {
let val = 0xdeadbeef_deadbeef_u64;
assert!((val as u64).hash() == (val as uint).hash());
assert!((val as u32).hash()!= (val as uint).hash());
}
#[test] #[cfg(target_arch = "x86")]
pub fn test_hash_uint() {
let val = 0xdeadbeef_deadbeef_u64;
assert!((val as u64).hash()!= (val as uint).hash());
assert!((val as u32).hash() == (val as uint).hash());
}
#[test]
pub fn test_hash_idempotent()
|
{
let val64 = 0xdeadbeef_deadbeef_u64;
val64.hash() == val64.hash();
let val32 = 0xdeadbeef_u32;
val32.hash() == val32.hash();
}
|
identifier_body
|
|
command_loop.rs
|
extern crate i3ipc;
use i3ipc::I3Connection;
use std::io;
use std::io::Write;
fn
|
() {
println!("Executes i3 commands in a loop. Enter \"q\" at any time to quit.");
let mut connection = I3Connection::connect().expect("failed to connect");
let stdin = io::stdin();
let mut stdout = io::stdout();
loop {
print!(">>> ");
stdout.flush().unwrap();
let mut command_text = String::new();
stdin.read_line(&mut command_text).unwrap();
command_text.pop(); // throw away the \n
if command_text == "q" {
break;
}
let outcomes = connection
.run_command(&command_text)
.expect("failed to send command")
.outcomes;
for outcome in outcomes {
if outcome.success {
println!("success");
} else {
println!("failure");
if let Some(e) = outcome.error.as_ref() {
println!("{}", e);
}
}
}
}
// the socket closes when `connection` goes out of scope
}
|
main
|
identifier_name
|
command_loop.rs
|
extern crate i3ipc;
use i3ipc::I3Connection;
use std::io;
use std::io::Write;
fn main()
|
if outcome.success {
println!("success");
} else {
println!("failure");
if let Some(e) = outcome.error.as_ref() {
println!("{}", e);
}
}
}
}
// the socket closes when `connection` goes out of scope
}
|
{
println!("Executes i3 commands in a loop. Enter \"q\" at any time to quit.");
let mut connection = I3Connection::connect().expect("failed to connect");
let stdin = io::stdin();
let mut stdout = io::stdout();
loop {
print!(">>> ");
stdout.flush().unwrap();
let mut command_text = String::new();
stdin.read_line(&mut command_text).unwrap();
command_text.pop(); // throw away the \n
if command_text == "q" {
break;
}
let outcomes = connection
.run_command(&command_text)
.expect("failed to send command")
.outcomes;
for outcome in outcomes {
|
identifier_body
|
command_loop.rs
|
extern crate i3ipc;
use i3ipc::I3Connection;
use std::io;
use std::io::Write;
fn main() {
println!("Executes i3 commands in a loop. Enter \"q\" at any time to quit.");
let mut connection = I3Connection::connect().expect("failed to connect");
let stdin = io::stdin();
let mut stdout = io::stdout();
loop {
print!(">>> ");
stdout.flush().unwrap();
let mut command_text = String::new();
stdin.read_line(&mut command_text).unwrap();
command_text.pop(); // throw away the \n
if command_text == "q" {
break;
}
let outcomes = connection
.run_command(&command_text)
.expect("failed to send command")
.outcomes;
for outcome in outcomes {
if outcome.success {
println!("success");
} else {
println!("failure");
if let Some(e) = outcome.error.as_ref()
|
}
}
}
// the socket closes when `connection` goes out of scope
}
|
{
println!("{}", e);
}
|
conditional_block
|
command_loop.rs
|
extern crate i3ipc;
use i3ipc::I3Connection;
use std::io;
use std::io::Write;
fn main() {
println!("Executes i3 commands in a loop. Enter \"q\" at any time to quit.");
let mut connection = I3Connection::connect().expect("failed to connect");
let stdin = io::stdin();
let mut stdout = io::stdout();
loop {
print!(">>> ");
stdout.flush().unwrap();
let mut command_text = String::new();
|
command_text.pop(); // throw away the \n
if command_text == "q" {
break;
}
let outcomes = connection
.run_command(&command_text)
.expect("failed to send command")
.outcomes;
for outcome in outcomes {
if outcome.success {
println!("success");
} else {
println!("failure");
if let Some(e) = outcome.error.as_ref() {
println!("{}", e);
}
}
}
}
// the socket closes when `connection` goes out of scope
}
|
stdin.read_line(&mut command_text).unwrap();
|
random_line_split
|
fullscreen.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io::{self, Write};
mod support;
#[cfg(target_os = "android")]
android_start!(main);
fn main() {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
io::stdout().flush().unwrap();
let mut num = String::new();
io::stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let monitor = glutin::get_available_monitors().nth(num).expect("Please enter a valid ID");
println!("Using {:?}", monitor.get_name());
monitor
};
let window = glutin::WindowBuilder::new()
.with_title("Hello world!")
.with_fullscreen(monitor)
.build()
.unwrap();
let _ = unsafe { window.make_current() };
let context = support::load(&window);
for event in window.wait_events() {
context.draw_frame((0.0, 1.0, 0.0, 1.0));
let _ = window.swap_buffers();
println!("{:?}", event);
match event {
glutin::Event::Closed => break,
glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break,
|
_ => ()
}
}
}
|
random_line_split
|
|
fullscreen.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io::{self, Write};
mod support;
#[cfg(target_os = "android")]
android_start!(main);
fn
|
() {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
io::stdout().flush().unwrap();
let mut num = String::new();
io::stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let monitor = glutin::get_available_monitors().nth(num).expect("Please enter a valid ID");
println!("Using {:?}", monitor.get_name());
monitor
};
let window = glutin::WindowBuilder::new()
.with_title("Hello world!")
.with_fullscreen(monitor)
.build()
.unwrap();
let _ = unsafe { window.make_current() };
let context = support::load(&window);
for event in window.wait_events() {
context.draw_frame((0.0, 1.0, 0.0, 1.0));
let _ = window.swap_buffers();
println!("{:?}", event);
match event {
glutin::Event::Closed => break,
glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break,
_ => ()
}
}
}
|
main
|
identifier_name
|
fullscreen.rs
|
#[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io::{self, Write};
mod support;
#[cfg(target_os = "android")]
android_start!(main);
fn main()
|
let window = glutin::WindowBuilder::new()
.with_title("Hello world!")
.with_fullscreen(monitor)
.build()
.unwrap();
let _ = unsafe { window.make_current() };
let context = support::load(&window);
for event in window.wait_events() {
context.draw_frame((0.0, 1.0, 0.0, 1.0));
let _ = window.swap_buffers();
println!("{:?}", event);
match event {
glutin::Event::Closed => break,
glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) => break,
_ => ()
}
}
}
|
{
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
io::stdout().flush().unwrap();
let mut num = String::new();
io::stdin().read_line(&mut num).unwrap();
let num = num.trim().parse().ok().expect("Please enter a number");
let monitor = glutin::get_available_monitors().nth(num).expect("Please enter a valid ID");
println!("Using {:?}", monitor.get_name());
monitor
};
|
identifier_body
|
util.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.
use core::prelude::*;
use common::config;
use core::io;
use core::os::getenv;
pub fn make_new_path(path: ~str) -> ~str {
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match getenv(lib_path_env_var()) {
Some(curr) => {
fmt!("%s%s%s", path, path_div(), curr)
}
None => path
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "freebsd")]
pub fn lib_path_env_var() -> ~str { ~"LD_LIBRARY_PATH" }
#[cfg(target_os = "macos")]
pub fn lib_path_env_var() -> ~str { ~"DYLD_LIBRARY_PATH" }
#[cfg(target_os = "win32")]
pub fn lib_path_env_var() -> ~str
|
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
pub fn path_div() -> ~str { ~":" }
#[cfg(target_os = "win32")]
pub fn path_div() -> ~str { ~";" }
pub fn logv(config: config, s: ~str) {
debug!("%s", s);
if config.verbose { io::println(s); }
}
|
{ ~"PATH" }
|
identifier_body
|
util.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.
use core::prelude::*;
use common::config;
use core::io;
use core::os::getenv;
pub fn make_new_path(path: ~str) -> ~str {
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match getenv(lib_path_env_var()) {
Some(curr) => {
fmt!("%s%s%s", path, path_div(), curr)
}
None => path
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "freebsd")]
pub fn lib_path_env_var() -> ~str { ~"LD_LIBRARY_PATH" }
#[cfg(target_os = "macos")]
pub fn lib_path_env_var() -> ~str { ~"DYLD_LIBRARY_PATH" }
#[cfg(target_os = "win32")]
pub fn lib_path_env_var() -> ~str { ~"PATH" }
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
pub fn path_div() -> ~str { ~":" }
#[cfg(target_os = "win32")]
pub fn path_div() -> ~str { ~";" }
pub fn logv(config: config, s: ~str) {
debug!("%s", s);
if config.verbose
|
}
|
{ io::println(s); }
|
conditional_block
|
util.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.
use core::prelude::*;
use common::config;
use core::io;
use core::os::getenv;
pub fn make_new_path(path: ~str) -> ~str {
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match getenv(lib_path_env_var()) {
Some(curr) => {
fmt!("%s%s%s", path, path_div(), curr)
}
None => path
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "freebsd")]
pub fn lib_path_env_var() -> ~str { ~"LD_LIBRARY_PATH" }
|
pub fn lib_path_env_var() -> ~str { ~"DYLD_LIBRARY_PATH" }
#[cfg(target_os = "win32")]
pub fn lib_path_env_var() -> ~str { ~"PATH" }
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
pub fn path_div() -> ~str { ~":" }
#[cfg(target_os = "win32")]
pub fn path_div() -> ~str { ~";" }
pub fn logv(config: config, s: ~str) {
debug!("%s", s);
if config.verbose { io::println(s); }
}
|
#[cfg(target_os = "macos")]
|
random_line_split
|
util.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.
use core::prelude::*;
use common::config;
use core::io;
use core::os::getenv;
pub fn make_new_path(path: ~str) -> ~str {
// Windows just uses PATH as the library search path, so we have to
// maintain the current value while adding our own
match getenv(lib_path_env_var()) {
Some(curr) => {
fmt!("%s%s%s", path, path_div(), curr)
}
None => path
}
}
#[cfg(target_os = "linux")]
#[cfg(target_os = "freebsd")]
pub fn lib_path_env_var() -> ~str { ~"LD_LIBRARY_PATH" }
#[cfg(target_os = "macos")]
pub fn lib_path_env_var() -> ~str { ~"DYLD_LIBRARY_PATH" }
#[cfg(target_os = "win32")]
pub fn
|
() -> ~str { ~"PATH" }
#[cfg(target_os = "linux")]
#[cfg(target_os = "macos")]
#[cfg(target_os = "freebsd")]
pub fn path_div() -> ~str { ~":" }
#[cfg(target_os = "win32")]
pub fn path_div() -> ~str { ~";" }
pub fn logv(config: config, s: ~str) {
debug!("%s", s);
if config.verbose { io::println(s); }
}
|
lib_path_env_var
|
identifier_name
|
match-range-fail.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.
|
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: &'static str
//~| end type: &'static str
match "wow" {
10... "what" => ()
};
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: _
//~| end type: &'static str
match 5 {
'c'... 100 => { }
_ => { }
};
//~^^^ ERROR mismatched types in range
//~| expected char
//~| found integral variable
}
|
fn main() {
match "wow" {
"bar" ... "foo" => { }
};
|
random_line_split
|
match-range-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main()
|
//~| expected char
//~| found integral variable
}
|
{
match "wow" {
"bar" ... "foo" => { }
};
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: &'static str
//~| end type: &'static str
match "wow" {
10 ... "what" => ()
};
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: _
//~| end type: &'static str
match 5 {
'c' ... 100 => { }
_ => { }
};
//~^^^ ERROR mismatched types in range
|
identifier_body
|
match-range-fail.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn
|
() {
match "wow" {
"bar"... "foo" => { }
};
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: &'static str
//~| end type: &'static str
match "wow" {
10... "what" => ()
};
//~^^ ERROR only char and numeric types are allowed in range
//~| start type: _
//~| end type: &'static str
match 5 {
'c'... 100 => { }
_ => { }
};
//~^^^ ERROR mismatched types in range
//~| expected char
//~| found integral variable
}
|
main
|
identifier_name
|
tridiagonal.rs
|
use ndarray::*;
use ndarray_linalg::*;
// Solve `Ax=b` for tridiagonal matrix
fn solve() -> Result<(), error::LinalgError>
|
// Solve `Ax=b` for many b with fixed A
fn factorize() -> Result<(), error::LinalgError> {
let mut a: Array2<f64> = random((3, 3));
a[[0, 2]] = 0.0;
a[[2, 0]] = 0.0;
let f = a.factorize_tridiagonal()?; // LU factorize A (A is *not* consumed)
for _ in 0..10 {
let b: Array1<f64> = random(3);
let _x = f.solve_tridiagonal_into(b)?; // solve Ax=b using factorized L, U
}
Ok(())
}
fn main() {
solve().unwrap();
factorize().unwrap();
}
|
{
let mut a: Array2<f64> = random((3, 3));
let b: Array1<f64> = random(3);
a[[0, 2]] = 0.0;
a[[2, 0]] = 0.0;
let _x = a.solve_tridiagonal(&b)?;
Ok(())
}
|
identifier_body
|
tridiagonal.rs
|
use ndarray::*;
use ndarray_linalg::*;
// Solve `Ax=b` for tridiagonal matrix
fn solve() -> Result<(), error::LinalgError> {
let mut a: Array2<f64> = random((3, 3));
let b: Array1<f64> = random(3);
a[[0, 2]] = 0.0;
a[[2, 0]] = 0.0;
let _x = a.solve_tridiagonal(&b)?;
Ok(())
}
// Solve `Ax=b` for many b with fixed A
fn factorize() -> Result<(), error::LinalgError> {
let mut a: Array2<f64> = random((3, 3));
a[[0, 2]] = 0.0;
a[[2, 0]] = 0.0;
let f = a.factorize_tridiagonal()?; // LU factorize A (A is *not* consumed)
for _ in 0..10 {
let b: Array1<f64> = random(3);
let _x = f.solve_tridiagonal_into(b)?; // solve Ax=b using factorized L, U
}
Ok(())
}
fn
|
() {
solve().unwrap();
factorize().unwrap();
}
|
main
|
identifier_name
|
tridiagonal.rs
|
use ndarray::*;
use ndarray_linalg::*;
// Solve `Ax=b` for tridiagonal matrix
fn solve() -> Result<(), error::LinalgError> {
let mut a: Array2<f64> = random((3, 3));
let b: Array1<f64> = random(3);
a[[0, 2]] = 0.0;
a[[2, 0]] = 0.0;
let _x = a.solve_tridiagonal(&b)?;
Ok(())
}
// Solve `Ax=b` for many b with fixed A
fn factorize() -> Result<(), error::LinalgError> {
let mut a: Array2<f64> = random((3, 3));
a[[0, 2]] = 0.0;
a[[2, 0]] = 0.0;
let f = a.factorize_tridiagonal()?; // LU factorize A (A is *not* consumed)
for _ in 0..10 {
let b: Array1<f64> = random(3);
let _x = f.solve_tridiagonal_into(b)?; // solve Ax=b using factorized L, U
}
|
Ok(())
}
fn main() {
solve().unwrap();
factorize().unwrap();
}
|
random_line_split
|
|
lib.rs
|
#![feature(macro_rules, log_syntax, trace_macros)]
#![allow(unused_variable)]
#![allow(dead_code)]
extern crate serialize;
extern crate url;
extern crate time;
use std::iter::Peekable;
use std::vec::MoveItems;
use self::client::{JsonClient, Client, JsonResult, JsonError};
use self::sub::Subreddit;
use self::user::{User, Message};
use self::time::{Timespec, Tm, at_utc};
use self::url::Url;
macro_rules! construct_opt(
($ty:ident { $($name:ident: $val:expr),+, }) => (
match ($($val,)+) {
($(Some($name),)+) => Some($ty {
$($name: $name,)+
}),
_ => None,
}
);
)
mod client;
pub mod user;
pub mod sub;
pub mod post;
pub static BASE_URL: &'static str = "https://www.reddit.com";
pub type RedditResult<T> = Result<T, RedditError>;
static CLIENT: Client = self::client::Client;
#[deriving(Show)]
pub enum RedditError {
/// Authentication failed. Possibly because of an invalid username/password combo,
/// or an expired session cookie. Contains exact error message from the reddit API.
AuthError(String),
/// The user is not allowed to access that resource (HTTP 403).
PermissionDenied,
/// The requested resource was not found (HTTP 404).
NotFound,
/// This API call requires a modhash
NeedModhash,
/// The submission failed because reddit is requiring the user to solve a captcha.
NeedCaptcha,
MiscError(JsonError),
}
// Sucks we can't init this
local_data_key!(batch_size: u32)
/// Get the batch size or a sensible default
pub fn get_batch_size() -> u32
|
pub fn set_batch_size(val: u32) {
batch_size.replace(Some(val));
}
/// Login to reddit. Returns `Ok(Session)` on success, `Err(AuthError("reason"))` on failure.
pub fn login(user: &str, pass: &str) -> RedditResult<Session> {
let url = make_url("api/login");
let params = params! {
"user": user,
"pass": pass,
"rem": false, // This will give us the session cookie in the JSON response
};
let response = try!(CLIENT.post(&url, params).map_err(|e| MiscError(e)));
println!("{}", find(&response, "json");
}
/// Resume a session with the given cookie string; does not make a request
pub fn resume_session(cookie: &str) -> Session {
Session {
cookie: cookie.into_string(),
}
}
/// Find the subreddit with the given /r/ value
pub fn sub(sub: &str) -> RedditResult<Subreddit> {
use json::{find, FromJson};
let url = make_url(format!("r/{}/about.json", sub)[]);
let response = try!(CLIENT.get(&url).map_err(|e| MiscError(e)));
let data = find(&response, "data");
data.and_then(|j| FromJson::from_json(j))
.ok_or_else(|| NotFound)
}
/// Find a user with the given /u/ value
pub fn user(user: &str) -> RedditResult<User> {
unimplemented!();
}
pub fn make_url(url_part: &str) -> Url {
let url = format!("{}/{}", BASE_URL, url_part);
Url::parse(url[]).unwrap()
}
/// Struct representing an authenticated user session;
/// required by any API endpoint that submits changes to reddit, such as posting to subreddits, replying to comments, etc.
pub struct Session {
cookie: String,
}
impl Session {
/// Return info about the current user.
pub fn me(&self) -> User {
unimplemented!();
}
/// Get the session cookie to be restored later
/// This consumes the Session
pub fn logout(self) -> String {
self.cookie
}
pub fn cookie(&self) -> &str {
self.cookie[]
}
pub fn inbox(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn unread(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn sent(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn needs_captcha(&self) -> bool {
unimplemented!();
}
}
/// An iterator that fetches items in batches from an underlying data source.
/// Its item type must implement `Batched`.
pub struct BatchedIter<T> {
size: u32,
current: Peekable<T, MoveItems<T>>,
}
impl<T: Batched> Iterator<T> for BatchedIter<T> {
fn next(&mut self) -> Option<T> {
let next = self.current.next();
if self.current.peek().is_none() {
let batch = Batched::batch(next.as_ref(), self.size);
if!batch.is_empty() {
self.current = batch.move_iter().peekable();
}
}
next
}
}
/// A trait for data types that should be fetched in batches, if possible.
pub trait Batched {
/// Get the next batch of length `size` or smaller,
/// starting after `last` if provided, the beginning if not.
/// If no (more) results are available, return an empty vector.
fn batch(last: Option<&Self>, size: u32) -> Vec<Self>;
}
/// Convert POSIX time (seconds since January 1, 1970 12:00 AM)
/// to Tm (UTC)
pub fn posix_to_utc(seconds: u64) -> Tm {
// This cast is a bit dangerous,
// as it may result in a negative value due to overflow,
// indicating a pre-epoch time instead of the intended time.
// However, the point at which POSIX time will overflow a 64-bit integer
// is, according to Wolfram|Alpha, about 300 billion years in the future.
// I think it's safe to say that we can deal with this later.
let tmspec = Timespec::new(seconds as i64, 0);
at_utc(tmspec)
}
/// Lightweight utilities for working with `serialize::json::Json`.
pub mod json {
use serialize::json::Json;
use time::Tm;
/// Get a u64 from the given JSON and key, convert
/// it to a Tm in UTC, assuming it is POSIX time
pub fn find_utc(json: &Json, key: &str) -> Option<Tm> {
find_u64(json, key).map(super::posix_to_utc)
}
#[inline]
pub fn find<'a>(json: &'a Json, key: &str) -> Option<&'a Json> {
json.find(&(key.into_string()))
}
pub fn find_string(json: &Json, key: &str) -> Option<String> {
find(json, key).and_then(|j| j.as_string()).map(|s| s.into_string())
}
pub fn find_u64(json: &Json, key: &str) -> Option<u64> {
find(json, key).and_then(|j| j.as_u64())
}
pub fn find_f64(json: &Json, key: &str) -> Option<f64> {
find(json, key).and_then(|j| j.as_f64())
}
pub fn find_u32(json: &Json, key: &str) -> Option<u32> {
find(json, key).and_then(|j| j.as_u64()).map(|x| x as u32)
}
/// A lighter-weight implementation alternative of Decodable for
/// structs that just want to deserialize from JSON
/// TODO: Implement this using a streaming parser
pub trait FromJson {
fn from_json(json: &Json) -> Option<Self>;
}
}
|
{
batch_size.get().map_or(50u32, |val| *val)
}
|
identifier_body
|
lib.rs
|
#![feature(macro_rules, log_syntax, trace_macros)]
#![allow(unused_variable)]
#![allow(dead_code)]
extern crate serialize;
extern crate url;
extern crate time;
use std::iter::Peekable;
use std::vec::MoveItems;
use self::client::{JsonClient, Client, JsonResult, JsonError};
use self::sub::Subreddit;
use self::user::{User, Message};
use self::time::{Timespec, Tm, at_utc};
use self::url::Url;
macro_rules! construct_opt(
($ty:ident { $($name:ident: $val:expr),+, }) => (
match ($($val,)+) {
($(Some($name),)+) => Some($ty {
$($name: $name,)+
}),
_ => None,
}
);
)
mod client;
pub mod user;
pub mod sub;
pub mod post;
pub static BASE_URL: &'static str = "https://www.reddit.com";
pub type RedditResult<T> = Result<T, RedditError>;
static CLIENT: Client = self::client::Client;
#[deriving(Show)]
pub enum RedditError {
/// Authentication failed. Possibly because of an invalid username/password combo,
/// or an expired session cookie. Contains exact error message from the reddit API.
AuthError(String),
/// The user is not allowed to access that resource (HTTP 403).
PermissionDenied,
/// The requested resource was not found (HTTP 404).
NotFound,
/// This API call requires a modhash
NeedModhash,
/// The submission failed because reddit is requiring the user to solve a captcha.
NeedCaptcha,
MiscError(JsonError),
}
// Sucks we can't init this
local_data_key!(batch_size: u32)
/// Get the batch size or a sensible default
pub fn get_batch_size() -> u32 {
batch_size.get().map_or(50u32, |val| *val)
}
pub fn set_batch_size(val: u32) {
batch_size.replace(Some(val));
}
/// Login to reddit. Returns `Ok(Session)` on success, `Err(AuthError("reason"))` on failure.
pub fn login(user: &str, pass: &str) -> RedditResult<Session> {
let url = make_url("api/login");
let params = params! {
"user": user,
"pass": pass,
"rem": false, // This will give us the session cookie in the JSON response
};
let response = try!(CLIENT.post(&url, params).map_err(|e| MiscError(e)));
println!("{}", find(&response, "json");
}
/// Resume a session with the given cookie string; does not make a request
pub fn resume_session(cookie: &str) -> Session {
Session {
cookie: cookie.into_string(),
}
}
/// Find the subreddit with the given /r/ value
pub fn sub(sub: &str) -> RedditResult<Subreddit> {
use json::{find, FromJson};
let url = make_url(format!("r/{}/about.json", sub)[]);
let response = try!(CLIENT.get(&url).map_err(|e| MiscError(e)));
let data = find(&response, "data");
data.and_then(|j| FromJson::from_json(j))
.ok_or_else(|| NotFound)
}
/// Find a user with the given /u/ value
pub fn user(user: &str) -> RedditResult<User> {
unimplemented!();
}
pub fn
|
(url_part: &str) -> Url {
let url = format!("{}/{}", BASE_URL, url_part);
Url::parse(url[]).unwrap()
}
/// Struct representing an authenticated user session;
/// required by any API endpoint that submits changes to reddit, such as posting to subreddits, replying to comments, etc.
pub struct Session {
cookie: String,
}
impl Session {
/// Return info about the current user.
pub fn me(&self) -> User {
unimplemented!();
}
/// Get the session cookie to be restored later
/// This consumes the Session
pub fn logout(self) -> String {
self.cookie
}
pub fn cookie(&self) -> &str {
self.cookie[]
}
pub fn inbox(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn unread(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn sent(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn needs_captcha(&self) -> bool {
unimplemented!();
}
}
/// An iterator that fetches items in batches from an underlying data source.
/// Its item type must implement `Batched`.
pub struct BatchedIter<T> {
size: u32,
current: Peekable<T, MoveItems<T>>,
}
impl<T: Batched> Iterator<T> for BatchedIter<T> {
fn next(&mut self) -> Option<T> {
let next = self.current.next();
if self.current.peek().is_none() {
let batch = Batched::batch(next.as_ref(), self.size);
if!batch.is_empty() {
self.current = batch.move_iter().peekable();
}
}
next
}
}
/// A trait for data types that should be fetched in batches, if possible.
pub trait Batched {
/// Get the next batch of length `size` or smaller,
/// starting after `last` if provided, the beginning if not.
/// If no (more) results are available, return an empty vector.
fn batch(last: Option<&Self>, size: u32) -> Vec<Self>;
}
/// Convert POSIX time (seconds since January 1, 1970 12:00 AM)
/// to Tm (UTC)
pub fn posix_to_utc(seconds: u64) -> Tm {
// This cast is a bit dangerous,
// as it may result in a negative value due to overflow,
// indicating a pre-epoch time instead of the intended time.
// However, the point at which POSIX time will overflow a 64-bit integer
// is, according to Wolfram|Alpha, about 300 billion years in the future.
// I think it's safe to say that we can deal with this later.
let tmspec = Timespec::new(seconds as i64, 0);
at_utc(tmspec)
}
/// Lightweight utilities for working with `serialize::json::Json`.
pub mod json {
use serialize::json::Json;
use time::Tm;
/// Get a u64 from the given JSON and key, convert
/// it to a Tm in UTC, assuming it is POSIX time
pub fn find_utc(json: &Json, key: &str) -> Option<Tm> {
find_u64(json, key).map(super::posix_to_utc)
}
#[inline]
pub fn find<'a>(json: &'a Json, key: &str) -> Option<&'a Json> {
json.find(&(key.into_string()))
}
pub fn find_string(json: &Json, key: &str) -> Option<String> {
find(json, key).and_then(|j| j.as_string()).map(|s| s.into_string())
}
pub fn find_u64(json: &Json, key: &str) -> Option<u64> {
find(json, key).and_then(|j| j.as_u64())
}
pub fn find_f64(json: &Json, key: &str) -> Option<f64> {
find(json, key).and_then(|j| j.as_f64())
}
pub fn find_u32(json: &Json, key: &str) -> Option<u32> {
find(json, key).and_then(|j| j.as_u64()).map(|x| x as u32)
}
/// A lighter-weight implementation alternative of Decodable for
/// structs that just want to deserialize from JSON
/// TODO: Implement this using a streaming parser
pub trait FromJson {
fn from_json(json: &Json) -> Option<Self>;
}
}
|
make_url
|
identifier_name
|
lib.rs
|
#![feature(macro_rules, log_syntax, trace_macros)]
#![allow(unused_variable)]
#![allow(dead_code)]
extern crate serialize;
extern crate url;
extern crate time;
use std::iter::Peekable;
use std::vec::MoveItems;
use self::client::{JsonClient, Client, JsonResult, JsonError};
use self::sub::Subreddit;
use self::user::{User, Message};
use self::time::{Timespec, Tm, at_utc};
use self::url::Url;
macro_rules! construct_opt(
($ty:ident { $($name:ident: $val:expr),+, }) => (
match ($($val,)+) {
($(Some($name),)+) => Some($ty {
$($name: $name,)+
}),
_ => None,
}
);
)
mod client;
pub mod user;
pub mod sub;
pub mod post;
pub static BASE_URL: &'static str = "https://www.reddit.com";
pub type RedditResult<T> = Result<T, RedditError>;
static CLIENT: Client = self::client::Client;
#[deriving(Show)]
pub enum RedditError {
/// Authentication failed. Possibly because of an invalid username/password combo,
/// or an expired session cookie. Contains exact error message from the reddit API.
AuthError(String),
/// The user is not allowed to access that resource (HTTP 403).
PermissionDenied,
/// The requested resource was not found (HTTP 404).
NotFound,
/// This API call requires a modhash
NeedModhash,
/// The submission failed because reddit is requiring the user to solve a captcha.
NeedCaptcha,
MiscError(JsonError),
}
// Sucks we can't init this
local_data_key!(batch_size: u32)
/// Get the batch size or a sensible default
pub fn get_batch_size() -> u32 {
batch_size.get().map_or(50u32, |val| *val)
}
pub fn set_batch_size(val: u32) {
batch_size.replace(Some(val));
}
/// Login to reddit. Returns `Ok(Session)` on success, `Err(AuthError("reason"))` on failure.
pub fn login(user: &str, pass: &str) -> RedditResult<Session> {
let url = make_url("api/login");
let params = params! {
"user": user,
"pass": pass,
"rem": false, // This will give us the session cookie in the JSON response
};
let response = try!(CLIENT.post(&url, params).map_err(|e| MiscError(e)));
println!("{}", find(&response, "json");
}
/// Resume a session with the given cookie string; does not make a request
pub fn resume_session(cookie: &str) -> Session {
Session {
cookie: cookie.into_string(),
}
}
/// Find the subreddit with the given /r/ value
pub fn sub(sub: &str) -> RedditResult<Subreddit> {
use json::{find, FromJson};
let url = make_url(format!("r/{}/about.json", sub)[]);
let response = try!(CLIENT.get(&url).map_err(|e| MiscError(e)));
let data = find(&response, "data");
data.and_then(|j| FromJson::from_json(j))
.ok_or_else(|| NotFound)
}
/// Find a user with the given /u/ value
pub fn user(user: &str) -> RedditResult<User> {
unimplemented!();
}
pub fn make_url(url_part: &str) -> Url {
let url = format!("{}/{}", BASE_URL, url_part);
Url::parse(url[]).unwrap()
}
/// Struct representing an authenticated user session;
/// required by any API endpoint that submits changes to reddit, such as posting to subreddits, replying to comments, etc.
pub struct Session {
cookie: String,
}
impl Session {
/// Return info about the current user.
pub fn me(&self) -> User {
unimplemented!();
}
/// Get the session cookie to be restored later
/// This consumes the Session
pub fn logout(self) -> String {
self.cookie
}
pub fn cookie(&self) -> &str {
self.cookie[]
}
pub fn inbox(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn unread(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn sent(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn needs_captcha(&self) -> bool {
unimplemented!();
}
}
/// An iterator that fetches items in batches from an underlying data source.
/// Its item type must implement `Batched`.
pub struct BatchedIter<T> {
size: u32,
current: Peekable<T, MoveItems<T>>,
}
impl<T: Batched> Iterator<T> for BatchedIter<T> {
fn next(&mut self) -> Option<T> {
let next = self.current.next();
if self.current.peek().is_none()
|
next
}
}
/// A trait for data types that should be fetched in batches, if possible.
pub trait Batched {
/// Get the next batch of length `size` or smaller,
/// starting after `last` if provided, the beginning if not.
/// If no (more) results are available, return an empty vector.
fn batch(last: Option<&Self>, size: u32) -> Vec<Self>;
}
/// Convert POSIX time (seconds since January 1, 1970 12:00 AM)
/// to Tm (UTC)
pub fn posix_to_utc(seconds: u64) -> Tm {
// This cast is a bit dangerous,
// as it may result in a negative value due to overflow,
// indicating a pre-epoch time instead of the intended time.
// However, the point at which POSIX time will overflow a 64-bit integer
// is, according to Wolfram|Alpha, about 300 billion years in the future.
// I think it's safe to say that we can deal with this later.
let tmspec = Timespec::new(seconds as i64, 0);
at_utc(tmspec)
}
/// Lightweight utilities for working with `serialize::json::Json`.
pub mod json {
use serialize::json::Json;
use time::Tm;
/// Get a u64 from the given JSON and key, convert
/// it to a Tm in UTC, assuming it is POSIX time
pub fn find_utc(json: &Json, key: &str) -> Option<Tm> {
find_u64(json, key).map(super::posix_to_utc)
}
#[inline]
pub fn find<'a>(json: &'a Json, key: &str) -> Option<&'a Json> {
json.find(&(key.into_string()))
}
pub fn find_string(json: &Json, key: &str) -> Option<String> {
find(json, key).and_then(|j| j.as_string()).map(|s| s.into_string())
}
pub fn find_u64(json: &Json, key: &str) -> Option<u64> {
find(json, key).and_then(|j| j.as_u64())
}
pub fn find_f64(json: &Json, key: &str) -> Option<f64> {
find(json, key).and_then(|j| j.as_f64())
}
pub fn find_u32(json: &Json, key: &str) -> Option<u32> {
find(json, key).and_then(|j| j.as_u64()).map(|x| x as u32)
}
/// A lighter-weight implementation alternative of Decodable for
/// structs that just want to deserialize from JSON
/// TODO: Implement this using a streaming parser
pub trait FromJson {
fn from_json(json: &Json) -> Option<Self>;
}
}
|
{
let batch = Batched::batch(next.as_ref(), self.size);
if !batch.is_empty() {
self.current = batch.move_iter().peekable();
}
}
|
conditional_block
|
lib.rs
|
#![feature(macro_rules, log_syntax, trace_macros)]
#![allow(unused_variable)]
#![allow(dead_code)]
extern crate serialize;
extern crate url;
extern crate time;
use std::iter::Peekable;
use std::vec::MoveItems;
use self::client::{JsonClient, Client, JsonResult, JsonError};
use self::sub::Subreddit;
use self::user::{User, Message};
use self::time::{Timespec, Tm, at_utc};
use self::url::Url;
macro_rules! construct_opt(
($ty:ident { $($name:ident: $val:expr),+, }) => (
match ($($val,)+) {
($(Some($name),)+) => Some($ty {
$($name: $name,)+
}),
_ => None,
}
);
)
mod client;
pub mod user;
pub mod sub;
pub mod post;
pub static BASE_URL: &'static str = "https://www.reddit.com";
pub type RedditResult<T> = Result<T, RedditError>;
static CLIENT: Client = self::client::Client;
#[deriving(Show)]
pub enum RedditError {
/// Authentication failed. Possibly because of an invalid username/password combo,
/// or an expired session cookie. Contains exact error message from the reddit API.
AuthError(String),
/// The user is not allowed to access that resource (HTTP 403).
PermissionDenied,
/// The requested resource was not found (HTTP 404).
NotFound,
/// This API call requires a modhash
NeedModhash,
/// The submission failed because reddit is requiring the user to solve a captcha.
NeedCaptcha,
MiscError(JsonError),
}
// Sucks we can't init this
local_data_key!(batch_size: u32)
/// Get the batch size or a sensible default
pub fn get_batch_size() -> u32 {
batch_size.get().map_or(50u32, |val| *val)
}
pub fn set_batch_size(val: u32) {
batch_size.replace(Some(val));
}
/// Login to reddit. Returns `Ok(Session)` on success, `Err(AuthError("reason"))` on failure.
pub fn login(user: &str, pass: &str) -> RedditResult<Session> {
let url = make_url("api/login");
let params = params! {
"user": user,
"pass": pass,
"rem": false, // This will give us the session cookie in the JSON response
};
let response = try!(CLIENT.post(&url, params).map_err(|e| MiscError(e)));
println!("{}", find(&response, "json");
}
/// Resume a session with the given cookie string; does not make a request
pub fn resume_session(cookie: &str) -> Session {
Session {
cookie: cookie.into_string(),
}
}
/// Find the subreddit with the given /r/ value
pub fn sub(sub: &str) -> RedditResult<Subreddit> {
use json::{find, FromJson};
let url = make_url(format!("r/{}/about.json", sub)[]);
let response = try!(CLIENT.get(&url).map_err(|e| MiscError(e)));
let data = find(&response, "data");
data.and_then(|j| FromJson::from_json(j))
.ok_or_else(|| NotFound)
}
/// Find a user with the given /u/ value
pub fn user(user: &str) -> RedditResult<User> {
unimplemented!();
}
pub fn make_url(url_part: &str) -> Url {
let url = format!("{}/{}", BASE_URL, url_part);
Url::parse(url[]).unwrap()
}
/// Struct representing an authenticated user session;
/// required by any API endpoint that submits changes to reddit, such as posting to subreddits, replying to comments, etc.
pub struct Session {
cookie: String,
}
impl Session {
/// Return info about the current user.
pub fn me(&self) -> User {
unimplemented!();
}
/// Get the session cookie to be restored later
/// This consumes the Session
pub fn logout(self) -> String {
self.cookie
}
pub fn cookie(&self) -> &str {
self.cookie[]
}
pub fn inbox(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn unread(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn sent(&self) -> BatchedIter<Message> {
unimplemented!();
}
pub fn needs_captcha(&self) -> bool {
unimplemented!();
}
}
/// An iterator that fetches items in batches from an underlying data source.
/// Its item type must implement `Batched`.
pub struct BatchedIter<T> {
size: u32,
current: Peekable<T, MoveItems<T>>,
}
impl<T: Batched> Iterator<T> for BatchedIter<T> {
fn next(&mut self) -> Option<T> {
let next = self.current.next();
if self.current.peek().is_none() {
let batch = Batched::batch(next.as_ref(), self.size);
if!batch.is_empty() {
self.current = batch.move_iter().peekable();
}
}
next
}
}
/// A trait for data types that should be fetched in batches, if possible.
pub trait Batched {
/// Get the next batch of length `size` or smaller,
/// starting after `last` if provided, the beginning if not.
/// If no (more) results are available, return an empty vector.
fn batch(last: Option<&Self>, size: u32) -> Vec<Self>;
}
/// Convert POSIX time (seconds since January 1, 1970 12:00 AM)
/// to Tm (UTC)
pub fn posix_to_utc(seconds: u64) -> Tm {
// This cast is a bit dangerous,
// as it may result in a negative value due to overflow,
// indicating a pre-epoch time instead of the intended time.
// However, the point at which POSIX time will overflow a 64-bit integer
|
at_utc(tmspec)
}
/// Lightweight utilities for working with `serialize::json::Json`.
pub mod json {
use serialize::json::Json;
use time::Tm;
/// Get a u64 from the given JSON and key, convert
/// it to a Tm in UTC, assuming it is POSIX time
pub fn find_utc(json: &Json, key: &str) -> Option<Tm> {
find_u64(json, key).map(super::posix_to_utc)
}
#[inline]
pub fn find<'a>(json: &'a Json, key: &str) -> Option<&'a Json> {
json.find(&(key.into_string()))
}
pub fn find_string(json: &Json, key: &str) -> Option<String> {
find(json, key).and_then(|j| j.as_string()).map(|s| s.into_string())
}
pub fn find_u64(json: &Json, key: &str) -> Option<u64> {
find(json, key).and_then(|j| j.as_u64())
}
pub fn find_f64(json: &Json, key: &str) -> Option<f64> {
find(json, key).and_then(|j| j.as_f64())
}
pub fn find_u32(json: &Json, key: &str) -> Option<u32> {
find(json, key).and_then(|j| j.as_u64()).map(|x| x as u32)
}
/// A lighter-weight implementation alternative of Decodable for
/// structs that just want to deserialize from JSON
/// TODO: Implement this using a streaming parser
pub trait FromJson {
fn from_json(json: &Json) -> Option<Self>;
}
}
|
// is, according to Wolfram|Alpha, about 300 billion years in the future.
// I think it's safe to say that we can deal with this later.
let tmspec = Timespec::new(seconds as i64, 0);
|
random_line_split
|
mod.rs
|
//! Implementations of the Wayland backends using the system `libwayland`
use crate::protocol::ArgumentType;
use wayland_sys::common::{wl_argument, wl_array};
#[cfg(any(test, feature = "client_system"))]
pub mod client;
#[cfg(any(test, feature = "server_system"))]
pub mod server;
/// Magic static for wayland objects managed by wayland-client or wayland-server
///
/// This static serves no purpose other than existing at a stable address.
static RUST_MANAGED: u8 = 42;
unsafe fn free_arrays(signature: &[ArgumentType], arglist: &[wl_argument])
|
{
for (typ, arg) in signature.iter().zip(arglist.iter()) {
if let ArgumentType::Array(_) = typ {
// Safety: the arglist provided arglist must be valid for associated signature
// and contains pointers to boxed arrays as appropriate
let _ = unsafe { Box::from_raw(arg.a as *mut wl_array) };
}
}
}
|
identifier_body
|
|
mod.rs
|
//! Implementations of the Wayland backends using the system `libwayland`
use crate::protocol::ArgumentType;
use wayland_sys::common::{wl_argument, wl_array};
#[cfg(any(test, feature = "client_system"))]
pub mod client;
#[cfg(any(test, feature = "server_system"))]
pub mod server;
/// Magic static for wayland objects managed by wayland-client or wayland-server
///
/// This static serves no purpose other than existing at a stable address.
static RUST_MANAGED: u8 = 42;
unsafe fn free_arrays(signature: &[ArgumentType], arglist: &[wl_argument]) {
for (typ, arg) in signature.iter().zip(arglist.iter()) {
if let ArgumentType::Array(_) = typ
|
}
}
|
{
// Safety: the arglist provided arglist must be valid for associated signature
// and contains pointers to boxed arrays as appropriate
let _ = unsafe { Box::from_raw(arg.a as *mut wl_array) };
}
|
conditional_block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.