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 |
---|---|---|---|---|
main.rs
|
use std::error;
use std::io;
fn get_sum(input: String) -> Result<i32, Box<dyn error::Error>>
|
fn main() -> Result<(), Box<dyn error::Error>> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let sum = get_sum(input)?;
println!("{}", sum);
Ok(())
}
#[cfg(test)]
mod tests {
use super::get_sum;
#[test]
fn integer_sum_test() {
let input = "2 2".to_string();
let output = get_sum(input);
assert_eq!(output.unwrap(), 4);
let input = "3 2".to_string();
let output = get_sum(input);
assert_eq!(output.unwrap(), 5);
let input = "79 -1".to_string();
let output = get_sum(input);
assert_eq!(output.unwrap(), 78);
let input = "-5 10".to_string();
let output = get_sum(input);
assert_eq!(output.unwrap(), 5);
let input = "1000 -1000".to_string();
let output = get_sum(input);
assert_eq!(output.unwrap(), 0);
}
#[test]
fn bad_parsing_test() {
let input = "2 1T".to_string();
let output = get_sum(input);
assert_eq!(output.is_err(), true);
let input = "2 2.4".to_string();
let output = get_sum(input);
assert_eq!(output.is_err(), true);
}
#[test]
fn bad_length_test() {
let input = "2 1 1".to_string();
let output = get_sum(input);
assert_eq!(output.is_err(), true);
let input = "2".to_string();
let output = get_sum(input);
assert_eq!(output.is_err(), true);
let input = "".to_string();
let output = get_sum(input);
assert_eq!(output.is_err(), true);
}
}
|
{
let numbers = input
.split_whitespace()
.map(|number| number.parse())
.collect::<Result<Vec<i32>, _>>()?;
if numbers.len() == 2 {
Ok(numbers.iter().sum())
} else {
Err("Please enter 2 integers".into())
}
}
|
identifier_body
|
main.rs
|
use std::error;
use std::io;
fn get_sum(input: String) -> Result<i32, Box<dyn error::Error>> {
let numbers = input
.split_whitespace()
.map(|number| number.parse())
.collect::<Result<Vec<i32>, _>>()?;
if numbers.len() == 2 {
Ok(numbers.iter().sum())
} else {
Err("Please enter 2 integers".into())
}
}
fn main() -> Result<(), Box<dyn error::Error>> {
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let sum = get_sum(input)?;
println!("{}", sum);
Ok(())
}
#[cfg(test)]
mod tests {
use super::get_sum;
#[test]
fn integer_sum_test() {
let input = "2 2".to_string();
let output = get_sum(input);
assert_eq!(output.unwrap(), 4);
let input = "3 2".to_string();
let output = get_sum(input);
assert_eq!(output.unwrap(), 5);
let input = "79 -1".to_string();
let output = get_sum(input);
assert_eq!(output.unwrap(), 78);
let input = "-5 10".to_string();
let output = get_sum(input);
assert_eq!(output.unwrap(), 5);
let input = "1000 -1000".to_string();
let output = get_sum(input);
assert_eq!(output.unwrap(), 0);
}
#[test]
fn
|
() {
let input = "2 1T".to_string();
let output = get_sum(input);
assert_eq!(output.is_err(), true);
let input = "2 2.4".to_string();
let output = get_sum(input);
assert_eq!(output.is_err(), true);
}
#[test]
fn bad_length_test() {
let input = "2 1 1".to_string();
let output = get_sum(input);
assert_eq!(output.is_err(), true);
let input = "2".to_string();
let output = get_sum(input);
assert_eq!(output.is_err(), true);
let input = "".to_string();
let output = get_sum(input);
assert_eq!(output.is_err(), true);
}
}
|
bad_parsing_test
|
identifier_name
|
fn.rs
|
struct S(A); // Concrete type `S`.
struct SGen<T>(T); // Generic type `SGen`.
// The following functions all take ownership of the variable passed into
// them and immediately go out of scope, freeing the variable.
// Define a function `reg_fn` that takes an argument `_s` of type `S`.
// This has no `<T>` so this is not a generic function.
fn reg_fn(_s: S) {}
// Define a function `gen_spec_t` that takes an argument `_s` of type `SGen<T>`.
// It has been explicitly given the type parameter `A`, but because `A` has not
// been specified as a generic type parameter for `gen_spec_t`, it is not generic.
fn gen_spec_t(_s: SGen<A>) {}
// Define a function `gen_spec_i32` that takes an argument `_s` of type `SGen<i32>`.
// It has been explicitly given the type parameter `i32`, which is a specific type.
// Because `i32` is not a generic type, this function is also not generic.
fn gen_spec_i32(_s: SGen<i32>) {}
// Define a function `generic` that takes an argument `_s` of type `SGen<T>`.
// Because `SGen<T>` is preceded by `<T>`, this function is generic over `T`.
fn generic<T>(_s: SGen<T>) {}
fn main() {
// Using the non-generic functions
reg_fn(S(A)); // Concrete type.
gen_spec_t(SGen(A)); // Implicitly specified type parameter `A`.
gen_spec_i32(SGen(6)); // Implicitly specified type parameter `i32`.
// Explicitly specified type parameter `char` to `generic()`.
generic::<char>(SGen('a'));
// Implicitly specified type parameter `char` to `generic()`.
generic(SGen('c'));
}
|
struct A; // Concrete type `A`.
|
random_line_split
|
|
fn.rs
|
struct
|
; // Concrete type `A`.
struct S(A); // Concrete type `S`.
struct SGen<T>(T); // Generic type `SGen`.
// The following functions all take ownership of the variable passed into
// them and immediately go out of scope, freeing the variable.
// Define a function `reg_fn` that takes an argument `_s` of type `S`.
// This has no `<T>` so this is not a generic function.
fn reg_fn(_s: S) {}
// Define a function `gen_spec_t` that takes an argument `_s` of type `SGen<T>`.
// It has been explicitly given the type parameter `A`, but because `A` has not
// been specified as a generic type parameter for `gen_spec_t`, it is not generic.
fn gen_spec_t(_s: SGen<A>) {}
// Define a function `gen_spec_i32` that takes an argument `_s` of type `SGen<i32>`.
// It has been explicitly given the type parameter `i32`, which is a specific type.
// Because `i32` is not a generic type, this function is also not generic.
fn gen_spec_i32(_s: SGen<i32>) {}
// Define a function `generic` that takes an argument `_s` of type `SGen<T>`.
// Because `SGen<T>` is preceded by `<T>`, this function is generic over `T`.
fn generic<T>(_s: SGen<T>) {}
fn main() {
// Using the non-generic functions
reg_fn(S(A)); // Concrete type.
gen_spec_t(SGen(A)); // Implicitly specified type parameter `A`.
gen_spec_i32(SGen(6)); // Implicitly specified type parameter `i32`.
// Explicitly specified type parameter `char` to `generic()`.
generic::<char>(SGen('a'));
// Implicitly specified type parameter `char` to `generic()`.
generic(SGen('c'));
}
|
A
|
identifier_name
|
issue-8898.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.
fn assert_repr_eq<T: std::fmt::Show>(obj : T, expected : String) {
assert_eq!(expected, format!("{:?}", obj));
}
pub fn main() {
let abc = [1i, 2, 3];
let tf = [true, false];
let x = [(), ()];
|
let slice = &x[0..1];
assert_repr_eq(&abc[], "[1i, 2i, 3i]".to_string());
assert_repr_eq(&tf[], "[true, false]".to_string());
assert_repr_eq(&x[], "[(), ()]".to_string());
assert_repr_eq(slice, "[()]".to_string());
assert_repr_eq(&x[], "[(), ()]".to_string());
}
|
random_line_split
|
|
issue-8898.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.
fn assert_repr_eq<T: std::fmt::Show>(obj : T, expected : String) {
assert_eq!(expected, format!("{:?}", obj));
}
pub fn main()
|
{
let abc = [1i, 2, 3];
let tf = [true, false];
let x = [(), ()];
let slice = &x[0..1];
assert_repr_eq(&abc[], "[1i, 2i, 3i]".to_string());
assert_repr_eq(&tf[], "[true, false]".to_string());
assert_repr_eq(&x[], "[(), ()]".to_string());
assert_repr_eq(slice, "[()]".to_string());
assert_repr_eq(&x[], "[(), ()]".to_string());
}
|
identifier_body
|
|
issue-8898.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.
fn assert_repr_eq<T: std::fmt::Show>(obj : T, expected : String) {
assert_eq!(expected, format!("{:?}", obj));
}
pub fn
|
() {
let abc = [1i, 2, 3];
let tf = [true, false];
let x = [(), ()];
let slice = &x[0..1];
assert_repr_eq(&abc[], "[1i, 2i, 3i]".to_string());
assert_repr_eq(&tf[], "[true, false]".to_string());
assert_repr_eq(&x[], "[(), ()]".to_string());
assert_repr_eq(slice, "[()]".to_string());
assert_repr_eq(&x[], "[(), ()]".to_string());
}
|
main
|
identifier_name
|
singleton.rs
|
extern crate qmlrs;
extern crate libc;
use qmlrs::*;
#[test]
pub fn
|
() {
let mut engine = qmlrs::Engine::new("name");
extern "C" fn slot(p: *mut ffi::QObject, id: libc::c_int, _: *const ffi::QVariantList, _: *mut ffi::QVariant) {
println!("id: {}",id);
if id == 2 {
Object::from_ptr(p).emit(1,&[Variant::String("hello".to_string())]);
}
}
extern "C" fn singleton(_: *mut ffi::QQmlEngine, _: *mut ffi::QJSEngine) -> *mut ffi::QObject {
let mut metaobj = MetaObject::new("Person",slot);
assert_eq!(metaobj.add_signal("nameChanged()"),0);
assert_eq!(metaobj.add_signal("testSignal(QString)"),1);
metaobj.add_property("name","QString",Some("nameChanged()"));
assert_eq!(metaobj.add_method("test()","void"),2);
let mut obj = metaobj.instantiate();
obj.set_property("name",Variant::String("Kai".to_string()));
obj.get_property("name");
obj.as_ptr()
}
register_singleton_type(&"Test",1,2,&"Person",singleton);
engine.load_local_file("tests/singleton.qml");
engine.exec();
}
|
singleton_test
|
identifier_name
|
singleton.rs
|
extern crate qmlrs;
extern crate libc;
use qmlrs::*;
#[test]
pub fn singleton_test()
|
obj.as_ptr()
}
register_singleton_type(&"Test",1,2,&"Person",singleton);
engine.load_local_file("tests/singleton.qml");
engine.exec();
}
|
{
let mut engine = qmlrs::Engine::new("name");
extern "C" fn slot(p: *mut ffi::QObject, id: libc::c_int, _: *const ffi::QVariantList, _: *mut ffi::QVariant) {
println!("id: {}",id);
if id == 2 {
Object::from_ptr(p).emit(1,&[Variant::String("hello".to_string())]);
}
}
extern "C" fn singleton(_: *mut ffi::QQmlEngine, _: *mut ffi::QJSEngine) -> *mut ffi::QObject {
let mut metaobj = MetaObject::new("Person",slot);
assert_eq!(metaobj.add_signal("nameChanged()"),0);
assert_eq!(metaobj.add_signal("testSignal(QString)"),1);
metaobj.add_property("name","QString",Some("nameChanged()"));
assert_eq!(metaobj.add_method("test()","void"),2);
let mut obj = metaobj.instantiate();
obj.set_property("name",Variant::String("Kai".to_string()));
obj.get_property("name");
|
identifier_body
|
singleton.rs
|
extern crate qmlrs;
extern crate libc;
use qmlrs::*;
#[test]
pub fn singleton_test() {
let mut engine = qmlrs::Engine::new("name");
extern "C" fn slot(p: *mut ffi::QObject, id: libc::c_int, _: *const ffi::QVariantList, _: *mut ffi::QVariant) {
println!("id: {}",id);
if id == 2
|
}
extern "C" fn singleton(_: *mut ffi::QQmlEngine, _: *mut ffi::QJSEngine) -> *mut ffi::QObject {
let mut metaobj = MetaObject::new("Person",slot);
assert_eq!(metaobj.add_signal("nameChanged()"),0);
assert_eq!(metaobj.add_signal("testSignal(QString)"),1);
metaobj.add_property("name","QString",Some("nameChanged()"));
assert_eq!(metaobj.add_method("test()","void"),2);
let mut obj = metaobj.instantiate();
obj.set_property("name",Variant::String("Kai".to_string()));
obj.get_property("name");
obj.as_ptr()
}
register_singleton_type(&"Test",1,2,&"Person",singleton);
engine.load_local_file("tests/singleton.qml");
engine.exec();
}
|
{
Object::from_ptr(p).emit(1,&[Variant::String("hello".to_string())]);
}
|
conditional_block
|
singleton.rs
|
extern crate qmlrs;
extern crate libc;
use qmlrs::*;
#[test]
pub fn singleton_test() {
let mut engine = qmlrs::Engine::new("name");
extern "C" fn slot(p: *mut ffi::QObject, id: libc::c_int, _: *const ffi::QVariantList, _: *mut ffi::QVariant) {
println!("id: {}",id);
if id == 2 {
Object::from_ptr(p).emit(1,&[Variant::String("hello".to_string())]);
}
|
assert_eq!(metaobj.add_signal("testSignal(QString)"),1);
metaobj.add_property("name","QString",Some("nameChanged()"));
assert_eq!(metaobj.add_method("test()","void"),2);
let mut obj = metaobj.instantiate();
obj.set_property("name",Variant::String("Kai".to_string()));
obj.get_property("name");
obj.as_ptr()
}
register_singleton_type(&"Test",1,2,&"Person",singleton);
engine.load_local_file("tests/singleton.qml");
engine.exec();
}
|
}
extern "C" fn singleton(_: *mut ffi::QQmlEngine, _: *mut ffi::QJSEngine) -> *mut ffi::QObject {
let mut metaobj = MetaObject::new("Person",slot);
assert_eq!(metaobj.add_signal("nameChanged()"),0);
|
random_line_split
|
focus_peak_cam1.rs
|
/*
* Copyright (C) 2015 The Android Open Source Project
|
*
* 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.
*/
#pragma version(1)
#pragma rs java_package_name(freed.utils)
#pragma rs_fp_relaxed
rs_allocation gCurrentFrame;
uchar4 __attribute__((kernel)) peak(uint32_t x, uint32_t y) {
uchar4 curPixel;
curPixel.r = rsGetElementAtYuv_uchar_Y(gCurrentFrame, x, y);
curPixel.g = rsGetElementAtYuv_uchar_U(gCurrentFrame, x, y);
curPixel.b = rsGetElementAtYuv_uchar_V(gCurrentFrame, x, y);
int dx = x + ((x == 0)? 1 : -1);
int sum = 0;
int tmp;
tmp = rsGetElementAtYuv_uchar_Y(gCurrentFrame, dx, y) - curPixel.r;
sum += tmp * tmp;
tmp = rsGetElementAtYuv_uchar_U(gCurrentFrame, dx, y) - curPixel.g;
sum += tmp * tmp;
tmp = rsGetElementAtYuv_uchar_V(gCurrentFrame, dx, y) - curPixel.b;
sum += tmp * tmp;
int dy = y + ((y == 0)? 1 : -1);
tmp = rsGetElementAtYuv_uchar_Y(gCurrentFrame, x, dy) - curPixel.r;
sum += tmp * tmp;
tmp = rsGetElementAtYuv_uchar_U(gCurrentFrame, x, dy) - curPixel.g;
sum += tmp * tmp;
tmp = rsGetElementAtYuv_uchar_V(gCurrentFrame, x, dy) - curPixel.b;
sum += tmp * tmp;
sum >>= 9;
sum *= sum * sum;
curPixel.a = 255;
uchar4 mergedPixel = curPixel;
int4 rgb;
rgb.r = mergedPixel.r +
mergedPixel.b * 1436 / 1024 - 179 + sum;
rgb.g = mergedPixel.r -
mergedPixel.g * 46549 / 131072 + 44 -
mergedPixel.b * 93604 / 131072 + 91 + sum;
rgb.b = mergedPixel.r +
mergedPixel.g * 1814 / 1024 - 227;
rgb.a = 255;
// Write out merged HDR result
int factor = 2;
if(rgb.r >=255 -factor && rgb.g >= 255 -factor && rgb.b >= 255 -factor)
{
rgb.r =255; rgb.g = 0; rgb.b = 0;
}
if(rgb.r <=0 +factor && rgb.g <= 0 +factor && rgb.b <= 0 +factor)
{
rgb.r =0; rgb.g = 0; rgb.b = 255;
}
if (rgb.r > 255) rgb.r = 255; if(rgb.r < 0) rgb.r = 0;
if (rgb.g > 255) rgb.g = 255; if(rgb.g < 0) rgb.g = 0;
if (rgb.b > 255) rgb.b = 255; if(rgb.b < 0) rgb.b = 0;
uchar4 out = convert_uchar4(rgb);
return out;
}
|
*
* 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
|
random_line_split
|
focus_peak_cam1.rs
|
/*
* Copyright (C) 2015 The Android Open Source Project
*
* 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.
*/
#pragma version(1)
#pragma rs java_package_name(freed.utils)
#pragma rs_fp_relaxed
rs_allocation gCurrentFrame;
uchar4 __attribute__((kernel)) peak(uint32_t x, uint32_t y) {
uchar4 curPixel;
curPixel.r = rsGetElementAtYuv_uchar_Y(gCurrentFrame, x, y);
curPixel.g = rsGetElementAtYuv_uchar_U(gCurrentFrame, x, y);
curPixel.b = rsGetElementAtYuv_uchar_V(gCurrentFrame, x, y);
int dx = x + ((x == 0)? 1 : -1);
int sum = 0;
int tmp;
tmp = rsGetElementAtYuv_uchar_Y(gCurrentFrame, dx, y) - curPixel.r;
sum += tmp * tmp;
tmp = rsGetElementAtYuv_uchar_U(gCurrentFrame, dx, y) - curPixel.g;
sum += tmp * tmp;
tmp = rsGetElementAtYuv_uchar_V(gCurrentFrame, dx, y) - curPixel.b;
sum += tmp * tmp;
int dy = y + ((y == 0)? 1 : -1);
tmp = rsGetElementAtYuv_uchar_Y(gCurrentFrame, x, dy) - curPixel.r;
sum += tmp * tmp;
tmp = rsGetElementAtYuv_uchar_U(gCurrentFrame, x, dy) - curPixel.g;
sum += tmp * tmp;
tmp = rsGetElementAtYuv_uchar_V(gCurrentFrame, x, dy) - curPixel.b;
sum += tmp * tmp;
sum >>= 9;
sum *= sum * sum;
curPixel.a = 255;
uchar4 mergedPixel = curPixel;
int4 rgb;
rgb.r = mergedPixel.r +
mergedPixel.b * 1436 / 1024 - 179 + sum;
rgb.g = mergedPixel.r -
mergedPixel.g * 46549 / 131072 + 44 -
mergedPixel.b * 93604 / 131072 + 91 + sum;
rgb.b = mergedPixel.r +
mergedPixel.g * 1814 / 1024 - 227;
rgb.a = 255;
// Write out merged HDR result
int factor = 2;
if(rgb.r >=255 -factor && rgb.g >= 255 -factor && rgb.b >= 255 -factor)
|
if(rgb.r <=0 +factor && rgb.g <= 0 +factor && rgb.b <= 0 +factor)
{
rgb.r =0; rgb.g = 0; rgb.b = 255;
}
if (rgb.r > 255) rgb.r = 255; if(rgb.r < 0) rgb.r = 0;
if (rgb.g > 255) rgb.g = 255; if(rgb.g < 0) rgb.g = 0;
if (rgb.b > 255) rgb.b = 255; if(rgb.b < 0) rgb.b = 0;
uchar4 out = convert_uchar4(rgb);
return out;
}
|
{
rgb.r =255; rgb.g = 0; rgb.b = 0;
}
|
conditional_block
|
tuple.rs
|
//! [Lambda-encoded `n`-tuple](https://www.mathstat.dal.ca/~selinger/papers/lambdanotes.pdf)
//!
|
/// # Example
/// ```
/// # #[macro_use] extern crate lambda_calculus;
/// # fn main() {
/// use lambda_calculus::term::*;
/// use lambda_calculus::*;
///
/// assert_eq!(
/// tuple!(1.into_church(), 2.into_church()),
/// abs(app!(Var(1), 1.into_church(), 2.into_church()))
/// );
///
/// assert_eq!(
/// tuple!(1.into_church(), 2.into_church(), 3.into_church()),
/// abs(app!(Var(1), 1.into_church(), 2.into_church(), 3.into_church()))
/// );
/// # }
/// ```
#[macro_export]
macro_rules! tuple {
($first:expr, $($next:expr),+) => {
{
let mut ret = app(Var(1), $first);
$(ret = app(ret, $next);)*
abs(ret)
}
};
}
/// A macro for obtaining a projection function (`π`) providing the `i`-th (one-indexed) element of
/// a lambda-encoded `n`-tuple.
///
/// # Example
/// ```
/// # #[macro_use] extern crate lambda_calculus;
/// # fn main() {
/// use lambda_calculus::term::*;
/// use lambda_calculus::*;
///
/// let t2 = || tuple!(1.into_church(), 2.into_church());
///
/// assert_eq!(beta(app(pi!(1, 2), t2()), NOR, 0), 1.into_church());
/// assert_eq!(beta(app(pi!(2, 2), t2()), NOR, 0), 2.into_church());
///
/// let t3 = || tuple!(1.into_church(), 2.into_church(), 3.into_church());
///
/// assert_eq!(beta(app(pi!(1, 3), t3()), NOR, 0), 1.into_church());
/// assert_eq!(beta(app(pi!(2, 3), t3()), NOR, 0), 2.into_church());
/// assert_eq!(beta(app(pi!(3, 3), t3()), NOR, 0), 3.into_church());
/// # }
/// ```
#[macro_export]
macro_rules! pi {
($i:expr, $n:expr) => {{
let mut ret = Var($n + 1 - $i);
for _ in 0..$n {
ret = abs(ret);
}
abs(app(Var(1), ret))
}};
}
|
//! This module contains the `tuple` and `pi` macros.
/// A macro for creating lambda-encoded tuples.
///
|
random_line_split
|
dom.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/. */
#![allow(unsafe_code)]
use data::PrivateStyleData;
use element_state::ElementState;
use properties::{ComputedValues, PropertyDeclaration, PropertyDeclarationBlock};
use restyle_hints::{ElementSnapshot, RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint};
use selector_impl::ElementExt;
use selectors::Element;
use selectors::matching::DeclarationBlock;
use smallvec::VecLike;
use std::cell::{Ref, RefMut};
use std::marker::PhantomData;
use std::ops::BitOr;
use std::sync::Arc;
use string_cache::{Atom, Namespace};
/// Opaque type stored in type-unsafe work queues for parallel layout.
/// Must be transmutable to and from TNode.
pub type UnsafeNode = (usize, usize);
/// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed
/// back into a non-opaque representation. The only safe operation that can be
/// performed on this node is to compare it to another opaque handle or to another
/// OpaqueNode.
///
/// Layout and Graphics use this to safely represent nodes for comparison purposes.
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[derive(Clone, PartialEq, Copy, Debug, HeapSizeOf, Hash, Eq, Deserialize, Serialize)]
pub struct OpaqueNode(pub usize);
impl OpaqueNode {
/// Returns the address of this node, for debugging purposes.
#[inline]
pub fn id(&self) -> usize {
let OpaqueNode(pointer) = *self;
pointer
}
}
pub trait TRestyleDamage : BitOr<Output=Self> + Copy {
fn compute(old: Option<&Arc<ComputedValues>>, new: &ComputedValues) -> Self;
fn rebuild_and_reflow() -> Self;
}
pub trait TNode<'ln> : Sized + Copy + Clone {
type ConcreteElement: TElement<'ln, ConcreteNode = Self, ConcreteDocument = Self::ConcreteDocument>;
type ConcreteDocument: TDocument<'ln, ConcreteNode = Self, ConcreteElement = Self::ConcreteElement>;
type ConcreteRestyleDamage: TRestyleDamage;
fn to_unsafe(&self) -> UnsafeNode;
unsafe fn from_unsafe(n: &UnsafeNode) -> Self;
/// Returns whether this is a text node. It turns out that this is all the style system cares
/// about, and thus obviates the need to compute the full type id, which would be expensive in
/// Gecko.
fn is_text_node(&self) -> bool;
fn is_element(&self) -> bool;
fn dump(self);
fn traverse_preorder(self) -> TreeIterator<'ln, Self> {
TreeIterator::new(self)
}
/// Returns an iterator over this node's children.
fn children(self) -> ChildrenIterator<'ln, Self> {
ChildrenIterator {
current: self.first_child(),
phantom: PhantomData,
}
}
fn rev_children(self) -> ReverseChildrenIterator<'ln, Self> {
ReverseChildrenIterator {
current: self.last_child(),
phantom: PhantomData,
}
}
/// Converts self into an `OpaqueNode`.
|
/// initialized.
///
/// FIXME(pcwalton): Do this as part of fragment building instead of in a traversal.
fn initialize_data(self);
/// While doing a reflow, the node at the root has no parent, as far as we're
/// concerned. This method returns `None` at the reflow root.
fn layout_parent_node(self, reflow_root: OpaqueNode) -> Option<Self>;
fn debug_id(self) -> usize;
fn as_element(&self) -> Option<Self::ConcreteElement>;
fn as_document(&self) -> Option<Self::ConcreteDocument>;
fn children_count(&self) -> u32;
fn has_changed(&self) -> bool;
unsafe fn set_changed(&self, value: bool);
fn is_dirty(&self) -> bool;
unsafe fn set_dirty(&self, value: bool);
fn has_dirty_descendants(&self) -> bool;
unsafe fn set_dirty_descendants(&self, value: bool);
fn dirty_self(&self) {
unsafe {
self.set_dirty(true);
self.set_dirty_descendants(true);
}
}
fn dirty_descendants(&self) {
for ref child in self.children() {
child.dirty_self();
child.dirty_descendants();
}
}
fn can_be_fragmented(&self) -> bool;
unsafe fn set_can_be_fragmented(&self, value: bool);
/// Borrows the PrivateStyleData without checks.
#[inline(always)]
unsafe fn borrow_data_unchecked(&self)
-> Option<*const PrivateStyleData<<Self::ConcreteElement as Element>::Impl>>;
/// Borrows the PrivateStyleData immutably. Fails on a conflicting borrow.
#[inline(always)]
fn borrow_data(&self)
-> Option<Ref<PrivateStyleData<<Self::ConcreteElement as Element>::Impl>>>;
/// Borrows the PrivateStyleData mutably. Fails on a conflicting borrow.
#[inline(always)]
fn mutate_data(&self)
-> Option<RefMut<PrivateStyleData<<Self::ConcreteElement as Element>::Impl>>>;
/// Get the description of how to account for recent style changes.
fn restyle_damage(self) -> Self::ConcreteRestyleDamage;
/// Set the restyle damage field.
fn set_restyle_damage(self, damage: Self::ConcreteRestyleDamage);
fn parent_node(&self) -> Option<Self>;
fn first_child(&self) -> Option<Self>;
fn last_child(&self) -> Option<Self>;
fn prev_sibling(&self) -> Option<Self>;
fn next_sibling(&self) -> Option<Self>;
/// Returns the style results for the given node. If CSS selector matching
/// has not yet been performed, fails.
fn style(&'ln self) -> Ref<Arc<ComputedValues>> {
Ref::map(self.borrow_data().unwrap(), |data| data.style.as_ref().unwrap())
}
/// Removes the style from this node.
fn unstyle(self) {
self.mutate_data().unwrap().style = None;
}
}
pub trait TDocument<'ld> : Sized + Copy + Clone {
type ConcreteNode: TNode<'ld, ConcreteElement = Self::ConcreteElement, ConcreteDocument = Self>;
type ConcreteElement: TElement<'ld, ConcreteNode = Self::ConcreteNode, ConcreteDocument = Self>;
fn as_node(&self) -> Self::ConcreteNode;
fn root_node(&self) -> Option<Self::ConcreteNode>;
fn drain_modified_elements(&self) -> Vec<(Self::ConcreteElement, ElementSnapshot)>;
}
pub trait TElement<'le> : Sized + Copy + Clone + ElementExt {
type ConcreteNode: TNode<'le, ConcreteElement = Self, ConcreteDocument = Self::ConcreteDocument>;
type ConcreteDocument: TDocument<'le, ConcreteNode = Self::ConcreteNode, ConcreteElement = Self>;
fn as_node(&self) -> Self::ConcreteNode;
fn style_attribute(&self) -> &'le Option<PropertyDeclarationBlock>;
fn get_state(&self) -> ElementState;
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, &mut V)
where V: VecLike<DeclarationBlock<Vec<PropertyDeclaration>>>;
fn get_attr<'a>(&'a self, namespace: &Namespace, attr: &Atom) -> Option<&'a str>;
fn get_attrs<'a>(&'a self, attr: &Atom) -> Vec<&'a str>;
/// Properly marks nodes as dirty in response to restyle hints.
fn note_restyle_hint(&self, mut hint: RestyleHint) {
// Bail early if there's no restyling to do.
if hint.is_empty() {
return;
}
// If the restyle hint is non-empty, we need to restyle either this element
// or one of its siblings. Mark our ancestor chain as having dirty descendants.
let node = self.as_node();
let mut curr = node;
while let Some(parent) = curr.parent_node() {
if parent.has_dirty_descendants() { break }
unsafe { parent.set_dirty_descendants(true); }
curr = parent;
}
// Process hints.
if hint.contains(RESTYLE_SELF) {
node.dirty_self();
// FIXME(bholley, #8438): We currently need to RESTYLE_DESCENDANTS in the
// RESTYLE_SELF case in order to make sure "inherit" style structs propagate
// properly. See the explanation in the github issue.
hint.insert(RESTYLE_DESCENDANTS);
}
if hint.contains(RESTYLE_DESCENDANTS) {
unsafe { node.set_dirty_descendants(true); }
node.dirty_descendants();
}
if hint.contains(RESTYLE_LATER_SIBLINGS) {
let mut next = ::selectors::Element::next_sibling_element(self);
while let Some(sib) = next {
let sib_node = sib.as_node();
sib_node.dirty_self();
sib_node.dirty_descendants();
next = ::selectors::Element::next_sibling_element(&sib);
}
}
}
}
pub struct TreeIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
stack: Vec<ConcreteNode>,
// Satisfy the compiler about the unused lifetime.
phantom: PhantomData<&'a ()>,
}
impl<'a, ConcreteNode> TreeIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
fn new(root: ConcreteNode) -> TreeIterator<'a, ConcreteNode> {
let mut stack = vec!();
stack.push(root);
TreeIterator {
stack: stack,
phantom: PhantomData,
}
}
}
impl<'a, ConcreteNode> Iterator for TreeIterator<'a, ConcreteNode>
where ConcreteNode: TNode<'a> {
type Item = ConcreteNode;
fn next(&mut self) -> Option<ConcreteNode> {
let ret = self.stack.pop();
ret.map(|node| self.stack.extend(node.rev_children()));
ret
}
}
pub struct ChildrenIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
current: Option<ConcreteNode>,
// Satisfy the compiler about the unused lifetime.
phantom: PhantomData<&'a ()>,
}
impl<'a, ConcreteNode> Iterator for ChildrenIterator<'a, ConcreteNode>
where ConcreteNode: TNode<'a> {
type Item = ConcreteNode;
fn next(&mut self) -> Option<ConcreteNode> {
let node = self.current;
self.current = node.and_then(|node| node.next_sibling());
node
}
}
pub struct ReverseChildrenIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
current: Option<ConcreteNode>,
// Satisfy the compiler about the unused lifetime.
phantom: PhantomData<&'a ()>,
}
impl<'a, ConcreteNode> Iterator for ReverseChildrenIterator<'a, ConcreteNode>
where ConcreteNode: TNode<'a> {
type Item = ConcreteNode;
fn next(&mut self) -> Option<ConcreteNode> {
let node = self.current;
self.current = node.and_then(|node| node.prev_sibling());
node
}
}
|
fn opaque(&self) -> OpaqueNode;
/// Initializes style and layout data for the node. No-op if the data is already
|
random_line_split
|
dom.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/. */
#![allow(unsafe_code)]
use data::PrivateStyleData;
use element_state::ElementState;
use properties::{ComputedValues, PropertyDeclaration, PropertyDeclarationBlock};
use restyle_hints::{ElementSnapshot, RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint};
use selector_impl::ElementExt;
use selectors::Element;
use selectors::matching::DeclarationBlock;
use smallvec::VecLike;
use std::cell::{Ref, RefMut};
use std::marker::PhantomData;
use std::ops::BitOr;
use std::sync::Arc;
use string_cache::{Atom, Namespace};
/// Opaque type stored in type-unsafe work queues for parallel layout.
/// Must be transmutable to and from TNode.
pub type UnsafeNode = (usize, usize);
/// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed
/// back into a non-opaque representation. The only safe operation that can be
/// performed on this node is to compare it to another opaque handle or to another
/// OpaqueNode.
///
/// Layout and Graphics use this to safely represent nodes for comparison purposes.
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[derive(Clone, PartialEq, Copy, Debug, HeapSizeOf, Hash, Eq, Deserialize, Serialize)]
pub struct OpaqueNode(pub usize);
impl OpaqueNode {
/// Returns the address of this node, for debugging purposes.
#[inline]
pub fn id(&self) -> usize {
let OpaqueNode(pointer) = *self;
pointer
}
}
pub trait TRestyleDamage : BitOr<Output=Self> + Copy {
fn compute(old: Option<&Arc<ComputedValues>>, new: &ComputedValues) -> Self;
fn rebuild_and_reflow() -> Self;
}
pub trait TNode<'ln> : Sized + Copy + Clone {
type ConcreteElement: TElement<'ln, ConcreteNode = Self, ConcreteDocument = Self::ConcreteDocument>;
type ConcreteDocument: TDocument<'ln, ConcreteNode = Self, ConcreteElement = Self::ConcreteElement>;
type ConcreteRestyleDamage: TRestyleDamage;
fn to_unsafe(&self) -> UnsafeNode;
unsafe fn from_unsafe(n: &UnsafeNode) -> Self;
/// Returns whether this is a text node. It turns out that this is all the style system cares
/// about, and thus obviates the need to compute the full type id, which would be expensive in
/// Gecko.
fn is_text_node(&self) -> bool;
fn is_element(&self) -> bool;
fn dump(self);
fn traverse_preorder(self) -> TreeIterator<'ln, Self> {
TreeIterator::new(self)
}
/// Returns an iterator over this node's children.
fn children(self) -> ChildrenIterator<'ln, Self> {
ChildrenIterator {
current: self.first_child(),
phantom: PhantomData,
}
}
fn rev_children(self) -> ReverseChildrenIterator<'ln, Self> {
ReverseChildrenIterator {
current: self.last_child(),
phantom: PhantomData,
}
}
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// Initializes style and layout data for the node. No-op if the data is already
/// initialized.
///
/// FIXME(pcwalton): Do this as part of fragment building instead of in a traversal.
fn initialize_data(self);
/// While doing a reflow, the node at the root has no parent, as far as we're
/// concerned. This method returns `None` at the reflow root.
fn layout_parent_node(self, reflow_root: OpaqueNode) -> Option<Self>;
fn debug_id(self) -> usize;
fn as_element(&self) -> Option<Self::ConcreteElement>;
fn as_document(&self) -> Option<Self::ConcreteDocument>;
fn children_count(&self) -> u32;
fn has_changed(&self) -> bool;
unsafe fn set_changed(&self, value: bool);
fn is_dirty(&self) -> bool;
unsafe fn set_dirty(&self, value: bool);
fn has_dirty_descendants(&self) -> bool;
unsafe fn set_dirty_descendants(&self, value: bool);
fn dirty_self(&self) {
unsafe {
self.set_dirty(true);
self.set_dirty_descendants(true);
}
}
fn dirty_descendants(&self) {
for ref child in self.children() {
child.dirty_self();
child.dirty_descendants();
}
}
fn can_be_fragmented(&self) -> bool;
unsafe fn set_can_be_fragmented(&self, value: bool);
/// Borrows the PrivateStyleData without checks.
#[inline(always)]
unsafe fn borrow_data_unchecked(&self)
-> Option<*const PrivateStyleData<<Self::ConcreteElement as Element>::Impl>>;
/// Borrows the PrivateStyleData immutably. Fails on a conflicting borrow.
#[inline(always)]
fn borrow_data(&self)
-> Option<Ref<PrivateStyleData<<Self::ConcreteElement as Element>::Impl>>>;
/// Borrows the PrivateStyleData mutably. Fails on a conflicting borrow.
#[inline(always)]
fn mutate_data(&self)
-> Option<RefMut<PrivateStyleData<<Self::ConcreteElement as Element>::Impl>>>;
/// Get the description of how to account for recent style changes.
fn restyle_damage(self) -> Self::ConcreteRestyleDamage;
/// Set the restyle damage field.
fn set_restyle_damage(self, damage: Self::ConcreteRestyleDamage);
fn parent_node(&self) -> Option<Self>;
fn first_child(&self) -> Option<Self>;
fn last_child(&self) -> Option<Self>;
fn prev_sibling(&self) -> Option<Self>;
fn next_sibling(&self) -> Option<Self>;
/// Returns the style results for the given node. If CSS selector matching
/// has not yet been performed, fails.
fn style(&'ln self) -> Ref<Arc<ComputedValues>> {
Ref::map(self.borrow_data().unwrap(), |data| data.style.as_ref().unwrap())
}
/// Removes the style from this node.
fn unstyle(self) {
self.mutate_data().unwrap().style = None;
}
}
pub trait TDocument<'ld> : Sized + Copy + Clone {
type ConcreteNode: TNode<'ld, ConcreteElement = Self::ConcreteElement, ConcreteDocument = Self>;
type ConcreteElement: TElement<'ld, ConcreteNode = Self::ConcreteNode, ConcreteDocument = Self>;
fn as_node(&self) -> Self::ConcreteNode;
fn root_node(&self) -> Option<Self::ConcreteNode>;
fn drain_modified_elements(&self) -> Vec<(Self::ConcreteElement, ElementSnapshot)>;
}
pub trait TElement<'le> : Sized + Copy + Clone + ElementExt {
type ConcreteNode: TNode<'le, ConcreteElement = Self, ConcreteDocument = Self::ConcreteDocument>;
type ConcreteDocument: TDocument<'le, ConcreteNode = Self::ConcreteNode, ConcreteElement = Self>;
fn as_node(&self) -> Self::ConcreteNode;
fn style_attribute(&self) -> &'le Option<PropertyDeclarationBlock>;
fn get_state(&self) -> ElementState;
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, &mut V)
where V: VecLike<DeclarationBlock<Vec<PropertyDeclaration>>>;
fn get_attr<'a>(&'a self, namespace: &Namespace, attr: &Atom) -> Option<&'a str>;
fn get_attrs<'a>(&'a self, attr: &Atom) -> Vec<&'a str>;
/// Properly marks nodes as dirty in response to restyle hints.
fn note_restyle_hint(&self, mut hint: RestyleHint) {
// Bail early if there's no restyling to do.
if hint.is_empty() {
return;
}
// If the restyle hint is non-empty, we need to restyle either this element
// or one of its siblings. Mark our ancestor chain as having dirty descendants.
let node = self.as_node();
let mut curr = node;
while let Some(parent) = curr.parent_node() {
if parent.has_dirty_descendants() { break }
unsafe { parent.set_dirty_descendants(true); }
curr = parent;
}
// Process hints.
if hint.contains(RESTYLE_SELF) {
node.dirty_self();
// FIXME(bholley, #8438): We currently need to RESTYLE_DESCENDANTS in the
// RESTYLE_SELF case in order to make sure "inherit" style structs propagate
// properly. See the explanation in the github issue.
hint.insert(RESTYLE_DESCENDANTS);
}
if hint.contains(RESTYLE_DESCENDANTS) {
unsafe { node.set_dirty_descendants(true); }
node.dirty_descendants();
}
if hint.contains(RESTYLE_LATER_SIBLINGS)
|
}
}
pub struct TreeIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
stack: Vec<ConcreteNode>,
// Satisfy the compiler about the unused lifetime.
phantom: PhantomData<&'a ()>,
}
impl<'a, ConcreteNode> TreeIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
fn new(root: ConcreteNode) -> TreeIterator<'a, ConcreteNode> {
let mut stack = vec!();
stack.push(root);
TreeIterator {
stack: stack,
phantom: PhantomData,
}
}
}
impl<'a, ConcreteNode> Iterator for TreeIterator<'a, ConcreteNode>
where ConcreteNode: TNode<'a> {
type Item = ConcreteNode;
fn next(&mut self) -> Option<ConcreteNode> {
let ret = self.stack.pop();
ret.map(|node| self.stack.extend(node.rev_children()));
ret
}
}
pub struct ChildrenIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
current: Option<ConcreteNode>,
// Satisfy the compiler about the unused lifetime.
phantom: PhantomData<&'a ()>,
}
impl<'a, ConcreteNode> Iterator for ChildrenIterator<'a, ConcreteNode>
where ConcreteNode: TNode<'a> {
type Item = ConcreteNode;
fn next(&mut self) -> Option<ConcreteNode> {
let node = self.current;
self.current = node.and_then(|node| node.next_sibling());
node
}
}
pub struct ReverseChildrenIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
current: Option<ConcreteNode>,
// Satisfy the compiler about the unused lifetime.
phantom: PhantomData<&'a ()>,
}
impl<'a, ConcreteNode> Iterator for ReverseChildrenIterator<'a, ConcreteNode>
where ConcreteNode: TNode<'a> {
type Item = ConcreteNode;
fn next(&mut self) -> Option<ConcreteNode> {
let node = self.current;
self.current = node.and_then(|node| node.prev_sibling());
node
}
}
|
{
let mut next = ::selectors::Element::next_sibling_element(self);
while let Some(sib) = next {
let sib_node = sib.as_node();
sib_node.dirty_self();
sib_node.dirty_descendants();
next = ::selectors::Element::next_sibling_element(&sib);
}
}
|
conditional_block
|
dom.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/. */
#![allow(unsafe_code)]
use data::PrivateStyleData;
use element_state::ElementState;
use properties::{ComputedValues, PropertyDeclaration, PropertyDeclarationBlock};
use restyle_hints::{ElementSnapshot, RESTYLE_DESCENDANTS, RESTYLE_LATER_SIBLINGS, RESTYLE_SELF, RestyleHint};
use selector_impl::ElementExt;
use selectors::Element;
use selectors::matching::DeclarationBlock;
use smallvec::VecLike;
use std::cell::{Ref, RefMut};
use std::marker::PhantomData;
use std::ops::BitOr;
use std::sync::Arc;
use string_cache::{Atom, Namespace};
/// Opaque type stored in type-unsafe work queues for parallel layout.
/// Must be transmutable to and from TNode.
pub type UnsafeNode = (usize, usize);
/// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed
/// back into a non-opaque representation. The only safe operation that can be
/// performed on this node is to compare it to another opaque handle or to another
/// OpaqueNode.
///
/// Layout and Graphics use this to safely represent nodes for comparison purposes.
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout
/// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for
/// locality reasons. Using `OpaqueNode` enforces this invariant.
#[derive(Clone, PartialEq, Copy, Debug, HeapSizeOf, Hash, Eq, Deserialize, Serialize)]
pub struct OpaqueNode(pub usize);
impl OpaqueNode {
/// Returns the address of this node, for debugging purposes.
#[inline]
pub fn id(&self) -> usize {
let OpaqueNode(pointer) = *self;
pointer
}
}
pub trait TRestyleDamage : BitOr<Output=Self> + Copy {
fn compute(old: Option<&Arc<ComputedValues>>, new: &ComputedValues) -> Self;
fn rebuild_and_reflow() -> Self;
}
pub trait TNode<'ln> : Sized + Copy + Clone {
type ConcreteElement: TElement<'ln, ConcreteNode = Self, ConcreteDocument = Self::ConcreteDocument>;
type ConcreteDocument: TDocument<'ln, ConcreteNode = Self, ConcreteElement = Self::ConcreteElement>;
type ConcreteRestyleDamage: TRestyleDamage;
fn to_unsafe(&self) -> UnsafeNode;
unsafe fn from_unsafe(n: &UnsafeNode) -> Self;
/// Returns whether this is a text node. It turns out that this is all the style system cares
/// about, and thus obviates the need to compute the full type id, which would be expensive in
/// Gecko.
fn is_text_node(&self) -> bool;
fn is_element(&self) -> bool;
fn dump(self);
fn traverse_preorder(self) -> TreeIterator<'ln, Self> {
TreeIterator::new(self)
}
/// Returns an iterator over this node's children.
fn children(self) -> ChildrenIterator<'ln, Self> {
ChildrenIterator {
current: self.first_child(),
phantom: PhantomData,
}
}
fn rev_children(self) -> ReverseChildrenIterator<'ln, Self> {
ReverseChildrenIterator {
current: self.last_child(),
phantom: PhantomData,
}
}
/// Converts self into an `OpaqueNode`.
fn opaque(&self) -> OpaqueNode;
/// Initializes style and layout data for the node. No-op if the data is already
/// initialized.
///
/// FIXME(pcwalton): Do this as part of fragment building instead of in a traversal.
fn initialize_data(self);
/// While doing a reflow, the node at the root has no parent, as far as we're
/// concerned. This method returns `None` at the reflow root.
fn layout_parent_node(self, reflow_root: OpaqueNode) -> Option<Self>;
fn debug_id(self) -> usize;
fn as_element(&self) -> Option<Self::ConcreteElement>;
fn as_document(&self) -> Option<Self::ConcreteDocument>;
fn children_count(&self) -> u32;
fn has_changed(&self) -> bool;
unsafe fn set_changed(&self, value: bool);
fn is_dirty(&self) -> bool;
unsafe fn set_dirty(&self, value: bool);
fn has_dirty_descendants(&self) -> bool;
unsafe fn set_dirty_descendants(&self, value: bool);
fn dirty_self(&self) {
unsafe {
self.set_dirty(true);
self.set_dirty_descendants(true);
}
}
fn dirty_descendants(&self) {
for ref child in self.children() {
child.dirty_self();
child.dirty_descendants();
}
}
fn can_be_fragmented(&self) -> bool;
unsafe fn set_can_be_fragmented(&self, value: bool);
/// Borrows the PrivateStyleData without checks.
#[inline(always)]
unsafe fn borrow_data_unchecked(&self)
-> Option<*const PrivateStyleData<<Self::ConcreteElement as Element>::Impl>>;
/// Borrows the PrivateStyleData immutably. Fails on a conflicting borrow.
#[inline(always)]
fn borrow_data(&self)
-> Option<Ref<PrivateStyleData<<Self::ConcreteElement as Element>::Impl>>>;
/// Borrows the PrivateStyleData mutably. Fails on a conflicting borrow.
#[inline(always)]
fn mutate_data(&self)
-> Option<RefMut<PrivateStyleData<<Self::ConcreteElement as Element>::Impl>>>;
/// Get the description of how to account for recent style changes.
fn restyle_damage(self) -> Self::ConcreteRestyleDamage;
/// Set the restyle damage field.
fn set_restyle_damage(self, damage: Self::ConcreteRestyleDamage);
fn parent_node(&self) -> Option<Self>;
fn first_child(&self) -> Option<Self>;
fn last_child(&self) -> Option<Self>;
fn prev_sibling(&self) -> Option<Self>;
fn next_sibling(&self) -> Option<Self>;
/// Returns the style results for the given node. If CSS selector matching
/// has not yet been performed, fails.
fn style(&'ln self) -> Ref<Arc<ComputedValues>> {
Ref::map(self.borrow_data().unwrap(), |data| data.style.as_ref().unwrap())
}
/// Removes the style from this node.
fn unstyle(self) {
self.mutate_data().unwrap().style = None;
}
}
pub trait TDocument<'ld> : Sized + Copy + Clone {
type ConcreteNode: TNode<'ld, ConcreteElement = Self::ConcreteElement, ConcreteDocument = Self>;
type ConcreteElement: TElement<'ld, ConcreteNode = Self::ConcreteNode, ConcreteDocument = Self>;
fn as_node(&self) -> Self::ConcreteNode;
fn root_node(&self) -> Option<Self::ConcreteNode>;
fn drain_modified_elements(&self) -> Vec<(Self::ConcreteElement, ElementSnapshot)>;
}
pub trait TElement<'le> : Sized + Copy + Clone + ElementExt {
type ConcreteNode: TNode<'le, ConcreteElement = Self, ConcreteDocument = Self::ConcreteDocument>;
type ConcreteDocument: TDocument<'le, ConcreteNode = Self::ConcreteNode, ConcreteElement = Self>;
fn as_node(&self) -> Self::ConcreteNode;
fn style_attribute(&self) -> &'le Option<PropertyDeclarationBlock>;
fn get_state(&self) -> ElementState;
fn synthesize_presentational_hints_for_legacy_attributes<V>(&self, &mut V)
where V: VecLike<DeclarationBlock<Vec<PropertyDeclaration>>>;
fn get_attr<'a>(&'a self, namespace: &Namespace, attr: &Atom) -> Option<&'a str>;
fn get_attrs<'a>(&'a self, attr: &Atom) -> Vec<&'a str>;
/// Properly marks nodes as dirty in response to restyle hints.
fn note_restyle_hint(&self, mut hint: RestyleHint) {
// Bail early if there's no restyling to do.
if hint.is_empty() {
return;
}
// If the restyle hint is non-empty, we need to restyle either this element
// or one of its siblings. Mark our ancestor chain as having dirty descendants.
let node = self.as_node();
let mut curr = node;
while let Some(parent) = curr.parent_node() {
if parent.has_dirty_descendants() { break }
unsafe { parent.set_dirty_descendants(true); }
curr = parent;
}
// Process hints.
if hint.contains(RESTYLE_SELF) {
node.dirty_self();
// FIXME(bholley, #8438): We currently need to RESTYLE_DESCENDANTS in the
// RESTYLE_SELF case in order to make sure "inherit" style structs propagate
// properly. See the explanation in the github issue.
hint.insert(RESTYLE_DESCENDANTS);
}
if hint.contains(RESTYLE_DESCENDANTS) {
unsafe { node.set_dirty_descendants(true); }
node.dirty_descendants();
}
if hint.contains(RESTYLE_LATER_SIBLINGS) {
let mut next = ::selectors::Element::next_sibling_element(self);
while let Some(sib) = next {
let sib_node = sib.as_node();
sib_node.dirty_self();
sib_node.dirty_descendants();
next = ::selectors::Element::next_sibling_element(&sib);
}
}
}
}
pub struct TreeIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
stack: Vec<ConcreteNode>,
// Satisfy the compiler about the unused lifetime.
phantom: PhantomData<&'a ()>,
}
impl<'a, ConcreteNode> TreeIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
fn new(root: ConcreteNode) -> TreeIterator<'a, ConcreteNode> {
let mut stack = vec!();
stack.push(root);
TreeIterator {
stack: stack,
phantom: PhantomData,
}
}
}
impl<'a, ConcreteNode> Iterator for TreeIterator<'a, ConcreteNode>
where ConcreteNode: TNode<'a> {
type Item = ConcreteNode;
fn next(&mut self) -> Option<ConcreteNode> {
let ret = self.stack.pop();
ret.map(|node| self.stack.extend(node.rev_children()));
ret
}
}
pub struct ChildrenIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
current: Option<ConcreteNode>,
// Satisfy the compiler about the unused lifetime.
phantom: PhantomData<&'a ()>,
}
impl<'a, ConcreteNode> Iterator for ChildrenIterator<'a, ConcreteNode>
where ConcreteNode: TNode<'a> {
type Item = ConcreteNode;
fn
|
(&mut self) -> Option<ConcreteNode> {
let node = self.current;
self.current = node.and_then(|node| node.next_sibling());
node
}
}
pub struct ReverseChildrenIterator<'a, ConcreteNode> where ConcreteNode: TNode<'a> {
current: Option<ConcreteNode>,
// Satisfy the compiler about the unused lifetime.
phantom: PhantomData<&'a ()>,
}
impl<'a, ConcreteNode> Iterator for ReverseChildrenIterator<'a, ConcreteNode>
where ConcreteNode: TNode<'a> {
type Item = ConcreteNode;
fn next(&mut self) -> Option<ConcreteNode> {
let node = self.current;
self.current = node.and_then(|node| node.prev_sibling());
node
}
}
|
next
|
identifier_name
|
connection.rs
|
//! The connection module contains the Connection struct, that provides an interface for a Server
//! Query connection.
use channel::ChannelList;
use client::ClientList;
use command::Command;
use error;
use error::{Error, SQError};
use map::*;
use std::fmt;
use std::io::prelude::*;
use std::io::BufReader;
use std::net;
use std::string::String;
/// Connection provides an interface for a Server Query connection.
#[derive(Debug)]
pub struct Connection {
addr: net::SocketAddrV4,
conn: BufReader<net::TcpStream>,
}
impl Connection {
/// creates a new Connection from an adress given as a string reference.
pub fn new(addr: &str) -> error::Result<Connection> {
let addr = addr.to_string();
let a = addr.parse()?;
let c = net::TcpStream::connect(a)?;
let mut connection = Connection {
addr: a,
conn: BufReader::new(c),
};
let mut tmp = String::new();
connection.conn.read_line(&mut tmp)?;
if tmp.trim()!= "TS3" {
return Err(From::from("the given server is not a TS3 server"));
}
connection.read_line(&mut tmp)?;
Ok(connection)
}
fn read_line<'a>(&mut self, buf: &'a mut String) -> error::Result<&'a str> {
let _ = self.conn.read_line(buf)?;
Ok(buf.trim_left_matches(char::is_control))
}
fn get_stream_mut(&mut self) -> &mut net::TcpStream {
self.conn.get_mut()
}
/// sends a given command to the Server Query server and returns the answer as a String, or
/// the error.
pub fn send_command<C>(&mut self, command: &C) -> error::Result<String>
where
C: Command,
{
let command = command.string();
if command.is_empty() {
return Err(Error::from("no command"));
}
writeln!(self.get_stream_mut(), "{}", command)?;
self.get_stream_mut().flush()?;
let mut result = String::new();
loop {
let mut line = String::new();
let line = self.read_line(&mut line)?;
let ok = SQError::parse_is_ok(line)?;
if ok {
break;
}
result += line; // + "\n";
}
Ok(result)
}
pub fn send_command_to_map<C>(&mut self, command: &C) -> error::Result<StringMap>
where
C: Command,
{
let result = self.send_command(command)?;
Ok(to_map(&result))
}
pub fn send_command_vec<C>(&mut self, commands: C) -> error::Result<Vec<String>>
where
C: IntoIterator,
C::Item: Command,
{
let mut results = Vec::new();
for cmd in commands {
let res = self.send_command(&cmd)?;
results.push(res);
}
Ok(results)
}
/// sends the quit command to the server and shuts the Connection down.
pub fn quit(&mut self) -> error::Result<()> {
self.send_command(&"quit")?;
self.conn.get_ref().shutdown(net::Shutdown::Both)?;
Ok(())
}
/// sends the use command with the given id to the server.
pub fn use_server_id(&mut self, id: u64) -> error::Result<()> {
self.send_command(&format!("use {}", id)).map(|_| ())
}
/// sends the login command with the name and password to the server.
pub fn login(&mut self, name: &str, pw: &str) -> error::Result<()> {
self.send_command(&format!("login {} {}", name, pw))
.map(|_| ())
}
/// tries to change the nickname of the Server Query client.
pub fn change_nickname(&mut self, nickname: &str) -> error::Result<()> {
let map = self.send_command_to_map(&"whoami")?;
let id = map
.get("client_id")
.ok_or("error at collecting client_id")?;
let cmd = format!("clientupdate clid={} client_nickname={}", id, nickname);
let _ = self.send_command(&cmd)?;
Ok(())
}
/// sends the clientlist command to the server and parses the result.
pub fn clientlist(&mut self) -> error::Result<ClientList> {
let s = self.send_command(&"clientlist")?;
let cl = s.parse()?;
Ok(cl)
}
/// # common errors
/// If a client disconnects between the getting of the clientlist and the getting of the client
/// information, then there will be an error 512, because the client id is invalid.
pub fn clientlist_with_info(&mut self) -> error::Result<ClientList> {
let mut clients = self.clientlist()?;
for client in clients.as_mut().iter_mut() {
let command = format!("clientinfo clid={}", client.clid);
let str = self.send_command(&command)?;
let map = to_map(&str);
client.mut_from_map(&map);
}
|
let s = self.send_command(&"channellist")?;
let cl = s.parse()?;
Ok(cl)
}
/// # common errors
/// If a client disconnects between the getting of the clientlist and the getting of the client
/// information, then there will be an error 512, because the client id is invalid.
pub fn channellist_with_clients(&mut self) -> error::Result<ChannelList> {
let clients = self.clientlist_with_info()?;
let mut channels = self.channellist()?;
channels.merge_clients(&clients);
Ok(channels)
}
}
impl fmt::Display for Connection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.addr)
}
}
|
Ok(clients)
}
/// sends the channellist command to the server and parses the result.
pub fn channellist(&mut self) -> error::Result<ChannelList> {
|
random_line_split
|
connection.rs
|
//! The connection module contains the Connection struct, that provides an interface for a Server
//! Query connection.
use channel::ChannelList;
use client::ClientList;
use command::Command;
use error;
use error::{Error, SQError};
use map::*;
use std::fmt;
use std::io::prelude::*;
use std::io::BufReader;
use std::net;
use std::string::String;
/// Connection provides an interface for a Server Query connection.
#[derive(Debug)]
pub struct Connection {
addr: net::SocketAddrV4,
conn: BufReader<net::TcpStream>,
}
impl Connection {
/// creates a new Connection from an adress given as a string reference.
pub fn new(addr: &str) -> error::Result<Connection> {
let addr = addr.to_string();
let a = addr.parse()?;
let c = net::TcpStream::connect(a)?;
let mut connection = Connection {
addr: a,
conn: BufReader::new(c),
};
let mut tmp = String::new();
connection.conn.read_line(&mut tmp)?;
if tmp.trim()!= "TS3" {
return Err(From::from("the given server is not a TS3 server"));
}
connection.read_line(&mut tmp)?;
Ok(connection)
}
fn read_line<'a>(&mut self, buf: &'a mut String) -> error::Result<&'a str> {
let _ = self.conn.read_line(buf)?;
Ok(buf.trim_left_matches(char::is_control))
}
fn get_stream_mut(&mut self) -> &mut net::TcpStream {
self.conn.get_mut()
}
/// sends a given command to the Server Query server and returns the answer as a String, or
/// the error.
pub fn send_command<C>(&mut self, command: &C) -> error::Result<String>
where
C: Command,
{
let command = command.string();
if command.is_empty() {
return Err(Error::from("no command"));
}
writeln!(self.get_stream_mut(), "{}", command)?;
self.get_stream_mut().flush()?;
let mut result = String::new();
loop {
let mut line = String::new();
let line = self.read_line(&mut line)?;
let ok = SQError::parse_is_ok(line)?;
if ok {
break;
}
result += line; // + "\n";
}
Ok(result)
}
pub fn send_command_to_map<C>(&mut self, command: &C) -> error::Result<StringMap>
where
C: Command,
{
let result = self.send_command(command)?;
Ok(to_map(&result))
}
pub fn send_command_vec<C>(&mut self, commands: C) -> error::Result<Vec<String>>
where
C: IntoIterator,
C::Item: Command,
{
let mut results = Vec::new();
for cmd in commands {
let res = self.send_command(&cmd)?;
results.push(res);
}
Ok(results)
}
/// sends the quit command to the server and shuts the Connection down.
pub fn quit(&mut self) -> error::Result<()> {
self.send_command(&"quit")?;
self.conn.get_ref().shutdown(net::Shutdown::Both)?;
Ok(())
}
/// sends the use command with the given id to the server.
pub fn use_server_id(&mut self, id: u64) -> error::Result<()> {
self.send_command(&format!("use {}", id)).map(|_| ())
}
/// sends the login command with the name and password to the server.
pub fn login(&mut self, name: &str, pw: &str) -> error::Result<()> {
self.send_command(&format!("login {} {}", name, pw))
.map(|_| ())
}
/// tries to change the nickname of the Server Query client.
pub fn change_nickname(&mut self, nickname: &str) -> error::Result<()> {
let map = self.send_command_to_map(&"whoami")?;
let id = map
.get("client_id")
.ok_or("error at collecting client_id")?;
let cmd = format!("clientupdate clid={} client_nickname={}", id, nickname);
let _ = self.send_command(&cmd)?;
Ok(())
}
/// sends the clientlist command to the server and parses the result.
pub fn clientlist(&mut self) -> error::Result<ClientList> {
let s = self.send_command(&"clientlist")?;
let cl = s.parse()?;
Ok(cl)
}
/// # common errors
/// If a client disconnects between the getting of the clientlist and the getting of the client
/// information, then there will be an error 512, because the client id is invalid.
pub fn clientlist_with_info(&mut self) -> error::Result<ClientList>
|
/// sends the channellist command to the server and parses the result.
pub fn channellist(&mut self) -> error::Result<ChannelList> {
let s = self.send_command(&"channellist")?;
let cl = s.parse()?;
Ok(cl)
}
/// # common errors
/// If a client disconnects between the getting of the clientlist and the getting of the client
/// information, then there will be an error 512, because the client id is invalid.
pub fn channellist_with_clients(&mut self) -> error::Result<ChannelList> {
let clients = self.clientlist_with_info()?;
let mut channels = self.channellist()?;
channels.merge_clients(&clients);
Ok(channels)
}
}
impl fmt::Display for Connection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.addr)
}
}
|
{
let mut clients = self.clientlist()?;
for client in clients.as_mut().iter_mut() {
let command = format!("clientinfo clid={}", client.clid);
let str = self.send_command(&command)?;
let map = to_map(&str);
client.mut_from_map(&map);
}
Ok(clients)
}
|
identifier_body
|
connection.rs
|
//! The connection module contains the Connection struct, that provides an interface for a Server
//! Query connection.
use channel::ChannelList;
use client::ClientList;
use command::Command;
use error;
use error::{Error, SQError};
use map::*;
use std::fmt;
use std::io::prelude::*;
use std::io::BufReader;
use std::net;
use std::string::String;
/// Connection provides an interface for a Server Query connection.
#[derive(Debug)]
pub struct Connection {
addr: net::SocketAddrV4,
conn: BufReader<net::TcpStream>,
}
impl Connection {
/// creates a new Connection from an adress given as a string reference.
pub fn new(addr: &str) -> error::Result<Connection> {
let addr = addr.to_string();
let a = addr.parse()?;
let c = net::TcpStream::connect(a)?;
let mut connection = Connection {
addr: a,
conn: BufReader::new(c),
};
let mut tmp = String::new();
connection.conn.read_line(&mut tmp)?;
if tmp.trim()!= "TS3" {
return Err(From::from("the given server is not a TS3 server"));
}
connection.read_line(&mut tmp)?;
Ok(connection)
}
fn read_line<'a>(&mut self, buf: &'a mut String) -> error::Result<&'a str> {
let _ = self.conn.read_line(buf)?;
Ok(buf.trim_left_matches(char::is_control))
}
fn get_stream_mut(&mut self) -> &mut net::TcpStream {
self.conn.get_mut()
}
/// sends a given command to the Server Query server and returns the answer as a String, or
/// the error.
pub fn send_command<C>(&mut self, command: &C) -> error::Result<String>
where
C: Command,
{
let command = command.string();
if command.is_empty() {
return Err(Error::from("no command"));
}
writeln!(self.get_stream_mut(), "{}", command)?;
self.get_stream_mut().flush()?;
let mut result = String::new();
loop {
let mut line = String::new();
let line = self.read_line(&mut line)?;
let ok = SQError::parse_is_ok(line)?;
if ok {
break;
}
result += line; // + "\n";
}
Ok(result)
}
pub fn send_command_to_map<C>(&mut self, command: &C) -> error::Result<StringMap>
where
C: Command,
{
let result = self.send_command(command)?;
Ok(to_map(&result))
}
pub fn send_command_vec<C>(&mut self, commands: C) -> error::Result<Vec<String>>
where
C: IntoIterator,
C::Item: Command,
{
let mut results = Vec::new();
for cmd in commands {
let res = self.send_command(&cmd)?;
results.push(res);
}
Ok(results)
}
/// sends the quit command to the server and shuts the Connection down.
pub fn quit(&mut self) -> error::Result<()> {
self.send_command(&"quit")?;
self.conn.get_ref().shutdown(net::Shutdown::Both)?;
Ok(())
}
/// sends the use command with the given id to the server.
pub fn use_server_id(&mut self, id: u64) -> error::Result<()> {
self.send_command(&format!("use {}", id)).map(|_| ())
}
/// sends the login command with the name and password to the server.
pub fn login(&mut self, name: &str, pw: &str) -> error::Result<()> {
self.send_command(&format!("login {} {}", name, pw))
.map(|_| ())
}
/// tries to change the nickname of the Server Query client.
pub fn
|
(&mut self, nickname: &str) -> error::Result<()> {
let map = self.send_command_to_map(&"whoami")?;
let id = map
.get("client_id")
.ok_or("error at collecting client_id")?;
let cmd = format!("clientupdate clid={} client_nickname={}", id, nickname);
let _ = self.send_command(&cmd)?;
Ok(())
}
/// sends the clientlist command to the server and parses the result.
pub fn clientlist(&mut self) -> error::Result<ClientList> {
let s = self.send_command(&"clientlist")?;
let cl = s.parse()?;
Ok(cl)
}
/// # common errors
/// If a client disconnects between the getting of the clientlist and the getting of the client
/// information, then there will be an error 512, because the client id is invalid.
pub fn clientlist_with_info(&mut self) -> error::Result<ClientList> {
let mut clients = self.clientlist()?;
for client in clients.as_mut().iter_mut() {
let command = format!("clientinfo clid={}", client.clid);
let str = self.send_command(&command)?;
let map = to_map(&str);
client.mut_from_map(&map);
}
Ok(clients)
}
/// sends the channellist command to the server and parses the result.
pub fn channellist(&mut self) -> error::Result<ChannelList> {
let s = self.send_command(&"channellist")?;
let cl = s.parse()?;
Ok(cl)
}
/// # common errors
/// If a client disconnects between the getting of the clientlist and the getting of the client
/// information, then there will be an error 512, because the client id is invalid.
pub fn channellist_with_clients(&mut self) -> error::Result<ChannelList> {
let clients = self.clientlist_with_info()?;
let mut channels = self.channellist()?;
channels.merge_clients(&clients);
Ok(channels)
}
}
impl fmt::Display for Connection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.addr)
}
}
|
change_nickname
|
identifier_name
|
connection.rs
|
//! The connection module contains the Connection struct, that provides an interface for a Server
//! Query connection.
use channel::ChannelList;
use client::ClientList;
use command::Command;
use error;
use error::{Error, SQError};
use map::*;
use std::fmt;
use std::io::prelude::*;
use std::io::BufReader;
use std::net;
use std::string::String;
/// Connection provides an interface for a Server Query connection.
#[derive(Debug)]
pub struct Connection {
addr: net::SocketAddrV4,
conn: BufReader<net::TcpStream>,
}
impl Connection {
/// creates a new Connection from an adress given as a string reference.
pub fn new(addr: &str) -> error::Result<Connection> {
let addr = addr.to_string();
let a = addr.parse()?;
let c = net::TcpStream::connect(a)?;
let mut connection = Connection {
addr: a,
conn: BufReader::new(c),
};
let mut tmp = String::new();
connection.conn.read_line(&mut tmp)?;
if tmp.trim()!= "TS3"
|
connection.read_line(&mut tmp)?;
Ok(connection)
}
fn read_line<'a>(&mut self, buf: &'a mut String) -> error::Result<&'a str> {
let _ = self.conn.read_line(buf)?;
Ok(buf.trim_left_matches(char::is_control))
}
fn get_stream_mut(&mut self) -> &mut net::TcpStream {
self.conn.get_mut()
}
/// sends a given command to the Server Query server and returns the answer as a String, or
/// the error.
pub fn send_command<C>(&mut self, command: &C) -> error::Result<String>
where
C: Command,
{
let command = command.string();
if command.is_empty() {
return Err(Error::from("no command"));
}
writeln!(self.get_stream_mut(), "{}", command)?;
self.get_stream_mut().flush()?;
let mut result = String::new();
loop {
let mut line = String::new();
let line = self.read_line(&mut line)?;
let ok = SQError::parse_is_ok(line)?;
if ok {
break;
}
result += line; // + "\n";
}
Ok(result)
}
pub fn send_command_to_map<C>(&mut self, command: &C) -> error::Result<StringMap>
where
C: Command,
{
let result = self.send_command(command)?;
Ok(to_map(&result))
}
pub fn send_command_vec<C>(&mut self, commands: C) -> error::Result<Vec<String>>
where
C: IntoIterator,
C::Item: Command,
{
let mut results = Vec::new();
for cmd in commands {
let res = self.send_command(&cmd)?;
results.push(res);
}
Ok(results)
}
/// sends the quit command to the server and shuts the Connection down.
pub fn quit(&mut self) -> error::Result<()> {
self.send_command(&"quit")?;
self.conn.get_ref().shutdown(net::Shutdown::Both)?;
Ok(())
}
/// sends the use command with the given id to the server.
pub fn use_server_id(&mut self, id: u64) -> error::Result<()> {
self.send_command(&format!("use {}", id)).map(|_| ())
}
/// sends the login command with the name and password to the server.
pub fn login(&mut self, name: &str, pw: &str) -> error::Result<()> {
self.send_command(&format!("login {} {}", name, pw))
.map(|_| ())
}
/// tries to change the nickname of the Server Query client.
pub fn change_nickname(&mut self, nickname: &str) -> error::Result<()> {
let map = self.send_command_to_map(&"whoami")?;
let id = map
.get("client_id")
.ok_or("error at collecting client_id")?;
let cmd = format!("clientupdate clid={} client_nickname={}", id, nickname);
let _ = self.send_command(&cmd)?;
Ok(())
}
/// sends the clientlist command to the server and parses the result.
pub fn clientlist(&mut self) -> error::Result<ClientList> {
let s = self.send_command(&"clientlist")?;
let cl = s.parse()?;
Ok(cl)
}
/// # common errors
/// If a client disconnects between the getting of the clientlist and the getting of the client
/// information, then there will be an error 512, because the client id is invalid.
pub fn clientlist_with_info(&mut self) -> error::Result<ClientList> {
let mut clients = self.clientlist()?;
for client in clients.as_mut().iter_mut() {
let command = format!("clientinfo clid={}", client.clid);
let str = self.send_command(&command)?;
let map = to_map(&str);
client.mut_from_map(&map);
}
Ok(clients)
}
/// sends the channellist command to the server and parses the result.
pub fn channellist(&mut self) -> error::Result<ChannelList> {
let s = self.send_command(&"channellist")?;
let cl = s.parse()?;
Ok(cl)
}
/// # common errors
/// If a client disconnects between the getting of the clientlist and the getting of the client
/// information, then there will be an error 512, because the client id is invalid.
pub fn channellist_with_clients(&mut self) -> error::Result<ChannelList> {
let clients = self.clientlist_with_info()?;
let mut channels = self.channellist()?;
channels.merge_clients(&clients);
Ok(channels)
}
}
impl fmt::Display for Connection {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", &self.addr)
}
}
|
{
return Err(From::from("the given server is not a TS3 server"));
}
|
conditional_block
|
stop-instance.rs
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// The ID of the instance to stop.
#[structopt(short, long)]
instance_id: String,
/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
}
// Stops an instance.
// snippet-start:[ec2.rust.stop-instance]
async fn stop_instance(client: &Client, id: &str) -> Result<(), Error> {
client.stop_instances().instance_ids(id).send().await?;
println!("Stopped instance.");
Ok(())
}
// snippet-end:[ec2.rust.stop-instance]
/// Stops an Amazon EC2 instance.
/// # Arguments
///
/// * `-i INSTANCE-ID` - The ID of the instances to stop.
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
region,
instance_id,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose
|
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
stop_instance(&client, &instance_id).await
}
|
{
println!("EC2 client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Instance ID: {}", instance_id);
println!();
}
|
conditional_block
|
stop-instance.rs
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// The ID of the instance to stop.
#[structopt(short, long)]
instance_id: String,
/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
}
// Stops an instance.
// snippet-start:[ec2.rust.stop-instance]
async fn stop_instance(client: &Client, id: &str) -> Result<(), Error> {
client.stop_instances().instance_ids(id).send().await?;
println!("Stopped instance.");
Ok(())
}
// snippet-end:[ec2.rust.stop-instance]
/// Stops an Amazon EC2 instance.
/// # Arguments
///
/// * `-i INSTANCE-ID` - The ID of the instances to stop.
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn
|
() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
region,
instance_id,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("EC2 client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Instance ID: {}", instance_id);
println!();
}
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
stop_instance(&client, &instance_id).await
}
|
main
|
identifier_name
|
stop-instance.rs
|
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_ec2::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
#[structopt(short, long)]
region: Option<String>,
/// The ID of the instance to stop.
#[structopt(short, long)]
instance_id: String,
/// Whether to display additional information.
#[structopt(short, long)]
verbose: bool,
}
// Stops an instance.
// snippet-start:[ec2.rust.stop-instance]
async fn stop_instance(client: &Client, id: &str) -> Result<(), Error> {
client.stop_instances().instance_ids(id).send().await?;
println!("Stopped instance.");
Ok(())
}
// snippet-end:[ec2.rust.stop-instance]
/// Stops an Amazon EC2 instance.
/// # Arguments
|
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to display additional information.
#[tokio::main]
async fn main() -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
region,
instance_id,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if verbose {
println!("EC2 client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Instance ID: {}", instance_id);
println!();
}
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
stop_instance(&client, &instance_id).await
}
|
///
/// * `-i INSTANCE-ID` - The ID of the instances to stop.
/// * `[-r REGION]` - The Region in which the client is created.
|
random_line_split
|
config.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::fold::Folder;
use syntax::{ast, fold, attr};
use syntax::codemap;
use std::gc::{Gc, GC};
struct Context<'a> {
in_cfg: |attrs: &[ast::Attribute]|: 'a -> bool,
}
// Support conditional compilation by transforming the AST, stripping out
// any items that do not belong in the current configuration
pub fn strip_unconfigured_items(krate: ast::Crate) -> ast::Crate {
let config = krate.config.clone();
strip_items(krate, |attrs| in_cfg(config.as_slice(), attrs))
}
impl<'a> fold::Folder for Context<'a> {
fn fold_mod(&mut self, module: &ast::Mod) -> ast::Mod {
fold_mod(self, module)
}
fn fold_block(&mut self, block: ast::P<ast::Block>) -> ast::P<ast::Block> {
fold_block(self, block)
}
fn fold_foreign_mod(&mut self, foreign_mod: &ast::ForeignMod) -> ast::ForeignMod {
fold_foreign_mod(self, foreign_mod)
}
fn fold_item_underscore(&mut self, item: &ast::Item_) -> ast::Item_ {
fold_item_underscore(self, item)
}
fn fold_expr(&mut self, expr: Gc<ast::Expr>) -> Gc<ast::Expr> {
fold_expr(self, expr)
}
}
pub fn strip_items(krate: ast::Crate,
in_cfg: |attrs: &[ast::Attribute]| -> bool)
-> ast::Crate {
let mut ctxt = Context {
in_cfg: in_cfg,
};
ctxt.fold_crate(krate)
}
fn filter_view_item<'r>(cx: &mut Context, view_item: &'r ast::ViewItem)
-> Option<&'r ast::ViewItem> {
if view_item_in_cfg(cx, view_item) {
Some(view_item)
} else {
None
}
}
fn fold_mod(cx: &mut Context, m: &ast::Mod) -> ast::Mod {
let filtered_items: Vec<&Gc<ast::Item>> = m.items.iter()
.filter(|a| item_in_cfg(cx, &***a))
.collect();
let flattened_items = filtered_items.move_iter()
.flat_map(|&x| cx.fold_item(x).move_iter())
.collect();
let filtered_view_items = m.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::Mod {
inner: m.inner,
view_items: filtered_view_items,
items: flattened_items
}
}
fn filter_foreign_item(cx: &mut Context, item: Gc<ast::ForeignItem>)
-> Option<Gc<ast::ForeignItem>> {
if foreign_item_in_cfg(cx, &*item) {
Some(item)
} else {
None
}
}
fn fold_foreign_mod(cx: &mut Context, nm: &ast::ForeignMod) -> ast::ForeignMod {
let filtered_items = nm.items
.iter()
.filter_map(|a| filter_foreign_item(cx, *a))
.collect();
let filtered_view_items = nm.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::ForeignMod {
abi: nm.abi,
view_items: filtered_view_items,
items: filtered_items
}
}
fn fold_item_underscore(cx: &mut Context, item: &ast::Item_) -> ast::Item_ {
let item = match *item {
ast::ItemImpl(ref a, ref b, c, ref methods) => {
let methods = methods.iter().filter(|m| method_in_cfg(cx, &***m))
.map(|x| *x).collect();
ast::ItemImpl((*a).clone(), (*b).clone(), c, methods)
}
ast::ItemTrait(ref a, b, ref c, ref methods) => {
let methods = methods.iter()
.filter(|m| trait_method_in_cfg(cx, *m) )
.map(|x| (*x).clone())
.collect();
ast::ItemTrait((*a).clone(), b, (*c).clone(), methods)
}
ast::ItemStruct(ref def, ref generics) => {
ast::ItemStruct(fold_struct(cx, &**def), generics.clone())
}
ast::ItemEnum(ref def, ref generics) => {
let mut variants = def.variants.iter().map(|c| c.clone()).
filter_map(|v| {
if!(cx.in_cfg)(v.node.attrs.as_slice()) {
None
} else {
Some(match v.node.kind {
ast::TupleVariantKind(..) => v,
ast::StructVariantKind(ref def) => {
let def = fold_struct(cx, &**def);
box(GC) codemap::Spanned {
node: ast::Variant_ {
kind: ast::StructVariantKind(def.clone()),
..v.node.clone()
},
..*v
}
}
})
}
});
ast::ItemEnum(ast::EnumDef {
variants: variants.collect(),
}, generics.clone())
}
ref item => item.clone(),
};
fold::noop_fold_item_underscore(&item, cx)
}
fn fold_struct(cx: &mut Context, def: &ast::StructDef) -> Gc<ast::StructDef> {
let mut fields = def.fields.iter().map(|c| c.clone()).filter(|m| {
(cx.in_cfg)(m.node.attrs.as_slice())
});
box(GC) ast::StructDef {
fields: fields.collect(),
ctor_id: def.ctor_id,
super_struct: def.super_struct.clone(),
is_virtual: def.is_virtual,
}
}
fn retain_stmt(cx: &mut Context, stmt: Gc<ast::Stmt>) -> bool {
match stmt.node {
ast::StmtDecl(decl, _) => {
match decl.node {
ast::DeclItem(ref item) =>
|
_ => true
}
}
_ => true
}
}
fn fold_block(cx: &mut Context, b: ast::P<ast::Block>) -> ast::P<ast::Block> {
let resulting_stmts: Vec<&Gc<ast::Stmt>> =
b.stmts.iter().filter(|&a| retain_stmt(cx, *a)).collect();
let resulting_stmts = resulting_stmts.move_iter()
.flat_map(|stmt| cx.fold_stmt(&**stmt).move_iter())
.collect();
let filtered_view_items = b.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::P(ast::Block {
view_items: filtered_view_items,
stmts: resulting_stmts,
expr: b.expr.map(|x| cx.fold_expr(x)),
id: b.id,
rules: b.rules,
span: b.span,
})
}
fn fold_expr(cx: &mut Context, expr: Gc<ast::Expr>) -> Gc<ast::Expr> {
let expr = match expr.node {
ast::ExprMatch(ref m, ref arms) => {
let arms = arms.iter()
.filter(|a| (cx.in_cfg)(a.attrs.as_slice()))
.map(|a| a.clone())
.collect();
box(GC) ast::Expr {
id: expr.id,
span: expr.span.clone(),
node: ast::ExprMatch(m.clone(), arms),
}
}
_ => expr.clone()
};
fold::noop_fold_expr(expr, cx)
}
fn item_in_cfg(cx: &mut Context, item: &ast::Item) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn foreign_item_in_cfg(cx: &mut Context, item: &ast::ForeignItem) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn view_item_in_cfg(cx: &mut Context, item: &ast::ViewItem) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn method_in_cfg(cx: &mut Context, meth: &ast::Method) -> bool {
return (cx.in_cfg)(meth.attrs.as_slice());
}
fn trait_method_in_cfg(cx: &mut Context, meth: &ast::TraitMethod) -> bool {
match *meth {
ast::Required(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
ast::Provided(meth) => (cx.in_cfg)(meth.attrs.as_slice())
}
}
// Determine if an item should be translated in the current crate
// configuration based on the item's attributes
fn in_cfg(cfg: &[Gc<ast::MetaItem>], attrs: &[ast::Attribute]) -> bool {
attr::test_cfg(cfg, attrs.iter().map(|x| *x))
}
|
{
item_in_cfg(cx, &**item)
}
|
conditional_block
|
config.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::fold::Folder;
use syntax::{ast, fold, attr};
use syntax::codemap;
use std::gc::{Gc, GC};
struct Context<'a> {
in_cfg: |attrs: &[ast::Attribute]|: 'a -> bool,
}
// Support conditional compilation by transforming the AST, stripping out
// any items that do not belong in the current configuration
pub fn strip_unconfigured_items(krate: ast::Crate) -> ast::Crate
|
impl<'a> fold::Folder for Context<'a> {
fn fold_mod(&mut self, module: &ast::Mod) -> ast::Mod {
fold_mod(self, module)
}
fn fold_block(&mut self, block: ast::P<ast::Block>) -> ast::P<ast::Block> {
fold_block(self, block)
}
fn fold_foreign_mod(&mut self, foreign_mod: &ast::ForeignMod) -> ast::ForeignMod {
fold_foreign_mod(self, foreign_mod)
}
fn fold_item_underscore(&mut self, item: &ast::Item_) -> ast::Item_ {
fold_item_underscore(self, item)
}
fn fold_expr(&mut self, expr: Gc<ast::Expr>) -> Gc<ast::Expr> {
fold_expr(self, expr)
}
}
pub fn strip_items(krate: ast::Crate,
in_cfg: |attrs: &[ast::Attribute]| -> bool)
-> ast::Crate {
let mut ctxt = Context {
in_cfg: in_cfg,
};
ctxt.fold_crate(krate)
}
fn filter_view_item<'r>(cx: &mut Context, view_item: &'r ast::ViewItem)
-> Option<&'r ast::ViewItem> {
if view_item_in_cfg(cx, view_item) {
Some(view_item)
} else {
None
}
}
fn fold_mod(cx: &mut Context, m: &ast::Mod) -> ast::Mod {
let filtered_items: Vec<&Gc<ast::Item>> = m.items.iter()
.filter(|a| item_in_cfg(cx, &***a))
.collect();
let flattened_items = filtered_items.move_iter()
.flat_map(|&x| cx.fold_item(x).move_iter())
.collect();
let filtered_view_items = m.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::Mod {
inner: m.inner,
view_items: filtered_view_items,
items: flattened_items
}
}
fn filter_foreign_item(cx: &mut Context, item: Gc<ast::ForeignItem>)
-> Option<Gc<ast::ForeignItem>> {
if foreign_item_in_cfg(cx, &*item) {
Some(item)
} else {
None
}
}
fn fold_foreign_mod(cx: &mut Context, nm: &ast::ForeignMod) -> ast::ForeignMod {
let filtered_items = nm.items
.iter()
.filter_map(|a| filter_foreign_item(cx, *a))
.collect();
let filtered_view_items = nm.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::ForeignMod {
abi: nm.abi,
view_items: filtered_view_items,
items: filtered_items
}
}
fn fold_item_underscore(cx: &mut Context, item: &ast::Item_) -> ast::Item_ {
let item = match *item {
ast::ItemImpl(ref a, ref b, c, ref methods) => {
let methods = methods.iter().filter(|m| method_in_cfg(cx, &***m))
.map(|x| *x).collect();
ast::ItemImpl((*a).clone(), (*b).clone(), c, methods)
}
ast::ItemTrait(ref a, b, ref c, ref methods) => {
let methods = methods.iter()
.filter(|m| trait_method_in_cfg(cx, *m) )
.map(|x| (*x).clone())
.collect();
ast::ItemTrait((*a).clone(), b, (*c).clone(), methods)
}
ast::ItemStruct(ref def, ref generics) => {
ast::ItemStruct(fold_struct(cx, &**def), generics.clone())
}
ast::ItemEnum(ref def, ref generics) => {
let mut variants = def.variants.iter().map(|c| c.clone()).
filter_map(|v| {
if!(cx.in_cfg)(v.node.attrs.as_slice()) {
None
} else {
Some(match v.node.kind {
ast::TupleVariantKind(..) => v,
ast::StructVariantKind(ref def) => {
let def = fold_struct(cx, &**def);
box(GC) codemap::Spanned {
node: ast::Variant_ {
kind: ast::StructVariantKind(def.clone()),
..v.node.clone()
},
..*v
}
}
})
}
});
ast::ItemEnum(ast::EnumDef {
variants: variants.collect(),
}, generics.clone())
}
ref item => item.clone(),
};
fold::noop_fold_item_underscore(&item, cx)
}
fn fold_struct(cx: &mut Context, def: &ast::StructDef) -> Gc<ast::StructDef> {
let mut fields = def.fields.iter().map(|c| c.clone()).filter(|m| {
(cx.in_cfg)(m.node.attrs.as_slice())
});
box(GC) ast::StructDef {
fields: fields.collect(),
ctor_id: def.ctor_id,
super_struct: def.super_struct.clone(),
is_virtual: def.is_virtual,
}
}
fn retain_stmt(cx: &mut Context, stmt: Gc<ast::Stmt>) -> bool {
match stmt.node {
ast::StmtDecl(decl, _) => {
match decl.node {
ast::DeclItem(ref item) => {
item_in_cfg(cx, &**item)
}
_ => true
}
}
_ => true
}
}
fn fold_block(cx: &mut Context, b: ast::P<ast::Block>) -> ast::P<ast::Block> {
let resulting_stmts: Vec<&Gc<ast::Stmt>> =
b.stmts.iter().filter(|&a| retain_stmt(cx, *a)).collect();
let resulting_stmts = resulting_stmts.move_iter()
.flat_map(|stmt| cx.fold_stmt(&**stmt).move_iter())
.collect();
let filtered_view_items = b.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::P(ast::Block {
view_items: filtered_view_items,
stmts: resulting_stmts,
expr: b.expr.map(|x| cx.fold_expr(x)),
id: b.id,
rules: b.rules,
span: b.span,
})
}
fn fold_expr(cx: &mut Context, expr: Gc<ast::Expr>) -> Gc<ast::Expr> {
let expr = match expr.node {
ast::ExprMatch(ref m, ref arms) => {
let arms = arms.iter()
.filter(|a| (cx.in_cfg)(a.attrs.as_slice()))
.map(|a| a.clone())
.collect();
box(GC) ast::Expr {
id: expr.id,
span: expr.span.clone(),
node: ast::ExprMatch(m.clone(), arms),
}
}
_ => expr.clone()
};
fold::noop_fold_expr(expr, cx)
}
fn item_in_cfg(cx: &mut Context, item: &ast::Item) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn foreign_item_in_cfg(cx: &mut Context, item: &ast::ForeignItem) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn view_item_in_cfg(cx: &mut Context, item: &ast::ViewItem) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn method_in_cfg(cx: &mut Context, meth: &ast::Method) -> bool {
return (cx.in_cfg)(meth.attrs.as_slice());
}
fn trait_method_in_cfg(cx: &mut Context, meth: &ast::TraitMethod) -> bool {
match *meth {
ast::Required(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
ast::Provided(meth) => (cx.in_cfg)(meth.attrs.as_slice())
}
}
// Determine if an item should be translated in the current crate
// configuration based on the item's attributes
fn in_cfg(cfg: &[Gc<ast::MetaItem>], attrs: &[ast::Attribute]) -> bool {
attr::test_cfg(cfg, attrs.iter().map(|x| *x))
}
|
{
let config = krate.config.clone();
strip_items(krate, |attrs| in_cfg(config.as_slice(), attrs))
}
|
identifier_body
|
config.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::fold::Folder;
use syntax::{ast, fold, attr};
use syntax::codemap;
use std::gc::{Gc, GC};
struct Context<'a> {
in_cfg: |attrs: &[ast::Attribute]|: 'a -> bool,
}
// Support conditional compilation by transforming the AST, stripping out
// any items that do not belong in the current configuration
pub fn strip_unconfigured_items(krate: ast::Crate) -> ast::Crate {
let config = krate.config.clone();
strip_items(krate, |attrs| in_cfg(config.as_slice(), attrs))
}
impl<'a> fold::Folder for Context<'a> {
fn fold_mod(&mut self, module: &ast::Mod) -> ast::Mod {
fold_mod(self, module)
}
fn fold_block(&mut self, block: ast::P<ast::Block>) -> ast::P<ast::Block> {
fold_block(self, block)
}
fn fold_foreign_mod(&mut self, foreign_mod: &ast::ForeignMod) -> ast::ForeignMod {
fold_foreign_mod(self, foreign_mod)
}
fn fold_item_underscore(&mut self, item: &ast::Item_) -> ast::Item_ {
fold_item_underscore(self, item)
}
fn fold_expr(&mut self, expr: Gc<ast::Expr>) -> Gc<ast::Expr> {
fold_expr(self, expr)
}
}
pub fn strip_items(krate: ast::Crate,
in_cfg: |attrs: &[ast::Attribute]| -> bool)
-> ast::Crate {
let mut ctxt = Context {
in_cfg: in_cfg,
};
ctxt.fold_crate(krate)
}
fn filter_view_item<'r>(cx: &mut Context, view_item: &'r ast::ViewItem)
-> Option<&'r ast::ViewItem> {
if view_item_in_cfg(cx, view_item) {
Some(view_item)
} else {
None
}
}
fn fold_mod(cx: &mut Context, m: &ast::Mod) -> ast::Mod {
let filtered_items: Vec<&Gc<ast::Item>> = m.items.iter()
.filter(|a| item_in_cfg(cx, &***a))
.collect();
|
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::Mod {
inner: m.inner,
view_items: filtered_view_items,
items: flattened_items
}
}
fn filter_foreign_item(cx: &mut Context, item: Gc<ast::ForeignItem>)
-> Option<Gc<ast::ForeignItem>> {
if foreign_item_in_cfg(cx, &*item) {
Some(item)
} else {
None
}
}
fn fold_foreign_mod(cx: &mut Context, nm: &ast::ForeignMod) -> ast::ForeignMod {
let filtered_items = nm.items
.iter()
.filter_map(|a| filter_foreign_item(cx, *a))
.collect();
let filtered_view_items = nm.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::ForeignMod {
abi: nm.abi,
view_items: filtered_view_items,
items: filtered_items
}
}
fn fold_item_underscore(cx: &mut Context, item: &ast::Item_) -> ast::Item_ {
let item = match *item {
ast::ItemImpl(ref a, ref b, c, ref methods) => {
let methods = methods.iter().filter(|m| method_in_cfg(cx, &***m))
.map(|x| *x).collect();
ast::ItemImpl((*a).clone(), (*b).clone(), c, methods)
}
ast::ItemTrait(ref a, b, ref c, ref methods) => {
let methods = methods.iter()
.filter(|m| trait_method_in_cfg(cx, *m) )
.map(|x| (*x).clone())
.collect();
ast::ItemTrait((*a).clone(), b, (*c).clone(), methods)
}
ast::ItemStruct(ref def, ref generics) => {
ast::ItemStruct(fold_struct(cx, &**def), generics.clone())
}
ast::ItemEnum(ref def, ref generics) => {
let mut variants = def.variants.iter().map(|c| c.clone()).
filter_map(|v| {
if!(cx.in_cfg)(v.node.attrs.as_slice()) {
None
} else {
Some(match v.node.kind {
ast::TupleVariantKind(..) => v,
ast::StructVariantKind(ref def) => {
let def = fold_struct(cx, &**def);
box(GC) codemap::Spanned {
node: ast::Variant_ {
kind: ast::StructVariantKind(def.clone()),
..v.node.clone()
},
..*v
}
}
})
}
});
ast::ItemEnum(ast::EnumDef {
variants: variants.collect(),
}, generics.clone())
}
ref item => item.clone(),
};
fold::noop_fold_item_underscore(&item, cx)
}
fn fold_struct(cx: &mut Context, def: &ast::StructDef) -> Gc<ast::StructDef> {
let mut fields = def.fields.iter().map(|c| c.clone()).filter(|m| {
(cx.in_cfg)(m.node.attrs.as_slice())
});
box(GC) ast::StructDef {
fields: fields.collect(),
ctor_id: def.ctor_id,
super_struct: def.super_struct.clone(),
is_virtual: def.is_virtual,
}
}
fn retain_stmt(cx: &mut Context, stmt: Gc<ast::Stmt>) -> bool {
match stmt.node {
ast::StmtDecl(decl, _) => {
match decl.node {
ast::DeclItem(ref item) => {
item_in_cfg(cx, &**item)
}
_ => true
}
}
_ => true
}
}
fn fold_block(cx: &mut Context, b: ast::P<ast::Block>) -> ast::P<ast::Block> {
let resulting_stmts: Vec<&Gc<ast::Stmt>> =
b.stmts.iter().filter(|&a| retain_stmt(cx, *a)).collect();
let resulting_stmts = resulting_stmts.move_iter()
.flat_map(|stmt| cx.fold_stmt(&**stmt).move_iter())
.collect();
let filtered_view_items = b.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::P(ast::Block {
view_items: filtered_view_items,
stmts: resulting_stmts,
expr: b.expr.map(|x| cx.fold_expr(x)),
id: b.id,
rules: b.rules,
span: b.span,
})
}
fn fold_expr(cx: &mut Context, expr: Gc<ast::Expr>) -> Gc<ast::Expr> {
let expr = match expr.node {
ast::ExprMatch(ref m, ref arms) => {
let arms = arms.iter()
.filter(|a| (cx.in_cfg)(a.attrs.as_slice()))
.map(|a| a.clone())
.collect();
box(GC) ast::Expr {
id: expr.id,
span: expr.span.clone(),
node: ast::ExprMatch(m.clone(), arms),
}
}
_ => expr.clone()
};
fold::noop_fold_expr(expr, cx)
}
fn item_in_cfg(cx: &mut Context, item: &ast::Item) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn foreign_item_in_cfg(cx: &mut Context, item: &ast::ForeignItem) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn view_item_in_cfg(cx: &mut Context, item: &ast::ViewItem) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn method_in_cfg(cx: &mut Context, meth: &ast::Method) -> bool {
return (cx.in_cfg)(meth.attrs.as_slice());
}
fn trait_method_in_cfg(cx: &mut Context, meth: &ast::TraitMethod) -> bool {
match *meth {
ast::Required(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
ast::Provided(meth) => (cx.in_cfg)(meth.attrs.as_slice())
}
}
// Determine if an item should be translated in the current crate
// configuration based on the item's attributes
fn in_cfg(cfg: &[Gc<ast::MetaItem>], attrs: &[ast::Attribute]) -> bool {
attr::test_cfg(cfg, attrs.iter().map(|x| *x))
}
|
let flattened_items = filtered_items.move_iter()
.flat_map(|&x| cx.fold_item(x).move_iter())
.collect();
let filtered_view_items = m.view_items.iter().filter_map(|a| {
|
random_line_split
|
config.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use syntax::fold::Folder;
use syntax::{ast, fold, attr};
use syntax::codemap;
use std::gc::{Gc, GC};
struct Context<'a> {
in_cfg: |attrs: &[ast::Attribute]|: 'a -> bool,
}
// Support conditional compilation by transforming the AST, stripping out
// any items that do not belong in the current configuration
pub fn strip_unconfigured_items(krate: ast::Crate) -> ast::Crate {
let config = krate.config.clone();
strip_items(krate, |attrs| in_cfg(config.as_slice(), attrs))
}
impl<'a> fold::Folder for Context<'a> {
fn fold_mod(&mut self, module: &ast::Mod) -> ast::Mod {
fold_mod(self, module)
}
fn fold_block(&mut self, block: ast::P<ast::Block>) -> ast::P<ast::Block> {
fold_block(self, block)
}
fn fold_foreign_mod(&mut self, foreign_mod: &ast::ForeignMod) -> ast::ForeignMod {
fold_foreign_mod(self, foreign_mod)
}
fn fold_item_underscore(&mut self, item: &ast::Item_) -> ast::Item_ {
fold_item_underscore(self, item)
}
fn fold_expr(&mut self, expr: Gc<ast::Expr>) -> Gc<ast::Expr> {
fold_expr(self, expr)
}
}
pub fn strip_items(krate: ast::Crate,
in_cfg: |attrs: &[ast::Attribute]| -> bool)
-> ast::Crate {
let mut ctxt = Context {
in_cfg: in_cfg,
};
ctxt.fold_crate(krate)
}
fn filter_view_item<'r>(cx: &mut Context, view_item: &'r ast::ViewItem)
-> Option<&'r ast::ViewItem> {
if view_item_in_cfg(cx, view_item) {
Some(view_item)
} else {
None
}
}
fn fold_mod(cx: &mut Context, m: &ast::Mod) -> ast::Mod {
let filtered_items: Vec<&Gc<ast::Item>> = m.items.iter()
.filter(|a| item_in_cfg(cx, &***a))
.collect();
let flattened_items = filtered_items.move_iter()
.flat_map(|&x| cx.fold_item(x).move_iter())
.collect();
let filtered_view_items = m.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::Mod {
inner: m.inner,
view_items: filtered_view_items,
items: flattened_items
}
}
fn
|
(cx: &mut Context, item: Gc<ast::ForeignItem>)
-> Option<Gc<ast::ForeignItem>> {
if foreign_item_in_cfg(cx, &*item) {
Some(item)
} else {
None
}
}
fn fold_foreign_mod(cx: &mut Context, nm: &ast::ForeignMod) -> ast::ForeignMod {
let filtered_items = nm.items
.iter()
.filter_map(|a| filter_foreign_item(cx, *a))
.collect();
let filtered_view_items = nm.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::ForeignMod {
abi: nm.abi,
view_items: filtered_view_items,
items: filtered_items
}
}
fn fold_item_underscore(cx: &mut Context, item: &ast::Item_) -> ast::Item_ {
let item = match *item {
ast::ItemImpl(ref a, ref b, c, ref methods) => {
let methods = methods.iter().filter(|m| method_in_cfg(cx, &***m))
.map(|x| *x).collect();
ast::ItemImpl((*a).clone(), (*b).clone(), c, methods)
}
ast::ItemTrait(ref a, b, ref c, ref methods) => {
let methods = methods.iter()
.filter(|m| trait_method_in_cfg(cx, *m) )
.map(|x| (*x).clone())
.collect();
ast::ItemTrait((*a).clone(), b, (*c).clone(), methods)
}
ast::ItemStruct(ref def, ref generics) => {
ast::ItemStruct(fold_struct(cx, &**def), generics.clone())
}
ast::ItemEnum(ref def, ref generics) => {
let mut variants = def.variants.iter().map(|c| c.clone()).
filter_map(|v| {
if!(cx.in_cfg)(v.node.attrs.as_slice()) {
None
} else {
Some(match v.node.kind {
ast::TupleVariantKind(..) => v,
ast::StructVariantKind(ref def) => {
let def = fold_struct(cx, &**def);
box(GC) codemap::Spanned {
node: ast::Variant_ {
kind: ast::StructVariantKind(def.clone()),
..v.node.clone()
},
..*v
}
}
})
}
});
ast::ItemEnum(ast::EnumDef {
variants: variants.collect(),
}, generics.clone())
}
ref item => item.clone(),
};
fold::noop_fold_item_underscore(&item, cx)
}
fn fold_struct(cx: &mut Context, def: &ast::StructDef) -> Gc<ast::StructDef> {
let mut fields = def.fields.iter().map(|c| c.clone()).filter(|m| {
(cx.in_cfg)(m.node.attrs.as_slice())
});
box(GC) ast::StructDef {
fields: fields.collect(),
ctor_id: def.ctor_id,
super_struct: def.super_struct.clone(),
is_virtual: def.is_virtual,
}
}
fn retain_stmt(cx: &mut Context, stmt: Gc<ast::Stmt>) -> bool {
match stmt.node {
ast::StmtDecl(decl, _) => {
match decl.node {
ast::DeclItem(ref item) => {
item_in_cfg(cx, &**item)
}
_ => true
}
}
_ => true
}
}
fn fold_block(cx: &mut Context, b: ast::P<ast::Block>) -> ast::P<ast::Block> {
let resulting_stmts: Vec<&Gc<ast::Stmt>> =
b.stmts.iter().filter(|&a| retain_stmt(cx, *a)).collect();
let resulting_stmts = resulting_stmts.move_iter()
.flat_map(|stmt| cx.fold_stmt(&**stmt).move_iter())
.collect();
let filtered_view_items = b.view_items.iter().filter_map(|a| {
filter_view_item(cx, a).map(|x| cx.fold_view_item(x))
}).collect();
ast::P(ast::Block {
view_items: filtered_view_items,
stmts: resulting_stmts,
expr: b.expr.map(|x| cx.fold_expr(x)),
id: b.id,
rules: b.rules,
span: b.span,
})
}
fn fold_expr(cx: &mut Context, expr: Gc<ast::Expr>) -> Gc<ast::Expr> {
let expr = match expr.node {
ast::ExprMatch(ref m, ref arms) => {
let arms = arms.iter()
.filter(|a| (cx.in_cfg)(a.attrs.as_slice()))
.map(|a| a.clone())
.collect();
box(GC) ast::Expr {
id: expr.id,
span: expr.span.clone(),
node: ast::ExprMatch(m.clone(), arms),
}
}
_ => expr.clone()
};
fold::noop_fold_expr(expr, cx)
}
fn item_in_cfg(cx: &mut Context, item: &ast::Item) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn foreign_item_in_cfg(cx: &mut Context, item: &ast::ForeignItem) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn view_item_in_cfg(cx: &mut Context, item: &ast::ViewItem) -> bool {
return (cx.in_cfg)(item.attrs.as_slice());
}
fn method_in_cfg(cx: &mut Context, meth: &ast::Method) -> bool {
return (cx.in_cfg)(meth.attrs.as_slice());
}
fn trait_method_in_cfg(cx: &mut Context, meth: &ast::TraitMethod) -> bool {
match *meth {
ast::Required(ref meth) => (cx.in_cfg)(meth.attrs.as_slice()),
ast::Provided(meth) => (cx.in_cfg)(meth.attrs.as_slice())
}
}
// Determine if an item should be translated in the current crate
// configuration based on the item's attributes
fn in_cfg(cfg: &[Gc<ast::MetaItem>], attrs: &[ast::Attribute]) -> bool {
attr::test_cfg(cfg, attrs.iter().map(|x| *x))
}
|
filter_foreign_item
|
identifier_name
|
heapapi.rs
|
// Copyright © 2015-2017 winapi-rs developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
|
STRUCT!{struct HEAP_SUMMARY {
cb: DWORD,
cbAllocated: SIZE_T,
cbCommitted: SIZE_T,
cbReserved: SIZE_T,
cbMaxReserve: SIZE_T,
}}
pub type PHEAP_SUMMARY = *mut HEAP_SUMMARY;
pub type LPHEAP_SUMMARY = PHEAP_SUMMARY;
|
// except according to those terms.
//! ApiSet Contract for api-ms-win-core-heap-l1
use shared::basetsd::SIZE_T;
use shared::minwindef::DWORD;
|
random_line_split
|
macro-crate.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:macro_crate_test.rs
// ignore-stage1
#![feature(phase)]
#[phase(syntax)]
extern crate macro_crate_test;
#[into_foo]
#[deriving(Eq, Clone, Show)]
fn
|
() -> AFakeTypeThatHadBetterGoAway {}
pub fn main() {
assert_eq!(1, make_a_1!());
assert_eq!(2, exported_macro!());
assert_eq!(Bar, Bar);
test(None::<Foo>);
}
fn test<T: Eq+Clone>(_: Option<T>) {}
|
foo
|
identifier_name
|
macro-crate.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:macro_crate_test.rs
// ignore-stage1
#![feature(phase)]
#[phase(syntax)]
extern crate macro_crate_test;
#[into_foo]
#[deriving(Eq, Clone, Show)]
fn foo() -> AFakeTypeThatHadBetterGoAway {}
|
assert_eq!(1, make_a_1!());
assert_eq!(2, exported_macro!());
assert_eq!(Bar, Bar);
test(None::<Foo>);
}
fn test<T: Eq+Clone>(_: Option<T>) {}
|
pub fn main() {
|
random_line_split
|
macro-crate.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// aux-build:macro_crate_test.rs
// ignore-stage1
#![feature(phase)]
#[phase(syntax)]
extern crate macro_crate_test;
#[into_foo]
#[deriving(Eq, Clone, Show)]
fn foo() -> AFakeTypeThatHadBetterGoAway
|
pub fn main() {
assert_eq!(1, make_a_1!());
assert_eq!(2, exported_macro!());
assert_eq!(Bar, Bar);
test(None::<Foo>);
}
fn test<T: Eq+Clone>(_: Option<T>) {}
|
{}
|
identifier_body
|
sms.rs
|
extern crate url;
extern crate request;
extern crate rustc_serialize;
use std::collections::HashMap;
use rustc_serialize::json::Json;
use twilio_config::TwilioConfig;
#[derive(Debug)]
pub enum SMSError {
UnknownException
}
pub fn send_sms(from: &str, to: &str, body: &str) -> Result<String, SMSError> {
let config = TwilioConfig::from_env();
let endpoint = twilio_api_sms_url(&config);
let mut headers: HashMap<String, String> = HashMap::new();
let mut params: HashMap<String, String> = HashMap::new();
|
params.insert("From".to_string(), from.to_string());
params.insert("To".to_string(), to.to_string());
params.insert("Body".to_string(), body.to_string());
headers.insert("Connection".to_string(), "close".to_string());
headers.insert("Authorization".to_string(), config.to_http_auth());
headers.insert("Content-Type".to_string(), "application/x-www-form-urlencoded".to_string());
let response = match request::post(&endpoint, &mut headers, serialize_message_request_mody(params).as_bytes()) {
Ok(response) => response,
Err(_) => { return Err(SMSError::UnknownException); }
};
if response.status_code!= 201 {
return Err(SMSError::UnknownException);
}
let json = Json::from_str(&response.body).expect("Got empty response body");
let message_sid = json.as_object().expect("Malformed JSON response").get("sid").expect("Missing SID");
return Ok(format!("{}", message_sid));
}
fn twilio_api_sms_url(config: &TwilioConfig) -> String {
return format!("https://api.twilio.com/2010-04-01/Accounts/{}/Messages.json", config.account_sid)
}
fn serialize_message_request_mody(params: HashMap<String, String>) -> String {
return url::form_urlencoded::serialize(params.iter());
}
#[test]
fn test_serialize_message_request_body() {
let mut params: HashMap<String, String> = HashMap::new();
params.insert("Foo".to_string(), "Bar".to_string());
assert_eq!(serialize_message_request_mody(params), "Foo=Bar".to_string())
}
|
random_line_split
|
|
sms.rs
|
extern crate url;
extern crate request;
extern crate rustc_serialize;
use std::collections::HashMap;
use rustc_serialize::json::Json;
use twilio_config::TwilioConfig;
#[derive(Debug)]
pub enum SMSError {
UnknownException
}
pub fn send_sms(from: &str, to: &str, body: &str) -> Result<String, SMSError> {
let config = TwilioConfig::from_env();
let endpoint = twilio_api_sms_url(&config);
let mut headers: HashMap<String, String> = HashMap::new();
let mut params: HashMap<String, String> = HashMap::new();
params.insert("From".to_string(), from.to_string());
params.insert("To".to_string(), to.to_string());
params.insert("Body".to_string(), body.to_string());
headers.insert("Connection".to_string(), "close".to_string());
headers.insert("Authorization".to_string(), config.to_http_auth());
headers.insert("Content-Type".to_string(), "application/x-www-form-urlencoded".to_string());
let response = match request::post(&endpoint, &mut headers, serialize_message_request_mody(params).as_bytes()) {
Ok(response) => response,
Err(_) => { return Err(SMSError::UnknownException); }
};
if response.status_code!= 201 {
return Err(SMSError::UnknownException);
}
let json = Json::from_str(&response.body).expect("Got empty response body");
let message_sid = json.as_object().expect("Malformed JSON response").get("sid").expect("Missing SID");
return Ok(format!("{}", message_sid));
}
fn twilio_api_sms_url(config: &TwilioConfig) -> String {
return format!("https://api.twilio.com/2010-04-01/Accounts/{}/Messages.json", config.account_sid)
}
fn serialize_message_request_mody(params: HashMap<String, String>) -> String {
return url::form_urlencoded::serialize(params.iter());
}
#[test]
fn
|
() {
let mut params: HashMap<String, String> = HashMap::new();
params.insert("Foo".to_string(), "Bar".to_string());
assert_eq!(serialize_message_request_mody(params), "Foo=Bar".to_string())
}
|
test_serialize_message_request_body
|
identifier_name
|
any.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Traits for dynamic typing of any `'static` type (through runtime reflection)
//!
//! This module implements the `Any` trait, which enables dynamic typing
//! of any `'static` type through runtime reflection.
//!
//! `Any` itself can be used to get a `TypeId`, and has more features when used
//! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and
//! `as_ref` methods, to test if the contained value is of a given type, and to
//! get a reference to the inner value as a type. As`&mut Any`, there is also
//! the `as_mut` method, for getting a mutable reference to the inner value.
//! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the
//! object. See the extension traits (`*Ext`) for the full details.
//!
//! Note that &Any is limited to testing whether a value is of a specified
//! concrete type, and cannot be used to test whether a type implements a trait.
//!
//! # Examples
//!
//! Consider a situation where we want to log out a value passed to a function.
//! We know the value we're working on implements Debug, but we don't know its
//! concrete type. We want to give special treatment to certain types: in this
//! case printing out the length of String values prior to their value.
//! We don't know the concrete type of our value at compile time, so we need to
//! use runtime reflection instead.
//!
//! ```rust
//! use std::fmt::Debug;
//! use std::any::Any;
//!
//! // Logger function for any type that implements Debug.
//! fn log<T: Any + Debug>(value: &T) {
//! let value_any = value as &Any;
//!
//! // try to convert our value to a String. If successful, we want to
//! // output the String's length as well as its value. If not, it's a
//! // different type: just print it out unadorned.
//! match value_any.downcast_ref::<String>() {
//! Some(as_string) => {
//! println!("String ({}): {}", as_string.len(), as_string);
//! }
//! None => {
//! println!("{:?}", value);
//! }
//! }
//! }
//!
//! // This function wants to log its parameter out prior to doing work with it.
//! fn do_work<T: Any + Debug>(value: &T) {
//! log(value);
//! //...do some other work
//! }
//!
//! fn main() {
//! let my_string = "Hello World".to_string();
//! do_work(&my_string);
//!
//! let my_i8: i8 = 100;
//! do_work(&my_i8);
//! }
//! ```
#![stable(feature = "rust1", since = "1.0.0")]
use fmt;
use marker::Send;
use mem::transmute;
use option::Option::{self, Some, None};
use raw::TraitObject;
use intrinsics;
use marker::{Reflect, Sized};
///////////////////////////////////////////////////////////////////////////////
// Any trait
///////////////////////////////////////////////////////////////////////////////
/// A type to emulate dynamic typing.
///
/// Every type with no non-`'static` references implements `Any`.
/// See the [module-level documentation][mod] for more details.
///
/// [mod]: index.html
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Any: Reflect +'static {
/// Gets the `TypeId` of `self`.
#[unstable(feature = "get_type_id",
reason = "this method will likely be replaced by an associated static")]
fn get_type_id(&self) -> TypeId;
}
impl<T: Reflect +'static> Any for T {
fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
}
///////////////////////////////////////////////////////////////////////////////
// Extension methods for Any trait objects.
///////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Any {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Any")
}
}
// Ensure that the result of e.g. joining a thread can be printed and
// hence used with `unwrap`. May eventually no longer be needed if
// dispatch works with upcasting.
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Any + Send {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Any")
}
}
impl Any {
/// Returns true if the boxed type is the same as `T`
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is<T: Any>(&self) -> bool {
// Get TypeId of the type this function is instantiated with
let t = TypeId::of::<T>();
// Get TypeId of the type in the trait object
let boxed = self.get_type_id();
// Compare both TypeIds on equality
t == boxed
}
/// Returns some reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute(self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
/// Returns some mutable reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>()
|
else {
None
}
}
}
impl Any+Send {
/// Forwards to the method defined on the type `Any`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is<T: Any>(&self) -> bool {
Any::is::<T>(self)
}
/// Forwards to the method defined on the type `Any`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
Any::downcast_ref::<T>(self)
}
/// Forwards to the method defined on the type `Any`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
Any::downcast_mut::<T>(self)
}
}
///////////////////////////////////////////////////////////////////////////////
// TypeID and its methods
///////////////////////////////////////////////////////////////////////////////
/// A `TypeId` represents a globally unique identifier for a type.
///
/// Each `TypeId` is an opaque object which does not allow inspection of what's
/// inside but does allow basic operations such as cloning, comparison,
/// printing, and showing.
///
/// A `TypeId` is currently only available for types which ascribe to `'static`,
/// but this limitation may be removed in the future.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct TypeId {
t: u64,
}
impl TypeId {
/// Returns the `TypeId` of the type this generic function has been
/// instantiated with
#[stable(feature = "rust1", since = "1.0.0")]
pub fn of<T:?Sized + Reflect +'static>() -> TypeId {
TypeId {
t: unsafe { intrinsics::type_id::<T>() },
}
}
}
|
{
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute(self);
// Extract the data pointer
Some(transmute(to.data))
}
}
|
conditional_block
|
any.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Traits for dynamic typing of any `'static` type (through runtime reflection)
//!
//! This module implements the `Any` trait, which enables dynamic typing
//! of any `'static` type through runtime reflection.
//!
//! `Any` itself can be used to get a `TypeId`, and has more features when used
//! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and
//! `as_ref` methods, to test if the contained value is of a given type, and to
//! get a reference to the inner value as a type. As`&mut Any`, there is also
//! the `as_mut` method, for getting a mutable reference to the inner value.
//! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the
//! object. See the extension traits (`*Ext`) for the full details.
//!
//! Note that &Any is limited to testing whether a value is of a specified
//! concrete type, and cannot be used to test whether a type implements a trait.
//!
//! # Examples
//!
//! Consider a situation where we want to log out a value passed to a function.
//! We know the value we're working on implements Debug, but we don't know its
//! concrete type. We want to give special treatment to certain types: in this
//! case printing out the length of String values prior to their value.
//! We don't know the concrete type of our value at compile time, so we need to
//! use runtime reflection instead.
//!
//! ```rust
//! use std::fmt::Debug;
//! use std::any::Any;
//!
//! // Logger function for any type that implements Debug.
//! fn log<T: Any + Debug>(value: &T) {
//! let value_any = value as &Any;
//!
//! // try to convert our value to a String. If successful, we want to
//! // output the String's length as well as its value. If not, it's a
//! // different type: just print it out unadorned.
//! match value_any.downcast_ref::<String>() {
//! Some(as_string) => {
//! println!("String ({}): {}", as_string.len(), as_string);
//! }
//! None => {
//! println!("{:?}", value);
//! }
//! }
//! }
//!
//! // This function wants to log its parameter out prior to doing work with it.
//! fn do_work<T: Any + Debug>(value: &T) {
//! log(value);
//! //...do some other work
//! }
//!
//! fn main() {
//! let my_string = "Hello World".to_string();
//! do_work(&my_string);
//!
//! let my_i8: i8 = 100;
//! do_work(&my_i8);
//! }
//! ```
#![stable(feature = "rust1", since = "1.0.0")]
use fmt;
use marker::Send;
use mem::transmute;
use option::Option::{self, Some, None};
use raw::TraitObject;
use intrinsics;
use marker::{Reflect, Sized};
///////////////////////////////////////////////////////////////////////////////
// Any trait
///////////////////////////////////////////////////////////////////////////////
/// A type to emulate dynamic typing.
///
/// Every type with no non-`'static` references implements `Any`.
/// See the [module-level documentation][mod] for more details.
///
/// [mod]: index.html
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Any: Reflect +'static {
/// Gets the `TypeId` of `self`.
#[unstable(feature = "get_type_id",
reason = "this method will likely be replaced by an associated static")]
fn get_type_id(&self) -> TypeId;
}
impl<T: Reflect +'static> Any for T {
fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
}
///////////////////////////////////////////////////////////////////////////////
// Extension methods for Any trait objects.
///////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Any {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Any")
}
}
// Ensure that the result of e.g. joining a thread can be printed and
// hence used with `unwrap`. May eventually no longer be needed if
// dispatch works with upcasting.
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Any + Send {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Any")
}
}
impl Any {
/// Returns true if the boxed type is the same as `T`
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
|
// Get TypeId of the type this function is instantiated with
let t = TypeId::of::<T>();
// Get TypeId of the type in the trait object
let boxed = self.get_type_id();
// Compare both TypeIds on equality
t == boxed
}
/// Returns some reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute(self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
/// Returns some mutable reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute(self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
}
impl Any+Send {
/// Forwards to the method defined on the type `Any`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is<T: Any>(&self) -> bool {
Any::is::<T>(self)
}
/// Forwards to the method defined on the type `Any`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
Any::downcast_ref::<T>(self)
}
/// Forwards to the method defined on the type `Any`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
Any::downcast_mut::<T>(self)
}
}
///////////////////////////////////////////////////////////////////////////////
// TypeID and its methods
///////////////////////////////////////////////////////////////////////////////
/// A `TypeId` represents a globally unique identifier for a type.
///
/// Each `TypeId` is an opaque object which does not allow inspection of what's
/// inside but does allow basic operations such as cloning, comparison,
/// printing, and showing.
///
/// A `TypeId` is currently only available for types which ascribe to `'static`,
/// but this limitation may be removed in the future.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct TypeId {
t: u64,
}
impl TypeId {
/// Returns the `TypeId` of the type this generic function has been
/// instantiated with
#[stable(feature = "rust1", since = "1.0.0")]
pub fn of<T:?Sized + Reflect +'static>() -> TypeId {
TypeId {
t: unsafe { intrinsics::type_id::<T>() },
}
}
}
|
pub fn is<T: Any>(&self) -> bool {
|
random_line_split
|
any.rs
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Traits for dynamic typing of any `'static` type (through runtime reflection)
//!
//! This module implements the `Any` trait, which enables dynamic typing
//! of any `'static` type through runtime reflection.
//!
//! `Any` itself can be used to get a `TypeId`, and has more features when used
//! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and
//! `as_ref` methods, to test if the contained value is of a given type, and to
//! get a reference to the inner value as a type. As`&mut Any`, there is also
//! the `as_mut` method, for getting a mutable reference to the inner value.
//! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the
//! object. See the extension traits (`*Ext`) for the full details.
//!
//! Note that &Any is limited to testing whether a value is of a specified
//! concrete type, and cannot be used to test whether a type implements a trait.
//!
//! # Examples
//!
//! Consider a situation where we want to log out a value passed to a function.
//! We know the value we're working on implements Debug, but we don't know its
//! concrete type. We want to give special treatment to certain types: in this
//! case printing out the length of String values prior to their value.
//! We don't know the concrete type of our value at compile time, so we need to
//! use runtime reflection instead.
//!
//! ```rust
//! use std::fmt::Debug;
//! use std::any::Any;
//!
//! // Logger function for any type that implements Debug.
//! fn log<T: Any + Debug>(value: &T) {
//! let value_any = value as &Any;
//!
//! // try to convert our value to a String. If successful, we want to
//! // output the String's length as well as its value. If not, it's a
//! // different type: just print it out unadorned.
//! match value_any.downcast_ref::<String>() {
//! Some(as_string) => {
//! println!("String ({}): {}", as_string.len(), as_string);
//! }
//! None => {
//! println!("{:?}", value);
//! }
//! }
//! }
//!
//! // This function wants to log its parameter out prior to doing work with it.
//! fn do_work<T: Any + Debug>(value: &T) {
//! log(value);
//! //...do some other work
//! }
//!
//! fn main() {
//! let my_string = "Hello World".to_string();
//! do_work(&my_string);
//!
//! let my_i8: i8 = 100;
//! do_work(&my_i8);
//! }
//! ```
#![stable(feature = "rust1", since = "1.0.0")]
use fmt;
use marker::Send;
use mem::transmute;
use option::Option::{self, Some, None};
use raw::TraitObject;
use intrinsics;
use marker::{Reflect, Sized};
///////////////////////////////////////////////////////////////////////////////
// Any trait
///////////////////////////////////////////////////////////////////////////////
/// A type to emulate dynamic typing.
///
/// Every type with no non-`'static` references implements `Any`.
/// See the [module-level documentation][mod] for more details.
///
/// [mod]: index.html
#[stable(feature = "rust1", since = "1.0.0")]
pub trait Any: Reflect +'static {
/// Gets the `TypeId` of `self`.
#[unstable(feature = "get_type_id",
reason = "this method will likely be replaced by an associated static")]
fn get_type_id(&self) -> TypeId;
}
impl<T: Reflect +'static> Any for T {
fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
}
///////////////////////////////////////////////////////////////////////////////
// Extension methods for Any trait objects.
///////////////////////////////////////////////////////////////////////////////
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Any {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Any")
}
}
// Ensure that the result of e.g. joining a thread can be printed and
// hence used with `unwrap`. May eventually no longer be needed if
// dispatch works with upcasting.
#[stable(feature = "rust1", since = "1.0.0")]
impl fmt::Debug for Any + Send {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad("Any")
}
}
impl Any {
/// Returns true if the boxed type is the same as `T`
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn
|
<T: Any>(&self) -> bool {
// Get TypeId of the type this function is instantiated with
let t = TypeId::of::<T>();
// Get TypeId of the type in the trait object
let boxed = self.get_type_id();
// Compare both TypeIds on equality
t == boxed
}
/// Returns some reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute(self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
/// Returns some mutable reference to the boxed value if it is of type `T`, or
/// `None` if it isn't.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
unsafe {
// Get the raw representation of the trait object
let to: TraitObject = transmute(self);
// Extract the data pointer
Some(transmute(to.data))
}
} else {
None
}
}
}
impl Any+Send {
/// Forwards to the method defined on the type `Any`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is<T: Any>(&self) -> bool {
Any::is::<T>(self)
}
/// Forwards to the method defined on the type `Any`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
Any::downcast_ref::<T>(self)
}
/// Forwards to the method defined on the type `Any`.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
Any::downcast_mut::<T>(self)
}
}
///////////////////////////////////////////////////////////////////////////////
// TypeID and its methods
///////////////////////////////////////////////////////////////////////////////
/// A `TypeId` represents a globally unique identifier for a type.
///
/// Each `TypeId` is an opaque object which does not allow inspection of what's
/// inside but does allow basic operations such as cloning, comparison,
/// printing, and showing.
///
/// A `TypeId` is currently only available for types which ascribe to `'static`,
/// but this limitation may be removed in the future.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct TypeId {
t: u64,
}
impl TypeId {
/// Returns the `TypeId` of the type this generic function has been
/// instantiated with
#[stable(feature = "rust1", since = "1.0.0")]
pub fn of<T:?Sized + Reflect +'static>() -> TypeId {
TypeId {
t: unsafe { intrinsics::type_id::<T>() },
}
}
}
|
is
|
identifier_name
|
new-impl-syntax.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
|
// <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 std::fmt;
struct Thingy {
x: isize,
y: isize
}
impl fmt::Debug for Thingy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{ x: {:?}, y: {:?} }}", self.x, self.y)
}
}
struct PolymorphicThingy<T> {
x: T
}
impl<T:fmt::Debug> fmt::Debug for PolymorphicThingy<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.x)
}
}
pub fn main() {
println!("{:?}", Thingy { x: 1, y: 2 });
println!("{:?}", PolymorphicThingy { x: Thingy { x: 1, y: 2 } });
}
|
// 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
|
random_line_split
|
new-impl-syntax.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.
use std::fmt;
struct
|
{
x: isize,
y: isize
}
impl fmt::Debug for Thingy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{ x: {:?}, y: {:?} }}", self.x, self.y)
}
}
struct PolymorphicThingy<T> {
x: T
}
impl<T:fmt::Debug> fmt::Debug for PolymorphicThingy<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.x)
}
}
pub fn main() {
println!("{:?}", Thingy { x: 1, y: 2 });
println!("{:?}", PolymorphicThingy { x: Thingy { x: 1, y: 2 } });
}
|
Thingy
|
identifier_name
|
new-impl-syntax.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.
use std::fmt;
struct Thingy {
x: isize,
y: isize
}
impl fmt::Debug for Thingy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
|
}
struct PolymorphicThingy<T> {
x: T
}
impl<T:fmt::Debug> fmt::Debug for PolymorphicThingy<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.x)
}
}
pub fn main() {
println!("{:?}", Thingy { x: 1, y: 2 });
println!("{:?}", PolymorphicThingy { x: Thingy { x: 1, y: 2 } });
}
|
{
write!(f, "{{ x: {:?}, y: {:?} }}", self.x, self.y)
}
|
identifier_body
|
mn.rs
|
extern crate cpr;
extern crate scoped_threadpool;
extern crate getopts;
extern crate bio;
extern crate num_cpus;
extern crate time;
use std::env;
use cpr::cpr;
use getopts::Options;
use std::path::Path;
use bio::io::fasta::Reader;
use scoped_threadpool::Pool;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
use std::fs::File;
use time::now;
use std::fs::{remove_dir_all, create_dir};
type Arg = String;
type ThrdNm = u32;
const DFLT_MX_SPN: usize = 200;
fn main() {
let args = env::args().collect::<Vec<Arg>>();
let prgrm = args[0].clone();
let mut opts = Options::new();
opts.reqopt("i", "", "Input RNA seqs in single file of FASTA format", "STR");
opts.reqopt("o", "", "Output prob. dist. seqs in single file of tabular format", "STR");
opts.optopt("m", "", &format!("Max. span between paired bases (Default: {})", DFLT_MX_SPN), "UINT");
|
let mtchs = match opts.parse(&args[1..]) {
Ok(mtch) => {mtch}
Err(fl) => {prnt_usg(&prgrm, &opts); panic!(fl.to_string())}
};
if mtchs.opt_present("h") {
prnt_usg(&prgrm, &opts);
return;
}
let i = mtchs.opt_str("i").expect("Failed to retrieve input file from command args.");
let o = mtchs.opt_str("o").expect("Failed to retrieve output file from command args.");
let m = if mtchs.opt_present("m") {
mtchs.opt_str("m").expect("Failed to retrieve max. span between paired bases from command args.").parse().expect("Failed to parse max. span between paired bases.")
} else {
DFLT_MX_SPN
};
let a = mtchs.opt_present("a");
let t = if mtchs.opt_present("t") {
mtchs.opt_str("t").expect("Failed to retrieve # of threads from command args failed.").parse().expect("Failed to parse # of threads.")
} else {
num_cpus::get() as ThrdNm
};
let fasta_rdr = Reader::from_file(Path::new(&i)).ok().expect("Failed to read FASTA file.");
let tm_stmp = gt_tm_stmp();
let tmp_dr = String::from("/tmp/cpr_") + &tm_stmp;
let tmp_dr = Path::new(&tmp_dr);
if!tmp_dr.exists() {
let _ = create_dir(tmp_dr);
}
let mut thrd_pl = Pool::new(t);
thrd_pl.scoped(|scp| {
for rc in fasta_rdr.records() {
scp.execute(|| {
let dt = rc.ok().expect("Failed to read FASTA record.");
let sq = dt.seq().to_vec();
let id = dt.id().expect("Failed to get FASTA record ID.");
let cntxt_dst_sq = cpr(&sq, m, a);
let mut tmp_otpt_fl = BufWriter::new(File::create(tmp_dr.join(&(String::from(id) + ".dat")).to_str().expect("Failed to parse temp. file path.")).expect("Failed to create temp. output file."));
let _ = tmp_otpt_fl.write_all((String::from(">") + id + "\n").as_bytes());
for cntxt_dst in &cntxt_dst_sq {
let mut bfr = cntxt_dst.iter().fold(String::new(), |acmltr, prb| acmltr + &format!("{:e} ", prb));
bfr.pop();
bfr += "\n";
let _ = tmp_otpt_fl.write_all(bfr.as_bytes());
}
let _ = tmp_otpt_fl.write_all(b"\n");
});
}
});
let mut otpt_fl = BufWriter::new(File::create(Path::new(&o)).expect("Failed to create output file."));
let _ = otpt_fl.write_all(b"# CapR version 1.1.0\n# Format = {bulge prob.} {internal prob.} {hairpin prob.} {exterior prob.} {multi prob.} {stem prob.} for the start to the end of each seq.\n");
for prb_dst_sq in tmp_dr.read_dir().ok().expect("Failed to read entries within temp. dir.") {
let prb_dst_sq = prb_dst_sq.ok().expect("Failed to read entry within temp. dir.");
let mut prb_dst_sq = BufReader::new(File::open(prb_dst_sq.path()).expect("Failed to open entry within temp. dir."));
let mut bfr = Vec::new();
let _ = prb_dst_sq.read_to_end(&mut bfr);
let _ = otpt_fl.write_all(&bfr);
}
let _ = remove_dir_all(tmp_dr);
}
#[inline]
fn prnt_usg(prgrm: &str, opts: &Options) {
let brf = format!("Usage: {} [options]", prgrm);
print!("{}", opts.usage(&brf));
}
#[inline]
fn gt_tm_stmp() -> String {
let nw = now();
format!("{}-{}-{}-{}:{}:{}", nw.tm_year + 1900, nw.tm_mon + 1, nw.tm_mday, nw.tm_hour, nw.tm_min, nw.tm_sec)
}
|
opts.optopt("t", "", "# of threads in multithreading (Default: system val.)", "UINT");
opts.optflag("a", "", "Approximate estimation");
opts.optflag("h", "help", "Print help menu");
|
random_line_split
|
mn.rs
|
extern crate cpr;
extern crate scoped_threadpool;
extern crate getopts;
extern crate bio;
extern crate num_cpus;
extern crate time;
use std::env;
use cpr::cpr;
use getopts::Options;
use std::path::Path;
use bio::io::fasta::Reader;
use scoped_threadpool::Pool;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
use std::fs::File;
use time::now;
use std::fs::{remove_dir_all, create_dir};
type Arg = String;
type ThrdNm = u32;
const DFLT_MX_SPN: usize = 200;
fn main() {
let args = env::args().collect::<Vec<Arg>>();
let prgrm = args[0].clone();
let mut opts = Options::new();
opts.reqopt("i", "", "Input RNA seqs in single file of FASTA format", "STR");
opts.reqopt("o", "", "Output prob. dist. seqs in single file of tabular format", "STR");
opts.optopt("m", "", &format!("Max. span between paired bases (Default: {})", DFLT_MX_SPN), "UINT");
opts.optopt("t", "", "# of threads in multithreading (Default: system val.)", "UINT");
opts.optflag("a", "", "Approximate estimation");
opts.optflag("h", "help", "Print help menu");
let mtchs = match opts.parse(&args[1..]) {
Ok(mtch) => {mtch}
Err(fl) => {prnt_usg(&prgrm, &opts); panic!(fl.to_string())}
};
if mtchs.opt_present("h") {
prnt_usg(&prgrm, &opts);
return;
}
let i = mtchs.opt_str("i").expect("Failed to retrieve input file from command args.");
let o = mtchs.opt_str("o").expect("Failed to retrieve output file from command args.");
let m = if mtchs.opt_present("m") {
mtchs.opt_str("m").expect("Failed to retrieve max. span between paired bases from command args.").parse().expect("Failed to parse max. span between paired bases.")
} else {
DFLT_MX_SPN
};
let a = mtchs.opt_present("a");
let t = if mtchs.opt_present("t") {
mtchs.opt_str("t").expect("Failed to retrieve # of threads from command args failed.").parse().expect("Failed to parse # of threads.")
} else {
num_cpus::get() as ThrdNm
};
let fasta_rdr = Reader::from_file(Path::new(&i)).ok().expect("Failed to read FASTA file.");
let tm_stmp = gt_tm_stmp();
let tmp_dr = String::from("/tmp/cpr_") + &tm_stmp;
let tmp_dr = Path::new(&tmp_dr);
if!tmp_dr.exists() {
let _ = create_dir(tmp_dr);
}
let mut thrd_pl = Pool::new(t);
thrd_pl.scoped(|scp| {
for rc in fasta_rdr.records() {
scp.execute(|| {
let dt = rc.ok().expect("Failed to read FASTA record.");
let sq = dt.seq().to_vec();
let id = dt.id().expect("Failed to get FASTA record ID.");
let cntxt_dst_sq = cpr(&sq, m, a);
let mut tmp_otpt_fl = BufWriter::new(File::create(tmp_dr.join(&(String::from(id) + ".dat")).to_str().expect("Failed to parse temp. file path.")).expect("Failed to create temp. output file."));
let _ = tmp_otpt_fl.write_all((String::from(">") + id + "\n").as_bytes());
for cntxt_dst in &cntxt_dst_sq {
let mut bfr = cntxt_dst.iter().fold(String::new(), |acmltr, prb| acmltr + &format!("{:e} ", prb));
bfr.pop();
bfr += "\n";
let _ = tmp_otpt_fl.write_all(bfr.as_bytes());
}
let _ = tmp_otpt_fl.write_all(b"\n");
});
}
});
let mut otpt_fl = BufWriter::new(File::create(Path::new(&o)).expect("Failed to create output file."));
let _ = otpt_fl.write_all(b"# CapR version 1.1.0\n# Format = {bulge prob.} {internal prob.} {hairpin prob.} {exterior prob.} {multi prob.} {stem prob.} for the start to the end of each seq.\n");
for prb_dst_sq in tmp_dr.read_dir().ok().expect("Failed to read entries within temp. dir.") {
let prb_dst_sq = prb_dst_sq.ok().expect("Failed to read entry within temp. dir.");
let mut prb_dst_sq = BufReader::new(File::open(prb_dst_sq.path()).expect("Failed to open entry within temp. dir."));
let mut bfr = Vec::new();
let _ = prb_dst_sq.read_to_end(&mut bfr);
let _ = otpt_fl.write_all(&bfr);
}
let _ = remove_dir_all(tmp_dr);
}
#[inline]
fn prnt_usg(prgrm: &str, opts: &Options) {
let brf = format!("Usage: {} [options]", prgrm);
print!("{}", opts.usage(&brf));
}
#[inline]
fn gt_tm_stmp() -> String
|
{
let nw = now();
format!("{}-{}-{}-{}:{}:{}", nw.tm_year + 1900, nw.tm_mon + 1, nw.tm_mday, nw.tm_hour, nw.tm_min, nw.tm_sec)
}
|
identifier_body
|
|
mn.rs
|
extern crate cpr;
extern crate scoped_threadpool;
extern crate getopts;
extern crate bio;
extern crate num_cpus;
extern crate time;
use std::env;
use cpr::cpr;
use getopts::Options;
use std::path::Path;
use bio::io::fasta::Reader;
use scoped_threadpool::Pool;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
use std::fs::File;
use time::now;
use std::fs::{remove_dir_all, create_dir};
type Arg = String;
type ThrdNm = u32;
const DFLT_MX_SPN: usize = 200;
fn main() {
let args = env::args().collect::<Vec<Arg>>();
let prgrm = args[0].clone();
let mut opts = Options::new();
opts.reqopt("i", "", "Input RNA seqs in single file of FASTA format", "STR");
opts.reqopt("o", "", "Output prob. dist. seqs in single file of tabular format", "STR");
opts.optopt("m", "", &format!("Max. span between paired bases (Default: {})", DFLT_MX_SPN), "UINT");
opts.optopt("t", "", "# of threads in multithreading (Default: system val.)", "UINT");
opts.optflag("a", "", "Approximate estimation");
opts.optflag("h", "help", "Print help menu");
let mtchs = match opts.parse(&args[1..]) {
Ok(mtch) =>
|
Err(fl) => {prnt_usg(&prgrm, &opts); panic!(fl.to_string())}
};
if mtchs.opt_present("h") {
prnt_usg(&prgrm, &opts);
return;
}
let i = mtchs.opt_str("i").expect("Failed to retrieve input file from command args.");
let o = mtchs.opt_str("o").expect("Failed to retrieve output file from command args.");
let m = if mtchs.opt_present("m") {
mtchs.opt_str("m").expect("Failed to retrieve max. span between paired bases from command args.").parse().expect("Failed to parse max. span between paired bases.")
} else {
DFLT_MX_SPN
};
let a = mtchs.opt_present("a");
let t = if mtchs.opt_present("t") {
mtchs.opt_str("t").expect("Failed to retrieve # of threads from command args failed.").parse().expect("Failed to parse # of threads.")
} else {
num_cpus::get() as ThrdNm
};
let fasta_rdr = Reader::from_file(Path::new(&i)).ok().expect("Failed to read FASTA file.");
let tm_stmp = gt_tm_stmp();
let tmp_dr = String::from("/tmp/cpr_") + &tm_stmp;
let tmp_dr = Path::new(&tmp_dr);
if!tmp_dr.exists() {
let _ = create_dir(tmp_dr);
}
let mut thrd_pl = Pool::new(t);
thrd_pl.scoped(|scp| {
for rc in fasta_rdr.records() {
scp.execute(|| {
let dt = rc.ok().expect("Failed to read FASTA record.");
let sq = dt.seq().to_vec();
let id = dt.id().expect("Failed to get FASTA record ID.");
let cntxt_dst_sq = cpr(&sq, m, a);
let mut tmp_otpt_fl = BufWriter::new(File::create(tmp_dr.join(&(String::from(id) + ".dat")).to_str().expect("Failed to parse temp. file path.")).expect("Failed to create temp. output file."));
let _ = tmp_otpt_fl.write_all((String::from(">") + id + "\n").as_bytes());
for cntxt_dst in &cntxt_dst_sq {
let mut bfr = cntxt_dst.iter().fold(String::new(), |acmltr, prb| acmltr + &format!("{:e} ", prb));
bfr.pop();
bfr += "\n";
let _ = tmp_otpt_fl.write_all(bfr.as_bytes());
}
let _ = tmp_otpt_fl.write_all(b"\n");
});
}
});
let mut otpt_fl = BufWriter::new(File::create(Path::new(&o)).expect("Failed to create output file."));
let _ = otpt_fl.write_all(b"# CapR version 1.1.0\n# Format = {bulge prob.} {internal prob.} {hairpin prob.} {exterior prob.} {multi prob.} {stem prob.} for the start to the end of each seq.\n");
for prb_dst_sq in tmp_dr.read_dir().ok().expect("Failed to read entries within temp. dir.") {
let prb_dst_sq = prb_dst_sq.ok().expect("Failed to read entry within temp. dir.");
let mut prb_dst_sq = BufReader::new(File::open(prb_dst_sq.path()).expect("Failed to open entry within temp. dir."));
let mut bfr = Vec::new();
let _ = prb_dst_sq.read_to_end(&mut bfr);
let _ = otpt_fl.write_all(&bfr);
}
let _ = remove_dir_all(tmp_dr);
}
#[inline]
fn prnt_usg(prgrm: &str, opts: &Options) {
let brf = format!("Usage: {} [options]", prgrm);
print!("{}", opts.usage(&brf));
}
#[inline]
fn gt_tm_stmp() -> String {
let nw = now();
format!("{}-{}-{}-{}:{}:{}", nw.tm_year + 1900, nw.tm_mon + 1, nw.tm_mday, nw.tm_hour, nw.tm_min, nw.tm_sec)
}
|
{mtch}
|
conditional_block
|
mn.rs
|
extern crate cpr;
extern crate scoped_threadpool;
extern crate getopts;
extern crate bio;
extern crate num_cpus;
extern crate time;
use std::env;
use cpr::cpr;
use getopts::Options;
use std::path::Path;
use bio::io::fasta::Reader;
use scoped_threadpool::Pool;
use std::io::prelude::*;
use std::io::{BufReader, BufWriter};
use std::fs::File;
use time::now;
use std::fs::{remove_dir_all, create_dir};
type Arg = String;
type ThrdNm = u32;
const DFLT_MX_SPN: usize = 200;
fn
|
() {
let args = env::args().collect::<Vec<Arg>>();
let prgrm = args[0].clone();
let mut opts = Options::new();
opts.reqopt("i", "", "Input RNA seqs in single file of FASTA format", "STR");
opts.reqopt("o", "", "Output prob. dist. seqs in single file of tabular format", "STR");
opts.optopt("m", "", &format!("Max. span between paired bases (Default: {})", DFLT_MX_SPN), "UINT");
opts.optopt("t", "", "# of threads in multithreading (Default: system val.)", "UINT");
opts.optflag("a", "", "Approximate estimation");
opts.optflag("h", "help", "Print help menu");
let mtchs = match opts.parse(&args[1..]) {
Ok(mtch) => {mtch}
Err(fl) => {prnt_usg(&prgrm, &opts); panic!(fl.to_string())}
};
if mtchs.opt_present("h") {
prnt_usg(&prgrm, &opts);
return;
}
let i = mtchs.opt_str("i").expect("Failed to retrieve input file from command args.");
let o = mtchs.opt_str("o").expect("Failed to retrieve output file from command args.");
let m = if mtchs.opt_present("m") {
mtchs.opt_str("m").expect("Failed to retrieve max. span between paired bases from command args.").parse().expect("Failed to parse max. span between paired bases.")
} else {
DFLT_MX_SPN
};
let a = mtchs.opt_present("a");
let t = if mtchs.opt_present("t") {
mtchs.opt_str("t").expect("Failed to retrieve # of threads from command args failed.").parse().expect("Failed to parse # of threads.")
} else {
num_cpus::get() as ThrdNm
};
let fasta_rdr = Reader::from_file(Path::new(&i)).ok().expect("Failed to read FASTA file.");
let tm_stmp = gt_tm_stmp();
let tmp_dr = String::from("/tmp/cpr_") + &tm_stmp;
let tmp_dr = Path::new(&tmp_dr);
if!tmp_dr.exists() {
let _ = create_dir(tmp_dr);
}
let mut thrd_pl = Pool::new(t);
thrd_pl.scoped(|scp| {
for rc in fasta_rdr.records() {
scp.execute(|| {
let dt = rc.ok().expect("Failed to read FASTA record.");
let sq = dt.seq().to_vec();
let id = dt.id().expect("Failed to get FASTA record ID.");
let cntxt_dst_sq = cpr(&sq, m, a);
let mut tmp_otpt_fl = BufWriter::new(File::create(tmp_dr.join(&(String::from(id) + ".dat")).to_str().expect("Failed to parse temp. file path.")).expect("Failed to create temp. output file."));
let _ = tmp_otpt_fl.write_all((String::from(">") + id + "\n").as_bytes());
for cntxt_dst in &cntxt_dst_sq {
let mut bfr = cntxt_dst.iter().fold(String::new(), |acmltr, prb| acmltr + &format!("{:e} ", prb));
bfr.pop();
bfr += "\n";
let _ = tmp_otpt_fl.write_all(bfr.as_bytes());
}
let _ = tmp_otpt_fl.write_all(b"\n");
});
}
});
let mut otpt_fl = BufWriter::new(File::create(Path::new(&o)).expect("Failed to create output file."));
let _ = otpt_fl.write_all(b"# CapR version 1.1.0\n# Format = {bulge prob.} {internal prob.} {hairpin prob.} {exterior prob.} {multi prob.} {stem prob.} for the start to the end of each seq.\n");
for prb_dst_sq in tmp_dr.read_dir().ok().expect("Failed to read entries within temp. dir.") {
let prb_dst_sq = prb_dst_sq.ok().expect("Failed to read entry within temp. dir.");
let mut prb_dst_sq = BufReader::new(File::open(prb_dst_sq.path()).expect("Failed to open entry within temp. dir."));
let mut bfr = Vec::new();
let _ = prb_dst_sq.read_to_end(&mut bfr);
let _ = otpt_fl.write_all(&bfr);
}
let _ = remove_dir_all(tmp_dr);
}
#[inline]
fn prnt_usg(prgrm: &str, opts: &Options) {
let brf = format!("Usage: {} [options]", prgrm);
print!("{}", opts.usage(&brf));
}
#[inline]
fn gt_tm_stmp() -> String {
let nw = now();
format!("{}-{}-{}-{}:{}:{}", nw.tm_year + 1900, nw.tm_mon + 1, nw.tm_mday, nw.tm_hour, nw.tm_min, nw.tm_sec)
}
|
main
|
identifier_name
|
rlperrors.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 std::fmt;
use std::error::Error as StdError;
use bytes::FromBytesError;
#[derive(Debug, PartialEq, Eq)]
/// Error concerning the RLP decoder.
pub enum DecoderError {
/// Couldn't convert given bytes to an instance of required type.
FromBytesError(FromBytesError),
/// Data has additional bytes at the end of the valid RLP fragment.
RlpIsTooBig,
/// Data has too few bytes for valid RLP.
RlpIsTooShort,
/// Expect an encoded list, RLP was something else.
RlpExpectedToBeList,
/// Expect encoded data, RLP was something else.
RlpExpectedToBeData,
/// Expected a different size list.
RlpIncorrectListLen,
/// Data length number has a prefixed zero byte, invalid for numbers.
RlpDataLenWithZeroPrefix,
/// List length number has a prefixed zero byte, invalid for numbers.
RlpListLenWithZeroPrefix,
/// Non-canonical (longer than necessary) representation used for data or list.
RlpInvalidIndirection,
/// Declared length is inconsistent with data specified after.
RlpInconsistentLengthAndData,
/// Custom rlp decoding error.
Custom(&'static str),
}
|
impl StdError for DecoderError {
fn description(&self) -> &str {
"builder error"
}
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<FromBytesError> for DecoderError {
fn from(err: FromBytesError) -> DecoderError {
DecoderError::FromBytesError(err)
}
}
|
random_line_split
|
|
rlperrors.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 std::fmt;
use std::error::Error as StdError;
use bytes::FromBytesError;
#[derive(Debug, PartialEq, Eq)]
/// Error concerning the RLP decoder.
pub enum DecoderError {
/// Couldn't convert given bytes to an instance of required type.
FromBytesError(FromBytesError),
/// Data has additional bytes at the end of the valid RLP fragment.
RlpIsTooBig,
/// Data has too few bytes for valid RLP.
RlpIsTooShort,
/// Expect an encoded list, RLP was something else.
RlpExpectedToBeList,
/// Expect encoded data, RLP was something else.
RlpExpectedToBeData,
/// Expected a different size list.
RlpIncorrectListLen,
/// Data length number has a prefixed zero byte, invalid for numbers.
RlpDataLenWithZeroPrefix,
/// List length number has a prefixed zero byte, invalid for numbers.
RlpListLenWithZeroPrefix,
/// Non-canonical (longer than necessary) representation used for data or list.
RlpInvalidIndirection,
/// Declared length is inconsistent with data specified after.
RlpInconsistentLengthAndData,
/// Custom rlp decoding error.
Custom(&'static str),
}
impl StdError for DecoderError {
fn description(&self) -> &str {
"builder error"
}
}
impl fmt::Display for DecoderError {
fn
|
(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<FromBytesError> for DecoderError {
fn from(err: FromBytesError) -> DecoderError {
DecoderError::FromBytesError(err)
}
}
|
fmt
|
identifier_name
|
rlperrors.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 std::fmt;
use std::error::Error as StdError;
use bytes::FromBytesError;
#[derive(Debug, PartialEq, Eq)]
/// Error concerning the RLP decoder.
pub enum DecoderError {
/// Couldn't convert given bytes to an instance of required type.
FromBytesError(FromBytesError),
/// Data has additional bytes at the end of the valid RLP fragment.
RlpIsTooBig,
/// Data has too few bytes for valid RLP.
RlpIsTooShort,
/// Expect an encoded list, RLP was something else.
RlpExpectedToBeList,
/// Expect encoded data, RLP was something else.
RlpExpectedToBeData,
/// Expected a different size list.
RlpIncorrectListLen,
/// Data length number has a prefixed zero byte, invalid for numbers.
RlpDataLenWithZeroPrefix,
/// List length number has a prefixed zero byte, invalid for numbers.
RlpListLenWithZeroPrefix,
/// Non-canonical (longer than necessary) representation used for data or list.
RlpInvalidIndirection,
/// Declared length is inconsistent with data specified after.
RlpInconsistentLengthAndData,
/// Custom rlp decoding error.
Custom(&'static str),
}
impl StdError for DecoderError {
fn description(&self) -> &str {
"builder error"
}
}
impl fmt::Display for DecoderError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self, f)
}
}
impl From<FromBytesError> for DecoderError {
fn from(err: FromBytesError) -> DecoderError
|
}
|
{
DecoderError::FromBytesError(err)
}
|
identifier_body
|
repr-transparent-aggregates-2.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -C no-prepopulate-passes
// ignore-aarch64
// ignore-asmjs
// ignore-mips64
// ignore-powerpc
// ignore-powerpc64
// ignore-powerpc64le
// ignore-s390x
// ignore-sparc
// ignore-sparc64
// ignore-wasm
// ignore-x86
// ignore-x86_64
// See repr-transparent.rs
#![crate_type="lib"]
#[repr(C)]
pub struct Big([u32; 16]);
#[repr(transparent)]
pub struct BigW(Big);
// CHECK: define void @test_Big(%Big* [[BIG_RET_ATTRS:.*]], [16 x i32]
#[no_mangle]
pub extern fn test_Big(_: Big) -> Big { loop {} }
// CHECK: define void @test_BigW(%BigW* [[BIG_RET_ATTRS]], [16 x i32]
#[no_mangle]
pub extern fn test_BigW(_: BigW) -> BigW { loop {} }
#[repr(C)]
pub union BigU {
foo: [u32; 16],
}
#[repr(transparent)]
pub struct BigUw(BigU);
// CHECK: define void @test_BigU(%BigU* [[BIGU_RET_ATTRS:.*]], [16 x i32]
#[no_mangle]
pub extern fn test_BigU(_: BigU) -> BigU { loop {} }
// CHECK: define void @test_BigUw(%BigUw* [[BIGU_RET_ATTRS]], [16 x i32]
#[no_mangle]
pub extern fn
|
(_: BigUw) -> BigUw { loop {} }
|
test_BigUw
|
identifier_name
|
repr-transparent-aggregates-2.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -C no-prepopulate-passes
// ignore-aarch64
// ignore-asmjs
// ignore-mips64
// ignore-powerpc
// ignore-powerpc64
// ignore-powerpc64le
// ignore-s390x
// ignore-sparc
// ignore-sparc64
// ignore-wasm
// ignore-x86
|
#![crate_type="lib"]
#[repr(C)]
pub struct Big([u32; 16]);
#[repr(transparent)]
pub struct BigW(Big);
// CHECK: define void @test_Big(%Big* [[BIG_RET_ATTRS:.*]], [16 x i32]
#[no_mangle]
pub extern fn test_Big(_: Big) -> Big { loop {} }
// CHECK: define void @test_BigW(%BigW* [[BIG_RET_ATTRS]], [16 x i32]
#[no_mangle]
pub extern fn test_BigW(_: BigW) -> BigW { loop {} }
#[repr(C)]
pub union BigU {
foo: [u32; 16],
}
#[repr(transparent)]
pub struct BigUw(BigU);
// CHECK: define void @test_BigU(%BigU* [[BIGU_RET_ATTRS:.*]], [16 x i32]
#[no_mangle]
pub extern fn test_BigU(_: BigU) -> BigU { loop {} }
// CHECK: define void @test_BigUw(%BigUw* [[BIGU_RET_ATTRS]], [16 x i32]
#[no_mangle]
pub extern fn test_BigUw(_: BigUw) -> BigUw { loop {} }
|
// ignore-x86_64
// See repr-transparent.rs
|
random_line_split
|
repr-transparent-aggregates-2.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -C no-prepopulate-passes
// ignore-aarch64
// ignore-asmjs
// ignore-mips64
// ignore-powerpc
// ignore-powerpc64
// ignore-powerpc64le
// ignore-s390x
// ignore-sparc
// ignore-sparc64
// ignore-wasm
// ignore-x86
// ignore-x86_64
// See repr-transparent.rs
#![crate_type="lib"]
#[repr(C)]
pub struct Big([u32; 16]);
#[repr(transparent)]
pub struct BigW(Big);
// CHECK: define void @test_Big(%Big* [[BIG_RET_ATTRS:.*]], [16 x i32]
#[no_mangle]
pub extern fn test_Big(_: Big) -> Big { loop {} }
// CHECK: define void @test_BigW(%BigW* [[BIG_RET_ATTRS]], [16 x i32]
#[no_mangle]
pub extern fn test_BigW(_: BigW) -> BigW { loop {} }
#[repr(C)]
pub union BigU {
foo: [u32; 16],
}
#[repr(transparent)]
pub struct BigUw(BigU);
// CHECK: define void @test_BigU(%BigU* [[BIGU_RET_ATTRS:.*]], [16 x i32]
#[no_mangle]
pub extern fn test_BigU(_: BigU) -> BigU { loop {} }
// CHECK: define void @test_BigUw(%BigUw* [[BIGU_RET_ATTRS]], [16 x i32]
#[no_mangle]
pub extern fn test_BigUw(_: BigUw) -> BigUw
|
{ loop {} }
|
identifier_body
|
|
issue-15896.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Regression test for #15896. It used to ICE rustc.
fn main()
|
{
enum R { REB(()) }
struct Tau { t: uint }
enum E { B(R, Tau) }
let e = B(REB(()), Tau { t: 3 });
let u = match e {
B(
Tau{t: x},
//~^ ERROR mismatched types: expected `main::R`, found `main::Tau`
// (expected enum main::R, found struct main::Tau)
_) => x,
};
}
|
identifier_body
|
|
issue-15896.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Regression test for #15896. It used to ICE rustc.
fn main() {
enum R { REB(()) }
struct
|
{ t: uint }
enum E { B(R, Tau) }
let e = B(REB(()), Tau { t: 3 });
let u = match e {
B(
Tau{t: x},
//~^ ERROR mismatched types: expected `main::R`, found `main::Tau`
// (expected enum main::R, found struct main::Tau)
_) => x,
};
}
|
Tau
|
identifier_name
|
issue-15896.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Regression test for #15896. It used to ICE rustc.
fn main() {
enum R { REB(()) }
struct Tau { t: uint }
enum E { B(R, Tau) }
let e = B(REB(()), Tau { t: 3 });
let u = match e {
B(
Tau{t: x},
//~^ ERROR mismatched types: expected `main::R`, found `main::Tau`
// (expected enum main::R, found struct main::Tau)
_) => x,
};
|
}
|
random_line_split
|
|
units.rs
|
use std::ops::Add;
use std::marker::PhantomData;
/// Create void enumerations to define unit types.
#[derive(Debug, Clone, Copy)]
enum Inch {}
#[derive(Debug, Clone, Copy)]
enum Mm {}
/// `Length` is a type with phantom type parameter `Unit`,
/// and is not generic over the length type (that is `f64`).
///
/// `f64` already implements the `Clone` and `Copy` traits.
#[derive(Debug, Clone, Copy)]
struct Length<Unit>(f64, PhantomData<Unit>);
|
impl<Unit> Add for Length<Unit> {
type Output = Length<Unit>;
// add() returns a new `Length` struct containing the sum.
fn add(self, rhs: Length<Unit>) -> Length<Unit> {
// `+` calls the `Add` implementation for `f64`.
Length(self.0 + rhs.0, PhantomData)
}
}
fn main() {
// Specifies `one_foot` to have phantom type parameter `Inch`.
let one_foot: Length<Inch> = Length(12.0, PhantomData);
// `one_meter` has phantom type parameter `Mm`.
let one_meter: Length<Mm> = Length(1000.0, PhantomData);
// `+` calls the `add()` method we implemented for `Length<Unit>`.
//
// Since `Length` implements `Copy`, `add()` does not consume
// `one_foot` and `one_meter` but copies them into `self` and `rhs`.
let two_feet = one_foot + one_foot;
let two_meters = one_meter + one_meter;
// Addition works.
println!("one foot + one_foot = {:?} in", two_feet.0);
println!("one meter + one_meter = {:?} mm", two_meters.0);
// Nonsensical operations fail as they should:
// Compile-time Error: type mismatch.
//let one_feter = one_foot + one_meter;
}
|
/// The `Add` trait defines the behavior of the `+` operator.
|
random_line_split
|
units.rs
|
use std::ops::Add;
use std::marker::PhantomData;
/// Create void enumerations to define unit types.
#[derive(Debug, Clone, Copy)]
enum Inch {}
#[derive(Debug, Clone, Copy)]
enum Mm {}
/// `Length` is a type with phantom type parameter `Unit`,
/// and is not generic over the length type (that is `f64`).
///
/// `f64` already implements the `Clone` and `Copy` traits.
#[derive(Debug, Clone, Copy)]
struct Length<Unit>(f64, PhantomData<Unit>);
/// The `Add` trait defines the behavior of the `+` operator.
impl<Unit> Add for Length<Unit> {
type Output = Length<Unit>;
// add() returns a new `Length` struct containing the sum.
fn add(self, rhs: Length<Unit>) -> Length<Unit> {
// `+` calls the `Add` implementation for `f64`.
Length(self.0 + rhs.0, PhantomData)
}
}
fn
|
() {
// Specifies `one_foot` to have phantom type parameter `Inch`.
let one_foot: Length<Inch> = Length(12.0, PhantomData);
// `one_meter` has phantom type parameter `Mm`.
let one_meter: Length<Mm> = Length(1000.0, PhantomData);
// `+` calls the `add()` method we implemented for `Length<Unit>`.
//
// Since `Length` implements `Copy`, `add()` does not consume
// `one_foot` and `one_meter` but copies them into `self` and `rhs`.
let two_feet = one_foot + one_foot;
let two_meters = one_meter + one_meter;
// Addition works.
println!("one foot + one_foot = {:?} in", two_feet.0);
println!("one meter + one_meter = {:?} mm", two_meters.0);
// Nonsensical operations fail as they should:
// Compile-time Error: type mismatch.
//let one_feter = one_foot + one_meter;
}
|
main
|
identifier_name
|
units.rs
|
use std::ops::Add;
use std::marker::PhantomData;
/// Create void enumerations to define unit types.
#[derive(Debug, Clone, Copy)]
enum Inch {}
#[derive(Debug, Clone, Copy)]
enum Mm {}
/// `Length` is a type with phantom type parameter `Unit`,
/// and is not generic over the length type (that is `f64`).
///
/// `f64` already implements the `Clone` and `Copy` traits.
#[derive(Debug, Clone, Copy)]
struct Length<Unit>(f64, PhantomData<Unit>);
/// The `Add` trait defines the behavior of the `+` operator.
impl<Unit> Add for Length<Unit> {
type Output = Length<Unit>;
// add() returns a new `Length` struct containing the sum.
fn add(self, rhs: Length<Unit>) -> Length<Unit>
|
}
fn main() {
// Specifies `one_foot` to have phantom type parameter `Inch`.
let one_foot: Length<Inch> = Length(12.0, PhantomData);
// `one_meter` has phantom type parameter `Mm`.
let one_meter: Length<Mm> = Length(1000.0, PhantomData);
// `+` calls the `add()` method we implemented for `Length<Unit>`.
//
// Since `Length` implements `Copy`, `add()` does not consume
// `one_foot` and `one_meter` but copies them into `self` and `rhs`.
let two_feet = one_foot + one_foot;
let two_meters = one_meter + one_meter;
// Addition works.
println!("one foot + one_foot = {:?} in", two_feet.0);
println!("one meter + one_meter = {:?} mm", two_meters.0);
// Nonsensical operations fail as they should:
// Compile-time Error: type mismatch.
//let one_feter = one_foot + one_meter;
}
|
{
// `+` calls the `Add` implementation for `f64`.
Length(self.0 + rhs.0, PhantomData)
}
|
identifier_body
|
ds.rs
|
/*
* Copyright (C) 2016 Benjamin Fry <[email protected]>
*
* 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.
*/
//! pointer record from parent zone to child zone for dnskey proof
use crate::error::*;
use crate::rr::dnssec::{Algorithm, DigestType};
use crate::serialize::binary::*;
use crate::rr::dnssec::rdata::DNSKEY;
use crate::rr::Name;
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5)
///
/// ```text
/// 5.1. DS RDATA Wire Format
///
/// The RDATA for a DS RR consists of a 2 octet Key Tag field, a 1 octet
/// Algorithm field, a 1 octet Digest Type field, and a Digest field.
///
/// 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | Key Tag | Algorithm | Digest Type |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// / /
/// / Digest /
/// / /
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// 5.2. Processing of DS RRs When Validating Responses
///
/// The DS RR links the authentication chain across zone boundaries, so
/// the DS RR requires extra care in processing. The DNSKEY RR referred
/// to in the DS RR MUST be a DNSSEC zone key. The DNSKEY RR Flags MUST
/// have Flags bit 7 set. If the DNSKEY flags do not indicate a DNSSEC
/// zone key, the DS RR (and the DNSKEY RR it references) MUST NOT be
/// used in the validation process.
///
/// 5.3. The DS RR Presentation Format
///
/// The presentation format of the RDATA portion is as follows:
///
/// The Key Tag field MUST be represented as an unsigned decimal integer.
///
/// The Algorithm field MUST be represented either as an unsigned decimal
/// integer or as an algorithm mnemonic specified in Appendix A.1.
///
/// The Digest Type field MUST be represented as an unsigned decimal
/// integer.
///
/// The Digest MUST be represented as a sequence of case-insensitive
/// hexadecimal digits. Whitespace is allowed within the hexadecimal
/// text.
/// ```
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct DS {
key_tag: u16,
algorithm: Algorithm,
digest_type: DigestType,
digest: Vec<u8>,
}
impl DS {
/// Constructs a new DS RData
///
/// # Arguments
///
/// * `key_tag` - the key_tag associated to the DNSKEY
/// * `algorithm` - algorithm as specified in the DNSKEY
/// * `digest_type` - hash algorithm used to validate the DNSKEY
/// * `digest` - hash of the DNSKEY
///
/// # Returns
///
/// the DS RDATA for use in a Resource Record
pub fn new(key_tag: u16, algorithm: Algorithm, digest_type: DigestType, digest: Vec<u8>) -> DS {
DS {
key_tag,
algorithm,
digest_type,
digest,
}
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.1. The Key Tag Field
///
/// The Key Tag field lists the key tag of the DNSKEY RR referred to by
/// the DS record, in network byte order.
///
/// The Key Tag used by the DS RR is identical to the Key Tag used by
/// RRSIG RRs. Appendix B describes how to compute a Key Tag.
/// ```
pub fn key_tag(&self) -> u16 {
self.key_tag
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.2. The Algorithm Field
///
/// The Algorithm field lists the algorithm number of the DNSKEY RR
/// referred to by the DS record.
///
/// The algorithm number used by the DS RR is identical to the algorithm
/// number used by RRSIG and DNSKEY RRs. Appendix A.1 lists the
/// algorithm number types.
/// ```
pub fn algorithm(&self) -> Algorithm {
self.algorithm
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.3. The Digest Type Field
///
/// The DS RR refers to a DNSKEY RR by including a digest of that DNSKEY
/// RR. The Digest Type field identifies the algorithm used to construct
/// the digest. Appendix A.2 lists the possible digest algorithm types.
/// ```
pub fn digest_type(&self) -> DigestType {
self.digest_type
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.4. The Digest Field
///
/// The DS record refers to a DNSKEY RR by including a digest of that
/// DNSKEY RR.
///
/// The digest is calculated by concatenating the canonical form of the
/// fully qualified owner name of the DNSKEY RR with the DNSKEY RDATA,
/// and then applying the digest algorithm.
///
/// digest = digest_algorithm( DNSKEY owner name | DNSKEY RDATA);
///
/// "|" denotes concatenation
///
/// DNSKEY RDATA = Flags | Protocol | Algorithm | Public Key.
///
/// The size of the digest may vary depending on the digest algorithm and
/// DNSKEY RR size. As of the time of this writing, the only defined
/// digest algorithm is SHA-1, which produces a 20 octet digest.
/// ```
pub fn digest(&self) -> &[u8] {
&self.digest
}
/// Validates that a given DNSKEY is covered by the DS record.
///
/// # Return
///
/// true if and only if the DNSKEY is covered by the DS record.
#[cfg(any(feature = "openssl", feature = "ring"))]
pub fn covers(&self, name: &Name, key: &DNSKEY) -> ProtoResult<bool> {
key.to_digest(name, self.digest_type())
.map(|hash| hash.as_ref() == self.digest())
}
/// This will always return an error unless the Ring or OpenSSL features are enabled
#[cfg(not(any(feature = "openssl", feature = "ring")))]
pub fn covers(&self, _: &Name, _: &DNSKEY) -> ProtoResult<bool>
|
}
/// Read the RData from the given Decoder
pub fn read(decoder: &mut BinDecoder, rdata_length: Restrict<u16>) -> ProtoResult<DS> {
let start_idx = decoder.index();
let key_tag: u16 = decoder.read_u16()?.unverified(/*key_tag is valid as any u16*/);
let algorithm: Algorithm = Algorithm::read(decoder)?;
let digest_type: DigestType =
DigestType::from_u8(decoder.read_u8()?.unverified(/*DigestType is verified as safe*/))?;
let bytes_read = decoder.index() - start_idx;
let left: usize = rdata_length
.map(|u| u as usize)
.checked_sub(bytes_read)
.map_err(|_| ProtoError::from("invalid rdata length in DS"))?
.unverified(/*used only as length safely*/);
let digest =
decoder.read_vec(left)?.unverified(/*the byte array will fail in usage if invalid*/);
Ok(DS::new(key_tag, algorithm, digest_type, digest))
}
/// Write the RData from the given Decoder
pub fn emit(encoder: &mut BinEncoder, rdata: &DS) -> ProtoResult<()> {
encoder.emit_u16(rdata.key_tag())?;
rdata.algorithm().emit(encoder)?; // always 3 for now
encoder.emit(rdata.digest_type().into())?;
encoder.emit_vec(rdata.digest())?;
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::dbg_macro, clippy::print_stdout)]
use super::*;
#[test]
pub fn test() {
let rdata = DS::new(
0xF00F,
Algorithm::RSASHA256,
DigestType::SHA256,
vec![5, 6, 7, 8],
);
let mut bytes = Vec::new();
let mut encoder: BinEncoder = BinEncoder::new(&mut bytes);
assert!(emit(&mut encoder, &rdata).is_ok());
let bytes = encoder.into_bytes();
println!("bytes: {:?}", bytes);
let mut decoder: BinDecoder = BinDecoder::new(bytes);
let restrict = Restrict::new(bytes.len() as u16);
let read_rdata = read(&mut decoder, restrict).expect("Decoding error");
assert_eq!(rdata, read_rdata);
}
#[test]
#[cfg(any(feature = "openssl", feature = "ring"))]
pub fn test_covers() {
use crate::rr::dnssec::rdata::DNSKEY;
let name = Name::parse("www.example.com.", None).unwrap();
let dnskey_rdata = DNSKEY::new(true, true, false, Algorithm::RSASHA256, vec![1, 2, 3, 4]);
let ds_rdata = DS::new(
0,
Algorithm::RSASHA256,
DigestType::SHA256,
dnskey_rdata
.to_digest(&name, DigestType::SHA256)
.unwrap()
.as_ref()
.to_owned(),
);
assert!(ds_rdata.covers(&name, &dnskey_rdata).unwrap());
}
}
|
{
Err("Ring or OpenSSL must be enabled for this feature".into())
}
|
identifier_body
|
ds.rs
|
/*
* Copyright (C) 2016 Benjamin Fry <[email protected]>
*
* 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.
*/
//! pointer record from parent zone to child zone for dnskey proof
use crate::error::*;
use crate::rr::dnssec::{Algorithm, DigestType};
use crate::serialize::binary::*;
use crate::rr::dnssec::rdata::DNSKEY;
use crate::rr::Name;
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5)
///
/// ```text
/// 5.1. DS RDATA Wire Format
///
/// The RDATA for a DS RR consists of a 2 octet Key Tag field, a 1 octet
/// Algorithm field, a 1 octet Digest Type field, and a Digest field.
///
/// 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | Key Tag | Algorithm | Digest Type |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// / /
/// / Digest /
/// / /
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// 5.2. Processing of DS RRs When Validating Responses
///
/// The DS RR links the authentication chain across zone boundaries, so
/// the DS RR requires extra care in processing. The DNSKEY RR referred
/// to in the DS RR MUST be a DNSSEC zone key. The DNSKEY RR Flags MUST
/// have Flags bit 7 set. If the DNSKEY flags do not indicate a DNSSEC
/// zone key, the DS RR (and the DNSKEY RR it references) MUST NOT be
/// used in the validation process.
///
/// 5.3. The DS RR Presentation Format
///
/// The presentation format of the RDATA portion is as follows:
///
/// The Key Tag field MUST be represented as an unsigned decimal integer.
///
/// The Algorithm field MUST be represented either as an unsigned decimal
/// integer or as an algorithm mnemonic specified in Appendix A.1.
///
/// The Digest Type field MUST be represented as an unsigned decimal
/// integer.
///
/// The Digest MUST be represented as a sequence of case-insensitive
/// hexadecimal digits. Whitespace is allowed within the hexadecimal
/// text.
/// ```
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct DS {
key_tag: u16,
algorithm: Algorithm,
digest_type: DigestType,
digest: Vec<u8>,
}
impl DS {
/// Constructs a new DS RData
///
/// # Arguments
///
/// * `key_tag` - the key_tag associated to the DNSKEY
/// * `algorithm` - algorithm as specified in the DNSKEY
/// * `digest_type` - hash algorithm used to validate the DNSKEY
/// * `digest` - hash of the DNSKEY
///
/// # Returns
///
/// the DS RDATA for use in a Resource Record
pub fn new(key_tag: u16, algorithm: Algorithm, digest_type: DigestType, digest: Vec<u8>) -> DS {
DS {
key_tag,
algorithm,
digest_type,
digest,
}
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.1. The Key Tag Field
///
/// The Key Tag field lists the key tag of the DNSKEY RR referred to by
/// the DS record, in network byte order.
///
/// The Key Tag used by the DS RR is identical to the Key Tag used by
/// RRSIG RRs. Appendix B describes how to compute a Key Tag.
/// ```
pub fn key_tag(&self) -> u16 {
self.key_tag
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.2. The Algorithm Field
///
/// The Algorithm field lists the algorithm number of the DNSKEY RR
/// referred to by the DS record.
///
/// The algorithm number used by the DS RR is identical to the algorithm
/// number used by RRSIG and DNSKEY RRs. Appendix A.1 lists the
/// algorithm number types.
/// ```
pub fn algorithm(&self) -> Algorithm {
self.algorithm
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.3. The Digest Type Field
///
/// The DS RR refers to a DNSKEY RR by including a digest of that DNSKEY
/// RR. The Digest Type field identifies the algorithm used to construct
/// the digest. Appendix A.2 lists the possible digest algorithm types.
/// ```
pub fn digest_type(&self) -> DigestType {
self.digest_type
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.4. The Digest Field
///
/// The DS record refers to a DNSKEY RR by including a digest of that
/// DNSKEY RR.
///
/// The digest is calculated by concatenating the canonical form of the
/// fully qualified owner name of the DNSKEY RR with the DNSKEY RDATA,
/// and then applying the digest algorithm.
///
/// digest = digest_algorithm( DNSKEY owner name | DNSKEY RDATA);
///
/// "|" denotes concatenation
///
/// DNSKEY RDATA = Flags | Protocol | Algorithm | Public Key.
///
/// The size of the digest may vary depending on the digest algorithm and
/// DNSKEY RR size. As of the time of this writing, the only defined
/// digest algorithm is SHA-1, which produces a 20 octet digest.
/// ```
pub fn digest(&self) -> &[u8] {
&self.digest
}
/// Validates that a given DNSKEY is covered by the DS record.
///
/// # Return
///
/// true if and only if the DNSKEY is covered by the DS record.
#[cfg(any(feature = "openssl", feature = "ring"))]
|
pub fn covers(&self, name: &Name, key: &DNSKEY) -> ProtoResult<bool> {
key.to_digest(name, self.digest_type())
.map(|hash| hash.as_ref() == self.digest())
}
/// This will always return an error unless the Ring or OpenSSL features are enabled
#[cfg(not(any(feature = "openssl", feature = "ring")))]
pub fn covers(&self, _: &Name, _: &DNSKEY) -> ProtoResult<bool> {
Err("Ring or OpenSSL must be enabled for this feature".into())
}
}
/// Read the RData from the given Decoder
pub fn read(decoder: &mut BinDecoder, rdata_length: Restrict<u16>) -> ProtoResult<DS> {
let start_idx = decoder.index();
let key_tag: u16 = decoder.read_u16()?.unverified(/*key_tag is valid as any u16*/);
let algorithm: Algorithm = Algorithm::read(decoder)?;
let digest_type: DigestType =
DigestType::from_u8(decoder.read_u8()?.unverified(/*DigestType is verified as safe*/))?;
let bytes_read = decoder.index() - start_idx;
let left: usize = rdata_length
.map(|u| u as usize)
.checked_sub(bytes_read)
.map_err(|_| ProtoError::from("invalid rdata length in DS"))?
.unverified(/*used only as length safely*/);
let digest =
decoder.read_vec(left)?.unverified(/*the byte array will fail in usage if invalid*/);
Ok(DS::new(key_tag, algorithm, digest_type, digest))
}
/// Write the RData from the given Decoder
pub fn emit(encoder: &mut BinEncoder, rdata: &DS) -> ProtoResult<()> {
encoder.emit_u16(rdata.key_tag())?;
rdata.algorithm().emit(encoder)?; // always 3 for now
encoder.emit(rdata.digest_type().into())?;
encoder.emit_vec(rdata.digest())?;
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::dbg_macro, clippy::print_stdout)]
use super::*;
#[test]
pub fn test() {
let rdata = DS::new(
0xF00F,
Algorithm::RSASHA256,
DigestType::SHA256,
vec![5, 6, 7, 8],
);
let mut bytes = Vec::new();
let mut encoder: BinEncoder = BinEncoder::new(&mut bytes);
assert!(emit(&mut encoder, &rdata).is_ok());
let bytes = encoder.into_bytes();
println!("bytes: {:?}", bytes);
let mut decoder: BinDecoder = BinDecoder::new(bytes);
let restrict = Restrict::new(bytes.len() as u16);
let read_rdata = read(&mut decoder, restrict).expect("Decoding error");
assert_eq!(rdata, read_rdata);
}
#[test]
#[cfg(any(feature = "openssl", feature = "ring"))]
pub fn test_covers() {
use crate::rr::dnssec::rdata::DNSKEY;
let name = Name::parse("www.example.com.", None).unwrap();
let dnskey_rdata = DNSKEY::new(true, true, false, Algorithm::RSASHA256, vec![1, 2, 3, 4]);
let ds_rdata = DS::new(
0,
Algorithm::RSASHA256,
DigestType::SHA256,
dnskey_rdata
.to_digest(&name, DigestType::SHA256)
.unwrap()
.as_ref()
.to_owned(),
);
assert!(ds_rdata.covers(&name, &dnskey_rdata).unwrap());
}
}
|
random_line_split
|
|
ds.rs
|
/*
* Copyright (C) 2016 Benjamin Fry <[email protected]>
*
* 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.
*/
//! pointer record from parent zone to child zone for dnskey proof
use crate::error::*;
use crate::rr::dnssec::{Algorithm, DigestType};
use crate::serialize::binary::*;
use crate::rr::dnssec::rdata::DNSKEY;
use crate::rr::Name;
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5)
///
/// ```text
/// 5.1. DS RDATA Wire Format
///
/// The RDATA for a DS RR consists of a 2 octet Key Tag field, a 1 octet
/// Algorithm field, a 1 octet Digest Type field, and a Digest field.
///
/// 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// | Key Tag | Algorithm | Digest Type |
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/// / /
/// / Digest /
/// / /
/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
///
/// 5.2. Processing of DS RRs When Validating Responses
///
/// The DS RR links the authentication chain across zone boundaries, so
/// the DS RR requires extra care in processing. The DNSKEY RR referred
/// to in the DS RR MUST be a DNSSEC zone key. The DNSKEY RR Flags MUST
/// have Flags bit 7 set. If the DNSKEY flags do not indicate a DNSSEC
/// zone key, the DS RR (and the DNSKEY RR it references) MUST NOT be
/// used in the validation process.
///
/// 5.3. The DS RR Presentation Format
///
/// The presentation format of the RDATA portion is as follows:
///
/// The Key Tag field MUST be represented as an unsigned decimal integer.
///
/// The Algorithm field MUST be represented either as an unsigned decimal
/// integer or as an algorithm mnemonic specified in Appendix A.1.
///
/// The Digest Type field MUST be represented as an unsigned decimal
/// integer.
///
/// The Digest MUST be represented as a sequence of case-insensitive
/// hexadecimal digits. Whitespace is allowed within the hexadecimal
/// text.
/// ```
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct DS {
key_tag: u16,
algorithm: Algorithm,
digest_type: DigestType,
digest: Vec<u8>,
}
impl DS {
/// Constructs a new DS RData
///
/// # Arguments
///
/// * `key_tag` - the key_tag associated to the DNSKEY
/// * `algorithm` - algorithm as specified in the DNSKEY
/// * `digest_type` - hash algorithm used to validate the DNSKEY
/// * `digest` - hash of the DNSKEY
///
/// # Returns
///
/// the DS RDATA for use in a Resource Record
pub fn new(key_tag: u16, algorithm: Algorithm, digest_type: DigestType, digest: Vec<u8>) -> DS {
DS {
key_tag,
algorithm,
digest_type,
digest,
}
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.1. The Key Tag Field
///
/// The Key Tag field lists the key tag of the DNSKEY RR referred to by
/// the DS record, in network byte order.
///
/// The Key Tag used by the DS RR is identical to the Key Tag used by
/// RRSIG RRs. Appendix B describes how to compute a Key Tag.
/// ```
pub fn key_tag(&self) -> u16 {
self.key_tag
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.2. The Algorithm Field
///
/// The Algorithm field lists the algorithm number of the DNSKEY RR
/// referred to by the DS record.
///
/// The algorithm number used by the DS RR is identical to the algorithm
/// number used by RRSIG and DNSKEY RRs. Appendix A.1 lists the
/// algorithm number types.
/// ```
pub fn algorithm(&self) -> Algorithm {
self.algorithm
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.3. The Digest Type Field
///
/// The DS RR refers to a DNSKEY RR by including a digest of that DNSKEY
/// RR. The Digest Type field identifies the algorithm used to construct
/// the digest. Appendix A.2 lists the possible digest algorithm types.
/// ```
pub fn digest_type(&self) -> DigestType {
self.digest_type
}
/// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5.1.1)
///
/// ```text
/// 5.1.4. The Digest Field
///
/// The DS record refers to a DNSKEY RR by including a digest of that
/// DNSKEY RR.
///
/// The digest is calculated by concatenating the canonical form of the
/// fully qualified owner name of the DNSKEY RR with the DNSKEY RDATA,
/// and then applying the digest algorithm.
///
/// digest = digest_algorithm( DNSKEY owner name | DNSKEY RDATA);
///
/// "|" denotes concatenation
///
/// DNSKEY RDATA = Flags | Protocol | Algorithm | Public Key.
///
/// The size of the digest may vary depending on the digest algorithm and
/// DNSKEY RR size. As of the time of this writing, the only defined
/// digest algorithm is SHA-1, which produces a 20 octet digest.
/// ```
pub fn digest(&self) -> &[u8] {
&self.digest
}
/// Validates that a given DNSKEY is covered by the DS record.
///
/// # Return
///
/// true if and only if the DNSKEY is covered by the DS record.
#[cfg(any(feature = "openssl", feature = "ring"))]
pub fn covers(&self, name: &Name, key: &DNSKEY) -> ProtoResult<bool> {
key.to_digest(name, self.digest_type())
.map(|hash| hash.as_ref() == self.digest())
}
/// This will always return an error unless the Ring or OpenSSL features are enabled
#[cfg(not(any(feature = "openssl", feature = "ring")))]
pub fn covers(&self, _: &Name, _: &DNSKEY) -> ProtoResult<bool> {
Err("Ring or OpenSSL must be enabled for this feature".into())
}
}
/// Read the RData from the given Decoder
pub fn read(decoder: &mut BinDecoder, rdata_length: Restrict<u16>) -> ProtoResult<DS> {
let start_idx = decoder.index();
let key_tag: u16 = decoder.read_u16()?.unverified(/*key_tag is valid as any u16*/);
let algorithm: Algorithm = Algorithm::read(decoder)?;
let digest_type: DigestType =
DigestType::from_u8(decoder.read_u8()?.unverified(/*DigestType is verified as safe*/))?;
let bytes_read = decoder.index() - start_idx;
let left: usize = rdata_length
.map(|u| u as usize)
.checked_sub(bytes_read)
.map_err(|_| ProtoError::from("invalid rdata length in DS"))?
.unverified(/*used only as length safely*/);
let digest =
decoder.read_vec(left)?.unverified(/*the byte array will fail in usage if invalid*/);
Ok(DS::new(key_tag, algorithm, digest_type, digest))
}
/// Write the RData from the given Decoder
pub fn
|
(encoder: &mut BinEncoder, rdata: &DS) -> ProtoResult<()> {
encoder.emit_u16(rdata.key_tag())?;
rdata.algorithm().emit(encoder)?; // always 3 for now
encoder.emit(rdata.digest_type().into())?;
encoder.emit_vec(rdata.digest())?;
Ok(())
}
#[cfg(test)]
mod tests {
#![allow(clippy::dbg_macro, clippy::print_stdout)]
use super::*;
#[test]
pub fn test() {
let rdata = DS::new(
0xF00F,
Algorithm::RSASHA256,
DigestType::SHA256,
vec![5, 6, 7, 8],
);
let mut bytes = Vec::new();
let mut encoder: BinEncoder = BinEncoder::new(&mut bytes);
assert!(emit(&mut encoder, &rdata).is_ok());
let bytes = encoder.into_bytes();
println!("bytes: {:?}", bytes);
let mut decoder: BinDecoder = BinDecoder::new(bytes);
let restrict = Restrict::new(bytes.len() as u16);
let read_rdata = read(&mut decoder, restrict).expect("Decoding error");
assert_eq!(rdata, read_rdata);
}
#[test]
#[cfg(any(feature = "openssl", feature = "ring"))]
pub fn test_covers() {
use crate::rr::dnssec::rdata::DNSKEY;
let name = Name::parse("www.example.com.", None).unwrap();
let dnskey_rdata = DNSKEY::new(true, true, false, Algorithm::RSASHA256, vec![1, 2, 3, 4]);
let ds_rdata = DS::new(
0,
Algorithm::RSASHA256,
DigestType::SHA256,
dnskey_rdata
.to_digest(&name, DigestType::SHA256)
.unwrap()
.as_ref()
.to_owned(),
);
assert!(ds_rdata.covers(&name, &dnskey_rdata).unwrap());
}
}
|
emit
|
identifier_name
|
segment.rs
|
use backend::obj;
use backend::obj::*;
use backend::world::agent;
use core::clock::Seconds;
use core::geometry::Transform;
use core::geometry::*;
use core::math;
use core::math::ExponentialFilter;
use num::Zero;
#[derive(Clone)]
pub enum PilotRotation {
None,
Orientation(Position),
LookAt(Position),
Turn(Angle),
FromVelocity,
}
#[derive(Clone)]
pub enum Intent {
Idle,
Move(Position),
Brake(Position),
RunAway(Position),
PilotTo(Option<Position>, PilotRotation),
|
#[derive(Clone)]
pub struct State {
age_seconds: Seconds,
age_frames: usize,
maturity: f32,
charge: ExponentialFilter<f32>,
pub intent: Intent,
pub last_touched: Option<agent::Key>,
}
impl Default for State {
fn default() -> Self {
State {
age_seconds: Seconds::zero(),
age_frames: 0,
maturity: 1.0,
charge: math::exponential_filter(0., 1., 2.),
intent: Intent::Idle,
last_touched: None,
}
}
}
impl State {
pub fn age_seconds(&self) -> Seconds { self.age_seconds }
pub fn age_frames(&self) -> usize { self.age_frames }
pub fn charge(&self) -> f32 { self.charge.get() }
pub fn reset_charge(&mut self, current_charge: f32, target_charge: f32) {
self.charge.reset_to(target_charge, current_charge);
}
pub fn set_output_charge(&mut self, charge: f32) { self.charge.force_to(charge); }
pub fn target_charge(&self) -> f32 { self.charge.last_input() }
pub fn set_target_charge(&mut self, target_charge: f32) { self.charge.input(target_charge); }
//pub fn recharge(&self) -> f32 { self.recharge }
pub fn maturity(&self) -> f32 { self.maturity }
pub fn set_maturity(&mut self, maturity: f32) { self.maturity = maturity }
pub fn restore(&mut self, current_charge: f32, target_charge: f32) {
self.charge.reset_to(target_charge, current_charge);
}
pub fn update(&mut self, dt: Seconds) {
self.age_seconds += dt;
self.age_frames += 1;
self.charge.update(dt.into());
}
pub fn with_charge(current_charge: f32, target_charge: f32, charge_decay_time: Seconds) -> Self {
State {
charge: math::exponential_filter(target_charge, current_charge, charge_decay_time.get() as f32),
..Self::default()
}
}
}
#[derive(Copy, Clone)]
pub struct Attachment {
pub index: SegmentIndex,
pub attachment_point: AttachmentIndex,
}
bitflags! {
pub struct Flags: u32 {
const SENSOR = 0x00001u32;
const ACTUATOR = 0x00002u32;
const JOINT = 0x00004u32;
const MOUTH = 0x00008u32;
const HEAD = 0x00010u32;
const LEG = 0x00020u32;
const ARM = 0x00040u32;
const CORE = 0x00100u32;
const STORAGE = 0x00200u32;
const TAIL = 0x00400u32;
const TRACKER = 0x00800u32;
const LEFT = 0x01000u32;
const RIGHT = 0x02000u32;
const MIDDLE = 0x04000u32;
const THRUSTER = 0x10000u32;
const RUDDER = 0x20000u32;
const BRAKE = 0x40000u32;
}
}
#[derive(Clone)]
pub struct Segment {
pub transform: Transform,
pub rest_angle: Angle,
pub motion: Motion,
pub index: SegmentIndex,
pub mesh: Mesh,
pub material: Material,
pub livery: Livery,
pub attached_to: Option<Attachment>,
pub state: State,
pub flags: Flags,
}
impl Segment {
pub fn new_attachment(&self, attachment_point: AttachmentIndex) -> Option<Attachment> {
let max = self.mesh.vertices.len() as AttachmentIndex;
Some(Attachment {
index: self.index,
attachment_point: if attachment_point < max { attachment_point } else { max - 1 },
})
}
pub fn growing_radius(&self) -> f32 { self.state.maturity * self.mesh.shape.radius() }
pub fn growing_scaled_vertex(&self, index: usize) -> Position {
self.state.maturity * self.mesh.scaled_vertex(index)
}
}
impl obj::Drawable for Segment {
fn color(&self) -> Rgba {
let rgba = self.livery.albedo;
let c = 5. * ((self.state.charge.get() * 0.99) + 0.01);
[rgba[0] * c, rgba[1] * c, rgba[2] * c, rgba[3] * self.material.density]
}
}
impl Transformable for Segment {
fn transform(&self) -> &Transform { &self.transform }
fn transform_to(&mut self, t: Transform) { self.transform = t; }
}
impl Motionable for Segment {
fn motion(&self) -> &Motion { &self.motion }
fn motion_to(&mut self, m: Motion) { self.motion = m; }
}
impl obj::Geometry for Segment {
fn mesh(&self) -> &Mesh { &self.mesh }
}
impl obj::Solid for Segment {
fn material(&self) -> &Material { &self.material }
fn livery(&self) -> &Livery { &self.livery }
}
|
}
|
random_line_split
|
segment.rs
|
use backend::obj;
use backend::obj::*;
use backend::world::agent;
use core::clock::Seconds;
use core::geometry::Transform;
use core::geometry::*;
use core::math;
use core::math::ExponentialFilter;
use num::Zero;
#[derive(Clone)]
pub enum PilotRotation {
None,
Orientation(Position),
LookAt(Position),
Turn(Angle),
FromVelocity,
}
#[derive(Clone)]
pub enum Intent {
Idle,
Move(Position),
Brake(Position),
RunAway(Position),
PilotTo(Option<Position>, PilotRotation),
}
#[derive(Clone)]
pub struct State {
age_seconds: Seconds,
age_frames: usize,
maturity: f32,
charge: ExponentialFilter<f32>,
pub intent: Intent,
pub last_touched: Option<agent::Key>,
}
impl Default for State {
fn default() -> Self {
State {
age_seconds: Seconds::zero(),
age_frames: 0,
maturity: 1.0,
charge: math::exponential_filter(0., 1., 2.),
intent: Intent::Idle,
last_touched: None,
}
}
}
impl State {
pub fn age_seconds(&self) -> Seconds { self.age_seconds }
pub fn age_frames(&self) -> usize { self.age_frames }
pub fn charge(&self) -> f32 { self.charge.get() }
pub fn reset_charge(&mut self, current_charge: f32, target_charge: f32) {
self.charge.reset_to(target_charge, current_charge);
}
pub fn set_output_charge(&mut self, charge: f32) { self.charge.force_to(charge); }
pub fn target_charge(&self) -> f32 { self.charge.last_input() }
pub fn set_target_charge(&mut self, target_charge: f32) { self.charge.input(target_charge); }
//pub fn recharge(&self) -> f32 { self.recharge }
pub fn maturity(&self) -> f32 { self.maturity }
pub fn set_maturity(&mut self, maturity: f32)
|
pub fn restore(&mut self, current_charge: f32, target_charge: f32) {
self.charge.reset_to(target_charge, current_charge);
}
pub fn update(&mut self, dt: Seconds) {
self.age_seconds += dt;
self.age_frames += 1;
self.charge.update(dt.into());
}
pub fn with_charge(current_charge: f32, target_charge: f32, charge_decay_time: Seconds) -> Self {
State {
charge: math::exponential_filter(target_charge, current_charge, charge_decay_time.get() as f32),
..Self::default()
}
}
}
#[derive(Copy, Clone)]
pub struct Attachment {
pub index: SegmentIndex,
pub attachment_point: AttachmentIndex,
}
bitflags! {
pub struct Flags: u32 {
const SENSOR = 0x00001u32;
const ACTUATOR = 0x00002u32;
const JOINT = 0x00004u32;
const MOUTH = 0x00008u32;
const HEAD = 0x00010u32;
const LEG = 0x00020u32;
const ARM = 0x00040u32;
const CORE = 0x00100u32;
const STORAGE = 0x00200u32;
const TAIL = 0x00400u32;
const TRACKER = 0x00800u32;
const LEFT = 0x01000u32;
const RIGHT = 0x02000u32;
const MIDDLE = 0x04000u32;
const THRUSTER = 0x10000u32;
const RUDDER = 0x20000u32;
const BRAKE = 0x40000u32;
}
}
#[derive(Clone)]
pub struct Segment {
pub transform: Transform,
pub rest_angle: Angle,
pub motion: Motion,
pub index: SegmentIndex,
pub mesh: Mesh,
pub material: Material,
pub livery: Livery,
pub attached_to: Option<Attachment>,
pub state: State,
pub flags: Flags,
}
impl Segment {
pub fn new_attachment(&self, attachment_point: AttachmentIndex) -> Option<Attachment> {
let max = self.mesh.vertices.len() as AttachmentIndex;
Some(Attachment {
index: self.index,
attachment_point: if attachment_point < max { attachment_point } else { max - 1 },
})
}
pub fn growing_radius(&self) -> f32 { self.state.maturity * self.mesh.shape.radius() }
pub fn growing_scaled_vertex(&self, index: usize) -> Position {
self.state.maturity * self.mesh.scaled_vertex(index)
}
}
impl obj::Drawable for Segment {
fn color(&self) -> Rgba {
let rgba = self.livery.albedo;
let c = 5. * ((self.state.charge.get() * 0.99) + 0.01);
[rgba[0] * c, rgba[1] * c, rgba[2] * c, rgba[3] * self.material.density]
}
}
impl Transformable for Segment {
fn transform(&self) -> &Transform { &self.transform }
fn transform_to(&mut self, t: Transform) { self.transform = t; }
}
impl Motionable for Segment {
fn motion(&self) -> &Motion { &self.motion }
fn motion_to(&mut self, m: Motion) { self.motion = m; }
}
impl obj::Geometry for Segment {
fn mesh(&self) -> &Mesh { &self.mesh }
}
impl obj::Solid for Segment {
fn material(&self) -> &Material { &self.material }
fn livery(&self) -> &Livery { &self.livery }
}
|
{ self.maturity = maturity }
|
identifier_body
|
segment.rs
|
use backend::obj;
use backend::obj::*;
use backend::world::agent;
use core::clock::Seconds;
use core::geometry::Transform;
use core::geometry::*;
use core::math;
use core::math::ExponentialFilter;
use num::Zero;
#[derive(Clone)]
pub enum PilotRotation {
None,
Orientation(Position),
LookAt(Position),
Turn(Angle),
FromVelocity,
}
#[derive(Clone)]
pub enum Intent {
Idle,
Move(Position),
Brake(Position),
RunAway(Position),
PilotTo(Option<Position>, PilotRotation),
}
#[derive(Clone)]
pub struct State {
age_seconds: Seconds,
age_frames: usize,
maturity: f32,
charge: ExponentialFilter<f32>,
pub intent: Intent,
pub last_touched: Option<agent::Key>,
}
impl Default for State {
fn default() -> Self {
State {
age_seconds: Seconds::zero(),
age_frames: 0,
maturity: 1.0,
charge: math::exponential_filter(0., 1., 2.),
intent: Intent::Idle,
last_touched: None,
}
}
}
impl State {
pub fn age_seconds(&self) -> Seconds { self.age_seconds }
pub fn age_frames(&self) -> usize { self.age_frames }
pub fn charge(&self) -> f32 { self.charge.get() }
pub fn reset_charge(&mut self, current_charge: f32, target_charge: f32) {
self.charge.reset_to(target_charge, current_charge);
}
pub fn set_output_charge(&mut self, charge: f32) { self.charge.force_to(charge); }
pub fn target_charge(&self) -> f32 { self.charge.last_input() }
pub fn set_target_charge(&mut self, target_charge: f32) { self.charge.input(target_charge); }
//pub fn recharge(&self) -> f32 { self.recharge }
pub fn maturity(&self) -> f32 { self.maturity }
pub fn set_maturity(&mut self, maturity: f32) { self.maturity = maturity }
pub fn restore(&mut self, current_charge: f32, target_charge: f32) {
self.charge.reset_to(target_charge, current_charge);
}
pub fn update(&mut self, dt: Seconds) {
self.age_seconds += dt;
self.age_frames += 1;
self.charge.update(dt.into());
}
pub fn with_charge(current_charge: f32, target_charge: f32, charge_decay_time: Seconds) -> Self {
State {
charge: math::exponential_filter(target_charge, current_charge, charge_decay_time.get() as f32),
..Self::default()
}
}
}
#[derive(Copy, Clone)]
pub struct Attachment {
pub index: SegmentIndex,
pub attachment_point: AttachmentIndex,
}
bitflags! {
pub struct Flags: u32 {
const SENSOR = 0x00001u32;
const ACTUATOR = 0x00002u32;
const JOINT = 0x00004u32;
const MOUTH = 0x00008u32;
const HEAD = 0x00010u32;
const LEG = 0x00020u32;
const ARM = 0x00040u32;
const CORE = 0x00100u32;
const STORAGE = 0x00200u32;
const TAIL = 0x00400u32;
const TRACKER = 0x00800u32;
const LEFT = 0x01000u32;
const RIGHT = 0x02000u32;
const MIDDLE = 0x04000u32;
const THRUSTER = 0x10000u32;
const RUDDER = 0x20000u32;
const BRAKE = 0x40000u32;
}
}
#[derive(Clone)]
pub struct Segment {
pub transform: Transform,
pub rest_angle: Angle,
pub motion: Motion,
pub index: SegmentIndex,
pub mesh: Mesh,
pub material: Material,
pub livery: Livery,
pub attached_to: Option<Attachment>,
pub state: State,
pub flags: Flags,
}
impl Segment {
pub fn new_attachment(&self, attachment_point: AttachmentIndex) -> Option<Attachment> {
let max = self.mesh.vertices.len() as AttachmentIndex;
Some(Attachment {
index: self.index,
attachment_point: if attachment_point < max { attachment_point } else
|
,
})
}
pub fn growing_radius(&self) -> f32 { self.state.maturity * self.mesh.shape.radius() }
pub fn growing_scaled_vertex(&self, index: usize) -> Position {
self.state.maturity * self.mesh.scaled_vertex(index)
}
}
impl obj::Drawable for Segment {
fn color(&self) -> Rgba {
let rgba = self.livery.albedo;
let c = 5. * ((self.state.charge.get() * 0.99) + 0.01);
[rgba[0] * c, rgba[1] * c, rgba[2] * c, rgba[3] * self.material.density]
}
}
impl Transformable for Segment {
fn transform(&self) -> &Transform { &self.transform }
fn transform_to(&mut self, t: Transform) { self.transform = t; }
}
impl Motionable for Segment {
fn motion(&self) -> &Motion { &self.motion }
fn motion_to(&mut self, m: Motion) { self.motion = m; }
}
impl obj::Geometry for Segment {
fn mesh(&self) -> &Mesh { &self.mesh }
}
impl obj::Solid for Segment {
fn material(&self) -> &Material { &self.material }
fn livery(&self) -> &Livery { &self.livery }
}
|
{ max - 1 }
|
conditional_block
|
segment.rs
|
use backend::obj;
use backend::obj::*;
use backend::world::agent;
use core::clock::Seconds;
use core::geometry::Transform;
use core::geometry::*;
use core::math;
use core::math::ExponentialFilter;
use num::Zero;
#[derive(Clone)]
pub enum PilotRotation {
None,
Orientation(Position),
LookAt(Position),
Turn(Angle),
FromVelocity,
}
#[derive(Clone)]
pub enum
|
{
Idle,
Move(Position),
Brake(Position),
RunAway(Position),
PilotTo(Option<Position>, PilotRotation),
}
#[derive(Clone)]
pub struct State {
age_seconds: Seconds,
age_frames: usize,
maturity: f32,
charge: ExponentialFilter<f32>,
pub intent: Intent,
pub last_touched: Option<agent::Key>,
}
impl Default for State {
fn default() -> Self {
State {
age_seconds: Seconds::zero(),
age_frames: 0,
maturity: 1.0,
charge: math::exponential_filter(0., 1., 2.),
intent: Intent::Idle,
last_touched: None,
}
}
}
impl State {
pub fn age_seconds(&self) -> Seconds { self.age_seconds }
pub fn age_frames(&self) -> usize { self.age_frames }
pub fn charge(&self) -> f32 { self.charge.get() }
pub fn reset_charge(&mut self, current_charge: f32, target_charge: f32) {
self.charge.reset_to(target_charge, current_charge);
}
pub fn set_output_charge(&mut self, charge: f32) { self.charge.force_to(charge); }
pub fn target_charge(&self) -> f32 { self.charge.last_input() }
pub fn set_target_charge(&mut self, target_charge: f32) { self.charge.input(target_charge); }
//pub fn recharge(&self) -> f32 { self.recharge }
pub fn maturity(&self) -> f32 { self.maturity }
pub fn set_maturity(&mut self, maturity: f32) { self.maturity = maturity }
pub fn restore(&mut self, current_charge: f32, target_charge: f32) {
self.charge.reset_to(target_charge, current_charge);
}
pub fn update(&mut self, dt: Seconds) {
self.age_seconds += dt;
self.age_frames += 1;
self.charge.update(dt.into());
}
pub fn with_charge(current_charge: f32, target_charge: f32, charge_decay_time: Seconds) -> Self {
State {
charge: math::exponential_filter(target_charge, current_charge, charge_decay_time.get() as f32),
..Self::default()
}
}
}
#[derive(Copy, Clone)]
pub struct Attachment {
pub index: SegmentIndex,
pub attachment_point: AttachmentIndex,
}
bitflags! {
pub struct Flags: u32 {
const SENSOR = 0x00001u32;
const ACTUATOR = 0x00002u32;
const JOINT = 0x00004u32;
const MOUTH = 0x00008u32;
const HEAD = 0x00010u32;
const LEG = 0x00020u32;
const ARM = 0x00040u32;
const CORE = 0x00100u32;
const STORAGE = 0x00200u32;
const TAIL = 0x00400u32;
const TRACKER = 0x00800u32;
const LEFT = 0x01000u32;
const RIGHT = 0x02000u32;
const MIDDLE = 0x04000u32;
const THRUSTER = 0x10000u32;
const RUDDER = 0x20000u32;
const BRAKE = 0x40000u32;
}
}
#[derive(Clone)]
pub struct Segment {
pub transform: Transform,
pub rest_angle: Angle,
pub motion: Motion,
pub index: SegmentIndex,
pub mesh: Mesh,
pub material: Material,
pub livery: Livery,
pub attached_to: Option<Attachment>,
pub state: State,
pub flags: Flags,
}
impl Segment {
pub fn new_attachment(&self, attachment_point: AttachmentIndex) -> Option<Attachment> {
let max = self.mesh.vertices.len() as AttachmentIndex;
Some(Attachment {
index: self.index,
attachment_point: if attachment_point < max { attachment_point } else { max - 1 },
})
}
pub fn growing_radius(&self) -> f32 { self.state.maturity * self.mesh.shape.radius() }
pub fn growing_scaled_vertex(&self, index: usize) -> Position {
self.state.maturity * self.mesh.scaled_vertex(index)
}
}
impl obj::Drawable for Segment {
fn color(&self) -> Rgba {
let rgba = self.livery.albedo;
let c = 5. * ((self.state.charge.get() * 0.99) + 0.01);
[rgba[0] * c, rgba[1] * c, rgba[2] * c, rgba[3] * self.material.density]
}
}
impl Transformable for Segment {
fn transform(&self) -> &Transform { &self.transform }
fn transform_to(&mut self, t: Transform) { self.transform = t; }
}
impl Motionable for Segment {
fn motion(&self) -> &Motion { &self.motion }
fn motion_to(&mut self, m: Motion) { self.motion = m; }
}
impl obj::Geometry for Segment {
fn mesh(&self) -> &Mesh { &self.mesh }
}
impl obj::Solid for Segment {
fn material(&self) -> &Material { &self.material }
fn livery(&self) -> &Livery { &self.livery }
}
|
Intent
|
identifier_name
|
lib.rs
|
// Copyright 2014 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! An efficient, low-level, bindless graphics API for Rust. See [the
//! blog](http://gfx-rs.github.io/) for explanations and annotated examples.
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate log;
extern crate draw_state;
extern crate num;
/// public re-exported traits
pub mod traits {
pub use device::{Device, Factory, DeviceFence};
pub use extra::factory::FactoryExt;
pub use extra::stream::{Stream, StreamFactory};
pub use render::RenderFactory;
pub use render::mesh::{ToIndexSlice, ToSlice};
pub use render::target::Output;
|
pub use draw_state::{DrawState, BlendPreset};
pub use draw_state::state;
pub use draw_state::target::*;
// public re-exports
pub use device::{Device, SubmitInfo, Factory, Resources};
pub use device::{attrib, tex, handle};
pub use device::as_byte_slice;
pub use device::{BufferRole, BufferInfo, BufferUsage};
pub use device::{VertexCount, InstanceCount};
pub use device::PrimitiveType;
pub use device::draw::{CommandBuffer, Gamma, InstanceOption};
pub use device::shade::{ProgramInfo, UniformValue};
pub use render::{Renderer, BlitError, DrawError, UpdateError};
pub use render::batch;
pub use render::mesh::{Attribute, Mesh, VertexFormat};
pub use render::mesh::Error as MeshError;
pub use render::mesh::{Slice, ToIndexSlice, ToSlice, SliceKind};
pub use render::shade;
pub use render::target::{Frame, Output, Plane};
pub use render::ParamStorage;
pub use extra::shade::{ShaderSource, ProgramError};
pub use extra::stream::{OwnedStream, Stream, Window};
pub mod device;
pub mod extra;
pub mod macros;
pub mod render;
|
}
// draw state re-exports
|
random_line_split
|
b64.rs
|
#[repr(C)]
#[cfg_attr(feature = "extra_traits", derive(Debug, Eq, Hash, PartialEq))]
pub struct stat {
pub st_dev: ::dev_t,
pub st_ino: ::ino_t,
pub st_nlink: ::nlink_t,
pub st_mode: ::mode_t,
st_padding0: i16,
pub st_uid: ::uid_t,
pub st_gid: ::gid_t,
st_padding1: i32,
pub st_rdev: ::dev_t,
pub st_atime: ::time_t,
pub st_atime_nsec: ::c_long,
pub st_mtime: ::time_t,
pub st_mtime_nsec: ::c_long,
pub st_ctime: ::time_t,
pub st_ctime_nsec: ::c_long,
pub st_birthtime: ::time_t,
pub st_birthtime_nsec: ::c_long,
pub st_size: ::off_t,
pub st_blocks: ::blkcnt_t,
pub st_blksize: ::blksize_t,
pub st_flags: ::fflags_t,
pub st_gen: u64,
pub st_spare: [u64; 10],
}
impl ::Copy for ::stat {}
impl ::Clone for ::stat {
fn
|
(&self) -> ::stat {
*self
}
}
|
clone
|
identifier_name
|
b64.rs
|
#[repr(C)]
#[cfg_attr(feature = "extra_traits", derive(Debug, Eq, Hash, PartialEq))]
pub struct stat {
pub st_dev: ::dev_t,
pub st_ino: ::ino_t,
pub st_nlink: ::nlink_t,
pub st_mode: ::mode_t,
st_padding0: i16,
pub st_uid: ::uid_t,
pub st_gid: ::gid_t,
st_padding1: i32,
pub st_rdev: ::dev_t,
pub st_atime: ::time_t,
pub st_atime_nsec: ::c_long,
pub st_mtime: ::time_t,
pub st_mtime_nsec: ::c_long,
pub st_ctime: ::time_t,
pub st_ctime_nsec: ::c_long,
pub st_birthtime: ::time_t,
pub st_birthtime_nsec: ::c_long,
pub st_size: ::off_t,
pub st_blocks: ::blkcnt_t,
pub st_blksize: ::blksize_t,
pub st_flags: ::fflags_t,
pub st_gen: u64,
pub st_spare: [u64; 10],
}
impl ::Copy for ::stat {}
impl ::Clone for ::stat {
fn clone(&self) -> ::stat {
*self
}
|
}
|
random_line_split
|
|
main.rs
|
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use std::collections::BTreeMap as Map;
#[derive(Serialize)]
struct Resource {
// Always serialized.
name: String,
// Never serialized.
#[serde(skip_serializing)]
hash: String,
// Use a method to decide whether the field should be skipped.
#[serde(skip_serializing_if = "Map::is_empty")]
metadata: Map<String, String>,
}
fn main()
|
// Prints:
//
// [
// {
// "name": "Stack Overflow"
// },
// {
// "name": "GitHub",
// "metadata": {
// "headquarters": "San Francisco"
// }
// }
// ]
println!("{}", json);
}
|
{
let resources = vec![
Resource {
name: "Stack Overflow".to_string(),
hash: "b6469c3f31653d281bbbfa6f94d60fea130abe38".to_string(),
metadata: Map::new(),
},
Resource {
name: "GitHub".to_string(),
hash: "5cb7a0c47e53854cd00e1a968de5abce1c124601".to_string(),
metadata: {
let mut metadata = Map::new();
metadata.insert("headquarters".to_string(),
"San Francisco".to_string());
metadata
},
},
];
let json = serde_json::to_string_pretty(&resources).unwrap();
|
identifier_body
|
main.rs
|
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use std::collections::BTreeMap as Map;
#[derive(Serialize)]
struct Resource {
// Always serialized.
name: String,
// Never serialized.
#[serde(skip_serializing)]
hash: String,
// Use a method to decide whether the field should be skipped.
#[serde(skip_serializing_if = "Map::is_empty")]
metadata: Map<String, String>,
}
fn main() {
let resources = vec![
Resource {
name: "Stack Overflow".to_string(),
hash: "b6469c3f31653d281bbbfa6f94d60fea130abe38".to_string(),
|
},
Resource {
name: "GitHub".to_string(),
hash: "5cb7a0c47e53854cd00e1a968de5abce1c124601".to_string(),
metadata: {
let mut metadata = Map::new();
metadata.insert("headquarters".to_string(),
"San Francisco".to_string());
metadata
},
},
];
let json = serde_json::to_string_pretty(&resources).unwrap();
// Prints:
//
// [
// {
// "name": "Stack Overflow"
// },
// {
// "name": "GitHub",
// "metadata": {
// "headquarters": "San Francisco"
// }
// }
// ]
println!("{}", json);
}
|
metadata: Map::new(),
|
random_line_split
|
main.rs
|
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use std::collections::BTreeMap as Map;
#[derive(Serialize)]
struct Resource {
// Always serialized.
name: String,
// Never serialized.
#[serde(skip_serializing)]
hash: String,
// Use a method to decide whether the field should be skipped.
#[serde(skip_serializing_if = "Map::is_empty")]
metadata: Map<String, String>,
}
fn
|
() {
let resources = vec![
Resource {
name: "Stack Overflow".to_string(),
hash: "b6469c3f31653d281bbbfa6f94d60fea130abe38".to_string(),
metadata: Map::new(),
},
Resource {
name: "GitHub".to_string(),
hash: "5cb7a0c47e53854cd00e1a968de5abce1c124601".to_string(),
metadata: {
let mut metadata = Map::new();
metadata.insert("headquarters".to_string(),
"San Francisco".to_string());
metadata
},
},
];
let json = serde_json::to_string_pretty(&resources).unwrap();
// Prints:
//
// [
// {
// "name": "Stack Overflow"
// },
// {
// "name": "GitHub",
// "metadata": {
// "headquarters": "San Francisco"
// }
// }
// ]
println!("{}", json);
}
|
main
|
identifier_name
|
mod.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/>.
//! Bridge between bloomchain crate types and ethcore.
|
mod bloom;
mod bloom_group;
mod group_position;
pub use self::bloom::Bloom;
pub use self::bloom_group::BloomGroup;
pub use self::group_position::GroupPosition;
|
random_line_split
|
|
assign_bit.rs
|
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::num::logic::traits::BitAccess;
use malachite_base_test_util::bench::bucketers::pair_2_triple_2_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::runner::Runner;
use malachite_nz_test_util::generators::{
natural_unsigned_bool_triple_gen_var_1, natural_unsigned_bool_triple_gen_var_1_rm,
};
pub(crate) fn register(runner: &mut Runner)
|
fn demo_natural_assign_bit(gm: GenMode, config: GenConfig, limit: usize) {
for (mut n, index, bit) in natural_unsigned_bool_triple_gen_var_1()
.get(gm, &config)
.take(limit)
{
let n_old = n.clone();
n.assign_bit(index, bit);
println!(
"x := {}; x.assign_bit({}, {}); x = {}",
n_old, index, bit, n
);
}
}
fn benchmark_natural_assign_bit_library_comparison(
gm: GenMode,
config: GenConfig,
limit: usize,
file_name: &str,
) {
run_benchmark(
"Natural.assign_bit(u64, bool)",
BenchmarkType::LibraryComparison,
natural_unsigned_bool_triple_gen_var_1_rm().get(gm, &config),
gm.name(),
limit,
file_name,
&pair_2_triple_2_bucketer("index"),
&mut [
("Malachite", &mut |(_, (mut n, index, bit))| {
n.assign_bit(index, bit)
}),
("rug", &mut |((mut n, index, bit), _)| {
no_out!(n.set_bit(u32::exact_from(index), bit))
}),
],
);
}
|
{
register_demo!(runner, demo_natural_assign_bit);
register_bench!(runner, benchmark_natural_assign_bit_library_comparison);
}
|
identifier_body
|
assign_bit.rs
|
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::num::logic::traits::BitAccess;
use malachite_base_test_util::bench::bucketers::pair_2_triple_2_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::runner::Runner;
use malachite_nz_test_util::generators::{
natural_unsigned_bool_triple_gen_var_1, natural_unsigned_bool_triple_gen_var_1_rm,
};
pub(crate) fn
|
(runner: &mut Runner) {
register_demo!(runner, demo_natural_assign_bit);
register_bench!(runner, benchmark_natural_assign_bit_library_comparison);
}
fn demo_natural_assign_bit(gm: GenMode, config: GenConfig, limit: usize) {
for (mut n, index, bit) in natural_unsigned_bool_triple_gen_var_1()
.get(gm, &config)
.take(limit)
{
let n_old = n.clone();
n.assign_bit(index, bit);
println!(
"x := {}; x.assign_bit({}, {}); x = {}",
n_old, index, bit, n
);
}
}
fn benchmark_natural_assign_bit_library_comparison(
gm: GenMode,
config: GenConfig,
limit: usize,
file_name: &str,
) {
run_benchmark(
"Natural.assign_bit(u64, bool)",
BenchmarkType::LibraryComparison,
natural_unsigned_bool_triple_gen_var_1_rm().get(gm, &config),
gm.name(),
limit,
file_name,
&pair_2_triple_2_bucketer("index"),
&mut [
("Malachite", &mut |(_, (mut n, index, bit))| {
n.assign_bit(index, bit)
}),
("rug", &mut |((mut n, index, bit), _)| {
no_out!(n.set_bit(u32::exact_from(index), bit))
}),
],
);
}
|
register
|
identifier_name
|
assign_bit.rs
|
use malachite_base::num::conversion::traits::ExactFrom;
use malachite_base::num::logic::traits::BitAccess;
use malachite_base_test_util::bench::bucketers::pair_2_triple_2_bucketer;
use malachite_base_test_util::bench::{run_benchmark, BenchmarkType};
use malachite_base_test_util::generators::common::{GenConfig, GenMode};
use malachite_base_test_util::runner::Runner;
use malachite_nz_test_util::generators::{
natural_unsigned_bool_triple_gen_var_1, natural_unsigned_bool_triple_gen_var_1_rm,
};
pub(crate) fn register(runner: &mut Runner) {
register_demo!(runner, demo_natural_assign_bit);
register_bench!(runner, benchmark_natural_assign_bit_library_comparison);
}
fn demo_natural_assign_bit(gm: GenMode, config: GenConfig, limit: usize) {
for (mut n, index, bit) in natural_unsigned_bool_triple_gen_var_1()
.get(gm, &config)
.take(limit)
{
let n_old = n.clone();
n.assign_bit(index, bit);
println!(
"x := {}; x.assign_bit({}, {}); x = {}",
n_old, index, bit, n
);
}
}
fn benchmark_natural_assign_bit_library_comparison(
gm: GenMode,
config: GenConfig,
limit: usize,
file_name: &str,
) {
run_benchmark(
"Natural.assign_bit(u64, bool)",
|
BenchmarkType::LibraryComparison,
natural_unsigned_bool_triple_gen_var_1_rm().get(gm, &config),
gm.name(),
limit,
file_name,
&pair_2_triple_2_bucketer("index"),
&mut [
("Malachite", &mut |(_, (mut n, index, bit))| {
n.assign_bit(index, bit)
}),
("rug", &mut |((mut n, index, bit), _)| {
no_out!(n.set_bit(u32::exact_from(index), bit))
}),
],
);
}
|
random_line_split
|
|
lib.rs
|
// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![deny(missing_docs)]
//! An efficient, low-level, bindless graphics API for Rust. See [the
//! blog](http://gfx-rs.github.io/) for explanations and annotated examples.
#[macro_use]
extern crate log;
extern crate draw_state;
extern crate gfx_core;
/// public re-exported traits
pub mod traits {
pub use gfx_core::{Device, Factory, DeviceFence};
pub use factory::FactoryExt;
}
// draw state re-exports
pub use draw_state::{preset, state};
pub use draw_state::target::*;
// public re-exports
pub use gfx_core as core;
pub use gfx_core::{Device, Resources, Primitive};
pub use gfx_core::{VertexCount, InstanceCount};
pub use gfx_core::{ShaderSet, VertexShader, HullShader, DomainShader,
GeometryShader, PixelShader};
pub use gfx_core::{format, handle, tex};
pub use gfx_core::factory::{Factory, Usage, Bind, MapAccess, ResourceViewError, TargetViewError,
BufferRole, BufferInfo, BufferError, BufferUpdateError, CombinedError,
RENDER_TARGET, DEPTH_STENCIL, SHADER_RESOURCE, UNORDERED_ACCESS,
cast_slice};
pub use gfx_core::draw::{CommandBuffer, InstanceOption};
pub use gfx_core::shade::{ProgramInfo, UniformValue};
pub use encoder::{Encoder, UpdateError};
pub use factory::PipelineStateError;
pub use mesh::{Slice, ToIndexSlice, SliceKind};
pub use pso::{PipelineState};
pub use pso::buffer::{VertexBuffer, InstanceBuffer, RawVertexBuffer,
ConstantBuffer, Global};
pub use pso::resource::{ShaderResource, RawShaderResource, UnorderedAccess,
|
/// Render commands encoder
mod encoder;
/// Factory extensions
mod factory;
/// Meshes
mod mesh;
/// Pipeline states
pub mod pso;
/// Shaders
pub mod shade;
/// Convenience macros
pub mod macros;
|
Sampler, TextureSampler};
pub use pso::target::{DepthStencilTarget, DepthTarget, StencilTarget,
RenderTarget, RawRenderTarget, BlendTarget, BlendRef, Scissor};
|
random_line_split
|
lib.rs
|
// Copyright 2012-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.
//! The Rust compiler.
|
//!
//! This API is completely unstable and subject to change.
// Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
#![cfg_attr(stage0, feature(custom_attribute))]
#![crate_name = "rustc_trans"]
#![unstable(feature = "rustc_private")]
#![staged_api]
#![crate_type = "dylib"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/nightly/")]
#![feature(alloc)]
#![feature(box_patterns)]
#![feature(box_syntax)]
#![feature(collections)]
#![feature(core)]
#![feature(libc)]
#![feature(quote)]
#![feature(rustc_diagnostic_macros)]
#![feature(rustc_private)]
#![feature(unsafe_destructor)]
#![feature(staged_api)]
#![feature(unicode)]
#![feature(path_ext)]
#![feature(fs)]
#![feature(path_relative_from)]
#![allow(trivial_casts)]
extern crate arena;
extern crate flate;
extern crate getopts;
extern crate graphviz;
extern crate libc;
extern crate rustc;
extern crate rustc_back;
extern crate serialize;
extern crate rustc_llvm as llvm;
#[macro_use] extern crate log;
#[macro_use] extern crate syntax;
pub use rustc::session;
pub use rustc::metadata;
pub use rustc::middle;
pub use rustc::lint;
pub use rustc::plugin;
pub use rustc::util;
pub mod back {
pub use rustc_back::abi;
pub use rustc_back::archive;
pub use rustc_back::arm;
pub use rustc_back::mips;
pub use rustc_back::mipsel;
pub use rustc_back::rpath;
pub use rustc_back::svh;
pub use rustc_back::target_strs;
pub use rustc_back::x86;
pub use rustc_back::x86_64;
pub mod link;
pub mod lto;
pub mod write;
}
pub mod trans;
pub mod save;
pub mod lib {
pub use llvm;
}
|
//!
//! # Note
|
random_line_split
|
lib.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.
#![feature(nll)]
#![feature(rustc_private)]
#[macro_use] extern crate log;
extern crate rustc;
extern crate rustc_data_structures;
extern crate rustc_errors;
extern crate rustc_target;
extern crate syntax;
extern crate syntax_pos;
#[macro_use]
extern crate smallvec;
pub mod expand;
pub static ALLOCATOR_METHODS: &[AllocatorMethod] = &[
AllocatorMethod {
name: "alloc",
inputs: &[AllocatorTy::Layout],
output: AllocatorTy::ResultPtr,
},
AllocatorMethod {
name: "dealloc",
inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout],
output: AllocatorTy::Unit,
},
AllocatorMethod {
name: "realloc",
inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout, AllocatorTy::Usize],
output: AllocatorTy::ResultPtr,
},
AllocatorMethod {
name: "alloc_zeroed",
inputs: &[AllocatorTy::Layout],
output: AllocatorTy::ResultPtr,
},
];
pub struct AllocatorMethod {
pub name: &'static str,
pub inputs: &'static [AllocatorTy],
pub output: AllocatorTy,
}
pub enum
|
{
Layout,
Ptr,
ResultPtr,
Unit,
Usize,
}
|
AllocatorTy
|
identifier_name
|
lib.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.
#![feature(nll)]
#![feature(rustc_private)]
#[macro_use] extern crate log;
extern crate rustc;
extern crate rustc_data_structures;
extern crate rustc_errors;
extern crate rustc_target;
extern crate syntax;
extern crate syntax_pos;
#[macro_use]
extern crate smallvec;
pub mod expand;
pub static ALLOCATOR_METHODS: &[AllocatorMethod] = &[
AllocatorMethod {
name: "alloc",
inputs: &[AllocatorTy::Layout],
output: AllocatorTy::ResultPtr,
},
AllocatorMethod {
name: "dealloc",
inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout],
output: AllocatorTy::Unit,
},
AllocatorMethod {
name: "realloc",
inputs: &[AllocatorTy::Ptr, AllocatorTy::Layout, AllocatorTy::Usize],
output: AllocatorTy::ResultPtr,
},
AllocatorMethod {
name: "alloc_zeroed",
inputs: &[AllocatorTy::Layout],
output: AllocatorTy::ResultPtr,
},
];
pub struct AllocatorMethod {
pub name: &'static str,
|
pub output: AllocatorTy,
}
pub enum AllocatorTy {
Layout,
Ptr,
ResultPtr,
Unit,
Usize,
}
|
pub inputs: &'static [AllocatorTy],
|
random_line_split
|
url_builder.rs
|
/* Some types from or based on types from elastic: https://github.com/elastic-rs/elastic
*
* Licensed under Apache 2.0: https://github.com/elastic-rs/elastic/blob/51298dd64278f34d2db911bd1a35eb757c336198/LICENSE-APACHE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::api_generator::code_gen::*;
use crate::api_generator::{Path, Type, TypeKind};
use quote::ToTokens;
use serde::{Deserialize, Deserializer};
use std::{collections::BTreeMap, fmt, iter::Iterator, str};
use syn;
/// A URL path
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct PathString(#[serde(deserialize_with = "rooted_path_string")] pub String);
/// Ensure all deserialized paths have a leading `/`
fn rooted_path_string<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
if!s.starts_with('/') {
Ok(format!("/{}", s))
} else {
Ok(s)
}
}
impl fmt::Display for PathString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl PathString {
/// Splits a path into a vector of parameter and literal parts
pub fn split(&self) -> Vec<PathPart> {
PathString::parse(self.0.as_bytes(), PathParseState::Literal, Vec::new())
}
/// Gets the parameters from the path
pub fn params(&self) -> Vec<&str> {
self.split()
.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => Some(p),
_ => None,
})
.collect()
}
fn parse<'a>(i: &'a [u8], state: PathParseState, r: Vec<PathPart<'a>>) -> Vec<PathPart<'a>> {
if i.is_empty() {
return r;
}
let mut r = r;
match state {
PathParseState::Literal => {
let (rest, part) = PathString::parse_literal(i);
if!part.is_empty() {
r.push(PathPart::Literal(part));
}
PathString::parse(rest, PathParseState::Param, r)
}
PathParseState::Param => {
let (rest, part) = PathString::parse_param(i);
if!part.is_empty() {
r.push(PathPart::Param(part));
}
PathString::parse(rest, PathParseState::Literal, r)
}
}
}
fn parse_literal(i: &[u8]) -> (&[u8], &str) {
if i[0] == b'}' {
let i = shift(i, 1);
take_while(i, |c| c!= b'{')
} else {
take_while(i, |c| c!= b'{')
}
}
fn parse_param(i: &[u8]) -> (&[u8], &str) {
if i[0] == b'{' {
let i = shift(i, 1);
take_while(i, |c| c!= b'}')
} else {
take_while(i, |c| c!= b'}')
}
}
}
enum PathParseState {
Literal,
Param,
}
/// A part of a Path
#[derive(Debug, PartialEq)]
pub enum PathPart<'a> {
Literal(&'a str),
Param(&'a str),
}
pub trait PathParams<'a> {
fn params(&'a self) -> Vec<&'a str>;
}
impl<'a> PathParams<'a> for Vec<PathPart<'a>> {
fn params(&'a self) -> Vec<&'a str> {
self.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => Some(p),
_ => None,
})
.collect()
}
}
/// Builder for an efficient url value replacer.
pub struct UrlBuilder<'a> {
path: Vec<PathPart<'a>>,
parts: &'a BTreeMap<String, Type>,
}
impl<'a> UrlBuilder<'a> {
pub fn new(path: &'a Path) -> Self {
let path_parts = path.path.split();
let parts = &path.parts;
UrlBuilder {
path: path_parts,
parts,
}
}
/// Build the AST for an allocated url from the path literals and params.
fn build_owned(self) -> syn::Block {
let lit_len_expr = Self::literal_length_expr(&self.path);
// collection of let {name}_str = [self.]{name}.[join(",")|to_string()];
let let_params_exprs = Self::let_parameters_exprs(&self.path, &self.parts);
let mut params_len_exprs = Self::parameter_length_exprs(&self.path, self.parts);
let mut len_exprs = vec![lit_len_expr];
len_exprs.append(&mut params_len_exprs);
let len_expr = Self::summed_length_expr(len_exprs);
let url_ident = ident("p");
let let_stmt = Self::let_p_stmt(url_ident.clone(), len_expr);
let mut push_stmts = Self::push_str_stmts(url_ident.clone(), &self.path, self.parts);
let return_expr = syn::Stmt::Expr(Box::new(parse_expr(quote!(#url_ident.into()))));
let mut stmts = let_params_exprs;
stmts.push(let_stmt);
stmts.append(&mut push_stmts);
stmts.push(return_expr);
syn::Block { stmts }
}
/// Build the AST for a literal path
fn build_borrowed_literal(self) -> syn::Expr {
let path: Vec<&'a str> = self
.path
.iter()
.map(|p| match *p {
PathPart::Literal(p) => p,
_ => panic!("Only PathPart::Literal is supported by a borrowed url."),
})
.collect();
let path = path.join("");
let lit = syn::Lit::Str(path, syn::StrStyle::Cooked);
parse_expr(quote!(#lit.into()))
}
/// Get the number of chars in all literal parts for the url.
fn literal_length_expr(url: &[PathPart<'a>]) -> syn::Expr {
let len = url
.iter()
.filter_map(|p| match *p {
PathPart::Literal(p) => Some(p),
_ => None,
})
.fold(0, |acc, p| acc + p.len());
syn::ExprKind::Lit(syn::Lit::Int(len as u64, syn::IntTy::Usize)).into()
}
/// Creates the AST for a let expression for path parts
fn let_parameters_exprs(
url: &[PathPart<'a>],
parts: &BTreeMap<String, Type>,
) -> Vec<syn::Stmt> {
url.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => {
let name = valid_name(p);
let name_ident = ident(&name);
let k = p.to_string();
let ty = parts[&k].ty;
// don't generate an assignment expression for strings
if ty == TypeKind::String {
return None;
}
let tokens = quote!(#name_ident);
// build a different expression, depending on the type of parameter
let (ident, init) = match ty {
TypeKind::List => {
// Join list values together
let name_str = format!("{}_str", &name);
let name_str_ident = ident(&name_str);
let join_call = syn::ExprKind::MethodCall(
ident("join"),
vec![],
vec![
parse_expr(tokens),
syn::ExprKind::Lit(syn::Lit::Str(
",".into(),
syn::StrStyle::Cooked,
))
.into(),
],
)
.into();
(name_str_ident, join_call)
}
_ => {
// Handle enums, long, int, etc. by calling to_string()
let to_string_call = syn::ExprKind::MethodCall(
ident("to_string"),
vec![],
vec![parse_expr(tokens)],
)
.into();
(ident(format!("{}_str", name)), to_string_call)
}
};
Some(syn::Stmt::Local(Box::new(syn::Local {
pat: Box::new(syn::Pat::Ident(
syn::BindingMode::ByValue(syn::Mutability::Immutable),
ident,
None,
)),
ty: None,
init: Some(Box::new(init)),
attrs: vec![],
})))
}
_ => None,
})
.collect()
}
/// Get an expression to find the number of chars in each parameter part for the url.
fn parameter_length_exprs(
url: &[PathPart<'a>],
parts: &BTreeMap<String, Type>,
) -> Vec<syn::Expr> {
url.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => {
let name = match parts[&p.to_string()].ty {
TypeKind::String => valid_name(p).into(),
// handle lists and enums
_ => format!("{}_str", valid_name(p)),
};
Some(
syn::ExprKind::MethodCall(
ident("len"),
vec![],
vec![syn::ExprKind::Path(None, path_none(name.as_ref())).into()],
)
.into(),
)
}
_ => None,
})
.collect()
}
/// Get an expression that is the binary addition of each of the given expressions.
fn summed_length_expr(len_exprs: Vec<syn::Expr>) -> syn::Expr {
match len_exprs.len() {
1 => len_exprs.into_iter().next().unwrap(),
_ => {
let mut len_iter = len_exprs.into_iter();
let first_expr = Box::new(len_iter.next().unwrap());
*(len_iter.map(Box::new).fold(first_expr, |acc, p| {
Box::new(syn::ExprKind::Binary(syn::BinOp::Add, acc, p).into())
}))
}
}
}
/// Get a statement to build a `String` with a capacity of the given expression.
fn let_p_stmt(url_ident: syn::Ident, len_expr: syn::Expr) -> syn::Stmt {
let string_with_capacity = syn::ExprKind::Call(
Box::new(
syn::ExprKind::Path(None, {
let mut method = path_none("String");
method
.segments
.push(syn::PathSegment::from("with_capacity"));
method
})
.into(),
),
vec![len_expr],
)
.into();
syn::Stmt::Local(Box::new(syn::Local {
pat: Box::new(syn::Pat::Ident(
syn::BindingMode::ByValue(syn::Mutability::Mutable),
url_ident.to_owned(),
None,
)),
ty: None,
init: Some(Box::new(string_with_capacity)),
attrs: vec![],
}))
}
/// Get a list of statements that append each part to a `String` in order.
fn push_str_stmts(
url_ident: syn::Ident,
url: &[PathPart<'a>],
parts: &BTreeMap<String, Type>,
) -> Vec<syn::Stmt> {
url.iter()
.map(|p| match *p {
PathPart::Literal(p) => {
let lit = syn::Lit::Str(p.to_string(), syn::StrStyle::Cooked);
syn::Stmt::Semi(Box::new(parse_expr(quote!(#url_ident.push_str(#lit)))))
}
PathPart::Param(p) => {
let name = match parts[&p.to_string()].ty {
TypeKind::String => valid_name(p).into(),
// handle lists and enums
_ => format!("{}_str", valid_name(p)),
};
let ident = ident(name);
syn::Stmt::Semi(Box::new(parse_expr(
quote!(#url_ident.push_str(#ident.as_ref())),
)))
}
})
.collect()
}
pub fn build(self) -> syn::Expr {
let has_params = self.path.iter().any(|p| match *p {
PathPart::Param(_) => true,
_ => false,
});
if has_params {
self.build_owned().into_expr()
} else {
self.build_borrowed_literal()
}
}
}
/// Helper for wrapping a value as a quotable expression.
pub trait IntoExpr {
fn into_expr(self) -> syn::Expr;
}
impl IntoExpr for syn::Path {
fn into_expr(self) -> syn::Expr {
syn::ExprKind::Path(None, self).into()
}
}
impl IntoExpr for syn::Block {
fn into_expr(self) -> syn::Expr {
syn::ExprKind::Block(syn::Unsafety::Normal, self).into()
}
}
impl IntoExpr for syn::Ty {
fn
|
(self) -> syn::Expr {
// TODO: Must be a nicer conversion than this
let mut tokens = quote::Tokens::new();
self.to_tokens(&mut tokens);
parse_expr(tokens)
}
}
impl IntoExpr for syn::Pat {
fn into_expr(self) -> syn::Expr {
// TODO: Must be a nicer conversion than this
let mut tokens = quote::Tokens::new();
self.to_tokens(&mut tokens);
parse_expr(tokens)
}
}
|
into_expr
|
identifier_name
|
url_builder.rs
|
/* Some types from or based on types from elastic: https://github.com/elastic-rs/elastic
*
* Licensed under Apache 2.0: https://github.com/elastic-rs/elastic/blob/51298dd64278f34d2db911bd1a35eb757c336198/LICENSE-APACHE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::api_generator::code_gen::*;
use crate::api_generator::{Path, Type, TypeKind};
use quote::ToTokens;
use serde::{Deserialize, Deserializer};
use std::{collections::BTreeMap, fmt, iter::Iterator, str};
use syn;
/// A URL path
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct PathString(#[serde(deserialize_with = "rooted_path_string")] pub String);
/// Ensure all deserialized paths have a leading `/`
fn rooted_path_string<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
if!s.starts_with('/') {
Ok(format!("/{}", s))
} else {
Ok(s)
}
}
impl fmt::Display for PathString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl PathString {
/// Splits a path into a vector of parameter and literal parts
pub fn split(&self) -> Vec<PathPart> {
PathString::parse(self.0.as_bytes(), PathParseState::Literal, Vec::new())
}
/// Gets the parameters from the path
pub fn params(&self) -> Vec<&str> {
self.split()
.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => Some(p),
_ => None,
})
.collect()
}
fn parse<'a>(i: &'a [u8], state: PathParseState, r: Vec<PathPart<'a>>) -> Vec<PathPart<'a>> {
if i.is_empty() {
return r;
}
let mut r = r;
match state {
PathParseState::Literal => {
let (rest, part) = PathString::parse_literal(i);
if!part.is_empty() {
r.push(PathPart::Literal(part));
}
PathString::parse(rest, PathParseState::Param, r)
}
PathParseState::Param => {
let (rest, part) = PathString::parse_param(i);
if!part.is_empty() {
r.push(PathPart::Param(part));
}
PathString::parse(rest, PathParseState::Literal, r)
}
}
}
fn parse_literal(i: &[u8]) -> (&[u8], &str) {
if i[0] == b'}' {
let i = shift(i, 1);
take_while(i, |c| c!= b'{')
} else {
take_while(i, |c| c!= b'{')
}
}
fn parse_param(i: &[u8]) -> (&[u8], &str) {
if i[0] == b'{' {
let i = shift(i, 1);
take_while(i, |c| c!= b'}')
} else {
take_while(i, |c| c!= b'}')
}
}
}
enum PathParseState {
Literal,
Param,
}
/// A part of a Path
#[derive(Debug, PartialEq)]
pub enum PathPart<'a> {
Literal(&'a str),
Param(&'a str),
}
pub trait PathParams<'a> {
fn params(&'a self) -> Vec<&'a str>;
}
impl<'a> PathParams<'a> for Vec<PathPart<'a>> {
fn params(&'a self) -> Vec<&'a str> {
self.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => Some(p),
_ => None,
})
.collect()
}
}
/// Builder for an efficient url value replacer.
pub struct UrlBuilder<'a> {
path: Vec<PathPart<'a>>,
parts: &'a BTreeMap<String, Type>,
}
impl<'a> UrlBuilder<'a> {
pub fn new(path: &'a Path) -> Self {
let path_parts = path.path.split();
let parts = &path.parts;
UrlBuilder {
path: path_parts,
parts,
}
}
/// Build the AST for an allocated url from the path literals and params.
fn build_owned(self) -> syn::Block {
let lit_len_expr = Self::literal_length_expr(&self.path);
// collection of let {name}_str = [self.]{name}.[join(",")|to_string()];
let let_params_exprs = Self::let_parameters_exprs(&self.path, &self.parts);
let mut params_len_exprs = Self::parameter_length_exprs(&self.path, self.parts);
let mut len_exprs = vec![lit_len_expr];
len_exprs.append(&mut params_len_exprs);
let len_expr = Self::summed_length_expr(len_exprs);
let url_ident = ident("p");
let let_stmt = Self::let_p_stmt(url_ident.clone(), len_expr);
let mut push_stmts = Self::push_str_stmts(url_ident.clone(), &self.path, self.parts);
let return_expr = syn::Stmt::Expr(Box::new(parse_expr(quote!(#url_ident.into()))));
let mut stmts = let_params_exprs;
stmts.push(let_stmt);
stmts.append(&mut push_stmts);
stmts.push(return_expr);
syn::Block { stmts }
}
/// Build the AST for a literal path
fn build_borrowed_literal(self) -> syn::Expr {
let path: Vec<&'a str> = self
.path
.iter()
.map(|p| match *p {
PathPart::Literal(p) => p,
_ => panic!("Only PathPart::Literal is supported by a borrowed url."),
})
.collect();
let path = path.join("");
let lit = syn::Lit::Str(path, syn::StrStyle::Cooked);
parse_expr(quote!(#lit.into()))
}
/// Get the number of chars in all literal parts for the url.
fn literal_length_expr(url: &[PathPart<'a>]) -> syn::Expr {
let len = url
.iter()
.filter_map(|p| match *p {
PathPart::Literal(p) => Some(p),
_ => None,
})
.fold(0, |acc, p| acc + p.len());
syn::ExprKind::Lit(syn::Lit::Int(len as u64, syn::IntTy::Usize)).into()
}
/// Creates the AST for a let expression for path parts
fn let_parameters_exprs(
url: &[PathPart<'a>],
parts: &BTreeMap<String, Type>,
) -> Vec<syn::Stmt> {
url.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => {
let name = valid_name(p);
let name_ident = ident(&name);
let k = p.to_string();
let ty = parts[&k].ty;
// don't generate an assignment expression for strings
if ty == TypeKind::String {
return None;
}
let tokens = quote!(#name_ident);
// build a different expression, depending on the type of parameter
let (ident, init) = match ty {
TypeKind::List => {
// Join list values together
let name_str = format!("{}_str", &name);
let name_str_ident = ident(&name_str);
let join_call = syn::ExprKind::MethodCall(
ident("join"),
vec![],
vec![
parse_expr(tokens),
syn::ExprKind::Lit(syn::Lit::Str(
",".into(),
syn::StrStyle::Cooked,
))
.into(),
],
)
.into();
(name_str_ident, join_call)
}
_ => {
// Handle enums, long, int, etc. by calling to_string()
let to_string_call = syn::ExprKind::MethodCall(
ident("to_string"),
vec![],
vec![parse_expr(tokens)],
)
.into();
(ident(format!("{}_str", name)), to_string_call)
}
};
Some(syn::Stmt::Local(Box::new(syn::Local {
pat: Box::new(syn::Pat::Ident(
syn::BindingMode::ByValue(syn::Mutability::Immutable),
ident,
None,
)),
ty: None,
init: Some(Box::new(init)),
attrs: vec![],
})))
}
_ => None,
})
.collect()
}
/// Get an expression to find the number of chars in each parameter part for the url.
fn parameter_length_exprs(
url: &[PathPart<'a>],
parts: &BTreeMap<String, Type>,
) -> Vec<syn::Expr> {
url.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => {
let name = match parts[&p.to_string()].ty {
TypeKind::String => valid_name(p).into(),
// handle lists and enums
_ => format!("{}_str", valid_name(p)),
};
Some(
syn::ExprKind::MethodCall(
ident("len"),
vec![],
vec![syn::ExprKind::Path(None, path_none(name.as_ref())).into()],
)
.into(),
)
}
_ => None,
})
.collect()
}
/// Get an expression that is the binary addition of each of the given expressions.
fn summed_length_expr(len_exprs: Vec<syn::Expr>) -> syn::Expr {
match len_exprs.len() {
1 => len_exprs.into_iter().next().unwrap(),
_ => {
let mut len_iter = len_exprs.into_iter();
let first_expr = Box::new(len_iter.next().unwrap());
*(len_iter.map(Box::new).fold(first_expr, |acc, p| {
Box::new(syn::ExprKind::Binary(syn::BinOp::Add, acc, p).into())
}))
}
}
}
/// Get a statement to build a `String` with a capacity of the given expression.
fn let_p_stmt(url_ident: syn::Ident, len_expr: syn::Expr) -> syn::Stmt {
let string_with_capacity = syn::ExprKind::Call(
Box::new(
syn::ExprKind::Path(None, {
let mut method = path_none("String");
method
.segments
.push(syn::PathSegment::from("with_capacity"));
method
})
.into(),
),
vec![len_expr],
)
.into();
syn::Stmt::Local(Box::new(syn::Local {
pat: Box::new(syn::Pat::Ident(
syn::BindingMode::ByValue(syn::Mutability::Mutable),
url_ident.to_owned(),
None,
)),
ty: None,
init: Some(Box::new(string_with_capacity)),
attrs: vec![],
}))
}
/// Get a list of statements that append each part to a `String` in order.
fn push_str_stmts(
url_ident: syn::Ident,
url: &[PathPart<'a>],
parts: &BTreeMap<String, Type>,
) -> Vec<syn::Stmt>
|
}
pub fn build(self) -> syn::Expr {
let has_params = self.path.iter().any(|p| match *p {
PathPart::Param(_) => true,
_ => false,
});
if has_params {
self.build_owned().into_expr()
} else {
self.build_borrowed_literal()
}
}
}
/// Helper for wrapping a value as a quotable expression.
pub trait IntoExpr {
fn into_expr(self) -> syn::Expr;
}
impl IntoExpr for syn::Path {
fn into_expr(self) -> syn::Expr {
syn::ExprKind::Path(None, self).into()
}
}
impl IntoExpr for syn::Block {
fn into_expr(self) -> syn::Expr {
syn::ExprKind::Block(syn::Unsafety::Normal, self).into()
}
}
impl IntoExpr for syn::Ty {
fn into_expr(self) -> syn::Expr {
// TODO: Must be a nicer conversion than this
let mut tokens = quote::Tokens::new();
self.to_tokens(&mut tokens);
parse_expr(tokens)
}
}
impl IntoExpr for syn::Pat {
fn into_expr(self) -> syn::Expr {
// TODO: Must be a nicer conversion than this
let mut tokens = quote::Tokens::new();
self.to_tokens(&mut tokens);
parse_expr(tokens)
}
}
|
{
url.iter()
.map(|p| match *p {
PathPart::Literal(p) => {
let lit = syn::Lit::Str(p.to_string(), syn::StrStyle::Cooked);
syn::Stmt::Semi(Box::new(parse_expr(quote!(#url_ident.push_str(#lit)))))
}
PathPart::Param(p) => {
let name = match parts[&p.to_string()].ty {
TypeKind::String => valid_name(p).into(),
// handle lists and enums
_ => format!("{}_str", valid_name(p)),
};
let ident = ident(name);
syn::Stmt::Semi(Box::new(parse_expr(
quote!(#url_ident.push_str(#ident.as_ref())),
)))
}
})
.collect()
|
identifier_body
|
url_builder.rs
|
/* Some types from or based on types from elastic: https://github.com/elastic-rs/elastic
*
* Licensed under Apache 2.0: https://github.com/elastic-rs/elastic/blob/51298dd64278f34d2db911bd1a35eb757c336198/LICENSE-APACHE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use crate::api_generator::code_gen::*;
use crate::api_generator::{Path, Type, TypeKind};
use quote::ToTokens;
use serde::{Deserialize, Deserializer};
use std::{collections::BTreeMap, fmt, iter::Iterator, str};
use syn;
/// A URL path
#[derive(Debug, Deserialize, PartialEq, Clone)]
pub struct PathString(#[serde(deserialize_with = "rooted_path_string")] pub String);
/// Ensure all deserialized paths have a leading `/`
fn rooted_path_string<'de, D>(deserializer: D) -> Result<String, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
if!s.starts_with('/') {
Ok(format!("/{}", s))
} else {
Ok(s)
}
}
impl fmt::Display for PathString {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl PathString {
/// Splits a path into a vector of parameter and literal parts
pub fn split(&self) -> Vec<PathPart> {
PathString::parse(self.0.as_bytes(), PathParseState::Literal, Vec::new())
}
/// Gets the parameters from the path
pub fn params(&self) -> Vec<&str> {
self.split()
.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => Some(p),
_ => None,
})
.collect()
}
fn parse<'a>(i: &'a [u8], state: PathParseState, r: Vec<PathPart<'a>>) -> Vec<PathPart<'a>> {
if i.is_empty() {
return r;
}
let mut r = r;
match state {
PathParseState::Literal => {
let (rest, part) = PathString::parse_literal(i);
if!part.is_empty() {
r.push(PathPart::Literal(part));
}
PathString::parse(rest, PathParseState::Param, r)
}
PathParseState::Param => {
let (rest, part) = PathString::parse_param(i);
if!part.is_empty() {
r.push(PathPart::Param(part));
}
PathString::parse(rest, PathParseState::Literal, r)
}
}
}
fn parse_literal(i: &[u8]) -> (&[u8], &str) {
if i[0] == b'}' {
let i = shift(i, 1);
take_while(i, |c| c!= b'{')
} else {
take_while(i, |c| c!= b'{')
}
}
fn parse_param(i: &[u8]) -> (&[u8], &str) {
if i[0] == b'{' {
let i = shift(i, 1);
take_while(i, |c| c!= b'}')
} else {
take_while(i, |c| c!= b'}')
}
}
}
enum PathParseState {
Literal,
Param,
}
/// A part of a Path
#[derive(Debug, PartialEq)]
pub enum PathPart<'a> {
Literal(&'a str),
Param(&'a str),
}
pub trait PathParams<'a> {
fn params(&'a self) -> Vec<&'a str>;
}
impl<'a> PathParams<'a> for Vec<PathPart<'a>> {
fn params(&'a self) -> Vec<&'a str> {
self.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => Some(p),
_ => None,
})
.collect()
}
}
/// Builder for an efficient url value replacer.
pub struct UrlBuilder<'a> {
path: Vec<PathPart<'a>>,
parts: &'a BTreeMap<String, Type>,
}
impl<'a> UrlBuilder<'a> {
pub fn new(path: &'a Path) -> Self {
let path_parts = path.path.split();
let parts = &path.parts;
UrlBuilder {
path: path_parts,
parts,
}
}
/// Build the AST for an allocated url from the path literals and params.
fn build_owned(self) -> syn::Block {
let lit_len_expr = Self::literal_length_expr(&self.path);
// collection of let {name}_str = [self.]{name}.[join(",")|to_string()];
let let_params_exprs = Self::let_parameters_exprs(&self.path, &self.parts);
let mut params_len_exprs = Self::parameter_length_exprs(&self.path, self.parts);
let mut len_exprs = vec![lit_len_expr];
len_exprs.append(&mut params_len_exprs);
let len_expr = Self::summed_length_expr(len_exprs);
let url_ident = ident("p");
let let_stmt = Self::let_p_stmt(url_ident.clone(), len_expr);
let mut push_stmts = Self::push_str_stmts(url_ident.clone(), &self.path, self.parts);
let return_expr = syn::Stmt::Expr(Box::new(parse_expr(quote!(#url_ident.into()))));
let mut stmts = let_params_exprs;
stmts.push(let_stmt);
stmts.append(&mut push_stmts);
stmts.push(return_expr);
syn::Block { stmts }
}
/// Build the AST for a literal path
fn build_borrowed_literal(self) -> syn::Expr {
let path: Vec<&'a str> = self
.path
.iter()
.map(|p| match *p {
PathPart::Literal(p) => p,
_ => panic!("Only PathPart::Literal is supported by a borrowed url."),
})
.collect();
let path = path.join("");
let lit = syn::Lit::Str(path, syn::StrStyle::Cooked);
parse_expr(quote!(#lit.into()))
}
/// Get the number of chars in all literal parts for the url.
fn literal_length_expr(url: &[PathPart<'a>]) -> syn::Expr {
let len = url
.iter()
.filter_map(|p| match *p {
PathPart::Literal(p) => Some(p),
_ => None,
})
.fold(0, |acc, p| acc + p.len());
syn::ExprKind::Lit(syn::Lit::Int(len as u64, syn::IntTy::Usize)).into()
}
/// Creates the AST for a let expression for path parts
fn let_parameters_exprs(
url: &[PathPart<'a>],
parts: &BTreeMap<String, Type>,
) -> Vec<syn::Stmt> {
url.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => {
let name = valid_name(p);
let name_ident = ident(&name);
let k = p.to_string();
let ty = parts[&k].ty;
// don't generate an assignment expression for strings
if ty == TypeKind::String {
return None;
}
let tokens = quote!(#name_ident);
// build a different expression, depending on the type of parameter
let (ident, init) = match ty {
TypeKind::List => {
// Join list values together
let name_str = format!("{}_str", &name);
let name_str_ident = ident(&name_str);
let join_call = syn::ExprKind::MethodCall(
ident("join"),
vec![],
vec![
parse_expr(tokens),
syn::ExprKind::Lit(syn::Lit::Str(
",".into(),
syn::StrStyle::Cooked,
))
.into(),
],
)
.into();
(name_str_ident, join_call)
}
_ => {
// Handle enums, long, int, etc. by calling to_string()
let to_string_call = syn::ExprKind::MethodCall(
ident("to_string"),
vec![],
vec![parse_expr(tokens)],
)
.into();
(ident(format!("{}_str", name)), to_string_call)
}
};
Some(syn::Stmt::Local(Box::new(syn::Local {
pat: Box::new(syn::Pat::Ident(
syn::BindingMode::ByValue(syn::Mutability::Immutable),
ident,
None,
)),
ty: None,
init: Some(Box::new(init)),
attrs: vec![],
})))
}
_ => None,
})
.collect()
}
/// Get an expression to find the number of chars in each parameter part for the url.
fn parameter_length_exprs(
url: &[PathPart<'a>],
parts: &BTreeMap<String, Type>,
) -> Vec<syn::Expr> {
url.iter()
.filter_map(|p| match *p {
PathPart::Param(p) => {
let name = match parts[&p.to_string()].ty {
TypeKind::String => valid_name(p).into(),
// handle lists and enums
_ => format!("{}_str", valid_name(p)),
};
Some(
syn::ExprKind::MethodCall(
ident("len"),
vec![],
vec![syn::ExprKind::Path(None, path_none(name.as_ref())).into()],
)
.into(),
)
}
_ => None,
})
.collect()
}
/// Get an expression that is the binary addition of each of the given expressions.
fn summed_length_expr(len_exprs: Vec<syn::Expr>) -> syn::Expr {
match len_exprs.len() {
1 => len_exprs.into_iter().next().unwrap(),
_ => {
let mut len_iter = len_exprs.into_iter();
let first_expr = Box::new(len_iter.next().unwrap());
*(len_iter.map(Box::new).fold(first_expr, |acc, p| {
Box::new(syn::ExprKind::Binary(syn::BinOp::Add, acc, p).into())
}))
}
}
}
/// Get a statement to build a `String` with a capacity of the given expression.
fn let_p_stmt(url_ident: syn::Ident, len_expr: syn::Expr) -> syn::Stmt {
let string_with_capacity = syn::ExprKind::Call(
Box::new(
syn::ExprKind::Path(None, {
let mut method = path_none("String");
method
.segments
.push(syn::PathSegment::from("with_capacity"));
method
})
.into(),
),
vec![len_expr],
)
.into();
syn::Stmt::Local(Box::new(syn::Local {
pat: Box::new(syn::Pat::Ident(
syn::BindingMode::ByValue(syn::Mutability::Mutable),
url_ident.to_owned(),
None,
)),
ty: None,
init: Some(Box::new(string_with_capacity)),
attrs: vec![],
}))
}
/// Get a list of statements that append each part to a `String` in order.
fn push_str_stmts(
url_ident: syn::Ident,
url: &[PathPart<'a>],
parts: &BTreeMap<String, Type>,
) -> Vec<syn::Stmt> {
url.iter()
.map(|p| match *p {
PathPart::Literal(p) => {
let lit = syn::Lit::Str(p.to_string(), syn::StrStyle::Cooked);
syn::Stmt::Semi(Box::new(parse_expr(quote!(#url_ident.push_str(#lit)))))
}
PathPart::Param(p) => {
let name = match parts[&p.to_string()].ty {
TypeKind::String => valid_name(p).into(),
// handle lists and enums
_ => format!("{}_str", valid_name(p)),
};
let ident = ident(name);
syn::Stmt::Semi(Box::new(parse_expr(
quote!(#url_ident.push_str(#ident.as_ref())),
)))
}
})
|
pub fn build(self) -> syn::Expr {
let has_params = self.path.iter().any(|p| match *p {
PathPart::Param(_) => true,
_ => false,
});
if has_params {
self.build_owned().into_expr()
} else {
self.build_borrowed_literal()
}
}
}
/// Helper for wrapping a value as a quotable expression.
pub trait IntoExpr {
fn into_expr(self) -> syn::Expr;
}
impl IntoExpr for syn::Path {
fn into_expr(self) -> syn::Expr {
syn::ExprKind::Path(None, self).into()
}
}
impl IntoExpr for syn::Block {
fn into_expr(self) -> syn::Expr {
syn::ExprKind::Block(syn::Unsafety::Normal, self).into()
}
}
impl IntoExpr for syn::Ty {
fn into_expr(self) -> syn::Expr {
// TODO: Must be a nicer conversion than this
let mut tokens = quote::Tokens::new();
self.to_tokens(&mut tokens);
parse_expr(tokens)
}
}
impl IntoExpr for syn::Pat {
fn into_expr(self) -> syn::Expr {
// TODO: Must be a nicer conversion than this
let mut tokens = quote::Tokens::new();
self.to_tokens(&mut tokens);
parse_expr(tokens)
}
}
|
.collect()
}
|
random_line_split
|
out-of-stack-new-thread-no-split.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//ignore-android
//ignore-freebsd
//ignore-ios
//ignore-dragonfly
#![feature(asm)]
use std::old_io::process::Command;
use std::os;
use std::thread::Thread;
// lifted from the test module
// Inlining to avoid llvm turning the recursive functions into tail calls,
// which doesn't consume stack.
#[inline(always)]
#[no_stack_check]
pub fn black_box<T>(dummy: T) { unsafe { asm!("" : : "r"(&dummy)) } }
#[no_stack_check]
fn recurse() {
let buf = [0; 10];
black_box(buf);
recurse();
}
fn
|
() {
let args = os::args();
let args = args;
if args.len() > 1 && args[1] == "recurse" {
let _t = Thread::scoped(recurse);
} else {
let recurse = Command::new(&args[0]).arg("recurse").output().unwrap();
assert!(!recurse.status.success());
let error = String::from_utf8_lossy(&recurse.error);
println!("wut");
println!("`{}`", error);
assert!(error.contains("has overflowed its stack"));
}
}
|
main
|
identifier_name
|
out-of-stack-new-thread-no-split.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//ignore-android
//ignore-freebsd
//ignore-ios
//ignore-dragonfly
#![feature(asm)]
use std::old_io::process::Command;
use std::os;
|
// lifted from the test module
// Inlining to avoid llvm turning the recursive functions into tail calls,
// which doesn't consume stack.
#[inline(always)]
#[no_stack_check]
pub fn black_box<T>(dummy: T) { unsafe { asm!("" : : "r"(&dummy)) } }
#[no_stack_check]
fn recurse() {
let buf = [0; 10];
black_box(buf);
recurse();
}
fn main() {
let args = os::args();
let args = args;
if args.len() > 1 && args[1] == "recurse" {
let _t = Thread::scoped(recurse);
} else {
let recurse = Command::new(&args[0]).arg("recurse").output().unwrap();
assert!(!recurse.status.success());
let error = String::from_utf8_lossy(&recurse.error);
println!("wut");
println!("`{}`", error);
assert!(error.contains("has overflowed its stack"));
}
}
|
use std::thread::Thread;
|
random_line_split
|
out-of-stack-new-thread-no-split.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//ignore-android
//ignore-freebsd
//ignore-ios
//ignore-dragonfly
#![feature(asm)]
use std::old_io::process::Command;
use std::os;
use std::thread::Thread;
// lifted from the test module
// Inlining to avoid llvm turning the recursive functions into tail calls,
// which doesn't consume stack.
#[inline(always)]
#[no_stack_check]
pub fn black_box<T>(dummy: T)
|
#[no_stack_check]
fn recurse() {
let buf = [0; 10];
black_box(buf);
recurse();
}
fn main() {
let args = os::args();
let args = args;
if args.len() > 1 && args[1] == "recurse" {
let _t = Thread::scoped(recurse);
} else {
let recurse = Command::new(&args[0]).arg("recurse").output().unwrap();
assert!(!recurse.status.success());
let error = String::from_utf8_lossy(&recurse.error);
println!("wut");
println!("`{}`", error);
assert!(error.contains("has overflowed its stack"));
}
}
|
{ unsafe { asm!("" : : "r"(&dummy)) } }
|
identifier_body
|
out-of-stack-new-thread-no-split.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//ignore-android
//ignore-freebsd
//ignore-ios
//ignore-dragonfly
#![feature(asm)]
use std::old_io::process::Command;
use std::os;
use std::thread::Thread;
// lifted from the test module
// Inlining to avoid llvm turning the recursive functions into tail calls,
// which doesn't consume stack.
#[inline(always)]
#[no_stack_check]
pub fn black_box<T>(dummy: T) { unsafe { asm!("" : : "r"(&dummy)) } }
#[no_stack_check]
fn recurse() {
let buf = [0; 10];
black_box(buf);
recurse();
}
fn main() {
let args = os::args();
let args = args;
if args.len() > 1 && args[1] == "recurse" {
let _t = Thread::scoped(recurse);
} else
|
}
|
{
let recurse = Command::new(&args[0]).arg("recurse").output().unwrap();
assert!(!recurse.status.success());
let error = String::from_utf8_lossy(&recurse.error);
println!("wut");
println!("`{}`", error);
assert!(error.contains("has overflowed its stack"));
}
|
conditional_block
|
array.rs
|
extern crate byteorder;
use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
use std::error::Error;
use std::io::Write;
use backend::Debug;
use pg::{Pg, PgTypeMetadata};
use query_source::Queryable;
use types::*;
impl<T> HasSqlType<Array<T>> for Pg where
Pg: HasSqlType<T>,
{
fn metadata() -> PgTypeMetadata {
PgTypeMetadata {
oid: <Pg as HasSqlType<T>>::metadata().array_oid,
array_oid: 0,
}
}
}
impl<T> HasSqlType<Array<T>> for Debug where
Debug: HasSqlType<T>,
{
fn metadata() {}
}
impl_query_id!(Array<T>);
impl<T> NotNull for Array<T> {
}
impl<T, ST> FromSql<Array<ST>, Pg> for Vec<T> where
T: FromSql<ST, Pg>,
Pg: HasSqlType<ST>,
{
fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error+Send+Sync>> {
let mut bytes = not_none!(bytes);
let num_dimensions = try!(bytes.read_i32::<BigEndian>());
let has_null = try!(bytes.read_i32::<BigEndian>())!= 0;
let _oid = try!(bytes.read_i32::<BigEndian>());
if num_dimensions == 0 {
return Ok(Vec::new())
}
let num_elements = try!(bytes.read_i32::<BigEndian>());
let lower_bound = try!(bytes.read_i32::<BigEndian>());
assert!(num_dimensions == 1, "multi-dimensional arrays are not supported");
assert!(lower_bound == 1, "lower bound must be 1");
(0..num_elements).map(|_| {
let elem_size = try!(bytes.read_i32::<BigEndian>());
if has_null && elem_size == -1 {
T::from_sql(None)
} else {
let (elem_bytes, new_bytes) = bytes.split_at(elem_size as usize);
bytes = new_bytes;
T::from_sql(Some(&elem_bytes))
}
}).collect()
}
}
impl<T, ST> FromSqlRow<Array<ST>, Pg> for Vec<T> where
Pg: HasSqlType<ST>,
Vec<T>: FromSql<Array<ST>, Pg>,
{
fn build_from_row<R: ::row::Row<Pg>>(row: &mut R) -> Result<Self, Box<Error+Send+Sync>> {
FromSql::<Array<ST>, Pg>::from_sql(row.take())
}
}
impl<T, ST> Queryable<Array<ST>, Pg> for Vec<T> where
T: FromSql<ST, Pg> + Queryable<ST, Pg>,
Pg: HasSqlType<ST>,
{
type Row = Self;
fn
|
(row: Self) -> Self {
row
}
}
use expression::AsExpression;
use expression::bound::Bound;
macro_rules! array_as_expression {
($ty:ty, $sql_type:ty) => {
impl<'a, ST, T> AsExpression<$sql_type> for $ty where
Pg: HasSqlType<ST>,
{
type Expression = Bound<$sql_type, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
}
}
array_as_expression!(&'a [T], Array<ST>);
array_as_expression!(&'a [T], Nullable<Array<ST>>);
array_as_expression!(&'a &'a [T], Array<ST>);
array_as_expression!(&'a &'a [T], Nullable<Array<ST>>);
array_as_expression!(Vec<T>, Array<ST>);
array_as_expression!(Vec<T>, Nullable<Array<ST>>);
array_as_expression!(&'a Vec<T>, Array<ST>);
array_as_expression!(&'a Vec<T>, Nullable<Array<ST>>);
impl<'a, ST, T> ToSql<Array<ST>, Pg> for &'a [T] where
Pg: HasSqlType<ST>,
T: ToSql<ST, Pg>,
{
fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
let num_dimensions = 1;
try!(out.write_i32::<BigEndian>(num_dimensions));
let flags = 0;
try!(out.write_i32::<BigEndian>(flags));
try!(out.write_u32::<BigEndian>(Pg::metadata().oid));
try!(out.write_i32::<BigEndian>(self.len() as i32));
let lower_bound = 1;
try!(out.write_i32::<BigEndian>(lower_bound));
let mut buffer = Vec::new();
for elem in self.iter() {
let is_null = try!(elem.to_sql(&mut buffer));
assert!(is_null == IsNull::No, "Arrays containing null are not supported");
try!(out.write_i32::<BigEndian>(buffer.len() as i32));
try!(out.write_all(&buffer));
buffer.clear();
}
Ok(IsNull::No)
}
}
impl<ST, T> ToSql<Array<ST>, Pg> for Vec<T> where
Pg: HasSqlType<ST>,
for<'a> &'a [T]: ToSql<Array<ST>, Pg>,
{
fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
(&self as &[T]).to_sql(out)
}
}
|
build
|
identifier_name
|
array.rs
|
extern crate byteorder;
use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
use std::error::Error;
use std::io::Write;
use backend::Debug;
use pg::{Pg, PgTypeMetadata};
use query_source::Queryable;
use types::*;
impl<T> HasSqlType<Array<T>> for Pg where
Pg: HasSqlType<T>,
{
fn metadata() -> PgTypeMetadata {
PgTypeMetadata {
oid: <Pg as HasSqlType<T>>::metadata().array_oid,
array_oid: 0,
}
}
}
impl<T> HasSqlType<Array<T>> for Debug where
Debug: HasSqlType<T>,
{
fn metadata() {}
}
impl_query_id!(Array<T>);
impl<T> NotNull for Array<T> {
}
impl<T, ST> FromSql<Array<ST>, Pg> for Vec<T> where
T: FromSql<ST, Pg>,
Pg: HasSqlType<ST>,
{
fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error+Send+Sync>> {
let mut bytes = not_none!(bytes);
let num_dimensions = try!(bytes.read_i32::<BigEndian>());
let has_null = try!(bytes.read_i32::<BigEndian>())!= 0;
let _oid = try!(bytes.read_i32::<BigEndian>());
if num_dimensions == 0
|
let num_elements = try!(bytes.read_i32::<BigEndian>());
let lower_bound = try!(bytes.read_i32::<BigEndian>());
assert!(num_dimensions == 1, "multi-dimensional arrays are not supported");
assert!(lower_bound == 1, "lower bound must be 1");
(0..num_elements).map(|_| {
let elem_size = try!(bytes.read_i32::<BigEndian>());
if has_null && elem_size == -1 {
T::from_sql(None)
} else {
let (elem_bytes, new_bytes) = bytes.split_at(elem_size as usize);
bytes = new_bytes;
T::from_sql(Some(&elem_bytes))
}
}).collect()
}
}
impl<T, ST> FromSqlRow<Array<ST>, Pg> for Vec<T> where
Pg: HasSqlType<ST>,
Vec<T>: FromSql<Array<ST>, Pg>,
{
fn build_from_row<R: ::row::Row<Pg>>(row: &mut R) -> Result<Self, Box<Error+Send+Sync>> {
FromSql::<Array<ST>, Pg>::from_sql(row.take())
}
}
impl<T, ST> Queryable<Array<ST>, Pg> for Vec<T> where
T: FromSql<ST, Pg> + Queryable<ST, Pg>,
Pg: HasSqlType<ST>,
{
type Row = Self;
fn build(row: Self) -> Self {
row
}
}
use expression::AsExpression;
use expression::bound::Bound;
macro_rules! array_as_expression {
($ty:ty, $sql_type:ty) => {
impl<'a, ST, T> AsExpression<$sql_type> for $ty where
Pg: HasSqlType<ST>,
{
type Expression = Bound<$sql_type, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
}
}
array_as_expression!(&'a [T], Array<ST>);
array_as_expression!(&'a [T], Nullable<Array<ST>>);
array_as_expression!(&'a &'a [T], Array<ST>);
array_as_expression!(&'a &'a [T], Nullable<Array<ST>>);
array_as_expression!(Vec<T>, Array<ST>);
array_as_expression!(Vec<T>, Nullable<Array<ST>>);
array_as_expression!(&'a Vec<T>, Array<ST>);
array_as_expression!(&'a Vec<T>, Nullable<Array<ST>>);
impl<'a, ST, T> ToSql<Array<ST>, Pg> for &'a [T] where
Pg: HasSqlType<ST>,
T: ToSql<ST, Pg>,
{
fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
let num_dimensions = 1;
try!(out.write_i32::<BigEndian>(num_dimensions));
let flags = 0;
try!(out.write_i32::<BigEndian>(flags));
try!(out.write_u32::<BigEndian>(Pg::metadata().oid));
try!(out.write_i32::<BigEndian>(self.len() as i32));
let lower_bound = 1;
try!(out.write_i32::<BigEndian>(lower_bound));
let mut buffer = Vec::new();
for elem in self.iter() {
let is_null = try!(elem.to_sql(&mut buffer));
assert!(is_null == IsNull::No, "Arrays containing null are not supported");
try!(out.write_i32::<BigEndian>(buffer.len() as i32));
try!(out.write_all(&buffer));
buffer.clear();
}
Ok(IsNull::No)
}
}
impl<ST, T> ToSql<Array<ST>, Pg> for Vec<T> where
Pg: HasSqlType<ST>,
for<'a> &'a [T]: ToSql<Array<ST>, Pg>,
{
fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
(&self as &[T]).to_sql(out)
}
}
|
{
return Ok(Vec::new())
}
|
conditional_block
|
array.rs
|
extern crate byteorder;
use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
use std::error::Error;
use std::io::Write;
use backend::Debug;
use pg::{Pg, PgTypeMetadata};
use query_source::Queryable;
use types::*;
impl<T> HasSqlType<Array<T>> for Pg where
Pg: HasSqlType<T>,
{
fn metadata() -> PgTypeMetadata {
PgTypeMetadata {
oid: <Pg as HasSqlType<T>>::metadata().array_oid,
array_oid: 0,
}
}
}
impl<T> HasSqlType<Array<T>> for Debug where
Debug: HasSqlType<T>,
{
fn metadata() {}
}
impl_query_id!(Array<T>);
impl<T> NotNull for Array<T> {
}
impl<T, ST> FromSql<Array<ST>, Pg> for Vec<T> where
T: FromSql<ST, Pg>,
Pg: HasSqlType<ST>,
{
fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error+Send+Sync>> {
let mut bytes = not_none!(bytes);
let num_dimensions = try!(bytes.read_i32::<BigEndian>());
let has_null = try!(bytes.read_i32::<BigEndian>())!= 0;
let _oid = try!(bytes.read_i32::<BigEndian>());
if num_dimensions == 0 {
return Ok(Vec::new())
}
let num_elements = try!(bytes.read_i32::<BigEndian>());
let lower_bound = try!(bytes.read_i32::<BigEndian>());
assert!(num_dimensions == 1, "multi-dimensional arrays are not supported");
assert!(lower_bound == 1, "lower bound must be 1");
(0..num_elements).map(|_| {
let elem_size = try!(bytes.read_i32::<BigEndian>());
if has_null && elem_size == -1 {
T::from_sql(None)
} else {
let (elem_bytes, new_bytes) = bytes.split_at(elem_size as usize);
bytes = new_bytes;
T::from_sql(Some(&elem_bytes))
}
}).collect()
}
}
impl<T, ST> FromSqlRow<Array<ST>, Pg> for Vec<T> where
Pg: HasSqlType<ST>,
Vec<T>: FromSql<Array<ST>, Pg>,
{
fn build_from_row<R: ::row::Row<Pg>>(row: &mut R) -> Result<Self, Box<Error+Send+Sync>> {
FromSql::<Array<ST>, Pg>::from_sql(row.take())
}
}
impl<T, ST> Queryable<Array<ST>, Pg> for Vec<T> where
T: FromSql<ST, Pg> + Queryable<ST, Pg>,
Pg: HasSqlType<ST>,
{
type Row = Self;
fn build(row: Self) -> Self {
row
}
}
use expression::AsExpression;
use expression::bound::Bound;
macro_rules! array_as_expression {
($ty:ty, $sql_type:ty) => {
impl<'a, ST, T> AsExpression<$sql_type> for $ty where
Pg: HasSqlType<ST>,
{
type Expression = Bound<$sql_type, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
}
}
array_as_expression!(&'a [T], Array<ST>);
array_as_expression!(&'a [T], Nullable<Array<ST>>);
array_as_expression!(&'a &'a [T], Array<ST>);
array_as_expression!(&'a &'a [T], Nullable<Array<ST>>);
array_as_expression!(Vec<T>, Array<ST>);
array_as_expression!(Vec<T>, Nullable<Array<ST>>);
array_as_expression!(&'a Vec<T>, Array<ST>);
array_as_expression!(&'a Vec<T>, Nullable<Array<ST>>);
impl<'a, ST, T> ToSql<Array<ST>, Pg> for &'a [T] where
Pg: HasSqlType<ST>,
T: ToSql<ST, Pg>,
{
fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
let num_dimensions = 1;
|
try!(out.write_u32::<BigEndian>(Pg::metadata().oid));
try!(out.write_i32::<BigEndian>(self.len() as i32));
let lower_bound = 1;
try!(out.write_i32::<BigEndian>(lower_bound));
let mut buffer = Vec::new();
for elem in self.iter() {
let is_null = try!(elem.to_sql(&mut buffer));
assert!(is_null == IsNull::No, "Arrays containing null are not supported");
try!(out.write_i32::<BigEndian>(buffer.len() as i32));
try!(out.write_all(&buffer));
buffer.clear();
}
Ok(IsNull::No)
}
}
impl<ST, T> ToSql<Array<ST>, Pg> for Vec<T> where
Pg: HasSqlType<ST>,
for<'a> &'a [T]: ToSql<Array<ST>, Pg>,
{
fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
(&self as &[T]).to_sql(out)
}
}
|
try!(out.write_i32::<BigEndian>(num_dimensions));
let flags = 0;
try!(out.write_i32::<BigEndian>(flags));
|
random_line_split
|
array.rs
|
extern crate byteorder;
use self::byteorder::{ReadBytesExt, WriteBytesExt, BigEndian};
use std::error::Error;
use std::io::Write;
use backend::Debug;
use pg::{Pg, PgTypeMetadata};
use query_source::Queryable;
use types::*;
impl<T> HasSqlType<Array<T>> for Pg where
Pg: HasSqlType<T>,
{
fn metadata() -> PgTypeMetadata {
PgTypeMetadata {
oid: <Pg as HasSqlType<T>>::metadata().array_oid,
array_oid: 0,
}
}
}
impl<T> HasSqlType<Array<T>> for Debug where
Debug: HasSqlType<T>,
{
fn metadata() {}
}
impl_query_id!(Array<T>);
impl<T> NotNull for Array<T> {
}
impl<T, ST> FromSql<Array<ST>, Pg> for Vec<T> where
T: FromSql<ST, Pg>,
Pg: HasSqlType<ST>,
{
fn from_sql(bytes: Option<&[u8]>) -> Result<Self, Box<Error+Send+Sync>> {
let mut bytes = not_none!(bytes);
let num_dimensions = try!(bytes.read_i32::<BigEndian>());
let has_null = try!(bytes.read_i32::<BigEndian>())!= 0;
let _oid = try!(bytes.read_i32::<BigEndian>());
if num_dimensions == 0 {
return Ok(Vec::new())
}
let num_elements = try!(bytes.read_i32::<BigEndian>());
let lower_bound = try!(bytes.read_i32::<BigEndian>());
assert!(num_dimensions == 1, "multi-dimensional arrays are not supported");
assert!(lower_bound == 1, "lower bound must be 1");
(0..num_elements).map(|_| {
let elem_size = try!(bytes.read_i32::<BigEndian>());
if has_null && elem_size == -1 {
T::from_sql(None)
} else {
let (elem_bytes, new_bytes) = bytes.split_at(elem_size as usize);
bytes = new_bytes;
T::from_sql(Some(&elem_bytes))
}
}).collect()
}
}
impl<T, ST> FromSqlRow<Array<ST>, Pg> for Vec<T> where
Pg: HasSqlType<ST>,
Vec<T>: FromSql<Array<ST>, Pg>,
{
fn build_from_row<R: ::row::Row<Pg>>(row: &mut R) -> Result<Self, Box<Error+Send+Sync>>
|
}
impl<T, ST> Queryable<Array<ST>, Pg> for Vec<T> where
T: FromSql<ST, Pg> + Queryable<ST, Pg>,
Pg: HasSqlType<ST>,
{
type Row = Self;
fn build(row: Self) -> Self {
row
}
}
use expression::AsExpression;
use expression::bound::Bound;
macro_rules! array_as_expression {
($ty:ty, $sql_type:ty) => {
impl<'a, ST, T> AsExpression<$sql_type> for $ty where
Pg: HasSqlType<ST>,
{
type Expression = Bound<$sql_type, Self>;
fn as_expression(self) -> Self::Expression {
Bound::new(self)
}
}
}
}
array_as_expression!(&'a [T], Array<ST>);
array_as_expression!(&'a [T], Nullable<Array<ST>>);
array_as_expression!(&'a &'a [T], Array<ST>);
array_as_expression!(&'a &'a [T], Nullable<Array<ST>>);
array_as_expression!(Vec<T>, Array<ST>);
array_as_expression!(Vec<T>, Nullable<Array<ST>>);
array_as_expression!(&'a Vec<T>, Array<ST>);
array_as_expression!(&'a Vec<T>, Nullable<Array<ST>>);
impl<'a, ST, T> ToSql<Array<ST>, Pg> for &'a [T] where
Pg: HasSqlType<ST>,
T: ToSql<ST, Pg>,
{
fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
let num_dimensions = 1;
try!(out.write_i32::<BigEndian>(num_dimensions));
let flags = 0;
try!(out.write_i32::<BigEndian>(flags));
try!(out.write_u32::<BigEndian>(Pg::metadata().oid));
try!(out.write_i32::<BigEndian>(self.len() as i32));
let lower_bound = 1;
try!(out.write_i32::<BigEndian>(lower_bound));
let mut buffer = Vec::new();
for elem in self.iter() {
let is_null = try!(elem.to_sql(&mut buffer));
assert!(is_null == IsNull::No, "Arrays containing null are not supported");
try!(out.write_i32::<BigEndian>(buffer.len() as i32));
try!(out.write_all(&buffer));
buffer.clear();
}
Ok(IsNull::No)
}
}
impl<ST, T> ToSql<Array<ST>, Pg> for Vec<T> where
Pg: HasSqlType<ST>,
for<'a> &'a [T]: ToSql<Array<ST>, Pg>,
{
fn to_sql<W: Write>(&self, out: &mut W) -> Result<IsNull, Box<Error+Send+Sync>> {
(&self as &[T]).to_sql(out)
}
}
|
{
FromSql::<Array<ST>, Pg>::from_sql(row.take())
}
|
identifier_body
|
frame.rs
|
/*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
File: client/md5/animation/frame.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
TODO
*/
use math;
struct Base_Frame
{
position: math::Vec3f,
orientation: math::Quaternion,
}
struct Frame_Data
{
id: i32,
data: ~[f32],
}
impl Base_Frame
{
pub fn new() -> Base_Frame
{
Base_Frame
{
position: math::Vec3f::zero(),
orientation: math::Quaternion::zero(),
}
}
}
impl Frame_Data
{
pub fn
|
() -> Frame_Data
{
Frame_Data
{
id: 0,
data: ~[],
}
}
}
|
new
|
identifier_name
|
frame.rs
|
/*
Copyright 2013 Jesse 'Jeaye' Wilkerson
See licensing in LICENSE file, or at:
http://www.opensource.org/licenses/BSD-3-Clause
|
File: client/md5/animation/frame.rs
Author: Jesse 'Jeaye' Wilkerson
Description:
TODO
*/
use math;
struct Base_Frame
{
position: math::Vec3f,
orientation: math::Quaternion,
}
struct Frame_Data
{
id: i32,
data: ~[f32],
}
impl Base_Frame
{
pub fn new() -> Base_Frame
{
Base_Frame
{
position: math::Vec3f::zero(),
orientation: math::Quaternion::zero(),
}
}
}
impl Frame_Data
{
pub fn new() -> Frame_Data
{
Frame_Data
{
id: 0,
data: ~[],
}
}
}
|
random_line_split
|
|
local_ptr.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.
//! Access to a single thread-local pointer.
//!
//! The runtime will use this for storing Box<Task>.
//!
//! FIXME: Add runtime checks for usage of inconsistent pointer types.
//! and for overwriting an existing pointer.
#![allow(dead_code)]
use core::prelude::*;
use core::mem;
use alloc::boxed::Box;
#[cfg(windows)] // mingw-w32 doesn't like thread_local things
#[cfg(target_os = "android")] // see #10686
#[cfg(target_os = "ios")]
pub use self::native::{init, cleanup, put, take, try_take, unsafe_take, exists,
unsafe_borrow, try_unsafe_borrow};
#[cfg(not(windows), not(target_os = "android"), not(target_os = "ios"))]
pub use self::compiled::{init, cleanup, put, take, try_take, unsafe_take, exists,
unsafe_borrow, try_unsafe_borrow};
/// Encapsulates a borrowed value. When this value goes out of scope, the
/// pointer is returned.
pub struct Borrowed<T> {
val: *const (),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: Box<T> = mem::transmute(self.val);
put::<T>(val);
rtassert!(exists());
}
}
}
impl<T> Deref<T> for Borrowed<T> {
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*(self.val as *const T) }
}
}
impl<T> DerefMut<T> for Borrowed<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *(self.val as *mut T) }
}
}
/// Borrow the thread-local value from thread-local storage.
/// While the value is borrowed it is not available in TLS.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn borrow<T>() -> Borrowed<T> {
let val: *const () = mem::transmute(take::<T>());
Borrowed {
val: val,
}
}
/// Compiled implementation of accessing the runtime local pointer. This is
/// implemented using LLVM's thread_local attribute which isn't necessarily
/// working on all platforms. This implementation is faster, however, so we use
/// it wherever possible.
#[cfg(not(windows), not(target_os = "android"), not(target_os = "ios"))]
pub mod compiled {
use core::prelude::*;
use alloc::boxed::Box;
use core::mem;
#[cfg(test)]
pub use realrustrt::shouldnt_be_public::RT_TLS_PTR;
#[cfg(not(test))]
#[thread_local]
pub static mut RT_TLS_PTR: *mut u8 = 0 as *mut u8;
pub fn init() {}
pub unsafe fn cleanup() {}
// Rationale for all of these functions being inline(never)
//
// The #[thread_local] annotation gets propagated all the way through to
// LLVM, meaning the global is specially treated by LLVM to lower it to an
// efficient sequence of instructions. This also involves dealing with fun
// stuff in object files and whatnot. Regardless, it turns out this causes
// trouble with green threads and lots of optimizations turned on. The
// following case study was done on linux x86_64, but I would imagine that
// other platforms are similar.
//
// On linux, the instruction sequence for loading the tls pointer global
// looks like:
//
// mov %fs:0x0, %rax
// mov -0x8(%rax), %rbx
//
// This code leads me to believe that (%fs:0x0) is a table, and then the
// table contains the TLS values for the process. Hence, the slot at offset
// -0x8 is the task TLS pointer. This leads us to the conclusion that this
// table is the actual thread local part of each thread. The kernel sets up
// the fs segment selector to point at the right region of memory for each
// thread.
//
// Optimizations lead me to believe that this code is lowered to these
// instructions in the LLVM codegen passes, because you'll see code like
// this when everything is optimized:
//
// mov %fs:0x0, %r14
// mov -0x8(%r14), %rbx
// // do something with %rbx, the rust Task pointer
//
// ... // <- do more things
//
// mov -0x8(%r14), %rbx
// // do something else with %rbx
//
// Note that the optimization done here is that the first load is not
// duplicated during the lower instructions. This means that the %fs:0x0
// memory location is only dereferenced once.
//
// Normally, this is actually a good thing! With green threads, however,
// it's very possible for the code labeled "do more things" to context
// switch to another thread. If this happens, then we *must* re-load %fs:0x0
// because it's changed (we're on a different thread). If we don't re-load
// the table location, then we'll be reading the original thread's TLS
// values, not our thread's TLS values.
//
// Hence, we never inline these functions. By never inlining, we're
// guaranteed that loading the table is a local decision which is forced to
// *always* happen.
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline(never)] // see comments above
pub unsafe fn put<T>(sched: Box<T>) {
RT_TLS_PTR = mem::transmute(sched)
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline(never)] // see comments above
pub unsafe fn take<T>() -> Box<T> {
let ptr = RT_TLS_PTR;
rtassert!(!ptr.is_null());
let ptr: Box<T> = mem::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = mem::transmute(0u);
ptr
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline(never)] // see comments above
pub unsafe fn try_take<T>() -> Option<Box<T>> {
let ptr = RT_TLS_PTR;
if ptr.is_null() {
None
} else {
let ptr: Box<T> = mem::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = mem::transmute(0u);
Some(ptr)
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline(never)] // see comments above
pub unsafe fn unsafe_take<T>() -> Box<T> {
mem::transmute(RT_TLS_PTR)
}
/// Check whether there is a thread-local pointer installed.
#[inline(never)] // see comments above
pub fn exists() -> bool {
unsafe {
RT_TLS_PTR.is_not_null()
}
}
#[inline(never)] // see comments above
pub unsafe fn unsafe_borrow<T>() -> *mut T {
if RT_TLS_PTR.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
RT_TLS_PTR as *mut T
}
#[inline(never)] // see comments above
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
if RT_TLS_PTR.is_null() {
None
} else {
Some(RT_TLS_PTR as *mut T)
}
}
}
/// Native implementation of having the runtime thread-local pointer. This
/// implementation uses the `thread_local_storage` module to provide a
/// thread-local value.
pub mod native {
use core::prelude::*;
use alloc::boxed::Box;
use core::mem;
use core::ptr;
use tls = thread_local_storage;
static mut RT_TLS_KEY: tls::Key = -1;
/// Initialize the TLS key. Other ops will fail if this isn't executed
/// first.
pub fn init() {
unsafe {
tls::create(&mut RT_TLS_KEY);
}
}
pub unsafe fn cleanup() {
rtassert!(RT_TLS_KEY!= -1);
tls::destroy(RT_TLS_KEY);
}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: Box<T>) {
let key = tls_key();
let void_ptr: *mut u8 = mem::transmute(sched);
tls::set(key, void_ptr);
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> Box<T> {
let key = tls_key();
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: Box<T> = mem::transmute(void_ptr);
tls::set(key, ptr::mut_null());
return ptr;
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn try_take<T>() -> Option<Box<T>> {
match maybe_tls_key() {
Some(key) => {
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
None
} else {
let ptr: Box<T> = mem::transmute(void_ptr);
tls::set(key, ptr::mut_null());
Some(ptr)
}
}
None => None
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline]
pub unsafe fn unsafe_take<T>() -> Box<T> {
let key = tls_key();
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: Box<T> = mem::transmute(void_ptr);
return ptr;
}
/// Check whether there is a thread-local pointer installed.
pub fn exists() -> bool {
unsafe {
match maybe_tls_key() {
Some(key) => tls::get(key).is_not_null(),
None => false
}
}
}
/// Borrow a mutable reference to the thread-local value
///
/// # Safety Note
///
/// Because this leaves the value in thread-local storage it is possible
/// For the Scheduler pointer to be aliased
pub unsafe fn unsafe_borrow<T>() -> *mut T {
let key = tls_key();
let void_ptr = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
void_ptr as *mut T
}
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr = tls::get(key);
if void_ptr.is_null() {
None
} else {
Some(void_ptr as *mut T)
}
}
None => None
}
}
#[inline]
fn tls_key() -> tls::Key {
match maybe_tls_key() {
Some(key) => key,
None => rtabort!("runtime tls key not initialized")
}
}
#[inline]
#[cfg(not(test))]
#[allow(visible_private_types)]
pub fn maybe_tls_key() -> Option<tls::Key> {
unsafe {
// NB: This is a little racy because, while the key is
// initialized under a mutex and it's assumed to be initialized
// in the Scheduler ctor by any thread that needs to use it,
// we are not accessing the key under a mutex. Threads that
// are not using the new Scheduler but still *want to check*
// whether they are running under a new Scheduler may see a 0
// value here that is in the process of being initialized in
// another thread. I think this is fine since the only action
// they could take if it was initialized would be to check the
// thread-local value and see that it's not set.
if RT_TLS_KEY!= -1 {
return Some(RT_TLS_KEY);
} else {
return None;
}
}
}
#[inline] #[cfg(test)]
pub fn maybe_tls_key() -> Option<tls::Key> {
use realrustrt;
unsafe {
|
}
|
mem::transmute(realrustrt::shouldnt_be_public::maybe_tls_key())
}
}
|
random_line_split
|
local_ptr.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.
//! Access to a single thread-local pointer.
//!
//! The runtime will use this for storing Box<Task>.
//!
//! FIXME: Add runtime checks for usage of inconsistent pointer types.
//! and for overwriting an existing pointer.
#![allow(dead_code)]
use core::prelude::*;
use core::mem;
use alloc::boxed::Box;
#[cfg(windows)] // mingw-w32 doesn't like thread_local things
#[cfg(target_os = "android")] // see #10686
#[cfg(target_os = "ios")]
pub use self::native::{init, cleanup, put, take, try_take, unsafe_take, exists,
unsafe_borrow, try_unsafe_borrow};
#[cfg(not(windows), not(target_os = "android"), not(target_os = "ios"))]
pub use self::compiled::{init, cleanup, put, take, try_take, unsafe_take, exists,
unsafe_borrow, try_unsafe_borrow};
/// Encapsulates a borrowed value. When this value goes out of scope, the
/// pointer is returned.
pub struct Borrowed<T> {
val: *const (),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: Box<T> = mem::transmute(self.val);
put::<T>(val);
rtassert!(exists());
}
}
}
impl<T> Deref<T> for Borrowed<T> {
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*(self.val as *const T) }
}
}
impl<T> DerefMut<T> for Borrowed<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *(self.val as *mut T) }
}
}
/// Borrow the thread-local value from thread-local storage.
/// While the value is borrowed it is not available in TLS.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn borrow<T>() -> Borrowed<T> {
let val: *const () = mem::transmute(take::<T>());
Borrowed {
val: val,
}
}
/// Compiled implementation of accessing the runtime local pointer. This is
/// implemented using LLVM's thread_local attribute which isn't necessarily
/// working on all platforms. This implementation is faster, however, so we use
/// it wherever possible.
#[cfg(not(windows), not(target_os = "android"), not(target_os = "ios"))]
pub mod compiled {
use core::prelude::*;
use alloc::boxed::Box;
use core::mem;
#[cfg(test)]
pub use realrustrt::shouldnt_be_public::RT_TLS_PTR;
#[cfg(not(test))]
#[thread_local]
pub static mut RT_TLS_PTR: *mut u8 = 0 as *mut u8;
pub fn init() {}
pub unsafe fn cleanup() {}
// Rationale for all of these functions being inline(never)
//
// The #[thread_local] annotation gets propagated all the way through to
// LLVM, meaning the global is specially treated by LLVM to lower it to an
// efficient sequence of instructions. This also involves dealing with fun
// stuff in object files and whatnot. Regardless, it turns out this causes
// trouble with green threads and lots of optimizations turned on. The
// following case study was done on linux x86_64, but I would imagine that
// other platforms are similar.
//
// On linux, the instruction sequence for loading the tls pointer global
// looks like:
//
// mov %fs:0x0, %rax
// mov -0x8(%rax), %rbx
//
// This code leads me to believe that (%fs:0x0) is a table, and then the
// table contains the TLS values for the process. Hence, the slot at offset
// -0x8 is the task TLS pointer. This leads us to the conclusion that this
// table is the actual thread local part of each thread. The kernel sets up
// the fs segment selector to point at the right region of memory for each
// thread.
//
// Optimizations lead me to believe that this code is lowered to these
// instructions in the LLVM codegen passes, because you'll see code like
// this when everything is optimized:
//
// mov %fs:0x0, %r14
// mov -0x8(%r14), %rbx
// // do something with %rbx, the rust Task pointer
//
// ... // <- do more things
//
// mov -0x8(%r14), %rbx
// // do something else with %rbx
//
// Note that the optimization done here is that the first load is not
// duplicated during the lower instructions. This means that the %fs:0x0
// memory location is only dereferenced once.
//
// Normally, this is actually a good thing! With green threads, however,
// it's very possible for the code labeled "do more things" to context
// switch to another thread. If this happens, then we *must* re-load %fs:0x0
// because it's changed (we're on a different thread). If we don't re-load
// the table location, then we'll be reading the original thread's TLS
// values, not our thread's TLS values.
//
// Hence, we never inline these functions. By never inlining, we're
// guaranteed that loading the table is a local decision which is forced to
// *always* happen.
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline(never)] // see comments above
pub unsafe fn put<T>(sched: Box<T>) {
RT_TLS_PTR = mem::transmute(sched)
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline(never)] // see comments above
pub unsafe fn take<T>() -> Box<T> {
let ptr = RT_TLS_PTR;
rtassert!(!ptr.is_null());
let ptr: Box<T> = mem::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = mem::transmute(0u);
ptr
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline(never)] // see comments above
pub unsafe fn try_take<T>() -> Option<Box<T>> {
let ptr = RT_TLS_PTR;
if ptr.is_null() {
None
} else {
let ptr: Box<T> = mem::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = mem::transmute(0u);
Some(ptr)
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline(never)] // see comments above
pub unsafe fn unsafe_take<T>() -> Box<T> {
mem::transmute(RT_TLS_PTR)
}
/// Check whether there is a thread-local pointer installed.
#[inline(never)] // see comments above
pub fn exists() -> bool {
unsafe {
RT_TLS_PTR.is_not_null()
}
}
#[inline(never)] // see comments above
pub unsafe fn unsafe_borrow<T>() -> *mut T {
if RT_TLS_PTR.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
RT_TLS_PTR as *mut T
}
#[inline(never)] // see comments above
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
if RT_TLS_PTR.is_null() {
None
} else {
Some(RT_TLS_PTR as *mut T)
}
}
}
/// Native implementation of having the runtime thread-local pointer. This
/// implementation uses the `thread_local_storage` module to provide a
/// thread-local value.
pub mod native {
use core::prelude::*;
use alloc::boxed::Box;
use core::mem;
use core::ptr;
use tls = thread_local_storage;
static mut RT_TLS_KEY: tls::Key = -1;
/// Initialize the TLS key. Other ops will fail if this isn't executed
/// first.
pub fn init() {
unsafe {
tls::create(&mut RT_TLS_KEY);
}
}
pub unsafe fn cleanup() {
rtassert!(RT_TLS_KEY!= -1);
tls::destroy(RT_TLS_KEY);
}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: Box<T>) {
let key = tls_key();
let void_ptr: *mut u8 = mem::transmute(sched);
tls::set(key, void_ptr);
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> Box<T> {
let key = tls_key();
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: Box<T> = mem::transmute(void_ptr);
tls::set(key, ptr::mut_null());
return ptr;
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn try_take<T>() -> Option<Box<T>> {
match maybe_tls_key() {
Some(key) => {
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
None
} else {
let ptr: Box<T> = mem::transmute(void_ptr);
tls::set(key, ptr::mut_null());
Some(ptr)
}
}
None => None
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline]
pub unsafe fn unsafe_take<T>() -> Box<T> {
let key = tls_key();
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: Box<T> = mem::transmute(void_ptr);
return ptr;
}
/// Check whether there is a thread-local pointer installed.
pub fn exists() -> bool {
unsafe {
match maybe_tls_key() {
Some(key) => tls::get(key).is_not_null(),
None => false
}
}
}
/// Borrow a mutable reference to the thread-local value
///
/// # Safety Note
///
/// Because this leaves the value in thread-local storage it is possible
/// For the Scheduler pointer to be aliased
pub unsafe fn unsafe_borrow<T>() -> *mut T {
let key = tls_key();
let void_ptr = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
void_ptr as *mut T
}
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr = tls::get(key);
if void_ptr.is_null()
|
else {
Some(void_ptr as *mut T)
}
}
None => None
}
}
#[inline]
fn tls_key() -> tls::Key {
match maybe_tls_key() {
Some(key) => key,
None => rtabort!("runtime tls key not initialized")
}
}
#[inline]
#[cfg(not(test))]
#[allow(visible_private_types)]
pub fn maybe_tls_key() -> Option<tls::Key> {
unsafe {
// NB: This is a little racy because, while the key is
// initialized under a mutex and it's assumed to be initialized
// in the Scheduler ctor by any thread that needs to use it,
// we are not accessing the key under a mutex. Threads that
// are not using the new Scheduler but still *want to check*
// whether they are running under a new Scheduler may see a 0
// value here that is in the process of being initialized in
// another thread. I think this is fine since the only action
// they could take if it was initialized would be to check the
// thread-local value and see that it's not set.
if RT_TLS_KEY!= -1 {
return Some(RT_TLS_KEY);
} else {
return None;
}
}
}
#[inline] #[cfg(test)]
pub fn maybe_tls_key() -> Option<tls::Key> {
use realrustrt;
unsafe {
mem::transmute(realrustrt::shouldnt_be_public::maybe_tls_key())
}
}
}
|
{
None
}
|
conditional_block
|
local_ptr.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.
//! Access to a single thread-local pointer.
//!
//! The runtime will use this for storing Box<Task>.
//!
//! FIXME: Add runtime checks for usage of inconsistent pointer types.
//! and for overwriting an existing pointer.
#![allow(dead_code)]
use core::prelude::*;
use core::mem;
use alloc::boxed::Box;
#[cfg(windows)] // mingw-w32 doesn't like thread_local things
#[cfg(target_os = "android")] // see #10686
#[cfg(target_os = "ios")]
pub use self::native::{init, cleanup, put, take, try_take, unsafe_take, exists,
unsafe_borrow, try_unsafe_borrow};
#[cfg(not(windows), not(target_os = "android"), not(target_os = "ios"))]
pub use self::compiled::{init, cleanup, put, take, try_take, unsafe_take, exists,
unsafe_borrow, try_unsafe_borrow};
/// Encapsulates a borrowed value. When this value goes out of scope, the
/// pointer is returned.
pub struct Borrowed<T> {
val: *const (),
}
#[unsafe_destructor]
impl<T> Drop for Borrowed<T> {
fn drop(&mut self) {
unsafe {
if self.val.is_null() {
rtabort!("Aiee, returning null borrowed object!");
}
let val: Box<T> = mem::transmute(self.val);
put::<T>(val);
rtassert!(exists());
}
}
}
impl<T> Deref<T> for Borrowed<T> {
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*(self.val as *const T) }
}
}
impl<T> DerefMut<T> for Borrowed<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *(self.val as *mut T) }
}
}
/// Borrow the thread-local value from thread-local storage.
/// While the value is borrowed it is not available in TLS.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn
|
<T>() -> Borrowed<T> {
let val: *const () = mem::transmute(take::<T>());
Borrowed {
val: val,
}
}
/// Compiled implementation of accessing the runtime local pointer. This is
/// implemented using LLVM's thread_local attribute which isn't necessarily
/// working on all platforms. This implementation is faster, however, so we use
/// it wherever possible.
#[cfg(not(windows), not(target_os = "android"), not(target_os = "ios"))]
pub mod compiled {
use core::prelude::*;
use alloc::boxed::Box;
use core::mem;
#[cfg(test)]
pub use realrustrt::shouldnt_be_public::RT_TLS_PTR;
#[cfg(not(test))]
#[thread_local]
pub static mut RT_TLS_PTR: *mut u8 = 0 as *mut u8;
pub fn init() {}
pub unsafe fn cleanup() {}
// Rationale for all of these functions being inline(never)
//
// The #[thread_local] annotation gets propagated all the way through to
// LLVM, meaning the global is specially treated by LLVM to lower it to an
// efficient sequence of instructions. This also involves dealing with fun
// stuff in object files and whatnot. Regardless, it turns out this causes
// trouble with green threads and lots of optimizations turned on. The
// following case study was done on linux x86_64, but I would imagine that
// other platforms are similar.
//
// On linux, the instruction sequence for loading the tls pointer global
// looks like:
//
// mov %fs:0x0, %rax
// mov -0x8(%rax), %rbx
//
// This code leads me to believe that (%fs:0x0) is a table, and then the
// table contains the TLS values for the process. Hence, the slot at offset
// -0x8 is the task TLS pointer. This leads us to the conclusion that this
// table is the actual thread local part of each thread. The kernel sets up
// the fs segment selector to point at the right region of memory for each
// thread.
//
// Optimizations lead me to believe that this code is lowered to these
// instructions in the LLVM codegen passes, because you'll see code like
// this when everything is optimized:
//
// mov %fs:0x0, %r14
// mov -0x8(%r14), %rbx
// // do something with %rbx, the rust Task pointer
//
// ... // <- do more things
//
// mov -0x8(%r14), %rbx
// // do something else with %rbx
//
// Note that the optimization done here is that the first load is not
// duplicated during the lower instructions. This means that the %fs:0x0
// memory location is only dereferenced once.
//
// Normally, this is actually a good thing! With green threads, however,
// it's very possible for the code labeled "do more things" to context
// switch to another thread. If this happens, then we *must* re-load %fs:0x0
// because it's changed (we're on a different thread). If we don't re-load
// the table location, then we'll be reading the original thread's TLS
// values, not our thread's TLS values.
//
// Hence, we never inline these functions. By never inlining, we're
// guaranteed that loading the table is a local decision which is forced to
// *always* happen.
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline(never)] // see comments above
pub unsafe fn put<T>(sched: Box<T>) {
RT_TLS_PTR = mem::transmute(sched)
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline(never)] // see comments above
pub unsafe fn take<T>() -> Box<T> {
let ptr = RT_TLS_PTR;
rtassert!(!ptr.is_null());
let ptr: Box<T> = mem::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = mem::transmute(0u);
ptr
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline(never)] // see comments above
pub unsafe fn try_take<T>() -> Option<Box<T>> {
let ptr = RT_TLS_PTR;
if ptr.is_null() {
None
} else {
let ptr: Box<T> = mem::transmute(ptr);
// can't use `as`, due to type not matching with `cfg(test)`
RT_TLS_PTR = mem::transmute(0u);
Some(ptr)
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline(never)] // see comments above
pub unsafe fn unsafe_take<T>() -> Box<T> {
mem::transmute(RT_TLS_PTR)
}
/// Check whether there is a thread-local pointer installed.
#[inline(never)] // see comments above
pub fn exists() -> bool {
unsafe {
RT_TLS_PTR.is_not_null()
}
}
#[inline(never)] // see comments above
pub unsafe fn unsafe_borrow<T>() -> *mut T {
if RT_TLS_PTR.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
RT_TLS_PTR as *mut T
}
#[inline(never)] // see comments above
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
if RT_TLS_PTR.is_null() {
None
} else {
Some(RT_TLS_PTR as *mut T)
}
}
}
/// Native implementation of having the runtime thread-local pointer. This
/// implementation uses the `thread_local_storage` module to provide a
/// thread-local value.
pub mod native {
use core::prelude::*;
use alloc::boxed::Box;
use core::mem;
use core::ptr;
use tls = thread_local_storage;
static mut RT_TLS_KEY: tls::Key = -1;
/// Initialize the TLS key. Other ops will fail if this isn't executed
/// first.
pub fn init() {
unsafe {
tls::create(&mut RT_TLS_KEY);
}
}
pub unsafe fn cleanup() {
rtassert!(RT_TLS_KEY!= -1);
tls::destroy(RT_TLS_KEY);
}
/// Give a pointer to thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn put<T>(sched: Box<T>) {
let key = tls_key();
let void_ptr: *mut u8 = mem::transmute(sched);
tls::set(key, void_ptr);
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn take<T>() -> Box<T> {
let key = tls_key();
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: Box<T> = mem::transmute(void_ptr);
tls::set(key, ptr::mut_null());
return ptr;
}
/// Optionally take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
#[inline]
pub unsafe fn try_take<T>() -> Option<Box<T>> {
match maybe_tls_key() {
Some(key) => {
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
None
} else {
let ptr: Box<T> = mem::transmute(void_ptr);
tls::set(key, ptr::mut_null());
Some(ptr)
}
}
None => None
}
}
/// Take ownership of a pointer from thread-local storage.
///
/// # Safety note
///
/// Does not validate the pointer type.
/// Leaves the old pointer in TLS for speed.
#[inline]
pub unsafe fn unsafe_take<T>() -> Box<T> {
let key = tls_key();
let void_ptr: *mut u8 = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
let ptr: Box<T> = mem::transmute(void_ptr);
return ptr;
}
/// Check whether there is a thread-local pointer installed.
pub fn exists() -> bool {
unsafe {
match maybe_tls_key() {
Some(key) => tls::get(key).is_not_null(),
None => false
}
}
}
/// Borrow a mutable reference to the thread-local value
///
/// # Safety Note
///
/// Because this leaves the value in thread-local storage it is possible
/// For the Scheduler pointer to be aliased
pub unsafe fn unsafe_borrow<T>() -> *mut T {
let key = tls_key();
let void_ptr = tls::get(key);
if void_ptr.is_null() {
rtabort!("thread-local pointer is null. bogus!");
}
void_ptr as *mut T
}
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr = tls::get(key);
if void_ptr.is_null() {
None
} else {
Some(void_ptr as *mut T)
}
}
None => None
}
}
#[inline]
fn tls_key() -> tls::Key {
match maybe_tls_key() {
Some(key) => key,
None => rtabort!("runtime tls key not initialized")
}
}
#[inline]
#[cfg(not(test))]
#[allow(visible_private_types)]
pub fn maybe_tls_key() -> Option<tls::Key> {
unsafe {
// NB: This is a little racy because, while the key is
// initialized under a mutex and it's assumed to be initialized
// in the Scheduler ctor by any thread that needs to use it,
// we are not accessing the key under a mutex. Threads that
// are not using the new Scheduler but still *want to check*
// whether they are running under a new Scheduler may see a 0
// value here that is in the process of being initialized in
// another thread. I think this is fine since the only action
// they could take if it was initialized would be to check the
// thread-local value and see that it's not set.
if RT_TLS_KEY!= -1 {
return Some(RT_TLS_KEY);
} else {
return None;
}
}
}
#[inline] #[cfg(test)]
pub fn maybe_tls_key() -> Option<tls::Key> {
use realrustrt;
unsafe {
mem::transmute(realrustrt::shouldnt_be_public::maybe_tls_key())
}
}
}
|
borrow
|
identifier_name
|
gather_moves.rs
|
// Copyright 2012-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.
/*!
* Computes moves.
*/
use mc = middle::mem_categorization;
use middle::borrowck::*;
use middle::borrowck::move_data::*;
use middle::moves;
use middle::ty;
use syntax::ast;
use syntax::ast_util;
use syntax::codemap::Span;
use util::ppaux::{UserString};
pub fn gather_decl(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
decl_id: ast::NodeId,
_decl_span: Span,
var_id: ast::NodeId) {
let loan_path = @LpVar(var_id);
move_data.add_move(bccx.tcx, loan_path, decl_id, Declared);
}
pub fn gather_move_from_expr(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
move_expr: @ast::Expr,
cmt: mc::cmt) {
gather_move_from_expr_or_pat(bccx, move_data, move_expr.id,
MoveExpr(move_expr), cmt);
}
pub fn gather_move_from_pat(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
move_pat: @ast::Pat,
cmt: mc::cmt) {
gather_move_from_expr_or_pat(bccx, move_data, move_pat.id,
MovePat(move_pat), cmt);
}
fn gather_move_from_expr_or_pat(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
move_id: ast::NodeId,
move_kind: MoveKind,
cmt: mc::cmt) {
if!check_is_legal_to_move_from(bccx, cmt, cmt) {
return;
}
match opt_loan_path(cmt) {
Some(loan_path) => {
move_data.add_move(bccx.tcx, loan_path, move_id, move_kind);
}
None => {
// move from rvalue or unsafe pointer, hence ok
}
}
}
pub fn gather_captures(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
closure_expr: @ast::Expr) {
let captured_vars = bccx.capture_map.get(&closure_expr.id);
for captured_var in captured_vars.iter() {
match captured_var.mode {
moves::CapMove => {
let fvar_id = ast_util::def_id_of_def(captured_var.def).node;
let loan_path = @LpVar(fvar_id);
move_data.add_move(bccx.tcx, loan_path, closure_expr.id,
Captured(closure_expr));
}
moves::CapCopy | moves::CapRef => {}
}
}
}
pub fn
|
(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
assignment_id: ast::NodeId,
assignment_span: Span,
assignee_loan_path: @LoanPath,
assignee_id: ast::NodeId) {
move_data.add_assignment(bccx.tcx,
assignee_loan_path,
assignment_id,
assignment_span,
assignee_id);
}
fn check_is_legal_to_move_from(bccx: &BorrowckCtxt,
cmt0: mc::cmt,
cmt: mc::cmt) -> bool {
match cmt.cat {
mc::cat_deref(_, _, mc::region_ptr(*)) |
mc::cat_deref(_, _, mc::gc_ptr(*)) |
mc::cat_deref(_, _, mc::unsafe_ptr(*)) |
mc::cat_stack_upvar(*) |
mc::cat_copied_upvar(mc::CopiedUpvar { onceness: ast::Many, _ }) => {
bccx.span_err(
cmt0.span,
format!("cannot move out of {}",
bccx.cmt_to_str(cmt)));
false
}
// Can move out of captured upvars only if the destination closure
// type is 'once'. 1-shot stack closures emit the copied_upvar form
// (see mem_categorization.rs).
mc::cat_copied_upvar(mc::CopiedUpvar { onceness: ast::Once, _ }) => {
true
}
// It seems strange to allow a move out of a static item,
// but what happens in practice is that you have a
// reference to a constant with a type that should be
// moved, like `None::<~int>`. The type of this constant
// is technically `Option<~int>`, which moves, but we know
// that the content of static items will never actually
// contain allocated pointers, so we can just memcpy it.
// Since static items can never have allocated memory,
// this is ok. For now anyhow.
mc::cat_static_item => {
true
}
mc::cat_rvalue(*) |
mc::cat_local(*) |
mc::cat_arg(*) |
mc::cat_self(*) => {
true
}
mc::cat_downcast(b) |
mc::cat_interior(b, _) => {
match ty::get(b.ty).sty {
ty::ty_struct(did, _) | ty::ty_enum(did, _) => {
if ty::has_dtor(bccx.tcx, did) {
bccx.span_err(
cmt0.span,
format!("cannot move out of type `{}`, \
which defines the `Drop` trait",
b.ty.user_string(bccx.tcx)));
false
} else {
check_is_legal_to_move_from(bccx, cmt0, b)
}
}
_ => {
check_is_legal_to_move_from(bccx, cmt0, b)
}
}
}
mc::cat_deref(b, _, mc::uniq_ptr) |
mc::cat_discr(b, _) => {
check_is_legal_to_move_from(bccx, cmt0, b)
}
}
}
|
gather_assignment
|
identifier_name
|
gather_moves.rs
|
// Copyright 2012-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.
/*!
* Computes moves.
*/
use mc = middle::mem_categorization;
use middle::borrowck::*;
use middle::borrowck::move_data::*;
use middle::moves;
use middle::ty;
use syntax::ast;
use syntax::ast_util;
use syntax::codemap::Span;
use util::ppaux::{UserString};
pub fn gather_decl(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
decl_id: ast::NodeId,
_decl_span: Span,
var_id: ast::NodeId) {
let loan_path = @LpVar(var_id);
move_data.add_move(bccx.tcx, loan_path, decl_id, Declared);
}
pub fn gather_move_from_expr(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
move_expr: @ast::Expr,
cmt: mc::cmt) {
gather_move_from_expr_or_pat(bccx, move_data, move_expr.id,
MoveExpr(move_expr), cmt);
}
pub fn gather_move_from_pat(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
move_pat: @ast::Pat,
cmt: mc::cmt) {
gather_move_from_expr_or_pat(bccx, move_data, move_pat.id,
MovePat(move_pat), cmt);
}
fn gather_move_from_expr_or_pat(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
move_id: ast::NodeId,
move_kind: MoveKind,
cmt: mc::cmt) {
|
match opt_loan_path(cmt) {
Some(loan_path) => {
move_data.add_move(bccx.tcx, loan_path, move_id, move_kind);
}
None => {
// move from rvalue or unsafe pointer, hence ok
}
}
}
pub fn gather_captures(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
closure_expr: @ast::Expr) {
let captured_vars = bccx.capture_map.get(&closure_expr.id);
for captured_var in captured_vars.iter() {
match captured_var.mode {
moves::CapMove => {
let fvar_id = ast_util::def_id_of_def(captured_var.def).node;
let loan_path = @LpVar(fvar_id);
move_data.add_move(bccx.tcx, loan_path, closure_expr.id,
Captured(closure_expr));
}
moves::CapCopy | moves::CapRef => {}
}
}
}
pub fn gather_assignment(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
assignment_id: ast::NodeId,
assignment_span: Span,
assignee_loan_path: @LoanPath,
assignee_id: ast::NodeId) {
move_data.add_assignment(bccx.tcx,
assignee_loan_path,
assignment_id,
assignment_span,
assignee_id);
}
fn check_is_legal_to_move_from(bccx: &BorrowckCtxt,
cmt0: mc::cmt,
cmt: mc::cmt) -> bool {
match cmt.cat {
mc::cat_deref(_, _, mc::region_ptr(*)) |
mc::cat_deref(_, _, mc::gc_ptr(*)) |
mc::cat_deref(_, _, mc::unsafe_ptr(*)) |
mc::cat_stack_upvar(*) |
mc::cat_copied_upvar(mc::CopiedUpvar { onceness: ast::Many, _ }) => {
bccx.span_err(
cmt0.span,
format!("cannot move out of {}",
bccx.cmt_to_str(cmt)));
false
}
// Can move out of captured upvars only if the destination closure
// type is 'once'. 1-shot stack closures emit the copied_upvar form
// (see mem_categorization.rs).
mc::cat_copied_upvar(mc::CopiedUpvar { onceness: ast::Once, _ }) => {
true
}
// It seems strange to allow a move out of a static item,
// but what happens in practice is that you have a
// reference to a constant with a type that should be
// moved, like `None::<~int>`. The type of this constant
// is technically `Option<~int>`, which moves, but we know
// that the content of static items will never actually
// contain allocated pointers, so we can just memcpy it.
// Since static items can never have allocated memory,
// this is ok. For now anyhow.
mc::cat_static_item => {
true
}
mc::cat_rvalue(*) |
mc::cat_local(*) |
mc::cat_arg(*) |
mc::cat_self(*) => {
true
}
mc::cat_downcast(b) |
mc::cat_interior(b, _) => {
match ty::get(b.ty).sty {
ty::ty_struct(did, _) | ty::ty_enum(did, _) => {
if ty::has_dtor(bccx.tcx, did) {
bccx.span_err(
cmt0.span,
format!("cannot move out of type `{}`, \
which defines the `Drop` trait",
b.ty.user_string(bccx.tcx)));
false
} else {
check_is_legal_to_move_from(bccx, cmt0, b)
}
}
_ => {
check_is_legal_to_move_from(bccx, cmt0, b)
}
}
}
mc::cat_deref(b, _, mc::uniq_ptr) |
mc::cat_discr(b, _) => {
check_is_legal_to_move_from(bccx, cmt0, b)
}
}
}
|
if !check_is_legal_to_move_from(bccx, cmt, cmt) {
return;
}
|
random_line_split
|
gather_moves.rs
|
// Copyright 2012-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.
/*!
* Computes moves.
*/
use mc = middle::mem_categorization;
use middle::borrowck::*;
use middle::borrowck::move_data::*;
use middle::moves;
use middle::ty;
use syntax::ast;
use syntax::ast_util;
use syntax::codemap::Span;
use util::ppaux::{UserString};
pub fn gather_decl(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
decl_id: ast::NodeId,
_decl_span: Span,
var_id: ast::NodeId) {
let loan_path = @LpVar(var_id);
move_data.add_move(bccx.tcx, loan_path, decl_id, Declared);
}
pub fn gather_move_from_expr(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
move_expr: @ast::Expr,
cmt: mc::cmt)
|
pub fn gather_move_from_pat(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
move_pat: @ast::Pat,
cmt: mc::cmt) {
gather_move_from_expr_or_pat(bccx, move_data, move_pat.id,
MovePat(move_pat), cmt);
}
fn gather_move_from_expr_or_pat(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
move_id: ast::NodeId,
move_kind: MoveKind,
cmt: mc::cmt) {
if!check_is_legal_to_move_from(bccx, cmt, cmt) {
return;
}
match opt_loan_path(cmt) {
Some(loan_path) => {
move_data.add_move(bccx.tcx, loan_path, move_id, move_kind);
}
None => {
// move from rvalue or unsafe pointer, hence ok
}
}
}
pub fn gather_captures(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
closure_expr: @ast::Expr) {
let captured_vars = bccx.capture_map.get(&closure_expr.id);
for captured_var in captured_vars.iter() {
match captured_var.mode {
moves::CapMove => {
let fvar_id = ast_util::def_id_of_def(captured_var.def).node;
let loan_path = @LpVar(fvar_id);
move_data.add_move(bccx.tcx, loan_path, closure_expr.id,
Captured(closure_expr));
}
moves::CapCopy | moves::CapRef => {}
}
}
}
pub fn gather_assignment(bccx: &BorrowckCtxt,
move_data: &mut MoveData,
assignment_id: ast::NodeId,
assignment_span: Span,
assignee_loan_path: @LoanPath,
assignee_id: ast::NodeId) {
move_data.add_assignment(bccx.tcx,
assignee_loan_path,
assignment_id,
assignment_span,
assignee_id);
}
fn check_is_legal_to_move_from(bccx: &BorrowckCtxt,
cmt0: mc::cmt,
cmt: mc::cmt) -> bool {
match cmt.cat {
mc::cat_deref(_, _, mc::region_ptr(*)) |
mc::cat_deref(_, _, mc::gc_ptr(*)) |
mc::cat_deref(_, _, mc::unsafe_ptr(*)) |
mc::cat_stack_upvar(*) |
mc::cat_copied_upvar(mc::CopiedUpvar { onceness: ast::Many, _ }) => {
bccx.span_err(
cmt0.span,
format!("cannot move out of {}",
bccx.cmt_to_str(cmt)));
false
}
// Can move out of captured upvars only if the destination closure
// type is 'once'. 1-shot stack closures emit the copied_upvar form
// (see mem_categorization.rs).
mc::cat_copied_upvar(mc::CopiedUpvar { onceness: ast::Once, _ }) => {
true
}
// It seems strange to allow a move out of a static item,
// but what happens in practice is that you have a
// reference to a constant with a type that should be
// moved, like `None::<~int>`. The type of this constant
// is technically `Option<~int>`, which moves, but we know
// that the content of static items will never actually
// contain allocated pointers, so we can just memcpy it.
// Since static items can never have allocated memory,
// this is ok. For now anyhow.
mc::cat_static_item => {
true
}
mc::cat_rvalue(*) |
mc::cat_local(*) |
mc::cat_arg(*) |
mc::cat_self(*) => {
true
}
mc::cat_downcast(b) |
mc::cat_interior(b, _) => {
match ty::get(b.ty).sty {
ty::ty_struct(did, _) | ty::ty_enum(did, _) => {
if ty::has_dtor(bccx.tcx, did) {
bccx.span_err(
cmt0.span,
format!("cannot move out of type `{}`, \
which defines the `Drop` trait",
b.ty.user_string(bccx.tcx)));
false
} else {
check_is_legal_to_move_from(bccx, cmt0, b)
}
}
_ => {
check_is_legal_to_move_from(bccx, cmt0, b)
}
}
}
mc::cat_deref(b, _, mc::uniq_ptr) |
mc::cat_discr(b, _) => {
check_is_legal_to_move_from(bccx, cmt0, b)
}
}
}
|
{
gather_move_from_expr_or_pat(bccx, move_data, move_expr.id,
MoveExpr(move_expr), cmt);
}
|
identifier_body
|
main.rs
|
// MIT License
//
// Copyright (c) 2017 Franziska Becker, René Warking
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Copyright (c) 2016 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
extern crate cgmath;
extern crate winit;
extern crate time;
#[macro_use]
extern crate vulkano;
extern crate vulkano_win;
use vulkano_win::VkSurfaceBuild;
use std::sync::Arc;
use std::time::Duration;
mod vs { include!{concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_vs.glsl")} }
mod fs { include!{concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_fs.glsl")} }
mod data;
mod model;
mod chess;
mod system;
mod graphics;
use model::Model;
use system::System;
use graphics::{GraphicsEngine, Matrices};
mod renderpass {
single_pass_renderpass!{
attachments: {
color: {
load: Clear,
store: Store,
format: ::vulkano::format::Format,
},
depth: {
load: Clear,
store: DontCare,
format: ::vulkano::format::D16Unorm,
}
},
pass: {
color: [color],
depth_stencil: {depth}
}
}
}
#[allow(dead_code)]
mod pipeline_layout {
pipeline_layout!{
set0: {
uniforms: UniformBuffer<::vs::ty::Data>
},
m_color: {
col: UniformBuffer<::vs::ty::FigureColor>
}
}
}
fn main() {
// Set up lots of stuff... see vulkano examples
let extensions = vulkano_win::required_extensions();
let instance = vulkano::instance::Instance::new(None, &extensions, None).expect("failed to create instance");
let physical = vulkano::instance::PhysicalDevice::enumerate(&instance)
.next().expect("no device available");
println!("Using device: {} (type: {:?})", physical.name(), physical.ty());
let window = winit::WindowBuilder::new().build_vk_surface(&instance).unwrap();
let queue = physical.queue_families().find(|q| q.supports_graphics() &&
window.surface().is_supported(q).unwrap_or(false))
.expect("couldn't find a graphical queue family");
let device_ext = vulkano::device::DeviceExtensions {
khr_swapchain: true,
.. vulkano::device::DeviceExtensions::none()
};
let (device, mut queues) = vulkano::device::Device::new(&physical, physical.supported_features(),
&device_ext, [(queue, 0.5)].iter().cloned())
.expect("failed to create device");
let queue = queues.next().unwrap();
let (swapchain, images) = {
let caps = window.surface().get_capabilities(&physical).expect("failed to get surface capabilities");
let dimensions = caps.current_extent.unwrap_or([1280, 1024]);
let present = caps.present_modes.iter().next().unwrap();
let usage = caps.supported_usage_flags;
let format = caps.supported_formats[0].0;
vulkano::swapchain::Swapchain::new(&device, &window.surface(), caps.min_image_count, format, dimensions, 1,
&usage, &queue, vulkano::swapchain::SurfaceTransform::Identity,
vulkano::swapchain::CompositeAlpha::Opaque,
present, true, None).expect("failed to create swapchain")
};
let depth_buffer = vulkano::image::attachment::AttachmentImage::transient(&device, images[0].dimensions(), vulkano::format::D16Unorm).unwrap();
let proj = cgmath::perspective(cgmath::Rad(std::f32::consts::FRAC_PI_2),
{ let d = images[0].dimensions(); d[0] as f32 / d[1] as f32 }, 0.01, 100.0);
let camera = cgmath::Point3::new(0.0, 5.5, 0.0);
let view = cgmath::Matrix4::look_at(camera, cgmath::Point3::new(0.0, 0.0, 0.0), cgmath::Vector3::new(0.0, 0.0, 1.0));
let uniform_buffer = vulkano::buffer::cpu_access::CpuAccessibleBuffer::<vs::ty::Data>
::from_data(&device, &vulkano::buffer::BufferUsage::all(), Some(queue.family()),
vs::ty::Data {
world : <cgmath::Matrix4<f32> as cgmath::SquareMatrix>::identity().into(),
view : view.into(),
proj : proj.into(),
camera: camera.into()
})
.expect("failed to create buffer");
let vs = vs::Shader::load(&device).expect("failed to create shader module");
let fs = fs::Shader::load(&device).expect("failed to create shader module");
let renderpass = renderpass::CustomRenderPass::new(&device, &renderpass::Formats {
color: (images[0].format(), 1),
depth: (vulkano::format::D16Unorm, 1),
}).unwrap();
let descriptor_pool = vulkano::descriptor::descriptor_set::DescriptorPool::new(&device);
let pipeline_layout = pipeline_layout::CustomPipeline::new(&device).unwrap();
let set = pipeline_layout::set0::Set::new(&descriptor_pool, &pipeline_layout, &pipeline_layout::set0::Descriptors {
uniforms: &uniform_buffer
});
let pipeline = vulkano::pipeline::GraphicsPipeline::new(&device, vulkano::pipeline::GraphicsPipelineParams {
vertex_input: vulkano::pipeline::vertex::TwoBuffersDefinition::new(),
vertex_shader: vs.main_entry_point(),
input_assembly: vulkano::pipeline::input_assembly::InputAssembly::triangle_list(),
tessellation: None,
geometry_shader: None,
viewport: vulkano::pipeline::viewport::ViewportsState::Fixed {
data: vec![(
vulkano::pipeline::viewport::Viewport {
origin: [0.0, 0.0],
depth_range: 0.0.. 1.0,
dimensions: [images[0].dimensions()[0] as f32, images[0].dimensions()[1] as f32],
},
vulkano::pipeline::viewport::Scissor::irrelevant()
)],
},
raster: Default::default(),
multisample: vulkano::pipeline::multisample::Multisample::disabled(),
fragment_shader: fs.main_entry_point(),
depth_stencil: vulkano::pipeline::depth_stencil::DepthStencil::simple_depth_test(),
blend: vulkano::pipeline::blend::Blend::pass_through(),
layout: &pipeline_layout,
render_pass: vulkano::framebuffer::Subpass::from(&renderpass, 0).unwrap(),
}).unwrap();
let framebuffers = images.iter().map(|image| {
let attachments = renderpass::AList {
color: &image,
depth: &depth_buffer,
};
vulkano::framebuffer::Framebuffer::new(&renderpass, [image.dimensions()[0], image.dimensions()[1], 1], attachments).unwrap()
}).collect::<Vec<_>>();
// Initialize chess fields and store their positions
let mut white_fields = Vec::new();
let mut black_fields = Vec::new();
let mut white_centers = Vec::new();
let mut black_centers = Vec::new();
for outer in 0..8 {
for i in 0..8 {
if (outer % 2 == 0 && i % 2 == 1) || (outer % 2 == 1 && i % 2 == 0) {
white_fields.push(Model::from_data(&data::FIELD_V, &data::FIELD_N, &data::FIELD_I));
white_fields.last_mut().unwrap().translate((i as f32 - 3.5, 0.0, outer as f32 - 3.5));
white_centers.push(cgmath::Point3{ x: i as f32 - 3.5,
y: 0.0,
z: outer as f32 - 3.5 });
} else {
black_fields.push(Model::from_data(&data::FIELD_V, &data::FIELD_N, &data::FIELD_I));
black_fields.last_mut().unwrap().translate((i as f32 - 3.5, 0.0, outer as f32 - 3.5));
black_centers.push(cgmath::Point3{ x: i as f32 - 3.5,
y: 0.0,
z: outer as f32 - 3.5 });
}
}
}
let mut submissions: Vec<Arc<vulkano::command_buffer::Submission>> = Vec::new();
// Construct graphics object
let mut graphics = GraphicsEngine{ device: device,
queue: queue,
swapchain: swapchain,
command_buffers: Arc::new(Vec::new()),
field_positions: Arc::new(Vec::new()),
uniform: Matrices {
world : <cgmath::Matrix4<f32> as cgmath::SquareMatrix>::identity(),
view : view,
proj : proj,
},
screenwidth: images[0].dimensions()[0],
screenheight: images[0].dimensions()[1],
white_figures: Arc::new(Vec::new()),
black_figures: Arc::new(Vec::new()),
camera: camera };
graphics.add_field_centers(white_centers);
graphics.add_field_centers(black_centers);
graphics.init_figures();
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
// Construct communicator between game and graphics
let mut system = System::new();
// Render loop
loop {
submissions.retain(|s| s.destroying_would_block());
let image_num = graphics.swapchain.acquire_next_image(Duration::from_millis(1)).unwrap();
for index in 0..graphics.command_buffers.len() {
submissions.push(vulkano::command_buffer::submit(&graphics.command_buffers[index][image_num], &graphics.queue).unwrap());
}
graphics.swapchain.present(&graphics.queue, image_num).unwrap();
// If there is an AI, let it make a move and update figures
if system.has_ai() {
if let Some(result) = system.execute_ai_turn() {
graphics.move_figure((result.0).0, (result.0).1, (result.0).2);
if result.1 {
graphics.delete_figure(!((result.0).0), (result.0).2);
}
if system.upgrade_needed() {
graphics.upgrade_pawn(system.upgrade().unwrap());
}
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
std::thread::sleep(std::time::Duration::from_millis(250));
}
}
// Window events
for ev in window.window().poll_events() {
match ev {
// Window was closed
winit::Event::Closed => return,
// Keyboard input
winit::Event::KeyboardInput(winit::ElementState::Pressed, _, Some(the_key)) => {
match the_key {
// On escape, reset the selection in system
winit::VirtualKeyCode::Escape => system.reset_selection(),
// Toggle black player AI
winit::VirtualKeyCode::Q => system.toggle_player_ai(false),
// Toggle white player AI
winit::VirtualKeyCode::W => system.toggle_player_ai(true),
// Set camera position and update view matrix
_ =>
if the_key == winit::VirtualKeyCode::Key1 || the_key == winit::VirtualKeyCode::Key2 {
let (cam, up) = {
if the_key == winit::VirtualKeyCode::Key1 {
|
else {
(cgmath::Point3::new(0.0, 5.5, 0.0), cgmath::Vector3::new(0.0, 0.0, 1.0))
}
};
graphics.set_camera_position(cam);
{
let mut buffer_content = uniform_buffer.write(Duration::new(1, 0)).unwrap();
buffer_content.view = cgmath::Matrix4::look_at(cam, cgmath::Point3::new(0.0, 0.0, 0.0), up).into();
buffer_content.camera = cam.into();
}
}
}
},
// Update mouse coordinates in System
winit::Event::MouseMoved(x, y) => system.set_mouse_coordinates(x, y),
// If a figure was selected, set position as selected in System
winit::Event::MouseInput(winit::ElementState::Pressed, winit::MouseButton::Left) => {
if let Some(selection) = graphics.get_field(system.mouse()) {
system.set_selected(selection);
// If two selections were made try to execute a turn and update graphics according to the turn
if let Some(result) = system.check_ready_and_play() {
graphics.move_figure((result.0).0, (result.0).1, (result.0).2);
if result.1 {
graphics.delete_figure(!((result.0).0), (result.0).2);
}
if system.upgrade_needed() {
graphics.upgrade_pawn(system.upgrade().unwrap());
}
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
}
}
},
_ => ()
}
}
}
}
|
(cgmath::Point3::new(4.0, 0.6, 0.0), cgmath::Vector3::new(0.0, -1.0, 0.0))
}
|
conditional_block
|
main.rs
|
// MIT License
//
// Copyright (c) 2017 Franziska Becker, René Warking
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Copyright (c) 2016 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
extern crate cgmath;
extern crate winit;
extern crate time;
#[macro_use]
extern crate vulkano;
extern crate vulkano_win;
use vulkano_win::VkSurfaceBuild;
use std::sync::Arc;
use std::time::Duration;
mod vs { include!{concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_vs.glsl")} }
mod fs { include!{concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_fs.glsl")} }
mod data;
mod model;
mod chess;
mod system;
mod graphics;
use model::Model;
use system::System;
use graphics::{GraphicsEngine, Matrices};
mod renderpass {
single_pass_renderpass!{
attachments: {
color: {
load: Clear,
store: Store,
format: ::vulkano::format::Format,
},
depth: {
load: Clear,
store: DontCare,
format: ::vulkano::format::D16Unorm,
}
},
pass: {
color: [color],
depth_stencil: {depth}
}
}
}
#[allow(dead_code)]
mod pipeline_layout {
pipeline_layout!{
set0: {
uniforms: UniformBuffer<::vs::ty::Data>
},
m_color: {
col: UniformBuffer<::vs::ty::FigureColor>
}
}
}
fn main() {
// Set up lots of stuff... see vulkano examples
let extensions = vulkano_win::required_extensions();
let instance = vulkano::instance::Instance::new(None, &extensions, None).expect("failed to create instance");
let physical = vulkano::instance::PhysicalDevice::enumerate(&instance)
.next().expect("no device available");
println!("Using device: {} (type: {:?})", physical.name(), physical.ty());
let window = winit::WindowBuilder::new().build_vk_surface(&instance).unwrap();
let queue = physical.queue_families().find(|q| q.supports_graphics() &&
window.surface().is_supported(q).unwrap_or(false))
.expect("couldn't find a graphical queue family");
let device_ext = vulkano::device::DeviceExtensions {
khr_swapchain: true,
.. vulkano::device::DeviceExtensions::none()
};
let (device, mut queues) = vulkano::device::Device::new(&physical, physical.supported_features(),
&device_ext, [(queue, 0.5)].iter().cloned())
.expect("failed to create device");
let queue = queues.next().unwrap();
let (swapchain, images) = {
let caps = window.surface().get_capabilities(&physical).expect("failed to get surface capabilities");
let dimensions = caps.current_extent.unwrap_or([1280, 1024]);
let present = caps.present_modes.iter().next().unwrap();
let usage = caps.supported_usage_flags;
let format = caps.supported_formats[0].0;
vulkano::swapchain::Swapchain::new(&device, &window.surface(), caps.min_image_count, format, dimensions, 1,
&usage, &queue, vulkano::swapchain::SurfaceTransform::Identity,
vulkano::swapchain::CompositeAlpha::Opaque,
present, true, None).expect("failed to create swapchain")
};
let depth_buffer = vulkano::image::attachment::AttachmentImage::transient(&device, images[0].dimensions(), vulkano::format::D16Unorm).unwrap();
let proj = cgmath::perspective(cgmath::Rad(std::f32::consts::FRAC_PI_2),
{ let d = images[0].dimensions(); d[0] as f32 / d[1] as f32 }, 0.01, 100.0);
let camera = cgmath::Point3::new(0.0, 5.5, 0.0);
let view = cgmath::Matrix4::look_at(camera, cgmath::Point3::new(0.0, 0.0, 0.0), cgmath::Vector3::new(0.0, 0.0, 1.0));
let uniform_buffer = vulkano::buffer::cpu_access::CpuAccessibleBuffer::<vs::ty::Data>
::from_data(&device, &vulkano::buffer::BufferUsage::all(), Some(queue.family()),
vs::ty::Data {
world : <cgmath::Matrix4<f32> as cgmath::SquareMatrix>::identity().into(),
view : view.into(),
proj : proj.into(),
camera: camera.into()
})
.expect("failed to create buffer");
let vs = vs::Shader::load(&device).expect("failed to create shader module");
let fs = fs::Shader::load(&device).expect("failed to create shader module");
let renderpass = renderpass::CustomRenderPass::new(&device, &renderpass::Formats {
color: (images[0].format(), 1),
depth: (vulkano::format::D16Unorm, 1),
}).unwrap();
let descriptor_pool = vulkano::descriptor::descriptor_set::DescriptorPool::new(&device);
let pipeline_layout = pipeline_layout::CustomPipeline::new(&device).unwrap();
let set = pipeline_layout::set0::Set::new(&descriptor_pool, &pipeline_layout, &pipeline_layout::set0::Descriptors {
uniforms: &uniform_buffer
});
let pipeline = vulkano::pipeline::GraphicsPipeline::new(&device, vulkano::pipeline::GraphicsPipelineParams {
vertex_input: vulkano::pipeline::vertex::TwoBuffersDefinition::new(),
vertex_shader: vs.main_entry_point(),
input_assembly: vulkano::pipeline::input_assembly::InputAssembly::triangle_list(),
tessellation: None,
geometry_shader: None,
viewport: vulkano::pipeline::viewport::ViewportsState::Fixed {
data: vec![(
vulkano::pipeline::viewport::Viewport {
origin: [0.0, 0.0],
depth_range: 0.0.. 1.0,
dimensions: [images[0].dimensions()[0] as f32, images[0].dimensions()[1] as f32],
},
vulkano::pipeline::viewport::Scissor::irrelevant()
)],
},
raster: Default::default(),
multisample: vulkano::pipeline::multisample::Multisample::disabled(),
fragment_shader: fs.main_entry_point(),
depth_stencil: vulkano::pipeline::depth_stencil::DepthStencil::simple_depth_test(),
blend: vulkano::pipeline::blend::Blend::pass_through(),
layout: &pipeline_layout,
render_pass: vulkano::framebuffer::Subpass::from(&renderpass, 0).unwrap(),
}).unwrap();
let framebuffers = images.iter().map(|image| {
let attachments = renderpass::AList {
color: &image,
depth: &depth_buffer,
};
vulkano::framebuffer::Framebuffer::new(&renderpass, [image.dimensions()[0], image.dimensions()[1], 1], attachments).unwrap()
}).collect::<Vec<_>>();
// Initialize chess fields and store their positions
let mut white_fields = Vec::new();
let mut black_fields = Vec::new();
let mut white_centers = Vec::new();
let mut black_centers = Vec::new();
for outer in 0..8 {
for i in 0..8 {
if (outer % 2 == 0 && i % 2 == 1) || (outer % 2 == 1 && i % 2 == 0) {
white_fields.push(Model::from_data(&data::FIELD_V, &data::FIELD_N, &data::FIELD_I));
white_fields.last_mut().unwrap().translate((i as f32 - 3.5, 0.0, outer as f32 - 3.5));
white_centers.push(cgmath::Point3{ x: i as f32 - 3.5,
y: 0.0,
z: outer as f32 - 3.5 });
} else {
black_fields.push(Model::from_data(&data::FIELD_V, &data::FIELD_N, &data::FIELD_I));
black_fields.last_mut().unwrap().translate((i as f32 - 3.5, 0.0, outer as f32 - 3.5));
black_centers.push(cgmath::Point3{ x: i as f32 - 3.5,
y: 0.0,
z: outer as f32 - 3.5 });
}
}
}
let mut submissions: Vec<Arc<vulkano::command_buffer::Submission>> = Vec::new();
// Construct graphics object
let mut graphics = GraphicsEngine{ device: device,
queue: queue,
swapchain: swapchain,
command_buffers: Arc::new(Vec::new()),
field_positions: Arc::new(Vec::new()),
uniform: Matrices {
world : <cgmath::Matrix4<f32> as cgmath::SquareMatrix>::identity(),
view : view,
proj : proj,
},
screenwidth: images[0].dimensions()[0],
screenheight: images[0].dimensions()[1],
white_figures: Arc::new(Vec::new()),
black_figures: Arc::new(Vec::new()),
camera: camera };
graphics.add_field_centers(white_centers);
graphics.add_field_centers(black_centers);
graphics.init_figures();
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
// Construct communicator between game and graphics
let mut system = System::new();
// Render loop
loop {
submissions.retain(|s| s.destroying_would_block());
let image_num = graphics.swapchain.acquire_next_image(Duration::from_millis(1)).unwrap();
for index in 0..graphics.command_buffers.len() {
submissions.push(vulkano::command_buffer::submit(&graphics.command_buffers[index][image_num], &graphics.queue).unwrap());
}
graphics.swapchain.present(&graphics.queue, image_num).unwrap();
// If there is an AI, let it make a move and update figures
if system.has_ai() {
if let Some(result) = system.execute_ai_turn() {
graphics.move_figure((result.0).0, (result.0).1, (result.0).2);
if result.1 {
graphics.delete_figure(!((result.0).0), (result.0).2);
}
if system.upgrade_needed() {
graphics.upgrade_pawn(system.upgrade().unwrap());
}
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
std::thread::sleep(std::time::Duration::from_millis(250));
}
}
// Window events
for ev in window.window().poll_events() {
match ev {
// Window was closed
winit::Event::Closed => return,
// Keyboard input
winit::Event::KeyboardInput(winit::ElementState::Pressed, _, Some(the_key)) => {
match the_key {
// On escape, reset the selection in system
winit::VirtualKeyCode::Escape => system.reset_selection(),
// Toggle black player AI
winit::VirtualKeyCode::Q => system.toggle_player_ai(false),
// Toggle white player AI
winit::VirtualKeyCode::W => system.toggle_player_ai(true),
// Set camera position and update view matrix
_ =>
if the_key == winit::VirtualKeyCode::Key1 || the_key == winit::VirtualKeyCode::Key2 {
let (cam, up) = {
if the_key == winit::VirtualKeyCode::Key1 {
(cgmath::Point3::new(4.0, 0.6, 0.0), cgmath::Vector3::new(0.0, -1.0, 0.0))
} else {
(cgmath::Point3::new(0.0, 5.5, 0.0), cgmath::Vector3::new(0.0, 0.0, 1.0))
}
};
graphics.set_camera_position(cam);
{
let mut buffer_content = uniform_buffer.write(Duration::new(1, 0)).unwrap();
buffer_content.view = cgmath::Matrix4::look_at(cam, cgmath::Point3::new(0.0, 0.0, 0.0), up).into();
buffer_content.camera = cam.into();
}
}
}
},
// Update mouse coordinates in System
winit::Event::MouseMoved(x, y) => system.set_mouse_coordinates(x, y),
// If a figure was selected, set position as selected in System
winit::Event::MouseInput(winit::ElementState::Pressed, winit::MouseButton::Left) => {
if let Some(selection) = graphics.get_field(system.mouse()) {
system.set_selected(selection);
// If two selections were made try to execute a turn and update graphics according to the turn
if let Some(result) = system.check_ready_and_play() {
graphics.move_figure((result.0).0, (result.0).1, (result.0).2);
if result.1 {
graphics.delete_figure(!((result.0).0), (result.0).2);
}
if system.upgrade_needed() {
graphics.upgrade_pawn(system.upgrade().unwrap());
}
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
}
}
},
_ => ()
}
}
}
}
|
// copies of the Software, and to permit persons to whom the Software is
|
random_line_split
|
main.rs
|
// MIT License
//
// Copyright (c) 2017 Franziska Becker, René Warking
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Copyright (c) 2016 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
extern crate cgmath;
extern crate winit;
extern crate time;
#[macro_use]
extern crate vulkano;
extern crate vulkano_win;
use vulkano_win::VkSurfaceBuild;
use std::sync::Arc;
use std::time::Duration;
mod vs { include!{concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_vs.glsl")} }
mod fs { include!{concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_fs.glsl")} }
mod data;
mod model;
mod chess;
mod system;
mod graphics;
use model::Model;
use system::System;
use graphics::{GraphicsEngine, Matrices};
mod renderpass {
single_pass_renderpass!{
attachments: {
color: {
load: Clear,
store: Store,
format: ::vulkano::format::Format,
},
depth: {
load: Clear,
store: DontCare,
format: ::vulkano::format::D16Unorm,
}
},
pass: {
color: [color],
depth_stencil: {depth}
}
}
}
#[allow(dead_code)]
mod pipeline_layout {
pipeline_layout!{
set0: {
uniforms: UniformBuffer<::vs::ty::Data>
},
m_color: {
col: UniformBuffer<::vs::ty::FigureColor>
}
}
}
fn main() {
|
let (device, mut queues) = vulkano::device::Device::new(&physical, physical.supported_features(),
&device_ext, [(queue, 0.5)].iter().cloned())
.expect("failed to create device");
let queue = queues.next().unwrap();
let (swapchain, images) = {
let caps = window.surface().get_capabilities(&physical).expect("failed to get surface capabilities");
let dimensions = caps.current_extent.unwrap_or([1280, 1024]);
let present = caps.present_modes.iter().next().unwrap();
let usage = caps.supported_usage_flags;
let format = caps.supported_formats[0].0;
vulkano::swapchain::Swapchain::new(&device, &window.surface(), caps.min_image_count, format, dimensions, 1,
&usage, &queue, vulkano::swapchain::SurfaceTransform::Identity,
vulkano::swapchain::CompositeAlpha::Opaque,
present, true, None).expect("failed to create swapchain")
};
let depth_buffer = vulkano::image::attachment::AttachmentImage::transient(&device, images[0].dimensions(), vulkano::format::D16Unorm).unwrap();
let proj = cgmath::perspective(cgmath::Rad(std::f32::consts::FRAC_PI_2),
{ let d = images[0].dimensions(); d[0] as f32 / d[1] as f32 }, 0.01, 100.0);
let camera = cgmath::Point3::new(0.0, 5.5, 0.0);
let view = cgmath::Matrix4::look_at(camera, cgmath::Point3::new(0.0, 0.0, 0.0), cgmath::Vector3::new(0.0, 0.0, 1.0));
let uniform_buffer = vulkano::buffer::cpu_access::CpuAccessibleBuffer::<vs::ty::Data>
::from_data(&device, &vulkano::buffer::BufferUsage::all(), Some(queue.family()),
vs::ty::Data {
world : <cgmath::Matrix4<f32> as cgmath::SquareMatrix>::identity().into(),
view : view.into(),
proj : proj.into(),
camera: camera.into()
})
.expect("failed to create buffer");
let vs = vs::Shader::load(&device).expect("failed to create shader module");
let fs = fs::Shader::load(&device).expect("failed to create shader module");
let renderpass = renderpass::CustomRenderPass::new(&device, &renderpass::Formats {
color: (images[0].format(), 1),
depth: (vulkano::format::D16Unorm, 1),
}).unwrap();
let descriptor_pool = vulkano::descriptor::descriptor_set::DescriptorPool::new(&device);
let pipeline_layout = pipeline_layout::CustomPipeline::new(&device).unwrap();
let set = pipeline_layout::set0::Set::new(&descriptor_pool, &pipeline_layout, &pipeline_layout::set0::Descriptors {
uniforms: &uniform_buffer
});
let pipeline = vulkano::pipeline::GraphicsPipeline::new(&device, vulkano::pipeline::GraphicsPipelineParams {
vertex_input: vulkano::pipeline::vertex::TwoBuffersDefinition::new(),
vertex_shader: vs.main_entry_point(),
input_assembly: vulkano::pipeline::input_assembly::InputAssembly::triangle_list(),
tessellation: None,
geometry_shader: None,
viewport: vulkano::pipeline::viewport::ViewportsState::Fixed {
data: vec![(
vulkano::pipeline::viewport::Viewport {
origin: [0.0, 0.0],
depth_range: 0.0.. 1.0,
dimensions: [images[0].dimensions()[0] as f32, images[0].dimensions()[1] as f32],
},
vulkano::pipeline::viewport::Scissor::irrelevant()
)],
},
raster: Default::default(),
multisample: vulkano::pipeline::multisample::Multisample::disabled(),
fragment_shader: fs.main_entry_point(),
depth_stencil: vulkano::pipeline::depth_stencil::DepthStencil::simple_depth_test(),
blend: vulkano::pipeline::blend::Blend::pass_through(),
layout: &pipeline_layout,
render_pass: vulkano::framebuffer::Subpass::from(&renderpass, 0).unwrap(),
}).unwrap();
let framebuffers = images.iter().map(|image| {
let attachments = renderpass::AList {
color: &image,
depth: &depth_buffer,
};
vulkano::framebuffer::Framebuffer::new(&renderpass, [image.dimensions()[0], image.dimensions()[1], 1], attachments).unwrap()
}).collect::<Vec<_>>();
// Initialize chess fields and store their positions
let mut white_fields = Vec::new();
let mut black_fields = Vec::new();
let mut white_centers = Vec::new();
let mut black_centers = Vec::new();
for outer in 0..8 {
for i in 0..8 {
if (outer % 2 == 0 && i % 2 == 1) || (outer % 2 == 1 && i % 2 == 0) {
white_fields.push(Model::from_data(&data::FIELD_V, &data::FIELD_N, &data::FIELD_I));
white_fields.last_mut().unwrap().translate((i as f32 - 3.5, 0.0, outer as f32 - 3.5));
white_centers.push(cgmath::Point3{ x: i as f32 - 3.5,
y: 0.0,
z: outer as f32 - 3.5 });
} else {
black_fields.push(Model::from_data(&data::FIELD_V, &data::FIELD_N, &data::FIELD_I));
black_fields.last_mut().unwrap().translate((i as f32 - 3.5, 0.0, outer as f32 - 3.5));
black_centers.push(cgmath::Point3{ x: i as f32 - 3.5,
y: 0.0,
z: outer as f32 - 3.5 });
}
}
}
let mut submissions: Vec<Arc<vulkano::command_buffer::Submission>> = Vec::new();
// Construct graphics object
let mut graphics = GraphicsEngine{ device: device,
queue: queue,
swapchain: swapchain,
command_buffers: Arc::new(Vec::new()),
field_positions: Arc::new(Vec::new()),
uniform: Matrices {
world : <cgmath::Matrix4<f32> as cgmath::SquareMatrix>::identity(),
view : view,
proj : proj,
},
screenwidth: images[0].dimensions()[0],
screenheight: images[0].dimensions()[1],
white_figures: Arc::new(Vec::new()),
black_figures: Arc::new(Vec::new()),
camera: camera };
graphics.add_field_centers(white_centers);
graphics.add_field_centers(black_centers);
graphics.init_figures();
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
// Construct communicator between game and graphics
let mut system = System::new();
// Render loop
loop {
submissions.retain(|s| s.destroying_would_block());
let image_num = graphics.swapchain.acquire_next_image(Duration::from_millis(1)).unwrap();
for index in 0..graphics.command_buffers.len() {
submissions.push(vulkano::command_buffer::submit(&graphics.command_buffers[index][image_num], &graphics.queue).unwrap());
}
graphics.swapchain.present(&graphics.queue, image_num).unwrap();
// If there is an AI, let it make a move and update figures
if system.has_ai() {
if let Some(result) = system.execute_ai_turn() {
graphics.move_figure((result.0).0, (result.0).1, (result.0).2);
if result.1 {
graphics.delete_figure(!((result.0).0), (result.0).2);
}
if system.upgrade_needed() {
graphics.upgrade_pawn(system.upgrade().unwrap());
}
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
std::thread::sleep(std::time::Duration::from_millis(250));
}
}
// Window events
for ev in window.window().poll_events() {
match ev {
// Window was closed
winit::Event::Closed => return,
// Keyboard input
winit::Event::KeyboardInput(winit::ElementState::Pressed, _, Some(the_key)) => {
match the_key {
// On escape, reset the selection in system
winit::VirtualKeyCode::Escape => system.reset_selection(),
// Toggle black player AI
winit::VirtualKeyCode::Q => system.toggle_player_ai(false),
// Toggle white player AI
winit::VirtualKeyCode::W => system.toggle_player_ai(true),
// Set camera position and update view matrix
_ =>
if the_key == winit::VirtualKeyCode::Key1 || the_key == winit::VirtualKeyCode::Key2 {
let (cam, up) = {
if the_key == winit::VirtualKeyCode::Key1 {
(cgmath::Point3::new(4.0, 0.6, 0.0), cgmath::Vector3::new(0.0, -1.0, 0.0))
} else {
(cgmath::Point3::new(0.0, 5.5, 0.0), cgmath::Vector3::new(0.0, 0.0, 1.0))
}
};
graphics.set_camera_position(cam);
{
let mut buffer_content = uniform_buffer.write(Duration::new(1, 0)).unwrap();
buffer_content.view = cgmath::Matrix4::look_at(cam, cgmath::Point3::new(0.0, 0.0, 0.0), up).into();
buffer_content.camera = cam.into();
}
}
}
},
// Update mouse coordinates in System
winit::Event::MouseMoved(x, y) => system.set_mouse_coordinates(x, y),
// If a figure was selected, set position as selected in System
winit::Event::MouseInput(winit::ElementState::Pressed, winit::MouseButton::Left) => {
if let Some(selection) = graphics.get_field(system.mouse()) {
system.set_selected(selection);
// If two selections were made try to execute a turn and update graphics according to the turn
if let Some(result) = system.check_ready_and_play() {
graphics.move_figure((result.0).0, (result.0).1, (result.0).2);
if result.1 {
graphics.delete_figure(!((result.0).0), (result.0).2);
}
if system.upgrade_needed() {
graphics.upgrade_pawn(system.upgrade().unwrap());
}
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
}
}
},
_ => ()
}
}
}
}
|
// Set up lots of stuff ... see vulkano examples
let extensions = vulkano_win::required_extensions();
let instance = vulkano::instance::Instance::new(None, &extensions, None).expect("failed to create instance");
let physical = vulkano::instance::PhysicalDevice::enumerate(&instance)
.next().expect("no device available");
println!("Using device: {} (type: {:?})", physical.name(), physical.ty());
let window = winit::WindowBuilder::new().build_vk_surface(&instance).unwrap();
let queue = physical.queue_families().find(|q| q.supports_graphics() &&
window.surface().is_supported(q).unwrap_or(false))
.expect("couldn't find a graphical queue family");
let device_ext = vulkano::device::DeviceExtensions {
khr_swapchain: true,
.. vulkano::device::DeviceExtensions::none()
};
|
identifier_body
|
main.rs
|
// MIT License
//
// Copyright (c) 2017 Franziska Becker, René Warking
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Copyright (c) 2016 The vulkano developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
extern crate cgmath;
extern crate winit;
extern crate time;
#[macro_use]
extern crate vulkano;
extern crate vulkano_win;
use vulkano_win::VkSurfaceBuild;
use std::sync::Arc;
use std::time::Duration;
mod vs { include!{concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_vs.glsl")} }
mod fs { include!{concat!(env!("OUT_DIR"), "/shaders/src/bin/chess_fs.glsl")} }
mod data;
mod model;
mod chess;
mod system;
mod graphics;
use model::Model;
use system::System;
use graphics::{GraphicsEngine, Matrices};
mod renderpass {
single_pass_renderpass!{
attachments: {
color: {
load: Clear,
store: Store,
format: ::vulkano::format::Format,
},
depth: {
load: Clear,
store: DontCare,
format: ::vulkano::format::D16Unorm,
}
},
pass: {
color: [color],
depth_stencil: {depth}
}
}
}
#[allow(dead_code)]
mod pipeline_layout {
pipeline_layout!{
set0: {
uniforms: UniformBuffer<::vs::ty::Data>
},
m_color: {
col: UniformBuffer<::vs::ty::FigureColor>
}
}
}
fn m
|
) {
// Set up lots of stuff... see vulkano examples
let extensions = vulkano_win::required_extensions();
let instance = vulkano::instance::Instance::new(None, &extensions, None).expect("failed to create instance");
let physical = vulkano::instance::PhysicalDevice::enumerate(&instance)
.next().expect("no device available");
println!("Using device: {} (type: {:?})", physical.name(), physical.ty());
let window = winit::WindowBuilder::new().build_vk_surface(&instance).unwrap();
let queue = physical.queue_families().find(|q| q.supports_graphics() &&
window.surface().is_supported(q).unwrap_or(false))
.expect("couldn't find a graphical queue family");
let device_ext = vulkano::device::DeviceExtensions {
khr_swapchain: true,
.. vulkano::device::DeviceExtensions::none()
};
let (device, mut queues) = vulkano::device::Device::new(&physical, physical.supported_features(),
&device_ext, [(queue, 0.5)].iter().cloned())
.expect("failed to create device");
let queue = queues.next().unwrap();
let (swapchain, images) = {
let caps = window.surface().get_capabilities(&physical).expect("failed to get surface capabilities");
let dimensions = caps.current_extent.unwrap_or([1280, 1024]);
let present = caps.present_modes.iter().next().unwrap();
let usage = caps.supported_usage_flags;
let format = caps.supported_formats[0].0;
vulkano::swapchain::Swapchain::new(&device, &window.surface(), caps.min_image_count, format, dimensions, 1,
&usage, &queue, vulkano::swapchain::SurfaceTransform::Identity,
vulkano::swapchain::CompositeAlpha::Opaque,
present, true, None).expect("failed to create swapchain")
};
let depth_buffer = vulkano::image::attachment::AttachmentImage::transient(&device, images[0].dimensions(), vulkano::format::D16Unorm).unwrap();
let proj = cgmath::perspective(cgmath::Rad(std::f32::consts::FRAC_PI_2),
{ let d = images[0].dimensions(); d[0] as f32 / d[1] as f32 }, 0.01, 100.0);
let camera = cgmath::Point3::new(0.0, 5.5, 0.0);
let view = cgmath::Matrix4::look_at(camera, cgmath::Point3::new(0.0, 0.0, 0.0), cgmath::Vector3::new(0.0, 0.0, 1.0));
let uniform_buffer = vulkano::buffer::cpu_access::CpuAccessibleBuffer::<vs::ty::Data>
::from_data(&device, &vulkano::buffer::BufferUsage::all(), Some(queue.family()),
vs::ty::Data {
world : <cgmath::Matrix4<f32> as cgmath::SquareMatrix>::identity().into(),
view : view.into(),
proj : proj.into(),
camera: camera.into()
})
.expect("failed to create buffer");
let vs = vs::Shader::load(&device).expect("failed to create shader module");
let fs = fs::Shader::load(&device).expect("failed to create shader module");
let renderpass = renderpass::CustomRenderPass::new(&device, &renderpass::Formats {
color: (images[0].format(), 1),
depth: (vulkano::format::D16Unorm, 1),
}).unwrap();
let descriptor_pool = vulkano::descriptor::descriptor_set::DescriptorPool::new(&device);
let pipeline_layout = pipeline_layout::CustomPipeline::new(&device).unwrap();
let set = pipeline_layout::set0::Set::new(&descriptor_pool, &pipeline_layout, &pipeline_layout::set0::Descriptors {
uniforms: &uniform_buffer
});
let pipeline = vulkano::pipeline::GraphicsPipeline::new(&device, vulkano::pipeline::GraphicsPipelineParams {
vertex_input: vulkano::pipeline::vertex::TwoBuffersDefinition::new(),
vertex_shader: vs.main_entry_point(),
input_assembly: vulkano::pipeline::input_assembly::InputAssembly::triangle_list(),
tessellation: None,
geometry_shader: None,
viewport: vulkano::pipeline::viewport::ViewportsState::Fixed {
data: vec![(
vulkano::pipeline::viewport::Viewport {
origin: [0.0, 0.0],
depth_range: 0.0.. 1.0,
dimensions: [images[0].dimensions()[0] as f32, images[0].dimensions()[1] as f32],
},
vulkano::pipeline::viewport::Scissor::irrelevant()
)],
},
raster: Default::default(),
multisample: vulkano::pipeline::multisample::Multisample::disabled(),
fragment_shader: fs.main_entry_point(),
depth_stencil: vulkano::pipeline::depth_stencil::DepthStencil::simple_depth_test(),
blend: vulkano::pipeline::blend::Blend::pass_through(),
layout: &pipeline_layout,
render_pass: vulkano::framebuffer::Subpass::from(&renderpass, 0).unwrap(),
}).unwrap();
let framebuffers = images.iter().map(|image| {
let attachments = renderpass::AList {
color: &image,
depth: &depth_buffer,
};
vulkano::framebuffer::Framebuffer::new(&renderpass, [image.dimensions()[0], image.dimensions()[1], 1], attachments).unwrap()
}).collect::<Vec<_>>();
// Initialize chess fields and store their positions
let mut white_fields = Vec::new();
let mut black_fields = Vec::new();
let mut white_centers = Vec::new();
let mut black_centers = Vec::new();
for outer in 0..8 {
for i in 0..8 {
if (outer % 2 == 0 && i % 2 == 1) || (outer % 2 == 1 && i % 2 == 0) {
white_fields.push(Model::from_data(&data::FIELD_V, &data::FIELD_N, &data::FIELD_I));
white_fields.last_mut().unwrap().translate((i as f32 - 3.5, 0.0, outer as f32 - 3.5));
white_centers.push(cgmath::Point3{ x: i as f32 - 3.5,
y: 0.0,
z: outer as f32 - 3.5 });
} else {
black_fields.push(Model::from_data(&data::FIELD_V, &data::FIELD_N, &data::FIELD_I));
black_fields.last_mut().unwrap().translate((i as f32 - 3.5, 0.0, outer as f32 - 3.5));
black_centers.push(cgmath::Point3{ x: i as f32 - 3.5,
y: 0.0,
z: outer as f32 - 3.5 });
}
}
}
let mut submissions: Vec<Arc<vulkano::command_buffer::Submission>> = Vec::new();
// Construct graphics object
let mut graphics = GraphicsEngine{ device: device,
queue: queue,
swapchain: swapchain,
command_buffers: Arc::new(Vec::new()),
field_positions: Arc::new(Vec::new()),
uniform: Matrices {
world : <cgmath::Matrix4<f32> as cgmath::SquareMatrix>::identity(),
view : view,
proj : proj,
},
screenwidth: images[0].dimensions()[0],
screenheight: images[0].dimensions()[1],
white_figures: Arc::new(Vec::new()),
black_figures: Arc::new(Vec::new()),
camera: camera };
graphics.add_field_centers(white_centers);
graphics.add_field_centers(black_centers);
graphics.init_figures();
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
// Construct communicator between game and graphics
let mut system = System::new();
// Render loop
loop {
submissions.retain(|s| s.destroying_would_block());
let image_num = graphics.swapchain.acquire_next_image(Duration::from_millis(1)).unwrap();
for index in 0..graphics.command_buffers.len() {
submissions.push(vulkano::command_buffer::submit(&graphics.command_buffers[index][image_num], &graphics.queue).unwrap());
}
graphics.swapchain.present(&graphics.queue, image_num).unwrap();
// If there is an AI, let it make a move and update figures
if system.has_ai() {
if let Some(result) = system.execute_ai_turn() {
graphics.move_figure((result.0).0, (result.0).1, (result.0).2);
if result.1 {
graphics.delete_figure(!((result.0).0), (result.0).2);
}
if system.upgrade_needed() {
graphics.upgrade_pawn(system.upgrade().unwrap());
}
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
std::thread::sleep(std::time::Duration::from_millis(250));
}
}
// Window events
for ev in window.window().poll_events() {
match ev {
// Window was closed
winit::Event::Closed => return,
// Keyboard input
winit::Event::KeyboardInput(winit::ElementState::Pressed, _, Some(the_key)) => {
match the_key {
// On escape, reset the selection in system
winit::VirtualKeyCode::Escape => system.reset_selection(),
// Toggle black player AI
winit::VirtualKeyCode::Q => system.toggle_player_ai(false),
// Toggle white player AI
winit::VirtualKeyCode::W => system.toggle_player_ai(true),
// Set camera position and update view matrix
_ =>
if the_key == winit::VirtualKeyCode::Key1 || the_key == winit::VirtualKeyCode::Key2 {
let (cam, up) = {
if the_key == winit::VirtualKeyCode::Key1 {
(cgmath::Point3::new(4.0, 0.6, 0.0), cgmath::Vector3::new(0.0, -1.0, 0.0))
} else {
(cgmath::Point3::new(0.0, 5.5, 0.0), cgmath::Vector3::new(0.0, 0.0, 1.0))
}
};
graphics.set_camera_position(cam);
{
let mut buffer_content = uniform_buffer.write(Duration::new(1, 0)).unwrap();
buffer_content.view = cgmath::Matrix4::look_at(cam, cgmath::Point3::new(0.0, 0.0, 0.0), up).into();
buffer_content.camera = cam.into();
}
}
}
},
// Update mouse coordinates in System
winit::Event::MouseMoved(x, y) => system.set_mouse_coordinates(x, y),
// If a figure was selected, set position as selected in System
winit::Event::MouseInput(winit::ElementState::Pressed, winit::MouseButton::Left) => {
if let Some(selection) = graphics.get_field(system.mouse()) {
system.set_selected(selection);
// If two selections were made try to execute a turn and update graphics according to the turn
if let Some(result) = system.check_ready_and_play() {
graphics.move_figure((result.0).0, (result.0).1, (result.0).2);
if result.1 {
graphics.delete_figure(!((result.0).0), (result.0).2);
}
if system.upgrade_needed() {
graphics.upgrade_pawn(system.upgrade().unwrap());
}
graphics.update_command_buffers(&white_fields, &black_fields, &pipeline, &set, &framebuffers, &renderpass);
}
}
},
_ => ()
}
}
}
}
|
ain(
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.