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
stylesheet.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StyleSheetBinding; use dom::bindings::codegen::Bindings::StyleSheetBinding::StyleSheetMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::window::Window; #[dom_struct] pub struct StyleSheet { reflector_: Reflector, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, }
StyleSheet { reflector_: Reflector::new(), type_: type_, href: href, title: title } } #[allow(unrooted_must_root)] pub fn new(window: &Window, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>) -> Root<StyleSheet> { reflect_dom_object(box StyleSheet::new_inherited(type_, href, title), window, StyleSheetBinding::Wrap) } } impl StyleSheetMethods for StyleSheet { // https://drafts.csswg.org/cssom/#dom-stylesheet-type fn Type_(&self) -> DOMString { self.type_.clone() } // https://drafts.csswg.org/cssom/#dom-stylesheet-href fn GetHref(&self) -> Option<DOMString> { self.href.clone() } // https://drafts.csswg.org/cssom/#dom-stylesheet-title fn GetTitle(&self) -> Option<DOMString> { self.title.clone() } }
impl StyleSheet { #[allow(unrooted_must_root)] fn new_inherited(type_: DOMString, href: Option<DOMString>, title: Option<DOMString>) -> StyleSheet {
random_line_split
stylesheet.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StyleSheetBinding; use dom::bindings::codegen::Bindings::StyleSheetBinding::StyleSheetMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::window::Window; #[dom_struct] pub struct StyleSheet { reflector_: Reflector, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, } impl StyleSheet { #[allow(unrooted_must_root)] fn new_inherited(type_: DOMString, href: Option<DOMString>, title: Option<DOMString>) -> StyleSheet { StyleSheet { reflector_: Reflector::new(), type_: type_, href: href, title: title } } #[allow(unrooted_must_root)] pub fn new(window: &Window, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>) -> Root<StyleSheet> { reflect_dom_object(box StyleSheet::new_inherited(type_, href, title), window, StyleSheetBinding::Wrap) } } impl StyleSheetMethods for StyleSheet { // https://drafts.csswg.org/cssom/#dom-stylesheet-type fn Type_(&self) -> DOMString { self.type_.clone() } // https://drafts.csswg.org/cssom/#dom-stylesheet-href fn GetHref(&self) -> Option<DOMString> { self.href.clone() } // https://drafts.csswg.org/cssom/#dom-stylesheet-title fn
(&self) -> Option<DOMString> { self.title.clone() } }
GetTitle
identifier_name
stylesheet.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::StyleSheetBinding; use dom::bindings::codegen::Bindings::StyleSheetBinding::StyleSheetMethods; use dom::bindings::js::Root; use dom::bindings::reflector::{Reflector, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::window::Window; #[dom_struct] pub struct StyleSheet { reflector_: Reflector, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>, } impl StyleSheet { #[allow(unrooted_must_root)] fn new_inherited(type_: DOMString, href: Option<DOMString>, title: Option<DOMString>) -> StyleSheet { StyleSheet { reflector_: Reflector::new(), type_: type_, href: href, title: title } } #[allow(unrooted_must_root)] pub fn new(window: &Window, type_: DOMString, href: Option<DOMString>, title: Option<DOMString>) -> Root<StyleSheet> { reflect_dom_object(box StyleSheet::new_inherited(type_, href, title), window, StyleSheetBinding::Wrap) } } impl StyleSheetMethods for StyleSheet { // https://drafts.csswg.org/cssom/#dom-stylesheet-type fn Type_(&self) -> DOMString { self.type_.clone() } // https://drafts.csswg.org/cssom/#dom-stylesheet-href fn GetHref(&self) -> Option<DOMString>
// https://drafts.csswg.org/cssom/#dom-stylesheet-title fn GetTitle(&self) -> Option<DOMString> { self.title.clone() } }
{ self.href.clone() }
identifier_body
cabi_powerpc.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_uint; use llvm; use llvm::{Integer, Pointer, Float, Double, Struct, Array}; use llvm::{StructRetAttribute, ZExtAttribute}; use trans::cabi::{FnType, ArgType}; use trans::context::CrateContext; use trans::type_::Type; use std::cmp; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => panic!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => panic!("ty_size: unhandled type") } } fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType { if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType
} fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { Some(Type::i32(ccx)) } else { None } } fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> { let int_ty = Type::i32(ccx); let mut args = Vec::new(); let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx(), r as c_uint))); } } args } fn struct_ty(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8; Type::struct_(ccx, &coerce_to_int(ccx, size), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ArgType::direct(Type::void(ccx), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; for aty in atys { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }
{ let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = cmp::min(cmp::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::direct( ty, Some(struct_ty(ccx, ty)), padding_ty(ccx, align, orig_offset), None ) }
identifier_body
cabi_powerpc.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. //
use libc::c_uint; use llvm; use llvm::{Integer, Pointer, Float, Double, Struct, Array}; use llvm::{StructRetAttribute, ZExtAttribute}; use trans::cabi::{FnType, ArgType}; use trans::context::CrateContext; use trans::type_::Type; use std::cmp; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => panic!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => panic!("ty_size: unhandled type") } } fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType { if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = cmp::min(cmp::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::direct( ty, Some(struct_ty(ccx, ty)), padding_ty(ccx, align, orig_offset), None ) } } fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { Some(Type::i32(ccx)) } else { None } } fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> { let int_ty = Type::i32(ccx); let mut args = Vec::new(); let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx(), r as c_uint))); } } args } fn struct_ty(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8; Type::struct_(ccx, &coerce_to_int(ccx, size), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ArgType::direct(Type::void(ccx), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; for aty in atys { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }
// 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.
random_line_split
cabi_powerpc.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_uint; use llvm; use llvm::{Integer, Pointer, Float, Double, Struct, Array}; use llvm::{StructRetAttribute, ZExtAttribute}; use trans::cabi::{FnType, ArgType}; use trans::context::CrateContext; use trans::type_::Type; use std::cmp; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => panic!("ty_size: unhandled type") } } fn
(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } } Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => panic!("ty_size: unhandled type") } } fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType { if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = cmp::min(cmp::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::direct( ty, Some(struct_ty(ccx, ty)), padding_ty(ccx, align, orig_offset), None ) } } fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { Some(Type::i32(ccx)) } else { None } } fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> { let int_ty = Type::i32(ccx); let mut args = Vec::new(); let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx(), r as c_uint))); } } args } fn struct_ty(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8; Type::struct_(ccx, &coerce_to_int(ccx, size), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ArgType::direct(Type::void(ccx), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; for aty in atys { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }
ty_size
identifier_name
cabi_powerpc.rs
// Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use libc::c_uint; use llvm; use llvm::{Integer, Pointer, Float, Double, Struct, Array}; use llvm::{StructRetAttribute, ZExtAttribute}; use trans::cabi::{FnType, ArgType}; use trans::context::CrateContext; use trans::type_::Type; use std::cmp; fn align_up_to(off: uint, a: uint) -> uint { return (off + a - 1) / a * a; } fn align(off: uint, ty: Type) -> uint { let a = ty_align(ty); return align_up_to(off, a); } fn ty_align(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t))) } } Array => { let elt = ty.element_type(); ty_align(elt) } _ => panic!("ty_size: unhandled type") } } fn ty_size(ty: Type) -> uint { match ty.kind() { Integer => { unsafe { ((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8 } } Pointer => 4, Float => 4, Double => 8, Struct =>
Array => { let len = ty.array_length(); let elt = ty.element_type(); let eltsz = ty_size(elt); len * eltsz } _ => panic!("ty_size: unhandled type") } } fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType { if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::indirect(ty, Some(StructRetAttribute)) } } fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType { let orig_offset = *offset; let size = ty_size(ty) * 8; let mut align = ty_align(ty); align = cmp::min(cmp::max(align, 4), 8); *offset = align_up_to(*offset, align); *offset += align_up_to(size, align * 8) / 8; if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; ArgType::direct(ty, None, None, attr) } else { ArgType::direct( ty, Some(struct_ty(ccx, ty)), padding_ty(ccx, align, orig_offset), None ) } } fn is_reg_ty(ty: Type) -> bool { return match ty.kind() { Integer | Pointer | Float | Double => true, _ => false }; } fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> { if ((align - 1 ) & offset) > 0 { Some(Type::i32(ccx)) } else { None } } fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> { let int_ty = Type::i32(ccx); let mut args = Vec::new(); let mut n = size / 32; while n > 0 { args.push(int_ty); n -= 1; } let r = size % 32; if r > 0 { unsafe { args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx(), r as c_uint))); } } args } fn struct_ty(ccx: &CrateContext, ty: Type) -> Type { let size = ty_size(ty) * 8; Type::struct_(ccx, &coerce_to_int(ccx, size), false) } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ret_def: bool) -> FnType { let ret_ty = if ret_def { classify_ret_ty(ccx, rty) } else { ArgType::direct(Type::void(ccx), None, None, None) }; let sret = ret_ty.is_indirect(); let mut arg_tys = Vec::new(); let mut offset = if sret { 4 } else { 0 }; for aty in atys { let ty = classify_arg_ty(ccx, *aty, &mut offset); arg_tys.push(ty); }; return FnType { arg_tys: arg_tys, ret_ty: ret_ty, }; }
{ if ty.is_packed() { let str_tys = ty.field_types(); str_tys.iter().fold(0, |s, t| s + ty_size(*t)) } else { let str_tys = ty.field_types(); let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t)); align(size, ty) } }
conditional_block
borrowck-insert-during-each.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 std::collections::HashSet; struct
{ n: HashSet<isize>, } impl Foo { pub fn foo<F>(&mut self, mut fun: F) where F: FnMut(&isize) { for f in &self.n { fun(f); } } } fn bar(f: &mut Foo) { f.foo( |a| { //~ ERROR closure requires unique access to `f` f.n.insert(*a); }) } fn main() { let mut f = Foo { n: HashSet::new() }; bar(&mut f); }
Foo
identifier_name
borrowck-insert-during-each.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 std::collections::HashSet; struct Foo { n: HashSet<isize>, } impl Foo { pub fn foo<F>(&mut self, mut fun: F) where F: FnMut(&isize) { for f in &self.n { fun(f); } } } fn bar(f: &mut Foo) { f.foo( |a| { //~ ERROR closure requires unique access to `f` f.n.insert(*a); }) }
fn main() { let mut f = Foo { n: HashSet::new() }; bar(&mut f); }
random_line_split
os.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashSet; use std::rc::Rc; use syntax::ast; use syntax::codemap::{respan, DUMMY_SP}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::ext::quote::rt::ToTokens; use syntax::parse::token::intern; use syntax::ptr::P; use builder::meta_args::{ToTyHash, set_ty_params_for_task}; use node; use super::{Builder, TokenString, add_node_dependency}; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); let mcu_node = builder.pt.get_by_path("mcu").unwrap(); let maybe_task_node = node.get_by_path("single_task"); if maybe_task_node.is_some() { let task_node = maybe_task_node.unwrap(); task_node.materializer.set(Some(build_single_task as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); add_node_dependency(&node, &task_node); add_node_dependency(&task_node, &mcu_node); let maybe_args_node = task_node.get_by_path("args"); if maybe_args_node.is_some() { let args_node = maybe_args_node.unwrap(); for (_, ref attr) in args_node.attributes.borrow().iter() { match attr.value { node::RefValue(ref refname) => { let refnode = builder.pt.get_by_name(refname.as_str()).unwrap(); add_node_dependency(&task_node, &refnode); }, _ => (), } } } } } pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { node.expect_no_attributes(cx); node.expect_subnodes(cx, &["single_task"]); if node.get_by_path("single_task").is_none() { cx.parse_sess().span_diagnostic.span_err(node.name_span, "subnode `single_task` must be present"); } } fn build_single_task(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { let some_loop_fn = node.get_required_string_attr(cx, "loop"); match some_loop_fn { Some(loop_fn) => { let args_node = node.get_by_path("args"); let args = match args_node.and_then(|args| { Some(build_args(builder, cx, &loop_fn, args)) }) { None => vec!(), Some(arg) => vec!(arg), }; let call_expr = cx.expr_call_ident( node.get_attr("loop").value_span, cx.ident_of(loop_fn.as_str()), args); let loop_stmt = quote_stmt!(&*cx, loop { $call_expr; } ).unwrap(); builder.add_main_statement(loop_stmt); }, None => (), } } fn build_args(builder: &mut Builder, cx: &mut ExtCtxt, struct_name: &String, node: Rc<node::Node>) -> P<ast::Expr> { let mut fields = vec!(); let mut expr_fields = vec!(); let node_attr = node.attributes.borrow(); let mut ty_params = HashSet::new(); // this is a bit slower than for (k, v) in node.attributes.iter(), but we need // to preserve sort order to make reasonably simple test code let mut all_keys = Vec::new(); for k in node_attr.keys() { all_keys.push(k.clone()) }; all_keys.sort(); for k in all_keys.iter() { let v = &(*node_attr)[k];
node::IntValue(i) => (cx.ty_ident(DUMMY_SP, cx.ident_of("u32")), quote_expr!(&*cx, $i)), node::BoolValue(b) => (cx.ty_ident(DUMMY_SP, cx.ident_of("bool")), quote_expr!(&*cx, $b)), node::StrValue(ref string) => { let static_lifetime = cx.lifetime(DUMMY_SP, intern("'static")); let val_slice = string.as_str(); (cx.ty_rptr( DUMMY_SP, cx.ty_ident(DUMMY_SP, cx.ident_of("str")), Some(static_lifetime), ast::MutImmutable), quote_expr!(&*cx, $val_slice)) }, node::RefValue(ref rname) => { let refnode = builder.pt.get_by_name(rname.as_str()).unwrap(); let reftype = refnode.type_name().unwrap(); let refparams = refnode.type_params(); for param in refparams.iter() { if!param.as_str().starts_with("'") { ty_params.insert(param.clone()); } } let val_slice = TokenString(rname.clone()); let a_lifetime = cx.lifetime(DUMMY_SP, intern("'a")); (cx.ty_rptr( DUMMY_SP, cx.ty_path(type_name_as_path(cx, reftype.as_str(), refparams)), Some(a_lifetime), ast::MutImmutable), quote_expr!(&*cx, &$val_slice)) }, }; let name_ident = cx.ident_of(k.as_str()); let sf = ast::StructField_ { kind: ast::NamedField(name_ident, ast::Public), id: ast::DUMMY_NODE_ID, ty: ty, attrs: vec!(), }; fields.push(respan(DUMMY_SP, sf)); expr_fields.push(cx.field_imm(DUMMY_SP, name_ident, val)); } let name_ident = cx.ident_of(format!("{}_args", struct_name).as_str()); let mut collected_params = vec!(); let mut ty_params_vec = vec!(); for ty in ty_params.iter() { let typaram = cx.typaram( DUMMY_SP, cx.ident_of(ty.to_tyhash().as_str()), P::from_vec(vec!( ast::RegionTyParamBound(cx.lifetime(DUMMY_SP, intern("'a"))) )), None); collected_params.push(typaram); ty_params_vec.push(ty.clone()); } set_ty_params_for_task(cx, struct_name.as_str(), ty_params_vec); let struct_item = P(ast::Item { ident: name_ident, attrs: vec!(), id: ast::DUMMY_NODE_ID, node: ast::ItemStruct( ast::VariantData::Struct(fields, ast::DUMMY_NODE_ID), ast::Generics { lifetimes: vec!(cx.lifetime_def(DUMMY_SP, intern("'a"), vec!())), ty_params: P::from_vec(collected_params), where_clause: ast::WhereClause { id: ast::DUMMY_NODE_ID, predicates: vec!(), } }), vis: ast::Public, span: DUMMY_SP, }); builder.add_type_item(struct_item); cx.expr_addr_of(DUMMY_SP, cx.expr_struct( DUMMY_SP, cx.path(DUMMY_SP, vec!(cx.ident_of("pt"), name_ident)), expr_fields)) } fn type_name_as_path(cx: &ExtCtxt, ty: &str, params: Vec<String>) -> ast::Path { let mut lifetimes = vec!(); let mut types = vec!(); for p in params.iter() { let slice = p.as_str(); if slice.starts_with("'") { let lifetime = cx.lifetime(DUMMY_SP, intern(slice)); lifetimes.push(lifetime); } else { let path = cx.ty_path(type_name_as_path(cx, p.to_tyhash().as_str(), vec!())); types.push(path); } } cx.path_all(DUMMY_SP, false, ty.split("::").map(|t| cx.ident_of(t)).collect(), lifetimes, types, vec!()) } #[cfg(test)] mod test { use std::ops::Deref; use syntax::codemap::DUMMY_SP; use syntax::ext::build::AstBuilder; use builder::Builder; use super::build_single_task; use test_helpers::{assert_equal_source, with_parsed}; #[test] fn builds_single_task_os_loop() { with_parsed(" single_task { loop = \"run\"; }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); build_single_task(&mut builder, cx, pt.get_by_path("single_task").unwrap().clone()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts.len() == 1); assert_equal_source(builder.main_stmts[0].deref(), "loop { run(); }"); }); } #[test] fn builds_single_task_with_args() { with_parsed(" single_task { loop = \"run\"; args { a = 1; b = \"a\"; c = &named; } } named@ref; ", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); pt.get_by_path("ref").unwrap().set_type_name("hello::world::Struct".to_string()); build_single_task(&mut builder, cx, pt.get_by_path("single_task").unwrap().clone()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts.len() == 1); assert!(builder.type_items.len() == 2); // XXX: builder.type_items[0] is `use zinc;` now assert_equal_source(cx.stmt_item(DUMMY_SP, builder.type_items[1].clone()).deref(), "pub struct run_args<'a> { pub a: u32, pub b: &'static str, pub c: &'a hello::world::Struct, }"); assert_equal_source(builder.main_stmts[0].deref(), "loop { run(&pt::run_args { a: 1usize, b: \"a\", c: &named, }); }"); }); } }
let (ty, val) = match v.value {
random_line_split
os.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashSet; use std::rc::Rc; use syntax::ast; use syntax::codemap::{respan, DUMMY_SP}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::ext::quote::rt::ToTokens; use syntax::parse::token::intern; use syntax::ptr::P; use builder::meta_args::{ToTyHash, set_ty_params_for_task}; use node; use super::{Builder, TokenString, add_node_dependency}; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); let mcu_node = builder.pt.get_by_path("mcu").unwrap(); let maybe_task_node = node.get_by_path("single_task"); if maybe_task_node.is_some() { let task_node = maybe_task_node.unwrap(); task_node.materializer.set(Some(build_single_task as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); add_node_dependency(&node, &task_node); add_node_dependency(&task_node, &mcu_node); let maybe_args_node = task_node.get_by_path("args"); if maybe_args_node.is_some() { let args_node = maybe_args_node.unwrap(); for (_, ref attr) in args_node.attributes.borrow().iter() { match attr.value { node::RefValue(ref refname) => { let refnode = builder.pt.get_by_name(refname.as_str()).unwrap(); add_node_dependency(&task_node, &refnode); }, _ => (), } } } } } pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { node.expect_no_attributes(cx); node.expect_subnodes(cx, &["single_task"]); if node.get_by_path("single_task").is_none() { cx.parse_sess().span_diagnostic.span_err(node.name_span, "subnode `single_task` must be present"); } } fn build_single_task(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { let some_loop_fn = node.get_required_string_attr(cx, "loop"); match some_loop_fn { Some(loop_fn) => { let args_node = node.get_by_path("args"); let args = match args_node.and_then(|args| { Some(build_args(builder, cx, &loop_fn, args)) }) { None => vec!(), Some(arg) => vec!(arg), }; let call_expr = cx.expr_call_ident( node.get_attr("loop").value_span, cx.ident_of(loop_fn.as_str()), args); let loop_stmt = quote_stmt!(&*cx, loop { $call_expr; } ).unwrap(); builder.add_main_statement(loop_stmt); }, None => (), } } fn build_args(builder: &mut Builder, cx: &mut ExtCtxt, struct_name: &String, node: Rc<node::Node>) -> P<ast::Expr> { let mut fields = vec!(); let mut expr_fields = vec!(); let node_attr = node.attributes.borrow(); let mut ty_params = HashSet::new(); // this is a bit slower than for (k, v) in node.attributes.iter(), but we need // to preserve sort order to make reasonably simple test code let mut all_keys = Vec::new(); for k in node_attr.keys() { all_keys.push(k.clone()) }; all_keys.sort(); for k in all_keys.iter() { let v = &(*node_attr)[k]; let (ty, val) = match v.value { node::IntValue(i) => (cx.ty_ident(DUMMY_SP, cx.ident_of("u32")), quote_expr!(&*cx, $i)), node::BoolValue(b) => (cx.ty_ident(DUMMY_SP, cx.ident_of("bool")), quote_expr!(&*cx, $b)), node::StrValue(ref string) => { let static_lifetime = cx.lifetime(DUMMY_SP, intern("'static")); let val_slice = string.as_str(); (cx.ty_rptr( DUMMY_SP, cx.ty_ident(DUMMY_SP, cx.ident_of("str")), Some(static_lifetime), ast::MutImmutable), quote_expr!(&*cx, $val_slice)) }, node::RefValue(ref rname) => { let refnode = builder.pt.get_by_name(rname.as_str()).unwrap(); let reftype = refnode.type_name().unwrap(); let refparams = refnode.type_params(); for param in refparams.iter() { if!param.as_str().starts_with("'") { ty_params.insert(param.clone()); } } let val_slice = TokenString(rname.clone()); let a_lifetime = cx.lifetime(DUMMY_SP, intern("'a")); (cx.ty_rptr( DUMMY_SP, cx.ty_path(type_name_as_path(cx, reftype.as_str(), refparams)), Some(a_lifetime), ast::MutImmutable), quote_expr!(&*cx, &$val_slice)) }, }; let name_ident = cx.ident_of(k.as_str()); let sf = ast::StructField_ { kind: ast::NamedField(name_ident, ast::Public), id: ast::DUMMY_NODE_ID, ty: ty, attrs: vec!(), }; fields.push(respan(DUMMY_SP, sf)); expr_fields.push(cx.field_imm(DUMMY_SP, name_ident, val)); } let name_ident = cx.ident_of(format!("{}_args", struct_name).as_str()); let mut collected_params = vec!(); let mut ty_params_vec = vec!(); for ty in ty_params.iter() { let typaram = cx.typaram( DUMMY_SP, cx.ident_of(ty.to_tyhash().as_str()), P::from_vec(vec!( ast::RegionTyParamBound(cx.lifetime(DUMMY_SP, intern("'a"))) )), None); collected_params.push(typaram); ty_params_vec.push(ty.clone()); } set_ty_params_for_task(cx, struct_name.as_str(), ty_params_vec); let struct_item = P(ast::Item { ident: name_ident, attrs: vec!(), id: ast::DUMMY_NODE_ID, node: ast::ItemStruct( ast::VariantData::Struct(fields, ast::DUMMY_NODE_ID), ast::Generics { lifetimes: vec!(cx.lifetime_def(DUMMY_SP, intern("'a"), vec!())), ty_params: P::from_vec(collected_params), where_clause: ast::WhereClause { id: ast::DUMMY_NODE_ID, predicates: vec!(), } }), vis: ast::Public, span: DUMMY_SP, }); builder.add_type_item(struct_item); cx.expr_addr_of(DUMMY_SP, cx.expr_struct( DUMMY_SP, cx.path(DUMMY_SP, vec!(cx.ident_of("pt"), name_ident)), expr_fields)) } fn
(cx: &ExtCtxt, ty: &str, params: Vec<String>) -> ast::Path { let mut lifetimes = vec!(); let mut types = vec!(); for p in params.iter() { let slice = p.as_str(); if slice.starts_with("'") { let lifetime = cx.lifetime(DUMMY_SP, intern(slice)); lifetimes.push(lifetime); } else { let path = cx.ty_path(type_name_as_path(cx, p.to_tyhash().as_str(), vec!())); types.push(path); } } cx.path_all(DUMMY_SP, false, ty.split("::").map(|t| cx.ident_of(t)).collect(), lifetimes, types, vec!()) } #[cfg(test)] mod test { use std::ops::Deref; use syntax::codemap::DUMMY_SP; use syntax::ext::build::AstBuilder; use builder::Builder; use super::build_single_task; use test_helpers::{assert_equal_source, with_parsed}; #[test] fn builds_single_task_os_loop() { with_parsed(" single_task { loop = \"run\"; }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); build_single_task(&mut builder, cx, pt.get_by_path("single_task").unwrap().clone()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts.len() == 1); assert_equal_source(builder.main_stmts[0].deref(), "loop { run(); }"); }); } #[test] fn builds_single_task_with_args() { with_parsed(" single_task { loop = \"run\"; args { a = 1; b = \"a\"; c = &named; } } named@ref; ", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); pt.get_by_path("ref").unwrap().set_type_name("hello::world::Struct".to_string()); build_single_task(&mut builder, cx, pt.get_by_path("single_task").unwrap().clone()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts.len() == 1); assert!(builder.type_items.len() == 2); // XXX: builder.type_items[0] is `use zinc;` now assert_equal_source(cx.stmt_item(DUMMY_SP, builder.type_items[1].clone()).deref(), "pub struct run_args<'a> { pub a: u32, pub b: &'static str, pub c: &'a hello::world::Struct, }"); assert_equal_source(builder.main_stmts[0].deref(), "loop { run(&pt::run_args { a: 1usize, b: \"a\", c: &named, }); }"); }); } }
type_name_as_path
identifier_name
os.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashSet; use std::rc::Rc; use syntax::ast; use syntax::codemap::{respan, DUMMY_SP}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::ext::quote::rt::ToTokens; use syntax::parse::token::intern; use syntax::ptr::P; use builder::meta_args::{ToTyHash, set_ty_params_for_task}; use node; use super::{Builder, TokenString, add_node_dependency}; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); let mcu_node = builder.pt.get_by_path("mcu").unwrap(); let maybe_task_node = node.get_by_path("single_task"); if maybe_task_node.is_some() { let task_node = maybe_task_node.unwrap(); task_node.materializer.set(Some(build_single_task as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); add_node_dependency(&node, &task_node); add_node_dependency(&task_node, &mcu_node); let maybe_args_node = task_node.get_by_path("args"); if maybe_args_node.is_some() { let args_node = maybe_args_node.unwrap(); for (_, ref attr) in args_node.attributes.borrow().iter() { match attr.value { node::RefValue(ref refname) => { let refnode = builder.pt.get_by_name(refname.as_str()).unwrap(); add_node_dependency(&task_node, &refnode); }, _ => (), } } } } } pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { node.expect_no_attributes(cx); node.expect_subnodes(cx, &["single_task"]); if node.get_by_path("single_task").is_none() { cx.parse_sess().span_diagnostic.span_err(node.name_span, "subnode `single_task` must be present"); } } fn build_single_task(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { let some_loop_fn = node.get_required_string_attr(cx, "loop"); match some_loop_fn { Some(loop_fn) => { let args_node = node.get_by_path("args"); let args = match args_node.and_then(|args| { Some(build_args(builder, cx, &loop_fn, args)) }) { None => vec!(), Some(arg) => vec!(arg), }; let call_expr = cx.expr_call_ident( node.get_attr("loop").value_span, cx.ident_of(loop_fn.as_str()), args); let loop_stmt = quote_stmt!(&*cx, loop { $call_expr; } ).unwrap(); builder.add_main_statement(loop_stmt); }, None => (), } } fn build_args(builder: &mut Builder, cx: &mut ExtCtxt, struct_name: &String, node: Rc<node::Node>) -> P<ast::Expr> { let mut fields = vec!(); let mut expr_fields = vec!(); let node_attr = node.attributes.borrow(); let mut ty_params = HashSet::new(); // this is a bit slower than for (k, v) in node.attributes.iter(), but we need // to preserve sort order to make reasonably simple test code let mut all_keys = Vec::new(); for k in node_attr.keys() { all_keys.push(k.clone()) }; all_keys.sort(); for k in all_keys.iter() { let v = &(*node_attr)[k]; let (ty, val) = match v.value { node::IntValue(i) => (cx.ty_ident(DUMMY_SP, cx.ident_of("u32")), quote_expr!(&*cx, $i)), node::BoolValue(b) => (cx.ty_ident(DUMMY_SP, cx.ident_of("bool")), quote_expr!(&*cx, $b)), node::StrValue(ref string) => { let static_lifetime = cx.lifetime(DUMMY_SP, intern("'static")); let val_slice = string.as_str(); (cx.ty_rptr( DUMMY_SP, cx.ty_ident(DUMMY_SP, cx.ident_of("str")), Some(static_lifetime), ast::MutImmutable), quote_expr!(&*cx, $val_slice)) }, node::RefValue(ref rname) => { let refnode = builder.pt.get_by_name(rname.as_str()).unwrap(); let reftype = refnode.type_name().unwrap(); let refparams = refnode.type_params(); for param in refparams.iter() { if!param.as_str().starts_with("'")
} let val_slice = TokenString(rname.clone()); let a_lifetime = cx.lifetime(DUMMY_SP, intern("'a")); (cx.ty_rptr( DUMMY_SP, cx.ty_path(type_name_as_path(cx, reftype.as_str(), refparams)), Some(a_lifetime), ast::MutImmutable), quote_expr!(&*cx, &$val_slice)) }, }; let name_ident = cx.ident_of(k.as_str()); let sf = ast::StructField_ { kind: ast::NamedField(name_ident, ast::Public), id: ast::DUMMY_NODE_ID, ty: ty, attrs: vec!(), }; fields.push(respan(DUMMY_SP, sf)); expr_fields.push(cx.field_imm(DUMMY_SP, name_ident, val)); } let name_ident = cx.ident_of(format!("{}_args", struct_name).as_str()); let mut collected_params = vec!(); let mut ty_params_vec = vec!(); for ty in ty_params.iter() { let typaram = cx.typaram( DUMMY_SP, cx.ident_of(ty.to_tyhash().as_str()), P::from_vec(vec!( ast::RegionTyParamBound(cx.lifetime(DUMMY_SP, intern("'a"))) )), None); collected_params.push(typaram); ty_params_vec.push(ty.clone()); } set_ty_params_for_task(cx, struct_name.as_str(), ty_params_vec); let struct_item = P(ast::Item { ident: name_ident, attrs: vec!(), id: ast::DUMMY_NODE_ID, node: ast::ItemStruct( ast::VariantData::Struct(fields, ast::DUMMY_NODE_ID), ast::Generics { lifetimes: vec!(cx.lifetime_def(DUMMY_SP, intern("'a"), vec!())), ty_params: P::from_vec(collected_params), where_clause: ast::WhereClause { id: ast::DUMMY_NODE_ID, predicates: vec!(), } }), vis: ast::Public, span: DUMMY_SP, }); builder.add_type_item(struct_item); cx.expr_addr_of(DUMMY_SP, cx.expr_struct( DUMMY_SP, cx.path(DUMMY_SP, vec!(cx.ident_of("pt"), name_ident)), expr_fields)) } fn type_name_as_path(cx: &ExtCtxt, ty: &str, params: Vec<String>) -> ast::Path { let mut lifetimes = vec!(); let mut types = vec!(); for p in params.iter() { let slice = p.as_str(); if slice.starts_with("'") { let lifetime = cx.lifetime(DUMMY_SP, intern(slice)); lifetimes.push(lifetime); } else { let path = cx.ty_path(type_name_as_path(cx, p.to_tyhash().as_str(), vec!())); types.push(path); } } cx.path_all(DUMMY_SP, false, ty.split("::").map(|t| cx.ident_of(t)).collect(), lifetimes, types, vec!()) } #[cfg(test)] mod test { use std::ops::Deref; use syntax::codemap::DUMMY_SP; use syntax::ext::build::AstBuilder; use builder::Builder; use super::build_single_task; use test_helpers::{assert_equal_source, with_parsed}; #[test] fn builds_single_task_os_loop() { with_parsed(" single_task { loop = \"run\"; }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); build_single_task(&mut builder, cx, pt.get_by_path("single_task").unwrap().clone()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts.len() == 1); assert_equal_source(builder.main_stmts[0].deref(), "loop { run(); }"); }); } #[test] fn builds_single_task_with_args() { with_parsed(" single_task { loop = \"run\"; args { a = 1; b = \"a\"; c = &named; } } named@ref; ", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); pt.get_by_path("ref").unwrap().set_type_name("hello::world::Struct".to_string()); build_single_task(&mut builder, cx, pt.get_by_path("single_task").unwrap().clone()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts.len() == 1); assert!(builder.type_items.len() == 2); // XXX: builder.type_items[0] is `use zinc;` now assert_equal_source(cx.stmt_item(DUMMY_SP, builder.type_items[1].clone()).deref(), "pub struct run_args<'a> { pub a: u32, pub b: &'static str, pub c: &'a hello::world::Struct, }"); assert_equal_source(builder.main_stmts[0].deref(), "loop { run(&pt::run_args { a: 1usize, b: \"a\", c: &named, }); }"); }); } }
{ ty_params.insert(param.clone()); }
conditional_block
os.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashSet; use std::rc::Rc; use syntax::ast; use syntax::codemap::{respan, DUMMY_SP}; use syntax::ext::base::ExtCtxt; use syntax::ext::build::AstBuilder; use syntax::ext::quote::rt::ToTokens; use syntax::parse::token::intern; use syntax::ptr::P; use builder::meta_args::{ToTyHash, set_ty_params_for_task}; use node; use super::{Builder, TokenString, add_node_dependency}; pub fn attach(builder: &mut Builder, _: &mut ExtCtxt, node: Rc<node::Node>) { node.materializer.set(Some(verify as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); let mcu_node = builder.pt.get_by_path("mcu").unwrap(); let maybe_task_node = node.get_by_path("single_task"); if maybe_task_node.is_some() { let task_node = maybe_task_node.unwrap(); task_node.materializer.set(Some(build_single_task as fn(&mut Builder, &mut ExtCtxt, Rc<node::Node>))); add_node_dependency(&node, &task_node); add_node_dependency(&task_node, &mcu_node); let maybe_args_node = task_node.get_by_path("args"); if maybe_args_node.is_some() { let args_node = maybe_args_node.unwrap(); for (_, ref attr) in args_node.attributes.borrow().iter() { match attr.value { node::RefValue(ref refname) => { let refnode = builder.pt.get_by_name(refname.as_str()).unwrap(); add_node_dependency(&task_node, &refnode); }, _ => (), } } } } } pub fn verify(_: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>) { node.expect_no_attributes(cx); node.expect_subnodes(cx, &["single_task"]); if node.get_by_path("single_task").is_none() { cx.parse_sess().span_diagnostic.span_err(node.name_span, "subnode `single_task` must be present"); } } fn build_single_task(builder: &mut Builder, cx: &mut ExtCtxt, node: Rc<node::Node>)
} } fn build_args(builder: &mut Builder, cx: &mut ExtCtxt, struct_name: &String, node: Rc<node::Node>) -> P<ast::Expr> { let mut fields = vec!(); let mut expr_fields = vec!(); let node_attr = node.attributes.borrow(); let mut ty_params = HashSet::new(); // this is a bit slower than for (k, v) in node.attributes.iter(), but we need // to preserve sort order to make reasonably simple test code let mut all_keys = Vec::new(); for k in node_attr.keys() { all_keys.push(k.clone()) }; all_keys.sort(); for k in all_keys.iter() { let v = &(*node_attr)[k]; let (ty, val) = match v.value { node::IntValue(i) => (cx.ty_ident(DUMMY_SP, cx.ident_of("u32")), quote_expr!(&*cx, $i)), node::BoolValue(b) => (cx.ty_ident(DUMMY_SP, cx.ident_of("bool")), quote_expr!(&*cx, $b)), node::StrValue(ref string) => { let static_lifetime = cx.lifetime(DUMMY_SP, intern("'static")); let val_slice = string.as_str(); (cx.ty_rptr( DUMMY_SP, cx.ty_ident(DUMMY_SP, cx.ident_of("str")), Some(static_lifetime), ast::MutImmutable), quote_expr!(&*cx, $val_slice)) }, node::RefValue(ref rname) => { let refnode = builder.pt.get_by_name(rname.as_str()).unwrap(); let reftype = refnode.type_name().unwrap(); let refparams = refnode.type_params(); for param in refparams.iter() { if!param.as_str().starts_with("'") { ty_params.insert(param.clone()); } } let val_slice = TokenString(rname.clone()); let a_lifetime = cx.lifetime(DUMMY_SP, intern("'a")); (cx.ty_rptr( DUMMY_SP, cx.ty_path(type_name_as_path(cx, reftype.as_str(), refparams)), Some(a_lifetime), ast::MutImmutable), quote_expr!(&*cx, &$val_slice)) }, }; let name_ident = cx.ident_of(k.as_str()); let sf = ast::StructField_ { kind: ast::NamedField(name_ident, ast::Public), id: ast::DUMMY_NODE_ID, ty: ty, attrs: vec!(), }; fields.push(respan(DUMMY_SP, sf)); expr_fields.push(cx.field_imm(DUMMY_SP, name_ident, val)); } let name_ident = cx.ident_of(format!("{}_args", struct_name).as_str()); let mut collected_params = vec!(); let mut ty_params_vec = vec!(); for ty in ty_params.iter() { let typaram = cx.typaram( DUMMY_SP, cx.ident_of(ty.to_tyhash().as_str()), P::from_vec(vec!( ast::RegionTyParamBound(cx.lifetime(DUMMY_SP, intern("'a"))) )), None); collected_params.push(typaram); ty_params_vec.push(ty.clone()); } set_ty_params_for_task(cx, struct_name.as_str(), ty_params_vec); let struct_item = P(ast::Item { ident: name_ident, attrs: vec!(), id: ast::DUMMY_NODE_ID, node: ast::ItemStruct( ast::VariantData::Struct(fields, ast::DUMMY_NODE_ID), ast::Generics { lifetimes: vec!(cx.lifetime_def(DUMMY_SP, intern("'a"), vec!())), ty_params: P::from_vec(collected_params), where_clause: ast::WhereClause { id: ast::DUMMY_NODE_ID, predicates: vec!(), } }), vis: ast::Public, span: DUMMY_SP, }); builder.add_type_item(struct_item); cx.expr_addr_of(DUMMY_SP, cx.expr_struct( DUMMY_SP, cx.path(DUMMY_SP, vec!(cx.ident_of("pt"), name_ident)), expr_fields)) } fn type_name_as_path(cx: &ExtCtxt, ty: &str, params: Vec<String>) -> ast::Path { let mut lifetimes = vec!(); let mut types = vec!(); for p in params.iter() { let slice = p.as_str(); if slice.starts_with("'") { let lifetime = cx.lifetime(DUMMY_SP, intern(slice)); lifetimes.push(lifetime); } else { let path = cx.ty_path(type_name_as_path(cx, p.to_tyhash().as_str(), vec!())); types.push(path); } } cx.path_all(DUMMY_SP, false, ty.split("::").map(|t| cx.ident_of(t)).collect(), lifetimes, types, vec!()) } #[cfg(test)] mod test { use std::ops::Deref; use syntax::codemap::DUMMY_SP; use syntax::ext::build::AstBuilder; use builder::Builder; use super::build_single_task; use test_helpers::{assert_equal_source, with_parsed}; #[test] fn builds_single_task_os_loop() { with_parsed(" single_task { loop = \"run\"; }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); build_single_task(&mut builder, cx, pt.get_by_path("single_task").unwrap().clone()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts.len() == 1); assert_equal_source(builder.main_stmts[0].deref(), "loop { run(); }"); }); } #[test] fn builds_single_task_with_args() { with_parsed(" single_task { loop = \"run\"; args { a = 1; b = \"a\"; c = &named; } } named@ref; ", |cx, failed, pt| { let mut builder = Builder::new(pt.clone(), cx); pt.get_by_path("ref").unwrap().set_type_name("hello::world::Struct".to_string()); build_single_task(&mut builder, cx, pt.get_by_path("single_task").unwrap().clone()); assert!(unsafe{*failed} == false); assert!(builder.main_stmts.len() == 1); assert!(builder.type_items.len() == 2); // XXX: builder.type_items[0] is `use zinc;` now assert_equal_source(cx.stmt_item(DUMMY_SP, builder.type_items[1].clone()).deref(), "pub struct run_args<'a> { pub a: u32, pub b: &'static str, pub c: &'a hello::world::Struct, }"); assert_equal_source(builder.main_stmts[0].deref(), "loop { run(&pt::run_args { a: 1usize, b: \"a\", c: &named, }); }"); }); } }
{ let some_loop_fn = node.get_required_string_attr(cx, "loop"); match some_loop_fn { Some(loop_fn) => { let args_node = node.get_by_path("args"); let args = match args_node.and_then(|args| { Some(build_args(builder, cx, &loop_fn, args)) }) { None => vec!(), Some(arg) => vec!(arg), }; let call_expr = cx.expr_call_ident( node.get_attr("loop").value_span, cx.ident_of(loop_fn.as_str()), args); let loop_stmt = quote_stmt!(&*cx, loop { $call_expr; } ).unwrap(); builder.add_main_statement(loop_stmt); }, None => (),
identifier_body
sleep.rs
#![crate_name = "sleep"] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; use std::io::Write; use std::thread::sleep_ms; use std::u32::MAX as U32_MAX; #[path = "../common/util.rs"]
static NAME: &'static str = "sleep"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("{}", f); return 1; } }; if matches.opt_present("help") { let msg = format!("{0} {1} Usage: {0} NUMBER[SUFFIX] or {0} OPTION Pause for NUMBER seconds. SUFFIX may be's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations that require NUMBER be an integer, here NUMBER may be an arbitrary floating point number. Given two or more arguments, pause for the amount of time specified by the sum of their values.", NAME, VERSION); print!("{}", opts.usage(&msg)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else if matches.free.is_empty() { show_error!("missing an argument"); show_error!("for help, try '{0} --help'", NAME); return 1; } else { sleep(matches.free); } 0 } fn sleep(args: Vec<String>) { let sleep_time = args.iter().fold(0.0, |result, arg| match parse_time::from_str(&arg[..]) { Ok(m) => m + result, Err(f) => crash!(1, "{}", f), }); let sleep_dur = if sleep_time > (U32_MAX as f64) { U32_MAX } else { (1000.0 * sleep_time) as u32 }; sleep_ms(sleep_dur); }
#[macro_use] mod util; #[path = "../common/parse_time.rs"] mod parse_time;
random_line_split
sleep.rs
#![crate_name = "sleep"] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; use std::io::Write; use std::thread::sleep_ms; use std::u32::MAX as U32_MAX; #[path = "../common/util.rs"] #[macro_use] mod util; #[path = "../common/parse_time.rs"] mod parse_time; static NAME: &'static str = "sleep"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("{}", f); return 1; } }; if matches.opt_present("help") { let msg = format!("{0} {1} Usage: {0} NUMBER[SUFFIX] or {0} OPTION Pause for NUMBER seconds. SUFFIX may be's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations that require NUMBER be an integer, here NUMBER may be an arbitrary floating point number. Given two or more arguments, pause for the amount of time specified by the sum of their values.", NAME, VERSION); print!("{}", opts.usage(&msg)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else if matches.free.is_empty() { show_error!("missing an argument"); show_error!("for help, try '{0} --help'", NAME); return 1; } else { sleep(matches.free); } 0 } fn
(args: Vec<String>) { let sleep_time = args.iter().fold(0.0, |result, arg| match parse_time::from_str(&arg[..]) { Ok(m) => m + result, Err(f) => crash!(1, "{}", f), }); let sleep_dur = if sleep_time > (U32_MAX as f64) { U32_MAX } else { (1000.0 * sleep_time) as u32 }; sleep_ms(sleep_dur); }
sleep
identifier_name
sleep.rs
#![crate_name = "sleep"] /* * This file is part of the uutils coreutils package. * * (c) Arcterus <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ extern crate getopts; extern crate libc; use std::io::Write; use std::thread::sleep_ms; use std::u32::MAX as U32_MAX; #[path = "../common/util.rs"] #[macro_use] mod util; #[path = "../common/parse_time.rs"] mod parse_time; static NAME: &'static str = "sleep"; static VERSION: &'static str = "1.0.0"; pub fn uumain(args: Vec<String>) -> i32
Pause for NUMBER seconds. SUFFIX may be's' for seconds (the default), 'm' for minutes, 'h' for hours or 'd' for days. Unlike most implementations that require NUMBER be an integer, here NUMBER may be an arbitrary floating point number. Given two or more arguments, pause for the amount of time specified by the sum of their values.", NAME, VERSION); print!("{}", opts.usage(&msg)); } else if matches.opt_present("version") { println!("{} {}", NAME, VERSION); } else if matches.free.is_empty() { show_error!("missing an argument"); show_error!("for help, try '{0} --help'", NAME); return 1; } else { sleep(matches.free); } 0 } fn sleep(args: Vec<String>) { let sleep_time = args.iter().fold(0.0, |result, arg| match parse_time::from_str(&arg[..]) { Ok(m) => m + result, Err(f) => crash!(1, "{}", f), }); let sleep_dur = if sleep_time > (U32_MAX as f64) { U32_MAX } else { (1000.0 * sleep_time) as u32 }; sleep_ms(sleep_dur); }
{ let mut opts = getopts::Options::new(); opts.optflag("h", "help", "display this help and exit"); opts.optflag("V", "version", "output version information and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { show_error!("{}", f); return 1; } }; if matches.opt_present("help") { let msg = format!("{0} {1} Usage: {0} NUMBER[SUFFIX] or {0} OPTION
identifier_body
htmldialogelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLDialogElementBinding; use dom::bindings::codegen::Bindings::HTMLDialogElementBinding::HTMLDialogElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLDialogElement { htmlelement: HTMLElement, return_value: DOMRefCell<DOMString>, } impl HTMLDialogElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLDialogElement { HTMLDialogElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), return_value: DOMRefCell::new(DOMString::new()), } } #[allow(unrooted_must_root)] pub fn
(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Root<HTMLDialogElement> { Node::reflect_node(box HTMLDialogElement::new_inherited(local_name, prefix, document), document, HTMLDialogElementBinding::Wrap) } } impl HTMLDialogElementMethods for HTMLDialogElement { // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_getter!(Open, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_setter!(SetOpen, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn ReturnValue(&self) -> DOMString { let return_value = self.return_value.borrow(); return_value.clone() } // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn SetReturnValue(&self, return_value: DOMString) { *self.return_value.borrow_mut() = return_value; } // https://html.spec.whatwg.org/multipage/#dom-dialog-close fn Close(&self, return_value: Option<DOMString>) { let element = self.upcast::<Element>(); let target = self.upcast::<EventTarget>(); let win = window_from_node(self); // Step 1 & 2 if element.remove_attribute(&ns!(), &local_name!("open")).is_none() { return; } // Step 3 if let Some(new_value) = return_value { *self.return_value.borrow_mut() = new_value; } // TODO: Step 4 implement pending dialog stack removal // Step 5 win.dom_manipulation_task_source().queue_simple_event(target, atom!("close"), &win); } }
new
identifier_name
htmldialogelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLDialogElementBinding; use dom::bindings::codegen::Bindings::HTMLDialogElementBinding::HTMLDialogElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLDialogElement { htmlelement: HTMLElement, return_value: DOMRefCell<DOMString>, } impl HTMLDialogElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLDialogElement { HTMLDialogElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), return_value: DOMRefCell::new(DOMString::new()), } }
#[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Root<HTMLDialogElement> { Node::reflect_node(box HTMLDialogElement::new_inherited(local_name, prefix, document), document, HTMLDialogElementBinding::Wrap) } } impl HTMLDialogElementMethods for HTMLDialogElement { // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_getter!(Open, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_setter!(SetOpen, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn ReturnValue(&self) -> DOMString { let return_value = self.return_value.borrow(); return_value.clone() } // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn SetReturnValue(&self, return_value: DOMString) { *self.return_value.borrow_mut() = return_value; } // https://html.spec.whatwg.org/multipage/#dom-dialog-close fn Close(&self, return_value: Option<DOMString>) { let element = self.upcast::<Element>(); let target = self.upcast::<EventTarget>(); let win = window_from_node(self); // Step 1 & 2 if element.remove_attribute(&ns!(), &local_name!("open")).is_none() { return; } // Step 3 if let Some(new_value) = return_value { *self.return_value.borrow_mut() = new_value; } // TODO: Step 4 implement pending dialog stack removal // Step 5 win.dom_manipulation_task_source().queue_simple_event(target, atom!("close"), &win); } }
random_line_split
htmldialogelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::HTMLDialogElementBinding; use dom::bindings::codegen::Bindings::HTMLDialogElementBinding::HTMLDialogElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::js::Root; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::Element; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{Node, window_from_node}; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLDialogElement { htmlelement: HTMLElement, return_value: DOMRefCell<DOMString>, } impl HTMLDialogElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLDialogElement { HTMLDialogElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), return_value: DOMRefCell::new(DOMString::new()), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> Root<HTMLDialogElement> { Node::reflect_node(box HTMLDialogElement::new_inherited(local_name, prefix, document), document, HTMLDialogElementBinding::Wrap) } } impl HTMLDialogElementMethods for HTMLDialogElement { // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_getter!(Open, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-open make_bool_setter!(SetOpen, "open"); // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn ReturnValue(&self) -> DOMString { let return_value = self.return_value.borrow(); return_value.clone() } // https://html.spec.whatwg.org/multipage/#dom-dialog-returnvalue fn SetReturnValue(&self, return_value: DOMString) { *self.return_value.borrow_mut() = return_value; } // https://html.spec.whatwg.org/multipage/#dom-dialog-close fn Close(&self, return_value: Option<DOMString>) { let element = self.upcast::<Element>(); let target = self.upcast::<EventTarget>(); let win = window_from_node(self); // Step 1 & 2 if element.remove_attribute(&ns!(), &local_name!("open")).is_none()
// Step 3 if let Some(new_value) = return_value { *self.return_value.borrow_mut() = new_value; } // TODO: Step 4 implement pending dialog stack removal // Step 5 win.dom_manipulation_task_source().queue_simple_event(target, atom!("close"), &win); } }
{ return; }
conditional_block
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 = "unsize")] #[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 /// 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")] #[deprecated(since = "1.2.0", reason = "structs are by default not copyable")] #[lang = "no_copy_bound"] #[allow(deprecated)] #[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 a raw 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(reflect_marker)] /// 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 = "reflect_marker", 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
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 = "unsize")] #[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 /// 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")] #[deprecated(since = "1.2.0", reason = "structs are by default not copyable")] #[lang = "no_copy_bound"] #[allow(deprecated)] #[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 a raw 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(reflect_marker)] /// 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 = "reflect_marker", 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
main.rs
use std::str::FromStr; fn group_by_sum(packages: &[usize], target: usize) -> Vec<Vec<usize>> { let mut results = Vec::new(); struct Iter<'a> { f: &'a Fn(&mut Iter, usize, usize, Vec<usize>) -> (), results: &'a mut Vec<Vec<usize>> } { let mut iter = Iter {results: &mut results, f: &|iter, index, so_far, current|{ if so_far == target {
iter.results.push(current.clone()); } else if index < packages.len() { if packages[index] <= target - so_far { let mut current = current.clone(); current.push(index); (iter.f)(iter, index + 1, so_far + packages[index], current); } (iter.f)(iter, index + 1, so_far, current); } }}; (iter.f)(&mut iter, 0, 0, Vec::new()); } results } fn intersects(a: &Vec<usize>, b: &Vec<usize>) -> bool { a.iter().any(|x| b.contains(x)) } fn quantum_entanglement(xs: &Vec<usize>) -> usize { xs.iter().fold(1, |acc, x| acc * x) } fn split_into_groups(packages: &Vec<usize>, target_weight: usize) -> Vec<Vec<usize>> { let mut grouped_by_sum: Vec<Vec<usize>> = group_by_sum(&packages, target_weight) .iter() // assuming that values are unique. .map(|combination| combination.iter().map(|i| packages[*i]).collect()) .collect(); grouped_by_sum.sort_by(|a, b| (a.len(), quantum_entanglement(a)).cmp(&(b.len(), quantum_entanglement(b)))); grouped_by_sum } fn main() { let input = include_str!("../input.txt"); let packages: Vec<_> = input.lines().map(|i|usize::from_str(i).unwrap()).rev().collect(); let sum = packages.iter().fold(0, |acc, x| acc + x); let target = sum / 3; let grouped_by_sum = split_into_groups(&packages, target); for group in grouped_by_sum.iter() { if grouped_by_sum.iter().any(|another| intersects(group, another)){ println!("Part 1. Min quantum entanglement: {}", quantum_entanglement(&group)); break; } } let target = sum / 4; let grouped_by_sum = split_into_groups(&packages, target); 'outer: for first in grouped_by_sum.iter() { for second in grouped_by_sum.iter() { for third in grouped_by_sum.iter() { if!intersects(first, second) && !intersects(second, third) && !intersects(third, first) { println!("Part 2. Min quantum entanglement: {}", quantum_entanglement(&first)); break 'outer; } } } } }
random_line_split
main.rs
use std::str::FromStr; fn group_by_sum(packages: &[usize], target: usize) -> Vec<Vec<usize>> { let mut results = Vec::new(); struct Iter<'a> { f: &'a Fn(&mut Iter, usize, usize, Vec<usize>) -> (), results: &'a mut Vec<Vec<usize>> } { let mut iter = Iter {results: &mut results, f: &|iter, index, so_far, current|{ if so_far == target { iter.results.push(current.clone()); } else if index < packages.len() { if packages[index] <= target - so_far { let mut current = current.clone(); current.push(index); (iter.f)(iter, index + 1, so_far + packages[index], current); } (iter.f)(iter, index + 1, so_far, current); } }}; (iter.f)(&mut iter, 0, 0, Vec::new()); } results } fn intersects(a: &Vec<usize>, b: &Vec<usize>) -> bool
fn quantum_entanglement(xs: &Vec<usize>) -> usize { xs.iter().fold(1, |acc, x| acc * x) } fn split_into_groups(packages: &Vec<usize>, target_weight: usize) -> Vec<Vec<usize>> { let mut grouped_by_sum: Vec<Vec<usize>> = group_by_sum(&packages, target_weight) .iter() // assuming that values are unique. .map(|combination| combination.iter().map(|i| packages[*i]).collect()) .collect(); grouped_by_sum.sort_by(|a, b| (a.len(), quantum_entanglement(a)).cmp(&(b.len(), quantum_entanglement(b)))); grouped_by_sum } fn main() { let input = include_str!("../input.txt"); let packages: Vec<_> = input.lines().map(|i|usize::from_str(i).unwrap()).rev().collect(); let sum = packages.iter().fold(0, |acc, x| acc + x); let target = sum / 3; let grouped_by_sum = split_into_groups(&packages, target); for group in grouped_by_sum.iter() { if grouped_by_sum.iter().any(|another| intersects(group, another)){ println!("Part 1. Min quantum entanglement: {}", quantum_entanglement(&group)); break; } } let target = sum / 4; let grouped_by_sum = split_into_groups(&packages, target); 'outer: for first in grouped_by_sum.iter() { for second in grouped_by_sum.iter() { for third in grouped_by_sum.iter() { if!intersects(first, second) && !intersects(second, third) && !intersects(third, first) { println!("Part 2. Min quantum entanglement: {}", quantum_entanglement(&first)); break 'outer; } } } } }
{ a.iter().any(|x| b.contains(x)) }
identifier_body
main.rs
use std::str::FromStr; fn group_by_sum(packages: &[usize], target: usize) -> Vec<Vec<usize>> { let mut results = Vec::new(); struct Iter<'a> { f: &'a Fn(&mut Iter, usize, usize, Vec<usize>) -> (), results: &'a mut Vec<Vec<usize>> } { let mut iter = Iter {results: &mut results, f: &|iter, index, so_far, current|{ if so_far == target { iter.results.push(current.clone()); } else if index < packages.len() { if packages[index] <= target - so_far { let mut current = current.clone(); current.push(index); (iter.f)(iter, index + 1, so_far + packages[index], current); } (iter.f)(iter, index + 1, so_far, current); } }}; (iter.f)(&mut iter, 0, 0, Vec::new()); } results } fn intersects(a: &Vec<usize>, b: &Vec<usize>) -> bool { a.iter().any(|x| b.contains(x)) } fn quantum_entanglement(xs: &Vec<usize>) -> usize { xs.iter().fold(1, |acc, x| acc * x) } fn split_into_groups(packages: &Vec<usize>, target_weight: usize) -> Vec<Vec<usize>> { let mut grouped_by_sum: Vec<Vec<usize>> = group_by_sum(&packages, target_weight) .iter() // assuming that values are unique. .map(|combination| combination.iter().map(|i| packages[*i]).collect()) .collect(); grouped_by_sum.sort_by(|a, b| (a.len(), quantum_entanglement(a)).cmp(&(b.len(), quantum_entanglement(b)))); grouped_by_sum } fn
() { let input = include_str!("../input.txt"); let packages: Vec<_> = input.lines().map(|i|usize::from_str(i).unwrap()).rev().collect(); let sum = packages.iter().fold(0, |acc, x| acc + x); let target = sum / 3; let grouped_by_sum = split_into_groups(&packages, target); for group in grouped_by_sum.iter() { if grouped_by_sum.iter().any(|another| intersects(group, another)){ println!("Part 1. Min quantum entanglement: {}", quantum_entanglement(&group)); break; } } let target = sum / 4; let grouped_by_sum = split_into_groups(&packages, target); 'outer: for first in grouped_by_sum.iter() { for second in grouped_by_sum.iter() { for third in grouped_by_sum.iter() { if!intersects(first, second) && !intersects(second, third) && !intersects(third, first) { println!("Part 2. Min quantum entanglement: {}", quantum_entanglement(&first)); break 'outer; } } } } }
main
identifier_name
main.rs
use std::str::FromStr; fn group_by_sum(packages: &[usize], target: usize) -> Vec<Vec<usize>> { let mut results = Vec::new(); struct Iter<'a> { f: &'a Fn(&mut Iter, usize, usize, Vec<usize>) -> (), results: &'a mut Vec<Vec<usize>> } { let mut iter = Iter {results: &mut results, f: &|iter, index, so_far, current|{ if so_far == target { iter.results.push(current.clone()); } else if index < packages.len() { if packages[index] <= target - so_far { let mut current = current.clone(); current.push(index); (iter.f)(iter, index + 1, so_far + packages[index], current); } (iter.f)(iter, index + 1, so_far, current); } }}; (iter.f)(&mut iter, 0, 0, Vec::new()); } results } fn intersects(a: &Vec<usize>, b: &Vec<usize>) -> bool { a.iter().any(|x| b.contains(x)) } fn quantum_entanglement(xs: &Vec<usize>) -> usize { xs.iter().fold(1, |acc, x| acc * x) } fn split_into_groups(packages: &Vec<usize>, target_weight: usize) -> Vec<Vec<usize>> { let mut grouped_by_sum: Vec<Vec<usize>> = group_by_sum(&packages, target_weight) .iter() // assuming that values are unique. .map(|combination| combination.iter().map(|i| packages[*i]).collect()) .collect(); grouped_by_sum.sort_by(|a, b| (a.len(), quantum_entanglement(a)).cmp(&(b.len(), quantum_entanglement(b)))); grouped_by_sum } fn main() { let input = include_str!("../input.txt"); let packages: Vec<_> = input.lines().map(|i|usize::from_str(i).unwrap()).rev().collect(); let sum = packages.iter().fold(0, |acc, x| acc + x); let target = sum / 3; let grouped_by_sum = split_into_groups(&packages, target); for group in grouped_by_sum.iter() { if grouped_by_sum.iter().any(|another| intersects(group, another))
} let target = sum / 4; let grouped_by_sum = split_into_groups(&packages, target); 'outer: for first in grouped_by_sum.iter() { for second in grouped_by_sum.iter() { for third in grouped_by_sum.iter() { if!intersects(first, second) && !intersects(second, third) && !intersects(third, first) { println!("Part 2. Min quantum entanglement: {}", quantum_entanglement(&first)); break 'outer; } } } } }
{ println!("Part 1. Min quantum entanglement: {}", quantum_entanglement(&group)); break; }
conditional_block
self-impl.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. // Test that we can use `Self` types in impls in the expected way. #![allow(unknown_features)] #![feature(box_syntax)] struct Foo; // Test uses on inherent impl. impl Foo { fn foo(_x: Self, _y: &Self, _z: Box<Self>) -> Self {
Foo } } // Test uses when implementing a trait and with a type parameter. pub struct Baz<X> { pub f: X, } trait Bar<X> { fn bar(x: Self, y: &Self, z: Box<Self>) -> Self; fn dummy(&self, x: X) { } } impl Bar<int> for Box<Baz<int>> { fn bar(_x: Self, _y: &Self, _z: Box<Self>) -> Self { box Baz { f: 42 } } } fn main() { let _: Foo = Foo::foo(Foo, &Foo, box Foo); let _: Box<Baz<int>> = Bar::bar(box Baz { f: 42 }, &box Baz { f: 42 }, box box Baz { f: 42 }); }
random_line_split
self-impl.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. // Test that we can use `Self` types in impls in the expected way. #![allow(unknown_features)] #![feature(box_syntax)] struct Foo; // Test uses on inherent impl. impl Foo { fn foo(_x: Self, _y: &Self, _z: Box<Self>) -> Self { Foo } } // Test uses when implementing a trait and with a type parameter. pub struct Baz<X> { pub f: X, } trait Bar<X> { fn bar(x: Self, y: &Self, z: Box<Self>) -> Self; fn dummy(&self, x: X)
} impl Bar<int> for Box<Baz<int>> { fn bar(_x: Self, _y: &Self, _z: Box<Self>) -> Self { box Baz { f: 42 } } } fn main() { let _: Foo = Foo::foo(Foo, &Foo, box Foo); let _: Box<Baz<int>> = Bar::bar(box Baz { f: 42 }, &box Baz { f: 42 }, box box Baz { f: 42 }); }
{ }
identifier_body
self-impl.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. // Test that we can use `Self` types in impls in the expected way. #![allow(unknown_features)] #![feature(box_syntax)] struct Foo; // Test uses on inherent impl. impl Foo { fn foo(_x: Self, _y: &Self, _z: Box<Self>) -> Self { Foo } } // Test uses when implementing a trait and with a type parameter. pub struct Baz<X> { pub f: X, } trait Bar<X> { fn bar(x: Self, y: &Self, z: Box<Self>) -> Self; fn
(&self, x: X) { } } impl Bar<int> for Box<Baz<int>> { fn bar(_x: Self, _y: &Self, _z: Box<Self>) -> Self { box Baz { f: 42 } } } fn main() { let _: Foo = Foo::foo(Foo, &Foo, box Foo); let _: Box<Baz<int>> = Bar::bar(box Baz { f: 42 }, &box Baz { f: 42 }, box box Baz { f: 42 }); }
dummy
identifier_name
lib.rs
pub struct
{ rows: Vec<Vec<u32>> } impl PascalsTriangle { fn next_row(current_row: &Vec<u32>) -> Vec<u32> { let mut row1 = current_row.clone(); let mut row2 = current_row.clone(); row1.push(0); row1.reverse(); row2.push(0); row1.iter().zip(row2).map(|(x, y)| x+y).collect() } pub fn new(row_count: u32) -> Self { let mut rows: Vec<Vec<u32>> = Vec::new(); let mut current = vec![1]; for i in 0..row_count { rows.push(current.clone()); current = PascalsTriangle::next_row(&current); }; PascalsTriangle{rows: rows} } pub fn rows(self) -> Vec<Vec<u32>> { self.rows } }
PascalsTriangle
identifier_name
lib.rs
pub struct PascalsTriangle { rows: Vec<Vec<u32>> } impl PascalsTriangle { fn next_row(current_row: &Vec<u32>) -> Vec<u32> { let mut row1 = current_row.clone(); let mut row2 = current_row.clone(); row1.push(0); row1.reverse(); row2.push(0); row1.iter().zip(row2).map(|(x, y)| x+y).collect() } pub fn new(row_count: u32) -> Self
pub fn rows(self) -> Vec<Vec<u32>> { self.rows } }
{ let mut rows: Vec<Vec<u32>> = Vec::new(); let mut current = vec![1]; for i in 0..row_count { rows.push(current.clone()); current = PascalsTriangle::next_row(&current); }; PascalsTriangle{rows: rows} }
identifier_body
lib.rs
pub struct PascalsTriangle { rows: Vec<Vec<u32>> } impl PascalsTriangle { fn next_row(current_row: &Vec<u32>) -> Vec<u32> { let mut row1 = current_row.clone(); let mut row2 = current_row.clone(); row1.push(0); row1.reverse(); row2.push(0); row1.iter().zip(row2).map(|(x, y)| x+y).collect() } pub fn new(row_count: u32) -> Self { let mut rows: Vec<Vec<u32>> = Vec::new(); let mut current = vec![1];
rows.push(current.clone()); current = PascalsTriangle::next_row(&current); }; PascalsTriangle{rows: rows} } pub fn rows(self) -> Vec<Vec<u32>> { self.rows } }
for i in 0..row_count {
random_line_split
ref_with_cost.rs
//! A reference packed with a cost value. use std::cmp::Ordering; /// A reference packed with a cost value. pub struct RefWithCost<'a, N, T: 'a> { /// The reference to an object. pub object: &'a T, /// The cost of the object. pub cost: N } impl<'a, N, T> RefWithCost<'a, N, T> { /// Creates a new reference packed with a cost value. #[inline] pub fn new(object: &'a T, cost: N) -> RefWithCost<'a, N, T> { RefWithCost { object: object, cost: cost } } } impl<'a, N: PartialEq, T> PartialEq for RefWithCost<'a, N, T> { #[inline] fn eq(&self, other: &RefWithCost<'a, N, T>) -> bool { self.cost.eq(&other.cost) } } impl<'a, N: PartialEq, T> Eq for RefWithCost<'a, N, T> { } impl<'a, N: PartialOrd, T> PartialOrd for RefWithCost<'a, N, T> { #[inline] fn partial_cmp(&self, other: &RefWithCost<'a, N, T>) -> Option<Ordering> { self.cost.partial_cmp(&other.cost) } } impl<'a, N: PartialOrd, T> Ord for RefWithCost<'a, N, T> { #[inline] fn
(&self, other: &RefWithCost<'a, N, T>) -> Ordering { if self.cost < other.cost { Ordering::Less } else if self.cost > other.cost { Ordering::Greater } else { Ordering::Equal } } }
cmp
identifier_name
ref_with_cost.rs
//! A reference packed with a cost value. use std::cmp::Ordering; /// A reference packed with a cost value. pub struct RefWithCost<'a, N, T: 'a> { /// The reference to an object. pub object: &'a T, /// The cost of the object. pub cost: N } impl<'a, N, T> RefWithCost<'a, N, T> { /// Creates a new reference packed with a cost value. #[inline] pub fn new(object: &'a T, cost: N) -> RefWithCost<'a, N, T> { RefWithCost { object: object, cost: cost } } } impl<'a, N: PartialEq, T> PartialEq for RefWithCost<'a, N, T> { #[inline] fn eq(&self, other: &RefWithCost<'a, N, T>) -> bool { self.cost.eq(&other.cost) } } impl<'a, N: PartialEq, T> Eq for RefWithCost<'a, N, T> { } impl<'a, N: PartialOrd, T> PartialOrd for RefWithCost<'a, N, T> { #[inline] fn partial_cmp(&self, other: &RefWithCost<'a, N, T>) -> Option<Ordering> { self.cost.partial_cmp(&other.cost) } } impl<'a, N: PartialOrd, T> Ord for RefWithCost<'a, N, T> { #[inline] fn cmp(&self, other: &RefWithCost<'a, N, T>) -> Ordering { if self.cost < other.cost
else if self.cost > other.cost { Ordering::Greater } else { Ordering::Equal } } }
{ Ordering::Less }
conditional_block
ref_with_cost.rs
//! A reference packed with a cost value. use std::cmp::Ordering; /// A reference packed with a cost value. pub struct RefWithCost<'a, N, T: 'a> { /// The reference to an object. pub object: &'a T, /// The cost of the object. pub cost: N } impl<'a, N, T> RefWithCost<'a, N, T> { /// Creates a new reference packed with a cost value. #[inline] pub fn new(object: &'a T, cost: N) -> RefWithCost<'a, N, T> { RefWithCost { object: object, cost: cost } } }
#[inline] fn eq(&self, other: &RefWithCost<'a, N, T>) -> bool { self.cost.eq(&other.cost) } } impl<'a, N: PartialEq, T> Eq for RefWithCost<'a, N, T> { } impl<'a, N: PartialOrd, T> PartialOrd for RefWithCost<'a, N, T> { #[inline] fn partial_cmp(&self, other: &RefWithCost<'a, N, T>) -> Option<Ordering> { self.cost.partial_cmp(&other.cost) } } impl<'a, N: PartialOrd, T> Ord for RefWithCost<'a, N, T> { #[inline] fn cmp(&self, other: &RefWithCost<'a, N, T>) -> Ordering { if self.cost < other.cost { Ordering::Less } else if self.cost > other.cost { Ordering::Greater } else { Ordering::Equal } } }
impl<'a, N: PartialEq, T> PartialEq for RefWithCost<'a, N, T> {
random_line_split
player.rs
use graphics::math::{ Scalar, Matrix2d }; use piston_window::{ G2d }; use operation::Operation; use game::Context; pub const DEFAULT_LENGTH: Scalar = 150.0; pub const LENGTH_RANGE: Scalar = 240.0; const LENGTH_TRANS_STEP: i32 = 200; pub const DEFAULT_Y: Scalar = 0.95; const MAX_Y: Scalar = 0.95; const MIN_Y: Scalar = 0.5; const MOVE: Scalar = 0.4; const FRICTION: Scalar = 0.95; pub const HEIGHT: Scalar = 10.0; const COLOR: [f32; 4] = [0.8, 0.8, 0.9, 0.8]; pub struct Player { pub pos: [Scalar; 2], pub vec: [Scalar; 2], pub length: Scalar, pub length_trans: Scalar, pub length_trans_step: i32, } impl Player { pub fn new(con: Context) -> Self { Player { pos: [(con.width / 2) as Scalar, con.height as f64 * DEFAULT_Y], vec: [0.0, 0.0], length: DEFAULT_LENGTH, length_trans: 0.0, length_trans_step: 0, } } fn transform(&mut self) { if self.length_trans_step!= 0 { self.length_trans_step -= 1; self.length += (self.length_trans - self.length) / LENGTH_TRANS_STEP as Scalar; } } pub fn transform_length(&mut self, trans: Scalar) { self.length_trans_step = LENGTH_TRANS_STEP; self.length_trans = trans; } pub fn update(&mut self, con: &Context) -> &mut Self { self.transform(); self.pos = [self.pos[0] + self.vec[0], self.pos[1] + self.vec[1]]; for v in &mut self.vec { *v = *v * FRICTION; } if self.pos[1] < con.height as f64 * MIN_Y { self.pos[1] = con.height as f64 * MIN_Y;
} if self.pos[1] > con.height as f64 * MAX_Y { self.pos[1] = con.height as f64 * MAX_Y; self.vec[1] = 0.; } self } pub fn press(&mut self, op: &Operation) { use operation::{ Operation, Direction, }; match op { &Operation::Move(Direction::Left) => { self.vec = [self.vec[0] - MOVE, self.vec[1]]; }, &Operation::Move(Direction::Right) => { self.vec = [self.vec[0] + MOVE, self.vec[1]]; }, &Operation::Move(Direction::Up) => { self.vec = [self.vec[0], self.vec[1] - MOVE]; }, &Operation::Move(Direction::Down) => { self.vec = [self.vec[0], self.vec[1] + MOVE]; }, _ => {}, } } pub fn draw(&self, t: Matrix2d, g: &mut G2d) { use figure; figure::rect(self.pos[0] - self.length / 2.0, self.pos[1], self.length, HEIGHT, COLOR, t, g); } }
self.vec[1] = 0.;
random_line_split
player.rs
use graphics::math::{ Scalar, Matrix2d }; use piston_window::{ G2d }; use operation::Operation; use game::Context; pub const DEFAULT_LENGTH: Scalar = 150.0; pub const LENGTH_RANGE: Scalar = 240.0; const LENGTH_TRANS_STEP: i32 = 200; pub const DEFAULT_Y: Scalar = 0.95; const MAX_Y: Scalar = 0.95; const MIN_Y: Scalar = 0.5; const MOVE: Scalar = 0.4; const FRICTION: Scalar = 0.95; pub const HEIGHT: Scalar = 10.0; const COLOR: [f32; 4] = [0.8, 0.8, 0.9, 0.8]; pub struct Player { pub pos: [Scalar; 2], pub vec: [Scalar; 2], pub length: Scalar, pub length_trans: Scalar, pub length_trans_step: i32, } impl Player { pub fn new(con: Context) -> Self { Player { pos: [(con.width / 2) as Scalar, con.height as f64 * DEFAULT_Y], vec: [0.0, 0.0], length: DEFAULT_LENGTH, length_trans: 0.0, length_trans_step: 0, } } fn transform(&mut self) { if self.length_trans_step!= 0 { self.length_trans_step -= 1; self.length += (self.length_trans - self.length) / LENGTH_TRANS_STEP as Scalar; } } pub fn transform_length(&mut self, trans: Scalar) { self.length_trans_step = LENGTH_TRANS_STEP; self.length_trans = trans; } pub fn update(&mut self, con: &Context) -> &mut Self { self.transform(); self.pos = [self.pos[0] + self.vec[0], self.pos[1] + self.vec[1]]; for v in &mut self.vec { *v = *v * FRICTION; } if self.pos[1] < con.height as f64 * MIN_Y { self.pos[1] = con.height as f64 * MIN_Y; self.vec[1] = 0.; } if self.pos[1] > con.height as f64 * MAX_Y { self.pos[1] = con.height as f64 * MAX_Y; self.vec[1] = 0.; } self } pub fn press(&mut self, op: &Operation) { use operation::{ Operation, Direction, }; match op { &Operation::Move(Direction::Left) =>
, &Operation::Move(Direction::Right) => { self.vec = [self.vec[0] + MOVE, self.vec[1]]; }, &Operation::Move(Direction::Up) => { self.vec = [self.vec[0], self.vec[1] - MOVE]; }, &Operation::Move(Direction::Down) => { self.vec = [self.vec[0], self.vec[1] + MOVE]; }, _ => {}, } } pub fn draw(&self, t: Matrix2d, g: &mut G2d) { use figure; figure::rect(self.pos[0] - self.length / 2.0, self.pos[1], self.length, HEIGHT, COLOR, t, g); } }
{ self.vec = [self.vec[0] - MOVE, self.vec[1]]; }
conditional_block
player.rs
use graphics::math::{ Scalar, Matrix2d }; use piston_window::{ G2d }; use operation::Operation; use game::Context; pub const DEFAULT_LENGTH: Scalar = 150.0; pub const LENGTH_RANGE: Scalar = 240.0; const LENGTH_TRANS_STEP: i32 = 200; pub const DEFAULT_Y: Scalar = 0.95; const MAX_Y: Scalar = 0.95; const MIN_Y: Scalar = 0.5; const MOVE: Scalar = 0.4; const FRICTION: Scalar = 0.95; pub const HEIGHT: Scalar = 10.0; const COLOR: [f32; 4] = [0.8, 0.8, 0.9, 0.8]; pub struct Player { pub pos: [Scalar; 2], pub vec: [Scalar; 2], pub length: Scalar, pub length_trans: Scalar, pub length_trans_step: i32, } impl Player { pub fn new(con: Context) -> Self { Player { pos: [(con.width / 2) as Scalar, con.height as f64 * DEFAULT_Y], vec: [0.0, 0.0], length: DEFAULT_LENGTH, length_trans: 0.0, length_trans_step: 0, } } fn transform(&mut self) { if self.length_trans_step!= 0 { self.length_trans_step -= 1; self.length += (self.length_trans - self.length) / LENGTH_TRANS_STEP as Scalar; } } pub fn transform_length(&mut self, trans: Scalar) { self.length_trans_step = LENGTH_TRANS_STEP; self.length_trans = trans; } pub fn
(&mut self, con: &Context) -> &mut Self { self.transform(); self.pos = [self.pos[0] + self.vec[0], self.pos[1] + self.vec[1]]; for v in &mut self.vec { *v = *v * FRICTION; } if self.pos[1] < con.height as f64 * MIN_Y { self.pos[1] = con.height as f64 * MIN_Y; self.vec[1] = 0.; } if self.pos[1] > con.height as f64 * MAX_Y { self.pos[1] = con.height as f64 * MAX_Y; self.vec[1] = 0.; } self } pub fn press(&mut self, op: &Operation) { use operation::{ Operation, Direction, }; match op { &Operation::Move(Direction::Left) => { self.vec = [self.vec[0] - MOVE, self.vec[1]]; }, &Operation::Move(Direction::Right) => { self.vec = [self.vec[0] + MOVE, self.vec[1]]; }, &Operation::Move(Direction::Up) => { self.vec = [self.vec[0], self.vec[1] - MOVE]; }, &Operation::Move(Direction::Down) => { self.vec = [self.vec[0], self.vec[1] + MOVE]; }, _ => {}, } } pub fn draw(&self, t: Matrix2d, g: &mut G2d) { use figure; figure::rect(self.pos[0] - self.length / 2.0, self.pos[1], self.length, HEIGHT, COLOR, t, g); } }
update
identifier_name
player.rs
use graphics::math::{ Scalar, Matrix2d }; use piston_window::{ G2d }; use operation::Operation; use game::Context; pub const DEFAULT_LENGTH: Scalar = 150.0; pub const LENGTH_RANGE: Scalar = 240.0; const LENGTH_TRANS_STEP: i32 = 200; pub const DEFAULT_Y: Scalar = 0.95; const MAX_Y: Scalar = 0.95; const MIN_Y: Scalar = 0.5; const MOVE: Scalar = 0.4; const FRICTION: Scalar = 0.95; pub const HEIGHT: Scalar = 10.0; const COLOR: [f32; 4] = [0.8, 0.8, 0.9, 0.8]; pub struct Player { pub pos: [Scalar; 2], pub vec: [Scalar; 2], pub length: Scalar, pub length_trans: Scalar, pub length_trans_step: i32, } impl Player { pub fn new(con: Context) -> Self
fn transform(&mut self) { if self.length_trans_step!= 0 { self.length_trans_step -= 1; self.length += (self.length_trans - self.length) / LENGTH_TRANS_STEP as Scalar; } } pub fn transform_length(&mut self, trans: Scalar) { self.length_trans_step = LENGTH_TRANS_STEP; self.length_trans = trans; } pub fn update(&mut self, con: &Context) -> &mut Self { self.transform(); self.pos = [self.pos[0] + self.vec[0], self.pos[1] + self.vec[1]]; for v in &mut self.vec { *v = *v * FRICTION; } if self.pos[1] < con.height as f64 * MIN_Y { self.pos[1] = con.height as f64 * MIN_Y; self.vec[1] = 0.; } if self.pos[1] > con.height as f64 * MAX_Y { self.pos[1] = con.height as f64 * MAX_Y; self.vec[1] = 0.; } self } pub fn press(&mut self, op: &Operation) { use operation::{ Operation, Direction, }; match op { &Operation::Move(Direction::Left) => { self.vec = [self.vec[0] - MOVE, self.vec[1]]; }, &Operation::Move(Direction::Right) => { self.vec = [self.vec[0] + MOVE, self.vec[1]]; }, &Operation::Move(Direction::Up) => { self.vec = [self.vec[0], self.vec[1] - MOVE]; }, &Operation::Move(Direction::Down) => { self.vec = [self.vec[0], self.vec[1] + MOVE]; }, _ => {}, } } pub fn draw(&self, t: Matrix2d, g: &mut G2d) { use figure; figure::rect(self.pos[0] - self.length / 2.0, self.pos[1], self.length, HEIGHT, COLOR, t, g); } }
{ Player { pos: [(con.width / 2) as Scalar, con.height as f64 * DEFAULT_Y], vec: [0.0, 0.0], length: DEFAULT_LENGTH, length_trans: 0.0, length_trans_step: 0, } }
identifier_body
mod.rs
// Copyright 2017-2021 int08h LLC // // 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. //! //! Ways to configure the Roughenough server. //! //! The [ServerConfig](trait.ServerConfig.html) trait specifies the required and optional //! parameters available for configuring a Roughenoguh server instance. //! //! Implementations of `ServerConfig` obtain configurations from different back-end sources //! such as files or environment variables. //! use std::net::SocketAddr; use std::time::Duration; use crate::Error; use crate::key::KmsProtection; use crate::SEED_LENGTH; pub use self::environment::EnvironmentConfig; pub use self::file::FileConfig; pub use self::memory::MemoryConfig; mod environment; mod file; mod memory; /// Maximum number of requests to process in one batch and include the the Merkle tree. pub const DEFAULT_BATCH_SIZE: u8 = 64; /// Amount of time between each logged status update. pub const DEFAULT_STATUS_INTERVAL: Duration = Duration::from_secs(600); /// /// Specifies parameters needed to configure a Roughenough server. /// /// Parameters labeled "**Required**" must always be provided and have no default value /// while those labeled "**Optional**" provide sane default values that can be overridden. /// /// YAML Key | Environment Variable | Necessity | Description /// --- | --- | --- | --- /// `interface` | `ROUGHENOUGH_INTERFACE` | Required | IP address or interface name for listening to client requests /// `port` | `ROUGHENOUGH_PORT` | Required | UDP port to listen for requests /// `seed` | `ROUGHENOUGH_SEED` | Required | A 32-byte hexadecimal value used to generate the server's long-term key pair. **This is a secret value and must be un-guessable**, treat it with care. (If compiled with KMS support, length will vary) /// `batch_size` | `ROUGHENOUGH_BATCH_SIZE` | Optional | The maximum number of requests to process in one batch. All nonces in a batch are used to build a Merkle tree, the root of which is signed. Default is `64` requests per batch. /// `status_interval` | `ROUGHENOUGH_STATUS_INTERVAL` | Optional | Number of _seconds_ between each logged status update. Default is `600` seconds (10 minutes). /// `health_check_port` | `ROUGHENOUGH_HEALTH_CHECK_PORT` | Optional | If present, enable an HTTP health check responder on the provided port. **Use with caution**. /// `kms_protection` | `ROUGHENOUGH_KMS_PROTECTION` | Optional | If compiled with KMS support, the ID of the KMS key used to protect the long-term identity. /// `client_stats` | `ROUGHENOUGH_CLIENT_STATS` | Optional | A value of `on` or `yes` will enable tracking of per-client request statistics that will be output each time server status is logged. Default is `off` (disabled). /// `fault_percentage` | `ROUGHENOUGH_FAULT_PERCENTAGE` | Optional | Likelihood (as a percentage) that the server will intentionally return an invalid client response. An integer range from `0` (disabled, all responses valid) to `50` (50% of responses will be invalid). Default is `0` (disabled). /// /// Implementations of this trait obtain a valid configuration from different back-end /// sources. See: /// * [FileConfig](struct.FileConfig.html) - configure via a YAML file /// * [EnvironmentConfig](struct.EnvironmentConfig.html) - configure via environment variables /// * [MemoryConfig](struct.MemoryConfig.html) - in-memory configuration for testing /// pub trait ServerConfig { /// [Required] IP address or interface name to listen for client requests fn interface(&self) -> &str; /// [Required] UDP port to listen for requests fn port(&self) -> u16; /// [Required] A 32-byte hexadecimal value used to generate the server's /// long-term key pair. **This is a secret value and must be un-guessable**, /// treat it with care. fn seed(&self) -> Vec<u8>; /// [Optional] The maximum number of requests to process in one batch. All /// nonces in a batch are used to build a Merkle tree, the root of which is signed. /// Defaults to [DEFAULT_BATCH_SIZE](constant.DEFAULT_BATCH_SIZE.html) fn batch_size(&self) -> u8; /// [Optional] Amount of time between each logged status update. /// Defaults to [DEFAULT_STATUS_INTERVAL](constant.DEFAULT_STATUS_INTERVAL.html) fn status_interval(&self) -> Duration; /// [Optional] Method used to protect the seed for the server's long-term key pair. /// Defaults to "`plaintext`" (no encryption, seed is in the clear). fn kms_protection(&self) -> &KmsProtection; /// [Optional] If present, the TCP port to respond to Google-style HTTP "legacy health check". /// This is a *very* simplistic check, it emits a fixed HTTP response to all TCP connections. /// https://cloud.google.com/load-balancing/docs/health-checks#legacy-health-checks fn health_check_port(&self) -> Option<u16>; /// [Optional] A value of `on` or `yes` will enable tracking of per-client request statistics /// that will be output each time server status is logged. Default is `off` (disabled). fn client_stats_enabled(&self) -> bool; /// [Optional] Likelihood (as a percentage) that the server will intentionally return an /// invalid client response. An integer range from `0` (disabled, all responses valid) to `50` /// (~50% of responses will be invalid). Default is `0` (disabled). /// /// See the [Roughtime spec](https://roughtime.googlesource.com/roughtime/+/HEAD/ECOSYSTEM.md#maintaining-a-healthy-software-ecosystem) /// for background and rationale. fn fault_percentage(&self) -> u8; /// Convenience function to create a `SocketAddr` from the provided `interface` and `port` fn udp_socket_addr(&self) -> Result<SocketAddr, Error> { let addr = format!("{}:{}", self.interface(), self.port()); match addr.parse() { Ok(v) => Ok(v), Err(_) => Err(Error::InvalidConfiguration(addr)), } } } /// Factory function to create a `ServerConfig` _trait object_ based on the value /// of the provided `arg`. /// /// * `ENV` will return an [`EnvironmentConfig`](struct.EnvironmentConfig.html) /// * any other value returns a [`FileConfig`](struct.FileConfig.html) /// pub fn make_config(arg: &str) -> Result<Box<dyn ServerConfig>, Error> { if arg == "ENV" { match EnvironmentConfig::new() { Ok(cfg) => Ok(Box::new(cfg)), Err(e) => Err(e), } } else { match FileConfig::new(arg) { Ok(cfg) => Ok(Box::new(cfg)), Err(e) => Err(e), } } } /// /// Validate configuration settings. Returns `true` if the config is valid, `false` otherwise. /// #[allow(clippy::useless_let_if_seq)] pub fn is_valid_config(cfg: &dyn ServerConfig) -> bool
"plaintext seed value must be 32 characters long, found {}", cfg.seed().len() ); is_valid = false; } else if *cfg.kms_protection()!= KmsProtection::Plaintext && cfg.seed().len() <= SEED_LENGTH as usize { error!("KMS use enabled but seed value is too short to be an encrypted blob"); is_valid = false; } if cfg.batch_size() < 1 || cfg.batch_size() > 64 { error!( "batch_size {} is invalid; valid range 1-64", cfg.batch_size() ); is_valid = false; } if cfg.fault_percentage() > 50 { error!( "fault_percentage {} is invalid; valid range 0-50", cfg.fault_percentage() ); is_valid = false; } if is_valid { if let Err(e) = cfg.udp_socket_addr() { error!( "failed to create UDP socket {}:{} {:?}", cfg.interface(), cfg.port(), e ); is_valid = false; } } is_valid }
{ let mut is_valid = true; if cfg.port() == 0 { error!("server port not set: {}", cfg.port()); is_valid = false; } if cfg.interface().is_empty() { error!("'interface' is missing"); is_valid = false; } if cfg.seed().is_empty() { error!("'seed' value is missing"); is_valid = false; } else if *cfg.kms_protection() == KmsProtection::Plaintext && cfg.seed().len() != SEED_LENGTH as usize { error!(
identifier_body
mod.rs
// Copyright 2017-2021 int08h LLC // // 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. //! //! Ways to configure the Roughenough server. //! //! The [ServerConfig](trait.ServerConfig.html) trait specifies the required and optional //! parameters available for configuring a Roughenoguh server instance. //! //! Implementations of `ServerConfig` obtain configurations from different back-end sources //! such as files or environment variables. //! use std::net::SocketAddr; use std::time::Duration; use crate::Error; use crate::key::KmsProtection; use crate::SEED_LENGTH; pub use self::environment::EnvironmentConfig; pub use self::file::FileConfig; pub use self::memory::MemoryConfig; mod environment; mod file; mod memory; /// Maximum number of requests to process in one batch and include the the Merkle tree. pub const DEFAULT_BATCH_SIZE: u8 = 64; /// Amount of time between each logged status update. pub const DEFAULT_STATUS_INTERVAL: Duration = Duration::from_secs(600); /// /// Specifies parameters needed to configure a Roughenough server. /// /// Parameters labeled "**Required**" must always be provided and have no default value /// while those labeled "**Optional**" provide sane default values that can be overridden. /// /// YAML Key | Environment Variable | Necessity | Description /// --- | --- | --- | --- /// `interface` | `ROUGHENOUGH_INTERFACE` | Required | IP address or interface name for listening to client requests /// `port` | `ROUGHENOUGH_PORT` | Required | UDP port to listen for requests /// `seed` | `ROUGHENOUGH_SEED` | Required | A 32-byte hexadecimal value used to generate the server's long-term key pair. **This is a secret value and must be un-guessable**, treat it with care. (If compiled with KMS support, length will vary) /// `batch_size` | `ROUGHENOUGH_BATCH_SIZE` | Optional | The maximum number of requests to process in one batch. All nonces in a batch are used to build a Merkle tree, the root of which is signed. Default is `64` requests per batch. /// `status_interval` | `ROUGHENOUGH_STATUS_INTERVAL` | Optional | Number of _seconds_ between each logged status update. Default is `600` seconds (10 minutes). /// `health_check_port` | `ROUGHENOUGH_HEALTH_CHECK_PORT` | Optional | If present, enable an HTTP health check responder on the provided port. **Use with caution**. /// `kms_protection` | `ROUGHENOUGH_KMS_PROTECTION` | Optional | If compiled with KMS support, the ID of the KMS key used to protect the long-term identity. /// `client_stats` | `ROUGHENOUGH_CLIENT_STATS` | Optional | A value of `on` or `yes` will enable tracking of per-client request statistics that will be output each time server status is logged. Default is `off` (disabled). /// `fault_percentage` | `ROUGHENOUGH_FAULT_PERCENTAGE` | Optional | Likelihood (as a percentage) that the server will intentionally return an invalid client response. An integer range from `0` (disabled, all responses valid) to `50` (50% of responses will be invalid). Default is `0` (disabled). /// /// Implementations of this trait obtain a valid configuration from different back-end /// sources. See: /// * [FileConfig](struct.FileConfig.html) - configure via a YAML file /// * [EnvironmentConfig](struct.EnvironmentConfig.html) - configure via environment variables /// * [MemoryConfig](struct.MemoryConfig.html) - in-memory configuration for testing /// pub trait ServerConfig { /// [Required] IP address or interface name to listen for client requests fn interface(&self) -> &str; /// [Required] UDP port to listen for requests fn port(&self) -> u16; /// [Required] A 32-byte hexadecimal value used to generate the server's /// long-term key pair. **This is a secret value and must be un-guessable**, /// treat it with care. fn seed(&self) -> Vec<u8>; /// [Optional] The maximum number of requests to process in one batch. All /// nonces in a batch are used to build a Merkle tree, the root of which is signed. /// Defaults to [DEFAULT_BATCH_SIZE](constant.DEFAULT_BATCH_SIZE.html) fn batch_size(&self) -> u8; /// [Optional] Amount of time between each logged status update. /// Defaults to [DEFAULT_STATUS_INTERVAL](constant.DEFAULT_STATUS_INTERVAL.html) fn status_interval(&self) -> Duration; /// [Optional] Method used to protect the seed for the server's long-term key pair. /// Defaults to "`plaintext`" (no encryption, seed is in the clear). fn kms_protection(&self) -> &KmsProtection; /// [Optional] If present, the TCP port to respond to Google-style HTTP "legacy health check". /// This is a *very* simplistic check, it emits a fixed HTTP response to all TCP connections. /// https://cloud.google.com/load-balancing/docs/health-checks#legacy-health-checks fn health_check_port(&self) -> Option<u16>; /// [Optional] A value of `on` or `yes` will enable tracking of per-client request statistics /// that will be output each time server status is logged. Default is `off` (disabled). fn client_stats_enabled(&self) -> bool; /// [Optional] Likelihood (as a percentage) that the server will intentionally return an /// invalid client response. An integer range from `0` (disabled, all responses valid) to `50` /// (~50% of responses will be invalid). Default is `0` (disabled). /// /// See the [Roughtime spec](https://roughtime.googlesource.com/roughtime/+/HEAD/ECOSYSTEM.md#maintaining-a-healthy-software-ecosystem) /// for background and rationale. fn fault_percentage(&self) -> u8; /// Convenience function to create a `SocketAddr` from the provided `interface` and `port` fn udp_socket_addr(&self) -> Result<SocketAddr, Error> { let addr = format!("{}:{}", self.interface(), self.port()); match addr.parse() { Ok(v) => Ok(v), Err(_) => Err(Error::InvalidConfiguration(addr)), } } } /// Factory function to create a `ServerConfig` _trait object_ based on the value /// of the provided `arg`. /// /// * `ENV` will return an [`EnvironmentConfig`](struct.EnvironmentConfig.html) /// * any other value returns a [`FileConfig`](struct.FileConfig.html) /// pub fn make_config(arg: &str) -> Result<Box<dyn ServerConfig>, Error> { if arg == "ENV" { match EnvironmentConfig::new() { Ok(cfg) => Ok(Box::new(cfg)), Err(e) => Err(e), } } else { match FileConfig::new(arg) { Ok(cfg) => Ok(Box::new(cfg)), Err(e) => Err(e), } } } /// /// Validate configuration settings. Returns `true` if the config is valid, `false` otherwise. /// #[allow(clippy::useless_let_if_seq)] pub fn is_valid_config(cfg: &dyn ServerConfig) -> bool { let mut is_valid = true; if cfg.port() == 0 { error!("server port not set: {}", cfg.port()); is_valid = false; } if cfg.interface().is_empty() { error!("'interface' is missing"); is_valid = false; } if cfg.seed().is_empty()
else if *cfg.kms_protection() == KmsProtection::Plaintext && cfg.seed().len()!= SEED_LENGTH as usize { error!( "plaintext seed value must be 32 characters long, found {}", cfg.seed().len() ); is_valid = false; } else if *cfg.kms_protection()!= KmsProtection::Plaintext && cfg.seed().len() <= SEED_LENGTH as usize { error!("KMS use enabled but seed value is too short to be an encrypted blob"); is_valid = false; } if cfg.batch_size() < 1 || cfg.batch_size() > 64 { error!( "batch_size {} is invalid; valid range 1-64", cfg.batch_size() ); is_valid = false; } if cfg.fault_percentage() > 50 { error!( "fault_percentage {} is invalid; valid range 0-50", cfg.fault_percentage() ); is_valid = false; } if is_valid { if let Err(e) = cfg.udp_socket_addr() { error!( "failed to create UDP socket {}:{} {:?}", cfg.interface(), cfg.port(), e ); is_valid = false; } } is_valid }
{ error!("'seed' value is missing"); is_valid = false; }
conditional_block
mod.rs
// Copyright 2017-2021 int08h LLC // // 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. //! //! Ways to configure the Roughenough server. //! //! The [ServerConfig](trait.ServerConfig.html) trait specifies the required and optional //! parameters available for configuring a Roughenoguh server instance. //! //! Implementations of `ServerConfig` obtain configurations from different back-end sources //! such as files or environment variables. //! use std::net::SocketAddr; use std::time::Duration; use crate::Error; use crate::key::KmsProtection; use crate::SEED_LENGTH; pub use self::environment::EnvironmentConfig; pub use self::file::FileConfig; pub use self::memory::MemoryConfig; mod environment; mod file; mod memory; /// Maximum number of requests to process in one batch and include the the Merkle tree. pub const DEFAULT_BATCH_SIZE: u8 = 64; /// Amount of time between each logged status update. pub const DEFAULT_STATUS_INTERVAL: Duration = Duration::from_secs(600); /// /// Specifies parameters needed to configure a Roughenough server. /// /// Parameters labeled "**Required**" must always be provided and have no default value /// while those labeled "**Optional**" provide sane default values that can be overridden. /// /// YAML Key | Environment Variable | Necessity | Description /// --- | --- | --- | --- /// `interface` | `ROUGHENOUGH_INTERFACE` | Required | IP address or interface name for listening to client requests /// `port` | `ROUGHENOUGH_PORT` | Required | UDP port to listen for requests /// `seed` | `ROUGHENOUGH_SEED` | Required | A 32-byte hexadecimal value used to generate the server's long-term key pair. **This is a secret value and must be un-guessable**, treat it with care. (If compiled with KMS support, length will vary) /// `batch_size` | `ROUGHENOUGH_BATCH_SIZE` | Optional | The maximum number of requests to process in one batch. All nonces in a batch are used to build a Merkle tree, the root of which is signed. Default is `64` requests per batch. /// `status_interval` | `ROUGHENOUGH_STATUS_INTERVAL` | Optional | Number of _seconds_ between each logged status update. Default is `600` seconds (10 minutes). /// `health_check_port` | `ROUGHENOUGH_HEALTH_CHECK_PORT` | Optional | If present, enable an HTTP health check responder on the provided port. **Use with caution**. /// `kms_protection` | `ROUGHENOUGH_KMS_PROTECTION` | Optional | If compiled with KMS support, the ID of the KMS key used to protect the long-term identity. /// `client_stats` | `ROUGHENOUGH_CLIENT_STATS` | Optional | A value of `on` or `yes` will enable tracking of per-client request statistics that will be output each time server status is logged. Default is `off` (disabled). /// `fault_percentage` | `ROUGHENOUGH_FAULT_PERCENTAGE` | Optional | Likelihood (as a percentage) that the server will intentionally return an invalid client response. An integer range from `0` (disabled, all responses valid) to `50` (50% of responses will be invalid). Default is `0` (disabled). /// /// Implementations of this trait obtain a valid configuration from different back-end /// sources. See: /// * [FileConfig](struct.FileConfig.html) - configure via a YAML file /// * [EnvironmentConfig](struct.EnvironmentConfig.html) - configure via environment variables /// * [MemoryConfig](struct.MemoryConfig.html) - in-memory configuration for testing /// pub trait ServerConfig { /// [Required] IP address or interface name to listen for client requests fn interface(&self) -> &str; /// [Required] UDP port to listen for requests fn port(&self) -> u16; /// [Required] A 32-byte hexadecimal value used to generate the server's /// long-term key pair. **This is a secret value and must be un-guessable**, /// treat it with care. fn seed(&self) -> Vec<u8>; /// [Optional] The maximum number of requests to process in one batch. All /// nonces in a batch are used to build a Merkle tree, the root of which is signed. /// Defaults to [DEFAULT_BATCH_SIZE](constant.DEFAULT_BATCH_SIZE.html) fn batch_size(&self) -> u8; /// [Optional] Amount of time between each logged status update. /// Defaults to [DEFAULT_STATUS_INTERVAL](constant.DEFAULT_STATUS_INTERVAL.html) fn status_interval(&self) -> Duration; /// [Optional] Method used to protect the seed for the server's long-term key pair. /// Defaults to "`plaintext`" (no encryption, seed is in the clear). fn kms_protection(&self) -> &KmsProtection; /// [Optional] If present, the TCP port to respond to Google-style HTTP "legacy health check". /// This is a *very* simplistic check, it emits a fixed HTTP response to all TCP connections. /// https://cloud.google.com/load-balancing/docs/health-checks#legacy-health-checks fn health_check_port(&self) -> Option<u16>; /// [Optional] A value of `on` or `yes` will enable tracking of per-client request statistics /// that will be output each time server status is logged. Default is `off` (disabled). fn client_stats_enabled(&self) -> bool; /// [Optional] Likelihood (as a percentage) that the server will intentionally return an /// invalid client response. An integer range from `0` (disabled, all responses valid) to `50` /// (~50% of responses will be invalid). Default is `0` (disabled). /// /// See the [Roughtime spec](https://roughtime.googlesource.com/roughtime/+/HEAD/ECOSYSTEM.md#maintaining-a-healthy-software-ecosystem) /// for background and rationale. fn fault_percentage(&self) -> u8; /// Convenience function to create a `SocketAddr` from the provided `interface` and `port` fn udp_socket_addr(&self) -> Result<SocketAddr, Error> { let addr = format!("{}:{}", self.interface(), self.port()); match addr.parse() { Ok(v) => Ok(v), Err(_) => Err(Error::InvalidConfiguration(addr)), } } } /// Factory function to create a `ServerConfig` _trait object_ based on the value /// of the provided `arg`. /// /// * `ENV` will return an [`EnvironmentConfig`](struct.EnvironmentConfig.html) /// * any other value returns a [`FileConfig`](struct.FileConfig.html) /// pub fn make_config(arg: &str) -> Result<Box<dyn ServerConfig>, Error> { if arg == "ENV" { match EnvironmentConfig::new() { Ok(cfg) => Ok(Box::new(cfg)), Err(e) => Err(e), } } else { match FileConfig::new(arg) { Ok(cfg) => Ok(Box::new(cfg)), Err(e) => Err(e), } } } /// /// Validate configuration settings. Returns `true` if the config is valid, `false` otherwise. /// #[allow(clippy::useless_let_if_seq)] pub fn
(cfg: &dyn ServerConfig) -> bool { let mut is_valid = true; if cfg.port() == 0 { error!("server port not set: {}", cfg.port()); is_valid = false; } if cfg.interface().is_empty() { error!("'interface' is missing"); is_valid = false; } if cfg.seed().is_empty() { error!("'seed' value is missing"); is_valid = false; } else if *cfg.kms_protection() == KmsProtection::Plaintext && cfg.seed().len()!= SEED_LENGTH as usize { error!( "plaintext seed value must be 32 characters long, found {}", cfg.seed().len() ); is_valid = false; } else if *cfg.kms_protection()!= KmsProtection::Plaintext && cfg.seed().len() <= SEED_LENGTH as usize { error!("KMS use enabled but seed value is too short to be an encrypted blob"); is_valid = false; } if cfg.batch_size() < 1 || cfg.batch_size() > 64 { error!( "batch_size {} is invalid; valid range 1-64", cfg.batch_size() ); is_valid = false; } if cfg.fault_percentage() > 50 { error!( "fault_percentage {} is invalid; valid range 0-50", cfg.fault_percentage() ); is_valid = false; } if is_valid { if let Err(e) = cfg.udp_socket_addr() { error!( "failed to create UDP socket {}:{} {:?}", cfg.interface(), cfg.port(), e ); is_valid = false; } } is_valid }
is_valid_config
identifier_name
mod.rs
// Copyright 2017-2021 int08h LLC // // 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. //! //! Ways to configure the Roughenough server. //! //! The [ServerConfig](trait.ServerConfig.html) trait specifies the required and optional //! parameters available for configuring a Roughenoguh server instance. //! //! Implementations of `ServerConfig` obtain configurations from different back-end sources //! such as files or environment variables. //! use std::net::SocketAddr; use std::time::Duration; use crate::Error; use crate::key::KmsProtection; use crate::SEED_LENGTH; pub use self::environment::EnvironmentConfig; pub use self::file::FileConfig; pub use self::memory::MemoryConfig; mod environment; mod file; mod memory; /// Maximum number of requests to process in one batch and include the the Merkle tree. pub const DEFAULT_BATCH_SIZE: u8 = 64; /// Amount of time between each logged status update. pub const DEFAULT_STATUS_INTERVAL: Duration = Duration::from_secs(600); /// /// Specifies parameters needed to configure a Roughenough server. /// /// Parameters labeled "**Required**" must always be provided and have no default value /// while those labeled "**Optional**" provide sane default values that can be overridden. /// /// YAML Key | Environment Variable | Necessity | Description /// --- | --- | --- | --- /// `interface` | `ROUGHENOUGH_INTERFACE` | Required | IP address or interface name for listening to client requests /// `port` | `ROUGHENOUGH_PORT` | Required | UDP port to listen for requests /// `seed` | `ROUGHENOUGH_SEED` | Required | A 32-byte hexadecimal value used to generate the server's long-term key pair. **This is a secret value and must be un-guessable**, treat it with care. (If compiled with KMS support, length will vary) /// `batch_size` | `ROUGHENOUGH_BATCH_SIZE` | Optional | The maximum number of requests to process in one batch. All nonces in a batch are used to build a Merkle tree, the root of which is signed. Default is `64` requests per batch. /// `status_interval` | `ROUGHENOUGH_STATUS_INTERVAL` | Optional | Number of _seconds_ between each logged status update. Default is `600` seconds (10 minutes). /// `health_check_port` | `ROUGHENOUGH_HEALTH_CHECK_PORT` | Optional | If present, enable an HTTP health check responder on the provided port. **Use with caution**. /// `kms_protection` | `ROUGHENOUGH_KMS_PROTECTION` | Optional | If compiled with KMS support, the ID of the KMS key used to protect the long-term identity. /// `client_stats` | `ROUGHENOUGH_CLIENT_STATS` | Optional | A value of `on` or `yes` will enable tracking of per-client request statistics that will be output each time server status is logged. Default is `off` (disabled). /// `fault_percentage` | `ROUGHENOUGH_FAULT_PERCENTAGE` | Optional | Likelihood (as a percentage) that the server will intentionally return an invalid client response. An integer range from `0` (disabled, all responses valid) to `50` (50% of responses will be invalid). Default is `0` (disabled). /// /// Implementations of this trait obtain a valid configuration from different back-end /// sources. See: /// * [FileConfig](struct.FileConfig.html) - configure via a YAML file /// * [EnvironmentConfig](struct.EnvironmentConfig.html) - configure via environment variables /// * [MemoryConfig](struct.MemoryConfig.html) - in-memory configuration for testing /// pub trait ServerConfig { /// [Required] IP address or interface name to listen for client requests fn interface(&self) -> &str; /// [Required] UDP port to listen for requests fn port(&self) -> u16; /// [Required] A 32-byte hexadecimal value used to generate the server's /// long-term key pair. **This is a secret value and must be un-guessable**, /// treat it with care. fn seed(&self) -> Vec<u8>; /// [Optional] The maximum number of requests to process in one batch. All /// nonces in a batch are used to build a Merkle tree, the root of which is signed. /// Defaults to [DEFAULT_BATCH_SIZE](constant.DEFAULT_BATCH_SIZE.html) fn batch_size(&self) -> u8; /// [Optional] Amount of time between each logged status update. /// Defaults to [DEFAULT_STATUS_INTERVAL](constant.DEFAULT_STATUS_INTERVAL.html) fn status_interval(&self) -> Duration; /// [Optional] Method used to protect the seed for the server's long-term key pair. /// Defaults to "`plaintext`" (no encryption, seed is in the clear). fn kms_protection(&self) -> &KmsProtection; /// [Optional] If present, the TCP port to respond to Google-style HTTP "legacy health check". /// This is a *very* simplistic check, it emits a fixed HTTP response to all TCP connections. /// https://cloud.google.com/load-balancing/docs/health-checks#legacy-health-checks fn health_check_port(&self) -> Option<u16>; /// [Optional] A value of `on` or `yes` will enable tracking of per-client request statistics /// that will be output each time server status is logged. Default is `off` (disabled). fn client_stats_enabled(&self) -> bool; /// [Optional] Likelihood (as a percentage) that the server will intentionally return an /// invalid client response. An integer range from `0` (disabled, all responses valid) to `50` /// (~50% of responses will be invalid). Default is `0` (disabled). /// /// See the [Roughtime spec](https://roughtime.googlesource.com/roughtime/+/HEAD/ECOSYSTEM.md#maintaining-a-healthy-software-ecosystem) /// for background and rationale. fn fault_percentage(&self) -> u8; /// Convenience function to create a `SocketAddr` from the provided `interface` and `port` fn udp_socket_addr(&self) -> Result<SocketAddr, Error> { let addr = format!("{}:{}", self.interface(), self.port()); match addr.parse() { Ok(v) => Ok(v), Err(_) => Err(Error::InvalidConfiguration(addr)), } } } /// Factory function to create a `ServerConfig` _trait object_ based on the value /// of the provided `arg`. /// /// * `ENV` will return an [`EnvironmentConfig`](struct.EnvironmentConfig.html) /// * any other value returns a [`FileConfig`](struct.FileConfig.html) /// pub fn make_config(arg: &str) -> Result<Box<dyn ServerConfig>, Error> { if arg == "ENV" { match EnvironmentConfig::new() { Ok(cfg) => Ok(Box::new(cfg)), Err(e) => Err(e), } } else { match FileConfig::new(arg) { Ok(cfg) => Ok(Box::new(cfg)), Err(e) => Err(e), } } } /// /// Validate configuration settings. Returns `true` if the config is valid, `false` otherwise. /// #[allow(clippy::useless_let_if_seq)] pub fn is_valid_config(cfg: &dyn ServerConfig) -> bool { let mut is_valid = true; if cfg.port() == 0 { error!("server port not set: {}", cfg.port()); is_valid = false; } if cfg.interface().is_empty() { error!("'interface' is missing"); is_valid = false; } if cfg.seed().is_empty() { error!("'seed' value is missing"); is_valid = false; } else if *cfg.kms_protection() == KmsProtection::Plaintext && cfg.seed().len()!= SEED_LENGTH as usize
); is_valid = false; } else if *cfg.kms_protection()!= KmsProtection::Plaintext && cfg.seed().len() <= SEED_LENGTH as usize { error!("KMS use enabled but seed value is too short to be an encrypted blob"); is_valid = false; } if cfg.batch_size() < 1 || cfg.batch_size() > 64 { error!( "batch_size {} is invalid; valid range 1-64", cfg.batch_size() ); is_valid = false; } if cfg.fault_percentage() > 50 { error!( "fault_percentage {} is invalid; valid range 0-50", cfg.fault_percentage() ); is_valid = false; } if is_valid { if let Err(e) = cfg.udp_socket_addr() { error!( "failed to create UDP socket {}:{} {:?}", cfg.interface(), cfg.port(), e ); is_valid = false; } } is_valid }
{ error!( "plaintext seed value must be 32 characters long, found {}", cfg.seed().len()
random_line_split
instr_roundpd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn roundpd_1() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(Literal8(62)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 234, 62], OperandSize::Dword) } #[test] fn roundpd_2() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledIndexed(ECX, ECX, Two, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(44)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 4, 73, 44], OperandSize::Dword) } #[test] fn roundpd_3() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(2)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 232, 2], OperandSize::Qword)
#[test] fn roundpd_4() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledDisplaced(RCX, Eight, 1594162194, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(99)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 44, 205, 18, 252, 4, 95, 99], OperandSize::Qword) }
}
random_line_split
instr_roundpd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn roundpd_1() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(Literal8(62)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 234, 62], OperandSize::Dword) } #[test] fn roundpd_2()
#[test] fn roundpd_3() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(2)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 232, 2], OperandSize::Qword) } #[test] fn roundpd_4() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledDisplaced(RCX, Eight, 1594162194, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(99)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 44, 205, 18, 252, 4, 95, 99], OperandSize::Qword) }
{ run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledIndexed(ECX, ECX, Two, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(44)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 4, 73, 44], OperandSize::Dword) }
identifier_body
instr_roundpd.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn roundpd_1() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM2)), operand3: Some(Literal8(62)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 234, 62], OperandSize::Dword) } #[test] fn
() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM0)), operand2: Some(IndirectScaledIndexed(ECX, ECX, Two, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(44)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 4, 73, 44], OperandSize::Dword) } #[test] fn roundpd_3() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM5)), operand2: Some(Direct(XMM0)), operand3: Some(Literal8(2)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 232, 2], OperandSize::Qword) } #[test] fn roundpd_4() { run_test(&Instruction { mnemonic: Mnemonic::ROUNDPD, operand1: Some(Direct(XMM5)), operand2: Some(IndirectScaledDisplaced(RCX, Eight, 1594162194, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(99)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[102, 15, 58, 9, 44, 205, 18, 252, 4, 95, 99], OperandSize::Qword) }
roundpd_2
identifier_name
user.rs
use aardwolf_models::user::{ email::Email, {AuthenticatedUser, UserLike}, }; use rocket::{ http::Status, outcome::IntoOutcome, request::{self, FromRequest}, {Outcome, Request, State}, }; use Pool; pub struct SignedInUser(pub AuthenticatedUser); impl<'l, 'r> FromRequest<'l, 'r> for SignedInUser { type Error = (); fn from_request(request: &'l Request<'r>) -> request::Outcome<Self, Self::Error> { let pool = request.guard::<State<Pool>>()?; let db = match pool.get() { Ok(db) => db, Err(_) => return Outcome::Failure((Status::ServiceUnavailable, ())), }; request .cookies() .get_private("user_id") .and_then(|c| c.value().parse::<i32>().ok()) .and_then(|user_id| AuthenticatedUser::get_authenticated_user_by_id(user_id, &db).ok()) .map(SignedInUser) .or_forward(()) } } pub struct SignedInUserWithEmail(pub AuthenticatedUser, pub Email); impl<'l, 'r> FromRequest<'l, 'r> for SignedInUserWithEmail { type Error = (); fn from_request(request: &'l Request<'r>) -> request::Outcome<Self, Self::Error> { let pool = request.guard::<State<Pool>>()?; let db = match pool.get() { Ok(db) => db, Err(_) => return Outcome::Failure((Status::ServiceUnavailable, ())), };
AuthenticatedUser::get_authenticated_user_by_id(user_id, &db) .ok() .and_then(|user| { user.primary_email() .and_then(|primary_email| Email::by_id(primary_email, &db).ok()) .or_else(|| Email::first_by_user_id(user_id, &db).ok()) .map(|email| SignedInUserWithEmail(user, email)) }) }) .or_forward(()) } }
request .cookies() .get_private("user_id") .and_then(|c| c.value().parse::<i32>().ok()) .and_then(|user_id| {
random_line_split
user.rs
use aardwolf_models::user::{ email::Email, {AuthenticatedUser, UserLike}, }; use rocket::{ http::Status, outcome::IntoOutcome, request::{self, FromRequest}, {Outcome, Request, State}, }; use Pool; pub struct
(pub AuthenticatedUser); impl<'l, 'r> FromRequest<'l, 'r> for SignedInUser { type Error = (); fn from_request(request: &'l Request<'r>) -> request::Outcome<Self, Self::Error> { let pool = request.guard::<State<Pool>>()?; let db = match pool.get() { Ok(db) => db, Err(_) => return Outcome::Failure((Status::ServiceUnavailable, ())), }; request .cookies() .get_private("user_id") .and_then(|c| c.value().parse::<i32>().ok()) .and_then(|user_id| AuthenticatedUser::get_authenticated_user_by_id(user_id, &db).ok()) .map(SignedInUser) .or_forward(()) } } pub struct SignedInUserWithEmail(pub AuthenticatedUser, pub Email); impl<'l, 'r> FromRequest<'l, 'r> for SignedInUserWithEmail { type Error = (); fn from_request(request: &'l Request<'r>) -> request::Outcome<Self, Self::Error> { let pool = request.guard::<State<Pool>>()?; let db = match pool.get() { Ok(db) => db, Err(_) => return Outcome::Failure((Status::ServiceUnavailable, ())), }; request .cookies() .get_private("user_id") .and_then(|c| c.value().parse::<i32>().ok()) .and_then(|user_id| { AuthenticatedUser::get_authenticated_user_by_id(user_id, &db) .ok() .and_then(|user| { user.primary_email() .and_then(|primary_email| Email::by_id(primary_email, &db).ok()) .or_else(|| Email::first_by_user_id(user_id, &db).ok()) .map(|email| SignedInUserWithEmail(user, email)) }) }) .or_forward(()) } }
SignedInUser
identifier_name
instructions.rs
fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", opcode_name(*self)) } } impl Opcode { /// Get the instruction format for this opcode. pub fn format(self) -> InstructionFormat { OPCODE_FORMAT[self as usize - 1] } /// Get the constraint descriptor for this opcode. /// Panic if this is called on `NotAnOpcode`. pub fn constraints(self) -> OpcodeConstraints { OPCODE_CONSTRAINTS[self as usize - 1] } } // This trait really belongs in cranelift-reader where it is used by the `.clif` file parser, but since // it critically depends on the `opcode_name()` function which is needed here anyway, it lives in // this module. This also saves us from running the build script twice to generate code for the two // separate crates. impl FromStr for Opcode { type Err = &'static str; /// Parse an Opcode name from a string. fn from_str(s: &str) -> Result<Self, &'static str> { use crate::constant_hash::{probe, simple_hash, Table}; impl<'a> Table<&'a str> for [Option<Opcode>] { fn len(&self) -> usize { self.len() } fn key(&self, idx: usize) -> Option<&'a str> { self[idx].map(opcode_name) } } match probe::<&str, [Option<Self>]>(&OPCODE_HASH_TABLE, s, simple_hash(s)) { Err(_) => Err("Unknown opcode"), // We unwrap here because probe() should have ensured that the entry // at this index is not None. Ok(i) => Ok(OPCODE_HASH_TABLE[i].unwrap()), } } } /// A variable list of `Value` operands used for function call arguments and passing arguments to /// basic blocks. #[derive(Clone, Debug)] pub struct VariableArgs(Vec<Value>); impl VariableArgs { /// Create an empty argument list. pub fn new() -> Self { VariableArgs(Vec::new()) } /// Add an argument to the end. pub fn push(&mut self, v: Value) { self.0.push(v) } /// Check if the list is empty. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Convert this to a value list in `pool` with `fixed` prepended. pub fn into_value_list(self, fixed: &[Value], pool: &mut ValueListPool) -> ValueList { let mut vlist = ValueList::default(); vlist.extend(fixed.iter().cloned(), pool); vlist.extend(self.0, pool); vlist } } // Coerce `VariableArgs` into a `&[Value]` slice. impl Deref for VariableArgs { type Target = [Value]; fn deref(&self) -> &[Value] { &self.0 } } impl DerefMut for VariableArgs { fn deref_mut(&mut self) -> &mut [Value] { &mut self.0 } } impl Display for VariableArgs { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { for (i, val) in self.0.iter().enumerate() { if i == 0 { write!(fmt, "{}", val)?; } else { write!(fmt, ", {}", val)?; } } Ok(()) } } impl Default for VariableArgs { fn default() -> Self { Self::new() } } /// Analyzing an instruction. /// /// Avoid large matches on instruction formats by using the methods defined here to examine /// instructions. impl InstructionData { /// Return information about the destination of a branch or jump instruction. /// /// Any instruction that can transfer control to another EBB reveals its possible destinations /// here. pub fn analyze_branch<'a>(&'a self, pool: &'a ValueListPool) -> BranchInfo<'a> { match *self { InstructionData::Jump { destination, ref args, .. } => BranchInfo::SingleDest(destination, args.as_slice(pool)), InstructionData::BranchInt { destination, ref args, .. } | InstructionData::BranchFloat { destination, ref args, .. } | InstructionData::Branch { destination, ref args, .. } => BranchInfo::SingleDest(destination, &args.as_slice(pool)[1..]), InstructionData::BranchIcmp { destination, ref args, .. } => BranchInfo::SingleDest(destination, &args.as_slice(pool)[2..]), InstructionData::BranchTable { table, destination,.. } => BranchInfo::Table(table, Some(destination)), InstructionData::IndirectJump { table,.. } => BranchInfo::Table(table, None), _ => { debug_assert!(!self.opcode().is_branch()); BranchInfo::NotABranch } } } /// Get the single destination of this branch instruction, if it is a single destination /// branch or jump. /// /// Multi-destination branches like `br_table` return `None`. pub fn branch_destination(&self) -> Option<Ebb> { match *self { InstructionData::Jump { destination,.. } | InstructionData::Branch { destination,.. } | InstructionData::BranchInt { destination,.. } | InstructionData::BranchFloat { destination,.. } | InstructionData::BranchIcmp { destination,.. } => Some(destination), InstructionData::BranchTable {.. } | InstructionData::IndirectJump {.. } => None, _ => { debug_assert!(!self.opcode().is_branch()); None } } } /// Get a mutable reference to the single destination of this branch instruction, if it is a /// single destination branch or jump. /// /// Multi-destination branches like `br_table` return `None`. pub fn branch_destination_mut(&mut self) -> Option<&mut Ebb> { match *self { InstructionData::Jump { ref mut destination, .. } | InstructionData::Branch { ref mut destination, .. } | InstructionData::BranchInt { ref mut destination, .. } | InstructionData::BranchFloat { ref mut destination, .. } | InstructionData::BranchIcmp { ref mut destination, .. } => Some(destination), InstructionData::BranchTable {.. } => None, _ => { debug_assert!(!self.opcode().is_branch()); None } } } /// Return information about a call instruction. /// /// Any instruction that can call another function reveals its call signature here. pub fn analyze_call<'a>(&'a self, pool: &'a ValueListPool) -> CallInfo<'a>
} /// Information about branch and jump instructions. pub enum BranchInfo<'a> { /// This is not a branch or jump instruction. /// This instruction will not transfer control to another EBB in the function, but it may still /// affect control flow by returning or trapping. NotABranch, /// This is a branch or jump to a single destination EBB, possibly taking value arguments. SingleDest(Ebb, &'a [Value]), /// This is a jump table branch which can have many destination EBBs and maybe one default EBB. Table(JumpTable, Option<Ebb>), } /// Information about call instructions. pub enum CallInfo<'a> { /// This is not a call instruction. NotACall, /// This is a direct call to an external function declared in the preamble. See /// `DataFlowGraph.ext_funcs`. Direct(FuncRef, &'a [Value]), /// This is an indirect call with the specified signature. See `DataFlowGraph.signatures`. Indirect(SigRef, &'a [Value]), } /// Value type constraints for a given opcode. /// /// The `InstructionFormat` determines the constraints on most operands, but `Value` operands and /// results are not determined by the format. Every `Opcode` has an associated /// `OpcodeConstraints` object that provides the missing details. #[derive(Clone, Copy)] pub struct OpcodeConstraints { /// Flags for this opcode encoded as a bit field: /// /// Bits 0-2: /// Number of fixed result values. This does not include `variable_args` results as are /// produced by call instructions. /// /// Bit 3: /// This opcode is polymorphic and the controlling type variable can be inferred from the /// designated input operand. This is the `typevar_operand` index given to the /// `InstructionFormat` meta language object. When this bit is not set, the controlling /// type variable must be the first output value instead. /// /// Bit 4: /// This opcode is polymorphic and the controlling type variable does *not* appear as the /// first result type. /// /// Bits 5-7: /// Number of fixed value arguments. The minimum required number of value operands. flags: u8, /// Permitted set of types for the controlling type variable as an index into `TYPE_SETS`. typeset_offset: u8, /// Offset into `OPERAND_CONSTRAINT` table of the descriptors for this opcode. The first /// `num_fixed_results()` entries describe the result constraints, then follows constraints for /// the fixed `Value` input operands. (`num_fixed_value_arguments()` of them). constraint_offset: u16, } impl OpcodeConstraints { /// Can the controlling type variable for this opcode be inferred from the designated value /// input operand? /// This also implies that this opcode is polymorphic. pub fn use_typevar_operand(self) -> bool { (self.flags & 0x8)!= 0 } /// Is it necessary to look at the designated value input operand in order to determine the /// controlling type variable, or is it good enough to use the first return type? /// /// Most polymorphic instructions produce a single result with the type of the controlling type /// variable. A few polymorphic instructions either don't produce any results, or produce /// results with a fixed type. These instructions return `true`. pub fn requires_typevar_operand(self) -> bool { (self.flags & 0x10)!= 0 } /// Get the number of *fixed* result values produced by this opcode. /// This does not include `variable_args` produced by calls. pub fn num_fixed_results(self) -> usize { (self.flags & 0x7) as usize } /// Get the number of *fixed* input values required by this opcode. /// /// This does not include `variable_args` arguments on call and branch instructions. /// /// The number of fixed input values is usually implied by the instruction format, but /// instruction formats that use a `ValueList` put both fixed and variable arguments in the /// list. This method returns the *minimum* number of values required in the value list. pub fn num_fixed_value_arguments(self) -> usize { ((self.flags >> 5) & 0x7) as usize } /// Get the offset into `TYPE_SETS` for the controlling type variable. /// Returns `None` if the instruction is not polymorphic. fn typeset_offset(self) -> Option<usize> { let offset = usize::from(self.typeset_offset); if offset < TYPE_SETS.len() { Some(offset) } else { None } } /// Get the offset into OPERAND_CONSTRAINTS where the descriptors for this opcode begin. fn constraint_offset(self) -> usize { self.constraint_offset as usize } /// Get the value type of result number `n`, having resolved the controlling type variable to /// `ctrl_type`. pub fn result_type(self, n: usize, ctrl_type: Type) -> Type { debug_assert!(n < self.num_fixed_results(), "Invalid result index"); if let ResolvedConstraint::Bound(t) = OPERAND_CONSTRAINTS[self.constraint_offset() + n].resolve(ctrl_type) { t } else { panic!("Result constraints can't be free"); } } /// Get the value type of input value number `n`, having resolved the controlling type variable /// to `ctrl_type`. /// /// Unlike results, it is possible for some input values to vary freely within a specific /// `ValueTypeSet`. This is represented with the `ArgumentConstraint::Free` variant. pub fn value_argument_constraint(self, n: usize, ctrl_type: Type) -> ResolvedConstraint { debug_assert!( n < self.num_fixed_value_arguments(), "Invalid value argument index" ); let offset = self.constraint_offset() + self.num_fixed_results(); OPERAND_CONSTRAINTS[offset + n].resolve(ctrl_type) } /// Get the typeset of allowed types for the controlling type variable in a polymorphic /// instruction. pub fn ctrl_typeset(self) -> Option<ValueTypeSet> { self.typeset_offset().map(|offset| TYPE_SETS[offset]) } /// Is this instruction polymorphic? pub fn is_polymorphic(self) -> bool { self.ctrl_typeset().is_some() } } type BitSet8 = BitSet<u8>; type BitSet16 = BitSet<u16>; /// A value type set describes the permitted set of types for a type variable. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ValueTypeSet { /// Allowed lane sizes pub lanes: BitSet16, /// Allowed int widths pub ints: BitSet8, /// Allowed float widths pub floats: BitSet8, /// Allowed bool widths pub bools: BitSet8, } impl ValueTypeSet { /// Is `scalar` part of the base type set? /// /// Note that the base type set does not have to be included in the type set proper. fn is_base_type(self, scalar: Type) -> bool { let l2b = scalar.log2_lane_bits(); if scalar.is_int() { self.ints.contains(l2b) } else if scalar.is_float() { self.floats.contains(l2b) } else if scalar.is_bool() { self.bools.contains(l2b) } else { false } } /// Does `typ` belong to this set? pub fn contains(self, typ: Type) -> bool { let l2l = typ.log2_lane_count(); self.lanes.contains(l2l) && self.is_base_type(typ.lane_type()) } /// Get an example member of this type set. /// /// This is used for error messages to avoid suggesting invalid types. pub fn example(self) -> Type { let t = if self.ints.max().unwrap_or(0) > 5 { types::I32 } else if self.floats.max().unwrap_or(0) > 5 { types::F32 } else if self.bools.max().unwrap_or(0) > 5 { types::B32 } else { types::B1 }; t.by(1 << self.lanes.min().unwrap()).unwrap() } } /// Operand constraints. This describes the value type constraints on a single `Value` operand. enum OperandConstraint { /// This operand has a concrete value type. Concrete(Type), /// This operand can vary freely within the given type set. /// The type set is identified by its index into the TYPE_SETS constant table. Free(u8), /// This operand is the same type as the controlling type variable. Same, /// This operand is `ctrlType.lane_type()`. LaneOf, /// This operand is `ctrlType.as_bool()`. AsBool, /// This operand is `ctrlType.half_width()`. HalfWidth, /// This operand is `ctrlType.double_width()`. DoubleWidth, /// This operand is `ctrlType.half_vector()`. HalfVector, /// This operand is `ctrlType.double_vector()`. DoubleVector, } impl OperandConstraint { /// Resolve this operand constraint into a concrete value type, given the value of the /// controlling type variable. pub fn resolve(&self, ctrl_type: Type) -> ResolvedConstraint { use self::OperandConstraint::*; use self::ResolvedConstraint::Bound; match *self { Concrete(t) => Bound(t), Free(vts) => ResolvedConstraint::Free(TYPE_SETS[vts as usize]), Same => Bound(ctrl_type), LaneOf => Bound(ctrl_type.lane_type()), AsBool => Bound(ctrl_type.as_bool()), HalfWidth => Bound(ctrl_type.half_width().expect("invalid type for half_width")), DoubleWidth => Bound( ctrl_type .double_width() .expect("invalid type for double_width"), ), HalfVector => Bound( ctrl_type .half_vector() .expect("invalid type for half_vector"), ), DoubleVector => Bound(ctrl_type.by(2).expect("invalid type for double_vector")), } } } /// The type constraint on a value argument once the controlling type variable is known. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum ResolvedConstraint { /// The operand is bound to a known type. Bound(Type), /// The operand type can vary freely within the given set. Free(ValueTypeSet), } #[cfg(test)] mod tests { use super::*; use std::string::ToString; #[test] fn opcodes() { use core::mem; let x = Opcode::Iadd; let mut y = Opcode::Isub; assert!(x!= y); y = Opcode::Iadd; assert_eq!(x, y); assert_eq!(x.format(), InstructionFormat::Binary); assert_eq!(format!("{:?}", Opcode::IaddImm), "IaddImm"); assert_eq!(Opcode::IaddImm.to_string(), "iadd_imm"); // Check the matcher. assert_eq!("iadd".parse::<Opcode>(), Ok(Opcode::Iadd)); assert_eq!("iadd_imm".parse::<Opcode>(), Ok(Opcode::IaddImm)); assert_eq!("iadd\0".parse::<Opcode>(), Err("Unknown opcode")); assert_eq!("".parse::<Opcode>(), Err("Unknown opcode")); assert_eq!("\0".parse::<Opcode>(), Err("Unknown opcode")); // Opcode is a single byte, and because Option<Opcode> originally came to 2 bytes, early on // Opcode included a variant NotAnOpcode to avoid the unnecessary bloat. Since then the Rust // compiler has brought in NonZero optimization, meaning that an enum not using the 0 value // can be optional for no size cost. We want to ensure Option<Opcode> remains small. assert_eq!(mem::size_of::<Opcode>(), mem::size_of::<Option<Opcode>>()); } #[test] fn instruction_data() { use core::mem; // The size of the `InstructionData` enum is important for performance. It should not // exceed 16 bytes. Use `Box<FooData>` out-of-line payloads for instruction formats that // require more space than that. It would be fine with a data structure smaller than 16 // bytes, but what are the odds of that? assert_eq!(mem::size_of::<InstructionData>(), 16); } #[test] fn constraints() { let a = Opcode::Iadd.constraints(); assert!(a.use_typevar_operand()); assert!(!a.requires_typevar_operand()); assert_eq!(a.num_fixed_results(), 1); assert_eq!(a.num_fixed_value_arguments(), 2); assert_eq!(a.result_type(0, types::I32), types::I32); assert_eq!(a.result_type(0, types::I8), types::I8); assert_eq!( a.value_argument_constraint(0, types::I32), ResolvedConstraint::Bound(types::I32) ); assert_eq!( a.value_argument_constraint(1, types::I32), ResolvedConstraint::Bound(types::I32) ); let b = Opcode::Bitcast.constraints(); assert!(!b.use_typevar_operand()); assert!(!b.requires_typevar_operand()); assert_eq!(b.num_fixed_results(), 1); assert_eq!(b.num_fixed_value_arguments(), 1); assert_eq!(b.result_type(0, types::I32), types::I32); assert_eq!(b.result_type(0, types::I8), types::I8); match b.value_argument_constraint(0, types::I32) { ResolvedConstraint::Free(vts) => assert!(vts.contains(types::F32)), _ => panic!("Unexpected constraint from value_argument_constraint"), } let c = Opcode::Call.constraints(); assert_eq!(c.num_fixed_results(), 0); assert_eq!(c.num_fixed_value_arguments(), 0); let
{ match *self { InstructionData::Call { func_ref, ref args, .. } => CallInfo::Direct(func_ref, args.as_slice(pool)), InstructionData::CallIndirect { sig_ref, ref args, .. } => CallInfo::Indirect(sig_ref, &args.as_slice(pool)[1..]), _ => { debug_assert!(!self.opcode().is_call()); CallInfo::NotACall } } }
identifier_body
instructions.rs
fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "{}", opcode_name(*self)) } } impl Opcode { /// Get the instruction format for this opcode. pub fn format(self) -> InstructionFormat { OPCODE_FORMAT[self as usize - 1] } /// Get the constraint descriptor for this opcode. /// Panic if this is called on `NotAnOpcode`. pub fn constraints(self) -> OpcodeConstraints { OPCODE_CONSTRAINTS[self as usize - 1] } } // This trait really belongs in cranelift-reader where it is used by the `.clif` file parser, but since // it critically depends on the `opcode_name()` function which is needed here anyway, it lives in // this module. This also saves us from running the build script twice to generate code for the two // separate crates. impl FromStr for Opcode { type Err = &'static str; /// Parse an Opcode name from a string. fn from_str(s: &str) -> Result<Self, &'static str> { use crate::constant_hash::{probe, simple_hash, Table}; impl<'a> Table<&'a str> for [Option<Opcode>] { fn len(&self) -> usize { self.len() } fn key(&self, idx: usize) -> Option<&'a str> { self[idx].map(opcode_name) } } match probe::<&str, [Option<Self>]>(&OPCODE_HASH_TABLE, s, simple_hash(s)) { Err(_) => Err("Unknown opcode"), // We unwrap here because probe() should have ensured that the entry // at this index is not None. Ok(i) => Ok(OPCODE_HASH_TABLE[i].unwrap()), } } } /// A variable list of `Value` operands used for function call arguments and passing arguments to /// basic blocks. #[derive(Clone, Debug)] pub struct VariableArgs(Vec<Value>); impl VariableArgs { /// Create an empty argument list. pub fn new() -> Self { VariableArgs(Vec::new()) } /// Add an argument to the end. pub fn push(&mut self, v: Value) { self.0.push(v) } /// Check if the list is empty. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Convert this to a value list in `pool` with `fixed` prepended. pub fn into_value_list(self, fixed: &[Value], pool: &mut ValueListPool) -> ValueList { let mut vlist = ValueList::default(); vlist.extend(fixed.iter().cloned(), pool); vlist.extend(self.0, pool); vlist } } // Coerce `VariableArgs` into a `&[Value]` slice. impl Deref for VariableArgs { type Target = [Value]; fn deref(&self) -> &[Value] { &self.0 } } impl DerefMut for VariableArgs { fn deref_mut(&mut self) -> &mut [Value] { &mut self.0 } } impl Display for VariableArgs { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { for (i, val) in self.0.iter().enumerate() { if i == 0 { write!(fmt, "{}", val)?; } else { write!(fmt, ", {}", val)?; } } Ok(()) } } impl Default for VariableArgs { fn default() -> Self { Self::new() } } /// Analyzing an instruction. /// /// Avoid large matches on instruction formats by using the methods defined here to examine /// instructions. impl InstructionData { /// Return information about the destination of a branch or jump instruction. /// /// Any instruction that can transfer control to another EBB reveals its possible destinations /// here. pub fn
<'a>(&'a self, pool: &'a ValueListPool) -> BranchInfo<'a> { match *self { InstructionData::Jump { destination, ref args, .. } => BranchInfo::SingleDest(destination, args.as_slice(pool)), InstructionData::BranchInt { destination, ref args, .. } | InstructionData::BranchFloat { destination, ref args, .. } | InstructionData::Branch { destination, ref args, .. } => BranchInfo::SingleDest(destination, &args.as_slice(pool)[1..]), InstructionData::BranchIcmp { destination, ref args, .. } => BranchInfo::SingleDest(destination, &args.as_slice(pool)[2..]), InstructionData::BranchTable { table, destination,.. } => BranchInfo::Table(table, Some(destination)), InstructionData::IndirectJump { table,.. } => BranchInfo::Table(table, None), _ => { debug_assert!(!self.opcode().is_branch()); BranchInfo::NotABranch } } } /// Get the single destination of this branch instruction, if it is a single destination /// branch or jump. /// /// Multi-destination branches like `br_table` return `None`. pub fn branch_destination(&self) -> Option<Ebb> { match *self { InstructionData::Jump { destination,.. } | InstructionData::Branch { destination,.. } | InstructionData::BranchInt { destination,.. } | InstructionData::BranchFloat { destination,.. } | InstructionData::BranchIcmp { destination,.. } => Some(destination), InstructionData::BranchTable {.. } | InstructionData::IndirectJump {.. } => None, _ => { debug_assert!(!self.opcode().is_branch()); None } } } /// Get a mutable reference to the single destination of this branch instruction, if it is a /// single destination branch or jump. /// /// Multi-destination branches like `br_table` return `None`. pub fn branch_destination_mut(&mut self) -> Option<&mut Ebb> { match *self { InstructionData::Jump { ref mut destination, .. } | InstructionData::Branch { ref mut destination, .. } | InstructionData::BranchInt { ref mut destination, .. } | InstructionData::BranchFloat { ref mut destination, .. } | InstructionData::BranchIcmp { ref mut destination, .. } => Some(destination), InstructionData::BranchTable {.. } => None, _ => { debug_assert!(!self.opcode().is_branch()); None } } } /// Return information about a call instruction. /// /// Any instruction that can call another function reveals its call signature here. pub fn analyze_call<'a>(&'a self, pool: &'a ValueListPool) -> CallInfo<'a> { match *self { InstructionData::Call { func_ref, ref args,.. } => CallInfo::Direct(func_ref, args.as_slice(pool)), InstructionData::CallIndirect { sig_ref, ref args,.. } => CallInfo::Indirect(sig_ref, &args.as_slice(pool)[1..]), _ => { debug_assert!(!self.opcode().is_call()); CallInfo::NotACall } } } } /// Information about branch and jump instructions. pub enum BranchInfo<'a> { /// This is not a branch or jump instruction. /// This instruction will not transfer control to another EBB in the function, but it may still /// affect control flow by returning or trapping. NotABranch, /// This is a branch or jump to a single destination EBB, possibly taking value arguments. SingleDest(Ebb, &'a [Value]), /// This is a jump table branch which can have many destination EBBs and maybe one default EBB. Table(JumpTable, Option<Ebb>), } /// Information about call instructions. pub enum CallInfo<'a> { /// This is not a call instruction. NotACall, /// This is a direct call to an external function declared in the preamble. See /// `DataFlowGraph.ext_funcs`. Direct(FuncRef, &'a [Value]), /// This is an indirect call with the specified signature. See `DataFlowGraph.signatures`. Indirect(SigRef, &'a [Value]), } /// Value type constraints for a given opcode. /// /// The `InstructionFormat` determines the constraints on most operands, but `Value` operands and /// results are not determined by the format. Every `Opcode` has an associated /// `OpcodeConstraints` object that provides the missing details. #[derive(Clone, Copy)] pub struct OpcodeConstraints { /// Flags for this opcode encoded as a bit field: /// /// Bits 0-2: /// Number of fixed result values. This does not include `variable_args` results as are /// produced by call instructions. /// /// Bit 3: /// This opcode is polymorphic and the controlling type variable can be inferred from the /// designated input operand. This is the `typevar_operand` index given to the /// `InstructionFormat` meta language object. When this bit is not set, the controlling /// type variable must be the first output value instead. /// /// Bit 4: /// This opcode is polymorphic and the controlling type variable does *not* appear as the /// first result type. /// /// Bits 5-7: /// Number of fixed value arguments. The minimum required number of value operands. flags: u8, /// Permitted set of types for the controlling type variable as an index into `TYPE_SETS`. typeset_offset: u8, /// Offset into `OPERAND_CONSTRAINT` table of the descriptors for this opcode. The first /// `num_fixed_results()` entries describe the result constraints, then follows constraints for /// the fixed `Value` input operands. (`num_fixed_value_arguments()` of them). constraint_offset: u16, } impl OpcodeConstraints { /// Can the controlling type variable for this opcode be inferred from the designated value /// input operand? /// This also implies that this opcode is polymorphic. pub fn use_typevar_operand(self) -> bool { (self.flags & 0x8)!= 0 } /// Is it necessary to look at the designated value input operand in order to determine the /// controlling type variable, or is it good enough to use the first return type? /// /// Most polymorphic instructions produce a single result with the type of the controlling type /// variable. A few polymorphic instructions either don't produce any results, or produce /// results with a fixed type. These instructions return `true`. pub fn requires_typevar_operand(self) -> bool { (self.flags & 0x10)!= 0 } /// Get the number of *fixed* result values produced by this opcode. /// This does not include `variable_args` produced by calls. pub fn num_fixed_results(self) -> usize { (self.flags & 0x7) as usize } /// Get the number of *fixed* input values required by this opcode. /// /// This does not include `variable_args` arguments on call and branch instructions. /// /// The number of fixed input values is usually implied by the instruction format, but /// instruction formats that use a `ValueList` put both fixed and variable arguments in the /// list. This method returns the *minimum* number of values required in the value list. pub fn num_fixed_value_arguments(self) -> usize { ((self.flags >> 5) & 0x7) as usize } /// Get the offset into `TYPE_SETS` for the controlling type variable. /// Returns `None` if the instruction is not polymorphic. fn typeset_offset(self) -> Option<usize> { let offset = usize::from(self.typeset_offset); if offset < TYPE_SETS.len() { Some(offset) } else { None } } /// Get the offset into OPERAND_CONSTRAINTS where the descriptors for this opcode begin. fn constraint_offset(self) -> usize { self.constraint_offset as usize } /// Get the value type of result number `n`, having resolved the controlling type variable to /// `ctrl_type`. pub fn result_type(self, n: usize, ctrl_type: Type) -> Type { debug_assert!(n < self.num_fixed_results(), "Invalid result index"); if let ResolvedConstraint::Bound(t) = OPERAND_CONSTRAINTS[self.constraint_offset() + n].resolve(ctrl_type) { t } else { panic!("Result constraints can't be free"); } } /// Get the value type of input value number `n`, having resolved the controlling type variable /// to `ctrl_type`. /// /// Unlike results, it is possible for some input values to vary freely within a specific /// `ValueTypeSet`. This is represented with the `ArgumentConstraint::Free` variant. pub fn value_argument_constraint(self, n: usize, ctrl_type: Type) -> ResolvedConstraint { debug_assert!( n < self.num_fixed_value_arguments(), "Invalid value argument index" ); let offset = self.constraint_offset() + self.num_fixed_results(); OPERAND_CONSTRAINTS[offset + n].resolve(ctrl_type) } /// Get the typeset of allowed types for the controlling type variable in a polymorphic /// instruction. pub fn ctrl_typeset(self) -> Option<ValueTypeSet> { self.typeset_offset().map(|offset| TYPE_SETS[offset]) } /// Is this instruction polymorphic? pub fn is_polymorphic(self) -> bool { self.ctrl_typeset().is_some() } } type BitSet8 = BitSet<u8>; type BitSet16 = BitSet<u16>; /// A value type set describes the permitted set of types for a type variable. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ValueTypeSet { /// Allowed lane sizes pub lanes: BitSet16, /// Allowed int widths pub ints: BitSet8, /// Allowed float widths pub floats: BitSet8, /// Allowed bool widths pub bools: BitSet8, } impl ValueTypeSet { /// Is `scalar` part of the base type set? /// /// Note that the base type set does not have to be included in the type set proper. fn is_base_type(self, scalar: Type) -> bool { let l2b = scalar.log2_lane_bits(); if scalar.is_int() { self.ints.contains(l2b) } else if scalar.is_float() { self.floats.contains(l2b) } else if scalar.is_bool() { self.bools.contains(l2b) } else { false } } /// Does `typ` belong to this set? pub fn contains(self, typ: Type) -> bool { let l2l = typ.log2_lane_count(); self.lanes.contains(l2l) && self.is_base_type(typ.lane_type()) } /// Get an example member of this type set. /// /// This is used for error messages to avoid suggesting invalid types. pub fn example(self) -> Type { let t = if self.ints.max().unwrap_or(0) > 5 { types::I32 } else if self.floats.max().unwrap_or(0) > 5 { types::F32 } else if self.bools.max().unwrap_or(0) > 5 { types::B32 } else { types::B1 }; t.by(1 << self.lanes.min().unwrap()).unwrap() } } /// Operand constraints. This describes the value type constraints on a single `Value` operand. enum OperandConstraint { /// This operand has a concrete value type. Concrete(Type), /// This operand can vary freely within the given type set. /// The type set is identified by its index into the TYPE_SETS constant table. Free(u8), /// This operand is the same type as the controlling type variable. Same, /// This operand is `ctrlType.lane_type()`. LaneOf, /// This operand is `ctrlType.as_bool()`. AsBool, /// This operand is `ctrlType.half_width()`. HalfWidth, /// This operand is `ctrlType.double_width()`. DoubleWidth, /// This operand is `ctrlType.half_vector()`. HalfVector, /// This operand is `ctrlType.double_vector()`. DoubleVector, } impl OperandConstraint { /// Resolve this operand constraint into a concrete value type, given the value of the /// controlling type variable. pub fn resolve(&self, ctrl_type: Type) -> ResolvedConstraint { use self::OperandConstraint::*; use self::ResolvedConstraint::Bound; match *self { Concrete(t) => Bound(t), Free(vts) => ResolvedConstraint::Free(TYPE_SETS[vts as usize]), Same => Bound(ctrl_type), LaneOf => Bound(ctrl_type.lane_type()), AsBool => Bound(ctrl_type.as_bool()), HalfWidth => Bound(ctrl_type.half_width().expect("invalid type for half_width")), DoubleWidth => Bound( ctrl_type .double_width() .expect("invalid type for double_width"), ), HalfVector => Bound( ctrl_type .half_vector() .expect("invalid type for half_vector"), ), DoubleVector => Bound(ctrl_type.by(2).expect("invalid type for double_vector")), } } } /// The type constraint on a value argument once the controlling type variable is known. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum ResolvedConstraint { /// The operand is bound to a known type. Bound(Type), /// The operand type can vary freely within the given set. Free(ValueTypeSet), } #[cfg(test)] mod tests { use super::*; use std::string::ToString; #[test] fn opcodes() { use core::mem; let x = Opcode::Iadd; let mut y = Opcode::Isub; assert!(x!= y); y = Opcode::Iadd; assert_eq!(x, y); assert_eq!(x.format(), InstructionFormat::Binary); assert_eq!(format!("{:?}", Opcode::IaddImm), "IaddImm"); assert_eq!(Opcode::IaddImm.to_string(), "iadd_imm"); // Check the matcher. assert_eq!("iadd".parse::<Opcode>(), Ok(Opcode::Iadd)); assert_eq!("iadd_imm".parse::<Opcode>(), Ok(Opcode::IaddImm)); assert_eq!("iadd\0".parse::<Opcode>(), Err("Unknown opcode")); assert_eq!("".parse::<Opcode>(), Err("Unknown opcode")); assert_eq!("\0".parse::<Opcode>(), Err("Unknown opcode")); // Opcode is a single byte, and because Option<Opcode> originally came to 2 bytes, early on // Opcode included a variant NotAnOpcode to avoid the unnecessary bloat. Since then the Rust // compiler has brought in NonZero optimization, meaning that an enum not using the 0 value // can be optional for no size cost. We want to ensure Option<Opcode> remains small. assert_eq!(mem::size_of::<Opcode>(), mem::size_of::<Option<Opcode>>()); } #[test] fn instruction_data() { use core::mem; // The size of the `InstructionData` enum is important for performance. It should not // exceed 16 bytes. Use `Box<FooData>` out-of-line payloads for instruction formats that // require more space than that. It would be fine with a data structure smaller than 16 // bytes, but what are the odds of that? assert_eq!(mem::size_of::<InstructionData>(), 16); } #[test] fn constraints() { let a = Opcode::Iadd.constraints(); assert!(a.use_typevar_operand()); assert!(!a.requires_typevar_operand()); assert_eq!(a.num_fixed_results(), 1); assert_eq!(a.num_fixed_value_arguments(), 2); assert_eq!(a.result_type(0, types::I32), types::I32); assert_eq!(a.result_type(0, types::I8), types::I8); assert_eq!( a.value_argument_constraint(0, types::I32), ResolvedConstraint::Bound(types::I32) ); assert_eq!( a.value_argument_constraint(1, types::I32), ResolvedConstraint::Bound(types::I32) ); let b = Opcode::Bitcast.constraints(); assert!(!b.use_typevar_operand()); assert!(!b.requires_typevar_operand()); assert_eq!(b.num_fixed_results(), 1); assert_eq!(b.num_fixed_value_arguments(), 1); assert_eq!(b.result_type(0, types::I32), types::I32); assert_eq!(b.result_type(0, types::I8), types::I8); match b.value_argument_constraint(0, types::I32) { ResolvedConstraint::Free(vts) => assert!(vts.contains(types::F32)), _ => panic!("Unexpected constraint from value_argument_constraint"), } let c = Opcode::Call.constraints(); assert_eq!(c.num_fixed_results(), 0); assert_eq!(c.num_fixed_value_arguments(), 0); let
analyze_branch
identifier_name
instructions.rs
Table}; impl<'a> Table<&'a str> for [Option<Opcode>] { fn len(&self) -> usize { self.len() } fn key(&self, idx: usize) -> Option<&'a str> { self[idx].map(opcode_name) } } match probe::<&str, [Option<Self>]>(&OPCODE_HASH_TABLE, s, simple_hash(s)) { Err(_) => Err("Unknown opcode"), // We unwrap here because probe() should have ensured that the entry // at this index is not None. Ok(i) => Ok(OPCODE_HASH_TABLE[i].unwrap()), } } } /// A variable list of `Value` operands used for function call arguments and passing arguments to /// basic blocks. #[derive(Clone, Debug)] pub struct VariableArgs(Vec<Value>); impl VariableArgs { /// Create an empty argument list. pub fn new() -> Self { VariableArgs(Vec::new()) } /// Add an argument to the end. pub fn push(&mut self, v: Value) { self.0.push(v) } /// Check if the list is empty. pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Convert this to a value list in `pool` with `fixed` prepended. pub fn into_value_list(self, fixed: &[Value], pool: &mut ValueListPool) -> ValueList { let mut vlist = ValueList::default(); vlist.extend(fixed.iter().cloned(), pool); vlist.extend(self.0, pool); vlist } } // Coerce `VariableArgs` into a `&[Value]` slice. impl Deref for VariableArgs { type Target = [Value]; fn deref(&self) -> &[Value] { &self.0 } } impl DerefMut for VariableArgs { fn deref_mut(&mut self) -> &mut [Value] { &mut self.0 } } impl Display for VariableArgs { fn fmt(&self, fmt: &mut Formatter) -> fmt::Result { for (i, val) in self.0.iter().enumerate() { if i == 0 { write!(fmt, "{}", val)?; } else { write!(fmt, ", {}", val)?; } } Ok(()) } } impl Default for VariableArgs { fn default() -> Self { Self::new() } } /// Analyzing an instruction. /// /// Avoid large matches on instruction formats by using the methods defined here to examine /// instructions. impl InstructionData { /// Return information about the destination of a branch or jump instruction. /// /// Any instruction that can transfer control to another EBB reveals its possible destinations /// here. pub fn analyze_branch<'a>(&'a self, pool: &'a ValueListPool) -> BranchInfo<'a> { match *self { InstructionData::Jump { destination, ref args, .. } => BranchInfo::SingleDest(destination, args.as_slice(pool)), InstructionData::BranchInt { destination, ref args, .. } | InstructionData::BranchFloat { destination, ref args, .. } | InstructionData::Branch { destination, ref args, .. } => BranchInfo::SingleDest(destination, &args.as_slice(pool)[1..]), InstructionData::BranchIcmp { destination, ref args, .. } => BranchInfo::SingleDest(destination, &args.as_slice(pool)[2..]), InstructionData::BranchTable { table, destination,.. } => BranchInfo::Table(table, Some(destination)), InstructionData::IndirectJump { table,.. } => BranchInfo::Table(table, None), _ => { debug_assert!(!self.opcode().is_branch()); BranchInfo::NotABranch } } } /// Get the single destination of this branch instruction, if it is a single destination /// branch or jump. /// /// Multi-destination branches like `br_table` return `None`. pub fn branch_destination(&self) -> Option<Ebb> { match *self { InstructionData::Jump { destination,.. } | InstructionData::Branch { destination,.. } | InstructionData::BranchInt { destination,.. } | InstructionData::BranchFloat { destination,.. } | InstructionData::BranchIcmp { destination,.. } => Some(destination), InstructionData::BranchTable {.. } | InstructionData::IndirectJump {.. } => None, _ => { debug_assert!(!self.opcode().is_branch()); None } } } /// Get a mutable reference to the single destination of this branch instruction, if it is a /// single destination branch or jump. /// /// Multi-destination branches like `br_table` return `None`. pub fn branch_destination_mut(&mut self) -> Option<&mut Ebb> { match *self { InstructionData::Jump { ref mut destination, .. } | InstructionData::Branch { ref mut destination, .. } | InstructionData::BranchInt { ref mut destination, .. } | InstructionData::BranchFloat { ref mut destination, .. } | InstructionData::BranchIcmp { ref mut destination, .. } => Some(destination), InstructionData::BranchTable {.. } => None, _ => { debug_assert!(!self.opcode().is_branch()); None } } } /// Return information about a call instruction. /// /// Any instruction that can call another function reveals its call signature here. pub fn analyze_call<'a>(&'a self, pool: &'a ValueListPool) -> CallInfo<'a> { match *self { InstructionData::Call { func_ref, ref args,.. } => CallInfo::Direct(func_ref, args.as_slice(pool)), InstructionData::CallIndirect { sig_ref, ref args,.. } => CallInfo::Indirect(sig_ref, &args.as_slice(pool)[1..]), _ => { debug_assert!(!self.opcode().is_call()); CallInfo::NotACall } } } } /// Information about branch and jump instructions. pub enum BranchInfo<'a> { /// This is not a branch or jump instruction. /// This instruction will not transfer control to another EBB in the function, but it may still /// affect control flow by returning or trapping. NotABranch, /// This is a branch or jump to a single destination EBB, possibly taking value arguments. SingleDest(Ebb, &'a [Value]), /// This is a jump table branch which can have many destination EBBs and maybe one default EBB. Table(JumpTable, Option<Ebb>), } /// Information about call instructions. pub enum CallInfo<'a> { /// This is not a call instruction. NotACall, /// This is a direct call to an external function declared in the preamble. See /// `DataFlowGraph.ext_funcs`. Direct(FuncRef, &'a [Value]), /// This is an indirect call with the specified signature. See `DataFlowGraph.signatures`. Indirect(SigRef, &'a [Value]), } /// Value type constraints for a given opcode. /// /// The `InstructionFormat` determines the constraints on most operands, but `Value` operands and /// results are not determined by the format. Every `Opcode` has an associated /// `OpcodeConstraints` object that provides the missing details. #[derive(Clone, Copy)] pub struct OpcodeConstraints { /// Flags for this opcode encoded as a bit field: /// /// Bits 0-2: /// Number of fixed result values. This does not include `variable_args` results as are /// produced by call instructions. /// /// Bit 3: /// This opcode is polymorphic and the controlling type variable can be inferred from the /// designated input operand. This is the `typevar_operand` index given to the /// `InstructionFormat` meta language object. When this bit is not set, the controlling /// type variable must be the first output value instead. /// /// Bit 4: /// This opcode is polymorphic and the controlling type variable does *not* appear as the /// first result type. /// /// Bits 5-7: /// Number of fixed value arguments. The minimum required number of value operands. flags: u8, /// Permitted set of types for the controlling type variable as an index into `TYPE_SETS`. typeset_offset: u8, /// Offset into `OPERAND_CONSTRAINT` table of the descriptors for this opcode. The first /// `num_fixed_results()` entries describe the result constraints, then follows constraints for /// the fixed `Value` input operands. (`num_fixed_value_arguments()` of them). constraint_offset: u16, } impl OpcodeConstraints { /// Can the controlling type variable for this opcode be inferred from the designated value /// input operand? /// This also implies that this opcode is polymorphic. pub fn use_typevar_operand(self) -> bool { (self.flags & 0x8)!= 0 } /// Is it necessary to look at the designated value input operand in order to determine the /// controlling type variable, or is it good enough to use the first return type? /// /// Most polymorphic instructions produce a single result with the type of the controlling type /// variable. A few polymorphic instructions either don't produce any results, or produce /// results with a fixed type. These instructions return `true`. pub fn requires_typevar_operand(self) -> bool { (self.flags & 0x10)!= 0 } /// Get the number of *fixed* result values produced by this opcode. /// This does not include `variable_args` produced by calls. pub fn num_fixed_results(self) -> usize { (self.flags & 0x7) as usize } /// Get the number of *fixed* input values required by this opcode. /// /// This does not include `variable_args` arguments on call and branch instructions. /// /// The number of fixed input values is usually implied by the instruction format, but /// instruction formats that use a `ValueList` put both fixed and variable arguments in the /// list. This method returns the *minimum* number of values required in the value list. pub fn num_fixed_value_arguments(self) -> usize { ((self.flags >> 5) & 0x7) as usize } /// Get the offset into `TYPE_SETS` for the controlling type variable. /// Returns `None` if the instruction is not polymorphic. fn typeset_offset(self) -> Option<usize> { let offset = usize::from(self.typeset_offset); if offset < TYPE_SETS.len() { Some(offset) } else { None } } /// Get the offset into OPERAND_CONSTRAINTS where the descriptors for this opcode begin. fn constraint_offset(self) -> usize { self.constraint_offset as usize } /// Get the value type of result number `n`, having resolved the controlling type variable to /// `ctrl_type`. pub fn result_type(self, n: usize, ctrl_type: Type) -> Type { debug_assert!(n < self.num_fixed_results(), "Invalid result index"); if let ResolvedConstraint::Bound(t) = OPERAND_CONSTRAINTS[self.constraint_offset() + n].resolve(ctrl_type) { t } else { panic!("Result constraints can't be free"); } } /// Get the value type of input value number `n`, having resolved the controlling type variable /// to `ctrl_type`. /// /// Unlike results, it is possible for some input values to vary freely within a specific /// `ValueTypeSet`. This is represented with the `ArgumentConstraint::Free` variant. pub fn value_argument_constraint(self, n: usize, ctrl_type: Type) -> ResolvedConstraint { debug_assert!( n < self.num_fixed_value_arguments(), "Invalid value argument index" ); let offset = self.constraint_offset() + self.num_fixed_results(); OPERAND_CONSTRAINTS[offset + n].resolve(ctrl_type) } /// Get the typeset of allowed types for the controlling type variable in a polymorphic /// instruction. pub fn ctrl_typeset(self) -> Option<ValueTypeSet> { self.typeset_offset().map(|offset| TYPE_SETS[offset]) } /// Is this instruction polymorphic? pub fn is_polymorphic(self) -> bool { self.ctrl_typeset().is_some() } } type BitSet8 = BitSet<u8>; type BitSet16 = BitSet<u16>; /// A value type set describes the permitted set of types for a type variable. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ValueTypeSet { /// Allowed lane sizes pub lanes: BitSet16, /// Allowed int widths pub ints: BitSet8, /// Allowed float widths pub floats: BitSet8, /// Allowed bool widths pub bools: BitSet8, } impl ValueTypeSet { /// Is `scalar` part of the base type set? /// /// Note that the base type set does not have to be included in the type set proper. fn is_base_type(self, scalar: Type) -> bool { let l2b = scalar.log2_lane_bits(); if scalar.is_int() { self.ints.contains(l2b) } else if scalar.is_float() { self.floats.contains(l2b) } else if scalar.is_bool() { self.bools.contains(l2b) } else { false } } /// Does `typ` belong to this set? pub fn contains(self, typ: Type) -> bool { let l2l = typ.log2_lane_count(); self.lanes.contains(l2l) && self.is_base_type(typ.lane_type()) } /// Get an example member of this type set. /// /// This is used for error messages to avoid suggesting invalid types. pub fn example(self) -> Type { let t = if self.ints.max().unwrap_or(0) > 5 { types::I32 } else if self.floats.max().unwrap_or(0) > 5 { types::F32 } else if self.bools.max().unwrap_or(0) > 5 { types::B32 } else { types::B1 }; t.by(1 << self.lanes.min().unwrap()).unwrap() } } /// Operand constraints. This describes the value type constraints on a single `Value` operand. enum OperandConstraint { /// This operand has a concrete value type. Concrete(Type), /// This operand can vary freely within the given type set. /// The type set is identified by its index into the TYPE_SETS constant table. Free(u8), /// This operand is the same type as the controlling type variable. Same, /// This operand is `ctrlType.lane_type()`. LaneOf, /// This operand is `ctrlType.as_bool()`. AsBool, /// This operand is `ctrlType.half_width()`. HalfWidth, /// This operand is `ctrlType.double_width()`. DoubleWidth, /// This operand is `ctrlType.half_vector()`. HalfVector, /// This operand is `ctrlType.double_vector()`. DoubleVector, } impl OperandConstraint { /// Resolve this operand constraint into a concrete value type, given the value of the /// controlling type variable. pub fn resolve(&self, ctrl_type: Type) -> ResolvedConstraint { use self::OperandConstraint::*; use self::ResolvedConstraint::Bound; match *self { Concrete(t) => Bound(t), Free(vts) => ResolvedConstraint::Free(TYPE_SETS[vts as usize]), Same => Bound(ctrl_type), LaneOf => Bound(ctrl_type.lane_type()), AsBool => Bound(ctrl_type.as_bool()), HalfWidth => Bound(ctrl_type.half_width().expect("invalid type for half_width")), DoubleWidth => Bound( ctrl_type .double_width() .expect("invalid type for double_width"), ), HalfVector => Bound( ctrl_type .half_vector() .expect("invalid type for half_vector"), ), DoubleVector => Bound(ctrl_type.by(2).expect("invalid type for double_vector")), } } } /// The type constraint on a value argument once the controlling type variable is known. #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum ResolvedConstraint { /// The operand is bound to a known type. Bound(Type), /// The operand type can vary freely within the given set. Free(ValueTypeSet), } #[cfg(test)] mod tests { use super::*; use std::string::ToString; #[test] fn opcodes() { use core::mem; let x = Opcode::Iadd; let mut y = Opcode::Isub; assert!(x!= y); y = Opcode::Iadd; assert_eq!(x, y); assert_eq!(x.format(), InstructionFormat::Binary); assert_eq!(format!("{:?}", Opcode::IaddImm), "IaddImm"); assert_eq!(Opcode::IaddImm.to_string(), "iadd_imm"); // Check the matcher. assert_eq!("iadd".parse::<Opcode>(), Ok(Opcode::Iadd)); assert_eq!("iadd_imm".parse::<Opcode>(), Ok(Opcode::IaddImm)); assert_eq!("iadd\0".parse::<Opcode>(), Err("Unknown opcode")); assert_eq!("".parse::<Opcode>(), Err("Unknown opcode")); assert_eq!("\0".parse::<Opcode>(), Err("Unknown opcode")); // Opcode is a single byte, and because Option<Opcode> originally came to 2 bytes, early on // Opcode included a variant NotAnOpcode to avoid the unnecessary bloat. Since then the Rust // compiler has brought in NonZero optimization, meaning that an enum not using the 0 value // can be optional for no size cost. We want to ensure Option<Opcode> remains small. assert_eq!(mem::size_of::<Opcode>(), mem::size_of::<Option<Opcode>>()); } #[test] fn instruction_data() { use core::mem; // The size of the `InstructionData` enum is important for performance. It should not // exceed 16 bytes. Use `Box<FooData>` out-of-line payloads for instruction formats that // require more space than that. It would be fine with a data structure smaller than 16 // bytes, but what are the odds of that? assert_eq!(mem::size_of::<InstructionData>(), 16); } #[test] fn constraints() { let a = Opcode::Iadd.constraints(); assert!(a.use_typevar_operand()); assert!(!a.requires_typevar_operand()); assert_eq!(a.num_fixed_results(), 1); assert_eq!(a.num_fixed_value_arguments(), 2); assert_eq!(a.result_type(0, types::I32), types::I32); assert_eq!(a.result_type(0, types::I8), types::I8); assert_eq!( a.value_argument_constraint(0, types::I32), ResolvedConstraint::Bound(types::I32) ); assert_eq!( a.value_argument_constraint(1, types::I32), ResolvedConstraint::Bound(types::I32) ); let b = Opcode::Bitcast.constraints(); assert!(!b.use_typevar_operand()); assert!(!b.requires_typevar_operand()); assert_eq!(b.num_fixed_results(), 1); assert_eq!(b.num_fixed_value_arguments(), 1); assert_eq!(b.result_type(0, types::I32), types::I32); assert_eq!(b.result_type(0, types::I8), types::I8); match b.value_argument_constraint(0, types::I32) { ResolvedConstraint::Free(vts) => assert!(vts.contains(types::F32)), _ => panic!("Unexpected constraint from value_argument_constraint"), } let c = Opcode::Call.constraints(); assert_eq!(c.num_fixed_results(), 0); assert_eq!(c.num_fixed_value_arguments(), 0); let i = Opcode::CallIndirect.constraints(); assert_eq!(i.num_fixed_results(), 0); assert_eq!(i.num_fixed_value_arguments(), 1); let cmp = Opcode::Icmp.constraints(); assert!(cmp.use_typevar_operand()); assert!(cmp.requires_typevar_operand()); assert_eq!(cmp.num_fixed_results(), 1); assert_eq!(cmp.num_fixed_value_arguments(), 2); } #[test] fn value_set() { use crate::ir::types::*; let vts = ValueTypeSet { lanes: BitSet16::from_range(0, 8),
ints: BitSet8::from_range(4, 7), floats: BitSet8::from_range(0, 0), bools: BitSet8::from_range(3, 7), };
random_line_split
union-fields-2.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. union U { a: u8, b: u16, }
let u = U {}; //~ ERROR union expressions should have exactly one field let u = U { a: 0 }; // OK let u = U { a: 0, b: 1 }; //~ ERROR union expressions should have exactly one field let u = U { a: 0, b: 1, c: 2 }; //~ ERROR union expressions should have exactly one field //~^ ERROR union `U` has no field named `c` let u = U {..u }; //~ ERROR union expressions should have exactly one field //~^ ERROR functional record update syntax requires a struct let U {} = u; //~ ERROR union patterns should have exactly one field let U { a } = u; // OK let U { a, b } = u; //~ ERROR union patterns should have exactly one field let U { a, b, c } = u; //~ ERROR union patterns should have exactly one field //~^ ERROR union `U` does not have a field named `c` let U {.. } = u; //~ ERROR union patterns should have exactly one field //~^ ERROR `..` cannot be used in union patterns let U { a,.. } = u; //~ ERROR `..` cannot be used in union patterns }
fn main() {
random_line_split
union-fields-2.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. union U { a: u8, b: u16, } fn
() { let u = U {}; //~ ERROR union expressions should have exactly one field let u = U { a: 0 }; // OK let u = U { a: 0, b: 1 }; //~ ERROR union expressions should have exactly one field let u = U { a: 0, b: 1, c: 2 }; //~ ERROR union expressions should have exactly one field //~^ ERROR union `U` has no field named `c` let u = U {..u }; //~ ERROR union expressions should have exactly one field //~^ ERROR functional record update syntax requires a struct let U {} = u; //~ ERROR union patterns should have exactly one field let U { a } = u; // OK let U { a, b } = u; //~ ERROR union patterns should have exactly one field let U { a, b, c } = u; //~ ERROR union patterns should have exactly one field //~^ ERROR union `U` does not have a field named `c` let U {.. } = u; //~ ERROR union patterns should have exactly one field //~^ ERROR `..` cannot be used in union patterns let U { a,.. } = u; //~ ERROR `..` cannot be used in union patterns }
main
identifier_name
union-fields-2.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. union U { a: u8, b: u16, } fn main()
{ let u = U {}; //~ ERROR union expressions should have exactly one field let u = U { a: 0 }; // OK let u = U { a: 0, b: 1 }; //~ ERROR union expressions should have exactly one field let u = U { a: 0, b: 1, c: 2 }; //~ ERROR union expressions should have exactly one field //~^ ERROR union `U` has no field named `c` let u = U { ..u }; //~ ERROR union expressions should have exactly one field //~^ ERROR functional record update syntax requires a struct let U {} = u; //~ ERROR union patterns should have exactly one field let U { a } = u; // OK let U { a, b } = u; //~ ERROR union patterns should have exactly one field let U { a, b, c } = u; //~ ERROR union patterns should have exactly one field //~^ ERROR union `U` does not have a field named `c` let U { .. } = u; //~ ERROR union patterns should have exactly one field //~^ ERROR `..` cannot be used in union patterns let U { a, .. } = u; //~ ERROR `..` cannot be used in union patterns }
identifier_body
lib.rs
// @generated by Thrift for src/mod.thrift // This file is probably not the place you want to edit! #![recursion_limit = "100000000"] #![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, unused_crate_dependencies)] pub use self::errors::*; pub use self::types::*; /// Thrift type definitions for `mod`. pub mod types { #![allow(clippy::redundant_closure)] #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Foo, Bar)] pub struct WithCustomDerives { pub a: ::std::primitive::bool, // This field forces `..Default::default()` when instantiating this // struct, to make code future-proof against new fields added later to // the definition in Thrift. If you don't want this, add the annotation // `(rust.exhaustive)` to the Thrift struct to eliminate this field. #[doc(hidden)] pub _dot_dot_Default_default: self::dot_dot::OtherFields, } impl ::std::default::Default for self::WithCustomDerives { fn default() -> Self { Self { a: ::std::default::Default::default(), _dot_dot_Default_default: self::dot_dot::OtherFields(()), } } } impl ::std::fmt::Debug for self::WithCustomDerives { fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { formatter .debug_struct("WithCustomDerives") .field("a", &self.a) .finish() } } unsafe impl ::std::marker::Send for self::WithCustomDerives {} unsafe impl ::std::marker::Sync for self::WithCustomDerives {} impl ::fbthrift::GetTType for self::WithCustomDerives { const TTYPE: ::fbthrift::TType = ::fbthrift::TType::Struct; } impl<P> ::fbthrift::Serialize<P> for self::WithCustomDerives where P: ::fbthrift::ProtocolWriter, { fn write(&self, p: &mut P) { p.write_struct_begin("WithCustomDerives"); p.write_field_begin("a", ::fbthrift::TType::Bool, 1); ::fbthrift::Serialize::write(&self.a, p); p.write_field_end(); p.write_field_stop(); p.write_struct_end(); } } impl<P> ::fbthrift::Deserialize<P> for self::WithCustomDerives where P: ::fbthrift::ProtocolReader, { fn read(p: &mut P) -> ::anyhow::Result<Self> { static FIELDS: &[::fbthrift::Field] = &[ ::fbthrift::Field::new("a", ::fbthrift::TType::Bool, 1), ]; let mut field_a = ::std::option::Option::None; let _ = p.read_struct_begin(|_| ())?; loop { let (_, fty, fid) = p.read_field_begin(|_| (), FIELDS)?; match (fty, fid as ::std::primitive::i32) { (::fbthrift::TType::Stop, _) => break, (::fbthrift::TType::Bool, 1) => field_a = ::std::option::Option::Some(::fbthrift::Deserialize::read(p)?), (fty, _) => p.skip(fty)?, } p.read_field_end()?; } p.read_struct_end()?; ::std::result::Result::Ok(Self { a: field_a.unwrap_or_default(), _dot_dot_Default_default: self::dot_dot::OtherFields(()), }) } } mod dot_dot { #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct
(pub(crate) ()); #[allow(dead_code)] // if serde isn't being used pub(super) fn default_for_serde_deserialize() -> OtherFields { OtherFields(()) } } } /// Error return types. pub mod errors { }
OtherFields
identifier_name
lib.rs
// @generated by Thrift for src/mod.thrift // This file is probably not the place you want to edit! #![recursion_limit = "100000000"] #![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, unused_crate_dependencies)] pub use self::errors::*; pub use self::types::*; /// Thrift type definitions for `mod`. pub mod types { #![allow(clippy::redundant_closure)] #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Foo, Bar)]
pub struct WithCustomDerives { pub a: ::std::primitive::bool, // This field forces `..Default::default()` when instantiating this // struct, to make code future-proof against new fields added later to // the definition in Thrift. If you don't want this, add the annotation // `(rust.exhaustive)` to the Thrift struct to eliminate this field. #[doc(hidden)] pub _dot_dot_Default_default: self::dot_dot::OtherFields, } impl ::std::default::Default for self::WithCustomDerives { fn default() -> Self { Self { a: ::std::default::Default::default(), _dot_dot_Default_default: self::dot_dot::OtherFields(()), } } } impl ::std::fmt::Debug for self::WithCustomDerives { fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { formatter .debug_struct("WithCustomDerives") .field("a", &self.a) .finish() } } unsafe impl ::std::marker::Send for self::WithCustomDerives {} unsafe impl ::std::marker::Sync for self::WithCustomDerives {} impl ::fbthrift::GetTType for self::WithCustomDerives { const TTYPE: ::fbthrift::TType = ::fbthrift::TType::Struct; } impl<P> ::fbthrift::Serialize<P> for self::WithCustomDerives where P: ::fbthrift::ProtocolWriter, { fn write(&self, p: &mut P) { p.write_struct_begin("WithCustomDerives"); p.write_field_begin("a", ::fbthrift::TType::Bool, 1); ::fbthrift::Serialize::write(&self.a, p); p.write_field_end(); p.write_field_stop(); p.write_struct_end(); } } impl<P> ::fbthrift::Deserialize<P> for self::WithCustomDerives where P: ::fbthrift::ProtocolReader, { fn read(p: &mut P) -> ::anyhow::Result<Self> { static FIELDS: &[::fbthrift::Field] = &[ ::fbthrift::Field::new("a", ::fbthrift::TType::Bool, 1), ]; let mut field_a = ::std::option::Option::None; let _ = p.read_struct_begin(|_| ())?; loop { let (_, fty, fid) = p.read_field_begin(|_| (), FIELDS)?; match (fty, fid as ::std::primitive::i32) { (::fbthrift::TType::Stop, _) => break, (::fbthrift::TType::Bool, 1) => field_a = ::std::option::Option::Some(::fbthrift::Deserialize::read(p)?), (fty, _) => p.skip(fty)?, } p.read_field_end()?; } p.read_struct_end()?; ::std::result::Result::Ok(Self { a: field_a.unwrap_or_default(), _dot_dot_Default_default: self::dot_dot::OtherFields(()), }) } } mod dot_dot { #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct OtherFields(pub(crate) ()); #[allow(dead_code)] // if serde isn't being used pub(super) fn default_for_serde_deserialize() -> OtherFields { OtherFields(()) } } } /// Error return types. pub mod errors { }
random_line_split
lib.rs
// @generated by Thrift for src/mod.thrift // This file is probably not the place you want to edit! #![recursion_limit = "100000000"] #![allow(non_camel_case_types, non_snake_case, non_upper_case_globals, unused_crate_dependencies)] pub use self::errors::*; pub use self::types::*; /// Thrift type definitions for `mod`. pub mod types { #![allow(clippy::redundant_closure)] #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Foo, Bar)] pub struct WithCustomDerives { pub a: ::std::primitive::bool, // This field forces `..Default::default()` when instantiating this // struct, to make code future-proof against new fields added later to // the definition in Thrift. If you don't want this, add the annotation // `(rust.exhaustive)` to the Thrift struct to eliminate this field. #[doc(hidden)] pub _dot_dot_Default_default: self::dot_dot::OtherFields, } impl ::std::default::Default for self::WithCustomDerives { fn default() -> Self { Self { a: ::std::default::Default::default(), _dot_dot_Default_default: self::dot_dot::OtherFields(()), } } } impl ::std::fmt::Debug for self::WithCustomDerives { fn fmt(&self, formatter: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { formatter .debug_struct("WithCustomDerives") .field("a", &self.a) .finish() } } unsafe impl ::std::marker::Send for self::WithCustomDerives {} unsafe impl ::std::marker::Sync for self::WithCustomDerives {} impl ::fbthrift::GetTType for self::WithCustomDerives { const TTYPE: ::fbthrift::TType = ::fbthrift::TType::Struct; } impl<P> ::fbthrift::Serialize<P> for self::WithCustomDerives where P: ::fbthrift::ProtocolWriter, { fn write(&self, p: &mut P) { p.write_struct_begin("WithCustomDerives"); p.write_field_begin("a", ::fbthrift::TType::Bool, 1); ::fbthrift::Serialize::write(&self.a, p); p.write_field_end(); p.write_field_stop(); p.write_struct_end(); } } impl<P> ::fbthrift::Deserialize<P> for self::WithCustomDerives where P: ::fbthrift::ProtocolReader, { fn read(p: &mut P) -> ::anyhow::Result<Self> { static FIELDS: &[::fbthrift::Field] = &[ ::fbthrift::Field::new("a", ::fbthrift::TType::Bool, 1), ]; let mut field_a = ::std::option::Option::None; let _ = p.read_struct_begin(|_| ())?; loop { let (_, fty, fid) = p.read_field_begin(|_| (), FIELDS)?; match (fty, fid as ::std::primitive::i32) { (::fbthrift::TType::Stop, _) => break, (::fbthrift::TType::Bool, 1) => field_a = ::std::option::Option::Some(::fbthrift::Deserialize::read(p)?), (fty, _) => p.skip(fty)?, } p.read_field_end()?; } p.read_struct_end()?; ::std::result::Result::Ok(Self { a: field_a.unwrap_or_default(), _dot_dot_Default_default: self::dot_dot::OtherFields(()), }) } } mod dot_dot { #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct OtherFields(pub(crate) ()); #[allow(dead_code)] // if serde isn't being used pub(super) fn default_for_serde_deserialize() -> OtherFields
} } /// Error return types. pub mod errors { }
{ OtherFields(()) }
identifier_body
stream.rs
use ffi::{sockaddr, socklen_t, AF_UNIX, SOCK_STREAM}; use core::{Endpoint, Protocol}; use socket_listener::SocketListener; use stream_socket::StreamSocket; use local::LocalEndpoint; use std::fmt; use std::mem; /// The stream-oriented UNIX domain protocol. /// /// # Example /// Create a server and client sockets. /// /// ```rust,no_run /// use asyncio::{IoContext, Endpoint}; /// use asyncio::local::{LocalStream, LocalStreamEndpoint, LocalStreamSocket, LocalStreamListener}; /// /// let ctx = &IoContext::new().unwrap(); /// let ep = LocalStreamEndpoint::new("example.sock").unwrap(); /// /// let sv = LocalStreamListener::new(ctx, LocalStream).unwrap(); /// sv.bind(&ep).unwrap(); /// sv.listen().unwrap(); /// /// let cl = LocalStreamSocket::new(ctx, ep.protocol()).unwrap(); /// cl.connect(&ep).unwrap(); /// ``` #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct LocalStream; impl Protocol for LocalStream { type Endpoint = LocalEndpoint<Self>; type Socket = LocalStreamSocket; fn family_type(&self) -> i32 { AF_UNIX
fn socket_type(&self) -> i32 { SOCK_STREAM } fn protocol_type(&self) -> i32 { 0 } unsafe fn uninitialized(&self) -> Self::Endpoint { mem::uninitialized() } } impl Endpoint<LocalStream> for LocalEndpoint<LocalStream> { fn protocol(&self) -> LocalStream { LocalStream } fn as_ptr(&self) -> *const sockaddr { &self.sun as *const _ as *const _ } fn as_mut_ptr(&mut self) -> *mut sockaddr { &mut self.sun as *mut _ as *mut _ } fn capacity(&self) -> socklen_t { self.sun.capacity() as socklen_t } fn size(&self) -> socklen_t { self.sun.size() as socklen_t } unsafe fn resize(&mut self, size: socklen_t) { debug_assert!(size <= self.capacity()); self.sun.resize(size as u8) } } impl fmt::Debug for LocalEndpoint<LocalStream> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}:{:?})", self.protocol(), self.as_pathname()) } } /// The stream-oriented UNIX domain endpoint type pub type LocalStreamEndpoint = LocalEndpoint<LocalStream>; /// The stream-oriented UNIX domain socket type. pub type LocalStreamSocket = StreamSocket<LocalStream>; /// The stream-oriented UNIX domain listener type. pub type LocalStreamListener = SocketListener<LocalStream>; #[test] fn test_getsockname_local() { use core::IoContext; use local::*; use std::fs; let ctx = &IoContext::new().unwrap(); let ep = LocalStreamEndpoint::new(".asio_foo.sock").unwrap(); println!("{:?}", ep.as_pathname().unwrap()); let _ = fs::remove_file(ep.as_pathname().unwrap()); let soc = LocalStreamSocket::new(ctx, ep.protocol()).unwrap(); soc.bind(&ep).unwrap(); assert_eq!(soc.local_endpoint().unwrap(), ep); assert_eq!(soc.local_endpoint().unwrap(), ep); let _ = fs::remove_file(ep.as_pathname().unwrap()); } #[test] fn test_format() { use core::IoContext; let _ctx = &IoContext::new().unwrap(); println!("{:?}", LocalStream); println!("{:?}", LocalStreamEndpoint::new("foo/bar").unwrap()); }
}
random_line_split
stream.rs
use ffi::{sockaddr, socklen_t, AF_UNIX, SOCK_STREAM}; use core::{Endpoint, Protocol}; use socket_listener::SocketListener; use stream_socket::StreamSocket; use local::LocalEndpoint; use std::fmt; use std::mem; /// The stream-oriented UNIX domain protocol. /// /// # Example /// Create a server and client sockets. /// /// ```rust,no_run /// use asyncio::{IoContext, Endpoint}; /// use asyncio::local::{LocalStream, LocalStreamEndpoint, LocalStreamSocket, LocalStreamListener}; /// /// let ctx = &IoContext::new().unwrap(); /// let ep = LocalStreamEndpoint::new("example.sock").unwrap(); /// /// let sv = LocalStreamListener::new(ctx, LocalStream).unwrap(); /// sv.bind(&ep).unwrap(); /// sv.listen().unwrap(); /// /// let cl = LocalStreamSocket::new(ctx, ep.protocol()).unwrap(); /// cl.connect(&ep).unwrap(); /// ``` #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct LocalStream; impl Protocol for LocalStream { type Endpoint = LocalEndpoint<Self>; type Socket = LocalStreamSocket; fn family_type(&self) -> i32 { AF_UNIX } fn socket_type(&self) -> i32 { SOCK_STREAM } fn protocol_type(&self) -> i32 { 0 } unsafe fn uninitialized(&self) -> Self::Endpoint { mem::uninitialized() } } impl Endpoint<LocalStream> for LocalEndpoint<LocalStream> { fn protocol(&self) -> LocalStream { LocalStream } fn as_ptr(&self) -> *const sockaddr { &self.sun as *const _ as *const _ } fn as_mut_ptr(&mut self) -> *mut sockaddr { &mut self.sun as *mut _ as *mut _ } fn capacity(&self) -> socklen_t { self.sun.capacity() as socklen_t } fn
(&self) -> socklen_t { self.sun.size() as socklen_t } unsafe fn resize(&mut self, size: socklen_t) { debug_assert!(size <= self.capacity()); self.sun.resize(size as u8) } } impl fmt::Debug for LocalEndpoint<LocalStream> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}:{:?})", self.protocol(), self.as_pathname()) } } /// The stream-oriented UNIX domain endpoint type pub type LocalStreamEndpoint = LocalEndpoint<LocalStream>; /// The stream-oriented UNIX domain socket type. pub type LocalStreamSocket = StreamSocket<LocalStream>; /// The stream-oriented UNIX domain listener type. pub type LocalStreamListener = SocketListener<LocalStream>; #[test] fn test_getsockname_local() { use core::IoContext; use local::*; use std::fs; let ctx = &IoContext::new().unwrap(); let ep = LocalStreamEndpoint::new(".asio_foo.sock").unwrap(); println!("{:?}", ep.as_pathname().unwrap()); let _ = fs::remove_file(ep.as_pathname().unwrap()); let soc = LocalStreamSocket::new(ctx, ep.protocol()).unwrap(); soc.bind(&ep).unwrap(); assert_eq!(soc.local_endpoint().unwrap(), ep); assert_eq!(soc.local_endpoint().unwrap(), ep); let _ = fs::remove_file(ep.as_pathname().unwrap()); } #[test] fn test_format() { use core::IoContext; let _ctx = &IoContext::new().unwrap(); println!("{:?}", LocalStream); println!("{:?}", LocalStreamEndpoint::new("foo/bar").unwrap()); }
size
identifier_name
stream.rs
use ffi::{sockaddr, socklen_t, AF_UNIX, SOCK_STREAM}; use core::{Endpoint, Protocol}; use socket_listener::SocketListener; use stream_socket::StreamSocket; use local::LocalEndpoint; use std::fmt; use std::mem; /// The stream-oriented UNIX domain protocol. /// /// # Example /// Create a server and client sockets. /// /// ```rust,no_run /// use asyncio::{IoContext, Endpoint}; /// use asyncio::local::{LocalStream, LocalStreamEndpoint, LocalStreamSocket, LocalStreamListener}; /// /// let ctx = &IoContext::new().unwrap(); /// let ep = LocalStreamEndpoint::new("example.sock").unwrap(); /// /// let sv = LocalStreamListener::new(ctx, LocalStream).unwrap(); /// sv.bind(&ep).unwrap(); /// sv.listen().unwrap(); /// /// let cl = LocalStreamSocket::new(ctx, ep.protocol()).unwrap(); /// cl.connect(&ep).unwrap(); /// ``` #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct LocalStream; impl Protocol for LocalStream { type Endpoint = LocalEndpoint<Self>; type Socket = LocalStreamSocket; fn family_type(&self) -> i32 { AF_UNIX } fn socket_type(&self) -> i32 { SOCK_STREAM } fn protocol_type(&self) -> i32 { 0 } unsafe fn uninitialized(&self) -> Self::Endpoint { mem::uninitialized() } } impl Endpoint<LocalStream> for LocalEndpoint<LocalStream> { fn protocol(&self) -> LocalStream
fn as_ptr(&self) -> *const sockaddr { &self.sun as *const _ as *const _ } fn as_mut_ptr(&mut self) -> *mut sockaddr { &mut self.sun as *mut _ as *mut _ } fn capacity(&self) -> socklen_t { self.sun.capacity() as socklen_t } fn size(&self) -> socklen_t { self.sun.size() as socklen_t } unsafe fn resize(&mut self, size: socklen_t) { debug_assert!(size <= self.capacity()); self.sun.resize(size as u8) } } impl fmt::Debug for LocalEndpoint<LocalStream> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}:{:?})", self.protocol(), self.as_pathname()) } } /// The stream-oriented UNIX domain endpoint type pub type LocalStreamEndpoint = LocalEndpoint<LocalStream>; /// The stream-oriented UNIX domain socket type. pub type LocalStreamSocket = StreamSocket<LocalStream>; /// The stream-oriented UNIX domain listener type. pub type LocalStreamListener = SocketListener<LocalStream>; #[test] fn test_getsockname_local() { use core::IoContext; use local::*; use std::fs; let ctx = &IoContext::new().unwrap(); let ep = LocalStreamEndpoint::new(".asio_foo.sock").unwrap(); println!("{:?}", ep.as_pathname().unwrap()); let _ = fs::remove_file(ep.as_pathname().unwrap()); let soc = LocalStreamSocket::new(ctx, ep.protocol()).unwrap(); soc.bind(&ep).unwrap(); assert_eq!(soc.local_endpoint().unwrap(), ep); assert_eq!(soc.local_endpoint().unwrap(), ep); let _ = fs::remove_file(ep.as_pathname().unwrap()); } #[test] fn test_format() { use core::IoContext; let _ctx = &IoContext::new().unwrap(); println!("{:?}", LocalStream); println!("{:?}", LocalStreamEndpoint::new("foo/bar").unwrap()); }
{ LocalStream }
identifier_body
bad-mid-path-type-params.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. // ignore-tidy-linelength struct S<T> { contents: T, } impl<T> S<T> { fn new<U>(x: T, _: U) -> S<T> { S { contents: x, } } } trait Trait<T> { fn new<U>(x: T, y: U) -> Self; } struct S2 { contents: isize, } impl Trait<isize> for S2 { fn new<U>(x: isize, _: U) -> S2 { S2 { contents: x, } } } fn
<'a>() { let _ = S::new::<isize,f64>(1, 1.0); //~^ ERROR too many type parameters provided let _ = S::<'a,isize>::new::<f64>(1, 1.0); //~^ ERROR wrong number of lifetime parameters let _: S2 = Trait::new::<isize,f64>(1, 1.0); //~^ ERROR too many type parameters provided let _: S2 = Trait::<'a,isize>::new::<f64>(1, 1.0); //~^ ERROR too many lifetime parameters provided } fn main() {}
foo
identifier_name
bad-mid-path-type-params.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. // ignore-tidy-linelength struct S<T> { contents: T, } impl<T> S<T> { fn new<U>(x: T, _: U) -> S<T> { S { contents: x, } } } trait Trait<T> { fn new<U>(x: T, y: U) -> Self; } struct S2 { contents: isize, } impl Trait<isize> for S2 { fn new<U>(x: isize, _: U) -> S2
} fn foo<'a>() { let _ = S::new::<isize,f64>(1, 1.0); //~^ ERROR too many type parameters provided let _ = S::<'a,isize>::new::<f64>(1, 1.0); //~^ ERROR wrong number of lifetime parameters let _: S2 = Trait::new::<isize,f64>(1, 1.0); //~^ ERROR too many type parameters provided let _: S2 = Trait::<'a,isize>::new::<f64>(1, 1.0); //~^ ERROR too many lifetime parameters provided } fn main() {}
{ S2 { contents: x, } }
identifier_body
bad-mid-path-type-params.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. // ignore-tidy-linelength struct S<T> { contents: T, } impl<T> S<T> { fn new<U>(x: T, _: U) -> S<T> { S { contents: x, } } } trait Trait<T> { fn new<U>(x: T, y: U) -> Self; } struct S2 { contents: isize, } impl Trait<isize> for S2 { fn new<U>(x: isize, _: U) -> S2 { S2 { contents: x, } } } fn foo<'a>() { let _ = S::new::<isize,f64>(1, 1.0); //~^ ERROR too many type parameters provided let _ = S::<'a,isize>::new::<f64>(1, 1.0); //~^ ERROR wrong number of lifetime parameters let _: S2 = Trait::new::<isize,f64>(1, 1.0); //~^ ERROR too many type parameters provided let _: S2 = Trait::<'a,isize>::new::<f64>(1, 1.0); //~^ ERROR too many lifetime parameters provided
} fn main() {}
random_line_split
mod.rs
mod err; use libc; use ::descriptor::Descriptor; pub use self::err::{MasterError, Result}; use std::io; use std::os::unix::io::{AsRawFd, RawFd}; #[derive(Debug, Copy, Clone)] pub struct Master { pty: RawFd, } impl Master { pub fn new(path: *const ::libc::c_char) -> Result<Self> { match Self::open(path, libc::O_RDWR, None) { Err(cause) => Err(MasterError::BadDescriptor(cause)), Ok(fd) => Ok(Master { pty: fd }), } } /// Change UID and GID of slave pty associated with master pty whose /// fd is provided, to the real UID and real GID of the calling thread. pub fn
(&self) -> Result<libc::c_int> { unsafe { match libc::grantpt(self.as_raw_fd()) { -1 => Err(MasterError::GrantptError), c => Ok(c), } } } /// Unlock the slave pty associated with the master to which fd refers. pub fn unlockpt(&self) -> Result<libc::c_int> { unsafe { match libc::unlockpt(self.as_raw_fd()) { -1 => Err(MasterError::UnlockptError), c => Ok(c), } } } /// Returns a pointer to a static buffer, which will be overwritten on /// subsequent calls. pub fn ptsname(&self) -> Result<*const libc::c_char> { unsafe { match libc::ptsname(self.as_raw_fd()) { c if c.is_null() => Err(MasterError::PtsnameError), c => Ok(c), } } } } impl Descriptor for Master {} impl AsRawFd for Master { /// The accessor function `as_raw_fd` returns the fd. fn as_raw_fd(&self) -> RawFd { self.pty } } impl io::Read for Master { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { unsafe { match libc::read(self.as_raw_fd(), buf.as_mut_ptr() as *mut libc::c_void, buf.len()) { -1 => Ok(0), len => Ok(len as usize), } } } } impl io::Write for Master { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { unsafe { match libc::write(self.as_raw_fd(), buf.as_ptr() as *const libc::c_void, buf.len()) { -1 => Err(io::Error::last_os_error()), ret => Ok(ret as usize), } } } fn flush(&mut self) -> io::Result<()> { Ok(()) } }
grantpt
identifier_name
mod.rs
mod err;
pub use self::err::{MasterError, Result}; use std::io; use std::os::unix::io::{AsRawFd, RawFd}; #[derive(Debug, Copy, Clone)] pub struct Master { pty: RawFd, } impl Master { pub fn new(path: *const ::libc::c_char) -> Result<Self> { match Self::open(path, libc::O_RDWR, None) { Err(cause) => Err(MasterError::BadDescriptor(cause)), Ok(fd) => Ok(Master { pty: fd }), } } /// Change UID and GID of slave pty associated with master pty whose /// fd is provided, to the real UID and real GID of the calling thread. pub fn grantpt(&self) -> Result<libc::c_int> { unsafe { match libc::grantpt(self.as_raw_fd()) { -1 => Err(MasterError::GrantptError), c => Ok(c), } } } /// Unlock the slave pty associated with the master to which fd refers. pub fn unlockpt(&self) -> Result<libc::c_int> { unsafe { match libc::unlockpt(self.as_raw_fd()) { -1 => Err(MasterError::UnlockptError), c => Ok(c), } } } /// Returns a pointer to a static buffer, which will be overwritten on /// subsequent calls. pub fn ptsname(&self) -> Result<*const libc::c_char> { unsafe { match libc::ptsname(self.as_raw_fd()) { c if c.is_null() => Err(MasterError::PtsnameError), c => Ok(c), } } } } impl Descriptor for Master {} impl AsRawFd for Master { /// The accessor function `as_raw_fd` returns the fd. fn as_raw_fd(&self) -> RawFd { self.pty } } impl io::Read for Master { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { unsafe { match libc::read(self.as_raw_fd(), buf.as_mut_ptr() as *mut libc::c_void, buf.len()) { -1 => Ok(0), len => Ok(len as usize), } } } } impl io::Write for Master { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { unsafe { match libc::write(self.as_raw_fd(), buf.as_ptr() as *const libc::c_void, buf.len()) { -1 => Err(io::Error::last_os_error()), ret => Ok(ret as usize), } } } fn flush(&mut self) -> io::Result<()> { Ok(()) } }
use libc; use ::descriptor::Descriptor;
random_line_split
bignum.rs
Ops for $ty { fn full_add(self, other: $ty, carry: bool) -> (bool, $ty) { // This cannot overflow; the output is between `0` and `2 * 2^nbits - 1`. // FIXME: will LLVM optimize this into ADC or similar? let (v, carry1) = intrinsics::add_with_overflow(self, other); let (v, carry2) = intrinsics::add_with_overflow(v, if carry {1} else {0}); (carry1 || carry2, v) } fn full_mul(self, other: $ty, carry: $ty) -> ($ty, $ty) { // This cannot overflow; // the output is between `0` and `2^nbits * (2^nbits - 1)`. // FIXME: will LLVM optimize this into ADC or similar? let v = (self as $bigty) * (other as $bigty) + (carry as $bigty); ((v >> <$ty>::BITS) as $ty, v as $ty) } fn full_mul_add(self, other: $ty, other2: $ty, carry: $ty) -> ($ty, $ty) { // This cannot overflow; // the output is between `0` and `2^nbits * (2^nbits - 1)`. let v = (self as $bigty) * (other as $bigty) + (other2 as $bigty) + (carry as $bigty); ((v >> <$ty>::BITS) as $ty, v as $ty) } fn full_div_rem(self, other: $ty, borrow: $ty) -> ($ty, $ty) { debug_assert!(borrow < other); // This cannot overflow; the output is between `0` and `other * (2^nbits - 1)`. let lhs = ((borrow as $bigty) << <$ty>::BITS) | (self as $bigty); let rhs = other as $bigty; ((lhs / rhs) as $ty, (lhs % rhs) as $ty) } } )* ) } impl_full_ops! { u8: add(intrinsics::u8_add_with_overflow), mul/div(u16); u16: add(intrinsics::u16_add_with_overflow), mul/div(u32); u32: add(intrinsics::u32_add_with_overflow), mul/div(u64); // See RFC #521 for enabling this. // u64: add(intrinsics::u64_add_with_overflow), mul/div(u128); } /// Table of powers of 5 representable in digits. Specifically, the largest {u8, u16, u32} value /// that's a power of five, plus the corresponding exponent. Used in `mul_pow5`. const SMALL_POW5: [(u64, usize); 3] = [(125, 3), (15625, 6), (1_220_703_125, 13)]; macro_rules! define_bignum { ($name:ident: type=$ty:ty, n=$n:expr) => { /// Stack-allocated arbitrary-precision (up to certain limit) integer. /// /// This is backed by a fixed-size array of given type ("digit"). /// While the array is not very large (normally some hundred bytes), /// copying it recklessly may result in the performance hit. /// Thus this is intentionally not `Copy`. /// /// All operations available to bignums panic in the case of overflows. /// The caller is responsible to use large enough bignum types. pub struct $name { /// One plus the offset to the maximum "digit" in use. /// This does not decrease, so be aware of the computation order. /// `base[size..]` should be zero. size: usize, /// Digits. `[a, b, c,...]` represents `a + b*2^W + c*2^(2W) +...` /// where `W` is the number of bits in the digit type. base: [$ty; $n], } impl $name { /// Makes a bignum from one digit. pub fn from_small(v: $ty) -> $name { let mut base = [0; $n]; base[0] = v; $name { size: 1, base } } /// Makes a bignum from `u64` value. pub fn from_u64(mut v: u64) -> $name { let mut base = [0; $n]; let mut sz = 0; while v > 0 { base[sz] = v as $ty; v >>= <$ty>::BITS; sz += 1; } $name { size: sz, base } } /// Returns the internal digits as a slice `[a, b, c,...]` such that the numeric /// value is `a + b * 2^W + c * 2^(2W) +...` where `W` is the number of bits in /// the digit type. pub fn digits(&self) -> &[$ty] { &self.base[..self.size] } /// Returns the `i`-th bit where bit 0 is the least significant one. /// In other words, the bit with weight `2^i`. pub fn get_bit(&self, i: usize) -> u8 { let digitbits = <$ty>::BITS as usize; let d = i / digitbits; let b = i % digitbits; ((self.base[d] >> b) & 1) as u8 } /// Returns `true` if the bignum is zero. pub fn is_zero(&self) -> bool { self.digits().iter().all(|&v| v == 0) } /// Returns the number of bits necessary to represent this value. Note that zero /// is considered to need 0 bits. pub fn bit_length(&self) -> usize { // Skip over the most significant digits which are zero. let digits = self.digits(); let zeros = digits.iter().rev().take_while(|&&x| x == 0).count(); let end = digits.len() - zeros; let nonzero = &digits[..end]; if nonzero.is_empty() { // There are no non-zero digits, i.e., the number is zero. return 0; } // This could be optimized with leading_zeros() and bit shifts, but that's // probably not worth the hassle. let digitbits = <$ty>::BITS as usize; let mut i = nonzero.len() * digitbits - 1; while self.get_bit(i) == 0 { i -= 1; } i + 1 } /// Adds `other` to itself and returns its own mutable reference. pub fn add<'a>(&'a mut self, other: &$name) -> &'a mut $name { use crate::cmp; use crate::iter; use crate::num::bignum::FullOps; let mut sz = cmp::max(self.size, other.size); let mut carry = false; for (a, b) in iter::zip(&mut self.base[..sz], &other.base[..sz]) { let (c, v) = (*a).full_add(*b, carry); *a = v; carry = c; } if carry { self.base[sz] = 1; sz += 1; } self.size = sz; self } pub fn add_small(&mut self, other: $ty) -> &mut $name { use crate::num::bignum::FullOps; let (mut carry, v) = self.base[0].full_add(other, false); self.base[0] = v; let mut i = 1; while carry { let (c, v) = self.base[i].full_add(0, carry); self.base[i] = v; carry = c; i += 1; } if i > self.size { self.size = i; } self } /// Subtracts `other` from itself and returns its own mutable reference. pub fn sub<'a>(&'a mut self, other: &$name) -> &'a mut $name { use crate::cmp; use crate::iter; use crate::num::bignum::FullOps; let sz = cmp::max(self.size, other.size); let mut noborrow = true; for (a, b) in iter::zip(&mut self.base[..sz], &other.base[..sz]) { let (c, v) = (*a).full_add(!*b, noborrow); *a = v; noborrow = c; }
assert!(noborrow); self.size = sz; self } /// Multiplies itself by a digit-sized `other` and returns its own /// mutable reference. pub fn mul_small(&mut self, other: $ty) -> &mut $name { use crate::num::bignum::FullOps; let mut sz = self.size; let mut carry = 0; for a in &mut self.base[..sz] { let (c, v) = (*a).full_mul(other, carry); *a = v; carry = c; } if carry > 0 { self.base[sz] = carry; sz += 1; } self.size = sz; self } /// Multiplies itself by `2^bits` and returns its own mutable reference. pub fn mul_pow2(&mut self, bits: usize) -> &mut $name { let digitbits = <$ty>::BITS as usize; let digits = bits / digitbits; let bits = bits % digitbits; assert!(digits < $n); debug_assert!(self.base[$n - digits..].iter().all(|&v| v == 0)); debug_assert!(bits == 0 || (self.base[$n - digits - 1] >> (digitbits - bits)) == 0); // shift by `digits * digitbits` bits for i in (0..self.size).rev() { self.base[i + digits] = self.base[i]; } for i in 0..digits { self.base[i] = 0; } // shift by `bits` bits let mut sz = self.size + digits; if bits > 0 { let last = sz; let overflow = self.base[last - 1] >> (digitbits - bits); if overflow > 0 { self.base[last] = overflow; sz += 1; } for i in (digits + 1..last).rev() { self.base[i] = (self.base[i] << bits) | (self.base[i - 1] >> (digitbits - bits)); } self.base[digits] <<= bits; // self.base[..digits] is zero, no need to shift } self.size = sz; self } /// Multiplies itself by `5^e` and returns its own mutable reference. pub fn mul_pow5(&mut self, mut e: usize) -> &mut $name { use crate::mem; use crate::num::bignum::SMALL_POW5; // There are exactly n trailing zeros on 2^n, and the only relevant digit sizes // are consecutive powers of two, so this is well suited index for the table. let table_index = mem::size_of::<$ty>().trailing_zeros() as usize; let (small_power, small_e) = SMALL_POW5[table_index]; let small_power = small_power as $ty; // Multiply with the largest single-digit power as long as possible... while e >= small_e { self.mul_small(small_power); e -= small_e; } //... then finish off the remainder. let mut rest_power = 1; for _ in 0..e { rest_power *= 5; } self.mul_small(rest_power); self } /// Multiplies itself by a number described by `other[0] + other[1] * 2^W + /// other[2] * 2^(2W) +...` (where `W` is the number of bits in the digit type) /// and returns its own mutable reference. pub fn mul_digits<'a>(&'a mut self, other: &[$ty]) -> &'a mut $name { // the internal routine. works best when aa.len() <= bb.len(). fn mul_inner(ret: &mut [$ty; $n], aa: &[$ty], bb: &[$ty]) -> usize { use crate::num::bignum::FullOps; let mut retsz = 0; for (i, &a) in aa.iter().enumerate() { if a == 0 { continue; } let mut sz = bb.len(); let mut carry = 0; for (j, &b) in bb.iter().enumerate() { let (c, v) = a.full_mul_add(b, ret[i + j], carry); ret[i + j] = v; carry = c; } if carry > 0 { ret[i + sz] = carry; sz += 1; } if retsz < i + sz { retsz = i + sz; } } retsz } let mut ret = [0; $n]; let retsz = if self.size < other.len() { mul_inner(&mut ret, &self.digits(), other) } else { mul_inner(&mut ret, other, &self.digits()) }; self.base = ret; self.size = retsz; self } /// Divides itself by a digit-sized `other` and returns its own /// mutable reference *and* the remainder. pub fn div_rem_small(&mut self, other: $ty) -> (&mut $name, $ty) { use crate::num::bignum::FullOps; assert!(other > 0); let sz = self.size; let mut borrow = 0; for a in self.base[..sz].iter_mut().rev() { let (q, r) = (*a).full_div_rem(other, borrow); *a = q; borrow = r; } (self, borrow) } /// Divide self by another bignum, overwriting `q` with the quotient and `r` with the /// remainder. pub fn div_rem(&self, d: &$name, q: &mut $name, r: &mut $name) { // Stupid slow base-2 long division taken from // https://en.wikipedia.org/wiki/Division_algorithm // FIXME use a greater base ($ty) for the long division. assert!(!d.is_zero()); let digitbits = <$ty>::BITS as usize; for digit in &mut q.base[..] { *digit = 0; } for digit in &mut r.base[..] { *digit = 0; } r.size = d.size;
random_line_split
class-implement-traits.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. trait noisy { fn speak(&mut self); } #[deriving(Clone)] struct cat { meows : uint, how_hungry : int, name : String, } impl cat { fn meow(&mut self) { println!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } impl cat { pub fn eat(&mut self) -> bool { if self.how_hungry > 0
else { println!("Not hungry!"); return false; } } } impl noisy for cat { fn speak(&mut self) { self.meow(); } } fn cat(in_x : uint, in_y : int, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name.clone() } } fn make_speak<C:noisy>(mut c: C) { c.speak(); } pub fn main() { let mut nyan = cat(0u, 2, "nyan".to_string()); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { make_speak(nyan.clone()); } }
{ println!("OM NOM NOM"); self.how_hungry -= 2; return true; }
conditional_block
class-implement-traits.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. trait noisy { fn speak(&mut self); } #[deriving(Clone)] struct cat { meows : uint, how_hungry : int, name : String, } impl cat { fn meow(&mut self) { println!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } impl cat { pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl noisy for cat { fn speak(&mut self) { self.meow(); } } fn cat(in_x : uint, in_y : int, in_name: String) -> cat
fn make_speak<C:noisy>(mut c: C) { c.speak(); } pub fn main() { let mut nyan = cat(0u, 2, "nyan".to_string()); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { make_speak(nyan.clone()); } }
{ cat { meows: in_x, how_hungry: in_y, name: in_name.clone() } }
identifier_body
class-implement-traits.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. trait noisy { fn speak(&mut self); } #[deriving(Clone)] struct
{ meows : uint, how_hungry : int, name : String, } impl cat { fn meow(&mut self) { println!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } impl cat { pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl noisy for cat { fn speak(&mut self) { self.meow(); } } fn cat(in_x : uint, in_y : int, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name.clone() } } fn make_speak<C:noisy>(mut c: C) { c.speak(); } pub fn main() { let mut nyan = cat(0u, 2, "nyan".to_string()); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { make_speak(nyan.clone()); } }
cat
identifier_name
class-implement-traits.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. trait noisy { fn speak(&mut self);
how_hungry : int, name : String, } impl cat { fn meow(&mut self) { println!("Meow"); self.meows += 1u; if self.meows % 5u == 0u { self.how_hungry += 1; } } } impl cat { pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl noisy for cat { fn speak(&mut self) { self.meow(); } } fn cat(in_x : uint, in_y : int, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name.clone() } } fn make_speak<C:noisy>(mut c: C) { c.speak(); } pub fn main() { let mut nyan = cat(0u, 2, "nyan".to_string()); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { make_speak(nyan.clone()); } }
} #[deriving(Clone)] struct cat { meows : uint,
random_line_split
tetromino.rs
use self::Rotation::*; use self::Color::*; pub static SHAPES: [Tetromino,..7] = [ Tetromino { color: Cyan, points: [[(0,2),(1,2),(2,2),(3,2)],[(2,0),(2,1),(2,2),(2,3)],[(0,2),(1,2),(2,2),(3,2)],[(2,0),(2,1),(2,2),(2,3)]] }, Tetromino { color: Blue, points: [[(0,1),(1,1),(2,1),(2,2)],[(1,0),(1,1),(0,2),(1,2)],[(0,0),(0,1),(1,1),(2,1)],[(1,0),(2,0),(1,1),(1,2)]] }, Tetromino { color: Orange, points: [[(0,1),(1,1),(2,1),(0,2)],[(0,0),(1,0),(1,1),(1,2)],[(2,0),(0,1),(1,1),(2,1)],[(1,0),(1,1),(1,2),(2,2)]] }, Tetromino { color: Yellow, points: [[(1,1),(2,1),(1,2),(2,2)],[(1,1),(2,1),(1,2),(2,2)],[(1,1),(2,1),(1,2),(2,2)],[(1,1),(2,1),(1,2),(2,2)]] }, Tetromino { color: Lime, points: [[(1,1),(2,1),(0,2),(1,2)],[(1,0),(1,1),(2,1),(2,2)],[(1,1),(2,1),(0,2),(1,2)],[(1,0),(1,1),(2,1),(2,2)]] }, Tetromino { color: Purple, points: [[(0,1),(1,1),(2,1),(1,2)],[(1,0),(0,1),(1,1),(1,2)],[(1,0),(0,1),(1,1),(2,1)],[(1,0),(1,1),(2,1),(1,2)]]
}, Tetromino { color: Red, points: [[(0,1),(1,1),(1,2),(2,2)],[(2,0),(1,1),(2,1),(1,2)],[(0,1),(1,1),(1,2),(2,2)],[(2,0),(1,1),(2,1),(1,2)]] } ]; pub struct Tetromino { color: Color, points: [[(uint,uint),..4],..4] } impl Tetromino { pub fn points(&'static self, rotation: Rotation) -> &'static [(uint,uint),..4] { &self.points[rotation as uint] } pub fn get_color(&self) -> Color { self.color } } #[deriving(Clone)] pub enum Rotation { R0, R1, R2, R3 } impl Rotation { pub fn increase(&self) -> Rotation { match *self { R0 => R1, R1 => R2, R2 => R3, R3 => R0 } } pub fn decrease(&self) -> Rotation { match *self { R0 => R3, R1 => R0, R2 => R1, R3 => R2 } } } pub enum Color { Cyan, Blue, Orange, Yellow, Lime, Purple, Red } impl Color { pub fn as_rgba(&self) -> [f32,..4] { match *self { Cyan => [0.0, 1.0, 1.0, 1.0], Blue => [0.0, 0.5, 1.0, 1.0], Orange => [1.0, 0.6, 0.0, 1.0], Yellow => [1.0, 1.0, 0.0, 1.0], Lime => [0.5, 1.0, 0.0, 1.0], Purple => [0.8, 0.0, 1.0, 1.0], Red => [1.0, 0.0, 0.0, 1.0] } } }
random_line_split
tetromino.rs
use self::Rotation::*; use self::Color::*; pub static SHAPES: [Tetromino,..7] = [ Tetromino { color: Cyan, points: [[(0,2),(1,2),(2,2),(3,2)],[(2,0),(2,1),(2,2),(2,3)],[(0,2),(1,2),(2,2),(3,2)],[(2,0),(2,1),(2,2),(2,3)]] }, Tetromino { color: Blue, points: [[(0,1),(1,1),(2,1),(2,2)],[(1,0),(1,1),(0,2),(1,2)],[(0,0),(0,1),(1,1),(2,1)],[(1,0),(2,0),(1,1),(1,2)]] }, Tetromino { color: Orange, points: [[(0,1),(1,1),(2,1),(0,2)],[(0,0),(1,0),(1,1),(1,2)],[(2,0),(0,1),(1,1),(2,1)],[(1,0),(1,1),(1,2),(2,2)]] }, Tetromino { color: Yellow, points: [[(1,1),(2,1),(1,2),(2,2)],[(1,1),(2,1),(1,2),(2,2)],[(1,1),(2,1),(1,2),(2,2)],[(1,1),(2,1),(1,2),(2,2)]] }, Tetromino { color: Lime, points: [[(1,1),(2,1),(0,2),(1,2)],[(1,0),(1,1),(2,1),(2,2)],[(1,1),(2,1),(0,2),(1,2)],[(1,0),(1,1),(2,1),(2,2)]] }, Tetromino { color: Purple, points: [[(0,1),(1,1),(2,1),(1,2)],[(1,0),(0,1),(1,1),(1,2)],[(1,0),(0,1),(1,1),(2,1)],[(1,0),(1,1),(2,1),(1,2)]] }, Tetromino { color: Red, points: [[(0,1),(1,1),(1,2),(2,2)],[(2,0),(1,1),(2,1),(1,2)],[(0,1),(1,1),(1,2),(2,2)],[(2,0),(1,1),(2,1),(1,2)]] } ]; pub struct Tetromino { color: Color, points: [[(uint,uint),..4],..4] } impl Tetromino { pub fn points(&'static self, rotation: Rotation) -> &'static [(uint,uint),..4] { &self.points[rotation as uint] } pub fn get_color(&self) -> Color { self.color } } #[deriving(Clone)] pub enum Rotation { R0, R1, R2, R3 } impl Rotation { pub fn
(&self) -> Rotation { match *self { R0 => R1, R1 => R2, R2 => R3, R3 => R0 } } pub fn decrease(&self) -> Rotation { match *self { R0 => R3, R1 => R0, R2 => R1, R3 => R2 } } } pub enum Color { Cyan, Blue, Orange, Yellow, Lime, Purple, Red } impl Color { pub fn as_rgba(&self) -> [f32,..4] { match *self { Cyan => [0.0, 1.0, 1.0, 1.0], Blue => [0.0, 0.5, 1.0, 1.0], Orange => [1.0, 0.6, 0.0, 1.0], Yellow => [1.0, 1.0, 0.0, 1.0], Lime => [0.5, 1.0, 0.0, 1.0], Purple => [0.8, 0.0, 1.0, 1.0], Red => [1.0, 0.0, 0.0, 1.0] } } }
increase
identifier_name
os.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Interfaces to the operating system provided random number //! generators. use rand::Rng; use ops::Drop; #[cfg(unix)] use rand::reader::ReaderRng; #[cfg(unix)] use io::File; #[cfg(windows)] use cast; #[cfg(windows)] use libc::{c_long, DWORD, BYTE}; #[cfg(windows)] type HCRYPTPROV = c_long; // the extern functions imported from the runtime on Windows are // implemented so that they either succeed or abort(), so we can just // assume they work when we call them. /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(unix)] pub struct OSRng { priv inner: ReaderRng<File> } /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(windows)] pub struct OSRng { priv hcryptprov: HCRYPTPROV } impl OSRng { /// Create a new `OSRng`. #[cfg(unix)] pub fn new() -> OSRng { use path::Path; let reader = File::open(&Path::new("/dev/urandom")); let reader = reader.expect("Error opening /dev/urandom"); let reader_rng = ReaderRng::new(reader); OSRng { inner: reader_rng } } /// Create a new `OSRng`. #[cfg(windows)] pub fn new() -> OSRng { extern { fn rust_win32_rand_acquire(phProv: *mut HCRYPTPROV); } let mut hcp = 0; unsafe {rust_win32_rand_acquire(&mut hcp)}; OSRng { hcryptprov: hcp } } } #[cfg(unix)] impl Rng for OSRng { fn
(&mut self) -> u32 { self.inner.next_u32() } fn next_u64(&mut self) -> u64 { self.inner.next_u64() } fn fill_bytes(&mut self, v: &mut [u8]) { self.inner.fill_bytes(v) } } #[cfg(windows)] impl Rng for OSRng { fn next_u32(&mut self) -> u32 { let mut v = [0u8,.. 4]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn next_u64(&mut self) -> u64 { let mut v = [0u8,.. 8]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn fill_bytes(&mut self, v: &mut [u8]) { use container::Container; use vec::MutableVector; extern { fn rust_win32_rand_gen(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *mut BYTE); } unsafe {rust_win32_rand_gen(self.hcryptprov, v.len() as DWORD, v.as_mut_ptr())} } } impl Drop for OSRng { #[cfg(unix)] fn drop(&mut self) { // ensure that OSRng is not implicitly copyable on all // platforms, for consistency. } #[cfg(windows)] fn drop(&mut self) { extern { fn rust_win32_rand_release(hProv: HCRYPTPROV); } unsafe {rust_win32_rand_release(self.hcryptprov)} } } #[cfg(test)] mod test { use prelude::*; use super::*; use rand::Rng; use task; #[test] fn test_os_rng() { let mut r = OSRng::new(); r.next_u32(); r.next_u64(); let mut v = [0u8,.. 1000]; r.fill_bytes(v); } #[test] fn test_os_rng_tasks() { let mut chans = ~[]; for _ in range(0, 20) { let (p, c) = Chan::new(); chans.push(c); do task::spawn { // wait until all the tasks are ready to go. p.recv(); // deschedule to attempt to interleave things as much // as possible (XXX: is this a good test?) let mut r = OSRng::new(); task::deschedule(); let mut v = [0u8,.. 1000]; for _ in range(0, 100) { r.next_u32(); task::deschedule(); r.next_u64(); task::deschedule(); r.fill_bytes(v); task::deschedule(); } } } // start all the tasks for c in chans.iter() { c.send(()) } } }
next_u32
identifier_name
os.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Interfaces to the operating system provided random number //! generators. use rand::Rng; use ops::Drop; #[cfg(unix)] use rand::reader::ReaderRng; #[cfg(unix)] use io::File; #[cfg(windows)] use cast; #[cfg(windows)] use libc::{c_long, DWORD, BYTE}; #[cfg(windows)] type HCRYPTPROV = c_long;
// assume they work when we call them. /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(unix)] pub struct OSRng { priv inner: ReaderRng<File> } /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(windows)] pub struct OSRng { priv hcryptprov: HCRYPTPROV } impl OSRng { /// Create a new `OSRng`. #[cfg(unix)] pub fn new() -> OSRng { use path::Path; let reader = File::open(&Path::new("/dev/urandom")); let reader = reader.expect("Error opening /dev/urandom"); let reader_rng = ReaderRng::new(reader); OSRng { inner: reader_rng } } /// Create a new `OSRng`. #[cfg(windows)] pub fn new() -> OSRng { extern { fn rust_win32_rand_acquire(phProv: *mut HCRYPTPROV); } let mut hcp = 0; unsafe {rust_win32_rand_acquire(&mut hcp)}; OSRng { hcryptprov: hcp } } } #[cfg(unix)] impl Rng for OSRng { fn next_u32(&mut self) -> u32 { self.inner.next_u32() } fn next_u64(&mut self) -> u64 { self.inner.next_u64() } fn fill_bytes(&mut self, v: &mut [u8]) { self.inner.fill_bytes(v) } } #[cfg(windows)] impl Rng for OSRng { fn next_u32(&mut self) -> u32 { let mut v = [0u8,.. 4]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn next_u64(&mut self) -> u64 { let mut v = [0u8,.. 8]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn fill_bytes(&mut self, v: &mut [u8]) { use container::Container; use vec::MutableVector; extern { fn rust_win32_rand_gen(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *mut BYTE); } unsafe {rust_win32_rand_gen(self.hcryptprov, v.len() as DWORD, v.as_mut_ptr())} } } impl Drop for OSRng { #[cfg(unix)] fn drop(&mut self) { // ensure that OSRng is not implicitly copyable on all // platforms, for consistency. } #[cfg(windows)] fn drop(&mut self) { extern { fn rust_win32_rand_release(hProv: HCRYPTPROV); } unsafe {rust_win32_rand_release(self.hcryptprov)} } } #[cfg(test)] mod test { use prelude::*; use super::*; use rand::Rng; use task; #[test] fn test_os_rng() { let mut r = OSRng::new(); r.next_u32(); r.next_u64(); let mut v = [0u8,.. 1000]; r.fill_bytes(v); } #[test] fn test_os_rng_tasks() { let mut chans = ~[]; for _ in range(0, 20) { let (p, c) = Chan::new(); chans.push(c); do task::spawn { // wait until all the tasks are ready to go. p.recv(); // deschedule to attempt to interleave things as much // as possible (XXX: is this a good test?) let mut r = OSRng::new(); task::deschedule(); let mut v = [0u8,.. 1000]; for _ in range(0, 100) { r.next_u32(); task::deschedule(); r.next_u64(); task::deschedule(); r.fill_bytes(v); task::deschedule(); } } } // start all the tasks for c in chans.iter() { c.send(()) } } }
// the extern functions imported from the runtime on Windows are // implemented so that they either succeed or abort(), so we can just
random_line_split
os.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Interfaces to the operating system provided random number //! generators. use rand::Rng; use ops::Drop; #[cfg(unix)] use rand::reader::ReaderRng; #[cfg(unix)] use io::File; #[cfg(windows)] use cast; #[cfg(windows)] use libc::{c_long, DWORD, BYTE}; #[cfg(windows)] type HCRYPTPROV = c_long; // the extern functions imported from the runtime on Windows are // implemented so that they either succeed or abort(), so we can just // assume they work when we call them. /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(unix)] pub struct OSRng { priv inner: ReaderRng<File> } /// A random number generator that retrieves randomness straight from /// the operating system. Platform sources: /// /// - Unix-like systems (Linux, Android, Mac OSX): read directly from /// `/dev/urandom`. /// - Windows: calls `CryptGenRandom`, using the default cryptographic /// service provider with the `PROV_RSA_FULL` type. /// /// This does not block. #[cfg(windows)] pub struct OSRng { priv hcryptprov: HCRYPTPROV } impl OSRng { /// Create a new `OSRng`. #[cfg(unix)] pub fn new() -> OSRng { use path::Path; let reader = File::open(&Path::new("/dev/urandom")); let reader = reader.expect("Error opening /dev/urandom"); let reader_rng = ReaderRng::new(reader); OSRng { inner: reader_rng } } /// Create a new `OSRng`. #[cfg(windows)] pub fn new() -> OSRng
} #[cfg(unix)] impl Rng for OSRng { fn next_u32(&mut self) -> u32 { self.inner.next_u32() } fn next_u64(&mut self) -> u64 { self.inner.next_u64() } fn fill_bytes(&mut self, v: &mut [u8]) { self.inner.fill_bytes(v) } } #[cfg(windows)] impl Rng for OSRng { fn next_u32(&mut self) -> u32 { let mut v = [0u8,.. 4]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn next_u64(&mut self) -> u64 { let mut v = [0u8,.. 8]; self.fill_bytes(v); unsafe { cast::transmute(v) } } fn fill_bytes(&mut self, v: &mut [u8]) { use container::Container; use vec::MutableVector; extern { fn rust_win32_rand_gen(hProv: HCRYPTPROV, dwLen: DWORD, pbBuffer: *mut BYTE); } unsafe {rust_win32_rand_gen(self.hcryptprov, v.len() as DWORD, v.as_mut_ptr())} } } impl Drop for OSRng { #[cfg(unix)] fn drop(&mut self) { // ensure that OSRng is not implicitly copyable on all // platforms, for consistency. } #[cfg(windows)] fn drop(&mut self) { extern { fn rust_win32_rand_release(hProv: HCRYPTPROV); } unsafe {rust_win32_rand_release(self.hcryptprov)} } } #[cfg(test)] mod test { use prelude::*; use super::*; use rand::Rng; use task; #[test] fn test_os_rng() { let mut r = OSRng::new(); r.next_u32(); r.next_u64(); let mut v = [0u8,.. 1000]; r.fill_bytes(v); } #[test] fn test_os_rng_tasks() { let mut chans = ~[]; for _ in range(0, 20) { let (p, c) = Chan::new(); chans.push(c); do task::spawn { // wait until all the tasks are ready to go. p.recv(); // deschedule to attempt to interleave things as much // as possible (XXX: is this a good test?) let mut r = OSRng::new(); task::deschedule(); let mut v = [0u8,.. 1000]; for _ in range(0, 100) { r.next_u32(); task::deschedule(); r.next_u64(); task::deschedule(); r.fill_bytes(v); task::deschedule(); } } } // start all the tasks for c in chans.iter() { c.send(()) } } }
{ extern { fn rust_win32_rand_acquire(phProv: *mut HCRYPTPROV); } let mut hcp = 0; unsafe {rust_win32_rand_acquire(&mut hcp)}; OSRng { hcryptprov: hcp } }
identifier_body
safe.rs
use std::fmt; #[link(name = "m")] extern { fn ccosf(z: Complex) -> Complex; } // safe wrapper fn cos(z: Complex) -> Complex { unsafe { ccosf(z) } } fn main()
// Minimal implementation of single precision complex numbers #[repr(C)] #[deriving(Copy)] struct Complex { re: f32, im: f32, } impl fmt::Show for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self.im) } else { write!(f, "{}+{}i", self.re, self.im) } } }
{ // z = 0 + 1i let z = Complex { re: 0., im: 1. }; println!("cos({}) = {}", z, cos(z)); }
identifier_body
safe.rs
use std::fmt; #[link(name = "m")] extern { fn ccosf(z: Complex) -> Complex; } // safe wrapper fn cos(z: Complex) -> Complex { unsafe { ccosf(z) } } fn main() { // z = 0 + 1i let z = Complex { re: 0., im: 1. }; println!("cos({}) = {}", z, cos(z)); } // Minimal implementation of single precision complex numbers #[repr(C)] #[deriving(Copy)] struct Complex { re: f32, im: f32, } impl fmt::Show for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0.
else { write!(f, "{}+{}i", self.re, self.im) } } }
{ write!(f, "{}-{}i", self.re, -self.im) }
conditional_block
safe.rs
use std::fmt; #[link(name = "m")] extern { fn ccosf(z: Complex) -> Complex; } // safe wrapper fn cos(z: Complex) -> Complex {
unsafe { ccosf(z) } } fn main() { // z = 0 + 1i let z = Complex { re: 0., im: 1. }; println!("cos({}) = {}", z, cos(z)); } // Minimal implementation of single precision complex numbers #[repr(C)] #[deriving(Copy)] struct Complex { re: f32, im: f32, } impl fmt::Show for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self.im) } else { write!(f, "{}+{}i", self.re, self.im) } } }
random_line_split
safe.rs
use std::fmt; #[link(name = "m")] extern { fn ccosf(z: Complex) -> Complex; } // safe wrapper fn cos(z: Complex) -> Complex { unsafe { ccosf(z) } } fn
() { // z = 0 + 1i let z = Complex { re: 0., im: 1. }; println!("cos({}) = {}", z, cos(z)); } // Minimal implementation of single precision complex numbers #[repr(C)] #[deriving(Copy)] struct Complex { re: f32, im: f32, } impl fmt::Show for Complex { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.im < 0. { write!(f, "{}-{}i", self.re, -self.im) } else { write!(f, "{}+{}i", self.re, self.im) } } }
main
identifier_name
rec-align-u32.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. // run-pass #![allow(dead_code)] #![allow(unused_unsafe)] // Issue #2303 #![feature(intrinsics)] use std::mem; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> usize; pub fn min_align_of<T>() -> usize; } } // This is the type with the questionable alignment #[derive(Debug)] struct Inner { c64: u32 } // This is the type that contains the type with the // questionable alignment, for testing #[derive(Debug)] struct Outer { c8: u8, t: Inner } mod m { pub fn align() -> usize { 4 } pub fn size() -> usize { 8 } } pub fn
() { unsafe { let x = Outer {c8: 22, t: Inner {c64: 44}}; // Send it through the shape code let y = format!("{:?}", x); println!("align inner = {:?}", rusti::min_align_of::<Inner>()); println!("size outer = {:?}", mem::size_of::<Outer>()); println!("y = {:?}", y); // per clang/gcc the alignment of `inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::align()); // per clang/gcc the size of `outer` should be 12 // because `inner`s alignment was 4. assert_eq!(mem::size_of::<Outer>(), m::size()); assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } }
main
identifier_name
rec-align-u32.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. // run-pass #![allow(dead_code)] #![allow(unused_unsafe)] // Issue #2303 #![feature(intrinsics)] use std::mem; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> usize; pub fn min_align_of<T>() -> usize; } } // This is the type with the questionable alignment #[derive(Debug)] struct Inner { c64: u32 } // This is the type that contains the type with the // questionable alignment, for testing #[derive(Debug)] struct Outer {
t: Inner } mod m { pub fn align() -> usize { 4 } pub fn size() -> usize { 8 } } pub fn main() { unsafe { let x = Outer {c8: 22, t: Inner {c64: 44}}; // Send it through the shape code let y = format!("{:?}", x); println!("align inner = {:?}", rusti::min_align_of::<Inner>()); println!("size outer = {:?}", mem::size_of::<Outer>()); println!("y = {:?}", y); // per clang/gcc the alignment of `inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::align()); // per clang/gcc the size of `outer` should be 12 // because `inner`s alignment was 4. assert_eq!(mem::size_of::<Outer>(), m::size()); assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } }
c8: u8,
random_line_split
rec-align-u32.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. // run-pass #![allow(dead_code)] #![allow(unused_unsafe)] // Issue #2303 #![feature(intrinsics)] use std::mem; mod rusti { extern "rust-intrinsic" { pub fn pref_align_of<T>() -> usize; pub fn min_align_of<T>() -> usize; } } // This is the type with the questionable alignment #[derive(Debug)] struct Inner { c64: u32 } // This is the type that contains the type with the // questionable alignment, for testing #[derive(Debug)] struct Outer { c8: u8, t: Inner } mod m { pub fn align() -> usize { 4 } pub fn size() -> usize
} pub fn main() { unsafe { let x = Outer {c8: 22, t: Inner {c64: 44}}; // Send it through the shape code let y = format!("{:?}", x); println!("align inner = {:?}", rusti::min_align_of::<Inner>()); println!("size outer = {:?}", mem::size_of::<Outer>()); println!("y = {:?}", y); // per clang/gcc the alignment of `inner` is 4 on x86. assert_eq!(rusti::min_align_of::<Inner>(), m::align()); // per clang/gcc the size of `outer` should be 12 // because `inner`s alignment was 4. assert_eq!(mem::size_of::<Outer>(), m::size()); assert_eq!(y, "Outer { c8: 22, t: Inner { c64: 44 } }".to_string()); } }
{ 8 }
identifier_body
time.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. use libc; use ops::Sub; use time::Duration; use sync::{Once, ONCE_INIT}; pub struct SteadyTime { t: libc::LARGE_INTEGER, } impl SteadyTime { pub fn now() -> SteadyTime { let mut t = SteadyTime { t: 0 }; unsafe { libc::QueryPerformanceCounter(&mut t.t); } t } pub fn ns(&self) -> u64 { self.t as u64 * 1_000_000_000 / frequency() as u64 } } fn
() -> libc::LARGE_INTEGER { static mut FREQUENCY: libc::LARGE_INTEGER = 0; static ONCE: Once = ONCE_INIT; unsafe { ONCE.call_once(|| { libc::QueryPerformanceFrequency(&mut FREQUENCY); }); FREQUENCY } } impl<'a> Sub for &'a SteadyTime { type Output = Duration; fn sub(self, other: &SteadyTime) -> Duration { let diff = self.t as i64 - other.t as i64; Duration::microseconds(diff * 1_000_000 / frequency() as i64) } }
frequency
identifier_name
time.rs
// 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 libc; use ops::Sub; use time::Duration; use sync::{Once, ONCE_INIT}; pub struct SteadyTime { t: libc::LARGE_INTEGER, } impl SteadyTime { pub fn now() -> SteadyTime { let mut t = SteadyTime { t: 0 }; unsafe { libc::QueryPerformanceCounter(&mut t.t); } t } pub fn ns(&self) -> u64 { self.t as u64 * 1_000_000_000 / frequency() as u64 } } fn frequency() -> libc::LARGE_INTEGER { static mut FREQUENCY: libc::LARGE_INTEGER = 0; static ONCE: Once = ONCE_INIT; unsafe { ONCE.call_once(|| { libc::QueryPerformanceFrequency(&mut FREQUENCY); }); FREQUENCY } } impl<'a> Sub for &'a SteadyTime { type Output = Duration; fn sub(self, other: &SteadyTime) -> Duration { let diff = self.t as i64 - other.t as i64; Duration::microseconds(diff * 1_000_000 / frequency() as i64) } }
// 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
random_line_split
time.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. use libc; use ops::Sub; use time::Duration; use sync::{Once, ONCE_INIT}; pub struct SteadyTime { t: libc::LARGE_INTEGER, } impl SteadyTime { pub fn now() -> SteadyTime
pub fn ns(&self) -> u64 { self.t as u64 * 1_000_000_000 / frequency() as u64 } } fn frequency() -> libc::LARGE_INTEGER { static mut FREQUENCY: libc::LARGE_INTEGER = 0; static ONCE: Once = ONCE_INIT; unsafe { ONCE.call_once(|| { libc::QueryPerformanceFrequency(&mut FREQUENCY); }); FREQUENCY } } impl<'a> Sub for &'a SteadyTime { type Output = Duration; fn sub(self, other: &SteadyTime) -> Duration { let diff = self.t as i64 - other.t as i64; Duration::microseconds(diff * 1_000_000 / frequency() as i64) } }
{ let mut t = SteadyTime { t: 0 }; unsafe { libc::QueryPerformanceCounter(&mut t.t); } t }
identifier_body
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding::HTMLAppletElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use style::attr::AttrValue; #[dom_struct] pub struct HTMLAppletElement { htmlelement: HTMLElement } impl HTMLAppletElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLAppletElement { HTMLAppletElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLAppletElement> { Node::reflect_node(box HTMLAppletElement::new_inherited(local_name, prefix, document), document, HTMLAppletElementBinding::Wrap) } } impl HTMLAppletElementMethods for HTMLAppletElement { // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_atomic_setter!(SetName, "name"); } impl VirtualMethods for HTMLAppletElement { fn super_type(&self) -> Option<&VirtualMethods>
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("name") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } }
{ Some(self.upcast::<HTMLElement>() as &VirtualMethods) }
identifier_body
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding::HTMLAppletElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use style::attr::AttrValue; #[dom_struct] pub struct HTMLAppletElement { htmlelement: HTMLElement } impl HTMLAppletElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> HTMLAppletElement { HTMLAppletElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn
(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLAppletElement> { Node::reflect_node(box HTMLAppletElement::new_inherited(local_name, prefix, document), document, HTMLAppletElementBinding::Wrap) } } impl HTMLAppletElementMethods for HTMLAppletElement { // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_atomic_setter!(SetName, "name"); } impl VirtualMethods for HTMLAppletElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("name") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } }
new
identifier_name
htmlappletelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAppletElementBinding; use dom::bindings::codegen::Bindings::HTMLAppletElementBinding::HTMLAppletElementMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::DomRoot; use dom::bindings::str::DOMString; use dom::document::Document; use dom::htmlelement::HTMLElement; use dom::node::Node; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use style::attr::AttrValue; #[dom_struct] pub struct HTMLAppletElement { htmlelement: HTMLElement }
prefix: Option<Prefix>, document: &Document) -> HTMLAppletElement { HTMLAppletElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<HTMLAppletElement> { Node::reflect_node(box HTMLAppletElement::new_inherited(local_name, prefix, document), document, HTMLAppletElementBinding::Wrap) } } impl HTMLAppletElementMethods for HTMLAppletElement { // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#the-applet-element:dom-applet-name make_atomic_setter!(SetName, "name"); } impl VirtualMethods for HTMLAppletElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("name") => AttrValue::from_atomic(value.into()), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } }
impl HTMLAppletElement { fn new_inherited(local_name: LocalName,
random_line_split
borrowck-move-out-of-vec-tail.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. // Test that we do not permit moves from &[] matched by a vec pattern. #[derive(Clone, Debug)] struct Foo { string: String } pub fn main()
println!("{:?}", z); } _ => { unreachable!(); } } }
{ let x = vec!( Foo { string: "foo".to_string() }, Foo { string: "bar".to_string() }, Foo { string: "baz".to_string() } ); let x: &[Foo] = &x; match x { [_, tail..] => { match tail { [Foo { string: a }, //~ ERROR cannot move out of borrowed content Foo { string: b }] => { //~^^ NOTE attempting to move value to here //~^^ NOTE and here } _ => { unreachable!(); } } let z = tail[0].clone();
identifier_body
borrowck-move-out-of-vec-tail.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. // Test that we do not permit moves from &[] matched by a vec pattern. #[derive(Clone, Debug)] struct Foo { string: String } pub fn main() { let x = vec!( Foo { string: "foo".to_string() }, Foo { string: "bar".to_string() }, Foo { string: "baz".to_string() } ); let x: &[Foo] = &x; match x { [_, tail..] => { match tail { [Foo { string: a }, //~ ERROR cannot move out of borrowed content Foo { string: b }] => {
} _ => { unreachable!(); } } let z = tail[0].clone(); println!("{:?}", z); } _ => { unreachable!(); } } }
//~^^ NOTE attempting to move value to here //~^^ NOTE and here
random_line_split
borrowck-move-out-of-vec-tail.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. // Test that we do not permit moves from &[] matched by a vec pattern. #[derive(Clone, Debug)] struct
{ string: String } pub fn main() { let x = vec!( Foo { string: "foo".to_string() }, Foo { string: "bar".to_string() }, Foo { string: "baz".to_string() } ); let x: &[Foo] = &x; match x { [_, tail..] => { match tail { [Foo { string: a }, //~ ERROR cannot move out of borrowed content Foo { string: b }] => { //~^^ NOTE attempting to move value to here //~^^ NOTE and here } _ => { unreachable!(); } } let z = tail[0].clone(); println!("{:?}", z); } _ => { unreachable!(); } } }
Foo
identifier_name
borrowck-move-out-of-vec-tail.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. // Test that we do not permit moves from &[] matched by a vec pattern. #[derive(Clone, Debug)] struct Foo { string: String } pub fn main() { let x = vec!( Foo { string: "foo".to_string() }, Foo { string: "bar".to_string() }, Foo { string: "baz".to_string() } ); let x: &[Foo] = &x; match x { [_, tail..] => { match tail { [Foo { string: a }, //~ ERROR cannot move out of borrowed content Foo { string: b }] => { //~^^ NOTE attempting to move value to here //~^^ NOTE and here } _ => { unreachable!(); } } let z = tail[0].clone(); println!("{:?}", z); } _ =>
} }
{ unreachable!(); }
conditional_block
arb.rs
use quickcheck::{Arbitrary, Gen}; use rand::{ distributions::{weighted::WeightedIndex, Distribution}, Rng, }; use crate::MultihashGeneric; /// Generates a random valid multihash. impl<const S: usize> Arbitrary for MultihashGeneric<S> { fn
<G: Gen>(g: &mut G) -> Self { // In real world lower multihash codes are more likely to happen, hence distribute them // with bias towards smaller values. let weights = [128, 64, 32, 16, 8, 4, 2, 1]; let dist = WeightedIndex::new(weights.iter()).unwrap(); let code = match dist.sample(g) { 0 => g.gen_range(0, u64::pow(2, 7)), 1 => g.gen_range(u64::pow(2, 7), u64::pow(2, 14)), 2 => g.gen_range(u64::pow(2, 14), u64::pow(2, 21)), 3 => g.gen_range(u64::pow(2, 21), u64::pow(2, 28)), 4 => g.gen_range(u64::pow(2, 28), u64::pow(2, 35)), 5 => g.gen_range(u64::pow(2, 35), u64::pow(2, 42)), 6 => g.gen_range(u64::pow(2, 42), u64::pow(2, 49)), 7 => g.gen_range(u64::pow(2, 56), u64::pow(2, 63)), _ => unreachable!(), }; // Maximum size is S byte due to the generic. let size = g.gen_range(0, S); let mut data = [0; S]; g.fill_bytes(&mut data); MultihashGeneric::wrap(code, &data[..size]).unwrap() } }
arbitrary
identifier_name
arb.rs
use quickcheck::{Arbitrary, Gen}; use rand::{ distributions::{weighted::WeightedIndex, Distribution}, Rng, }; use crate::MultihashGeneric; /// Generates a random valid multihash. impl<const S: usize> Arbitrary for MultihashGeneric<S> { fn arbitrary<G: Gen>(g: &mut G) -> Self { // In real world lower multihash codes are more likely to happen, hence distribute them // with bias towards smaller values. let weights = [128, 64, 32, 16, 8, 4, 2, 1]; let dist = WeightedIndex::new(weights.iter()).unwrap(); let code = match dist.sample(g) { 0 => g.gen_range(0, u64::pow(2, 7)), 1 => g.gen_range(u64::pow(2, 7), u64::pow(2, 14)), 2 => g.gen_range(u64::pow(2, 14), u64::pow(2, 21)), 3 => g.gen_range(u64::pow(2, 21), u64::pow(2, 28)), 4 => g.gen_range(u64::pow(2, 28), u64::pow(2, 35)), 5 => g.gen_range(u64::pow(2, 35), u64::pow(2, 42)), 6 => g.gen_range(u64::pow(2, 42), u64::pow(2, 49)), 7 => g.gen_range(u64::pow(2, 56), u64::pow(2, 63)), _ => unreachable!(), };
let size = g.gen_range(0, S); let mut data = [0; S]; g.fill_bytes(&mut data); MultihashGeneric::wrap(code, &data[..size]).unwrap() } }
// Maximum size is S byte due to the generic.
random_line_split
arb.rs
use quickcheck::{Arbitrary, Gen}; use rand::{ distributions::{weighted::WeightedIndex, Distribution}, Rng, }; use crate::MultihashGeneric; /// Generates a random valid multihash. impl<const S: usize> Arbitrary for MultihashGeneric<S> { fn arbitrary<G: Gen>(g: &mut G) -> Self
g.fill_bytes(&mut data); MultihashGeneric::wrap(code, &data[..size]).unwrap() } }
{ // In real world lower multihash codes are more likely to happen, hence distribute them // with bias towards smaller values. let weights = [128, 64, 32, 16, 8, 4, 2, 1]; let dist = WeightedIndex::new(weights.iter()).unwrap(); let code = match dist.sample(g) { 0 => g.gen_range(0, u64::pow(2, 7)), 1 => g.gen_range(u64::pow(2, 7), u64::pow(2, 14)), 2 => g.gen_range(u64::pow(2, 14), u64::pow(2, 21)), 3 => g.gen_range(u64::pow(2, 21), u64::pow(2, 28)), 4 => g.gen_range(u64::pow(2, 28), u64::pow(2, 35)), 5 => g.gen_range(u64::pow(2, 35), u64::pow(2, 42)), 6 => g.gen_range(u64::pow(2, 42), u64::pow(2, 49)), 7 => g.gen_range(u64::pow(2, 56), u64::pow(2, 63)), _ => unreachable!(), }; // Maximum size is S byte due to the generic. let size = g.gen_range(0, S); let mut data = [0; S];
identifier_body
lib.rs
#![feature(box_syntax, box_patterns)] #![feature(associated_consts)] #![feature(collections, collections_bound, btree_range)] #![feature(unicode)] extern crate libc; extern crate docopt; extern crate toml; extern crate term; extern crate rustc_serialize; extern crate collections; mod bar; pub use self::bar::Bar; pub use self::bar::{ Format, Formatter, Position, Align, }; pub mod data; pub mod util; pub mod pipe; use term::color; use term::Terminal; use rustc_serialize::{ Decodable, Encodable, }; use docopt::Docopt; use util::{ Error, Result, }; pub fn execute<A, V>(exec: fn(A) -> Result<V>, usage: &str) where A: Decodable, V: Encodable, { let args: A = decode_args(usage); match (exec)(args) { Ok(..) => {}, Err(e) => handle_error(e), } } fn decode_args<A>(usage: &str) -> A where A: Decodable { let docopt = Docopt::new(usage).unwrap() .help(true) .version(Some(::version())); docopt.decode().unwrap_or_else(|e| e.exit()) } fn handle_error(err: Error) ->!
fn version() -> String { format!("bar {}", env!("CARGO_PKG_VERSION")) }
{ if let Some(mut t) = term::stderr() { let _ = t.fg(color::RED); let _ = writeln!(t, "{}", err); let _ = t.reset(); } ::std::process::exit(1) }
identifier_body
lib.rs
#![feature(box_syntax, box_patterns)] #![feature(associated_consts)] #![feature(collections, collections_bound, btree_range)] #![feature(unicode)] extern crate libc; extern crate docopt; extern crate toml; extern crate term; extern crate rustc_serialize; extern crate collections; mod bar; pub use self::bar::Bar; pub use self::bar::{ Format, Formatter, Position, Align, }; pub mod data; pub mod util; pub mod pipe; use term::color; use term::Terminal; use rustc_serialize::{ Decodable, Encodable, }; use docopt::Docopt; use util::{ Error, Result, }; pub fn execute<A, V>(exec: fn(A) -> Result<V>, usage: &str) where A: Decodable, V: Encodable, { let args: A = decode_args(usage); match (exec)(args) { Ok(..) => {}, Err(e) => handle_error(e), } } fn
<A>(usage: &str) -> A where A: Decodable { let docopt = Docopt::new(usage).unwrap() .help(true) .version(Some(::version())); docopt.decode().unwrap_or_else(|e| e.exit()) } fn handle_error(err: Error) ->! { if let Some(mut t) = term::stderr() { let _ = t.fg(color::RED); let _ = writeln!(t, "{}", err); let _ = t.reset(); } ::std::process::exit(1) } fn version() -> String { format!("bar {}", env!("CARGO_PKG_VERSION")) }
decode_args
identifier_name
lib.rs
#![feature(box_syntax, box_patterns)] #![feature(associated_consts)] #![feature(collections, collections_bound, btree_range)] #![feature(unicode)] extern crate libc; extern crate docopt; extern crate toml; extern crate term; extern crate rustc_serialize; extern crate collections; mod bar; pub use self::bar::Bar; pub use self::bar::{ Format, Formatter, Position, Align, }; pub mod data; pub mod util; pub mod pipe; use term::color; use term::Terminal; use rustc_serialize::{ Decodable, Encodable, }; use docopt::Docopt; use util::{ Error, Result, }; pub fn execute<A, V>(exec: fn(A) -> Result<V>, usage: &str) where A: Decodable, V: Encodable, { let args: A = decode_args(usage); match (exec)(args) { Ok(..) => {}, Err(e) => handle_error(e), } } fn decode_args<A>(usage: &str) -> A where A: Decodable { let docopt = Docopt::new(usage).unwrap() .help(true) .version(Some(::version())); docopt.decode().unwrap_or_else(|e| e.exit()) } fn handle_error(err: Error) ->! { if let Some(mut t) = term::stderr()
::std::process::exit(1) } fn version() -> String { format!("bar {}", env!("CARGO_PKG_VERSION")) }
{ let _ = t.fg(color::RED); let _ = writeln!(t, "{}", err); let _ = t.reset(); }
conditional_block
lib.rs
#![feature(box_syntax, box_patterns)] #![feature(associated_consts)] #![feature(collections, collections_bound, btree_range)] #![feature(unicode)] extern crate libc; extern crate docopt; extern crate toml; extern crate term; extern crate rustc_serialize; extern crate collections; mod bar; pub use self::bar::Bar; pub use self::bar::{ Format, Formatter, Position, Align, }; pub mod data; pub mod util; pub mod pipe; use term::color; use term::Terminal; use rustc_serialize::{ Decodable, Encodable, }; use docopt::Docopt; use util::{ Error, Result, }; pub fn execute<A, V>(exec: fn(A) -> Result<V>, usage: &str)
match (exec)(args) { Ok(..) => {}, Err(e) => handle_error(e), } } fn decode_args<A>(usage: &str) -> A where A: Decodable { let docopt = Docopt::new(usage).unwrap() .help(true) .version(Some(::version())); docopt.decode().unwrap_or_else(|e| e.exit()) } fn handle_error(err: Error) ->! { if let Some(mut t) = term::stderr() { let _ = t.fg(color::RED); let _ = writeln!(t, "{}", err); let _ = t.reset(); } ::std::process::exit(1) } fn version() -> String { format!("bar {}", env!("CARGO_PKG_VERSION")) }
where A: Decodable, V: Encodable, { let args: A = decode_args(usage);
random_line_split
data.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 construct::ConstructionResult; use script_layout_interface::restyle_damage::RestyleDamage; use style::data::PersistentStyleData; /// Data that layout associates with a node. pub struct PersistentLayoutData { /// Data that the style system associates with a node. When the /// style system is being used standalone, this is all that hangs /// off the node. This must be first to permit the various /// transmutations between PersistentStyleData and PersistentLayoutData. pub style_data: PersistentStyleData, /// Description of how to account for recent style changes. pub restyle_damage: RestyleDamage, /// The current results of flow construction for this node. This is either a /// flow or a `ConstructionItem`. See comments in `construct.rs` for more /// details. pub flow_construction_result: ConstructionResult, pub before_flow_construction_result: ConstructionResult, pub after_flow_construction_result: ConstructionResult, pub details_summary_flow_construction_result: ConstructionResult, pub details_content_flow_construction_result: ConstructionResult, /// Various flags. pub flags: LayoutDataFlags, } impl PersistentLayoutData { /// Creates new layout data. pub fn new() -> PersistentLayoutData
} bitflags! { pub flags LayoutDataFlags: u8 { #[doc = "Whether a flow has been newly constructed."] const HAS_NEWLY_CONSTRUCTED_FLOW = 0x01 } }
{ PersistentLayoutData { style_data: PersistentStyleData::new(), restyle_damage: RestyleDamage::empty(), flow_construction_result: ConstructionResult::None, before_flow_construction_result: ConstructionResult::None, after_flow_construction_result: ConstructionResult::None, details_summary_flow_construction_result: ConstructionResult::None, details_content_flow_construction_result: ConstructionResult::None, flags: LayoutDataFlags::empty(), } }
identifier_body
data.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 construct::ConstructionResult; use script_layout_interface::restyle_damage::RestyleDamage; use style::data::PersistentStyleData; /// Data that layout associates with a node. pub struct PersistentLayoutData { /// Data that the style system associates with a node. When the /// style system is being used standalone, this is all that hangs /// off the node. This must be first to permit the various /// transmutations between PersistentStyleData and PersistentLayoutData. pub style_data: PersistentStyleData,
/// Description of how to account for recent style changes. pub restyle_damage: RestyleDamage, /// The current results of flow construction for this node. This is either a /// flow or a `ConstructionItem`. See comments in `construct.rs` for more /// details. pub flow_construction_result: ConstructionResult, pub before_flow_construction_result: ConstructionResult, pub after_flow_construction_result: ConstructionResult, pub details_summary_flow_construction_result: ConstructionResult, pub details_content_flow_construction_result: ConstructionResult, /// Various flags. pub flags: LayoutDataFlags, } impl PersistentLayoutData { /// Creates new layout data. pub fn new() -> PersistentLayoutData { PersistentLayoutData { style_data: PersistentStyleData::new(), restyle_damage: RestyleDamage::empty(), flow_construction_result: ConstructionResult::None, before_flow_construction_result: ConstructionResult::None, after_flow_construction_result: ConstructionResult::None, details_summary_flow_construction_result: ConstructionResult::None, details_content_flow_construction_result: ConstructionResult::None, flags: LayoutDataFlags::empty(), } } } bitflags! { pub flags LayoutDataFlags: u8 { #[doc = "Whether a flow has been newly constructed."] const HAS_NEWLY_CONSTRUCTED_FLOW = 0x01 } }
random_line_split