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 |
---|---|---|---|---|
global.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/. */
//! Abstractions for global scopes.
//!
//! This module contains smart pointers to global scopes, to simplify writing
//! code that works in workers as well as window scopes.
use dom::bindings::conversions::native_from_reflector_jsmanaged;
use dom::bindings::js::{JS, JSRef, Root, Unrooted};
use dom::bindings::utils::{Reflectable, Reflector};
use dom::workerglobalscope::{WorkerGlobalScope, WorkerGlobalScopeHelpers};
use dom::window::{self, WindowHelpers};
use devtools_traits::DevtoolsControlChan;
use script_task::{ScriptChan, ScriptPort, ScriptMsg, ScriptTask};
use msg::constellation_msg::{PipelineId, WorkerId};
use net_traits::ResourceTask;
use js::{JSCLASS_IS_GLOBAL, JSCLASS_IS_DOMJSCLASS};
use js::glue::{GetGlobalForObjectCrossCompartment};
use js::jsapi::{JSContext, JSObject};
use js::jsapi::{JS_GetClass};
use url::Url;
/// A freely-copyable reference to a rooted global object.
#[derive(Copy)]
pub enum GlobalRef<'a> {
/// A reference to a `Window` object.
Window(JSRef<'a, window::Window>),
/// A reference to a `WorkerGlobalScope` object.
Worker(JSRef<'a, WorkerGlobalScope>),
}
/// A stack-based rooted reference to a global object.
pub enum GlobalRoot {
/// A root for a `Window` object.
Window(Root<window::Window>),
/// A root for a `WorkerGlobalScope` object.
Worker(Root<WorkerGlobalScope>),
}
/// A traced reference to a global object, for use in fields of traced Rust
/// structures.
#[jstraceable]
#[must_root]
pub enum GlobalField {
/// A field for a `Window` object.
Window(JS<window::Window>),
/// A field for a `WorkerGlobalScope` object.
Worker(JS<WorkerGlobalScope>),
}
/// An unrooted reference to a global object.
#[must_root]
pub enum GlobalUnrooted {
/// An unrooted reference to a `Window` object.
Window(Unrooted<window::Window>),
/// An unrooted reference to a `WorkerGlobalScope` object.
Worker(Unrooted<WorkerGlobalScope>),
}
impl<'a> GlobalRef<'a> {
/// Get the `JSContext` for the `JSRuntime` associated with the thread
/// this global object is on.
pub fn get_cx(&self) -> *mut JSContext {
match *self {
GlobalRef::Window(ref window) => window.get_cx(),
GlobalRef::Worker(ref worker) => worker.get_cx(),
}
}
/// Extract a `Window`, causing task failure if the global object is not
/// a `Window`.
pub fn as_window<'b>(&'b self) -> JSRef<'b, window::Window> {
match *self {
GlobalRef::Window(window) => window,
GlobalRef::Worker(_) => panic!("expected a Window scope"),
}
}
/// Get the `PipelineId` for this global scope.
pub fn pipeline(&self) -> PipelineId {
match *self {
GlobalRef::Window(window) => window.pipeline(),
GlobalRef::Worker(worker) => worker.pipeline(),
}
}
/// Get `DevtoolsControlChan` to send messages to Devtools
/// task when available.
pub fn devtools_chan(&self) -> Option<DevtoolsControlChan> {
match *self {
GlobalRef::Window(window) => window.devtools_chan(),
GlobalRef::Worker(worker) => worker.devtools_chan(),
}
}
/// Get the `ResourceTask` for this global scope.
pub fn resource_task(&self) -> ResourceTask {
match *self {
GlobalRef::Window(ref window) => window.resource_task().clone(),
GlobalRef::Worker(ref worker) => worker.resource_task().clone(),
}
}
/// Get next worker id.
pub fn get_next_worker_id(&self) -> WorkerId {
match *self {
GlobalRef::Window(ref window) => window.get_next_worker_id(),
GlobalRef::Worker(ref worker) => worker.get_next_worker_id()
}
}
/// Get the URL for this global scope.
pub fn get_url(&self) -> Url {
match *self {
GlobalRef::Window(ref window) => window.get_url(),
GlobalRef::Worker(ref worker) => worker.get_url().clone(),
}
}
/// `ScriptChan` used to send messages to the event loop of this global's
/// thread.
pub fn script_chan(&self) -> Box<ScriptChan+Send> {
match *self {
GlobalRef::Window(ref window) => window.script_chan(),
GlobalRef::Worker(ref worker) => worker.script_chan(),
}
}
/// Create a new sender/receiver pair that can be used to implement an on-demand
/// event loop. Used for implementing web APIs that require blocking semantics
/// without resorting to nested event loops.
pub fn new_script_pair(&self) -> (Box<ScriptChan+Send>, Box<ScriptPort+Send>) |
/// Process a single event as if it were the next event in the task queue for
/// this global.
pub fn process_event(&self, msg: ScriptMsg) {
match *self {
GlobalRef::Window(_) => ScriptTask::process_event(msg),
GlobalRef::Worker(ref worker) => worker.process_event(msg),
}
}
}
impl<'a> Reflectable for GlobalRef<'a> {
fn reflector<'b>(&'b self) -> &'b Reflector {
match *self {
GlobalRef::Window(ref window) => window.reflector(),
GlobalRef::Worker(ref worker) => worker.reflector(),
}
}
}
impl GlobalRoot {
/// Obtain a safe reference to the global object that cannot outlive the
/// lifetime of this root.
pub fn r<'c>(&'c self) -> GlobalRef<'c> {
match *self {
GlobalRoot::Window(ref window) => GlobalRef::Window(window.r()),
GlobalRoot::Worker(ref worker) => GlobalRef::Worker(worker.r()),
}
}
}
impl GlobalField {
/// Create a new `GlobalField` from a rooted reference.
pub fn from_rooted(global: &GlobalRef) -> GlobalField {
match *global {
GlobalRef::Window(window) => GlobalField::Window(JS::from_rooted(window)),
GlobalRef::Worker(worker) => GlobalField::Worker(JS::from_rooted(worker)),
}
}
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalField::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalField::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
impl GlobalUnrooted {
/// Create a stack-bounded root for this reference.
pub fn root(&self) -> GlobalRoot {
match *self {
GlobalUnrooted::Window(ref window) => GlobalRoot::Window(window.root()),
GlobalUnrooted::Worker(ref worker) => GlobalRoot::Worker(worker.root()),
}
}
}
/// Returns the global object of the realm that the given JS object was created in.
#[allow(unrooted_must_root)]
pub fn global_object_for_js_object(obj: *mut JSObject) -> GlobalUnrooted {
unsafe {
let global = GetGlobalForObjectCrossCompartment(obj);
let clasp = JS_GetClass(global);
assert!(((*clasp).flags & (JSCLASS_IS_DOMJSCLASS | JSCLASS_IS_GLOBAL))!= 0);
match native_from_reflector_jsmanaged(global) {
Ok(window) => return GlobalUnrooted::Window(window),
Err(_) => (),
}
match native_from_reflector_jsmanaged(global) {
Ok(worker) => return GlobalUnrooted::Worker(worker),
Err(_) => (),
}
panic!("found DOM global that doesn't unwrap to Window or WorkerGlobalScope")
}
}
| {
match *self {
GlobalRef::Window(ref window) => window.new_script_pair(),
GlobalRef::Worker(ref worker) => worker.new_script_pair(),
}
} | identifier_body |
attr.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 devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap};
use dom::bindings::js::{LayoutJS, Root, RootedReference};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeMutation, Element};
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use std::ops::Deref;
use string_cache::{Atom, Namespace};
use util::str::{DOMString, parse_unsigned_integer, split_html_space_chars, str_join};
#[derive(JSTraceable, PartialEq, Clone, HeapSizeOf)]
pub enum AttrValue {
String(DOMString),
TokenList(DOMString, Vec<Atom>),
UInt(DOMString, u32),
Atom(Atom),
}
impl AttrValue {
pub fn from_serialized_tokenlist(tokens: DOMString) -> AttrValue {
let atoms =
split_html_space_chars(&tokens)
.map(Atom::from_slice)
.fold(vec![], |mut acc, atom| {
if!acc.contains(&atom) { acc.push(atom) }
acc
});
AttrValue::TokenList(tokens, atoms)
}
pub fn from_atomic_tokens(atoms: Vec<Atom>) -> AttrValue {
let tokens = str_join(&atoms, "\x20");
AttrValue::TokenList(tokens, atoms)
}
// https://html.spec.whatwg.org/multipage/#reflecting-content-attributes-in-idl-attributes:idl-unsigned-long
pub fn from_u32(string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
// https://html.spec.whatwg.org/multipage/#limited-to-only-non-negative-numbers-greater-than-zero
pub fn from_limited_u32(string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result == 0 || result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
pub fn from_atomic(string: DOMString) -> AttrValue {
let value = Atom::from_slice(&string);
AttrValue::Atom(value)
}
pub fn as_tokens(&self) -> &[Atom] {
match *self {
AttrValue::TokenList(_, ref tokens) => tokens,
_ => panic!("Tokens not found"),
}
}
pub fn as_atom(&self) -> &Atom {
match *self {
AttrValue::Atom(ref value) => value,
_ => panic!("Atom not found"),
}
}
/// Return the AttrValue as its integer representation, if any.
/// This corresponds to attribute values returned as `AttrValue::UInt(_)`
/// by `VirtualMethods::parse_plain_attribute()`.
pub fn as_uint(&self) -> u32 {
if let AttrValue::UInt(_, value) = *self {
value
} else {
panic!("Uint not found");
}
}
}
impl Deref for AttrValue {
type Target = str;
fn deref(&self) -> &str {
match *self {
AttrValue::String(ref value) |
AttrValue::TokenList(ref value, _) |
AttrValue::UInt(ref value, _) => &value,
AttrValue::Atom(ref value) => &value,
}
}
}
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
local_name: Atom,
value: DOMRefCell<AttrValue>,
name: Atom,
namespace: Namespace,
prefix: Option<Atom>,
/// the element that owns this attribute.
owner: MutNullableHeap<JS<Element>>,
}
impl Attr {
fn new_inherited(local_name: Atom, value: AttrValue, name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Attr {
Attr {
reflector_: Reflector::new(),
local_name: local_name,
value: DOMRefCell::new(value),
name: name,
namespace: namespace,
prefix: prefix,
owner: MutNullableHeap::new(owner.map(JS::from_ref)),
}
}
pub fn new(window: &Window, local_name: Atom, value: AttrValue,
name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Root<Attr> {
reflect_dom_object(
box Attr::new_inherited(local_name, value, name, namespace, prefix, owner),
GlobalRef::Window(window),
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &Atom {
&self.name
}
#[inline]
pub fn namespace(&self) -> &Namespace { | #[inline]
pub fn prefix(&self) -> &Option<Atom> {
&self.prefix
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
(**self.local_name()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
(**self.value()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
match self.owner() {
None => *self.value.borrow_mut() = AttrValue::String(value),
Some(owner) => {
let value = owner.r().parse_attribute(&self.namespace, self.local_name(), value);
self.set_value(value, owner.r());
}
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
(*self.name).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
let Namespace(ref atom) = self.namespace;
match &**atom {
"" => None,
url => Some(url.to_owned()),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
self.prefix().as_ref().map(|p| (**p).to_owned())
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
assert!(Some(owner) == self.owner().r());
mem::swap(&mut *self.value.borrow_mut(), &mut value);
if self.namespace == ns!("") {
vtable_for(NodeCast::from_ref(owner)).attribute_mutated(
self, AttributeMutation::Set(Some(&value)));
}
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &Atom {
&self.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ref ns = self.namespace;
match (self.owner().r(), owner) {
(None, Some(new)) => {
// Already in the list of attributes of new owner.
assert!(new.get_attribute(&ns, &self.local_name) == Some(Root::from_ref(self)))
}
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.local_name).is_none())
}
(old, new) => assert!(old == new)
}
self.owner.set(owner.map(JS::from_ref))
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get().map(Root::from_rooted)
}
pub fn summarize(&self) -> AttrInfo {
let Namespace(ref ns) = self.namespace;
AttrInfo {
namespace: (**ns).to_owned(),
name: self.Name(),
value: self.Value(),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> Atom;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> Atom {
(*self.unsafe_get()).local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
} | &self.namespace
}
| random_line_split |
attr.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 devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap};
use dom::bindings::js::{LayoutJS, Root, RootedReference};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeMutation, Element};
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use std::ops::Deref;
use string_cache::{Atom, Namespace};
use util::str::{DOMString, parse_unsigned_integer, split_html_space_chars, str_join};
#[derive(JSTraceable, PartialEq, Clone, HeapSizeOf)]
pub enum AttrValue {
String(DOMString),
TokenList(DOMString, Vec<Atom>),
UInt(DOMString, u32),
Atom(Atom),
}
impl AttrValue {
pub fn from_serialized_tokenlist(tokens: DOMString) -> AttrValue {
let atoms =
split_html_space_chars(&tokens)
.map(Atom::from_slice)
.fold(vec![], |mut acc, atom| {
if!acc.contains(&atom) { acc.push(atom) }
acc
});
AttrValue::TokenList(tokens, atoms)
}
pub fn from_atomic_tokens(atoms: Vec<Atom>) -> AttrValue {
let tokens = str_join(&atoms, "\x20");
AttrValue::TokenList(tokens, atoms)
}
// https://html.spec.whatwg.org/multipage/#reflecting-content-attributes-in-idl-attributes:idl-unsigned-long
pub fn from_u32(string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
// https://html.spec.whatwg.org/multipage/#limited-to-only-non-negative-numbers-greater-than-zero
pub fn from_limited_u32(string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result == 0 || result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
pub fn from_atomic(string: DOMString) -> AttrValue {
let value = Atom::from_slice(&string);
AttrValue::Atom(value)
}
pub fn as_tokens(&self) -> &[Atom] {
match *self {
AttrValue::TokenList(_, ref tokens) => tokens,
_ => panic!("Tokens not found"),
}
}
pub fn as_atom(&self) -> &Atom {
match *self {
AttrValue::Atom(ref value) => value,
_ => panic!("Atom not found"),
}
}
/// Return the AttrValue as its integer representation, if any.
/// This corresponds to attribute values returned as `AttrValue::UInt(_)`
/// by `VirtualMethods::parse_plain_attribute()`.
pub fn as_uint(&self) -> u32 {
if let AttrValue::UInt(_, value) = *self {
value
} else {
panic!("Uint not found");
}
}
}
impl Deref for AttrValue {
type Target = str;
fn deref(&self) -> &str {
match *self {
AttrValue::String(ref value) |
AttrValue::TokenList(ref value, _) |
AttrValue::UInt(ref value, _) => &value,
AttrValue::Atom(ref value) => &value,
}
}
}
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
local_name: Atom,
value: DOMRefCell<AttrValue>,
name: Atom,
namespace: Namespace,
prefix: Option<Atom>,
/// the element that owns this attribute.
owner: MutNullableHeap<JS<Element>>,
}
impl Attr {
fn new_inherited(local_name: Atom, value: AttrValue, name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Attr {
Attr {
reflector_: Reflector::new(),
local_name: local_name,
value: DOMRefCell::new(value),
name: name,
namespace: namespace,
prefix: prefix,
owner: MutNullableHeap::new(owner.map(JS::from_ref)),
}
}
pub fn new(window: &Window, local_name: Atom, value: AttrValue,
name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Root<Attr> {
reflect_dom_object(
box Attr::new_inherited(local_name, value, name, namespace, prefix, owner),
GlobalRef::Window(window),
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &Atom {
&self.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.namespace
}
#[inline]
pub fn prefix(&self) -> &Option<Atom> {
&self.prefix
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
(**self.local_name()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
(**self.value()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
match self.owner() {
None => *self.value.borrow_mut() = AttrValue::String(value),
Some(owner) => {
let value = owner.r().parse_attribute(&self.namespace, self.local_name(), value);
self.set_value(value, owner.r());
}
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
(*self.name).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
let Namespace(ref atom) = self.namespace;
match &**atom {
"" => None,
url => Some(url.to_owned()),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
self.prefix().as_ref().map(|p| (**p).to_owned())
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
assert!(Some(owner) == self.owner().r());
mem::swap(&mut *self.value.borrow_mut(), &mut value);
if self.namespace == ns!("") {
vtable_for(NodeCast::from_ref(owner)).attribute_mutated(
self, AttributeMutation::Set(Some(&value)));
}
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &Atom {
&self.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ref ns = self.namespace;
match (self.owner().r(), owner) {
(None, Some(new)) => {
// Already in the list of attributes of new owner.
assert!(new.get_attribute(&ns, &self.local_name) == Some(Root::from_ref(self)))
}
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.local_name).is_none())
}
(old, new) => assert!(old == new)
}
self.owner.set(owner.map(JS::from_ref))
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get().map(Root::from_rooted)
}
pub fn summarize(&self) -> AttrInfo {
let Namespace(ref ns) = self.namespace;
AttrInfo {
namespace: (**ns).to_owned(),
name: self.Name(),
value: self.Value(),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> Atom;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> |
#[inline]
unsafe fn local_name_atom_forever(&self) -> Atom {
(*self.unsafe_get()).local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
}
| {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
} | identifier_body |
attr.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 devtools_traits::AttrInfo;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods};
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, MutNullableHeap};
use dom::bindings::js::{LayoutJS, Root, RootedReference};
use dom::bindings::utils::{Reflector, reflect_dom_object};
use dom::element::{AttributeMutation, Element};
use dom::virtualmethods::vtable_for;
use dom::window::Window;
use std::borrow::ToOwned;
use std::cell::Ref;
use std::mem;
use std::ops::Deref;
use string_cache::{Atom, Namespace};
use util::str::{DOMString, parse_unsigned_integer, split_html_space_chars, str_join};
#[derive(JSTraceable, PartialEq, Clone, HeapSizeOf)]
pub enum AttrValue {
String(DOMString),
TokenList(DOMString, Vec<Atom>),
UInt(DOMString, u32),
Atom(Atom),
}
impl AttrValue {
pub fn from_serialized_tokenlist(tokens: DOMString) -> AttrValue {
let atoms =
split_html_space_chars(&tokens)
.map(Atom::from_slice)
.fold(vec![], |mut acc, atom| {
if!acc.contains(&atom) { acc.push(atom) }
acc
});
AttrValue::TokenList(tokens, atoms)
}
pub fn from_atomic_tokens(atoms: Vec<Atom>) -> AttrValue {
let tokens = str_join(&atoms, "\x20");
AttrValue::TokenList(tokens, atoms)
}
// https://html.spec.whatwg.org/multipage/#reflecting-content-attributes-in-idl-attributes:idl-unsigned-long
pub fn | (string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
// https://html.spec.whatwg.org/multipage/#limited-to-only-non-negative-numbers-greater-than-zero
pub fn from_limited_u32(string: DOMString, default: u32) -> AttrValue {
let result = parse_unsigned_integer(string.chars()).unwrap_or(default);
let result = if result == 0 || result > 2147483647 {
default
} else {
result
};
AttrValue::UInt(string, result)
}
pub fn from_atomic(string: DOMString) -> AttrValue {
let value = Atom::from_slice(&string);
AttrValue::Atom(value)
}
pub fn as_tokens(&self) -> &[Atom] {
match *self {
AttrValue::TokenList(_, ref tokens) => tokens,
_ => panic!("Tokens not found"),
}
}
pub fn as_atom(&self) -> &Atom {
match *self {
AttrValue::Atom(ref value) => value,
_ => panic!("Atom not found"),
}
}
/// Return the AttrValue as its integer representation, if any.
/// This corresponds to attribute values returned as `AttrValue::UInt(_)`
/// by `VirtualMethods::parse_plain_attribute()`.
pub fn as_uint(&self) -> u32 {
if let AttrValue::UInt(_, value) = *self {
value
} else {
panic!("Uint not found");
}
}
}
impl Deref for AttrValue {
type Target = str;
fn deref(&self) -> &str {
match *self {
AttrValue::String(ref value) |
AttrValue::TokenList(ref value, _) |
AttrValue::UInt(ref value, _) => &value,
AttrValue::Atom(ref value) => &value,
}
}
}
// https://dom.spec.whatwg.org/#interface-attr
#[dom_struct]
pub struct Attr {
reflector_: Reflector,
local_name: Atom,
value: DOMRefCell<AttrValue>,
name: Atom,
namespace: Namespace,
prefix: Option<Atom>,
/// the element that owns this attribute.
owner: MutNullableHeap<JS<Element>>,
}
impl Attr {
fn new_inherited(local_name: Atom, value: AttrValue, name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Attr {
Attr {
reflector_: Reflector::new(),
local_name: local_name,
value: DOMRefCell::new(value),
name: name,
namespace: namespace,
prefix: prefix,
owner: MutNullableHeap::new(owner.map(JS::from_ref)),
}
}
pub fn new(window: &Window, local_name: Atom, value: AttrValue,
name: Atom, namespace: Namespace,
prefix: Option<Atom>, owner: Option<&Element>) -> Root<Attr> {
reflect_dom_object(
box Attr::new_inherited(local_name, value, name, namespace, prefix, owner),
GlobalRef::Window(window),
AttrBinding::Wrap)
}
#[inline]
pub fn name(&self) -> &Atom {
&self.name
}
#[inline]
pub fn namespace(&self) -> &Namespace {
&self.namespace
}
#[inline]
pub fn prefix(&self) -> &Option<Atom> {
&self.prefix
}
}
impl AttrMethods for Attr {
// https://dom.spec.whatwg.org/#dom-attr-localname
fn LocalName(&self) -> DOMString {
(**self.local_name()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn Value(&self) -> DOMString {
(**self.value()).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-value
fn SetValue(&self, value: DOMString) {
match self.owner() {
None => *self.value.borrow_mut() = AttrValue::String(value),
Some(owner) => {
let value = owner.r().parse_attribute(&self.namespace, self.local_name(), value);
self.set_value(value, owner.r());
}
}
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn TextContent(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-textcontent
fn SetTextContent(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn NodeValue(&self) -> DOMString {
self.Value()
}
// https://dom.spec.whatwg.org/#dom-attr-nodevalue
fn SetNodeValue(&self, value: DOMString) {
self.SetValue(value)
}
// https://dom.spec.whatwg.org/#dom-attr-name
fn Name(&self) -> DOMString {
(*self.name).to_owned()
}
// https://dom.spec.whatwg.org/#dom-attr-namespaceuri
fn GetNamespaceURI(&self) -> Option<DOMString> {
let Namespace(ref atom) = self.namespace;
match &**atom {
"" => None,
url => Some(url.to_owned()),
}
}
// https://dom.spec.whatwg.org/#dom-attr-prefix
fn GetPrefix(&self) -> Option<DOMString> {
self.prefix().as_ref().map(|p| (**p).to_owned())
}
// https://dom.spec.whatwg.org/#dom-attr-ownerelement
fn GetOwnerElement(&self) -> Option<Root<Element>> {
self.owner()
}
// https://dom.spec.whatwg.org/#dom-attr-specified
fn Specified(&self) -> bool {
true // Always returns true
}
}
impl Attr {
pub fn set_value(&self, mut value: AttrValue, owner: &Element) {
assert!(Some(owner) == self.owner().r());
mem::swap(&mut *self.value.borrow_mut(), &mut value);
if self.namespace == ns!("") {
vtable_for(NodeCast::from_ref(owner)).attribute_mutated(
self, AttributeMutation::Set(Some(&value)));
}
}
pub fn value(&self) -> Ref<AttrValue> {
self.value.borrow()
}
pub fn local_name(&self) -> &Atom {
&self.local_name
}
/// Sets the owner element. Should be called after the attribute is added
/// or removed from its older parent.
pub fn set_owner(&self, owner: Option<&Element>) {
let ref ns = self.namespace;
match (self.owner().r(), owner) {
(None, Some(new)) => {
// Already in the list of attributes of new owner.
assert!(new.get_attribute(&ns, &self.local_name) == Some(Root::from_ref(self)))
}
(Some(old), None) => {
// Already gone from the list of attributes of old owner.
assert!(old.get_attribute(&ns, &self.local_name).is_none())
}
(old, new) => assert!(old == new)
}
self.owner.set(owner.map(JS::from_ref))
}
pub fn owner(&self) -> Option<Root<Element>> {
self.owner.get().map(Root::from_rooted)
}
pub fn summarize(&self) -> AttrInfo {
let Namespace(ref ns) = self.namespace;
AttrInfo {
namespace: (**ns).to_owned(),
name: self.Name(),
value: self.Value(),
}
}
}
#[allow(unsafe_code)]
pub trait AttrHelpersForLayout {
unsafe fn value_forever(&self) -> &'static AttrValue;
unsafe fn value_ref_forever(&self) -> &'static str;
unsafe fn value_atom_forever(&self) -> Option<Atom>;
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]>;
unsafe fn local_name_atom_forever(&self) -> Atom;
unsafe fn value_for_layout(&self) -> &AttrValue;
}
#[allow(unsafe_code)]
impl AttrHelpersForLayout for LayoutJS<Attr> {
#[inline]
unsafe fn value_forever(&self) -> &'static AttrValue {
// This transmute is used to cheat the lifetime restriction.
mem::transmute::<&AttrValue, &AttrValue>((*self.unsafe_get()).value.borrow_for_layout())
}
#[inline]
unsafe fn value_ref_forever(&self) -> &'static str {
&**self.value_forever()
}
#[inline]
unsafe fn value_atom_forever(&self) -> Option<Atom> {
let value = (*self.unsafe_get()).value.borrow_for_layout();
match *value {
AttrValue::Atom(ref val) => Some(val.clone()),
_ => None,
}
}
#[inline]
unsafe fn value_tokens_forever(&self) -> Option<&'static [Atom]> {
// This transmute is used to cheat the lifetime restriction.
match *self.value_forever() {
AttrValue::TokenList(_, ref tokens) => Some(tokens),
_ => None,
}
}
#[inline]
unsafe fn local_name_atom_forever(&self) -> Atom {
(*self.unsafe_get()).local_name.clone()
}
#[inline]
unsafe fn value_for_layout(&self) -> &AttrValue {
(*self.unsafe_get()).value.borrow_for_layout()
}
}
| from_u32 | identifier_name |
simple-lexical-scope.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print x
// gdb-check:$1 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$2 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$3 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$4 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$5 = 10.5
// gdb-command:continue
// gdb-command:print x
// gdb-check:$6 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$7 = false
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print x
// lldbg-check:[...]$0 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$1 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$2 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$3 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$4 = 10.5
// lldbr-check:(f64) x = 10.5
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$5 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$6 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn main() {
let x = false;
zzz(); // #break
sentinel();
{
zzz(); // #break
sentinel();
let x = 10;
zzz(); // #break
sentinel();
{
zzz(); // #break
sentinel();
let x = 10.5f64;
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
fn | () {()}
fn sentinel() {()}
| zzz | identifier_name |
simple-lexical-scope.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print x
// gdb-check:$1 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$2 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$3 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$4 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$5 = 10.5
// gdb-command:continue
// gdb-command:print x
// gdb-check:$6 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$7 = false
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print x
// lldbg-check:[...]$0 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$1 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$2 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$3 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$4 = 10.5
// lldbr-check:(f64) x = 10.5
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$5 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$6 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn main() {
let x = false;
zzz(); // #break
sentinel();
{
zzz(); // #break
sentinel();
let x = 10;
|
{
zzz(); // #break
sentinel();
let x = 10.5f64;
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
fn zzz() {()}
fn sentinel() {()} | zzz(); // #break
sentinel(); | random_line_split |
simple-lexical-scope.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// min-lldb-version: 310
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print x
// gdb-check:$1 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$2 = false
// gdb-command:continue
// gdb-command:print x
// gdb-check:$3 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$4 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$5 = 10.5
// gdb-command:continue
// gdb-command:print x
// gdb-check:$6 = 10
// gdb-command:continue
// gdb-command:print x
// gdb-check:$7 = false
// gdb-command:continue
// === LLDB TESTS ==================================================================================
// lldb-command:run
// lldb-command:print x
// lldbg-check:[...]$0 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$1 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$2 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$3 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$4 = 10.5
// lldbr-check:(f64) x = 10.5
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$5 = 10
// lldbr-check:(i32) x = 10
// lldb-command:continue
// lldb-command:print x
// lldbg-check:[...]$6 = false
// lldbr-check:(bool) x = false
// lldb-command:continue
#![feature(omit_gdb_pretty_printer_section)]
#![omit_gdb_pretty_printer_section]
fn main() {
let x = false;
zzz(); // #break
sentinel();
{
zzz(); // #break
sentinel();
let x = 10;
zzz(); // #break
sentinel();
{
zzz(); // #break
sentinel();
let x = 10.5f64;
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
zzz(); // #break
sentinel();
}
fn zzz() |
fn sentinel() {()}
| {()} | identifier_body |
issue-40001-plugin.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax, plugin, plugin_registrar, rustc_private)]
#![crate_type = "dylib"]
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::attr;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
use rustc::hir;
use rustc::hir::intravisit;
use rustc::hir::map as hir_map;
use hir::Node;
use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext};
use rustc::ty;
use syntax::{ast, source_map};
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_late_lint_pass(box MissingWhitelistedAttrPass);
reg.register_attribute("whitelisted_attr".to_string(), Whitelisted);
}
declare_lint!(MISSING_WHITELISTED_ATTR, Deny,
"Checks for missing `whitelisted_attr` attribute");
struct MissingWhitelistedAttrPass;
impl LintPass for MissingWhitelistedAttrPass {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_WHITELISTED_ATTR)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingWhitelistedAttrPass {
fn check_fn(&mut self,
cx: &LateContext<'a, 'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx hir::FnDecl,
_: &'tcx hir::Body,
span: source_map::Span,
id: ast::NodeId) {
let item = match cx.tcx.hir().get(id) {
Node::Item(item) => item,
_ => cx.tcx.hir().expect_item(cx.tcx.hir().get_parent(id)),
};
if!attr::contains_name(&item.attrs, "whitelisted_attr") |
}
}
| {
cx.span_lint(MISSING_WHITELISTED_ATTR, span,
"Missing 'whitelisted_attr' attribute");
} | conditional_block |
issue-40001-plugin.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax, plugin, plugin_registrar, rustc_private)]
#![crate_type = "dylib"]
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::attr;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
use rustc::hir;
use rustc::hir::intravisit;
use rustc::hir::map as hir_map;
use hir::Node;
use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext};
use rustc::ty;
use syntax::{ast, source_map};
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_late_lint_pass(box MissingWhitelistedAttrPass);
reg.register_attribute("whitelisted_attr".to_string(), Whitelisted);
}
declare_lint!(MISSING_WHITELISTED_ATTR, Deny,
"Checks for missing `whitelisted_attr` attribute");
struct MissingWhitelistedAttrPass;
impl LintPass for MissingWhitelistedAttrPass {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_WHITELISTED_ATTR)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingWhitelistedAttrPass {
fn | (&mut self,
cx: &LateContext<'a, 'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx hir::FnDecl,
_: &'tcx hir::Body,
span: source_map::Span,
id: ast::NodeId) {
let item = match cx.tcx.hir().get(id) {
Node::Item(item) => item,
_ => cx.tcx.hir().expect_item(cx.tcx.hir().get_parent(id)),
};
if!attr::contains_name(&item.attrs, "whitelisted_attr") {
cx.span_lint(MISSING_WHITELISTED_ATTR, span,
"Missing 'whitelisted_attr' attribute");
}
}
}
| check_fn | identifier_name |
issue-40001-plugin.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax, plugin, plugin_registrar, rustc_private)]
#![crate_type = "dylib"]
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::attr;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
use rustc::hir;
use rustc::hir::intravisit;
use rustc::hir::map as hir_map;
use hir::Node;
use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext};
use rustc::ty;
use syntax::{ast, source_map};
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) |
declare_lint!(MISSING_WHITELISTED_ATTR, Deny,
"Checks for missing `whitelisted_attr` attribute");
struct MissingWhitelistedAttrPass;
impl LintPass for MissingWhitelistedAttrPass {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_WHITELISTED_ATTR)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingWhitelistedAttrPass {
fn check_fn(&mut self,
cx: &LateContext<'a, 'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx hir::FnDecl,
_: &'tcx hir::Body,
span: source_map::Span,
id: ast::NodeId) {
let item = match cx.tcx.hir().get(id) {
Node::Item(item) => item,
_ => cx.tcx.hir().expect_item(cx.tcx.hir().get_parent(id)),
};
if!attr::contains_name(&item.attrs, "whitelisted_attr") {
cx.span_lint(MISSING_WHITELISTED_ATTR, span,
"Missing 'whitelisted_attr' attribute");
}
}
}
| {
reg.register_late_lint_pass(box MissingWhitelistedAttrPass);
reg.register_attribute("whitelisted_attr".to_string(), Whitelisted);
} | identifier_body |
issue-40001-plugin.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 | // except according to those terms.
#![feature(box_syntax, plugin, plugin_registrar, rustc_private)]
#![crate_type = "dylib"]
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::attr;
use syntax::ext::base::*;
use syntax::feature_gate::AttributeType::Whitelisted;
use syntax::symbol::Symbol;
use rustc::hir;
use rustc::hir::intravisit;
use rustc::hir::map as hir_map;
use hir::Node;
use rustc::lint::{LateContext, LintPass, LintArray, LateLintPass, LintContext};
use rustc::ty;
use syntax::{ast, source_map};
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_late_lint_pass(box MissingWhitelistedAttrPass);
reg.register_attribute("whitelisted_attr".to_string(), Whitelisted);
}
declare_lint!(MISSING_WHITELISTED_ATTR, Deny,
"Checks for missing `whitelisted_attr` attribute");
struct MissingWhitelistedAttrPass;
impl LintPass for MissingWhitelistedAttrPass {
fn get_lints(&self) -> LintArray {
lint_array!(MISSING_WHITELISTED_ATTR)
}
}
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingWhitelistedAttrPass {
fn check_fn(&mut self,
cx: &LateContext<'a, 'tcx>,
_: intravisit::FnKind<'tcx>,
_: &'tcx hir::FnDecl,
_: &'tcx hir::Body,
span: source_map::Span,
id: ast::NodeId) {
let item = match cx.tcx.hir().get(id) {
Node::Item(item) => item,
_ => cx.tcx.hir().expect_item(cx.tcx.hir().get_parent(id)),
};
if!attr::contains_name(&item.attrs, "whitelisted_attr") {
cx.span_lint(MISSING_WHITELISTED_ATTR, span,
"Missing 'whitelisted_attr' attribute");
}
}
} | // option. This file may not be copied, modified, or distributed | random_line_split |
main.rs | extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate curl;
extern crate inflections;
mod parser;
mod types;
mod writer;
use std::env;
use std::collections::HashMap;
use curl::easy::Easy;
fn main() |
let res = parser::parse(&events).unwrap();
let sections = types::to_sections(res, &mut types);
println!("\n\n\n");
println!("{:?}", sections);
writer::write(path, sections, types).unwrap();
}
fn download(url: &str) -> String {
let mut buf = Vec::new();
{
let mut easy = Easy::new();
easy.url(url).unwrap();
let mut transfer = easy.transfer();
transfer.write_function(|data| {
buf.extend(data);
Ok(data.len())
}).unwrap();
transfer.perform().unwrap();
}
String::from_utf8(buf).unwrap()
}
| {
let mut args = env::args();
let name = args.next().unwrap();
let (version, path) = match (args.next(), args.next()) {
(Some(v), Some(f)) => (v,f),
_ => {
println!("Usage: {} [qemu-version] [export-path]", name);
::std::process::exit(1);
}
};
let schema = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi-schema.json", version));
let events = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi/event.json", version));
let res = parser::parse(&schema).unwrap();
println!("{:?}", res);
let mut types = HashMap::new();
types::to_types(res, &mut types);
println!("\n\n\n");
println!("{:?}", types); | identifier_body |
main.rs | extern crate serde;
extern crate serde_json;
#[macro_use] | extern crate serde_derive;
extern crate curl;
extern crate inflections;
mod parser;
mod types;
mod writer;
use std::env;
use std::collections::HashMap;
use curl::easy::Easy;
fn main() {
let mut args = env::args();
let name = args.next().unwrap();
let (version, path) = match (args.next(), args.next()) {
(Some(v), Some(f)) => (v,f),
_ => {
println!("Usage: {} [qemu-version] [export-path]", name);
::std::process::exit(1);
}
};
let schema = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi-schema.json", version));
let events = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi/event.json", version));
let res = parser::parse(&schema).unwrap();
println!("{:?}", res);
let mut types = HashMap::new();
types::to_types(res, &mut types);
println!("\n\n\n");
println!("{:?}", types);
let res = parser::parse(&events).unwrap();
let sections = types::to_sections(res, &mut types);
println!("\n\n\n");
println!("{:?}", sections);
writer::write(path, sections, types).unwrap();
}
fn download(url: &str) -> String {
let mut buf = Vec::new();
{
let mut easy = Easy::new();
easy.url(url).unwrap();
let mut transfer = easy.transfer();
transfer.write_function(|data| {
buf.extend(data);
Ok(data.len())
}).unwrap();
transfer.perform().unwrap();
}
String::from_utf8(buf).unwrap()
} | random_line_split |
|
main.rs | extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
extern crate curl;
extern crate inflections;
mod parser;
mod types;
mod writer;
use std::env;
use std::collections::HashMap;
use curl::easy::Easy;
fn | () {
let mut args = env::args();
let name = args.next().unwrap();
let (version, path) = match (args.next(), args.next()) {
(Some(v), Some(f)) => (v,f),
_ => {
println!("Usage: {} [qemu-version] [export-path]", name);
::std::process::exit(1);
}
};
let schema = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi-schema.json", version));
let events = download(&format!("https://raw.githubusercontent.com/qemu/qemu/{}/qapi/event.json", version));
let res = parser::parse(&schema).unwrap();
println!("{:?}", res);
let mut types = HashMap::new();
types::to_types(res, &mut types);
println!("\n\n\n");
println!("{:?}", types);
let res = parser::parse(&events).unwrap();
let sections = types::to_sections(res, &mut types);
println!("\n\n\n");
println!("{:?}", sections);
writer::write(path, sections, types).unwrap();
}
fn download(url: &str) -> String {
let mut buf = Vec::new();
{
let mut easy = Easy::new();
easy.url(url).unwrap();
let mut transfer = easy.transfer();
transfer.write_function(|data| {
buf.extend(data);
Ok(data.len())
}).unwrap();
transfer.perform().unwrap();
}
String::from_utf8(buf).unwrap()
}
| main | identifier_name |
stop_guard.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Stop guard mod
use std::sync::Arc;
use std::sync::atomic::*;
/// Stop guard that will set a stop flag on drop
pub struct StopGuard {
flag: Arc<AtomicBool>,
}
impl StopGuard {
/// Create a stop guard
pub fn new() -> StopGuard {
StopGuard {
flag: Arc::new(AtomicBool::new(false))
}
}
/// Share stop guard between the threads
pub fn share(&self) -> Arc<AtomicBool> {
self.flag.clone()
}
}
impl Drop for StopGuard {
fn drop(&mut self) |
}
| {
self.flag.store(true, Ordering::Relaxed)
} | identifier_body |
stop_guard.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Stop guard mod
use std::sync::Arc;
use std::sync::atomic::*;
/// Stop guard that will set a stop flag on drop
pub struct | {
flag: Arc<AtomicBool>,
}
impl StopGuard {
/// Create a stop guard
pub fn new() -> StopGuard {
StopGuard {
flag: Arc::new(AtomicBool::new(false))
}
}
/// Share stop guard between the threads
pub fn share(&self) -> Arc<AtomicBool> {
self.flag.clone()
}
}
impl Drop for StopGuard {
fn drop(&mut self) {
self.flag.store(true, Ordering::Relaxed)
}
}
| StopGuard | identifier_name |
stop_guard.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//! Stop guard mod |
use std::sync::Arc;
use std::sync::atomic::*;
/// Stop guard that will set a stop flag on drop
pub struct StopGuard {
flag: Arc<AtomicBool>,
}
impl StopGuard {
/// Create a stop guard
pub fn new() -> StopGuard {
StopGuard {
flag: Arc::new(AtomicBool::new(false))
}
}
/// Share stop guard between the threads
pub fn share(&self) -> Arc<AtomicBool> {
self.flag.clone()
}
}
impl Drop for StopGuard {
fn drop(&mut self) {
self.flag.store(true, Ordering::Relaxed)
}
} | random_line_split |
|
helm.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::ffi::OsString;
use common::ui::UI;
use error::Result;
const EXPORT_CMD: &'static str = "hab-pkg-export-helm";
const EXPORT_CMD_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_BINARY";
const EXPORT_PKG_IDENT: &'static str = "core/hab-pkg-export-helm";
const EXPORT_PKG_IDENT_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_PKG_IDENT";
pub fn | (ui: &mut UI, args: Vec<OsString>) -> Result<()> {
::command::pkg::export::export_common::start(
ui,
args,
EXPORT_CMD,
EXPORT_CMD_ENVVAR,
EXPORT_PKG_IDENT,
EXPORT_PKG_IDENT_ENVVAR,
)
}
| start | identifier_name |
helm.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::ffi::OsString;
use common::ui::UI;
use error::Result;
| pub fn start(ui: &mut UI, args: Vec<OsString>) -> Result<()> {
::command::pkg::export::export_common::start(
ui,
args,
EXPORT_CMD,
EXPORT_CMD_ENVVAR,
EXPORT_PKG_IDENT,
EXPORT_PKG_IDENT_ENVVAR,
)
} | const EXPORT_CMD: &'static str = "hab-pkg-export-helm";
const EXPORT_CMD_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_BINARY";
const EXPORT_PKG_IDENT: &'static str = "core/hab-pkg-export-helm";
const EXPORT_PKG_IDENT_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_PKG_IDENT";
| random_line_split |
helm.rs | // Copyright (c) 2017 Chef Software Inc. and/or applicable contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::ffi::OsString;
use common::ui::UI;
use error::Result;
const EXPORT_CMD: &'static str = "hab-pkg-export-helm";
const EXPORT_CMD_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_BINARY";
const EXPORT_PKG_IDENT: &'static str = "core/hab-pkg-export-helm";
const EXPORT_PKG_IDENT_ENVVAR: &'static str = "HAB_PKG_EXPORT_HELM_PKG_IDENT";
pub fn start(ui: &mut UI, args: Vec<OsString>) -> Result<()> | {
::command::pkg::export::export_common::start(
ui,
args,
EXPORT_CMD,
EXPORT_CMD_ENVVAR,
EXPORT_PKG_IDENT,
EXPORT_PKG_IDENT_ENVVAR,
)
} | identifier_body |
|
mona.rs | extern crate mon_artist;
use mon_artist::render::svg::{SvgRender};
use mon_artist::render::{RenderS};
use mon_artist::grid::{Grid, ParseError};
use mon_artist::{SceneOpts};
use std::convert::From;
use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Write};
fn main() {
let mut args = env::args();
args.next(); // skip program name
loop {
let table = if let Some(arg) = args.next() { arg } else { break; };
let in_file = if let Some(arg) = args.next() { arg } else { break; };
let out_file = if let Some(arg) = args.next() { arg } else { break; };
println!("processing {} to {} via {}", in_file, out_file, table);
process(&table, &in_file, &out_file).unwrap();
}
// describe_table();
}
#[allow(dead_code)]
fn describe_table() {
use mon_artist::format::{Table, Neighbor};
let t: Table = Default::default();
let mut may_both_count = 0;
let mut may_start_count = 0;
let mut may_end_count = 0;
let mut neither_count = 0;
for (j, e) in t.entries().enumerate() {
println!("{} {:?}", j+1, e);
match (&e.incoming(), &e.outgoing()) {
(&Neighbor::May(..), &Neighbor::May(..)) => may_both_count += 1,
(&Neighbor::May(..), _) => may_start_count += 1,
(_, &Neighbor::May(..)) => may_end_count += 1,
_ => neither_count += 1,
}
}
println!("");
println!("both: {} may_start: {} may_end: {} neither: {}",
may_both_count, may_start_count, may_end_count, neither_count);
}
#[derive(Debug)]
enum Error { | Parse(ParseError),
}
impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::IO(e) } }
impl From<ParseError> for Error { fn from(e: ParseError) -> Self { Error::Parse(e) } }
use mon_artist::format::Table;
fn get_table(table: &str) -> Table {
match File::open(table) {
Ok(input) => Table::from_lines(BufReader::new(input).lines()),
Err(err) => match table {
"default" => Table::default(),
"demo" => Table::demo(),
_ => panic!("Unknown table name: {}, file err: {:?}", table, err),
},
}
}
fn process(table: &str, in_file: &str, out_file: &str) -> Result<(), Error> {
let mut input = File::open(in_file)?;
let mut content = String::new();
input.read_to_string(&mut content)?;
let table = get_table(table);
let s = content.parse::<Grid>()?.into_scene(
&table,
Some(SceneOpts { text_infer_id: false,..Default::default() }));
let r = SvgRender {
x_scale: 8, y_scale: 13,
font_family: "monospace".to_string(), font_size: 13,
show_gridlines: false,
infer_rect_elements: false,
name: in_file.to_string(),
format_table: table,
};
let svg = r.render_s(&s);
let mut output = File::create(out_file)?;
Ok(write!(&mut output, "{}", svg)?)
} | IO(io::Error), | random_line_split |
mona.rs | extern crate mon_artist;
use mon_artist::render::svg::{SvgRender};
use mon_artist::render::{RenderS};
use mon_artist::grid::{Grid, ParseError};
use mon_artist::{SceneOpts};
use std::convert::From;
use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Write};
fn main() {
let mut args = env::args();
args.next(); // skip program name
loop {
let table = if let Some(arg) = args.next() { arg } else { break; };
let in_file = if let Some(arg) = args.next() { arg } else { break; };
let out_file = if let Some(arg) = args.next() { arg } else { break; };
println!("processing {} to {} via {}", in_file, out_file, table);
process(&table, &in_file, &out_file).unwrap();
}
// describe_table();
}
#[allow(dead_code)]
fn describe_table() {
use mon_artist::format::{Table, Neighbor};
let t: Table = Default::default();
let mut may_both_count = 0;
let mut may_start_count = 0;
let mut may_end_count = 0;
let mut neither_count = 0;
for (j, e) in t.entries().enumerate() {
println!("{} {:?}", j+1, e);
match (&e.incoming(), &e.outgoing()) {
(&Neighbor::May(..), &Neighbor::May(..)) => may_both_count += 1,
(&Neighbor::May(..), _) => may_start_count += 1,
(_, &Neighbor::May(..)) => may_end_count += 1,
_ => neither_count += 1,
}
}
println!("");
println!("both: {} may_start: {} may_end: {} neither: {}",
may_both_count, may_start_count, may_end_count, neither_count);
}
#[derive(Debug)]
enum Error {
IO(io::Error),
Parse(ParseError),
}
impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::IO(e) } }
impl From<ParseError> for Error { fn from(e: ParseError) -> Self { Error::Parse(e) } }
use mon_artist::format::Table;
fn | (table: &str) -> Table {
match File::open(table) {
Ok(input) => Table::from_lines(BufReader::new(input).lines()),
Err(err) => match table {
"default" => Table::default(),
"demo" => Table::demo(),
_ => panic!("Unknown table name: {}, file err: {:?}", table, err),
},
}
}
fn process(table: &str, in_file: &str, out_file: &str) -> Result<(), Error> {
let mut input = File::open(in_file)?;
let mut content = String::new();
input.read_to_string(&mut content)?;
let table = get_table(table);
let s = content.parse::<Grid>()?.into_scene(
&table,
Some(SceneOpts { text_infer_id: false,..Default::default() }));
let r = SvgRender {
x_scale: 8, y_scale: 13,
font_family: "monospace".to_string(), font_size: 13,
show_gridlines: false,
infer_rect_elements: false,
name: in_file.to_string(),
format_table: table,
};
let svg = r.render_s(&s);
let mut output = File::create(out_file)?;
Ok(write!(&mut output, "{}", svg)?)
}
| get_table | identifier_name |
mona.rs | extern crate mon_artist;
use mon_artist::render::svg::{SvgRender};
use mon_artist::render::{RenderS};
use mon_artist::grid::{Grid, ParseError};
use mon_artist::{SceneOpts};
use std::convert::From;
use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Write};
fn main() {
let mut args = env::args();
args.next(); // skip program name
loop {
let table = if let Some(arg) = args.next() | else { break; };
let in_file = if let Some(arg) = args.next() { arg } else { break; };
let out_file = if let Some(arg) = args.next() { arg } else { break; };
println!("processing {} to {} via {}", in_file, out_file, table);
process(&table, &in_file, &out_file).unwrap();
}
// describe_table();
}
#[allow(dead_code)]
fn describe_table() {
use mon_artist::format::{Table, Neighbor};
let t: Table = Default::default();
let mut may_both_count = 0;
let mut may_start_count = 0;
let mut may_end_count = 0;
let mut neither_count = 0;
for (j, e) in t.entries().enumerate() {
println!("{} {:?}", j+1, e);
match (&e.incoming(), &e.outgoing()) {
(&Neighbor::May(..), &Neighbor::May(..)) => may_both_count += 1,
(&Neighbor::May(..), _) => may_start_count += 1,
(_, &Neighbor::May(..)) => may_end_count += 1,
_ => neither_count += 1,
}
}
println!("");
println!("both: {} may_start: {} may_end: {} neither: {}",
may_both_count, may_start_count, may_end_count, neither_count);
}
#[derive(Debug)]
enum Error {
IO(io::Error),
Parse(ParseError),
}
impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::IO(e) } }
impl From<ParseError> for Error { fn from(e: ParseError) -> Self { Error::Parse(e) } }
use mon_artist::format::Table;
fn get_table(table: &str) -> Table {
match File::open(table) {
Ok(input) => Table::from_lines(BufReader::new(input).lines()),
Err(err) => match table {
"default" => Table::default(),
"demo" => Table::demo(),
_ => panic!("Unknown table name: {}, file err: {:?}", table, err),
},
}
}
fn process(table: &str, in_file: &str, out_file: &str) -> Result<(), Error> {
let mut input = File::open(in_file)?;
let mut content = String::new();
input.read_to_string(&mut content)?;
let table = get_table(table);
let s = content.parse::<Grid>()?.into_scene(
&table,
Some(SceneOpts { text_infer_id: false,..Default::default() }));
let r = SvgRender {
x_scale: 8, y_scale: 13,
font_family: "monospace".to_string(), font_size: 13,
show_gridlines: false,
infer_rect_elements: false,
name: in_file.to_string(),
format_table: table,
};
let svg = r.render_s(&s);
let mut output = File::create(out_file)?;
Ok(write!(&mut output, "{}", svg)?)
}
| { arg } | conditional_block |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use regex::Regex;
use toml::Value;
use store::Result;
use store::Header;
use error::StoreErrorKind as SEK;
use error::StoreError as SE;
#[cfg(feature = "early-panic")]
#[macro_export]
macro_rules! if_cfg_panic {
() => { panic!() };
($msg:expr) => { panic!($msg) };
($fmt:expr, $($arg:tt)+) => { panic!($fmt, $($arg),+) };
}
#[cfg(not(feature = "early-panic"))]
#[macro_export]
macro_rules! if_cfg_panic {
() => { };
($msg:expr) => { };
($fmt:expr, $($arg:tt)+) => { };
}
pub fn entry_buffer_to_header_content(buf: &str) -> Result<(Value, String)> {
debug!("Building entry from string");
lazy_static! {
static ref RE: Regex = Regex::new(r"(?smx)
^---$
(?P<header>.*) # Header
^---$\n
(?P<content>.*) # Content
").unwrap();
}
let matches = match RE.captures(buf) {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s,
};
let header = match matches.name("header") {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s
}; | let content = matches.name("content").map(|r| r.as_str()).unwrap_or("");
Ok((Value::parse(header.as_str())?, String::from(content)))
} | random_line_split |
|
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use regex::Regex;
use toml::Value;
use store::Result;
use store::Header;
use error::StoreErrorKind as SEK;
use error::StoreError as SE;
#[cfg(feature = "early-panic")]
#[macro_export]
macro_rules! if_cfg_panic {
() => { panic!() };
($msg:expr) => { panic!($msg) };
($fmt:expr, $($arg:tt)+) => { panic!($fmt, $($arg),+) };
}
#[cfg(not(feature = "early-panic"))]
#[macro_export]
macro_rules! if_cfg_panic {
() => { };
($msg:expr) => { };
($fmt:expr, $($arg:tt)+) => { };
}
pub fn | (buf: &str) -> Result<(Value, String)> {
debug!("Building entry from string");
lazy_static! {
static ref RE: Regex = Regex::new(r"(?smx)
^---$
(?P<header>.*) # Header
^---$\n
(?P<content>.*) # Content
").unwrap();
}
let matches = match RE.captures(buf) {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s,
};
let header = match matches.name("header") {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s
};
let content = matches.name("content").map(|r| r.as_str()).unwrap_or("");
Ok((Value::parse(header.as_str())?, String::from(content)))
}
| entry_buffer_to_header_content | identifier_name |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <[email protected]> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use regex::Regex;
use toml::Value;
use store::Result;
use store::Header;
use error::StoreErrorKind as SEK;
use error::StoreError as SE;
#[cfg(feature = "early-panic")]
#[macro_export]
macro_rules! if_cfg_panic {
() => { panic!() };
($msg:expr) => { panic!($msg) };
($fmt:expr, $($arg:tt)+) => { panic!($fmt, $($arg),+) };
}
#[cfg(not(feature = "early-panic"))]
#[macro_export]
macro_rules! if_cfg_panic {
() => { };
($msg:expr) => { };
($fmt:expr, $($arg:tt)+) => { };
}
pub fn entry_buffer_to_header_content(buf: &str) -> Result<(Value, String)> |
let content = matches.name("content").map(|r| r.as_str()).unwrap_or("");
Ok((Value::parse(header.as_str())?, String::from(content)))
}
| {
debug!("Building entry from string");
lazy_static! {
static ref RE: Regex = Regex::new(r"(?smx)
^---$
(?P<header>.*) # Header
^---$\n
(?P<content>.*) # Content
").unwrap();
}
let matches = match RE.captures(buf) {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s,
};
let header = match matches.name("header") {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s
}; | identifier_body |
lib.rs | /*
* Exopticon - A free video surveillance system.
* Copyright (C) 2020 David Matthew Mattli <[email protected]>
*
* This file is part of Exopticon.
*
* Exopticon is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Exopticon is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Exopticon. If not, see <http://www.gnu.org/licenses/>.
*/
use std::convert::TryFrom;
use std::ffi::CStr;
use std::io::{self, Write};
use std::slice;
//
use bincode::serialize;
use libc::c_char;
use crate::models::{CaptureMessage, FrameMessage};
pub mod models;
pub fn print_message(message: CaptureMessage) {
let serialized = serialize(&message).expect("Unable to serialize message!");
let stdout = io::stdout();
let mut handle = stdout.lock();
// write length of message as big-endian u32 for framing
let message_length = u32::try_from(serialized.len()).expect("Framed message too large!");
let message_length_be = message_length.to_be_bytes();
handle
.write_all(&message_length_be)
.expect("unable to write frame length!");
// Write message
handle
.write_all(serialized.as_slice())
.expect("unable to write frame!");
}
/// Take FrameMessage struct and write a framed message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_frame_message(frame: *const FrameMessage) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::Frame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Take FrameMessage struct and write a framed scaled, message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_scaled_frame_message(frame: *const FrameMessage, _height: i32) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::ScaledFrame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Send a message signaling a new file was created.
///
/// # Safety
///
/// filename and iso_begin_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_new_file_message(
filename: *const c_char,
iso_begin_time: *const c_char,
) {
let filename = {
assert!(!filename.is_null()); | let iso_begin_time = {
assert!(!iso_begin_time.is_null());
CStr::from_ptr(iso_begin_time)
.to_string_lossy()
.into_owned()
};
let message = CaptureMessage::NewFile {
filename,
begin_time: iso_begin_time,
};
print_message(message);
}
/// Send a message signaling the closing of a file.
///
/// # Safety
///
/// filename and iso_end_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_end_file_message(
filename: *const c_char,
iso_end_time: *const c_char,
) {
let filename = {
assert!(!filename.is_null());
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
let iso_end_time = {
assert!(!iso_end_time.is_null());
CStr::from_ptr(iso_end_time).to_string_lossy().into_owned()
};
let message = CaptureMessage::EndFile {
filename,
end_time: iso_end_time,
};
print_message(message);
}
/// Send a log message
///
/// # Safety
///
/// message must be a null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_log_message(_level: i32, message: *const c_char) {
let message = {
assert!(!message.is_null());
CStr::from_ptr(message).to_string_lossy().into_owned()
};
let capture_message = CaptureMessage::Log { message };
print_message(capture_message);
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
} |
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
| random_line_split |
lib.rs | /*
* Exopticon - A free video surveillance system.
* Copyright (C) 2020 David Matthew Mattli <[email protected]>
*
* This file is part of Exopticon.
*
* Exopticon is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Exopticon is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Exopticon. If not, see <http://www.gnu.org/licenses/>.
*/
use std::convert::TryFrom;
use std::ffi::CStr;
use std::io::{self, Write};
use std::slice;
//
use bincode::serialize;
use libc::c_char;
use crate::models::{CaptureMessage, FrameMessage};
pub mod models;
pub fn print_message(message: CaptureMessage) {
let serialized = serialize(&message).expect("Unable to serialize message!");
let stdout = io::stdout();
let mut handle = stdout.lock();
// write length of message as big-endian u32 for framing
let message_length = u32::try_from(serialized.len()).expect("Framed message too large!");
let message_length_be = message_length.to_be_bytes();
handle
.write_all(&message_length_be)
.expect("unable to write frame length!");
// Write message
handle
.write_all(serialized.as_slice())
.expect("unable to write frame!");
}
/// Take FrameMessage struct and write a framed message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_frame_message(frame: *const FrameMessage) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::Frame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Take FrameMessage struct and write a framed scaled, message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_scaled_frame_message(frame: *const FrameMessage, _height: i32) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::ScaledFrame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Send a message signaling a new file was created.
///
/// # Safety
///
/// filename and iso_begin_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_new_file_message(
filename: *const c_char,
iso_begin_time: *const c_char,
) | print_message(message);
}
/// Send a message signaling the closing of a file.
///
/// # Safety
///
/// filename and iso_end_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_end_file_message(
filename: *const c_char,
iso_end_time: *const c_char,
) {
let filename = {
assert!(!filename.is_null());
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
let iso_end_time = {
assert!(!iso_end_time.is_null());
CStr::from_ptr(iso_end_time).to_string_lossy().into_owned()
};
let message = CaptureMessage::EndFile {
filename,
end_time: iso_end_time,
};
print_message(message);
}
/// Send a log message
///
/// # Safety
///
/// message must be a null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_log_message(_level: i32, message: *const c_char) {
let message = {
assert!(!message.is_null());
CStr::from_ptr(message).to_string_lossy().into_owned()
};
let capture_message = CaptureMessage::Log { message };
print_message(capture_message);
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
| {
let filename = {
assert!(!filename.is_null());
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
let iso_begin_time = {
assert!(!iso_begin_time.is_null());
CStr::from_ptr(iso_begin_time)
.to_string_lossy()
.into_owned()
};
let message = CaptureMessage::NewFile {
filename,
begin_time: iso_begin_time,
};
| identifier_body |
lib.rs | /*
* Exopticon - A free video surveillance system.
* Copyright (C) 2020 David Matthew Mattli <[email protected]>
*
* This file is part of Exopticon.
*
* Exopticon is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Exopticon is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Exopticon. If not, see <http://www.gnu.org/licenses/>.
*/
use std::convert::TryFrom;
use std::ffi::CStr;
use std::io::{self, Write};
use std::slice;
//
use bincode::serialize;
use libc::c_char;
use crate::models::{CaptureMessage, FrameMessage};
pub mod models;
pub fn print_message(message: CaptureMessage) {
let serialized = serialize(&message).expect("Unable to serialize message!");
let stdout = io::stdout();
let mut handle = stdout.lock();
// write length of message as big-endian u32 for framing
let message_length = u32::try_from(serialized.len()).expect("Framed message too large!");
let message_length_be = message_length.to_be_bytes();
handle
.write_all(&message_length_be)
.expect("unable to write frame length!");
// Write message
handle
.write_all(serialized.as_slice())
.expect("unable to write frame!");
}
/// Take FrameMessage struct and write a framed message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_frame_message(frame: *const FrameMessage) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::Frame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Take FrameMessage struct and write a framed scaled, message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_scaled_frame_message(frame: *const FrameMessage, _height: i32) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::ScaledFrame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Send a message signaling a new file was created.
///
/// # Safety
///
/// filename and iso_begin_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_new_file_message(
filename: *const c_char,
iso_begin_time: *const c_char,
) {
let filename = {
assert!(!filename.is_null());
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
let iso_begin_time = {
assert!(!iso_begin_time.is_null());
CStr::from_ptr(iso_begin_time)
.to_string_lossy()
.into_owned()
};
let message = CaptureMessage::NewFile {
filename,
begin_time: iso_begin_time,
};
print_message(message);
}
/// Send a message signaling the closing of a file.
///
/// # Safety
///
/// filename and iso_end_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_end_file_message(
filename: *const c_char,
iso_end_time: *const c_char,
) {
let filename = {
assert!(!filename.is_null());
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
let iso_end_time = {
assert!(!iso_end_time.is_null());
CStr::from_ptr(iso_end_time).to_string_lossy().into_owned()
};
let message = CaptureMessage::EndFile {
filename,
end_time: iso_end_time,
};
print_message(message);
}
/// Send a log message
///
/// # Safety
///
/// message must be a null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn | (_level: i32, message: *const c_char) {
let message = {
assert!(!message.is_null());
CStr::from_ptr(message).to_string_lossy().into_owned()
};
let capture_message = CaptureMessage::Log { message };
print_message(capture_message);
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
| send_log_message | identifier_name |
lib.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.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn | (bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
| deflate_bytes_internal | identifier_name |
lib.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.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() | else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
| {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} | conditional_block |
lib.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.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal" | fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
} | static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
| random_line_split |
lib.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.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if!res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> |
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
| {
inflate_bytes_internal(bytes, 0)
} | identifier_body |
mutable.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::*;
pub trait SyncMutable {
fn put(&self, key: &[u8], value: &[u8]) -> Result<()>;
fn put_cf(&self, cf: &str, key: &[u8], value: &[u8]) -> Result<()>;
fn delete(&self, key: &[u8]) -> Result<()>;
fn delete_cf(&self, cf: &str, key: &[u8]) -> Result<()>;
fn delete_range_cf(&self, cf: &str, begin_key: &[u8], end_key: &[u8]) -> Result<()>;
fn put_msg<M: protobuf::Message>(&self, key: &[u8], m: &M) -> Result<()> {
self.put(key, &m.write_to_bytes()?)
}
fn put_msg_cf<M: protobuf::Message>(&self, cf: &str, key: &[u8], m: &M) -> Result<()> |
}
| {
self.put_cf(cf, key, &m.write_to_bytes()?)
} | identifier_body |
mutable.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::*;
pub trait SyncMutable {
fn put(&self, key: &[u8], value: &[u8]) -> Result<()>;
fn put_cf(&self, cf: &str, key: &[u8], value: &[u8]) -> Result<()>;
fn delete(&self, key: &[u8]) -> Result<()>;
fn delete_cf(&self, cf: &str, key: &[u8]) -> Result<()>;
fn delete_range_cf(&self, cf: &str, begin_key: &[u8], end_key: &[u8]) -> Result<()>;
fn | <M: protobuf::Message>(&self, key: &[u8], m: &M) -> Result<()> {
self.put(key, &m.write_to_bytes()?)
}
fn put_msg_cf<M: protobuf::Message>(&self, cf: &str, key: &[u8], m: &M) -> Result<()> {
self.put_cf(cf, key, &m.write_to_bytes()?)
}
}
| put_msg | identifier_name |
mutable.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::*;
pub trait SyncMutable {
fn put(&self, key: &[u8], value: &[u8]) -> Result<()>;
fn put_cf(&self, cf: &str, key: &[u8], value: &[u8]) -> Result<()>;
fn delete(&self, key: &[u8]) -> Result<()>;
fn delete_cf(&self, cf: &str, key: &[u8]) -> Result<()>;
fn delete_range_cf(&self, cf: &str, begin_key: &[u8], end_key: &[u8]) -> Result<()>;
| }
fn put_msg_cf<M: protobuf::Message>(&self, cf: &str, key: &[u8], m: &M) -> Result<()> {
self.put_cf(cf, key, &m.write_to_bytes()?)
}
} | fn put_msg<M: protobuf::Message>(&self, key: &[u8], m: &M) -> Result<()> {
self.put(key, &m.write_to_bytes()?) | random_line_split |
elf_arch-i386.rs | pub const ELF_CLASS: u8 = 1;
pub type ElfAddr = u32;
pub type ElfHalf = u16;
pub type ElfOff = u32;
pub type ElfWord = u32;
/// An ELF header
#[repr(packed)]
pub struct ElfHeader {
/// The "magic number" (4 bytes)
pub magic: [u8; 4],
/// 64 or 32 bit?
pub class: u8,
/// Little (1) or big endianness (2)?
pub endian: u8,
/// The ELF version (set to 1 for default)
pub ver: u8,
/// Operating system ABI (0x03 for Linux)
pub abi: [u8; 2],
/// Unused
pub pad: [u8; 7],
/// Specify whether the object is relocatable, executable, shared, or core (in order).
pub _type: ElfHalf,
/// Instruction set archcitecture
pub machine: ElfHalf, | pub ver_2: ElfWord,
/// The ELF entry
pub entry: ElfAddr,
/// The program header table offset
pub ph_off: ElfOff,
/// The section header table offset
pub sh_off: ElfOff,
/// The flags set
pub flags: ElfWord,
/// The header table length
pub h_len: ElfHalf,
/// The program header table entry length
pub ph_ent_len: ElfHalf,
/// The program head table length
pub ph_len: ElfHalf,
/// The section header table entry length
pub sh_ent_len: ElfHalf,
/// The section header table length
pub sh_len: ElfHalf,
/// The section header table string index
pub sh_str_index: ElfHalf,
}
/// An ELF segment
#[repr(packed)]
pub struct ElfSegment {
pub _type: ElfWord,
pub off: ElfOff,
pub vaddr: ElfAddr,
pub paddr: ElfAddr,
pub file_len: ElfWord,
pub mem_len: ElfWord,
pub flags: ElfWord,
pub align: ElfWord,
}
/// An ELF section
#[repr(packed)]
pub struct ElfSection {
pub name: ElfWord,
pub _type: ElfWord,
pub flags: ElfWord,
pub addr: ElfAddr,
pub off: ElfOff,
pub len: ElfWord,
pub link: ElfWord,
pub info: ElfWord,
pub addr_align: ElfWord,
pub ent_len: ElfWord,
}
/// An ELF symbol
#[repr(packed)]
pub struct ElfSymbol {
pub name: ElfWord,
pub value: ElfAddr,
pub size: ElfWord,
pub info: u8,
pub other: u8,
pub sh_index: ElfHalf,
} | /// Second version | random_line_split |
elf_arch-i386.rs | pub const ELF_CLASS: u8 = 1;
pub type ElfAddr = u32;
pub type ElfHalf = u16;
pub type ElfOff = u32;
pub type ElfWord = u32;
/// An ELF header
#[repr(packed)]
pub struct ElfHeader {
/// The "magic number" (4 bytes)
pub magic: [u8; 4],
/// 64 or 32 bit?
pub class: u8,
/// Little (1) or big endianness (2)?
pub endian: u8,
/// The ELF version (set to 1 for default)
pub ver: u8,
/// Operating system ABI (0x03 for Linux)
pub abi: [u8; 2],
/// Unused
pub pad: [u8; 7],
/// Specify whether the object is relocatable, executable, shared, or core (in order).
pub _type: ElfHalf,
/// Instruction set archcitecture
pub machine: ElfHalf,
/// Second version
pub ver_2: ElfWord,
/// The ELF entry
pub entry: ElfAddr,
/// The program header table offset
pub ph_off: ElfOff,
/// The section header table offset
pub sh_off: ElfOff,
/// The flags set
pub flags: ElfWord,
/// The header table length
pub h_len: ElfHalf,
/// The program header table entry length
pub ph_ent_len: ElfHalf,
/// The program head table length
pub ph_len: ElfHalf,
/// The section header table entry length
pub sh_ent_len: ElfHalf,
/// The section header table length
pub sh_len: ElfHalf,
/// The section header table string index
pub sh_str_index: ElfHalf,
}
/// An ELF segment
#[repr(packed)]
pub struct | {
pub _type: ElfWord,
pub off: ElfOff,
pub vaddr: ElfAddr,
pub paddr: ElfAddr,
pub file_len: ElfWord,
pub mem_len: ElfWord,
pub flags: ElfWord,
pub align: ElfWord,
}
/// An ELF section
#[repr(packed)]
pub struct ElfSection {
pub name: ElfWord,
pub _type: ElfWord,
pub flags: ElfWord,
pub addr: ElfAddr,
pub off: ElfOff,
pub len: ElfWord,
pub link: ElfWord,
pub info: ElfWord,
pub addr_align: ElfWord,
pub ent_len: ElfWord,
}
/// An ELF symbol
#[repr(packed)]
pub struct ElfSymbol {
pub name: ElfWord,
pub value: ElfAddr,
pub size: ElfWord,
pub info: u8,
pub other: u8,
pub sh_index: ElfHalf,
}
| ElfSegment | identifier_name |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
#[derive(Clone, PartialEq, Debug)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
pub tag: String
}
impl Display for EntityTag {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
try!(write!(fmt, "{}", "W/"));
}
write!(fmt, "{}", self.tag)
}
}
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool {
for c in slice.bytes() {
match c {
b'\x21' | b'\x23'... b'\x7e' | b'\x80'... b'\xff' => (),
_ => { return false; }
}
}
true
}
impl FromStr for EntityTag {
type Err = ();
fn from_str(s: &str) -> Result<EntityTag, ()> {
let length: usize = s.len();
let slice = &s[];
// Early exits:
// 1. The string is empty, or,
// 2. it doesn't terminate in a DQUOTE.
if slice.is_empty() ||!slice.ends_with("\"") |
// The etag is weak if its first char is not a DQUOTE.
if slice.char_at(0) == '"' /* '"' */ {
// No need to check if the last char is a DQUOTE,
// we already did that above.
if check_slice_validity(slice.slice_chars(1, length-1)) {
return Ok(EntityTag {
weak: false,
tag: slice.slice_chars(1, length-1).to_string()
});
} else {
return Err(());
}
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1).to_string()
});
} else {
return Err(());
}
}
Err(())
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_successes() {
// Expected successes
let mut etag : EntityTag = "\"foobar\"".parse().unwrap();
assert_eq!(etag, (EntityTag {
weak: false,
tag: "foobar".to_string()
}));
etag = "\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: false,
tag: "".to_string()
});
etag = "W/\"weak-etag\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "weak-etag".to_string()
});
etag = "W/\"\x65\x62\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "\u{0065}\u{0062}".to_string()
});
etag = "W/\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "".to_string()
});
}
#[test]
fn test_etag_failures() {
// Expected failures
let mut etag: Result<EntityTag,()>;
etag = "no-dquotes".parse();
assert_eq!(etag, Err(()));
etag = "w/\"the-first-w-is-case-sensitive\"".parse();
assert_eq!(etag, Err(()));
etag = "".parse();
assert_eq!(etag, Err(()));
etag = "\"unmatched-dquotes1".parse();
assert_eq!(etag, Err(()));
etag = "unmatched-dquotes2\"".parse();
assert_eq!(etag, Err(()));
etag = "matched-\"dquotes\"".parse();
assert_eq!(etag, Err(()));
}
}
| {
return Err(());
} | conditional_block |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
#[derive(Clone, PartialEq, Debug)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
pub tag: String
}
impl Display for EntityTag {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
try!(write!(fmt, "{}", "W/"));
}
write!(fmt, "{}", self.tag)
}
}
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool {
for c in slice.bytes() {
match c {
b'\x21' | b'\x23'... b'\x7e' | b'\x80'... b'\xff' => (),
_ => { return false; }
}
}
true
}
impl FromStr for EntityTag {
type Err = ();
fn from_str(s: &str) -> Result<EntityTag, ()> {
let length: usize = s.len();
let slice = &s[];
// Early exits:
// 1. The string is empty, or,
// 2. it doesn't terminate in a DQUOTE.
if slice.is_empty() ||!slice.ends_with("\"") {
return Err(());
}
// The etag is weak if its first char is not a DQUOTE.
if slice.char_at(0) == '"' /* '"' */ {
// No need to check if the last char is a DQUOTE,
// we already did that above.
if check_slice_validity(slice.slice_chars(1, length-1)) {
return Ok(EntityTag {
weak: false,
tag: slice.slice_chars(1, length-1).to_string()
});
} else {
return Err(());
}
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1).to_string()
});
} else {
return Err(());
}
}
Err(())
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn | () {
// Expected successes
let mut etag : EntityTag = "\"foobar\"".parse().unwrap();
assert_eq!(etag, (EntityTag {
weak: false,
tag: "foobar".to_string()
}));
etag = "\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: false,
tag: "".to_string()
});
etag = "W/\"weak-etag\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "weak-etag".to_string()
});
etag = "W/\"\x65\x62\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "\u{0065}\u{0062}".to_string()
});
etag = "W/\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "".to_string()
});
}
#[test]
fn test_etag_failures() {
// Expected failures
let mut etag: Result<EntityTag,()>;
etag = "no-dquotes".parse();
assert_eq!(etag, Err(()));
etag = "w/\"the-first-w-is-case-sensitive\"".parse();
assert_eq!(etag, Err(()));
etag = "".parse();
assert_eq!(etag, Err(()));
etag = "\"unmatched-dquotes1".parse();
assert_eq!(etag, Err(()));
etag = "unmatched-dquotes2\"".parse();
assert_eq!(etag, Err(()));
etag = "matched-\"dquotes\"".parse();
assert_eq!(etag, Err(()));
}
}
| test_etag_successes | identifier_name |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
#[derive(Clone, PartialEq, Debug)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
pub tag: String
}
impl Display for EntityTag {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
try!(write!(fmt, "{}", "W/"));
}
write!(fmt, "{}", self.tag)
}
}
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool |
impl FromStr for EntityTag {
type Err = ();
fn from_str(s: &str) -> Result<EntityTag, ()> {
let length: usize = s.len();
let slice = &s[];
// Early exits:
// 1. The string is empty, or,
// 2. it doesn't terminate in a DQUOTE.
if slice.is_empty() ||!slice.ends_with("\"") {
return Err(());
}
// The etag is weak if its first char is not a DQUOTE.
if slice.char_at(0) == '"' /* '"' */ {
// No need to check if the last char is a DQUOTE,
// we already did that above.
if check_slice_validity(slice.slice_chars(1, length-1)) {
return Ok(EntityTag {
weak: false,
tag: slice.slice_chars(1, length-1).to_string()
});
} else {
return Err(());
}
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1).to_string()
});
} else {
return Err(());
}
}
Err(())
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_successes() {
// Expected successes
let mut etag : EntityTag = "\"foobar\"".parse().unwrap();
assert_eq!(etag, (EntityTag {
weak: false,
tag: "foobar".to_string()
}));
etag = "\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: false,
tag: "".to_string()
});
etag = "W/\"weak-etag\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "weak-etag".to_string()
});
etag = "W/\"\x65\x62\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "\u{0065}\u{0062}".to_string()
});
etag = "W/\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "".to_string()
});
}
#[test]
fn test_etag_failures() {
// Expected failures
let mut etag: Result<EntityTag,()>;
etag = "no-dquotes".parse();
assert_eq!(etag, Err(()));
etag = "w/\"the-first-w-is-case-sensitive\"".parse();
assert_eq!(etag, Err(()));
etag = "".parse();
assert_eq!(etag, Err(()));
etag = "\"unmatched-dquotes1".parse();
assert_eq!(etag, Err(()));
etag = "unmatched-dquotes2\"".parse();
assert_eq!(etag, Err(()));
etag = "matched-\"dquotes\"".parse();
assert_eq!(etag, Err(()));
}
}
| {
for c in slice.bytes() {
match c {
b'\x21' | b'\x23' ... b'\x7e' | b'\x80' ... b'\xff' => (),
_ => { return false; }
}
}
true
} | identifier_body |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
#[derive(Clone, PartialEq, Debug)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
pub tag: String
}
impl Display for EntityTag {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
try!(write!(fmt, "{}", "W/"));
}
write!(fmt, "{}", self.tag)
}
}
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool {
for c in slice.bytes() {
match c {
b'\x21' | b'\x23'... b'\x7e' | b'\x80'... b'\xff' => (),
_ => { return false; }
}
}
true
}
impl FromStr for EntityTag {
type Err = ();
fn from_str(s: &str) -> Result<EntityTag, ()> {
let length: usize = s.len();
let slice = &s[];
// Early exits:
// 1. The string is empty, or,
// 2. it doesn't terminate in a DQUOTE.
if slice.is_empty() ||!slice.ends_with("\"") {
return Err(());
}
| return Ok(EntityTag {
weak: false,
tag: slice.slice_chars(1, length-1).to_string()
});
} else {
return Err(());
}
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1).to_string()
});
} else {
return Err(());
}
}
Err(())
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_successes() {
// Expected successes
let mut etag : EntityTag = "\"foobar\"".parse().unwrap();
assert_eq!(etag, (EntityTag {
weak: false,
tag: "foobar".to_string()
}));
etag = "\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: false,
tag: "".to_string()
});
etag = "W/\"weak-etag\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "weak-etag".to_string()
});
etag = "W/\"\x65\x62\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "\u{0065}\u{0062}".to_string()
});
etag = "W/\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "".to_string()
});
}
#[test]
fn test_etag_failures() {
// Expected failures
let mut etag: Result<EntityTag,()>;
etag = "no-dquotes".parse();
assert_eq!(etag, Err(()));
etag = "w/\"the-first-w-is-case-sensitive\"".parse();
assert_eq!(etag, Err(()));
etag = "".parse();
assert_eq!(etag, Err(()));
etag = "\"unmatched-dquotes1".parse();
assert_eq!(etag, Err(()));
etag = "unmatched-dquotes2\"".parse();
assert_eq!(etag, Err(()));
etag = "matched-\"dquotes\"".parse();
assert_eq!(etag, Err(()));
}
} | // The etag is weak if its first char is not a DQUOTE.
if slice.char_at(0) == '"' /* '"' */ {
// No need to check if the last char is a DQUOTE,
// we already did that above.
if check_slice_validity(slice.slice_chars(1, length-1)) { | random_line_split |
dst-index.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 overloaded index expressions with DST result types
// can't be used as rvalues
use std::ops::Index;
use std::fmt::Show;
struct S;
impl Index<uint, str> for S {
fn | <'a>(&'a self, _: &uint) -> &'a str {
"hello"
}
}
struct T;
impl Index<uint, Show +'static> for T {
fn index<'a>(&'a self, idx: &uint) -> &'a (Show +'static) {
static x: uint = 42;
&x
}
}
fn main() {
S[0];
//~^ ERROR E0161
T[0];
//~^ ERROR cannot move out of dereference
//~^^ ERROR E0161
}
| index | identifier_name |
dst-index.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 overloaded index expressions with DST result types
// can't be used as rvalues |
struct S;
impl Index<uint, str> for S {
fn index<'a>(&'a self, _: &uint) -> &'a str {
"hello"
}
}
struct T;
impl Index<uint, Show +'static> for T {
fn index<'a>(&'a self, idx: &uint) -> &'a (Show +'static) {
static x: uint = 42;
&x
}
}
fn main() {
S[0];
//~^ ERROR E0161
T[0];
//~^ ERROR cannot move out of dereference
//~^^ ERROR E0161
} |
use std::ops::Index;
use std::fmt::Show; | random_line_split |
player_unit.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use error::*;
use identifier::*;
use io_tools::*;
use std::io::Read;
#[derive(Default, Debug)]
pub struct PlayerUnit {
pub position_x: f32,
pub position_y: f32,
pub position_z: f32,
pub spawn_id: Option<SpawnId>,
pub unit_id: UnitId,
pub state: u8,
pub rotation: f32,
}
impl PlayerUnit {
// TODO: Implement writing
pub fn | <S: Read>(stream: &mut S) -> Result<PlayerUnit> {
let mut data: PlayerUnit = Default::default();
data.position_x = try!(stream.read_f32());
data.position_y = try!(stream.read_f32());
data.position_z = try!(stream.read_f32());
data.spawn_id = optional_id!(try!(stream.read_i32()));
data.unit_id = required_id!(try!(stream.read_i16()));
data.state = try!(stream.read_u8());
data.rotation = try!(stream.read_f32());
Ok(data)
}
}
| read_from_stream | identifier_name |
player_unit.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use error::*;
use identifier::*;
use io_tools::*;
use std::io::Read;
#[derive(Default, Debug)]
pub struct PlayerUnit {
pub position_x: f32,
pub position_y: f32,
pub position_z: f32,
pub spawn_id: Option<SpawnId>,
pub unit_id: UnitId,
pub state: u8,
pub rotation: f32,
}
impl PlayerUnit {
// TODO: Implement writing
pub fn read_from_stream<S: Read>(stream: &mut S) -> Result<PlayerUnit> {
let mut data: PlayerUnit = Default::default();
data.position_x = try!(stream.read_f32());
data.position_y = try!(stream.read_f32());
data.position_z = try!(stream.read_f32());
data.spawn_id = optional_id!(try!(stream.read_i32()));
data.unit_id = required_id!(try!(stream.read_i16()));
data.state = try!(stream.read_u8());
data.rotation = try!(stream.read_f32());
Ok(data)
}
} | // copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | random_line_split |
trait-with-bounds-default.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.
//
pub trait Clone2 {
/// Returns a copy of the value. The contents of boxes
/// are copied to maintain uniqueness, while the contents of
/// managed pointers are not copied.
fn clone(&self) -> Self;
}
trait Getter<T: Clone> {
fn do_get(&self) -> T;
fn do_get2(&self) -> (T, T) {
let x = self.do_get();
(x.clone(), x.clone())
}
}
impl Getter<isize> for isize {
fn do_get(&self) -> isize { *self }
}
impl<T: Clone> Getter<T> for Option<T> {
fn do_get(&self) -> T { self.as_ref().unwrap().clone() }
}
pub fn | () {
assert_eq!(3.do_get2(), (3, 3));
assert_eq!(Some("hi".to_string()).do_get2(), ("hi".to_string(), "hi".to_string()));
}
| main | identifier_name |
trait-with-bounds-default.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.
//
pub trait Clone2 {
/// Returns a copy of the value. The contents of boxes
/// are copied to maintain uniqueness, while the contents of
/// managed pointers are not copied.
fn clone(&self) -> Self;
}
trait Getter<T: Clone> {
fn do_get(&self) -> T;
fn do_get2(&self) -> (T, T) {
let x = self.do_get();
(x.clone(), x.clone())
}
}
impl Getter<isize> for isize {
fn do_get(&self) -> isize { *self }
}
impl<T: Clone> Getter<T> for Option<T> {
fn do_get(&self) -> T |
}
pub fn main() {
assert_eq!(3.do_get2(), (3, 3));
assert_eq!(Some("hi".to_string()).do_get2(), ("hi".to_string(), "hi".to_string()));
}
| { self.as_ref().unwrap().clone() } | identifier_body |
trait-with-bounds-default.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.
//
pub trait Clone2 {
/// Returns a copy of the value. The contents of boxes
/// are copied to maintain uniqueness, while the contents of
/// managed pointers are not copied.
fn clone(&self) -> Self;
}
| fn do_get(&self) -> T;
fn do_get2(&self) -> (T, T) {
let x = self.do_get();
(x.clone(), x.clone())
}
}
impl Getter<isize> for isize {
fn do_get(&self) -> isize { *self }
}
impl<T: Clone> Getter<T> for Option<T> {
fn do_get(&self) -> T { self.as_ref().unwrap().clone() }
}
pub fn main() {
assert_eq!(3.do_get2(), (3, 3));
assert_eq!(Some("hi".to_string()).do_get2(), ("hi".to_string(), "hi".to_string()));
} | trait Getter<T: Clone> { | random_line_split |
mod.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::cmp::PartialEq;
use core::fmt::Debug;
use core::ops::{Add, Sub, Mul, Div, Rem};
use core::marker::Copy;
#[macro_use]
mod int_macros;
mod i8;
mod i16;
mod i32;
mod i64;
#[macro_use]
mod uint_macros;
mod u8;
mod u16;
mod u32;
mod u64;
mod flt2dec;
/// Helper function for testing numeric operations
pub fn test_num<T>(ten: T, two: T) where
T: PartialEq
+ Add<Output=T> + Sub<Output=T>
+ Mul<Output=T> + Div<Output=T>
+ Rem<Output=T> + Debug
+ Copy
{
assert_eq!(ten.add(two), ten + two);
assert_eq!(ten.sub(two), ten - two);
assert_eq!(ten.mul(two), ten * two);
assert_eq!(ten.div(two), ten / two);
assert_eq!(ten.rem(two), ten % two);
}
#[cfg(test)]
mod tests {
use core::option::Option;
use core::option::Option::{Some, None};
use core::num::Float;
#[test]
fn from_str_issue7588() {
let u : Option<u8> = u8::from_str_radix("1000", 10).ok();
assert_eq!(u, None);
let s : Option<i16> = i16::from_str_radix("80000", 10).ok();
assert_eq!(s, None);
let s = "10000000000000000000000000000000000000000";
let f : Option<f32> = f32::from_str_radix(s, 10).ok();
assert_eq!(f, Some(Float::infinity()));
let fe : Option<f32> = f32::from_str_radix("1e40", 10).ok();
assert_eq!(fe, Some(Float::infinity()));
}
#[test]
fn test_from_str_radix_float() |
#[test]
fn test_int_from_str_overflow() {
let mut i8_val: i8 = 127;
assert_eq!("127".parse::<i8>().ok(), Some(i8_val));
assert_eq!("128".parse::<i8>().ok(), None);
i8_val = i8_val.wrapping_add(1);
assert_eq!("-128".parse::<i8>().ok(), Some(i8_val));
assert_eq!("-129".parse::<i8>().ok(), None);
let mut i16_val: i16 = 32_767;
assert_eq!("32767".parse::<i16>().ok(), Some(i16_val));
assert_eq!("32768".parse::<i16>().ok(), None);
i16_val = i16_val.wrapping_add(1);
assert_eq!("-32768".parse::<i16>().ok(), Some(i16_val));
assert_eq!("-32769".parse::<i16>().ok(), None);
let mut i32_val: i32 = 2_147_483_647;
assert_eq!("2147483647".parse::<i32>().ok(), Some(i32_val));
assert_eq!("2147483648".parse::<i32>().ok(), None);
i32_val = i32_val.wrapping_add(1);
assert_eq!("-2147483648".parse::<i32>().ok(), Some(i32_val));
assert_eq!("-2147483649".parse::<i32>().ok(), None);
let mut i64_val: i64 = 9_223_372_036_854_775_807;
assert_eq!("9223372036854775807".parse::<i64>().ok(), Some(i64_val));
assert_eq!("9223372036854775808".parse::<i64>().ok(), None);
i64_val = i64_val.wrapping_add(1);
assert_eq!("-9223372036854775808".parse::<i64>().ok(), Some(i64_val));
assert_eq!("-9223372036854775809".parse::<i64>().ok(), None);
}
#[test]
fn test_invalid() {
assert_eq!("--129".parse::<i8>().ok(), None);
assert_eq!("Съешь".parse::<u8>().ok(), None);
}
#[test]
fn test_empty() {
assert_eq!("-".parse::<i8>().ok(), None);
assert_eq!("".parse::<u8>().ok(), None);
}
}
| {
let x1 : Option<f64> = f64::from_str_radix("-123.456", 10).ok();
assert_eq!(x1, Some(-123.456));
let x2 : Option<f32> = f32::from_str_radix("123.456", 10).ok();
assert_eq!(x2, Some(123.456));
let x3 : Option<f32> = f32::from_str_radix("-0.0", 10).ok();
assert_eq!(x3, Some(-0.0));
let x4 : Option<f32> = f32::from_str_radix("0.0", 10).ok();
assert_eq!(x4, Some(0.0));
let x4 : Option<f32> = f32::from_str_radix("1.0", 10).ok();
assert_eq!(x4, Some(1.0));
let x5 : Option<f32> = f32::from_str_radix("-1.0", 10).ok();
assert_eq!(x5, Some(-1.0));
} | identifier_body |
mod.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::cmp::PartialEq;
use core::fmt::Debug;
use core::ops::{Add, Sub, Mul, Div, Rem};
use core::marker::Copy;
#[macro_use]
mod int_macros;
mod i8;
mod i16;
mod i32;
mod i64;
#[macro_use]
mod uint_macros;
mod u8;
mod u16;
mod u32;
mod u64;
mod flt2dec;
/// Helper function for testing numeric operations
pub fn | <T>(ten: T, two: T) where
T: PartialEq
+ Add<Output=T> + Sub<Output=T>
+ Mul<Output=T> + Div<Output=T>
+ Rem<Output=T> + Debug
+ Copy
{
assert_eq!(ten.add(two), ten + two);
assert_eq!(ten.sub(two), ten - two);
assert_eq!(ten.mul(two), ten * two);
assert_eq!(ten.div(two), ten / two);
assert_eq!(ten.rem(two), ten % two);
}
#[cfg(test)]
mod tests {
use core::option::Option;
use core::option::Option::{Some, None};
use core::num::Float;
#[test]
fn from_str_issue7588() {
let u : Option<u8> = u8::from_str_radix("1000", 10).ok();
assert_eq!(u, None);
let s : Option<i16> = i16::from_str_radix("80000", 10).ok();
assert_eq!(s, None);
let s = "10000000000000000000000000000000000000000";
let f : Option<f32> = f32::from_str_radix(s, 10).ok();
assert_eq!(f, Some(Float::infinity()));
let fe : Option<f32> = f32::from_str_radix("1e40", 10).ok();
assert_eq!(fe, Some(Float::infinity()));
}
#[test]
fn test_from_str_radix_float() {
let x1 : Option<f64> = f64::from_str_radix("-123.456", 10).ok();
assert_eq!(x1, Some(-123.456));
let x2 : Option<f32> = f32::from_str_radix("123.456", 10).ok();
assert_eq!(x2, Some(123.456));
let x3 : Option<f32> = f32::from_str_radix("-0.0", 10).ok();
assert_eq!(x3, Some(-0.0));
let x4 : Option<f32> = f32::from_str_radix("0.0", 10).ok();
assert_eq!(x4, Some(0.0));
let x4 : Option<f32> = f32::from_str_radix("1.0", 10).ok();
assert_eq!(x4, Some(1.0));
let x5 : Option<f32> = f32::from_str_radix("-1.0", 10).ok();
assert_eq!(x5, Some(-1.0));
}
#[test]
fn test_int_from_str_overflow() {
let mut i8_val: i8 = 127;
assert_eq!("127".parse::<i8>().ok(), Some(i8_val));
assert_eq!("128".parse::<i8>().ok(), None);
i8_val = i8_val.wrapping_add(1);
assert_eq!("-128".parse::<i8>().ok(), Some(i8_val));
assert_eq!("-129".parse::<i8>().ok(), None);
let mut i16_val: i16 = 32_767;
assert_eq!("32767".parse::<i16>().ok(), Some(i16_val));
assert_eq!("32768".parse::<i16>().ok(), None);
i16_val = i16_val.wrapping_add(1);
assert_eq!("-32768".parse::<i16>().ok(), Some(i16_val));
assert_eq!("-32769".parse::<i16>().ok(), None);
let mut i32_val: i32 = 2_147_483_647;
assert_eq!("2147483647".parse::<i32>().ok(), Some(i32_val));
assert_eq!("2147483648".parse::<i32>().ok(), None);
i32_val = i32_val.wrapping_add(1);
assert_eq!("-2147483648".parse::<i32>().ok(), Some(i32_val));
assert_eq!("-2147483649".parse::<i32>().ok(), None);
let mut i64_val: i64 = 9_223_372_036_854_775_807;
assert_eq!("9223372036854775807".parse::<i64>().ok(), Some(i64_val));
assert_eq!("9223372036854775808".parse::<i64>().ok(), None);
i64_val = i64_val.wrapping_add(1);
assert_eq!("-9223372036854775808".parse::<i64>().ok(), Some(i64_val));
assert_eq!("-9223372036854775809".parse::<i64>().ok(), None);
}
#[test]
fn test_invalid() {
assert_eq!("--129".parse::<i8>().ok(), None);
assert_eq!("Съешь".parse::<u8>().ok(), None);
}
#[test]
fn test_empty() {
assert_eq!("-".parse::<i8>().ok(), None);
assert_eq!("".parse::<u8>().ok(), None);
}
}
| test_num | identifier_name |
mod.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use core::cmp::PartialEq;
use core::fmt::Debug;
use core::ops::{Add, Sub, Mul, Div, Rem};
use core::marker::Copy;
#[macro_use]
mod int_macros;
mod i8;
mod i16;
mod i32;
mod i64;
#[macro_use]
mod uint_macros;
mod u8;
mod u16;
mod u32;
mod u64;
mod flt2dec;
/// Helper function for testing numeric operations
pub fn test_num<T>(ten: T, two: T) where
T: PartialEq
+ Add<Output=T> + Sub<Output=T>
+ Mul<Output=T> + Div<Output=T>
+ Rem<Output=T> + Debug
+ Copy
{
assert_eq!(ten.add(two), ten + two);
assert_eq!(ten.sub(two), ten - two);
assert_eq!(ten.mul(two), ten * two);
assert_eq!(ten.div(two), ten / two);
assert_eq!(ten.rem(two), ten % two);
}
#[cfg(test)]
mod tests {
use core::option::Option;
use core::option::Option::{Some, None};
use core::num::Float;
#[test]
fn from_str_issue7588() {
let u : Option<u8> = u8::from_str_radix("1000", 10).ok();
assert_eq!(u, None);
let s : Option<i16> = i16::from_str_radix("80000", 10).ok();
assert_eq!(s, None);
let s = "10000000000000000000000000000000000000000";
let f : Option<f32> = f32::from_str_radix(s, 10).ok();
assert_eq!(f, Some(Float::infinity()));
let fe : Option<f32> = f32::from_str_radix("1e40", 10).ok();
assert_eq!(fe, Some(Float::infinity()));
}
#[test]
fn test_from_str_radix_float() {
let x1 : Option<f64> = f64::from_str_radix("-123.456", 10).ok();
assert_eq!(x1, Some(-123.456));
let x2 : Option<f32> = f32::from_str_radix("123.456", 10).ok();
assert_eq!(x2, Some(123.456));
let x3 : Option<f32> = f32::from_str_radix("-0.0", 10).ok();
assert_eq!(x3, Some(-0.0));
let x4 : Option<f32> = f32::from_str_radix("0.0", 10).ok();
assert_eq!(x4, Some(0.0));
let x4 : Option<f32> = f32::from_str_radix("1.0", 10).ok(); | #[test]
fn test_int_from_str_overflow() {
let mut i8_val: i8 = 127;
assert_eq!("127".parse::<i8>().ok(), Some(i8_val));
assert_eq!("128".parse::<i8>().ok(), None);
i8_val = i8_val.wrapping_add(1);
assert_eq!("-128".parse::<i8>().ok(), Some(i8_val));
assert_eq!("-129".parse::<i8>().ok(), None);
let mut i16_val: i16 = 32_767;
assert_eq!("32767".parse::<i16>().ok(), Some(i16_val));
assert_eq!("32768".parse::<i16>().ok(), None);
i16_val = i16_val.wrapping_add(1);
assert_eq!("-32768".parse::<i16>().ok(), Some(i16_val));
assert_eq!("-32769".parse::<i16>().ok(), None);
let mut i32_val: i32 = 2_147_483_647;
assert_eq!("2147483647".parse::<i32>().ok(), Some(i32_val));
assert_eq!("2147483648".parse::<i32>().ok(), None);
i32_val = i32_val.wrapping_add(1);
assert_eq!("-2147483648".parse::<i32>().ok(), Some(i32_val));
assert_eq!("-2147483649".parse::<i32>().ok(), None);
let mut i64_val: i64 = 9_223_372_036_854_775_807;
assert_eq!("9223372036854775807".parse::<i64>().ok(), Some(i64_val));
assert_eq!("9223372036854775808".parse::<i64>().ok(), None);
i64_val = i64_val.wrapping_add(1);
assert_eq!("-9223372036854775808".parse::<i64>().ok(), Some(i64_val));
assert_eq!("-9223372036854775809".parse::<i64>().ok(), None);
}
#[test]
fn test_invalid() {
assert_eq!("--129".parse::<i8>().ok(), None);
assert_eq!("Съешь".parse::<u8>().ok(), None);
}
#[test]
fn test_empty() {
assert_eq!("-".parse::<i8>().ok(), None);
assert_eq!("".parse::<u8>().ok(), None);
}
} | assert_eq!(x4, Some(1.0));
let x5 : Option<f32> = f32::from_str_radix("-1.0", 10).ok();
assert_eq!(x5, Some(-1.0));
}
| random_line_split |
issue-34798.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![forbid(improper_ctypes)]
#![allow(dead_code)]
#[repr(C)]
pub struct Foo {
size: u8,
__value: ::std::marker::PhantomData<i32>,
}
| pub struct ZeroSizeWithPhantomData<T>(::std::marker::PhantomData<T>);
#[repr(C)]
pub struct Bar {
size: u8,
baz: ZeroSizeWithPhantomData<i32>,
}
extern "C" {
pub fn bar(_: *mut Foo, _: *mut Bar);
}
fn main() {
} | #[repr(C)] | random_line_split |
issue-34798.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
#![forbid(improper_ctypes)]
#![allow(dead_code)]
#[repr(C)]
pub struct Foo {
size: u8,
__value: ::std::marker::PhantomData<i32>,
}
#[repr(C)]
pub struct ZeroSizeWithPhantomData<T>(::std::marker::PhantomData<T>);
#[repr(C)]
pub struct | {
size: u8,
baz: ZeroSizeWithPhantomData<i32>,
}
extern "C" {
pub fn bar(_: *mut Foo, _: *mut Bar);
}
fn main() {
}
| Bar | identifier_name |
vec-res-add.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.
#[deriving(Show)]
struct r {
i:int
} |
impl Drop for r {
fn drop(&mut self) {}
}
fn main() {
// This can't make sense as it would copy the classes
let i = vec!(r(0));
let j = vec!(r(1));
let k = i + j;
//~^ ERROR binary operation `+` cannot be applied to type
println!("{}", j);
} |
fn r(i:int) -> r { r { i: i } } | random_line_split |
vec-res-add.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.
#[deriving(Show)]
struct r {
i:int
}
fn r(i:int) -> r { r { i: i } }
impl Drop for r {
fn | (&mut self) {}
}
fn main() {
// This can't make sense as it would copy the classes
let i = vec!(r(0));
let j = vec!(r(1));
let k = i + j;
//~^ ERROR binary operation `+` cannot be applied to type
println!("{}", j);
}
| drop | identifier_name |
vec-res-add.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.
#[deriving(Show)]
struct r {
i:int
}
fn r(i:int) -> r |
impl Drop for r {
fn drop(&mut self) {}
}
fn main() {
// This can't make sense as it would copy the classes
let i = vec!(r(0));
let j = vec!(r(1));
let k = i + j;
//~^ ERROR binary operation `+` cannot be applied to type
println!("{}", j);
}
| { r { i: i } } | identifier_body |
generic_path.rs | use std::io::Write;
use std::ops::Deref;
use syn::ext::IdentExt;
use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver};
use crate::bindgen::ir::{Path, Type};
use crate::bindgen::utilities::IterHelpers;
use crate::bindgen::writer::{Source, SourceWriter};
#[derive(Default, Debug, Clone)]
pub struct GenericParams(pub Vec<Path>);
impl GenericParams {
pub fn new(generics: &syn::Generics) -> Self {
GenericParams(
generics
.params
.iter()
.filter_map(|x| match *x {
syn::GenericParam::Type(syn::TypeParam { ref ident,.. }) => {
Some(Path::new(ident.unraw().to_string()))
}
_ => None,
})
.collect(),
)
}
fn write_internal<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
with_default: bool,
) {
if!self.0.is_empty() && config.language == Language::Cxx {
out.write("template<");
for (i, item) in self.0.iter().enumerate() {
if i!= 0 {
out.write(", ");
}
write!(out, "typename {}", item);
if with_default {
write!(out, " = void");
}
}
out.write(">");
out.new_line();
}
}
pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, true);
}
}
impl Deref for GenericParams {
type Target = [Path];
fn | (&self) -> &[Path] {
&self.0
}
}
impl Source for GenericParams {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, false);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GenericPath {
path: Path,
export_name: String,
generics: Vec<Type>,
ctype: Option<DeclarationType>,
}
impl GenericPath {
pub fn new(path: Path, generics: Vec<Type>) -> Self {
let export_name = path.name().to_owned();
Self {
path,
export_name,
generics,
ctype: None,
}
}
pub fn self_path() -> Self {
Self::new(Path::new("Self"), vec![])
}
pub fn replace_self_with(&mut self, self_ty: &Path) {
if self.path.replace_self_with(self_ty) {
self.export_name = self_ty.name().to_owned();
}
// Caller deals with generics.
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn generics(&self) -> &[Type] {
&self.generics
}
pub fn generics_mut(&mut self) -> &mut [Type] {
&mut self.generics
}
pub fn ctype(&self) -> Option<&DeclarationType> {
self.ctype.as_ref()
}
pub fn name(&self) -> &str {
self.path.name()
}
pub fn export_name(&self) -> &str {
&self.export_name
}
pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) {
for generic in &mut self.generics {
generic.rename_for_config(config, generic_params);
}
if!generic_params.contains(&self.path) {
config.export.rename(&mut self.export_name);
}
}
pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
self.ctype = resolver.type_for(&self.path);
}
pub fn load(path: &syn::Path) -> Result<Self, String> {
assert!(
!path.segments.is_empty(),
"{:?} doesn't have any segments",
path
);
let last_segment = path.segments.last().unwrap();
let name = last_segment.ident.unraw().to_string();
let path = Path::new(name);
let phantom_data_path = Path::new("PhantomData");
if path == phantom_data_path {
return Ok(Self::new(path, Vec::new()));
}
let generics = match last_segment.arguments {
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
ref args,
..
}) => args.iter().try_skip_map(|x| match *x {
syn::GenericArgument::Type(ref x) => Type::load(x),
syn::GenericArgument::Lifetime(_) => Ok(None),
_ => Err(format!("can't handle generic argument {:?}", x)),
})?,
syn::PathArguments::Parenthesized(_) => {
return Err("Path contains parentheses.".to_owned());
}
_ => Vec::new(),
};
Ok(Self::new(path, generics))
}
}
| deref | identifier_name |
generic_path.rs | use std::io::Write;
use std::ops::Deref;
use syn::ext::IdentExt;
use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver};
use crate::bindgen::ir::{Path, Type};
use crate::bindgen::utilities::IterHelpers;
use crate::bindgen::writer::{Source, SourceWriter};
#[derive(Default, Debug, Clone)]
pub struct GenericParams(pub Vec<Path>);
impl GenericParams {
pub fn new(generics: &syn::Generics) -> Self {
GenericParams(
generics
.params
.iter()
.filter_map(|x| match *x {
syn::GenericParam::Type(syn::TypeParam { ref ident,.. }) => {
Some(Path::new(ident.unraw().to_string()))
}
_ => None,
})
.collect(),
)
}
fn write_internal<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
with_default: bool,
) {
if!self.0.is_empty() && config.language == Language::Cxx {
out.write("template<");
for (i, item) in self.0.iter().enumerate() {
if i!= 0 {
out.write(", ");
}
write!(out, "typename {}", item);
if with_default {
write!(out, " = void");
}
}
out.write(">");
out.new_line();
}
}
pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, true);
}
}
impl Deref for GenericParams {
type Target = [Path];
fn deref(&self) -> &[Path] {
&self.0
}
}
impl Source for GenericParams {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, false);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GenericPath {
path: Path,
export_name: String,
generics: Vec<Type>,
ctype: Option<DeclarationType>,
}
impl GenericPath {
pub fn new(path: Path, generics: Vec<Type>) -> Self {
let export_name = path.name().to_owned();
Self {
path,
export_name,
generics,
ctype: None,
}
}
pub fn self_path() -> Self {
Self::new(Path::new("Self"), vec![])
}
pub fn replace_self_with(&mut self, self_ty: &Path) {
if self.path.replace_self_with(self_ty) {
self.export_name = self_ty.name().to_owned();
}
// Caller deals with generics.
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn generics(&self) -> &[Type] {
&self.generics
}
pub fn generics_mut(&mut self) -> &mut [Type] {
&mut self.generics
}
pub fn ctype(&self) -> Option<&DeclarationType> |
pub fn name(&self) -> &str {
self.path.name()
}
pub fn export_name(&self) -> &str {
&self.export_name
}
pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) {
for generic in &mut self.generics {
generic.rename_for_config(config, generic_params);
}
if!generic_params.contains(&self.path) {
config.export.rename(&mut self.export_name);
}
}
pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
self.ctype = resolver.type_for(&self.path);
}
pub fn load(path: &syn::Path) -> Result<Self, String> {
assert!(
!path.segments.is_empty(),
"{:?} doesn't have any segments",
path
);
let last_segment = path.segments.last().unwrap();
let name = last_segment.ident.unraw().to_string();
let path = Path::new(name);
let phantom_data_path = Path::new("PhantomData");
if path == phantom_data_path {
return Ok(Self::new(path, Vec::new()));
}
let generics = match last_segment.arguments {
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
ref args,
..
}) => args.iter().try_skip_map(|x| match *x {
syn::GenericArgument::Type(ref x) => Type::load(x),
syn::GenericArgument::Lifetime(_) => Ok(None),
_ => Err(format!("can't handle generic argument {:?}", x)),
})?,
syn::PathArguments::Parenthesized(_) => {
return Err("Path contains parentheses.".to_owned());
}
_ => Vec::new(),
};
Ok(Self::new(path, generics))
}
}
| {
self.ctype.as_ref()
} | identifier_body |
generic_path.rs | use std::io::Write;
use std::ops::Deref;
use syn::ext::IdentExt;
use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver};
use crate::bindgen::ir::{Path, Type};
use crate::bindgen::utilities::IterHelpers;
use crate::bindgen::writer::{Source, SourceWriter};
#[derive(Default, Debug, Clone)]
pub struct GenericParams(pub Vec<Path>);
impl GenericParams {
pub fn new(generics: &syn::Generics) -> Self {
GenericParams(
generics
.params
.iter()
.filter_map(|x| match *x {
syn::GenericParam::Type(syn::TypeParam { ref ident,.. }) => {
Some(Path::new(ident.unraw().to_string()))
}
_ => None,
})
.collect(),
)
}
fn write_internal<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
with_default: bool,
) {
if!self.0.is_empty() && config.language == Language::Cxx {
out.write("template<");
for (i, item) in self.0.iter().enumerate() {
if i!= 0 {
out.write(", ");
}
write!(out, "typename {}", item);
if with_default {
write!(out, " = void");
}
}
out.write(">");
out.new_line();
}
} | }
impl Deref for GenericParams {
type Target = [Path];
fn deref(&self) -> &[Path] {
&self.0
}
}
impl Source for GenericParams {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, false);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GenericPath {
path: Path,
export_name: String,
generics: Vec<Type>,
ctype: Option<DeclarationType>,
}
impl GenericPath {
pub fn new(path: Path, generics: Vec<Type>) -> Self {
let export_name = path.name().to_owned();
Self {
path,
export_name,
generics,
ctype: None,
}
}
pub fn self_path() -> Self {
Self::new(Path::new("Self"), vec![])
}
pub fn replace_self_with(&mut self, self_ty: &Path) {
if self.path.replace_self_with(self_ty) {
self.export_name = self_ty.name().to_owned();
}
// Caller deals with generics.
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn generics(&self) -> &[Type] {
&self.generics
}
pub fn generics_mut(&mut self) -> &mut [Type] {
&mut self.generics
}
pub fn ctype(&self) -> Option<&DeclarationType> {
self.ctype.as_ref()
}
pub fn name(&self) -> &str {
self.path.name()
}
pub fn export_name(&self) -> &str {
&self.export_name
}
pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) {
for generic in &mut self.generics {
generic.rename_for_config(config, generic_params);
}
if!generic_params.contains(&self.path) {
config.export.rename(&mut self.export_name);
}
}
pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
self.ctype = resolver.type_for(&self.path);
}
pub fn load(path: &syn::Path) -> Result<Self, String> {
assert!(
!path.segments.is_empty(),
"{:?} doesn't have any segments",
path
);
let last_segment = path.segments.last().unwrap();
let name = last_segment.ident.unraw().to_string();
let path = Path::new(name);
let phantom_data_path = Path::new("PhantomData");
if path == phantom_data_path {
return Ok(Self::new(path, Vec::new()));
}
let generics = match last_segment.arguments {
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
ref args,
..
}) => args.iter().try_skip_map(|x| match *x {
syn::GenericArgument::Type(ref x) => Type::load(x),
syn::GenericArgument::Lifetime(_) => Ok(None),
_ => Err(format!("can't handle generic argument {:?}", x)),
})?,
syn::PathArguments::Parenthesized(_) => {
return Err("Path contains parentheses.".to_owned());
}
_ => Vec::new(),
};
Ok(Self::new(path, generics))
}
} |
pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, true);
} | random_line_split |
generic_path.rs | use std::io::Write;
use std::ops::Deref;
use syn::ext::IdentExt;
use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver};
use crate::bindgen::ir::{Path, Type};
use crate::bindgen::utilities::IterHelpers;
use crate::bindgen::writer::{Source, SourceWriter};
#[derive(Default, Debug, Clone)]
pub struct GenericParams(pub Vec<Path>);
impl GenericParams {
pub fn new(generics: &syn::Generics) -> Self {
GenericParams(
generics
.params
.iter()
.filter_map(|x| match *x {
syn::GenericParam::Type(syn::TypeParam { ref ident,.. }) => {
Some(Path::new(ident.unraw().to_string()))
}
_ => None,
})
.collect(),
)
}
fn write_internal<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
with_default: bool,
) {
if!self.0.is_empty() && config.language == Language::Cxx {
out.write("template<");
for (i, item) in self.0.iter().enumerate() {
if i!= 0 |
write!(out, "typename {}", item);
if with_default {
write!(out, " = void");
}
}
out.write(">");
out.new_line();
}
}
pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, true);
}
}
impl Deref for GenericParams {
type Target = [Path];
fn deref(&self) -> &[Path] {
&self.0
}
}
impl Source for GenericParams {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, false);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GenericPath {
path: Path,
export_name: String,
generics: Vec<Type>,
ctype: Option<DeclarationType>,
}
impl GenericPath {
pub fn new(path: Path, generics: Vec<Type>) -> Self {
let export_name = path.name().to_owned();
Self {
path,
export_name,
generics,
ctype: None,
}
}
pub fn self_path() -> Self {
Self::new(Path::new("Self"), vec![])
}
pub fn replace_self_with(&mut self, self_ty: &Path) {
if self.path.replace_self_with(self_ty) {
self.export_name = self_ty.name().to_owned();
}
// Caller deals with generics.
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn generics(&self) -> &[Type] {
&self.generics
}
pub fn generics_mut(&mut self) -> &mut [Type] {
&mut self.generics
}
pub fn ctype(&self) -> Option<&DeclarationType> {
self.ctype.as_ref()
}
pub fn name(&self) -> &str {
self.path.name()
}
pub fn export_name(&self) -> &str {
&self.export_name
}
pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) {
for generic in &mut self.generics {
generic.rename_for_config(config, generic_params);
}
if!generic_params.contains(&self.path) {
config.export.rename(&mut self.export_name);
}
}
pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
self.ctype = resolver.type_for(&self.path);
}
pub fn load(path: &syn::Path) -> Result<Self, String> {
assert!(
!path.segments.is_empty(),
"{:?} doesn't have any segments",
path
);
let last_segment = path.segments.last().unwrap();
let name = last_segment.ident.unraw().to_string();
let path = Path::new(name);
let phantom_data_path = Path::new("PhantomData");
if path == phantom_data_path {
return Ok(Self::new(path, Vec::new()));
}
let generics = match last_segment.arguments {
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
ref args,
..
}) => args.iter().try_skip_map(|x| match *x {
syn::GenericArgument::Type(ref x) => Type::load(x),
syn::GenericArgument::Lifetime(_) => Ok(None),
_ => Err(format!("can't handle generic argument {:?}", x)),
})?,
syn::PathArguments::Parenthesized(_) => {
return Err("Path contains parentheses.".to_owned());
}
_ => Vec::new(),
};
Ok(Self::new(path, generics))
}
}
| {
out.write(", ");
} | conditional_block |
detect.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// written by Pierre Chifflier <[email protected]>
use crate::krb::krb5::KRB5Transaction;
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_msgtype(tx: &mut KRB5Transaction,
ptr: *mut u32)
{
*ptr = tx.msg_type.0;
}
/// Get error code, if present in transaction
/// Return 0 if error code was filled, else 1
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_errcode(tx: &mut KRB5Transaction,
ptr: *mut i32) -> u32
{
match tx.error_code {
Some(ref e) => {
*ptr = e.0;
0
},
None => 1
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_cname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.cname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_sname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.sname {
if (i as usize) < s.name_string.len() |
}
0
}
| {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
} | conditional_block |
detect.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// written by Pierre Chifflier <[email protected]>
use crate::krb::krb5::KRB5Transaction;
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_msgtype(tx: &mut KRB5Transaction,
ptr: *mut u32)
{
*ptr = tx.msg_type.0;
}
/// Get error code, if present in transaction
/// Return 0 if error code was filled, else 1
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_errcode(tx: &mut KRB5Transaction,
ptr: *mut i32) -> u32
{
match tx.error_code {
Some(ref e) => {
*ptr = e.0;
0
},
None => 1
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_cname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8, | -> u8
{
if let Some(ref s) = tx.cname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_sname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.sname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
} | buffer_len: *mut u32) | random_line_split |
detect.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// written by Pierre Chifflier <[email protected]>
use crate::krb::krb5::KRB5Transaction;
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_msgtype(tx: &mut KRB5Transaction,
ptr: *mut u32)
{
*ptr = tx.msg_type.0;
}
/// Get error code, if present in transaction
/// Return 0 if error code was filled, else 1
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_errcode(tx: &mut KRB5Transaction,
ptr: *mut i32) -> u32
{
match tx.error_code {
Some(ref e) => {
*ptr = e.0;
0
},
None => 1
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_cname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
|
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_sname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.sname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
}
| {
if let Some(ref s) = tx.cname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
} | identifier_body |
detect.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// written by Pierre Chifflier <[email protected]>
use crate::krb::krb5::KRB5Transaction;
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_msgtype(tx: &mut KRB5Transaction,
ptr: *mut u32)
{
*ptr = tx.msg_type.0;
}
/// Get error code, if present in transaction
/// Return 0 if error code was filled, else 1
#[no_mangle]
pub unsafe extern "C" fn | (tx: &mut KRB5Transaction,
ptr: *mut i32) -> u32
{
match tx.error_code {
Some(ref e) => {
*ptr = e.0;
0
},
None => 1
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_cname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.cname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_sname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.sname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
}
| rs_krb5_tx_get_errcode | identifier_name |
fp.rs | // Copyright 2021 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{DecodeError, FieldInfo};
/// Decodes the ISS value for a floating-point exception.
pub fn decode_iss_fp(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> {
let res0a = FieldInfo::get_bit(iss, "RES0", Some("Reserved"), 24).check_res0()?;
let tfv =
FieldInfo::get_bit(iss, "TFV", Some("Trapped Fault Valid"), 23).describe_bit(describe_tfv);
let res0b = FieldInfo::get(iss, "RES0", Some("Reserved"), 11, 23).check_res0()?;
let vecitr = FieldInfo::get(iss, "VECITR", Some("RES1 or UNKNOWN"), 8, 11);
let idf = FieldInfo::get_bit(iss, "IDF", Some("Input Denormal"), 7).describe_bit(describe_idf);
let res0c = FieldInfo::get(iss, "RES0", Some("Reserved"), 5, 7).check_res0()?;
let ixf = FieldInfo::get_bit(iss, "IXF", Some("Inexact"), 4).describe_bit(describe_ixf);
let uff = FieldInfo::get_bit(iss, "UFF", Some("Underflow"), 3).describe_bit(describe_uff);
let off = FieldInfo::get_bit(iss, "OFF", Some("Overflow"), 2).describe_bit(describe_off);
let dzf = FieldInfo::get_bit(iss, "DZF", Some("Divide by Zero"), 1).describe_bit(describe_dzf);
let iof =
FieldInfo::get_bit(iss, "IOF", Some("Invalid Operation"), 0).describe_bit(describe_iof);
Ok(vec![
res0a, tfv, res0b, vecitr, idf, res0c, ixf, uff, off, dzf, iof,
])
}
fn describe_tfv(tfv: bool) -> &'static str {
if tfv {
"One or more floating-point exceptions occurred; IDF, IXF, UFF, OFF, DZF and IOF hold information about what."
} else {
"IDF, IXF, UFF, OFF, DZF and IOF do not hold valid information."
}
}
fn | (idf: bool) -> &'static str {
if idf {
"Input denormal floating-point exception occurred."
} else {
"Input denormal floating-point exception did not occur."
}
}
fn describe_ixf(ixf: bool) -> &'static str {
if ixf {
"Inexact floating-point exception occurred."
} else {
"Inexact floating-point exception did not occur."
}
}
fn describe_uff(uff: bool) -> &'static str {
if uff {
"Underflow floating-point exception occurred."
} else {
"Underflow floating-point exception did not occur."
}
}
fn describe_off(off: bool) -> &'static str {
if off {
"Overflow floating-point exception occurred."
} else {
"Overflow floating-point exception did not occur."
}
}
fn describe_dzf(dzf: bool) -> &'static str {
if dzf {
"Divide by Zero floating-point exception occurred."
} else {
"Divide by Zero floating-point exception did not occur."
}
}
fn describe_iof(iof: bool) -> &'static str {
if iof {
"Invalid Operation floating-point exception occurred."
} else {
"Invalid Operation floating-point exception did not occur."
}
}
| describe_idf | identifier_name |
fp.rs | // Copyright 2021 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{DecodeError, FieldInfo};
/// Decodes the ISS value for a floating-point exception.
pub fn decode_iss_fp(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> {
let res0a = FieldInfo::get_bit(iss, "RES0", Some("Reserved"), 24).check_res0()?;
let tfv =
FieldInfo::get_bit(iss, "TFV", Some("Trapped Fault Valid"), 23).describe_bit(describe_tfv);
let res0b = FieldInfo::get(iss, "RES0", Some("Reserved"), 11, 23).check_res0()?;
let vecitr = FieldInfo::get(iss, "VECITR", Some("RES1 or UNKNOWN"), 8, 11);
let idf = FieldInfo::get_bit(iss, "IDF", Some("Input Denormal"), 7).describe_bit(describe_idf);
let res0c = FieldInfo::get(iss, "RES0", Some("Reserved"), 5, 7).check_res0()?;
let ixf = FieldInfo::get_bit(iss, "IXF", Some("Inexact"), 4).describe_bit(describe_ixf);
let uff = FieldInfo::get_bit(iss, "UFF", Some("Underflow"), 3).describe_bit(describe_uff);
let off = FieldInfo::get_bit(iss, "OFF", Some("Overflow"), 2).describe_bit(describe_off);
let dzf = FieldInfo::get_bit(iss, "DZF", Some("Divide by Zero"), 1).describe_bit(describe_dzf);
let iof =
FieldInfo::get_bit(iss, "IOF", Some("Invalid Operation"), 0).describe_bit(describe_iof);
Ok(vec![
res0a, tfv, res0b, vecitr, idf, res0c, ixf, uff, off, dzf, iof,
])
}
fn describe_tfv(tfv: bool) -> &'static str {
if tfv {
"One or more floating-point exceptions occurred; IDF, IXF, UFF, OFF, DZF and IOF hold information about what." | }
}
fn describe_idf(idf: bool) -> &'static str {
if idf {
"Input denormal floating-point exception occurred."
} else {
"Input denormal floating-point exception did not occur."
}
}
fn describe_ixf(ixf: bool) -> &'static str {
if ixf {
"Inexact floating-point exception occurred."
} else {
"Inexact floating-point exception did not occur."
}
}
fn describe_uff(uff: bool) -> &'static str {
if uff {
"Underflow floating-point exception occurred."
} else {
"Underflow floating-point exception did not occur."
}
}
fn describe_off(off: bool) -> &'static str {
if off {
"Overflow floating-point exception occurred."
} else {
"Overflow floating-point exception did not occur."
}
}
fn describe_dzf(dzf: bool) -> &'static str {
if dzf {
"Divide by Zero floating-point exception occurred."
} else {
"Divide by Zero floating-point exception did not occur."
}
}
fn describe_iof(iof: bool) -> &'static str {
if iof {
"Invalid Operation floating-point exception occurred."
} else {
"Invalid Operation floating-point exception did not occur."
}
} | } else {
"IDF, IXF, UFF, OFF, DZF and IOF do not hold valid information." | random_line_split |
fp.rs | // Copyright 2021 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{DecodeError, FieldInfo};
/// Decodes the ISS value for a floating-point exception.
pub fn decode_iss_fp(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> {
let res0a = FieldInfo::get_bit(iss, "RES0", Some("Reserved"), 24).check_res0()?;
let tfv =
FieldInfo::get_bit(iss, "TFV", Some("Trapped Fault Valid"), 23).describe_bit(describe_tfv);
let res0b = FieldInfo::get(iss, "RES0", Some("Reserved"), 11, 23).check_res0()?;
let vecitr = FieldInfo::get(iss, "VECITR", Some("RES1 or UNKNOWN"), 8, 11);
let idf = FieldInfo::get_bit(iss, "IDF", Some("Input Denormal"), 7).describe_bit(describe_idf);
let res0c = FieldInfo::get(iss, "RES0", Some("Reserved"), 5, 7).check_res0()?;
let ixf = FieldInfo::get_bit(iss, "IXF", Some("Inexact"), 4).describe_bit(describe_ixf);
let uff = FieldInfo::get_bit(iss, "UFF", Some("Underflow"), 3).describe_bit(describe_uff);
let off = FieldInfo::get_bit(iss, "OFF", Some("Overflow"), 2).describe_bit(describe_off);
let dzf = FieldInfo::get_bit(iss, "DZF", Some("Divide by Zero"), 1).describe_bit(describe_dzf);
let iof =
FieldInfo::get_bit(iss, "IOF", Some("Invalid Operation"), 0).describe_bit(describe_iof);
Ok(vec![
res0a, tfv, res0b, vecitr, idf, res0c, ixf, uff, off, dzf, iof,
])
}
fn describe_tfv(tfv: bool) -> &'static str {
if tfv {
"One or more floating-point exceptions occurred; IDF, IXF, UFF, OFF, DZF and IOF hold information about what."
} else {
"IDF, IXF, UFF, OFF, DZF and IOF do not hold valid information."
}
}
fn describe_idf(idf: bool) -> &'static str {
if idf {
"Input denormal floating-point exception occurred."
} else {
"Input denormal floating-point exception did not occur."
}
}
fn describe_ixf(ixf: bool) -> &'static str {
if ixf {
"Inexact floating-point exception occurred."
} else |
}
fn describe_uff(uff: bool) -> &'static str {
if uff {
"Underflow floating-point exception occurred."
} else {
"Underflow floating-point exception did not occur."
}
}
fn describe_off(off: bool) -> &'static str {
if off {
"Overflow floating-point exception occurred."
} else {
"Overflow floating-point exception did not occur."
}
}
fn describe_dzf(dzf: bool) -> &'static str {
if dzf {
"Divide by Zero floating-point exception occurred."
} else {
"Divide by Zero floating-point exception did not occur."
}
}
fn describe_iof(iof: bool) -> &'static str {
if iof {
"Invalid Operation floating-point exception occurred."
} else {
"Invalid Operation floating-point exception did not occur."
}
}
| {
"Inexact floating-point exception did not occur."
} | conditional_block |
fp.rs | // Copyright 2021 Google 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{DecodeError, FieldInfo};
/// Decodes the ISS value for a floating-point exception.
pub fn decode_iss_fp(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> {
let res0a = FieldInfo::get_bit(iss, "RES0", Some("Reserved"), 24).check_res0()?;
let tfv =
FieldInfo::get_bit(iss, "TFV", Some("Trapped Fault Valid"), 23).describe_bit(describe_tfv);
let res0b = FieldInfo::get(iss, "RES0", Some("Reserved"), 11, 23).check_res0()?;
let vecitr = FieldInfo::get(iss, "VECITR", Some("RES1 or UNKNOWN"), 8, 11);
let idf = FieldInfo::get_bit(iss, "IDF", Some("Input Denormal"), 7).describe_bit(describe_idf);
let res0c = FieldInfo::get(iss, "RES0", Some("Reserved"), 5, 7).check_res0()?;
let ixf = FieldInfo::get_bit(iss, "IXF", Some("Inexact"), 4).describe_bit(describe_ixf);
let uff = FieldInfo::get_bit(iss, "UFF", Some("Underflow"), 3).describe_bit(describe_uff);
let off = FieldInfo::get_bit(iss, "OFF", Some("Overflow"), 2).describe_bit(describe_off);
let dzf = FieldInfo::get_bit(iss, "DZF", Some("Divide by Zero"), 1).describe_bit(describe_dzf);
let iof =
FieldInfo::get_bit(iss, "IOF", Some("Invalid Operation"), 0).describe_bit(describe_iof);
Ok(vec![
res0a, tfv, res0b, vecitr, idf, res0c, ixf, uff, off, dzf, iof,
])
}
fn describe_tfv(tfv: bool) -> &'static str {
if tfv {
"One or more floating-point exceptions occurred; IDF, IXF, UFF, OFF, DZF and IOF hold information about what."
} else {
"IDF, IXF, UFF, OFF, DZF and IOF do not hold valid information."
}
}
fn describe_idf(idf: bool) -> &'static str {
if idf {
"Input denormal floating-point exception occurred."
} else {
"Input denormal floating-point exception did not occur."
}
}
fn describe_ixf(ixf: bool) -> &'static str {
if ixf {
"Inexact floating-point exception occurred."
} else {
"Inexact floating-point exception did not occur."
}
}
fn describe_uff(uff: bool) -> &'static str {
if uff {
"Underflow floating-point exception occurred."
} else {
"Underflow floating-point exception did not occur."
}
}
fn describe_off(off: bool) -> &'static str {
if off {
"Overflow floating-point exception occurred."
} else {
"Overflow floating-point exception did not occur."
}
}
fn describe_dzf(dzf: bool) -> &'static str {
if dzf {
"Divide by Zero floating-point exception occurred."
} else {
"Divide by Zero floating-point exception did not occur."
}
}
fn describe_iof(iof: bool) -> &'static str | {
if iof {
"Invalid Operation floating-point exception occurred."
} else {
"Invalid Operation floating-point exception did not occur."
}
} | identifier_body |
|
const-vec-of-fns.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.
/*!
* Try to double-check that static fns have the right size (with or
* without dummy env ptr, as appropriate) by iterating a size-2 array.
* If the static size differs from the runtime size, the second element
* should be read as a null or otherwise wrong pointer and crash.
*/
fn | () { }
static bare_fns: &'static [fn()] = &[f, f];
struct S<F: FnOnce()>(F);
static mut closures: &'static mut [S<fn()>] = &mut [S(f as fn()), S(f as fn())];
pub fn main() {
unsafe {
for &bare_fn in bare_fns { bare_fn() }
for closure in &mut *closures {
let S(ref mut closure) = *closure;
(*closure)()
}
}
}
| f | identifier_name |
const-vec-of-fns.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.
/*!
* Try to double-check that static fns have the right size (with or
* without dummy env ptr, as appropriate) by iterating a size-2 array.
* If the static size differs from the runtime size, the second element
* should be read as a null or otherwise wrong pointer and crash.
*/
fn f() { }
static bare_fns: &'static [fn()] = &[f, f];
struct S<F: FnOnce()>(F);
static mut closures: &'static mut [S<fn()>] = &mut [S(f as fn()), S(f as fn())];
pub fn main() {
unsafe {
for &bare_fn in bare_fns { bare_fn() }
for closure in &mut *closures {
let S(ref mut closure) = *closure;
(*closure)()
}
}
} | random_line_split |
|
shootout-k-nucleotide.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-android see #10393 #13206
use std::string::String;
use std::slice;
use std::sync::{Arc, Future};
static TABLE: [u8,..4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str,..5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[deriving(PartialEq, PartialOrd, Ord, Eq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn push_char(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn unpack(&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in range(0, frame) {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
count: uint,
items: Vec<Option<Box<Entry>>> }
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Items<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
count: 0,
items: Vec::from_fn(TABLE_SIZE, |_| None),
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
}
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
{
if self.items.get(index as uint).is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
*self.items.get_mut(index as uint) = Some(entry);
return;
}
}
{
let entry = &mut *self.items.get_mut(index as uint).get_mut_ref();
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
fn iter<'a>(&'a self) -> Items<'a> {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator<&'a Entry> for Items<'a> {
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8 {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => fail!("{}", c as char),
}
}
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in range(0, frame) {
code = code.push_char(input[0]);
input = input.slice_from(1);
}
frequencies.lookup(code, BumpCallback);
while input.len()!= 0 && input[0]!= ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = input.slice_from(1);
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.as_mut_slice().sort();
let mut total_count = 0;
for &(count, _) in vector.iter() {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3f}",
key.unpack(frame).as_slice(),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key!= l.as_slice().slice_to(key.len())).skip(1)
{
res.push_all(l.as_slice().trim().as_bytes());
}
for b in res.mut_iter() {
*b = b.to_ascii().to_upper().to_byte();
}
res
}
fn main() {
let input = if std::os::getenv("RUST_BENCH").is_some() | else {
get_sequence(&mut std::io::stdin(), ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<(uint, Future<Table>)> = range(1u, 3).map(|i| {
let input = input.clone();
(i, Future::spawn(proc() generate_frequencies(input.as_slice(), i)))
}).collect();
let occ_freqs: Vec<Future<Table>> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
Future::spawn(proc() generate_frequencies(input.as_slice(), occ.len()))
}).collect();
for (i, freq) in nb_freqs.move_iter() {
print_frequencies(&freq.unwrap(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.move_iter()) {
print_occurrences(&mut freq.unwrap(), occ);
}
}
| {
let fd = std::io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::io::BufferedReader::new(fd), ">THREE")
} | conditional_block |
shootout-k-nucleotide.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-android see #10393 #13206
use std::string::String;
use std::slice;
use std::sync::{Arc, Future};
static TABLE: [u8,..4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str,..5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[deriving(PartialEq, PartialOrd, Ord, Eq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn push_char(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn | (&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in range(0, frame) {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
count: uint,
items: Vec<Option<Box<Entry>>> }
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Items<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
count: 0,
items: Vec::from_fn(TABLE_SIZE, |_| None),
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
}
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
{
if self.items.get(index as uint).is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
*self.items.get_mut(index as uint) = Some(entry);
return;
}
}
{
let entry = &mut *self.items.get_mut(index as uint).get_mut_ref();
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
fn iter<'a>(&'a self) -> Items<'a> {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator<&'a Entry> for Items<'a> {
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8 {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => fail!("{}", c as char),
}
}
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in range(0, frame) {
code = code.push_char(input[0]);
input = input.slice_from(1);
}
frequencies.lookup(code, BumpCallback);
while input.len()!= 0 && input[0]!= ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = input.slice_from(1);
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.as_mut_slice().sort();
let mut total_count = 0;
for &(count, _) in vector.iter() {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3f}",
key.unpack(frame).as_slice(),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key!= l.as_slice().slice_to(key.len())).skip(1)
{
res.push_all(l.as_slice().trim().as_bytes());
}
for b in res.mut_iter() {
*b = b.to_ascii().to_upper().to_byte();
}
res
}
fn main() {
let input = if std::os::getenv("RUST_BENCH").is_some() {
let fd = std::io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::io::BufferedReader::new(fd), ">THREE")
} else {
get_sequence(&mut std::io::stdin(), ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<(uint, Future<Table>)> = range(1u, 3).map(|i| {
let input = input.clone();
(i, Future::spawn(proc() generate_frequencies(input.as_slice(), i)))
}).collect();
let occ_freqs: Vec<Future<Table>> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
Future::spawn(proc() generate_frequencies(input.as_slice(), occ.len()))
}).collect();
for (i, freq) in nb_freqs.move_iter() {
print_frequencies(&freq.unwrap(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.move_iter()) {
print_occurrences(&mut freq.unwrap(), occ);
}
}
| unpack | identifier_name |
shootout-k-nucleotide.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-android see #10393 #13206
use std::string::String;
use std::slice;
use std::sync::{Arc, Future};
static TABLE: [u8,..4] = [ 'A' as u8, 'C' as u8, 'G' as u8, 'T' as u8 ];
static TABLE_SIZE: uint = 2 << 16;
static OCCURRENCES: [&'static str,..5] = [
"GGT",
"GGTA",
"GGTATT",
"GGTATTTTAATT",
"GGTATTTTAATTTATAGT",
];
// Code implementation
#[deriving(PartialEq, PartialOrd, Ord, Eq)]
struct Code(u64);
impl Code {
fn hash(&self) -> u64 {
let Code(ret) = *self;
return ret;
}
fn push_char(&self, c: u8) -> Code {
Code((self.hash() << 2) + (pack_symbol(c) as u64))
}
fn rotate(&self, c: u8, frame: uint) -> Code {
Code(self.push_char(c).hash() & ((1u64 << (2 * frame)) - 1))
}
fn pack(string: &str) -> Code {
string.bytes().fold(Code(0u64), |a, b| a.push_char(b))
}
fn unpack(&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in range(0, frame) {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}
// Hash table implementation
trait TableCallback {
fn f(&self, entry: &mut Entry);
}
struct BumpCallback;
impl TableCallback for BumpCallback {
fn f(&self, entry: &mut Entry) {
entry.count += 1;
}
}
struct PrintCallback(&'static str);
impl TableCallback for PrintCallback {
fn f(&self, entry: &mut Entry) {
let PrintCallback(s) = *self;
println!("{}\t{}", entry.count as int, s);
}
}
struct Entry {
code: Code,
count: uint,
next: Option<Box<Entry>>,
}
struct Table {
count: uint,
items: Vec<Option<Box<Entry>>> }
struct Items<'a> {
cur: Option<&'a Entry>,
items: slice::Items<'a, Option<Box<Entry>>>,
}
impl Table {
fn new() -> Table {
Table {
count: 0,
items: Vec::from_fn(TABLE_SIZE, |_| None),
}
}
fn search_remainder<C:TableCallback>(item: &mut Entry, key: Code, c: C) {
match item.next {
None => {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
item.next = Some(entry);
}
Some(ref mut entry) => {
if entry.code == key {
c.f(&mut **entry);
return;
}
Table::search_remainder(&mut **entry, key, c)
}
}
}
fn lookup<C:TableCallback>(&mut self, key: Code, c: C) {
let index = key.hash() % (TABLE_SIZE as u64);
{
if self.items.get(index as uint).is_none() {
let mut entry = box Entry {
code: key,
count: 0,
next: None,
};
c.f(&mut *entry);
*self.items.get_mut(index as uint) = Some(entry);
return;
}
}
{
let entry = &mut *self.items.get_mut(index as uint).get_mut_ref(); | }
Table::search_remainder(&mut **entry, key, c)
}
}
fn iter<'a>(&'a self) -> Items<'a> {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator<&'a Entry> for Items<'a> {
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
None => {
let i;
loop {
match self.items.next() {
None => return None,
Some(&None) => {}
Some(&Some(ref a)) => { i = &**a; break }
}
}
self.cur = Some(&*i);
&*i
}
Some(c) => c
};
match ret.next {
None => { self.cur = None; }
Some(ref next) => { self.cur = Some(&**next); }
}
return Some(ret);
}
}
// Main program
fn pack_symbol(c: u8) -> u8 {
match c as char {
'A' => 0,
'C' => 1,
'G' => 2,
'T' => 3,
_ => fail!("{}", c as char),
}
}
fn unpack_symbol(c: u8) -> u8 {
TABLE[c as uint]
}
fn generate_frequencies(mut input: &[u8], frame: uint) -> Table {
let mut frequencies = Table::new();
if input.len() < frame { return frequencies; }
let mut code = Code(0);
// Pull first frame.
for _ in range(0, frame) {
code = code.push_char(input[0]);
input = input.slice_from(1);
}
frequencies.lookup(code, BumpCallback);
while input.len()!= 0 && input[0]!= ('>' as u8) {
code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback);
input = input.slice_from(1);
}
frequencies
}
fn print_frequencies(frequencies: &Table, frame: uint) {
let mut vector = Vec::new();
for entry in frequencies.iter() {
vector.push((entry.count, entry.code));
}
vector.as_mut_slice().sort();
let mut total_count = 0;
for &(count, _) in vector.iter() {
total_count += count;
}
for &(count, key) in vector.iter().rev() {
println!("{} {:.3f}",
key.unpack(frame).as_slice(),
(count as f32 * 100.0) / (total_count as f32));
}
println!("");
}
fn print_occurrences(frequencies: &mut Table, occurrence: &'static str) {
frequencies.lookup(Code::pack(occurrence), PrintCallback(occurrence))
}
fn get_sequence<R: Buffer>(r: &mut R, key: &str) -> Vec<u8> {
let mut res = Vec::new();
for l in r.lines().map(|l| l.ok().unwrap())
.skip_while(|l| key!= l.as_slice().slice_to(key.len())).skip(1)
{
res.push_all(l.as_slice().trim().as_bytes());
}
for b in res.mut_iter() {
*b = b.to_ascii().to_upper().to_byte();
}
res
}
fn main() {
let input = if std::os::getenv("RUST_BENCH").is_some() {
let fd = std::io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::io::BufferedReader::new(fd), ">THREE")
} else {
get_sequence(&mut std::io::stdin(), ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<(uint, Future<Table>)> = range(1u, 3).map(|i| {
let input = input.clone();
(i, Future::spawn(proc() generate_frequencies(input.as_slice(), i)))
}).collect();
let occ_freqs: Vec<Future<Table>> = OCCURRENCES.iter().map(|&occ| {
let input = input.clone();
Future::spawn(proc() generate_frequencies(input.as_slice(), occ.len()))
}).collect();
for (i, freq) in nb_freqs.move_iter() {
print_frequencies(&freq.unwrap(), i);
}
for (&occ, freq) in OCCURRENCES.iter().zip(occ_freqs.move_iter()) {
print_occurrences(&mut freq.unwrap(), occ);
}
} | if entry.code == key {
c.f(&mut **entry);
return; | random_line_split |
pat-tuple-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.
// run-pass
fn tuple() {
let x = (1,);
match x {
(2,..) => panic!(),
(..) => ()
}
}
fn tuple_struct() {
struct S(u8);
let x = S(1);
match x {
S(2,..) => panic!(),
S(..) => ()
}
}
fn | () {
tuple();
tuple_struct();
}
| main | identifier_name |
pat-tuple-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.
// run-pass
fn tuple() {
let x = (1,);
match x { | (..) => ()
}
}
fn tuple_struct() {
struct S(u8);
let x = S(1);
match x {
S(2,..) => panic!(),
S(..) => ()
}
}
fn main() {
tuple();
tuple_struct();
} | (2, ..) => panic!(), | random_line_split |
cabi_x86_64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// The classification code for the x86_64 ABI is taken from the clay language
// https://github.com/jckarter/clay/blob/master/compiler/src/externals.cpp
#![allow(non_upper_case_globals)]
use self::RegClass::*;
use llvm::{Integer, Pointer, Float, Double};
use llvm::{Struct, Array, Attribute, Vector};
use trans::cabi::{ArgType, FnType};
use trans::context::CrateContext;
use trans::type_::Type;
use std::cmp;
use std::iter::repeat;
#[derive(Clone, Copy, PartialEq)]
enum RegClass {
NoClass,
Int,
SSEFs,
SSEFv,
SSEDs,
SSEDv,
SSEInt(/* bitwidth */ u64),
/// Data that can appear in the upper half of an SSE register.
SSEUp,
X87,
X87Up,
ComplexX87,
Memory
}
trait TypeMethods {
fn is_reg_ty(&self) -> bool;
}
impl TypeMethods for Type {
fn is_reg_ty(&self) -> bool {
match self.kind() {
Integer | Pointer | Float | Double => true,
_ => false
}
}
}
impl RegClass {
fn is_sse(&self) -> bool {
match *self {
SSEFs | SSEFv | SSEDs | SSEDv | SSEInt(_) => true,
_ => false
}
}
}
trait ClassList {
fn is_pass_byval(&self) -> bool;
fn is_ret_bysret(&self) -> bool;
}
impl ClassList for [RegClass] {
fn is_pass_byval(&self) -> bool {
if self.is_empty() { return false; }
let class = self[0];
class == Memory
|| class == X87
|| class == ComplexX87
}
fn is_ret_bysret(&self) -> bool {
if self.is_empty() { return false; }
self[0] == Memory
}
}
fn classify_ty(ty: Type) -> Vec<RegClass> {
fn align(off: usize, ty: Type) -> usize {
let a = ty_align(ty);
return (off + a - 1) / a * a;
}
fn ty_align(ty: Type) -> usize {
match ty.kind() {
Integer => ((ty.int_width() as usize) + 7) / 8,
Pointer => 8,
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)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
fn ty_size(ty: Type) -> usize {
match ty.kind() {
Integer => (ty.int_width() as usize + 7) / 8,
Pointer => 8,
Float => 4,
Double => 8,
Struct => {
let str_tys = ty.field_types();
if ty.is_packed() {
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
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
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => panic!("ty_size: unhandled type")
}
}
fn all_mem(cls: &mut [RegClass]) {
for elt in cls {
*elt = Memory;
}
}
fn unify(cls: &mut [RegClass],
i: usize,
newv: RegClass) {
if cls[i] == newv { return }
let to_write = match (cls[i], newv) {
(NoClass, _) => newv,
(_, NoClass) => return,
(Memory, _) |
(_, Memory) => Memory,
(Int, _) |
(_, Int) => Int,
(X87, _) |
(X87Up, _) |
(ComplexX87, _) |
(_, X87) |
(_, X87Up) |
(_, ComplexX87) => Memory,
(SSEFv, SSEUp) |
(SSEFs, SSEUp) |
(SSEDv, SSEUp) |
(SSEDs, SSEUp) |
(SSEInt(_), SSEUp) => return,
(_, _) => newv
};
cls[i] = to_write;
}
fn classify_struct(tys: &[Type],
cls: &mut [RegClass],
i: usize,
off: usize,
packed: bool) {
let mut field_off = off;
for ty in tys {
if!packed {
field_off = align(field_off, *ty);
}
classify(*ty, cls, i, field_off);
field_off += ty_size(*ty);
}
}
fn classify(ty: Type,
cls: &mut [RegClass], ix: usize,
off: usize) {
let t_align = ty_align(ty);
let t_size = ty_size(ty);
let misalign = off % t_align;
if misalign!= 0 {
let mut i = off / 8;
let e = (off + t_size + 7) / 8;
while i < e {
unify(cls, ix + i, Memory);
i += 1;
}
return;
}
match ty.kind() {
Integer |
Pointer => {
unify(cls, ix + off / 8, Int);
}
Float => {
if off % 8 == 4 {
unify(cls, ix + off / 8, SSEFv);
} else {
unify(cls, ix + off / 8, SSEFs);
}
}
Double => {
unify(cls, ix + off / 8, SSEDs);
}
Struct => {
classify_struct(&ty.field_types(), cls, ix, off, ty.is_packed());
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut i = 0;
while i < len {
classify(elt, cls, ix, off + i * eltsz);
i += 1;
}
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut reg = match elt.kind() {
Integer => SSEInt(elt.int_width()),
Float => SSEFv,
Double => SSEDv,
_ => panic!("classify: unhandled vector element type")
};
let mut i = 0;
while i < len {
unify(cls, ix + (off + i * eltsz) / 8, reg);
// everything after the first one is the upper
// half of a register.
reg = SSEUp;
i += 1;
}
}
_ => panic!("classify: unhandled type")
}
}
fn fixup(ty: Type, cls: &mut [RegClass]) {
let mut i = 0;
let ty_kind = ty.kind();
let e = cls.len();
if cls.len() > 2 && (ty_kind == Struct || ty_kind == Array || ty_kind == Vector) {
if cls[i].is_sse() {
i += 1;
while i < e {
if cls[i]!= SSEUp {
all_mem(cls);
return;
}
i += 1;
}
} else {
all_mem(cls);
return
}
} else {
while i < e {
if cls[i] == Memory {
all_mem(cls);
return;
}
if cls[i] == X87Up {
// for darwin
// cls[i] = SSEDs;
all_mem(cls);
return;
}
if cls[i] == SSEUp {
cls[i] = SSEDv;
} else if cls[i].is_sse() {
i += 1;
while i!= e && cls[i] == SSEUp { i += 1; }
} else if cls[i] == X87 {
i += 1;
while i!= e && cls[i] == X87Up { i += 1; }
} else {
i += 1;
}
}
}
}
let words = (ty_size(ty) + 7) / 8;
let mut cls: Vec<_> = repeat(NoClass).take(words).collect();
if words > 4 {
all_mem(&mut cls);
return cls;
}
classify(ty, &mut cls, 0, 0);
fixup(ty, &mut cls);
return cls;
}
fn | (ccx: &CrateContext, cls: &[RegClass]) -> Type {
fn llvec_len(cls: &[RegClass]) -> usize {
let mut len = 1;
for c in cls {
if *c!= SSEUp {
break;
}
len += 1;
}
return len;
}
let mut tys = Vec::new();
let mut i = 0;
let e = cls.len();
while i < e {
match cls[i] {
Int => {
tys.push(Type::i64(ccx));
}
SSEFv | SSEDv | SSEInt(_) => {
let (elts_per_word, elt_ty) = match cls[i] {
SSEFv => (2, Type::f32(ccx)),
SSEDv => (1, Type::f64(ccx)),
SSEInt(bits) => {
assert!(bits == 8 || bits == 16 || bits == 32 || bits == 64,
"llreg_ty: unsupported SSEInt width {}", bits);
(64 / bits, Type::ix(ccx, bits))
}
_ => unreachable!(),
};
let vec_len = llvec_len(&cls[i + 1..]);
let vec_ty = Type::vector(&elt_ty, vec_len as u64 * elts_per_word);
tys.push(vec_ty);
i += vec_len;
continue;
}
SSEFs => {
tys.push(Type::f32(ccx));
}
SSEDs => {
tys.push(Type::f64(ccx));
}
_ => panic!("llregtype: unhandled class")
}
i += 1;
}
if tys.len() == 1 && tys[0].kind() == Vector {
// if the type contains only a vector, pass it as that vector.
tys[0]
} else {
Type::struct_(ccx, &tys, false)
}
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
fn x86_64_ty<F>(ccx: &CrateContext,
ty: Type,
is_mem_cls: F,
ind_attr: Attribute)
-> ArgType where
F: FnOnce(&[RegClass]) -> bool,
{
if!ty.is_reg_ty() {
let cls = classify_ty(ty);
if is_mem_cls(&cls) {
ArgType::indirect(ty, Some(ind_attr))
} else {
ArgType::direct(ty,
Some(llreg_ty(ccx, &cls)),
None,
None)
}
} else {
let attr = if ty == Type::i1(ccx) { Some(Attribute::ZExt) } else { None };
ArgType::direct(ty, None, None, attr)
}
}
let mut arg_tys = Vec::new();
for t in atys {
let ty = x86_64_ty(ccx, *t, |cls| cls.is_pass_byval(), Attribute::ByVal);
arg_tys.push(ty);
}
let ret_ty = if ret_def {
x86_64_ty(ccx, rty, |cls| cls.is_ret_bysret(), Attribute::StructRet)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
| llreg_ty | identifier_name |
cabi_x86_64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// The classification code for the x86_64 ABI is taken from the clay language
// https://github.com/jckarter/clay/blob/master/compiler/src/externals.cpp
#![allow(non_upper_case_globals)]
use self::RegClass::*;
use llvm::{Integer, Pointer, Float, Double};
use llvm::{Struct, Array, Attribute, Vector};
use trans::cabi::{ArgType, FnType};
use trans::context::CrateContext;
use trans::type_::Type;
use std::cmp;
use std::iter::repeat;
#[derive(Clone, Copy, PartialEq)]
enum RegClass {
NoClass,
Int,
SSEFs,
SSEFv,
SSEDs,
SSEDv,
SSEInt(/* bitwidth */ u64),
/// Data that can appear in the upper half of an SSE register.
SSEUp,
X87,
X87Up,
ComplexX87,
Memory
}
trait TypeMethods {
fn is_reg_ty(&self) -> bool;
}
impl TypeMethods for Type {
fn is_reg_ty(&self) -> bool {
match self.kind() {
Integer | Pointer | Float | Double => true,
_ => false
}
}
}
impl RegClass {
fn is_sse(&self) -> bool {
match *self {
SSEFs | SSEFv | SSEDs | SSEDv | SSEInt(_) => true,
_ => false
}
}
}
trait ClassList {
fn is_pass_byval(&self) -> bool;
fn is_ret_bysret(&self) -> bool;
}
impl ClassList for [RegClass] {
fn is_pass_byval(&self) -> bool {
if self.is_empty() { return false; }
let class = self[0];
class == Memory
|| class == X87
|| class == ComplexX87
} | if self.is_empty() { return false; }
self[0] == Memory
}
}
fn classify_ty(ty: Type) -> Vec<RegClass> {
fn align(off: usize, ty: Type) -> usize {
let a = ty_align(ty);
return (off + a - 1) / a * a;
}
fn ty_align(ty: Type) -> usize {
match ty.kind() {
Integer => ((ty.int_width() as usize) + 7) / 8,
Pointer => 8,
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)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
fn ty_size(ty: Type) -> usize {
match ty.kind() {
Integer => (ty.int_width() as usize + 7) / 8,
Pointer => 8,
Float => 4,
Double => 8,
Struct => {
let str_tys = ty.field_types();
if ty.is_packed() {
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
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
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => panic!("ty_size: unhandled type")
}
}
fn all_mem(cls: &mut [RegClass]) {
for elt in cls {
*elt = Memory;
}
}
fn unify(cls: &mut [RegClass],
i: usize,
newv: RegClass) {
if cls[i] == newv { return }
let to_write = match (cls[i], newv) {
(NoClass, _) => newv,
(_, NoClass) => return,
(Memory, _) |
(_, Memory) => Memory,
(Int, _) |
(_, Int) => Int,
(X87, _) |
(X87Up, _) |
(ComplexX87, _) |
(_, X87) |
(_, X87Up) |
(_, ComplexX87) => Memory,
(SSEFv, SSEUp) |
(SSEFs, SSEUp) |
(SSEDv, SSEUp) |
(SSEDs, SSEUp) |
(SSEInt(_), SSEUp) => return,
(_, _) => newv
};
cls[i] = to_write;
}
fn classify_struct(tys: &[Type],
cls: &mut [RegClass],
i: usize,
off: usize,
packed: bool) {
let mut field_off = off;
for ty in tys {
if!packed {
field_off = align(field_off, *ty);
}
classify(*ty, cls, i, field_off);
field_off += ty_size(*ty);
}
}
fn classify(ty: Type,
cls: &mut [RegClass], ix: usize,
off: usize) {
let t_align = ty_align(ty);
let t_size = ty_size(ty);
let misalign = off % t_align;
if misalign!= 0 {
let mut i = off / 8;
let e = (off + t_size + 7) / 8;
while i < e {
unify(cls, ix + i, Memory);
i += 1;
}
return;
}
match ty.kind() {
Integer |
Pointer => {
unify(cls, ix + off / 8, Int);
}
Float => {
if off % 8 == 4 {
unify(cls, ix + off / 8, SSEFv);
} else {
unify(cls, ix + off / 8, SSEFs);
}
}
Double => {
unify(cls, ix + off / 8, SSEDs);
}
Struct => {
classify_struct(&ty.field_types(), cls, ix, off, ty.is_packed());
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut i = 0;
while i < len {
classify(elt, cls, ix, off + i * eltsz);
i += 1;
}
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut reg = match elt.kind() {
Integer => SSEInt(elt.int_width()),
Float => SSEFv,
Double => SSEDv,
_ => panic!("classify: unhandled vector element type")
};
let mut i = 0;
while i < len {
unify(cls, ix + (off + i * eltsz) / 8, reg);
// everything after the first one is the upper
// half of a register.
reg = SSEUp;
i += 1;
}
}
_ => panic!("classify: unhandled type")
}
}
fn fixup(ty: Type, cls: &mut [RegClass]) {
let mut i = 0;
let ty_kind = ty.kind();
let e = cls.len();
if cls.len() > 2 && (ty_kind == Struct || ty_kind == Array || ty_kind == Vector) {
if cls[i].is_sse() {
i += 1;
while i < e {
if cls[i]!= SSEUp {
all_mem(cls);
return;
}
i += 1;
}
} else {
all_mem(cls);
return
}
} else {
while i < e {
if cls[i] == Memory {
all_mem(cls);
return;
}
if cls[i] == X87Up {
// for darwin
// cls[i] = SSEDs;
all_mem(cls);
return;
}
if cls[i] == SSEUp {
cls[i] = SSEDv;
} else if cls[i].is_sse() {
i += 1;
while i!= e && cls[i] == SSEUp { i += 1; }
} else if cls[i] == X87 {
i += 1;
while i!= e && cls[i] == X87Up { i += 1; }
} else {
i += 1;
}
}
}
}
let words = (ty_size(ty) + 7) / 8;
let mut cls: Vec<_> = repeat(NoClass).take(words).collect();
if words > 4 {
all_mem(&mut cls);
return cls;
}
classify(ty, &mut cls, 0, 0);
fixup(ty, &mut cls);
return cls;
}
fn llreg_ty(ccx: &CrateContext, cls: &[RegClass]) -> Type {
fn llvec_len(cls: &[RegClass]) -> usize {
let mut len = 1;
for c in cls {
if *c!= SSEUp {
break;
}
len += 1;
}
return len;
}
let mut tys = Vec::new();
let mut i = 0;
let e = cls.len();
while i < e {
match cls[i] {
Int => {
tys.push(Type::i64(ccx));
}
SSEFv | SSEDv | SSEInt(_) => {
let (elts_per_word, elt_ty) = match cls[i] {
SSEFv => (2, Type::f32(ccx)),
SSEDv => (1, Type::f64(ccx)),
SSEInt(bits) => {
assert!(bits == 8 || bits == 16 || bits == 32 || bits == 64,
"llreg_ty: unsupported SSEInt width {}", bits);
(64 / bits, Type::ix(ccx, bits))
}
_ => unreachable!(),
};
let vec_len = llvec_len(&cls[i + 1..]);
let vec_ty = Type::vector(&elt_ty, vec_len as u64 * elts_per_word);
tys.push(vec_ty);
i += vec_len;
continue;
}
SSEFs => {
tys.push(Type::f32(ccx));
}
SSEDs => {
tys.push(Type::f64(ccx));
}
_ => panic!("llregtype: unhandled class")
}
i += 1;
}
if tys.len() == 1 && tys[0].kind() == Vector {
// if the type contains only a vector, pass it as that vector.
tys[0]
} else {
Type::struct_(ccx, &tys, false)
}
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
fn x86_64_ty<F>(ccx: &CrateContext,
ty: Type,
is_mem_cls: F,
ind_attr: Attribute)
-> ArgType where
F: FnOnce(&[RegClass]) -> bool,
{
if!ty.is_reg_ty() {
let cls = classify_ty(ty);
if is_mem_cls(&cls) {
ArgType::indirect(ty, Some(ind_attr))
} else {
ArgType::direct(ty,
Some(llreg_ty(ccx, &cls)),
None,
None)
}
} else {
let attr = if ty == Type::i1(ccx) { Some(Attribute::ZExt) } else { None };
ArgType::direct(ty, None, None, attr)
}
}
let mut arg_tys = Vec::new();
for t in atys {
let ty = x86_64_ty(ccx, *t, |cls| cls.is_pass_byval(), Attribute::ByVal);
arg_tys.push(ty);
}
let ret_ty = if ret_def {
x86_64_ty(ccx, rty, |cls| cls.is_ret_bysret(), Attribute::StructRet)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
} |
fn is_ret_bysret(&self) -> bool { | random_line_split |
cabi_x86_64.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// The classification code for the x86_64 ABI is taken from the clay language
// https://github.com/jckarter/clay/blob/master/compiler/src/externals.cpp
#![allow(non_upper_case_globals)]
use self::RegClass::*;
use llvm::{Integer, Pointer, Float, Double};
use llvm::{Struct, Array, Attribute, Vector};
use trans::cabi::{ArgType, FnType};
use trans::context::CrateContext;
use trans::type_::Type;
use std::cmp;
use std::iter::repeat;
#[derive(Clone, Copy, PartialEq)]
enum RegClass {
NoClass,
Int,
SSEFs,
SSEFv,
SSEDs,
SSEDv,
SSEInt(/* bitwidth */ u64),
/// Data that can appear in the upper half of an SSE register.
SSEUp,
X87,
X87Up,
ComplexX87,
Memory
}
trait TypeMethods {
fn is_reg_ty(&self) -> bool;
}
impl TypeMethods for Type {
fn is_reg_ty(&self) -> bool {
match self.kind() {
Integer | Pointer | Float | Double => true,
_ => false
}
}
}
impl RegClass {
fn is_sse(&self) -> bool |
}
trait ClassList {
fn is_pass_byval(&self) -> bool;
fn is_ret_bysret(&self) -> bool;
}
impl ClassList for [RegClass] {
fn is_pass_byval(&self) -> bool {
if self.is_empty() { return false; }
let class = self[0];
class == Memory
|| class == X87
|| class == ComplexX87
}
fn is_ret_bysret(&self) -> bool {
if self.is_empty() { return false; }
self[0] == Memory
}
}
fn classify_ty(ty: Type) -> Vec<RegClass> {
fn align(off: usize, ty: Type) -> usize {
let a = ty_align(ty);
return (off + a - 1) / a * a;
}
fn ty_align(ty: Type) -> usize {
match ty.kind() {
Integer => ((ty.int_width() as usize) + 7) / 8,
Pointer => 8,
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)
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
ty_align(elt) * len
}
_ => panic!("ty_align: unhandled type")
}
}
fn ty_size(ty: Type) -> usize {
match ty.kind() {
Integer => (ty.int_width() as usize + 7) / 8,
Pointer => 8,
Float => 4,
Double => 8,
Struct => {
let str_tys = ty.field_types();
if ty.is_packed() {
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
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
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => panic!("ty_size: unhandled type")
}
}
fn all_mem(cls: &mut [RegClass]) {
for elt in cls {
*elt = Memory;
}
}
fn unify(cls: &mut [RegClass],
i: usize,
newv: RegClass) {
if cls[i] == newv { return }
let to_write = match (cls[i], newv) {
(NoClass, _) => newv,
(_, NoClass) => return,
(Memory, _) |
(_, Memory) => Memory,
(Int, _) |
(_, Int) => Int,
(X87, _) |
(X87Up, _) |
(ComplexX87, _) |
(_, X87) |
(_, X87Up) |
(_, ComplexX87) => Memory,
(SSEFv, SSEUp) |
(SSEFs, SSEUp) |
(SSEDv, SSEUp) |
(SSEDs, SSEUp) |
(SSEInt(_), SSEUp) => return,
(_, _) => newv
};
cls[i] = to_write;
}
fn classify_struct(tys: &[Type],
cls: &mut [RegClass],
i: usize,
off: usize,
packed: bool) {
let mut field_off = off;
for ty in tys {
if!packed {
field_off = align(field_off, *ty);
}
classify(*ty, cls, i, field_off);
field_off += ty_size(*ty);
}
}
fn classify(ty: Type,
cls: &mut [RegClass], ix: usize,
off: usize) {
let t_align = ty_align(ty);
let t_size = ty_size(ty);
let misalign = off % t_align;
if misalign!= 0 {
let mut i = off / 8;
let e = (off + t_size + 7) / 8;
while i < e {
unify(cls, ix + i, Memory);
i += 1;
}
return;
}
match ty.kind() {
Integer |
Pointer => {
unify(cls, ix + off / 8, Int);
}
Float => {
if off % 8 == 4 {
unify(cls, ix + off / 8, SSEFv);
} else {
unify(cls, ix + off / 8, SSEFs);
}
}
Double => {
unify(cls, ix + off / 8, SSEDs);
}
Struct => {
classify_struct(&ty.field_types(), cls, ix, off, ty.is_packed());
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut i = 0;
while i < len {
classify(elt, cls, ix, off + i * eltsz);
i += 1;
}
}
Vector => {
let len = ty.vector_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
let mut reg = match elt.kind() {
Integer => SSEInt(elt.int_width()),
Float => SSEFv,
Double => SSEDv,
_ => panic!("classify: unhandled vector element type")
};
let mut i = 0;
while i < len {
unify(cls, ix + (off + i * eltsz) / 8, reg);
// everything after the first one is the upper
// half of a register.
reg = SSEUp;
i += 1;
}
}
_ => panic!("classify: unhandled type")
}
}
fn fixup(ty: Type, cls: &mut [RegClass]) {
let mut i = 0;
let ty_kind = ty.kind();
let e = cls.len();
if cls.len() > 2 && (ty_kind == Struct || ty_kind == Array || ty_kind == Vector) {
if cls[i].is_sse() {
i += 1;
while i < e {
if cls[i]!= SSEUp {
all_mem(cls);
return;
}
i += 1;
}
} else {
all_mem(cls);
return
}
} else {
while i < e {
if cls[i] == Memory {
all_mem(cls);
return;
}
if cls[i] == X87Up {
// for darwin
// cls[i] = SSEDs;
all_mem(cls);
return;
}
if cls[i] == SSEUp {
cls[i] = SSEDv;
} else if cls[i].is_sse() {
i += 1;
while i!= e && cls[i] == SSEUp { i += 1; }
} else if cls[i] == X87 {
i += 1;
while i!= e && cls[i] == X87Up { i += 1; }
} else {
i += 1;
}
}
}
}
let words = (ty_size(ty) + 7) / 8;
let mut cls: Vec<_> = repeat(NoClass).take(words).collect();
if words > 4 {
all_mem(&mut cls);
return cls;
}
classify(ty, &mut cls, 0, 0);
fixup(ty, &mut cls);
return cls;
}
fn llreg_ty(ccx: &CrateContext, cls: &[RegClass]) -> Type {
fn llvec_len(cls: &[RegClass]) -> usize {
let mut len = 1;
for c in cls {
if *c!= SSEUp {
break;
}
len += 1;
}
return len;
}
let mut tys = Vec::new();
let mut i = 0;
let e = cls.len();
while i < e {
match cls[i] {
Int => {
tys.push(Type::i64(ccx));
}
SSEFv | SSEDv | SSEInt(_) => {
let (elts_per_word, elt_ty) = match cls[i] {
SSEFv => (2, Type::f32(ccx)),
SSEDv => (1, Type::f64(ccx)),
SSEInt(bits) => {
assert!(bits == 8 || bits == 16 || bits == 32 || bits == 64,
"llreg_ty: unsupported SSEInt width {}", bits);
(64 / bits, Type::ix(ccx, bits))
}
_ => unreachable!(),
};
let vec_len = llvec_len(&cls[i + 1..]);
let vec_ty = Type::vector(&elt_ty, vec_len as u64 * elts_per_word);
tys.push(vec_ty);
i += vec_len;
continue;
}
SSEFs => {
tys.push(Type::f32(ccx));
}
SSEDs => {
tys.push(Type::f64(ccx));
}
_ => panic!("llregtype: unhandled class")
}
i += 1;
}
if tys.len() == 1 && tys[0].kind() == Vector {
// if the type contains only a vector, pass it as that vector.
tys[0]
} else {
Type::struct_(ccx, &tys, false)
}
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
fn x86_64_ty<F>(ccx: &CrateContext,
ty: Type,
is_mem_cls: F,
ind_attr: Attribute)
-> ArgType where
F: FnOnce(&[RegClass]) -> bool,
{
if!ty.is_reg_ty() {
let cls = classify_ty(ty);
if is_mem_cls(&cls) {
ArgType::indirect(ty, Some(ind_attr))
} else {
ArgType::direct(ty,
Some(llreg_ty(ccx, &cls)),
None,
None)
}
} else {
let attr = if ty == Type::i1(ccx) { Some(Attribute::ZExt) } else { None };
ArgType::direct(ty, None, None, attr)
}
}
let mut arg_tys = Vec::new();
for t in atys {
let ty = x86_64_ty(ccx, *t, |cls| cls.is_pass_byval(), Attribute::ByVal);
arg_tys.push(ty);
}
let ret_ty = if ret_def {
x86_64_ty(ccx, rty, |cls| cls.is_ret_bysret(), Attribute::StructRet)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
| {
match *self {
SSEFs | SSEFv | SSEDs | SSEDv | SSEInt(_) => true,
_ => false
}
} | identifier_body |
lib.rs | #[macro_use(expect)]
extern crate expectest;
extern crate sql;
pub mod lexer;
pub mod parser;
pub mod query_typer;
pub mod query_validator; | use sql::parser::parse;
use sql::query_typer::type_inferring_old;
use sql::query_validator::validate_old;
use sql::query_executer::{execute, ExecutionResult};
use sql::data_manager::DataManager;
use sql::catalog_manager::CatalogManager;
pub fn evaluate_query(query: &str, data_manager: &DataManager, catalog_manager: &CatalogManager) -> Result<ExecutionResult, String> {
tokenize(query)
.and_then(parse)
.and_then(|statement| type_inferring_old(catalog_manager, statement))
.and_then(|statement| validate_old(catalog_manager, statement))
.and_then(|statement| execute(catalog_manager, data_manager, statement))
} | pub mod query_executer;
pub mod catalog_manager;
pub mod data_manager;
use sql::lexer::tokenize; | random_line_split |
lib.rs | #[macro_use(expect)]
extern crate expectest;
extern crate sql;
pub mod lexer;
pub mod parser;
pub mod query_typer;
pub mod query_validator;
pub mod query_executer;
pub mod catalog_manager;
pub mod data_manager;
use sql::lexer::tokenize;
use sql::parser::parse;
use sql::query_typer::type_inferring_old;
use sql::query_validator::validate_old;
use sql::query_executer::{execute, ExecutionResult};
use sql::data_manager::DataManager;
use sql::catalog_manager::CatalogManager;
pub fn evaluate_query(query: &str, data_manager: &DataManager, catalog_manager: &CatalogManager) -> Result<ExecutionResult, String> | {
tokenize(query)
.and_then(parse)
.and_then(|statement| type_inferring_old(catalog_manager, statement))
.and_then(|statement| validate_old(catalog_manager, statement))
.and_then(|statement| execute(catalog_manager, data_manager, statement))
} | identifier_body |
|
lib.rs | #[macro_use(expect)]
extern crate expectest;
extern crate sql;
pub mod lexer;
pub mod parser;
pub mod query_typer;
pub mod query_validator;
pub mod query_executer;
pub mod catalog_manager;
pub mod data_manager;
use sql::lexer::tokenize;
use sql::parser::parse;
use sql::query_typer::type_inferring_old;
use sql::query_validator::validate_old;
use sql::query_executer::{execute, ExecutionResult};
use sql::data_manager::DataManager;
use sql::catalog_manager::CatalogManager;
pub fn | (query: &str, data_manager: &DataManager, catalog_manager: &CatalogManager) -> Result<ExecutionResult, String> {
tokenize(query)
.and_then(parse)
.and_then(|statement| type_inferring_old(catalog_manager, statement))
.and_then(|statement| validate_old(catalog_manager, statement))
.and_then(|statement| execute(catalog_manager, data_manager, statement))
}
| evaluate_query | identifier_name |
project-cache-issue-31849.rs | // run-pass
// Regression test for #31849: the problem here was actually a performance
// cliff, but I'm adding the test for reference.
pub trait Upcast<T> {
fn upcast(self) -> T;
}
impl<S1, S2, T1, T2> Upcast<(T1, T2)> for (S1,S2)
where S1: Upcast<T1>,
S2: Upcast<T2>,
{
fn upcast(self) -> (T1, T2) { (self.0.upcast(), self.1.upcast()) }
}
impl Upcast<()> for ()
{
fn upcast(self) -> () { () }
}
pub trait ToStatic {
type Static:'static;
fn to_static(self) -> Self::Static where Self: Sized;
}
impl<T, U> ToStatic for (T, U)
where T: ToStatic,
U: ToStatic
{
type Static = (T::Static, U::Static);
fn to_static(self) -> Self::Static { (self.0.to_static(), self.1.to_static()) }
}
impl ToStatic for ()
{
type Static = ();
fn to_static(self) -> () { () }
}
trait Factory {
type Output; |
impl<S,T> Factory for (S, T)
where S: Factory,
T: Factory,
S::Output: ToStatic,
<S::Output as ToStatic>::Static: Upcast<S::Output>,
{
type Output = (S::Output, T::Output);
fn build(&self) -> Self::Output { (self.0.build().to_static().upcast(), self.1.build()) }
}
impl Factory for () {
type Output = ();
fn build(&self) -> Self::Output { () }
}
fn main() {
// More parens, more time.
let it = ((((((((((),()),()),()),()),()),()),()),()),());
it.build();
} | fn build(&self) -> Self::Output;
} | random_line_split |
project-cache-issue-31849.rs | // run-pass
// Regression test for #31849: the problem here was actually a performance
// cliff, but I'm adding the test for reference.
pub trait Upcast<T> {
fn upcast(self) -> T;
}
impl<S1, S2, T1, T2> Upcast<(T1, T2)> for (S1,S2)
where S1: Upcast<T1>,
S2: Upcast<T2>,
{
fn upcast(self) -> (T1, T2) |
}
impl Upcast<()> for ()
{
fn upcast(self) -> () { () }
}
pub trait ToStatic {
type Static:'static;
fn to_static(self) -> Self::Static where Self: Sized;
}
impl<T, U> ToStatic for (T, U)
where T: ToStatic,
U: ToStatic
{
type Static = (T::Static, U::Static);
fn to_static(self) -> Self::Static { (self.0.to_static(), self.1.to_static()) }
}
impl ToStatic for ()
{
type Static = ();
fn to_static(self) -> () { () }
}
trait Factory {
type Output;
fn build(&self) -> Self::Output;
}
impl<S,T> Factory for (S, T)
where S: Factory,
T: Factory,
S::Output: ToStatic,
<S::Output as ToStatic>::Static: Upcast<S::Output>,
{
type Output = (S::Output, T::Output);
fn build(&self) -> Self::Output { (self.0.build().to_static().upcast(), self.1.build()) }
}
impl Factory for () {
type Output = ();
fn build(&self) -> Self::Output { () }
}
fn main() {
// More parens, more time.
let it = ((((((((((),()),()),()),()),()),()),()),()),());
it.build();
}
| { (self.0.upcast(), self.1.upcast()) } | identifier_body |
project-cache-issue-31849.rs | // run-pass
// Regression test for #31849: the problem here was actually a performance
// cliff, but I'm adding the test for reference.
pub trait Upcast<T> {
fn upcast(self) -> T;
}
impl<S1, S2, T1, T2> Upcast<(T1, T2)> for (S1,S2)
where S1: Upcast<T1>,
S2: Upcast<T2>,
{
fn upcast(self) -> (T1, T2) { (self.0.upcast(), self.1.upcast()) }
}
impl Upcast<()> for ()
{
fn upcast(self) -> () { () }
}
pub trait ToStatic {
type Static:'static;
fn to_static(self) -> Self::Static where Self: Sized;
}
impl<T, U> ToStatic for (T, U)
where T: ToStatic,
U: ToStatic
{
type Static = (T::Static, U::Static);
fn | (self) -> Self::Static { (self.0.to_static(), self.1.to_static()) }
}
impl ToStatic for ()
{
type Static = ();
fn to_static(self) -> () { () }
}
trait Factory {
type Output;
fn build(&self) -> Self::Output;
}
impl<S,T> Factory for (S, T)
where S: Factory,
T: Factory,
S::Output: ToStatic,
<S::Output as ToStatic>::Static: Upcast<S::Output>,
{
type Output = (S::Output, T::Output);
fn build(&self) -> Self::Output { (self.0.build().to_static().upcast(), self.1.build()) }
}
impl Factory for () {
type Output = ();
fn build(&self) -> Self::Output { () }
}
fn main() {
// More parens, more time.
let it = ((((((((((),()),()),()),()),()),()),()),()),());
it.build();
}
| to_static | identifier_name |
prime_field.rs | use normalize::*;
use pack::Pack;
use rand::Rand;
use std::marker::Sized;
use std::ops::Add;
use std::ops::AddAssign;
use std::ops::Div;
use std::ops::DivAssign;
use std::ops::Mul;
use std::ops::MulAssign;
use std::ops::Neg;
use std::ops::Sub;
use std::ops::SubAssign;
| Div<Self, Output = Self> + DivAssign<Self> +
MulAssign<i32> + MulAssign<i16> + MulAssign<i8> + MulAssign<Self> +
Mul<i32, Output = Self> + Mul<i16, Output = Self> +
Mul<i8, Output = Self> + Mul<Self, Output = Self> +
Neg<Output = Self> + Normalize + NormalizeEq + Pack + Rand + Sized +
SubAssign<i32> + SubAssign<i16> + SubAssign<i8> + SubAssign<Self> +
Sub<i32, Output = Self> + Sub<i16, Output = Self> +
Sub<i8, Output = Self> + Sub<Self, Output = Self> {
/// Get the number of bits in the number.
fn nbits() -> usize;
/// Get the bit given by idx. This normalizes the internal representation.
fn bit(&mut self, idx: usize) -> bool;
/// Get the bit given by idx, assuming the internal representation
/// is already normalized.
fn bit_normalized(&self, idx: usize) -> bool;
/// Set every bit of this number to the given bit.
fn fill(&mut self, bit: bool);
/// Generate a mask consisting entirely of the given bit.
fn filled(bit: bool) -> Self;
/// Normalize both arguments and bitwise-and assign.
fn normalize_bitand(&mut self, rhs: &mut Self);
/// Normalize self and bitwise-and assign.
fn normalize_self_bitand(&mut self, rhs: &Self);
/// Bitwise-and assign with both arguments normalized.
fn normalized_bitand(&mut self, rhs: &Self);
/// Normalize both arguments and bitwise-or assign.
fn normalize_bitor(&mut self, rhs: &mut Self);
/// Normalize self and bitwise-or assign.
fn normalize_self_bitor(&mut self, rhs: &Self);
/// Bitwise-or assign with both arguments normalized.
fn normalized_bitor(&mut self, rhs: &Self);
/// Get the representation of the value 0.
fn zero() -> Self;
/// Get the representation of the value 1.
fn one() -> Self;
/// Get the representation of the value -1.
fn m_one() -> Self;
/// Get the representation of the modulus.
fn modulus() -> Self;
/// In-place square.
fn square(&mut self);
/// Functional square.
fn squared(&self) -> Self;
/// In-place multiplicative inverse.
fn invert(&mut self);
/// Functional multiplicative inverse.
fn inverted(&self) -> Self;
/// Legendre symbol. This is 1 for a quadratic residue (meaning a
/// square root value exists), and -1 otherwise.
fn legendre(&self) -> Self;
/// Compute the square root. This has meaning only for quadratic
/// residue (legendre returns 1). Non-residues return a garbage
/// value.
fn sqrt(&self) -> Self;
/// Add a single digit (represented as an i32) in-place.
fn small_add_assign(&mut self, b: i32);
/// Add a single digit (represented as an i32).
fn small_add(&self, b: i32) -> Self;
/// Subtract a single digit (represented as an i32) in place.
fn small_sub_assign(&mut self, b: i32);
/// Subtract a single digit (represented as an i32).
fn small_sub(&self, b: i32) -> Self;
/// Multiply in-place by a single digit (represented as an i32).
fn small_mul_assign(&mut self, b: i32);
/// Multiply by a single digit (represented as an i32).
fn small_mul(&self, b: i32) -> Self;
}
/// Bitmasks corresponding to a PrimeField type. These are used as
/// arguments to bitwise and operations to retain or clear entire
/// PrimeField elements at once.
///
/// The primary use of this is to replace some branch operations with
/// bitwise tricks to eliminate data-dependent control-flow branches.
pub trait PrimeFieldMask {
/// Set every bit of this number to the given bit.
fn fill(&mut self, bit: bool);
/// Generate a mask consisting entirely of the given bit.
fn filled(bit: bool) -> Self;
} | /// Operations on prime fields.
pub trait PrimeField : Add<i32, Output = Self> + Add<i16, Output = Self> +
Add<i8, Output = Self> + Add<Self, Output = Self> +
AddAssign<i32> + AddAssign<i16> + AddAssign<i8> + AddAssign<Self> + | random_line_split |
lib.rs | //! D-Bus bindings for Rust
//!
//! [D-Bus](http://dbus.freedesktop.org/) is a message bus, and is mainly used in Linux
//! for communication between processes. It is present by default on almost every
//! Linux distribution out there, and runs in two instances - one per session, and one
//! system-wide.
//!
//! See the examples directory for some examples to get you started.
extern crate libc;
pub use ffi::DBusBusType as BusType;
pub use ffi::DBusNameFlag as NameFlag;
pub use ffi::DBusRequestNameReply as RequestNameReply;
pub use ffi::DBusReleaseNameReply as ReleaseNameReply;
pub use ffi::DBusMessageType as MessageType;
pub use message::{Message, MessageItem, FromMessageItem, OwnedFd, OPath, ArrayError};
pub use prop::PropHandler;
pub use prop::Props;
/// A TypeSig describes the type of a MessageItem.
pub type TypeSig<'a> = std::borrow::Cow<'a, str>;
use std::ffi::{CString, CStr};
use std::ptr::{self};
use std::collections::LinkedList;
use std::cell::{Cell, RefCell};
mod ffi;
mod message;
mod prop;
mod objpath;
/// Contains functionality for the "server" of a D-Bus object. A remote application can
/// introspect this object and call methods on it.
pub mod obj {
pub use objpath::{ObjectPath, Interface, Property, Signal, Argument};
pub use objpath::{Method, MethodHandler, MethodResult};
pub use objpath::{PropertyROHandler, PropertyRWHandler, PropertyWOHandler, PropertyGetResult, PropertySetResult};
}
static INITDBUS: std::sync::Once = std::sync::ONCE_INIT;
fn init_dbus() {
INITDBUS.call_once(|| {
if unsafe { ffi::dbus_threads_init_default() } == 0 {
panic!("Out of memory when trying to initialize D-Bus library!");
}
});
}
/// D-Bus Error wrapper
pub struct Error {
e: ffi::DBusError,
}
unsafe impl Send for Error {}
fn c_str_to_slice(c: & *const libc::c_char) -> Option<&str> {
if *c == ptr::null() { None }
else { std::str::from_utf8( unsafe { CStr::from_ptr(*c).to_bytes() }).ok() }
}
fn to_c_str(n: &str) -> CString { CString::new(n.as_bytes()).unwrap() }
impl Error {
pub fn new_custom(name: &str, message: &str) -> Error {
let n = to_c_str(name);
let m = to_c_str(&message.replace("%","%%"));
let mut e = Error::empty();
unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
e
}
fn empty() -> Error {
init_dbus();
let mut e = ffi::DBusError {
name: ptr::null(),
message: ptr::null(),
dummy: 0,
padding1: ptr::null()
};
unsafe { ffi::dbus_error_init(&mut e); }
Error{ e: e }
}
/// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
pub fn name(&self) -> Option<&str> {
c_str_to_slice(&self.e.name)
}
/// Custom message, e g 'Could not find a matching object path'
pub fn message(&self) -> Option<&str> {
c_str_to_slice(&self.e.message)
}
fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
}
impl Drop for Error {
fn drop(&mut self) {
unsafe { ffi::dbus_error_free(&mut self.e); }
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
self.name().unwrap_or(""))
}
}
impl std::error::Error for Error {
fn description(&self) -> &str { "D-Bus error" }
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
if let Some(x) = self.message() {
write!(f, "{:?}", x.to_string())
} else { Ok(()) }
}
}
/// When listening for incoming events on the D-Bus, this enum will tell you what type
/// of incoming event has happened.
#[derive(Debug)]
pub enum ConnectionItem {
Nothing,
MethodCall(Message),
Signal(Message),
}
/// ConnectionItem iterator
pub struct ConnectionItems<'a> {
c: &'a Connection,
timeout_ms: i32,
}
impl<'a> Iterator for ConnectionItems<'a> {
type Item = ConnectionItem;
fn next(&mut self) -> Option<ConnectionItem> {
loop {
let i = self.c.i.pending_items.borrow_mut().pop_front();
if i.is_some() { return i; }
let r = unsafe { ffi::dbus_connection_read_write_dispatch(self.c.conn(), self.timeout_ms as libc::c_int) };
if!self.c.i.pending_items.borrow().is_empty() { continue };
if r == 0 { return None; }
return Some(ConnectionItem::Nothing);
}
}
}
/* Since we register callbacks with userdata pointers,
we need to make sure the connection pointer does not move around.
Hence this extra indirection. */
struct IConnection {
conn: Cell<*mut ffi::DBusConnection>,
pending_items: RefCell<LinkedList<ConnectionItem>>,
}
/// A D-Bus connection. Start here if you want to get on the D-Bus!
pub struct Connection {
i: Box<IConnection>,
}
extern "C" fn filter_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
let mtype: ffi::DBusMessageType = unsafe { std::mem::transmute(ffi::dbus_message_get_type(msg)) };
let r = match mtype {
ffi::DBusMessageType::Signal => {
i.pending_items.borrow_mut().push_back(ConnectionItem::Signal(m));
ffi::DBusHandlerResult::Handled
}
_ => ffi::DBusHandlerResult::NotYetHandled,
};
r
}
extern "C" fn object_path_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
i.pending_items.borrow_mut().push_back(ConnectionItem::MethodCall(m));
ffi::DBusHandlerResult::Handled
}
impl Connection {
#[inline(always)]
fn conn(&self) -> *mut ffi::DBusConnection {
self.i.conn.get()
}
/// Creates a new D-Bus connection.
pub fn get_private(bus: BusType) -> Result<Connection, Error> {
let mut e = Error::empty();
let conn = unsafe { ffi::dbus_bus_get_private(bus, e.get_mut()) };
if conn == ptr::null_mut() {
return Err(e)
}
let c = Connection { i: Box::new(IConnection { conn: Cell::new(conn), pending_items: RefCell::new(LinkedList::new()) })};
/* No, we don't want our app to suddenly quit if dbus goes down */
unsafe { ffi::dbus_connection_set_exit_on_disconnect(conn, 0) };
assert!(unsafe {
ffi::dbus_connection_add_filter(c.conn(), Some(filter_message_cb as ffi::DBusCallback), std::mem::transmute(&*c.i), None)
}!= 0);
Ok(c)
}
/// Sends a message over the D-Bus and waits for a reply.
/// This is usually used for method calls.
pub fn send_with_reply_and_block(&self, msg: Message, timeout_ms: i32) -> Result<Message, Error> {
let mut e = Error::empty();
let response = unsafe {
ffi::dbus_connection_send_with_reply_and_block(self.conn(), message::get_message_ptr(&msg),
timeout_ms as libc::c_int, e.get_mut())
};
if response == ptr::null_mut() {
return Err(e);
}
Ok(message::message_from_ptr(response, false))
}
/// Sends a message over the D-Bus without waiting. Useful for sending signals and method call replies.
pub fn send(&self, msg: Message) -> Result<u32,()> {
let mut serial = 0u32;
let r = unsafe { ffi::dbus_connection_send(self.conn(), message::get_message_ptr(&msg), &mut serial) };
if r == 0 { return Err(()); }
unsafe { ffi::dbus_connection_flush(self.conn()) };
Ok(serial)
}
pub fn unique_name(&self) -> String {
let c = unsafe { ffi::dbus_bus_get_unique_name(self.conn()) };
c_str_to_slice(&c).unwrap_or("").to_string()
}
// Check if there are new incoming events
pub fn iter(&self, timeout_ms: i32) -> ConnectionItems {
ConnectionItems {
c: self,
timeout_ms: timeout_ms,
}
}
pub fn register_object_path(&self, path: &str) -> Result<(), Error> {
let mut e = Error::empty();
let p = to_c_str(path);
let vtable = ffi::DBusObjectPathVTable {
unregister_function: None,
message_function: Some(object_path_message_cb as ffi::DBusCallback),
dbus_internal_pad1: None,
dbus_internal_pad2: None,
dbus_internal_pad3: None,
dbus_internal_pad4: None,
};
let r = unsafe {
let user_data: *mut libc::c_void = std::mem::transmute(&*self.i);
ffi::dbus_connection_try_register_object_path(self.conn(), p.as_ptr(), &vtable, user_data, e.get_mut())
};
if r == 0 { Err(e) } else { Ok(()) }
}
pub fn unregister_object_path(&self, path: &str) {
let p = to_c_str(path);
let r = unsafe { ffi::dbus_connection_unregister_object_path(self.conn(), p.as_ptr()) };
if r == 0 { panic!("Out of memory"); }
}
pub fn list_registered_object_paths(&self, path: &str) -> Vec<String> {
let p = to_c_str(path);
let mut clist: *mut *mut libc::c_char = ptr::null_mut();
let r = unsafe { ffi::dbus_connection_list_registered(self.conn(), p.as_ptr(), &mut clist) };
if r == 0 |
let mut v = Vec::new();
let mut i = 0;
loop {
let s = unsafe {
let citer = clist.offset(i);
if *citer == ptr::null_mut() { break };
std::mem::transmute(citer)
};
v.push(format!("{}", c_str_to_slice(s).unwrap()));
i += 1;
}
unsafe { ffi::dbus_free_string_array(clist) };
v
}
pub fn register_name(&self, name: &str, flags: u32) -> Result<RequestNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_request_name(self.conn(), n.as_ptr(), flags, e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn release_name(&self, name: &str) -> Result<ReleaseNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_release_name(self.conn(), n.as_ptr(), e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn add_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_add_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
pub fn remove_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_remove_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
}
impl Drop for Connection {
fn drop(&mut self) {
unsafe {
ffi::dbus_connection_close(self.conn());
ffi::dbus_connection_unref(self.conn());
}
}
}
impl std::fmt::Debug for Connection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus Connection({})", self.unique_name())
}
}
#[cfg(test)]
mod test {
use super::{Connection, Message, BusType, MessageItem, ConnectionItem, NameFlag,
RequestNameReply, ReleaseNameReply};
#[test]
fn connection() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = c.unique_name();
assert!(n.starts_with(":1."));
println!("Connected to DBus, unique name: {}", n);
}
#[test]
fn invalid_message() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("foo.bar", "/", "foo.bar", "FooBar").unwrap();
let e = c.send_with_reply_and_block(m, 2000).err().unwrap();
assert!(e.name().unwrap() == "org.freedesktop.DBus.Error.ServiceUnknown");
}
#[test]
fn message_listnames() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
}
#[test]
fn message_namehasowner() {
let c = Connection::get_private(BusType::Session).unwrap();
let mut m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "NameHasOwner").unwrap();
m.append_items(&[MessageItem::Str("org.freedesktop.DBus".to_string())]);
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
assert_eq!(reply, vec!(MessageItem::Bool(true)));
}
#[test]
fn object_path() {
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
let thread = ::std::thread::spawn(move || {
let c = Connection::get_private(BusType::Session).unwrap();
c.register_object_path("/hello").unwrap();
// println!("Waiting...");
tx.send(c.unique_name()).unwrap();
for n in c.iter(1000) {
// println!("Found message... ({})", n);
match n {
ConnectionItem::MethodCall(ref m) => {
let reply = Message::new_method_return(m).unwrap();
c.send(reply).unwrap();
break;
}
_ => {}
}
}
c.unregister_object_path("/hello");
});
let c = Connection::get_private(BusType::Session).unwrap();
let n = rx.recv().unwrap();
let m = Message::new_method_call(&n, "/hello", "com.example.hello", "Hello").unwrap();
println!("Sending...");
let r = c.send_with_reply_and_block(m, 8000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
thread.join().unwrap();
}
#[test]
fn register_name() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = format!("com.example.hello.test.register_name");
assert_eq!(c.register_name(&n, NameFlag::ReplaceExisting as u32).unwrap(), RequestNameReply::PrimaryOwner);
assert_eq!(c.release_name(&n).unwrap(), ReleaseNameReply::Released);
}
#[test]
fn signal() {
let c = Connection::get_private(BusType::Session).unwrap();
let iface = "com.example.signaltest";
let mstr = format!("interface='{}',member='ThisIsASignal'", iface);
c.add_match(&mstr).unwrap();
let m = Message::new_signal("/mysignal", iface, "ThisIsASignal").unwrap();
let uname = c.unique_name();
c.send(m).unwrap();
for n in c.iter(1000) {
match n {
ConnectionItem::Signal(s) => {
let (_, p, i, m) = s.headers();
match (&*p.unwrap(), &*i.unwrap(), &*m.unwrap()) {
("/mysignal", "com.example.signaltest", "ThisIsASignal") => {
assert_eq!(s.sender().unwrap(), uname);
break;
},
(_, _, _) => println!("Other signal: {:?}", s.headers()),
}
}
_ => {},
}
}
c.remove_match(&mstr).unwrap();
}
}
| { panic!("Out of memory"); } | conditional_block |
lib.rs | //! D-Bus bindings for Rust
//!
//! [D-Bus](http://dbus.freedesktop.org/) is a message bus, and is mainly used in Linux
//! for communication between processes. It is present by default on almost every
//! Linux distribution out there, and runs in two instances - one per session, and one
//! system-wide.
//!
//! See the examples directory for some examples to get you started.
extern crate libc;
pub use ffi::DBusBusType as BusType;
pub use ffi::DBusNameFlag as NameFlag;
pub use ffi::DBusRequestNameReply as RequestNameReply;
pub use ffi::DBusReleaseNameReply as ReleaseNameReply;
pub use ffi::DBusMessageType as MessageType;
pub use message::{Message, MessageItem, FromMessageItem, OwnedFd, OPath, ArrayError};
pub use prop::PropHandler;
pub use prop::Props;
/// A TypeSig describes the type of a MessageItem.
pub type TypeSig<'a> = std::borrow::Cow<'a, str>;
use std::ffi::{CString, CStr};
use std::ptr::{self};
use std::collections::LinkedList;
use std::cell::{Cell, RefCell};
mod ffi;
mod message;
mod prop;
mod objpath;
/// Contains functionality for the "server" of a D-Bus object. A remote application can
/// introspect this object and call methods on it.
pub mod obj {
pub use objpath::{ObjectPath, Interface, Property, Signal, Argument};
pub use objpath::{Method, MethodHandler, MethodResult};
pub use objpath::{PropertyROHandler, PropertyRWHandler, PropertyWOHandler, PropertyGetResult, PropertySetResult};
}
static INITDBUS: std::sync::Once = std::sync::ONCE_INIT;
fn init_dbus() {
INITDBUS.call_once(|| {
if unsafe { ffi::dbus_threads_init_default() } == 0 {
panic!("Out of memory when trying to initialize D-Bus library!");
}
});
}
/// D-Bus Error wrapper
pub struct Error {
e: ffi::DBusError,
}
unsafe impl Send for Error {}
fn c_str_to_slice(c: & *const libc::c_char) -> Option<&str> {
if *c == ptr::null() { None }
else { std::str::from_utf8( unsafe { CStr::from_ptr(*c).to_bytes() }).ok() }
}
fn to_c_str(n: &str) -> CString { CString::new(n.as_bytes()).unwrap() }
impl Error {
pub fn new_custom(name: &str, message: &str) -> Error {
let n = to_c_str(name);
let m = to_c_str(&message.replace("%","%%"));
let mut e = Error::empty();
unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
e
}
fn empty() -> Error {
init_dbus();
let mut e = ffi::DBusError {
name: ptr::null(),
message: ptr::null(),
dummy: 0,
padding1: ptr::null()
};
unsafe { ffi::dbus_error_init(&mut e); }
Error{ e: e }
}
/// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
pub fn name(&self) -> Option<&str> {
c_str_to_slice(&self.e.name)
}
/// Custom message, e g 'Could not find a matching object path'
pub fn message(&self) -> Option<&str> {
c_str_to_slice(&self.e.message)
}
fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
}
impl Drop for Error {
fn drop(&mut self) {
unsafe { ffi::dbus_error_free(&mut self.e); }
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
self.name().unwrap_or(""))
}
}
impl std::error::Error for Error {
fn description(&self) -> &str { "D-Bus error" }
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
if let Some(x) = self.message() {
write!(f, "{:?}", x.to_string())
} else { Ok(()) }
}
}
/// When listening for incoming events on the D-Bus, this enum will tell you what type
/// of incoming event has happened.
#[derive(Debug)]
pub enum ConnectionItem {
Nothing,
MethodCall(Message),
Signal(Message),
}
/// ConnectionItem iterator
pub struct ConnectionItems<'a> {
c: &'a Connection,
timeout_ms: i32,
}
impl<'a> Iterator for ConnectionItems<'a> {
type Item = ConnectionItem;
fn next(&mut self) -> Option<ConnectionItem> {
loop {
let i = self.c.i.pending_items.borrow_mut().pop_front();
if i.is_some() { return i; }
let r = unsafe { ffi::dbus_connection_read_write_dispatch(self.c.conn(), self.timeout_ms as libc::c_int) };
if!self.c.i.pending_items.borrow().is_empty() { continue };
if r == 0 { return None; }
return Some(ConnectionItem::Nothing);
}
}
}
/* Since we register callbacks with userdata pointers,
we need to make sure the connection pointer does not move around.
Hence this extra indirection. */
struct | {
conn: Cell<*mut ffi::DBusConnection>,
pending_items: RefCell<LinkedList<ConnectionItem>>,
}
/// A D-Bus connection. Start here if you want to get on the D-Bus!
pub struct Connection {
i: Box<IConnection>,
}
extern "C" fn filter_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
let mtype: ffi::DBusMessageType = unsafe { std::mem::transmute(ffi::dbus_message_get_type(msg)) };
let r = match mtype {
ffi::DBusMessageType::Signal => {
i.pending_items.borrow_mut().push_back(ConnectionItem::Signal(m));
ffi::DBusHandlerResult::Handled
}
_ => ffi::DBusHandlerResult::NotYetHandled,
};
r
}
extern "C" fn object_path_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
i.pending_items.borrow_mut().push_back(ConnectionItem::MethodCall(m));
ffi::DBusHandlerResult::Handled
}
impl Connection {
#[inline(always)]
fn conn(&self) -> *mut ffi::DBusConnection {
self.i.conn.get()
}
/// Creates a new D-Bus connection.
pub fn get_private(bus: BusType) -> Result<Connection, Error> {
let mut e = Error::empty();
let conn = unsafe { ffi::dbus_bus_get_private(bus, e.get_mut()) };
if conn == ptr::null_mut() {
return Err(e)
}
let c = Connection { i: Box::new(IConnection { conn: Cell::new(conn), pending_items: RefCell::new(LinkedList::new()) })};
/* No, we don't want our app to suddenly quit if dbus goes down */
unsafe { ffi::dbus_connection_set_exit_on_disconnect(conn, 0) };
assert!(unsafe {
ffi::dbus_connection_add_filter(c.conn(), Some(filter_message_cb as ffi::DBusCallback), std::mem::transmute(&*c.i), None)
}!= 0);
Ok(c)
}
/// Sends a message over the D-Bus and waits for a reply.
/// This is usually used for method calls.
pub fn send_with_reply_and_block(&self, msg: Message, timeout_ms: i32) -> Result<Message, Error> {
let mut e = Error::empty();
let response = unsafe {
ffi::dbus_connection_send_with_reply_and_block(self.conn(), message::get_message_ptr(&msg),
timeout_ms as libc::c_int, e.get_mut())
};
if response == ptr::null_mut() {
return Err(e);
}
Ok(message::message_from_ptr(response, false))
}
/// Sends a message over the D-Bus without waiting. Useful for sending signals and method call replies.
pub fn send(&self, msg: Message) -> Result<u32,()> {
let mut serial = 0u32;
let r = unsafe { ffi::dbus_connection_send(self.conn(), message::get_message_ptr(&msg), &mut serial) };
if r == 0 { return Err(()); }
unsafe { ffi::dbus_connection_flush(self.conn()) };
Ok(serial)
}
pub fn unique_name(&self) -> String {
let c = unsafe { ffi::dbus_bus_get_unique_name(self.conn()) };
c_str_to_slice(&c).unwrap_or("").to_string()
}
// Check if there are new incoming events
pub fn iter(&self, timeout_ms: i32) -> ConnectionItems {
ConnectionItems {
c: self,
timeout_ms: timeout_ms,
}
}
pub fn register_object_path(&self, path: &str) -> Result<(), Error> {
let mut e = Error::empty();
let p = to_c_str(path);
let vtable = ffi::DBusObjectPathVTable {
unregister_function: None,
message_function: Some(object_path_message_cb as ffi::DBusCallback),
dbus_internal_pad1: None,
dbus_internal_pad2: None,
dbus_internal_pad3: None,
dbus_internal_pad4: None,
};
let r = unsafe {
let user_data: *mut libc::c_void = std::mem::transmute(&*self.i);
ffi::dbus_connection_try_register_object_path(self.conn(), p.as_ptr(), &vtable, user_data, e.get_mut())
};
if r == 0 { Err(e) } else { Ok(()) }
}
pub fn unregister_object_path(&self, path: &str) {
let p = to_c_str(path);
let r = unsafe { ffi::dbus_connection_unregister_object_path(self.conn(), p.as_ptr()) };
if r == 0 { panic!("Out of memory"); }
}
pub fn list_registered_object_paths(&self, path: &str) -> Vec<String> {
let p = to_c_str(path);
let mut clist: *mut *mut libc::c_char = ptr::null_mut();
let r = unsafe { ffi::dbus_connection_list_registered(self.conn(), p.as_ptr(), &mut clist) };
if r == 0 { panic!("Out of memory"); }
let mut v = Vec::new();
let mut i = 0;
loop {
let s = unsafe {
let citer = clist.offset(i);
if *citer == ptr::null_mut() { break };
std::mem::transmute(citer)
};
v.push(format!("{}", c_str_to_slice(s).unwrap()));
i += 1;
}
unsafe { ffi::dbus_free_string_array(clist) };
v
}
pub fn register_name(&self, name: &str, flags: u32) -> Result<RequestNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_request_name(self.conn(), n.as_ptr(), flags, e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn release_name(&self, name: &str) -> Result<ReleaseNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_release_name(self.conn(), n.as_ptr(), e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn add_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_add_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
pub fn remove_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_remove_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
}
impl Drop for Connection {
fn drop(&mut self) {
unsafe {
ffi::dbus_connection_close(self.conn());
ffi::dbus_connection_unref(self.conn());
}
}
}
impl std::fmt::Debug for Connection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus Connection({})", self.unique_name())
}
}
#[cfg(test)]
mod test {
use super::{Connection, Message, BusType, MessageItem, ConnectionItem, NameFlag,
RequestNameReply, ReleaseNameReply};
#[test]
fn connection() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = c.unique_name();
assert!(n.starts_with(":1."));
println!("Connected to DBus, unique name: {}", n);
}
#[test]
fn invalid_message() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("foo.bar", "/", "foo.bar", "FooBar").unwrap();
let e = c.send_with_reply_and_block(m, 2000).err().unwrap();
assert!(e.name().unwrap() == "org.freedesktop.DBus.Error.ServiceUnknown");
}
#[test]
fn message_listnames() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
}
#[test]
fn message_namehasowner() {
let c = Connection::get_private(BusType::Session).unwrap();
let mut m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "NameHasOwner").unwrap();
m.append_items(&[MessageItem::Str("org.freedesktop.DBus".to_string())]);
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
assert_eq!(reply, vec!(MessageItem::Bool(true)));
}
#[test]
fn object_path() {
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
let thread = ::std::thread::spawn(move || {
let c = Connection::get_private(BusType::Session).unwrap();
c.register_object_path("/hello").unwrap();
// println!("Waiting...");
tx.send(c.unique_name()).unwrap();
for n in c.iter(1000) {
// println!("Found message... ({})", n);
match n {
ConnectionItem::MethodCall(ref m) => {
let reply = Message::new_method_return(m).unwrap();
c.send(reply).unwrap();
break;
}
_ => {}
}
}
c.unregister_object_path("/hello");
});
let c = Connection::get_private(BusType::Session).unwrap();
let n = rx.recv().unwrap();
let m = Message::new_method_call(&n, "/hello", "com.example.hello", "Hello").unwrap();
println!("Sending...");
let r = c.send_with_reply_and_block(m, 8000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
thread.join().unwrap();
}
#[test]
fn register_name() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = format!("com.example.hello.test.register_name");
assert_eq!(c.register_name(&n, NameFlag::ReplaceExisting as u32).unwrap(), RequestNameReply::PrimaryOwner);
assert_eq!(c.release_name(&n).unwrap(), ReleaseNameReply::Released);
}
#[test]
fn signal() {
let c = Connection::get_private(BusType::Session).unwrap();
let iface = "com.example.signaltest";
let mstr = format!("interface='{}',member='ThisIsASignal'", iface);
c.add_match(&mstr).unwrap();
let m = Message::new_signal("/mysignal", iface, "ThisIsASignal").unwrap();
let uname = c.unique_name();
c.send(m).unwrap();
for n in c.iter(1000) {
match n {
ConnectionItem::Signal(s) => {
let (_, p, i, m) = s.headers();
match (&*p.unwrap(), &*i.unwrap(), &*m.unwrap()) {
("/mysignal", "com.example.signaltest", "ThisIsASignal") => {
assert_eq!(s.sender().unwrap(), uname);
break;
},
(_, _, _) => println!("Other signal: {:?}", s.headers()),
}
}
_ => {},
}
}
c.remove_match(&mstr).unwrap();
}
}
| IConnection | identifier_name |
lib.rs | //! D-Bus bindings for Rust
//!
//! [D-Bus](http://dbus.freedesktop.org/) is a message bus, and is mainly used in Linux
//! for communication between processes. It is present by default on almost every
//! Linux distribution out there, and runs in two instances - one per session, and one
//! system-wide.
//!
//! See the examples directory for some examples to get you started.
extern crate libc;
pub use ffi::DBusBusType as BusType;
pub use ffi::DBusNameFlag as NameFlag;
pub use ffi::DBusRequestNameReply as RequestNameReply;
pub use ffi::DBusReleaseNameReply as ReleaseNameReply;
pub use ffi::DBusMessageType as MessageType;
pub use message::{Message, MessageItem, FromMessageItem, OwnedFd, OPath, ArrayError};
pub use prop::PropHandler;
pub use prop::Props;
/// A TypeSig describes the type of a MessageItem.
pub type TypeSig<'a> = std::borrow::Cow<'a, str>;
use std::ffi::{CString, CStr};
use std::ptr::{self};
use std::collections::LinkedList;
use std::cell::{Cell, RefCell};
mod ffi;
mod message;
mod prop;
mod objpath;
/// Contains functionality for the "server" of a D-Bus object. A remote application can
/// introspect this object and call methods on it.
pub mod obj {
pub use objpath::{ObjectPath, Interface, Property, Signal, Argument};
pub use objpath::{Method, MethodHandler, MethodResult};
pub use objpath::{PropertyROHandler, PropertyRWHandler, PropertyWOHandler, PropertyGetResult, PropertySetResult};
}
static INITDBUS: std::sync::Once = std::sync::ONCE_INIT;
fn init_dbus() {
INITDBUS.call_once(|| {
if unsafe { ffi::dbus_threads_init_default() } == 0 {
panic!("Out of memory when trying to initialize D-Bus library!");
}
});
}
/// D-Bus Error wrapper
pub struct Error {
e: ffi::DBusError,
}
unsafe impl Send for Error {}
fn c_str_to_slice(c: & *const libc::c_char) -> Option<&str> {
if *c == ptr::null() { None }
else { std::str::from_utf8( unsafe { CStr::from_ptr(*c).to_bytes() }).ok() }
}
fn to_c_str(n: &str) -> CString { CString::new(n.as_bytes()).unwrap() }
impl Error {
pub fn new_custom(name: &str, message: &str) -> Error {
let n = to_c_str(name);
let m = to_c_str(&message.replace("%","%%"));
let mut e = Error::empty();
unsafe { ffi::dbus_set_error(e.get_mut(), n.as_ptr(), m.as_ptr()) };
e
}
fn empty() -> Error {
init_dbus();
let mut e = ffi::DBusError {
name: ptr::null(),
message: ptr::null(),
dummy: 0,
padding1: ptr::null()
};
unsafe { ffi::dbus_error_init(&mut e); }
Error{ e: e }
}
/// Error name/type, e g 'org.freedesktop.DBus.Error.Failed'
pub fn name(&self) -> Option<&str> {
c_str_to_slice(&self.e.name)
}
/// Custom message, e g 'Could not find a matching object path'
pub fn message(&self) -> Option<&str> {
c_str_to_slice(&self.e.message)
}
fn get_mut(&mut self) -> &mut ffi::DBusError { &mut self.e }
}
impl Drop for Error {
fn drop(&mut self) {
unsafe { ffi::dbus_error_free(&mut self.e); }
}
}
impl std::fmt::Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus error: {} ({})", self.message().unwrap_or(""),
self.name().unwrap_or(""))
}
}
impl std::error::Error for Error {
fn description(&self) -> &str { "D-Bus error" }
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(),std::fmt::Error> {
if let Some(x) = self.message() {
write!(f, "{:?}", x.to_string())
} else { Ok(()) }
}
}
/// When listening for incoming events on the D-Bus, this enum will tell you what type
/// of incoming event has happened.
#[derive(Debug)]
pub enum ConnectionItem {
Nothing,
MethodCall(Message),
Signal(Message),
}
/// ConnectionItem iterator
pub struct ConnectionItems<'a> {
c: &'a Connection,
timeout_ms: i32,
}
impl<'a> Iterator for ConnectionItems<'a> {
type Item = ConnectionItem;
fn next(&mut self) -> Option<ConnectionItem> {
loop {
let i = self.c.i.pending_items.borrow_mut().pop_front();
if i.is_some() { return i; }
let r = unsafe { ffi::dbus_connection_read_write_dispatch(self.c.conn(), self.timeout_ms as libc::c_int) };
if!self.c.i.pending_items.borrow().is_empty() { continue };
if r == 0 { return None; }
return Some(ConnectionItem::Nothing);
}
}
}
/* Since we register callbacks with userdata pointers,
we need to make sure the connection pointer does not move around.
Hence this extra indirection. */
struct IConnection {
conn: Cell<*mut ffi::DBusConnection>,
pending_items: RefCell<LinkedList<ConnectionItem>>,
}
/// A D-Bus connection. Start here if you want to get on the D-Bus!
pub struct Connection {
i: Box<IConnection>,
}
extern "C" fn filter_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
let mtype: ffi::DBusMessageType = unsafe { std::mem::transmute(ffi::dbus_message_get_type(msg)) };
let r = match mtype {
ffi::DBusMessageType::Signal => {
i.pending_items.borrow_mut().push_back(ConnectionItem::Signal(m));
ffi::DBusHandlerResult::Handled
}
_ => ffi::DBusHandlerResult::NotYetHandled,
};
r
}
extern "C" fn object_path_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
user_data: *mut libc::c_void) -> ffi::DBusHandlerResult {
let m = message::message_from_ptr(msg, true);
let i: &IConnection = unsafe { std::mem::transmute(user_data) };
assert!(i.conn.get() == conn);
i.pending_items.borrow_mut().push_back(ConnectionItem::MethodCall(m));
ffi::DBusHandlerResult::Handled
}
impl Connection {
#[inline(always)]
fn conn(&self) -> *mut ffi::DBusConnection {
self.i.conn.get()
}
/// Creates a new D-Bus connection.
pub fn get_private(bus: BusType) -> Result<Connection, Error> {
let mut e = Error::empty();
let conn = unsafe { ffi::dbus_bus_get_private(bus, e.get_mut()) };
if conn == ptr::null_mut() {
return Err(e)
}
let c = Connection { i: Box::new(IConnection { conn: Cell::new(conn), pending_items: RefCell::new(LinkedList::new()) })};
/* No, we don't want our app to suddenly quit if dbus goes down */
unsafe { ffi::dbus_connection_set_exit_on_disconnect(conn, 0) };
assert!(unsafe {
ffi::dbus_connection_add_filter(c.conn(), Some(filter_message_cb as ffi::DBusCallback), std::mem::transmute(&*c.i), None)
}!= 0);
Ok(c)
}
/// Sends a message over the D-Bus and waits for a reply.
/// This is usually used for method calls.
pub fn send_with_reply_and_block(&self, msg: Message, timeout_ms: i32) -> Result<Message, Error> {
let mut e = Error::empty();
let response = unsafe {
ffi::dbus_connection_send_with_reply_and_block(self.conn(), message::get_message_ptr(&msg),
timeout_ms as libc::c_int, e.get_mut())
};
if response == ptr::null_mut() {
return Err(e);
}
Ok(message::message_from_ptr(response, false))
}
/// Sends a message over the D-Bus without waiting. Useful for sending signals and method call replies.
pub fn send(&self, msg: Message) -> Result<u32,()> {
let mut serial = 0u32;
let r = unsafe { ffi::dbus_connection_send(self.conn(), message::get_message_ptr(&msg), &mut serial) };
if r == 0 { return Err(()); }
unsafe { ffi::dbus_connection_flush(self.conn()) };
Ok(serial)
}
pub fn unique_name(&self) -> String {
let c = unsafe { ffi::dbus_bus_get_unique_name(self.conn()) };
c_str_to_slice(&c).unwrap_or("").to_string()
}
// Check if there are new incoming events
pub fn iter(&self, timeout_ms: i32) -> ConnectionItems {
ConnectionItems {
c: self,
timeout_ms: timeout_ms,
}
}
pub fn register_object_path(&self, path: &str) -> Result<(), Error> {
let mut e = Error::empty();
let p = to_c_str(path);
let vtable = ffi::DBusObjectPathVTable {
unregister_function: None,
message_function: Some(object_path_message_cb as ffi::DBusCallback),
dbus_internal_pad1: None,
dbus_internal_pad2: None,
dbus_internal_pad3: None,
dbus_internal_pad4: None,
};
let r = unsafe {
let user_data: *mut libc::c_void = std::mem::transmute(&*self.i);
ffi::dbus_connection_try_register_object_path(self.conn(), p.as_ptr(), &vtable, user_data, e.get_mut())
};
if r == 0 { Err(e) } else { Ok(()) }
}
pub fn unregister_object_path(&self, path: &str) {
let p = to_c_str(path);
let r = unsafe { ffi::dbus_connection_unregister_object_path(self.conn(), p.as_ptr()) };
if r == 0 { panic!("Out of memory"); }
}
pub fn list_registered_object_paths(&self, path: &str) -> Vec<String> {
let p = to_c_str(path);
let mut clist: *mut *mut libc::c_char = ptr::null_mut();
let r = unsafe { ffi::dbus_connection_list_registered(self.conn(), p.as_ptr(), &mut clist) };
if r == 0 { panic!("Out of memory"); }
let mut v = Vec::new();
let mut i = 0;
loop {
let s = unsafe {
let citer = clist.offset(i);
if *citer == ptr::null_mut() { break };
std::mem::transmute(citer)
};
v.push(format!("{}", c_str_to_slice(s).unwrap()));
i += 1;
}
unsafe { ffi::dbus_free_string_array(clist) };
v
}
pub fn register_name(&self, name: &str, flags: u32) -> Result<RequestNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_request_name(self.conn(), n.as_ptr(), flags, e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn release_name(&self, name: &str) -> Result<ReleaseNameReply, Error> {
let mut e = Error::empty();
let n = to_c_str(name);
let r = unsafe { ffi::dbus_bus_release_name(self.conn(), n.as_ptr(), e.get_mut()) };
if r == -1 { Err(e) } else { Ok(unsafe { std::mem::transmute(r) }) }
}
pub fn add_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_add_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
pub fn remove_match(&self, rule: &str) -> Result<(), Error> {
let mut e = Error::empty();
let n = to_c_str(rule);
unsafe { ffi::dbus_bus_remove_match(self.conn(), n.as_ptr(), e.get_mut()) };
if e.name().is_some() { Err(e) } else { Ok(()) }
}
}
impl Drop for Connection {
fn drop(&mut self) {
unsafe {
ffi::dbus_connection_close(self.conn());
ffi::dbus_connection_unref(self.conn());
}
}
}
impl std::fmt::Debug for Connection {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
write!(f, "D-Bus Connection({})", self.unique_name())
}
}
#[cfg(test)]
mod test {
use super::{Connection, Message, BusType, MessageItem, ConnectionItem, NameFlag,
RequestNameReply, ReleaseNameReply};
#[test]
fn connection() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = c.unique_name();
assert!(n.starts_with(":1."));
println!("Connected to DBus, unique name: {}", n);
}
#[test]
fn invalid_message() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("foo.bar", "/", "foo.bar", "FooBar").unwrap();
let e = c.send_with_reply_and_block(m, 2000).err().unwrap();
assert!(e.name().unwrap() == "org.freedesktop.DBus.Error.ServiceUnknown");
}
#[test]
fn message_listnames() {
let c = Connection::get_private(BusType::Session).unwrap();
let m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "ListNames").unwrap();
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
}
#[test]
fn message_namehasowner() {
let c = Connection::get_private(BusType::Session).unwrap();
let mut m = Message::new_method_call("org.freedesktop.DBus", "/", "org.freedesktop.DBus", "NameHasOwner").unwrap();
m.append_items(&[MessageItem::Str("org.freedesktop.DBus".to_string())]);
let r = c.send_with_reply_and_block(m, 2000).unwrap();
let reply = r.get_items();
println!("{:?}", reply); |
#[test]
fn object_path() {
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
let thread = ::std::thread::spawn(move || {
let c = Connection::get_private(BusType::Session).unwrap();
c.register_object_path("/hello").unwrap();
// println!("Waiting...");
tx.send(c.unique_name()).unwrap();
for n in c.iter(1000) {
// println!("Found message... ({})", n);
match n {
ConnectionItem::MethodCall(ref m) => {
let reply = Message::new_method_return(m).unwrap();
c.send(reply).unwrap();
break;
}
_ => {}
}
}
c.unregister_object_path("/hello");
});
let c = Connection::get_private(BusType::Session).unwrap();
let n = rx.recv().unwrap();
let m = Message::new_method_call(&n, "/hello", "com.example.hello", "Hello").unwrap();
println!("Sending...");
let r = c.send_with_reply_and_block(m, 8000).unwrap();
let reply = r.get_items();
println!("{:?}", reply);
thread.join().unwrap();
}
#[test]
fn register_name() {
let c = Connection::get_private(BusType::Session).unwrap();
let n = format!("com.example.hello.test.register_name");
assert_eq!(c.register_name(&n, NameFlag::ReplaceExisting as u32).unwrap(), RequestNameReply::PrimaryOwner);
assert_eq!(c.release_name(&n).unwrap(), ReleaseNameReply::Released);
}
#[test]
fn signal() {
let c = Connection::get_private(BusType::Session).unwrap();
let iface = "com.example.signaltest";
let mstr = format!("interface='{}',member='ThisIsASignal'", iface);
c.add_match(&mstr).unwrap();
let m = Message::new_signal("/mysignal", iface, "ThisIsASignal").unwrap();
let uname = c.unique_name();
c.send(m).unwrap();
for n in c.iter(1000) {
match n {
ConnectionItem::Signal(s) => {
let (_, p, i, m) = s.headers();
match (&*p.unwrap(), &*i.unwrap(), &*m.unwrap()) {
("/mysignal", "com.example.signaltest", "ThisIsASignal") => {
assert_eq!(s.sender().unwrap(), uname);
break;
},
(_, _, _) => println!("Other signal: {:?}", s.headers()),
}
}
_ => {},
}
}
c.remove_match(&mstr).unwrap();
}
} | assert_eq!(reply, vec!(MessageItem::Bool(true)));
} | random_line_split |
to_str.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast;
use ast::{meta_item, item, expr};
use codemap::span;
use ext::base::ExtCtxt;
use ext::build::AstBuilder;
use ext::deriving::generic::*;
pub fn expand_deriving_to_str(cx: @ExtCtxt,
span: span,
mitem: @meta_item,
in_items: ~[@item])
-> ~[@item] {
let trait_def = TraitDef {
path: Path::new(~["std", "to_str", "ToStr"]),
additional_bounds: ~[],
generics: LifetimeBounds::empty(),
methods: ~[
MethodDef {
name: "to_str",
generics: LifetimeBounds::empty(),
explicit_self: borrowed_explicit_self(),
args: ~[],
ret_ty: Ptr(~Literal(Path::new_local("str")), Send),
const_nonmatching: false,
combine_substructure: to_str_substructure
}
]
};
trait_def.expand(cx, span, mitem, in_items)
}
// It used to be the case that this deriving implementation invoked
// std::sys::log_str, but this isn't sufficient because it doesn't invoke the
// to_str() method on each field. Hence we mirror the logic of the log_str()
// method, but with tweaks to call to_str() on sub-fields.
fn to_str_substructure(cx: @ExtCtxt, span: span,
substr: &Substructure) -> @expr {
let to_str = cx.ident_of("to_str");
let doit = |start: &str, end: @str, name: ast::ident,
fields: &[(Option<ast::ident>, @expr, ~[@expr])]| {
if fields.len() == 0 {
cx.expr_str_uniq(span, cx.str_of(name))
} else {
let buf = cx.ident_of("buf");
let start = cx.str_of(name) + start;
let init = cx.expr_str_uniq(span, start.to_managed());
let mut stmts = ~[cx.stmt_let(span, true, buf, init)];
let push_str = cx.ident_of("push_str");
let push = |s: @expr| {
let ebuf = cx.expr_ident(span, buf);
let call = cx.expr_method_call(span, ebuf, push_str, ~[s]);
stmts.push(cx.stmt_expr(call));
};
for fields.iter().enumerate().advance |(i, &(name, e, _))| {
if i > 0 {
push(cx.expr_str(span, @", "));
}
match name {
None => {}
Some(id) => {
let name = cx.str_of(id) + ": ";
push(cx.expr_str(span, name.to_managed()));
}
}
push(cx.expr_method_call(span, e, to_str, ~[]));
}
push(cx.expr_str(span, end));
cx.expr_blk(cx.blk(span, stmts, Some(cx.expr_ident(span, buf))))
}
};
return match *substr.fields {
Struct(ref fields) => {
if fields.len() == 0 || fields[0].n0_ref().is_none() {
doit("(", @")", substr.type_ident, *fields)
} else {
doit("{", @"}", substr.type_ident, *fields)
}
}
EnumMatching(_, variant, ref fields) => {
match variant.node.kind {
ast::tuple_variant_kind(*) =>
doit("(", @")", variant.node.name, *fields),
ast::struct_variant_kind(*) =>
doit("{", @"}", variant.node.name, *fields), | }
_ => cx.bug("expected Struct or EnumMatching in deriving(ToStr)")
};
} | } | random_line_split |
mod.rs | use alloc::boxed::{Box, FnBox};
use super::stack::Stack;
#[cfg(target_arch = "x86")]
mod i686;
#[cfg(target_arch = "x86_64")]
mod x86_64;
mod imp {
#[cfg(target_arch = "x86")]
pub use super::i686::*;
#[cfg(target_arch = "x86_64")]
pub use super::x86_64::*;
}
/// A thread has to be wrapped by a calling function. This function
/// is responsible to setup/cleanup for the actual closure that the user wants
/// to call. This closure is passed as first parameter to the wrapping function
/// and is named 'f' here. This pointer *IS* extracted from a Box via a call
/// to Box::into_raw. The wrapper function is now responsible for its proper
/// deallocation when the thread is terminated
pub type WrapperFn = extern "C" fn(f: *mut u8) ->!;
#[derive(Debug)]
pub struct Context {
regs: imp::Registers,
}
impl Context {
pub unsafe fn new<F>(wrapper: WrapperFn, mut f: F, stack: &mut Stack) -> Self
where F: FnMut() -> (), F: Send +'static {
let fun = move || {
f();
};
let boxed_fun: Box<FnBox()> = Box::new(fun);
let fun_ptr = Box::into_raw(Box::new(boxed_fun)) as *mut u8;
Context {
regs: imp::Registers::new(wrapper, fun_ptr, stack.top().unwrap()),
}
}
/// Load the current context to the CPU
pub fn load(&self) ->! |
#[inline(always)]
#[cfg_attr(feature = "clippy", allow(inline_always))]
/// Save the current context. This function will actually return twice.
/// The first return is just after saving the context and will return false
/// The second time is when the saved context gets restored and will return
/// true
///
/// This function is always inlined because otherwise the stack frame gets
/// corrupted as this will return twice. The second time the function
/// returns the stack frame will most likely be corrupted. To avoid that
/// inline the function to merge the stack frame of this function with
/// the caller's.
pub fn save(&mut self) -> bool {
unsafe {
imp::registers_save(&mut self.regs)
}
}
}
| {
unsafe {
imp::registers_load(&self.regs);
}
} | identifier_body |
mod.rs | use alloc::boxed::{Box, FnBox};
use super::stack::Stack;
#[cfg(target_arch = "x86")]
mod i686;
#[cfg(target_arch = "x86_64")]
mod x86_64;
mod imp {
#[cfg(target_arch = "x86")]
pub use super::i686::*;
#[cfg(target_arch = "x86_64")]
pub use super::x86_64::*;
}
/// A thread has to be wrapped by a calling function. This function
/// is responsible to setup/cleanup for the actual closure that the user wants
/// to call. This closure is passed as first parameter to the wrapping function
/// and is named 'f' here. This pointer *IS* extracted from a Box via a call
/// to Box::into_raw. The wrapper function is now responsible for its proper
/// deallocation when the thread is terminated
pub type WrapperFn = extern "C" fn(f: *mut u8) ->!;
#[derive(Debug)]
pub struct Context {
regs: imp::Registers,
}
impl Context {
pub unsafe fn | <F>(wrapper: WrapperFn, mut f: F, stack: &mut Stack) -> Self
where F: FnMut() -> (), F: Send +'static {
let fun = move || {
f();
};
let boxed_fun: Box<FnBox()> = Box::new(fun);
let fun_ptr = Box::into_raw(Box::new(boxed_fun)) as *mut u8;
Context {
regs: imp::Registers::new(wrapper, fun_ptr, stack.top().unwrap()),
}
}
/// Load the current context to the CPU
pub fn load(&self) ->! {
unsafe {
imp::registers_load(&self.regs);
}
}
#[inline(always)]
#[cfg_attr(feature = "clippy", allow(inline_always))]
/// Save the current context. This function will actually return twice.
/// The first return is just after saving the context and will return false
/// The second time is when the saved context gets restored and will return
/// true
///
/// This function is always inlined because otherwise the stack frame gets
/// corrupted as this will return twice. The second time the function
/// returns the stack frame will most likely be corrupted. To avoid that
/// inline the function to merge the stack frame of this function with
/// the caller's.
pub fn save(&mut self) -> bool {
unsafe {
imp::registers_save(&mut self.regs)
}
}
}
| new | identifier_name |
mod.rs | use alloc::boxed::{Box, FnBox};
use super::stack::Stack;
#[cfg(target_arch = "x86")]
mod i686;
#[cfg(target_arch = "x86_64")]
mod x86_64;
mod imp {
#[cfg(target_arch = "x86")]
pub use super::i686::*;
#[cfg(target_arch = "x86_64")]
pub use super::x86_64::*;
}
/// A thread has to be wrapped by a calling function. This function
/// is responsible to setup/cleanup for the actual closure that the user wants
/// to call. This closure is passed as first parameter to the wrapping function
/// and is named 'f' here. This pointer *IS* extracted from a Box via a call
/// to Box::into_raw. The wrapper function is now responsible for its proper
/// deallocation when the thread is terminated
pub type WrapperFn = extern "C" fn(f: *mut u8) ->!;
#[derive(Debug)]
pub struct Context {
regs: imp::Registers,
}
impl Context {
pub unsafe fn new<F>(wrapper: WrapperFn, mut f: F, stack: &mut Stack) -> Self
where F: FnMut() -> (), F: Send +'static {
let fun = move || {
f();
};
let boxed_fun: Box<FnBox()> = Box::new(fun);
let fun_ptr = Box::into_raw(Box::new(boxed_fun)) as *mut u8;
Context {
regs: imp::Registers::new(wrapper, fun_ptr, stack.top().unwrap()),
}
} | pub fn load(&self) ->! {
unsafe {
imp::registers_load(&self.regs);
}
}
#[inline(always)]
#[cfg_attr(feature = "clippy", allow(inline_always))]
/// Save the current context. This function will actually return twice.
/// The first return is just after saving the context and will return false
/// The second time is when the saved context gets restored and will return
/// true
///
/// This function is always inlined because otherwise the stack frame gets
/// corrupted as this will return twice. The second time the function
/// returns the stack frame will most likely be corrupted. To avoid that
/// inline the function to merge the stack frame of this function with
/// the caller's.
pub fn save(&mut self) -> bool {
unsafe {
imp::registers_save(&mut self.regs)
}
}
} |
/// Load the current context to the CPU | random_line_split |
borrowck-preserve-box-in-pat.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 | // exec-env:RUST_POISON_ON_FREE=1
use std::ptr;
struct F { f: ~int }
pub fn main() {
let x = @mut @F {f: ~3};
match x {
@@F{f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(x.f)), ptr::to_unsafe_ptr(b_x));
*x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
assert_eq!(**b_x, 3);
assert!(ptr::to_unsafe_ptr(&(*x.f))!= ptr::to_unsafe_ptr(&(**b_x)));
}
}
} | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
borrowck-preserve-box-in-pat.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.
// exec-env:RUST_POISON_ON_FREE=1
use std::ptr;
struct F { f: ~int }
pub fn main() | {
let x = @mut @F {f: ~3};
match x {
@@F{f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(x.f)), ptr::to_unsafe_ptr(b_x));
*x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
assert_eq!(**b_x, 3);
assert!(ptr::to_unsafe_ptr(&(*x.f)) != ptr::to_unsafe_ptr(&(**b_x)));
}
}
} | identifier_body |
|
borrowck-preserve-box-in-pat.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.
// exec-env:RUST_POISON_ON_FREE=1
use std::ptr;
struct F { f: ~int }
pub fn | () {
let x = @mut @F {f: ~3};
match x {
@@F{f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(x.f)), ptr::to_unsafe_ptr(b_x));
*x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
assert_eq!(**b_x, 3);
assert!(ptr::to_unsafe_ptr(&(*x.f))!= ptr::to_unsafe_ptr(&(**b_x)));
}
}
}
| main | identifier_name |
mdata_info.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
use crate::crypto::shared_secretbox;
use crate::errors::CoreError;
use crate::ffi::arrays::{SymNonce, SymSecretKey};
use crate::ffi::MDataInfo as FfiMDataInfo;
use crate::ipc::IpcError;
use crate::utils::{symmetric_decrypt, symmetric_encrypt};
use ffi_utils::ReprC;
use rand::{OsRng, Rng};
use routing::{EntryAction, Value, XorName};
use rust_sodium::crypto::secretbox;
use std::collections::{BTreeMap, BTreeSet};
use tiny_keccak::sha3_256;
/// Information allowing to locate and access mutable data on the network.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct MDataInfo {
/// Name of the data where the directory is stored.
pub name: XorName,
/// Type tag of the data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
}
impl MDataInfo {
/// Construct `MDataInfo` for private (encrypted) data with a provided private key.
pub fn new_private(
name: XorName,
type_tag: u64,
enc_info: (shared_secretbox::Key, secretbox::Nonce),
) -> Self {
MDataInfo {
name,
type_tag,
enc_info: Some(enc_info),
new_enc_info: None,
}
}
/// Construct `MDataInfo` for public data.
pub fn new_public(name: XorName, type_tag: u64) -> Self {
MDataInfo {
name,
type_tag,
enc_info: None,
new_enc_info: None,
}
}
/// Generate random `MDataInfo` for private (encrypted) mutable data.
pub fn random_private(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
let enc_info = (shared_secretbox::gen_key(), secretbox::gen_nonce());
Ok(Self::new_private(rng.gen(), type_tag, enc_info))
}
/// Generate random `MDataInfo` for public mutable data.
pub fn random_public(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
Ok(Self::new_public(rng.gen(), type_tag))
}
/// Returns the encryption key, if any.
pub fn enc_key(&self) -> Option<&shared_secretbox::Key> {
self.enc_info.as_ref().map(|&(ref key, _)| key)
}
/// Returns the nonce, if any.
pub fn nonce(&self) -> Option<&secretbox::Nonce> {
self.enc_info.as_ref().map(|&(_, ref nonce)| nonce)
}
/// Encrypt the key for the mdata entry accordingly.
pub fn enc_entry_key(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, seed)) = self.new_enc_info {
enc_entry_key(plain_text, key, seed)
} else if let Some((ref key, seed)) = self.enc_info {
enc_entry_key(plain_text, key, seed)
} else {
Ok(plain_text.to_vec())
}
}
/// Encrypt the value for this mdata entry accordingly.
pub fn enc_entry_value(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
symmetric_encrypt(plain_text, key, None)
} else if let Some((ref key, _)) = self.enc_info {
symmetric_encrypt(plain_text, key, None)
} else {
Ok(plain_text.to_vec())
}
}
/// Decrypt key or value of this mdata entry.
pub fn decrypt(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
if let Ok(plain) = symmetric_decrypt(cipher, key) {
return Ok(plain);
}
}
if let Some((ref key, _)) = self.enc_info {
symmetric_decrypt(cipher, key)
} else {
Ok(cipher.to_vec())
}
}
/// Start the encryption info re-generation by populating the `new_enc_info`
/// field with random keys, unless it's already populated.
pub fn start_new_enc_info(&mut self) {
if self.enc_info.is_some() && self.new_enc_info.is_none() {
self.new_enc_info = Some((shared_secretbox::gen_key(), secretbox::gen_nonce()));
}
}
/// Commit the encryption info re-generation by replacing the current encryption info
/// with `new_enc_info` (if any).
pub fn commit_new_enc_info(&mut self) {
if let Some(new_enc_info) = self.new_enc_info.take() {
self.enc_info = Some(new_enc_info);
}
}
/// Construct FFI wrapper for the native Rust object, consuming self.
pub fn into_repr_c(self) -> FfiMDataInfo {
let (has_enc_info, enc_key, enc_nonce) = enc_info_into_repr_c(self.enc_info);
let (has_new_enc_info, new_enc_key, new_enc_nonce) =
enc_info_into_repr_c(self.new_enc_info);
FfiMDataInfo {
name: self.name.0,
type_tag: self.type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
}
}
}
fn os_rng() -> Result<OsRng, CoreError> {
OsRng::new().map_err(|_| CoreError::RandomDataGenerationFailure)
}
/// Encrypt the entries (both keys and values) using the `MDataInfo`.
pub fn encrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_value = encrypt_value(info, value)?;
let _ = output.insert(encrypted_key, encrypted_value);
}
Ok(output)
}
/// Encrypt entry actions using the `MDataInfo`. The effect of this is that the entries
/// mutated by the encrypted actions will end up encrypted using the `MDataInfo`.
pub fn encrypt_entry_actions(
info: &MDataInfo,
actions: &BTreeMap<Vec<u8>, EntryAction>,
) -> Result<BTreeMap<Vec<u8>, EntryAction>, CoreError> {
let mut output = BTreeMap::new();
for (key, action) in actions {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_action = match *action {
EntryAction::Ins(ref value) => EntryAction::Ins(encrypt_value(info, value)?),
EntryAction::Update(ref value) => EntryAction::Update(encrypt_value(info, value)?),
EntryAction::Del(version) => EntryAction::Del(version),
};
let _ = output.insert(encrypted_key, encrypted_action);
}
Ok(output)
}
/// Decrypt entries using the `MDataInfo`.
pub fn decrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let decrypted_key = info.decrypt(key)?;
let decrypted_value = decrypt_value(info, value)?;
let _ = output.insert(decrypted_key, decrypted_value);
}
Ok(output)
}
/// Decrypt all keys using the `MDataInfo`.
pub fn decrypt_keys(
info: &MDataInfo,
keys: &BTreeSet<Vec<u8>>,
) -> Result<BTreeSet<Vec<u8>>, CoreError> {
let mut output = BTreeSet::new();
for key in keys {
let _ = output.insert(info.decrypt(key)?);
}
Ok(output)
}
/// Decrypt all values using the `MDataInfo`.
pub fn decrypt_values(info: &MDataInfo, values: &[Value]) -> Result<Vec<Value>, CoreError> {
let mut output = Vec::with_capacity(values.len());
for value in values {
output.push(decrypt_value(info, value)?);
}
Ok(output)
}
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.decrypt(&value.content)?,
entry_version: value.entry_version,
})
}
fn enc_entry_key(
plain_text: &[u8],
key: &secretbox::Key,
seed: secretbox::Nonce,
) -> Result<Vec<u8>, CoreError> {
let nonce = {
let secretbox::Nonce(ref nonce) = seed;
let mut pt = plain_text.to_vec();
pt.extend_from_slice(&nonce[..]);
unwrap!(secretbox::Nonce::from_slice(
&sha3_256(&pt)[..secretbox::NONCEBYTES],
))
};
symmetric_encrypt(plain_text, key, Some(&nonce))
}
impl ReprC for MDataInfo {
type C = *const FfiMDataInfo;
type Error = IpcError;
#[allow(unsafe_code)]
unsafe fn clone_from_repr_c(repr_c: Self::C) -> Result<Self, Self::Error> {
let FfiMDataInfo {
name,
type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
} = *repr_c;
Ok(Self {
name: XorName(name),
type_tag,
enc_info: enc_info_from_repr_c(has_enc_info, enc_key, enc_nonce),
new_enc_info: enc_info_from_repr_c(has_new_enc_info, new_enc_key, new_enc_nonce),
})
}
}
fn enc_info_into_repr_c(
info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
) -> (bool, SymSecretKey, SymNonce) {
if let Some((key, nonce)) = info | else {
(false, Default::default(), Default::default())
}
}
fn enc_info_from_repr_c(
is_set: bool,
key: SymSecretKey,
nonce: SymNonce,
) -> Option<(shared_secretbox::Key, secretbox::Nonce)> {
if is_set {
Some((
shared_secretbox::Key::from_raw(&key),
secretbox::Nonce(nonce),
))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
// Ensure that a private mdata info is encrypted.
#[test]
fn private_mdata_info_encrypts() {
let info = unwrap!(MDataInfo::random_private(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
let enc_key = unwrap!(info.enc_entry_key(&key));
let enc_val = unwrap!(info.enc_entry_value(&val));
assert_ne!(enc_key, key);
assert_ne!(enc_val, val);
assert_eq!(unwrap!(info.decrypt(&enc_key)), key);
assert_eq!(unwrap!(info.decrypt(&enc_val)), val);
}
// Ensure that a public mdata info is not encrypted.
#[test]
fn public_mdata_info_doesnt_encrypt() {
let info = unwrap!(MDataInfo::random_public(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
assert_eq!(unwrap!(info.enc_entry_key(&key)), key);
assert_eq!(unwrap!(info.enc_entry_value(&val)), val);
assert_eq!(unwrap!(info.decrypt(&val)), val);
}
// Test creating and committing new encryption info.
#[test]
fn decrypt() {
let mut info = unwrap!(MDataInfo::random_private(0));
let plain = Vec::from("plaintext");
let old_cipher = unwrap!(info.enc_entry_value(&plain));
info.start_new_enc_info();
let new_cipher = unwrap!(info.enc_entry_value(&plain));
// After start, both encryption infos work.
assert_eq!(unwrap!(info.decrypt(&old_cipher)), plain);
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
// After commit, only the new encryption info works.
info.commit_new_enc_info();
match info.decrypt(&old_cipher) {
Err(CoreError::SymmetricDecipherFailure) => (),
x => panic!("Unexpected {:?}", x),
}
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
}
}
| {
(true, key.0, nonce.0)
} | conditional_block |
mdata_info.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
use crate::crypto::shared_secretbox;
use crate::errors::CoreError;
use crate::ffi::arrays::{SymNonce, SymSecretKey};
use crate::ffi::MDataInfo as FfiMDataInfo;
use crate::ipc::IpcError;
use crate::utils::{symmetric_decrypt, symmetric_encrypt};
use ffi_utils::ReprC;
use rand::{OsRng, Rng};
use routing::{EntryAction, Value, XorName};
use rust_sodium::crypto::secretbox;
use std::collections::{BTreeMap, BTreeSet};
use tiny_keccak::sha3_256;
/// Information allowing to locate and access mutable data on the network.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct MDataInfo {
/// Name of the data where the directory is stored.
pub name: XorName,
/// Type tag of the data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
}
impl MDataInfo {
/// Construct `MDataInfo` for private (encrypted) data with a provided private key.
pub fn new_private(
name: XorName,
type_tag: u64,
enc_info: (shared_secretbox::Key, secretbox::Nonce),
) -> Self {
MDataInfo {
name,
type_tag,
enc_info: Some(enc_info),
new_enc_info: None,
}
}
/// Construct `MDataInfo` for public data.
pub fn new_public(name: XorName, type_tag: u64) -> Self {
MDataInfo {
name,
type_tag,
enc_info: None,
new_enc_info: None,
}
}
/// Generate random `MDataInfo` for private (encrypted) mutable data.
pub fn random_private(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
let enc_info = (shared_secretbox::gen_key(), secretbox::gen_nonce());
Ok(Self::new_private(rng.gen(), type_tag, enc_info))
}
/// Generate random `MDataInfo` for public mutable data.
pub fn random_public(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
Ok(Self::new_public(rng.gen(), type_tag))
}
/// Returns the encryption key, if any.
pub fn enc_key(&self) -> Option<&shared_secretbox::Key> {
self.enc_info.as_ref().map(|&(ref key, _)| key)
}
/// Returns the nonce, if any.
pub fn nonce(&self) -> Option<&secretbox::Nonce> {
self.enc_info.as_ref().map(|&(_, ref nonce)| nonce)
}
/// Encrypt the key for the mdata entry accordingly.
pub fn enc_entry_key(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, seed)) = self.new_enc_info {
enc_entry_key(plain_text, key, seed)
} else if let Some((ref key, seed)) = self.enc_info {
enc_entry_key(plain_text, key, seed)
} else {
Ok(plain_text.to_vec())
}
}
/// Encrypt the value for this mdata entry accordingly.
pub fn enc_entry_value(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
symmetric_encrypt(plain_text, key, None)
} else if let Some((ref key, _)) = self.enc_info {
symmetric_encrypt(plain_text, key, None)
} else {
Ok(plain_text.to_vec())
}
}
/// Decrypt key or value of this mdata entry.
pub fn decrypt(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
if let Ok(plain) = symmetric_decrypt(cipher, key) {
return Ok(plain);
}
}
if let Some((ref key, _)) = self.enc_info {
symmetric_decrypt(cipher, key)
} else {
Ok(cipher.to_vec())
}
}
/// Start the encryption info re-generation by populating the `new_enc_info`
/// field with random keys, unless it's already populated.
pub fn start_new_enc_info(&mut self) {
if self.enc_info.is_some() && self.new_enc_info.is_none() {
self.new_enc_info = Some((shared_secretbox::gen_key(), secretbox::gen_nonce()));
}
}
/// Commit the encryption info re-generation by replacing the current encryption info
/// with `new_enc_info` (if any).
pub fn | (&mut self) {
if let Some(new_enc_info) = self.new_enc_info.take() {
self.enc_info = Some(new_enc_info);
}
}
/// Construct FFI wrapper for the native Rust object, consuming self.
pub fn into_repr_c(self) -> FfiMDataInfo {
let (has_enc_info, enc_key, enc_nonce) = enc_info_into_repr_c(self.enc_info);
let (has_new_enc_info, new_enc_key, new_enc_nonce) =
enc_info_into_repr_c(self.new_enc_info);
FfiMDataInfo {
name: self.name.0,
type_tag: self.type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
}
}
}
fn os_rng() -> Result<OsRng, CoreError> {
OsRng::new().map_err(|_| CoreError::RandomDataGenerationFailure)
}
/// Encrypt the entries (both keys and values) using the `MDataInfo`.
pub fn encrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_value = encrypt_value(info, value)?;
let _ = output.insert(encrypted_key, encrypted_value);
}
Ok(output)
}
/// Encrypt entry actions using the `MDataInfo`. The effect of this is that the entries
/// mutated by the encrypted actions will end up encrypted using the `MDataInfo`.
pub fn encrypt_entry_actions(
info: &MDataInfo,
actions: &BTreeMap<Vec<u8>, EntryAction>,
) -> Result<BTreeMap<Vec<u8>, EntryAction>, CoreError> {
let mut output = BTreeMap::new();
for (key, action) in actions {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_action = match *action {
EntryAction::Ins(ref value) => EntryAction::Ins(encrypt_value(info, value)?),
EntryAction::Update(ref value) => EntryAction::Update(encrypt_value(info, value)?),
EntryAction::Del(version) => EntryAction::Del(version),
};
let _ = output.insert(encrypted_key, encrypted_action);
}
Ok(output)
}
/// Decrypt entries using the `MDataInfo`.
pub fn decrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let decrypted_key = info.decrypt(key)?;
let decrypted_value = decrypt_value(info, value)?;
let _ = output.insert(decrypted_key, decrypted_value);
}
Ok(output)
}
/// Decrypt all keys using the `MDataInfo`.
pub fn decrypt_keys(
info: &MDataInfo,
keys: &BTreeSet<Vec<u8>>,
) -> Result<BTreeSet<Vec<u8>>, CoreError> {
let mut output = BTreeSet::new();
for key in keys {
let _ = output.insert(info.decrypt(key)?);
}
Ok(output)
}
/// Decrypt all values using the `MDataInfo`.
pub fn decrypt_values(info: &MDataInfo, values: &[Value]) -> Result<Vec<Value>, CoreError> {
let mut output = Vec::with_capacity(values.len());
for value in values {
output.push(decrypt_value(info, value)?);
}
Ok(output)
}
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.decrypt(&value.content)?,
entry_version: value.entry_version,
})
}
fn enc_entry_key(
plain_text: &[u8],
key: &secretbox::Key,
seed: secretbox::Nonce,
) -> Result<Vec<u8>, CoreError> {
let nonce = {
let secretbox::Nonce(ref nonce) = seed;
let mut pt = plain_text.to_vec();
pt.extend_from_slice(&nonce[..]);
unwrap!(secretbox::Nonce::from_slice(
&sha3_256(&pt)[..secretbox::NONCEBYTES],
))
};
symmetric_encrypt(plain_text, key, Some(&nonce))
}
impl ReprC for MDataInfo {
type C = *const FfiMDataInfo;
type Error = IpcError;
#[allow(unsafe_code)]
unsafe fn clone_from_repr_c(repr_c: Self::C) -> Result<Self, Self::Error> {
let FfiMDataInfo {
name,
type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
} = *repr_c;
Ok(Self {
name: XorName(name),
type_tag,
enc_info: enc_info_from_repr_c(has_enc_info, enc_key, enc_nonce),
new_enc_info: enc_info_from_repr_c(has_new_enc_info, new_enc_key, new_enc_nonce),
})
}
}
fn enc_info_into_repr_c(
info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
) -> (bool, SymSecretKey, SymNonce) {
if let Some((key, nonce)) = info {
(true, key.0, nonce.0)
} else {
(false, Default::default(), Default::default())
}
}
fn enc_info_from_repr_c(
is_set: bool,
key: SymSecretKey,
nonce: SymNonce,
) -> Option<(shared_secretbox::Key, secretbox::Nonce)> {
if is_set {
Some((
shared_secretbox::Key::from_raw(&key),
secretbox::Nonce(nonce),
))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
// Ensure that a private mdata info is encrypted.
#[test]
fn private_mdata_info_encrypts() {
let info = unwrap!(MDataInfo::random_private(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
let enc_key = unwrap!(info.enc_entry_key(&key));
let enc_val = unwrap!(info.enc_entry_value(&val));
assert_ne!(enc_key, key);
assert_ne!(enc_val, val);
assert_eq!(unwrap!(info.decrypt(&enc_key)), key);
assert_eq!(unwrap!(info.decrypt(&enc_val)), val);
}
// Ensure that a public mdata info is not encrypted.
#[test]
fn public_mdata_info_doesnt_encrypt() {
let info = unwrap!(MDataInfo::random_public(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
assert_eq!(unwrap!(info.enc_entry_key(&key)), key);
assert_eq!(unwrap!(info.enc_entry_value(&val)), val);
assert_eq!(unwrap!(info.decrypt(&val)), val);
}
// Test creating and committing new encryption info.
#[test]
fn decrypt() {
let mut info = unwrap!(MDataInfo::random_private(0));
let plain = Vec::from("plaintext");
let old_cipher = unwrap!(info.enc_entry_value(&plain));
info.start_new_enc_info();
let new_cipher = unwrap!(info.enc_entry_value(&plain));
// After start, both encryption infos work.
assert_eq!(unwrap!(info.decrypt(&old_cipher)), plain);
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
// After commit, only the new encryption info works.
info.commit_new_enc_info();
match info.decrypt(&old_cipher) {
Err(CoreError::SymmetricDecipherFailure) => (),
x => panic!("Unexpected {:?}", x),
}
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
}
}
| commit_new_enc_info | identifier_name |
mdata_info.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
use crate::crypto::shared_secretbox;
use crate::errors::CoreError;
use crate::ffi::arrays::{SymNonce, SymSecretKey};
use crate::ffi::MDataInfo as FfiMDataInfo;
use crate::ipc::IpcError;
use crate::utils::{symmetric_decrypt, symmetric_encrypt};
use ffi_utils::ReprC;
use rand::{OsRng, Rng};
use routing::{EntryAction, Value, XorName};
use rust_sodium::crypto::secretbox;
use std::collections::{BTreeMap, BTreeSet};
use tiny_keccak::sha3_256;
/// Information allowing to locate and access mutable data on the network.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct MDataInfo {
/// Name of the data where the directory is stored.
pub name: XorName,
/// Type tag of the data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
}
impl MDataInfo {
/// Construct `MDataInfo` for private (encrypted) data with a provided private key.
pub fn new_private(
name: XorName,
type_tag: u64,
enc_info: (shared_secretbox::Key, secretbox::Nonce),
) -> Self {
MDataInfo {
name,
type_tag,
enc_info: Some(enc_info),
new_enc_info: None,
}
}
/// Construct `MDataInfo` for public data.
pub fn new_public(name: XorName, type_tag: u64) -> Self {
MDataInfo {
name,
type_tag,
enc_info: None,
new_enc_info: None,
}
}
/// Generate random `MDataInfo` for private (encrypted) mutable data.
pub fn random_private(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
let enc_info = (shared_secretbox::gen_key(), secretbox::gen_nonce());
Ok(Self::new_private(rng.gen(), type_tag, enc_info))
}
/// Generate random `MDataInfo` for public mutable data.
pub fn random_public(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
Ok(Self::new_public(rng.gen(), type_tag))
}
/// Returns the encryption key, if any.
pub fn enc_key(&self) -> Option<&shared_secretbox::Key> {
self.enc_info.as_ref().map(|&(ref key, _)| key)
}
/// Returns the nonce, if any.
pub fn nonce(&self) -> Option<&secretbox::Nonce> {
self.enc_info.as_ref().map(|&(_, ref nonce)| nonce)
}
/// Encrypt the key for the mdata entry accordingly.
pub fn enc_entry_key(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, seed)) = self.new_enc_info {
enc_entry_key(plain_text, key, seed)
} else if let Some((ref key, seed)) = self.enc_info {
enc_entry_key(plain_text, key, seed)
} else {
Ok(plain_text.to_vec())
}
}
/// Encrypt the value for this mdata entry accordingly.
pub fn enc_entry_value(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
symmetric_encrypt(plain_text, key, None)
} else if let Some((ref key, _)) = self.enc_info {
symmetric_encrypt(plain_text, key, None)
} else {
Ok(plain_text.to_vec())
}
}
/// Decrypt key or value of this mdata entry.
pub fn decrypt(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
if let Ok(plain) = symmetric_decrypt(cipher, key) {
return Ok(plain);
}
}
if let Some((ref key, _)) = self.enc_info {
symmetric_decrypt(cipher, key)
} else {
Ok(cipher.to_vec())
}
}
/// Start the encryption info re-generation by populating the `new_enc_info`
/// field with random keys, unless it's already populated.
pub fn start_new_enc_info(&mut self) {
if self.enc_info.is_some() && self.new_enc_info.is_none() {
self.new_enc_info = Some((shared_secretbox::gen_key(), secretbox::gen_nonce()));
}
}
/// Commit the encryption info re-generation by replacing the current encryption info
/// with `new_enc_info` (if any).
pub fn commit_new_enc_info(&mut self) {
if let Some(new_enc_info) = self.new_enc_info.take() {
self.enc_info = Some(new_enc_info);
}
}
/// Construct FFI wrapper for the native Rust object, consuming self.
pub fn into_repr_c(self) -> FfiMDataInfo {
let (has_enc_info, enc_key, enc_nonce) = enc_info_into_repr_c(self.enc_info);
let (has_new_enc_info, new_enc_key, new_enc_nonce) =
enc_info_into_repr_c(self.new_enc_info);
FfiMDataInfo {
name: self.name.0,
type_tag: self.type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
}
}
}
fn os_rng() -> Result<OsRng, CoreError> {
OsRng::new().map_err(|_| CoreError::RandomDataGenerationFailure)
}
/// Encrypt the entries (both keys and values) using the `MDataInfo`.
pub fn encrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_value = encrypt_value(info, value)?;
let _ = output.insert(encrypted_key, encrypted_value);
}
Ok(output)
}
/// Encrypt entry actions using the `MDataInfo`. The effect of this is that the entries
/// mutated by the encrypted actions will end up encrypted using the `MDataInfo`.
pub fn encrypt_entry_actions(
info: &MDataInfo,
actions: &BTreeMap<Vec<u8>, EntryAction>,
) -> Result<BTreeMap<Vec<u8>, EntryAction>, CoreError> {
let mut output = BTreeMap::new();
for (key, action) in actions {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_action = match *action {
EntryAction::Ins(ref value) => EntryAction::Ins(encrypt_value(info, value)?),
EntryAction::Update(ref value) => EntryAction::Update(encrypt_value(info, value)?),
EntryAction::Del(version) => EntryAction::Del(version),
};
let _ = output.insert(encrypted_key, encrypted_action);
}
Ok(output)
}
/// Decrypt entries using the `MDataInfo`.
pub fn decrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let decrypted_key = info.decrypt(key)?;
let decrypted_value = decrypt_value(info, value)?;
let _ = output.insert(decrypted_key, decrypted_value);
}
Ok(output)
}
/// Decrypt all keys using the `MDataInfo`.
pub fn decrypt_keys(
info: &MDataInfo,
keys: &BTreeSet<Vec<u8>>,
) -> Result<BTreeSet<Vec<u8>>, CoreError> {
let mut output = BTreeSet::new();
for key in keys {
let _ = output.insert(info.decrypt(key)?);
}
Ok(output)
}
/// Decrypt all values using the `MDataInfo`.
pub fn decrypt_values(info: &MDataInfo, values: &[Value]) -> Result<Vec<Value>, CoreError> {
let mut output = Vec::with_capacity(values.len());
for value in values {
output.push(decrypt_value(info, value)?);
} |
Ok(output)
}
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.decrypt(&value.content)?,
entry_version: value.entry_version,
})
}
fn enc_entry_key(
plain_text: &[u8],
key: &secretbox::Key,
seed: secretbox::Nonce,
) -> Result<Vec<u8>, CoreError> {
let nonce = {
let secretbox::Nonce(ref nonce) = seed;
let mut pt = plain_text.to_vec();
pt.extend_from_slice(&nonce[..]);
unwrap!(secretbox::Nonce::from_slice(
&sha3_256(&pt)[..secretbox::NONCEBYTES],
))
};
symmetric_encrypt(plain_text, key, Some(&nonce))
}
impl ReprC for MDataInfo {
type C = *const FfiMDataInfo;
type Error = IpcError;
#[allow(unsafe_code)]
unsafe fn clone_from_repr_c(repr_c: Self::C) -> Result<Self, Self::Error> {
let FfiMDataInfo {
name,
type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
} = *repr_c;
Ok(Self {
name: XorName(name),
type_tag,
enc_info: enc_info_from_repr_c(has_enc_info, enc_key, enc_nonce),
new_enc_info: enc_info_from_repr_c(has_new_enc_info, new_enc_key, new_enc_nonce),
})
}
}
fn enc_info_into_repr_c(
info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
) -> (bool, SymSecretKey, SymNonce) {
if let Some((key, nonce)) = info {
(true, key.0, nonce.0)
} else {
(false, Default::default(), Default::default())
}
}
fn enc_info_from_repr_c(
is_set: bool,
key: SymSecretKey,
nonce: SymNonce,
) -> Option<(shared_secretbox::Key, secretbox::Nonce)> {
if is_set {
Some((
shared_secretbox::Key::from_raw(&key),
secretbox::Nonce(nonce),
))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
// Ensure that a private mdata info is encrypted.
#[test]
fn private_mdata_info_encrypts() {
let info = unwrap!(MDataInfo::random_private(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
let enc_key = unwrap!(info.enc_entry_key(&key));
let enc_val = unwrap!(info.enc_entry_value(&val));
assert_ne!(enc_key, key);
assert_ne!(enc_val, val);
assert_eq!(unwrap!(info.decrypt(&enc_key)), key);
assert_eq!(unwrap!(info.decrypt(&enc_val)), val);
}
// Ensure that a public mdata info is not encrypted.
#[test]
fn public_mdata_info_doesnt_encrypt() {
let info = unwrap!(MDataInfo::random_public(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
assert_eq!(unwrap!(info.enc_entry_key(&key)), key);
assert_eq!(unwrap!(info.enc_entry_value(&val)), val);
assert_eq!(unwrap!(info.decrypt(&val)), val);
}
// Test creating and committing new encryption info.
#[test]
fn decrypt() {
let mut info = unwrap!(MDataInfo::random_private(0));
let plain = Vec::from("plaintext");
let old_cipher = unwrap!(info.enc_entry_value(&plain));
info.start_new_enc_info();
let new_cipher = unwrap!(info.enc_entry_value(&plain));
// After start, both encryption infos work.
assert_eq!(unwrap!(info.decrypt(&old_cipher)), plain);
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
// After commit, only the new encryption info works.
info.commit_new_enc_info();
match info.decrypt(&old_cipher) {
Err(CoreError::SymmetricDecipherFailure) => (),
x => panic!("Unexpected {:?}", x),
}
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
}
} | random_line_split |
|
mdata_info.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.
use crate::crypto::shared_secretbox;
use crate::errors::CoreError;
use crate::ffi::arrays::{SymNonce, SymSecretKey};
use crate::ffi::MDataInfo as FfiMDataInfo;
use crate::ipc::IpcError;
use crate::utils::{symmetric_decrypt, symmetric_encrypt};
use ffi_utils::ReprC;
use rand::{OsRng, Rng};
use routing::{EntryAction, Value, XorName};
use rust_sodium::crypto::secretbox;
use std::collections::{BTreeMap, BTreeSet};
use tiny_keccak::sha3_256;
/// Information allowing to locate and access mutable data on the network.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct MDataInfo {
/// Name of the data where the directory is stored.
pub name: XorName,
/// Type tag of the data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
}
impl MDataInfo {
/// Construct `MDataInfo` for private (encrypted) data with a provided private key.
pub fn new_private(
name: XorName,
type_tag: u64,
enc_info: (shared_secretbox::Key, secretbox::Nonce),
) -> Self {
MDataInfo {
name,
type_tag,
enc_info: Some(enc_info),
new_enc_info: None,
}
}
/// Construct `MDataInfo` for public data.
pub fn new_public(name: XorName, type_tag: u64) -> Self {
MDataInfo {
name,
type_tag,
enc_info: None,
new_enc_info: None,
}
}
/// Generate random `MDataInfo` for private (encrypted) mutable data.
pub fn random_private(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
let enc_info = (shared_secretbox::gen_key(), secretbox::gen_nonce());
Ok(Self::new_private(rng.gen(), type_tag, enc_info))
}
/// Generate random `MDataInfo` for public mutable data.
pub fn random_public(type_tag: u64) -> Result<Self, CoreError> {
let mut rng = os_rng()?;
Ok(Self::new_public(rng.gen(), type_tag))
}
/// Returns the encryption key, if any.
pub fn enc_key(&self) -> Option<&shared_secretbox::Key> {
self.enc_info.as_ref().map(|&(ref key, _)| key)
}
/// Returns the nonce, if any.
pub fn nonce(&self) -> Option<&secretbox::Nonce> {
self.enc_info.as_ref().map(|&(_, ref nonce)| nonce)
}
/// Encrypt the key for the mdata entry accordingly.
pub fn enc_entry_key(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, seed)) = self.new_enc_info {
enc_entry_key(plain_text, key, seed)
} else if let Some((ref key, seed)) = self.enc_info {
enc_entry_key(plain_text, key, seed)
} else {
Ok(plain_text.to_vec())
}
}
/// Encrypt the value for this mdata entry accordingly.
pub fn enc_entry_value(&self, plain_text: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
symmetric_encrypt(plain_text, key, None)
} else if let Some((ref key, _)) = self.enc_info {
symmetric_encrypt(plain_text, key, None)
} else {
Ok(plain_text.to_vec())
}
}
/// Decrypt key or value of this mdata entry.
pub fn decrypt(&self, cipher: &[u8]) -> Result<Vec<u8>, CoreError> {
if let Some((ref key, _)) = self.new_enc_info {
if let Ok(plain) = symmetric_decrypt(cipher, key) {
return Ok(plain);
}
}
if let Some((ref key, _)) = self.enc_info {
symmetric_decrypt(cipher, key)
} else {
Ok(cipher.to_vec())
}
}
/// Start the encryption info re-generation by populating the `new_enc_info`
/// field with random keys, unless it's already populated.
pub fn start_new_enc_info(&mut self) {
if self.enc_info.is_some() && self.new_enc_info.is_none() {
self.new_enc_info = Some((shared_secretbox::gen_key(), secretbox::gen_nonce()));
}
}
/// Commit the encryption info re-generation by replacing the current encryption info
/// with `new_enc_info` (if any).
pub fn commit_new_enc_info(&mut self) {
if let Some(new_enc_info) = self.new_enc_info.take() {
self.enc_info = Some(new_enc_info);
}
}
/// Construct FFI wrapper for the native Rust object, consuming self.
pub fn into_repr_c(self) -> FfiMDataInfo {
let (has_enc_info, enc_key, enc_nonce) = enc_info_into_repr_c(self.enc_info);
let (has_new_enc_info, new_enc_key, new_enc_nonce) =
enc_info_into_repr_c(self.new_enc_info);
FfiMDataInfo {
name: self.name.0,
type_tag: self.type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
}
}
}
fn os_rng() -> Result<OsRng, CoreError> {
OsRng::new().map_err(|_| CoreError::RandomDataGenerationFailure)
}
/// Encrypt the entries (both keys and values) using the `MDataInfo`.
pub fn encrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_value = encrypt_value(info, value)?;
let _ = output.insert(encrypted_key, encrypted_value);
}
Ok(output)
}
/// Encrypt entry actions using the `MDataInfo`. The effect of this is that the entries
/// mutated by the encrypted actions will end up encrypted using the `MDataInfo`.
pub fn encrypt_entry_actions(
info: &MDataInfo,
actions: &BTreeMap<Vec<u8>, EntryAction>,
) -> Result<BTreeMap<Vec<u8>, EntryAction>, CoreError> {
let mut output = BTreeMap::new();
for (key, action) in actions {
let encrypted_key = info.enc_entry_key(key)?;
let encrypted_action = match *action {
EntryAction::Ins(ref value) => EntryAction::Ins(encrypt_value(info, value)?),
EntryAction::Update(ref value) => EntryAction::Update(encrypt_value(info, value)?),
EntryAction::Del(version) => EntryAction::Del(version),
};
let _ = output.insert(encrypted_key, encrypted_action);
}
Ok(output)
}
/// Decrypt entries using the `MDataInfo`.
pub fn decrypt_entries(
info: &MDataInfo,
entries: &BTreeMap<Vec<u8>, Value>,
) -> Result<BTreeMap<Vec<u8>, Value>, CoreError> {
let mut output = BTreeMap::new();
for (key, value) in entries {
let decrypted_key = info.decrypt(key)?;
let decrypted_value = decrypt_value(info, value)?;
let _ = output.insert(decrypted_key, decrypted_value);
}
Ok(output)
}
/// Decrypt all keys using the `MDataInfo`.
pub fn decrypt_keys(
info: &MDataInfo,
keys: &BTreeSet<Vec<u8>>,
) -> Result<BTreeSet<Vec<u8>>, CoreError> {
let mut output = BTreeSet::new();
for key in keys {
let _ = output.insert(info.decrypt(key)?);
}
Ok(output)
}
/// Decrypt all values using the `MDataInfo`.
pub fn decrypt_values(info: &MDataInfo, values: &[Value]) -> Result<Vec<Value>, CoreError> |
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.decrypt(&value.content)?,
entry_version: value.entry_version,
})
}
fn enc_entry_key(
plain_text: &[u8],
key: &secretbox::Key,
seed: secretbox::Nonce,
) -> Result<Vec<u8>, CoreError> {
let nonce = {
let secretbox::Nonce(ref nonce) = seed;
let mut pt = plain_text.to_vec();
pt.extend_from_slice(&nonce[..]);
unwrap!(secretbox::Nonce::from_slice(
&sha3_256(&pt)[..secretbox::NONCEBYTES],
))
};
symmetric_encrypt(plain_text, key, Some(&nonce))
}
impl ReprC for MDataInfo {
type C = *const FfiMDataInfo;
type Error = IpcError;
#[allow(unsafe_code)]
unsafe fn clone_from_repr_c(repr_c: Self::C) -> Result<Self, Self::Error> {
let FfiMDataInfo {
name,
type_tag,
has_enc_info,
enc_key,
enc_nonce,
has_new_enc_info,
new_enc_key,
new_enc_nonce,
} = *repr_c;
Ok(Self {
name: XorName(name),
type_tag,
enc_info: enc_info_from_repr_c(has_enc_info, enc_key, enc_nonce),
new_enc_info: enc_info_from_repr_c(has_new_enc_info, new_enc_key, new_enc_nonce),
})
}
}
fn enc_info_into_repr_c(
info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
) -> (bool, SymSecretKey, SymNonce) {
if let Some((key, nonce)) = info {
(true, key.0, nonce.0)
} else {
(false, Default::default(), Default::default())
}
}
fn enc_info_from_repr_c(
is_set: bool,
key: SymSecretKey,
nonce: SymNonce,
) -> Option<(shared_secretbox::Key, secretbox::Nonce)> {
if is_set {
Some((
shared_secretbox::Key::from_raw(&key),
secretbox::Nonce(nonce),
))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
// Ensure that a private mdata info is encrypted.
#[test]
fn private_mdata_info_encrypts() {
let info = unwrap!(MDataInfo::random_private(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
let enc_key = unwrap!(info.enc_entry_key(&key));
let enc_val = unwrap!(info.enc_entry_value(&val));
assert_ne!(enc_key, key);
assert_ne!(enc_val, val);
assert_eq!(unwrap!(info.decrypt(&enc_key)), key);
assert_eq!(unwrap!(info.decrypt(&enc_val)), val);
}
// Ensure that a public mdata info is not encrypted.
#[test]
fn public_mdata_info_doesnt_encrypt() {
let info = unwrap!(MDataInfo::random_public(0));
let key = Vec::from("str of key");
let val = Vec::from("other is value");
assert_eq!(unwrap!(info.enc_entry_key(&key)), key);
assert_eq!(unwrap!(info.enc_entry_value(&val)), val);
assert_eq!(unwrap!(info.decrypt(&val)), val);
}
// Test creating and committing new encryption info.
#[test]
fn decrypt() {
let mut info = unwrap!(MDataInfo::random_private(0));
let plain = Vec::from("plaintext");
let old_cipher = unwrap!(info.enc_entry_value(&plain));
info.start_new_enc_info();
let new_cipher = unwrap!(info.enc_entry_value(&plain));
// After start, both encryption infos work.
assert_eq!(unwrap!(info.decrypt(&old_cipher)), plain);
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
// After commit, only the new encryption info works.
info.commit_new_enc_info();
match info.decrypt(&old_cipher) {
Err(CoreError::SymmetricDecipherFailure) => (),
x => panic!("Unexpected {:?}", x),
}
assert_eq!(unwrap!(info.decrypt(&new_cipher)), plain);
}
}
| {
let mut output = Vec::with_capacity(values.len());
for value in values {
output.push(decrypt_value(info, value)?);
}
Ok(output)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.