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 |
---|---|---|---|---|
function-arguments.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.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print x
// gdb-check:$1 = 111102
// gdb-command:print y
// gdb-check:$2 = true
// gdb-command:continue
// gdb-command:finish
// gdb-command:print a
// gdb-check:$3 = 2000
// gdb-command:print b
// gdb-check:$4 = 3000
fn main() {
fun(111102, true);
nested(2000, 3000);
fn nested(a: i32, b: i64) -> (i32, i64) {
zzz();
(a, b)
}
}
fn fun(x: int, y: bool) -> (int, bool) |
fn zzz() {()}
| {
zzz();
(x, y)
} | identifier_body |
errors.rs | use super::ast::AstLocation;
use tok::Tok;
use tok::Location as TokenLocation;
error_chain! {
types {
Error, ErrorKind, ResultExt, Result;
}
foreign_links {
Io(::std::io::Error);
Parse(::lalrpop_util::ParseError<TokenLocation, Tok, char>);
}
errors {
TypeMismatch(expected: &'static str, actual: &'static str, identifier: String, location: AstLocation) {
description("Type mismatch")
display("Type mismatch: Expected {} to be {}, but got {} at {}", identifier, expected, actual, location)
}
MissingVarRef(identifier: String, location: AstLocation) {
description("Missing variable reference")
display("Unresolved variable reference: {} at {}", identifier, location)
}
MissingValue(node: String, location: AstLocation) {
description("Expected expression to return value, none found")
display("Expected Expression to return a value: {:?} at {}", node, location)
}
WrongParameterCount(node: String, expected: usize, actual: usize, location: AstLocation) {
description("Wrong mixin call parameter count")
display("Wrong mixin call parameter count in {}: expected {}, got {} at {}", node, expected, actual, location)
}
IncompatibleTypes(value: String, type_name: &'static str) {
description("Cannot convert value to a given type")
display("Cannot convert {} to {}.", value, type_name)
}
UnsupportedOperation(value: String, op: &'static str) {
description("Operation is unsupported by this type")
display("{} operation cannot be performed with {} because it is not supported.", op, value)
}
ImportError(node: String, location: AstLocation) {
description("Invalid import path") | }
} | display("Invalid import expression: {:?} at {}", node, location)
} | random_line_split |
main.rs | #![feature(slicing_syntax)]
use std::io::{File,BufferedReader};
use std::num::SignedInt; // abs method
use std::io::fs;
fn filesize(size: int) -> String {
let units = "KMGT";
let mut left = size.abs() as f64;
let mut unit = -1i;
while left > 1100. && unit < 3 {
left /= 1024.;
unit += 1;
}
if unit == -1 {
format!("{}B", size)
} else {
if size < 0 {
left = -left;
}
format!("{:.1}{}iB", left, units.char_at(unit as uint))
}
}
fn chop_null(s: String) -> String {
let last = s.len() - 1;
let mut s = s;
if s.len() > 0 && s.as_bytes()[last] == 0 {
s.truncate(last);
}
s.replace("\0", " ")
}
fn get_comm_for(pid: uint) -> String {
let cmdline_path = format!("/proc/{}/cmdline", pid);
match File::open(&Path::new(&cmdline_path)).read_to_string() {
// s may be empty for kernel threads
Ok(s) => chop_null(s),
Err(_) => String::new(),
}
}
fn get_swap_for(pid: uint) -> int |
fn get_swap() -> Vec<(uint, int, String)> {
fs::readdir(&Path::new("/proc")).unwrap().iter().filter_map(
|d| d.filename_str().unwrap().parse().and_then(|pid|
match get_swap_for(pid) {
0 => None,
swap => Some((pid, swap, get_comm_for(pid))),
}
)
).collect()
}
fn main() {
// let format = "{:>5} {:>9} {}";
// let totalFmt = "Total: {:8}";
let mut swapinfo = get_swap();
swapinfo.sort_by(|&(_, a, _), &(_, b, _)| { a.cmp(&b) });
println!("{:>5} {:>9} {}", "PID", "SWAP", "COMMAND");
let mut total = 0i;
for &(pid, swap, ref comm) in swapinfo.iter() {
total += swap;
println!("{:>5} {:>9} {}", pid, filesize(swap), comm);
}
println!("Total: {:>8}", filesize(total));
}
// vim: se sw=2:
| {
let smaps_path = format!("/proc/{}/smaps", pid);
let mut file = BufferedReader::new(File::open(&Path::new(smaps_path)));
let mut s = 0;
for l in file.lines() {
let line = match l {
Ok(s) => s,
Err(_) => return 0,
};
if line.starts_with("Swap:") {
s += line.words().nth(1).unwrap().parse().unwrap();
}
}
s * 1024
} | identifier_body |
main.rs | #![feature(slicing_syntax)]
use std::io::{File,BufferedReader};
use std::num::SignedInt; // abs method
use std::io::fs;
fn filesize(size: int) -> String {
let units = "KMGT";
let mut left = size.abs() as f64;
let mut unit = -1i;
while left > 1100. && unit < 3 {
left /= 1024.;
unit += 1;
}
if unit == -1 {
format!("{}B", size)
} else {
if size < 0 {
left = -left;
}
format!("{:.1}{}iB", left, units.char_at(unit as uint))
}
}
fn chop_null(s: String) -> String {
let last = s.len() - 1;
let mut s = s;
if s.len() > 0 && s.as_bytes()[last] == 0 {
s.truncate(last);
}
s.replace("\0", " ")
}
fn | (pid: uint) -> String {
let cmdline_path = format!("/proc/{}/cmdline", pid);
match File::open(&Path::new(&cmdline_path)).read_to_string() {
// s may be empty for kernel threads
Ok(s) => chop_null(s),
Err(_) => String::new(),
}
}
fn get_swap_for(pid: uint) -> int {
let smaps_path = format!("/proc/{}/smaps", pid);
let mut file = BufferedReader::new(File::open(&Path::new(smaps_path)));
let mut s = 0;
for l in file.lines() {
let line = match l {
Ok(s) => s,
Err(_) => return 0,
};
if line.starts_with("Swap:") {
s += line.words().nth(1).unwrap().parse().unwrap();
}
}
s * 1024
}
fn get_swap() -> Vec<(uint, int, String)> {
fs::readdir(&Path::new("/proc")).unwrap().iter().filter_map(
|d| d.filename_str().unwrap().parse().and_then(|pid|
match get_swap_for(pid) {
0 => None,
swap => Some((pid, swap, get_comm_for(pid))),
}
)
).collect()
}
fn main() {
// let format = "{:>5} {:>9} {}";
// let totalFmt = "Total: {:8}";
let mut swapinfo = get_swap();
swapinfo.sort_by(|&(_, a, _), &(_, b, _)| { a.cmp(&b) });
println!("{:>5} {:>9} {}", "PID", "SWAP", "COMMAND");
let mut total = 0i;
for &(pid, swap, ref comm) in swapinfo.iter() {
total += swap;
println!("{:>5} {:>9} {}", pid, filesize(swap), comm);
}
println!("Total: {:>8}", filesize(total));
}
// vim: se sw=2:
| get_comm_for | identifier_name |
main.rs | #![feature(slicing_syntax)]
use std::io::{File,BufferedReader};
use std::num::SignedInt; // abs method
use std::io::fs;
fn filesize(size: int) -> String {
let units = "KMGT";
let mut left = size.abs() as f64;
let mut unit = -1i; |
while left > 1100. && unit < 3 {
left /= 1024.;
unit += 1;
}
if unit == -1 {
format!("{}B", size)
} else {
if size < 0 {
left = -left;
}
format!("{:.1}{}iB", left, units.char_at(unit as uint))
}
}
fn chop_null(s: String) -> String {
let last = s.len() - 1;
let mut s = s;
if s.len() > 0 && s.as_bytes()[last] == 0 {
s.truncate(last);
}
s.replace("\0", " ")
}
fn get_comm_for(pid: uint) -> String {
let cmdline_path = format!("/proc/{}/cmdline", pid);
match File::open(&Path::new(&cmdline_path)).read_to_string() {
// s may be empty for kernel threads
Ok(s) => chop_null(s),
Err(_) => String::new(),
}
}
fn get_swap_for(pid: uint) -> int {
let smaps_path = format!("/proc/{}/smaps", pid);
let mut file = BufferedReader::new(File::open(&Path::new(smaps_path)));
let mut s = 0;
for l in file.lines() {
let line = match l {
Ok(s) => s,
Err(_) => return 0,
};
if line.starts_with("Swap:") {
s += line.words().nth(1).unwrap().parse().unwrap();
}
}
s * 1024
}
fn get_swap() -> Vec<(uint, int, String)> {
fs::readdir(&Path::new("/proc")).unwrap().iter().filter_map(
|d| d.filename_str().unwrap().parse().and_then(|pid|
match get_swap_for(pid) {
0 => None,
swap => Some((pid, swap, get_comm_for(pid))),
}
)
).collect()
}
fn main() {
// let format = "{:>5} {:>9} {}";
// let totalFmt = "Total: {:8}";
let mut swapinfo = get_swap();
swapinfo.sort_by(|&(_, a, _), &(_, b, _)| { a.cmp(&b) });
println!("{:>5} {:>9} {}", "PID", "SWAP", "COMMAND");
let mut total = 0i;
for &(pid, swap, ref comm) in swapinfo.iter() {
total += swap;
println!("{:>5} {:>9} {}", pid, filesize(swap), comm);
}
println!("Total: {:>8}", filesize(total));
}
// vim: se sw=2: | random_line_split |
|
event.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 crate::dom::bindings::callback::ExceptionHandling;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::EventBinding;
use crate::dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{DomRoot, MutNullableDom, RootedReference};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::Document;
use crate::dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase};
use crate::dom::globalscope::GlobalScope;
use crate::dom::node::Node;
use crate::dom::virtualmethods::vtable_for;
use crate::dom::window::Window;
use crate::task::TaskOnce;
use devtools_traits::{TimelineMarker, TimelineMarkerType};
use dom_struct::dom_struct;
use servo_atoms::Atom;
use std::cell::Cell;
use std::default::Default;
#[dom_struct]
pub struct Event {
reflector_: Reflector,
current_target: MutNullableDom<EventTarget>,
target: MutNullableDom<EventTarget>,
type_: DomRefCell<Atom>,
phase: Cell<EventPhase>,
canceled: Cell<EventDefault>,
stop_propagation: Cell<bool>,
stop_immediate: Cell<bool>,
cancelable: Cell<bool>,
bubbles: Cell<bool>,
trusted: Cell<bool>,
dispatching: Cell<bool>,
initialized: Cell<bool>,
timestamp: u64,
}
impl Event {
pub fn new_inherited() -> Event {
Event {
reflector_: Reflector::new(),
current_target: Default::default(),
target: Default::default(),
type_: DomRefCell::new(atom!("")),
phase: Cell::new(EventPhase::None),
canceled: Cell::new(EventDefault::Allowed),
stop_propagation: Cell::new(false),
stop_immediate: Cell::new(false),
cancelable: Cell::new(false),
bubbles: Cell::new(false),
trusted: Cell::new(false),
dispatching: Cell::new(false),
initialized: Cell::new(false),
timestamp: time::get_time().sec as u64,
}
}
pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<Event> {
reflect_dom_object(Box::new(Event::new_inherited()), global, EventBinding::Wrap)
}
pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
) -> DomRoot<Event> {
let event = Event::new_uninitialized(global);
event.init_event(type_, bool::from(bubbles), bool::from(cancelable));
event
}
pub fn Constructor(
global: &GlobalScope,
type_: DOMString,
init: &EventBinding::EventInit,
) -> Fallible<DomRoot<Event>> {
let bubbles = EventBubbles::from(init.bubbles);
let cancelable = EventCancelable::from(init.cancelable);
Ok(Event::new(global, Atom::from(type_), bubbles, cancelable))
}
pub fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) {
if self.dispatching.get() {
return;
}
self.initialized.set(true);
self.stop_propagation.set(false);
self.stop_immediate.set(false);
self.canceled.set(EventDefault::Allowed);
self.trusted.set(false);
self.target.set(None);
*self.type_.borrow_mut() = type_;
self.bubbles.set(bubbles);
self.cancelable.set(cancelable);
}
// Determine if there are any listeners for a given target and type.
// See https://github.com/whatwg/dom/issues/453
pub fn has_listeners_for(&self, target: &EventTarget, type_: &Atom) -> bool {
// TODO: take'removed' into account? Not implemented in Servo yet.
// https://dom.spec.whatwg.org/#event-listener-removed
let mut event_path = self.construct_event_path(&target);
event_path.push(DomRoot::from_ref(target));
event_path
.iter()
.any(|target| target.has_listeners_for(type_))
}
// https://dom.spec.whatwg.org/#event-path
fn construct_event_path(&self, target: &EventTarget) -> Vec<DomRoot<EventTarget>> {
let mut event_path = vec![];
// The "invoke" algorithm is only used on `target` separately,
// so we don't put it in the path.
if let Some(target_node) = target.downcast::<Node>() {
for ancestor in target_node.ancestors() {
event_path.push(DomRoot::from_ref(ancestor.upcast::<EventTarget>()));
}
let top_most_ancestor_or_target = event_path
.last()
.cloned()
.unwrap_or(DomRoot::from_ref(target));
if let Some(document) = DomRoot::downcast::<Document>(top_most_ancestor_or_target) {
if self.type_()!= atom!("load") && document.browsing_context().is_some() {
event_path.push(DomRoot::from_ref(document.window().upcast()));
}
}
}
event_path
}
// https://dom.spec.whatwg.org/#concept-event-dispatch
pub fn dispatch(
&self,
target: &EventTarget,
target_override: Option<&EventTarget>,
) -> EventStatus {
assert!(!self.dispatching());
assert!(self.initialized());
assert_eq!(self.phase.get(), EventPhase::None);
assert!(self.GetCurrentTarget().is_none());
// Step 1.
self.dispatching.set(true);
// Step 2.
self.target.set(Some(target_override.unwrap_or(target)));
if self.stop_propagation.get() {
// If the event's stop propagation flag is set, we can skip everything because
// it prevents the calls of the invoke algorithm in the spec.
// Step 10-12.
self.clear_dispatching_flags();
// Step 14.
return self.status();
}
// Step 3-4.
let path = self.construct_event_path(&target);
rooted_vec!(let event_path <- path.into_iter());
// Steps 5-9. In a separate function to short-circuit various things easily.
dispatch_to_listeners(self, target, event_path.r());
// Default action.
if let Some(target) = self.GetTarget() {
if let Some(node) = target.downcast::<Node>() {
let vtable = vtable_for(&node);
vtable.handle_event(self);
}
}
// Step 10-12.
self.clear_dispatching_flags();
// Step 14.
self.status()
}
pub fn status(&self) -> EventStatus {
match self.DefaultPrevented() {
true => EventStatus::Canceled,
false => EventStatus::NotCanceled,
}
}
#[inline]
pub fn dispatching(&self) -> bool {
self.dispatching.get()
}
#[inline]
// https://dom.spec.whatwg.org/#concept-event-dispatch Steps 10-12.
fn clear_dispatching_flags(&self) {
assert!(self.dispatching.get());
self.dispatching.set(false);
self.stop_propagation.set(false);
self.stop_immediate.set(false);
self.phase.set(EventPhase::None);
self.current_target.set(None);
}
#[inline]
pub fn initialized(&self) -> bool {
self.initialized.get()
}
#[inline]
pub fn type_(&self) -> Atom {
self.type_.borrow().clone()
}
#[inline]
pub fn mark_as_handled(&self) {
self.canceled.set(EventDefault::Handled);
}
#[inline]
pub fn get_cancel_state(&self) -> EventDefault {
self.canceled.get()
}
pub fn set_trusted(&self, trusted: bool) {
self.trusted.set(trusted);
}
// https://html.spec.whatwg.org/multipage/#fire-a-simple-event
pub fn fire(&self, target: &EventTarget) -> EventStatus {
self.set_trusted(true);
target.dispatch_event(self)
}
}
impl EventMethods for Event {
// https://dom.spec.whatwg.org/#dom-event-eventphase
fn EventPhase(&self) -> u16 {
self.phase.get() as u16
}
// https://dom.spec.whatwg.org/#dom-event-type
fn Type(&self) -> DOMString {
DOMString::from(&*self.type_()) // FIXME(ajeffrey): Directly convert from Atom to DOMString
}
// https://dom.spec.whatwg.org/#dom-event-target
fn GetTarget(&self) -> Option<DomRoot<EventTarget>> {
self.target.get()
}
// https://dom.spec.whatwg.org/#dom-event-currenttarget
fn GetCurrentTarget(&self) -> Option<DomRoot<EventTarget>> {
self.current_target.get()
}
// https://dom.spec.whatwg.org/#dom-event-defaultprevented
fn DefaultPrevented(&self) -> bool {
self.canceled.get() == EventDefault::Prevented
}
// https://dom.spec.whatwg.org/#dom-event-preventdefault
fn PreventDefault(&self) {
if self.cancelable.get() {
self.canceled.set(EventDefault::Prevented)
}
}
// https://dom.spec.whatwg.org/#dom-event-stoppropagation
fn StopPropagation(&self) {
self.stop_propagation.set(true);
}
// https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation
fn StopImmediatePropagation(&self) {
self.stop_immediate.set(true);
self.stop_propagation.set(true);
}
// https://dom.spec.whatwg.org/#dom-event-bubbles
fn Bubbles(&self) -> bool {
self.bubbles.get()
}
// https://dom.spec.whatwg.org/#dom-event-cancelable
fn Cancelable(&self) -> bool {
self.cancelable.get()
}
// https://dom.spec.whatwg.org/#dom-event-timestamp
fn TimeStamp(&self) -> u64 {
self.timestamp
}
// https://dom.spec.whatwg.org/#dom-event-initevent
fn InitEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool) {
self.init_event(Atom::from(type_), bubbles, cancelable)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.trusted.get()
}
}
#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
pub enum EventBubbles {
Bubbles,
DoesNotBubble,
}
impl From<bool> for EventBubbles {
fn from(boolean: bool) -> Self {
match boolean {
true => EventBubbles::Bubbles,
false => EventBubbles::DoesNotBubble,
}
}
}
impl From<EventBubbles> for bool {
fn | (bubbles: EventBubbles) -> Self {
match bubbles {
EventBubbles::Bubbles => true,
EventBubbles::DoesNotBubble => false,
}
}
}
#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
pub enum EventCancelable {
Cancelable,
NotCancelable,
}
impl From<bool> for EventCancelable {
fn from(boolean: bool) -> Self {
match boolean {
true => EventCancelable::Cancelable,
false => EventCancelable::NotCancelable,
}
}
}
impl From<EventCancelable> for bool {
fn from(bubbles: EventCancelable) -> Self {
match bubbles {
EventCancelable::Cancelable => true,
EventCancelable::NotCancelable => false,
}
}
}
#[derive(Clone, Copy, Debug, Eq, JSTraceable, PartialEq)]
#[repr(u16)]
#[derive(MallocSizeOf)]
pub enum EventPhase {
None = EventConstants::NONE,
Capturing = EventConstants::CAPTURING_PHASE,
AtTarget = EventConstants::AT_TARGET,
Bubbling = EventConstants::BUBBLING_PHASE,
}
/// An enum to indicate whether the default action of an event is allowed.
///
/// This should've been a bool. Instead, it's an enum, because, aside from the allowed/canceled
/// states, we also need something to stop the event from being handled again (without cancelling
/// the event entirely). For example, an Up/Down `KeyEvent` inside a `textarea` element will
/// trigger the cursor to go up/down if the text inside the element spans multiple lines. This enum
/// helps us to prevent such events from being [sent to the constellation][msg] where it will be
/// handled once again for page scrolling (which is definitely not what we'd want).
///
/// [msg]: https://doc.servo.org/script_traits/enum.ConstellationMsg.html#variant.KeyEvent
///
#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
pub enum EventDefault {
/// The default action of the event is allowed (constructor's default)
Allowed,
/// The default action has been prevented by calling `PreventDefault`
Prevented,
/// The event has been handled somewhere in the DOM, and it should be prevented from being
/// re-handled elsewhere. This doesn't affect the judgement of `DefaultPrevented`
Handled,
}
#[derive(PartialEq)]
pub enum EventStatus {
Canceled,
NotCanceled,
}
// https://dom.spec.whatwg.org/#concept-event-fire
pub struct EventTask {
pub target: Trusted<EventTarget>,
pub name: Atom,
pub bubbles: EventBubbles,
pub cancelable: EventCancelable,
}
impl TaskOnce for EventTask {
fn run_once(self) {
let target = self.target.root();
let bubbles = self.bubbles;
let cancelable = self.cancelable;
target.fire_event_with_params(self.name, bubbles, cancelable);
}
}
// https://html.spec.whatwg.org/multipage/#fire-a-simple-event
pub struct SimpleEventTask {
pub target: Trusted<EventTarget>,
pub name: Atom,
}
impl TaskOnce for SimpleEventTask {
fn run_once(self) {
let target = self.target.root();
target.fire_event(self.name);
}
}
// See dispatch_event.
// https://dom.spec.whatwg.org/#concept-event-dispatch
fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&EventTarget]) {
assert!(!event.stop_propagation.get());
assert!(!event.stop_immediate.get());
let window = match DomRoot::downcast::<Window>(target.global()) {
Some(window) => {
if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) {
Some(window)
} else {
None
}
},
_ => None,
};
// Step 5.
event.phase.set(EventPhase::Capturing);
// Step 6.
for object in event_path.iter().rev() {
invoke(window.r(), object, event, Some(ListenerPhase::Capturing));
if event.stop_propagation.get() {
return;
}
}
assert!(!event.stop_propagation.get());
assert!(!event.stop_immediate.get());
// Step 7.
event.phase.set(EventPhase::AtTarget);
// Step 8.
invoke(window.r(), target, event, None);
if event.stop_propagation.get() {
return;
}
assert!(!event.stop_propagation.get());
assert!(!event.stop_immediate.get());
if!event.bubbles.get() {
return;
}
// Step 9.1.
event.phase.set(EventPhase::Bubbling);
// Step 9.2.
for object in event_path {
invoke(window.r(), object, event, Some(ListenerPhase::Bubbling));
if event.stop_propagation.get() {
return;
}
}
}
// https://dom.spec.whatwg.org/#concept-event-listener-invoke
fn invoke(
window: Option<&Window>,
object: &EventTarget,
event: &Event,
specific_listener_phase: Option<ListenerPhase>,
) {
// Step 1.
assert!(!event.stop_propagation.get());
// Steps 2-3.
let listeners = object.get_listeners_for(&event.type_(), specific_listener_phase);
// Step 4.
event.current_target.set(Some(object));
// Step 5.
inner_invoke(window, object, event, &listeners);
// TODO: step 6.
}
// https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
fn inner_invoke(
window: Option<&Window>,
object: &EventTarget,
event: &Event,
listeners: &[CompiledEventListener],
) -> bool {
// Step 1.
let mut found = false;
// Step 2.
for listener in listeners {
// Steps 2.1 and 2.3-2.4 are not done because `listeners` contain only the
// relevant ones for this invoke call during the dispatch algorithm.
// Step 2.2.
found = true;
// TODO: step 2.5.
// Step 2.6.
let marker = TimelineMarker::start("DOMEvent".to_owned());
listener.call_or_handle_event(object, event, ExceptionHandling::Report);
if let Some(window) = window {
window.emit_timeline_marker(marker.end());
}
if event.stop_immediate.get() {
return found;
}
// TODO: step 2.7.
}
// Step 3.
found
}
impl Default for EventBinding::EventInit {
fn default() -> EventBinding::EventInit {
EventBinding::EventInit {
bubbles: false,
cancelable: false,
}
}
}
| from | identifier_name |
event.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 crate::dom::bindings::callback::ExceptionHandling;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::EventBinding;
use crate::dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{DomRoot, MutNullableDom, RootedReference};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::Document;
use crate::dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase};
use crate::dom::globalscope::GlobalScope;
use crate::dom::node::Node;
use crate::dom::virtualmethods::vtable_for;
use crate::dom::window::Window;
use crate::task::TaskOnce;
use devtools_traits::{TimelineMarker, TimelineMarkerType};
use dom_struct::dom_struct;
use servo_atoms::Atom;
use std::cell::Cell;
use std::default::Default;
#[dom_struct]
pub struct Event {
reflector_: Reflector,
current_target: MutNullableDom<EventTarget>,
target: MutNullableDom<EventTarget>,
type_: DomRefCell<Atom>,
phase: Cell<EventPhase>,
canceled: Cell<EventDefault>,
stop_propagation: Cell<bool>,
stop_immediate: Cell<bool>,
cancelable: Cell<bool>,
bubbles: Cell<bool>,
trusted: Cell<bool>,
dispatching: Cell<bool>,
initialized: Cell<bool>,
timestamp: u64,
}
impl Event {
pub fn new_inherited() -> Event |
pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<Event> {
reflect_dom_object(Box::new(Event::new_inherited()), global, EventBinding::Wrap)
}
pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
) -> DomRoot<Event> {
let event = Event::new_uninitialized(global);
event.init_event(type_, bool::from(bubbles), bool::from(cancelable));
event
}
pub fn Constructor(
global: &GlobalScope,
type_: DOMString,
init: &EventBinding::EventInit,
) -> Fallible<DomRoot<Event>> {
let bubbles = EventBubbles::from(init.bubbles);
let cancelable = EventCancelable::from(init.cancelable);
Ok(Event::new(global, Atom::from(type_), bubbles, cancelable))
}
pub fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) {
if self.dispatching.get() {
return;
}
self.initialized.set(true);
self.stop_propagation.set(false);
self.stop_immediate.set(false);
self.canceled.set(EventDefault::Allowed);
self.trusted.set(false);
self.target.set(None);
*self.type_.borrow_mut() = type_;
self.bubbles.set(bubbles);
self.cancelable.set(cancelable);
}
// Determine if there are any listeners for a given target and type.
// See https://github.com/whatwg/dom/issues/453
pub fn has_listeners_for(&self, target: &EventTarget, type_: &Atom) -> bool {
// TODO: take'removed' into account? Not implemented in Servo yet.
// https://dom.spec.whatwg.org/#event-listener-removed
let mut event_path = self.construct_event_path(&target);
event_path.push(DomRoot::from_ref(target));
event_path
.iter()
.any(|target| target.has_listeners_for(type_))
}
// https://dom.spec.whatwg.org/#event-path
fn construct_event_path(&self, target: &EventTarget) -> Vec<DomRoot<EventTarget>> {
let mut event_path = vec![];
// The "invoke" algorithm is only used on `target` separately,
// so we don't put it in the path.
if let Some(target_node) = target.downcast::<Node>() {
for ancestor in target_node.ancestors() {
event_path.push(DomRoot::from_ref(ancestor.upcast::<EventTarget>()));
}
let top_most_ancestor_or_target = event_path
.last()
.cloned()
.unwrap_or(DomRoot::from_ref(target));
if let Some(document) = DomRoot::downcast::<Document>(top_most_ancestor_or_target) {
if self.type_()!= atom!("load") && document.browsing_context().is_some() {
event_path.push(DomRoot::from_ref(document.window().upcast()));
}
}
}
event_path
}
// https://dom.spec.whatwg.org/#concept-event-dispatch
pub fn dispatch(
&self,
target: &EventTarget,
target_override: Option<&EventTarget>,
) -> EventStatus {
assert!(!self.dispatching());
assert!(self.initialized());
assert_eq!(self.phase.get(), EventPhase::None);
assert!(self.GetCurrentTarget().is_none());
// Step 1.
self.dispatching.set(true);
// Step 2.
self.target.set(Some(target_override.unwrap_or(target)));
if self.stop_propagation.get() {
// If the event's stop propagation flag is set, we can skip everything because
// it prevents the calls of the invoke algorithm in the spec.
// Step 10-12.
self.clear_dispatching_flags();
// Step 14.
return self.status();
}
// Step 3-4.
let path = self.construct_event_path(&target);
rooted_vec!(let event_path <- path.into_iter());
// Steps 5-9. In a separate function to short-circuit various things easily.
dispatch_to_listeners(self, target, event_path.r());
// Default action.
if let Some(target) = self.GetTarget() {
if let Some(node) = target.downcast::<Node>() {
let vtable = vtable_for(&node);
vtable.handle_event(self);
}
}
// Step 10-12.
self.clear_dispatching_flags();
// Step 14.
self.status()
}
pub fn status(&self) -> EventStatus {
match self.DefaultPrevented() {
true => EventStatus::Canceled,
false => EventStatus::NotCanceled,
}
}
#[inline]
pub fn dispatching(&self) -> bool {
self.dispatching.get()
}
#[inline]
// https://dom.spec.whatwg.org/#concept-event-dispatch Steps 10-12.
fn clear_dispatching_flags(&self) {
assert!(self.dispatching.get());
self.dispatching.set(false);
self.stop_propagation.set(false);
self.stop_immediate.set(false);
self.phase.set(EventPhase::None);
self.current_target.set(None);
}
#[inline]
pub fn initialized(&self) -> bool {
self.initialized.get()
}
#[inline]
pub fn type_(&self) -> Atom {
self.type_.borrow().clone()
}
#[inline]
pub fn mark_as_handled(&self) {
self.canceled.set(EventDefault::Handled);
}
#[inline]
pub fn get_cancel_state(&self) -> EventDefault {
self.canceled.get()
}
pub fn set_trusted(&self, trusted: bool) {
self.trusted.set(trusted);
}
// https://html.spec.whatwg.org/multipage/#fire-a-simple-event
pub fn fire(&self, target: &EventTarget) -> EventStatus {
self.set_trusted(true);
target.dispatch_event(self)
}
}
impl EventMethods for Event {
// https://dom.spec.whatwg.org/#dom-event-eventphase
fn EventPhase(&self) -> u16 {
self.phase.get() as u16
}
// https://dom.spec.whatwg.org/#dom-event-type
fn Type(&self) -> DOMString {
DOMString::from(&*self.type_()) // FIXME(ajeffrey): Directly convert from Atom to DOMString
}
// https://dom.spec.whatwg.org/#dom-event-target
fn GetTarget(&self) -> Option<DomRoot<EventTarget>> {
self.target.get()
}
// https://dom.spec.whatwg.org/#dom-event-currenttarget
fn GetCurrentTarget(&self) -> Option<DomRoot<EventTarget>> {
self.current_target.get()
}
// https://dom.spec.whatwg.org/#dom-event-defaultprevented
fn DefaultPrevented(&self) -> bool {
self.canceled.get() == EventDefault::Prevented
}
// https://dom.spec.whatwg.org/#dom-event-preventdefault
fn PreventDefault(&self) {
if self.cancelable.get() {
self.canceled.set(EventDefault::Prevented)
}
}
// https://dom.spec.whatwg.org/#dom-event-stoppropagation
fn StopPropagation(&self) {
self.stop_propagation.set(true);
}
// https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation
fn StopImmediatePropagation(&self) {
self.stop_immediate.set(true);
self.stop_propagation.set(true);
}
// https://dom.spec.whatwg.org/#dom-event-bubbles
fn Bubbles(&self) -> bool {
self.bubbles.get()
}
// https://dom.spec.whatwg.org/#dom-event-cancelable
fn Cancelable(&self) -> bool {
self.cancelable.get()
}
// https://dom.spec.whatwg.org/#dom-event-timestamp
fn TimeStamp(&self) -> u64 {
self.timestamp
}
// https://dom.spec.whatwg.org/#dom-event-initevent
fn InitEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool) {
self.init_event(Atom::from(type_), bubbles, cancelable)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.trusted.get()
}
}
#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
pub enum EventBubbles {
Bubbles,
DoesNotBubble,
}
impl From<bool> for EventBubbles {
fn from(boolean: bool) -> Self {
match boolean {
true => EventBubbles::Bubbles,
false => EventBubbles::DoesNotBubble,
}
}
}
impl From<EventBubbles> for bool {
fn from(bubbles: EventBubbles) -> Self {
match bubbles {
EventBubbles::Bubbles => true,
EventBubbles::DoesNotBubble => false,
}
}
}
#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
pub enum EventCancelable {
Cancelable,
NotCancelable,
}
impl From<bool> for EventCancelable {
fn from(boolean: bool) -> Self {
match boolean {
true => EventCancelable::Cancelable,
false => EventCancelable::NotCancelable,
}
}
}
impl From<EventCancelable> for bool {
fn from(bubbles: EventCancelable) -> Self {
match bubbles {
EventCancelable::Cancelable => true,
EventCancelable::NotCancelable => false,
}
}
}
#[derive(Clone, Copy, Debug, Eq, JSTraceable, PartialEq)]
#[repr(u16)]
#[derive(MallocSizeOf)]
pub enum EventPhase {
None = EventConstants::NONE,
Capturing = EventConstants::CAPTURING_PHASE,
AtTarget = EventConstants::AT_TARGET,
Bubbling = EventConstants::BUBBLING_PHASE,
}
/// An enum to indicate whether the default action of an event is allowed.
///
/// This should've been a bool. Instead, it's an enum, because, aside from the allowed/canceled
/// states, we also need something to stop the event from being handled again (without cancelling
/// the event entirely). For example, an Up/Down `KeyEvent` inside a `textarea` element will
/// trigger the cursor to go up/down if the text inside the element spans multiple lines. This enum
/// helps us to prevent such events from being [sent to the constellation][msg] where it will be
/// handled once again for page scrolling (which is definitely not what we'd want).
///
/// [msg]: https://doc.servo.org/script_traits/enum.ConstellationMsg.html#variant.KeyEvent
///
#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
pub enum EventDefault {
/// The default action of the event is allowed (constructor's default)
Allowed,
/// The default action has been prevented by calling `PreventDefault`
Prevented,
/// The event has been handled somewhere in the DOM, and it should be prevented from being
/// re-handled elsewhere. This doesn't affect the judgement of `DefaultPrevented`
Handled,
}
#[derive(PartialEq)]
pub enum EventStatus {
Canceled,
NotCanceled,
}
// https://dom.spec.whatwg.org/#concept-event-fire
pub struct EventTask {
pub target: Trusted<EventTarget>,
pub name: Atom,
pub bubbles: EventBubbles,
pub cancelable: EventCancelable,
}
impl TaskOnce for EventTask {
fn run_once(self) {
let target = self.target.root();
let bubbles = self.bubbles;
let cancelable = self.cancelable;
target.fire_event_with_params(self.name, bubbles, cancelable);
}
}
// https://html.spec.whatwg.org/multipage/#fire-a-simple-event
pub struct SimpleEventTask {
pub target: Trusted<EventTarget>,
pub name: Atom,
}
impl TaskOnce for SimpleEventTask {
fn run_once(self) {
let target = self.target.root();
target.fire_event(self.name);
}
}
// See dispatch_event.
// https://dom.spec.whatwg.org/#concept-event-dispatch
fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&EventTarget]) {
assert!(!event.stop_propagation.get());
assert!(!event.stop_immediate.get());
let window = match DomRoot::downcast::<Window>(target.global()) {
Some(window) => {
if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) {
Some(window)
} else {
None
}
},
_ => None,
};
// Step 5.
event.phase.set(EventPhase::Capturing);
// Step 6.
for object in event_path.iter().rev() {
invoke(window.r(), object, event, Some(ListenerPhase::Capturing));
if event.stop_propagation.get() {
return;
}
}
assert!(!event.stop_propagation.get());
assert!(!event.stop_immediate.get());
// Step 7.
event.phase.set(EventPhase::AtTarget);
// Step 8.
invoke(window.r(), target, event, None);
if event.stop_propagation.get() {
return;
}
assert!(!event.stop_propagation.get());
assert!(!event.stop_immediate.get());
if!event.bubbles.get() {
return;
}
// Step 9.1.
event.phase.set(EventPhase::Bubbling);
// Step 9.2.
for object in event_path {
invoke(window.r(), object, event, Some(ListenerPhase::Bubbling));
if event.stop_propagation.get() {
return;
}
}
}
// https://dom.spec.whatwg.org/#concept-event-listener-invoke
fn invoke(
window: Option<&Window>,
object: &EventTarget,
event: &Event,
specific_listener_phase: Option<ListenerPhase>,
) {
// Step 1.
assert!(!event.stop_propagation.get());
// Steps 2-3.
let listeners = object.get_listeners_for(&event.type_(), specific_listener_phase);
// Step 4.
event.current_target.set(Some(object));
// Step 5.
inner_invoke(window, object, event, &listeners);
// TODO: step 6.
}
// https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
fn inner_invoke(
window: Option<&Window>,
object: &EventTarget,
event: &Event,
listeners: &[CompiledEventListener],
) -> bool {
// Step 1.
let mut found = false;
// Step 2.
for listener in listeners {
// Steps 2.1 and 2.3-2.4 are not done because `listeners` contain only the
// relevant ones for this invoke call during the dispatch algorithm.
// Step 2.2.
found = true;
// TODO: step 2.5.
// Step 2.6.
let marker = TimelineMarker::start("DOMEvent".to_owned());
listener.call_or_handle_event(object, event, ExceptionHandling::Report);
if let Some(window) = window {
window.emit_timeline_marker(marker.end());
}
if event.stop_immediate.get() {
return found;
}
// TODO: step 2.7.
}
// Step 3.
found
}
impl Default for EventBinding::EventInit {
fn default() -> EventBinding::EventInit {
EventBinding::EventInit {
bubbles: false,
cancelable: false,
}
}
}
| {
Event {
reflector_: Reflector::new(),
current_target: Default::default(),
target: Default::default(),
type_: DomRefCell::new(atom!("")),
phase: Cell::new(EventPhase::None),
canceled: Cell::new(EventDefault::Allowed),
stop_propagation: Cell::new(false),
stop_immediate: Cell::new(false),
cancelable: Cell::new(false),
bubbles: Cell::new(false),
trusted: Cell::new(false),
dispatching: Cell::new(false),
initialized: Cell::new(false),
timestamp: time::get_time().sec as u64,
}
} | identifier_body |
event.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 crate::dom::bindings::callback::ExceptionHandling;
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::EventBinding;
use crate::dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::inheritance::Castable;
use crate::dom::bindings::refcounted::Trusted;
use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector};
use crate::dom::bindings::root::{DomRoot, MutNullableDom, RootedReference};
use crate::dom::bindings::str::DOMString;
use crate::dom::document::Document;
use crate::dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase};
use crate::dom::globalscope::GlobalScope;
use crate::dom::node::Node;
use crate::dom::virtualmethods::vtable_for;
use crate::dom::window::Window;
use crate::task::TaskOnce;
use devtools_traits::{TimelineMarker, TimelineMarkerType};
use dom_struct::dom_struct;
use servo_atoms::Atom;
use std::cell::Cell;
use std::default::Default;
#[dom_struct]
pub struct Event {
reflector_: Reflector,
current_target: MutNullableDom<EventTarget>,
target: MutNullableDom<EventTarget>,
type_: DomRefCell<Atom>,
phase: Cell<EventPhase>,
canceled: Cell<EventDefault>,
stop_propagation: Cell<bool>,
stop_immediate: Cell<bool>,
cancelable: Cell<bool>,
bubbles: Cell<bool>,
trusted: Cell<bool>,
dispatching: Cell<bool>,
initialized: Cell<bool>,
timestamp: u64,
}
impl Event {
pub fn new_inherited() -> Event {
Event {
reflector_: Reflector::new(),
current_target: Default::default(),
target: Default::default(),
type_: DomRefCell::new(atom!("")),
phase: Cell::new(EventPhase::None),
canceled: Cell::new(EventDefault::Allowed),
stop_propagation: Cell::new(false),
stop_immediate: Cell::new(false),
cancelable: Cell::new(false),
bubbles: Cell::new(false),
trusted: Cell::new(false),
dispatching: Cell::new(false),
initialized: Cell::new(false),
timestamp: time::get_time().sec as u64,
}
}
pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<Event> {
reflect_dom_object(Box::new(Event::new_inherited()), global, EventBinding::Wrap)
}
pub fn new(
global: &GlobalScope,
type_: Atom,
bubbles: EventBubbles,
cancelable: EventCancelable,
) -> DomRoot<Event> {
let event = Event::new_uninitialized(global);
event.init_event(type_, bool::from(bubbles), bool::from(cancelable));
event
}
pub fn Constructor(
global: &GlobalScope,
type_: DOMString,
init: &EventBinding::EventInit,
) -> Fallible<DomRoot<Event>> {
let bubbles = EventBubbles::from(init.bubbles);
let cancelable = EventCancelable::from(init.cancelable);
Ok(Event::new(global, Atom::from(type_), bubbles, cancelable))
}
pub fn init_event(&self, type_: Atom, bubbles: bool, cancelable: bool) {
if self.dispatching.get() {
return;
}
self.initialized.set(true);
self.stop_propagation.set(false);
self.stop_immediate.set(false);
self.canceled.set(EventDefault::Allowed);
self.trusted.set(false);
self.target.set(None);
*self.type_.borrow_mut() = type_;
self.bubbles.set(bubbles);
self.cancelable.set(cancelable);
}
// Determine if there are any listeners for a given target and type.
// See https://github.com/whatwg/dom/issues/453
pub fn has_listeners_for(&self, target: &EventTarget, type_: &Atom) -> bool {
// TODO: take'removed' into account? Not implemented in Servo yet.
// https://dom.spec.whatwg.org/#event-listener-removed
let mut event_path = self.construct_event_path(&target);
event_path.push(DomRoot::from_ref(target));
event_path
.iter()
.any(|target| target.has_listeners_for(type_))
}
// https://dom.spec.whatwg.org/#event-path
fn construct_event_path(&self, target: &EventTarget) -> Vec<DomRoot<EventTarget>> {
let mut event_path = vec![];
// The "invoke" algorithm is only used on `target` separately,
// so we don't put it in the path.
if let Some(target_node) = target.downcast::<Node>() {
for ancestor in target_node.ancestors() {
event_path.push(DomRoot::from_ref(ancestor.upcast::<EventTarget>()));
}
let top_most_ancestor_or_target = event_path
.last()
.cloned()
.unwrap_or(DomRoot::from_ref(target));
if let Some(document) = DomRoot::downcast::<Document>(top_most_ancestor_or_target) {
if self.type_()!= atom!("load") && document.browsing_context().is_some() {
event_path.push(DomRoot::from_ref(document.window().upcast()));
}
}
}
event_path
}
// https://dom.spec.whatwg.org/#concept-event-dispatch
pub fn dispatch(
&self,
target: &EventTarget,
target_override: Option<&EventTarget>,
) -> EventStatus {
assert!(!self.dispatching());
assert!(self.initialized());
assert_eq!(self.phase.get(), EventPhase::None);
assert!(self.GetCurrentTarget().is_none());
// Step 1.
self.dispatching.set(true);
// Step 2.
self.target.set(Some(target_override.unwrap_or(target)));
if self.stop_propagation.get() {
// If the event's stop propagation flag is set, we can skip everything because
// it prevents the calls of the invoke algorithm in the spec.
// Step 10-12.
self.clear_dispatching_flags();
// Step 14.
return self.status();
}
// Step 3-4.
let path = self.construct_event_path(&target);
rooted_vec!(let event_path <- path.into_iter());
// Steps 5-9. In a separate function to short-circuit various things easily.
dispatch_to_listeners(self, target, event_path.r());
// Default action.
if let Some(target) = self.GetTarget() {
if let Some(node) = target.downcast::<Node>() {
let vtable = vtable_for(&node);
vtable.handle_event(self);
}
} | self.status()
}
pub fn status(&self) -> EventStatus {
match self.DefaultPrevented() {
true => EventStatus::Canceled,
false => EventStatus::NotCanceled,
}
}
#[inline]
pub fn dispatching(&self) -> bool {
self.dispatching.get()
}
#[inline]
// https://dom.spec.whatwg.org/#concept-event-dispatch Steps 10-12.
fn clear_dispatching_flags(&self) {
assert!(self.dispatching.get());
self.dispatching.set(false);
self.stop_propagation.set(false);
self.stop_immediate.set(false);
self.phase.set(EventPhase::None);
self.current_target.set(None);
}
#[inline]
pub fn initialized(&self) -> bool {
self.initialized.get()
}
#[inline]
pub fn type_(&self) -> Atom {
self.type_.borrow().clone()
}
#[inline]
pub fn mark_as_handled(&self) {
self.canceled.set(EventDefault::Handled);
}
#[inline]
pub fn get_cancel_state(&self) -> EventDefault {
self.canceled.get()
}
pub fn set_trusted(&self, trusted: bool) {
self.trusted.set(trusted);
}
// https://html.spec.whatwg.org/multipage/#fire-a-simple-event
pub fn fire(&self, target: &EventTarget) -> EventStatus {
self.set_trusted(true);
target.dispatch_event(self)
}
}
impl EventMethods for Event {
// https://dom.spec.whatwg.org/#dom-event-eventphase
fn EventPhase(&self) -> u16 {
self.phase.get() as u16
}
// https://dom.spec.whatwg.org/#dom-event-type
fn Type(&self) -> DOMString {
DOMString::from(&*self.type_()) // FIXME(ajeffrey): Directly convert from Atom to DOMString
}
// https://dom.spec.whatwg.org/#dom-event-target
fn GetTarget(&self) -> Option<DomRoot<EventTarget>> {
self.target.get()
}
// https://dom.spec.whatwg.org/#dom-event-currenttarget
fn GetCurrentTarget(&self) -> Option<DomRoot<EventTarget>> {
self.current_target.get()
}
// https://dom.spec.whatwg.org/#dom-event-defaultprevented
fn DefaultPrevented(&self) -> bool {
self.canceled.get() == EventDefault::Prevented
}
// https://dom.spec.whatwg.org/#dom-event-preventdefault
fn PreventDefault(&self) {
if self.cancelable.get() {
self.canceled.set(EventDefault::Prevented)
}
}
// https://dom.spec.whatwg.org/#dom-event-stoppropagation
fn StopPropagation(&self) {
self.stop_propagation.set(true);
}
// https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation
fn StopImmediatePropagation(&self) {
self.stop_immediate.set(true);
self.stop_propagation.set(true);
}
// https://dom.spec.whatwg.org/#dom-event-bubbles
fn Bubbles(&self) -> bool {
self.bubbles.get()
}
// https://dom.spec.whatwg.org/#dom-event-cancelable
fn Cancelable(&self) -> bool {
self.cancelable.get()
}
// https://dom.spec.whatwg.org/#dom-event-timestamp
fn TimeStamp(&self) -> u64 {
self.timestamp
}
// https://dom.spec.whatwg.org/#dom-event-initevent
fn InitEvent(&self, type_: DOMString, bubbles: bool, cancelable: bool) {
self.init_event(Atom::from(type_), bubbles, cancelable)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.trusted.get()
}
}
#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
pub enum EventBubbles {
Bubbles,
DoesNotBubble,
}
impl From<bool> for EventBubbles {
fn from(boolean: bool) -> Self {
match boolean {
true => EventBubbles::Bubbles,
false => EventBubbles::DoesNotBubble,
}
}
}
impl From<EventBubbles> for bool {
fn from(bubbles: EventBubbles) -> Self {
match bubbles {
EventBubbles::Bubbles => true,
EventBubbles::DoesNotBubble => false,
}
}
}
#[derive(Clone, Copy, MallocSizeOf, PartialEq)]
pub enum EventCancelable {
Cancelable,
NotCancelable,
}
impl From<bool> for EventCancelable {
fn from(boolean: bool) -> Self {
match boolean {
true => EventCancelable::Cancelable,
false => EventCancelable::NotCancelable,
}
}
}
impl From<EventCancelable> for bool {
fn from(bubbles: EventCancelable) -> Self {
match bubbles {
EventCancelable::Cancelable => true,
EventCancelable::NotCancelable => false,
}
}
}
#[derive(Clone, Copy, Debug, Eq, JSTraceable, PartialEq)]
#[repr(u16)]
#[derive(MallocSizeOf)]
pub enum EventPhase {
None = EventConstants::NONE,
Capturing = EventConstants::CAPTURING_PHASE,
AtTarget = EventConstants::AT_TARGET,
Bubbling = EventConstants::BUBBLING_PHASE,
}
/// An enum to indicate whether the default action of an event is allowed.
///
/// This should've been a bool. Instead, it's an enum, because, aside from the allowed/canceled
/// states, we also need something to stop the event from being handled again (without cancelling
/// the event entirely). For example, an Up/Down `KeyEvent` inside a `textarea` element will
/// trigger the cursor to go up/down if the text inside the element spans multiple lines. This enum
/// helps us to prevent such events from being [sent to the constellation][msg] where it will be
/// handled once again for page scrolling (which is definitely not what we'd want).
///
/// [msg]: https://doc.servo.org/script_traits/enum.ConstellationMsg.html#variant.KeyEvent
///
#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)]
pub enum EventDefault {
/// The default action of the event is allowed (constructor's default)
Allowed,
/// The default action has been prevented by calling `PreventDefault`
Prevented,
/// The event has been handled somewhere in the DOM, and it should be prevented from being
/// re-handled elsewhere. This doesn't affect the judgement of `DefaultPrevented`
Handled,
}
#[derive(PartialEq)]
pub enum EventStatus {
Canceled,
NotCanceled,
}
// https://dom.spec.whatwg.org/#concept-event-fire
pub struct EventTask {
pub target: Trusted<EventTarget>,
pub name: Atom,
pub bubbles: EventBubbles,
pub cancelable: EventCancelable,
}
impl TaskOnce for EventTask {
fn run_once(self) {
let target = self.target.root();
let bubbles = self.bubbles;
let cancelable = self.cancelable;
target.fire_event_with_params(self.name, bubbles, cancelable);
}
}
// https://html.spec.whatwg.org/multipage/#fire-a-simple-event
pub struct SimpleEventTask {
pub target: Trusted<EventTarget>,
pub name: Atom,
}
impl TaskOnce for SimpleEventTask {
fn run_once(self) {
let target = self.target.root();
target.fire_event(self.name);
}
}
// See dispatch_event.
// https://dom.spec.whatwg.org/#concept-event-dispatch
fn dispatch_to_listeners(event: &Event, target: &EventTarget, event_path: &[&EventTarget]) {
assert!(!event.stop_propagation.get());
assert!(!event.stop_immediate.get());
let window = match DomRoot::downcast::<Window>(target.global()) {
Some(window) => {
if window.need_emit_timeline_marker(TimelineMarkerType::DOMEvent) {
Some(window)
} else {
None
}
},
_ => None,
};
// Step 5.
event.phase.set(EventPhase::Capturing);
// Step 6.
for object in event_path.iter().rev() {
invoke(window.r(), object, event, Some(ListenerPhase::Capturing));
if event.stop_propagation.get() {
return;
}
}
assert!(!event.stop_propagation.get());
assert!(!event.stop_immediate.get());
// Step 7.
event.phase.set(EventPhase::AtTarget);
// Step 8.
invoke(window.r(), target, event, None);
if event.stop_propagation.get() {
return;
}
assert!(!event.stop_propagation.get());
assert!(!event.stop_immediate.get());
if!event.bubbles.get() {
return;
}
// Step 9.1.
event.phase.set(EventPhase::Bubbling);
// Step 9.2.
for object in event_path {
invoke(window.r(), object, event, Some(ListenerPhase::Bubbling));
if event.stop_propagation.get() {
return;
}
}
}
// https://dom.spec.whatwg.org/#concept-event-listener-invoke
fn invoke(
window: Option<&Window>,
object: &EventTarget,
event: &Event,
specific_listener_phase: Option<ListenerPhase>,
) {
// Step 1.
assert!(!event.stop_propagation.get());
// Steps 2-3.
let listeners = object.get_listeners_for(&event.type_(), specific_listener_phase);
// Step 4.
event.current_target.set(Some(object));
// Step 5.
inner_invoke(window, object, event, &listeners);
// TODO: step 6.
}
// https://dom.spec.whatwg.org/#concept-event-listener-inner-invoke
fn inner_invoke(
window: Option<&Window>,
object: &EventTarget,
event: &Event,
listeners: &[CompiledEventListener],
) -> bool {
// Step 1.
let mut found = false;
// Step 2.
for listener in listeners {
// Steps 2.1 and 2.3-2.4 are not done because `listeners` contain only the
// relevant ones for this invoke call during the dispatch algorithm.
// Step 2.2.
found = true;
// TODO: step 2.5.
// Step 2.6.
let marker = TimelineMarker::start("DOMEvent".to_owned());
listener.call_or_handle_event(object, event, ExceptionHandling::Report);
if let Some(window) = window {
window.emit_timeline_marker(marker.end());
}
if event.stop_immediate.get() {
return found;
}
// TODO: step 2.7.
}
// Step 3.
found
}
impl Default for EventBinding::EventInit {
fn default() -> EventBinding::EventInit {
EventBinding::EventInit {
bubbles: false,
cancelable: false,
}
}
} |
// Step 10-12.
self.clear_dispatching_flags();
// Step 14. | random_line_split |
lib.rs | /*
* Copyright 2015-2019 Ben Ashford
*
* 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.
*/
//! A client for ElasticSearch's REST API
//!
//! The `Client` itself is used as the central access point, from which numerous
//! operations are defined implementing each of the specific ElasticSearch APIs.
//!
//! Warning: at the time of writing the majority of such APIs are currently
//! unimplemented.
#[cfg(test)]
#[macro_use]
extern crate doc_comment;
#[cfg(test)]
doctest!("../README.md");
#[macro_use]
pub mod util;
#[macro_use]
pub mod json;
pub mod error;
pub mod operations;
pub mod query;
pub mod units;
use std::time;
use reqwest::{header::CONTENT_TYPE, RequestBuilder, StatusCode, Url};
use serde::{de::DeserializeOwned, ser::Serialize};
use crate::error::EsError;
pub trait EsResponse {
fn status_code(&self) -> StatusCode;
fn read_response<R>(self) -> Result<R, EsError>
where
R: DeserializeOwned;
}
impl EsResponse for reqwest::Response {
fn status_code(&self) -> StatusCode {
self.status()
}
fn read_response<R>(self) -> Result<R, EsError>
where
R: DeserializeOwned,
{
Ok(serde_json::from_reader(self)?)
}
}
// The client
/// Process the result of an HTTP request, returning the status code and the
/// `Json` result (if the result had a body) or an `EsError` if there were any
/// errors | ///
/// This function is exposed to allow extensions to certain operations, it is
/// not expected to be used by consumers of the library
fn do_req(resp: reqwest::Response) -> Result<reqwest::Response, EsError> {
let mut resp = resp;
let status = resp.status();
match status {
StatusCode::OK | StatusCode::CREATED | StatusCode::NOT_FOUND => Ok(resp),
_ => Err(EsError::from(&mut resp)),
}
}
/// The core of the ElasticSearch client, owns a HTTP connection.
///
/// Each instance of `Client` is reusable, but only one thread can use each one
/// at once. This will be enforced by the borrow-checker as most methods are
/// defined on `&mut self`.
///
/// To create a `Client`, the URL needs to be specified.
///
/// Each ElasticSearch API operation is defined as a method on `Client`. Any
/// compulsory parameters must be given as arguments to this method. It returns
/// an operation builder that can be used to add any optional parameters.
///
/// Finally `send` is called to submit the operation:
///
/// # Examples
///
/// ```
/// use rs_es::Client;
///
/// let mut client = Client::init("http://localhost:9200");
/// ```
///
/// See the specific operations and their builder objects for details.
#[derive(Debug, Clone)]
pub struct Client {
base_url: Url,
http_client: reqwest::Client,
}
impl Client {
fn do_es_op(
&self,
url: &str,
action: impl FnOnce(Url) -> RequestBuilder,
) -> Result<reqwest::Response, EsError> {
let url = self.full_url(url);
let username = self.base_url.username();
let mut method = action(url);
if!username.is_empty() {
method = method.basic_auth(username, self.base_url.password());
}
let result = method.header(CONTENT_TYPE, "application/json").send()?;
do_req(result)
}
}
/// Create a HTTP function for the given method (GET/PUT/POST/DELETE)
macro_rules! es_op {
($n:ident,$cn:ident) => {
fn $n(&self, url: &str) -> Result<reqwest::Response, EsError> {
log::info!("Doing {} on {}", stringify!($n), url);
self.do_es_op(url, |url| self.http_client.$cn(url.clone()))
}
}
}
/// Create a HTTP function with a request body for the given method
/// (GET/PUT/POST/DELETE)
///
macro_rules! es_body_op {
($n:ident,$cn:ident) => {
fn $n<E>(&mut self, url: &str, body: &E) -> Result<reqwest::Response, EsError>
where E: Serialize {
log::info!("Doing {} on {}", stringify!($n), url);
let json_string = serde_json::to_string(body)?;
log::debug!("With body: {}", &json_string);
self.do_es_op(url, |url| {
self.http_client.$cn(url.clone()).body(json_string)
})
}
}
}
impl Client {
/// Create a new client
pub fn init(url_s: &str) -> Result<Client, reqwest::UrlError> {
let url = Url::parse(url_s)?;
Ok(Client {
http_client: reqwest::Client::new(),
base_url: url,
})
}
// TODO - this should be replaced with a builder object, especially if more options are going
// to be allowed
pub fn init_with_timeout(
url_s: &str,
timeout: Option<time::Duration>,
) -> Result<Client, reqwest::UrlError> {
let url = Url::parse(url_s)?;
Ok(Client {
http_client: reqwest::Client::builder()
.timeout(timeout)
.build()
.expect("Failed to build client"),
base_url: url,
})
}
/// Take a nearly complete ElasticSearch URL, and stick
/// the URL on the front.
pub fn full_url(&self, suffix: &str) -> Url {
self.base_url.join(suffix).expect("Invalid URL created")
}
es_op!(get_op, get);
es_op!(post_op, post);
es_body_op!(post_body_op, post);
es_op!(put_op, put);
es_body_op!(put_body_op, put);
es_op!(delete_op, delete);
}
#[cfg(test)]
pub mod tests {
use std::env;
use serde::{Deserialize, Serialize};
use super::{error::EsError, Client};
// test setup
pub fn make_client() -> Client {
let hostname = match env::var("ES_HOST") {
Ok(val) => val,
Err(_) => "http://localhost:9200".to_owned(),
};
Client::init(&hostname).unwrap()
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TestDocument {
pub str_field: String,
pub int_field: i64,
pub bool_field: bool,
}
#[allow(clippy::new_without_default)]
impl TestDocument {
pub fn new() -> TestDocument {
TestDocument {
str_field: "I am a test".to_owned(),
int_field: 1,
bool_field: true,
}
}
pub fn with_str_field(mut self, s: &str) -> TestDocument {
self.str_field = s.to_owned();
self
}
pub fn with_int_field(mut self, i: i64) -> TestDocument {
self.int_field = i;
self
}
pub fn with_bool_field(mut self, b: bool) -> TestDocument {
self.bool_field = b;
self
}
}
pub fn setup_test_data(client: &mut Client, index_name: &str) {
// TODO - this should use the Bulk API
let documents = vec![
TestDocument::new()
.with_str_field("Document A123")
.with_int_field(1),
TestDocument::new()
.with_str_field("Document B456")
.with_int_field(2),
TestDocument::new()
.with_str_field("Document 1ABC")
.with_int_field(3),
];
for doc in documents.iter() {
client
.index(index_name, "test_type")
.with_doc(doc)
.send()
.unwrap();
}
client.refresh().with_indexes(&[index_name]).send().unwrap();
}
pub fn clean_db(client: &mut Client, test_idx: &str) {
match client.delete_index(test_idx) {
// Ignore indices which don't exist yet
Err(EsError::EsError(ref msg)) if msg == "Unexpected status: 404 Not Found" => {}
Ok(_) => {}
e => {
e.unwrap_or_else(|_| panic!("Failed to clean db for index {:?}", test_idx));
}
};
}
} | random_line_split |
|
lib.rs | /*
* Copyright 2015-2019 Ben Ashford
*
* 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.
*/
//! A client for ElasticSearch's REST API
//!
//! The `Client` itself is used as the central access point, from which numerous
//! operations are defined implementing each of the specific ElasticSearch APIs.
//!
//! Warning: at the time of writing the majority of such APIs are currently
//! unimplemented.
#[cfg(test)]
#[macro_use]
extern crate doc_comment;
#[cfg(test)]
doctest!("../README.md");
#[macro_use]
pub mod util;
#[macro_use]
pub mod json;
pub mod error;
pub mod operations;
pub mod query;
pub mod units;
use std::time;
use reqwest::{header::CONTENT_TYPE, RequestBuilder, StatusCode, Url};
use serde::{de::DeserializeOwned, ser::Serialize};
use crate::error::EsError;
pub trait EsResponse {
fn status_code(&self) -> StatusCode;
fn read_response<R>(self) -> Result<R, EsError>
where
R: DeserializeOwned;
}
impl EsResponse for reqwest::Response {
fn status_code(&self) -> StatusCode {
self.status()
}
fn read_response<R>(self) -> Result<R, EsError>
where
R: DeserializeOwned,
{
Ok(serde_json::from_reader(self)?)
}
}
// The client
/// Process the result of an HTTP request, returning the status code and the
/// `Json` result (if the result had a body) or an `EsError` if there were any
/// errors
///
/// This function is exposed to allow extensions to certain operations, it is
/// not expected to be used by consumers of the library
fn do_req(resp: reqwest::Response) -> Result<reqwest::Response, EsError> {
let mut resp = resp;
let status = resp.status();
match status {
StatusCode::OK | StatusCode::CREATED | StatusCode::NOT_FOUND => Ok(resp),
_ => Err(EsError::from(&mut resp)),
}
}
/// The core of the ElasticSearch client, owns a HTTP connection.
///
/// Each instance of `Client` is reusable, but only one thread can use each one
/// at once. This will be enforced by the borrow-checker as most methods are
/// defined on `&mut self`.
///
/// To create a `Client`, the URL needs to be specified.
///
/// Each ElasticSearch API operation is defined as a method on `Client`. Any
/// compulsory parameters must be given as arguments to this method. It returns
/// an operation builder that can be used to add any optional parameters.
///
/// Finally `send` is called to submit the operation:
///
/// # Examples
///
/// ```
/// use rs_es::Client;
///
/// let mut client = Client::init("http://localhost:9200");
/// ```
///
/// See the specific operations and their builder objects for details.
#[derive(Debug, Clone)]
pub struct Client {
base_url: Url,
http_client: reqwest::Client,
}
impl Client {
fn do_es_op(
&self,
url: &str,
action: impl FnOnce(Url) -> RequestBuilder,
) -> Result<reqwest::Response, EsError> {
let url = self.full_url(url);
let username = self.base_url.username();
let mut method = action(url);
if!username.is_empty() {
method = method.basic_auth(username, self.base_url.password());
}
let result = method.header(CONTENT_TYPE, "application/json").send()?;
do_req(result)
}
}
/// Create a HTTP function for the given method (GET/PUT/POST/DELETE)
macro_rules! es_op {
($n:ident,$cn:ident) => {
fn $n(&self, url: &str) -> Result<reqwest::Response, EsError> {
log::info!("Doing {} on {}", stringify!($n), url);
self.do_es_op(url, |url| self.http_client.$cn(url.clone()))
}
}
}
/// Create a HTTP function with a request body for the given method
/// (GET/PUT/POST/DELETE)
///
macro_rules! es_body_op {
($n:ident,$cn:ident) => {
fn $n<E>(&mut self, url: &str, body: &E) -> Result<reqwest::Response, EsError>
where E: Serialize {
log::info!("Doing {} on {}", stringify!($n), url);
let json_string = serde_json::to_string(body)?;
log::debug!("With body: {}", &json_string);
self.do_es_op(url, |url| {
self.http_client.$cn(url.clone()).body(json_string)
})
}
}
}
impl Client {
/// Create a new client
pub fn init(url_s: &str) -> Result<Client, reqwest::UrlError> {
let url = Url::parse(url_s)?;
Ok(Client {
http_client: reqwest::Client::new(),
base_url: url,
})
}
// TODO - this should be replaced with a builder object, especially if more options are going
// to be allowed
pub fn init_with_timeout(
url_s: &str,
timeout: Option<time::Duration>,
) -> Result<Client, reqwest::UrlError> {
let url = Url::parse(url_s)?;
Ok(Client {
http_client: reqwest::Client::builder()
.timeout(timeout)
.build()
.expect("Failed to build client"),
base_url: url,
})
}
/// Take a nearly complete ElasticSearch URL, and stick
/// the URL on the front.
pub fn full_url(&self, suffix: &str) -> Url {
self.base_url.join(suffix).expect("Invalid URL created")
}
es_op!(get_op, get);
es_op!(post_op, post);
es_body_op!(post_body_op, post);
es_op!(put_op, put);
es_body_op!(put_body_op, put);
es_op!(delete_op, delete);
}
#[cfg(test)]
pub mod tests {
use std::env;
use serde::{Deserialize, Serialize};
use super::{error::EsError, Client};
// test setup
pub fn make_client() -> Client {
let hostname = match env::var("ES_HOST") {
Ok(val) => val,
Err(_) => "http://localhost:9200".to_owned(),
};
Client::init(&hostname).unwrap()
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TestDocument {
pub str_field: String,
pub int_field: i64,
pub bool_field: bool,
}
#[allow(clippy::new_without_default)]
impl TestDocument {
pub fn new() -> TestDocument {
TestDocument {
str_field: "I am a test".to_owned(),
int_field: 1,
bool_field: true,
}
}
pub fn with_str_field(mut self, s: &str) -> TestDocument {
self.str_field = s.to_owned();
self
}
pub fn with_int_field(mut self, i: i64) -> TestDocument {
self.int_field = i;
self
}
pub fn with_bool_field(mut self, b: bool) -> TestDocument {
self.bool_field = b;
self
}
}
pub fn | (client: &mut Client, index_name: &str) {
// TODO - this should use the Bulk API
let documents = vec![
TestDocument::new()
.with_str_field("Document A123")
.with_int_field(1),
TestDocument::new()
.with_str_field("Document B456")
.with_int_field(2),
TestDocument::new()
.with_str_field("Document 1ABC")
.with_int_field(3),
];
for doc in documents.iter() {
client
.index(index_name, "test_type")
.with_doc(doc)
.send()
.unwrap();
}
client.refresh().with_indexes(&[index_name]).send().unwrap();
}
pub fn clean_db(client: &mut Client, test_idx: &str) {
match client.delete_index(test_idx) {
// Ignore indices which don't exist yet
Err(EsError::EsError(ref msg)) if msg == "Unexpected status: 404 Not Found" => {}
Ok(_) => {}
e => {
e.unwrap_or_else(|_| panic!("Failed to clean db for index {:?}", test_idx));
}
};
}
}
| setup_test_data | identifier_name |
capability_list.rs | // Copyright (c) 2017 David Renshaw and contributors
//
// 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.
//! List of capabilities.
use alloc::boxed::Box;
use core::marker::PhantomData;
use crate::capability::{FromClientHook};
use crate::private::capability::ClientHook;
use crate::private::layout::{ListReader, ListBuilder, PointerReader, PointerBuilder, Pointer};
use crate::traits::{FromPointerReader, FromPointerBuilder, IndexMove, ListIter};
use crate::Result;
#[derive(Copy, Clone)]
pub struct Owned<T> where T: FromClientHook {
marker: PhantomData<T>,
}
impl<'a, T> crate::traits::Owned<'a> for Owned<T> where T: FromClientHook {
type Reader = Reader<'a, T>;
type Builder = Builder<'a, T>;
}
pub struct Reader<'a, T> where T: FromClientHook {
marker: PhantomData<T>,
reader: ListReader<'a>
}
impl <'a, T> Clone for Reader<'a, T> where T: FromClientHook {
fn clone(&self) -> Reader<'a, T> {
Reader { marker : self.marker, reader : self.reader }
}
}
impl <'a, T> Copy for Reader<'a, T> where T: FromClientHook {}
impl <'a, T> Reader<'a, T> where T: FromClientHook {
pub fn len(&self) -> u32 { self.reader.len() }
pub fn iter(self) -> ListIter<Reader<'a, T>, Result<T>> {
ListIter::new(self, self.len())
}
}
impl <'a, T> Reader<'a, T> where T: FromClientHook {
pub fn reborrow<'b>(&'b self) -> Reader<'b, T> {
Reader { reader: self.reader, marker: PhantomData }
}
}
impl <'a, T> FromPointerReader<'a> for Reader<'a, T> where T: FromClientHook {
fn get_from_pointer(reader: &PointerReader<'a>, default: Option<&'a [crate::Word]>) -> Result<Reader<'a, T>> {
Ok(Reader { reader: reader.get_list(Pointer, default)?,
marker: PhantomData })
}
}
impl <'a, T> Reader<'a, T> where T: FromClientHook {
pub fn get(self, index: u32) -> Result<T> {
assert!(index < self.len());
Ok(FromClientHook::new(self.reader.get_pointer_element(index).get_capability()?))
}
}
impl <'a, T> IndexMove<u32, Result<T>> for Reader<'a, T> where T: FromClientHook {
fn index_move(&self, index: u32) -> Result<T> {
self.get(index)
}
}
pub struct Builder<'a, T> where T: FromClientHook {
marker: PhantomData<T>,
builder: ListBuilder<'a>
}
impl <'a, T> Builder<'a, T> where T: FromClientHook {
pub fn len(&self) -> u32 { self.builder.len() }
pub fn into_reader(self) -> Reader<'a, T> {
Reader {
marker: PhantomData,
reader: self.builder.into_reader(),
}
}
pub fn set(&mut self, index: u32, value: Box<dyn ClientHook>) {
assert!(index < self.len());
self.builder.reborrow().get_pointer_element(index).set_capability(value);
}
}
impl <'a, T> Builder<'a, T> where T: FromClientHook {
pub fn reborrow<'b>(&'b mut self) -> Builder<'b, T> {
Builder { builder: self.builder, marker: PhantomData }
}
}
impl <'a, T> FromPointerBuilder<'a> for Builder<'a, T> where T: FromClientHook {
fn init_pointer(builder: PointerBuilder<'a>, size: u32) -> Builder<'a, T> |
fn get_from_pointer(builder: PointerBuilder<'a>, default: Option<&'a [crate::Word]>) -> Result<Builder<'a, T>> {
Ok(Builder {
marker: PhantomData,
builder: builder.get_list(Pointer, default)?
})
}
}
impl <'a, T> Builder<'a, T> where T: FromClientHook {
pub fn get(self, index: u32) -> Result<T> {
assert!(index < self.len());
Ok(FromClientHook::new(self.builder.get_pointer_element(index).get_capability()?))
}
}
impl <'a, T> crate::traits::SetPointerBuilder for Reader<'a, T>
where T: FromClientHook
{
fn set_pointer_builder<'b>(pointer: crate::private::layout::PointerBuilder<'b>,
value: Reader<'a, T>,
canonicalize: bool) -> Result<()> {
pointer.set_list(&value.reader, canonicalize)
}
}
impl <'a, T> ::core::iter::IntoIterator for Reader<'a, T>
where T: FromClientHook
{
type Item = Result<T>;
type IntoIter = ListIter<Reader<'a, T>, Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
| {
Builder {
marker: PhantomData,
builder: builder.init_list(Pointer, size),
}
} | identifier_body |
capability_list.rs | // Copyright (c) 2017 David Renshaw and contributors
//
// 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.
//! List of capabilities.
use alloc::boxed::Box;
use core::marker::PhantomData;
use crate::capability::{FromClientHook};
use crate::private::capability::ClientHook;
use crate::private::layout::{ListReader, ListBuilder, PointerReader, PointerBuilder, Pointer};
use crate::traits::{FromPointerReader, FromPointerBuilder, IndexMove, ListIter};
use crate::Result;
#[derive(Copy, Clone)]
pub struct Owned<T> where T: FromClientHook {
marker: PhantomData<T>,
}
impl<'a, T> crate::traits::Owned<'a> for Owned<T> where T: FromClientHook {
type Reader = Reader<'a, T>;
type Builder = Builder<'a, T>;
}
pub struct Reader<'a, T> where T: FromClientHook {
marker: PhantomData<T>,
reader: ListReader<'a>
}
impl <'a, T> Clone for Reader<'a, T> where T: FromClientHook {
fn clone(&self) -> Reader<'a, T> {
Reader { marker : self.marker, reader : self.reader }
}
}
impl <'a, T> Copy for Reader<'a, T> where T: FromClientHook {}
impl <'a, T> Reader<'a, T> where T: FromClientHook {
pub fn len(&self) -> u32 { self.reader.len() }
pub fn iter(self) -> ListIter<Reader<'a, T>, Result<T>> {
ListIter::new(self, self.len())
}
}
impl <'a, T> Reader<'a, T> where T: FromClientHook {
pub fn reborrow<'b>(&'b self) -> Reader<'b, T> {
Reader { reader: self.reader, marker: PhantomData }
}
}
impl <'a, T> FromPointerReader<'a> for Reader<'a, T> where T: FromClientHook {
fn | (reader: &PointerReader<'a>, default: Option<&'a [crate::Word]>) -> Result<Reader<'a, T>> {
Ok(Reader { reader: reader.get_list(Pointer, default)?,
marker: PhantomData })
}
}
impl <'a, T> Reader<'a, T> where T: FromClientHook {
pub fn get(self, index: u32) -> Result<T> {
assert!(index < self.len());
Ok(FromClientHook::new(self.reader.get_pointer_element(index).get_capability()?))
}
}
impl <'a, T> IndexMove<u32, Result<T>> for Reader<'a, T> where T: FromClientHook {
fn index_move(&self, index: u32) -> Result<T> {
self.get(index)
}
}
pub struct Builder<'a, T> where T: FromClientHook {
marker: PhantomData<T>,
builder: ListBuilder<'a>
}
impl <'a, T> Builder<'a, T> where T: FromClientHook {
pub fn len(&self) -> u32 { self.builder.len() }
pub fn into_reader(self) -> Reader<'a, T> {
Reader {
marker: PhantomData,
reader: self.builder.into_reader(),
}
}
pub fn set(&mut self, index: u32, value: Box<dyn ClientHook>) {
assert!(index < self.len());
self.builder.reborrow().get_pointer_element(index).set_capability(value);
}
}
impl <'a, T> Builder<'a, T> where T: FromClientHook {
pub fn reborrow<'b>(&'b mut self) -> Builder<'b, T> {
Builder { builder: self.builder, marker: PhantomData }
}
}
impl <'a, T> FromPointerBuilder<'a> for Builder<'a, T> where T: FromClientHook {
fn init_pointer(builder: PointerBuilder<'a>, size: u32) -> Builder<'a, T> {
Builder {
marker: PhantomData,
builder: builder.init_list(Pointer, size),
}
}
fn get_from_pointer(builder: PointerBuilder<'a>, default: Option<&'a [crate::Word]>) -> Result<Builder<'a, T>> {
Ok(Builder {
marker: PhantomData,
builder: builder.get_list(Pointer, default)?
})
}
}
impl <'a, T> Builder<'a, T> where T: FromClientHook {
pub fn get(self, index: u32) -> Result<T> {
assert!(index < self.len());
Ok(FromClientHook::new(self.builder.get_pointer_element(index).get_capability()?))
}
}
impl <'a, T> crate::traits::SetPointerBuilder for Reader<'a, T>
where T: FromClientHook
{
fn set_pointer_builder<'b>(pointer: crate::private::layout::PointerBuilder<'b>,
value: Reader<'a, T>,
canonicalize: bool) -> Result<()> {
pointer.set_list(&value.reader, canonicalize)
}
}
impl <'a, T> ::core::iter::IntoIterator for Reader<'a, T>
where T: FromClientHook
{
type Item = Result<T>;
type IntoIter = ListIter<Reader<'a, T>, Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
| get_from_pointer | identifier_name |
capability_list.rs | // Copyright (c) 2017 David Renshaw and contributors
//
// 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.
//! List of capabilities.
use alloc::boxed::Box;
use core::marker::PhantomData;
use crate::capability::{FromClientHook};
use crate::private::capability::ClientHook;
use crate::private::layout::{ListReader, ListBuilder, PointerReader, PointerBuilder, Pointer};
use crate::traits::{FromPointerReader, FromPointerBuilder, IndexMove, ListIter};
use crate::Result;
#[derive(Copy, Clone)]
pub struct Owned<T> where T: FromClientHook {
marker: PhantomData<T>,
}
impl<'a, T> crate::traits::Owned<'a> for Owned<T> where T: FromClientHook {
type Reader = Reader<'a, T>;
type Builder = Builder<'a, T>;
}
pub struct Reader<'a, T> where T: FromClientHook {
marker: PhantomData<T>,
reader: ListReader<'a>
}
impl <'a, T> Clone for Reader<'a, T> where T: FromClientHook {
fn clone(&self) -> Reader<'a, T> {
Reader { marker : self.marker, reader : self.reader }
}
}
impl <'a, T> Copy for Reader<'a, T> where T: FromClientHook {}
impl <'a, T> Reader<'a, T> where T: FromClientHook {
pub fn len(&self) -> u32 { self.reader.len() }
pub fn iter(self) -> ListIter<Reader<'a, T>, Result<T>> {
ListIter::new(self, self.len())
}
}
impl <'a, T> Reader<'a, T> where T: FromClientHook {
pub fn reborrow<'b>(&'b self) -> Reader<'b, T> {
Reader { reader: self.reader, marker: PhantomData }
}
}
impl <'a, T> FromPointerReader<'a> for Reader<'a, T> where T: FromClientHook {
fn get_from_pointer(reader: &PointerReader<'a>, default: Option<&'a [crate::Word]>) -> Result<Reader<'a, T>> {
Ok(Reader { reader: reader.get_list(Pointer, default)?,
marker: PhantomData })
}
}
impl <'a, T> Reader<'a, T> where T: FromClientHook {
pub fn get(self, index: u32) -> Result<T> {
assert!(index < self.len());
Ok(FromClientHook::new(self.reader.get_pointer_element(index).get_capability()?))
}
}
impl <'a, T> IndexMove<u32, Result<T>> for Reader<'a, T> where T: FromClientHook {
fn index_move(&self, index: u32) -> Result<T> {
self.get(index)
}
}
pub struct Builder<'a, T> where T: FromClientHook {
marker: PhantomData<T>,
builder: ListBuilder<'a>
}
impl <'a, T> Builder<'a, T> where T: FromClientHook {
pub fn len(&self) -> u32 { self.builder.len() }
pub fn into_reader(self) -> Reader<'a, T> {
Reader {
marker: PhantomData,
reader: self.builder.into_reader(),
}
}
pub fn set(&mut self, index: u32, value: Box<dyn ClientHook>) {
assert!(index < self.len());
self.builder.reborrow().get_pointer_element(index).set_capability(value);
}
}
impl <'a, T> Builder<'a, T> where T: FromClientHook {
pub fn reborrow<'b>(&'b mut self) -> Builder<'b, T> {
Builder { builder: self.builder, marker: PhantomData }
}
}
impl <'a, T> FromPointerBuilder<'a> for Builder<'a, T> where T: FromClientHook {
fn init_pointer(builder: PointerBuilder<'a>, size: u32) -> Builder<'a, T> {
Builder {
marker: PhantomData,
builder: builder.init_list(Pointer, size),
}
}
fn get_from_pointer(builder: PointerBuilder<'a>, default: Option<&'a [crate::Word]>) -> Result<Builder<'a, T>> {
Ok(Builder {
marker: PhantomData,
builder: builder.get_list(Pointer, default)?
})
}
}
impl <'a, T> Builder<'a, T> where T: FromClientHook {
pub fn get(self, index: u32) -> Result<T> {
assert!(index < self.len());
Ok(FromClientHook::new(self.builder.get_pointer_element(index).get_capability()?))
}
}
impl <'a, T> crate::traits::SetPointerBuilder for Reader<'a, T>
where T: FromClientHook
{
fn set_pointer_builder<'b>(pointer: crate::private::layout::PointerBuilder<'b>,
value: Reader<'a, T>,
canonicalize: bool) -> Result<()> {
pointer.set_list(&value.reader, canonicalize)
}
}
impl <'a, T> ::core::iter::IntoIterator for Reader<'a, T>
where T: FromClientHook
{
type Item = Result<T>;
type IntoIter = ListIter<Reader<'a, T>, Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
} | random_line_split |
|
capsule.rs |
/// existing traditional C ones, be it for gradual rewrites or to extend with new functionality.
/// They can also be used for interaction between independently compiled Rust extensions if needed.
///
/// Capsules can point to data, usually static arrays of constants and function pointers,
/// or to function pointers directly. These two cases have to be handled differently in Rust,
/// and the latter is possible only for architectures were data and function pointers have
/// the same sizes.
///
/// # Examples
/// ## Using a capsule defined in another extension module
/// This retrieves and use one of the simplest capsules in the Python standard library, found in
/// the `unicodedata` module. The C API enclosed in this capsule is the same for all Python
/// versions supported by this crate. This is not the case of all capsules from the standard
/// library. For instance the `struct` referenced by `datetime.datetime_CAPI` gets a new member
/// in version 3.7.
///
/// Note: this example is a lower-level version of the [`py_capsule!`] example. Only the
/// capsule retrieval actually differs.
/// ```no_run
/// use cpython::{Python, PyCapsule};
/// use libc::{c_void, c_char, c_int};
/// use std::ffi::{CStr, CString};
/// use std::mem;
/// use std::ptr::null;
///
/// #[allow(non_camel_case_types)]
/// type Py_UCS4 = u32;
/// const UNICODE_NAME_MAXLEN: usize = 256;
///
/// #[repr(C)]
/// pub struct unicode_name_CAPI {
/// // the `ucd` signature arguments are actually optional (can be `NULL`) FFI PyObject
/// // pointers used to pass alternate (former) versions of Unicode data.
/// // We won't need to use them with an actual value in these examples, so it's enough to
/// // specify them as `*const c_void`, and it spares us a direct reference to the lower
/// // level Python FFI bindings.
/// size: c_int,
/// getname: unsafe extern "C" fn(
/// ucd: *const c_void,
/// code: Py_UCS4,
/// buffer: *const c_char,
/// buflen: c_int,
/// with_alias_and_seq: c_int,
/// ) -> c_int,
/// getcode: unsafe extern "C" fn(
/// ucd: *const c_void,
/// name: *const c_char,
/// namelen: c_int,
/// code: *const Py_UCS4,
/// ) -> c_int,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub enum UnicodeDataError {
/// InvalidCode,
/// UnknownName,
/// }
///
/// impl unicode_name_CAPI {
/// pub fn get_name(&self, code: Py_UCS4) -> Result<CString, UnicodeDataError> {
/// let mut buf: Vec<c_char> = Vec::with_capacity(UNICODE_NAME_MAXLEN);
/// let buf_ptr = buf.as_mut_ptr();
/// if unsafe {
/// ((*self).getname)(null(), code, buf_ptr, UNICODE_NAME_MAXLEN as c_int, 0)
/// }!= 1 {
/// return Err(UnicodeDataError::InvalidCode);
/// }
/// mem::forget(buf);
/// Ok(unsafe { CString::from_raw(buf_ptr) })
/// }
///
/// pub fn get_code(&self, name: &CStr) -> Result<Py_UCS4, UnicodeDataError> {
/// let namelen = name.to_bytes().len() as c_int;
/// let mut code: [Py_UCS4; 1] = [0; 1];
/// if unsafe {
/// ((*self).getcode)(null(), name.as_ptr(), namelen, code.as_mut_ptr())
/// }!= 1 {
/// return Err(UnicodeDataError::UnknownName);
/// }
/// Ok(code[0])
/// }
/// }
///
/// let gil = Python::acquire_gil();
/// let py = gil.python();
///
/// let capi: &unicode_name_CAPI = unsafe {
/// PyCapsule::import_data(
/// py,
/// CStr::from_bytes_with_nul_unchecked(b"unicodedata.ucnhash_CAPI\0"),
/// )
/// }
///.unwrap();
///
/// assert_eq!(capi.get_name(32).unwrap().to_str(), Ok("SPACE"));
/// assert_eq!(capi.get_name(0), Err(UnicodeDataError::InvalidCode));
///
/// assert_eq!(
/// capi.get_code(CStr::from_bytes_with_nul(b"COMMA\0").unwrap()),
/// Ok(44)
/// );
/// assert_eq!(
/// capi.get_code(CStr::from_bytes_with_nul(b"\0").unwrap()),
/// Err(UnicodeDataError::UnknownName)
/// );
/// ```
///
/// ## Creating a capsule from Rust
/// In this example, we enclose some data and a function in a capsule, using an intermediate
/// `struct` as enclosing type, then retrieve them back and use them.
///
/// Warning: you definitely need to declare the data as `static`. If it's
/// only `const`, it's possible it would get cloned elsewhere, with the orginal
/// location being deallocated before it's actually used from another Python
/// extension.
///
///
/// ```
/// use libc::{c_void, c_int};
/// use cpython::{PyCapsule, Python};
/// use std::ffi::{CStr, CString};
///
/// #[repr(C)]
/// struct CapsData {
/// value: c_int,
/// fun: fn(c_int, c_int) -> c_int,
/// }
///
/// fn add(a: c_int, b: c_int) -> c_int {
/// a + b
/// }
///
/// static DATA: CapsData = CapsData{value: 1, fun: add};
///
/// fn main() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let caps = PyCapsule::new_data(py, &DATA, "somemod.capsdata").unwrap();
///
/// let retrieved: &CapsData = unsafe {caps.data_ref("somemod.capsdata")}.unwrap();
/// assert_eq!(retrieved.value, 1);
/// assert_eq!((retrieved.fun)(2 as c_int, 3 as c_int), 5);
/// }
/// ```
///
/// Of course, a more realistic example would be to store the capsule in a Python module,
/// allowing another extension (possibly foreign) to retrieve and use it.
/// Note that in that case, the capsule `name` must be full dotted name of the capsule object,
/// as we're doing here.
/// ```
/// # use libc::c_int;
/// # use cpython::{PyCapsule, py_module_initializer};
/// # #[repr(C)]
/// # struct CapsData {
/// # value: c_int,
/// # fun: fn(c_int, c_int) -> c_int,
/// # }
/// # fn add(a: c_int, b: c_int) -> c_int {
/// # a + b
/// # }
/// # static DATA: CapsData = CapsData{value: 1, fun: add};
/// py_module_initializer!(somemod, |py, m| {
/// m.add(py, "__doc__", "A module holding a capsule")?;
/// m.add(py, "capsdata", PyCapsule::new_data(py, &DATA, "somemod.capsdata").unwrap())?;
/// Ok(())
/// });
/// # fn main() {}
/// ```
/// Another Rust extension could then declare `CapsData` and use `PyCapsule::import_data` to
/// fetch it back.
///
/// [`py_capsule!`]: macro.py_capsule.html
pub struct PyCapsule(PyObject);
pyobject_newtype!(PyCapsule, PyCapsule_CheckExact, PyCapsule_Type);
/// Macro to retrieve a Python capsule pointing to an array of data, with a layer of caching.
///
/// For more details on capsules, see [`PyCapsule`]
///
/// The caller has to define an appropriate `repr(C)` `struct` first, and put it in
/// scope (`use`) if needed along the macro invocation.
///
/// # Usage
///
/// ```ignore
/// py_capsule!(from some.python.module import capsulename as rustmodule for CapsuleStruct)
/// ```
///
/// where `CapsuleStruct` is the above mentioned `struct` defined by the caller.
///
/// The macro defines a Rust module named `rustmodule`, as specified by the caller.
/// This module provides a retrieval function with the following signature:
///
/// ```ignore
/// mod rustmodule {
/// pub unsafe fn retrieve<'a>(py: Python) -> PyResult<&'a CapsuleStruct> {... }
/// }
/// ```
///
/// The `retrieve()` function is unsafe for the same reasons as [`PyCapsule::import_data`],
/// upon which it relies.
///
/// The newly defined module also contains a `RawPyObject` type suitable to represent C-level
/// Python objects. It can be used in `cpython` public API involving raw FFI pointers, such as
/// [`from_owned_ptr`].
///
/// # Examples
/// ## Using a capsule from the standard library
///
/// This retrieves and uses one of the simplest capsules in the Python standard library, found in
/// the `unicodedata` module. The C API enclosed in this capsule is the same for all Python
/// versions supported by this crate.
///
/// In this case, as with all capsules from the Python standard library, the capsule data
/// is an array (`static struct`) with constants and function pointers.
/// ```no_run
/// use cpython::{Python, PyCapsule, py_capsule};
/// use libc::{c_char, c_int};
/// use std::ffi::{c_void, CStr, CString};
/// use std::mem;
/// use std::ptr::null;
///
/// #[allow(non_camel_case_types)]
/// type Py_UCS4 = u32;
/// const UNICODE_NAME_MAXLEN: usize = 256;
///
/// #[repr(C)]
/// pub struct unicode_name_CAPI {
/// // the `ucd` signature arguments are actually optional (can be `NULL`) FFI PyObject
/// // pointers used to pass alternate (former) versions of Unicode data.
/// // We won't need to use them with an actual value in these examples, so it's enough to
/// // specify them as `const c_void`, and it spares us a direct reference to the lower
/// // level Python FFI bindings.
/// size: c_int,
/// getname: unsafe extern "C" fn(
/// ucd: *const c_void,
/// code: Py_UCS4,
/// buffer: *const c_char,
/// buflen: c_int,
/// with_alias_and_seq: c_int,
/// ) -> c_int,
/// getcode: unsafe extern "C" fn(
/// ucd: *const c_void,
/// name: *const c_char,
/// namelen: c_int,
/// code: *const Py_UCS4,
/// ) -> c_int,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub enum UnicodeDataError {
/// InvalidCode,
/// UnknownName,
/// }
///
/// impl unicode_name_CAPI {
/// pub fn get_name(&self, code: Py_UCS4) -> Result<CString, UnicodeDataError> {
/// let mut buf: Vec<c_char> = Vec::with_capacity(UNICODE_NAME_MAXLEN);
/// let buf_ptr = buf.as_mut_ptr();
/// if unsafe {
/// ((*self).getname)(null(), code, buf_ptr, UNICODE_NAME_MAXLEN as c_int, 0)
/// }!= 1 {
/// return Err(UnicodeDataError::InvalidCode);
/// }
/// mem::forget(buf);
/// Ok(unsafe { CString::from_raw(buf_ptr) })
/// }
///
/// pub fn get_code(&self, name: &CStr) -> Result<Py_UCS4, UnicodeDataError> {
/// let namelen = name.to_bytes().len() as c_int;
/// let mut code: [Py_UCS4; 1] = [0; 1];
/// if unsafe {
/// ((*self).getcode)(null(), name.as_ptr(), namelen, code.as_mut_ptr())
/// }!= 1 {
/// return Err(UnicodeDataError::UnknownName);
/// }
/// Ok(code[0])
/// }
/// }
///
/// py_capsule!(from unicodedata import ucnhash_CAPI as capsmod for unicode_name_CAPI);
///
/// fn main() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
///
/// let capi = unsafe { capsmod::retrieve(py).unwrap() };
/// assert_eq!(capi.get_name(32).unwrap().to_str(), Ok("SPACE"));
/// assert_eq!(capi.get_name(0), Err(UnicodeDataError::InvalidCode));
///
/// assert_eq!(capi.get_code(CStr::from_bytes_with_nul(b"COMMA\0").unwrap()), Ok(44));
/// assert_eq!(capi.get_code(CStr::from_bytes_with_nul(b"\0").unwrap()),
/// Err(UnicodeDataError::UnknownName));
/// }
/// ```
///
/// ## With Python objects
///
/// In this example, we lend a Python object and receive a new one of which we take ownership.
///
/// ```
/// use cpython::{PyCapsule, PyObject, PyResult, Python, py_capsule};
/// use libc::c_void;
///
/// // In the struct, we still have to use c_void for C-level Python objects.
/// #[repr(C)]
/// pub struct spawn_CAPI {
/// spawnfrom: unsafe extern "C" fn(obj: *const c_void) -> *mut c_void,
/// }
///
/// py_capsule!(from some.mod import CAPI as capsmod for spawn_CAPI);
///
/// impl spawn_CAPI {
/// pub fn spawn_from(&self, py: Python, obj: PyObject) -> PyResult<PyObject> {
/// let raw = obj.as_ptr() as *const c_void;
/// Ok(unsafe {
/// PyObject::from_owned_ptr(
/// py,
/// ((*self).spawnfrom)(raw) as *mut capsmod::RawPyObject)
/// })
/// }
/// }
///
/// # fn main() {} // just to avoid confusion with use due to insertion of main() in doctests
/// ```
///
/// [`PyCapsule`]: struct.PyCapsule.html
/// [`PyCapsule::import_data`]: struct.PyCapsule.html#method.import_data
#[macro_export]
macro_rules! py_capsule {
(from $($capsmod:ident).+ import $capsname:ident as $rustmod:ident for $ruststruct: ident ) => (
mod $rustmod {
use super::*;
use std::sync::Once;
use $crate::PyClone;
static mut CAPS_DATA: Option<$crate::PyResult<&$ruststruct>> = None;
static INIT: Once = Once::new();
pub type RawPyObject = $crate::_detail::ffi::PyObject;
pub unsafe fn retrieve<'a>(py: $crate::Python) -> $crate::PyResult<&'a $ruststruct> {
INIT.call_once(|| {
let caps_name =
std::ffi::CStr::from_bytes_with_nul_unchecked(
concat!($( stringify!($capsmod), "."),*,
stringify!($capsname),
"\0").as_bytes());
CAPS_DATA = Some($crate::PyCapsule::import_data(py, caps_name));
});
match CAPS_DATA {
Some(Ok(d)) => Ok(d),
Some(Err(ref e)) => Err(e.clone_ref(py)),
_ => panic!("Uninitialized"), // can't happen
}
}
}
)
}
/// Macro to retrieve a function pointer capsule.
///
/// This is not suitable for architectures where the sizes of function and data pointers
/// differ.
/// For general explanations about capsules, see [`PyCapsule`].
///
/// # Usage
///
/// ```ignore
/// py_capsule_fn!(from some.python.module import capsulename as rustmodule
/// signature (args) -> ret_type)
/// ```
///
/// Similarly to [py_capsule!](macro_py_capsule), the macro defines
///
/// - a Rust module according to the name provided by the caller (here, `rustmodule`)
/// - a type alias for the given signature
/// - a retrieval function:
///
/// ```ignore
/// mod $rustmod {
/// pub type CapsuleFn = unsafe extern "C" (args) -> ret_type ;
/// pub unsafe fn retrieve<'a>(py: Python) -> PyResult<CapsuleFn) {... }
/// }
/// ```
/// - a `RawPyObject` type suitable for signatures that involve Python C objects;
/// it can be used in `cpython` public API involving raw FFI pointers, such as
/// [`from_owned_ptr`].
///
/// The first call to `retrieve()` is cached for subsequent calls.
///
/// # Examples
/// ## Full example with primitive types
/// There is in the Python library no capsule enclosing a function pointer directly,
/// although the documentation presents it as a valid use-case. For this example, we'll
/// therefore have to create one, using the [`PyCapsule`] constructor, and to set it in an
/// existing module (not to imply that a real extension should follow that example
/// and set capsules in modules they don't define!)
///
///
/// ```
/// use cpython::{PyCapsule, Python, FromPyObject, py_capsule_fn};
/// use libc::{c_int, c_void};
///
/// extern "C" fn inc(a: c_int) -> c_int {
/// a + 1
/// }
///
/// /// for testing purposes, stores a capsule named `sys.capsfn`` pointing to `inc()`.
/// fn create_capsule() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let pymod = py.import("sys").unwrap();
/// let caps = PyCapsule::new(py, inc as *const c_void, "sys.capsfn").unwrap();
/// pymod.add(py, "capsfn", caps).unwrap();
/// }
///
/// py_capsule_fn!(from sys import capsfn as capsmod signature (a: c_int) -> c_int);
///
/// // One could, e.g., reexport if needed:
/// pub use capsmod::CapsuleFn;
///
/// fn retrieve_use_capsule() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let fun = capsmod::retrieve(py).unwrap();
/// assert_eq!( unsafe { fun(1) }, 2);
///
/// // let's demonstrate the (reexported) function type
/// let g: CapsuleFn = fun;
/// }
///
/// fn main() {
/// create_capsule();
/// retrieve_use_capsule();
/// // second call uses the cached function pointer
/// retrieve_use_capsule();
/// }
/// ```
///
/// ## With Python objects
///
/// In this example, we lend a Python object and receive a new one of which we take ownership.
///
/// ```
/// use cpython::{PyCapsule, PyObject, PyResult, Python, py_capsule_fn};
///
/// py_capsule_fn!(from some.mod import capsfn as capsmod
/// signature (raw: *mut RawPyObject) -> *mut RawPyObject);
///
/// fn retrieve_use_capsule(py: Python, obj: PyObject) -> PyResult<PyObject> {
/// let fun = capsmod::retrieve(py)?;
/// let raw = obj.as_ptr();
/// Ok(unsafe { PyObject::from_owned_ptr(py, fun(raw)) })
/// }
///
/// # fn main() {} // avoid problems with injection of declarations with Rust 1.25
///
/// ```
///
/// [`PyCapsule`]: struct.PyCapsule.html
/// [`from_owned_ptr`]: struct.PyObject.html#method.from_owned_ptr`
#[macro_export]
macro_rules! py_capsule_fn {
(from $($capsmod:ident).+ import $capsname:ident as $rustmod:ident signature $( $sig: tt)* ) => (
mod $rustmod {
use super::*;
use std::sync::Once;
use $crate::PyClone;
pub type CapsuleFn = unsafe extern "C" fn $( $sig )*;
pub type RawPyObject = $crate::_detail::ffi::PyObject;
static mut CAPS_FN: Option<$crate::PyResult<CapsuleFn>> = None;
static INIT: Once = Once::new();
fn import(py: $crate::Python) -> $crate::PyResult<CapsuleFn> {
unsafe {
let caps_name =
std::ffi::CStr::from_bytes_with_nul_unchecked(
concat!($( stringify!($capsmod), "."),*,
stringify!($capsname),
"\0").as_bytes());
Ok(::std::mem::transmute($crate::PyCapsule::import(py, caps_name)?))
}
}
pub fn retrieve(py: $crate::Python) -> $crate::PyResult<CapsuleFn> {
unsafe {
INIT.call_once(|| { CAPS_FN = Some(import(py)) });
match CAPS_FN.as_ref().unwrap() {
&Ok(f) => Ok(f),
&Err(ref e) => Err(e.clone_ref(py)),
}
}
}
}
)
}
impl PyCapsule {
/// Retrieve the contents of a capsule pointing to some data as a reference.
///
/// The retrieved data would typically be an array of static data and/or function pointers.
/// This method doesn't work for standalone function pointers.
///
/// # Safety
/// This method is unsafe, because
/// - nothing guarantees that the `T` type is appropriate for the data referenced by the capsule
/// pointer
/// - the returned lifetime doesn't guarantee either to cover the actual lifetime of the data
/// (although capsule data is usually static)
pub unsafe fn import_data<'a, T>(py: Python, name: &CStr) -> PyResult<&'a T> {
Ok(&*(Self::import(py, name)? as *const T))
}
/// Retrieves the contents of a capsule as a void pointer by its name.
///
/// This is suitable in particular for later conversion as a function pointer
/// with `mem::transmute`, for architectures where data and function pointers have
/// the same size (see details about this in the
/// [documentation](https://doc.rust-lang.org/std/mem/fn.transmute.html#examples)
/// of the Rust standard library).
pub fn import(py: Python, name: &CStr) -> PyResult<*const c_void> {
let caps_ptr = unsafe { PyCapsule_Import(name.as_ptr(), 0) };
if caps_ptr.is_null() |
Ok(caps_ptr)
}
/// Convenience method to create a capsule for some data
///
/// The encapsuled data may be an array of functions, but it can't be itself a
/// function directly.
///
/// May panic when running out of memory.
///
pub fn new_data<T, N>(py: Python, data: &'static T, name: N) -> Result<Self, NulError>
where
N: Into<Vec<u8>>,
{
Self::new(py, data as *const T as *const c_void, name)
}
/// Creates a new capsule from a raw void pointer
///
/// This is suitable in particular to store a function pointer in a capsule. These
/// can be obtained simply by a simple cast:
///
/// ```
/// use libc::c_void;
///
/// extern "C" fn inc(a: i32) -> i32 {
/// a + 1
/// }
///
/// fn main() {
/// let ptr = inc as *const c_void;
/// }
/// ```
///
/// # Errors
/// This method returns `NulError` if `name` contains a 0 byte (see also `CString::new`)
pub fn new<N>(py: Python, pointer: *const c_void, name: N) -> Result<Self, NulError>
where
N: Into<Vec<u8>>,
{
let name = CString::new(name)?;
let caps = unsafe {
Ok(err::cast_from_owned_ptr_or_panic(
py,
PyCapsule_New(pointer as *mut c_void, name.as_ptr(), None),
))
};
// it is required that the capsule name outlives the call as a char*
// TODO implement a proper PyCapsule_Destructor to release it properly
mem::forget(name);
caps
}
/// Returns a reference to the capsule data.
///
/// The name must match exactly the one given at capsule creation time (see `new_data`) and
/// is converted to a C string under the hood. If that | {
return Err(PyErr::fetch(py));
} | conditional_block |
capsule.rs |
/// existing traditional C ones, be it for gradual rewrites or to extend with new functionality.
/// They can also be used for interaction between independently compiled Rust extensions if needed.
///
/// Capsules can point to data, usually static arrays of constants and function pointers,
/// or to function pointers directly. These two cases have to be handled differently in Rust,
/// and the latter is possible only for architectures were data and function pointers have
/// the same sizes.
///
/// # Examples
/// ## Using a capsule defined in another extension module
/// This retrieves and use one of the simplest capsules in the Python standard library, found in
/// the `unicodedata` module. The C API enclosed in this capsule is the same for all Python
/// versions supported by this crate. This is not the case of all capsules from the standard
/// library. For instance the `struct` referenced by `datetime.datetime_CAPI` gets a new member
/// in version 3.7.
///
/// Note: this example is a lower-level version of the [`py_capsule!`] example. Only the
/// capsule retrieval actually differs.
/// ```no_run
/// use cpython::{Python, PyCapsule};
/// use libc::{c_void, c_char, c_int};
/// use std::ffi::{CStr, CString};
/// use std::mem;
/// use std::ptr::null;
///
/// #[allow(non_camel_case_types)]
/// type Py_UCS4 = u32;
/// const UNICODE_NAME_MAXLEN: usize = 256;
///
/// #[repr(C)]
/// pub struct unicode_name_CAPI {
/// // the `ucd` signature arguments are actually optional (can be `NULL`) FFI PyObject
/// // pointers used to pass alternate (former) versions of Unicode data.
/// // We won't need to use them with an actual value in these examples, so it's enough to
/// // specify them as `*const c_void`, and it spares us a direct reference to the lower
/// // level Python FFI bindings.
/// size: c_int,
/// getname: unsafe extern "C" fn(
/// ucd: *const c_void,
/// code: Py_UCS4,
/// buffer: *const c_char,
/// buflen: c_int,
/// with_alias_and_seq: c_int,
/// ) -> c_int,
/// getcode: unsafe extern "C" fn(
/// ucd: *const c_void,
/// name: *const c_char,
/// namelen: c_int,
/// code: *const Py_UCS4,
/// ) -> c_int,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub enum UnicodeDataError {
/// InvalidCode,
/// UnknownName,
/// }
///
/// impl unicode_name_CAPI {
/// pub fn get_name(&self, code: Py_UCS4) -> Result<CString, UnicodeDataError> {
/// let mut buf: Vec<c_char> = Vec::with_capacity(UNICODE_NAME_MAXLEN);
/// let buf_ptr = buf.as_mut_ptr();
/// if unsafe {
/// ((*self).getname)(null(), code, buf_ptr, UNICODE_NAME_MAXLEN as c_int, 0)
/// }!= 1 {
/// return Err(UnicodeDataError::InvalidCode);
/// }
/// mem::forget(buf);
/// Ok(unsafe { CString::from_raw(buf_ptr) })
/// }
///
/// pub fn get_code(&self, name: &CStr) -> Result<Py_UCS4, UnicodeDataError> {
/// let namelen = name.to_bytes().len() as c_int;
/// let mut code: [Py_UCS4; 1] = [0; 1];
/// if unsafe {
/// ((*self).getcode)(null(), name.as_ptr(), namelen, code.as_mut_ptr())
/// }!= 1 {
/// return Err(UnicodeDataError::UnknownName);
/// }
/// Ok(code[0])
/// }
/// }
///
/// let gil = Python::acquire_gil();
/// let py = gil.python();
///
/// let capi: &unicode_name_CAPI = unsafe {
/// PyCapsule::import_data(
/// py,
/// CStr::from_bytes_with_nul_unchecked(b"unicodedata.ucnhash_CAPI\0"),
/// )
/// }
///.unwrap();
///
/// assert_eq!(capi.get_name(32).unwrap().to_str(), Ok("SPACE"));
/// assert_eq!(capi.get_name(0), Err(UnicodeDataError::InvalidCode));
///
/// assert_eq!(
/// capi.get_code(CStr::from_bytes_with_nul(b"COMMA\0").unwrap()),
/// Ok(44)
/// );
/// assert_eq!(
/// capi.get_code(CStr::from_bytes_with_nul(b"\0").unwrap()),
/// Err(UnicodeDataError::UnknownName)
/// );
/// ```
///
/// ## Creating a capsule from Rust
/// In this example, we enclose some data and a function in a capsule, using an intermediate
/// `struct` as enclosing type, then retrieve them back and use them.
///
/// Warning: you definitely need to declare the data as `static`. If it's
/// only `const`, it's possible it would get cloned elsewhere, with the orginal
/// location being deallocated before it's actually used from another Python
/// extension.
///
///
/// ```
/// use libc::{c_void, c_int};
/// use cpython::{PyCapsule, Python};
/// use std::ffi::{CStr, CString};
///
/// #[repr(C)]
/// struct CapsData {
/// value: c_int,
/// fun: fn(c_int, c_int) -> c_int,
/// }
///
/// fn add(a: c_int, b: c_int) -> c_int {
/// a + b
/// }
///
/// static DATA: CapsData = CapsData{value: 1, fun: add};
///
/// fn main() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let caps = PyCapsule::new_data(py, &DATA, "somemod.capsdata").unwrap();
///
/// let retrieved: &CapsData = unsafe {caps.data_ref("somemod.capsdata")}.unwrap();
/// assert_eq!(retrieved.value, 1);
/// assert_eq!((retrieved.fun)(2 as c_int, 3 as c_int), 5);
/// }
/// ```
///
/// Of course, a more realistic example would be to store the capsule in a Python module,
/// allowing another extension (possibly foreign) to retrieve and use it.
/// Note that in that case, the capsule `name` must be full dotted name of the capsule object,
/// as we're doing here.
/// ```
/// # use libc::c_int;
/// # use cpython::{PyCapsule, py_module_initializer};
/// # #[repr(C)]
/// # struct CapsData {
/// # value: c_int,
/// # fun: fn(c_int, c_int) -> c_int,
/// # }
/// # fn add(a: c_int, b: c_int) -> c_int {
/// # a + b
/// # }
/// # static DATA: CapsData = CapsData{value: 1, fun: add};
/// py_module_initializer!(somemod, |py, m| {
/// m.add(py, "__doc__", "A module holding a capsule")?;
/// m.add(py, "capsdata", PyCapsule::new_data(py, &DATA, "somemod.capsdata").unwrap())?;
/// Ok(())
/// });
/// # fn main() {}
/// ```
/// Another Rust extension could then declare `CapsData` and use `PyCapsule::import_data` to
/// fetch it back.
///
/// [`py_capsule!`]: macro.py_capsule.html
pub struct PyCapsule(PyObject);
pyobject_newtype!(PyCapsule, PyCapsule_CheckExact, PyCapsule_Type);
/// Macro to retrieve a Python capsule pointing to an array of data, with a layer of caching.
///
/// For more details on capsules, see [`PyCapsule`]
///
/// The caller has to define an appropriate `repr(C)` `struct` first, and put it in
/// scope (`use`) if needed along the macro invocation.
///
/// # Usage
///
/// ```ignore
/// py_capsule!(from some.python.module import capsulename as rustmodule for CapsuleStruct)
/// ```
///
/// where `CapsuleStruct` is the above mentioned `struct` defined by the caller.
///
/// The macro defines a Rust module named `rustmodule`, as specified by the caller.
/// This module provides a retrieval function with the following signature:
///
/// ```ignore
/// mod rustmodule {
/// pub unsafe fn retrieve<'a>(py: Python) -> PyResult<&'a CapsuleStruct> {... }
/// }
/// ```
///
/// The `retrieve()` function is unsafe for the same reasons as [`PyCapsule::import_data`],
/// upon which it relies.
///
/// The newly defined module also contains a `RawPyObject` type suitable to represent C-level
/// Python objects. It can be used in `cpython` public API involving raw FFI pointers, such as
/// [`from_owned_ptr`].
///
/// # Examples
/// ## Using a capsule from the standard library
///
/// This retrieves and uses one of the simplest capsules in the Python standard library, found in
/// the `unicodedata` module. The C API enclosed in this capsule is the same for all Python
/// versions supported by this crate.
///
/// In this case, as with all capsules from the Python standard library, the capsule data
/// is an array (`static struct`) with constants and function pointers.
/// ```no_run
/// use cpython::{Python, PyCapsule, py_capsule};
/// use libc::{c_char, c_int};
/// use std::ffi::{c_void, CStr, CString};
/// use std::mem;
/// use std::ptr::null;
///
/// #[allow(non_camel_case_types)]
/// type Py_UCS4 = u32;
/// const UNICODE_NAME_MAXLEN: usize = 256;
///
/// #[repr(C)]
/// pub struct unicode_name_CAPI {
/// // the `ucd` signature arguments are actually optional (can be `NULL`) FFI PyObject
/// // pointers used to pass alternate (former) versions of Unicode data.
/// // We won't need to use them with an actual value in these examples, so it's enough to
/// // specify them as `const c_void`, and it spares us a direct reference to the lower
/// // level Python FFI bindings.
/// size: c_int,
/// getname: unsafe extern "C" fn(
/// ucd: *const c_void,
/// code: Py_UCS4,
/// buffer: *const c_char,
/// buflen: c_int,
/// with_alias_and_seq: c_int,
/// ) -> c_int,
/// getcode: unsafe extern "C" fn(
/// ucd: *const c_void,
/// name: *const c_char,
/// namelen: c_int,
/// code: *const Py_UCS4,
/// ) -> c_int,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub enum UnicodeDataError {
/// InvalidCode,
/// UnknownName,
/// }
///
/// impl unicode_name_CAPI {
/// pub fn get_name(&self, code: Py_UCS4) -> Result<CString, UnicodeDataError> {
/// let mut buf: Vec<c_char> = Vec::with_capacity(UNICODE_NAME_MAXLEN);
/// let buf_ptr = buf.as_mut_ptr();
/// if unsafe {
/// ((*self).getname)(null(), code, buf_ptr, UNICODE_NAME_MAXLEN as c_int, 0)
/// }!= 1 {
/// return Err(UnicodeDataError::InvalidCode);
/// }
/// mem::forget(buf);
/// Ok(unsafe { CString::from_raw(buf_ptr) })
/// }
///
/// pub fn get_code(&self, name: &CStr) -> Result<Py_UCS4, UnicodeDataError> {
/// let namelen = name.to_bytes().len() as c_int;
/// let mut code: [Py_UCS4; 1] = [0; 1];
/// if unsafe {
/// ((*self).getcode)(null(), name.as_ptr(), namelen, code.as_mut_ptr())
/// }!= 1 {
/// return Err(UnicodeDataError::UnknownName);
/// }
/// Ok(code[0])
/// }
/// }
///
/// py_capsule!(from unicodedata import ucnhash_CAPI as capsmod for unicode_name_CAPI);
///
/// fn main() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
///
/// let capi = unsafe { capsmod::retrieve(py).unwrap() };
/// assert_eq!(capi.get_name(32).unwrap().to_str(), Ok("SPACE"));
/// assert_eq!(capi.get_name(0), Err(UnicodeDataError::InvalidCode));
///
/// assert_eq!(capi.get_code(CStr::from_bytes_with_nul(b"COMMA\0").unwrap()), Ok(44));
/// assert_eq!(capi.get_code(CStr::from_bytes_with_nul(b"\0").unwrap()),
/// Err(UnicodeDataError::UnknownName));
/// }
/// ```
///
/// ## With Python objects
///
/// In this example, we lend a Python object and receive a new one of which we take ownership.
///
/// ```
/// use cpython::{PyCapsule, PyObject, PyResult, Python, py_capsule};
/// use libc::c_void;
///
/// // In the struct, we still have to use c_void for C-level Python objects.
/// #[repr(C)]
/// pub struct spawn_CAPI {
/// spawnfrom: unsafe extern "C" fn(obj: *const c_void) -> *mut c_void,
/// }
///
/// py_capsule!(from some.mod import CAPI as capsmod for spawn_CAPI);
///
/// impl spawn_CAPI {
/// pub fn spawn_from(&self, py: Python, obj: PyObject) -> PyResult<PyObject> {
/// let raw = obj.as_ptr() as *const c_void;
/// Ok(unsafe {
/// PyObject::from_owned_ptr(
/// py,
/// ((*self).spawnfrom)(raw) as *mut capsmod::RawPyObject)
/// })
/// }
/// }
///
/// # fn main() {} // just to avoid confusion with use due to insertion of main() in doctests
/// ```
///
/// [`PyCapsule`]: struct.PyCapsule.html
/// [`PyCapsule::import_data`]: struct.PyCapsule.html#method.import_data
#[macro_export]
macro_rules! py_capsule {
(from $($capsmod:ident).+ import $capsname:ident as $rustmod:ident for $ruststruct: ident ) => (
mod $rustmod {
use super::*;
use std::sync::Once;
use $crate::PyClone;
static mut CAPS_DATA: Option<$crate::PyResult<&$ruststruct>> = None;
static INIT: Once = Once::new();
pub type RawPyObject = $crate::_detail::ffi::PyObject;
pub unsafe fn retrieve<'a>(py: $crate::Python) -> $crate::PyResult<&'a $ruststruct> {
INIT.call_once(|| {
let caps_name =
std::ffi::CStr::from_bytes_with_nul_unchecked(
concat!($( stringify!($capsmod), "."),*,
stringify!($capsname),
"\0").as_bytes());
CAPS_DATA = Some($crate::PyCapsule::import_data(py, caps_name));
});
match CAPS_DATA {
Some(Ok(d)) => Ok(d),
Some(Err(ref e)) => Err(e.clone_ref(py)),
_ => panic!("Uninitialized"), // can't happen
}
}
}
)
}
/// Macro to retrieve a function pointer capsule.
///
/// This is not suitable for architectures where the sizes of function and data pointers
/// differ.
/// For general explanations about capsules, see [`PyCapsule`].
///
/// # Usage
///
/// ```ignore
/// py_capsule_fn!(from some.python.module import capsulename as rustmodule
/// signature (args) -> ret_type)
/// ```
///
/// Similarly to [py_capsule!](macro_py_capsule), the macro defines
///
/// - a Rust module according to the name provided by the caller (here, `rustmodule`)
/// - a type alias for the given signature
/// - a retrieval function:
///
/// ```ignore
/// mod $rustmod {
/// pub type CapsuleFn = unsafe extern "C" (args) -> ret_type ;
/// pub unsafe fn retrieve<'a>(py: Python) -> PyResult<CapsuleFn) {... }
/// }
/// ```
/// - a `RawPyObject` type suitable for signatures that involve Python C objects;
/// it can be used in `cpython` public API involving raw FFI pointers, such as
/// [`from_owned_ptr`].
///
/// The first call to `retrieve()` is cached for subsequent calls.
///
/// # Examples
/// ## Full example with primitive types
/// There is in the Python library no capsule enclosing a function pointer directly,
/// although the documentation presents it as a valid use-case. For this example, we'll
/// therefore have to create one, using the [`PyCapsule`] constructor, and to set it in an
/// existing module (not to imply that a real extension should follow that example
/// and set capsules in modules they don't define!)
///
///
/// ```
/// use cpython::{PyCapsule, Python, FromPyObject, py_capsule_fn};
/// use libc::{c_int, c_void};
///
/// extern "C" fn inc(a: c_int) -> c_int {
/// a + 1
/// }
///
/// /// for testing purposes, stores a capsule named `sys.capsfn`` pointing to `inc()`.
/// fn create_capsule() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let pymod = py.import("sys").unwrap();
/// let caps = PyCapsule::new(py, inc as *const c_void, "sys.capsfn").unwrap();
/// pymod.add(py, "capsfn", caps).unwrap();
/// }
///
/// py_capsule_fn!(from sys import capsfn as capsmod signature (a: c_int) -> c_int);
///
/// // One could, e.g., reexport if needed:
/// pub use capsmod::CapsuleFn;
///
/// fn retrieve_use_capsule() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let fun = capsmod::retrieve(py).unwrap();
/// assert_eq!( unsafe { fun(1) }, 2);
///
/// // let's demonstrate the (reexported) function type
/// let g: CapsuleFn = fun;
/// }
///
/// fn main() {
/// create_capsule();
/// retrieve_use_capsule();
/// // second call uses the cached function pointer
/// retrieve_use_capsule();
/// }
/// ```
///
/// ## With Python objects
///
/// In this example, we lend a Python object and receive a new one of which we take ownership.
///
/// ```
/// use cpython::{PyCapsule, PyObject, PyResult, Python, py_capsule_fn};
///
/// py_capsule_fn!(from some.mod import capsfn as capsmod
/// signature (raw: *mut RawPyObject) -> *mut RawPyObject);
///
/// fn retrieve_use_capsule(py: Python, obj: PyObject) -> PyResult<PyObject> {
/// let fun = capsmod::retrieve(py)?;
/// let raw = obj.as_ptr();
/// Ok(unsafe { PyObject::from_owned_ptr(py, fun(raw)) })
/// }
///
/// # fn main() {} // avoid problems with injection of declarations with Rust 1.25
///
/// ```
///
/// [`PyCapsule`]: struct.PyCapsule.html
/// [`from_owned_ptr`]: struct.PyObject.html#method.from_owned_ptr`
#[macro_export]
macro_rules! py_capsule_fn {
(from $($capsmod:ident).+ import $capsname:ident as $rustmod:ident signature $( $sig: tt)* ) => (
mod $rustmod {
use super::*;
use std::sync::Once;
use $crate::PyClone;
pub type CapsuleFn = unsafe extern "C" fn $( $sig )*;
pub type RawPyObject = $crate::_detail::ffi::PyObject;
static mut CAPS_FN: Option<$crate::PyResult<CapsuleFn>> = None;
static INIT: Once = Once::new();
fn import(py: $crate::Python) -> $crate::PyResult<CapsuleFn> {
unsafe {
let caps_name =
std::ffi::CStr::from_bytes_with_nul_unchecked(
concat!($( stringify!($capsmod), "."),*,
stringify!($capsname),
"\0").as_bytes());
Ok(::std::mem::transmute($crate::PyCapsule::import(py, caps_name)?))
}
}
pub fn retrieve(py: $crate::Python) -> $crate::PyResult<CapsuleFn> {
unsafe {
INIT.call_once(|| { CAPS_FN = Some(import(py)) });
match CAPS_FN.as_ref().unwrap() {
&Ok(f) => Ok(f),
&Err(ref e) => Err(e.clone_ref(py)),
}
}
}
}
)
}
impl PyCapsule {
/// Retrieve the contents of a capsule pointing to some data as a reference.
///
/// The retrieved data would typically be an array of static data and/or function pointers.
/// This method doesn't work for standalone function pointers.
///
/// # Safety
/// This method is unsafe, because
/// - nothing guarantees that the `T` type is appropriate for the data referenced by the capsule
/// pointer
/// - the returned lifetime doesn't guarantee either to cover the actual lifetime of the data
/// (although capsule data is usually static)
pub unsafe fn import_data<'a, T>(py: Python, name: &CStr) -> PyResult<&'a T> {
Ok(&*(Self::import(py, name)? as *const T))
}
/// Retrieves the contents of a capsule as a void pointer by its name.
///
/// This is suitable in particular for later conversion as a function pointer
/// with `mem::transmute`, for architectures where data and function pointers have
/// the same size (see details about this in the
/// [documentation](https://doc.rust-lang.org/std/mem/fn.transmute.html#examples)
/// of the Rust standard library).
pub fn import(py: Python, name: &CStr) -> PyResult<*const c_void> {
let caps_ptr = unsafe { PyCapsule_Import(name.as_ptr(), 0) };
if caps_ptr.is_null() {
return Err(PyErr::fetch(py));
}
Ok(caps_ptr)
}
/// Convenience method to create a capsule for some data
///
/// The encapsuled data may be an array of functions, but it can't be itself a
/// function directly.
///
/// May panic when running out of memory.
///
pub fn new_data<T, N>(py: Python, data: &'static T, name: N) -> Result<Self, NulError>
where
N: Into<Vec<u8>>,
|
/// Creates a new capsule from a raw void pointer
///
/// This is suitable in particular to store a function pointer in a capsule. These
/// can be obtained simply by a simple cast:
///
/// ```
/// use libc::c_void;
///
/// extern "C" fn inc(a: i32) -> i32 {
/// a + 1
/// }
///
/// fn main() {
/// let ptr = inc as *const c_void;
/// }
/// ```
///
/// # Errors
/// This method returns `NulError` if `name` contains a 0 byte (see also `CString::new`)
pub fn new<N>(py: Python, pointer: *const c_void, name: N) -> Result<Self, NulError>
where
N: Into<Vec<u8>>,
{
let name = CString::new(name)?;
let caps = unsafe {
Ok(err::cast_from_owned_ptr_or_panic(
py,
PyCapsule_New(pointer as *mut c_void, name.as_ptr(), None),
))
};
// it is required that the capsule name outlives the call as a char*
// TODO implement a proper PyCapsule_Destructor to release it properly
mem::forget(name);
caps
}
/// Returns a reference to the capsule data.
///
/// The name must match exactly the one given at capsule creation time (see `new_data`) and
/// is converted to a C string under the hood. If that | {
Self::new(py, data as *const T as *const c_void, name)
} | identifier_body |
capsule.rs |
/// existing traditional C ones, be it for gradual rewrites or to extend with new functionality.
/// They can also be used for interaction between independently compiled Rust extensions if needed.
///
/// Capsules can point to data, usually static arrays of constants and function pointers,
/// or to function pointers directly. These two cases have to be handled differently in Rust,
/// and the latter is possible only for architectures were data and function pointers have
/// the same sizes.
///
/// # Examples
/// ## Using a capsule defined in another extension module
/// This retrieves and use one of the simplest capsules in the Python standard library, found in
/// the `unicodedata` module. The C API enclosed in this capsule is the same for all Python
/// versions supported by this crate. This is not the case of all capsules from the standard
/// library. For instance the `struct` referenced by `datetime.datetime_CAPI` gets a new member
/// in version 3.7.
///
/// Note: this example is a lower-level version of the [`py_capsule!`] example. Only the
/// capsule retrieval actually differs.
/// ```no_run
/// use cpython::{Python, PyCapsule};
/// use libc::{c_void, c_char, c_int};
/// use std::ffi::{CStr, CString};
/// use std::mem;
/// use std::ptr::null;
///
/// #[allow(non_camel_case_types)]
/// type Py_UCS4 = u32;
/// const UNICODE_NAME_MAXLEN: usize = 256;
///
/// #[repr(C)]
/// pub struct unicode_name_CAPI {
/// // the `ucd` signature arguments are actually optional (can be `NULL`) FFI PyObject
/// // pointers used to pass alternate (former) versions of Unicode data.
/// // We won't need to use them with an actual value in these examples, so it's enough to
/// // specify them as `*const c_void`, and it spares us a direct reference to the lower
/// // level Python FFI bindings.
/// size: c_int,
/// getname: unsafe extern "C" fn(
/// ucd: *const c_void,
/// code: Py_UCS4,
/// buffer: *const c_char,
/// buflen: c_int,
/// with_alias_and_seq: c_int,
/// ) -> c_int,
/// getcode: unsafe extern "C" fn(
/// ucd: *const c_void,
/// name: *const c_char,
/// namelen: c_int,
/// code: *const Py_UCS4,
/// ) -> c_int,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub enum UnicodeDataError {
/// InvalidCode,
/// UnknownName,
/// }
///
/// impl unicode_name_CAPI {
/// pub fn get_name(&self, code: Py_UCS4) -> Result<CString, UnicodeDataError> {
/// let mut buf: Vec<c_char> = Vec::with_capacity(UNICODE_NAME_MAXLEN);
/// let buf_ptr = buf.as_mut_ptr();
/// if unsafe {
/// ((*self).getname)(null(), code, buf_ptr, UNICODE_NAME_MAXLEN as c_int, 0)
/// }!= 1 {
/// return Err(UnicodeDataError::InvalidCode);
/// }
/// mem::forget(buf);
/// Ok(unsafe { CString::from_raw(buf_ptr) })
/// }
///
/// pub fn get_code(&self, name: &CStr) -> Result<Py_UCS4, UnicodeDataError> {
/// let namelen = name.to_bytes().len() as c_int;
/// let mut code: [Py_UCS4; 1] = [0; 1];
/// if unsafe {
/// ((*self).getcode)(null(), name.as_ptr(), namelen, code.as_mut_ptr())
/// }!= 1 {
/// return Err(UnicodeDataError::UnknownName);
/// }
/// Ok(code[0])
/// }
/// }
///
/// let gil = Python::acquire_gil();
/// let py = gil.python();
///
/// let capi: &unicode_name_CAPI = unsafe {
/// PyCapsule::import_data(
/// py,
/// CStr::from_bytes_with_nul_unchecked(b"unicodedata.ucnhash_CAPI\0"),
/// )
/// }
///.unwrap();
///
/// assert_eq!(capi.get_name(32).unwrap().to_str(), Ok("SPACE"));
/// assert_eq!(capi.get_name(0), Err(UnicodeDataError::InvalidCode));
///
/// assert_eq!(
/// capi.get_code(CStr::from_bytes_with_nul(b"COMMA\0").unwrap()),
/// Ok(44)
/// );
/// assert_eq!(
/// capi.get_code(CStr::from_bytes_with_nul(b"\0").unwrap()),
/// Err(UnicodeDataError::UnknownName)
/// );
/// ```
///
/// ## Creating a capsule from Rust
/// In this example, we enclose some data and a function in a capsule, using an intermediate
/// `struct` as enclosing type, then retrieve them back and use them.
///
/// Warning: you definitely need to declare the data as `static`. If it's
/// only `const`, it's possible it would get cloned elsewhere, with the orginal
/// location being deallocated before it's actually used from another Python
/// extension.
///
///
/// ```
/// use libc::{c_void, c_int};
/// use cpython::{PyCapsule, Python};
/// use std::ffi::{CStr, CString};
///
/// #[repr(C)]
/// struct CapsData {
/// value: c_int,
/// fun: fn(c_int, c_int) -> c_int,
/// }
///
/// fn add(a: c_int, b: c_int) -> c_int {
/// a + b
/// }
///
/// static DATA: CapsData = CapsData{value: 1, fun: add};
///
/// fn main() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let caps = PyCapsule::new_data(py, &DATA, "somemod.capsdata").unwrap();
///
/// let retrieved: &CapsData = unsafe {caps.data_ref("somemod.capsdata")}.unwrap();
/// assert_eq!(retrieved.value, 1);
/// assert_eq!((retrieved.fun)(2 as c_int, 3 as c_int), 5);
/// }
/// ```
///
/// Of course, a more realistic example would be to store the capsule in a Python module,
/// allowing another extension (possibly foreign) to retrieve and use it.
/// Note that in that case, the capsule `name` must be full dotted name of the capsule object,
/// as we're doing here.
/// ```
/// # use libc::c_int;
/// # use cpython::{PyCapsule, py_module_initializer};
/// # #[repr(C)]
/// # struct CapsData {
/// # value: c_int,
/// # fun: fn(c_int, c_int) -> c_int,
/// # }
/// # fn add(a: c_int, b: c_int) -> c_int {
/// # a + b
/// # }
/// # static DATA: CapsData = CapsData{value: 1, fun: add};
/// py_module_initializer!(somemod, |py, m| {
/// m.add(py, "__doc__", "A module holding a capsule")?;
/// m.add(py, "capsdata", PyCapsule::new_data(py, &DATA, "somemod.capsdata").unwrap())?;
/// Ok(())
/// });
/// # fn main() {}
/// ```
/// Another Rust extension could then declare `CapsData` and use `PyCapsule::import_data` to
/// fetch it back.
///
/// [`py_capsule!`]: macro.py_capsule.html
pub struct PyCapsule(PyObject);
pyobject_newtype!(PyCapsule, PyCapsule_CheckExact, PyCapsule_Type);
/// Macro to retrieve a Python capsule pointing to an array of data, with a layer of caching.
///
/// For more details on capsules, see [`PyCapsule`]
///
/// The caller has to define an appropriate `repr(C)` `struct` first, and put it in
/// scope (`use`) if needed along the macro invocation.
///
/// # Usage
///
/// ```ignore
/// py_capsule!(from some.python.module import capsulename as rustmodule for CapsuleStruct)
/// ```
///
/// where `CapsuleStruct` is the above mentioned `struct` defined by the caller.
///
/// The macro defines a Rust module named `rustmodule`, as specified by the caller.
/// This module provides a retrieval function with the following signature:
///
/// ```ignore
/// mod rustmodule {
/// pub unsafe fn retrieve<'a>(py: Python) -> PyResult<&'a CapsuleStruct> {... }
/// }
/// ```
///
/// The `retrieve()` function is unsafe for the same reasons as [`PyCapsule::import_data`],
/// upon which it relies.
///
/// The newly defined module also contains a `RawPyObject` type suitable to represent C-level
/// Python objects. It can be used in `cpython` public API involving raw FFI pointers, such as
/// [`from_owned_ptr`].
///
/// # Examples
/// ## Using a capsule from the standard library
///
/// This retrieves and uses one of the simplest capsules in the Python standard library, found in
/// the `unicodedata` module. The C API enclosed in this capsule is the same for all Python
/// versions supported by this crate.
///
/// In this case, as with all capsules from the Python standard library, the capsule data
/// is an array (`static struct`) with constants and function pointers.
/// ```no_run
/// use cpython::{Python, PyCapsule, py_capsule};
/// use libc::{c_char, c_int};
/// use std::ffi::{c_void, CStr, CString};
/// use std::mem;
/// use std::ptr::null;
///
/// #[allow(non_camel_case_types)]
/// type Py_UCS4 = u32;
/// const UNICODE_NAME_MAXLEN: usize = 256;
///
/// #[repr(C)]
/// pub struct unicode_name_CAPI {
/// // the `ucd` signature arguments are actually optional (can be `NULL`) FFI PyObject
/// // pointers used to pass alternate (former) versions of Unicode data.
/// // We won't need to use them with an actual value in these examples, so it's enough to
/// // specify them as `const c_void`, and it spares us a direct reference to the lower
/// // level Python FFI bindings.
/// size: c_int,
/// getname: unsafe extern "C" fn(
/// ucd: *const c_void,
/// code: Py_UCS4,
/// buffer: *const c_char,
/// buflen: c_int,
/// with_alias_and_seq: c_int,
/// ) -> c_int,
/// getcode: unsafe extern "C" fn(
/// ucd: *const c_void,
/// name: *const c_char,
/// namelen: c_int,
/// code: *const Py_UCS4,
/// ) -> c_int,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub enum UnicodeDataError {
/// InvalidCode,
/// UnknownName,
/// }
///
/// impl unicode_name_CAPI {
/// pub fn get_name(&self, code: Py_UCS4) -> Result<CString, UnicodeDataError> {
/// let mut buf: Vec<c_char> = Vec::with_capacity(UNICODE_NAME_MAXLEN);
/// let buf_ptr = buf.as_mut_ptr();
/// if unsafe {
/// ((*self).getname)(null(), code, buf_ptr, UNICODE_NAME_MAXLEN as c_int, 0)
/// }!= 1 {
/// return Err(UnicodeDataError::InvalidCode);
/// }
/// mem::forget(buf);
/// Ok(unsafe { CString::from_raw(buf_ptr) })
/// }
///
/// pub fn get_code(&self, name: &CStr) -> Result<Py_UCS4, UnicodeDataError> {
/// let namelen = name.to_bytes().len() as c_int;
/// let mut code: [Py_UCS4; 1] = [0; 1];
/// if unsafe {
/// ((*self).getcode)(null(), name.as_ptr(), namelen, code.as_mut_ptr())
/// }!= 1 {
/// return Err(UnicodeDataError::UnknownName);
/// }
/// Ok(code[0])
/// }
/// }
///
/// py_capsule!(from unicodedata import ucnhash_CAPI as capsmod for unicode_name_CAPI);
///
/// fn main() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
///
/// let capi = unsafe { capsmod::retrieve(py).unwrap() };
/// assert_eq!(capi.get_name(32).unwrap().to_str(), Ok("SPACE"));
/// assert_eq!(capi.get_name(0), Err(UnicodeDataError::InvalidCode));
///
/// assert_eq!(capi.get_code(CStr::from_bytes_with_nul(b"COMMA\0").unwrap()), Ok(44));
/// assert_eq!(capi.get_code(CStr::from_bytes_with_nul(b"\0").unwrap()),
/// Err(UnicodeDataError::UnknownName));
/// }
/// ```
///
/// ## With Python objects
///
/// In this example, we lend a Python object and receive a new one of which we take ownership.
///
/// ```
/// use cpython::{PyCapsule, PyObject, PyResult, Python, py_capsule};
/// use libc::c_void;
///
/// // In the struct, we still have to use c_void for C-level Python objects.
/// #[repr(C)]
/// pub struct spawn_CAPI {
/// spawnfrom: unsafe extern "C" fn(obj: *const c_void) -> *mut c_void,
/// }
///
/// py_capsule!(from some.mod import CAPI as capsmod for spawn_CAPI);
///
/// impl spawn_CAPI {
/// pub fn spawn_from(&self, py: Python, obj: PyObject) -> PyResult<PyObject> {
/// let raw = obj.as_ptr() as *const c_void;
/// Ok(unsafe {
/// PyObject::from_owned_ptr(
/// py,
/// ((*self).spawnfrom)(raw) as *mut capsmod::RawPyObject)
/// })
/// }
/// }
///
/// # fn main() {} // just to avoid confusion with use due to insertion of main() in doctests
/// ```
///
/// [`PyCapsule`]: struct.PyCapsule.html
/// [`PyCapsule::import_data`]: struct.PyCapsule.html#method.import_data
#[macro_export]
macro_rules! py_capsule {
(from $($capsmod:ident).+ import $capsname:ident as $rustmod:ident for $ruststruct: ident ) => (
mod $rustmod {
use super::*;
use std::sync::Once;
use $crate::PyClone;
static mut CAPS_DATA: Option<$crate::PyResult<&$ruststruct>> = None;
static INIT: Once = Once::new();
pub type RawPyObject = $crate::_detail::ffi::PyObject;
pub unsafe fn retrieve<'a>(py: $crate::Python) -> $crate::PyResult<&'a $ruststruct> {
INIT.call_once(|| {
let caps_name =
std::ffi::CStr::from_bytes_with_nul_unchecked(
concat!($( stringify!($capsmod), "."),*,
stringify!($capsname),
"\0").as_bytes());
CAPS_DATA = Some($crate::PyCapsule::import_data(py, caps_name));
});
match CAPS_DATA {
Some(Ok(d)) => Ok(d),
Some(Err(ref e)) => Err(e.clone_ref(py)),
_ => panic!("Uninitialized"), // can't happen
}
}
}
)
}
/// Macro to retrieve a function pointer capsule.
///
/// This is not suitable for architectures where the sizes of function and data pointers
/// differ.
/// For general explanations about capsules, see [`PyCapsule`].
///
/// # Usage
///
/// ```ignore
/// py_capsule_fn!(from some.python.module import capsulename as rustmodule
/// signature (args) -> ret_type)
/// ```
///
/// Similarly to [py_capsule!](macro_py_capsule), the macro defines
///
/// - a Rust module according to the name provided by the caller (here, `rustmodule`)
/// - a type alias for the given signature
/// - a retrieval function:
///
/// ```ignore
/// mod $rustmod {
/// pub type CapsuleFn = unsafe extern "C" (args) -> ret_type ;
/// pub unsafe fn retrieve<'a>(py: Python) -> PyResult<CapsuleFn) {... }
/// }
/// ```
/// - a `RawPyObject` type suitable for signatures that involve Python C objects;
/// it can be used in `cpython` public API involving raw FFI pointers, such as
/// [`from_owned_ptr`].
///
/// The first call to `retrieve()` is cached for subsequent calls.
///
/// # Examples
/// ## Full example with primitive types
/// There is in the Python library no capsule enclosing a function pointer directly,
/// although the documentation presents it as a valid use-case. For this example, we'll
/// therefore have to create one, using the [`PyCapsule`] constructor, and to set it in an
/// existing module (not to imply that a real extension should follow that example
/// and set capsules in modules they don't define!)
///
///
/// ```
/// use cpython::{PyCapsule, Python, FromPyObject, py_capsule_fn};
/// use libc::{c_int, c_void};
///
/// extern "C" fn inc(a: c_int) -> c_int {
/// a + 1
/// }
///
/// /// for testing purposes, stores a capsule named `sys.capsfn`` pointing to `inc()`.
/// fn create_capsule() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let pymod = py.import("sys").unwrap();
/// let caps = PyCapsule::new(py, inc as *const c_void, "sys.capsfn").unwrap();
/// pymod.add(py, "capsfn", caps).unwrap();
/// }
///
/// py_capsule_fn!(from sys import capsfn as capsmod signature (a: c_int) -> c_int);
///
/// // One could, e.g., reexport if needed:
/// pub use capsmod::CapsuleFn;
///
/// fn retrieve_use_capsule() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let fun = capsmod::retrieve(py).unwrap();
/// assert_eq!( unsafe { fun(1) }, 2);
///
/// // let's demonstrate the (reexported) function type
/// let g: CapsuleFn = fun;
/// }
///
/// fn main() {
/// create_capsule();
/// retrieve_use_capsule();
/// // second call uses the cached function pointer
/// retrieve_use_capsule();
/// }
/// ```
///
/// ## With Python objects
///
/// In this example, we lend a Python object and receive a new one of which we take ownership.
///
/// ```
/// use cpython::{PyCapsule, PyObject, PyResult, Python, py_capsule_fn};
///
/// py_capsule_fn!(from some.mod import capsfn as capsmod
/// signature (raw: *mut RawPyObject) -> *mut RawPyObject);
///
/// fn retrieve_use_capsule(py: Python, obj: PyObject) -> PyResult<PyObject> {
/// let fun = capsmod::retrieve(py)?;
/// let raw = obj.as_ptr();
/// Ok(unsafe { PyObject::from_owned_ptr(py, fun(raw)) })
/// }
///
/// # fn main() {} // avoid problems with injection of declarations with Rust 1.25
///
/// ```
///
/// [`PyCapsule`]: struct.PyCapsule.html
/// [`from_owned_ptr`]: struct.PyObject.html#method.from_owned_ptr`
#[macro_export]
macro_rules! py_capsule_fn {
(from $($capsmod:ident).+ import $capsname:ident as $rustmod:ident signature $( $sig: tt)* ) => (
mod $rustmod {
use super::*;
use std::sync::Once;
use $crate::PyClone;
pub type CapsuleFn = unsafe extern "C" fn $( $sig )*;
pub type RawPyObject = $crate::_detail::ffi::PyObject;
static mut CAPS_FN: Option<$crate::PyResult<CapsuleFn>> = None;
static INIT: Once = Once::new();
fn import(py: $crate::Python) -> $crate::PyResult<CapsuleFn> {
unsafe {
let caps_name =
std::ffi::CStr::from_bytes_with_nul_unchecked(
concat!($( stringify!($capsmod), "."),*,
stringify!($capsname),
"\0").as_bytes());
Ok(::std::mem::transmute($crate::PyCapsule::import(py, caps_name)?))
}
}
pub fn retrieve(py: $crate::Python) -> $crate::PyResult<CapsuleFn> {
unsafe {
INIT.call_once(|| { CAPS_FN = Some(import(py)) });
match CAPS_FN.as_ref().unwrap() {
&Ok(f) => Ok(f),
&Err(ref e) => Err(e.clone_ref(py)),
}
}
}
}
)
}
impl PyCapsule {
/// Retrieve the contents of a capsule pointing to some data as a reference.
///
/// The retrieved data would typically be an array of static data and/or function pointers.
/// This method doesn't work for standalone function pointers.
///
/// # Safety
/// This method is unsafe, because
/// - nothing guarantees that the `T` type is appropriate for the data referenced by the capsule
/// pointer
/// - the returned lifetime doesn't guarantee either to cover the actual lifetime of the data
/// (although capsule data is usually static)
pub unsafe fn import_data<'a, T>(py: Python, name: &CStr) -> PyResult<&'a T> {
Ok(&*(Self::import(py, name)? as *const T))
}
/// Retrieves the contents of a capsule as a void pointer by its name.
///
/// This is suitable in particular for later conversion as a function pointer
/// with `mem::transmute`, for architectures where data and function pointers have
/// the same size (see details about this in the
/// [documentation](https://doc.rust-lang.org/std/mem/fn.transmute.html#examples)
/// of the Rust standard library).
pub fn | (py: Python, name: &CStr) -> PyResult<*const c_void> {
let caps_ptr = unsafe { PyCapsule_Import(name.as_ptr(), 0) };
if caps_ptr.is_null() {
return Err(PyErr::fetch(py));
}
Ok(caps_ptr)
}
/// Convenience method to create a capsule for some data
///
/// The encapsuled data may be an array of functions, but it can't be itself a
/// function directly.
///
/// May panic when running out of memory.
///
pub fn new_data<T, N>(py: Python, data: &'static T, name: N) -> Result<Self, NulError>
where
N: Into<Vec<u8>>,
{
Self::new(py, data as *const T as *const c_void, name)
}
/// Creates a new capsule from a raw void pointer
///
/// This is suitable in particular to store a function pointer in a capsule. These
/// can be obtained simply by a simple cast:
///
/// ```
/// use libc::c_void;
///
/// extern "C" fn inc(a: i32) -> i32 {
/// a + 1
/// }
///
/// fn main() {
/// let ptr = inc as *const c_void;
/// }
/// ```
///
/// # Errors
/// This method returns `NulError` if `name` contains a 0 byte (see also `CString::new`)
pub fn new<N>(py: Python, pointer: *const c_void, name: N) -> Result<Self, NulError>
where
N: Into<Vec<u8>>,
{
let name = CString::new(name)?;
let caps = unsafe {
Ok(err::cast_from_owned_ptr_or_panic(
py,
PyCapsule_New(pointer as *mut c_void, name.as_ptr(), None),
))
};
// it is required that the capsule name outlives the call as a char*
// TODO implement a proper PyCapsule_Destructor to release it properly
mem::forget(name);
caps
}
/// Returns a reference to the capsule data.
///
/// The name must match exactly the one given at capsule creation time (see `new_data`) and
/// is converted to a C string under the hood. If that | import | identifier_name |
capsule.rs | besides
/// existing traditional C ones, be it for gradual rewrites or to extend with new functionality.
/// They can also be used for interaction between independently compiled Rust extensions if needed.
///
/// Capsules can point to data, usually static arrays of constants and function pointers,
/// or to function pointers directly. These two cases have to be handled differently in Rust,
/// and the latter is possible only for architectures were data and function pointers have
/// the same sizes.
///
/// # Examples
/// ## Using a capsule defined in another extension module
/// This retrieves and use one of the simplest capsules in the Python standard library, found in
/// the `unicodedata` module. The C API enclosed in this capsule is the same for all Python
/// versions supported by this crate. This is not the case of all capsules from the standard
/// library. For instance the `struct` referenced by `datetime.datetime_CAPI` gets a new member
/// in version 3.7.
///
/// Note: this example is a lower-level version of the [`py_capsule!`] example. Only the
/// capsule retrieval actually differs.
/// ```no_run
/// use cpython::{Python, PyCapsule};
/// use libc::{c_void, c_char, c_int};
/// use std::ffi::{CStr, CString};
/// use std::mem;
/// use std::ptr::null;
///
/// #[allow(non_camel_case_types)]
/// type Py_UCS4 = u32;
/// const UNICODE_NAME_MAXLEN: usize = 256;
///
/// #[repr(C)]
/// pub struct unicode_name_CAPI {
/// // the `ucd` signature arguments are actually optional (can be `NULL`) FFI PyObject
/// // pointers used to pass alternate (former) versions of Unicode data.
/// // We won't need to use them with an actual value in these examples, so it's enough to
/// // specify them as `*const c_void`, and it spares us a direct reference to the lower
/// // level Python FFI bindings.
/// size: c_int,
/// getname: unsafe extern "C" fn(
/// ucd: *const c_void,
/// code: Py_UCS4,
/// buffer: *const c_char,
/// buflen: c_int,
/// with_alias_and_seq: c_int,
/// ) -> c_int,
/// getcode: unsafe extern "C" fn(
/// ucd: *const c_void,
/// name: *const c_char,
/// namelen: c_int,
/// code: *const Py_UCS4,
/// ) -> c_int,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub enum UnicodeDataError {
/// InvalidCode,
/// UnknownName,
/// }
///
/// impl unicode_name_CAPI {
/// pub fn get_name(&self, code: Py_UCS4) -> Result<CString, UnicodeDataError> {
/// let mut buf: Vec<c_char> = Vec::with_capacity(UNICODE_NAME_MAXLEN);
/// let buf_ptr = buf.as_mut_ptr();
/// if unsafe {
/// ((*self).getname)(null(), code, buf_ptr, UNICODE_NAME_MAXLEN as c_int, 0)
/// }!= 1 {
/// return Err(UnicodeDataError::InvalidCode);
/// }
/// mem::forget(buf);
/// Ok(unsafe { CString::from_raw(buf_ptr) })
/// }
///
/// pub fn get_code(&self, name: &CStr) -> Result<Py_UCS4, UnicodeDataError> {
/// let namelen = name.to_bytes().len() as c_int;
/// let mut code: [Py_UCS4; 1] = [0; 1];
/// if unsafe {
/// ((*self).getcode)(null(), name.as_ptr(), namelen, code.as_mut_ptr())
/// }!= 1 {
/// return Err(UnicodeDataError::UnknownName);
/// }
/// Ok(code[0])
/// }
/// }
///
/// let gil = Python::acquire_gil();
/// let py = gil.python();
///
/// let capi: &unicode_name_CAPI = unsafe {
/// PyCapsule::import_data(
/// py,
/// CStr::from_bytes_with_nul_unchecked(b"unicodedata.ucnhash_CAPI\0"),
/// )
/// }
///.unwrap();
///
/// assert_eq!(capi.get_name(32).unwrap().to_str(), Ok("SPACE"));
/// assert_eq!(capi.get_name(0), Err(UnicodeDataError::InvalidCode));
///
/// assert_eq!(
/// capi.get_code(CStr::from_bytes_with_nul(b"COMMA\0").unwrap()),
/// Ok(44)
/// );
/// assert_eq!(
/// capi.get_code(CStr::from_bytes_with_nul(b"\0").unwrap()),
/// Err(UnicodeDataError::UnknownName)
/// );
/// ```
///
/// ## Creating a capsule from Rust
/// In this example, we enclose some data and a function in a capsule, using an intermediate
/// `struct` as enclosing type, then retrieve them back and use them.
///
/// Warning: you definitely need to declare the data as `static`. If it's
/// only `const`, it's possible it would get cloned elsewhere, with the orginal
/// location being deallocated before it's actually used from another Python
/// extension.
///
///
/// ```
/// use libc::{c_void, c_int};
/// use cpython::{PyCapsule, Python};
/// use std::ffi::{CStr, CString};
///
/// #[repr(C)]
/// struct CapsData {
/// value: c_int,
/// fun: fn(c_int, c_int) -> c_int,
/// }
///
/// fn add(a: c_int, b: c_int) -> c_int {
/// a + b
/// }
///
/// static DATA: CapsData = CapsData{value: 1, fun: add};
///
/// fn main() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let caps = PyCapsule::new_data(py, &DATA, "somemod.capsdata").unwrap();
///
/// let retrieved: &CapsData = unsafe {caps.data_ref("somemod.capsdata")}.unwrap();
/// assert_eq!(retrieved.value, 1);
/// assert_eq!((retrieved.fun)(2 as c_int, 3 as c_int), 5);
/// }
/// ```
///
/// Of course, a more realistic example would be to store the capsule in a Python module,
/// allowing another extension (possibly foreign) to retrieve and use it.
/// Note that in that case, the capsule `name` must be full dotted name of the capsule object,
/// as we're doing here.
/// ```
/// # use libc::c_int;
/// # use cpython::{PyCapsule, py_module_initializer};
/// # #[repr(C)]
/// # struct CapsData {
/// # value: c_int,
/// # fun: fn(c_int, c_int) -> c_int,
/// # }
/// # fn add(a: c_int, b: c_int) -> c_int {
/// # a + b
/// # }
/// # static DATA: CapsData = CapsData{value: 1, fun: add};
/// py_module_initializer!(somemod, |py, m| {
/// m.add(py, "__doc__", "A module holding a capsule")?;
/// m.add(py, "capsdata", PyCapsule::new_data(py, &DATA, "somemod.capsdata").unwrap())?;
/// Ok(())
/// });
/// # fn main() {}
/// ```
/// Another Rust extension could then declare `CapsData` and use `PyCapsule::import_data` to
/// fetch it back.
///
/// [`py_capsule!`]: macro.py_capsule.html
pub struct PyCapsule(PyObject);
pyobject_newtype!(PyCapsule, PyCapsule_CheckExact, PyCapsule_Type);
/// Macro to retrieve a Python capsule pointing to an array of data, with a layer of caching.
///
/// For more details on capsules, see [`PyCapsule`]
///
/// The caller has to define an appropriate `repr(C)` `struct` first, and put it in
/// scope (`use`) if needed along the macro invocation.
///
/// # Usage
///
/// ```ignore
/// py_capsule!(from some.python.module import capsulename as rustmodule for CapsuleStruct)
/// ```
///
/// where `CapsuleStruct` is the above mentioned `struct` defined by the caller.
///
/// The macro defines a Rust module named `rustmodule`, as specified by the caller.
/// This module provides a retrieval function with the following signature:
///
/// ```ignore
/// mod rustmodule {
/// pub unsafe fn retrieve<'a>(py: Python) -> PyResult<&'a CapsuleStruct> {... }
/// }
/// ```
///
/// The `retrieve()` function is unsafe for the same reasons as [`PyCapsule::import_data`],
/// upon which it relies.
///
/// The newly defined module also contains a `RawPyObject` type suitable to represent C-level
/// Python objects. It can be used in `cpython` public API involving raw FFI pointers, such as
/// [`from_owned_ptr`].
///
/// # Examples
/// ## Using a capsule from the standard library
///
/// This retrieves and uses one of the simplest capsules in the Python standard library, found in
/// the `unicodedata` module. The C API enclosed in this capsule is the same for all Python
/// versions supported by this crate.
///
/// In this case, as with all capsules from the Python standard library, the capsule data
/// is an array (`static struct`) with constants and function pointers.
/// ```no_run
/// use cpython::{Python, PyCapsule, py_capsule};
/// use libc::{c_char, c_int};
/// use std::ffi::{c_void, CStr, CString};
/// use std::mem;
/// use std::ptr::null;
///
/// #[allow(non_camel_case_types)]
/// type Py_UCS4 = u32;
/// const UNICODE_NAME_MAXLEN: usize = 256;
///
/// #[repr(C)]
/// pub struct unicode_name_CAPI {
/// // the `ucd` signature arguments are actually optional (can be `NULL`) FFI PyObject
/// // pointers used to pass alternate (former) versions of Unicode data.
/// // We won't need to use them with an actual value in these examples, so it's enough to
/// // specify them as `const c_void`, and it spares us a direct reference to the lower
/// // level Python FFI bindings.
/// size: c_int,
/// getname: unsafe extern "C" fn(
/// ucd: *const c_void,
/// code: Py_UCS4,
/// buffer: *const c_char,
/// buflen: c_int,
/// with_alias_and_seq: c_int,
/// ) -> c_int,
/// getcode: unsafe extern "C" fn(
/// ucd: *const c_void,
/// name: *const c_char,
/// namelen: c_int,
/// code: *const Py_UCS4,
/// ) -> c_int,
/// }
///
/// #[derive(Debug, PartialEq)]
/// pub enum UnicodeDataError {
/// InvalidCode,
/// UnknownName,
/// }
///
/// impl unicode_name_CAPI {
/// pub fn get_name(&self, code: Py_UCS4) -> Result<CString, UnicodeDataError> {
/// let mut buf: Vec<c_char> = Vec::with_capacity(UNICODE_NAME_MAXLEN);
/// let buf_ptr = buf.as_mut_ptr();
/// if unsafe {
/// ((*self).getname)(null(), code, buf_ptr, UNICODE_NAME_MAXLEN as c_int, 0)
/// }!= 1 {
/// return Err(UnicodeDataError::InvalidCode);
/// }
/// mem::forget(buf);
/// Ok(unsafe { CString::from_raw(buf_ptr) })
/// }
///
/// pub fn get_code(&self, name: &CStr) -> Result<Py_UCS4, UnicodeDataError> {
/// let namelen = name.to_bytes().len() as c_int;
/// let mut code: [Py_UCS4; 1] = [0; 1];
/// if unsafe {
/// ((*self).getcode)(null(), name.as_ptr(), namelen, code.as_mut_ptr())
/// }!= 1 {
/// return Err(UnicodeDataError::UnknownName);
/// }
/// Ok(code[0])
/// }
/// }
///
/// py_capsule!(from unicodedata import ucnhash_CAPI as capsmod for unicode_name_CAPI);
///
/// fn main() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
///
/// let capi = unsafe { capsmod::retrieve(py).unwrap() };
/// assert_eq!(capi.get_name(32).unwrap().to_str(), Ok("SPACE"));
/// assert_eq!(capi.get_name(0), Err(UnicodeDataError::InvalidCode));
///
/// assert_eq!(capi.get_code(CStr::from_bytes_with_nul(b"COMMA\0").unwrap()), Ok(44));
/// assert_eq!(capi.get_code(CStr::from_bytes_with_nul(b"\0").unwrap()),
/// Err(UnicodeDataError::UnknownName));
/// }
/// ```
///
/// ## With Python objects
///
/// In this example, we lend a Python object and receive a new one of which we take ownership.
///
/// ```
/// use cpython::{PyCapsule, PyObject, PyResult, Python, py_capsule};
/// use libc::c_void;
///
/// // In the struct, we still have to use c_void for C-level Python objects.
/// #[repr(C)]
/// pub struct spawn_CAPI {
/// spawnfrom: unsafe extern "C" fn(obj: *const c_void) -> *mut c_void,
/// }
///
/// py_capsule!(from some.mod import CAPI as capsmod for spawn_CAPI);
///
/// impl spawn_CAPI {
/// pub fn spawn_from(&self, py: Python, obj: PyObject) -> PyResult<PyObject> {
/// let raw = obj.as_ptr() as *const c_void;
/// Ok(unsafe {
/// PyObject::from_owned_ptr(
/// py,
/// ((*self).spawnfrom)(raw) as *mut capsmod::RawPyObject)
/// })
/// }
/// }
///
/// # fn main() {} // just to avoid confusion with use due to insertion of main() in doctests
/// ```
///
/// [`PyCapsule`]: struct.PyCapsule.html
/// [`PyCapsule::import_data`]: struct.PyCapsule.html#method.import_data
#[macro_export]
macro_rules! py_capsule {
(from $($capsmod:ident).+ import $capsname:ident as $rustmod:ident for $ruststruct: ident ) => (
mod $rustmod {
use super::*;
use std::sync::Once;
use $crate::PyClone;
static mut CAPS_DATA: Option<$crate::PyResult<&$ruststruct>> = None;
static INIT: Once = Once::new();
pub type RawPyObject = $crate::_detail::ffi::PyObject;
pub unsafe fn retrieve<'a>(py: $crate::Python) -> $crate::PyResult<&'a $ruststruct> {
INIT.call_once(|| {
let caps_name =
std::ffi::CStr::from_bytes_with_nul_unchecked(
concat!($( stringify!($capsmod), "."),*,
stringify!($capsname),
"\0").as_bytes());
CAPS_DATA = Some($crate::PyCapsule::import_data(py, caps_name));
});
match CAPS_DATA {
Some(Ok(d)) => Ok(d),
Some(Err(ref e)) => Err(e.clone_ref(py)),
_ => panic!("Uninitialized"), // can't happen
}
}
}
)
}
/// Macro to retrieve a function pointer capsule.
///
/// This is not suitable for architectures where the sizes of function and data pointers
/// differ.
/// For general explanations about capsules, see [`PyCapsule`].
///
/// # Usage
///
/// ```ignore
/// py_capsule_fn!(from some.python.module import capsulename as rustmodule
/// signature (args) -> ret_type)
/// ```
///
/// Similarly to [py_capsule!](macro_py_capsule), the macro defines
///
/// - a Rust module according to the name provided by the caller (here, `rustmodule`)
/// - a type alias for the given signature
/// - a retrieval function:
///
/// ```ignore
/// mod $rustmod {
/// pub type CapsuleFn = unsafe extern "C" (args) -> ret_type ;
/// pub unsafe fn retrieve<'a>(py: Python) -> PyResult<CapsuleFn) {... }
/// }
/// ```
/// - a `RawPyObject` type suitable for signatures that involve Python C objects;
/// it can be used in `cpython` public API involving raw FFI pointers, such as
/// [`from_owned_ptr`].
///
/// The first call to `retrieve()` is cached for subsequent calls.
///
/// # Examples
/// ## Full example with primitive types
/// There is in the Python library no capsule enclosing a function pointer directly,
/// although the documentation presents it as a valid use-case. For this example, we'll
/// therefore have to create one, using the [`PyCapsule`] constructor, and to set it in an
/// existing module (not to imply that a real extension should follow that example
/// and set capsules in modules they don't define!)
///
///
/// ```
/// use cpython::{PyCapsule, Python, FromPyObject, py_capsule_fn};
/// use libc::{c_int, c_void};
///
/// extern "C" fn inc(a: c_int) -> c_int {
/// a + 1
/// }
///
/// /// for testing purposes, stores a capsule named `sys.capsfn`` pointing to `inc()`.
/// fn create_capsule() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let pymod = py.import("sys").unwrap();
/// let caps = PyCapsule::new(py, inc as *const c_void, "sys.capsfn").unwrap();
/// pymod.add(py, "capsfn", caps).unwrap();
/// }
///
/// py_capsule_fn!(from sys import capsfn as capsmod signature (a: c_int) -> c_int);
///
/// // One could, e.g., reexport if needed:
/// pub use capsmod::CapsuleFn;
///
/// fn retrieve_use_capsule() {
/// let gil = Python::acquire_gil();
/// let py = gil.python();
/// let fun = capsmod::retrieve(py).unwrap();
/// assert_eq!( unsafe { fun(1) }, 2);
///
/// // let's demonstrate the (reexported) function type
/// let g: CapsuleFn = fun;
/// }
///
/// fn main() {
/// create_capsule();
/// retrieve_use_capsule();
/// // second call uses the cached function pointer
/// retrieve_use_capsule();
/// }
/// ```
///
/// ## With Python objects
///
/// In this example, we lend a Python object and receive a new one of which we take ownership.
///
/// ```
/// use cpython::{PyCapsule, PyObject, PyResult, Python, py_capsule_fn};
///
/// py_capsule_fn!(from some.mod import capsfn as capsmod
/// signature (raw: *mut RawPyObject) -> *mut RawPyObject);
///
/// fn retrieve_use_capsule(py: Python, obj: PyObject) -> PyResult<PyObject> {
/// let fun = capsmod::retrieve(py)?;
/// let raw = obj.as_ptr();
/// Ok(unsafe { PyObject::from_owned_ptr(py, fun(raw)) })
/// }
///
/// # fn main() {} // avoid problems with injection of declarations with Rust 1.25
///
/// ```
///
/// [`PyCapsule`]: struct.PyCapsule.html
/// [`from_owned_ptr`]: struct.PyObject.html#method.from_owned_ptr`
#[macro_export]
macro_rules! py_capsule_fn {
(from $($capsmod:ident).+ import $capsname:ident as $rustmod:ident signature $( $sig: tt)* ) => (
mod $rustmod {
use super::*;
use std::sync::Once;
use $crate::PyClone;
pub type CapsuleFn = unsafe extern "C" fn $( $sig )*;
pub type RawPyObject = $crate::_detail::ffi::PyObject;
static mut CAPS_FN: Option<$crate::PyResult<CapsuleFn>> = None;
static INIT: Once = Once::new();
fn import(py: $crate::Python) -> $crate::PyResult<CapsuleFn> {
unsafe {
let caps_name =
std::ffi::CStr::from_bytes_with_nul_unchecked(
concat!($( stringify!($capsmod), "."),*,
stringify!($capsname),
"\0").as_bytes());
Ok(::std::mem::transmute($crate::PyCapsule::import(py, caps_name)?))
}
}
pub fn retrieve(py: $crate::Python) -> $crate::PyResult<CapsuleFn> {
unsafe {
INIT.call_once(|| { CAPS_FN = Some(import(py)) });
match CAPS_FN.as_ref().unwrap() {
&Ok(f) => Ok(f),
&Err(ref e) => Err(e.clone_ref(py)),
}
}
}
}
)
}
impl PyCapsule {
/// Retrieve the contents of a capsule pointing to some data as a reference.
///
/// The retrieved data would typically be an array of static data and/or function pointers.
/// This method doesn't work for standalone function pointers.
///
/// # Safety
/// This method is unsafe, because
/// - nothing guarantees that the `T` type is appropriate for the data referenced by the capsule
/// pointer
/// - the returned lifetime doesn't guarantee either to cover the actual lifetime of the data
/// (although capsule data is usually static)
pub unsafe fn import_data<'a, T>(py: Python, name: &CStr) -> PyResult<&'a T> {
Ok(&*(Self::import(py, name)? as *const T))
}
/// Retrieves the contents of a capsule as a void pointer by its name.
///
/// This is suitable in particular for later conversion as a function pointer
/// with `mem::transmute`, for architectures where data and function pointers have
/// the same size (see details about this in the
/// [documentation](https://doc.rust-lang.org/std/mem/fn.transmute.html#examples)
/// of the Rust standard library).
pub fn import(py: Python, name: &CStr) -> PyResult<*const c_void> {
let caps_ptr = unsafe { PyCapsule_Import(name.as_ptr(), 0) };
if caps_ptr.is_null() {
return Err(PyErr::fetch(py));
} |
/// Convenience method to create a capsule for some data
///
/// The encapsuled data may be an array of functions, but it can't be itself a
/// function directly.
///
/// May panic when running out of memory.
///
pub fn new_data<T, N>(py: Python, data: &'static T, name: N) -> Result<Self, NulError>
where
N: Into<Vec<u8>>,
{
Self::new(py, data as *const T as *const c_void, name)
}
/// Creates a new capsule from a raw void pointer
///
/// This is suitable in particular to store a function pointer in a capsule. These
/// can be obtained simply by a simple cast:
///
/// ```
/// use libc::c_void;
///
/// extern "C" fn inc(a: i32) -> i32 {
/// a + 1
/// }
///
/// fn main() {
/// let ptr = inc as *const c_void;
/// }
/// ```
///
/// # Errors
/// This method returns `NulError` if `name` contains a 0 byte (see also `CString::new`)
pub fn new<N>(py: Python, pointer: *const c_void, name: N) -> Result<Self, NulError>
where
N: Into<Vec<u8>>,
{
let name = CString::new(name)?;
let caps = unsafe {
Ok(err::cast_from_owned_ptr_or_panic(
py,
PyCapsule_New(pointer as *mut c_void, name.as_ptr(), None),
))
};
// it is required that the capsule name outlives the call as a char*
// TODO implement a proper PyCapsule_Destructor to release it properly
mem::forget(name);
caps
}
/// Returns a reference to the capsule data.
///
/// The name must match exactly the one given at capsule creation time (see `new_data`) and
/// is converted to a C string under the hood. If that's too | Ok(caps_ptr)
} | random_line_split |
nul-characters.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 fn | ()
{
let all_nuls1 = "\0\x00\u0000\U00000000";
let all_nuls2 = "\U00000000\u0000\x00\0";
let all_nuls3 = "\u0000\U00000000\x00\0";
let all_nuls4 = "\x00\u0000\0\U00000000";
// sizes for two should suffice
assert_eq!(all_nuls1.len(), 4);
assert_eq!(all_nuls2.len(), 4);
// string equality should pass between the strings
assert_eq!(all_nuls1, all_nuls2);
assert_eq!(all_nuls2, all_nuls3);
assert_eq!(all_nuls3, all_nuls4);
// all extracted characters in all_nuls are equivalent to each other
for c1 in all_nuls1.iter()
{
for c2 in all_nuls1.iter()
{
assert_eq!(c1,c2);
}
}
// testing equality between explicit character literals
assert_eq!('\0', '\x00');
assert_eq!('\u0000', '\x00');
assert_eq!('\u0000', '\U00000000');
// NUL characters should make a difference
assert!("Hello World"!= "Hello \0World");
assert!("Hello World"!= "Hello World\0");
}
| main | identifier_name |
nul-characters.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 fn main()
| assert_eq!(c1,c2);
}
}
// testing equality between explicit character literals
assert_eq!('\0', '\x00');
assert_eq!('\u0000', '\x00');
assert_eq!('\u0000', '\U00000000');
// NUL characters should make a difference
assert!("Hello World"!= "Hello \0World");
assert!("Hello World"!= "Hello World\0");
}
| {
let all_nuls1 = "\0\x00\u0000\U00000000";
let all_nuls2 = "\U00000000\u0000\x00\0";
let all_nuls3 = "\u0000\U00000000\x00\0";
let all_nuls4 = "\x00\u0000\0\U00000000";
// sizes for two should suffice
assert_eq!(all_nuls1.len(), 4);
assert_eq!(all_nuls2.len(), 4);
// string equality should pass between the strings
assert_eq!(all_nuls1, all_nuls2);
assert_eq!(all_nuls2, all_nuls3);
assert_eq!(all_nuls3, all_nuls4);
// all extracted characters in all_nuls are equivalent to each other
for c1 in all_nuls1.iter()
{
for c2 in all_nuls1.iter()
{ | identifier_body |
nul-characters.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 fn main()
{
let all_nuls1 = "\0\x00\u0000\U00000000";
let all_nuls2 = "\U00000000\u0000\x00\0";
let all_nuls3 = "\u0000\U00000000\x00\0";
let all_nuls4 = "\x00\u0000\0\U00000000";
// sizes for two should suffice
assert_eq!(all_nuls1.len(), 4);
assert_eq!(all_nuls2.len(), 4);
// string equality should pass between the strings
assert_eq!(all_nuls1, all_nuls2);
assert_eq!(all_nuls2, all_nuls3);
assert_eq!(all_nuls3, all_nuls4);
// all extracted characters in all_nuls are equivalent to each other
for c1 in all_nuls1.iter() | assert_eq!(c1,c2);
}
}
// testing equality between explicit character literals
assert_eq!('\0', '\x00');
assert_eq!('\u0000', '\x00');
assert_eq!('\u0000', '\U00000000');
// NUL characters should make a difference
assert!("Hello World"!= "Hello \0World");
assert!("Hello World"!= "Hello World\0");
} | {
for c2 in all_nuls1.iter()
{ | random_line_split |
hrtb-perfect-forwarding.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 a case where you have an impl of `Foo<X>` for all `X` that
// is being applied to `for<'a> Foo<&'a mut X>`. Issue #19730.
trait Foo<X> {
fn foo(&mut self, x: X) { }
}
trait Bar<X> {
fn bar(&mut self, x: X) { }
}
impl<'a,X,F> Foo<X> for &'a mut F
where F : Foo<X> + Bar<X>
{
}
impl<'a,X,F> Bar<X> for &'a mut F
where F : Bar<X>
{
}
fn no_hrtb<'b,T>(mut t: T)
where T : Bar<&'b isize>
{
// OK -- `T : Bar<&'b isize>`, and thus the impl above ensures that
// `&mut T : Bar<&'b isize>`.
no_hrtb(&mut t);
}
fn bar_hrtb<T>(mut t: T)
where T : for<'b> Bar<&'b isize>
{
// OK -- `T : for<'b> Bar<&'b isize>`, and thus the impl above
// ensures that `&mut T : for<'b> Bar<&'b isize>`. This is an
// example of a "perfect forwarding" impl.
bar_hrtb(&mut t);
}
fn foo_hrtb_bar_not<'b,T>(mut t: T)
where T : for<'a> Foo<&'a isize> + Bar<&'b isize>
{
// Not OK -- The forwarding impl for `Foo` requires that `Bar` also
// be implemented. Thus to satisfy `&mut T : for<'a> Foo<&'a
// isize>`, we require `T : for<'a> Bar<&'a isize>`, but the where
// clause only specifies `T : Bar<&'b isize>`.
foo_hrtb_bar_not(&mut t); //~ ERROR `for<'a> Bar<&'a isize>` is not implemented for the type `T`
}
fn foo_hrtb_bar_hrtb<T>(mut t: T)
where T : for<'a> Foo<&'a isize> + for<'b> Bar<&'b isize>
|
fn main() { }
| {
// OK -- now we have `T : for<'b> Bar&'b isize>`.
foo_hrtb_bar_hrtb(&mut t);
} | identifier_body |
hrtb-perfect-forwarding.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 a case where you have an impl of `Foo<X>` for all `X` that
// is being applied to `for<'a> Foo<&'a mut X>`. Issue #19730.
trait Foo<X> {
fn foo(&mut self, x: X) { }
}
trait Bar<X> {
fn bar(&mut self, x: X) { }
}
impl<'a,X,F> Foo<X> for &'a mut F
where F : Foo<X> + Bar<X>
{
}
impl<'a,X,F> Bar<X> for &'a mut F
where F : Bar<X>
{
}
fn no_hrtb<'b,T>(mut t: T)
where T : Bar<&'b isize>
{
// OK -- `T : Bar<&'b isize>`, and thus the impl above ensures that
// `&mut T : Bar<&'b isize>`.
no_hrtb(&mut t);
}
fn bar_hrtb<T>(mut t: T)
where T : for<'b> Bar<&'b isize>
{
// OK -- `T : for<'b> Bar<&'b isize>`, and thus the impl above
// ensures that `&mut T : for<'b> Bar<&'b isize>`. This is an |
fn foo_hrtb_bar_not<'b,T>(mut t: T)
where T : for<'a> Foo<&'a isize> + Bar<&'b isize>
{
// Not OK -- The forwarding impl for `Foo` requires that `Bar` also
// be implemented. Thus to satisfy `&mut T : for<'a> Foo<&'a
// isize>`, we require `T : for<'a> Bar<&'a isize>`, but the where
// clause only specifies `T : Bar<&'b isize>`.
foo_hrtb_bar_not(&mut t); //~ ERROR `for<'a> Bar<&'a isize>` is not implemented for the type `T`
}
fn foo_hrtb_bar_hrtb<T>(mut t: T)
where T : for<'a> Foo<&'a isize> + for<'b> Bar<&'b isize>
{
// OK -- now we have `T : for<'b> Bar&'b isize>`.
foo_hrtb_bar_hrtb(&mut t);
}
fn main() { } | // example of a "perfect forwarding" impl.
bar_hrtb(&mut t);
} | random_line_split |
hrtb-perfect-forwarding.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 a case where you have an impl of `Foo<X>` for all `X` that
// is being applied to `for<'a> Foo<&'a mut X>`. Issue #19730.
trait Foo<X> {
fn foo(&mut self, x: X) { }
}
trait Bar<X> {
fn | (&mut self, x: X) { }
}
impl<'a,X,F> Foo<X> for &'a mut F
where F : Foo<X> + Bar<X>
{
}
impl<'a,X,F> Bar<X> for &'a mut F
where F : Bar<X>
{
}
fn no_hrtb<'b,T>(mut t: T)
where T : Bar<&'b isize>
{
// OK -- `T : Bar<&'b isize>`, and thus the impl above ensures that
// `&mut T : Bar<&'b isize>`.
no_hrtb(&mut t);
}
fn bar_hrtb<T>(mut t: T)
where T : for<'b> Bar<&'b isize>
{
// OK -- `T : for<'b> Bar<&'b isize>`, and thus the impl above
// ensures that `&mut T : for<'b> Bar<&'b isize>`. This is an
// example of a "perfect forwarding" impl.
bar_hrtb(&mut t);
}
fn foo_hrtb_bar_not<'b,T>(mut t: T)
where T : for<'a> Foo<&'a isize> + Bar<&'b isize>
{
// Not OK -- The forwarding impl for `Foo` requires that `Bar` also
// be implemented. Thus to satisfy `&mut T : for<'a> Foo<&'a
// isize>`, we require `T : for<'a> Bar<&'a isize>`, but the where
// clause only specifies `T : Bar<&'b isize>`.
foo_hrtb_bar_not(&mut t); //~ ERROR `for<'a> Bar<&'a isize>` is not implemented for the type `T`
}
fn foo_hrtb_bar_hrtb<T>(mut t: T)
where T : for<'a> Foo<&'a isize> + for<'b> Bar<&'b isize>
{
// OK -- now we have `T : for<'b> Bar&'b isize>`.
foo_hrtb_bar_hrtb(&mut t);
}
fn main() { }
| bar | identifier_name |
package.rs | use std::get_slice::GetSlice;
use std::url::Url;
use std::fs::File;
use std::io::Read;
use orbital::BmpFile;
/// A package (_REDOX content serialized)
pub struct | {
/// The URL
pub url: Url,
/// The ID of the package
pub id: String,
/// The name of the package
pub name: String,
/// The binary for the package
pub binary: String,
/// The icon for the package
pub icon: BmpFile,
/// The accepted extensions
pub accepts: Vec<String>,
/// The author(s) of the package
pub authors: Vec<String>,
/// The description of the package
pub descriptions: Vec<String>,
}
impl Package {
/// Create package from URL
pub fn from_url(url: &Url) -> Box<Self> {
let mut package = box Package {
url: url.clone(),
id: String::new(),
name: String::new(),
binary: url.to_string() + "main.bin",
icon: BmpFile::default(),
accepts: Vec::new(),
authors: Vec::new(),
descriptions: Vec::new(),
};
for part in url.to_string().rsplit('/') {
if!part.is_empty() {
package.id = part.to_string();
break;
}
}
let mut info = String::new();
if let Ok(mut file) = File::open(&(url.to_string() + "_REDOX")) {
file.read_to_string(&mut info);
}
for line in info.lines() {
if line.starts_with("name=") {
package.name = line.get_slice(Some(5), None).to_string();
} else if line.starts_with("binary=") {
package.binary = url.to_string() + line.get_slice(Some(7), None);
} else if line.starts_with("icon=") {
package.icon = BmpFile::from_path(line.get_slice(Some(5), None));
} else if line.starts_with("accept=") {
package.accepts.push(line.get_slice(Some(7), None).to_string());
} else if line.starts_with("author=") {
package.authors.push(line.get_slice(Some(7), None).to_string());
} else if line.starts_with("description=") {
package.descriptions.push(line.get_slice(Some(12), None).to_string());
} else {
println!("Unknown package info: {}", line);
}
}
package
}
}
| Package | identifier_name |
package.rs | use std::get_slice::GetSlice;
use std::url::Url;
use std::fs::File;
use std::io::Read;
use orbital::BmpFile;
/// A package (_REDOX content serialized)
pub struct Package {
/// The URL
pub url: Url,
/// The ID of the package
pub id: String,
/// The name of the package
pub name: String,
/// The binary for the package
pub binary: String,
/// The icon for the package
pub icon: BmpFile,
/// The accepted extensions
pub accepts: Vec<String>,
/// The author(s) of the package
pub authors: Vec<String>,
/// The description of the package
pub descriptions: Vec<String>,
}
impl Package {
/// Create package from URL
pub fn from_url(url: &Url) -> Box<Self> {
let mut package = box Package {
url: url.clone(),
id: String::new(),
name: String::new(),
binary: url.to_string() + "main.bin",
icon: BmpFile::default(),
accepts: Vec::new(),
authors: Vec::new(),
descriptions: Vec::new(),
};
| }
let mut info = String::new();
if let Ok(mut file) = File::open(&(url.to_string() + "_REDOX")) {
file.read_to_string(&mut info);
}
for line in info.lines() {
if line.starts_with("name=") {
package.name = line.get_slice(Some(5), None).to_string();
} else if line.starts_with("binary=") {
package.binary = url.to_string() + line.get_slice(Some(7), None);
} else if line.starts_with("icon=") {
package.icon = BmpFile::from_path(line.get_slice(Some(5), None));
} else if line.starts_with("accept=") {
package.accepts.push(line.get_slice(Some(7), None).to_string());
} else if line.starts_with("author=") {
package.authors.push(line.get_slice(Some(7), None).to_string());
} else if line.starts_with("description=") {
package.descriptions.push(line.get_slice(Some(12), None).to_string());
} else {
println!("Unknown package info: {}", line);
}
}
package
}
} | for part in url.to_string().rsplit('/') {
if !part.is_empty() {
package.id = part.to_string();
break;
} | random_line_split |
package.rs | use std::get_slice::GetSlice;
use std::url::Url;
use std::fs::File;
use std::io::Read;
use orbital::BmpFile;
/// A package (_REDOX content serialized)
pub struct Package {
/// The URL
pub url: Url,
/// The ID of the package
pub id: String,
/// The name of the package
pub name: String,
/// The binary for the package
pub binary: String,
/// The icon for the package
pub icon: BmpFile,
/// The accepted extensions
pub accepts: Vec<String>,
/// The author(s) of the package
pub authors: Vec<String>,
/// The description of the package
pub descriptions: Vec<String>,
}
impl Package {
/// Create package from URL
pub fn from_url(url: &Url) -> Box<Self> {
let mut package = box Package {
url: url.clone(),
id: String::new(),
name: String::new(),
binary: url.to_string() + "main.bin",
icon: BmpFile::default(),
accepts: Vec::new(),
authors: Vec::new(),
descriptions: Vec::new(),
};
for part in url.to_string().rsplit('/') {
if!part.is_empty() {
package.id = part.to_string();
break;
}
}
let mut info = String::new();
if let Ok(mut file) = File::open(&(url.to_string() + "_REDOX")) {
file.read_to_string(&mut info);
}
for line in info.lines() {
if line.starts_with("name=") {
package.name = line.get_slice(Some(5), None).to_string();
} else if line.starts_with("binary=") | else if line.starts_with("icon=") {
package.icon = BmpFile::from_path(line.get_slice(Some(5), None));
} else if line.starts_with("accept=") {
package.accepts.push(line.get_slice(Some(7), None).to_string());
} else if line.starts_with("author=") {
package.authors.push(line.get_slice(Some(7), None).to_string());
} else if line.starts_with("description=") {
package.descriptions.push(line.get_slice(Some(12), None).to_string());
} else {
println!("Unknown package info: {}", line);
}
}
package
}
}
| {
package.binary = url.to_string() + line.get_slice(Some(7), None);
} | conditional_block |
point-mutations.rs | extern crate point_mutations as dna;
#[test]
fn | () {
assert_eq!(dna::hamming_distance("", "").unwrap(), 0);
}
#[test]
#[ignore]
fn test_no_difference_between_identical_strands() {
assert_eq!(dna::hamming_distance("GGACTGA", "GGACTGA").unwrap(), 0);
}
#[test]
#[ignore]
fn test_complete_hamming_distance_in_small_strand() {
assert_eq!(dna::hamming_distance("ACT", "GGA").unwrap(), 3);
}
#[test]
#[ignore]
fn test_small_hamming_distance_in_the_middle_somewhere() {
assert_eq!(dna::hamming_distance("GGACG", "GGTCG").unwrap(), 1);
}
#[test]
#[ignore]
fn test_larger_distance() {
assert_eq!(dna::hamming_distance("ACCAGGG", "ACTATGG").unwrap(), 2);
}
#[test]
#[ignore]
fn test_first_string_is_longer() {
assert_eq!(dna::hamming_distance("AAA", "AA"), Result::Err("inputs of different length"));
}
#[test]
#[ignore]
fn test_second_string_is_longer() {
assert_eq!(dna::hamming_distance("A", "AA"), Result::Err("inputs of different length"));
}
| test_no_difference_between_empty_strands | identifier_name |
point-mutations.rs | extern crate point_mutations as dna;
#[test]
fn test_no_difference_between_empty_strands() {
assert_eq!(dna::hamming_distance("", "").unwrap(), 0);
}
#[test]
#[ignore]
fn test_no_difference_between_identical_strands() {
assert_eq!(dna::hamming_distance("GGACTGA", "GGACTGA").unwrap(), 0);
}
#[test]
#[ignore]
fn test_complete_hamming_distance_in_small_strand() {
assert_eq!(dna::hamming_distance("ACT", "GGA").unwrap(), 3);
}
#[test]
#[ignore]
fn test_small_hamming_distance_in_the_middle_somewhere() {
assert_eq!(dna::hamming_distance("GGACG", "GGTCG").unwrap(), 1);
}
#[test]
#[ignore] |
#[test]
#[ignore]
fn test_first_string_is_longer() {
assert_eq!(dna::hamming_distance("AAA", "AA"), Result::Err("inputs of different length"));
}
#[test]
#[ignore]
fn test_second_string_is_longer() {
assert_eq!(dna::hamming_distance("A", "AA"), Result::Err("inputs of different length"));
} | fn test_larger_distance() {
assert_eq!(dna::hamming_distance("ACCAGGG", "ACTATGG").unwrap(), 2);
} | random_line_split |
point-mutations.rs | extern crate point_mutations as dna;
#[test]
fn test_no_difference_between_empty_strands() {
assert_eq!(dna::hamming_distance("", "").unwrap(), 0);
}
#[test]
#[ignore]
fn test_no_difference_between_identical_strands() {
assert_eq!(dna::hamming_distance("GGACTGA", "GGACTGA").unwrap(), 0);
}
#[test]
#[ignore]
fn test_complete_hamming_distance_in_small_strand() {
assert_eq!(dna::hamming_distance("ACT", "GGA").unwrap(), 3);
}
#[test]
#[ignore]
fn test_small_hamming_distance_in_the_middle_somewhere() |
#[test]
#[ignore]
fn test_larger_distance() {
assert_eq!(dna::hamming_distance("ACCAGGG", "ACTATGG").unwrap(), 2);
}
#[test]
#[ignore]
fn test_first_string_is_longer() {
assert_eq!(dna::hamming_distance("AAA", "AA"), Result::Err("inputs of different length"));
}
#[test]
#[ignore]
fn test_second_string_is_longer() {
assert_eq!(dna::hamming_distance("A", "AA"), Result::Err("inputs of different length"));
}
| {
assert_eq!(dna::hamming_distance("GGACG", "GGTCG").unwrap(), 1);
} | identifier_body |
p048.rs | //! [Problem 48](https://projecteuler.net/problem=48) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use num_bigint::BigUint;
use num_traits::{FromPrimitive, ToPrimitive};
fn compute(max: u64, modulo: u64) -> u64 {
let bu_m: BigUint = FromPrimitive::from_u64(modulo).unwrap();
let mut sum = 0;
for n in 1..(max + 1) {
let bu_n: BigUint = FromPrimitive::from_u64(n).unwrap();
let pow = bu_n.modpow(&bu_n, &bu_m).to_u64().unwrap();
sum = (sum + pow) % modulo;
}
sum
}
fn solve() -> String {
compute(1000, 100_0000_0000).to_string() | }
common::problem!("9110846700", solve);
#[cfg(test)]
mod tests {
#[test]
fn ten() {
let modulo = 100_0000_0000;
assert_eq!(10405071317 % modulo, super::compute(10, modulo))
}
} | random_line_split |
|
p048.rs | //! [Problem 48](https://projecteuler.net/problem=48) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use num_bigint::BigUint;
use num_traits::{FromPrimitive, ToPrimitive};
fn compute(max: u64, modulo: u64) -> u64 {
let bu_m: BigUint = FromPrimitive::from_u64(modulo).unwrap();
let mut sum = 0;
for n in 1..(max + 1) {
let bu_n: BigUint = FromPrimitive::from_u64(n).unwrap();
let pow = bu_n.modpow(&bu_n, &bu_m).to_u64().unwrap();
sum = (sum + pow) % modulo;
}
sum
}
fn | () -> String {
compute(1000, 100_0000_0000).to_string()
}
common::problem!("9110846700", solve);
#[cfg(test)]
mod tests {
#[test]
fn ten() {
let modulo = 100_0000_0000;
assert_eq!(10405071317 % modulo, super::compute(10, modulo))
}
}
| solve | identifier_name |
p048.rs | //! [Problem 48](https://projecteuler.net/problem=48) solver.
#![warn(
bad_style,
unused,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
use num_bigint::BigUint;
use num_traits::{FromPrimitive, ToPrimitive};
fn compute(max: u64, modulo: u64) -> u64 {
let bu_m: BigUint = FromPrimitive::from_u64(modulo).unwrap();
let mut sum = 0;
for n in 1..(max + 1) {
let bu_n: BigUint = FromPrimitive::from_u64(n).unwrap();
let pow = bu_n.modpow(&bu_n, &bu_m).to_u64().unwrap();
sum = (sum + pow) % modulo;
}
sum
}
fn solve() -> String |
common::problem!("9110846700", solve);
#[cfg(test)]
mod tests {
#[test]
fn ten() {
let modulo = 100_0000_0000;
assert_eq!(10405071317 % modulo, super::compute(10, modulo))
}
}
| {
compute(1000, 100_0000_0000).to_string()
} | 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.
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(unused_unsafe)]
#![allow(unused_mut)]
use prelude::v1::*;
use ffi;
use io::{self, ErrorKind};
use libc;
use num::{Int, SignedInt};
use num;
use old_io::{self, IoResult, IoError};
use str;
use sys_common::mkerr_libc;
macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
static $name: Helper<$m> = Helper {
lock: ::sync::MUTEX_INIT,
cond: ::sync::CONDVAR_INIT,
chan: ::cell::UnsafeCell { value: 0 as *mut Sender<$m> },
signal: ::cell::UnsafeCell { value: 0 },
initialized: ::cell::UnsafeCell { value: false },
shutdown: ::cell::UnsafeCell { value: false },
};
) }
pub mod backtrace;
pub mod c;
pub mod condvar;
pub mod ext;
pub mod fd;
pub mod fs; // support for std::old_io
pub mod fs2; // support for std::fs
pub mod helper_signal;
pub mod mutex;
pub mod net;
pub mod os;
pub mod os_str;
pub mod pipe;
pub mod process;
pub mod rwlock;
pub mod stack_overflow;
pub mod sync;
pub mod tcp;
pub mod thread;
pub mod thread_local;
pub mod time;
pub mod timer;
pub mod tty;
pub mod udp;
pub mod addrinfo {
pub use sys_common::net::get_host_addresses;
pub use sys_common::net::get_address_name;
}
// FIXME: move these to c module
pub type sock_t = self::fs::fd_t;
pub type wrlen = libc::size_t;
pub type msglen_t = libc::size_t;
pub unsafe fn close_sock(sock: sock_t) { let _ = libc::close(sock); }
pub fn last_error() -> IoError {
decode_error_detailed(os::errno() as i32)
}
pub fn last_net_error() -> IoError {
last_error()
}
extern "system" {
fn gai_strerror(errcode: libc::c_int) -> *const libc::c_char;
}
pub fn last_gai_error(s: libc::c_int) -> IoError {
let mut err = decode_error(s);
err.detail = Some(unsafe {
str::from_utf8(ffi::c_str_to_bytes(&gai_strerror(s))).unwrap().to_string()
});
err
}
/// Convert an `errno` value into a high-level error variant and description.
pub fn decode_error(errno: i32) -> IoError {
// FIXME: this should probably be a bit more descriptive...
let (kind, desc) = match errno {
libc::EOF => (old_io::EndOfFile, "end of file"),
libc::ECONNREFUSED => (old_io::ConnectionRefused, "connection refused"),
libc::ECONNRESET => (old_io::ConnectionReset, "connection reset"),
libc::EPERM | libc::EACCES =>
(old_io::PermissionDenied, "permission denied"),
libc::EPIPE => (old_io::BrokenPipe, "broken pipe"),
libc::ENOTCONN => (old_io::NotConnected, "not connected"),
libc::ECONNABORTED => (old_io::ConnectionAborted, "connection aborted"),
libc::EADDRNOTAVAIL => (old_io::ConnectionRefused, "address not available"),
libc::EADDRINUSE => (old_io::ConnectionRefused, "address in use"),
libc::ENOENT => (old_io::FileNotFound, "no such file or directory"),
libc::EISDIR => (old_io::InvalidInput, "illegal operation on a directory"),
libc::ENOSYS => (old_io::IoUnavailable, "function not implemented"),
libc::EINVAL => (old_io::InvalidInput, "invalid argument"),
libc::ENOTTY =>
(old_io::MismatchedFileTypeForOperation,
"file descriptor is not a TTY"),
libc::ETIMEDOUT => (old_io::TimedOut, "operation timed out"),
libc::ECANCELED => (old_io::TimedOut, "operation aborted"),
libc::consts::os::posix88::EEXIST =>
(old_io::PathAlreadyExists, "path already exists"),
// These two constants can have the same value on some systems,
// but different values on others, so we can't use a match
// clause
x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
(old_io::ResourceUnavailable, "resource temporarily unavailable"),
_ => (old_io::OtherIoError, "unknown error")
};
IoError { kind: kind, desc: desc, detail: None }
}
pub fn decode_error_detailed(errno: i32) -> IoError {
let mut err = decode_error(errno);
err.detail = Some(os::error_string(errno));
err
}
pub fn decode_error_kind(errno: i32) -> ErrorKind {
match errno as libc::c_int {
libc::ECONNREFUSED => ErrorKind::ConnectionRefused,
libc::ECONNRESET => ErrorKind::ConnectionReset,
libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied,
libc::EPIPE => ErrorKind::BrokenPipe,
libc::ENOTCONN => ErrorKind::NotConnected,
libc::ECONNABORTED => ErrorKind::ConnectionAborted,
libc::EADDRNOTAVAIL => ErrorKind::ConnectionRefused,
libc::EADDRINUSE => ErrorKind::ConnectionRefused,
libc::ENOENT => ErrorKind::FileNotFound,
libc::EISDIR => ErrorKind::InvalidInput,
libc::EINTR => ErrorKind::Interrupted,
libc::EINVAL => ErrorKind::InvalidInput,
libc::ENOTTY => ErrorKind::MismatchedFileTypeForOperation,
libc::ETIMEDOUT => ErrorKind::TimedOut,
libc::ECANCELED => ErrorKind::TimedOut,
libc::consts::os::posix88::EEXIST => ErrorKind::PathAlreadyExists,
// These two constants can have the same value on some systems,
// but different values on others, so we can't use a match
// clause
x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
ErrorKind::ResourceUnavailable,
_ => ErrorKind::Other,
}
}
#[inline]
pub fn retry<T, F> (mut f: F) -> T where
T: SignedInt,
F: FnMut() -> T,
{
let one: T = Int::one();
loop {
let n = f();
if n == -one && os::errno() == libc::EINTR as i32 { }
else { return n }
}
}
pub fn cvt<T: SignedInt>(t: T) -> io::Result<T> {
let one: T = Int::one();
if t == -one {
Err(io::Error::last_os_error())
} else {
Ok(t)
}
}
pub fn | <T, F>(mut f: F) -> io::Result<T>
where T: SignedInt, F: FnMut() -> T
{
loop {
match cvt(f()) {
Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
other => return other,
}
}
}
pub fn ms_to_timeval(ms: u64) -> libc::timeval {
libc::timeval {
tv_sec: (ms / 1000) as libc::time_t,
tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t,
}
}
pub fn wouldblock() -> bool {
let err = os::errno();
err == libc::EWOULDBLOCK as i32 || err == libc::EAGAIN as i32
}
pub fn set_nonblocking(fd: sock_t, nb: bool) -> IoResult<()> {
let set = nb as libc::c_int;
mkerr_libc(retry(|| unsafe { c::ioctl(fd, c::FIONBIO, &set) }))
}
// nothing needed on unix platforms
pub fn init_net() {}
| cvt_r | 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.
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(unused_unsafe)]
#![allow(unused_mut)]
use prelude::v1::*;
use ffi;
use io::{self, ErrorKind};
use libc;
use num::{Int, SignedInt};
use num;
use old_io::{self, IoResult, IoError};
use str;
use sys_common::mkerr_libc;
macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
static $name: Helper<$m> = Helper {
lock: ::sync::MUTEX_INIT,
cond: ::sync::CONDVAR_INIT,
chan: ::cell::UnsafeCell { value: 0 as *mut Sender<$m> },
signal: ::cell::UnsafeCell { value: 0 },
initialized: ::cell::UnsafeCell { value: false },
shutdown: ::cell::UnsafeCell { value: false },
};
) }
pub mod backtrace;
pub mod c;
pub mod condvar;
pub mod ext;
pub mod fd;
pub mod fs; // support for std::old_io
pub mod fs2; // support for std::fs
pub mod helper_signal;
pub mod mutex;
pub mod net;
pub mod os;
pub mod os_str;
pub mod pipe;
pub mod process;
pub mod rwlock;
pub mod stack_overflow;
pub mod sync;
pub mod tcp;
pub mod thread;
pub mod thread_local;
pub mod time;
pub mod timer;
pub mod tty;
pub mod udp;
pub mod addrinfo {
pub use sys_common::net::get_host_addresses;
pub use sys_common::net::get_address_name;
}
// FIXME: move these to c module
pub type sock_t = self::fs::fd_t;
pub type wrlen = libc::size_t;
pub type msglen_t = libc::size_t;
pub unsafe fn close_sock(sock: sock_t) { let _ = libc::close(sock); }
pub fn last_error() -> IoError {
decode_error_detailed(os::errno() as i32)
}
pub fn last_net_error() -> IoError {
last_error()
}
extern "system" {
fn gai_strerror(errcode: libc::c_int) -> *const libc::c_char;
}
pub fn last_gai_error(s: libc::c_int) -> IoError {
let mut err = decode_error(s);
err.detail = Some(unsafe {
str::from_utf8(ffi::c_str_to_bytes(&gai_strerror(s))).unwrap().to_string()
});
err
}
/// Convert an `errno` value into a high-level error variant and description.
pub fn decode_error(errno: i32) -> IoError {
// FIXME: this should probably be a bit more descriptive...
let (kind, desc) = match errno {
libc::EOF => (old_io::EndOfFile, "end of file"),
libc::ECONNREFUSED => (old_io::ConnectionRefused, "connection refused"),
libc::ECONNRESET => (old_io::ConnectionReset, "connection reset"),
libc::EPERM | libc::EACCES =>
(old_io::PermissionDenied, "permission denied"),
libc::EPIPE => (old_io::BrokenPipe, "broken pipe"),
libc::ENOTCONN => (old_io::NotConnected, "not connected"),
libc::ECONNABORTED => (old_io::ConnectionAborted, "connection aborted"),
libc::EADDRNOTAVAIL => (old_io::ConnectionRefused, "address not available"),
libc::EADDRINUSE => (old_io::ConnectionRefused, "address in use"),
libc::ENOENT => (old_io::FileNotFound, "no such file or directory"),
libc::EISDIR => (old_io::InvalidInput, "illegal operation on a directory"),
libc::ENOSYS => (old_io::IoUnavailable, "function not implemented"),
libc::EINVAL => (old_io::InvalidInput, "invalid argument"),
libc::ENOTTY =>
(old_io::MismatchedFileTypeForOperation,
"file descriptor is not a TTY"),
libc::ETIMEDOUT => (old_io::TimedOut, "operation timed out"),
libc::ECANCELED => (old_io::TimedOut, "operation aborted"),
libc::consts::os::posix88::EEXIST =>
(old_io::PathAlreadyExists, "path already exists"),
// These two constants can have the same value on some systems,
// but different values on others, so we can't use a match
// clause
x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
(old_io::ResourceUnavailable, "resource temporarily unavailable"),
_ => (old_io::OtherIoError, "unknown error")
};
IoError { kind: kind, desc: desc, detail: None }
}
pub fn decode_error_detailed(errno: i32) -> IoError {
let mut err = decode_error(errno);
err.detail = Some(os::error_string(errno));
err
}
pub fn decode_error_kind(errno: i32) -> ErrorKind {
match errno as libc::c_int {
libc::ECONNREFUSED => ErrorKind::ConnectionRefused,
libc::ECONNRESET => ErrorKind::ConnectionReset,
libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied,
libc::EPIPE => ErrorKind::BrokenPipe,
libc::ENOTCONN => ErrorKind::NotConnected,
libc::ECONNABORTED => ErrorKind::ConnectionAborted,
libc::EADDRNOTAVAIL => ErrorKind::ConnectionRefused,
libc::EADDRINUSE => ErrorKind::ConnectionRefused,
libc::ENOENT => ErrorKind::FileNotFound,
libc::EISDIR => ErrorKind::InvalidInput,
libc::EINTR => ErrorKind::Interrupted,
libc::EINVAL => ErrorKind::InvalidInput,
libc::ENOTTY => ErrorKind::MismatchedFileTypeForOperation,
libc::ETIMEDOUT => ErrorKind::TimedOut,
libc::ECANCELED => ErrorKind::TimedOut,
libc::consts::os::posix88::EEXIST => ErrorKind::PathAlreadyExists,
// These two constants can have the same value on some systems,
// but different values on others, so we can't use a match
// clause
x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
ErrorKind::ResourceUnavailable,
_ => ErrorKind::Other,
}
}
#[inline]
pub fn retry<T, F> (mut f: F) -> T where
T: SignedInt,
F: FnMut() -> T,
{
let one: T = Int::one();
loop {
let n = f();
if n == -one && os::errno() == libc::EINTR as i32 { }
else { return n }
}
}
pub fn cvt<T: SignedInt>(t: T) -> io::Result<T> {
let one: T = Int::one();
if t == -one {
Err(io::Error::last_os_error())
} else {
Ok(t)
}
}
pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
where T: SignedInt, F: FnMut() -> T
{
loop {
match cvt(f()) {
Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
other => return other,
}
}
}
pub fn ms_to_timeval(ms: u64) -> libc::timeval |
pub fn wouldblock() -> bool {
let err = os::errno();
err == libc::EWOULDBLOCK as i32 || err == libc::EAGAIN as i32
}
pub fn set_nonblocking(fd: sock_t, nb: bool) -> IoResult<()> {
let set = nb as libc::c_int;
mkerr_libc(retry(|| unsafe { c::ioctl(fd, c::FIONBIO, &set) }))
}
// nothing needed on unix platforms
pub fn init_net() {}
| {
libc::timeval {
tv_sec: (ms / 1000) as libc::time_t,
tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t,
}
} | 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.
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![allow(unused_imports)]
#![allow(dead_code)]
#![allow(unused_unsafe)]
#![allow(unused_mut)]
use prelude::v1::*;
use ffi;
use io::{self, ErrorKind};
use libc;
use num::{Int, SignedInt};
use num;
use old_io::{self, IoResult, IoError};
use str;
use sys_common::mkerr_libc;
macro_rules! helper_init { (static $name:ident: Helper<$m:ty>) => (
static $name: Helper<$m> = Helper {
lock: ::sync::MUTEX_INIT, | };
) }
pub mod backtrace;
pub mod c;
pub mod condvar;
pub mod ext;
pub mod fd;
pub mod fs; // support for std::old_io
pub mod fs2; // support for std::fs
pub mod helper_signal;
pub mod mutex;
pub mod net;
pub mod os;
pub mod os_str;
pub mod pipe;
pub mod process;
pub mod rwlock;
pub mod stack_overflow;
pub mod sync;
pub mod tcp;
pub mod thread;
pub mod thread_local;
pub mod time;
pub mod timer;
pub mod tty;
pub mod udp;
pub mod addrinfo {
pub use sys_common::net::get_host_addresses;
pub use sys_common::net::get_address_name;
}
// FIXME: move these to c module
pub type sock_t = self::fs::fd_t;
pub type wrlen = libc::size_t;
pub type msglen_t = libc::size_t;
pub unsafe fn close_sock(sock: sock_t) { let _ = libc::close(sock); }
pub fn last_error() -> IoError {
decode_error_detailed(os::errno() as i32)
}
pub fn last_net_error() -> IoError {
last_error()
}
extern "system" {
fn gai_strerror(errcode: libc::c_int) -> *const libc::c_char;
}
pub fn last_gai_error(s: libc::c_int) -> IoError {
let mut err = decode_error(s);
err.detail = Some(unsafe {
str::from_utf8(ffi::c_str_to_bytes(&gai_strerror(s))).unwrap().to_string()
});
err
}
/// Convert an `errno` value into a high-level error variant and description.
pub fn decode_error(errno: i32) -> IoError {
// FIXME: this should probably be a bit more descriptive...
let (kind, desc) = match errno {
libc::EOF => (old_io::EndOfFile, "end of file"),
libc::ECONNREFUSED => (old_io::ConnectionRefused, "connection refused"),
libc::ECONNRESET => (old_io::ConnectionReset, "connection reset"),
libc::EPERM | libc::EACCES =>
(old_io::PermissionDenied, "permission denied"),
libc::EPIPE => (old_io::BrokenPipe, "broken pipe"),
libc::ENOTCONN => (old_io::NotConnected, "not connected"),
libc::ECONNABORTED => (old_io::ConnectionAborted, "connection aborted"),
libc::EADDRNOTAVAIL => (old_io::ConnectionRefused, "address not available"),
libc::EADDRINUSE => (old_io::ConnectionRefused, "address in use"),
libc::ENOENT => (old_io::FileNotFound, "no such file or directory"),
libc::EISDIR => (old_io::InvalidInput, "illegal operation on a directory"),
libc::ENOSYS => (old_io::IoUnavailable, "function not implemented"),
libc::EINVAL => (old_io::InvalidInput, "invalid argument"),
libc::ENOTTY =>
(old_io::MismatchedFileTypeForOperation,
"file descriptor is not a TTY"),
libc::ETIMEDOUT => (old_io::TimedOut, "operation timed out"),
libc::ECANCELED => (old_io::TimedOut, "operation aborted"),
libc::consts::os::posix88::EEXIST =>
(old_io::PathAlreadyExists, "path already exists"),
// These two constants can have the same value on some systems,
// but different values on others, so we can't use a match
// clause
x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
(old_io::ResourceUnavailable, "resource temporarily unavailable"),
_ => (old_io::OtherIoError, "unknown error")
};
IoError { kind: kind, desc: desc, detail: None }
}
pub fn decode_error_detailed(errno: i32) -> IoError {
let mut err = decode_error(errno);
err.detail = Some(os::error_string(errno));
err
}
pub fn decode_error_kind(errno: i32) -> ErrorKind {
match errno as libc::c_int {
libc::ECONNREFUSED => ErrorKind::ConnectionRefused,
libc::ECONNRESET => ErrorKind::ConnectionReset,
libc::EPERM | libc::EACCES => ErrorKind::PermissionDenied,
libc::EPIPE => ErrorKind::BrokenPipe,
libc::ENOTCONN => ErrorKind::NotConnected,
libc::ECONNABORTED => ErrorKind::ConnectionAborted,
libc::EADDRNOTAVAIL => ErrorKind::ConnectionRefused,
libc::EADDRINUSE => ErrorKind::ConnectionRefused,
libc::ENOENT => ErrorKind::FileNotFound,
libc::EISDIR => ErrorKind::InvalidInput,
libc::EINTR => ErrorKind::Interrupted,
libc::EINVAL => ErrorKind::InvalidInput,
libc::ENOTTY => ErrorKind::MismatchedFileTypeForOperation,
libc::ETIMEDOUT => ErrorKind::TimedOut,
libc::ECANCELED => ErrorKind::TimedOut,
libc::consts::os::posix88::EEXIST => ErrorKind::PathAlreadyExists,
// These two constants can have the same value on some systems,
// but different values on others, so we can't use a match
// clause
x if x == libc::EAGAIN || x == libc::EWOULDBLOCK =>
ErrorKind::ResourceUnavailable,
_ => ErrorKind::Other,
}
}
#[inline]
pub fn retry<T, F> (mut f: F) -> T where
T: SignedInt,
F: FnMut() -> T,
{
let one: T = Int::one();
loop {
let n = f();
if n == -one && os::errno() == libc::EINTR as i32 { }
else { return n }
}
}
pub fn cvt<T: SignedInt>(t: T) -> io::Result<T> {
let one: T = Int::one();
if t == -one {
Err(io::Error::last_os_error())
} else {
Ok(t)
}
}
pub fn cvt_r<T, F>(mut f: F) -> io::Result<T>
where T: SignedInt, F: FnMut() -> T
{
loop {
match cvt(f()) {
Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
other => return other,
}
}
}
pub fn ms_to_timeval(ms: u64) -> libc::timeval {
libc::timeval {
tv_sec: (ms / 1000) as libc::time_t,
tv_usec: ((ms % 1000) * 1000) as libc::suseconds_t,
}
}
pub fn wouldblock() -> bool {
let err = os::errno();
err == libc::EWOULDBLOCK as i32 || err == libc::EAGAIN as i32
}
pub fn set_nonblocking(fd: sock_t, nb: bool) -> IoResult<()> {
let set = nb as libc::c_int;
mkerr_libc(retry(|| unsafe { c::ioctl(fd, c::FIONBIO, &set) }))
}
// nothing needed on unix platforms
pub fn init_net() {} | cond: ::sync::CONDVAR_INIT,
chan: ::cell::UnsafeCell { value: 0 as *mut Sender<$m> },
signal: ::cell::UnsafeCell { value: 0 },
initialized: ::cell::UnsafeCell { value: false },
shutdown: ::cell::UnsafeCell { value: false }, | random_line_split |
main.rs | #![feature(asm)]
#![feature(const_fn)]
#![feature(proc_macro)]
#![no_std]
extern crate cast;
extern crate cortex_m;
extern crate cortex_m_rtfm as rtfm;
extern crate blue_pill;
extern crate numtoa;
use blue_pill::stm32f103xx::Interrupt;
use cortex_m::peripheral::SystClkSource;
use rtfm::{app, Threshold};
mod font5x7;
mod i2c;
mod mma8652fc;
mod ssd1306;
mod state;
use mma8652fc::MMA8652FC;
use ssd1306::SSD1306;
use state::{ConfigPage, Keys, State, StateMachine};
const OLED_ADDR: u8 = 0x3c;
app! {
device: blue_pill::stm32f103xx,
resources: {
static TICKS: u32 = 0;
static STATE: StateMachine = StateMachine::new();
},
tasks: {
SYS_TICK: {
path: tick,
resources: [TICKS],
},
EXTI0: {
path: update_ui,
resources: [I2C1, STATE],
},
EXTI9_5: {
path: exti9_5,
resources: [I2C1, STATE, GPIOA, GPIOB, EXTI],
},
},
}
fn init(p: init::Peripherals, _r: init::Resources) {
// 48Mhz
p.FLASH.acr.modify(
|_, w| w.prftbe().enabled().latency().one(),
);
p.RCC.cfgr.modify(|_, w| unsafe { w.bits(0x0068840A) });
p.RCC.cr.modify(
|_, w| w.pllon().set_bit().hsion().set_bit(),
);
while p.RCC.cr.read().pllrdy().bit_is_clear() {}
while p.RCC.cr.read().hsirdy().bit_is_clear() {}
p.RCC.apb2enr.modify(|_, w| {
w.iopaen().enabled().iopben().enabled().afioen().enabled() |
p.RCC.apb1enr.modify(|_, w| w.i2c1en().enabled());
p.I2C1.cr1.write(|w| w.pe().clear_bit());
p.GPIOA.crl.modify(|_, w| w.mode6().input());
p.GPIOA.crh.modify(|_, w| {
w.mode8().output50().cnf8().push().mode9().input()
});
p.GPIOA.bsrr.write(|w| {
w.bs6().set_bit().bs8().set_bit().bs9().set_bit()
});
p.GPIOB.crl.modify(|_, w| {
w.mode5()
.input()
.mode6()
.output50()
.cnf6()
.alt_open()
.mode7()
.output50()
.cnf7()
.alt_open()
});
p.GPIOB.bsrr.write(|w| w.bs5().set_bit());
p.AFIO.exticr2.modify(|_, w| unsafe {
w.exti5().bits(1).exti6().bits(0)
});
p.AFIO.exticr3.modify(|_, w| unsafe { w.exti9().bits(0) });
p.EXTI.imr.modify(|_, w| {
w.mr5().set_bit().mr6().set_bit().mr9().set_bit()
});
p.EXTI.rtsr.modify(|_, w| {
w.tr5().set_bit().tr6().set_bit().tr9().set_bit()
});
p.EXTI.ftsr.modify(|_, w| {
w.tr5().set_bit().tr6().set_bit().tr9().set_bit()
});
p.I2C1.cr2.modify(|_, w| unsafe { w.freq().bits(24) });
p.I2C1.cr1.modify(|_, w| w.pe().clear_bit());
p.I2C1.trise.modify(
|_, w| unsafe { w.trise().bits(24 + 1) },
);
p.I2C1.ccr.modify(|_, w| unsafe {
w.f_s().clear_bit().duty().clear_bit().ccr().bits(120)
});
p.I2C1.cr1.modify(|_, w| {
w.nostretch()
.clear_bit()
.ack()
.set_bit()
.smbus()
.clear_bit()
});
p.I2C1.cr1.write(|w| w.pe().set_bit());
p.I2C1.oar1.write(|w| unsafe {
w.addmode()
.clear_bit()
.add0()
.clear_bit()
.add7()
.bits(0)
.add10()
.bits(0)
});
let oled = SSD1306(OLED_ADDR, &p.I2C1);
oled.init();
oled.print(0, 0, " ");
oled.print(0, 1, " ");
let accel = MMA8652FC(&p.I2C1);
accel.init();
p.SYST.set_clock_source(SystClkSource::Core);
p.SYST.set_reload(48_000_000);
p.SYST.enable_interrupt();
p.SYST.enable_counter();
}
fn idle() ->! {
rtfm::set_pending(Interrupt::EXTI0);
loop {
rtfm::wfi();
}
}
fn tick(_t: &mut Threshold, r: SYS_TICK::Resources) {
**r.TICKS += 1;
}
fn update_ui(_t: &mut Threshold, r: EXTI0::Resources) {
let i2c1 = &**r.I2C1;
let oled = SSD1306(OLED_ADDR, &i2c1);
let am = MMA8652FC(&i2c1);
r.STATE.update_accel(am.accel());
r.STATE.update_state();
oled.print(0, 0, "X ");
oled.print(8, 0, "Y ");
oled.print(0, 1, "Z ");
let accel = r.STATE.get_accel();
oled.print_number(2, 0, accel.x);
oled.print_number(10, 0, accel.y);
oled.print_number(2, 1, accel.z);
/*
match r.STATE.current_state() {
State::Idle => {
oled.print(0, 0, " IDLE ");
oled.print(0, 1, " ");
}
State::Soldering => {
oled.print(0, 0, " SOLDERING ");
oled.print(0, 1, " ");
}
State::Cooling => {
oled.print(0, 0, " COOLING ");
oled.print(0, 1, " ");
}
State::Sleep => {
oled.print(0, 0, " zZzZzZ ");
oled.print(0, 1, " ");
}
State::TemperatureControl => {
oled.print(0, 0, " < 200 C > ");
}
State::Thermometer => {
oled.print(0, 0, " 200.1 C ");
}
State::Config(page) => {
match page {
ConfigPage::Save => {
oled.print(0, 0, "Save and Reset? ");
}
}
}
}
*/
}
fn exti9_5(_t: &mut Threshold, r: EXTI9_5::Resources) {
let exti = &**r.EXTI;
let gpioa = &**r.GPIOA;
let gpiob = &**r.GPIOB;
let i2c1 = &**r.I2C1;
// Button A
if exti.pr.read().pr6().bit_is_set() {
if gpioa.idr.read().idr6().bit_is_clear() {
r.STATE.update_keys(Keys::A);
} else {
r.STATE.update_keys(Keys::None);
};
exti.pr.write(|w| w.pr6().set_bit());
// Button B
} else if exti.pr.read().pr9().bit_is_set() {
if gpioa.idr.read().idr9().bit_is_clear() {
r.STATE.update_keys(Keys::B)
} else {
r.STATE.update_keys(Keys::None)
};
exti.pr.write(|w| w.pr9().set_bit());
// Movement
// interrupt doesn't fire
} else if exti.pr.read().pr5().bit_is_set() {
if gpiob.idr.read().idr5().bit_is_clear() {
let am = MMA8652FC(&i2c1);
r.STATE.update_accel(am.accel());
}
exti.pr.write(|w| w.pr5().set_bit());
}
rtfm::set_pending(Interrupt::EXTI0);
} | });
p.AFIO.mapr.modify(|_, w| unsafe {
w.swj_cfg().bits(2).i2c1_remap().clear_bit()
}); | random_line_split |
main.rs | #![feature(asm)]
#![feature(const_fn)]
#![feature(proc_macro)]
#![no_std]
extern crate cast;
extern crate cortex_m;
extern crate cortex_m_rtfm as rtfm;
extern crate blue_pill;
extern crate numtoa;
use blue_pill::stm32f103xx::Interrupt;
use cortex_m::peripheral::SystClkSource;
use rtfm::{app, Threshold};
mod font5x7;
mod i2c;
mod mma8652fc;
mod ssd1306;
mod state;
use mma8652fc::MMA8652FC;
use ssd1306::SSD1306;
use state::{ConfigPage, Keys, State, StateMachine};
const OLED_ADDR: u8 = 0x3c;
app! {
device: blue_pill::stm32f103xx,
resources: {
static TICKS: u32 = 0;
static STATE: StateMachine = StateMachine::new();
},
tasks: {
SYS_TICK: {
path: tick,
resources: [TICKS],
},
EXTI0: {
path: update_ui,
resources: [I2C1, STATE],
},
EXTI9_5: {
path: exti9_5,
resources: [I2C1, STATE, GPIOA, GPIOB, EXTI],
},
},
}
fn init(p: init::Peripherals, _r: init::Resources) {
// 48Mhz
p.FLASH.acr.modify(
|_, w| w.prftbe().enabled().latency().one(),
);
p.RCC.cfgr.modify(|_, w| unsafe { w.bits(0x0068840A) });
p.RCC.cr.modify(
|_, w| w.pllon().set_bit().hsion().set_bit(),
);
while p.RCC.cr.read().pllrdy().bit_is_clear() {}
while p.RCC.cr.read().hsirdy().bit_is_clear() {}
p.RCC.apb2enr.modify(|_, w| {
w.iopaen().enabled().iopben().enabled().afioen().enabled()
});
p.AFIO.mapr.modify(|_, w| unsafe {
w.swj_cfg().bits(2).i2c1_remap().clear_bit()
});
p.RCC.apb1enr.modify(|_, w| w.i2c1en().enabled());
p.I2C1.cr1.write(|w| w.pe().clear_bit());
p.GPIOA.crl.modify(|_, w| w.mode6().input());
p.GPIOA.crh.modify(|_, w| {
w.mode8().output50().cnf8().push().mode9().input()
});
p.GPIOA.bsrr.write(|w| {
w.bs6().set_bit().bs8().set_bit().bs9().set_bit()
});
p.GPIOB.crl.modify(|_, w| {
w.mode5()
.input()
.mode6()
.output50()
.cnf6()
.alt_open()
.mode7()
.output50()
.cnf7()
.alt_open()
});
p.GPIOB.bsrr.write(|w| w.bs5().set_bit());
p.AFIO.exticr2.modify(|_, w| unsafe {
w.exti5().bits(1).exti6().bits(0)
});
p.AFIO.exticr3.modify(|_, w| unsafe { w.exti9().bits(0) });
p.EXTI.imr.modify(|_, w| {
w.mr5().set_bit().mr6().set_bit().mr9().set_bit()
});
p.EXTI.rtsr.modify(|_, w| {
w.tr5().set_bit().tr6().set_bit().tr9().set_bit()
});
p.EXTI.ftsr.modify(|_, w| {
w.tr5().set_bit().tr6().set_bit().tr9().set_bit()
});
p.I2C1.cr2.modify(|_, w| unsafe { w.freq().bits(24) });
p.I2C1.cr1.modify(|_, w| w.pe().clear_bit());
p.I2C1.trise.modify(
|_, w| unsafe { w.trise().bits(24 + 1) },
);
p.I2C1.ccr.modify(|_, w| unsafe {
w.f_s().clear_bit().duty().clear_bit().ccr().bits(120)
});
p.I2C1.cr1.modify(|_, w| {
w.nostretch()
.clear_bit()
.ack()
.set_bit()
.smbus()
.clear_bit()
});
p.I2C1.cr1.write(|w| w.pe().set_bit());
p.I2C1.oar1.write(|w| unsafe {
w.addmode()
.clear_bit()
.add0()
.clear_bit()
.add7()
.bits(0)
.add10()
.bits(0)
});
let oled = SSD1306(OLED_ADDR, &p.I2C1);
oled.init();
oled.print(0, 0, " ");
oled.print(0, 1, " ");
let accel = MMA8652FC(&p.I2C1);
accel.init();
p.SYST.set_clock_source(SystClkSource::Core);
p.SYST.set_reload(48_000_000);
p.SYST.enable_interrupt();
p.SYST.enable_counter();
}
fn idle() ->! {
rtfm::set_pending(Interrupt::EXTI0);
loop {
rtfm::wfi();
}
}
fn tick(_t: &mut Threshold, r: SYS_TICK::Resources) {
**r.TICKS += 1;
}
fn | (_t: &mut Threshold, r: EXTI0::Resources) {
let i2c1 = &**r.I2C1;
let oled = SSD1306(OLED_ADDR, &i2c1);
let am = MMA8652FC(&i2c1);
r.STATE.update_accel(am.accel());
r.STATE.update_state();
oled.print(0, 0, "X ");
oled.print(8, 0, "Y ");
oled.print(0, 1, "Z ");
let accel = r.STATE.get_accel();
oled.print_number(2, 0, accel.x);
oled.print_number(10, 0, accel.y);
oled.print_number(2, 1, accel.z);
/*
match r.STATE.current_state() {
State::Idle => {
oled.print(0, 0, " IDLE ");
oled.print(0, 1, " ");
}
State::Soldering => {
oled.print(0, 0, " SOLDERING ");
oled.print(0, 1, " ");
}
State::Cooling => {
oled.print(0, 0, " COOLING ");
oled.print(0, 1, " ");
}
State::Sleep => {
oled.print(0, 0, " zZzZzZ ");
oled.print(0, 1, " ");
}
State::TemperatureControl => {
oled.print(0, 0, " < 200 C > ");
}
State::Thermometer => {
oled.print(0, 0, " 200.1 C ");
}
State::Config(page) => {
match page {
ConfigPage::Save => {
oled.print(0, 0, "Save and Reset? ");
}
}
}
}
*/
}
fn exti9_5(_t: &mut Threshold, r: EXTI9_5::Resources) {
let exti = &**r.EXTI;
let gpioa = &**r.GPIOA;
let gpiob = &**r.GPIOB;
let i2c1 = &**r.I2C1;
// Button A
if exti.pr.read().pr6().bit_is_set() {
if gpioa.idr.read().idr6().bit_is_clear() {
r.STATE.update_keys(Keys::A);
} else {
r.STATE.update_keys(Keys::None);
};
exti.pr.write(|w| w.pr6().set_bit());
// Button B
} else if exti.pr.read().pr9().bit_is_set() {
if gpioa.idr.read().idr9().bit_is_clear() {
r.STATE.update_keys(Keys::B)
} else {
r.STATE.update_keys(Keys::None)
};
exti.pr.write(|w| w.pr9().set_bit());
// Movement
// interrupt doesn't fire
} else if exti.pr.read().pr5().bit_is_set() {
if gpiob.idr.read().idr5().bit_is_clear() {
let am = MMA8652FC(&i2c1);
r.STATE.update_accel(am.accel());
}
exti.pr.write(|w| w.pr5().set_bit());
}
rtfm::set_pending(Interrupt::EXTI0);
}
| update_ui | identifier_name |
main.rs | #![feature(asm)]
#![feature(const_fn)]
#![feature(proc_macro)]
#![no_std]
extern crate cast;
extern crate cortex_m;
extern crate cortex_m_rtfm as rtfm;
extern crate blue_pill;
extern crate numtoa;
use blue_pill::stm32f103xx::Interrupt;
use cortex_m::peripheral::SystClkSource;
use rtfm::{app, Threshold};
mod font5x7;
mod i2c;
mod mma8652fc;
mod ssd1306;
mod state;
use mma8652fc::MMA8652FC;
use ssd1306::SSD1306;
use state::{ConfigPage, Keys, State, StateMachine};
const OLED_ADDR: u8 = 0x3c;
app! {
device: blue_pill::stm32f103xx,
resources: {
static TICKS: u32 = 0;
static STATE: StateMachine = StateMachine::new();
},
tasks: {
SYS_TICK: {
path: tick,
resources: [TICKS],
},
EXTI0: {
path: update_ui,
resources: [I2C1, STATE],
},
EXTI9_5: {
path: exti9_5,
resources: [I2C1, STATE, GPIOA, GPIOB, EXTI],
},
},
}
fn init(p: init::Peripherals, _r: init::Resources) {
// 48Mhz
p.FLASH.acr.modify(
|_, w| w.prftbe().enabled().latency().one(),
);
p.RCC.cfgr.modify(|_, w| unsafe { w.bits(0x0068840A) });
p.RCC.cr.modify(
|_, w| w.pllon().set_bit().hsion().set_bit(),
);
while p.RCC.cr.read().pllrdy().bit_is_clear() {}
while p.RCC.cr.read().hsirdy().bit_is_clear() {}
p.RCC.apb2enr.modify(|_, w| {
w.iopaen().enabled().iopben().enabled().afioen().enabled()
});
p.AFIO.mapr.modify(|_, w| unsafe {
w.swj_cfg().bits(2).i2c1_remap().clear_bit()
});
p.RCC.apb1enr.modify(|_, w| w.i2c1en().enabled());
p.I2C1.cr1.write(|w| w.pe().clear_bit());
p.GPIOA.crl.modify(|_, w| w.mode6().input());
p.GPIOA.crh.modify(|_, w| {
w.mode8().output50().cnf8().push().mode9().input()
});
p.GPIOA.bsrr.write(|w| {
w.bs6().set_bit().bs8().set_bit().bs9().set_bit()
});
p.GPIOB.crl.modify(|_, w| {
w.mode5()
.input()
.mode6()
.output50()
.cnf6()
.alt_open()
.mode7()
.output50()
.cnf7()
.alt_open()
});
p.GPIOB.bsrr.write(|w| w.bs5().set_bit());
p.AFIO.exticr2.modify(|_, w| unsafe {
w.exti5().bits(1).exti6().bits(0)
});
p.AFIO.exticr3.modify(|_, w| unsafe { w.exti9().bits(0) });
p.EXTI.imr.modify(|_, w| {
w.mr5().set_bit().mr6().set_bit().mr9().set_bit()
});
p.EXTI.rtsr.modify(|_, w| {
w.tr5().set_bit().tr6().set_bit().tr9().set_bit()
});
p.EXTI.ftsr.modify(|_, w| {
w.tr5().set_bit().tr6().set_bit().tr9().set_bit()
});
p.I2C1.cr2.modify(|_, w| unsafe { w.freq().bits(24) });
p.I2C1.cr1.modify(|_, w| w.pe().clear_bit());
p.I2C1.trise.modify(
|_, w| unsafe { w.trise().bits(24 + 1) },
);
p.I2C1.ccr.modify(|_, w| unsafe {
w.f_s().clear_bit().duty().clear_bit().ccr().bits(120)
});
p.I2C1.cr1.modify(|_, w| {
w.nostretch()
.clear_bit()
.ack()
.set_bit()
.smbus()
.clear_bit()
});
p.I2C1.cr1.write(|w| w.pe().set_bit());
p.I2C1.oar1.write(|w| unsafe {
w.addmode()
.clear_bit()
.add0()
.clear_bit()
.add7()
.bits(0)
.add10()
.bits(0)
});
let oled = SSD1306(OLED_ADDR, &p.I2C1);
oled.init();
oled.print(0, 0, " ");
oled.print(0, 1, " ");
let accel = MMA8652FC(&p.I2C1);
accel.init();
p.SYST.set_clock_source(SystClkSource::Core);
p.SYST.set_reload(48_000_000);
p.SYST.enable_interrupt();
p.SYST.enable_counter();
}
fn idle() ->! {
rtfm::set_pending(Interrupt::EXTI0);
loop {
rtfm::wfi();
}
}
fn tick(_t: &mut Threshold, r: SYS_TICK::Resources) {
**r.TICKS += 1;
}
fn update_ui(_t: &mut Threshold, r: EXTI0::Resources) {
let i2c1 = &**r.I2C1;
let oled = SSD1306(OLED_ADDR, &i2c1);
let am = MMA8652FC(&i2c1);
r.STATE.update_accel(am.accel());
r.STATE.update_state();
oled.print(0, 0, "X ");
oled.print(8, 0, "Y ");
oled.print(0, 1, "Z ");
let accel = r.STATE.get_accel();
oled.print_number(2, 0, accel.x);
oled.print_number(10, 0, accel.y);
oled.print_number(2, 1, accel.z);
/*
match r.STATE.current_state() {
State::Idle => {
oled.print(0, 0, " IDLE ");
oled.print(0, 1, " ");
}
State::Soldering => {
oled.print(0, 0, " SOLDERING ");
oled.print(0, 1, " ");
}
State::Cooling => {
oled.print(0, 0, " COOLING ");
oled.print(0, 1, " ");
}
State::Sleep => {
oled.print(0, 0, " zZzZzZ ");
oled.print(0, 1, " ");
}
State::TemperatureControl => {
oled.print(0, 0, " < 200 C > ");
}
State::Thermometer => {
oled.print(0, 0, " 200.1 C ");
}
State::Config(page) => {
match page {
ConfigPage::Save => {
oled.print(0, 0, "Save and Reset? ");
}
}
}
}
*/
}
fn exti9_5(_t: &mut Threshold, r: EXTI9_5::Resources) {
let exti = &**r.EXTI;
let gpioa = &**r.GPIOA;
let gpiob = &**r.GPIOB;
let i2c1 = &**r.I2C1;
// Button A
if exti.pr.read().pr6().bit_is_set() {
if gpioa.idr.read().idr6().bit_is_clear() {
r.STATE.update_keys(Keys::A);
} else | ;
exti.pr.write(|w| w.pr6().set_bit());
// Button B
} else if exti.pr.read().pr9().bit_is_set() {
if gpioa.idr.read().idr9().bit_is_clear() {
r.STATE.update_keys(Keys::B)
} else {
r.STATE.update_keys(Keys::None)
};
exti.pr.write(|w| w.pr9().set_bit());
// Movement
// interrupt doesn't fire
} else if exti.pr.read().pr5().bit_is_set() {
if gpiob.idr.read().idr5().bit_is_clear() {
let am = MMA8652FC(&i2c1);
r.STATE.update_accel(am.accel());
}
exti.pr.write(|w| w.pr5().set_bit());
}
rtfm::set_pending(Interrupt::EXTI0);
}
| {
r.STATE.update_keys(Keys::None);
} | conditional_block |
main.rs | #![feature(asm)]
#![feature(const_fn)]
#![feature(proc_macro)]
#![no_std]
extern crate cast;
extern crate cortex_m;
extern crate cortex_m_rtfm as rtfm;
extern crate blue_pill;
extern crate numtoa;
use blue_pill::stm32f103xx::Interrupt;
use cortex_m::peripheral::SystClkSource;
use rtfm::{app, Threshold};
mod font5x7;
mod i2c;
mod mma8652fc;
mod ssd1306;
mod state;
use mma8652fc::MMA8652FC;
use ssd1306::SSD1306;
use state::{ConfigPage, Keys, State, StateMachine};
const OLED_ADDR: u8 = 0x3c;
app! {
device: blue_pill::stm32f103xx,
resources: {
static TICKS: u32 = 0;
static STATE: StateMachine = StateMachine::new();
},
tasks: {
SYS_TICK: {
path: tick,
resources: [TICKS],
},
EXTI0: {
path: update_ui,
resources: [I2C1, STATE],
},
EXTI9_5: {
path: exti9_5,
resources: [I2C1, STATE, GPIOA, GPIOB, EXTI],
},
},
}
fn init(p: init::Peripherals, _r: init::Resources) |
p.RCC.apb1enr.modify(|_, w| w.i2c1en().enabled());
p.I2C1.cr1.write(|w| w.pe().clear_bit());
p.GPIOA.crl.modify(|_, w| w.mode6().input());
p.GPIOA.crh.modify(|_, w| {
w.mode8().output50().cnf8().push().mode9().input()
});
p.GPIOA.bsrr.write(|w| {
w.bs6().set_bit().bs8().set_bit().bs9().set_bit()
});
p.GPIOB.crl.modify(|_, w| {
w.mode5()
.input()
.mode6()
.output50()
.cnf6()
.alt_open()
.mode7()
.output50()
.cnf7()
.alt_open()
});
p.GPIOB.bsrr.write(|w| w.bs5().set_bit());
p.AFIO.exticr2.modify(|_, w| unsafe {
w.exti5().bits(1).exti6().bits(0)
});
p.AFIO.exticr3.modify(|_, w| unsafe { w.exti9().bits(0) });
p.EXTI.imr.modify(|_, w| {
w.mr5().set_bit().mr6().set_bit().mr9().set_bit()
});
p.EXTI.rtsr.modify(|_, w| {
w.tr5().set_bit().tr6().set_bit().tr9().set_bit()
});
p.EXTI.ftsr.modify(|_, w| {
w.tr5().set_bit().tr6().set_bit().tr9().set_bit()
});
p.I2C1.cr2.modify(|_, w| unsafe { w.freq().bits(24) });
p.I2C1.cr1.modify(|_, w| w.pe().clear_bit());
p.I2C1.trise.modify(
|_, w| unsafe { w.trise().bits(24 + 1) },
);
p.I2C1.ccr.modify(|_, w| unsafe {
w.f_s().clear_bit().duty().clear_bit().ccr().bits(120)
});
p.I2C1.cr1.modify(|_, w| {
w.nostretch()
.clear_bit()
.ack()
.set_bit()
.smbus()
.clear_bit()
});
p.I2C1.cr1.write(|w| w.pe().set_bit());
p.I2C1.oar1.write(|w| unsafe {
w.addmode()
.clear_bit()
.add0()
.clear_bit()
.add7()
.bits(0)
.add10()
.bits(0)
});
let oled = SSD1306(OLED_ADDR, &p.I2C1);
oled.init();
oled.print(0, 0, " ");
oled.print(0, 1, " ");
let accel = MMA8652FC(&p.I2C1);
accel.init();
p.SYST.set_clock_source(SystClkSource::Core);
p.SYST.set_reload(48_000_000);
p.SYST.enable_interrupt();
p.SYST.enable_counter();
}
fn idle() ->! {
rtfm::set_pending(Interrupt::EXTI0);
loop {
rtfm::wfi();
}
}
fn tick(_t: &mut Threshold, r: SYS_TICK::Resources) {
**r.TICKS += 1;
}
fn update_ui(_t: &mut Threshold, r: EXTI0::Resources) {
let i2c1 = &**r.I2C1;
let oled = SSD1306(OLED_ADDR, &i2c1);
let am = MMA8652FC(&i2c1);
r.STATE.update_accel(am.accel());
r.STATE.update_state();
oled.print(0, 0, "X ");
oled.print(8, 0, "Y ");
oled.print(0, 1, "Z ");
let accel = r.STATE.get_accel();
oled.print_number(2, 0, accel.x);
oled.print_number(10, 0, accel.y);
oled.print_number(2, 1, accel.z);
/*
match r.STATE.current_state() {
State::Idle => {
oled.print(0, 0, " IDLE ");
oled.print(0, 1, " ");
}
State::Soldering => {
oled.print(0, 0, " SOLDERING ");
oled.print(0, 1, " ");
}
State::Cooling => {
oled.print(0, 0, " COOLING ");
oled.print(0, 1, " ");
}
State::Sleep => {
oled.print(0, 0, " zZzZzZ ");
oled.print(0, 1, " ");
}
State::TemperatureControl => {
oled.print(0, 0, " < 200 C > ");
}
State::Thermometer => {
oled.print(0, 0, " 200.1 C ");
}
State::Config(page) => {
match page {
ConfigPage::Save => {
oled.print(0, 0, "Save and Reset? ");
}
}
}
}
*/
}
fn exti9_5(_t: &mut Threshold, r: EXTI9_5::Resources) {
let exti = &**r.EXTI;
let gpioa = &**r.GPIOA;
let gpiob = &**r.GPIOB;
let i2c1 = &**r.I2C1;
// Button A
if exti.pr.read().pr6().bit_is_set() {
if gpioa.idr.read().idr6().bit_is_clear() {
r.STATE.update_keys(Keys::A);
} else {
r.STATE.update_keys(Keys::None);
};
exti.pr.write(|w| w.pr6().set_bit());
// Button B
} else if exti.pr.read().pr9().bit_is_set() {
if gpioa.idr.read().idr9().bit_is_clear() {
r.STATE.update_keys(Keys::B)
} else {
r.STATE.update_keys(Keys::None)
};
exti.pr.write(|w| w.pr9().set_bit());
// Movement
// interrupt doesn't fire
} else if exti.pr.read().pr5().bit_is_set() {
if gpiob.idr.read().idr5().bit_is_clear() {
let am = MMA8652FC(&i2c1);
r.STATE.update_accel(am.accel());
}
exti.pr.write(|w| w.pr5().set_bit());
}
rtfm::set_pending(Interrupt::EXTI0);
}
| {
// 48Mhz
p.FLASH.acr.modify(
|_, w| w.prftbe().enabled().latency().one(),
);
p.RCC.cfgr.modify(|_, w| unsafe { w.bits(0x0068840A) });
p.RCC.cr.modify(
|_, w| w.pllon().set_bit().hsion().set_bit(),
);
while p.RCC.cr.read().pllrdy().bit_is_clear() {}
while p.RCC.cr.read().hsirdy().bit_is_clear() {}
p.RCC.apb2enr.modify(|_, w| {
w.iopaen().enabled().iopben().enabled().afioen().enabled()
});
p.AFIO.mapr.modify(|_, w| unsafe {
w.swj_cfg().bits(2).i2c1_remap().clear_bit()
}); | identifier_body |
packet_kind.rs | /*
Copyright © 2016 Zetok Zalbavar <[email protected]>
This file is part of Tox.
| Tox 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 Tox. If not, see <http://www.gnu.org/licenses/>.
*/
/*! Data associated with the `PacketKind`. Used by most of other `toxcore`
modules.
Used by:
* [`dht`](../dht/index.html)
*/
use nom::le_u8;
use toxcore::binary_io::*;
/** Top-level packet kind names and their associated numbers.
According to https://zetok.github.io/tox-spec.html#packet-kind.
*/
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PacketKind {
/// [`Ping`](./struct.Ping.html) request number.
PingReq = 0,
/// [`Ping`](./struct.Ping.html) response number.
PingResp = 1,
/// [`GetNodes`](./struct.GetNodes.html) packet number.
GetN = 2,
/// [`SendNodes`](./struct.SendNodes.html) packet number.
SendN = 4,
/// Cookie Request.
CookieReq = 24,
/// Cookie Response.
CookieResp = 25,
/// Crypto Handshake.
CryptoHs = 26,
/// Crypto Data (general purpose packet for transporting encrypted data).
CryptoData = 27,
/// DHT Request.
DhtReq = 32,
/// LAN Discovery.
LanDisc = 33,
/// Onion Reuqest 0.
OnionReq0 = 128,
/// Onion Request 1.
OnionReq1 = 129,
/// Onion Request 2.
OnionReq2 = 130,
/// Announce Request.
AnnReq = 131,
/// Announce Response.
AnnResp = 132,
/// Onion Data Request.
OnionDataReq = 133,
/// Onion Data Response.
OnionDataResp = 134,
/// Onion Response 3.
OnionResp3 = 140,
/// Onion Response 2.
OnionResp2 = 141,
/// Onion Response 1.
OnionResp1 = 142,
}
/** Parse first byte from provided `bytes` as `PacketKind`.
Returns `None` if no bytes provided, or first byte doesn't match.
*/
from_bytes!(PacketKind, switch!(le_u8,
0 => value!(PacketKind::PingReq) |
1 => value!(PacketKind::PingResp) |
2 => value!(PacketKind::GetN) |
4 => value!(PacketKind::SendN) |
24 => value!(PacketKind::CookieReq) |
25 => value!(PacketKind::CookieResp) |
26 => value!(PacketKind::CryptoHs) |
27 => value!(PacketKind::CryptoData) |
32 => value!(PacketKind::DhtReq) |
33 => value!(PacketKind::LanDisc) |
128 => value!(PacketKind::OnionReq0) |
129 => value!(PacketKind::OnionReq1) |
130 => value!(PacketKind::OnionReq2) |
131 => value!(PacketKind::AnnReq) |
132 => value!(PacketKind::AnnResp) |
133 => value!(PacketKind::OnionDataReq) |
134 => value!(PacketKind::OnionDataResp) |
140 => value!(PacketKind::OnionResp3) |
141 => value!(PacketKind::OnionResp2) |
142 => value!(PacketKind::OnionResp1)
)); | Tox is libre 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.
| random_line_split |
packet_kind.rs | /*
Copyright © 2016 Zetok Zalbavar <[email protected]>
This file is part of Tox.
Tox is libre 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.
Tox 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 Tox. If not, see <http://www.gnu.org/licenses/>.
*/
/*! Data associated with the `PacketKind`. Used by most of other `toxcore`
modules.
Used by:
* [`dht`](../dht/index.html)
*/
use nom::le_u8;
use toxcore::binary_io::*;
/** Top-level packet kind names and their associated numbers.
According to https://zetok.github.io/tox-spec.html#packet-kind.
*/
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum P | {
/// [`Ping`](./struct.Ping.html) request number.
PingReq = 0,
/// [`Ping`](./struct.Ping.html) response number.
PingResp = 1,
/// [`GetNodes`](./struct.GetNodes.html) packet number.
GetN = 2,
/// [`SendNodes`](./struct.SendNodes.html) packet number.
SendN = 4,
/// Cookie Request.
CookieReq = 24,
/// Cookie Response.
CookieResp = 25,
/// Crypto Handshake.
CryptoHs = 26,
/// Crypto Data (general purpose packet for transporting encrypted data).
CryptoData = 27,
/// DHT Request.
DhtReq = 32,
/// LAN Discovery.
LanDisc = 33,
/// Onion Reuqest 0.
OnionReq0 = 128,
/// Onion Request 1.
OnionReq1 = 129,
/// Onion Request 2.
OnionReq2 = 130,
/// Announce Request.
AnnReq = 131,
/// Announce Response.
AnnResp = 132,
/// Onion Data Request.
OnionDataReq = 133,
/// Onion Data Response.
OnionDataResp = 134,
/// Onion Response 3.
OnionResp3 = 140,
/// Onion Response 2.
OnionResp2 = 141,
/// Onion Response 1.
OnionResp1 = 142,
}
/** Parse first byte from provided `bytes` as `PacketKind`.
Returns `None` if no bytes provided, or first byte doesn't match.
*/
from_bytes!(PacketKind, switch!(le_u8,
0 => value!(PacketKind::PingReq) |
1 => value!(PacketKind::PingResp) |
2 => value!(PacketKind::GetN) |
4 => value!(PacketKind::SendN) |
24 => value!(PacketKind::CookieReq) |
25 => value!(PacketKind::CookieResp) |
26 => value!(PacketKind::CryptoHs) |
27 => value!(PacketKind::CryptoData) |
32 => value!(PacketKind::DhtReq) |
33 => value!(PacketKind::LanDisc) |
128 => value!(PacketKind::OnionReq0) |
129 => value!(PacketKind::OnionReq1) |
130 => value!(PacketKind::OnionReq2) |
131 => value!(PacketKind::AnnReq) |
132 => value!(PacketKind::AnnResp) |
133 => value!(PacketKind::OnionDataReq) |
134 => value!(PacketKind::OnionDataResp) |
140 => value!(PacketKind::OnionResp3) |
141 => value!(PacketKind::OnionResp2) |
142 => value!(PacketKind::OnionResp1)
));
| acketKind | identifier_name |
instr_subsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn subsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 213], OperandSize::Dword)
}
#[test]
fn subsd_2() {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectScaledIndexed(EBX, EDI, Eight, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 36, 251], OperandSize::Dword)
}
#[test]
fn subsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 196], OperandSize::Qword)
}
#[test]
fn subsd_4() | {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectDisplaced(RBX, 212302300, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 163, 220, 121, 167, 12], OperandSize::Qword)
} | identifier_body |
|
instr_subsd.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;
#[test]
fn subsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 213], OperandSize::Dword)
}
#[test]
fn subsd_2() {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectScaledIndexed(EBX, EDI, Eight, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 36, 251], OperandSize::Dword)
}
#[test]
fn subsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 196], OperandSize::Qword)
}
#[test]
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectDisplaced(RBX, 212302300, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 163, 220, 121, 167, 12], OperandSize::Qword)
}
| subsd_4 | identifier_name |
instr_subsd.rs | use ::RegScale::*;
use ::test::run_test;
#[test]
fn subsd_1() {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM2)), operand2: Some(Direct(XMM5)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 213], OperandSize::Dword)
}
#[test]
fn subsd_2() {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectScaledIndexed(EBX, EDI, Eight, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 36, 251], OperandSize::Dword)
}
#[test]
fn subsd_3() {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM4)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 196], OperandSize::Qword)
}
#[test]
fn subsd_4() {
run_test(&Instruction { mnemonic: Mnemonic::SUBSD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectDisplaced(RBX, 212302300, Some(OperandSize::Qword), None)), operand3: None, operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[242, 15, 92, 163, 220, 121, 167, 12], OperandSize::Qword)
} | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*; | random_line_split |
|
opeq.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.
// -*- rust -*-
pub fn main() | {
let mut x: int = 1;
x *= 2;
debug!(x);
assert_eq!(x, 2);
x += 3;
debug!(x);
assert_eq!(x, 5);
x *= x;
debug!(x);
assert_eq!(x, 25);
x /= 5;
debug!(x);
assert_eq!(x, 5);
} | identifier_body |
|
opeq.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.
// -*- rust -*-
pub fn | () {
let mut x: int = 1;
x *= 2;
debug!(x);
assert_eq!(x, 2);
x += 3;
debug!(x);
assert_eq!(x, 5);
x *= x;
debug!(x);
assert_eq!(x, 25);
x /= 5;
debug!(x);
assert_eq!(x, 5);
}
| main | identifier_name |
opeq.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.
// -*- rust -*-
pub fn main() {
let mut x: int = 1;
x *= 2;
debug!(x);
assert_eq!(x, 2);
x += 3;
debug!(x);
assert_eq!(x, 5);
x *= x;
debug!(x);
assert_eq!(x, 25); | } | x /= 5;
debug!(x);
assert_eq!(x, 5); | random_line_split |
dst-bad-coerce4.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.
// Attempt to coerce from unsized to sized.
#![feature(unsized_tuple_coercion)]
struct Fat<T:?Sized> { | pub fn main() {
// With a vec of isizes.
let f1: &Fat<[isize]> = &Fat { ptr: [1, 2, 3] };
let f2: &Fat<[isize; 3]> = f1;
//~^ ERROR mismatched types
//~| expected type `&Fat<[isize; 3]>`
//~| found type `&Fat<[isize]>`
//~| expected array of 3 elements, found slice
// Tuple with a vec of isizes.
let f1: &([isize],) = &([1, 2, 3],);
let f2: &([isize; 3],) = f1;
//~^ ERROR mismatched types
//~| expected type `&([isize; 3],)`
//~| found type `&([isize],)`
//~| expected array of 3 elements, found slice
} | ptr: T
}
| random_line_split |
dst-bad-coerce4.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.
// Attempt to coerce from unsized to sized.
#![feature(unsized_tuple_coercion)]
struct Fat<T:?Sized> {
ptr: T
}
pub fn | () {
// With a vec of isizes.
let f1: &Fat<[isize]> = &Fat { ptr: [1, 2, 3] };
let f2: &Fat<[isize; 3]> = f1;
//~^ ERROR mismatched types
//~| expected type `&Fat<[isize; 3]>`
//~| found type `&Fat<[isize]>`
//~| expected array of 3 elements, found slice
// Tuple with a vec of isizes.
let f1: &([isize],) = &([1, 2, 3],);
let f2: &([isize; 3],) = f1;
//~^ ERROR mismatched types
//~| expected type `&([isize; 3],)`
//~| found type `&([isize],)`
//~| expected array of 3 elements, found slice
}
| main | identifier_name |
dst-bad-coerce4.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.
// Attempt to coerce from unsized to sized.
#![feature(unsized_tuple_coercion)]
struct Fat<T:?Sized> {
ptr: T
}
pub fn main() | {
// With a vec of isizes.
let f1: &Fat<[isize]> = &Fat { ptr: [1, 2, 3] };
let f2: &Fat<[isize; 3]> = f1;
//~^ ERROR mismatched types
//~| expected type `&Fat<[isize; 3]>`
//~| found type `&Fat<[isize]>`
//~| expected array of 3 elements, found slice
// Tuple with a vec of isizes.
let f1: &([isize],) = &([1, 2, 3],);
let f2: &([isize; 3],) = f1;
//~^ ERROR mismatched types
//~| expected type `&([isize; 3],)`
//~| found type `&([isize],)`
//~| expected array of 3 elements, found slice
} | identifier_body |
|
mod.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.
/*!
Module that constructs a control-flow graph representing an item.
Uses `Graph` as the underlying representation.
*/
#![allow(dead_code)] // still a WIP, #6298
use middle::graph;
use middle::ty;
use syntax::ast;
use util::nodemap::NodeMap;
mod construct;
pub mod graphviz;
pub struct CFG {
pub exit_map: NodeMap<CFGIndex>,
pub graph: CFGGraph,
pub entry: CFGIndex,
pub exit: CFGIndex,
}
pub struct CFGNodeData {
pub id: ast::NodeId
}
pub struct CFGEdgeData {
pub exiting_scopes: Vec<ast::NodeId>
}
pub type CFGIndex = graph::NodeIndex;
pub type CFGGraph = graph::Graph<CFGNodeData, CFGEdgeData>;
pub type CFGNode = graph::Node<CFGNodeData>;
pub type CFGEdge = graph::Edge<CFGEdgeData>;
pub struct | {
entry: CFGIndex,
exit: CFGIndex,
}
impl CFG {
pub fn new(tcx: &ty::ctxt,
blk: &ast::Block) -> CFG {
construct::construct(tcx, blk)
}
}
| CFGIndices | identifier_name |
mod.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.
/*!
Module that constructs a control-flow graph representing an item.
Uses `Graph` as the underlying representation. |
*/
#![allow(dead_code)] // still a WIP, #6298
use middle::graph;
use middle::ty;
use syntax::ast;
use util::nodemap::NodeMap;
mod construct;
pub mod graphviz;
pub struct CFG {
pub exit_map: NodeMap<CFGIndex>,
pub graph: CFGGraph,
pub entry: CFGIndex,
pub exit: CFGIndex,
}
pub struct CFGNodeData {
pub id: ast::NodeId
}
pub struct CFGEdgeData {
pub exiting_scopes: Vec<ast::NodeId>
}
pub type CFGIndex = graph::NodeIndex;
pub type CFGGraph = graph::Graph<CFGNodeData, CFGEdgeData>;
pub type CFGNode = graph::Node<CFGNodeData>;
pub type CFGEdge = graph::Edge<CFGEdgeData>;
pub struct CFGIndices {
entry: CFGIndex,
exit: CFGIndex,
}
impl CFG {
pub fn new(tcx: &ty::ctxt,
blk: &ast::Block) -> CFG {
construct::construct(tcx, blk)
}
} | random_line_split |
|
create_changeset.rs |
impl CreateCopyInfo {
pub fn new(path: MononokePath, parent_index: usize) -> Self {
CreateCopyInfo { path, parent_index }
}
async fn resolve(
self,
parents: &Vec<ChangesetContext>,
) -> Result<(MPath, ChangesetId), MononokeError> {
let parent_ctx = parents.get(self.parent_index).ok_or_else(|| {
MononokeError::InvalidRequest(format!(
"Parent index '{}' out of range for commit with {} parent(s)",
self.parent_index,
parents.len()
))
})?;
if!parent_ctx
.path_with_content(self.path.clone())?
.is_file()
.await?
{
return Err(MononokeError::InvalidRequest(String::from(
"Copy-from path must reference a file",
)));
}
let mpath = self.path.into_mpath().ok_or_else(|| {
MononokeError::InvalidRequest(String::from("Copy-from path cannot be the root"))
})?;
Ok((mpath, parent_ctx.id()))
}
}
/// Description of a change to make to a file.
#[derive(Clone)]
pub enum CreateChange {
/// The file is created or modified to contain new data.
Tracked(CreateChangeFile, Option<CreateCopyInfo>),
/// A new file is modified in the working copy
Untracked(CreateChangeFile),
/// The file is not present in the working copy
UntrackedDeletion,
/// The file is marked as deleted
Deletion,
}
#[derive(Clone)]
pub enum CreateChangeFile {
// Upload content from bytes
New {
bytes: Bytes,
file_type: FileType,
},
// Use already uploaded content
Existing {
file_id: FileId,
file_type: FileType,
// If not present, will be fetched from the blobstore
maybe_size: Option<u64>,
},
}
// Enum for recording whether a path is not changed, changed or deleted.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum CreateChangeType {
None,
Change,
Deletion,
}
impl Default for CreateChangeType {
fn default() -> Self {
CreateChangeType::None
}
}
impl CreateChange {
pub async fn resolve(
self,
ctx: &CoreContext,
filestore_config: FilestoreConfig,
repo_blobstore: RepoBlobstore,
parents: &Vec<ChangesetContext>,
) -> Result<FileChange, MononokeError> {
let (file, copy_info, tracked) = match self {
CreateChange::Tracked(file, copy_info) => (
file,
match copy_info {
Some(copy_info) => Some(copy_info.resolve(parents).await?),
None => None,
},
true,
),
CreateChange::Untracked(file) => (file, None, false),
CreateChange::UntrackedDeletion => return Ok(FileChange::UntrackedDeletion),
CreateChange::Deletion => return Ok(FileChange::Deletion),
};
let (file_id, file_type, size) = match file {
CreateChangeFile::New { bytes, file_type } => {
let meta = filestore::store(
&repo_blobstore,
filestore_config,
&ctx,
&StoreRequest::new(bytes.len() as u64),
stream::once(async move { Ok(bytes) }),
)
.await?;
(meta.content_id, file_type, meta.total_size)
}
CreateChangeFile::Existing {
file_id,
file_type,
maybe_size,
} => (
file_id,
file_type,
match maybe_size {
Some(size) => size,
None => {
filestore::get_metadata(
&repo_blobstore,
&ctx,
&FetchKey::Canonical(file_id),
)
.await?
.ok_or_else(|| {
MononokeError::InvalidRequest(format!(
"File id '{}' is not available in this repo",
file_id
))
})?
.total_size
}
},
),
};
if tracked {
Ok(FileChange::tracked(file_id, file_type, size, copy_info))
} else {
Ok(FileChange::untracked(file_id, file_type, size))
}
}
fn change_type(&self) -> CreateChangeType {
match self {
CreateChange::Deletion | CreateChange::UntrackedDeletion => CreateChangeType::Deletion,
CreateChange::Tracked(..) | CreateChange::Untracked(..) => CreateChangeType::Change,
}
}
}
/// Verify that all deleted files existed in at least one of the parents.
async fn verify_deleted_files_existed_in_a_parent(
parent_ctxs: &[ChangesetContext],
deleted_files: BTreeSet<MononokePath>,
) -> Result<(), MononokeError> {
async fn get_matching_files<'a>(
parent_ctx: &'a ChangesetContext,
files: &'a BTreeSet<MononokePath>,
) -> Result<impl Stream<Item = Result<MononokePath, MononokeError>> + 'a, MononokeError> {
Ok(parent_ctx
.paths(files.iter().cloned())
.await?
.try_filter_map(|changeset_path| async move {
if changeset_path.is_file().await? {
Ok(Some(changeset_path.path().clone()))
} else {
Ok(None)
}
})
.boxed())
}
// Filter the deleted files to those that existed in a parent.
let parent_files: BTreeSet<_> = parent_ctxs
.iter()
.map(|parent_ctx| get_matching_files(parent_ctx, &deleted_files))
.collect::<FuturesUnordered<_>>()
.try_flatten()
.try_collect()
.await?;
// Quickly check if all deleted files existed by comparing set lengths.
if deleted_files.len() == parent_files.len() {
Ok(())
} else {
// At least one deleted file didn't exist. Find out which ones to
// give a good error message.
let non_existent_path = deleted_files
.difference(&parent_files)
.next()
.expect("at least one file did not exist");
let path_count = deleted_files.len().saturating_sub(parent_files.len());
if path_count == 1 {
Err(MononokeError::InvalidRequest(format!(
"Deleted file '{}' does not exist in any parent",
non_existent_path
)))
} else {
Err(MononokeError::InvalidRequest(format!(
"{} deleted files ('{}',...) do not exist in any parent",
path_count, non_existent_path
)))
}
}
}
/// Returns `true` if any prefix of the path has a change. Use for
/// detecting when a directory is replaced by a file.
fn is_prefix_changed(path: &MononokePath, paths: &PathTree<CreateChangeType>) -> bool {
path.prefixes()
.any(|prefix| paths.get(prefix.as_mpath()) == Some(&CreateChangeType::Change))
}
/// Verify that any files in `prefix_paths` that exist in `parent_ctx` have
/// been marked as deleted in `path_changes`.
async fn verify_prefix_files_deleted(
parent_ctx: &ChangesetContext,
prefix_paths: &BTreeSet<MononokePath>,
path_changes: &PathTree<CreateChangeType>,
) -> Result<(), MononokeError> {
parent_ctx
.paths(prefix_paths.iter().cloned())
.await?
.try_for_each(|prefix_path| async move {
if prefix_path.is_file().await?
&& path_changes.get(prefix_path.path().as_mpath())
!= Some(&CreateChangeType::Deletion)
{
Err(MononokeError::InvalidRequest(format!(
"Creating files inside '{}' requires deleting the file at that path",
prefix_path.path()
)))
} else {
Ok(())
}
})
.await
}
impl RepoContext {
async fn save_changeset(
&self,
changeset: BonsaiChangeset,
container: &(impl ChangesetsRef + RepoBlobstoreRef + RepoIdentityRef),
bubble: Option<&Bubble>,
) -> Result<(), MononokeError> {
blobrepo::save_bonsai_changesets(vec![changeset.clone()], self.ctx().clone(), container)
.await?;
if let Some(category) = self.config().infinitepush.commit_scribe_category.as_deref() {
blobrepo::scribe::log_commit_to_scribe(
self.ctx(),
category,
container,
&changeset,
bubble.map(|x| x.bubble_id()),
)
.await;
}
Ok(())
}
// TODO(T105334556): This should require draft_write permission
/// Create a new changeset in the repository.
///
/// The new changeset is created with the given metadata by unioning the
/// contents of all parent changesets and then applying the provided
/// changes on top.
///
/// Note that:
/// - The changes must be internally consistent (there must be no path
/// conflicts between changed files).
/// - If a file in any parent changeset is being replaced by a directory
/// then that file must be deleted in the set of changes.
/// - If a directory in any parent changeset is being replaced by a file,
/// then the contents of the parent directory do not need to be deleted.
/// If deletions for the contents of the directory are included they will
/// be checked for correctness (the files must exist), but they will
/// otherwise be ignored.
/// - Any merge conflicts introduced by merging the parent changesets
/// must be resolved by a corresponding change in the set of changes.
///
/// Currenly only a single parent is supported, and root changesets (changesets
/// with no parents) cannot be created.
pub async fn create_changeset(
&self,
parents: Vec<ChangesetId>,
author: String,
author_date: DateTime<FixedOffset>,
committer: Option<String>,
committer_date: Option<DateTime<FixedOffset>>,
message: String,
extra: BTreeMap<String, Vec<u8>>,
changes: BTreeMap<MononokePath, CreateChange>,
// If some, this changeset is a snapshot. Currently unsupported to upload a
// normal commit to a bubble, though can be easily added.
bubble: Option<&Bubble>,
) -> Result<ChangesetContext, MononokeError> | .ok_or_else(|| {
MononokeError::InvalidRequest(format!(
"Parent {} does not exist",
parent_id
))
})?;
Ok::<_, MononokeError>(parent_ctx)
})
.collect::<FuturesOrdered<_>>()
.try_collect()
.await?;
// Check that changes are valid according to bonsai rules:
// (1) deletions and copy-from info must reference a real path in a
// valid parent.
// (2) deletions for paths where a prefix directory has been replaced
// by a file should be dropped, as the deletion is implicit from the
// file change for the prefix path.
// (3) conversely, when a file has been replaced by a directory, there
// must be a delete for the file.
//
// Extract the set of deleted files.
let tracked_deletion_files: BTreeSet<_> = changes
.iter()
.filter(|(_path, change)| matches!(change, CreateChange::Deletion))
.map(|(path, _change)| path.clone())
.collect();
// Check deleted files existed in a parent. (1)
let fut_verify_deleted_files_existed = async {
// This does NOT consider "missing" (untracked deletion) files as it is NOT
// necessary for them to exist in a parent. If they don't exist on a parent,
// this means the file was "hg added" and then manually deleted.
let (stats, result) =
verify_deleted_files_existed_in_a_parent(&parent_ctxs, tracked_deletion_files)
.timed()
.await;
let mut scuba = self.ctx().scuba().clone();
scuba.add_future_stats(&stats);
scuba.log_with_msg("Verify deleted files existed in a parent", None);
result
};
// Build a path tree recording each path that has been created or deleted.
let path_changes = PathTree::from_iter(
changes
.iter()
.map(|(path, change)| (path.as_mpath().cloned(), change.change_type())),
);
// Determine the prefixes of all changed files.
let prefix_paths: BTreeSet<_> = changes
.iter()
.filter(|(_path, change)| change.change_type() == CreateChangeType::Change)
.map(|(path, _change)| path.clone().prefixes())
.flatten()
.collect();
// Check changes that replace a file with a directory also delete
// this replaced file. (3)
let fut_verify_prefix_files_deleted = async {
let (stats, result) = parent_ctxs
.iter()
.map(|parent_ctx| {
verify_prefix_files_deleted(parent_ctx, &prefix_paths, &path_changes)
})
.collect::<FuturesUnordered<_>>()
.try_for_each(|_| async { Ok(()) })
.timed()
.await;
let mut scuba = self.ctx().scuba().clone();
scuba.add_future_stats(&stats);
scuba.log_with_msg("Verify prefix files in parents have been deleted", None);
result
};
// Convert change paths into the form needed for the bonsai changeset.
let changes: Vec<(MPath, CreateChange)> = changes
.into_iter()
// Filter deletions that have a change at a path prefix. The
// deletion is implicit from the change. (2)
.filter(|(path, change)| {
change.change_type()!= CreateChangeType::Deletion
||!is_prefix_changed(path, &path_changes)
})
// Then convert the paths to MPaths. Do this before we start
// resolving any changes, so that we don't start storing data
// until we're happy that the changes are valid.
.map(|(path, change)| {
path.into_mpath()
.ok_or_else(|| {
MononokeError::InvalidRequest(String::from(
"Cannot create a file with an empty path",
))
})
.map(move |mpath| (mpath, change))
})
.collect::<Result<_, _>>()?;
// Resolve the changes into bonsai changes. This also checks (1) for
// copy-from info.
let file_changes_fut = async {
let (stats, result) = changes
.into_iter()
.map(|(path, change)| {
let parent_ctxs = &parent_ctxs;
async move {
let change = change
.resolve(
self.ctx(),
self.blob_repo().filestore_config(),
match &bubble {
Some(bubble) => bubble
.wrap_repo_blobstore(self.blob_repo().blobstore().clone()),
None => self.blob_repo().blobstore().clone(),
},
&parent_ctxs,
)
.await?;
Ok::<_, MononokeError>((path, change))
}
})
.collect::<FuturesUnordered<_>>()
.try_collect::<SortedVectorMap<MPath, FileChange>>()
.timed()
.await;
let mut scuba = self.ctx().scuba(). | {
let allowed_no_parents = self
.config()
.source_control_service
.permit_commits_without_parents;
let valid_parent_count = parents.len() == 1 || (parents.len() == 0 && allowed_no_parents);
// Merge rules are not validated yet, so only a single parent is supported.
if !valid_parent_count {
return Err(MononokeError::InvalidRequest(String::from(
"Merge changesets cannot be created",
)));
}
// Obtain contexts for each of the parents (which should exist).
let parent_ctxs: Vec<_> = parents
.iter()
.map(|parent_id| async move {
let parent_ctx = self
.changeset(ChangesetSpecifier::Bonsai(parent_id.clone()))
.await? | identifier_body |
create_changeset.rs |
impl CreateCopyInfo {
pub fn new(path: MononokePath, parent_index: usize) -> Self {
CreateCopyInfo { path, parent_index }
}
async fn resolve(
self,
parents: &Vec<ChangesetContext>,
) -> Result<(MPath, ChangesetId), MononokeError> {
let parent_ctx = parents.get(self.parent_index).ok_or_else(|| {
MononokeError::InvalidRequest(format!(
"Parent index '{}' out of range for commit with {} parent(s)",
self.parent_index,
parents.len()
))
})?;
if!parent_ctx
.path_with_content(self.path.clone())?
.is_file()
.await?
{
return Err(MononokeError::InvalidRequest(String::from(
"Copy-from path must reference a file",
)));
}
let mpath = self.path.into_mpath().ok_or_else(|| {
MononokeError::InvalidRequest(String::from("Copy-from path cannot be the root"))
})?;
Ok((mpath, parent_ctx.id()))
}
}
/// Description of a change to make to a file.
#[derive(Clone)]
pub enum CreateChange {
/// The file is created or modified to contain new data.
Tracked(CreateChangeFile, Option<CreateCopyInfo>),
/// A new file is modified in the working copy
Untracked(CreateChangeFile),
/// The file is not present in the working copy
UntrackedDeletion,
/// The file is marked as deleted
Deletion,
}
#[derive(Clone)]
pub enum CreateChangeFile {
// Upload content from bytes
New {
bytes: Bytes,
file_type: FileType,
},
// Use already uploaded content
Existing {
file_id: FileId,
file_type: FileType,
// If not present, will be fetched from the blobstore
maybe_size: Option<u64>,
},
}
// Enum for recording whether a path is not changed, changed or deleted.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum CreateChangeType {
None,
Change,
Deletion,
}
impl Default for CreateChangeType {
fn default() -> Self {
CreateChangeType::None
}
}
impl CreateChange {
pub async fn resolve(
self,
ctx: &CoreContext,
filestore_config: FilestoreConfig,
repo_blobstore: RepoBlobstore,
parents: &Vec<ChangesetContext>,
) -> Result<FileChange, MononokeError> {
let (file, copy_info, tracked) = match self {
CreateChange::Tracked(file, copy_info) => (
file,
match copy_info {
Some(copy_info) => Some(copy_info.resolve(parents).await?),
None => None,
},
true,
),
CreateChange::Untracked(file) => (file, None, false),
CreateChange::UntrackedDeletion => return Ok(FileChange::UntrackedDeletion),
CreateChange::Deletion => return Ok(FileChange::Deletion),
};
let (file_id, file_type, size) = match file {
CreateChangeFile::New { bytes, file_type } => {
let meta = filestore::store(
&repo_blobstore,
filestore_config,
&ctx,
&StoreRequest::new(bytes.len() as u64),
stream::once(async move { Ok(bytes) }),
)
.await?;
(meta.content_id, file_type, meta.total_size)
}
CreateChangeFile::Existing {
file_id,
file_type,
maybe_size,
} => (
file_id,
file_type,
match maybe_size {
Some(size) => size,
None => {
filestore::get_metadata(
&repo_blobstore,
&ctx,
&FetchKey::Canonical(file_id),
)
.await?
.ok_or_else(|| {
MononokeError::InvalidRequest(format!(
"File id '{}' is not available in this repo",
file_id
))
})?
.total_size
}
},
),
};
if tracked {
Ok(FileChange::tracked(file_id, file_type, size, copy_info))
} else {
Ok(FileChange::untracked(file_id, file_type, size))
}
}
fn change_type(&self) -> CreateChangeType {
match self {
CreateChange::Deletion | CreateChange::UntrackedDeletion => CreateChangeType::Deletion,
CreateChange::Tracked(..) | CreateChange::Untracked(..) => CreateChangeType::Change,
}
}
}
/// Verify that all deleted files existed in at least one of the parents.
async fn verify_deleted_files_existed_in_a_parent(
parent_ctxs: &[ChangesetContext],
deleted_files: BTreeSet<MononokePath>,
) -> Result<(), MononokeError> {
async fn get_matching_files<'a>(
parent_ctx: &'a ChangesetContext,
files: &'a BTreeSet<MononokePath>,
) -> Result<impl Stream<Item = Result<MononokePath, MononokeError>> + 'a, MononokeError> {
Ok(parent_ctx
.paths(files.iter().cloned())
.await?
.try_filter_map(|changeset_path| async move {
if changeset_path.is_file().await? {
Ok(Some(changeset_path.path().clone()))
} else {
Ok(None)
}
})
.boxed())
}
// Filter the deleted files to those that existed in a parent.
let parent_files: BTreeSet<_> = parent_ctxs
.iter()
.map(|parent_ctx| get_matching_files(parent_ctx, &deleted_files))
.collect::<FuturesUnordered<_>>()
.try_flatten()
.try_collect()
.await?;
// Quickly check if all deleted files existed by comparing set lengths.
if deleted_files.len() == parent_files.len() {
Ok(())
} else {
// At least one deleted file didn't exist. Find out which ones to
// give a good error message.
let non_existent_path = deleted_files
.difference(&parent_files)
.next()
.expect("at least one file did not exist");
let path_count = deleted_files.len().saturating_sub(parent_files.len());
if path_count == 1 {
Err(MononokeError::InvalidRequest(format!(
"Deleted file '{}' does not exist in any parent",
non_existent_path
)))
} else {
Err(MononokeError::InvalidRequest(format!(
"{} deleted files ('{}',...) do not exist in any parent",
path_count, non_existent_path
)))
}
}
}
/// Returns `true` if any prefix of the path has a change. Use for
/// detecting when a directory is replaced by a file.
fn is_prefix_changed(path: &MononokePath, paths: &PathTree<CreateChangeType>) -> bool {
path.prefixes()
.any(|prefix| paths.get(prefix.as_mpath()) == Some(&CreateChangeType::Change))
}
/// Verify that any files in `prefix_paths` that exist in `parent_ctx` have
/// been marked as deleted in `path_changes`.
async fn verify_prefix_files_deleted(
parent_ctx: &ChangesetContext,
prefix_paths: &BTreeSet<MononokePath>,
path_changes: &PathTree<CreateChangeType>,
) -> Result<(), MononokeError> {
parent_ctx
.paths(prefix_paths.iter().cloned())
.await?
.try_for_each(|prefix_path| async move {
if prefix_path.is_file().await?
&& path_changes.get(prefix_path.path().as_mpath())
!= Some(&CreateChangeType::Deletion)
{
Err(MononokeError::InvalidRequest(format!(
"Creating files inside '{}' requires deleting the file at that path",
prefix_path.path()
)))
} else {
Ok(())
}
})
.await
}
impl RepoContext {
async fn save_changeset(
&self,
changeset: BonsaiChangeset,
container: &(impl ChangesetsRef + RepoBlobstoreRef + RepoIdentityRef),
bubble: Option<&Bubble>,
) -> Result<(), MononokeError> {
blobrepo::save_bonsai_changesets(vec![changeset.clone()], self.ctx().clone(), container)
.await?;
if let Some(category) = self.config().infinitepush.commit_scribe_category.as_deref() {
blobrepo::scribe::log_commit_to_scribe(
self.ctx(),
category,
container,
&changeset,
bubble.map(|x| x.bubble_id()),
)
.await;
}
Ok(())
}
// TODO(T105334556): This should require draft_write permission
/// Create a new changeset in the repository.
///
/// The new changeset is created with the given metadata by unioning the
/// contents of all parent changesets and then applying the provided
/// changes on top.
///
/// Note that:
/// - The changes must be internally consistent (there must be no path
/// conflicts between changed files).
/// - If a file in any parent changeset is being replaced by a directory
/// then that file must be deleted in the set of changes.
/// - If a directory in any parent changeset is being replaced by a file,
/// then the contents of the parent directory do not need to be deleted.
/// If deletions for the contents of the directory are included they will
/// be checked for correctness (the files must exist), but they will
/// otherwise be ignored.
/// - Any merge conflicts introduced by merging the parent changesets
/// must be resolved by a corresponding change in the set of changes.
///
/// Currenly only a single parent is supported, and root changesets (changesets
/// with no parents) cannot be created.
pub async fn create_changeset(
&self,
parents: Vec<ChangesetId>,
author: String,
author_date: DateTime<FixedOffset>,
committer: Option<String>,
committer_date: Option<DateTime<FixedOffset>>,
message: String,
extra: BTreeMap<String, Vec<u8>>,
changes: BTreeMap<MononokePath, CreateChange>,
// If some, this changeset is a snapshot. Currently unsupported to upload a
// normal commit to a bubble, though can be easily added.
bubble: Option<&Bubble>,
) -> Result<ChangesetContext, MononokeError> {
let allowed_no_parents = self
.config()
.source_control_service
.permit_commits_without_parents;
let valid_parent_count = parents.len() == 1 || (parents.len() == 0 && allowed_no_parents);
// Merge rules are not validated yet, so only a single parent is supported.
if!valid_parent_count {
return Err(MononokeError::InvalidRequest(String::from(
"Merge changesets cannot be created",
)));
}
| let parent_ctxs: Vec<_> = parents
.iter()
.map(|parent_id| async move {
let parent_ctx = self
.changeset(ChangesetSpecifier::Bonsai(parent_id.clone()))
.await?
.ok_or_else(|| {
MononokeError::InvalidRequest(format!(
"Parent {} does not exist",
parent_id
))
})?;
Ok::<_, MononokeError>(parent_ctx)
})
.collect::<FuturesOrdered<_>>()
.try_collect()
.await?;
// Check that changes are valid according to bonsai rules:
// (1) deletions and copy-from info must reference a real path in a
// valid parent.
// (2) deletions for paths where a prefix directory has been replaced
// by a file should be dropped, as the deletion is implicit from the
// file change for the prefix path.
// (3) conversely, when a file has been replaced by a directory, there
// must be a delete for the file.
//
// Extract the set of deleted files.
let tracked_deletion_files: BTreeSet<_> = changes
.iter()
.filter(|(_path, change)| matches!(change, CreateChange::Deletion))
.map(|(path, _change)| path.clone())
.collect();
// Check deleted files existed in a parent. (1)
let fut_verify_deleted_files_existed = async {
// This does NOT consider "missing" (untracked deletion) files as it is NOT
// necessary for them to exist in a parent. If they don't exist on a parent,
// this means the file was "hg added" and then manually deleted.
let (stats, result) =
verify_deleted_files_existed_in_a_parent(&parent_ctxs, tracked_deletion_files)
.timed()
.await;
let mut scuba = self.ctx().scuba().clone();
scuba.add_future_stats(&stats);
scuba.log_with_msg("Verify deleted files existed in a parent", None);
result
};
// Build a path tree recording each path that has been created or deleted.
let path_changes = PathTree::from_iter(
changes
.iter()
.map(|(path, change)| (path.as_mpath().cloned(), change.change_type())),
);
// Determine the prefixes of all changed files.
let prefix_paths: BTreeSet<_> = changes
.iter()
.filter(|(_path, change)| change.change_type() == CreateChangeType::Change)
.map(|(path, _change)| path.clone().prefixes())
.flatten()
.collect();
// Check changes that replace a file with a directory also delete
// this replaced file. (3)
let fut_verify_prefix_files_deleted = async {
let (stats, result) = parent_ctxs
.iter()
.map(|parent_ctx| {
verify_prefix_files_deleted(parent_ctx, &prefix_paths, &path_changes)
})
.collect::<FuturesUnordered<_>>()
.try_for_each(|_| async { Ok(()) })
.timed()
.await;
let mut scuba = self.ctx().scuba().clone();
scuba.add_future_stats(&stats);
scuba.log_with_msg("Verify prefix files in parents have been deleted", None);
result
};
// Convert change paths into the form needed for the bonsai changeset.
let changes: Vec<(MPath, CreateChange)> = changes
.into_iter()
// Filter deletions that have a change at a path prefix. The
// deletion is implicit from the change. (2)
.filter(|(path, change)| {
change.change_type()!= CreateChangeType::Deletion
||!is_prefix_changed(path, &path_changes)
})
// Then convert the paths to MPaths. Do this before we start
// resolving any changes, so that we don't start storing data
// until we're happy that the changes are valid.
.map(|(path, change)| {
path.into_mpath()
.ok_or_else(|| {
MononokeError::InvalidRequest(String::from(
"Cannot create a file with an empty path",
))
})
.map(move |mpath| (mpath, change))
})
.collect::<Result<_, _>>()?;
// Resolve the changes into bonsai changes. This also checks (1) for
// copy-from info.
let file_changes_fut = async {
let (stats, result) = changes
.into_iter()
.map(|(path, change)| {
let parent_ctxs = &parent_ctxs;
async move {
let change = change
.resolve(
self.ctx(),
self.blob_repo().filestore_config(),
match &bubble {
Some(bubble) => bubble
.wrap_repo_blobstore(self.blob_repo().blobstore().clone()),
None => self.blob_repo().blobstore().clone(),
},
&parent_ctxs,
)
.await?;
Ok::<_, MononokeError>((path, change))
}
})
.collect::<FuturesUnordered<_>>()
.try_collect::<SortedVectorMap<MPath, FileChange>>()
.timed()
.await;
let mut scuba = self.ctx().scuba().clone | // Obtain contexts for each of the parents (which should exist). | random_line_split |
create_changeset.rs |
impl CreateCopyInfo {
pub fn new(path: MononokePath, parent_index: usize) -> Self {
CreateCopyInfo { path, parent_index }
}
async fn resolve(
self,
parents: &Vec<ChangesetContext>,
) -> Result<(MPath, ChangesetId), MononokeError> {
let parent_ctx = parents.get(self.parent_index).ok_or_else(|| {
MononokeError::InvalidRequest(format!(
"Parent index '{}' out of range for commit with {} parent(s)",
self.parent_index,
parents.len()
))
})?;
if!parent_ctx
.path_with_content(self.path.clone())?
.is_file()
.await?
{
return Err(MononokeError::InvalidRequest(String::from(
"Copy-from path must reference a file",
)));
}
let mpath = self.path.into_mpath().ok_or_else(|| {
MononokeError::InvalidRequest(String::from("Copy-from path cannot be the root"))
})?;
Ok((mpath, parent_ctx.id()))
}
}
/// Description of a change to make to a file.
#[derive(Clone)]
pub enum CreateChange {
/// The file is created or modified to contain new data.
Tracked(CreateChangeFile, Option<CreateCopyInfo>),
/// A new file is modified in the working copy
Untracked(CreateChangeFile),
/// The file is not present in the working copy
UntrackedDeletion,
/// The file is marked as deleted
Deletion,
}
#[derive(Clone)]
pub enum CreateChangeFile {
// Upload content from bytes
New {
bytes: Bytes,
file_type: FileType,
},
// Use already uploaded content
Existing {
file_id: FileId,
file_type: FileType,
// If not present, will be fetched from the blobstore
maybe_size: Option<u64>,
},
}
// Enum for recording whether a path is not changed, changed or deleted.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum CreateChangeType {
None,
Change,
Deletion,
}
impl Default for CreateChangeType {
fn default() -> Self {
CreateChangeType::None
}
}
impl CreateChange {
pub async fn resolve(
self,
ctx: &CoreContext,
filestore_config: FilestoreConfig,
repo_blobstore: RepoBlobstore,
parents: &Vec<ChangesetContext>,
) -> Result<FileChange, MononokeError> {
let (file, copy_info, tracked) = match self {
CreateChange::Tracked(file, copy_info) => (
file,
match copy_info {
Some(copy_info) => Some(copy_info.resolve(parents).await?),
None => None,
},
true,
),
CreateChange::Untracked(file) => (file, None, false),
CreateChange::UntrackedDeletion => return Ok(FileChange::UntrackedDeletion),
CreateChange::Deletion => return Ok(FileChange::Deletion),
};
let (file_id, file_type, size) = match file {
CreateChangeFile::New { bytes, file_type } => {
let meta = filestore::store(
&repo_blobstore,
filestore_config,
&ctx,
&StoreRequest::new(bytes.len() as u64),
stream::once(async move { Ok(bytes) }),
)
.await?;
(meta.content_id, file_type, meta.total_size)
}
CreateChangeFile::Existing {
file_id,
file_type,
maybe_size,
} => (
file_id,
file_type,
match maybe_size {
Some(size) => size,
None => {
filestore::get_metadata(
&repo_blobstore,
&ctx,
&FetchKey::Canonical(file_id),
)
.await?
.ok_or_else(|| {
MononokeError::InvalidRequest(format!(
"File id '{}' is not available in this repo",
file_id
))
})?
.total_size
}
},
),
};
if tracked {
Ok(FileChange::tracked(file_id, file_type, size, copy_info))
} else {
Ok(FileChange::untracked(file_id, file_type, size))
}
}
fn change_type(&self) -> CreateChangeType {
match self {
CreateChange::Deletion | CreateChange::UntrackedDeletion => CreateChangeType::Deletion,
CreateChange::Tracked(..) | CreateChange::Untracked(..) => CreateChangeType::Change,
}
}
}
/// Verify that all deleted files existed in at least one of the parents.
async fn verify_deleted_files_existed_in_a_parent(
parent_ctxs: &[ChangesetContext],
deleted_files: BTreeSet<MononokePath>,
) -> Result<(), MononokeError> {
async fn get_matching_files<'a>(
parent_ctx: &'a ChangesetContext,
files: &'a BTreeSet<MononokePath>,
) -> Result<impl Stream<Item = Result<MononokePath, MononokeError>> + 'a, MononokeError> {
Ok(parent_ctx
.paths(files.iter().cloned())
.await?
.try_filter_map(|changeset_path| async move {
if changeset_path.is_file().await? {
Ok(Some(changeset_path.path().clone()))
} else {
Ok(None)
}
})
.boxed())
}
// Filter the deleted files to those that existed in a parent.
let parent_files: BTreeSet<_> = parent_ctxs
.iter()
.map(|parent_ctx| get_matching_files(parent_ctx, &deleted_files))
.collect::<FuturesUnordered<_>>()
.try_flatten()
.try_collect()
.await?;
// Quickly check if all deleted files existed by comparing set lengths.
if deleted_files.len() == parent_files.len() {
Ok(())
} else {
// At least one deleted file didn't exist. Find out which ones to
// give a good error message.
let non_existent_path = deleted_files
.difference(&parent_files)
.next()
.expect("at least one file did not exist");
let path_count = deleted_files.len().saturating_sub(parent_files.len());
if path_count == 1 {
Err(MononokeError::InvalidRequest(format!(
"Deleted file '{}' does not exist in any parent",
non_existent_path
)))
} else {
Err(MononokeError::InvalidRequest(format!(
"{} deleted files ('{}',...) do not exist in any parent",
path_count, non_existent_path
)))
}
}
}
/// Returns `true` if any prefix of the path has a change. Use for
/// detecting when a directory is replaced by a file.
fn is_prefix_changed(path: &MononokePath, paths: &PathTree<CreateChangeType>) -> bool {
path.prefixes()
.any(|prefix| paths.get(prefix.as_mpath()) == Some(&CreateChangeType::Change))
}
/// Verify that any files in `prefix_paths` that exist in `parent_ctx` have
/// been marked as deleted in `path_changes`.
async fn verify_prefix_files_deleted(
parent_ctx: &ChangesetContext,
prefix_paths: &BTreeSet<MononokePath>,
path_changes: &PathTree<CreateChangeType>,
) -> Result<(), MononokeError> {
parent_ctx
.paths(prefix_paths.iter().cloned())
.await?
.try_for_each(|prefix_path| async move {
if prefix_path.is_file().await?
&& path_changes.get(prefix_path.path().as_mpath())
!= Some(&CreateChangeType::Deletion)
{
Err(MononokeError::InvalidRequest(format!(
"Creating files inside '{}' requires deleting the file at that path",
prefix_path.path()
)))
} else {
Ok(())
}
})
.await
}
impl RepoContext {
async fn save_changeset(
&self,
changeset: BonsaiChangeset,
container: &(impl ChangesetsRef + RepoBlobstoreRef + RepoIdentityRef),
bubble: Option<&Bubble>,
) -> Result<(), MononokeError> {
blobrepo::save_bonsai_changesets(vec![changeset.clone()], self.ctx().clone(), container)
.await?;
if let Some(category) = self.config().infinitepush.commit_scribe_category.as_deref() {
blobrepo::scribe::log_commit_to_scribe(
self.ctx(),
category,
container,
&changeset,
bubble.map(|x| x.bubble_id()),
)
.await;
}
Ok(())
}
// TODO(T105334556): This should require draft_write permission
/// Create a new changeset in the repository.
///
/// The new changeset is created with the given metadata by unioning the
/// contents of all parent changesets and then applying the provided
/// changes on top.
///
/// Note that:
/// - The changes must be internally consistent (there must be no path
/// conflicts between changed files).
/// - If a file in any parent changeset is being replaced by a directory
/// then that file must be deleted in the set of changes.
/// - If a directory in any parent changeset is being replaced by a file,
/// then the contents of the parent directory do not need to be deleted.
/// If deletions for the contents of the directory are included they will
/// be checked for correctness (the files must exist), but they will
/// otherwise be ignored.
/// - Any merge conflicts introduced by merging the parent changesets
/// must be resolved by a corresponding change in the set of changes.
///
/// Currenly only a single parent is supported, and root changesets (changesets
/// with no parents) cannot be created.
pub async fn | (
&self,
parents: Vec<ChangesetId>,
author: String,
author_date: DateTime<FixedOffset>,
committer: Option<String>,
committer_date: Option<DateTime<FixedOffset>>,
message: String,
extra: BTreeMap<String, Vec<u8>>,
changes: BTreeMap<MononokePath, CreateChange>,
// If some, this changeset is a snapshot. Currently unsupported to upload a
// normal commit to a bubble, though can be easily added.
bubble: Option<&Bubble>,
) -> Result<ChangesetContext, MononokeError> {
let allowed_no_parents = self
.config()
.source_control_service
.permit_commits_without_parents;
let valid_parent_count = parents.len() == 1 || (parents.len() == 0 && allowed_no_parents);
// Merge rules are not validated yet, so only a single parent is supported.
if!valid_parent_count {
return Err(MononokeError::InvalidRequest(String::from(
"Merge changesets cannot be created",
)));
}
// Obtain contexts for each of the parents (which should exist).
let parent_ctxs: Vec<_> = parents
.iter()
.map(|parent_id| async move {
let parent_ctx = self
.changeset(ChangesetSpecifier::Bonsai(parent_id.clone()))
.await?
.ok_or_else(|| {
MononokeError::InvalidRequest(format!(
"Parent {} does not exist",
parent_id
))
})?;
Ok::<_, MononokeError>(parent_ctx)
})
.collect::<FuturesOrdered<_>>()
.try_collect()
.await?;
// Check that changes are valid according to bonsai rules:
// (1) deletions and copy-from info must reference a real path in a
// valid parent.
// (2) deletions for paths where a prefix directory has been replaced
// by a file should be dropped, as the deletion is implicit from the
// file change for the prefix path.
// (3) conversely, when a file has been replaced by a directory, there
// must be a delete for the file.
//
// Extract the set of deleted files.
let tracked_deletion_files: BTreeSet<_> = changes
.iter()
.filter(|(_path, change)| matches!(change, CreateChange::Deletion))
.map(|(path, _change)| path.clone())
.collect();
// Check deleted files existed in a parent. (1)
let fut_verify_deleted_files_existed = async {
// This does NOT consider "missing" (untracked deletion) files as it is NOT
// necessary for them to exist in a parent. If they don't exist on a parent,
// this means the file was "hg added" and then manually deleted.
let (stats, result) =
verify_deleted_files_existed_in_a_parent(&parent_ctxs, tracked_deletion_files)
.timed()
.await;
let mut scuba = self.ctx().scuba().clone();
scuba.add_future_stats(&stats);
scuba.log_with_msg("Verify deleted files existed in a parent", None);
result
};
// Build a path tree recording each path that has been created or deleted.
let path_changes = PathTree::from_iter(
changes
.iter()
.map(|(path, change)| (path.as_mpath().cloned(), change.change_type())),
);
// Determine the prefixes of all changed files.
let prefix_paths: BTreeSet<_> = changes
.iter()
.filter(|(_path, change)| change.change_type() == CreateChangeType::Change)
.map(|(path, _change)| path.clone().prefixes())
.flatten()
.collect();
// Check changes that replace a file with a directory also delete
// this replaced file. (3)
let fut_verify_prefix_files_deleted = async {
let (stats, result) = parent_ctxs
.iter()
.map(|parent_ctx| {
verify_prefix_files_deleted(parent_ctx, &prefix_paths, &path_changes)
})
.collect::<FuturesUnordered<_>>()
.try_for_each(|_| async { Ok(()) })
.timed()
.await;
let mut scuba = self.ctx().scuba().clone();
scuba.add_future_stats(&stats);
scuba.log_with_msg("Verify prefix files in parents have been deleted", None);
result
};
// Convert change paths into the form needed for the bonsai changeset.
let changes: Vec<(MPath, CreateChange)> = changes
.into_iter()
// Filter deletions that have a change at a path prefix. The
// deletion is implicit from the change. (2)
.filter(|(path, change)| {
change.change_type()!= CreateChangeType::Deletion
||!is_prefix_changed(path, &path_changes)
})
// Then convert the paths to MPaths. Do this before we start
// resolving any changes, so that we don't start storing data
// until we're happy that the changes are valid.
.map(|(path, change)| {
path.into_mpath()
.ok_or_else(|| {
MononokeError::InvalidRequest(String::from(
"Cannot create a file with an empty path",
))
})
.map(move |mpath| (mpath, change))
})
.collect::<Result<_, _>>()?;
// Resolve the changes into bonsai changes. This also checks (1) for
// copy-from info.
let file_changes_fut = async {
let (stats, result) = changes
.into_iter()
.map(|(path, change)| {
let parent_ctxs = &parent_ctxs;
async move {
let change = change
.resolve(
self.ctx(),
self.blob_repo().filestore_config(),
match &bubble {
Some(bubble) => bubble
.wrap_repo_blobstore(self.blob_repo().blobstore().clone()),
None => self.blob_repo().blobstore().clone(),
},
&parent_ctxs,
)
.await?;
Ok::<_, MononokeError>((path, change))
}
})
.collect::<FuturesUnordered<_>>()
.try_collect::<SortedVectorMap<MPath, FileChange>>()
.timed()
.await;
let mut scuba = self.ctx().scuba | create_changeset | identifier_name |
generic-arg-mismatch-recover.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Foo<'a, T: 'a>(&'a T);
struct Bar<'a>(&'a ());
fn | () {
Foo::<'static,'static, ()>(&0); //~ ERROR wrong number of lifetime arguments
//~^ ERROR mismatched types
Bar::<'static,'static, ()>(&()); //~ ERROR wrong number of lifetime arguments
//~^ ERROR wrong number of type arguments
}
| main | identifier_name |
generic-arg-mismatch-recover.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct Foo<'a, T: 'a>(&'a T); |
fn main() {
Foo::<'static,'static, ()>(&0); //~ ERROR wrong number of lifetime arguments
//~^ ERROR mismatched types
Bar::<'static,'static, ()>(&()); //~ ERROR wrong number of lifetime arguments
//~^ ERROR wrong number of type arguments
} |
struct Bar<'a>(&'a ()); | random_line_split |
log_handler.rs | use chrono::{Local, NaiveDate};
use std::collections::HashMap;
use std::fs::{create_dir_all, File, OpenOptions};
use std::io;
use std::io::Write;
use std::path::Path;
use std::thread;
use tokio::{runtime::Runtime, sync::mpsc::Receiver, task};
use super::log_messages::LogMessage;
pub fn create_log_handler(log_dir: String, mut log_rx: Receiver<Box<dyn LogMessage>>) {
thread::spawn(move || {
let rt = Runtime::new().unwrap();
let local = task::LocalSet::new();
local.block_on(&rt, async move {
task::spawn_local(async move {
let mut day = Local::today().naive_local();
let mut log_files: HashMap<String, File> = HashMap::new();
while let Some(log_message) = log_rx.recv().await {
let now = Local::now().naive_local();
let today = now.date();
if day!= today {
log_files.clear();
day = today;
}
let log = log_message.get_log();
let mut file = if let Some(file) = log_files.get(log) {
file
} else {
match create_log_file(&log_dir, log, &day) {
Ok(file) => {
log_files.insert(log.to_owned(), file);
log_files.get(log).unwrap()
}
Err(error) => {
println!("Could not create log file: {:?}", error);
break;
}
}
};
let log_line = format!(
"{} {}\n",
now.format("%H:%M:%S%.3f"),
log_message.get_message() | if let Err(error) = file.write_all(log_line.as_bytes()) {
println!("Error writing log file: {:?}", error);
break;
}
}
println!("Logging disabled.");
})
.await
.unwrap();
});
});
}
fn create_log_file(log_dir: &str, log: &str, day: &NaiveDate) -> io::Result<File> {
let dir_path = format!("{}/{}", log_dir, day.format("%Y%m%d"));
create_dir_all(Path::new(&dir_path))?;
let file_path = format!("{}/{}", dir_path, log);
OpenOptions::new().create(true).append(true).open(file_path)
} | ); | random_line_split |
log_handler.rs | use chrono::{Local, NaiveDate};
use std::collections::HashMap;
use std::fs::{create_dir_all, File, OpenOptions};
use std::io;
use std::io::Write;
use std::path::Path;
use std::thread;
use tokio::{runtime::Runtime, sync::mpsc::Receiver, task};
use super::log_messages::LogMessage;
pub fn | (log_dir: String, mut log_rx: Receiver<Box<dyn LogMessage>>) {
thread::spawn(move || {
let rt = Runtime::new().unwrap();
let local = task::LocalSet::new();
local.block_on(&rt, async move {
task::spawn_local(async move {
let mut day = Local::today().naive_local();
let mut log_files: HashMap<String, File> = HashMap::new();
while let Some(log_message) = log_rx.recv().await {
let now = Local::now().naive_local();
let today = now.date();
if day!= today {
log_files.clear();
day = today;
}
let log = log_message.get_log();
let mut file = if let Some(file) = log_files.get(log) {
file
} else {
match create_log_file(&log_dir, log, &day) {
Ok(file) => {
log_files.insert(log.to_owned(), file);
log_files.get(log).unwrap()
}
Err(error) => {
println!("Could not create log file: {:?}", error);
break;
}
}
};
let log_line = format!(
"{} {}\n",
now.format("%H:%M:%S%.3f"),
log_message.get_message()
);
if let Err(error) = file.write_all(log_line.as_bytes()) {
println!("Error writing log file: {:?}", error);
break;
}
}
println!("Logging disabled.");
})
.await
.unwrap();
});
});
}
fn create_log_file(log_dir: &str, log: &str, day: &NaiveDate) -> io::Result<File> {
let dir_path = format!("{}/{}", log_dir, day.format("%Y%m%d"));
create_dir_all(Path::new(&dir_path))?;
let file_path = format!("{}/{}", dir_path, log);
OpenOptions::new().create(true).append(true).open(file_path)
}
| create_log_handler | identifier_name |
log_handler.rs | use chrono::{Local, NaiveDate};
use std::collections::HashMap;
use std::fs::{create_dir_all, File, OpenOptions};
use std::io;
use std::io::Write;
use std::path::Path;
use std::thread;
use tokio::{runtime::Runtime, sync::mpsc::Receiver, task};
use super::log_messages::LogMessage;
pub fn create_log_handler(log_dir: String, mut log_rx: Receiver<Box<dyn LogMessage>>) | } else {
match create_log_file(&log_dir, log, &day) {
Ok(file) => {
log_files.insert(log.to_owned(), file);
log_files.get(log).unwrap()
}
Err(error) => {
println!("Could not create log file: {:?}", error);
break;
}
}
};
let log_line = format!(
"{} {}\n",
now.format("%H:%M:%S%.3f"),
log_message.get_message()
);
if let Err(error) = file.write_all(log_line.as_bytes()) {
println!("Error writing log file: {:?}", error);
break;
}
}
println!("Logging disabled.");
})
.await
.unwrap();
});
});
}
fn create_log_file(log_dir: &str, log: &str, day: &NaiveDate) -> io::Result<File> {
let dir_path = format!("{}/{}", log_dir, day.format("%Y%m%d"));
create_dir_all(Path::new(&dir_path))?;
let file_path = format!("{}/{}", dir_path, log);
OpenOptions::new().create(true).append(true).open(file_path)
}
| {
thread::spawn(move || {
let rt = Runtime::new().unwrap();
let local = task::LocalSet::new();
local.block_on(&rt, async move {
task::spawn_local(async move {
let mut day = Local::today().naive_local();
let mut log_files: HashMap<String, File> = HashMap::new();
while let Some(log_message) = log_rx.recv().await {
let now = Local::now().naive_local();
let today = now.date();
if day != today {
log_files.clear();
day = today;
}
let log = log_message.get_log();
let mut file = if let Some(file) = log_files.get(log) {
file | identifier_body |
log_handler.rs | use chrono::{Local, NaiveDate};
use std::collections::HashMap;
use std::fs::{create_dir_all, File, OpenOptions};
use std::io;
use std::io::Write;
use std::path::Path;
use std::thread;
use tokio::{runtime::Runtime, sync::mpsc::Receiver, task};
use super::log_messages::LogMessage;
pub fn create_log_handler(log_dir: String, mut log_rx: Receiver<Box<dyn LogMessage>>) {
thread::spawn(move || {
let rt = Runtime::new().unwrap();
let local = task::LocalSet::new();
local.block_on(&rt, async move {
task::spawn_local(async move {
let mut day = Local::today().naive_local();
let mut log_files: HashMap<String, File> = HashMap::new();
while let Some(log_message) = log_rx.recv().await {
let now = Local::now().naive_local();
let today = now.date();
if day!= today {
log_files.clear();
day = today;
}
let log = log_message.get_log();
let mut file = if let Some(file) = log_files.get(log) {
file
} else {
match create_log_file(&log_dir, log, &day) {
Ok(file) => {
log_files.insert(log.to_owned(), file);
log_files.get(log).unwrap()
}
Err(error) => |
}
};
let log_line = format!(
"{} {}\n",
now.format("%H:%M:%S%.3f"),
log_message.get_message()
);
if let Err(error) = file.write_all(log_line.as_bytes()) {
println!("Error writing log file: {:?}", error);
break;
}
}
println!("Logging disabled.");
})
.await
.unwrap();
});
});
}
fn create_log_file(log_dir: &str, log: &str, day: &NaiveDate) -> io::Result<File> {
let dir_path = format!("{}/{}", log_dir, day.format("%Y%m%d"));
create_dir_all(Path::new(&dir_path))?;
let file_path = format!("{}/{}", dir_path, log);
OpenOptions::new().create(true).append(true).open(file_path)
}
| {
println!("Could not create log file: {:?}", error);
break;
} | conditional_block |
var-captured-in-nested-closure.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.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print variable
// gdb-check:$1 = 1
// gdb-command:print constant
// gdb-check:$2 = 2
// gdb-command:print a_struct
// gdb-check:$3 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *struct_ref
// gdb-check:$4 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *owned
// gdb-check:$5 = 6
// gdb-command:print managed->val
// gdb-check:$6 = 7
// gdb-command:print closure_local
// gdb-check:$7 = 8
// gdb-command:continue
// gdb-command:finish
// gdb-command:print variable
// gdb-check:$8 = 1
// gdb-command:print constant
// gdb-check:$9 = 2
// gdb-command:print a_struct
// gdb-check:$10 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *struct_ref
// gdb-check:$11 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *owned
// gdb-check:$12 = 6
// gdb-command:print managed->val
// gdb-check:$13 = 7
// gdb-command:print closure_local
// gdb-check:$14 = 8
// gdb-command:continue
#![feature(managed_boxes)]
#![allow(unused_variable)]
struct | {
a: int,
b: f64,
c: uint
}
fn main() {
let mut variable = 1;
let constant = 2;
let a_struct = Struct {
a: -3,
b: 4.5,
c: 5
};
let struct_ref = &a_struct;
let owned = box 6;
let managed = @7;
let closure = || {
let closure_local = 8;
let nested_closure = || {
zzz();
variable = constant + a_struct.a + struct_ref.a + *owned + *managed + closure_local;
};
zzz();
nested_closure();
};
closure();
}
fn zzz() {()}
| Struct | identifier_name |
var-captured-in-nested-closure.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.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print variable
// gdb-check:$1 = 1
// gdb-command:print constant
// gdb-check:$2 = 2
// gdb-command:print a_struct
// gdb-check:$3 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *struct_ref
// gdb-check:$4 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *owned
// gdb-check:$5 = 6
// gdb-command:print managed->val
// gdb-check:$6 = 7
// gdb-command:print closure_local
// gdb-check:$7 = 8
// gdb-command:continue
// gdb-command:finish
// gdb-command:print variable
// gdb-check:$8 = 1
// gdb-command:print constant
// gdb-check:$9 = 2
// gdb-command:print a_struct
// gdb-check:$10 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *struct_ref
// gdb-check:$11 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *owned
// gdb-check:$12 = 6
// gdb-command:print managed->val
// gdb-check:$13 = 7
// gdb-command:print closure_local
// gdb-check:$14 = 8
// gdb-command:continue
#![feature(managed_boxes)]
#![allow(unused_variable)]
struct Struct {
a: int,
b: f64,
c: uint
}
fn main() | };
zzz();
nested_closure();
};
closure();
}
fn zzz() {()}
| {
let mut variable = 1;
let constant = 2;
let a_struct = Struct {
a: -3,
b: 4.5,
c: 5
};
let struct_ref = &a_struct;
let owned = box 6;
let managed = @7;
let closure = || {
let closure_local = 8;
let nested_closure = || {
zzz();
variable = constant + a_struct.a + struct_ref.a + *owned + *managed + closure_local; | identifier_body |
var-captured-in-nested-closure.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.
// ignore-android: FIXME(#10381)
| // gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print variable
// gdb-check:$1 = 1
// gdb-command:print constant
// gdb-check:$2 = 2
// gdb-command:print a_struct
// gdb-check:$3 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *struct_ref
// gdb-check:$4 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *owned
// gdb-check:$5 = 6
// gdb-command:print managed->val
// gdb-check:$6 = 7
// gdb-command:print closure_local
// gdb-check:$7 = 8
// gdb-command:continue
// gdb-command:finish
// gdb-command:print variable
// gdb-check:$8 = 1
// gdb-command:print constant
// gdb-check:$9 = 2
// gdb-command:print a_struct
// gdb-check:$10 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *struct_ref
// gdb-check:$11 = {a = -3, b = 4.5, c = 5}
// gdb-command:print *owned
// gdb-check:$12 = 6
// gdb-command:print managed->val
// gdb-check:$13 = 7
// gdb-command:print closure_local
// gdb-check:$14 = 8
// gdb-command:continue
#![feature(managed_boxes)]
#![allow(unused_variable)]
struct Struct {
a: int,
b: f64,
c: uint
}
fn main() {
let mut variable = 1;
let constant = 2;
let a_struct = Struct {
a: -3,
b: 4.5,
c: 5
};
let struct_ref = &a_struct;
let owned = box 6;
let managed = @7;
let closure = || {
let closure_local = 8;
let nested_closure = || {
zzz();
variable = constant + a_struct.a + struct_ref.a + *owned + *managed + closure_local;
};
zzz();
nested_closure();
};
closure();
}
fn zzz() {()} | // compile-flags:-g | random_line_split |
str.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::alloc::{OncePool};
#[test]
fn debug_char() {
let mut buf = [0; 30];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{:?}", 'a');
write!(&mut buf, "{:?}", 'ä');
write!(&mut buf, "{:?}", '日');
test!(&*buf == "'a''\\u{e4}''\\u{65e5}'");
}
#[test]
fn display_char() {
let mut buf = [0; 10];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{}", 'a');
write!(&mut buf, "{}", 'ä');
write!(&mut buf, "{}", '日');
test!(&*buf == "aä日");
}
#[test]
fn debug_str() {
let | display_str() {
let mut buf = [0; 30];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{}", "aä日");
test!(&*buf == "aä日");
}
| mut buf = [0; 30];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{:?}", "aä日");
test!(&*buf == "\"a\\u{e4}\\u{65e5}\"");
}
#[test]
fn | identifier_body |
str.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::alloc::{OncePool};
#[test]
fn debug_char() {
let mut buf = [0; 30];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{:?}", 'a');
write!(&mut buf, "{:?}", 'ä');
write!(&mut buf, "{:?}", '日');
test!(&*buf == "'a''\\u{e4}''\\u{65e5}'");
}
#[test]
fn display_char() {
let mut buf = [0; 10];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{}", 'a');
write!(&mut buf, "{}", 'ä');
write!(&mut buf, "{}", '日');
test!(&*buf == "aä日");
}
#[test]
fn debug_str() {
let mut buf = [0; 30];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{:?}", "aä日");
test!(&*buf == "\"a\\u{e4}\\u{65e5}\"");
}
#[test]
fn display_str( | mut buf = [0; 30];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{}", "aä日");
test!(&*buf == "aä日");
}
| ) {
let | identifier_name |
str.rs | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
use std::alloc::{OncePool};
| #[test]
fn debug_char() {
let mut buf = [0; 30];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{:?}", 'a');
write!(&mut buf, "{:?}", 'ä');
write!(&mut buf, "{:?}", '日');
test!(&*buf == "'a''\\u{e4}''\\u{65e5}'");
}
#[test]
fn display_char() {
let mut buf = [0; 10];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{}", 'a');
write!(&mut buf, "{}", 'ä');
write!(&mut buf, "{}", '日');
test!(&*buf == "aä日");
}
#[test]
fn debug_str() {
let mut buf = [0; 30];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{:?}", "aä日");
test!(&*buf == "\"a\\u{e4}\\u{65e5}\"");
}
#[test]
fn display_str() {
let mut buf = [0; 30];
let mut buf = Vec::with_pool(OncePool::new(buf.as_mut()));
write!(&mut buf, "{}", "aä日");
test!(&*buf == "aä日");
} | random_line_split |
|
header_chain.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/>.
//! Light client header chain.
//!
//! Unlike a full node's `BlockChain` this doesn't store much in the database.
//! It stores candidates for the last 2048-4096 blocks as well as CHT roots for
//! historical blocks all the way to the genesis.
//!
//! This is separate from the `BlockChain` for two reasons:
//! - It stores only headers (and a pruned subset of them)
//! - To allow for flexibility in the database layout once that's incorporated.
// TODO: use DB instead of memory. DB Layout: just the contents of `candidates`/`headers`
//
use std::collections::{BTreeMap, HashMap};
use cht;
use ethcore::block_status::BlockStatus;
use ethcore::error::BlockError;
use ethcore::ids::BlockId;
use ethcore::views::HeaderView;
use util::{Bytes, H256, U256, HeapSizeOf, Mutex, RwLock};
use smallvec::SmallVec;
/// Store at least this many candidate headers at all times.
/// Also functions as the delay for computing CHTs as they aren't
/// relevant to any blocks we've got in memory.
const HISTORY: u64 = 2048;
/// Information about a block.
#[derive(Debug, Clone)]
pub struct BlockDescriptor {
/// The block's hash
pub hash: H256,
/// The block's number
pub number: u64,
/// The block's total difficulty.
pub total_difficulty: U256,
}
// candidate block description.
struct Candidate {
hash: H256,
parent_hash: H256,
total_difficulty: U256,
}
struct Entry {
candidates: SmallVec<[Candidate; 3]>, // 3 arbitrarily chosen
canonical_hash: H256,
}
impl HeapSizeOf for Entry {
fn heap_size_of_children(&self) -> usize {
match self.candidates.spilled() {
false => 0,
true => self.candidates.capacity() * ::std::mem::size_of::<Candidate>(),
}
}
}
/// Header chain. See module docs for more details.
pub struct | {
genesis_header: Bytes, // special-case the genesis.
candidates: RwLock<BTreeMap<u64, Entry>>,
headers: RwLock<HashMap<H256, Bytes>>,
best_block: RwLock<BlockDescriptor>,
cht_roots: Mutex<Vec<H256>>,
}
impl HeaderChain {
/// Create a new header chain given this genesis block.
pub fn new(genesis: &[u8]) -> Self {
let g_view = HeaderView::new(genesis);
HeaderChain {
genesis_header: genesis.to_owned(),
best_block: RwLock::new(BlockDescriptor {
hash: g_view.hash(),
number: 0,
total_difficulty: g_view.difficulty(),
}),
candidates: RwLock::new(BTreeMap::new()),
headers: RwLock::new(HashMap::new()),
cht_roots: Mutex::new(Vec::new()),
}
}
/// Insert a pre-verified header.
///
/// This blindly trusts that the data given to it is
/// a) valid RLP encoding of a header and
/// b) has sensible data contained within it.
pub fn insert(&self, header: Bytes) -> Result<(), BlockError> {
let view = HeaderView::new(&header);
let hash = view.hash();
let number = view.number();
let parent_hash = view.parent_hash();
// hold candidates the whole time to guard import order.
let mut candidates = self.candidates.write();
// find parent details.
let parent_td =
if number == 1 {
let g_view = HeaderView::new(&self.genesis_header);
g_view.difficulty()
} else {
candidates.get(&(number - 1))
.and_then(|entry| entry.candidates.iter().find(|c| c.hash == parent_hash))
.map(|c| c.total_difficulty)
.ok_or_else(|| BlockError::UnknownParent(parent_hash))?
};
let total_difficulty = parent_td + view.difficulty();
// insert headers and candidates entries.
candidates.entry(number).or_insert_with(|| Entry { candidates: SmallVec::new(), canonical_hash: hash })
.candidates.push(Candidate {
hash: hash,
parent_hash: parent_hash,
total_difficulty: total_difficulty,
});
self.headers.write().insert(hash, header.clone());
// reorganize ancestors so canonical entries are first in their
// respective candidates vectors.
if self.best_block.read().total_difficulty < total_difficulty {
let mut canon_hash = hash;
for (&height, entry) in candidates.iter_mut().rev().skip_while(|&(height, _)| *height > number) {
if height!= number && entry.canonical_hash == canon_hash { break; }
trace!(target: "chain", "Setting new canonical block {} for block height {}",
canon_hash, height);
let canon_pos = entry.candidates.iter().position(|x| x.hash == canon_hash)
.expect("blocks are only inserted if parent is present; or this is the block we just added; qed");
// move the new canonical entry to the front and set the
// era's canonical hash.
entry.candidates.swap(0, canon_pos);
entry.canonical_hash = canon_hash;
// what about reorgs > cht::SIZE + HISTORY?
// resetting to the last block of a given CHT should be possible.
canon_hash = entry.candidates[0].parent_hash;
}
trace!(target: "chain", "New best block: ({}, {}), TD {}", number, hash, total_difficulty);
*self.best_block.write() = BlockDescriptor {
hash: hash,
number: number,
total_difficulty: total_difficulty,
};
// produce next CHT root if it's time.
let earliest_era = *candidates.keys().next().expect("at least one era just created; qed");
if earliest_era + HISTORY + cht::SIZE <= number {
let mut values = Vec::with_capacity(cht::SIZE as usize);
{
let mut headers = self.headers.write();
for i in (0..cht::SIZE).map(|x| x + earliest_era) {
let era_entry = candidates.remove(&i)
.expect("all eras are sequential with no gaps; qed");
for ancient in &era_entry.candidates {
headers.remove(&ancient.hash);
}
values.push((
::rlp::encode(&i).to_vec(),
::rlp::encode(&era_entry.canonical_hash).to_vec(),
));
}
}
let cht_root = ::util::triehash::trie_root(values);
debug!(target: "chain", "Produced CHT {} root: {:?}", (earliest_era - 1) % cht::SIZE, cht_root);
self.cht_roots.lock().push(cht_root);
}
}
Ok(())
}
/// Get a block header. In the case of query by number, only canonical blocks
/// will be returned.
pub fn get_header(&self, id: BlockId) -> Option<Bytes> {
match id {
BlockId::Earliest | BlockId::Number(0) => Some(self.genesis_header.clone()),
BlockId::Hash(hash) => self.headers.read().get(&hash).map(|x| x.to_vec()),
BlockId::Number(num) => {
if self.best_block.read().number < num { return None }
self.candidates.read().get(&num).map(|entry| entry.canonical_hash)
.and_then(|hash| self.headers.read().get(&hash).map(|x| x.to_vec()))
}
BlockId::Latest | BlockId::Pending => {
let hash = self.best_block.read().hash;
self.headers.read().get(&hash).map(|x| x.to_vec())
}
}
}
/// Get the nth CHT root, if it's been computed.
///
/// CHT root 0 is from block `1..2048`.
/// CHT root 1 is from block `2049..4096`
/// and so on.
///
/// This is because it's assumed that the genesis hash is known,
/// so including it within a CHT would be redundant.
pub fn cht_root(&self, n: usize) -> Option<H256> {
self.cht_roots.lock().get(n).map(|h| h.clone())
}
/// Get the genesis hash.
pub fn genesis_hash(&self) -> H256 {
::util::Hashable::sha3(&self.genesis_header)
}
/// Get the best block's data.
pub fn best_block(&self) -> BlockDescriptor {
self.best_block.read().clone()
}
/// If there is a gap between the genesis and the rest
/// of the stored blocks, return the first post-gap block.
pub fn first_block(&self) -> Option<BlockDescriptor> {
let candidates = self.candidates.read();
match candidates.iter().next() {
None | Some((&1, _)) => None,
Some((&height, entry)) => Some(BlockDescriptor {
number: height,
hash: entry.canonical_hash,
total_difficulty: entry.candidates.iter().find(|x| x.hash == entry.canonical_hash)
.expect("entry always stores canonical candidate; qed").total_difficulty,
})
}
}
/// Get block status.
pub fn status(&self, hash: &H256) -> BlockStatus {
match self.headers.read().contains_key(hash) {
true => BlockStatus::InChain,
false => BlockStatus::Unknown,
}
}
}
impl HeapSizeOf for HeaderChain {
fn heap_size_of_children(&self) -> usize {
self.candidates.read().heap_size_of_children() +
self.headers.read().heap_size_of_children() +
self.cht_roots.lock().heap_size_of_children()
}
}
#[cfg(test)]
mod tests {
use super::HeaderChain;
use ethcore::ids::BlockId;
use ethcore::header::Header;
use ethcore::spec::Spec;
#[test]
fn basic_chain() {
let spec = Spec::new_test();
let genesis_header = spec.genesis_header();
let chain = HeaderChain::new(&::rlp::encode(&genesis_header));
let mut parent_hash = genesis_header.hash();
let mut rolling_timestamp = genesis_header.timestamp();
for i in 1..10000 {
let mut header = Header::new();
header.set_parent_hash(parent_hash);
header.set_number(i);
header.set_timestamp(rolling_timestamp);
header.set_difficulty(*genesis_header.difficulty() * i.into());
chain.insert(::rlp::encode(&header).to_vec()).unwrap();
parent_hash = header.hash();
rolling_timestamp += 10;
}
assert!(chain.get_header(BlockId::Number(10)).is_none());
assert!(chain.get_header(BlockId::Number(9000)).is_some());
assert!(chain.cht_root(2).is_some());
assert!(chain.cht_root(3).is_none());
}
#[test]
fn reorganize() {
let spec = Spec::new_test();
let genesis_header = spec.genesis_header();
let chain = HeaderChain::new(&::rlp::encode(&genesis_header));
let mut parent_hash = genesis_header.hash();
let mut rolling_timestamp = genesis_header.timestamp();
for i in 1..6 {
let mut header = Header::new();
header.set_parent_hash(parent_hash);
header.set_number(i);
header.set_timestamp(rolling_timestamp);
header.set_difficulty(*genesis_header.difficulty() * i.into());
chain.insert(::rlp::encode(&header).to_vec()).unwrap();
parent_hash = header.hash();
rolling_timestamp += 10;
}
{
let mut rolling_timestamp = rolling_timestamp;
let mut parent_hash = parent_hash;
for i in 6..16 {
let mut header = Header::new();
header.set_parent_hash(parent_hash);
header.set_number(i);
header.set_timestamp(rolling_timestamp);
header.set_difficulty(*genesis_header.difficulty() * i.into());
chain.insert(::rlp::encode(&header).to_vec()).unwrap();
parent_hash = header.hash();
rolling_timestamp += 10;
}
}
assert_eq!(chain.best_block().number, 15);
{
let mut rolling_timestamp = rolling_timestamp;
let mut parent_hash = parent_hash;
// import a shorter chain which has better TD.
for i in 6..13 {
let mut header = Header::new();
header.set_parent_hash(parent_hash);
header.set_number(i);
header.set_timestamp(rolling_timestamp);
header.set_difficulty(*genesis_header.difficulty() * (i * i).into());
chain.insert(::rlp::encode(&header).to_vec()).unwrap();
parent_hash = header.hash();
rolling_timestamp += 11;
}
}
let (mut num, mut canon_hash) = (chain.best_block().number, chain.best_block().hash);
assert_eq!(num, 12);
while num > 0 {
let header: Header = ::rlp::decode(&chain.get_header(BlockId::Number(num)).unwrap());
assert_eq!(header.hash(), canon_hash);
canon_hash = *header.parent_hash();
num -= 1;
}
}
}
| HeaderChain | identifier_name |
header_chain.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/>.
//! Light client header chain.
//!
//! Unlike a full node's `BlockChain` this doesn't store much in the database.
//! It stores candidates for the last 2048-4096 blocks as well as CHT roots for
//! historical blocks all the way to the genesis.
//!
//! This is separate from the `BlockChain` for two reasons:
//! - It stores only headers (and a pruned subset of them)
//! - To allow for flexibility in the database layout once that's incorporated.
// TODO: use DB instead of memory. DB Layout: just the contents of `candidates`/`headers`
//
use std::collections::{BTreeMap, HashMap};
use cht;
use ethcore::block_status::BlockStatus;
use ethcore::error::BlockError;
use ethcore::ids::BlockId;
use ethcore::views::HeaderView;
use util::{Bytes, H256, U256, HeapSizeOf, Mutex, RwLock};
use smallvec::SmallVec;
/// Store at least this many candidate headers at all times.
/// Also functions as the delay for computing CHTs as they aren't
/// relevant to any blocks we've got in memory.
const HISTORY: u64 = 2048;
/// Information about a block.
#[derive(Debug, Clone)]
pub struct BlockDescriptor {
/// The block's hash
pub hash: H256,
/// The block's number
pub number: u64,
/// The block's total difficulty.
pub total_difficulty: U256,
}
// candidate block description.
struct Candidate {
hash: H256,
parent_hash: H256,
total_difficulty: U256,
}
struct Entry {
candidates: SmallVec<[Candidate; 3]>, // 3 arbitrarily chosen
canonical_hash: H256,
}
impl HeapSizeOf for Entry {
fn heap_size_of_children(&self) -> usize {
match self.candidates.spilled() {
false => 0,
true => self.candidates.capacity() * ::std::mem::size_of::<Candidate>(),
}
}
}
/// Header chain. See module docs for more details.
pub struct HeaderChain {
genesis_header: Bytes, // special-case the genesis.
candidates: RwLock<BTreeMap<u64, Entry>>,
headers: RwLock<HashMap<H256, Bytes>>,
best_block: RwLock<BlockDescriptor>,
cht_roots: Mutex<Vec<H256>>,
}
impl HeaderChain {
/// Create a new header chain given this genesis block.
pub fn new(genesis: &[u8]) -> Self {
let g_view = HeaderView::new(genesis);
HeaderChain {
genesis_header: genesis.to_owned(),
best_block: RwLock::new(BlockDescriptor {
hash: g_view.hash(),
number: 0,
total_difficulty: g_view.difficulty(),
}),
candidates: RwLock::new(BTreeMap::new()),
headers: RwLock::new(HashMap::new()),
cht_roots: Mutex::new(Vec::new()),
}
}
/// Insert a pre-verified header.
///
/// This blindly trusts that the data given to it is
/// a) valid RLP encoding of a header and
/// b) has sensible data contained within it.
pub fn insert(&self, header: Bytes) -> Result<(), BlockError> {
let view = HeaderView::new(&header);
let hash = view.hash();
let number = view.number();
let parent_hash = view.parent_hash();
// hold candidates the whole time to guard import order.
let mut candidates = self.candidates.write();
// find parent details.
let parent_td =
if number == 1 {
let g_view = HeaderView::new(&self.genesis_header);
g_view.difficulty()
} else {
candidates.get(&(number - 1))
.and_then(|entry| entry.candidates.iter().find(|c| c.hash == parent_hash))
.map(|c| c.total_difficulty)
.ok_or_else(|| BlockError::UnknownParent(parent_hash))?
};
let total_difficulty = parent_td + view.difficulty();
// insert headers and candidates entries.
candidates.entry(number).or_insert_with(|| Entry { candidates: SmallVec::new(), canonical_hash: hash })
.candidates.push(Candidate {
hash: hash,
parent_hash: parent_hash,
total_difficulty: total_difficulty,
});
self.headers.write().insert(hash, header.clone());
// reorganize ancestors so canonical entries are first in their
// respective candidates vectors.
if self.best_block.read().total_difficulty < total_difficulty {
let mut canon_hash = hash;
for (&height, entry) in candidates.iter_mut().rev().skip_while(|&(height, _)| *height > number) {
if height!= number && entry.canonical_hash == canon_hash { break; }
trace!(target: "chain", "Setting new canonical block {} for block height {}",
canon_hash, height);
let canon_pos = entry.candidates.iter().position(|x| x.hash == canon_hash)
.expect("blocks are only inserted if parent is present; or this is the block we just added; qed");
// move the new canonical entry to the front and set the
// era's canonical hash.
entry.candidates.swap(0, canon_pos);
entry.canonical_hash = canon_hash;
// what about reorgs > cht::SIZE + HISTORY?
// resetting to the last block of a given CHT should be possible.
canon_hash = entry.candidates[0].parent_hash;
}
trace!(target: "chain", "New best block: ({}, {}), TD {}", number, hash, total_difficulty);
*self.best_block.write() = BlockDescriptor {
hash: hash,
number: number,
total_difficulty: total_difficulty,
};
// produce next CHT root if it's time.
let earliest_era = *candidates.keys().next().expect("at least one era just created; qed");
if earliest_era + HISTORY + cht::SIZE <= number {
let mut values = Vec::with_capacity(cht::SIZE as usize);
{
let mut headers = self.headers.write();
for i in (0..cht::SIZE).map(|x| x + earliest_era) {
let era_entry = candidates.remove(&i)
.expect("all eras are sequential with no gaps; qed");
for ancient in &era_entry.candidates {
headers.remove(&ancient.hash);
}
values.push((
::rlp::encode(&i).to_vec(),
::rlp::encode(&era_entry.canonical_hash).to_vec(),
));
}
}
let cht_root = ::util::triehash::trie_root(values);
debug!(target: "chain", "Produced CHT {} root: {:?}", (earliest_era - 1) % cht::SIZE, cht_root);
self.cht_roots.lock().push(cht_root);
}
}
Ok(())
}
/// Get a block header. In the case of query by number, only canonical blocks
/// will be returned.
pub fn get_header(&self, id: BlockId) -> Option<Bytes> {
match id {
BlockId::Earliest | BlockId::Number(0) => Some(self.genesis_header.clone()),
BlockId::Hash(hash) => self.headers.read().get(&hash).map(|x| x.to_vec()),
BlockId::Number(num) => {
if self.best_block.read().number < num { return None }
self.candidates.read().get(&num).map(|entry| entry.canonical_hash)
.and_then(|hash| self.headers.read().get(&hash).map(|x| x.to_vec()))
}
BlockId::Latest | BlockId::Pending => {
let hash = self.best_block.read().hash;
self.headers.read().get(&hash).map(|x| x.to_vec())
}
}
}
/// Get the nth CHT root, if it's been computed.
///
/// CHT root 0 is from block `1..2048`.
/// CHT root 1 is from block `2049..4096`
/// and so on.
///
/// This is because it's assumed that the genesis hash is known,
/// so including it within a CHT would be redundant.
pub fn cht_root(&self, n: usize) -> Option<H256> {
self.cht_roots.lock().get(n).map(|h| h.clone())
}
/// Get the genesis hash.
pub fn genesis_hash(&self) -> H256 {
::util::Hashable::sha3(&self.genesis_header)
}
/// Get the best block's data.
pub fn best_block(&self) -> BlockDescriptor {
self.best_block.read().clone()
}
/// If there is a gap between the genesis and the rest
/// of the stored blocks, return the first post-gap block.
pub fn first_block(&self) -> Option<BlockDescriptor> {
let candidates = self.candidates.read();
match candidates.iter().next() {
None | Some((&1, _)) => None,
Some((&height, entry)) => Some(BlockDescriptor {
number: height,
hash: entry.canonical_hash,
total_difficulty: entry.candidates.iter().find(|x| x.hash == entry.canonical_hash)
.expect("entry always stores canonical candidate; qed").total_difficulty,
})
}
}
/// Get block status.
pub fn status(&self, hash: &H256) -> BlockStatus {
match self.headers.read().contains_key(hash) {
true => BlockStatus::InChain,
false => BlockStatus::Unknown,
}
}
}
impl HeapSizeOf for HeaderChain {
fn heap_size_of_children(&self) -> usize {
self.candidates.read().heap_size_of_children() +
self.headers.read().heap_size_of_children() +
self.cht_roots.lock().heap_size_of_children()
}
}
#[cfg(test)]
mod tests {
use super::HeaderChain;
use ethcore::ids::BlockId;
use ethcore::header::Header;
use ethcore::spec::Spec;
#[test]
fn basic_chain() {
let spec = Spec::new_test();
let genesis_header = spec.genesis_header();
let chain = HeaderChain::new(&::rlp::encode(&genesis_header));
let mut parent_hash = genesis_header.hash();
let mut rolling_timestamp = genesis_header.timestamp();
for i in 1..10000 {
let mut header = Header::new();
header.set_parent_hash(parent_hash);
header.set_number(i);
header.set_timestamp(rolling_timestamp);
header.set_difficulty(*genesis_header.difficulty() * i.into());
chain.insert(::rlp::encode(&header).to_vec()).unwrap();
parent_hash = header.hash();
rolling_timestamp += 10;
}
assert!(chain.get_header(BlockId::Number(10)).is_none()); | }
#[test]
fn reorganize() {
let spec = Spec::new_test();
let genesis_header = spec.genesis_header();
let chain = HeaderChain::new(&::rlp::encode(&genesis_header));
let mut parent_hash = genesis_header.hash();
let mut rolling_timestamp = genesis_header.timestamp();
for i in 1..6 {
let mut header = Header::new();
header.set_parent_hash(parent_hash);
header.set_number(i);
header.set_timestamp(rolling_timestamp);
header.set_difficulty(*genesis_header.difficulty() * i.into());
chain.insert(::rlp::encode(&header).to_vec()).unwrap();
parent_hash = header.hash();
rolling_timestamp += 10;
}
{
let mut rolling_timestamp = rolling_timestamp;
let mut parent_hash = parent_hash;
for i in 6..16 {
let mut header = Header::new();
header.set_parent_hash(parent_hash);
header.set_number(i);
header.set_timestamp(rolling_timestamp);
header.set_difficulty(*genesis_header.difficulty() * i.into());
chain.insert(::rlp::encode(&header).to_vec()).unwrap();
parent_hash = header.hash();
rolling_timestamp += 10;
}
}
assert_eq!(chain.best_block().number, 15);
{
let mut rolling_timestamp = rolling_timestamp;
let mut parent_hash = parent_hash;
// import a shorter chain which has better TD.
for i in 6..13 {
let mut header = Header::new();
header.set_parent_hash(parent_hash);
header.set_number(i);
header.set_timestamp(rolling_timestamp);
header.set_difficulty(*genesis_header.difficulty() * (i * i).into());
chain.insert(::rlp::encode(&header).to_vec()).unwrap();
parent_hash = header.hash();
rolling_timestamp += 11;
}
}
let (mut num, mut canon_hash) = (chain.best_block().number, chain.best_block().hash);
assert_eq!(num, 12);
while num > 0 {
let header: Header = ::rlp::decode(&chain.get_header(BlockId::Number(num)).unwrap());
assert_eq!(header.hash(), canon_hash);
canon_hash = *header.parent_hash();
num -= 1;
}
}
} | assert!(chain.get_header(BlockId::Number(9000)).is_some());
assert!(chain.cht_root(2).is_some());
assert!(chain.cht_root(3).is_none()); | random_line_split |
general.rs | use std::fmt::Write;
use eew::*;
pub fn format_eew_full(eew: &EEW) -> String
{
let mut output = String::new();
write_unwrap!(&mut output, "[EEW: {} - {}]\n", eew.id, eew.number);
write_unwrap!(&mut output, "issue_pattern: {:?}, source: {:?}, kind: {:?}, \
issued_at: {:?}, occurred_at: {:?}, status: {:?}\n",
eew.issue_pattern, eew.source, eew.kind, eew.issued_at, eew.occurred_at, eew.status);
if let Some(ref detail) = eew.detail |
output
}
| {
write_unwrap!(&mut output, "epicenter_name: {}, epicenter: {:?}, \
depth: {:?}, magnitude: {:?}, maximum_intensity: {:?}, epicenter_accuracy: {:?}, \
depth_accuracy: {:?}, magnitude_accuracy: {:?}, epicenter_category: {:?}, \
warning_status: {:?}, intensity_change: {:?}, change_reason: {:?}\n",
detail.epicenter_name, detail.epicenter, detail.depth,
detail.magnitude, detail.maximum_intensity, detail.epicenter_accuracy,
detail.depth_accuracy, detail.magnitude_accuracy, detail.epicenter_category,
detail.warning_status, detail.intensity_change, detail.change_reason);
for area in detail.area_info.iter() {
write_unwrap!(&mut output, "area_name: {}, minimum_intensity: {:?}, \
maximum_intensity: {:?}, reach_at: {:?}, warning_status: {:?}, wave_status: {:?}\n",
area.area_name, area.minimum_intensity, area.maximum_intensity,
area.reach_at, area.warning_status, area.wave_status);
}
} | conditional_block |
general.rs | use std::fmt::Write;
use eew::*;
pub fn | (eew: &EEW) -> String
{
let mut output = String::new();
write_unwrap!(&mut output, "[EEW: {} - {}]\n", eew.id, eew.number);
write_unwrap!(&mut output, "issue_pattern: {:?}, source: {:?}, kind: {:?}, \
issued_at: {:?}, occurred_at: {:?}, status: {:?}\n",
eew.issue_pattern, eew.source, eew.kind, eew.issued_at, eew.occurred_at, eew.status);
if let Some(ref detail) = eew.detail {
write_unwrap!(&mut output, "epicenter_name: {}, epicenter: {:?}, \
depth: {:?}, magnitude: {:?}, maximum_intensity: {:?}, epicenter_accuracy: {:?}, \
depth_accuracy: {:?}, magnitude_accuracy: {:?}, epicenter_category: {:?}, \
warning_status: {:?}, intensity_change: {:?}, change_reason: {:?}\n",
detail.epicenter_name, detail.epicenter, detail.depth,
detail.magnitude, detail.maximum_intensity, detail.epicenter_accuracy,
detail.depth_accuracy, detail.magnitude_accuracy, detail.epicenter_category,
detail.warning_status, detail.intensity_change, detail.change_reason);
for area in detail.area_info.iter() {
write_unwrap!(&mut output, "area_name: {}, minimum_intensity: {:?}, \
maximum_intensity: {:?}, reach_at: {:?}, warning_status: {:?}, wave_status: {:?}\n",
area.area_name, area.minimum_intensity, area.maximum_intensity,
area.reach_at, area.warning_status, area.wave_status);
}
}
output
}
| format_eew_full | identifier_name |
general.rs | use std::fmt::Write;
use eew::*;
pub fn format_eew_full(eew: &EEW) -> String
| for area in detail.area_info.iter() {
write_unwrap!(&mut output, "area_name: {}, minimum_intensity: {:?}, \
maximum_intensity: {:?}, reach_at: {:?}, warning_status: {:?}, wave_status: {:?}\n",
area.area_name, area.minimum_intensity, area.maximum_intensity,
area.reach_at, area.warning_status, area.wave_status);
}
}
output
}
| {
let mut output = String::new();
write_unwrap!(&mut output, "[EEW: {} - {}]\n", eew.id, eew.number);
write_unwrap!(&mut output, "issue_pattern: {:?}, source: {:?}, kind: {:?}, \
issued_at: {:?}, occurred_at: {:?}, status: {:?}\n",
eew.issue_pattern, eew.source, eew.kind, eew.issued_at, eew.occurred_at, eew.status);
if let Some(ref detail) = eew.detail {
write_unwrap!(&mut output, "epicenter_name: {}, epicenter: {:?}, \
depth: {:?}, magnitude: {:?}, maximum_intensity: {:?}, epicenter_accuracy: {:?}, \
depth_accuracy: {:?}, magnitude_accuracy: {:?}, epicenter_category: {:?}, \
warning_status: {:?}, intensity_change: {:?}, change_reason: {:?}\n",
detail.epicenter_name, detail.epicenter, detail.depth,
detail.magnitude, detail.maximum_intensity, detail.epicenter_accuracy,
detail.depth_accuracy, detail.magnitude_accuracy, detail.epicenter_category,
detail.warning_status, detail.intensity_change, detail.change_reason);
| identifier_body |
general.rs | use std::fmt::Write;
use eew::*;
pub fn format_eew_full(eew: &EEW) -> String
{
let mut output = String::new();
write_unwrap!(&mut output, "[EEW: {} - {}]\n", eew.id, eew.number);
write_unwrap!(&mut output, "issue_pattern: {:?}, source: {:?}, kind: {:?}, \
issued_at: {:?}, occurred_at: {:?}, status: {:?}\n",
eew.issue_pattern, eew.source, eew.kind, eew.issued_at, eew.occurred_at, eew.status);
if let Some(ref detail) = eew.detail {
write_unwrap!(&mut output, "epicenter_name: {}, epicenter: {:?}, \ | detail.epicenter_name, detail.epicenter, detail.depth,
detail.magnitude, detail.maximum_intensity, detail.epicenter_accuracy,
detail.depth_accuracy, detail.magnitude_accuracy, detail.epicenter_category,
detail.warning_status, detail.intensity_change, detail.change_reason);
for area in detail.area_info.iter() {
write_unwrap!(&mut output, "area_name: {}, minimum_intensity: {:?}, \
maximum_intensity: {:?}, reach_at: {:?}, warning_status: {:?}, wave_status: {:?}\n",
area.area_name, area.minimum_intensity, area.maximum_intensity,
area.reach_at, area.warning_status, area.wave_status);
}
}
output
} | depth: {:?}, magnitude: {:?}, maximum_intensity: {:?}, epicenter_accuracy: {:?}, \
depth_accuracy: {:?}, magnitude_accuracy: {:?}, epicenter_category: {:?}, \
warning_status: {:?}, intensity_change: {:?}, change_reason: {:?}\n", | random_line_split |
main.rs | use std::io;
use std::rand;
use std::cmp::Ordering;
fn main() {
let secret_number = (rand::random::<u32>() % 100) + 1;
println!("Guess the number!");
loop {
println!("Please input your guess.");
let input = io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.trim().parse();
let num = match input_num {
Some(num) => num,
None => {
println!("Please input a number!");
continue;
}
};
println!("You guessed: {}", num);
match cmp(num, secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
return;
}
}
}
}
fn cmp(a: u32, b: u32) -> Ordering | {
if a < b {
Ordering::Less
} else if a > b {
Ordering::Greater
} else {
Ordering::Equal
}
} | identifier_body |
|
main.rs | use std::io;
use std::rand;
use std::cmp::Ordering;
fn main() {
let secret_number = (rand::random::<u32>() % 100) + 1;
println!("Guess the number!");
loop {
println!("Please input your guess.");
let input = io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.trim().parse();
let num = match input_num {
Some(num) => num,
None => { | };
println!("You guessed: {}", num);
match cmp(num, secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
return;
}
}
}
}
fn cmp(a: u32, b: u32) -> Ordering {
if a < b {
Ordering::Less
} else if a > b {
Ordering::Greater
} else {
Ordering::Equal
}
} | println!("Please input a number!");
continue;
} | random_line_split |
main.rs | use std::io;
use std::rand;
use std::cmp::Ordering;
fn | () {
let secret_number = (rand::random::<u32>() % 100) + 1;
println!("Guess the number!");
loop {
println!("Please input your guess.");
let input = io::stdin().read_line()
.ok()
.expect("Failed to read line");
let input_num: Option<u32> = input.trim().parse();
let num = match input_num {
Some(num) => num,
None => {
println!("Please input a number!");
continue;
}
};
println!("You guessed: {}", num);
match cmp(num, secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
return;
}
}
}
}
fn cmp(a: u32, b: u32) -> Ordering {
if a < b {
Ordering::Less
} else if a > b {
Ordering::Greater
} else {
Ordering::Equal
}
}
| main | identifier_name |
manager.rs | /*use std::io::Write;
use dbus::{BusType, Connection, ConnectionItem, Error, Message, MessageItem, NameFlag};
use dbus::obj::{Argument, Interface, Method, ObjectPath, Property};
use constants::*;
pub struct Manager {
running: bool,
}
impl Manager {
pub fn new() -> Manager {
Manager { running: false }
}
pub fn start(self) {
let conn = match Connection::get_private(BusType::System) {
Ok(c) => c,
Err(e) => panic!("Manager: Failed to get DBUS connection: {:?}", e),
};
info!("Manager: Opened {:?}", conn);
conn.register_name(DBUS_SERVICE_NAME, NameFlag::ReplaceExisting as u32).unwrap();
info!("Manager: Registered service name {}", DBUS_SERVICE_NAME);
| vec![],
vec![Argument::new("reply", "s")],
Box::new(|msg| {
Ok(vec!(MessageItem::Str(format!("Hello {}!", msg.sender().unwrap()))))
}))],
vec![],
vec![]);
let mut root_path = ObjectPath::new(&conn, "/", true);
root_path.insert_interface(DBUS_ROOT_PATH, root_iface);
root_path.set_registered(true).unwrap();
info!("Manager: Registered interface!");
info!("Manager: Starting main loop!");
for n in conn.iter(1) {
if let ConnectionItem::MethodCall(mut m) = n {
if root_path.handle_message(&mut m).is_none() {
conn.send(Message::new_error(&m,
"org.freedesktop.DBus.Error.Failed",
"Object path not found")
.unwrap())
.unwrap();
info!("Path not found");
} else {
info!("Handled method call!");
}
};
}
info!("Manager: Quit main loop. Exiting..");
}
}*/ | let root_iface = Interface::new(vec![Method::new("Hello", | random_line_split |
math.rs |
use Vec3;
use cgmath::Vector2;
use cgmath::InnerSpace;
use cgmath::dot;
use std;
#[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
pub struct Rect<F> {
pub min : Vector2<F>,
pub max : Vector2<F>,
}
pub type RectI = Rect<i32>;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct LineSegment {
pub from: Vec3,
pub to: Vec3,
}
const PI : f64 = std::f64::consts::PI;
const TAU : f64 = PI * 2.0;
const EPSILON: f64 = 0.0000001;
impl LineSegment {
pub fn intersects(&self, plane:Plane) -> Option<Vec3> {
let direction = (self.to - self.from).normalize();
let denominator = dot(plane.normal, direction);
if denominator > -EPSILON && denominator < EPSILON {
return None
}
let numerator = -(dot(plane.normal, self.from) - plane.coefficient);
let ratio = numerator / denominator;
if ratio < EPSILON {
None
} else |
}
}
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Plane {
pub normal: Vec3,
pub coefficient: f64,
}
impl Plane {
pub fn from_origin_normal(origin:Vec3, normal:Vec3) -> Plane {
Plane {
normal:normal,
coefficient: (normal.x * origin.x + normal.y * origin.y + normal.z * origin.z),
}
}
} | {
Some((direction * ratio) + self.from)
} | conditional_block |
math.rs | use Vec3;
use cgmath::Vector2;
use cgmath::InnerSpace;
use cgmath::dot;
use std;
#[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
pub struct Rect<F> {
pub min : Vector2<F>,
pub max : Vector2<F>,
}
pub type RectI = Rect<i32>;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct LineSegment {
pub from: Vec3,
pub to: Vec3,
}
const PI : f64 = std::f64::consts::PI;
const TAU : f64 = PI * 2.0;
const EPSILON: f64 = 0.0000001;
impl LineSegment {
pub fn intersects(&self, plane:Plane) -> Option<Vec3> {
let direction = (self.to - self.from).normalize();
let denominator = dot(plane.normal, direction);
if denominator > -EPSILON && denominator < EPSILON {
return None
}
let numerator = -(dot(plane.normal, self.from) - plane.coefficient);
let ratio = numerator / denominator;
if ratio < EPSILON {
None |
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Plane {
pub normal: Vec3,
pub coefficient: f64,
}
impl Plane {
pub fn from_origin_normal(origin:Vec3, normal:Vec3) -> Plane {
Plane {
normal:normal,
coefficient: (normal.x * origin.x + normal.y * origin.y + normal.z * origin.z),
}
}
} | } else {
Some((direction * ratio) + self.from)
}
}
} | random_line_split |
math.rs |
use Vec3;
use cgmath::Vector2;
use cgmath::InnerSpace;
use cgmath::dot;
use std;
#[derive(Eq, PartialEq, Copy, Clone, Debug, Hash)]
pub struct Rect<F> {
pub min : Vector2<F>,
pub max : Vector2<F>,
}
pub type RectI = Rect<i32>;
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct LineSegment {
pub from: Vec3,
pub to: Vec3,
}
const PI : f64 = std::f64::consts::PI;
const TAU : f64 = PI * 2.0;
const EPSILON: f64 = 0.0000001;
impl LineSegment {
pub fn | (&self, plane:Plane) -> Option<Vec3> {
let direction = (self.to - self.from).normalize();
let denominator = dot(plane.normal, direction);
if denominator > -EPSILON && denominator < EPSILON {
return None
}
let numerator = -(dot(plane.normal, self.from) - plane.coefficient);
let ratio = numerator / denominator;
if ratio < EPSILON {
None
} else {
Some((direction * ratio) + self.from)
}
}
}
#[derive(PartialEq, Debug, Copy, Clone)]
pub struct Plane {
pub normal: Vec3,
pub coefficient: f64,
}
impl Plane {
pub fn from_origin_normal(origin:Vec3, normal:Vec3) -> Plane {
Plane {
normal:normal,
coefficient: (normal.x * origin.x + normal.y * origin.y + normal.z * origin.z),
}
}
} | intersects | identifier_name |
uint_macros.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | #![macro_escape]
#![doc(hidden)]
macro_rules! uint_module (($T:ty, $T_SIGNED:ty, $bits:expr) => (
#[unstable]
pub static BITS : uint = $bits;
#[unstable]
pub static BYTES : uint = ($bits / 8);
#[unstable]
pub static MIN: $T = 0 as $T;
#[unstable]
pub static MAX: $T = 0 as $T - 1 as $T;
)) | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
text.rs | use std::{env, process};
use yaml_rust::YamlLoader;
#[allow(dead_code)]
pub enum Errors {
GtkInitError,
ScreenshotUnsuccessful,
StrfTimeUnavailable,
PicturesFolderUnavailable,
ScreenshotSaveError,
ImageViewerError,
FileError,
ImgurUploadFailure,
ClipboardUnavailable,
MastodonImageUnsuccessful,
MastodonTootUnsuccessful,
MastodonLoginError,
TwitterImageUnsuccessful,
TwitterTweetUnsucessful,
TwitterLoginError,
NotificationUnavailable,
}
#[allow(dead_code)]
pub enum Text {
UnsupportedWayland,
}
// Retrieves locale settings of the user using LC_CTYPE or LANG
fn locale() -> String {
match env::var("LC_CTYPE") {
Ok(ok) => ok,
Err(_) => match env::var("LANG") {
Ok(ok) => ok,
Err(_) => String::new(),
},
}
}
// Retrieves the correct localization file and returns a String
pub fn loader() -> String {
let lang = locale();
if lang.contains("fr") {
return include_str!("../lang/fr.yml").to_string();
} else if lang.contains("es") {
return include_str!("../lang/es.yml").to_string();
} else if lang.contains("eo") {
return include_str!("../lang/eo.yml").to_string();
} else if lang.contains("CN") && lang.contains("zh") {
return include_str!("../lang/cn.yml").to_string();
} else if lang.contains("TW") && lang.contains("zh") {
return include_str!("../lang/tw.yml").to_string();
} else if lang.contains("ja") {
return include_str!("../lang/ja.yml").to_string();
} else if lang.contains("ko") {
return include_str!("../lang/ko.yml").to_string();
} else if lang.contains("de") {
return include_str!("../lang/de.yml").to_string();
} else if lang.contains("pl") {
return include_str!("../lang/pl.yml").to_string();
} else if lang.contains("pt") {
return include_str!("../lang/pt.yml").to_string();
} else if lang.contains("sv") {
return include_str!("../lang/sv.yml").to_string();
} else if lang.contains("tr") {
return include_str!("../lang/tr.yml").to_string();
} else {
return include_str!("../lang/en.yml").to_string();
}
}
// Ends the current process with an error code (useful in BASH scripting)
pub fn exit() ->! {
process::exit(1);
}
// Gets error message from appropriate localization file provided by language::loader()
// and returns it as a String
pub fn message(code: usize) -> String | {
let locators = YamlLoader::load_from_str(&loader()).unwrap();
let locator = &locators[0]["Error"];
let error = &locator["Error"].as_str().unwrap();
match code {
1..=31 => return format!("{} {}: {}", error, code, &locator[code].as_str().unwrap()),
_ => unreachable!("Internal Logic Error"),
};
} | identifier_body |
|
text.rs | use std::{env, process};
use yaml_rust::YamlLoader;
#[allow(dead_code)]
pub enum | {
GtkInitError,
ScreenshotUnsuccessful,
StrfTimeUnavailable,
PicturesFolderUnavailable,
ScreenshotSaveError,
ImageViewerError,
FileError,
ImgurUploadFailure,
ClipboardUnavailable,
MastodonImageUnsuccessful,
MastodonTootUnsuccessful,
MastodonLoginError,
TwitterImageUnsuccessful,
TwitterTweetUnsucessful,
TwitterLoginError,
NotificationUnavailable,
}
#[allow(dead_code)]
pub enum Text {
UnsupportedWayland,
}
// Retrieves locale settings of the user using LC_CTYPE or LANG
fn locale() -> String {
match env::var("LC_CTYPE") {
Ok(ok) => ok,
Err(_) => match env::var("LANG") {
Ok(ok) => ok,
Err(_) => String::new(),
},
}
}
// Retrieves the correct localization file and returns a String
pub fn loader() -> String {
let lang = locale();
if lang.contains("fr") {
return include_str!("../lang/fr.yml").to_string();
} else if lang.contains("es") {
return include_str!("../lang/es.yml").to_string();
} else if lang.contains("eo") {
return include_str!("../lang/eo.yml").to_string();
} else if lang.contains("CN") && lang.contains("zh") {
return include_str!("../lang/cn.yml").to_string();
} else if lang.contains("TW") && lang.contains("zh") {
return include_str!("../lang/tw.yml").to_string();
} else if lang.contains("ja") {
return include_str!("../lang/ja.yml").to_string();
} else if lang.contains("ko") {
return include_str!("../lang/ko.yml").to_string();
} else if lang.contains("de") {
return include_str!("../lang/de.yml").to_string();
} else if lang.contains("pl") {
return include_str!("../lang/pl.yml").to_string();
} else if lang.contains("pt") {
return include_str!("../lang/pt.yml").to_string();
} else if lang.contains("sv") {
return include_str!("../lang/sv.yml").to_string();
} else if lang.contains("tr") {
return include_str!("../lang/tr.yml").to_string();
} else {
return include_str!("../lang/en.yml").to_string();
}
}
// Ends the current process with an error code (useful in BASH scripting)
pub fn exit() ->! {
process::exit(1);
}
// Gets error message from appropriate localization file provided by language::loader()
// and returns it as a String
pub fn message(code: usize) -> String {
let locators = YamlLoader::load_from_str(&loader()).unwrap();
let locator = &locators[0]["Error"];
let error = &locator["Error"].as_str().unwrap();
match code {
1..=31 => return format!("{} {}: {}", error, code, &locator[code].as_str().unwrap()),
_ => unreachable!("Internal Logic Error"),
};
}
| Errors | identifier_name |
text.rs | use std::{env, process};
use yaml_rust::YamlLoader;
#[allow(dead_code)]
pub enum Errors {
GtkInitError,
ScreenshotUnsuccessful,
StrfTimeUnavailable,
PicturesFolderUnavailable,
ScreenshotSaveError,
ImageViewerError,
FileError,
ImgurUploadFailure,
ClipboardUnavailable,
MastodonImageUnsuccessful,
MastodonTootUnsuccessful,
MastodonLoginError,
TwitterImageUnsuccessful,
TwitterTweetUnsucessful,
TwitterLoginError,
NotificationUnavailable,
}
#[allow(dead_code)]
pub enum Text {
UnsupportedWayland,
}
// Retrieves locale settings of the user using LC_CTYPE or LANG
fn locale() -> String {
match env::var("LC_CTYPE") {
Ok(ok) => ok,
Err(_) => match env::var("LANG") {
Ok(ok) => ok,
Err(_) => String::new(),
},
}
}
// Retrieves the correct localization file and returns a String
pub fn loader() -> String {
let lang = locale();
if lang.contains("fr") {
return include_str!("../lang/fr.yml").to_string();
} else if lang.contains("es") {
return include_str!("../lang/es.yml").to_string();
} else if lang.contains("eo") {
return include_str!("../lang/eo.yml").to_string();
} else if lang.contains("CN") && lang.contains("zh") {
return include_str!("../lang/cn.yml").to_string();
} else if lang.contains("TW") && lang.contains("zh") {
return include_str!("../lang/tw.yml").to_string();
} else if lang.contains("ja") {
return include_str!("../lang/ja.yml").to_string();
} else if lang.contains("ko") {
return include_str!("../lang/ko.yml").to_string(); | } else if lang.contains("de") {
return include_str!("../lang/de.yml").to_string();
} else if lang.contains("pl") {
return include_str!("../lang/pl.yml").to_string();
} else if lang.contains("pt") {
return include_str!("../lang/pt.yml").to_string();
} else if lang.contains("sv") {
return include_str!("../lang/sv.yml").to_string();
} else if lang.contains("tr") {
return include_str!("../lang/tr.yml").to_string();
} else {
return include_str!("../lang/en.yml").to_string();
}
}
// Ends the current process with an error code (useful in BASH scripting)
pub fn exit() ->! {
process::exit(1);
}
// Gets error message from appropriate localization file provided by language::loader()
// and returns it as a String
pub fn message(code: usize) -> String {
let locators = YamlLoader::load_from_str(&loader()).unwrap();
let locator = &locators[0]["Error"];
let error = &locator["Error"].as_str().unwrap();
match code {
1..=31 => return format!("{} {}: {}", error, code, &locator[code].as_str().unwrap()),
_ => unreachable!("Internal Logic Error"),
};
} | random_line_split |
|
string_expressions.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//! String expressions
use crate::error::{DataFusionError, Result};
use arrow::array::{Array, ArrayRef, StringArray, StringBuilder};
macro_rules! downcast_vec {
($ARGS:expr, $ARRAY_TYPE:ident) => {{
$ARGS
.iter()
.map(|e| match e.as_any().downcast_ref::<$ARRAY_TYPE>() {
Some(array) => Ok(array),
_ => Err(DataFusionError::Internal("failed to downcast".to_string())),
})
}};
}
/// concatenate string columns together.
pub fn | (args: &[ArrayRef]) -> Result<StringArray> {
// downcast all arguments to strings
let args = downcast_vec!(args, StringArray).collect::<Result<Vec<&StringArray>>>()?;
// do not accept 0 arguments.
if args.len() == 0 {
return Err(DataFusionError::Internal(
"Concatenate was called with 0 arguments. It requires at least one."
.to_string(),
));
}
let mut builder = StringBuilder::new(args.len());
// for each entry in the array
for index in 0..args[0].len() {
let mut owned_string: String = "".to_owned();
// if any is null, the result is null
let mut is_null = false;
for arg in &args {
if arg.is_null(index) {
is_null = true;
break; // short-circuit as we already know the result
} else {
owned_string.push_str(&arg.value(index));
}
}
if is_null {
builder.append_null()?;
} else {
builder.append_value(&owned_string)?;
}
}
Ok(builder.finish())
}
| concatenate | identifier_name |
string_expressions.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//! String expressions
use crate::error::{DataFusionError, Result};
use arrow::array::{Array, ArrayRef, StringArray, StringBuilder};
macro_rules! downcast_vec {
($ARGS:expr, $ARRAY_TYPE:ident) => {{
$ARGS
.iter()
.map(|e| match e.as_any().downcast_ref::<$ARRAY_TYPE>() {
Some(array) => Ok(array),
_ => Err(DataFusionError::Internal("failed to downcast".to_string())),
})
}};
}
/// concatenate string columns together.
pub fn concatenate(args: &[ArrayRef]) -> Result<StringArray> {
// downcast all arguments to strings
let args = downcast_vec!(args, StringArray).collect::<Result<Vec<&StringArray>>>()?;
// do not accept 0 arguments.
if args.len() == 0 {
return Err(DataFusionError::Internal(
"Concatenate was called with 0 arguments. It requires at least one."
.to_string(),
));
}
let mut builder = StringBuilder::new(args.len());
// for each entry in the array
for index in 0..args[0].len() {
let mut owned_string: String = "".to_owned();
// if any is null, the result is null
let mut is_null = false;
for arg in &args {
if arg.is_null(index) {
is_null = true;
break; // short-circuit as we already know the result
} else {
owned_string.push_str(&arg.value(index));
}
}
if is_null {
builder.append_null()?;
} else |
}
Ok(builder.finish())
}
| {
builder.append_value(&owned_string)?;
} | conditional_block |
string_expressions.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//! String expressions
use crate::error::{DataFusionError, Result};
use arrow::array::{Array, ArrayRef, StringArray, StringBuilder};
macro_rules! downcast_vec {
($ARGS:expr, $ARRAY_TYPE:ident) => {{
$ARGS
.iter()
.map(|e| match e.as_any().downcast_ref::<$ARRAY_TYPE>() {
Some(array) => Ok(array),
_ => Err(DataFusionError::Internal("failed to downcast".to_string())),
})
}};
}
/// concatenate string columns together.
pub fn concatenate(args: &[ArrayRef]) -> Result<StringArray> | is_null = true;
break; // short-circuit as we already know the result
} else {
owned_string.push_str(&arg.value(index));
}
}
if is_null {
builder.append_null()?;
} else {
builder.append_value(&owned_string)?;
}
}
Ok(builder.finish())
}
| {
// downcast all arguments to strings
let args = downcast_vec!(args, StringArray).collect::<Result<Vec<&StringArray>>>()?;
// do not accept 0 arguments.
if args.len() == 0 {
return Err(DataFusionError::Internal(
"Concatenate was called with 0 arguments. It requires at least one."
.to_string(),
));
}
let mut builder = StringBuilder::new(args.len());
// for each entry in the array
for index in 0..args[0].len() {
let mut owned_string: String = "".to_owned();
// if any is null, the result is null
let mut is_null = false;
for arg in &args {
if arg.is_null(index) { | identifier_body |
string_expressions.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//! String expressions
use crate::error::{DataFusionError, Result};
use arrow::array::{Array, ArrayRef, StringArray, StringBuilder};
macro_rules! downcast_vec {
($ARGS:expr, $ARRAY_TYPE:ident) => {{
$ARGS
.iter()
.map(|e| match e.as_any().downcast_ref::<$ARRAY_TYPE>() {
Some(array) => Ok(array),
_ => Err(DataFusionError::Internal("failed to downcast".to_string())),
})
}};
}
/// concatenate string columns together.
pub fn concatenate(args: &[ArrayRef]) -> Result<StringArray> {
// downcast all arguments to strings
let args = downcast_vec!(args, StringArray).collect::<Result<Vec<&StringArray>>>()?;
// do not accept 0 arguments.
if args.len() == 0 {
return Err(DataFusionError::Internal(
"Concatenate was called with 0 arguments. It requires at least one."
.to_string(),
));
}
let mut builder = StringBuilder::new(args.len());
// for each entry in the array
for index in 0..args[0].len() {
let mut owned_string: String = "".to_owned(); | if arg.is_null(index) {
is_null = true;
break; // short-circuit as we already know the result
} else {
owned_string.push_str(&arg.value(index));
}
}
if is_null {
builder.append_null()?;
} else {
builder.append_value(&owned_string)?;
}
}
Ok(builder.finish())
} |
// if any is null, the result is null
let mut is_null = false;
for arg in &args { | random_line_split |
borrowed-unique-basic.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.
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// Gdb doesn't know about UTF-32 character encoding and will print a rust char as only
// its numerical value.
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *bool_ref
// gdb-check:$1 = true
// gdb-command:print *int_ref
// gdb-check:$2 = -1
// gdb-command:print *char_ref
// gdb-check:$3 = 97
// gdb-command:print/d *i8_ref
// gdb-check:$4 = 68
// gdb-command:print *i16_ref
// gdb-check:$5 = -16
// gdb-command:print *i32_ref
// gdb-check:$6 = -32
// gdb-command:print *i64_ref
// gdb-check:$7 = -64
// gdb-command:print *uint_ref
// gdb-check:$8 = 1
// gdb-command:print/d *u8_ref
// gdb-check:$9 = 100
// gdb-command:print *u16_ref
// gdb-check:$10 = 16
// gdb-command:print *u32_ref
// gdb-check:$11 = 32
// gdb-command:print *u64_ref
// gdb-check:$12 = 64
// gdb-command:print *f32_ref
// gdb-check:$13 = 2.5
// gdb-command:print *f64_ref
// gdb-check:$14 = 3.5
// === LLDB TESTS ==================================================================================
// lldb-command:type format add -f decimal char
// lldb-command:type format add -f decimal 'unsigned char'
// lldb-command:run
// lldb-command:print *bool_ref
// lldb-check:[...]$0 = true
// lldb-command:print *int_ref
// lldb-check:[...]$1 = -1
// d ebugger:print *char_ref
// c heck:[...]$3 = 97
// lldb-command:print *i8_ref
// lldb-check:[...]$2 = 68
// lldb-command:print *i16_ref
// lldb-check:[...]$3 = -16
// lldb-command:print *i32_ref
// lldb-check:[...]$4 = -32
// lldb-command:print *i64_ref
// lldb-check:[...]$5 = -64
// lldb-command:print *uint_ref
// lldb-check:[...]$6 = 1
// lldb-command:print *u8_ref
// lldb-check:[...]$7 = 100
// lldb-command:print *u16_ref
// lldb-check:[...]$8 = 16
// lldb-command:print *u32_ref
// lldb-check:[...]$9 = 32
// lldb-command:print *u64_ref
// lldb-check:[...]$10 = 64
// lldb-command:print *f32_ref
// lldb-check:[...]$11 = 2.5
// lldb-command:print *f64_ref
// lldb-check:[...]$12 = 3.5
#![allow(unused_variables)]
fn main() {
let bool_box: Box<bool> = box true;
let bool_ref: &bool = &*bool_box;
let int_box: Box<int> = box -1;
let int_ref: &int = &*int_box;
let char_box: Box<char> = box 'a';
let char_ref: &char = &*char_box;
let i8_box: Box<i8> = box 68;
let i8_ref: &i8 = &*i8_box;
let i16_box: Box<i16> = box -16;
let i16_ref: &i16 = &*i16_box;
let i32_box: Box<i32> = box -32;
let i32_ref: &i32 = &*i32_box;
let i64_box: Box<i64> = box -64;
let i64_ref: &i64 = &*i64_box;
let uint_box: Box<uint> = box 1;
let uint_ref: &uint = &*uint_box;
let u8_box: Box<u8> = box 100;
let u8_ref: &u8 = &*u8_box;
let u16_box: Box<u16> = box 16;
let u16_ref: &u16 = &*u16_box;
let u32_box: Box<u32> = box 32;
let u32_ref: &u32 = &*u32_box;
let u64_box: Box<u64> = box 64;
let u64_ref: &u64 = &*u64_box;
let f32_box: Box<f32> = box 2.5;
let f32_ref: &f32 = &*f32_box;
let f64_box: Box<f64> = box 3.5;
let f64_ref: &f64 = &*f64_box;
zzz(); // #break
}
fn zzz() | {()} | identifier_body |
|
borrowed-unique-basic.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.
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// Gdb doesn't know about UTF-32 character encoding and will print a rust char as only
// its numerical value.
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *bool_ref
// gdb-check:$1 = true
// gdb-command:print *int_ref
// gdb-check:$2 = -1
// gdb-command:print *char_ref
// gdb-check:$3 = 97
// gdb-command:print/d *i8_ref
// gdb-check:$4 = 68
// gdb-command:print *i16_ref
// gdb-check:$5 = -16
// gdb-command:print *i32_ref
// gdb-check:$6 = -32
// gdb-command:print *i64_ref
// gdb-check:$7 = -64
// gdb-command:print *uint_ref
// gdb-check:$8 = 1
// gdb-command:print/d *u8_ref
// gdb-check:$9 = 100
// gdb-command:print *u16_ref
// gdb-check:$10 = 16
// gdb-command:print *u32_ref
// gdb-check:$11 = 32 |
// gdb-command:print *f32_ref
// gdb-check:$13 = 2.5
// gdb-command:print *f64_ref
// gdb-check:$14 = 3.5
// === LLDB TESTS ==================================================================================
// lldb-command:type format add -f decimal char
// lldb-command:type format add -f decimal 'unsigned char'
// lldb-command:run
// lldb-command:print *bool_ref
// lldb-check:[...]$0 = true
// lldb-command:print *int_ref
// lldb-check:[...]$1 = -1
// d ebugger:print *char_ref
// c heck:[...]$3 = 97
// lldb-command:print *i8_ref
// lldb-check:[...]$2 = 68
// lldb-command:print *i16_ref
// lldb-check:[...]$3 = -16
// lldb-command:print *i32_ref
// lldb-check:[...]$4 = -32
// lldb-command:print *i64_ref
// lldb-check:[...]$5 = -64
// lldb-command:print *uint_ref
// lldb-check:[...]$6 = 1
// lldb-command:print *u8_ref
// lldb-check:[...]$7 = 100
// lldb-command:print *u16_ref
// lldb-check:[...]$8 = 16
// lldb-command:print *u32_ref
// lldb-check:[...]$9 = 32
// lldb-command:print *u64_ref
// lldb-check:[...]$10 = 64
// lldb-command:print *f32_ref
// lldb-check:[...]$11 = 2.5
// lldb-command:print *f64_ref
// lldb-check:[...]$12 = 3.5
#![allow(unused_variables)]
fn main() {
let bool_box: Box<bool> = box true;
let bool_ref: &bool = &*bool_box;
let int_box: Box<int> = box -1;
let int_ref: &int = &*int_box;
let char_box: Box<char> = box 'a';
let char_ref: &char = &*char_box;
let i8_box: Box<i8> = box 68;
let i8_ref: &i8 = &*i8_box;
let i16_box: Box<i16> = box -16;
let i16_ref: &i16 = &*i16_box;
let i32_box: Box<i32> = box -32;
let i32_ref: &i32 = &*i32_box;
let i64_box: Box<i64> = box -64;
let i64_ref: &i64 = &*i64_box;
let uint_box: Box<uint> = box 1;
let uint_ref: &uint = &*uint_box;
let u8_box: Box<u8> = box 100;
let u8_ref: &u8 = &*u8_box;
let u16_box: Box<u16> = box 16;
let u16_ref: &u16 = &*u16_box;
let u32_box: Box<u32> = box 32;
let u32_ref: &u32 = &*u32_box;
let u64_box: Box<u64> = box 64;
let u64_ref: &u64 = &*u64_box;
let f32_box: Box<f32> = box 2.5;
let f32_ref: &f32 = &*f32_box;
let f64_box: Box<f64> = box 3.5;
let f64_ref: &f64 = &*f64_box;
zzz(); // #break
}
fn zzz() {()} |
// gdb-command:print *u64_ref
// gdb-check:$12 = 64 | random_line_split |
borrowed-unique-basic.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.
// ignore-android: FIXME(#10381)
// min-lldb-version: 310
// Gdb doesn't know about UTF-32 character encoding and will print a rust char as only
// its numerical value.
// compile-flags:-g
// === GDB TESTS ===================================================================================
// gdb-command:run
// gdb-command:print *bool_ref
// gdb-check:$1 = true
// gdb-command:print *int_ref
// gdb-check:$2 = -1
// gdb-command:print *char_ref
// gdb-check:$3 = 97
// gdb-command:print/d *i8_ref
// gdb-check:$4 = 68
// gdb-command:print *i16_ref
// gdb-check:$5 = -16
// gdb-command:print *i32_ref
// gdb-check:$6 = -32
// gdb-command:print *i64_ref
// gdb-check:$7 = -64
// gdb-command:print *uint_ref
// gdb-check:$8 = 1
// gdb-command:print/d *u8_ref
// gdb-check:$9 = 100
// gdb-command:print *u16_ref
// gdb-check:$10 = 16
// gdb-command:print *u32_ref
// gdb-check:$11 = 32
// gdb-command:print *u64_ref
// gdb-check:$12 = 64
// gdb-command:print *f32_ref
// gdb-check:$13 = 2.5
// gdb-command:print *f64_ref
// gdb-check:$14 = 3.5
// === LLDB TESTS ==================================================================================
// lldb-command:type format add -f decimal char
// lldb-command:type format add -f decimal 'unsigned char'
// lldb-command:run
// lldb-command:print *bool_ref
// lldb-check:[...]$0 = true
// lldb-command:print *int_ref
// lldb-check:[...]$1 = -1
// d ebugger:print *char_ref
// c heck:[...]$3 = 97
// lldb-command:print *i8_ref
// lldb-check:[...]$2 = 68
// lldb-command:print *i16_ref
// lldb-check:[...]$3 = -16
// lldb-command:print *i32_ref
// lldb-check:[...]$4 = -32
// lldb-command:print *i64_ref
// lldb-check:[...]$5 = -64
// lldb-command:print *uint_ref
// lldb-check:[...]$6 = 1
// lldb-command:print *u8_ref
// lldb-check:[...]$7 = 100
// lldb-command:print *u16_ref
// lldb-check:[...]$8 = 16
// lldb-command:print *u32_ref
// lldb-check:[...]$9 = 32
// lldb-command:print *u64_ref
// lldb-check:[...]$10 = 64
// lldb-command:print *f32_ref
// lldb-check:[...]$11 = 2.5
// lldb-command:print *f64_ref
// lldb-check:[...]$12 = 3.5
#![allow(unused_variables)]
fn main() {
let bool_box: Box<bool> = box true;
let bool_ref: &bool = &*bool_box;
let int_box: Box<int> = box -1;
let int_ref: &int = &*int_box;
let char_box: Box<char> = box 'a';
let char_ref: &char = &*char_box;
let i8_box: Box<i8> = box 68;
let i8_ref: &i8 = &*i8_box;
let i16_box: Box<i16> = box -16;
let i16_ref: &i16 = &*i16_box;
let i32_box: Box<i32> = box -32;
let i32_ref: &i32 = &*i32_box;
let i64_box: Box<i64> = box -64;
let i64_ref: &i64 = &*i64_box;
let uint_box: Box<uint> = box 1;
let uint_ref: &uint = &*uint_box;
let u8_box: Box<u8> = box 100;
let u8_ref: &u8 = &*u8_box;
let u16_box: Box<u16> = box 16;
let u16_ref: &u16 = &*u16_box;
let u32_box: Box<u32> = box 32;
let u32_ref: &u32 = &*u32_box;
let u64_box: Box<u64> = box 64;
let u64_ref: &u64 = &*u64_box;
let f32_box: Box<f32> = box 2.5;
let f32_ref: &f32 = &*f32_box;
let f64_box: Box<f64> = box 3.5;
let f64_ref: &f64 = &*f64_box;
zzz(); // #break
}
fn | () {()}
| zzz | identifier_name |
circd.rs | ///////////////////////////////////////////////////////////////////////////////
#![feature(phase)]
extern crate circ_comms;
extern crate irc;
#[phase(plugin, link)] extern crate log;
extern crate time;
///////////////////////////////////////////////////////////////////////////////
use irc::data::config::Config;
use std::io::fs;
use std::io::net::pipe::UnixListener;
use std::io::{Listener, Acceptor};
use std::os;
use std::io::fs::PathExtensions;
mod connection;
mod irc_channel;
///////////////////////////////////////////////////////////////////////////////
fn process_args() -> Config
{
match os::args().tail()
{
[ref arg] =>
{
let filename = Path::new(arg.as_slice());
if!filename.exists()
{
panic!("File {} doesn't exist", arg);
}
Config::load(filename).unwrap()
},
_ => panic!("Configuration file must be specified")
}
}
///////////////////////////////////////////////////////////////////////////////
fn | ()
{
let config = process_args();
let connection = connection::Connection::new(config);
let socket = Path::new(circ_comms::address());
if socket.exists()
{
match fs::unlink(&socket)
{
Ok(_) => (),
Err(e) => panic!("Unable to remove {}: {}", circ_comms::address(), e)
}
}
let stream = UnixListener::bind(&socket);
for c in stream.listen().incoming()
{
let mut client = match c
{
Ok(x) => x,
Err(e) => { println!("Failed to get client: {}", e); continue }
};
let request = match circ_comms::read_request(&mut client)
{
Some(r) => r,
None => continue
};
match request
{
circ_comms::Request::ListChannels =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetStatus =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetMessages(_) =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetUsers(_) => (),
circ_comms::Request::Join(_) => connection.request(request),
circ_comms::Request::Part(_) => connection.request(request),
circ_comms::Request::SendMessage(_, _) => connection.request(request),
circ_comms::Request::Quit => {connection.request(request); break} // not a clean quit, but it works
}
}
}
| main | identifier_name |
circd.rs | ///////////////////////////////////////////////////////////////////////////////
#![feature(phase)]
extern crate circ_comms;
extern crate irc;
#[phase(plugin, link)] extern crate log;
extern crate time;
///////////////////////////////////////////////////////////////////////////////
use irc::data::config::Config;
use std::io::fs;
use std::io::net::pipe::UnixListener;
use std::io::{Listener, Acceptor};
use std::os;
use std::io::fs::PathExtensions;
mod connection;
mod irc_channel;
///////////////////////////////////////////////////////////////////////////////
fn process_args() -> Config
{
match os::args().tail()
{
[ref arg] =>
{
let filename = Path::new(arg.as_slice());
if!filename.exists()
{ |
Config::load(filename).unwrap()
},
_ => panic!("Configuration file must be specified")
}
}
///////////////////////////////////////////////////////////////////////////////
fn main()
{
let config = process_args();
let connection = connection::Connection::new(config);
let socket = Path::new(circ_comms::address());
if socket.exists()
{
match fs::unlink(&socket)
{
Ok(_) => (),
Err(e) => panic!("Unable to remove {}: {}", circ_comms::address(), e)
}
}
let stream = UnixListener::bind(&socket);
for c in stream.listen().incoming()
{
let mut client = match c
{
Ok(x) => x,
Err(e) => { println!("Failed to get client: {}", e); continue }
};
let request = match circ_comms::read_request(&mut client)
{
Some(r) => r,
None => continue
};
match request
{
circ_comms::Request::ListChannels =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetStatus =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetMessages(_) =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetUsers(_) => (),
circ_comms::Request::Join(_) => connection.request(request),
circ_comms::Request::Part(_) => connection.request(request),
circ_comms::Request::SendMessage(_, _) => connection.request(request),
circ_comms::Request::Quit => {connection.request(request); break} // not a clean quit, but it works
}
}
} | panic!("File {} doesn't exist", arg);
} | random_line_split |
circd.rs | ///////////////////////////////////////////////////////////////////////////////
#![feature(phase)]
extern crate circ_comms;
extern crate irc;
#[phase(plugin, link)] extern crate log;
extern crate time;
///////////////////////////////////////////////////////////////////////////////
use irc::data::config::Config;
use std::io::fs;
use std::io::net::pipe::UnixListener;
use std::io::{Listener, Acceptor};
use std::os;
use std::io::fs::PathExtensions;
mod connection;
mod irc_channel;
///////////////////////////////////////////////////////////////////////////////
fn process_args() -> Config
|
///////////////////////////////////////////////////////////////////////////////
fn main()
{
let config = process_args();
let connection = connection::Connection::new(config);
let socket = Path::new(circ_comms::address());
if socket.exists()
{
match fs::unlink(&socket)
{
Ok(_) => (),
Err(e) => panic!("Unable to remove {}: {}", circ_comms::address(), e)
}
}
let stream = UnixListener::bind(&socket);
for c in stream.listen().incoming()
{
let mut client = match c
{
Ok(x) => x,
Err(e) => { println!("Failed to get client: {}", e); continue }
};
let request = match circ_comms::read_request(&mut client)
{
Some(r) => r,
None => continue
};
match request
{
circ_comms::Request::ListChannels =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetStatus =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetMessages(_) =>
circ_comms::write_response(&mut client,
connection.request_response(request)),
circ_comms::Request::GetUsers(_) => (),
circ_comms::Request::Join(_) => connection.request(request),
circ_comms::Request::Part(_) => connection.request(request),
circ_comms::Request::SendMessage(_, _) => connection.request(request),
circ_comms::Request::Quit => {connection.request(request); break} // not a clean quit, but it works
}
}
}
| {
match os::args().tail()
{
[ref arg] =>
{
let filename = Path::new(arg.as_slice());
if !filename.exists()
{
panic!("File {} doesn't exist", arg);
}
Config::load(filename).unwrap()
},
_ => panic!("Configuration file must be specified")
}
} | identifier_body |
image_decoder_d.rs | /*!
A application that uses the `image-decoder` feature to load resources and display them.
Requires the following features: `cargo run --example image_decoder_d --features "image-decoder file-dialog"`
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
use std::{env};
use std::cell::RefCell;
#[derive(Default, NwgUi)]
pub struct ImageDecoderApp {
// The image that will be loaded dynamically
loaded_image: RefCell<Option<nwg::Bitmap>>,
#[nwg_control(size: (400, 300), position: (400, 150), title: "Image decoder")]
#[nwg_events( OnWindowClose: [ImageDecoderApp::exit] )]
window: nwg::Window,
#[nwg_layout(parent: window, max_row: Some(5), max_column: Some(5) )]
main_layout: nwg::GridLayout,
#[nwg_resource]
decoder: nwg::ImageDecoder,
#[nwg_resource(title: "Open File", action: nwg::FileDialogAction::Open, filters: "Png(*.png)|Jpeg(*.jpg;*.jpeg)|DDS(*.dds)|TIFF(*.tiff)|BMP(*.bmp)|Any (*.*)")]
dialog: nwg::FileDialog,
#[nwg_control(text: "Open", focus: true)]
#[nwg_layout_item(layout: main_layout, col: 0, row: 0)]
#[nwg_events(OnButtonClick: [ImageDecoderApp::open_file])]
open_btn: nwg::Button,
#[nwg_control(readonly: true)]
#[nwg_layout_item(layout: main_layout, col: 1, row: 0, col_span: 4)]
file_name: nwg::TextInput,
#[nwg_control]
#[nwg_layout_item(layout: main_layout, col: 0, row: 1, col_span: 5, row_span: 4)]
img: nwg::ImageFrame,
}
impl ImageDecoderApp {
fn open_file(&self) {
if let Ok(d) = env::current_dir() {
if let Some(d) = d.to_str() {
self.dialog.set_default_folder(d).expect("Failed to set default folder.");
}
}
if self.dialog.run(Some(&self.window)) {
self.file_name.set_text("");
if let Ok(directory) = self.dialog.get_selected_item() {
let dir = directory.into_string().unwrap();
self.file_name.set_text(&dir);
self.read_file();
}
}
}
fn read_file(&self) {
println!("{}", self.file_name.text());
let image = match self.decoder.from_filename(&self.file_name.text()) {
Ok(img) => img,
Err(_) => { println!("Could not read image!"); return; }
};
println!("Frame count: {}", image.frame_count());
println!("Format: {:?}", image.container_format());
let frame = match image.frame(0) {
Ok(bmp) => bmp,
Err(_) => { println!("Could not read image frame!"); return; }
};
println!("Resolution: {:?}", frame.resolution());
println!("Size: {:?}", frame.size());
// Create a new Bitmap image from the image data
match frame.as_bitmap() {
Ok(bitmap) => {
let mut img = self.loaded_image.borrow_mut();
img.replace(bitmap);
self.img.set_bitmap(img.as_ref());
},
Err(_) => { println!("Could not convert image to bitmap!"); }
}
}
fn exit(&self) {
nwg::stop_thread_dispatch();
}
}
fn main() | {
nwg::init().expect("Failed to init Native Windows GUI");
nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
let _app = ImageDecoderApp::build_ui(Default::default()).expect("Failed to build UI");
nwg::dispatch_thread_events();
} | identifier_body |
|
image_decoder_d.rs | /*!
A application that uses the `image-decoder` feature to load resources and display them.
Requires the following features: `cargo run --example image_decoder_d --features "image-decoder file-dialog"`
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
use std::{env};
use std::cell::RefCell;
#[derive(Default, NwgUi)]
pub struct ImageDecoderApp {
// The image that will be loaded dynamically
loaded_image: RefCell<Option<nwg::Bitmap>>,
#[nwg_control(size: (400, 300), position: (400, 150), title: "Image decoder")]
#[nwg_events( OnWindowClose: [ImageDecoderApp::exit] )]
window: nwg::Window,
#[nwg_layout(parent: window, max_row: Some(5), max_column: Some(5) )]
main_layout: nwg::GridLayout,
#[nwg_resource]
decoder: nwg::ImageDecoder,
#[nwg_resource(title: "Open File", action: nwg::FileDialogAction::Open, filters: "Png(*.png)|Jpeg(*.jpg;*.jpeg)|DDS(*.dds)|TIFF(*.tiff)|BMP(*.bmp)|Any (*.*)")]
dialog: nwg::FileDialog,
#[nwg_control(text: "Open", focus: true)]
#[nwg_layout_item(layout: main_layout, col: 0, row: 0)]
#[nwg_events(OnButtonClick: [ImageDecoderApp::open_file])]
open_btn: nwg::Button,
#[nwg_control(readonly: true)]
#[nwg_layout_item(layout: main_layout, col: 1, row: 0, col_span: 4)]
file_name: nwg::TextInput,
#[nwg_control]
#[nwg_layout_item(layout: main_layout, col: 0, row: 1, col_span: 5, row_span: 4)]
img: nwg::ImageFrame,
}
impl ImageDecoderApp {
fn open_file(&self) {
if let Ok(d) = env::current_dir() {
if let Some(d) = d.to_str() {
self.dialog.set_default_folder(d).expect("Failed to set default folder."); | if let Ok(directory) = self.dialog.get_selected_item() {
let dir = directory.into_string().unwrap();
self.file_name.set_text(&dir);
self.read_file();
}
}
}
fn read_file(&self) {
println!("{}", self.file_name.text());
let image = match self.decoder.from_filename(&self.file_name.text()) {
Ok(img) => img,
Err(_) => { println!("Could not read image!"); return; }
};
println!("Frame count: {}", image.frame_count());
println!("Format: {:?}", image.container_format());
let frame = match image.frame(0) {
Ok(bmp) => bmp,
Err(_) => { println!("Could not read image frame!"); return; }
};
println!("Resolution: {:?}", frame.resolution());
println!("Size: {:?}", frame.size());
// Create a new Bitmap image from the image data
match frame.as_bitmap() {
Ok(bitmap) => {
let mut img = self.loaded_image.borrow_mut();
img.replace(bitmap);
self.img.set_bitmap(img.as_ref());
},
Err(_) => { println!("Could not convert image to bitmap!"); }
}
}
fn exit(&self) {
nwg::stop_thread_dispatch();
}
}
fn main() {
nwg::init().expect("Failed to init Native Windows GUI");
nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
let _app = ImageDecoderApp::build_ui(Default::default()).expect("Failed to build UI");
nwg::dispatch_thread_events();
} | }
}
if self.dialog.run(Some(&self.window)) {
self.file_name.set_text(""); | random_line_split |
image_decoder_d.rs | /*!
A application that uses the `image-decoder` feature to load resources and display them.
Requires the following features: `cargo run --example image_decoder_d --features "image-decoder file-dialog"`
*/
extern crate native_windows_gui as nwg;
extern crate native_windows_derive as nwd;
use nwd::NwgUi;
use nwg::NativeUi;
use std::{env};
use std::cell::RefCell;
#[derive(Default, NwgUi)]
pub struct ImageDecoderApp {
// The image that will be loaded dynamically
loaded_image: RefCell<Option<nwg::Bitmap>>,
#[nwg_control(size: (400, 300), position: (400, 150), title: "Image decoder")]
#[nwg_events( OnWindowClose: [ImageDecoderApp::exit] )]
window: nwg::Window,
#[nwg_layout(parent: window, max_row: Some(5), max_column: Some(5) )]
main_layout: nwg::GridLayout,
#[nwg_resource]
decoder: nwg::ImageDecoder,
#[nwg_resource(title: "Open File", action: nwg::FileDialogAction::Open, filters: "Png(*.png)|Jpeg(*.jpg;*.jpeg)|DDS(*.dds)|TIFF(*.tiff)|BMP(*.bmp)|Any (*.*)")]
dialog: nwg::FileDialog,
#[nwg_control(text: "Open", focus: true)]
#[nwg_layout_item(layout: main_layout, col: 0, row: 0)]
#[nwg_events(OnButtonClick: [ImageDecoderApp::open_file])]
open_btn: nwg::Button,
#[nwg_control(readonly: true)]
#[nwg_layout_item(layout: main_layout, col: 1, row: 0, col_span: 4)]
file_name: nwg::TextInput,
#[nwg_control]
#[nwg_layout_item(layout: main_layout, col: 0, row: 1, col_span: 5, row_span: 4)]
img: nwg::ImageFrame,
}
impl ImageDecoderApp {
fn open_file(&self) {
if let Ok(d) = env::current_dir() {
if let Some(d) = d.to_str() {
self.dialog.set_default_folder(d).expect("Failed to set default folder.");
}
}
if self.dialog.run(Some(&self.window)) {
self.file_name.set_text("");
if let Ok(directory) = self.dialog.get_selected_item() {
let dir = directory.into_string().unwrap();
self.file_name.set_text(&dir);
self.read_file();
}
}
}
fn read_file(&self) {
println!("{}", self.file_name.text());
let image = match self.decoder.from_filename(&self.file_name.text()) {
Ok(img) => img,
Err(_) => { println!("Could not read image!"); return; }
};
println!("Frame count: {}", image.frame_count());
println!("Format: {:?}", image.container_format());
let frame = match image.frame(0) {
Ok(bmp) => bmp,
Err(_) => { println!("Could not read image frame!"); return; }
};
println!("Resolution: {:?}", frame.resolution());
println!("Size: {:?}", frame.size());
// Create a new Bitmap image from the image data
match frame.as_bitmap() {
Ok(bitmap) => {
let mut img = self.loaded_image.borrow_mut();
img.replace(bitmap);
self.img.set_bitmap(img.as_ref());
},
Err(_) => { println!("Could not convert image to bitmap!"); }
}
}
fn exit(&self) {
nwg::stop_thread_dispatch();
}
}
fn | () {
nwg::init().expect("Failed to init Native Windows GUI");
nwg::Font::set_global_family("Segoe UI").expect("Failed to set default font");
let _app = ImageDecoderApp::build_ui(Default::default()).expect("Failed to build UI");
nwg::dispatch_thread_events();
}
| main | identifier_name |
htmldatalistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods;
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::codegen::InheritTypes::{HTMLDataListElementDerived, HTMLOptionElementDerived};
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::Element;
use dom::element::ElementTypeId;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlcollection::{CollectionFilter, HTMLCollection};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId, window_from_node};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLDataListElement {
htmlelement: HTMLElement
}
impl HTMLDataListElementDerived for EventTarget {
fn is_htmldatalistelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLDataListElement)))
}
}
impl HTMLDataListElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLDataListElement {
HTMLDataListElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLDataListElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLDataListElement> {
let element = HTMLDataListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap)
}
}
impl HTMLDataListElementMethods for HTMLDataListElement {
// https://html.spec.whatwg.org/multipage/#dom-datalist-options
fn Options(&self) -> Root<HTMLCollection> {
#[derive(JSTraceable, HeapSizeOf)]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool |
}
let node = NodeCast::from_ref(self);
let filter = box HTMLDataListOptionsFilter;
let window = window_from_node(node);
HTMLCollection::create(window.r(), node, filter)
}
}
| {
elem.is_htmloptionelement()
} | identifier_body |
htmldatalistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods;
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::codegen::InheritTypes::{HTMLDataListElementDerived, HTMLOptionElementDerived};
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::Element;
use dom::element::ElementTypeId;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlcollection::{CollectionFilter, HTMLCollection};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId, window_from_node};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLDataListElement {
htmlelement: HTMLElement
}
impl HTMLDataListElementDerived for EventTarget {
fn is_htmldatalistelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLDataListElement)))
}
}
impl HTMLDataListElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLDataListElement {
HTMLDataListElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLDataListElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLDataListElement> { | }
}
impl HTMLDataListElementMethods for HTMLDataListElement {
// https://html.spec.whatwg.org/multipage/#dom-datalist-options
fn Options(&self) -> Root<HTMLCollection> {
#[derive(JSTraceable, HeapSizeOf)]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is_htmloptionelement()
}
}
let node = NodeCast::from_ref(self);
let filter = box HTMLDataListOptionsFilter;
let window = window_from_node(node);
HTMLCollection::create(window.r(), node, filter)
}
} | let element = HTMLDataListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap) | random_line_split |
htmldatalistelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding;
use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods;
use dom::bindings::codegen::InheritTypes::NodeCast;
use dom::bindings::codegen::InheritTypes::{HTMLDataListElementDerived, HTMLOptionElementDerived};
use dom::bindings::js::Root;
use dom::document::Document;
use dom::element::Element;
use dom::element::ElementTypeId;
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlcollection::{CollectionFilter, HTMLCollection};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeTypeId, window_from_node};
use util::str::DOMString;
#[dom_struct]
pub struct HTMLDataListElement {
htmlelement: HTMLElement
}
impl HTMLDataListElementDerived for EventTarget {
fn is_htmldatalistelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLDataListElement)))
}
}
impl HTMLDataListElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLDataListElement {
HTMLDataListElement {
htmlelement:
HTMLElement::new_inherited(HTMLElementTypeId::HTMLDataListElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn | (localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLDataListElement> {
let element = HTMLDataListElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLDataListElementBinding::Wrap)
}
}
impl HTMLDataListElementMethods for HTMLDataListElement {
// https://html.spec.whatwg.org/multipage/#dom-datalist-options
fn Options(&self) -> Root<HTMLCollection> {
#[derive(JSTraceable, HeapSizeOf)]
struct HTMLDataListOptionsFilter;
impl CollectionFilter for HTMLDataListOptionsFilter {
fn filter(&self, elem: &Element, _root: &Node) -> bool {
elem.is_htmloptionelement()
}
}
let node = NodeCast::from_ref(self);
let filter = box HTMLDataListOptionsFilter;
let window = window_from_node(node);
HTMLCollection::create(window.r(), node, filter)
}
}
| new | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.