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 |
---|---|---|---|---|
import-glob-circular.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-pattern: unresolved
mod circ1 {
pub use circ2::f2;
pub fn
|
() { info!("f1"); }
pub fn common() -> uint { return 0u; }
}
mod circ2 {
pub use circ1::f1;
pub fn f2() { info!("f2"); }
pub fn common() -> uint { return 1u; }
}
mod test {
use circ1::*;
fn test() { f1066(); }
}
|
f1
|
identifier_name
|
main.rs
|
mod vector;
mod objects;
mod raytrace;
use vector::*;
use objects::*;
use raytrace::*;
fn main()
|
specular_exponent: 100.0
};
let scene = Scene {
camera: Camera {
position: Vec3::new(0.0, 0.0, 0.0),
direction: Vec3::new(0.0, 0.0, -1.0),
up: Vec3::new(0.0, 1.0, 0.0)
},
lights: vec![
Light {
position: Point::new(0.5, 0.0, -0.2),
color: Color::new(1.0, 1.0, 1.0),
intensity: 0.6
},
Light {
position: Point::new(-0.8, 0.5, -0.1),
color: Color::new(1.0, 1.0, 1.0),
intensity: 0.2
}],
objects: vec![(sphere, material), (sphere2, material2)]
};
raytrace(&scene, 1920, 1080, std::f64::consts::PI / 3.5);
}
|
{
let sphere = Object::Sphere {
center: Vec3::new(0.0, 0.0, -2.0),
radius: 0.5
};
let material = Material {
ambient: Color::new(0.0, 0.2, 0.2),
diffuse: Color::new(1.0, 1.0, 1.0),
specular: Color::new(1.0, 1.0, 1.0),
specular_exponent: 10.0
};
let sphere2 = Object::Sphere {
center: Vec3::new(0.2, 0.0, -1.0),
radius: 0.1
};
let material2 = Material {
ambient: Color::new(0.2, 0.0, 0.2),
diffuse: Color::new(1.0, 1.0, 1.0),
specular: Color::new(1.0, 1.0, 1.0),
|
identifier_body
|
main.rs
|
mod vector;
mod objects;
mod raytrace;
use vector::*;
use objects::*;
use raytrace::*;
fn main() {
let sphere = Object::Sphere {
center: Vec3::new(0.0, 0.0, -2.0),
radius: 0.5
};
let material = Material {
ambient: Color::new(0.0, 0.2, 0.2),
diffuse: Color::new(1.0, 1.0, 1.0),
specular: Color::new(1.0, 1.0, 1.0),
specular_exponent: 10.0
};
let sphere2 = Object::Sphere {
center: Vec3::new(0.2, 0.0, -1.0),
radius: 0.1
};
let material2 = Material {
ambient: Color::new(0.2, 0.0, 0.2),
diffuse: Color::new(1.0, 1.0, 1.0),
specular: Color::new(1.0, 1.0, 1.0),
specular_exponent: 100.0
};
let scene = Scene {
camera: Camera {
position: Vec3::new(0.0, 0.0, 0.0),
direction: Vec3::new(0.0, 0.0, -1.0),
up: Vec3::new(0.0, 1.0, 0.0)
},
lights: vec![
Light {
position: Point::new(0.5, 0.0, -0.2),
color: Color::new(1.0, 1.0, 1.0),
intensity: 0.6
},
Light {
position: Point::new(-0.8, 0.5, -0.1),
color: Color::new(1.0, 1.0, 1.0),
|
intensity: 0.2
}],
objects: vec![(sphere, material), (sphere2, material2)]
};
raytrace(&scene, 1920, 1080, std::f64::consts::PI / 3.5);
}
|
random_line_split
|
|
main.rs
|
mod vector;
mod objects;
mod raytrace;
use vector::*;
use objects::*;
use raytrace::*;
fn
|
() {
let sphere = Object::Sphere {
center: Vec3::new(0.0, 0.0, -2.0),
radius: 0.5
};
let material = Material {
ambient: Color::new(0.0, 0.2, 0.2),
diffuse: Color::new(1.0, 1.0, 1.0),
specular: Color::new(1.0, 1.0, 1.0),
specular_exponent: 10.0
};
let sphere2 = Object::Sphere {
center: Vec3::new(0.2, 0.0, -1.0),
radius: 0.1
};
let material2 = Material {
ambient: Color::new(0.2, 0.0, 0.2),
diffuse: Color::new(1.0, 1.0, 1.0),
specular: Color::new(1.0, 1.0, 1.0),
specular_exponent: 100.0
};
let scene = Scene {
camera: Camera {
position: Vec3::new(0.0, 0.0, 0.0),
direction: Vec3::new(0.0, 0.0, -1.0),
up: Vec3::new(0.0, 1.0, 0.0)
},
lights: vec![
Light {
position: Point::new(0.5, 0.0, -0.2),
color: Color::new(1.0, 1.0, 1.0),
intensity: 0.6
},
Light {
position: Point::new(-0.8, 0.5, -0.1),
color: Color::new(1.0, 1.0, 1.0),
intensity: 0.2
}],
objects: vec![(sphere, material), (sphere2, material2)]
};
raytrace(&scene, 1920, 1080, std::f64::consts::PI / 3.5);
}
|
main
|
identifier_name
|
homotopy.rs
|
/*
This example demonstrates the usage of a discrete homotopy space.
In homotopy theory, one constructs a continuous map between functions.
There can be many different kinds of continuous maps, so spaces get very complex.
It even gets worse by having continuous maps between continuous maps.
Since there is a combinatorial explosion of possibilities,
mathematicians developed techniques to classify these spaces.
One of these techniques is called a "homotopy level".
Here is an introduction by Vladimir Voedvodsky: https://www.youtube.com/watch?v=E3steS2Hr1Y
A homotopy level is a way of connecting pieces of a space of a lower homotopy level.
At homotopy level 0, the pieces of the space itself are constructed.
In a space consisting of a single element,
there exists only one way of connecting it to iself,
therefore at homotopy level 1, there is just one element.
This element represents the path from element in homotopy level 0 to itself.
At homotopy level 2, the paths in homotopy level 1 are connected.
Since there is only one path, there is only one path between paths at level 2.
However, when you start with 2 elements at homotopy level 0,
there are 3 ways to connect the 2 elements in homotopy level 1:
0 ~= 0 0 ~= 1 1 ~= 1
Here is an overview of the first 6 homotopy levels up to `n=4`:
level n=0 n=1 n=2 n=3 n=4
0 0 1 2 3 4
1 0 1 3 6 10
2 0 1 6 21 55
3 0 1 21 231 1540
4 0 1 231 26796 1186570
5 0 1 26796 359026206 703974775735
*/
extern crate discrete;
use discrete::*;
use HPoint::*;
fn main()
|
println!("================================");
println!("Another way to construct a homotopy level 2 is to use `EqPair<Of<EqPair>>`:");
let s: EqPair<Of<EqPair>> = Construct::new();
let dim = 2;
println!("{}", s.count(&dim));
println!("Similarly, at homotopy level 3 one can use `EqPair<Of<EqPair<Of<EqPair>>>>`:");
let s: EqPair<Of<EqPair<Of<EqPair>>>> = Construct::new();
let dim = 2;
println!("{}", s.count(&dim));
println!("However, for the more general case is it easier to use the `Homotopy` space:");
let s: Homotopy = Construct::new();
let level = 2;
let pieces = 2;
let n = s.count(&(level, pieces));
println!("{}", n);
let mut pos = s.zero(&(level, pieces));
for x in 0..n {
s.to_pos(&(level, pieces), x, &mut pos);
println!("{:?}", pos);
}
println!("================================");
println!("The `HPoint` enum represents positions in the `Homotopy` space:");
let a = Path(Box::new((Point(0), Point(0))));
let b = Path(Box::new((Point(1), Point(1))));
let pos = Path(Box::new((a, b)));
let level = pos.level();
println!("{:?} - level {}", pos, level);
println!("{}", s.to_index(&(level, 2), &pos));
println!("================================");
println!("One can also construct a homotopy of another discrete space, e.g. `Homotopy<Of<Pair>>`:");
let s: Homotopy<Of<Pair>> = Construct::new();
let level = 1;
let pieces = 3;
let n = s.count(&(level, pieces));
println!("{}", n);
let mut pos = s.zero(&(level, pieces));
for x in 0..n {
s.to_pos(&(level, pieces), x, &mut pos);
println!("{:?}", pos);
}
}
|
{
println!("A discrete homotopy space uses `EqPair` internally:");
let s: EqPair = Construct::new();
let dim = 4;
let n = s.count(&dim);
println!("{}", n);
let mut pos = (0, 0);
for x in 0..n {
s.to_pos(&n, x, &mut pos);
println!("{:?}", pos);
}
println!("================================");
println!("Using `EqPair` recursively gives the complexity of homotopy levels:");
let mut dim = 4;
println!("{}", dim);
for _ in 0..5 {
dim = s.count(&dim);
println!("{}", dim);
}
|
identifier_body
|
homotopy.rs
|
/*
This example demonstrates the usage of a discrete homotopy space.
In homotopy theory, one constructs a continuous map between functions.
There can be many different kinds of continuous maps, so spaces get very complex.
It even gets worse by having continuous maps between continuous maps.
Since there is a combinatorial explosion of possibilities,
mathematicians developed techniques to classify these spaces.
One of these techniques is called a "homotopy level".
Here is an introduction by Vladimir Voedvodsky: https://www.youtube.com/watch?v=E3steS2Hr1Y
A homotopy level is a way of connecting pieces of a space of a lower homotopy level.
At homotopy level 0, the pieces of the space itself are constructed.
In a space consisting of a single element,
there exists only one way of connecting it to iself,
therefore at homotopy level 1, there is just one element.
This element represents the path from element in homotopy level 0 to itself.
At homotopy level 2, the paths in homotopy level 1 are connected.
Since there is only one path, there is only one path between paths at level 2.
However, when you start with 2 elements at homotopy level 0,
there are 3 ways to connect the 2 elements in homotopy level 1:
0 ~= 0 0 ~= 1 1 ~= 1
Here is an overview of the first 6 homotopy levels up to `n=4`:
level n=0 n=1 n=2 n=3 n=4
0 0 1 2 3 4
1 0 1 3 6 10
2 0 1 6 21 55
3 0 1 21 231 1540
4 0 1 231 26796 1186570
5 0 1 26796 359026206 703974775735
*/
extern crate discrete;
use discrete::*;
use HPoint::*;
fn
|
() {
println!("A discrete homotopy space uses `EqPair` internally:");
let s: EqPair = Construct::new();
let dim = 4;
let n = s.count(&dim);
println!("{}", n);
let mut pos = (0, 0);
for x in 0..n {
s.to_pos(&n, x, &mut pos);
println!("{:?}", pos);
}
println!("================================");
println!("Using `EqPair` recursively gives the complexity of homotopy levels:");
let mut dim = 4;
println!("{}", dim);
for _ in 0..5 {
dim = s.count(&dim);
println!("{}", dim);
}
println!("================================");
println!("Another way to construct a homotopy level 2 is to use `EqPair<Of<EqPair>>`:");
let s: EqPair<Of<EqPair>> = Construct::new();
let dim = 2;
println!("{}", s.count(&dim));
println!("Similarly, at homotopy level 3 one can use `EqPair<Of<EqPair<Of<EqPair>>>>`:");
let s: EqPair<Of<EqPair<Of<EqPair>>>> = Construct::new();
let dim = 2;
println!("{}", s.count(&dim));
println!("However, for the more general case is it easier to use the `Homotopy` space:");
let s: Homotopy = Construct::new();
let level = 2;
let pieces = 2;
let n = s.count(&(level, pieces));
println!("{}", n);
let mut pos = s.zero(&(level, pieces));
for x in 0..n {
s.to_pos(&(level, pieces), x, &mut pos);
println!("{:?}", pos);
}
println!("================================");
println!("The `HPoint` enum represents positions in the `Homotopy` space:");
let a = Path(Box::new((Point(0), Point(0))));
let b = Path(Box::new((Point(1), Point(1))));
let pos = Path(Box::new((a, b)));
let level = pos.level();
println!("{:?} - level {}", pos, level);
println!("{}", s.to_index(&(level, 2), &pos));
println!("================================");
println!("One can also construct a homotopy of another discrete space, e.g. `Homotopy<Of<Pair>>`:");
let s: Homotopy<Of<Pair>> = Construct::new();
let level = 1;
let pieces = 3;
let n = s.count(&(level, pieces));
println!("{}", n);
let mut pos = s.zero(&(level, pieces));
for x in 0..n {
s.to_pos(&(level, pieces), x, &mut pos);
println!("{:?}", pos);
}
}
|
main
|
identifier_name
|
homotopy.rs
|
/*
This example demonstrates the usage of a discrete homotopy space.
In homotopy theory, one constructs a continuous map between functions.
There can be many different kinds of continuous maps, so spaces get very complex.
It even gets worse by having continuous maps between continuous maps.
Since there is a combinatorial explosion of possibilities,
mathematicians developed techniques to classify these spaces.
One of these techniques is called a "homotopy level".
Here is an introduction by Vladimir Voedvodsky: https://www.youtube.com/watch?v=E3steS2Hr1Y
A homotopy level is a way of connecting pieces of a space of a lower homotopy level.
At homotopy level 0, the pieces of the space itself are constructed.
In a space consisting of a single element,
there exists only one way of connecting it to iself,
therefore at homotopy level 1, there is just one element.
This element represents the path from element in homotopy level 0 to itself.
At homotopy level 2, the paths in homotopy level 1 are connected.
Since there is only one path, there is only one path between paths at level 2.
However, when you start with 2 elements at homotopy level 0,
there are 3 ways to connect the 2 elements in homotopy level 1:
0 ~= 0 0 ~= 1 1 ~= 1
Here is an overview of the first 6 homotopy levels up to `n=4`:
level n=0 n=1 n=2 n=3 n=4
0 0 1 2 3 4
|
1 0 1 3 6 10
2 0 1 6 21 55
3 0 1 21 231 1540
4 0 1 231 26796 1186570
5 0 1 26796 359026206 703974775735
*/
extern crate discrete;
use discrete::*;
use HPoint::*;
fn main() {
println!("A discrete homotopy space uses `EqPair` internally:");
let s: EqPair = Construct::new();
let dim = 4;
let n = s.count(&dim);
println!("{}", n);
let mut pos = (0, 0);
for x in 0..n {
s.to_pos(&n, x, &mut pos);
println!("{:?}", pos);
}
println!("================================");
println!("Using `EqPair` recursively gives the complexity of homotopy levels:");
let mut dim = 4;
println!("{}", dim);
for _ in 0..5 {
dim = s.count(&dim);
println!("{}", dim);
}
println!("================================");
println!("Another way to construct a homotopy level 2 is to use `EqPair<Of<EqPair>>`:");
let s: EqPair<Of<EqPair>> = Construct::new();
let dim = 2;
println!("{}", s.count(&dim));
println!("Similarly, at homotopy level 3 one can use `EqPair<Of<EqPair<Of<EqPair>>>>`:");
let s: EqPair<Of<EqPair<Of<EqPair>>>> = Construct::new();
let dim = 2;
println!("{}", s.count(&dim));
println!("However, for the more general case is it easier to use the `Homotopy` space:");
let s: Homotopy = Construct::new();
let level = 2;
let pieces = 2;
let n = s.count(&(level, pieces));
println!("{}", n);
let mut pos = s.zero(&(level, pieces));
for x in 0..n {
s.to_pos(&(level, pieces), x, &mut pos);
println!("{:?}", pos);
}
println!("================================");
println!("The `HPoint` enum represents positions in the `Homotopy` space:");
let a = Path(Box::new((Point(0), Point(0))));
let b = Path(Box::new((Point(1), Point(1))));
let pos = Path(Box::new((a, b)));
let level = pos.level();
println!("{:?} - level {}", pos, level);
println!("{}", s.to_index(&(level, 2), &pos));
println!("================================");
println!("One can also construct a homotopy of another discrete space, e.g. `Homotopy<Of<Pair>>`:");
let s: Homotopy<Of<Pair>> = Construct::new();
let level = 1;
let pieces = 3;
let n = s.count(&(level, pieces));
println!("{}", n);
let mut pos = s.zero(&(level, pieces));
for x in 0..n {
s.to_pos(&(level, pieces), x, &mut pos);
println!("{:?}", pos);
}
}
|
random_line_split
|
|
update.rs
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use diem_documentation_tool as diem_doc;
use serde::Deserialize;
use serde_reflection::{Samples, Tracer, TracerConfig};
#[allow(dead_code)]
#[derive(Deserialize)]
enum
|
{
Unit,
Newtype(MyStruct),
Tuple(u16, Option<bool>),
Struct { a: u32 },
NewTupleArray((u16, u16, u16)),
}
#[derive(Deserialize)]
struct MyStruct(u64);
#[test]
fn test_doctool() {
let mut tracer = Tracer::new(TracerConfig::default());
let samples = Samples::new();
tracer.trace_type::<MyEnum>(&samples).unwrap();
let registry = tracer.registry().unwrap();
let definitions = diem_doc::quote_container_definitions(®istry).unwrap();
let input = r#"
<!-- @begin-diemdoc name=Unknown -->
<!-- @end-diemdoc -->
111111
<!-- @begin-diemdoc name=MyStruct -->
222222
<!-- @end-diemdoc -->
<!-- @begin-diemdoc name=MyEnum -->
<!-- @end-diemdoc -->
33333333
"#
.to_string();
let expected_output = r#"
<!-- @begin-diemdoc name=Unknown -->
<!-- @end-diemdoc -->
111111
<!-- @begin-diemdoc name=MyStruct -->
```rust
struct MyStruct(u64);
```
<!-- @end-diemdoc -->
<!-- @begin-diemdoc name=MyEnum -->
```rust
enum MyEnum {
Unit,
Newtype(MyStruct),
Tuple(u16, Option<bool>),
Struct {
a: u32,
},
NewTupleArray([u16; 3]),
}
```
<!-- @end-diemdoc -->
33333333
"#
.to_string();
let reader = std::io::BufReader::new(input.as_bytes());
assert_eq!(
diem_doc::update_rust_quotes(reader, &definitions).unwrap(),
expected_output
);
}
|
MyEnum
|
identifier_name
|
update.rs
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
|
#[allow(dead_code)]
#[derive(Deserialize)]
enum MyEnum {
Unit,
Newtype(MyStruct),
Tuple(u16, Option<bool>),
Struct { a: u32 },
NewTupleArray((u16, u16, u16)),
}
#[derive(Deserialize)]
struct MyStruct(u64);
#[test]
fn test_doctool() {
let mut tracer = Tracer::new(TracerConfig::default());
let samples = Samples::new();
tracer.trace_type::<MyEnum>(&samples).unwrap();
let registry = tracer.registry().unwrap();
let definitions = diem_doc::quote_container_definitions(®istry).unwrap();
let input = r#"
<!-- @begin-diemdoc name=Unknown -->
<!-- @end-diemdoc -->
111111
<!-- @begin-diemdoc name=MyStruct -->
222222
<!-- @end-diemdoc -->
<!-- @begin-diemdoc name=MyEnum -->
<!-- @end-diemdoc -->
33333333
"#
.to_string();
let expected_output = r#"
<!-- @begin-diemdoc name=Unknown -->
<!-- @end-diemdoc -->
111111
<!-- @begin-diemdoc name=MyStruct -->
```rust
struct MyStruct(u64);
```
<!-- @end-diemdoc -->
<!-- @begin-diemdoc name=MyEnum -->
```rust
enum MyEnum {
Unit,
Newtype(MyStruct),
Tuple(u16, Option<bool>),
Struct {
a: u32,
},
NewTupleArray([u16; 3]),
}
```
<!-- @end-diemdoc -->
33333333
"#
.to_string();
let reader = std::io::BufReader::new(input.as_bytes());
assert_eq!(
diem_doc::update_rust_quotes(reader, &definitions).unwrap(),
expected_output
);
}
|
use diem_documentation_tool as diem_doc;
use serde::Deserialize;
use serde_reflection::{Samples, Tracer, TracerConfig};
|
random_line_split
|
step4.rs
|
println!("14. Issuer (Trust Anchor) is creating a Credential Offer for Prover");
let cred_offer_json = anoncreds::issuer_create_credential_offer(wallet_handle, &cred_def_id).wait().unwrap();
println!("15. Prover creates Credential Request");
let (cred_req_json, cred_req_metadata_json) = anoncreds::prover_create_credential_req(prover_wallet_handle, prover_did, &cred_offer_json, &cred_def_json, &master_secret_name).wait().unwrap();
println!("16. Issuer (Trust Anchor) creates Credential for Credential Request");
let cred_values_json = json!({
"sex": { "raw": "male", "encoded": "5944657099558967239210949258394887428692050081607692519917050011144233115103" },
"name": { "raw": "Alex", "encoded": "99262857098057710338306967609588410025648622308394250666849665532448612202874" },
"height": { "raw": "175", "encoded": "175" },
"age": { "raw": "28", "encoded": "28" },
});
println!("cred_values_json = '{}'", &cred_values_json.to_string());
let (cred_json, _cred_revoc_id, _revoc_reg_delta_json) =
|
println!("Stored Credential ID is {}", &out_cred_id);
// Clean UP
println!("17. Close and delete two wallets");
wallet::close_wallet(prover_wallet_handle).wait().unwrap();
wallet::delete_wallet(&prover_wallet_config, USEFUL_CREDENTIALS).wait().unwrap();
wallet::close_wallet(wallet_handle).wait().unwrap();
wallet::delete_wallet(&config, USEFUL_CREDENTIALS).wait().unwrap();
println!("18. Close pool and delete pool ledger config");
pool::close_pool_ledger(pool_handle).wait().unwrap();
pool::delete_pool_ledger(&pool_name).wait().unwrap();
|
anoncreds::issuer_create_credential(wallet_handle, &cred_offer_json, &cred_req_json, &cred_values_json.to_string(), None, -1).wait().unwrap();
println!("17. Prover processes and stores Credential");
let out_cred_id = anoncreds::prover_store_credential(prover_wallet_handle, None, &cred_req_metadata_json, &cred_json, &cred_def_json, None).wait().unwrap();
|
random_line_split
|
keccak.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/>.
use tiny_keccak::Keccak;
pub trait Keccak256<T> {
fn keccak256(&self) -> T
where
T: Sized;
}
impl Keccak256<[u8; 32]> for [u8] {
fn keccak256(&self) -> [u8; 32]
|
}
|
{
let mut keccak = Keccak::new_keccak256();
let mut result = [0u8; 32];
keccak.update(self);
keccak.finalize(&mut result);
result
}
|
identifier_body
|
keccak.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/>.
|
fn keccak256(&self) -> T
where
T: Sized;
}
impl Keccak256<[u8; 32]> for [u8] {
fn keccak256(&self) -> [u8; 32] {
let mut keccak = Keccak::new_keccak256();
let mut result = [0u8; 32];
keccak.update(self);
keccak.finalize(&mut result);
result
}
}
|
use tiny_keccak::Keccak;
pub trait Keccak256<T> {
|
random_line_split
|
keccak.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/>.
use tiny_keccak::Keccak;
pub trait Keccak256<T> {
fn keccak256(&self) -> T
where
T: Sized;
}
impl Keccak256<[u8; 32]> for [u8] {
fn
|
(&self) -> [u8; 32] {
let mut keccak = Keccak::new_keccak256();
let mut result = [0u8; 32];
keccak.update(self);
keccak.finalize(&mut result);
result
}
}
|
keccak256
|
identifier_name
|
coord.rs
|
// Copyright 2014-2015 The GeoRust 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.
use std::fmt;
use std::str::FromStr;
use tokenizer::{PeekableTokens, Token};
use {FromTokens, WktFloat};
#[derive(Clone, Debug, Default)]
pub struct Coord<T>
where
T: WktFloat,
{
pub x: T,
pub y: T,
pub z: Option<T>,
pub m: Option<T>,
}
impl<T> fmt::Display for Coord<T>
where
T: WktFloat + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{} {}", self.x, self.y)?;
if let Some(z) = self.z {
write!(f, " {}", z)?;
}
if let Some(m) = self.m
|
Ok(())
}
}
impl<T> FromTokens<T> for Coord<T>
where
T: WktFloat + FromStr + Default,
{
fn from_tokens(tokens: &mut PeekableTokens<T>) -> Result<Self, &'static str> {
let x = match tokens.next() {
Some(Token::Number(n)) => n,
_ => return Err("Expected a number for the X coordinate"),
};
let y = match tokens.next() {
Some(Token::Number(n)) => n,
_ => return Err("Expected a number for the Y coordinate"),
};
Ok(Coord {
x: x,
y: y,
z: None,
m: None,
})
}
}
#[cfg(test)]
mod tests {
use super::Coord;
#[test]
fn write_2d_coord() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: None,
m: None,
};
assert_eq!("10.1 20.2", format!("{}", coord));
}
#[test]
fn write_3d_coord() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: Some(-30.3),
m: None,
};
assert_eq!("10.1 20.2 -30.3", format!("{}", coord));
}
#[test]
fn write_2d_coord_with_linear_referencing_system() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: None,
m: Some(10.),
};
assert_eq!("10.1 20.2 10", format!("{}", coord));
}
#[test]
fn write_3d_coord_with_linear_referencing_system() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: Some(-30.3),
m: Some(10.),
};
assert_eq!("10.1 20.2 -30.3 10", format!("{}", coord));
}
}
|
{
write!(f, " {}", m)?;
}
|
conditional_block
|
coord.rs
|
// Copyright 2014-2015 The GeoRust 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.
use std::fmt;
use std::str::FromStr;
use tokenizer::{PeekableTokens, Token};
use {FromTokens, WktFloat};
#[derive(Clone, Debug, Default)]
pub struct Coord<T>
where
T: WktFloat,
{
pub x: T,
pub y: T,
pub z: Option<T>,
pub m: Option<T>,
}
|
impl<T> fmt::Display for Coord<T>
where
T: WktFloat + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{} {}", self.x, self.y)?;
if let Some(z) = self.z {
write!(f, " {}", z)?;
}
if let Some(m) = self.m {
write!(f, " {}", m)?;
}
Ok(())
}
}
impl<T> FromTokens<T> for Coord<T>
where
T: WktFloat + FromStr + Default,
{
fn from_tokens(tokens: &mut PeekableTokens<T>) -> Result<Self, &'static str> {
let x = match tokens.next() {
Some(Token::Number(n)) => n,
_ => return Err("Expected a number for the X coordinate"),
};
let y = match tokens.next() {
Some(Token::Number(n)) => n,
_ => return Err("Expected a number for the Y coordinate"),
};
Ok(Coord {
x: x,
y: y,
z: None,
m: None,
})
}
}
#[cfg(test)]
mod tests {
use super::Coord;
#[test]
fn write_2d_coord() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: None,
m: None,
};
assert_eq!("10.1 20.2", format!("{}", coord));
}
#[test]
fn write_3d_coord() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: Some(-30.3),
m: None,
};
assert_eq!("10.1 20.2 -30.3", format!("{}", coord));
}
#[test]
fn write_2d_coord_with_linear_referencing_system() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: None,
m: Some(10.),
};
assert_eq!("10.1 20.2 10", format!("{}", coord));
}
#[test]
fn write_3d_coord_with_linear_referencing_system() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: Some(-30.3),
m: Some(10.),
};
assert_eq!("10.1 20.2 -30.3 10", format!("{}", coord));
}
}
|
random_line_split
|
|
coord.rs
|
// Copyright 2014-2015 The GeoRust 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.
use std::fmt;
use std::str::FromStr;
use tokenizer::{PeekableTokens, Token};
use {FromTokens, WktFloat};
#[derive(Clone, Debug, Default)]
pub struct Coord<T>
where
T: WktFloat,
{
pub x: T,
pub y: T,
pub z: Option<T>,
pub m: Option<T>,
}
impl<T> fmt::Display for Coord<T>
where
T: WktFloat + fmt::Display,
{
fn
|
(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{} {}", self.x, self.y)?;
if let Some(z) = self.z {
write!(f, " {}", z)?;
}
if let Some(m) = self.m {
write!(f, " {}", m)?;
}
Ok(())
}
}
impl<T> FromTokens<T> for Coord<T>
where
T: WktFloat + FromStr + Default,
{
fn from_tokens(tokens: &mut PeekableTokens<T>) -> Result<Self, &'static str> {
let x = match tokens.next() {
Some(Token::Number(n)) => n,
_ => return Err("Expected a number for the X coordinate"),
};
let y = match tokens.next() {
Some(Token::Number(n)) => n,
_ => return Err("Expected a number for the Y coordinate"),
};
Ok(Coord {
x: x,
y: y,
z: None,
m: None,
})
}
}
#[cfg(test)]
mod tests {
use super::Coord;
#[test]
fn write_2d_coord() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: None,
m: None,
};
assert_eq!("10.1 20.2", format!("{}", coord));
}
#[test]
fn write_3d_coord() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: Some(-30.3),
m: None,
};
assert_eq!("10.1 20.2 -30.3", format!("{}", coord));
}
#[test]
fn write_2d_coord_with_linear_referencing_system() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: None,
m: Some(10.),
};
assert_eq!("10.1 20.2 10", format!("{}", coord));
}
#[test]
fn write_3d_coord_with_linear_referencing_system() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: Some(-30.3),
m: Some(10.),
};
assert_eq!("10.1 20.2 -30.3 10", format!("{}", coord));
}
}
|
fmt
|
identifier_name
|
coord.rs
|
// Copyright 2014-2015 The GeoRust 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.
use std::fmt;
use std::str::FromStr;
use tokenizer::{PeekableTokens, Token};
use {FromTokens, WktFloat};
#[derive(Clone, Debug, Default)]
pub struct Coord<T>
where
T: WktFloat,
{
pub x: T,
pub y: T,
pub z: Option<T>,
pub m: Option<T>,
}
impl<T> fmt::Display for Coord<T>
where
T: WktFloat + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{} {}", self.x, self.y)?;
if let Some(z) = self.z {
write!(f, " {}", z)?;
}
if let Some(m) = self.m {
write!(f, " {}", m)?;
}
Ok(())
}
}
impl<T> FromTokens<T> for Coord<T>
where
T: WktFloat + FromStr + Default,
{
fn from_tokens(tokens: &mut PeekableTokens<T>) -> Result<Self, &'static str> {
let x = match tokens.next() {
Some(Token::Number(n)) => n,
_ => return Err("Expected a number for the X coordinate"),
};
let y = match tokens.next() {
Some(Token::Number(n)) => n,
_ => return Err("Expected a number for the Y coordinate"),
};
Ok(Coord {
x: x,
y: y,
z: None,
m: None,
})
}
}
#[cfg(test)]
mod tests {
use super::Coord;
#[test]
fn write_2d_coord()
|
#[test]
fn write_3d_coord() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: Some(-30.3),
m: None,
};
assert_eq!("10.1 20.2 -30.3", format!("{}", coord));
}
#[test]
fn write_2d_coord_with_linear_referencing_system() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: None,
m: Some(10.),
};
assert_eq!("10.1 20.2 10", format!("{}", coord));
}
#[test]
fn write_3d_coord_with_linear_referencing_system() {
let coord = Coord {
x: 10.1,
y: 20.2,
z: Some(-30.3),
m: Some(10.),
};
assert_eq!("10.1 20.2 -30.3 10", format!("{}", coord));
}
}
|
{
let coord = Coord {
x: 10.1,
y: 20.2,
z: None,
m: None,
};
assert_eq!("10.1 20.2", format!("{}", coord));
}
|
identifier_body
|
rectangle.rs
|
use rand;
use rand::Rng;
use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
}
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle {
top_left: top_left,
bottom_right: Point {
x: top_left.x + width as i16,
y: top_left.y + height as i16,
}
}
}
pub fn centre(&self) -> Point<i16> {
Point {
x: ((self.top_left.x + self.bottom_right.x) / 2),
y: ((self.top_left.y + self.bottom_right.y) / 2),
}
}
pub fn get_random_position(&self, rng: &mut rand::ThreadRng) -> Point<i16> {
Point {
x: rng.gen_range(self.top_left.x+1, self.bottom_right.x),
y: rng.gen_range(self.top_left.y+1, self.bottom_right.y),
}
}
pub fn is_intersecting(&self, other: &Rectangle) -> bool
|
pub fn clamp_to(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) {
if self.top_left.x < left {
let diff = left - self.top_left.x;
self.top_left.x += diff;
self.bottom_right.x += diff;
}
if self.top_left.y < top {
let diff = top - self.top_left.y;
self.top_left.y += diff;
self.bottom_right.y += diff;
}
if self.bottom_right.x > right {
let diff = right - self.bottom_right.x;
self.top_left.x += diff;
self.bottom_right.x += diff;
}
if self.bottom_right.y > bottom {
let diff = bottom - self.bottom_right.y;
self.top_left.y += diff;
self.bottom_right.y += diff;
}
}
}
|
{
self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x
&& self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y
}
|
identifier_body
|
rectangle.rs
|
use rand::Rng;
use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
}
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle {
top_left: top_left,
bottom_right: Point {
x: top_left.x + width as i16,
y: top_left.y + height as i16,
}
}
}
pub fn centre(&self) -> Point<i16> {
Point {
x: ((self.top_left.x + self.bottom_right.x) / 2),
y: ((self.top_left.y + self.bottom_right.y) / 2),
}
}
pub fn get_random_position(&self, rng: &mut rand::ThreadRng) -> Point<i16> {
Point {
x: rng.gen_range(self.top_left.x+1, self.bottom_right.x),
y: rng.gen_range(self.top_left.y+1, self.bottom_right.y),
}
}
pub fn is_intersecting(&self, other: &Rectangle) -> bool {
self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x
&& self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y
}
pub fn clamp_to(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) {
if self.top_left.x < left {
let diff = left - self.top_left.x;
self.top_left.x += diff;
self.bottom_right.x += diff;
}
if self.top_left.y < top {
let diff = top - self.top_left.y;
self.top_left.y += diff;
self.bottom_right.y += diff;
}
if self.bottom_right.x > right {
let diff = right - self.bottom_right.x;
self.top_left.x += diff;
self.bottom_right.x += diff;
}
if self.bottom_right.y > bottom {
let diff = bottom - self.bottom_right.y;
self.top_left.y += diff;
self.bottom_right.y += diff;
}
}
}
|
use rand;
|
random_line_split
|
|
rectangle.rs
|
use rand;
use rand::Rng;
use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
}
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle {
top_left: top_left,
bottom_right: Point {
x: top_left.x + width as i16,
y: top_left.y + height as i16,
}
}
}
pub fn centre(&self) -> Point<i16> {
Point {
x: ((self.top_left.x + self.bottom_right.x) / 2),
y: ((self.top_left.y + self.bottom_right.y) / 2),
}
}
pub fn get_random_position(&self, rng: &mut rand::ThreadRng) -> Point<i16> {
Point {
x: rng.gen_range(self.top_left.x+1, self.bottom_right.x),
y: rng.gen_range(self.top_left.y+1, self.bottom_right.y),
}
}
pub fn is_intersecting(&self, other: &Rectangle) -> bool {
self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x
&& self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y
}
pub fn clamp_to(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) {
if self.top_left.x < left
|
if self.top_left.y < top {
let diff = top - self.top_left.y;
self.top_left.y += diff;
self.bottom_right.y += diff;
}
if self.bottom_right.x > right {
let diff = right - self.bottom_right.x;
self.top_left.x += diff;
self.bottom_right.x += diff;
}
if self.bottom_right.y > bottom {
let diff = bottom - self.bottom_right.y;
self.top_left.y += diff;
self.bottom_right.y += diff;
}
}
}
|
{
let diff = left - self.top_left.x;
self.top_left.x += diff;
self.bottom_right.x += diff;
}
|
conditional_block
|
rectangle.rs
|
use rand;
use rand::Rng;
use point::Point;
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct Rectangle {
pub top_left: Point<i16>,
pub bottom_right: Point<i16>,
}
impl Rectangle {
pub fn new(top_left: Point<i16>, (width, height): (u8, u8)) -> Rectangle {
Rectangle {
top_left: top_left,
bottom_right: Point {
x: top_left.x + width as i16,
y: top_left.y + height as i16,
}
}
}
pub fn centre(&self) -> Point<i16> {
Point {
x: ((self.top_left.x + self.bottom_right.x) / 2),
y: ((self.top_left.y + self.bottom_right.y) / 2),
}
}
pub fn get_random_position(&self, rng: &mut rand::ThreadRng) -> Point<i16> {
Point {
x: rng.gen_range(self.top_left.x+1, self.bottom_right.x),
y: rng.gen_range(self.top_left.y+1, self.bottom_right.y),
}
}
pub fn is_intersecting(&self, other: &Rectangle) -> bool {
self.top_left.x <= other.bottom_right.x && self.bottom_right.x >= other.top_left.x
&& self.top_left.y <= other.bottom_right.y && self.bottom_right.y >= other.top_left.y
}
pub fn
|
(&mut self, (left, top): (i16, i16), (right, bottom): (i16, i16)) {
if self.top_left.x < left {
let diff = left - self.top_left.x;
self.top_left.x += diff;
self.bottom_right.x += diff;
}
if self.top_left.y < top {
let diff = top - self.top_left.y;
self.top_left.y += diff;
self.bottom_right.y += diff;
}
if self.bottom_right.x > right {
let diff = right - self.bottom_right.x;
self.top_left.x += diff;
self.bottom_right.x += diff;
}
if self.bottom_right.y > bottom {
let diff = bottom - self.bottom_right.y;
self.top_left.y += diff;
self.bottom_right.y += diff;
}
}
}
|
clamp_to
|
identifier_name
|
templates.rs
|
/// Wrapper around the ``liquid`` crate to handle templating.
use liquid::ParserBuilder;
use std::{
fs::{create_dir_all, File},
io::Write,
path::{Path, PathBuf},
};
use crate::error::{Result, ResultExt};
pub use liquid::value::{Object as Parameters, Value};
mod external {
include!(concat!(env!("OUT_DIR"), "/_template_files.rs"));
}
const LIQUID_TEMPLATE_EXTENSION: &str = ".gdpu";
pub fn deploy(
template: &str,
version: &Option<String>,
no_defaults: bool,
output: &Path,
params: &Parameters,
) -> Result<()>
|
#[cfg(target_os = "macos")]
{
params.insert("graphics_backend".into(), Value::scalar("metal"));
}
#[cfg(not(target_os = "macos"))]
{
params.insert("graphics_backend".into(), Value::scalar("vulkan"));
}
}
let params = ¶ms;
let template_files = template_map
.get::<str>(&version)
.ok_or_else(|| format!("No template for version {}", version))?;
for &(path, content) in template_files.iter() {
let mut path = path.to_owned();
let is_parsed = path.ends_with(LIQUID_TEMPLATE_EXTENSION);
if is_parsed {
let len = path.len();
path.truncate(len - LIQUID_TEMPLATE_EXTENSION.len());
}
let mut out = if is_parsed {
parser
.parse(content)
.chain_err(|| format!("Could not parse liquid template at {:?}", path))?
.render(params)
.chain_err(|| {
format!(
"Could not render liquid template at {:?} with parameters {:?}",
path, params
)
})?
} else {
content.to_owned()
};
#[cfg(target_os = "windows")]
{
use regex::Regex;
out = Regex::new("(?P<last>[^\r])\n")
.unwrap()
.replace_all(&out, "$last\r\n")
.to_string();
}
#[cfg(not(target_os = "windows"))]
{
out = out.replace("\r\n", "\n");
}
let path: PathBuf = output
.join(path)
.iter()
.enumerate()
.filter_map(|(_, e)| if e == template { None } else { Some(e) })
.collect();
create_dir_all(path.parent().expect("Path has no parent"))?;
File::create(&path)
.chain_err(|| format!("failed to create file {:?}", &path))?
.write_all(out.as_bytes())
.chain_err(|| format!("could not write contents to file {:?}", &path))?;
}
Ok(())
}
|
{
let parser = ParserBuilder::with_liquid().build().unwrap();
let template_map = external::template_files();
let template_versions = template_map
.keys()
.map(|v| semver::Version::parse(v).unwrap());
let version: String = match version {
Some(ref ver) => semver::Version::parse(ver)
.chain_err(|| format!("Could not parse version {}", ver))?
.to_string(),
None => template_versions
.max()
.ok_or("No template available")?
.to_string(),
};
let mut params = params.clone();
params.insert("amethyst_version".into(), Value::scalar(version.clone()));
if !no_defaults {
|
identifier_body
|
templates.rs
|
/// Wrapper around the ``liquid`` crate to handle templating.
use liquid::ParserBuilder;
use std::{
fs::{create_dir_all, File},
io::Write,
path::{Path, PathBuf},
};
use crate::error::{Result, ResultExt};
pub use liquid::value::{Object as Parameters, Value};
mod external {
include!(concat!(env!("OUT_DIR"), "/_template_files.rs"));
}
const LIQUID_TEMPLATE_EXTENSION: &str = ".gdpu";
pub fn deploy(
template: &str,
version: &Option<String>,
no_defaults: bool,
output: &Path,
params: &Parameters,
) -> Result<()> {
let parser = ParserBuilder::with_liquid().build().unwrap();
let template_map = external::template_files();
let template_versions = template_map
.keys()
.map(|v| semver::Version::parse(v).unwrap());
let version: String = match version {
Some(ref ver) => semver::Version::parse(ver)
.chain_err(|| format!("Could not parse version {}", ver))?
.to_string(),
None => template_versions
.max()
.ok_or("No template available")?
.to_string(),
};
let mut params = params.clone();
params.insert("amethyst_version".into(), Value::scalar(version.clone()));
if!no_defaults {
#[cfg(target_os = "macos")]
{
params.insert("graphics_backend".into(), Value::scalar("metal"));
}
#[cfg(not(target_os = "macos"))]
{
params.insert("graphics_backend".into(), Value::scalar("vulkan"));
}
}
let params = ¶ms;
let template_files = template_map
.get::<str>(&version)
.ok_or_else(|| format!("No template for version {}", version))?;
for &(path, content) in template_files.iter() {
let mut path = path.to_owned();
let is_parsed = path.ends_with(LIQUID_TEMPLATE_EXTENSION);
if is_parsed {
let len = path.len();
path.truncate(len - LIQUID_TEMPLATE_EXTENSION.len());
}
let mut out = if is_parsed {
parser
.parse(content)
.chain_err(|| format!("Could not parse liquid template at {:?}", path))?
.render(params)
.chain_err(|| {
format!(
"Could not render liquid template at {:?} with parameters {:?}",
path, params
)
})?
} else
|
;
#[cfg(target_os = "windows")]
{
use regex::Regex;
out = Regex::new("(?P<last>[^\r])\n")
.unwrap()
.replace_all(&out, "$last\r\n")
.to_string();
}
#[cfg(not(target_os = "windows"))]
{
out = out.replace("\r\n", "\n");
}
let path: PathBuf = output
.join(path)
.iter()
.enumerate()
.filter_map(|(_, e)| if e == template { None } else { Some(e) })
.collect();
create_dir_all(path.parent().expect("Path has no parent"))?;
File::create(&path)
.chain_err(|| format!("failed to create file {:?}", &path))?
.write_all(out.as_bytes())
.chain_err(|| format!("could not write contents to file {:?}", &path))?;
}
Ok(())
}
|
{
content.to_owned()
}
|
conditional_block
|
templates.rs
|
/// Wrapper around the ``liquid`` crate to handle templating.
use liquid::ParserBuilder;
use std::{
fs::{create_dir_all, File},
io::Write,
path::{Path, PathBuf},
};
use crate::error::{Result, ResultExt};
pub use liquid::value::{Object as Parameters, Value};
mod external {
include!(concat!(env!("OUT_DIR"), "/_template_files.rs"));
}
const LIQUID_TEMPLATE_EXTENSION: &str = ".gdpu";
pub fn
|
(
template: &str,
version: &Option<String>,
no_defaults: bool,
output: &Path,
params: &Parameters,
) -> Result<()> {
let parser = ParserBuilder::with_liquid().build().unwrap();
let template_map = external::template_files();
let template_versions = template_map
.keys()
.map(|v| semver::Version::parse(v).unwrap());
let version: String = match version {
Some(ref ver) => semver::Version::parse(ver)
.chain_err(|| format!("Could not parse version {}", ver))?
.to_string(),
None => template_versions
.max()
.ok_or("No template available")?
.to_string(),
};
let mut params = params.clone();
params.insert("amethyst_version".into(), Value::scalar(version.clone()));
if!no_defaults {
#[cfg(target_os = "macos")]
{
params.insert("graphics_backend".into(), Value::scalar("metal"));
}
#[cfg(not(target_os = "macos"))]
{
params.insert("graphics_backend".into(), Value::scalar("vulkan"));
}
}
let params = ¶ms;
let template_files = template_map
.get::<str>(&version)
.ok_or_else(|| format!("No template for version {}", version))?;
for &(path, content) in template_files.iter() {
let mut path = path.to_owned();
let is_parsed = path.ends_with(LIQUID_TEMPLATE_EXTENSION);
if is_parsed {
let len = path.len();
path.truncate(len - LIQUID_TEMPLATE_EXTENSION.len());
}
let mut out = if is_parsed {
parser
.parse(content)
.chain_err(|| format!("Could not parse liquid template at {:?}", path))?
.render(params)
.chain_err(|| {
format!(
"Could not render liquid template at {:?} with parameters {:?}",
path, params
)
})?
} else {
content.to_owned()
};
#[cfg(target_os = "windows")]
{
use regex::Regex;
out = Regex::new("(?P<last>[^\r])\n")
.unwrap()
.replace_all(&out, "$last\r\n")
.to_string();
}
#[cfg(not(target_os = "windows"))]
{
out = out.replace("\r\n", "\n");
}
let path: PathBuf = output
.join(path)
.iter()
.enumerate()
.filter_map(|(_, e)| if e == template { None } else { Some(e) })
.collect();
create_dir_all(path.parent().expect("Path has no parent"))?;
File::create(&path)
.chain_err(|| format!("failed to create file {:?}", &path))?
.write_all(out.as_bytes())
.chain_err(|| format!("could not write contents to file {:?}", &path))?;
}
Ok(())
}
|
deploy
|
identifier_name
|
templates.rs
|
/// Wrapper around the ``liquid`` crate to handle templating.
use liquid::ParserBuilder;
use std::{
fs::{create_dir_all, File},
io::Write,
path::{Path, PathBuf},
};
use crate::error::{Result, ResultExt};
pub use liquid::value::{Object as Parameters, Value};
mod external {
include!(concat!(env!("OUT_DIR"), "/_template_files.rs"));
}
const LIQUID_TEMPLATE_EXTENSION: &str = ".gdpu";
pub fn deploy(
template: &str,
version: &Option<String>,
no_defaults: bool,
output: &Path,
params: &Parameters,
) -> Result<()> {
let parser = ParserBuilder::with_liquid().build().unwrap();
let template_map = external::template_files();
let template_versions = template_map
.keys()
.map(|v| semver::Version::parse(v).unwrap());
let version: String = match version {
Some(ref ver) => semver::Version::parse(ver)
.chain_err(|| format!("Could not parse version {}", ver))?
.to_string(),
None => template_versions
.max()
.ok_or("No template available")?
.to_string(),
};
let mut params = params.clone();
params.insert("amethyst_version".into(), Value::scalar(version.clone()));
if!no_defaults {
#[cfg(target_os = "macos")]
{
params.insert("graphics_backend".into(), Value::scalar("metal"));
}
#[cfg(not(target_os = "macos"))]
{
params.insert("graphics_backend".into(), Value::scalar("vulkan"));
}
}
let params = ¶ms;
let template_files = template_map
.get::<str>(&version)
|
.ok_or_else(|| format!("No template for version {}", version))?;
for &(path, content) in template_files.iter() {
let mut path = path.to_owned();
let is_parsed = path.ends_with(LIQUID_TEMPLATE_EXTENSION);
if is_parsed {
let len = path.len();
path.truncate(len - LIQUID_TEMPLATE_EXTENSION.len());
}
let mut out = if is_parsed {
parser
.parse(content)
.chain_err(|| format!("Could not parse liquid template at {:?}", path))?
.render(params)
.chain_err(|| {
format!(
"Could not render liquid template at {:?} with parameters {:?}",
path, params
)
})?
} else {
content.to_owned()
};
#[cfg(target_os = "windows")]
{
use regex::Regex;
out = Regex::new("(?P<last>[^\r])\n")
.unwrap()
.replace_all(&out, "$last\r\n")
.to_string();
}
#[cfg(not(target_os = "windows"))]
{
out = out.replace("\r\n", "\n");
}
let path: PathBuf = output
.join(path)
.iter()
.enumerate()
.filter_map(|(_, e)| if e == template { None } else { Some(e) })
.collect();
create_dir_all(path.parent().expect("Path has no parent"))?;
File::create(&path)
.chain_err(|| format!("failed to create file {:?}", &path))?
.write_all(out.as_bytes())
.chain_err(|| format!("could not write contents to file {:?}", &path))?;
}
Ok(())
}
|
random_line_split
|
|
channel.rs
|
use std::collections::HashSet;
use ircnvim::user::User;
const CHANNEL_STARTING_CHARACTERS: &'static str = "#&+!~";
pub trait IsChannelName {
fn is_channel_name(&self) -> bool;
}
impl<'a> IsChannelName for &'a str {
fn is_channel_name(&self) -> bool {
return self.chars().nth(0).and_then(|c| CHANNEL_STARTING_CHARACTERS.find(c)).is_some();
}
}
impl IsChannelName for String {
fn is_channel_name(&self) -> bool {
return (&self[..]).is_channel_name();
}
}
pub struct Channel {
pub name: String,
pub topic: Option<String>,
users: HashSet<User>
}
impl Channel {
pub fn new(name: &str) -> Channel {
return Channel {
name: name.to_string(),
topic: None,
users: HashSet::new()
};
}
pub fn add_user(&mut self, user: User) {
self.users.insert(user);
}
pub fn remove_user(&mut self, user: &User) {
self.users.remove(user);
}
pub fn rename(&mut self, user: &User, new_nick: &str) {
self.users.remove(user);
self.users.insert(User::from_nick(new_nick.to_string()));
}
pub fn is_user_present(&self, user: &User) -> bool {
return self.users.contains(user);
}
pub fn set_topic(&mut self, topic: String) {
self.topic = Some(topic);
}
pub fn num_users(&self) -> usize {
return self.users.len();
|
mod tests {
use super::*;
#[test]
fn test_is_channel_name() {
assert!("##c".to_string().is_channel_name());
assert!("&mychan".is_channel_name());
assert!("~otherchan".is_channel_name());
}
}
|
}
}
#[cfg(test)]
|
random_line_split
|
channel.rs
|
use std::collections::HashSet;
use ircnvim::user::User;
const CHANNEL_STARTING_CHARACTERS: &'static str = "#&+!~";
pub trait IsChannelName {
fn is_channel_name(&self) -> bool;
}
impl<'a> IsChannelName for &'a str {
fn is_channel_name(&self) -> bool {
return self.chars().nth(0).and_then(|c| CHANNEL_STARTING_CHARACTERS.find(c)).is_some();
}
}
impl IsChannelName for String {
fn is_channel_name(&self) -> bool
|
}
pub struct Channel {
pub name: String,
pub topic: Option<String>,
users: HashSet<User>
}
impl Channel {
pub fn new(name: &str) -> Channel {
return Channel {
name: name.to_string(),
topic: None,
users: HashSet::new()
};
}
pub fn add_user(&mut self, user: User) {
self.users.insert(user);
}
pub fn remove_user(&mut self, user: &User) {
self.users.remove(user);
}
pub fn rename(&mut self, user: &User, new_nick: &str) {
self.users.remove(user);
self.users.insert(User::from_nick(new_nick.to_string()));
}
pub fn is_user_present(&self, user: &User) -> bool {
return self.users.contains(user);
}
pub fn set_topic(&mut self, topic: String) {
self.topic = Some(topic);
}
pub fn num_users(&self) -> usize {
return self.users.len();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_channel_name() {
assert!("##c".to_string().is_channel_name());
assert!("&mychan".is_channel_name());
assert!("~otherchan".is_channel_name());
}
}
|
{
return (&self[..]).is_channel_name();
}
|
identifier_body
|
channel.rs
|
use std::collections::HashSet;
use ircnvim::user::User;
const CHANNEL_STARTING_CHARACTERS: &'static str = "#&+!~";
pub trait IsChannelName {
fn is_channel_name(&self) -> bool;
}
impl<'a> IsChannelName for &'a str {
fn is_channel_name(&self) -> bool {
return self.chars().nth(0).and_then(|c| CHANNEL_STARTING_CHARACTERS.find(c)).is_some();
}
}
impl IsChannelName for String {
fn is_channel_name(&self) -> bool {
return (&self[..]).is_channel_name();
}
}
pub struct Channel {
pub name: String,
pub topic: Option<String>,
users: HashSet<User>
}
impl Channel {
pub fn new(name: &str) -> Channel {
return Channel {
name: name.to_string(),
topic: None,
users: HashSet::new()
};
}
pub fn add_user(&mut self, user: User) {
self.users.insert(user);
}
pub fn remove_user(&mut self, user: &User) {
self.users.remove(user);
}
pub fn
|
(&mut self, user: &User, new_nick: &str) {
self.users.remove(user);
self.users.insert(User::from_nick(new_nick.to_string()));
}
pub fn is_user_present(&self, user: &User) -> bool {
return self.users.contains(user);
}
pub fn set_topic(&mut self, topic: String) {
self.topic = Some(topic);
}
pub fn num_users(&self) -> usize {
return self.users.len();
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_is_channel_name() {
assert!("##c".to_string().is_channel_name());
assert!("&mychan".is_channel_name());
assert!("~otherchan".is_channel_name());
}
}
|
rename
|
identifier_name
|
render.rs
|
// pub use primitive::{Sphere};
// pub type Ray = ray::Ray3<float>;
// pub type Point = Point<float>;
use super::Float;
use nalgebra as na;
use rayon::prelude::*;
use std::cmp;
use truescad_luascad::implicit3d::Object;
const EPSILON: Float = 0.003;
const APPROX_SLACK: Float = 0.1;
const FOCAL_FACTOR: Float = 36. /* 36 mm film */ / 50.;
#[derive(Copy, Clone, Debug)]
pub struct Ray {
pub origin: na::Point3<Float>,
pub dir: na::Vector3<Float>,
}
impl Ray {
pub fn new(o: na::Point3<Float>, d: na::Vector3<Float>) -> Ray {
Ray { origin: o, dir: d }
}
}
#[derive(Clone)]
pub struct Renderer {
light_dir: na::Vector3<Float>,
trans: na::Matrix4<Float>,
object: Option<Box<dyn Object<Float>>>,
epsilon: Float,
maxval: Float,
approx_slack: Float,
}
impl Renderer {
pub fn new() -> Renderer {
Renderer {
light_dir: na::Vector3::new(-2. / 3., 2. / 3., -1. / 3.),
trans: na::Matrix4::identity(),
object: None,
epsilon: EPSILON,
maxval: 0.,
approx_slack: APPROX_SLACK,
}
}
pub fn set_object(&mut self, object: Option<Box<dyn Object<Float>>>) {
self.object = object;
self.epsilon = self.object_width() * EPSILON;
self.maxval = self.object_width();
self.approx_slack = self.object_width() * APPROX_SLACK;
}
pub fn rotate_from_screen(&mut self, x: Float, y: Float) {
let euler = ::na::Rotation::from_euler_angles(y, x, 0.).to_homogeneous();
self.trans *= euler;
}
pub fn
|
(&mut self, x: Float, y: Float) {
let v = na::Vector3::new(-x as Float, y as Float, 0.);
self.trans = self.trans.append_translation(&v);
}
fn cast_ray(
&self,
obj: &dyn Object<Float>,
r: &Ray,
light_dir: &na::Vector3<Float>,
origin_value: Float,
) -> (usize, Float) {
let mut cr = *r;
let mut value = origin_value;
let mut iter: usize = 0;
loop {
cr.dir = cr.dir.normalize();
cr.origin += cr.dir * value;
value = obj.approx_value(&cr.origin, self.approx_slack);
iter += 1;
if value > self.maxval {
return (iter, 0.);
}
if value < self.epsilon {
break;
}
}
let norm = obj.normal(&cr.origin);
let dot = norm.dot(light_dir);
if dot < 0. {
return (iter, 0.);
}
(iter, dot)
}
pub fn draw_on_buf(&self, buf: &mut [u8], width: i32, height: i32) {
if let Some(my_obj) = &self.object {
let object_width = self.object_width();
let viewer_dist = FOCAL_FACTOR * object_width * 3.;
let scale = 1. / Float::from(cmp::min(width, height));
let w2 = width / 2;
let h2 = height / 2;
let dir_front = self.trans.transform_vector(&na::Vector3::new(0., 0., 1.));
let dir_rl = self
.trans
.transform_vector(&na::Vector3::new(FOCAL_FACTOR, 0., 0.));
let dir_tb = self
.trans
.transform_vector(&na::Vector3::new(0., -FOCAL_FACTOR, 0.));
let light_dir = self.trans.transform_vector(&self.light_dir);
let ray_origin = self
.trans
.transform_point(&na::Point3::new(0., 0., -viewer_dist));
let ray = Ray::new(ray_origin, dir_front);
let origin_value = my_obj.approx_value(&ray.origin, self.approx_slack);
let mut rows: Vec<_> = buf.chunks_mut((width * 4) as usize).enumerate().collect();
rows.par_iter_mut().for_each(|y_and_buf| {
let y = y_and_buf.0 as i32;
let row_buf = &mut y_and_buf.1;
let dir_row = dir_front + dir_tb * (Float::from(y - h2) * scale);
let mut row_ray = ray;
let mut index: usize = 0;
for x in 0..width {
row_ray.dir = dir_row + dir_rl * (Float::from(x - w2) * scale);
let (i, v) = self.cast_ray(&**my_obj, &row_ray, &light_dir, origin_value);
let b = (255.0 * v * v) as u8;
row_buf[index] = i as u8;
index += 1;
row_buf[index] = b;
index += 1;
row_buf[index] = b;
index += 1;
index += 1;
}
})
}
}
fn object_width(&self) -> Float {
if let Some(ref my_obj) = self.object {
return my_obj
.bbox()
.max
.x
.abs()
.max(my_obj.bbox().min.x.abs())
.max(my_obj.bbox().max.y.abs().max(my_obj.bbox().min.y.abs()))
.max(my_obj.bbox().max.z.abs().max(my_obj.bbox().min.z.abs()))
* 2.;
}
0.
}
}
impl Default for Renderer {
fn default() -> Self {
Self::new()
}
}
|
translate_from_screen
|
identifier_name
|
render.rs
|
// pub use primitive::{Sphere};
// pub type Ray = ray::Ray3<float>;
// pub type Point = Point<float>;
use super::Float;
use nalgebra as na;
use rayon::prelude::*;
use std::cmp;
use truescad_luascad::implicit3d::Object;
const EPSILON: Float = 0.003;
const APPROX_SLACK: Float = 0.1;
const FOCAL_FACTOR: Float = 36. /* 36 mm film */ / 50.;
#[derive(Copy, Clone, Debug)]
pub struct Ray {
pub origin: na::Point3<Float>,
pub dir: na::Vector3<Float>,
}
impl Ray {
pub fn new(o: na::Point3<Float>, d: na::Vector3<Float>) -> Ray {
Ray { origin: o, dir: d }
}
}
#[derive(Clone)]
pub struct Renderer {
light_dir: na::Vector3<Float>,
trans: na::Matrix4<Float>,
object: Option<Box<dyn Object<Float>>>,
epsilon: Float,
maxval: Float,
approx_slack: Float,
}
impl Renderer {
pub fn new() -> Renderer {
Renderer {
light_dir: na::Vector3::new(-2. / 3., 2. / 3., -1. / 3.),
trans: na::Matrix4::identity(),
object: None,
epsilon: EPSILON,
maxval: 0.,
approx_slack: APPROX_SLACK,
}
}
pub fn set_object(&mut self, object: Option<Box<dyn Object<Float>>>) {
self.object = object;
self.epsilon = self.object_width() * EPSILON;
self.maxval = self.object_width();
self.approx_slack = self.object_width() * APPROX_SLACK;
}
pub fn rotate_from_screen(&mut self, x: Float, y: Float) {
let euler = ::na::Rotation::from_euler_angles(y, x, 0.).to_homogeneous();
self.trans *= euler;
}
pub fn translate_from_screen(&mut self, x: Float, y: Float) {
let v = na::Vector3::new(-x as Float, y as Float, 0.);
self.trans = self.trans.append_translation(&v);
}
fn cast_ray(
&self,
obj: &dyn Object<Float>,
r: &Ray,
light_dir: &na::Vector3<Float>,
origin_value: Float,
) -> (usize, Float) {
let mut cr = *r;
let mut value = origin_value;
let mut iter: usize = 0;
loop {
cr.dir = cr.dir.normalize();
cr.origin += cr.dir * value;
value = obj.approx_value(&cr.origin, self.approx_slack);
iter += 1;
if value > self.maxval
|
if value < self.epsilon {
break;
}
}
let norm = obj.normal(&cr.origin);
let dot = norm.dot(light_dir);
if dot < 0. {
return (iter, 0.);
}
(iter, dot)
}
pub fn draw_on_buf(&self, buf: &mut [u8], width: i32, height: i32) {
if let Some(my_obj) = &self.object {
let object_width = self.object_width();
let viewer_dist = FOCAL_FACTOR * object_width * 3.;
let scale = 1. / Float::from(cmp::min(width, height));
let w2 = width / 2;
let h2 = height / 2;
let dir_front = self.trans.transform_vector(&na::Vector3::new(0., 0., 1.));
let dir_rl = self
.trans
.transform_vector(&na::Vector3::new(FOCAL_FACTOR, 0., 0.));
let dir_tb = self
.trans
.transform_vector(&na::Vector3::new(0., -FOCAL_FACTOR, 0.));
let light_dir = self.trans.transform_vector(&self.light_dir);
let ray_origin = self
.trans
.transform_point(&na::Point3::new(0., 0., -viewer_dist));
let ray = Ray::new(ray_origin, dir_front);
let origin_value = my_obj.approx_value(&ray.origin, self.approx_slack);
let mut rows: Vec<_> = buf.chunks_mut((width * 4) as usize).enumerate().collect();
rows.par_iter_mut().for_each(|y_and_buf| {
let y = y_and_buf.0 as i32;
let row_buf = &mut y_and_buf.1;
let dir_row = dir_front + dir_tb * (Float::from(y - h2) * scale);
let mut row_ray = ray;
let mut index: usize = 0;
for x in 0..width {
row_ray.dir = dir_row + dir_rl * (Float::from(x - w2) * scale);
let (i, v) = self.cast_ray(&**my_obj, &row_ray, &light_dir, origin_value);
let b = (255.0 * v * v) as u8;
row_buf[index] = i as u8;
index += 1;
row_buf[index] = b;
index += 1;
row_buf[index] = b;
index += 1;
index += 1;
}
})
}
}
fn object_width(&self) -> Float {
if let Some(ref my_obj) = self.object {
return my_obj
.bbox()
.max
.x
.abs()
.max(my_obj.bbox().min.x.abs())
.max(my_obj.bbox().max.y.abs().max(my_obj.bbox().min.y.abs()))
.max(my_obj.bbox().max.z.abs().max(my_obj.bbox().min.z.abs()))
* 2.;
}
0.
}
}
impl Default for Renderer {
fn default() -> Self {
Self::new()
}
}
|
{
return (iter, 0.);
}
|
conditional_block
|
render.rs
|
// pub use primitive::{Sphere};
// pub type Ray = ray::Ray3<float>;
// pub type Point = Point<float>;
use super::Float;
use nalgebra as na;
use rayon::prelude::*;
use std::cmp;
use truescad_luascad::implicit3d::Object;
const EPSILON: Float = 0.003;
const APPROX_SLACK: Float = 0.1;
const FOCAL_FACTOR: Float = 36. /* 36 mm film */ / 50.;
#[derive(Copy, Clone, Debug)]
pub struct Ray {
pub origin: na::Point3<Float>,
pub dir: na::Vector3<Float>,
}
impl Ray {
pub fn new(o: na::Point3<Float>, d: na::Vector3<Float>) -> Ray {
Ray { origin: o, dir: d }
}
}
#[derive(Clone)]
pub struct Renderer {
light_dir: na::Vector3<Float>,
trans: na::Matrix4<Float>,
object: Option<Box<dyn Object<Float>>>,
epsilon: Float,
maxval: Float,
approx_slack: Float,
}
impl Renderer {
pub fn new() -> Renderer {
Renderer {
light_dir: na::Vector3::new(-2. / 3., 2. / 3., -1. / 3.),
trans: na::Matrix4::identity(),
object: None,
epsilon: EPSILON,
maxval: 0.,
approx_slack: APPROX_SLACK,
}
}
pub fn set_object(&mut self, object: Option<Box<dyn Object<Float>>>) {
self.object = object;
self.epsilon = self.object_width() * EPSILON;
self.maxval = self.object_width();
self.approx_slack = self.object_width() * APPROX_SLACK;
}
pub fn rotate_from_screen(&mut self, x: Float, y: Float) {
let euler = ::na::Rotation::from_euler_angles(y, x, 0.).to_homogeneous();
self.trans *= euler;
}
pub fn translate_from_screen(&mut self, x: Float, y: Float) {
let v = na::Vector3::new(-x as Float, y as Float, 0.);
self.trans = self.trans.append_translation(&v);
}
fn cast_ray(
&self,
obj: &dyn Object<Float>,
r: &Ray,
light_dir: &na::Vector3<Float>,
origin_value: Float,
) -> (usize, Float) {
let mut cr = *r;
let mut value = origin_value;
let mut iter: usize = 0;
loop {
cr.dir = cr.dir.normalize();
cr.origin += cr.dir * value;
value = obj.approx_value(&cr.origin, self.approx_slack);
iter += 1;
if value > self.maxval {
return (iter, 0.);
}
if value < self.epsilon {
break;
}
}
let norm = obj.normal(&cr.origin);
let dot = norm.dot(light_dir);
if dot < 0. {
return (iter, 0.);
}
(iter, dot)
}
pub fn draw_on_buf(&self, buf: &mut [u8], width: i32, height: i32) {
if let Some(my_obj) = &self.object {
let object_width = self.object_width();
let viewer_dist = FOCAL_FACTOR * object_width * 3.;
let scale = 1. / Float::from(cmp::min(width, height));
let w2 = width / 2;
let h2 = height / 2;
let dir_front = self.trans.transform_vector(&na::Vector3::new(0., 0., 1.));
let dir_rl = self
.trans
.transform_vector(&na::Vector3::new(FOCAL_FACTOR, 0., 0.));
let dir_tb = self
.trans
.transform_vector(&na::Vector3::new(0., -FOCAL_FACTOR, 0.));
let light_dir = self.trans.transform_vector(&self.light_dir);
let ray_origin = self
.trans
.transform_point(&na::Point3::new(0., 0., -viewer_dist));
let ray = Ray::new(ray_origin, dir_front);
let origin_value = my_obj.approx_value(&ray.origin, self.approx_slack);
let mut rows: Vec<_> = buf.chunks_mut((width * 4) as usize).enumerate().collect();
rows.par_iter_mut().for_each(|y_and_buf| {
let y = y_and_buf.0 as i32;
let row_buf = &mut y_and_buf.1;
let dir_row = dir_front + dir_tb * (Float::from(y - h2) * scale);
let mut row_ray = ray;
let mut index: usize = 0;
for x in 0..width {
row_ray.dir = dir_row + dir_rl * (Float::from(x - w2) * scale);
let (i, v) = self.cast_ray(&**my_obj, &row_ray, &light_dir, origin_value);
let b = (255.0 * v * v) as u8;
row_buf[index] = i as u8;
index += 1;
row_buf[index] = b;
index += 1;
row_buf[index] = b;
index += 1;
index += 1;
}
})
}
}
fn object_width(&self) -> Float {
if let Some(ref my_obj) = self.object {
return my_obj
.bbox()
.max
.x
.abs()
|
.max(my_obj.bbox().max.y.abs().max(my_obj.bbox().min.y.abs()))
.max(my_obj.bbox().max.z.abs().max(my_obj.bbox().min.z.abs()))
* 2.;
}
0.
}
}
impl Default for Renderer {
fn default() -> Self {
Self::new()
}
}
|
.max(my_obj.bbox().min.x.abs())
|
random_line_split
|
kailua-check-test.rs
|
#[macro_use] extern crate log;
extern crate env_logger;
extern crate clap;
extern crate kailua_test;
extern crate kailua_env;
extern crate kailua_diag;
extern crate kailua_syntax;
extern crate kailua_types;
extern crate kailua_check;
use std::str;
use std::usize;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use clap::{App, Arg, ArgMatches};
use kailua_env::{Source, Span, Spanned};
use kailua_diag::{Stop, Locale, Report, Reporter, TrackMaxKind};
use kailua_syntax::{Chunk, parse_chunk};
use kailua_types::ty::{TypeContext, Display};
use kailua_check::check_from_chunk;
use kailua_check::options::Options;
use kailua_check::env::Context;
struct Testing {
note_spanned_infos: bool,
}
impl Testing {
fn new() -> Testing {
Testing { note_spanned_infos: false }
}
}
impl kailua_test::Testing for Testing {
fn augment_args<'a, 'b: 'a>(&self, app: App<'a, 'b>) -> App<'a, 'b> {
app.arg(
Arg::with_name("note_spanned_infos")
.short("s")
.long("note-spanned-infos")
.help("Displays a list of spanned informations.\n\
Only useful when used with `--exact-diags`."))
}
fn collect_args<'a>(&mut self, matches: &ArgMatches<'a>) {
self.note_spanned_infos = matches.is_present("note_spanned_infos");
}
fn run(&self, source: Rc<RefCell<Source>>, span: Span, filespans: &HashMap<String, Span>,
report: Rc<Report>) -> String {
let chunk = match parse_chunk(&source.borrow(), span, &*report) {
Ok(chunk) => chunk,
Err(_) => return format!("parse error"),
};
struct Opts {
source: Rc<RefCell<Source>>,
filespans: HashMap<String, Span>,
}
impl Options for Opts {
fn require_chunk(&mut self, path: Spanned<&[u8]>,
report: &Report) -> Result<Chunk, Option<Stop>> {
let path = str::from_utf8(&path).map_err(|_| None)?;
let span = *self.filespans.get(path).ok_or(None)?;
parse_chunk(&self.source.borrow(), span, report).map_err(|_| None)
}
}
let report = Rc::new(TrackMaxKind::new(report));
let opts = Rc::new(RefCell::new(Opts { source: source, filespans: filespans.clone() }));
let mut context = Context::new(report.clone());
let ret = check_from_chunk(&mut context, chunk, opts);
// spanned information is available even on error
if self.note_spanned_infos {
let mut slots: Vec<_> = context.spanned_slots().iter().collect();
slots.sort_by_key(|slot| {
(slot.span.unit(), slot.span.end().to_usize(),
usize::MAX - slot.span.begin().to_usize())
});
for slot in slots {
let msg = format!("slot: {}",
slot.display(context.types() as &TypeContext)
.localized(Locale::dummy()));
report.info(slot.span, &msg).done().unwrap();
}
}
match ret {
Ok(()) =>
|
,
Err(e) => {
info!("check failed: {:?}", e);
format!("error")
},
}
}
}
fn main() {
env_logger::init().unwrap();
kailua_test::Tester::new("kailua-check-test", Testing::new())
.feature("no_implicit_func_sig", cfg!(feature = "no_implicit_func_sig"))
.feature("warn_on_useless_conds", cfg!(feature = "warn_on_useless_conds"))
.feature("warn_on_dead_code", cfg!(feature = "warn_on_dead_code"))
.scan("src/tests")
.done();
}
|
{
if report.can_continue() {
format!("ok")
} else {
info!("check failed due to prior errors");
format!("error")
}
}
|
conditional_block
|
kailua-check-test.rs
|
#[macro_use] extern crate log;
extern crate env_logger;
extern crate clap;
extern crate kailua_test;
extern crate kailua_env;
extern crate kailua_diag;
extern crate kailua_syntax;
extern crate kailua_types;
extern crate kailua_check;
use std::str;
use std::usize;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use clap::{App, Arg, ArgMatches};
use kailua_env::{Source, Span, Spanned};
use kailua_diag::{Stop, Locale, Report, Reporter, TrackMaxKind};
use kailua_syntax::{Chunk, parse_chunk};
use kailua_types::ty::{TypeContext, Display};
use kailua_check::check_from_chunk;
use kailua_check::options::Options;
use kailua_check::env::Context;
struct Testing {
note_spanned_infos: bool,
}
impl Testing {
fn new() -> Testing
|
}
impl kailua_test::Testing for Testing {
fn augment_args<'a, 'b: 'a>(&self, app: App<'a, 'b>) -> App<'a, 'b> {
app.arg(
Arg::with_name("note_spanned_infos")
.short("s")
.long("note-spanned-infos")
.help("Displays a list of spanned informations.\n\
Only useful when used with `--exact-diags`."))
}
fn collect_args<'a>(&mut self, matches: &ArgMatches<'a>) {
self.note_spanned_infos = matches.is_present("note_spanned_infos");
}
fn run(&self, source: Rc<RefCell<Source>>, span: Span, filespans: &HashMap<String, Span>,
report: Rc<Report>) -> String {
let chunk = match parse_chunk(&source.borrow(), span, &*report) {
Ok(chunk) => chunk,
Err(_) => return format!("parse error"),
};
struct Opts {
source: Rc<RefCell<Source>>,
filespans: HashMap<String, Span>,
}
impl Options for Opts {
fn require_chunk(&mut self, path: Spanned<&[u8]>,
report: &Report) -> Result<Chunk, Option<Stop>> {
let path = str::from_utf8(&path).map_err(|_| None)?;
let span = *self.filespans.get(path).ok_or(None)?;
parse_chunk(&self.source.borrow(), span, report).map_err(|_| None)
}
}
let report = Rc::new(TrackMaxKind::new(report));
let opts = Rc::new(RefCell::new(Opts { source: source, filespans: filespans.clone() }));
let mut context = Context::new(report.clone());
let ret = check_from_chunk(&mut context, chunk, opts);
// spanned information is available even on error
if self.note_spanned_infos {
let mut slots: Vec<_> = context.spanned_slots().iter().collect();
slots.sort_by_key(|slot| {
(slot.span.unit(), slot.span.end().to_usize(),
usize::MAX - slot.span.begin().to_usize())
});
for slot in slots {
let msg = format!("slot: {}",
slot.display(context.types() as &TypeContext)
.localized(Locale::dummy()));
report.info(slot.span, &msg).done().unwrap();
}
}
match ret {
Ok(()) => {
if report.can_continue() {
format!("ok")
} else {
info!("check failed due to prior errors");
format!("error")
}
},
Err(e) => {
info!("check failed: {:?}", e);
format!("error")
},
}
}
}
fn main() {
env_logger::init().unwrap();
kailua_test::Tester::new("kailua-check-test", Testing::new())
.feature("no_implicit_func_sig", cfg!(feature = "no_implicit_func_sig"))
.feature("warn_on_useless_conds", cfg!(feature = "warn_on_useless_conds"))
.feature("warn_on_dead_code", cfg!(feature = "warn_on_dead_code"))
.scan("src/tests")
.done();
}
|
{
Testing { note_spanned_infos: false }
}
|
identifier_body
|
kailua-check-test.rs
|
#[macro_use] extern crate log;
extern crate env_logger;
extern crate clap;
extern crate kailua_test;
extern crate kailua_env;
extern crate kailua_diag;
extern crate kailua_syntax;
extern crate kailua_types;
extern crate kailua_check;
use std::str;
use std::usize;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use clap::{App, Arg, ArgMatches};
use kailua_env::{Source, Span, Spanned};
use kailua_diag::{Stop, Locale, Report, Reporter, TrackMaxKind};
use kailua_syntax::{Chunk, parse_chunk};
use kailua_types::ty::{TypeContext, Display};
use kailua_check::check_from_chunk;
use kailua_check::options::Options;
|
impl Testing {
fn new() -> Testing {
Testing { note_spanned_infos: false }
}
}
impl kailua_test::Testing for Testing {
fn augment_args<'a, 'b: 'a>(&self, app: App<'a, 'b>) -> App<'a, 'b> {
app.arg(
Arg::with_name("note_spanned_infos")
.short("s")
.long("note-spanned-infos")
.help("Displays a list of spanned informations.\n\
Only useful when used with `--exact-diags`."))
}
fn collect_args<'a>(&mut self, matches: &ArgMatches<'a>) {
self.note_spanned_infos = matches.is_present("note_spanned_infos");
}
fn run(&self, source: Rc<RefCell<Source>>, span: Span, filespans: &HashMap<String, Span>,
report: Rc<Report>) -> String {
let chunk = match parse_chunk(&source.borrow(), span, &*report) {
Ok(chunk) => chunk,
Err(_) => return format!("parse error"),
};
struct Opts {
source: Rc<RefCell<Source>>,
filespans: HashMap<String, Span>,
}
impl Options for Opts {
fn require_chunk(&mut self, path: Spanned<&[u8]>,
report: &Report) -> Result<Chunk, Option<Stop>> {
let path = str::from_utf8(&path).map_err(|_| None)?;
let span = *self.filespans.get(path).ok_or(None)?;
parse_chunk(&self.source.borrow(), span, report).map_err(|_| None)
}
}
let report = Rc::new(TrackMaxKind::new(report));
let opts = Rc::new(RefCell::new(Opts { source: source, filespans: filespans.clone() }));
let mut context = Context::new(report.clone());
let ret = check_from_chunk(&mut context, chunk, opts);
// spanned information is available even on error
if self.note_spanned_infos {
let mut slots: Vec<_> = context.spanned_slots().iter().collect();
slots.sort_by_key(|slot| {
(slot.span.unit(), slot.span.end().to_usize(),
usize::MAX - slot.span.begin().to_usize())
});
for slot in slots {
let msg = format!("slot: {}",
slot.display(context.types() as &TypeContext)
.localized(Locale::dummy()));
report.info(slot.span, &msg).done().unwrap();
}
}
match ret {
Ok(()) => {
if report.can_continue() {
format!("ok")
} else {
info!("check failed due to prior errors");
format!("error")
}
},
Err(e) => {
info!("check failed: {:?}", e);
format!("error")
},
}
}
}
fn main() {
env_logger::init().unwrap();
kailua_test::Tester::new("kailua-check-test", Testing::new())
.feature("no_implicit_func_sig", cfg!(feature = "no_implicit_func_sig"))
.feature("warn_on_useless_conds", cfg!(feature = "warn_on_useless_conds"))
.feature("warn_on_dead_code", cfg!(feature = "warn_on_dead_code"))
.scan("src/tests")
.done();
}
|
use kailua_check::env::Context;
struct Testing {
note_spanned_infos: bool,
}
|
random_line_split
|
kailua-check-test.rs
|
#[macro_use] extern crate log;
extern crate env_logger;
extern crate clap;
extern crate kailua_test;
extern crate kailua_env;
extern crate kailua_diag;
extern crate kailua_syntax;
extern crate kailua_types;
extern crate kailua_check;
use std::str;
use std::usize;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::HashMap;
use clap::{App, Arg, ArgMatches};
use kailua_env::{Source, Span, Spanned};
use kailua_diag::{Stop, Locale, Report, Reporter, TrackMaxKind};
use kailua_syntax::{Chunk, parse_chunk};
use kailua_types::ty::{TypeContext, Display};
use kailua_check::check_from_chunk;
use kailua_check::options::Options;
use kailua_check::env::Context;
struct Testing {
note_spanned_infos: bool,
}
impl Testing {
fn new() -> Testing {
Testing { note_spanned_infos: false }
}
}
impl kailua_test::Testing for Testing {
fn augment_args<'a, 'b: 'a>(&self, app: App<'a, 'b>) -> App<'a, 'b> {
app.arg(
Arg::with_name("note_spanned_infos")
.short("s")
.long("note-spanned-infos")
.help("Displays a list of spanned informations.\n\
Only useful when used with `--exact-diags`."))
}
fn collect_args<'a>(&mut self, matches: &ArgMatches<'a>) {
self.note_spanned_infos = matches.is_present("note_spanned_infos");
}
fn
|
(&self, source: Rc<RefCell<Source>>, span: Span, filespans: &HashMap<String, Span>,
report: Rc<Report>) -> String {
let chunk = match parse_chunk(&source.borrow(), span, &*report) {
Ok(chunk) => chunk,
Err(_) => return format!("parse error"),
};
struct Opts {
source: Rc<RefCell<Source>>,
filespans: HashMap<String, Span>,
}
impl Options for Opts {
fn require_chunk(&mut self, path: Spanned<&[u8]>,
report: &Report) -> Result<Chunk, Option<Stop>> {
let path = str::from_utf8(&path).map_err(|_| None)?;
let span = *self.filespans.get(path).ok_or(None)?;
parse_chunk(&self.source.borrow(), span, report).map_err(|_| None)
}
}
let report = Rc::new(TrackMaxKind::new(report));
let opts = Rc::new(RefCell::new(Opts { source: source, filespans: filespans.clone() }));
let mut context = Context::new(report.clone());
let ret = check_from_chunk(&mut context, chunk, opts);
// spanned information is available even on error
if self.note_spanned_infos {
let mut slots: Vec<_> = context.spanned_slots().iter().collect();
slots.sort_by_key(|slot| {
(slot.span.unit(), slot.span.end().to_usize(),
usize::MAX - slot.span.begin().to_usize())
});
for slot in slots {
let msg = format!("slot: {}",
slot.display(context.types() as &TypeContext)
.localized(Locale::dummy()));
report.info(slot.span, &msg).done().unwrap();
}
}
match ret {
Ok(()) => {
if report.can_continue() {
format!("ok")
} else {
info!("check failed due to prior errors");
format!("error")
}
},
Err(e) => {
info!("check failed: {:?}", e);
format!("error")
},
}
}
}
fn main() {
env_logger::init().unwrap();
kailua_test::Tester::new("kailua-check-test", Testing::new())
.feature("no_implicit_func_sig", cfg!(feature = "no_implicit_func_sig"))
.feature("warn_on_useless_conds", cfg!(feature = "warn_on_useless_conds"))
.feature("warn_on_dead_code", cfg!(feature = "warn_on_dead_code"))
.scan("src/tests")
.done();
}
|
run
|
identifier_name
|
day9.rs
|
use std::io::prelude::*;
#[derive(Debug, Default, PartialEq)]
struct Marker {
length: u32,
multiplier: u32,
}
fn main()
|
fn decoding_nested(line: &str) -> u64 {
let (ret, _) = decoding_nested_rec(&mut line.chars(), std::u64::MAX);
ret
}
fn decoding_nested_rec(it: &mut std::str::Chars, length: u64) -> (u64, u64) {
let mut total_length: u64 = 0;
let mut char_read: u64 = 0;
while char_read < length {
let letter = match it.next() {
Some(letter) => letter,
None => break,
};
if letter =='' {
continue;
}
char_read += 1;
if is_marker_start(letter) {
let (marker, marker_read) = decode_marker(it);
char_read += marker_read as u64;
let (nested_length, nested_read) = decoding_nested_rec(it, marker.length as u64);
total_length += nested_length * (marker.multiplier as u64);
char_read += nested_read as u64;
} else {
total_length += 1;
}
}
(total_length, char_read)
}
#[test]
fn decoding_nested_test() {
let input = "X(7x2)A(1x2)AY"; //A(1x2)AA(1x2)A ; AAAAAA
assert_eq!(decoding_nested(input), 8);
let input = "(11x2)ABCDEF(6x1)(1x1)A";
assert_eq!(decoding_nested(input), 14);
let input = "(3x3)XYZ";
assert_eq!(decoding_nested(input), 9);
let input = "(1x1)B";
assert_eq!(decoding_nested(input), 1);
let input = "X(8x2)(3x3)ABCY";
assert_eq!(decoding_nested(input), 20);
let input = "(27x12)(20x12)(13x14)(7x10)(1x12)A";
assert_eq!(decoding_nested(input), 241920);
let input = "(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN";
assert_eq!(decoding_nested(input), 445);
}
fn decoding_light(line: String) -> u32 {
let mut total_length: u32 = 0;
let mut it = line.chars();
loop {
let letter = match it.next() {
Some(letter) => letter,
None => break,
};
if letter =='' {
continue;
}
if is_marker_start(letter) {
let (marker, _) = decode_marker(&mut it);
total_length += marker.length * marker.multiplier;
skip_letter(&mut it, marker.length);
} else {
total_length += 1;
}
}
total_length
}
#[test]
fn decoding_light_test() {
assert_eq!(decoding_light(String::from("ADVENT")), 6);
assert_eq!(decoding_light(String::from("A(1x5)BC")), 7);
assert_eq!(decoding_light(String::from("(3x3)XYZ")), 9);
assert_eq!(decoding_light(String::from("A(2x2)BCD(2x2)EFG")), 11);
assert_eq!(decoding_light(String::from("(6x1)(1x3)A")), 6);
assert_eq!(decoding_light(String::from("X(8x2)(3x3)ABCY")), 18);
}
fn is_marker_start(letter: char) -> bool {
letter == '('
}
fn skip_letter<IteratorChars>(it: &mut IteratorChars, n: u32)
where IteratorChars: Iterator<Item = char>
{
for _ in 0..n {
it.next();
}
}
fn decode_marker(it: &mut std::str::Chars) -> (Marker, u32) {
let (length, length_length) = read_number(it);
let (multiplier, multiplier_length) = read_number(it);
(Marker {
length: length,
multiplier: multiplier,
},
length_length + multiplier_length + 2)
}
#[test]
fn decode_marker_test() {
assert_eq!(decode_marker(&mut "1x2)".chars()),
(Marker {
length: 1,
multiplier: 2,
},
4));
assert_eq!(decode_marker(&mut "123w456r".chars()),
(Marker {
length: 123,
multiplier: 456,
},
8));
}
fn read_number(it: &mut std::str::Chars) -> (u32, u32) {
let mut number = String::new();
loop {
let letter = match it.next() {
Some(letter) => letter,
_ => break,
};
if letter.is_numeric() {
number.push(letter);
} else {
break;
}
}
if number.is_empty() {
panic!("No integer to parse at beginnig of string");
} else {
(number.parse::<u32>().expect("Cannot parse u32"), number.len() as u32)
}
}
#[test]
fn read_number_test() {
assert_eq!(read_number(&mut "123".chars()), (123, 3));
assert_eq!(read_number(&mut "1".chars()), (1, 1));
assert_eq!(read_number(&mut "42)".chars()), (42, 2));
assert_eq!(read_number(&mut "2x".chars()), (2, 1));
}
|
{
let mut inputs = std::fs::File::open("day9_inputs.txt").expect("Cannot open input file");
let mut line = String::new();
inputs.read_to_string(&mut line).expect("Cannot read line");
line.pop(); // Last char is a new line.
let length = decoding_light(line.clone());
println!("Length: {}", length);
assert_eq!(length, 98135);
let length = decoding_nested(&line);
println!("Nested length: {}", length);
assert_eq!(length, 10964557606);
}
|
identifier_body
|
day9.rs
|
use std::io::prelude::*;
#[derive(Debug, Default, PartialEq)]
struct Marker {
length: u32,
multiplier: u32,
}
fn main() {
let mut inputs = std::fs::File::open("day9_inputs.txt").expect("Cannot open input file");
let mut line = String::new();
inputs.read_to_string(&mut line).expect("Cannot read line");
line.pop(); // Last char is a new line.
let length = decoding_light(line.clone());
println!("Length: {}", length);
assert_eq!(length, 98135);
let length = decoding_nested(&line);
println!("Nested length: {}", length);
assert_eq!(length, 10964557606);
}
fn decoding_nested(line: &str) -> u64 {
let (ret, _) = decoding_nested_rec(&mut line.chars(), std::u64::MAX);
ret
}
fn decoding_nested_rec(it: &mut std::str::Chars, length: u64) -> (u64, u64) {
let mut total_length: u64 = 0;
let mut char_read: u64 = 0;
while char_read < length {
let letter = match it.next() {
Some(letter) => letter,
None => break,
};
if letter =='' {
continue;
}
char_read += 1;
if is_marker_start(letter) {
let (marker, marker_read) = decode_marker(it);
char_read += marker_read as u64;
let (nested_length, nested_read) = decoding_nested_rec(it, marker.length as u64);
total_length += nested_length * (marker.multiplier as u64);
char_read += nested_read as u64;
} else {
total_length += 1;
}
}
(total_length, char_read)
}
#[test]
fn decoding_nested_test() {
let input = "X(7x2)A(1x2)AY"; //A(1x2)AA(1x2)A ; AAAAAA
assert_eq!(decoding_nested(input), 8);
let input = "(11x2)ABCDEF(6x1)(1x1)A";
assert_eq!(decoding_nested(input), 14);
let input = "(3x3)XYZ";
assert_eq!(decoding_nested(input), 9);
|
assert_eq!(decoding_nested(input), 20);
let input = "(27x12)(20x12)(13x14)(7x10)(1x12)A";
assert_eq!(decoding_nested(input), 241920);
let input = "(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN";
assert_eq!(decoding_nested(input), 445);
}
fn decoding_light(line: String) -> u32 {
let mut total_length: u32 = 0;
let mut it = line.chars();
loop {
let letter = match it.next() {
Some(letter) => letter,
None => break,
};
if letter =='' {
continue;
}
if is_marker_start(letter) {
let (marker, _) = decode_marker(&mut it);
total_length += marker.length * marker.multiplier;
skip_letter(&mut it, marker.length);
} else {
total_length += 1;
}
}
total_length
}
#[test]
fn decoding_light_test() {
assert_eq!(decoding_light(String::from("ADVENT")), 6);
assert_eq!(decoding_light(String::from("A(1x5)BC")), 7);
assert_eq!(decoding_light(String::from("(3x3)XYZ")), 9);
assert_eq!(decoding_light(String::from("A(2x2)BCD(2x2)EFG")), 11);
assert_eq!(decoding_light(String::from("(6x1)(1x3)A")), 6);
assert_eq!(decoding_light(String::from("X(8x2)(3x3)ABCY")), 18);
}
fn is_marker_start(letter: char) -> bool {
letter == '('
}
fn skip_letter<IteratorChars>(it: &mut IteratorChars, n: u32)
where IteratorChars: Iterator<Item = char>
{
for _ in 0..n {
it.next();
}
}
fn decode_marker(it: &mut std::str::Chars) -> (Marker, u32) {
let (length, length_length) = read_number(it);
let (multiplier, multiplier_length) = read_number(it);
(Marker {
length: length,
multiplier: multiplier,
},
length_length + multiplier_length + 2)
}
#[test]
fn decode_marker_test() {
assert_eq!(decode_marker(&mut "1x2)".chars()),
(Marker {
length: 1,
multiplier: 2,
},
4));
assert_eq!(decode_marker(&mut "123w456r".chars()),
(Marker {
length: 123,
multiplier: 456,
},
8));
}
fn read_number(it: &mut std::str::Chars) -> (u32, u32) {
let mut number = String::new();
loop {
let letter = match it.next() {
Some(letter) => letter,
_ => break,
};
if letter.is_numeric() {
number.push(letter);
} else {
break;
}
}
if number.is_empty() {
panic!("No integer to parse at beginnig of string");
} else {
(number.parse::<u32>().expect("Cannot parse u32"), number.len() as u32)
}
}
#[test]
fn read_number_test() {
assert_eq!(read_number(&mut "123".chars()), (123, 3));
assert_eq!(read_number(&mut "1".chars()), (1, 1));
assert_eq!(read_number(&mut "42)".chars()), (42, 2));
assert_eq!(read_number(&mut "2x".chars()), (2, 1));
}
|
let input = "(1x1)B";
assert_eq!(decoding_nested(input), 1);
let input = "X(8x2)(3x3)ABCY";
|
random_line_split
|
day9.rs
|
use std::io::prelude::*;
#[derive(Debug, Default, PartialEq)]
struct Marker {
length: u32,
multiplier: u32,
}
fn main() {
let mut inputs = std::fs::File::open("day9_inputs.txt").expect("Cannot open input file");
let mut line = String::new();
inputs.read_to_string(&mut line).expect("Cannot read line");
line.pop(); // Last char is a new line.
let length = decoding_light(line.clone());
println!("Length: {}", length);
assert_eq!(length, 98135);
let length = decoding_nested(&line);
println!("Nested length: {}", length);
assert_eq!(length, 10964557606);
}
fn decoding_nested(line: &str) -> u64 {
let (ret, _) = decoding_nested_rec(&mut line.chars(), std::u64::MAX);
ret
}
fn decoding_nested_rec(it: &mut std::str::Chars, length: u64) -> (u64, u64) {
let mut total_length: u64 = 0;
let mut char_read: u64 = 0;
while char_read < length {
let letter = match it.next() {
Some(letter) => letter,
None => break,
};
if letter =='' {
continue;
}
char_read += 1;
if is_marker_start(letter) {
let (marker, marker_read) = decode_marker(it);
char_read += marker_read as u64;
let (nested_length, nested_read) = decoding_nested_rec(it, marker.length as u64);
total_length += nested_length * (marker.multiplier as u64);
char_read += nested_read as u64;
} else {
total_length += 1;
}
}
(total_length, char_read)
}
#[test]
fn decoding_nested_test() {
let input = "X(7x2)A(1x2)AY"; //A(1x2)AA(1x2)A ; AAAAAA
assert_eq!(decoding_nested(input), 8);
let input = "(11x2)ABCDEF(6x1)(1x1)A";
assert_eq!(decoding_nested(input), 14);
let input = "(3x3)XYZ";
assert_eq!(decoding_nested(input), 9);
let input = "(1x1)B";
assert_eq!(decoding_nested(input), 1);
let input = "X(8x2)(3x3)ABCY";
assert_eq!(decoding_nested(input), 20);
let input = "(27x12)(20x12)(13x14)(7x10)(1x12)A";
assert_eq!(decoding_nested(input), 241920);
let input = "(25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN";
assert_eq!(decoding_nested(input), 445);
}
fn decoding_light(line: String) -> u32 {
let mut total_length: u32 = 0;
let mut it = line.chars();
loop {
let letter = match it.next() {
Some(letter) => letter,
None => break,
};
if letter =='' {
continue;
}
if is_marker_start(letter) {
let (marker, _) = decode_marker(&mut it);
total_length += marker.length * marker.multiplier;
skip_letter(&mut it, marker.length);
} else {
total_length += 1;
}
}
total_length
}
#[test]
fn decoding_light_test() {
assert_eq!(decoding_light(String::from("ADVENT")), 6);
assert_eq!(decoding_light(String::from("A(1x5)BC")), 7);
assert_eq!(decoding_light(String::from("(3x3)XYZ")), 9);
assert_eq!(decoding_light(String::from("A(2x2)BCD(2x2)EFG")), 11);
assert_eq!(decoding_light(String::from("(6x1)(1x3)A")), 6);
assert_eq!(decoding_light(String::from("X(8x2)(3x3)ABCY")), 18);
}
fn is_marker_start(letter: char) -> bool {
letter == '('
}
fn skip_letter<IteratorChars>(it: &mut IteratorChars, n: u32)
where IteratorChars: Iterator<Item = char>
{
for _ in 0..n {
it.next();
}
}
fn decode_marker(it: &mut std::str::Chars) -> (Marker, u32) {
let (length, length_length) = read_number(it);
let (multiplier, multiplier_length) = read_number(it);
(Marker {
length: length,
multiplier: multiplier,
},
length_length + multiplier_length + 2)
}
#[test]
fn decode_marker_test() {
assert_eq!(decode_marker(&mut "1x2)".chars()),
(Marker {
length: 1,
multiplier: 2,
},
4));
assert_eq!(decode_marker(&mut "123w456r".chars()),
(Marker {
length: 123,
multiplier: 456,
},
8));
}
fn read_number(it: &mut std::str::Chars) -> (u32, u32) {
let mut number = String::new();
loop {
let letter = match it.next() {
Some(letter) => letter,
_ => break,
};
if letter.is_numeric() {
number.push(letter);
} else {
break;
}
}
if number.is_empty() {
panic!("No integer to parse at beginnig of string");
} else {
(number.parse::<u32>().expect("Cannot parse u32"), number.len() as u32)
}
}
#[test]
fn
|
() {
assert_eq!(read_number(&mut "123".chars()), (123, 3));
assert_eq!(read_number(&mut "1".chars()), (1, 1));
assert_eq!(read_number(&mut "42)".chars()), (42, 2));
assert_eq!(read_number(&mut "2x".chars()), (2, 1));
}
|
read_number_test
|
identifier_name
|
regions-close-over-type-parameter-2.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax)]
// Test for what happens when a type parameter `A` is closed over into
// an object. This should yield errors unless `A` (and the object)
// both have suitable bounds.
trait Foo { fn get(&self); }
impl<A> Foo for A {
fn get(&self) { }
}
fn repeater3<'a,A:'a>(v: A) -> Box<Foo+'a> {
box v as Box<Foo+'a>
}
fn main() {
// Error results because the type of is inferred to be
// ~Repeat<&'blk int> where blk is the lifetime of the block below.
let _ = {
let tmp0 = 3i;
let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long enough
|
}
|
repeater3(tmp1)
};
|
random_line_split
|
regions-close-over-type-parameter-2.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax)]
// Test for what happens when a type parameter `A` is closed over into
// an object. This should yield errors unless `A` (and the object)
// both have suitable bounds.
trait Foo { fn get(&self); }
impl<A> Foo for A {
fn get(&self) { }
}
fn repeater3<'a,A:'a>(v: A) -> Box<Foo+'a> {
box v as Box<Foo+'a>
}
fn
|
() {
// Error results because the type of is inferred to be
// ~Repeat<&'blk int> where blk is the lifetime of the block below.
let _ = {
let tmp0 = 3i;
let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long enough
repeater3(tmp1)
};
}
|
main
|
identifier_name
|
regions-close-over-type-parameter-2.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax)]
// Test for what happens when a type parameter `A` is closed over into
// an object. This should yield errors unless `A` (and the object)
// both have suitable bounds.
trait Foo { fn get(&self); }
impl<A> Foo for A {
fn get(&self)
|
}
fn repeater3<'a,A:'a>(v: A) -> Box<Foo+'a> {
box v as Box<Foo+'a>
}
fn main() {
// Error results because the type of is inferred to be
// ~Repeat<&'blk int> where blk is the lifetime of the block below.
let _ = {
let tmp0 = 3i;
let tmp1 = &tmp0; //~ ERROR `tmp0` does not live long enough
repeater3(tmp1)
};
}
|
{ }
|
identifier_body
|
gamepadlist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::GamepadListBinding;
use dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::gamepad::Gamepad;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
// https://www.w3.org/TR/gamepad/
#[dom_struct]
pub struct GamepadList {
reflector_: Reflector,
list: DomRefCell<Vec<Dom<Gamepad>>>
}
impl GamepadList {
fn new_inherited(list: &[&Gamepad]) -> GamepadList {
GamepadList {
reflector_: Reflector::new(),
list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect())
}
}
pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> {
reflect_dom_object(box GamepadList::new_inherited(list),
global,
GamepadListBinding::Wrap)
}
pub fn add_if_not_exists(&self, gamepads: &[DomRoot<Gamepad>]) {
for gamepad in gamepads {
if!self.list.borrow().iter().any(|g| g.gamepad_id() == gamepad.gamepad_id())
|
}
}
}
impl GamepadListMethods for GamepadList {
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn Length(&self) -> u32 {
self.list.borrow().len() as u32
}
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn Item(&self, index: u32) -> Option<DomRoot<Gamepad>> {
self.list.borrow().get(index as usize).map(|gamepad| DomRoot::from_ref(&**gamepad))
}
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Gamepad>> {
self.Item(index)
}
}
|
{
self.list.borrow_mut().push(Dom::from_ref(&*gamepad));
// Ensure that the gamepad has the correct index
gamepad.update_index(self.list.borrow().len() as i32 - 1);
}
|
conditional_block
|
gamepadlist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::GamepadListBinding;
use dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::gamepad::Gamepad;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
// https://www.w3.org/TR/gamepad/
#[dom_struct]
pub struct GamepadList {
reflector_: Reflector,
list: DomRefCell<Vec<Dom<Gamepad>>>
}
impl GamepadList {
fn new_inherited(list: &[&Gamepad]) -> GamepadList
|
pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> {
reflect_dom_object(box GamepadList::new_inherited(list),
global,
GamepadListBinding::Wrap)
}
pub fn add_if_not_exists(&self, gamepads: &[DomRoot<Gamepad>]) {
for gamepad in gamepads {
if!self.list.borrow().iter().any(|g| g.gamepad_id() == gamepad.gamepad_id()) {
self.list.borrow_mut().push(Dom::from_ref(&*gamepad));
// Ensure that the gamepad has the correct index
gamepad.update_index(self.list.borrow().len() as i32 - 1);
}
}
}
}
impl GamepadListMethods for GamepadList {
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn Length(&self) -> u32 {
self.list.borrow().len() as u32
}
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn Item(&self, index: u32) -> Option<DomRoot<Gamepad>> {
self.list.borrow().get(index as usize).map(|gamepad| DomRoot::from_ref(&**gamepad))
}
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Gamepad>> {
self.Item(index)
}
}
|
{
GamepadList {
reflector_: Reflector::new(),
list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect())
}
}
|
identifier_body
|
gamepadlist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::GamepadListBinding;
use dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::gamepad::Gamepad;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
// https://www.w3.org/TR/gamepad/
#[dom_struct]
pub struct GamepadList {
reflector_: Reflector,
list: DomRefCell<Vec<Dom<Gamepad>>>
}
impl GamepadList {
fn new_inherited(list: &[&Gamepad]) -> GamepadList {
GamepadList {
reflector_: Reflector::new(),
list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect())
}
}
pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> {
reflect_dom_object(box GamepadList::new_inherited(list),
global,
GamepadListBinding::Wrap)
}
pub fn
|
(&self, gamepads: &[DomRoot<Gamepad>]) {
for gamepad in gamepads {
if!self.list.borrow().iter().any(|g| g.gamepad_id() == gamepad.gamepad_id()) {
self.list.borrow_mut().push(Dom::from_ref(&*gamepad));
// Ensure that the gamepad has the correct index
gamepad.update_index(self.list.borrow().len() as i32 - 1);
}
}
}
}
impl GamepadListMethods for GamepadList {
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn Length(&self) -> u32 {
self.list.borrow().len() as u32
}
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn Item(&self, index: u32) -> Option<DomRoot<Gamepad>> {
self.list.borrow().get(index as usize).map(|gamepad| DomRoot::from_ref(&**gamepad))
}
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Gamepad>> {
self.Item(index)
}
}
|
add_if_not_exists
|
identifier_name
|
gamepadlist.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::cell::DomRefCell;
use dom::bindings::codegen::Bindings::GamepadListBinding;
use dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::{Dom, DomRoot};
use dom::gamepad::Gamepad;
use dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
// https://www.w3.org/TR/gamepad/
#[dom_struct]
pub struct GamepadList {
reflector_: Reflector,
list: DomRefCell<Vec<Dom<Gamepad>>>
}
impl GamepadList {
fn new_inherited(list: &[&Gamepad]) -> GamepadList {
GamepadList {
reflector_: Reflector::new(),
list: DomRefCell::new(list.iter().map(|g| Dom::from_ref(&**g)).collect())
}
}
pub fn new(global: &GlobalScope, list: &[&Gamepad]) -> DomRoot<GamepadList> {
reflect_dom_object(box GamepadList::new_inherited(list),
global,
GamepadListBinding::Wrap)
}
pub fn add_if_not_exists(&self, gamepads: &[DomRoot<Gamepad>]) {
for gamepad in gamepads {
if!self.list.borrow().iter().any(|g| g.gamepad_id() == gamepad.gamepad_id()) {
|
}
}
}
}
impl GamepadListMethods for GamepadList {
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn Length(&self) -> u32 {
self.list.borrow().len() as u32
}
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn Item(&self, index: u32) -> Option<DomRoot<Gamepad>> {
self.list.borrow().get(index as usize).map(|gamepad| DomRoot::from_ref(&**gamepad))
}
// https://w3c.github.io/gamepad/#dom-navigator-getgamepads
fn IndexedGetter(&self, index: u32) -> Option<DomRoot<Gamepad>> {
self.Item(index)
}
}
|
self.list.borrow_mut().push(Dom::from_ref(&*gamepad));
// Ensure that the gamepad has the correct index
gamepad.update_index(self.list.borrow().len() as i32 - 1);
|
random_line_split
|
whoami.rs
|
#![crate_name = "whoami"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.21 */
extern crate getopts;
extern crate libc;
use getopts::Options;
use std::io::Write;
#[path = "../common/util.rs"] #[macro_use] mod util;
mod platform;
static NAME: &'static str = "whoami";
static VERSION: &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> i32 {
|
let mut opts = Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "{}", f),
};
if matches.opt_present("help") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTIONS]", NAME);
println!("");
println!("{}", opts.usage("print effective userid"));
return 0;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
exec();
0
}
pub fn exec() {
unsafe {
let username = platform::getusername();
println!("{}", username);
}
}
|
random_line_split
|
|
whoami.rs
|
#![crate_name = "whoami"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.21 */
extern crate getopts;
extern crate libc;
use getopts::Options;
use std::io::Write;
#[path = "../common/util.rs"] #[macro_use] mod util;
mod platform;
static NAME: &'static str = "whoami";
static VERSION: &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> i32
|
println!("{} {}", NAME, VERSION);
return 0;
}
exec();
0
}
pub fn exec() {
unsafe {
let username = platform::getusername();
println!("{}", username);
}
}
|
{
let mut opts = Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "{}", f),
};
if matches.opt_present("help") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTIONS]", NAME);
println!("");
println!("{}", opts.usage("print effective userid"));
return 0;
}
if matches.opt_present("version") {
|
identifier_body
|
whoami.rs
|
#![crate_name = "whoami"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Jordi Boggiano <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/* last synced with: whoami (GNU coreutils) 8.21 */
extern crate getopts;
extern crate libc;
use getopts::Options;
use std::io::Write;
#[path = "../common/util.rs"] #[macro_use] mod util;
mod platform;
static NAME: &'static str = "whoami";
static VERSION: &'static str = "1.0.0";
pub fn uumain(args: Vec<String>) -> i32 {
let mut opts = Options::new();
opts.optflag("h", "help", "display this help and exit");
opts.optflag("V", "version", "output version information and exit");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => crash!(1, "{}", f),
};
if matches.opt_present("help") {
println!("{} {}", NAME, VERSION);
println!("");
println!("Usage:");
println!(" {} [OPTIONS]", NAME);
println!("");
println!("{}", opts.usage("print effective userid"));
return 0;
}
if matches.opt_present("version") {
println!("{} {}", NAME, VERSION);
return 0;
}
exec();
0
}
pub fn
|
() {
unsafe {
let username = platform::getusername();
println!("{}", username);
}
}
|
exec
|
identifier_name
|
mipsel.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn
|
(target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsiOS => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsWindows => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsLinux => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsAndroid => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsFreebsd | abi::OsDragonfly | abi::OsBitrig | abi::OsOpenbsd => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
},
target_triple: target_triple,
cc_args: Vec::new(),
};
}
|
get_target_strs
|
identifier_name
|
mipsel.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t
|
abi::OsWindows => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsLinux => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsAndroid => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsFreebsd | abi::OsDragonfly | abi::OsBitrig | abi::OsOpenbsd => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
},
target_triple: target_triple,
cc_args: Vec::new(),
};
}
|
{
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsiOS => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
|
identifier_body
|
mipsel.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsiOS => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsWindows => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsLinux => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
|
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsFreebsd | abi::OsDragonfly | abi::OsBitrig | abi::OsOpenbsd => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
},
target_triple: target_triple,
cc_args: Vec::new(),
};
}
|
}
abi::OsAndroid => {
"e-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
|
random_line_split
|
htmlparamelement.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::HTMLParamElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use html5ever_atoms::LocalName;
#[dom_struct]
pub struct HTMLParamElement {
htmlelement: HTMLElement
}
impl HTMLParamElement {
fn
|
(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLParamElement {
HTMLParamElement {
htmlelement:
HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLParamElement> {
Node::reflect_node(box HTMLParamElement::new_inherited(local_name, prefix, document),
document,
HTMLParamElementBinding::Wrap)
}
}
|
new_inherited
|
identifier_name
|
htmlparamelement.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::HTMLParamElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use html5ever_atoms::LocalName;
#[dom_struct]
pub struct HTMLParamElement {
htmlelement: HTMLElement
}
impl HTMLParamElement {
fn new_inherited(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLParamElement {
HTMLParamElement {
|
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLParamElement> {
Node::reflect_node(box HTMLParamElement::new_inherited(local_name, prefix, document),
document,
HTMLParamElementBinding::Wrap)
}
}
|
htmlelement:
HTMLElement::new_inherited(local_name, prefix, document)
|
random_line_split
|
htmlparamelement.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::HTMLParamElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use html5ever_atoms::LocalName;
#[dom_struct]
pub struct HTMLParamElement {
htmlelement: HTMLElement
}
impl HTMLParamElement {
fn new_inherited(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLParamElement {
HTMLParamElement {
htmlelement:
HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLParamElement>
|
}
|
{
Node::reflect_node(box HTMLParamElement::new_inherited(local_name, prefix, document),
document,
HTMLParamElementBinding::Wrap)
}
|
identifier_body
|
trait-impl-fn-incompatibility.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// rustc-env:RUST_NEW_ERROR_FORMAT
trait Foo {
fn foo(x: u16);
fn bar(&mut self, bar: &mut Bar);
}
struct Bar;
impl Foo for Bar {
fn
|
(x: i16) { } //~ ERROR incompatible type
fn bar(&mut self, bar: &Bar) { } //~ ERROR incompatible type
}
fn main() {
}
|
foo
|
identifier_name
|
trait-impl-fn-incompatibility.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// rustc-env:RUST_NEW_ERROR_FORMAT
trait Foo {
fn foo(x: u16);
fn bar(&mut self, bar: &mut Bar);
}
struct Bar;
impl Foo for Bar {
fn foo(x: i16) { } //~ ERROR incompatible type
fn bar(&mut self, bar: &Bar) { } //~ ERROR incompatible type
}
fn main() {
}
|
random_line_split
|
|
expect-infer-var-supply-ty-with-free-region.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-pass
|
where F: FnOnce(A, &u32)
{
}
fn foo() {
// This version works; we infer `A` to be `u32`, and take the type
// of `y` to be `&u32`.
with_closure(|x: u32, y| {});
}
fn bar<'x>(x: &'x u32) {
// Same.
with_closure(|x: &'x u32, y| {});
}
fn main() { }
|
fn with_closure<F, A>(_: F)
|
random_line_split
|
expect-infer-var-supply-ty-with-free-region.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-pass
fn with_closure<F, A>(_: F)
where F: FnOnce(A, &u32)
{
}
fn foo() {
// This version works; we infer `A` to be `u32`, and take the type
// of `y` to be `&u32`.
with_closure(|x: u32, y| {});
}
fn
|
<'x>(x: &'x u32) {
// Same.
with_closure(|x: &'x u32, y| {});
}
fn main() { }
|
bar
|
identifier_name
|
expect-infer-var-supply-ty-with-free-region.rs
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-pass
fn with_closure<F, A>(_: F)
where F: FnOnce(A, &u32)
{
}
fn foo() {
// This version works; we infer `A` to be `u32`, and take the type
// of `y` to be `&u32`.
with_closure(|x: u32, y| {});
}
fn bar<'x>(x: &'x u32) {
// Same.
with_closure(|x: &'x u32, y| {});
}
fn main()
|
{ }
|
identifier_body
|
|
post.rs
|
#[macro_use]
extern crate rustful;
use std::io::{self, Read};
use std::fs::File;
use std::path::Path;
use std::borrow::Cow;
use std::error::Error;
use rustful::{Server, Context, Response, Log, Handler};
use rustful::context::body::ExtQueryBody;
use rustful::StatusCode::{InternalServerError, BadRequest};
fn say_hello(mut context: Context, mut response: Response) {
let body = match context.body.read_query_body() {
Ok(body) => body,
Err(_) => {
//Oh no! Could not read the body
response.set_status(BadRequest);
return;
}
};
let files: &Files = if let Some(files) = context.global.get() {
files
} else {
//Oh no! Why is the global data not a File instance?!
context.log.error("the global data should be of the type `Files`, but it's not");
response.set_status(InternalServerError);
return;
|
} else {
Cow::Borrowed(&files.form)
};
//Insert the content into the page and write it to the response
let complete_page = files.page.replace("{}", &content);
response.send(complete_page);
}
//Dodge an ICE, related to functions as handlers.
struct HandlerFn(fn(Context, Response));
impl Handler for HandlerFn {
fn handle_request(&self, context: Context, response: Response) {
self.0(context, response);
}
}
fn main() {
println!("Visit http://localhost:8080 to try this example.");
//Preload the files
let files = Files {
page: read_string("examples/post/page.html").unwrap(),
form: read_string("examples/post/form.html").unwrap()
};
//Handlers implements the Router trait, so it can be passed to the server as it is
let server_result = Server {
host: 8080.into(),
global: Box::new(files).into(),
content_type: content_type!(Text / Html; Charset = Utf8),
..Server::new(HandlerFn(say_hello))
}.run();
//Check if the server started successfully
match server_result {
Ok(_server) => {},
Err(e) => println!("could not start server: {}", e.description())
}
}
fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
//Read file into a string
let mut string = String::new();
File::open(path).and_then(|mut f| f.read_to_string(&mut string)).map(|_| string)
}
//We want to store the files as strings
struct Files {
page: String,
form: String
}
|
};
//Format the name or use the cached form
let content = if let Some(name) = body.get("name") {
Cow::Owned(format!("<p>Hello, {}!</p>", name))
|
random_line_split
|
post.rs
|
#[macro_use]
extern crate rustful;
use std::io::{self, Read};
use std::fs::File;
use std::path::Path;
use std::borrow::Cow;
use std::error::Error;
use rustful::{Server, Context, Response, Log, Handler};
use rustful::context::body::ExtQueryBody;
use rustful::StatusCode::{InternalServerError, BadRequest};
fn say_hello(mut context: Context, mut response: Response) {
let body = match context.body.read_query_body() {
Ok(body) => body,
Err(_) =>
|
};
let files: &Files = if let Some(files) = context.global.get() {
files
} else {
//Oh no! Why is the global data not a File instance?!
context.log.error("the global data should be of the type `Files`, but it's not");
response.set_status(InternalServerError);
return;
};
//Format the name or use the cached form
let content = if let Some(name) = body.get("name") {
Cow::Owned(format!("<p>Hello, {}!</p>", name))
} else {
Cow::Borrowed(&files.form)
};
//Insert the content into the page and write it to the response
let complete_page = files.page.replace("{}", &content);
response.send(complete_page);
}
//Dodge an ICE, related to functions as handlers.
struct HandlerFn(fn(Context, Response));
impl Handler for HandlerFn {
fn handle_request(&self, context: Context, response: Response) {
self.0(context, response);
}
}
fn main() {
println!("Visit http://localhost:8080 to try this example.");
//Preload the files
let files = Files {
page: read_string("examples/post/page.html").unwrap(),
form: read_string("examples/post/form.html").unwrap()
};
//Handlers implements the Router trait, so it can be passed to the server as it is
let server_result = Server {
host: 8080.into(),
global: Box::new(files).into(),
content_type: content_type!(Text / Html; Charset = Utf8),
..Server::new(HandlerFn(say_hello))
}.run();
//Check if the server started successfully
match server_result {
Ok(_server) => {},
Err(e) => println!("could not start server: {}", e.description())
}
}
fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
//Read file into a string
let mut string = String::new();
File::open(path).and_then(|mut f| f.read_to_string(&mut string)).map(|_| string)
}
//We want to store the files as strings
struct Files {
page: String,
form: String
}
|
{
//Oh no! Could not read the body
response.set_status(BadRequest);
return;
}
|
conditional_block
|
post.rs
|
#[macro_use]
extern crate rustful;
use std::io::{self, Read};
use std::fs::File;
use std::path::Path;
use std::borrow::Cow;
use std::error::Error;
use rustful::{Server, Context, Response, Log, Handler};
use rustful::context::body::ExtQueryBody;
use rustful::StatusCode::{InternalServerError, BadRequest};
fn say_hello(mut context: Context, mut response: Response) {
let body = match context.body.read_query_body() {
Ok(body) => body,
Err(_) => {
//Oh no! Could not read the body
response.set_status(BadRequest);
return;
}
};
let files: &Files = if let Some(files) = context.global.get() {
files
} else {
//Oh no! Why is the global data not a File instance?!
context.log.error("the global data should be of the type `Files`, but it's not");
response.set_status(InternalServerError);
return;
};
//Format the name or use the cached form
let content = if let Some(name) = body.get("name") {
Cow::Owned(format!("<p>Hello, {}!</p>", name))
} else {
Cow::Borrowed(&files.form)
};
//Insert the content into the page and write it to the response
let complete_page = files.page.replace("{}", &content);
response.send(complete_page);
}
//Dodge an ICE, related to functions as handlers.
struct HandlerFn(fn(Context, Response));
impl Handler for HandlerFn {
fn handle_request(&self, context: Context, response: Response) {
self.0(context, response);
}
}
fn main()
|
Err(e) => println!("could not start server: {}", e.description())
}
}
fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
//Read file into a string
let mut string = String::new();
File::open(path).and_then(|mut f| f.read_to_string(&mut string)).map(|_| string)
}
//We want to store the files as strings
struct Files {
page: String,
form: String
}
|
{
println!("Visit http://localhost:8080 to try this example.");
//Preload the files
let files = Files {
page: read_string("examples/post/page.html").unwrap(),
form: read_string("examples/post/form.html").unwrap()
};
//Handlers implements the Router trait, so it can be passed to the server as it is
let server_result = Server {
host: 8080.into(),
global: Box::new(files).into(),
content_type: content_type!(Text / Html; Charset = Utf8),
..Server::new(HandlerFn(say_hello))
}.run();
//Check if the server started successfully
match server_result {
Ok(_server) => {},
|
identifier_body
|
post.rs
|
#[macro_use]
extern crate rustful;
use std::io::{self, Read};
use std::fs::File;
use std::path::Path;
use std::borrow::Cow;
use std::error::Error;
use rustful::{Server, Context, Response, Log, Handler};
use rustful::context::body::ExtQueryBody;
use rustful::StatusCode::{InternalServerError, BadRequest};
fn
|
(mut context: Context, mut response: Response) {
let body = match context.body.read_query_body() {
Ok(body) => body,
Err(_) => {
//Oh no! Could not read the body
response.set_status(BadRequest);
return;
}
};
let files: &Files = if let Some(files) = context.global.get() {
files
} else {
//Oh no! Why is the global data not a File instance?!
context.log.error("the global data should be of the type `Files`, but it's not");
response.set_status(InternalServerError);
return;
};
//Format the name or use the cached form
let content = if let Some(name) = body.get("name") {
Cow::Owned(format!("<p>Hello, {}!</p>", name))
} else {
Cow::Borrowed(&files.form)
};
//Insert the content into the page and write it to the response
let complete_page = files.page.replace("{}", &content);
response.send(complete_page);
}
//Dodge an ICE, related to functions as handlers.
struct HandlerFn(fn(Context, Response));
impl Handler for HandlerFn {
fn handle_request(&self, context: Context, response: Response) {
self.0(context, response);
}
}
fn main() {
println!("Visit http://localhost:8080 to try this example.");
//Preload the files
let files = Files {
page: read_string("examples/post/page.html").unwrap(),
form: read_string("examples/post/form.html").unwrap()
};
//Handlers implements the Router trait, so it can be passed to the server as it is
let server_result = Server {
host: 8080.into(),
global: Box::new(files).into(),
content_type: content_type!(Text / Html; Charset = Utf8),
..Server::new(HandlerFn(say_hello))
}.run();
//Check if the server started successfully
match server_result {
Ok(_server) => {},
Err(e) => println!("could not start server: {}", e.description())
}
}
fn read_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
//Read file into a string
let mut string = String::new();
File::open(path).and_then(|mut f| f.read_to_string(&mut string)).map(|_| string)
}
//We want to store the files as strings
struct Files {
page: String,
form: String
}
|
say_hello
|
identifier_name
|
layer.rs
|
use crate::*;
#[derive(Clone, Debug)]
pub struct Layer {
crate neurons: Vec<Neuron>,
}
impl Layer {
pub fn new(neurons: Vec<Neuron>) -> Self {
assert!(!neurons.is_empty());
assert!(neurons
.iter()
.all(|neuron| neuron.weights.len() == neurons[0].weights.len()));
Self { neurons }
}
pub fn from_weights(
input_size: usize,
output_size: usize,
weights: &mut dyn Iterator<Item = f32>,
) -> Self {
let neurons = (0..output_size)
.map(|_| Neuron::from_weights(input_size, weights))
.collect();
Self::new(neurons)
}
pub fn random(rng: &mut dyn RngCore, input_neurons: usize, output_neurons: usize) -> Self {
let neurons = (0..output_neurons)
.map(|_| Neuron::random(rng, input_neurons))
.collect();
Self::new(neurons)
}
pub fn propagate(&self, inputs: Vec<f32>) -> Vec<f32> {
self.neurons
.iter()
.map(|neuron| neuron.propagate(&inputs))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
mod random {
use super::*;
use rand::SeedableRng;
use rand_chacha::ChaCha8Rng;
#[test]
fn test() {
let mut rng = ChaCha8Rng::from_seed(Default::default());
let layer = Layer::random(&mut rng, 3, 2);
let actual_biases: Vec<_> = layer.neurons.iter().map(|neuron| neuron.bias).collect();
let expected_biases = vec![-0.6255188, 0.5238807];
let actual_weights: Vec<_> = layer
.neurons
.iter()
.map(|neuron| neuron.weights.as_slice())
.collect();
let expected_weights: Vec<&[f32]> = vec![
&[0.67383957, 0.8181262, 0.26284897],
&[-0.53516835, 0.069369674, -0.7648182],
];
approx::assert_relative_eq!(actual_biases.as_slice(), expected_biases.as_slice());
approx::assert_relative_eq!(actual_weights.as_slice(), expected_weights.as_slice());
}
}
mod propagate {
use super::*;
#[test]
fn
|
() {
let neurons = (
Neuron::new(0.0, vec![0.1, 0.2, 0.3]),
Neuron::new(0.0, vec![0.4, 0.5, 0.6]),
);
let layer = Layer::new(vec![neurons.0.clone(), neurons.1.clone()]);
let inputs = &[-0.5, 0.0, 0.5];
let actual = layer.propagate(inputs.to_vec());
let expected = vec![neurons.0.propagate(inputs), neurons.1.propagate(inputs)];
approx::assert_relative_eq!(actual.as_slice(), expected.as_slice());
}
}
mod from_weights {
use super::*;
#[test]
fn test() {
let layer = Layer::from_weights(
3,
2,
&mut vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8].into_iter(),
);
let actual_biases: Vec<_> = layer.neurons.iter().map(|neuron| neuron.bias).collect();
let expected_biases = vec![0.1, 0.5];
let actual_weights: Vec<_> = layer
.neurons
.iter()
.map(|neuron| neuron.weights.as_slice())
.collect();
let expected_weights: Vec<&[f32]> = vec![&[0.2, 0.3, 0.4], &[0.6, 0.7, 0.8]];
approx::assert_relative_eq!(actual_biases.as_slice(), expected_biases.as_slice());
approx::assert_relative_eq!(actual_weights.as_slice(), expected_weights.as_slice());
}
}
}
|
test
|
identifier_name
|
layer.rs
|
use crate::*;
#[derive(Clone, Debug)]
pub struct Layer {
crate neurons: Vec<Neuron>,
}
impl Layer {
pub fn new(neurons: Vec<Neuron>) -> Self {
assert!(!neurons.is_empty());
assert!(neurons
.iter()
.all(|neuron| neuron.weights.len() == neurons[0].weights.len()));
Self { neurons }
}
pub fn from_weights(
input_size: usize,
output_size: usize,
weights: &mut dyn Iterator<Item = f32>,
) -> Self {
let neurons = (0..output_size)
.map(|_| Neuron::from_weights(input_size, weights))
.collect();
Self::new(neurons)
}
pub fn random(rng: &mut dyn RngCore, input_neurons: usize, output_neurons: usize) -> Self {
let neurons = (0..output_neurons)
.map(|_| Neuron::random(rng, input_neurons))
.collect();
Self::new(neurons)
}
pub fn propagate(&self, inputs: Vec<f32>) -> Vec<f32> {
self.neurons
.iter()
.map(|neuron| neuron.propagate(&inputs))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
mod random {
use super::*;
use rand::SeedableRng;
use rand_chacha::ChaCha8Rng;
#[test]
fn test() {
let mut rng = ChaCha8Rng::from_seed(Default::default());
let layer = Layer::random(&mut rng, 3, 2);
let actual_biases: Vec<_> = layer.neurons.iter().map(|neuron| neuron.bias).collect();
let expected_biases = vec![-0.6255188, 0.5238807];
let actual_weights: Vec<_> = layer
.neurons
.iter()
.map(|neuron| neuron.weights.as_slice())
.collect();
let expected_weights: Vec<&[f32]> = vec![
&[0.67383957, 0.8181262, 0.26284897],
&[-0.53516835, 0.069369674, -0.7648182],
];
approx::assert_relative_eq!(actual_biases.as_slice(), expected_biases.as_slice());
approx::assert_relative_eq!(actual_weights.as_slice(), expected_weights.as_slice());
}
|
#[test]
fn test() {
let neurons = (
Neuron::new(0.0, vec![0.1, 0.2, 0.3]),
Neuron::new(0.0, vec![0.4, 0.5, 0.6]),
);
let layer = Layer::new(vec![neurons.0.clone(), neurons.1.clone()]);
let inputs = &[-0.5, 0.0, 0.5];
let actual = layer.propagate(inputs.to_vec());
let expected = vec![neurons.0.propagate(inputs), neurons.1.propagate(inputs)];
approx::assert_relative_eq!(actual.as_slice(), expected.as_slice());
}
}
mod from_weights {
use super::*;
#[test]
fn test() {
let layer = Layer::from_weights(
3,
2,
&mut vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8].into_iter(),
);
let actual_biases: Vec<_> = layer.neurons.iter().map(|neuron| neuron.bias).collect();
let expected_biases = vec![0.1, 0.5];
let actual_weights: Vec<_> = layer
.neurons
.iter()
.map(|neuron| neuron.weights.as_slice())
.collect();
let expected_weights: Vec<&[f32]> = vec![&[0.2, 0.3, 0.4], &[0.6, 0.7, 0.8]];
approx::assert_relative_eq!(actual_biases.as_slice(), expected_biases.as_slice());
approx::assert_relative_eq!(actual_weights.as_slice(), expected_weights.as_slice());
}
}
}
|
}
mod propagate {
use super::*;
|
random_line_split
|
layer.rs
|
use crate::*;
#[derive(Clone, Debug)]
pub struct Layer {
crate neurons: Vec<Neuron>,
}
impl Layer {
pub fn new(neurons: Vec<Neuron>) -> Self {
assert!(!neurons.is_empty());
assert!(neurons
.iter()
.all(|neuron| neuron.weights.len() == neurons[0].weights.len()));
Self { neurons }
}
pub fn from_weights(
input_size: usize,
output_size: usize,
weights: &mut dyn Iterator<Item = f32>,
) -> Self {
let neurons = (0..output_size)
.map(|_| Neuron::from_weights(input_size, weights))
.collect();
Self::new(neurons)
}
pub fn random(rng: &mut dyn RngCore, input_neurons: usize, output_neurons: usize) -> Self {
let neurons = (0..output_neurons)
.map(|_| Neuron::random(rng, input_neurons))
.collect();
Self::new(neurons)
}
pub fn propagate(&self, inputs: Vec<f32>) -> Vec<f32>
|
}
#[cfg(test)]
mod tests {
use super::*;
mod random {
use super::*;
use rand::SeedableRng;
use rand_chacha::ChaCha8Rng;
#[test]
fn test() {
let mut rng = ChaCha8Rng::from_seed(Default::default());
let layer = Layer::random(&mut rng, 3, 2);
let actual_biases: Vec<_> = layer.neurons.iter().map(|neuron| neuron.bias).collect();
let expected_biases = vec![-0.6255188, 0.5238807];
let actual_weights: Vec<_> = layer
.neurons
.iter()
.map(|neuron| neuron.weights.as_slice())
.collect();
let expected_weights: Vec<&[f32]> = vec![
&[0.67383957, 0.8181262, 0.26284897],
&[-0.53516835, 0.069369674, -0.7648182],
];
approx::assert_relative_eq!(actual_biases.as_slice(), expected_biases.as_slice());
approx::assert_relative_eq!(actual_weights.as_slice(), expected_weights.as_slice());
}
}
mod propagate {
use super::*;
#[test]
fn test() {
let neurons = (
Neuron::new(0.0, vec![0.1, 0.2, 0.3]),
Neuron::new(0.0, vec![0.4, 0.5, 0.6]),
);
let layer = Layer::new(vec![neurons.0.clone(), neurons.1.clone()]);
let inputs = &[-0.5, 0.0, 0.5];
let actual = layer.propagate(inputs.to_vec());
let expected = vec![neurons.0.propagate(inputs), neurons.1.propagate(inputs)];
approx::assert_relative_eq!(actual.as_slice(), expected.as_slice());
}
}
mod from_weights {
use super::*;
#[test]
fn test() {
let layer = Layer::from_weights(
3,
2,
&mut vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8].into_iter(),
);
let actual_biases: Vec<_> = layer.neurons.iter().map(|neuron| neuron.bias).collect();
let expected_biases = vec![0.1, 0.5];
let actual_weights: Vec<_> = layer
.neurons
.iter()
.map(|neuron| neuron.weights.as_slice())
.collect();
let expected_weights: Vec<&[f32]> = vec![&[0.2, 0.3, 0.4], &[0.6, 0.7, 0.8]];
approx::assert_relative_eq!(actual_biases.as_slice(), expected_biases.as_slice());
approx::assert_relative_eq!(actual_weights.as_slice(), expected_weights.as_slice());
}
}
}
|
{
self.neurons
.iter()
.map(|neuron| neuron.propagate(&inputs))
.collect()
}
|
identifier_body
|
main.rs
|
extern crate clap;
extern crate intcode;
// Time Start: Thu, 05 Dec 2019 19:25:20 -0500
|
// Time Finish 1: Thu, 05 Dec 2019 20:59:57 -0500 (1 hour, 34 minutes, 37 seconds)
// Time Finish 2: Thu, 05 Dec 2019 21:11:50 -0500 (11 minutes, 53 seconds)
// Time Total: 1 hour, 46 minutes, 30 seconds
use clap::{Arg, App};
use intcode::Intcode;
fn main() {
let matches = App::new("Advent of Code 2019, Day 05")
.arg(Arg::with_name("FILE")
.help("Input file to process")
.index(1))
.get_matches();
let fname = String::from(matches.value_of("FILE").unwrap_or("05.in"));
let mut ic = Intcode::load(&fname);
ic.pipe(1);
ic.run();
println!("Step 1 diagnostic: {:?}", ic.cat());
let mut ic = Intcode::load(&fname);
ic.pipe(5);
ic.run();
println!("Step 2 diagnostic: {:?}", ic.cat());
}
|
random_line_split
|
|
main.rs
|
extern crate clap;
extern crate intcode;
// Time Start: Thu, 05 Dec 2019 19:25:20 -0500
// Time Finish 1: Thu, 05 Dec 2019 20:59:57 -0500 (1 hour, 34 minutes, 37 seconds)
// Time Finish 2: Thu, 05 Dec 2019 21:11:50 -0500 (11 minutes, 53 seconds)
// Time Total: 1 hour, 46 minutes, 30 seconds
use clap::{Arg, App};
use intcode::Intcode;
fn main()
|
{
let matches = App::new("Advent of Code 2019, Day 05")
.arg(Arg::with_name("FILE")
.help("Input file to process")
.index(1))
.get_matches();
let fname = String::from(matches.value_of("FILE").unwrap_or("05.in"));
let mut ic = Intcode::load(&fname);
ic.pipe(1);
ic.run();
println!("Step 1 diagnostic: {:?}", ic.cat());
let mut ic = Intcode::load(&fname);
ic.pipe(5);
ic.run();
println!("Step 2 diagnostic: {:?}", ic.cat());
}
|
identifier_body
|
|
main.rs
|
extern crate clap;
extern crate intcode;
// Time Start: Thu, 05 Dec 2019 19:25:20 -0500
// Time Finish 1: Thu, 05 Dec 2019 20:59:57 -0500 (1 hour, 34 minutes, 37 seconds)
// Time Finish 2: Thu, 05 Dec 2019 21:11:50 -0500 (11 minutes, 53 seconds)
// Time Total: 1 hour, 46 minutes, 30 seconds
use clap::{Arg, App};
use intcode::Intcode;
fn
|
() {
let matches = App::new("Advent of Code 2019, Day 05")
.arg(Arg::with_name("FILE")
.help("Input file to process")
.index(1))
.get_matches();
let fname = String::from(matches.value_of("FILE").unwrap_or("05.in"));
let mut ic = Intcode::load(&fname);
ic.pipe(1);
ic.run();
println!("Step 1 diagnostic: {:?}", ic.cat());
let mut ic = Intcode::load(&fname);
ic.pipe(5);
ic.run();
println!("Step 2 diagnostic: {:?}", ic.cat());
}
|
main
|
identifier_name
|
dissimilaroriginwindow.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::DissimilarOriginWindowBinding;
use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding::DissimilarOriginWindowMethods;
use dom::bindings::error::{Error, ErrorResult};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::str::DOMString;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::dissimilaroriginlocation::DissimilarOriginLocation;
use dom::globalscope::GlobalScope;
use dom::windowproxy::WindowProxy;
use dom_struct::dom_struct;
use ipc_channel::ipc;
use js::jsapi::{JSContext, HandleValue};
use js::jsval::{JSVal, UndefinedValue};
use msg::constellation_msg::PipelineId;
use script_traits::ScriptMsg;
use servo_url::ImmutableOrigin;
use servo_url::MutableOrigin;
use servo_url::ServoUrl;
/// Represents a dissimilar-origin `Window` that exists in another script thread.
///
/// Since the `Window` is in a different script thread, we cannot access it
/// directly, but some of its accessors (for example `window.parent`)
/// still need to function.
///
/// In `windowproxy.rs`, we create a custom window proxy for these windows,
/// that throws security exceptions for most accessors. This is not a replacement
/// for XOWs, but provides belt-and-braces security.
#[dom_struct]
pub struct DissimilarOriginWindow {
/// The global for this window.
globalscope: GlobalScope,
/// The window proxy for this window.
window_proxy: JS<WindowProxy>,
/// The location of this window, initialized lazily.
location: MutNullableJS<DissimilarOriginLocation>,
}
impl DissimilarOriginWindow {
#[allow(unsafe_code)]
pub fn new(
global_to_clone_from: &GlobalScope,
window_proxy: &WindowProxy,
) -> Root<Self> {
let cx = global_to_clone_from.get_cx();
// Any timer events fired on this window are ignored.
let (timer_event_chan, _) = ipc::channel().unwrap();
let win = box Self {
globalscope: GlobalScope::new_inherited(
PipelineId::new(),
global_to_clone_from.devtools_chan().cloned(),
global_to_clone_from.mem_profiler_chan().clone(),
global_to_clone_from.time_profiler_chan().clone(),
global_to_clone_from.script_to_constellation_chan().clone(),
global_to_clone_from.scheduler_chan().clone(),
global_to_clone_from.resource_threads().clone(),
timer_event_chan,
global_to_clone_from.origin().clone(),
// FIXME(nox): The microtask queue is probably not important
// here, but this whole DOM interface is a hack anyway.
global_to_clone_from.microtask_queue().clone(),
),
window_proxy: JS::from_ref(window_proxy),
location: Default::default(),
};
unsafe { DissimilarOriginWindowBinding::Wrap(cx, win) }
}
pub fn
|
(&self) -> &MutableOrigin {
self.upcast::<GlobalScope>().origin()
}
}
impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
// https://html.spec.whatwg.org/multipage/#dom-window
fn Window(&self) -> Root<WindowProxy> {
Root::from_ref(&*self.window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-self
fn Self_(&self) -> Root<WindowProxy> {
Root::from_ref(&*self.window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-frames
fn Frames(&self) -> Root<WindowProxy> {
Root::from_ref(&*self.window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-parent
fn GetParent(&self) -> Option<Root<WindowProxy>> {
// Steps 1-3.
if self.window_proxy.is_browsing_context_discarded() {
return None;
}
// Step 4.
if let Some(parent) = self.window_proxy.parent() {
return Some(Root::from_ref(parent));
}
// Step 5.
Some(Root::from_ref(&*self.window_proxy))
}
// https://html.spec.whatwg.org/multipage/#dom-top
fn GetTop(&self) -> Option<Root<WindowProxy>> {
// Steps 1-3.
if self.window_proxy.is_browsing_context_discarded() {
return None;
}
// Steps 4-5.
Some(Root::from_ref(self.window_proxy.top()))
}
// https://html.spec.whatwg.org/multipage/#dom-length
fn Length(&self) -> u32 {
// TODO: Implement x-origin length
0
}
// https://html.spec.whatwg.org/multipage/#dom-window-close
fn Close(&self) {
// TODO: Implement x-origin close
}
// https://html.spec.whatwg.org/multipage/#dom-window-closed
fn Closed(&self) -> bool {
// TODO: Implement x-origin close
false
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-window-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue, origin: DOMString) -> ErrorResult {
// Step 3-5.
let origin = match &origin[..] {
"*" => None,
"/" => {
// TODO: Should be the origin of the incumbent settings object.
None
},
url => match ServoUrl::parse(&url) {
Ok(url) => Some(url.origin()),
Err(_) => return Err(Error::Syntax),
}
};
// Step 1-2, 6-8.
// TODO(#12717): Should implement the `transfer` argument.
let data = StructuredCloneData::write(cx, message)?;
// Step 9.
self.post_message(origin, data);
Ok(())
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn Opener(&self, _: *mut JSContext) -> JSVal {
// TODO: Implement x-origin opener
UndefinedValue()
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn SetOpener(&self, _: *mut JSContext, _: HandleValue) {
// TODO: Implement x-origin opener
}
// https://html.spec.whatwg.org/multipage/#dom-window-blur
fn Blur(&self) {
// TODO: Implement x-origin blur
}
// https://html.spec.whatwg.org/multipage/#dom-focus
fn Focus(&self) {
// TODO: Implement x-origin focus
}
// https://html.spec.whatwg.org/multipage/#dom-location
fn Location(&self) -> Root<DissimilarOriginLocation> {
self.location.or_init(|| DissimilarOriginLocation::new(self))
}
}
impl DissimilarOriginWindow {
pub fn post_message(&self, origin: Option<ImmutableOrigin>, data: StructuredCloneData) {
let msg = ScriptMsg::PostMessage(self.window_proxy.browsing_context_id(),
origin,
data.move_to_arraybuffer());
let _ = self.upcast::<GlobalScope>().script_to_constellation_chan().send(msg);
}
}
|
origin
|
identifier_name
|
dissimilaroriginwindow.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::DissimilarOriginWindowBinding;
use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding::DissimilarOriginWindowMethods;
use dom::bindings::error::{Error, ErrorResult};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::str::DOMString;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::dissimilaroriginlocation::DissimilarOriginLocation;
use dom::globalscope::GlobalScope;
use dom::windowproxy::WindowProxy;
use dom_struct::dom_struct;
use ipc_channel::ipc;
use js::jsapi::{JSContext, HandleValue};
use js::jsval::{JSVal, UndefinedValue};
use msg::constellation_msg::PipelineId;
use script_traits::ScriptMsg;
use servo_url::ImmutableOrigin;
use servo_url::MutableOrigin;
use servo_url::ServoUrl;
/// Represents a dissimilar-origin `Window` that exists in another script thread.
///
/// Since the `Window` is in a different script thread, we cannot access it
/// directly, but some of its accessors (for example `window.parent`)
/// still need to function.
///
/// In `windowproxy.rs`, we create a custom window proxy for these windows,
/// that throws security exceptions for most accessors. This is not a replacement
/// for XOWs, but provides belt-and-braces security.
#[dom_struct]
pub struct DissimilarOriginWindow {
/// The global for this window.
globalscope: GlobalScope,
/// The window proxy for this window.
window_proxy: JS<WindowProxy>,
/// The location of this window, initialized lazily.
location: MutNullableJS<DissimilarOriginLocation>,
}
impl DissimilarOriginWindow {
#[allow(unsafe_code)]
pub fn new(
global_to_clone_from: &GlobalScope,
window_proxy: &WindowProxy,
) -> Root<Self> {
let cx = global_to_clone_from.get_cx();
// Any timer events fired on this window are ignored.
let (timer_event_chan, _) = ipc::channel().unwrap();
let win = box Self {
globalscope: GlobalScope::new_inherited(
PipelineId::new(),
global_to_clone_from.devtools_chan().cloned(),
global_to_clone_from.mem_profiler_chan().clone(),
global_to_clone_from.time_profiler_chan().clone(),
global_to_clone_from.script_to_constellation_chan().clone(),
global_to_clone_from.scheduler_chan().clone(),
global_to_clone_from.resource_threads().clone(),
timer_event_chan,
global_to_clone_from.origin().clone(),
// FIXME(nox): The microtask queue is probably not important
// here, but this whole DOM interface is a hack anyway.
global_to_clone_from.microtask_queue().clone(),
),
window_proxy: JS::from_ref(window_proxy),
location: Default::default(),
};
unsafe { DissimilarOriginWindowBinding::Wrap(cx, win) }
}
pub fn origin(&self) -> &MutableOrigin {
self.upcast::<GlobalScope>().origin()
}
}
impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
// https://html.spec.whatwg.org/multipage/#dom-window
fn Window(&self) -> Root<WindowProxy> {
Root::from_ref(&*self.window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-self
fn Self_(&self) -> Root<WindowProxy> {
Root::from_ref(&*self.window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-frames
fn Frames(&self) -> Root<WindowProxy> {
Root::from_ref(&*self.window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-parent
fn GetParent(&self) -> Option<Root<WindowProxy>> {
// Steps 1-3.
if self.window_proxy.is_browsing_context_discarded() {
return None;
}
// Step 4.
if let Some(parent) = self.window_proxy.parent() {
return Some(Root::from_ref(parent));
}
// Step 5.
Some(Root::from_ref(&*self.window_proxy))
}
// https://html.spec.whatwg.org/multipage/#dom-top
fn GetTop(&self) -> Option<Root<WindowProxy>> {
// Steps 1-3.
if self.window_proxy.is_browsing_context_discarded() {
return None;
}
// Steps 4-5.
Some(Root::from_ref(self.window_proxy.top()))
}
// https://html.spec.whatwg.org/multipage/#dom-length
fn Length(&self) -> u32 {
// TODO: Implement x-origin length
0
}
// https://html.spec.whatwg.org/multipage/#dom-window-close
fn Close(&self) {
// TODO: Implement x-origin close
}
// https://html.spec.whatwg.org/multipage/#dom-window-closed
fn Closed(&self) -> bool {
// TODO: Implement x-origin close
false
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-window-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue, origin: DOMString) -> ErrorResult {
// Step 3-5.
let origin = match &origin[..] {
"*" => None,
"/" => {
// TODO: Should be the origin of the incumbent settings object.
None
},
url => match ServoUrl::parse(&url) {
Ok(url) => Some(url.origin()),
Err(_) => return Err(Error::Syntax),
}
};
// Step 1-2, 6-8.
// TODO(#12717): Should implement the `transfer` argument.
let data = StructuredCloneData::write(cx, message)?;
// Step 9.
self.post_message(origin, data);
Ok(())
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn Opener(&self, _: *mut JSContext) -> JSVal {
// TODO: Implement x-origin opener
UndefinedValue()
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn SetOpener(&self, _: *mut JSContext, _: HandleValue) {
// TODO: Implement x-origin opener
}
// https://html.spec.whatwg.org/multipage/#dom-window-blur
fn Blur(&self)
|
// https://html.spec.whatwg.org/multipage/#dom-focus
fn Focus(&self) {
// TODO: Implement x-origin focus
}
// https://html.spec.whatwg.org/multipage/#dom-location
fn Location(&self) -> Root<DissimilarOriginLocation> {
self.location.or_init(|| DissimilarOriginLocation::new(self))
}
}
impl DissimilarOriginWindow {
pub fn post_message(&self, origin: Option<ImmutableOrigin>, data: StructuredCloneData) {
let msg = ScriptMsg::PostMessage(self.window_proxy.browsing_context_id(),
origin,
data.move_to_arraybuffer());
let _ = self.upcast::<GlobalScope>().script_to_constellation_chan().send(msg);
}
}
|
{
// TODO: Implement x-origin blur
}
|
identifier_body
|
dissimilaroriginwindow.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::DissimilarOriginWindowBinding;
use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding::DissimilarOriginWindowMethods;
use dom::bindings::error::{Error, ErrorResult};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableJS, Root};
use dom::bindings::str::DOMString;
use dom::bindings::structuredclone::StructuredCloneData;
use dom::dissimilaroriginlocation::DissimilarOriginLocation;
use dom::globalscope::GlobalScope;
use dom::windowproxy::WindowProxy;
use dom_struct::dom_struct;
use ipc_channel::ipc;
use js::jsapi::{JSContext, HandleValue};
use js::jsval::{JSVal, UndefinedValue};
use msg::constellation_msg::PipelineId;
use script_traits::ScriptMsg;
use servo_url::ImmutableOrigin;
use servo_url::MutableOrigin;
use servo_url::ServoUrl;
/// Represents a dissimilar-origin `Window` that exists in another script thread.
///
/// Since the `Window` is in a different script thread, we cannot access it
/// directly, but some of its accessors (for example `window.parent`)
/// still need to function.
///
/// In `windowproxy.rs`, we create a custom window proxy for these windows,
/// that throws security exceptions for most accessors. This is not a replacement
/// for XOWs, but provides belt-and-braces security.
#[dom_struct]
pub struct DissimilarOriginWindow {
/// The global for this window.
globalscope: GlobalScope,
/// The window proxy for this window.
window_proxy: JS<WindowProxy>,
/// The location of this window, initialized lazily.
location: MutNullableJS<DissimilarOriginLocation>,
}
impl DissimilarOriginWindow {
#[allow(unsafe_code)]
pub fn new(
global_to_clone_from: &GlobalScope,
window_proxy: &WindowProxy,
) -> Root<Self> {
let cx = global_to_clone_from.get_cx();
// Any timer events fired on this window are ignored.
let (timer_event_chan, _) = ipc::channel().unwrap();
let win = box Self {
globalscope: GlobalScope::new_inherited(
PipelineId::new(),
global_to_clone_from.devtools_chan().cloned(),
global_to_clone_from.mem_profiler_chan().clone(),
global_to_clone_from.time_profiler_chan().clone(),
global_to_clone_from.script_to_constellation_chan().clone(),
global_to_clone_from.scheduler_chan().clone(),
global_to_clone_from.resource_threads().clone(),
timer_event_chan,
global_to_clone_from.origin().clone(),
// FIXME(nox): The microtask queue is probably not important
// here, but this whole DOM interface is a hack anyway.
global_to_clone_from.microtask_queue().clone(),
),
window_proxy: JS::from_ref(window_proxy),
location: Default::default(),
};
unsafe { DissimilarOriginWindowBinding::Wrap(cx, win) }
}
pub fn origin(&self) -> &MutableOrigin {
self.upcast::<GlobalScope>().origin()
}
}
impl DissimilarOriginWindowMethods for DissimilarOriginWindow {
// https://html.spec.whatwg.org/multipage/#dom-window
fn Window(&self) -> Root<WindowProxy> {
Root::from_ref(&*self.window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-self
fn Self_(&self) -> Root<WindowProxy> {
Root::from_ref(&*self.window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-frames
fn Frames(&self) -> Root<WindowProxy> {
Root::from_ref(&*self.window_proxy)
}
// https://html.spec.whatwg.org/multipage/#dom-parent
fn GetParent(&self) -> Option<Root<WindowProxy>> {
// Steps 1-3.
if self.window_proxy.is_browsing_context_discarded() {
return None;
}
// Step 4.
if let Some(parent) = self.window_proxy.parent() {
return Some(Root::from_ref(parent));
}
// Step 5.
Some(Root::from_ref(&*self.window_proxy))
}
// https://html.spec.whatwg.org/multipage/#dom-top
fn GetTop(&self) -> Option<Root<WindowProxy>> {
// Steps 1-3.
if self.window_proxy.is_browsing_context_discarded() {
return None;
}
// Steps 4-5.
Some(Root::from_ref(self.window_proxy.top()))
}
// https://html.spec.whatwg.org/multipage/#dom-length
fn Length(&self) -> u32 {
// TODO: Implement x-origin length
0
}
// https://html.spec.whatwg.org/multipage/#dom-window-close
fn Close(&self) {
// TODO: Implement x-origin close
}
// https://html.spec.whatwg.org/multipage/#dom-window-closed
fn Closed(&self) -> bool {
// TODO: Implement x-origin close
false
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-window-postmessage
unsafe fn PostMessage(&self, cx: *mut JSContext, message: HandleValue, origin: DOMString) -> ErrorResult {
// Step 3-5.
let origin = match &origin[..] {
"*" => None,
"/" => {
// TODO: Should be the origin of the incumbent settings object.
None
},
url => match ServoUrl::parse(&url) {
Ok(url) => Some(url.origin()),
Err(_) => return Err(Error::Syntax),
}
};
// Step 1-2, 6-8.
// TODO(#12717): Should implement the `transfer` argument.
let data = StructuredCloneData::write(cx, message)?;
// Step 9.
self.post_message(origin, data);
Ok(())
}
|
unsafe fn Opener(&self, _: *mut JSContext) -> JSVal {
// TODO: Implement x-origin opener
UndefinedValue()
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener
unsafe fn SetOpener(&self, _: *mut JSContext, _: HandleValue) {
// TODO: Implement x-origin opener
}
// https://html.spec.whatwg.org/multipage/#dom-window-blur
fn Blur(&self) {
// TODO: Implement x-origin blur
}
// https://html.spec.whatwg.org/multipage/#dom-focus
fn Focus(&self) {
// TODO: Implement x-origin focus
}
// https://html.spec.whatwg.org/multipage/#dom-location
fn Location(&self) -> Root<DissimilarOriginLocation> {
self.location.or_init(|| DissimilarOriginLocation::new(self))
}
}
impl DissimilarOriginWindow {
pub fn post_message(&self, origin: Option<ImmutableOrigin>, data: StructuredCloneData) {
let msg = ScriptMsg::PostMessage(self.window_proxy.browsing_context_id(),
origin,
data.move_to_arraybuffer());
let _ = self.upcast::<GlobalScope>().script_to_constellation_chan().send(msg);
}
}
|
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-opener
|
random_line_split
|
solver.rs
|
use node::{OwnedNode, WeakNode};
use problem::{Problem, Constraint, Action};
use iter::{iter_col, ColumnIterator};
use cover::{try_cover_column, cover_column, uncover_column, try_cover_row, cover_row, uncover_row};
/// A `Solver` consumes a problem and computes solutions to the exact
/// cover problem.
pub struct Solver<A: Action, C: Constraint> {
problem: Problem<A, C>,
partial_solution: Vec<A>,
}
#[derive(Debug)]
struct FrameState {
iter: ColumnIterator,
column: OwnedNode,
row: Option<WeakNode>
}
impl Drop for FrameState {
fn drop(&mut self) {
// uncover the column
uncover_column(&self.column);
// uncover the row, if there is one
if let Some(ref node) = self.row {
uncover_row(node);
}
}
}
pub struct SolutionIterator<A: Action, C: Constraint> {
problem: Problem<A, C>,
partial: Vec<A>,
current_solution: Vec<A>,
iter_stack: Vec< FrameState >,
running: bool
}
impl<A: Action, C: Constraint> Drop for SolutionIterator<A, C> {
fn drop(&mut self) {
while!self.iter_stack.is_empty() {
self.iter_stack.pop();
}
}
}
impl <A: Action, C: Constraint> SolutionIterator<A, C> {
pub fn new(problem: Problem<A, C>) -> SolutionIterator<A, C> {
Self::from_solver(Solver::new(problem))
}
pub fn from_solver(solver: Solver<A, C>) -> SolutionIterator<A, C> {
SolutionIterator { problem: solver.problem,
current_solution: solver.partial_solution.clone(),
partial: solver.partial_solution,
iter_stack: Vec::new(),
running: false}
}
// If init returns a solution, that's the only solution
fn init(&mut self) -> Option<Vec<A>> {
let c = self.problem.choose_column();
match c {
None => Some(self.partial.clone()),
Some(c) => {
if c.borrow().get_count().unwrap() > 0 {
cover_column(&c);
self.iter_stack.push(FrameState { iter: iter_col(&c),
column: c.clone(),
row: None })
}
None
}
}
}
}
impl<A: Action, C: Constraint> Iterator for SolutionIterator<A, C> {
type Item = Vec<A>;
fn next(&mut self) -> Option<Vec<A>> {
if!self.running {
self.init();
self.running = true;
}
let mut s = None;
// At each step, take the next action in the iterator. Try to push a new state onto the column.
while!self.iter_stack.is_empty() {
let next_action = {
let n = self.iter_stack.len();
self.iter_stack[n - 1].iter.next()
};
// Take the next action.
if let Some(action_node) = next_action {
let a = self.problem.get_action(&action_node);
// {
// let sa = action_node.upgrade().unwrap();
// println!("trying action {}", sa.borrow().get_row().unwrap());
// }
// add the action the current solution
self.current_solution.push(a);
cover_row(&action_node);
// Choose a new constraint
let c = self.problem.choose_column();
match c {
// If there's no column to choose, we've found a result.
None => {
s = Some(self.current_solution.clone());
// We need to uncover the row ourselves,
// since we don't FrameState to do it for
// us.
uncover_row(&action_node);
self.current_solution.pop();
},
// Otherwise, check to see if there are still options left.
Some(c) => {
// If there are, push a new frame.
cover_column(&c);
self.iter_stack.push(FrameState { iter: iter_col(&c),
column: c.clone(),
row: Some(action_node) });
}
}
} else {
let r = self.iter_stack.pop();
if let Some(_) = r {
self.current_solution.pop();
}
}
// if we found a solution during the iteration, return it
if s.is_some() {
return s;
}
}
None
}
}
impl<A: Action, C: Constraint> Solver<A, C> {
pub fn new(problem: Problem<A, C>) -> Solver<A, C> {
Solver { problem: problem, partial_solution: Vec::new() }
}
pub fn problem(&self) -> &Problem<A, C> {
&self.problem
}
/// Specify that an action must be present in the final solution.
///
/// If no solution contains the set of required actions, then any
/// solution-returning method will return no solution, even if
/// another solution (that doesn't contain the require actions)
/// would otherewise exits.
pub fn require_action(&mut self, action: A) -> Result<(), String> {
match self.problem.require_row(action) {
Ok(_) => {
self.partial_solution.push(action);
Ok(())
},
Err(s) => {
Err(s)
}
}
}
/// Return a solution to the problem that includes any previously
/// required actions (set via `require_actions()`), if one
/// exists.
///
/// 'First' is an arbitrary qualifier; there are no guarantees
/// that, for instance, the lexographically smallest action-set is
/// returned. It is only guaranteed that, if at least one solution
/// exists, a solution will be returned.
pub fn first_solution(&self) -> Option<Vec<A>> {
let mut sol: Vec<A> = Vec::new();
if self.first_solution_aux(&mut sol){
Some(sol)
} else {
None
}
}
fn first_solution_aux(&self, solution: &mut Vec<A>) -> bool {
let (_tc, action_nodes) = {
let constraint = self.problem.choose_column();
if let None = constraint
|
let con = constraint.unwrap();
if con.borrow().get_count().unwrap() == 0 {
return false;
}
// pick an action for the constraint to satisfy
(try_cover_column(&con), iter_col(&con))
};
// Try that action, and return the solution to partial
// problem, if possible.
for action in action_nodes {
let a = self.problem.get_action(&action);
solution.push(a);
let _cover = try_cover_row(&action);
let sol = self.first_solution_aux(solution);
if sol {
return true;
}
solution.pop();
}
false
}
}
impl<A: Action, C: Constraint> IntoIterator for Solver<A, C> {
type Item = Vec<A>;
type IntoIter = SolutionIterator<A, C>;
fn into_iter(self) -> Self::IntoIter {
SolutionIterator::from_solver(self)
}
}
|
{
solution.extend_from_slice(&self.partial_solution);
return true;
}
|
conditional_block
|
solver.rs
|
use node::{OwnedNode, WeakNode};
use problem::{Problem, Constraint, Action};
use iter::{iter_col, ColumnIterator};
use cover::{try_cover_column, cover_column, uncover_column, try_cover_row, cover_row, uncover_row};
/// A `Solver` consumes a problem and computes solutions to the exact
/// cover problem.
pub struct Solver<A: Action, C: Constraint> {
problem: Problem<A, C>,
partial_solution: Vec<A>,
}
#[derive(Debug)]
struct FrameState {
iter: ColumnIterator,
column: OwnedNode,
row: Option<WeakNode>
}
impl Drop for FrameState {
fn drop(&mut self) {
// uncover the column
uncover_column(&self.column);
// uncover the row, if there is one
if let Some(ref node) = self.row {
uncover_row(node);
}
}
}
pub struct SolutionIterator<A: Action, C: Constraint> {
problem: Problem<A, C>,
partial: Vec<A>,
current_solution: Vec<A>,
iter_stack: Vec< FrameState >,
running: bool
}
impl<A: Action, C: Constraint> Drop for SolutionIterator<A, C> {
fn drop(&mut self) {
while!self.iter_stack.is_empty() {
self.iter_stack.pop();
}
}
}
impl <A: Action, C: Constraint> SolutionIterator<A, C> {
pub fn new(problem: Problem<A, C>) -> SolutionIterator<A, C> {
Self::from_solver(Solver::new(problem))
}
pub fn from_solver(solver: Solver<A, C>) -> SolutionIterator<A, C> {
SolutionIterator { problem: solver.problem,
current_solution: solver.partial_solution.clone(),
partial: solver.partial_solution,
iter_stack: Vec::new(),
running: false}
}
// If init returns a solution, that's the only solution
fn init(&mut self) -> Option<Vec<A>> {
let c = self.problem.choose_column();
match c {
None => Some(self.partial.clone()),
Some(c) => {
if c.borrow().get_count().unwrap() > 0 {
cover_column(&c);
self.iter_stack.push(FrameState { iter: iter_col(&c),
column: c.clone(),
row: None })
}
None
}
}
}
}
impl<A: Action, C: Constraint> Iterator for SolutionIterator<A, C> {
type Item = Vec<A>;
fn next(&mut self) -> Option<Vec<A>> {
if!self.running {
self.init();
self.running = true;
}
let mut s = None;
// At each step, take the next action in the iterator. Try to push a new state onto the column.
while!self.iter_stack.is_empty() {
let next_action = {
let n = self.iter_stack.len();
self.iter_stack[n - 1].iter.next()
};
// Take the next action.
if let Some(action_node) = next_action {
let a = self.problem.get_action(&action_node);
// {
// let sa = action_node.upgrade().unwrap();
// println!("trying action {}", sa.borrow().get_row().unwrap());
// }
// add the action the current solution
self.current_solution.push(a);
cover_row(&action_node);
// Choose a new constraint
let c = self.problem.choose_column();
match c {
// If there's no column to choose, we've found a result.
None => {
s = Some(self.current_solution.clone());
// We need to uncover the row ourselves,
// since we don't FrameState to do it for
// us.
uncover_row(&action_node);
self.current_solution.pop();
},
// Otherwise, check to see if there are still options left.
Some(c) => {
// If there are, push a new frame.
cover_column(&c);
self.iter_stack.push(FrameState { iter: iter_col(&c),
column: c.clone(),
row: Some(action_node) });
}
}
} else {
let r = self.iter_stack.pop();
if let Some(_) = r {
self.current_solution.pop();
}
}
// if we found a solution during the iteration, return it
if s.is_some() {
return s;
}
}
None
}
}
impl<A: Action, C: Constraint> Solver<A, C> {
pub fn new(problem: Problem<A, C>) -> Solver<A, C> {
Solver { problem: problem, partial_solution: Vec::new() }
}
pub fn problem(&self) -> &Problem<A, C> {
&self.problem
}
/// Specify that an action must be present in the final solution.
///
/// If no solution contains the set of required actions, then any
/// solution-returning method will return no solution, even if
/// another solution (that doesn't contain the require actions)
/// would otherewise exits.
pub fn require_action(&mut self, action: A) -> Result<(), String> {
match self.problem.require_row(action) {
Ok(_) => {
self.partial_solution.push(action);
Ok(())
},
Err(s) => {
Err(s)
}
}
}
/// Return a solution to the problem that includes any previously
/// required actions (set via `require_actions()`), if one
/// exists.
///
/// 'First' is an arbitrary qualifier; there are no guarantees
/// that, for instance, the lexographically smallest action-set is
/// returned. It is only guaranteed that, if at least one solution
/// exists, a solution will be returned.
pub fn first_solution(&self) -> Option<Vec<A>> {
let mut sol: Vec<A> = Vec::new();
if self.first_solution_aux(&mut sol){
Some(sol)
} else {
None
}
}
fn first_solution_aux(&self, solution: &mut Vec<A>) -> bool {
let (_tc, action_nodes) = {
let constraint = self.problem.choose_column();
if let None = constraint {
solution.extend_from_slice(&self.partial_solution);
return true;
}
let con = constraint.unwrap();
if con.borrow().get_count().unwrap() == 0 {
|
}
// pick an action for the constraint to satisfy
(try_cover_column(&con), iter_col(&con))
};
// Try that action, and return the solution to partial
// problem, if possible.
for action in action_nodes {
let a = self.problem.get_action(&action);
solution.push(a);
let _cover = try_cover_row(&action);
let sol = self.first_solution_aux(solution);
if sol {
return true;
}
solution.pop();
}
false
}
}
impl<A: Action, C: Constraint> IntoIterator for Solver<A, C> {
type Item = Vec<A>;
type IntoIter = SolutionIterator<A, C>;
fn into_iter(self) -> Self::IntoIter {
SolutionIterator::from_solver(self)
}
}
|
return false;
|
random_line_split
|
solver.rs
|
use node::{OwnedNode, WeakNode};
use problem::{Problem, Constraint, Action};
use iter::{iter_col, ColumnIterator};
use cover::{try_cover_column, cover_column, uncover_column, try_cover_row, cover_row, uncover_row};
/// A `Solver` consumes a problem and computes solutions to the exact
/// cover problem.
pub struct Solver<A: Action, C: Constraint> {
problem: Problem<A, C>,
partial_solution: Vec<A>,
}
#[derive(Debug)]
struct FrameState {
iter: ColumnIterator,
column: OwnedNode,
row: Option<WeakNode>
}
impl Drop for FrameState {
fn drop(&mut self) {
// uncover the column
uncover_column(&self.column);
// uncover the row, if there is one
if let Some(ref node) = self.row {
uncover_row(node);
}
}
}
pub struct SolutionIterator<A: Action, C: Constraint> {
problem: Problem<A, C>,
partial: Vec<A>,
current_solution: Vec<A>,
iter_stack: Vec< FrameState >,
running: bool
}
impl<A: Action, C: Constraint> Drop for SolutionIterator<A, C> {
fn drop(&mut self) {
while!self.iter_stack.is_empty() {
self.iter_stack.pop();
}
}
}
impl <A: Action, C: Constraint> SolutionIterator<A, C> {
pub fn new(problem: Problem<A, C>) -> SolutionIterator<A, C> {
Self::from_solver(Solver::new(problem))
}
pub fn from_solver(solver: Solver<A, C>) -> SolutionIterator<A, C> {
SolutionIterator { problem: solver.problem,
current_solution: solver.partial_solution.clone(),
partial: solver.partial_solution,
iter_stack: Vec::new(),
running: false}
}
// If init returns a solution, that's the only solution
fn init(&mut self) -> Option<Vec<A>> {
let c = self.problem.choose_column();
match c {
None => Some(self.partial.clone()),
Some(c) => {
if c.borrow().get_count().unwrap() > 0 {
cover_column(&c);
self.iter_stack.push(FrameState { iter: iter_col(&c),
column: c.clone(),
row: None })
}
None
}
}
}
}
impl<A: Action, C: Constraint> Iterator for SolutionIterator<A, C> {
type Item = Vec<A>;
fn next(&mut self) -> Option<Vec<A>> {
if!self.running {
self.init();
self.running = true;
}
let mut s = None;
// At each step, take the next action in the iterator. Try to push a new state onto the column.
while!self.iter_stack.is_empty() {
let next_action = {
let n = self.iter_stack.len();
self.iter_stack[n - 1].iter.next()
};
// Take the next action.
if let Some(action_node) = next_action {
let a = self.problem.get_action(&action_node);
// {
// let sa = action_node.upgrade().unwrap();
// println!("trying action {}", sa.borrow().get_row().unwrap());
// }
// add the action the current solution
self.current_solution.push(a);
cover_row(&action_node);
// Choose a new constraint
let c = self.problem.choose_column();
match c {
// If there's no column to choose, we've found a result.
None => {
s = Some(self.current_solution.clone());
// We need to uncover the row ourselves,
// since we don't FrameState to do it for
// us.
uncover_row(&action_node);
self.current_solution.pop();
},
// Otherwise, check to see if there are still options left.
Some(c) => {
// If there are, push a new frame.
cover_column(&c);
self.iter_stack.push(FrameState { iter: iter_col(&c),
column: c.clone(),
row: Some(action_node) });
}
}
} else {
let r = self.iter_stack.pop();
if let Some(_) = r {
self.current_solution.pop();
}
}
// if we found a solution during the iteration, return it
if s.is_some() {
return s;
}
}
None
}
}
impl<A: Action, C: Constraint> Solver<A, C> {
pub fn new(problem: Problem<A, C>) -> Solver<A, C> {
Solver { problem: problem, partial_solution: Vec::new() }
}
pub fn problem(&self) -> &Problem<A, C> {
&self.problem
}
/// Specify that an action must be present in the final solution.
///
/// If no solution contains the set of required actions, then any
/// solution-returning method will return no solution, even if
/// another solution (that doesn't contain the require actions)
/// would otherewise exits.
pub fn
|
(&mut self, action: A) -> Result<(), String> {
match self.problem.require_row(action) {
Ok(_) => {
self.partial_solution.push(action);
Ok(())
},
Err(s) => {
Err(s)
}
}
}
/// Return a solution to the problem that includes any previously
/// required actions (set via `require_actions()`), if one
/// exists.
///
/// 'First' is an arbitrary qualifier; there are no guarantees
/// that, for instance, the lexographically smallest action-set is
/// returned. It is only guaranteed that, if at least one solution
/// exists, a solution will be returned.
pub fn first_solution(&self) -> Option<Vec<A>> {
let mut sol: Vec<A> = Vec::new();
if self.first_solution_aux(&mut sol){
Some(sol)
} else {
None
}
}
fn first_solution_aux(&self, solution: &mut Vec<A>) -> bool {
let (_tc, action_nodes) = {
let constraint = self.problem.choose_column();
if let None = constraint {
solution.extend_from_slice(&self.partial_solution);
return true;
}
let con = constraint.unwrap();
if con.borrow().get_count().unwrap() == 0 {
return false;
}
// pick an action for the constraint to satisfy
(try_cover_column(&con), iter_col(&con))
};
// Try that action, and return the solution to partial
// problem, if possible.
for action in action_nodes {
let a = self.problem.get_action(&action);
solution.push(a);
let _cover = try_cover_row(&action);
let sol = self.first_solution_aux(solution);
if sol {
return true;
}
solution.pop();
}
false
}
}
impl<A: Action, C: Constraint> IntoIterator for Solver<A, C> {
type Item = Vec<A>;
type IntoIter = SolutionIterator<A, C>;
fn into_iter(self) -> Self::IntoIter {
SolutionIterator::from_solver(self)
}
}
|
require_action
|
identifier_name
|
solver.rs
|
use node::{OwnedNode, WeakNode};
use problem::{Problem, Constraint, Action};
use iter::{iter_col, ColumnIterator};
use cover::{try_cover_column, cover_column, uncover_column, try_cover_row, cover_row, uncover_row};
/// A `Solver` consumes a problem and computes solutions to the exact
/// cover problem.
pub struct Solver<A: Action, C: Constraint> {
problem: Problem<A, C>,
partial_solution: Vec<A>,
}
#[derive(Debug)]
struct FrameState {
iter: ColumnIterator,
column: OwnedNode,
row: Option<WeakNode>
}
impl Drop for FrameState {
fn drop(&mut self) {
// uncover the column
uncover_column(&self.column);
// uncover the row, if there is one
if let Some(ref node) = self.row {
uncover_row(node);
}
}
}
pub struct SolutionIterator<A: Action, C: Constraint> {
problem: Problem<A, C>,
partial: Vec<A>,
current_solution: Vec<A>,
iter_stack: Vec< FrameState >,
running: bool
}
impl<A: Action, C: Constraint> Drop for SolutionIterator<A, C> {
fn drop(&mut self) {
while!self.iter_stack.is_empty() {
self.iter_stack.pop();
}
}
}
impl <A: Action, C: Constraint> SolutionIterator<A, C> {
pub fn new(problem: Problem<A, C>) -> SolutionIterator<A, C> {
Self::from_solver(Solver::new(problem))
}
pub fn from_solver(solver: Solver<A, C>) -> SolutionIterator<A, C> {
SolutionIterator { problem: solver.problem,
current_solution: solver.partial_solution.clone(),
partial: solver.partial_solution,
iter_stack: Vec::new(),
running: false}
}
// If init returns a solution, that's the only solution
fn init(&mut self) -> Option<Vec<A>> {
let c = self.problem.choose_column();
match c {
None => Some(self.partial.clone()),
Some(c) => {
if c.borrow().get_count().unwrap() > 0 {
cover_column(&c);
self.iter_stack.push(FrameState { iter: iter_col(&c),
column: c.clone(),
row: None })
}
None
}
}
}
}
impl<A: Action, C: Constraint> Iterator for SolutionIterator<A, C> {
type Item = Vec<A>;
fn next(&mut self) -> Option<Vec<A>>
|
// println!("trying action {}", sa.borrow().get_row().unwrap());
// }
// add the action the current solution
self.current_solution.push(a);
cover_row(&action_node);
// Choose a new constraint
let c = self.problem.choose_column();
match c {
// If there's no column to choose, we've found a result.
None => {
s = Some(self.current_solution.clone());
// We need to uncover the row ourselves,
// since we don't FrameState to do it for
// us.
uncover_row(&action_node);
self.current_solution.pop();
},
// Otherwise, check to see if there are still options left.
Some(c) => {
// If there are, push a new frame.
cover_column(&c);
self.iter_stack.push(FrameState { iter: iter_col(&c),
column: c.clone(),
row: Some(action_node) });
}
}
} else {
let r = self.iter_stack.pop();
if let Some(_) = r {
self.current_solution.pop();
}
}
// if we found a solution during the iteration, return it
if s.is_some() {
return s;
}
}
None
}
}
impl<A: Action, C: Constraint> Solver<A, C> {
pub fn new(problem: Problem<A, C>) -> Solver<A, C> {
Solver { problem: problem, partial_solution: Vec::new() }
}
pub fn problem(&self) -> &Problem<A, C> {
&self.problem
}
/// Specify that an action must be present in the final solution.
///
/// If no solution contains the set of required actions, then any
/// solution-returning method will return no solution, even if
/// another solution (that doesn't contain the require actions)
/// would otherewise exits.
pub fn require_action(&mut self, action: A) -> Result<(), String> {
match self.problem.require_row(action) {
Ok(_) => {
self.partial_solution.push(action);
Ok(())
},
Err(s) => {
Err(s)
}
}
}
/// Return a solution to the problem that includes any previously
/// required actions (set via `require_actions()`), if one
/// exists.
///
/// 'First' is an arbitrary qualifier; there are no guarantees
/// that, for instance, the lexographically smallest action-set is
/// returned. It is only guaranteed that, if at least one solution
/// exists, a solution will be returned.
pub fn first_solution(&self) -> Option<Vec<A>> {
let mut sol: Vec<A> = Vec::new();
if self.first_solution_aux(&mut sol){
Some(sol)
} else {
None
}
}
fn first_solution_aux(&self, solution: &mut Vec<A>) -> bool {
let (_tc, action_nodes) = {
let constraint = self.problem.choose_column();
if let None = constraint {
solution.extend_from_slice(&self.partial_solution);
return true;
}
let con = constraint.unwrap();
if con.borrow().get_count().unwrap() == 0 {
return false;
}
// pick an action for the constraint to satisfy
(try_cover_column(&con), iter_col(&con))
};
// Try that action, and return the solution to partial
// problem, if possible.
for action in action_nodes {
let a = self.problem.get_action(&action);
solution.push(a);
let _cover = try_cover_row(&action);
let sol = self.first_solution_aux(solution);
if sol {
return true;
}
solution.pop();
}
false
}
}
impl<A: Action, C: Constraint> IntoIterator for Solver<A, C> {
type Item = Vec<A>;
type IntoIter = SolutionIterator<A, C>;
fn into_iter(self) -> Self::IntoIter {
SolutionIterator::from_solver(self)
}
}
|
{
if !self.running {
self.init();
self.running = true;
}
let mut s = None;
// At each step, take the next action in the iterator. Try to push a new state onto the column.
while !self.iter_stack.is_empty() {
let next_action = {
let n = self.iter_stack.len();
self.iter_stack[n - 1].iter.next()
};
// Take the next action.
if let Some(action_node) = next_action {
let a = self.problem.get_action(&action_node);
// {
// let sa = action_node.upgrade().unwrap();
|
identifier_body
|
build.rs
|
//! This tiny build script ensures that rocket is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version needed to compile Rocket.
const MIN_DATE: &'static str = "2017-07-09";
const MIN_VERSION: &'static str = "1.20.0-nightly";
fn main()
|
eprintln!("{}{}{}",
Blue.paint("See the getting started guide ("),
White.paint("https://rocket.rs/guide/getting-started/"),
Blue.paint(") for more information."));
panic!("Aborting compilation due to incompatible compiler.")
}
if!ok_version ||!ok_date {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a more recent version of rustc."));
eprintln!("{}{}{}",
Blue.paint("Use `"),
White.paint("rustup update"),
Blue.paint("` or your preferred method to update Rust."));
print_version_err(&*version, &*date);
panic!("Aborting compilation due to incompatible compiler.")
}
} else {
println!("cargo:warning={}", "Rocket was unable to check rustc compatibility.");
println!("cargo:warning={}", "Build may fail due to incompatible rustc version.");
}
}
|
{
let ok_channel = supports_features();
let ok_version = is_min_version(MIN_VERSION);
let ok_date = is_min_date(MIN_DATE);
let triple = (ok_channel, ok_version, ok_date);
let print_version_err = |version: &str, date: &str| {
eprintln!("{} {}. {} {}.",
White.paint("Installed version is:"),
Yellow.paint(format!("{} ({})", version, date)),
White.paint("Minimum required:"),
Yellow.paint(format!("{} ({})", MIN_VERSION, MIN_DATE)));
};
if let (Some(ok_channel), Some((ok_version, version)), Some((ok_date, date))) = triple {
if !ok_channel {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a nightly or dev version of Rust."));
print_version_err(&*version, &*date);
|
identifier_body
|
build.rs
|
//! This tiny build script ensures that rocket is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version needed to compile Rocket.
const MIN_DATE: &'static str = "2017-07-09";
const MIN_VERSION: &'static str = "1.20.0-nightly";
fn main() {
let ok_channel = supports_features();
let ok_version = is_min_version(MIN_VERSION);
let ok_date = is_min_date(MIN_DATE);
let triple = (ok_channel, ok_version, ok_date);
let print_version_err = |version: &str, date: &str| {
eprintln!("{} {}. {} {}.",
White.paint("Installed version is:"),
Yellow.paint(format!("{} ({})", version, date)),
White.paint("Minimum required:"),
Yellow.paint(format!("{} ({})", MIN_VERSION, MIN_DATE)));
};
if let (Some(ok_channel), Some((ok_version, version)), Some((ok_date, date))) = triple {
if!ok_channel
|
if!ok_version ||!ok_date {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a more recent version of rustc."));
eprintln!("{}{}{}",
Blue.paint("Use `"),
White.paint("rustup update"),
Blue.paint("` or your preferred method to update Rust."));
print_version_err(&*version, &*date);
panic!("Aborting compilation due to incompatible compiler.")
}
} else {
println!("cargo:warning={}", "Rocket was unable to check rustc compatibility.");
println!("cargo:warning={}", "Build may fail due to incompatible rustc version.");
}
}
|
{
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a nightly or dev version of Rust."));
print_version_err(&*version, &*date);
eprintln!("{}{}{}",
Blue.paint("See the getting started guide ("),
White.paint("https://rocket.rs/guide/getting-started/"),
Blue.paint(") for more information."));
panic!("Aborting compilation due to incompatible compiler.")
}
|
conditional_block
|
build.rs
|
//! This tiny build script ensures that rocket is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
|
fn main() {
let ok_channel = supports_features();
let ok_version = is_min_version(MIN_VERSION);
let ok_date = is_min_date(MIN_DATE);
let triple = (ok_channel, ok_version, ok_date);
let print_version_err = |version: &str, date: &str| {
eprintln!("{} {}. {} {}.",
White.paint("Installed version is:"),
Yellow.paint(format!("{} ({})", version, date)),
White.paint("Minimum required:"),
Yellow.paint(format!("{} ({})", MIN_VERSION, MIN_DATE)));
};
if let (Some(ok_channel), Some((ok_version, version)), Some((ok_date, date))) = triple {
if!ok_channel {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a nightly or dev version of Rust."));
print_version_err(&*version, &*date);
eprintln!("{}{}{}",
Blue.paint("See the getting started guide ("),
White.paint("https://rocket.rs/guide/getting-started/"),
Blue.paint(") for more information."));
panic!("Aborting compilation due to incompatible compiler.")
}
if!ok_version ||!ok_date {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a more recent version of rustc."));
eprintln!("{}{}{}",
Blue.paint("Use `"),
White.paint("rustup update"),
Blue.paint("` or your preferred method to update Rust."));
print_version_err(&*version, &*date);
panic!("Aborting compilation due to incompatible compiler.")
}
} else {
println!("cargo:warning={}", "Rocket was unable to check rustc compatibility.");
println!("cargo:warning={}", "Build may fail due to incompatible rustc version.");
}
}
|
// Specifies the minimum nightly version needed to compile Rocket.
const MIN_DATE: &'static str = "2017-07-09";
const MIN_VERSION: &'static str = "1.20.0-nightly";
|
random_line_split
|
build.rs
|
//! This tiny build script ensures that rocket is not compiled with an
//! incompatible version of rust.
extern crate yansi;
extern crate version_check;
use yansi::Color::{Red, Yellow, Blue, White};
use version_check::{supports_features, is_min_version, is_min_date};
// Specifies the minimum nightly version needed to compile Rocket.
const MIN_DATE: &'static str = "2017-07-09";
const MIN_VERSION: &'static str = "1.20.0-nightly";
fn
|
() {
let ok_channel = supports_features();
let ok_version = is_min_version(MIN_VERSION);
let ok_date = is_min_date(MIN_DATE);
let triple = (ok_channel, ok_version, ok_date);
let print_version_err = |version: &str, date: &str| {
eprintln!("{} {}. {} {}.",
White.paint("Installed version is:"),
Yellow.paint(format!("{} ({})", version, date)),
White.paint("Minimum required:"),
Yellow.paint(format!("{} ({})", MIN_VERSION, MIN_DATE)));
};
if let (Some(ok_channel), Some((ok_version, version)), Some((ok_date, date))) = triple {
if!ok_channel {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a nightly or dev version of Rust."));
print_version_err(&*version, &*date);
eprintln!("{}{}{}",
Blue.paint("See the getting started guide ("),
White.paint("https://rocket.rs/guide/getting-started/"),
Blue.paint(") for more information."));
panic!("Aborting compilation due to incompatible compiler.")
}
if!ok_version ||!ok_date {
eprintln!("{} {}",
Red.paint("Error:").bold(),
White.paint("Rocket requires a more recent version of rustc."));
eprintln!("{}{}{}",
Blue.paint("Use `"),
White.paint("rustup update"),
Blue.paint("` or your preferred method to update Rust."));
print_version_err(&*version, &*date);
panic!("Aborting compilation due to incompatible compiler.")
}
} else {
println!("cargo:warning={}", "Rocket was unable to check rustc compatibility.");
println!("cargo:warning={}", "Build may fail due to incompatible rustc version.");
}
}
|
main
|
identifier_name
|
net.rs
|
//! A trait to represent a stream
use std::io;
use std::io::{ErrorKind, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::fmt;
use std::fmt::{Debug, Formatter};
use openssl::ssl::{SslContext, SslStream};
/// A trait for the concept of opening a stream
pub trait Connector: Sized {
/// Opens a connection to the given IP socket
fn connect(addr: &SocketAddr, ssl_context: Option<&SslContext>) -> io::Result<Self>;
/// Upgrades to TLS connection
fn upgrade_tls(&mut self, ssl_context: &SslContext) -> io::Result<()>;
}
impl Connector for NetworkStream {
fn connect(addr: &SocketAddr, ssl_context: Option<&SslContext>) -> io::Result<NetworkStream> {
let tcp_stream = try!(TcpStream::connect(addr));
match ssl_context {
Some(context) => match SslStream::connect_generic(context, tcp_stream) {
Ok(stream) => Ok(NetworkStream::Ssl(stream)),
Err(err) => Err(io::Error::new(ErrorKind::Other, err)),
},
None => Ok(NetworkStream::Plain(tcp_stream)),
}
}
|
Ok(ssl_stream) => NetworkStream::Ssl(ssl_stream),
Err(err) => return Err(io::Error::new(ErrorKind::Other, err)),
},
NetworkStream::Ssl(stream) => NetworkStream::Ssl(stream),
};
Ok(())
}
}
/// Represents the different types of underlying network streams
pub enum NetworkStream {
/// Plain TCP
Plain(TcpStream),
/// SSL over TCP
Ssl(SslStream<TcpStream>),
}
impl Clone for NetworkStream {
#[inline]
fn clone(&self) -> NetworkStream {
match self {
&NetworkStream::Plain(ref stream) => NetworkStream::Plain(stream.try_clone().unwrap()),
&NetworkStream::Ssl(ref stream) => NetworkStream::Ssl(stream.try_clone().unwrap()),
}
}
}
impl Debug for NetworkStream {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("NetworkStream(_)")
}
}
impl Read for NetworkStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
NetworkStream::Plain(ref mut stream) => stream.read(buf),
NetworkStream::Ssl(ref mut stream) => stream.read(buf),
}
}
}
impl Write for NetworkStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
match *self {
NetworkStream::Plain(ref mut stream) => stream.write(msg),
NetworkStream::Ssl(ref mut stream) => stream.write(msg),
}
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
match *self {
NetworkStream::Plain(ref mut stream) => stream.flush(),
NetworkStream::Ssl(ref mut stream) => stream.flush(),
}
}
}
|
fn upgrade_tls(&mut self, ssl_context: &SslContext) -> io::Result<()> {
*self = match self.clone() {
NetworkStream::Plain(stream) => match SslStream::connect_generic(ssl_context, stream) {
|
random_line_split
|
net.rs
|
//! A trait to represent a stream
use std::io;
use std::io::{ErrorKind, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::fmt;
use std::fmt::{Debug, Formatter};
use openssl::ssl::{SslContext, SslStream};
/// A trait for the concept of opening a stream
pub trait Connector: Sized {
/// Opens a connection to the given IP socket
fn connect(addr: &SocketAddr, ssl_context: Option<&SslContext>) -> io::Result<Self>;
/// Upgrades to TLS connection
fn upgrade_tls(&mut self, ssl_context: &SslContext) -> io::Result<()>;
}
impl Connector for NetworkStream {
fn connect(addr: &SocketAddr, ssl_context: Option<&SslContext>) -> io::Result<NetworkStream> {
let tcp_stream = try!(TcpStream::connect(addr));
match ssl_context {
Some(context) => match SslStream::connect_generic(context, tcp_stream) {
Ok(stream) => Ok(NetworkStream::Ssl(stream)),
Err(err) => Err(io::Error::new(ErrorKind::Other, err)),
},
None => Ok(NetworkStream::Plain(tcp_stream)),
}
}
fn upgrade_tls(&mut self, ssl_context: &SslContext) -> io::Result<()> {
*self = match self.clone() {
NetworkStream::Plain(stream) => match SslStream::connect_generic(ssl_context, stream) {
Ok(ssl_stream) => NetworkStream::Ssl(ssl_stream),
Err(err) => return Err(io::Error::new(ErrorKind::Other, err)),
},
NetworkStream::Ssl(stream) => NetworkStream::Ssl(stream),
};
Ok(())
}
}
/// Represents the different types of underlying network streams
pub enum NetworkStream {
/// Plain TCP
Plain(TcpStream),
/// SSL over TCP
Ssl(SslStream<TcpStream>),
}
impl Clone for NetworkStream {
#[inline]
fn clone(&self) -> NetworkStream {
match self {
&NetworkStream::Plain(ref stream) => NetworkStream::Plain(stream.try_clone().unwrap()),
&NetworkStream::Ssl(ref stream) => NetworkStream::Ssl(stream.try_clone().unwrap()),
}
}
}
impl Debug for NetworkStream {
fn fmt(&self, f: &mut Formatter) -> fmt::Result
|
}
impl Read for NetworkStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
NetworkStream::Plain(ref mut stream) => stream.read(buf),
NetworkStream::Ssl(ref mut stream) => stream.read(buf),
}
}
}
impl Write for NetworkStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
match *self {
NetworkStream::Plain(ref mut stream) => stream.write(msg),
NetworkStream::Ssl(ref mut stream) => stream.write(msg),
}
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
match *self {
NetworkStream::Plain(ref mut stream) => stream.flush(),
NetworkStream::Ssl(ref mut stream) => stream.flush(),
}
}
}
|
{
f.write_str("NetworkStream(_)")
}
|
identifier_body
|
net.rs
|
//! A trait to represent a stream
use std::io;
use std::io::{ErrorKind, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::fmt;
use std::fmt::{Debug, Formatter};
use openssl::ssl::{SslContext, SslStream};
/// A trait for the concept of opening a stream
pub trait Connector: Sized {
/// Opens a connection to the given IP socket
fn connect(addr: &SocketAddr, ssl_context: Option<&SslContext>) -> io::Result<Self>;
/// Upgrades to TLS connection
fn upgrade_tls(&mut self, ssl_context: &SslContext) -> io::Result<()>;
}
impl Connector for NetworkStream {
fn
|
(addr: &SocketAddr, ssl_context: Option<&SslContext>) -> io::Result<NetworkStream> {
let tcp_stream = try!(TcpStream::connect(addr));
match ssl_context {
Some(context) => match SslStream::connect_generic(context, tcp_stream) {
Ok(stream) => Ok(NetworkStream::Ssl(stream)),
Err(err) => Err(io::Error::new(ErrorKind::Other, err)),
},
None => Ok(NetworkStream::Plain(tcp_stream)),
}
}
fn upgrade_tls(&mut self, ssl_context: &SslContext) -> io::Result<()> {
*self = match self.clone() {
NetworkStream::Plain(stream) => match SslStream::connect_generic(ssl_context, stream) {
Ok(ssl_stream) => NetworkStream::Ssl(ssl_stream),
Err(err) => return Err(io::Error::new(ErrorKind::Other, err)),
},
NetworkStream::Ssl(stream) => NetworkStream::Ssl(stream),
};
Ok(())
}
}
/// Represents the different types of underlying network streams
pub enum NetworkStream {
/// Plain TCP
Plain(TcpStream),
/// SSL over TCP
Ssl(SslStream<TcpStream>),
}
impl Clone for NetworkStream {
#[inline]
fn clone(&self) -> NetworkStream {
match self {
&NetworkStream::Plain(ref stream) => NetworkStream::Plain(stream.try_clone().unwrap()),
&NetworkStream::Ssl(ref stream) => NetworkStream::Ssl(stream.try_clone().unwrap()),
}
}
}
impl Debug for NetworkStream {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("NetworkStream(_)")
}
}
impl Read for NetworkStream {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
NetworkStream::Plain(ref mut stream) => stream.read(buf),
NetworkStream::Ssl(ref mut stream) => stream.read(buf),
}
}
}
impl Write for NetworkStream {
#[inline]
fn write(&mut self, msg: &[u8]) -> io::Result<usize> {
match *self {
NetworkStream::Plain(ref mut stream) => stream.write(msg),
NetworkStream::Ssl(ref mut stream) => stream.write(msg),
}
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
match *self {
NetworkStream::Plain(ref mut stream) => stream.flush(),
NetworkStream::Ssl(ref mut stream) => stream.flush(),
}
}
}
|
connect
|
identifier_name
|
object-safety-sized-self-generic-method.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that a trait is still object-safe (and usable) if it has
// generic methods so long as they require `Self : Sized`.
trait Counter {
fn tick(&mut self) -> u32;
fn with<F:FnOnce(u32)>(&self, f: F) where Self : Sized;
}
struct CCounter {
c: u32
}
impl Counter for CCounter {
fn tick(&mut self) -> u32 { self.c += 1; self.c }
fn with<F:FnOnce(u32)>(&self, f: F) { f(self.c); }
}
fn tick1<C:Counter>(c: &mut C) {
tick2(c);
c.with(|i| ());
}
fn tick2(c: &mut Counter) {
tick3(c);
}
fn tick3<C:?Sized+Counter>(c: &mut C) {
c.tick();
c.tick();
}
fn main()
|
{
let mut c = CCounter { c: 0 };
tick1(&mut c);
assert_eq!(c.tick(), 3);
}
|
identifier_body
|
|
object-safety-sized-self-generic-method.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that a trait is still object-safe (and usable) if it has
// generic methods so long as they require `Self : Sized`.
trait Counter {
fn tick(&mut self) -> u32;
fn with<F:FnOnce(u32)>(&self, f: F) where Self : Sized;
}
|
impl Counter for CCounter {
fn tick(&mut self) -> u32 { self.c += 1; self.c }
fn with<F:FnOnce(u32)>(&self, f: F) { f(self.c); }
}
fn tick1<C:Counter>(c: &mut C) {
tick2(c);
c.with(|i| ());
}
fn tick2(c: &mut Counter) {
tick3(c);
}
fn tick3<C:?Sized+Counter>(c: &mut C) {
c.tick();
c.tick();
}
fn main() {
let mut c = CCounter { c: 0 };
tick1(&mut c);
assert_eq!(c.tick(), 3);
}
|
struct CCounter {
c: u32
}
|
random_line_split
|
object-safety-sized-self-generic-method.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Check that a trait is still object-safe (and usable) if it has
// generic methods so long as they require `Self : Sized`.
trait Counter {
fn tick(&mut self) -> u32;
fn with<F:FnOnce(u32)>(&self, f: F) where Self : Sized;
}
struct CCounter {
c: u32
}
impl Counter for CCounter {
fn tick(&mut self) -> u32 { self.c += 1; self.c }
fn with<F:FnOnce(u32)>(&self, f: F) { f(self.c); }
}
fn tick1<C:Counter>(c: &mut C) {
tick2(c);
c.with(|i| ());
}
fn tick2(c: &mut Counter) {
tick3(c);
}
fn tick3<C:?Sized+Counter>(c: &mut C) {
c.tick();
c.tick();
}
fn
|
() {
let mut c = CCounter { c: 0 };
tick1(&mut c);
assert_eq!(c.tick(), 3);
}
|
main
|
identifier_name
|
remerge_source.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::common::{
find_source_config, find_target_bookmark_and_value, find_target_sync_config, MegarepoOp,
};
use anyhow::anyhow;
use context::CoreContext;
use megarepo_config::{MononokeMegarepoConfigs, Target};
use megarepo_error::MegarepoError;
use megarepo_mapping::SourceName;
use mononoke_api::{Mononoke, RepoContext};
use mononoke_types::ChangesetId;
use mutable_renames::MutableRenames;
use std::sync::Arc;
// remerge_source resets source in a given target to a specified commit.
// This is normally used for the cases where a bookmark had a non-fast
// forward move.
pub struct RemergeSource<'a> {
pub megarepo_configs: &'a Arc<dyn MononokeMegarepoConfigs>,
pub mononoke: &'a Arc<Mononoke>,
pub mutable_renames: &'a Arc<MutableRenames>,
}
impl<'a> MegarepoOp for RemergeSource<'a> {
fn mononoke(&self) -> &Arc<Mononoke> {
&self.mononoke
}
}
impl<'a> RemergeSource<'a> {
pub fn new(
megarepo_configs: &'a Arc<dyn MononokeMegarepoConfigs>,
mononoke: &'a Arc<Mononoke>,
mutable_renames: &'a Arc<MutableRenames>,
) -> Self {
Self {
megarepo_configs,
mononoke,
mutable_renames,
}
}
pub async fn run(
self,
ctx: &CoreContext,
source_name: &SourceName,
remerge_cs_id: ChangesetId,
message: Option<String>,
target: &Target,
target_location: ChangesetId,
) -> Result<ChangesetId, MegarepoError> {
let target_repo = self.find_repo_by_id(&ctx, target.repo_id).await?;
// Find the target config version and remapping state that was used to
// create the latest target commit.
let (_, actual_target_location) =
find_target_bookmark_and_value(&ctx, &target_repo, &target).await?;
// target doesn't point to the commit we expect - check
// if this method has already succeded and just immediately return the
// result if so.
if actual_target_location!= target_location {
return self
.check_if_this_method_has_already_succeeded(
ctx,
(target_location, actual_target_location),
source_name,
remerge_cs_id,
&target_repo,
)
.await;
}
let old_target_cs = &target_repo
.changeset(target_location)
.await?
.ok_or_else(|| {
MegarepoError::internal(anyhow!("programming error - target changeset not found!"))
})?;
let (old_remapping_state, config) = find_target_sync_config(
&ctx,
target_repo.blob_repo(),
target_location,
&target,
&self.megarepo_configs,
)
.await?;
let mut new_remapping_state = old_remapping_state.clone();
new_remapping_state.set_source_changeset(source_name.clone(), remerge_cs_id);
let source_config = find_source_config(&source_name, &config)?;
let moved_commits = self
.create_move_commits(
ctx,
target_repo.blob_repo(),
&vec![source_config.clone()],
new_remapping_state.get_all_latest_synced_changesets(),
self.mutable_renames,
)
.await?;
if moved_commits.len()!= 1
|
let move_commit = &moved_commits[0];
let move_commit = target_repo
.changeset(move_commit.1.moved.get_changeset_id())
.await?
.ok_or_else(|| {
MegarepoError::internal(anyhow!("programming error - moved changeset not found!"))
})?;
let current_source_cs = old_remapping_state
.get_latest_synced_changeset(&source_name)
.ok_or_else(|| {
anyhow!(
"Source {} does not exist in target {:?}",
source_name,
target
)
})?;
let remerged = self
.create_final_merge_commit_with_removals(
ctx,
&target_repo,
&[(source_config.clone(), *current_source_cs)],
message,
&Some(move_commit),
old_target_cs,
&new_remapping_state,
None, // new_version parameter. Since version doesn't change let's pass None here
)
.await?;
self.move_bookmark_conditionally(
ctx,
target_repo.blob_repo(),
target.bookmark.clone(),
(target_location, remerged),
)
.await?;
Ok(remerged)
}
async fn check_if_this_method_has_already_succeeded(
&self,
ctx: &CoreContext,
(expected_target_location, actual_target_location): (ChangesetId, ChangesetId),
source_name: &SourceName,
remerge_cs_id: ChangesetId,
repo: &RepoContext,
) -> Result<ChangesetId, MegarepoError> {
let parents = repo
.blob_repo()
.get_changeset_parents_by_bonsai(ctx.clone(), actual_target_location)
.await?;
if parents.len()!= 2 || parents[0]!= expected_target_location {
return Err(MegarepoError::request(anyhow!(
"Neither {} nor its first parent {:?} point to a target location {}",
actual_target_location,
parents.get(0),
expected_target_location,
)));
}
let state = self
.read_remapping_state_file(ctx, repo, actual_target_location)
.await?;
let latest_synced_for_source = state.get_latest_synced_changeset(source_name);
if state.get_latest_synced_changeset(source_name)!= Some(&remerge_cs_id) {
return Err(MegarepoError::request(anyhow!(
"Target cs {} has unexpected changeset {:?} for {}",
actual_target_location,
latest_synced_for_source,
source_name,
)));
}
return Ok(actual_target_location);
}
}
|
{
return Err(
anyhow!("unexpected number of move commits {}", moved_commits.len()).into(),
);
}
|
conditional_block
|
remerge_source.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
|
};
use anyhow::anyhow;
use context::CoreContext;
use megarepo_config::{MononokeMegarepoConfigs, Target};
use megarepo_error::MegarepoError;
use megarepo_mapping::SourceName;
use mononoke_api::{Mononoke, RepoContext};
use mononoke_types::ChangesetId;
use mutable_renames::MutableRenames;
use std::sync::Arc;
// remerge_source resets source in a given target to a specified commit.
// This is normally used for the cases where a bookmark had a non-fast
// forward move.
pub struct RemergeSource<'a> {
pub megarepo_configs: &'a Arc<dyn MononokeMegarepoConfigs>,
pub mononoke: &'a Arc<Mononoke>,
pub mutable_renames: &'a Arc<MutableRenames>,
}
impl<'a> MegarepoOp for RemergeSource<'a> {
fn mononoke(&self) -> &Arc<Mononoke> {
&self.mononoke
}
}
impl<'a> RemergeSource<'a> {
pub fn new(
megarepo_configs: &'a Arc<dyn MononokeMegarepoConfigs>,
mononoke: &'a Arc<Mononoke>,
mutable_renames: &'a Arc<MutableRenames>,
) -> Self {
Self {
megarepo_configs,
mononoke,
mutable_renames,
}
}
pub async fn run(
self,
ctx: &CoreContext,
source_name: &SourceName,
remerge_cs_id: ChangesetId,
message: Option<String>,
target: &Target,
target_location: ChangesetId,
) -> Result<ChangesetId, MegarepoError> {
let target_repo = self.find_repo_by_id(&ctx, target.repo_id).await?;
// Find the target config version and remapping state that was used to
// create the latest target commit.
let (_, actual_target_location) =
find_target_bookmark_and_value(&ctx, &target_repo, &target).await?;
// target doesn't point to the commit we expect - check
// if this method has already succeded and just immediately return the
// result if so.
if actual_target_location!= target_location {
return self
.check_if_this_method_has_already_succeeded(
ctx,
(target_location, actual_target_location),
source_name,
remerge_cs_id,
&target_repo,
)
.await;
}
let old_target_cs = &target_repo
.changeset(target_location)
.await?
.ok_or_else(|| {
MegarepoError::internal(anyhow!("programming error - target changeset not found!"))
})?;
let (old_remapping_state, config) = find_target_sync_config(
&ctx,
target_repo.blob_repo(),
target_location,
&target,
&self.megarepo_configs,
)
.await?;
let mut new_remapping_state = old_remapping_state.clone();
new_remapping_state.set_source_changeset(source_name.clone(), remerge_cs_id);
let source_config = find_source_config(&source_name, &config)?;
let moved_commits = self
.create_move_commits(
ctx,
target_repo.blob_repo(),
&vec![source_config.clone()],
new_remapping_state.get_all_latest_synced_changesets(),
self.mutable_renames,
)
.await?;
if moved_commits.len()!= 1 {
return Err(
anyhow!("unexpected number of move commits {}", moved_commits.len()).into(),
);
}
let move_commit = &moved_commits[0];
let move_commit = target_repo
.changeset(move_commit.1.moved.get_changeset_id())
.await?
.ok_or_else(|| {
MegarepoError::internal(anyhow!("programming error - moved changeset not found!"))
})?;
let current_source_cs = old_remapping_state
.get_latest_synced_changeset(&source_name)
.ok_or_else(|| {
anyhow!(
"Source {} does not exist in target {:?}",
source_name,
target
)
})?;
let remerged = self
.create_final_merge_commit_with_removals(
ctx,
&target_repo,
&[(source_config.clone(), *current_source_cs)],
message,
&Some(move_commit),
old_target_cs,
&new_remapping_state,
None, // new_version parameter. Since version doesn't change let's pass None here
)
.await?;
self.move_bookmark_conditionally(
ctx,
target_repo.blob_repo(),
target.bookmark.clone(),
(target_location, remerged),
)
.await?;
Ok(remerged)
}
async fn check_if_this_method_has_already_succeeded(
&self,
ctx: &CoreContext,
(expected_target_location, actual_target_location): (ChangesetId, ChangesetId),
source_name: &SourceName,
remerge_cs_id: ChangesetId,
repo: &RepoContext,
) -> Result<ChangesetId, MegarepoError> {
let parents = repo
.blob_repo()
.get_changeset_parents_by_bonsai(ctx.clone(), actual_target_location)
.await?;
if parents.len()!= 2 || parents[0]!= expected_target_location {
return Err(MegarepoError::request(anyhow!(
"Neither {} nor its first parent {:?} point to a target location {}",
actual_target_location,
parents.get(0),
expected_target_location,
)));
}
let state = self
.read_remapping_state_file(ctx, repo, actual_target_location)
.await?;
let latest_synced_for_source = state.get_latest_synced_changeset(source_name);
if state.get_latest_synced_changeset(source_name)!= Some(&remerge_cs_id) {
return Err(MegarepoError::request(anyhow!(
"Target cs {} has unexpected changeset {:?} for {}",
actual_target_location,
latest_synced_for_source,
source_name,
)));
}
return Ok(actual_target_location);
}
}
|
use crate::common::{
find_source_config, find_target_bookmark_and_value, find_target_sync_config, MegarepoOp,
|
random_line_split
|
remerge_source.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::common::{
find_source_config, find_target_bookmark_and_value, find_target_sync_config, MegarepoOp,
};
use anyhow::anyhow;
use context::CoreContext;
use megarepo_config::{MononokeMegarepoConfigs, Target};
use megarepo_error::MegarepoError;
use megarepo_mapping::SourceName;
use mononoke_api::{Mononoke, RepoContext};
use mononoke_types::ChangesetId;
use mutable_renames::MutableRenames;
use std::sync::Arc;
// remerge_source resets source in a given target to a specified commit.
// This is normally used for the cases where a bookmark had a non-fast
// forward move.
pub struct RemergeSource<'a> {
pub megarepo_configs: &'a Arc<dyn MononokeMegarepoConfigs>,
pub mononoke: &'a Arc<Mononoke>,
pub mutable_renames: &'a Arc<MutableRenames>,
}
impl<'a> MegarepoOp for RemergeSource<'a> {
fn mononoke(&self) -> &Arc<Mononoke>
|
}
impl<'a> RemergeSource<'a> {
pub fn new(
megarepo_configs: &'a Arc<dyn MononokeMegarepoConfigs>,
mononoke: &'a Arc<Mononoke>,
mutable_renames: &'a Arc<MutableRenames>,
) -> Self {
Self {
megarepo_configs,
mononoke,
mutable_renames,
}
}
pub async fn run(
self,
ctx: &CoreContext,
source_name: &SourceName,
remerge_cs_id: ChangesetId,
message: Option<String>,
target: &Target,
target_location: ChangesetId,
) -> Result<ChangesetId, MegarepoError> {
let target_repo = self.find_repo_by_id(&ctx, target.repo_id).await?;
// Find the target config version and remapping state that was used to
// create the latest target commit.
let (_, actual_target_location) =
find_target_bookmark_and_value(&ctx, &target_repo, &target).await?;
// target doesn't point to the commit we expect - check
// if this method has already succeded and just immediately return the
// result if so.
if actual_target_location!= target_location {
return self
.check_if_this_method_has_already_succeeded(
ctx,
(target_location, actual_target_location),
source_name,
remerge_cs_id,
&target_repo,
)
.await;
}
let old_target_cs = &target_repo
.changeset(target_location)
.await?
.ok_or_else(|| {
MegarepoError::internal(anyhow!("programming error - target changeset not found!"))
})?;
let (old_remapping_state, config) = find_target_sync_config(
&ctx,
target_repo.blob_repo(),
target_location,
&target,
&self.megarepo_configs,
)
.await?;
let mut new_remapping_state = old_remapping_state.clone();
new_remapping_state.set_source_changeset(source_name.clone(), remerge_cs_id);
let source_config = find_source_config(&source_name, &config)?;
let moved_commits = self
.create_move_commits(
ctx,
target_repo.blob_repo(),
&vec![source_config.clone()],
new_remapping_state.get_all_latest_synced_changesets(),
self.mutable_renames,
)
.await?;
if moved_commits.len()!= 1 {
return Err(
anyhow!("unexpected number of move commits {}", moved_commits.len()).into(),
);
}
let move_commit = &moved_commits[0];
let move_commit = target_repo
.changeset(move_commit.1.moved.get_changeset_id())
.await?
.ok_or_else(|| {
MegarepoError::internal(anyhow!("programming error - moved changeset not found!"))
})?;
let current_source_cs = old_remapping_state
.get_latest_synced_changeset(&source_name)
.ok_or_else(|| {
anyhow!(
"Source {} does not exist in target {:?}",
source_name,
target
)
})?;
let remerged = self
.create_final_merge_commit_with_removals(
ctx,
&target_repo,
&[(source_config.clone(), *current_source_cs)],
message,
&Some(move_commit),
old_target_cs,
&new_remapping_state,
None, // new_version parameter. Since version doesn't change let's pass None here
)
.await?;
self.move_bookmark_conditionally(
ctx,
target_repo.blob_repo(),
target.bookmark.clone(),
(target_location, remerged),
)
.await?;
Ok(remerged)
}
async fn check_if_this_method_has_already_succeeded(
&self,
ctx: &CoreContext,
(expected_target_location, actual_target_location): (ChangesetId, ChangesetId),
source_name: &SourceName,
remerge_cs_id: ChangesetId,
repo: &RepoContext,
) -> Result<ChangesetId, MegarepoError> {
let parents = repo
.blob_repo()
.get_changeset_parents_by_bonsai(ctx.clone(), actual_target_location)
.await?;
if parents.len()!= 2 || parents[0]!= expected_target_location {
return Err(MegarepoError::request(anyhow!(
"Neither {} nor its first parent {:?} point to a target location {}",
actual_target_location,
parents.get(0),
expected_target_location,
)));
}
let state = self
.read_remapping_state_file(ctx, repo, actual_target_location)
.await?;
let latest_synced_for_source = state.get_latest_synced_changeset(source_name);
if state.get_latest_synced_changeset(source_name)!= Some(&remerge_cs_id) {
return Err(MegarepoError::request(anyhow!(
"Target cs {} has unexpected changeset {:?} for {}",
actual_target_location,
latest_synced_for_source,
source_name,
)));
}
return Ok(actual_target_location);
}
}
|
{
&self.mononoke
}
|
identifier_body
|
remerge_source.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use crate::common::{
find_source_config, find_target_bookmark_and_value, find_target_sync_config, MegarepoOp,
};
use anyhow::anyhow;
use context::CoreContext;
use megarepo_config::{MononokeMegarepoConfigs, Target};
use megarepo_error::MegarepoError;
use megarepo_mapping::SourceName;
use mononoke_api::{Mononoke, RepoContext};
use mononoke_types::ChangesetId;
use mutable_renames::MutableRenames;
use std::sync::Arc;
// remerge_source resets source in a given target to a specified commit.
// This is normally used for the cases where a bookmark had a non-fast
// forward move.
pub struct RemergeSource<'a> {
pub megarepo_configs: &'a Arc<dyn MononokeMegarepoConfigs>,
pub mononoke: &'a Arc<Mononoke>,
pub mutable_renames: &'a Arc<MutableRenames>,
}
impl<'a> MegarepoOp for RemergeSource<'a> {
fn mononoke(&self) -> &Arc<Mononoke> {
&self.mononoke
}
}
impl<'a> RemergeSource<'a> {
pub fn
|
(
megarepo_configs: &'a Arc<dyn MononokeMegarepoConfigs>,
mononoke: &'a Arc<Mononoke>,
mutable_renames: &'a Arc<MutableRenames>,
) -> Self {
Self {
megarepo_configs,
mononoke,
mutable_renames,
}
}
pub async fn run(
self,
ctx: &CoreContext,
source_name: &SourceName,
remerge_cs_id: ChangesetId,
message: Option<String>,
target: &Target,
target_location: ChangesetId,
) -> Result<ChangesetId, MegarepoError> {
let target_repo = self.find_repo_by_id(&ctx, target.repo_id).await?;
// Find the target config version and remapping state that was used to
// create the latest target commit.
let (_, actual_target_location) =
find_target_bookmark_and_value(&ctx, &target_repo, &target).await?;
// target doesn't point to the commit we expect - check
// if this method has already succeded and just immediately return the
// result if so.
if actual_target_location!= target_location {
return self
.check_if_this_method_has_already_succeeded(
ctx,
(target_location, actual_target_location),
source_name,
remerge_cs_id,
&target_repo,
)
.await;
}
let old_target_cs = &target_repo
.changeset(target_location)
.await?
.ok_or_else(|| {
MegarepoError::internal(anyhow!("programming error - target changeset not found!"))
})?;
let (old_remapping_state, config) = find_target_sync_config(
&ctx,
target_repo.blob_repo(),
target_location,
&target,
&self.megarepo_configs,
)
.await?;
let mut new_remapping_state = old_remapping_state.clone();
new_remapping_state.set_source_changeset(source_name.clone(), remerge_cs_id);
let source_config = find_source_config(&source_name, &config)?;
let moved_commits = self
.create_move_commits(
ctx,
target_repo.blob_repo(),
&vec![source_config.clone()],
new_remapping_state.get_all_latest_synced_changesets(),
self.mutable_renames,
)
.await?;
if moved_commits.len()!= 1 {
return Err(
anyhow!("unexpected number of move commits {}", moved_commits.len()).into(),
);
}
let move_commit = &moved_commits[0];
let move_commit = target_repo
.changeset(move_commit.1.moved.get_changeset_id())
.await?
.ok_or_else(|| {
MegarepoError::internal(anyhow!("programming error - moved changeset not found!"))
})?;
let current_source_cs = old_remapping_state
.get_latest_synced_changeset(&source_name)
.ok_or_else(|| {
anyhow!(
"Source {} does not exist in target {:?}",
source_name,
target
)
})?;
let remerged = self
.create_final_merge_commit_with_removals(
ctx,
&target_repo,
&[(source_config.clone(), *current_source_cs)],
message,
&Some(move_commit),
old_target_cs,
&new_remapping_state,
None, // new_version parameter. Since version doesn't change let's pass None here
)
.await?;
self.move_bookmark_conditionally(
ctx,
target_repo.blob_repo(),
target.bookmark.clone(),
(target_location, remerged),
)
.await?;
Ok(remerged)
}
async fn check_if_this_method_has_already_succeeded(
&self,
ctx: &CoreContext,
(expected_target_location, actual_target_location): (ChangesetId, ChangesetId),
source_name: &SourceName,
remerge_cs_id: ChangesetId,
repo: &RepoContext,
) -> Result<ChangesetId, MegarepoError> {
let parents = repo
.blob_repo()
.get_changeset_parents_by_bonsai(ctx.clone(), actual_target_location)
.await?;
if parents.len()!= 2 || parents[0]!= expected_target_location {
return Err(MegarepoError::request(anyhow!(
"Neither {} nor its first parent {:?} point to a target location {}",
actual_target_location,
parents.get(0),
expected_target_location,
)));
}
let state = self
.read_remapping_state_file(ctx, repo, actual_target_location)
.await?;
let latest_synced_for_source = state.get_latest_synced_changeset(source_name);
if state.get_latest_synced_changeset(source_name)!= Some(&remerge_cs_id) {
return Err(MegarepoError::request(anyhow!(
"Target cs {} has unexpected changeset {:?} for {}",
actual_target_location,
latest_synced_for_source,
source_name,
)));
}
return Ok(actual_target_location);
}
}
|
new
|
identifier_name
|
partial_eq.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use deriving::{path_local, path_std};
use deriving::generic::*;
use deriving::generic::ty::*;
use syntax::ast::{BinOpKind, Expr, MetaItem};
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder;
use syntax::ptr::P;
use syntax::symbol::Symbol;
use syntax_pos::Span;
pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable)) {
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
fn cs_op(cx: &mut ExtCtxt,
span: Span,
substr: &Substructure,
op: BinOpKind,
combiner: BinOpKind,
base: bool)
-> P<Expr>
{
let op = |cx: &mut ExtCtxt, span: Span, self_f: P<Expr>, other_fs: &[P<Expr>]| {
let other_f = match (other_fs.len(), other_fs.get(0)) {
(1, Some(o_f)) => o_f,
_ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialEq)`"),
};
cx.expr_binary(span, op, self_f, other_f.clone())
};
cs_fold1(true, // use foldl
|cx, span, subexpr, self_f, other_fs| {
let eq = op(cx, span, self_f, other_fs);
cx.expr_binary(span, combiner, subexpr, eq)
},
|cx, args| {
match args {
Some((span, self_f, other_fs)) => {
// Special-case the base case to generate cleaner code.
op(cx, span, self_f, other_fs)
}
None => cx.expr_bool(span, base),
}
},
Box::new(|cx, span, _, _| cx.expr_bool(span,!base)),
cx,
span,
substr)
}
fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
cs_op(cx, span, substr, BinOpKind::Eq, BinOpKind::And, true)
}
fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr>
|
macro_rules! md {
($name:expr, $f:ident) => { {
let inline = cx.meta_word(span, Symbol::intern("inline"));
let attrs = vec![cx.attribute(span, inline)];
MethodDef {
name: $name,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec![(borrowed_self(), "other")],
ret_ty: Literal(path_local!(bool)),
attributes: attrs,
is_unsafe: false,
unify_fieldless_variants: true,
combine_substructure: combine_substructure(Box::new(|a, b, c| {
$f(a, b, c)
}))
}
} }
}
// avoid defining `ne` if we can
// c-like enums, enums without any fields and structs without fields
// can safely define only `eq`.
let mut methods = vec![md!("eq", cs_eq)];
if!is_type_without_fields(item) {
methods.push(md!("ne", cs_ne));
}
let trait_def = TraitDef {
span,
attributes: Vec::new(),
path: path_std!(cx, cmp::PartialEq),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
supports_unions: false,
methods,
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
|
{
cs_op(cx, span, substr, BinOpKind::Ne, BinOpKind::Or, false)
}
|
identifier_body
|
partial_eq.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use deriving::{path_local, path_std};
use deriving::generic::*;
use deriving::generic::ty::*;
use syntax::ast::{BinOpKind, Expr, MetaItem};
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder;
use syntax::ptr::P;
use syntax::symbol::Symbol;
use syntax_pos::Span;
pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable)) {
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
fn
|
(cx: &mut ExtCtxt,
span: Span,
substr: &Substructure,
op: BinOpKind,
combiner: BinOpKind,
base: bool)
-> P<Expr>
{
let op = |cx: &mut ExtCtxt, span: Span, self_f: P<Expr>, other_fs: &[P<Expr>]| {
let other_f = match (other_fs.len(), other_fs.get(0)) {
(1, Some(o_f)) => o_f,
_ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialEq)`"),
};
cx.expr_binary(span, op, self_f, other_f.clone())
};
cs_fold1(true, // use foldl
|cx, span, subexpr, self_f, other_fs| {
let eq = op(cx, span, self_f, other_fs);
cx.expr_binary(span, combiner, subexpr, eq)
},
|cx, args| {
match args {
Some((span, self_f, other_fs)) => {
// Special-case the base case to generate cleaner code.
op(cx, span, self_f, other_fs)
}
None => cx.expr_bool(span, base),
}
},
Box::new(|cx, span, _, _| cx.expr_bool(span,!base)),
cx,
span,
substr)
}
fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
cs_op(cx, span, substr, BinOpKind::Eq, BinOpKind::And, true)
}
fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
cs_op(cx, span, substr, BinOpKind::Ne, BinOpKind::Or, false)
}
macro_rules! md {
($name:expr, $f:ident) => { {
let inline = cx.meta_word(span, Symbol::intern("inline"));
let attrs = vec![cx.attribute(span, inline)];
MethodDef {
name: $name,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec![(borrowed_self(), "other")],
ret_ty: Literal(path_local!(bool)),
attributes: attrs,
is_unsafe: false,
unify_fieldless_variants: true,
combine_substructure: combine_substructure(Box::new(|a, b, c| {
$f(a, b, c)
}))
}
} }
}
// avoid defining `ne` if we can
// c-like enums, enums without any fields and structs without fields
// can safely define only `eq`.
let mut methods = vec![md!("eq", cs_eq)];
if!is_type_without_fields(item) {
methods.push(md!("ne", cs_ne));
}
let trait_def = TraitDef {
span,
attributes: Vec::new(),
path: path_std!(cx, cmp::PartialEq),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
supports_unions: false,
methods,
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
|
cs_op
|
identifier_name
|
partial_eq.rs
|
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use deriving::{path_local, path_std};
use deriving::generic::*;
use deriving::generic::ty::*;
use syntax::ast::{BinOpKind, Expr, MetaItem};
use syntax::ext::base::{Annotatable, ExtCtxt};
use syntax::ext::build::AstBuilder;
use syntax::ptr::P;
use syntax::symbol::Symbol;
use syntax_pos::Span;
pub fn expand_deriving_partial_eq(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable)) {
// structures are equal if all fields are equal, and non equal, if
// any fields are not equal or if the enum variants are different
fn cs_op(cx: &mut ExtCtxt,
span: Span,
substr: &Substructure,
op: BinOpKind,
combiner: BinOpKind,
base: bool)
-> P<Expr>
{
let op = |cx: &mut ExtCtxt, span: Span, self_f: P<Expr>, other_fs: &[P<Expr>]| {
let other_f = match (other_fs.len(), other_fs.get(0)) {
(1, Some(o_f)) => o_f,
|
_ => cx.span_bug(span, "not exactly 2 arguments in `derive(PartialEq)`"),
};
cx.expr_binary(span, op, self_f, other_f.clone())
};
cs_fold1(true, // use foldl
|cx, span, subexpr, self_f, other_fs| {
let eq = op(cx, span, self_f, other_fs);
cx.expr_binary(span, combiner, subexpr, eq)
},
|cx, args| {
match args {
Some((span, self_f, other_fs)) => {
// Special-case the base case to generate cleaner code.
op(cx, span, self_f, other_fs)
}
None => cx.expr_bool(span, base),
}
},
Box::new(|cx, span, _, _| cx.expr_bool(span,!base)),
cx,
span,
substr)
}
fn cs_eq(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
cs_op(cx, span, substr, BinOpKind::Eq, BinOpKind::And, true)
}
fn cs_ne(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
cs_op(cx, span, substr, BinOpKind::Ne, BinOpKind::Or, false)
}
macro_rules! md {
($name:expr, $f:ident) => { {
let inline = cx.meta_word(span, Symbol::intern("inline"));
let attrs = vec![cx.attribute(span, inline)];
MethodDef {
name: $name,
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: vec![(borrowed_self(), "other")],
ret_ty: Literal(path_local!(bool)),
attributes: attrs,
is_unsafe: false,
unify_fieldless_variants: true,
combine_substructure: combine_substructure(Box::new(|a, b, c| {
$f(a, b, c)
}))
}
} }
}
// avoid defining `ne` if we can
// c-like enums, enums without any fields and structs without fields
// can safely define only `eq`.
let mut methods = vec![md!("eq", cs_eq)];
if!is_type_without_fields(item) {
methods.push(md!("ne", cs_ne));
}
let trait_def = TraitDef {
span,
attributes: Vec::new(),
path: path_std!(cx, cmp::PartialEq),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
supports_unions: false,
methods,
associated_types: Vec::new(),
};
trait_def.expand(cx, mitem, item, push)
}
|
random_line_split
|
|
mod.rs
|
extern crate discotech;
#[macro_use]
extern crate log;
extern crate log4rs;
use discotech::{Serverset, DiscoConfig, read_config};
use std::env;
fn initialize_logging() {
let root = log4rs::config::Root::builder(log::LogLevelFilter::Debug)
.appender("stderr".to_string());
let console = Box::new(log4rs::appender::ConsoleAppender::builder().build());
let config = log4rs::config::Config::builder(root.build())
.appender(log4rs::config::Appender::builder("stderr".to_string(), console).build());
log4rs::init_config(config.build().unwrap()).unwrap();
}
fn initialize(config: DiscoConfig)
|
#[test]
fn integration() {
let config_file_loc = match env::var("DISCO_CONF") {
Err(_) => panic!("Please set the DISCO_CONF environment variable"),
Ok(location) => location,
};
match read_config(config_file_loc) {
Err(reason) => panic!("Unable to read configuration; bailing: {}", reason),
Ok(config) => initialize(config),
}
}
|
{
initialize_logging();
let serverset = *Box::new(Serverset::new(config));
debug!("THINGS");
serverset.update_members();
for member in serverset.members.read().unwrap().iter() {
debug!("Member: {:?}", member);
}
}
|
identifier_body
|
mod.rs
|
extern crate discotech;
#[macro_use]
extern crate log;
extern crate log4rs;
use discotech::{Serverset, DiscoConfig, read_config};
use std::env;
fn
|
() {
let root = log4rs::config::Root::builder(log::LogLevelFilter::Debug)
.appender("stderr".to_string());
let console = Box::new(log4rs::appender::ConsoleAppender::builder().build());
let config = log4rs::config::Config::builder(root.build())
.appender(log4rs::config::Appender::builder("stderr".to_string(), console).build());
log4rs::init_config(config.build().unwrap()).unwrap();
}
fn initialize(config: DiscoConfig) {
initialize_logging();
let serverset = *Box::new(Serverset::new(config));
debug!("THINGS");
serverset.update_members();
for member in serverset.members.read().unwrap().iter() {
debug!("Member: {:?}", member);
}
}
#[test]
fn integration() {
let config_file_loc = match env::var("DISCO_CONF") {
Err(_) => panic!("Please set the DISCO_CONF environment variable"),
Ok(location) => location,
};
match read_config(config_file_loc) {
Err(reason) => panic!("Unable to read configuration; bailing: {}", reason),
Ok(config) => initialize(config),
}
}
|
initialize_logging
|
identifier_name
|
mod.rs
|
extern crate discotech;
#[macro_use]
extern crate log;
extern crate log4rs;
use discotech::{Serverset, DiscoConfig, read_config};
|
fn initialize_logging() {
let root = log4rs::config::Root::builder(log::LogLevelFilter::Debug)
.appender("stderr".to_string());
let console = Box::new(log4rs::appender::ConsoleAppender::builder().build());
let config = log4rs::config::Config::builder(root.build())
.appender(log4rs::config::Appender::builder("stderr".to_string(), console).build());
log4rs::init_config(config.build().unwrap()).unwrap();
}
fn initialize(config: DiscoConfig) {
initialize_logging();
let serverset = *Box::new(Serverset::new(config));
debug!("THINGS");
serverset.update_members();
for member in serverset.members.read().unwrap().iter() {
debug!("Member: {:?}", member);
}
}
#[test]
fn integration() {
let config_file_loc = match env::var("DISCO_CONF") {
Err(_) => panic!("Please set the DISCO_CONF environment variable"),
Ok(location) => location,
};
match read_config(config_file_loc) {
Err(reason) => panic!("Unable to read configuration; bailing: {}", reason),
Ok(config) => initialize(config),
}
}
|
use std::env;
|
random_line_split
|
main.rs
|
use std::env;
use std::process::exit;
use std::sync::{Arc, RwLock};
use std::{thread, time};
use varlink::{Connection, VarlinkService};
use crate::org_example_more::*;
// Dynamically build the varlink rust code.
mod org_example_more;
#[cfg(test)]
mod test;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
// Main
fn print_usage(program: &str, opts: &getopts::Options) {
let brief = format!("Usage: {} [--varlink=<address>] [--client]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<_> = env::args().collect();
let program = args[0].clone();
let mut opts = getopts::Options::new();
opts.optopt("", "varlink", "varlink address URL", "<address>");
opts.optflag("", "client", "run in client mode");
opts.optflag("h", "help", "print this help menu");
opts.optopt("", "bridge", "bridge", "<bridge>");
opts.optopt("", "timeout", "server timeout", "<seconds>");
opts.optopt("", "sleep", "sleep duration", "<milliseconds>");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => {
eprintln!("{}", f.to_string());
print_usage(&program, &opts);
return;
}
};
if matches.opt_present("h") {
print_usage(&program, &opts);
return;
}
let client_mode = matches.opt_present("client");
let timeout = matches
.opt_str("timeout")
.unwrap_or_default()
.parse::<u64>()
.unwrap_or(0);
let sleep = matches
.opt_str("sleep")
.unwrap_or_default()
.parse::<u64>()
.unwrap_or(1000);
let bridge = matches.opt_str("bridge").unwrap_or_default();
let ret: Result<()> = if client_mode {
let connection = if bridge.is_empty() {
match matches.opt_str("varlink") {
None => {
Connection::with_activate(&format!("{} --varlink=$VARLINK_ADDRESS", program))
.unwrap()
}
Some(address) => Connection::with_address(&address).unwrap(),
}
} else {
Connection::with_bridge(&bridge).unwrap()
};
run_client(connection)
} else if let Some(address) = matches.opt_str("varlink") {
run_server(&address, timeout, sleep).map_err(|e| e.into())
} else {
print_usage(&program, &opts);
eprintln!("Need varlink address in server mode.");
exit(1);
};
exit(match ret {
Ok(_) => 0,
Err(err) =>
|
});
}
// Client
fn run_client(connection: Arc<RwLock<varlink::Connection>>) -> Result<()> {
/*
let new_addr = {
let conn = connection.read().unwrap();
conn.address()
};
*/
let mut iface = org_example_more::VarlinkClient::new(connection);
//let con2 = varlink::Connection::with_address(&new_addr)?;
//let mut pingiface = org_example_more::VarlinkClient::new(con2);
for reply in iface.test_more(10).more()? {
let reply = reply?;
//assert!(reply.state.is_some());
let state = reply.state;
match state {
State {
start: Some(true),
end: None,
progress: None,
..
} => {
eprintln!("--- Start ---");
}
State {
start: None,
end: Some(true),
progress: None,
..
} => {
eprintln!("--- End ---");
}
State {
start: None,
end: None,
progress: Some(progress),
..
} => {
eprintln!("Progress: {}", progress);
/*
if progress > 50 {
let reply = pingiface.ping("Test".into()).call()?;
eprintln!("Pong: '{}'", reply.pong);
}
*/
}
_ => eprintln!("Got unknown state: {:?}", state),
}
}
Ok(())
}
// Server
struct MyOrgExampleMore {
sleep_duration: u64,
}
impl VarlinkInterface for MyOrgExampleMore {
fn ping(&self, call: &mut dyn Call_Ping, ping: String) -> varlink::Result<()> {
call.reply(ping)
}
fn stop_serving(&self, call: &mut dyn Call_StopServing) -> varlink::Result<()> {
call.reply()?;
Err(varlink::ErrorKind::ConnectionClosed.into())
}
fn test_more(&self, call: &mut dyn Call_TestMore, n: i64) -> varlink::Result<()> {
if!call.wants_more() {
return call.reply_test_more_error("called without more".into());
}
if n == 0 {
return call.reply_test_more_error("n == 0".into());
}
call.set_continues(true);
call.reply(State {
start: Some(true),
end: None,
progress: None,
})?;
for i in 0..n {
thread::sleep(time::Duration::from_millis(self.sleep_duration));
call.reply(State {
progress: Some(i * 100 / n),
start: None,
end: None,
})?;
}
call.reply(State {
progress: Some(100),
start: None,
end: None,
})?;
call.set_continues(false);
call.reply(State {
end: Some(true),
progress: None,
start: None,
})
}
}
fn run_server(address: &str, timeout: u64, sleep_duration: u64) -> varlink::Result<()> {
let myexamplemore = MyOrgExampleMore { sleep_duration };
let myinterface = org_example_more::new(Box::new(myexamplemore));
let service = VarlinkService::new(
"org.varlink",
"test service",
"0.1",
"http://varlink.org",
vec![Box::new(myinterface)],
);
varlink::listen(
service,
&address,
&varlink::ListenConfig {
idle_timeout: timeout,
..Default::default()
},
)?;
Ok(())
}
|
{
eprintln!("error: {:?}", err);
1
}
|
conditional_block
|
main.rs
|
use std::env;
use std::process::exit;
use std::sync::{Arc, RwLock};
use std::{thread, time};
use varlink::{Connection, VarlinkService};
use crate::org_example_more::*;
// Dynamically build the varlink rust code.
mod org_example_more;
#[cfg(test)]
mod test;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
// Main
fn print_usage(program: &str, opts: &getopts::Options) {
let brief = format!("Usage: {} [--varlink=<address>] [--client]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<_> = env::args().collect();
let program = args[0].clone();
let mut opts = getopts::Options::new();
opts.optopt("", "varlink", "varlink address URL", "<address>");
opts.optflag("", "client", "run in client mode");
opts.optflag("h", "help", "print this help menu");
opts.optopt("", "bridge", "bridge", "<bridge>");
opts.optopt("", "timeout", "server timeout", "<seconds>");
opts.optopt("", "sleep", "sleep duration", "<milliseconds>");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => {
eprintln!("{}", f.to_string());
print_usage(&program, &opts);
return;
}
};
if matches.opt_present("h") {
print_usage(&program, &opts);
return;
}
let client_mode = matches.opt_present("client");
let timeout = matches
.opt_str("timeout")
.unwrap_or_default()
.parse::<u64>()
.unwrap_or(0);
let sleep = matches
.opt_str("sleep")
.unwrap_or_default()
.parse::<u64>()
.unwrap_or(1000);
let bridge = matches.opt_str("bridge").unwrap_or_default();
let ret: Result<()> = if client_mode {
let connection = if bridge.is_empty() {
match matches.opt_str("varlink") {
None => {
Connection::with_activate(&format!("{} --varlink=$VARLINK_ADDRESS", program))
.unwrap()
}
Some(address) => Connection::with_address(&address).unwrap(),
}
} else {
Connection::with_bridge(&bridge).unwrap()
};
run_client(connection)
} else if let Some(address) = matches.opt_str("varlink") {
run_server(&address, timeout, sleep).map_err(|e| e.into())
} else {
print_usage(&program, &opts);
eprintln!("Need varlink address in server mode.");
exit(1);
};
exit(match ret {
Ok(_) => 0,
Err(err) => {
eprintln!("error: {:?}", err);
1
}
});
}
// Client
fn run_client(connection: Arc<RwLock<varlink::Connection>>) -> Result<()> {
/*
let new_addr = {
let conn = connection.read().unwrap();
conn.address()
};
*/
let mut iface = org_example_more::VarlinkClient::new(connection);
//let con2 = varlink::Connection::with_address(&new_addr)?;
//let mut pingiface = org_example_more::VarlinkClient::new(con2);
for reply in iface.test_more(10).more()? {
let reply = reply?;
//assert!(reply.state.is_some());
let state = reply.state;
match state {
State {
start: Some(true),
end: None,
progress: None,
..
} => {
eprintln!("--- Start ---");
}
State {
start: None,
end: Some(true),
progress: None,
..
} => {
eprintln!("--- End ---");
}
State {
start: None,
end: None,
progress: Some(progress),
..
} => {
eprintln!("Progress: {}", progress);
/*
if progress > 50 {
let reply = pingiface.ping("Test".into()).call()?;
eprintln!("Pong: '{}'", reply.pong);
}
*/
}
_ => eprintln!("Got unknown state: {:?}", state),
}
}
Ok(())
}
// Server
struct MyOrgExampleMore {
sleep_duration: u64,
}
impl VarlinkInterface for MyOrgExampleMore {
fn ping(&self, call: &mut dyn Call_Ping, ping: String) -> varlink::Result<()> {
call.reply(ping)
}
fn stop_serving(&self, call: &mut dyn Call_StopServing) -> varlink::Result<()> {
call.reply()?;
Err(varlink::ErrorKind::ConnectionClosed.into())
}
fn test_more(&self, call: &mut dyn Call_TestMore, n: i64) -> varlink::Result<()> {
if!call.wants_more() {
return call.reply_test_more_error("called without more".into());
}
if n == 0 {
return call.reply_test_more_error("n == 0".into());
}
call.set_continues(true);
call.reply(State {
start: Some(true),
end: None,
progress: None,
})?;
for i in 0..n {
thread::sleep(time::Duration::from_millis(self.sleep_duration));
call.reply(State {
progress: Some(i * 100 / n),
start: None,
end: None,
})?;
}
call.reply(State {
progress: Some(100),
start: None,
end: None,
})?;
call.set_continues(false);
call.reply(State {
end: Some(true),
progress: None,
start: None,
})
}
}
fn run_server(address: &str, timeout: u64, sleep_duration: u64) -> varlink::Result<()>
|
{
let myexamplemore = MyOrgExampleMore { sleep_duration };
let myinterface = org_example_more::new(Box::new(myexamplemore));
let service = VarlinkService::new(
"org.varlink",
"test service",
"0.1",
"http://varlink.org",
vec![Box::new(myinterface)],
);
varlink::listen(
service,
&address,
&varlink::ListenConfig {
idle_timeout: timeout,
..Default::default()
},
)?;
Ok(())
}
|
identifier_body
|
|
main.rs
|
use std::env;
use std::process::exit;
use std::sync::{Arc, RwLock};
use std::{thread, time};
use varlink::{Connection, VarlinkService};
use crate::org_example_more::*;
// Dynamically build the varlink rust code.
mod org_example_more;
#[cfg(test)]
mod test;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
// Main
fn print_usage(program: &str, opts: &getopts::Options) {
let brief = format!("Usage: {} [--varlink=<address>] [--client]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<_> = env::args().collect();
let program = args[0].clone();
let mut opts = getopts::Options::new();
opts.optopt("", "varlink", "varlink address URL", "<address>");
opts.optflag("", "client", "run in client mode");
opts.optflag("h", "help", "print this help menu");
opts.optopt("", "bridge", "bridge", "<bridge>");
opts.optopt("", "timeout", "server timeout", "<seconds>");
opts.optopt("", "sleep", "sleep duration", "<milliseconds>");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => {
eprintln!("{}", f.to_string());
print_usage(&program, &opts);
return;
}
};
if matches.opt_present("h") {
print_usage(&program, &opts);
return;
}
let client_mode = matches.opt_present("client");
let timeout = matches
.opt_str("timeout")
.unwrap_or_default()
.parse::<u64>()
.unwrap_or(0);
let sleep = matches
.opt_str("sleep")
.unwrap_or_default()
.parse::<u64>()
.unwrap_or(1000);
let bridge = matches.opt_str("bridge").unwrap_or_default();
let ret: Result<()> = if client_mode {
let connection = if bridge.is_empty() {
match matches.opt_str("varlink") {
None => {
Connection::with_activate(&format!("{} --varlink=$VARLINK_ADDRESS", program))
.unwrap()
}
Some(address) => Connection::with_address(&address).unwrap(),
}
} else {
Connection::with_bridge(&bridge).unwrap()
};
run_client(connection)
} else if let Some(address) = matches.opt_str("varlink") {
run_server(&address, timeout, sleep).map_err(|e| e.into())
} else {
print_usage(&program, &opts);
eprintln!("Need varlink address in server mode.");
exit(1);
};
exit(match ret {
Ok(_) => 0,
Err(err) => {
eprintln!("error: {:?}", err);
1
}
});
}
// Client
fn run_client(connection: Arc<RwLock<varlink::Connection>>) -> Result<()> {
/*
let new_addr = {
let conn = connection.read().unwrap();
conn.address()
};
*/
let mut iface = org_example_more::VarlinkClient::new(connection);
//let con2 = varlink::Connection::with_address(&new_addr)?;
//let mut pingiface = org_example_more::VarlinkClient::new(con2);
for reply in iface.test_more(10).more()? {
let reply = reply?;
//assert!(reply.state.is_some());
let state = reply.state;
match state {
State {
start: Some(true),
end: None,
progress: None,
..
} => {
eprintln!("--- Start ---");
}
State {
start: None,
end: Some(true),
progress: None,
..
} => {
eprintln!("--- End ---");
}
State {
start: None,
end: None,
progress: Some(progress),
..
} => {
eprintln!("Progress: {}", progress);
/*
if progress > 50 {
let reply = pingiface.ping("Test".into()).call()?;
eprintln!("Pong: '{}'", reply.pong);
}
*/
}
_ => eprintln!("Got unknown state: {:?}", state),
}
}
Ok(())
}
// Server
struct MyOrgExampleMore {
sleep_duration: u64,
}
impl VarlinkInterface for MyOrgExampleMore {
fn ping(&self, call: &mut dyn Call_Ping, ping: String) -> varlink::Result<()> {
call.reply(ping)
}
fn
|
(&self, call: &mut dyn Call_StopServing) -> varlink::Result<()> {
call.reply()?;
Err(varlink::ErrorKind::ConnectionClosed.into())
}
fn test_more(&self, call: &mut dyn Call_TestMore, n: i64) -> varlink::Result<()> {
if!call.wants_more() {
return call.reply_test_more_error("called without more".into());
}
if n == 0 {
return call.reply_test_more_error("n == 0".into());
}
call.set_continues(true);
call.reply(State {
start: Some(true),
end: None,
progress: None,
})?;
for i in 0..n {
thread::sleep(time::Duration::from_millis(self.sleep_duration));
call.reply(State {
progress: Some(i * 100 / n),
start: None,
end: None,
})?;
}
call.reply(State {
progress: Some(100),
start: None,
end: None,
})?;
call.set_continues(false);
call.reply(State {
end: Some(true),
progress: None,
start: None,
})
}
}
fn run_server(address: &str, timeout: u64, sleep_duration: u64) -> varlink::Result<()> {
let myexamplemore = MyOrgExampleMore { sleep_duration };
let myinterface = org_example_more::new(Box::new(myexamplemore));
let service = VarlinkService::new(
"org.varlink",
"test service",
"0.1",
"http://varlink.org",
vec![Box::new(myinterface)],
);
varlink::listen(
service,
&address,
&varlink::ListenConfig {
idle_timeout: timeout,
..Default::default()
},
)?;
Ok(())
}
|
stop_serving
|
identifier_name
|
main.rs
|
use std::env;
use std::process::exit;
use std::sync::{Arc, RwLock};
use std::{thread, time};
use varlink::{Connection, VarlinkService};
use crate::org_example_more::*;
// Dynamically build the varlink rust code.
mod org_example_more;
#[cfg(test)]
mod test;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
// Main
fn print_usage(program: &str, opts: &getopts::Options) {
let brief = format!("Usage: {} [--varlink=<address>] [--client]", program);
print!("{}", opts.usage(&brief));
}
fn main() {
let args: Vec<_> = env::args().collect();
let program = args[0].clone();
let mut opts = getopts::Options::new();
opts.optopt("", "varlink", "varlink address URL", "<address>");
opts.optflag("", "client", "run in client mode");
opts.optflag("h", "help", "print this help menu");
opts.optopt("", "bridge", "bridge", "<bridge>");
opts.optopt("", "timeout", "server timeout", "<seconds>");
opts.optopt("", "sleep", "sleep duration", "<milliseconds>");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => {
eprintln!("{}", f.to_string());
print_usage(&program, &opts);
return;
}
};
if matches.opt_present("h") {
print_usage(&program, &opts);
return;
}
let client_mode = matches.opt_present("client");
let timeout = matches
.opt_str("timeout")
.unwrap_or_default()
.parse::<u64>()
.unwrap_or(0);
let sleep = matches
.opt_str("sleep")
.unwrap_or_default()
.parse::<u64>()
.unwrap_or(1000);
let bridge = matches.opt_str("bridge").unwrap_or_default();
let ret: Result<()> = if client_mode {
let connection = if bridge.is_empty() {
match matches.opt_str("varlink") {
None => {
Connection::with_activate(&format!("{} --varlink=$VARLINK_ADDRESS", program))
.unwrap()
}
Some(address) => Connection::with_address(&address).unwrap(),
}
} else {
Connection::with_bridge(&bridge).unwrap()
};
run_client(connection)
} else if let Some(address) = matches.opt_str("varlink") {
run_server(&address, timeout, sleep).map_err(|e| e.into())
} else {
print_usage(&program, &opts);
eprintln!("Need varlink address in server mode.");
exit(1);
};
exit(match ret {
Ok(_) => 0,
Err(err) => {
eprintln!("error: {:?}", err);
1
}
});
}
// Client
fn run_client(connection: Arc<RwLock<varlink::Connection>>) -> Result<()> {
/*
let new_addr = {
let conn = connection.read().unwrap();
conn.address()
};
*/
let mut iface = org_example_more::VarlinkClient::new(connection);
//let con2 = varlink::Connection::with_address(&new_addr)?;
//let mut pingiface = org_example_more::VarlinkClient::new(con2);
for reply in iface.test_more(10).more()? {
let reply = reply?;
//assert!(reply.state.is_some());
let state = reply.state;
match state {
State {
start: Some(true),
end: None,
progress: None,
..
} => {
eprintln!("--- Start ---");
}
State {
start: None,
end: Some(true),
progress: None,
..
} => {
eprintln!("--- End ---");
}
State {
start: None,
end: None,
progress: Some(progress),
..
} => {
eprintln!("Progress: {}", progress);
/*
if progress > 50 {
let reply = pingiface.ping("Test".into()).call()?;
eprintln!("Pong: '{}'", reply.pong);
}
*/
}
_ => eprintln!("Got unknown state: {:?}", state),
}
}
Ok(())
}
// Server
struct MyOrgExampleMore {
sleep_duration: u64,
}
impl VarlinkInterface for MyOrgExampleMore {
fn ping(&self, call: &mut dyn Call_Ping, ping: String) -> varlink::Result<()> {
call.reply(ping)
}
|
fn stop_serving(&self, call: &mut dyn Call_StopServing) -> varlink::Result<()> {
call.reply()?;
Err(varlink::ErrorKind::ConnectionClosed.into())
}
fn test_more(&self, call: &mut dyn Call_TestMore, n: i64) -> varlink::Result<()> {
if!call.wants_more() {
return call.reply_test_more_error("called without more".into());
}
if n == 0 {
return call.reply_test_more_error("n == 0".into());
}
call.set_continues(true);
call.reply(State {
start: Some(true),
end: None,
progress: None,
})?;
for i in 0..n {
thread::sleep(time::Duration::from_millis(self.sleep_duration));
call.reply(State {
progress: Some(i * 100 / n),
start: None,
end: None,
})?;
}
call.reply(State {
progress: Some(100),
start: None,
end: None,
})?;
call.set_continues(false);
call.reply(State {
end: Some(true),
progress: None,
start: None,
})
}
}
fn run_server(address: &str, timeout: u64, sleep_duration: u64) -> varlink::Result<()> {
let myexamplemore = MyOrgExampleMore { sleep_duration };
let myinterface = org_example_more::new(Box::new(myexamplemore));
let service = VarlinkService::new(
"org.varlink",
"test service",
"0.1",
"http://varlink.org",
vec![Box::new(myinterface)],
);
varlink::listen(
service,
&address,
&varlink::ListenConfig {
idle_timeout: timeout,
..Default::default()
},
)?;
Ok(())
}
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.