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 |
---|---|---|---|---|
visitor.rs
|
// Copyright 2016 Google Inc. All rights reserved.
//
// 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 kythe::corpus::Corpus;
use kythe::schema::{Complete, EdgeKind, Fact, NodeKind, VName};
use kythe::writer::EntryWriter;
use rustc::hir;
use rustc::hir::{Block, Expr, ImplItem, ItemId, Pat};
use rustc::hir::def_id::DefId;
use rustc::hir::Expr_::{ExprCall, ExprLoop, ExprMatch, ExprMethodCall, ExprPath};
use rustc::hir::intravisit::*;
use rustc::hir::MatchSource::ForLoopDesugar;
use rustc::lint::{LateContext, LintContext};
use rustc::ty::{MethodCall, TyCtxt};
use syntax::ast;
use syntax::codemap::{CodeMap, Pos, Span, Spanned};
/// Indexes all kythe entries except files
pub struct KytheVisitor<'a, 'tcx: 'a> {
pub writer: &'a Box<EntryWriter>,
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
pub codemap: &'a CodeMap,
pub corpus: &'a Corpus,
/// The vname of the parent item. The value changes as we recurse through the HIR, and is used
/// for childof relationships
parent_vname: Option<VName>,
}
impl<'a, 'tcx> KytheVisitor<'a, 'tcx> {
/// Creates a new KytheVisitor
pub fn new(writer: &'a Box<EntryWriter>,
corpus: &'a Corpus,
cx: &'a LateContext<'a, 'tcx>)
-> KytheVisitor<'a, 'tcx> {
KytheVisitor {
writer: writer,
tcx: cx.tcx,
codemap: cx.sess().codemap(),
corpus: corpus,
parent_vname: None,
}
}
/// Emits the appropriate node and facts for an anchor defined by a span
/// and returns the node's VName
fn anchor_from_span(&self, span: Span) -> VName {
let start = self.codemap.lookup_byte_offset(span.lo);
let end = self.codemap.lookup_byte_offset(span.hi);
let start_byte = start.pos.to_usize();
let end_byte = end.pos.to_usize();
self.anchor(&start.fm.name, start_byte, end_byte)
}
/// Emits the appropriate node and facts for an anchor defined as a substring within a span
/// and returns the node's VName
fn anchor_from_sub_span(&self, span: Span, sub: &str) -> Result<VName, String> {
let start = self.codemap.lookup_byte_offset(span.lo);
let snippet = match self.codemap.span_to_snippet(span) {
Ok(s) => s,
Err(e) => return Err(format!("{:?}", e)),
};
let sub_start = match snippet.find(sub) {
None => return Err(format!("Substring: '{}' not found in snippet '{}'", sub, snippet)),
Some(s) => s,
};
let start_byte = start.pos.to_usize() + sub_start;
let end_byte = start_byte + sub.len();
Ok(self.anchor(&start.fm.name, start_byte, end_byte))
}
/// Emits an anchor node based on the byte range provided
fn anchor(&self, file_name: &str, start_byte: usize, end_byte: usize) -> VName {
let vname = self.corpus.anchor_vname(file_name, start_byte, end_byte);
let start_str: String = start_byte.to_string();
let end_str: String = end_byte.to_string();
let file_vname = self.corpus.file_vname(&file_name);
self.writer.node(&vname, Fact::NodeKind, &NodeKind::Anchor);
self.writer.node(&vname, Fact::LocStart, &start_str);
self.writer.node(&vname, Fact::LocEnd, &end_str);
self.writer.edge(&vname, EdgeKind::ChildOf, &file_vname);
vname
}
/// Produces a vname unique to a given DefId
fn vname_from_defid(&self, def_id: DefId) -> VName {
let def_id_num = def_id.index.as_u32();
let var_name = self.tcx.absolute_item_path_str(def_id);
self.corpus.def_vname(&var_name, def_id_num)
}
/// Emits the appropriate ref/call and childof nodes for a function call
fn function_call(&self, call_node_id: ast::NodeId, callee_def_id: DefId) {
let call_span = self.tcx.map.span(call_node_id);
// The call anchor includes the subject (if function is a method) and the params
let call_anchor_vname = self.anchor_from_span(call_span);
let callee_vname = self.vname_from_defid(callee_def_id);
self.writer.edge(&call_anchor_vname, EdgeKind::RefCall, &callee_vname);
if let Some(ref parent_vname) = self.parent_vname {
self.writer.edge(&call_anchor_vname, EdgeKind::ChildOf, &parent_vname);
}
}
}
/// Tests whether a span is the result of macro expansion
fn is_from_macro(span: &Span) -> bool {
span.expn_id.into_u32()!= u32::max_value()
}
impl<'v, 'tcx: 'v> Visitor<'v> for KytheVisitor<'v, 'tcx> {
/// Enables recursing through nested items
fn visit_nested_item(&mut self, id: ItemId) {
let item = self.tcx.map.expect_item(id.id);
self.visit_item(item);
}
/// Captures variable bindings
fn visit_pat(&mut self, pat: &'v Pat) {
use rustc::hir::PatKind::Binding;
if let Binding(_, _, _) = pat.node {
if let Some(def) = self.tcx.expect_def_or_none(pat.id) {
let local_vname = self.vname_from_defid(def.def_id());
let anchor_vname = self.anchor_from_span(pat.span);
self.writer.edge(&anchor_vname, EdgeKind::DefinesBinding, &local_vname);
self.writer.node(&local_vname, Fact::NodeKind, &NodeKind::Variable);
}
}
walk_pat(self, pat);
}
/// Navigates the visitor around desugared for loops while hitting their important
/// components
fn visit_block(&mut self, block: &'v Block) {
// Desugaring for loops turns:
// [opt_ident]: for <pat> in <head> {
// <body>
// }
//
// into
//
// {
// let result = match ::std::iter::IntoIterator::into_iter(<head>) {
// mut iter => {
// [opt_ident]: loop {
// match ::std::iter::Iterator::next(&mut iter) {
// ::std::option::Option::Some(<pat>) => <body>,
// ::std::option::Option::None => break
// }
// }
// }
// };
// result
// }
//
// Here we check block contents to pick out <pat> <head> and <body>
use rustc::hir::Decl_::DeclLocal;
use rustc::hir::Stmt_::StmtDecl;
use rustc::hir::PatKind::TupleStruct;
if let [Spanned { node: StmtDecl(ref decl, _),.. }] = *block.stmts {
if let DeclLocal(ref local) = decl.node {
if let Some(ref expr) = local.init {
if let ExprMatch(ref base, ref outer_arms, ForLoopDesugar) = expr.node {
if let ExprCall(_, ref args) = base.node {
if let ExprLoop(ref block, _) = outer_arms[0].body.node {
if let Some(ref expr) = block.expr {
if let ExprMatch(_, ref arms, _) = expr.node {
if let TupleStruct(_, ref pats, _) = arms[0].pats[0].node {
// Walk the interesting parts of <head>
for a in args {
self.visit_expr(&a);
}
// Walk <pat>
self.visit_pat(&pats[0]);
// Walk <body>
self.visit_expr(&arms[0].body);
return;
}
}
}
}
}
}
}
}
}
walk_block(self, block);
}
/// Captures refs and ref/calls
fn visit_expr(&mut self, expr: &'v Expr) {
if is_from_macro(&expr.span) {
return walk_expr(self, expr);
}
match expr.node {
// Paths are static references to items (including static methods)
ExprPath(..) => {
if let Some(def) = self.tcx.expect_def_or_none(expr.id) {
let def_id = def.def_id();
let local_vname = self.vname_from_defid(def_id);
let anchor_vname = self.anchor_from_span(expr.span);
self.writer.edge(&anchor_vname, EdgeKind::Ref, &local_vname);
}
}
// Method calls are calls to any impl_fn that consumes self (requiring a vtable)
ExprMethodCall(sp_name, _, _) => {
let callee = self.tcx.tables.borrow().method_map[&MethodCall::expr(expr.id)];
let local_vname = self.vname_from_defid(callee.def_id);
let anchor_vname = self.anchor_from_span(sp_name.span);
self.function_call(expr.id, callee.def_id);
self.writer.edge(&anchor_vname, EdgeKind::Ref, &local_vname);
}
// Calls to statically addressable functions. The ref edge is handled in the ExprPath
// branch
ExprCall(ref fn_expr, _) => {
let callee = self.tcx.def_map.borrow()[&fn_expr.id].base_def;
self.function_call(expr.id, callee.def_id());
}
_ => (),
}
walk_expr(self, expr);
}
/// Captures function and method decl/bindings
fn visit_fn(&mut self,
kind: hir::intravisit::FnKind<'v>,
decl: &'v hir::FnDecl,
body: &'v hir::Block,
span: Span,
id: ast::NodeId) {
use rustc::hir::intravisit::FnKind;
match kind {
FnKind::ItemFn(n, _, _, _, _, _, _) |
FnKind::Method(n, _, _, _) => {
let fn_name = n.to_string();
let def_id = self.tcx.map.get_parent_did(body.id);
let fn_vname = self.vname_from_defid(def_id);
let decl_vname = self.anchor_from_span(span);
self.writer.node(&fn_vname, Fact::NodeKind, &NodeKind::Function);
self.writer.node(&fn_vname, Fact::Complete, &Complete::Definition);
self.writer.edge(&decl_vname, EdgeKind::Defines, &fn_vname);
if let Ok(bind_vname) = self.anchor_from_sub_span(span, &fn_name) {
self.writer.edge(&bind_vname, EdgeKind::DefinesBinding, &fn_vname)
}
}
_ => (),
};
walk_fn(self, kind, decl, body, span, id);
}
/// Called instead of visit_item for items inside an impl, this function sets the
/// parent_vname to the impl's vname
fn visit_impl_item(&mut self, impl_item: &'v ImplItem) {
let old_parent = self.parent_vname.clone();
let def_id = self.tcx.map.local_def_id(impl_item.id);
self.parent_vname = Some(self.vname_from_defid(def_id));
walk_impl_item(self, impl_item);
self.parent_vname = old_parent;
}
/// Run on every module-level item. Currently we only capture static and const items.
/// (Functions are handled in visit_fn)
fn visit_item(&mut self, item: &'v hir::Item)
|
// node or span for the item name
if let Ok(bind_vname) = self.anchor_from_sub_span(item.span, &def_name) {
self.writer.edge(&bind_vname, EdgeKind::DefinesBinding, &def_vname)
}
}
_ => (),
}
self.parent_vname = Some(self.vname_from_defid(def_id));
walk_item(self, item);
self.parent_vname = old_parent;
}
}
|
{
let old_parent = self.parent_vname.clone();
let def_id = self.tcx.map.local_def_id(item.id);
let def_name = item.name.to_string();
let def_vname = self.vname_from_defid(def_id);
use rustc::hir::Item_::*;
match item.node {
ItemStatic(..) | ItemConst(..) => {
let kind = if let ItemStatic(..) = item.node {
NodeKind::Variable
} else {
NodeKind::Constant
};
let anchor_vname = self.anchor_from_span(item.span);
self.writer.node(&def_vname, Fact::NodeKind, &kind);
self.writer.edge(&anchor_vname, EdgeKind::Defines, &def_vname);
// Substring matching is suboptimal, but there doesn't appear to be an accessible
|
identifier_body
|
closure.rs
|
use arena::TypedArena;
use back::link::{self, mangle_internal_name_by_path_and_seq};
use llvm::{ValueRef, get_params};
use middle::mem_categorization::Typer;
use trans::adt;
use trans::attributes;
use trans::base::*;
use trans::build::*;
use trans::callee::{self, ArgVals, Callee, TraitItem, MethodData};
use trans::cleanup::{CleanupMethods, CustomScope, ScopeId};
use trans::common::*;
use trans::datum::{self, Datum, rvalue_scratch_datum, Rvalue, ByValue};
use trans::debuginfo::{self, DebugLoc};
use trans::declare;
use trans::expr;
use trans::monomorphize::{self, MonoId};
use trans::type_of::*;
use middle::ty::{self, ClosureTyper};
use middle::subst::Substs;
use session::config::FullDebugInfo;
use syntax::abi::RustCall;
use syntax::ast;
use syntax::ast_util;
fn
|
<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
arg_scope_id: ScopeId,
freevars: &[ty::Freevar])
-> Block<'blk, 'tcx>
{
let _icx = push_ctxt("closure::load_closure_environment");
// Special case for small by-value selfs.
let closure_id = ast_util::local_def(bcx.fcx.id);
let self_type = self_type_for_closure(bcx.ccx(), closure_id,
node_id_type(bcx, closure_id.node));
let kind = kind_for_closure(bcx.ccx(), closure_id);
let llenv = if kind == ty::FnOnceClosureKind &&
!arg_is_indirect(bcx.ccx(), self_type) {
let datum = rvalue_scratch_datum(bcx,
self_type,
"closure_env");
store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type);
datum.val
} else {
bcx.fcx.llenv.unwrap()
};
// Store the pointer to closure data in an alloca for debug info because that's what the
// llvm.dbg.declare intrinsic expects
let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
let alloc = alloca(bcx, val_ty(llenv), "__debuginfo_env_ptr");
Store(bcx, llenv, alloc);
Some(alloc)
} else {
None
};
for (i, freevar) in freevars.iter().enumerate() {
let upvar_id = ty::UpvarId { var_id: freevar.def.local_node_id(),
closure_expr_id: closure_id.node };
let upvar_capture = bcx.tcx().upvar_capture(upvar_id).unwrap();
let mut upvar_ptr = GEPi(bcx, llenv, &[0, i]);
let captured_by_ref = match upvar_capture {
ty::UpvarCapture::ByValue => false,
ty::UpvarCapture::ByRef(..) => {
upvar_ptr = Load(bcx, upvar_ptr);
true
}
};
let def_id = freevar.def.def_id();
bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr);
if kind == ty::FnOnceClosureKind &&!captured_by_ref {
bcx.fcx.schedule_drop_mem(arg_scope_id,
upvar_ptr,
node_id_type(bcx, def_id.node))
}
if let Some(env_pointer_alloca) = env_pointer_alloca {
debuginfo::create_captured_var_metadata(
bcx,
def_id.node,
env_pointer_alloca,
i,
captured_by_ref,
freevar.span);
}
}
bcx
}
pub enum ClosureEnv<'a> {
NotClosure,
Closure(&'a [ty::Freevar]),
}
impl<'a> ClosureEnv<'a> {
pub fn load<'blk,'tcx>(self, bcx: Block<'blk, 'tcx>, arg_scope: ScopeId)
-> Block<'blk, 'tcx>
{
match self {
ClosureEnv::NotClosure => bcx,
ClosureEnv::Closure(freevars) => {
if freevars.is_empty() {
bcx
} else {
load_closure_environment(bcx, arg_scope, freevars)
}
}
}
}
}
/// Returns the LLVM function declaration for a closure, creating it if
/// necessary. If the ID does not correspond to a closure ID, returns None.
pub fn get_or_create_declaration_if_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
closure_id: ast::DefId,
substs: &Substs<'tcx>)
-> Option<Datum<'tcx, Rvalue>> {
if!ccx.tcx().closure_kinds.borrow().contains_key(&closure_id) {
// Not a closure.
return None
}
let function_type = ccx.tcx().node_id_to_type(closure_id.node);
let function_type = monomorphize::apply_param_substs(ccx.tcx(), substs, &function_type);
// Normalize type so differences in regions and typedefs don't cause
// duplicate declarations
let function_type = erase_regions(ccx.tcx(), &function_type);
let params = match function_type.sty {
ty::TyClosure(_, substs) => &substs.types,
_ => unreachable!()
};
let mono_id = MonoId {
def: closure_id,
params: params
};
match ccx.closure_vals().borrow().get(&mono_id) {
Some(&llfn) => {
debug!("get_or_create_declaration_if_closure(): found closure {:?}: {:?}",
mono_id, ccx.tn().val_to_string(llfn));
return Some(Datum::new(llfn, function_type, Rvalue::new(ByValue)))
}
None => {}
}
let symbol = ccx.tcx().map.with_path(closure_id.node, |path| {
mangle_internal_name_by_path_and_seq(path, "closure")
});
// Currently there’s only a single user of get_or_create_declaration_if_closure and it
// unconditionally defines the function, therefore we use define_* here.
let llfn = declare::define_internal_rust_fn(ccx, &symbol[..], function_type).unwrap_or_else(||{
ccx.sess().bug(&format!("symbol `{}` already defined", symbol));
});
// set an inline hint for all closures
attributes::inline(llfn, attributes::InlineAttr::Hint);
debug!("get_or_create_declaration_if_closure(): inserting new \
closure {:?} (type {}): {:?}",
mono_id,
ccx.tn().type_to_string(val_ty(llfn)),
ccx.tn().val_to_string(llfn));
ccx.closure_vals().borrow_mut().insert(mono_id, llfn);
Some(Datum::new(llfn, function_type, Rvalue::new(ByValue)))
}
pub enum Dest<'a, 'tcx: 'a> {
SaveIn(Block<'a, 'tcx>, ValueRef),
Ignore(&'a CrateContext<'a, 'tcx>)
}
pub fn trans_closure_expr<'a, 'tcx>(dest: Dest<'a, 'tcx>,
decl: &ast::FnDecl,
body: &ast::Block,
id: ast::NodeId,
param_substs: &'tcx Substs<'tcx>)
-> Option<Block<'a, 'tcx>>
{
let ccx = match dest {
Dest::SaveIn(bcx, _) => bcx.ccx(),
Dest::Ignore(ccx) => ccx
};
let tcx = ccx.tcx();
let _icx = push_ctxt("closure::trans_closure_expr");
debug!("trans_closure_expr()");
let closure_id = ast_util::local_def(id);
let llfn = get_or_create_declaration_if_closure(
ccx,
closure_id,
param_substs).unwrap();
// Get the type of this closure. Use the current `param_substs` as
// the closure substitutions. This makes sense because the closure
// takes the same set of type arguments as the enclosing fn, and
// this function (`trans_closure`) is invoked at the point
// of the closure expression.
let typer = NormalizingClosureTyper::new(tcx);
let function_type = typer.closure_type(closure_id, param_substs);
let freevars: Vec<ty::Freevar> =
tcx.with_freevars(id, |fv| fv.iter().cloned().collect());
let sig = tcx.erase_late_bound_regions(&function_type.sig);
trans_closure(ccx,
decl,
body,
llfn.val,
param_substs,
id,
&[],
sig.output,
function_type.abi,
ClosureEnv::Closure(&freevars));
// Don't hoist this to the top of the function. It's perfectly legitimate
// to have a zero-size closure (in which case dest will be `Ignore`) and
// we must still generate the closure body.
let (mut bcx, dest_addr) = match dest {
Dest::SaveIn(bcx, p) => (bcx, p),
Dest::Ignore(_) => {
debug!("trans_closure_expr() ignoring result");
return None;
}
};
let repr = adt::represent_type(ccx, node_id_type(bcx, id));
// Create the closure.
for (i, freevar) in freevars.iter().enumerate() {
let datum = expr::trans_local_var(bcx, freevar.def);
let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr, dest_addr, 0, i);
let upvar_id = ty::UpvarId { var_id: freevar.def.local_node_id(),
closure_expr_id: id };
match tcx.upvar_capture(upvar_id).unwrap() {
ty::UpvarCapture::ByValue => {
bcx = datum.store_to(bcx, upvar_slot_dest);
}
ty::UpvarCapture::ByRef(..) => {
Store(bcx, datum.to_llref(), upvar_slot_dest);
}
}
}
adt::trans_set_discr(bcx, &*repr, dest_addr, 0);
Some(bcx)
}
pub fn trans_closure_method<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
closure_def_id: ast::DefId,
substs: Substs<'tcx>,
node: ExprOrMethodCall,
param_substs: &'tcx Substs<'tcx>,
trait_closure_kind: ty::ClosureKind)
-> ValueRef
{
// The substitutions should have no type parameters remaining
// after passing through fulfill_obligation
let llfn = callee::trans_fn_ref_with_substs(ccx,
closure_def_id,
node,
param_substs,
substs.clone()).val;
// If the closure is a Fn closure, but a FnOnce is needed (etc),
// then adapt the self type
let closure_kind = ccx.tcx().closure_kind(closure_def_id);
trans_closure_adapter_shim(ccx,
closure_def_id,
substs,
closure_kind,
trait_closure_kind,
llfn)
}
fn trans_closure_adapter_shim<'a, 'tcx>(
ccx: &'a CrateContext<'a, 'tcx>,
closure_def_id: ast::DefId,
substs: Substs<'tcx>,
llfn_closure_kind: ty::ClosureKind,
trait_closure_kind: ty::ClosureKind,
llfn: ValueRef)
-> ValueRef
{
let _icx = push_ctxt("trans_closure_adapter_shim");
let tcx = ccx.tcx();
debug!("trans_closure_adapter_shim(llfn_closure_kind={:?}, \
trait_closure_kind={:?}, \
llfn={})",
llfn_closure_kind,
trait_closure_kind,
ccx.tn().val_to_string(llfn));
match (llfn_closure_kind, trait_closure_kind) {
(ty::FnClosureKind, ty::FnClosureKind) |
(ty::FnMutClosureKind, ty::FnMutClosureKind) |
(ty::FnOnceClosureKind, ty::FnOnceClosureKind) => {
// No adapter needed.
llfn
}
(ty::FnClosureKind, ty::FnMutClosureKind) => {
// The closure fn `llfn` is a `fn(&self,...)`. We want a
// `fn(&mut self,...)`. In fact, at trans time, these are
// basically the same thing, so we can just return llfn.
llfn
}
(ty::FnClosureKind, ty::FnOnceClosureKind) |
(ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
// The closure fn `llfn` is a `fn(&self,...)` or `fn(&mut
// self,...)`. We want a `fn(self,...)`. We can produce
// this by doing something like:
//
// fn call_once(self,...) { call_mut(&self,...) }
// fn call_once(mut self,...) { call_mut(&mut self,...) }
//
// These are both the same at trans time.
trans_fn_once_adapter_shim(ccx, closure_def_id, substs, llfn)
}
_ => {
tcx.sess.bug(&format!("trans_closure_adapter_shim: cannot convert {:?} to {:?}",
llfn_closure_kind,
trait_closure_kind));
}
}
}
fn trans_fn_once_adapter_shim<'a, 'tcx>(
ccx: &'a CrateContext<'a, 'tcx>,
closure_def_id: ast::DefId,
substs: Substs<'tcx>,
llreffn: ValueRef)
-> ValueRef
{
debug!("trans_fn_once_adapter_shim(closure_def_id={:?}, substs={:?}, llreffn={})",
closure_def_id,
substs,
ccx.tn().val_to_string(llreffn));
let tcx = ccx.tcx();
let typer = NormalizingClosureTyper::new(tcx);
// Find a version of the closure type. Substitute static for the
// region since it doesn't really matter.
let substs = tcx.mk_substs(substs);
let closure_ty = tcx.mk_closure(closure_def_id, substs);
let ref_closure_ty = tcx.mk_imm_ref(tcx.mk_region(ty::ReStatic), closure_ty);
// Make a version with the type of by-ref closure.
let ty::ClosureTy { unsafety, abi, mut sig } = typer.closure_type(closure_def_id, substs);
sig.0.inputs.insert(0, ref_closure_ty); // sig has no self type as of yet
let llref_bare_fn_ty = tcx.mk_bare_fn(ty::BareFnTy { unsafety: unsafety,
abi: abi,
sig: sig.clone() });
let llref_fn_ty = tcx.mk_fn(None, llref_bare_fn_ty);
debug!("trans_fn_once_adapter_shim: llref_fn_ty={:?}",
llref_fn_ty);
// Make a version of the closure type with the same arguments, but
// with argument #0 being by value.
assert_eq!(abi, RustCall);
sig.0.inputs[0] = closure_ty;
let llonce_bare_fn_ty = tcx.mk_bare_fn(ty::BareFnTy { unsafety: unsafety,
abi: abi,
sig: sig });
let llonce_fn_ty = tcx.mk_fn(None, llonce_bare_fn_ty);
// Create the by-value helper.
let function_name = link::mangle_internal_name_by_type_and_seq(ccx, llonce_fn_ty, "once_shim");
let lloncefn = declare::define_internal_rust_fn(ccx, &function_name[..], llonce_fn_ty)
.unwrap_or_else(||{
ccx.sess().bug(&format!("symbol `{}` already defined", function_name));
});
let sig = tcx.erase_late_bound_regions(&llonce_bare_fn_ty.sig);
let (block_arena, fcx): (TypedArena<_>, FunctionContext);
block_arena = TypedArena::new();
fcx = new_fn_ctxt(ccx,
lloncefn,
ast::DUMMY_NODE_ID,
false,
sig.output,
substs,
None,
&block_arena);
let mut bcx = init_function(&fcx, false, sig.output);
let llargs = get_params(fcx.llfn);
// the first argument (`self`) will be the (by value) closure env.
let self_scope = fcx.push_custom_cleanup_scope();
let self_scope_id = CustomScope(self_scope);
let rvalue_mode = datum::appropriate_rvalue_mode(ccx, closure_ty);
let self_idx = fcx.arg_offset();
let llself = llargs[self_idx];
let env_datum = Datum::new(llself, closure_ty, Rvalue::new(rvalue_mode));
let env_datum = unpack_datum!(bcx,
env_datum.to_lvalue_datum_in_scope(bcx, "self",
self_scope_id));
debug!("trans_fn_once_adapter_shim: env_datum={}",
bcx.val_to_string(env_datum.val));
let dest =
fcx.llretslotptr.get().map(
|_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
let callee_data = TraitItem(MethodData { llfn: llreffn,
llself: env_datum.val });
bcx = callee
|
load_closure_environment
|
identifier_name
|
closure.rs
|
use arena::TypedArena;
use back::link::{self, mangle_internal_name_by_path_and_seq};
use llvm::{ValueRef, get_params};
use middle::mem_categorization::Typer;
use trans::adt;
use trans::attributes;
use trans::base::*;
use trans::build::*;
use trans::callee::{self, ArgVals, Callee, TraitItem, MethodData};
use trans::cleanup::{CleanupMethods, CustomScope, ScopeId};
use trans::common::*;
use trans::datum::{self, Datum, rvalue_scratch_datum, Rvalue, ByValue};
use trans::debuginfo::{self, DebugLoc};
use trans::declare;
use trans::expr;
use trans::monomorphize::{self, MonoId};
use trans::type_of::*;
use middle::ty::{self, ClosureTyper};
use middle::subst::Substs;
use session::config::FullDebugInfo;
use syntax::abi::RustCall;
use syntax::ast;
use syntax::ast_util;
fn load_closure_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
arg_scope_id: ScopeId,
freevars: &[ty::Freevar])
-> Block<'blk, 'tcx>
{
let _icx = push_ctxt("closure::load_closure_environment");
// Special case for small by-value selfs.
let closure_id = ast_util::local_def(bcx.fcx.id);
let self_type = self_type_for_closure(bcx.ccx(), closure_id,
node_id_type(bcx, closure_id.node));
let kind = kind_for_closure(bcx.ccx(), closure_id);
let llenv = if kind == ty::FnOnceClosureKind &&
!arg_is_indirect(bcx.ccx(), self_type) {
let datum = rvalue_scratch_datum(bcx,
self_type,
"closure_env");
store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type);
datum.val
} else {
bcx.fcx.llenv.unwrap()
};
// Store the pointer to closure data in an alloca for debug info because that's what the
// llvm.dbg.declare intrinsic expects
let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
let alloc = alloca(bcx, val_ty(llenv), "__debuginfo_env_ptr");
Store(bcx, llenv, alloc);
Some(alloc)
} else {
None
};
for (i, freevar) in freevars.iter().enumerate() {
let upvar_id = ty::UpvarId { var_id: freevar.def.local_node_id(),
closure_expr_id: closure_id.node };
let upvar_capture = bcx.tcx().upvar_capture(upvar_id).unwrap();
let mut upvar_ptr = GEPi(bcx, llenv, &[0, i]);
let captured_by_ref = match upvar_capture {
ty::UpvarCapture::ByValue => false,
ty::UpvarCapture::ByRef(..) => {
upvar_ptr = Load(bcx, upvar_ptr);
true
}
};
let def_id = freevar.def.def_id();
bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr);
if kind == ty::FnOnceClosureKind &&!captured_by_ref {
bcx.fcx.schedule_drop_mem(arg_scope_id,
upvar_ptr,
node_id_type(bcx, def_id.node))
}
if let Some(env_pointer_alloca) = env_pointer_alloca {
debuginfo::create_captured_var_metadata(
bcx,
def_id.node,
env_pointer_alloca,
i,
captured_by_ref,
freevar.span);
}
}
bcx
}
pub enum ClosureEnv<'a> {
NotClosure,
Closure(&'a [ty::Freevar]),
}
impl<'a> ClosureEnv<'a> {
pub fn load<'blk,'tcx>(self, bcx: Block<'blk, 'tcx>, arg_scope: ScopeId)
-> Block<'blk, 'tcx>
{
match self {
ClosureEnv::NotClosure => bcx,
ClosureEnv::Closure(freevars) => {
if freevars.is_empty() {
bcx
} else {
load_closure_environment(bcx, arg_scope, freevars)
}
}
}
}
}
/// Returns the LLVM function declaration for a closure, creating it if
/// necessary. If the ID does not correspond to a closure ID, returns None.
pub fn get_or_create_declaration_if_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
closure_id: ast::DefId,
substs: &Substs<'tcx>)
-> Option<Datum<'tcx, Rvalue>> {
if!ccx.tcx().closure_kinds.borrow().contains_key(&closure_id) {
// Not a closure.
return None
}
let function_type = ccx.tcx().node_id_to_type(closure_id.node);
let function_type = monomorphize::apply_param_substs(ccx.tcx(), substs, &function_type);
// Normalize type so differences in regions and typedefs don't cause
// duplicate declarations
let function_type = erase_regions(ccx.tcx(), &function_type);
let params = match function_type.sty {
ty::TyClosure(_, substs) => &substs.types,
_ => unreachable!()
};
let mono_id = MonoId {
def: closure_id,
params: params
};
match ccx.closure_vals().borrow().get(&mono_id) {
Some(&llfn) => {
debug!("get_or_create_declaration_if_closure(): found closure {:?}: {:?}",
mono_id, ccx.tn().val_to_string(llfn));
return Some(Datum::new(llfn, function_type, Rvalue::new(ByValue)))
}
None => {}
}
let symbol = ccx.tcx().map.with_path(closure_id.node, |path| {
mangle_internal_name_by_path_and_seq(path, "closure")
});
// Currently there’s only a single user of get_or_create_declaration_if_closure and it
// unconditionally defines the function, therefore we use define_* here.
let llfn = declare::define_internal_rust_fn(ccx, &symbol[..], function_type).unwrap_or_else(||{
ccx.sess().bug(&format!("symbol `{}` already defined", symbol));
});
// set an inline hint for all closures
attributes::inline(llfn, attributes::InlineAttr::Hint);
debug!("get_or_create_declaration_if_closure(): inserting new \
closure {:?} (type {}): {:?}",
mono_id,
ccx.tn().type_to_string(val_ty(llfn)),
ccx.tn().val_to_string(llfn));
ccx.closure_vals().borrow_mut().insert(mono_id, llfn);
Some(Datum::new(llfn, function_type, Rvalue::new(ByValue)))
}
pub enum Dest<'a, 'tcx: 'a> {
SaveIn(Block<'a, 'tcx>, ValueRef),
Ignore(&'a CrateContext<'a, 'tcx>)
}
pub fn trans_closure_expr<'a, 'tcx>(dest: Dest<'a, 'tcx>,
decl: &ast::FnDecl,
body: &ast::Block,
id: ast::NodeId,
param_substs: &'tcx Substs<'tcx>)
-> Option<Block<'a, 'tcx>>
{
let ccx = match dest {
Dest::SaveIn(bcx, _) => bcx.ccx(),
Dest::Ignore(ccx) => ccx
};
let tcx = ccx.tcx();
let _icx = push_ctxt("closure::trans_closure_expr");
debug!("trans_closure_expr()");
let closure_id = ast_util::local_def(id);
let llfn = get_or_create_declaration_if_closure(
ccx,
closure_id,
param_substs).unwrap();
// Get the type of this closure. Use the current `param_substs` as
// the closure substitutions. This makes sense because the closure
// takes the same set of type arguments as the enclosing fn, and
// this function (`trans_closure`) is invoked at the point
// of the closure expression.
let typer = NormalizingClosureTyper::new(tcx);
let function_type = typer.closure_type(closure_id, param_substs);
let freevars: Vec<ty::Freevar> =
tcx.with_freevars(id, |fv| fv.iter().cloned().collect());
let sig = tcx.erase_late_bound_regions(&function_type.sig);
trans_closure(ccx,
decl,
body,
llfn.val,
param_substs,
id,
&[],
sig.output,
function_type.abi,
ClosureEnv::Closure(&freevars));
// Don't hoist this to the top of the function. It's perfectly legitimate
// to have a zero-size closure (in which case dest will be `Ignore`) and
// we must still generate the closure body.
let (mut bcx, dest_addr) = match dest {
Dest::SaveIn(bcx, p) => (bcx, p),
Dest::Ignore(_) => {
debug!("trans_closure_expr() ignoring result");
return None;
}
};
let repr = adt::represent_type(ccx, node_id_type(bcx, id));
// Create the closure.
for (i, freevar) in freevars.iter().enumerate() {
let datum = expr::trans_local_var(bcx, freevar.def);
let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr, dest_addr, 0, i);
let upvar_id = ty::UpvarId { var_id: freevar.def.local_node_id(),
closure_expr_id: id };
match tcx.upvar_capture(upvar_id).unwrap() {
ty::UpvarCapture::ByValue => {
bcx = datum.store_to(bcx, upvar_slot_dest);
}
ty::UpvarCapture::ByRef(..) => {
Store(bcx, datum.to_llref(), upvar_slot_dest);
}
}
}
adt::trans_set_discr(bcx, &*repr, dest_addr, 0);
Some(bcx)
}
pub fn trans_closure_method<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
closure_def_id: ast::DefId,
substs: Substs<'tcx>,
node: ExprOrMethodCall,
param_substs: &'tcx Substs<'tcx>,
trait_closure_kind: ty::ClosureKind)
-> ValueRef
{
// The substitutions should have no type parameters remaining
// after passing through fulfill_obligation
let llfn = callee::trans_fn_ref_with_substs(ccx,
closure_def_id,
node,
param_substs,
substs.clone()).val;
// If the closure is a Fn closure, but a FnOnce is needed (etc),
// then adapt the self type
let closure_kind = ccx.tcx().closure_kind(closure_def_id);
trans_closure_adapter_shim(ccx,
closure_def_id,
substs,
closure_kind,
trait_closure_kind,
llfn)
}
fn trans_closure_adapter_shim<'a, 'tcx>(
ccx: &'a CrateContext<'a, 'tcx>,
closure_def_id: ast::DefId,
substs: Substs<'tcx>,
llfn_closure_kind: ty::ClosureKind,
trait_closure_kind: ty::ClosureKind,
llfn: ValueRef)
-> ValueRef
{
let _icx = push_ctxt("trans_closure_adapter_shim");
let tcx = ccx.tcx();
debug!("trans_closure_adapter_shim(llfn_closure_kind={:?}, \
trait_closure_kind={:?}, \
llfn={})",
llfn_closure_kind,
trait_closure_kind,
ccx.tn().val_to_string(llfn));
match (llfn_closure_kind, trait_closure_kind) {
(ty::FnClosureKind, ty::FnClosureKind) |
(ty::FnMutClosureKind, ty::FnMutClosureKind) |
(ty::FnOnceClosureKind, ty::FnOnceClosureKind) => {
// No adapter needed.
llfn
}
(ty::FnClosureKind, ty::FnMutClosureKind) => {
// The closure fn `llfn` is a `fn(&self,...)`. We want a
// `fn(&mut self,...)`. In fact, at trans time, these are
// basically the same thing, so we can just return llfn.
llfn
}
(ty::FnClosureKind, ty::FnOnceClosureKind) |
(ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
// The closure fn `llfn` is a `fn(&self,...)` or `fn(&mut
// self,...)`. We want a `fn(self,...)`. We can produce
// this by doing something like:
//
// fn call_once(self,...) { call_mut(&self,...) }
// fn call_once(mut self,...) { call_mut(&mut self,...) }
//
// These are both the same at trans time.
trans_fn_once_adapter_shim(ccx, closure_def_id, substs, llfn)
}
_ => {
tcx.sess.bug(&format!("trans_closure_adapter_shim: cannot convert {:?} to {:?}",
llfn_closure_kind,
trait_closure_kind));
}
}
}
fn trans_fn_once_adapter_shim<'a, 'tcx>(
ccx: &'a CrateContext<'a, 'tcx>,
closure_def_id: ast::DefId,
substs: Substs<'tcx>,
llreffn: ValueRef)
-> ValueRef
{
debug!("trans_fn_once_adapter_shim(closure_def_id={:?}, substs={:?}, llreffn={})",
closure_def_id,
substs,
ccx.tn().val_to_string(llreffn));
|
// region since it doesn't really matter.
let substs = tcx.mk_substs(substs);
let closure_ty = tcx.mk_closure(closure_def_id, substs);
let ref_closure_ty = tcx.mk_imm_ref(tcx.mk_region(ty::ReStatic), closure_ty);
// Make a version with the type of by-ref closure.
let ty::ClosureTy { unsafety, abi, mut sig } = typer.closure_type(closure_def_id, substs);
sig.0.inputs.insert(0, ref_closure_ty); // sig has no self type as of yet
let llref_bare_fn_ty = tcx.mk_bare_fn(ty::BareFnTy { unsafety: unsafety,
abi: abi,
sig: sig.clone() });
let llref_fn_ty = tcx.mk_fn(None, llref_bare_fn_ty);
debug!("trans_fn_once_adapter_shim: llref_fn_ty={:?}",
llref_fn_ty);
// Make a version of the closure type with the same arguments, but
// with argument #0 being by value.
assert_eq!(abi, RustCall);
sig.0.inputs[0] = closure_ty;
let llonce_bare_fn_ty = tcx.mk_bare_fn(ty::BareFnTy { unsafety: unsafety,
abi: abi,
sig: sig });
let llonce_fn_ty = tcx.mk_fn(None, llonce_bare_fn_ty);
// Create the by-value helper.
let function_name = link::mangle_internal_name_by_type_and_seq(ccx, llonce_fn_ty, "once_shim");
let lloncefn = declare::define_internal_rust_fn(ccx, &function_name[..], llonce_fn_ty)
.unwrap_or_else(||{
ccx.sess().bug(&format!("symbol `{}` already defined", function_name));
});
let sig = tcx.erase_late_bound_regions(&llonce_bare_fn_ty.sig);
let (block_arena, fcx): (TypedArena<_>, FunctionContext);
block_arena = TypedArena::new();
fcx = new_fn_ctxt(ccx,
lloncefn,
ast::DUMMY_NODE_ID,
false,
sig.output,
substs,
None,
&block_arena);
let mut bcx = init_function(&fcx, false, sig.output);
let llargs = get_params(fcx.llfn);
// the first argument (`self`) will be the (by value) closure env.
let self_scope = fcx.push_custom_cleanup_scope();
let self_scope_id = CustomScope(self_scope);
let rvalue_mode = datum::appropriate_rvalue_mode(ccx, closure_ty);
let self_idx = fcx.arg_offset();
let llself = llargs[self_idx];
let env_datum = Datum::new(llself, closure_ty, Rvalue::new(rvalue_mode));
let env_datum = unpack_datum!(bcx,
env_datum.to_lvalue_datum_in_scope(bcx, "self",
self_scope_id));
debug!("trans_fn_once_adapter_shim: env_datum={}",
bcx.val_to_string(env_datum.val));
let dest =
fcx.llretslotptr.get().map(
|_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
let callee_data = TraitItem(MethodData { llfn: llreffn,
llself: env_datum.val });
bcx = callee::trans
|
let tcx = ccx.tcx();
let typer = NormalizingClosureTyper::new(tcx);
// Find a version of the closure type. Substitute static for the
|
random_line_split
|
closure.rs
|
use arena::TypedArena;
use back::link::{self, mangle_internal_name_by_path_and_seq};
use llvm::{ValueRef, get_params};
use middle::mem_categorization::Typer;
use trans::adt;
use trans::attributes;
use trans::base::*;
use trans::build::*;
use trans::callee::{self, ArgVals, Callee, TraitItem, MethodData};
use trans::cleanup::{CleanupMethods, CustomScope, ScopeId};
use trans::common::*;
use trans::datum::{self, Datum, rvalue_scratch_datum, Rvalue, ByValue};
use trans::debuginfo::{self, DebugLoc};
use trans::declare;
use trans::expr;
use trans::monomorphize::{self, MonoId};
use trans::type_of::*;
use middle::ty::{self, ClosureTyper};
use middle::subst::Substs;
use session::config::FullDebugInfo;
use syntax::abi::RustCall;
use syntax::ast;
use syntax::ast_util;
fn load_closure_environment<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
arg_scope_id: ScopeId,
freevars: &[ty::Freevar])
-> Block<'blk, 'tcx>
{
let _icx = push_ctxt("closure::load_closure_environment");
// Special case for small by-value selfs.
let closure_id = ast_util::local_def(bcx.fcx.id);
let self_type = self_type_for_closure(bcx.ccx(), closure_id,
node_id_type(bcx, closure_id.node));
let kind = kind_for_closure(bcx.ccx(), closure_id);
let llenv = if kind == ty::FnOnceClosureKind &&
!arg_is_indirect(bcx.ccx(), self_type) {
let datum = rvalue_scratch_datum(bcx,
self_type,
"closure_env");
store_ty(bcx, bcx.fcx.llenv.unwrap(), datum.val, self_type);
datum.val
} else {
bcx.fcx.llenv.unwrap()
};
// Store the pointer to closure data in an alloca for debug info because that's what the
// llvm.dbg.declare intrinsic expects
let env_pointer_alloca = if bcx.sess().opts.debuginfo == FullDebugInfo {
let alloc = alloca(bcx, val_ty(llenv), "__debuginfo_env_ptr");
Store(bcx, llenv, alloc);
Some(alloc)
} else {
None
};
for (i, freevar) in freevars.iter().enumerate() {
let upvar_id = ty::UpvarId { var_id: freevar.def.local_node_id(),
closure_expr_id: closure_id.node };
let upvar_capture = bcx.tcx().upvar_capture(upvar_id).unwrap();
let mut upvar_ptr = GEPi(bcx, llenv, &[0, i]);
let captured_by_ref = match upvar_capture {
ty::UpvarCapture::ByValue => false,
ty::UpvarCapture::ByRef(..) => {
upvar_ptr = Load(bcx, upvar_ptr);
true
}
};
let def_id = freevar.def.def_id();
bcx.fcx.llupvars.borrow_mut().insert(def_id.node, upvar_ptr);
if kind == ty::FnOnceClosureKind &&!captured_by_ref {
bcx.fcx.schedule_drop_mem(arg_scope_id,
upvar_ptr,
node_id_type(bcx, def_id.node))
}
if let Some(env_pointer_alloca) = env_pointer_alloca {
debuginfo::create_captured_var_metadata(
bcx,
def_id.node,
env_pointer_alloca,
i,
captured_by_ref,
freevar.span);
}
}
bcx
}
pub enum ClosureEnv<'a> {
NotClosure,
Closure(&'a [ty::Freevar]),
}
impl<'a> ClosureEnv<'a> {
pub fn load<'blk,'tcx>(self, bcx: Block<'blk, 'tcx>, arg_scope: ScopeId)
-> Block<'blk, 'tcx>
{
match self {
ClosureEnv::NotClosure => bcx,
ClosureEnv::Closure(freevars) => {
if freevars.is_empty() {
bcx
} else {
load_closure_environment(bcx, arg_scope, freevars)
}
}
}
}
}
/// Returns the LLVM function declaration for a closure, creating it if
/// necessary. If the ID does not correspond to a closure ID, returns None.
pub fn get_or_create_declaration_if_closure<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
closure_id: ast::DefId,
substs: &Substs<'tcx>)
-> Option<Datum<'tcx, Rvalue>> {
if!ccx.tcx().closure_kinds.borrow().contains_key(&closure_id) {
// Not a closure.
return None
}
let function_type = ccx.tcx().node_id_to_type(closure_id.node);
let function_type = monomorphize::apply_param_substs(ccx.tcx(), substs, &function_type);
// Normalize type so differences in regions and typedefs don't cause
// duplicate declarations
let function_type = erase_regions(ccx.tcx(), &function_type);
let params = match function_type.sty {
ty::TyClosure(_, substs) => &substs.types,
_ => unreachable!()
};
let mono_id = MonoId {
def: closure_id,
params: params
};
match ccx.closure_vals().borrow().get(&mono_id) {
Some(&llfn) => {
debug!("get_or_create_declaration_if_closure(): found closure {:?}: {:?}",
mono_id, ccx.tn().val_to_string(llfn));
return Some(Datum::new(llfn, function_type, Rvalue::new(ByValue)))
}
None => {}
}
let symbol = ccx.tcx().map.with_path(closure_id.node, |path| {
mangle_internal_name_by_path_and_seq(path, "closure")
});
// Currently there’s only a single user of get_or_create_declaration_if_closure and it
// unconditionally defines the function, therefore we use define_* here.
let llfn = declare::define_internal_rust_fn(ccx, &symbol[..], function_type).unwrap_or_else(||{
ccx.sess().bug(&format!("symbol `{}` already defined", symbol));
});
// set an inline hint for all closures
attributes::inline(llfn, attributes::InlineAttr::Hint);
debug!("get_or_create_declaration_if_closure(): inserting new \
closure {:?} (type {}): {:?}",
mono_id,
ccx.tn().type_to_string(val_ty(llfn)),
ccx.tn().val_to_string(llfn));
ccx.closure_vals().borrow_mut().insert(mono_id, llfn);
Some(Datum::new(llfn, function_type, Rvalue::new(ByValue)))
}
pub enum Dest<'a, 'tcx: 'a> {
SaveIn(Block<'a, 'tcx>, ValueRef),
Ignore(&'a CrateContext<'a, 'tcx>)
}
pub fn trans_closure_expr<'a, 'tcx>(dest: Dest<'a, 'tcx>,
decl: &ast::FnDecl,
body: &ast::Block,
id: ast::NodeId,
param_substs: &'tcx Substs<'tcx>)
-> Option<Block<'a, 'tcx>>
{
let ccx = match dest {
Dest::SaveIn(bcx, _) => bcx.ccx(),
Dest::Ignore(ccx) => ccx
};
let tcx = ccx.tcx();
let _icx = push_ctxt("closure::trans_closure_expr");
debug!("trans_closure_expr()");
let closure_id = ast_util::local_def(id);
let llfn = get_or_create_declaration_if_closure(
ccx,
closure_id,
param_substs).unwrap();
// Get the type of this closure. Use the current `param_substs` as
// the closure substitutions. This makes sense because the closure
// takes the same set of type arguments as the enclosing fn, and
// this function (`trans_closure`) is invoked at the point
// of the closure expression.
let typer = NormalizingClosureTyper::new(tcx);
let function_type = typer.closure_type(closure_id, param_substs);
let freevars: Vec<ty::Freevar> =
tcx.with_freevars(id, |fv| fv.iter().cloned().collect());
let sig = tcx.erase_late_bound_regions(&function_type.sig);
trans_closure(ccx,
decl,
body,
llfn.val,
param_substs,
id,
&[],
sig.output,
function_type.abi,
ClosureEnv::Closure(&freevars));
// Don't hoist this to the top of the function. It's perfectly legitimate
// to have a zero-size closure (in which case dest will be `Ignore`) and
// we must still generate the closure body.
let (mut bcx, dest_addr) = match dest {
Dest::SaveIn(bcx, p) => (bcx, p),
Dest::Ignore(_) => {
debug!("trans_closure_expr() ignoring result");
return None;
}
};
let repr = adt::represent_type(ccx, node_id_type(bcx, id));
// Create the closure.
for (i, freevar) in freevars.iter().enumerate() {
let datum = expr::trans_local_var(bcx, freevar.def);
let upvar_slot_dest = adt::trans_field_ptr(bcx, &*repr, dest_addr, 0, i);
let upvar_id = ty::UpvarId { var_id: freevar.def.local_node_id(),
closure_expr_id: id };
match tcx.upvar_capture(upvar_id).unwrap() {
ty::UpvarCapture::ByValue => {
bcx = datum.store_to(bcx, upvar_slot_dest);
}
ty::UpvarCapture::ByRef(..) => {
Store(bcx, datum.to_llref(), upvar_slot_dest);
}
}
}
adt::trans_set_discr(bcx, &*repr, dest_addr, 0);
Some(bcx)
}
pub fn trans_closure_method<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
closure_def_id: ast::DefId,
substs: Substs<'tcx>,
node: ExprOrMethodCall,
param_substs: &'tcx Substs<'tcx>,
trait_closure_kind: ty::ClosureKind)
-> ValueRef
{
|
fn trans_closure_adapter_shim<'a, 'tcx>(
ccx: &'a CrateContext<'a, 'tcx>,
closure_def_id: ast::DefId,
substs: Substs<'tcx>,
llfn_closure_kind: ty::ClosureKind,
trait_closure_kind: ty::ClosureKind,
llfn: ValueRef)
-> ValueRef
{
let _icx = push_ctxt("trans_closure_adapter_shim");
let tcx = ccx.tcx();
debug!("trans_closure_adapter_shim(llfn_closure_kind={:?}, \
trait_closure_kind={:?}, \
llfn={})",
llfn_closure_kind,
trait_closure_kind,
ccx.tn().val_to_string(llfn));
match (llfn_closure_kind, trait_closure_kind) {
(ty::FnClosureKind, ty::FnClosureKind) |
(ty::FnMutClosureKind, ty::FnMutClosureKind) |
(ty::FnOnceClosureKind, ty::FnOnceClosureKind) => {
// No adapter needed.
llfn
}
(ty::FnClosureKind, ty::FnMutClosureKind) => {
// The closure fn `llfn` is a `fn(&self,...)`. We want a
// `fn(&mut self,...)`. In fact, at trans time, these are
// basically the same thing, so we can just return llfn.
llfn
}
(ty::FnClosureKind, ty::FnOnceClosureKind) |
(ty::FnMutClosureKind, ty::FnOnceClosureKind) => {
// The closure fn `llfn` is a `fn(&self,...)` or `fn(&mut
// self,...)`. We want a `fn(self,...)`. We can produce
// this by doing something like:
//
// fn call_once(self,...) { call_mut(&self,...) }
// fn call_once(mut self,...) { call_mut(&mut self,...) }
//
// These are both the same at trans time.
trans_fn_once_adapter_shim(ccx, closure_def_id, substs, llfn)
}
_ => {
tcx.sess.bug(&format!("trans_closure_adapter_shim: cannot convert {:?} to {:?}",
llfn_closure_kind,
trait_closure_kind));
}
}
}
fn trans_fn_once_adapter_shim<'a, 'tcx>(
ccx: &'a CrateContext<'a, 'tcx>,
closure_def_id: ast::DefId,
substs: Substs<'tcx>,
llreffn: ValueRef)
-> ValueRef
{
debug!("trans_fn_once_adapter_shim(closure_def_id={:?}, substs={:?}, llreffn={})",
closure_def_id,
substs,
ccx.tn().val_to_string(llreffn));
let tcx = ccx.tcx();
let typer = NormalizingClosureTyper::new(tcx);
// Find a version of the closure type. Substitute static for the
// region since it doesn't really matter.
let substs = tcx.mk_substs(substs);
let closure_ty = tcx.mk_closure(closure_def_id, substs);
let ref_closure_ty = tcx.mk_imm_ref(tcx.mk_region(ty::ReStatic), closure_ty);
// Make a version with the type of by-ref closure.
let ty::ClosureTy { unsafety, abi, mut sig } = typer.closure_type(closure_def_id, substs);
sig.0.inputs.insert(0, ref_closure_ty); // sig has no self type as of yet
let llref_bare_fn_ty = tcx.mk_bare_fn(ty::BareFnTy { unsafety: unsafety,
abi: abi,
sig: sig.clone() });
let llref_fn_ty = tcx.mk_fn(None, llref_bare_fn_ty);
debug!("trans_fn_once_adapter_shim: llref_fn_ty={:?}",
llref_fn_ty);
// Make a version of the closure type with the same arguments, but
// with argument #0 being by value.
assert_eq!(abi, RustCall);
sig.0.inputs[0] = closure_ty;
let llonce_bare_fn_ty = tcx.mk_bare_fn(ty::BareFnTy { unsafety: unsafety,
abi: abi,
sig: sig });
let llonce_fn_ty = tcx.mk_fn(None, llonce_bare_fn_ty);
// Create the by-value helper.
let function_name = link::mangle_internal_name_by_type_and_seq(ccx, llonce_fn_ty, "once_shim");
let lloncefn = declare::define_internal_rust_fn(ccx, &function_name[..], llonce_fn_ty)
.unwrap_or_else(||{
ccx.sess().bug(&format!("symbol `{}` already defined", function_name));
});
let sig = tcx.erase_late_bound_regions(&llonce_bare_fn_ty.sig);
let (block_arena, fcx): (TypedArena<_>, FunctionContext);
block_arena = TypedArena::new();
fcx = new_fn_ctxt(ccx,
lloncefn,
ast::DUMMY_NODE_ID,
false,
sig.output,
substs,
None,
&block_arena);
let mut bcx = init_function(&fcx, false, sig.output);
let llargs = get_params(fcx.llfn);
// the first argument (`self`) will be the (by value) closure env.
let self_scope = fcx.push_custom_cleanup_scope();
let self_scope_id = CustomScope(self_scope);
let rvalue_mode = datum::appropriate_rvalue_mode(ccx, closure_ty);
let self_idx = fcx.arg_offset();
let llself = llargs[self_idx];
let env_datum = Datum::new(llself, closure_ty, Rvalue::new(rvalue_mode));
let env_datum = unpack_datum!(bcx,
env_datum.to_lvalue_datum_in_scope(bcx, "self",
self_scope_id));
debug!("trans_fn_once_adapter_shim: env_datum={}",
bcx.val_to_string(env_datum.val));
let dest =
fcx.llretslotptr.get().map(
|_| expr::SaveIn(fcx.get_ret_slot(bcx, sig.output, "ret_slot")));
let callee_data = TraitItem(MethodData { llfn: llreffn,
llself: env_datum.val });
bcx = callee::
|
// The substitutions should have no type parameters remaining
// after passing through fulfill_obligation
let llfn = callee::trans_fn_ref_with_substs(ccx,
closure_def_id,
node,
param_substs,
substs.clone()).val;
// If the closure is a Fn closure, but a FnOnce is needed (etc),
// then adapt the self type
let closure_kind = ccx.tcx().closure_kind(closure_def_id);
trans_closure_adapter_shim(ccx,
closure_def_id,
substs,
closure_kind,
trait_closure_kind,
llfn)
}
|
identifier_body
|
aarch64.rs
|
//! Aarch64 run-time features.
/// Checks if `aarch64` feature is enabled.
#[macro_export]
#[unstable(feature = "stdsimd", issue = "27731")]
#[allow_internal_unstable(stdsimd_internal, stdsimd)]
macro_rules! is_aarch64_feature_detected {
("neon") => {
// FIXME: this should be removed once we rename Aarch64 neon to asimd
cfg!(target_feature = "neon") || $crate::detect::check_for($crate::detect::Feature::asimd)
};
("asimd") => {
cfg!(target_feature = "neon") || $crate::detect::check_for($crate::detect::Feature::asimd)
};
("pmull") => {
cfg!(target_feature = "pmull") || $crate::detect::check_for($crate::detect::Feature::pmull)
};
("fp") => {
cfg!(target_feature = "fp") || $crate::detect::check_for($crate::detect::Feature::fp)
};
("fp16") => {
cfg!(target_feature = "fp16") || $crate::detect::check_for($crate::detect::Feature::fp16)
};
("sve") => {
cfg!(target_feature = "sve") || $crate::detect::check_for($crate::detect::Feature::sve)
};
("crc") => {
cfg!(target_feature = "crc") || $crate::detect::check_for($crate::detect::Feature::crc)
};
("crypto") => {
cfg!(target_feature = "crypto")
|| $crate::detect::check_for($crate::detect::Feature::crypto)
};
("lse") => {
cfg!(target_feature = "lse") || $crate::detect::check_for($crate::detect::Feature::lse)
};
("rdm") => {
cfg!(target_feature = "rdm") || $crate::detect::check_for($crate::detect::Feature::rdm)
};
("rcpc") => {
cfg!(target_feature = "rcpc") || $crate::detect::check_for($crate::detect::Feature::rcpc)
};
("dotprod") => {
cfg!(target_feature = "dotprod")
|| $crate::detect::check_for($crate::detect::Feature::dotprod)
};
("ras") => {
compile_error!("\"ras\" feature cannot be detected at run-time")
};
("v8.1a") => {
compile_error!("\"v8.1a\" feature cannot be detected at run-time")
};
("v8.2a") => {
compile_error!("\"v8.2a\" feature cannot be detected at run-time")
};
("v8.3a") => {
compile_error!("\"v8.3a\" feature cannot be detected at run-time")
};
($t:tt,) => {
is_aarch64_feature_detected!($t);
};
($t:tt) => {
compile_error!(concat!("unknown aarch64 target feature: ", $t))
};
}
/// ARM Aarch64 CPU Feature enum. Each variant denotes a position in a bitset
/// for a particular feature.
///
/// PLEASE: do not use this, it is an implementation detail subject to change.
#[doc(hidden)]
#[allow(non_camel_case_types)]
#[repr(u8)]
#[unstable(feature = "stdsimd_internal", issue = "0")]
pub enum
|
{
/// ARM Advanced SIMD (ASIMD)
asimd,
/// Polynomial Multiply
pmull,
/// Floating point support
fp,
/// Half-float support.
fp16,
/// Scalable Vector Extension (SVE)
sve,
/// CRC32 (Cyclic Redundancy Check)
crc,
/// Crypto: AES + PMULL + SHA1 + SHA2
crypto,
/// Atomics (Large System Extension)
lse,
/// Rounding Double Multiply (ASIMDRDM)
rdm,
/// Release consistent Processor consistent (RcPc)
rcpc,
/// Vector Dot-Product (ASIMDDP)
dotprod,
}
|
Feature
|
identifier_name
|
aarch64.rs
|
//! Aarch64 run-time features.
/// Checks if `aarch64` feature is enabled.
#[macro_export]
#[unstable(feature = "stdsimd", issue = "27731")]
#[allow_internal_unstable(stdsimd_internal, stdsimd)]
macro_rules! is_aarch64_feature_detected {
("neon") => {
// FIXME: this should be removed once we rename Aarch64 neon to asimd
cfg!(target_feature = "neon") || $crate::detect::check_for($crate::detect::Feature::asimd)
};
("asimd") => {
cfg!(target_feature = "neon") || $crate::detect::check_for($crate::detect::Feature::asimd)
};
("pmull") => {
cfg!(target_feature = "pmull") || $crate::detect::check_for($crate::detect::Feature::pmull)
};
("fp") => {
cfg!(target_feature = "fp") || $crate::detect::check_for($crate::detect::Feature::fp)
};
("fp16") => {
cfg!(target_feature = "fp16") || $crate::detect::check_for($crate::detect::Feature::fp16)
};
("sve") => {
cfg!(target_feature = "sve") || $crate::detect::check_for($crate::detect::Feature::sve)
};
("crc") => {
cfg!(target_feature = "crc") || $crate::detect::check_for($crate::detect::Feature::crc)
};
("crypto") => {
cfg!(target_feature = "crypto")
|| $crate::detect::check_for($crate::detect::Feature::crypto)
};
("lse") => {
cfg!(target_feature = "lse") || $crate::detect::check_for($crate::detect::Feature::lse)
};
("rdm") => {
cfg!(target_feature = "rdm") || $crate::detect::check_for($crate::detect::Feature::rdm)
};
("rcpc") => {
cfg!(target_feature = "rcpc") || $crate::detect::check_for($crate::detect::Feature::rcpc)
};
("dotprod") => {
cfg!(target_feature = "dotprod")
|| $crate::detect::check_for($crate::detect::Feature::dotprod)
};
("ras") => {
compile_error!("\"ras\" feature cannot be detected at run-time")
};
("v8.1a") => {
compile_error!("\"v8.1a\" feature cannot be detected at run-time")
};
("v8.2a") => {
compile_error!("\"v8.2a\" feature cannot be detected at run-time")
};
("v8.3a") => {
compile_error!("\"v8.3a\" feature cannot be detected at run-time")
};
($t:tt,) => {
|
};
}
/// ARM Aarch64 CPU Feature enum. Each variant denotes a position in a bitset
/// for a particular feature.
///
/// PLEASE: do not use this, it is an implementation detail subject to change.
#[doc(hidden)]
#[allow(non_camel_case_types)]
#[repr(u8)]
#[unstable(feature = "stdsimd_internal", issue = "0")]
pub enum Feature {
/// ARM Advanced SIMD (ASIMD)
asimd,
/// Polynomial Multiply
pmull,
/// Floating point support
fp,
/// Half-float support.
fp16,
/// Scalable Vector Extension (SVE)
sve,
/// CRC32 (Cyclic Redundancy Check)
crc,
/// Crypto: AES + PMULL + SHA1 + SHA2
crypto,
/// Atomics (Large System Extension)
lse,
/// Rounding Double Multiply (ASIMDRDM)
rdm,
/// Release consistent Processor consistent (RcPc)
rcpc,
/// Vector Dot-Product (ASIMDDP)
dotprod,
}
|
is_aarch64_feature_detected!($t);
};
($t:tt) => {
compile_error!(concat!("unknown aarch64 target feature: ", $t))
|
random_line_split
|
reject-specialized-drops-8142.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Issue 8142: Test that Drop impls cannot be specialized beyond the
// predicates attached to the struct/enum definition itself.
#![feature(unsafe_destructor)]
trait Bound { fn foo(&self) { } }
struct K<'l1,'l2> { x: &'l1 i8, y: &'l2 u8 }
struct L<'l1,'l2> { x: &'l1 i8, y: &'l2 u8 }
struct M<'m> { x: &'m i8 }
struct N<'n> { x: &'n i8 }
struct O<To> { x: *const To }
struct P<Tp> { x: *const Tp }
struct Q<Tq> { x: *const Tq }
struct R<Tr> { x: *const Tr }
struct S<Ts:Bound> { x: *const Ts }
struct T<'t,Ts:'t> { x: &'t Ts }
struct U;
struct V<Tva, Tvb> { x: *const Tva, y: *const Tvb }
struct W<'l1, 'l2> { x: &'l1 i8, y: &'l2 u8 }
#[unsafe_destructor]
impl<'al,'adds_bnd:'al> Drop for K<'al,'adds_bnd> { // REJECT
//~^ ERROR The requirement `'adds_bnd : 'al` is added only by the Drop impl.
fn drop(&mut self) { } }
#[unsafe_destructor]
impl<'al,'adds_bnd> Drop for L<'al,'adds_bnd> where 'adds_bnd:'al { // REJECT
//~^ ERROR The requirement `'adds_bnd : 'al` is added only by the Drop impl.
fn drop(&mut self) { } }
#[unsafe_destructor]
impl<'ml> Drop for M<'ml> { fn drop(&mut self) { } } // ACCEPT
#[unsafe_destructor]
impl Drop for N<'static> { fn drop(&mut self) { } } // REJECT
//~^ ERROR Implementations of Drop cannot be specialized
#[unsafe_destructor]
impl<Cok_nobound> Drop for O<Cok_nobound> { fn drop(&mut self) { } } // ACCEPT
#[unsafe_destructor]
impl Drop for P<i8> { fn drop(&mut self) { } } // REJECT
//~^ ERROR Implementations of Drop cannot be specialized
#[unsafe_destructor]
impl<Adds_bnd:Bound> Drop for Q<Adds_bnd> { fn drop(&mut self) { } } // REJECT
//~^ ERROR The requirement `Adds_bnd : Bound` is added only by the Drop impl.
#[unsafe_destructor]
impl<'rbnd,Adds_rbnd:'rbnd> Drop for R<Adds_rbnd> { fn drop(&mut self) { } } // REJECT
//~^ ERROR The requirement `Adds_rbnd : 'rbnd` is added only by the Drop impl.
#[unsafe_destructor]
impl<Bs:Bound> Drop for S<Bs> { fn drop(&mut self) { } } // ACCEPT
|
#[unsafe_destructor]
impl<One> Drop for V<One,One> { fn drop(&mut self) { } } // REJECT
//~^ERROR Implementations of Drop cannot be specialized
#[unsafe_destructor]
impl<'lw> Drop for W<'lw,'lw> { fn drop(&mut self) { } } // REJECT
//~^ERROR Implementations of Drop cannot be specialized
pub fn main() { }
|
#[unsafe_destructor]
impl<'t,Bt:'t> Drop for T<'t,Bt> { fn drop(&mut self) { } } // ACCEPT
impl Drop for U { fn drop(&mut self) { } } // ACCEPT
|
random_line_split
|
reject-specialized-drops-8142.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Issue 8142: Test that Drop impls cannot be specialized beyond the
// predicates attached to the struct/enum definition itself.
#![feature(unsafe_destructor)]
trait Bound { fn foo(&self) { } }
struct K<'l1,'l2> { x: &'l1 i8, y: &'l2 u8 }
struct L<'l1,'l2> { x: &'l1 i8, y: &'l2 u8 }
struct M<'m> { x: &'m i8 }
struct N<'n> { x: &'n i8 }
struct O<To> { x: *const To }
struct P<Tp> { x: *const Tp }
struct Q<Tq> { x: *const Tq }
struct R<Tr> { x: *const Tr }
struct S<Ts:Bound> { x: *const Ts }
struct T<'t,Ts:'t> { x: &'t Ts }
struct U;
struct V<Tva, Tvb> { x: *const Tva, y: *const Tvb }
struct W<'l1, 'l2> { x: &'l1 i8, y: &'l2 u8 }
#[unsafe_destructor]
impl<'al,'adds_bnd:'al> Drop for K<'al,'adds_bnd> { // REJECT
//~^ ERROR The requirement `'adds_bnd : 'al` is added only by the Drop impl.
fn drop(&mut self) { } }
#[unsafe_destructor]
impl<'al,'adds_bnd> Drop for L<'al,'adds_bnd> where 'adds_bnd:'al { // REJECT
//~^ ERROR The requirement `'adds_bnd : 'al` is added only by the Drop impl.
fn drop(&mut self) { } }
#[unsafe_destructor]
impl<'ml> Drop for M<'ml> { fn drop(&mut self) { } } // ACCEPT
#[unsafe_destructor]
impl Drop for N<'static> { fn drop(&mut self) { } } // REJECT
//~^ ERROR Implementations of Drop cannot be specialized
#[unsafe_destructor]
impl<Cok_nobound> Drop for O<Cok_nobound> { fn drop(&mut self) { } } // ACCEPT
#[unsafe_destructor]
impl Drop for P<i8> { fn
|
(&mut self) { } } // REJECT
//~^ ERROR Implementations of Drop cannot be specialized
#[unsafe_destructor]
impl<Adds_bnd:Bound> Drop for Q<Adds_bnd> { fn drop(&mut self) { } } // REJECT
//~^ ERROR The requirement `Adds_bnd : Bound` is added only by the Drop impl.
#[unsafe_destructor]
impl<'rbnd,Adds_rbnd:'rbnd> Drop for R<Adds_rbnd> { fn drop(&mut self) { } } // REJECT
//~^ ERROR The requirement `Adds_rbnd : 'rbnd` is added only by the Drop impl.
#[unsafe_destructor]
impl<Bs:Bound> Drop for S<Bs> { fn drop(&mut self) { } } // ACCEPT
#[unsafe_destructor]
impl<'t,Bt:'t> Drop for T<'t,Bt> { fn drop(&mut self) { } } // ACCEPT
impl Drop for U { fn drop(&mut self) { } } // ACCEPT
#[unsafe_destructor]
impl<One> Drop for V<One,One> { fn drop(&mut self) { } } // REJECT
//~^ERROR Implementations of Drop cannot be specialized
#[unsafe_destructor]
impl<'lw> Drop for W<'lw,'lw> { fn drop(&mut self) { } } // REJECT
//~^ERROR Implementations of Drop cannot be specialized
pub fn main() { }
|
drop
|
identifier_name
|
cell.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Shareable mutable containers.
//!
//! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
//! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
//! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
//! with typical Rust types that exhibit 'inherited mutability'.
//!
//! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` provides `get` and `set`
//! methods that change the interior value with a single method call. `Cell<T>` though is only
//! compatible with types that implement `Copy`. For other types, one must use the `RefCell<T>`
//! type, acquiring a write lock before mutating.
//!
//! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
//! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
//! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
//! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
//! to borrow a value that is already mutably borrowed; when this happens it results in thread
//! panic.
//!
//! # When to choose interior mutability
//!
//! The more common inherited mutability, where one must have unique access to mutate a value, is
//! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
//! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
//! interior mutability is something of a last resort. Since cell types enable mutation where it
//! would otherwise be disallowed though, there are occasions when interior mutability might be
//! appropriate, or even *must* be used, e.g.
//!
//! * Introducing inherited mutability roots to shared types.
//! * Implementation details of logically-immutable methods.
//! * Mutating implementations of `clone`.
//!
//! ## Introducing inherited mutability roots to shared types
//!
//! Shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
//! cloned and shared between multiple parties. Because the contained values may be
//! multiply-aliased, they can only be borrowed as shared references, not mutable references.
//! Without cells it would be impossible to mutate data inside of shared boxes at all!
//!
//! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
//! mutability:
//!
//! ```
//! use std::collections::HashMap;
//! use std::cell::RefCell;
//! use std::rc::Rc;
//!
//! fn main() {
//! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
//! shared_map.borrow_mut().insert("africa", 92388);
//! shared_map.borrow_mut().insert("kyoto", 11837);
//! shared_map.borrow_mut().insert("piccadilly", 11826);
//! shared_map.borrow_mut().insert("marbles", 38);
//! }
//! ```
//!
//! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
//! scenarios. Consider using `Mutex<T>` if you need shared mutability in a multi-threaded
//! situation.
//!
//! ## Implementation details of logically-immutable methods
//!
//! Occasionally it may be desirable not to expose in an API that there is mutation happening
//! "under the hood". This may be because logically the operation is immutable, but e.g. caching
//! forces the implementation to perform mutation; or because you must employ mutation to implement
//! a trait method that was originally defined to take `&self`.
//!
//! ```
//! use std::cell::RefCell;
//!
//! struct Graph {
//! edges: Vec<(i32, i32)>,
//! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
//! }
//!
//! impl Graph {
//! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
//! // Create a new scope to contain the lifetime of the
//! // dynamic borrow
//! {
//! // Take a reference to the inside of cache cell
//! let mut cache = self.span_tree_cache.borrow_mut();
//! if cache.is_some() {
//! return cache.as_ref().unwrap().clone();
//! }
//!
//! let span_tree = self.calc_span_tree();
//! *cache = Some(span_tree);
//! }
//!
//! // Recursive call to return the just-cached value.
//! // Note that if we had not let the previous borrow
//! // of the cache fall out of scope then the subsequent
//! // recursive borrow would cause a dynamic thread panic.
//! // This is the major hazard of using `RefCell`.
//! self.minimum_spanning_tree()
//! }
//! # fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
//! }
//! ```
//!
//! ## Mutating implementations of `clone`
//!
//! This is simply a special - but common - case of the previous: hiding mutability for operations
//! that appear to be immutable. The `clone` method is expected to not change the source value, and
//! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the
//! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
//! `Cell<T>`.
//!
//! ```
//! use std::cell::Cell;
//!
//! struct Rc<T> {
//! ptr: *mut RcBox<T>
//! }
//!
//! struct RcBox<T> {
//! value: T,
//! refcount: Cell<usize>
//! }
//!
//! impl<T> Clone for Rc<T> {
//! fn clone(&self) -> Rc<T> {
//! unsafe {
//! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1);
//! Rc { ptr: self.ptr }
//! }
//! }
//! }
//! ```
//!
#![stable(feature = "rust1", since = "1.0.0")]
use clone::Clone;
use cmp::PartialEq;
use default::Default;
use marker::{Copy, Send, Sync, Sized};
use ops::{Deref, DerefMut, Drop};
use option::Option;
use option::Option::{None, Some};
/// A mutable memory location that admits only `Copy` data.
///
/// See the [module-level documentation](index.html) for more.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Cell<T> {
value: UnsafeCell<T>,
}
impl<T:Copy> Cell<T> {
/// Creates a new `Cell` containing the given value.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn new(value: T) -> Cell<T> {
Cell {
value: UnsafeCell::new(value),
}
}
/// Returns a copy of the contained value.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
///
/// let five = c.get();
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get(&self) -> T {
unsafe{ *self.value.get() }
}
/// Sets the contained value.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
///
/// c.set(10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn set(&self, value: T) {
unsafe {
*self.value.get() = value;
}
}
/// Gets a reference to the underlying `UnsafeCell`.
///
/// # Unsafety
///
/// This function is `unsafe` because `UnsafeCell`'s field is public.
///
/// # Examples
///
/// ```
/// # #![feature(core)]
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
///
/// let uc = unsafe { c.as_unsafe_cell() };
/// ```
#[inline]
#[unstable(feature = "core")]
pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> {
&self.value
}
}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T> Send for Cell<T> where T: Send {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:Copy> Clone for Cell<T> {
#[inline]
fn clone(&self) -> Cell<T> {
Cell::new(self.get())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:Default + Copy> Default for Cell<T> {
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
fn default() -> Cell<T> {
Cell::new(Default::default())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:PartialEq + Copy> PartialEq for Cell<T> {
#[inline]
fn eq(&self, other: &Cell<T>) -> bool {
self.get() == other.get()
}
}
/// A mutable memory location with dynamically checked borrow rules
///
/// See the [module-level documentation](index.html) for more.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RefCell<T:?Sized> {
borrow: Cell<BorrowFlag>,
value: UnsafeCell<T>,
}
/// An enumeration of values returned from the `state` method on a `RefCell<T>`.
#[derive(Copy, Clone, PartialEq, Debug)]
#[unstable(feature = "std_misc")]
pub enum BorrowState {
/// The cell is currently being read, there is at least one active `borrow`.
Reading,
/// The cell is currently being written to, there is an active `borrow_mut`.
Writing,
/// There are no outstanding borrows on this cell.
Unused,
}
// Values [1, MAX-1] represent the number of `Ref` active
// (will not outgrow its range since `usize` is the size of the address space)
type BorrowFlag = usize;
const UNUSED: BorrowFlag = 0;
const WRITING: BorrowFlag =!0;
impl<T> RefCell<T> {
/// Creates a new `RefCell` containing `value`.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn new(value: T) -> RefCell<T> {
RefCell {
value: UnsafeCell::new(value),
borrow: Cell::new(UNUSED),
}
}
/// Consumes the `RefCell`, returning the wrapped value.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// let five = c.into_inner();
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn into_inner(self) -> T {
// Since this function takes `self` (the `RefCell`) by value, the
// compiler statically verifies that it is not currently borrowed.
// Therefore the following assertion is just a `debug_assert!`.
debug_assert!(self.borrow.get() == UNUSED);
unsafe { self.value.into_inner() }
}
}
impl<T:?Sized> RefCell<T> {
/// Query the current state of this `RefCell`
///
/// The returned value can be dispatched on to determine if a call to
/// `borrow` or `borrow_mut` would succeed.
#[unstable(feature = "std_misc")]
#[inline]
pub fn borrow_state(&self) -> BorrowState {
match self.borrow.get() {
WRITING => BorrowState::Writing,
UNUSED => BorrowState::Unused,
_ => BorrowState::Reading,
}
}
/// Immutably borrows the wrapped value.
///
/// The borrow lasts until the returned `Ref` exits scope. Multiple
/// immutable borrows can be taken out at the same time.
///
/// # Panics
///
/// Panics if the value is currently mutably borrowed.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// let borrowed_five = c.borrow();
/// let borrowed_five2 = c.borrow();
/// ```
///
/// An example of panic:
///
/// ```
/// use std::cell::RefCell;
/// use std::thread;
///
/// let result = thread::spawn(move || {
/// let c = RefCell::new(5);
/// let m = c.borrow_mut();
///
/// let b = c.borrow(); // this causes a panic
/// }).join();
///
/// assert!(result.is_err());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn borrow<'a>(&'a self) -> Ref<'a, T> {
match BorrowRef::new(&self.borrow) {
Some(b) => Ref {
_value: unsafe { &*self.value.get() },
_borrow: b,
},
None => panic!("RefCell<T> already mutably borrowed"),
}
}
/// Mutably borrows the wrapped value.
///
/// The borrow lasts until the returned `RefMut` exits scope. The value
/// cannot be borrowed while this borrow is active.
///
/// # Panics
///
/// Panics if the value is currently borrowed.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// let borrowed_five = c.borrow_mut();
/// ```
///
/// An example of panic:
///
/// ```
/// use std::cell::RefCell;
/// use std::thread;
///
/// let result = thread::spawn(move || {
/// let c = RefCell::new(5);
/// let m = c.borrow();
///
/// let b = c.borrow_mut(); // this causes a panic
/// }).join();
///
/// assert!(result.is_err());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> {
match BorrowRefMut::new(&self.borrow) {
Some(b) => RefMut {
_value: unsafe { &mut *self.value.get() },
_borrow: b,
},
None => panic!("RefCell<T> already borrowed"),
}
}
/// Gets a reference to the underlying `UnsafeCell`.
///
/// This can be used to circumvent `RefCell`'s safety checks.
///
/// This function is `unsafe` because `UnsafeCell`'s field is public.
#[inline]
#[unstable(feature = "core")]
pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> {
&self.value
}
}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T:?Sized> Send for RefCell<T> where T: Send {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for RefCell<T> {
#[inline]
fn clone(&self) -> RefCell<T> {
RefCell::new(self.borrow().clone())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:Default> Default for RefCell<T> {
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
fn default() -> RefCell<T> {
RefCell::new(Default::default())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for RefCell<T> {
#[inline]
fn eq(&self, other: &RefCell<T>) -> bool {
*self.borrow() == *other.borrow()
}
}
struct BorrowRef<'b> {
_borrow: &'b Cell<BorrowFlag>,
}
impl<'b> BorrowRef<'b> {
#[inline]
fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
match borrow.get() {
WRITING => None,
b => {
borrow.set(b + 1);
Some(BorrowRef { _borrow: borrow })
},
}
}
}
impl<'b> Drop for BorrowRef<'b> {
#[inline]
fn drop(&mut self) {
let borrow = self._borrow.get();
debug_assert!(borrow!= WRITING && borrow!= UNUSED);
self._borrow.set(borrow - 1);
}
}
impl<'b> Clone for BorrowRef<'b> {
#[inline]
fn clone(&self) -> BorrowRef<'b> {
// Since this Ref exists, we know the borrow flag
// is not set to WRITING.
let borrow = self._borrow.get();
debug_assert!(borrow!= WRITING && borrow!= UNUSED);
self._borrow.set(borrow + 1);
BorrowRef { _borrow: self._borrow }
}
}
/// Wraps a borrowed reference to a value in a `RefCell` box.
/// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
///
/// See the [module-level documentation](index.html) for more.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Ref<'b, T:?Sized + 'b> {
// FIXME #12808: strange name to try to avoid interfering with
// field accesses of the contained type via Deref
_value: &'b T,
_borrow: BorrowRef<'b>,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'b, T:?Sized> Deref for Ref<'b, T> {
type Target = T;
#[inline]
fn
|
<'a>(&'a self) -> &'a T {
self._value
}
}
/// Copies a `Ref`.
///
/// The `RefCell` is already immutably borrowed, so this cannot fail.
///
/// A `Clone` implementation would interfere with the widespread
/// use of `r.borrow().clone()` to clone the contents of a `RefCell`.
#[unstable(feature = "core",
reason = "likely to be moved to a method, pending language changes")]
#[inline]
pub fn clone_ref<'b, T:Clone>(orig: &Ref<'b, T>) -> Ref<'b, T> {
Ref {
_value: orig._value,
_borrow: orig._borrow.clone(),
}
}
struct BorrowRefMut<'b> {
_borrow: &'b Cell<BorrowFlag>,
}
impl<'b> Drop for BorrowRefMut<'b> {
#[inline]
fn drop(&mut self) {
let borrow = self._borrow.get();
debug_assert!(borrow == WRITING);
self._borrow.set(UNUSED);
}
}
impl<'b> BorrowRefMut<'b> {
#[inline]
fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
match borrow.get() {
UNUSED => {
borrow.set(WRITING);
Some(BorrowRefMut { _borrow: borrow })
},
_ => None,
}
}
}
/// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
///
/// See the [module-level documentation](index.html) for more.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RefMut<'b, T:?Sized + 'b> {
// FIXME #12808: strange name to try to avoid interfering with
// field accesses of the contained type via Deref
_value: &'b mut T,
_borrow: BorrowRefMut<'b>,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'b, T:?Sized> Deref for RefMut<'b, T> {
type Target = T;
#[inline]
fn deref<'a>(&'a self) -> &'a T {
self._value
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'b, T:?Sized> DerefMut for RefMut<'b, T> {
#[inline]
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
self._value
}
}
/// The core primitive for interior mutability in Rust.
///
/// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
/// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
/// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
/// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
///
/// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
///
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
/// use std::marker::Sync;
///
/// struct NotThreadSafe<T> {
/// value: UnsafeCell<T>,
/// }
///
/// unsafe impl<T> Sync for NotThreadSafe<T> {}
/// ```
///
/// **NOTE:** `UnsafeCell<T>`'s fields are public to allow static initializers. It is not
/// recommended to access its fields directly, `get` should be used instead.
#[lang = "unsafe_cell"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct UnsafeCell<T:?Sized> {
/// Wrapped value
///
/// This field should not be accessed directly, it is made public for static
/// initializers.
#[unstable(feature = "core")]
pub value: T,
}
impl<T:?Sized>!Sync for UnsafeCell<T> {}
impl<T> UnsafeCell<T> {
/// Constructs a new instance of `UnsafeCell` which will wrap the specified
/// value.
///
/// All access to the inner value through methods is `unsafe`, and it is highly discouraged to
/// access the fields directly.
///
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
///
/// let uc = UnsafeCell::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn new(value: T) -> UnsafeCell<T> {
UnsafeCell { value: value }
}
/// Unwraps the value.
///
/// # Unsafety
///
/// This function is unsafe because there is no guarantee that this or other threads are
/// currently inspecting the inner value.
///
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
///
/// let uc = UnsafeCell::new(5);
///
/// let five = unsafe { uc.into_inner() };
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn into_inner(self) -> T { self.value }
}
impl<T:?Sized> UnsafeCell<T> {
/// Gets a mutable pointer to the wrapped value.
///
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
///
/// let uc = UnsafeCell::new(5);
///
/// let five = uc.get();
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get(&self) -> *mut T {
// FIXME(#23542) Replace with type ascription.
#![allow(trivial_casts)]
&self.value as *const T as *mut T
}
}
|
deref
|
identifier_name
|
cell.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Shareable mutable containers.
//!
//! Values of the `Cell<T>` and `RefCell<T>` types may be mutated through shared references (i.e.
//! the common `&T` type), whereas most Rust types can only be mutated through unique (`&mut T`)
//! references. We say that `Cell<T>` and `RefCell<T>` provide 'interior mutability', in contrast
//! with typical Rust types that exhibit 'inherited mutability'.
//!
//! Cell types come in two flavors: `Cell<T>` and `RefCell<T>`. `Cell<T>` provides `get` and `set`
//! methods that change the interior value with a single method call. `Cell<T>` though is only
//! compatible with types that implement `Copy`. For other types, one must use the `RefCell<T>`
//! type, acquiring a write lock before mutating.
//!
//! `RefCell<T>` uses Rust's lifetimes to implement 'dynamic borrowing', a process whereby one can
//! claim temporary, exclusive, mutable access to the inner value. Borrows for `RefCell<T>`s are
//! tracked 'at runtime', unlike Rust's native reference types which are entirely tracked
//! statically, at compile time. Because `RefCell<T>` borrows are dynamic it is possible to attempt
//! to borrow a value that is already mutably borrowed; when this happens it results in thread
//! panic.
//!
//! # When to choose interior mutability
//!
//! The more common inherited mutability, where one must have unique access to mutate a value, is
//! one of the key language elements that enables Rust to reason strongly about pointer aliasing,
//! statically preventing crash bugs. Because of that, inherited mutability is preferred, and
//! interior mutability is something of a last resort. Since cell types enable mutation where it
//! would otherwise be disallowed though, there are occasions when interior mutability might be
//! appropriate, or even *must* be used, e.g.
//!
//! * Introducing inherited mutability roots to shared types.
//! * Implementation details of logically-immutable methods.
//! * Mutating implementations of `clone`.
//!
//! ## Introducing inherited mutability roots to shared types
//!
//! Shared smart pointer types, including `Rc<T>` and `Arc<T>`, provide containers that can be
//! cloned and shared between multiple parties. Because the contained values may be
//! multiply-aliased, they can only be borrowed as shared references, not mutable references.
//! Without cells it would be impossible to mutate data inside of shared boxes at all!
//!
//! It's very common then to put a `RefCell<T>` inside shared pointer types to reintroduce
//! mutability:
//!
//! ```
//! use std::collections::HashMap;
//! use std::cell::RefCell;
//! use std::rc::Rc;
//!
//! fn main() {
//! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new()));
//! shared_map.borrow_mut().insert("africa", 92388);
//! shared_map.borrow_mut().insert("kyoto", 11837);
//! shared_map.borrow_mut().insert("piccadilly", 11826);
//! shared_map.borrow_mut().insert("marbles", 38);
//! }
//! ```
//!
//! Note that this example uses `Rc<T>` and not `Arc<T>`. `RefCell<T>`s are for single-threaded
//! scenarios. Consider using `Mutex<T>` if you need shared mutability in a multi-threaded
//! situation.
//!
//! ## Implementation details of logically-immutable methods
//!
//! Occasionally it may be desirable not to expose in an API that there is mutation happening
//! "under the hood". This may be because logically the operation is immutable, but e.g. caching
//! forces the implementation to perform mutation; or because you must employ mutation to implement
//! a trait method that was originally defined to take `&self`.
//!
//! ```
//! use std::cell::RefCell;
//!
//! struct Graph {
//! edges: Vec<(i32, i32)>,
//! span_tree_cache: RefCell<Option<Vec<(i32, i32)>>>
//! }
//!
//! impl Graph {
//! fn minimum_spanning_tree(&self) -> Vec<(i32, i32)> {
//! // Create a new scope to contain the lifetime of the
//! // dynamic borrow
//! {
//! // Take a reference to the inside of cache cell
//! let mut cache = self.span_tree_cache.borrow_mut();
//! if cache.is_some() {
//! return cache.as_ref().unwrap().clone();
//! }
//!
//! let span_tree = self.calc_span_tree();
//! *cache = Some(span_tree);
//! }
//!
//! // Recursive call to return the just-cached value.
//! // Note that if we had not let the previous borrow
//! // of the cache fall out of scope then the subsequent
//! // recursive borrow would cause a dynamic thread panic.
//! // This is the major hazard of using `RefCell`.
//! self.minimum_spanning_tree()
//! }
//! # fn calc_span_tree(&self) -> Vec<(i32, i32)> { vec![] }
//! }
//! ```
//!
//! ## Mutating implementations of `clone`
//!
//! This is simply a special - but common - case of the previous: hiding mutability for operations
//! that appear to be immutable. The `clone` method is expected to not change the source value, and
//! is declared to take `&self`, not `&mut self`. Therefore any mutation that happens in the
//! `clone` method must use cell types. For example, `Rc<T>` maintains its reference counts within a
//! `Cell<T>`.
//!
//! ```
//! use std::cell::Cell;
//!
//! struct Rc<T> {
//! ptr: *mut RcBox<T>
//! }
//!
//! struct RcBox<T> {
//! value: T,
//! refcount: Cell<usize>
//! }
//!
//! impl<T> Clone for Rc<T> {
//! fn clone(&self) -> Rc<T> {
//! unsafe {
//! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1);
//! Rc { ptr: self.ptr }
//! }
//! }
//! }
//! ```
//!
#![stable(feature = "rust1", since = "1.0.0")]
use clone::Clone;
use cmp::PartialEq;
use default::Default;
use marker::{Copy, Send, Sync, Sized};
use ops::{Deref, DerefMut, Drop};
use option::Option;
use option::Option::{None, Some};
/// A mutable memory location that admits only `Copy` data.
///
/// See the [module-level documentation](index.html) for more.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Cell<T> {
value: UnsafeCell<T>,
}
impl<T:Copy> Cell<T> {
/// Creates a new `Cell` containing the given value.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn new(value: T) -> Cell<T> {
Cell {
value: UnsafeCell::new(value),
}
}
/// Returns a copy of the contained value.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
///
/// let five = c.get();
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get(&self) -> T {
unsafe{ *self.value.get() }
}
/// Sets the contained value.
///
/// # Examples
///
/// ```
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
///
/// c.set(10);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn set(&self, value: T) {
unsafe {
*self.value.get() = value;
}
}
/// Gets a reference to the underlying `UnsafeCell`.
///
/// # Unsafety
///
/// This function is `unsafe` because `UnsafeCell`'s field is public.
///
/// # Examples
///
/// ```
/// # #![feature(core)]
/// use std::cell::Cell;
///
/// let c = Cell::new(5);
///
/// let uc = unsafe { c.as_unsafe_cell() };
/// ```
#[inline]
#[unstable(feature = "core")]
pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> {
&self.value
}
}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T> Send for Cell<T> where T: Send {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:Copy> Clone for Cell<T> {
#[inline]
fn clone(&self) -> Cell<T> {
Cell::new(self.get())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:Default + Copy> Default for Cell<T> {
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
fn default() -> Cell<T> {
Cell::new(Default::default())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:PartialEq + Copy> PartialEq for Cell<T> {
#[inline]
fn eq(&self, other: &Cell<T>) -> bool {
self.get() == other.get()
}
}
/// A mutable memory location with dynamically checked borrow rules
///
/// See the [module-level documentation](index.html) for more.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RefCell<T:?Sized> {
borrow: Cell<BorrowFlag>,
value: UnsafeCell<T>,
}
/// An enumeration of values returned from the `state` method on a `RefCell<T>`.
#[derive(Copy, Clone, PartialEq, Debug)]
#[unstable(feature = "std_misc")]
pub enum BorrowState {
/// The cell is currently being read, there is at least one active `borrow`.
Reading,
/// The cell is currently being written to, there is an active `borrow_mut`.
Writing,
/// There are no outstanding borrows on this cell.
Unused,
}
// Values [1, MAX-1] represent the number of `Ref` active
// (will not outgrow its range since `usize` is the size of the address space)
type BorrowFlag = usize;
const UNUSED: BorrowFlag = 0;
const WRITING: BorrowFlag =!0;
impl<T> RefCell<T> {
/// Creates a new `RefCell` containing `value`.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn new(value: T) -> RefCell<T> {
RefCell {
value: UnsafeCell::new(value),
borrow: Cell::new(UNUSED),
}
}
/// Consumes the `RefCell`, returning the wrapped value.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// let five = c.into_inner();
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn into_inner(self) -> T {
// Since this function takes `self` (the `RefCell`) by value, the
// compiler statically verifies that it is not currently borrowed.
// Therefore the following assertion is just a `debug_assert!`.
debug_assert!(self.borrow.get() == UNUSED);
unsafe { self.value.into_inner() }
}
}
impl<T:?Sized> RefCell<T> {
/// Query the current state of this `RefCell`
///
/// The returned value can be dispatched on to determine if a call to
/// `borrow` or `borrow_mut` would succeed.
#[unstable(feature = "std_misc")]
#[inline]
pub fn borrow_state(&self) -> BorrowState {
match self.borrow.get() {
WRITING => BorrowState::Writing,
UNUSED => BorrowState::Unused,
_ => BorrowState::Reading,
}
}
/// Immutably borrows the wrapped value.
///
/// The borrow lasts until the returned `Ref` exits scope. Multiple
/// immutable borrows can be taken out at the same time.
///
/// # Panics
///
/// Panics if the value is currently mutably borrowed.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// let borrowed_five = c.borrow();
/// let borrowed_five2 = c.borrow();
/// ```
///
/// An example of panic:
///
/// ```
/// use std::cell::RefCell;
/// use std::thread;
///
/// let result = thread::spawn(move || {
/// let c = RefCell::new(5);
/// let m = c.borrow_mut();
///
/// let b = c.borrow(); // this causes a panic
/// }).join();
///
/// assert!(result.is_err());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn borrow<'a>(&'a self) -> Ref<'a, T> {
match BorrowRef::new(&self.borrow) {
Some(b) => Ref {
_value: unsafe { &*self.value.get() },
_borrow: b,
},
None => panic!("RefCell<T> already mutably borrowed"),
}
}
/// Mutably borrows the wrapped value.
///
/// The borrow lasts until the returned `RefMut` exits scope. The value
/// cannot be borrowed while this borrow is active.
///
/// # Panics
///
/// Panics if the value is currently borrowed.
///
/// # Examples
///
/// ```
/// use std::cell::RefCell;
///
/// let c = RefCell::new(5);
///
/// let borrowed_five = c.borrow_mut();
/// ```
///
/// An example of panic:
///
/// ```
/// use std::cell::RefCell;
/// use std::thread;
///
/// let result = thread::spawn(move || {
/// let c = RefCell::new(5);
/// let m = c.borrow();
///
/// let b = c.borrow_mut(); // this causes a panic
/// }).join();
///
/// assert!(result.is_err());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> {
|
Some(b) => RefMut {
_value: unsafe { &mut *self.value.get() },
_borrow: b,
},
None => panic!("RefCell<T> already borrowed"),
}
}
/// Gets a reference to the underlying `UnsafeCell`.
///
/// This can be used to circumvent `RefCell`'s safety checks.
///
/// This function is `unsafe` because `UnsafeCell`'s field is public.
#[inline]
#[unstable(feature = "core")]
pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> {
&self.value
}
}
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl<T:?Sized> Send for RefCell<T> where T: Send {}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T: Clone> Clone for RefCell<T> {
#[inline]
fn clone(&self) -> RefCell<T> {
RefCell::new(self.borrow().clone())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:Default> Default for RefCell<T> {
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
fn default() -> RefCell<T> {
RefCell::new(Default::default())
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<T:?Sized + PartialEq> PartialEq for RefCell<T> {
#[inline]
fn eq(&self, other: &RefCell<T>) -> bool {
*self.borrow() == *other.borrow()
}
}
struct BorrowRef<'b> {
_borrow: &'b Cell<BorrowFlag>,
}
impl<'b> BorrowRef<'b> {
#[inline]
fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRef<'b>> {
match borrow.get() {
WRITING => None,
b => {
borrow.set(b + 1);
Some(BorrowRef { _borrow: borrow })
},
}
}
}
impl<'b> Drop for BorrowRef<'b> {
#[inline]
fn drop(&mut self) {
let borrow = self._borrow.get();
debug_assert!(borrow!= WRITING && borrow!= UNUSED);
self._borrow.set(borrow - 1);
}
}
impl<'b> Clone for BorrowRef<'b> {
#[inline]
fn clone(&self) -> BorrowRef<'b> {
// Since this Ref exists, we know the borrow flag
// is not set to WRITING.
let borrow = self._borrow.get();
debug_assert!(borrow!= WRITING && borrow!= UNUSED);
self._borrow.set(borrow + 1);
BorrowRef { _borrow: self._borrow }
}
}
/// Wraps a borrowed reference to a value in a `RefCell` box.
/// A wrapper type for an immutably borrowed value from a `RefCell<T>`.
///
/// See the [module-level documentation](index.html) for more.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct Ref<'b, T:?Sized + 'b> {
// FIXME #12808: strange name to try to avoid interfering with
// field accesses of the contained type via Deref
_value: &'b T,
_borrow: BorrowRef<'b>,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'b, T:?Sized> Deref for Ref<'b, T> {
type Target = T;
#[inline]
fn deref<'a>(&'a self) -> &'a T {
self._value
}
}
/// Copies a `Ref`.
///
/// The `RefCell` is already immutably borrowed, so this cannot fail.
///
/// A `Clone` implementation would interfere with the widespread
/// use of `r.borrow().clone()` to clone the contents of a `RefCell`.
#[unstable(feature = "core",
reason = "likely to be moved to a method, pending language changes")]
#[inline]
pub fn clone_ref<'b, T:Clone>(orig: &Ref<'b, T>) -> Ref<'b, T> {
Ref {
_value: orig._value,
_borrow: orig._borrow.clone(),
}
}
struct BorrowRefMut<'b> {
_borrow: &'b Cell<BorrowFlag>,
}
impl<'b> Drop for BorrowRefMut<'b> {
#[inline]
fn drop(&mut self) {
let borrow = self._borrow.get();
debug_assert!(borrow == WRITING);
self._borrow.set(UNUSED);
}
}
impl<'b> BorrowRefMut<'b> {
#[inline]
fn new(borrow: &'b Cell<BorrowFlag>) -> Option<BorrowRefMut<'b>> {
match borrow.get() {
UNUSED => {
borrow.set(WRITING);
Some(BorrowRefMut { _borrow: borrow })
},
_ => None,
}
}
}
/// A wrapper type for a mutably borrowed value from a `RefCell<T>`.
///
/// See the [module-level documentation](index.html) for more.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RefMut<'b, T:?Sized + 'b> {
// FIXME #12808: strange name to try to avoid interfering with
// field accesses of the contained type via Deref
_value: &'b mut T,
_borrow: BorrowRefMut<'b>,
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'b, T:?Sized> Deref for RefMut<'b, T> {
type Target = T;
#[inline]
fn deref<'a>(&'a self) -> &'a T {
self._value
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'b, T:?Sized> DerefMut for RefMut<'b, T> {
#[inline]
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
self._value
}
}
/// The core primitive for interior mutability in Rust.
///
/// `UnsafeCell<T>` is a type that wraps some `T` and indicates unsafe interior operations on the
/// wrapped type. Types with an `UnsafeCell<T>` field are considered to have an 'unsafe interior'.
/// The `UnsafeCell<T>` type is the only legal way to obtain aliasable data that is considered
/// mutable. In general, transmuting an `&T` type into an `&mut T` is considered undefined behavior.
///
/// Types like `Cell<T>` and `RefCell<T>` use this type to wrap their internal data.
///
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
/// use std::marker::Sync;
///
/// struct NotThreadSafe<T> {
/// value: UnsafeCell<T>,
/// }
///
/// unsafe impl<T> Sync for NotThreadSafe<T> {}
/// ```
///
/// **NOTE:** `UnsafeCell<T>`'s fields are public to allow static initializers. It is not
/// recommended to access its fields directly, `get` should be used instead.
#[lang = "unsafe_cell"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct UnsafeCell<T:?Sized> {
/// Wrapped value
///
/// This field should not be accessed directly, it is made public for static
/// initializers.
#[unstable(feature = "core")]
pub value: T,
}
impl<T:?Sized>!Sync for UnsafeCell<T> {}
impl<T> UnsafeCell<T> {
/// Constructs a new instance of `UnsafeCell` which will wrap the specified
/// value.
///
/// All access to the inner value through methods is `unsafe`, and it is highly discouraged to
/// access the fields directly.
///
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
///
/// let uc = UnsafeCell::new(5);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn new(value: T) -> UnsafeCell<T> {
UnsafeCell { value: value }
}
/// Unwraps the value.
///
/// # Unsafety
///
/// This function is unsafe because there is no guarantee that this or other threads are
/// currently inspecting the inner value.
///
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
///
/// let uc = UnsafeCell::new(5);
///
/// let five = unsafe { uc.into_inner() };
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn into_inner(self) -> T { self.value }
}
impl<T:?Sized> UnsafeCell<T> {
/// Gets a mutable pointer to the wrapped value.
///
/// # Examples
///
/// ```
/// use std::cell::UnsafeCell;
///
/// let uc = UnsafeCell::new(5);
///
/// let five = uc.get();
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn get(&self) -> *mut T {
// FIXME(#23542) Replace with type ascription.
#![allow(trivial_casts)]
&self.value as *const T as *mut T
}
}
|
match BorrowRefMut::new(&self.borrow) {
|
random_line_split
|
num.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Integer and floating-point number formatting
// FIXME: #6220 Implement floating point formatting
#![allow(unsigned_negation)]
use fmt;
use iter::IteratorExt;
use num::{Int, cast};
use slice::SliceExt;
use str;
/// A type that represents a specific radix
#[doc(hidden)]
trait GenericRadix {
/// The number of digits.
fn base(&self) -> u8;
/// A radix-specific prefix string.
fn prefix(&self) -> &'static str { "" }
/// Converts an integer to corresponding radix digit.
fn digit(&self, x: u8) -> u8;
/// Format an integer using the radix using a formatter.
fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
// The radix can be as low as 2, so we need a buffer of at least 64
// characters for a base 2 number.
let zero = Int::zero();
let is_positive = x >= zero;
let mut buf = [0u8; 64];
let mut curr = buf.len();
let base = cast(self.base()).unwrap();
if is_positive {
// Accumulate each digit of the number from the least significant
// to the most significant figure.
for byte in buf.iter_mut().rev() {
let n = x % base; // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero
|
; // No more digits left to accumulate.
}
} else {
// Do the same as above, but accounting for two's complement.
for byte in buf.iter_mut().rev() {
let n = zero - (x % base); // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero { break }; // No more digits left to accumulate.
}
}
let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) };
f.pad_integral(is_positive, self.prefix(), buf)
}
}
/// A binary (base 2) radix
#[derive(Clone, PartialEq)]
struct Binary;
/// An octal (base 8) radix
#[derive(Clone, PartialEq)]
struct Octal;
/// A decimal (base 10) radix
#[derive(Clone, PartialEq)]
struct Decimal;
/// A hexadecimal (base 16) radix, formatted with lower-case characters
#[derive(Clone, PartialEq)]
struct LowerHex;
/// A hexadecimal (base 16) radix, formatted with upper-case characters
#[derive(Clone, PartialEq)]
pub struct UpperHex;
macro_rules! radix {
($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
impl GenericRadix for $T {
fn base(&self) -> u8 { $base }
fn prefix(&self) -> &'static str { $prefix }
fn digit(&self, x: u8) -> u8 {
match x {
$($x => $conv,)+
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
}
}
radix! { Binary, 2, "0b", x @ 0... 2 => b'0' + x }
radix! { Octal, 8, "0o", x @ 0... 7 => b'0' + x }
radix! { Decimal, 10, "", x @ 0... 9 => b'0' + x }
radix! { LowerHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'a' + (x - 10) }
radix! { UpperHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'A' + (x - 10) }
/// A radix with in the range of `2..36`.
#[derive(Clone, Copy, PartialEq)]
#[unstable = "may be renamed or move to a different module"]
pub struct Radix {
base: u8,
}
impl Radix {
fn new(base: u8) -> Radix {
assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
Radix { base: base }
}
}
impl GenericRadix for Radix {
fn base(&self) -> u8 { self.base }
fn digit(&self, x: u8) -> u8 {
match x {
x @ 0... 9 => b'0' + x,
x if x < self.base() => b'a' + (x - 10),
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
/// A helper type for formatting radixes.
#[unstable = "may be renamed or move to a different module"]
#[derive(Copy)]
pub struct RadixFmt<T, R>(T, R);
/// Constructs a radix formatter in the range of `2..36`.
///
/// # Example
///
/// ```
/// use std::fmt::radix;
/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string());
/// ```
#[unstable = "may be renamed or move to a different module"]
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base))
}
macro_rules! radix_fmt {
($T:ty as $U:ty, $fmt:ident, $S:expr) => {
#[stable]
impl fmt::Debug for RadixFmt<$T, Radix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[stable]
impl fmt::Display for RadixFmt<$T, Radix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
}
}
}
}
macro_rules! int_base {
($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
#[stable]
impl fmt::$Trait for $T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
$Radix.fmt_int(*self as $U, f)
}
}
}
}
macro_rules! show {
($T:ident with $S:expr) => {
#[stable]
impl fmt::Debug for $T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
}
}
macro_rules! integer {
($Int:ident, $Uint:ident) => {
integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) }
};
($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => {
int_base! { Display for $Int as $Int -> Decimal }
int_base! { Binary for $Int as $Uint -> Binary }
int_base! { Octal for $Int as $Uint -> Octal }
int_base! { LowerHex for $Int as $Uint -> LowerHex }
int_base! { UpperHex for $Int as $Uint -> UpperHex }
radix_fmt! { $Int as $Int, fmt_int, $SI }
show! { $Int with $SI }
int_base! { Display for $Uint as $Uint -> Decimal }
int_base! { Binary for $Uint as $Uint -> Binary }
int_base! { Octal for $Uint as $Uint -> Octal }
int_base! { LowerHex for $Uint as $Uint -> LowerHex }
int_base! { UpperHex for $Uint as $Uint -> UpperHex }
radix_fmt! { $Uint as $Uint, fmt_int, $SU }
show! { $Uint with $SU }
}
}
integer! { int, uint, "i", "u" }
integer! { i8, u8 }
integer! { i16, u16 }
integer! { i32, u32 }
integer! { i64, u64 }
|
{ break }
|
conditional_block
|
num.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Integer and floating-point number formatting
// FIXME: #6220 Implement floating point formatting
#![allow(unsigned_negation)]
use fmt;
use iter::IteratorExt;
use num::{Int, cast};
use slice::SliceExt;
use str;
/// A type that represents a specific radix
#[doc(hidden)]
trait GenericRadix {
/// The number of digits.
fn base(&self) -> u8;
/// A radix-specific prefix string.
fn prefix(&self) -> &'static str { "" }
/// Converts an integer to corresponding radix digit.
fn digit(&self, x: u8) -> u8;
/// Format an integer using the radix using a formatter.
fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
// The radix can be as low as 2, so we need a buffer of at least 64
// characters for a base 2 number.
let zero = Int::zero();
let is_positive = x >= zero;
let mut buf = [0u8; 64];
let mut curr = buf.len();
let base = cast(self.base()).unwrap();
if is_positive {
// Accumulate each digit of the number from the least significant
// to the most significant figure.
for byte in buf.iter_mut().rev() {
let n = x % base; // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero { break }; // No more digits left to accumulate.
}
} else {
// Do the same as above, but accounting for two's complement.
for byte in buf.iter_mut().rev() {
let n = zero - (x % base); // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero { break }; // No more digits left to accumulate.
}
}
let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) };
f.pad_integral(is_positive, self.prefix(), buf)
}
}
|
/// A binary (base 2) radix
#[derive(Clone, PartialEq)]
struct Binary;
/// An octal (base 8) radix
#[derive(Clone, PartialEq)]
struct Octal;
/// A decimal (base 10) radix
#[derive(Clone, PartialEq)]
struct Decimal;
/// A hexadecimal (base 16) radix, formatted with lower-case characters
#[derive(Clone, PartialEq)]
struct LowerHex;
/// A hexadecimal (base 16) radix, formatted with upper-case characters
#[derive(Clone, PartialEq)]
pub struct UpperHex;
macro_rules! radix {
($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
impl GenericRadix for $T {
fn base(&self) -> u8 { $base }
fn prefix(&self) -> &'static str { $prefix }
fn digit(&self, x: u8) -> u8 {
match x {
$($x => $conv,)+
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
}
}
radix! { Binary, 2, "0b", x @ 0... 2 => b'0' + x }
radix! { Octal, 8, "0o", x @ 0... 7 => b'0' + x }
radix! { Decimal, 10, "", x @ 0... 9 => b'0' + x }
radix! { LowerHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'a' + (x - 10) }
radix! { UpperHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'A' + (x - 10) }
/// A radix with in the range of `2..36`.
#[derive(Clone, Copy, PartialEq)]
#[unstable = "may be renamed or move to a different module"]
pub struct Radix {
base: u8,
}
impl Radix {
fn new(base: u8) -> Radix {
assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
Radix { base: base }
}
}
impl GenericRadix for Radix {
fn base(&self) -> u8 { self.base }
fn digit(&self, x: u8) -> u8 {
match x {
x @ 0... 9 => b'0' + x,
x if x < self.base() => b'a' + (x - 10),
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
/// A helper type for formatting radixes.
#[unstable = "may be renamed or move to a different module"]
#[derive(Copy)]
pub struct RadixFmt<T, R>(T, R);
/// Constructs a radix formatter in the range of `2..36`.
///
/// # Example
///
/// ```
/// use std::fmt::radix;
/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string());
/// ```
#[unstable = "may be renamed or move to a different module"]
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base))
}
macro_rules! radix_fmt {
($T:ty as $U:ty, $fmt:ident, $S:expr) => {
#[stable]
impl fmt::Debug for RadixFmt<$T, Radix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[stable]
impl fmt::Display for RadixFmt<$T, Radix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
}
}
}
}
macro_rules! int_base {
($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
#[stable]
impl fmt::$Trait for $T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
$Radix.fmt_int(*self as $U, f)
}
}
}
}
macro_rules! show {
($T:ident with $S:expr) => {
#[stable]
impl fmt::Debug for $T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
}
}
macro_rules! integer {
($Int:ident, $Uint:ident) => {
integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) }
};
($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => {
int_base! { Display for $Int as $Int -> Decimal }
int_base! { Binary for $Int as $Uint -> Binary }
int_base! { Octal for $Int as $Uint -> Octal }
int_base! { LowerHex for $Int as $Uint -> LowerHex }
int_base! { UpperHex for $Int as $Uint -> UpperHex }
radix_fmt! { $Int as $Int, fmt_int, $SI }
show! { $Int with $SI }
int_base! { Display for $Uint as $Uint -> Decimal }
int_base! { Binary for $Uint as $Uint -> Binary }
int_base! { Octal for $Uint as $Uint -> Octal }
int_base! { LowerHex for $Uint as $Uint -> LowerHex }
int_base! { UpperHex for $Uint as $Uint -> UpperHex }
radix_fmt! { $Uint as $Uint, fmt_int, $SU }
show! { $Uint with $SU }
}
}
integer! { int, uint, "i", "u" }
integer! { i8, u8 }
integer! { i16, u16 }
integer! { i32, u32 }
integer! { i64, u64 }
|
random_line_split
|
|
num.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Integer and floating-point number formatting
// FIXME: #6220 Implement floating point formatting
#![allow(unsigned_negation)]
use fmt;
use iter::IteratorExt;
use num::{Int, cast};
use slice::SliceExt;
use str;
/// A type that represents a specific radix
#[doc(hidden)]
trait GenericRadix {
/// The number of digits.
fn base(&self) -> u8;
/// A radix-specific prefix string.
fn prefix(&self) -> &'static str { "" }
/// Converts an integer to corresponding radix digit.
fn digit(&self, x: u8) -> u8;
/// Format an integer using the radix using a formatter.
fn fmt_int<T: Int>(&self, mut x: T, f: &mut fmt::Formatter) -> fmt::Result {
// The radix can be as low as 2, so we need a buffer of at least 64
// characters for a base 2 number.
let zero = Int::zero();
let is_positive = x >= zero;
let mut buf = [0u8; 64];
let mut curr = buf.len();
let base = cast(self.base()).unwrap();
if is_positive {
// Accumulate each digit of the number from the least significant
// to the most significant figure.
for byte in buf.iter_mut().rev() {
let n = x % base; // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero { break }; // No more digits left to accumulate.
}
} else {
// Do the same as above, but accounting for two's complement.
for byte in buf.iter_mut().rev() {
let n = zero - (x % base); // Get the current place value.
x = x / base; // Deaccumulate the number.
*byte = self.digit(cast(n).unwrap()); // Store the digit in the buffer.
curr -= 1;
if x == zero { break }; // No more digits left to accumulate.
}
}
let buf = unsafe { str::from_utf8_unchecked(&buf[curr..]) };
f.pad_integral(is_positive, self.prefix(), buf)
}
}
/// A binary (base 2) radix
#[derive(Clone, PartialEq)]
struct Binary;
/// An octal (base 8) radix
#[derive(Clone, PartialEq)]
struct Octal;
/// A decimal (base 10) radix
#[derive(Clone, PartialEq)]
struct Decimal;
/// A hexadecimal (base 16) radix, formatted with lower-case characters
#[derive(Clone, PartialEq)]
struct
|
;
/// A hexadecimal (base 16) radix, formatted with upper-case characters
#[derive(Clone, PartialEq)]
pub struct UpperHex;
macro_rules! radix {
($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
impl GenericRadix for $T {
fn base(&self) -> u8 { $base }
fn prefix(&self) -> &'static str { $prefix }
fn digit(&self, x: u8) -> u8 {
match x {
$($x => $conv,)+
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
}
}
radix! { Binary, 2, "0b", x @ 0... 2 => b'0' + x }
radix! { Octal, 8, "0o", x @ 0... 7 => b'0' + x }
radix! { Decimal, 10, "", x @ 0... 9 => b'0' + x }
radix! { LowerHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'a' + (x - 10) }
radix! { UpperHex, 16, "0x", x @ 0... 9 => b'0' + x,
x @ 10... 15 => b'A' + (x - 10) }
/// A radix with in the range of `2..36`.
#[derive(Clone, Copy, PartialEq)]
#[unstable = "may be renamed or move to a different module"]
pub struct Radix {
base: u8,
}
impl Radix {
fn new(base: u8) -> Radix {
assert!(2 <= base && base <= 36, "the base must be in the range of 2..36: {}", base);
Radix { base: base }
}
}
impl GenericRadix for Radix {
fn base(&self) -> u8 { self.base }
fn digit(&self, x: u8) -> u8 {
match x {
x @ 0... 9 => b'0' + x,
x if x < self.base() => b'a' + (x - 10),
x => panic!("number not in the range 0..{}: {}", self.base() - 1, x),
}
}
}
/// A helper type for formatting radixes.
#[unstable = "may be renamed or move to a different module"]
#[derive(Copy)]
pub struct RadixFmt<T, R>(T, R);
/// Constructs a radix formatter in the range of `2..36`.
///
/// # Example
///
/// ```
/// use std::fmt::radix;
/// assert_eq!(format!("{}", radix(55, 36)), "1j".to_string());
/// ```
#[unstable = "may be renamed or move to a different module"]
pub fn radix<T>(x: T, base: u8) -> RadixFmt<T, Radix> {
RadixFmt(x, Radix::new(base))
}
macro_rules! radix_fmt {
($T:ty as $U:ty, $fmt:ident, $S:expr) => {
#[stable]
impl fmt::Debug for RadixFmt<$T, Radix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
#[stable]
impl fmt::Display for RadixFmt<$T, Radix> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self { RadixFmt(ref x, radix) => radix.$fmt(*x as $U, f) }
}
}
}
}
macro_rules! int_base {
($Trait:ident for $T:ident as $U:ident -> $Radix:ident) => {
#[stable]
impl fmt::$Trait for $T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
$Radix.fmt_int(*self as $U, f)
}
}
}
}
macro_rules! show {
($T:ident with $S:expr) => {
#[stable]
impl fmt::Debug for $T {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
}
}
macro_rules! integer {
($Int:ident, $Uint:ident) => {
integer! { $Int, $Uint, stringify!($Int), stringify!($Uint) }
};
($Int:ident, $Uint:ident, $SI:expr, $SU:expr) => {
int_base! { Display for $Int as $Int -> Decimal }
int_base! { Binary for $Int as $Uint -> Binary }
int_base! { Octal for $Int as $Uint -> Octal }
int_base! { LowerHex for $Int as $Uint -> LowerHex }
int_base! { UpperHex for $Int as $Uint -> UpperHex }
radix_fmt! { $Int as $Int, fmt_int, $SI }
show! { $Int with $SI }
int_base! { Display for $Uint as $Uint -> Decimal }
int_base! { Binary for $Uint as $Uint -> Binary }
int_base! { Octal for $Uint as $Uint -> Octal }
int_base! { LowerHex for $Uint as $Uint -> LowerHex }
int_base! { UpperHex for $Uint as $Uint -> UpperHex }
radix_fmt! { $Uint as $Uint, fmt_int, $SU }
show! { $Uint with $SU }
}
}
integer! { int, uint, "i", "u" }
integer! { i8, u8 }
integer! { i16, u16 }
integer! { i32, u32 }
integer! { i64, u64 }
|
LowerHex
|
identifier_name
|
my_task.rs
|
use std::collections::VecDeque;
use std::{thread, time};
use tokio::prelude::*;
const SLEEP_MILLIS: u64 = 100;
fn poll_number() -> Async<u32> {
Async::Ready(233)
}
pub struct MyTask;
impl Future for MyTask {
type Item = ();
type Error = ();
fn poll(&mut self) -> Result<Async<()>, ()> {
match poll_number() {
Async::Ready(number) => {
println!("number={:?}", number);
Ok(Async::Ready(()))
}
Async::NotReady => {
return Ok(Async::NotReady);
}
}
}
}
pub struct SpinExecutor {
ready_tasks: VecDeque<Box<Future<Item = (), Error = ()>>>,
not_ready_tasks: VecDeque<Box<Future<Item = (), Error = ()>>>,
}
impl SpinExecutor {
pub fn spawn<T>(&mut self, task: T)
where T: Future<Item = (), Error = ()> +'static
|
pub fn run(&mut self) {
loop {
while let Some(mut task) = self.ready_tasks.pop_front() {
match task.poll().unwrap() {
Async::Ready(_) => {}
Async::NotReady => {
self.not_ready_tasks.push_back(task);
}
}
}
if self.not_ready_tasks.is_empty() { return; }
self.sleep_until_tasks_are_ready();
}
}
fn sleep_until_tasks_are_ready(&mut self) {
loop {
if self.not_ready_tasks.is_empty() {
thread::sleep(time::Duration::from_millis(SLEEP_MILLIS));
} else {
while let Some(mut task) = self.not_ready_tasks.pop_front() {
self.ready_tasks.push_back(task);
}
return;
}
}
}
}
|
{
self.not_ready_tasks.push_back(Box::new(task));
}
|
identifier_body
|
my_task.rs
|
use std::collections::VecDeque;
use std::{thread, time};
use tokio::prelude::*;
const SLEEP_MILLIS: u64 = 100;
fn poll_number() -> Async<u32> {
Async::Ready(233)
}
pub struct MyTask;
impl Future for MyTask {
type Item = ();
type Error = ();
fn poll(&mut self) -> Result<Async<()>, ()> {
match poll_number() {
Async::Ready(number) => {
println!("number={:?}", number);
Ok(Async::Ready(()))
}
Async::NotReady => {
return Ok(Async::NotReady);
}
}
}
}
pub struct SpinExecutor {
ready_tasks: VecDeque<Box<Future<Item = (), Error = ()>>>,
not_ready_tasks: VecDeque<Box<Future<Item = (), Error = ()>>>,
}
impl SpinExecutor {
pub fn spawn<T>(&mut self, task: T)
where T: Future<Item = (), Error = ()> +'static {
self.not_ready_tasks.push_back(Box::new(task));
}
pub fn run(&mut self) {
loop {
while let Some(mut task) = self.ready_tasks.pop_front() {
match task.poll().unwrap() {
Async::Ready(_) => {}
Async::NotReady => {
self.not_ready_tasks.push_back(task);
}
}
}
if self.not_ready_tasks.is_empty()
|
self.sleep_until_tasks_are_ready();
}
}
fn sleep_until_tasks_are_ready(&mut self) {
loop {
if self.not_ready_tasks.is_empty() {
thread::sleep(time::Duration::from_millis(SLEEP_MILLIS));
} else {
while let Some(mut task) = self.not_ready_tasks.pop_front() {
self.ready_tasks.push_back(task);
}
return;
}
}
}
}
|
{ return; }
|
conditional_block
|
my_task.rs
|
use std::collections::VecDeque;
use std::{thread, time};
use tokio::prelude::*;
const SLEEP_MILLIS: u64 = 100;
fn poll_number() -> Async<u32> {
Async::Ready(233)
}
pub struct MyTask;
impl Future for MyTask {
type Item = ();
type Error = ();
fn poll(&mut self) -> Result<Async<()>, ()> {
match poll_number() {
Async::Ready(number) => {
println!("number={:?}", number);
Ok(Async::Ready(()))
}
Async::NotReady => {
return Ok(Async::NotReady);
}
}
}
}
pub struct SpinExecutor {
ready_tasks: VecDeque<Box<Future<Item = (), Error = ()>>>,
not_ready_tasks: VecDeque<Box<Future<Item = (), Error = ()>>>,
}
impl SpinExecutor {
pub fn spawn<T>(&mut self, task: T)
where T: Future<Item = (), Error = ()> +'static {
self.not_ready_tasks.push_back(Box::new(task));
}
pub fn run(&mut self) {
|
Async::NotReady => {
self.not_ready_tasks.push_back(task);
}
}
}
if self.not_ready_tasks.is_empty() { return; }
self.sleep_until_tasks_are_ready();
}
}
fn sleep_until_tasks_are_ready(&mut self) {
loop {
if self.not_ready_tasks.is_empty() {
thread::sleep(time::Duration::from_millis(SLEEP_MILLIS));
} else {
while let Some(mut task) = self.not_ready_tasks.pop_front() {
self.ready_tasks.push_back(task);
}
return;
}
}
}
}
|
loop {
while let Some(mut task) = self.ready_tasks.pop_front() {
match task.poll().unwrap() {
Async::Ready(_) => {}
|
random_line_split
|
my_task.rs
|
use std::collections::VecDeque;
use std::{thread, time};
use tokio::prelude::*;
const SLEEP_MILLIS: u64 = 100;
fn poll_number() -> Async<u32> {
Async::Ready(233)
}
pub struct MyTask;
impl Future for MyTask {
type Item = ();
type Error = ();
fn poll(&mut self) -> Result<Async<()>, ()> {
match poll_number() {
Async::Ready(number) => {
println!("number={:?}", number);
Ok(Async::Ready(()))
}
Async::NotReady => {
return Ok(Async::NotReady);
}
}
}
}
pub struct SpinExecutor {
ready_tasks: VecDeque<Box<Future<Item = (), Error = ()>>>,
not_ready_tasks: VecDeque<Box<Future<Item = (), Error = ()>>>,
}
impl SpinExecutor {
pub fn spawn<T>(&mut self, task: T)
where T: Future<Item = (), Error = ()> +'static {
self.not_ready_tasks.push_back(Box::new(task));
}
pub fn run(&mut self) {
loop {
while let Some(mut task) = self.ready_tasks.pop_front() {
match task.poll().unwrap() {
Async::Ready(_) => {}
Async::NotReady => {
self.not_ready_tasks.push_back(task);
}
}
}
if self.not_ready_tasks.is_empty() { return; }
self.sleep_until_tasks_are_ready();
}
}
fn
|
(&mut self) {
loop {
if self.not_ready_tasks.is_empty() {
thread::sleep(time::Duration::from_millis(SLEEP_MILLIS));
} else {
while let Some(mut task) = self.not_ready_tasks.pop_front() {
self.ready_tasks.push_back(task);
}
return;
}
}
}
}
|
sleep_until_tasks_are_ready
|
identifier_name
|
mod.rs
|
//! Bounding volumes.
#[doc(inline)]
pub use bounding_volume::bounding_volume::{HasBoundingVolume, BoundingVolume};
#[doc(inline)]
pub use bounding_volume::aabb::{AABB, aabb};
#[doc(inline)]
pub use bounding_volume::bounding_sphere::{BoundingSphere, bounding_sphere};
pub use bounding_volume::aabb_utils::{implicit_shape_aabb, point_cloud_aabb};
pub use bounding_volume::aabb_ball::ball_aabb;
pub use bounding_volume::bounding_sphere_utils::{point_cloud_bounding_sphere_with_center, point_cloud_bounding_sphere};
pub use bounding_volume::bounding_volume_bvt::BoundingVolumeInterferencesCollector;
use na::{Pnt2, Pnt3};
#[doc(hidden)]
pub mod bounding_volume;
mod bounding_volume_bvt;
#[doc(hidden)]
pub mod aabb;
mod aabb_cuboid;
mod aabb_support_map;
mod aabb_ball;
mod aabb_plane;
mod aabb_convex;
mod aabb_compound;
mod aabb_mesh;
mod aabb_utils;
mod aabb_repr;
#[doc(hidden)]
pub mod bounding_sphere;
mod bounding_sphere_cuboid;
mod bounding_sphere_cone;
mod bounding_sphere_ball;
mod bounding_sphere_cylinder;
mod bounding_sphere_capsule;
mod bounding_sphere_plane;
mod bounding_sphere_convex;
mod bounding_sphere_compound;
mod bounding_sphere_triangle;
mod bounding_sphere_segment;
mod bounding_sphere_mesh;
mod bounding_sphere_utils;
mod bounding_sphere_repr;
/*
*
* Aliases.
*
*/
/// A 2D bounding sphere.
pub type BoundingSphere2<N> = BoundingSphere<Pnt2<N>>;
/// A 2D AABB.
pub type AABB2<N> = AABB<Pnt2<N>>;
|
pub type BoundingSphere3<N> = BoundingSphere<Pnt3<N>>;
/// A 3D AABB.
pub type AABB3<N> = AABB<Pnt3<N>>;
|
/// A 3D bounding sphere:
|
random_line_split
|
mir_raw_fat_ptr.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// check raw fat pointer ops in mir
// FIXME: please improve this when we get monomorphization support
use std::mem;
#[derive(Debug, PartialEq, Eq)]
struct ComparisonResults {
lt: bool,
le: bool,
gt: bool,
ge: bool,
eq: bool,
ne: bool
}
const LT: ComparisonResults = ComparisonResults {
lt: true,
le: true,
gt: false,
ge: false,
eq: false,
ne: true
};
const EQ: ComparisonResults = ComparisonResults {
lt: false,
le: true,
gt: false,
ge: true,
eq: true,
ne: false
};
const GT: ComparisonResults = ComparisonResults {
lt: false,
le: false,
gt: true,
ge: true,
eq: false,
ne: true
};
fn compare_su8(a: *const S<[u8]>, b: *const S<[u8]>) -> ComparisonResults {
ComparisonResults {
lt: a < b,
le: a <= b,
gt: a > b,
ge: a >= b,
eq: a == b,
ne: a!= b
}
}
fn compare_au8(a: *const [u8], b: *const [u8]) -> ComparisonResults {
ComparisonResults {
lt: a < b,
le: a <= b,
gt: a > b,
ge: a >= b,
eq: a == b,
ne: a!= b
}
}
fn compare_foo<'a>(a: *const (Foo+'a), b: *const (Foo+'a)) -> ComparisonResults
|
fn simple_eq<'a>(a: *const (Foo+'a), b: *const (Foo+'a)) -> bool {
let result = a == b;
result
}
fn assert_inorder<T: Copy>(a: &[T],
compare: fn(T, T) -> ComparisonResults) {
for i in 0..a.len() {
for j in 0..a.len() {
let cres = compare(a[i], a[j]);
if i < j {
assert_eq!(cres, LT);
} else if i == j {
assert_eq!(cres, EQ);
} else {
assert_eq!(cres, GT);
}
}
}
}
trait Foo { fn foo(&self) -> usize; }
impl<T> Foo for T {
fn foo(&self) -> usize {
mem::size_of::<T>()
}
}
struct S<T:?Sized>(u32, T);
fn main() {
let array = [0,1,2,3,4];
let array2 = [5,6,7,8,9];
// fat ptr comparison: addr then extra
// check ordering for arrays
let mut ptrs: Vec<*const [u8]> = vec![
&array[0..0], &array[0..1], &array, &array[1..]
];
let array_addr = &array as *const [u8] as *const u8 as usize;
let array2_addr = &array2 as *const [u8] as *const u8 as usize;
if array2_addr < array_addr {
ptrs.insert(0, &array2);
} else {
ptrs.push(&array2);
}
assert_inorder(&ptrs, compare_au8);
let u8_ = (0u8, 1u8);
let u32_ = (4u32, 5u32);
// check ordering for ptrs
let buf: &mut [*const Foo] = &mut [
&u8_, &u8_.0,
&u32_, &u32_.0,
];
buf.sort_by(|u,v| {
let u : [*const (); 2] = unsafe { mem::transmute(*u) };
let v : [*const (); 2] = unsafe { mem::transmute(*v) };
u.cmp(&v)
});
assert_inorder(buf, compare_foo);
// check ordering for structs containing arrays
let ss: (S<[u8; 2]>,
S<[u8; 3]>,
S<[u8; 2]>) = (
S(7, [8, 9]),
S(10, [11, 12, 13]),
S(4, [5, 6])
);
assert_inorder(&[
&ss.0 as *const S<[u8]>,
&ss.1 as *const S<[u8]>,
&ss.2 as *const S<[u8]>
], compare_su8);
assert!(simple_eq(&0u8 as *const _, &0u8 as *const _));
assert!(!simple_eq(&0u8 as *const _, &1u8 as *const _));
}
|
{
ComparisonResults {
lt: a < b,
le: a <= b,
gt: a > b,
ge: a >= b,
eq: a == b,
ne: a != b
}
}
|
identifier_body
|
mir_raw_fat_ptr.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// check raw fat pointer ops in mir
// FIXME: please improve this when we get monomorphization support
use std::mem;
#[derive(Debug, PartialEq, Eq)]
struct ComparisonResults {
lt: bool,
le: bool,
gt: bool,
ge: bool,
eq: bool,
ne: bool
}
const LT: ComparisonResults = ComparisonResults {
lt: true,
le: true,
gt: false,
ge: false,
eq: false,
ne: true
};
const EQ: ComparisonResults = ComparisonResults {
lt: false,
le: true,
gt: false,
ge: true,
eq: true,
ne: false
};
const GT: ComparisonResults = ComparisonResults {
lt: false,
le: false,
gt: true,
ge: true,
eq: false,
ne: true
};
fn compare_su8(a: *const S<[u8]>, b: *const S<[u8]>) -> ComparisonResults {
ComparisonResults {
lt: a < b,
le: a <= b,
gt: a > b,
ge: a >= b,
eq: a == b,
ne: a!= b
}
}
fn compare_au8(a: *const [u8], b: *const [u8]) -> ComparisonResults {
ComparisonResults {
lt: a < b,
le: a <= b,
gt: a > b,
ge: a >= b,
eq: a == b,
ne: a!= b
}
}
fn compare_foo<'a>(a: *const (Foo+'a), b: *const (Foo+'a)) -> ComparisonResults {
ComparisonResults {
lt: a < b,
le: a <= b,
gt: a > b,
ge: a >= b,
eq: a == b,
ne: a!= b
}
}
fn simple_eq<'a>(a: *const (Foo+'a), b: *const (Foo+'a)) -> bool {
let result = a == b;
result
}
fn assert_inorder<T: Copy>(a: &[T],
compare: fn(T, T) -> ComparisonResults) {
for i in 0..a.len() {
for j in 0..a.len() {
let cres = compare(a[i], a[j]);
if i < j {
assert_eq!(cres, LT);
} else if i == j {
assert_eq!(cres, EQ);
} else {
assert_eq!(cres, GT);
}
}
}
}
trait Foo { fn foo(&self) -> usize; }
impl<T> Foo for T {
fn foo(&self) -> usize {
mem::size_of::<T>()
}
}
struct S<T:?Sized>(u32, T);
fn main() {
let array = [0,1,2,3,4];
let array2 = [5,6,7,8,9];
// fat ptr comparison: addr then extra
// check ordering for arrays
let mut ptrs: Vec<*const [u8]> = vec![
&array[0..0], &array[0..1], &array, &array[1..]
];
let array_addr = &array as *const [u8] as *const u8 as usize;
let array2_addr = &array2 as *const [u8] as *const u8 as usize;
if array2_addr < array_addr {
ptrs.insert(0, &array2);
} else {
ptrs.push(&array2);
}
assert_inorder(&ptrs, compare_au8);
let u8_ = (0u8, 1u8);
let u32_ = (4u32, 5u32);
// check ordering for ptrs
let buf: &mut [*const Foo] = &mut [
&u8_, &u8_.0,
&u32_, &u32_.0,
];
buf.sort_by(|u,v| {
let u : [*const (); 2] = unsafe { mem::transmute(*u) };
let v : [*const (); 2] = unsafe { mem::transmute(*v) };
u.cmp(&v)
});
assert_inorder(buf, compare_foo);
// check ordering for structs containing arrays
let ss: (S<[u8; 2]>,
S<[u8; 3]>,
S<[u8; 2]>) = (
S(7, [8, 9]),
S(10, [11, 12, 13]),
S(4, [5, 6])
);
assert_inorder(&[
&ss.0 as *const S<[u8]>,
&ss.1 as *const S<[u8]>,
&ss.2 as *const S<[u8]>
], compare_su8);
assert!(simple_eq(&0u8 as *const _, &0u8 as *const _));
|
assert!(!simple_eq(&0u8 as *const _, &1u8 as *const _));
}
|
random_line_split
|
|
mir_raw_fat_ptr.rs
|
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// check raw fat pointer ops in mir
// FIXME: please improve this when we get monomorphization support
use std::mem;
#[derive(Debug, PartialEq, Eq)]
struct ComparisonResults {
lt: bool,
le: bool,
gt: bool,
ge: bool,
eq: bool,
ne: bool
}
const LT: ComparisonResults = ComparisonResults {
lt: true,
le: true,
gt: false,
ge: false,
eq: false,
ne: true
};
const EQ: ComparisonResults = ComparisonResults {
lt: false,
le: true,
gt: false,
ge: true,
eq: true,
ne: false
};
const GT: ComparisonResults = ComparisonResults {
lt: false,
le: false,
gt: true,
ge: true,
eq: false,
ne: true
};
fn compare_su8(a: *const S<[u8]>, b: *const S<[u8]>) -> ComparisonResults {
ComparisonResults {
lt: a < b,
le: a <= b,
gt: a > b,
ge: a >= b,
eq: a == b,
ne: a!= b
}
}
fn compare_au8(a: *const [u8], b: *const [u8]) -> ComparisonResults {
ComparisonResults {
lt: a < b,
le: a <= b,
gt: a > b,
ge: a >= b,
eq: a == b,
ne: a!= b
}
}
fn compare_foo<'a>(a: *const (Foo+'a), b: *const (Foo+'a)) -> ComparisonResults {
ComparisonResults {
lt: a < b,
le: a <= b,
gt: a > b,
ge: a >= b,
eq: a == b,
ne: a!= b
}
}
fn simple_eq<'a>(a: *const (Foo+'a), b: *const (Foo+'a)) -> bool {
let result = a == b;
result
}
fn
|
<T: Copy>(a: &[T],
compare: fn(T, T) -> ComparisonResults) {
for i in 0..a.len() {
for j in 0..a.len() {
let cres = compare(a[i], a[j]);
if i < j {
assert_eq!(cres, LT);
} else if i == j {
assert_eq!(cres, EQ);
} else {
assert_eq!(cres, GT);
}
}
}
}
trait Foo { fn foo(&self) -> usize; }
impl<T> Foo for T {
fn foo(&self) -> usize {
mem::size_of::<T>()
}
}
struct S<T:?Sized>(u32, T);
fn main() {
let array = [0,1,2,3,4];
let array2 = [5,6,7,8,9];
// fat ptr comparison: addr then extra
// check ordering for arrays
let mut ptrs: Vec<*const [u8]> = vec![
&array[0..0], &array[0..1], &array, &array[1..]
];
let array_addr = &array as *const [u8] as *const u8 as usize;
let array2_addr = &array2 as *const [u8] as *const u8 as usize;
if array2_addr < array_addr {
ptrs.insert(0, &array2);
} else {
ptrs.push(&array2);
}
assert_inorder(&ptrs, compare_au8);
let u8_ = (0u8, 1u8);
let u32_ = (4u32, 5u32);
// check ordering for ptrs
let buf: &mut [*const Foo] = &mut [
&u8_, &u8_.0,
&u32_, &u32_.0,
];
buf.sort_by(|u,v| {
let u : [*const (); 2] = unsafe { mem::transmute(*u) };
let v : [*const (); 2] = unsafe { mem::transmute(*v) };
u.cmp(&v)
});
assert_inorder(buf, compare_foo);
// check ordering for structs containing arrays
let ss: (S<[u8; 2]>,
S<[u8; 3]>,
S<[u8; 2]>) = (
S(7, [8, 9]),
S(10, [11, 12, 13]),
S(4, [5, 6])
);
assert_inorder(&[
&ss.0 as *const S<[u8]>,
&ss.1 as *const S<[u8]>,
&ss.2 as *const S<[u8]>
], compare_su8);
assert!(simple_eq(&0u8 as *const _, &0u8 as *const _));
assert!(!simple_eq(&0u8 as *const _, &1u8 as *const _));
}
|
assert_inorder
|
identifier_name
|
main.rs
|
#![feature(proc_macro_hygiene, decl_macro)]
extern crate rand;
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde_derive;
use diesel::prelude::*;
use diesel::result::Error;
use rand::Rng;
use rocket_contrib::json::Json;
use rocket_contrib::templates::Template;
mod db;
mod models;
mod schema;
fn random_number() -> i32 {
rand::thread_rng().gen_range(1, 10_001)
}
#[get("/plaintext")]
fn plaintext() -> &'static str {
"Hello, World!"
}
#[get("/json")]
fn json() -> Json<models::Message> {
let message = models::Message {
message: "Hello, World!",
};
Json(message)
}
#[get("/db")]
fn db(conn: db::DbConn) -> Json<models::World> {
use schema::world::dsl::*;
let result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
Json(result)
}
#[get("/queries")]
fn queries_empty(conn: db::DbConn) -> Json<Vec<models::World>> {
queries(conn, 1)
}
#[get("/queries?<q>")]
fn queries(conn: db::DbConn, q: u16) -> Json<Vec<models::World>> {
use schema::world::dsl::*;
let q = if q == 0 {
1
} else if q > 500 {
500
} else {
q
};
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q {
let result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
results.push(result);
}
Json(results)
}
#[get("/fortunes")]
fn fortunes(conn: db::DbConn) -> Template {
use schema::fortune::dsl::*;
let mut context = fortune
.load::<models::Fortune>(&*conn)
.expect("error loading fortunes");
context.push(models::Fortune {
id: 0,
message: "Additional fortune added at request time.".to_string(),
});
context.sort_by(|a, b| a.message.cmp(&b.message));
Template::render("fortunes", &context)
}
#[get("/updates")]
fn updates_empty(conn: db::DbConn) -> Json<Vec<models::World>>
|
#[get("/updates?<q>")]
fn updates(conn: db::DbConn, q: u16) -> Json<Vec<models::World>> {
use schema::world::dsl::*;
let q = if q == 0 {
1
} else if q > 500 {
500
} else {
q
};
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q {
let mut result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
result.randomNumber = random_number();
results.push(result);
}
let _ = conn.transaction::<(), Error, _>(|| {
for w in &results {
let _ = diesel::update(world)
.filter(id.eq(w.id))
.set(randomnumber.eq(w.randomNumber))
.execute(&*conn);
}
Ok(())
});
Json(results)
}
fn main() {
rocket::ignite()
.mount(
"/",
routes![
json,
plaintext,
db,
queries,
queries_empty,
fortunes,
updates,
updates_empty,
],
)
.manage(db::init_pool())
.attach(Template::fairing())
.launch();
}
|
{
updates(conn, 1)
}
|
identifier_body
|
main.rs
|
#![feature(proc_macro_hygiene, decl_macro)]
extern crate rand;
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde_derive;
use diesel::prelude::*;
use diesel::result::Error;
use rand::Rng;
use rocket_contrib::json::Json;
use rocket_contrib::templates::Template;
mod db;
mod models;
mod schema;
fn random_number() -> i32 {
rand::thread_rng().gen_range(1, 10_001)
}
#[get("/plaintext")]
fn plaintext() -> &'static str {
"Hello, World!"
}
#[get("/json")]
fn json() -> Json<models::Message> {
let message = models::Message {
message: "Hello, World!",
};
Json(message)
}
#[get("/db")]
fn db(conn: db::DbConn) -> Json<models::World> {
use schema::world::dsl::*;
let result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
Json(result)
}
#[get("/queries")]
fn queries_empty(conn: db::DbConn) -> Json<Vec<models::World>> {
queries(conn, 1)
}
#[get("/queries?<q>")]
fn queries(conn: db::DbConn, q: u16) -> Json<Vec<models::World>> {
use schema::world::dsl::*;
let q = if q == 0 {
1
} else if q > 500 {
500
} else {
q
};
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q {
let result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
results.push(result);
}
Json(results)
}
#[get("/fortunes")]
fn
|
(conn: db::DbConn) -> Template {
use schema::fortune::dsl::*;
let mut context = fortune
.load::<models::Fortune>(&*conn)
.expect("error loading fortunes");
context.push(models::Fortune {
id: 0,
message: "Additional fortune added at request time.".to_string(),
});
context.sort_by(|a, b| a.message.cmp(&b.message));
Template::render("fortunes", &context)
}
#[get("/updates")]
fn updates_empty(conn: db::DbConn) -> Json<Vec<models::World>> {
updates(conn, 1)
}
#[get("/updates?<q>")]
fn updates(conn: db::DbConn, q: u16) -> Json<Vec<models::World>> {
use schema::world::dsl::*;
let q = if q == 0 {
1
} else if q > 500 {
500
} else {
q
};
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q {
let mut result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
result.randomNumber = random_number();
results.push(result);
}
let _ = conn.transaction::<(), Error, _>(|| {
for w in &results {
let _ = diesel::update(world)
.filter(id.eq(w.id))
.set(randomnumber.eq(w.randomNumber))
.execute(&*conn);
}
Ok(())
});
Json(results)
}
fn main() {
rocket::ignite()
.mount(
"/",
routes![
json,
plaintext,
db,
queries,
queries_empty,
fortunes,
updates,
updates_empty,
],
)
.manage(db::init_pool())
.attach(Template::fairing())
.launch();
}
|
fortunes
|
identifier_name
|
main.rs
|
#![feature(proc_macro_hygiene, decl_macro)]
extern crate rand;
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde_derive;
use diesel::prelude::*;
use diesel::result::Error;
use rand::Rng;
use rocket_contrib::json::Json;
use rocket_contrib::templates::Template;
mod db;
mod models;
mod schema;
fn random_number() -> i32 {
rand::thread_rng().gen_range(1, 10_001)
}
#[get("/plaintext")]
fn plaintext() -> &'static str {
"Hello, World!"
}
#[get("/json")]
fn json() -> Json<models::Message> {
let message = models::Message {
message: "Hello, World!",
};
Json(message)
}
#[get("/db")]
fn db(conn: db::DbConn) -> Json<models::World> {
use schema::world::dsl::*;
let result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
Json(result)
}
#[get("/queries")]
fn queries_empty(conn: db::DbConn) -> Json<Vec<models::World>> {
queries(conn, 1)
}
#[get("/queries?<q>")]
fn queries(conn: db::DbConn, q: u16) -> Json<Vec<models::World>> {
use schema::world::dsl::*;
let q = if q == 0 {
1
} else if q > 500 {
500
} else {
q
};
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q {
let result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
results.push(result);
}
Json(results)
}
#[get("/fortunes")]
fn fortunes(conn: db::DbConn) -> Template {
use schema::fortune::dsl::*;
let mut context = fortune
.load::<models::Fortune>(&*conn)
.expect("error loading fortunes");
context.push(models::Fortune {
id: 0,
message: "Additional fortune added at request time.".to_string(),
});
context.sort_by(|a, b| a.message.cmp(&b.message));
Template::render("fortunes", &context)
}
#[get("/updates")]
fn updates_empty(conn: db::DbConn) -> Json<Vec<models::World>> {
updates(conn, 1)
}
#[get("/updates?<q>")]
fn updates(conn: db::DbConn, q: u16) -> Json<Vec<models::World>> {
use schema::world::dsl::*;
let q = if q == 0 {
1
} else if q > 500 {
500
} else {
q
};
|
let mut result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
result.randomNumber = random_number();
results.push(result);
}
let _ = conn.transaction::<(), Error, _>(|| {
for w in &results {
let _ = diesel::update(world)
.filter(id.eq(w.id))
.set(randomnumber.eq(w.randomNumber))
.execute(&*conn);
}
Ok(())
});
Json(results)
}
fn main() {
rocket::ignite()
.mount(
"/",
routes![
json,
plaintext,
db,
queries,
queries_empty,
fortunes,
updates,
updates_empty,
],
)
.manage(db::init_pool())
.attach(Template::fairing())
.launch();
}
|
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q {
|
random_line_split
|
main.rs
|
#![feature(proc_macro_hygiene, decl_macro)]
extern crate rand;
#[macro_use]
extern crate rocket;
extern crate rocket_contrib;
#[macro_use]
extern crate diesel;
#[macro_use]
extern crate serde_derive;
use diesel::prelude::*;
use diesel::result::Error;
use rand::Rng;
use rocket_contrib::json::Json;
use rocket_contrib::templates::Template;
mod db;
mod models;
mod schema;
fn random_number() -> i32 {
rand::thread_rng().gen_range(1, 10_001)
}
#[get("/plaintext")]
fn plaintext() -> &'static str {
"Hello, World!"
}
#[get("/json")]
fn json() -> Json<models::Message> {
let message = models::Message {
message: "Hello, World!",
};
Json(message)
}
#[get("/db")]
fn db(conn: db::DbConn) -> Json<models::World> {
use schema::world::dsl::*;
let result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
Json(result)
}
#[get("/queries")]
fn queries_empty(conn: db::DbConn) -> Json<Vec<models::World>> {
queries(conn, 1)
}
#[get("/queries?<q>")]
fn queries(conn: db::DbConn, q: u16) -> Json<Vec<models::World>> {
use schema::world::dsl::*;
let q = if q == 0 {
1
} else if q > 500 {
500
} else
|
;
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q {
let result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
results.push(result);
}
Json(results)
}
#[get("/fortunes")]
fn fortunes(conn: db::DbConn) -> Template {
use schema::fortune::dsl::*;
let mut context = fortune
.load::<models::Fortune>(&*conn)
.expect("error loading fortunes");
context.push(models::Fortune {
id: 0,
message: "Additional fortune added at request time.".to_string(),
});
context.sort_by(|a, b| a.message.cmp(&b.message));
Template::render("fortunes", &context)
}
#[get("/updates")]
fn updates_empty(conn: db::DbConn) -> Json<Vec<models::World>> {
updates(conn, 1)
}
#[get("/updates?<q>")]
fn updates(conn: db::DbConn, q: u16) -> Json<Vec<models::World>> {
use schema::world::dsl::*;
let q = if q == 0 {
1
} else if q > 500 {
500
} else {
q
};
let mut results = Vec::with_capacity(q as usize);
for _ in 0..q {
let mut result = world
.filter(id.eq(random_number()))
.first::<models::World>(&*conn)
.expect("error loading world");
result.randomNumber = random_number();
results.push(result);
}
let _ = conn.transaction::<(), Error, _>(|| {
for w in &results {
let _ = diesel::update(world)
.filter(id.eq(w.id))
.set(randomnumber.eq(w.randomNumber))
.execute(&*conn);
}
Ok(())
});
Json(results)
}
fn main() {
rocket::ignite()
.mount(
"/",
routes![
json,
plaintext,
db,
queries,
queries_empty,
fortunes,
updates,
updates_empty,
],
)
.manage(db::init_pool())
.attach(Template::fairing())
.launch();
}
|
{
q
}
|
conditional_block
|
domtokenlist.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, AttrHelpers};
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::error::{ErrorResult, Fallible};
use dom::bindings::error::Error::{InvalidCharacter, Syntax};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootable};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{Element, AttributeHandlers};
use dom::node::window_from_node;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS};
use string_cache::Atom;
#[dom_struct]
pub struct DOMTokenList {
reflector_: Reflector,
element: JS<Element>,
local_name: Atom,
}
impl DOMTokenList {
pub fn new_inherited(element: JSRef<Element>, local_name: Atom) -> DOMTokenList {
DOMTokenList {
reflector_: Reflector::new(),
element: JS::from_rooted(element),
local_name: local_name,
}
}
pub fn new(element: JSRef<Element>, local_name: &Atom) -> Temporary<DOMTokenList> {
let window = window_from_node(element).root();
reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()),
GlobalRef::Window(window.r()),
DOMTokenListBinding::Wrap)
}
}
trait PrivateDOMTokenListHelpers {
fn attribute(self) -> Option<Temporary<Attr>>;
fn check_token_exceptions<'a>(self, token: &'a str) -> Fallible<Atom>;
}
impl<'a> PrivateDOMTokenListHelpers for JSRef<'a, DOMTokenList> {
fn attribute(self) -> Option<Temporary<Attr>> {
let element = self.element.root();
element.r().get_attribute(ns!(""), &self.local_name)
}
fn check_token_exceptions<'a>(self, token: &'a str) -> Fallible<Atom> {
match token {
"" => Err(Syntax),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter),
slice => Ok(Atom::from_slice(slice))
}
}
}
// http://dom.spec.whatwg.org/#domtokenlist
impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> {
// http://dom.spec.whatwg.org/#dom-domtokenlist-length
fn Length(self) -> u32 {
self.attribute().root().map(|attr| {
attr.r().value().tokens().map(|tokens| tokens.len()).unwrap_or(0)
}).unwrap_or(0) as u32
}
// http://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(self, index: u32) -> Option<DOMString> {
self.attribute().root().and_then(|attr| attr.r().value().tokens().and_then(|tokens| {
tokens.get(index as uint).map(|token| token.as_slice().into_string())
}))
}
fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<DOMString> {
let item = self.Item(index);
*found = item.is_some();
item
}
// http://dom.spec.whatwg.org/#dom-domtokenlist-contains
fn Contains(self, token: DOMString) -> Fallible<bool> {
self.check_token_exceptions(token.as_slice()).map(|token| {
self.attribute().root().map(|attr| {
attr.r()
.value()
.tokens()
.expect("Should have parsed this attribute")
.iter()
.any(|atom| *atom == token)
}).unwrap_or(false)
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-add
fn Add(self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in tokens.iter() {
let token = try!(self.check_token_exceptions(token.as_slice()));
if!atoms.iter().any(|atom| *atom == token) {
atoms.push(token);
}
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-remove
fn Remove(self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in tokens.iter() {
let token = try!(self.check_token_exceptions(token.as_slice()));
atoms.iter().position(|atom| *atom == token).and_then(|index| {
atoms.remove(index)
});
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
fn Toggle(self, token: DOMString, force: Option<bool>) -> Fallible<bool>
|
}
}
}
}
|
{
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
let token = try!(self.check_token_exceptions(token.as_slice()));
match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force {
Some(true) => Ok(true),
_ => {
atoms.remove(index);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(false)
}
},
None => match force {
Some(false) => Ok(false),
_ => {
atoms.push(token);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(true)
}
|
identifier_body
|
domtokenlist.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, AttrHelpers};
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::error::{ErrorResult, Fallible};
use dom::bindings::error::Error::{InvalidCharacter, Syntax};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootable};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{Element, AttributeHandlers};
use dom::node::window_from_node;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS};
use string_cache::Atom;
#[dom_struct]
pub struct DOMTokenList {
reflector_: Reflector,
element: JS<Element>,
local_name: Atom,
}
impl DOMTokenList {
pub fn
|
(element: JSRef<Element>, local_name: Atom) -> DOMTokenList {
DOMTokenList {
reflector_: Reflector::new(),
element: JS::from_rooted(element),
local_name: local_name,
}
}
pub fn new(element: JSRef<Element>, local_name: &Atom) -> Temporary<DOMTokenList> {
let window = window_from_node(element).root();
reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()),
GlobalRef::Window(window.r()),
DOMTokenListBinding::Wrap)
}
}
trait PrivateDOMTokenListHelpers {
fn attribute(self) -> Option<Temporary<Attr>>;
fn check_token_exceptions<'a>(self, token: &'a str) -> Fallible<Atom>;
}
impl<'a> PrivateDOMTokenListHelpers for JSRef<'a, DOMTokenList> {
fn attribute(self) -> Option<Temporary<Attr>> {
let element = self.element.root();
element.r().get_attribute(ns!(""), &self.local_name)
}
fn check_token_exceptions<'a>(self, token: &'a str) -> Fallible<Atom> {
match token {
"" => Err(Syntax),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter),
slice => Ok(Atom::from_slice(slice))
}
}
}
// http://dom.spec.whatwg.org/#domtokenlist
impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> {
// http://dom.spec.whatwg.org/#dom-domtokenlist-length
fn Length(self) -> u32 {
self.attribute().root().map(|attr| {
attr.r().value().tokens().map(|tokens| tokens.len()).unwrap_or(0)
}).unwrap_or(0) as u32
}
// http://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(self, index: u32) -> Option<DOMString> {
self.attribute().root().and_then(|attr| attr.r().value().tokens().and_then(|tokens| {
tokens.get(index as uint).map(|token| token.as_slice().into_string())
}))
}
fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<DOMString> {
let item = self.Item(index);
*found = item.is_some();
item
}
// http://dom.spec.whatwg.org/#dom-domtokenlist-contains
fn Contains(self, token: DOMString) -> Fallible<bool> {
self.check_token_exceptions(token.as_slice()).map(|token| {
self.attribute().root().map(|attr| {
attr.r()
.value()
.tokens()
.expect("Should have parsed this attribute")
.iter()
.any(|atom| *atom == token)
}).unwrap_or(false)
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-add
fn Add(self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in tokens.iter() {
let token = try!(self.check_token_exceptions(token.as_slice()));
if!atoms.iter().any(|atom| *atom == token) {
atoms.push(token);
}
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-remove
fn Remove(self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in tokens.iter() {
let token = try!(self.check_token_exceptions(token.as_slice()));
atoms.iter().position(|atom| *atom == token).and_then(|index| {
atoms.remove(index)
});
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
fn Toggle(self, token: DOMString, force: Option<bool>) -> Fallible<bool> {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
let token = try!(self.check_token_exceptions(token.as_slice()));
match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force {
Some(true) => Ok(true),
_ => {
atoms.remove(index);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(false)
}
},
None => match force {
Some(false) => Ok(false),
_ => {
atoms.push(token);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(true)
}
}
}
}
}
|
new_inherited
|
identifier_name
|
domtokenlist.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, AttrHelpers};
use dom::bindings::codegen::Bindings::DOMTokenListBinding;
use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use dom::bindings::error::{ErrorResult, Fallible};
use dom::bindings::error::Error::{InvalidCharacter, Syntax};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, JSRef, Temporary, OptionalRootable};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{Element, AttributeHandlers};
use dom::node::window_from_node;
use servo_util::str::{DOMString, HTML_SPACE_CHARACTERS};
use string_cache::Atom;
#[dom_struct]
pub struct DOMTokenList {
reflector_: Reflector,
element: JS<Element>,
local_name: Atom,
}
impl DOMTokenList {
pub fn new_inherited(element: JSRef<Element>, local_name: Atom) -> DOMTokenList {
DOMTokenList {
reflector_: Reflector::new(),
element: JS::from_rooted(element),
local_name: local_name,
}
}
pub fn new(element: JSRef<Element>, local_name: &Atom) -> Temporary<DOMTokenList> {
let window = window_from_node(element).root();
reflect_dom_object(box DOMTokenList::new_inherited(element, local_name.clone()),
GlobalRef::Window(window.r()),
DOMTokenListBinding::Wrap)
}
}
trait PrivateDOMTokenListHelpers {
fn attribute(self) -> Option<Temporary<Attr>>;
fn check_token_exceptions<'a>(self, token: &'a str) -> Fallible<Atom>;
}
impl<'a> PrivateDOMTokenListHelpers for JSRef<'a, DOMTokenList> {
fn attribute(self) -> Option<Temporary<Attr>> {
let element = self.element.root();
element.r().get_attribute(ns!(""), &self.local_name)
}
fn check_token_exceptions<'a>(self, token: &'a str) -> Fallible<Atom> {
match token {
|
slice => Ok(Atom::from_slice(slice))
}
}
}
// http://dom.spec.whatwg.org/#domtokenlist
impl<'a> DOMTokenListMethods for JSRef<'a, DOMTokenList> {
// http://dom.spec.whatwg.org/#dom-domtokenlist-length
fn Length(self) -> u32 {
self.attribute().root().map(|attr| {
attr.r().value().tokens().map(|tokens| tokens.len()).unwrap_or(0)
}).unwrap_or(0) as u32
}
// http://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(self, index: u32) -> Option<DOMString> {
self.attribute().root().and_then(|attr| attr.r().value().tokens().and_then(|tokens| {
tokens.get(index as uint).map(|token| token.as_slice().into_string())
}))
}
fn IndexedGetter(self, index: u32, found: &mut bool) -> Option<DOMString> {
let item = self.Item(index);
*found = item.is_some();
item
}
// http://dom.spec.whatwg.org/#dom-domtokenlist-contains
fn Contains(self, token: DOMString) -> Fallible<bool> {
self.check_token_exceptions(token.as_slice()).map(|token| {
self.attribute().root().map(|attr| {
attr.r()
.value()
.tokens()
.expect("Should have parsed this attribute")
.iter()
.any(|atom| *atom == token)
}).unwrap_or(false)
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-add
fn Add(self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in tokens.iter() {
let token = try!(self.check_token_exceptions(token.as_slice()));
if!atoms.iter().any(|atom| *atom == token) {
atoms.push(token);
}
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-remove
fn Remove(self, tokens: Vec<DOMString>) -> ErrorResult {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
for token in tokens.iter() {
let token = try!(self.check_token_exceptions(token.as_slice()));
atoms.iter().position(|atom| *atom == token).and_then(|index| {
atoms.remove(index)
});
}
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
fn Toggle(self, token: DOMString, force: Option<bool>) -> Fallible<bool> {
let element = self.element.root();
let mut atoms = element.r().get_tokenlist_attribute(&self.local_name);
let token = try!(self.check_token_exceptions(token.as_slice()));
match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force {
Some(true) => Ok(true),
_ => {
atoms.remove(index);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(false)
}
},
None => match force {
Some(false) => Ok(false),
_ => {
atoms.push(token);
element.r().set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(true)
}
}
}
}
}
|
"" => Err(Syntax),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(InvalidCharacter),
|
random_line_split
|
x86_64.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::target_strs;
use driver::session::sess_os_to_meta_os;
use driver::session;
use metadata::loader::meta_section_name;
pub fn get_target_strs(target_os: session::os) -> target_strs::t {
return target_strs::t {
module_asm: ~"",
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)),
data_layout: match target_os {
session::os_macos => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64"
}
session::os_win32 => {
// FIXME: Test this. Copied from linux (#2398)
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_linux => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_android => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_freebsd =>
|
},
target_triple: match target_os {
session::os_macos => ~"x86_64-apple-darwin",
session::os_win32 => ~"x86_64-pc-mingw32",
session::os_linux => ~"x86_64-unknown-linux-gnu",
session::os_android => ~"x86_64-unknown-android-gnu",
session::os_freebsd => ~"x86_64-unknown-freebsd",
},
cc_args: ~[~"-m64"]
};
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
|
{
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
|
conditional_block
|
x86_64.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::target_strs;
use driver::session::sess_os_to_meta_os;
use driver::session;
use metadata::loader::meta_section_name;
pub fn get_target_strs(target_os: session::os) -> target_strs::t
|
session::os_linux => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_android => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_freebsd => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
},
target_triple: match target_os {
session::os_macos => ~"x86_64-apple-darwin",
session::os_win32 => ~"x86_64-pc-mingw32",
session::os_linux => ~"x86_64-unknown-linux-gnu",
session::os_android => ~"x86_64-unknown-android-gnu",
session::os_freebsd => ~"x86_64-unknown-freebsd",
},
cc_args: ~[~"-m64"]
};
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
|
{
return target_strs::t {
module_asm: ~"",
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)),
data_layout: match target_os {
session::os_macos => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64"
}
session::os_win32 => {
// FIXME: Test this. Copied from linux (#2398)
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
|
identifier_body
|
x86_64.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::target_strs;
use driver::session::sess_os_to_meta_os;
use driver::session;
use metadata::loader::meta_section_name;
pub fn get_target_strs(target_os: session::os) -> target_strs::t {
return target_strs::t {
module_asm: ~"",
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)),
data_layout: match target_os {
|
session::os_win32 => {
// FIXME: Test this. Copied from linux (#2398)
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_linux => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_android => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_freebsd => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
},
target_triple: match target_os {
session::os_macos => ~"x86_64-apple-darwin",
session::os_win32 => ~"x86_64-pc-mingw32",
session::os_linux => ~"x86_64-unknown-linux-gnu",
session::os_android => ~"x86_64-unknown-android-gnu",
session::os_freebsd => ~"x86_64-unknown-freebsd",
},
cc_args: ~[~"-m64"]
};
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
|
session::os_macos => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64"
}
|
random_line_split
|
x86_64.rs
|
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use back::target_strs;
use driver::session::sess_os_to_meta_os;
use driver::session;
use metadata::loader::meta_section_name;
pub fn
|
(target_os: session::os) -> target_strs::t {
return target_strs::t {
module_asm: ~"",
meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)),
data_layout: match target_os {
session::os_macos => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64"
}
session::os_win32 => {
// FIXME: Test this. Copied from linux (#2398)
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_linux => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_android => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
session::os_freebsd => {
~"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"+
~"f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-"+
~"s0:64:64-f80:128:128-n8:16:32:64-S128"
}
},
target_triple: match target_os {
session::os_macos => ~"x86_64-apple-darwin",
session::os_win32 => ~"x86_64-pc-mingw32",
session::os_linux => ~"x86_64-unknown-linux-gnu",
session::os_android => ~"x86_64-unknown-android-gnu",
session::os_freebsd => ~"x86_64-unknown-freebsd",
},
cc_args: ~[~"-m64"]
};
}
//
// Local Variables:
// mode: rust
// fill-column: 78;
// indent-tabs-mode: nil
// c-basic-offset: 4
// buffer-file-coding-system: utf-8-unix
// End:
//
|
get_target_strs
|
identifier_name
|
filter_collector_wrapper.rs
|
// # Custom collector example
//
// This example shows how you can implement your own
// collector. As an example, we will compute a collector
// that computes the standard deviation of a given fast field.
//
// Of course, you can have a look at the tantivy's built-in collectors
// such as the `CountCollector` for more examples.
// ---
// Importing tantivy...
use std::marker::PhantomData;
use crate::collector::{Collector, SegmentCollector};
use crate::fastfield::{DynamicFastFieldReader, FastFieldReader, FastValue};
use crate::schema::Field;
use crate::{Score, SegmentReader, TantivyError};
/// The `FilterCollector` filters docs using a fast field value and a predicate.
/// Only the documents for which the predicate returned "true" will be passed on to the next collector.
///
/// ```rust
/// use tantivy::collector::{TopDocs, FilterCollector};
/// use tantivy::query::QueryParser;
/// use tantivy::schema::{Schema, TEXT, INDEXED, FAST};
/// use tantivy::{doc, DocAddress, Index};
///
/// # fn main() -> tantivy::Result<()> {
/// let mut schema_builder = Schema::builder();
/// let title = schema_builder.add_text_field("title", TEXT);
/// let price = schema_builder.add_u64_field("price", INDEXED | FAST);
/// let schema = schema_builder.build();
/// let index = Index::create_in_ram(schema);
///
/// let mut index_writer = index.writer_with_num_threads(1, 10_000_000)?;
/// index_writer.add_document(doc!(title => "The Name of the Wind", price => 30_200u64))?;
/// index_writer.add_document(doc!(title => "The Diary of Muadib", price => 29_240u64))?;
/// index_writer.add_document(doc!(title => "A Dairy Cow", price => 21_240u64))?;
/// index_writer.add_document(doc!(title => "The Diary of a Young Girl", price => 20_120u64))?;
/// index_writer.commit()?;
///
/// let reader = index.reader()?;
/// let searcher = reader.searcher();
///
/// let query_parser = QueryParser::for_index(&index, vec![title]);
/// let query = query_parser.parse_query("diary")?;
/// let no_filter_collector = FilterCollector::new(price, &|value: u64| value > 20_120u64, TopDocs::with_limit(2));
/// let top_docs = searcher.search(&query, &no_filter_collector)?;
///
/// assert_eq!(top_docs.len(), 1);
/// assert_eq!(top_docs[0].1, DocAddress::new(0, 1));
///
/// let filter_all_collector: FilterCollector<_, _, u64> = FilterCollector::new(price, &|value| value < 5u64, TopDocs::with_limit(2));
/// let filtered_top_docs = searcher.search(&query, &filter_all_collector)?;
///
/// assert_eq!(filtered_top_docs.len(), 0);
/// # Ok(())
/// # }
/// ```
pub struct FilterCollector<TCollector, TPredicate, TPredicateValue: FastValue>
where
TPredicate:'static + Clone,
{
field: Field,
collector: TCollector,
predicate: TPredicate,
t_predicate_value: PhantomData<TPredicateValue>,
}
impl<TCollector, TPredicate, TPredicateValue: FastValue>
FilterCollector<TCollector, TPredicate, TPredicateValue>
where
TCollector: Collector + Send + Sync,
TPredicate: Fn(TPredicateValue) -> bool + Send + Sync + Clone,
{
/// Create a new FilterCollector.
pub fn new(
field: Field,
predicate: TPredicate,
collector: TCollector,
) -> FilterCollector<TCollector, TPredicate, TPredicateValue> {
FilterCollector {
field,
predicate,
collector,
t_predicate_value: PhantomData,
}
}
}
impl<TCollector, TPredicate, TPredicateValue: FastValue> Collector
for FilterCollector<TCollector, TPredicate, TPredicateValue>
where
TCollector: Collector + Send + Sync,
TPredicate:'static + Fn(TPredicateValue) -> bool + Send + Sync + Clone,
TPredicateValue: FastValue,
{
// That's the type of our result.
// Our standard deviation will be a float.
type Fruit = TCollector::Fruit;
type Child = FilterSegmentCollector<TCollector::Child, TPredicate, TPredicateValue>;
fn for_segment(
&self,
segment_local_id: u32,
segment_reader: &SegmentReader,
) -> crate::Result<FilterSegmentCollector<TCollector::Child, TPredicate, TPredicateValue>> {
let schema = segment_reader.schema();
let field_entry = schema.get_field_entry(self.field);
if!field_entry.is_fast() {
return Err(TantivyError::SchemaError(format!(
"Field {:?} is not a fast field.",
field_entry.name()
)));
}
let requested_type = TPredicateValue::to_type();
let field_schema_type = field_entry.field_type().value_type();
if requested_type!= field_schema_type {
return Err(TantivyError::SchemaError(format!(
"Field {:?} is of type {:?}!={:?}",
field_entry.name(),
requested_type,
field_schema_type
)));
}
let fast_field_reader = segment_reader
.fast_fields()
.typed_fast_field_reader(self.field)?;
let segment_collector = self
.collector
.for_segment(segment_local_id, segment_reader)?;
Ok(FilterSegmentCollector {
fast_field_reader,
segment_collector,
predicate: self.predicate.clone(),
t_predicate_value: PhantomData,
})
}
fn requires_scoring(&self) -> bool {
self.collector.requires_scoring()
}
fn merge_fruits(
&self,
segment_fruits: Vec<<TCollector::Child as SegmentCollector>::Fruit>,
) -> crate::Result<TCollector::Fruit>
|
}
pub struct FilterSegmentCollector<TSegmentCollector, TPredicate, TPredicateValue>
where
TPredicate:'static,
TPredicateValue: FastValue,
{
fast_field_reader: DynamicFastFieldReader<TPredicateValue>,
segment_collector: TSegmentCollector,
predicate: TPredicate,
t_predicate_value: PhantomData<TPredicateValue>,
}
impl<TSegmentCollector, TPredicate, TPredicateValue> SegmentCollector
for FilterSegmentCollector<TSegmentCollector, TPredicate, TPredicateValue>
where
TSegmentCollector: SegmentCollector,
TPredicate:'static + Fn(TPredicateValue) -> bool + Send + Sync,
TPredicateValue: FastValue,
{
type Fruit = TSegmentCollector::Fruit;
fn collect(&mut self, doc: u32, score: Score) {
let value = self.fast_field_reader.get(doc);
if (self.predicate)(value) {
self.segment_collector.collect(doc, score)
}
}
fn harvest(self) -> <TSegmentCollector as SegmentCollector>::Fruit {
self.segment_collector.harvest()
}
}
|
{
self.collector.merge_fruits(segment_fruits)
}
|
identifier_body
|
filter_collector_wrapper.rs
|
// # Custom collector example
//
// This example shows how you can implement your own
// collector. As an example, we will compute a collector
// that computes the standard deviation of a given fast field.
//
// Of course, you can have a look at the tantivy's built-in collectors
// such as the `CountCollector` for more examples.
// ---
// Importing tantivy...
use std::marker::PhantomData;
use crate::collector::{Collector, SegmentCollector};
use crate::fastfield::{DynamicFastFieldReader, FastFieldReader, FastValue};
use crate::schema::Field;
use crate::{Score, SegmentReader, TantivyError};
/// The `FilterCollector` filters docs using a fast field value and a predicate.
/// Only the documents for which the predicate returned "true" will be passed on to the next collector.
///
/// ```rust
/// use tantivy::collector::{TopDocs, FilterCollector};
/// use tantivy::query::QueryParser;
/// use tantivy::schema::{Schema, TEXT, INDEXED, FAST};
/// use tantivy::{doc, DocAddress, Index};
///
/// # fn main() -> tantivy::Result<()> {
/// let mut schema_builder = Schema::builder();
/// let title = schema_builder.add_text_field("title", TEXT);
/// let price = schema_builder.add_u64_field("price", INDEXED | FAST);
/// let schema = schema_builder.build();
/// let index = Index::create_in_ram(schema);
///
/// let mut index_writer = index.writer_with_num_threads(1, 10_000_000)?;
/// index_writer.add_document(doc!(title => "The Name of the Wind", price => 30_200u64))?;
/// index_writer.add_document(doc!(title => "The Diary of Muadib", price => 29_240u64))?;
/// index_writer.add_document(doc!(title => "A Dairy Cow", price => 21_240u64))?;
/// index_writer.add_document(doc!(title => "The Diary of a Young Girl", price => 20_120u64))?;
/// index_writer.commit()?;
///
/// let reader = index.reader()?;
/// let searcher = reader.searcher();
///
/// let query_parser = QueryParser::for_index(&index, vec![title]);
/// let query = query_parser.parse_query("diary")?;
/// let no_filter_collector = FilterCollector::new(price, &|value: u64| value > 20_120u64, TopDocs::with_limit(2));
/// let top_docs = searcher.search(&query, &no_filter_collector)?;
///
/// assert_eq!(top_docs.len(), 1);
/// assert_eq!(top_docs[0].1, DocAddress::new(0, 1));
///
/// let filter_all_collector: FilterCollector<_, _, u64> = FilterCollector::new(price, &|value| value < 5u64, TopDocs::with_limit(2));
/// let filtered_top_docs = searcher.search(&query, &filter_all_collector)?;
///
/// assert_eq!(filtered_top_docs.len(), 0);
/// # Ok(())
/// # }
/// ```
pub struct FilterCollector<TCollector, TPredicate, TPredicateValue: FastValue>
where
TPredicate:'static + Clone,
{
field: Field,
collector: TCollector,
predicate: TPredicate,
t_predicate_value: PhantomData<TPredicateValue>,
}
impl<TCollector, TPredicate, TPredicateValue: FastValue>
FilterCollector<TCollector, TPredicate, TPredicateValue>
where
TCollector: Collector + Send + Sync,
TPredicate: Fn(TPredicateValue) -> bool + Send + Sync + Clone,
{
/// Create a new FilterCollector.
pub fn new(
field: Field,
predicate: TPredicate,
collector: TCollector,
) -> FilterCollector<TCollector, TPredicate, TPredicateValue> {
FilterCollector {
field,
predicate,
collector,
t_predicate_value: PhantomData,
}
}
}
impl<TCollector, TPredicate, TPredicateValue: FastValue> Collector
for FilterCollector<TCollector, TPredicate, TPredicateValue>
where
TCollector: Collector + Send + Sync,
TPredicate:'static + Fn(TPredicateValue) -> bool + Send + Sync + Clone,
TPredicateValue: FastValue,
{
// That's the type of our result.
// Our standard deviation will be a float.
type Fruit = TCollector::Fruit;
type Child = FilterSegmentCollector<TCollector::Child, TPredicate, TPredicateValue>;
fn for_segment(
&self,
segment_local_id: u32,
segment_reader: &SegmentReader,
) -> crate::Result<FilterSegmentCollector<TCollector::Child, TPredicate, TPredicateValue>> {
let schema = segment_reader.schema();
let field_entry = schema.get_field_entry(self.field);
if!field_entry.is_fast() {
return Err(TantivyError::SchemaError(format!(
"Field {:?} is not a fast field.",
field_entry.name()
)));
}
let requested_type = TPredicateValue::to_type();
let field_schema_type = field_entry.field_type().value_type();
if requested_type!= field_schema_type {
return Err(TantivyError::SchemaError(format!(
"Field {:?} is of type {:?}!={:?}",
field_entry.name(),
requested_type,
field_schema_type
)));
}
let fast_field_reader = segment_reader
.fast_fields()
.typed_fast_field_reader(self.field)?;
let segment_collector = self
.collector
.for_segment(segment_local_id, segment_reader)?;
Ok(FilterSegmentCollector {
fast_field_reader,
segment_collector,
predicate: self.predicate.clone(),
t_predicate_value: PhantomData,
})
}
fn requires_scoring(&self) -> bool {
self.collector.requires_scoring()
}
fn merge_fruits(
&self,
segment_fruits: Vec<<TCollector::Child as SegmentCollector>::Fruit>,
) -> crate::Result<TCollector::Fruit> {
self.collector.merge_fruits(segment_fruits)
}
}
pub struct FilterSegmentCollector<TSegmentCollector, TPredicate, TPredicateValue>
where
TPredicate:'static,
TPredicateValue: FastValue,
{
fast_field_reader: DynamicFastFieldReader<TPredicateValue>,
segment_collector: TSegmentCollector,
predicate: TPredicate,
t_predicate_value: PhantomData<TPredicateValue>,
}
impl<TSegmentCollector, TPredicate, TPredicateValue> SegmentCollector
for FilterSegmentCollector<TSegmentCollector, TPredicate, TPredicateValue>
where
TSegmentCollector: SegmentCollector,
TPredicate:'static + Fn(TPredicateValue) -> bool + Send + Sync,
TPredicateValue: FastValue,
{
type Fruit = TSegmentCollector::Fruit;
fn collect(&mut self, doc: u32, score: Score) {
let value = self.fast_field_reader.get(doc);
if (self.predicate)(value) {
self.segment_collector.collect(doc, score)
}
}
fn
|
(self) -> <TSegmentCollector as SegmentCollector>::Fruit {
self.segment_collector.harvest()
}
}
|
harvest
|
identifier_name
|
filter_collector_wrapper.rs
|
// # Custom collector example
//
// This example shows how you can implement your own
// collector. As an example, we will compute a collector
// that computes the standard deviation of a given fast field.
//
// Of course, you can have a look at the tantivy's built-in collectors
// such as the `CountCollector` for more examples.
// ---
// Importing tantivy...
use std::marker::PhantomData;
use crate::collector::{Collector, SegmentCollector};
use crate::fastfield::{DynamicFastFieldReader, FastFieldReader, FastValue};
use crate::schema::Field;
use crate::{Score, SegmentReader, TantivyError};
/// The `FilterCollector` filters docs using a fast field value and a predicate.
/// Only the documents for which the predicate returned "true" will be passed on to the next collector.
///
/// ```rust
/// use tantivy::collector::{TopDocs, FilterCollector};
/// use tantivy::query::QueryParser;
/// use tantivy::schema::{Schema, TEXT, INDEXED, FAST};
/// use tantivy::{doc, DocAddress, Index};
///
/// # fn main() -> tantivy::Result<()> {
/// let mut schema_builder = Schema::builder();
/// let title = schema_builder.add_text_field("title", TEXT);
/// let price = schema_builder.add_u64_field("price", INDEXED | FAST);
/// let schema = schema_builder.build();
/// let index = Index::create_in_ram(schema);
///
/// let mut index_writer = index.writer_with_num_threads(1, 10_000_000)?;
/// index_writer.add_document(doc!(title => "The Name of the Wind", price => 30_200u64))?;
/// index_writer.add_document(doc!(title => "The Diary of Muadib", price => 29_240u64))?;
/// index_writer.add_document(doc!(title => "A Dairy Cow", price => 21_240u64))?;
/// index_writer.add_document(doc!(title => "The Diary of a Young Girl", price => 20_120u64))?;
/// index_writer.commit()?;
///
/// let reader = index.reader()?;
/// let searcher = reader.searcher();
///
/// let query_parser = QueryParser::for_index(&index, vec![title]);
/// let query = query_parser.parse_query("diary")?;
/// let no_filter_collector = FilterCollector::new(price, &|value: u64| value > 20_120u64, TopDocs::with_limit(2));
/// let top_docs = searcher.search(&query, &no_filter_collector)?;
///
/// assert_eq!(top_docs.len(), 1);
/// assert_eq!(top_docs[0].1, DocAddress::new(0, 1));
///
/// let filter_all_collector: FilterCollector<_, _, u64> = FilterCollector::new(price, &|value| value < 5u64, TopDocs::with_limit(2));
/// let filtered_top_docs = searcher.search(&query, &filter_all_collector)?;
///
/// assert_eq!(filtered_top_docs.len(), 0);
/// # Ok(())
/// # }
/// ```
pub struct FilterCollector<TCollector, TPredicate, TPredicateValue: FastValue>
where
TPredicate:'static + Clone,
{
field: Field,
collector: TCollector,
predicate: TPredicate,
t_predicate_value: PhantomData<TPredicateValue>,
}
impl<TCollector, TPredicate, TPredicateValue: FastValue>
FilterCollector<TCollector, TPredicate, TPredicateValue>
where
TCollector: Collector + Send + Sync,
TPredicate: Fn(TPredicateValue) -> bool + Send + Sync + Clone,
{
/// Create a new FilterCollector.
pub fn new(
field: Field,
predicate: TPredicate,
collector: TCollector,
) -> FilterCollector<TCollector, TPredicate, TPredicateValue> {
FilterCollector {
field,
predicate,
collector,
t_predicate_value: PhantomData,
}
}
}
impl<TCollector, TPredicate, TPredicateValue: FastValue> Collector
for FilterCollector<TCollector, TPredicate, TPredicateValue>
where
TCollector: Collector + Send + Sync,
TPredicate:'static + Fn(TPredicateValue) -> bool + Send + Sync + Clone,
TPredicateValue: FastValue,
{
// That's the type of our result.
// Our standard deviation will be a float.
type Fruit = TCollector::Fruit;
type Child = FilterSegmentCollector<TCollector::Child, TPredicate, TPredicateValue>;
fn for_segment(
&self,
segment_local_id: u32,
segment_reader: &SegmentReader,
) -> crate::Result<FilterSegmentCollector<TCollector::Child, TPredicate, TPredicateValue>> {
let schema = segment_reader.schema();
let field_entry = schema.get_field_entry(self.field);
if!field_entry.is_fast() {
return Err(TantivyError::SchemaError(format!(
"Field {:?} is not a fast field.",
field_entry.name()
)));
}
let requested_type = TPredicateValue::to_type();
let field_schema_type = field_entry.field_type().value_type();
if requested_type!= field_schema_type {
return Err(TantivyError::SchemaError(format!(
"Field {:?} is of type {:?}!={:?}",
field_entry.name(),
requested_type,
field_schema_type
)));
}
let fast_field_reader = segment_reader
.fast_fields()
.typed_fast_field_reader(self.field)?;
let segment_collector = self
.collector
.for_segment(segment_local_id, segment_reader)?;
Ok(FilterSegmentCollector {
fast_field_reader,
segment_collector,
predicate: self.predicate.clone(),
t_predicate_value: PhantomData,
})
}
fn requires_scoring(&self) -> bool {
self.collector.requires_scoring()
}
fn merge_fruits(
&self,
segment_fruits: Vec<<TCollector::Child as SegmentCollector>::Fruit>,
) -> crate::Result<TCollector::Fruit> {
self.collector.merge_fruits(segment_fruits)
}
}
pub struct FilterSegmentCollector<TSegmentCollector, TPredicate, TPredicateValue>
where
TPredicate:'static,
TPredicateValue: FastValue,
{
fast_field_reader: DynamicFastFieldReader<TPredicateValue>,
segment_collector: TSegmentCollector,
predicate: TPredicate,
t_predicate_value: PhantomData<TPredicateValue>,
}
impl<TSegmentCollector, TPredicate, TPredicateValue> SegmentCollector
for FilterSegmentCollector<TSegmentCollector, TPredicate, TPredicateValue>
where
TSegmentCollector: SegmentCollector,
TPredicate:'static + Fn(TPredicateValue) -> bool + Send + Sync,
TPredicateValue: FastValue,
{
type Fruit = TSegmentCollector::Fruit;
fn collect(&mut self, doc: u32, score: Score) {
let value = self.fast_field_reader.get(doc);
if (self.predicate)(value)
|
}
fn harvest(self) -> <TSegmentCollector as SegmentCollector>::Fruit {
self.segment_collector.harvest()
}
}
|
{
self.segment_collector.collect(doc, score)
}
|
conditional_block
|
filter_collector_wrapper.rs
|
// # Custom collector example
//
// This example shows how you can implement your own
// collector. As an example, we will compute a collector
// that computes the standard deviation of a given fast field.
//
// Of course, you can have a look at the tantivy's built-in collectors
// such as the `CountCollector` for more examples.
// ---
// Importing tantivy...
use std::marker::PhantomData;
use crate::collector::{Collector, SegmentCollector};
use crate::fastfield::{DynamicFastFieldReader, FastFieldReader, FastValue};
use crate::schema::Field;
use crate::{Score, SegmentReader, TantivyError};
/// The `FilterCollector` filters docs using a fast field value and a predicate.
/// Only the documents for which the predicate returned "true" will be passed on to the next collector.
///
/// ```rust
/// use tantivy::collector::{TopDocs, FilterCollector};
/// use tantivy::query::QueryParser;
/// use tantivy::schema::{Schema, TEXT, INDEXED, FAST};
/// use tantivy::{doc, DocAddress, Index};
///
/// # fn main() -> tantivy::Result<()> {
/// let mut schema_builder = Schema::builder();
/// let title = schema_builder.add_text_field("title", TEXT);
/// let price = schema_builder.add_u64_field("price", INDEXED | FAST);
/// let schema = schema_builder.build();
/// let index = Index::create_in_ram(schema);
///
/// let mut index_writer = index.writer_with_num_threads(1, 10_000_000)?;
/// index_writer.add_document(doc!(title => "The Name of the Wind", price => 30_200u64))?;
/// index_writer.add_document(doc!(title => "The Diary of Muadib", price => 29_240u64))?;
/// index_writer.add_document(doc!(title => "A Dairy Cow", price => 21_240u64))?;
/// index_writer.add_document(doc!(title => "The Diary of a Young Girl", price => 20_120u64))?;
/// index_writer.commit()?;
///
/// let reader = index.reader()?;
/// let searcher = reader.searcher();
///
/// let query_parser = QueryParser::for_index(&index, vec![title]);
/// let query = query_parser.parse_query("diary")?;
/// let no_filter_collector = FilterCollector::new(price, &|value: u64| value > 20_120u64, TopDocs::with_limit(2));
/// let top_docs = searcher.search(&query, &no_filter_collector)?;
///
/// assert_eq!(top_docs.len(), 1);
/// assert_eq!(top_docs[0].1, DocAddress::new(0, 1));
///
/// let filter_all_collector: FilterCollector<_, _, u64> = FilterCollector::new(price, &|value| value < 5u64, TopDocs::with_limit(2));
/// let filtered_top_docs = searcher.search(&query, &filter_all_collector)?;
///
/// assert_eq!(filtered_top_docs.len(), 0);
/// # Ok(())
/// # }
/// ```
pub struct FilterCollector<TCollector, TPredicate, TPredicateValue: FastValue>
where
TPredicate:'static + Clone,
{
field: Field,
collector: TCollector,
predicate: TPredicate,
t_predicate_value: PhantomData<TPredicateValue>,
}
impl<TCollector, TPredicate, TPredicateValue: FastValue>
FilterCollector<TCollector, TPredicate, TPredicateValue>
where
TCollector: Collector + Send + Sync,
TPredicate: Fn(TPredicateValue) -> bool + Send + Sync + Clone,
{
/// Create a new FilterCollector.
pub fn new(
field: Field,
predicate: TPredicate,
collector: TCollector,
) -> FilterCollector<TCollector, TPredicate, TPredicateValue> {
FilterCollector {
field,
predicate,
collector,
t_predicate_value: PhantomData,
}
}
}
impl<TCollector, TPredicate, TPredicateValue: FastValue> Collector
for FilterCollector<TCollector, TPredicate, TPredicateValue>
|
TPredicateValue: FastValue,
{
// That's the type of our result.
// Our standard deviation will be a float.
type Fruit = TCollector::Fruit;
type Child = FilterSegmentCollector<TCollector::Child, TPredicate, TPredicateValue>;
fn for_segment(
&self,
segment_local_id: u32,
segment_reader: &SegmentReader,
) -> crate::Result<FilterSegmentCollector<TCollector::Child, TPredicate, TPredicateValue>> {
let schema = segment_reader.schema();
let field_entry = schema.get_field_entry(self.field);
if!field_entry.is_fast() {
return Err(TantivyError::SchemaError(format!(
"Field {:?} is not a fast field.",
field_entry.name()
)));
}
let requested_type = TPredicateValue::to_type();
let field_schema_type = field_entry.field_type().value_type();
if requested_type!= field_schema_type {
return Err(TantivyError::SchemaError(format!(
"Field {:?} is of type {:?}!={:?}",
field_entry.name(),
requested_type,
field_schema_type
)));
}
let fast_field_reader = segment_reader
.fast_fields()
.typed_fast_field_reader(self.field)?;
let segment_collector = self
.collector
.for_segment(segment_local_id, segment_reader)?;
Ok(FilterSegmentCollector {
fast_field_reader,
segment_collector,
predicate: self.predicate.clone(),
t_predicate_value: PhantomData,
})
}
fn requires_scoring(&self) -> bool {
self.collector.requires_scoring()
}
fn merge_fruits(
&self,
segment_fruits: Vec<<TCollector::Child as SegmentCollector>::Fruit>,
) -> crate::Result<TCollector::Fruit> {
self.collector.merge_fruits(segment_fruits)
}
}
pub struct FilterSegmentCollector<TSegmentCollector, TPredicate, TPredicateValue>
where
TPredicate:'static,
TPredicateValue: FastValue,
{
fast_field_reader: DynamicFastFieldReader<TPredicateValue>,
segment_collector: TSegmentCollector,
predicate: TPredicate,
t_predicate_value: PhantomData<TPredicateValue>,
}
impl<TSegmentCollector, TPredicate, TPredicateValue> SegmentCollector
for FilterSegmentCollector<TSegmentCollector, TPredicate, TPredicateValue>
where
TSegmentCollector: SegmentCollector,
TPredicate:'static + Fn(TPredicateValue) -> bool + Send + Sync,
TPredicateValue: FastValue,
{
type Fruit = TSegmentCollector::Fruit;
fn collect(&mut self, doc: u32, score: Score) {
let value = self.fast_field_reader.get(doc);
if (self.predicate)(value) {
self.segment_collector.collect(doc, score)
}
}
fn harvest(self) -> <TSegmentCollector as SegmentCollector>::Fruit {
self.segment_collector.harvest()
}
}
|
where
TCollector: Collector + Send + Sync,
TPredicate: 'static + Fn(TPredicateValue) -> bool + Send + Sync + Clone,
|
random_line_split
|
lint-unused-extern-crate.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(globs)]
#![deny(unused_extern_crate)]
#![allow(unused_variable)]
extern crate libc; //~ ERROR: unused extern crate
extern crate "collections" as collecs; // no error, it is used
extern crate rand; // no error, the use marks it as used
// even if imported objects aren't used
extern crate time; // no error, the use * marks it as used
#[allow(unused_imports)]
use rand::isaac::IsaacRng;
use time::*;
fn
|
() {
let x: collecs::vec::Vec<uint> = Vec::new();
let y = now();
}
|
main
|
identifier_name
|
lint-unused-extern-crate.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(globs)]
#![deny(unused_extern_crate)]
#![allow(unused_variable)]
extern crate libc; //~ ERROR: unused extern crate
extern crate "collections" as collecs; // no error, it is used
extern crate rand; // no error, the use marks it as used
// even if imported objects aren't used
|
#[allow(unused_imports)]
use rand::isaac::IsaacRng;
use time::*;
fn main() {
let x: collecs::vec::Vec<uint> = Vec::new();
let y = now();
}
|
extern crate time; // no error, the use * marks it as used
|
random_line_split
|
lint-unused-extern-crate.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(globs)]
#![deny(unused_extern_crate)]
#![allow(unused_variable)]
extern crate libc; //~ ERROR: unused extern crate
extern crate "collections" as collecs; // no error, it is used
extern crate rand; // no error, the use marks it as used
// even if imported objects aren't used
extern crate time; // no error, the use * marks it as used
#[allow(unused_imports)]
use rand::isaac::IsaacRng;
use time::*;
fn main()
|
{
let x: collecs::vec::Vec<uint> = Vec::new();
let y = now();
}
|
identifier_body
|
|
lib.rs
|
//! This is a library for controlling colours and formatting, such as
//! red bold text or blue underlined text, on ANSI terminals.
//!
//!
//! ## Basic usage
//!
//! There are two main data structures in this crate that you need to be
//! concerned with: `ANSIString` and `Style`. A `Style` holds stylistic
//! information: colours, whether the text should be bold, or blinking, or
//! whatever. There are also `Colour` variants that represent simple foreground
//! colour styles. An `ANSIString` is a string paired with a `Style`.
//!
//! (Yes, it’s British English, but you won’t have to write “colour” very often.
//! `Style` is used the majority of the time.)
//!
//! To format a string, call the `paint` method on a `Style` or a `Colour`,
//! passing in the string you want to format as the argument. For example,
//! here’s how to get some red text:
//!
//! use ansi_term::Colour::Red;
//! println!("This is in red: {}", Red.paint("a red string"));
//!
//! It’s important to note that the `paint` method does *not* actually return a
//! string with the ANSI control characters surrounding it. Instead, it returns
//! an `ANSIString` value that has a `Display` implementation that, when
//! formatted, returns the characters. This allows strings to be printed with a
//! minimum of `String` allocations being performed behind the scenes.
//!
//! If you *do* want to get at the escape codes, then you can convert the
//! `ANSIString` to a string as you would any other `Display` value:
//!
//! use ansi_term::Colour::Red;
//! use std::string::ToString;
//! let red_string = Red.paint("a red string").to_string();
//!
//!
//! ## Bold, underline, background, and other styles
//!
//! For anything more complex than plain foreground colour changes, you need to
//! construct `Style` objects themselves, rather than beginning with a `Colour`.
//! You can do this by chaining methods based on a new `Style`, created with
//! `Style::new()`. Each method creates a new style that has that specific
//! property set. For example:
//!
//! use ansi_term::Style;
//! println!("How about some {} and {}?",
//! Style::new().bold().paint("bold"),
//! Style::new().underline().paint("underline"));
//!
//! For brevity, these methods have also been implemented for `Colour` values,
//! so you can give your styles a foreground colour without having to begin with
//! an empty `Style` value:
//!
//! use ansi_term::Colour::{Blue, Yellow};
//! println!("Demonstrating {} and {}!",
//! Blue.bold().paint("blue bold"),
//! Yellow.underline().paint("yellow underline"));
//! println!("Yellow on blue: {}", Yellow.on(Blue).paint("wow!"));
//!
//! The complete list of styles you can use are: `bold`, `dimmed`, `italic`,
//! `underline`, `blink`, `reverse`, `hidden`, `strikethrough`, and `on` for
//! background colours.
//!
//! In some cases, you may find it easier to change the foreground on an
//! existing `Style` rather than starting from the appropriate `Colour`.
//! You can do this using the `fg` method:
//!
//! use ansi_term::Style;
//! use ansi_term::Colour::{Blue, Cyan, Yellow};
//! println!("Yellow on blue: {}", Style::new().on(Blue).fg(Yellow).paint("yow!"));
//! println!("Also yellow on blue: {}", Cyan.on(Blue).fg(Yellow).paint("zow!"));
//!
//! Finally, you can turn a `Colour` into a `Style` with the `normal` method.
//! This will produce the exact same `ANSIString` as if you just used the
//! `paint` method on the `Colour` directly, but it’s useful in certain cases:
|
//! the same type. The `Style` struct also has a `Default` implementation if you
//! want to have a style with *nothing* set.
//!
//! use ansi_term::Style;
//! use ansi_term::Colour::Red;
//! Red.normal().paint("yet another red string");
//! Style::default().paint("a completely regular string");
//!
//!
//! ## Extended colours
//!
//! You can access the extended range of 256 colours by using the `Fixed` colour
//! variant, which takes an argument of the colour number to use. This can be
//! included wherever you would use a `Colour`:
//!
//! use ansi_term::Colour::Fixed;
//! Fixed(134).paint("A sort of light purple");
//! Fixed(221).on(Fixed(124)).paint("Mustard in the ketchup");
//!
//! The first sixteen of these values are the same as the normal and bold
//! standard colour variants. There’s nothing stopping you from using these as
//! `Fixed` colours instead, but there’s nothing to be gained by doing so
//! either.
//!
//! You can also access full 24-bit color by using the `RGB` colour variant,
//! which takes separate `u8` arguments for red, green, and blue:
//!
//! use ansi_term::Colour::RGB;
//! RGB(70, 130, 180).paint("Steel blue");
//!
//! ## Combining successive coloured strings
//!
//! The benefit of writing ANSI escape codes to the terminal is that they
//! *stack*: you do not need to end every coloured string with a reset code if
//! the text that follows it is of a similar style. For example, if you want to
//! have some blue text followed by some blue bold text, it’s possible to send
//! the ANSI code for blue, followed by the ANSI code for bold, and finishing
//! with a reset code without having to have an extra one between the two
//! strings.
//!
//! This crate can optimise the ANSI codes that get printed in situations like
//! this, making life easier for your terminal renderer. The `ANSIStrings`
//! struct takes a slice of several `ANSIString` values, and will iterate over
//! each of them, printing only the codes for the styles that need to be updated
//! as part of its formatting routine.
//!
//! The following code snippet uses this to enclose a binary number displayed in
//! red bold text inside some red, but not bold, brackets:
//!
//! use ansi_term::Colour::Red;
//! use ansi_term::{ANSIString, ANSIStrings};
//! let some_value = format!("{:b}", 42);
//! let strings: &[ANSIString<'static>] = &[
//! Red.paint("["),
//! Red.bold().paint(some_value),
//! Red.paint("]"),
//! ];
//! println!("Value: {}", ANSIStrings(strings));
//!
//! There are several things to note here. Firstly, the `paint` method can take
//! *either* an owned `String` or a borrowed `&str`. Internally, an `ANSIString`
//! holds a copy-on-write (`Cow`) string value to deal with both owned and
//! borrowed strings at the same time. This is used here to display a `String`,
//! the result of the `format!` call, using the same mechanism as some
//! statically-available `&str` slices. Secondly, that the `ANSIStrings` value
//! works in the same way as its singular counterpart, with a `Display`
//! implementation that only performs the formatting when required.
//!
//! ## Byte strings
//!
//! This library also supports formatting `[u8]` byte strings; this supports
//! applications working with text in an unknown encoding. `Style` and
//! `Color` support painting `[u8]` values, resulting in an `ANSIByteString`.
//! This type does not implement `Display`, as it may not contain UTF-8, but
//! it does provide a method `write_to` to write the result to any
//! `io::Write`:
//!
//! use ansi_term::Colour::Green;
//! Green.paint("user data".as_bytes()).write_to(&mut std::io::stdout()).unwrap();
//!
//! Similarly, the type `ANSIByteStrings` supports writing a list of
//! `ANSIByteString` values with minimal escape sequences:
//!
//! use ansi_term::Colour::Green;
//! use ansi_term::ANSIByteStrings;
//! ANSIByteStrings(&[
//! Green.paint("user data 1\n".as_bytes()),
//! Green.bold().paint("user data 2\n".as_bytes()),
//! ]).write_to(&mut std::io::stdout()).unwrap();
#![crate_name = "ansi_term"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![warn(missing_copy_implementations)]
#![warn(missing_docs)]
#![warn(trivial_casts, trivial_numeric_casts)]
#![warn(unused_extern_crates, unused_qualifications)]
#[cfg(target_os="windows")]
extern crate winapi;
mod ansi;
pub use ansi::{Prefix, Infix, Suffix};
mod style;
pub use style::{Colour, Style};
/// Color is a type alias for Colour for those who can't be bothered.
pub use Colour as Color;
// I'm not beyond calling Colour Colour, rather than Color, but I did
// purposefully name this crate 'ansi-term' so people wouldn't get
// confused when they tried to install it.
//
// Only *after* they'd installed it.
mod difference;
mod display;
pub use display::*;
mod write;
mod windows;
pub use windows::*;
mod debug;
|
//! for example, you may have a method that returns `Styles`, and need to
//! represent both the “red bold” and “red, but not bold” styles with values of
|
random_line_split
|
marker.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.
//! Primitive traits and marker types representing basic 'kinds' of types.
//!
//! Rust types can be classified in various useful ways according to
//! intrinsic properties of the type. These classifications, often called
//! 'kinds', are represented as traits.
//!
//! They cannot be implemented by user code, but are instead implemented
//! by the compiler automatically for the types to which they apply.
//!
//! Marker types are special types that are used with unsafe code to
//! inform the compiler of special constraints. Marker types should
//! only be needed when you are creating an abstraction that is
//! implemented using unsafe code. In that case, you may want to embed
//! some of the marker types below into your type.
#![stable(feature = "rust1", since = "1.0.0")]
use clone::Clone;
use cmp;
use option::Option;
use hash::Hash;
use hash::Hasher;
/// Types able to be transferred across thread boundaries.
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "send"]
#[rustc_on_unimplemented = "`{Self}` cannot be sent between threads safely"]
pub unsafe trait Send {
// empty.
}
unsafe impl Send for.. { }
impl<T>!Send for *const T { }
impl<T>!Send for *mut T { }
/// Types with a constant size known at compile-time.
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "sized"]
#[rustc_on_unimplemented = "`{Self}` does not have a constant size known at compile-time"]
#[fundamental] // for Default, for example, which requires that `[T]:!Default` be evaluatable
pub trait Sized {
// Empty.
}
/// Types that can be "unsized" to a dynamically sized type.
#[unstable(feature = "core")]
#[cfg(not(stage0))]
#[lang="unsize"]
pub trait Unsize<T> {
// Empty.
}
/// Types that can be copied by simply copying bits (i.e. `memcpy`).
///
/// By default, variable bindings have'move semantics.' In other
/// words:
///
/// ```
/// #[derive(Debug)]
/// struct Foo;
///
/// let x = Foo;
///
/// let y = x;
///
/// // `x` has moved into `y`, and so cannot be used
///
/// // println!("{:?}", x); // error: use of moved value
/// ```
///
/// However, if a type implements `Copy`, it instead has 'copy semantics':
///
/// ```
/// // we can just derive a `Copy` implementation
/// #[derive(Debug, Copy, Clone)]
/// struct Foo;
///
/// let x = Foo;
///
/// let y = x;
///
/// // `y` is a copy of `x`
///
/// println!("{:?}", x); // A-OK!
/// ```
///
/// It's important to note that in these two examples, the only difference is if you are allowed to
/// access `x` after the assignment: a move is also a bitwise copy under the hood.
///
/// ## When can my type be `Copy`?
///
/// A type can implement `Copy` if all of its components implement `Copy`. For example, this
/// `struct` can be `Copy`:
///
/// ```
/// struct Point {
/// x: i32,
/// y: i32,
/// }
/// ```
///
/// A `struct` can be `Copy`, and `i32` is `Copy`, so therefore, `Point` is eligible to be `Copy`.
///
/// ```
/// # struct Point;
/// struct PointList {
/// points: Vec<Point>,
/// }
/// ```
///
/// The `PointList` `struct` cannot implement `Copy`, because `Vec<T>` is not `Copy`. If we
/// attempt to derive a `Copy` implementation, we'll get an error.
///
/// ```text
/// error: the trait `Copy` may not be implemented for this type; field `points` does not implement
/// `Copy`
/// ```
///
/// ## How can I implement `Copy`?
///
/// There are two ways to implement `Copy` on your type:
///
/// ```
/// #[derive(Copy, Clone)]
/// struct MyStruct;
/// ```
///
/// and
///
/// ```
/// struct MyStruct;
/// impl Copy for MyStruct {}
/// impl Clone for MyStruct { fn clone(&self) -> MyStruct { *self } }
/// ```
///
/// There is a small difference between the two: the `derive` strategy will also place a `Copy`
/// bound on type parameters, which isn't always desired.
///
/// ## When can my type _not_ be `Copy`?
///
/// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
/// mutable reference, and copying `String` would result in two attempts to free the same buffer.
///
/// Generalizing the latter case, any type implementing `Drop` can't be `Copy`, because it's
/// managing some resource besides its own `size_of::<T>()` bytes.
///
/// ## When should my type be `Copy`?
///
/// Generally speaking, if your type _can_ implement `Copy`, it should. There's one important thing
/// to consider though: if you think your type may _not_ be able to implement `Copy` in the future,
/// then it might be prudent to not implement `Copy`. This is because removing `Copy` is a breaking
/// change: that second example would fail to compile if we made `Foo` non-`Copy`.
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "copy"]
pub trait Copy : Clone {
// Empty.
}
/// Types that can be safely shared between threads when aliased.
///
/// The precise definition is: a type `T` is `Sync` if `&T` is
/// thread-safe. In other words, there is no possibility of data races
/// when passing `&T` references between threads.
///
/// As one would expect, primitive types like `u8` and `f64` are all
/// `Sync`, and so are simple aggregate types containing them (like
/// tuples, structs and enums). More instances of basic `Sync` types
/// include "immutable" types like `&T` and those with simple
/// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
/// collection types. (Generic parameters need to be `Sync` for their
/// container to be `Sync`.)
///
/// A somewhat surprising consequence of the definition is `&mut T` is
/// `Sync` (if `T` is `Sync`) even though it seems that it might
/// provide unsynchronised mutation. The trick is a mutable reference
/// stored in an aliasable reference (that is, `& &mut T`) becomes
/// read-only, as if it were a `& &T`, hence there is no risk of a data
/// race.
///
/// Types that are not `Sync` are those that have "interior
/// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
/// in `std::cell`. These types allow for mutation of their contents
/// even when in an immutable, aliasable slot, e.g. the contents of
/// `&Cell<T>` can be `.set`, and do not ensure data races are
/// impossible, hence they cannot be `Sync`. A higher level example
/// of a non-`Sync` type is the reference counted pointer
/// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
/// reference, which modifies the reference counts in a non-atomic
/// way.
///
/// For cases when one does need thread-safe interior mutability,
/// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
/// the `sync` crate do ensure that any mutation cannot cause data
/// races. Hence these types are `Sync`.
///
/// Any types with interior mutability must also use the `std::cell::UnsafeCell`
/// wrapper around the value(s) which can be mutated when behind a `&`
/// reference; not doing this is undefined behaviour (for example,
/// `transmute`-ing from `&T` to `&mut T` is illegal).
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "sync"]
#[rustc_on_unimplemented = "`{Self}` cannot be shared between threads safely"]
pub unsafe trait Sync {
// Empty
}
unsafe impl Sync for.. { }
impl<T>!Sync for *const T { }
impl<T>!Sync for *mut T { }
/// A type which is considered "not POD", meaning that it is not
/// implicitly copyable. This is typically embedded in other types to
/// ensure that they are never copied, even if they lack a destructor.
#[unstable(feature = "core",
reason = "likely to change with new variance strategy")]
#[lang = "no_copy_bound"]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct NoCopy;
macro_rules! impls{
($t: ident) => (
impl<T:?Sized> Hash for $t<T> {
#[inline]
fn hash<H: Hasher>(&self, _: &mut H) {
}
}
impl<T:?Sized> cmp::PartialEq for $t<T> {
fn eq(&self, _other: &$t<T>) -> bool {
true
}
}
impl<T:?Sized> cmp::Eq for $t<T> {
}
impl<T:?Sized> cmp::PartialOrd for $t<T> {
fn partial_cmp(&self, _other: &$t<T>) -> Option<cmp::Ordering> {
Option::Some(cmp::Ordering::Equal)
}
}
impl<T:?Sized> cmp::Ord for $t<T> {
fn cmp(&self, _other: &$t<T>) -> cmp::Ordering {
cmp::Ordering::Equal
}
}
impl<T:?Sized> Copy for $t<T> { }
impl<T:?Sized> Clone for $t<T> {
fn clone(&self) -> $t<T> {
$t
}
}
)
}
/// `PhantomData<T>` allows you to describe that a type acts as if it stores a value of type `T`,
/// even though it does not. This allows you to inform the compiler about certain safety properties
/// of your code.
///
/// Though they both have scary names, `PhantomData<T>` and "phantom types" are unrelated. 👻👻👻
///
/// # Examples
///
/// ## Unused lifetime parameter
///
/// Perhaps the most common time that `PhantomData` is required is
/// with a struct that has an unused lifetime parameter, typically as
/// part of some unsafe code. For example, here is a struct `Slice`
/// that has two pointers of type `*const T`, presumably pointing into
/// an array somewhere:
///
/// ```ignore
/// struct Slice<'a, T> {
/// start: *const T,
/// end: *const T,
/// }
/// ```
///
/// The intention is that the underlying data is only valid for the
/// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
/// intent is not expressed in the code, since there are no uses of
/// the lifetime `'a` and hence it is not clear what data it applies
/// to. We can correct this by telling the compiler to act *as if* the
/// `Slice` struct contained a borrowed reference `&'a T`:
///
/// ```
/// use std::marker::PhantomData;
///
/// struct Slice<'a, T:'a> {
/// start: *const T,
/// end: *const T,
/// phantom: PhantomData<&'a T>
/// }
/// ```
///
/// This also in turn requires that we annotate `T:'a`, indicating
/// that `T` is a type that can be borrowed for the lifetime `'a`.
///
/// ## Unused type parameters
///
/// It sometimes happens that there are unused type parameters that
/// indicate what type of data a struct is "tied" to, even though that
/// data is not actually found in the struct itself. Here is an
/// example where this arises when handling external resources over a
/// foreign function interface. `PhantomData<T>` can prevent
/// mismatches by enforcing types in the method implementations:
///
/// ```
/// # trait ResType { fn foo(&self); }
/// # struct ParamType;
/// # mod foreign_lib {
/// # pub fn new(_: usize) -> *mut () { 42 as *mut () }
/// # pub fn do_stuff(_: *mut (), _: usize) {}
/// # }
/// # fn convert_params(_: ParamType) -> usize { 42 }
/// use std::marker::PhantomData;
/// use std::mem;
///
/// struct ExternalResource<R> {
/// resource_handle: *mut (),
/// resource_type: PhantomData<R>,
/// }
///
/// impl<R: ResType> ExternalResource<R> {
/// fn new() -> ExternalResource<R> {
/// let size_of_res = mem::size_of::<R>();
/// ExternalResource {
/// resource_handle: foreign_lib::new(size_of_res),
/// resource_type: PhantomData,
/// }
/// }
///
/// fn do_stuff(&self, param: ParamType) {
/// let foreign_params = convert_params(param);
/// foreign_lib::do_stuff(self.resource_handle, foreign_params);
/// }
/// }
/// ```
///
/// ## Indicating ownership
///
/// Adding a field of type `PhantomData<T>` also indicates that your
/// struct owns data of type `T`. This in turn implies that when your
/// struct is dropped, it may in turn drop one or more instances of
/// the type `T`, though that may not be apparent from the other
/// structure of the type itself. This is commonly necessary if the
/// structure is using an unsafe pointer like `*mut T` whose referent
/// may be dropped when the type is dropped, as a `*mut T` is
/// otherwise not treated as owned.
///
/// If your struct does not in fact *own* the data of type `T`, it is
/// better to use a reference type, like `PhantomData<&'a T>`
/// (ideally) or `PhantomData<*const T>` (if no lifetime applies), so
/// as not to indicate ownership.
#[lang = "phantom_data"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct PhantomData<T:?Sized>;
impls! { PhantomData }
mod impls {
use super::{Send, Sync, Sized};
unsafe impl<'a, T: Sync +?Sized> Send for &'a T {}
unsafe impl<'a, T: Send +?Sized> Send for &'a mut T {}
}
/// A marker trait indicates a type that can be reflected over. This
/// trait is implemented for all types. Its purpose is to ensure that
/// when you write a generic function that will employ reflection,
/// that must be reflected (no pun intended) in the generic bounds of
/// that function. Here is an example:
///
/// ```
/// #![feature(core)]
/// use std::marker::Reflect;
/// use std::any::Any;
/// fn foo<T:Reflect+'static>(x: &T) {
/// let any: &Any = x;
/// if any.is::<u32>() { println!("u32"); }
/// }
/// ```
///
/// Without the declaration `T:Reflect`, `foo` would not type check
/// (note: as a matter of style, it would be preferable to to write
/// `T:Any`, because `T:Any` implies `T:Reflect` and `T:'static`, but
/// we use `Reflect` here to show how it works). The `Reflect` bound
/// thus serves to alert `foo`'s caller to the fact that `foo` may
/// behave differently depending on whether `T=u32` or not. In
/// particular, thanks to the `Reflect` bound, callers know that a
/// function declared like `fn bar<T>(...)` will always act in
/// precisely the same way no matter what type `T` is supplied,
/// because there are no bounds declared on `T`. (The ability for a
/// caller to reason about what a function may do based solely on what
/// generic bounds are declared is often called the ["parametricity
/// property"][1].)
///
/// [1]: http://en.wikipedia.org/wiki/Parametricity
#[rustc_reflect_like]
|
#[unstable(feature = "core", reason = "requires RFC and more experience")]
#[allow(deprecated)]
#[rustc_on_unimplemented = "`{Self}` does not implement `Any`; \
ensure all type parameters are bounded by `Any`"]
pub trait Reflect {}
impl Reflect for.. { }
|
random_line_split
|
|
marker.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.
//! Primitive traits and marker types representing basic 'kinds' of types.
//!
//! Rust types can be classified in various useful ways according to
//! intrinsic properties of the type. These classifications, often called
//! 'kinds', are represented as traits.
//!
//! They cannot be implemented by user code, but are instead implemented
//! by the compiler automatically for the types to which they apply.
//!
//! Marker types are special types that are used with unsafe code to
//! inform the compiler of special constraints. Marker types should
//! only be needed when you are creating an abstraction that is
//! implemented using unsafe code. In that case, you may want to embed
//! some of the marker types below into your type.
#![stable(feature = "rust1", since = "1.0.0")]
use clone::Clone;
use cmp;
use option::Option;
use hash::Hash;
use hash::Hasher;
/// Types able to be transferred across thread boundaries.
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "send"]
#[rustc_on_unimplemented = "`{Self}` cannot be sent between threads safely"]
pub unsafe trait Send {
// empty.
}
unsafe impl Send for.. { }
impl<T>!Send for *const T { }
impl<T>!Send for *mut T { }
/// Types with a constant size known at compile-time.
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "sized"]
#[rustc_on_unimplemented = "`{Self}` does not have a constant size known at compile-time"]
#[fundamental] // for Default, for example, which requires that `[T]:!Default` be evaluatable
pub trait Sized {
// Empty.
}
/// Types that can be "unsized" to a dynamically sized type.
#[unstable(feature = "core")]
#[cfg(not(stage0))]
#[lang="unsize"]
pub trait Unsize<T> {
// Empty.
}
/// Types that can be copied by simply copying bits (i.e. `memcpy`).
///
/// By default, variable bindings have'move semantics.' In other
/// words:
///
/// ```
/// #[derive(Debug)]
/// struct Foo;
///
/// let x = Foo;
///
/// let y = x;
///
/// // `x` has moved into `y`, and so cannot be used
///
/// // println!("{:?}", x); // error: use of moved value
/// ```
///
/// However, if a type implements `Copy`, it instead has 'copy semantics':
///
/// ```
/// // we can just derive a `Copy` implementation
/// #[derive(Debug, Copy, Clone)]
/// struct Foo;
///
/// let x = Foo;
///
/// let y = x;
///
/// // `y` is a copy of `x`
///
/// println!("{:?}", x); // A-OK!
/// ```
///
/// It's important to note that in these two examples, the only difference is if you are allowed to
/// access `x` after the assignment: a move is also a bitwise copy under the hood.
///
/// ## When can my type be `Copy`?
///
/// A type can implement `Copy` if all of its components implement `Copy`. For example, this
/// `struct` can be `Copy`:
///
/// ```
/// struct Point {
/// x: i32,
/// y: i32,
/// }
/// ```
///
/// A `struct` can be `Copy`, and `i32` is `Copy`, so therefore, `Point` is eligible to be `Copy`.
///
/// ```
/// # struct Point;
/// struct PointList {
/// points: Vec<Point>,
/// }
/// ```
///
/// The `PointList` `struct` cannot implement `Copy`, because `Vec<T>` is not `Copy`. If we
/// attempt to derive a `Copy` implementation, we'll get an error.
///
/// ```text
/// error: the trait `Copy` may not be implemented for this type; field `points` does not implement
/// `Copy`
/// ```
///
/// ## How can I implement `Copy`?
///
/// There are two ways to implement `Copy` on your type:
///
/// ```
/// #[derive(Copy, Clone)]
/// struct MyStruct;
/// ```
///
/// and
///
/// ```
/// struct MyStruct;
/// impl Copy for MyStruct {}
/// impl Clone for MyStruct { fn clone(&self) -> MyStruct { *self } }
/// ```
///
/// There is a small difference between the two: the `derive` strategy will also place a `Copy`
/// bound on type parameters, which isn't always desired.
///
/// ## When can my type _not_ be `Copy`?
///
/// Some types can't be copied safely. For example, copying `&mut T` would create an aliased
/// mutable reference, and copying `String` would result in two attempts to free the same buffer.
///
/// Generalizing the latter case, any type implementing `Drop` can't be `Copy`, because it's
/// managing some resource besides its own `size_of::<T>()` bytes.
///
/// ## When should my type be `Copy`?
///
/// Generally speaking, if your type _can_ implement `Copy`, it should. There's one important thing
/// to consider though: if you think your type may _not_ be able to implement `Copy` in the future,
/// then it might be prudent to not implement `Copy`. This is because removing `Copy` is a breaking
/// change: that second example would fail to compile if we made `Foo` non-`Copy`.
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "copy"]
pub trait Copy : Clone {
// Empty.
}
/// Types that can be safely shared between threads when aliased.
///
/// The precise definition is: a type `T` is `Sync` if `&T` is
/// thread-safe. In other words, there is no possibility of data races
/// when passing `&T` references between threads.
///
/// As one would expect, primitive types like `u8` and `f64` are all
/// `Sync`, and so are simple aggregate types containing them (like
/// tuples, structs and enums). More instances of basic `Sync` types
/// include "immutable" types like `&T` and those with simple
/// inherited mutability, such as `Box<T>`, `Vec<T>` and most other
/// collection types. (Generic parameters need to be `Sync` for their
/// container to be `Sync`.)
///
/// A somewhat surprising consequence of the definition is `&mut T` is
/// `Sync` (if `T` is `Sync`) even though it seems that it might
/// provide unsynchronised mutation. The trick is a mutable reference
/// stored in an aliasable reference (that is, `& &mut T`) becomes
/// read-only, as if it were a `& &T`, hence there is no risk of a data
/// race.
///
/// Types that are not `Sync` are those that have "interior
/// mutability" in a non-thread-safe way, such as `Cell` and `RefCell`
/// in `std::cell`. These types allow for mutation of their contents
/// even when in an immutable, aliasable slot, e.g. the contents of
/// `&Cell<T>` can be `.set`, and do not ensure data races are
/// impossible, hence they cannot be `Sync`. A higher level example
/// of a non-`Sync` type is the reference counted pointer
/// `std::rc::Rc`, because any reference `&Rc<T>` can clone a new
/// reference, which modifies the reference counts in a non-atomic
/// way.
///
/// For cases when one does need thread-safe interior mutability,
/// types like the atomics in `std::sync` and `Mutex` & `RWLock` in
/// the `sync` crate do ensure that any mutation cannot cause data
/// races. Hence these types are `Sync`.
///
/// Any types with interior mutability must also use the `std::cell::UnsafeCell`
/// wrapper around the value(s) which can be mutated when behind a `&`
/// reference; not doing this is undefined behaviour (for example,
/// `transmute`-ing from `&T` to `&mut T` is illegal).
#[stable(feature = "rust1", since = "1.0.0")]
#[lang = "sync"]
#[rustc_on_unimplemented = "`{Self}` cannot be shared between threads safely"]
pub unsafe trait Sync {
// Empty
}
unsafe impl Sync for.. { }
impl<T>!Sync for *const T { }
impl<T>!Sync for *mut T { }
/// A type which is considered "not POD", meaning that it is not
/// implicitly copyable. This is typically embedded in other types to
/// ensure that they are never copied, even if they lack a destructor.
#[unstable(feature = "core",
reason = "likely to change with new variance strategy")]
#[lang = "no_copy_bound"]
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct
|
;
macro_rules! impls{
($t: ident) => (
impl<T:?Sized> Hash for $t<T> {
#[inline]
fn hash<H: Hasher>(&self, _: &mut H) {
}
}
impl<T:?Sized> cmp::PartialEq for $t<T> {
fn eq(&self, _other: &$t<T>) -> bool {
true
}
}
impl<T:?Sized> cmp::Eq for $t<T> {
}
impl<T:?Sized> cmp::PartialOrd for $t<T> {
fn partial_cmp(&self, _other: &$t<T>) -> Option<cmp::Ordering> {
Option::Some(cmp::Ordering::Equal)
}
}
impl<T:?Sized> cmp::Ord for $t<T> {
fn cmp(&self, _other: &$t<T>) -> cmp::Ordering {
cmp::Ordering::Equal
}
}
impl<T:?Sized> Copy for $t<T> { }
impl<T:?Sized> Clone for $t<T> {
fn clone(&self) -> $t<T> {
$t
}
}
)
}
/// `PhantomData<T>` allows you to describe that a type acts as if it stores a value of type `T`,
/// even though it does not. This allows you to inform the compiler about certain safety properties
/// of your code.
///
/// Though they both have scary names, `PhantomData<T>` and "phantom types" are unrelated. 👻👻👻
///
/// # Examples
///
/// ## Unused lifetime parameter
///
/// Perhaps the most common time that `PhantomData` is required is
/// with a struct that has an unused lifetime parameter, typically as
/// part of some unsafe code. For example, here is a struct `Slice`
/// that has two pointers of type `*const T`, presumably pointing into
/// an array somewhere:
///
/// ```ignore
/// struct Slice<'a, T> {
/// start: *const T,
/// end: *const T,
/// }
/// ```
///
/// The intention is that the underlying data is only valid for the
/// lifetime `'a`, so `Slice` should not outlive `'a`. However, this
/// intent is not expressed in the code, since there are no uses of
/// the lifetime `'a` and hence it is not clear what data it applies
/// to. We can correct this by telling the compiler to act *as if* the
/// `Slice` struct contained a borrowed reference `&'a T`:
///
/// ```
/// use std::marker::PhantomData;
///
/// struct Slice<'a, T:'a> {
/// start: *const T,
/// end: *const T,
/// phantom: PhantomData<&'a T>
/// }
/// ```
///
/// This also in turn requires that we annotate `T:'a`, indicating
/// that `T` is a type that can be borrowed for the lifetime `'a`.
///
/// ## Unused type parameters
///
/// It sometimes happens that there are unused type parameters that
/// indicate what type of data a struct is "tied" to, even though that
/// data is not actually found in the struct itself. Here is an
/// example where this arises when handling external resources over a
/// foreign function interface. `PhantomData<T>` can prevent
/// mismatches by enforcing types in the method implementations:
///
/// ```
/// # trait ResType { fn foo(&self); }
/// # struct ParamType;
/// # mod foreign_lib {
/// # pub fn new(_: usize) -> *mut () { 42 as *mut () }
/// # pub fn do_stuff(_: *mut (), _: usize) {}
/// # }
/// # fn convert_params(_: ParamType) -> usize { 42 }
/// use std::marker::PhantomData;
/// use std::mem;
///
/// struct ExternalResource<R> {
/// resource_handle: *mut (),
/// resource_type: PhantomData<R>,
/// }
///
/// impl<R: ResType> ExternalResource<R> {
/// fn new() -> ExternalResource<R> {
/// let size_of_res = mem::size_of::<R>();
/// ExternalResource {
/// resource_handle: foreign_lib::new(size_of_res),
/// resource_type: PhantomData,
/// }
/// }
///
/// fn do_stuff(&self, param: ParamType) {
/// let foreign_params = convert_params(param);
/// foreign_lib::do_stuff(self.resource_handle, foreign_params);
/// }
/// }
/// ```
///
/// ## Indicating ownership
///
/// Adding a field of type `PhantomData<T>` also indicates that your
/// struct owns data of type `T`. This in turn implies that when your
/// struct is dropped, it may in turn drop one or more instances of
/// the type `T`, though that may not be apparent from the other
/// structure of the type itself. This is commonly necessary if the
/// structure is using an unsafe pointer like `*mut T` whose referent
/// may be dropped when the type is dropped, as a `*mut T` is
/// otherwise not treated as owned.
///
/// If your struct does not in fact *own* the data of type `T`, it is
/// better to use a reference type, like `PhantomData<&'a T>`
/// (ideally) or `PhantomData<*const T>` (if no lifetime applies), so
/// as not to indicate ownership.
#[lang = "phantom_data"]
#[stable(feature = "rust1", since = "1.0.0")]
pub struct PhantomData<T:?Sized>;
impls! { PhantomData }
mod impls {
use super::{Send, Sync, Sized};
unsafe impl<'a, T: Sync +?Sized> Send for &'a T {}
unsafe impl<'a, T: Send +?Sized> Send for &'a mut T {}
}
/// A marker trait indicates a type that can be reflected over. This
/// trait is implemented for all types. Its purpose is to ensure that
/// when you write a generic function that will employ reflection,
/// that must be reflected (no pun intended) in the generic bounds of
/// that function. Here is an example:
///
/// ```
/// #![feature(core)]
/// use std::marker::Reflect;
/// use std::any::Any;
/// fn foo<T:Reflect+'static>(x: &T) {
/// let any: &Any = x;
/// if any.is::<u32>() { println!("u32"); }
/// }
/// ```
///
/// Without the declaration `T:Reflect`, `foo` would not type check
/// (note: as a matter of style, it would be preferable to to write
/// `T:Any`, because `T:Any` implies `T:Reflect` and `T:'static`, but
/// we use `Reflect` here to show how it works). The `Reflect` bound
/// thus serves to alert `foo`'s caller to the fact that `foo` may
/// behave differently depending on whether `T=u32` or not. In
/// particular, thanks to the `Reflect` bound, callers know that a
/// function declared like `fn bar<T>(...)` will always act in
/// precisely the same way no matter what type `T` is supplied,
/// because there are no bounds declared on `T`. (The ability for a
/// caller to reason about what a function may do based solely on what
/// generic bounds are declared is often called the ["parametricity
/// property"][1].)
///
/// [1]: http://en.wikipedia.org/wiki/Parametricity
#[rustc_reflect_like]
#[unstable(feature = "core", reason = "requires RFC and more experience")]
#[allow(deprecated)]
#[rustc_on_unimplemented = "`{Self}` does not implement `Any`; \
ensure all type parameters are bounded by `Any`"]
pub trait Reflect {}
impl Reflect for.. { }
|
NoCopy
|
identifier_name
|
lib.rs
|
// too darn annoying to try and make them do so.
#![cfg_attr(test, allow(dead_code))]
extern crate ascii_canvas;
extern crate atty;
extern crate bit_set;
extern crate diff;
extern crate ena;
extern crate itertools;
extern crate lalrpop_util;
extern crate petgraph;
extern crate regex;
extern crate regex_syntax;
extern crate string_cache;
extern crate term;
extern crate unicode_xid;
extern crate sha2;
#[cfg(test)]
extern crate rand;
// hoist the modules that define macros up earlier
#[macro_use]
mod rust;
#[macro_use]
mod log;
mod api;
mod build;
mod collections;
mod file_text;
mod grammar;
mod lexer;
mod lr1;
mod message;
mod normalize;
mod parser;
mod kernel_set;
mod session;
mod tls;
mod tok;
mod util;
#[cfg(test)]
mod generate;
#[cfg(test)]
mod test_util;
pub use api::Configuration;
pub use api::process_root;
pub use api::process_root_unconditionally;
use ascii_canvas::style;
|
// Need this for rusty_peg
#![recursion_limit = "256"]
// I hate this lint.
#![allow(unused_parens)]
// The builtin tests don't cover the CLI and so forth, and it's just
|
random_line_split
|
|
mod.rs
|
use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
use serde_json::Value;
use sql_types::{FollowPolicy, Url};
pub mod follow_request;
pub mod follower;
pub mod group;
pub mod persona;
use self::follower::Follower;
use schema::base_actors;
use user::UserLike;
#[derive(Debug, AsChangeset)]
#[table_name = "base_actors"]
pub struct ModifiedBaseActor {
id: i32,
display_name: String,
profile_url: Url,
inbox_url: Url,
outbox_url: Url,
follow_policy: FollowPolicy,
original_json: Value,
}
impl ModifiedBaseActor {
pub fn set_display_name(&mut self, display_name: String) {
self.display_name = display_name;
}
pub fn set_profile_url<U: Into<Url>>(&mut self, profile_url: U) {
self.profile_url = profile_url.into();
}
pub fn set_inbox_url<U: Into<Url>>(&mut self, inbox_url: U) {
self.inbox_url = inbox_url.into();
}
pub fn set_outbox_url<U: Into<Url>>(&mut self, outbox_url: U) {
self.outbox_url = outbox_url.into();
}
|
}
pub fn save_changes(self, conn: &PgConnection) -> Result<BaseActor, diesel::result::Error> {
use diesel::prelude::*;
diesel::update(base_actors::table)
.set(&self)
.get_result(conn)
}
}
#[derive(Debug, Queryable, QueryableByName)]
#[table_name = "base_actors"]
pub struct BaseActor {
id: i32,
display_name: String, // max_length: 80
profile_url: Url, // max_length: 2048
inbox_url: Url, // max_length: 2048
outbox_url: Url, // max_length: 2048
local_user: Option<i32>, // foreign key to User
follow_policy: FollowPolicy, // max_length: 8
original_json: Value, // original json
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
}
impl BaseActor {
pub fn id(&self) -> i32 {
self.id
}
pub fn modify(self) -> ModifiedBaseActor {
ModifiedBaseActor {
id: self.id,
display_name: self.display_name,
profile_url: self.profile_url,
inbox_url: self.inbox_url,
outbox_url: self.outbox_url,
follow_policy: self.follow_policy,
original_json: self.original_json,
}
}
pub fn is_following(
&self,
follows: &BaseActor,
conn: &PgConnection,
) -> Result<bool, diesel::result::Error> {
self.is_following_id(follows.id, conn)
}
pub fn is_following_id(
&self,
follows: i32,
conn: &PgConnection,
) -> Result<bool, diesel::result::Error> {
use diesel::prelude::*;
use schema::followers;
followers::table
.filter(followers::dsl::follower.eq(self.id))
.filter(followers::dsl::follows.eq(follows))
.get_result(conn)
.map(|_: Follower| true)
.or_else(|e| match e {
diesel::result::Error::NotFound => Ok(false),
e => Err(e),
})
}
pub fn display_name(&self) -> &str {
&self.display_name
}
pub fn profile_url(&self) -> &Url {
&self.profile_url
}
pub fn inbox_url(&self) -> &Url {
&self.inbox_url
}
pub fn outbox_url(&self) -> &Url {
&self.outbox_url
}
pub fn local_user(&self) -> Option<i32> {
self.local_user
}
pub fn follow_policy(&self) -> FollowPolicy {
self.follow_policy
}
pub fn original_json(&self) -> &Value {
&self.original_json
}
}
#[derive(Insertable)]
#[table_name = "base_actors"]
pub struct NewBaseActor {
display_name: String,
profile_url: Url,
inbox_url: Url,
outbox_url: Url,
local_user: Option<i32>,
follow_policy: FollowPolicy,
original_json: Value,
}
impl NewBaseActor {
pub fn insert(self, conn: &PgConnection) -> Result<BaseActor, diesel::result::Error> {
use diesel::prelude::*;
diesel::insert_into(base_actors::table)
.values(&self)
.get_result(conn)
}
pub fn new<U: UserLike>(
display_name: String,
profile_url: Url,
inbox_url: Url,
outbox_url: Url,
local_user: Option<&U>,
follow_policy: FollowPolicy,
original_json: Value,
) -> Self {
NewBaseActor {
display_name,
profile_url: profile_url.into(),
inbox_url: inbox_url.into(),
outbox_url: outbox_url.into(),
local_user: local_user.map(|lu| lu.id()),
follow_policy,
original_json,
}
}
}
#[cfg(test)]
mod tests {
use test_helper::*;
#[test]
fn create_base_actor() {
with_connection(|conn| with_base_actor(conn, |_| Ok(())))
}
}
|
pub fn set_follow_policy(&mut self, follow_policy: FollowPolicy) {
self.follow_policy = follow_policy;
|
random_line_split
|
mod.rs
|
use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
use serde_json::Value;
use sql_types::{FollowPolicy, Url};
pub mod follow_request;
pub mod follower;
pub mod group;
pub mod persona;
use self::follower::Follower;
use schema::base_actors;
use user::UserLike;
#[derive(Debug, AsChangeset)]
#[table_name = "base_actors"]
pub struct ModifiedBaseActor {
id: i32,
display_name: String,
profile_url: Url,
inbox_url: Url,
outbox_url: Url,
follow_policy: FollowPolicy,
original_json: Value,
}
impl ModifiedBaseActor {
pub fn set_display_name(&mut self, display_name: String) {
self.display_name = display_name;
}
pub fn set_profile_url<U: Into<Url>>(&mut self, profile_url: U) {
self.profile_url = profile_url.into();
}
pub fn set_inbox_url<U: Into<Url>>(&mut self, inbox_url: U) {
self.inbox_url = inbox_url.into();
}
pub fn set_outbox_url<U: Into<Url>>(&mut self, outbox_url: U) {
self.outbox_url = outbox_url.into();
}
pub fn set_follow_policy(&mut self, follow_policy: FollowPolicy) {
self.follow_policy = follow_policy;
}
pub fn save_changes(self, conn: &PgConnection) -> Result<BaseActor, diesel::result::Error> {
use diesel::prelude::*;
diesel::update(base_actors::table)
.set(&self)
.get_result(conn)
}
}
#[derive(Debug, Queryable, QueryableByName)]
#[table_name = "base_actors"]
pub struct BaseActor {
id: i32,
display_name: String, // max_length: 80
profile_url: Url, // max_length: 2048
inbox_url: Url, // max_length: 2048
outbox_url: Url, // max_length: 2048
local_user: Option<i32>, // foreign key to User
follow_policy: FollowPolicy, // max_length: 8
original_json: Value, // original json
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
}
impl BaseActor {
pub fn id(&self) -> i32 {
self.id
}
pub fn modify(self) -> ModifiedBaseActor {
ModifiedBaseActor {
id: self.id,
display_name: self.display_name,
profile_url: self.profile_url,
inbox_url: self.inbox_url,
outbox_url: self.outbox_url,
follow_policy: self.follow_policy,
original_json: self.original_json,
}
}
pub fn
|
(
&self,
follows: &BaseActor,
conn: &PgConnection,
) -> Result<bool, diesel::result::Error> {
self.is_following_id(follows.id, conn)
}
pub fn is_following_id(
&self,
follows: i32,
conn: &PgConnection,
) -> Result<bool, diesel::result::Error> {
use diesel::prelude::*;
use schema::followers;
followers::table
.filter(followers::dsl::follower.eq(self.id))
.filter(followers::dsl::follows.eq(follows))
.get_result(conn)
.map(|_: Follower| true)
.or_else(|e| match e {
diesel::result::Error::NotFound => Ok(false),
e => Err(e),
})
}
pub fn display_name(&self) -> &str {
&self.display_name
}
pub fn profile_url(&self) -> &Url {
&self.profile_url
}
pub fn inbox_url(&self) -> &Url {
&self.inbox_url
}
pub fn outbox_url(&self) -> &Url {
&self.outbox_url
}
pub fn local_user(&self) -> Option<i32> {
self.local_user
}
pub fn follow_policy(&self) -> FollowPolicy {
self.follow_policy
}
pub fn original_json(&self) -> &Value {
&self.original_json
}
}
#[derive(Insertable)]
#[table_name = "base_actors"]
pub struct NewBaseActor {
display_name: String,
profile_url: Url,
inbox_url: Url,
outbox_url: Url,
local_user: Option<i32>,
follow_policy: FollowPolicy,
original_json: Value,
}
impl NewBaseActor {
pub fn insert(self, conn: &PgConnection) -> Result<BaseActor, diesel::result::Error> {
use diesel::prelude::*;
diesel::insert_into(base_actors::table)
.values(&self)
.get_result(conn)
}
pub fn new<U: UserLike>(
display_name: String,
profile_url: Url,
inbox_url: Url,
outbox_url: Url,
local_user: Option<&U>,
follow_policy: FollowPolicy,
original_json: Value,
) -> Self {
NewBaseActor {
display_name,
profile_url: profile_url.into(),
inbox_url: inbox_url.into(),
outbox_url: outbox_url.into(),
local_user: local_user.map(|lu| lu.id()),
follow_policy,
original_json,
}
}
}
#[cfg(test)]
mod tests {
use test_helper::*;
#[test]
fn create_base_actor() {
with_connection(|conn| with_base_actor(conn, |_| Ok(())))
}
}
|
is_following
|
identifier_name
|
mod.rs
|
use chrono::{offset::Utc, DateTime};
use diesel::{self, pg::PgConnection};
use serde_json::Value;
use sql_types::{FollowPolicy, Url};
pub mod follow_request;
pub mod follower;
pub mod group;
pub mod persona;
use self::follower::Follower;
use schema::base_actors;
use user::UserLike;
#[derive(Debug, AsChangeset)]
#[table_name = "base_actors"]
pub struct ModifiedBaseActor {
id: i32,
display_name: String,
profile_url: Url,
inbox_url: Url,
outbox_url: Url,
follow_policy: FollowPolicy,
original_json: Value,
}
impl ModifiedBaseActor {
pub fn set_display_name(&mut self, display_name: String) {
self.display_name = display_name;
}
pub fn set_profile_url<U: Into<Url>>(&mut self, profile_url: U) {
self.profile_url = profile_url.into();
}
pub fn set_inbox_url<U: Into<Url>>(&mut self, inbox_url: U) {
self.inbox_url = inbox_url.into();
}
pub fn set_outbox_url<U: Into<Url>>(&mut self, outbox_url: U) {
self.outbox_url = outbox_url.into();
}
pub fn set_follow_policy(&mut self, follow_policy: FollowPolicy) {
self.follow_policy = follow_policy;
}
pub fn save_changes(self, conn: &PgConnection) -> Result<BaseActor, diesel::result::Error> {
use diesel::prelude::*;
diesel::update(base_actors::table)
.set(&self)
.get_result(conn)
}
}
#[derive(Debug, Queryable, QueryableByName)]
#[table_name = "base_actors"]
pub struct BaseActor {
id: i32,
display_name: String, // max_length: 80
profile_url: Url, // max_length: 2048
inbox_url: Url, // max_length: 2048
outbox_url: Url, // max_length: 2048
local_user: Option<i32>, // foreign key to User
follow_policy: FollowPolicy, // max_length: 8
original_json: Value, // original json
created_at: DateTime<Utc>,
updated_at: DateTime<Utc>,
}
impl BaseActor {
pub fn id(&self) -> i32 {
self.id
}
pub fn modify(self) -> ModifiedBaseActor
|
pub fn is_following(
&self,
follows: &BaseActor,
conn: &PgConnection,
) -> Result<bool, diesel::result::Error> {
self.is_following_id(follows.id, conn)
}
pub fn is_following_id(
&self,
follows: i32,
conn: &PgConnection,
) -> Result<bool, diesel::result::Error> {
use diesel::prelude::*;
use schema::followers;
followers::table
.filter(followers::dsl::follower.eq(self.id))
.filter(followers::dsl::follows.eq(follows))
.get_result(conn)
.map(|_: Follower| true)
.or_else(|e| match e {
diesel::result::Error::NotFound => Ok(false),
e => Err(e),
})
}
pub fn display_name(&self) -> &str {
&self.display_name
}
pub fn profile_url(&self) -> &Url {
&self.profile_url
}
pub fn inbox_url(&self) -> &Url {
&self.inbox_url
}
pub fn outbox_url(&self) -> &Url {
&self.outbox_url
}
pub fn local_user(&self) -> Option<i32> {
self.local_user
}
pub fn follow_policy(&self) -> FollowPolicy {
self.follow_policy
}
pub fn original_json(&self) -> &Value {
&self.original_json
}
}
#[derive(Insertable)]
#[table_name = "base_actors"]
pub struct NewBaseActor {
display_name: String,
profile_url: Url,
inbox_url: Url,
outbox_url: Url,
local_user: Option<i32>,
follow_policy: FollowPolicy,
original_json: Value,
}
impl NewBaseActor {
pub fn insert(self, conn: &PgConnection) -> Result<BaseActor, diesel::result::Error> {
use diesel::prelude::*;
diesel::insert_into(base_actors::table)
.values(&self)
.get_result(conn)
}
pub fn new<U: UserLike>(
display_name: String,
profile_url: Url,
inbox_url: Url,
outbox_url: Url,
local_user: Option<&U>,
follow_policy: FollowPolicy,
original_json: Value,
) -> Self {
NewBaseActor {
display_name,
profile_url: profile_url.into(),
inbox_url: inbox_url.into(),
outbox_url: outbox_url.into(),
local_user: local_user.map(|lu| lu.id()),
follow_policy,
original_json,
}
}
}
#[cfg(test)]
mod tests {
use test_helper::*;
#[test]
fn create_base_actor() {
with_connection(|conn| with_base_actor(conn, |_| Ok(())))
}
}
|
{
ModifiedBaseActor {
id: self.id,
display_name: self.display_name,
profile_url: self.profile_url,
inbox_url: self.inbox_url,
outbox_url: self.outbox_url,
follow_policy: self.follow_policy,
original_json: self.original_json,
}
}
|
identifier_body
|
fix-shoff.rs
|
; radare script to fix elf.shoff
; author: pancake -- nopcode.org @ 2009
;
; Usage example:
; cp /usr/bin/gedit gedit
; # TRASH ELF SHT PTR
; echo wx 99 @ 0x21 | radare -nw gedit
; # OBJDUMP/GDB/LTRACE/... CANNOT DO ANYTHING
; objdump -d gedit # objdump: gedit: File format not recognized
; # FIX ELF SHT PTR
; echo ".(fix-sht) && q" | radare -i scripts/fix-shoff.rs -nw gedit
; # TRY OBJDUMP AGAIN :)
(fix-sht
s 0
s/.text
loop:
s/x 00
|
? [1:$$+1]
?!.loop:
s +4-$$%4
f nsht
wv nsht @ 0x20
)
|
random_line_split
|
|
workspace.rs
|
use crate::config::{CrateDependency, CrateDependencyKind, CrateDependencySource};
use crate::database::{DatabaseCache, DatabaseClient, CRATE_DB_FILE_NAME};
use crate::download_db::download_db;
use log::info;
use ritual_common::errors::{bail, Result};
use ritual_common::file_utils::{
create_dir_all, load_json, os_string_into_string, read_dir, remove_file, save_json,
save_toml_table,
};
use ritual_common::utils::MapIfOk;
use ritual_common::{toml, ReadOnly};
use serde_derive::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct WorkspaceConfig {}
/// Provides access to data stored in the user's project directory.
/// The directory contains a subdirectory for each crate the user wants
/// to process. When running any operations, the data is read from and
/// saved to the workspace files. Global workspace configuration
/// can also be set through the `Workspace` object.
#[derive(Debug)]
pub struct Workspace {
path: PathBuf,
config: WorkspaceConfig,
}
fn config_path(path: &Path) -> PathBuf {
path.join("config.json")
}
fn database_path(workspace_path: &Path, crate_name: &str) -> PathBuf {
workspace_path
.join("db")
.join(format!("{}.json", crate_name))
}
impl Workspace {
pub fn new(path: PathBuf) -> Result<Self> {
if!path.is_dir() {
bail!("No such directory: {}", path.display());
}
let config_path = config_path(&path);
for &dir in &["tmp", "out", "log", "backup", "db", "external_db"] {
create_dir_all(path.join(dir))?;
}
let w = Workspace {
path,
config: if config_path.exists() {
load_json(config_path)?
} else {
WorkspaceConfig::default()
},
};
Ok(w)
}
pub fn database_path(&self, crate_name: &str) -> PathBuf {
database_path(&self.path, crate_name)
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn tmp_path(&self) -> PathBuf {
self.path.join("tmp")
}
pub fn config(&self) -> &WorkspaceConfig {
&self.config
}
pub fn log_path(&self) -> PathBuf {
self.path.join("log")
}
pub fn
|
(&self, crate_name: &str) -> PathBuf {
self.path.join("out").join(crate_name)
}
pub fn delete_database_if_exists(&mut self, crate_name: &str) -> Result<()> {
let path = database_path(&self.path, crate_name);
let mut cache = DatabaseCache::global().lock().unwrap();
cache.remove_if_exists(&path);
if path.exists() {
remove_file(path)?;
}
Ok(())
}
pub fn get_database_client(
&mut self,
crate_name: &str,
dependencies: &[CrateDependency],
allow_load: bool,
allow_create: bool,
) -> Result<DatabaseClient> {
let mut cache = DatabaseCache::global().lock().unwrap();
let current_database = cache.get(
self.database_path(crate_name),
crate_name,
allow_load,
allow_create,
)?;
let dependencies = dependencies
.iter()
.filter(|dep| dep.kind() == CrateDependencyKind::Ritual)
.map_if_ok(|dependency| {
let path = match dependency.source() {
CrateDependencySource::CratesIo { version } => {
self.external_db_path(dependency.name(), version)?
}
CrateDependencySource::Local { path } => path.join(CRATE_DB_FILE_NAME),
CrateDependencySource::CurrentWorkspace => {
self.database_path(dependency.name())
}
};
cache.get(path, dependency.name(), true, false)
})?;
Ok(DatabaseClient::new(
current_database,
ReadOnly::new(dependencies),
))
}
fn database_backup_path(&self, crate_name: &str) -> PathBuf {
let date = chrono::Local::now();
self.path.join("backup").join(format!(
"db_{}_{}.json",
crate_name,
date.format("%Y-%m-%d_%H-%M-%S")
))
}
pub fn save_database(&self, database: &mut DatabaseClient) -> Result<()> {
if database.is_modified() {
info!("Saving data");
let backup_path = self.database_backup_path(database.crate_name());
save_json(
database_path(&self.path, database.crate_name()),
database.data(),
Some(&backup_path),
)?;
database.set_saved();
}
Ok(())
}
pub fn update_cargo_toml(&self) -> Result<()> {
let mut members = Vec::new();
for item in read_dir(self.path.join("out"))? {
let item = item?;
let path = item.path().join("Cargo.toml");
if path.exists() {
let dir_name = os_string_into_string(item.file_name())?;
members.push(toml::Value::String(format!("out/{}", dir_name)));
}
}
let mut table = toml::value::Table::new();
table.insert("members".to_string(), toml::Value::Array(members));
let mut cargo_toml = toml::value::Table::new();
cargo_toml.insert("workspace".to_string(), toml::Value::Table(table));
save_toml_table(
self.path.join("Cargo.toml"),
&toml::Value::Table(cargo_toml),
)?;
Ok(())
}
fn external_db_path(&mut self, crate_name: &str, crate_version: &str) -> Result<PathBuf> {
let path = self
.path
.join(format!("external_db/{}_{}.json", crate_name, crate_version));
if!path.exists() {
download_db(crate_name, crate_version, &path)?;
}
Ok(path)
}
}
|
crate_path
|
identifier_name
|
workspace.rs
|
use crate::config::{CrateDependency, CrateDependencyKind, CrateDependencySource};
use crate::database::{DatabaseCache, DatabaseClient, CRATE_DB_FILE_NAME};
use crate::download_db::download_db;
use log::info;
use ritual_common::errors::{bail, Result};
use ritual_common::file_utils::{
create_dir_all, load_json, os_string_into_string, read_dir, remove_file, save_json,
save_toml_table,
};
use ritual_common::utils::MapIfOk;
use ritual_common::{toml, ReadOnly};
use serde_derive::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct WorkspaceConfig {}
/// Provides access to data stored in the user's project directory.
/// The directory contains a subdirectory for each crate the user wants
/// to process. When running any operations, the data is read from and
/// saved to the workspace files. Global workspace configuration
/// can also be set through the `Workspace` object.
#[derive(Debug)]
pub struct Workspace {
path: PathBuf,
config: WorkspaceConfig,
}
fn config_path(path: &Path) -> PathBuf {
path.join("config.json")
}
|
.join("db")
.join(format!("{}.json", crate_name))
}
impl Workspace {
pub fn new(path: PathBuf) -> Result<Self> {
if!path.is_dir() {
bail!("No such directory: {}", path.display());
}
let config_path = config_path(&path);
for &dir in &["tmp", "out", "log", "backup", "db", "external_db"] {
create_dir_all(path.join(dir))?;
}
let w = Workspace {
path,
config: if config_path.exists() {
load_json(config_path)?
} else {
WorkspaceConfig::default()
},
};
Ok(w)
}
pub fn database_path(&self, crate_name: &str) -> PathBuf {
database_path(&self.path, crate_name)
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn tmp_path(&self) -> PathBuf {
self.path.join("tmp")
}
pub fn config(&self) -> &WorkspaceConfig {
&self.config
}
pub fn log_path(&self) -> PathBuf {
self.path.join("log")
}
pub fn crate_path(&self, crate_name: &str) -> PathBuf {
self.path.join("out").join(crate_name)
}
pub fn delete_database_if_exists(&mut self, crate_name: &str) -> Result<()> {
let path = database_path(&self.path, crate_name);
let mut cache = DatabaseCache::global().lock().unwrap();
cache.remove_if_exists(&path);
if path.exists() {
remove_file(path)?;
}
Ok(())
}
pub fn get_database_client(
&mut self,
crate_name: &str,
dependencies: &[CrateDependency],
allow_load: bool,
allow_create: bool,
) -> Result<DatabaseClient> {
let mut cache = DatabaseCache::global().lock().unwrap();
let current_database = cache.get(
self.database_path(crate_name),
crate_name,
allow_load,
allow_create,
)?;
let dependencies = dependencies
.iter()
.filter(|dep| dep.kind() == CrateDependencyKind::Ritual)
.map_if_ok(|dependency| {
let path = match dependency.source() {
CrateDependencySource::CratesIo { version } => {
self.external_db_path(dependency.name(), version)?
}
CrateDependencySource::Local { path } => path.join(CRATE_DB_FILE_NAME),
CrateDependencySource::CurrentWorkspace => {
self.database_path(dependency.name())
}
};
cache.get(path, dependency.name(), true, false)
})?;
Ok(DatabaseClient::new(
current_database,
ReadOnly::new(dependencies),
))
}
fn database_backup_path(&self, crate_name: &str) -> PathBuf {
let date = chrono::Local::now();
self.path.join("backup").join(format!(
"db_{}_{}.json",
crate_name,
date.format("%Y-%m-%d_%H-%M-%S")
))
}
pub fn save_database(&self, database: &mut DatabaseClient) -> Result<()> {
if database.is_modified() {
info!("Saving data");
let backup_path = self.database_backup_path(database.crate_name());
save_json(
database_path(&self.path, database.crate_name()),
database.data(),
Some(&backup_path),
)?;
database.set_saved();
}
Ok(())
}
pub fn update_cargo_toml(&self) -> Result<()> {
let mut members = Vec::new();
for item in read_dir(self.path.join("out"))? {
let item = item?;
let path = item.path().join("Cargo.toml");
if path.exists() {
let dir_name = os_string_into_string(item.file_name())?;
members.push(toml::Value::String(format!("out/{}", dir_name)));
}
}
let mut table = toml::value::Table::new();
table.insert("members".to_string(), toml::Value::Array(members));
let mut cargo_toml = toml::value::Table::new();
cargo_toml.insert("workspace".to_string(), toml::Value::Table(table));
save_toml_table(
self.path.join("Cargo.toml"),
&toml::Value::Table(cargo_toml),
)?;
Ok(())
}
fn external_db_path(&mut self, crate_name: &str, crate_version: &str) -> Result<PathBuf> {
let path = self
.path
.join(format!("external_db/{}_{}.json", crate_name, crate_version));
if!path.exists() {
download_db(crate_name, crate_version, &path)?;
}
Ok(path)
}
}
|
fn database_path(workspace_path: &Path, crate_name: &str) -> PathBuf {
workspace_path
|
random_line_split
|
workspace.rs
|
use crate::config::{CrateDependency, CrateDependencyKind, CrateDependencySource};
use crate::database::{DatabaseCache, DatabaseClient, CRATE_DB_FILE_NAME};
use crate::download_db::download_db;
use log::info;
use ritual_common::errors::{bail, Result};
use ritual_common::file_utils::{
create_dir_all, load_json, os_string_into_string, read_dir, remove_file, save_json,
save_toml_table,
};
use ritual_common::utils::MapIfOk;
use ritual_common::{toml, ReadOnly};
use serde_derive::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct WorkspaceConfig {}
/// Provides access to data stored in the user's project directory.
/// The directory contains a subdirectory for each crate the user wants
/// to process. When running any operations, the data is read from and
/// saved to the workspace files. Global workspace configuration
/// can also be set through the `Workspace` object.
#[derive(Debug)]
pub struct Workspace {
path: PathBuf,
config: WorkspaceConfig,
}
fn config_path(path: &Path) -> PathBuf {
path.join("config.json")
}
fn database_path(workspace_path: &Path, crate_name: &str) -> PathBuf {
workspace_path
.join("db")
.join(format!("{}.json", crate_name))
}
impl Workspace {
pub fn new(path: PathBuf) -> Result<Self> {
if!path.is_dir()
|
let config_path = config_path(&path);
for &dir in &["tmp", "out", "log", "backup", "db", "external_db"] {
create_dir_all(path.join(dir))?;
}
let w = Workspace {
path,
config: if config_path.exists() {
load_json(config_path)?
} else {
WorkspaceConfig::default()
},
};
Ok(w)
}
pub fn database_path(&self, crate_name: &str) -> PathBuf {
database_path(&self.path, crate_name)
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn tmp_path(&self) -> PathBuf {
self.path.join("tmp")
}
pub fn config(&self) -> &WorkspaceConfig {
&self.config
}
pub fn log_path(&self) -> PathBuf {
self.path.join("log")
}
pub fn crate_path(&self, crate_name: &str) -> PathBuf {
self.path.join("out").join(crate_name)
}
pub fn delete_database_if_exists(&mut self, crate_name: &str) -> Result<()> {
let path = database_path(&self.path, crate_name);
let mut cache = DatabaseCache::global().lock().unwrap();
cache.remove_if_exists(&path);
if path.exists() {
remove_file(path)?;
}
Ok(())
}
pub fn get_database_client(
&mut self,
crate_name: &str,
dependencies: &[CrateDependency],
allow_load: bool,
allow_create: bool,
) -> Result<DatabaseClient> {
let mut cache = DatabaseCache::global().lock().unwrap();
let current_database = cache.get(
self.database_path(crate_name),
crate_name,
allow_load,
allow_create,
)?;
let dependencies = dependencies
.iter()
.filter(|dep| dep.kind() == CrateDependencyKind::Ritual)
.map_if_ok(|dependency| {
let path = match dependency.source() {
CrateDependencySource::CratesIo { version } => {
self.external_db_path(dependency.name(), version)?
}
CrateDependencySource::Local { path } => path.join(CRATE_DB_FILE_NAME),
CrateDependencySource::CurrentWorkspace => {
self.database_path(dependency.name())
}
};
cache.get(path, dependency.name(), true, false)
})?;
Ok(DatabaseClient::new(
current_database,
ReadOnly::new(dependencies),
))
}
fn database_backup_path(&self, crate_name: &str) -> PathBuf {
let date = chrono::Local::now();
self.path.join("backup").join(format!(
"db_{}_{}.json",
crate_name,
date.format("%Y-%m-%d_%H-%M-%S")
))
}
pub fn save_database(&self, database: &mut DatabaseClient) -> Result<()> {
if database.is_modified() {
info!("Saving data");
let backup_path = self.database_backup_path(database.crate_name());
save_json(
database_path(&self.path, database.crate_name()),
database.data(),
Some(&backup_path),
)?;
database.set_saved();
}
Ok(())
}
pub fn update_cargo_toml(&self) -> Result<()> {
let mut members = Vec::new();
for item in read_dir(self.path.join("out"))? {
let item = item?;
let path = item.path().join("Cargo.toml");
if path.exists() {
let dir_name = os_string_into_string(item.file_name())?;
members.push(toml::Value::String(format!("out/{}", dir_name)));
}
}
let mut table = toml::value::Table::new();
table.insert("members".to_string(), toml::Value::Array(members));
let mut cargo_toml = toml::value::Table::new();
cargo_toml.insert("workspace".to_string(), toml::Value::Table(table));
save_toml_table(
self.path.join("Cargo.toml"),
&toml::Value::Table(cargo_toml),
)?;
Ok(())
}
fn external_db_path(&mut self, crate_name: &str, crate_version: &str) -> Result<PathBuf> {
let path = self
.path
.join(format!("external_db/{}_{}.json", crate_name, crate_version));
if!path.exists() {
download_db(crate_name, crate_version, &path)?;
}
Ok(path)
}
}
|
{
bail!("No such directory: {}", path.display());
}
|
conditional_block
|
trait-bounds-on-structs-and-enums.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait U : ::std::marker::MarkerTrait {}
trait T<X: U> { fn get(self) -> X; }
trait S2<Y: U> : ::std::marker::MarkerTrait {
fn m(x: Box<T<Y>+'static>) {}
}
struct St<X: U> {
f: Box<T<X>+'static>,
}
impl<X: U> St<X> {
fn
|
() {}
}
fn main() {}
|
blah
|
identifier_name
|
trait-bounds-on-structs-and-enums.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
trait U : ::std::marker::MarkerTrait {}
trait T<X: U> { fn get(self) -> X; }
trait S2<Y: U> : ::std::marker::MarkerTrait {
fn m(x: Box<T<Y>+'static>) {}
|
f: Box<T<X>+'static>,
}
impl<X: U> St<X> {
fn blah() {}
}
fn main() {}
|
}
struct St<X: U> {
|
random_line_split
|
main.rs
|
// normalize-stderr-32bit: "`&str` \(64 bits\)" -> "`&str` ($$STR bits)"
// normalize-stderr-64bit: "`&str` \(128 bits\)" -> "`&str` ($$STR bits)"
use std::mem::transmute;
pub trait TypeConstructor<'a> {
type T;
}
unsafe fn transmute_lifetime<'a, 'b, C>(x: <C as TypeConstructor<'a>>::T)
-> <C as TypeConstructor<'b>>::T
where for<'z> C: TypeConstructor<'z> {
transmute(x) //~ ERROR cannot transmute between types of different sizes
}
unsafe fn sizes() {
let x: u8 = transmute(10u16); //~ ERROR cannot transmute between types of different sizes
}
unsafe fn ptrs() {
let x: u8 = transmute("test"); //~ ERROR cannot transmute between types of different sizes
}
|
let x: Foo = transmute(10); //~ ERROR cannot transmute between types of different sizes
}
fn main() {}
|
union Foo { x: () }
unsafe fn vary() {
|
random_line_split
|
main.rs
|
// normalize-stderr-32bit: "`&str` \(64 bits\)" -> "`&str` ($$STR bits)"
// normalize-stderr-64bit: "`&str` \(128 bits\)" -> "`&str` ($$STR bits)"
use std::mem::transmute;
pub trait TypeConstructor<'a> {
type T;
}
unsafe fn transmute_lifetime<'a, 'b, C>(x: <C as TypeConstructor<'a>>::T)
-> <C as TypeConstructor<'b>>::T
where for<'z> C: TypeConstructor<'z>
|
unsafe fn sizes() {
let x: u8 = transmute(10u16); //~ ERROR cannot transmute between types of different sizes
}
unsafe fn ptrs() {
let x: u8 = transmute("test"); //~ ERROR cannot transmute between types of different sizes
}
union Foo { x: () }
unsafe fn vary() {
let x: Foo = transmute(10); //~ ERROR cannot transmute between types of different sizes
}
fn main() {}
|
{
transmute(x) //~ ERROR cannot transmute between types of different sizes
}
|
identifier_body
|
main.rs
|
// normalize-stderr-32bit: "`&str` \(64 bits\)" -> "`&str` ($$STR bits)"
// normalize-stderr-64bit: "`&str` \(128 bits\)" -> "`&str` ($$STR bits)"
use std::mem::transmute;
pub trait TypeConstructor<'a> {
type T;
}
unsafe fn transmute_lifetime<'a, 'b, C>(x: <C as TypeConstructor<'a>>::T)
-> <C as TypeConstructor<'b>>::T
where for<'z> C: TypeConstructor<'z> {
transmute(x) //~ ERROR cannot transmute between types of different sizes
}
unsafe fn sizes() {
let x: u8 = transmute(10u16); //~ ERROR cannot transmute between types of different sizes
}
unsafe fn ptrs() {
let x: u8 = transmute("test"); //~ ERROR cannot transmute between types of different sizes
}
union Foo { x: () }
unsafe fn vary() {
let x: Foo = transmute(10); //~ ERROR cannot transmute between types of different sizes
}
fn
|
() {}
|
main
|
identifier_name
|
issue-83538-tainted-cache-after-cycle.rs
|
// Regression test for issue #83538. The problem here is that we have
// two cycles:
//
// * `Ty` embeds `Box<Ty>` indirectly, which depends on `Global:'static`, which is OkModuloRegions.
// * But `Ty` also references `First`, which has a cycle on itself. That should just be `Ok`.
//
// But our caching mechanism was blending both cycles and giving the incorrect result.
#![feature(rustc_attrs)]
#![allow(bad_style)]
struct First {
b: Vec<First>,
}
pub struct Second {
d: Vec<First>,
}
struct Third<'a, f> {
g: Vec<(f, &'a f)>,
}
enum Ty {
j(Fourth, Fifth, Sixth),
}
struct Fourth {
o: Vec<Ty>,
}
struct Fifth {
bounds: First,
}
struct Sixth {
p: Box<Ty>,
}
#[rustc_evaluate_where_clauses]
fn forward<'a>()
where
Vec<First>: Unpin,
Third<'a, Ty>: Unpin,
{
}
#[rustc_evaluate_where_clauses]
fn reverse<'a>()
|
}
fn main() {
// Key is that Vec<First> is "ok" and Third<'_, Ty> is "ok modulo regions":
forward();
//~^ ERROR evaluate(Binder(TraitPredicate(<std::vec::Vec<First> as std::marker::Unpin>), [])) = Ok(EvaluatedToOk)
//~| ERROR evaluate(Binder(TraitPredicate(<Third<'_, Ty> as std::marker::Unpin>), [])) = Ok(EvaluatedToOkModuloRegions)
reverse();
//~^ ERROR evaluate(Binder(TraitPredicate(<std::vec::Vec<First> as std::marker::Unpin>), [])) = Ok(EvaluatedToOk)
//~| ERROR evaluate(Binder(TraitPredicate(<Third<'_, Ty> as std::marker::Unpin>), [])) = Ok(EvaluatedToOkModuloRegions)
}
|
where
Third<'a, Ty>: Unpin,
Vec<First>: Unpin,
{
|
random_line_split
|
issue-83538-tainted-cache-after-cycle.rs
|
// Regression test for issue #83538. The problem here is that we have
// two cycles:
//
// * `Ty` embeds `Box<Ty>` indirectly, which depends on `Global:'static`, which is OkModuloRegions.
// * But `Ty` also references `First`, which has a cycle on itself. That should just be `Ok`.
//
// But our caching mechanism was blending both cycles and giving the incorrect result.
#![feature(rustc_attrs)]
#![allow(bad_style)]
struct First {
b: Vec<First>,
}
pub struct Second {
d: Vec<First>,
}
struct
|
<'a, f> {
g: Vec<(f, &'a f)>,
}
enum Ty {
j(Fourth, Fifth, Sixth),
}
struct Fourth {
o: Vec<Ty>,
}
struct Fifth {
bounds: First,
}
struct Sixth {
p: Box<Ty>,
}
#[rustc_evaluate_where_clauses]
fn forward<'a>()
where
Vec<First>: Unpin,
Third<'a, Ty>: Unpin,
{
}
#[rustc_evaluate_where_clauses]
fn reverse<'a>()
where
Third<'a, Ty>: Unpin,
Vec<First>: Unpin,
{
}
fn main() {
// Key is that Vec<First> is "ok" and Third<'_, Ty> is "ok modulo regions":
forward();
//~^ ERROR evaluate(Binder(TraitPredicate(<std::vec::Vec<First> as std::marker::Unpin>), [])) = Ok(EvaluatedToOk)
//~| ERROR evaluate(Binder(TraitPredicate(<Third<'_, Ty> as std::marker::Unpin>), [])) = Ok(EvaluatedToOkModuloRegions)
reverse();
//~^ ERROR evaluate(Binder(TraitPredicate(<std::vec::Vec<First> as std::marker::Unpin>), [])) = Ok(EvaluatedToOk)
//~| ERROR evaluate(Binder(TraitPredicate(<Third<'_, Ty> as std::marker::Unpin>), [])) = Ok(EvaluatedToOkModuloRegions)
}
|
Third
|
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", animation_value_type="discrete",
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-position")}
// 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.
//
// In gecko, {upper,lower}-{roman,alpha} are implemented as @counter-styles in the
// UA, however they can also be set from pres attrs. When @counter-style is supported
// we may need to look into this and handle these differently.
//
// [1]: http://dev.w3.org/csswg/css-counter-styles/
% if product == "servo":
${helpers.single_keyword("list-style-type", """
disc none circle square decimal disclosure-open disclosure-closed lower-alpha upper-alpha
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""",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-type")}
% else:
<%helpers:longhand name="list-style-type" animation_value_type="discrete" boxed="True"
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-type">
use values::CustomIdent;
use values::computed::ComputedValueAsSpecified;
use values::generics::CounterStyleOrNone;
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
use values::generics::CounterStyleOrNone;
/// <counter-style> | <string> | none
#[derive(Debug, Clone, Eq, PartialEq, ToCss)]
pub enum
|
{
CounterStyle(CounterStyleOrNone),
String(String),
}
}
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
#[cfg(feature = "gecko")]
impl SpecifiedValue {
/// Convert from gecko keyword to list-style-type.
///
/// This should only be used for mapping type attribute to
/// list-style-type, and thus only values possible in that
/// attribute is considered here.
pub fn from_gecko_keyword(value: u32) -> Self {
use gecko_bindings::structs;
SpecifiedValue::CounterStyle(if value == structs::NS_STYLE_LIST_STYLE_NONE {
CounterStyleOrNone::None
} else {
<%
values = """disc circle square decimal lower-roman
upper-roman lower-alpha upper-alpha""".split()
%>
CounterStyleOrNone::Name(CustomIdent(match value {
% for style in values:
structs::NS_STYLE_LIST_STYLE_${style.replace('-', '_').upper()} => atom!("${style}"),
% endfor
_ => unreachable!("Unknown counter style keyword value"),
}))
})
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::CounterStyle(CounterStyleOrNone::disc())
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::CounterStyle(CounterStyleOrNone::disc())
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
Ok(if let Ok(style) = input.try(|i| CounterStyleOrNone::parse(context, i)) {
SpecifiedValue::CounterStyle(style)
} else {
SpecifiedValue::String(input.expect_string()?.as_ref().to_owned())
})
}
</%helpers:longhand>
% endif
<%helpers:longhand name="list-style-image" animation_value_type="discrete"
boxed="${product == 'gecko'}"
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-image">
use values::computed::ComputedValueAsSpecified;
use values::specified::UrlOrNone;
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
use values::specified::UrlOrNone;
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Debug, Clone, PartialEq, ToCss)]
pub struct T(pub UrlOrNone);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(Either::Second(None_))
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue(Either::Second(None_))
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue,ParseError<'i>> {
% if product == "gecko":
let mut value = input.try(|input| UrlOrNone::parse(context, input))?;
if let Either::First(ref mut url) = value {
url.build_image_value();
}
% else :
let value = input.try(|input| UrlOrNone::parse(context, input))?;
% endif
return Ok(SpecifiedValue(value));
}
</%helpers:longhand>
<%helpers:longhand name="quotes" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-content/#propdef-quotes">
use cssparser::serialize_string;
use std::fmt;
use style_traits::ToCss;
use values::computed::ComputedValueAsSpecified;
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 {}
no_viewport_percentage!(SpecifiedValue);
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.0.is_empty() {
return dest.write_str("none")
}
let mut first = true;
for pair in &self.0 {
if!first {
dest.write_str(" ")?;
}
first = false;
serialize_string(&*pair.0, dest)?;
dest.write_str(" ")?;
serialize_string(&*pair.1, 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<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue,ParseError<'i>> {
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(ref value)) => value.as_ref().to_owned(),
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(_) => break,
};
let second = match input.next() {
Ok(&Token::QuotedString(ref value)) => value.as_ref().to_owned(),
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(e) => return Err(e.into()),
};
quotes.push((first, second))
}
if!quotes.is_empty() {
Ok(SpecifiedValue(quotes))
} else {
Err(StyleParseError::UnspecifiedError.into())
}
}
</%helpers:longhand>
${helpers.predefined_type("-moz-image-region",
"ClipRectOrAuto",
"computed::ClipRectOrAuto::auto()",
animation_value_type="ComputedValue",
products="gecko",
boxed="True",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-image-region)")}
|
T
|
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" />
|
// 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.
//
// In gecko, {upper,lower}-{roman,alpha} are implemented as @counter-styles in the
// UA, however they can also be set from pres attrs. When @counter-style is supported
// we may need to look into this and handle these differently.
//
// [1]: http://dev.w3.org/csswg/css-counter-styles/
% if product == "servo":
${helpers.single_keyword("list-style-type", """
disc none circle square decimal disclosure-open disclosure-closed lower-alpha upper-alpha
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""",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-type")}
% else:
<%helpers:longhand name="list-style-type" animation_value_type="discrete" boxed="True"
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-type">
use values::CustomIdent;
use values::computed::ComputedValueAsSpecified;
use values::generics::CounterStyleOrNone;
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
use values::generics::CounterStyleOrNone;
/// <counter-style> | <string> | none
#[derive(Debug, Clone, Eq, PartialEq, ToCss)]
pub enum T {
CounterStyle(CounterStyleOrNone),
String(String),
}
}
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
#[cfg(feature = "gecko")]
impl SpecifiedValue {
/// Convert from gecko keyword to list-style-type.
///
/// This should only be used for mapping type attribute to
/// list-style-type, and thus only values possible in that
/// attribute is considered here.
pub fn from_gecko_keyword(value: u32) -> Self {
use gecko_bindings::structs;
SpecifiedValue::CounterStyle(if value == structs::NS_STYLE_LIST_STYLE_NONE {
CounterStyleOrNone::None
} else {
<%
values = """disc circle square decimal lower-roman
upper-roman lower-alpha upper-alpha""".split()
%>
CounterStyleOrNone::Name(CustomIdent(match value {
% for style in values:
structs::NS_STYLE_LIST_STYLE_${style.replace('-', '_').upper()} => atom!("${style}"),
% endfor
_ => unreachable!("Unknown counter style keyword value"),
}))
})
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::CounterStyle(CounterStyleOrNone::disc())
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::CounterStyle(CounterStyleOrNone::disc())
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
Ok(if let Ok(style) = input.try(|i| CounterStyleOrNone::parse(context, i)) {
SpecifiedValue::CounterStyle(style)
} else {
SpecifiedValue::String(input.expect_string()?.as_ref().to_owned())
})
}
</%helpers:longhand>
% endif
<%helpers:longhand name="list-style-image" animation_value_type="discrete"
boxed="${product == 'gecko'}"
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-image">
use values::computed::ComputedValueAsSpecified;
use values::specified::UrlOrNone;
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
use values::specified::UrlOrNone;
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Debug, Clone, PartialEq, ToCss)]
pub struct T(pub UrlOrNone);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(Either::Second(None_))
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue(Either::Second(None_))
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue,ParseError<'i>> {
% if product == "gecko":
let mut value = input.try(|input| UrlOrNone::parse(context, input))?;
if let Either::First(ref mut url) = value {
url.build_image_value();
}
% else :
let value = input.try(|input| UrlOrNone::parse(context, input))?;
% endif
return Ok(SpecifiedValue(value));
}
</%helpers:longhand>
<%helpers:longhand name="quotes" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-content/#propdef-quotes">
use cssparser::serialize_string;
use std::fmt;
use style_traits::ToCss;
use values::computed::ComputedValueAsSpecified;
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 {}
no_viewport_percentage!(SpecifiedValue);
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.0.is_empty() {
return dest.write_str("none")
}
let mut first = true;
for pair in &self.0 {
if!first {
dest.write_str(" ")?;
}
first = false;
serialize_string(&*pair.0, dest)?;
dest.write_str(" ")?;
serialize_string(&*pair.1, 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<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue,ParseError<'i>> {
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(ref value)) => value.as_ref().to_owned(),
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(_) => break,
};
let second = match input.next() {
Ok(&Token::QuotedString(ref value)) => value.as_ref().to_owned(),
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(e) => return Err(e.into()),
};
quotes.push((first, second))
}
if!quotes.is_empty() {
Ok(SpecifiedValue(quotes))
} else {
Err(StyleParseError::UnspecifiedError.into())
}
}
</%helpers:longhand>
${helpers.predefined_type("-moz-image-region",
"ClipRectOrAuto",
"computed::ClipRectOrAuto::auto()",
animation_value_type="ComputedValue",
products="gecko",
boxed="True",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-image-region)")}
|
<% data.new_style_struct("List", inherited=True) %>
${helpers.single_keyword("list-style-position", "outside inside", animation_value_type="discrete",
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-position")}
|
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", animation_value_type="discrete",
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-position")}
// 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.
//
// In gecko, {upper,lower}-{roman,alpha} are implemented as @counter-styles in the
// UA, however they can also be set from pres attrs. When @counter-style is supported
// we may need to look into this and handle these differently.
//
// [1]: http://dev.w3.org/csswg/css-counter-styles/
% if product == "servo":
${helpers.single_keyword("list-style-type", """
disc none circle square decimal disclosure-open disclosure-closed lower-alpha upper-alpha
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""",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-type")}
% else:
<%helpers:longhand name="list-style-type" animation_value_type="discrete" boxed="True"
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-type">
use values::CustomIdent;
use values::computed::ComputedValueAsSpecified;
use values::generics::CounterStyleOrNone;
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
use values::generics::CounterStyleOrNone;
/// <counter-style> | <string> | none
#[derive(Debug, Clone, Eq, PartialEq, ToCss)]
pub enum T {
CounterStyle(CounterStyleOrNone),
String(String),
}
}
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
#[cfg(feature = "gecko")]
impl SpecifiedValue {
/// Convert from gecko keyword to list-style-type.
///
/// This should only be used for mapping type attribute to
/// list-style-type, and thus only values possible in that
/// attribute is considered here.
pub fn from_gecko_keyword(value: u32) -> Self {
use gecko_bindings::structs;
SpecifiedValue::CounterStyle(if value == structs::NS_STYLE_LIST_STYLE_NONE {
CounterStyleOrNone::None
} else {
<%
values = """disc circle square decimal lower-roman
upper-roman lower-alpha upper-alpha""".split()
%>
CounterStyleOrNone::Name(CustomIdent(match value {
% for style in values:
structs::NS_STYLE_LIST_STYLE_${style.replace('-', '_').upper()} => atom!("${style}"),
% endfor
_ => unreachable!("Unknown counter style keyword value"),
}))
})
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T::CounterStyle(CounterStyleOrNone::disc())
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::CounterStyle(CounterStyleOrNone::disc())
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
Ok(if let Ok(style) = input.try(|i| CounterStyleOrNone::parse(context, i)) {
SpecifiedValue::CounterStyle(style)
} else {
SpecifiedValue::String(input.expect_string()?.as_ref().to_owned())
})
}
</%helpers:longhand>
% endif
<%helpers:longhand name="list-style-image" animation_value_type="discrete"
boxed="${product == 'gecko'}"
spec="https://drafts.csswg.org/css-lists/#propdef-list-style-image">
use values::computed::ComputedValueAsSpecified;
use values::specified::UrlOrNone;
pub use self::computed_value::T as SpecifiedValue;
pub mod computed_value {
use values::specified::UrlOrNone;
#[cfg_attr(feature = "servo", derive(HeapSizeOf))]
#[derive(Debug, Clone, PartialEq, ToCss)]
pub struct T(pub UrlOrNone);
}
impl ComputedValueAsSpecified for SpecifiedValue {}
no_viewport_percentage!(SpecifiedValue);
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T(Either::Second(None_))
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue(Either::Second(None_))
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue,ParseError<'i>> {
% if product == "gecko":
let mut value = input.try(|input| UrlOrNone::parse(context, input))?;
if let Either::First(ref mut url) = value {
url.build_image_value();
}
% else :
let value = input.try(|input| UrlOrNone::parse(context, input))?;
% endif
return Ok(SpecifiedValue(value));
}
</%helpers:longhand>
<%helpers:longhand name="quotes" animation_value_type="discrete"
spec="https://drafts.csswg.org/css-content/#propdef-quotes">
use cssparser::serialize_string;
use std::fmt;
use style_traits::ToCss;
use values::computed::ComputedValueAsSpecified;
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 {}
no_viewport_percentage!(SpecifiedValue);
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.0.is_empty() {
return dest.write_str("none")
}
let mut first = true;
for pair in &self.0 {
if!first {
dest.write_str(" ")?;
}
first = false;
serialize_string(&*pair.0, dest)?;
dest.write_str(" ")?;
serialize_string(&*pair.1, 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<'i, 't>(_: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue,ParseError<'i>>
|
Ok(SpecifiedValue(quotes))
} else {
Err(StyleParseError::UnspecifiedError.into())
}
}
</%helpers:longhand>
${helpers.predefined_type("-moz-image-region",
"ClipRectOrAuto",
"computed::ClipRectOrAuto::auto()",
animation_value_type="ComputedValue",
products="gecko",
boxed="True",
spec="Nonstandard (https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-image-region)")}
|
{
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(ref value)) => value.as_ref().to_owned(),
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(_) => break,
};
let second = match input.next() {
Ok(&Token::QuotedString(ref value)) => value.as_ref().to_owned(),
Ok(t) => return Err(BasicParseError::UnexpectedToken(t.clone()).into()),
Err(e) => return Err(e.into()),
};
quotes.push((first, second))
}
if !quotes.is_empty() {
|
identifier_body
|
mod.rs
|
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Database migrations.
pub mod state;
pub mod blocks;
pub mod extras;
mod v9;
pub use self::v9::ToV9;
pub use self::v9::Extract;
mod v10;
pub use self::v10::ToV10;
|
// Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
|
random_line_split
|
|
fn-trait-formatting.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
#![feature(box_syntax)]
fn needs_fn<F>(x: F) where F: Fn(isize) -> isize {}
fn main()
|
needs_fn(1);
//~^ ERROR `core::ops::Fn<(isize,)>`
//~| ERROR `core::ops::Fn<(isize,)>`
}
|
{
let _: () = (box |_: isize| {}) as Box<FnOnce(isize)>;
//~^ ERROR object-safe
//~| ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::FnOnce(isize)>`
//~| expected ()
//~| found box
let _: () = (box |_: isize, isize| {}) as Box<Fn(isize, isize)>;
//~^ ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::Fn(isize, isize)>`
//~| expected ()
//~| found box
let _: () = (box || -> isize unimplemented!()) as Box<FnMut() -> isize>;
//~^ ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::FnMut() -> isize>`
//~| expected ()
//~| found box
|
identifier_body
|
fn-trait-formatting.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
#![feature(box_syntax)]
fn needs_fn<F>(x: F) where F: Fn(isize) -> isize {}
fn main() {
let _: () = (box |_: isize| {}) as Box<FnOnce(isize)>;
//~^ ERROR object-safe
|
//~| ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::FnOnce(isize)>`
//~| expected ()
//~| found box
let _: () = (box |_: isize, isize| {}) as Box<Fn(isize, isize)>;
//~^ ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::Fn(isize, isize)>`
//~| expected ()
//~| found box
let _: () = (box || -> isize unimplemented!()) as Box<FnMut() -> isize>;
//~^ ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::FnMut() -> isize>`
//~| expected ()
//~| found box
needs_fn(1);
//~^ ERROR `core::ops::Fn<(isize,)>`
//~| ERROR `core::ops::Fn<(isize,)>`
}
|
random_line_split
|
|
fn-trait-formatting.rs
|
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(unboxed_closures)]
#![feature(box_syntax)]
fn needs_fn<F>(x: F) where F: Fn(isize) -> isize {}
fn
|
() {
let _: () = (box |_: isize| {}) as Box<FnOnce(isize)>;
//~^ ERROR object-safe
//~| ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::FnOnce(isize)>`
//~| expected ()
//~| found box
let _: () = (box |_: isize, isize| {}) as Box<Fn(isize, isize)>;
//~^ ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::Fn(isize, isize)>`
//~| expected ()
//~| found box
let _: () = (box || -> isize unimplemented!()) as Box<FnMut() -> isize>;
//~^ ERROR mismatched types
//~| expected `()`
//~| found `Box<core::ops::FnMut() -> isize>`
//~| expected ()
//~| found box
needs_fn(1);
//~^ ERROR `core::ops::Fn<(isize,)>`
//~| ERROR `core::ops::Fn<(isize,)>`
}
|
main
|
identifier_name
|
int_test.rs
|
// int_test.rs
//
// Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Jim Davies, Brian Gough
// Copyright (C) 2016 G.vd.Schoot
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or (at
// your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
mod gsl;
extern crate stat;
use stat::*;
#[test]
fn test_i32_slice()
|
gsl::test_rel(mean, expected, rel, "mean(fractional)");
}
{
let mean = mean(slice_a);
let variance = variance_with_fixed_mean(slice_a, mean);
let expected = 13.7;
gsl::test_rel(variance, expected, rel, "variance_with_fixed_mean");
}
{
let mean = mean(slice_a);
let sd = sd_with_fixed_mean(slice_a, mean);
let expected = 3.70135110466435;
gsl::test_rel(sd, expected, rel, "sd_with_fixed_mean");
}
{
let variance = variance(slice_a);
let expected = 14.4210526315789;
gsl::test_rel(variance, expected, rel, "variance");
}
{
let sd_est = sd(slice_a);
let expected = 3.79750610685209;
gsl::test_rel(sd_est, expected, rel, "sd");
}
{
let absdev = absdev(slice_a);
let expected = 2.9;
gsl::test_rel(absdev, expected, rel, "absdev");
}
{
let skew = skew(slice_a);
let expected = -0.909355923168064;
gsl::test_rel(skew, expected, rel, "skew");
}
{
let kurt = kurtosis(slice_a);
let expected = -0.233692524908094;
gsl::test_rel(kurt, expected, rel, "kurtosis");
}
{
let c = covariance(slice_a, slice_b);
let expected = 14.5263157894737;
gsl::test_rel(c, expected, rel, "covariance");
}
{
let r = correlation(slice_a, slice_b);
let expected = 0.793090350710101;
gsl::test_rel(r, expected, rel, "correlation");
}
{
let pv = p_variance(slice_a, slice_b);
let expected = 18.8421052631579;
gsl::test_rel(pv, expected, rel, "p_variance");
}
{
let t = t_test(slice_a, slice_b);
let expected = -1.45701922702927;
gsl::test_rel(t, expected, rel, "t_test");
}
{
let (maxf, max_index) = max(slice_a);
let max = maxf as i64;
let expected = 22i64;
let expected_index = 9;
let str1 = format!("max ({} observed vs {} expected)", max, expected);
gsl::test(max!= expected, &str1);
let str2 = format!("max index ({} observed vs {} expected)",
max_index,
expected_index);
gsl::test(max_index!= expected_index, &str2);
}
{
let (minf, min_index) = min(slice_a);
let min = minf as i32;
let expected = 8;
let expected_index = 12;
let str1 = format!("min ({} observed vs {} expected)", min, expected);
gsl::test(min!= expected, &str1);
let str2 = format!("min index ({} observed vs {} expected)",
min_index,
expected_index);
gsl::test(min_index!= expected_index, &str2);
}
{
let (minf, min_index, maxf, max_index) = minmax(slice_a);
let min = minf as i32;
let max = maxf as i32;
let expected_max = 22;
let expected_min = 8;
let expected_max_index = 9;
let expected_min_index = 12;
let str1 = format!("minmax max ({} observed vs {} expected)", max, expected_max);
gsl::test(max!= expected_max, &str1);
let str2 = format!("minmax min ({} observed vs {} expected)", min, expected_min);
gsl::test(min!= expected_min, &str2);
let str3 = format!("minmax index max ({} observed vs {} expected)",
max_index,
expected_max_index);
gsl::test(max_index!= expected_max_index, &str3);
let str4 = format!("minmax index min ({} observed vs {} expected)",
min_index,
expected_min_index);
gsl::test(min_index!= expected_min_index, &str4);
}
let mut sorted = slice_a.clone();
sorted.sort();
{
let median = median_from_sorted_data(&sorted);
let expected = 18.0;
gsl::test_rel(median, expected, rel, "median_from_sorted_data(even)");
}
{
let zeroth = quantile_from_sorted_data(&sorted, 0.0);
let expected = 8.0;
gsl::test_rel(zeroth, expected, rel, "quantile_from_sorted_data(0)");
}
{
let top = quantile_from_sorted_data(&sorted, 1.0);
let expected = 22.0;
gsl::test_rel(top, expected, rel, "quantile_from_sorted_data(100)");
}
{
let median = quantile_from_sorted_data(&sorted, 0.5);
let expected = 18.0;
gsl::test_rel(median, expected, rel, "quantile_from_sorted_data(50, even)");
}
}
|
{
// sample sets of integers
let slice_1 = &[1, 2, 3, 4, 5, 6];
let slice_a = &[17, 18, 16, 18, 12, 20, 18, 20, 20, 22, 20, 10, 8, 12, 16, 16, 18, 20, 18, 21];
let slice_b = &[19, 20, 22, 24, 10, 25, 20, 22, 21, 23, 20, 10, 12, 14, 12, 20, 22, 24, 23, 17];
let rel = 1.0e-10;
{
let mean = mean(slice_a);
let expected = 17.0;
gsl::test_rel(mean, expected, rel, "mean(integer)");
}
{
let mean = mean(slice_1);
let expected = 3.5;
|
identifier_body
|
int_test.rs
|
// int_test.rs
//
// Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Jim Davies, Brian Gough
// Copyright (C) 2016 G.vd.Schoot
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or (at
// your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
mod gsl;
extern crate stat;
use stat::*;
#[test]
fn
|
() {
// sample sets of integers
let slice_1 = &[1, 2, 3, 4, 5, 6];
let slice_a = &[17, 18, 16, 18, 12, 20, 18, 20, 20, 22, 20, 10, 8, 12, 16, 16, 18, 20, 18, 21];
let slice_b = &[19, 20, 22, 24, 10, 25, 20, 22, 21, 23, 20, 10, 12, 14, 12, 20, 22, 24, 23, 17];
let rel = 1.0e-10;
{
let mean = mean(slice_a);
let expected = 17.0;
gsl::test_rel(mean, expected, rel, "mean(integer)");
}
{
let mean = mean(slice_1);
let expected = 3.5;
gsl::test_rel(mean, expected, rel, "mean(fractional)");
}
{
let mean = mean(slice_a);
let variance = variance_with_fixed_mean(slice_a, mean);
let expected = 13.7;
gsl::test_rel(variance, expected, rel, "variance_with_fixed_mean");
}
{
let mean = mean(slice_a);
let sd = sd_with_fixed_mean(slice_a, mean);
let expected = 3.70135110466435;
gsl::test_rel(sd, expected, rel, "sd_with_fixed_mean");
}
{
let variance = variance(slice_a);
let expected = 14.4210526315789;
gsl::test_rel(variance, expected, rel, "variance");
}
{
let sd_est = sd(slice_a);
let expected = 3.79750610685209;
gsl::test_rel(sd_est, expected, rel, "sd");
}
{
let absdev = absdev(slice_a);
let expected = 2.9;
gsl::test_rel(absdev, expected, rel, "absdev");
}
{
let skew = skew(slice_a);
let expected = -0.909355923168064;
gsl::test_rel(skew, expected, rel, "skew");
}
{
let kurt = kurtosis(slice_a);
let expected = -0.233692524908094;
gsl::test_rel(kurt, expected, rel, "kurtosis");
}
{
let c = covariance(slice_a, slice_b);
let expected = 14.5263157894737;
gsl::test_rel(c, expected, rel, "covariance");
}
{
let r = correlation(slice_a, slice_b);
let expected = 0.793090350710101;
gsl::test_rel(r, expected, rel, "correlation");
}
{
let pv = p_variance(slice_a, slice_b);
let expected = 18.8421052631579;
gsl::test_rel(pv, expected, rel, "p_variance");
}
{
let t = t_test(slice_a, slice_b);
let expected = -1.45701922702927;
gsl::test_rel(t, expected, rel, "t_test");
}
{
let (maxf, max_index) = max(slice_a);
let max = maxf as i64;
let expected = 22i64;
let expected_index = 9;
let str1 = format!("max ({} observed vs {} expected)", max, expected);
gsl::test(max!= expected, &str1);
let str2 = format!("max index ({} observed vs {} expected)",
max_index,
expected_index);
gsl::test(max_index!= expected_index, &str2);
}
{
let (minf, min_index) = min(slice_a);
let min = minf as i32;
let expected = 8;
let expected_index = 12;
let str1 = format!("min ({} observed vs {} expected)", min, expected);
gsl::test(min!= expected, &str1);
let str2 = format!("min index ({} observed vs {} expected)",
min_index,
expected_index);
gsl::test(min_index!= expected_index, &str2);
}
{
let (minf, min_index, maxf, max_index) = minmax(slice_a);
let min = minf as i32;
let max = maxf as i32;
let expected_max = 22;
let expected_min = 8;
let expected_max_index = 9;
let expected_min_index = 12;
let str1 = format!("minmax max ({} observed vs {} expected)", max, expected_max);
gsl::test(max!= expected_max, &str1);
let str2 = format!("minmax min ({} observed vs {} expected)", min, expected_min);
gsl::test(min!= expected_min, &str2);
let str3 = format!("minmax index max ({} observed vs {} expected)",
max_index,
expected_max_index);
gsl::test(max_index!= expected_max_index, &str3);
let str4 = format!("minmax index min ({} observed vs {} expected)",
min_index,
expected_min_index);
gsl::test(min_index!= expected_min_index, &str4);
}
let mut sorted = slice_a.clone();
sorted.sort();
{
let median = median_from_sorted_data(&sorted);
let expected = 18.0;
gsl::test_rel(median, expected, rel, "median_from_sorted_data(even)");
}
{
let zeroth = quantile_from_sorted_data(&sorted, 0.0);
let expected = 8.0;
gsl::test_rel(zeroth, expected, rel, "quantile_from_sorted_data(0)");
}
{
let top = quantile_from_sorted_data(&sorted, 1.0);
let expected = 22.0;
gsl::test_rel(top, expected, rel, "quantile_from_sorted_data(100)");
}
{
let median = quantile_from_sorted_data(&sorted, 0.5);
let expected = 18.0;
gsl::test_rel(median, expected, rel, "quantile_from_sorted_data(50, even)");
}
}
|
test_i32_slice
|
identifier_name
|
int_test.rs
|
// int_test.rs
//
// Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Jim Davies, Brian Gough
// Copyright (C) 2016 G.vd.Schoot
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or (at
// your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
//
mod gsl;
|
#[test]
fn test_i32_slice() {
// sample sets of integers
let slice_1 = &[1, 2, 3, 4, 5, 6];
let slice_a = &[17, 18, 16, 18, 12, 20, 18, 20, 20, 22, 20, 10, 8, 12, 16, 16, 18, 20, 18, 21];
let slice_b = &[19, 20, 22, 24, 10, 25, 20, 22, 21, 23, 20, 10, 12, 14, 12, 20, 22, 24, 23, 17];
let rel = 1.0e-10;
{
let mean = mean(slice_a);
let expected = 17.0;
gsl::test_rel(mean, expected, rel, "mean(integer)");
}
{
let mean = mean(slice_1);
let expected = 3.5;
gsl::test_rel(mean, expected, rel, "mean(fractional)");
}
{
let mean = mean(slice_a);
let variance = variance_with_fixed_mean(slice_a, mean);
let expected = 13.7;
gsl::test_rel(variance, expected, rel, "variance_with_fixed_mean");
}
{
let mean = mean(slice_a);
let sd = sd_with_fixed_mean(slice_a, mean);
let expected = 3.70135110466435;
gsl::test_rel(sd, expected, rel, "sd_with_fixed_mean");
}
{
let variance = variance(slice_a);
let expected = 14.4210526315789;
gsl::test_rel(variance, expected, rel, "variance");
}
{
let sd_est = sd(slice_a);
let expected = 3.79750610685209;
gsl::test_rel(sd_est, expected, rel, "sd");
}
{
let absdev = absdev(slice_a);
let expected = 2.9;
gsl::test_rel(absdev, expected, rel, "absdev");
}
{
let skew = skew(slice_a);
let expected = -0.909355923168064;
gsl::test_rel(skew, expected, rel, "skew");
}
{
let kurt = kurtosis(slice_a);
let expected = -0.233692524908094;
gsl::test_rel(kurt, expected, rel, "kurtosis");
}
{
let c = covariance(slice_a, slice_b);
let expected = 14.5263157894737;
gsl::test_rel(c, expected, rel, "covariance");
}
{
let r = correlation(slice_a, slice_b);
let expected = 0.793090350710101;
gsl::test_rel(r, expected, rel, "correlation");
}
{
let pv = p_variance(slice_a, slice_b);
let expected = 18.8421052631579;
gsl::test_rel(pv, expected, rel, "p_variance");
}
{
let t = t_test(slice_a, slice_b);
let expected = -1.45701922702927;
gsl::test_rel(t, expected, rel, "t_test");
}
{
let (maxf, max_index) = max(slice_a);
let max = maxf as i64;
let expected = 22i64;
let expected_index = 9;
let str1 = format!("max ({} observed vs {} expected)", max, expected);
gsl::test(max!= expected, &str1);
let str2 = format!("max index ({} observed vs {} expected)",
max_index,
expected_index);
gsl::test(max_index!= expected_index, &str2);
}
{
let (minf, min_index) = min(slice_a);
let min = minf as i32;
let expected = 8;
let expected_index = 12;
let str1 = format!("min ({} observed vs {} expected)", min, expected);
gsl::test(min!= expected, &str1);
let str2 = format!("min index ({} observed vs {} expected)",
min_index,
expected_index);
gsl::test(min_index!= expected_index, &str2);
}
{
let (minf, min_index, maxf, max_index) = minmax(slice_a);
let min = minf as i32;
let max = maxf as i32;
let expected_max = 22;
let expected_min = 8;
let expected_max_index = 9;
let expected_min_index = 12;
let str1 = format!("minmax max ({} observed vs {} expected)", max, expected_max);
gsl::test(max!= expected_max, &str1);
let str2 = format!("minmax min ({} observed vs {} expected)", min, expected_min);
gsl::test(min!= expected_min, &str2);
let str3 = format!("minmax index max ({} observed vs {} expected)",
max_index,
expected_max_index);
gsl::test(max_index!= expected_max_index, &str3);
let str4 = format!("minmax index min ({} observed vs {} expected)",
min_index,
expected_min_index);
gsl::test(min_index!= expected_min_index, &str4);
}
let mut sorted = slice_a.clone();
sorted.sort();
{
let median = median_from_sorted_data(&sorted);
let expected = 18.0;
gsl::test_rel(median, expected, rel, "median_from_sorted_data(even)");
}
{
let zeroth = quantile_from_sorted_data(&sorted, 0.0);
let expected = 8.0;
gsl::test_rel(zeroth, expected, rel, "quantile_from_sorted_data(0)");
}
{
let top = quantile_from_sorted_data(&sorted, 1.0);
let expected = 22.0;
gsl::test_rel(top, expected, rel, "quantile_from_sorted_data(100)");
}
{
let median = quantile_from_sorted_data(&sorted, 0.5);
let expected = 18.0;
gsl::test_rel(median, expected, rel, "quantile_from_sorted_data(50, even)");
}
}
|
extern crate stat;
use stat::*;
|
random_line_split
|
auth.rs
|
// Copyright 2017 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
use super::{AppExchangeInfo, ContainerPermissions, containers_from_repr_c, containers_into_vec};
use ffi::ipc::req as ffi;
use ffi_utils::{ReprC, StringError, vec_into_raw_parts};
use ipc::errors::IpcError;
use std::collections::HashMap;
/// Represents an authorization request
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AuthReq {
/// The application identifier for this request
pub app: AppExchangeInfo,
/// `true` if the app wants dedicated container for itself. `false`
/// otherwise.
pub app_container: bool,
/// The list of containers it wishes to access (and desired permissions).
pub containers: HashMap<String, ContainerPermissions>,
}
impl AuthReq {
/// Consumes the object and returns the FFI counterpart.
///
/// You're now responsible for freeing the subobjects memory once you're
/// done.
pub fn into_repr_c(self) -> Result<ffi::AuthReq, IpcError>
|
}
impl ReprC for AuthReq {
type C = *const ffi::AuthReq;
type Error = IpcError;
/// Constructs the object from the FFI counterpart.
///
/// After calling this function, the subobjects memory is owned by the
/// resulting object.
unsafe fn clone_from_repr_c(repr_c: *const ffi::AuthReq) -> Result<Self, IpcError> {
Ok(AuthReq {
app: AppExchangeInfo::clone_from_repr_c(&(*repr_c).app)?,
app_container: (*repr_c).app_container,
containers: containers_from_repr_c((*repr_c).containers, (*repr_c).containers_len)?,
})
}
}
|
{
let AuthReq {
app,
app_container,
containers,
} = self;
let containers = containers_into_vec(containers).map_err(StringError::from)?;
let (containers_ptr, containers_len, containers_cap) = vec_into_raw_parts(containers);
Ok(ffi::AuthReq {
app: app.into_repr_c()?,
app_container,
containers: containers_ptr,
containers_len,
containers_cap,
})
}
|
identifier_body
|
auth.rs
|
// Copyright 2017 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
use super::{AppExchangeInfo, ContainerPermissions, containers_from_repr_c, containers_into_vec};
|
/// Represents an authorization request
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AuthReq {
/// The application identifier for this request
pub app: AppExchangeInfo,
/// `true` if the app wants dedicated container for itself. `false`
/// otherwise.
pub app_container: bool,
/// The list of containers it wishes to access (and desired permissions).
pub containers: HashMap<String, ContainerPermissions>,
}
impl AuthReq {
/// Consumes the object and returns the FFI counterpart.
///
/// You're now responsible for freeing the subobjects memory once you're
/// done.
pub fn into_repr_c(self) -> Result<ffi::AuthReq, IpcError> {
let AuthReq {
app,
app_container,
containers,
} = self;
let containers = containers_into_vec(containers).map_err(StringError::from)?;
let (containers_ptr, containers_len, containers_cap) = vec_into_raw_parts(containers);
Ok(ffi::AuthReq {
app: app.into_repr_c()?,
app_container,
containers: containers_ptr,
containers_len,
containers_cap,
})
}
}
impl ReprC for AuthReq {
type C = *const ffi::AuthReq;
type Error = IpcError;
/// Constructs the object from the FFI counterpart.
///
/// After calling this function, the subobjects memory is owned by the
/// resulting object.
unsafe fn clone_from_repr_c(repr_c: *const ffi::AuthReq) -> Result<Self, IpcError> {
Ok(AuthReq {
app: AppExchangeInfo::clone_from_repr_c(&(*repr_c).app)?,
app_container: (*repr_c).app_container,
containers: containers_from_repr_c((*repr_c).containers, (*repr_c).containers_len)?,
})
}
}
|
use ffi::ipc::req as ffi;
use ffi_utils::{ReprC, StringError, vec_into_raw_parts};
use ipc::errors::IpcError;
use std::collections::HashMap;
|
random_line_split
|
auth.rs
|
// Copyright 2017 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By contributing code to the SAFE Network Software, or to this project generally, you agree to be
// bound by the terms of the MaidSafe Contributor Agreement. This, along with the Licenses can be
// found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR.
//
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.
//
// Please review the Licences for the specific language governing permissions and limitations
// relating to use of the SAFE Network Software.
use super::{AppExchangeInfo, ContainerPermissions, containers_from_repr_c, containers_into_vec};
use ffi::ipc::req as ffi;
use ffi_utils::{ReprC, StringError, vec_into_raw_parts};
use ipc::errors::IpcError;
use std::collections::HashMap;
/// Represents an authorization request
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct
|
{
/// The application identifier for this request
pub app: AppExchangeInfo,
/// `true` if the app wants dedicated container for itself. `false`
/// otherwise.
pub app_container: bool,
/// The list of containers it wishes to access (and desired permissions).
pub containers: HashMap<String, ContainerPermissions>,
}
impl AuthReq {
/// Consumes the object and returns the FFI counterpart.
///
/// You're now responsible for freeing the subobjects memory once you're
/// done.
pub fn into_repr_c(self) -> Result<ffi::AuthReq, IpcError> {
let AuthReq {
app,
app_container,
containers,
} = self;
let containers = containers_into_vec(containers).map_err(StringError::from)?;
let (containers_ptr, containers_len, containers_cap) = vec_into_raw_parts(containers);
Ok(ffi::AuthReq {
app: app.into_repr_c()?,
app_container,
containers: containers_ptr,
containers_len,
containers_cap,
})
}
}
impl ReprC for AuthReq {
type C = *const ffi::AuthReq;
type Error = IpcError;
/// Constructs the object from the FFI counterpart.
///
/// After calling this function, the subobjects memory is owned by the
/// resulting object.
unsafe fn clone_from_repr_c(repr_c: *const ffi::AuthReq) -> Result<Self, IpcError> {
Ok(AuthReq {
app: AppExchangeInfo::clone_from_repr_c(&(*repr_c).app)?,
app_container: (*repr_c).app_container,
containers: containers_from_repr_c((*repr_c).containers, (*repr_c).containers_len)?,
})
}
}
|
AuthReq
|
identifier_name
|
mod.rs
|
pub mod pic;
pub mod pit;
pub mod port_io;
use driver::vga;
use core::fmt::Write;
use driver::vga::Writer;
pub fn pic_init() {
unsafe {
//start the initialisation of the PICs
port_io::outb(pic::PIC_MASTER_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4);
port_io::wait();
port_io::outb(pic::PIC_SLAVE_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4);
port_io::wait();
//provide the PIC vector offsets
port_io::outb(pic::PIC_MASTER_DATA, pic::PIC_OFFSET_MASTER);
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, pic::PIC_OFFSET_SLAVE);
port_io::wait();
|
port_io::wait();
//provide additional environment information
port_io::outb(pic::PIC_MASTER_DATA, pic::ICW4_8086); //operate in 8086 mode
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, pic::ICW4_8086); //operate in 8086 mode
port_io::wait();
//mask all interrupts, since none are currently initialised
port_io::outb(pic::PIC_MASTER_DATA, 0xFF);
port_io::outb(pic::PIC_SLAVE_DATA, 0xFF);
pic::irq_set_mask(0, false);
pic::irq_set_mask(1, false);
}
vga::okay();
vga::println("Initialised the PIC, at an offset of 0x20");
}
pub fn pit_init(hz: u32) {
pit::set_phase(hz);
vga::okay();
write!(Writer::new(), "Initialised the PIT, at a phase of {:#} Hz\n", hz)
.expect("Unexpected failure in write!()");
}
|
//provide slave/master relationship information
port_io::outb(pic::PIC_MASTER_DATA, 4); //inform MASTER there is a SLAVE at IRQ2
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, 2); //inform SLAVE it is a cascade identity
|
random_line_split
|
mod.rs
|
pub mod pic;
pub mod pit;
pub mod port_io;
use driver::vga;
use core::fmt::Write;
use driver::vga::Writer;
pub fn
|
() {
unsafe {
//start the initialisation of the PICs
port_io::outb(pic::PIC_MASTER_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4);
port_io::wait();
port_io::outb(pic::PIC_SLAVE_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4);
port_io::wait();
//provide the PIC vector offsets
port_io::outb(pic::PIC_MASTER_DATA, pic::PIC_OFFSET_MASTER);
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, pic::PIC_OFFSET_SLAVE);
port_io::wait();
//provide slave/master relationship information
port_io::outb(pic::PIC_MASTER_DATA, 4); //inform MASTER there is a SLAVE at IRQ2
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, 2); //inform SLAVE it is a cascade identity
port_io::wait();
//provide additional environment information
port_io::outb(pic::PIC_MASTER_DATA, pic::ICW4_8086); //operate in 8086 mode
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, pic::ICW4_8086); //operate in 8086 mode
port_io::wait();
//mask all interrupts, since none are currently initialised
port_io::outb(pic::PIC_MASTER_DATA, 0xFF);
port_io::outb(pic::PIC_SLAVE_DATA, 0xFF);
pic::irq_set_mask(0, false);
pic::irq_set_mask(1, false);
}
vga::okay();
vga::println("Initialised the PIC, at an offset of 0x20");
}
pub fn pit_init(hz: u32) {
pit::set_phase(hz);
vga::okay();
write!(Writer::new(), "Initialised the PIT, at a phase of {:#} Hz\n", hz)
.expect("Unexpected failure in write!()");
}
|
pic_init
|
identifier_name
|
mod.rs
|
pub mod pic;
pub mod pit;
pub mod port_io;
use driver::vga;
use core::fmt::Write;
use driver::vga::Writer;
pub fn pic_init() {
unsafe {
//start the initialisation of the PICs
port_io::outb(pic::PIC_MASTER_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4);
port_io::wait();
port_io::outb(pic::PIC_SLAVE_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4);
port_io::wait();
//provide the PIC vector offsets
port_io::outb(pic::PIC_MASTER_DATA, pic::PIC_OFFSET_MASTER);
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, pic::PIC_OFFSET_SLAVE);
port_io::wait();
//provide slave/master relationship information
port_io::outb(pic::PIC_MASTER_DATA, 4); //inform MASTER there is a SLAVE at IRQ2
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, 2); //inform SLAVE it is a cascade identity
port_io::wait();
//provide additional environment information
port_io::outb(pic::PIC_MASTER_DATA, pic::ICW4_8086); //operate in 8086 mode
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, pic::ICW4_8086); //operate in 8086 mode
port_io::wait();
//mask all interrupts, since none are currently initialised
port_io::outb(pic::PIC_MASTER_DATA, 0xFF);
port_io::outb(pic::PIC_SLAVE_DATA, 0xFF);
pic::irq_set_mask(0, false);
pic::irq_set_mask(1, false);
}
vga::okay();
vga::println("Initialised the PIC, at an offset of 0x20");
}
pub fn pit_init(hz: u32)
|
{
pit::set_phase(hz);
vga::okay();
write!(Writer::new(), "Initialised the PIT, at a phase of {:#} Hz\n", hz)
.expect("Unexpected failure in write!()");
}
|
identifier_body
|
|
server.rs
|
#![feature(core)]
#![feature(path_ext)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use std::fs::PathExt;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::static_server;
#[allow(dead_code)]
fn main()
|
return;
}
// parse static file server address
let default_addr = SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file server address.\nDefaulting to {:?}",default_addr);
default_addr
}
}
},
None => default_addr,
};
// parse the saves directory
let default_saves_dir = "../saves/".to_owned();
let saves_dir = match matches.opt_str("s") {
Some(saves_dir) => saves_dir,
None => default_saves_dir,
};
let absolute_saves_dir = env::current_dir().unwrap().join(saves_dir).canonicalize().unwrap();
thread::spawn(move || static_server::run(addr.clone()));
server::run(absolute_saves_dir.as_path());
}
|
{
// handle command line arguments
let args: Vec<String> = env::args().collect();
// define the command line arguments
let mut opts = Options::new();
opts.optopt("f", "file-server-address", "specify a socket address for the static file server. Defaults to 0.0.0.0:8080","SOCKET ADDRESS");
opts.optopt("s", "saves", "specify the location of the saves directory","PATH");
opts.optflag("h", "help", "prints all options and usage");
// parse raw input arguments into options
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
// print the help menu
if matches.opt_present("h") {
print!("{}", opts.usage(""));
|
identifier_body
|
server.rs
|
#![feature(core)]
#![feature(path_ext)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use std::fs::PathExt;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::static_server;
#[allow(dead_code)]
fn
|
() {
// handle command line arguments
let args: Vec<String> = env::args().collect();
// define the command line arguments
let mut opts = Options::new();
opts.optopt("f", "file-server-address", "specify a socket address for the static file server. Defaults to 0.0.0.0:8080","SOCKET ADDRESS");
opts.optopt("s", "saves", "specify the location of the saves directory","PATH");
opts.optflag("h", "help", "prints all options and usage");
// parse raw input arguments into options
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
// print the help menu
if matches.opt_present("h") {
print!("{}", opts.usage(""));
return;
}
// parse static file server address
let default_addr = SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file server address.\nDefaulting to {:?}",default_addr);
default_addr
}
}
},
None => default_addr,
};
// parse the saves directory
let default_saves_dir = "../saves/".to_owned();
let saves_dir = match matches.opt_str("s") {
Some(saves_dir) => saves_dir,
None => default_saves_dir,
};
let absolute_saves_dir = env::current_dir().unwrap().join(saves_dir).canonicalize().unwrap();
thread::spawn(move || static_server::run(addr.clone()));
server::run(absolute_saves_dir.as_path());
}
|
main
|
identifier_name
|
server.rs
|
#![feature(core)]
#![feature(path_ext)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use std::fs::PathExt;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::static_server;
#[allow(dead_code)]
fn main() {
// handle command line arguments
let args: Vec<String> = env::args().collect();
// define the command line arguments
let mut opts = Options::new();
opts.optopt("f", "file-server-address", "specify a socket address for the static file server. Defaults to 0.0.0.0:8080","SOCKET ADDRESS");
opts.optopt("s", "saves", "specify the location of the saves directory","PATH");
opts.optflag("h", "help", "prints all options and usage");
// parse raw input arguments into options
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
// print the help menu
if matches.opt_present("h") {
|
// parse static file server address
let default_addr = SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file server address.\nDefaulting to {:?}",default_addr);
default_addr
}
}
},
None => default_addr,
};
// parse the saves directory
let default_saves_dir = "../saves/".to_owned();
let saves_dir = match matches.opt_str("s") {
Some(saves_dir) => saves_dir,
None => default_saves_dir,
};
let absolute_saves_dir = env::current_dir().unwrap().join(saves_dir).canonicalize().unwrap();
thread::spawn(move || static_server::run(addr.clone()));
server::run(absolute_saves_dir.as_path());
}
|
print!("{}", opts.usage(""));
return;
}
|
random_line_split
|
server.rs
|
#![feature(core)]
#![feature(path_ext)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use std::fs::PathExt;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::static_server;
#[allow(dead_code)]
fn main() {
// handle command line arguments
let args: Vec<String> = env::args().collect();
// define the command line arguments
let mut opts = Options::new();
opts.optopt("f", "file-server-address", "specify a socket address for the static file server. Defaults to 0.0.0.0:8080","SOCKET ADDRESS");
opts.optopt("s", "saves", "specify the location of the saves directory","PATH");
opts.optflag("h", "help", "prints all options and usage");
// parse raw input arguments into options
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
// print the help menu
if matches.opt_present("h")
|
// parse static file server address
let default_addr = SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file server address.\nDefaulting to {:?}",default_addr);
default_addr
}
}
},
None => default_addr,
};
// parse the saves directory
let default_saves_dir = "../saves/".to_owned();
let saves_dir = match matches.opt_str("s") {
Some(saves_dir) => saves_dir,
None => default_saves_dir,
};
let absolute_saves_dir = env::current_dir().unwrap().join(saves_dir).canonicalize().unwrap();
thread::spawn(move || static_server::run(addr.clone()));
server::run(absolute_saves_dir.as_path());
}
|
{
print!("{}", opts.usage(""));
return;
}
|
conditional_block
|
lib.rs
|
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
#[allow(unused_extern_crates)]
extern crate tikv_alloc;
mod client;
mod feature_gate;
pub mod metrics;
mod util;
mod config;
pub mod errors;
pub use self::client::{DummyPdClient, RpcClient};
pub use self::config::Config;
pub use self::errors::{Error, Result};
pub use self::feature_gate::{Feature, FeatureGate};
pub use self::util::PdConnector;
pub use self::util::REQUEST_RECONNECT_INTERVAL;
use std::ops::Deref;
use futures::future::BoxFuture;
use kvproto::metapb;
use kvproto::pdpb;
use kvproto::replication_modepb::{RegionReplicationStatus, ReplicationStatus};
use tikv_util::time::UnixSecs;
use txn_types::TimeStamp;
pub type Key = Vec<u8>;
pub type PdFuture<T> = BoxFuture<'static, Result<T>>;
#[derive(Default, Clone)]
pub struct RegionStat {
pub down_peers: Vec<pdpb::PeerStats>,
pub pending_peers: Vec<metapb::Peer>,
pub written_bytes: u64,
pub written_keys: u64,
pub read_bytes: u64,
pub read_keys: u64,
pub approximate_size: u64,
pub approximate_keys: u64,
pub last_report_ts: UnixSecs,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RegionInfo {
pub region: metapb::Region,
pub leader: Option<metapb::Peer>,
}
impl RegionInfo {
pub fn new(region: metapb::Region, leader: Option<metapb::Peer>) -> RegionInfo {
RegionInfo { region, leader }
}
}
impl Deref for RegionInfo {
type Target = metapb::Region;
fn deref(&self) -> &Self::Target {
&self.region
}
}
pub const INVALID_ID: u64 = 0;
/// PdClient communicates with Placement Driver (PD).
/// Because now one PD only supports one cluster, so it is no need to pass
/// cluster id in trait interface every time, so passing the cluster id when
/// creating the PdClient is enough and the PdClient will use this cluster id
/// all the time.
pub trait PdClient: Send + Sync {
/// Returns the cluster ID.
fn get_cluster_id(&self) -> Result<u64> {
unimplemented!();
}
/// Creates the cluster with cluster ID, node, stores and first Region.
/// If the cluster is already bootstrapped, return ClusterBootstrapped error.
/// When a node starts, if it finds nothing in the node and
/// cluster is not bootstrapped, it begins to create node, stores, first Region
/// and then call bootstrap_cluster to let PD know it.
/// It may happen that multi nodes start at same time to try to
/// bootstrap, but only one can succeed, while others will fail
/// and must remove their created local Region data themselves.
fn bootstrap_cluster(
&self,
_stores: metapb::Store,
_region: metapb::Region,
) -> Result<Option<ReplicationStatus>> {
unimplemented!();
}
/// Returns whether the cluster is bootstrapped or not.
///
/// Cluster must be bootstrapped when we use it, so when the
/// node starts, `is_cluster_bootstrapped` must be called,
/// and panics if cluster was not bootstrapped.
fn is_cluster_bootstrapped(&self) -> Result<bool> {
unimplemented!();
}
/// Allocates a unique positive id.
fn alloc_id(&self) -> Result<u64> {
unimplemented!();
}
/// Informs PD when the store starts or some store information changes.
fn put_store(&self, _store: metapb::Store) -> Result<Option<ReplicationStatus>> {
unimplemented!();
}
/// We don't need to support Region and Peer put/delete,
/// because PD knows all Region and Peers itself:
/// - For bootstrapping, PD knows first Region with `bootstrap_cluster`.
/// - For changing Peer, PD determines where to add a new Peer in some store
/// for this Region.
/// - For Region splitting, PD determines the new Region id and Peer id for the
/// split Region.
/// - For Region merging, PD knows which two Regions will be merged and which Region
/// and Peers will be removed.
/// - For auto-balance, PD determines how to move the Region from one store to another.
/// Gets store information if it is not a tombstone store.
fn get_store(&self, _store_id: u64) -> Result<metapb::Store> {
unimplemented!();
}
/// Gets store information if it is not a tombstone store asynchronously
fn get_store_async(&self, _store_id: u64) -> PdFuture<metapb::Store> {
unimplemented!();
}
/// Gets all stores information.
fn get_all_stores(&self, _exclude_tombstone: bool) -> Result<Vec<metapb::Store>> {
unimplemented!();
}
/// Gets cluster meta information.
fn get_cluster_config(&self) -> Result<metapb::Cluster> {
unimplemented!();
}
/// For route.
/// Gets Region which the key belongs to.
fn get_region(&self, _key: &[u8]) -> Result<metapb::Region> {
unimplemented!();
}
/// Gets Region which the key belongs to asynchronously.
fn get_region_async<'k>(&'k self, _key: &'k [u8]) -> BoxFuture<'k, Result<metapb::Region>> {
unimplemented!();
}
/// Gets Region info which the key belongs to.
fn get_region_info(&self, _key: &[u8]) -> Result<RegionInfo> {
unimplemented!();
}
/// Gets Region info which the key belongs to asynchronously.
fn get_region_info_async<'k>(&'k self, _key: &'k [u8]) -> BoxFuture<'k, Result<RegionInfo>>
|
/// Gets Region by Region id.
fn get_region_by_id(&self, _region_id: u64) -> PdFuture<Option<metapb::Region>> {
unimplemented!();
}
/// Gets Region and its leader by Region id.
fn get_region_leader_by_id(
&self,
_region_id: u64,
) -> PdFuture<Option<(metapb::Region, metapb::Peer)>> {
unimplemented!();
}
/// Region's Leader uses this to heartbeat PD.
fn region_heartbeat(
&self,
_term: u64,
_region: metapb::Region,
_leader: metapb::Peer,
_region_stat: RegionStat,
_replication_status: Option<RegionReplicationStatus>,
) -> PdFuture<()> {
unimplemented!();
}
/// Gets a stream of Region heartbeat response.
///
/// Please note that this method should only be called once.
fn handle_region_heartbeat_response<F>(&self, _store_id: u64, _f: F) -> PdFuture<()>
where
Self: Sized,
F: Fn(pdpb::RegionHeartbeatResponse) + Send +'static,
{
unimplemented!();
}
/// Asks PD for split. PD returns the newly split Region id.
fn ask_split(&self, _region: metapb::Region) -> PdFuture<pdpb::AskSplitResponse> {
unimplemented!();
}
/// Asks PD for batch split. PD returns the newly split Region ids.
fn ask_batch_split(
&self,
_region: metapb::Region,
_count: usize,
) -> PdFuture<pdpb::AskBatchSplitResponse> {
unimplemented!();
}
/// Sends store statistics regularly.
fn store_heartbeat(&self, _stats: pdpb::StoreStats) -> PdFuture<pdpb::StoreHeartbeatResponse> {
unimplemented!();
}
/// Reports PD the split Region.
fn report_batch_split(&self, _regions: Vec<metapb::Region>) -> PdFuture<()> {
unimplemented!();
}
/// Scatters the Region across the cluster.
fn scatter_region(&self, _: RegionInfo) -> Result<()> {
unimplemented!();
}
/// Registers a handler to the client, which will be invoked after reconnecting to PD.
///
/// Please note that this method should only be called once.
fn handle_reconnect<F: Fn() + Sync + Send +'static>(&self, _: F)
where
Self: Sized,
{
}
fn get_gc_safe_point(&self) -> PdFuture<u64> {
unimplemented!();
}
/// Gets store state if it is not a tombstone store asynchronously.
fn get_store_stats_async(&self, _store_id: u64) -> BoxFuture<'_, Result<pdpb::StoreStats>> {
unimplemented!();
}
/// Gets current operator of the region
fn get_operator(&self, _region_id: u64) -> Result<pdpb::GetOperatorResponse> {
unimplemented!();
}
/// Gets a timestamp from PD.
fn get_tso(&self) -> PdFuture<TimeStamp> {
unimplemented!()
}
/// Gets the internal `FeatureGate`.
fn feature_gate(&self) -> &FeatureGate {
unimplemented!()
}
}
const REQUEST_TIMEOUT: u64 = 2; // 2s
/// Takes the peer address (for sending raft messages) from a store.
pub fn take_peer_address(store: &mut metapb::Store) -> String {
if!store.get_peer_address().is_empty() {
store.take_peer_address()
} else {
store.take_address()
}
}
|
{
unimplemented!();
}
|
identifier_body
|
lib.rs
|
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
#[allow(unused_extern_crates)]
extern crate tikv_alloc;
mod client;
mod feature_gate;
pub mod metrics;
mod util;
mod config;
pub mod errors;
pub use self::client::{DummyPdClient, RpcClient};
pub use self::config::Config;
pub use self::errors::{Error, Result};
pub use self::feature_gate::{Feature, FeatureGate};
pub use self::util::PdConnector;
pub use self::util::REQUEST_RECONNECT_INTERVAL;
use std::ops::Deref;
use futures::future::BoxFuture;
use kvproto::metapb;
use kvproto::pdpb;
use kvproto::replication_modepb::{RegionReplicationStatus, ReplicationStatus};
use tikv_util::time::UnixSecs;
use txn_types::TimeStamp;
pub type Key = Vec<u8>;
pub type PdFuture<T> = BoxFuture<'static, Result<T>>;
#[derive(Default, Clone)]
pub struct RegionStat {
pub down_peers: Vec<pdpb::PeerStats>,
pub pending_peers: Vec<metapb::Peer>,
pub written_bytes: u64,
pub written_keys: u64,
pub read_bytes: u64,
pub read_keys: u64,
pub approximate_size: u64,
pub approximate_keys: u64,
pub last_report_ts: UnixSecs,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RegionInfo {
pub region: metapb::Region,
pub leader: Option<metapb::Peer>,
}
impl RegionInfo {
pub fn new(region: metapb::Region, leader: Option<metapb::Peer>) -> RegionInfo {
RegionInfo { region, leader }
}
}
impl Deref for RegionInfo {
type Target = metapb::Region;
fn deref(&self) -> &Self::Target {
&self.region
}
}
pub const INVALID_ID: u64 = 0;
/// PdClient communicates with Placement Driver (PD).
/// Because now one PD only supports one cluster, so it is no need to pass
/// cluster id in trait interface every time, so passing the cluster id when
/// creating the PdClient is enough and the PdClient will use this cluster id
/// all the time.
pub trait PdClient: Send + Sync {
/// Returns the cluster ID.
fn get_cluster_id(&self) -> Result<u64> {
unimplemented!();
}
/// Creates the cluster with cluster ID, node, stores and first Region.
/// If the cluster is already bootstrapped, return ClusterBootstrapped error.
/// When a node starts, if it finds nothing in the node and
/// cluster is not bootstrapped, it begins to create node, stores, first Region
/// and then call bootstrap_cluster to let PD know it.
/// It may happen that multi nodes start at same time to try to
/// bootstrap, but only one can succeed, while others will fail
/// and must remove their created local Region data themselves.
fn bootstrap_cluster(
&self,
_stores: metapb::Store,
_region: metapb::Region,
) -> Result<Option<ReplicationStatus>> {
unimplemented!();
}
/// Returns whether the cluster is bootstrapped or not.
///
/// Cluster must be bootstrapped when we use it, so when the
/// node starts, `is_cluster_bootstrapped` must be called,
/// and panics if cluster was not bootstrapped.
fn is_cluster_bootstrapped(&self) -> Result<bool> {
unimplemented!();
}
/// Allocates a unique positive id.
fn alloc_id(&self) -> Result<u64> {
unimplemented!();
}
/// Informs PD when the store starts or some store information changes.
fn put_store(&self, _store: metapb::Store) -> Result<Option<ReplicationStatus>> {
unimplemented!();
}
/// We don't need to support Region and Peer put/delete,
/// because PD knows all Region and Peers itself:
/// - For bootstrapping, PD knows first Region with `bootstrap_cluster`.
/// - For changing Peer, PD determines where to add a new Peer in some store
/// for this Region.
/// - For Region splitting, PD determines the new Region id and Peer id for the
/// split Region.
/// - For Region merging, PD knows which two Regions will be merged and which Region
/// and Peers will be removed.
/// - For auto-balance, PD determines how to move the Region from one store to another.
/// Gets store information if it is not a tombstone store.
fn get_store(&self, _store_id: u64) -> Result<metapb::Store> {
unimplemented!();
}
/// Gets store information if it is not a tombstone store asynchronously
fn get_store_async(&self, _store_id: u64) -> PdFuture<metapb::Store> {
unimplemented!();
}
/// Gets all stores information.
fn get_all_stores(&self, _exclude_tombstone: bool) -> Result<Vec<metapb::Store>> {
unimplemented!();
}
/// Gets cluster meta information.
fn get_cluster_config(&self) -> Result<metapb::Cluster> {
unimplemented!();
}
/// For route.
/// Gets Region which the key belongs to.
fn get_region(&self, _key: &[u8]) -> Result<metapb::Region> {
unimplemented!();
}
/// Gets Region which the key belongs to asynchronously.
fn get_region_async<'k>(&'k self, _key: &'k [u8]) -> BoxFuture<'k, Result<metapb::Region>> {
unimplemented!();
}
/// Gets Region info which the key belongs to.
fn get_region_info(&self, _key: &[u8]) -> Result<RegionInfo> {
unimplemented!();
}
/// Gets Region info which the key belongs to asynchronously.
fn get_region_info_async<'k>(&'k self, _key: &'k [u8]) -> BoxFuture<'k, Result<RegionInfo>> {
unimplemented!();
}
/// Gets Region by Region id.
fn get_region_by_id(&self, _region_id: u64) -> PdFuture<Option<metapb::Region>> {
unimplemented!();
}
/// Gets Region and its leader by Region id.
fn get_region_leader_by_id(
&self,
_region_id: u64,
) -> PdFuture<Option<(metapb::Region, metapb::Peer)>> {
unimplemented!();
}
/// Region's Leader uses this to heartbeat PD.
fn region_heartbeat(
&self,
_term: u64,
_region: metapb::Region,
_leader: metapb::Peer,
_region_stat: RegionStat,
_replication_status: Option<RegionReplicationStatus>,
) -> PdFuture<()> {
unimplemented!();
}
/// Gets a stream of Region heartbeat response.
///
/// Please note that this method should only be called once.
fn handle_region_heartbeat_response<F>(&self, _store_id: u64, _f: F) -> PdFuture<()>
where
Self: Sized,
F: Fn(pdpb::RegionHeartbeatResponse) + Send +'static,
{
unimplemented!();
}
/// Asks PD for split. PD returns the newly split Region id.
fn ask_split(&self, _region: metapb::Region) -> PdFuture<pdpb::AskSplitResponse> {
unimplemented!();
}
/// Asks PD for batch split. PD returns the newly split Region ids.
fn ask_batch_split(
&self,
_region: metapb::Region,
_count: usize,
) -> PdFuture<pdpb::AskBatchSplitResponse> {
unimplemented!();
}
/// Sends store statistics regularly.
fn store_heartbeat(&self, _stats: pdpb::StoreStats) -> PdFuture<pdpb::StoreHeartbeatResponse> {
unimplemented!();
}
/// Reports PD the split Region.
fn report_batch_split(&self, _regions: Vec<metapb::Region>) -> PdFuture<()> {
unimplemented!();
}
/// Scatters the Region across the cluster.
fn scatter_region(&self, _: RegionInfo) -> Result<()> {
unimplemented!();
}
/// Registers a handler to the client, which will be invoked after reconnecting to PD.
///
/// Please note that this method should only be called once.
fn handle_reconnect<F: Fn() + Sync + Send +'static>(&self, _: F)
where
Self: Sized,
{
}
fn get_gc_safe_point(&self) -> PdFuture<u64> {
unimplemented!();
}
/// Gets store state if it is not a tombstone store asynchronously.
fn get_store_stats_async(&self, _store_id: u64) -> BoxFuture<'_, Result<pdpb::StoreStats>> {
unimplemented!();
}
/// Gets current operator of the region
fn get_operator(&self, _region_id: u64) -> Result<pdpb::GetOperatorResponse> {
unimplemented!();
}
/// Gets a timestamp from PD.
fn get_tso(&self) -> PdFuture<TimeStamp> {
unimplemented!()
}
/// Gets the internal `FeatureGate`.
fn feature_gate(&self) -> &FeatureGate {
unimplemented!()
}
}
const REQUEST_TIMEOUT: u64 = 2; // 2s
/// Takes the peer address (for sending raft messages) from a store.
pub fn take_peer_address(store: &mut metapb::Store) -> String {
if!store.get_peer_address().is_empty()
|
else {
store.take_address()
}
}
|
{
store.take_peer_address()
}
|
conditional_block
|
lib.rs
|
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
#[allow(unused_extern_crates)]
extern crate tikv_alloc;
mod client;
mod feature_gate;
pub mod metrics;
mod util;
mod config;
pub mod errors;
pub use self::client::{DummyPdClient, RpcClient};
pub use self::config::Config;
pub use self::errors::{Error, Result};
pub use self::feature_gate::{Feature, FeatureGate};
pub use self::util::PdConnector;
pub use self::util::REQUEST_RECONNECT_INTERVAL;
use std::ops::Deref;
use futures::future::BoxFuture;
use kvproto::metapb;
use kvproto::pdpb;
use kvproto::replication_modepb::{RegionReplicationStatus, ReplicationStatus};
use tikv_util::time::UnixSecs;
use txn_types::TimeStamp;
pub type Key = Vec<u8>;
pub type PdFuture<T> = BoxFuture<'static, Result<T>>;
#[derive(Default, Clone)]
pub struct RegionStat {
pub down_peers: Vec<pdpb::PeerStats>,
pub pending_peers: Vec<metapb::Peer>,
pub written_bytes: u64,
pub written_keys: u64,
pub read_bytes: u64,
pub read_keys: u64,
pub approximate_size: u64,
pub approximate_keys: u64,
pub last_report_ts: UnixSecs,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RegionInfo {
pub region: metapb::Region,
pub leader: Option<metapb::Peer>,
}
impl RegionInfo {
pub fn new(region: metapb::Region, leader: Option<metapb::Peer>) -> RegionInfo {
RegionInfo { region, leader }
}
}
impl Deref for RegionInfo {
type Target = metapb::Region;
fn deref(&self) -> &Self::Target {
&self.region
}
}
pub const INVALID_ID: u64 = 0;
/// PdClient communicates with Placement Driver (PD).
/// Because now one PD only supports one cluster, so it is no need to pass
/// cluster id in trait interface every time, so passing the cluster id when
/// creating the PdClient is enough and the PdClient will use this cluster id
/// all the time.
pub trait PdClient: Send + Sync {
/// Returns the cluster ID.
fn get_cluster_id(&self) -> Result<u64> {
unimplemented!();
}
/// Creates the cluster with cluster ID, node, stores and first Region.
/// If the cluster is already bootstrapped, return ClusterBootstrapped error.
/// When a node starts, if it finds nothing in the node and
/// cluster is not bootstrapped, it begins to create node, stores, first Region
/// and then call bootstrap_cluster to let PD know it.
/// It may happen that multi nodes start at same time to try to
/// bootstrap, but only one can succeed, while others will fail
/// and must remove their created local Region data themselves.
fn bootstrap_cluster(
&self,
_stores: metapb::Store,
_region: metapb::Region,
) -> Result<Option<ReplicationStatus>> {
unimplemented!();
}
/// Returns whether the cluster is bootstrapped or not.
///
/// Cluster must be bootstrapped when we use it, so when the
/// node starts, `is_cluster_bootstrapped` must be called,
/// and panics if cluster was not bootstrapped.
fn is_cluster_bootstrapped(&self) -> Result<bool> {
unimplemented!();
}
/// Allocates a unique positive id.
fn alloc_id(&self) -> Result<u64> {
unimplemented!();
}
/// Informs PD when the store starts or some store information changes.
fn put_store(&self, _store: metapb::Store) -> Result<Option<ReplicationStatus>> {
unimplemented!();
}
/// We don't need to support Region and Peer put/delete,
/// because PD knows all Region and Peers itself:
/// - For bootstrapping, PD knows first Region with `bootstrap_cluster`.
/// - For changing Peer, PD determines where to add a new Peer in some store
/// for this Region.
/// - For Region splitting, PD determines the new Region id and Peer id for the
/// split Region.
/// - For Region merging, PD knows which two Regions will be merged and which Region
/// and Peers will be removed.
/// - For auto-balance, PD determines how to move the Region from one store to another.
/// Gets store information if it is not a tombstone store.
fn get_store(&self, _store_id: u64) -> Result<metapb::Store> {
unimplemented!();
}
/// Gets store information if it is not a tombstone store asynchronously
fn get_store_async(&self, _store_id: u64) -> PdFuture<metapb::Store> {
unimplemented!();
}
/// Gets all stores information.
fn get_all_stores(&self, _exclude_tombstone: bool) -> Result<Vec<metapb::Store>> {
unimplemented!();
}
/// Gets cluster meta information.
fn get_cluster_config(&self) -> Result<metapb::Cluster> {
unimplemented!();
}
/// For route.
/// Gets Region which the key belongs to.
fn get_region(&self, _key: &[u8]) -> Result<metapb::Region> {
unimplemented!();
}
/// Gets Region which the key belongs to asynchronously.
fn get_region_async<'k>(&'k self, _key: &'k [u8]) -> BoxFuture<'k, Result<metapb::Region>> {
unimplemented!();
}
/// Gets Region info which the key belongs to.
fn get_region_info(&self, _key: &[u8]) -> Result<RegionInfo> {
unimplemented!();
}
/// Gets Region info which the key belongs to asynchronously.
fn get_region_info_async<'k>(&'k self, _key: &'k [u8]) -> BoxFuture<'k, Result<RegionInfo>> {
unimplemented!();
}
/// Gets Region by Region id.
fn get_region_by_id(&self, _region_id: u64) -> PdFuture<Option<metapb::Region>> {
unimplemented!();
}
/// Gets Region and its leader by Region id.
fn get_region_leader_by_id(
&self,
_region_id: u64,
) -> PdFuture<Option<(metapb::Region, metapb::Peer)>> {
unimplemented!();
}
/// Region's Leader uses this to heartbeat PD.
fn region_heartbeat(
&self,
_term: u64,
_region: metapb::Region,
_leader: metapb::Peer,
_region_stat: RegionStat,
_replication_status: Option<RegionReplicationStatus>,
) -> PdFuture<()> {
unimplemented!();
}
/// Gets a stream of Region heartbeat response.
///
/// Please note that this method should only be called once.
fn handle_region_heartbeat_response<F>(&self, _store_id: u64, _f: F) -> PdFuture<()>
where
Self: Sized,
F: Fn(pdpb::RegionHeartbeatResponse) + Send +'static,
{
unimplemented!();
}
/// Asks PD for split. PD returns the newly split Region id.
fn ask_split(&self, _region: metapb::Region) -> PdFuture<pdpb::AskSplitResponse> {
unimplemented!();
}
/// Asks PD for batch split. PD returns the newly split Region ids.
fn ask_batch_split(
&self,
_region: metapb::Region,
_count: usize,
) -> PdFuture<pdpb::AskBatchSplitResponse> {
unimplemented!();
}
/// Sends store statistics regularly.
fn store_heartbeat(&self, _stats: pdpb::StoreStats) -> PdFuture<pdpb::StoreHeartbeatResponse> {
unimplemented!();
}
/// Reports PD the split Region.
fn report_batch_split(&self, _regions: Vec<metapb::Region>) -> PdFuture<()> {
unimplemented!();
}
/// Scatters the Region across the cluster.
fn scatter_region(&self, _: RegionInfo) -> Result<()> {
unimplemented!();
}
|
/// Registers a handler to the client, which will be invoked after reconnecting to PD.
///
/// Please note that this method should only be called once.
fn handle_reconnect<F: Fn() + Sync + Send +'static>(&self, _: F)
where
Self: Sized,
{
}
fn get_gc_safe_point(&self) -> PdFuture<u64> {
unimplemented!();
}
/// Gets store state if it is not a tombstone store asynchronously.
fn get_store_stats_async(&self, _store_id: u64) -> BoxFuture<'_, Result<pdpb::StoreStats>> {
unimplemented!();
}
/// Gets current operator of the region
fn get_operator(&self, _region_id: u64) -> Result<pdpb::GetOperatorResponse> {
unimplemented!();
}
/// Gets a timestamp from PD.
fn get_tso(&self) -> PdFuture<TimeStamp> {
unimplemented!()
}
/// Gets the internal `FeatureGate`.
fn feature_gate(&self) -> &FeatureGate {
unimplemented!()
}
}
const REQUEST_TIMEOUT: u64 = 2; // 2s
/// Takes the peer address (for sending raft messages) from a store.
pub fn take_peer_address(store: &mut metapb::Store) -> String {
if!store.get_peer_address().is_empty() {
store.take_peer_address()
} else {
store.take_address()
}
}
|
random_line_split
|
|
lib.rs
|
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0.
#[allow(unused_extern_crates)]
extern crate tikv_alloc;
mod client;
mod feature_gate;
pub mod metrics;
mod util;
mod config;
pub mod errors;
pub use self::client::{DummyPdClient, RpcClient};
pub use self::config::Config;
pub use self::errors::{Error, Result};
pub use self::feature_gate::{Feature, FeatureGate};
pub use self::util::PdConnector;
pub use self::util::REQUEST_RECONNECT_INTERVAL;
use std::ops::Deref;
use futures::future::BoxFuture;
use kvproto::metapb;
use kvproto::pdpb;
use kvproto::replication_modepb::{RegionReplicationStatus, ReplicationStatus};
use tikv_util::time::UnixSecs;
use txn_types::TimeStamp;
pub type Key = Vec<u8>;
pub type PdFuture<T> = BoxFuture<'static, Result<T>>;
#[derive(Default, Clone)]
pub struct RegionStat {
pub down_peers: Vec<pdpb::PeerStats>,
pub pending_peers: Vec<metapb::Peer>,
pub written_bytes: u64,
pub written_keys: u64,
pub read_bytes: u64,
pub read_keys: u64,
pub approximate_size: u64,
pub approximate_keys: u64,
pub last_report_ts: UnixSecs,
}
#[derive(Clone, Debug, PartialEq)]
pub struct RegionInfo {
pub region: metapb::Region,
pub leader: Option<metapb::Peer>,
}
impl RegionInfo {
pub fn new(region: metapb::Region, leader: Option<metapb::Peer>) -> RegionInfo {
RegionInfo { region, leader }
}
}
impl Deref for RegionInfo {
type Target = metapb::Region;
fn deref(&self) -> &Self::Target {
&self.region
}
}
pub const INVALID_ID: u64 = 0;
/// PdClient communicates with Placement Driver (PD).
/// Because now one PD only supports one cluster, so it is no need to pass
/// cluster id in trait interface every time, so passing the cluster id when
/// creating the PdClient is enough and the PdClient will use this cluster id
/// all the time.
pub trait PdClient: Send + Sync {
/// Returns the cluster ID.
fn
|
(&self) -> Result<u64> {
unimplemented!();
}
/// Creates the cluster with cluster ID, node, stores and first Region.
/// If the cluster is already bootstrapped, return ClusterBootstrapped error.
/// When a node starts, if it finds nothing in the node and
/// cluster is not bootstrapped, it begins to create node, stores, first Region
/// and then call bootstrap_cluster to let PD know it.
/// It may happen that multi nodes start at same time to try to
/// bootstrap, but only one can succeed, while others will fail
/// and must remove their created local Region data themselves.
fn bootstrap_cluster(
&self,
_stores: metapb::Store,
_region: metapb::Region,
) -> Result<Option<ReplicationStatus>> {
unimplemented!();
}
/// Returns whether the cluster is bootstrapped or not.
///
/// Cluster must be bootstrapped when we use it, so when the
/// node starts, `is_cluster_bootstrapped` must be called,
/// and panics if cluster was not bootstrapped.
fn is_cluster_bootstrapped(&self) -> Result<bool> {
unimplemented!();
}
/// Allocates a unique positive id.
fn alloc_id(&self) -> Result<u64> {
unimplemented!();
}
/// Informs PD when the store starts or some store information changes.
fn put_store(&self, _store: metapb::Store) -> Result<Option<ReplicationStatus>> {
unimplemented!();
}
/// We don't need to support Region and Peer put/delete,
/// because PD knows all Region and Peers itself:
/// - For bootstrapping, PD knows first Region with `bootstrap_cluster`.
/// - For changing Peer, PD determines where to add a new Peer in some store
/// for this Region.
/// - For Region splitting, PD determines the new Region id and Peer id for the
/// split Region.
/// - For Region merging, PD knows which two Regions will be merged and which Region
/// and Peers will be removed.
/// - For auto-balance, PD determines how to move the Region from one store to another.
/// Gets store information if it is not a tombstone store.
fn get_store(&self, _store_id: u64) -> Result<metapb::Store> {
unimplemented!();
}
/// Gets store information if it is not a tombstone store asynchronously
fn get_store_async(&self, _store_id: u64) -> PdFuture<metapb::Store> {
unimplemented!();
}
/// Gets all stores information.
fn get_all_stores(&self, _exclude_tombstone: bool) -> Result<Vec<metapb::Store>> {
unimplemented!();
}
/// Gets cluster meta information.
fn get_cluster_config(&self) -> Result<metapb::Cluster> {
unimplemented!();
}
/// For route.
/// Gets Region which the key belongs to.
fn get_region(&self, _key: &[u8]) -> Result<metapb::Region> {
unimplemented!();
}
/// Gets Region which the key belongs to asynchronously.
fn get_region_async<'k>(&'k self, _key: &'k [u8]) -> BoxFuture<'k, Result<metapb::Region>> {
unimplemented!();
}
/// Gets Region info which the key belongs to.
fn get_region_info(&self, _key: &[u8]) -> Result<RegionInfo> {
unimplemented!();
}
/// Gets Region info which the key belongs to asynchronously.
fn get_region_info_async<'k>(&'k self, _key: &'k [u8]) -> BoxFuture<'k, Result<RegionInfo>> {
unimplemented!();
}
/// Gets Region by Region id.
fn get_region_by_id(&self, _region_id: u64) -> PdFuture<Option<metapb::Region>> {
unimplemented!();
}
/// Gets Region and its leader by Region id.
fn get_region_leader_by_id(
&self,
_region_id: u64,
) -> PdFuture<Option<(metapb::Region, metapb::Peer)>> {
unimplemented!();
}
/// Region's Leader uses this to heartbeat PD.
fn region_heartbeat(
&self,
_term: u64,
_region: metapb::Region,
_leader: metapb::Peer,
_region_stat: RegionStat,
_replication_status: Option<RegionReplicationStatus>,
) -> PdFuture<()> {
unimplemented!();
}
/// Gets a stream of Region heartbeat response.
///
/// Please note that this method should only be called once.
fn handle_region_heartbeat_response<F>(&self, _store_id: u64, _f: F) -> PdFuture<()>
where
Self: Sized,
F: Fn(pdpb::RegionHeartbeatResponse) + Send +'static,
{
unimplemented!();
}
/// Asks PD for split. PD returns the newly split Region id.
fn ask_split(&self, _region: metapb::Region) -> PdFuture<pdpb::AskSplitResponse> {
unimplemented!();
}
/// Asks PD for batch split. PD returns the newly split Region ids.
fn ask_batch_split(
&self,
_region: metapb::Region,
_count: usize,
) -> PdFuture<pdpb::AskBatchSplitResponse> {
unimplemented!();
}
/// Sends store statistics regularly.
fn store_heartbeat(&self, _stats: pdpb::StoreStats) -> PdFuture<pdpb::StoreHeartbeatResponse> {
unimplemented!();
}
/// Reports PD the split Region.
fn report_batch_split(&self, _regions: Vec<metapb::Region>) -> PdFuture<()> {
unimplemented!();
}
/// Scatters the Region across the cluster.
fn scatter_region(&self, _: RegionInfo) -> Result<()> {
unimplemented!();
}
/// Registers a handler to the client, which will be invoked after reconnecting to PD.
///
/// Please note that this method should only be called once.
fn handle_reconnect<F: Fn() + Sync + Send +'static>(&self, _: F)
where
Self: Sized,
{
}
fn get_gc_safe_point(&self) -> PdFuture<u64> {
unimplemented!();
}
/// Gets store state if it is not a tombstone store asynchronously.
fn get_store_stats_async(&self, _store_id: u64) -> BoxFuture<'_, Result<pdpb::StoreStats>> {
unimplemented!();
}
/// Gets current operator of the region
fn get_operator(&self, _region_id: u64) -> Result<pdpb::GetOperatorResponse> {
unimplemented!();
}
/// Gets a timestamp from PD.
fn get_tso(&self) -> PdFuture<TimeStamp> {
unimplemented!()
}
/// Gets the internal `FeatureGate`.
fn feature_gate(&self) -> &FeatureGate {
unimplemented!()
}
}
const REQUEST_TIMEOUT: u64 = 2; // 2s
/// Takes the peer address (for sending raft messages) from a store.
pub fn take_peer_address(store: &mut metapb::Store) -> String {
if!store.get_peer_address().is_empty() {
store.take_peer_address()
} else {
store.take_address()
}
}
|
get_cluster_id
|
identifier_name
|
distinct_on.rs
|
use crate::expression::SelectableExpression;
use crate::pg::Pg;
use crate::query_builder::order_clause::{NoOrderClause, OrderClause};
use crate::query_builder::{AstPass, QueryFragment, QueryId, SelectQuery, SelectStatement};
use crate::query_dsl::methods::DistinctOnDsl;
use crate::query_dsl::order_dsl::ValidOrderingForDistinct;
use crate::result::QueryResult;
use crate::sql_types::SingleValue;
use crate::Expression;
/// Represents `DISTINCT ON (...)`
#[derive(Debug, Clone, Copy, QueryId)]
pub struct DistinctOnClause<T>(pub(crate) T);
impl<T> ValidOrderingForDistinct<DistinctOnClause<T>> for NoOrderClause {}
impl<T> ValidOrderingForDistinct<DistinctOnClause<T>> for OrderClause<(T,)> {}
impl<T> ValidOrderingForDistinct<DistinctOnClause<T>> for OrderClause<T>
where
T: Expression,
T::SqlType: SingleValue,
{
}
impl<T> QueryFragment<Pg> for DistinctOnClause<T>
where
T: QueryFragment<Pg>,
{
fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
out.push_sql("DISTINCT ON (");
|
}
}
impl<ST, F, S, D, W, O, LOf, G, Selection> DistinctOnDsl<Selection>
for SelectStatement<F, S, D, W, O, LOf, G>
where
Selection: SelectableExpression<F>,
Selection::SqlType: SingleValue,
Self: SelectQuery<SqlType = ST>,
O: ValidOrderingForDistinct<DistinctOnClause<Selection>>,
SelectStatement<F, S, DistinctOnClause<Selection>, W, O, LOf, G>: SelectQuery<SqlType = ST>,
{
type Output = SelectStatement<F, S, DistinctOnClause<Selection>, W, O, LOf, G>;
fn distinct_on(self, selection: Selection) -> Self::Output {
SelectStatement::new(
self.select,
self.from,
DistinctOnClause(selection),
self.where_clause,
self.order,
self.limit_offset,
self.group_by,
self.locking,
)
}
}
|
self.0.walk_ast(out.reborrow())?;
out.push_sql(")");
Ok(())
|
random_line_split
|
distinct_on.rs
|
use crate::expression::SelectableExpression;
use crate::pg::Pg;
use crate::query_builder::order_clause::{NoOrderClause, OrderClause};
use crate::query_builder::{AstPass, QueryFragment, QueryId, SelectQuery, SelectStatement};
use crate::query_dsl::methods::DistinctOnDsl;
use crate::query_dsl::order_dsl::ValidOrderingForDistinct;
use crate::result::QueryResult;
use crate::sql_types::SingleValue;
use crate::Expression;
/// Represents `DISTINCT ON (...)`
#[derive(Debug, Clone, Copy, QueryId)]
pub struct DistinctOnClause<T>(pub(crate) T);
impl<T> ValidOrderingForDistinct<DistinctOnClause<T>> for NoOrderClause {}
impl<T> ValidOrderingForDistinct<DistinctOnClause<T>> for OrderClause<(T,)> {}
impl<T> ValidOrderingForDistinct<DistinctOnClause<T>> for OrderClause<T>
where
T: Expression,
T::SqlType: SingleValue,
{
}
impl<T> QueryFragment<Pg> for DistinctOnClause<T>
where
T: QueryFragment<Pg>,
{
fn walk_ast(&self, mut out: AstPass<Pg>) -> QueryResult<()> {
out.push_sql("DISTINCT ON (");
self.0.walk_ast(out.reborrow())?;
out.push_sql(")");
Ok(())
}
}
impl<ST, F, S, D, W, O, LOf, G, Selection> DistinctOnDsl<Selection>
for SelectStatement<F, S, D, W, O, LOf, G>
where
Selection: SelectableExpression<F>,
Selection::SqlType: SingleValue,
Self: SelectQuery<SqlType = ST>,
O: ValidOrderingForDistinct<DistinctOnClause<Selection>>,
SelectStatement<F, S, DistinctOnClause<Selection>, W, O, LOf, G>: SelectQuery<SqlType = ST>,
{
type Output = SelectStatement<F, S, DistinctOnClause<Selection>, W, O, LOf, G>;
fn
|
(self, selection: Selection) -> Self::Output {
SelectStatement::new(
self.select,
self.from,
DistinctOnClause(selection),
self.where_clause,
self.order,
self.limit_offset,
self.group_by,
self.locking,
)
}
}
|
distinct_on
|
identifier_name
|
lib.rs
|
extern crate regex;
extern crate fall_tree;
extern crate fall_parse;
mod fall;
mod ast_ext;
pub use self::fall::language as lang_fall;
pub use self::fall::{
ERROR,
WHITESPACE,
EOL_COMMENT,
NODE,
CLASS,
TOKENIZER,
RULE,
VERBATIM,
AST,
PUB,
TEST,
EQ,
PIPE,
STAR,
QUESTION,
DOT,
COMMA,
COLON,
HASH,
L_CURLY,
R_CURLY,
L_SQUARE,
R_SQUARE,
L_ANGLE,
R_ANGLE,
L_PAREN,
R_PAREN,
NUMBER,
SIMPLE_STRING,
HASH_STRING,
IDENT,
FALL_FILE,
SYN_RULE,
PARAMETERS,
PARAMETER,
REF_EXPR,
SEQ_EXPR,
BLOCK_EXPR,
OPT_EXPR,
REP_EXPR,
CALL_EXPR,
TOKENIZER_DEF,
LEX_RULE,
TEST_DEF,
ATTRIBUTES,
ATTRIBUTE,
ATTRIBUTE_VALUE,
STRING,
VERBATIM_DEF,
AST_DEF,
|
TRAIT,
AST_TRAIT_DEF,
};
pub use self::fall::{
FallFile,
TokenizerDef,
LexRule,
SynRule,
Parameters,
Parameter,
Attributes,
Attribute,
AttributeValue,
VerbatimDef,
AstDef,
AstNodeDef,
AstClassDef,
AstTraitDef,
MethodDef,
AstSelector,
TestDef,
Expr,
RefExpr,
CallExpr,
BlockExpr,
OptExpr,
RepExpr,
SeqExpr,
};
|
AST_NODE_DEF,
AST_CLASS_DEF,
METHOD_DEF,
AST_SELECTOR,
|
random_line_split
|
toolbox.rs
|
// +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of Tuna. |
// | |
// | Tuna is free software: you can redistribute it and/or modify it under |
// | the terms of the GNU General Public License as published by the Free |
// | Software Foundation, either version 3 of the License, or (at your |
// | option) any later version. |
// | |
// | Tuna is distributed in the hope that it will be useful, but WITHOUT ANY |
// | WARRANTY; without even the implied warranty of MERCHANTABILITY or |
// | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
// | for details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with Tuna. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use crate::canvas::{Canvas, Resources, ToolIcon};
use crate::element::{Action, AggregateElement, GuiElement, SubrectElement};
use crate::event::{Event, Keycode, NONE};
use crate::state::{EditorState, Tool};
use sdl2::rect::{Point, Rect};
//===========================================================================//
pub struct Toolbox {
element: SubrectElement<AggregateElement<Tool, ()>>,
}
impl Toolbox {
const WIDTH: u32 = 72;
const HEIGHT: u32 = 96;
pub fn new(left: i32, top: i32) -> Toolbox {
let elements: Vec<Box<dyn GuiElement<Tool, ()>>> = vec![
Toolbox::picker(2, 2, Tool::Pencil, Keycode::P),
Toolbox::picker(26, 2, Tool::PaintBucket, Keycode::K),
Toolbox::picker(50, 2, Tool::PaletteReplace, Keycode::V),
Toolbox::picker(2, 26, Tool::Watercolor, Keycode::W),
Toolbox::picker(26, 26, Tool::Checkerboard, Keycode::H),
Toolbox::picker(50, 26, Tool::PaletteSwap, Keycode::X),
Toolbox::picker(2, 50, Tool::Line, Keycode::I),
Toolbox::picker(26, 50, Tool::Rectangle, Keycode::R),
Toolbox::picker(50, 50, Tool::Oval, Keycode::O),
Toolbox::picker(2, 74, Tool::Eyedropper, Keycode::Y),
Toolbox::picker(26, 74, Tool::Select, Keycode::S),
Toolbox::picker(50, 74, Tool::Lasso, Keycode::L),
];
Toolbox {
element: SubrectElement::new(
AggregateElement::new(elements),
Rect::new(left, top, Toolbox::WIDTH, Toolbox::HEIGHT),
),
}
}
fn picker(
x: i32,
y: i32,
tool: Tool,
key: Keycode,
) -> Box<dyn GuiElement<Tool, ()>> {
Box::new(SubrectElement::new(
ToolPicker::new(tool, key),
Rect::new(x, y, 20, 20),
))
}
}
impl GuiElement<EditorState, ()> for Toolbox {
fn draw(
&self,
state: &EditorState,
resources: &Resources,
canvas: &mut Canvas,
) {
canvas.fill_rect((95, 95, 95, 255), self.element.rect());
self.element.draw(&state.tool(), resources, canvas);
}
fn on_event(
&mut self,
event: &Event,
state: &mut EditorState,
) -> Action<()> {
let mut new_tool = state.tool();
let action = self.element.on_event(event, &mut new_tool);
if new_tool!= state.tool() {
state.set_tool(new_tool);
}
action
}
}
//===========================================================================//
struct ToolPicker {
tool: Tool,
key: Keycode,
icon: ToolIcon,
}
impl ToolPicker {
fn new(tool: Tool, key: Keycode) -> ToolPicker {
let icon = match tool {
Tool::Checkerboard => ToolIcon::Checkerboard,
Tool::Eyedropper => ToolIcon::Eyedropper,
Tool::Lasso => ToolIcon::Lasso,
Tool::Line => ToolIcon::Line,
Tool::Oval => ToolIcon::Oval,
Tool::PaintBucket => ToolIcon::PaintBucket,
Tool::PaletteReplace => ToolIcon::PaletteReplace,
Tool::PaletteSwap => ToolIcon::PaletteSwap,
Tool::Pencil => ToolIcon::Pencil,
Tool::Rectangle => ToolIcon::Rectangle,
Tool::Select => ToolIcon::Select,
Tool::Watercolor => ToolIcon::Watercolor,
};
ToolPicker { tool, key, icon }
}
}
impl GuiElement<Tool, ()> for ToolPicker {
fn draw(&self, tool: &Tool, resources: &Resources, canvas: &mut Canvas) {
if *tool == self.tool {
canvas.clear((255, 255, 255, 255));
} else {
canvas.clear((95, 95, 95, 255));
}
canvas.draw_sprite(resources.tool_icon(self.icon), Point::new(2, 2));
}
fn on_event(&mut self, event: &Event, tool: &mut Tool) -> Action<()> {
match event {
&Event::MouseDown(_) =>
|
&Event::KeyDown(key, kmod) => {
if key == self.key && kmod == NONE {
*tool = self.tool;
return Action::redraw().and_stop();
}
}
_ => {}
}
Action::ignore()
}
}
//===========================================================================//
|
{
*tool = self.tool;
return Action::redraw().and_stop();
}
|
conditional_block
|
toolbox.rs
|
// +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of Tuna. |
// | |
// | Tuna is free software: you can redistribute it and/or modify it under |
// | the terms of the GNU General Public License as published by the Free |
// | Software Foundation, either version 3 of the License, or (at your |
// | option) any later version. |
// | |
// | Tuna is distributed in the hope that it will be useful, but WITHOUT ANY |
// | WARRANTY; without even the implied warranty of MERCHANTABILITY or |
// | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
// | for details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with Tuna. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use crate::canvas::{Canvas, Resources, ToolIcon};
use crate::element::{Action, AggregateElement, GuiElement, SubrectElement};
use crate::event::{Event, Keycode, NONE};
use crate::state::{EditorState, Tool};
use sdl2::rect::{Point, Rect};
//===========================================================================//
pub struct Toolbox {
element: SubrectElement<AggregateElement<Tool, ()>>,
}
impl Toolbox {
const WIDTH: u32 = 72;
const HEIGHT: u32 = 96;
pub fn new(left: i32, top: i32) -> Toolbox {
let elements: Vec<Box<dyn GuiElement<Tool, ()>>> = vec![
Toolbox::picker(2, 2, Tool::Pencil, Keycode::P),
Toolbox::picker(26, 2, Tool::PaintBucket, Keycode::K),
Toolbox::picker(50, 2, Tool::PaletteReplace, Keycode::V),
Toolbox::picker(2, 26, Tool::Watercolor, Keycode::W),
Toolbox::picker(26, 26, Tool::Checkerboard, Keycode::H),
Toolbox::picker(50, 26, Tool::PaletteSwap, Keycode::X),
Toolbox::picker(2, 50, Tool::Line, Keycode::I),
Toolbox::picker(26, 50, Tool::Rectangle, Keycode::R),
Toolbox::picker(50, 50, Tool::Oval, Keycode::O),
Toolbox::picker(2, 74, Tool::Eyedropper, Keycode::Y),
Toolbox::picker(26, 74, Tool::Select, Keycode::S),
Toolbox::picker(50, 74, Tool::Lasso, Keycode::L),
];
Toolbox {
element: SubrectElement::new(
AggregateElement::new(elements),
Rect::new(left, top, Toolbox::WIDTH, Toolbox::HEIGHT),
),
}
}
fn picker(
x: i32,
y: i32,
tool: Tool,
key: Keycode,
) -> Box<dyn GuiElement<Tool, ()>> {
Box::new(SubrectElement::new(
ToolPicker::new(tool, key),
Rect::new(x, y, 20, 20),
))
}
}
impl GuiElement<EditorState, ()> for Toolbox {
fn draw(
&self,
state: &EditorState,
resources: &Resources,
canvas: &mut Canvas,
) {
canvas.fill_rect((95, 95, 95, 255), self.element.rect());
self.element.draw(&state.tool(), resources, canvas);
}
fn on_event(
&mut self,
event: &Event,
state: &mut EditorState,
) -> Action<()> {
let mut new_tool = state.tool();
let action = self.element.on_event(event, &mut new_tool);
if new_tool!= state.tool() {
state.set_tool(new_tool);
}
action
}
}
//===========================================================================//
struct
|
{
tool: Tool,
key: Keycode,
icon: ToolIcon,
}
impl ToolPicker {
fn new(tool: Tool, key: Keycode) -> ToolPicker {
let icon = match tool {
Tool::Checkerboard => ToolIcon::Checkerboard,
Tool::Eyedropper => ToolIcon::Eyedropper,
Tool::Lasso => ToolIcon::Lasso,
Tool::Line => ToolIcon::Line,
Tool::Oval => ToolIcon::Oval,
Tool::PaintBucket => ToolIcon::PaintBucket,
Tool::PaletteReplace => ToolIcon::PaletteReplace,
Tool::PaletteSwap => ToolIcon::PaletteSwap,
Tool::Pencil => ToolIcon::Pencil,
Tool::Rectangle => ToolIcon::Rectangle,
Tool::Select => ToolIcon::Select,
Tool::Watercolor => ToolIcon::Watercolor,
};
ToolPicker { tool, key, icon }
}
}
impl GuiElement<Tool, ()> for ToolPicker {
fn draw(&self, tool: &Tool, resources: &Resources, canvas: &mut Canvas) {
if *tool == self.tool {
canvas.clear((255, 255, 255, 255));
} else {
canvas.clear((95, 95, 95, 255));
}
canvas.draw_sprite(resources.tool_icon(self.icon), Point::new(2, 2));
}
fn on_event(&mut self, event: &Event, tool: &mut Tool) -> Action<()> {
match event {
&Event::MouseDown(_) => {
*tool = self.tool;
return Action::redraw().and_stop();
}
&Event::KeyDown(key, kmod) => {
if key == self.key && kmod == NONE {
*tool = self.tool;
return Action::redraw().and_stop();
}
}
_ => {}
}
Action::ignore()
}
}
//===========================================================================//
|
ToolPicker
|
identifier_name
|
toolbox.rs
|
// +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of Tuna. |
// | |
// | Tuna is free software: you can redistribute it and/or modify it under |
// | the terms of the GNU General Public License as published by the Free |
// | Software Foundation, either version 3 of the License, or (at your |
// | option) any later version. |
// | |
// | Tuna is distributed in the hope that it will be useful, but WITHOUT ANY |
// | WARRANTY; without even the implied warranty of MERCHANTABILITY or |
// | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
// | for details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with Tuna. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use crate::canvas::{Canvas, Resources, ToolIcon};
use crate::element::{Action, AggregateElement, GuiElement, SubrectElement};
use crate::event::{Event, Keycode, NONE};
use crate::state::{EditorState, Tool};
use sdl2::rect::{Point, Rect};
//===========================================================================//
pub struct Toolbox {
element: SubrectElement<AggregateElement<Tool, ()>>,
}
impl Toolbox {
const WIDTH: u32 = 72;
const HEIGHT: u32 = 96;
pub fn new(left: i32, top: i32) -> Toolbox
|
}
}
fn picker(
x: i32,
y: i32,
tool: Tool,
key: Keycode,
) -> Box<dyn GuiElement<Tool, ()>> {
Box::new(SubrectElement::new(
ToolPicker::new(tool, key),
Rect::new(x, y, 20, 20),
))
}
}
impl GuiElement<EditorState, ()> for Toolbox {
fn draw(
&self,
state: &EditorState,
resources: &Resources,
canvas: &mut Canvas,
) {
canvas.fill_rect((95, 95, 95, 255), self.element.rect());
self.element.draw(&state.tool(), resources, canvas);
}
fn on_event(
&mut self,
event: &Event,
state: &mut EditorState,
) -> Action<()> {
let mut new_tool = state.tool();
let action = self.element.on_event(event, &mut new_tool);
if new_tool!= state.tool() {
state.set_tool(new_tool);
}
action
}
}
//===========================================================================//
struct ToolPicker {
tool: Tool,
key: Keycode,
icon: ToolIcon,
}
impl ToolPicker {
fn new(tool: Tool, key: Keycode) -> ToolPicker {
let icon = match tool {
Tool::Checkerboard => ToolIcon::Checkerboard,
Tool::Eyedropper => ToolIcon::Eyedropper,
Tool::Lasso => ToolIcon::Lasso,
Tool::Line => ToolIcon::Line,
Tool::Oval => ToolIcon::Oval,
Tool::PaintBucket => ToolIcon::PaintBucket,
Tool::PaletteReplace => ToolIcon::PaletteReplace,
Tool::PaletteSwap => ToolIcon::PaletteSwap,
Tool::Pencil => ToolIcon::Pencil,
Tool::Rectangle => ToolIcon::Rectangle,
Tool::Select => ToolIcon::Select,
Tool::Watercolor => ToolIcon::Watercolor,
};
ToolPicker { tool, key, icon }
}
}
impl GuiElement<Tool, ()> for ToolPicker {
fn draw(&self, tool: &Tool, resources: &Resources, canvas: &mut Canvas) {
if *tool == self.tool {
canvas.clear((255, 255, 255, 255));
} else {
canvas.clear((95, 95, 95, 255));
}
canvas.draw_sprite(resources.tool_icon(self.icon), Point::new(2, 2));
}
fn on_event(&mut self, event: &Event, tool: &mut Tool) -> Action<()> {
match event {
&Event::MouseDown(_) => {
*tool = self.tool;
return Action::redraw().and_stop();
}
&Event::KeyDown(key, kmod) => {
if key == self.key && kmod == NONE {
*tool = self.tool;
return Action::redraw().and_stop();
}
}
_ => {}
}
Action::ignore()
}
}
//===========================================================================//
|
{
let elements: Vec<Box<dyn GuiElement<Tool, ()>>> = vec![
Toolbox::picker(2, 2, Tool::Pencil, Keycode::P),
Toolbox::picker(26, 2, Tool::PaintBucket, Keycode::K),
Toolbox::picker(50, 2, Tool::PaletteReplace, Keycode::V),
Toolbox::picker(2, 26, Tool::Watercolor, Keycode::W),
Toolbox::picker(26, 26, Tool::Checkerboard, Keycode::H),
Toolbox::picker(50, 26, Tool::PaletteSwap, Keycode::X),
Toolbox::picker(2, 50, Tool::Line, Keycode::I),
Toolbox::picker(26, 50, Tool::Rectangle, Keycode::R),
Toolbox::picker(50, 50, Tool::Oval, Keycode::O),
Toolbox::picker(2, 74, Tool::Eyedropper, Keycode::Y),
Toolbox::picker(26, 74, Tool::Select, Keycode::S),
Toolbox::picker(50, 74, Tool::Lasso, Keycode::L),
];
Toolbox {
element: SubrectElement::new(
AggregateElement::new(elements),
Rect::new(left, top, Toolbox::WIDTH, Toolbox::HEIGHT),
),
|
identifier_body
|
toolbox.rs
|
// +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <[email protected]> |
// | |
// | This file is part of Tuna. |
// | |
// | Tuna is free software: you can redistribute it and/or modify it under |
// | the terms of the GNU General Public License as published by the Free |
// | Software Foundation, either version 3 of the License, or (at your |
// | option) any later version. |
// | |
// | Tuna is distributed in the hope that it will be useful, but WITHOUT ANY |
// | WARRANTY; without even the implied warranty of MERCHANTABILITY or |
// | FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
// | for details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with Tuna. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
use crate::canvas::{Canvas, Resources, ToolIcon};
use crate::element::{Action, AggregateElement, GuiElement, SubrectElement};
use crate::event::{Event, Keycode, NONE};
use crate::state::{EditorState, Tool};
use sdl2::rect::{Point, Rect};
//===========================================================================//
pub struct Toolbox {
element: SubrectElement<AggregateElement<Tool, ()>>,
}
impl Toolbox {
const WIDTH: u32 = 72;
const HEIGHT: u32 = 96;
pub fn new(left: i32, top: i32) -> Toolbox {
let elements: Vec<Box<dyn GuiElement<Tool, ()>>> = vec![
Toolbox::picker(2, 2, Tool::Pencil, Keycode::P),
Toolbox::picker(26, 2, Tool::PaintBucket, Keycode::K),
Toolbox::picker(50, 2, Tool::PaletteReplace, Keycode::V),
Toolbox::picker(2, 26, Tool::Watercolor, Keycode::W),
Toolbox::picker(26, 26, Tool::Checkerboard, Keycode::H),
Toolbox::picker(50, 26, Tool::PaletteSwap, Keycode::X),
Toolbox::picker(2, 50, Tool::Line, Keycode::I),
Toolbox::picker(26, 50, Tool::Rectangle, Keycode::R),
Toolbox::picker(50, 50, Tool::Oval, Keycode::O),
Toolbox::picker(2, 74, Tool::Eyedropper, Keycode::Y),
Toolbox::picker(26, 74, Tool::Select, Keycode::S),
Toolbox::picker(50, 74, Tool::Lasso, Keycode::L),
];
Toolbox {
element: SubrectElement::new(
AggregateElement::new(elements),
Rect::new(left, top, Toolbox::WIDTH, Toolbox::HEIGHT),
),
}
}
fn picker(
x: i32,
y: i32,
tool: Tool,
key: Keycode,
) -> Box<dyn GuiElement<Tool, ()>> {
Box::new(SubrectElement::new(
ToolPicker::new(tool, key),
Rect::new(x, y, 20, 20),
))
}
}
impl GuiElement<EditorState, ()> for Toolbox {
fn draw(
&self,
state: &EditorState,
resources: &Resources,
canvas: &mut Canvas,
) {
canvas.fill_rect((95, 95, 95, 255), self.element.rect());
self.element.draw(&state.tool(), resources, canvas);
}
fn on_event(
&mut self,
event: &Event,
state: &mut EditorState,
) -> Action<()> {
let mut new_tool = state.tool();
let action = self.element.on_event(event, &mut new_tool);
if new_tool!= state.tool() {
state.set_tool(new_tool);
}
action
}
}
//===========================================================================//
struct ToolPicker {
tool: Tool,
key: Keycode,
icon: ToolIcon,
}
impl ToolPicker {
fn new(tool: Tool, key: Keycode) -> ToolPicker {
let icon = match tool {
Tool::Checkerboard => ToolIcon::Checkerboard,
Tool::Eyedropper => ToolIcon::Eyedropper,
Tool::Lasso => ToolIcon::Lasso,
Tool::Line => ToolIcon::Line,
Tool::Oval => ToolIcon::Oval,
Tool::PaintBucket => ToolIcon::PaintBucket,
Tool::PaletteReplace => ToolIcon::PaletteReplace,
Tool::PaletteSwap => ToolIcon::PaletteSwap,
Tool::Pencil => ToolIcon::Pencil,
Tool::Rectangle => ToolIcon::Rectangle,
Tool::Select => ToolIcon::Select,
Tool::Watercolor => ToolIcon::Watercolor,
};
ToolPicker { tool, key, icon }
}
}
impl GuiElement<Tool, ()> for ToolPicker {
fn draw(&self, tool: &Tool, resources: &Resources, canvas: &mut Canvas) {
if *tool == self.tool {
canvas.clear((255, 255, 255, 255));
} else {
canvas.clear((95, 95, 95, 255));
}
canvas.draw_sprite(resources.tool_icon(self.icon), Point::new(2, 2));
}
fn on_event(&mut self, event: &Event, tool: &mut Tool) -> Action<()> {
match event {
&Event::MouseDown(_) => {
*tool = self.tool;
|
return Action::redraw().and_stop();
}
}
_ => {}
}
Action::ignore()
}
}
//===========================================================================//
|
return Action::redraw().and_stop();
}
&Event::KeyDown(key, kmod) => {
if key == self.key && kmod == NONE {
*tool = self.tool;
|
random_line_split
|
lib.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/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(hashmap_hasher)]
#![feature(heap_api)]
#![feature(oom)]
#![feature(optin_builtin_traits)]
#![feature(path_ext)]
#![feature(plugin)]
#![feature(slice_splits)]
#![feature(step_by)]
#![feature(step_trait)]
#![feature(zero_one)]
#![plugin(plugins, serde_macros)]
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate cssparser;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate alloc;
extern crate azure;
extern crate euclid;
extern crate getopts;
extern crate html5ever;
extern crate hyper;
extern crate ipc_channel;
extern crate js;
extern crate layers;
extern crate libc;
extern crate num_cpus;
extern crate num as num_lib;
extern crate rand;
extern crate rustc_serialize;
extern crate selectors;
extern crate serde;
extern crate smallvec;
extern crate string_cache;
extern crate url;
use std::sync::Arc;
pub mod bezier;
pub mod cache;
pub mod cursor;
pub mod debug_utils;
pub mod deque;
pub mod geometry;
pub mod ipc;
pub mod linked_list;
pub mod logical_geometry;
pub mod mem;
pub mod opts;
pub mod persistent_list;
pub mod prefs;
pub mod print_tree;
pub mod range;
pub mod resource_files;
pub mod str;
pub mod task;
pub mod task_state;
pub mod taskpool;
pub mod tid;
pub mod vec;
pub mod workqueue;
|
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T:'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
|
pub fn breakpoint() {
unsafe { ::std::intrinsics::breakpoint() };
}
|
random_line_split
|
lib.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/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(hashmap_hasher)]
#![feature(heap_api)]
#![feature(oom)]
#![feature(optin_builtin_traits)]
#![feature(path_ext)]
#![feature(plugin)]
#![feature(slice_splits)]
#![feature(step_by)]
#![feature(step_trait)]
#![feature(zero_one)]
#![plugin(plugins, serde_macros)]
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate cssparser;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate alloc;
extern crate azure;
extern crate euclid;
extern crate getopts;
extern crate html5ever;
extern crate hyper;
extern crate ipc_channel;
extern crate js;
extern crate layers;
extern crate libc;
extern crate num_cpus;
extern crate num as num_lib;
extern crate rand;
extern crate rustc_serialize;
extern crate selectors;
extern crate serde;
extern crate smallvec;
extern crate string_cache;
extern crate url;
use std::sync::Arc;
pub mod bezier;
pub mod cache;
pub mod cursor;
pub mod debug_utils;
pub mod deque;
pub mod geometry;
pub mod ipc;
pub mod linked_list;
pub mod logical_geometry;
pub mod mem;
pub mod opts;
pub mod persistent_list;
pub mod prefs;
pub mod print_tree;
pub mod range;
pub mod resource_files;
pub mod str;
pub mod task;
pub mod task_state;
pub mod taskpool;
pub mod tid;
pub mod vec;
pub mod workqueue;
pub fn
|
() {
unsafe { ::std::intrinsics::breakpoint() };
}
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T:'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
|
breakpoint
|
identifier_name
|
lib.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/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![feature(fnbox)]
#![feature(hashmap_hasher)]
#![feature(heap_api)]
#![feature(oom)]
#![feature(optin_builtin_traits)]
#![feature(path_ext)]
#![feature(plugin)]
#![feature(slice_splits)]
#![feature(step_by)]
#![feature(step_trait)]
#![feature(zero_one)]
#![plugin(plugins, serde_macros)]
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate cssparser;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate alloc;
extern crate azure;
extern crate euclid;
extern crate getopts;
extern crate html5ever;
extern crate hyper;
extern crate ipc_channel;
extern crate js;
extern crate layers;
extern crate libc;
extern crate num_cpus;
extern crate num as num_lib;
extern crate rand;
extern crate rustc_serialize;
extern crate selectors;
extern crate serde;
extern crate smallvec;
extern crate string_cache;
extern crate url;
use std::sync::Arc;
pub mod bezier;
pub mod cache;
pub mod cursor;
pub mod debug_utils;
pub mod deque;
pub mod geometry;
pub mod ipc;
pub mod linked_list;
pub mod logical_geometry;
pub mod mem;
pub mod opts;
pub mod persistent_list;
pub mod prefs;
pub mod print_tree;
pub mod range;
pub mod resource_files;
pub mod str;
pub mod task;
pub mod task_state;
pub mod taskpool;
pub mod tid;
pub mod vec;
pub mod workqueue;
pub fn breakpoint()
|
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T:'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
|
{
unsafe { ::std::intrinsics::breakpoint() };
}
|
identifier_body
|
rustkernel.rs
|
/*
* Copyright (C) 2018, Nils Asmussen <[email protected]>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* M3 is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License version 2 for more details.
*/
#![feature(core_intrinsics)]
#![feature(ptr_internals)]
#![no_std]
#[macro_use]
extern crate base;
#[macro_use]
extern crate bitflags;
extern crate thread;
#[macro_use]
mod log;
pub mod arch;
|
mod syscalls;
mod tests;
mod workloop;
|
mod cap;
mod com;
mod mem;
mod pes;
mod platform;
|
random_line_split
|
grids.rs
|
/* Copyright 2017-2019 the Conwayste Developers.
*
* This file is part of libconway.
*
* libconway is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* libconway is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with libconway. If not, see <http://www.gnu.org/licenses/>. */
use std::ops::{Index, IndexMut};
use std::cmp;
use crate::universe::Region;
use crate::rle::Pattern;
#[derive(Eq, PartialEq, Debug, Clone, Copy)]
pub enum BitOperation {
Clear,
Set,
Toggle
}
#[derive(Debug, PartialEq, Clone)]
pub struct BitGrid(pub Vec<Vec<u64>>);
impl BitGrid {
/// Creates a new zero-initialized BitGrid of given dimensions.
///
/// # Panics
///
/// This function will panic if `with_in_words` or `height` are zero.
pub fn new(width_in_words: usize, height: usize) -> Self {
assert!(width_in_words!= 0);
assert!(height!= 0);
let mut rows: Vec<Vec<u64>> = Vec::with_capacity(height);
for _ in 0.. height {
let row: Vec<u64> = vec![0; width_in_words];
rows.push(row);
}
BitGrid(rows)
}
pub fn width_in_words(&self) -> usize {
if self.height() > 0 {
self.0[0].len()
} else {
0
}
}
#[inline]
pub fn modify_bits_in_word(&mut self, row: usize, word_col: usize, mask: u64, op: BitOperation) {
match op {
BitOperation::Set => self[row][word_col] |= mask,
BitOperation::Clear => self[row][word_col] &=!mask,
BitOperation::Toggle => self[row][word_col] ^= mask,
}
}
/// Sets, clears, or toggles a rectangle of bits.
///
/// # Panics
///
/// This function will panic if `region` is out of range.
pub fn modify_region(&mut self, region: Region, op: BitOperation) {
for y in region.top().. region.bottom() + 1 {
assert!(y >= 0);
for word_col in 0.. self[y as usize].len() {
let x_left = word_col * 64;
let x_right = x_left + 63;
if region.right() >= x_left as isize && region.left() <= x_right as isize {
let mut mask = u64::max_value();
for shift in (0..64).rev() {
let x = x_right - shift;
if (x as isize) < region.left() || (x as isize) > region.right() {
mask &=!(1 << shift);
}
}
// apply change to bitgrid based on mask and bit
self.modify_bits_in_word(y as usize, word_col, mask, op);
}
}
}
}
/// Returns `Some(`smallest region containing every 1 bit`)`, or `None` if there are no 1 bits.
pub fn bounding_box(&self) -> Option<Region>
|
}
let run_last_col = col + rle_len - 1;
if let Some(_last_col) = last_col {
if _last_col < run_last_col {
last_col = Some(run_last_col);
}
} else {
last_col = Some(run_last_col);
}
last_row = Some(row);
}
col += rle_len;
}
}
if first_row.is_some() {
let width = last_col.unwrap() - first_col.unwrap() + 1;
let height = last_row.unwrap() - first_row.unwrap() + 1;
Some(Region::new(first_col.unwrap() as isize, first_row.unwrap() as isize, width, height))
} else {
None
}
}
/// Copies `src` BitGrid into `dst` BitGrid, but fit into `dst_region` with clipping. If there
/// is a 10x10 pattern in source starting at 0,0 and the dst_region is only 8x8 with top left
/// corner at 3,3 then the resulting pattern will be clipped in a 2 pixel region on the bottom
/// and right and extend from 3,3 to 10,10. If `dst_region` extends beyond `dst`, the pattern
/// will be further clipped by the dimensions of `dst`.
///
/// The bits are copied using an `|=` operation, so 1 bits in the destination will not ever be
/// cleared.
pub fn copy(src: &BitGrid, dst: &mut BitGrid, dst_region: Region) {
let dst_left = cmp::max(0, dst_region.left()) as usize;
let dst_right = cmp::min(dst.width() as isize - 1, dst_region.right()) as usize;
let dst_top = cmp::max(0, dst_region.top()) as usize;
let dst_bottom = cmp::min(dst.height() as isize - 1, dst_region.bottom()) as usize;
if dst_left > dst_right || dst_top > dst_bottom {
// nothing to do because both dimensions aren't positive
return;
}
for src_row in 0..src.height() {
let dst_row = src_row + dst_top;
if dst_row > dst_bottom {
break;
}
let mut src_col = 0; // word-aligned
while src_col < src.width() {
let dst_col = src_col + dst_left; // not word-aligned
if dst_col > dst_right {
break;
}
let dst_word_idx = dst_col / 64;
let shift = dst_col - dst_word_idx*64; // right shift amount
let mut word = src[src_row][src_col/64];
// clear bits that would be beyond dst_right
if dst_right - dst_col + 1 < 64 {
let mask =!((1u64 << (64 - (dst_right - dst_col + 1))) - 1);
word &= mask;
}
dst[dst_row][dst_word_idx] |= word >> shift;
if shift > 0 && dst_word_idx+1 < dst.width_in_words() {
dst[dst_row][dst_word_idx+1] |= word << (64 - shift);
}
src_col += 64;
}
}
}
/// Get a Region of the same size as the BitGrid.
pub fn region(&self) -> Region {
Region::new(0, 0, self.width(), self.height())
}
/// Clear this BitGrid.
pub fn clear(&mut self) {
for row in &mut self.0 {
for col_idx in 0..row.len() {
row[col_idx] = 0;
}
}
}
}
impl Index<usize> for BitGrid {
type Output = Vec<u64>;
fn index(&self, i: usize) -> &Vec<u64> {
&self.0[i]
}
}
impl IndexMut<usize> for BitGrid {
fn index_mut(&mut self, i: usize) -> &mut Vec<u64> {
&mut self.0[i]
}
}
pub trait CharGrid {
/// Write a char `ch` to (`col`, `row`).
///
/// # Panics
///
/// Panics if:
/// * `col` or `row` are out of range
/// * `char` is invalid for this type. Use `is_valid` to check first.
/// * `visibility` is invalid. That is, it equals `Some(player_id)`, but there is no such `player_id`.
fn write_at_position(&mut self, col: usize, row: usize, ch: char, visibility: Option<usize>);
/// Is `ch` a valid character?
fn is_valid(ch: char) -> bool;
/// Width in cells
fn width(&self) -> usize;
/// Height in cells
fn height(&self) -> usize;
/// Returns a Pattern that describes this `CharGrid` as viewed by specified player if
/// `visibility.is_some()`, or a fog-less view if `visibility.is_none()`.
fn to_pattern(&self, visibility: Option<usize>) -> Pattern {
fn push(result: &mut String, output_col: &mut usize, rle_len: usize, ch: char) {
let what_to_add = if rle_len == 1 {
let mut s = String::with_capacity(1);
s.push(ch);
s
} else { format!("{}{}", rle_len, ch) };
if *output_col + what_to_add.len() > 70 {
result.push_str("\r\n");
*output_col = 0;
}
result.push_str(what_to_add.as_str());
*output_col += what_to_add.len();
}
let mut result = "".to_owned();
let (mut col, mut row) = (0, 0);
let mut line_ends_buffered = 0;
let mut output_col = 0;
while row < self.height() {
while col < self.width() {
let (rle_len, ch) = self.get_run(col, row, visibility);
match ch {
'b' => {
// Blank
// TODO: if supporting diffs with this same algorithm, then need to allow
// other characters to serve this purpose.
if col + rle_len < self.width() {
if line_ends_buffered > 0 {
push(&mut result, &mut output_col, line_ends_buffered, '$');
line_ends_buffered = 0;
}
push(&mut result, &mut output_col, rle_len, ch);
}
}
_ => {
// Non-blank
if line_ends_buffered > 0 {
push(&mut result, &mut output_col, line_ends_buffered, '$');
line_ends_buffered = 0;
}
push(&mut result, &mut output_col, rle_len, ch);
}
}
col += rle_len;
}
row += 1;
col = 0;
line_ends_buffered += 1;
}
push(&mut result, &mut output_col, 1, '!');
Pattern(result)
}
/// Given a starting cell at `(col, row)`, get the character at that cell, and the number of
/// contiguous identical cells considering only this cell and the cells to the right of it.
/// This is intended for exporting to RLE.
///
/// The `visibility` parameter, if not `None`, is used to generate a run as observed by a
/// particular player.
///
/// # Returns
///
/// `(run_length, ch)`
///
/// # Panics
///
/// This function will panic if `col`, `row`, or `visibility` (`Some(player_id)`) are out of bounds.
fn get_run(&self, col: usize, row: usize, visibility: Option<usize>) -> (usize, char);
}
const VALID_BIT_GRID_CHARS: [char; 2] = ['b', 'o'];
impl CharGrid for BitGrid {
/// Width in cells
fn width(&self) -> usize {
self.width_in_words() * 64
}
/// Height in cells
fn height(&self) -> usize {
self.0.len()
}
/// _visibility is ignored, since BitGrids have no concept of a player.
fn write_at_position(&mut self, col: usize, row: usize, ch: char, _visibility: Option<usize>) {
let word_col = col/64;
let shift = 63 - (col & (64 - 1));
match ch {
'b' => {
self.modify_bits_in_word(row, word_col, 1 << shift, BitOperation::Clear)
}
'o' => {
self.modify_bits_in_word(row, word_col, 1 << shift, BitOperation::Set)
}
_ => panic!("invalid character: {:?}", ch)
}
}
fn is_valid(ch: char) -> bool {
VALID_BIT_GRID_CHARS.contains(&ch)
}
/// Given a starting cell at `(col, row)`, get the character at that cell, and the number of
/// contiguous identical cells considering only this cell and the cells to the right of it.
/// This is intended for exporting to RLE.
///
/// The `_visibility` argument is unused and should be `None`.
///
/// # Returns
///
/// `(run_length, ch)`
///
/// # Panics
///
/// This function will panic if `col` or `row` are out of bounds.
fn get_run(&self, col: usize, row: usize, _visibility: Option<usize>) -> (usize, char) {
let word_col = col/64;
let shift = 63 - (col & (64 - 1));
let mut word = self.0[row][word_col];
let mut mask = 1 << shift;
let is_set = (word & (1 << shift)) > 0;
let mut end_col = col + 1;
let ch = if is_set { 'o' } else { 'b' };
// go to end of current word
mask >>= 1;
while mask > 0 {
if (word & mask > 0)!= is_set {
return (end_col - col, ch);
}
end_col += 1;
mask >>= 1;
}
assert_eq!(end_col % 64, 0);
// skip words
let mut end_word_col = word_col + 1;
while end_word_col < self.0[row].len() {
word = self.0[row][end_word_col];
if is_set && word < u64::max_value() {
break;
}
if!is_set && word > 0 {
break;
}
end_col += 64;
end_word_col += 1;
}
// start from beginning of last word
if end_word_col == self.0[row].len() {
return (end_col - col, ch);
}
mask = 1 << 63;
while mask > 0 {
if (word & mask > 0)!= is_set {
break;
}
end_col += 1;
mask >>= 1;
}
return (end_col - col, ch);
}
}
|
{
let (width, height) = (self.width(), self.height());
let mut first_row = None;
let mut last_row = None;
let mut first_col = None;
let mut last_col = None;
for row in 0..height {
let mut col = 0;
while col < width {
let (rle_len, ch) = self.get_run(col, row, None);
if ch == 'o' {
if let Some(_first_col) = first_col {
if _first_col > col {
first_col = Some(col);
}
} else {
first_col = Some(col);
}
if first_row.is_none() {
first_row = Some(row);
|
identifier_body
|
grids.rs
|
/* Copyright 2017-2019 the Conwayste Developers.
*
* This file is part of libconway.
*
* libconway is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* libconway is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with libconway. If not, see <http://www.gnu.org/licenses/>. */
use std::ops::{Index, IndexMut};
use std::cmp;
use crate::universe::Region;
use crate::rle::Pattern;
#[derive(Eq, PartialEq, Debug, Clone, Copy)]
pub enum BitOperation {
Clear,
Set,
Toggle
}
#[derive(Debug, PartialEq, Clone)]
pub struct BitGrid(pub Vec<Vec<u64>>);
impl BitGrid {
/// Creates a new zero-initialized BitGrid of given dimensions.
///
/// # Panics
///
/// This function will panic if `with_in_words` or `height` are zero.
pub fn new(width_in_words: usize, height: usize) -> Self {
assert!(width_in_words!= 0);
assert!(height!= 0);
let mut rows: Vec<Vec<u64>> = Vec::with_capacity(height);
for _ in 0.. height {
let row: Vec<u64> = vec![0; width_in_words];
rows.push(row);
}
BitGrid(rows)
}
pub fn width_in_words(&self) -> usize {
if self.height() > 0
|
else {
0
}
}
#[inline]
pub fn modify_bits_in_word(&mut self, row: usize, word_col: usize, mask: u64, op: BitOperation) {
match op {
BitOperation::Set => self[row][word_col] |= mask,
BitOperation::Clear => self[row][word_col] &=!mask,
BitOperation::Toggle => self[row][word_col] ^= mask,
}
}
/// Sets, clears, or toggles a rectangle of bits.
///
/// # Panics
///
/// This function will panic if `region` is out of range.
pub fn modify_region(&mut self, region: Region, op: BitOperation) {
for y in region.top().. region.bottom() + 1 {
assert!(y >= 0);
for word_col in 0.. self[y as usize].len() {
let x_left = word_col * 64;
let x_right = x_left + 63;
if region.right() >= x_left as isize && region.left() <= x_right as isize {
let mut mask = u64::max_value();
for shift in (0..64).rev() {
let x = x_right - shift;
if (x as isize) < region.left() || (x as isize) > region.right() {
mask &=!(1 << shift);
}
}
// apply change to bitgrid based on mask and bit
self.modify_bits_in_word(y as usize, word_col, mask, op);
}
}
}
}
/// Returns `Some(`smallest region containing every 1 bit`)`, or `None` if there are no 1 bits.
pub fn bounding_box(&self) -> Option<Region> {
let (width, height) = (self.width(), self.height());
let mut first_row = None;
let mut last_row = None;
let mut first_col = None;
let mut last_col = None;
for row in 0..height {
let mut col = 0;
while col < width {
let (rle_len, ch) = self.get_run(col, row, None);
if ch == 'o' {
if let Some(_first_col) = first_col {
if _first_col > col {
first_col = Some(col);
}
} else {
first_col = Some(col);
}
if first_row.is_none() {
first_row = Some(row);
}
let run_last_col = col + rle_len - 1;
if let Some(_last_col) = last_col {
if _last_col < run_last_col {
last_col = Some(run_last_col);
}
} else {
last_col = Some(run_last_col);
}
last_row = Some(row);
}
col += rle_len;
}
}
if first_row.is_some() {
let width = last_col.unwrap() - first_col.unwrap() + 1;
let height = last_row.unwrap() - first_row.unwrap() + 1;
Some(Region::new(first_col.unwrap() as isize, first_row.unwrap() as isize, width, height))
} else {
None
}
}
/// Copies `src` BitGrid into `dst` BitGrid, but fit into `dst_region` with clipping. If there
/// is a 10x10 pattern in source starting at 0,0 and the dst_region is only 8x8 with top left
/// corner at 3,3 then the resulting pattern will be clipped in a 2 pixel region on the bottom
/// and right and extend from 3,3 to 10,10. If `dst_region` extends beyond `dst`, the pattern
/// will be further clipped by the dimensions of `dst`.
///
/// The bits are copied using an `|=` operation, so 1 bits in the destination will not ever be
/// cleared.
pub fn copy(src: &BitGrid, dst: &mut BitGrid, dst_region: Region) {
let dst_left = cmp::max(0, dst_region.left()) as usize;
let dst_right = cmp::min(dst.width() as isize - 1, dst_region.right()) as usize;
let dst_top = cmp::max(0, dst_region.top()) as usize;
let dst_bottom = cmp::min(dst.height() as isize - 1, dst_region.bottom()) as usize;
if dst_left > dst_right || dst_top > dst_bottom {
// nothing to do because both dimensions aren't positive
return;
}
for src_row in 0..src.height() {
let dst_row = src_row + dst_top;
if dst_row > dst_bottom {
break;
}
let mut src_col = 0; // word-aligned
while src_col < src.width() {
let dst_col = src_col + dst_left; // not word-aligned
if dst_col > dst_right {
break;
}
let dst_word_idx = dst_col / 64;
let shift = dst_col - dst_word_idx*64; // right shift amount
let mut word = src[src_row][src_col/64];
// clear bits that would be beyond dst_right
if dst_right - dst_col + 1 < 64 {
let mask =!((1u64 << (64 - (dst_right - dst_col + 1))) - 1);
word &= mask;
}
dst[dst_row][dst_word_idx] |= word >> shift;
if shift > 0 && dst_word_idx+1 < dst.width_in_words() {
dst[dst_row][dst_word_idx+1] |= word << (64 - shift);
}
src_col += 64;
}
}
}
/// Get a Region of the same size as the BitGrid.
pub fn region(&self) -> Region {
Region::new(0, 0, self.width(), self.height())
}
/// Clear this BitGrid.
pub fn clear(&mut self) {
for row in &mut self.0 {
for col_idx in 0..row.len() {
row[col_idx] = 0;
}
}
}
}
impl Index<usize> for BitGrid {
type Output = Vec<u64>;
fn index(&self, i: usize) -> &Vec<u64> {
&self.0[i]
}
}
impl IndexMut<usize> for BitGrid {
fn index_mut(&mut self, i: usize) -> &mut Vec<u64> {
&mut self.0[i]
}
}
pub trait CharGrid {
/// Write a char `ch` to (`col`, `row`).
///
/// # Panics
///
/// Panics if:
/// * `col` or `row` are out of range
/// * `char` is invalid for this type. Use `is_valid` to check first.
/// * `visibility` is invalid. That is, it equals `Some(player_id)`, but there is no such `player_id`.
fn write_at_position(&mut self, col: usize, row: usize, ch: char, visibility: Option<usize>);
/// Is `ch` a valid character?
fn is_valid(ch: char) -> bool;
/// Width in cells
fn width(&self) -> usize;
/// Height in cells
fn height(&self) -> usize;
/// Returns a Pattern that describes this `CharGrid` as viewed by specified player if
/// `visibility.is_some()`, or a fog-less view if `visibility.is_none()`.
fn to_pattern(&self, visibility: Option<usize>) -> Pattern {
fn push(result: &mut String, output_col: &mut usize, rle_len: usize, ch: char) {
let what_to_add = if rle_len == 1 {
let mut s = String::with_capacity(1);
s.push(ch);
s
} else { format!("{}{}", rle_len, ch) };
if *output_col + what_to_add.len() > 70 {
result.push_str("\r\n");
*output_col = 0;
}
result.push_str(what_to_add.as_str());
*output_col += what_to_add.len();
}
let mut result = "".to_owned();
let (mut col, mut row) = (0, 0);
let mut line_ends_buffered = 0;
let mut output_col = 0;
while row < self.height() {
while col < self.width() {
let (rle_len, ch) = self.get_run(col, row, visibility);
match ch {
'b' => {
// Blank
// TODO: if supporting diffs with this same algorithm, then need to allow
// other characters to serve this purpose.
if col + rle_len < self.width() {
if line_ends_buffered > 0 {
push(&mut result, &mut output_col, line_ends_buffered, '$');
line_ends_buffered = 0;
}
push(&mut result, &mut output_col, rle_len, ch);
}
}
_ => {
// Non-blank
if line_ends_buffered > 0 {
push(&mut result, &mut output_col, line_ends_buffered, '$');
line_ends_buffered = 0;
}
push(&mut result, &mut output_col, rle_len, ch);
}
}
col += rle_len;
}
row += 1;
col = 0;
line_ends_buffered += 1;
}
push(&mut result, &mut output_col, 1, '!');
Pattern(result)
}
/// Given a starting cell at `(col, row)`, get the character at that cell, and the number of
/// contiguous identical cells considering only this cell and the cells to the right of it.
/// This is intended for exporting to RLE.
///
/// The `visibility` parameter, if not `None`, is used to generate a run as observed by a
/// particular player.
///
/// # Returns
///
/// `(run_length, ch)`
///
/// # Panics
///
/// This function will panic if `col`, `row`, or `visibility` (`Some(player_id)`) are out of bounds.
fn get_run(&self, col: usize, row: usize, visibility: Option<usize>) -> (usize, char);
}
const VALID_BIT_GRID_CHARS: [char; 2] = ['b', 'o'];
impl CharGrid for BitGrid {
/// Width in cells
fn width(&self) -> usize {
self.width_in_words() * 64
}
/// Height in cells
fn height(&self) -> usize {
self.0.len()
}
/// _visibility is ignored, since BitGrids have no concept of a player.
fn write_at_position(&mut self, col: usize, row: usize, ch: char, _visibility: Option<usize>) {
let word_col = col/64;
let shift = 63 - (col & (64 - 1));
match ch {
'b' => {
self.modify_bits_in_word(row, word_col, 1 << shift, BitOperation::Clear)
}
'o' => {
self.modify_bits_in_word(row, word_col, 1 << shift, BitOperation::Set)
}
_ => panic!("invalid character: {:?}", ch)
}
}
fn is_valid(ch: char) -> bool {
VALID_BIT_GRID_CHARS.contains(&ch)
}
/// Given a starting cell at `(col, row)`, get the character at that cell, and the number of
/// contiguous identical cells considering only this cell and the cells to the right of it.
/// This is intended for exporting to RLE.
///
/// The `_visibility` argument is unused and should be `None`.
///
/// # Returns
///
/// `(run_length, ch)`
///
/// # Panics
///
/// This function will panic if `col` or `row` are out of bounds.
fn get_run(&self, col: usize, row: usize, _visibility: Option<usize>) -> (usize, char) {
let word_col = col/64;
let shift = 63 - (col & (64 - 1));
let mut word = self.0[row][word_col];
let mut mask = 1 << shift;
let is_set = (word & (1 << shift)) > 0;
let mut end_col = col + 1;
let ch = if is_set { 'o' } else { 'b' };
// go to end of current word
mask >>= 1;
while mask > 0 {
if (word & mask > 0)!= is_set {
return (end_col - col, ch);
}
end_col += 1;
mask >>= 1;
}
assert_eq!(end_col % 64, 0);
// skip words
let mut end_word_col = word_col + 1;
while end_word_col < self.0[row].len() {
word = self.0[row][end_word_col];
if is_set && word < u64::max_value() {
break;
}
if!is_set && word > 0 {
break;
}
end_col += 64;
end_word_col += 1;
}
// start from beginning of last word
if end_word_col == self.0[row].len() {
return (end_col - col, ch);
}
mask = 1 << 63;
while mask > 0 {
if (word & mask > 0)!= is_set {
break;
}
end_col += 1;
mask >>= 1;
}
return (end_col - col, ch);
}
}
|
{
self.0[0].len()
}
|
conditional_block
|
grids.rs
|
/* Copyright 2017-2019 the Conwayste Developers.
*
* This file is part of libconway.
*
* libconway is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* libconway is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with libconway. If not, see <http://www.gnu.org/licenses/>. */
use std::ops::{Index, IndexMut};
use std::cmp;
use crate::universe::Region;
use crate::rle::Pattern;
#[derive(Eq, PartialEq, Debug, Clone, Copy)]
pub enum BitOperation {
Clear,
Set,
Toggle
}
#[derive(Debug, PartialEq, Clone)]
pub struct BitGrid(pub Vec<Vec<u64>>);
impl BitGrid {
/// Creates a new zero-initialized BitGrid of given dimensions.
///
/// # Panics
///
/// This function will panic if `with_in_words` or `height` are zero.
pub fn new(width_in_words: usize, height: usize) -> Self {
assert!(width_in_words!= 0);
assert!(height!= 0);
let mut rows: Vec<Vec<u64>> = Vec::with_capacity(height);
for _ in 0.. height {
let row: Vec<u64> = vec![0; width_in_words];
rows.push(row);
}
BitGrid(rows)
}
pub fn width_in_words(&self) -> usize {
if self.height() > 0 {
self.0[0].len()
} else {
0
}
}
#[inline]
pub fn modify_bits_in_word(&mut self, row: usize, word_col: usize, mask: u64, op: BitOperation) {
match op {
BitOperation::Set => self[row][word_col] |= mask,
BitOperation::Clear => self[row][word_col] &=!mask,
BitOperation::Toggle => self[row][word_col] ^= mask,
}
}
/// Sets, clears, or toggles a rectangle of bits.
///
/// # Panics
///
/// This function will panic if `region` is out of range.
pub fn modify_region(&mut self, region: Region, op: BitOperation) {
for y in region.top().. region.bottom() + 1 {
assert!(y >= 0);
for word_col in 0.. self[y as usize].len() {
let x_left = word_col * 64;
let x_right = x_left + 63;
if region.right() >= x_left as isize && region.left() <= x_right as isize {
let mut mask = u64::max_value();
for shift in (0..64).rev() {
let x = x_right - shift;
if (x as isize) < region.left() || (x as isize) > region.right() {
mask &=!(1 << shift);
}
}
// apply change to bitgrid based on mask and bit
self.modify_bits_in_word(y as usize, word_col, mask, op);
}
}
}
}
/// Returns `Some(`smallest region containing every 1 bit`)`, or `None` if there are no 1 bits.
pub fn bounding_box(&self) -> Option<Region> {
let (width, height) = (self.width(), self.height());
let mut first_row = None;
let mut last_row = None;
let mut first_col = None;
let mut last_col = None;
for row in 0..height {
let mut col = 0;
while col < width {
let (rle_len, ch) = self.get_run(col, row, None);
if ch == 'o' {
if let Some(_first_col) = first_col {
if _first_col > col {
first_col = Some(col);
}
} else {
first_col = Some(col);
}
if first_row.is_none() {
first_row = Some(row);
}
let run_last_col = col + rle_len - 1;
if let Some(_last_col) = last_col {
if _last_col < run_last_col {
last_col = Some(run_last_col);
}
} else {
last_col = Some(run_last_col);
}
last_row = Some(row);
}
col += rle_len;
}
}
if first_row.is_some() {
let width = last_col.unwrap() - first_col.unwrap() + 1;
let height = last_row.unwrap() - first_row.unwrap() + 1;
Some(Region::new(first_col.unwrap() as isize, first_row.unwrap() as isize, width, height))
} else {
None
}
}
/// Copies `src` BitGrid into `dst` BitGrid, but fit into `dst_region` with clipping. If there
/// is a 10x10 pattern in source starting at 0,0 and the dst_region is only 8x8 with top left
/// corner at 3,3 then the resulting pattern will be clipped in a 2 pixel region on the bottom
/// and right and extend from 3,3 to 10,10. If `dst_region` extends beyond `dst`, the pattern
/// will be further clipped by the dimensions of `dst`.
///
/// The bits are copied using an `|=` operation, so 1 bits in the destination will not ever be
/// cleared.
pub fn copy(src: &BitGrid, dst: &mut BitGrid, dst_region: Region) {
let dst_left = cmp::max(0, dst_region.left()) as usize;
let dst_right = cmp::min(dst.width() as isize - 1, dst_region.right()) as usize;
let dst_top = cmp::max(0, dst_region.top()) as usize;
let dst_bottom = cmp::min(dst.height() as isize - 1, dst_region.bottom()) as usize;
if dst_left > dst_right || dst_top > dst_bottom {
// nothing to do because both dimensions aren't positive
return;
}
for src_row in 0..src.height() {
let dst_row = src_row + dst_top;
if dst_row > dst_bottom {
break;
}
let mut src_col = 0; // word-aligned
while src_col < src.width() {
let dst_col = src_col + dst_left; // not word-aligned
if dst_col > dst_right {
break;
}
let dst_word_idx = dst_col / 64;
let shift = dst_col - dst_word_idx*64; // right shift amount
let mut word = src[src_row][src_col/64];
// clear bits that would be beyond dst_right
if dst_right - dst_col + 1 < 64 {
let mask =!((1u64 << (64 - (dst_right - dst_col + 1))) - 1);
word &= mask;
}
dst[dst_row][dst_word_idx] |= word >> shift;
if shift > 0 && dst_word_idx+1 < dst.width_in_words() {
dst[dst_row][dst_word_idx+1] |= word << (64 - shift);
}
src_col += 64;
}
}
}
/// Get a Region of the same size as the BitGrid.
pub fn region(&self) -> Region {
Region::new(0, 0, self.width(), self.height())
}
/// Clear this BitGrid.
pub fn clear(&mut self) {
for row in &mut self.0 {
for col_idx in 0..row.len() {
row[col_idx] = 0;
}
}
}
}
impl Index<usize> for BitGrid {
type Output = Vec<u64>;
fn index(&self, i: usize) -> &Vec<u64> {
&self.0[i]
}
}
impl IndexMut<usize> for BitGrid {
fn index_mut(&mut self, i: usize) -> &mut Vec<u64> {
&mut self.0[i]
}
}
pub trait CharGrid {
/// Write a char `ch` to (`col`, `row`).
///
/// # Panics
///
/// Panics if:
/// * `col` or `row` are out of range
/// * `char` is invalid for this type. Use `is_valid` to check first.
/// * `visibility` is invalid. That is, it equals `Some(player_id)`, but there is no such `player_id`.
fn write_at_position(&mut self, col: usize, row: usize, ch: char, visibility: Option<usize>);
/// Is `ch` a valid character?
fn is_valid(ch: char) -> bool;
/// Width in cells
fn width(&self) -> usize;
/// Height in cells
fn height(&self) -> usize;
/// Returns a Pattern that describes this `CharGrid` as viewed by specified player if
/// `visibility.is_some()`, or a fog-less view if `visibility.is_none()`.
fn to_pattern(&self, visibility: Option<usize>) -> Pattern {
fn
|
(result: &mut String, output_col: &mut usize, rle_len: usize, ch: char) {
let what_to_add = if rle_len == 1 {
let mut s = String::with_capacity(1);
s.push(ch);
s
} else { format!("{}{}", rle_len, ch) };
if *output_col + what_to_add.len() > 70 {
result.push_str("\r\n");
*output_col = 0;
}
result.push_str(what_to_add.as_str());
*output_col += what_to_add.len();
}
let mut result = "".to_owned();
let (mut col, mut row) = (0, 0);
let mut line_ends_buffered = 0;
let mut output_col = 0;
while row < self.height() {
while col < self.width() {
let (rle_len, ch) = self.get_run(col, row, visibility);
match ch {
'b' => {
// Blank
// TODO: if supporting diffs with this same algorithm, then need to allow
// other characters to serve this purpose.
if col + rle_len < self.width() {
if line_ends_buffered > 0 {
push(&mut result, &mut output_col, line_ends_buffered, '$');
line_ends_buffered = 0;
}
push(&mut result, &mut output_col, rle_len, ch);
}
}
_ => {
// Non-blank
if line_ends_buffered > 0 {
push(&mut result, &mut output_col, line_ends_buffered, '$');
line_ends_buffered = 0;
}
push(&mut result, &mut output_col, rle_len, ch);
}
}
col += rle_len;
}
row += 1;
col = 0;
line_ends_buffered += 1;
}
push(&mut result, &mut output_col, 1, '!');
Pattern(result)
}
/// Given a starting cell at `(col, row)`, get the character at that cell, and the number of
/// contiguous identical cells considering only this cell and the cells to the right of it.
/// This is intended for exporting to RLE.
///
/// The `visibility` parameter, if not `None`, is used to generate a run as observed by a
/// particular player.
///
/// # Returns
///
/// `(run_length, ch)`
///
/// # Panics
///
/// This function will panic if `col`, `row`, or `visibility` (`Some(player_id)`) are out of bounds.
fn get_run(&self, col: usize, row: usize, visibility: Option<usize>) -> (usize, char);
}
const VALID_BIT_GRID_CHARS: [char; 2] = ['b', 'o'];
impl CharGrid for BitGrid {
/// Width in cells
fn width(&self) -> usize {
self.width_in_words() * 64
}
/// Height in cells
fn height(&self) -> usize {
self.0.len()
}
/// _visibility is ignored, since BitGrids have no concept of a player.
fn write_at_position(&mut self, col: usize, row: usize, ch: char, _visibility: Option<usize>) {
let word_col = col/64;
let shift = 63 - (col & (64 - 1));
match ch {
'b' => {
self.modify_bits_in_word(row, word_col, 1 << shift, BitOperation::Clear)
}
'o' => {
self.modify_bits_in_word(row, word_col, 1 << shift, BitOperation::Set)
}
_ => panic!("invalid character: {:?}", ch)
}
}
fn is_valid(ch: char) -> bool {
VALID_BIT_GRID_CHARS.contains(&ch)
}
/// Given a starting cell at `(col, row)`, get the character at that cell, and the number of
/// contiguous identical cells considering only this cell and the cells to the right of it.
/// This is intended for exporting to RLE.
///
/// The `_visibility` argument is unused and should be `None`.
///
/// # Returns
///
/// `(run_length, ch)`
///
/// # Panics
///
/// This function will panic if `col` or `row` are out of bounds.
fn get_run(&self, col: usize, row: usize, _visibility: Option<usize>) -> (usize, char) {
let word_col = col/64;
let shift = 63 - (col & (64 - 1));
let mut word = self.0[row][word_col];
let mut mask = 1 << shift;
let is_set = (word & (1 << shift)) > 0;
let mut end_col = col + 1;
let ch = if is_set { 'o' } else { 'b' };
// go to end of current word
mask >>= 1;
while mask > 0 {
if (word & mask > 0)!= is_set {
return (end_col - col, ch);
}
end_col += 1;
mask >>= 1;
}
assert_eq!(end_col % 64, 0);
// skip words
let mut end_word_col = word_col + 1;
while end_word_col < self.0[row].len() {
word = self.0[row][end_word_col];
if is_set && word < u64::max_value() {
break;
}
if!is_set && word > 0 {
break;
}
end_col += 64;
end_word_col += 1;
}
// start from beginning of last word
if end_word_col == self.0[row].len() {
return (end_col - col, ch);
}
mask = 1 << 63;
while mask > 0 {
if (word & mask > 0)!= is_set {
break;
}
end_col += 1;
mask >>= 1;
}
return (end_col - col, ch);
}
}
|
push
|
identifier_name
|
grids.rs
|
/* Copyright 2017-2019 the Conwayste Developers.
*
* This file is part of libconway.
*
* libconway is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* libconway is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with libconway. If not, see <http://www.gnu.org/licenses/>. */
use std::ops::{Index, IndexMut};
use std::cmp;
use crate::universe::Region;
use crate::rle::Pattern;
#[derive(Eq, PartialEq, Debug, Clone, Copy)]
pub enum BitOperation {
Clear,
Set,
Toggle
}
#[derive(Debug, PartialEq, Clone)]
pub struct BitGrid(pub Vec<Vec<u64>>);
impl BitGrid {
/// Creates a new zero-initialized BitGrid of given dimensions.
///
/// # Panics
///
/// This function will panic if `with_in_words` or `height` are zero.
pub fn new(width_in_words: usize, height: usize) -> Self {
assert!(width_in_words!= 0);
assert!(height!= 0);
let mut rows: Vec<Vec<u64>> = Vec::with_capacity(height);
for _ in 0.. height {
let row: Vec<u64> = vec![0; width_in_words];
rows.push(row);
}
BitGrid(rows)
}
pub fn width_in_words(&self) -> usize {
if self.height() > 0 {
self.0[0].len()
} else {
0
}
}
#[inline]
pub fn modify_bits_in_word(&mut self, row: usize, word_col: usize, mask: u64, op: BitOperation) {
match op {
BitOperation::Set => self[row][word_col] |= mask,
BitOperation::Clear => self[row][word_col] &=!mask,
BitOperation::Toggle => self[row][word_col] ^= mask,
}
}
/// Sets, clears, or toggles a rectangle of bits.
///
/// # Panics
///
/// This function will panic if `region` is out of range.
pub fn modify_region(&mut self, region: Region, op: BitOperation) {
for y in region.top().. region.bottom() + 1 {
assert!(y >= 0);
for word_col in 0.. self[y as usize].len() {
let x_left = word_col * 64;
let x_right = x_left + 63;
if region.right() >= x_left as isize && region.left() <= x_right as isize {
let mut mask = u64::max_value();
for shift in (0..64).rev() {
let x = x_right - shift;
if (x as isize) < region.left() || (x as isize) > region.right() {
mask &=!(1 << shift);
}
}
// apply change to bitgrid based on mask and bit
self.modify_bits_in_word(y as usize, word_col, mask, op);
}
}
}
}
/// Returns `Some(`smallest region containing every 1 bit`)`, or `None` if there are no 1 bits.
pub fn bounding_box(&self) -> Option<Region> {
let (width, height) = (self.width(), self.height());
let mut first_row = None;
let mut last_row = None;
let mut first_col = None;
let mut last_col = None;
for row in 0..height {
let mut col = 0;
while col < width {
let (rle_len, ch) = self.get_run(col, row, None);
if ch == 'o' {
if let Some(_first_col) = first_col {
if _first_col > col {
first_col = Some(col);
}
} else {
first_col = Some(col);
}
if first_row.is_none() {
first_row = Some(row);
}
let run_last_col = col + rle_len - 1;
if let Some(_last_col) = last_col {
if _last_col < run_last_col {
last_col = Some(run_last_col);
}
} else {
last_col = Some(run_last_col);
}
last_row = Some(row);
}
col += rle_len;
}
}
if first_row.is_some() {
let width = last_col.unwrap() - first_col.unwrap() + 1;
let height = last_row.unwrap() - first_row.unwrap() + 1;
Some(Region::new(first_col.unwrap() as isize, first_row.unwrap() as isize, width, height))
} else {
None
}
}
/// Copies `src` BitGrid into `dst` BitGrid, but fit into `dst_region` with clipping. If there
/// is a 10x10 pattern in source starting at 0,0 and the dst_region is only 8x8 with top left
/// corner at 3,3 then the resulting pattern will be clipped in a 2 pixel region on the bottom
/// and right and extend from 3,3 to 10,10. If `dst_region` extends beyond `dst`, the pattern
/// will be further clipped by the dimensions of `dst`.
///
/// The bits are copied using an `|=` operation, so 1 bits in the destination will not ever be
/// cleared.
pub fn copy(src: &BitGrid, dst: &mut BitGrid, dst_region: Region) {
let dst_left = cmp::max(0, dst_region.left()) as usize;
let dst_right = cmp::min(dst.width() as isize - 1, dst_region.right()) as usize;
let dst_top = cmp::max(0, dst_region.top()) as usize;
let dst_bottom = cmp::min(dst.height() as isize - 1, dst_region.bottom()) as usize;
if dst_left > dst_right || dst_top > dst_bottom {
// nothing to do because both dimensions aren't positive
return;
}
for src_row in 0..src.height() {
let dst_row = src_row + dst_top;
if dst_row > dst_bottom {
break;
}
let mut src_col = 0; // word-aligned
while src_col < src.width() {
let dst_col = src_col + dst_left; // not word-aligned
if dst_col > dst_right {
break;
}
let dst_word_idx = dst_col / 64;
let shift = dst_col - dst_word_idx*64; // right shift amount
let mut word = src[src_row][src_col/64];
// clear bits that would be beyond dst_right
if dst_right - dst_col + 1 < 64 {
let mask =!((1u64 << (64 - (dst_right - dst_col + 1))) - 1);
word &= mask;
}
dst[dst_row][dst_word_idx] |= word >> shift;
if shift > 0 && dst_word_idx+1 < dst.width_in_words() {
dst[dst_row][dst_word_idx+1] |= word << (64 - shift);
}
src_col += 64;
}
}
}
/// Get a Region of the same size as the BitGrid.
pub fn region(&self) -> Region {
Region::new(0, 0, self.width(), self.height())
}
/// Clear this BitGrid.
pub fn clear(&mut self) {
for row in &mut self.0 {
for col_idx in 0..row.len() {
row[col_idx] = 0;
}
}
}
}
impl Index<usize> for BitGrid {
type Output = Vec<u64>;
fn index(&self, i: usize) -> &Vec<u64> {
&self.0[i]
}
}
impl IndexMut<usize> for BitGrid {
fn index_mut(&mut self, i: usize) -> &mut Vec<u64> {
&mut self.0[i]
}
}
pub trait CharGrid {
/// Write a char `ch` to (`col`, `row`).
///
/// # Panics
///
/// Panics if:
/// * `col` or `row` are out of range
/// * `char` is invalid for this type. Use `is_valid` to check first.
/// * `visibility` is invalid. That is, it equals `Some(player_id)`, but there is no such `player_id`.
fn write_at_position(&mut self, col: usize, row: usize, ch: char, visibility: Option<usize>);
/// Is `ch` a valid character?
fn is_valid(ch: char) -> bool;
/// Width in cells
fn width(&self) -> usize;
/// Height in cells
fn height(&self) -> usize;
/// Returns a Pattern that describes this `CharGrid` as viewed by specified player if
/// `visibility.is_some()`, or a fog-less view if `visibility.is_none()`.
fn to_pattern(&self, visibility: Option<usize>) -> Pattern {
fn push(result: &mut String, output_col: &mut usize, rle_len: usize, ch: char) {
let what_to_add = if rle_len == 1 {
let mut s = String::with_capacity(1);
s.push(ch);
s
} else { format!("{}{}", rle_len, ch) };
if *output_col + what_to_add.len() > 70 {
result.push_str("\r\n");
*output_col = 0;
}
result.push_str(what_to_add.as_str());
*output_col += what_to_add.len();
}
let mut result = "".to_owned();
let (mut col, mut row) = (0, 0);
let mut line_ends_buffered = 0;
let mut output_col = 0;
while row < self.height() {
while col < self.width() {
let (rle_len, ch) = self.get_run(col, row, visibility);
match ch {
'b' => {
// Blank
// TODO: if supporting diffs with this same algorithm, then need to allow
// other characters to serve this purpose.
if col + rle_len < self.width() {
if line_ends_buffered > 0 {
push(&mut result, &mut output_col, line_ends_buffered, '$');
line_ends_buffered = 0;
}
push(&mut result, &mut output_col, rle_len, ch);
}
}
_ => {
// Non-blank
if line_ends_buffered > 0 {
push(&mut result, &mut output_col, line_ends_buffered, '$');
line_ends_buffered = 0;
}
push(&mut result, &mut output_col, rle_len, ch);
}
}
col += rle_len;
|
}
push(&mut result, &mut output_col, 1, '!');
Pattern(result)
}
/// Given a starting cell at `(col, row)`, get the character at that cell, and the number of
/// contiguous identical cells considering only this cell and the cells to the right of it.
/// This is intended for exporting to RLE.
///
/// The `visibility` parameter, if not `None`, is used to generate a run as observed by a
/// particular player.
///
/// # Returns
///
/// `(run_length, ch)`
///
/// # Panics
///
/// This function will panic if `col`, `row`, or `visibility` (`Some(player_id)`) are out of bounds.
fn get_run(&self, col: usize, row: usize, visibility: Option<usize>) -> (usize, char);
}
const VALID_BIT_GRID_CHARS: [char; 2] = ['b', 'o'];
impl CharGrid for BitGrid {
/// Width in cells
fn width(&self) -> usize {
self.width_in_words() * 64
}
/// Height in cells
fn height(&self) -> usize {
self.0.len()
}
/// _visibility is ignored, since BitGrids have no concept of a player.
fn write_at_position(&mut self, col: usize, row: usize, ch: char, _visibility: Option<usize>) {
let word_col = col/64;
let shift = 63 - (col & (64 - 1));
match ch {
'b' => {
self.modify_bits_in_word(row, word_col, 1 << shift, BitOperation::Clear)
}
'o' => {
self.modify_bits_in_word(row, word_col, 1 << shift, BitOperation::Set)
}
_ => panic!("invalid character: {:?}", ch)
}
}
fn is_valid(ch: char) -> bool {
VALID_BIT_GRID_CHARS.contains(&ch)
}
/// Given a starting cell at `(col, row)`, get the character at that cell, and the number of
/// contiguous identical cells considering only this cell and the cells to the right of it.
/// This is intended for exporting to RLE.
///
/// The `_visibility` argument is unused and should be `None`.
///
/// # Returns
///
/// `(run_length, ch)`
///
/// # Panics
///
/// This function will panic if `col` or `row` are out of bounds.
fn get_run(&self, col: usize, row: usize, _visibility: Option<usize>) -> (usize, char) {
let word_col = col/64;
let shift = 63 - (col & (64 - 1));
let mut word = self.0[row][word_col];
let mut mask = 1 << shift;
let is_set = (word & (1 << shift)) > 0;
let mut end_col = col + 1;
let ch = if is_set { 'o' } else { 'b' };
// go to end of current word
mask >>= 1;
while mask > 0 {
if (word & mask > 0)!= is_set {
return (end_col - col, ch);
}
end_col += 1;
mask >>= 1;
}
assert_eq!(end_col % 64, 0);
// skip words
let mut end_word_col = word_col + 1;
while end_word_col < self.0[row].len() {
word = self.0[row][end_word_col];
if is_set && word < u64::max_value() {
break;
}
if!is_set && word > 0 {
break;
}
end_col += 64;
end_word_col += 1;
}
// start from beginning of last word
if end_word_col == self.0[row].len() {
return (end_col - col, ch);
}
mask = 1 << 63;
while mask > 0 {
if (word & mask > 0)!= is_set {
break;
}
end_col += 1;
mask >>= 1;
}
return (end_col - col, ch);
}
}
|
}
row += 1;
col = 0;
line_ends_buffered += 1;
|
random_line_split
|
int.rs
|
use arch::int;
pub fn mask_interrupt(i: u32, mask: bool) {
int::mask_interrupt(i, mask);
}
pub fn set_int(i: u32, idt_idx: u32) {
int::set_int(i, idt_idx);
}
pub fn fire_timer() {
int::fire_timer();
}
pub fn enable_interrupts() {
int::enable_interrupts();
}
pub fn disable_interrupts() {
int::disable_interrupts();
}
pub fn interrupt_handler(int_id: u32, error_code: u32, retaddr: usize) {
match int_id {
80 => {
println!("[ TASK ] System call from user space");
}
81 => {
println!("[ OK ] Interrupt test passes");
},
33 => println!("Keyboard interrupt detected"),
13 => {
println!("GPF 0x{:x} err: 0x{:x}", retaddr, error_code);
|
loop{};
},
_ => {
//println!("OTHER INTERRUPT {}", ctx.int_id);
//loop{};
}
}
}
|
disable_interrupts();
loop{}
}
14 => {
println!("PAGE FAULT 0x{:x}, addr: 0x{:x}", error_code, retaddr);
|
random_line_split
|
int.rs
|
use arch::int;
pub fn mask_interrupt(i: u32, mask: bool) {
int::mask_interrupt(i, mask);
}
pub fn set_int(i: u32, idt_idx: u32) {
int::set_int(i, idt_idx);
}
pub fn fire_timer()
|
pub fn enable_interrupts() {
int::enable_interrupts();
}
pub fn disable_interrupts() {
int::disable_interrupts();
}
pub fn interrupt_handler(int_id: u32, error_code: u32, retaddr: usize) {
match int_id {
80 => {
println!("[ TASK ] System call from user space");
}
81 => {
println!("[ OK ] Interrupt test passes");
},
33 => println!("Keyboard interrupt detected"),
13 => {
println!("GPF 0x{:x} err: 0x{:x}", retaddr, error_code);
disable_interrupts();
loop{}
}
14 => {
println!("PAGE FAULT 0x{:x}, addr: 0x{:x}", error_code, retaddr);
loop{};
},
_ => {
//println!("OTHER INTERRUPT {}", ctx.int_id);
//loop{};
}
}
}
|
{
int::fire_timer();
}
|
identifier_body
|
int.rs
|
use arch::int;
pub fn mask_interrupt(i: u32, mask: bool) {
int::mask_interrupt(i, mask);
}
pub fn set_int(i: u32, idt_idx: u32) {
int::set_int(i, idt_idx);
}
pub fn fire_timer() {
int::fire_timer();
}
pub fn enable_interrupts() {
int::enable_interrupts();
}
pub fn disable_interrupts() {
int::disable_interrupts();
}
pub fn interrupt_handler(int_id: u32, error_code: u32, retaddr: usize) {
match int_id {
80 => {
println!("[ TASK ] System call from user space");
}
81 => {
println!("[ OK ] Interrupt test passes");
},
33 => println!("Keyboard interrupt detected"),
13 => {
println!("GPF 0x{:x} err: 0x{:x}", retaddr, error_code);
disable_interrupts();
loop{}
}
14 => {
println!("PAGE FAULT 0x{:x}, addr: 0x{:x}", error_code, retaddr);
loop{};
},
_ =>
|
}
}
|
{
//println!("OTHER INTERRUPT {}", ctx.int_id);
//loop{};
}
|
conditional_block
|
int.rs
|
use arch::int;
pub fn mask_interrupt(i: u32, mask: bool) {
int::mask_interrupt(i, mask);
}
pub fn set_int(i: u32, idt_idx: u32) {
int::set_int(i, idt_idx);
}
pub fn fire_timer() {
int::fire_timer();
}
pub fn enable_interrupts() {
int::enable_interrupts();
}
pub fn
|
() {
int::disable_interrupts();
}
pub fn interrupt_handler(int_id: u32, error_code: u32, retaddr: usize) {
match int_id {
80 => {
println!("[ TASK ] System call from user space");
}
81 => {
println!("[ OK ] Interrupt test passes");
},
33 => println!("Keyboard interrupt detected"),
13 => {
println!("GPF 0x{:x} err: 0x{:x}", retaddr, error_code);
disable_interrupts();
loop{}
}
14 => {
println!("PAGE FAULT 0x{:x}, addr: 0x{:x}", error_code, retaddr);
loop{};
},
_ => {
//println!("OTHER INTERRUPT {}", ctx.int_id);
//loop{};
}
}
}
|
disable_interrupts
|
identifier_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.