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 |
---|---|---|---|---|
buffer.rs
|
/*
gl/src/gl_wrapper/buffer.rs, 2017-07-19
Copyright (c) 2017 Juuso Tuononen
This file is licensed under
Apache License, Version 2.0
or
MIT License
*/
//! Send data to GPU.
use super::gl_raw;
use self::gl_raw::types::*;
use std::mem::size_of;
use std::os::raw::c_void;
use std::ptr;
/// Send static data to GPU with Vertex Buffer Object
struct VertexBufferStatic {
id: GLuint,
attribute_component_count: GLint,
}
impl VertexBufferStatic {
/// Sends static data to GPU.
///
/// # Arguments
/// * `data` - Float data which is sent to GPU.
/// * `attribute_component_count` - Number of floats in one vertex attribute.
///
/// # Safety
/// This function does not check if data length and `attribute_component_count` match.
unsafe fn new(data: &[f32], attribute_component_count: GLint) -> VertexBufferStatic {
let mut id: GLuint = 0;
gl_raw::GenBuffers(1, &mut id);
gl_raw::BindBuffer(gl_raw::ARRAY_BUFFER, id);
let size: GLsizeiptr = (size_of::<f32>() * data.len()) as GLsizeiptr;
let data_ptr = data.as_ptr() as *const c_void;
gl_raw::BufferData(gl_raw::ARRAY_BUFFER, size, data_ptr, gl_raw::STATIC_DRAW);
VertexBufferStatic {id, attribute_component_count}
}
/// Set vertex attribute to match buffer data.
///
/// # Arguments
/// * `attribute_index` - Index of vertex attribute.
fn set_vertex_attributes(&mut self, attribute_index: GLuint) {
unsafe {
gl_raw::BindBuffer(gl_raw::ARRAY_BUFFER, self.id);
let stride = (self.attribute_component_count * size_of::<f32>() as GLint) as GLsizei;
gl_raw::VertexAttribPointer(attribute_index, self.attribute_component_count, gl_raw::FLOAT, gl_raw::FALSE, stride, ptr::null());
gl_raw::EnableVertexAttribArray(attribute_index);
}
}
}
impl Drop for VertexBufferStatic {
/// Deletes OpenGL's buffer object.
|
}
}
/// Send multiple buffers of data to GPU.
///
/// OpenGL 3.3 version of this struct is implemented
/// with OpenGL's Vertex Array Object.
///
/// OpenGL ES 2.0 does not support Vertex Array Objects, so vertex
/// attributes are set for every buffer
/// when `draw` method is called if using OpenGL ES version of this struct.
#[cfg(not(feature = "gles"))]
pub struct VertexArray {
id: GLuint,
vertex_buffers: Vec<VertexBufferStatic>,
vertex_count: GLsizei,
}
#[cfg(feature = "gles")]
pub struct VertexArray {
vertex_buffers: Vec<(VertexBufferStatic, GLuint)>,
vertex_count: GLsizei,
}
impl VertexArray {
/// Creates new Vertex Array Object
#[cfg(not(feature = "gles"))]
pub fn new(vertex_count: GLsizei) -> VertexArray {
let mut id: GLuint = 0;
let vertex_buffers = vec![];
unsafe {
gl_raw::GenVertexArrays(1, &mut id);
VertexArray {id, vertex_buffers, vertex_count}
}
}
#[cfg(feature = "gles")]
pub fn new(vertex_count: GLsizei) -> VertexArray {
let vertex_buffers = vec![];
VertexArray {vertex_buffers, vertex_count}
}
/// Adds new buffer to Vertex Array Object
///
/// # Arguments
/// * `data` - Float data to send to the GPU.
/// * `attribute_component_count` - Number of floats in one attribute.
/// * `attribute_index` - Index of vertex attribute.
///
/// # Panics
/// * If buffer length doesn't match with `VertexArray`'s vertex count.
/// * If buffer length doesn't match with attribute_component_count.
pub fn add_static_buffer(&mut self, data: &[f32], attribute_component_count: GLint, attribute_index: GLuint) {
if data.len() / attribute_component_count as usize!= self.vertex_count as usize {
panic!("buffer length doesn't match with VertexArray's vertex count");
}
if data.len() % attribute_component_count as usize!= 0 {
panic!("buffer length doesn't match with attribute_component_count");
}
#[cfg(not(feature = "gles"))]
{
let mut buffer;
unsafe {
buffer = VertexBufferStatic::new(data, attribute_component_count);
}
self.bind();
buffer.set_vertex_attributes(attribute_index);
self.vertex_buffers.push(buffer);
}
#[cfg(feature = "gles")]
{
let buffer;
unsafe {
buffer = VertexBufferStatic::new(data, attribute_component_count);
}
self.vertex_buffers.push((buffer, attribute_index));
}
}
/// Bind OpenGL's Vertex Array Object. This method
/// only exists for OpenGL 3.3 version of `VertexArray` struct.
#[cfg(not(feature = "gles"))]
fn bind(&self) {
unsafe {
gl_raw::BindVertexArray(self.id);
}
}
/// Draw with buffers currently existing buffers in `VertexArray`. Remember to enable
/// correct shader `Program` with it's `use_program` method before calling this method.
pub fn draw(&mut self) {
#[cfg(not(feature = "gles"))]
{
self.bind();
}
#[cfg(feature = "gles")]
{
for &mut (ref mut buffer, attribute_index) in &mut self.vertex_buffers {
buffer.set_vertex_attributes(attribute_index);
}
}
unsafe {
gl_raw::DrawArrays(gl_raw::TRIANGLES, 0, self.vertex_count);
}
}
}
#[cfg(not(feature = "gles"))]
impl Drop for VertexArray {
/// Delete OpenGL's Vertex Array Object. This implementation of Drop trait
/// only exists for OpenGL 3.3 version of `VertexArray` struct.
fn drop(&mut self) {
unsafe {
gl_raw::DeleteVertexArrays(1, &self.id);
}
}
}
|
fn drop(&mut self) {
unsafe {
gl_raw::DeleteBuffers(1, &self.id);
}
|
random_line_split
|
player_score.rs
|
extern crate serialize;
use self::serialize::json;
use error;
use json_helpers::{find, get_float, get_i32, get_object, get_string};
// Public
#[deriving(Eq, PartialEq, Show)]
pub struct PlayerScore {
pub added_datetime: String,
pub owner_id: i32,
pub account_id: i32,
pub capital_ships: i32,
pub freighters: i32,
pub planets: i32,
pub starbases: i32,
pub military_score: i32,
pub inventory_score: i32,
pub priority_points: i32,
pub turn: i32,
pub percent: String,
pub id: i32,
}
pub fn build(json: &json::Json) -> Result<PlayerScore, error::Error>
|
try!(get_i32(try!(find(map, "inventoryscore")))),
priority_points:
try!(get_i32(try!(find(map, "prioritypoints")))),
turn:
try!(get_i32(try!(find(map, "turn")))),
percent:
try!(get_float(try!(find(map, "percent")), 2u)),
id:
try!(get_i32(try!(find(map, "id")))),
})
}
// Tests
#[cfg(test)]
mod tests {
use super::*;
use json_helpers::parse;
#[test]
fn test_build() {
let json = "{\
\"dateadded\": \"10/8/2014 5:10:54 PM\",\
\"ownerid\": 1,\
\"accountid\": 12345,\
\"capitalships\": 5,\
\"freighters\": 2,\
\"planets\": 11,\
\"starbases\": 1,\
\"militaryscore\": 10754,\
\"inventoryscore\": 282,\
\"prioritypoints\": 0,\
\"turn\": 7,\
\"percent\": 17.88,\
\"id\": 37,\
\"shipchange\": 1,\
\"freighterchange\": 0,\
\"planetchange\": 4,\
\"starbasechange\": 0,\
\"militarychange\": 1099,\
\"inventorychange\": 50,\
\"prioritypointchange\": 0,\
\"percentchange\": -0.73\
}";
let result = PlayerScore {
added_datetime: "10/8/2014 5:10:54 PM".to_string(),
owner_id: 1i32,
account_id: 12345i32,
capital_ships: 5i32,
freighters: 2i32,
planets: 11i32,
starbases: 1i32,
military_score: 10754i32,
inventory_score: 282i32,
priority_points: 0i32,
turn: 7i32,
percent: "17.88".to_string(),
id: 37i32,
};
assert_eq!(result, build(&parse(json).unwrap()).unwrap());
}
}
|
{
let map = try!(get_object(json));
Ok(PlayerScore {
added_datetime:
try!(get_string(try!(find(map, "dateadded")))),
owner_id:
try!(get_i32(try!(find(map, "ownerid")))),
account_id:
try!(get_i32(try!(find(map, "accountid")))),
capital_ships:
try!(get_i32(try!(find(map, "capitalships")))),
freighters:
try!(get_i32(try!(find(map, "freighters")))),
planets:
try!(get_i32(try!(find(map, "planets")))),
starbases:
try!(get_i32(try!(find(map, "starbases")))),
military_score:
try!(get_i32(try!(find(map, "militaryscore")))),
inventory_score:
|
identifier_body
|
player_score.rs
|
extern crate serialize;
use self::serialize::json;
use error;
use json_helpers::{find, get_float, get_i32, get_object, get_string};
// Public
#[deriving(Eq, PartialEq, Show)]
pub struct PlayerScore {
pub added_datetime: String,
pub owner_id: i32,
pub account_id: i32,
pub capital_ships: i32,
pub freighters: i32,
pub planets: i32,
pub starbases: i32,
pub military_score: i32,
pub inventory_score: i32,
pub priority_points: i32,
pub turn: i32,
pub percent: String,
pub id: i32,
}
pub fn
|
(json: &json::Json) -> Result<PlayerScore, error::Error> {
let map = try!(get_object(json));
Ok(PlayerScore {
added_datetime:
try!(get_string(try!(find(map, "dateadded")))),
owner_id:
try!(get_i32(try!(find(map, "ownerid")))),
account_id:
try!(get_i32(try!(find(map, "accountid")))),
capital_ships:
try!(get_i32(try!(find(map, "capitalships")))),
freighters:
try!(get_i32(try!(find(map, "freighters")))),
planets:
try!(get_i32(try!(find(map, "planets")))),
starbases:
try!(get_i32(try!(find(map, "starbases")))),
military_score:
try!(get_i32(try!(find(map, "militaryscore")))),
inventory_score:
try!(get_i32(try!(find(map, "inventoryscore")))),
priority_points:
try!(get_i32(try!(find(map, "prioritypoints")))),
turn:
try!(get_i32(try!(find(map, "turn")))),
percent:
try!(get_float(try!(find(map, "percent")), 2u)),
id:
try!(get_i32(try!(find(map, "id")))),
})
}
// Tests
#[cfg(test)]
mod tests {
use super::*;
use json_helpers::parse;
#[test]
fn test_build() {
let json = "{\
\"dateadded\": \"10/8/2014 5:10:54 PM\",\
\"ownerid\": 1,\
\"accountid\": 12345,\
\"capitalships\": 5,\
\"freighters\": 2,\
\"planets\": 11,\
\"starbases\": 1,\
\"militaryscore\": 10754,\
\"inventoryscore\": 282,\
\"prioritypoints\": 0,\
\"turn\": 7,\
\"percent\": 17.88,\
\"id\": 37,\
\"shipchange\": 1,\
\"freighterchange\": 0,\
\"planetchange\": 4,\
\"starbasechange\": 0,\
\"militarychange\": 1099,\
\"inventorychange\": 50,\
\"prioritypointchange\": 0,\
\"percentchange\": -0.73\
}";
let result = PlayerScore {
added_datetime: "10/8/2014 5:10:54 PM".to_string(),
owner_id: 1i32,
account_id: 12345i32,
capital_ships: 5i32,
freighters: 2i32,
planets: 11i32,
starbases: 1i32,
military_score: 10754i32,
inventory_score: 282i32,
priority_points: 0i32,
turn: 7i32,
percent: "17.88".to_string(),
id: 37i32,
};
assert_eq!(result, build(&parse(json).unwrap()).unwrap());
}
}
|
build
|
identifier_name
|
player_score.rs
|
extern crate serialize;
use self::serialize::json;
use error;
use json_helpers::{find, get_float, get_i32, get_object, get_string};
// Public
#[deriving(Eq, PartialEq, Show)]
pub struct PlayerScore {
pub added_datetime: String,
pub owner_id: i32,
pub account_id: i32,
pub capital_ships: i32,
pub freighters: i32,
pub planets: i32,
pub starbases: i32,
pub military_score: i32,
pub inventory_score: i32,
pub priority_points: i32,
pub turn: i32,
pub percent: String,
pub id: i32,
}
pub fn build(json: &json::Json) -> Result<PlayerScore, error::Error> {
let map = try!(get_object(json));
Ok(PlayerScore {
added_datetime:
try!(get_string(try!(find(map, "dateadded")))),
owner_id:
try!(get_i32(try!(find(map, "ownerid")))),
account_id:
try!(get_i32(try!(find(map, "accountid")))),
capital_ships:
try!(get_i32(try!(find(map, "capitalships")))),
freighters:
try!(get_i32(try!(find(map, "freighters")))),
planets:
try!(get_i32(try!(find(map, "planets")))),
starbases:
try!(get_i32(try!(find(map, "starbases")))),
military_score:
try!(get_i32(try!(find(map, "militaryscore")))),
inventory_score:
try!(get_i32(try!(find(map, "inventoryscore")))),
priority_points:
try!(get_i32(try!(find(map, "prioritypoints")))),
turn:
try!(get_i32(try!(find(map, "turn")))),
percent:
try!(get_float(try!(find(map, "percent")), 2u)),
id:
try!(get_i32(try!(find(map, "id")))),
})
}
// Tests
#[cfg(test)]
mod tests {
use super::*;
use json_helpers::parse;
#[test]
fn test_build() {
let json = "{\
\"dateadded\": \"10/8/2014 5:10:54 PM\",\
\"ownerid\": 1,\
\"accountid\": 12345,\
\"capitalships\": 5,\
\"freighters\": 2,\
\"planets\": 11,\
\"starbases\": 1,\
\"militaryscore\": 10754,\
\"inventoryscore\": 282,\
\"prioritypoints\": 0,\
\"turn\": 7,\
\"percent\": 17.88,\
\"id\": 37,\
|
\"shipchange\": 1,\
\"freighterchange\": 0,\
\"planetchange\": 4,\
\"starbasechange\": 0,\
\"militarychange\": 1099,\
\"inventorychange\": 50,\
\"prioritypointchange\": 0,\
\"percentchange\": -0.73\
}";
let result = PlayerScore {
added_datetime: "10/8/2014 5:10:54 PM".to_string(),
owner_id: 1i32,
account_id: 12345i32,
capital_ships: 5i32,
freighters: 2i32,
planets: 11i32,
starbases: 1i32,
military_score: 10754i32,
inventory_score: 282i32,
priority_points: 0i32,
turn: 7i32,
percent: "17.88".to_string(),
id: 37i32,
};
assert_eq!(result, build(&parse(json).unwrap()).unwrap());
}
}
|
random_line_split
|
|
main.rs
|
extern crate itertools;
extern crate num_traits;
extern crate smallvec;
extern crate rand;
pub mod board;
pub mod player;
use std::time::Duration;
use board::{Board, GameState};
use player::Player;
fn main() {
let mut b = Board::generate(10, 6);
let dur = Duration::new(5, 0);
let players: [Box<Player>; 2] = [
Box::new(player::HumanPlayer),
//Box::new(player::MCTSPlayer::new(dur)),
Box::new(player::MCTSPlayer::new(dur)),
];
println!("{}", b);
for p in players.iter().cycle() {
let m = p.choose(&b);
let r = b.make_legal_move(m);
println!("{}", b);
match r {
GameState::Ongoing => (),
GameState::Drawn =>
|
,
GameState::Won => {
println!("Won! ({})", b.active());
break;
},
}
}
}
|
{
println!("Drawn.");
break;
}
|
conditional_block
|
main.rs
|
extern crate itertools;
extern crate num_traits;
extern crate smallvec;
extern crate rand;
pub mod board;
pub mod player;
use std::time::Duration;
use board::{Board, GameState};
use player::Player;
fn main()
|
println!("Won! ({})", b.active());
break;
},
}
}
}
|
{
let mut b = Board::generate(10, 6);
let dur = Duration::new(5, 0);
let players: [Box<Player>; 2] = [
Box::new(player::HumanPlayer),
//Box::new(player::MCTSPlayer::new(dur)),
Box::new(player::MCTSPlayer::new(dur)),
];
println!("{}", b);
for p in players.iter().cycle() {
let m = p.choose(&b);
let r = b.make_legal_move(m);
println!("{}", b);
match r {
GameState::Ongoing => (),
GameState::Drawn => {
println!("Drawn.");
break;
},
GameState::Won => {
|
identifier_body
|
main.rs
|
extern crate itertools;
extern crate num_traits;
extern crate smallvec;
extern crate rand;
pub mod board;
pub mod player;
use std::time::Duration;
use board::{Board, GameState};
use player::Player;
fn main() {
let mut b = Board::generate(10, 6);
let dur = Duration::new(5, 0);
let players: [Box<Player>; 2] = [
Box::new(player::HumanPlayer),
//Box::new(player::MCTSPlayer::new(dur)),
Box::new(player::MCTSPlayer::new(dur)),
];
println!("{}", b);
for p in players.iter().cycle() {
let m = p.choose(&b);
let r = b.make_legal_move(m);
println!("{}", b);
match r {
GameState::Ongoing => (),
GameState::Drawn => {
println!("Drawn.");
break;
},
GameState::Won => {
println!("Won! ({})", b.active());
break;
},
}
|
}
}
|
random_line_split
|
|
main.rs
|
extern crate itertools;
extern crate num_traits;
extern crate smallvec;
extern crate rand;
pub mod board;
pub mod player;
use std::time::Duration;
use board::{Board, GameState};
use player::Player;
fn
|
() {
let mut b = Board::generate(10, 6);
let dur = Duration::new(5, 0);
let players: [Box<Player>; 2] = [
Box::new(player::HumanPlayer),
//Box::new(player::MCTSPlayer::new(dur)),
Box::new(player::MCTSPlayer::new(dur)),
];
println!("{}", b);
for p in players.iter().cycle() {
let m = p.choose(&b);
let r = b.make_legal_move(m);
println!("{}", b);
match r {
GameState::Ongoing => (),
GameState::Drawn => {
println!("Drawn.");
break;
},
GameState::Won => {
println!("Won! ({})", b.active());
break;
},
}
}
}
|
main
|
identifier_name
|
lib.rs
|
// =================================================================
//
// * WARNING *
//
// This file is generated!
//
// Changes made to this file will be overwritten. If changes are
// required to the generated code, the service_crategen project
// must be updated to generate the changes.
//
// =================================================================
#![doc(
html_logo_url = "https://raw.githubusercontent.com/rusoto/rusoto/master/assets/logo-square.png"
|
)]
//! <p>Amazon EMR is a web service that makes it easier to process large amounts of data efficiently. Amazon EMR uses Hadoop processing combined with several AWS services to do tasks such as web indexing, data mining, log file analysis, machine learning, scientific simulation, and data warehouse management.</p>
//!
//! If you're using the service, you're probably looking for [EmrClient](struct.EmrClient.html) and [Emr](trait.Emr.html).
mod custom;
mod generated;
pub use custom::*;
pub use generated::*;
|
random_line_split
|
|
mod.rs
|
//! System bindings for the Fortanix SGX platform
//!
//! This module contains the facade (aka platform-specific) implementations of
//! OS level functionality for Fortanix SGX.
#![deny(unsafe_op_in_unsafe_fn)]
use crate::io::ErrorKind;
use crate::os::raw::c_char;
use crate::sync::atomic::{AtomicBool, Ordering};
pub mod abi;
mod waitqueue;
pub mod alloc;
pub mod args;
#[path = "../unix/cmath.rs"]
pub mod cmath;
pub mod condvar;
pub mod env;
pub mod fd;
#[path = "../unsupported/fs.rs"]
pub mod fs;
#[path = "../unsupported/io.rs"]
pub mod io;
pub mod memchr;
pub mod mutex;
pub mod net;
pub mod os;
#[path = "../unix/os_str.rs"]
pub mod os_str;
pub mod path;
#[path = "../unsupported/pipe.rs"]
pub mod pipe;
#[path = "../unsupported/process.rs"]
pub mod process;
pub mod rwlock;
pub mod stdio;
pub mod thread;
pub mod thread_local_key;
pub mod time;
// SAFETY: must be called only once during runtime initialization.
// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
pub unsafe fn init(argc: isize, argv: *const *const u8) {
unsafe {
args::init(argc, argv);
}
}
// SAFETY: must be called only once during runtime cleanup.
// NOTE: this is not guaranteed to run, for example when the program aborts.
pub unsafe fn cleanup() {}
/// This function is used to implement functionality that simply doesn't exist.
/// Programs relying on this functionality will need to deal with the error.
pub fn unsupported<T>() -> crate::io::Result<T> {
Err(unsupported_err())
}
pub fn unsupported_err() -> crate::io::Error {
crate::io::Error::new_const(ErrorKind::Unsupported, &"operation not supported on SGX yet")
}
/// This function is used to implement various functions that doesn't exist,
/// but the lack of which might not be reason for error. If no error is
/// returned, the program might very well be able to function normally. This is
/// what happens when `SGX_INEFFECTIVE_ERROR` is set to `true`. If it is
/// `false`, the behavior is the same as `unsupported`.
pub fn sgx_ineffective<T>(v: T) -> crate::io::Result<T> {
static SGX_INEFFECTIVE_ERROR: AtomicBool = AtomicBool::new(false);
if SGX_INEFFECTIVE_ERROR.load(Ordering::Relaxed) {
Err(crate::io::Error::new_const(
ErrorKind::Uncategorized,
&"operation can't be trusted to have any effect on SGX",
))
} else {
Ok(v)
}
}
pub fn decode_error_kind(code: i32) -> ErrorKind {
use fortanix_sgx_abi::Error;
// FIXME: not sure how to make sure all variants of Error are covered
if code == Error::NotFound as _ {
ErrorKind::NotFound
} else if code == Error::PermissionDenied as _ {
ErrorKind::PermissionDenied
} else if code == Error::ConnectionRefused as _ {
ErrorKind::ConnectionRefused
} else if code == Error::ConnectionReset as _ {
ErrorKind::ConnectionReset
} else if code == Error::ConnectionAborted as _ {
ErrorKind::ConnectionAborted
} else if code == Error::NotConnected as _ {
ErrorKind::NotConnected
} else if code == Error::AddrInUse as _ {
ErrorKind::AddrInUse
} else if code == Error::AddrNotAvailable as _ {
ErrorKind::AddrNotAvailable
} else if code == Error::BrokenPipe as _ {
ErrorKind::BrokenPipe
} else if code == Error::AlreadyExists as _ {
ErrorKind::AlreadyExists
} else if code == Error::WouldBlock as _ {
ErrorKind::WouldBlock
} else if code == Error::InvalidInput as _ {
ErrorKind::InvalidInput
} else if code == Error::InvalidData as _ {
ErrorKind::InvalidData
} else if code == Error::TimedOut as _ {
ErrorKind::TimedOut
} else if code == Error::WriteZero as _ {
ErrorKind::WriteZero
} else if code == Error::Interrupted as _ {
ErrorKind::Interrupted
} else if code == Error::Other as _ {
ErrorKind::Uncategorized
} else if code == Error::UnexpectedEof as _ {
ErrorKind::UnexpectedEof
} else {
ErrorKind::Uncategorized
}
}
pub unsafe fn strlen(mut s: *const c_char) -> usize {
let mut n = 0;
while unsafe { *s }!= 0 {
n += 1;
s = unsafe { s.offset(1) };
}
return n;
}
pub fn abort_internal() ->! {
abi::usercalls::exit(true)
}
// This function is needed by the panic runtime. The symbol is named in
// pre-link args for the target specification, so keep that in sync.
#[cfg(not(test))]
#[no_mangle]
// NB. used by both libunwind and libpanic_abort
pub extern "C" fn __rust_abort() {
abort_internal();
}
pub mod rand {
pub fn
|
() -> u64 {
unsafe {
let mut ret: u64 = 0;
for _ in 0..10 {
if crate::arch::x86_64::_rdrand64_step(&mut ret) == 1 {
return ret;
}
}
rtabort!("Failed to obtain random data");
}
}
}
pub fn hashmap_random_keys() -> (u64, u64) {
(self::rand::rdrand64(), self::rand::rdrand64())
}
pub use crate::sys_common::{AsInner, FromInner, IntoInner};
pub trait TryIntoInner<Inner>: Sized {
fn try_into_inner(self) -> Result<Inner, Self>;
}
|
rdrand64
|
identifier_name
|
mod.rs
|
//! System bindings for the Fortanix SGX platform
//!
//! This module contains the facade (aka platform-specific) implementations of
//! OS level functionality for Fortanix SGX.
#![deny(unsafe_op_in_unsafe_fn)]
use crate::io::ErrorKind;
use crate::os::raw::c_char;
use crate::sync::atomic::{AtomicBool, Ordering};
pub mod abi;
mod waitqueue;
pub mod alloc;
pub mod args;
#[path = "../unix/cmath.rs"]
pub mod cmath;
pub mod condvar;
pub mod env;
pub mod fd;
#[path = "../unsupported/fs.rs"]
pub mod fs;
#[path = "../unsupported/io.rs"]
pub mod io;
pub mod memchr;
pub mod mutex;
pub mod net;
pub mod os;
#[path = "../unix/os_str.rs"]
pub mod os_str;
pub mod path;
#[path = "../unsupported/pipe.rs"]
pub mod pipe;
#[path = "../unsupported/process.rs"]
pub mod process;
pub mod rwlock;
pub mod stdio;
pub mod thread;
pub mod thread_local_key;
pub mod time;
// SAFETY: must be called only once during runtime initialization.
// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
pub unsafe fn init(argc: isize, argv: *const *const u8) {
unsafe {
args::init(argc, argv);
}
}
// SAFETY: must be called only once during runtime cleanup.
// NOTE: this is not guaranteed to run, for example when the program aborts.
pub unsafe fn cleanup() {}
/// This function is used to implement functionality that simply doesn't exist.
/// Programs relying on this functionality will need to deal with the error.
pub fn unsupported<T>() -> crate::io::Result<T> {
Err(unsupported_err())
}
pub fn unsupported_err() -> crate::io::Error {
crate::io::Error::new_const(ErrorKind::Unsupported, &"operation not supported on SGX yet")
}
/// This function is used to implement various functions that doesn't exist,
/// but the lack of which might not be reason for error. If no error is
/// returned, the program might very well be able to function normally. This is
/// what happens when `SGX_INEFFECTIVE_ERROR` is set to `true`. If it is
/// `false`, the behavior is the same as `unsupported`.
pub fn sgx_ineffective<T>(v: T) -> crate::io::Result<T> {
static SGX_INEFFECTIVE_ERROR: AtomicBool = AtomicBool::new(false);
if SGX_INEFFECTIVE_ERROR.load(Ordering::Relaxed) {
Err(crate::io::Error::new_const(
ErrorKind::Uncategorized,
&"operation can't be trusted to have any effect on SGX",
))
} else {
Ok(v)
}
}
pub fn decode_error_kind(code: i32) -> ErrorKind {
use fortanix_sgx_abi::Error;
// FIXME: not sure how to make sure all variants of Error are covered
if code == Error::NotFound as _ {
ErrorKind::NotFound
} else if code == Error::PermissionDenied as _ {
ErrorKind::PermissionDenied
} else if code == Error::ConnectionRefused as _ {
ErrorKind::ConnectionRefused
} else if code == Error::ConnectionReset as _ {
ErrorKind::ConnectionReset
} else if code == Error::ConnectionAborted as _ {
ErrorKind::ConnectionAborted
} else if code == Error::NotConnected as _ {
ErrorKind::NotConnected
} else if code == Error::AddrInUse as _ {
ErrorKind::AddrInUse
} else if code == Error::AddrNotAvailable as _ {
ErrorKind::AddrNotAvailable
} else if code == Error::BrokenPipe as _ {
ErrorKind::BrokenPipe
} else if code == Error::AlreadyExists as _ {
ErrorKind::AlreadyExists
} else if code == Error::WouldBlock as _ {
ErrorKind::WouldBlock
} else if code == Error::InvalidInput as _
|
else if code == Error::InvalidData as _ {
ErrorKind::InvalidData
} else if code == Error::TimedOut as _ {
ErrorKind::TimedOut
} else if code == Error::WriteZero as _ {
ErrorKind::WriteZero
} else if code == Error::Interrupted as _ {
ErrorKind::Interrupted
} else if code == Error::Other as _ {
ErrorKind::Uncategorized
} else if code == Error::UnexpectedEof as _ {
ErrorKind::UnexpectedEof
} else {
ErrorKind::Uncategorized
}
}
pub unsafe fn strlen(mut s: *const c_char) -> usize {
let mut n = 0;
while unsafe { *s }!= 0 {
n += 1;
s = unsafe { s.offset(1) };
}
return n;
}
pub fn abort_internal() ->! {
abi::usercalls::exit(true)
}
// This function is needed by the panic runtime. The symbol is named in
// pre-link args for the target specification, so keep that in sync.
#[cfg(not(test))]
#[no_mangle]
// NB. used by both libunwind and libpanic_abort
pub extern "C" fn __rust_abort() {
abort_internal();
}
pub mod rand {
pub fn rdrand64() -> u64 {
unsafe {
let mut ret: u64 = 0;
for _ in 0..10 {
if crate::arch::x86_64::_rdrand64_step(&mut ret) == 1 {
return ret;
}
}
rtabort!("Failed to obtain random data");
}
}
}
pub fn hashmap_random_keys() -> (u64, u64) {
(self::rand::rdrand64(), self::rand::rdrand64())
}
pub use crate::sys_common::{AsInner, FromInner, IntoInner};
pub trait TryIntoInner<Inner>: Sized {
fn try_into_inner(self) -> Result<Inner, Self>;
}
|
{
ErrorKind::InvalidInput
}
|
conditional_block
|
mod.rs
|
//! System bindings for the Fortanix SGX platform
//!
//! This module contains the facade (aka platform-specific) implementations of
//! OS level functionality for Fortanix SGX.
#![deny(unsafe_op_in_unsafe_fn)]
use crate::io::ErrorKind;
use crate::os::raw::c_char;
use crate::sync::atomic::{AtomicBool, Ordering};
pub mod abi;
mod waitqueue;
pub mod alloc;
pub mod args;
#[path = "../unix/cmath.rs"]
pub mod cmath;
pub mod condvar;
pub mod env;
pub mod fd;
#[path = "../unsupported/fs.rs"]
pub mod fs;
#[path = "../unsupported/io.rs"]
pub mod io;
pub mod memchr;
pub mod mutex;
pub mod net;
pub mod os;
#[path = "../unix/os_str.rs"]
pub mod os_str;
pub mod path;
#[path = "../unsupported/pipe.rs"]
pub mod pipe;
#[path = "../unsupported/process.rs"]
pub mod process;
pub mod rwlock;
pub mod stdio;
pub mod thread;
pub mod thread_local_key;
pub mod time;
// SAFETY: must be called only once during runtime initialization.
// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
pub unsafe fn init(argc: isize, argv: *const *const u8) {
unsafe {
args::init(argc, argv);
}
}
// SAFETY: must be called only once during runtime cleanup.
// NOTE: this is not guaranteed to run, for example when the program aborts.
pub unsafe fn cleanup() {}
/// This function is used to implement functionality that simply doesn't exist.
/// Programs relying on this functionality will need to deal with the error.
pub fn unsupported<T>() -> crate::io::Result<T> {
Err(unsupported_err())
}
pub fn unsupported_err() -> crate::io::Error {
crate::io::Error::new_const(ErrorKind::Unsupported, &"operation not supported on SGX yet")
}
/// This function is used to implement various functions that doesn't exist,
/// but the lack of which might not be reason for error. If no error is
/// returned, the program might very well be able to function normally. This is
/// what happens when `SGX_INEFFECTIVE_ERROR` is set to `true`. If it is
/// `false`, the behavior is the same as `unsupported`.
pub fn sgx_ineffective<T>(v: T) -> crate::io::Result<T> {
static SGX_INEFFECTIVE_ERROR: AtomicBool = AtomicBool::new(false);
if SGX_INEFFECTIVE_ERROR.load(Ordering::Relaxed) {
Err(crate::io::Error::new_const(
ErrorKind::Uncategorized,
&"operation can't be trusted to have any effect on SGX",
))
} else {
Ok(v)
}
}
pub fn decode_error_kind(code: i32) -> ErrorKind {
use fortanix_sgx_abi::Error;
// FIXME: not sure how to make sure all variants of Error are covered
if code == Error::NotFound as _ {
ErrorKind::NotFound
} else if code == Error::PermissionDenied as _ {
ErrorKind::PermissionDenied
} else if code == Error::ConnectionRefused as _ {
ErrorKind::ConnectionRefused
} else if code == Error::ConnectionReset as _ {
ErrorKind::ConnectionReset
} else if code == Error::ConnectionAborted as _ {
ErrorKind::ConnectionAborted
} else if code == Error::NotConnected as _ {
ErrorKind::NotConnected
} else if code == Error::AddrInUse as _ {
ErrorKind::AddrInUse
} else if code == Error::AddrNotAvailable as _ {
ErrorKind::AddrNotAvailable
} else if code == Error::BrokenPipe as _ {
ErrorKind::BrokenPipe
} else if code == Error::AlreadyExists as _ {
ErrorKind::AlreadyExists
} else if code == Error::WouldBlock as _ {
ErrorKind::WouldBlock
} else if code == Error::InvalidInput as _ {
ErrorKind::InvalidInput
} else if code == Error::InvalidData as _ {
ErrorKind::InvalidData
} else if code == Error::TimedOut as _ {
ErrorKind::TimedOut
} else if code == Error::WriteZero as _ {
ErrorKind::WriteZero
} else if code == Error::Interrupted as _ {
ErrorKind::Interrupted
} else if code == Error::Other as _ {
ErrorKind::Uncategorized
} else if code == Error::UnexpectedEof as _ {
ErrorKind::UnexpectedEof
} else {
ErrorKind::Uncategorized
}
}
pub unsafe fn strlen(mut s: *const c_char) -> usize {
let mut n = 0;
while unsafe { *s }!= 0 {
n += 1;
s = unsafe { s.offset(1) };
}
return n;
}
pub fn abort_internal() ->! {
abi::usercalls::exit(true)
}
// This function is needed by the panic runtime. The symbol is named in
// pre-link args for the target specification, so keep that in sync.
#[cfg(not(test))]
#[no_mangle]
// NB. used by both libunwind and libpanic_abort
pub extern "C" fn __rust_abort() {
abort_internal();
}
pub mod rand {
pub fn rdrand64() -> u64 {
unsafe {
let mut ret: u64 = 0;
for _ in 0..10 {
if crate::arch::x86_64::_rdrand64_step(&mut ret) == 1 {
return ret;
}
}
rtabort!("Failed to obtain random data");
}
}
}
pub fn hashmap_random_keys() -> (u64, u64) {
(self::rand::rdrand64(), self::rand::rdrand64())
}
pub use crate::sys_common::{AsInner, FromInner, IntoInner};
pub trait TryIntoInner<Inner>: Sized {
|
}
|
fn try_into_inner(self) -> Result<Inner, Self>;
|
random_line_split
|
mod.rs
|
//! System bindings for the Fortanix SGX platform
//!
//! This module contains the facade (aka platform-specific) implementations of
//! OS level functionality for Fortanix SGX.
#![deny(unsafe_op_in_unsafe_fn)]
use crate::io::ErrorKind;
use crate::os::raw::c_char;
use crate::sync::atomic::{AtomicBool, Ordering};
pub mod abi;
mod waitqueue;
pub mod alloc;
pub mod args;
#[path = "../unix/cmath.rs"]
pub mod cmath;
pub mod condvar;
pub mod env;
pub mod fd;
#[path = "../unsupported/fs.rs"]
pub mod fs;
#[path = "../unsupported/io.rs"]
pub mod io;
pub mod memchr;
pub mod mutex;
pub mod net;
pub mod os;
#[path = "../unix/os_str.rs"]
pub mod os_str;
pub mod path;
#[path = "../unsupported/pipe.rs"]
pub mod pipe;
#[path = "../unsupported/process.rs"]
pub mod process;
pub mod rwlock;
pub mod stdio;
pub mod thread;
pub mod thread_local_key;
pub mod time;
// SAFETY: must be called only once during runtime initialization.
// NOTE: this is not guaranteed to run, for example when Rust code is called externally.
pub unsafe fn init(argc: isize, argv: *const *const u8) {
unsafe {
args::init(argc, argv);
}
}
// SAFETY: must be called only once during runtime cleanup.
// NOTE: this is not guaranteed to run, for example when the program aborts.
pub unsafe fn cleanup() {}
/// This function is used to implement functionality that simply doesn't exist.
/// Programs relying on this functionality will need to deal with the error.
pub fn unsupported<T>() -> crate::io::Result<T> {
Err(unsupported_err())
}
pub fn unsupported_err() -> crate::io::Error {
crate::io::Error::new_const(ErrorKind::Unsupported, &"operation not supported on SGX yet")
}
/// This function is used to implement various functions that doesn't exist,
/// but the lack of which might not be reason for error. If no error is
/// returned, the program might very well be able to function normally. This is
/// what happens when `SGX_INEFFECTIVE_ERROR` is set to `true`. If it is
/// `false`, the behavior is the same as `unsupported`.
pub fn sgx_ineffective<T>(v: T) -> crate::io::Result<T> {
static SGX_INEFFECTIVE_ERROR: AtomicBool = AtomicBool::new(false);
if SGX_INEFFECTIVE_ERROR.load(Ordering::Relaxed) {
Err(crate::io::Error::new_const(
ErrorKind::Uncategorized,
&"operation can't be trusted to have any effect on SGX",
))
} else {
Ok(v)
}
}
pub fn decode_error_kind(code: i32) -> ErrorKind {
use fortanix_sgx_abi::Error;
// FIXME: not sure how to make sure all variants of Error are covered
if code == Error::NotFound as _ {
ErrorKind::NotFound
} else if code == Error::PermissionDenied as _ {
ErrorKind::PermissionDenied
} else if code == Error::ConnectionRefused as _ {
ErrorKind::ConnectionRefused
} else if code == Error::ConnectionReset as _ {
ErrorKind::ConnectionReset
} else if code == Error::ConnectionAborted as _ {
ErrorKind::ConnectionAborted
} else if code == Error::NotConnected as _ {
ErrorKind::NotConnected
} else if code == Error::AddrInUse as _ {
ErrorKind::AddrInUse
} else if code == Error::AddrNotAvailable as _ {
ErrorKind::AddrNotAvailable
} else if code == Error::BrokenPipe as _ {
ErrorKind::BrokenPipe
} else if code == Error::AlreadyExists as _ {
ErrorKind::AlreadyExists
} else if code == Error::WouldBlock as _ {
ErrorKind::WouldBlock
} else if code == Error::InvalidInput as _ {
ErrorKind::InvalidInput
} else if code == Error::InvalidData as _ {
ErrorKind::InvalidData
} else if code == Error::TimedOut as _ {
ErrorKind::TimedOut
} else if code == Error::WriteZero as _ {
ErrorKind::WriteZero
} else if code == Error::Interrupted as _ {
ErrorKind::Interrupted
} else if code == Error::Other as _ {
ErrorKind::Uncategorized
} else if code == Error::UnexpectedEof as _ {
ErrorKind::UnexpectedEof
} else {
ErrorKind::Uncategorized
}
}
pub unsafe fn strlen(mut s: *const c_char) -> usize {
let mut n = 0;
while unsafe { *s }!= 0 {
n += 1;
s = unsafe { s.offset(1) };
}
return n;
}
pub fn abort_internal() ->! {
abi::usercalls::exit(true)
}
// This function is needed by the panic runtime. The symbol is named in
// pre-link args for the target specification, so keep that in sync.
#[cfg(not(test))]
#[no_mangle]
// NB. used by both libunwind and libpanic_abort
pub extern "C" fn __rust_abort() {
abort_internal();
}
pub mod rand {
pub fn rdrand64() -> u64
|
}
pub fn hashmap_random_keys() -> (u64, u64) {
(self::rand::rdrand64(), self::rand::rdrand64())
}
pub use crate::sys_common::{AsInner, FromInner, IntoInner};
pub trait TryIntoInner<Inner>: Sized {
fn try_into_inner(self) -> Result<Inner, Self>;
}
|
{
unsafe {
let mut ret: u64 = 0;
for _ in 0..10 {
if crate::arch::x86_64::_rdrand64_step(&mut ret) == 1 {
return ret;
}
}
rtabort!("Failed to obtain random data");
}
}
|
identifier_body
|
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling between these two components.
use hyper::header::Headers;
use hyper::method::Method;
use ipc_channel::ipc::IpcSharedMemory;
use std::cell::Cell;
use std::fmt;
use url::Url;
use webrender_traits;
#[derive(Deserialize, Eq, PartialEq, Serialize, Copy, Clone, HeapSizeOf)]
pub enum
|
{
Initial,
Resize,
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum KeyState {
Pressed,
Released,
Repeated,
}
//N.B. Based on the glutin key enum
#[derive(Debug, PartialEq, Eq, Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LeftBracket,
Backslash,
RightBracket,
GraveAccent,
World1,
World2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Kp0,
Kp1,
Kp2,
Kp3,
Kp4,
Kp5,
Kp6,
Kp7,
Kp8,
Kp9,
KpDecimal,
KpDivide,
KpMultiply,
KpSubtract,
KpAdd,
KpEnter,
KpEqual,
LeftShift,
LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu,
NavigateBackward,
NavigateForward,
}
bitflags! {
#[derive(Deserialize, Serialize)]
pub flags KeyModifiers: u8 {
const NONE = 0x00,
const SHIFT = 0x01,
const CONTROL = 0x02,
const ALT = 0x04,
const SUPER = 0x08,
}
}
#[derive(Clone, Copy, Deserialize, Eq, PartialEq, Serialize, HeapSizeOf)]
pub enum PixelFormat {
K8, // Luminance channel only
KA8, // Luminance + alpha
RGB8, // RGB, 8 bits per channel
RGBA8, // RGB + alpha, 8 bits per channel
}
#[derive(Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct Image {
pub width: u32,
pub height: u32,
pub format: PixelFormat,
#[ignore_heap_size_of = "Defined in ipc-channel"]
pub bytes: IpcSharedMemory,
#[ignore_heap_size_of = "Defined in webrender_traits"]
pub id: Option<webrender_traits::ImageKey>,
}
/// Similar to net::resource_thread::LoadData
/// can be passed to LoadUrl to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Deserialize, Serialize)]
pub struct LoadData {
pub url: Url,
pub method: Method,
pub headers: Headers,
pub data: Option<Vec<u8>>,
pub referrer_policy: Option<ReferrerPolicy>,
pub referrer_url: Option<Url>,
}
impl LoadData {
pub fn new(url: Url, referrer_policy: Option<ReferrerPolicy>, referrer_url: Option<Url>) -> LoadData {
LoadData {
url: url,
method: Method::Get,
headers: Headers::new(),
data: None,
referrer_policy: referrer_policy,
referrer_url: referrer_url,
}
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)]
pub enum TraversalDirection {
Forward(usize),
Back(usize),
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, PartialOrd, Ord)]
pub struct FrameId(pub u32);
/// Each pipeline ID needs to be unique. However, it also needs to be possible to
/// generate the pipeline ID from an iframe element (this simplifies a lot of other
/// code that makes use of pipeline IDs).
///
/// To achieve this, each pipeline index belongs to a particular namespace. There is
/// a namespace for the constellation thread, and also one for every script thread.
/// This allows pipeline IDs to be generated by any of those threads without conflicting
/// with pipeline IDs created by other script threads or the constellation. The
/// constellation is the only code that is responsible for creating new *namespaces*.
/// This ensures that namespaces are always unique, even when using multi-process mode.
///
/// It may help conceptually to think of the namespace ID as an identifier for the
/// thread that created this pipeline ID - however this is really an implementation
/// detail so shouldn't be relied upon in code logic. It's best to think of the
/// pipeline ID as a simple unique identifier that doesn't convey any more information.
#[derive(Clone, Copy)]
pub struct PipelineNamespace {
id: PipelineNamespaceId,
next_index: PipelineIndex,
}
impl PipelineNamespace {
pub fn install(namespace_id: PipelineNamespaceId) {
PIPELINE_NAMESPACE.with(|tls| {
assert!(tls.get().is_none());
tls.set(Some(PipelineNamespace {
id: namespace_id,
next_index: PipelineIndex(0),
}));
});
}
fn next(&mut self) -> PipelineId {
let pipeline_id = PipelineId {
namespace_id: self.id,
index: self.next_index,
};
let PipelineIndex(current_index) = self.next_index;
self.next_index = PipelineIndex(current_index + 1);
pipeline_id
}
}
thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = Cell::new(None));
thread_local!(pub static PIPELINE_ID: Cell<Option<PipelineId>> = Cell::new(None));
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineNamespaceId(pub u32);
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineIndex(pub u32);
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineId {
pub namespace_id: PipelineNamespaceId,
pub index: PipelineIndex
}
impl PipelineId {
pub fn new() -> PipelineId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_pipeline_id = namespace.next();
tls.set(Some(namespace));
new_pipeline_id
})
}
// TODO(gw): This should be removed. It's only required because of the code
// that uses it in the devtools lib.rs file (which itself is a TODO). Once
// that is fixed, this should be removed. It also relies on the first
// call to PipelineId::new() returning (0,0), which is checked with an
// assert in handle_init_load().
pub fn fake_root_pipeline_id() -> PipelineId {
PipelineId {
namespace_id: PipelineNamespaceId(0),
index: PipelineIndex(0),
}
}
pub fn to_webrender(&self) -> webrender_traits::PipelineId {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
webrender_traits::PipelineId(namespace_id, index)
}
pub fn install(id: PipelineId) {
PIPELINE_ID.with(|tls| tls.set(Some(id)))
}
pub fn installed() -> Option<PipelineId> {
PIPELINE_ID.with(|tls| tls.get())
}
}
impl fmt::Display for PipelineId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index)
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct SubpageId(pub u32);
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub enum FrameType {
IFrame,
MozBrowserIFrame,
}
/// [Policies](https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-states)
/// for providing a referrer header for a request
#[derive(Clone, Copy, Debug, Deserialize, HeapSizeOf, Serialize)]
pub enum ReferrerPolicy {
NoReferrer,
NoReferrerWhenDowngrade,
Origin,
SameOrigin,
OriginWhenCrossOrigin,
UnsafeUrl,
}
|
WindowSizeType
|
identifier_name
|
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling between these two components.
use hyper::header::Headers;
use hyper::method::Method;
use ipc_channel::ipc::IpcSharedMemory;
use std::cell::Cell;
use std::fmt;
use url::Url;
use webrender_traits;
#[derive(Deserialize, Eq, PartialEq, Serialize, Copy, Clone, HeapSizeOf)]
pub enum WindowSizeType {
Initial,
Resize,
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum KeyState {
Pressed,
Released,
Repeated,
}
//N.B. Based on the glutin key enum
#[derive(Debug, PartialEq, Eq, Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LeftBracket,
Backslash,
RightBracket,
GraveAccent,
World1,
World2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Kp0,
Kp1,
Kp2,
Kp3,
Kp4,
Kp5,
Kp6,
Kp7,
Kp8,
Kp9,
KpDecimal,
KpDivide,
KpMultiply,
KpSubtract,
KpAdd,
KpEnter,
KpEqual,
LeftShift,
LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu,
NavigateBackward,
NavigateForward,
}
bitflags! {
#[derive(Deserialize, Serialize)]
pub flags KeyModifiers: u8 {
const NONE = 0x00,
const SHIFT = 0x01,
const CONTROL = 0x02,
const ALT = 0x04,
const SUPER = 0x08,
}
}
#[derive(Clone, Copy, Deserialize, Eq, PartialEq, Serialize, HeapSizeOf)]
pub enum PixelFormat {
K8, // Luminance channel only
KA8, // Luminance + alpha
RGB8, // RGB, 8 bits per channel
RGBA8, // RGB + alpha, 8 bits per channel
}
#[derive(Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct Image {
pub width: u32,
pub height: u32,
pub format: PixelFormat,
#[ignore_heap_size_of = "Defined in ipc-channel"]
pub bytes: IpcSharedMemory,
#[ignore_heap_size_of = "Defined in webrender_traits"]
pub id: Option<webrender_traits::ImageKey>,
}
/// Similar to net::resource_thread::LoadData
/// can be passed to LoadUrl to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Deserialize, Serialize)]
pub struct LoadData {
pub url: Url,
pub method: Method,
pub headers: Headers,
pub data: Option<Vec<u8>>,
pub referrer_policy: Option<ReferrerPolicy>,
pub referrer_url: Option<Url>,
}
impl LoadData {
pub fn new(url: Url, referrer_policy: Option<ReferrerPolicy>, referrer_url: Option<Url>) -> LoadData {
LoadData {
url: url,
method: Method::Get,
headers: Headers::new(),
data: None,
referrer_policy: referrer_policy,
referrer_url: referrer_url,
}
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)]
pub enum TraversalDirection {
Forward(usize),
Back(usize),
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, PartialOrd, Ord)]
pub struct FrameId(pub u32);
/// Each pipeline ID needs to be unique. However, it also needs to be possible to
|
/// a namespace for the constellation thread, and also one for every script thread.
/// This allows pipeline IDs to be generated by any of those threads without conflicting
/// with pipeline IDs created by other script threads or the constellation. The
/// constellation is the only code that is responsible for creating new *namespaces*.
/// This ensures that namespaces are always unique, even when using multi-process mode.
///
/// It may help conceptually to think of the namespace ID as an identifier for the
/// thread that created this pipeline ID - however this is really an implementation
/// detail so shouldn't be relied upon in code logic. It's best to think of the
/// pipeline ID as a simple unique identifier that doesn't convey any more information.
#[derive(Clone, Copy)]
pub struct PipelineNamespace {
id: PipelineNamespaceId,
next_index: PipelineIndex,
}
impl PipelineNamespace {
pub fn install(namespace_id: PipelineNamespaceId) {
PIPELINE_NAMESPACE.with(|tls| {
assert!(tls.get().is_none());
tls.set(Some(PipelineNamespace {
id: namespace_id,
next_index: PipelineIndex(0),
}));
});
}
fn next(&mut self) -> PipelineId {
let pipeline_id = PipelineId {
namespace_id: self.id,
index: self.next_index,
};
let PipelineIndex(current_index) = self.next_index;
self.next_index = PipelineIndex(current_index + 1);
pipeline_id
}
}
thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = Cell::new(None));
thread_local!(pub static PIPELINE_ID: Cell<Option<PipelineId>> = Cell::new(None));
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineNamespaceId(pub u32);
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineIndex(pub u32);
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineId {
pub namespace_id: PipelineNamespaceId,
pub index: PipelineIndex
}
impl PipelineId {
pub fn new() -> PipelineId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_pipeline_id = namespace.next();
tls.set(Some(namespace));
new_pipeline_id
})
}
// TODO(gw): This should be removed. It's only required because of the code
// that uses it in the devtools lib.rs file (which itself is a TODO). Once
// that is fixed, this should be removed. It also relies on the first
// call to PipelineId::new() returning (0,0), which is checked with an
// assert in handle_init_load().
pub fn fake_root_pipeline_id() -> PipelineId {
PipelineId {
namespace_id: PipelineNamespaceId(0),
index: PipelineIndex(0),
}
}
pub fn to_webrender(&self) -> webrender_traits::PipelineId {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
webrender_traits::PipelineId(namespace_id, index)
}
pub fn install(id: PipelineId) {
PIPELINE_ID.with(|tls| tls.set(Some(id)))
}
pub fn installed() -> Option<PipelineId> {
PIPELINE_ID.with(|tls| tls.get())
}
}
impl fmt::Display for PipelineId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index)
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct SubpageId(pub u32);
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub enum FrameType {
IFrame,
MozBrowserIFrame,
}
/// [Policies](https://w3c.github.io/webappsec-referrer-policy/#referrer-policy-states)
/// for providing a referrer header for a request
#[derive(Clone, Copy, Debug, Deserialize, HeapSizeOf, Serialize)]
pub enum ReferrerPolicy {
NoReferrer,
NoReferrerWhenDowngrade,
Origin,
SameOrigin,
OriginWhenCrossOrigin,
UnsafeUrl,
}
|
/// generate the pipeline ID from an iframe element (this simplifies a lot of other
/// code that makes use of pipeline IDs).
///
/// To achieve this, each pipeline index belongs to a particular namespace. There is
|
random_line_split
|
weldr.rs
|
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate weldr;
extern crate clap;
extern crate tokio_core;
extern crate net2;
use std::io;
use std::net::SocketAddr;
use clap::{Arg, App, SubCommand};
use net2::TcpBuilder;
use net2::unix::UnixTcpBuilderExt;
use tokio_core::reactor::{Core, Handle};
use tokio_core::net::TcpListener;
use weldr::pool::Pool;
use weldr::config::Config;
use weldr::mgmt::{worker, manager};
use weldr::mgmt::health::BackendHealth;
fn
|
() {
env_logger::init().expect("Failed to start logger");
let matches = App::new("weldr")
.arg(
Arg::with_name("admin-ip")
.long("admin-ip")
.value_name("admin-ip")
.takes_value(true)
.help(
"admin ip and port used to issue commands to cluster. default: 0.0.0.0:8687",
),
)
.arg(
Arg::with_name("ip")
.long("ip")
.value_name("ip")
.takes_value(true)
.help("listening ip and port for cluster. default: 0.0.0.0:8080"),
)
.subcommand(
SubCommand::with_name("worker").about("start a worker").arg(
Arg::with_name("id")
.long("id")
.value_name("id")
.takes_value(true)
.help("worker id assigned by the manager"),
),
)
.get_matches();
let mut core = Core::new().unwrap();
let handle = core.handle();
// TODO make this dynamic and pass it down to workers
let internal_addr = "127.0.0.1:4000";
let internal_addr = internal_addr
.parse::<SocketAddr>()
.expect("Failed to parse addr");
let ip = matches.value_of("worker").unwrap_or("0.0.0.0:8080");
let ip = ip.parse::<SocketAddr>().unwrap();
let pool = Pool::default();
let config = Config::default();
if let Some(matches) = matches.subcommand_matches("worker") {
let id = matches.value_of("id").unwrap();
debug!("Spawned worker {}", id);
let _result = worker::subscribe(internal_addr, handle, pool.clone());
let listener = setup_listener(ip, &core.handle()).expect("Failed to setup listener");
//weldr::proxy::run(ip, pool, core).expect("Failed to start server");
let srv = weldr::proxy::serve(listener, pool, &core.handle(), &config).expect("Failed to create server future");
core.run(srv).expect("Server failed");
} else {
let mut manager = manager::Manager::new();
manager.listen(internal_addr, handle.clone());
manager.start_workers(5).expect("Failed to start manager");
let health = BackendHealth::new();
let admin_ip = matches.value_of("worker").unwrap_or("0.0.0.0:8687");
let admin_ip = admin_ip.parse::<SocketAddr>().unwrap();
weldr::mgmt::run(admin_ip, pool, core, manager.clone(), &config, health.clone())
.expect("Failed to start server");
}
}
fn setup_listener(addr: SocketAddr, handle: &Handle) -> io::Result<TcpListener> {
let listener = TcpBuilder::new_v4()?;
listener.reuse_address(true)?;
listener.reuse_port(true)?;
let listener = listener.bind(&addr)?;
let listener = listener.listen(128)?;
let listener = TcpListener::from_listener(listener, &addr, &handle)?;
Ok(listener)
}
|
main
|
identifier_name
|
weldr.rs
|
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate weldr;
extern crate clap;
extern crate tokio_core;
extern crate net2;
use std::io;
use std::net::SocketAddr;
use clap::{Arg, App, SubCommand};
use net2::TcpBuilder;
use net2::unix::UnixTcpBuilderExt;
use tokio_core::reactor::{Core, Handle};
use tokio_core::net::TcpListener;
use weldr::pool::Pool;
use weldr::config::Config;
use weldr::mgmt::{worker, manager};
use weldr::mgmt::health::BackendHealth;
fn main() {
|
Arg::with_name("admin-ip")
.long("admin-ip")
.value_name("admin-ip")
.takes_value(true)
.help(
"admin ip and port used to issue commands to cluster. default: 0.0.0.0:8687",
),
)
.arg(
Arg::with_name("ip")
.long("ip")
.value_name("ip")
.takes_value(true)
.help("listening ip and port for cluster. default: 0.0.0.0:8080"),
)
.subcommand(
SubCommand::with_name("worker").about("start a worker").arg(
Arg::with_name("id")
.long("id")
.value_name("id")
.takes_value(true)
.help("worker id assigned by the manager"),
),
)
.get_matches();
let mut core = Core::new().unwrap();
let handle = core.handle();
// TODO make this dynamic and pass it down to workers
let internal_addr = "127.0.0.1:4000";
let internal_addr = internal_addr
.parse::<SocketAddr>()
.expect("Failed to parse addr");
let ip = matches.value_of("worker").unwrap_or("0.0.0.0:8080");
let ip = ip.parse::<SocketAddr>().unwrap();
let pool = Pool::default();
let config = Config::default();
if let Some(matches) = matches.subcommand_matches("worker") {
let id = matches.value_of("id").unwrap();
debug!("Spawned worker {}", id);
let _result = worker::subscribe(internal_addr, handle, pool.clone());
let listener = setup_listener(ip, &core.handle()).expect("Failed to setup listener");
//weldr::proxy::run(ip, pool, core).expect("Failed to start server");
let srv = weldr::proxy::serve(listener, pool, &core.handle(), &config).expect("Failed to create server future");
core.run(srv).expect("Server failed");
} else {
let mut manager = manager::Manager::new();
manager.listen(internal_addr, handle.clone());
manager.start_workers(5).expect("Failed to start manager");
let health = BackendHealth::new();
let admin_ip = matches.value_of("worker").unwrap_or("0.0.0.0:8687");
let admin_ip = admin_ip.parse::<SocketAddr>().unwrap();
weldr::mgmt::run(admin_ip, pool, core, manager.clone(), &config, health.clone())
.expect("Failed to start server");
}
}
fn setup_listener(addr: SocketAddr, handle: &Handle) -> io::Result<TcpListener> {
let listener = TcpBuilder::new_v4()?;
listener.reuse_address(true)?;
listener.reuse_port(true)?;
let listener = listener.bind(&addr)?;
let listener = listener.listen(128)?;
let listener = TcpListener::from_listener(listener, &addr, &handle)?;
Ok(listener)
}
|
env_logger::init().expect("Failed to start logger");
let matches = App::new("weldr")
.arg(
|
random_line_split
|
weldr.rs
|
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate weldr;
extern crate clap;
extern crate tokio_core;
extern crate net2;
use std::io;
use std::net::SocketAddr;
use clap::{Arg, App, SubCommand};
use net2::TcpBuilder;
use net2::unix::UnixTcpBuilderExt;
use tokio_core::reactor::{Core, Handle};
use tokio_core::net::TcpListener;
use weldr::pool::Pool;
use weldr::config::Config;
use weldr::mgmt::{worker, manager};
use weldr::mgmt::health::BackendHealth;
fn main() {
env_logger::init().expect("Failed to start logger");
let matches = App::new("weldr")
.arg(
Arg::with_name("admin-ip")
.long("admin-ip")
.value_name("admin-ip")
.takes_value(true)
.help(
"admin ip and port used to issue commands to cluster. default: 0.0.0.0:8687",
),
)
.arg(
Arg::with_name("ip")
.long("ip")
.value_name("ip")
.takes_value(true)
.help("listening ip and port for cluster. default: 0.0.0.0:8080"),
)
.subcommand(
SubCommand::with_name("worker").about("start a worker").arg(
Arg::with_name("id")
.long("id")
.value_name("id")
.takes_value(true)
.help("worker id assigned by the manager"),
),
)
.get_matches();
let mut core = Core::new().unwrap();
let handle = core.handle();
// TODO make this dynamic and pass it down to workers
let internal_addr = "127.0.0.1:4000";
let internal_addr = internal_addr
.parse::<SocketAddr>()
.expect("Failed to parse addr");
let ip = matches.value_of("worker").unwrap_or("0.0.0.0:8080");
let ip = ip.parse::<SocketAddr>().unwrap();
let pool = Pool::default();
let config = Config::default();
if let Some(matches) = matches.subcommand_matches("worker")
|
else {
let mut manager = manager::Manager::new();
manager.listen(internal_addr, handle.clone());
manager.start_workers(5).expect("Failed to start manager");
let health = BackendHealth::new();
let admin_ip = matches.value_of("worker").unwrap_or("0.0.0.0:8687");
let admin_ip = admin_ip.parse::<SocketAddr>().unwrap();
weldr::mgmt::run(admin_ip, pool, core, manager.clone(), &config, health.clone())
.expect("Failed to start server");
}
}
fn setup_listener(addr: SocketAddr, handle: &Handle) -> io::Result<TcpListener> {
let listener = TcpBuilder::new_v4()?;
listener.reuse_address(true)?;
listener.reuse_port(true)?;
let listener = listener.bind(&addr)?;
let listener = listener.listen(128)?;
let listener = TcpListener::from_listener(listener, &addr, &handle)?;
Ok(listener)
}
|
{
let id = matches.value_of("id").unwrap();
debug!("Spawned worker {}", id);
let _result = worker::subscribe(internal_addr, handle, pool.clone());
let listener = setup_listener(ip, &core.handle()).expect("Failed to setup listener");
//weldr::proxy::run(ip, pool, core).expect("Failed to start server");
let srv = weldr::proxy::serve(listener, pool, &core.handle(), &config).expect("Failed to create server future");
core.run(srv).expect("Server failed");
}
|
conditional_block
|
weldr.rs
|
#[macro_use]
extern crate log;
extern crate env_logger;
extern crate hyper;
extern crate weldr;
extern crate clap;
extern crate tokio_core;
extern crate net2;
use std::io;
use std::net::SocketAddr;
use clap::{Arg, App, SubCommand};
use net2::TcpBuilder;
use net2::unix::UnixTcpBuilderExt;
use tokio_core::reactor::{Core, Handle};
use tokio_core::net::TcpListener;
use weldr::pool::Pool;
use weldr::config::Config;
use weldr::mgmt::{worker, manager};
use weldr::mgmt::health::BackendHealth;
fn main() {
env_logger::init().expect("Failed to start logger");
let matches = App::new("weldr")
.arg(
Arg::with_name("admin-ip")
.long("admin-ip")
.value_name("admin-ip")
.takes_value(true)
.help(
"admin ip and port used to issue commands to cluster. default: 0.0.0.0:8687",
),
)
.arg(
Arg::with_name("ip")
.long("ip")
.value_name("ip")
.takes_value(true)
.help("listening ip and port for cluster. default: 0.0.0.0:8080"),
)
.subcommand(
SubCommand::with_name("worker").about("start a worker").arg(
Arg::with_name("id")
.long("id")
.value_name("id")
.takes_value(true)
.help("worker id assigned by the manager"),
),
)
.get_matches();
let mut core = Core::new().unwrap();
let handle = core.handle();
// TODO make this dynamic and pass it down to workers
let internal_addr = "127.0.0.1:4000";
let internal_addr = internal_addr
.parse::<SocketAddr>()
.expect("Failed to parse addr");
let ip = matches.value_of("worker").unwrap_or("0.0.0.0:8080");
let ip = ip.parse::<SocketAddr>().unwrap();
let pool = Pool::default();
let config = Config::default();
if let Some(matches) = matches.subcommand_matches("worker") {
let id = matches.value_of("id").unwrap();
debug!("Spawned worker {}", id);
let _result = worker::subscribe(internal_addr, handle, pool.clone());
let listener = setup_listener(ip, &core.handle()).expect("Failed to setup listener");
//weldr::proxy::run(ip, pool, core).expect("Failed to start server");
let srv = weldr::proxy::serve(listener, pool, &core.handle(), &config).expect("Failed to create server future");
core.run(srv).expect("Server failed");
} else {
let mut manager = manager::Manager::new();
manager.listen(internal_addr, handle.clone());
manager.start_workers(5).expect("Failed to start manager");
let health = BackendHealth::new();
let admin_ip = matches.value_of("worker").unwrap_or("0.0.0.0:8687");
let admin_ip = admin_ip.parse::<SocketAddr>().unwrap();
weldr::mgmt::run(admin_ip, pool, core, manager.clone(), &config, health.clone())
.expect("Failed to start server");
}
}
fn setup_listener(addr: SocketAddr, handle: &Handle) -> io::Result<TcpListener>
|
{
let listener = TcpBuilder::new_v4()?;
listener.reuse_address(true)?;
listener.reuse_port(true)?;
let listener = listener.bind(&addr)?;
let listener = listener.listen(128)?;
let listener = TcpListener::from_listener(listener, &addr, &handle)?;
Ok(listener)
}
|
identifier_body
|
|
calculator.rs
|
//! # Simple 4-function calculator
//!
//! This demonstrates usage of Peresil, and also shows how you can
//! write a recursive-descent parser that handles left-associative
//! operators.
//!
//! For an extra wrinkle, input numbers must be integers in the range
//! [0, 31]. This allows an opportunity to show how errors outside the
//! grammar can be generated at parsing time.
//!
//! ## Grammar
//!
//! Expr := Add
//! Add := Add '+' Mul
//! := Add '-' Mul
//! := Mul
//! Mul := Mul '*' Num
//! := Mul '/' Num
//! := Num
//! Num := [0-9]+
#[macro_use]
extern crate peresil;
use peresil::{ParseMaster, Recoverable, StringPoint};
// It's recommended to make type aliases to clean up signatures
type CalcMaster<'a> = ParseMaster<StringPoint<'a>, Error>;
type CalcProgress<'a, T> = peresil::Progress<StringPoint<'a>, T, Error>;
#[derive(Debug, Clone, PartialEq)]
enum Expression {
Add(Box<Expression>, Box<Expression>),
Sub(Box<Expression>, Box<Expression>),
Mul(Box<Expression>, Box<Expression>),
Div(Box<Expression>, Box<Expression>),
Num(u8),
}
impl Expression {
fn evaluate(&self) -> i32 {
use Expression::*;
match *self {
Add(ref l, ref r) => l.evaluate() + r.evaluate(),
Sub(ref l, ref r) => l.evaluate() - r.evaluate(),
Mul(ref l, ref r) => l.evaluate() * r.evaluate(),
Div(ref l, ref r) => l.evaluate() / r.evaluate(),
Num(v) => v as i32,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum Error {
ExpectedNumber,
InvalidNumber(u8),
}
impl Recoverable for Error {
fn recoverable(&self) -> bool {
use Error::*;
match *self {
ExpectedNumber => true,
InvalidNumber(..) => false,
}
}
}
/// Maps an operator to a function that builds the corresponding Expression
type LeftAssociativeRule<'a> = (
&'static str,
&'a dyn Fn(Expression, Expression) -> Expression,
);
/// Iteratively parses left-associative operators, avoiding infinite
/// recursion. Provide a `child_parser` that corresponds to each side
/// of the operator, as well as a rule for each operator.
fn parse_left_associative_operator<'a, P>(
pm: &mut CalcMaster<'a>,
pt: StringPoint<'a>,
child_parser: P,
rules: &[LeftAssociativeRule],
) -> CalcProgress<'a, Expression>
where
P: for<'b> Fn(&mut CalcMaster<'b>, StringPoint<'b>) -> CalcProgress<'b, Expression>,
{
let (pt, mut a) = try_parse!(child_parser(pm, pt));
let mut start = pt;
loop {
let mut matched = false;
for &(ref operator, ref builder) in rules {
let (pt, op) = start.consume_literal(operator).optional(start);
if op.is_none() {
continue;
}
let (pt, b) = try_parse!(child_parser(pm, pt));
a = builder(a, b);
start = pt;
matched = true;
break;
}
if!matched {
break;
}
}
peresil::Progress::success(pt, a)
}
/// Parse a sequence of one-or-more ASCII digits
fn parse_num<'a>(_: &mut CalcMaster<'a>, pt: StringPoint<'a>) -> CalcProgress<'a, Expression> {
let original_pt = pt;
// We can cheat and know that ASCII 0-9 only takes one byte each
let digits = pt.s.chars().take_while(|&c| c >= '0' && c <= '9').count();
let r = if digits == 0 {
pt.consume_to(None)
} else {
pt.consume_to(Some(digits))
};
let (pt, v) = try_parse!(r.map_err(|_| Error::ExpectedNumber));
let num = v.parse().unwrap();
// Here's where we can raise our own parsing errors. Note that we
// kept the point where the number started, in order to give an
// accurate error position.
if num > 31 {
peresil::Progress::failure(original_pt, Error::InvalidNumber(num))
} else {
peresil::Progress::success(pt, Expression::Num(num))
}
}
fn parse_muldiv<'a>(pm: &mut CalcMaster<'a>, pt: StringPoint<'a>) -> CalcProgress<'a, Expression> {
parse_left_associative_operator(
pm,
pt,
parse_num,
&[
("*", &|a, b| Expression::Mul(Box::new(a), Box::new(b))),
("/", &|a, b| Expression::Div(Box::new(a), Box::new(b))),
],
)
}
fn parse_addsub<'a>(pm: &mut CalcMaster<'a>, pt: StringPoint<'a>) -> CalcProgress<'a, Expression> {
parse_left_associative_operator(
pm,
pt,
parse_muldiv,
&[
("+", &|a, b| Expression::Add(Box::new(a), Box::new(b))),
("-", &|a, b| Expression::Sub(Box::new(a), Box::new(b))),
],
)
}
fn parse(s: &str) -> Result<Expression, (usize, Vec<Error>)> {
let mut pm = ParseMaster::new();
let pt = StringPoint::new(s);
let result = parse_addsub(&mut pm, pt);
match pm.finish(result) {
peresil::Progress {
status: peresil::Status::Success(v),
..
} => Ok(v),
peresil::Progress {
status: peresil::Status::Failure(f),
point,
} => Err((point.offset, f)),
}
}
fn n(n: u8) -> Box<Expression> {
Box::new(Expression::Num(n))
}
#[test]
fn single_number()
|
#[test]
fn add_two_numbers() {
use Expression::*;
assert_eq!(parse("1+2"), Ok(Add(n(1), n(2))));
}
#[test]
fn add_three_numbers() {
use Expression::*;
assert_eq!(parse("3+4+5"), Ok(Add(Box::new(Add(n(3), n(4))), n(5))));
}
#[test]
fn subtract_two_numbers() {
use Expression::*;
assert_eq!(parse("9-8"), Ok(Sub(n(9), n(8))));
}
#[test]
fn multiply_two_numbers() {
use Expression::*;
assert_eq!(parse("5*6"), Ok(Mul(n(5), n(6))));
}
#[test]
fn multiply_three_numbers() {
use Expression::*;
assert_eq!(parse("3*6*9"), Ok(Mul(Box::new(Mul(n(3), n(6))), n(9))));
}
#[test]
fn divide_two_numbers() {
use Expression::*;
assert_eq!(parse("9/3"), Ok(Div(n(9), n(3))));
}
#[test]
fn addition_adds() {
assert_eq!(parse("1+2+3").unwrap().evaluate(), 6);
}
#[test]
fn subtraction_subtracts() {
assert_eq!(parse("1-2-3").unwrap().evaluate(), -4);
}
#[test]
fn multiplication_multiplies() {
assert_eq!(parse("2*3*4").unwrap().evaluate(), 24);
}
#[test]
fn division_divides() {
assert_eq!(parse("9/3/3").unwrap().evaluate(), 1);
}
#[test]
fn all_operators_together() {
assert_eq!(parse("3+2-2*9/3").unwrap().evaluate(), -1);
}
#[test]
fn failure_not_a_number() {
assert_eq!(parse("cow"), Err((0, vec![Error::ExpectedNumber])));
}
#[test]
fn failure_invalid_number() {
assert_eq!(parse("32"), Err((0, vec![Error::InvalidNumber(32)])));
}
#[test]
fn failure_invalid_number_in_other_position() {
assert_eq!(parse("1+99"), Err((2, vec![Error::InvalidNumber(99)])));
}
|
{
use Expression::*;
assert_eq!(parse("1"), Ok(Num(1)));
}
|
identifier_body
|
calculator.rs
|
//! # Simple 4-function calculator
//!
//! This demonstrates usage of Peresil, and also shows how you can
//! write a recursive-descent parser that handles left-associative
//! operators.
//!
//! For an extra wrinkle, input numbers must be integers in the range
//! [0, 31]. This allows an opportunity to show how errors outside the
//! grammar can be generated at parsing time.
//!
//! ## Grammar
//!
//! Expr := Add
//! Add := Add '+' Mul
//! := Add '-' Mul
//! := Mul
//! Mul := Mul '*' Num
//! := Mul '/' Num
//! := Num
//! Num := [0-9]+
#[macro_use]
extern crate peresil;
use peresil::{ParseMaster, Recoverable, StringPoint};
// It's recommended to make type aliases to clean up signatures
type CalcMaster<'a> = ParseMaster<StringPoint<'a>, Error>;
type CalcProgress<'a, T> = peresil::Progress<StringPoint<'a>, T, Error>;
#[derive(Debug, Clone, PartialEq)]
enum Expression {
Add(Box<Expression>, Box<Expression>),
Sub(Box<Expression>, Box<Expression>),
Mul(Box<Expression>, Box<Expression>),
Div(Box<Expression>, Box<Expression>),
Num(u8),
}
impl Expression {
fn evaluate(&self) -> i32 {
use Expression::*;
match *self {
Add(ref l, ref r) => l.evaluate() + r.evaluate(),
Sub(ref l, ref r) => l.evaluate() - r.evaluate(),
Mul(ref l, ref r) => l.evaluate() * r.evaluate(),
Div(ref l, ref r) => l.evaluate() / r.evaluate(),
Num(v) => v as i32,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum Error {
ExpectedNumber,
InvalidNumber(u8),
}
impl Recoverable for Error {
fn recoverable(&self) -> bool {
use Error::*;
match *self {
ExpectedNumber => true,
InvalidNumber(..) => false,
}
}
}
/// Maps an operator to a function that builds the corresponding Expression
type LeftAssociativeRule<'a> = (
&'static str,
&'a dyn Fn(Expression, Expression) -> Expression,
);
/// Iteratively parses left-associative operators, avoiding infinite
/// recursion. Provide a `child_parser` that corresponds to each side
/// of the operator, as well as a rule for each operator.
fn parse_left_associative_operator<'a, P>(
pm: &mut CalcMaster<'a>,
pt: StringPoint<'a>,
child_parser: P,
rules: &[LeftAssociativeRule],
) -> CalcProgress<'a, Expression>
where
P: for<'b> Fn(&mut CalcMaster<'b>, StringPoint<'b>) -> CalcProgress<'b, Expression>,
{
let (pt, mut a) = try_parse!(child_parser(pm, pt));
let mut start = pt;
loop {
let mut matched = false;
for &(ref operator, ref builder) in rules {
let (pt, op) = start.consume_literal(operator).optional(start);
if op.is_none() {
continue;
}
let (pt, b) = try_parse!(child_parser(pm, pt));
a = builder(a, b);
start = pt;
matched = true;
break;
}
if!matched {
break;
}
}
peresil::Progress::success(pt, a)
}
/// Parse a sequence of one-or-more ASCII digits
fn parse_num<'a>(_: &mut CalcMaster<'a>, pt: StringPoint<'a>) -> CalcProgress<'a, Expression> {
let original_pt = pt;
// We can cheat and know that ASCII 0-9 only takes one byte each
let digits = pt.s.chars().take_while(|&c| c >= '0' && c <= '9').count();
let r = if digits == 0 {
pt.consume_to(None)
|
};
let (pt, v) = try_parse!(r.map_err(|_| Error::ExpectedNumber));
let num = v.parse().unwrap();
// Here's where we can raise our own parsing errors. Note that we
// kept the point where the number started, in order to give an
// accurate error position.
if num > 31 {
peresil::Progress::failure(original_pt, Error::InvalidNumber(num))
} else {
peresil::Progress::success(pt, Expression::Num(num))
}
}
fn parse_muldiv<'a>(pm: &mut CalcMaster<'a>, pt: StringPoint<'a>) -> CalcProgress<'a, Expression> {
parse_left_associative_operator(
pm,
pt,
parse_num,
&[
("*", &|a, b| Expression::Mul(Box::new(a), Box::new(b))),
("/", &|a, b| Expression::Div(Box::new(a), Box::new(b))),
],
)
}
fn parse_addsub<'a>(pm: &mut CalcMaster<'a>, pt: StringPoint<'a>) -> CalcProgress<'a, Expression> {
parse_left_associative_operator(
pm,
pt,
parse_muldiv,
&[
("+", &|a, b| Expression::Add(Box::new(a), Box::new(b))),
("-", &|a, b| Expression::Sub(Box::new(a), Box::new(b))),
],
)
}
fn parse(s: &str) -> Result<Expression, (usize, Vec<Error>)> {
let mut pm = ParseMaster::new();
let pt = StringPoint::new(s);
let result = parse_addsub(&mut pm, pt);
match pm.finish(result) {
peresil::Progress {
status: peresil::Status::Success(v),
..
} => Ok(v),
peresil::Progress {
status: peresil::Status::Failure(f),
point,
} => Err((point.offset, f)),
}
}
fn n(n: u8) -> Box<Expression> {
Box::new(Expression::Num(n))
}
#[test]
fn single_number() {
use Expression::*;
assert_eq!(parse("1"), Ok(Num(1)));
}
#[test]
fn add_two_numbers() {
use Expression::*;
assert_eq!(parse("1+2"), Ok(Add(n(1), n(2))));
}
#[test]
fn add_three_numbers() {
use Expression::*;
assert_eq!(parse("3+4+5"), Ok(Add(Box::new(Add(n(3), n(4))), n(5))));
}
#[test]
fn subtract_two_numbers() {
use Expression::*;
assert_eq!(parse("9-8"), Ok(Sub(n(9), n(8))));
}
#[test]
fn multiply_two_numbers() {
use Expression::*;
assert_eq!(parse("5*6"), Ok(Mul(n(5), n(6))));
}
#[test]
fn multiply_three_numbers() {
use Expression::*;
assert_eq!(parse("3*6*9"), Ok(Mul(Box::new(Mul(n(3), n(6))), n(9))));
}
#[test]
fn divide_two_numbers() {
use Expression::*;
assert_eq!(parse("9/3"), Ok(Div(n(9), n(3))));
}
#[test]
fn addition_adds() {
assert_eq!(parse("1+2+3").unwrap().evaluate(), 6);
}
#[test]
fn subtraction_subtracts() {
assert_eq!(parse("1-2-3").unwrap().evaluate(), -4);
}
#[test]
fn multiplication_multiplies() {
assert_eq!(parse("2*3*4").unwrap().evaluate(), 24);
}
#[test]
fn division_divides() {
assert_eq!(parse("9/3/3").unwrap().evaluate(), 1);
}
#[test]
fn all_operators_together() {
assert_eq!(parse("3+2-2*9/3").unwrap().evaluate(), -1);
}
#[test]
fn failure_not_a_number() {
assert_eq!(parse("cow"), Err((0, vec![Error::ExpectedNumber])));
}
#[test]
fn failure_invalid_number() {
assert_eq!(parse("32"), Err((0, vec![Error::InvalidNumber(32)])));
}
#[test]
fn failure_invalid_number_in_other_position() {
assert_eq!(parse("1+99"), Err((2, vec![Error::InvalidNumber(99)])));
}
|
} else {
pt.consume_to(Some(digits))
|
random_line_split
|
calculator.rs
|
//! # Simple 4-function calculator
//!
//! This demonstrates usage of Peresil, and also shows how you can
//! write a recursive-descent parser that handles left-associative
//! operators.
//!
//! For an extra wrinkle, input numbers must be integers in the range
//! [0, 31]. This allows an opportunity to show how errors outside the
//! grammar can be generated at parsing time.
//!
//! ## Grammar
//!
//! Expr := Add
//! Add := Add '+' Mul
//! := Add '-' Mul
//! := Mul
//! Mul := Mul '*' Num
//! := Mul '/' Num
//! := Num
//! Num := [0-9]+
#[macro_use]
extern crate peresil;
use peresil::{ParseMaster, Recoverable, StringPoint};
// It's recommended to make type aliases to clean up signatures
type CalcMaster<'a> = ParseMaster<StringPoint<'a>, Error>;
type CalcProgress<'a, T> = peresil::Progress<StringPoint<'a>, T, Error>;
#[derive(Debug, Clone, PartialEq)]
enum Expression {
Add(Box<Expression>, Box<Expression>),
Sub(Box<Expression>, Box<Expression>),
Mul(Box<Expression>, Box<Expression>),
Div(Box<Expression>, Box<Expression>),
Num(u8),
}
impl Expression {
fn evaluate(&self) -> i32 {
use Expression::*;
match *self {
Add(ref l, ref r) => l.evaluate() + r.evaluate(),
Sub(ref l, ref r) => l.evaluate() - r.evaluate(),
Mul(ref l, ref r) => l.evaluate() * r.evaluate(),
Div(ref l, ref r) => l.evaluate() / r.evaluate(),
Num(v) => v as i32,
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum Error {
ExpectedNumber,
InvalidNumber(u8),
}
impl Recoverable for Error {
fn recoverable(&self) -> bool {
use Error::*;
match *self {
ExpectedNumber => true,
InvalidNumber(..) => false,
}
}
}
/// Maps an operator to a function that builds the corresponding Expression
type LeftAssociativeRule<'a> = (
&'static str,
&'a dyn Fn(Expression, Expression) -> Expression,
);
/// Iteratively parses left-associative operators, avoiding infinite
/// recursion. Provide a `child_parser` that corresponds to each side
/// of the operator, as well as a rule for each operator.
fn parse_left_associative_operator<'a, P>(
pm: &mut CalcMaster<'a>,
pt: StringPoint<'a>,
child_parser: P,
rules: &[LeftAssociativeRule],
) -> CalcProgress<'a, Expression>
where
P: for<'b> Fn(&mut CalcMaster<'b>, StringPoint<'b>) -> CalcProgress<'b, Expression>,
{
let (pt, mut a) = try_parse!(child_parser(pm, pt));
let mut start = pt;
loop {
let mut matched = false;
for &(ref operator, ref builder) in rules {
let (pt, op) = start.consume_literal(operator).optional(start);
if op.is_none() {
continue;
}
let (pt, b) = try_parse!(child_parser(pm, pt));
a = builder(a, b);
start = pt;
matched = true;
break;
}
if!matched {
break;
}
}
peresil::Progress::success(pt, a)
}
/// Parse a sequence of one-or-more ASCII digits
fn parse_num<'a>(_: &mut CalcMaster<'a>, pt: StringPoint<'a>) -> CalcProgress<'a, Expression> {
let original_pt = pt;
// We can cheat and know that ASCII 0-9 only takes one byte each
let digits = pt.s.chars().take_while(|&c| c >= '0' && c <= '9').count();
let r = if digits == 0 {
pt.consume_to(None)
} else {
pt.consume_to(Some(digits))
};
let (pt, v) = try_parse!(r.map_err(|_| Error::ExpectedNumber));
let num = v.parse().unwrap();
// Here's where we can raise our own parsing errors. Note that we
// kept the point where the number started, in order to give an
// accurate error position.
if num > 31 {
peresil::Progress::failure(original_pt, Error::InvalidNumber(num))
} else {
peresil::Progress::success(pt, Expression::Num(num))
}
}
fn parse_muldiv<'a>(pm: &mut CalcMaster<'a>, pt: StringPoint<'a>) -> CalcProgress<'a, Expression> {
parse_left_associative_operator(
pm,
pt,
parse_num,
&[
("*", &|a, b| Expression::Mul(Box::new(a), Box::new(b))),
("/", &|a, b| Expression::Div(Box::new(a), Box::new(b))),
],
)
}
fn parse_addsub<'a>(pm: &mut CalcMaster<'a>, pt: StringPoint<'a>) -> CalcProgress<'a, Expression> {
parse_left_associative_operator(
pm,
pt,
parse_muldiv,
&[
("+", &|a, b| Expression::Add(Box::new(a), Box::new(b))),
("-", &|a, b| Expression::Sub(Box::new(a), Box::new(b))),
],
)
}
fn parse(s: &str) -> Result<Expression, (usize, Vec<Error>)> {
let mut pm = ParseMaster::new();
let pt = StringPoint::new(s);
let result = parse_addsub(&mut pm, pt);
match pm.finish(result) {
peresil::Progress {
status: peresil::Status::Success(v),
..
} => Ok(v),
peresil::Progress {
status: peresil::Status::Failure(f),
point,
} => Err((point.offset, f)),
}
}
fn n(n: u8) -> Box<Expression> {
Box::new(Expression::Num(n))
}
#[test]
fn single_number() {
use Expression::*;
assert_eq!(parse("1"), Ok(Num(1)));
}
#[test]
fn add_two_numbers() {
use Expression::*;
assert_eq!(parse("1+2"), Ok(Add(n(1), n(2))));
}
#[test]
fn add_three_numbers() {
use Expression::*;
assert_eq!(parse("3+4+5"), Ok(Add(Box::new(Add(n(3), n(4))), n(5))));
}
#[test]
fn subtract_two_numbers() {
use Expression::*;
assert_eq!(parse("9-8"), Ok(Sub(n(9), n(8))));
}
#[test]
fn multiply_two_numbers() {
use Expression::*;
assert_eq!(parse("5*6"), Ok(Mul(n(5), n(6))));
}
#[test]
fn multiply_three_numbers() {
use Expression::*;
assert_eq!(parse("3*6*9"), Ok(Mul(Box::new(Mul(n(3), n(6))), n(9))));
}
#[test]
fn divide_two_numbers() {
use Expression::*;
assert_eq!(parse("9/3"), Ok(Div(n(9), n(3))));
}
#[test]
fn addition_adds() {
assert_eq!(parse("1+2+3").unwrap().evaluate(), 6);
}
#[test]
fn subtraction_subtracts() {
assert_eq!(parse("1-2-3").unwrap().evaluate(), -4);
}
#[test]
fn
|
() {
assert_eq!(parse("2*3*4").unwrap().evaluate(), 24);
}
#[test]
fn division_divides() {
assert_eq!(parse("9/3/3").unwrap().evaluate(), 1);
}
#[test]
fn all_operators_together() {
assert_eq!(parse("3+2-2*9/3").unwrap().evaluate(), -1);
}
#[test]
fn failure_not_a_number() {
assert_eq!(parse("cow"), Err((0, vec![Error::ExpectedNumber])));
}
#[test]
fn failure_invalid_number() {
assert_eq!(parse("32"), Err((0, vec![Error::InvalidNumber(32)])));
}
#[test]
fn failure_invalid_number_in_other_position() {
assert_eq!(parse("1+99"), Err((2, vec![Error::InvalidNumber(99)])));
}
|
multiplication_multiplies
|
identifier_name
|
value_prop_tests.rs
|
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::values::{prop::layout_and_value_strategy, Value};
use move_core_types::value::MoveValue;
use proptest::prelude::*;
|
let value_deserialized = Value::simple_deserialize(&blob, &layout).expect("must deserialize");
assert!(value.equals(&value_deserialized).unwrap());
let move_value = value.as_move_value(&layout);
let blob2 = move_value.simple_serialize().expect("must serialize");
assert_eq!(blob, blob2);
let move_value_deserialized = MoveValue::simple_deserialize(&blob2, &layout).expect("must deserialize.");
assert_eq!(move_value, move_value_deserialized);
}
}
|
proptest! {
#[test]
fn serializer_round_trip((layout, value) in layout_and_value_strategy()) {
let blob = value.simple_serialize(&layout).expect("must serialize");
|
random_line_split
|
borrowck-closures-two-mut.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.
// Tests that two closures cannot simultaneously have mutable
// access to the variable, whether that mutable access be used
// for direct assignment or for taking mutable ref. Issue #6801.
// compile-flags: -Z borrowck=compare
#![feature(box_syntax)]
fn to_fn_mut<F: FnMut()>(f: F) -> F { f }
fn a() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 4);
let c2 = to_fn_mut(|| x = 5); //~ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn set(x: &mut isize) {
*x = 4;
}
fn b() {
let mut x = 3;
let c1 = to_fn_mut(|| set(&mut x));
let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn c()
|
fn d() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 5);
let c2 = to_fn_mut(|| { let _y = to_fn_mut(|| set(&mut x)); }); // (nested closure)
//~^ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn g() {
struct Foo {
f: Box<isize>
}
let mut x: Box<_> = box Foo { f: box 3 };
let c1 = to_fn_mut(|| set(&mut *x.f));
let c2 = to_fn_mut(|| set(&mut *x.f));
//~^ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn main() {
}
|
{
let mut x = 3;
let c1 = to_fn_mut(|| x = 5);
let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
|
identifier_body
|
borrowck-closures-two-mut.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.
// Tests that two closures cannot simultaneously have mutable
// access to the variable, whether that mutable access be used
// for direct assignment or for taking mutable ref. Issue #6801.
// compile-flags: -Z borrowck=compare
#![feature(box_syntax)]
fn to_fn_mut<F: FnMut()>(f: F) -> F { f }
fn a() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 4);
let c2 = to_fn_mut(|| x = 5); //~ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn set(x: &mut isize) {
*x = 4;
}
fn b() {
let mut x = 3;
let c1 = to_fn_mut(|| set(&mut x));
let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn c() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 5);
let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn
|
() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 5);
let c2 = to_fn_mut(|| { let _y = to_fn_mut(|| set(&mut x)); }); // (nested closure)
//~^ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn g() {
struct Foo {
f: Box<isize>
}
let mut x: Box<_> = box Foo { f: box 3 };
let c1 = to_fn_mut(|| set(&mut *x.f));
let c2 = to_fn_mut(|| set(&mut *x.f));
//~^ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn main() {
}
|
d
|
identifier_name
|
borrowck-closures-two-mut.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.
// Tests that two closures cannot simultaneously have mutable
// access to the variable, whether that mutable access be used
// for direct assignment or for taking mutable ref. Issue #6801.
// compile-flags: -Z borrowck=compare
#![feature(box_syntax)]
fn to_fn_mut<F: FnMut()>(f: F) -> F { f }
fn a() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 4);
let c2 = to_fn_mut(|| x = 5); //~ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn set(x: &mut isize) {
*x = 4;
}
fn b() {
let mut x = 3;
let c1 = to_fn_mut(|| set(&mut x));
let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
|
let mut x = 3;
let c1 = to_fn_mut(|| x = 5);
let c2 = to_fn_mut(|| set(&mut x)); //~ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn d() {
let mut x = 3;
let c1 = to_fn_mut(|| x = 5);
let c2 = to_fn_mut(|| { let _y = to_fn_mut(|| set(&mut x)); }); // (nested closure)
//~^ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn g() {
struct Foo {
f: Box<isize>
}
let mut x: Box<_> = box Foo { f: box 3 };
let c1 = to_fn_mut(|| set(&mut *x.f));
let c2 = to_fn_mut(|| set(&mut *x.f));
//~^ ERROR cannot borrow `x` as mutable more than once
//~| ERROR cannot borrow `x` as mutable more than once
drop((c1, c2));
}
fn main() {
}
|
fn c() {
|
random_line_split
|
static-methods-in-traits.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
mod a {
pub trait Foo {
fn foo() -> Self;
}
impl Foo for isize {
fn foo() -> isize {
3
}
}
impl Foo for usize {
fn
|
() -> usize {
5
}
}
}
pub fn main() {
let x: isize = a::Foo::foo();
let y: usize = a::Foo::foo();
assert_eq!(x, 3);
assert_eq!(y, 5);
}
|
foo
|
identifier_name
|
static-methods-in-traits.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
mod a {
pub trait Foo {
fn foo() -> Self;
}
impl Foo for isize {
fn foo() -> isize {
3
}
}
impl Foo for usize {
fn foo() -> usize
|
}
}
pub fn main() {
let x: isize = a::Foo::foo();
let y: usize = a::Foo::foo();
assert_eq!(x, 3);
assert_eq!(y, 5);
}
|
{
5
}
|
identifier_body
|
static-methods-in-traits.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
mod a {
pub trait Foo {
fn foo() -> Self;
}
impl Foo for isize {
fn foo() -> isize {
3
}
}
impl Foo for usize {
fn foo() -> usize {
5
}
}
}
pub fn main() {
let x: isize = a::Foo::foo();
|
}
|
let y: usize = a::Foo::foo();
assert_eq!(x, 3);
assert_eq!(y, 5);
|
random_line_split
|
mkuutils.rs
|
#![feature(exit_status)]
use std::env;
use std::fs::File;
use std::io::{Read, Write};
fn main()
|
util_map.push_str("map.insert(\"sha256sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha384sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha512sum\", hashsum::uumain);\n");
hashsum = true;
}
}
"true" => util_map.push_str("fn uutrue(_: Vec<String>) -> i32 { 0 }\nmap.insert(\"true\", uutrue);\n"),
"false" => util_map.push_str("fn uufalse(_: Vec<String>) -> i32 { 1 }\nmap.insert(\"false\", uufalse);\n"),
_ => {
crates.push_str(&(format!("extern crate {0} as uu{0};\n", prog))[..]);
util_map.push_str(&(format!("map.insert(\"{prog}\", uu{prog}::uumain as fn(Vec<String>) -> i32);\n", prog = prog))[..]);
}
}
}
let outfile = &(args[1])[..];
// XXX: this all just assumes that the IO works correctly
let mut out = File::create(outfile).unwrap();
let mut input = File::open("src/uutils/uutils.rs").unwrap();
let mut template = String::new();
input.read_to_string(&mut template).unwrap();
let template = template;
let main = template.replace("@CRATES@", &crates[..]).replace("@UTIL_MAP@", &util_map[..]);
match out.write_all(main.as_bytes()) {
Err(e) => panic!("{}", e),
_ => (),
}
}
|
{
let args : Vec<String> = env::args().collect();
if args.len() < 3 {
println!("usage: mkuutils <outfile> <crates>");
env::set_exit_status(1);
return;
}
let mut crates = String::new();
let mut util_map = String::new();
let mut hashsum = false;
for prog in args[2..].iter() {
match &prog[..] {
"hashsum" | "md5sum" | "sha1sum" | "sha224sum" | "sha256sum" | "sha384sum" | "sha512sum" => {
if !hashsum {
crates.push_str("extern crate hashsum;\n");
util_map.push_str("map.insert(\"hashsum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"md5sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha1sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha224sum\", hashsum::uumain);\n");
|
identifier_body
|
mkuutils.rs
|
#![feature(exit_status)]
use std::env;
use std::fs::File;
use std::io::{Read, Write};
fn
|
() {
let args : Vec<String> = env::args().collect();
if args.len() < 3 {
println!("usage: mkuutils <outfile> <crates>");
env::set_exit_status(1);
return;
}
let mut crates = String::new();
let mut util_map = String::new();
let mut hashsum = false;
for prog in args[2..].iter() {
match &prog[..] {
"hashsum" | "md5sum" | "sha1sum" | "sha224sum" | "sha256sum" | "sha384sum" | "sha512sum" => {
if!hashsum {
crates.push_str("extern crate hashsum;\n");
util_map.push_str("map.insert(\"hashsum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"md5sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha1sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha224sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha256sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha384sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha512sum\", hashsum::uumain);\n");
hashsum = true;
}
}
"true" => util_map.push_str("fn uutrue(_: Vec<String>) -> i32 { 0 }\nmap.insert(\"true\", uutrue);\n"),
"false" => util_map.push_str("fn uufalse(_: Vec<String>) -> i32 { 1 }\nmap.insert(\"false\", uufalse);\n"),
_ => {
crates.push_str(&(format!("extern crate {0} as uu{0};\n", prog))[..]);
util_map.push_str(&(format!("map.insert(\"{prog}\", uu{prog}::uumain as fn(Vec<String>) -> i32);\n", prog = prog))[..]);
}
}
}
let outfile = &(args[1])[..];
// XXX: this all just assumes that the IO works correctly
let mut out = File::create(outfile).unwrap();
let mut input = File::open("src/uutils/uutils.rs").unwrap();
let mut template = String::new();
input.read_to_string(&mut template).unwrap();
let template = template;
let main = template.replace("@CRATES@", &crates[..]).replace("@UTIL_MAP@", &util_map[..]);
match out.write_all(main.as_bytes()) {
Err(e) => panic!("{}", e),
_ => (),
}
}
|
main
|
identifier_name
|
mkuutils.rs
|
#![feature(exit_status)]
use std::env;
use std::fs::File;
use std::io::{Read, Write};
fn main() {
let args : Vec<String> = env::args().collect();
if args.len() < 3 {
println!("usage: mkuutils <outfile> <crates>");
env::set_exit_status(1);
return;
}
let mut crates = String::new();
let mut util_map = String::new();
let mut hashsum = false;
|
"hashsum" | "md5sum" | "sha1sum" | "sha224sum" | "sha256sum" | "sha384sum" | "sha512sum" => {
if!hashsum {
crates.push_str("extern crate hashsum;\n");
util_map.push_str("map.insert(\"hashsum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"md5sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha1sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha224sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha256sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha384sum\", hashsum::uumain);\n");
util_map.push_str("map.insert(\"sha512sum\", hashsum::uumain);\n");
hashsum = true;
}
}
"true" => util_map.push_str("fn uutrue(_: Vec<String>) -> i32 { 0 }\nmap.insert(\"true\", uutrue);\n"),
"false" => util_map.push_str("fn uufalse(_: Vec<String>) -> i32 { 1 }\nmap.insert(\"false\", uufalse);\n"),
_ => {
crates.push_str(&(format!("extern crate {0} as uu{0};\n", prog))[..]);
util_map.push_str(&(format!("map.insert(\"{prog}\", uu{prog}::uumain as fn(Vec<String>) -> i32);\n", prog = prog))[..]);
}
}
}
let outfile = &(args[1])[..];
// XXX: this all just assumes that the IO works correctly
let mut out = File::create(outfile).unwrap();
let mut input = File::open("src/uutils/uutils.rs").unwrap();
let mut template = String::new();
input.read_to_string(&mut template).unwrap();
let template = template;
let main = template.replace("@CRATES@", &crates[..]).replace("@UTIL_MAP@", &util_map[..]);
match out.write_all(main.as_bytes()) {
Err(e) => panic!("{}", e),
_ => (),
}
}
|
for prog in args[2..].iter() {
match &prog[..] {
|
random_line_split
|
main.rs
|
use std::collections::HashMap;
use std::hash::Hash;
/// Returns the most common element a collection implementing
/// `IntoIterator<Item=T>`, where `T` must implement the `Eq` and `Hash` traits
///
/// ```
/// let v1 = vec![1,3,6,6,6,6,7,7,12,12,17];
/// println!("{}", mode(v1));
/// ```
fn mode<I>(items: I) -> Vec<I::Item>
where
I: IntoIterator,
I::Item: Hash + Eq,
{
// NOTE: Usually, you wouldn't need to explicitly call `into_iter()` before
// looping over a type implementing `IntoIterator`. However, we do it here
// because we need to call `size_hint()` on the iterator so we can
// preallocate the `HashMap`.
let items = items.into_iter();
let (lower_bound, _upper_bound) = items.size_hint();
// Allocate a new HashMap with enough space to fit the lower bound of the
// number of items in `items`.
//
// If the lower bound (`lower_bound`) is the same as the upper bound as
// will be the case for most collections (e.g. `Vec<T>`, `[T]`,
// `HashSet<T>`, etc.) it will be an overestimate on the number of unique
// elements in the collection. This means that, in the common case, we'll
// never have to grow the `HashMap`. While overestimating means we'll likely
// use more memory than necessary, the allocation size will usually be
// proportional to the size of the input collection (assuming it's not a
// lazy collection). This `HashMap` is short lived anyways.
let mut map = HashMap::with_capacity(lower_bound); // HashMap<I::Item, i32>
// Count the number of occurrences of each item.
for item in items {
*map.entry(item).or_insert(0) += 1;
}
// Iterate over the counts, and find the maximum or default to 0.
let max = map.values().cloned().max().unwrap_or(0);
// Iterate by (item, value) pairs and find all modes (there may be multiple).
map.into_iter()
.filter(|&(_, v)| v == max)
.map(|(k, _)| k)
.collect()
}
fn
|
() {
let items = vec![1, 2, 3, 1, 2, 4, 2, 6, 3, 3, 1, 3, 6];
println!("{:?}", mode(&items));
}
#[test]
fn simple_tests() {
let v1 = vec![1, 2, 3, 2, 1];
let mut m1 = mode(v1);
m1.sort_unstable();
assert_eq!(m1, vec![1, 2]);
let v2: &[u64] = &[0xdeadbeef, 0xba5eba11, 0xdeadbeef];
let mut m2 = mode(v2.iter().cloned());
m2.sort_unstable();
assert_eq!(m2, vec![0xdeadbeef]);
let v3 = "Eneyi\u{e4}n";
let mut m3 = mode(v3.chars());
m3.sort_unstable();
assert_eq!(m3, vec!['n']);
let v4 = vec![1, 3, 6, 6, 7, 7, 12, 12, 17];
let mut m4 = mode(&v4);
m4.sort_unstable();
assert_eq!(m4, &[&6, &7, &12]);
}
|
main
|
identifier_name
|
main.rs
|
use std::collections::HashMap;
use std::hash::Hash;
/// Returns the most common element a collection implementing
/// `IntoIterator<Item=T>`, where `T` must implement the `Eq` and `Hash` traits
///
/// ```
/// let v1 = vec![1,3,6,6,6,6,7,7,12,12,17];
/// println!("{}", mode(v1));
/// ```
fn mode<I>(items: I) -> Vec<I::Item>
where
I: IntoIterator,
I::Item: Hash + Eq,
{
// NOTE: Usually, you wouldn't need to explicitly call `into_iter()` before
// looping over a type implementing `IntoIterator`. However, we do it here
// because we need to call `size_hint()` on the iterator so we can
// preallocate the `HashMap`.
let items = items.into_iter();
let (lower_bound, _upper_bound) = items.size_hint();
// Allocate a new HashMap with enough space to fit the lower bound of the
// number of items in `items`.
//
// If the lower bound (`lower_bound`) is the same as the upper bound as
// will be the case for most collections (e.g. `Vec<T>`, `[T]`,
// `HashSet<T>`, etc.) it will be an overestimate on the number of unique
// elements in the collection. This means that, in the common case, we'll
// never have to grow the `HashMap`. While overestimating means we'll likely
// use more memory than necessary, the allocation size will usually be
// proportional to the size of the input collection (assuming it's not a
// lazy collection). This `HashMap` is short lived anyways.
let mut map = HashMap::with_capacity(lower_bound); // HashMap<I::Item, i32>
// Count the number of occurrences of each item.
for item in items {
*map.entry(item).or_insert(0) += 1;
}
// Iterate over the counts, and find the maximum or default to 0.
let max = map.values().cloned().max().unwrap_or(0);
// Iterate by (item, value) pairs and find all modes (there may be multiple).
map.into_iter()
.filter(|&(_, v)| v == max)
.map(|(k, _)| k)
.collect()
}
fn main()
|
#[test]
fn simple_tests() {
let v1 = vec![1, 2, 3, 2, 1];
let mut m1 = mode(v1);
m1.sort_unstable();
assert_eq!(m1, vec![1, 2]);
let v2: &[u64] = &[0xdeadbeef, 0xba5eba11, 0xdeadbeef];
let mut m2 = mode(v2.iter().cloned());
m2.sort_unstable();
assert_eq!(m2, vec![0xdeadbeef]);
let v3 = "Eneyi\u{e4}n";
let mut m3 = mode(v3.chars());
m3.sort_unstable();
assert_eq!(m3, vec!['n']);
let v4 = vec![1, 3, 6, 6, 7, 7, 12, 12, 17];
let mut m4 = mode(&v4);
m4.sort_unstable();
assert_eq!(m4, &[&6, &7, &12]);
}
|
{
let items = vec![1, 2, 3, 1, 2, 4, 2, 6, 3, 3, 1, 3, 6];
println!("{:?}", mode(&items));
}
|
identifier_body
|
main.rs
|
use std::collections::HashMap;
use std::hash::Hash;
/// Returns the most common element a collection implementing
/// `IntoIterator<Item=T>`, where `T` must implement the `Eq` and `Hash` traits
///
/// ```
/// let v1 = vec![1,3,6,6,6,6,7,7,12,12,17];
|
I::Item: Hash + Eq,
{
// NOTE: Usually, you wouldn't need to explicitly call `into_iter()` before
// looping over a type implementing `IntoIterator`. However, we do it here
// because we need to call `size_hint()` on the iterator so we can
// preallocate the `HashMap`.
let items = items.into_iter();
let (lower_bound, _upper_bound) = items.size_hint();
// Allocate a new HashMap with enough space to fit the lower bound of the
// number of items in `items`.
//
// If the lower bound (`lower_bound`) is the same as the upper bound as
// will be the case for most collections (e.g. `Vec<T>`, `[T]`,
// `HashSet<T>`, etc.) it will be an overestimate on the number of unique
// elements in the collection. This means that, in the common case, we'll
// never have to grow the `HashMap`. While overestimating means we'll likely
// use more memory than necessary, the allocation size will usually be
// proportional to the size of the input collection (assuming it's not a
// lazy collection). This `HashMap` is short lived anyways.
let mut map = HashMap::with_capacity(lower_bound); // HashMap<I::Item, i32>
// Count the number of occurrences of each item.
for item in items {
*map.entry(item).or_insert(0) += 1;
}
// Iterate over the counts, and find the maximum or default to 0.
let max = map.values().cloned().max().unwrap_or(0);
// Iterate by (item, value) pairs and find all modes (there may be multiple).
map.into_iter()
.filter(|&(_, v)| v == max)
.map(|(k, _)| k)
.collect()
}
fn main() {
let items = vec![1, 2, 3, 1, 2, 4, 2, 6, 3, 3, 1, 3, 6];
println!("{:?}", mode(&items));
}
#[test]
fn simple_tests() {
let v1 = vec![1, 2, 3, 2, 1];
let mut m1 = mode(v1);
m1.sort_unstable();
assert_eq!(m1, vec![1, 2]);
let v2: &[u64] = &[0xdeadbeef, 0xba5eba11, 0xdeadbeef];
let mut m2 = mode(v2.iter().cloned());
m2.sort_unstable();
assert_eq!(m2, vec![0xdeadbeef]);
let v3 = "Eneyi\u{e4}n";
let mut m3 = mode(v3.chars());
m3.sort_unstable();
assert_eq!(m3, vec!['n']);
let v4 = vec![1, 3, 6, 6, 7, 7, 12, 12, 17];
let mut m4 = mode(&v4);
m4.sort_unstable();
assert_eq!(m4, &[&6, &7, &12]);
}
|
/// println!("{}", mode(v1));
/// ```
fn mode<I>(items: I) -> Vec<I::Item>
where
I: IntoIterator,
|
random_line_split
|
material_mutation_resolvers.rs
|
use chrono::prelude::*;
use async_graphql::{
FieldResult,
ID,
Context,
};
use eyre::{
Context as _,
// eyre,
// Result
};
// use printspool_json_store::Record as _;
use printspool_auth::AuthContext;
use printspool_json_store::Record;
use crate::{FdmFilament, MaterialTypeGQL, material::{
Material,
MaterialConfigEnum,
}};
// Input Types
// ---------------------------------------------
#[derive(async_graphql::InputObject, Debug)]
pub struct CreateMaterialInput {
pub material_type: MaterialTypeGQL,
pub model: async_graphql::Json<serde_json::Value>,
}
#[derive(async_graphql::InputObject, Debug)]
pub struct UpdateMaterialInput {
#[graphql(name="materialID")]
pub material_id: ID,
pub model_version: i32,
pub model: async_graphql::Json<serde_json::Value>,
}
#[derive(async_graphql::InputObject)]
pub struct DeleteMaterialInput {
#[graphql(name="materialID")]
pub material_id: ID,
}
// Resolvers
// ---------------------------------------------
#[derive(Default)]
pub struct MaterialMutation;
#[async_graphql::Object]
impl MaterialMutation {
async fn create_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: CreateMaterialInput,
) -> FieldResult<Material> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
auth.authorize_admins_only()?;
let config = match input.material_type {
MaterialTypeGQL::FdmFilament => {
let config: FdmFilament = serde_json::from_value(input.model.0)?;
MaterialConfigEnum::FdmFilament(Box::new(config))
}
};
let material = Material {
id: nanoid!(11),
version: 0,
created_at: Utc::now(),
deleted_at: None,
config,
};
material.insert(db).await?;
Ok(material)
}
#[instrument(skip(self, ctx))]
async fn update_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: UpdateMaterialInput,
) -> FieldResult<Material> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
let material_hooks: &crate::MaterialHooksList = ctx.data()?;
auth.authorize_admins_only()?;
async move {
let mut material = Material::get_with_version(
db,
&input.material_id,
input.model_version,
false,
).await?;
material.config = match material.config {
MaterialConfigEnum::FdmFilament(_) =>
|
};
material.update(db).await?;
for hooks_provider in material_hooks.iter() {
hooks_provider.after_update(
&material.id
).await?;
}
Ok(material)
}
// log the backtrace which is otherwise lost by FieldResult
.await
.map_err(|err: eyre::Error| {
warn!("{:?}", err);
err.into()
})
}
async fn delete_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: DeleteMaterialInput
) -> FieldResult<Option<printspool_common::Void>> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
auth.authorize_admins_only()?;
let DeleteMaterialInput { material_id } = input;
Material::get(db, &material_id.0, true)
.await?
.remove(db, false)
.await
.wrap_err_with(|| "Error deleting material")?;
Ok(None)
}
}
|
{
let config: FdmFilament = serde_json::from_value(input.model.0)?;
MaterialConfigEnum::FdmFilament(Box::new(config))
}
|
conditional_block
|
material_mutation_resolvers.rs
|
use chrono::prelude::*;
use async_graphql::{
FieldResult,
ID,
Context,
};
use eyre::{
Context as _,
// eyre,
// Result
};
// use printspool_json_store::Record as _;
use printspool_auth::AuthContext;
use printspool_json_store::Record;
use crate::{FdmFilament, MaterialTypeGQL, material::{
Material,
MaterialConfigEnum,
}};
// Input Types
// ---------------------------------------------
#[derive(async_graphql::InputObject, Debug)]
pub struct CreateMaterialInput {
pub material_type: MaterialTypeGQL,
pub model: async_graphql::Json<serde_json::Value>,
}
#[derive(async_graphql::InputObject, Debug)]
pub struct UpdateMaterialInput {
#[graphql(name="materialID")]
pub material_id: ID,
pub model_version: i32,
pub model: async_graphql::Json<serde_json::Value>,
}
#[derive(async_graphql::InputObject)]
pub struct DeleteMaterialInput {
#[graphql(name="materialID")]
pub material_id: ID,
}
// Resolvers
// ---------------------------------------------
#[derive(Default)]
pub struct MaterialMutation;
#[async_graphql::Object]
impl MaterialMutation {
async fn create_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: CreateMaterialInput,
) -> FieldResult<Material> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
auth.authorize_admins_only()?;
let config = match input.material_type {
MaterialTypeGQL::FdmFilament => {
let config: FdmFilament = serde_json::from_value(input.model.0)?;
MaterialConfigEnum::FdmFilament(Box::new(config))
}
};
let material = Material {
id: nanoid!(11),
version: 0,
created_at: Utc::now(),
deleted_at: None,
config,
};
material.insert(db).await?;
Ok(material)
}
#[instrument(skip(self, ctx))]
async fn update_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: UpdateMaterialInput,
) -> FieldResult<Material> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
let material_hooks: &crate::MaterialHooksList = ctx.data()?;
auth.authorize_admins_only()?;
async move {
let mut material = Material::get_with_version(
db,
&input.material_id,
input.model_version,
false,
).await?;
material.config = match material.config {
MaterialConfigEnum::FdmFilament(_) => {
let config: FdmFilament = serde_json::from_value(input.model.0)?;
MaterialConfigEnum::FdmFilament(Box::new(config))
}
};
material.update(db).await?;
for hooks_provider in material_hooks.iter() {
hooks_provider.after_update(
&material.id
).await?;
}
Ok(material)
}
// log the backtrace which is otherwise lost by FieldResult
.await
.map_err(|err: eyre::Error| {
warn!("{:?}", err);
err.into()
})
}
async fn
|
<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: DeleteMaterialInput
) -> FieldResult<Option<printspool_common::Void>> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
auth.authorize_admins_only()?;
let DeleteMaterialInput { material_id } = input;
Material::get(db, &material_id.0, true)
.await?
.remove(db, false)
.await
.wrap_err_with(|| "Error deleting material")?;
Ok(None)
}
}
|
delete_material
|
identifier_name
|
material_mutation_resolvers.rs
|
use chrono::prelude::*;
use async_graphql::{
FieldResult,
ID,
Context,
};
use eyre::{
Context as _,
// eyre,
// Result
};
// use printspool_json_store::Record as _;
use printspool_auth::AuthContext;
use printspool_json_store::Record;
use crate::{FdmFilament, MaterialTypeGQL, material::{
Material,
MaterialConfigEnum,
}};
// Input Types
// ---------------------------------------------
#[derive(async_graphql::InputObject, Debug)]
pub struct CreateMaterialInput {
pub material_type: MaterialTypeGQL,
pub model: async_graphql::Json<serde_json::Value>,
}
#[derive(async_graphql::InputObject, Debug)]
pub struct UpdateMaterialInput {
#[graphql(name="materialID")]
pub material_id: ID,
pub model_version: i32,
pub model: async_graphql::Json<serde_json::Value>,
}
#[derive(async_graphql::InputObject)]
pub struct DeleteMaterialInput {
#[graphql(name="materialID")]
pub material_id: ID,
}
// Resolvers
// ---------------------------------------------
#[derive(Default)]
pub struct MaterialMutation;
#[async_graphql::Object]
impl MaterialMutation {
async fn create_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: CreateMaterialInput,
) -> FieldResult<Material> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
auth.authorize_admins_only()?;
let config = match input.material_type {
MaterialTypeGQL::FdmFilament => {
let config: FdmFilament = serde_json::from_value(input.model.0)?;
MaterialConfigEnum::FdmFilament(Box::new(config))
}
};
let material = Material {
id: nanoid!(11),
version: 0,
created_at: Utc::now(),
|
material.insert(db).await?;
Ok(material)
}
#[instrument(skip(self, ctx))]
async fn update_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: UpdateMaterialInput,
) -> FieldResult<Material> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
let material_hooks: &crate::MaterialHooksList = ctx.data()?;
auth.authorize_admins_only()?;
async move {
let mut material = Material::get_with_version(
db,
&input.material_id,
input.model_version,
false,
).await?;
material.config = match material.config {
MaterialConfigEnum::FdmFilament(_) => {
let config: FdmFilament = serde_json::from_value(input.model.0)?;
MaterialConfigEnum::FdmFilament(Box::new(config))
}
};
material.update(db).await?;
for hooks_provider in material_hooks.iter() {
hooks_provider.after_update(
&material.id
).await?;
}
Ok(material)
}
// log the backtrace which is otherwise lost by FieldResult
.await
.map_err(|err: eyre::Error| {
warn!("{:?}", err);
err.into()
})
}
async fn delete_material<'ctx>(
&self,
ctx: &'ctx Context<'_>,
input: DeleteMaterialInput
) -> FieldResult<Option<printspool_common::Void>> {
let db: &crate::Db = ctx.data()?;
let auth: &AuthContext = ctx.data()?;
auth.authorize_admins_only()?;
let DeleteMaterialInput { material_id } = input;
Material::get(db, &material_id.0, true)
.await?
.remove(db, false)
.await
.wrap_err_with(|| "Error deleting material")?;
Ok(None)
}
}
|
deleted_at: None,
config,
};
|
random_line_split
|
triangle.rs
|
extern mod gl;
extern mod glfw;
extern mod sgl;
use sgl::vertex_buffer::*;
use sgl::vertex_array::*;
use sgl::shader::*;
use sgl::shader_program::*;
#[start]
fn start(argc: int, argv: **u8, crate_map: *u8) -> int {
// Run GLFW on the main thread
std::rt::start_on_main_thread(argc, argv, crate_map, main)
}
fn main() {
static vertices: [gl::types::GLfloat,..6] = [
-0.5, -0.5,
0.5, -0.5,
-0.5, 0.5
];
do glfw::set_error_callback |_, description| {
printfln!("GLFW Error: %s", description);
}
do glfw::start {
// Choose a GL profile that is compatible with OS X 10.7+
glfw::window_hint::context_version(3, 2);
glfw::window_hint::opengl_profile(glfw::OPENGL_CORE_PROFILE);
glfw::window_hint::opengl_forward_compat(true);
let window = glfw::Window::create(800, 600, "OpenGL", glfw::Windowed).unwrap();
window.make_context_current();
// Load the OpenGL function pointers
gl::load_with(glfw::get_proc_address);
// Create Vertex Array Object
// Create a Vertex Buffer Object and copy the vertex data to it
let vbo = VertexBuffer::new();
vbo.set_buffer_data(vertices,
gl::STATIC_DRAW);
let vertex_source = std::io::read_whole_file_str(&std::path::Path("triangle.vs")).unwrap();
let fragment_source = std::io::read_whole_file_str(&std::path::Path("triangle.fs")).unwrap();
// Create and compile the vertex shader
let vertex_shader = Shader::new_vs(vertex_source).unwrap();
// Create and compile the fragment shader
let fragment_shader = Shader::new_fs(fragment_source).unwrap();
// Link the vertex and fragment shader into a shader program
let shader_program = ShaderProgram::new([&vertex_shader,
&fragment_shader]).unwrap();
shader_program.use_program();
//shader_program.bind_frag_location(1,~"123123outColor");
let vao = VertexArray::new();
vao.bind_attrib(shader_program.get_attrib_location("position"),
2,
&vbo);
while!window.should_close() {
// Poll events
glfw::poll_events();
// Clear the screen to black
gl::ClearColor(0.0, 0.0, 0.0, 1.0);
gl::Clear(gl::COLOR_BUFFER_BIT);
vao.bind();
gl::DrawArrays(gl::TRIANGLES, 0, 3);
|
// Swap buffers
window.swap_buffers();
}
}
}
|
random_line_split
|
|
triangle.rs
|
extern mod gl;
extern mod glfw;
extern mod sgl;
use sgl::vertex_buffer::*;
use sgl::vertex_array::*;
use sgl::shader::*;
use sgl::shader_program::*;
#[start]
fn start(argc: int, argv: **u8, crate_map: *u8) -> int {
// Run GLFW on the main thread
std::rt::start_on_main_thread(argc, argv, crate_map, main)
}
fn main()
|
// Load the OpenGL function pointers
gl::load_with(glfw::get_proc_address);
// Create Vertex Array Object
// Create a Vertex Buffer Object and copy the vertex data to it
let vbo = VertexBuffer::new();
vbo.set_buffer_data(vertices,
gl::STATIC_DRAW);
let vertex_source = std::io::read_whole_file_str(&std::path::Path("triangle.vs")).unwrap();
let fragment_source = std::io::read_whole_file_str(&std::path::Path("triangle.fs")).unwrap();
// Create and compile the vertex shader
let vertex_shader = Shader::new_vs(vertex_source).unwrap();
// Create and compile the fragment shader
let fragment_shader = Shader::new_fs(fragment_source).unwrap();
// Link the vertex and fragment shader into a shader program
let shader_program = ShaderProgram::new([&vertex_shader,
&fragment_shader]).unwrap();
shader_program.use_program();
//shader_program.bind_frag_location(1,~"123123outColor");
let vao = VertexArray::new();
vao.bind_attrib(shader_program.get_attrib_location("position"),
2,
&vbo);
while!window.should_close() {
// Poll events
glfw::poll_events();
// Clear the screen to black
gl::ClearColor(0.0, 0.0, 0.0, 1.0);
gl::Clear(gl::COLOR_BUFFER_BIT);
vao.bind();
gl::DrawArrays(gl::TRIANGLES, 0, 3);
// Swap buffers
window.swap_buffers();
}
}
}
|
{
static vertices: [gl::types::GLfloat, ..6] = [
-0.5, -0.5,
0.5, -0.5,
-0.5, 0.5
];
do glfw::set_error_callback |_, description| {
printfln!("GLFW Error: %s", description);
}
do glfw::start {
// Choose a GL profile that is compatible with OS X 10.7+
glfw::window_hint::context_version(3, 2);
glfw::window_hint::opengl_profile(glfw::OPENGL_CORE_PROFILE);
glfw::window_hint::opengl_forward_compat(true);
let window = glfw::Window::create(800, 600, "OpenGL", glfw::Windowed).unwrap();
window.make_context_current();
|
identifier_body
|
triangle.rs
|
extern mod gl;
extern mod glfw;
extern mod sgl;
use sgl::vertex_buffer::*;
use sgl::vertex_array::*;
use sgl::shader::*;
use sgl::shader_program::*;
#[start]
fn start(argc: int, argv: **u8, crate_map: *u8) -> int {
// Run GLFW on the main thread
std::rt::start_on_main_thread(argc, argv, crate_map, main)
}
fn
|
() {
static vertices: [gl::types::GLfloat,..6] = [
-0.5, -0.5,
0.5, -0.5,
-0.5, 0.5
];
do glfw::set_error_callback |_, description| {
printfln!("GLFW Error: %s", description);
}
do glfw::start {
// Choose a GL profile that is compatible with OS X 10.7+
glfw::window_hint::context_version(3, 2);
glfw::window_hint::opengl_profile(glfw::OPENGL_CORE_PROFILE);
glfw::window_hint::opengl_forward_compat(true);
let window = glfw::Window::create(800, 600, "OpenGL", glfw::Windowed).unwrap();
window.make_context_current();
// Load the OpenGL function pointers
gl::load_with(glfw::get_proc_address);
// Create Vertex Array Object
// Create a Vertex Buffer Object and copy the vertex data to it
let vbo = VertexBuffer::new();
vbo.set_buffer_data(vertices,
gl::STATIC_DRAW);
let vertex_source = std::io::read_whole_file_str(&std::path::Path("triangle.vs")).unwrap();
let fragment_source = std::io::read_whole_file_str(&std::path::Path("triangle.fs")).unwrap();
// Create and compile the vertex shader
let vertex_shader = Shader::new_vs(vertex_source).unwrap();
// Create and compile the fragment shader
let fragment_shader = Shader::new_fs(fragment_source).unwrap();
// Link the vertex and fragment shader into a shader program
let shader_program = ShaderProgram::new([&vertex_shader,
&fragment_shader]).unwrap();
shader_program.use_program();
//shader_program.bind_frag_location(1,~"123123outColor");
let vao = VertexArray::new();
vao.bind_attrib(shader_program.get_attrib_location("position"),
2,
&vbo);
while!window.should_close() {
// Poll events
glfw::poll_events();
// Clear the screen to black
gl::ClearColor(0.0, 0.0, 0.0, 1.0);
gl::Clear(gl::COLOR_BUFFER_BIT);
vao.bind();
gl::DrawArrays(gl::TRIANGLES, 0, 3);
// Swap buffers
window.swap_buffers();
}
}
}
|
main
|
identifier_name
|
os_str.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A type that can represent all platform-native strings, but is cheaply
//! interconvertable with Rust strings.
//!
//! The need for this type arises from the fact that:
//!
//! * On Unix systems, strings are often arbitrary sequences of non-zero
//! bytes, in many cases interpreted as UTF-8.
//!
//! * On Windows, strings are often arbitrary sequences of non-zero 16-bit
//! values, interpreted as UTF-16 when it is valid to do so.
//!
//! * In Rust, strings are always valid UTF-8, but may contain zeros.
//!
//! The types in this module bridge this gap by simultaneously representing Rust
//! and platform-native string values, and in particular allowing a Rust string
//! to be converted into an "OS" string with no cost.
//!
//! **Note**: At the moment, these types are extremely bare-bones, usable only
//! for conversion to/from various other string types. Eventually these types
//! will offer a full-fledged string API.
#![unstable(feature = "os",
reason = "recently added as part of path/io reform")]
use core::prelude::*;
use borrow::{Borrow, Cow, ToOwned};
use fmt::{self, Debug};
use mem;
use string::String;
use ops;
use cmp;
use hash::{Hash, Hasher};
use old_path::{Path, GenericPath};
use sys::os_str::{Buf, Slice};
use sys_common::{AsInner, IntoInner, FromInner};
use super::AsOsStr;
/// Owned, mutable OS strings.
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct OsString {
inner: Buf
}
/// Slices into OS strings.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct OsStr {
inner: Slice
}
impl OsString {
/// Constructs an `OsString` at no cost by consuming a `String`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_string(s: String) -> OsString {
OsString { inner: Buf::from_string(s) }
}
/// Constructs an `OsString` by copying from a `&str` slice.
///
/// Equivalent to: `OsString::from_string(String::from_str(s))`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str(s: &str) -> OsString {
OsString { inner: Buf::from_str(s) }
}
/// Constructs a new empty `OsString`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> OsString {
OsString { inner: Buf::from_string(String::new()) }
}
/// Convert the `OsString` into a `String` if it contains valid Unicode data.
///
/// On failure, ownership of the original `OsString` is returned.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_string(self) -> Result<String, OsString> {
self.inner.into_string().map_err(|buf| OsString { inner: buf} )
}
/// Extend the string with the given `&OsStr` slice.
#[deprecated(since = "1.0.0", reason = "renamed to `push`")]
#[unstable(feature = "os")]
pub fn push_os_str(&mut self, s: &OsStr) {
self.inner.push_slice(&s.inner)
}
/// Extend the string with the given `&OsStr` slice.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push<T: AsOsStr +?Sized>(&mut self, s: &T) {
self.inner.push_slice(&s.as_os_str().inner)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFull> for OsString {
type Output = OsStr;
#[inline]
fn index(&self, _index: &ops::RangeFull) -> &OsStr {
unsafe { mem::transmute(self.inner.as_slice()) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Deref for OsString {
type Target = OsStr;
#[inline]
fn deref(&self) -> &OsStr {
&self[..]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for OsString {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&**self, formatter)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for OsString {
fn eq(&self, other: &OsString) -> bool {
&**self == &**other
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<str> for OsString {
fn eq(&self, other: &str) -> bool {
&**self == other
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<OsString> for str {
fn eq(&self, other: &OsString) -> bool {
&**other == self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Eq for OsString {}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd for OsString {
#[inline]
fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
(&**self).partial_cmp(&**other)
}
#[inline]
fn lt(&self, other: &OsString) -> bool { &**self < &**other }
#[inline]
fn le(&self, other: &OsString) -> bool { &**self <= &**other }
#[inline]
fn gt(&self, other: &OsString) -> bool { &**self > &**other }
#[inline]
fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd<str> for OsString {
#[inline]
fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
(&**self).partial_cmp(other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for OsString {
#[inline]
fn cmp(&self, other: &OsString) -> cmp::Ordering
|
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Hash for OsString {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
(&**self).hash(state)
}
}
impl OsStr {
/// Coerce directly from a `&str` slice to a `&OsStr` slice.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str(s: &str) -> &OsStr {
unsafe { mem::transmute(Slice::from_str(s)) }
}
/// Yield a `&str` slice if the `OsStr` is valid unicode.
///
/// This conversion may entail doing a check for UTF-8 validity.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_str(&self) -> Option<&str> {
self.inner.to_str()
}
/// Convert an `OsStr` to a `Cow<str>`.
///
/// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_string_lossy(&self) -> Cow<str> {
self.inner.to_string_lossy()
}
/// Copy the slice into an owned `OsString`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_os_string(&self) -> OsString {
OsString { inner: self.inner.to_owned() }
}
/// Get the underlying byte representation.
///
/// Note: it is *crucial* that this API is private, to avoid
/// revealing the internal, platform-specific encodings.
fn bytes(&self) -> &[u8] {
unsafe { mem::transmute(&self.inner) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for OsStr {
fn eq(&self, other: &OsStr) -> bool {
self.bytes().eq(other.bytes())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<str> for OsStr {
fn eq(&self, other: &str) -> bool {
*self == *OsStr::from_str(other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<OsStr> for str {
fn eq(&self, other: &OsStr) -> bool {
*other == *OsStr::from_str(self)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Eq for OsStr {}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd for OsStr {
#[inline]
fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
self.bytes().partial_cmp(other.bytes())
}
#[inline]
fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
#[inline]
fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
#[inline]
fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
#[inline]
fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd<str> for OsStr {
#[inline]
fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
self.partial_cmp(OsStr::from_str(other))
}
}
// FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
// have more flexible coherence rules.
#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for OsStr {
#[inline]
fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Hash for OsStr {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.bytes().hash(state)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for OsStr {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.inner.fmt(formatter)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Borrow<OsStr> for OsString {
fn borrow(&self) -> &OsStr { &self[..] }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ToOwned for OsStr {
type Owned = OsString;
fn to_owned(&self) -> OsString { self.to_os_string() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: AsOsStr +?Sized> AsOsStr for &'a T {
fn as_os_str(&self) -> &OsStr {
(*self).as_os_str()
}
}
impl AsOsStr for OsStr {
fn as_os_str(&self) -> &OsStr {
self
}
}
impl AsOsStr for OsString {
fn as_os_str(&self) -> &OsStr {
&self[..]
}
}
impl AsOsStr for str {
fn as_os_str(&self) -> &OsStr {
OsStr::from_str(self)
}
}
impl AsOsStr for String {
fn as_os_str(&self) -> &OsStr {
OsStr::from_str(&self[..])
}
}
impl AsOsStr for Path {
#[cfg(unix)]
fn as_os_str(&self) -> &OsStr {
unsafe { mem::transmute(self.as_vec()) }
}
#[cfg(windows)]
fn as_os_str(&self) -> &OsStr {
// currently.as_str() is actually infallible on windows
OsStr::from_str(self.as_str().unwrap())
}
}
impl FromInner<Buf> for OsString {
fn from_inner(buf: Buf) -> OsString {
OsString { inner: buf }
}
}
impl IntoInner<Buf> for OsString {
fn into_inner(self) -> Buf {
self.inner
}
}
impl AsInner<Slice> for OsStr {
fn as_inner(&self) -> &Slice {
&self.inner
}
}
|
{
(&**self).cmp(&**other)
}
|
identifier_body
|
os_str.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A type that can represent all platform-native strings, but is cheaply
//! interconvertable with Rust strings.
//!
//! The need for this type arises from the fact that:
//!
//! * On Unix systems, strings are often arbitrary sequences of non-zero
//! bytes, in many cases interpreted as UTF-8.
//!
//! * On Windows, strings are often arbitrary sequences of non-zero 16-bit
//! values, interpreted as UTF-16 when it is valid to do so.
//!
//! * In Rust, strings are always valid UTF-8, but may contain zeros.
//!
//! The types in this module bridge this gap by simultaneously representing Rust
//! and platform-native string values, and in particular allowing a Rust string
//! to be converted into an "OS" string with no cost.
//!
//! **Note**: At the moment, these types are extremely bare-bones, usable only
//! for conversion to/from various other string types. Eventually these types
//! will offer a full-fledged string API.
#![unstable(feature = "os",
reason = "recently added as part of path/io reform")]
use core::prelude::*;
use borrow::{Borrow, Cow, ToOwned};
use fmt::{self, Debug};
use mem;
use string::String;
use ops;
use cmp;
use hash::{Hash, Hasher};
use old_path::{Path, GenericPath};
use sys::os_str::{Buf, Slice};
use sys_common::{AsInner, IntoInner, FromInner};
use super::AsOsStr;
/// Owned, mutable OS strings.
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct OsString {
inner: Buf
}
/// Slices into OS strings.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct OsStr {
inner: Slice
}
impl OsString {
/// Constructs an `OsString` at no cost by consuming a `String`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_string(s: String) -> OsString {
OsString { inner: Buf::from_string(s) }
}
/// Constructs an `OsString` by copying from a `&str` slice.
///
/// Equivalent to: `OsString::from_string(String::from_str(s))`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str(s: &str) -> OsString {
OsString { inner: Buf::from_str(s) }
}
/// Constructs a new empty `OsString`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> OsString {
OsString { inner: Buf::from_string(String::new()) }
}
/// Convert the `OsString` into a `String` if it contains valid Unicode data.
///
/// On failure, ownership of the original `OsString` is returned.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_string(self) -> Result<String, OsString> {
self.inner.into_string().map_err(|buf| OsString { inner: buf} )
}
/// Extend the string with the given `&OsStr` slice.
#[deprecated(since = "1.0.0", reason = "renamed to `push`")]
#[unstable(feature = "os")]
pub fn push_os_str(&mut self, s: &OsStr) {
self.inner.push_slice(&s.inner)
}
/// Extend the string with the given `&OsStr` slice.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push<T: AsOsStr +?Sized>(&mut self, s: &T) {
self.inner.push_slice(&s.as_os_str().inner)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFull> for OsString {
type Output = OsStr;
#[inline]
fn index(&self, _index: &ops::RangeFull) -> &OsStr {
unsafe { mem::transmute(self.inner.as_slice()) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Deref for OsString {
type Target = OsStr;
#[inline]
fn deref(&self) -> &OsStr {
&self[..]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for OsString {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&**self, formatter)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for OsString {
fn eq(&self, other: &OsString) -> bool {
&**self == &**other
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<str> for OsString {
fn eq(&self, other: &str) -> bool {
&**self == other
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<OsString> for str {
fn eq(&self, other: &OsString) -> bool {
&**other == self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Eq for OsString {}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd for OsString {
#[inline]
fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
(&**self).partial_cmp(&**other)
}
#[inline]
fn lt(&self, other: &OsString) -> bool { &**self < &**other }
#[inline]
fn le(&self, other: &OsString) -> bool { &**self <= &**other }
#[inline]
fn gt(&self, other: &OsString) -> bool { &**self > &**other }
#[inline]
fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd<str> for OsString {
#[inline]
fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
(&**self).partial_cmp(other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for OsString {
#[inline]
fn cmp(&self, other: &OsString) -> cmp::Ordering {
(&**self).cmp(&**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Hash for OsString {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
(&**self).hash(state)
}
}
impl OsStr {
/// Coerce directly from a `&str` slice to a `&OsStr` slice.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str(s: &str) -> &OsStr {
unsafe { mem::transmute(Slice::from_str(s)) }
}
/// Yield a `&str` slice if the `OsStr` is valid unicode.
///
/// This conversion may entail doing a check for UTF-8 validity.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_str(&self) -> Option<&str> {
self.inner.to_str()
}
/// Convert an `OsStr` to a `Cow<str>`.
///
/// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_string_lossy(&self) -> Cow<str> {
self.inner.to_string_lossy()
}
/// Copy the slice into an owned `OsString`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_os_string(&self) -> OsString {
OsString { inner: self.inner.to_owned() }
}
/// Get the underlying byte representation.
///
/// Note: it is *crucial* that this API is private, to avoid
/// revealing the internal, platform-specific encodings.
fn bytes(&self) -> &[u8] {
unsafe { mem::transmute(&self.inner) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for OsStr {
fn eq(&self, other: &OsStr) -> bool {
self.bytes().eq(other.bytes())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<str> for OsStr {
fn eq(&self, other: &str) -> bool {
*self == *OsStr::from_str(other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<OsStr> for str {
fn eq(&self, other: &OsStr) -> bool {
*other == *OsStr::from_str(self)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Eq for OsStr {}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd for OsStr {
#[inline]
fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
self.bytes().partial_cmp(other.bytes())
}
#[inline]
fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
#[inline]
fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
#[inline]
fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
#[inline]
fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd<str> for OsStr {
#[inline]
fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
self.partial_cmp(OsStr::from_str(other))
}
}
// FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
// have more flexible coherence rules.
#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for OsStr {
#[inline]
fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Hash for OsStr {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.bytes().hash(state)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for OsStr {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.inner.fmt(formatter)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Borrow<OsStr> for OsString {
fn borrow(&self) -> &OsStr { &self[..] }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ToOwned for OsStr {
type Owned = OsString;
fn to_owned(&self) -> OsString { self.to_os_string() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: AsOsStr +?Sized> AsOsStr for &'a T {
fn as_os_str(&self) -> &OsStr {
(*self).as_os_str()
}
}
impl AsOsStr for OsStr {
fn
|
(&self) -> &OsStr {
self
}
}
impl AsOsStr for OsString {
fn as_os_str(&self) -> &OsStr {
&self[..]
}
}
impl AsOsStr for str {
fn as_os_str(&self) -> &OsStr {
OsStr::from_str(self)
}
}
impl AsOsStr for String {
fn as_os_str(&self) -> &OsStr {
OsStr::from_str(&self[..])
}
}
impl AsOsStr for Path {
#[cfg(unix)]
fn as_os_str(&self) -> &OsStr {
unsafe { mem::transmute(self.as_vec()) }
}
#[cfg(windows)]
fn as_os_str(&self) -> &OsStr {
// currently.as_str() is actually infallible on windows
OsStr::from_str(self.as_str().unwrap())
}
}
impl FromInner<Buf> for OsString {
fn from_inner(buf: Buf) -> OsString {
OsString { inner: buf }
}
}
impl IntoInner<Buf> for OsString {
fn into_inner(self) -> Buf {
self.inner
}
}
impl AsInner<Slice> for OsStr {
fn as_inner(&self) -> &Slice {
&self.inner
}
}
|
as_os_str
|
identifier_name
|
os_str.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A type that can represent all platform-native strings, but is cheaply
//! interconvertable with Rust strings.
//!
//! The need for this type arises from the fact that:
//!
//! * On Unix systems, strings are often arbitrary sequences of non-zero
//! bytes, in many cases interpreted as UTF-8.
|
//!
//! * In Rust, strings are always valid UTF-8, but may contain zeros.
//!
//! The types in this module bridge this gap by simultaneously representing Rust
//! and platform-native string values, and in particular allowing a Rust string
//! to be converted into an "OS" string with no cost.
//!
//! **Note**: At the moment, these types are extremely bare-bones, usable only
//! for conversion to/from various other string types. Eventually these types
//! will offer a full-fledged string API.
#![unstable(feature = "os",
reason = "recently added as part of path/io reform")]
use core::prelude::*;
use borrow::{Borrow, Cow, ToOwned};
use fmt::{self, Debug};
use mem;
use string::String;
use ops;
use cmp;
use hash::{Hash, Hasher};
use old_path::{Path, GenericPath};
use sys::os_str::{Buf, Slice};
use sys_common::{AsInner, IntoInner, FromInner};
use super::AsOsStr;
/// Owned, mutable OS strings.
#[derive(Clone)]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct OsString {
inner: Buf
}
/// Slices into OS strings.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct OsStr {
inner: Slice
}
impl OsString {
/// Constructs an `OsString` at no cost by consuming a `String`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_string(s: String) -> OsString {
OsString { inner: Buf::from_string(s) }
}
/// Constructs an `OsString` by copying from a `&str` slice.
///
/// Equivalent to: `OsString::from_string(String::from_str(s))`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str(s: &str) -> OsString {
OsString { inner: Buf::from_str(s) }
}
/// Constructs a new empty `OsString`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn new() -> OsString {
OsString { inner: Buf::from_string(String::new()) }
}
/// Convert the `OsString` into a `String` if it contains valid Unicode data.
///
/// On failure, ownership of the original `OsString` is returned.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn into_string(self) -> Result<String, OsString> {
self.inner.into_string().map_err(|buf| OsString { inner: buf} )
}
/// Extend the string with the given `&OsStr` slice.
#[deprecated(since = "1.0.0", reason = "renamed to `push`")]
#[unstable(feature = "os")]
pub fn push_os_str(&mut self, s: &OsStr) {
self.inner.push_slice(&s.inner)
}
/// Extend the string with the given `&OsStr` slice.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn push<T: AsOsStr +?Sized>(&mut self, s: &T) {
self.inner.push_slice(&s.as_os_str().inner)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Index<ops::RangeFull> for OsString {
type Output = OsStr;
#[inline]
fn index(&self, _index: &ops::RangeFull) -> &OsStr {
unsafe { mem::transmute(self.inner.as_slice()) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ops::Deref for OsString {
type Target = OsStr;
#[inline]
fn deref(&self) -> &OsStr {
&self[..]
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for OsString {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&**self, formatter)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for OsString {
fn eq(&self, other: &OsString) -> bool {
&**self == &**other
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<str> for OsString {
fn eq(&self, other: &str) -> bool {
&**self == other
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<OsString> for str {
fn eq(&self, other: &OsString) -> bool {
&**other == self
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Eq for OsString {}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd for OsString {
#[inline]
fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
(&**self).partial_cmp(&**other)
}
#[inline]
fn lt(&self, other: &OsString) -> bool { &**self < &**other }
#[inline]
fn le(&self, other: &OsString) -> bool { &**self <= &**other }
#[inline]
fn gt(&self, other: &OsString) -> bool { &**self > &**other }
#[inline]
fn ge(&self, other: &OsString) -> bool { &**self >= &**other }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd<str> for OsString {
#[inline]
fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
(&**self).partial_cmp(other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for OsString {
#[inline]
fn cmp(&self, other: &OsString) -> cmp::Ordering {
(&**self).cmp(&**other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Hash for OsString {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
(&**self).hash(state)
}
}
impl OsStr {
/// Coerce directly from a `&str` slice to a `&OsStr` slice.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn from_str(s: &str) -> &OsStr {
unsafe { mem::transmute(Slice::from_str(s)) }
}
/// Yield a `&str` slice if the `OsStr` is valid unicode.
///
/// This conversion may entail doing a check for UTF-8 validity.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_str(&self) -> Option<&str> {
self.inner.to_str()
}
/// Convert an `OsStr` to a `Cow<str>`.
///
/// Any non-Unicode sequences are replaced with U+FFFD REPLACEMENT CHARACTER.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_string_lossy(&self) -> Cow<str> {
self.inner.to_string_lossy()
}
/// Copy the slice into an owned `OsString`.
#[stable(feature = "rust1", since = "1.0.0")]
pub fn to_os_string(&self) -> OsString {
OsString { inner: self.inner.to_owned() }
}
/// Get the underlying byte representation.
///
/// Note: it is *crucial* that this API is private, to avoid
/// revealing the internal, platform-specific encodings.
fn bytes(&self) -> &[u8] {
unsafe { mem::transmute(&self.inner) }
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq for OsStr {
fn eq(&self, other: &OsStr) -> bool {
self.bytes().eq(other.bytes())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<str> for OsStr {
fn eq(&self, other: &str) -> bool {
*self == *OsStr::from_str(other)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialEq<OsStr> for str {
fn eq(&self, other: &OsStr) -> bool {
*other == *OsStr::from_str(self)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Eq for OsStr {}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd for OsStr {
#[inline]
fn partial_cmp(&self, other: &OsStr) -> Option<cmp::Ordering> {
self.bytes().partial_cmp(other.bytes())
}
#[inline]
fn lt(&self, other: &OsStr) -> bool { self.bytes().lt(other.bytes()) }
#[inline]
fn le(&self, other: &OsStr) -> bool { self.bytes().le(other.bytes()) }
#[inline]
fn gt(&self, other: &OsStr) -> bool { self.bytes().gt(other.bytes()) }
#[inline]
fn ge(&self, other: &OsStr) -> bool { self.bytes().ge(other.bytes()) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl PartialOrd<str> for OsStr {
#[inline]
fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
self.partial_cmp(OsStr::from_str(other))
}
}
// FIXME (#19470): cannot provide PartialOrd<OsStr> for str until we
// have more flexible coherence rules.
#[stable(feature = "rust1", since = "1.0.0")]
impl Ord for OsStr {
#[inline]
fn cmp(&self, other: &OsStr) -> cmp::Ordering { self.bytes().cmp(other.bytes()) }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Hash for OsStr {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.bytes().hash(state)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Debug for OsStr {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
self.inner.fmt(formatter)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl Borrow<OsStr> for OsString {
fn borrow(&self) -> &OsStr { &self[..] }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl ToOwned for OsStr {
type Owned = OsString;
fn to_owned(&self) -> OsString { self.to_os_string() }
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T: AsOsStr +?Sized> AsOsStr for &'a T {
fn as_os_str(&self) -> &OsStr {
(*self).as_os_str()
}
}
impl AsOsStr for OsStr {
fn as_os_str(&self) -> &OsStr {
self
}
}
impl AsOsStr for OsString {
fn as_os_str(&self) -> &OsStr {
&self[..]
}
}
impl AsOsStr for str {
fn as_os_str(&self) -> &OsStr {
OsStr::from_str(self)
}
}
impl AsOsStr for String {
fn as_os_str(&self) -> &OsStr {
OsStr::from_str(&self[..])
}
}
impl AsOsStr for Path {
#[cfg(unix)]
fn as_os_str(&self) -> &OsStr {
unsafe { mem::transmute(self.as_vec()) }
}
#[cfg(windows)]
fn as_os_str(&self) -> &OsStr {
// currently.as_str() is actually infallible on windows
OsStr::from_str(self.as_str().unwrap())
}
}
impl FromInner<Buf> for OsString {
fn from_inner(buf: Buf) -> OsString {
OsString { inner: buf }
}
}
impl IntoInner<Buf> for OsString {
fn into_inner(self) -> Buf {
self.inner
}
}
impl AsInner<Slice> for OsStr {
fn as_inner(&self) -> &Slice {
&self.inner
}
}
|
//!
//! * On Windows, strings are often arbitrary sequences of non-zero 16-bit
//! values, interpreted as UTF-16 when it is valid to do so.
|
random_line_split
|
mod.rs
|
// Copyright 2017 The Xyrosource Team.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate rustyline;
#[derive(Debug)]
pub enum Command {
Dummy,
}
#[derive(Default)]
pub struct Console {
editor: rustyline::Editor<()>,
error: bool,
}
impl Console {
pub fn new() -> Self {
Console {
editor: rustyline::Editor::<()>::new(),
error: false,
}
}
}
impl Iterator for Console {
type Item = Command;
fn next(&mut self) -> Option<Self::Item> {
loop {
let readline = self.editor.readline(if self.error { "! " } else { "λ " });
use self::rustyline::error::ReadlineError;
match readline {
Ok(ref line) => {
match line.into() {
InternalCommand::Empty => continue,
InternalCommand::Invalid => {
self.error = true;
self.editor.add_history_entry(line);
continue;
}
InternalCommand::Entry(cmd) => {
self.error = false;
self.editor.add_history_entry(line);
return Some(cmd);
}
InternalCommand::Quit => return None,
InternalCommand::Help => {
self.error = false;
self.editor.add_history_entry(line);
display_help();
continue;
}
}
}
Err(ReadlineError::Eof) => return None,
Err(_) => continue,
};
}
}
}
enum InternalCommand {
Entry(Command),
Empty,
Invalid,
Quit,
Help,
}
impl<T: AsRef<str>> From<T> for InternalCommand {
fn from(other: T) -> Self {
match other.as_ref().trim() {
"" => InternalCommand::Empty,
"quit" | "exit" => InternalCommand::Quit,
"dummy" => InternalCommand::Entry(Command::Dummy),
"help" => InternalCommand::Help,
_ => InternalCommand::Invalid,
}
}
}
fn display_help() {
|
println!("\
help - Display help
quit - Exit the server
exit - Exit the server
dummy - \
Example command
");
}
|
identifier_body
|
|
mod.rs
|
// Copyright 2017 The Xyrosource Team.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate rustyline;
#[derive(Debug)]
pub enum Command {
Dummy,
}
#[derive(Default)]
pub struct Console {
editor: rustyline::Editor<()>,
error: bool,
}
impl Console {
pub fn new() -> Self {
Console {
editor: rustyline::Editor::<()>::new(),
error: false,
}
}
}
impl Iterator for Console {
type Item = Command;
fn next(&mut self) -> Option<Self::Item> {
loop {
let readline = self.editor.readline(if self.error { "! " } else { "λ " });
use self::rustyline::error::ReadlineError;
match readline {
Ok(ref line) => {
match line.into() {
InternalCommand::Empty => continue,
InternalCommand::Invalid => {
self.error = true;
self.editor.add_history_entry(line);
continue;
}
InternalCommand::Entry(cmd) => {
self.error = false;
self.editor.add_history_entry(line);
return Some(cmd);
}
InternalCommand::Quit => return None,
InternalCommand::Help => {
self.error = false;
self.editor.add_history_entry(line);
display_help();
continue;
}
}
}
Err(ReadlineError::Eof) => return None,
Err(_) => continue,
};
}
}
}
enum InternalCommand {
Entry(Command),
|
impl<T: AsRef<str>> From<T> for InternalCommand {
fn from(other: T) -> Self {
match other.as_ref().trim() {
"" => InternalCommand::Empty,
"quit" | "exit" => InternalCommand::Quit,
"dummy" => InternalCommand::Entry(Command::Dummy),
"help" => InternalCommand::Help,
_ => InternalCommand::Invalid,
}
}
}
fn display_help() {
println!("\
help - Display help
quit - Exit the server
exit - Exit the server
dummy - \
Example command
");
}
|
Empty,
Invalid,
Quit,
Help,
}
|
random_line_split
|
mod.rs
|
// Copyright 2017 The Xyrosource Team.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern crate rustyline;
#[derive(Debug)]
pub enum
|
{
Dummy,
}
#[derive(Default)]
pub struct Console {
editor: rustyline::Editor<()>,
error: bool,
}
impl Console {
pub fn new() -> Self {
Console {
editor: rustyline::Editor::<()>::new(),
error: false,
}
}
}
impl Iterator for Console {
type Item = Command;
fn next(&mut self) -> Option<Self::Item> {
loop {
let readline = self.editor.readline(if self.error { "! " } else { "λ " });
use self::rustyline::error::ReadlineError;
match readline {
Ok(ref line) => {
match line.into() {
InternalCommand::Empty => continue,
InternalCommand::Invalid => {
self.error = true;
self.editor.add_history_entry(line);
continue;
}
InternalCommand::Entry(cmd) => {
self.error = false;
self.editor.add_history_entry(line);
return Some(cmd);
}
InternalCommand::Quit => return None,
InternalCommand::Help => {
self.error = false;
self.editor.add_history_entry(line);
display_help();
continue;
}
}
}
Err(ReadlineError::Eof) => return None,
Err(_) => continue,
};
}
}
}
enum InternalCommand {
Entry(Command),
Empty,
Invalid,
Quit,
Help,
}
impl<T: AsRef<str>> From<T> for InternalCommand {
fn from(other: T) -> Self {
match other.as_ref().trim() {
"" => InternalCommand::Empty,
"quit" | "exit" => InternalCommand::Quit,
"dummy" => InternalCommand::Entry(Command::Dummy),
"help" => InternalCommand::Help,
_ => InternalCommand::Invalid,
}
}
}
fn display_help() {
println!("\
help - Display help
quit - Exit the server
exit - Exit the server
dummy - \
Example command
");
}
|
Command
|
identifier_name
|
negamax.rs
|
//! An implementation of Negamax.
//!
//! Currently, only the basic alpha-pruning variant is implemented. Further work
//! could add advanced features, like history and/or transposition tables. This
//! picks randomly among the "best" moves, so that it's non-deterministic.
use super::super::interface::*;
use rand;
use rand::Rng;
use std::cmp::max;
use std::marker::PhantomData;
fn negamax<E: Evaluator>(s: &mut <E::G as Game>::S,
depth: usize,
mut alpha: Evaluation,
beta: Evaluation,
p: Player)
-> Evaluation
where <<E as Evaluator>::G as Game>::M: Copy
{
let maybe_winner = E::G::get_winner(s);
if depth == 0 || maybe_winner.is_some() {
return p * E::evaluate(s, maybe_winner);
}
let mut moves = [None; 100];
E::G::generate_moves(s, p, &mut moves);
let mut best = Evaluation::Worst;
for m in moves.iter().take_while(|om| om.is_some()).map(|om| om.unwrap()) {
m.apply(s);
let value = -negamax::<E>(s, depth - 1, -beta, -alpha, -p);
m.undo(s);
best = max(best, value);
alpha = max(alpha, value);
if alpha >= beta {
break
}
}
best
}
/// Options to use for the `Negamax` engine.
pub struct Options {
/// The maximum depth within the game tree.
pub max_depth: usize,
}
pub struct Negamax<E> {
opts: Options,
rng: rand::ThreadRng,
_eval: PhantomData<E>,
}
impl<E: Evaluator> Negamax<E> {
pub fn new(opts: Options) -> Negamax<E>
|
}
impl<E: Evaluator> Strategy<E::G> for Negamax<E>
where <E::G as Game>::S: Clone,
<E::G as Game>::M: Copy {
fn choose_move(&mut self, s: &<E::G as Game>::S, p: Player) -> Option<<E::G as Game>::M> {
let mut best = Evaluation::Worst;
let mut moves = [None; 100];
E::G::generate_moves(s, p, &mut moves);
let mut candidate_moves = Vec::new();
let mut s_clone = s.clone();
for m in moves.iter().take_while(|m| m.is_some()).map(|m| m.unwrap()) {
// determine value for this move
m.apply(&mut s_clone);
let value = -negamax::<E>(&mut s_clone,
self.opts.max_depth,
Evaluation::Worst,
Evaluation::Best,
-p);
m.undo(&mut s_clone);
// this move is a candidate move
if value == best {
candidate_moves.push(m);
// this move is better than any previous, so it's the sole candidate
} else if value > best {
candidate_moves.clear();
candidate_moves.push(m);
best = value;
}
}
if candidate_moves.is_empty() {
None
} else {
Some(candidate_moves[self.rng.gen_range(0, candidate_moves.len())])
}
}
}
|
{
Negamax {
opts: opts,
rng: rand::thread_rng(),
_eval: PhantomData,
}
}
|
identifier_body
|
negamax.rs
|
//! An implementation of Negamax.
//!
//! Currently, only the basic alpha-pruning variant is implemented. Further work
//! could add advanced features, like history and/or transposition tables. This
//! picks randomly among the "best" moves, so that it's non-deterministic.
use super::super::interface::*;
use rand;
use rand::Rng;
use std::cmp::max;
use std::marker::PhantomData;
fn negamax<E: Evaluator>(s: &mut <E::G as Game>::S,
depth: usize,
mut alpha: Evaluation,
beta: Evaluation,
p: Player)
-> Evaluation
where <<E as Evaluator>::G as Game>::M: Copy
{
let maybe_winner = E::G::get_winner(s);
if depth == 0 || maybe_winner.is_some() {
return p * E::evaluate(s, maybe_winner);
}
let mut moves = [None; 100];
E::G::generate_moves(s, p, &mut moves);
let mut best = Evaluation::Worst;
for m in moves.iter().take_while(|om| om.is_some()).map(|om| om.unwrap()) {
m.apply(s);
let value = -negamax::<E>(s, depth - 1, -beta, -alpha, -p);
m.undo(s);
best = max(best, value);
alpha = max(alpha, value);
if alpha >= beta {
break
}
}
best
}
/// Options to use for the `Negamax` engine.
pub struct Options {
/// The maximum depth within the game tree.
pub max_depth: usize,
}
pub struct Negamax<E> {
opts: Options,
rng: rand::ThreadRng,
_eval: PhantomData<E>,
}
impl<E: Evaluator> Negamax<E> {
pub fn
|
(opts: Options) -> Negamax<E> {
Negamax {
opts: opts,
rng: rand::thread_rng(),
_eval: PhantomData,
}
}
}
impl<E: Evaluator> Strategy<E::G> for Negamax<E>
where <E::G as Game>::S: Clone,
<E::G as Game>::M: Copy {
fn choose_move(&mut self, s: &<E::G as Game>::S, p: Player) -> Option<<E::G as Game>::M> {
let mut best = Evaluation::Worst;
let mut moves = [None; 100];
E::G::generate_moves(s, p, &mut moves);
let mut candidate_moves = Vec::new();
let mut s_clone = s.clone();
for m in moves.iter().take_while(|m| m.is_some()).map(|m| m.unwrap()) {
// determine value for this move
m.apply(&mut s_clone);
let value = -negamax::<E>(&mut s_clone,
self.opts.max_depth,
Evaluation::Worst,
Evaluation::Best,
-p);
m.undo(&mut s_clone);
// this move is a candidate move
if value == best {
candidate_moves.push(m);
// this move is better than any previous, so it's the sole candidate
} else if value > best {
candidate_moves.clear();
candidate_moves.push(m);
best = value;
}
}
if candidate_moves.is_empty() {
None
} else {
Some(candidate_moves[self.rng.gen_range(0, candidate_moves.len())])
}
}
}
|
new
|
identifier_name
|
negamax.rs
|
//! An implementation of Negamax.
//!
//! Currently, only the basic alpha-pruning variant is implemented. Further work
//! could add advanced features, like history and/or transposition tables. This
//! picks randomly among the "best" moves, so that it's non-deterministic.
use super::super::interface::*;
use rand;
use rand::Rng;
use std::cmp::max;
use std::marker::PhantomData;
fn negamax<E: Evaluator>(s: &mut <E::G as Game>::S,
depth: usize,
mut alpha: Evaluation,
beta: Evaluation,
p: Player)
-> Evaluation
where <<E as Evaluator>::G as Game>::M: Copy
{
let maybe_winner = E::G::get_winner(s);
if depth == 0 || maybe_winner.is_some() {
return p * E::evaluate(s, maybe_winner);
}
let mut moves = [None; 100];
E::G::generate_moves(s, p, &mut moves);
let mut best = Evaluation::Worst;
for m in moves.iter().take_while(|om| om.is_some()).map(|om| om.unwrap()) {
m.apply(s);
let value = -negamax::<E>(s, depth - 1, -beta, -alpha, -p);
m.undo(s);
best = max(best, value);
alpha = max(alpha, value);
if alpha >= beta {
break
}
}
best
}
/// Options to use for the `Negamax` engine.
pub struct Options {
/// The maximum depth within the game tree.
pub max_depth: usize,
}
pub struct Negamax<E> {
opts: Options,
rng: rand::ThreadRng,
_eval: PhantomData<E>,
}
impl<E: Evaluator> Negamax<E> {
pub fn new(opts: Options) -> Negamax<E> {
Negamax {
opts: opts,
rng: rand::thread_rng(),
_eval: PhantomData,
}
}
}
impl<E: Evaluator> Strategy<E::G> for Negamax<E>
where <E::G as Game>::S: Clone,
<E::G as Game>::M: Copy {
fn choose_move(&mut self, s: &<E::G as Game>::S, p: Player) -> Option<<E::G as Game>::M> {
let mut best = Evaluation::Worst;
let mut moves = [None; 100];
E::G::generate_moves(s, p, &mut moves);
let mut candidate_moves = Vec::new();
let mut s_clone = s.clone();
for m in moves.iter().take_while(|m| m.is_some()).map(|m| m.unwrap()) {
// determine value for this move
m.apply(&mut s_clone);
let value = -negamax::<E>(&mut s_clone,
self.opts.max_depth,
Evaluation::Worst,
Evaluation::Best,
-p);
m.undo(&mut s_clone);
// this move is a candidate move
if value == best {
candidate_moves.push(m);
// this move is better than any previous, so it's the sole candidate
} else if value > best {
candidate_moves.clear();
candidate_moves.push(m);
best = value;
}
}
if candidate_moves.is_empty() {
|
Some(candidate_moves[self.rng.gen_range(0, candidate_moves.len())])
}
}
}
|
None
} else {
|
random_line_split
|
negamax.rs
|
//! An implementation of Negamax.
//!
//! Currently, only the basic alpha-pruning variant is implemented. Further work
//! could add advanced features, like history and/or transposition tables. This
//! picks randomly among the "best" moves, so that it's non-deterministic.
use super::super::interface::*;
use rand;
use rand::Rng;
use std::cmp::max;
use std::marker::PhantomData;
fn negamax<E: Evaluator>(s: &mut <E::G as Game>::S,
depth: usize,
mut alpha: Evaluation,
beta: Evaluation,
p: Player)
-> Evaluation
where <<E as Evaluator>::G as Game>::M: Copy
{
let maybe_winner = E::G::get_winner(s);
if depth == 0 || maybe_winner.is_some() {
return p * E::evaluate(s, maybe_winner);
}
let mut moves = [None; 100];
E::G::generate_moves(s, p, &mut moves);
let mut best = Evaluation::Worst;
for m in moves.iter().take_while(|om| om.is_some()).map(|om| om.unwrap()) {
m.apply(s);
let value = -negamax::<E>(s, depth - 1, -beta, -alpha, -p);
m.undo(s);
best = max(best, value);
alpha = max(alpha, value);
if alpha >= beta {
break
}
}
best
}
/// Options to use for the `Negamax` engine.
pub struct Options {
/// The maximum depth within the game tree.
pub max_depth: usize,
}
pub struct Negamax<E> {
opts: Options,
rng: rand::ThreadRng,
_eval: PhantomData<E>,
}
impl<E: Evaluator> Negamax<E> {
pub fn new(opts: Options) -> Negamax<E> {
Negamax {
opts: opts,
rng: rand::thread_rng(),
_eval: PhantomData,
}
}
}
impl<E: Evaluator> Strategy<E::G> for Negamax<E>
where <E::G as Game>::S: Clone,
<E::G as Game>::M: Copy {
fn choose_move(&mut self, s: &<E::G as Game>::S, p: Player) -> Option<<E::G as Game>::M> {
let mut best = Evaluation::Worst;
let mut moves = [None; 100];
E::G::generate_moves(s, p, &mut moves);
let mut candidate_moves = Vec::new();
let mut s_clone = s.clone();
for m in moves.iter().take_while(|m| m.is_some()).map(|m| m.unwrap()) {
// determine value for this move
m.apply(&mut s_clone);
let value = -negamax::<E>(&mut s_clone,
self.opts.max_depth,
Evaluation::Worst,
Evaluation::Best,
-p);
m.undo(&mut s_clone);
// this move is a candidate move
if value == best {
candidate_moves.push(m);
// this move is better than any previous, so it's the sole candidate
} else if value > best
|
}
if candidate_moves.is_empty() {
None
} else {
Some(candidate_moves[self.rng.gen_range(0, candidate_moves.len())])
}
}
}
|
{
candidate_moves.clear();
candidate_moves.push(m);
best = value;
}
|
conditional_block
|
htmlspanelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLSpanElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use dom_struct::dom_struct;
use html5ever_atoms::LocalName;
#[dom_struct]
pub struct HTMLSpanElement {
htmlelement: HTMLElement
}
impl HTMLSpanElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLSpanElement {
HTMLSpanElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn
|
(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSpanElement> {
Node::reflect_node(box HTMLSpanElement::new_inherited(local_name, prefix, document),
document,
HTMLSpanElementBinding::Wrap)
}
}
|
new
|
identifier_name
|
htmlspanelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use dom_struct::dom_struct;
use html5ever_atoms::LocalName;
#[dom_struct]
pub struct HTMLSpanElement {
htmlelement: HTMLElement
}
impl HTMLSpanElement {
fn new_inherited(local_name: LocalName, prefix: Option<DOMString>, document: &Document) -> HTMLSpanElement {
HTMLSpanElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSpanElement> {
Node::reflect_node(box HTMLSpanElement::new_inherited(local_name, prefix, document),
document,
HTMLSpanElementBinding::Wrap)
}
}
|
use dom::bindings::codegen::Bindings::HTMLSpanElementBinding;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
|
random_line_split
|
enclaveapi.rs
|
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied, modified, or distributed
// except according to those terms.
use shared::basetsd::{PSIZE_T, SIZE_T};
use shared::minwindef::{BOOL, DWORD, LPCVOID, LPDWORD, LPVOID};
use shared::ntdef::{HANDLE};
use um::minwinbase::LPENCLAVE_ROUTINE;
use um::winnt::{LPCSTR, LPCWSTR};
extern "system" {
pub fn IsEnclaveTypeSupported(
flEnclaveType: DWORD,
) -> BOOL;
pub fn CreateEnclave(
hProcess: HANDLE,
lpAddress: LPVOID,
dwSize: SIZE_T,
dwInitialCommitment: SIZE_T,
flEnclaveType: DWORD,
lpEnclaveInformation: LPCVOID,
dwInfoLength: DWORD,
lpEnclaveError: LPDWORD,
) -> LPVOID;
pub fn LoadEnclaveData(
hProcess: HANDLE,
lpAddress: LPVOID,
lpBuffer: LPCVOID,
nSize: SIZE_T,
flProtect: DWORD,
lpPageInformation: LPCVOID,
dwInfoLength: DWORD,
lpNumberOfBytesWritten: PSIZE_T,
lpEnclaveError: LPDWORD,
) -> BOOL;
pub fn InitializeEnclave(
hProcess: HANDLE,
lpAddress: LPVOID,
lpEnclaveInformation: LPCVOID,
dwInfoLength: DWORD,
lpEnclaveError: LPDWORD,
) -> BOOL;
pub fn LoadEnclaveImageA(
lpEnclaveAddress: LPVOID,
lpImageName: LPCSTR,
) -> BOOL;
pub fn LoadEnclaveImageW(
lpEnclaveAddress: LPVOID,
lpImageName: LPCWSTR,
) -> BOOL;
pub fn CallEnclave(
lpRoutine: LPENCLAVE_ROUTINE,
lpParameter: LPVOID,
fWaitForThread: BOOL,
lpReturnValue: *mut LPVOID,
) -> BOOL;
pub fn TerminateEnclave(
lpAddress: LPVOID,
fWait: BOOL,
) -> BOOL;
pub fn DeleteEnclave(
lpAddress: LPVOID,
|
}
|
) -> BOOL;
|
random_line_split
|
buffer.rs
|
use std::cmp;
use std::iter;
use std::io::{self, Read, BufRead};
pub struct BufReader<R> {
inner: R,
buf: Vec<u8>,
pos: usize,
cap: usize,
}
const INIT_BUFFER_SIZE: usize = 4096;
const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100;
impl<R: Read> BufReader<R> {
#[inline]
pub fn new(rdr: R) -> BufReader<R> {
BufReader::with_capacity(rdr, INIT_BUFFER_SIZE)
}
#[inline]
pub fn with_capacity(rdr: R, cap: usize) -> BufReader<R> {
let mut buf = Vec::with_capacity(cap);
buf.extend(iter::repeat(0).take(cap));
BufReader {
inner: rdr,
buf: buf,
pos: 0,
cap: 0,
}
}
#[inline]
pub fn get_ref(&self) -> &R { &self.inner }
#[inline]
pub fn get_mut(&mut self) -> &mut R { &mut self.inner }
#[inline]
pub fn get_buf(&self) -> &[u8] {
if self.pos < self.cap {
trace!("slicing {:?}", (self.pos, self.cap, self.buf.len()));
&self.buf[self.pos..self.cap]
} else {
&[]
}
}
#[inline]
pub fn into_inner(self) -> R { self.inner }
#[inline]
pub fn read_into_buf(&mut self) -> io::Result<usize> {
self.maybe_reserve();
let v = &mut self.buf;
if self.cap < v.capacity() {
let nread = try!(self.inner.read(&mut v[self.cap..]));
self.cap += nread;
Ok(nread)
} else {
Ok(0)
}
}
#[inline]
fn maybe_reserve(&mut self) {
let cap = self.buf.capacity();
if self.cap == cap {
self.buf.reserve(cmp::min(cap * 4, MAX_BUFFER_SIZE) - cap);
let new = self.buf.capacity() - self.buf.len();
trace!("reserved {}", new);
self.buf.extend(iter::repeat(0).take(new));
}
}
}
impl<R: Read> Read for BufReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.cap == self.pos && buf.len() >= self.buf.len() {
return self.inner.read(buf);
}
let nread = {
let mut rem = try!(self.fill_buf());
try!(rem.read(buf))
};
self.consume(nread);
Ok(nread)
}
}
impl<R: Read> BufRead for BufReader<R> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
if self.pos == self.cap {
self.cap = try!(self.inner.read(&mut self.buf));
self.pos = 0;
}
Ok(&self.buf[self.pos..self.cap])
}
#[inline]
fn consume(&mut self, amt: usize) {
self.pos = cmp::min(self.pos + amt, self.cap);
if self.pos == self.cap {
self.pos = 0;
self.cap = 0;
}
}
}
#[cfg(test)]
mod tests {
use std::io::{self, Read, BufRead};
|
struct SlowRead(u8);
impl Read for SlowRead {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let state = self.0;
self.0 += 1;
(&match state % 3 {
0 => b"foo",
1 => b"bar",
_ => b"baz",
}[..]).read(buf)
}
}
#[test]
fn test_consume_and_get_buf() {
let mut rdr = BufReader::new(SlowRead(0));
rdr.read_into_buf().unwrap();
rdr.consume(1);
assert_eq!(rdr.get_buf(), b"oo");
rdr.read_into_buf().unwrap();
rdr.read_into_buf().unwrap();
assert_eq!(rdr.get_buf(), b"oobarbaz");
rdr.consume(5);
assert_eq!(rdr.get_buf(), b"baz");
rdr.consume(3);
assert_eq!(rdr.get_buf(), b"");
assert_eq!(rdr.pos, 0);
assert_eq!(rdr.cap, 0);
}
}
|
use super::BufReader;
|
random_line_split
|
buffer.rs
|
use std::cmp;
use std::iter;
use std::io::{self, Read, BufRead};
pub struct BufReader<R> {
inner: R,
buf: Vec<u8>,
pos: usize,
cap: usize,
}
const INIT_BUFFER_SIZE: usize = 4096;
const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100;
impl<R: Read> BufReader<R> {
#[inline]
pub fn new(rdr: R) -> BufReader<R> {
BufReader::with_capacity(rdr, INIT_BUFFER_SIZE)
}
#[inline]
pub fn with_capacity(rdr: R, cap: usize) -> BufReader<R> {
let mut buf = Vec::with_capacity(cap);
buf.extend(iter::repeat(0).take(cap));
BufReader {
inner: rdr,
buf: buf,
pos: 0,
cap: 0,
}
}
#[inline]
pub fn get_ref(&self) -> &R { &self.inner }
#[inline]
pub fn get_mut(&mut self) -> &mut R { &mut self.inner }
#[inline]
pub fn get_buf(&self) -> &[u8] {
if self.pos < self.cap
|
else {
&[]
}
}
#[inline]
pub fn into_inner(self) -> R { self.inner }
#[inline]
pub fn read_into_buf(&mut self) -> io::Result<usize> {
self.maybe_reserve();
let v = &mut self.buf;
if self.cap < v.capacity() {
let nread = try!(self.inner.read(&mut v[self.cap..]));
self.cap += nread;
Ok(nread)
} else {
Ok(0)
}
}
#[inline]
fn maybe_reserve(&mut self) {
let cap = self.buf.capacity();
if self.cap == cap {
self.buf.reserve(cmp::min(cap * 4, MAX_BUFFER_SIZE) - cap);
let new = self.buf.capacity() - self.buf.len();
trace!("reserved {}", new);
self.buf.extend(iter::repeat(0).take(new));
}
}
}
impl<R: Read> Read for BufReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.cap == self.pos && buf.len() >= self.buf.len() {
return self.inner.read(buf);
}
let nread = {
let mut rem = try!(self.fill_buf());
try!(rem.read(buf))
};
self.consume(nread);
Ok(nread)
}
}
impl<R: Read> BufRead for BufReader<R> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
if self.pos == self.cap {
self.cap = try!(self.inner.read(&mut self.buf));
self.pos = 0;
}
Ok(&self.buf[self.pos..self.cap])
}
#[inline]
fn consume(&mut self, amt: usize) {
self.pos = cmp::min(self.pos + amt, self.cap);
if self.pos == self.cap {
self.pos = 0;
self.cap = 0;
}
}
}
#[cfg(test)]
mod tests {
use std::io::{self, Read, BufRead};
use super::BufReader;
struct SlowRead(u8);
impl Read for SlowRead {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let state = self.0;
self.0 += 1;
(&match state % 3 {
0 => b"foo",
1 => b"bar",
_ => b"baz",
}[..]).read(buf)
}
}
#[test]
fn test_consume_and_get_buf() {
let mut rdr = BufReader::new(SlowRead(0));
rdr.read_into_buf().unwrap();
rdr.consume(1);
assert_eq!(rdr.get_buf(), b"oo");
rdr.read_into_buf().unwrap();
rdr.read_into_buf().unwrap();
assert_eq!(rdr.get_buf(), b"oobarbaz");
rdr.consume(5);
assert_eq!(rdr.get_buf(), b"baz");
rdr.consume(3);
assert_eq!(rdr.get_buf(), b"");
assert_eq!(rdr.pos, 0);
assert_eq!(rdr.cap, 0);
}
}
|
{
trace!("slicing {:?}", (self.pos, self.cap, self.buf.len()));
&self.buf[self.pos..self.cap]
}
|
conditional_block
|
buffer.rs
|
use std::cmp;
use std::iter;
use std::io::{self, Read, BufRead};
pub struct BufReader<R> {
inner: R,
buf: Vec<u8>,
pos: usize,
cap: usize,
}
const INIT_BUFFER_SIZE: usize = 4096;
const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100;
impl<R: Read> BufReader<R> {
#[inline]
pub fn new(rdr: R) -> BufReader<R> {
BufReader::with_capacity(rdr, INIT_BUFFER_SIZE)
}
#[inline]
pub fn with_capacity(rdr: R, cap: usize) -> BufReader<R> {
let mut buf = Vec::with_capacity(cap);
buf.extend(iter::repeat(0).take(cap));
BufReader {
inner: rdr,
buf: buf,
pos: 0,
cap: 0,
}
}
#[inline]
pub fn get_ref(&self) -> &R { &self.inner }
#[inline]
pub fn get_mut(&mut self) -> &mut R
|
#[inline]
pub fn get_buf(&self) -> &[u8] {
if self.pos < self.cap {
trace!("slicing {:?}", (self.pos, self.cap, self.buf.len()));
&self.buf[self.pos..self.cap]
} else {
&[]
}
}
#[inline]
pub fn into_inner(self) -> R { self.inner }
#[inline]
pub fn read_into_buf(&mut self) -> io::Result<usize> {
self.maybe_reserve();
let v = &mut self.buf;
if self.cap < v.capacity() {
let nread = try!(self.inner.read(&mut v[self.cap..]));
self.cap += nread;
Ok(nread)
} else {
Ok(0)
}
}
#[inline]
fn maybe_reserve(&mut self) {
let cap = self.buf.capacity();
if self.cap == cap {
self.buf.reserve(cmp::min(cap * 4, MAX_BUFFER_SIZE) - cap);
let new = self.buf.capacity() - self.buf.len();
trace!("reserved {}", new);
self.buf.extend(iter::repeat(0).take(new));
}
}
}
impl<R: Read> Read for BufReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.cap == self.pos && buf.len() >= self.buf.len() {
return self.inner.read(buf);
}
let nread = {
let mut rem = try!(self.fill_buf());
try!(rem.read(buf))
};
self.consume(nread);
Ok(nread)
}
}
impl<R: Read> BufRead for BufReader<R> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
if self.pos == self.cap {
self.cap = try!(self.inner.read(&mut self.buf));
self.pos = 0;
}
Ok(&self.buf[self.pos..self.cap])
}
#[inline]
fn consume(&mut self, amt: usize) {
self.pos = cmp::min(self.pos + amt, self.cap);
if self.pos == self.cap {
self.pos = 0;
self.cap = 0;
}
}
}
#[cfg(test)]
mod tests {
use std::io::{self, Read, BufRead};
use super::BufReader;
struct SlowRead(u8);
impl Read for SlowRead {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let state = self.0;
self.0 += 1;
(&match state % 3 {
0 => b"foo",
1 => b"bar",
_ => b"baz",
}[..]).read(buf)
}
}
#[test]
fn test_consume_and_get_buf() {
let mut rdr = BufReader::new(SlowRead(0));
rdr.read_into_buf().unwrap();
rdr.consume(1);
assert_eq!(rdr.get_buf(), b"oo");
rdr.read_into_buf().unwrap();
rdr.read_into_buf().unwrap();
assert_eq!(rdr.get_buf(), b"oobarbaz");
rdr.consume(5);
assert_eq!(rdr.get_buf(), b"baz");
rdr.consume(3);
assert_eq!(rdr.get_buf(), b"");
assert_eq!(rdr.pos, 0);
assert_eq!(rdr.cap, 0);
}
}
|
{ &mut self.inner }
|
identifier_body
|
buffer.rs
|
use std::cmp;
use std::iter;
use std::io::{self, Read, BufRead};
pub struct BufReader<R> {
inner: R,
buf: Vec<u8>,
pos: usize,
cap: usize,
}
const INIT_BUFFER_SIZE: usize = 4096;
const MAX_BUFFER_SIZE: usize = 8192 + 4096 * 100;
impl<R: Read> BufReader<R> {
#[inline]
pub fn new(rdr: R) -> BufReader<R> {
BufReader::with_capacity(rdr, INIT_BUFFER_SIZE)
}
#[inline]
pub fn with_capacity(rdr: R, cap: usize) -> BufReader<R> {
let mut buf = Vec::with_capacity(cap);
buf.extend(iter::repeat(0).take(cap));
BufReader {
inner: rdr,
buf: buf,
pos: 0,
cap: 0,
}
}
#[inline]
pub fn get_ref(&self) -> &R { &self.inner }
#[inline]
pub fn get_mut(&mut self) -> &mut R { &mut self.inner }
#[inline]
pub fn get_buf(&self) -> &[u8] {
if self.pos < self.cap {
trace!("slicing {:?}", (self.pos, self.cap, self.buf.len()));
&self.buf[self.pos..self.cap]
} else {
&[]
}
}
#[inline]
pub fn into_inner(self) -> R { self.inner }
#[inline]
pub fn read_into_buf(&mut self) -> io::Result<usize> {
self.maybe_reserve();
let v = &mut self.buf;
if self.cap < v.capacity() {
let nread = try!(self.inner.read(&mut v[self.cap..]));
self.cap += nread;
Ok(nread)
} else {
Ok(0)
}
}
#[inline]
fn maybe_reserve(&mut self) {
let cap = self.buf.capacity();
if self.cap == cap {
self.buf.reserve(cmp::min(cap * 4, MAX_BUFFER_SIZE) - cap);
let new = self.buf.capacity() - self.buf.len();
trace!("reserved {}", new);
self.buf.extend(iter::repeat(0).take(new));
}
}
}
impl<R: Read> Read for BufReader<R> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.cap == self.pos && buf.len() >= self.buf.len() {
return self.inner.read(buf);
}
let nread = {
let mut rem = try!(self.fill_buf());
try!(rem.read(buf))
};
self.consume(nread);
Ok(nread)
}
}
impl<R: Read> BufRead for BufReader<R> {
fn fill_buf(&mut self) -> io::Result<&[u8]> {
if self.pos == self.cap {
self.cap = try!(self.inner.read(&mut self.buf));
self.pos = 0;
}
Ok(&self.buf[self.pos..self.cap])
}
#[inline]
fn consume(&mut self, amt: usize) {
self.pos = cmp::min(self.pos + amt, self.cap);
if self.pos == self.cap {
self.pos = 0;
self.cap = 0;
}
}
}
#[cfg(test)]
mod tests {
use std::io::{self, Read, BufRead};
use super::BufReader;
struct
|
(u8);
impl Read for SlowRead {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
let state = self.0;
self.0 += 1;
(&match state % 3 {
0 => b"foo",
1 => b"bar",
_ => b"baz",
}[..]).read(buf)
}
}
#[test]
fn test_consume_and_get_buf() {
let mut rdr = BufReader::new(SlowRead(0));
rdr.read_into_buf().unwrap();
rdr.consume(1);
assert_eq!(rdr.get_buf(), b"oo");
rdr.read_into_buf().unwrap();
rdr.read_into_buf().unwrap();
assert_eq!(rdr.get_buf(), b"oobarbaz");
rdr.consume(5);
assert_eq!(rdr.get_buf(), b"baz");
rdr.consume(3);
assert_eq!(rdr.get_buf(), b"");
assert_eq!(rdr.pos, 0);
assert_eq!(rdr.cap, 0);
}
}
|
SlowRead
|
identifier_name
|
bare-fn-implements-fn-mut.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn call_f<F:FnMut()>(mut f: F) {
f();
}
fn f() {
println!("hello");
}
fn call_g<G:FnMut(String,String) -> String>(mut g: G, x: String, y: String)
-> String {
g(x, y)
}
fn
|
(mut x: String, y: String) -> String {
x.push_str(&y);
x
}
fn main() {
call_f(f);
assert_eq!(call_g(g, "foo".to_string(), "bar".to_string()),
"foobar");
}
|
g
|
identifier_name
|
bare-fn-implements-fn-mut.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn call_f<F:FnMut()>(mut f: F) {
f();
}
fn f() {
println!("hello");
}
fn call_g<G:FnMut(String,String) -> String>(mut g: G, x: String, y: String)
-> String {
g(x, y)
}
fn g(mut x: String, y: String) -> String
|
fn main() {
call_f(f);
assert_eq!(call_g(g, "foo".to_string(), "bar".to_string()),
"foobar");
}
|
{
x.push_str(&y);
x
}
|
identifier_body
|
bare-fn-implements-fn-mut.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
use std::ops::FnMut;
fn call_f<F:FnMut()>(mut f: F) {
f();
}
fn f() {
println!("hello");
}
fn call_g<G:FnMut(String,String) -> String>(mut g: G, x: String, y: String)
-> String {
g(x, y)
}
fn g(mut x: String, y: String) -> String {
x.push_str(&y);
x
}
fn main() {
call_f(f);
|
assert_eq!(call_g(g, "foo".to_string(), "bar".to_string()),
"foobar");
}
|
random_line_split
|
|
deprecation-sanity.rs
|
// Various checks that deprecation attributes are used correctly
mod bogus_attribute_types_1 {
#[deprecated(since = "a", note = "a", reason)] //~ ERROR unknown meta item'reason'
fn f1() { }
#[deprecated(since = "a", note)] //~ ERROR incorrect meta item
fn f2() { }
#[deprecated(since, note = "a")] //~ ERROR incorrect meta item
fn
|
() { }
#[deprecated(since = "a", note(b))] //~ ERROR incorrect meta item
fn f5() { }
#[deprecated(since(b), note = "a")] //~ ERROR incorrect meta item
fn f6() { }
#[deprecated(note = b"test")] //~ ERROR literal in `deprecated` value must be a string
fn f7() { }
#[deprecated("test")] //~ ERROR item in `deprecated` must be a key/value pair
fn f8() { }
}
#[deprecated(since = "a", note = "b")]
#[deprecated(since = "a", note = "b")] //~ ERROR multiple deprecated attributes
fn multiple1() { }
#[deprecated(since = "a", since = "b", note = "c")] //~ ERROR multiple'since' items
fn f1() { }
struct X;
#[deprecated = "hello"] //~ ERROR this `#[deprecated]` annotation has no effect
impl Default for X {
fn default() -> Self {
X
}
}
fn main() { }
|
f3
|
identifier_name
|
deprecation-sanity.rs
|
// Various checks that deprecation attributes are used correctly
mod bogus_attribute_types_1 {
#[deprecated(since = "a", note = "a", reason)] //~ ERROR unknown meta item'reason'
fn f1() { }
#[deprecated(since = "a", note)] //~ ERROR incorrect meta item
fn f2() { }
#[deprecated(since, note = "a")] //~ ERROR incorrect meta item
fn f3() { }
#[deprecated(since = "a", note(b))] //~ ERROR incorrect meta item
fn f5() { }
#[deprecated(since(b), note = "a")] //~ ERROR incorrect meta item
fn f6() { }
#[deprecated(note = b"test")] //~ ERROR literal in `deprecated` value must be a string
fn f7() { }
#[deprecated("test")] //~ ERROR item in `deprecated` must be a key/value pair
fn f8() { }
}
#[deprecated(since = "a", note = "b")]
#[deprecated(since = "a", note = "b")] //~ ERROR multiple deprecated attributes
fn multiple1() { }
#[deprecated(since = "a", since = "b", note = "c")] //~ ERROR multiple'since' items
fn f1() { }
struct X;
#[deprecated = "hello"] //~ ERROR this `#[deprecated]` annotation has no effect
impl Default for X {
fn default() -> Self {
X
}
|
fn main() { }
|
}
|
random_line_split
|
input.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use script_traits::MouseButton;
use std::path::Path;
use std::mem::size_of;
use std::mem::transmute;
use std::mem::zeroed;
use std::os::unix::io::AsRawFd;
use std::fs::File;
use std::thread;
use std::sync::mpsc::Sender;
use std::io::Read;
use geom::point::Point2D;
use errno::errno;
use libc::c_int;
use libc::c_long;
use libc::time_t;
use compositing::windowing::WindowEvent;
use compositing::windowing::MouseWindowEvent;
extern {
// XXX: no variadic form in std libs?
fn ioctl(fd: c_int, req: c_int,...) -> c_int;
}
#[repr(C)]
struct linux_input_event {
sec: time_t,
msec: c_long,
evt_type: u16,
code: u16,
value: i32,
}
#[repr(C)]
struct linux_input_absinfo {
value: i32,
minimum: i32,
maximum: i32,
fuzz: i32,
flat: i32,
resolution: i32,
}
const IOC_NONE: c_int = 0;
const IOC_WRITE: c_int = 1;
const IOC_READ: c_int = 2;
fn ioc(dir: c_int, ioctype: c_int, nr: c_int, size: c_int) -> c_int {
dir << 30 | size << 16 | ioctype << 8 | nr
}
fn ev_ioc_g_abs(abs: u16) -> c_int {
ioc(IOC_READ, 'E' as c_int, (0x40 + abs) as i32, size_of::<linux_input_absinfo>() as i32)
}
const EV_SYN: u16 = 0;
const EV_ABS: u16 = 3;
const EV_REPORT: u16 = 0;
const ABS_MT_SLOT: u16 = 0x2F;
const ABS_MT_TOUCH_MAJOR: u16 = 0x30;
const ABS_MT_TOUCH_MINOR: u16 = 0x31;
const ABS_MT_WIDTH_MAJOR: u16 = 0x32;
const ABS_MT_WIDTH_MINOR: u16 = 0x33;
const ABS_MT_ORIENTATION: u16 = 0x34;
const ABS_MT_POSITION_X: u16 = 0x35;
const ABS_MT_POSITION_Y: u16 = 0x36;
const ABS_MT_TRACKING_ID: u16 = 0x39;
struct InputSlot {
tracking_id: i32,
x: i32,
y: i32,
}
fn dist(x1: i32, x2: i32, y1: i32, y2: i32) -> f32 {
let deltaX = (x2 - x1) as f32;
let deltaY = (y2 - y1) as f32;
(deltaX * deltaX + deltaY * deltaY).sqrt()
}
fn read_input_device(device_path: &Path,
sender: &Sender<WindowEvent>) {
let mut device = match File::open(device_path) {
Ok(dev) => dev,
Err(e) => {
println!("Couldn't open device! {}", e);
return;
},
};
let fd = device.as_raw_fd();
let mut x_info: linux_input_absinfo = unsafe { zeroed() };
let mut y_info: linux_input_absinfo = unsafe { zeroed() };
unsafe {
let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_X), &mut x_info);
if ret < 0 {
println!("Couldn't get ABS_MT_POSITION_X info {} {}", ret, errno());
}
}
unsafe {
let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_Y), &mut y_info);
if ret < 0 {
println!("Couldn't get ABS_MT_POSITION_Y info {} {}", ret, errno());
}
}
let touchWidth = x_info.maximum - x_info.minimum;
let touchHeight = y_info.maximum - y_info.minimum;
println!("xMin: {}, yMin: {}, touchWidth: {}, touchHeight: {}",
x_info.minimum, y_info.minimum, touchWidth, touchHeight);
// XXX: Why isn't size_of treated as constant?
// let buf: [u8; (16 * size_of::<linux_input_event>())];
let mut buf: [u8; (16 * 16)] = unsafe { zeroed() };
let mut slots: [InputSlot; 10] = unsafe { zeroed() };
for slot in slots.iter_mut() {
slot.tracking_id = -1;
}
let mut last_x = 0;
let mut last_y = 0;
let mut first_x = 0;
let mut first_y = 0;
let mut last_dist: f32 = 0f32;
let mut touch_count: i32 = 0;
let mut current_slot: usize = 0;
// XXX: Need to use the real dimensions of the screen
let screen_dist = dist(0, 480, 854, 0);
loop {
let read = match device.read(&mut buf) {
Ok(count) => {
assert!(count % size_of::<linux_input_event>() == 0,
"Unexpected input device read length!");
count
},
|
};
let count = read / size_of::<linux_input_event>();
let events: *mut linux_input_event = unsafe { transmute(buf.as_mut_ptr()) };
let mut tracking_updated = false;
for idx in 0..(count as isize) {
let event: &linux_input_event = unsafe { transmute(events.offset(idx)) };
match (event.evt_type, event.code) {
(EV_SYN, EV_REPORT) => {
let slotA = &slots[0];
if tracking_updated {
tracking_updated = false;
if slotA.tracking_id == -1 {
println!("Touch up");
let delta_x = slotA.x - first_x;
let delta_y = slotA.y - first_y;
let dist = delta_x * delta_x + delta_y * delta_y;
if dist < 16 {
let click_pt = Point2D::typed(slotA.x as f32, slotA.y as f32);
println!("Dispatching click!");
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::MouseDown(MouseButton::Left, click_pt))).ok().unwrap();
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::MouseUp(MouseButton::Left, click_pt))).ok().unwrap();
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::Click(MouseButton::Left, click_pt))).ok().unwrap();
}
} else {
println!("Touch down");
last_x = slotA.x;
last_y = slotA.y;
first_x = slotA.x;
first_y = slotA.y;
if touch_count >= 2 {
let slotB = &slots[1];
last_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y);
}
}
} else {
println!("Touch move x: {}, y: {}", slotA.x, slotA.y);
sender.send(
WindowEvent::Scroll(Point2D::typed((slotA.x - last_x) as f32, (slotA.y - last_y) as f32),
Point2D::typed(slotA.x, slotA.y))).ok().unwrap();
last_x = slotA.x;
last_y = slotA.y;
if touch_count >= 2 {
let slotB = &slots[1];
let cur_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y);
println!("Zooming {} {} {} {}",
cur_dist, last_dist, screen_dist,
((screen_dist + (cur_dist - last_dist))/screen_dist));
sender.send(
WindowEvent::Zoom((screen_dist + (cur_dist - last_dist))/screen_dist)).ok().unwrap();
last_dist = cur_dist;
}
}
},
(EV_SYN, _) => println!("Unknown SYN code {}", event.code),
(EV_ABS, ABS_MT_SLOT) => {
if (event.value as usize) < slots.len() {
current_slot = event.value as usize;
} else {
println!("Invalid slot! {}", event.value);
}
},
(EV_ABS, ABS_MT_TOUCH_MAJOR) => (),
(EV_ABS, ABS_MT_TOUCH_MINOR) => (),
(EV_ABS, ABS_MT_WIDTH_MAJOR) => (),
(EV_ABS, ABS_MT_WIDTH_MINOR) => (),
(EV_ABS, ABS_MT_ORIENTATION) => (),
(EV_ABS, ABS_MT_POSITION_X) => {
slots[current_slot].x = event.value - x_info.minimum;
},
(EV_ABS, ABS_MT_POSITION_Y) => {
slots[current_slot].y = event.value - y_info.minimum;
},
(EV_ABS, ABS_MT_TRACKING_ID) => {
let current_id = slots[current_slot].tracking_id;
if current_id!= event.value &&
(current_id == -1 || event.value == -1) {
tracking_updated = true;
if event.value == -1 {
touch_count -= 1;
} else {
touch_count += 1;
}
}
slots[current_slot].tracking_id = event.value;
},
(EV_ABS, _) => println!("Unknown ABS code {}", event.code),
(_, _) => println!("Unknown event type {}", event.evt_type),
}
}
}
}
pub fn run_input_loop(event_sender: &Sender<WindowEvent>) {
let sender = event_sender.clone();
thread::spawn(move || {
// XXX need to scan all devices and read every one.
let touchinputdev = Path::new("/dev/input/event0");
read_input_device(&touchinputdev, &sender);
});
}
|
Err(e) => {
println!("Couldn't read device! {}", e);
return;
}
|
random_line_split
|
input.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use script_traits::MouseButton;
use std::path::Path;
use std::mem::size_of;
use std::mem::transmute;
use std::mem::zeroed;
use std::os::unix::io::AsRawFd;
use std::fs::File;
use std::thread;
use std::sync::mpsc::Sender;
use std::io::Read;
use geom::point::Point2D;
use errno::errno;
use libc::c_int;
use libc::c_long;
use libc::time_t;
use compositing::windowing::WindowEvent;
use compositing::windowing::MouseWindowEvent;
extern {
// XXX: no variadic form in std libs?
fn ioctl(fd: c_int, req: c_int,...) -> c_int;
}
#[repr(C)]
struct linux_input_event {
sec: time_t,
msec: c_long,
evt_type: u16,
code: u16,
value: i32,
}
#[repr(C)]
struct linux_input_absinfo {
value: i32,
minimum: i32,
maximum: i32,
fuzz: i32,
flat: i32,
resolution: i32,
}
const IOC_NONE: c_int = 0;
const IOC_WRITE: c_int = 1;
const IOC_READ: c_int = 2;
fn ioc(dir: c_int, ioctype: c_int, nr: c_int, size: c_int) -> c_int {
dir << 30 | size << 16 | ioctype << 8 | nr
}
fn ev_ioc_g_abs(abs: u16) -> c_int {
ioc(IOC_READ, 'E' as c_int, (0x40 + abs) as i32, size_of::<linux_input_absinfo>() as i32)
}
const EV_SYN: u16 = 0;
const EV_ABS: u16 = 3;
const EV_REPORT: u16 = 0;
const ABS_MT_SLOT: u16 = 0x2F;
const ABS_MT_TOUCH_MAJOR: u16 = 0x30;
const ABS_MT_TOUCH_MINOR: u16 = 0x31;
const ABS_MT_WIDTH_MAJOR: u16 = 0x32;
const ABS_MT_WIDTH_MINOR: u16 = 0x33;
const ABS_MT_ORIENTATION: u16 = 0x34;
const ABS_MT_POSITION_X: u16 = 0x35;
const ABS_MT_POSITION_Y: u16 = 0x36;
const ABS_MT_TRACKING_ID: u16 = 0x39;
struct InputSlot {
tracking_id: i32,
x: i32,
y: i32,
}
fn dist(x1: i32, x2: i32, y1: i32, y2: i32) -> f32 {
let deltaX = (x2 - x1) as f32;
let deltaY = (y2 - y1) as f32;
(deltaX * deltaX + deltaY * deltaY).sqrt()
}
fn read_input_device(device_path: &Path,
sender: &Sender<WindowEvent>) {
let mut device = match File::open(device_path) {
Ok(dev) => dev,
Err(e) => {
println!("Couldn't open device! {}", e);
return;
},
};
let fd = device.as_raw_fd();
let mut x_info: linux_input_absinfo = unsafe { zeroed() };
let mut y_info: linux_input_absinfo = unsafe { zeroed() };
unsafe {
let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_X), &mut x_info);
if ret < 0 {
println!("Couldn't get ABS_MT_POSITION_X info {} {}", ret, errno());
}
}
unsafe {
let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_Y), &mut y_info);
if ret < 0 {
println!("Couldn't get ABS_MT_POSITION_Y info {} {}", ret, errno());
}
}
let touchWidth = x_info.maximum - x_info.minimum;
let touchHeight = y_info.maximum - y_info.minimum;
println!("xMin: {}, yMin: {}, touchWidth: {}, touchHeight: {}",
x_info.minimum, y_info.minimum, touchWidth, touchHeight);
// XXX: Why isn't size_of treated as constant?
// let buf: [u8; (16 * size_of::<linux_input_event>())];
let mut buf: [u8; (16 * 16)] = unsafe { zeroed() };
let mut slots: [InputSlot; 10] = unsafe { zeroed() };
for slot in slots.iter_mut() {
slot.tracking_id = -1;
}
let mut last_x = 0;
let mut last_y = 0;
let mut first_x = 0;
let mut first_y = 0;
let mut last_dist: f32 = 0f32;
let mut touch_count: i32 = 0;
let mut current_slot: usize = 0;
// XXX: Need to use the real dimensions of the screen
let screen_dist = dist(0, 480, 854, 0);
loop {
let read = match device.read(&mut buf) {
Ok(count) => {
assert!(count % size_of::<linux_input_event>() == 0,
"Unexpected input device read length!");
count
},
Err(e) => {
println!("Couldn't read device! {}", e);
return;
}
};
let count = read / size_of::<linux_input_event>();
let events: *mut linux_input_event = unsafe { transmute(buf.as_mut_ptr()) };
let mut tracking_updated = false;
for idx in 0..(count as isize) {
let event: &linux_input_event = unsafe { transmute(events.offset(idx)) };
match (event.evt_type, event.code) {
(EV_SYN, EV_REPORT) => {
let slotA = &slots[0];
if tracking_updated {
tracking_updated = false;
if slotA.tracking_id == -1 {
println!("Touch up");
let delta_x = slotA.x - first_x;
let delta_y = slotA.y - first_y;
let dist = delta_x * delta_x + delta_y * delta_y;
if dist < 16 {
let click_pt = Point2D::typed(slotA.x as f32, slotA.y as f32);
println!("Dispatching click!");
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::MouseDown(MouseButton::Left, click_pt))).ok().unwrap();
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::MouseUp(MouseButton::Left, click_pt))).ok().unwrap();
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::Click(MouseButton::Left, click_pt))).ok().unwrap();
}
} else {
println!("Touch down");
last_x = slotA.x;
last_y = slotA.y;
first_x = slotA.x;
first_y = slotA.y;
if touch_count >= 2 {
let slotB = &slots[1];
last_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y);
}
}
} else {
println!("Touch move x: {}, y: {}", slotA.x, slotA.y);
sender.send(
WindowEvent::Scroll(Point2D::typed((slotA.x - last_x) as f32, (slotA.y - last_y) as f32),
Point2D::typed(slotA.x, slotA.y))).ok().unwrap();
last_x = slotA.x;
last_y = slotA.y;
if touch_count >= 2 {
let slotB = &slots[1];
let cur_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y);
println!("Zooming {} {} {} {}",
cur_dist, last_dist, screen_dist,
((screen_dist + (cur_dist - last_dist))/screen_dist));
sender.send(
WindowEvent::Zoom((screen_dist + (cur_dist - last_dist))/screen_dist)).ok().unwrap();
last_dist = cur_dist;
}
}
},
(EV_SYN, _) => println!("Unknown SYN code {}", event.code),
(EV_ABS, ABS_MT_SLOT) => {
if (event.value as usize) < slots.len() {
current_slot = event.value as usize;
} else {
println!("Invalid slot! {}", event.value);
}
},
(EV_ABS, ABS_MT_TOUCH_MAJOR) => (),
(EV_ABS, ABS_MT_TOUCH_MINOR) => (),
(EV_ABS, ABS_MT_WIDTH_MAJOR) => (),
(EV_ABS, ABS_MT_WIDTH_MINOR) => (),
(EV_ABS, ABS_MT_ORIENTATION) => (),
(EV_ABS, ABS_MT_POSITION_X) => {
slots[current_slot].x = event.value - x_info.minimum;
},
(EV_ABS, ABS_MT_POSITION_Y) => {
slots[current_slot].y = event.value - y_info.minimum;
},
(EV_ABS, ABS_MT_TRACKING_ID) =>
|
,
(EV_ABS, _) => println!("Unknown ABS code {}", event.code),
(_, _) => println!("Unknown event type {}", event.evt_type),
}
}
}
}
pub fn run_input_loop(event_sender: &Sender<WindowEvent>) {
let sender = event_sender.clone();
thread::spawn(move || {
// XXX need to scan all devices and read every one.
let touchinputdev = Path::new("/dev/input/event0");
read_input_device(&touchinputdev, &sender);
});
}
|
{
let current_id = slots[current_slot].tracking_id;
if current_id != event.value &&
(current_id == -1 || event.value == -1) {
tracking_updated = true;
if event.value == -1 {
touch_count -= 1;
} else {
touch_count += 1;
}
}
slots[current_slot].tracking_id = event.value;
}
|
conditional_block
|
input.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use script_traits::MouseButton;
use std::path::Path;
use std::mem::size_of;
use std::mem::transmute;
use std::mem::zeroed;
use std::os::unix::io::AsRawFd;
use std::fs::File;
use std::thread;
use std::sync::mpsc::Sender;
use std::io::Read;
use geom::point::Point2D;
use errno::errno;
use libc::c_int;
use libc::c_long;
use libc::time_t;
use compositing::windowing::WindowEvent;
use compositing::windowing::MouseWindowEvent;
extern {
// XXX: no variadic form in std libs?
fn ioctl(fd: c_int, req: c_int,...) -> c_int;
}
#[repr(C)]
struct linux_input_event {
sec: time_t,
msec: c_long,
evt_type: u16,
code: u16,
value: i32,
}
#[repr(C)]
struct linux_input_absinfo {
value: i32,
minimum: i32,
maximum: i32,
fuzz: i32,
flat: i32,
resolution: i32,
}
const IOC_NONE: c_int = 0;
const IOC_WRITE: c_int = 1;
const IOC_READ: c_int = 2;
fn ioc(dir: c_int, ioctype: c_int, nr: c_int, size: c_int) -> c_int {
dir << 30 | size << 16 | ioctype << 8 | nr
}
fn ev_ioc_g_abs(abs: u16) -> c_int {
ioc(IOC_READ, 'E' as c_int, (0x40 + abs) as i32, size_of::<linux_input_absinfo>() as i32)
}
const EV_SYN: u16 = 0;
const EV_ABS: u16 = 3;
const EV_REPORT: u16 = 0;
const ABS_MT_SLOT: u16 = 0x2F;
const ABS_MT_TOUCH_MAJOR: u16 = 0x30;
const ABS_MT_TOUCH_MINOR: u16 = 0x31;
const ABS_MT_WIDTH_MAJOR: u16 = 0x32;
const ABS_MT_WIDTH_MINOR: u16 = 0x33;
const ABS_MT_ORIENTATION: u16 = 0x34;
const ABS_MT_POSITION_X: u16 = 0x35;
const ABS_MT_POSITION_Y: u16 = 0x36;
const ABS_MT_TRACKING_ID: u16 = 0x39;
struct
|
{
tracking_id: i32,
x: i32,
y: i32,
}
fn dist(x1: i32, x2: i32, y1: i32, y2: i32) -> f32 {
let deltaX = (x2 - x1) as f32;
let deltaY = (y2 - y1) as f32;
(deltaX * deltaX + deltaY * deltaY).sqrt()
}
fn read_input_device(device_path: &Path,
sender: &Sender<WindowEvent>) {
let mut device = match File::open(device_path) {
Ok(dev) => dev,
Err(e) => {
println!("Couldn't open device! {}", e);
return;
},
};
let fd = device.as_raw_fd();
let mut x_info: linux_input_absinfo = unsafe { zeroed() };
let mut y_info: linux_input_absinfo = unsafe { zeroed() };
unsafe {
let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_X), &mut x_info);
if ret < 0 {
println!("Couldn't get ABS_MT_POSITION_X info {} {}", ret, errno());
}
}
unsafe {
let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_Y), &mut y_info);
if ret < 0 {
println!("Couldn't get ABS_MT_POSITION_Y info {} {}", ret, errno());
}
}
let touchWidth = x_info.maximum - x_info.minimum;
let touchHeight = y_info.maximum - y_info.minimum;
println!("xMin: {}, yMin: {}, touchWidth: {}, touchHeight: {}",
x_info.minimum, y_info.minimum, touchWidth, touchHeight);
// XXX: Why isn't size_of treated as constant?
// let buf: [u8; (16 * size_of::<linux_input_event>())];
let mut buf: [u8; (16 * 16)] = unsafe { zeroed() };
let mut slots: [InputSlot; 10] = unsafe { zeroed() };
for slot in slots.iter_mut() {
slot.tracking_id = -1;
}
let mut last_x = 0;
let mut last_y = 0;
let mut first_x = 0;
let mut first_y = 0;
let mut last_dist: f32 = 0f32;
let mut touch_count: i32 = 0;
let mut current_slot: usize = 0;
// XXX: Need to use the real dimensions of the screen
let screen_dist = dist(0, 480, 854, 0);
loop {
let read = match device.read(&mut buf) {
Ok(count) => {
assert!(count % size_of::<linux_input_event>() == 0,
"Unexpected input device read length!");
count
},
Err(e) => {
println!("Couldn't read device! {}", e);
return;
}
};
let count = read / size_of::<linux_input_event>();
let events: *mut linux_input_event = unsafe { transmute(buf.as_mut_ptr()) };
let mut tracking_updated = false;
for idx in 0..(count as isize) {
let event: &linux_input_event = unsafe { transmute(events.offset(idx)) };
match (event.evt_type, event.code) {
(EV_SYN, EV_REPORT) => {
let slotA = &slots[0];
if tracking_updated {
tracking_updated = false;
if slotA.tracking_id == -1 {
println!("Touch up");
let delta_x = slotA.x - first_x;
let delta_y = slotA.y - first_y;
let dist = delta_x * delta_x + delta_y * delta_y;
if dist < 16 {
let click_pt = Point2D::typed(slotA.x as f32, slotA.y as f32);
println!("Dispatching click!");
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::MouseDown(MouseButton::Left, click_pt))).ok().unwrap();
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::MouseUp(MouseButton::Left, click_pt))).ok().unwrap();
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::Click(MouseButton::Left, click_pt))).ok().unwrap();
}
} else {
println!("Touch down");
last_x = slotA.x;
last_y = slotA.y;
first_x = slotA.x;
first_y = slotA.y;
if touch_count >= 2 {
let slotB = &slots[1];
last_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y);
}
}
} else {
println!("Touch move x: {}, y: {}", slotA.x, slotA.y);
sender.send(
WindowEvent::Scroll(Point2D::typed((slotA.x - last_x) as f32, (slotA.y - last_y) as f32),
Point2D::typed(slotA.x, slotA.y))).ok().unwrap();
last_x = slotA.x;
last_y = slotA.y;
if touch_count >= 2 {
let slotB = &slots[1];
let cur_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y);
println!("Zooming {} {} {} {}",
cur_dist, last_dist, screen_dist,
((screen_dist + (cur_dist - last_dist))/screen_dist));
sender.send(
WindowEvent::Zoom((screen_dist + (cur_dist - last_dist))/screen_dist)).ok().unwrap();
last_dist = cur_dist;
}
}
},
(EV_SYN, _) => println!("Unknown SYN code {}", event.code),
(EV_ABS, ABS_MT_SLOT) => {
if (event.value as usize) < slots.len() {
current_slot = event.value as usize;
} else {
println!("Invalid slot! {}", event.value);
}
},
(EV_ABS, ABS_MT_TOUCH_MAJOR) => (),
(EV_ABS, ABS_MT_TOUCH_MINOR) => (),
(EV_ABS, ABS_MT_WIDTH_MAJOR) => (),
(EV_ABS, ABS_MT_WIDTH_MINOR) => (),
(EV_ABS, ABS_MT_ORIENTATION) => (),
(EV_ABS, ABS_MT_POSITION_X) => {
slots[current_slot].x = event.value - x_info.minimum;
},
(EV_ABS, ABS_MT_POSITION_Y) => {
slots[current_slot].y = event.value - y_info.minimum;
},
(EV_ABS, ABS_MT_TRACKING_ID) => {
let current_id = slots[current_slot].tracking_id;
if current_id!= event.value &&
(current_id == -1 || event.value == -1) {
tracking_updated = true;
if event.value == -1 {
touch_count -= 1;
} else {
touch_count += 1;
}
}
slots[current_slot].tracking_id = event.value;
},
(EV_ABS, _) => println!("Unknown ABS code {}", event.code),
(_, _) => println!("Unknown event type {}", event.evt_type),
}
}
}
}
pub fn run_input_loop(event_sender: &Sender<WindowEvent>) {
let sender = event_sender.clone();
thread::spawn(move || {
// XXX need to scan all devices and read every one.
let touchinputdev = Path::new("/dev/input/event0");
read_input_device(&touchinputdev, &sender);
});
}
|
InputSlot
|
identifier_name
|
input.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use script_traits::MouseButton;
use std::path::Path;
use std::mem::size_of;
use std::mem::transmute;
use std::mem::zeroed;
use std::os::unix::io::AsRawFd;
use std::fs::File;
use std::thread;
use std::sync::mpsc::Sender;
use std::io::Read;
use geom::point::Point2D;
use errno::errno;
use libc::c_int;
use libc::c_long;
use libc::time_t;
use compositing::windowing::WindowEvent;
use compositing::windowing::MouseWindowEvent;
extern {
// XXX: no variadic form in std libs?
fn ioctl(fd: c_int, req: c_int,...) -> c_int;
}
#[repr(C)]
struct linux_input_event {
sec: time_t,
msec: c_long,
evt_type: u16,
code: u16,
value: i32,
}
#[repr(C)]
struct linux_input_absinfo {
value: i32,
minimum: i32,
maximum: i32,
fuzz: i32,
flat: i32,
resolution: i32,
}
const IOC_NONE: c_int = 0;
const IOC_WRITE: c_int = 1;
const IOC_READ: c_int = 2;
fn ioc(dir: c_int, ioctype: c_int, nr: c_int, size: c_int) -> c_int {
dir << 30 | size << 16 | ioctype << 8 | nr
}
fn ev_ioc_g_abs(abs: u16) -> c_int
|
const EV_SYN: u16 = 0;
const EV_ABS: u16 = 3;
const EV_REPORT: u16 = 0;
const ABS_MT_SLOT: u16 = 0x2F;
const ABS_MT_TOUCH_MAJOR: u16 = 0x30;
const ABS_MT_TOUCH_MINOR: u16 = 0x31;
const ABS_MT_WIDTH_MAJOR: u16 = 0x32;
const ABS_MT_WIDTH_MINOR: u16 = 0x33;
const ABS_MT_ORIENTATION: u16 = 0x34;
const ABS_MT_POSITION_X: u16 = 0x35;
const ABS_MT_POSITION_Y: u16 = 0x36;
const ABS_MT_TRACKING_ID: u16 = 0x39;
struct InputSlot {
tracking_id: i32,
x: i32,
y: i32,
}
fn dist(x1: i32, x2: i32, y1: i32, y2: i32) -> f32 {
let deltaX = (x2 - x1) as f32;
let deltaY = (y2 - y1) as f32;
(deltaX * deltaX + deltaY * deltaY).sqrt()
}
fn read_input_device(device_path: &Path,
sender: &Sender<WindowEvent>) {
let mut device = match File::open(device_path) {
Ok(dev) => dev,
Err(e) => {
println!("Couldn't open device! {}", e);
return;
},
};
let fd = device.as_raw_fd();
let mut x_info: linux_input_absinfo = unsafe { zeroed() };
let mut y_info: linux_input_absinfo = unsafe { zeroed() };
unsafe {
let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_X), &mut x_info);
if ret < 0 {
println!("Couldn't get ABS_MT_POSITION_X info {} {}", ret, errno());
}
}
unsafe {
let ret = ioctl(fd, ev_ioc_g_abs(ABS_MT_POSITION_Y), &mut y_info);
if ret < 0 {
println!("Couldn't get ABS_MT_POSITION_Y info {} {}", ret, errno());
}
}
let touchWidth = x_info.maximum - x_info.minimum;
let touchHeight = y_info.maximum - y_info.minimum;
println!("xMin: {}, yMin: {}, touchWidth: {}, touchHeight: {}",
x_info.minimum, y_info.minimum, touchWidth, touchHeight);
// XXX: Why isn't size_of treated as constant?
// let buf: [u8; (16 * size_of::<linux_input_event>())];
let mut buf: [u8; (16 * 16)] = unsafe { zeroed() };
let mut slots: [InputSlot; 10] = unsafe { zeroed() };
for slot in slots.iter_mut() {
slot.tracking_id = -1;
}
let mut last_x = 0;
let mut last_y = 0;
let mut first_x = 0;
let mut first_y = 0;
let mut last_dist: f32 = 0f32;
let mut touch_count: i32 = 0;
let mut current_slot: usize = 0;
// XXX: Need to use the real dimensions of the screen
let screen_dist = dist(0, 480, 854, 0);
loop {
let read = match device.read(&mut buf) {
Ok(count) => {
assert!(count % size_of::<linux_input_event>() == 0,
"Unexpected input device read length!");
count
},
Err(e) => {
println!("Couldn't read device! {}", e);
return;
}
};
let count = read / size_of::<linux_input_event>();
let events: *mut linux_input_event = unsafe { transmute(buf.as_mut_ptr()) };
let mut tracking_updated = false;
for idx in 0..(count as isize) {
let event: &linux_input_event = unsafe { transmute(events.offset(idx)) };
match (event.evt_type, event.code) {
(EV_SYN, EV_REPORT) => {
let slotA = &slots[0];
if tracking_updated {
tracking_updated = false;
if slotA.tracking_id == -1 {
println!("Touch up");
let delta_x = slotA.x - first_x;
let delta_y = slotA.y - first_y;
let dist = delta_x * delta_x + delta_y * delta_y;
if dist < 16 {
let click_pt = Point2D::typed(slotA.x as f32, slotA.y as f32);
println!("Dispatching click!");
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::MouseDown(MouseButton::Left, click_pt))).ok().unwrap();
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::MouseUp(MouseButton::Left, click_pt))).ok().unwrap();
sender.send(
WindowEvent::MouseWindowEventClass(
MouseWindowEvent::Click(MouseButton::Left, click_pt))).ok().unwrap();
}
} else {
println!("Touch down");
last_x = slotA.x;
last_y = slotA.y;
first_x = slotA.x;
first_y = slotA.y;
if touch_count >= 2 {
let slotB = &slots[1];
last_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y);
}
}
} else {
println!("Touch move x: {}, y: {}", slotA.x, slotA.y);
sender.send(
WindowEvent::Scroll(Point2D::typed((slotA.x - last_x) as f32, (slotA.y - last_y) as f32),
Point2D::typed(slotA.x, slotA.y))).ok().unwrap();
last_x = slotA.x;
last_y = slotA.y;
if touch_count >= 2 {
let slotB = &slots[1];
let cur_dist = dist(slotA.x, slotB.x, slotA.y, slotB.y);
println!("Zooming {} {} {} {}",
cur_dist, last_dist, screen_dist,
((screen_dist + (cur_dist - last_dist))/screen_dist));
sender.send(
WindowEvent::Zoom((screen_dist + (cur_dist - last_dist))/screen_dist)).ok().unwrap();
last_dist = cur_dist;
}
}
},
(EV_SYN, _) => println!("Unknown SYN code {}", event.code),
(EV_ABS, ABS_MT_SLOT) => {
if (event.value as usize) < slots.len() {
current_slot = event.value as usize;
} else {
println!("Invalid slot! {}", event.value);
}
},
(EV_ABS, ABS_MT_TOUCH_MAJOR) => (),
(EV_ABS, ABS_MT_TOUCH_MINOR) => (),
(EV_ABS, ABS_MT_WIDTH_MAJOR) => (),
(EV_ABS, ABS_MT_WIDTH_MINOR) => (),
(EV_ABS, ABS_MT_ORIENTATION) => (),
(EV_ABS, ABS_MT_POSITION_X) => {
slots[current_slot].x = event.value - x_info.minimum;
},
(EV_ABS, ABS_MT_POSITION_Y) => {
slots[current_slot].y = event.value - y_info.minimum;
},
(EV_ABS, ABS_MT_TRACKING_ID) => {
let current_id = slots[current_slot].tracking_id;
if current_id!= event.value &&
(current_id == -1 || event.value == -1) {
tracking_updated = true;
if event.value == -1 {
touch_count -= 1;
} else {
touch_count += 1;
}
}
slots[current_slot].tracking_id = event.value;
},
(EV_ABS, _) => println!("Unknown ABS code {}", event.code),
(_, _) => println!("Unknown event type {}", event.evt_type),
}
}
}
}
pub fn run_input_loop(event_sender: &Sender<WindowEvent>) {
let sender = event_sender.clone();
thread::spawn(move || {
// XXX need to scan all devices and read every one.
let touchinputdev = Path::new("/dev/input/event0");
read_input_device(&touchinputdev, &sender);
});
}
|
{
ioc(IOC_READ, 'E' as c_int, (0x40 + abs) as i32, size_of::<linux_input_absinfo>() as i32)
}
|
identifier_body
|
opaque_pointer.rs
|
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
/// <div rustbindgen opaque></div>
#[repr(C)]
#[repr(align(4))]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct OtherOpaque {
pub _bindgen_opaque_blob: u32,
}
#[test]
|
assert_eq!(
::std::mem::size_of::<OtherOpaque>(),
4usize,
concat!("Size of: ", stringify!(OtherOpaque))
);
assert_eq!(
::std::mem::align_of::<OtherOpaque>(),
4usize,
concat!("Alignment of ", stringify!(OtherOpaque))
);
}
/// <div rustbindgen opaque></div>
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Opaque {
pub _address: u8,
}
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialEq)]
pub struct WithOpaquePtr {
pub whatever: *mut u8,
pub other: u32,
pub t: OtherOpaque,
}
#[test]
fn bindgen_test_layout_WithOpaquePtr() {
assert_eq!(
::std::mem::size_of::<WithOpaquePtr>(),
16usize,
concat!("Size of: ", stringify!(WithOpaquePtr))
);
assert_eq!(
::std::mem::align_of::<WithOpaquePtr>(),
8usize,
concat!("Alignment of ", stringify!(WithOpaquePtr))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<WithOpaquePtr>())).whatever as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(WithOpaquePtr),
"::",
stringify!(whatever)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<WithOpaquePtr>())).other as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(WithOpaquePtr),
"::",
stringify!(other)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<WithOpaquePtr>())).t as *const _ as usize
},
12usize,
concat!(
"Offset of field: ",
stringify!(WithOpaquePtr),
"::",
stringify!(t)
)
);
}
impl Default for WithOpaquePtr {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
|
fn bindgen_test_layout_OtherOpaque() {
|
random_line_split
|
opaque_pointer.rs
|
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
/// <div rustbindgen opaque></div>
#[repr(C)]
#[repr(align(4))]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct OtherOpaque {
pub _bindgen_opaque_blob: u32,
}
#[test]
fn bindgen_test_layout_OtherOpaque() {
assert_eq!(
::std::mem::size_of::<OtherOpaque>(),
4usize,
concat!("Size of: ", stringify!(OtherOpaque))
);
assert_eq!(
::std::mem::align_of::<OtherOpaque>(),
4usize,
concat!("Alignment of ", stringify!(OtherOpaque))
);
}
/// <div rustbindgen opaque></div>
#[repr(C)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct Opaque {
pub _address: u8,
}
#[repr(C)]
#[derive(Debug, Copy, Clone, Hash, PartialEq)]
pub struct WithOpaquePtr {
pub whatever: *mut u8,
pub other: u32,
pub t: OtherOpaque,
}
#[test]
fn
|
() {
assert_eq!(
::std::mem::size_of::<WithOpaquePtr>(),
16usize,
concat!("Size of: ", stringify!(WithOpaquePtr))
);
assert_eq!(
::std::mem::align_of::<WithOpaquePtr>(),
8usize,
concat!("Alignment of ", stringify!(WithOpaquePtr))
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<WithOpaquePtr>())).whatever as *const _
as usize
},
0usize,
concat!(
"Offset of field: ",
stringify!(WithOpaquePtr),
"::",
stringify!(whatever)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<WithOpaquePtr>())).other as *const _ as usize
},
8usize,
concat!(
"Offset of field: ",
stringify!(WithOpaquePtr),
"::",
stringify!(other)
)
);
assert_eq!(
unsafe {
&(*(::std::ptr::null::<WithOpaquePtr>())).t as *const _ as usize
},
12usize,
concat!(
"Offset of field: ",
stringify!(WithOpaquePtr),
"::",
stringify!(t)
)
);
}
impl Default for WithOpaquePtr {
fn default() -> Self {
let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
}
|
bindgen_test_layout_WithOpaquePtr
|
identifier_name
|
stages.rs
|
/// A stage number
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
pub struct StageNumber(pub i64);
/// Tournament stage type
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StageType {
/// Group type
Group,
/// League type
League,
/// Swiss type
Swiss,
/// Single-elimination type
SingleElimination,
/// Double-elimination type
DoubleElimination,
/// Bracket group type
BracketGroup,
}
/// A tournament stage
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
pub struct
|
{
/// Stage number.
pub number: StageNumber,
/// Name of this stage.
pub name: String,
/// Stage type.
#[serde(rename = "type")]
pub stage_type: StageType,
/// Number of participants of this stage.
pub size: i64,
}
/// A list of tournament stages
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
pub struct Stages(pub Vec<Stage>);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stages_parse() {
let string = r#"
[
{
"number": 1,
"name": "Playoffs",
"type": "single_elimination",
"size": 8
}
]
"#;
let stages: Stages = serde_json::from_str(string).unwrap();
assert_eq!(stages.0.len(), 1);
let s = stages.0.first().unwrap().clone();
assert_eq!(s.number, StageNumber(1i64));
assert_eq!(s.name, "Playoffs".to_owned());
assert_eq!(s.stage_type, StageType::SingleElimination);
assert_eq!(s.size, 8i64);
}
}
|
Stage
|
identifier_name
|
stages.rs
|
/// A stage number
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
pub struct StageNumber(pub i64);
/// Tournament stage type
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StageType {
|
League,
/// Swiss type
Swiss,
/// Single-elimination type
SingleElimination,
/// Double-elimination type
DoubleElimination,
/// Bracket group type
BracketGroup,
}
/// A tournament stage
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
pub struct Stage {
/// Stage number.
pub number: StageNumber,
/// Name of this stage.
pub name: String,
/// Stage type.
#[serde(rename = "type")]
pub stage_type: StageType,
/// Number of participants of this stage.
pub size: i64,
}
/// A list of tournament stages
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)]
pub struct Stages(pub Vec<Stage>);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_stages_parse() {
let string = r#"
[
{
"number": 1,
"name": "Playoffs",
"type": "single_elimination",
"size": 8
}
]
"#;
let stages: Stages = serde_json::from_str(string).unwrap();
assert_eq!(stages.0.len(), 1);
let s = stages.0.first().unwrap().clone();
assert_eq!(s.number, StageNumber(1i64));
assert_eq!(s.name, "Playoffs".to_owned());
assert_eq!(s.stage_type, StageType::SingleElimination);
assert_eq!(s.size, 8i64);
}
}
|
/// Group type
Group,
/// League type
|
random_line_split
|
htmlscriptelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::ascii::AsciiExt;
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::HTMLScriptElementBinding;
use dom::bindings::codegen::Bindings::HTMLScriptElementBinding::HTMLScriptElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived, HTMLScriptElementCast};
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, NodeCast};
use dom::bindings::js::{JSRef, Temporary, OptionalRootable};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::{HTMLScriptElementTypeId, Element, AttributeHandlers};
use dom::element::{ElementCreator, ParserCreated};
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeHelpers, ElementNodeTypeId, window_from_node, CloneChildrenFlag};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;
use encoding::all::UTF_8;
use encoding::types::{Encoding, DecodeReplace};
use servo_net::resource_task::load_whole_resource;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS, StaticStringVec};
use std::cell::Cell;
use url::UrlParser;
#[dom_struct]
pub struct HTMLScriptElement {
htmlelement: HTMLElement,
/// https://html.spec.whatwg.org/multipage/scripting.html#already-started
already_started: Cell<bool>,
/// https://html.spec.whatwg.org/multipage/scripting.html#parser-inserted
parser_inserted: Cell<bool>,
/// https://html.spec.whatwg.org/multipage/scripting.html#non-blocking
///
/// (currently unused)
non_blocking: Cell<bool>,
/// https://html.spec.whatwg.org/multipage/scripting.html#ready-to-be-parser-executed
///
/// (currently unused)
ready_to_be_parser_executed: Cell<bool>,
}
impl HTMLScriptElementDerived for EventTarget {
fn is_htmlscriptelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLScriptElementTypeId))
}
}
impl HTMLScriptElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>,
creator: ElementCreator) -> HTMLScriptElement
|
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>,
creator: ElementCreator) -> Temporary<HTMLScriptElement> {
let element = HTMLScriptElement::new_inherited(localName, prefix, document, creator);
Node::reflect_node(box element, document, HTMLScriptElementBinding::Wrap)
}
}
pub trait HTMLScriptElementHelpers {
/// Prepare a script (<http://www.whatwg.org/html/#prepare-a-script>)
fn prepare(self);
/// Prepare a script, steps 6 and 7.
fn is_javascript(self) -> bool;
/// Set the "already started" flag (<https://whatwg.org/html/#already-started>)
fn mark_already_started(self);
}
/// Supported script types as defined by
/// <http://whatwg.org/html/#support-the-scripting-language>.
static SCRIPT_JS_MIMES: StaticStringVec = &[
"application/ecmascript",
"application/javascript",
"application/x-ecmascript",
"application/x-javascript",
"text/ecmascript",
"text/javascript",
"text/javascript1.0",
"text/javascript1.1",
"text/javascript1.2",
"text/javascript1.3",
"text/javascript1.4",
"text/javascript1.5",
"text/jscript",
"text/livescript",
"text/x-ecmascript",
"text/x-javascript",
];
impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> {
fn prepare(self) {
// https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
// Step 1.
if self.already_started.get() {
return;
}
// Step 2.
let was_parser_inserted = self.parser_inserted.get();
self.parser_inserted.set(false);
// Step 3.
let element: JSRef<Element> = ElementCast::from_ref(self);
if was_parser_inserted && element.has_attribute(&atom!("async")) {
self.non_blocking.set(true);
}
// Step 4.
let text = self.Text();
if text.len() == 0 &&!element.has_attribute(&atom!("src")) {
return;
}
// Step 5.
let node: JSRef<Node> = NodeCast::from_ref(self);
if!node.is_in_doc() {
return;
}
// Step 6, 7.
if!self.is_javascript() {
return;
}
// Step 8.
if was_parser_inserted {
self.parser_inserted.set(true);
self.non_blocking.set(false);
}
// Step 9.
self.already_started.set(true);
// Step 10.
// TODO: If the element is flagged as "parser-inserted", but the element's node document is
// not the Document of the parser that created the element, then abort these steps.
// Step 11.
// TODO: If scripting is disabled for the script element, then the user agent must abort
// these steps at this point. The script is not executed.
// Step 12.
// TODO: If the script element has an `event` attribute and a `for` attribute, then run
// these substeps...
// Step 13.
// TODO: If the script element has a `charset` attribute, then let the script block's
// character encoding for this script element be the result of getting an encoding from the
// value of the `charset` attribute.
// Step 14 and 15.
// TODO: Add support for the `defer` and `async` attributes. (For now, we fetch all
// scripts synchronously and execute them immediately.)
let window = window_from_node(self).root();
let page = window.page();
let base_url = page.get_url();
let (source, url) = match element.get_attribute(ns!(""), &atom!("src")).root() {
Some(src) => {
if src.deref().Value().is_empty() {
// TODO: queue a task to fire a simple event named `error` at the element
return;
}
match UrlParser::new().base_url(&base_url).parse(src.deref().Value().as_slice()) {
Ok(url) => {
// TODO: Do a potentially CORS-enabled fetch with the mode being the current
// state of the element's `crossorigin` content attribute, the origin being
// the origin of the script element's node document, and the default origin
// behaviour set to taint.
match load_whole_resource(&page.resource_task, url) {
Ok((metadata, bytes)) => {
// TODO: use the charset from step 13.
let source = UTF_8.decode(bytes.as_slice(), DecodeReplace).unwrap();
(source, metadata.final_url)
}
Err(_) => {
error!("error loading script {}", src.deref().Value());
return;
}
}
}
Err(_) => {
// TODO: queue a task to fire a simple event named `error` at the element
error!("error parsing URL for script {}", src.deref().Value());
return;
}
}
}
None => (text, base_url)
};
window.evaluate_script_with_result(source.as_slice(), url.serialize().as_slice());
}
fn is_javascript(self) -> bool {
let element: JSRef<Element> = ElementCast::from_ref(self);
match element.get_attribute(ns!(""), &atom!("type")).root().map(|s| s.Value()) {
Some(ref s) if s.is_empty() => {
// type attr exists, but empty means js
debug!("script type empty, inferring js");
true
},
Some(ref s) => {
debug!("script type={:s}", *s);
SCRIPT_JS_MIMES.contains(&s.to_ascii_lower().as_slice().trim_chars(HTML_SPACE_CHARACTERS))
},
None => {
debug!("no script type");
match element.get_attribute(ns!(""), &atom!("language"))
.root()
.map(|s| s.Value()) {
Some(ref s) if s.is_empty() => {
debug!("script language empty, inferring js");
true
},
Some(ref s) => {
debug!("script language={:s}", *s);
SCRIPT_JS_MIMES.contains(&format!("text/{}", s).to_ascii_lower().as_slice())
},
None => {
debug!("no script type or language, inferring js");
true
}
}
}
}
}
fn mark_already_started(self) {
self.already_started.set(true);
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLScriptElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.after_set_attr(attr),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if attr.local_name() == &atom!("src") &&!self.parser_inserted.get() && node.is_in_doc() {
self.prepare();
}
}
fn child_inserted(&self, child: JSRef<Node>) {
match self.super_type() {
Some(ref s) => s.child_inserted(child),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if!self.parser_inserted.get() && node.is_in_doc() {
self.prepare();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => ()
}
if tree_in_doc &&!self.parser_inserted.get() {
self.prepare();
}
}
fn cloning_steps(&self, copy: JSRef<Node>, maybe_doc: Option<JSRef<Document>>,
clone_children: CloneChildrenFlag) {
match self.super_type() {
Some(ref s) => s.cloning_steps(copy, maybe_doc, clone_children),
_ => (),
}
// https://whatwg.org/html/#already-started
if self.already_started.get() {
let copy_elem: JSRef<HTMLScriptElement> = HTMLScriptElementCast::to_ref(copy).unwrap();
copy_elem.mark_already_started();
}
}
}
impl<'a> HTMLScriptElementMethods for JSRef<'a, HTMLScriptElement> {
fn Src(self) -> DOMString {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.get_url_attribute(&atom!("src"))
}
// http://www.whatwg.org/html/#dom-script-text
fn Text(self) -> DOMString {
let node: JSRef<Node> = NodeCast::from_ref(self);
Node::collect_text_contents(node.children())
}
// http://www.whatwg.org/html/#dom-script-text
fn SetText(self, value: DOMString) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.SetTextContent(Some(value))
}
}
impl Reflectable for HTMLScriptElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
|
{
HTMLScriptElement {
htmlelement: HTMLElement::new_inherited(HTMLScriptElementTypeId, localName, prefix, document),
already_started: Cell::new(false),
parser_inserted: Cell::new(creator == ParserCreated),
non_blocking: Cell::new(creator != ParserCreated),
ready_to_be_parser_executed: Cell::new(false),
}
}
|
identifier_body
|
htmlscriptelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::ascii::AsciiExt;
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::HTMLScriptElementBinding;
use dom::bindings::codegen::Bindings::HTMLScriptElementBinding::HTMLScriptElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived, HTMLScriptElementCast};
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, NodeCast};
use dom::bindings::js::{JSRef, Temporary, OptionalRootable};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::{HTMLScriptElementTypeId, Element, AttributeHandlers};
use dom::element::{ElementCreator, ParserCreated};
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeHelpers, ElementNodeTypeId, window_from_node, CloneChildrenFlag};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;
use encoding::all::UTF_8;
use encoding::types::{Encoding, DecodeReplace};
use servo_net::resource_task::load_whole_resource;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS, StaticStringVec};
use std::cell::Cell;
use url::UrlParser;
#[dom_struct]
pub struct HTMLScriptElement {
htmlelement: HTMLElement,
/// https://html.spec.whatwg.org/multipage/scripting.html#already-started
already_started: Cell<bool>,
/// https://html.spec.whatwg.org/multipage/scripting.html#parser-inserted
parser_inserted: Cell<bool>,
/// https://html.spec.whatwg.org/multipage/scripting.html#non-blocking
///
/// (currently unused)
non_blocking: Cell<bool>,
/// https://html.spec.whatwg.org/multipage/scripting.html#ready-to-be-parser-executed
///
/// (currently unused)
ready_to_be_parser_executed: Cell<bool>,
}
impl HTMLScriptElementDerived for EventTarget {
fn is_htmlscriptelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLScriptElementTypeId))
}
}
impl HTMLScriptElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>,
creator: ElementCreator) -> HTMLScriptElement {
HTMLScriptElement {
htmlelement: HTMLElement::new_inherited(HTMLScriptElementTypeId, localName, prefix, document),
already_started: Cell::new(false),
parser_inserted: Cell::new(creator == ParserCreated),
non_blocking: Cell::new(creator!= ParserCreated),
ready_to_be_parser_executed: Cell::new(false),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>,
creator: ElementCreator) -> Temporary<HTMLScriptElement> {
let element = HTMLScriptElement::new_inherited(localName, prefix, document, creator);
Node::reflect_node(box element, document, HTMLScriptElementBinding::Wrap)
}
}
pub trait HTMLScriptElementHelpers {
/// Prepare a script (<http://www.whatwg.org/html/#prepare-a-script>)
fn prepare(self);
/// Prepare a script, steps 6 and 7.
fn is_javascript(self) -> bool;
/// Set the "already started" flag (<https://whatwg.org/html/#already-started>)
fn mark_already_started(self);
}
/// Supported script types as defined by
/// <http://whatwg.org/html/#support-the-scripting-language>.
static SCRIPT_JS_MIMES: StaticStringVec = &[
"application/ecmascript",
"application/javascript",
"application/x-ecmascript",
"application/x-javascript",
"text/ecmascript",
"text/javascript",
"text/javascript1.0",
"text/javascript1.1",
"text/javascript1.2",
"text/javascript1.3",
"text/javascript1.4",
"text/javascript1.5",
"text/jscript",
"text/livescript",
"text/x-ecmascript",
"text/x-javascript",
];
impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> {
fn prepare(self) {
// https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
// Step 1.
if self.already_started.get() {
return;
}
// Step 2.
let was_parser_inserted = self.parser_inserted.get();
self.parser_inserted.set(false);
// Step 3.
let element: JSRef<Element> = ElementCast::from_ref(self);
if was_parser_inserted && element.has_attribute(&atom!("async")) {
self.non_blocking.set(true);
}
// Step 4.
let text = self.Text();
if text.len() == 0 &&!element.has_attribute(&atom!("src")) {
return;
}
// Step 5.
let node: JSRef<Node> = NodeCast::from_ref(self);
if!node.is_in_doc() {
return;
}
// Step 6, 7.
if!self.is_javascript() {
return;
}
// Step 8.
if was_parser_inserted {
self.parser_inserted.set(true);
self.non_blocking.set(false);
}
// Step 9.
self.already_started.set(true);
// Step 10.
// TODO: If the element is flagged as "parser-inserted", but the element's node document is
// not the Document of the parser that created the element, then abort these steps.
// Step 11.
// TODO: If scripting is disabled for the script element, then the user agent must abort
// these steps at this point. The script is not executed.
// Step 12.
// TODO: If the script element has an `event` attribute and a `for` attribute, then run
// these substeps...
// Step 13.
// TODO: If the script element has a `charset` attribute, then let the script block's
// character encoding for this script element be the result of getting an encoding from the
// value of the `charset` attribute.
// Step 14 and 15.
// TODO: Add support for the `defer` and `async` attributes. (For now, we fetch all
// scripts synchronously and execute them immediately.)
let window = window_from_node(self).root();
let page = window.page();
let base_url = page.get_url();
let (source, url) = match element.get_attribute(ns!(""), &atom!("src")).root() {
Some(src) => {
if src.deref().Value().is_empty() {
// TODO: queue a task to fire a simple event named `error` at the element
return;
}
match UrlParser::new().base_url(&base_url).parse(src.deref().Value().as_slice()) {
Ok(url) => {
// TODO: Do a potentially CORS-enabled fetch with the mode being the current
// state of the element's `crossorigin` content attribute, the origin being
// the origin of the script element's node document, and the default origin
// behaviour set to taint.
match load_whole_resource(&page.resource_task, url) {
Ok((metadata, bytes)) => {
// TODO: use the charset from step 13.
let source = UTF_8.decode(bytes.as_slice(), DecodeReplace).unwrap();
(source, metadata.final_url)
}
Err(_) => {
error!("error loading script {}", src.deref().Value());
return;
}
}
}
Err(_) => {
// TODO: queue a task to fire a simple event named `error` at the element
error!("error parsing URL for script {}", src.deref().Value());
return;
}
}
}
None => (text, base_url)
};
window.evaluate_script_with_result(source.as_slice(), url.serialize().as_slice());
}
fn is_javascript(self) -> bool {
let element: JSRef<Element> = ElementCast::from_ref(self);
match element.get_attribute(ns!(""), &atom!("type")).root().map(|s| s.Value()) {
Some(ref s) if s.is_empty() => {
// type attr exists, but empty means js
debug!("script type empty, inferring js");
true
},
Some(ref s) => {
debug!("script type={:s}", *s);
SCRIPT_JS_MIMES.contains(&s.to_ascii_lower().as_slice().trim_chars(HTML_SPACE_CHARACTERS))
},
None => {
debug!("no script type");
match element.get_attribute(ns!(""), &atom!("language"))
.root()
.map(|s| s.Value()) {
Some(ref s) if s.is_empty() => {
debug!("script language empty, inferring js");
true
},
Some(ref s) => {
debug!("script language={:s}", *s);
SCRIPT_JS_MIMES.contains(&format!("text/{}", s).to_ascii_lower().as_slice())
},
None => {
debug!("no script type or language, inferring js");
true
}
}
}
}
}
fn mark_already_started(self) {
self.already_started.set(true);
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLScriptElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.after_set_attr(attr),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if attr.local_name() == &atom!("src") &&!self.parser_inserted.get() && node.is_in_doc() {
self.prepare();
}
}
fn child_inserted(&self, child: JSRef<Node>) {
match self.super_type() {
Some(ref s) => s.child_inserted(child),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if!self.parser_inserted.get() && node.is_in_doc() {
self.prepare();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => ()
}
if tree_in_doc &&!self.parser_inserted.get() {
self.prepare();
}
}
fn cloning_steps(&self, copy: JSRef<Node>, maybe_doc: Option<JSRef<Document>>,
clone_children: CloneChildrenFlag) {
match self.super_type() {
Some(ref s) => s.cloning_steps(copy, maybe_doc, clone_children),
_ => (),
}
// https://whatwg.org/html/#already-started
if self.already_started.get() {
let copy_elem: JSRef<HTMLScriptElement> = HTMLScriptElementCast::to_ref(copy).unwrap();
copy_elem.mark_already_started();
}
}
}
impl<'a> HTMLScriptElementMethods for JSRef<'a, HTMLScriptElement> {
fn Src(self) -> DOMString {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.get_url_attribute(&atom!("src"))
}
// http://www.whatwg.org/html/#dom-script-text
fn Text(self) -> DOMString {
let node: JSRef<Node> = NodeCast::from_ref(self);
Node::collect_text_contents(node.children())
}
// http://www.whatwg.org/html/#dom-script-text
fn SetText(self, value: DOMString) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.SetTextContent(Some(value))
}
}
impl Reflectable for HTMLScriptElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
|
}
|
random_line_split
|
|
htmlscriptelement.rs
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::ascii::AsciiExt;
use dom::attr::Attr;
use dom::attr::AttrHelpers;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::HTMLScriptElementBinding;
use dom::bindings::codegen::Bindings::HTMLScriptElementBinding::HTMLScriptElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLScriptElementDerived, HTMLScriptElementCast};
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, NodeCast};
use dom::bindings::js::{JSRef, Temporary, OptionalRootable};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::document::Document;
use dom::element::{HTMLScriptElementTypeId, Element, AttributeHandlers};
use dom::element::{ElementCreator, ParserCreated};
use dom::eventtarget::{EventTarget, NodeTargetTypeId};
use dom::htmlelement::HTMLElement;
use dom::node::{Node, NodeHelpers, ElementNodeTypeId, window_from_node, CloneChildrenFlag};
use dom::virtualmethods::VirtualMethods;
use dom::window::WindowHelpers;
use encoding::all::UTF_8;
use encoding::types::{Encoding, DecodeReplace};
use servo_net::resource_task::load_whole_resource;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS, StaticStringVec};
use std::cell::Cell;
use url::UrlParser;
#[dom_struct]
pub struct HTMLScriptElement {
htmlelement: HTMLElement,
/// https://html.spec.whatwg.org/multipage/scripting.html#already-started
already_started: Cell<bool>,
/// https://html.spec.whatwg.org/multipage/scripting.html#parser-inserted
parser_inserted: Cell<bool>,
/// https://html.spec.whatwg.org/multipage/scripting.html#non-blocking
///
/// (currently unused)
non_blocking: Cell<bool>,
/// https://html.spec.whatwg.org/multipage/scripting.html#ready-to-be-parser-executed
///
/// (currently unused)
ready_to_be_parser_executed: Cell<bool>,
}
impl HTMLScriptElementDerived for EventTarget {
fn is_htmlscriptelement(&self) -> bool {
*self.type_id() == NodeTargetTypeId(ElementNodeTypeId(HTMLScriptElementTypeId))
}
}
impl HTMLScriptElement {
fn
|
(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>,
creator: ElementCreator) -> HTMLScriptElement {
HTMLScriptElement {
htmlelement: HTMLElement::new_inherited(HTMLScriptElementTypeId, localName, prefix, document),
already_started: Cell::new(false),
parser_inserted: Cell::new(creator == ParserCreated),
non_blocking: Cell::new(creator!= ParserCreated),
ready_to_be_parser_executed: Cell::new(false),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>,
creator: ElementCreator) -> Temporary<HTMLScriptElement> {
let element = HTMLScriptElement::new_inherited(localName, prefix, document, creator);
Node::reflect_node(box element, document, HTMLScriptElementBinding::Wrap)
}
}
pub trait HTMLScriptElementHelpers {
/// Prepare a script (<http://www.whatwg.org/html/#prepare-a-script>)
fn prepare(self);
/// Prepare a script, steps 6 and 7.
fn is_javascript(self) -> bool;
/// Set the "already started" flag (<https://whatwg.org/html/#already-started>)
fn mark_already_started(self);
}
/// Supported script types as defined by
/// <http://whatwg.org/html/#support-the-scripting-language>.
static SCRIPT_JS_MIMES: StaticStringVec = &[
"application/ecmascript",
"application/javascript",
"application/x-ecmascript",
"application/x-javascript",
"text/ecmascript",
"text/javascript",
"text/javascript1.0",
"text/javascript1.1",
"text/javascript1.2",
"text/javascript1.3",
"text/javascript1.4",
"text/javascript1.5",
"text/jscript",
"text/livescript",
"text/x-ecmascript",
"text/x-javascript",
];
impl<'a> HTMLScriptElementHelpers for JSRef<'a, HTMLScriptElement> {
fn prepare(self) {
// https://html.spec.whatwg.org/multipage/scripting.html#prepare-a-script
// Step 1.
if self.already_started.get() {
return;
}
// Step 2.
let was_parser_inserted = self.parser_inserted.get();
self.parser_inserted.set(false);
// Step 3.
let element: JSRef<Element> = ElementCast::from_ref(self);
if was_parser_inserted && element.has_attribute(&atom!("async")) {
self.non_blocking.set(true);
}
// Step 4.
let text = self.Text();
if text.len() == 0 &&!element.has_attribute(&atom!("src")) {
return;
}
// Step 5.
let node: JSRef<Node> = NodeCast::from_ref(self);
if!node.is_in_doc() {
return;
}
// Step 6, 7.
if!self.is_javascript() {
return;
}
// Step 8.
if was_parser_inserted {
self.parser_inserted.set(true);
self.non_blocking.set(false);
}
// Step 9.
self.already_started.set(true);
// Step 10.
// TODO: If the element is flagged as "parser-inserted", but the element's node document is
// not the Document of the parser that created the element, then abort these steps.
// Step 11.
// TODO: If scripting is disabled for the script element, then the user agent must abort
// these steps at this point. The script is not executed.
// Step 12.
// TODO: If the script element has an `event` attribute and a `for` attribute, then run
// these substeps...
// Step 13.
// TODO: If the script element has a `charset` attribute, then let the script block's
// character encoding for this script element be the result of getting an encoding from the
// value of the `charset` attribute.
// Step 14 and 15.
// TODO: Add support for the `defer` and `async` attributes. (For now, we fetch all
// scripts synchronously and execute them immediately.)
let window = window_from_node(self).root();
let page = window.page();
let base_url = page.get_url();
let (source, url) = match element.get_attribute(ns!(""), &atom!("src")).root() {
Some(src) => {
if src.deref().Value().is_empty() {
// TODO: queue a task to fire a simple event named `error` at the element
return;
}
match UrlParser::new().base_url(&base_url).parse(src.deref().Value().as_slice()) {
Ok(url) => {
// TODO: Do a potentially CORS-enabled fetch with the mode being the current
// state of the element's `crossorigin` content attribute, the origin being
// the origin of the script element's node document, and the default origin
// behaviour set to taint.
match load_whole_resource(&page.resource_task, url) {
Ok((metadata, bytes)) => {
// TODO: use the charset from step 13.
let source = UTF_8.decode(bytes.as_slice(), DecodeReplace).unwrap();
(source, metadata.final_url)
}
Err(_) => {
error!("error loading script {}", src.deref().Value());
return;
}
}
}
Err(_) => {
// TODO: queue a task to fire a simple event named `error` at the element
error!("error parsing URL for script {}", src.deref().Value());
return;
}
}
}
None => (text, base_url)
};
window.evaluate_script_with_result(source.as_slice(), url.serialize().as_slice());
}
fn is_javascript(self) -> bool {
let element: JSRef<Element> = ElementCast::from_ref(self);
match element.get_attribute(ns!(""), &atom!("type")).root().map(|s| s.Value()) {
Some(ref s) if s.is_empty() => {
// type attr exists, but empty means js
debug!("script type empty, inferring js");
true
},
Some(ref s) => {
debug!("script type={:s}", *s);
SCRIPT_JS_MIMES.contains(&s.to_ascii_lower().as_slice().trim_chars(HTML_SPACE_CHARACTERS))
},
None => {
debug!("no script type");
match element.get_attribute(ns!(""), &atom!("language"))
.root()
.map(|s| s.Value()) {
Some(ref s) if s.is_empty() => {
debug!("script language empty, inferring js");
true
},
Some(ref s) => {
debug!("script language={:s}", *s);
SCRIPT_JS_MIMES.contains(&format!("text/{}", s).to_ascii_lower().as_slice())
},
None => {
debug!("no script type or language, inferring js");
true
}
}
}
}
}
fn mark_already_started(self) {
self.already_started.set(true);
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLScriptElement> {
fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: JSRef<Attr>) {
match self.super_type() {
Some(ref s) => s.after_set_attr(attr),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if attr.local_name() == &atom!("src") &&!self.parser_inserted.get() && node.is_in_doc() {
self.prepare();
}
}
fn child_inserted(&self, child: JSRef<Node>) {
match self.super_type() {
Some(ref s) => s.child_inserted(child),
_ => (),
}
let node: JSRef<Node> = NodeCast::from_ref(*self);
if!self.parser_inserted.get() && node.is_in_doc() {
self.prepare();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
match self.super_type() {
Some(ref s) => s.bind_to_tree(tree_in_doc),
_ => ()
}
if tree_in_doc &&!self.parser_inserted.get() {
self.prepare();
}
}
fn cloning_steps(&self, copy: JSRef<Node>, maybe_doc: Option<JSRef<Document>>,
clone_children: CloneChildrenFlag) {
match self.super_type() {
Some(ref s) => s.cloning_steps(copy, maybe_doc, clone_children),
_ => (),
}
// https://whatwg.org/html/#already-started
if self.already_started.get() {
let copy_elem: JSRef<HTMLScriptElement> = HTMLScriptElementCast::to_ref(copy).unwrap();
copy_elem.mark_already_started();
}
}
}
impl<'a> HTMLScriptElementMethods for JSRef<'a, HTMLScriptElement> {
fn Src(self) -> DOMString {
let element: JSRef<Element> = ElementCast::from_ref(self);
element.get_url_attribute(&atom!("src"))
}
// http://www.whatwg.org/html/#dom-script-text
fn Text(self) -> DOMString {
let node: JSRef<Node> = NodeCast::from_ref(self);
Node::collect_text_contents(node.children())
}
// http://www.whatwg.org/html/#dom-script-text
fn SetText(self, value: DOMString) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.SetTextContent(Some(value))
}
}
impl Reflectable for HTMLScriptElement {
fn reflector<'a>(&'a self) -> &'a Reflector {
self.htmlelement.reflector()
}
}
|
new_inherited
|
identifier_name
|
closest_points_shape_shape.rs
|
use na::RealField;
use crate::math::{Isometry, Point};
use crate::query::{self, ClosestPoints};
use crate::shape::{Ball, Plane, Segment, Shape};
/// Computes the pair of closest points between two shapes.
///
/// Returns `None` if the objects are separated by a distance greater than `max_dist`.
pub fn closest_points<N: RealField>(
m1: &Isometry<N>,
g1: &dyn Shape<N>,
m2: &Isometry<N>,
g2: &dyn Shape<N>,
max_dist: N,
) -> ClosestPoints<N>
|
panic!("No algorithm known to compute a contact point between the given pair of shapes.")
}
}
|
{
if let (Some(b1), Some(b2)) = (g1.as_shape::<Ball<N>>(), g2.as_shape::<Ball<N>>()) {
let p1 = Point::from(m1.translation.vector);
let p2 = Point::from(m2.translation.vector);
query::closest_points_ball_ball(&p1, b1, &p2, b2, max_dist)
} else if let (Some(s1), Some(s2)) = (g1.as_shape::<Segment<N>>(), g2.as_shape::<Segment<N>>())
{
query::closest_points_segment_segment(m1, s1, m2, s2, max_dist)
} else if let (Some(p1), Some(s2)) = (g1.as_shape::<Plane<N>>(), g2.as_support_map()) {
query::closest_points_plane_support_map(m1, p1, m2, s2, max_dist)
} else if let (Some(s1), Some(p2)) = (g1.as_support_map(), g2.as_shape::<Plane<N>>()) {
query::closest_points_support_map_plane(m1, s1, m2, p2, max_dist)
} else if let (Some(s1), Some(s2)) = (g1.as_support_map(), g2.as_support_map()) {
query::closest_points_support_map_support_map(m1, s1, m2, s2, max_dist)
} else if let Some(c1) = g1.as_composite_shape() {
query::closest_points_composite_shape_shape(m1, c1, m2, g2, max_dist)
} else if let Some(c2) = g2.as_composite_shape() {
query::closest_points_shape_composite_shape(m1, g1, m2, c2, max_dist)
} else {
|
identifier_body
|
closest_points_shape_shape.rs
|
use na::RealField;
use crate::math::{Isometry, Point};
use crate::query::{self, ClosestPoints};
use crate::shape::{Ball, Plane, Segment, Shape};
/// Computes the pair of closest points between two shapes.
///
/// Returns `None` if the objects are separated by a distance greater than `max_dist`.
pub fn closest_points<N: RealField>(
m1: &Isometry<N>,
g1: &dyn Shape<N>,
m2: &Isometry<N>,
g2: &dyn Shape<N>,
max_dist: N,
) -> ClosestPoints<N> {
if let (Some(b1), Some(b2)) = (g1.as_shape::<Ball<N>>(), g2.as_shape::<Ball<N>>()) {
let p1 = Point::from(m1.translation.vector);
let p2 = Point::from(m2.translation.vector);
query::closest_points_ball_ball(&p1, b1, &p2, b2, max_dist)
} else if let (Some(s1), Some(s2)) = (g1.as_shape::<Segment<N>>(), g2.as_shape::<Segment<N>>())
{
query::closest_points_segment_segment(m1, s1, m2, s2, max_dist)
} else if let (Some(p1), Some(s2)) = (g1.as_shape::<Plane<N>>(), g2.as_support_map()) {
query::closest_points_plane_support_map(m1, p1, m2, s2, max_dist)
} else if let (Some(s1), Some(p2)) = (g1.as_support_map(), g2.as_shape::<Plane<N>>()) {
query::closest_points_support_map_plane(m1, s1, m2, p2, max_dist)
} else if let (Some(s1), Some(s2)) = (g1.as_support_map(), g2.as_support_map()) {
query::closest_points_support_map_support_map(m1, s1, m2, s2, max_dist)
} else if let Some(c1) = g1.as_composite_shape()
|
else if let Some(c2) = g2.as_composite_shape() {
query::closest_points_shape_composite_shape(m1, g1, m2, c2, max_dist)
} else {
panic!("No algorithm known to compute a contact point between the given pair of shapes.")
}
}
|
{
query::closest_points_composite_shape_shape(m1, c1, m2, g2, max_dist)
}
|
conditional_block
|
closest_points_shape_shape.rs
|
use na::RealField;
use crate::math::{Isometry, Point};
use crate::query::{self, ClosestPoints};
use crate::shape::{Ball, Plane, Segment, Shape};
/// Computes the pair of closest points between two shapes.
///
/// Returns `None` if the objects are separated by a distance greater than `max_dist`.
pub fn closest_points<N: RealField>(
m1: &Isometry<N>,
g1: &dyn Shape<N>,
m2: &Isometry<N>,
g2: &dyn Shape<N>,
max_dist: N,
) -> ClosestPoints<N> {
if let (Some(b1), Some(b2)) = (g1.as_shape::<Ball<N>>(), g2.as_shape::<Ball<N>>()) {
let p1 = Point::from(m1.translation.vector);
let p2 = Point::from(m2.translation.vector);
query::closest_points_ball_ball(&p1, b1, &p2, b2, max_dist)
|
{
query::closest_points_segment_segment(m1, s1, m2, s2, max_dist)
} else if let (Some(p1), Some(s2)) = (g1.as_shape::<Plane<N>>(), g2.as_support_map()) {
query::closest_points_plane_support_map(m1, p1, m2, s2, max_dist)
} else if let (Some(s1), Some(p2)) = (g1.as_support_map(), g2.as_shape::<Plane<N>>()) {
query::closest_points_support_map_plane(m1, s1, m2, p2, max_dist)
} else if let (Some(s1), Some(s2)) = (g1.as_support_map(), g2.as_support_map()) {
query::closest_points_support_map_support_map(m1, s1, m2, s2, max_dist)
} else if let Some(c1) = g1.as_composite_shape() {
query::closest_points_composite_shape_shape(m1, c1, m2, g2, max_dist)
} else if let Some(c2) = g2.as_composite_shape() {
query::closest_points_shape_composite_shape(m1, g1, m2, c2, max_dist)
} else {
panic!("No algorithm known to compute a contact point between the given pair of shapes.")
}
}
|
} else if let (Some(s1), Some(s2)) = (g1.as_shape::<Segment<N>>(), g2.as_shape::<Segment<N>>())
|
random_line_split
|
closest_points_shape_shape.rs
|
use na::RealField;
use crate::math::{Isometry, Point};
use crate::query::{self, ClosestPoints};
use crate::shape::{Ball, Plane, Segment, Shape};
/// Computes the pair of closest points between two shapes.
///
/// Returns `None` if the objects are separated by a distance greater than `max_dist`.
pub fn
|
<N: RealField>(
m1: &Isometry<N>,
g1: &dyn Shape<N>,
m2: &Isometry<N>,
g2: &dyn Shape<N>,
max_dist: N,
) -> ClosestPoints<N> {
if let (Some(b1), Some(b2)) = (g1.as_shape::<Ball<N>>(), g2.as_shape::<Ball<N>>()) {
let p1 = Point::from(m1.translation.vector);
let p2 = Point::from(m2.translation.vector);
query::closest_points_ball_ball(&p1, b1, &p2, b2, max_dist)
} else if let (Some(s1), Some(s2)) = (g1.as_shape::<Segment<N>>(), g2.as_shape::<Segment<N>>())
{
query::closest_points_segment_segment(m1, s1, m2, s2, max_dist)
} else if let (Some(p1), Some(s2)) = (g1.as_shape::<Plane<N>>(), g2.as_support_map()) {
query::closest_points_plane_support_map(m1, p1, m2, s2, max_dist)
} else if let (Some(s1), Some(p2)) = (g1.as_support_map(), g2.as_shape::<Plane<N>>()) {
query::closest_points_support_map_plane(m1, s1, m2, p2, max_dist)
} else if let (Some(s1), Some(s2)) = (g1.as_support_map(), g2.as_support_map()) {
query::closest_points_support_map_support_map(m1, s1, m2, s2, max_dist)
} else if let Some(c1) = g1.as_composite_shape() {
query::closest_points_composite_shape_shape(m1, c1, m2, g2, max_dist)
} else if let Some(c2) = g2.as_composite_shape() {
query::closest_points_shape_composite_shape(m1, g1, m2, c2, max_dist)
} else {
panic!("No algorithm known to compute a contact point between the given pair of shapes.")
}
}
|
closest_points
|
identifier_name
|
lib.rs
|
#![feature(recover, std_panic, panic_handler, fnbox)]
#[macro_use]
extern crate lazy_static;
pub mod example_group;
mod macros;
mod util;
mod reporter;
mod world;
mod world_result;
mod world_state;
mod example;
mod example_group_and_block;
pub use util::SourceLocation;
use std::sync::{Arc, Mutex};
use world::World;
use example_group::example_group::ExampleGroup;
lazy_static! {
static ref WORLD: Arc<Mutex<World>> = Arc::new(Mutex::new(World::new()));
}
fn with_world<F, T>(blk: F) -> T where F: FnOnce(&mut World) -> T {
let c = WORLD.clone();
let mut guard = c.lock().unwrap();
blk(&mut guard)
}
fn consuming_world<F, T>(blk: F) -> T where F: FnOnce(World) -> T
|
pub fn describe<F>(description: &str, source_location: SourceLocation, example_group_definition_block: F) where F: Fn(&mut ExampleGroup) + Send +'static {
with_world(|world| {
world.describe(description, source_location, example_group_definition_block);
});
}
pub fn descriptor_main() {
consuming_world(|world| world.run());
}
|
{
let guard = WORLD.clone();
let mut world_current = guard.lock().unwrap();
let mut world = World::new();
std::mem::swap(&mut world, &mut world_current);
blk(world)
}
|
identifier_body
|
lib.rs
|
#![feature(recover, std_panic, panic_handler, fnbox)]
#[macro_use]
extern crate lazy_static;
pub mod example_group;
mod macros;
mod util;
mod reporter;
mod world;
mod world_result;
mod world_state;
mod example;
mod example_group_and_block;
pub use util::SourceLocation;
use std::sync::{Arc, Mutex};
use world::World;
use example_group::example_group::ExampleGroup;
lazy_static! {
static ref WORLD: Arc<Mutex<World>> = Arc::new(Mutex::new(World::new()));
}
fn with_world<F, T>(blk: F) -> T where F: FnOnce(&mut World) -> T {
let c = WORLD.clone();
let mut guard = c.lock().unwrap();
blk(&mut guard)
}
fn consuming_world<F, T>(blk: F) -> T where F: FnOnce(World) -> T {
let guard = WORLD.clone();
let mut world_current = guard.lock().unwrap();
let mut world = World::new();
std::mem::swap(&mut world, &mut world_current);
blk(world)
|
});
}
pub fn descriptor_main() {
consuming_world(|world| world.run());
}
|
}
pub fn describe<F>(description: &str, source_location: SourceLocation, example_group_definition_block: F) where F: Fn(&mut ExampleGroup) + Send + 'static {
with_world(|world| {
world.describe(description, source_location, example_group_definition_block);
|
random_line_split
|
lib.rs
|
#![feature(recover, std_panic, panic_handler, fnbox)]
#[macro_use]
extern crate lazy_static;
pub mod example_group;
mod macros;
mod util;
mod reporter;
mod world;
mod world_result;
mod world_state;
mod example;
mod example_group_and_block;
pub use util::SourceLocation;
use std::sync::{Arc, Mutex};
use world::World;
use example_group::example_group::ExampleGroup;
lazy_static! {
static ref WORLD: Arc<Mutex<World>> = Arc::new(Mutex::new(World::new()));
}
fn with_world<F, T>(blk: F) -> T where F: FnOnce(&mut World) -> T {
let c = WORLD.clone();
let mut guard = c.lock().unwrap();
blk(&mut guard)
}
fn
|
<F, T>(blk: F) -> T where F: FnOnce(World) -> T {
let guard = WORLD.clone();
let mut world_current = guard.lock().unwrap();
let mut world = World::new();
std::mem::swap(&mut world, &mut world_current);
blk(world)
}
pub fn describe<F>(description: &str, source_location: SourceLocation, example_group_definition_block: F) where F: Fn(&mut ExampleGroup) + Send +'static {
with_world(|world| {
world.describe(description, source_location, example_group_definition_block);
});
}
pub fn descriptor_main() {
consuming_world(|world| world.run());
}
|
consuming_world
|
identifier_name
|
main.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.
#[macro_use]
extern crate gfx;
extern crate gfx_app;
extern crate image;
pub use gfx_app::ColorFormat;
pub use gfx::format::{Rgba8, DepthStencil};
gfx_vertex_struct!( Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] = "a_Uv",
});
impl Vertex {
fn new(p: [f32; 2], u: [f32; 2]) -> Vertex
|
}
gfx_constant_struct!( Locals {
blend: i32 = "u_Blend",
});
gfx_pipeline!( pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
lena: gfx::TextureSampler<[f32; 4]> = "t_Lena",
tint: gfx::TextureSampler<[f32; 4]> = "t_Tint",
blend: gfx::Global<i32> = "i_Blend",
locals: gfx::ConstantBuffer<Locals> = "Locals",
out: gfx::RenderTarget<ColorFormat> = "Target0",
});
fn load_texture<R, F>(factory: &mut F, data: &[u8])
-> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where
R: gfx::Resources, F: gfx::Factory<R> {
use std::io::Cursor;
use gfx::tex as t;
let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba();
let (width, height) = img.dimensions();
let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single);
let (_, view) = factory.create_texture_const_u8::<Rgba8>(kind, &[&img]).unwrap();
Ok(view)
}
const BLENDS: [&'static str; 9] = [
"Screen",
"Dodge",
"Burn",
"Overlay",
"Multiply",
"Add",
"Divide",
"Grain Extract",
"Grain Merge",
];
struct App<R: gfx::Resources>{
bundle: pipe::Bundle<R>,
id: u8,
}
impl<R: gfx::Resources> gfx_app::Application<R> for App<R> {
fn new<F: gfx::Factory<R>>(mut factory: F, init: gfx_app::Init<R>) -> Self {
use gfx::traits::FactoryExt;
let vs = gfx_app::shade::Source {
glsl_120: include_bytes!("shader/blend_120.glslv"),
glsl_150: include_bytes!("shader/blend_150.glslv"),
hlsl_40: include_bytes!("data/vertex.fx"),
.. gfx_app::shade::Source::empty()
};
let ps = gfx_app::shade::Source {
glsl_120: include_bytes!("shader/blend_120.glslf"),
glsl_150: include_bytes!("shader/blend_150.glslf"),
hlsl_40: include_bytes!("data/pixel.fx"),
.. gfx_app::shade::Source::empty()
};
// fullscreen quad
let vertex_data = [
Vertex::new([-1.0, -1.0], [0.0, 1.0]),
Vertex::new([ 1.0, -1.0], [1.0, 1.0]),
Vertex::new([ 1.0, 1.0], [1.0, 0.0]),
Vertex::new([-1.0, -1.0], [0.0, 1.0]),
Vertex::new([ 1.0, 1.0], [1.0, 0.0]),
Vertex::new([-1.0, 1.0], [0.0, 0.0]),
];
let (vbuf, slice) = factory.create_vertex_buffer(&vertex_data);
let lena_texture = load_texture(&mut factory, &include_bytes!("image/lena.png")[..]).unwrap();
let tint_texture = load_texture(&mut factory, &include_bytes!("image/tint.png")[..]).unwrap();
let sampler = factory.create_sampler_linear();
let pso = factory.create_pipeline_simple(
vs.select(init.backend).unwrap(),
ps.select(init.backend).unwrap(),
gfx::state::CullFace::Nothing,
pipe::new()
).unwrap();
// we pass a integer to our shader to show what blending function we want
// it to use. normally you'd have a shader program per technique, but for
// the sake of simplicity we'll just branch on it inside the shader.
// each index correspond to a conditional branch inside the shader
println!("Using '{}' blend equation", BLENDS[0]);
let cbuf = factory.create_constant_buffer(1);
let data = pipe::Data {
vbuf: vbuf,
lena: (lena_texture, sampler.clone()),
tint: (tint_texture, sampler),
blend: 0,
locals: cbuf,
out: init.color,
};
App {
bundle: pipe::bundle(slice, pso, data),
id: 0,
}
}
//fn update() {
// glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::B)) => {
// let blend_func = blends_cycle.next().unwrap();
// println!("Using '{}' blend equation", blend_func.1);
// data.blend = blend_func.0;
// },
//
//}
fn render<C: gfx::CommandBuffer<R>>(&mut self, encoder: &mut gfx::Encoder<R, C>) {
let locals = Locals { blend: self.id as i32 };
encoder.update_constant_buffer(&self.bundle.data.locals, &locals);
encoder.clear(&self.bundle.data.out, [0.0; 4]);
self.bundle.encode(encoder);
}
}
pub fn main() {
use gfx_app::Application;
App::launch_default("Blending example");
}
|
{
Vertex {
pos: p,
uv: u,
}
}
|
identifier_body
|
main.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.
#[macro_use]
extern crate gfx;
extern crate gfx_app;
extern crate image;
pub use gfx_app::ColorFormat;
pub use gfx::format::{Rgba8, DepthStencil};
gfx_vertex_struct!( Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] = "a_Uv",
});
impl Vertex {
fn new(p: [f32; 2], u: [f32; 2]) -> Vertex {
Vertex {
pos: p,
uv: u,
}
}
}
gfx_constant_struct!( Locals {
blend: i32 = "u_Blend",
});
gfx_pipeline!( pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
lena: gfx::TextureSampler<[f32; 4]> = "t_Lena",
tint: gfx::TextureSampler<[f32; 4]> = "t_Tint",
blend: gfx::Global<i32> = "i_Blend",
locals: gfx::ConstantBuffer<Locals> = "Locals",
out: gfx::RenderTarget<ColorFormat> = "Target0",
});
fn load_texture<R, F>(factory: &mut F, data: &[u8])
-> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where
R: gfx::Resources, F: gfx::Factory<R> {
use std::io::Cursor;
use gfx::tex as t;
let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba();
let (width, height) = img.dimensions();
let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single);
let (_, view) = factory.create_texture_const_u8::<Rgba8>(kind, &[&img]).unwrap();
Ok(view)
}
const BLENDS: [&'static str; 9] = [
"Screen",
"Dodge",
"Burn",
"Overlay",
"Multiply",
"Add",
"Divide",
"Grain Extract",
"Grain Merge",
];
struct
|
<R: gfx::Resources>{
bundle: pipe::Bundle<R>,
id: u8,
}
impl<R: gfx::Resources> gfx_app::Application<R> for App<R> {
fn new<F: gfx::Factory<R>>(mut factory: F, init: gfx_app::Init<R>) -> Self {
use gfx::traits::FactoryExt;
let vs = gfx_app::shade::Source {
glsl_120: include_bytes!("shader/blend_120.glslv"),
glsl_150: include_bytes!("shader/blend_150.glslv"),
hlsl_40: include_bytes!("data/vertex.fx"),
.. gfx_app::shade::Source::empty()
};
let ps = gfx_app::shade::Source {
glsl_120: include_bytes!("shader/blend_120.glslf"),
glsl_150: include_bytes!("shader/blend_150.glslf"),
hlsl_40: include_bytes!("data/pixel.fx"),
.. gfx_app::shade::Source::empty()
};
// fullscreen quad
let vertex_data = [
Vertex::new([-1.0, -1.0], [0.0, 1.0]),
Vertex::new([ 1.0, -1.0], [1.0, 1.0]),
Vertex::new([ 1.0, 1.0], [1.0, 0.0]),
Vertex::new([-1.0, -1.0], [0.0, 1.0]),
Vertex::new([ 1.0, 1.0], [1.0, 0.0]),
Vertex::new([-1.0, 1.0], [0.0, 0.0]),
];
let (vbuf, slice) = factory.create_vertex_buffer(&vertex_data);
let lena_texture = load_texture(&mut factory, &include_bytes!("image/lena.png")[..]).unwrap();
let tint_texture = load_texture(&mut factory, &include_bytes!("image/tint.png")[..]).unwrap();
let sampler = factory.create_sampler_linear();
let pso = factory.create_pipeline_simple(
vs.select(init.backend).unwrap(),
ps.select(init.backend).unwrap(),
gfx::state::CullFace::Nothing,
pipe::new()
).unwrap();
// we pass a integer to our shader to show what blending function we want
// it to use. normally you'd have a shader program per technique, but for
// the sake of simplicity we'll just branch on it inside the shader.
// each index correspond to a conditional branch inside the shader
println!("Using '{}' blend equation", BLENDS[0]);
let cbuf = factory.create_constant_buffer(1);
let data = pipe::Data {
vbuf: vbuf,
lena: (lena_texture, sampler.clone()),
tint: (tint_texture, sampler),
blend: 0,
locals: cbuf,
out: init.color,
};
App {
bundle: pipe::bundle(slice, pso, data),
id: 0,
}
}
//fn update() {
// glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::B)) => {
// let blend_func = blends_cycle.next().unwrap();
// println!("Using '{}' blend equation", blend_func.1);
// data.blend = blend_func.0;
// },
//
//}
fn render<C: gfx::CommandBuffer<R>>(&mut self, encoder: &mut gfx::Encoder<R, C>) {
let locals = Locals { blend: self.id as i32 };
encoder.update_constant_buffer(&self.bundle.data.locals, &locals);
encoder.clear(&self.bundle.data.out, [0.0; 4]);
self.bundle.encode(encoder);
}
}
pub fn main() {
use gfx_app::Application;
App::launch_default("Blending example");
}
|
App
|
identifier_name
|
main.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.
#[macro_use]
extern crate gfx;
extern crate gfx_app;
extern crate image;
pub use gfx_app::ColorFormat;
pub use gfx::format::{Rgba8, DepthStencil};
gfx_vertex_struct!( Vertex {
pos: [f32; 2] = "a_Pos",
uv: [f32; 2] = "a_Uv",
});
impl Vertex {
fn new(p: [f32; 2], u: [f32; 2]) -> Vertex {
Vertex {
pos: p,
uv: u,
}
}
}
gfx_constant_struct!( Locals {
blend: i32 = "u_Blend",
});
gfx_pipeline!( pipe {
vbuf: gfx::VertexBuffer<Vertex> = (),
lena: gfx::TextureSampler<[f32; 4]> = "t_Lena",
tint: gfx::TextureSampler<[f32; 4]> = "t_Tint",
blend: gfx::Global<i32> = "i_Blend",
locals: gfx::ConstantBuffer<Locals> = "Locals",
out: gfx::RenderTarget<ColorFormat> = "Target0",
});
fn load_texture<R, F>(factory: &mut F, data: &[u8])
-> Result<gfx::handle::ShaderResourceView<R, [f32; 4]>, String> where
R: gfx::Resources, F: gfx::Factory<R> {
use std::io::Cursor;
use gfx::tex as t;
let img = image::load(Cursor::new(data), image::PNG).unwrap().to_rgba();
let (width, height) = img.dimensions();
let kind = t::Kind::D2(width as t::Size, height as t::Size, t::AaMode::Single);
let (_, view) = factory.create_texture_const_u8::<Rgba8>(kind, &[&img]).unwrap();
Ok(view)
}
const BLENDS: [&'static str; 9] = [
"Screen",
"Dodge",
"Burn",
"Overlay",
"Multiply",
"Add",
"Divide",
"Grain Extract",
"Grain Merge",
];
struct App<R: gfx::Resources>{
bundle: pipe::Bundle<R>,
id: u8,
}
impl<R: gfx::Resources> gfx_app::Application<R> for App<R> {
fn new<F: gfx::Factory<R>>(mut factory: F, init: gfx_app::Init<R>) -> Self {
use gfx::traits::FactoryExt;
let vs = gfx_app::shade::Source {
glsl_120: include_bytes!("shader/blend_120.glslv"),
glsl_150: include_bytes!("shader/blend_150.glslv"),
hlsl_40: include_bytes!("data/vertex.fx"),
.. gfx_app::shade::Source::empty()
};
let ps = gfx_app::shade::Source {
glsl_120: include_bytes!("shader/blend_120.glslf"),
glsl_150: include_bytes!("shader/blend_150.glslf"),
hlsl_40: include_bytes!("data/pixel.fx"),
.. gfx_app::shade::Source::empty()
};
// fullscreen quad
let vertex_data = [
Vertex::new([-1.0, -1.0], [0.0, 1.0]),
Vertex::new([ 1.0, -1.0], [1.0, 1.0]),
Vertex::new([ 1.0, 1.0], [1.0, 0.0]),
Vertex::new([-1.0, -1.0], [0.0, 1.0]),
Vertex::new([ 1.0, 1.0], [1.0, 0.0]),
Vertex::new([-1.0, 1.0], [0.0, 0.0]),
];
let (vbuf, slice) = factory.create_vertex_buffer(&vertex_data);
let lena_texture = load_texture(&mut factory, &include_bytes!("image/lena.png")[..]).unwrap();
let tint_texture = load_texture(&mut factory, &include_bytes!("image/tint.png")[..]).unwrap();
let sampler = factory.create_sampler_linear();
let pso = factory.create_pipeline_simple(
vs.select(init.backend).unwrap(),
ps.select(init.backend).unwrap(),
gfx::state::CullFace::Nothing,
pipe::new()
).unwrap();
// we pass a integer to our shader to show what blending function we want
// it to use. normally you'd have a shader program per technique, but for
// the sake of simplicity we'll just branch on it inside the shader.
// each index correspond to a conditional branch inside the shader
println!("Using '{}' blend equation", BLENDS[0]);
let cbuf = factory.create_constant_buffer(1);
let data = pipe::Data {
vbuf: vbuf,
lena: (lena_texture, sampler.clone()),
tint: (tint_texture, sampler),
blend: 0,
locals: cbuf,
out: init.color,
};
App {
bundle: pipe::bundle(slice, pso, data),
id: 0,
}
}
//fn update() {
// glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::B)) => {
// let blend_func = blends_cycle.next().unwrap();
// println!("Using '{}' blend equation", blend_func.1);
|
// data.blend = blend_func.0;
// },
//
//}
fn render<C: gfx::CommandBuffer<R>>(&mut self, encoder: &mut gfx::Encoder<R, C>) {
let locals = Locals { blend: self.id as i32 };
encoder.update_constant_buffer(&self.bundle.data.locals, &locals);
encoder.clear(&self.bundle.data.out, [0.0; 4]);
self.bundle.encode(encoder);
}
}
pub fn main() {
use gfx_app::Application;
App::launch_default("Blending example");
}
|
random_line_split
|
|
parser_test.rs
|
extern crate l20n;
extern crate serde;
extern crate serde_json;
use std::io::prelude::*;
use std::fs::File;
use std::io;
use std::fs;
use l20n::ftl::entries::parser::Parser as EntriesParser;
use l20n::ftl::entries::ast::Resource as EntriesResource;
fn read_file(path: &str) -> Result<String, io::Error> {
let mut f = try!(File::open(path));
let mut s = String::new();
try!(f.read_to_string(&mut s));
Ok(s)
}
fn read_json_file(path: &str) -> Result<EntriesResource, io::Error> {
let mut f = try!(File::open(path));
let mut data = String::new();
try!(f.read_to_string(&mut data));
let json = serde_json::from_str(&data).unwrap();
Ok(json)
}
#[test]
fn entries_parser() {
let paths = fs::read_dir("./tests/fixtures/parser/ftl/").unwrap();
for p in paths {
let path = p.unwrap().path();
if path.extension().unwrap().to_str().unwrap()!= "ftl" ||
path.to_str().unwrap().contains("errors")
|
let path_len = path.to_str().unwrap().len();
let entries_path = format!("{}.entries.json",
&path.to_str().unwrap()[0..(path_len - 4)]);
let string = read_file(path.to_str().unwrap()).expect("Failed to read");
let reference_res = read_json_file(&entries_path).expect("Failed to read");
let mut parser = EntriesParser::new(string.trim());
let res = parser.parse();
assert_eq!(reference_res,
res.unwrap(),
"File {} didn't match it's fixture",
path.to_str().unwrap());
}
}
|
{
continue;
}
|
conditional_block
|
parser_test.rs
|
extern crate l20n;
extern crate serde;
extern crate serde_json;
use std::io::prelude::*;
|
use std::fs;
use l20n::ftl::entries::parser::Parser as EntriesParser;
use l20n::ftl::entries::ast::Resource as EntriesResource;
fn read_file(path: &str) -> Result<String, io::Error> {
let mut f = try!(File::open(path));
let mut s = String::new();
try!(f.read_to_string(&mut s));
Ok(s)
}
fn read_json_file(path: &str) -> Result<EntriesResource, io::Error> {
let mut f = try!(File::open(path));
let mut data = String::new();
try!(f.read_to_string(&mut data));
let json = serde_json::from_str(&data).unwrap();
Ok(json)
}
#[test]
fn entries_parser() {
let paths = fs::read_dir("./tests/fixtures/parser/ftl/").unwrap();
for p in paths {
let path = p.unwrap().path();
if path.extension().unwrap().to_str().unwrap()!= "ftl" ||
path.to_str().unwrap().contains("errors") {
continue;
}
let path_len = path.to_str().unwrap().len();
let entries_path = format!("{}.entries.json",
&path.to_str().unwrap()[0..(path_len - 4)]);
let string = read_file(path.to_str().unwrap()).expect("Failed to read");
let reference_res = read_json_file(&entries_path).expect("Failed to read");
let mut parser = EntriesParser::new(string.trim());
let res = parser.parse();
assert_eq!(reference_res,
res.unwrap(),
"File {} didn't match it's fixture",
path.to_str().unwrap());
}
}
|
use std::fs::File;
use std::io;
|
random_line_split
|
parser_test.rs
|
extern crate l20n;
extern crate serde;
extern crate serde_json;
use std::io::prelude::*;
use std::fs::File;
use std::io;
use std::fs;
use l20n::ftl::entries::parser::Parser as EntriesParser;
use l20n::ftl::entries::ast::Resource as EntriesResource;
fn read_file(path: &str) -> Result<String, io::Error> {
let mut f = try!(File::open(path));
let mut s = String::new();
try!(f.read_to_string(&mut s));
Ok(s)
}
fn
|
(path: &str) -> Result<EntriesResource, io::Error> {
let mut f = try!(File::open(path));
let mut data = String::new();
try!(f.read_to_string(&mut data));
let json = serde_json::from_str(&data).unwrap();
Ok(json)
}
#[test]
fn entries_parser() {
let paths = fs::read_dir("./tests/fixtures/parser/ftl/").unwrap();
for p in paths {
let path = p.unwrap().path();
if path.extension().unwrap().to_str().unwrap()!= "ftl" ||
path.to_str().unwrap().contains("errors") {
continue;
}
let path_len = path.to_str().unwrap().len();
let entries_path = format!("{}.entries.json",
&path.to_str().unwrap()[0..(path_len - 4)]);
let string = read_file(path.to_str().unwrap()).expect("Failed to read");
let reference_res = read_json_file(&entries_path).expect("Failed to read");
let mut parser = EntriesParser::new(string.trim());
let res = parser.parse();
assert_eq!(reference_res,
res.unwrap(),
"File {} didn't match it's fixture",
path.to_str().unwrap());
}
}
|
read_json_file
|
identifier_name
|
parser_test.rs
|
extern crate l20n;
extern crate serde;
extern crate serde_json;
use std::io::prelude::*;
use std::fs::File;
use std::io;
use std::fs;
use l20n::ftl::entries::parser::Parser as EntriesParser;
use l20n::ftl::entries::ast::Resource as EntriesResource;
fn read_file(path: &str) -> Result<String, io::Error> {
let mut f = try!(File::open(path));
let mut s = String::new();
try!(f.read_to_string(&mut s));
Ok(s)
}
fn read_json_file(path: &str) -> Result<EntriesResource, io::Error>
|
#[test]
fn entries_parser() {
let paths = fs::read_dir("./tests/fixtures/parser/ftl/").unwrap();
for p in paths {
let path = p.unwrap().path();
if path.extension().unwrap().to_str().unwrap()!= "ftl" ||
path.to_str().unwrap().contains("errors") {
continue;
}
let path_len = path.to_str().unwrap().len();
let entries_path = format!("{}.entries.json",
&path.to_str().unwrap()[0..(path_len - 4)]);
let string = read_file(path.to_str().unwrap()).expect("Failed to read");
let reference_res = read_json_file(&entries_path).expect("Failed to read");
let mut parser = EntriesParser::new(string.trim());
let res = parser.parse();
assert_eq!(reference_res,
res.unwrap(),
"File {} didn't match it's fixture",
path.to_str().unwrap());
}
}
|
{
let mut f = try!(File::open(path));
let mut data = String::new();
try!(f.read_to_string(&mut data));
let json = serde_json::from_str(&data).unwrap();
Ok(json)
}
|
identifier_body
|
too-live-local-in-immovable-gen.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_unsafe)]
#![feature(generators)]
fn
|
() {
unsafe {
static move || {
// Tests that the generator transformation finds out that `a` is not live
// during the yield expression. Type checking will also compute liveness
// and it should also find out that `a` is not live.
// The compiler will panic if the generator transformation finds that
// `a` is live and type checking finds it dead.
let a = {
yield ();
4i32
};
&a;
};
}
}
|
main
|
identifier_name
|
too-live-local-in-immovable-gen.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_unsafe)]
#![feature(generators)]
fn main()
|
{
unsafe {
static move || {
// Tests that the generator transformation finds out that `a` is not live
// during the yield expression. Type checking will also compute liveness
// and it should also find out that `a` is not live.
// The compiler will panic if the generator transformation finds that
// `a` is live and type checking finds it dead.
let a = {
yield ();
4i32
};
&a;
};
}
}
|
identifier_body
|
|
too-live-local-in-immovable-gen.rs
|
// Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![allow(unused_unsafe)]
#![feature(generators)]
fn main() {
unsafe {
static move || {
// Tests that the generator transformation finds out that `a` is not live
// during the yield expression. Type checking will also compute liveness
// and it should also find out that `a` is not live.
// The compiler will panic if the generator transformation finds that
// `a` is live and type checking finds it dead.
let a = {
yield ();
4i32
};
&a;
};
}
}
|
random_line_split
|
|
context_provider.rs
|
use std::{
cell::{Cell, RefCell},
collections::BTreeMap,
rc::Rc,
sync::mpsc,
};
use dces::prelude::*;
|
layout::*,
localization::Localization,
render_object::*,
shell::{ShellRequest, WindowRequest},
utils::Point,
widget_base::*,
};
/// Temporary solution to share dependencies. Will be refactored soon.
#[derive(Clone)]
pub struct ContextProvider {
/// Reference counted cells of render objects.
pub render_objects: Rc<RefCell<BTreeMap<Entity, Box<dyn RenderObject>>>>,
/// Reference counted cells of layouts objects.
pub layouts: Rc<RefCell<BTreeMap<Entity, Box<dyn Layout>>>>,
/// Reference counted cells of handler_map objects.
pub handler_map: Rc<RefCell<EventHandlerMap>>,
/// Reference counted cells of handler_states.
pub states: Rc<RefCell<BTreeMap<Entity, Box<dyn State>>>>,
/// Event adapter objects.
pub event_adapter: EventAdapter,
/// Message adapter objects.
pub message_adapter: MessageAdapter,
/// Reference counted cells of mouse_positions defined as `points`
pub mouse_position: Rc<Cell<Point>>,
/// A window_sender object, used for multiparty session-typed communication.
pub window_sender: mpsc::Sender<WindowRequest>,
/// A shell_sender object, used for multiparty session-typed communication.
pub shell_sender: mpsc::Sender<ShellRequest<WindowAdapter>>,
/// Holds the application name.
pub application_name: String,
/// Reference counted cell to track the `first_run`
pub first_run: Rc<Cell<bool>>,
/// Holds a raw window handler object.
pub raw_window_handle: Option<raw_window_handle::RawWindowHandle>,
// TODO: make it thread safe
/// Reference counted cells that hold the supported localization identifiers.
pub localization: Option<Rc<RefCell<Box<dyn Localization>>>>,
}
impl ContextProvider {
/// Creates a new context provider.
pub fn new(
window_sender: mpsc::Sender<WindowRequest>,
shell_sender: mpsc::Sender<ShellRequest<WindowAdapter>>,
application_name: impl Into<String>,
localization: Option<Rc<RefCell<Box<dyn Localization>>>>,
) -> Self {
ContextProvider {
render_objects: Rc::new(RefCell::new(BTreeMap::new())),
layouts: Rc::new(RefCell::new(BTreeMap::new())),
handler_map: Rc::new(RefCell::new(EventHandlerMap::new())),
states: Rc::new(RefCell::new(BTreeMap::new())),
event_adapter: EventAdapter::new(window_sender.clone()),
message_adapter: MessageAdapter::new(window_sender.clone()),
mouse_position: Rc::new(Cell::new(Point::new(0.0, 0.0))),
window_sender,
shell_sender,
application_name: application_name.into(),
first_run: Rc::new(Cell::new(true)),
raw_window_handle: None,
localization,
}
}
}
|
use super::WindowAdapter;
use crate::{
event::*,
|
random_line_split
|
context_provider.rs
|
use std::{
cell::{Cell, RefCell},
collections::BTreeMap,
rc::Rc,
sync::mpsc,
};
use dces::prelude::*;
use super::WindowAdapter;
use crate::{
event::*,
layout::*,
localization::Localization,
render_object::*,
shell::{ShellRequest, WindowRequest},
utils::Point,
widget_base::*,
};
/// Temporary solution to share dependencies. Will be refactored soon.
#[derive(Clone)]
pub struct ContextProvider {
/// Reference counted cells of render objects.
pub render_objects: Rc<RefCell<BTreeMap<Entity, Box<dyn RenderObject>>>>,
/// Reference counted cells of layouts objects.
pub layouts: Rc<RefCell<BTreeMap<Entity, Box<dyn Layout>>>>,
/// Reference counted cells of handler_map objects.
pub handler_map: Rc<RefCell<EventHandlerMap>>,
/// Reference counted cells of handler_states.
pub states: Rc<RefCell<BTreeMap<Entity, Box<dyn State>>>>,
/// Event adapter objects.
pub event_adapter: EventAdapter,
/// Message adapter objects.
pub message_adapter: MessageAdapter,
/// Reference counted cells of mouse_positions defined as `points`
pub mouse_position: Rc<Cell<Point>>,
/// A window_sender object, used for multiparty session-typed communication.
pub window_sender: mpsc::Sender<WindowRequest>,
/// A shell_sender object, used for multiparty session-typed communication.
pub shell_sender: mpsc::Sender<ShellRequest<WindowAdapter>>,
/// Holds the application name.
pub application_name: String,
/// Reference counted cell to track the `first_run`
pub first_run: Rc<Cell<bool>>,
/// Holds a raw window handler object.
pub raw_window_handle: Option<raw_window_handle::RawWindowHandle>,
// TODO: make it thread safe
/// Reference counted cells that hold the supported localization identifiers.
pub localization: Option<Rc<RefCell<Box<dyn Localization>>>>,
}
impl ContextProvider {
/// Creates a new context provider.
pub fn
|
(
window_sender: mpsc::Sender<WindowRequest>,
shell_sender: mpsc::Sender<ShellRequest<WindowAdapter>>,
application_name: impl Into<String>,
localization: Option<Rc<RefCell<Box<dyn Localization>>>>,
) -> Self {
ContextProvider {
render_objects: Rc::new(RefCell::new(BTreeMap::new())),
layouts: Rc::new(RefCell::new(BTreeMap::new())),
handler_map: Rc::new(RefCell::new(EventHandlerMap::new())),
states: Rc::new(RefCell::new(BTreeMap::new())),
event_adapter: EventAdapter::new(window_sender.clone()),
message_adapter: MessageAdapter::new(window_sender.clone()),
mouse_position: Rc::new(Cell::new(Point::new(0.0, 0.0))),
window_sender,
shell_sender,
application_name: application_name.into(),
first_run: Rc::new(Cell::new(true)),
raw_window_handle: None,
localization,
}
}
}
|
new
|
identifier_name
|
account_meta.rs
|
// Copyright 2015, 2016 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/>.
//! Misc deserialization.
use std::io::{Read, Write};
use std::collections::HashMap;
use serde_json;
use util;
use hash;
/// Collected account metadata
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccountMeta {
/// The name of the account.
pub name: String,
/// The rest of the metadata of the account.
pub meta: String,
/// The 128-bit Uuid of the account, if it has one (brain-wallets don't).
pub uuid: Option<String>,
}
impl Default for AccountMeta {
fn default() -> Self {
AccountMeta {
name: String::new(),
meta: "{}".to_owned(),
uuid: None,
}
}
}
impl AccountMeta {
/// Read a hash map of Address -> AccountMeta.
pub fn read_address_map<R>(reader: R) -> Result<HashMap<util::Address, AccountMeta>, serde_json::Error> where R: Read {
serde_json::from_reader(reader).map(|ok: HashMap<hash::Address, AccountMeta>|
ok.into_iter().map(|(a, m)| (a.into(), m)).collect()
)
}
/// Write a hash map of Address -> AccountMeta.
pub fn
|
<W>(m: &HashMap<util::Address, AccountMeta>, writer: &mut W) -> Result<(), serde_json::Error> where W: Write {
serde_json::to_writer(writer, &m.iter().map(|(a, m)| (a.clone().into(), m)).collect::<HashMap<hash::Address, _>>())
}
}
|
write_address_map
|
identifier_name
|
account_meta.rs
|
// Copyright 2015, 2016 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/>.
//! Misc deserialization.
use std::io::{Read, Write};
use std::collections::HashMap;
use serde_json;
use util;
use hash;
/// Collected account metadata
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccountMeta {
/// The name of the account.
pub name: String,
/// The rest of the metadata of the account.
pub meta: String,
/// The 128-bit Uuid of the account, if it has one (brain-wallets don't).
pub uuid: Option<String>,
}
|
name: String::new(),
meta: "{}".to_owned(),
uuid: None,
}
}
}
impl AccountMeta {
/// Read a hash map of Address -> AccountMeta.
pub fn read_address_map<R>(reader: R) -> Result<HashMap<util::Address, AccountMeta>, serde_json::Error> where R: Read {
serde_json::from_reader(reader).map(|ok: HashMap<hash::Address, AccountMeta>|
ok.into_iter().map(|(a, m)| (a.into(), m)).collect()
)
}
/// Write a hash map of Address -> AccountMeta.
pub fn write_address_map<W>(m: &HashMap<util::Address, AccountMeta>, writer: &mut W) -> Result<(), serde_json::Error> where W: Write {
serde_json::to_writer(writer, &m.iter().map(|(a, m)| (a.clone().into(), m)).collect::<HashMap<hash::Address, _>>())
}
}
|
impl Default for AccountMeta {
fn default() -> Self {
AccountMeta {
|
random_line_split
|
account_meta.rs
|
// Copyright 2015, 2016 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/>.
//! Misc deserialization.
use std::io::{Read, Write};
use std::collections::HashMap;
use serde_json;
use util;
use hash;
/// Collected account metadata
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AccountMeta {
/// The name of the account.
pub name: String,
/// The rest of the metadata of the account.
pub meta: String,
/// The 128-bit Uuid of the account, if it has one (brain-wallets don't).
pub uuid: Option<String>,
}
impl Default for AccountMeta {
fn default() -> Self {
AccountMeta {
name: String::new(),
meta: "{}".to_owned(),
uuid: None,
}
}
}
impl AccountMeta {
/// Read a hash map of Address -> AccountMeta.
pub fn read_address_map<R>(reader: R) -> Result<HashMap<util::Address, AccountMeta>, serde_json::Error> where R: Read {
serde_json::from_reader(reader).map(|ok: HashMap<hash::Address, AccountMeta>|
ok.into_iter().map(|(a, m)| (a.into(), m)).collect()
)
}
/// Write a hash map of Address -> AccountMeta.
pub fn write_address_map<W>(m: &HashMap<util::Address, AccountMeta>, writer: &mut W) -> Result<(), serde_json::Error> where W: Write
|
}
|
{
serde_json::to_writer(writer, &m.iter().map(|(a, m)| (a.clone().into(), m)).collect::<HashMap<hash::Address, _>>())
}
|
identifier_body
|
fallible_impl_from.rs
|
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{is_expn_of, match_panic_def_id, method_chain_args};
use if_chain::if_chain;
use rustc_hir as hir;
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
|
declare_clippy_lint! {
/// ### What it does
/// Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`
///
/// ### Why is this bad?
/// `TryFrom` should be used if there's a possibility of failure.
///
/// ### Example
/// ```rust
/// struct Foo(i32);
///
/// // Bad
/// impl From<String> for Foo {
/// fn from(s: String) -> Self {
/// Foo(s.parse().unwrap())
/// }
/// }
/// ```
///
/// ```rust
/// // Good
/// struct Foo(i32);
///
/// use std::convert::TryFrom;
/// impl TryFrom<String> for Foo {
/// type Error = ();
/// fn try_from(s: String) -> Result<Self, Self::Error> {
/// if let Ok(parsed) = s.parse() {
/// Ok(Foo(parsed))
/// } else {
/// Err(())
/// }
/// }
/// }
/// ```
pub FALLIBLE_IMPL_FROM,
nursery,
"Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
}
declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]);
impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
// check for `impl From<???> for..`
if_chain! {
if let hir::ItemKind::Impl(impl_) = &item.kind;
if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
if cx.tcx.is_diagnostic_item(sym::From, impl_trait_ref.def_id);
then {
lint_impl_body(cx, item.span, impl_.items);
}
}
}
}
fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef]) {
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath};
struct FindPanicUnwrap<'a, 'tcx> {
lcx: &'a LateContext<'tcx>,
typeck_results: &'tcx ty::TypeckResults<'tcx>,
result: Vec<Span>,
}
impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
type Map = Map<'tcx>;
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
// check for `begin_panic`
if_chain! {
if let ExprKind::Call(func_expr, _) = expr.kind;
if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind;
if let Some(path_def_id) = path.res.opt_def_id();
if match_panic_def_id(self.lcx, path_def_id);
if is_expn_of(expr.span, "unreachable").is_none();
then {
self.result.push(expr.span);
}
}
// check for `unwrap`
if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
if is_type_diagnostic_item(self.lcx, reciever_ty, sym::Option)
|| is_type_diagnostic_item(self.lcx, reciever_ty, sym::Result)
{
self.result.push(expr.span);
}
}
// and check sub-expressions
intravisit::walk_expr(self, expr);
}
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::None
}
}
for impl_item in impl_items {
if_chain! {
if impl_item.ident.name == sym::from;
if let ImplItemKind::Fn(_, body_id) =
cx.tcx.hir().impl_item(impl_item.id).kind;
then {
// check the body for `begin_panic` or `unwrap`
let body = cx.tcx.hir().body(body_id);
let mut fpu = FindPanicUnwrap {
lcx: cx,
typeck_results: cx.tcx.typeck(impl_item.id.def_id),
result: Vec::new(),
};
fpu.visit_expr(&body.value);
// if we've found one, lint
if!fpu.result.is_empty() {
span_lint_and_then(
cx,
FALLIBLE_IMPL_FROM,
impl_span,
"consider implementing `TryFrom` instead",
move |diag| {
diag.help(
"`From` is intended for infallible conversions only. \
Use `TryFrom` if there's a possibility for the conversion to fail");
diag.span_note(fpu.result, "potential failure(s)");
});
}
}
}
}
}
|
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{sym, Span};
|
random_line_split
|
fallible_impl_from.rs
|
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{is_expn_of, match_panic_def_id, method_chain_args};
use if_chain::if_chain;
use rustc_hir as hir;
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{sym, Span};
declare_clippy_lint! {
/// ### What it does
/// Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`
///
/// ### Why is this bad?
/// `TryFrom` should be used if there's a possibility of failure.
///
/// ### Example
/// ```rust
/// struct Foo(i32);
///
/// // Bad
/// impl From<String> for Foo {
/// fn from(s: String) -> Self {
/// Foo(s.parse().unwrap())
/// }
/// }
/// ```
///
/// ```rust
/// // Good
/// struct Foo(i32);
///
/// use std::convert::TryFrom;
/// impl TryFrom<String> for Foo {
/// type Error = ();
/// fn try_from(s: String) -> Result<Self, Self::Error> {
/// if let Ok(parsed) = s.parse() {
/// Ok(Foo(parsed))
/// } else {
/// Err(())
/// }
/// }
/// }
/// ```
pub FALLIBLE_IMPL_FROM,
nursery,
"Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
}
declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]);
impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom {
fn
|
(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
// check for `impl From<???> for..`
if_chain! {
if let hir::ItemKind::Impl(impl_) = &item.kind;
if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
if cx.tcx.is_diagnostic_item(sym::From, impl_trait_ref.def_id);
then {
lint_impl_body(cx, item.span, impl_.items);
}
}
}
}
fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef]) {
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath};
struct FindPanicUnwrap<'a, 'tcx> {
lcx: &'a LateContext<'tcx>,
typeck_results: &'tcx ty::TypeckResults<'tcx>,
result: Vec<Span>,
}
impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
type Map = Map<'tcx>;
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
// check for `begin_panic`
if_chain! {
if let ExprKind::Call(func_expr, _) = expr.kind;
if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind;
if let Some(path_def_id) = path.res.opt_def_id();
if match_panic_def_id(self.lcx, path_def_id);
if is_expn_of(expr.span, "unreachable").is_none();
then {
self.result.push(expr.span);
}
}
// check for `unwrap`
if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
if is_type_diagnostic_item(self.lcx, reciever_ty, sym::Option)
|| is_type_diagnostic_item(self.lcx, reciever_ty, sym::Result)
{
self.result.push(expr.span);
}
}
// and check sub-expressions
intravisit::walk_expr(self, expr);
}
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::None
}
}
for impl_item in impl_items {
if_chain! {
if impl_item.ident.name == sym::from;
if let ImplItemKind::Fn(_, body_id) =
cx.tcx.hir().impl_item(impl_item.id).kind;
then {
// check the body for `begin_panic` or `unwrap`
let body = cx.tcx.hir().body(body_id);
let mut fpu = FindPanicUnwrap {
lcx: cx,
typeck_results: cx.tcx.typeck(impl_item.id.def_id),
result: Vec::new(),
};
fpu.visit_expr(&body.value);
// if we've found one, lint
if!fpu.result.is_empty() {
span_lint_and_then(
cx,
FALLIBLE_IMPL_FROM,
impl_span,
"consider implementing `TryFrom` instead",
move |diag| {
diag.help(
"`From` is intended for infallible conversions only. \
Use `TryFrom` if there's a possibility for the conversion to fail");
diag.span_note(fpu.result, "potential failure(s)");
});
}
}
}
}
}
|
check_item
|
identifier_name
|
fallible_impl_from.rs
|
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{is_expn_of, match_panic_def_id, method_chain_args};
use if_chain::if_chain;
use rustc_hir as hir;
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{sym, Span};
declare_clippy_lint! {
/// ### What it does
/// Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`
///
/// ### Why is this bad?
/// `TryFrom` should be used if there's a possibility of failure.
///
/// ### Example
/// ```rust
/// struct Foo(i32);
///
/// // Bad
/// impl From<String> for Foo {
/// fn from(s: String) -> Self {
/// Foo(s.parse().unwrap())
/// }
/// }
/// ```
///
/// ```rust
/// // Good
/// struct Foo(i32);
///
/// use std::convert::TryFrom;
/// impl TryFrom<String> for Foo {
/// type Error = ();
/// fn try_from(s: String) -> Result<Self, Self::Error> {
/// if let Ok(parsed) = s.parse() {
/// Ok(Foo(parsed))
/// } else {
/// Err(())
/// }
/// }
/// }
/// ```
pub FALLIBLE_IMPL_FROM,
nursery,
"Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
}
declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]);
impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>)
|
}
fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef]) {
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath};
struct FindPanicUnwrap<'a, 'tcx> {
lcx: &'a LateContext<'tcx>,
typeck_results: &'tcx ty::TypeckResults<'tcx>,
result: Vec<Span>,
}
impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
type Map = Map<'tcx>;
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
// check for `begin_panic`
if_chain! {
if let ExprKind::Call(func_expr, _) = expr.kind;
if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind;
if let Some(path_def_id) = path.res.opt_def_id();
if match_panic_def_id(self.lcx, path_def_id);
if is_expn_of(expr.span, "unreachable").is_none();
then {
self.result.push(expr.span);
}
}
// check for `unwrap`
if let Some(arglists) = method_chain_args(expr, &["unwrap"]) {
let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
if is_type_diagnostic_item(self.lcx, reciever_ty, sym::Option)
|| is_type_diagnostic_item(self.lcx, reciever_ty, sym::Result)
{
self.result.push(expr.span);
}
}
// and check sub-expressions
intravisit::walk_expr(self, expr);
}
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::None
}
}
for impl_item in impl_items {
if_chain! {
if impl_item.ident.name == sym::from;
if let ImplItemKind::Fn(_, body_id) =
cx.tcx.hir().impl_item(impl_item.id).kind;
then {
// check the body for `begin_panic` or `unwrap`
let body = cx.tcx.hir().body(body_id);
let mut fpu = FindPanicUnwrap {
lcx: cx,
typeck_results: cx.tcx.typeck(impl_item.id.def_id),
result: Vec::new(),
};
fpu.visit_expr(&body.value);
// if we've found one, lint
if!fpu.result.is_empty() {
span_lint_and_then(
cx,
FALLIBLE_IMPL_FROM,
impl_span,
"consider implementing `TryFrom` instead",
move |diag| {
diag.help(
"`From` is intended for infallible conversions only. \
Use `TryFrom` if there's a possibility for the conversion to fail");
diag.span_note(fpu.result, "potential failure(s)");
});
}
}
}
}
}
|
{
// check for `impl From<???> for ..`
if_chain! {
if let hir::ItemKind::Impl(impl_) = &item.kind;
if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
if cx.tcx.is_diagnostic_item(sym::From, impl_trait_ref.def_id);
then {
lint_impl_body(cx, item.span, impl_.items);
}
}
}
|
identifier_body
|
fallible_impl_from.rs
|
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::ty::is_type_diagnostic_item;
use clippy_utils::{is_expn_of, match_panic_def_id, method_chain_args};
use if_chain::if_chain;
use rustc_hir as hir;
use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::hir::map::Map;
use rustc_middle::ty;
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::{sym, Span};
declare_clippy_lint! {
/// ### What it does
/// Checks for impls of `From<..>` that contain `panic!()` or `unwrap()`
///
/// ### Why is this bad?
/// `TryFrom` should be used if there's a possibility of failure.
///
/// ### Example
/// ```rust
/// struct Foo(i32);
///
/// // Bad
/// impl From<String> for Foo {
/// fn from(s: String) -> Self {
/// Foo(s.parse().unwrap())
/// }
/// }
/// ```
///
/// ```rust
/// // Good
/// struct Foo(i32);
///
/// use std::convert::TryFrom;
/// impl TryFrom<String> for Foo {
/// type Error = ();
/// fn try_from(s: String) -> Result<Self, Self::Error> {
/// if let Ok(parsed) = s.parse() {
/// Ok(Foo(parsed))
/// } else {
/// Err(())
/// }
/// }
/// }
/// ```
pub FALLIBLE_IMPL_FROM,
nursery,
"Warn on impls of `From<..>` that contain `panic!()` or `unwrap()`"
}
declare_lint_pass!(FallibleImplFrom => [FALLIBLE_IMPL_FROM]);
impl<'tcx> LateLintPass<'tcx> for FallibleImplFrom {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
// check for `impl From<???> for..`
if_chain! {
if let hir::ItemKind::Impl(impl_) = &item.kind;
if let Some(impl_trait_ref) = cx.tcx.impl_trait_ref(item.def_id);
if cx.tcx.is_diagnostic_item(sym::From, impl_trait_ref.def_id);
then {
lint_impl_body(cx, item.span, impl_.items);
}
}
}
}
fn lint_impl_body<'tcx>(cx: &LateContext<'tcx>, impl_span: Span, impl_items: &[hir::ImplItemRef]) {
use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
use rustc_hir::{Expr, ExprKind, ImplItemKind, QPath};
struct FindPanicUnwrap<'a, 'tcx> {
lcx: &'a LateContext<'tcx>,
typeck_results: &'tcx ty::TypeckResults<'tcx>,
result: Vec<Span>,
}
impl<'a, 'tcx> Visitor<'tcx> for FindPanicUnwrap<'a, 'tcx> {
type Map = Map<'tcx>;
fn visit_expr(&mut self, expr: &'tcx Expr<'_>) {
// check for `begin_panic`
if_chain! {
if let ExprKind::Call(func_expr, _) = expr.kind;
if let ExprKind::Path(QPath::Resolved(_, path)) = func_expr.kind;
if let Some(path_def_id) = path.res.opt_def_id();
if match_panic_def_id(self.lcx, path_def_id);
if is_expn_of(expr.span, "unreachable").is_none();
then {
self.result.push(expr.span);
}
}
// check for `unwrap`
if let Some(arglists) = method_chain_args(expr, &["unwrap"])
|
// and check sub-expressions
intravisit::walk_expr(self, expr);
}
fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
NestedVisitorMap::None
}
}
for impl_item in impl_items {
if_chain! {
if impl_item.ident.name == sym::from;
if let ImplItemKind::Fn(_, body_id) =
cx.tcx.hir().impl_item(impl_item.id).kind;
then {
// check the body for `begin_panic` or `unwrap`
let body = cx.tcx.hir().body(body_id);
let mut fpu = FindPanicUnwrap {
lcx: cx,
typeck_results: cx.tcx.typeck(impl_item.id.def_id),
result: Vec::new(),
};
fpu.visit_expr(&body.value);
// if we've found one, lint
if!fpu.result.is_empty() {
span_lint_and_then(
cx,
FALLIBLE_IMPL_FROM,
impl_span,
"consider implementing `TryFrom` instead",
move |diag| {
diag.help(
"`From` is intended for infallible conversions only. \
Use `TryFrom` if there's a possibility for the conversion to fail");
diag.span_note(fpu.result, "potential failure(s)");
});
}
}
}
}
}
|
{
let reciever_ty = self.typeck_results.expr_ty(&arglists[0][0]).peel_refs();
if is_type_diagnostic_item(self.lcx, reciever_ty, sym::Option)
|| is_type_diagnostic_item(self.lcx, reciever_ty, sym::Result)
{
self.result.push(expr.span);
}
}
|
conditional_block
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.