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 |
---|---|---|---|---|
asm.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # Translation of inline assembly.
use llvm;
use trans::build::*;
use trans::callee;
use trans::common::*;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::expr;
use trans::type_of;
use trans::type_::Type;
use syntax::ast;
use std::ffi::CString;
use libc::{c_uint, c_char};
// Take an inline assembly expression and splat it out via LLVM
pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
-> Block<'blk, 'tcx> {
let fcx = bcx.fcx;
let mut bcx = bcx;
let mut constraints = Vec::new();
let mut output_types = Vec::new();
let temp_scope = fcx.push_custom_cleanup_scope();
let mut ext_inputs = Vec::new();
let mut ext_constraints = Vec::new();
// Prepare the output operands
let outputs = ia.outputs.iter().enumerate().map(|(i, &(ref c, ref out, is_rw))| {
constraints.push((*c).clone());
let out_datum = unpack_datum!(bcx, expr::trans(bcx, &**out));
output_types.push(type_of::type_of(bcx.ccx(), out_datum.ty));
let val = out_datum.val;
if is_rw {
ext_inputs.push(unpack_result!(bcx, {
callee::trans_arg_datum(bcx,
expr_ty(bcx, &**out),
out_datum,
cleanup::CustomScope(temp_scope),
callee::DontAutorefArg)
}));
ext_constraints.push(i.to_string());
}
val
}).collect::<Vec<_>>();
// Now the input operands
let mut inputs = ia.inputs.iter().map(|&(ref c, ref input)| {
constraints.push((*c).clone());
let in_datum = unpack_datum!(bcx, expr::trans(bcx, &**input));
unpack_result!(bcx, {
callee::trans_arg_datum(bcx,
expr_ty(bcx, &**input),
in_datum,
cleanup::CustomScope(temp_scope),
callee::DontAutorefArg)
})
}).collect::<Vec<_>>();
inputs.push_all(&ext_inputs[]);
// no failure occurred preparing operands, no need to cleanup
fcx.pop_custom_cleanup_scope(temp_scope);
let mut constraints = constraints.iter()
.map(|s| s.get().to_string())
.chain(ext_constraints.into_iter())
.collect::<Vec<String>>()
.connect(",");
| .map(|s| format!("~{{{}}}", s.get()))
.collect::<Vec<String>>()
.connect(",");
let more_clobbers = get_clobbers();
if!more_clobbers.is_empty() {
if!clobbers.is_empty() {
clobbers.push(',');
}
clobbers.push_str(&more_clobbers[]);
}
// Add the clobbers to our constraints list
if clobbers.len()!= 0 && constraints.len()!= 0 {
constraints.push(',');
constraints.push_str(&clobbers[]);
} else {
constraints.push_str(&clobbers[]);
}
debug!("Asm Constraints: {}", &constraints[]);
let num_outputs = outputs.len();
// Depending on how many outputs we have, the return type is different
let output_type = if num_outputs == 0 {
Type::void(bcx.ccx())
} else if num_outputs == 1 {
output_types[0]
} else {
Type::struct_(bcx.ccx(), &output_types[], false)
};
let dialect = match ia.dialect {
ast::AsmAtt => llvm::AD_ATT,
ast::AsmIntel => llvm::AD_Intel
};
let asm = CString::from_slice(ia.asm.get().as_bytes());
let constraints = CString::from_slice(constraints.as_bytes());
let r = InlineAsmCall(bcx,
asm.as_ptr(),
constraints.as_ptr(),
inputs.as_slice(),
output_type,
ia.volatile,
ia.alignstack,
dialect);
// Again, based on how many outputs we have
if num_outputs == 1 {
Store(bcx, r, outputs[0]);
} else {
for (i, o) in outputs.iter().enumerate() {
let v = ExtractValue(bcx, r, i);
Store(bcx, v, *o);
}
}
// Store expn_id in a metadata node so we can map LLVM errors
// back to source locations. See #17552.
unsafe {
let key = "srcloc";
let kind = llvm::LLVMGetMDKindIDInContext(bcx.ccx().llcx(),
key.as_ptr() as *const c_char, key.len() as c_uint);
let val: llvm::ValueRef = C_i32(bcx.ccx(), ia.expn_id.to_llvm_cookie());
llvm::LLVMSetMetadata(r, kind,
llvm::LLVMMDNodeInContext(bcx.ccx().llcx(), &val, 1));
}
return bcx;
}
// Default per-arch clobbers
// Basically what clang does
#[cfg(any(target_arch = "arm",
target_arch = "aarch64",
target_arch = "mips",
target_arch = "mipsel"))]
fn get_clobbers() -> String {
"".to_string()
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn get_clobbers() -> String {
"~{dirflag},~{fpsr},~{flags}".to_string()
} | let mut clobbers = ia.clobbers.iter() | random_line_split |
asm.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # Translation of inline assembly.
use llvm;
use trans::build::*;
use trans::callee;
use trans::common::*;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::expr;
use trans::type_of;
use trans::type_::Type;
use syntax::ast;
use std::ffi::CString;
use libc::{c_uint, c_char};
// Take an inline assembly expression and splat it out via LLVM
pub fn | <'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
-> Block<'blk, 'tcx> {
let fcx = bcx.fcx;
let mut bcx = bcx;
let mut constraints = Vec::new();
let mut output_types = Vec::new();
let temp_scope = fcx.push_custom_cleanup_scope();
let mut ext_inputs = Vec::new();
let mut ext_constraints = Vec::new();
// Prepare the output operands
let outputs = ia.outputs.iter().enumerate().map(|(i, &(ref c, ref out, is_rw))| {
constraints.push((*c).clone());
let out_datum = unpack_datum!(bcx, expr::trans(bcx, &**out));
output_types.push(type_of::type_of(bcx.ccx(), out_datum.ty));
let val = out_datum.val;
if is_rw {
ext_inputs.push(unpack_result!(bcx, {
callee::trans_arg_datum(bcx,
expr_ty(bcx, &**out),
out_datum,
cleanup::CustomScope(temp_scope),
callee::DontAutorefArg)
}));
ext_constraints.push(i.to_string());
}
val
}).collect::<Vec<_>>();
// Now the input operands
let mut inputs = ia.inputs.iter().map(|&(ref c, ref input)| {
constraints.push((*c).clone());
let in_datum = unpack_datum!(bcx, expr::trans(bcx, &**input));
unpack_result!(bcx, {
callee::trans_arg_datum(bcx,
expr_ty(bcx, &**input),
in_datum,
cleanup::CustomScope(temp_scope),
callee::DontAutorefArg)
})
}).collect::<Vec<_>>();
inputs.push_all(&ext_inputs[]);
// no failure occurred preparing operands, no need to cleanup
fcx.pop_custom_cleanup_scope(temp_scope);
let mut constraints = constraints.iter()
.map(|s| s.get().to_string())
.chain(ext_constraints.into_iter())
.collect::<Vec<String>>()
.connect(",");
let mut clobbers = ia.clobbers.iter()
.map(|s| format!("~{{{}}}", s.get()))
.collect::<Vec<String>>()
.connect(",");
let more_clobbers = get_clobbers();
if!more_clobbers.is_empty() {
if!clobbers.is_empty() {
clobbers.push(',');
}
clobbers.push_str(&more_clobbers[]);
}
// Add the clobbers to our constraints list
if clobbers.len()!= 0 && constraints.len()!= 0 {
constraints.push(',');
constraints.push_str(&clobbers[]);
} else {
constraints.push_str(&clobbers[]);
}
debug!("Asm Constraints: {}", &constraints[]);
let num_outputs = outputs.len();
// Depending on how many outputs we have, the return type is different
let output_type = if num_outputs == 0 {
Type::void(bcx.ccx())
} else if num_outputs == 1 {
output_types[0]
} else {
Type::struct_(bcx.ccx(), &output_types[], false)
};
let dialect = match ia.dialect {
ast::AsmAtt => llvm::AD_ATT,
ast::AsmIntel => llvm::AD_Intel
};
let asm = CString::from_slice(ia.asm.get().as_bytes());
let constraints = CString::from_slice(constraints.as_bytes());
let r = InlineAsmCall(bcx,
asm.as_ptr(),
constraints.as_ptr(),
inputs.as_slice(),
output_type,
ia.volatile,
ia.alignstack,
dialect);
// Again, based on how many outputs we have
if num_outputs == 1 {
Store(bcx, r, outputs[0]);
} else {
for (i, o) in outputs.iter().enumerate() {
let v = ExtractValue(bcx, r, i);
Store(bcx, v, *o);
}
}
// Store expn_id in a metadata node so we can map LLVM errors
// back to source locations. See #17552.
unsafe {
let key = "srcloc";
let kind = llvm::LLVMGetMDKindIDInContext(bcx.ccx().llcx(),
key.as_ptr() as *const c_char, key.len() as c_uint);
let val: llvm::ValueRef = C_i32(bcx.ccx(), ia.expn_id.to_llvm_cookie());
llvm::LLVMSetMetadata(r, kind,
llvm::LLVMMDNodeInContext(bcx.ccx().llcx(), &val, 1));
}
return bcx;
}
// Default per-arch clobbers
// Basically what clang does
#[cfg(any(target_arch = "arm",
target_arch = "aarch64",
target_arch = "mips",
target_arch = "mipsel"))]
fn get_clobbers() -> String {
"".to_string()
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn get_clobbers() -> String {
"~{dirflag},~{fpsr},~{flags}".to_string()
}
| trans_inline_asm | identifier_name |
asm.rs | // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! # Translation of inline assembly.
use llvm;
use trans::build::*;
use trans::callee;
use trans::common::*;
use trans::cleanup;
use trans::cleanup::CleanupMethods;
use trans::expr;
use trans::type_of;
use trans::type_::Type;
use syntax::ast;
use std::ffi::CString;
use libc::{c_uint, c_char};
// Take an inline assembly expression and splat it out via LLVM
pub fn trans_inline_asm<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, ia: &ast::InlineAsm)
-> Block<'blk, 'tcx> {
let fcx = bcx.fcx;
let mut bcx = bcx;
let mut constraints = Vec::new();
let mut output_types = Vec::new();
let temp_scope = fcx.push_custom_cleanup_scope();
let mut ext_inputs = Vec::new();
let mut ext_constraints = Vec::new();
// Prepare the output operands
let outputs = ia.outputs.iter().enumerate().map(|(i, &(ref c, ref out, is_rw))| {
constraints.push((*c).clone());
let out_datum = unpack_datum!(bcx, expr::trans(bcx, &**out));
output_types.push(type_of::type_of(bcx.ccx(), out_datum.ty));
let val = out_datum.val;
if is_rw {
ext_inputs.push(unpack_result!(bcx, {
callee::trans_arg_datum(bcx,
expr_ty(bcx, &**out),
out_datum,
cleanup::CustomScope(temp_scope),
callee::DontAutorefArg)
}));
ext_constraints.push(i.to_string());
}
val
}).collect::<Vec<_>>();
// Now the input operands
let mut inputs = ia.inputs.iter().map(|&(ref c, ref input)| {
constraints.push((*c).clone());
let in_datum = unpack_datum!(bcx, expr::trans(bcx, &**input));
unpack_result!(bcx, {
callee::trans_arg_datum(bcx,
expr_ty(bcx, &**input),
in_datum,
cleanup::CustomScope(temp_scope),
callee::DontAutorefArg)
})
}).collect::<Vec<_>>();
inputs.push_all(&ext_inputs[]);
// no failure occurred preparing operands, no need to cleanup
fcx.pop_custom_cleanup_scope(temp_scope);
let mut constraints = constraints.iter()
.map(|s| s.get().to_string())
.chain(ext_constraints.into_iter())
.collect::<Vec<String>>()
.connect(",");
let mut clobbers = ia.clobbers.iter()
.map(|s| format!("~{{{}}}", s.get()))
.collect::<Vec<String>>()
.connect(",");
let more_clobbers = get_clobbers();
if!more_clobbers.is_empty() {
if!clobbers.is_empty() {
clobbers.push(',');
}
clobbers.push_str(&more_clobbers[]);
}
// Add the clobbers to our constraints list
if clobbers.len()!= 0 && constraints.len()!= 0 {
constraints.push(',');
constraints.push_str(&clobbers[]);
} else {
constraints.push_str(&clobbers[]);
}
debug!("Asm Constraints: {}", &constraints[]);
let num_outputs = outputs.len();
// Depending on how many outputs we have, the return type is different
let output_type = if num_outputs == 0 {
Type::void(bcx.ccx())
} else if num_outputs == 1 {
output_types[0]
} else {
Type::struct_(bcx.ccx(), &output_types[], false)
};
let dialect = match ia.dialect {
ast::AsmAtt => llvm::AD_ATT,
ast::AsmIntel => llvm::AD_Intel
};
let asm = CString::from_slice(ia.asm.get().as_bytes());
let constraints = CString::from_slice(constraints.as_bytes());
let r = InlineAsmCall(bcx,
asm.as_ptr(),
constraints.as_ptr(),
inputs.as_slice(),
output_type,
ia.volatile,
ia.alignstack,
dialect);
// Again, based on how many outputs we have
if num_outputs == 1 {
Store(bcx, r, outputs[0]);
} else {
for (i, o) in outputs.iter().enumerate() {
let v = ExtractValue(bcx, r, i);
Store(bcx, v, *o);
}
}
// Store expn_id in a metadata node so we can map LLVM errors
// back to source locations. See #17552.
unsafe {
let key = "srcloc";
let kind = llvm::LLVMGetMDKindIDInContext(bcx.ccx().llcx(),
key.as_ptr() as *const c_char, key.len() as c_uint);
let val: llvm::ValueRef = C_i32(bcx.ccx(), ia.expn_id.to_llvm_cookie());
llvm::LLVMSetMetadata(r, kind,
llvm::LLVMMDNodeInContext(bcx.ccx().llcx(), &val, 1));
}
return bcx;
}
// Default per-arch clobbers
// Basically what clang does
#[cfg(any(target_arch = "arm",
target_arch = "aarch64",
target_arch = "mips",
target_arch = "mipsel"))]
fn get_clobbers() -> String |
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn get_clobbers() -> String {
"~{dirflag},~{fpsr},~{flags}".to_string()
}
| {
"".to_string()
} | identifier_body |
communicate.rs | //! Defines the messages passed between client and server.
use cgmath::{Aabb3, Vector2, Vector3, Point3};
use std::default::Default;
use std::ops::Add;
use block_position::BlockPosition;
use entity::EntityId;
use lod::LODIndex;
use serialize::{Copyable, Flatten, MemStream, EOF};
use terrain_block::TerrainBlock;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
/// Unique client ID.
pub struct ClientId(u32);
impl Default for ClientId {
fn default() -> ClientId {
ClientId(0)
}
}
impl Add<u32> for ClientId {
type Output = ClientId;
fn | (self, rhs: u32) -> ClientId {
let ClientId(i) = self;
ClientId(i + rhs)
}
}
#[derive(Debug, Clone)]
/// TerrainBlock plus identifying info, e.g. for transmission between server and client.
pub struct TerrainBlockSend {
#[allow(missing_docs)]
pub position: Copyable<BlockPosition>,
#[allow(missing_docs)]
pub block: TerrainBlock,
#[allow(missing_docs)]
pub lod: Copyable<LODIndex>,
}
flatten_struct_impl!(TerrainBlockSend, position, block, lod);
#[derive(Debug, Clone)]
/// Messages the client sends to the server.
pub enum ClientToServer {
/// Notify the server that the client exists, and provide a "return address".
Init(String),
/// Ping
Ping(Copyable<ClientId>),
/// Ask the server to create a new player.
AddPlayer(Copyable<ClientId>),
/// Add a vector the player's acceleration.
Walk(Copyable<EntityId>, Copyable<Vector3<f32>>),
/// Rotate the player by some amount.
RotatePlayer(Copyable<EntityId>, Copyable<Vector2<f32>>),
/// [Try to] start a jump for the player.
StartJump(Copyable<EntityId>),
/// [Try to] stop a jump for the player.
StopJump(Copyable<EntityId>),
/// Ask the server to send a block of terrain.
RequestBlock(Copyable<ClientId>, Copyable<BlockPosition>, Copyable<LODIndex>),
/// Remove the voxel the given player's looking at.
RemoveVoxel(Copyable<EntityId>),
}
flatten_enum_impl!(
ClientToServer,
Copyable<u8>,
(Init, Copyable(0), Copyable(0), x),
(Ping, Copyable(1), Copyable(1), x),
(AddPlayer, Copyable(2), Copyable(2), x),
(Walk, Copyable(3), Copyable(3), x, y),
(RotatePlayer, Copyable(4), Copyable(4), x, y),
(StartJump, Copyable(5), Copyable(5), x),
(StopJump, Copyable(6), Copyable(6), x),
(RequestBlock, Copyable(7), Copyable(7), x, y, z),
(RemoveVoxel, Copyable(8), Copyable(8), x),
);
#[derive(Debug, Clone)]
/// Messages the server sends to the client.
pub enum ServerToClient {
/// Provide the client a unique id to tag its messages.
LeaseId(Copyable<ClientId>),
/// Ping
Ping(Copyable<()>),
/// Complete an AddPlayer request.
PlayerAdded(Copyable<EntityId>, Copyable<Point3<f32>>),
/// Update a player's position.
UpdatePlayer(Copyable<EntityId>, Copyable<Aabb3<f32>>),
/// Update the client's view of a mob with a given mesh.
UpdateMob(Copyable<EntityId>, Copyable<Aabb3<f32>>),
/// The sun as a [0, 1) portion of its cycle.
UpdateSun(Copyable<f32>),
/// Provide a block of terrain to a client.
UpdateBlock(TerrainBlockSend),
}
flatten_enum_impl!(
ServerToClient,
Copyable<u8>,
(LeaseId, Copyable(0), Copyable(0), x),
(Ping, Copyable(1), Copyable(1), x),
(PlayerAdded, Copyable(2), Copyable(2), x, y),
(UpdatePlayer, Copyable(3), Copyable(3), x, y),
(UpdateMob, Copyable(4), Copyable(4), x, y),
(UpdateSun, Copyable(5), Copyable(5), x),
(UpdateBlock, Copyable(6), Copyable(6), x),
);
| add | identifier_name |
communicate.rs | //! Defines the messages passed between client and server.
use cgmath::{Aabb3, Vector2, Vector3, Point3};
use std::default::Default;
use std::ops::Add;
use block_position::BlockPosition;
use entity::EntityId;
use lod::LODIndex;
use serialize::{Copyable, Flatten, MemStream, EOF};
use terrain_block::TerrainBlock;
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
/// Unique client ID.
pub struct ClientId(u32);
impl Default for ClientId {
fn default() -> ClientId {
ClientId(0)
}
}
impl Add<u32> for ClientId {
type Output = ClientId;
fn add(self, rhs: u32) -> ClientId {
let ClientId(i) = self;
ClientId(i + rhs)
}
}
#[derive(Debug, Clone)]
/// TerrainBlock plus identifying info, e.g. for transmission between server and client.
pub struct TerrainBlockSend {
#[allow(missing_docs)]
pub position: Copyable<BlockPosition>,
#[allow(missing_docs)]
pub block: TerrainBlock,
#[allow(missing_docs)]
pub lod: Copyable<LODIndex>,
}
flatten_struct_impl!(TerrainBlockSend, position, block, lod);
#[derive(Debug, Clone)]
/// Messages the client sends to the server.
pub enum ClientToServer {
/// Notify the server that the client exists, and provide a "return address".
Init(String),
/// Ping
Ping(Copyable<ClientId>),
/// Ask the server to create a new player.
AddPlayer(Copyable<ClientId>),
/// Add a vector the player's acceleration.
Walk(Copyable<EntityId>, Copyable<Vector3<f32>>),
/// Rotate the player by some amount.
RotatePlayer(Copyable<EntityId>, Copyable<Vector2<f32>>),
/// [Try to] start a jump for the player.
StartJump(Copyable<EntityId>),
/// [Try to] stop a jump for the player.
StopJump(Copyable<EntityId>),
/// Ask the server to send a block of terrain.
RequestBlock(Copyable<ClientId>, Copyable<BlockPosition>, Copyable<LODIndex>),
/// Remove the voxel the given player's looking at.
RemoveVoxel(Copyable<EntityId>),
}
flatten_enum_impl!(
ClientToServer,
Copyable<u8>,
(Init, Copyable(0), Copyable(0), x),
(Ping, Copyable(1), Copyable(1), x),
(AddPlayer, Copyable(2), Copyable(2), x),
(Walk, Copyable(3), Copyable(3), x, y),
(RotatePlayer, Copyable(4), Copyable(4), x, y),
(StartJump, Copyable(5), Copyable(5), x),
(StopJump, Copyable(6), Copyable(6), x),
(RequestBlock, Copyable(7), Copyable(7), x, y, z),
(RemoveVoxel, Copyable(8), Copyable(8), x),
);
#[derive(Debug, Clone)]
/// Messages the server sends to the client.
pub enum ServerToClient {
/// Provide the client a unique id to tag its messages.
LeaseId(Copyable<ClientId>),
/// Ping
Ping(Copyable<()>),
/// Complete an AddPlayer request.
PlayerAdded(Copyable<EntityId>, Copyable<Point3<f32>>),
/// Update a player's position. | UpdatePlayer(Copyable<EntityId>, Copyable<Aabb3<f32>>),
/// Update the client's view of a mob with a given mesh.
UpdateMob(Copyable<EntityId>, Copyable<Aabb3<f32>>),
/// The sun as a [0, 1) portion of its cycle.
UpdateSun(Copyable<f32>),
/// Provide a block of terrain to a client.
UpdateBlock(TerrainBlockSend),
}
flatten_enum_impl!(
ServerToClient,
Copyable<u8>,
(LeaseId, Copyable(0), Copyable(0), x),
(Ping, Copyable(1), Copyable(1), x),
(PlayerAdded, Copyable(2), Copyable(2), x, y),
(UpdatePlayer, Copyable(3), Copyable(3), x, y),
(UpdateMob, Copyable(4), Copyable(4), x, y),
(UpdateSun, Copyable(5), Copyable(5), x),
(UpdateBlock, Copyable(6), Copyable(6), x),
); | random_line_split |
|
ccuclkcr.rs | #[doc = "Register `CCUCLKCR` reader"]
pub struct R(crate::R<CCUCLKCR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CCUCLKCR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CCUCLKCR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CCUCLKCR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `CCUCLKCR` writer"]
pub struct W(crate::W<CCUCLKCR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<CCUCLKCR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<CCUCLKCR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<CCUCLKCR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "CCU Clock Divider Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CCUDIV_A {
#[doc = "0: fCCU = fSYS"]
VALUE1 = 0,
#[doc = "1: fCCU = fSYS / 2"]
VALUE2 = 1,
}
impl From<CCUDIV_A> for bool {
#[inline(always)]
fn from(variant: CCUDIV_A) -> Self {
variant as u8!= 0
}
}
#[doc = "Field `CCUDIV` reader - CCU Clock Divider Enable"]
pub struct CCUDIV_R(crate::FieldReader<bool, CCUDIV_A>);
impl CCUDIV_R {
pub(crate) fn new(bits: bool) -> Self {
CCUDIV_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CCUDIV_A {
match self.bits {
false => CCUDIV_A::VALUE1,
true => CCUDIV_A::VALUE2,
}
}
#[doc = "Checks if the value of the field is `VALUE1`"]
#[inline(always)]
pub fn is_value1(&self) -> bool {
**self == CCUDIV_A::VALUE1
}
#[doc = "Checks if the value of the field is `VALUE2`"]
#[inline(always)]
pub fn is_value2(&self) -> bool {
**self == CCUDIV_A::VALUE2
}
}
impl core::ops::Deref for CCUDIV_R {
type Target = crate::FieldReader<bool, CCUDIV_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CCUDIV` writer - CCU Clock Divider Enable"]
pub struct CCUDIV_W<'a> {
w: &'a mut W,
}
impl<'a> CCUDIV_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CCUDIV_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "fCCU = fSYS"]
#[inline(always)]
pub fn value1(self) -> &'a mut W {
self.variant(CCUDIV_A::VALUE1)
}
#[doc = "fCCU = fSYS / 2"]
#[inline(always)]
pub fn value2(self) -> &'a mut W {
self.variant(CCUDIV_A::VALUE2)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"] | }
}
impl R {
#[doc = "Bit 0 - CCU Clock Divider Enable"]
#[inline(always)]
pub fn ccudiv(&self) -> CCUDIV_R {
CCUDIV_R::new((self.bits & 0x01)!= 0)
}
}
impl W {
#[doc = "Bit 0 - CCU Clock Divider Enable"]
#[inline(always)]
pub fn ccudiv(&mut self) -> CCUDIV_W {
CCUDIV_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "CCU Clock Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ccuclkcr](index.html) module"]
pub struct CCUCLKCR_SPEC;
impl crate::RegisterSpec for CCUCLKCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [ccuclkcr::R](R) reader structure"]
impl crate::Readable for CCUCLKCR_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [ccuclkcr::W](W) writer structure"]
impl crate::Writable for CCUCLKCR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets CCUCLKCR to value 0"]
impl crate::Resettable for CCUCLKCR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
} | #[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w | random_line_split |
ccuclkcr.rs | #[doc = "Register `CCUCLKCR` reader"]
pub struct R(crate::R<CCUCLKCR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CCUCLKCR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CCUCLKCR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CCUCLKCR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `CCUCLKCR` writer"]
pub struct | (crate::W<CCUCLKCR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<CCUCLKCR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<CCUCLKCR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<CCUCLKCR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "CCU Clock Divider Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CCUDIV_A {
#[doc = "0: fCCU = fSYS"]
VALUE1 = 0,
#[doc = "1: fCCU = fSYS / 2"]
VALUE2 = 1,
}
impl From<CCUDIV_A> for bool {
#[inline(always)]
fn from(variant: CCUDIV_A) -> Self {
variant as u8!= 0
}
}
#[doc = "Field `CCUDIV` reader - CCU Clock Divider Enable"]
pub struct CCUDIV_R(crate::FieldReader<bool, CCUDIV_A>);
impl CCUDIV_R {
pub(crate) fn new(bits: bool) -> Self {
CCUDIV_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CCUDIV_A {
match self.bits {
false => CCUDIV_A::VALUE1,
true => CCUDIV_A::VALUE2,
}
}
#[doc = "Checks if the value of the field is `VALUE1`"]
#[inline(always)]
pub fn is_value1(&self) -> bool {
**self == CCUDIV_A::VALUE1
}
#[doc = "Checks if the value of the field is `VALUE2`"]
#[inline(always)]
pub fn is_value2(&self) -> bool {
**self == CCUDIV_A::VALUE2
}
}
impl core::ops::Deref for CCUDIV_R {
type Target = crate::FieldReader<bool, CCUDIV_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CCUDIV` writer - CCU Clock Divider Enable"]
pub struct CCUDIV_W<'a> {
w: &'a mut W,
}
impl<'a> CCUDIV_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CCUDIV_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "fCCU = fSYS"]
#[inline(always)]
pub fn value1(self) -> &'a mut W {
self.variant(CCUDIV_A::VALUE1)
}
#[doc = "fCCU = fSYS / 2"]
#[inline(always)]
pub fn value2(self) -> &'a mut W {
self.variant(CCUDIV_A::VALUE2)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits &!0x01) | (value as u32 & 0x01);
self.w
}
}
impl R {
#[doc = "Bit 0 - CCU Clock Divider Enable"]
#[inline(always)]
pub fn ccudiv(&self) -> CCUDIV_R {
CCUDIV_R::new((self.bits & 0x01)!= 0)
}
}
impl W {
#[doc = "Bit 0 - CCU Clock Divider Enable"]
#[inline(always)]
pub fn ccudiv(&mut self) -> CCUDIV_W {
CCUDIV_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "CCU Clock Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ccuclkcr](index.html) module"]
pub struct CCUCLKCR_SPEC;
impl crate::RegisterSpec for CCUCLKCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [ccuclkcr::R](R) reader structure"]
impl crate::Readable for CCUCLKCR_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [ccuclkcr::W](W) writer structure"]
impl crate::Writable for CCUCLKCR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets CCUCLKCR to value 0"]
impl crate::Resettable for CCUCLKCR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| W | identifier_name |
ccuclkcr.rs | #[doc = "Register `CCUCLKCR` reader"]
pub struct R(crate::R<CCUCLKCR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<CCUCLKCR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<CCUCLKCR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<CCUCLKCR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `CCUCLKCR` writer"]
pub struct W(crate::W<CCUCLKCR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<CCUCLKCR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<CCUCLKCR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<CCUCLKCR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "CCU Clock Divider Enable\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CCUDIV_A {
#[doc = "0: fCCU = fSYS"]
VALUE1 = 0,
#[doc = "1: fCCU = fSYS / 2"]
VALUE2 = 1,
}
impl From<CCUDIV_A> for bool {
#[inline(always)]
fn from(variant: CCUDIV_A) -> Self {
variant as u8!= 0
}
}
#[doc = "Field `CCUDIV` reader - CCU Clock Divider Enable"]
pub struct CCUDIV_R(crate::FieldReader<bool, CCUDIV_A>);
impl CCUDIV_R {
pub(crate) fn new(bits: bool) -> Self {
CCUDIV_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> CCUDIV_A {
match self.bits {
false => CCUDIV_A::VALUE1,
true => CCUDIV_A::VALUE2,
}
}
#[doc = "Checks if the value of the field is `VALUE1`"]
#[inline(always)]
pub fn is_value1(&self) -> bool {
**self == CCUDIV_A::VALUE1
}
#[doc = "Checks if the value of the field is `VALUE2`"]
#[inline(always)]
pub fn is_value2(&self) -> bool {
**self == CCUDIV_A::VALUE2
}
}
impl core::ops::Deref for CCUDIV_R {
type Target = crate::FieldReader<bool, CCUDIV_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CCUDIV` writer - CCU Clock Divider Enable"]
pub struct CCUDIV_W<'a> {
w: &'a mut W,
}
impl<'a> CCUDIV_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CCUDIV_A) -> &'a mut W {
self.bit(variant.into())
}
#[doc = "fCCU = fSYS"]
#[inline(always)]
pub fn value1(self) -> &'a mut W {
self.variant(CCUDIV_A::VALUE1)
}
#[doc = "fCCU = fSYS / 2"]
#[inline(always)]
pub fn value2(self) -> &'a mut W {
self.variant(CCUDIV_A::VALUE2)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W |
}
impl R {
#[doc = "Bit 0 - CCU Clock Divider Enable"]
#[inline(always)]
pub fn ccudiv(&self) -> CCUDIV_R {
CCUDIV_R::new((self.bits & 0x01)!= 0)
}
}
impl W {
#[doc = "Bit 0 - CCU Clock Divider Enable"]
#[inline(always)]
pub fn ccudiv(&mut self) -> CCUDIV_W {
CCUDIV_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "CCU Clock Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ccuclkcr](index.html) module"]
pub struct CCUCLKCR_SPEC;
impl crate::RegisterSpec for CCUCLKCR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [ccuclkcr::R](R) reader structure"]
impl crate::Readable for CCUCLKCR_SPEC {
type Reader = R;
}
#[doc = "`write(|w|..)` method takes [ccuclkcr::W](W) writer structure"]
impl crate::Writable for CCUCLKCR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets CCUCLKCR to value 0"]
impl crate::Resettable for CCUCLKCR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
| {
self.w.bits = (self.w.bits & !0x01) | (value as u32 & 0x01);
self.w
} | identifier_body |
strutil.rs | // miscelaneous string utilities
// returns the string slice following the target, if any
pub fn after<'a>(s: &'a str, target: &str) -> Option<&'a str> {
if let Some(idx) = s.find(target) {
Some(&s[(idx+target.len())..])
} else {
None
}
} | // like after, but subsequently finds a word following...
pub fn word_after(txt: &str, target: &str) -> Option<String> {
if let Some(txt) = after(txt,target) {
// maybe skip some space, and end with whitespace or semicolon
let start = txt.find(|c:char| c.is_alphanumeric()).unwrap();
let end = txt.find(|c:char| c == ';' || c.is_whitespace()).unwrap();
Some((&txt[start..end]).to_string())
} else {
None
}
}
// next two items from an iterator, assuming that it has at least two items...
pub fn next_2<T, I: Iterator<Item=T>> (mut iter: I) -> (T,T) {
(iter.next().unwrap(), iter.next().unwrap())
}
// split into two at a delimiter
pub fn split(txt: &str, delim: char) -> (&str,&str) {
if let Some(idx) = txt.find(delim) {
(&txt[0..idx], &txt[idx+1..])
} else {
(txt,"")
}
} | random_line_split |
|
strutil.rs | // miscelaneous string utilities
// returns the string slice following the target, if any
pub fn after<'a>(s: &'a str, target: &str) -> Option<&'a str> {
if let Some(idx) = s.find(target) {
Some(&s[(idx+target.len())..])
} else {
None
}
}
// like after, but subsequently finds a word following...
pub fn word_after(txt: &str, target: &str) -> Option<String> {
if let Some(txt) = after(txt,target) {
// maybe skip some space, and end with whitespace or semicolon
let start = txt.find(|c:char| c.is_alphanumeric()).unwrap();
let end = txt.find(|c:char| c == ';' || c.is_whitespace()).unwrap();
Some((&txt[start..end]).to_string())
} else {
None
}
}
// next two items from an iterator, assuming that it has at least two items...
pub fn next_2<T, I: Iterator<Item=T>> (mut iter: I) -> (T,T) |
// split into two at a delimiter
pub fn split(txt: &str, delim: char) -> (&str,&str) {
if let Some(idx) = txt.find(delim) {
(&txt[0..idx], &txt[idx+1..])
} else {
(txt,"")
}
}
| {
(iter.next().unwrap(), iter.next().unwrap())
} | identifier_body |
strutil.rs | // miscelaneous string utilities
// returns the string slice following the target, if any
pub fn after<'a>(s: &'a str, target: &str) -> Option<&'a str> {
if let Some(idx) = s.find(target) {
Some(&s[(idx+target.len())..])
} else {
None
}
}
// like after, but subsequently finds a word following...
pub fn word_after(txt: &str, target: &str) -> Option<String> {
if let Some(txt) = after(txt,target) {
// maybe skip some space, and end with whitespace or semicolon
let start = txt.find(|c:char| c.is_alphanumeric()).unwrap();
let end = txt.find(|c:char| c == ';' || c.is_whitespace()).unwrap();
Some((&txt[start..end]).to_string())
} else {
None
}
}
// next two items from an iterator, assuming that it has at least two items...
pub fn next_2<T, I: Iterator<Item=T>> (mut iter: I) -> (T,T) {
(iter.next().unwrap(), iter.next().unwrap())
}
// split into two at a delimiter
pub fn | (txt: &str, delim: char) -> (&str,&str) {
if let Some(idx) = txt.find(delim) {
(&txt[0..idx], &txt[idx+1..])
} else {
(txt,"")
}
}
| split | identifier_name |
strutil.rs | // miscelaneous string utilities
// returns the string slice following the target, if any
pub fn after<'a>(s: &'a str, target: &str) -> Option<&'a str> {
if let Some(idx) = s.find(target) | else {
None
}
}
// like after, but subsequently finds a word following...
pub fn word_after(txt: &str, target: &str) -> Option<String> {
if let Some(txt) = after(txt,target) {
// maybe skip some space, and end with whitespace or semicolon
let start = txt.find(|c:char| c.is_alphanumeric()).unwrap();
let end = txt.find(|c:char| c == ';' || c.is_whitespace()).unwrap();
Some((&txt[start..end]).to_string())
} else {
None
}
}
// next two items from an iterator, assuming that it has at least two items...
pub fn next_2<T, I: Iterator<Item=T>> (mut iter: I) -> (T,T) {
(iter.next().unwrap(), iter.next().unwrap())
}
// split into two at a delimiter
pub fn split(txt: &str, delim: char) -> (&str,&str) {
if let Some(idx) = txt.find(delim) {
(&txt[0..idx], &txt[idx+1..])
} else {
(txt,"")
}
}
| {
Some(&s[(idx+target.len())..])
} | conditional_block |
searcher.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.
//! ncurses-compatible database discovery
//!
//! Does not support hashed database, only filesystem!
use std::io::File;
use std::io::fs::PathExtensions;
use std::os::getenv;
use std::os;
/// Return path to database entry for `term`
pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> | if i == "" {
dirs_to_search.push(Path::new("/usr/share/terminfo"));
} else {
dirs_to_search.push(Path::new(i));
}
},
// Found nothing in TERMINFO_DIRS, use the default paths:
// According to /etc/terminfo/README, after looking at
// ~/.terminfo, ncurses will search /etc/terminfo, then
// /lib/terminfo, and eventually /usr/share/terminfo.
None => {
dirs_to_search.push(Path::new("/etc/terminfo"));
dirs_to_search.push(Path::new("/lib/terminfo"));
dirs_to_search.push(Path::new("/usr/share/terminfo"));
}
}
}
};
// Look for the terminal in all of the search directories
for p in dirs_to_search.iter() {
if p.exists() {
let f = first_char.to_string();
let newp = p.join_many(&[&f[], term]);
if newp.exists() {
return Some(box newp);
}
// on some installations the dir is named after the hex of the char (e.g. OS X)
let f = format!("{:x}", first_char as uint);
let newp = p.join_many(&[&f[], term]);
if newp.exists() {
return Some(box newp);
}
}
}
None
}
/// Return open file for `term`
pub fn open(term: &str) -> Result<File, String> {
match get_dbpath_for_term(term) {
Some(x) => {
match File::open(&*x) {
Ok(file) => Ok(file),
Err(e) => Err(format!("error opening file: {:?}", e)),
}
}
None => {
Err(format!("could not find terminfo entry for {:?}", term))
}
}
}
#[test]
#[ignore(reason = "buildbots don't have ncurses installed and I can't mock everything I need")]
fn test_get_dbpath_for_term() {
// woefully inadequate test coverage
// note: current tests won't work with non-standard terminfo hierarchies (e.g. OS X's)
use std::os::{setenv, unsetenv};
// FIXME (#9639): This needs to handle non-utf8 paths
fn x(t: &str) -> String {
let p = get_dbpath_for_term(t).expect("no terminfo entry found");
p.as_str().unwrap().to_string()
};
assert!(x("screen") == "/usr/share/terminfo/s/screen");
assert!(get_dbpath_for_term("") == None);
setenv("TERMINFO_DIRS", ":");
assert!(x("screen") == "/usr/share/terminfo/s/screen");
unsetenv("TERMINFO_DIRS");
}
#[test]
#[ignore(reason = "see test_get_dbpath_for_term")]
fn test_open() {
open("screen").unwrap();
let t = open("nonexistent terminal that hopefully does not exist");
assert!(t.is_err());
}
| {
if term.len() == 0 {
return None;
}
let homedir = os::homedir();
let mut dirs_to_search = Vec::new();
let first_char = term.char_at(0);
// Find search directory
match getenv("TERMINFO") {
Some(dir) => dirs_to_search.push(Path::new(dir)),
None => {
if homedir.is_some() {
// ncurses compatibility;
dirs_to_search.push(homedir.unwrap().join(".terminfo"))
}
match getenv("TERMINFO_DIRS") {
Some(dirs) => for i in dirs.split(':') { | identifier_body |
searcher.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.
//! ncurses-compatible database discovery
//!
//! Does not support hashed database, only filesystem!
use std::io::File;
use std::io::fs::PathExtensions;
use std::os::getenv;
use std::os;
/// Return path to database entry for `term`
pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> {
if term.len() == 0 {
return None;
}
let homedir = os::homedir();
let mut dirs_to_search = Vec::new();
let first_char = term.char_at(0);
// Find search directory
match getenv("TERMINFO") {
Some(dir) => dirs_to_search.push(Path::new(dir)),
None => {
if homedir.is_some() {
// ncurses compatibility;
dirs_to_search.push(homedir.unwrap().join(".terminfo"))
}
match getenv("TERMINFO_DIRS") {
Some(dirs) => for i in dirs.split(':') {
if i == "" {
dirs_to_search.push(Path::new("/usr/share/terminfo"));
} else {
dirs_to_search.push(Path::new(i));
}
},
// Found nothing in TERMINFO_DIRS, use the default paths:
// According to /etc/terminfo/README, after looking at
// ~/.terminfo, ncurses will search /etc/terminfo, then
// /lib/terminfo, and eventually /usr/share/terminfo.
None => {
dirs_to_search.push(Path::new("/etc/terminfo"));
dirs_to_search.push(Path::new("/lib/terminfo"));
dirs_to_search.push(Path::new("/usr/share/terminfo"));
}
}
}
};
// Look for the terminal in all of the search directories
for p in dirs_to_search.iter() {
if p.exists() {
let f = first_char.to_string();
let newp = p.join_many(&[&f[], term]);
if newp.exists() {
return Some(box newp);
}
// on some installations the dir is named after the hex of the char (e.g. OS X)
let f = format!("{:x}", first_char as uint);
let newp = p.join_many(&[&f[], term]);
if newp.exists() {
return Some(box newp);
}
}
}
None
}
/// Return open file for `term`
pub fn | (term: &str) -> Result<File, String> {
match get_dbpath_for_term(term) {
Some(x) => {
match File::open(&*x) {
Ok(file) => Ok(file),
Err(e) => Err(format!("error opening file: {:?}", e)),
}
}
None => {
Err(format!("could not find terminfo entry for {:?}", term))
}
}
}
#[test]
#[ignore(reason = "buildbots don't have ncurses installed and I can't mock everything I need")]
fn test_get_dbpath_for_term() {
// woefully inadequate test coverage
// note: current tests won't work with non-standard terminfo hierarchies (e.g. OS X's)
use std::os::{setenv, unsetenv};
// FIXME (#9639): This needs to handle non-utf8 paths
fn x(t: &str) -> String {
let p = get_dbpath_for_term(t).expect("no terminfo entry found");
p.as_str().unwrap().to_string()
};
assert!(x("screen") == "/usr/share/terminfo/s/screen");
assert!(get_dbpath_for_term("") == None);
setenv("TERMINFO_DIRS", ":");
assert!(x("screen") == "/usr/share/terminfo/s/screen");
unsetenv("TERMINFO_DIRS");
}
#[test]
#[ignore(reason = "see test_get_dbpath_for_term")]
fn test_open() {
open("screen").unwrap();
let t = open("nonexistent terminal that hopefully does not exist");
assert!(t.is_err());
}
| open | identifier_name |
searcher.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.
//! ncurses-compatible database discovery
//!
//! Does not support hashed database, only filesystem!
use std::io::File;
use std::io::fs::PathExtensions;
use std::os::getenv;
use std::os;
/// Return path to database entry for `term`
pub fn get_dbpath_for_term(term: &str) -> Option<Box<Path>> {
if term.len() == 0 {
return None;
}
let homedir = os::homedir();
let mut dirs_to_search = Vec::new();
let first_char = term.char_at(0);
// Find search directory
match getenv("TERMINFO") {
Some(dir) => dirs_to_search.push(Path::new(dir)),
None => {
if homedir.is_some() {
// ncurses compatibility;
dirs_to_search.push(homedir.unwrap().join(".terminfo"))
}
match getenv("TERMINFO_DIRS") {
Some(dirs) => for i in dirs.split(':') {
if i == "" {
dirs_to_search.push(Path::new("/usr/share/terminfo"));
} else {
dirs_to_search.push(Path::new(i));
}
},
// Found nothing in TERMINFO_DIRS, use the default paths:
// According to /etc/terminfo/README, after looking at
// ~/.terminfo, ncurses will search /etc/terminfo, then
// /lib/terminfo, and eventually /usr/share/terminfo.
None => {
dirs_to_search.push(Path::new("/etc/terminfo"));
dirs_to_search.push(Path::new("/lib/terminfo"));
dirs_to_search.push(Path::new("/usr/share/terminfo"));
}
}
}
};
// Look for the terminal in all of the search directories
for p in dirs_to_search.iter() {
if p.exists() {
let f = first_char.to_string();
let newp = p.join_many(&[&f[], term]);
if newp.exists() {
return Some(box newp);
}
// on some installations the dir is named after the hex of the char (e.g. OS X)
let f = format!("{:x}", first_char as uint);
let newp = p.join_many(&[&f[], term]);
if newp.exists() {
return Some(box newp);
}
}
}
None
}
/// Return open file for `term`
pub fn open(term: &str) -> Result<File, String> {
match get_dbpath_for_term(term) {
Some(x) => {
match File::open(&*x) {
Ok(file) => Ok(file),
Err(e) => Err(format!("error opening file: {:?}", e)),
}
}
None => {
Err(format!("could not find terminfo entry for {:?}", term))
}
}
}
#[test]
#[ignore(reason = "buildbots don't have ncurses installed and I can't mock everything I need")]
fn test_get_dbpath_for_term() {
// woefully inadequate test coverage
// note: current tests won't work with non-standard terminfo hierarchies (e.g. OS X's)
use std::os::{setenv, unsetenv};
// FIXME (#9639): This needs to handle non-utf8 paths
fn x(t: &str) -> String {
let p = get_dbpath_for_term(t).expect("no terminfo entry found");
p.as_str().unwrap().to_string()
};
assert!(x("screen") == "/usr/share/terminfo/s/screen");
assert!(get_dbpath_for_term("") == None);
setenv("TERMINFO_DIRS", ":");
assert!(x("screen") == "/usr/share/terminfo/s/screen");
unsetenv("TERMINFO_DIRS"); |
#[test]
#[ignore(reason = "see test_get_dbpath_for_term")]
fn test_open() {
open("screen").unwrap();
let t = open("nonexistent terminal that hopefully does not exist");
assert!(t.is_err());
} | } | random_line_split |
deriving-meta.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::hash::{Hash, SipHasher};
#[derive(PartialEq, Clone, Hash)]
struct Foo {
bar: uint,
baz: int
}
fn hash<T: Hash>(_t: &T) {}
pub fn main() {
let a = Foo {bar: 4, baz: -3};
| } | a == a; // check for PartialEq impl w/o testing its correctness
a.clone(); // check for Clone impl w/o testing its correctness
hash(&a); // check for Hash impl w/o testing its correctness | random_line_split |
deriving-meta.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::hash::{Hash, SipHasher};
#[derive(PartialEq, Clone, Hash)]
struct Foo {
bar: uint,
baz: int
}
fn hash<T: Hash>(_t: &T) |
pub fn main() {
let a = Foo {bar: 4, baz: -3};
a == a; // check for PartialEq impl w/o testing its correctness
a.clone(); // check for Clone impl w/o testing its correctness
hash(&a); // check for Hash impl w/o testing its correctness
}
| {} | identifier_body |
deriving-meta.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use std::hash::{Hash, SipHasher};
#[derive(PartialEq, Clone, Hash)]
struct Foo {
bar: uint,
baz: int
}
fn | <T: Hash>(_t: &T) {}
pub fn main() {
let a = Foo {bar: 4, baz: -3};
a == a; // check for PartialEq impl w/o testing its correctness
a.clone(); // check for Clone impl w/o testing its correctness
hash(&a); // check for Hash impl w/o testing its correctness
}
| hash | identifier_name |
constantsourcenode.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::audioparam::AudioParam;
use crate::dom::audioscheduledsourcenode::AudioScheduledSourceNode;
use crate::dom::baseaudiocontext::BaseAudioContext;
use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate;
use crate::dom::bindings::codegen::Bindings::ConstantSourceNodeBinding::ConstantSourceNodeMethods;
use crate::dom::bindings::codegen::Bindings::ConstantSourceNodeBinding::{
self, ConstantSourceOptions,
};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_media::audio::constant_source_node::ConstantSourceNodeOptions as ServoMediaConstantSourceOptions;
use servo_media::audio::node::AudioNodeInit;
use servo_media::audio::param::ParamType;
use std::f32;
#[dom_struct]
pub struct ConstantSourceNode {
source_node: AudioScheduledSourceNode,
offset: Dom<AudioParam>,
}
impl ConstantSourceNode {
#[allow(unrooted_must_root)]
fn new_inherited(
window: &Window,
context: &BaseAudioContext,
options: &ConstantSourceOptions,
) -> Fallible<ConstantSourceNode> {
let node_options = Default::default();
let source_node = AudioScheduledSourceNode::new_inherited(
AudioNodeInit::ConstantSourceNode(options.into()),
context,
node_options, /* 2, MAX, Speakers */
0, /* inputs */
1, /* outputs */
)?;
let node_id = source_node.node().node_id();
let offset = AudioParam::new(
window,
context,
node_id,
ParamType::Offset,
AutomationRate::A_rate,
*options.offset,
f32::MIN,
f32::MAX,
);
Ok(ConstantSourceNode {
source_node,
offset: Dom::from_ref(&offset),
}) |
#[allow(unrooted_must_root)]
pub fn new(
window: &Window,
context: &BaseAudioContext,
options: &ConstantSourceOptions,
) -> Fallible<DomRoot<ConstantSourceNode>> {
let node = ConstantSourceNode::new_inherited(window, context, options)?;
Ok(reflect_dom_object(
Box::new(node),
window,
ConstantSourceNodeBinding::Wrap,
))
}
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
context: &BaseAudioContext,
options: &ConstantSourceOptions,
) -> Fallible<DomRoot<ConstantSourceNode>> {
ConstantSourceNode::new(window, context, options)
}
}
impl ConstantSourceNodeMethods for ConstantSourceNode {
// https://webaudio.github.io/web-audio-api/#dom-constantsourcenode-offset
fn Offset(&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.offset)
}
}
impl<'a> From<&'a ConstantSourceOptions> for ServoMediaConstantSourceOptions {
fn from(options: &'a ConstantSourceOptions) -> Self {
Self {
offset: *options.offset,
}
}
} | } | random_line_split |
constantsourcenode.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::audioparam::AudioParam;
use crate::dom::audioscheduledsourcenode::AudioScheduledSourceNode;
use crate::dom::baseaudiocontext::BaseAudioContext;
use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate;
use crate::dom::bindings::codegen::Bindings::ConstantSourceNodeBinding::ConstantSourceNodeMethods;
use crate::dom::bindings::codegen::Bindings::ConstantSourceNodeBinding::{
self, ConstantSourceOptions,
};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_media::audio::constant_source_node::ConstantSourceNodeOptions as ServoMediaConstantSourceOptions;
use servo_media::audio::node::AudioNodeInit;
use servo_media::audio::param::ParamType;
use std::f32;
#[dom_struct]
pub struct ConstantSourceNode {
source_node: AudioScheduledSourceNode,
offset: Dom<AudioParam>,
}
impl ConstantSourceNode {
#[allow(unrooted_must_root)]
fn new_inherited(
window: &Window,
context: &BaseAudioContext,
options: &ConstantSourceOptions,
) -> Fallible<ConstantSourceNode> {
let node_options = Default::default();
let source_node = AudioScheduledSourceNode::new_inherited(
AudioNodeInit::ConstantSourceNode(options.into()),
context,
node_options, /* 2, MAX, Speakers */
0, /* inputs */
1, /* outputs */
)?;
let node_id = source_node.node().node_id();
let offset = AudioParam::new(
window,
context,
node_id,
ParamType::Offset,
AutomationRate::A_rate,
*options.offset,
f32::MIN,
f32::MAX,
);
Ok(ConstantSourceNode {
source_node,
offset: Dom::from_ref(&offset),
})
}
#[allow(unrooted_must_root)]
pub fn new(
window: &Window,
context: &BaseAudioContext,
options: &ConstantSourceOptions,
) -> Fallible<DomRoot<ConstantSourceNode>> {
let node = ConstantSourceNode::new_inherited(window, context, options)?;
Ok(reflect_dom_object(
Box::new(node),
window,
ConstantSourceNodeBinding::Wrap,
))
}
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
context: &BaseAudioContext,
options: &ConstantSourceOptions,
) -> Fallible<DomRoot<ConstantSourceNode>> {
ConstantSourceNode::new(window, context, options)
}
}
impl ConstantSourceNodeMethods for ConstantSourceNode {
// https://webaudio.github.io/web-audio-api/#dom-constantsourcenode-offset
fn | (&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.offset)
}
}
impl<'a> From<&'a ConstantSourceOptions> for ServoMediaConstantSourceOptions {
fn from(options: &'a ConstantSourceOptions) -> Self {
Self {
offset: *options.offset,
}
}
}
| Offset | identifier_name |
try_init.rs | use { serde_json, string };
use dispatch::{ add_node, connect_nodes, get };
use error::*;
use action::{ AddNode, ConnectNodes };
use libflo_action_std::{ ACTION_MAPPER, BasicAction, dispatch_fn, DispatchMap, DISPATCH_MAP, parse_fn, ParseMap, PARSE_MAP };
use libflo_std::LIBFLO;
pub unsafe fn | () -> Result<()> {
if ACTION_MAPPER.is_set()? && LIBFLO.is_set()? {
let action_mapper = ACTION_MAPPER.read()?;
let libflo = LIBFLO.read()?;
let module_mapper = libflo.get_module_mapper();
// Set up parser
let add_node_parser = parse_fn(|arg| serde_json::from_str::<AddNode>(arg));
let connect_nodes_parser = parse_fn(|arg| serde_json::from_str::<ConnectNodes>(arg));
let get_parser = parse_fn(|arg| serde_json::from_str::<BasicAction>(arg));
let parser = ParseMap::new(
module_mapper,
&action_mapper,
vec![
(string::module(), string::add_node_action(), add_node_parser),
(string::module(), string::connect_nodes_action(), connect_nodes_parser),
(string::module(), string::get_action(), get_parser),
]
)?;
PARSE_MAP.set(parser)?;
// Set up dispatch map
let add_node_dispatch = dispatch_fn(|arg| add_node(arg));
let connect_nodes_dispatch = dispatch_fn(|arg| connect_nodes(arg));
let get_dispatch = dispatch_fn(|_: &BasicAction| get());
let dispatch_map = DispatchMap::new(
module_mapper,
&action_mapper,
vec![
(string::module(), string::add_node_action(), add_node_dispatch),
(string::module(), string::connect_nodes_action(), connect_nodes_dispatch),
(string::module(), string::get_action(), get_dispatch),
]
)?;
DISPATCH_MAP.set(dispatch_map)?;
}
Ok(())
}
| try_init | identifier_name |
try_init.rs | use { serde_json, string };
use dispatch::{ add_node, connect_nodes, get };
use error::*;
use action::{ AddNode, ConnectNodes };
use libflo_action_std::{ ACTION_MAPPER, BasicAction, dispatch_fn, DispatchMap, DISPATCH_MAP, parse_fn, ParseMap, PARSE_MAP };
use libflo_std::LIBFLO;
|
// Set up parser
let add_node_parser = parse_fn(|arg| serde_json::from_str::<AddNode>(arg));
let connect_nodes_parser = parse_fn(|arg| serde_json::from_str::<ConnectNodes>(arg));
let get_parser = parse_fn(|arg| serde_json::from_str::<BasicAction>(arg));
let parser = ParseMap::new(
module_mapper,
&action_mapper,
vec![
(string::module(), string::add_node_action(), add_node_parser),
(string::module(), string::connect_nodes_action(), connect_nodes_parser),
(string::module(), string::get_action(), get_parser),
]
)?;
PARSE_MAP.set(parser)?;
// Set up dispatch map
let add_node_dispatch = dispatch_fn(|arg| add_node(arg));
let connect_nodes_dispatch = dispatch_fn(|arg| connect_nodes(arg));
let get_dispatch = dispatch_fn(|_: &BasicAction| get());
let dispatch_map = DispatchMap::new(
module_mapper,
&action_mapper,
vec![
(string::module(), string::add_node_action(), add_node_dispatch),
(string::module(), string::connect_nodes_action(), connect_nodes_dispatch),
(string::module(), string::get_action(), get_dispatch),
]
)?;
DISPATCH_MAP.set(dispatch_map)?;
}
Ok(())
} | pub unsafe fn try_init() -> Result<()> {
if ACTION_MAPPER.is_set()? && LIBFLO.is_set()? {
let action_mapper = ACTION_MAPPER.read()?;
let libflo = LIBFLO.read()?;
let module_mapper = libflo.get_module_mapper(); | random_line_split |
try_init.rs | use { serde_json, string };
use dispatch::{ add_node, connect_nodes, get };
use error::*;
use action::{ AddNode, ConnectNodes };
use libflo_action_std::{ ACTION_MAPPER, BasicAction, dispatch_fn, DispatchMap, DISPATCH_MAP, parse_fn, ParseMap, PARSE_MAP };
use libflo_std::LIBFLO;
pub unsafe fn try_init() -> Result<()> {
if ACTION_MAPPER.is_set()? && LIBFLO.is_set()? | PARSE_MAP.set(parser)?;
// Set up dispatch map
let add_node_dispatch = dispatch_fn(|arg| add_node(arg));
let connect_nodes_dispatch = dispatch_fn(|arg| connect_nodes(arg));
let get_dispatch = dispatch_fn(|_: &BasicAction| get());
let dispatch_map = DispatchMap::new(
module_mapper,
&action_mapper,
vec![
(string::module(), string::add_node_action(), add_node_dispatch),
(string::module(), string::connect_nodes_action(), connect_nodes_dispatch),
(string::module(), string::get_action(), get_dispatch),
]
)?;
DISPATCH_MAP.set(dispatch_map)?;
}
Ok(())
}
| {
let action_mapper = ACTION_MAPPER.read()?;
let libflo = LIBFLO.read()?;
let module_mapper = libflo.get_module_mapper();
// Set up parser
let add_node_parser = parse_fn(|arg| serde_json::from_str::<AddNode>(arg));
let connect_nodes_parser = parse_fn(|arg| serde_json::from_str::<ConnectNodes>(arg));
let get_parser = parse_fn(|arg| serde_json::from_str::<BasicAction>(arg));
let parser = ParseMap::new(
module_mapper,
&action_mapper,
vec![
(string::module(), string::add_node_action(), add_node_parser),
(string::module(), string::connect_nodes_action(), connect_nodes_parser),
(string::module(), string::get_action(), get_parser),
]
)?;
| conditional_block |
try_init.rs | use { serde_json, string };
use dispatch::{ add_node, connect_nodes, get };
use error::*;
use action::{ AddNode, ConnectNodes };
use libflo_action_std::{ ACTION_MAPPER, BasicAction, dispatch_fn, DispatchMap, DISPATCH_MAP, parse_fn, ParseMap, PARSE_MAP };
use libflo_std::LIBFLO;
pub unsafe fn try_init() -> Result<()> |
PARSE_MAP.set(parser)?;
// Set up dispatch map
let add_node_dispatch = dispatch_fn(|arg| add_node(arg));
let connect_nodes_dispatch = dispatch_fn(|arg| connect_nodes(arg));
let get_dispatch = dispatch_fn(|_: &BasicAction| get());
let dispatch_map = DispatchMap::new(
module_mapper,
&action_mapper,
vec![
(string::module(), string::add_node_action(), add_node_dispatch),
(string::module(), string::connect_nodes_action(), connect_nodes_dispatch),
(string::module(), string::get_action(), get_dispatch),
]
)?;
DISPATCH_MAP.set(dispatch_map)?;
}
Ok(())
}
| {
if ACTION_MAPPER.is_set()? && LIBFLO.is_set()? {
let action_mapper = ACTION_MAPPER.read()?;
let libflo = LIBFLO.read()?;
let module_mapper = libflo.get_module_mapper();
// Set up parser
let add_node_parser = parse_fn(|arg| serde_json::from_str::<AddNode>(arg));
let connect_nodes_parser = parse_fn(|arg| serde_json::from_str::<ConnectNodes>(arg));
let get_parser = parse_fn(|arg| serde_json::from_str::<BasicAction>(arg));
let parser = ParseMap::new(
module_mapper,
&action_mapper,
vec![
(string::module(), string::add_node_action(), add_node_parser),
(string::module(), string::connect_nodes_action(), connect_nodes_parser),
(string::module(), string::get_action(), get_parser),
]
)?; | identifier_body |
plain.rs | use text::style::{Style, StyleCommand, Color, PaletteColor};
use std::fmt::{self, Display};
use std::str::FromStr;
use serde::de::{Deserializer, Deserialize, Error, Visitor};
use serde::{Serializer, Serialize};
use std::iter::Peekable;
use std::slice;
// [PlainBuf] Overhead: 48 bytes for collections, 4 bytes per descriptor, random access
// [Encoded] Overhead: 24 bytes for collections, 2 to 12 bytes per descriptor
/// A buffer storing an unstyled string annotated with styles in a descriptor buffer.
#[derive(Debug)]
pub struct PlainBuf {
/// The unstyled string
string: String,
/// The descriptors holding the styles.
descriptors: Vec<(u8, Style)>
}
impl PlainBuf {
/// Creates a new, empty PlainBuf.
pub fn new() -> Self {
PlainBuf {
string: String::new(),
descriptors: Vec::new()
}
}
/// Creates a new PlainBuf where each buffer has a certain capacity.
pub fn with_capacity(string: usize, descriptors: usize) -> Self {
PlainBuf {
string: String::with_capacity(string),
descriptors: Vec::with_capacity(descriptors)
}
}
pub fn capacity(&self) -> (usize, usize) {
(self.string.capacity(), self.descriptors.capacity())
}
pub fn reserve(&mut self, string: usize, descriptors: usize) {
self.string.reserve(string);
self.descriptors.reserve(string);
}
pub fn reserve_exact(&mut self, string: usize, descriptors: usize) {
self.string.reserve_exact(string);
self.descriptors.reserve_exact(string);
}
pub fn shrink_to_fit(&mut self) {
self.string.shrink_to_fit();
self.descriptors.shrink_to_fit();
}
pub fn push(&mut self, string: &str, style: Style) {
self.string.push_str(string);
self.break_descriptor(string.len(), style);
}
fn break_descriptor(&mut self, len: usize, style: Style) {
let total_len = self.string.len();
let mut string = &self.string[total_len - len..];
while string.len() > 0 {
let mut chunk_len = u8::max_value();
while!string.is_char_boundary(chunk_len as usize) {
chunk_len -= 1;
}
self.descriptors.push((chunk_len, style));
string = &string[chunk_len as usize..];
}
}
pub fn unstyled(&self) -> &str {
&self.string
}
pub fn iter(&self) -> Iter {
Iter {
head: &self.string,
descriptors: self.descriptors.iter().peekable()
}
}
// TODO: Pop, Truncate
}
impl FromStr for PlainBuf {
type Err = ();
fn from_str(s: &str) -> Result<Self, ()> {
let mut reader = FormatReader::new();
reader.append(s);
Ok(reader.finish())
}
}
impl Display for PlainBuf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut writer = FormatWriter::new(f);
let mut head = &self.string as &str;
let mut offset = 0;
for &(len, style) in &self.descriptors {
let (part, rest) = head.split_at(len as usize);
head = rest;
writer.write(part, style)?;
}
Ok(())
}
}
pub struct Iter<'a, 'b> {
head: &'a str,
descriptors: Peekable<slice::Iter<'b, (u8, Style)>>
}
impl<'a, 'b> Iter<'a, 'b> {
pub fn empty() -> Self {
Iter {
head: "",
descriptors: [].iter().peekable()
}
}
}
impl<'a, 'b> Iterator for Iter<'a, 'b> {
type Item = (&'a str, Style);
fn next(&mut self) -> Option<Self::Item> {
if let Some(&(len, style)) = self.descriptors.next() {
let mut len = len as usize;
// Try to merge descriptors of the same style together.
while let Some(&&(next_len, next_style)) = self.descriptors.peek() {
if next_style!= style {
break;
} | }
let (part, rest) = self.head.split_at(len);
self.head = rest;
Some((part, style))
} else {
None
}
}
}
pub struct FormatReader {
target: PlainBuf,
marker: char,
expect_code: bool,
style: Style,
current_len: usize
}
impl FormatReader {
pub fn new() -> Self {
Self::with_marker('§')
}
pub fn with_marker(marker: char) -> Self {
FormatReader {
target: PlainBuf::new(),
marker: marker,
expect_code: false,
style: Style::new(),
current_len: 0
}
}
pub fn extend(target: PlainBuf, marker: char) -> Self {
FormatReader {
target: target,
marker: marker,
expect_code: false,
style: Style::new(),
current_len: 0
}
}
fn flush(&mut self) {
if self.current_len!= 0 {
self.target.break_descriptor(self.current_len, self.style);
self.current_len = 0;
}
}
pub fn append(&mut self, string: &str) {
let mut start = 0;
for (index, char) in string.char_indices() {
if self.expect_code {
self.target.string.push_str(&string[start..start+self.current_len]);
self.flush();
self.style.process(&StyleCommand::from_code(char).unwrap_or(StyleCommand::Color(PaletteColor::White)));
self.expect_code = false;
} else if char == self.marker {
self.expect_code = true;
} else {
if self.current_len == 0 {
start = index;
}
self.current_len += utf8_len(char);
}
}
self.target.string.push_str(&string[start..start+self.current_len]);
}
pub fn finish(mut self) -> PlainBuf {
self.flush();
self.target
}
}
// TODO: Does the stdlib have a function like this?
fn utf8_len(c: char) -> usize {
let c = c as u32;
if c <= 0x7F {
1
} else if c <= 0x7FF {
2
} else if c <= 0xFFFF {
3
} else {
4
}
}
pub struct FormatWriter<'w, W> where W: fmt::Write, W: 'w {
target: &'w mut W,
current_style: Style,
marker: char
}
impl<'w, W> FormatWriter<'w, W> where W: fmt::Write {
pub fn new(target: &'w mut W) -> Self {
FormatWriter { target, current_style: Style::new(), marker: '§' }
}
pub fn with_marker(target: &'w mut W, marker: char) -> Self {
FormatWriter { target, current_style: Style::new(), marker }
}
pub fn write(&mut self, string: &str, style: Style) -> fmt::Result {
for command in self.current_style.transition(style) {
self.target.write_char(self.marker)?;
self.target.write_char(command.as_code())?;
}
self.current_style = style;
self.target.write_str(string)
}
}
impl<'de> Deserialize<'de> for PlainBuf {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
struct PlainVisitor;
impl<'de> Visitor<'de> for PlainVisitor {
type Value = PlainBuf;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string containing Minecraft formatting codes")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error {
Ok(v.parse::<PlainBuf>().expect("Parsing a PlainBuf should never return an error!"))
}
}
deserializer.deserialize_str(PlainVisitor)
}
}
impl Serialize for PlainBuf {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(&self.to_string())
}
} |
len += next_len as usize;
self.descriptors.next(); | random_line_split |
plain.rs | use text::style::{Style, StyleCommand, Color, PaletteColor};
use std::fmt::{self, Display};
use std::str::FromStr;
use serde::de::{Deserializer, Deserialize, Error, Visitor};
use serde::{Serializer, Serialize};
use std::iter::Peekable;
use std::slice;
// [PlainBuf] Overhead: 48 bytes for collections, 4 bytes per descriptor, random access
// [Encoded] Overhead: 24 bytes for collections, 2 to 12 bytes per descriptor
/// A buffer storing an unstyled string annotated with styles in a descriptor buffer.
#[derive(Debug)]
pub struct PlainBuf {
/// The unstyled string
string: String,
/// The descriptors holding the styles.
descriptors: Vec<(u8, Style)>
}
impl PlainBuf {
/// Creates a new, empty PlainBuf.
pub fn new() -> Self {
PlainBuf {
string: String::new(),
descriptors: Vec::new()
}
}
/// Creates a new PlainBuf where each buffer has a certain capacity.
pub fn with_capacity(string: usize, descriptors: usize) -> Self {
PlainBuf {
string: String::with_capacity(string),
descriptors: Vec::with_capacity(descriptors)
}
}
pub fn capacity(&self) -> (usize, usize) {
(self.string.capacity(), self.descriptors.capacity())
}
pub fn reserve(&mut self, string: usize, descriptors: usize) {
self.string.reserve(string);
self.descriptors.reserve(string);
}
pub fn reserve_exact(&mut self, string: usize, descriptors: usize) {
self.string.reserve_exact(string);
self.descriptors.reserve_exact(string);
}
pub fn shrink_to_fit(&mut self) {
self.string.shrink_to_fit();
self.descriptors.shrink_to_fit();
}
pub fn push(&mut self, string: &str, style: Style) {
self.string.push_str(string);
self.break_descriptor(string.len(), style);
}
fn break_descriptor(&mut self, len: usize, style: Style) {
let total_len = self.string.len();
let mut string = &self.string[total_len - len..];
while string.len() > 0 {
let mut chunk_len = u8::max_value();
while!string.is_char_boundary(chunk_len as usize) {
chunk_len -= 1;
}
self.descriptors.push((chunk_len, style));
string = &string[chunk_len as usize..];
}
}
pub fn unstyled(&self) -> &str {
&self.string
}
pub fn iter(&self) -> Iter {
Iter {
head: &self.string,
descriptors: self.descriptors.iter().peekable()
}
}
// TODO: Pop, Truncate
}
impl FromStr for PlainBuf {
type Err = ();
fn from_str(s: &str) -> Result<Self, ()> {
let mut reader = FormatReader::new();
reader.append(s);
Ok(reader.finish())
}
}
impl Display for PlainBuf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut writer = FormatWriter::new(f);
let mut head = &self.string as &str;
let mut offset = 0;
for &(len, style) in &self.descriptors {
let (part, rest) = head.split_at(len as usize);
head = rest;
writer.write(part, style)?;
}
Ok(())
}
}
pub struct Iter<'a, 'b> {
head: &'a str,
descriptors: Peekable<slice::Iter<'b, (u8, Style)>>
}
impl<'a, 'b> Iter<'a, 'b> {
pub fn empty() -> Self {
Iter {
head: "",
descriptors: [].iter().peekable()
}
}
}
impl<'a, 'b> Iterator for Iter<'a, 'b> {
type Item = (&'a str, Style);
fn next(&mut self) -> Option<Self::Item> {
if let Some(&(len, style)) = self.descriptors.next() {
let mut len = len as usize;
// Try to merge descriptors of the same style together.
while let Some(&&(next_len, next_style)) = self.descriptors.peek() {
if next_style!= style {
break;
}
len += next_len as usize;
self.descriptors.next();
}
let (part, rest) = self.head.split_at(len);
self.head = rest;
Some((part, style))
} else {
None
}
}
}
pub struct FormatReader {
target: PlainBuf,
marker: char,
expect_code: bool,
style: Style,
current_len: usize
}
impl FormatReader {
pub fn new() -> Self |
pub fn with_marker(marker: char) -> Self {
FormatReader {
target: PlainBuf::new(),
marker: marker,
expect_code: false,
style: Style::new(),
current_len: 0
}
}
pub fn extend(target: PlainBuf, marker: char) -> Self {
FormatReader {
target: target,
marker: marker,
expect_code: false,
style: Style::new(),
current_len: 0
}
}
fn flush(&mut self) {
if self.current_len!= 0 {
self.target.break_descriptor(self.current_len, self.style);
self.current_len = 0;
}
}
pub fn append(&mut self, string: &str) {
let mut start = 0;
for (index, char) in string.char_indices() {
if self.expect_code {
self.target.string.push_str(&string[start..start+self.current_len]);
self.flush();
self.style.process(&StyleCommand::from_code(char).unwrap_or(StyleCommand::Color(PaletteColor::White)));
self.expect_code = false;
} else if char == self.marker {
self.expect_code = true;
} else {
if self.current_len == 0 {
start = index;
}
self.current_len += utf8_len(char);
}
}
self.target.string.push_str(&string[start..start+self.current_len]);
}
pub fn finish(mut self) -> PlainBuf {
self.flush();
self.target
}
}
// TODO: Does the stdlib have a function like this?
fn utf8_len(c: char) -> usize {
let c = c as u32;
if c <= 0x7F {
1
} else if c <= 0x7FF {
2
} else if c <= 0xFFFF {
3
} else {
4
}
}
pub struct FormatWriter<'w, W> where W: fmt::Write, W: 'w {
target: &'w mut W,
current_style: Style,
marker: char
}
impl<'w, W> FormatWriter<'w, W> where W: fmt::Write {
pub fn new(target: &'w mut W) -> Self {
FormatWriter { target, current_style: Style::new(), marker: '§' }
}
pub fn with_marker(target: &'w mut W, marker: char) -> Self {
FormatWriter { target, current_style: Style::new(), marker }
}
pub fn write(&mut self, string: &str, style: Style) -> fmt::Result {
for command in self.current_style.transition(style) {
self.target.write_char(self.marker)?;
self.target.write_char(command.as_code())?;
}
self.current_style = style;
self.target.write_str(string)
}
}
impl<'de> Deserialize<'de> for PlainBuf {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
struct PlainVisitor;
impl<'de> Visitor<'de> for PlainVisitor {
type Value = PlainBuf;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string containing Minecraft formatting codes")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error {
Ok(v.parse::<PlainBuf>().expect("Parsing a PlainBuf should never return an error!"))
}
}
deserializer.deserialize_str(PlainVisitor)
}
}
impl Serialize for PlainBuf {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(&self.to_string())
}
} | {
Self::with_marker('§')
}
| identifier_body |
plain.rs | use text::style::{Style, StyleCommand, Color, PaletteColor};
use std::fmt::{self, Display};
use std::str::FromStr;
use serde::de::{Deserializer, Deserialize, Error, Visitor};
use serde::{Serializer, Serialize};
use std::iter::Peekable;
use std::slice;
// [PlainBuf] Overhead: 48 bytes for collections, 4 bytes per descriptor, random access
// [Encoded] Overhead: 24 bytes for collections, 2 to 12 bytes per descriptor
/// A buffer storing an unstyled string annotated with styles in a descriptor buffer.
#[derive(Debug)]
pub struct PlainBuf {
/// The unstyled string
string: String,
/// The descriptors holding the styles.
descriptors: Vec<(u8, Style)>
}
impl PlainBuf {
/// Creates a new, empty PlainBuf.
pub fn new() -> Self {
PlainBuf {
string: String::new(),
descriptors: Vec::new()
}
}
/// Creates a new PlainBuf where each buffer has a certain capacity.
pub fn with_capacity(string: usize, descriptors: usize) -> Self {
PlainBuf {
string: String::with_capacity(string),
descriptors: Vec::with_capacity(descriptors)
}
}
pub fn capacity(&self) -> (usize, usize) {
(self.string.capacity(), self.descriptors.capacity())
}
pub fn reserve(&mut self, string: usize, descriptors: usize) {
self.string.reserve(string);
self.descriptors.reserve(string);
}
pub fn reserve_exact(&mut self, string: usize, descriptors: usize) {
self.string.reserve_exact(string);
self.descriptors.reserve_exact(string);
}
pub fn shrink_to_fit(&mut self) {
self.string.shrink_to_fit();
self.descriptors.shrink_to_fit();
}
pub fn push(&mut self, string: &str, style: Style) {
self.string.push_str(string);
self.break_descriptor(string.len(), style);
}
fn break_descriptor(&mut self, len: usize, style: Style) {
let total_len = self.string.len();
let mut string = &self.string[total_len - len..];
while string.len() > 0 {
let mut chunk_len = u8::max_value();
while!string.is_char_boundary(chunk_len as usize) {
chunk_len -= 1;
}
self.descriptors.push((chunk_len, style));
string = &string[chunk_len as usize..];
}
}
pub fn unstyled(&self) -> &str {
&self.string
}
pub fn iter(&self) -> Iter {
Iter {
head: &self.string,
descriptors: self.descriptors.iter().peekable()
}
}
// TODO: Pop, Truncate
}
impl FromStr for PlainBuf {
type Err = ();
fn from_str(s: &str) -> Result<Self, ()> {
let mut reader = FormatReader::new();
reader.append(s);
Ok(reader.finish())
}
}
impl Display for PlainBuf {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut writer = FormatWriter::new(f);
let mut head = &self.string as &str;
let mut offset = 0;
for &(len, style) in &self.descriptors {
let (part, rest) = head.split_at(len as usize);
head = rest;
writer.write(part, style)?;
}
Ok(())
}
}
pub struct Iter<'a, 'b> {
head: &'a str,
descriptors: Peekable<slice::Iter<'b, (u8, Style)>>
}
impl<'a, 'b> Iter<'a, 'b> {
pub fn empty() -> Self {
Iter {
head: "",
descriptors: [].iter().peekable()
}
}
}
impl<'a, 'b> Iterator for Iter<'a, 'b> {
type Item = (&'a str, Style);
fn next(&mut self) -> Option<Self::Item> {
if let Some(&(len, style)) = self.descriptors.next() {
let mut len = len as usize;
// Try to merge descriptors of the same style together.
while let Some(&&(next_len, next_style)) = self.descriptors.peek() {
if next_style!= style {
break;
}
len += next_len as usize;
self.descriptors.next();
}
let (part, rest) = self.head.split_at(len);
self.head = rest;
Some((part, style))
} else {
None
}
}
}
pub struct FormatReader {
target: PlainBuf,
marker: char,
expect_code: bool,
style: Style,
current_len: usize
}
impl FormatReader {
pub fn new() -> Self {
Self::with_marker('§')
}
pub fn with_marker(marker: char) -> Self {
FormatReader {
target: PlainBuf::new(),
marker: marker,
expect_code: false,
style: Style::new(),
current_len: 0
}
}
pub fn extend(target: PlainBuf, marker: char) -> Self {
FormatReader {
target: target,
marker: marker,
expect_code: false,
style: Style::new(),
current_len: 0
}
}
fn flush(&mut self) {
if self.current_len!= 0 {
self.target.break_descriptor(self.current_len, self.style);
self.current_len = 0;
}
}
pub fn a | &mut self, string: &str) {
let mut start = 0;
for (index, char) in string.char_indices() {
if self.expect_code {
self.target.string.push_str(&string[start..start+self.current_len]);
self.flush();
self.style.process(&StyleCommand::from_code(char).unwrap_or(StyleCommand::Color(PaletteColor::White)));
self.expect_code = false;
} else if char == self.marker {
self.expect_code = true;
} else {
if self.current_len == 0 {
start = index;
}
self.current_len += utf8_len(char);
}
}
self.target.string.push_str(&string[start..start+self.current_len]);
}
pub fn finish(mut self) -> PlainBuf {
self.flush();
self.target
}
}
// TODO: Does the stdlib have a function like this?
fn utf8_len(c: char) -> usize {
let c = c as u32;
if c <= 0x7F {
1
} else if c <= 0x7FF {
2
} else if c <= 0xFFFF {
3
} else {
4
}
}
pub struct FormatWriter<'w, W> where W: fmt::Write, W: 'w {
target: &'w mut W,
current_style: Style,
marker: char
}
impl<'w, W> FormatWriter<'w, W> where W: fmt::Write {
pub fn new(target: &'w mut W) -> Self {
FormatWriter { target, current_style: Style::new(), marker: '§' }
}
pub fn with_marker(target: &'w mut W, marker: char) -> Self {
FormatWriter { target, current_style: Style::new(), marker }
}
pub fn write(&mut self, string: &str, style: Style) -> fmt::Result {
for command in self.current_style.transition(style) {
self.target.write_char(self.marker)?;
self.target.write_char(command.as_code())?;
}
self.current_style = style;
self.target.write_str(string)
}
}
impl<'de> Deserialize<'de> for PlainBuf {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
struct PlainVisitor;
impl<'de> Visitor<'de> for PlainVisitor {
type Value = PlainBuf;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a string containing Minecraft formatting codes")
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E> where E: Error {
Ok(v.parse::<PlainBuf>().expect("Parsing a PlainBuf should never return an error!"))
}
}
deserializer.deserialize_str(PlainVisitor)
}
}
impl Serialize for PlainBuf {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
serializer.serialize_str(&self.to_string())
}
} | ppend( | identifier_name |
match-on-borrowed.rs | // Test that a (partially) mutably borrowed place can be matched on, so long as
// we don't have to read any values that are mutably borrowed to determine
// which arm to take.
//
// Test that we don't allow mutating the value being matched on in a way that
// changes which patterns it matches, until we have chosen an arm.
#![feature(nll)]
struct A(i32, i32);
fn struct_example(mut a: A) {
let x = &mut a.0;
match a { // OK, no access of borrowed data
_ if false => (),
A(_, r) => (),
}
x;
}
fn indirect_struct_example(mut b: &mut A) {
let x = &mut b.0;
match *b { // OK, no access of borrowed data
_ if false => (),
A(_, r) => (),
}
x;
}
fn underscore_example(mut c: i32) {
let r = &mut c;
match c { // OK, no access of borrowed data (or any data at all)
_ if false => (),
_ => (),
}
r;
}
enum E {
V(i32, i32),
W,
}
fn enum_example(mut e: E) {
let x = match e {
E::V(ref mut x, _) => x,
E::W => panic!(),
};
match e { // Don't know that E uses a tag for its discriminant
_ if false => (),
E::V(_, r) => (), //~ ERROR
E::W => (),
}
x;
}
fn indirect_enum_example(mut f: &mut E) {
let x = match *f {
E::V(ref mut x, _) => x,
E::W => panic!(),
};
match f { // Don't know that E uses a tag for its discriminant
_ if false => (),
E::V(_, r) => (), //~ ERROR
E::W => (),
}
x;
}
fn match_on_muatbly_borrowed_ref(mut p: &bool) {
let r = &mut p;
match *p { // OK, no access at all
_ if false => (),
_ => (),
}
r;
}
fn match_on_borrowed(mut t: bool) {
let x = &mut t;
match t {
true => (), //~ ERROR
false => (),
}
x;
}
enum Never {}
fn never_init() {
let n: Never;
match n {} //~ ERROR
}
fn | () {}
| main | identifier_name |
match-on-borrowed.rs | // Test that a (partially) mutably borrowed place can be matched on, so long as
// we don't have to read any values that are mutably borrowed to determine
// which arm to take.
//
// Test that we don't allow mutating the value being matched on in a way that
// changes which patterns it matches, until we have chosen an arm.
#![feature(nll)]
struct A(i32, i32);
fn struct_example(mut a: A) {
let x = &mut a.0;
match a { // OK, no access of borrowed data
_ if false => (),
A(_, r) => (),
}
x;
} | let x = &mut b.0;
match *b { // OK, no access of borrowed data
_ if false => (),
A(_, r) => (),
}
x;
}
fn underscore_example(mut c: i32) {
let r = &mut c;
match c { // OK, no access of borrowed data (or any data at all)
_ if false => (),
_ => (),
}
r;
}
enum E {
V(i32, i32),
W,
}
fn enum_example(mut e: E) {
let x = match e {
E::V(ref mut x, _) => x,
E::W => panic!(),
};
match e { // Don't know that E uses a tag for its discriminant
_ if false => (),
E::V(_, r) => (), //~ ERROR
E::W => (),
}
x;
}
fn indirect_enum_example(mut f: &mut E) {
let x = match *f {
E::V(ref mut x, _) => x,
E::W => panic!(),
};
match f { // Don't know that E uses a tag for its discriminant
_ if false => (),
E::V(_, r) => (), //~ ERROR
E::W => (),
}
x;
}
fn match_on_muatbly_borrowed_ref(mut p: &bool) {
let r = &mut p;
match *p { // OK, no access at all
_ if false => (),
_ => (),
}
r;
}
fn match_on_borrowed(mut t: bool) {
let x = &mut t;
match t {
true => (), //~ ERROR
false => (),
}
x;
}
enum Never {}
fn never_init() {
let n: Never;
match n {} //~ ERROR
}
fn main() {} |
fn indirect_struct_example(mut b: &mut A) { | random_line_split |
match-on-borrowed.rs | // Test that a (partially) mutably borrowed place can be matched on, so long as
// we don't have to read any values that are mutably borrowed to determine
// which arm to take.
//
// Test that we don't allow mutating the value being matched on in a way that
// changes which patterns it matches, until we have chosen an arm.
#![feature(nll)]
struct A(i32, i32);
fn struct_example(mut a: A) {
let x = &mut a.0;
match a { // OK, no access of borrowed data
_ if false => (),
A(_, r) => (),
}
x;
}
fn indirect_struct_example(mut b: &mut A) {
let x = &mut b.0;
match *b { // OK, no access of borrowed data
_ if false => (),
A(_, r) => (),
}
x;
}
fn underscore_example(mut c: i32) {
let r = &mut c;
match c { // OK, no access of borrowed data (or any data at all)
_ if false => (),
_ => (),
}
r;
}
enum E {
V(i32, i32),
W,
}
fn enum_example(mut e: E) {
let x = match e {
E::V(ref mut x, _) => x,
E::W => panic!(),
};
match e { // Don't know that E uses a tag for its discriminant
_ if false => (),
E::V(_, r) => (), //~ ERROR
E::W => (),
}
x;
}
fn indirect_enum_example(mut f: &mut E) {
let x = match *f {
E::V(ref mut x, _) => x,
E::W => panic!(),
};
match f { // Don't know that E uses a tag for its discriminant
_ if false => (),
E::V(_, r) => (), //~ ERROR
E::W => (),
}
x;
}
fn match_on_muatbly_borrowed_ref(mut p: &bool) {
let r = &mut p;
match *p { // OK, no access at all
_ if false => (),
_ => (),
}
r;
}
fn match_on_borrowed(mut t: bool) |
enum Never {}
fn never_init() {
let n: Never;
match n {} //~ ERROR
}
fn main() {}
| {
let x = &mut t;
match t {
true => (), //~ ERROR
false => (),
}
x;
} | identifier_body |
namespaces.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 cssparser::ast::*;
use std::collections::hashmap::HashMap;
use servo_util::namespace::Namespace;
use errors::log_css_error;
pub struct NamespaceMap {
pub default: Option<Namespace>,
pub prefix_map: HashMap<String, Namespace>,
} | }
}
pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) {
let location = rule.location;
macro_rules! syntax_error(
() => {{
log_css_error(location, "Invalid @namespace rule");
return
}};
);
if rule.block.is_some() { syntax_error!() }
let mut prefix: Option<String> = None;
let mut ns: Option<Namespace> = None;
let mut iter = rule.prelude.move_skip_whitespace();
for component_value in iter {
match component_value {
Ident(value) => {
if prefix.is_some() { syntax_error!() }
prefix = Some(value.into_string());
},
URL(value) | String(value) => {
if ns.is_some() { syntax_error!() }
ns = Some(Namespace::from_str(value.as_slice()));
break
},
_ => syntax_error!(),
}
}
if iter.next().is_some() { syntax_error!() }
match (prefix, ns) {
(Some(prefix), Some(ns)) => {
if namespaces.prefix_map.swap(prefix, ns).is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
},
(None, Some(ns)) => {
if namespaces.default.is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
namespaces.default = Some(ns);
},
_ => syntax_error!()
}
} |
impl NamespaceMap {
pub fn new() -> NamespaceMap {
NamespaceMap { default: None, prefix_map: HashMap::new() } | random_line_split |
namespaces.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 cssparser::ast::*;
use std::collections::hashmap::HashMap;
use servo_util::namespace::Namespace;
use errors::log_css_error;
pub struct NamespaceMap {
pub default: Option<Namespace>,
pub prefix_map: HashMap<String, Namespace>,
}
impl NamespaceMap {
pub fn new() -> NamespaceMap |
}
pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) {
let location = rule.location;
macro_rules! syntax_error(
() => {{
log_css_error(location, "Invalid @namespace rule");
return
}};
);
if rule.block.is_some() { syntax_error!() }
let mut prefix: Option<String> = None;
let mut ns: Option<Namespace> = None;
let mut iter = rule.prelude.move_skip_whitespace();
for component_value in iter {
match component_value {
Ident(value) => {
if prefix.is_some() { syntax_error!() }
prefix = Some(value.into_string());
},
URL(value) | String(value) => {
if ns.is_some() { syntax_error!() }
ns = Some(Namespace::from_str(value.as_slice()));
break
},
_ => syntax_error!(),
}
}
if iter.next().is_some() { syntax_error!() }
match (prefix, ns) {
(Some(prefix), Some(ns)) => {
if namespaces.prefix_map.swap(prefix, ns).is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
},
(None, Some(ns)) => {
if namespaces.default.is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
namespaces.default = Some(ns);
},
_ => syntax_error!()
}
}
| {
NamespaceMap { default: None, prefix_map: HashMap::new() }
} | identifier_body |
namespaces.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 cssparser::ast::*;
use std::collections::hashmap::HashMap;
use servo_util::namespace::Namespace;
use errors::log_css_error;
pub struct NamespaceMap {
pub default: Option<Namespace>,
pub prefix_map: HashMap<String, Namespace>,
}
impl NamespaceMap {
pub fn new() -> NamespaceMap {
NamespaceMap { default: None, prefix_map: HashMap::new() }
}
}
pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) {
let location = rule.location;
macro_rules! syntax_error(
() => {{
log_css_error(location, "Invalid @namespace rule");
return
}};
);
if rule.block.is_some() { syntax_error!() }
let mut prefix: Option<String> = None;
let mut ns: Option<Namespace> = None;
let mut iter = rule.prelude.move_skip_whitespace();
for component_value in iter {
match component_value {
Ident(value) => {
if prefix.is_some() { syntax_error!() }
prefix = Some(value.into_string());
},
URL(value) | String(value) => {
if ns.is_some() { syntax_error!() }
ns = Some(Namespace::from_str(value.as_slice()));
break
},
_ => syntax_error!(),
}
}
if iter.next().is_some() { syntax_error!() }
match (prefix, ns) {
(Some(prefix), Some(ns)) => {
if namespaces.prefix_map.swap(prefix, ns).is_some() |
},
(None, Some(ns)) => {
if namespaces.default.is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
namespaces.default = Some(ns);
},
_ => syntax_error!()
}
}
| {
log_css_error(location, "Duplicate @namespace rule");
} | conditional_block |
namespaces.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 cssparser::ast::*;
use std::collections::hashmap::HashMap;
use servo_util::namespace::Namespace;
use errors::log_css_error;
pub struct NamespaceMap {
pub default: Option<Namespace>,
pub prefix_map: HashMap<String, Namespace>,
}
impl NamespaceMap {
pub fn new() -> NamespaceMap {
NamespaceMap { default: None, prefix_map: HashMap::new() }
}
}
pub fn | (rule: AtRule, namespaces: &mut NamespaceMap) {
let location = rule.location;
macro_rules! syntax_error(
() => {{
log_css_error(location, "Invalid @namespace rule");
return
}};
);
if rule.block.is_some() { syntax_error!() }
let mut prefix: Option<String> = None;
let mut ns: Option<Namespace> = None;
let mut iter = rule.prelude.move_skip_whitespace();
for component_value in iter {
match component_value {
Ident(value) => {
if prefix.is_some() { syntax_error!() }
prefix = Some(value.into_string());
},
URL(value) | String(value) => {
if ns.is_some() { syntax_error!() }
ns = Some(Namespace::from_str(value.as_slice()));
break
},
_ => syntax_error!(),
}
}
if iter.next().is_some() { syntax_error!() }
match (prefix, ns) {
(Some(prefix), Some(ns)) => {
if namespaces.prefix_map.swap(prefix, ns).is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
},
(None, Some(ns)) => {
if namespaces.default.is_some() {
log_css_error(location, "Duplicate @namespace rule");
}
namespaces.default = Some(ns);
},
_ => syntax_error!()
}
}
| parse_namespace_rule | identifier_name |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding::HTMLObjectElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::node::{Node, window_from_node};
use dom::validation::Validatable;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use net_traits::image::base::Image;
use std::sync::Arc;
use string_cache::Atom;
#[dom_struct]
pub struct HTMLObjectElement {
htmlelement: HTMLElement,
image: DOMRefCell<Option<Arc<Image>>>,
}
impl HTMLObjectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLObjectElement {
HTMLObjectElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document),
image: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLObjectElement> {
Node::reflect_node(box HTMLObjectElement::new_inherited(localName, prefix, document),
document,
HTMLObjectElementBinding::Wrap)
}
}
trait ProcessDataURL {
fn process_data_url(&self);
}
impl<'a> ProcessDataURL for &'a HTMLObjectElement {
// Makes the local `data` member match the status of the `data` attribute and starts
/// prefetching the image. This method must be called after `data` is changed.
fn process_data_url(&self) {
let elem = self.upcast::<Element>();
// TODO: support other values
match (elem.get_attribute(&ns!(), &atom!("type")),
elem.get_attribute(&ns!(), &atom!("data"))) {
(None, Some(_uri)) => {
// TODO(gw): Prefetch the image here.
}
_ => { }
}
}
}
impl HTMLObjectElementMethods for HTMLObjectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r(), self.upcast())
}
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn | (&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
}
impl Validatable for HTMLObjectElement {}
impl VirtualMethods for HTMLObjectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("data") => {
if let AttributeMutation::Set(_) = mutation {
self.process_data_url();
}
},
_ => {},
}
}
}
impl FormControl for HTMLObjectElement {}
| GetForm | identifier_name |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding::HTMLObjectElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::node::{Node, window_from_node};
use dom::validation::Validatable;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use net_traits::image::base::Image;
use std::sync::Arc;
use string_cache::Atom;
#[dom_struct]
pub struct HTMLObjectElement {
htmlelement: HTMLElement,
image: DOMRefCell<Option<Arc<Image>>>,
}
impl HTMLObjectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLObjectElement {
HTMLObjectElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document),
image: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLObjectElement> {
Node::reflect_node(box HTMLObjectElement::new_inherited(localName, prefix, document),
document,
HTMLObjectElementBinding::Wrap)
}
}
trait ProcessDataURL {
fn process_data_url(&self);
}
impl<'a> ProcessDataURL for &'a HTMLObjectElement {
// Makes the local `data` member match the status of the `data` attribute and starts
/// prefetching the image. This method must be called after `data` is changed.
fn process_data_url(&self) {
let elem = self.upcast::<Element>();
// TODO: support other values
match (elem.get_attribute(&ns!(), &atom!("type")),
elem.get_attribute(&ns!(), &atom!("data"))) {
(None, Some(_uri)) => {
// TODO(gw): Prefetch the image here.
}
_ => { }
}
}
}
impl HTMLObjectElementMethods for HTMLObjectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r(), self.upcast())
}
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> |
}
impl Validatable for HTMLObjectElement {}
impl VirtualMethods for HTMLObjectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("data") => {
if let AttributeMutation::Set(_) = mutation {
self.process_data_url();
}
},
_ => {},
}
}
}
impl FormControl for HTMLObjectElement {}
| {
self.form_owner()
} | identifier_body |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding::HTMLObjectElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::node::{Node, window_from_node};
use dom::validation::Validatable;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use net_traits::image::base::Image;
use std::sync::Arc;
use string_cache::Atom;
#[dom_struct]
pub struct HTMLObjectElement {
htmlelement: HTMLElement,
image: DOMRefCell<Option<Arc<Image>>>,
}
impl HTMLObjectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLObjectElement {
HTMLObjectElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document),
image: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLObjectElement> {
Node::reflect_node(box HTMLObjectElement::new_inherited(localName, prefix, document),
document,
HTMLObjectElementBinding::Wrap)
}
}
trait ProcessDataURL {
fn process_data_url(&self);
}
impl<'a> ProcessDataURL for &'a HTMLObjectElement {
// Makes the local `data` member match the status of the `data` attribute and starts
/// prefetching the image. This method must be called after `data` is changed.
fn process_data_url(&self) {
let elem = self.upcast::<Element>();
// TODO: support other values
match (elem.get_attribute(&ns!(), &atom!("type")),
elem.get_attribute(&ns!(), &atom!("data"))) {
(None, Some(_uri)) => {
// TODO(gw): Prefetch the image here.
}
_ => |
}
}
}
impl HTMLObjectElementMethods for HTMLObjectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r(), self.upcast())
}
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
}
impl Validatable for HTMLObjectElement {}
impl VirtualMethods for HTMLObjectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("data") => {
if let AttributeMutation::Set(_) = mutation {
self.process_data_url();
}
},
_ => {},
}
}
}
impl FormControl for HTMLObjectElement {}
| { } | conditional_block |
htmlobjectelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding;
use dom::bindings::codegen::Bindings::HTMLObjectElementBinding::HTMLObjectElementMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root; | use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::node::{Node, window_from_node};
use dom::validation::Validatable;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use net_traits::image::base::Image;
use std::sync::Arc;
use string_cache::Atom;
#[dom_struct]
pub struct HTMLObjectElement {
htmlelement: HTMLElement,
image: DOMRefCell<Option<Arc<Image>>>,
}
impl HTMLObjectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLObjectElement {
HTMLObjectElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document),
image: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLObjectElement> {
Node::reflect_node(box HTMLObjectElement::new_inherited(localName, prefix, document),
document,
HTMLObjectElementBinding::Wrap)
}
}
trait ProcessDataURL {
fn process_data_url(&self);
}
impl<'a> ProcessDataURL for &'a HTMLObjectElement {
// Makes the local `data` member match the status of the `data` attribute and starts
/// prefetching the image. This method must be called after `data` is changed.
fn process_data_url(&self) {
let elem = self.upcast::<Element>();
// TODO: support other values
match (elem.get_attribute(&ns!(), &atom!("type")),
elem.get_attribute(&ns!(), &atom!("data"))) {
(None, Some(_uri)) => {
// TODO(gw): Prefetch the image here.
}
_ => { }
}
}
}
impl HTMLObjectElementMethods for HTMLObjectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r(), self.upcast())
}
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_getter!(Type, "type");
// https://html.spec.whatwg.org/multipage/#dom-object-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
}
impl Validatable for HTMLObjectElement {}
impl VirtualMethods for HTMLObjectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("data") => {
if let AttributeMutation::Set(_) = mutation {
self.process_data_url();
}
},
_ => {},
}
}
}
impl FormControl for HTMLObjectElement {} | use dom::bindings::str::DOMString;
use dom::document::Document; | random_line_split |
image.rs | //
//
//
use geom::{Rect,Px};
use surface::Colour;
pub enum Align {
Left,
Center,
Right,
}
//enum Tile {
// None,
// Stretch,
// Repeat,
//}
/// Static image wrapper
pub struct Image<T: Buffer>
{
has_changed: ::std::cell::Cell<bool>,
align_v: Align,
align_h: Align,
data: T,
}
impl Align
{
fn get_ofs(&self, item: u32, avail: u32) -> u32 {
if item >= avail {
return 0;
}
match self
{
&Align::Left => 0,
&Align::Center => avail / 2 - item / 2,
&Align::Right => avail - item,
}
}
}
impl<T: Buffer> Image<T>
{
pub fn new(i: T) -> Image<T> {
Image {
has_changed: ::std::cell::Cell::new(true),
data: i,
align_h: Align::Center,
align_v: Align::Center,
}
}
/// Set the vertical alignment of the image
pub fn set_align_v(&mut self, align: Align) {
self.align_v = align;
self.force_redraw();
}
/// Set the horizontal alignment of the image
pub fn set_align_h(&mut self, align: Align) {
self.align_h = align;
self.force_redraw();
}
pub fn force_redraw(&self) {
self.has_changed.set(true);
}
pub fn dims_px(&self) -> (u32,u32) {
let Rect { w: Px(w), h: Px(h),.. } = self.data.dims_px();
(w, h)
}
}
impl<T: Buffer> ::Element for Image<T>
{
fn focus_change(&self, _have: bool) {
// Don't care
}
fn handle_event(&self, _ev: ::InputEvent, _win: &mut ::window::Window) -> bool {
// Don't care
false
}
fn render(&self, surface: ::surface::SurfaceView, force: bool) {
if force || self.has_changed.get() {
let (i_w, i_h) = self.dims_px();
let x = self.align_h.get_ofs(i_w, surface.width());
let y = self.align_h.get_ofs(i_h, surface.height());
let subsurf = surface.slice( Rect::new(Px(x), Px(y), Px(!0), Px(!0)) );
self.data.render(subsurf);
self.has_changed.set(false);
}
}
fn element_at_pos(&self, _x: u32, _y: u32) -> (&::Element, (u32,u32)) {
(self, (0,0))
}
}
pub trait Buffer
{
fn dims_px(&self) -> Rect<Px>;
//fn dims_phys(&self) -> Rect<::geom::Mm>;
fn render(&self, buf: ::surface::SurfaceView);
}
impl Buffer for ::surface::Colour {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0,0,0)
}
fn render(&self, buf: ::surface::SurfaceView) {
buf.fill_rect(buf.rect(), *self);
}
}
#[derive(Debug)]
pub enum LoadError {
Io( ::std::io::Error ),
Malformed,
}
impl_conv! {
From<::std::io::Error>(v) for LoadError {{
LoadError::Io(v)
}}
From<::byteorder::Error>(v) for LoadError {{
match v
{
::byteorder::Error::Io(v) => LoadError::Io(v),
::byteorder::Error::UnexpectedEOF => LoadError::Malformed,
}
}}
}
fn get_4_bytes<F: ::std::io::Read>(f: &mut F) -> Result<[u8; 4], ::std::io::Error> {
let mut rv = [0; 4];
if try!(f.read(&mut rv))!= 4 {
todo!("Handle unexpected EOF in get_4_bytes");
}
Ok( rv )
}
/// Full-colour raster image
pub struct RasterRGB
{
width: usize,
data: Vec<u8>,
}
impl RasterRGB
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P) -> Result<Image<Self>,LoadError> {
Self::new(path).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P) -> Result<RasterRGB,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
use std::io::Read;
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR24" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
kernel_log!("w = {}, h = {}", w, h);
// - Read data
let mut data: Vec<u8> = (0.. w*h*3).map(|_| 0u8).collect();
try!(file.read(&mut data));
Ok(RasterRGB {
width: w,
data: data,
})
}
}
impl Buffer for RasterRGB {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.data.len() / 3 / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
kernel_log!("buf.rect() = {:?}, self.dims_px() = {:?}", buf.rect(), self.dims_px());
let mut buf_rows = self.data.chunks(self.width*3);
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let val = buf_rows.next().unwrap();
for (d, px) in Iterator::zip( line.iter_mut(), val.chunks(3) )
{
let v = (px[0] as u32) << 16 | (px[1] as u32) << 8 | (px[2] as u32) << 0;
*d = v;
}
});
}
}
/// Raster single-colour image with alpha
pub struct RasterMonoA
{
fg: ::surface::Colour,
width: usize,
alpha: Vec<u8>,
}
impl RasterMonoA
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour) -> Result<Image<Self>,LoadError> {
Self::new(path, fg).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour) -> Result<RasterMonoA,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
use std::io::Read;
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR8M" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
// - Read data (directly)
let mut alpha: Vec<u8> = (0.. w*h).map(|_| 0u8).collect();
try!(file.read(&mut alpha));
Ok(RasterMonoA {
fg: fg,
width: w,
alpha: alpha,
})
}
}
impl Buffer for RasterMonoA {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.alpha.len() / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
let mut buf_rows = self.alpha.chunks(self.width);
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let alpha = buf_rows.next().unwrap();
for (d, a) in Iterator::zip( line.iter_mut(), alpha.iter().cloned() )
{
*d = Colour::blend_alpha( Colour::from_argb32(*d), self.fg, 255 - a ).as_argb32();
}
});
}
}
/// Raster two-colour image with alpha
pub struct RasterBiA
{
bg: ::surface::Colour,
fg: ::surface::Colour,
width: usize,
data: Vec<bool>, // TODO: Use BitVec or similar
alpha: Vec<u8>,
}
impl RasterBiA
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour, bg: ::surface::Colour) -> Result<Image<Self>,LoadError> {
Self::new(path, fg, bg).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour, bg: ::surface::Colour) -> Result<RasterBiA,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR8B" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
let mut data = Vec::with_capacity(w * h);
let mut alpha = Vec::with_capacity(w * h);
for _ in 0.. w * h
{
let v = try!( file.read_u8() );
data.push( v >= 128 );
alpha.push( (v & 0x7F) * 2 | ((v >> 6) & 1) );
}
Ok(RasterBiA {
bg: bg,
fg: fg,
width: w,
data: data,
alpha: alpha,
})
}
}
impl Buffer for RasterBiA {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.data.len() / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
// - Alpha defaults to zero if the alpha vec is empty
let mut buf_rows = Iterator::zip( self.data.chunks(self.width), self.alpha.chunks(self.width).chain(::std::iter::repeat(&[][..])) );
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let (bitmap, alpha) = buf_rows.next().unwrap();
for (d, (bm, a)) in Iterator::zip( line.iter_mut(), Iterator::zip( bitmap.iter(), alpha.iter().cloned().chain(::std::iter::repeat(0)) ) )
{
let c = if *bm { self.fg } else | ;
//kernel_log!("c = {:x}, alpha = {}", c.as_argb32(), a);
*d = Colour::blend_alpha( Colour::from_argb32(*d), c, 255 - a ).as_argb32();
}
});
}
}
| { self.bg } | conditional_block |
image.rs | //
//
//
use geom::{Rect,Px};
use surface::Colour;
pub enum Align {
Left,
Center,
Right,
}
//enum Tile {
// None,
// Stretch,
// Repeat,
//}
/// Static image wrapper
pub struct Image<T: Buffer>
{
has_changed: ::std::cell::Cell<bool>,
align_v: Align,
align_h: Align,
data: T,
}
impl Align
{
fn get_ofs(&self, item: u32, avail: u32) -> u32 {
if item >= avail {
return 0;
}
match self
{
&Align::Left => 0,
&Align::Center => avail / 2 - item / 2,
&Align::Right => avail - item,
}
}
}
impl<T: Buffer> Image<T>
{
pub fn new(i: T) -> Image<T> {
Image {
has_changed: ::std::cell::Cell::new(true),
data: i,
align_h: Align::Center,
align_v: Align::Center,
}
}
/// Set the vertical alignment of the image
pub fn set_align_v(&mut self, align: Align) {
self.align_v = align;
self.force_redraw();
}
/// Set the horizontal alignment of the image
pub fn set_align_h(&mut self, align: Align) {
self.align_h = align;
self.force_redraw();
}
pub fn force_redraw(&self) {
self.has_changed.set(true);
}
pub fn dims_px(&self) -> (u32,u32) {
let Rect { w: Px(w), h: Px(h),.. } = self.data.dims_px();
(w, h)
}
}
impl<T: Buffer> ::Element for Image<T>
{
fn focus_change(&self, _have: bool) {
// Don't care
}
fn handle_event(&self, _ev: ::InputEvent, _win: &mut ::window::Window) -> bool |
fn render(&self, surface: ::surface::SurfaceView, force: bool) {
if force || self.has_changed.get() {
let (i_w, i_h) = self.dims_px();
let x = self.align_h.get_ofs(i_w, surface.width());
let y = self.align_h.get_ofs(i_h, surface.height());
let subsurf = surface.slice( Rect::new(Px(x), Px(y), Px(!0), Px(!0)) );
self.data.render(subsurf);
self.has_changed.set(false);
}
}
fn element_at_pos(&self, _x: u32, _y: u32) -> (&::Element, (u32,u32)) {
(self, (0,0))
}
}
pub trait Buffer
{
fn dims_px(&self) -> Rect<Px>;
//fn dims_phys(&self) -> Rect<::geom::Mm>;
fn render(&self, buf: ::surface::SurfaceView);
}
impl Buffer for ::surface::Colour {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0,0,0)
}
fn render(&self, buf: ::surface::SurfaceView) {
buf.fill_rect(buf.rect(), *self);
}
}
#[derive(Debug)]
pub enum LoadError {
Io( ::std::io::Error ),
Malformed,
}
impl_conv! {
From<::std::io::Error>(v) for LoadError {{
LoadError::Io(v)
}}
From<::byteorder::Error>(v) for LoadError {{
match v
{
::byteorder::Error::Io(v) => LoadError::Io(v),
::byteorder::Error::UnexpectedEOF => LoadError::Malformed,
}
}}
}
fn get_4_bytes<F: ::std::io::Read>(f: &mut F) -> Result<[u8; 4], ::std::io::Error> {
let mut rv = [0; 4];
if try!(f.read(&mut rv))!= 4 {
todo!("Handle unexpected EOF in get_4_bytes");
}
Ok( rv )
}
/// Full-colour raster image
pub struct RasterRGB
{
width: usize,
data: Vec<u8>,
}
impl RasterRGB
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P) -> Result<Image<Self>,LoadError> {
Self::new(path).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P) -> Result<RasterRGB,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
use std::io::Read;
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR24" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
kernel_log!("w = {}, h = {}", w, h);
// - Read data
let mut data: Vec<u8> = (0.. w*h*3).map(|_| 0u8).collect();
try!(file.read(&mut data));
Ok(RasterRGB {
width: w,
data: data,
})
}
}
impl Buffer for RasterRGB {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.data.len() / 3 / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
kernel_log!("buf.rect() = {:?}, self.dims_px() = {:?}", buf.rect(), self.dims_px());
let mut buf_rows = self.data.chunks(self.width*3);
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let val = buf_rows.next().unwrap();
for (d, px) in Iterator::zip( line.iter_mut(), val.chunks(3) )
{
let v = (px[0] as u32) << 16 | (px[1] as u32) << 8 | (px[2] as u32) << 0;
*d = v;
}
});
}
}
/// Raster single-colour image with alpha
pub struct RasterMonoA
{
fg: ::surface::Colour,
width: usize,
alpha: Vec<u8>,
}
impl RasterMonoA
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour) -> Result<Image<Self>,LoadError> {
Self::new(path, fg).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour) -> Result<RasterMonoA,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
use std::io::Read;
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR8M" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
// - Read data (directly)
let mut alpha: Vec<u8> = (0.. w*h).map(|_| 0u8).collect();
try!(file.read(&mut alpha));
Ok(RasterMonoA {
fg: fg,
width: w,
alpha: alpha,
})
}
}
impl Buffer for RasterMonoA {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.alpha.len() / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
let mut buf_rows = self.alpha.chunks(self.width);
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let alpha = buf_rows.next().unwrap();
for (d, a) in Iterator::zip( line.iter_mut(), alpha.iter().cloned() )
{
*d = Colour::blend_alpha( Colour::from_argb32(*d), self.fg, 255 - a ).as_argb32();
}
});
}
}
/// Raster two-colour image with alpha
pub struct RasterBiA
{
bg: ::surface::Colour,
fg: ::surface::Colour,
width: usize,
data: Vec<bool>, // TODO: Use BitVec or similar
alpha: Vec<u8>,
}
impl RasterBiA
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour, bg: ::surface::Colour) -> Result<Image<Self>,LoadError> {
Self::new(path, fg, bg).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour, bg: ::surface::Colour) -> Result<RasterBiA,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR8B" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
let mut data = Vec::with_capacity(w * h);
let mut alpha = Vec::with_capacity(w * h);
for _ in 0.. w * h
{
let v = try!( file.read_u8() );
data.push( v >= 128 );
alpha.push( (v & 0x7F) * 2 | ((v >> 6) & 1) );
}
Ok(RasterBiA {
bg: bg,
fg: fg,
width: w,
data: data,
alpha: alpha,
})
}
}
impl Buffer for RasterBiA {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.data.len() / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
// - Alpha defaults to zero if the alpha vec is empty
let mut buf_rows = Iterator::zip( self.data.chunks(self.width), self.alpha.chunks(self.width).chain(::std::iter::repeat(&[][..])) );
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let (bitmap, alpha) = buf_rows.next().unwrap();
for (d, (bm, a)) in Iterator::zip( line.iter_mut(), Iterator::zip( bitmap.iter(), alpha.iter().cloned().chain(::std::iter::repeat(0)) ) )
{
let c = if *bm { self.fg } else { self.bg };
//kernel_log!("c = {:x}, alpha = {}", c.as_argb32(), a);
*d = Colour::blend_alpha( Colour::from_argb32(*d), c, 255 - a ).as_argb32();
}
});
}
}
| {
// Don't care
false
} | identifier_body |
image.rs | //
//
//
use geom::{Rect,Px};
use surface::Colour;
pub enum Align {
Left,
Center,
Right,
}
//enum Tile {
// None,
// Stretch,
// Repeat,
//}
/// Static image wrapper
pub struct Image<T: Buffer>
{
has_changed: ::std::cell::Cell<bool>,
align_v: Align,
align_h: Align,
data: T,
}
impl Align
{
fn get_ofs(&self, item: u32, avail: u32) -> u32 {
if item >= avail {
return 0;
}
match self
{
&Align::Left => 0,
&Align::Center => avail / 2 - item / 2,
&Align::Right => avail - item,
}
}
}
impl<T: Buffer> Image<T>
{
pub fn new(i: T) -> Image<T> {
Image {
has_changed: ::std::cell::Cell::new(true),
data: i,
align_h: Align::Center,
align_v: Align::Center,
}
}
/// Set the vertical alignment of the image
pub fn set_align_v(&mut self, align: Align) {
self.align_v = align;
self.force_redraw();
}
/// Set the horizontal alignment of the image
pub fn set_align_h(&mut self, align: Align) {
self.align_h = align;
self.force_redraw();
}
pub fn force_redraw(&self) {
self.has_changed.set(true);
}
pub fn dims_px(&self) -> (u32,u32) {
let Rect { w: Px(w), h: Px(h),.. } = self.data.dims_px();
(w, h)
}
}
impl<T: Buffer> ::Element for Image<T>
{
fn focus_change(&self, _have: bool) {
// Don't care
}
fn handle_event(&self, _ev: ::InputEvent, _win: &mut ::window::Window) -> bool {
// Don't care
false
}
fn render(&self, surface: ::surface::SurfaceView, force: bool) {
if force || self.has_changed.get() {
let (i_w, i_h) = self.dims_px();
let x = self.align_h.get_ofs(i_w, surface.width());
let y = self.align_h.get_ofs(i_h, surface.height());
let subsurf = surface.slice( Rect::new(Px(x), Px(y), Px(!0), Px(!0)) );
self.data.render(subsurf);
self.has_changed.set(false);
}
}
fn element_at_pos(&self, _x: u32, _y: u32) -> (&::Element, (u32,u32)) {
(self, (0,0))
}
}
pub trait Buffer
{
fn dims_px(&self) -> Rect<Px>;
//fn dims_phys(&self) -> Rect<::geom::Mm>;
fn render(&self, buf: ::surface::SurfaceView);
}
impl Buffer for ::surface::Colour {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0,0,0)
}
fn render(&self, buf: ::surface::SurfaceView) {
buf.fill_rect(buf.rect(), *self);
}
}
#[derive(Debug)]
pub enum LoadError {
Io( ::std::io::Error ),
Malformed,
}
impl_conv! {
From<::std::io::Error>(v) for LoadError {{
LoadError::Io(v)
}}
From<::byteorder::Error>(v) for LoadError {{
match v
{
::byteorder::Error::Io(v) => LoadError::Io(v),
::byteorder::Error::UnexpectedEOF => LoadError::Malformed,
}
}}
}
fn get_4_bytes<F: ::std::io::Read>(f: &mut F) -> Result<[u8; 4], ::std::io::Error> {
let mut rv = [0; 4];
if try!(f.read(&mut rv))!= 4 {
todo!("Handle unexpected EOF in get_4_bytes");
}
Ok( rv )
}
/// Full-colour raster image
pub struct RasterRGB
{
width: usize,
data: Vec<u8>,
}
impl RasterRGB
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P) -> Result<Image<Self>,LoadError> {
Self::new(path).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P) -> Result<RasterRGB,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
use std::io::Read;
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR24" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
kernel_log!("w = {}, h = {}", w, h);
// - Read data
let mut data: Vec<u8> = (0.. w*h*3).map(|_| 0u8).collect();
try!(file.read(&mut data));
Ok(RasterRGB {
width: w,
data: data,
})
}
}
impl Buffer for RasterRGB {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.data.len() / 3 / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
kernel_log!("buf.rect() = {:?}, self.dims_px() = {:?}", buf.rect(), self.dims_px());
let mut buf_rows = self.data.chunks(self.width*3);
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let val = buf_rows.next().unwrap();
for (d, px) in Iterator::zip( line.iter_mut(), val.chunks(3) )
{
let v = (px[0] as u32) << 16 | (px[1] as u32) << 8 | (px[2] as u32) << 0;
*d = v;
}
});
}
}
/// Raster single-colour image with alpha
pub struct RasterMonoA
{
fg: ::surface::Colour,
width: usize,
alpha: Vec<u8>,
}
impl RasterMonoA
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour) -> Result<Image<Self>,LoadError> {
Self::new(path, fg).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour) -> Result<RasterMonoA,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
use std::io::Read;
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR8M" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
// - Read data (directly)
let mut alpha: Vec<u8> = (0.. w*h).map(|_| 0u8).collect();
try!(file.read(&mut alpha));
Ok(RasterMonoA {
fg: fg,
width: w,
alpha: alpha,
})
}
}
impl Buffer for RasterMonoA {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.alpha.len() / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
let mut buf_rows = self.alpha.chunks(self.width);
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let alpha = buf_rows.next().unwrap();
for (d, a) in Iterator::zip( line.iter_mut(), alpha.iter().cloned() )
{
*d = Colour::blend_alpha( Colour::from_argb32(*d), self.fg, 255 - a ).as_argb32();
}
}); | pub struct RasterBiA
{
bg: ::surface::Colour,
fg: ::surface::Colour,
width: usize,
data: Vec<bool>, // TODO: Use BitVec or similar
alpha: Vec<u8>,
}
impl RasterBiA
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour, bg: ::surface::Colour) -> Result<Image<Self>,LoadError> {
Self::new(path, fg, bg).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour, bg: ::surface::Colour) -> Result<RasterBiA,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR8B" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
let mut data = Vec::with_capacity(w * h);
let mut alpha = Vec::with_capacity(w * h);
for _ in 0.. w * h
{
let v = try!( file.read_u8() );
data.push( v >= 128 );
alpha.push( (v & 0x7F) * 2 | ((v >> 6) & 1) );
}
Ok(RasterBiA {
bg: bg,
fg: fg,
width: w,
data: data,
alpha: alpha,
})
}
}
impl Buffer for RasterBiA {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.data.len() / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
// - Alpha defaults to zero if the alpha vec is empty
let mut buf_rows = Iterator::zip( self.data.chunks(self.width), self.alpha.chunks(self.width).chain(::std::iter::repeat(&[][..])) );
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let (bitmap, alpha) = buf_rows.next().unwrap();
for (d, (bm, a)) in Iterator::zip( line.iter_mut(), Iterator::zip( bitmap.iter(), alpha.iter().cloned().chain(::std::iter::repeat(0)) ) )
{
let c = if *bm { self.fg } else { self.bg };
//kernel_log!("c = {:x}, alpha = {}", c.as_argb32(), a);
*d = Colour::blend_alpha( Colour::from_argb32(*d), c, 255 - a ).as_argb32();
}
});
}
} | }
}
/// Raster two-colour image with alpha | random_line_split |
image.rs | //
//
//
use geom::{Rect,Px};
use surface::Colour;
pub enum Align {
Left,
Center,
Right,
}
//enum Tile {
// None,
// Stretch,
// Repeat,
//}
/// Static image wrapper
pub struct | <T: Buffer>
{
has_changed: ::std::cell::Cell<bool>,
align_v: Align,
align_h: Align,
data: T,
}
impl Align
{
fn get_ofs(&self, item: u32, avail: u32) -> u32 {
if item >= avail {
return 0;
}
match self
{
&Align::Left => 0,
&Align::Center => avail / 2 - item / 2,
&Align::Right => avail - item,
}
}
}
impl<T: Buffer> Image<T>
{
pub fn new(i: T) -> Image<T> {
Image {
has_changed: ::std::cell::Cell::new(true),
data: i,
align_h: Align::Center,
align_v: Align::Center,
}
}
/// Set the vertical alignment of the image
pub fn set_align_v(&mut self, align: Align) {
self.align_v = align;
self.force_redraw();
}
/// Set the horizontal alignment of the image
pub fn set_align_h(&mut self, align: Align) {
self.align_h = align;
self.force_redraw();
}
pub fn force_redraw(&self) {
self.has_changed.set(true);
}
pub fn dims_px(&self) -> (u32,u32) {
let Rect { w: Px(w), h: Px(h),.. } = self.data.dims_px();
(w, h)
}
}
impl<T: Buffer> ::Element for Image<T>
{
fn focus_change(&self, _have: bool) {
// Don't care
}
fn handle_event(&self, _ev: ::InputEvent, _win: &mut ::window::Window) -> bool {
// Don't care
false
}
fn render(&self, surface: ::surface::SurfaceView, force: bool) {
if force || self.has_changed.get() {
let (i_w, i_h) = self.dims_px();
let x = self.align_h.get_ofs(i_w, surface.width());
let y = self.align_h.get_ofs(i_h, surface.height());
let subsurf = surface.slice( Rect::new(Px(x), Px(y), Px(!0), Px(!0)) );
self.data.render(subsurf);
self.has_changed.set(false);
}
}
fn element_at_pos(&self, _x: u32, _y: u32) -> (&::Element, (u32,u32)) {
(self, (0,0))
}
}
pub trait Buffer
{
fn dims_px(&self) -> Rect<Px>;
//fn dims_phys(&self) -> Rect<::geom::Mm>;
fn render(&self, buf: ::surface::SurfaceView);
}
impl Buffer for ::surface::Colour {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0,0,0)
}
fn render(&self, buf: ::surface::SurfaceView) {
buf.fill_rect(buf.rect(), *self);
}
}
#[derive(Debug)]
pub enum LoadError {
Io( ::std::io::Error ),
Malformed,
}
impl_conv! {
From<::std::io::Error>(v) for LoadError {{
LoadError::Io(v)
}}
From<::byteorder::Error>(v) for LoadError {{
match v
{
::byteorder::Error::Io(v) => LoadError::Io(v),
::byteorder::Error::UnexpectedEOF => LoadError::Malformed,
}
}}
}
fn get_4_bytes<F: ::std::io::Read>(f: &mut F) -> Result<[u8; 4], ::std::io::Error> {
let mut rv = [0; 4];
if try!(f.read(&mut rv))!= 4 {
todo!("Handle unexpected EOF in get_4_bytes");
}
Ok( rv )
}
/// Full-colour raster image
pub struct RasterRGB
{
width: usize,
data: Vec<u8>,
}
impl RasterRGB
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P) -> Result<Image<Self>,LoadError> {
Self::new(path).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P) -> Result<RasterRGB,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
use std::io::Read;
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR24" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
kernel_log!("w = {}, h = {}", w, h);
// - Read data
let mut data: Vec<u8> = (0.. w*h*3).map(|_| 0u8).collect();
try!(file.read(&mut data));
Ok(RasterRGB {
width: w,
data: data,
})
}
}
impl Buffer for RasterRGB {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.data.len() / 3 / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
kernel_log!("buf.rect() = {:?}, self.dims_px() = {:?}", buf.rect(), self.dims_px());
let mut buf_rows = self.data.chunks(self.width*3);
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let val = buf_rows.next().unwrap();
for (d, px) in Iterator::zip( line.iter_mut(), val.chunks(3) )
{
let v = (px[0] as u32) << 16 | (px[1] as u32) << 8 | (px[2] as u32) << 0;
*d = v;
}
});
}
}
/// Raster single-colour image with alpha
pub struct RasterMonoA
{
fg: ::surface::Colour,
width: usize,
alpha: Vec<u8>,
}
impl RasterMonoA
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour) -> Result<Image<Self>,LoadError> {
Self::new(path, fg).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour) -> Result<RasterMonoA,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
use std::io::Read;
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR8M" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
// - Read data (directly)
let mut alpha: Vec<u8> = (0.. w*h).map(|_| 0u8).collect();
try!(file.read(&mut alpha));
Ok(RasterMonoA {
fg: fg,
width: w,
alpha: alpha,
})
}
}
impl Buffer for RasterMonoA {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.alpha.len() / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
let mut buf_rows = self.alpha.chunks(self.width);
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let alpha = buf_rows.next().unwrap();
for (d, a) in Iterator::zip( line.iter_mut(), alpha.iter().cloned() )
{
*d = Colour::blend_alpha( Colour::from_argb32(*d), self.fg, 255 - a ).as_argb32();
}
});
}
}
/// Raster two-colour image with alpha
pub struct RasterBiA
{
bg: ::surface::Colour,
fg: ::surface::Colour,
width: usize,
data: Vec<bool>, // TODO: Use BitVec or similar
alpha: Vec<u8>,
}
impl RasterBiA
{
pub fn new_img<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour, bg: ::surface::Colour) -> Result<Image<Self>,LoadError> {
Self::new(path, fg, bg).map(|b| Image::new(b))
}
pub fn new<P: AsRef<::std::fs::Path>>(path: P, fg: ::surface::Colour, bg: ::surface::Colour) -> Result<RasterBiA,LoadError> {
use ::byteorder::{LittleEndian,ReadBytesExt};
let path = path.as_ref();
let mut file = try!( ::std::fs::File::open(path) );
// - Check magic
if &try!(get_4_bytes(&mut file))!= b"\x7FR8B" {
return Err(LoadError::Malformed);
}
// - Read dimensions
let w = try!( file.read_u16::<LittleEndian>() ) as usize;
let h = try!( file.read_u16::<LittleEndian>() ) as usize;
let mut data = Vec::with_capacity(w * h);
let mut alpha = Vec::with_capacity(w * h);
for _ in 0.. w * h
{
let v = try!( file.read_u8() );
data.push( v >= 128 );
alpha.push( (v & 0x7F) * 2 | ((v >> 6) & 1) );
}
Ok(RasterBiA {
bg: bg,
fg: fg,
width: w,
data: data,
alpha: alpha,
})
}
}
impl Buffer for RasterBiA {
fn dims_px(&self) -> Rect<Px> {
Rect::new(0,0, self.width as u32, (self.data.len() / self.width) as u32)
}
fn render(&self, buf: ::surface::SurfaceView) {
// - Alpha defaults to zero if the alpha vec is empty
let mut buf_rows = Iterator::zip( self.data.chunks(self.width), self.alpha.chunks(self.width).chain(::std::iter::repeat(&[][..])) );
buf.foreach_scanlines(self.dims_px(), |_row, line| {
let (bitmap, alpha) = buf_rows.next().unwrap();
for (d, (bm, a)) in Iterator::zip( line.iter_mut(), Iterator::zip( bitmap.iter(), alpha.iter().cloned().chain(::std::iter::repeat(0)) ) )
{
let c = if *bm { self.fg } else { self.bg };
//kernel_log!("c = {:x}, alpha = {}", c.as_argb32(), a);
*d = Colour::blend_alpha( Colour::from_argb32(*d), c, 255 - a ).as_argb32();
}
});
}
}
| Image | identifier_name |
lib.rs | extern crate gitignore;
extern crate libc;
use std::ffi::CStr;
use std::ffi::CString;
use std::mem;
use std::path::{Path, PathBuf};
use std::string::FromUtf8Error;
#[repr(C)]
pub struct RubyArray {
len: libc::size_t,
data: *const libc::c_void,
}
impl RubyArray {
fn from_vec<T>(vec: Vec<T>) -> RubyArray {
let array = RubyArray {
data: vec.as_ptr() as *const libc::c_void,
len: vec.len() as libc::size_t
};
mem::forget(vec);
array
}
}
#[no_mangle]
pub extern "C" fn | (path_ptr: *const libc::c_char) -> RubyArray {
let path_string = ptr_to_string(path_ptr).unwrap();
let path = Path::new(&*path_string).to_path_buf();
let gitignore_path = path.join(".gitignore");
let file = gitignore::File::new(&gitignore_path).unwrap();
let files = file.included_files().unwrap();
RubyArray::from_vec(paths_to_ptrs(files))
}
fn ptr_to_string(ptr: *const libc::c_char) -> Result<String, FromUtf8Error> {
let cstr = unsafe { CStr::from_ptr(ptr) };
let mut bytes = Vec::new();
bytes.extend(cstr.to_bytes());
String::from_utf8(bytes)
}
fn paths_to_ptrs(paths: Vec<PathBuf>) -> Vec<*const libc::c_char> {
paths.iter().flat_map(|p| p.to_str())
.flat_map(|s| CString::new(s))
.map(|cs| {
let ptr = cs.as_ptr();
mem::forget(cs);
ptr
})
.collect()
}
| included_files | identifier_name |
lib.rs | extern crate gitignore;
extern crate libc;
use std::ffi::CStr;
use std::ffi::CString;
use std::mem;
use std::path::{Path, PathBuf};
use std::string::FromUtf8Error;
#[repr(C)]
pub struct RubyArray {
len: libc::size_t,
data: *const libc::c_void,
}
impl RubyArray {
fn from_vec<T>(vec: Vec<T>) -> RubyArray {
let array = RubyArray {
data: vec.as_ptr() as *const libc::c_void,
len: vec.len() as libc::size_t
};
mem::forget(vec);
array
}
}
#[no_mangle] | let path_string = ptr_to_string(path_ptr).unwrap();
let path = Path::new(&*path_string).to_path_buf();
let gitignore_path = path.join(".gitignore");
let file = gitignore::File::new(&gitignore_path).unwrap();
let files = file.included_files().unwrap();
RubyArray::from_vec(paths_to_ptrs(files))
}
fn ptr_to_string(ptr: *const libc::c_char) -> Result<String, FromUtf8Error> {
let cstr = unsafe { CStr::from_ptr(ptr) };
let mut bytes = Vec::new();
bytes.extend(cstr.to_bytes());
String::from_utf8(bytes)
}
fn paths_to_ptrs(paths: Vec<PathBuf>) -> Vec<*const libc::c_char> {
paths.iter().flat_map(|p| p.to_str())
.flat_map(|s| CString::new(s))
.map(|cs| {
let ptr = cs.as_ptr();
mem::forget(cs);
ptr
})
.collect()
} | pub extern "C" fn included_files(path_ptr: *const libc::c_char) -> RubyArray { | random_line_split |
test_pd_client.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use grpcio::EnvBuilder;
use kvproto::metapb::*;
use pd_client::{PdClient, RegionInfo, RegionStat, RpcClient};
use security::{SecurityConfig, SecurityManager};
use test_pd::{mocker::*, util::*, Server as MockServer};
use tikv_util::config::ReadableDuration;
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
fn new_test_server_and_client(
update_interval: ReadableDuration,
) -> (MockServer<Service>, RpcClient) {
let server = MockServer::new(1);
let eps = server.bind_addrs();
let client = new_client_with_update_interval(eps, None, update_interval);
(server, client)
}
macro_rules! request {
($client: ident => block_on($func: tt($($arg: expr),*))) => {
(stringify!($func), {
let client = $client.clone();
Box::new(move || {
let _ = futures::executor::block_on(client.$func($($arg),*));
})
})
};
($client: ident => $func: tt($($arg: expr),*)) => {
(stringify!($func), {
let client = $client.clone();
Box::new(move || {
let _ = client.$func($($arg),*);
})
})
};
}
#[test]
fn test_pd_client_deadlock() {
let (_server, client) = new_test_server_and_client(ReadableDuration::millis(100));
let client = Arc::new(client);
let pd_client_reconnect_fp = "pd_client_reconnect";
// It contains all interfaces of PdClient.
let test_funcs: Vec<(_, Box<dyn FnOnce() + Send>)> = vec![
request!(client => reconnect()),
request!(client => get_cluster_id()),
request!(client => bootstrap_cluster(Store::default(), Region::default())),
request!(client => is_cluster_bootstrapped()),
request!(client => alloc_id()),
request!(client => put_store(Store::default())),
request!(client => get_store(0)),
request!(client => get_all_stores(false)),
request!(client => get_cluster_config()),
request!(client => get_region(b"")),
request!(client => get_region_info(b"")),
request!(client => block_on(get_region_async(b""))),
request!(client => block_on(get_region_info_async(b""))),
request!(client => block_on(get_region_by_id(0))),
request!(client => block_on(region_heartbeat(0, Region::default(), Peer::default(), RegionStat::default(), None))),
request!(client => block_on(ask_split(Region::default()))),
request!(client => block_on(ask_batch_split(Region::default(), 1))),
request!(client => block_on(store_heartbeat(Default::default()))),
request!(client => block_on(report_batch_split(vec![]))),
request!(client => scatter_region(RegionInfo::new(Region::default(), None))),
request!(client => block_on(get_gc_safe_point())),
request!(client => block_on(get_store_stats_async(0))),
request!(client => get_operator(0)),
request!(client => block_on(get_tso())),
];
for (name, func) in test_funcs {
fail::cfg(pd_client_reconnect_fp, "pause").unwrap();
// Wait for the PD client thread blocking on the fail point.
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
func();
tx.send(()).unwrap();
});
// Only allow to reconnect once for a func.
client.handle_reconnect(move || {
fail::cfg(pd_client_reconnect_fp, "return").unwrap();
});
// Remove the fail point to let the PD client thread go on.
fail::remove(pd_client_reconnect_fp);
let timeout = Duration::from_millis(500);
if rx.recv_timeout(timeout).is_err() {
panic!("PdClient::{}() hangs", name);
}
handle.join().unwrap();
}
drop(client);
fail::remove(pd_client_reconnect_fp);
}
// Updating pd leader may be slow, we need to make sure it does not block other
// RPC in the same gRPC Environment.
#[test]
fn test_slow_periodical_update() {
let pd_client_reconnect_fp = "pd_client_reconnect";
let server = MockServer::new(1);
let eps = server.bind_addrs();
let mut cfg = new_config(eps);
let env = Arc::new(EnvBuilder::new().cq_count(1).build());
let mgr = Arc::new(SecurityManager::new(&SecurityConfig::default()).unwrap());
// client1 updates leader frequently (100ms).
cfg.update_interval = ReadableDuration(Duration::from_millis(100));
let _client1 = RpcClient::new(&cfg, Some(env.clone()), mgr.clone()).unwrap();
// client2 never updates leader in the test.
cfg.update_interval = ReadableDuration(Duration::from_secs(100));
let client2 = RpcClient::new(&cfg, Some(env), mgr).unwrap();
fail::cfg(pd_client_reconnect_fp, "pause").unwrap();
// Wait for the PD client thread blocking on the fail point.
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
client2.alloc_id().unwrap();
tx.send(()).unwrap();
});
let timeout = Duration::from_millis(500);
if rx.recv_timeout(timeout).is_err() |
// Clean up the fail point.
fail::remove(pd_client_reconnect_fp);
handle.join().unwrap();
}
// Reconnection will be speed limited.
#[test]
fn test_reconnect_limit() {
let pd_client_reconnect_fp = "pd_client_reconnect";
let (_server, client) = new_test_server_and_client(ReadableDuration::secs(100));
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
// The first reconnection will succeed, and the last_update will not be updated.
fail::cfg(pd_client_reconnect_fp, "return").unwrap();
client.reconnect().unwrap();
// The subsequent reconnection will be cancelled.
for _ in 0..10 {
let ret = client.reconnect();
assert!(format!("{:?}", ret.unwrap_err()).contains("cancel reconnection"));
}
fail::remove(pd_client_reconnect_fp);
}
| {
panic!("pd client2 is blocked");
} | conditional_block |
test_pd_client.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use grpcio::EnvBuilder;
use kvproto::metapb::*;
use pd_client::{PdClient, RegionInfo, RegionStat, RpcClient};
use security::{SecurityConfig, SecurityManager};
use test_pd::{mocker::*, util::*, Server as MockServer};
use tikv_util::config::ReadableDuration;
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
fn new_test_server_and_client(
update_interval: ReadableDuration,
) -> (MockServer<Service>, RpcClient) {
let server = MockServer::new(1);
let eps = server.bind_addrs();
let client = new_client_with_update_interval(eps, None, update_interval);
(server, client)
}
macro_rules! request {
($client: ident => block_on($func: tt($($arg: expr),*))) => {
(stringify!($func), {
let client = $client.clone();
Box::new(move || {
let _ = futures::executor::block_on(client.$func($($arg),*));
})
})
};
($client: ident => $func: tt($($arg: expr),*)) => {
(stringify!($func), {
let client = $client.clone();
Box::new(move || {
let _ = client.$func($($arg),*);
})
})
};
}
#[test]
fn test_pd_client_deadlock() | request!(client => block_on(get_region_by_id(0))),
request!(client => block_on(region_heartbeat(0, Region::default(), Peer::default(), RegionStat::default(), None))),
request!(client => block_on(ask_split(Region::default()))),
request!(client => block_on(ask_batch_split(Region::default(), 1))),
request!(client => block_on(store_heartbeat(Default::default()))),
request!(client => block_on(report_batch_split(vec![]))),
request!(client => scatter_region(RegionInfo::new(Region::default(), None))),
request!(client => block_on(get_gc_safe_point())),
request!(client => block_on(get_store_stats_async(0))),
request!(client => get_operator(0)),
request!(client => block_on(get_tso())),
];
for (name, func) in test_funcs {
fail::cfg(pd_client_reconnect_fp, "pause").unwrap();
// Wait for the PD client thread blocking on the fail point.
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
func();
tx.send(()).unwrap();
});
// Only allow to reconnect once for a func.
client.handle_reconnect(move || {
fail::cfg(pd_client_reconnect_fp, "return").unwrap();
});
// Remove the fail point to let the PD client thread go on.
fail::remove(pd_client_reconnect_fp);
let timeout = Duration::from_millis(500);
if rx.recv_timeout(timeout).is_err() {
panic!("PdClient::{}() hangs", name);
}
handle.join().unwrap();
}
drop(client);
fail::remove(pd_client_reconnect_fp);
}
// Updating pd leader may be slow, we need to make sure it does not block other
// RPC in the same gRPC Environment.
#[test]
fn test_slow_periodical_update() {
let pd_client_reconnect_fp = "pd_client_reconnect";
let server = MockServer::new(1);
let eps = server.bind_addrs();
let mut cfg = new_config(eps);
let env = Arc::new(EnvBuilder::new().cq_count(1).build());
let mgr = Arc::new(SecurityManager::new(&SecurityConfig::default()).unwrap());
// client1 updates leader frequently (100ms).
cfg.update_interval = ReadableDuration(Duration::from_millis(100));
let _client1 = RpcClient::new(&cfg, Some(env.clone()), mgr.clone()).unwrap();
// client2 never updates leader in the test.
cfg.update_interval = ReadableDuration(Duration::from_secs(100));
let client2 = RpcClient::new(&cfg, Some(env), mgr).unwrap();
fail::cfg(pd_client_reconnect_fp, "pause").unwrap();
// Wait for the PD client thread blocking on the fail point.
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
client2.alloc_id().unwrap();
tx.send(()).unwrap();
});
let timeout = Duration::from_millis(500);
if rx.recv_timeout(timeout).is_err() {
panic!("pd client2 is blocked");
}
// Clean up the fail point.
fail::remove(pd_client_reconnect_fp);
handle.join().unwrap();
}
// Reconnection will be speed limited.
#[test]
fn test_reconnect_limit() {
let pd_client_reconnect_fp = "pd_client_reconnect";
let (_server, client) = new_test_server_and_client(ReadableDuration::secs(100));
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
// The first reconnection will succeed, and the last_update will not be updated.
fail::cfg(pd_client_reconnect_fp, "return").unwrap();
client.reconnect().unwrap();
// The subsequent reconnection will be cancelled.
for _ in 0..10 {
let ret = client.reconnect();
assert!(format!("{:?}", ret.unwrap_err()).contains("cancel reconnection"));
}
fail::remove(pd_client_reconnect_fp);
}
| {
let (_server, client) = new_test_server_and_client(ReadableDuration::millis(100));
let client = Arc::new(client);
let pd_client_reconnect_fp = "pd_client_reconnect";
// It contains all interfaces of PdClient.
let test_funcs: Vec<(_, Box<dyn FnOnce() + Send>)> = vec![
request!(client => reconnect()),
request!(client => get_cluster_id()),
request!(client => bootstrap_cluster(Store::default(), Region::default())),
request!(client => is_cluster_bootstrapped()),
request!(client => alloc_id()),
request!(client => put_store(Store::default())),
request!(client => get_store(0)),
request!(client => get_all_stores(false)),
request!(client => get_cluster_config()),
request!(client => get_region(b"")),
request!(client => get_region_info(b"")),
request!(client => block_on(get_region_async(b""))),
request!(client => block_on(get_region_info_async(b""))), | identifier_body |
test_pd_client.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use grpcio::EnvBuilder;
use kvproto::metapb::*;
use pd_client::{PdClient, RegionInfo, RegionStat, RpcClient};
use security::{SecurityConfig, SecurityManager};
use test_pd::{mocker::*, util::*, Server as MockServer};
use tikv_util::config::ReadableDuration;
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
fn new_test_server_and_client(
update_interval: ReadableDuration,
) -> (MockServer<Service>, RpcClient) {
let server = MockServer::new(1);
let eps = server.bind_addrs();
let client = new_client_with_update_interval(eps, None, update_interval);
(server, client)
}
macro_rules! request {
($client: ident => block_on($func: tt($($arg: expr),*))) => {
(stringify!($func), {
let client = $client.clone();
Box::new(move || {
let _ = futures::executor::block_on(client.$func($($arg),*));
})
})
};
($client: ident => $func: tt($($arg: expr),*)) => {
(stringify!($func), {
let client = $client.clone();
Box::new(move || {
let _ = client.$func($($arg),*);
})
})
};
}
#[test]
fn test_pd_client_deadlock() {
let (_server, client) = new_test_server_and_client(ReadableDuration::millis(100));
let client = Arc::new(client);
let pd_client_reconnect_fp = "pd_client_reconnect";
// It contains all interfaces of PdClient.
let test_funcs: Vec<(_, Box<dyn FnOnce() + Send>)> = vec![
request!(client => reconnect()),
request!(client => get_cluster_id()),
request!(client => bootstrap_cluster(Store::default(), Region::default())),
request!(client => is_cluster_bootstrapped()),
request!(client => alloc_id()),
request!(client => put_store(Store::default())),
request!(client => get_store(0)),
request!(client => get_all_stores(false)),
request!(client => get_cluster_config()),
request!(client => get_region(b"")),
request!(client => get_region_info(b"")),
request!(client => block_on(get_region_async(b""))),
request!(client => block_on(get_region_info_async(b""))),
request!(client => block_on(get_region_by_id(0))),
request!(client => block_on(region_heartbeat(0, Region::default(), Peer::default(), RegionStat::default(), None))),
request!(client => block_on(ask_split(Region::default()))),
request!(client => block_on(ask_batch_split(Region::default(), 1))),
request!(client => block_on(store_heartbeat(Default::default()))),
request!(client => block_on(report_batch_split(vec![]))),
request!(client => scatter_region(RegionInfo::new(Region::default(), None))),
request!(client => block_on(get_gc_safe_point())),
request!(client => block_on(get_store_stats_async(0))),
request!(client => get_operator(0)),
request!(client => block_on(get_tso())),
];
for (name, func) in test_funcs {
fail::cfg(pd_client_reconnect_fp, "pause").unwrap();
// Wait for the PD client thread blocking on the fail point.
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
func();
tx.send(()).unwrap();
});
// Only allow to reconnect once for a func.
client.handle_reconnect(move || {
fail::cfg(pd_client_reconnect_fp, "return").unwrap();
});
// Remove the fail point to let the PD client thread go on.
fail::remove(pd_client_reconnect_fp);
let timeout = Duration::from_millis(500);
if rx.recv_timeout(timeout).is_err() {
panic!("PdClient::{}() hangs", name);
}
handle.join().unwrap();
}
drop(client);
fail::remove(pd_client_reconnect_fp);
}
// Updating pd leader may be slow, we need to make sure it does not block other
// RPC in the same gRPC Environment.
#[test]
fn test_slow_periodical_update() {
let pd_client_reconnect_fp = "pd_client_reconnect";
let server = MockServer::new(1);
let eps = server.bind_addrs();
let mut cfg = new_config(eps);
let env = Arc::new(EnvBuilder::new().cq_count(1).build());
let mgr = Arc::new(SecurityManager::new(&SecurityConfig::default()).unwrap());
// client1 updates leader frequently (100ms).
cfg.update_interval = ReadableDuration(Duration::from_millis(100));
let _client1 = RpcClient::new(&cfg, Some(env.clone()), mgr.clone()).unwrap();
// client2 never updates leader in the test.
cfg.update_interval = ReadableDuration(Duration::from_secs(100));
let client2 = RpcClient::new(&cfg, Some(env), mgr).unwrap();
fail::cfg(pd_client_reconnect_fp, "pause").unwrap();
// Wait for the PD client thread blocking on the fail point.
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
client2.alloc_id().unwrap();
tx.send(()).unwrap();
});
let timeout = Duration::from_millis(500);
if rx.recv_timeout(timeout).is_err() {
panic!("pd client2 is blocked");
}
// Clean up the fail point.
fail::remove(pd_client_reconnect_fp);
handle.join().unwrap();
}
// Reconnection will be speed limited.
#[test]
fn | () {
let pd_client_reconnect_fp = "pd_client_reconnect";
let (_server, client) = new_test_server_and_client(ReadableDuration::secs(100));
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
// The first reconnection will succeed, and the last_update will not be updated.
fail::cfg(pd_client_reconnect_fp, "return").unwrap();
client.reconnect().unwrap();
// The subsequent reconnection will be cancelled.
for _ in 0..10 {
let ret = client.reconnect();
assert!(format!("{:?}", ret.unwrap_err()).contains("cancel reconnection"));
}
fail::remove(pd_client_reconnect_fp);
}
| test_reconnect_limit | identifier_name |
test_pd_client.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use grpcio::EnvBuilder;
use kvproto::metapb::*; | use test_pd::{mocker::*, util::*, Server as MockServer};
use tikv_util::config::ReadableDuration;
use std::sync::{mpsc, Arc};
use std::thread;
use std::time::Duration;
fn new_test_server_and_client(
update_interval: ReadableDuration,
) -> (MockServer<Service>, RpcClient) {
let server = MockServer::new(1);
let eps = server.bind_addrs();
let client = new_client_with_update_interval(eps, None, update_interval);
(server, client)
}
macro_rules! request {
($client: ident => block_on($func: tt($($arg: expr),*))) => {
(stringify!($func), {
let client = $client.clone();
Box::new(move || {
let _ = futures::executor::block_on(client.$func($($arg),*));
})
})
};
($client: ident => $func: tt($($arg: expr),*)) => {
(stringify!($func), {
let client = $client.clone();
Box::new(move || {
let _ = client.$func($($arg),*);
})
})
};
}
#[test]
fn test_pd_client_deadlock() {
let (_server, client) = new_test_server_and_client(ReadableDuration::millis(100));
let client = Arc::new(client);
let pd_client_reconnect_fp = "pd_client_reconnect";
// It contains all interfaces of PdClient.
let test_funcs: Vec<(_, Box<dyn FnOnce() + Send>)> = vec![
request!(client => reconnect()),
request!(client => get_cluster_id()),
request!(client => bootstrap_cluster(Store::default(), Region::default())),
request!(client => is_cluster_bootstrapped()),
request!(client => alloc_id()),
request!(client => put_store(Store::default())),
request!(client => get_store(0)),
request!(client => get_all_stores(false)),
request!(client => get_cluster_config()),
request!(client => get_region(b"")),
request!(client => get_region_info(b"")),
request!(client => block_on(get_region_async(b""))),
request!(client => block_on(get_region_info_async(b""))),
request!(client => block_on(get_region_by_id(0))),
request!(client => block_on(region_heartbeat(0, Region::default(), Peer::default(), RegionStat::default(), None))),
request!(client => block_on(ask_split(Region::default()))),
request!(client => block_on(ask_batch_split(Region::default(), 1))),
request!(client => block_on(store_heartbeat(Default::default()))),
request!(client => block_on(report_batch_split(vec![]))),
request!(client => scatter_region(RegionInfo::new(Region::default(), None))),
request!(client => block_on(get_gc_safe_point())),
request!(client => block_on(get_store_stats_async(0))),
request!(client => get_operator(0)),
request!(client => block_on(get_tso())),
];
for (name, func) in test_funcs {
fail::cfg(pd_client_reconnect_fp, "pause").unwrap();
// Wait for the PD client thread blocking on the fail point.
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
func();
tx.send(()).unwrap();
});
// Only allow to reconnect once for a func.
client.handle_reconnect(move || {
fail::cfg(pd_client_reconnect_fp, "return").unwrap();
});
// Remove the fail point to let the PD client thread go on.
fail::remove(pd_client_reconnect_fp);
let timeout = Duration::from_millis(500);
if rx.recv_timeout(timeout).is_err() {
panic!("PdClient::{}() hangs", name);
}
handle.join().unwrap();
}
drop(client);
fail::remove(pd_client_reconnect_fp);
}
// Updating pd leader may be slow, we need to make sure it does not block other
// RPC in the same gRPC Environment.
#[test]
fn test_slow_periodical_update() {
let pd_client_reconnect_fp = "pd_client_reconnect";
let server = MockServer::new(1);
let eps = server.bind_addrs();
let mut cfg = new_config(eps);
let env = Arc::new(EnvBuilder::new().cq_count(1).build());
let mgr = Arc::new(SecurityManager::new(&SecurityConfig::default()).unwrap());
// client1 updates leader frequently (100ms).
cfg.update_interval = ReadableDuration(Duration::from_millis(100));
let _client1 = RpcClient::new(&cfg, Some(env.clone()), mgr.clone()).unwrap();
// client2 never updates leader in the test.
cfg.update_interval = ReadableDuration(Duration::from_secs(100));
let client2 = RpcClient::new(&cfg, Some(env), mgr).unwrap();
fail::cfg(pd_client_reconnect_fp, "pause").unwrap();
// Wait for the PD client thread blocking on the fail point.
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
let (tx, rx) = mpsc::channel();
let handle = thread::spawn(move || {
client2.alloc_id().unwrap();
tx.send(()).unwrap();
});
let timeout = Duration::from_millis(500);
if rx.recv_timeout(timeout).is_err() {
panic!("pd client2 is blocked");
}
// Clean up the fail point.
fail::remove(pd_client_reconnect_fp);
handle.join().unwrap();
}
// Reconnection will be speed limited.
#[test]
fn test_reconnect_limit() {
let pd_client_reconnect_fp = "pd_client_reconnect";
let (_server, client) = new_test_server_and_client(ReadableDuration::secs(100));
// The GLOBAL_RECONNECT_INTERVAL is 0.1s so sleeps 0.2s here.
thread::sleep(Duration::from_millis(200));
// The first reconnection will succeed, and the last_update will not be updated.
fail::cfg(pd_client_reconnect_fp, "return").unwrap();
client.reconnect().unwrap();
// The subsequent reconnection will be cancelled.
for _ in 0..10 {
let ret = client.reconnect();
assert!(format!("{:?}", ret.unwrap_err()).contains("cancel reconnection"));
}
fail::remove(pd_client_reconnect_fp);
} | use pd_client::{PdClient, RegionInfo, RegionStat, RpcClient};
use security::{SecurityConfig, SecurityManager}; | random_line_split |
depart.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::thread;
use std::time;
use butterfly::client::Client; | use hcore::crypto::SymKey;
use error::{Error, Result};
pub fn run(
ui: &mut UI,
member_id: &str,
peers: Vec<String>,
ring_key: Option<SymKey>,
) -> Result<()> {
ui.begin(
format!("Permanently marking {} as departed", member_id),
)?;
ui.status(
Status::Creating,
format!("service configuration"),
)?;
for peer in peers.into_iter() {
ui.status(Status::Applying, format!("to peer {}", peer))?;
let mut client = Client::new(peer, ring_key.clone()).map_err(|e| {
Error::ButterflyError(e.to_string())
})?;
client.send_departure(member_id).map_err(|e| {
Error::ButterflyError(e.to_string())
})?;
// please take a moment to weep over the following line
// of code. We must sleep to allow messages to be sent
// before freeing the socket to prevent loss.
// see https://github.com/zeromq/libzmq/issues/1264
thread::sleep(time::Duration::from_millis(100));
}
ui.end("Departure recorded.")?;
Ok(())
} | use common::ui::{Status, UI}; | random_line_split |
depart.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::thread;
use std::time;
use butterfly::client::Client;
use common::ui::{Status, UI};
use hcore::crypto::SymKey;
use error::{Error, Result};
pub fn | (
ui: &mut UI,
member_id: &str,
peers: Vec<String>,
ring_key: Option<SymKey>,
) -> Result<()> {
ui.begin(
format!("Permanently marking {} as departed", member_id),
)?;
ui.status(
Status::Creating,
format!("service configuration"),
)?;
for peer in peers.into_iter() {
ui.status(Status::Applying, format!("to peer {}", peer))?;
let mut client = Client::new(peer, ring_key.clone()).map_err(|e| {
Error::ButterflyError(e.to_string())
})?;
client.send_departure(member_id).map_err(|e| {
Error::ButterflyError(e.to_string())
})?;
// please take a moment to weep over the following line
// of code. We must sleep to allow messages to be sent
// before freeing the socket to prevent loss.
// see https://github.com/zeromq/libzmq/issues/1264
thread::sleep(time::Duration::from_millis(100));
}
ui.end("Departure recorded.")?;
Ok(())
}
| run | identifier_name |
depart.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::thread;
use std::time;
use butterfly::client::Client;
use common::ui::{Status, UI};
use hcore::crypto::SymKey;
use error::{Error, Result};
pub fn run(
ui: &mut UI,
member_id: &str,
peers: Vec<String>,
ring_key: Option<SymKey>,
) -> Result<()> | thread::sleep(time::Duration::from_millis(100));
}
ui.end("Departure recorded.")?;
Ok(())
}
| {
ui.begin(
format!("Permanently marking {} as departed", member_id),
)?;
ui.status(
Status::Creating,
format!("service configuration"),
)?;
for peer in peers.into_iter() {
ui.status(Status::Applying, format!("to peer {}", peer))?;
let mut client = Client::new(peer, ring_key.clone()).map_err(|e| {
Error::ButterflyError(e.to_string())
})?;
client.send_departure(member_id).map_err(|e| {
Error::ButterflyError(e.to_string())
})?;
// please take a moment to weep over the following line
// of code. We must sleep to allow messages to be sent
// before freeing the socket to prevent loss.
// see https://github.com/zeromq/libzmq/issues/1264 | identifier_body |
sequence.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/.
*/
//! Utilities for paquet sequencing
use std::cmp::*;
use std::iter::Step;
use std::num::{Zero, One};
#[derive(Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
pub struct Sequence<I>(I);
impl<I: Clone + Step + Zero + One> Sequence<I> {
/// use `let seq : Sequence = Default::default()` if no start value
pub fn new(start: I) -> Sequence<I> {
Sequence(start)
}
pub fn step(&mut self) -> I { | Some(val) => self.0 = val,
None => self.0 = I::zero()
};
self.0.clone()
}
pub fn stepu(&mut self) { let _ = self.step(); }
}
#[test]
fn test_step_incr() {
let mut seq = Sequence::new(0 as u8);
assert_eq!(0, seq.0);
seq.step();
assert_eq!(1, seq.0);
seq.step();
assert_eq!(2, seq.0);
seq.step();
assert_eq!(3, seq.0);
seq.step();
assert_eq!(4, seq.0)
}
#[test]
fn test_step_cycle() {
use std::u8;
let mut seq = Sequence::new(0 as u8);
for _ in 0..(u8::MAX as u16 + 1) { seq.stepu() }
assert_eq!(0, seq.0);
seq.step();
for _ in 0..(u8::MAX as u16 + 1) { seq.stepu() }
assert_eq!(1, seq.0)
} | match self.0.step(&I::one()) { | random_line_split |
sequence.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/.
*/
//! Utilities for paquet sequencing
use std::cmp::*;
use std::iter::Step;
use std::num::{Zero, One};
#[derive(Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
pub struct Sequence<I>(I);
impl<I: Clone + Step + Zero + One> Sequence<I> {
/// use `let seq : Sequence = Default::default()` if no start value
pub fn new(start: I) -> Sequence<I> {
Sequence(start)
}
pub fn | (&mut self) -> I {
match self.0.step(&I::one()) {
Some(val) => self.0 = val,
None => self.0 = I::zero()
};
self.0.clone()
}
pub fn stepu(&mut self) { let _ = self.step(); }
}
#[test]
fn test_step_incr() {
let mut seq = Sequence::new(0 as u8);
assert_eq!(0, seq.0);
seq.step();
assert_eq!(1, seq.0);
seq.step();
assert_eq!(2, seq.0);
seq.step();
assert_eq!(3, seq.0);
seq.step();
assert_eq!(4, seq.0)
}
#[test]
fn test_step_cycle() {
use std::u8;
let mut seq = Sequence::new(0 as u8);
for _ in 0..(u8::MAX as u16 + 1) { seq.stepu() }
assert_eq!(0, seq.0);
seq.step();
for _ in 0..(u8::MAX as u16 + 1) { seq.stepu() }
assert_eq!(1, seq.0)
}
| step | identifier_name |
sequence.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/.
*/
//! Utilities for paquet sequencing
use std::cmp::*;
use std::iter::Step;
use std::num::{Zero, One};
#[derive(Clone, Debug, Default, PartialEq, PartialOrd, Eq, Ord)]
pub struct Sequence<I>(I);
impl<I: Clone + Step + Zero + One> Sequence<I> {
/// use `let seq : Sequence = Default::default()` if no start value
pub fn new(start: I) -> Sequence<I> {
Sequence(start)
}
pub fn step(&mut self) -> I {
match self.0.step(&I::one()) {
Some(val) => self.0 = val,
None => self.0 = I::zero()
};
self.0.clone()
}
pub fn stepu(&mut self) |
}
#[test]
fn test_step_incr() {
let mut seq = Sequence::new(0 as u8);
assert_eq!(0, seq.0);
seq.step();
assert_eq!(1, seq.0);
seq.step();
assert_eq!(2, seq.0);
seq.step();
assert_eq!(3, seq.0);
seq.step();
assert_eq!(4, seq.0)
}
#[test]
fn test_step_cycle() {
use std::u8;
let mut seq = Sequence::new(0 as u8);
for _ in 0..(u8::MAX as u16 + 1) { seq.stepu() }
assert_eq!(0, seq.0);
seq.step();
for _ in 0..(u8::MAX as u16 + 1) { seq.stepu() }
assert_eq!(1, seq.0)
}
| { let _ = self.step(); } | identifier_body |
problem-005.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// 2520 is the smallest number that can be divided by each of the numbers
// from 1 to 10 without any remainder.
//
// What is the smallest positive number that is evenly divisible by all of
// the numbers from 1 to 20?
#![feature(test)]
extern crate test;
pub fn solution() -> u32 {
// Any number divisible by 11-20 is also divisible by 2-10
const FACTORS: [u32; 10] = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11];
let mut n = 20;
let mut all_divisible = false;
// This might take a while; 20! is pretty big...
while!all_divisible {
n += 20;
all_divisible = true;
for f in FACTORS.iter() {
if n % f!= 0 {
all_divisible = false;
break;
}
}
}
return n; | }
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
assert_eq!(232792560, solution());
}
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
} | }
fn main() {
println!("The smallest positive integer divisible by all of [1,20] is {}", solution()); | random_line_split |
problem-005.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// 2520 is the smallest number that can be divided by each of the numbers
// from 1 to 10 without any remainder.
//
// What is the smallest positive number that is evenly divisible by all of
// the numbers from 1 to 20?
#![feature(test)]
extern crate test;
pub fn solution() -> u32 {
// Any number divisible by 11-20 is also divisible by 2-10
const FACTORS: [u32; 10] = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11];
let mut n = 20;
let mut all_divisible = false;
// This might take a while; 20! is pretty big...
while!all_divisible {
n += 20;
all_divisible = true;
for f in FACTORS.iter() {
if n % f!= 0 {
all_divisible = false;
break;
}
}
}
return n;
}
fn main() {
println!("The smallest positive integer divisible by all of [1,20] is {}", solution());
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn | () {
assert_eq!(232792560, solution());
}
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
}
| correct | identifier_name |
problem-005.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// 2520 is the smallest number that can be divided by each of the numbers
// from 1 to 10 without any remainder.
//
// What is the smallest positive number that is evenly divisible by all of
// the numbers from 1 to 20?
#![feature(test)]
extern crate test;
pub fn solution() -> u32 {
// Any number divisible by 11-20 is also divisible by 2-10
const FACTORS: [u32; 10] = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11];
let mut n = 20;
let mut all_divisible = false;
// This might take a while; 20! is pretty big...
while!all_divisible {
n += 20;
all_divisible = true;
for f in FACTORS.iter() {
if n % f!= 0 |
}
}
return n;
}
fn main() {
println!("The smallest positive integer divisible by all of [1,20] is {}", solution());
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() {
assert_eq!(232792560, solution());
}
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
}
| {
all_divisible = false;
break;
} | conditional_block |
problem-005.rs | // Copyright 2016 Peter Beard
// Distributed under the GNU GPL v2. For full terms, see the LICENSE file.
//
// 2520 is the smallest number that can be divided by each of the numbers
// from 1 to 10 without any remainder.
//
// What is the smallest positive number that is evenly divisible by all of
// the numbers from 1 to 20?
#![feature(test)]
extern crate test;
pub fn solution() -> u32 {
// Any number divisible by 11-20 is also divisible by 2-10
const FACTORS: [u32; 10] = [20, 19, 18, 17, 16, 15, 14, 13, 12, 11];
let mut n = 20;
let mut all_divisible = false;
// This might take a while; 20! is pretty big...
while!all_divisible {
n += 20;
all_divisible = true;
for f in FACTORS.iter() {
if n % f!= 0 {
all_divisible = false;
break;
}
}
}
return n;
}
fn main() {
println!("The smallest positive integer divisible by all of [1,20] is {}", solution());
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
#[test]
fn correct() |
#[bench]
fn bench(b: &mut Bencher) {
b.iter(|| solution());
}
}
| {
assert_eq!(232792560, solution());
} | identifier_body |
list.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${helpers.single_keyword("list-style-position", "outside inside", animatable=False)}
// TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1:
//
// decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman,
// upper-roman
//
// TODO(bholley): Missing quite a few gecko properties here as well.
// | gujarati gurmukhi kannada khmer lao malayalam mongolian
myanmar oriya persian telugu thai tibetan cjk-earthly-branch
cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana
katakana-iroha""",
gecko_constant_prefix="NS_STYLE_LIST_STYLE",
animatable=False)}
<%helpers:longhand name="list-style-image" animatable="False">
use cssparser::{ToCss, Token};
use std::fmt;
use url::Url;
use values::LocalToCss;
use values::NoViewportPercentage;
impl NoViewportPercentage for SpecifiedValue {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum SpecifiedValue {
None,
Url(Url),
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
SpecifiedValue::None => dest.write_str("none"),
SpecifiedValue::Url(ref url) => url.to_css(dest),
}
}
}
pub mod computed_value {
use cssparser::{ToCss, Token};
use std::fmt;
use url::Url;
use values::LocalToCss;
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Option<Url>);
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match self.0 {
None => dest.write_str("none"),
Some(ref url) => url.to_css(dest),
}
}
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, _context: &Context) -> computed_value::T {
match *self {
SpecifiedValue::None => computed_value::T(None),
SpecifiedValue::Url(ref url) => computed_value::T(Some(url.clone())),
}
}
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
Ok(SpecifiedValue::None)
} else {
Ok(SpecifiedValue::Url(context.parse_url(&*try!(input.expect_url()))))
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(None)
}
</%helpers:longhand>
<%helpers:longhand name="quotes" products="servo" animatable="False">
use std::borrow::Cow;
use std::fmt;
use values::NoViewportPercentage;
use values::computed::ComputedValueAsSpecified;
use cssparser::{ToCss, Token};
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Vec<(String,String)>);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
impl NoViewportPercentage for SpecifiedValue {}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut first = true;
for pair in &self.0 {
if!first {
try!(dest.write_str(" "));
}
first = false;
try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest));
try!(dest.write_str(" "));
try!(Token::QuotedString(Cow::from(&*pair.1)).to_css(dest));
}
Ok(())
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(vec![
("\u{201c}".to_owned(), "\u{201d}".to_owned()),
("\u{2018}".to_owned(), "\u{2019}".to_owned()),
])
}
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue(Vec::new()))
}
let mut quotes = Vec::new();
loop {
let first = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
Ok(_) => return Err(()),
Err(()) => break,
};
let second = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
_ => return Err(()),
};
quotes.push((first, second))
}
if!quotes.is_empty() {
Ok(SpecifiedValue(quotes))
} else {
Err(())
}
}
</%helpers:longhand> | // [1]: http://dev.w3.org/csswg/css-counter-styles/
${helpers.single_keyword("list-style-type", """
disc none circle square decimal lower-alpha upper-alpha disclosure-open disclosure-closed
""", extra_servo_values="""arabic-indic bengali cambodian cjk-decimal devanagari | random_line_split |
list.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${helpers.single_keyword("list-style-position", "outside inside", animatable=False)}
// TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1:
//
// decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman,
// upper-roman
//
// TODO(bholley): Missing quite a few gecko properties here as well.
//
// [1]: http://dev.w3.org/csswg/css-counter-styles/
${helpers.single_keyword("list-style-type", """
disc none circle square decimal lower-alpha upper-alpha disclosure-open disclosure-closed
""", extra_servo_values="""arabic-indic bengali cambodian cjk-decimal devanagari
gujarati gurmukhi kannada khmer lao malayalam mongolian
myanmar oriya persian telugu thai tibetan cjk-earthly-branch
cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana
katakana-iroha""",
gecko_constant_prefix="NS_STYLE_LIST_STYLE",
animatable=False)}
<%helpers:longhand name="list-style-image" animatable="False">
use cssparser::{ToCss, Token};
use std::fmt;
use url::Url;
use values::LocalToCss;
use values::NoViewportPercentage;
impl NoViewportPercentage for SpecifiedValue {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum | {
None,
Url(Url),
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
SpecifiedValue::None => dest.write_str("none"),
SpecifiedValue::Url(ref url) => url.to_css(dest),
}
}
}
pub mod computed_value {
use cssparser::{ToCss, Token};
use std::fmt;
use url::Url;
use values::LocalToCss;
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Option<Url>);
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match self.0 {
None => dest.write_str("none"),
Some(ref url) => url.to_css(dest),
}
}
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, _context: &Context) -> computed_value::T {
match *self {
SpecifiedValue::None => computed_value::T(None),
SpecifiedValue::Url(ref url) => computed_value::T(Some(url.clone())),
}
}
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
Ok(SpecifiedValue::None)
} else {
Ok(SpecifiedValue::Url(context.parse_url(&*try!(input.expect_url()))))
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(None)
}
</%helpers:longhand>
<%helpers:longhand name="quotes" products="servo" animatable="False">
use std::borrow::Cow;
use std::fmt;
use values::NoViewportPercentage;
use values::computed::ComputedValueAsSpecified;
use cssparser::{ToCss, Token};
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Vec<(String,String)>);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
impl NoViewportPercentage for SpecifiedValue {}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut first = true;
for pair in &self.0 {
if!first {
try!(dest.write_str(" "));
}
first = false;
try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest));
try!(dest.write_str(" "));
try!(Token::QuotedString(Cow::from(&*pair.1)).to_css(dest));
}
Ok(())
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(vec![
("\u{201c}".to_owned(), "\u{201d}".to_owned()),
("\u{2018}".to_owned(), "\u{2019}".to_owned()),
])
}
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue(Vec::new()))
}
let mut quotes = Vec::new();
loop {
let first = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
Ok(_) => return Err(()),
Err(()) => break,
};
let second = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
_ => return Err(()),
};
quotes.push((first, second))
}
if!quotes.is_empty() {
Ok(SpecifiedValue(quotes))
} else {
Err(())
}
}
</%helpers:longhand>
| SpecifiedValue | identifier_name |
list.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% data.new_style_struct("List", inherited=True) %>
${helpers.single_keyword("list-style-position", "outside inside", animatable=False)}
// TODO(pcwalton): Implement the full set of counter styles per CSS-COUNTER-STYLES [1] 6.1:
//
// decimal-leading-zero, armenian, upper-armenian, lower-armenian, georgian, lower-roman,
// upper-roman
//
// TODO(bholley): Missing quite a few gecko properties here as well.
//
// [1]: http://dev.w3.org/csswg/css-counter-styles/
${helpers.single_keyword("list-style-type", """
disc none circle square decimal lower-alpha upper-alpha disclosure-open disclosure-closed
""", extra_servo_values="""arabic-indic bengali cambodian cjk-decimal devanagari
gujarati gurmukhi kannada khmer lao malayalam mongolian
myanmar oriya persian telugu thai tibetan cjk-earthly-branch
cjk-heavenly-stem lower-greek hiragana hiragana-iroha katakana
katakana-iroha""",
gecko_constant_prefix="NS_STYLE_LIST_STYLE",
animatable=False)}
<%helpers:longhand name="list-style-image" animatable="False">
use cssparser::{ToCss, Token};
use std::fmt;
use url::Url;
use values::LocalToCss;
use values::NoViewportPercentage;
impl NoViewportPercentage for SpecifiedValue {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub enum SpecifiedValue {
None,
Url(Url),
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match *self {
SpecifiedValue::None => dest.write_str("none"),
SpecifiedValue::Url(ref url) => url.to_css(dest),
}
}
}
pub mod computed_value {
use cssparser::{ToCss, Token};
use std::fmt;
use url::Url;
use values::LocalToCss;
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Option<Url>);
impl ToCss for T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
match self.0 {
None => dest.write_str("none"),
Some(ref url) => url.to_css(dest),
}
}
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, _context: &Context) -> computed_value::T {
match *self {
SpecifiedValue::None => computed_value::T(None),
SpecifiedValue::Url(ref url) => computed_value::T(Some(url.clone())),
}
}
}
pub fn parse(context: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue, ()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
Ok(SpecifiedValue::None)
} else {
Ok(SpecifiedValue::Url(context.parse_url(&*try!(input.expect_url()))))
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(None)
}
</%helpers:longhand>
<%helpers:longhand name="quotes" products="servo" animatable="False">
use std::borrow::Cow;
use std::fmt;
use values::NoViewportPercentage;
use values::computed::ComputedValueAsSpecified;
use cssparser::{ToCss, Token};
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
pub struct T(pub Vec<(String,String)>);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
impl NoViewportPercentage for SpecifiedValue {}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write |
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(vec![
("\u{201c}".to_owned(), "\u{201d}".to_owned()),
("\u{2018}".to_owned(), "\u{2019}".to_owned()),
])
}
pub fn parse(_: &ParserContext, input: &mut Parser) -> Result<SpecifiedValue,()> {
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(SpecifiedValue(Vec::new()))
}
let mut quotes = Vec::new();
loop {
let first = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
Ok(_) => return Err(()),
Err(()) => break,
};
let second = match input.next() {
Ok(Token::QuotedString(value)) => value.into_owned(),
_ => return Err(()),
};
quotes.push((first, second))
}
if!quotes.is_empty() {
Ok(SpecifiedValue(quotes))
} else {
Err(())
}
}
</%helpers:longhand>
| {
let mut first = true;
for pair in &self.0 {
if !first {
try!(dest.write_str(" "));
}
first = false;
try!(Token::QuotedString(Cow::from(&*pair.0)).to_css(dest));
try!(dest.write_str(" "));
try!(Token::QuotedString(Cow::from(&*pair.1)).to_css(dest));
}
Ok(())
} | identifier_body |
row_polymorphism.rs | use gluon::{ | };
use crate::support::make_vm;
#[macro_use]
mod support;
test_expr! { polymorphic_field_access,
r#"
let f record = record.x
f { y = 1, x = 123 }
"#,
123
}
test_expr! { polymorphic_record_unpack,
r#"
let f record =
let { x, y } = record
x #Int- y
f { y = 1, z = 0, x = 123 }
"#,
122
}
#[test]
fn polymorphic_record_access_from_child_thread() {
let _ = ::env_logger::try_init();
let vm = make_vm();
let child = vm.new_thread().unwrap();
vm.run_expr::<OpaqueValue<&Thread, Hole>>("", "import! std.function")
.unwrap();
let result = child.run_expr::<FunctionRef<fn(i32) -> i32>>(
"test",
r#"
let function = import! std.function
let f r = r.id in
f function
"#,
);
assert!(result.is_ok(), "{}", result.err().unwrap());
assert_eq!(result.unwrap().0.call(123), Ok(123));
}
// FIXME Add this test back when order no longer matters for fields
// test_expr! { prelude different_order_on_fields,
// r#"
// let x =
// if False then
// { x = 1, y = "a" }
// else
// { y = "b", x = 2 }
// x.y
// "#,
// String::from("a")
// }
// | vm::api::{FunctionRef, Hole, OpaqueValue},
Thread, ThreadExt, | random_line_split |
row_polymorphism.rs | use gluon::{
vm::api::{FunctionRef, Hole, OpaqueValue},
Thread, ThreadExt,
};
use crate::support::make_vm;
#[macro_use]
mod support;
test_expr! { polymorphic_field_access,
r#"
let f record = record.x
f { y = 1, x = 123 }
"#,
123
}
test_expr! { polymorphic_record_unpack,
r#"
let f record =
let { x, y } = record
x #Int- y
f { y = 1, z = 0, x = 123 }
"#,
122
}
#[test]
fn polymorphic_record_access_from_child_thread() |
// FIXME Add this test back when order no longer matters for fields
// test_expr! { prelude different_order_on_fields,
// r#"
// let x =
// if False then
// { x = 1, y = "a" }
// else
// { y = "b", x = 2 }
// x.y
// "#,
// String::from("a")
// }
//
| {
let _ = ::env_logger::try_init();
let vm = make_vm();
let child = vm.new_thread().unwrap();
vm.run_expr::<OpaqueValue<&Thread, Hole>>("", "import! std.function")
.unwrap();
let result = child.run_expr::<FunctionRef<fn(i32) -> i32>>(
"test",
r#"
let function = import! std.function
let f r = r.id in
f function
"#,
);
assert!(result.is_ok(), "{}", result.err().unwrap());
assert_eq!(result.unwrap().0.call(123), Ok(123));
} | identifier_body |
row_polymorphism.rs | use gluon::{
vm::api::{FunctionRef, Hole, OpaqueValue},
Thread, ThreadExt,
};
use crate::support::make_vm;
#[macro_use]
mod support;
test_expr! { polymorphic_field_access,
r#"
let f record = record.x
f { y = 1, x = 123 }
"#,
123
}
test_expr! { polymorphic_record_unpack,
r#"
let f record =
let { x, y } = record
x #Int- y
f { y = 1, z = 0, x = 123 }
"#,
122
}
#[test]
fn | () {
let _ = ::env_logger::try_init();
let vm = make_vm();
let child = vm.new_thread().unwrap();
vm.run_expr::<OpaqueValue<&Thread, Hole>>("", "import! std.function")
.unwrap();
let result = child.run_expr::<FunctionRef<fn(i32) -> i32>>(
"test",
r#"
let function = import! std.function
let f r = r.id in
f function
"#,
);
assert!(result.is_ok(), "{}", result.err().unwrap());
assert_eq!(result.unwrap().0.call(123), Ok(123));
}
// FIXME Add this test back when order no longer matters for fields
// test_expr! { prelude different_order_on_fields,
// r#"
// let x =
// if False then
// { x = 1, y = "a" }
// else
// { y = "b", x = 2 }
// x.y
// "#,
// String::from("a")
// }
//
| polymorphic_record_access_from_child_thread | identifier_name |
stylesheet_set.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/. */
//! A centralized set of stylesheets for a document.
use dom::TElement;
use invalidation::stylesheets::StylesheetInvalidationSet;
use shared_lock::SharedRwLockReadGuard;
use std::slice;
use stylesheets::StylesheetInDocument;
use stylist::Stylist;
/// Entry for a StylesheetSet. We don't bother creating a constructor, because
/// there's no sensible defaults for the member variables.
pub struct StylesheetSetEntry<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
sheet: S,
}
/// A iterator over the stylesheets of a list of entries in the StylesheetSet.
#[derive(Clone)]
pub struct StylesheetIterator<'a, S>(slice::Iter<'a, StylesheetSetEntry<S>>)
where
S: StylesheetInDocument + PartialEq +'static;
impl<'a, S> Iterator for StylesheetIterator<'a, S>
where
S: StylesheetInDocument + PartialEq +'static,
{
type Item = &'a S;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|entry| &entry.sheet)
}
}
/// The set of stylesheets effective for a given document.
pub struct StylesheetSet<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
/// The actual list of all the stylesheets that apply to the given document,
/// each stylesheet associated with a unique ID.
///
/// This is only a list of top-level stylesheets, and as such it doesn't
/// include recursive `@import` rules.
entries: Vec<StylesheetSetEntry<S>>,
/// Whether the entries list above has changed since the last restyle.
dirty: bool,
/// Has author style been disabled?
author_style_disabled: bool,
/// The style invalidations that we still haven't processed.
invalidations: StylesheetInvalidationSet,
}
impl<S> StylesheetSet<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
/// Create a new empty StylesheetSet.
pub fn new() -> Self {
StylesheetSet {
entries: vec![],
dirty: false,
author_style_disabled: false,
invalidations: StylesheetInvalidationSet::new(),
}
}
/// Returns whether author styles have been disabled for the current
/// stylesheet set.
pub fn author_style_disabled(&self) -> bool {
self.author_style_disabled
}
fn remove_stylesheet_if_present(&mut self, sheet: &S) {
self.entries.retain(|entry| entry.sheet!= *sheet);
}
/// Appends a new stylesheet to the current set.
pub fn append_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::append_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.dirty = true;
self.entries.push(StylesheetSetEntry { sheet });
}
/// Prepend a new stylesheet to the current set.
pub fn prepend_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::prepend_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.entries.insert(0, StylesheetSetEntry { sheet });
self.dirty = true;
}
/// Insert a given stylesheet before another stylesheet in the document.
pub fn insert_stylesheet_before(
&mut self,
stylist: &Stylist,
sheet: S,
before_sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::insert_stylesheet_before");
self.remove_stylesheet_if_present(&sheet);
let index = self.entries.iter().position(|entry| {
entry.sheet == before_sheet
}).expect("`before_sheet` stylesheet not found");
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.entries.insert(index, StylesheetSetEntry { sheet });
self.dirty = true;
}
/// Remove a given stylesheet from the set.
pub fn remove_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard,
) {
debug!("StylesheetSet::remove_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.dirty = true;
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
}
/// Notes that the author style has been disabled for this document.
pub fn set_author_style_disabled(&mut self, disabled: bool) |
/// Returns whether the given set has changed from the last flush.
pub fn has_changed(&self) -> bool {
self.dirty
}
/// Flush the current set, unmarking it as dirty, and returns an iterator
/// over the new stylesheet list.
pub fn flush<E>(
&mut self,
document_element: Option<E>
) -> StylesheetIterator<S>
where
E: TElement,
{
debug!("StylesheetSet::flush");
debug_assert!(self.dirty);
self.dirty = false;
self.invalidations.flush(document_element);
self.iter()
}
/// Returns an iterator over the current list of stylesheets.
pub fn iter(&self) -> StylesheetIterator<S> {
StylesheetIterator(self.entries.iter())
}
/// Mark the stylesheets as dirty, because something external may have
/// invalidated it.
///
/// FIXME(emilio): Make this more granular.
pub fn force_dirty(&mut self) {
self.dirty = true;
self.invalidations.invalidate_fully();
}
}
| {
debug!("StylesheetSet::set_author_style_disabled");
if self.author_style_disabled == disabled {
return;
}
self.author_style_disabled = disabled;
self.dirty = true;
self.invalidations.invalidate_fully();
} | identifier_body |
stylesheet_set.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/. */
//! A centralized set of stylesheets for a document.
use dom::TElement;
use invalidation::stylesheets::StylesheetInvalidationSet;
use shared_lock::SharedRwLockReadGuard;
use std::slice;
use stylesheets::StylesheetInDocument;
use stylist::Stylist;
/// Entry for a StylesheetSet. We don't bother creating a constructor, because
/// there's no sensible defaults for the member variables.
pub struct StylesheetSetEntry<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
sheet: S,
}
/// A iterator over the stylesheets of a list of entries in the StylesheetSet.
#[derive(Clone)]
pub struct StylesheetIterator<'a, S>(slice::Iter<'a, StylesheetSetEntry<S>>)
where
S: StylesheetInDocument + PartialEq +'static;
impl<'a, S> Iterator for StylesheetIterator<'a, S>
where
S: StylesheetInDocument + PartialEq +'static,
{
type Item = &'a S;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|entry| &entry.sheet)
}
}
/// The set of stylesheets effective for a given document.
pub struct StylesheetSet<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
/// The actual list of all the stylesheets that apply to the given document,
/// each stylesheet associated with a unique ID.
///
/// This is only a list of top-level stylesheets, and as such it doesn't
/// include recursive `@import` rules.
entries: Vec<StylesheetSetEntry<S>>,
/// Whether the entries list above has changed since the last restyle.
dirty: bool,
/// Has author style been disabled?
author_style_disabled: bool,
/// The style invalidations that we still haven't processed.
invalidations: StylesheetInvalidationSet,
}
impl<S> StylesheetSet<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
/// Create a new empty StylesheetSet.
pub fn new() -> Self {
StylesheetSet {
entries: vec![],
dirty: false,
author_style_disabled: false,
invalidations: StylesheetInvalidationSet::new(),
}
}
/// Returns whether author styles have been disabled for the current
/// stylesheet set.
pub fn author_style_disabled(&self) -> bool {
self.author_style_disabled
}
fn remove_stylesheet_if_present(&mut self, sheet: &S) {
self.entries.retain(|entry| entry.sheet!= *sheet);
}
/// Appends a new stylesheet to the current set.
pub fn append_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::append_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.dirty = true;
self.entries.push(StylesheetSetEntry { sheet });
}
/// Prepend a new stylesheet to the current set.
pub fn prepend_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::prepend_stylesheet");
self.remove_stylesheet_if_present(&sheet); | &sheet,
guard
);
self.entries.insert(0, StylesheetSetEntry { sheet });
self.dirty = true;
}
/// Insert a given stylesheet before another stylesheet in the document.
pub fn insert_stylesheet_before(
&mut self,
stylist: &Stylist,
sheet: S,
before_sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::insert_stylesheet_before");
self.remove_stylesheet_if_present(&sheet);
let index = self.entries.iter().position(|entry| {
entry.sheet == before_sheet
}).expect("`before_sheet` stylesheet not found");
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.entries.insert(index, StylesheetSetEntry { sheet });
self.dirty = true;
}
/// Remove a given stylesheet from the set.
pub fn remove_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard,
) {
debug!("StylesheetSet::remove_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.dirty = true;
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
}
/// Notes that the author style has been disabled for this document.
pub fn set_author_style_disabled(&mut self, disabled: bool) {
debug!("StylesheetSet::set_author_style_disabled");
if self.author_style_disabled == disabled {
return;
}
self.author_style_disabled = disabled;
self.dirty = true;
self.invalidations.invalidate_fully();
}
/// Returns whether the given set has changed from the last flush.
pub fn has_changed(&self) -> bool {
self.dirty
}
/// Flush the current set, unmarking it as dirty, and returns an iterator
/// over the new stylesheet list.
pub fn flush<E>(
&mut self,
document_element: Option<E>
) -> StylesheetIterator<S>
where
E: TElement,
{
debug!("StylesheetSet::flush");
debug_assert!(self.dirty);
self.dirty = false;
self.invalidations.flush(document_element);
self.iter()
}
/// Returns an iterator over the current list of stylesheets.
pub fn iter(&self) -> StylesheetIterator<S> {
StylesheetIterator(self.entries.iter())
}
/// Mark the stylesheets as dirty, because something external may have
/// invalidated it.
///
/// FIXME(emilio): Make this more granular.
pub fn force_dirty(&mut self) {
self.dirty = true;
self.invalidations.invalidate_fully();
}
} | self.invalidations.collect_invalidations_for(
stylist, | random_line_split |
stylesheet_set.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/. */
//! A centralized set of stylesheets for a document.
use dom::TElement;
use invalidation::stylesheets::StylesheetInvalidationSet;
use shared_lock::SharedRwLockReadGuard;
use std::slice;
use stylesheets::StylesheetInDocument;
use stylist::Stylist;
/// Entry for a StylesheetSet. We don't bother creating a constructor, because
/// there's no sensible defaults for the member variables.
pub struct StylesheetSetEntry<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
sheet: S,
}
/// A iterator over the stylesheets of a list of entries in the StylesheetSet.
#[derive(Clone)]
pub struct StylesheetIterator<'a, S>(slice::Iter<'a, StylesheetSetEntry<S>>)
where
S: StylesheetInDocument + PartialEq +'static;
impl<'a, S> Iterator for StylesheetIterator<'a, S>
where
S: StylesheetInDocument + PartialEq +'static,
{
type Item = &'a S;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|entry| &entry.sheet)
}
}
/// The set of stylesheets effective for a given document.
pub struct StylesheetSet<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
/// The actual list of all the stylesheets that apply to the given document,
/// each stylesheet associated with a unique ID.
///
/// This is only a list of top-level stylesheets, and as such it doesn't
/// include recursive `@import` rules.
entries: Vec<StylesheetSetEntry<S>>,
/// Whether the entries list above has changed since the last restyle.
dirty: bool,
/// Has author style been disabled?
author_style_disabled: bool,
/// The style invalidations that we still haven't processed.
invalidations: StylesheetInvalidationSet,
}
impl<S> StylesheetSet<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
/// Create a new empty StylesheetSet.
pub fn new() -> Self {
StylesheetSet {
entries: vec![],
dirty: false,
author_style_disabled: false,
invalidations: StylesheetInvalidationSet::new(),
}
}
/// Returns whether author styles have been disabled for the current
/// stylesheet set.
pub fn author_style_disabled(&self) -> bool {
self.author_style_disabled
}
fn remove_stylesheet_if_present(&mut self, sheet: &S) {
self.entries.retain(|entry| entry.sheet!= *sheet);
}
/// Appends a new stylesheet to the current set.
pub fn append_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::append_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.dirty = true;
self.entries.push(StylesheetSetEntry { sheet });
}
/// Prepend a new stylesheet to the current set.
pub fn prepend_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::prepend_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.entries.insert(0, StylesheetSetEntry { sheet });
self.dirty = true;
}
/// Insert a given stylesheet before another stylesheet in the document.
pub fn insert_stylesheet_before(
&mut self,
stylist: &Stylist,
sheet: S,
before_sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::insert_stylesheet_before");
self.remove_stylesheet_if_present(&sheet);
let index = self.entries.iter().position(|entry| {
entry.sheet == before_sheet
}).expect("`before_sheet` stylesheet not found");
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.entries.insert(index, StylesheetSetEntry { sheet });
self.dirty = true;
}
/// Remove a given stylesheet from the set.
pub fn remove_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard,
) {
debug!("StylesheetSet::remove_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.dirty = true;
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
}
/// Notes that the author style has been disabled for this document.
pub fn set_author_style_disabled(&mut self, disabled: bool) {
debug!("StylesheetSet::set_author_style_disabled");
if self.author_style_disabled == disabled |
self.author_style_disabled = disabled;
self.dirty = true;
self.invalidations.invalidate_fully();
}
/// Returns whether the given set has changed from the last flush.
pub fn has_changed(&self) -> bool {
self.dirty
}
/// Flush the current set, unmarking it as dirty, and returns an iterator
/// over the new stylesheet list.
pub fn flush<E>(
&mut self,
document_element: Option<E>
) -> StylesheetIterator<S>
where
E: TElement,
{
debug!("StylesheetSet::flush");
debug_assert!(self.dirty);
self.dirty = false;
self.invalidations.flush(document_element);
self.iter()
}
/// Returns an iterator over the current list of stylesheets.
pub fn iter(&self) -> StylesheetIterator<S> {
StylesheetIterator(self.entries.iter())
}
/// Mark the stylesheets as dirty, because something external may have
/// invalidated it.
///
/// FIXME(emilio): Make this more granular.
pub fn force_dirty(&mut self) {
self.dirty = true;
self.invalidations.invalidate_fully();
}
}
| {
return;
} | conditional_block |
stylesheet_set.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/. */
//! A centralized set of stylesheets for a document.
use dom::TElement;
use invalidation::stylesheets::StylesheetInvalidationSet;
use shared_lock::SharedRwLockReadGuard;
use std::slice;
use stylesheets::StylesheetInDocument;
use stylist::Stylist;
/// Entry for a StylesheetSet. We don't bother creating a constructor, because
/// there's no sensible defaults for the member variables.
pub struct StylesheetSetEntry<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
sheet: S,
}
/// A iterator over the stylesheets of a list of entries in the StylesheetSet.
#[derive(Clone)]
pub struct StylesheetIterator<'a, S>(slice::Iter<'a, StylesheetSetEntry<S>>)
where
S: StylesheetInDocument + PartialEq +'static;
impl<'a, S> Iterator for StylesheetIterator<'a, S>
where
S: StylesheetInDocument + PartialEq +'static,
{
type Item = &'a S;
fn next(&mut self) -> Option<Self::Item> {
self.0.next().map(|entry| &entry.sheet)
}
}
/// The set of stylesheets effective for a given document.
pub struct StylesheetSet<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
/// The actual list of all the stylesheets that apply to the given document,
/// each stylesheet associated with a unique ID.
///
/// This is only a list of top-level stylesheets, and as such it doesn't
/// include recursive `@import` rules.
entries: Vec<StylesheetSetEntry<S>>,
/// Whether the entries list above has changed since the last restyle.
dirty: bool,
/// Has author style been disabled?
author_style_disabled: bool,
/// The style invalidations that we still haven't processed.
invalidations: StylesheetInvalidationSet,
}
impl<S> StylesheetSet<S>
where
S: StylesheetInDocument + PartialEq +'static,
{
/// Create a new empty StylesheetSet.
pub fn new() -> Self {
StylesheetSet {
entries: vec![],
dirty: false,
author_style_disabled: false,
invalidations: StylesheetInvalidationSet::new(),
}
}
/// Returns whether author styles have been disabled for the current
/// stylesheet set.
pub fn author_style_disabled(&self) -> bool {
self.author_style_disabled
}
fn remove_stylesheet_if_present(&mut self, sheet: &S) {
self.entries.retain(|entry| entry.sheet!= *sheet);
}
/// Appends a new stylesheet to the current set.
pub fn append_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::append_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.dirty = true;
self.entries.push(StylesheetSetEntry { sheet });
}
/// Prepend a new stylesheet to the current set.
pub fn prepend_stylesheet(
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::prepend_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.entries.insert(0, StylesheetSetEntry { sheet });
self.dirty = true;
}
/// Insert a given stylesheet before another stylesheet in the document.
pub fn insert_stylesheet_before(
&mut self,
stylist: &Stylist,
sheet: S,
before_sheet: S,
guard: &SharedRwLockReadGuard
) {
debug!("StylesheetSet::insert_stylesheet_before");
self.remove_stylesheet_if_present(&sheet);
let index = self.entries.iter().position(|entry| {
entry.sheet == before_sheet
}).expect("`before_sheet` stylesheet not found");
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
self.entries.insert(index, StylesheetSetEntry { sheet });
self.dirty = true;
}
/// Remove a given stylesheet from the set.
pub fn | (
&mut self,
stylist: &Stylist,
sheet: S,
guard: &SharedRwLockReadGuard,
) {
debug!("StylesheetSet::remove_stylesheet");
self.remove_stylesheet_if_present(&sheet);
self.dirty = true;
self.invalidations.collect_invalidations_for(
stylist,
&sheet,
guard
);
}
/// Notes that the author style has been disabled for this document.
pub fn set_author_style_disabled(&mut self, disabled: bool) {
debug!("StylesheetSet::set_author_style_disabled");
if self.author_style_disabled == disabled {
return;
}
self.author_style_disabled = disabled;
self.dirty = true;
self.invalidations.invalidate_fully();
}
/// Returns whether the given set has changed from the last flush.
pub fn has_changed(&self) -> bool {
self.dirty
}
/// Flush the current set, unmarking it as dirty, and returns an iterator
/// over the new stylesheet list.
pub fn flush<E>(
&mut self,
document_element: Option<E>
) -> StylesheetIterator<S>
where
E: TElement,
{
debug!("StylesheetSet::flush");
debug_assert!(self.dirty);
self.dirty = false;
self.invalidations.flush(document_element);
self.iter()
}
/// Returns an iterator over the current list of stylesheets.
pub fn iter(&self) -> StylesheetIterator<S> {
StylesheetIterator(self.entries.iter())
}
/// Mark the stylesheets as dirty, because something external may have
/// invalidated it.
///
/// FIXME(emilio): Make this more granular.
pub fn force_dirty(&mut self) {
self.dirty = true;
self.invalidations.invalidate_fully();
}
}
| remove_stylesheet | identifier_name |
cli.rs | //! Provides the CLI option parser
//!
//! Used to parse the argv/config file into a struct that
//! the server can consume and use as configuration data.
use docopt::Docopt;
static USAGE: &'static str = "
Usage: statsd [options]
statsd --help
Options:
-h, --help Print help information.
-p, --port=<p> The UDP port to bind to [default: 8125].
--flush-interval=<p> How frequently to flush metrics to the backends in seconds. [default: 10].
--console Enable the console backend.
--graphite Enable the graphite backend.
--graphite-port=<p> The port graphite/carbon is running on. [default: 2003].
--graphite-host=<p> The host graphite/carbon is running on. [default: 127.0.0.1]
--admin-host=<p> The host to bind the management server on. [default: 127.0.0.1]
--admin-port=<p> The port to bind the management server to. [default: 8126]
";
/// Holds the parsed command line arguments
#[derive(Deserialize, Debug)]
pub struct | {
pub flag_port: u16,
pub flag_admin_port: u16,
pub flag_admin_host: String,
pub flag_flush_interval: u64,
pub flag_console: bool,
pub flag_graphite: bool,
pub flag_graphite_port: u16,
pub flag_graphite_host: String,
pub flag_help: bool,
}
pub fn parse_args() -> Args {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
args
}
| Args | identifier_name |
cli.rs | //! Provides the CLI option parser
//!
//! Used to parse the argv/config file into a struct that
//! the server can consume and use as configuration data.
use docopt::Docopt;
static USAGE: &'static str = "
Usage: statsd [options]
statsd --help
Options:
-h, --help Print help information.
-p, --port=<p> The UDP port to bind to [default: 8125].
--flush-interval=<p> How frequently to flush metrics to the backends in seconds. [default: 10].
--console Enable the console backend. | --graphite-port=<p> The port graphite/carbon is running on. [default: 2003].
--graphite-host=<p> The host graphite/carbon is running on. [default: 127.0.0.1]
--admin-host=<p> The host to bind the management server on. [default: 127.0.0.1]
--admin-port=<p> The port to bind the management server to. [default: 8126]
";
/// Holds the parsed command line arguments
#[derive(Deserialize, Debug)]
pub struct Args {
pub flag_port: u16,
pub flag_admin_port: u16,
pub flag_admin_host: String,
pub flag_flush_interval: u64,
pub flag_console: bool,
pub flag_graphite: bool,
pub flag_graphite_port: u16,
pub flag_graphite_host: String,
pub flag_help: bool,
}
pub fn parse_args() -> Args {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
args
} | --graphite Enable the graphite backend. | random_line_split |
image.rs | extern crate piston_window;
extern crate find_folder;
use piston_window::*;
fn main() {
let opengl = OpenGL::V3_2;
let mut window: PistonWindow =
WindowSettings::new("piston: image", [300, 300])
.exit_on_esc(true)
.graphics_api(opengl)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let rust_logo = assets.join("rust.png");
let rust_logo: G2dTexture = Texture::from_path(
&mut window.create_texture_context(),
&rust_logo,
Flip::None,
&TextureSettings::new()
).unwrap(); | image(&rust_logo, c.transform, g);
});
}
} | window.set_lazy(true);
while let Some(e) = window.next() {
window.draw_2d(&e, |c, g, _| {
clear([1.0; 4], g); | random_line_split |
image.rs | extern crate piston_window;
extern crate find_folder;
use piston_window::*;
fn main() | window.draw_2d(&e, |c, g, _| {
clear([1.0; 4], g);
image(&rust_logo, c.transform, g);
});
}
}
| {
let opengl = OpenGL::V3_2;
let mut window: PistonWindow =
WindowSettings::new("piston: image", [300, 300])
.exit_on_esc(true)
.graphics_api(opengl)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let rust_logo = assets.join("rust.png");
let rust_logo: G2dTexture = Texture::from_path(
&mut window.create_texture_context(),
&rust_logo,
Flip::None,
&TextureSettings::new()
).unwrap();
window.set_lazy(true);
while let Some(e) = window.next() { | identifier_body |
image.rs | extern crate piston_window;
extern crate find_folder;
use piston_window::*;
fn | () {
let opengl = OpenGL::V3_2;
let mut window: PistonWindow =
WindowSettings::new("piston: image", [300, 300])
.exit_on_esc(true)
.graphics_api(opengl)
.build()
.unwrap();
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets").unwrap();
let rust_logo = assets.join("rust.png");
let rust_logo: G2dTexture = Texture::from_path(
&mut window.create_texture_context(),
&rust_logo,
Flip::None,
&TextureSettings::new()
).unwrap();
window.set_lazy(true);
while let Some(e) = window.next() {
window.draw_2d(&e, |c, g, _| {
clear([1.0; 4], g);
image(&rust_logo, c.transform, g);
});
}
}
| main | identifier_name |
skip_split_operation.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::DIRECTIVE_SPLIT_OPERATION;
use common::NamedItem;
use graphql_ir::{FragmentDefinition, OperationDefinition, Program, Transformed, Transformer};
/// A transform that removes field `splitOperations`. Intended for use when e.g.
/// printing queries to send to a GraphQL server.
pub fn skip_split_operation(program: &Program) -> Program {
let mut transform = SkipSplitOperation {};
transform
.transform_program(program)
.replace_or_else(|| program.clone())
}
pub struct SkipSplitOperation;
impl Transformer for SkipSplitOperation {
const NAME: &'static str = "SkipSplitOperationTransform";
const VISIT_ARGUMENTS: bool = false;
const VISIT_DIRECTIVES: bool = false;
fn transform_operation(
&mut self,
operation: &OperationDefinition,
) -> Transformed<OperationDefinition> {
if operation
.directives
.named(*DIRECTIVE_SPLIT_OPERATION)
.is_some()
| else {
Transformed::Keep
}
}
fn transform_fragment(&mut self, _: &FragmentDefinition) -> Transformed<FragmentDefinition> {
Transformed::Keep
}
}
| {
Transformed::Delete
} | conditional_block |
skip_split_operation.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::DIRECTIVE_SPLIT_OPERATION;
use common::NamedItem;
use graphql_ir::{FragmentDefinition, OperationDefinition, Program, Transformed, Transformer};
/// A transform that removes field `splitOperations`. Intended for use when e.g.
/// printing queries to send to a GraphQL server.
pub fn skip_split_operation(program: &Program) -> Program {
let mut transform = SkipSplitOperation {};
transform
.transform_program(program)
.replace_or_else(|| program.clone())
}
pub struct SkipSplitOperation;
impl Transformer for SkipSplitOperation {
const NAME: &'static str = "SkipSplitOperationTransform";
const VISIT_ARGUMENTS: bool = false;
const VISIT_DIRECTIVES: bool = false;
fn transform_operation(
&mut self,
operation: &OperationDefinition,
) -> Transformed<OperationDefinition> {
if operation | Transformed::Delete
} else {
Transformed::Keep
}
}
fn transform_fragment(&mut self, _: &FragmentDefinition) -> Transformed<FragmentDefinition> {
Transformed::Keep
}
} | .directives
.named(*DIRECTIVE_SPLIT_OPERATION)
.is_some()
{ | random_line_split |
skip_split_operation.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::DIRECTIVE_SPLIT_OPERATION;
use common::NamedItem;
use graphql_ir::{FragmentDefinition, OperationDefinition, Program, Transformed, Transformer};
/// A transform that removes field `splitOperations`. Intended for use when e.g.
/// printing queries to send to a GraphQL server.
pub fn skip_split_operation(program: &Program) -> Program {
let mut transform = SkipSplitOperation {};
transform
.transform_program(program)
.replace_or_else(|| program.clone())
}
pub struct SkipSplitOperation;
impl Transformer for SkipSplitOperation {
const NAME: &'static str = "SkipSplitOperationTransform";
const VISIT_ARGUMENTS: bool = false;
const VISIT_DIRECTIVES: bool = false;
fn | (
&mut self,
operation: &OperationDefinition,
) -> Transformed<OperationDefinition> {
if operation
.directives
.named(*DIRECTIVE_SPLIT_OPERATION)
.is_some()
{
Transformed::Delete
} else {
Transformed::Keep
}
}
fn transform_fragment(&mut self, _: &FragmentDefinition) -> Transformed<FragmentDefinition> {
Transformed::Keep
}
}
| transform_operation | identifier_name |
skip_split_operation.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::DIRECTIVE_SPLIT_OPERATION;
use common::NamedItem;
use graphql_ir::{FragmentDefinition, OperationDefinition, Program, Transformed, Transformer};
/// A transform that removes field `splitOperations`. Intended for use when e.g.
/// printing queries to send to a GraphQL server.
pub fn skip_split_operation(program: &Program) -> Program |
pub struct SkipSplitOperation;
impl Transformer for SkipSplitOperation {
const NAME: &'static str = "SkipSplitOperationTransform";
const VISIT_ARGUMENTS: bool = false;
const VISIT_DIRECTIVES: bool = false;
fn transform_operation(
&mut self,
operation: &OperationDefinition,
) -> Transformed<OperationDefinition> {
if operation
.directives
.named(*DIRECTIVE_SPLIT_OPERATION)
.is_some()
{
Transformed::Delete
} else {
Transformed::Keep
}
}
fn transform_fragment(&mut self, _: &FragmentDefinition) -> Transformed<FragmentDefinition> {
Transformed::Keep
}
}
| {
let mut transform = SkipSplitOperation {};
transform
.transform_program(program)
.replace_or_else(|| program.clone())
} | identifier_body |
entry.rs | use memory::Frame;
pub struct Entry(u64);
impl Entry {
pub fn is_unused(&self) -> bool |
pub fn set_unused(&mut self) {
self.0 = 0;
}
pub fn flags(&self) -> EntryFlags {
EntryFlags::from_bits_truncate(self.0)
}
pub fn pointed_frame(&self) -> Option<Frame> {
if self.flags().contains(PRESENT) {
Some(Frame::containing_address(self.0 as usize & 0x000fffff_fffff000))
} else {
None
}
}
pub fn set(&mut self, frame: Frame, flags: EntryFlags) {
assert!(frame.start_address() &!0x000fffff_fffff000 == 0);
self.0 = (frame.start_address() as u64) | flags.bits();
}
}
bitflags! {
flags EntryFlags: u64 {
const PRESENT = 1 << 0,
const WRITABLE = 1 << 1,
const USER_ACCESSIBLE = 1 << 2,
const WRITE_THROUGH = 1 << 3,
const NO_CACHE = 1 << 4,
const ACCESSED = 1 << 5,
const DIRTY = 1 << 6,
const HUGE_PAGE = 1 << 7,
const GLOBAL = 1 << 8,
const NO_EXECUTE = 1 << 63,
}
}
| {
self.0 == 0
} | identifier_body |
entry.rs | use memory::Frame;
pub struct Entry(u64);
impl Entry {
pub fn is_unused(&self) -> bool {
self.0 == 0
}
pub fn set_unused(&mut self) {
self.0 = 0;
}
pub fn flags(&self) -> EntryFlags {
EntryFlags::from_bits_truncate(self.0)
}
pub fn pointed_frame(&self) -> Option<Frame> {
if self.flags().contains(PRESENT) {
Some(Frame::containing_address(self.0 as usize & 0x000fffff_fffff000))
} else |
}
pub fn set(&mut self, frame: Frame, flags: EntryFlags) {
assert!(frame.start_address() &!0x000fffff_fffff000 == 0);
self.0 = (frame.start_address() as u64) | flags.bits();
}
}
bitflags! {
flags EntryFlags: u64 {
const PRESENT = 1 << 0,
const WRITABLE = 1 << 1,
const USER_ACCESSIBLE = 1 << 2,
const WRITE_THROUGH = 1 << 3,
const NO_CACHE = 1 << 4,
const ACCESSED = 1 << 5,
const DIRTY = 1 << 6,
const HUGE_PAGE = 1 << 7,
const GLOBAL = 1 << 8,
const NO_EXECUTE = 1 << 63,
}
}
| {
None
} | conditional_block |
entry.rs | use memory::Frame;
pub struct Entry(u64);
impl Entry {
pub fn is_unused(&self) -> bool {
self.0 == 0
}
pub fn | (&mut self) {
self.0 = 0;
}
pub fn flags(&self) -> EntryFlags {
EntryFlags::from_bits_truncate(self.0)
}
pub fn pointed_frame(&self) -> Option<Frame> {
if self.flags().contains(PRESENT) {
Some(Frame::containing_address(self.0 as usize & 0x000fffff_fffff000))
} else {
None
}
}
pub fn set(&mut self, frame: Frame, flags: EntryFlags) {
assert!(frame.start_address() &!0x000fffff_fffff000 == 0);
self.0 = (frame.start_address() as u64) | flags.bits();
}
}
bitflags! {
flags EntryFlags: u64 {
const PRESENT = 1 << 0,
const WRITABLE = 1 << 1,
const USER_ACCESSIBLE = 1 << 2,
const WRITE_THROUGH = 1 << 3,
const NO_CACHE = 1 << 4,
const ACCESSED = 1 << 5,
const DIRTY = 1 << 6,
const HUGE_PAGE = 1 << 7,
const GLOBAL = 1 << 8,
const NO_EXECUTE = 1 << 63,
}
}
| set_unused | identifier_name |
entry.rs | use memory::Frame; | pub fn is_unused(&self) -> bool {
self.0 == 0
}
pub fn set_unused(&mut self) {
self.0 = 0;
}
pub fn flags(&self) -> EntryFlags {
EntryFlags::from_bits_truncate(self.0)
}
pub fn pointed_frame(&self) -> Option<Frame> {
if self.flags().contains(PRESENT) {
Some(Frame::containing_address(self.0 as usize & 0x000fffff_fffff000))
} else {
None
}
}
pub fn set(&mut self, frame: Frame, flags: EntryFlags) {
assert!(frame.start_address() &!0x000fffff_fffff000 == 0);
self.0 = (frame.start_address() as u64) | flags.bits();
}
}
bitflags! {
flags EntryFlags: u64 {
const PRESENT = 1 << 0,
const WRITABLE = 1 << 1,
const USER_ACCESSIBLE = 1 << 2,
const WRITE_THROUGH = 1 << 3,
const NO_CACHE = 1 << 4,
const ACCESSED = 1 << 5,
const DIRTY = 1 << 6,
const HUGE_PAGE = 1 << 7,
const GLOBAL = 1 << 8,
const NO_EXECUTE = 1 << 63,
}
} |
pub struct Entry(u64);
impl Entry { | random_line_split |
windowing.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/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use compositor_thread::{CompositorProxy, CompositorReceiver};
use euclid::{Point2D, Size2D};
use euclid::point::TypedPoint2D;
use euclid::rect::TypedRect;
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use gleam::gl;
use msg::constellation_msg::{Key, KeyModifiers, KeyState};
use net_traits::net_error_list::NetError;
use script_traits::{DevicePixel, LoadData, MouseButton, TouchEventType, TouchId, TouchpadPressurePhase};
use servo_geometry::DeviceIndependentPixel;
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::rc::Rc;
use style_traits::cursor::Cursor;
use webrender_traits::ScrollLocation;
#[derive(Clone)]
pub enum | {
Click(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseDown(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseUp(MouseButton, TypedPoint2D<f32, DevicePixel>),
}
#[derive(Clone)]
pub enum WindowNavigateMsg {
Forward,
Back,
}
/// Events that the windowing system sends to Servo.
#[derive(Clone)]
pub enum WindowEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem).
///
/// FIXME(pcwalton): This is kind of ugly and may not work well with multiprocess Servo.
/// It's possible that this should be something like
/// `CompositorMessageWindowEvent(compositor_thread::Msg)` instead.
Idle,
/// Sent when part of the window is marked dirty and needs to be redrawn. Before sending this
/// message, the window must make the same GL context as in `PrepareRenderingEvent` current.
Refresh,
/// Sent to initialize the GL context. The windowing system must have a valid, current GL
/// context when this message is sent.
InitializeCompositing,
/// Sent when the window is resized.
Resize(TypedSize2D<u32, DevicePixel>),
/// Touchpad Pressure
TouchpadPressure(TypedPoint2D<f32, DevicePixel>, f32, TouchpadPressurePhase),
/// Sent when a new URL is to be loaded.
LoadUrl(String),
/// Sent when a mouse hit test is to be performed.
MouseWindowEventClass(MouseWindowEvent),
/// Sent when a mouse move.
MouseWindowMoveEventClass(TypedPoint2D<f32, DevicePixel>),
/// Touch event: type, identifier, point
Touch(TouchEventType, TouchId, TypedPoint2D<f32, DevicePixel>),
/// Sent when the user scrolls. The first point is the delta and the second point is the
/// origin.
Scroll(ScrollLocation, TypedPoint2D<i32, DevicePixel>, TouchEventType),
/// Sent when the user zooms.
Zoom(f32),
/// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel).
PinchZoom(f32),
/// Sent when the user resets zoom to default.
ResetZoom,
/// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace).
Navigation(WindowNavigateMsg),
/// Sent when the user quits the application
Quit,
/// Sent when a key input state changes
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Sent when Ctr+R/Apple+R is called to reload the current page.
Reload,
}
impl Debug for WindowEvent {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
WindowEvent::Idle => write!(f, "Idle"),
WindowEvent::Refresh => write!(f, "Refresh"),
WindowEvent::InitializeCompositing => write!(f, "InitializeCompositing"),
WindowEvent::Resize(..) => write!(f, "Resize"),
WindowEvent::TouchpadPressure(..) => write!(f, "TouchpadPressure"),
WindowEvent::KeyEvent(..) => write!(f, "Key"),
WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"),
WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"),
WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"),
WindowEvent::Touch(..) => write!(f, "Touch"),
WindowEvent::Scroll(..) => write!(f, "Scroll"),
WindowEvent::Zoom(..) => write!(f, "Zoom"),
WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"),
WindowEvent::ResetZoom => write!(f, "ResetZoom"),
WindowEvent::Navigation(..) => write!(f, "Navigation"),
WindowEvent::Quit => write!(f, "Quit"),
WindowEvent::Reload => write!(f, "Reload"),
}
}
}
pub trait WindowMethods {
/// Returns the rendering area size in hardware pixels.
fn framebuffer_size(&self) -> TypedSize2D<u32, DevicePixel>;
/// Returns the position and size of the window within the rendering area.
fn window_rect(&self) -> TypedRect<u32, DevicePixel>;
/// Returns the size of the window in density-independent "px" units.
fn size(&self) -> TypedSize2D<f32, DeviceIndependentPixel>;
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self);
/// Return the size of the window with head and borders and position of the window values
fn client_window(&self) -> (Size2D<u32>, Point2D<i32>);
/// Set the size inside of borders and head
fn set_inner_size(&self, size: Size2D<u32>);
/// Set the window position
fn set_position(&self, point: Point2D<i32>);
/// Set fullscreen state
fn set_fullscreen_state(&self, state: bool);
/// Sets the page title for the current page.
fn set_page_title(&self, title: Option<String>);
/// Called when the browser chrome should display a status message.
fn status(&self, Option<String>);
/// Called when the browser has started loading a frame.
fn load_start(&self);
/// Called when the browser is done loading a frame.
fn load_end(&self);
/// Called when the browser encounters an error while loading a URL
fn load_error(&self, code: NetError, url: String);
/// Wether or not to follow a link
fn allow_navigation(&self, url: ServoUrl) -> bool;
/// Called when the <head> tag has finished parsing
fn head_parsed(&self);
/// Called when the history state has changed.
fn history_changed(&self, Vec<LoadData>, usize);
/// Returns the scale factor of the system (device pixels / device independent pixels).
fn hidpi_factor(&self) -> ScaleFactor<f32, DeviceIndependentPixel, DevicePixel>;
/// Creates a channel to the compositor. The dummy parameter is needed because we don't have
/// UFCS in Rust yet.
///
/// This is part of the windowing system because its implementation often involves OS-specific
/// magic to wake the up window's event loop.
fn create_compositor_channel(&self) -> (Box<CompositorProxy + Send>, Box<CompositorReceiver>);
/// Requests that the window system prepare a composite. Typically this will involve making
/// some type of platform-specific graphics context current. Returns true if the composite may
/// proceed and false if it should not.
fn prepare_for_composite(&self, width: usize, height: usize) -> bool;
/// Sets the cursor to be used in the window.
fn set_cursor(&self, cursor: Cursor);
/// Process a key event.
fn handle_key(&self, ch: Option<char>, key: Key, mods: KeyModifiers);
/// Does this window support a clipboard
fn supports_clipboard(&self) -> bool;
/// Add a favicon
fn set_favicon(&self, url: ServoUrl);
/// Return the GL function pointer trait.
fn gl(&self) -> Rc<gl::Gl>;
}
| MouseWindowEvent | identifier_name |
windowing.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/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use compositor_thread::{CompositorProxy, CompositorReceiver};
use euclid::{Point2D, Size2D};
use euclid::point::TypedPoint2D;
use euclid::rect::TypedRect;
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use gleam::gl;
use msg::constellation_msg::{Key, KeyModifiers, KeyState};
use net_traits::net_error_list::NetError;
use script_traits::{DevicePixel, LoadData, MouseButton, TouchEventType, TouchId, TouchpadPressurePhase};
use servo_geometry::DeviceIndependentPixel;
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::rc::Rc;
use style_traits::cursor::Cursor;
use webrender_traits::ScrollLocation;
#[derive(Clone)]
pub enum MouseWindowEvent {
Click(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseDown(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseUp(MouseButton, TypedPoint2D<f32, DevicePixel>),
}
#[derive(Clone)]
pub enum WindowNavigateMsg {
Forward,
Back,
}
/// Events that the windowing system sends to Servo.
#[derive(Clone)]
pub enum WindowEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem).
///
/// FIXME(pcwalton): This is kind of ugly and may not work well with multiprocess Servo.
/// It's possible that this should be something like
/// `CompositorMessageWindowEvent(compositor_thread::Msg)` instead.
Idle,
/// Sent when part of the window is marked dirty and needs to be redrawn. Before sending this
/// message, the window must make the same GL context as in `PrepareRenderingEvent` current.
Refresh,
/// Sent to initialize the GL context. The windowing system must have a valid, current GL
/// context when this message is sent.
InitializeCompositing,
/// Sent when the window is resized.
Resize(TypedSize2D<u32, DevicePixel>),
/// Touchpad Pressure
TouchpadPressure(TypedPoint2D<f32, DevicePixel>, f32, TouchpadPressurePhase),
/// Sent when a new URL is to be loaded.
LoadUrl(String),
/// Sent when a mouse hit test is to be performed.
MouseWindowEventClass(MouseWindowEvent),
/// Sent when a mouse move.
MouseWindowMoveEventClass(TypedPoint2D<f32, DevicePixel>),
/// Touch event: type, identifier, point
Touch(TouchEventType, TouchId, TypedPoint2D<f32, DevicePixel>),
/// Sent when the user scrolls. The first point is the delta and the second point is the
/// origin.
Scroll(ScrollLocation, TypedPoint2D<i32, DevicePixel>, TouchEventType),
/// Sent when the user zooms.
Zoom(f32),
/// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel).
PinchZoom(f32),
/// Sent when the user resets zoom to default.
ResetZoom,
/// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace).
Navigation(WindowNavigateMsg),
/// Sent when the user quits the application
Quit,
/// Sent when a key input state changes
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Sent when Ctr+R/Apple+R is called to reload the current page.
Reload,
}
impl Debug for WindowEvent {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
WindowEvent::Idle => write!(f, "Idle"),
WindowEvent::Refresh => write!(f, "Refresh"),
WindowEvent::InitializeCompositing => write!(f, "InitializeCompositing"),
WindowEvent::Resize(..) => write!(f, "Resize"),
WindowEvent::TouchpadPressure(..) => write!(f, "TouchpadPressure"),
WindowEvent::KeyEvent(..) => write!(f, "Key"),
WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"),
WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"),
WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"),
WindowEvent::Touch(..) => write!(f, "Touch"),
WindowEvent::Scroll(..) => write!(f, "Scroll"),
WindowEvent::Zoom(..) => write!(f, "Zoom"),
WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"),
WindowEvent::ResetZoom => write!(f, "ResetZoom"),
WindowEvent::Navigation(..) => write!(f, "Navigation"),
WindowEvent::Quit => write!(f, "Quit"),
WindowEvent::Reload => write!(f, "Reload"),
}
}
}
pub trait WindowMethods {
/// Returns the rendering area size in hardware pixels.
fn framebuffer_size(&self) -> TypedSize2D<u32, DevicePixel>;
/// Returns the position and size of the window within the rendering area.
fn window_rect(&self) -> TypedRect<u32, DevicePixel>;
/// Returns the size of the window in density-independent "px" units.
fn size(&self) -> TypedSize2D<f32, DeviceIndependentPixel>;
/// Presents the window to the screen (perhaps by page flipping). | fn present(&self);
/// Return the size of the window with head and borders and position of the window values
fn client_window(&self) -> (Size2D<u32>, Point2D<i32>);
/// Set the size inside of borders and head
fn set_inner_size(&self, size: Size2D<u32>);
/// Set the window position
fn set_position(&self, point: Point2D<i32>);
/// Set fullscreen state
fn set_fullscreen_state(&self, state: bool);
/// Sets the page title for the current page.
fn set_page_title(&self, title: Option<String>);
/// Called when the browser chrome should display a status message.
fn status(&self, Option<String>);
/// Called when the browser has started loading a frame.
fn load_start(&self);
/// Called when the browser is done loading a frame.
fn load_end(&self);
/// Called when the browser encounters an error while loading a URL
fn load_error(&self, code: NetError, url: String);
/// Wether or not to follow a link
fn allow_navigation(&self, url: ServoUrl) -> bool;
/// Called when the <head> tag has finished parsing
fn head_parsed(&self);
/// Called when the history state has changed.
fn history_changed(&self, Vec<LoadData>, usize);
/// Returns the scale factor of the system (device pixels / device independent pixels).
fn hidpi_factor(&self) -> ScaleFactor<f32, DeviceIndependentPixel, DevicePixel>;
/// Creates a channel to the compositor. The dummy parameter is needed because we don't have
/// UFCS in Rust yet.
///
/// This is part of the windowing system because its implementation often involves OS-specific
/// magic to wake the up window's event loop.
fn create_compositor_channel(&self) -> (Box<CompositorProxy + Send>, Box<CompositorReceiver>);
/// Requests that the window system prepare a composite. Typically this will involve making
/// some type of platform-specific graphics context current. Returns true if the composite may
/// proceed and false if it should not.
fn prepare_for_composite(&self, width: usize, height: usize) -> bool;
/// Sets the cursor to be used in the window.
fn set_cursor(&self, cursor: Cursor);
/// Process a key event.
fn handle_key(&self, ch: Option<char>, key: Key, mods: KeyModifiers);
/// Does this window support a clipboard
fn supports_clipboard(&self) -> bool;
/// Add a favicon
fn set_favicon(&self, url: ServoUrl);
/// Return the GL function pointer trait.
fn gl(&self) -> Rc<gl::Gl>;
} | random_line_split |
|
from_form.rs | use request::FormItems;
/// Trait to create an instance of some type from an HTTP form. The
/// [Form](struct.Form.html) type requires that its generic parameter implements
/// this trait.
///
/// This trait can be automatically derived via the
/// [rocket_codegen](/rocket_codegen) plugin:
///
/// ```rust
/// #![feature(plugin, custom_derive)]
/// #![plugin(rocket_codegen)]
///
/// extern crate rocket;
///
/// #[derive(FromForm)]
/// struct TodoTask {
/// description: String,
/// completed: bool
/// }
/// ```
///
/// The type can then be parsed from incoming form data via the `data`
/// parameter and `Form` type.
///
/// ```rust
/// # #![feature(plugin, custom_derive)]
/// # #![plugin(rocket_codegen)]
/// # extern crate rocket;
/// # use rocket::request::Form;
/// # #[derive(FromForm)]
/// # struct TodoTask { description: String, completed: bool }
/// #[post("/submit", data = "<task>")]
/// fn submit_task(task: Form<TodoTask>) -> String {
/// format!("New task: {}", task.get().description)
/// }
/// # fn main() { }
/// ```
///
/// When deriving `FromForm`, every field in the structure must implement
/// [FromFormValue](trait.FromFormValue.html).
///
/// # Implementing
///
/// If you implement `FormForm` yourself, use the | /// [FormItems](struct.FormItems.html) iterator to iterate through the form
/// key/value pairs. Be aware that form fields that are typically hidden from
/// your application, such as `_method`, will be present while iterating.
pub trait FromForm<'f>: Sized {
/// The associated error to be returned when parsing fails.
type Error;
/// Parses an instance of `Self` from a raw HTTP form string
/// (`application/x-www-form-urlencoded data`) or returns an `Error` if one
/// cannot be parsed.
fn from_form_items(form_items: &mut FormItems<'f>) -> Result<Self, Self::Error>;
}
/// This implementation should only be used during debugging!
impl<'f> FromForm<'f> for &'f str {
type Error = ();
fn from_form_items(items: &mut FormItems<'f>) -> Result<Self, Self::Error> {
items.mark_complete();
Ok(items.inner_str())
}
} | random_line_split |
|
from_form.rs | use request::FormItems;
/// Trait to create an instance of some type from an HTTP form. The
/// [Form](struct.Form.html) type requires that its generic parameter implements
/// this trait.
///
/// This trait can be automatically derived via the
/// [rocket_codegen](/rocket_codegen) plugin:
///
/// ```rust
/// #![feature(plugin, custom_derive)]
/// #![plugin(rocket_codegen)]
///
/// extern crate rocket;
///
/// #[derive(FromForm)]
/// struct TodoTask {
/// description: String,
/// completed: bool
/// }
/// ```
///
/// The type can then be parsed from incoming form data via the `data`
/// parameter and `Form` type.
///
/// ```rust
/// # #![feature(plugin, custom_derive)]
/// # #![plugin(rocket_codegen)]
/// # extern crate rocket;
/// # use rocket::request::Form;
/// # #[derive(FromForm)]
/// # struct TodoTask { description: String, completed: bool }
/// #[post("/submit", data = "<task>")]
/// fn submit_task(task: Form<TodoTask>) -> String {
/// format!("New task: {}", task.get().description)
/// }
/// # fn main() { }
/// ```
///
/// When deriving `FromForm`, every field in the structure must implement
/// [FromFormValue](trait.FromFormValue.html).
///
/// # Implementing
///
/// If you implement `FormForm` yourself, use the
/// [FormItems](struct.FormItems.html) iterator to iterate through the form
/// key/value pairs. Be aware that form fields that are typically hidden from
/// your application, such as `_method`, will be present while iterating.
pub trait FromForm<'f>: Sized {
/// The associated error to be returned when parsing fails.
type Error;
/// Parses an instance of `Self` from a raw HTTP form string
/// (`application/x-www-form-urlencoded data`) or returns an `Error` if one
/// cannot be parsed.
fn from_form_items(form_items: &mut FormItems<'f>) -> Result<Self, Self::Error>;
}
/// This implementation should only be used during debugging!
impl<'f> FromForm<'f> for &'f str {
type Error = ();
fn from_form_items(items: &mut FormItems<'f>) -> Result<Self, Self::Error> |
}
| {
items.mark_complete();
Ok(items.inner_str())
} | identifier_body |
from_form.rs | use request::FormItems;
/// Trait to create an instance of some type from an HTTP form. The
/// [Form](struct.Form.html) type requires that its generic parameter implements
/// this trait.
///
/// This trait can be automatically derived via the
/// [rocket_codegen](/rocket_codegen) plugin:
///
/// ```rust
/// #![feature(plugin, custom_derive)]
/// #![plugin(rocket_codegen)]
///
/// extern crate rocket;
///
/// #[derive(FromForm)]
/// struct TodoTask {
/// description: String,
/// completed: bool
/// }
/// ```
///
/// The type can then be parsed from incoming form data via the `data`
/// parameter and `Form` type.
///
/// ```rust
/// # #![feature(plugin, custom_derive)]
/// # #![plugin(rocket_codegen)]
/// # extern crate rocket;
/// # use rocket::request::Form;
/// # #[derive(FromForm)]
/// # struct TodoTask { description: String, completed: bool }
/// #[post("/submit", data = "<task>")]
/// fn submit_task(task: Form<TodoTask>) -> String {
/// format!("New task: {}", task.get().description)
/// }
/// # fn main() { }
/// ```
///
/// When deriving `FromForm`, every field in the structure must implement
/// [FromFormValue](trait.FromFormValue.html).
///
/// # Implementing
///
/// If you implement `FormForm` yourself, use the
/// [FormItems](struct.FormItems.html) iterator to iterate through the form
/// key/value pairs. Be aware that form fields that are typically hidden from
/// your application, such as `_method`, will be present while iterating.
pub trait FromForm<'f>: Sized {
/// The associated error to be returned when parsing fails.
type Error;
/// Parses an instance of `Self` from a raw HTTP form string
/// (`application/x-www-form-urlencoded data`) or returns an `Error` if one
/// cannot be parsed.
fn from_form_items(form_items: &mut FormItems<'f>) -> Result<Self, Self::Error>;
}
/// This implementation should only be used during debugging!
impl<'f> FromForm<'f> for &'f str {
type Error = ();
fn | (items: &mut FormItems<'f>) -> Result<Self, Self::Error> {
items.mark_complete();
Ok(items.inner_str())
}
}
| from_form_items | identifier_name |
workernavigator.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::WorkerNavigatorBinding;
use dom::bindings::codegen::Bindings::WorkerNavigatorBinding::WorkerNavigatorMethods;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::navigatorinfo;
use dom::workerglobalscope::WorkerGlobalScope;
// https://html.spec.whatwg.org/multipage/#workernavigator
#[dom_struct]
pub struct WorkerNavigator {
reflector_: Reflector,
}
impl WorkerNavigator {
fn new_inherited() -> WorkerNavigator {
WorkerNavigator {
reflector_: Reflector::new(),
}
}
pub fn new(global: &WorkerGlobalScope) -> Root<WorkerNavigator> {
reflect_dom_object(box WorkerNavigator::new_inherited(),
global,
WorkerNavigatorBinding::Wrap)
}
}
impl WorkerNavigatorMethods for WorkerNavigator {
// https://html.spec.whatwg.org/multipage/#dom-navigator-product
fn Product(&self) -> DOMString {
navigatorinfo::Product()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled |
// https://html.spec.whatwg.org/multipage/#dom-navigator-appname
fn AppName(&self) -> DOMString {
navigatorinfo::AppName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename
fn AppCodeName(&self) -> DOMString {
navigatorinfo::AppCodeName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-platform
fn Platform(&self) -> DOMString {
navigatorinfo::Platform()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-useragent
fn UserAgent(&self) -> DOMString {
navigatorinfo::UserAgent()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appversion
fn AppVersion(&self) -> DOMString {
navigatorinfo::AppVersion()
}
// https://html.spec.whatwg.org/multipage/#navigatorlanguage
fn Language(&self) -> DOMString {
navigatorinfo::Language()
}
} | fn TaintEnabled(&self) -> bool {
navigatorinfo::TaintEnabled()
} | random_line_split |
workernavigator.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::WorkerNavigatorBinding;
use dom::bindings::codegen::Bindings::WorkerNavigatorBinding::WorkerNavigatorMethods;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::navigatorinfo;
use dom::workerglobalscope::WorkerGlobalScope;
// https://html.spec.whatwg.org/multipage/#workernavigator
#[dom_struct]
pub struct WorkerNavigator {
reflector_: Reflector,
}
impl WorkerNavigator {
fn new_inherited() -> WorkerNavigator |
pub fn new(global: &WorkerGlobalScope) -> Root<WorkerNavigator> {
reflect_dom_object(box WorkerNavigator::new_inherited(),
global,
WorkerNavigatorBinding::Wrap)
}
}
impl WorkerNavigatorMethods for WorkerNavigator {
// https://html.spec.whatwg.org/multipage/#dom-navigator-product
fn Product(&self) -> DOMString {
navigatorinfo::Product()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled
fn TaintEnabled(&self) -> bool {
navigatorinfo::TaintEnabled()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appname
fn AppName(&self) -> DOMString {
navigatorinfo::AppName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename
fn AppCodeName(&self) -> DOMString {
navigatorinfo::AppCodeName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-platform
fn Platform(&self) -> DOMString {
navigatorinfo::Platform()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-useragent
fn UserAgent(&self) -> DOMString {
navigatorinfo::UserAgent()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appversion
fn AppVersion(&self) -> DOMString {
navigatorinfo::AppVersion()
}
// https://html.spec.whatwg.org/multipage/#navigatorlanguage
fn Language(&self) -> DOMString {
navigatorinfo::Language()
}
}
| {
WorkerNavigator {
reflector_: Reflector::new(),
}
} | identifier_body |
workernavigator.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::WorkerNavigatorBinding;
use dom::bindings::codegen::Bindings::WorkerNavigatorBinding::WorkerNavigatorMethods;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
use dom::navigatorinfo;
use dom::workerglobalscope::WorkerGlobalScope;
// https://html.spec.whatwg.org/multipage/#workernavigator
#[dom_struct]
pub struct WorkerNavigator {
reflector_: Reflector,
}
impl WorkerNavigator {
fn new_inherited() -> WorkerNavigator {
WorkerNavigator {
reflector_: Reflector::new(),
}
}
pub fn new(global: &WorkerGlobalScope) -> Root<WorkerNavigator> {
reflect_dom_object(box WorkerNavigator::new_inherited(),
global,
WorkerNavigatorBinding::Wrap)
}
}
impl WorkerNavigatorMethods for WorkerNavigator {
// https://html.spec.whatwg.org/multipage/#dom-navigator-product
fn Product(&self) -> DOMString {
navigatorinfo::Product()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-taintenabled
fn TaintEnabled(&self) -> bool {
navigatorinfo::TaintEnabled()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appname
fn AppName(&self) -> DOMString {
navigatorinfo::AppName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appcodename
fn AppCodeName(&self) -> DOMString {
navigatorinfo::AppCodeName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-platform
fn | (&self) -> DOMString {
navigatorinfo::Platform()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-useragent
fn UserAgent(&self) -> DOMString {
navigatorinfo::UserAgent()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-appversion
fn AppVersion(&self) -> DOMString {
navigatorinfo::AppVersion()
}
// https://html.spec.whatwg.org/multipage/#navigatorlanguage
fn Language(&self) -> DOMString {
navigatorinfo::Language()
}
}
| Platform | identifier_name |
checks.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/. */
//! Different checks done during the style sharing process in order to determine
//! quickly whether it's worth to share style, and whether two different
//! elements can indeed share the same style.
use bloom::StyleBloom;
use context::{SelectorFlagsMap, SharedStyleContext};
use dom::TElement;
use selectors::NthIndexCache;
use sharing::{StyleSharingCandidate, StyleSharingTarget};
/// Determines whether a target and a candidate have compatible parents for
/// sharing.
pub fn parents_allow_sharing<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>
) -> bool
where
E: TElement,
{
// If the identity of the parent style isn't equal, we can't share. We check
// this first, because the result is cached.
if target.parent_style_identity()!= candidate.parent_style_identity() {
return false;
}
// Siblings can always share.
let parent = target.inheritance_parent().unwrap();
let candidate_parent = candidate.element.inheritance_parent().unwrap();
if parent == candidate_parent {
return true;
}
// Cousins are a bit more complicated.
//
// If a parent element was already styled and we traversed past it without
// restyling it, that may be because our clever invalidation logic was able
// to prove that the styles of that element would remain unchanged despite
// changes to the id or class attributes. However, style sharing relies in
// the strong guarantee that all the classes and ids up the respective parent
// chains are identical. As such, if we skipped styling for one (or both) of
// the parents on this traversal, we can't share styles across cousins.
//
// This is a somewhat conservative check. We could tighten it by having the
// invalidation logic explicitly flag elements for which it ellided styling.
let parent_data = parent.borrow_data().unwrap();
let candidate_parent_data = candidate_parent.borrow_data().unwrap();
if!parent_data.safe_for_cousin_sharing() ||!candidate_parent_data.safe_for_cousin_sharing() {
return false;
}
true
}
/// Whether two elements have the same same style attribute (by pointer identity).
pub fn have_same_style_attribute<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>
) -> bool
where
E: TElement,
|
/// Whether two elements have the same same presentational attributes.
pub fn have_same_presentational_hints<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>
) -> bool
where
E: TElement,
{
target.pres_hints() == candidate.pres_hints()
}
/// Whether a given element has the same class attribute than a given candidate.
///
/// We don't try to share style across elements with different class attributes.
pub fn have_same_class<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>,
) -> bool
where
E: TElement,
{
target.class_list() == candidate.class_list()
}
/// Whether a given element and a candidate match the same set of "revalidation"
/// selectors.
///
/// Revalidation selectors are those that depend on the DOM structure, like
/// :first-child, etc, or on attributes that we don't check off-hand (pretty
/// much every attribute selector except `id` and `class`.
#[inline]
pub fn revalidate<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>,
shared_context: &SharedStyleContext,
bloom: &StyleBloom<E>,
nth_index_cache: &mut NthIndexCache,
selector_flags_map: &mut SelectorFlagsMap<E>,
) -> bool
where
E: TElement,
{
let stylist = &shared_context.stylist;
let for_element = target.revalidation_match_results(
stylist,
bloom,
nth_index_cache,
selector_flags_map,
);
let for_candidate = candidate.revalidation_match_results(
stylist,
bloom,
nth_index_cache,
);
// This assert "ensures", to some extent, that the two candidates have
// matched the same rulehash buckets, and as such, that the bits we're
// comparing represent the same set of selectors.
debug_assert_eq!(for_element.len(), for_candidate.len());
for_element == for_candidate
}
/// Checks whether we might have rules for either of the two ids.
#[inline]
pub fn may_match_different_id_rules<E>(
shared_context: &SharedStyleContext,
element: E,
candidate: E,
) -> bool
where
E: TElement,
{
let element_id = element.id();
let candidate_id = candidate.id();
if element_id == candidate_id {
return false;
}
let stylist = &shared_context.stylist;
let may_have_rules_for_element = match element_id {
Some(id) => stylist.may_have_rules_for_id(id, element),
None => false
};
if may_have_rules_for_element {
return true;
}
match candidate_id {
Some(id) => stylist.may_have_rules_for_id(id, candidate),
None => false
}
}
| {
match (target.style_attribute(), candidate.style_attribute()) {
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
(Some(a), Some(b)) => &*a as *const _ == &*b as *const _
}
} | identifier_body |
checks.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/. */
//! Different checks done during the style sharing process in order to determine
//! quickly whether it's worth to share style, and whether two different
//! elements can indeed share the same style.
use bloom::StyleBloom;
use context::{SelectorFlagsMap, SharedStyleContext};
use dom::TElement;
use selectors::NthIndexCache;
use sharing::{StyleSharingCandidate, StyleSharingTarget};
/// Determines whether a target and a candidate have compatible parents for
/// sharing.
pub fn parents_allow_sharing<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>
) -> bool
where
E: TElement,
{
// If the identity of the parent style isn't equal, we can't share. We check
// this first, because the result is cached.
if target.parent_style_identity()!= candidate.parent_style_identity() {
return false;
}
// Siblings can always share.
let parent = target.inheritance_parent().unwrap();
let candidate_parent = candidate.element.inheritance_parent().unwrap();
if parent == candidate_parent {
return true;
}
// Cousins are a bit more complicated.
//
// If a parent element was already styled and we traversed past it without
// restyling it, that may be because our clever invalidation logic was able
// to prove that the styles of that element would remain unchanged despite
// changes to the id or class attributes. However, style sharing relies in
// the strong guarantee that all the classes and ids up the respective parent
// chains are identical. As such, if we skipped styling for one (or both) of
// the parents on this traversal, we can't share styles across cousins.
//
// This is a somewhat conservative check. We could tighten it by having the
// invalidation logic explicitly flag elements for which it ellided styling.
let parent_data = parent.borrow_data().unwrap();
let candidate_parent_data = candidate_parent.borrow_data().unwrap();
if!parent_data.safe_for_cousin_sharing() ||!candidate_parent_data.safe_for_cousin_sharing() {
return false;
}
true
}
/// Whether two elements have the same same style attribute (by pointer identity).
pub fn have_same_style_attribute<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>
) -> bool
where
E: TElement,
{
match (target.style_attribute(), candidate.style_attribute()) {
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
(Some(a), Some(b)) => &*a as *const _ == &*b as *const _ | }
}
/// Whether two elements have the same same presentational attributes.
pub fn have_same_presentational_hints<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>
) -> bool
where
E: TElement,
{
target.pres_hints() == candidate.pres_hints()
}
/// Whether a given element has the same class attribute than a given candidate.
///
/// We don't try to share style across elements with different class attributes.
pub fn have_same_class<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>,
) -> bool
where
E: TElement,
{
target.class_list() == candidate.class_list()
}
/// Whether a given element and a candidate match the same set of "revalidation"
/// selectors.
///
/// Revalidation selectors are those that depend on the DOM structure, like
/// :first-child, etc, or on attributes that we don't check off-hand (pretty
/// much every attribute selector except `id` and `class`.
#[inline]
pub fn revalidate<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>,
shared_context: &SharedStyleContext,
bloom: &StyleBloom<E>,
nth_index_cache: &mut NthIndexCache,
selector_flags_map: &mut SelectorFlagsMap<E>,
) -> bool
where
E: TElement,
{
let stylist = &shared_context.stylist;
let for_element = target.revalidation_match_results(
stylist,
bloom,
nth_index_cache,
selector_flags_map,
);
let for_candidate = candidate.revalidation_match_results(
stylist,
bloom,
nth_index_cache,
);
// This assert "ensures", to some extent, that the two candidates have
// matched the same rulehash buckets, and as such, that the bits we're
// comparing represent the same set of selectors.
debug_assert_eq!(for_element.len(), for_candidate.len());
for_element == for_candidate
}
/// Checks whether we might have rules for either of the two ids.
#[inline]
pub fn may_match_different_id_rules<E>(
shared_context: &SharedStyleContext,
element: E,
candidate: E,
) -> bool
where
E: TElement,
{
let element_id = element.id();
let candidate_id = candidate.id();
if element_id == candidate_id {
return false;
}
let stylist = &shared_context.stylist;
let may_have_rules_for_element = match element_id {
Some(id) => stylist.may_have_rules_for_id(id, element),
None => false
};
if may_have_rules_for_element {
return true;
}
match candidate_id {
Some(id) => stylist.may_have_rules_for_id(id, candidate),
None => false
}
} | random_line_split |
|
checks.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/. */
//! Different checks done during the style sharing process in order to determine
//! quickly whether it's worth to share style, and whether two different
//! elements can indeed share the same style.
use bloom::StyleBloom;
use context::{SelectorFlagsMap, SharedStyleContext};
use dom::TElement;
use selectors::NthIndexCache;
use sharing::{StyleSharingCandidate, StyleSharingTarget};
/// Determines whether a target and a candidate have compatible parents for
/// sharing.
pub fn parents_allow_sharing<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>
) -> bool
where
E: TElement,
{
// If the identity of the parent style isn't equal, we can't share. We check
// this first, because the result is cached.
if target.parent_style_identity()!= candidate.parent_style_identity() {
return false;
}
// Siblings can always share.
let parent = target.inheritance_parent().unwrap();
let candidate_parent = candidate.element.inheritance_parent().unwrap();
if parent == candidate_parent {
return true;
}
// Cousins are a bit more complicated.
//
// If a parent element was already styled and we traversed past it without
// restyling it, that may be because our clever invalidation logic was able
// to prove that the styles of that element would remain unchanged despite
// changes to the id or class attributes. However, style sharing relies in
// the strong guarantee that all the classes and ids up the respective parent
// chains are identical. As such, if we skipped styling for one (or both) of
// the parents on this traversal, we can't share styles across cousins.
//
// This is a somewhat conservative check. We could tighten it by having the
// invalidation logic explicitly flag elements for which it ellided styling.
let parent_data = parent.borrow_data().unwrap();
let candidate_parent_data = candidate_parent.borrow_data().unwrap();
if!parent_data.safe_for_cousin_sharing() ||!candidate_parent_data.safe_for_cousin_sharing() {
return false;
}
true
}
/// Whether two elements have the same same style attribute (by pointer identity).
pub fn have_same_style_attribute<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>
) -> bool
where
E: TElement,
{
match (target.style_attribute(), candidate.style_attribute()) {
(None, None) => true,
(Some(_), None) | (None, Some(_)) => false,
(Some(a), Some(b)) => &*a as *const _ == &*b as *const _
}
}
/// Whether two elements have the same same presentational attributes.
pub fn have_same_presentational_hints<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>
) -> bool
where
E: TElement,
{
target.pres_hints() == candidate.pres_hints()
}
/// Whether a given element has the same class attribute than a given candidate.
///
/// We don't try to share style across elements with different class attributes.
pub fn | <E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>,
) -> bool
where
E: TElement,
{
target.class_list() == candidate.class_list()
}
/// Whether a given element and a candidate match the same set of "revalidation"
/// selectors.
///
/// Revalidation selectors are those that depend on the DOM structure, like
/// :first-child, etc, or on attributes that we don't check off-hand (pretty
/// much every attribute selector except `id` and `class`.
#[inline]
pub fn revalidate<E>(
target: &mut StyleSharingTarget<E>,
candidate: &mut StyleSharingCandidate<E>,
shared_context: &SharedStyleContext,
bloom: &StyleBloom<E>,
nth_index_cache: &mut NthIndexCache,
selector_flags_map: &mut SelectorFlagsMap<E>,
) -> bool
where
E: TElement,
{
let stylist = &shared_context.stylist;
let for_element = target.revalidation_match_results(
stylist,
bloom,
nth_index_cache,
selector_flags_map,
);
let for_candidate = candidate.revalidation_match_results(
stylist,
bloom,
nth_index_cache,
);
// This assert "ensures", to some extent, that the two candidates have
// matched the same rulehash buckets, and as such, that the bits we're
// comparing represent the same set of selectors.
debug_assert_eq!(for_element.len(), for_candidate.len());
for_element == for_candidate
}
/// Checks whether we might have rules for either of the two ids.
#[inline]
pub fn may_match_different_id_rules<E>(
shared_context: &SharedStyleContext,
element: E,
candidate: E,
) -> bool
where
E: TElement,
{
let element_id = element.id();
let candidate_id = candidate.id();
if element_id == candidate_id {
return false;
}
let stylist = &shared_context.stylist;
let may_have_rules_for_element = match element_id {
Some(id) => stylist.may_have_rules_for_id(id, element),
None => false
};
if may_have_rules_for_element {
return true;
}
match candidate_id {
Some(id) => stylist.may_have_rules_for_id(id, candidate),
None => false
}
}
| have_same_class | identifier_name |
recursion_limit_deref.rs | // Test that the recursion limit can be changed and that the compiler
// suggests a fix. In this case, we have a long chain of Deref impls
// which will cause an overflow during the autoderef loop.
#![allow(dead_code)]
#![recursion_limit="10"]
macro_rules! link {
($outer:ident, $inner:ident) => {
struct $outer($inner);
impl $outer {
fn new() -> $outer {
$outer($inner::new())
}
}
impl std::ops::Deref for $outer {
type Target = $inner;
fn deref(&self) -> &$inner {
&self.0
}
}
}
}
struct | ;
impl Bottom {
fn new() -> Bottom {
Bottom
}
}
link!(Top, A);
link!(A, B);
link!(B, C);
link!(C, D);
link!(D, E);
link!(E, F);
link!(F, G);
link!(G, H);
link!(H, I);
link!(I, J);
link!(J, K);
link!(K, Bottom);
fn main() {
let t = Top::new();
let x: &Bottom = &t; //~ ERROR mismatched types
//~^ error recursion limit
}
| Bottom | identifier_name |
recursion_limit_deref.rs | // Test that the recursion limit can be changed and that the compiler
// suggests a fix. In this case, we have a long chain of Deref impls
// which will cause an overflow during the autoderef loop.
#![allow(dead_code)]
#![recursion_limit="10"]
macro_rules! link {
($outer:ident, $inner:ident) => {
struct $outer($inner);
impl $outer {
fn new() -> $outer {
$outer($inner::new())
}
}
impl std::ops::Deref for $outer {
type Target = $inner;
fn deref(&self) -> &$inner {
&self.0
}
}
}
}
struct Bottom;
impl Bottom {
fn new() -> Bottom {
Bottom
}
}
link!(Top, A);
link!(A, B);
link!(B, C);
link!(C, D);
link!(D, E);
link!(E, F);
link!(F, G);
link!(G, H);
link!(H, I);
link!(I, J);
link!(J, K);
link!(K, Bottom);
fn main() | {
let t = Top::new();
let x: &Bottom = &t; //~ ERROR mismatched types
//~^ error recursion limit
} | identifier_body |
|
recursion_limit_deref.rs | // Test that the recursion limit can be changed and that the compiler
// suggests a fix. In this case, we have a long chain of Deref impls
// which will cause an overflow during the autoderef loop.
#![allow(dead_code)]
#![recursion_limit="10"]
macro_rules! link {
($outer:ident, $inner:ident) => {
struct $outer($inner);
impl $outer {
fn new() -> $outer {
$outer($inner::new())
}
}
| &self.0
}
}
}
}
struct Bottom;
impl Bottom {
fn new() -> Bottom {
Bottom
}
}
link!(Top, A);
link!(A, B);
link!(B, C);
link!(C, D);
link!(D, E);
link!(E, F);
link!(F, G);
link!(G, H);
link!(H, I);
link!(I, J);
link!(J, K);
link!(K, Bottom);
fn main() {
let t = Top::new();
let x: &Bottom = &t; //~ ERROR mismatched types
//~^ error recursion limit
} | impl std::ops::Deref for $outer {
type Target = $inner;
fn deref(&self) -> &$inner { | random_line_split |
lib.rs | // ================================================================= | //
// 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>AWS Transfer Family is a fully managed service that enables the transfer of files over the File Transfer Protocol (FTP), File Transfer Protocol over SSL (FTPS), or Secure Shell (SSH) File Transfer Protocol (SFTP) directly into and out of Amazon Simple Storage Service (Amazon S3). AWS helps you seamlessly migrate your file transfer workflows to AWS Transfer Family by integrating with existing authentication systems, and providing DNS routing with Amazon Route 53 so nothing changes for your customers and partners, or their applications. With your data in Amazon S3, you can use it with AWS services for processing, analytics, machine learning, and archiving. Getting started with AWS Transfer Family is easy since there is no infrastructure to buy and set up.</p>
//!
//! If you're using the service, you're probably looking for [TransferClient](struct.TransferClient.html) and [Transfer](trait.Transfer.html).
mod custom;
mod generated;
pub use custom::*;
pub use generated::*; | //
// * WARNING *
//
// This file is generated! | random_line_split |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations
// Borrowing Aliasing in Rust
struct Point { x: i32, y: i32, z: i32 }
fn ma | {
let mut point = Point { x: 0, y: 0, z: 0 };
{
let borrowed_point = &point;
let another_borrow = &point;
// Data can be accessed via the references an the original owner
println!("Point has coordiantes: ({}, {}, {})",
borrowed_point.x, another_borrow.y, point.z);
// Error! Can't borrow point as mutable because it's currently
// borrowed as immutable.
//let mutable_borrow = &mut point;
// TODO ^ Try uncommenting this line
// Immutable references go out of scope
}
{
let mutable_borrow = &mut point;
// Change data via mutable reference
mutable_borrow.x = 5;
mutable_borrow.y = 2;
mutable_borrow.z = 1;
// Error! Can't borrow `point` as immutable because it's currently
// borrowed as mutable.
//let y = &point.y.
// TODO ^ Try uncommenting this line
// Error! Can't print because `println!` takes an immutable reference.
//println!("Point Z coordinate is {}", piont.z);
// TODO ^ Try uncommenting this line
// Ok! Mutable references can be passed as immutable to `println!`
println!("Point has coordiantes: ({}, {}, {})",
mutable_borrow.x, mutable_borrow.y, mutable_borrow.z);
// Mutable reference goes out of scope
}
// Immutable reference to point are allowed again
let borrowed_point = &point;
println!("Point now has coordinates: ({}, {}, {})",
borrowed_point.x, borrowed_point.y, borrowed_point.z);
}
| in() | identifier_name |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations
// Borrowing Aliasing in Rust
struct Point { x: i32, y: i32, z: i32 }
fn main() {
|
// Change data via mutable reference
mutable_borrow.x = 5;
mutable_borrow.y = 2;
mutable_borrow.z = 1;
// Error! Can't borrow `point` as immutable because it's currently
// borrowed as mutable.
//let y = &point.y.
// TODO ^ Try uncommenting this line
// Error! Can't print because `println!` takes an immutable reference.
//println!("Point Z coordinate is {}", piont.z);
// TODO ^ Try uncommenting this line
// Ok! Mutable references can be passed as immutable to `println!`
println!("Point has coordiantes: ({}, {}, {})",
mutable_borrow.x, mutable_borrow.y, mutable_borrow.z);
// Mutable reference goes out of scope
}
// Immutable reference to point are allowed again
let borrowed_point = &point;
println!("Point now has coordinates: ({}, {}, {})",
borrowed_point.x, borrowed_point.y, borrowed_point.z);
}
| let mut point = Point { x: 0, y: 0, z: 0 };
{
let borrowed_point = &point;
let another_borrow = &point;
// Data can be accessed via the references an the original owner
println!("Point has coordiantes: ({}, {}, {})",
borrowed_point.x, another_borrow.y, point.z);
// Error! Can't borrow point as mutable because it's currently
// borrowed as immutable.
//let mutable_borrow = &mut point;
// TODO ^ Try uncommenting this line
// Immutable references go out of scope
}
{
let mutable_borrow = &mut point; | identifier_body |
main.rs | /* Aurélien DESBRIÈRES
aurelien(at)hackers(dot)camp
License GNU GPL latest */
// Rust experimentations
// Borrowing Aliasing in Rust
struct Point { x: i32, y: i32, z: i32 }
fn main() {
let mut point = Point { x: 0, y: 0, z: 0 };
{
let borrowed_point = &point;
let another_borrow = &point;
// Data can be accessed via the references an the original owner
println!("Point has coordiantes: ({}, {}, {})",
borrowed_point.x, another_borrow.y, point.z);
// Error! Can't borrow point as mutable because it's currently
// borrowed as immutable.
//let mutable_borrow = &mut point;
// TODO ^ Try uncommenting this line
// Immutable references go out of scope
}
| mutable_borrow.x = 5;
mutable_borrow.y = 2;
mutable_borrow.z = 1;
// Error! Can't borrow `point` as immutable because it's currently
// borrowed as mutable.
//let y = &point.y.
// TODO ^ Try uncommenting this line
// Error! Can't print because `println!` takes an immutable reference.
//println!("Point Z coordinate is {}", piont.z);
// TODO ^ Try uncommenting this line
// Ok! Mutable references can be passed as immutable to `println!`
println!("Point has coordiantes: ({}, {}, {})",
mutable_borrow.x, mutable_borrow.y, mutable_borrow.z);
// Mutable reference goes out of scope
}
// Immutable reference to point are allowed again
let borrowed_point = &point;
println!("Point now has coordinates: ({}, {}, {})",
borrowed_point.x, borrowed_point.y, borrowed_point.z);
} | {
let mutable_borrow = &mut point;
// Change data via mutable reference | random_line_split |
typing.rs | use std::sync::Arc;
#[cfg(all(feature = "tokio_compat", not(feature = "tokio")))]
use tokio::time::delay_for as sleep;
#[cfg(feature = "tokio")]
use tokio::time::sleep;
use tokio::{
sync::oneshot::{self, error::TryRecvError, Sender},
time::Duration,
};
use crate::{error::Result, http::Http};
/// A struct to start typing in a [`Channel`] for an indefinite period of time.
///
/// It indicates that the current user is currently typing in the channel.
///
/// Typing is started by using the [`Typing::start`] method
/// and stopped by using the [`Typing::stop`] method.
/// Note that on some clients, typing may persist for a few seconds after [`Typing::stop`] is called.
/// Typing is also stopped when the struct is dropped.
///
/// If a message is sent while typing is triggered, the user will stop typing for a brief period
/// of time and then resume again until either [`Typing::stop`] is called or the struct is dropped.
///
/// This should rarely be used for bots, although it is a good indicator that a
/// long-running command is still being processed.
///
/// ## Examples
///
/// ```rust,no_run
/// # use serenity::{http::{Http, Typing}, Result};
/// # use std::sync::Arc;
/// #
/// # fn long_process() {}
/// # fn main() -> Result<()> {
/// # let http = Http::default();
/// // Initiate typing (assuming `http` is bound)
/// let typing = Typing::start(Arc::new(http), 7)?;
///
/// // Run some long-running process
/// long_process();
///
/// // Stop typing
/// typing.stop();
/// #
/// # Ok(())
/// # }
/// ```
///
/// [`Channel`]: crate::model::channel::Channel
#[derive(Debug)]
pub struct | (Sender<()>);
impl Typing {
/// Starts typing in the specified [`Channel`] for an indefinite period of time.
///
/// Returns [`Typing`]. To stop typing, you must call the [`Typing::stop`] method on
/// the returned [`Typing`] object or wait for it to be dropped. Note that on some
/// clients, typing may persist for a few seconds after stopped.
///
/// # Errors
///
/// Returns an [`Error::Http`] if there is an error.
///
/// [`Channel`]: crate::model::channel::Channel
/// [`Error::Http`]: crate::error::Error::Http
pub fn start(http: Arc<Http>, channel_id: u64) -> Result<Self> {
let (sx, mut rx) = oneshot::channel();
tokio::spawn(async move {
loop {
match rx.try_recv() {
Ok(_) | Err(TryRecvError::Closed) => break,
_ => (),
}
http.broadcast_typing(channel_id).await?;
// It is unclear for how long typing persists after this method is called.
// It is generally assumed to be 7 or 10 seconds, so we use 7 to be safe.
sleep(Duration::from_secs(7)).await;
}
Result::Ok(())
});
Ok(Self(sx))
}
/// Stops typing in [`Channel`].
///
/// This should be used to stop typing after it is started using [`Typing::start`].
/// Typing may persist for a few seconds on some clients after this is called.
///
/// [`Channel`]: crate::model::channel::Channel
pub fn stop(self) -> Option<()> {
self.0.send(()).ok()
}
}
| Typing | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.