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 |
|---|---|---|---|---|
nist-spce.rs |
//! Testing energy computation for SPC/E water using data from
//! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff
//! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-10å-cutoff
extern crate lumol;
extern crate lumol_input as input;
use lumol::sys::{System, UnitCell};
use lumol::sys::Trajectory;
use lumol::energy::{PairInteraction, LennardJones, NullPotential};
use lumol::energy::{Ewald, PairRestriction, CoulombicPotential};
use lumol::consts::K_BOLTZMANN;
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
pub fn get_system(path: &str, cutoff: f64) -> System {
let path = Path::new(file!()).parent().unwrap()
.join("data")
.join("nist-spce")
.join(path);
let mut system = Trajectory::open(&path)
.and_then(|mut traj| traj.read())
.unwrap();
let mut file = File::open(path).unwrap();
let mut buffer = String::new();
file.read_to_string(&mut buffer).unwrap();
let line = buffer.lines().skip(1).next().unwrap();
let mut splited = line.split_whitespace();
assert_eq!(splited.next(), Some("cell:"));
let a: f64 = splited.next().expect("Missing 'a' cell parameter")
.parse().expect("'a' cell parameter is not a float");
let b: f64 = splited.next().expect("Missing 'b' cell parameter")
.parse().expect("'b' cell parameter is not a float");
let c: f64 = splited.next().expect("Missing 'c' cell parameter")
.parse().expect("'c' cell parameter is not a float");
system.set_cell(UnitCell::ortho(a, b, c));
for i in 0..system.size() {
if i % 3 == 0 {
system.add_bond(i, i + 1);
system.add_bond(i, i + 2);
}
}
for particle in &mut system {
particle.charge = match particle.name() {
"H" => 0.42380,
"O" => -2.0 * 0.42380,
other => panic!("Unknown particle name: {}", other)
}
}
let mut lj = PairInteraction::new(Box::new(LennardJones{
epsilon: 78.19743111 * K_BOLTZMANN,
sigma: 3.16555789
}), cutoff);
lj.enable_tail_corrections();
system.interactions_mut().add_pair("O", "O", lj);
system.interactions_mut().add_pair("O", "H",
PairInteraction::new(Box::new(NullPotential), cutoff)
);
system.interactions_mut().add_pair("H", "H",
PairInteraction::new(Box::new(NullPotential), cutoff)
);
let mut ewald = Ewald::new(cutoff, 5);
ewald.set_restriction(PairRestriction::InterMolecular);
ewald.set_alpha(5.6 / f64::min(f64::min(a, b), c));
system.interactions_mut().set_coulomb(Box::new(ewald));
return system;
}
mod cutoff_9 {
use super::*;
use lumol::consts::K_BOLTZMANN;
#[test]
fn nist1() {
let system = get_system("spce-1.xyz", 9.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -4.88608e5;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist2() {
let system = get_system("spce-2.xyz", 9.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -1.06602e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist3() {
let system = get_system("spce-3.xyz", 9.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -1.71488e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist4() {
let system = get_system("spce-4.xyz", 9.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -3.08010e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
}
mod cutoff_10 {
use super::*;
use lumol::consts::K_BOLTZMANN;
#[test]
fn nist1() {
let system = get_system("spce-1.xyz", 10.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -4.88604e5;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist2() {
let system = get_system("spce-2.xyz", 10.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -1.06590e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist3() {
let system = get_system("spce-3.xyz", 10.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -1.71488e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist4() {
let system = get_system("spce-4.xyz", 10.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -3.20501e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
} | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 G. Fraux — BSD license | random_line_split | |
nist-spce.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) 2015-2016 G. Fraux — BSD license
//! Testing energy computation for SPC/E water using data from
//! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-9%C3%A5-cutoff
//! https://www.nist.gov/mml/csd/chemical-informatics-research-group/spce-water-reference-calculations-10å-cutoff
extern crate lumol;
extern crate lumol_input as input;
use lumol::sys::{System, UnitCell};
use lumol::sys::Trajectory;
use lumol::energy::{PairInteraction, LennardJones, NullPotential};
use lumol::energy::{Ewald, PairRestriction, CoulombicPotential};
use lumol::consts::K_BOLTZMANN;
use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
pub fn get_system(path: &str, cutoff: f64) -> System {
let path = Path::new(file!()).parent().unwrap()
.join("data")
.join("nist-spce")
.join(path);
let mut system = Trajectory::open(&path)
.and_then(|mut traj| traj.read())
.unwrap();
let mut file = File::open(path).unwrap();
let mut buffer = String::new();
file.read_to_string(&mut buffer).unwrap();
let line = buffer.lines().skip(1).next().unwrap();
let mut splited = line.split_whitespace();
assert_eq!(splited.next(), Some("cell:"));
let a: f64 = splited.next().expect("Missing 'a' cell parameter")
.parse().expect("'a' cell parameter is not a float");
let b: f64 = splited.next().expect("Missing 'b' cell parameter")
.parse().expect("'b' cell parameter is not a float");
let c: f64 = splited.next().expect("Missing 'c' cell parameter")
.parse().expect("'c' cell parameter is not a float");
system.set_cell(UnitCell::ortho(a, b, c));
for i in 0..system.size() {
if i % 3 == 0 {
system.add_bond(i, i + 1);
system.add_bond(i, i + 2);
}
}
for particle in &mut system {
particle.charge = match particle.name() {
"H" => 0.42380,
"O" => -2.0 * 0.42380,
other => panic!("Unknown particle name: {}", other)
}
}
let mut lj = PairInteraction::new(Box::new(LennardJones{
epsilon: 78.19743111 * K_BOLTZMANN,
sigma: 3.16555789
}), cutoff);
lj.enable_tail_corrections();
system.interactions_mut().add_pair("O", "O", lj);
system.interactions_mut().add_pair("O", "H",
PairInteraction::new(Box::new(NullPotential), cutoff)
);
system.interactions_mut().add_pair("H", "H",
PairInteraction::new(Box::new(NullPotential), cutoff)
);
let mut ewald = Ewald::new(cutoff, 5);
ewald.set_restriction(PairRestriction::InterMolecular);
ewald.set_alpha(5.6 / f64::min(f64::min(a, b), c));
system.interactions_mut().set_coulomb(Box::new(ewald));
return system;
}
mod cutoff_9 {
use super::*;
use lumol::consts::K_BOLTZMANN;
#[test]
fn nist1() {
let system = get_system("spce-1.xyz", 9.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -4.88608e5;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist2() {
| #[test]
fn nist3() {
let system = get_system("spce-3.xyz", 9.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -1.71488e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist4() {
let system = get_system("spce-4.xyz", 9.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -3.08010e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
}
mod cutoff_10 {
use super::*;
use lumol::consts::K_BOLTZMANN;
#[test]
fn nist1() {
let system = get_system("spce-1.xyz", 10.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -4.88604e5;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist2() {
let system = get_system("spce-2.xyz", 10.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -1.06590e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist3() {
let system = get_system("spce-3.xyz", 10.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -1.71488e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
#[test]
fn nist4() {
let system = get_system("spce-4.xyz", 10.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -3.20501e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
}
| let system = get_system("spce-2.xyz", 9.0);
let energy = system.potential_energy() / K_BOLTZMANN;
let expected = -1.06602e6;
assert!(f64::abs((energy - expected)/expected) < 1e-3);
}
| identifier_body |
vec-to_str.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.
#[feature(managed_boxes)];
pub fn | () {
assert_eq!((~[0, 1]).to_str(), ~"[0, 1]");
assert_eq!((&[1, 2]).to_str(), ~"[1, 2]");
assert_eq!((@[2, 3]).to_str(), ~"[2, 3]");
let foo = ~[3, 4];
let bar = &[4, 5];
let baz = @[5, 6];
assert_eq!(foo.to_str(), ~"[3, 4]");
assert_eq!(bar.to_str(), ~"[4, 5]");
assert_eq!(baz.to_str(), ~"[5, 6]");
}
| main | identifier_name |
vec-to_str.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.
#[feature(managed_boxes)];
pub fn main() {
assert_eq!((~[0, 1]).to_str(), ~"[0, 1]");
assert_eq!((&[1, 2]).to_str(), ~"[1, 2]"); |
assert_eq!(foo.to_str(), ~"[3, 4]");
assert_eq!(bar.to_str(), ~"[4, 5]");
assert_eq!(baz.to_str(), ~"[5, 6]");
} | assert_eq!((@[2, 3]).to_str(), ~"[2, 3]");
let foo = ~[3, 4];
let bar = &[4, 5];
let baz = @[5, 6]; | random_line_split |
vec-to_str.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.
#[feature(managed_boxes)];
pub fn main() | {
assert_eq!((~[0, 1]).to_str(), ~"[0, 1]");
assert_eq!((&[1, 2]).to_str(), ~"[1, 2]");
assert_eq!((@[2, 3]).to_str(), ~"[2, 3]");
let foo = ~[3, 4];
let bar = &[4, 5];
let baz = @[5, 6];
assert_eq!(foo.to_str(), ~"[3, 4]");
assert_eq!(bar.to_str(), ~"[4, 5]");
assert_eq!(baz.to_str(), ~"[5, 6]");
} | identifier_body | |
events.rs | //! (De)serializable types for the events in the [Matrix](https://matrix.org) specification.
//! These types are used by other Ruma crates.
//!
//! All data exchanged over Matrix is expressed as an event.
//! Different event types represent different actions, such as joining a room or sending a message.
//! Events are stored and transmitted as simple JSON structures.
//! While anyone can create a new event type for their own purposes, the Matrix specification
//! defines a number of event types which are considered core to the protocol, and Matrix clients
//! and servers must understand their semantics.
//! This module contains Rust types for each of the event types defined by the specification and
//! facilities for extending the event system for custom event types.
//!
//! # Event types
//!
//! This module includes a Rust enum called [`EventType`], which provides a simple enumeration of
//! all the event types defined by the Matrix specification. Matrix event types are serialized to
//! JSON strings in [reverse domain name
//! notation](https://en.wikipedia.org/wiki/Reverse_domain_name_notation), although the core event
//! types all use the special "m" TLD, e.g. `m.room.message`.
//!
//! # Core event types
//!
//! This module includes Rust types for every one of the event types in the Matrix specification.
//! To better organize the crate, these types live in separate modules with a hierarchy that
//! matches the reverse domain name notation of the event type.
//! For example, the `m.room.message` event lives at
//! `ruma_common::events::::room::message::MessageLikeEvent`. Each type's module also contains a
//! Rust type for that event type's `content` field, and any other supporting types required by the
//! event's other fields.
//!
//! # Extending Ruma with custom events
//!
//! For our examples we will start with a simple custom state event. `ruma_event`
//! specifies the state event's `type` and it's [`kind`](EventKind).
//!
//! ```rust
//! use ruma_common::events::macros::EventContent;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
//! #[ruma_event(type = "org.example.event", kind = State)]
//! pub struct ExampleContent {
//! field: String,
//! }
//! ```
//!
//! This can be used with events structs, such as passing it into
//! `ruma::api::client::state::send_state_event`'s `Request`.
//!
//! As a more advanced example we create a reaction message event. For this event we will use a
//! [`SyncMessageLikeEvent`] struct but any [`MessageLikeEvent`] struct would work.
//!
//! ```rust
//! use ruma_common::events::{macros::EventContent, SyncMessageLikeEvent};
//! use ruma_common::EventId;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Clone, Debug, Deserialize, Serialize)]
//! #[serde(tag = "rel_type")]
//! pub enum RelatesTo {
//! #[serde(rename = "m.annotation")]
//! Annotation {
//! /// The event this reaction relates to.
//! event_id: Box<EventId>,
//! /// The displayable content of the reaction.
//! key: String,
//! },
//!
//! /// Since this event is not fully specified in the Matrix spec
//! /// it may change or types may be added, we are ready!
//! #[serde(rename = "m.whatever")]
//! Whatever,
//! }
//!
//! /// The payload for our reaction event.
//! #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
//! #[ruma_event(type = "m.reaction", kind = MessageLike)]
//! pub struct ReactionEventContent {
//! #[serde(rename = "m.relates_to")]
//! pub relates_to: RelatesTo,
//! }
//!
//! let json = serde_json::json!({
//! "content": {
//! "m.relates_to": {
//! "event_id": "$xxxx-xxxx",
//! "key": "👍",
//! "rel_type": "m.annotation"
//! }
//! },
//! "event_id": "$xxxx-xxxx",
//! "origin_server_ts": 1,
//! "sender": "@someone:example.org",
//! "type": "m.reaction",
//! "unsigned": {
//! "age": 85
//! }
//! });
//!
//! // The downside of this event is we cannot use it with event enums,
//! // but could be deserialized from a `Raw<_>` that has failed to deserialize.
//! matches::assert_matches!(
//! serde_json::from_value::<SyncMessageLikeEvent<ReactionEventContent>>(json),
//! Ok(SyncMessageLikeEvent {
//! content: ReactionEventContent {
//! relates_to: RelatesTo::Annotation { key,.. },
//! },
//! ..
//! }) if key == "👍"
//! );
//! ```
//!
//! # Serialization and deserialization
//!
//! All concrete event types in this module can be serialized via the `Serialize` trait from
//! [serde](https://serde.rs/) and can be deserialized from a `Raw<EventType>`. In order to
//! handle incoming data that may not conform to this module's strict definitions of event
//! structures, deserialization will return `Raw::Err` on error. This error covers both
//! structurally invalid JSON data as well as structurally valid JSON that doesn't fulfill
//! additional constraints the matrix specification defines for some event types. The error exposes
//! the deserialized `serde_json::Value` so that developers can still work with the received
//! event data. This makes it possible to deserialize a collection of events without the entire
//! collection failing to deserialize due to a single invalid event. The "content" type for each
//! event also implements `Serialize` and either `TryFromRaw` (enabling usage as
//! `Raw<ContentType>` for dedicated content types) or `Deserialize` (when the content is a
//! type alias), allowing content to be converted to and from JSON independently of the surrounding
//! event structure, if needed.
use ruma_serde::Raw;
use serde::{de::IgnoredAny, Deserialize, Serialize, Serializer};
use serde_json::value::RawValue as RawJsonValue;
use self::room::redaction::SyncRoomRedactionEvent;
use crate::{EventEncryptionAlgorithm, RoomVersionId};
// Needs to be public for trybuild tests
#[doc(hidden)]
pub mod _custom;
mod enums;
mod event_kinds;
mod unsigned;
/// Re-export of all the derives needed to create your own event types.
pub mod macros {
pub use ruma_macros::{Event, EventContent};
}
pub mod call;
pub mod direct;
pub mod dummy;
#[cfg(feature = "unstable-msc1767")]
pub mod emote;
#[cfg(feature = "unstable-msc3551")]
pub mod file;
pub mod forwarded_room_key;
pub mod fully_read;
pub mod ignored_user_list;
pub mod key;
#[cfg(feature = "unstable-msc1767")]
pub mod message;
#[cfg(feature = "unstable-msc1767")]
pub mod notice;
#[cfg(feature = "unstable-pdu")]
pub mod pdu;
pub mod policy;
pub mod presence;
pub mod push_rules;
#[cfg(feature = "unstable-msc2677")]
pub mod reaction;
pub mod receipt;
#[cfg(feature = "unstable-msc2675")]
pub mod relation;
pub mod room;
pub mod room_key;
pub mod room_key_request;
pub mod secret;
pub mod space;
pub mod sticker;
pub mod tag;
pub mod typing;
#[cfg(feature = "unstable-msc2675")]
pub use self::relation::Relations;
#[doc(hidden)]
#[cfg(feature = "compat")]
pub use self::unsigned::{RedactedUnsignedWithPrevContent, UnsignedWithPrevContent};
pub use self::{
enums::*,
event_kinds::*,
unsigned::{RedactedUnsigned, Unsigned},
};
/// The base trait that all event content types implement.
///
/// Implementing this trait allows content types to be serialized as well as deserialized.
pub trait EventContent: Sized + Serialize {
/// A matrix event identifier, like `m.room.message`.
fn event_type(&self) -> &str;
/// Constructs the given event content.
fn from_parts(event_type: &str, content: &RawJsonValue) -> serde_json::Result<Self>;
}
/// Trait to define the behavior of redacting an event.
pub trait Redact {
/// The redacted form of the event.
type Redacted;
/// Transforms `self` into a redacted form (removing most fields) according to the spec.
///
/// A small number of events have room-version specific redaction behavior, so a version has to
/// be specified.
fn redact(self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) -> Self::Redacted;
}
/// Trait to define the behavior of redact an event's content object.
pub trait RedactContent {
/// The redacted form of the event's content.
type Redacted;
/// Transform `self` into a redacted form (removing most or all fields) according to the spec.
///
/// A small number of events have room-version specific redaction behavior, so a version has to
/// be specified.
///
/// Where applicable, it is preferred to use [`Redact::redact`] on the outer event.
fn redact(self, version: &RoomVersionId) -> Self::Redacted;
}
/// Extension trait for [`Raw<_>`][ruma_serde::Raw].
pub trait RawExt<T: EventContent> {
/// Try to deserialize the JSON as an event's content.
fn deserialize_content(&self, event_type: &str) -> serde_json::Result<T>;
}
impl<T: EventContent> RawExt<T> for Raw<T> {
fn deserialize_content(&self, event_type: &str) -> serde_json::Result<T> {
| / Marker trait for the content of an ephemeral room event.
pub trait EphemeralRoomEventContent: EventContent {}
/// Marker trait for the content of a global account data event.
pub trait GlobalAccountDataEventContent: EventContent {}
/// Marker trait for the content of a room account data event.
pub trait RoomAccountDataEventContent: EventContent {}
/// Marker trait for the content of a to device event.
pub trait ToDeviceEventContent: EventContent {}
/// Marker trait for the content of a message-like event.
pub trait MessageLikeEventContent: EventContent {}
/// Marker trait for the content of a state event.
pub trait StateEventContent: EventContent {}
/// The base trait that all redacted event content types implement.
///
/// This trait's associated functions and methods should not be used to build
/// redacted events, prefer the `redact` method on `AnyStateEvent` and
/// `AnyMessageLikeEvent` and their "sync" and "stripped" counterparts. The
/// `RedactedEventContent` trait is an implementation detail, ruma makes no
/// API guarantees.
pub trait RedactedEventContent: EventContent {
/// Constructs the redacted event content.
///
/// If called for anything but "empty" redacted content this will error.
#[doc(hidden)]
fn empty(_event_type: &str) -> serde_json::Result<Self> {
Err(serde::de::Error::custom("this event is not redacted"))
}
/// Determines if the redacted event content needs to serialize fields.
#[doc(hidden)]
fn has_serialize_fields(&self) -> bool;
/// Determines if the redacted event content needs to deserialize fields.
#[doc(hidden)]
fn has_deserialize_fields() -> HasDeserializeFields;
}
/// Marker trait for the content of a redacted message-like event.
pub trait RedactedMessageLikeEventContent: RedactedEventContent {}
/// Marker trait for the content of a redacted state event.
pub trait RedactedStateEventContent: RedactedEventContent {}
/// Trait for abstracting over event content structs.
///
/// … but *not* enums which don't always have an event type and kind (e.g. message vs state) that's
/// fixed / known at compile time.
pub trait StaticEventContent: EventContent {
/// The event's "kind".
///
/// See the type's documentation.
const KIND: EventKind;
/// The event type.
const TYPE: &'static str;
}
/// The "kind" of an event.
///
/// This corresponds directly to the event content marker traits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum EventKind {
/// Global account data event kind.
GlobalAccountData,
/// Room account data event kind.
RoomAccountData,
/// Ephemeral room event kind.
EphemeralRoomData,
/// Message-like event kind.
///
/// Since redacted / non-redacted message-like events are used in the same places but have
/// different sets of fields, these two variations are treated as two closely-related event
/// kinds.
MessageLike {
/// Redacted variation?
redacted: bool,
},
/// State event kind.
///
/// Since redacted / non-redacted state events are used in the same places but have different
/// sets of fields, these two variations are treated as two closely-related event kinds.
State {
/// Redacted variation?
redacted: bool,
},
/// To-device event kind.
ToDevice,
/// Presence event kind.
Presence,
/// Hierarchy space child kind.
HierarchySpaceChild,
}
/// `HasDeserializeFields` is used in the code generated by the `Event` derive
/// to aid in deserializing redacted events.
#[doc(hidden)]
#[derive(Debug)]
#[allow(clippy::exhaustive_enums)]
pub enum HasDeserializeFields {
/// Deserialize the event's content, failing if invalid.
True,
/// Return the redacted version of this event's content.
False,
/// `Optional` is used for `RedactedAliasesEventContent` since it has
/// an empty version and one with content left after redaction that
/// must be supported together.
Optional,
}
/// Helper struct to determine the event kind from a `serde_json::value::RawValue`.
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct EventTypeDeHelper<'a> {
#[serde(borrow, rename = "type")]
pub ev_type: std::borrow::Cow<'a, str>,
}
/// Helper struct to determine if an event has been redacted.
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct RedactionDeHelper {
/// Used to check whether redacted_because exists.
pub unsigned: Option<UnsignedDeHelper>,
}
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct UnsignedDeHelper {
/// This is the field that signals an event has been redacted.
pub redacted_because: Option<IgnoredAny>,
}
/// Helper function for erroring when trying to serialize an event enum _Custom variant that can
/// only be created by deserializing from an unknown event type.
#[doc(hidden)]
#[allow(clippy::ptr_arg)]
pub fn serialize_custom_event_error<T, S: Serializer>(_: &T, _: S) -> Result<S::Ok, S::Error> {
Err(serde::ser::Error::custom(
"Failed to serialize event [content] enum: Unknown event type.\n\
To send custom events, turn them into `Raw<EnumType>` by going through
`serde_json::value::to_raw_value` and `Raw::from_json`.",
))
}
| T::from_parts(event_type, self.json())
}
}
// | identifier_body |
events.rs | //! (De)serializable types for the events in the [Matrix](https://matrix.org) specification.
//! These types are used by other Ruma crates.
//!
//! All data exchanged over Matrix is expressed as an event.
//! Different event types represent different actions, such as joining a room or sending a message.
//! Events are stored and transmitted as simple JSON structures.
//! While anyone can create a new event type for their own purposes, the Matrix specification
//! defines a number of event types which are considered core to the protocol, and Matrix clients
//! and servers must understand their semantics.
//! This module contains Rust types for each of the event types defined by the specification and
//! facilities for extending the event system for custom event types.
//!
//! # Event types
//!
//! This module includes a Rust enum called [`EventType`], which provides a simple enumeration of
//! all the event types defined by the Matrix specification. Matrix event types are serialized to
//! JSON strings in [reverse domain name
//! notation](https://en.wikipedia.org/wiki/Reverse_domain_name_notation), although the core event
//! types all use the special "m" TLD, e.g. `m.room.message`.
//!
//! # Core event types
//!
//! This module includes Rust types for every one of the event types in the Matrix specification.
//! To better organize the crate, these types live in separate modules with a hierarchy that
//! matches the reverse domain name notation of the event type.
//! For example, the `m.room.message` event lives at
//! `ruma_common::events::::room::message::MessageLikeEvent`. Each type's module also contains a
//! Rust type for that event type's `content` field, and any other supporting types required by the
//! event's other fields.
//!
//! # Extending Ruma with custom events
//!
//! For our examples we will start with a simple custom state event. `ruma_event`
//! specifies the state event's `type` and it's [`kind`](EventKind).
//!
//! ```rust
//! use ruma_common::events::macros::EventContent;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
//! #[ruma_event(type = "org.example.event", kind = State)]
//! pub struct ExampleContent {
//! field: String,
//! }
//! ```
//!
//! This can be used with events structs, such as passing it into
//! `ruma::api::client::state::send_state_event`'s `Request`.
//!
//! As a more advanced example we create a reaction message event. For this event we will use a
//! [`SyncMessageLikeEvent`] struct but any [`MessageLikeEvent`] struct would work.
//!
//! ```rust
//! use ruma_common::events::{macros::EventContent, SyncMessageLikeEvent};
//! use ruma_common::EventId;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Clone, Debug, Deserialize, Serialize)]
//! #[serde(tag = "rel_type")]
//! pub enum RelatesTo {
//! #[serde(rename = "m.annotation")]
//! Annotation {
//! /// The event this reaction relates to.
//! event_id: Box<EventId>,
//! /// The displayable content of the reaction.
//! key: String,
//! },
//!
//! /// Since this event is not fully specified in the Matrix spec
//! /// it may change or types may be added, we are ready!
//! #[serde(rename = "m.whatever")]
//! Whatever,
//! }
//!
//! /// The payload for our reaction event.
//! #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
//! #[ruma_event(type = "m.reaction", kind = MessageLike)]
//! pub struct ReactionEventContent {
//! #[serde(rename = "m.relates_to")]
//! pub relates_to: RelatesTo,
//! }
//!
//! let json = serde_json::json!({
//! "content": {
//! "m.relates_to": {
//! "event_id": "$xxxx-xxxx",
//! "key": "👍",
//! "rel_type": "m.annotation"
//! }
//! },
//! "event_id": "$xxxx-xxxx",
//! "origin_server_ts": 1,
//! "sender": "@someone:example.org",
//! "type": "m.reaction",
//! "unsigned": {
//! "age": 85
//! }
//! });
//!
//! // The downside of this event is we cannot use it with event enums,
//! // but could be deserialized from a `Raw<_>` that has failed to deserialize.
//! matches::assert_matches!(
//! serde_json::from_value::<SyncMessageLikeEvent<ReactionEventContent>>(json),
//! Ok(SyncMessageLikeEvent {
//! content: ReactionEventContent {
//! relates_to: RelatesTo::Annotation { key,.. },
//! },
//! ..
//! }) if key == "👍"
//! );
//! ```
//!
//! # Serialization and deserialization
//!
//! All concrete event types in this module can be serialized via the `Serialize` trait from
//! [serde](https://serde.rs/) and can be deserialized from a `Raw<EventType>`. In order to
//! handle incoming data that may not conform to this module's strict definitions of event
//! structures, deserialization will return `Raw::Err` on error. This error covers both
//! structurally invalid JSON data as well as structurally valid JSON that doesn't fulfill
//! additional constraints the matrix specification defines for some event types. The error exposes
//! the deserialized `serde_json::Value` so that developers can still work with the received
//! event data. This makes it possible to deserialize a collection of events without the entire
//! collection failing to deserialize due to a single invalid event. The "content" type for each
//! event also implements `Serialize` and either `TryFromRaw` (enabling usage as
//! `Raw<ContentType>` for dedicated content types) or `Deserialize` (when the content is a
//! type alias), allowing content to be converted to and from JSON independently of the surrounding
//! event structure, if needed.
use ruma_serde::Raw;
use serde::{de::IgnoredAny, Deserialize, Serialize, Serializer};
use serde_json::value::RawValue as RawJsonValue;
use self::room::redaction::SyncRoomRedactionEvent;
use crate::{EventEncryptionAlgorithm, RoomVersionId};
// Needs to be public for trybuild tests
#[doc(hidden)]
pub mod _custom;
mod enums;
mod event_kinds;
mod unsigned;
/// Re-export of all the derives needed to create your own event types.
pub mod macros {
pub use ruma_macros::{Event, EventContent};
}
pub mod call;
pub mod direct;
pub mod dummy;
#[cfg(feature = "unstable-msc1767")]
pub mod emote;
#[cfg(feature = "unstable-msc3551")]
pub mod file;
pub mod forwarded_room_key;
pub mod fully_read;
pub mod ignored_user_list;
pub mod key;
#[cfg(feature = "unstable-msc1767")]
pub mod message;
#[cfg(feature = "unstable-msc1767")]
pub mod notice;
#[cfg(feature = "unstable-pdu")]
pub mod pdu;
pub mod policy;
pub mod presence;
pub mod push_rules;
#[cfg(feature = "unstable-msc2677")]
pub mod reaction;
pub mod receipt;
#[cfg(feature = "unstable-msc2675")]
pub mod relation;
pub mod room;
pub mod room_key;
pub mod room_key_request;
pub mod secret;
pub mod space;
pub mod sticker;
pub mod tag;
pub mod typing;
#[cfg(feature = "unstable-msc2675")]
pub use self::relation::Relations;
#[doc(hidden)]
#[cfg(feature = "compat")]
pub use self::unsigned::{RedactedUnsignedWithPrevContent, UnsignedWithPrevContent};
pub use self::{
enums::*,
event_kinds::*,
unsigned::{RedactedUnsigned, Unsigned},
};
/// The base trait that all event content types implement.
///
/// Implementing this trait allows content types to be serialized as well as deserialized.
pub trait EventContent: Sized + Serialize {
/// A matrix event identifier, like `m.room.message`.
fn event_type(&self) -> &str;
/// Constructs the given event content.
fn from_parts(event_type: &str, content: &RawJsonValue) -> serde_json::Result<Self>;
}
/// Trait to define the behavior of redacting an event.
pub trait Redact {
/// The redacted form of the event.
type Redacted;
/// Transforms `self` into a redacted form (removing most fields) according to the spec.
///
/// A small number of events have room-version specific redaction behavior, so a version has to
/// be specified.
fn redact(self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) -> Self::Redacted;
}
/// Trait to define the behavior of redact an event's content object.
pub trait RedactContent {
/// The redacted form of the event's content.
type Redacted;
/// Transform `self` into a redacted form (removing most or all fields) according to the spec.
///
/// A small number of events have room-version specific redaction behavior, so a version has to
/// be specified.
///
/// Where applicable, it is preferred to use [`Redact::redact`] on the outer event.
fn redact(self, version: &RoomVersionId) -> Self::Redacted;
}
/// Extension trait for [`Raw<_>`][ruma_serde::Raw].
pub trait RawExt<T: EventContent> {
/// Try to deserialize the JSON as an event's content.
fn deserialize_content(&self, event_type: &str) -> serde_json::Result<T>;
}
impl<T: EventContent> RawExt<T> for Raw<T> {
fn deserialize_content(&self, event_type: &str) -> serde_json::Result<T> {
T::from_parts(event_type, self.json())
}
}
/// Marker trait for the content of an ephemeral room event.
pub trait EphemeralRoomEventContent: EventContent {}
/// Marker trait for the content of a global account data event.
pub trait GlobalAccountDataEventContent: EventContent {}
/// Marker trait for the content of a room account data event.
pub trait RoomAccountDataEventContent: EventContent {}
/// Marker trait for the content of a to device event.
pub trait ToDeviceEventContent: EventContent {}
/// Marker trait for the content of a message-like event.
pub trait MessageLikeEventContent: EventContent {}
/// Marker trait for the content of a state event.
pub trait StateEventContent: EventContent {}
/// The base trait that all redacted event content types implement.
///
/// This trait's associated functions and methods should not be used to build
/// redacted events, prefer the `redact` method on `AnyStateEvent` and
/// `AnyMessageLikeEvent` and their "sync" and "stripped" counterparts. The
/// `RedactedEventContent` trait is an implementation detail, ruma makes no
/// API guarantees.
pub trait RedactedEventContent: EventContent {
/// Constructs the redacted event content.
///
/// If called for anything but "empty" redacted content this will error.
#[doc(hidden)]
fn empty(_event_type: &str) -> serde_json::Result<Self> {
Err(serde::de::Error::custom("this event is not redacted"))
}
/// Determines if the redacted event content needs to serialize fields.
#[doc(hidden)]
fn has_serialize_fields(&self) -> bool;
/// Determines if the redacted event content needs to deserialize fields.
#[doc(hidden)]
fn has_deserialize_fields() -> HasDeserializeFields;
}
/// Marker trait for the content of a redacted message-like event.
pub trait RedactedMessageLikeEventContent: RedactedEventContent {}
/// Marker trait for the content of a redacted state event.
pub trait RedactedStateEventContent: RedactedEventContent {}
/// Trait for abstracting over event content structs.
///
/// … but *not* enums which don't always have an event type and kind (e.g. message vs state) that's
/// fixed / known at compile time.
pub trait StaticEventContent: EventContent {
/// The event's "kind".
///
/// See the type's documentation.
const KIND: EventKind;
/// The event type.
const TYPE: &'static str;
}
/// The "kind" of an event.
///
/// This corresponds directly to the event content marker traits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum EventKin | // Global account data event kind.
GlobalAccountData,
/// Room account data event kind.
RoomAccountData,
/// Ephemeral room event kind.
EphemeralRoomData,
/// Message-like event kind.
///
/// Since redacted / non-redacted message-like events are used in the same places but have
/// different sets of fields, these two variations are treated as two closely-related event
/// kinds.
MessageLike {
/// Redacted variation?
redacted: bool,
},
/// State event kind.
///
/// Since redacted / non-redacted state events are used in the same places but have different
/// sets of fields, these two variations are treated as two closely-related event kinds.
State {
/// Redacted variation?
redacted: bool,
},
/// To-device event kind.
ToDevice,
/// Presence event kind.
Presence,
/// Hierarchy space child kind.
HierarchySpaceChild,
}
/// `HasDeserializeFields` is used in the code generated by the `Event` derive
/// to aid in deserializing redacted events.
#[doc(hidden)]
#[derive(Debug)]
#[allow(clippy::exhaustive_enums)]
pub enum HasDeserializeFields {
/// Deserialize the event's content, failing if invalid.
True,
/// Return the redacted version of this event's content.
False,
/// `Optional` is used for `RedactedAliasesEventContent` since it has
/// an empty version and one with content left after redaction that
/// must be supported together.
Optional,
}
/// Helper struct to determine the event kind from a `serde_json::value::RawValue`.
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct EventTypeDeHelper<'a> {
#[serde(borrow, rename = "type")]
pub ev_type: std::borrow::Cow<'a, str>,
}
/// Helper struct to determine if an event has been redacted.
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct RedactionDeHelper {
/// Used to check whether redacted_because exists.
pub unsigned: Option<UnsignedDeHelper>,
}
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct UnsignedDeHelper {
/// This is the field that signals an event has been redacted.
pub redacted_because: Option<IgnoredAny>,
}
/// Helper function for erroring when trying to serialize an event enum _Custom variant that can
/// only be created by deserializing from an unknown event type.
#[doc(hidden)]
#[allow(clippy::ptr_arg)]
pub fn serialize_custom_event_error<T, S: Serializer>(_: &T, _: S) -> Result<S::Ok, S::Error> {
Err(serde::ser::Error::custom(
"Failed to serialize event [content] enum: Unknown event type.\n\
To send custom events, turn them into `Raw<EnumType>` by going through
`serde_json::value::to_raw_value` and `Raw::from_json`.",
))
}
| d {
/ | identifier_name |
events.rs | //! (De)serializable types for the events in the [Matrix](https://matrix.org) specification.
//! These types are used by other Ruma crates.
//!
//! All data exchanged over Matrix is expressed as an event.
//! Different event types represent different actions, such as joining a room or sending a message.
//! Events are stored and transmitted as simple JSON structures.
//! While anyone can create a new event type for their own purposes, the Matrix specification
//! defines a number of event types which are considered core to the protocol, and Matrix clients
//! and servers must understand their semantics.
//! This module contains Rust types for each of the event types defined by the specification and
//! facilities for extending the event system for custom event types.
//!
//! # Event types
//!
//! This module includes a Rust enum called [`EventType`], which provides a simple enumeration of
//! all the event types defined by the Matrix specification. Matrix event types are serialized to
//! JSON strings in [reverse domain name
//! notation](https://en.wikipedia.org/wiki/Reverse_domain_name_notation), although the core event
//! types all use the special "m" TLD, e.g. `m.room.message`.
//!
//! # Core event types
//!
//! This module includes Rust types for every one of the event types in the Matrix specification.
//! To better organize the crate, these types live in separate modules with a hierarchy that
//! matches the reverse domain name notation of the event type.
//! For example, the `m.room.message` event lives at
//! `ruma_common::events::::room::message::MessageLikeEvent`. Each type's module also contains a
//! Rust type for that event type's `content` field, and any other supporting types required by the
//! event's other fields.
//!
//! # Extending Ruma with custom events
//!
//! For our examples we will start with a simple custom state event. `ruma_event`
//! specifies the state event's `type` and it's [`kind`](EventKind).
//!
//! ```rust
//! use ruma_common::events::macros::EventContent;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
//! #[ruma_event(type = "org.example.event", kind = State)]
//! pub struct ExampleContent {
//! field: String,
//! }
//! ```
//!
//! This can be used with events structs, such as passing it into
//! `ruma::api::client::state::send_state_event`'s `Request`.
//!
//! As a more advanced example we create a reaction message event. For this event we will use a
//! [`SyncMessageLikeEvent`] struct but any [`MessageLikeEvent`] struct would work.
//!
//! ```rust
//! use ruma_common::events::{macros::EventContent, SyncMessageLikeEvent};
//! use ruma_common::EventId;
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Clone, Debug, Deserialize, Serialize)]
//! #[serde(tag = "rel_type")]
//! pub enum RelatesTo {
//! #[serde(rename = "m.annotation")]
//! Annotation {
//! /// The event this reaction relates to.
//! event_id: Box<EventId>,
//! /// The displayable content of the reaction.
//! key: String,
//! },
//!
//! /// Since this event is not fully specified in the Matrix spec
//! /// it may change or types may be added, we are ready!
//! #[serde(rename = "m.whatever")]
//! Whatever,
//! }
//!
//! /// The payload for our reaction event.
//! #[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
//! #[ruma_event(type = "m.reaction", kind = MessageLike)]
//! pub struct ReactionEventContent {
//! #[serde(rename = "m.relates_to")]
//! pub relates_to: RelatesTo,
//! }
//!
//! let json = serde_json::json!({
//! "content": {
//! "m.relates_to": {
//! "event_id": "$xxxx-xxxx",
//! "key": "👍",
//! "rel_type": "m.annotation"
//! }
//! },
//! "event_id": "$xxxx-xxxx",
//! "origin_server_ts": 1,
//! "sender": "@someone:example.org",
//! "type": "m.reaction",
//! "unsigned": {
//! "age": 85
//! }
//! });
//!
//! // The downside of this event is we cannot use it with event enums, | //! Ok(SyncMessageLikeEvent {
//! content: ReactionEventContent {
//! relates_to: RelatesTo::Annotation { key,.. },
//! },
//! ..
//! }) if key == "👍"
//! );
//! ```
//!
//! # Serialization and deserialization
//!
//! All concrete event types in this module can be serialized via the `Serialize` trait from
//! [serde](https://serde.rs/) and can be deserialized from a `Raw<EventType>`. In order to
//! handle incoming data that may not conform to this module's strict definitions of event
//! structures, deserialization will return `Raw::Err` on error. This error covers both
//! structurally invalid JSON data as well as structurally valid JSON that doesn't fulfill
//! additional constraints the matrix specification defines for some event types. The error exposes
//! the deserialized `serde_json::Value` so that developers can still work with the received
//! event data. This makes it possible to deserialize a collection of events without the entire
//! collection failing to deserialize due to a single invalid event. The "content" type for each
//! event also implements `Serialize` and either `TryFromRaw` (enabling usage as
//! `Raw<ContentType>` for dedicated content types) or `Deserialize` (when the content is a
//! type alias), allowing content to be converted to and from JSON independently of the surrounding
//! event structure, if needed.
use ruma_serde::Raw;
use serde::{de::IgnoredAny, Deserialize, Serialize, Serializer};
use serde_json::value::RawValue as RawJsonValue;
use self::room::redaction::SyncRoomRedactionEvent;
use crate::{EventEncryptionAlgorithm, RoomVersionId};
// Needs to be public for trybuild tests
#[doc(hidden)]
pub mod _custom;
mod enums;
mod event_kinds;
mod unsigned;
/// Re-export of all the derives needed to create your own event types.
pub mod macros {
pub use ruma_macros::{Event, EventContent};
}
pub mod call;
pub mod direct;
pub mod dummy;
#[cfg(feature = "unstable-msc1767")]
pub mod emote;
#[cfg(feature = "unstable-msc3551")]
pub mod file;
pub mod forwarded_room_key;
pub mod fully_read;
pub mod ignored_user_list;
pub mod key;
#[cfg(feature = "unstable-msc1767")]
pub mod message;
#[cfg(feature = "unstable-msc1767")]
pub mod notice;
#[cfg(feature = "unstable-pdu")]
pub mod pdu;
pub mod policy;
pub mod presence;
pub mod push_rules;
#[cfg(feature = "unstable-msc2677")]
pub mod reaction;
pub mod receipt;
#[cfg(feature = "unstable-msc2675")]
pub mod relation;
pub mod room;
pub mod room_key;
pub mod room_key_request;
pub mod secret;
pub mod space;
pub mod sticker;
pub mod tag;
pub mod typing;
#[cfg(feature = "unstable-msc2675")]
pub use self::relation::Relations;
#[doc(hidden)]
#[cfg(feature = "compat")]
pub use self::unsigned::{RedactedUnsignedWithPrevContent, UnsignedWithPrevContent};
pub use self::{
enums::*,
event_kinds::*,
unsigned::{RedactedUnsigned, Unsigned},
};
/// The base trait that all event content types implement.
///
/// Implementing this trait allows content types to be serialized as well as deserialized.
pub trait EventContent: Sized + Serialize {
/// A matrix event identifier, like `m.room.message`.
fn event_type(&self) -> &str;
/// Constructs the given event content.
fn from_parts(event_type: &str, content: &RawJsonValue) -> serde_json::Result<Self>;
}
/// Trait to define the behavior of redacting an event.
pub trait Redact {
/// The redacted form of the event.
type Redacted;
/// Transforms `self` into a redacted form (removing most fields) according to the spec.
///
/// A small number of events have room-version specific redaction behavior, so a version has to
/// be specified.
fn redact(self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) -> Self::Redacted;
}
/// Trait to define the behavior of redact an event's content object.
pub trait RedactContent {
/// The redacted form of the event's content.
type Redacted;
/// Transform `self` into a redacted form (removing most or all fields) according to the spec.
///
/// A small number of events have room-version specific redaction behavior, so a version has to
/// be specified.
///
/// Where applicable, it is preferred to use [`Redact::redact`] on the outer event.
fn redact(self, version: &RoomVersionId) -> Self::Redacted;
}
/// Extension trait for [`Raw<_>`][ruma_serde::Raw].
pub trait RawExt<T: EventContent> {
/// Try to deserialize the JSON as an event's content.
fn deserialize_content(&self, event_type: &str) -> serde_json::Result<T>;
}
impl<T: EventContent> RawExt<T> for Raw<T> {
fn deserialize_content(&self, event_type: &str) -> serde_json::Result<T> {
T::from_parts(event_type, self.json())
}
}
/// Marker trait for the content of an ephemeral room event.
pub trait EphemeralRoomEventContent: EventContent {}
/// Marker trait for the content of a global account data event.
pub trait GlobalAccountDataEventContent: EventContent {}
/// Marker trait for the content of a room account data event.
pub trait RoomAccountDataEventContent: EventContent {}
/// Marker trait for the content of a to device event.
pub trait ToDeviceEventContent: EventContent {}
/// Marker trait for the content of a message-like event.
pub trait MessageLikeEventContent: EventContent {}
/// Marker trait for the content of a state event.
pub trait StateEventContent: EventContent {}
/// The base trait that all redacted event content types implement.
///
/// This trait's associated functions and methods should not be used to build
/// redacted events, prefer the `redact` method on `AnyStateEvent` and
/// `AnyMessageLikeEvent` and their "sync" and "stripped" counterparts. The
/// `RedactedEventContent` trait is an implementation detail, ruma makes no
/// API guarantees.
pub trait RedactedEventContent: EventContent {
/// Constructs the redacted event content.
///
/// If called for anything but "empty" redacted content this will error.
#[doc(hidden)]
fn empty(_event_type: &str) -> serde_json::Result<Self> {
Err(serde::de::Error::custom("this event is not redacted"))
}
/// Determines if the redacted event content needs to serialize fields.
#[doc(hidden)]
fn has_serialize_fields(&self) -> bool;
/// Determines if the redacted event content needs to deserialize fields.
#[doc(hidden)]
fn has_deserialize_fields() -> HasDeserializeFields;
}
/// Marker trait for the content of a redacted message-like event.
pub trait RedactedMessageLikeEventContent: RedactedEventContent {}
/// Marker trait for the content of a redacted state event.
pub trait RedactedStateEventContent: RedactedEventContent {}
/// Trait for abstracting over event content structs.
///
/// … but *not* enums which don't always have an event type and kind (e.g. message vs state) that's
/// fixed / known at compile time.
pub trait StaticEventContent: EventContent {
/// The event's "kind".
///
/// See the type's documentation.
const KIND: EventKind;
/// The event type.
const TYPE: &'static str;
}
/// The "kind" of an event.
///
/// This corresponds directly to the event content marker traits.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum EventKind {
/// Global account data event kind.
GlobalAccountData,
/// Room account data event kind.
RoomAccountData,
/// Ephemeral room event kind.
EphemeralRoomData,
/// Message-like event kind.
///
/// Since redacted / non-redacted message-like events are used in the same places but have
/// different sets of fields, these two variations are treated as two closely-related event
/// kinds.
MessageLike {
/// Redacted variation?
redacted: bool,
},
/// State event kind.
///
/// Since redacted / non-redacted state events are used in the same places but have different
/// sets of fields, these two variations are treated as two closely-related event kinds.
State {
/// Redacted variation?
redacted: bool,
},
/// To-device event kind.
ToDevice,
/// Presence event kind.
Presence,
/// Hierarchy space child kind.
HierarchySpaceChild,
}
/// `HasDeserializeFields` is used in the code generated by the `Event` derive
/// to aid in deserializing redacted events.
#[doc(hidden)]
#[derive(Debug)]
#[allow(clippy::exhaustive_enums)]
pub enum HasDeserializeFields {
/// Deserialize the event's content, failing if invalid.
True,
/// Return the redacted version of this event's content.
False,
/// `Optional` is used for `RedactedAliasesEventContent` since it has
/// an empty version and one with content left after redaction that
/// must be supported together.
Optional,
}
/// Helper struct to determine the event kind from a `serde_json::value::RawValue`.
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct EventTypeDeHelper<'a> {
#[serde(borrow, rename = "type")]
pub ev_type: std::borrow::Cow<'a, str>,
}
/// Helper struct to determine if an event has been redacted.
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct RedactionDeHelper {
/// Used to check whether redacted_because exists.
pub unsigned: Option<UnsignedDeHelper>,
}
#[doc(hidden)]
#[derive(Deserialize)]
#[allow(clippy::exhaustive_structs)]
pub struct UnsignedDeHelper {
/// This is the field that signals an event has been redacted.
pub redacted_because: Option<IgnoredAny>,
}
/// Helper function for erroring when trying to serialize an event enum _Custom variant that can
/// only be created by deserializing from an unknown event type.
#[doc(hidden)]
#[allow(clippy::ptr_arg)]
pub fn serialize_custom_event_error<T, S: Serializer>(_: &T, _: S) -> Result<S::Ok, S::Error> {
Err(serde::ser::Error::custom(
"Failed to serialize event [content] enum: Unknown event type.\n\
To send custom events, turn them into `Raw<EnumType>` by going through
`serde_json::value::to_raw_value` and `Raw::from_json`.",
))
} | //! // but could be deserialized from a `Raw<_>` that has failed to deserialize.
//! matches::assert_matches!(
//! serde_json::from_value::<SyncMessageLikeEvent<ReactionEventContent>>(json), | random_line_split |
into.rs | use std::iter;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse::Result, DeriveInput};
use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State};
/// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into`
pub fn expand(input: &DeriveInput, trait_name: &'static str) -> Result<TokenStream> {
let state = State::with_attr_params(
input,
trait_name,
quote!(::core::convert),
trait_name.to_lowercase(),
AttrParams {
enum_: vec!["ignore", "owned", "ref", "ref_mut"],
variant: vec!["ignore", "owned", "ref", "ref_mut"],
struct_: vec!["ignore", "owned", "ref", "ref_mut", "types"],
field: vec!["ignore"],
},
)?;
let MultiFieldData {
variant_info,
field_types,
field_idents,
input_type,
..
} = state.enabled_fields_data();
let mut tokens = TokenStream::new();
for ref_type in variant_info.ref_types() {
let reference = ref_type.reference();
let lifetime = ref_type.lifetime();
let reference_with_lifetime = ref_type.reference_with_lifetime();
let generics_impl;
let (_, ty_generics, where_clause) = input.generics.split_for_impl(); | };
let additional_types = variant_info.additional_types(ref_type);
for explicit_type in iter::once(None).chain(additional_types.iter().map(Some)) {
let into_types: Vec<_> = field_types
.iter()
.map(|field_type| {
// No, `.unwrap_or()` won't work here, because we use different types.
if let Some(type_) = explicit_type {
quote! { #reference_with_lifetime #type_ }
} else {
quote! { #reference_with_lifetime #field_type }
}
})
.collect();
let initializers = field_idents.iter().map(|field_ident| {
if let Some(type_) = explicit_type {
quote! { <#reference #type_>::from(#reference original.#field_ident) }
} else {
quote! { #reference original.#field_ident }
}
});
(quote! {
#[automatically_derived]
impl#impl_generics ::core::convert::From<#reference_with_lifetime #input_type#ty_generics> for
(#(#into_types),*) #where_clause {
#[inline]
fn from(original: #reference_with_lifetime #input_type#ty_generics) -> Self {
(#(#initializers),*)
}
}
}).to_tokens(&mut tokens);
}
}
Ok(tokens)
} | let (impl_generics, _, _) = if ref_type.is_ref() {
generics_impl = add_extra_generic_param(&input.generics, lifetime);
generics_impl.split_for_impl()
} else {
input.generics.split_for_impl() | random_line_split |
into.rs | use std::iter;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse::Result, DeriveInput};
use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State};
/// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into`
pub fn | (input: &DeriveInput, trait_name: &'static str) -> Result<TokenStream> {
let state = State::with_attr_params(
input,
trait_name,
quote!(::core::convert),
trait_name.to_lowercase(),
AttrParams {
enum_: vec!["ignore", "owned", "ref", "ref_mut"],
variant: vec!["ignore", "owned", "ref", "ref_mut"],
struct_: vec!["ignore", "owned", "ref", "ref_mut", "types"],
field: vec!["ignore"],
},
)?;
let MultiFieldData {
variant_info,
field_types,
field_idents,
input_type,
..
} = state.enabled_fields_data();
let mut tokens = TokenStream::new();
for ref_type in variant_info.ref_types() {
let reference = ref_type.reference();
let lifetime = ref_type.lifetime();
let reference_with_lifetime = ref_type.reference_with_lifetime();
let generics_impl;
let (_, ty_generics, where_clause) = input.generics.split_for_impl();
let (impl_generics, _, _) = if ref_type.is_ref() {
generics_impl = add_extra_generic_param(&input.generics, lifetime);
generics_impl.split_for_impl()
} else {
input.generics.split_for_impl()
};
let additional_types = variant_info.additional_types(ref_type);
for explicit_type in iter::once(None).chain(additional_types.iter().map(Some)) {
let into_types: Vec<_> = field_types
.iter()
.map(|field_type| {
// No, `.unwrap_or()` won't work here, because we use different types.
if let Some(type_) = explicit_type {
quote! { #reference_with_lifetime #type_ }
} else {
quote! { #reference_with_lifetime #field_type }
}
})
.collect();
let initializers = field_idents.iter().map(|field_ident| {
if let Some(type_) = explicit_type {
quote! { <#reference #type_>::from(#reference original.#field_ident) }
} else {
quote! { #reference original.#field_ident }
}
});
(quote! {
#[automatically_derived]
impl#impl_generics ::core::convert::From<#reference_with_lifetime #input_type#ty_generics> for
(#(#into_types),*) #where_clause {
#[inline]
fn from(original: #reference_with_lifetime #input_type#ty_generics) -> Self {
(#(#initializers),*)
}
}
}).to_tokens(&mut tokens);
}
}
Ok(tokens)
}
| expand | identifier_name |
into.rs | use std::iter;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse::Result, DeriveInput};
use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State};
/// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into`
pub fn expand(input: &DeriveInput, trait_name: &'static str) -> Result<TokenStream> |
let mut tokens = TokenStream::new();
for ref_type in variant_info.ref_types() {
let reference = ref_type.reference();
let lifetime = ref_type.lifetime();
let reference_with_lifetime = ref_type.reference_with_lifetime();
let generics_impl;
let (_, ty_generics, where_clause) = input.generics.split_for_impl();
let (impl_generics, _, _) = if ref_type.is_ref() {
generics_impl = add_extra_generic_param(&input.generics, lifetime);
generics_impl.split_for_impl()
} else {
input.generics.split_for_impl()
};
let additional_types = variant_info.additional_types(ref_type);
for explicit_type in iter::once(None).chain(additional_types.iter().map(Some)) {
let into_types: Vec<_> = field_types
.iter()
.map(|field_type| {
// No, `.unwrap_or()` won't work here, because we use different types.
if let Some(type_) = explicit_type {
quote! { #reference_with_lifetime #type_ }
} else {
quote! { #reference_with_lifetime #field_type }
}
})
.collect();
let initializers = field_idents.iter().map(|field_ident| {
if let Some(type_) = explicit_type {
quote! { <#reference #type_>::from(#reference original.#field_ident) }
} else {
quote! { #reference original.#field_ident }
}
});
(quote! {
#[automatically_derived]
impl#impl_generics ::core::convert::From<#reference_with_lifetime #input_type#ty_generics> for
(#(#into_types),*) #where_clause {
#[inline]
fn from(original: #reference_with_lifetime #input_type#ty_generics) -> Self {
(#(#initializers),*)
}
}
}).to_tokens(&mut tokens);
}
}
Ok(tokens)
}
| {
let state = State::with_attr_params(
input,
trait_name,
quote!(::core::convert),
trait_name.to_lowercase(),
AttrParams {
enum_: vec!["ignore", "owned", "ref", "ref_mut"],
variant: vec!["ignore", "owned", "ref", "ref_mut"],
struct_: vec!["ignore", "owned", "ref", "ref_mut", "types"],
field: vec!["ignore"],
},
)?;
let MultiFieldData {
variant_info,
field_types,
field_idents,
input_type,
..
} = state.enabled_fields_data(); | identifier_body |
into.rs | use std::iter;
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{parse::Result, DeriveInput};
use crate::utils::{add_extra_generic_param, AttrParams, MultiFieldData, State};
/// Provides the hook to expand `#[derive(Into)]` into an implementation of `Into`
pub fn expand(input: &DeriveInput, trait_name: &'static str) -> Result<TokenStream> {
let state = State::with_attr_params(
input,
trait_name,
quote!(::core::convert),
trait_name.to_lowercase(),
AttrParams {
enum_: vec!["ignore", "owned", "ref", "ref_mut"],
variant: vec!["ignore", "owned", "ref", "ref_mut"],
struct_: vec!["ignore", "owned", "ref", "ref_mut", "types"],
field: vec!["ignore"],
},
)?;
let MultiFieldData {
variant_info,
field_types,
field_idents,
input_type,
..
} = state.enabled_fields_data();
let mut tokens = TokenStream::new();
for ref_type in variant_info.ref_types() {
let reference = ref_type.reference();
let lifetime = ref_type.lifetime();
let reference_with_lifetime = ref_type.reference_with_lifetime();
let generics_impl;
let (_, ty_generics, where_clause) = input.generics.split_for_impl();
let (impl_generics, _, _) = if ref_type.is_ref() {
generics_impl = add_extra_generic_param(&input.generics, lifetime);
generics_impl.split_for_impl()
} else {
input.generics.split_for_impl()
};
let additional_types = variant_info.additional_types(ref_type);
for explicit_type in iter::once(None).chain(additional_types.iter().map(Some)) {
let into_types: Vec<_> = field_types
.iter()
.map(|field_type| {
// No, `.unwrap_or()` won't work here, because we use different types.
if let Some(type_) = explicit_type {
quote! { #reference_with_lifetime #type_ }
} else {
quote! { #reference_with_lifetime #field_type }
}
})
.collect();
let initializers = field_idents.iter().map(|field_ident| {
if let Some(type_) = explicit_type {
quote! { <#reference #type_>::from(#reference original.#field_ident) }
} else |
});
(quote! {
#[automatically_derived]
impl#impl_generics ::core::convert::From<#reference_with_lifetime #input_type#ty_generics> for
(#(#into_types),*) #where_clause {
#[inline]
fn from(original: #reference_with_lifetime #input_type#ty_generics) -> Self {
(#(#initializers),*)
}
}
}).to_tokens(&mut tokens);
}
}
Ok(tokens)
}
| {
quote! { #reference original.#field_ident }
} | conditional_block |
traits.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.
use rustc::ty::{self, Ty};
use rustc::ty::layout::{Size, Align, LayoutOf};
use rustc::mir::interpret::{Scalar, Pointer, EvalResult, PointerArithmetic};
use super::{EvalContext, Machine, MemoryKind};
impl<'a,'mir, 'tcx, M: Machine<'a,'mir, 'tcx>> EvalContext<'a,'mir, 'tcx, M> {
/// Creates a dynamic vtable for the given type and vtable origin. This is used only for
/// objects.
///
/// The `trait_ref` encodes the erased self type. Hence if we are
/// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
/// `trait_ref` would map `T:Trait`.
pub fn get_vtable(
&mut self,
ty: Ty<'tcx>,
poly_trait_ref: ty::PolyExistentialTraitRef<'tcx>,
) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
trace!("get_vtable(trait_ref={:?})", poly_trait_ref);
let (ty, poly_trait_ref) = self.tcx.erase_regions(&(ty, poly_trait_ref));
if let Some(&vtable) = self.vtables.get(&(ty, poly_trait_ref)) {
return Ok(Pointer::from(vtable).with_default_tag());
}
let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty);
let trait_ref = self.tcx.erase_regions(&trait_ref);
let methods = self.tcx.vtable_methods(trait_ref);
let layout = self.layout_of(ty)?;
assert!(!layout.is_unsized(), "can't create a vtable for an unsized type");
let size = layout.size.bytes();
let align = layout.align.abi.bytes();
let ptr_size = self.pointer_size();
let ptr_align = self.tcx.data_layout.pointer_align.abi;
// /////////////////////////////////////////////////////////////////////////////////////////
// If you touch this code, be sure to also make the corresponding changes to
// `get_vtable` in rust_codegen_llvm/meth.rs
// /////////////////////////////////////////////////////////////////////////////////////////
let vtable = self.memory.allocate(
ptr_size * (3 + methods.len() as u64),
ptr_align,
MemoryKind::Vtable,
)?.with_default_tag();
let tcx = &*self.tcx;
let drop = ::monomorphize::resolve_drop_in_place(*tcx, ty);
let drop = self.memory.create_fn_alloc(drop).with_default_tag();
// no need to do any alignment checks on the memory accesses below, because we know the
// allocation is correctly aligned as we created it above. Also we're only offsetting by
// multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`.
self.memory
.get_mut(vtable.alloc_id)?
.write_ptr_sized(tcx, vtable, Scalar::Ptr(drop).into())?;
let size_ptr = vtable.offset(ptr_size, self)?;
self.memory
.get_mut(size_ptr.alloc_id)?
.write_ptr_sized(tcx, size_ptr, Scalar::from_uint(size, ptr_size).into())?;
let align_ptr = vtable.offset(ptr_size * 2, self)?;
self.memory
.get_mut(align_ptr.alloc_id)?
.write_ptr_sized(tcx, align_ptr, Scalar::from_uint(align, ptr_size).into())?;
for (i, method) in methods.iter().enumerate() {
if let Some((def_id, substs)) = *method {
let instance = self.resolve(def_id, substs)?;
let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag();
let method_ptr = vtable.offset(ptr_size * (3 + i as u64), self)?;
self.memory
.get_mut(method_ptr.alloc_id)?
.write_ptr_sized(tcx, method_ptr, Scalar::Ptr(fn_ptr).into())?;
}
}
self.memory.mark_immutable(vtable.alloc_id)?;
assert!(self.vtables.insert((ty, poly_trait_ref), vtable.alloc_id).is_none());
Ok(vtable)
}
/// Return the drop fn instance as well as the actual dynamic type
pub fn read_drop_type_from_vtable(
&self,
vtable: Pointer<M::PointerTag>,
) -> EvalResult<'tcx, (ty::Instance<'tcx>, ty::Ty<'tcx>)> {
// we don't care about the pointee type, we just want a pointer
self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
let drop_fn = self.memory
.get(vtable.alloc_id)?
.read_ptr_sized(self, vtable)?
.to_ptr()?;
let drop_instance = self.memory.get_fn(drop_fn)?;
trace!("Found drop fn: {:?}", drop_instance);
let fn_sig = drop_instance.ty(*self.tcx).fn_sig(*self.tcx);
let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, &fn_sig);
// the drop function takes *mut T where T is the type being dropped, so get that
let ty = fn_sig.inputs()[0].builtin_deref(true).unwrap().ty;
Ok((drop_instance, ty))
}
pub fn read_size_and_align_from_vtable(
&self,
vtable: Pointer<M::PointerTag>,
) -> EvalResult<'tcx, (Size, Align)> |
}
| {
let pointer_size = self.pointer_size();
self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
let alloc = self.memory.get(vtable.alloc_id)?;
let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)?
.to_bits(pointer_size)? as u64;
let align = alloc.read_ptr_sized(
self,
vtable.offset(pointer_size * 2, self)?,
)?.to_bits(pointer_size)? as u64;
Ok((Size::from_bytes(size), Align::from_bytes(align).unwrap()))
} | identifier_body |
traits.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.
use rustc::ty::{self, Ty};
use rustc::ty::layout::{Size, Align, LayoutOf};
use rustc::mir::interpret::{Scalar, Pointer, EvalResult, PointerArithmetic};
use super::{EvalContext, Machine, MemoryKind};
impl<'a,'mir, 'tcx, M: Machine<'a,'mir, 'tcx>> EvalContext<'a,'mir, 'tcx, M> {
/// Creates a dynamic vtable for the given type and vtable origin. This is used only for
/// objects.
///
/// The `trait_ref` encodes the erased self type. Hence if we are
/// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
/// `trait_ref` would map `T:Trait`.
pub fn get_vtable(
&mut self,
ty: Ty<'tcx>,
poly_trait_ref: ty::PolyExistentialTraitRef<'tcx>,
) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
trace!("get_vtable(trait_ref={:?})", poly_trait_ref);
let (ty, poly_trait_ref) = self.tcx.erase_regions(&(ty, poly_trait_ref));
if let Some(&vtable) = self.vtables.get(&(ty, poly_trait_ref)) {
return Ok(Pointer::from(vtable).with_default_tag());
}
let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty);
let trait_ref = self.tcx.erase_regions(&trait_ref);
let methods = self.tcx.vtable_methods(trait_ref);
let layout = self.layout_of(ty)?;
assert!(!layout.is_unsized(), "can't create a vtable for an unsized type");
let size = layout.size.bytes();
let align = layout.align.abi.bytes();
let ptr_size = self.pointer_size();
let ptr_align = self.tcx.data_layout.pointer_align.abi;
// /////////////////////////////////////////////////////////////////////////////////////////
// If you touch this code, be sure to also make the corresponding changes to
// `get_vtable` in rust_codegen_llvm/meth.rs
// /////////////////////////////////////////////////////////////////////////////////////////
let vtable = self.memory.allocate(
ptr_size * (3 + methods.len() as u64),
ptr_align,
MemoryKind::Vtable,
)?.with_default_tag();
let tcx = &*self.tcx;
let drop = ::monomorphize::resolve_drop_in_place(*tcx, ty);
let drop = self.memory.create_fn_alloc(drop).with_default_tag();
// no need to do any alignment checks on the memory accesses below, because we know the
// allocation is correctly aligned as we created it above. Also we're only offsetting by
// multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`.
self.memory
.get_mut(vtable.alloc_id)?
.write_ptr_sized(tcx, vtable, Scalar::Ptr(drop).into())?;
let size_ptr = vtable.offset(ptr_size, self)?;
self.memory
.get_mut(size_ptr.alloc_id)?
.write_ptr_sized(tcx, size_ptr, Scalar::from_uint(size, ptr_size).into())?;
let align_ptr = vtable.offset(ptr_size * 2, self)?;
self.memory
.get_mut(align_ptr.alloc_id)?
.write_ptr_sized(tcx, align_ptr, Scalar::from_uint(align, ptr_size).into())?;
for (i, method) in methods.iter().enumerate() {
if let Some((def_id, substs)) = *method |
}
self.memory.mark_immutable(vtable.alloc_id)?;
assert!(self.vtables.insert((ty, poly_trait_ref), vtable.alloc_id).is_none());
Ok(vtable)
}
/// Return the drop fn instance as well as the actual dynamic type
pub fn read_drop_type_from_vtable(
&self,
vtable: Pointer<M::PointerTag>,
) -> EvalResult<'tcx, (ty::Instance<'tcx>, ty::Ty<'tcx>)> {
// we don't care about the pointee type, we just want a pointer
self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
let drop_fn = self.memory
.get(vtable.alloc_id)?
.read_ptr_sized(self, vtable)?
.to_ptr()?;
let drop_instance = self.memory.get_fn(drop_fn)?;
trace!("Found drop fn: {:?}", drop_instance);
let fn_sig = drop_instance.ty(*self.tcx).fn_sig(*self.tcx);
let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, &fn_sig);
// the drop function takes *mut T where T is the type being dropped, so get that
let ty = fn_sig.inputs()[0].builtin_deref(true).unwrap().ty;
Ok((drop_instance, ty))
}
pub fn read_size_and_align_from_vtable(
&self,
vtable: Pointer<M::PointerTag>,
) -> EvalResult<'tcx, (Size, Align)> {
let pointer_size = self.pointer_size();
self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
let alloc = self.memory.get(vtable.alloc_id)?;
let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)?
.to_bits(pointer_size)? as u64;
let align = alloc.read_ptr_sized(
self,
vtable.offset(pointer_size * 2, self)?,
)?.to_bits(pointer_size)? as u64;
Ok((Size::from_bytes(size), Align::from_bytes(align).unwrap()))
}
}
| {
let instance = self.resolve(def_id, substs)?;
let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag();
let method_ptr = vtable.offset(ptr_size * (3 + i as u64), self)?;
self.memory
.get_mut(method_ptr.alloc_id)?
.write_ptr_sized(tcx, method_ptr, Scalar::Ptr(fn_ptr).into())?;
} | conditional_block |
traits.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.
use rustc::ty::{self, Ty};
use rustc::ty::layout::{Size, Align, LayoutOf};
use rustc::mir::interpret::{Scalar, Pointer, EvalResult, PointerArithmetic};
use super::{EvalContext, Machine, MemoryKind};
impl<'a,'mir, 'tcx, M: Machine<'a,'mir, 'tcx>> EvalContext<'a,'mir, 'tcx, M> {
/// Creates a dynamic vtable for the given type and vtable origin. This is used only for
/// objects.
///
/// The `trait_ref` encodes the erased self type. Hence if we are
/// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
/// `trait_ref` would map `T:Trait`.
pub fn get_vtable(
&mut self,
ty: Ty<'tcx>,
poly_trait_ref: ty::PolyExistentialTraitRef<'tcx>,
) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
trace!("get_vtable(trait_ref={:?})", poly_trait_ref);
let (ty, poly_trait_ref) = self.tcx.erase_regions(&(ty, poly_trait_ref));
if let Some(&vtable) = self.vtables.get(&(ty, poly_trait_ref)) {
return Ok(Pointer::from(vtable).with_default_tag());
}
let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty);
let trait_ref = self.tcx.erase_regions(&trait_ref);
let methods = self.tcx.vtable_methods(trait_ref);
let layout = self.layout_of(ty)?;
assert!(!layout.is_unsized(), "can't create a vtable for an unsized type");
let size = layout.size.bytes();
let align = layout.align.abi.bytes();
let ptr_size = self.pointer_size();
let ptr_align = self.tcx.data_layout.pointer_align.abi;
// /////////////////////////////////////////////////////////////////////////////////////////
// If you touch this code, be sure to also make the corresponding changes to
// `get_vtable` in rust_codegen_llvm/meth.rs
// /////////////////////////////////////////////////////////////////////////////////////////
let vtable = self.memory.allocate(
ptr_size * (3 + methods.len() as u64),
ptr_align,
MemoryKind::Vtable,
)?.with_default_tag();
let tcx = &*self.tcx;
let drop = ::monomorphize::resolve_drop_in_place(*tcx, ty);
let drop = self.memory.create_fn_alloc(drop).with_default_tag();
// no need to do any alignment checks on the memory accesses below, because we know the
// allocation is correctly aligned as we created it above. Also we're only offsetting by
// multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`.
self.memory
.get_mut(vtable.alloc_id)?
.write_ptr_sized(tcx, vtable, Scalar::Ptr(drop).into())?;
let size_ptr = vtable.offset(ptr_size, self)?;
self.memory
.get_mut(size_ptr.alloc_id)?
.write_ptr_sized(tcx, size_ptr, Scalar::from_uint(size, ptr_size).into())?;
let align_ptr = vtable.offset(ptr_size * 2, self)?;
self.memory
.get_mut(align_ptr.alloc_id)?
.write_ptr_sized(tcx, align_ptr, Scalar::from_uint(align, ptr_size).into())?;
for (i, method) in methods.iter().enumerate() {
if let Some((def_id, substs)) = *method {
let instance = self.resolve(def_id, substs)?;
let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag();
let method_ptr = vtable.offset(ptr_size * (3 + i as u64), self)?;
self.memory
.get_mut(method_ptr.alloc_id)?
.write_ptr_sized(tcx, method_ptr, Scalar::Ptr(fn_ptr).into())?;
}
}
self.memory.mark_immutable(vtable.alloc_id)?;
assert!(self.vtables.insert((ty, poly_trait_ref), vtable.alloc_id).is_none());
Ok(vtable)
}
/// Return the drop fn instance as well as the actual dynamic type
pub fn read_drop_type_from_vtable(
&self,
vtable: Pointer<M::PointerTag>,
) -> EvalResult<'tcx, (ty::Instance<'tcx>, ty::Ty<'tcx>)> {
// we don't care about the pointee type, we just want a pointer
self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
let drop_fn = self.memory
.get(vtable.alloc_id)?
.read_ptr_sized(self, vtable)?
.to_ptr()?;
let drop_instance = self.memory.get_fn(drop_fn)?;
trace!("Found drop fn: {:?}", drop_instance);
let fn_sig = drop_instance.ty(*self.tcx).fn_sig(*self.tcx);
let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, &fn_sig);
// the drop function takes *mut T where T is the type being dropped, so get that
let ty = fn_sig.inputs()[0].builtin_deref(true).unwrap().ty;
Ok((drop_instance, ty))
}
| ) -> EvalResult<'tcx, (Size, Align)> {
let pointer_size = self.pointer_size();
self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
let alloc = self.memory.get(vtable.alloc_id)?;
let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)?
.to_bits(pointer_size)? as u64;
let align = alloc.read_ptr_sized(
self,
vtable.offset(pointer_size * 2, self)?,
)?.to_bits(pointer_size)? as u64;
Ok((Size::from_bytes(size), Align::from_bytes(align).unwrap()))
}
} | pub fn read_size_and_align_from_vtable(
&self,
vtable: Pointer<M::PointerTag>, | random_line_split |
traits.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.
use rustc::ty::{self, Ty};
use rustc::ty::layout::{Size, Align, LayoutOf};
use rustc::mir::interpret::{Scalar, Pointer, EvalResult, PointerArithmetic};
use super::{EvalContext, Machine, MemoryKind};
impl<'a,'mir, 'tcx, M: Machine<'a,'mir, 'tcx>> EvalContext<'a,'mir, 'tcx, M> {
/// Creates a dynamic vtable for the given type and vtable origin. This is used only for
/// objects.
///
/// The `trait_ref` encodes the erased self type. Hence if we are
/// making an object `Foo<Trait>` from a value of type `Foo<T>`, then
/// `trait_ref` would map `T:Trait`.
pub fn | (
&mut self,
ty: Ty<'tcx>,
poly_trait_ref: ty::PolyExistentialTraitRef<'tcx>,
) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
trace!("get_vtable(trait_ref={:?})", poly_trait_ref);
let (ty, poly_trait_ref) = self.tcx.erase_regions(&(ty, poly_trait_ref));
if let Some(&vtable) = self.vtables.get(&(ty, poly_trait_ref)) {
return Ok(Pointer::from(vtable).with_default_tag());
}
let trait_ref = poly_trait_ref.with_self_ty(*self.tcx, ty);
let trait_ref = self.tcx.erase_regions(&trait_ref);
let methods = self.tcx.vtable_methods(trait_ref);
let layout = self.layout_of(ty)?;
assert!(!layout.is_unsized(), "can't create a vtable for an unsized type");
let size = layout.size.bytes();
let align = layout.align.abi.bytes();
let ptr_size = self.pointer_size();
let ptr_align = self.tcx.data_layout.pointer_align.abi;
// /////////////////////////////////////////////////////////////////////////////////////////
// If you touch this code, be sure to also make the corresponding changes to
// `get_vtable` in rust_codegen_llvm/meth.rs
// /////////////////////////////////////////////////////////////////////////////////////////
let vtable = self.memory.allocate(
ptr_size * (3 + methods.len() as u64),
ptr_align,
MemoryKind::Vtable,
)?.with_default_tag();
let tcx = &*self.tcx;
let drop = ::monomorphize::resolve_drop_in_place(*tcx, ty);
let drop = self.memory.create_fn_alloc(drop).with_default_tag();
// no need to do any alignment checks on the memory accesses below, because we know the
// allocation is correctly aligned as we created it above. Also we're only offsetting by
// multiples of `ptr_align`, which means that it will stay aligned to `ptr_align`.
self.memory
.get_mut(vtable.alloc_id)?
.write_ptr_sized(tcx, vtable, Scalar::Ptr(drop).into())?;
let size_ptr = vtable.offset(ptr_size, self)?;
self.memory
.get_mut(size_ptr.alloc_id)?
.write_ptr_sized(tcx, size_ptr, Scalar::from_uint(size, ptr_size).into())?;
let align_ptr = vtable.offset(ptr_size * 2, self)?;
self.memory
.get_mut(align_ptr.alloc_id)?
.write_ptr_sized(tcx, align_ptr, Scalar::from_uint(align, ptr_size).into())?;
for (i, method) in methods.iter().enumerate() {
if let Some((def_id, substs)) = *method {
let instance = self.resolve(def_id, substs)?;
let fn_ptr = self.memory.create_fn_alloc(instance).with_default_tag();
let method_ptr = vtable.offset(ptr_size * (3 + i as u64), self)?;
self.memory
.get_mut(method_ptr.alloc_id)?
.write_ptr_sized(tcx, method_ptr, Scalar::Ptr(fn_ptr).into())?;
}
}
self.memory.mark_immutable(vtable.alloc_id)?;
assert!(self.vtables.insert((ty, poly_trait_ref), vtable.alloc_id).is_none());
Ok(vtable)
}
/// Return the drop fn instance as well as the actual dynamic type
pub fn read_drop_type_from_vtable(
&self,
vtable: Pointer<M::PointerTag>,
) -> EvalResult<'tcx, (ty::Instance<'tcx>, ty::Ty<'tcx>)> {
// we don't care about the pointee type, we just want a pointer
self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
let drop_fn = self.memory
.get(vtable.alloc_id)?
.read_ptr_sized(self, vtable)?
.to_ptr()?;
let drop_instance = self.memory.get_fn(drop_fn)?;
trace!("Found drop fn: {:?}", drop_instance);
let fn_sig = drop_instance.ty(*self.tcx).fn_sig(*self.tcx);
let fn_sig = self.tcx.normalize_erasing_late_bound_regions(self.param_env, &fn_sig);
// the drop function takes *mut T where T is the type being dropped, so get that
let ty = fn_sig.inputs()[0].builtin_deref(true).unwrap().ty;
Ok((drop_instance, ty))
}
pub fn read_size_and_align_from_vtable(
&self,
vtable: Pointer<M::PointerTag>,
) -> EvalResult<'tcx, (Size, Align)> {
let pointer_size = self.pointer_size();
self.memory.check_align(vtable.into(), self.tcx.data_layout.pointer_align.abi)?;
let alloc = self.memory.get(vtable.alloc_id)?;
let size = alloc.read_ptr_sized(self, vtable.offset(pointer_size, self)?)?
.to_bits(pointer_size)? as u64;
let align = alloc.read_ptr_sized(
self,
vtable.offset(pointer_size * 2, self)?,
)?.to_bits(pointer_size)? as u64;
Ok((Size::from_bytes(size), Align::from_bytes(align).unwrap()))
}
}
| get_vtable | identifier_name |
associated-types-simple.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.
// pretty-expanded FIXME #23616
| }
struct Struct {
x: isize,
}
impl Get for Struct {
type Value = isize;
fn get(&self) -> &isize {
&self.x
}
}
fn main() {
let s = Struct {
x: 100,
};
assert_eq!(*s.get(), 100);
} | trait Get {
type Value;
fn get(&self) -> &<Self as Get>::Value; | random_line_split |
associated-types-simple.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.
// pretty-expanded FIXME #23616
trait Get {
type Value;
fn get(&self) -> &<Self as Get>::Value;
}
struct Struct {
x: isize,
}
impl Get for Struct {
type Value = isize;
fn | (&self) -> &isize {
&self.x
}
}
fn main() {
let s = Struct {
x: 100,
};
assert_eq!(*s.get(), 100);
}
| get | identifier_name |
associated-types-simple.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.
// pretty-expanded FIXME #23616
trait Get {
type Value;
fn get(&self) -> &<Self as Get>::Value;
}
struct Struct {
x: isize,
}
impl Get for Struct {
type Value = isize;
fn get(&self) -> &isize |
}
fn main() {
let s = Struct {
x: 100,
};
assert_eq!(*s.get(), 100);
}
| {
&self.x
} | identifier_body |
tasks.rs | use chrono::{Duration, Local};
use postgres::GenericConnection as PostgresConnection;
use redis::Connection as RedisConnection;
use timer::{Guard, Timer};
use db::{PostgresPool, RedisPool};
use library::streak::Streak;
pub struct TaskRunner {
timer: Timer,
pg_pool: PostgresPool,
redis_pool: RedisPool,
}
macro_rules! get_conn {
($pool:ident) => {
match $pool.get() {
Ok(conn) => conn,
Err(err) => {
error!("Failed to get pooled connection: {}", err);
return;
}
}
}
}
impl TaskRunner {
pub fn | (pg_pool: PostgresPool, redis_pool: RedisPool) -> TaskRunner {
TaskRunner {
timer: Timer::new(),
pg_pool: pg_pool,
redis_pool: redis_pool,
}
}
pub fn run(&self) -> Vec<Guard> {
let mut guards = Vec::<Guard>::new();
guards.push({
let pg_pool = self.pg_pool.clone();
let redis_pool = self.redis_pool.clone();
self.timer.schedule(Local::now(), Some(Duration::days(1)), move || {
let pg_conn = get_conn!(pg_pool);
let redis_conn = get_conn!(redis_pool);
update_streak(&*pg_conn, &redis_conn);
})
});
guards
}
}
fn update_streak(pg: &PostgresConnection, rds: &RedisConnection) {
let streak = match Streak::calculate(pg) {
Ok(streak) => streak,
Err(err) => {
error!("Failed to calculate streak: {}", err);
return;
}
};
if let Err(err) = streak.save(rds) {
error!("Failed to save streak: {}", err);
} else {
trace!("Streak updated: {:?}", streak);
}
}
| new | identifier_name |
tasks.rs | use chrono::{Duration, Local};
use postgres::GenericConnection as PostgresConnection;
use redis::Connection as RedisConnection;
use timer::{Guard, Timer};
use db::{PostgresPool, RedisPool};
use library::streak::Streak;
pub struct TaskRunner {
timer: Timer,
pg_pool: PostgresPool, | macro_rules! get_conn {
($pool:ident) => {
match $pool.get() {
Ok(conn) => conn,
Err(err) => {
error!("Failed to get pooled connection: {}", err);
return;
}
}
}
}
impl TaskRunner {
pub fn new(pg_pool: PostgresPool, redis_pool: RedisPool) -> TaskRunner {
TaskRunner {
timer: Timer::new(),
pg_pool: pg_pool,
redis_pool: redis_pool,
}
}
pub fn run(&self) -> Vec<Guard> {
let mut guards = Vec::<Guard>::new();
guards.push({
let pg_pool = self.pg_pool.clone();
let redis_pool = self.redis_pool.clone();
self.timer.schedule(Local::now(), Some(Duration::days(1)), move || {
let pg_conn = get_conn!(pg_pool);
let redis_conn = get_conn!(redis_pool);
update_streak(&*pg_conn, &redis_conn);
})
});
guards
}
}
fn update_streak(pg: &PostgresConnection, rds: &RedisConnection) {
let streak = match Streak::calculate(pg) {
Ok(streak) => streak,
Err(err) => {
error!("Failed to calculate streak: {}", err);
return;
}
};
if let Err(err) = streak.save(rds) {
error!("Failed to save streak: {}", err);
} else {
trace!("Streak updated: {:?}", streak);
}
} | redis_pool: RedisPool,
}
| random_line_split |
tasks.rs | use chrono::{Duration, Local};
use postgres::GenericConnection as PostgresConnection;
use redis::Connection as RedisConnection;
use timer::{Guard, Timer};
use db::{PostgresPool, RedisPool};
use library::streak::Streak;
pub struct TaskRunner {
timer: Timer,
pg_pool: PostgresPool,
redis_pool: RedisPool,
}
macro_rules! get_conn {
($pool:ident) => {
match $pool.get() {
Ok(conn) => conn,
Err(err) => {
error!("Failed to get pooled connection: {}", err);
return;
}
}
}
}
impl TaskRunner {
pub fn new(pg_pool: PostgresPool, redis_pool: RedisPool) -> TaskRunner {
TaskRunner {
timer: Timer::new(),
pg_pool: pg_pool,
redis_pool: redis_pool,
}
}
pub fn run(&self) -> Vec<Guard> {
let mut guards = Vec::<Guard>::new();
guards.push({
let pg_pool = self.pg_pool.clone();
let redis_pool = self.redis_pool.clone();
self.timer.schedule(Local::now(), Some(Duration::days(1)), move || {
let pg_conn = get_conn!(pg_pool);
let redis_conn = get_conn!(redis_pool);
update_streak(&*pg_conn, &redis_conn);
})
});
guards
}
}
fn update_streak(pg: &PostgresConnection, rds: &RedisConnection) {
let streak = match Streak::calculate(pg) {
Ok(streak) => streak,
Err(err) => |
};
if let Err(err) = streak.save(rds) {
error!("Failed to save streak: {}", err);
} else {
trace!("Streak updated: {:?}", streak);
}
}
| {
error!("Failed to calculate streak: {}", err);
return;
} | conditional_block |
tasks.rs | use chrono::{Duration, Local};
use postgres::GenericConnection as PostgresConnection;
use redis::Connection as RedisConnection;
use timer::{Guard, Timer};
use db::{PostgresPool, RedisPool};
use library::streak::Streak;
pub struct TaskRunner {
timer: Timer,
pg_pool: PostgresPool,
redis_pool: RedisPool,
}
macro_rules! get_conn {
($pool:ident) => {
match $pool.get() {
Ok(conn) => conn,
Err(err) => {
error!("Failed to get pooled connection: {}", err);
return;
}
}
}
}
impl TaskRunner {
pub fn new(pg_pool: PostgresPool, redis_pool: RedisPool) -> TaskRunner {
TaskRunner {
timer: Timer::new(),
pg_pool: pg_pool,
redis_pool: redis_pool,
}
}
pub fn run(&self) -> Vec<Guard> |
}
fn update_streak(pg: &PostgresConnection, rds: &RedisConnection) {
let streak = match Streak::calculate(pg) {
Ok(streak) => streak,
Err(err) => {
error!("Failed to calculate streak: {}", err);
return;
}
};
if let Err(err) = streak.save(rds) {
error!("Failed to save streak: {}", err);
} else {
trace!("Streak updated: {:?}", streak);
}
}
| {
let mut guards = Vec::<Guard>::new();
guards.push({
let pg_pool = self.pg_pool.clone();
let redis_pool = self.redis_pool.clone();
self.timer.schedule(Local::now(), Some(Duration::days(1)), move || {
let pg_conn = get_conn!(pg_pool);
let redis_conn = get_conn!(redis_pool);
update_streak(&*pg_conn, &redis_conn);
})
});
guards
} | identifier_body |
struct-destructuring-cross-crate.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.
// xfail-fast
// aux-build:struct_destructuring_cross_crate.rs
extern mod struct_destructuring_cross_crate;
| pub fn main() {
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
} | random_line_split | |
struct-destructuring-cross-crate.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.
// xfail-fast
// aux-build:struct_destructuring_cross_crate.rs
extern mod struct_destructuring_cross_crate;
pub fn | () {
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
}
| main | identifier_name |
struct-destructuring-cross-crate.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.
// xfail-fast
// aux-build:struct_destructuring_cross_crate.rs
extern mod struct_destructuring_cross_crate;
pub fn main() | {
let x = struct_destructuring_cross_crate::S { x: 1, y: 2 };
let struct_destructuring_cross_crate::S { x: a, y: b } = x;
assert_eq!(a, 1);
assert_eq!(b, 2);
} | identifier_body | |
browsingcontext.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use dom::bindings::js::{JS, Root, RootedReference};
use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor};
use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector};
use dom::bindings::str::DOMString;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::WindowProxyHandler;
use dom::bindings::utils::get_array_index_from_id;
use dom::document::Document;
use dom::element::Element;
use dom::window::Window;
use js::JSCLASS_IS_GLOBAL;
use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy};
use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra};
use js::jsapi::{Handle, HandleId, HandleObject, HandleValue};
use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject};
use js::jsapi::{JSPROP_READONLY, JSTracer, JS_DefinePropertyById};
use js::jsapi::{JS_ForwardGetPropertyTo, JS_ForwardSetPropertyTo, JS_GetClass};
use js::jsapi::{JS_GetOwnPropertyDescriptorById, JS_HasPropertyById};
use js::jsapi::{MutableHandle, MutableHandleObject, MutableHandleValue};
use js::jsapi::{ObjectOpResult, PropertyDescriptor};
use js::jsval::{UndefinedValue, PrivateValue};
use msg::constellation_msg::{PipelineId, SubpageId};
use std::cell::Cell;
use url::Url;
#[dom_struct]
pub struct BrowsingContext {
reflector: Reflector,
/// Pipeline id associated with this context.
id: PipelineId,
/// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>,
/// Stores this context's session history
history: DOMRefCell<Vec<SessionHistoryEntry>>,
/// The index of the active session history entry
active_index: Cell<usize>,
/// Stores the child browsing contexts (ex. iframe browsing context)
children: DOMRefCell<Vec<JS<BrowsingContext>>>,
frame_element: Option<JS<Element>>,
}
impl BrowsingContext {
pub fn new_inherited(frame_element: Option<&Element>, id: PipelineId) -> BrowsingContext {
BrowsingContext {
reflector: Reflector::new(),
id: id,
needs_reflow: Cell::new(true),
history: DOMRefCell::new(vec![]),
active_index: Cell::new(0),
children: DOMRefCell::new(vec![]),
frame_element: frame_element.map(JS::from_ref),
}
}
#[allow(unsafe_code)]
pub fn new(window: &Window, frame_element: Option<&Element>, id: PipelineId) -> Root<BrowsingContext> {
unsafe {
let WindowProxyHandler(handler) = window.windowproxy_handler();
assert!(!handler.is_null());
let cx = window.get_cx();
let parent = window.reflector().get_jsobject();
assert!(!parent.get().is_null());
assert!(((*JS_GetClass(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0);
let _ac = JSAutoCompartment::new(cx, parent.get());
rooted!(in(cx) let window_proxy = NewWindowProxy(cx, parent, handler));
assert!(!window_proxy.is_null());
let object = box BrowsingContext::new_inherited(frame_element, id);
let raw = Box::into_raw(object);
SetProxyExtra(window_proxy.get(), 0, &PrivateValue(raw as *const _));
(*raw).init_reflector(window_proxy.get());
Root::from_ref(&*raw)
}
}
pub fn init(&self, document: &Document) {
assert!(self.history.borrow().is_empty());
assert_eq!(self.active_index.get(), 0);
self.history.borrow_mut().push(SessionHistoryEntry::new(document, document.url().clone(), document.Title()));
}
pub fn push_history(&self, document: &Document) {
let mut history = self.history.borrow_mut();
// Clear all session history entries after the active index
history.drain((self.active_index.get() + 1)..);
history.push(SessionHistoryEntry::new(document, document.url().clone(), document.Title()));
self.active_index.set(self.active_index.get() + 1);
assert_eq!(self.active_index.get(), history.len() - 1);
}
pub fn active_document(&self) -> Root<Document> {
Root::from_ref(&self.history.borrow()[self.active_index.get()].document)
}
pub fn maybe_active_document(&self) -> Option<Root<Document>> {
self.history.borrow().get(self.active_index.get()).map(|entry| {
Root::from_ref(&*entry.document)
})
}
pub fn active_window(&self) -> Root<Window> {
Root::from_ref(self.active_document().window())
}
pub fn frame_element(&self) -> Option<&Element> {
self.frame_element.r()
}
pub fn window_proxy(&self) -> *mut JSObject {
let window_proxy = self.reflector.get_jsobject();
assert!(!window_proxy.get().is_null());
window_proxy.get()
}
pub fn remove(&self, id: PipelineId) -> Option<Root<BrowsingContext>> {
let remove_idx = self.children
.borrow()
.iter()
.position(|context| context.id == id);
match remove_idx {
Some(idx) => Some(Root::from_ref(&*self.children.borrow_mut().remove(idx))),
None => {
self.children
.borrow_mut()
.iter_mut()
.filter_map(|context| context.remove(id))
.next()
}
}
}
pub fn set_reflow_status(&self, status: bool) -> bool {
let old = self.needs_reflow.get();
self.needs_reflow.set(status);
old
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn push_child_context(&self, context: &BrowsingContext) {
self.children.borrow_mut().push(JS::from_ref(&context));
}
pub fn find_child_by_subpage(&self, subpage_id: SubpageId) -> Option<Root<Window>> {
self.children.borrow().iter().find(|context| {
let window = context.active_window();
window.subpage() == Some(subpage_id)
}).map(|context| context.active_window())
}
pub fn clear_session_history(&self) {
self.active_index.set(0);
self.history.borrow_mut().clear();
}
pub fn iter(&self) -> ContextIterator {
ContextIterator {
stack: vec!(Root::from_ref(self)),
}
}
pub fn find(&self, id: PipelineId) -> Option<Root<BrowsingContext>> {
if self.id == id {
return Some(Root::from_ref(self));
}
self.children.borrow()
.iter()
.filter_map(|c| c.find(id))
.next()
}
}
pub struct ContextIterator {
stack: Vec<Root<BrowsingContext>>,
}
impl Iterator for ContextIterator {
type Item = Root<BrowsingContext>;
fn next(&mut self) -> Option<Root<BrowsingContext>> {
let popped = self.stack.pop();
if let Some(ref context) = popped {
self.stack.extend(context.children.borrow()
.iter()
.map(|c| Root::from_ref(&**c)));
}
popped
}
}
// This isn't a DOM struct, just a convenience struct
// without a reflector, so we don't mark this as #[dom_struct]
#[must_root]
#[privatize]
#[derive(JSTraceable, HeapSizeOf)]
pub struct SessionHistoryEntry {
document: JS<Document>,
url: Url,
title: DOMString,
}
impl SessionHistoryEntry {
fn new(document: &Document, url: Url, title: DOMString) -> SessionHistoryEntry {
SessionHistoryEntry {
document: JS::from_ref(document),
url: url,
title: title,
}
}
}
#[allow(unsafe_code)]
unsafe fn GetSubframeWindow(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId)
-> Option<Root<Window>> {
let index = get_array_index_from_id(cx, id);
if let Some(index) = index {
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
let win = root_from_handleobject::<Window>(target.handle()).unwrap();
let mut found = false;
return win.IndexedGetter(index, &mut found);
}
None
}
#[allow(unsafe_code)]
unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
mut desc: MutableHandle<PropertyDescriptor>)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if let Some(window) = window {
rooted!(in(cx) let mut val = UndefinedValue());
window.to_jsval(cx, val.handle_mut());
desc.value = val.get();
fill_property_descriptor(&mut desc, proxy.get(), JSPROP_READONLY);
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(proxy.get()).to_object());
if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) {
return false;
}
assert!(desc.obj.is_null() || desc.obj == target.get());
if desc.obj == target.get() {
// FIXME(#11868) Should assign to desc.obj, desc.get() is a copy.
desc.get().obj = proxy.get();
}
true
}
#[allow(unsafe_code)]
unsafe extern "C" fn defineProperty(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
desc: Handle<PropertyDescriptor>,
res: *mut ObjectOpResult)
-> bool {
if get_array_index_from_id(cx, id).is_some() {
// Spec says to Reject whether this is a supported index or not,
// since we have no indexed setter or indexed creator. That means
// throwing in strict mode (FIXME: Bug 828137), doing nothing in
// non-strict mode.
(*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_DefinePropertyById(cx, target.handle(), id, desc, res)
}
#[allow(unsafe_code)]
unsafe extern "C" fn | (cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
bp: *mut bool)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if window.is_some() {
*bp = true;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
let mut found = false;
if!JS_HasPropertyById(cx, target.handle(), id, &mut found) {
return false;
}
*bp = found;
true
}
#[allow(unsafe_code)]
unsafe extern "C" fn get(cx: *mut JSContext,
proxy: HandleObject,
receiver: HandleValue,
id: HandleId,
vp: MutableHandleValue)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if let Some(window) = window {
window.to_jsval(cx, vp);
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp)
}
#[allow(unsafe_code)]
unsafe extern "C" fn set(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
v: HandleValue,
receiver: HandleValue,
res: *mut ObjectOpResult)
-> bool {
if get_array_index_from_id(cx, id).is_some() {
// Reject (which means throw if and only if strict) the set.
(*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_ForwardSetPropertyTo(cx,
target.handle(),
id,
v,
receiver,
res)
}
#[allow(unsafe_code)]
unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext,
_: HandleObject,
is_ordinary: *mut bool,
_: MutableHandleObject)
-> bool {
// Window's [[GetPrototypeOf]] trap isn't the ordinary definition:
//
// https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof
//
// We nonetheless can implement it with a static [[Prototype]], because
// wrapper-class handlers (particularly, XOW in FilteringWrapper.cpp) supply
// all non-ordinary behavior.
//
// But from a spec point of view, it's the exact same object in both cases --
// only the observer's changed. So this getPrototypeIfOrdinary trap on the
// non-wrapper object *must* report non-ordinary, even if static [[Prototype]]
// usually means ordinary.
*is_ordinary = false;
return true;
}
static PROXY_HANDLER: ProxyTraps = ProxyTraps {
enter: None,
getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor),
defineProperty: Some(defineProperty),
ownPropertyKeys: None,
delete_: None,
enumerate: None,
getPrototypeIfOrdinary: Some(get_prototype_if_ordinary),
preventExtensions: None,
isExtensible: None,
has: Some(has),
get: Some(get),
set: Some(set),
call: None,
construct: None,
getPropertyDescriptor: Some(get_property_descriptor),
hasOwn: None,
getOwnEnumerablePropertyKeys: None,
nativeCall: None,
hasInstance: None,
objectClassIs: None,
className: None,
fun_toString: None,
boxedValue_unbox: None,
defaultValue: None,
trace: Some(trace),
finalize: Some(finalize),
objectMoved: None,
isCallable: None,
isConstructor: None,
};
#[allow(unsafe_code)]
unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) {
let this = GetProxyExtra(obj, 0).to_private() as *mut BrowsingContext;
assert!(!this.is_null());
let _ = Box::from_raw(this);
debug!("BrowsingContext finalize: {:p}", this);
}
#[allow(unsafe_code)]
unsafe extern fn trace(trc: *mut JSTracer, obj: *mut JSObject) {
let this = GetProxyExtra(obj, 0).to_private() as *const BrowsingContext;
if this.is_null() {
// GC during obj creation
return;
}
(*this).trace(trc);
}
#[allow(unsafe_code)]
pub fn new_window_proxy_handler() -> WindowProxyHandler {
unsafe {
WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER))
}
}
| has | identifier_name |
browsingcontext.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use dom::bindings::js::{JS, Root, RootedReference};
use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor};
use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector};
use dom::bindings::str::DOMString;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::WindowProxyHandler;
use dom::bindings::utils::get_array_index_from_id;
use dom::document::Document;
use dom::element::Element;
use dom::window::Window;
use js::JSCLASS_IS_GLOBAL;
use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy};
use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra};
use js::jsapi::{Handle, HandleId, HandleObject, HandleValue};
use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject};
use js::jsapi::{JSPROP_READONLY, JSTracer, JS_DefinePropertyById};
use js::jsapi::{JS_ForwardGetPropertyTo, JS_ForwardSetPropertyTo, JS_GetClass};
use js::jsapi::{JS_GetOwnPropertyDescriptorById, JS_HasPropertyById};
use js::jsapi::{MutableHandle, MutableHandleObject, MutableHandleValue};
use js::jsapi::{ObjectOpResult, PropertyDescriptor};
use js::jsval::{UndefinedValue, PrivateValue};
use msg::constellation_msg::{PipelineId, SubpageId};
use std::cell::Cell;
use url::Url;
#[dom_struct]
pub struct BrowsingContext {
reflector: Reflector,
/// Pipeline id associated with this context.
id: PipelineId,
/// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>,
/// Stores this context's session history
history: DOMRefCell<Vec<SessionHistoryEntry>>,
/// The index of the active session history entry
active_index: Cell<usize>,
/// Stores the child browsing contexts (ex. iframe browsing context)
children: DOMRefCell<Vec<JS<BrowsingContext>>>,
frame_element: Option<JS<Element>>,
}
impl BrowsingContext {
pub fn new_inherited(frame_element: Option<&Element>, id: PipelineId) -> BrowsingContext {
BrowsingContext {
reflector: Reflector::new(),
id: id,
needs_reflow: Cell::new(true),
history: DOMRefCell::new(vec![]),
active_index: Cell::new(0),
children: DOMRefCell::new(vec![]),
frame_element: frame_element.map(JS::from_ref),
}
}
#[allow(unsafe_code)]
pub fn new(window: &Window, frame_element: Option<&Element>, id: PipelineId) -> Root<BrowsingContext> {
unsafe {
let WindowProxyHandler(handler) = window.windowproxy_handler();
assert!(!handler.is_null());
let cx = window.get_cx();
let parent = window.reflector().get_jsobject();
assert!(!parent.get().is_null());
assert!(((*JS_GetClass(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0);
let _ac = JSAutoCompartment::new(cx, parent.get());
rooted!(in(cx) let window_proxy = NewWindowProxy(cx, parent, handler));
assert!(!window_proxy.is_null());
let object = box BrowsingContext::new_inherited(frame_element, id);
let raw = Box::into_raw(object);
SetProxyExtra(window_proxy.get(), 0, &PrivateValue(raw as *const _));
(*raw).init_reflector(window_proxy.get());
Root::from_ref(&*raw)
}
}
pub fn init(&self, document: &Document) {
assert!(self.history.borrow().is_empty());
assert_eq!(self.active_index.get(), 0);
self.history.borrow_mut().push(SessionHistoryEntry::new(document, document.url().clone(), document.Title()));
}
pub fn push_history(&self, document: &Document) {
let mut history = self.history.borrow_mut();
// Clear all session history entries after the active index
history.drain((self.active_index.get() + 1)..);
history.push(SessionHistoryEntry::new(document, document.url().clone(), document.Title()));
self.active_index.set(self.active_index.get() + 1);
assert_eq!(self.active_index.get(), history.len() - 1);
}
pub fn active_document(&self) -> Root<Document> {
Root::from_ref(&self.history.borrow()[self.active_index.get()].document)
}
pub fn maybe_active_document(&self) -> Option<Root<Document>> {
self.history.borrow().get(self.active_index.get()).map(|entry| {
Root::from_ref(&*entry.document)
})
}
pub fn active_window(&self) -> Root<Window> {
Root::from_ref(self.active_document().window())
}
pub fn frame_element(&self) -> Option<&Element> {
self.frame_element.r()
}
pub fn window_proxy(&self) -> *mut JSObject {
let window_proxy = self.reflector.get_jsobject();
assert!(!window_proxy.get().is_null());
window_proxy.get()
}
pub fn remove(&self, id: PipelineId) -> Option<Root<BrowsingContext>> {
let remove_idx = self.children
.borrow()
.iter()
.position(|context| context.id == id);
match remove_idx {
Some(idx) => Some(Root::from_ref(&*self.children.borrow_mut().remove(idx))),
None => |
}
}
pub fn set_reflow_status(&self, status: bool) -> bool {
let old = self.needs_reflow.get();
self.needs_reflow.set(status);
old
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn push_child_context(&self, context: &BrowsingContext) {
self.children.borrow_mut().push(JS::from_ref(&context));
}
pub fn find_child_by_subpage(&self, subpage_id: SubpageId) -> Option<Root<Window>> {
self.children.borrow().iter().find(|context| {
let window = context.active_window();
window.subpage() == Some(subpage_id)
}).map(|context| context.active_window())
}
pub fn clear_session_history(&self) {
self.active_index.set(0);
self.history.borrow_mut().clear();
}
pub fn iter(&self) -> ContextIterator {
ContextIterator {
stack: vec!(Root::from_ref(self)),
}
}
pub fn find(&self, id: PipelineId) -> Option<Root<BrowsingContext>> {
if self.id == id {
return Some(Root::from_ref(self));
}
self.children.borrow()
.iter()
.filter_map(|c| c.find(id))
.next()
}
}
pub struct ContextIterator {
stack: Vec<Root<BrowsingContext>>,
}
impl Iterator for ContextIterator {
type Item = Root<BrowsingContext>;
fn next(&mut self) -> Option<Root<BrowsingContext>> {
let popped = self.stack.pop();
if let Some(ref context) = popped {
self.stack.extend(context.children.borrow()
.iter()
.map(|c| Root::from_ref(&**c)));
}
popped
}
}
// This isn't a DOM struct, just a convenience struct
// without a reflector, so we don't mark this as #[dom_struct]
#[must_root]
#[privatize]
#[derive(JSTraceable, HeapSizeOf)]
pub struct SessionHistoryEntry {
document: JS<Document>,
url: Url,
title: DOMString,
}
impl SessionHistoryEntry {
fn new(document: &Document, url: Url, title: DOMString) -> SessionHistoryEntry {
SessionHistoryEntry {
document: JS::from_ref(document),
url: url,
title: title,
}
}
}
#[allow(unsafe_code)]
unsafe fn GetSubframeWindow(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId)
-> Option<Root<Window>> {
let index = get_array_index_from_id(cx, id);
if let Some(index) = index {
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
let win = root_from_handleobject::<Window>(target.handle()).unwrap();
let mut found = false;
return win.IndexedGetter(index, &mut found);
}
None
}
#[allow(unsafe_code)]
unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
mut desc: MutableHandle<PropertyDescriptor>)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if let Some(window) = window {
rooted!(in(cx) let mut val = UndefinedValue());
window.to_jsval(cx, val.handle_mut());
desc.value = val.get();
fill_property_descriptor(&mut desc, proxy.get(), JSPROP_READONLY);
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(proxy.get()).to_object());
if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) {
return false;
}
assert!(desc.obj.is_null() || desc.obj == target.get());
if desc.obj == target.get() {
// FIXME(#11868) Should assign to desc.obj, desc.get() is a copy.
desc.get().obj = proxy.get();
}
true
}
#[allow(unsafe_code)]
unsafe extern "C" fn defineProperty(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
desc: Handle<PropertyDescriptor>,
res: *mut ObjectOpResult)
-> bool {
if get_array_index_from_id(cx, id).is_some() {
// Spec says to Reject whether this is a supported index or not,
// since we have no indexed setter or indexed creator. That means
// throwing in strict mode (FIXME: Bug 828137), doing nothing in
// non-strict mode.
(*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_DefinePropertyById(cx, target.handle(), id, desc, res)
}
#[allow(unsafe_code)]
unsafe extern "C" fn has(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
bp: *mut bool)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if window.is_some() {
*bp = true;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
let mut found = false;
if!JS_HasPropertyById(cx, target.handle(), id, &mut found) {
return false;
}
*bp = found;
true
}
#[allow(unsafe_code)]
unsafe extern "C" fn get(cx: *mut JSContext,
proxy: HandleObject,
receiver: HandleValue,
id: HandleId,
vp: MutableHandleValue)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if let Some(window) = window {
window.to_jsval(cx, vp);
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp)
}
#[allow(unsafe_code)]
unsafe extern "C" fn set(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
v: HandleValue,
receiver: HandleValue,
res: *mut ObjectOpResult)
-> bool {
if get_array_index_from_id(cx, id).is_some() {
// Reject (which means throw if and only if strict) the set.
(*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_ForwardSetPropertyTo(cx,
target.handle(),
id,
v,
receiver,
res)
}
#[allow(unsafe_code)]
unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext,
_: HandleObject,
is_ordinary: *mut bool,
_: MutableHandleObject)
-> bool {
// Window's [[GetPrototypeOf]] trap isn't the ordinary definition:
//
// https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof
//
// We nonetheless can implement it with a static [[Prototype]], because
// wrapper-class handlers (particularly, XOW in FilteringWrapper.cpp) supply
// all non-ordinary behavior.
//
// But from a spec point of view, it's the exact same object in both cases --
// only the observer's changed. So this getPrototypeIfOrdinary trap on the
// non-wrapper object *must* report non-ordinary, even if static [[Prototype]]
// usually means ordinary.
*is_ordinary = false;
return true;
}
static PROXY_HANDLER: ProxyTraps = ProxyTraps {
enter: None,
getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor),
defineProperty: Some(defineProperty),
ownPropertyKeys: None,
delete_: None,
enumerate: None,
getPrototypeIfOrdinary: Some(get_prototype_if_ordinary),
preventExtensions: None,
isExtensible: None,
has: Some(has),
get: Some(get),
set: Some(set),
call: None,
construct: None,
getPropertyDescriptor: Some(get_property_descriptor),
hasOwn: None,
getOwnEnumerablePropertyKeys: None,
nativeCall: None,
hasInstance: None,
objectClassIs: None,
className: None,
fun_toString: None,
boxedValue_unbox: None,
defaultValue: None,
trace: Some(trace),
finalize: Some(finalize),
objectMoved: None,
isCallable: None,
isConstructor: None,
};
#[allow(unsafe_code)]
unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) {
let this = GetProxyExtra(obj, 0).to_private() as *mut BrowsingContext;
assert!(!this.is_null());
let _ = Box::from_raw(this);
debug!("BrowsingContext finalize: {:p}", this);
}
#[allow(unsafe_code)]
unsafe extern fn trace(trc: *mut JSTracer, obj: *mut JSObject) {
let this = GetProxyExtra(obj, 0).to_private() as *const BrowsingContext;
if this.is_null() {
// GC during obj creation
return;
}
(*this).trace(trc);
}
#[allow(unsafe_code)]
pub fn new_window_proxy_handler() -> WindowProxyHandler {
unsafe {
WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER))
}
}
| {
self.children
.borrow_mut()
.iter_mut()
.filter_map(|context| context.remove(id))
.next()
} | conditional_block |
browsingcontext.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use dom::bindings::js::{JS, Root, RootedReference};
use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor};
use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector};
use dom::bindings::str::DOMString;
use dom::bindings::trace::JSTraceable;
use dom::bindings::utils::WindowProxyHandler;
use dom::bindings::utils::get_array_index_from_id;
use dom::document::Document;
use dom::element::Element;
use dom::window::Window;
use js::JSCLASS_IS_GLOBAL;
use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy};
use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra};
use js::jsapi::{Handle, HandleId, HandleObject, HandleValue};
use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject};
use js::jsapi::{JSPROP_READONLY, JSTracer, JS_DefinePropertyById};
use js::jsapi::{JS_ForwardGetPropertyTo, JS_ForwardSetPropertyTo, JS_GetClass};
use js::jsapi::{JS_GetOwnPropertyDescriptorById, JS_HasPropertyById};
use js::jsapi::{MutableHandle, MutableHandleObject, MutableHandleValue};
use js::jsapi::{ObjectOpResult, PropertyDescriptor};
use js::jsval::{UndefinedValue, PrivateValue};
use msg::constellation_msg::{PipelineId, SubpageId};
use std::cell::Cell;
use url::Url;
#[dom_struct]
pub struct BrowsingContext {
reflector: Reflector,
/// Pipeline id associated with this context.
id: PipelineId,
/// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>,
/// Stores this context's session history
history: DOMRefCell<Vec<SessionHistoryEntry>>,
/// The index of the active session history entry
active_index: Cell<usize>,
/// Stores the child browsing contexts (ex. iframe browsing context)
children: DOMRefCell<Vec<JS<BrowsingContext>>>,
frame_element: Option<JS<Element>>,
}
impl BrowsingContext {
pub fn new_inherited(frame_element: Option<&Element>, id: PipelineId) -> BrowsingContext {
BrowsingContext {
reflector: Reflector::new(),
id: id,
needs_reflow: Cell::new(true),
history: DOMRefCell::new(vec![]),
active_index: Cell::new(0),
children: DOMRefCell::new(vec![]),
frame_element: frame_element.map(JS::from_ref),
}
}
#[allow(unsafe_code)]
pub fn new(window: &Window, frame_element: Option<&Element>, id: PipelineId) -> Root<BrowsingContext> {
unsafe {
let WindowProxyHandler(handler) = window.windowproxy_handler();
assert!(!handler.is_null());
let cx = window.get_cx();
let parent = window.reflector().get_jsobject();
assert!(!parent.get().is_null());
assert!(((*JS_GetClass(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0);
let _ac = JSAutoCompartment::new(cx, parent.get());
rooted!(in(cx) let window_proxy = NewWindowProxy(cx, parent, handler));
assert!(!window_proxy.is_null());
let object = box BrowsingContext::new_inherited(frame_element, id);
let raw = Box::into_raw(object);
SetProxyExtra(window_proxy.get(), 0, &PrivateValue(raw as *const _));
(*raw).init_reflector(window_proxy.get());
Root::from_ref(&*raw)
}
}
pub fn init(&self, document: &Document) {
assert!(self.history.borrow().is_empty());
assert_eq!(self.active_index.get(), 0);
self.history.borrow_mut().push(SessionHistoryEntry::new(document, document.url().clone(), document.Title()));
}
pub fn push_history(&self, document: &Document) |
pub fn active_document(&self) -> Root<Document> {
Root::from_ref(&self.history.borrow()[self.active_index.get()].document)
}
pub fn maybe_active_document(&self) -> Option<Root<Document>> {
self.history.borrow().get(self.active_index.get()).map(|entry| {
Root::from_ref(&*entry.document)
})
}
pub fn active_window(&self) -> Root<Window> {
Root::from_ref(self.active_document().window())
}
pub fn frame_element(&self) -> Option<&Element> {
self.frame_element.r()
}
pub fn window_proxy(&self) -> *mut JSObject {
let window_proxy = self.reflector.get_jsobject();
assert!(!window_proxy.get().is_null());
window_proxy.get()
}
pub fn remove(&self, id: PipelineId) -> Option<Root<BrowsingContext>> {
let remove_idx = self.children
.borrow()
.iter()
.position(|context| context.id == id);
match remove_idx {
Some(idx) => Some(Root::from_ref(&*self.children.borrow_mut().remove(idx))),
None => {
self.children
.borrow_mut()
.iter_mut()
.filter_map(|context| context.remove(id))
.next()
}
}
}
pub fn set_reflow_status(&self, status: bool) -> bool {
let old = self.needs_reflow.get();
self.needs_reflow.set(status);
old
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn push_child_context(&self, context: &BrowsingContext) {
self.children.borrow_mut().push(JS::from_ref(&context));
}
pub fn find_child_by_subpage(&self, subpage_id: SubpageId) -> Option<Root<Window>> {
self.children.borrow().iter().find(|context| {
let window = context.active_window();
window.subpage() == Some(subpage_id)
}).map(|context| context.active_window())
}
pub fn clear_session_history(&self) {
self.active_index.set(0);
self.history.borrow_mut().clear();
}
pub fn iter(&self) -> ContextIterator {
ContextIterator {
stack: vec!(Root::from_ref(self)),
}
}
pub fn find(&self, id: PipelineId) -> Option<Root<BrowsingContext>> {
if self.id == id {
return Some(Root::from_ref(self));
}
self.children.borrow()
.iter()
.filter_map(|c| c.find(id))
.next()
}
}
pub struct ContextIterator {
stack: Vec<Root<BrowsingContext>>,
}
impl Iterator for ContextIterator {
type Item = Root<BrowsingContext>;
fn next(&mut self) -> Option<Root<BrowsingContext>> {
let popped = self.stack.pop();
if let Some(ref context) = popped {
self.stack.extend(context.children.borrow()
.iter()
.map(|c| Root::from_ref(&**c)));
}
popped
}
}
// This isn't a DOM struct, just a convenience struct
// without a reflector, so we don't mark this as #[dom_struct]
#[must_root]
#[privatize]
#[derive(JSTraceable, HeapSizeOf)]
pub struct SessionHistoryEntry {
document: JS<Document>,
url: Url,
title: DOMString,
}
impl SessionHistoryEntry {
fn new(document: &Document, url: Url, title: DOMString) -> SessionHistoryEntry {
SessionHistoryEntry {
document: JS::from_ref(document),
url: url,
title: title,
}
}
}
#[allow(unsafe_code)]
unsafe fn GetSubframeWindow(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId)
-> Option<Root<Window>> {
let index = get_array_index_from_id(cx, id);
if let Some(index) = index {
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
let win = root_from_handleobject::<Window>(target.handle()).unwrap();
let mut found = false;
return win.IndexedGetter(index, &mut found);
}
None
}
#[allow(unsafe_code)]
unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
mut desc: MutableHandle<PropertyDescriptor>)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if let Some(window) = window {
rooted!(in(cx) let mut val = UndefinedValue());
window.to_jsval(cx, val.handle_mut());
desc.value = val.get();
fill_property_descriptor(&mut desc, proxy.get(), JSPROP_READONLY);
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(proxy.get()).to_object());
if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) {
return false;
}
assert!(desc.obj.is_null() || desc.obj == target.get());
if desc.obj == target.get() {
// FIXME(#11868) Should assign to desc.obj, desc.get() is a copy.
desc.get().obj = proxy.get();
}
true
}
#[allow(unsafe_code)]
unsafe extern "C" fn defineProperty(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
desc: Handle<PropertyDescriptor>,
res: *mut ObjectOpResult)
-> bool {
if get_array_index_from_id(cx, id).is_some() {
// Spec says to Reject whether this is a supported index or not,
// since we have no indexed setter or indexed creator. That means
// throwing in strict mode (FIXME: Bug 828137), doing nothing in
// non-strict mode.
(*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_DefinePropertyById(cx, target.handle(), id, desc, res)
}
#[allow(unsafe_code)]
unsafe extern "C" fn has(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
bp: *mut bool)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if window.is_some() {
*bp = true;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
let mut found = false;
if!JS_HasPropertyById(cx, target.handle(), id, &mut found) {
return false;
}
*bp = found;
true
}
#[allow(unsafe_code)]
unsafe extern "C" fn get(cx: *mut JSContext,
proxy: HandleObject,
receiver: HandleValue,
id: HandleId,
vp: MutableHandleValue)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if let Some(window) = window {
window.to_jsval(cx, vp);
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp)
}
#[allow(unsafe_code)]
unsafe extern "C" fn set(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
v: HandleValue,
receiver: HandleValue,
res: *mut ObjectOpResult)
-> bool {
if get_array_index_from_id(cx, id).is_some() {
// Reject (which means throw if and only if strict) the set.
(*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_ForwardSetPropertyTo(cx,
target.handle(),
id,
v,
receiver,
res)
}
#[allow(unsafe_code)]
unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext,
_: HandleObject,
is_ordinary: *mut bool,
_: MutableHandleObject)
-> bool {
// Window's [[GetPrototypeOf]] trap isn't the ordinary definition:
//
// https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof
//
// We nonetheless can implement it with a static [[Prototype]], because
// wrapper-class handlers (particularly, XOW in FilteringWrapper.cpp) supply
// all non-ordinary behavior.
//
// But from a spec point of view, it's the exact same object in both cases --
// only the observer's changed. So this getPrototypeIfOrdinary trap on the
// non-wrapper object *must* report non-ordinary, even if static [[Prototype]]
// usually means ordinary.
*is_ordinary = false;
return true;
}
static PROXY_HANDLER: ProxyTraps = ProxyTraps {
enter: None,
getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor),
defineProperty: Some(defineProperty),
ownPropertyKeys: None,
delete_: None,
enumerate: None,
getPrototypeIfOrdinary: Some(get_prototype_if_ordinary),
preventExtensions: None,
isExtensible: None,
has: Some(has),
get: Some(get),
set: Some(set),
call: None,
construct: None,
getPropertyDescriptor: Some(get_property_descriptor),
hasOwn: None,
getOwnEnumerablePropertyKeys: None,
nativeCall: None,
hasInstance: None,
objectClassIs: None,
className: None,
fun_toString: None,
boxedValue_unbox: None,
defaultValue: None,
trace: Some(trace),
finalize: Some(finalize),
objectMoved: None,
isCallable: None,
isConstructor: None,
};
#[allow(unsafe_code)]
unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) {
let this = GetProxyExtra(obj, 0).to_private() as *mut BrowsingContext;
assert!(!this.is_null());
let _ = Box::from_raw(this);
debug!("BrowsingContext finalize: {:p}", this);
}
#[allow(unsafe_code)]
unsafe extern fn trace(trc: *mut JSTracer, obj: *mut JSObject) {
let this = GetProxyExtra(obj, 0).to_private() as *const BrowsingContext;
if this.is_null() {
// GC during obj creation
return;
}
(*this).trace(trc);
}
#[allow(unsafe_code)]
pub fn new_window_proxy_handler() -> WindowProxyHandler {
unsafe {
WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER))
}
}
| {
let mut history = self.history.borrow_mut();
// Clear all session history entries after the active index
history.drain((self.active_index.get() + 1)..);
history.push(SessionHistoryEntry::new(document, document.url().clone(), document.Title()));
self.active_index.set(self.active_index.get() + 1);
assert_eq!(self.active_index.get(), history.len() - 1);
} | identifier_body |
browsingcontext.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods;
use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use dom::bindings::js::{JS, Root, RootedReference}; | use dom::bindings::utils::WindowProxyHandler;
use dom::bindings::utils::get_array_index_from_id;
use dom::document::Document;
use dom::element::Element;
use dom::window::Window;
use js::JSCLASS_IS_GLOBAL;
use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy};
use js::glue::{GetProxyPrivate, SetProxyExtra, GetProxyExtra};
use js::jsapi::{Handle, HandleId, HandleObject, HandleValue};
use js::jsapi::{JSAutoCompartment, JSContext, JSErrNum, JSFreeOp, JSObject};
use js::jsapi::{JSPROP_READONLY, JSTracer, JS_DefinePropertyById};
use js::jsapi::{JS_ForwardGetPropertyTo, JS_ForwardSetPropertyTo, JS_GetClass};
use js::jsapi::{JS_GetOwnPropertyDescriptorById, JS_HasPropertyById};
use js::jsapi::{MutableHandle, MutableHandleObject, MutableHandleValue};
use js::jsapi::{ObjectOpResult, PropertyDescriptor};
use js::jsval::{UndefinedValue, PrivateValue};
use msg::constellation_msg::{PipelineId, SubpageId};
use std::cell::Cell;
use url::Url;
#[dom_struct]
pub struct BrowsingContext {
reflector: Reflector,
/// Pipeline id associated with this context.
id: PipelineId,
/// Indicates if reflow is required when reloading.
needs_reflow: Cell<bool>,
/// Stores this context's session history
history: DOMRefCell<Vec<SessionHistoryEntry>>,
/// The index of the active session history entry
active_index: Cell<usize>,
/// Stores the child browsing contexts (ex. iframe browsing context)
children: DOMRefCell<Vec<JS<BrowsingContext>>>,
frame_element: Option<JS<Element>>,
}
impl BrowsingContext {
pub fn new_inherited(frame_element: Option<&Element>, id: PipelineId) -> BrowsingContext {
BrowsingContext {
reflector: Reflector::new(),
id: id,
needs_reflow: Cell::new(true),
history: DOMRefCell::new(vec![]),
active_index: Cell::new(0),
children: DOMRefCell::new(vec![]),
frame_element: frame_element.map(JS::from_ref),
}
}
#[allow(unsafe_code)]
pub fn new(window: &Window, frame_element: Option<&Element>, id: PipelineId) -> Root<BrowsingContext> {
unsafe {
let WindowProxyHandler(handler) = window.windowproxy_handler();
assert!(!handler.is_null());
let cx = window.get_cx();
let parent = window.reflector().get_jsobject();
assert!(!parent.get().is_null());
assert!(((*JS_GetClass(parent.get())).flags & JSCLASS_IS_GLOBAL)!= 0);
let _ac = JSAutoCompartment::new(cx, parent.get());
rooted!(in(cx) let window_proxy = NewWindowProxy(cx, parent, handler));
assert!(!window_proxy.is_null());
let object = box BrowsingContext::new_inherited(frame_element, id);
let raw = Box::into_raw(object);
SetProxyExtra(window_proxy.get(), 0, &PrivateValue(raw as *const _));
(*raw).init_reflector(window_proxy.get());
Root::from_ref(&*raw)
}
}
pub fn init(&self, document: &Document) {
assert!(self.history.borrow().is_empty());
assert_eq!(self.active_index.get(), 0);
self.history.borrow_mut().push(SessionHistoryEntry::new(document, document.url().clone(), document.Title()));
}
pub fn push_history(&self, document: &Document) {
let mut history = self.history.borrow_mut();
// Clear all session history entries after the active index
history.drain((self.active_index.get() + 1)..);
history.push(SessionHistoryEntry::new(document, document.url().clone(), document.Title()));
self.active_index.set(self.active_index.get() + 1);
assert_eq!(self.active_index.get(), history.len() - 1);
}
pub fn active_document(&self) -> Root<Document> {
Root::from_ref(&self.history.borrow()[self.active_index.get()].document)
}
pub fn maybe_active_document(&self) -> Option<Root<Document>> {
self.history.borrow().get(self.active_index.get()).map(|entry| {
Root::from_ref(&*entry.document)
})
}
pub fn active_window(&self) -> Root<Window> {
Root::from_ref(self.active_document().window())
}
pub fn frame_element(&self) -> Option<&Element> {
self.frame_element.r()
}
pub fn window_proxy(&self) -> *mut JSObject {
let window_proxy = self.reflector.get_jsobject();
assert!(!window_proxy.get().is_null());
window_proxy.get()
}
pub fn remove(&self, id: PipelineId) -> Option<Root<BrowsingContext>> {
let remove_idx = self.children
.borrow()
.iter()
.position(|context| context.id == id);
match remove_idx {
Some(idx) => Some(Root::from_ref(&*self.children.borrow_mut().remove(idx))),
None => {
self.children
.borrow_mut()
.iter_mut()
.filter_map(|context| context.remove(id))
.next()
}
}
}
pub fn set_reflow_status(&self, status: bool) -> bool {
let old = self.needs_reflow.get();
self.needs_reflow.set(status);
old
}
pub fn pipeline(&self) -> PipelineId {
self.id
}
pub fn push_child_context(&self, context: &BrowsingContext) {
self.children.borrow_mut().push(JS::from_ref(&context));
}
pub fn find_child_by_subpage(&self, subpage_id: SubpageId) -> Option<Root<Window>> {
self.children.borrow().iter().find(|context| {
let window = context.active_window();
window.subpage() == Some(subpage_id)
}).map(|context| context.active_window())
}
pub fn clear_session_history(&self) {
self.active_index.set(0);
self.history.borrow_mut().clear();
}
pub fn iter(&self) -> ContextIterator {
ContextIterator {
stack: vec!(Root::from_ref(self)),
}
}
pub fn find(&self, id: PipelineId) -> Option<Root<BrowsingContext>> {
if self.id == id {
return Some(Root::from_ref(self));
}
self.children.borrow()
.iter()
.filter_map(|c| c.find(id))
.next()
}
}
pub struct ContextIterator {
stack: Vec<Root<BrowsingContext>>,
}
impl Iterator for ContextIterator {
type Item = Root<BrowsingContext>;
fn next(&mut self) -> Option<Root<BrowsingContext>> {
let popped = self.stack.pop();
if let Some(ref context) = popped {
self.stack.extend(context.children.borrow()
.iter()
.map(|c| Root::from_ref(&**c)));
}
popped
}
}
// This isn't a DOM struct, just a convenience struct
// without a reflector, so we don't mark this as #[dom_struct]
#[must_root]
#[privatize]
#[derive(JSTraceable, HeapSizeOf)]
pub struct SessionHistoryEntry {
document: JS<Document>,
url: Url,
title: DOMString,
}
impl SessionHistoryEntry {
fn new(document: &Document, url: Url, title: DOMString) -> SessionHistoryEntry {
SessionHistoryEntry {
document: JS::from_ref(document),
url: url,
title: title,
}
}
}
#[allow(unsafe_code)]
unsafe fn GetSubframeWindow(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId)
-> Option<Root<Window>> {
let index = get_array_index_from_id(cx, id);
if let Some(index) = index {
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
let win = root_from_handleobject::<Window>(target.handle()).unwrap();
let mut found = false;
return win.IndexedGetter(index, &mut found);
}
None
}
#[allow(unsafe_code)]
unsafe extern "C" fn getOwnPropertyDescriptor(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
mut desc: MutableHandle<PropertyDescriptor>)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if let Some(window) = window {
rooted!(in(cx) let mut val = UndefinedValue());
window.to_jsval(cx, val.handle_mut());
desc.value = val.get();
fill_property_descriptor(&mut desc, proxy.get(), JSPROP_READONLY);
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(proxy.get()).to_object());
if!JS_GetOwnPropertyDescriptorById(cx, target.handle(), id, desc) {
return false;
}
assert!(desc.obj.is_null() || desc.obj == target.get());
if desc.obj == target.get() {
// FIXME(#11868) Should assign to desc.obj, desc.get() is a copy.
desc.get().obj = proxy.get();
}
true
}
#[allow(unsafe_code)]
unsafe extern "C" fn defineProperty(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
desc: Handle<PropertyDescriptor>,
res: *mut ObjectOpResult)
-> bool {
if get_array_index_from_id(cx, id).is_some() {
// Spec says to Reject whether this is a supported index or not,
// since we have no indexed setter or indexed creator. That means
// throwing in strict mode (FIXME: Bug 828137), doing nothing in
// non-strict mode.
(*res).code_ = JSErrNum::JSMSG_CANT_DEFINE_WINDOW_ELEMENT as ::libc::uintptr_t;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_DefinePropertyById(cx, target.handle(), id, desc, res)
}
#[allow(unsafe_code)]
unsafe extern "C" fn has(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
bp: *mut bool)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if window.is_some() {
*bp = true;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
let mut found = false;
if!JS_HasPropertyById(cx, target.handle(), id, &mut found) {
return false;
}
*bp = found;
true
}
#[allow(unsafe_code)]
unsafe extern "C" fn get(cx: *mut JSContext,
proxy: HandleObject,
receiver: HandleValue,
id: HandleId,
vp: MutableHandleValue)
-> bool {
let window = GetSubframeWindow(cx, proxy, id);
if let Some(window) = window {
window.to_jsval(cx, vp);
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_ForwardGetPropertyTo(cx, target.handle(), id, receiver, vp)
}
#[allow(unsafe_code)]
unsafe extern "C" fn set(cx: *mut JSContext,
proxy: HandleObject,
id: HandleId,
v: HandleValue,
receiver: HandleValue,
res: *mut ObjectOpResult)
-> bool {
if get_array_index_from_id(cx, id).is_some() {
// Reject (which means throw if and only if strict) the set.
(*res).code_ = JSErrNum::JSMSG_READ_ONLY as ::libc::uintptr_t;
return true;
}
rooted!(in(cx) let target = GetProxyPrivate(*proxy.ptr).to_object());
JS_ForwardSetPropertyTo(cx,
target.handle(),
id,
v,
receiver,
res)
}
#[allow(unsafe_code)]
unsafe extern "C" fn get_prototype_if_ordinary(_: *mut JSContext,
_: HandleObject,
is_ordinary: *mut bool,
_: MutableHandleObject)
-> bool {
// Window's [[GetPrototypeOf]] trap isn't the ordinary definition:
//
// https://html.spec.whatwg.org/multipage/#windowproxy-getprototypeof
//
// We nonetheless can implement it with a static [[Prototype]], because
// wrapper-class handlers (particularly, XOW in FilteringWrapper.cpp) supply
// all non-ordinary behavior.
//
// But from a spec point of view, it's the exact same object in both cases --
// only the observer's changed. So this getPrototypeIfOrdinary trap on the
// non-wrapper object *must* report non-ordinary, even if static [[Prototype]]
// usually means ordinary.
*is_ordinary = false;
return true;
}
static PROXY_HANDLER: ProxyTraps = ProxyTraps {
enter: None,
getOwnPropertyDescriptor: Some(getOwnPropertyDescriptor),
defineProperty: Some(defineProperty),
ownPropertyKeys: None,
delete_: None,
enumerate: None,
getPrototypeIfOrdinary: Some(get_prototype_if_ordinary),
preventExtensions: None,
isExtensible: None,
has: Some(has),
get: Some(get),
set: Some(set),
call: None,
construct: None,
getPropertyDescriptor: Some(get_property_descriptor),
hasOwn: None,
getOwnEnumerablePropertyKeys: None,
nativeCall: None,
hasInstance: None,
objectClassIs: None,
className: None,
fun_toString: None,
boxedValue_unbox: None,
defaultValue: None,
trace: Some(trace),
finalize: Some(finalize),
objectMoved: None,
isCallable: None,
isConstructor: None,
};
#[allow(unsafe_code)]
unsafe extern fn finalize(_fop: *mut JSFreeOp, obj: *mut JSObject) {
let this = GetProxyExtra(obj, 0).to_private() as *mut BrowsingContext;
assert!(!this.is_null());
let _ = Box::from_raw(this);
debug!("BrowsingContext finalize: {:p}", this);
}
#[allow(unsafe_code)]
unsafe extern fn trace(trc: *mut JSTracer, obj: *mut JSObject) {
let this = GetProxyExtra(obj, 0).to_private() as *const BrowsingContext;
if this.is_null() {
// GC during obj creation
return;
}
(*this).trace(trc);
}
#[allow(unsafe_code)]
pub fn new_window_proxy_handler() -> WindowProxyHandler {
unsafe {
WindowProxyHandler(CreateWrapperProxyHandler(&PROXY_HANDLER))
}
} | use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor};
use dom::bindings::reflector::{Reflectable, MutReflectable, Reflector};
use dom::bindings::str::DOMString;
use dom::bindings::trace::JSTraceable; | random_line_split |
delete_machine.rs | use std::os::unix::fs::PermissionsExt;
use pidfile_rs::{
Pidfile,
PidfileError,
};
use eyre::{
eyre,
Result,
// Context as _,
};
use crate::machine::Machine;
use crate::config::MachineConfig;
#[xactor::message(result = "Result<()>")]
pub struct DeleteMachine;
#[async_trait::async_trait]
impl xactor::Handler<DeleteMachine> for Machine {
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: DeleteMachine) -> Result<()> | attempts += 1;
if attempts >= 10 {
break
}
// Attempt to lock the pidfile
let pid_file = MachineConfig::pid_file_path(&self.id);
let lock_result = Pidfile::new(
&pid_file,
std::fs::Permissions::from_mode(0o600),
)
// Drop the pidfile lock immediately to prevent blocking the driver from starting
.map(|_| ());
match lock_result {
Err(PidfileError::AlreadyRunning { pid: Some(pid) }) => {
// The driver process is running (as expected) so lets kill it.
let pid = nix::unistd::Pid::from_raw(pid);
let kill_signal = if attempted_sig_int {
info!("Force killing driver for machine ID: {}", self.id);
nix::sys::signal::Signal::SIGKILL
} else {
info!("Resetting driver for machine ID: {}", self.id);
nix::sys::signal::Signal::SIGINT
};
match nix::sys::signal::kill(pid, kill_signal) {
Ok(()) => {
attempted_sig_int = true;
},
Err(err) => {
warn!("Error killing driver: {:?}", err);
}
};
}
Ok(_) => {
// The drive process was killed successfully.
ctx.stop(Some(eyre!("Machine ID: {} deleted", self.id)));
return Ok(());
}
_ => {
// Other weirdness - let's try again in a little bit
}
};
async_std::task::sleep(std::time::Duration::from_millis(10)).await;
}
ctx.stop(Some(eyre!("Unable to kill pid for deleted machine ID: {}", self.id)));
Ok(())
}
}
| {
// Delete the machine foreign keys in the database
sqlx::query!(
r#"
DELETE FROM machine_print_queues
WHERE machine_id = $1
"#,
self.id,
)
.fetch_optional(&self.db)
.await?;
// Delete the machine config
let config_path = crate::paths::etc_common().join(format!("machine-{}.toml", self.id));
let _ = std::fs::remove_file(config_path);
let mut attempted_sig_int = false;
let mut attempts = 0;
loop { | identifier_body |
delete_machine.rs | use std::os::unix::fs::PermissionsExt;
use pidfile_rs::{
Pidfile,
PidfileError,
};
use eyre::{
eyre,
Result,
// Context as _,
};
use crate::machine::Machine;
use crate::config::MachineConfig;
#[xactor::message(result = "Result<()>")]
pub struct DeleteMachine;
#[async_trait::async_trait]
impl xactor::Handler<DeleteMachine> for Machine {
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: DeleteMachine) -> Result<()> {
// Delete the machine foreign keys in the database
sqlx::query!(
r#"
DELETE FROM machine_print_queues | )
.fetch_optional(&self.db)
.await?;
// Delete the machine config
let config_path = crate::paths::etc_common().join(format!("machine-{}.toml", self.id));
let _ = std::fs::remove_file(config_path);
let mut attempted_sig_int = false;
let mut attempts = 0;
loop {
attempts += 1;
if attempts >= 10 {
break
}
// Attempt to lock the pidfile
let pid_file = MachineConfig::pid_file_path(&self.id);
let lock_result = Pidfile::new(
&pid_file,
std::fs::Permissions::from_mode(0o600),
)
// Drop the pidfile lock immediately to prevent blocking the driver from starting
.map(|_| ());
match lock_result {
Err(PidfileError::AlreadyRunning { pid: Some(pid) }) => {
// The driver process is running (as expected) so lets kill it.
let pid = nix::unistd::Pid::from_raw(pid);
let kill_signal = if attempted_sig_int {
info!("Force killing driver for machine ID: {}", self.id);
nix::sys::signal::Signal::SIGKILL
} else {
info!("Resetting driver for machine ID: {}", self.id);
nix::sys::signal::Signal::SIGINT
};
match nix::sys::signal::kill(pid, kill_signal) {
Ok(()) => {
attempted_sig_int = true;
},
Err(err) => {
warn!("Error killing driver: {:?}", err);
}
};
}
Ok(_) => {
// The drive process was killed successfully.
ctx.stop(Some(eyre!("Machine ID: {} deleted", self.id)));
return Ok(());
}
_ => {
// Other weirdness - let's try again in a little bit
}
};
async_std::task::sleep(std::time::Duration::from_millis(10)).await;
}
ctx.stop(Some(eyre!("Unable to kill pid for deleted machine ID: {}", self.id)));
Ok(())
}
} | WHERE machine_id = $1
"#,
self.id, | random_line_split |
delete_machine.rs | use std::os::unix::fs::PermissionsExt;
use pidfile_rs::{
Pidfile,
PidfileError,
};
use eyre::{
eyre,
Result,
// Context as _,
};
use crate::machine::Machine;
use crate::config::MachineConfig;
#[xactor::message(result = "Result<()>")]
pub struct DeleteMachine;
#[async_trait::async_trait]
impl xactor::Handler<DeleteMachine> for Machine {
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: DeleteMachine) -> Result<()> {
// Delete the machine foreign keys in the database
sqlx::query!(
r#"
DELETE FROM machine_print_queues
WHERE machine_id = $1
"#,
self.id,
)
.fetch_optional(&self.db)
.await?;
// Delete the machine config
let config_path = crate::paths::etc_common().join(format!("machine-{}.toml", self.id));
let _ = std::fs::remove_file(config_path);
let mut attempted_sig_int = false;
let mut attempts = 0;
loop {
attempts += 1;
if attempts >= 10 {
break
}
// Attempt to lock the pidfile
let pid_file = MachineConfig::pid_file_path(&self.id);
let lock_result = Pidfile::new(
&pid_file,
std::fs::Permissions::from_mode(0o600),
)
// Drop the pidfile lock immediately to prevent blocking the driver from starting
.map(|_| ());
match lock_result {
Err(PidfileError::AlreadyRunning { pid: Some(pid) }) => {
// The driver process is running (as expected) so lets kill it.
let pid = nix::unistd::Pid::from_raw(pid);
let kill_signal = if attempted_sig_int {
info!("Force killing driver for machine ID: {}", self.id);
nix::sys::signal::Signal::SIGKILL
} else {
info!("Resetting driver for machine ID: {}", self.id);
nix::sys::signal::Signal::SIGINT
};
match nix::sys::signal::kill(pid, kill_signal) {
Ok(()) => {
attempted_sig_int = true;
},
Err(err) => {
warn!("Error killing driver: {:?}", err);
}
};
}
Ok(_) => {
// The drive process was killed successfully.
ctx.stop(Some(eyre!("Machine ID: {} deleted", self.id)));
return Ok(());
}
_ => |
};
async_std::task::sleep(std::time::Duration::from_millis(10)).await;
}
ctx.stop(Some(eyre!("Unable to kill pid for deleted machine ID: {}", self.id)));
Ok(())
}
}
| {
// Other weirdness - let's try again in a little bit
} | conditional_block |
delete_machine.rs | use std::os::unix::fs::PermissionsExt;
use pidfile_rs::{
Pidfile,
PidfileError,
};
use eyre::{
eyre,
Result,
// Context as _,
};
use crate::machine::Machine;
use crate::config::MachineConfig;
#[xactor::message(result = "Result<()>")]
pub struct | ;
#[async_trait::async_trait]
impl xactor::Handler<DeleteMachine> for Machine {
async fn handle(&mut self, ctx: &mut xactor::Context<Self>, _msg: DeleteMachine) -> Result<()> {
// Delete the machine foreign keys in the database
sqlx::query!(
r#"
DELETE FROM machine_print_queues
WHERE machine_id = $1
"#,
self.id,
)
.fetch_optional(&self.db)
.await?;
// Delete the machine config
let config_path = crate::paths::etc_common().join(format!("machine-{}.toml", self.id));
let _ = std::fs::remove_file(config_path);
let mut attempted_sig_int = false;
let mut attempts = 0;
loop {
attempts += 1;
if attempts >= 10 {
break
}
// Attempt to lock the pidfile
let pid_file = MachineConfig::pid_file_path(&self.id);
let lock_result = Pidfile::new(
&pid_file,
std::fs::Permissions::from_mode(0o600),
)
// Drop the pidfile lock immediately to prevent blocking the driver from starting
.map(|_| ());
match lock_result {
Err(PidfileError::AlreadyRunning { pid: Some(pid) }) => {
// The driver process is running (as expected) so lets kill it.
let pid = nix::unistd::Pid::from_raw(pid);
let kill_signal = if attempted_sig_int {
info!("Force killing driver for machine ID: {}", self.id);
nix::sys::signal::Signal::SIGKILL
} else {
info!("Resetting driver for machine ID: {}", self.id);
nix::sys::signal::Signal::SIGINT
};
match nix::sys::signal::kill(pid, kill_signal) {
Ok(()) => {
attempted_sig_int = true;
},
Err(err) => {
warn!("Error killing driver: {:?}", err);
}
};
}
Ok(_) => {
// The drive process was killed successfully.
ctx.stop(Some(eyre!("Machine ID: {} deleted", self.id)));
return Ok(());
}
_ => {
// Other weirdness - let's try again in a little bit
}
};
async_std::task::sleep(std::time::Duration::from_millis(10)).await;
}
ctx.stop(Some(eyre!("Unable to kill pid for deleted machine ID: {}", self.id)));
Ok(())
}
}
| DeleteMachine | identifier_name |
no_0350_intersection_of_two_arrays_ii.rs | struct Solution;
impl Solution {
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> | 意理解错了
// 这个解法求的是连续出现的,题目是可以不连续的,而且顺序也无关。
pub fn intersect_failed(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// 练习下动态规划
let (m, n) = (nums1.len(), nums2.len());
let mut dp = vec![vec![0; n + 1]; m + 1];
let mut max_len = 0;
let mut pos = (0, 0);
for i in (0..m).rev() {
for j in (0..n).rev() {
if nums1[i] == nums2[j] {
dp[i][j] = dp[i + 1][j + 1] + 1;
} else {
dp[i][j] = 0;
}
if max_len <= dp[i][j] {
max_len = dp[i][j];
pos = (i, j);
}
}
}
nums1
.get(pos.0..(pos.0 + max_len))
.map(|x| x.iter().map(|x| *x).collect())
.unwrap_or(Vec::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_intersect1() {
let mut res = Solution::intersect(vec![1, 2, 2, 1], vec![2, 2]);
res.sort();
assert_eq!(res, vec![2, 2]);
}
#[test]
fn test_intersect2() {
let mut res = Solution::intersect(vec![4, 9, 5], vec![9, 4, 9, 8, 4]);
res.sort();
assert_eq!(res, vec![4, 9]);
}
#[test]
fn test_intersect3() {
let mut res = Solution::intersect(vec![1, 2], vec![2, 1]);
res.sort();
assert_eq!(res, vec![1, 2]);
}
}
| {
// key => num, value => 出现的次数
let mut map = std::collections::HashMap::with_capacity(nums1.len());
for num in nums1 {
let v = map.entry(num).or_insert(0);
*v += 1;
}
let mut ans = Vec::new();
for num in nums2 {
if let Some(count) = map.get_mut(&num) {
if *count > 0 {
*count -= 1;
ans.push(num);
}
}
}
ans
}
// 题 | identifier_body |
no_0350_intersection_of_two_arrays_ii.rs | struct Solution;
impl Solution {
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// key => num, value => 出现的次数
let mut map = std::collections::HashMap::with_capacity(nums1.len());
for num in nums1 {
let v = map.entry(num).or_insert(0);
*v += 1;
}
let mut ans = Vec::new();
for num in nums2 {
if let Some(count) = map.get_mut(&num) {
if *count > 0 {
*count -= 1;
ans.push(num);
}
}
}
ans
}
// 题意理解错了
// 这个解法求的是连续出现的,题目是可以不连续的,而且顺序也无关。
pub fn intersect_failed(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// 练习下动态规划
let (m, n) = (nums1.len(), nums2.len());
let mut dp = vec![vec![0; n + 1]; m + 1];
let mut max_len = 0;
let mut pos = (0, 0); | if nums1[i] == nums2[j] {
dp[i][j] = dp[i + 1][j + 1] + 1;
} else {
dp[i][j] = 0;
}
if max_len <= dp[i][j] {
max_len = dp[i][j];
pos = (i, j);
}
}
}
nums1
.get(pos.0..(pos.0 + max_len))
.map(|x| x.iter().map(|x| *x).collect())
.unwrap_or(Vec::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_intersect1() {
let mut res = Solution::intersect(vec![1, 2, 2, 1], vec![2, 2]);
res.sort();
assert_eq!(res, vec![2, 2]);
}
#[test]
fn test_intersect2() {
let mut res = Solution::intersect(vec![4, 9, 5], vec![9, 4, 9, 8, 4]);
res.sort();
assert_eq!(res, vec![4, 9]);
}
#[test]
fn test_intersect3() {
let mut res = Solution::intersect(vec![1, 2], vec![2, 1]);
res.sort();
assert_eq!(res, vec![1, 2]);
}
} |
for i in (0..m).rev() {
for j in (0..n).rev() { | random_line_split |
no_0350_intersection_of_two_arrays_ii.rs | struct Solution;
impl Solution {
pub fn | (nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// key => num, value => 出现的次数
let mut map = std::collections::HashMap::with_capacity(nums1.len());
for num in nums1 {
let v = map.entry(num).or_insert(0);
*v += 1;
}
let mut ans = Vec::new();
for num in nums2 {
if let Some(count) = map.get_mut(&num) {
if *count > 0 {
*count -= 1;
ans.push(num);
}
}
}
ans
}
// 题意理解错了
// 这个解法求的是连续出现的,题目是可以不连续的,而且顺序也无关。
pub fn intersect_failed(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// 练习下动态规划
let (m, n) = (nums1.len(), nums2.len());
let mut dp = vec![vec![0; n + 1]; m + 1];
let mut max_len = 0;
let mut pos = (0, 0);
for i in (0..m).rev() {
for j in (0..n).rev() {
if nums1[i] == nums2[j] {
dp[i][j] = dp[i + 1][j + 1] + 1;
} else {
dp[i][j] = 0;
}
if max_len <= dp[i][j] {
max_len = dp[i][j];
pos = (i, j);
}
}
}
nums1
.get(pos.0..(pos.0 + max_len))
.map(|x| x.iter().map(|x| *x).collect())
.unwrap_or(Vec::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_intersect1() {
let mut res = Solution::intersect(vec![1, 2, 2, 1], vec![2, 2]);
res.sort();
assert_eq!(res, vec![2, 2]);
}
#[test]
fn test_intersect2() {
let mut res = Solution::intersect(vec![4, 9, 5], vec![9, 4, 9, 8, 4]);
res.sort();
assert_eq!(res, vec![4, 9]);
}
#[test]
fn test_intersect3() {
let mut res = Solution::intersect(vec![1, 2], vec![2, 1]);
res.sort();
assert_eq!(res, vec![1, 2]);
}
}
| intersect | identifier_name |
no_0350_intersection_of_two_arrays_ii.rs | struct Solution;
impl Solution {
pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// key => num, value => 出现的次数
let mut map = std::collections::HashMap::with_capacity(nums1.len());
for num in nums1 {
let v = map.entry(num).or_insert(0);
*v += 1;
}
let mut ans = Vec::new();
for num in nums2 {
if let Some(count) = map.get_mut(&num) {
if *count > 0 {
*count -= 1;
ans.push(num);
}
}
}
ans
}
// 题意理解错了
// 这个解法求的是连续出现的,题目是可以不连续的,而且顺序也无关。
pub fn intersect_failed(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
// 练习下动态规划
let (m, n) = (nums1.len(), nums2.len());
let mut dp = vec![vec![0; n + 1]; m + 1];
let mut max_len = 0;
let mut pos = (0, 0);
for i in (0..m).rev() {
for j in (0..n).rev() {
if nums1[i] == nums2[j] {
dp[i][j] = dp[i + 1][j + 1] + 1;
} else {
dp[i][j] = 0;
}
if max_len <= dp[i][j] {
| pos = (i, j);
}
}
}
nums1
.get(pos.0..(pos.0 + max_len))
.map(|x| x.iter().map(|x| *x).collect())
.unwrap_or(Vec::new())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_intersect1() {
let mut res = Solution::intersect(vec![1, 2, 2, 1], vec![2, 2]);
res.sort();
assert_eq!(res, vec![2, 2]);
}
#[test]
fn test_intersect2() {
let mut res = Solution::intersect(vec![4, 9, 5], vec![9, 4, 9, 8, 4]);
res.sort();
assert_eq!(res, vec![4, 9]);
}
#[test]
fn test_intersect3() {
let mut res = Solution::intersect(vec![1, 2], vec![2, 1]);
res.sort();
assert_eq!(res, vec![1, 2]);
}
}
| max_len = dp[i][j];
| conditional_block |
config.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use serde::{Deserialize, Serialize};
use tikv_util::config::ReadableDuration;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
#[serde(rename_all = "kebab-case")]
pub struct Config {
pub max_batch_size: Option<usize>,
pub pool_size: usize,
pub reschedule_duration: ReadableDuration,
pub low_priority_pool_size: usize,
}
impl Config {
pub fn max_batch_size(&self) -> usize {
// `Config::validate` is not called for test so the `max_batch_size` is None.
self.max_batch_size.unwrap_or(256)
}
}
impl Default for Config {
fn | () -> Config {
Config {
max_batch_size: None,
pool_size: 2,
reschedule_duration: ReadableDuration::secs(5),
low_priority_pool_size: 1,
}
}
}
| default | identifier_name |
config.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use serde::{Deserialize, Serialize};
use tikv_util::config::ReadableDuration;
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
#[serde(rename_all = "kebab-case")]
pub struct Config {
pub max_batch_size: Option<usize>,
pub pool_size: usize,
pub reschedule_duration: ReadableDuration,
pub low_priority_pool_size: usize,
}
impl Config {
pub fn max_batch_size(&self) -> usize {
// `Config::validate` is not called for test so the `max_batch_size` is None.
self.max_batch_size.unwrap_or(256)
}
}
impl Default for Config {
fn default() -> Config {
Config {
max_batch_size: None,
pool_size: 2,
reschedule_duration: ReadableDuration::secs(5),
low_priority_pool_size: 1,
}
} | } | random_line_split | |
operator-overloading.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.
// xfail-fast
struct Point {
x: int,
y: int
}
impl ops::Add<Point,Point> for Point {
fn add(&self, other: &Point) -> Point {
Point {x: self.x + (*other).x, y: self.y + (*other).y}
}
}
impl ops::Sub<Point,Point> for Point {
fn sub(&self, other: &Point) -> Point {
Point {x: self.x - (*other).x, y: self.y - (*other).y}
}
}
impl ops::Neg<Point> for Point {
fn neg(&self) -> Point {
Point {x: -self.x, y: -self.y}
}
}
impl ops::Not<Point> for Point {
fn not(&self) -> Point |
}
impl ops::Index<bool,int> for Point {
fn index(&self, +x: &bool) -> int {
if *x { self.x } else { self.y }
}
}
impl cmp::Eq for Point {
fn eq(&self, other: &Point) -> bool {
(*self).x == (*other).x && (*self).y == (*other).y
}
fn ne(&self, other: &Point) -> bool {!(*self).eq(other) }
}
pub fn main() {
let mut p = Point {x: 10, y: 20};
p += Point {x: 101, y: 102};
p = p - Point {x: 100, y: 100};
assert!(p + Point {x: 5, y: 5} == Point {x: 16, y: 27});
assert!(-p == Point {x: -11, y: -22});
assert!(p[true] == 11);
assert!(p[false] == 22);
let q =!p;
assert!(q.x ==!(p.x));
assert!(q.y ==!(p.y));
// Issue #1733
let result: ~fn(int) = |_|();
result(p[true]);
}
| {
Point {x: !self.x, y: !self.y }
} | identifier_body |
operator-overloading.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.
// xfail-fast
struct Point {
x: int,
y: int
}
impl ops::Add<Point,Point> for Point {
fn add(&self, other: &Point) -> Point {
Point {x: self.x + (*other).x, y: self.y + (*other).y}
}
}
impl ops::Sub<Point,Point> for Point {
fn sub(&self, other: &Point) -> Point {
Point {x: self.x - (*other).x, y: self.y - (*other).y}
}
}
impl ops::Neg<Point> for Point {
fn neg(&self) -> Point {
Point {x: -self.x, y: -self.y}
}
}
impl ops::Not<Point> for Point {
fn not(&self) -> Point {
Point {x:!self.x, y:!self.y }
}
}
impl ops::Index<bool,int> for Point {
fn index(&self, +x: &bool) -> int {
if *x | else { self.y }
}
}
impl cmp::Eq for Point {
fn eq(&self, other: &Point) -> bool {
(*self).x == (*other).x && (*self).y == (*other).y
}
fn ne(&self, other: &Point) -> bool {!(*self).eq(other) }
}
pub fn main() {
let mut p = Point {x: 10, y: 20};
p += Point {x: 101, y: 102};
p = p - Point {x: 100, y: 100};
assert!(p + Point {x: 5, y: 5} == Point {x: 16, y: 27});
assert!(-p == Point {x: -11, y: -22});
assert!(p[true] == 11);
assert!(p[false] == 22);
let q =!p;
assert!(q.x ==!(p.x));
assert!(q.y ==!(p.y));
// Issue #1733
let result: ~fn(int) = |_|();
result(p[true]);
}
| { self.x } | conditional_block |
operator-overloading.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.
// xfail-fast
struct Point {
x: int,
y: int
}
impl ops::Add<Point,Point> for Point {
fn add(&self, other: &Point) -> Point {
Point {x: self.x + (*other).x, y: self.y + (*other).y}
}
}
impl ops::Sub<Point,Point> for Point {
fn sub(&self, other: &Point) -> Point {
Point {x: self.x - (*other).x, y: self.y - (*other).y}
}
}
impl ops::Neg<Point> for Point {
fn neg(&self) -> Point {
Point {x: -self.x, y: -self.y}
}
}
impl ops::Not<Point> for Point {
fn | (&self) -> Point {
Point {x:!self.x, y:!self.y }
}
}
impl ops::Index<bool,int> for Point {
fn index(&self, +x: &bool) -> int {
if *x { self.x } else { self.y }
}
}
impl cmp::Eq for Point {
fn eq(&self, other: &Point) -> bool {
(*self).x == (*other).x && (*self).y == (*other).y
}
fn ne(&self, other: &Point) -> bool {!(*self).eq(other) }
}
pub fn main() {
let mut p = Point {x: 10, y: 20};
p += Point {x: 101, y: 102};
p = p - Point {x: 100, y: 100};
assert!(p + Point {x: 5, y: 5} == Point {x: 16, y: 27});
assert!(-p == Point {x: -11, y: -22});
assert!(p[true] == 11);
assert!(p[false] == 22);
let q =!p;
assert!(q.x ==!(p.x));
assert!(q.y ==!(p.y));
// Issue #1733
let result: ~fn(int) = |_|();
result(p[true]);
}
| not | identifier_name |
operator-overloading.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.
// xfail-fast
struct Point {
x: int,
y: int
}
impl ops::Add<Point,Point> for Point {
fn add(&self, other: &Point) -> Point {
Point {x: self.x + (*other).x, y: self.y + (*other).y}
}
}
impl ops::Sub<Point,Point> for Point {
fn sub(&self, other: &Point) -> Point {
Point {x: self.x - (*other).x, y: self.y - (*other).y}
}
}
impl ops::Neg<Point> for Point {
fn neg(&self) -> Point {
Point {x: -self.x, y: -self.y}
}
}
impl ops::Not<Point> for Point {
fn not(&self) -> Point {
Point {x:!self.x, y:!self.y }
}
}
impl ops::Index<bool,int> for Point {
fn index(&self, +x: &bool) -> int {
if *x { self.x } else { self.y }
}
}
impl cmp::Eq for Point {
fn eq(&self, other: &Point) -> bool {
(*self).x == (*other).x && (*self).y == (*other).y
}
fn ne(&self, other: &Point) -> bool {!(*self).eq(other) }
}
pub fn main() {
let mut p = Point {x: 10, y: 20};
p += Point {x: 101, y: 102}; |
let q =!p;
assert!(q.x ==!(p.x));
assert!(q.y ==!(p.y));
// Issue #1733
let result: ~fn(int) = |_|();
result(p[true]);
} | p = p - Point {x: 100, y: 100};
assert!(p + Point {x: 5, y: 5} == Point {x: 16, y: 27});
assert!(-p == Point {x: -11, y: -22});
assert!(p[true] == 11);
assert!(p[false] == 22); | random_line_split |
tac_code.rs | use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result;
use super::{
function_attributes::FunctionAttribute,
types::Type,
node_info::{ DeclarationInfo, FunctionInfo },
};
use std::rc::Rc;
#[derive(Clone, Debug, PartialEq)]
pub enum Statement {
Assignment{ operator: Option<Operator>, destination: Option<Operand>, left_operand: Option<Operand>, right_operand: Option<Operand> },
Array{ id: u32, length: i32, size_in_bytes: u32 },
Call(Rc<String>, Vec<Operand>, Option<Operand>),
Label(u32),
Jump(u32),
JumpIfTrue(Operand, u32),
JumpIfFalse(Operand, u32),
Return(Option<Operand>),
Empty,
PhiFunction(Operand, Vec<Operand>)
}
// TODO replace tuples with structs for better readability
#[derive(Clone, Debug, PartialEq)]
pub enum Operand {
Variable(DeclarationInfo, u32),
AddressOf{ variable_info: DeclarationInfo, id: u32, },
ArrayIndex{ id: u32, index_operand: Box<Operand>, variable_info: DeclarationInfo, },
ArraySlice{ id: u32, start_operand: Box<Operand>, end_operand: Box<Operand>, variable_info: DeclarationInfo, },
SSAVariable(DeclarationInfo, u32, u32),
Long(i64),
Integer(i32),
Short(i16),
Byte(i8),
Float(f32),
Double(f64),
Boolean(bool),
// special operand to represent initialized, but unknown, value
// used for things like function parameters
Initialized(Type),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Operator {
Plus,
Minus,
Multiply,
Divide,
Modulo,
Less,
LessOrEq,
Equals,
NotEquals,
GreaterOrEq,
Greater,
ArithmeticShiftRight,
LogicalShiftRight,
LogicalShiftLeft,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
BitwiseNot,
Cast{ from: Type, to: Type},
}
#[derive(Clone, Debug)]
pub struct Function {
pub statements: Vec<Statement>,
pub function_info: FunctionInfo,
pub attributes: Vec<FunctionAttribute>,
}
impl Function {
pub fn new(function_info: FunctionInfo) -> Function {
Function {
statements: vec![],
function_info,
attributes: vec![],
}
}
pub fn print(&self) {
let mut counter = 0;
println!("Function '{}'\n", self.function_info.name);
for s in &self.statements {
println!(" {}: {}", counter, s);
counter += 1;
}
println!();
}
pub fn has_attribute(&self, attribute: FunctionAttribute) -> bool {
self.attributes.contains(&attribute)
}
}
impl Display for Statement {
fn fmt(&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Statement::Assignment{ref operator, ref destination, ref left_operand, ref right_operand} =>
format!("{}= {}{}{}",
opt_to_str(destination),
opt_to_str(left_operand),
opt_to_str(operator),
opt_to_str(right_operand)),
Statement::Array{ id: _, length, size_in_bytes} => format!("Init<Array[{}], {} bytes>", length, size_in_bytes),
Statement::Call(ref name, ref operands, ref dest) => {
let op_str = operands.iter()
.fold(
String::new(),
|acc, v| format!("{}, {}", acc, v))
.chars()
.skip(2) // get rid of the leading spaces
.collect::<String>();
let dest_str = if let Some(ref op) = *dest {
format!("{} = ", op)
} else {
String::new()
};
format!("{}{}({})",
dest_str,
name,
op_str)
},
Statement::Return(ref v0) =>
format!("return {}", opt_to_str(v0)),
Statement::Label(id) => format!("Label {}", id),
Statement::Jump(id) => format!("Jump {}", id),
Statement::JumpIfTrue(ref op, id) =>
format!("Jump {} if {}", id, op),
Statement::JumpIfFalse(ref op, id) =>
format!("Jump {} if not {}", id, op),
Statement::PhiFunction(ref dest, ref operands) => {
let mut op_str = operands.
iter().
fold(
String::new(),
|acc, ref t| format!("'{}', {}", t, acc));
op_str.pop(); op_str.pop();
format!("{} = phi<{}>", dest, op_str)
},
Statement::Empty => "<Empty statement>".to_owned()
})
}
}
impl Display for Operand {
fn fmt(&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Operand::ArrayIndex { id, ref index_operand, ref variable_info} => {
format!("{}_{}[{}]", variable_info.name, id, index_operand)
},
Operand::ArraySlice{ id, ref start_operand, ref end_operand, ref variable_info} => {
format!("{}_{}[{}:{}]", variable_info.name, id, start_operand, end_operand)
},
Operand::Variable(ref info, id) => format!("{}_{}", info.name, id),
Operand::AddressOf { ref variable_info, ref id } => format!("&{}_{}", variable_info.name, id),
Operand::SSAVariable(ref info, id, ssa_id) =>
format!("{}_{}:{}", info.name, id, ssa_id),
Operand::Long(v) => format!("{}L", v),
Operand::Integer(v) => format!("{}I", v),
Operand::Short(v) => format!("{}S", v),
Operand::Byte(v) => format!("{}B", v),
Operand::Float(v) => format!("{}F", v),
Operand::Double(v) => format!("{}D", v),
Operand::Boolean(v) => v.to_string(),
Operand::Initialized(ref t) => format!(
"<initialized {} value>", t),
})
}
}
impl Display for Operator {
fn | (&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Operator::Plus => "+".to_string(),
Operator::Minus => "-".to_string(),
Operator::Multiply => "*".to_string(),
Operator::Divide => "/".to_string(),
Operator::Modulo=> "%".to_string(),
Operator::Less => "<".to_string(),
Operator::LessOrEq => "<=".to_string(),
Operator::Equals => "==".to_string(),
Operator::NotEquals => "!=".to_string(),
Operator::GreaterOrEq => ">=".to_string(),
Operator::Greater => ">".to_string(),
Operator::ArithmeticShiftRight => ">>".to_string(),
Operator::LogicalShiftRight => ">>>".to_string(),
Operator::LogicalShiftLeft => "<<".to_string(),
Operator::BitwiseAnd => "&".to_string(),
Operator::BitwiseOr => "|".to_string(),
Operator::BitwiseXor => "^".to_string(),
Operator::BitwiseNot => "~".to_string(),
Operator::Cast{ref from, ref to}=> format!("Cast({} to {})", from, to),
})
}
}
fn opt_to_str<T: Display>(op: &Option<T>) -> String {
match *op {
Some(ref val) => format!("{} ", val),
None => "".to_owned(),
}
} | fmt | identifier_name |
tac_code.rs | use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result;
use super::{
function_attributes::FunctionAttribute,
types::Type,
node_info::{ DeclarationInfo, FunctionInfo },
};
use std::rc::Rc;
#[derive(Clone, Debug, PartialEq)]
pub enum Statement {
Assignment{ operator: Option<Operator>, destination: Option<Operand>, left_operand: Option<Operand>, right_operand: Option<Operand> },
Array{ id: u32, length: i32, size_in_bytes: u32 },
Call(Rc<String>, Vec<Operand>, Option<Operand>),
Label(u32),
Jump(u32),
JumpIfTrue(Operand, u32),
JumpIfFalse(Operand, u32),
Return(Option<Operand>),
Empty,
PhiFunction(Operand, Vec<Operand>)
}
// TODO replace tuples with structs for better readability
#[derive(Clone, Debug, PartialEq)]
pub enum Operand {
Variable(DeclarationInfo, u32),
AddressOf{ variable_info: DeclarationInfo, id: u32, },
ArrayIndex{ id: u32, index_operand: Box<Operand>, variable_info: DeclarationInfo, },
ArraySlice{ id: u32, start_operand: Box<Operand>, end_operand: Box<Operand>, variable_info: DeclarationInfo, },
SSAVariable(DeclarationInfo, u32, u32),
Long(i64),
Integer(i32),
Short(i16),
Byte(i8),
Float(f32),
Double(f64),
Boolean(bool),
// special operand to represent initialized, but unknown, value
// used for things like function parameters
Initialized(Type),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Operator {
Plus,
Minus,
Multiply,
Divide,
Modulo,
Less,
LessOrEq,
Equals,
NotEquals,
GreaterOrEq,
Greater,
ArithmeticShiftRight,
LogicalShiftRight,
LogicalShiftLeft,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
BitwiseNot,
Cast{ from: Type, to: Type},
}
#[derive(Clone, Debug)]
pub struct Function {
pub statements: Vec<Statement>,
pub function_info: FunctionInfo,
pub attributes: Vec<FunctionAttribute>,
}
impl Function {
pub fn new(function_info: FunctionInfo) -> Function {
Function {
statements: vec![],
function_info,
attributes: vec![],
}
}
pub fn print(&self) {
let mut counter = 0;
println!("Function '{}'\n", self.function_info.name);
for s in &self.statements {
println!(" {}: {}", counter, s);
counter += 1;
}
println!();
}
pub fn has_attribute(&self, attribute: FunctionAttribute) -> bool {
self.attributes.contains(&attribute)
}
| fn fmt(&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Statement::Assignment{ref operator, ref destination, ref left_operand, ref right_operand} =>
format!("{}= {}{}{}",
opt_to_str(destination),
opt_to_str(left_operand),
opt_to_str(operator),
opt_to_str(right_operand)),
Statement::Array{ id: _, length, size_in_bytes} => format!("Init<Array[{}], {} bytes>", length, size_in_bytes),
Statement::Call(ref name, ref operands, ref dest) => {
let op_str = operands.iter()
.fold(
String::new(),
|acc, v| format!("{}, {}", acc, v))
.chars()
.skip(2) // get rid of the leading spaces
.collect::<String>();
let dest_str = if let Some(ref op) = *dest {
format!("{} = ", op)
} else {
String::new()
};
format!("{}{}({})",
dest_str,
name,
op_str)
},
Statement::Return(ref v0) =>
format!("return {}", opt_to_str(v0)),
Statement::Label(id) => format!("Label {}", id),
Statement::Jump(id) => format!("Jump {}", id),
Statement::JumpIfTrue(ref op, id) =>
format!("Jump {} if {}", id, op),
Statement::JumpIfFalse(ref op, id) =>
format!("Jump {} if not {}", id, op),
Statement::PhiFunction(ref dest, ref operands) => {
let mut op_str = operands.
iter().
fold(
String::new(),
|acc, ref t| format!("'{}', {}", t, acc));
op_str.pop(); op_str.pop();
format!("{} = phi<{}>", dest, op_str)
},
Statement::Empty => "<Empty statement>".to_owned()
})
}
}
impl Display for Operand {
fn fmt(&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Operand::ArrayIndex { id, ref index_operand, ref variable_info} => {
format!("{}_{}[{}]", variable_info.name, id, index_operand)
},
Operand::ArraySlice{ id, ref start_operand, ref end_operand, ref variable_info} => {
format!("{}_{}[{}:{}]", variable_info.name, id, start_operand, end_operand)
},
Operand::Variable(ref info, id) => format!("{}_{}", info.name, id),
Operand::AddressOf { ref variable_info, ref id } => format!("&{}_{}", variable_info.name, id),
Operand::SSAVariable(ref info, id, ssa_id) =>
format!("{}_{}:{}", info.name, id, ssa_id),
Operand::Long(v) => format!("{}L", v),
Operand::Integer(v) => format!("{}I", v),
Operand::Short(v) => format!("{}S", v),
Operand::Byte(v) => format!("{}B", v),
Operand::Float(v) => format!("{}F", v),
Operand::Double(v) => format!("{}D", v),
Operand::Boolean(v) => v.to_string(),
Operand::Initialized(ref t) => format!(
"<initialized {} value>", t),
})
}
}
impl Display for Operator {
fn fmt(&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Operator::Plus => "+".to_string(),
Operator::Minus => "-".to_string(),
Operator::Multiply => "*".to_string(),
Operator::Divide => "/".to_string(),
Operator::Modulo=> "%".to_string(),
Operator::Less => "<".to_string(),
Operator::LessOrEq => "<=".to_string(),
Operator::Equals => "==".to_string(),
Operator::NotEquals => "!=".to_string(),
Operator::GreaterOrEq => ">=".to_string(),
Operator::Greater => ">".to_string(),
Operator::ArithmeticShiftRight => ">>".to_string(),
Operator::LogicalShiftRight => ">>>".to_string(),
Operator::LogicalShiftLeft => "<<".to_string(),
Operator::BitwiseAnd => "&".to_string(),
Operator::BitwiseOr => "|".to_string(),
Operator::BitwiseXor => "^".to_string(),
Operator::BitwiseNot => "~".to_string(),
Operator::Cast{ref from, ref to}=> format!("Cast({} to {})", from, to),
})
}
}
fn opt_to_str<T: Display>(op: &Option<T>) -> String {
match *op {
Some(ref val) => format!("{} ", val),
None => "".to_owned(),
}
} | }
impl Display for Statement {
| random_line_split |
tac_code.rs | use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result;
use super::{
function_attributes::FunctionAttribute,
types::Type,
node_info::{ DeclarationInfo, FunctionInfo },
};
use std::rc::Rc;
#[derive(Clone, Debug, PartialEq)]
pub enum Statement {
Assignment{ operator: Option<Operator>, destination: Option<Operand>, left_operand: Option<Operand>, right_operand: Option<Operand> },
Array{ id: u32, length: i32, size_in_bytes: u32 },
Call(Rc<String>, Vec<Operand>, Option<Operand>),
Label(u32),
Jump(u32),
JumpIfTrue(Operand, u32),
JumpIfFalse(Operand, u32),
Return(Option<Operand>),
Empty,
PhiFunction(Operand, Vec<Operand>)
}
// TODO replace tuples with structs for better readability
#[derive(Clone, Debug, PartialEq)]
pub enum Operand {
Variable(DeclarationInfo, u32),
AddressOf{ variable_info: DeclarationInfo, id: u32, },
ArrayIndex{ id: u32, index_operand: Box<Operand>, variable_info: DeclarationInfo, },
ArraySlice{ id: u32, start_operand: Box<Operand>, end_operand: Box<Operand>, variable_info: DeclarationInfo, },
SSAVariable(DeclarationInfo, u32, u32),
Long(i64),
Integer(i32),
Short(i16),
Byte(i8),
Float(f32),
Double(f64),
Boolean(bool),
// special operand to represent initialized, but unknown, value
// used for things like function parameters
Initialized(Type),
}
#[derive(Clone, Debug, PartialEq)]
pub enum Operator {
Plus,
Minus,
Multiply,
Divide,
Modulo,
Less,
LessOrEq,
Equals,
NotEquals,
GreaterOrEq,
Greater,
ArithmeticShiftRight,
LogicalShiftRight,
LogicalShiftLeft,
BitwiseAnd,
BitwiseOr,
BitwiseXor,
BitwiseNot,
Cast{ from: Type, to: Type},
}
#[derive(Clone, Debug)]
pub struct Function {
pub statements: Vec<Statement>,
pub function_info: FunctionInfo,
pub attributes: Vec<FunctionAttribute>,
}
impl Function {
pub fn new(function_info: FunctionInfo) -> Function {
Function {
statements: vec![],
function_info,
attributes: vec![],
}
}
pub fn print(&self) {
let mut counter = 0;
println!("Function '{}'\n", self.function_info.name);
for s in &self.statements {
println!(" {}: {}", counter, s);
counter += 1;
}
println!();
}
pub fn has_attribute(&self, attribute: FunctionAttribute) -> bool {
self.attributes.contains(&attribute)
}
}
impl Display for Statement {
fn fmt(&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Statement::Assignment{ref operator, ref destination, ref left_operand, ref right_operand} =>
format!("{}= {}{}{}",
opt_to_str(destination),
opt_to_str(left_operand),
opt_to_str(operator),
opt_to_str(right_operand)),
Statement::Array{ id: _, length, size_in_bytes} => format!("Init<Array[{}], {} bytes>", length, size_in_bytes),
Statement::Call(ref name, ref operands, ref dest) => {
let op_str = operands.iter()
.fold(
String::new(),
|acc, v| format!("{}, {}", acc, v))
.chars()
.skip(2) // get rid of the leading spaces
.collect::<String>();
let dest_str = if let Some(ref op) = *dest {
format!("{} = ", op)
} else {
String::new()
};
format!("{}{}({})",
dest_str,
name,
op_str)
},
Statement::Return(ref v0) =>
format!("return {}", opt_to_str(v0)),
Statement::Label(id) => format!("Label {}", id),
Statement::Jump(id) => format!("Jump {}", id),
Statement::JumpIfTrue(ref op, id) =>
format!("Jump {} if {}", id, op),
Statement::JumpIfFalse(ref op, id) =>
format!("Jump {} if not {}", id, op),
Statement::PhiFunction(ref dest, ref operands) => {
let mut op_str = operands.
iter().
fold(
String::new(),
|acc, ref t| format!("'{}', {}", t, acc));
op_str.pop(); op_str.pop();
format!("{} = phi<{}>", dest, op_str)
},
Statement::Empty => "<Empty statement>".to_owned()
})
}
}
impl Display for Operand {
fn fmt(&self, formatter: &mut Formatter) -> Result | "<initialized {} value>", t),
})
}
}
impl Display for Operator {
fn fmt(&self, formatter: &mut Formatter) -> Result {
write!(formatter, "{}", match *self {
Operator::Plus => "+".to_string(),
Operator::Minus => "-".to_string(),
Operator::Multiply => "*".to_string(),
Operator::Divide => "/".to_string(),
Operator::Modulo=> "%".to_string(),
Operator::Less => "<".to_string(),
Operator::LessOrEq => "<=".to_string(),
Operator::Equals => "==".to_string(),
Operator::NotEquals => "!=".to_string(),
Operator::GreaterOrEq => ">=".to_string(),
Operator::Greater => ">".to_string(),
Operator::ArithmeticShiftRight => ">>".to_string(),
Operator::LogicalShiftRight => ">>>".to_string(),
Operator::LogicalShiftLeft => "<<".to_string(),
Operator::BitwiseAnd => "&".to_string(),
Operator::BitwiseOr => "|".to_string(),
Operator::BitwiseXor => "^".to_string(),
Operator::BitwiseNot => "~".to_string(),
Operator::Cast{ref from, ref to}=> format!("Cast({} to {})", from, to),
})
}
}
fn opt_to_str<T: Display>(op: &Option<T>) -> String {
match *op {
Some(ref val) => format!("{} ", val),
None => "".to_owned(),
}
} | {
write!(formatter, "{}", match *self {
Operand::ArrayIndex { id, ref index_operand, ref variable_info} => {
format!("{}_{}[{}]", variable_info.name, id, index_operand)
},
Operand::ArraySlice{ id, ref start_operand, ref end_operand, ref variable_info} => {
format!("{}_{}[{}:{}]", variable_info.name, id, start_operand, end_operand)
},
Operand::Variable(ref info, id) => format!("{}_{}", info.name, id),
Operand::AddressOf { ref variable_info, ref id } => format!("&{}_{}", variable_info.name, id),
Operand::SSAVariable(ref info, id, ssa_id) =>
format!("{}_{}:{}", info.name, id, ssa_id),
Operand::Long(v) => format!("{}L", v),
Operand::Integer(v) => format!("{}I", v),
Operand::Short(v) => format!("{}S", v),
Operand::Byte(v) => format!("{}B", v),
Operand::Float(v) => format!("{}F", v),
Operand::Double(v) => format!("{}D", v),
Operand::Boolean(v) => v.to_string(),
Operand::Initialized(ref t) => format!(
| identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use egl::egl::EGLContext;
use egl::egl::EGLDisplay;
use egl::egl::EGLSurface;
use egl::egl::MakeCurrent;
use egl::egl::SwapBuffers;
use libc::{dup2, pipe, read};
use log::info;
use log::warn;
use rust_webvr::api::MagicLeapVRService;
use servo::euclid::Scale;
use servo::keyboard_types::Key;
use servo::servo_url::ServoUrl;
use servo::webrender_api::units::{DeviceIntRect, DevicePixel, DevicePoint, LayoutPixel};
use simpleservo::{self, deinit, gl_glue, MouseButton, ServoGlue, SERVO};
use simpleservo::{
Coordinates, EventLoopWaker, HostTrait, InitOptions, InputMethodType, PromptResult,
VRInitOptions,
};
use smallvec::SmallVec;
use std::cell::Cell;
use std::ffi::CStr;
use std::ffi::CString;
use std::io::Write;
use std::os::raw::c_char;
use std::os::raw::c_int;
use std::os::raw::c_void;
use std::rc::Rc;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use webxr::magicleap::MagicLeapDiscovery;
#[repr(u32)]
pub enum MLLogLevel {
Fatal = 0,
Error = 1,
Warning = 2,
Info = 3,
Debug = 4,
Verbose = 5,
}
#[repr(C)]
#[allow(non_camel_case_types)]
pub enum MLKeyType {
kNone,
kCharacter,
kBackspace,
kShift,
kSpeechToText,
kPageEmoji,
kPageLowerLetters,
kPageNumericSymbols,
kCancel,
kSubmit,
kPrevious,
kNext,
kClear,
kClose,
kEnter,
kCustom1,
kCustom2,
kCustom3,
kCustom4,
kCustom5,
}
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct MLLogger(Option<extern "C" fn(MLLogLevel, *const c_char)>);
#[repr(transparent)]
pub struct MLHistoryUpdate(Option<extern "C" fn(MLApp, bool, bool)>);
#[repr(transparent)]
pub struct MLURLUpdate(Option<extern "C" fn(MLApp, *const c_char)>);
#[repr(transparent)]
pub struct MLKeyboard(Option<extern "C" fn(MLApp, bool)>);
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct MLApp(*mut c_void);
const LOG_LEVEL: log::LevelFilter = log::LevelFilter::Info;
fn call<F, T>(f: F) -> Result<T, &'static str>
where
F: FnOnce(&mut ServoGlue) -> Result<T, &'static str>,
{
SERVO.with(|s| match s.borrow_mut().as_mut() {
Some(ref mut s) => (f)(s),
None => Err("Servo is not available in this thread"),
})
}
#[no_mangle]
pub unsafe extern "C" fn init_servo(
ctxt: EGLContext,
surf: EGLSurface,
disp: EGLDisplay,
landscape: bool,
app: MLApp,
logger: MLLogger,
history_update: MLHistoryUpdate,
url_update: MLURLUpdate,
keyboard: MLKeyboard,
url: *const c_char,
default_args: *const c_char,
width: u32,
height: u32,
hidpi: f32,
) -> *mut ServoInstance {
redirect_stdout_to_log(logger);
let _ = log::set_boxed_logger(Box::new(logger));
log::set_max_level(LOG_LEVEL);
let gl = gl_glue::egl::init().expect("EGL initialization failure");
let coordinates = Coordinates::new(
0,
0,
width as i32,
height as i32,
width as i32,
height as i32,
);
let mut url = CStr::from_ptr(url).to_str().unwrap_or("about:blank");
// If the URL has a space in it, then treat everything before the space as arguments
let args = if let Some(i) = url.rfind(' ') {
let (front, back) = url.split_at(i);
url = back;
front.split(' ').map(|s| s.to_owned()).collect()
} else if!default_args.is_null() {
CStr::from_ptr(default_args)
.to_str()
.unwrap_or("")
.split(' ')
.map(|s| s.to_owned())
.collect()
} else {
Vec::new()
};
info!("got args: {:?}", args);
let vr_init = if!landscape {
let name = String::from("Magic Leap VR Display");
let (service, heartbeat) = MagicLeapVRService::new(name, ctxt, gl.gl_wrapper.clone())
.expect("Failed to create VR service");
let service = Box::new(service);
let heartbeat = Box::new(heartbeat);
VRInitOptions::VRService(service, heartbeat)
} else {
VRInitOptions::None
};
let xr_discovery: Option<Box<dyn webxr_api::Discovery>> = if!landscape {
let discovery = MagicLeapDiscovery::new(ctxt, gl.gl_wrapper.clone());
Some(Box::new(discovery))
} else {
None
};
let opts = InitOptions {
args,
url: Some(url.to_string()),
density: hidpi,
enable_subpixel_text_antialiasing: false,
vr_init,
xr_discovery,
coordinates,
gl_context_pointer: Some(ctxt),
native_display_pointer: Some(disp),
};
let wakeup = Box::new(EventLoopWakerInstance);
let shut_down_complete = Rc::new(Cell::new(false));
let callbacks = Box::new(HostCallbacks {
app,
ctxt,
surf,
disp,
landscape,
shut_down_complete: shut_down_complete.clone(),
history_update,
url_update,
keyboard,
});
info!("Starting servo");
simpleservo::init(opts, gl.gl_wrapper, wakeup, callbacks).expect("error initializing Servo");
let result = Box::new(ServoInstance {
scroll_state: ScrollState::TriggerUp,
scroll_scale: Scale::new(SCROLL_SCALE / hidpi),
shut_down_complete,
});
Box::into_raw(result)
}
#[no_mangle]
pub unsafe extern "C" fn heartbeat_servo(_servo: *mut ServoInstance) {
let _ = call(|s| s.perform_updates());
}
#[no_mangle]
pub unsafe extern "C" fn keyboard_servo(
_servo: *mut ServoInstance,
key_code: char,
key_type: MLKeyType,
) {
let key = match key_type {
MLKeyType::kCharacter => Key::Character([key_code].iter().collect()),
MLKeyType::kBackspace => Key::Backspace,
MLKeyType::kEnter => Key::Enter,
_ => return,
};
// TODO: can the ML1 generate separate press and release events?
let key2 = key.clone();
let _ = call(move |s| s.key_down(key2));
let _ = call(move |s| s.key_up(key));
}
// Some magic numbers.
// How far does the cursor have to move for it to count as a drag rather than a click?
// (In device pixels squared, to avoid taking a sqrt when calculating move distance.)
const DRAG_CUTOFF_SQUARED: f32 = 900.0;
// How much should we scale scrolling by?
const SCROLL_SCALE: f32 = 3.0;
#[no_mangle]
pub unsafe extern "C" fn move_servo(servo: *mut ServoInstance, x: f32, y: f32) {
// Servo's cursor was moved
if let Some(servo) = servo.as_mut() {
let point = DevicePoint::new(x, y);
match servo.scroll_state {
ScrollState::TriggerUp => {
servo.scroll_state = ScrollState::TriggerUp;
let _ = call(|s| s.mouse_move(x, y));
},
ScrollState::TriggerDown(start)
if (start - point).square_length() < DRAG_CUTOFF_SQUARED =>
{
return;
}
ScrollState::TriggerDown(start) => {
servo.scroll_state = ScrollState::TriggerDragging(start, point);
let _ = call(|s| s.mouse_move(x, y));
let delta = (point - start) * servo.scroll_scale;
let start = start.to_i32();
let _ = call(|s| s.scroll_start(delta.x, delta.y, start.x, start.y));
},
ScrollState::TriggerDragging(start, prev) => {
servo.scroll_state = ScrollState::TriggerDragging(start, point);
let _ = call(|s| s.mouse_move(x, y));
let delta = (point - prev) * servo.scroll_scale;
let start = start.to_i32();
let _ = call(|s| s.scroll(delta.x, delta.y, start.x, start.y));
},
}
}
}
#[no_mangle]
pub unsafe extern "C" fn trigger_servo(servo: *mut ServoInstance, x: f32, y: f32, down: bool) {
// Servo was triggered
if let Some(servo) = servo.as_mut() {
let point = DevicePoint::new(x, y);
match servo.scroll_state {
ScrollState::TriggerUp if down => {
servo.scroll_state = ScrollState::TriggerDown(point);
let _ = call(|s| s.mouse_down(x, y, MouseButton::Left));
},
ScrollState::TriggerDown(start) if!down => {
servo.scroll_state = ScrollState::TriggerUp;
let _ = call(|s| s.mouse_up(start.x, start.y, MouseButton::Left));
let _ = call(|s| s.click(start.x as f32, start.y as f32));
let _ = call(|s| s.mouse_move(start.x, start.y));
},
ScrollState::TriggerDragging(start, prev) if!down => {
servo.scroll_state = ScrollState::TriggerUp;
let delta = (point - prev) * servo.scroll_scale;
let start = start.to_i32();
let _ = call(|s| s.scroll_end(delta.x, delta.y, start.x, start.y));
let _ = call(|s| s.mouse_up(x, y, MouseButton::Left));
},
_ => return,
}
}
}
#[no_mangle]
pub unsafe extern "C" fn traverse_servo(_servo: *mut ServoInstance, delta: i32) {
// Traverse the session history
if delta == 0 {
let _ = call(|s| s.reload());
} else if delta < 0 {
let _ = call(|s| s.go_back());
} else {
let _ = call(|s| s.go_forward());
}
}
#[no_mangle]
pub unsafe extern "C" fn navigate_servo(_servo: *mut ServoInstance, text: *const c_char) {
let text = CStr::from_ptr(text)
.to_str()
.expect("Failed to convert text to UTF-8");
let url = ServoUrl::parse(text).unwrap_or_else(|_| {
let mut search = ServoUrl::parse("https://duckduckgo.com")
.expect("Failed to parse search URL")
.into_url();
search.query_pairs_mut().append_pair("q", text);
ServoUrl::from_url(search)
});
let _ = call(|s| s.load_uri(url.as_str()));
}
// Some magic numbers for shutdown
const SHUTDOWN_DURATION: Duration = Duration::from_secs(10);
const SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(100);
#[no_mangle]
pub unsafe extern "C" fn discard_servo(servo: *mut ServoInstance) {
if let Some(servo) = servo.as_mut() {
let servo = Box::from_raw(servo);
let finish = Instant::now() + SHUTDOWN_DURATION;
let _ = call(|s| s.request_shutdown());
while!servo.shut_down_complete.get() {
let _ = call(|s| s.perform_updates());
if Instant::now() > finish {
warn!("Incomplete shutdown.");
}
thread::sleep(SHUTDOWN_POLL_INTERVAL);
}
deinit();
}
}
struct HostCallbacks {
ctxt: EGLContext,
surf: EGLSurface,
disp: EGLDisplay,
landscape: bool,
shut_down_complete: Rc<Cell<bool>>,
history_update: MLHistoryUpdate,
url_update: MLURLUpdate,
app: MLApp,
keyboard: MLKeyboard,
}
impl HostTrait for HostCallbacks {
fn flush(&self) {
// Immersive and landscape apps have different requirements for who calls SwapBuffers.
if self.landscape {
SwapBuffers(self.disp, self.surf);
}
}
fn make_current(&self) {
MakeCurrent(self.disp, self.surf, self.surf, self.ctxt);
}
fn prompt_alert(&self, message: String, _trusted: bool) {
warn!("Prompt Alert: {}", message);
}
fn prompt_ok_cancel(&self, message: String, _trusted: bool) -> PromptResult {
warn!("Prompt not implemented. Cancelled. {}", message);
PromptResult::Secondary
}
fn prompt_yes_no(&self, message: String, _trusted: bool) -> PromptResult {
warn!("Prompt not implemented. Cancelled. {}", message);
PromptResult::Secondary
}
fn prompt_input(&self, message: String, default: String, _trusted: bool) -> Option<String> {
warn!("Input prompt not implemented. {}", message);
Some(default)
}
fn on_load_started(&self) {}
fn on_load_ended(&self) {}
fn on_title_changed(&self, _title: String) {}
fn on_allow_navigation(&self, _url: String) -> bool {
true
}
fn on_url_changed(&self, url: String) {
if let Ok(cstr) = CString::new(url.as_str()) {
if let Some(url_update) = self.url_update.0 {
url_update(self.app, cstr.as_ptr());
}
}
}
fn on_history_changed(&self, can_go_back: bool, can_go_forward: bool) {
if let Some(history_update) = self.history_update.0 {
history_update(self.app, can_go_back, can_go_forward);
}
}
fn on_animating_changed(&self, _animating: bool) {}
fn on_shutdown_complete(&self) {
self.shut_down_complete.set(true);
}
fn on_ime_show(
&self,
_input_type: InputMethodType,
_text: Option<String>,
_bounds: DeviceIntRect,
) {
if let Some(keyboard) = self.keyboard.0 {
keyboard(self.app, true)
}
}
fn on_ime_hide(&self) {
if let Some(keyboard) = self.keyboard.0 {
keyboard(self.app, false)
}
}
fn get_clipboard_contents(&self) -> Option<String> {
None
}
fn | (&self, _contents: String) {}
fn on_devtools_started(&self, port: Result<u16, ()>) {
match port {
Ok(p) => info!("Devtools Server running on port {}", p),
Err(()) => error!("Error running Devtools server"),
}
}
}
pub struct ServoInstance {
scroll_state: ScrollState,
scroll_scale: Scale<f32, DevicePixel, LayoutPixel>,
shut_down_complete: Rc<Cell<bool>>,
}
#[derive(Clone, Copy)]
enum ScrollState {
TriggerUp,
TriggerDown(DevicePoint),
TriggerDragging(DevicePoint, DevicePoint),
}
struct EventLoopWakerInstance;
impl EventLoopWaker for EventLoopWakerInstance {
fn clone_box(&self) -> Box<dyn EventLoopWaker> {
Box::new(EventLoopWakerInstance)
}
fn wake(&self) {}
}
impl log::Log for MLLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= LOG_LEVEL
}
fn log(&self, record: &log::Record) {
if let Some(log) = self.0 {
let lvl = match record.level() {
log::Level::Error => MLLogLevel::Error,
log::Level::Warn => MLLogLevel::Warning,
log::Level::Info => MLLogLevel::Info,
log::Level::Debug => MLLogLevel::Debug,
log::Level::Trace => MLLogLevel::Verbose,
};
let mut msg = SmallVec::<[u8; 128]>::new();
write!(msg, "{}\0", record.args()).unwrap();
log(lvl, &msg[0] as *const _ as *const _);
}
}
fn flush(&self) {}
}
fn redirect_stdout_to_log(logger: MLLogger) {
let log = match logger.0 {
None => return,
Some(log) => log,
};
// The first step is to redirect stdout and stderr to the logs.
// We redirect stdout and stderr to a custom descriptor.
let mut pfd: [c_int; 2] = [0, 0];
unsafe {
pipe(pfd.as_mut_ptr());
dup2(pfd[1], 1);
dup2(pfd[1], 2);
}
let descriptor = pfd[0];
// Then we spawn a thread whose only job is to read from the other side of the
// pipe and redirect to the logs.
let _detached = thread::spawn(move || {
const BUF_LENGTH: usize = 512;
let mut buf = vec![b'\0' as c_char; BUF_LENGTH];
// Always keep at least one null terminator
const BUF_AVAILABLE: usize = BUF_LENGTH - 1;
let buf = &mut buf[..BUF_AVAILABLE];
let mut cursor = 0_usize;
loop {
let result = {
let read_into = &mut buf[cursor..];
unsafe {
read(
descriptor,
read_into.as_mut_ptr() as *mut _,
read_into.len(),
)
}
};
let end = if result == 0 {
return;
} else if result < 0 {
log(
MLLogLevel::Error,
b"error in log thread; closing\0".as_ptr() as *const _,
);
return;
} else {
result as usize + cursor
};
// Only modify the portion of the buffer that contains real data.
let buf = &mut buf[0..end];
if let Some(last_newline_pos) = buf.iter().rposition(|&c| c == b'\n' as c_char) {
buf[last_newline_pos] = b'\0' as c_char;
log(MLLogLevel::Info, buf.as_ptr());
if last_newline_pos < buf.len() - 1 {
let pos_after_newline = last_newline_pos + 1;
let len_not_logged_yet = buf[pos_after_newline..].len();
for j in 0..len_not_logged_yet as usize {
buf[j] = buf[pos_after_newline + j];
}
cursor = len_not_logged_yet;
} else {
cursor = 0;
}
} else if end == BUF_AVAILABLE {
// No newline found but the buffer is full, flush it anyway.
// `buf.as_ptr()` is null-terminated by BUF_LENGTH being 1 less than BUF_AVAILABLE.
log(MLLogLevel::Info, buf.as_ptr());
cursor = 0;
} else {
cursor = end;
}
}
});
}
| set_clipboard_contents | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use egl::egl::EGLContext;
use egl::egl::EGLDisplay;
use egl::egl::EGLSurface;
use egl::egl::MakeCurrent;
use egl::egl::SwapBuffers;
use libc::{dup2, pipe, read};
use log::info;
use log::warn;
use rust_webvr::api::MagicLeapVRService;
use servo::euclid::Scale;
use servo::keyboard_types::Key;
use servo::servo_url::ServoUrl;
use servo::webrender_api::units::{DeviceIntRect, DevicePixel, DevicePoint, LayoutPixel};
use simpleservo::{self, deinit, gl_glue, MouseButton, ServoGlue, SERVO};
use simpleservo::{
Coordinates, EventLoopWaker, HostTrait, InitOptions, InputMethodType, PromptResult,
VRInitOptions,
};
use smallvec::SmallVec;
use std::cell::Cell;
use std::ffi::CStr;
use std::ffi::CString;
use std::io::Write;
use std::os::raw::c_char;
use std::os::raw::c_int;
use std::os::raw::c_void;
use std::rc::Rc;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use webxr::magicleap::MagicLeapDiscovery;
#[repr(u32)]
pub enum MLLogLevel {
Fatal = 0,
Error = 1,
Warning = 2,
Info = 3,
Debug = 4,
Verbose = 5,
}
#[repr(C)]
#[allow(non_camel_case_types)]
pub enum MLKeyType {
kNone,
kCharacter,
kBackspace,
kShift,
kSpeechToText,
kPageEmoji,
kPageLowerLetters,
kPageNumericSymbols,
kCancel,
kSubmit,
kPrevious,
kNext,
kClear,
kClose,
kEnter,
kCustom1,
kCustom2,
kCustom3,
kCustom4,
kCustom5,
}
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct MLLogger(Option<extern "C" fn(MLLogLevel, *const c_char)>);
#[repr(transparent)]
pub struct MLHistoryUpdate(Option<extern "C" fn(MLApp, bool, bool)>);
#[repr(transparent)]
pub struct MLURLUpdate(Option<extern "C" fn(MLApp, *const c_char)>);
#[repr(transparent)]
pub struct MLKeyboard(Option<extern "C" fn(MLApp, bool)>);
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct MLApp(*mut c_void);
const LOG_LEVEL: log::LevelFilter = log::LevelFilter::Info;
fn call<F, T>(f: F) -> Result<T, &'static str>
where
F: FnOnce(&mut ServoGlue) -> Result<T, &'static str>,
{
SERVO.with(|s| match s.borrow_mut().as_mut() {
Some(ref mut s) => (f)(s),
None => Err("Servo is not available in this thread"),
})
}
#[no_mangle]
pub unsafe extern "C" fn init_servo(
ctxt: EGLContext,
surf: EGLSurface,
disp: EGLDisplay,
landscape: bool,
app: MLApp,
logger: MLLogger,
history_update: MLHistoryUpdate,
url_update: MLURLUpdate,
keyboard: MLKeyboard,
url: *const c_char,
default_args: *const c_char,
width: u32,
height: u32,
hidpi: f32,
) -> *mut ServoInstance {
redirect_stdout_to_log(logger);
let _ = log::set_boxed_logger(Box::new(logger));
log::set_max_level(LOG_LEVEL);
let gl = gl_glue::egl::init().expect("EGL initialization failure");
let coordinates = Coordinates::new(
0,
0,
width as i32,
height as i32,
width as i32,
height as i32,
);
let mut url = CStr::from_ptr(url).to_str().unwrap_or("about:blank");
// If the URL has a space in it, then treat everything before the space as arguments
let args = if let Some(i) = url.rfind(' ') {
let (front, back) = url.split_at(i);
url = back;
front.split(' ').map(|s| s.to_owned()).collect()
} else if!default_args.is_null() {
CStr::from_ptr(default_args)
.to_str()
.unwrap_or("")
.split(' ')
.map(|s| s.to_owned())
.collect()
} else {
Vec::new()
};
info!("got args: {:?}", args);
let vr_init = if!landscape {
let name = String::from("Magic Leap VR Display");
let (service, heartbeat) = MagicLeapVRService::new(name, ctxt, gl.gl_wrapper.clone())
.expect("Failed to create VR service");
let service = Box::new(service);
let heartbeat = Box::new(heartbeat);
VRInitOptions::VRService(service, heartbeat)
} else {
VRInitOptions::None
};
let xr_discovery: Option<Box<dyn webxr_api::Discovery>> = if!landscape {
let discovery = MagicLeapDiscovery::new(ctxt, gl.gl_wrapper.clone());
Some(Box::new(discovery))
} else {
None
};
let opts = InitOptions {
args,
url: Some(url.to_string()),
density: hidpi,
enable_subpixel_text_antialiasing: false,
vr_init,
xr_discovery,
coordinates,
gl_context_pointer: Some(ctxt),
native_display_pointer: Some(disp),
};
let wakeup = Box::new(EventLoopWakerInstance);
let shut_down_complete = Rc::new(Cell::new(false));
let callbacks = Box::new(HostCallbacks {
app,
ctxt,
surf,
disp,
landscape,
shut_down_complete: shut_down_complete.clone(),
history_update,
url_update,
keyboard,
});
info!("Starting servo");
simpleservo::init(opts, gl.gl_wrapper, wakeup, callbacks).expect("error initializing Servo");
let result = Box::new(ServoInstance {
scroll_state: ScrollState::TriggerUp,
scroll_scale: Scale::new(SCROLL_SCALE / hidpi),
shut_down_complete,
});
Box::into_raw(result)
}
#[no_mangle]
pub unsafe extern "C" fn heartbeat_servo(_servo: *mut ServoInstance) {
let _ = call(|s| s.perform_updates());
}
#[no_mangle]
pub unsafe extern "C" fn keyboard_servo(
_servo: *mut ServoInstance,
key_code: char,
key_type: MLKeyType,
) {
let key = match key_type {
MLKeyType::kCharacter => Key::Character([key_code].iter().collect()),
MLKeyType::kBackspace => Key::Backspace,
MLKeyType::kEnter => Key::Enter,
_ => return,
};
// TODO: can the ML1 generate separate press and release events?
let key2 = key.clone();
let _ = call(move |s| s.key_down(key2));
let _ = call(move |s| s.key_up(key));
}
// Some magic numbers.
// How far does the cursor have to move for it to count as a drag rather than a click?
// (In device pixels squared, to avoid taking a sqrt when calculating move distance.)
const DRAG_CUTOFF_SQUARED: f32 = 900.0;
// How much should we scale scrolling by?
const SCROLL_SCALE: f32 = 3.0;
#[no_mangle]
pub unsafe extern "C" fn move_servo(servo: *mut ServoInstance, x: f32, y: f32) {
// Servo's cursor was moved
if let Some(servo) = servo.as_mut() {
let point = DevicePoint::new(x, y);
match servo.scroll_state {
ScrollState::TriggerUp => {
servo.scroll_state = ScrollState::TriggerUp;
let _ = call(|s| s.mouse_move(x, y));
},
ScrollState::TriggerDown(start)
if (start - point).square_length() < DRAG_CUTOFF_SQUARED =>
{
return;
}
ScrollState::TriggerDown(start) => {
servo.scroll_state = ScrollState::TriggerDragging(start, point);
let _ = call(|s| s.mouse_move(x, y));
let delta = (point - start) * servo.scroll_scale;
let start = start.to_i32();
let _ = call(|s| s.scroll_start(delta.x, delta.y, start.x, start.y));
},
ScrollState::TriggerDragging(start, prev) => {
servo.scroll_state = ScrollState::TriggerDragging(start, point);
let _ = call(|s| s.mouse_move(x, y));
let delta = (point - prev) * servo.scroll_scale;
let start = start.to_i32();
let _ = call(|s| s.scroll(delta.x, delta.y, start.x, start.y));
},
}
}
}
#[no_mangle]
pub unsafe extern "C" fn trigger_servo(servo: *mut ServoInstance, x: f32, y: f32, down: bool) {
// Servo was triggered
if let Some(servo) = servo.as_mut() {
let point = DevicePoint::new(x, y);
match servo.scroll_state {
ScrollState::TriggerUp if down => {
servo.scroll_state = ScrollState::TriggerDown(point);
let _ = call(|s| s.mouse_down(x, y, MouseButton::Left));
},
ScrollState::TriggerDown(start) if!down => {
servo.scroll_state = ScrollState::TriggerUp;
let _ = call(|s| s.mouse_up(start.x, start.y, MouseButton::Left));
let _ = call(|s| s.click(start.x as f32, start.y as f32));
let _ = call(|s| s.mouse_move(start.x, start.y));
},
ScrollState::TriggerDragging(start, prev) if!down => {
servo.scroll_state = ScrollState::TriggerUp;
let delta = (point - prev) * servo.scroll_scale;
let start = start.to_i32();
let _ = call(|s| s.scroll_end(delta.x, delta.y, start.x, start.y));
let _ = call(|s| s.mouse_up(x, y, MouseButton::Left));
},
_ => return,
}
}
}
#[no_mangle]
pub unsafe extern "C" fn traverse_servo(_servo: *mut ServoInstance, delta: i32) {
// Traverse the session history
if delta == 0 {
let _ = call(|s| s.reload());
} else if delta < 0 {
let _ = call(|s| s.go_back());
} else {
let _ = call(|s| s.go_forward());
}
}
#[no_mangle]
pub unsafe extern "C" fn navigate_servo(_servo: *mut ServoInstance, text: *const c_char) {
let text = CStr::from_ptr(text)
.to_str()
.expect("Failed to convert text to UTF-8");
let url = ServoUrl::parse(text).unwrap_or_else(|_| {
let mut search = ServoUrl::parse("https://duckduckgo.com")
.expect("Failed to parse search URL")
.into_url();
search.query_pairs_mut().append_pair("q", text);
ServoUrl::from_url(search)
});
let _ = call(|s| s.load_uri(url.as_str()));
}
// Some magic numbers for shutdown
const SHUTDOWN_DURATION: Duration = Duration::from_secs(10);
const SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(100);
#[no_mangle]
pub unsafe extern "C" fn discard_servo(servo: *mut ServoInstance) {
if let Some(servo) = servo.as_mut() {
let servo = Box::from_raw(servo);
let finish = Instant::now() + SHUTDOWN_DURATION;
let _ = call(|s| s.request_shutdown());
while!servo.shut_down_complete.get() {
let _ = call(|s| s.perform_updates());
if Instant::now() > finish {
warn!("Incomplete shutdown.");
}
thread::sleep(SHUTDOWN_POLL_INTERVAL);
}
deinit();
}
}
struct HostCallbacks {
ctxt: EGLContext,
surf: EGLSurface,
disp: EGLDisplay,
landscape: bool,
shut_down_complete: Rc<Cell<bool>>,
history_update: MLHistoryUpdate,
url_update: MLURLUpdate,
app: MLApp,
keyboard: MLKeyboard,
}
impl HostTrait for HostCallbacks {
fn flush(&self) {
// Immersive and landscape apps have different requirements for who calls SwapBuffers.
if self.landscape {
SwapBuffers(self.disp, self.surf);
}
}
fn make_current(&self) {
MakeCurrent(self.disp, self.surf, self.surf, self.ctxt);
}
fn prompt_alert(&self, message: String, _trusted: bool) {
warn!("Prompt Alert: {}", message);
}
fn prompt_ok_cancel(&self, message: String, _trusted: bool) -> PromptResult {
warn!("Prompt not implemented. Cancelled. {}", message);
PromptResult::Secondary
}
fn prompt_yes_no(&self, message: String, _trusted: bool) -> PromptResult {
warn!("Prompt not implemented. Cancelled. {}", message);
PromptResult::Secondary
}
fn prompt_input(&self, message: String, default: String, _trusted: bool) -> Option<String> {
warn!("Input prompt not implemented. {}", message);
Some(default)
}
fn on_load_started(&self) {}
fn on_load_ended(&self) {}
fn on_title_changed(&self, _title: String) {}
fn on_allow_navigation(&self, _url: String) -> bool {
true
}
fn on_url_changed(&self, url: String) {
if let Ok(cstr) = CString::new(url.as_str()) {
if let Some(url_update) = self.url_update.0 {
url_update(self.app, cstr.as_ptr());
}
}
}
fn on_history_changed(&self, can_go_back: bool, can_go_forward: bool) {
if let Some(history_update) = self.history_update.0 {
history_update(self.app, can_go_back, can_go_forward);
}
}
fn on_animating_changed(&self, _animating: bool) {}
fn on_shutdown_complete(&self) {
self.shut_down_complete.set(true);
}
fn on_ime_show(
&self,
_input_type: InputMethodType,
_text: Option<String>,
_bounds: DeviceIntRect,
) {
if let Some(keyboard) = self.keyboard.0 {
keyboard(self.app, true)
}
}
fn on_ime_hide(&self) {
if let Some(keyboard) = self.keyboard.0 {
keyboard(self.app, false)
}
}
fn get_clipboard_contents(&self) -> Option<String> |
fn set_clipboard_contents(&self, _contents: String) {}
fn on_devtools_started(&self, port: Result<u16, ()>) {
match port {
Ok(p) => info!("Devtools Server running on port {}", p),
Err(()) => error!("Error running Devtools server"),
}
}
}
pub struct ServoInstance {
scroll_state: ScrollState,
scroll_scale: Scale<f32, DevicePixel, LayoutPixel>,
shut_down_complete: Rc<Cell<bool>>,
}
#[derive(Clone, Copy)]
enum ScrollState {
TriggerUp,
TriggerDown(DevicePoint),
TriggerDragging(DevicePoint, DevicePoint),
}
struct EventLoopWakerInstance;
impl EventLoopWaker for EventLoopWakerInstance {
fn clone_box(&self) -> Box<dyn EventLoopWaker> {
Box::new(EventLoopWakerInstance)
}
fn wake(&self) {}
}
impl log::Log for MLLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= LOG_LEVEL
}
fn log(&self, record: &log::Record) {
if let Some(log) = self.0 {
let lvl = match record.level() {
log::Level::Error => MLLogLevel::Error,
log::Level::Warn => MLLogLevel::Warning,
log::Level::Info => MLLogLevel::Info,
log::Level::Debug => MLLogLevel::Debug,
log::Level::Trace => MLLogLevel::Verbose,
};
let mut msg = SmallVec::<[u8; 128]>::new();
write!(msg, "{}\0", record.args()).unwrap();
log(lvl, &msg[0] as *const _ as *const _);
}
}
fn flush(&self) {}
}
fn redirect_stdout_to_log(logger: MLLogger) {
let log = match logger.0 {
None => return,
Some(log) => log,
};
// The first step is to redirect stdout and stderr to the logs.
// We redirect stdout and stderr to a custom descriptor.
let mut pfd: [c_int; 2] = [0, 0];
unsafe {
pipe(pfd.as_mut_ptr());
dup2(pfd[1], 1);
dup2(pfd[1], 2);
}
let descriptor = pfd[0];
// Then we spawn a thread whose only job is to read from the other side of the
// pipe and redirect to the logs.
let _detached = thread::spawn(move || {
const BUF_LENGTH: usize = 512;
let mut buf = vec![b'\0' as c_char; BUF_LENGTH];
// Always keep at least one null terminator
const BUF_AVAILABLE: usize = BUF_LENGTH - 1;
let buf = &mut buf[..BUF_AVAILABLE];
let mut cursor = 0_usize;
loop {
let result = {
let read_into = &mut buf[cursor..];
unsafe {
read(
descriptor,
read_into.as_mut_ptr() as *mut _,
read_into.len(),
)
}
};
let end = if result == 0 {
return;
} else if result < 0 {
log(
MLLogLevel::Error,
b"error in log thread; closing\0".as_ptr() as *const _,
);
return;
} else {
result as usize + cursor
};
// Only modify the portion of the buffer that contains real data.
let buf = &mut buf[0..end];
if let Some(last_newline_pos) = buf.iter().rposition(|&c| c == b'\n' as c_char) {
buf[last_newline_pos] = b'\0' as c_char;
log(MLLogLevel::Info, buf.as_ptr());
if last_newline_pos < buf.len() - 1 {
let pos_after_newline = last_newline_pos + 1;
let len_not_logged_yet = buf[pos_after_newline..].len();
for j in 0..len_not_logged_yet as usize {
buf[j] = buf[pos_after_newline + j];
}
cursor = len_not_logged_yet;
} else {
cursor = 0;
}
} else if end == BUF_AVAILABLE {
// No newline found but the buffer is full, flush it anyway.
// `buf.as_ptr()` is null-terminated by BUF_LENGTH being 1 less than BUF_AVAILABLE.
log(MLLogLevel::Info, buf.as_ptr());
cursor = 0;
} else {
cursor = end;
}
}
});
}
| {
None
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use egl::egl::EGLContext;
use egl::egl::EGLDisplay;
use egl::egl::EGLSurface;
use egl::egl::MakeCurrent;
use egl::egl::SwapBuffers;
use libc::{dup2, pipe, read};
use log::info;
use log::warn;
use rust_webvr::api::MagicLeapVRService;
use servo::euclid::Scale;
use servo::keyboard_types::Key;
use servo::servo_url::ServoUrl;
use servo::webrender_api::units::{DeviceIntRect, DevicePixel, DevicePoint, LayoutPixel};
use simpleservo::{self, deinit, gl_glue, MouseButton, ServoGlue, SERVO};
use simpleservo::{
Coordinates, EventLoopWaker, HostTrait, InitOptions, InputMethodType, PromptResult,
VRInitOptions,
};
use smallvec::SmallVec;
use std::cell::Cell;
use std::ffi::CStr;
use std::ffi::CString;
use std::io::Write;
use std::os::raw::c_char;
use std::os::raw::c_int;
use std::os::raw::c_void;
use std::rc::Rc;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use webxr::magicleap::MagicLeapDiscovery;
#[repr(u32)]
pub enum MLLogLevel {
Fatal = 0,
Error = 1,
Warning = 2,
Info = 3,
Debug = 4,
Verbose = 5,
}
#[repr(C)]
#[allow(non_camel_case_types)]
pub enum MLKeyType {
kNone,
kCharacter,
kBackspace,
kShift,
kSpeechToText,
kPageEmoji,
kPageLowerLetters,
kPageNumericSymbols,
kCancel,
kSubmit,
kPrevious,
kNext,
kClear,
kClose,
kEnter,
kCustom1,
kCustom2,
kCustom3,
kCustom4,
kCustom5,
}
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct MLLogger(Option<extern "C" fn(MLLogLevel, *const c_char)>);
#[repr(transparent)]
pub struct MLHistoryUpdate(Option<extern "C" fn(MLApp, bool, bool)>);
#[repr(transparent)]
pub struct MLURLUpdate(Option<extern "C" fn(MLApp, *const c_char)>);
#[repr(transparent)]
pub struct MLKeyboard(Option<extern "C" fn(MLApp, bool)>);
#[repr(transparent)]
#[derive(Clone, Copy)]
pub struct MLApp(*mut c_void);
const LOG_LEVEL: log::LevelFilter = log::LevelFilter::Info;
fn call<F, T>(f: F) -> Result<T, &'static str>
where
F: FnOnce(&mut ServoGlue) -> Result<T, &'static str>,
{
SERVO.with(|s| match s.borrow_mut().as_mut() {
Some(ref mut s) => (f)(s),
None => Err("Servo is not available in this thread"),
})
}
#[no_mangle]
pub unsafe extern "C" fn init_servo(
ctxt: EGLContext,
surf: EGLSurface,
disp: EGLDisplay,
landscape: bool,
app: MLApp,
logger: MLLogger,
history_update: MLHistoryUpdate,
url_update: MLURLUpdate,
keyboard: MLKeyboard,
url: *const c_char,
default_args: *const c_char,
width: u32,
height: u32,
hidpi: f32,
) -> *mut ServoInstance {
redirect_stdout_to_log(logger);
let _ = log::set_boxed_logger(Box::new(logger));
log::set_max_level(LOG_LEVEL);
let gl = gl_glue::egl::init().expect("EGL initialization failure");
let coordinates = Coordinates::new(
0,
0,
width as i32,
height as i32,
width as i32,
height as i32,
);
let mut url = CStr::from_ptr(url).to_str().unwrap_or("about:blank");
// If the URL has a space in it, then treat everything before the space as arguments
let args = if let Some(i) = url.rfind(' ') {
let (front, back) = url.split_at(i);
url = back;
front.split(' ').map(|s| s.to_owned()).collect()
} else if!default_args.is_null() {
CStr::from_ptr(default_args)
.to_str()
.unwrap_or("")
.split(' ')
.map(|s| s.to_owned())
.collect()
} else {
Vec::new()
};
info!("got args: {:?}", args);
| let service = Box::new(service);
let heartbeat = Box::new(heartbeat);
VRInitOptions::VRService(service, heartbeat)
} else {
VRInitOptions::None
};
let xr_discovery: Option<Box<dyn webxr_api::Discovery>> = if!landscape {
let discovery = MagicLeapDiscovery::new(ctxt, gl.gl_wrapper.clone());
Some(Box::new(discovery))
} else {
None
};
let opts = InitOptions {
args,
url: Some(url.to_string()),
density: hidpi,
enable_subpixel_text_antialiasing: false,
vr_init,
xr_discovery,
coordinates,
gl_context_pointer: Some(ctxt),
native_display_pointer: Some(disp),
};
let wakeup = Box::new(EventLoopWakerInstance);
let shut_down_complete = Rc::new(Cell::new(false));
let callbacks = Box::new(HostCallbacks {
app,
ctxt,
surf,
disp,
landscape,
shut_down_complete: shut_down_complete.clone(),
history_update,
url_update,
keyboard,
});
info!("Starting servo");
simpleservo::init(opts, gl.gl_wrapper, wakeup, callbacks).expect("error initializing Servo");
let result = Box::new(ServoInstance {
scroll_state: ScrollState::TriggerUp,
scroll_scale: Scale::new(SCROLL_SCALE / hidpi),
shut_down_complete,
});
Box::into_raw(result)
}
#[no_mangle]
pub unsafe extern "C" fn heartbeat_servo(_servo: *mut ServoInstance) {
let _ = call(|s| s.perform_updates());
}
#[no_mangle]
pub unsafe extern "C" fn keyboard_servo(
_servo: *mut ServoInstance,
key_code: char,
key_type: MLKeyType,
) {
let key = match key_type {
MLKeyType::kCharacter => Key::Character([key_code].iter().collect()),
MLKeyType::kBackspace => Key::Backspace,
MLKeyType::kEnter => Key::Enter,
_ => return,
};
// TODO: can the ML1 generate separate press and release events?
let key2 = key.clone();
let _ = call(move |s| s.key_down(key2));
let _ = call(move |s| s.key_up(key));
}
// Some magic numbers.
// How far does the cursor have to move for it to count as a drag rather than a click?
// (In device pixels squared, to avoid taking a sqrt when calculating move distance.)
const DRAG_CUTOFF_SQUARED: f32 = 900.0;
// How much should we scale scrolling by?
const SCROLL_SCALE: f32 = 3.0;
#[no_mangle]
pub unsafe extern "C" fn move_servo(servo: *mut ServoInstance, x: f32, y: f32) {
// Servo's cursor was moved
if let Some(servo) = servo.as_mut() {
let point = DevicePoint::new(x, y);
match servo.scroll_state {
ScrollState::TriggerUp => {
servo.scroll_state = ScrollState::TriggerUp;
let _ = call(|s| s.mouse_move(x, y));
},
ScrollState::TriggerDown(start)
if (start - point).square_length() < DRAG_CUTOFF_SQUARED =>
{
return;
}
ScrollState::TriggerDown(start) => {
servo.scroll_state = ScrollState::TriggerDragging(start, point);
let _ = call(|s| s.mouse_move(x, y));
let delta = (point - start) * servo.scroll_scale;
let start = start.to_i32();
let _ = call(|s| s.scroll_start(delta.x, delta.y, start.x, start.y));
},
ScrollState::TriggerDragging(start, prev) => {
servo.scroll_state = ScrollState::TriggerDragging(start, point);
let _ = call(|s| s.mouse_move(x, y));
let delta = (point - prev) * servo.scroll_scale;
let start = start.to_i32();
let _ = call(|s| s.scroll(delta.x, delta.y, start.x, start.y));
},
}
}
}
#[no_mangle]
pub unsafe extern "C" fn trigger_servo(servo: *mut ServoInstance, x: f32, y: f32, down: bool) {
// Servo was triggered
if let Some(servo) = servo.as_mut() {
let point = DevicePoint::new(x, y);
match servo.scroll_state {
ScrollState::TriggerUp if down => {
servo.scroll_state = ScrollState::TriggerDown(point);
let _ = call(|s| s.mouse_down(x, y, MouseButton::Left));
},
ScrollState::TriggerDown(start) if!down => {
servo.scroll_state = ScrollState::TriggerUp;
let _ = call(|s| s.mouse_up(start.x, start.y, MouseButton::Left));
let _ = call(|s| s.click(start.x as f32, start.y as f32));
let _ = call(|s| s.mouse_move(start.x, start.y));
},
ScrollState::TriggerDragging(start, prev) if!down => {
servo.scroll_state = ScrollState::TriggerUp;
let delta = (point - prev) * servo.scroll_scale;
let start = start.to_i32();
let _ = call(|s| s.scroll_end(delta.x, delta.y, start.x, start.y));
let _ = call(|s| s.mouse_up(x, y, MouseButton::Left));
},
_ => return,
}
}
}
#[no_mangle]
pub unsafe extern "C" fn traverse_servo(_servo: *mut ServoInstance, delta: i32) {
// Traverse the session history
if delta == 0 {
let _ = call(|s| s.reload());
} else if delta < 0 {
let _ = call(|s| s.go_back());
} else {
let _ = call(|s| s.go_forward());
}
}
#[no_mangle]
pub unsafe extern "C" fn navigate_servo(_servo: *mut ServoInstance, text: *const c_char) {
let text = CStr::from_ptr(text)
.to_str()
.expect("Failed to convert text to UTF-8");
let url = ServoUrl::parse(text).unwrap_or_else(|_| {
let mut search = ServoUrl::parse("https://duckduckgo.com")
.expect("Failed to parse search URL")
.into_url();
search.query_pairs_mut().append_pair("q", text);
ServoUrl::from_url(search)
});
let _ = call(|s| s.load_uri(url.as_str()));
}
// Some magic numbers for shutdown
const SHUTDOWN_DURATION: Duration = Duration::from_secs(10);
const SHUTDOWN_POLL_INTERVAL: Duration = Duration::from_millis(100);
#[no_mangle]
pub unsafe extern "C" fn discard_servo(servo: *mut ServoInstance) {
if let Some(servo) = servo.as_mut() {
let servo = Box::from_raw(servo);
let finish = Instant::now() + SHUTDOWN_DURATION;
let _ = call(|s| s.request_shutdown());
while!servo.shut_down_complete.get() {
let _ = call(|s| s.perform_updates());
if Instant::now() > finish {
warn!("Incomplete shutdown.");
}
thread::sleep(SHUTDOWN_POLL_INTERVAL);
}
deinit();
}
}
struct HostCallbacks {
ctxt: EGLContext,
surf: EGLSurface,
disp: EGLDisplay,
landscape: bool,
shut_down_complete: Rc<Cell<bool>>,
history_update: MLHistoryUpdate,
url_update: MLURLUpdate,
app: MLApp,
keyboard: MLKeyboard,
}
impl HostTrait for HostCallbacks {
fn flush(&self) {
// Immersive and landscape apps have different requirements for who calls SwapBuffers.
if self.landscape {
SwapBuffers(self.disp, self.surf);
}
}
fn make_current(&self) {
MakeCurrent(self.disp, self.surf, self.surf, self.ctxt);
}
fn prompt_alert(&self, message: String, _trusted: bool) {
warn!("Prompt Alert: {}", message);
}
fn prompt_ok_cancel(&self, message: String, _trusted: bool) -> PromptResult {
warn!("Prompt not implemented. Cancelled. {}", message);
PromptResult::Secondary
}
fn prompt_yes_no(&self, message: String, _trusted: bool) -> PromptResult {
warn!("Prompt not implemented. Cancelled. {}", message);
PromptResult::Secondary
}
fn prompt_input(&self, message: String, default: String, _trusted: bool) -> Option<String> {
warn!("Input prompt not implemented. {}", message);
Some(default)
}
fn on_load_started(&self) {}
fn on_load_ended(&self) {}
fn on_title_changed(&self, _title: String) {}
fn on_allow_navigation(&self, _url: String) -> bool {
true
}
fn on_url_changed(&self, url: String) {
if let Ok(cstr) = CString::new(url.as_str()) {
if let Some(url_update) = self.url_update.0 {
url_update(self.app, cstr.as_ptr());
}
}
}
fn on_history_changed(&self, can_go_back: bool, can_go_forward: bool) {
if let Some(history_update) = self.history_update.0 {
history_update(self.app, can_go_back, can_go_forward);
}
}
fn on_animating_changed(&self, _animating: bool) {}
fn on_shutdown_complete(&self) {
self.shut_down_complete.set(true);
}
fn on_ime_show(
&self,
_input_type: InputMethodType,
_text: Option<String>,
_bounds: DeviceIntRect,
) {
if let Some(keyboard) = self.keyboard.0 {
keyboard(self.app, true)
}
}
fn on_ime_hide(&self) {
if let Some(keyboard) = self.keyboard.0 {
keyboard(self.app, false)
}
}
fn get_clipboard_contents(&self) -> Option<String> {
None
}
fn set_clipboard_contents(&self, _contents: String) {}
fn on_devtools_started(&self, port: Result<u16, ()>) {
match port {
Ok(p) => info!("Devtools Server running on port {}", p),
Err(()) => error!("Error running Devtools server"),
}
}
}
pub struct ServoInstance {
scroll_state: ScrollState,
scroll_scale: Scale<f32, DevicePixel, LayoutPixel>,
shut_down_complete: Rc<Cell<bool>>,
}
#[derive(Clone, Copy)]
enum ScrollState {
TriggerUp,
TriggerDown(DevicePoint),
TriggerDragging(DevicePoint, DevicePoint),
}
struct EventLoopWakerInstance;
impl EventLoopWaker for EventLoopWakerInstance {
fn clone_box(&self) -> Box<dyn EventLoopWaker> {
Box::new(EventLoopWakerInstance)
}
fn wake(&self) {}
}
impl log::Log for MLLogger {
fn enabled(&self, metadata: &log::Metadata) -> bool {
metadata.level() <= LOG_LEVEL
}
fn log(&self, record: &log::Record) {
if let Some(log) = self.0 {
let lvl = match record.level() {
log::Level::Error => MLLogLevel::Error,
log::Level::Warn => MLLogLevel::Warning,
log::Level::Info => MLLogLevel::Info,
log::Level::Debug => MLLogLevel::Debug,
log::Level::Trace => MLLogLevel::Verbose,
};
let mut msg = SmallVec::<[u8; 128]>::new();
write!(msg, "{}\0", record.args()).unwrap();
log(lvl, &msg[0] as *const _ as *const _);
}
}
fn flush(&self) {}
}
fn redirect_stdout_to_log(logger: MLLogger) {
let log = match logger.0 {
None => return,
Some(log) => log,
};
// The first step is to redirect stdout and stderr to the logs.
// We redirect stdout and stderr to a custom descriptor.
let mut pfd: [c_int; 2] = [0, 0];
unsafe {
pipe(pfd.as_mut_ptr());
dup2(pfd[1], 1);
dup2(pfd[1], 2);
}
let descriptor = pfd[0];
// Then we spawn a thread whose only job is to read from the other side of the
// pipe and redirect to the logs.
let _detached = thread::spawn(move || {
const BUF_LENGTH: usize = 512;
let mut buf = vec![b'\0' as c_char; BUF_LENGTH];
// Always keep at least one null terminator
const BUF_AVAILABLE: usize = BUF_LENGTH - 1;
let buf = &mut buf[..BUF_AVAILABLE];
let mut cursor = 0_usize;
loop {
let result = {
let read_into = &mut buf[cursor..];
unsafe {
read(
descriptor,
read_into.as_mut_ptr() as *mut _,
read_into.len(),
)
}
};
let end = if result == 0 {
return;
} else if result < 0 {
log(
MLLogLevel::Error,
b"error in log thread; closing\0".as_ptr() as *const _,
);
return;
} else {
result as usize + cursor
};
// Only modify the portion of the buffer that contains real data.
let buf = &mut buf[0..end];
if let Some(last_newline_pos) = buf.iter().rposition(|&c| c == b'\n' as c_char) {
buf[last_newline_pos] = b'\0' as c_char;
log(MLLogLevel::Info, buf.as_ptr());
if last_newline_pos < buf.len() - 1 {
let pos_after_newline = last_newline_pos + 1;
let len_not_logged_yet = buf[pos_after_newline..].len();
for j in 0..len_not_logged_yet as usize {
buf[j] = buf[pos_after_newline + j];
}
cursor = len_not_logged_yet;
} else {
cursor = 0;
}
} else if end == BUF_AVAILABLE {
// No newline found but the buffer is full, flush it anyway.
// `buf.as_ptr()` is null-terminated by BUF_LENGTH being 1 less than BUF_AVAILABLE.
log(MLLogLevel::Info, buf.as_ptr());
cursor = 0;
} else {
cursor = end;
}
}
});
} | let vr_init = if !landscape {
let name = String::from("Magic Leap VR Display");
let (service, heartbeat) = MagicLeapVRService::new(name, ctxt, gl.gl_wrapper.clone())
.expect("Failed to create VR service"); | random_line_split |
tips.rs | /// Utilties for loading remote FROG tips.
use futures::{Future, Stream};
use errors::*;
use hyper::{self, Method, Request};
use hyper::header::ContentType;
use hyper_tls;
use tokio_core::reactor::Core; |
/// A tip, as received from the server. These are the public API fields.
#[allow(dead_code)]
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Tip {
pub number: TipNum,
pub tip: String,
}
/// A croak is normally precisely 50 tips, but serde_json can't handle encoding and decoding
/// fixed-sized arrays, so this contains a vector of tips.
#[derive(Serialize, Deserialize, Debug)]
pub struct Croak {
pub tips: Vec<Tip>,
}
/// Return a `Result` with a `Croak` of tips.
pub fn croak() -> Result<Croak> {
let mut core = Core::new()
.chain_err(|| "Cannot initialize connection pool")?;
let handle = core.handle();
let client = hyper::Client::configure()
.connector(hyper_tls::HttpsConnector::new(1, &handle)
.chain_err(|| "Cannot initialze TLS")?)
.build(&handle);
let uri = "https://frog.tips/api/1/tips/"
.parse()
.chain_err(|| "Cannot parse FROG.TIPS URL")?;
let mut req = Request::new(Method::Get, uri);
req.headers_mut().set(ContentType::json());
let get_croak = client.request(req).and_then(|res| {
res.body().concat2().and_then(move |body| {
let croak: Croak = serde_json::from_slice(&body)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(croak)
})
});
core.run(get_croak).chain_err(|| "Cannot make request")
} | use serde_json;
use std::io;
/// A tip number, as received from the server. I doubt we'll overflow.
type TipNum = u64; | random_line_split |
tips.rs | /// Utilties for loading remote FROG tips.
use futures::{Future, Stream};
use errors::*;
use hyper::{self, Method, Request};
use hyper::header::ContentType;
use hyper_tls;
use tokio_core::reactor::Core;
use serde_json;
use std::io;
/// A tip number, as received from the server. I doubt we'll overflow.
type TipNum = u64;
/// A tip, as received from the server. These are the public API fields.
#[allow(dead_code)]
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct | {
pub number: TipNum,
pub tip: String,
}
/// A croak is normally precisely 50 tips, but serde_json can't handle encoding and decoding
/// fixed-sized arrays, so this contains a vector of tips.
#[derive(Serialize, Deserialize, Debug)]
pub struct Croak {
pub tips: Vec<Tip>,
}
/// Return a `Result` with a `Croak` of tips.
pub fn croak() -> Result<Croak> {
let mut core = Core::new()
.chain_err(|| "Cannot initialize connection pool")?;
let handle = core.handle();
let client = hyper::Client::configure()
.connector(hyper_tls::HttpsConnector::new(1, &handle)
.chain_err(|| "Cannot initialze TLS")?)
.build(&handle);
let uri = "https://frog.tips/api/1/tips/"
.parse()
.chain_err(|| "Cannot parse FROG.TIPS URL")?;
let mut req = Request::new(Method::Get, uri);
req.headers_mut().set(ContentType::json());
let get_croak = client.request(req).and_then(|res| {
res.body().concat2().and_then(move |body| {
let croak: Croak = serde_json::from_slice(&body)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
Ok(croak)
})
});
core.run(get_croak).chain_err(|| "Cannot make request")
}
| Tip | identifier_name |
block_sync.rs | // Copyright 2015-2017 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/>.
///
/// Blockchain downloader
///
use util::*;
use rlp::*;
use ethcore::views::{BlockView};
use ethcore::header::{BlockNumber, Header as BlockHeader};
use ethcore::client::{BlockStatus, BlockId, BlockImportError};
use ethcore::block::Block;
use ethcore::error::{ImportError, BlockError};
use sync_io::SyncIo;
use blocks::BlockCollection;
const MAX_HEADERS_TO_REQUEST: usize = 128;
const MAX_BODIES_TO_REQUEST: usize = 64;
const MAX_RECEPITS_TO_REQUEST: usize = 128;
const SUBCHAIN_SIZE: u64 = 256;
const MAX_ROUND_PARENTS: usize = 16;
const MAX_PARALLEL_SUBCHAIN_DOWNLOAD: usize = 5;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
/// Downloader state
pub enum State {
/// No active downloads.
Idle,
/// Downloading subchain heads
ChainHead,
/// Downloading blocks
Blocks,
/// Download is complete
Complete,
}
/// Data that needs to be requested from a peer.
pub enum BlockRequest {
Headers {
start: H256,
count: u64,
skip: u64,
},
Bodies {
hashes: Vec<H256>,
},
Receipts {
hashes: Vec<H256>,
},
}
/// Indicates sync action
pub enum DownloadAction {
/// Do nothing
None,
/// Reset downloads for all peers
Reset
}
#[derive(Eq, PartialEq, Debug)]
pub enum BlockDownloaderImportError {
/// Imported data is rejected as invalid.
Invalid,
/// Imported data is valid but rejected cause the downloader does not need it.
Useless,
}
/// Block downloader strategy.
/// Manages state and block data for a block download process.
pub struct BlockDownloader {
/// Downloader state
state: State,
/// Highest block number seen
highest_block: Option<BlockNumber>,
/// Downloaded blocks, holds `H`, `B` and `S`
blocks: BlockCollection,
/// Last impoted block number
last_imported_block: BlockNumber,
/// Last impoted block hash
last_imported_hash: H256,
/// Number of blocks imported this round
imported_this_round: Option<usize>,
/// Block number the last round started with.
last_round_start: BlockNumber,
last_round_start_hash: H256,
/// Block parents imported this round (hash, parent)
round_parents: VecDeque<(H256, H256)>,
/// Do we need to download block recetips.
download_receipts: bool,
/// Sync up to the block with this hash.
target_hash: Option<H256>,
/// Probing range for seeking common best block.
retract_step: u64,
/// Whether reorg should be limited.
limit_reorg: bool,
}
impl BlockDownloader {
/// Create a new instance of syncing strategy. This won't reorganize to before the
/// last kept state.
pub fn new(sync_receipts: bool, start_hash: &H256, start_number: BlockNumber) -> Self {
BlockDownloader {
state: State::Idle,
highest_block: None,
last_imported_block: start_number,
last_imported_hash: start_hash.clone(),
last_round_start: start_number,
last_round_start_hash: start_hash.clone(),
blocks: BlockCollection::new(sync_receipts),
imported_this_round: None,
round_parents: VecDeque::new(),
download_receipts: sync_receipts,
target_hash: None,
retract_step: 1,
limit_reorg: true,
}
}
/// Create a new instance of sync with unlimited reorg allowed.
pub fn with_unlimited_reorg(sync_receipts: bool, start_hash: &H256, start_number: BlockNumber) -> Self {
BlockDownloader {
state: State::Idle,
highest_block: None,
last_imported_block: start_number,
last_imported_hash: start_hash.clone(),
last_round_start: start_number,
last_round_start_hash: start_hash.clone(),
blocks: BlockCollection::new(sync_receipts),
imported_this_round: None,
round_parents: VecDeque::new(),
download_receipts: sync_receipts,
target_hash: None,
retract_step: 1,
limit_reorg: false,
}
}
/// Reset sync. Clear all local downloaded data.
pub fn reset(&mut self) {
self.blocks.clear();
self.state = State::Idle;
}
/// Mark a block as known in the chain
pub fn mark_as_known(&mut self, hash: &H256, number: BlockNumber) {
if number >= self.last_imported_block + 1 {
self.last_imported_block = number;
self.last_imported_hash = hash.clone();
self.imported_this_round = Some(self.imported_this_round.unwrap_or(0) + 1);
self.last_round_start = number;
self.last_round_start_hash = hash.clone();
}
}
/// Check if download is complete
pub fn is_complete(&self) -> bool {
self.state == State::Complete
}
/// Check if particular block hash is being downloaded
pub fn is_downloading(&self, hash: &H256) -> bool {
self.blocks.is_downloading(hash)
}
/// Set starting sync block
pub fn set_target(&mut self, hash: &H256) {
self.target_hash = Some(hash.clone());
}
/// Unmark header as being downloaded.
pub fn clear_header_download(&mut self, hash: &H256) {
self.blocks.clear_header_download(hash)
}
/// Unmark block body as being downloaded.
pub fn clear_body_download(&mut self, hashes: &[H256]) {
self.blocks.clear_body_download(hashes)
}
/// Unmark block receipt as being downloaded.
pub fn clear_receipt_download(&mut self, hashes: &[H256]) {
self.blocks.clear_receipt_download(hashes)
}
/// Reset collection for a new sync round with given subchain block hashes.
pub fn reset_to(&mut self, hashes: Vec<H256>) {
self.reset();
self.blocks.reset_to(hashes);
self.state = State::Blocks;
}
/// Returns used heap memory size.
pub fn heap_size(&self) -> usize {
self.blocks.heap_size() + self.round_parents.heap_size_of_children()
}
/// Returns best imported block number.
pub fn last_imported_block_number(&self) -> BlockNumber {
self.last_imported_block
}
/// Add new block headers.
pub fn import_headers(&mut self, io: &mut SyncIo, r: &UntrustedRlp, expected_hash: Option<H256>) -> Result<DownloadAction, BlockDownloaderImportError> {
let item_count = r.item_count();
if self.state == State::Idle {
trace!(target: "sync", "Ignored unexpected block headers");
return Ok(DownloadAction::None)
}
if item_count == 0 && (self.state == State::Blocks) {
return Err(BlockDownloaderImportError::Invalid);
}
let mut headers = Vec::new();
let mut hashes = Vec::new();
let mut valid_response = item_count == 0; //empty response is valid
let mut any_known = false;
for i in 0..item_count {
let info: BlockHeader = r.val_at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block header RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
let number = BlockNumber::from(info.number());
// Check if any of the headers matches the hash we requested
if!valid_response {
if let Some(expected) = expected_hash {
valid_response = expected == info.hash()
}
}
any_known = any_known || self.blocks.contains_head(&info.hash());
if self.blocks.contains(&info.hash()) {
trace!(target: "sync", "Skipping existing block header {} ({:?})", number, info.hash());
continue;
}
if self.highest_block.as_ref().map_or(true, |n| number > *n) {
self.highest_block = Some(number);
}
let hash = info.hash();
let hdr = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block header RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
match io.chain().block_status(BlockId::Hash(hash.clone())) {
BlockStatus::InChain | BlockStatus::Queued => {
match self.state {
State::Blocks => trace!(target: "sync", "Header already in chain {} ({})", number, hash),
_ => trace!(target: "sync", "Header already in chain {} ({}), state = {:?}", number, hash, self.state),
}
headers.push(hdr.as_raw().to_vec());
hashes.push(hash);
},
BlockStatus::Bad => {
return Err(BlockDownloaderImportError::Invalid);
},
BlockStatus::Unknown => {
headers.push(hdr.as_raw().to_vec());
hashes.push(hash);
}
}
}
// Disable the peer for this syncing round if it gives invalid chain
if!valid_response {
trace!(target: "sync", "Invalid headers response");
return Err(BlockDownloaderImportError::Invalid);
}
match self.state {
State::ChainHead => {
if!headers.is_empty() {
// TODO: validate heads better. E.g. check that there is enough distance between blocks.
trace!(target: "sync", "Received {} subchain heads, proceeding to download", headers.len());
self.blocks.reset_to(hashes);
self.state = State::Blocks;
return Ok(DownloadAction::Reset);
} else {
let best = io.chain().chain_info().best_block_number;
let oldest_reorg = io.chain().pruning_info().earliest_state;
let last = self.last_imported_block;
if self.limit_reorg && best > last && (last == 0 || last < oldest_reorg) {
trace!(target: "sync", "No common block, disabling peer");
return Err(BlockDownloaderImportError::Invalid);
}
}
},
State::Blocks => {
let count = headers.len();
// At least one of the heades must advance the subchain. Otherwise they are all useless.
if count == 0 ||!any_known |
self.blocks.insert_headers(headers);
trace!(target: "sync", "Inserted {} headers", count);
},
_ => trace!(target: "sync", "Unexpected headers({})", headers.len()),
}
Ok(DownloadAction::None)
}
/// Called by peer once it has new block bodies
pub fn import_bodies(&mut self, _io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), BlockDownloaderImportError> {
let item_count = r.item_count();
if item_count == 0 {
return Err(BlockDownloaderImportError::Useless);
}
else if self.state!= State::Blocks {
trace!(target: "sync", "Ignored unexpected block bodies");
}
else {
let mut bodies = Vec::with_capacity(item_count);
for i in 0..item_count {
let body = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block boides RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
bodies.push(body.as_raw().to_vec());
}
if self.blocks.insert_bodies(bodies)!= item_count {
trace!(target: "sync", "Deactivating peer for giving invalid block bodies");
return Err(BlockDownloaderImportError::Invalid);
}
}
Ok(())
}
/// Called by peer once it has new block bodies
pub fn import_receipts(&mut self, _io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), BlockDownloaderImportError> {
let item_count = r.item_count();
if item_count == 0 {
return Err(BlockDownloaderImportError::Useless);
}
else if self.state!= State::Blocks {
trace!(target: "sync", "Ignored unexpected block receipts");
}
else {
let mut receipts = Vec::with_capacity(item_count);
for i in 0..item_count {
let receipt = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block receipts RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
receipts.push(receipt.as_raw().to_vec());
}
if self.blocks.insert_receipts(receipts)!= item_count {
trace!(target: "sync", "Deactivating peer for giving invalid block receipts");
return Err(BlockDownloaderImportError::Invalid);
}
}
Ok(())
}
fn start_sync_round(&mut self, io: &mut SyncIo) {
self.state = State::ChainHead;
trace!(target: "sync", "Starting round (last imported count = {:?}, last started = {}, block = {:?}", self.imported_this_round, self.last_round_start, self.last_imported_block);
// Check if need to retract to find the common block. The problem is that the peers still return headers by hash even
// from the non-canonical part of the tree. So we also retract if nothing has been imported last round.
let start = self.last_round_start;
let start_hash = self.last_round_start_hash;
match self.imported_this_round {
Some(n) if n == 0 && start > 0 => {
// nothing was imported last round, step back to a previous block
// search parent in last round known parents first
if let Some(&(_, p)) = self.round_parents.iter().find(|&&(h, _)| h == start_hash) {
self.last_imported_block = start - 1;
self.last_imported_hash = p.clone();
trace!(target: "sync", "Searching common header from the last round {} ({})", self.last_imported_block, self.last_imported_hash);
} else {
let best = io.chain().chain_info().best_block_number;
let oldest_reorg = io.chain().pruning_info().earliest_state;
if self.limit_reorg && best > start && start < oldest_reorg {
debug!(target: "sync", "Could not revert to previous ancient block, last: {} ({})", start, start_hash);
self.reset();
} else {
let n = start - min(self.retract_step, start);
self.retract_step *= 2;
match io.chain().block_hash(BlockId::Number(n)) {
Some(h) => {
self.last_imported_block = n;
self.last_imported_hash = h;
trace!(target: "sync", "Searching common header in the blockchain {} ({})", start, self.last_imported_hash);
}
None => {
debug!(target: "sync", "Could not revert to previous block, last: {} ({})", start, self.last_imported_hash);
self.reset();
}
}
}
}
},
_ => {
self.retract_step = 1;
},
}
self.last_round_start = self.last_imported_block;
self.last_round_start_hash = self.last_imported_hash;
self.imported_this_round = None;
}
/// Find some headers or blocks to download for a peer.
pub fn request_blocks(&mut self, io: &mut SyncIo, num_active_peers: usize) -> Option<BlockRequest> {
match self.state {
State::Idle => {
self.start_sync_round(io);
if self.state == State::ChainHead {
return self.request_blocks(io, num_active_peers);
}
},
State::ChainHead => {
if num_active_peers < MAX_PARALLEL_SUBCHAIN_DOWNLOAD {
// Request subchain headers
trace!(target: "sync", "Starting sync with better chain");
// Request MAX_HEADERS_TO_REQUEST - 2 headers apart so that
// MAX_HEADERS_TO_REQUEST would include headers for neighbouring subchains
return Some(BlockRequest::Headers {
start: self.last_imported_hash.clone(),
count: SUBCHAIN_SIZE,
skip: (MAX_HEADERS_TO_REQUEST - 2) as u64,
});
}
},
State::Blocks => {
// check to see if we need to download any block bodies first
let needed_bodies = self.blocks.needed_bodies(MAX_BODIES_TO_REQUEST, false);
if!needed_bodies.is_empty() {
return Some(BlockRequest::Bodies {
hashes: needed_bodies,
});
}
if self.download_receipts {
let needed_receipts = self.blocks.needed_receipts(MAX_RECEPITS_TO_REQUEST, false);
if!needed_receipts.is_empty() {
return Some(BlockRequest::Receipts {
hashes: needed_receipts,
});
}
}
// find subchain to download
if let Some((h, count)) = self.blocks.needed_headers(MAX_HEADERS_TO_REQUEST, false) {
return Some(BlockRequest::Headers {
start: h,
count: count as u64,
skip: 0,
});
}
},
State::Complete => (),
}
None
}
/// Checks if there are blocks fully downloaded that can be imported into the blockchain and does the import.
pub fn collect_blocks(&mut self, io: &mut SyncIo, allow_out_of_order: bool) -> Result<(), BlockDownloaderImportError> {
let mut bad = false;
let mut imported = HashSet::new();
let blocks = self.blocks.drain();
let count = blocks.len();
for block_and_receipts in blocks {
let block = block_and_receipts.block;
let receipts = block_and_receipts.receipts;
let (h, number, parent) = {
let header = BlockView::new(&block).header_view();
(header.sha3(), header.number(), header.parent_hash())
};
// Perform basic block verification
if!Block::is_good(&block) {
debug!(target: "sync", "Bad block rlp {:?} : {:?}", h, block);
bad = true;
break;
}
if self.target_hash.as_ref().map_or(false, |t| t == &h) {
self.state = State::Complete;
trace!(target: "sync", "Sync target reached");
return Ok(());
}
let result = if let Some(receipts) = receipts {
io.chain().import_block_with_receipts(block, receipts)
} else {
io.chain().import_block(block)
};
match result {
Err(BlockImportError::Import(ImportError::AlreadyInChain)) => {
trace!(target: "sync", "Block already in chain {:?}", h);
self.block_imported(&h, number, &parent);
},
Err(BlockImportError::Import(ImportError::AlreadyQueued)) => {
trace!(target: "sync", "Block already queued {:?}", h);
self.block_imported(&h, number, &parent);
},
Ok(_) => {
trace!(target: "sync", "Block queued {:?}", h);
imported.insert(h.clone());
self.block_imported(&h, number, &parent);
},
Err(BlockImportError::Block(BlockError::UnknownParent(_))) if allow_out_of_order => {
break;
},
Err(BlockImportError::Block(BlockError::UnknownParent(_))) => {
trace!(target: "sync", "Unknown new block parent, restarting sync");
break;
},
Err(e) => {
debug!(target: "sync", "Bad block {:?} : {:?}", h, e);
bad = true;
break;
}
}
}
trace!(target: "sync", "Imported {} of {}", imported.len(), count);
self.imported_this_round = Some(self.imported_this_round.unwrap_or(0) + imported.len());
if bad {
return Err(BlockDownloaderImportError::Invalid);
}
if self.blocks.is_empty() {
// complete sync round
trace!(target: "sync", "Sync round complete");
self.reset();
}
Ok(())
}
fn block_imported(&mut self, hash: &H256, number: BlockNumber, parent: &H256) {
self.last_imported_block = number;
self.last_imported_hash = hash.clone();
self.round_parents.push_back((hash.clone(), parent.clone()));
if self.round_parents.len() > MAX_ROUND_PARENTS {
self.round_parents.pop_front();
}
}
}
//TODO: module tests
| {
trace!(target: "sync", "No useful headers");
return Err(BlockDownloaderImportError::Useless);
} | conditional_block |
block_sync.rs | // Copyright 2015-2017 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/>.
///
/// Blockchain downloader
///
use util::*;
use rlp::*;
use ethcore::views::{BlockView};
use ethcore::header::{BlockNumber, Header as BlockHeader};
use ethcore::client::{BlockStatus, BlockId, BlockImportError};
use ethcore::block::Block;
use ethcore::error::{ImportError, BlockError};
use sync_io::SyncIo;
use blocks::BlockCollection;
const MAX_HEADERS_TO_REQUEST: usize = 128;
const MAX_BODIES_TO_REQUEST: usize = 64;
const MAX_RECEPITS_TO_REQUEST: usize = 128;
const SUBCHAIN_SIZE: u64 = 256;
const MAX_ROUND_PARENTS: usize = 16;
const MAX_PARALLEL_SUBCHAIN_DOWNLOAD: usize = 5;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
/// Downloader state
pub enum State {
/// No active downloads.
Idle,
/// Downloading subchain heads
ChainHead,
/// Downloading blocks
Blocks,
/// Download is complete
Complete,
}
/// Data that needs to be requested from a peer.
pub enum BlockRequest {
Headers {
start: H256,
count: u64,
skip: u64,
},
Bodies {
hashes: Vec<H256>,
},
Receipts {
hashes: Vec<H256>,
},
}
/// Indicates sync action
pub enum DownloadAction {
/// Do nothing
None,
/// Reset downloads for all peers
Reset
}
#[derive(Eq, PartialEq, Debug)]
pub enum BlockDownloaderImportError {
/// Imported data is rejected as invalid.
Invalid,
/// Imported data is valid but rejected cause the downloader does not need it.
Useless,
}
/// Block downloader strategy.
/// Manages state and block data for a block download process.
pub struct BlockDownloader {
/// Downloader state
state: State,
/// Highest block number seen
highest_block: Option<BlockNumber>,
/// Downloaded blocks, holds `H`, `B` and `S`
blocks: BlockCollection,
/// Last impoted block number
last_imported_block: BlockNumber,
/// Last impoted block hash
last_imported_hash: H256,
/// Number of blocks imported this round
imported_this_round: Option<usize>,
/// Block number the last round started with.
last_round_start: BlockNumber,
last_round_start_hash: H256,
/// Block parents imported this round (hash, parent)
round_parents: VecDeque<(H256, H256)>,
/// Do we need to download block recetips.
download_receipts: bool,
/// Sync up to the block with this hash.
target_hash: Option<H256>,
/// Probing range for seeking common best block.
retract_step: u64,
/// Whether reorg should be limited.
limit_reorg: bool,
}
impl BlockDownloader {
/// Create a new instance of syncing strategy. This won't reorganize to before the
/// last kept state.
pub fn new(sync_receipts: bool, start_hash: &H256, start_number: BlockNumber) -> Self {
BlockDownloader {
state: State::Idle,
highest_block: None,
last_imported_block: start_number,
last_imported_hash: start_hash.clone(),
last_round_start: start_number,
last_round_start_hash: start_hash.clone(),
blocks: BlockCollection::new(sync_receipts),
imported_this_round: None,
round_parents: VecDeque::new(),
download_receipts: sync_receipts,
target_hash: None,
retract_step: 1,
limit_reorg: true,
}
}
/// Create a new instance of sync with unlimited reorg allowed.
pub fn with_unlimited_reorg(sync_receipts: bool, start_hash: &H256, start_number: BlockNumber) -> Self {
BlockDownloader {
state: State::Idle,
highest_block: None,
last_imported_block: start_number,
last_imported_hash: start_hash.clone(),
last_round_start: start_number,
last_round_start_hash: start_hash.clone(),
blocks: BlockCollection::new(sync_receipts),
imported_this_round: None,
round_parents: VecDeque::new(),
download_receipts: sync_receipts,
target_hash: None,
retract_step: 1,
limit_reorg: false,
}
}
/// Reset sync. Clear all local downloaded data.
pub fn reset(&mut self) {
self.blocks.clear();
self.state = State::Idle;
}
/// Mark a block as known in the chain
pub fn mark_as_known(&mut self, hash: &H256, number: BlockNumber) {
if number >= self.last_imported_block + 1 {
self.last_imported_block = number;
self.last_imported_hash = hash.clone();
self.imported_this_round = Some(self.imported_this_round.unwrap_or(0) + 1);
self.last_round_start = number;
self.last_round_start_hash = hash.clone();
}
}
/// Check if download is complete
pub fn is_complete(&self) -> bool {
self.state == State::Complete
}
/// Check if particular block hash is being downloaded
pub fn is_downloading(&self, hash: &H256) -> bool {
self.blocks.is_downloading(hash)
}
/// Set starting sync block
pub fn set_target(&mut self, hash: &H256) {
self.target_hash = Some(hash.clone());
}
/// Unmark header as being downloaded.
pub fn clear_header_download(&mut self, hash: &H256) {
self.blocks.clear_header_download(hash)
}
/// Unmark block body as being downloaded.
pub fn clear_body_download(&mut self, hashes: &[H256]) {
self.blocks.clear_body_download(hashes)
}
/// Unmark block receipt as being downloaded.
pub fn clear_receipt_download(&mut self, hashes: &[H256]) {
self.blocks.clear_receipt_download(hashes)
}
/// Reset collection for a new sync round with given subchain block hashes.
pub fn reset_to(&mut self, hashes: Vec<H256>) {
self.reset();
self.blocks.reset_to(hashes);
self.state = State::Blocks;
}
/// Returns used heap memory size.
pub fn heap_size(&self) -> usize {
self.blocks.heap_size() + self.round_parents.heap_size_of_children()
}
/// Returns best imported block number.
pub fn last_imported_block_number(&self) -> BlockNumber {
self.last_imported_block
}
/// Add new block headers.
pub fn import_headers(&mut self, io: &mut SyncIo, r: &UntrustedRlp, expected_hash: Option<H256>) -> Result<DownloadAction, BlockDownloaderImportError> {
let item_count = r.item_count();
if self.state == State::Idle {
trace!(target: "sync", "Ignored unexpected block headers");
return Ok(DownloadAction::None)
}
if item_count == 0 && (self.state == State::Blocks) {
return Err(BlockDownloaderImportError::Invalid);
}
let mut headers = Vec::new();
let mut hashes = Vec::new();
let mut valid_response = item_count == 0; //empty response is valid
let mut any_known = false;
for i in 0..item_count {
let info: BlockHeader = r.val_at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block header RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
let number = BlockNumber::from(info.number());
// Check if any of the headers matches the hash we requested
if!valid_response {
if let Some(expected) = expected_hash {
valid_response = expected == info.hash()
}
}
any_known = any_known || self.blocks.contains_head(&info.hash());
if self.blocks.contains(&info.hash()) {
trace!(target: "sync", "Skipping existing block header {} ({:?})", number, info.hash());
continue;
}
if self.highest_block.as_ref().map_or(true, |n| number > *n) {
self.highest_block = Some(number);
}
let hash = info.hash();
let hdr = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block header RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
match io.chain().block_status(BlockId::Hash(hash.clone())) {
BlockStatus::InChain | BlockStatus::Queued => {
match self.state {
State::Blocks => trace!(target: "sync", "Header already in chain {} ({})", number, hash),
_ => trace!(target: "sync", "Header already in chain {} ({}), state = {:?}", number, hash, self.state),
}
headers.push(hdr.as_raw().to_vec());
hashes.push(hash);
},
BlockStatus::Bad => {
return Err(BlockDownloaderImportError::Invalid);
},
BlockStatus::Unknown => {
headers.push(hdr.as_raw().to_vec());
hashes.push(hash);
}
}
}
// Disable the peer for this syncing round if it gives invalid chain
if!valid_response {
trace!(target: "sync", "Invalid headers response");
return Err(BlockDownloaderImportError::Invalid);
}
match self.state {
State::ChainHead => {
if!headers.is_empty() {
// TODO: validate heads better. E.g. check that there is enough distance between blocks.
trace!(target: "sync", "Received {} subchain heads, proceeding to download", headers.len());
self.blocks.reset_to(hashes);
self.state = State::Blocks;
return Ok(DownloadAction::Reset);
} else {
let best = io.chain().chain_info().best_block_number;
let oldest_reorg = io.chain().pruning_info().earliest_state;
let last = self.last_imported_block;
if self.limit_reorg && best > last && (last == 0 || last < oldest_reorg) {
trace!(target: "sync", "No common block, disabling peer");
return Err(BlockDownloaderImportError::Invalid);
}
}
},
State::Blocks => {
let count = headers.len();
// At least one of the heades must advance the subchain. Otherwise they are all useless.
if count == 0 ||!any_known {
trace!(target: "sync", "No useful headers");
return Err(BlockDownloaderImportError::Useless);
}
self.blocks.insert_headers(headers);
trace!(target: "sync", "Inserted {} headers", count);
},
_ => trace!(target: "sync", "Unexpected headers({})", headers.len()),
}
Ok(DownloadAction::None)
}
/// Called by peer once it has new block bodies
pub fn import_bodies(&mut self, _io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), BlockDownloaderImportError> {
let item_count = r.item_count();
if item_count == 0 {
return Err(BlockDownloaderImportError::Useless);
}
else if self.state!= State::Blocks {
trace!(target: "sync", "Ignored unexpected block bodies");
}
else {
let mut bodies = Vec::with_capacity(item_count);
for i in 0..item_count {
let body = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block boides RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
bodies.push(body.as_raw().to_vec());
}
if self.blocks.insert_bodies(bodies)!= item_count {
trace!(target: "sync", "Deactivating peer for giving invalid block bodies");
return Err(BlockDownloaderImportError::Invalid);
}
}
Ok(())
}
/// Called by peer once it has new block bodies
pub fn import_receipts(&mut self, _io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), BlockDownloaderImportError> {
let item_count = r.item_count();
if item_count == 0 {
return Err(BlockDownloaderImportError::Useless);
}
else if self.state!= State::Blocks {
trace!(target: "sync", "Ignored unexpected block receipts");
}
else {
let mut receipts = Vec::with_capacity(item_count);
for i in 0..item_count {
let receipt = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block receipts RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
receipts.push(receipt.as_raw().to_vec());
}
if self.blocks.insert_receipts(receipts)!= item_count {
trace!(target: "sync", "Deactivating peer for giving invalid block receipts");
return Err(BlockDownloaderImportError::Invalid);
}
}
Ok(())
}
fn start_sync_round(&mut self, io: &mut SyncIo) {
self.state = State::ChainHead;
trace!(target: "sync", "Starting round (last imported count = {:?}, last started = {}, block = {:?}", self.imported_this_round, self.last_round_start, self.last_imported_block);
// Check if need to retract to find the common block. The problem is that the peers still return headers by hash even
// from the non-canonical part of the tree. So we also retract if nothing has been imported last round.
let start = self.last_round_start;
let start_hash = self.last_round_start_hash;
match self.imported_this_round {
Some(n) if n == 0 && start > 0 => {
// nothing was imported last round, step back to a previous block
// search parent in last round known parents first
if let Some(&(_, p)) = self.round_parents.iter().find(|&&(h, _)| h == start_hash) {
self.last_imported_block = start - 1;
self.last_imported_hash = p.clone();
trace!(target: "sync", "Searching common header from the last round {} ({})", self.last_imported_block, self.last_imported_hash);
} else {
let best = io.chain().chain_info().best_block_number;
let oldest_reorg = io.chain().pruning_info().earliest_state;
if self.limit_reorg && best > start && start < oldest_reorg {
debug!(target: "sync", "Could not revert to previous ancient block, last: {} ({})", start, start_hash);
self.reset();
} else {
let n = start - min(self.retract_step, start);
self.retract_step *= 2;
match io.chain().block_hash(BlockId::Number(n)) {
Some(h) => {
self.last_imported_block = n;
self.last_imported_hash = h;
trace!(target: "sync", "Searching common header in the blockchain {} ({})", start, self.last_imported_hash);
}
None => {
debug!(target: "sync", "Could not revert to previous block, last: {} ({})", start, self.last_imported_hash);
self.reset();
}
}
}
}
},
_ => {
self.retract_step = 1;
},
}
self.last_round_start = self.last_imported_block;
self.last_round_start_hash = self.last_imported_hash;
self.imported_this_round = None;
}
/// Find some headers or blocks to download for a peer.
pub fn request_blocks(&mut self, io: &mut SyncIo, num_active_peers: usize) -> Option<BlockRequest> {
match self.state {
State::Idle => {
self.start_sync_round(io);
if self.state == State::ChainHead {
return self.request_blocks(io, num_active_peers);
}
},
State::ChainHead => {
if num_active_peers < MAX_PARALLEL_SUBCHAIN_DOWNLOAD {
// Request subchain headers
trace!(target: "sync", "Starting sync with better chain");
// Request MAX_HEADERS_TO_REQUEST - 2 headers apart so that
// MAX_HEADERS_TO_REQUEST would include headers for neighbouring subchains
return Some(BlockRequest::Headers {
start: self.last_imported_hash.clone(),
count: SUBCHAIN_SIZE,
skip: (MAX_HEADERS_TO_REQUEST - 2) as u64,
});
}
},
State::Blocks => {
// check to see if we need to download any block bodies first
let needed_bodies = self.blocks.needed_bodies(MAX_BODIES_TO_REQUEST, false);
if!needed_bodies.is_empty() {
return Some(BlockRequest::Bodies {
hashes: needed_bodies,
});
}
if self.download_receipts {
let needed_receipts = self.blocks.needed_receipts(MAX_RECEPITS_TO_REQUEST, false);
if!needed_receipts.is_empty() {
return Some(BlockRequest::Receipts {
hashes: needed_receipts,
});
}
}
// find subchain to download
if let Some((h, count)) = self.blocks.needed_headers(MAX_HEADERS_TO_REQUEST, false) {
return Some(BlockRequest::Headers {
start: h,
count: count as u64,
skip: 0,
});
}
},
State::Complete => (),
}
None
}
/// Checks if there are blocks fully downloaded that can be imported into the blockchain and does the import.
pub fn collect_blocks(&mut self, io: &mut SyncIo, allow_out_of_order: bool) -> Result<(), BlockDownloaderImportError> {
let mut bad = false;
let mut imported = HashSet::new();
let blocks = self.blocks.drain();
let count = blocks.len();
for block_and_receipts in blocks { | };
// Perform basic block verification
if!Block::is_good(&block) {
debug!(target: "sync", "Bad block rlp {:?} : {:?}", h, block);
bad = true;
break;
}
if self.target_hash.as_ref().map_or(false, |t| t == &h) {
self.state = State::Complete;
trace!(target: "sync", "Sync target reached");
return Ok(());
}
let result = if let Some(receipts) = receipts {
io.chain().import_block_with_receipts(block, receipts)
} else {
io.chain().import_block(block)
};
match result {
Err(BlockImportError::Import(ImportError::AlreadyInChain)) => {
trace!(target: "sync", "Block already in chain {:?}", h);
self.block_imported(&h, number, &parent);
},
Err(BlockImportError::Import(ImportError::AlreadyQueued)) => {
trace!(target: "sync", "Block already queued {:?}", h);
self.block_imported(&h, number, &parent);
},
Ok(_) => {
trace!(target: "sync", "Block queued {:?}", h);
imported.insert(h.clone());
self.block_imported(&h, number, &parent);
},
Err(BlockImportError::Block(BlockError::UnknownParent(_))) if allow_out_of_order => {
break;
},
Err(BlockImportError::Block(BlockError::UnknownParent(_))) => {
trace!(target: "sync", "Unknown new block parent, restarting sync");
break;
},
Err(e) => {
debug!(target: "sync", "Bad block {:?} : {:?}", h, e);
bad = true;
break;
}
}
}
trace!(target: "sync", "Imported {} of {}", imported.len(), count);
self.imported_this_round = Some(self.imported_this_round.unwrap_or(0) + imported.len());
if bad {
return Err(BlockDownloaderImportError::Invalid);
}
if self.blocks.is_empty() {
// complete sync round
trace!(target: "sync", "Sync round complete");
self.reset();
}
Ok(())
}
fn block_imported(&mut self, hash: &H256, number: BlockNumber, parent: &H256) {
self.last_imported_block = number;
self.last_imported_hash = hash.clone();
self.round_parents.push_back((hash.clone(), parent.clone()));
if self.round_parents.len() > MAX_ROUND_PARENTS {
self.round_parents.pop_front();
}
}
}
//TODO: module tests | let block = block_and_receipts.block;
let receipts = block_and_receipts.receipts;
let (h, number, parent) = {
let header = BlockView::new(&block).header_view();
(header.sha3(), header.number(), header.parent_hash()) | random_line_split |
block_sync.rs | // Copyright 2015-2017 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/>.
///
/// Blockchain downloader
///
use util::*;
use rlp::*;
use ethcore::views::{BlockView};
use ethcore::header::{BlockNumber, Header as BlockHeader};
use ethcore::client::{BlockStatus, BlockId, BlockImportError};
use ethcore::block::Block;
use ethcore::error::{ImportError, BlockError};
use sync_io::SyncIo;
use blocks::BlockCollection;
const MAX_HEADERS_TO_REQUEST: usize = 128;
const MAX_BODIES_TO_REQUEST: usize = 64;
const MAX_RECEPITS_TO_REQUEST: usize = 128;
const SUBCHAIN_SIZE: u64 = 256;
const MAX_ROUND_PARENTS: usize = 16;
const MAX_PARALLEL_SUBCHAIN_DOWNLOAD: usize = 5;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
/// Downloader state
pub enum State {
/// No active downloads.
Idle,
/// Downloading subchain heads
ChainHead,
/// Downloading blocks
Blocks,
/// Download is complete
Complete,
}
/// Data that needs to be requested from a peer.
pub enum BlockRequest {
Headers {
start: H256,
count: u64,
skip: u64,
},
Bodies {
hashes: Vec<H256>,
},
Receipts {
hashes: Vec<H256>,
},
}
/// Indicates sync action
pub enum DownloadAction {
/// Do nothing
None,
/// Reset downloads for all peers
Reset
}
#[derive(Eq, PartialEq, Debug)]
pub enum BlockDownloaderImportError {
/// Imported data is rejected as invalid.
Invalid,
/// Imported data is valid but rejected cause the downloader does not need it.
Useless,
}
/// Block downloader strategy.
/// Manages state and block data for a block download process.
pub struct BlockDownloader {
/// Downloader state
state: State,
/// Highest block number seen
highest_block: Option<BlockNumber>,
/// Downloaded blocks, holds `H`, `B` and `S`
blocks: BlockCollection,
/// Last impoted block number
last_imported_block: BlockNumber,
/// Last impoted block hash
last_imported_hash: H256,
/// Number of blocks imported this round
imported_this_round: Option<usize>,
/// Block number the last round started with.
last_round_start: BlockNumber,
last_round_start_hash: H256,
/// Block parents imported this round (hash, parent)
round_parents: VecDeque<(H256, H256)>,
/// Do we need to download block recetips.
download_receipts: bool,
/// Sync up to the block with this hash.
target_hash: Option<H256>,
/// Probing range for seeking common best block.
retract_step: u64,
/// Whether reorg should be limited.
limit_reorg: bool,
}
impl BlockDownloader {
/// Create a new instance of syncing strategy. This won't reorganize to before the
/// last kept state.
pub fn new(sync_receipts: bool, start_hash: &H256, start_number: BlockNumber) -> Self {
BlockDownloader {
state: State::Idle,
highest_block: None,
last_imported_block: start_number,
last_imported_hash: start_hash.clone(),
last_round_start: start_number,
last_round_start_hash: start_hash.clone(),
blocks: BlockCollection::new(sync_receipts),
imported_this_round: None,
round_parents: VecDeque::new(),
download_receipts: sync_receipts,
target_hash: None,
retract_step: 1,
limit_reorg: true,
}
}
/// Create a new instance of sync with unlimited reorg allowed.
pub fn with_unlimited_reorg(sync_receipts: bool, start_hash: &H256, start_number: BlockNumber) -> Self {
BlockDownloader {
state: State::Idle,
highest_block: None,
last_imported_block: start_number,
last_imported_hash: start_hash.clone(),
last_round_start: start_number,
last_round_start_hash: start_hash.clone(),
blocks: BlockCollection::new(sync_receipts),
imported_this_round: None,
round_parents: VecDeque::new(),
download_receipts: sync_receipts,
target_hash: None,
retract_step: 1,
limit_reorg: false,
}
}
/// Reset sync. Clear all local downloaded data.
pub fn reset(&mut self) {
self.blocks.clear();
self.state = State::Idle;
}
/// Mark a block as known in the chain
pub fn mark_as_known(&mut self, hash: &H256, number: BlockNumber) {
if number >= self.last_imported_block + 1 {
self.last_imported_block = number;
self.last_imported_hash = hash.clone();
self.imported_this_round = Some(self.imported_this_round.unwrap_or(0) + 1);
self.last_round_start = number;
self.last_round_start_hash = hash.clone();
}
}
/// Check if download is complete
pub fn is_complete(&self) -> bool {
self.state == State::Complete
}
/// Check if particular block hash is being downloaded
pub fn is_downloading(&self, hash: &H256) -> bool {
self.blocks.is_downloading(hash)
}
/// Set starting sync block
pub fn set_target(&mut self, hash: &H256) {
self.target_hash = Some(hash.clone());
}
/// Unmark header as being downloaded.
pub fn clear_header_download(&mut self, hash: &H256) {
self.blocks.clear_header_download(hash)
}
/// Unmark block body as being downloaded.
pub fn clear_body_download(&mut self, hashes: &[H256]) {
self.blocks.clear_body_download(hashes)
}
/// Unmark block receipt as being downloaded.
pub fn clear_receipt_download(&mut self, hashes: &[H256]) {
self.blocks.clear_receipt_download(hashes)
}
/// Reset collection for a new sync round with given subchain block hashes.
pub fn reset_to(&mut self, hashes: Vec<H256>) {
self.reset();
self.blocks.reset_to(hashes);
self.state = State::Blocks;
}
/// Returns used heap memory size.
pub fn heap_size(&self) -> usize {
self.blocks.heap_size() + self.round_parents.heap_size_of_children()
}
/// Returns best imported block number.
pub fn last_imported_block_number(&self) -> BlockNumber {
self.last_imported_block
}
/// Add new block headers.
pub fn import_headers(&mut self, io: &mut SyncIo, r: &UntrustedRlp, expected_hash: Option<H256>) -> Result<DownloadAction, BlockDownloaderImportError> {
let item_count = r.item_count();
if self.state == State::Idle {
trace!(target: "sync", "Ignored unexpected block headers");
return Ok(DownloadAction::None)
}
if item_count == 0 && (self.state == State::Blocks) {
return Err(BlockDownloaderImportError::Invalid);
}
let mut headers = Vec::new();
let mut hashes = Vec::new();
let mut valid_response = item_count == 0; //empty response is valid
let mut any_known = false;
for i in 0..item_count {
let info: BlockHeader = r.val_at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block header RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
let number = BlockNumber::from(info.number());
// Check if any of the headers matches the hash we requested
if!valid_response {
if let Some(expected) = expected_hash {
valid_response = expected == info.hash()
}
}
any_known = any_known || self.blocks.contains_head(&info.hash());
if self.blocks.contains(&info.hash()) {
trace!(target: "sync", "Skipping existing block header {} ({:?})", number, info.hash());
continue;
}
if self.highest_block.as_ref().map_or(true, |n| number > *n) {
self.highest_block = Some(number);
}
let hash = info.hash();
let hdr = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block header RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
match io.chain().block_status(BlockId::Hash(hash.clone())) {
BlockStatus::InChain | BlockStatus::Queued => {
match self.state {
State::Blocks => trace!(target: "sync", "Header already in chain {} ({})", number, hash),
_ => trace!(target: "sync", "Header already in chain {} ({}), state = {:?}", number, hash, self.state),
}
headers.push(hdr.as_raw().to_vec());
hashes.push(hash);
},
BlockStatus::Bad => {
return Err(BlockDownloaderImportError::Invalid);
},
BlockStatus::Unknown => {
headers.push(hdr.as_raw().to_vec());
hashes.push(hash);
}
}
}
// Disable the peer for this syncing round if it gives invalid chain
if!valid_response {
trace!(target: "sync", "Invalid headers response");
return Err(BlockDownloaderImportError::Invalid);
}
match self.state {
State::ChainHead => {
if!headers.is_empty() {
// TODO: validate heads better. E.g. check that there is enough distance between blocks.
trace!(target: "sync", "Received {} subchain heads, proceeding to download", headers.len());
self.blocks.reset_to(hashes);
self.state = State::Blocks;
return Ok(DownloadAction::Reset);
} else {
let best = io.chain().chain_info().best_block_number;
let oldest_reorg = io.chain().pruning_info().earliest_state;
let last = self.last_imported_block;
if self.limit_reorg && best > last && (last == 0 || last < oldest_reorg) {
trace!(target: "sync", "No common block, disabling peer");
return Err(BlockDownloaderImportError::Invalid);
}
}
},
State::Blocks => {
let count = headers.len();
// At least one of the heades must advance the subchain. Otherwise they are all useless.
if count == 0 ||!any_known {
trace!(target: "sync", "No useful headers");
return Err(BlockDownloaderImportError::Useless);
}
self.blocks.insert_headers(headers);
trace!(target: "sync", "Inserted {} headers", count);
},
_ => trace!(target: "sync", "Unexpected headers({})", headers.len()),
}
Ok(DownloadAction::None)
}
/// Called by peer once it has new block bodies
pub fn import_bodies(&mut self, _io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), BlockDownloaderImportError> {
let item_count = r.item_count();
if item_count == 0 {
return Err(BlockDownloaderImportError::Useless);
}
else if self.state!= State::Blocks {
trace!(target: "sync", "Ignored unexpected block bodies");
}
else {
let mut bodies = Vec::with_capacity(item_count);
for i in 0..item_count {
let body = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block boides RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
bodies.push(body.as_raw().to_vec());
}
if self.blocks.insert_bodies(bodies)!= item_count {
trace!(target: "sync", "Deactivating peer for giving invalid block bodies");
return Err(BlockDownloaderImportError::Invalid);
}
}
Ok(())
}
/// Called by peer once it has new block bodies
pub fn import_receipts(&mut self, _io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), BlockDownloaderImportError> {
let item_count = r.item_count();
if item_count == 0 {
return Err(BlockDownloaderImportError::Useless);
}
else if self.state!= State::Blocks {
trace!(target: "sync", "Ignored unexpected block receipts");
}
else {
let mut receipts = Vec::with_capacity(item_count);
for i in 0..item_count {
let receipt = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block receipts RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
receipts.push(receipt.as_raw().to_vec());
}
if self.blocks.insert_receipts(receipts)!= item_count {
trace!(target: "sync", "Deactivating peer for giving invalid block receipts");
return Err(BlockDownloaderImportError::Invalid);
}
}
Ok(())
}
fn start_sync_round(&mut self, io: &mut SyncIo) | self.reset();
} else {
let n = start - min(self.retract_step, start);
self.retract_step *= 2;
match io.chain().block_hash(BlockId::Number(n)) {
Some(h) => {
self.last_imported_block = n;
self.last_imported_hash = h;
trace!(target: "sync", "Searching common header in the blockchain {} ({})", start, self.last_imported_hash);
}
None => {
debug!(target: "sync", "Could not revert to previous block, last: {} ({})", start, self.last_imported_hash);
self.reset();
}
}
}
}
},
_ => {
self.retract_step = 1;
},
}
self.last_round_start = self.last_imported_block;
self.last_round_start_hash = self.last_imported_hash;
self.imported_this_round = None;
}
/// Find some headers or blocks to download for a peer.
pub fn request_blocks(&mut self, io: &mut SyncIo, num_active_peers: usize) -> Option<BlockRequest> {
match self.state {
State::Idle => {
self.start_sync_round(io);
if self.state == State::ChainHead {
return self.request_blocks(io, num_active_peers);
}
},
State::ChainHead => {
if num_active_peers < MAX_PARALLEL_SUBCHAIN_DOWNLOAD {
// Request subchain headers
trace!(target: "sync", "Starting sync with better chain");
// Request MAX_HEADERS_TO_REQUEST - 2 headers apart so that
// MAX_HEADERS_TO_REQUEST would include headers for neighbouring subchains
return Some(BlockRequest::Headers {
start: self.last_imported_hash.clone(),
count: SUBCHAIN_SIZE,
skip: (MAX_HEADERS_TO_REQUEST - 2) as u64,
});
}
},
State::Blocks => {
// check to see if we need to download any block bodies first
let needed_bodies = self.blocks.needed_bodies(MAX_BODIES_TO_REQUEST, false);
if!needed_bodies.is_empty() {
return Some(BlockRequest::Bodies {
hashes: needed_bodies,
});
}
if self.download_receipts {
let needed_receipts = self.blocks.needed_receipts(MAX_RECEPITS_TO_REQUEST, false);
if!needed_receipts.is_empty() {
return Some(BlockRequest::Receipts {
hashes: needed_receipts,
});
}
}
// find subchain to download
if let Some((h, count)) = self.blocks.needed_headers(MAX_HEADERS_TO_REQUEST, false) {
return Some(BlockRequest::Headers {
start: h,
count: count as u64,
skip: 0,
});
}
},
State::Complete => (),
}
None
}
/// Checks if there are blocks fully downloaded that can be imported into the blockchain and does the import.
pub fn collect_blocks(&mut self, io: &mut SyncIo, allow_out_of_order: bool) -> Result<(), BlockDownloaderImportError> {
let mut bad = false;
let mut imported = HashSet::new();
let blocks = self.blocks.drain();
let count = blocks.len();
for block_and_receipts in blocks {
let block = block_and_receipts.block;
let receipts = block_and_receipts.receipts;
let (h, number, parent) = {
let header = BlockView::new(&block).header_view();
(header.sha3(), header.number(), header.parent_hash())
};
// Perform basic block verification
if!Block::is_good(&block) {
debug!(target: "sync", "Bad block rlp {:?} : {:?}", h, block);
bad = true;
break;
}
if self.target_hash.as_ref().map_or(false, |t| t == &h) {
self.state = State::Complete;
trace!(target: "sync", "Sync target reached");
return Ok(());
}
let result = if let Some(receipts) = receipts {
io.chain().import_block_with_receipts(block, receipts)
} else {
io.chain().import_block(block)
};
match result {
Err(BlockImportError::Import(ImportError::AlreadyInChain)) => {
trace!(target: "sync", "Block already in chain {:?}", h);
self.block_imported(&h, number, &parent);
},
Err(BlockImportError::Import(ImportError::AlreadyQueued)) => {
trace!(target: "sync", "Block already queued {:?}", h);
self.block_imported(&h, number, &parent);
},
Ok(_) => {
trace!(target: "sync", "Block queued {:?}", h);
imported.insert(h.clone());
self.block_imported(&h, number, &parent);
},
Err(BlockImportError::Block(BlockError::UnknownParent(_))) if allow_out_of_order => {
break;
},
Err(BlockImportError::Block(BlockError::UnknownParent(_))) => {
trace!(target: "sync", "Unknown new block parent, restarting sync");
break;
},
Err(e) => {
debug!(target: "sync", "Bad block {:?} : {:?}", h, e);
bad = true;
break;
}
}
}
trace!(target: "sync", "Imported {} of {}", imported.len(), count);
self.imported_this_round = Some(self.imported_this_round.unwrap_or(0) + imported.len());
if bad {
return Err(BlockDownloaderImportError::Invalid);
}
if self.blocks.is_empty() {
// complete sync round
trace!(target: "sync", "Sync round complete");
self.reset();
}
Ok(())
}
fn block_imported(&mut self, hash: &H256, number: BlockNumber, parent: &H256) {
self.last_imported_block = number;
self.last_imported_hash = hash.clone();
self.round_parents.push_back((hash.clone(), parent.clone()));
if self.round_parents.len() > MAX_ROUND_PARENTS {
self.round_parents.pop_front();
}
}
}
//TODO: module tests
| {
self.state = State::ChainHead;
trace!(target: "sync", "Starting round (last imported count = {:?}, last started = {}, block = {:?}", self.imported_this_round, self.last_round_start, self.last_imported_block);
// Check if need to retract to find the common block. The problem is that the peers still return headers by hash even
// from the non-canonical part of the tree. So we also retract if nothing has been imported last round.
let start = self.last_round_start;
let start_hash = self.last_round_start_hash;
match self.imported_this_round {
Some(n) if n == 0 && start > 0 => {
// nothing was imported last round, step back to a previous block
// search parent in last round known parents first
if let Some(&(_, p)) = self.round_parents.iter().find(|&&(h, _)| h == start_hash) {
self.last_imported_block = start - 1;
self.last_imported_hash = p.clone();
trace!(target: "sync", "Searching common header from the last round {} ({})", self.last_imported_block, self.last_imported_hash);
} else {
let best = io.chain().chain_info().best_block_number;
let oldest_reorg = io.chain().pruning_info().earliest_state;
if self.limit_reorg && best > start && start < oldest_reorg {
debug!(target: "sync", "Could not revert to previous ancient block, last: {} ({})", start, start_hash); | identifier_body |
block_sync.rs | // Copyright 2015-2017 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/>.
///
/// Blockchain downloader
///
use util::*;
use rlp::*;
use ethcore::views::{BlockView};
use ethcore::header::{BlockNumber, Header as BlockHeader};
use ethcore::client::{BlockStatus, BlockId, BlockImportError};
use ethcore::block::Block;
use ethcore::error::{ImportError, BlockError};
use sync_io::SyncIo;
use blocks::BlockCollection;
const MAX_HEADERS_TO_REQUEST: usize = 128;
const MAX_BODIES_TO_REQUEST: usize = 64;
const MAX_RECEPITS_TO_REQUEST: usize = 128;
const SUBCHAIN_SIZE: u64 = 256;
const MAX_ROUND_PARENTS: usize = 16;
const MAX_PARALLEL_SUBCHAIN_DOWNLOAD: usize = 5;
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
/// Downloader state
pub enum | {
/// No active downloads.
Idle,
/// Downloading subchain heads
ChainHead,
/// Downloading blocks
Blocks,
/// Download is complete
Complete,
}
/// Data that needs to be requested from a peer.
pub enum BlockRequest {
Headers {
start: H256,
count: u64,
skip: u64,
},
Bodies {
hashes: Vec<H256>,
},
Receipts {
hashes: Vec<H256>,
},
}
/// Indicates sync action
pub enum DownloadAction {
/// Do nothing
None,
/// Reset downloads for all peers
Reset
}
#[derive(Eq, PartialEq, Debug)]
pub enum BlockDownloaderImportError {
/// Imported data is rejected as invalid.
Invalid,
/// Imported data is valid but rejected cause the downloader does not need it.
Useless,
}
/// Block downloader strategy.
/// Manages state and block data for a block download process.
pub struct BlockDownloader {
/// Downloader state
state: State,
/// Highest block number seen
highest_block: Option<BlockNumber>,
/// Downloaded blocks, holds `H`, `B` and `S`
blocks: BlockCollection,
/// Last impoted block number
last_imported_block: BlockNumber,
/// Last impoted block hash
last_imported_hash: H256,
/// Number of blocks imported this round
imported_this_round: Option<usize>,
/// Block number the last round started with.
last_round_start: BlockNumber,
last_round_start_hash: H256,
/// Block parents imported this round (hash, parent)
round_parents: VecDeque<(H256, H256)>,
/// Do we need to download block recetips.
download_receipts: bool,
/// Sync up to the block with this hash.
target_hash: Option<H256>,
/// Probing range for seeking common best block.
retract_step: u64,
/// Whether reorg should be limited.
limit_reorg: bool,
}
impl BlockDownloader {
/// Create a new instance of syncing strategy. This won't reorganize to before the
/// last kept state.
pub fn new(sync_receipts: bool, start_hash: &H256, start_number: BlockNumber) -> Self {
BlockDownloader {
state: State::Idle,
highest_block: None,
last_imported_block: start_number,
last_imported_hash: start_hash.clone(),
last_round_start: start_number,
last_round_start_hash: start_hash.clone(),
blocks: BlockCollection::new(sync_receipts),
imported_this_round: None,
round_parents: VecDeque::new(),
download_receipts: sync_receipts,
target_hash: None,
retract_step: 1,
limit_reorg: true,
}
}
/// Create a new instance of sync with unlimited reorg allowed.
pub fn with_unlimited_reorg(sync_receipts: bool, start_hash: &H256, start_number: BlockNumber) -> Self {
BlockDownloader {
state: State::Idle,
highest_block: None,
last_imported_block: start_number,
last_imported_hash: start_hash.clone(),
last_round_start: start_number,
last_round_start_hash: start_hash.clone(),
blocks: BlockCollection::new(sync_receipts),
imported_this_round: None,
round_parents: VecDeque::new(),
download_receipts: sync_receipts,
target_hash: None,
retract_step: 1,
limit_reorg: false,
}
}
/// Reset sync. Clear all local downloaded data.
pub fn reset(&mut self) {
self.blocks.clear();
self.state = State::Idle;
}
/// Mark a block as known in the chain
pub fn mark_as_known(&mut self, hash: &H256, number: BlockNumber) {
if number >= self.last_imported_block + 1 {
self.last_imported_block = number;
self.last_imported_hash = hash.clone();
self.imported_this_round = Some(self.imported_this_round.unwrap_or(0) + 1);
self.last_round_start = number;
self.last_round_start_hash = hash.clone();
}
}
/// Check if download is complete
pub fn is_complete(&self) -> bool {
self.state == State::Complete
}
/// Check if particular block hash is being downloaded
pub fn is_downloading(&self, hash: &H256) -> bool {
self.blocks.is_downloading(hash)
}
/// Set starting sync block
pub fn set_target(&mut self, hash: &H256) {
self.target_hash = Some(hash.clone());
}
/// Unmark header as being downloaded.
pub fn clear_header_download(&mut self, hash: &H256) {
self.blocks.clear_header_download(hash)
}
/// Unmark block body as being downloaded.
pub fn clear_body_download(&mut self, hashes: &[H256]) {
self.blocks.clear_body_download(hashes)
}
/// Unmark block receipt as being downloaded.
pub fn clear_receipt_download(&mut self, hashes: &[H256]) {
self.blocks.clear_receipt_download(hashes)
}
/// Reset collection for a new sync round with given subchain block hashes.
pub fn reset_to(&mut self, hashes: Vec<H256>) {
self.reset();
self.blocks.reset_to(hashes);
self.state = State::Blocks;
}
/// Returns used heap memory size.
pub fn heap_size(&self) -> usize {
self.blocks.heap_size() + self.round_parents.heap_size_of_children()
}
/// Returns best imported block number.
pub fn last_imported_block_number(&self) -> BlockNumber {
self.last_imported_block
}
/// Add new block headers.
pub fn import_headers(&mut self, io: &mut SyncIo, r: &UntrustedRlp, expected_hash: Option<H256>) -> Result<DownloadAction, BlockDownloaderImportError> {
let item_count = r.item_count();
if self.state == State::Idle {
trace!(target: "sync", "Ignored unexpected block headers");
return Ok(DownloadAction::None)
}
if item_count == 0 && (self.state == State::Blocks) {
return Err(BlockDownloaderImportError::Invalid);
}
let mut headers = Vec::new();
let mut hashes = Vec::new();
let mut valid_response = item_count == 0; //empty response is valid
let mut any_known = false;
for i in 0..item_count {
let info: BlockHeader = r.val_at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block header RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
let number = BlockNumber::from(info.number());
// Check if any of the headers matches the hash we requested
if!valid_response {
if let Some(expected) = expected_hash {
valid_response = expected == info.hash()
}
}
any_known = any_known || self.blocks.contains_head(&info.hash());
if self.blocks.contains(&info.hash()) {
trace!(target: "sync", "Skipping existing block header {} ({:?})", number, info.hash());
continue;
}
if self.highest_block.as_ref().map_or(true, |n| number > *n) {
self.highest_block = Some(number);
}
let hash = info.hash();
let hdr = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block header RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
match io.chain().block_status(BlockId::Hash(hash.clone())) {
BlockStatus::InChain | BlockStatus::Queued => {
match self.state {
State::Blocks => trace!(target: "sync", "Header already in chain {} ({})", number, hash),
_ => trace!(target: "sync", "Header already in chain {} ({}), state = {:?}", number, hash, self.state),
}
headers.push(hdr.as_raw().to_vec());
hashes.push(hash);
},
BlockStatus::Bad => {
return Err(BlockDownloaderImportError::Invalid);
},
BlockStatus::Unknown => {
headers.push(hdr.as_raw().to_vec());
hashes.push(hash);
}
}
}
// Disable the peer for this syncing round if it gives invalid chain
if!valid_response {
trace!(target: "sync", "Invalid headers response");
return Err(BlockDownloaderImportError::Invalid);
}
match self.state {
State::ChainHead => {
if!headers.is_empty() {
// TODO: validate heads better. E.g. check that there is enough distance between blocks.
trace!(target: "sync", "Received {} subchain heads, proceeding to download", headers.len());
self.blocks.reset_to(hashes);
self.state = State::Blocks;
return Ok(DownloadAction::Reset);
} else {
let best = io.chain().chain_info().best_block_number;
let oldest_reorg = io.chain().pruning_info().earliest_state;
let last = self.last_imported_block;
if self.limit_reorg && best > last && (last == 0 || last < oldest_reorg) {
trace!(target: "sync", "No common block, disabling peer");
return Err(BlockDownloaderImportError::Invalid);
}
}
},
State::Blocks => {
let count = headers.len();
// At least one of the heades must advance the subchain. Otherwise they are all useless.
if count == 0 ||!any_known {
trace!(target: "sync", "No useful headers");
return Err(BlockDownloaderImportError::Useless);
}
self.blocks.insert_headers(headers);
trace!(target: "sync", "Inserted {} headers", count);
},
_ => trace!(target: "sync", "Unexpected headers({})", headers.len()),
}
Ok(DownloadAction::None)
}
/// Called by peer once it has new block bodies
pub fn import_bodies(&mut self, _io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), BlockDownloaderImportError> {
let item_count = r.item_count();
if item_count == 0 {
return Err(BlockDownloaderImportError::Useless);
}
else if self.state!= State::Blocks {
trace!(target: "sync", "Ignored unexpected block bodies");
}
else {
let mut bodies = Vec::with_capacity(item_count);
for i in 0..item_count {
let body = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block boides RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
bodies.push(body.as_raw().to_vec());
}
if self.blocks.insert_bodies(bodies)!= item_count {
trace!(target: "sync", "Deactivating peer for giving invalid block bodies");
return Err(BlockDownloaderImportError::Invalid);
}
}
Ok(())
}
/// Called by peer once it has new block bodies
pub fn import_receipts(&mut self, _io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), BlockDownloaderImportError> {
let item_count = r.item_count();
if item_count == 0 {
return Err(BlockDownloaderImportError::Useless);
}
else if self.state!= State::Blocks {
trace!(target: "sync", "Ignored unexpected block receipts");
}
else {
let mut receipts = Vec::with_capacity(item_count);
for i in 0..item_count {
let receipt = r.at(i).map_err(|e| {
trace!(target: "sync", "Error decoding block receipts RLP: {:?}", e);
BlockDownloaderImportError::Invalid
})?;
receipts.push(receipt.as_raw().to_vec());
}
if self.blocks.insert_receipts(receipts)!= item_count {
trace!(target: "sync", "Deactivating peer for giving invalid block receipts");
return Err(BlockDownloaderImportError::Invalid);
}
}
Ok(())
}
fn start_sync_round(&mut self, io: &mut SyncIo) {
self.state = State::ChainHead;
trace!(target: "sync", "Starting round (last imported count = {:?}, last started = {}, block = {:?}", self.imported_this_round, self.last_round_start, self.last_imported_block);
// Check if need to retract to find the common block. The problem is that the peers still return headers by hash even
// from the non-canonical part of the tree. So we also retract if nothing has been imported last round.
let start = self.last_round_start;
let start_hash = self.last_round_start_hash;
match self.imported_this_round {
Some(n) if n == 0 && start > 0 => {
// nothing was imported last round, step back to a previous block
// search parent in last round known parents first
if let Some(&(_, p)) = self.round_parents.iter().find(|&&(h, _)| h == start_hash) {
self.last_imported_block = start - 1;
self.last_imported_hash = p.clone();
trace!(target: "sync", "Searching common header from the last round {} ({})", self.last_imported_block, self.last_imported_hash);
} else {
let best = io.chain().chain_info().best_block_number;
let oldest_reorg = io.chain().pruning_info().earliest_state;
if self.limit_reorg && best > start && start < oldest_reorg {
debug!(target: "sync", "Could not revert to previous ancient block, last: {} ({})", start, start_hash);
self.reset();
} else {
let n = start - min(self.retract_step, start);
self.retract_step *= 2;
match io.chain().block_hash(BlockId::Number(n)) {
Some(h) => {
self.last_imported_block = n;
self.last_imported_hash = h;
trace!(target: "sync", "Searching common header in the blockchain {} ({})", start, self.last_imported_hash);
}
None => {
debug!(target: "sync", "Could not revert to previous block, last: {} ({})", start, self.last_imported_hash);
self.reset();
}
}
}
}
},
_ => {
self.retract_step = 1;
},
}
self.last_round_start = self.last_imported_block;
self.last_round_start_hash = self.last_imported_hash;
self.imported_this_round = None;
}
/// Find some headers or blocks to download for a peer.
pub fn request_blocks(&mut self, io: &mut SyncIo, num_active_peers: usize) -> Option<BlockRequest> {
match self.state {
State::Idle => {
self.start_sync_round(io);
if self.state == State::ChainHead {
return self.request_blocks(io, num_active_peers);
}
},
State::ChainHead => {
if num_active_peers < MAX_PARALLEL_SUBCHAIN_DOWNLOAD {
// Request subchain headers
trace!(target: "sync", "Starting sync with better chain");
// Request MAX_HEADERS_TO_REQUEST - 2 headers apart so that
// MAX_HEADERS_TO_REQUEST would include headers for neighbouring subchains
return Some(BlockRequest::Headers {
start: self.last_imported_hash.clone(),
count: SUBCHAIN_SIZE,
skip: (MAX_HEADERS_TO_REQUEST - 2) as u64,
});
}
},
State::Blocks => {
// check to see if we need to download any block bodies first
let needed_bodies = self.blocks.needed_bodies(MAX_BODIES_TO_REQUEST, false);
if!needed_bodies.is_empty() {
return Some(BlockRequest::Bodies {
hashes: needed_bodies,
});
}
if self.download_receipts {
let needed_receipts = self.blocks.needed_receipts(MAX_RECEPITS_TO_REQUEST, false);
if!needed_receipts.is_empty() {
return Some(BlockRequest::Receipts {
hashes: needed_receipts,
});
}
}
// find subchain to download
if let Some((h, count)) = self.blocks.needed_headers(MAX_HEADERS_TO_REQUEST, false) {
return Some(BlockRequest::Headers {
start: h,
count: count as u64,
skip: 0,
});
}
},
State::Complete => (),
}
None
}
/// Checks if there are blocks fully downloaded that can be imported into the blockchain and does the import.
pub fn collect_blocks(&mut self, io: &mut SyncIo, allow_out_of_order: bool) -> Result<(), BlockDownloaderImportError> {
let mut bad = false;
let mut imported = HashSet::new();
let blocks = self.blocks.drain();
let count = blocks.len();
for block_and_receipts in blocks {
let block = block_and_receipts.block;
let receipts = block_and_receipts.receipts;
let (h, number, parent) = {
let header = BlockView::new(&block).header_view();
(header.sha3(), header.number(), header.parent_hash())
};
// Perform basic block verification
if!Block::is_good(&block) {
debug!(target: "sync", "Bad block rlp {:?} : {:?}", h, block);
bad = true;
break;
}
if self.target_hash.as_ref().map_or(false, |t| t == &h) {
self.state = State::Complete;
trace!(target: "sync", "Sync target reached");
return Ok(());
}
let result = if let Some(receipts) = receipts {
io.chain().import_block_with_receipts(block, receipts)
} else {
io.chain().import_block(block)
};
match result {
Err(BlockImportError::Import(ImportError::AlreadyInChain)) => {
trace!(target: "sync", "Block already in chain {:?}", h);
self.block_imported(&h, number, &parent);
},
Err(BlockImportError::Import(ImportError::AlreadyQueued)) => {
trace!(target: "sync", "Block already queued {:?}", h);
self.block_imported(&h, number, &parent);
},
Ok(_) => {
trace!(target: "sync", "Block queued {:?}", h);
imported.insert(h.clone());
self.block_imported(&h, number, &parent);
},
Err(BlockImportError::Block(BlockError::UnknownParent(_))) if allow_out_of_order => {
break;
},
Err(BlockImportError::Block(BlockError::UnknownParent(_))) => {
trace!(target: "sync", "Unknown new block parent, restarting sync");
break;
},
Err(e) => {
debug!(target: "sync", "Bad block {:?} : {:?}", h, e);
bad = true;
break;
}
}
}
trace!(target: "sync", "Imported {} of {}", imported.len(), count);
self.imported_this_round = Some(self.imported_this_round.unwrap_or(0) + imported.len());
if bad {
return Err(BlockDownloaderImportError::Invalid);
}
if self.blocks.is_empty() {
// complete sync round
trace!(target: "sync", "Sync round complete");
self.reset();
}
Ok(())
}
fn block_imported(&mut self, hash: &H256, number: BlockNumber, parent: &H256) {
self.last_imported_block = number;
self.last_imported_hash = hash.clone();
self.round_parents.push_back((hash.clone(), parent.clone()));
if self.round_parents.len() > MAX_ROUND_PARENTS {
self.round_parents.pop_front();
}
}
}
//TODO: module tests
| State | identifier_name |
char_class.rs | // Copyright 2014 Strahinja Val Markovic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use base::unicode::{bytesFollowing, readCodepoint};
use super::{Expression, ParseState, ParseResult};
macro_rules! class( ( $ex:expr ) => (
&base::CharClass::new( $ex.as_bytes() ) ) );
fn toU32Vector( input: &[u8] ) -> Vec<u32> {
let mut i = 0;
let mut out_vec : Vec<u32> = vec!();
loop {
match input.get( i ) {
Some( byte ) => match bytesFollowing( *byte ) {
Some( num_following ) => {
if num_following > 0 {
match readCodepoint( &input[ i.. ] ) {
Some( ch ) => {
out_vec.push( ch as u32 );
i += num_following + 1
}
_ => { out_vec.push( *byte as u32 ); i += 1 }
};
} else { out_vec.push( *byte as u32 ); i += 1 }
}
_ => { out_vec.push( *byte as u32 ); i += 1 }
},
_ => return out_vec
}
}
}
pub struct CharClass {
// All the single chars in the char class.
// May be unicode codepoints or binary octets stored as codepoints.
single_chars: Vec<u32>,
// Sequence of [from, to] (inclusive bounds) char ranges.
// May be unicode codepoints or binary octets stored as codepoints.
ranges: Vec<( u32, u32 )>
}
impl CharClass {
// Takes the inner content of square brackets, so for [a-z], send "a-z".
pub fn new( contents: &[u8] ) -> CharClass {
fn rangeAtIndex( index: usize, chars: &[u32] ) -> Option<( u32, u32 )> |
let chars = toU32Vector( &contents );
let mut char_class = CharClass { single_chars: Vec::new(),
ranges: Vec::new() };
let mut index = 0;
loop {
match rangeAtIndex( index, &chars ) {
Some( range ) => {
char_class.ranges.push( range );
index += 3;
}
_ => {
if index >= chars.len() {
break
}
char_class.single_chars.push( chars[ index ] );
index += 1;
}
};
}
char_class
}
fn matches( &self, character: u32 ) -> bool {
return self.single_chars.contains( &character ) ||
self.ranges.iter().any(
| &(from, to) | character >= from && character <= to );
}
fn applyToUtf8<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
match readCodepoint( parse_state.input ) {
Some( ch ) if self.matches( ch as u32 ) => {
let num_following = bytesFollowing( parse_state.input[ 0 ] ).unwrap();
parse_state.offsetToResult( parse_state.offset + num_following + 1 )
}
_ => None
}
}
fn applyToBytes<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
match parse_state.input.get( 0 ) {
Some( byte ) if self.matches( *byte as u32 ) => {
parse_state.offsetToResult( parse_state.offset + 1 )
}
_ => None
}
}
}
impl Expression for CharClass {
fn apply<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
self.applyToUtf8( parse_state ).or( self.applyToBytes( parse_state ) )
}
}
#[cfg(test)]
mod tests {
use base;
use base::{Node, Data, ParseResult, Expression, ParseState};
use base::test_utils::ToParseState;
use base::unicode::bytesFollowing;
use super::{CharClass};
fn charClassMatch( char_class: &Expression, input: &[u8] ) -> bool {
fn bytesRead( input: &[u8] ) -> usize {
bytesFollowing( input[ 0 ] ).map_or( 1, |num| num + 1 )
}
match char_class.apply( &ToParseState( input ) ) {
Some( ParseResult { nodes, parse_state } ) => {
let bytes_read = bytesRead( input );
assert_eq!( nodes[ 0 ],
Node::withoutName( 0, bytes_read, Data( input ) ) );
assert_eq!( parse_state, ParseState{ input: &[], offset: bytes_read } );
true
}
_ => false
}
}
#[test]
fn CharClass_Match() {
assert!( charClassMatch( class!( "a" ), b"a" ) );
assert!( charClassMatch( class!( "abcdef" ), b"e" ) );
assert!( charClassMatch( class!( "a-z" ), b"a" ) );
assert!( charClassMatch( class!( "a-z" ), b"c" ) );
assert!( charClassMatch( class!( "a-z" ), b"z" ) );
assert!( charClassMatch( class!( "0-9" ), b"2" ) );
assert!( charClassMatch( class!( "α-ω" ), "η".as_bytes() ) );
assert!( charClassMatch( class!( "-" ), b"-" ) );
assert!( charClassMatch( class!( "a-" ), b"-" ) );
assert!( charClassMatch( class!( "-a" ), b"-" ) );
assert!( charClassMatch( class!( "a-zA-Z-" ), b"-" ) );
assert!( charClassMatch( class!( "aa-zA-Z-a" ), b"-" ) );
assert!( charClassMatch( class!( "a-zA-Z-" ), b"z" ) );
assert!( charClassMatch( class!( "aa-zA-Z-0" ), b"0" ) );
assert!( charClassMatch( class!( "a-cdefgh-k" ), b"e" ) );
assert!( charClassMatch( class!( "---" ), b"-" ) );
assert!( charClassMatch( class!( "a-a" ), b"a" ) );
}
#[test]
fn CharClass_Match_NonUnicode() {
assert!( charClassMatch( &CharClass::new( &[255] ), &[255] ) );
}
#[test]
fn CharClass_NoMatch() {
assert!(!charClassMatch( class!( "a" ), b"b" ) );
assert!(!charClassMatch( class!( "-" ), b"a" ) );
assert!(!charClassMatch( class!( "z-a" ), b"a" ) );
assert!(!charClassMatch( class!( "z-a" ), b"b" ) );
assert!(!charClassMatch( class!( "a-z" ), b"0" ) );
assert!(!charClassMatch( class!( "a-z" ), b"A" ) );
}
// TODO: tests for escaped chars in class
}
| {
match ( chars.get( index ),
chars.get( index + 1 ),
chars.get( index + 2 ) ) {
( Some( char1 ), Some( char2 ), Some( char3 ) )
if *char2 == '-' as u32 => Some( ( *char1, *char3 ) ),
_ => None
}
} | identifier_body |
char_class.rs | // Copyright 2014 Strahinja Val Markovic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use base::unicode::{bytesFollowing, readCodepoint};
use super::{Expression, ParseState, ParseResult};
macro_rules! class( ( $ex:expr ) => (
&base::CharClass::new( $ex.as_bytes() ) ) );
fn toU32Vector( input: &[u8] ) -> Vec<u32> {
let mut i = 0;
let mut out_vec : Vec<u32> = vec!();
loop {
match input.get( i ) {
Some( byte ) => match bytesFollowing( *byte ) {
Some( num_following ) => {
if num_following > 0 {
match readCodepoint( &input[ i.. ] ) {
Some( ch ) => {
out_vec.push( ch as u32 );
i += num_following + 1
}
_ => { out_vec.push( *byte as u32 ); i += 1 }
};
} else { out_vec.push( *byte as u32 ); i += 1 }
}
_ => { out_vec.push( *byte as u32 ); i += 1 }
},
_ => return out_vec
}
}
}
pub struct CharClass {
// All the single chars in the char class.
// May be unicode codepoints or binary octets stored as codepoints.
single_chars: Vec<u32>,
// Sequence of [from, to] (inclusive bounds) char ranges.
// May be unicode codepoints or binary octets stored as codepoints.
ranges: Vec<( u32, u32 )>
}
impl CharClass {
// Takes the inner content of square brackets, so for [a-z], send "a-z".
pub fn new( contents: &[u8] ) -> CharClass {
fn rangeAtIndex( index: usize, chars: &[u32] ) -> Option<( u32, u32 )> {
match ( chars.get( index ),
chars.get( index + 1 ),
chars.get( index + 2 ) ) {
( Some( char1 ), Some( char2 ), Some( char3 ) )
if *char2 == '-' as u32 => Some( ( *char1, *char3 ) ),
_ => None
}
}
let chars = toU32Vector( &contents );
let mut char_class = CharClass { single_chars: Vec::new(),
ranges: Vec::new() };
let mut index = 0;
loop {
match rangeAtIndex( index, &chars ) {
Some( range ) => {
char_class.ranges.push( range );
index += 3;
}
_ => {
if index >= chars.len() {
break
}
char_class.single_chars.push( chars[ index ] );
index += 1;
}
};
}
char_class
}
fn matches( &self, character: u32 ) -> bool {
return self.single_chars.contains( &character ) ||
self.ranges.iter().any(
| &(from, to) | character >= from && character <= to );
}
fn applyToUtf8<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
match readCodepoint( parse_state.input ) {
Some( ch ) if self.matches( ch as u32 ) => {
let num_following = bytesFollowing( parse_state.input[ 0 ] ).unwrap();
parse_state.offsetToResult( parse_state.offset + num_following + 1 )
}
_ => None
}
}
fn applyToBytes<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
match parse_state.input.get( 0 ) {
Some( byte ) if self.matches( *byte as u32 ) => {
parse_state.offsetToResult( parse_state.offset + 1 )
}
_ => None
}
}
}
impl Expression for CharClass {
fn apply<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
self.applyToUtf8( parse_state ).or( self.applyToBytes( parse_state ) )
}
}
#[cfg(test)]
mod tests {
use base;
use base::{Node, Data, ParseResult, Expression, ParseState};
use base::test_utils::ToParseState;
use base::unicode::bytesFollowing;
use super::{CharClass};
fn charClassMatch( char_class: &Expression, input: &[u8] ) -> bool {
fn bytesRead( input: &[u8] ) -> usize {
bytesFollowing( input[ 0 ] ).map_or( 1, |num| num + 1 )
}
match char_class.apply( &ToParseState( input ) ) {
Some( ParseResult { nodes, parse_state } ) => {
let bytes_read = bytesRead( input );
assert_eq!( nodes[ 0 ],
Node::withoutName( 0, bytes_read, Data( input ) ) );
assert_eq!( parse_state, ParseState{ input: &[], offset: bytes_read } );
true
}
_ => false
}
}
#[test]
fn | () {
assert!( charClassMatch( class!( "a" ), b"a" ) );
assert!( charClassMatch( class!( "abcdef" ), b"e" ) );
assert!( charClassMatch( class!( "a-z" ), b"a" ) );
assert!( charClassMatch( class!( "a-z" ), b"c" ) );
assert!( charClassMatch( class!( "a-z" ), b"z" ) );
assert!( charClassMatch( class!( "0-9" ), b"2" ) );
assert!( charClassMatch( class!( "α-ω" ), "η".as_bytes() ) );
assert!( charClassMatch( class!( "-" ), b"-" ) );
assert!( charClassMatch( class!( "a-" ), b"-" ) );
assert!( charClassMatch( class!( "-a" ), b"-" ) );
assert!( charClassMatch( class!( "a-zA-Z-" ), b"-" ) );
assert!( charClassMatch( class!( "aa-zA-Z-a" ), b"-" ) );
assert!( charClassMatch( class!( "a-zA-Z-" ), b"z" ) );
assert!( charClassMatch( class!( "aa-zA-Z-0" ), b"0" ) );
assert!( charClassMatch( class!( "a-cdefgh-k" ), b"e" ) );
assert!( charClassMatch( class!( "---" ), b"-" ) );
assert!( charClassMatch( class!( "a-a" ), b"a" ) );
}
#[test]
fn CharClass_Match_NonUnicode() {
assert!( charClassMatch( &CharClass::new( &[255] ), &[255] ) );
}
#[test]
fn CharClass_NoMatch() {
assert!(!charClassMatch( class!( "a" ), b"b" ) );
assert!(!charClassMatch( class!( "-" ), b"a" ) );
assert!(!charClassMatch( class!( "z-a" ), b"a" ) );
assert!(!charClassMatch( class!( "z-a" ), b"b" ) );
assert!(!charClassMatch( class!( "a-z" ), b"0" ) );
assert!(!charClassMatch( class!( "a-z" ), b"A" ) );
}
// TODO: tests for escaped chars in class
}
| CharClass_Match | identifier_name |
char_class.rs | // Copyright 2014 Strahinja Val Markovic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use base::unicode::{bytesFollowing, readCodepoint};
use super::{Expression, ParseState, ParseResult};
macro_rules! class( ( $ex:expr ) => (
&base::CharClass::new( $ex.as_bytes() ) ) );
fn toU32Vector( input: &[u8] ) -> Vec<u32> {
let mut i = 0;
let mut out_vec : Vec<u32> = vec!();
loop {
match input.get( i ) {
Some( byte ) => match bytesFollowing( *byte ) {
Some( num_following ) => {
if num_following > 0 {
match readCodepoint( &input[ i.. ] ) {
Some( ch ) => {
out_vec.push( ch as u32 );
i += num_following + 1
}
_ => { out_vec.push( *byte as u32 ); i += 1 }
};
} else { out_vec.push( *byte as u32 ); i += 1 }
}
_ => { out_vec.push( *byte as u32 ); i += 1 }
},
_ => return out_vec
}
}
}
pub struct CharClass {
// All the single chars in the char class.
// May be unicode codepoints or binary octets stored as codepoints.
single_chars: Vec<u32>,
// Sequence of [from, to] (inclusive bounds) char ranges.
// May be unicode codepoints or binary octets stored as codepoints.
ranges: Vec<( u32, u32 )>
}
impl CharClass {
// Takes the inner content of square brackets, so for [a-z], send "a-z".
pub fn new( contents: &[u8] ) -> CharClass {
fn rangeAtIndex( index: usize, chars: &[u32] ) -> Option<( u32, u32 )> {
match ( chars.get( index ),
chars.get( index + 1 ),
chars.get( index + 2 ) ) {
( Some( char1 ), Some( char2 ), Some( char3 ) )
if *char2 == '-' as u32 => Some( ( *char1, *char3 ) ),
_ => None
}
}
let chars = toU32Vector( &contents );
let mut char_class = CharClass { single_chars: Vec::new(),
ranges: Vec::new() };
let mut index = 0;
loop {
match rangeAtIndex( index, &chars ) {
Some( range ) => {
char_class.ranges.push( range );
index += 3;
}
_ => {
if index >= chars.len() {
break
}
char_class.single_chars.push( chars[ index ] );
index += 1;
}
};
}
char_class
}
fn matches( &self, character: u32 ) -> bool {
return self.single_chars.contains( &character ) ||
self.ranges.iter().any(
| &(from, to) | character >= from && character <= to );
}
fn applyToUtf8<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
match readCodepoint( parse_state.input ) {
Some( ch ) if self.matches( ch as u32 ) => {
let num_following = bytesFollowing( parse_state.input[ 0 ] ).unwrap();
parse_state.offsetToResult( parse_state.offset + num_following + 1 )
}
_ => None
}
}
fn applyToBytes<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
match parse_state.input.get( 0 ) {
Some( byte ) if self.matches( *byte as u32 ) => |
_ => None
}
}
}
impl Expression for CharClass {
fn apply<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
self.applyToUtf8( parse_state ).or( self.applyToBytes( parse_state ) )
}
}
#[cfg(test)]
mod tests {
use base;
use base::{Node, Data, ParseResult, Expression, ParseState};
use base::test_utils::ToParseState;
use base::unicode::bytesFollowing;
use super::{CharClass};
fn charClassMatch( char_class: &Expression, input: &[u8] ) -> bool {
fn bytesRead( input: &[u8] ) -> usize {
bytesFollowing( input[ 0 ] ).map_or( 1, |num| num + 1 )
}
match char_class.apply( &ToParseState( input ) ) {
Some( ParseResult { nodes, parse_state } ) => {
let bytes_read = bytesRead( input );
assert_eq!( nodes[ 0 ],
Node::withoutName( 0, bytes_read, Data( input ) ) );
assert_eq!( parse_state, ParseState{ input: &[], offset: bytes_read } );
true
}
_ => false
}
}
#[test]
fn CharClass_Match() {
assert!( charClassMatch( class!( "a" ), b"a" ) );
assert!( charClassMatch( class!( "abcdef" ), b"e" ) );
assert!( charClassMatch( class!( "a-z" ), b"a" ) );
assert!( charClassMatch( class!( "a-z" ), b"c" ) );
assert!( charClassMatch( class!( "a-z" ), b"z" ) );
assert!( charClassMatch( class!( "0-9" ), b"2" ) );
assert!( charClassMatch( class!( "α-ω" ), "η".as_bytes() ) );
assert!( charClassMatch( class!( "-" ), b"-" ) );
assert!( charClassMatch( class!( "a-" ), b"-" ) );
assert!( charClassMatch( class!( "-a" ), b"-" ) );
assert!( charClassMatch( class!( "a-zA-Z-" ), b"-" ) );
assert!( charClassMatch( class!( "aa-zA-Z-a" ), b"-" ) );
assert!( charClassMatch( class!( "a-zA-Z-" ), b"z" ) );
assert!( charClassMatch( class!( "aa-zA-Z-0" ), b"0" ) );
assert!( charClassMatch( class!( "a-cdefgh-k" ), b"e" ) );
assert!( charClassMatch( class!( "---" ), b"-" ) );
assert!( charClassMatch( class!( "a-a" ), b"a" ) );
}
#[test]
fn CharClass_Match_NonUnicode() {
assert!( charClassMatch( &CharClass::new( &[255] ), &[255] ) );
}
#[test]
fn CharClass_NoMatch() {
assert!(!charClassMatch( class!( "a" ), b"b" ) );
assert!(!charClassMatch( class!( "-" ), b"a" ) );
assert!(!charClassMatch( class!( "z-a" ), b"a" ) );
assert!(!charClassMatch( class!( "z-a" ), b"b" ) );
assert!(!charClassMatch( class!( "a-z" ), b"0" ) );
assert!(!charClassMatch( class!( "a-z" ), b"A" ) );
}
// TODO: tests for escaped chars in class
}
| {
parse_state.offsetToResult( parse_state.offset + 1 )
} | conditional_block |
char_class.rs | // Copyright 2014 Strahinja Val Markovic
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use base::unicode::{bytesFollowing, readCodepoint};
use super::{Expression, ParseState, ParseResult};
macro_rules! class( ( $ex:expr ) => (
&base::CharClass::new( $ex.as_bytes() ) ) );
fn toU32Vector( input: &[u8] ) -> Vec<u32> {
let mut i = 0;
let mut out_vec : Vec<u32> = vec!();
loop {
match input.get( i ) {
Some( byte ) => match bytesFollowing( *byte ) {
Some( num_following ) => {
if num_following > 0 {
match readCodepoint( &input[ i.. ] ) {
Some( ch ) => {
out_vec.push( ch as u32 );
i += num_following + 1
}
_ => { out_vec.push( *byte as u32 ); i += 1 }
};
} else { out_vec.push( *byte as u32 ); i += 1 }
}
_ => { out_vec.push( *byte as u32 ); i += 1 }
},
_ => return out_vec
}
}
}
pub struct CharClass {
// All the single chars in the char class.
// May be unicode codepoints or binary octets stored as codepoints.
single_chars: Vec<u32>,
// Sequence of [from, to] (inclusive bounds) char ranges.
// May be unicode codepoints or binary octets stored as codepoints.
ranges: Vec<( u32, u32 )>
}
impl CharClass {
// Takes the inner content of square brackets, so for [a-z], send "a-z".
pub fn new( contents: &[u8] ) -> CharClass {
fn rangeAtIndex( index: usize, chars: &[u32] ) -> Option<( u32, u32 )> {
match ( chars.get( index ),
chars.get( index + 1 ),
chars.get( index + 2 ) ) {
( Some( char1 ), Some( char2 ), Some( char3 ) )
if *char2 == '-' as u32 => Some( ( *char1, *char3 ) ),
_ => None
}
}
let chars = toU32Vector( &contents );
let mut char_class = CharClass { single_chars: Vec::new(),
ranges: Vec::new() };
let mut index = 0;
loop {
match rangeAtIndex( index, &chars ) {
Some( range ) => {
char_class.ranges.push( range );
index += 3;
}
_ => {
if index >= chars.len() {
break
}
char_class.single_chars.push( chars[ index ] );
index += 1;
}
};
}
char_class
}
fn matches( &self, character: u32 ) -> bool {
return self.single_chars.contains( &character ) ||
self.ranges.iter().any(
| &(from, to) | character >= from && character <= to );
}
fn applyToUtf8<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
match readCodepoint( parse_state.input ) {
Some( ch ) if self.matches( ch as u32 ) => {
let num_following = bytesFollowing( parse_state.input[ 0 ] ).unwrap();
parse_state.offsetToResult( parse_state.offset + num_following + 1 )
}
_ => None
}
}
fn applyToBytes<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
match parse_state.input.get( 0 ) {
Some( byte ) if self.matches( *byte as u32 ) => {
parse_state.offsetToResult( parse_state.offset + 1 )
}
_ => None
}
}
}
impl Expression for CharClass {
fn apply<'a>( &self, parse_state: &ParseState<'a> ) ->
Option< ParseResult<'a> > {
self.applyToUtf8( parse_state ).or( self.applyToBytes( parse_state ) )
}
}
#[cfg(test)]
mod tests {
use base;
use base::{Node, Data, ParseResult, Expression, ParseState};
use base::test_utils::ToParseState;
use base::unicode::bytesFollowing;
use super::{CharClass};
fn charClassMatch( char_class: &Expression, input: &[u8] ) -> bool {
fn bytesRead( input: &[u8] ) -> usize {
bytesFollowing( input[ 0 ] ).map_or( 1, |num| num + 1 )
}
match char_class.apply( &ToParseState( input ) ) {
Some( ParseResult { nodes, parse_state } ) => {
let bytes_read = bytesRead( input );
assert_eq!( nodes[ 0 ],
Node::withoutName( 0, bytes_read, Data( input ) ) );
assert_eq!( parse_state, ParseState{ input: &[], offset: bytes_read } );
true
}
_ => false
}
}
#[test]
fn CharClass_Match() {
assert!( charClassMatch( class!( "a" ), b"a" ) );
assert!( charClassMatch( class!( "abcdef" ), b"e" ) );
assert!( charClassMatch( class!( "a-z" ), b"a" ) );
assert!( charClassMatch( class!( "a-z" ), b"c" ) );
assert!( charClassMatch( class!( "a-z" ), b"z" ) );
assert!( charClassMatch( class!( "0-9" ), b"2" ) );
assert!( charClassMatch( class!( "α-ω" ), "η".as_bytes() ) ); | assert!( charClassMatch( class!( "a-zA-Z-" ), b"z" ) );
assert!( charClassMatch( class!( "aa-zA-Z-0" ), b"0" ) );
assert!( charClassMatch( class!( "a-cdefgh-k" ), b"e" ) );
assert!( charClassMatch( class!( "---" ), b"-" ) );
assert!( charClassMatch( class!( "a-a" ), b"a" ) );
}
#[test]
fn CharClass_Match_NonUnicode() {
assert!( charClassMatch( &CharClass::new( &[255] ), &[255] ) );
}
#[test]
fn CharClass_NoMatch() {
assert!(!charClassMatch( class!( "a" ), b"b" ) );
assert!(!charClassMatch( class!( "-" ), b"a" ) );
assert!(!charClassMatch( class!( "z-a" ), b"a" ) );
assert!(!charClassMatch( class!( "z-a" ), b"b" ) );
assert!(!charClassMatch( class!( "a-z" ), b"0" ) );
assert!(!charClassMatch( class!( "a-z" ), b"A" ) );
}
// TODO: tests for escaped chars in class
} | assert!( charClassMatch( class!( "-" ), b"-" ) );
assert!( charClassMatch( class!( "a-" ), b"-" ) );
assert!( charClassMatch( class!( "-a" ), b"-" ) );
assert!( charClassMatch( class!( "a-zA-Z-" ), b"-" ) );
assert!( charClassMatch( class!( "aa-zA-Z-a" ), b"-" ) ); | random_line_split |
issue-3953.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.
// ignore-tidy-linelength
use std::cmp::PartialEq;
trait Hahaha: PartialEq + PartialEq {
//~^ ERROR trait `PartialEq` already appears in the list of bounds
}
struct Lol(isize);
impl Hahaha for Lol { }
impl PartialEq for Lol {
fn eq(&self, other: &Lol) -> bool { **self!= **other }
fn ne(&self, other: &Lol) -> bool { **self == **other }
}
fn main() | {
if Lol(2) == Lol(4) {
println!("2 == 4");
} else {
println!("2 != 4");
}
} | identifier_body | |
issue-3953.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.
// ignore-tidy-linelength
use std::cmp::PartialEq;
trait Hahaha: PartialEq + PartialEq {
//~^ ERROR trait `PartialEq` already appears in the list of bounds
}
struct Lol(isize);
impl Hahaha for Lol { }
impl PartialEq for Lol {
fn eq(&self, other: &Lol) -> bool { **self!= **other }
fn ne(&self, other: &Lol) -> bool { **self == **other }
}
fn main() {
if Lol(2) == Lol(4) {
println!("2 == 4");
} else |
}
| {
println!("2 != 4");
} | conditional_block |
issue-3953.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.
// ignore-tidy-linelength
use std::cmp::PartialEq;
trait Hahaha: PartialEq + PartialEq {
//~^ ERROR trait `PartialEq` already appears in the list of bounds
}
struct Lol(isize);
impl Hahaha for Lol { }
impl PartialEq for Lol {
fn eq(&self, other: &Lol) -> bool { **self!= **other }
fn | (&self, other: &Lol) -> bool { **self == **other }
}
fn main() {
if Lol(2) == Lol(4) {
println!("2 == 4");
} else {
println!("2!= 4");
}
}
| ne | identifier_name |
issue-3953.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.
// | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
use std::cmp::PartialEq;
trait Hahaha: PartialEq + PartialEq {
//~^ ERROR trait `PartialEq` already appears in the list of bounds
}
struct Lol(isize);
impl Hahaha for Lol { }
impl PartialEq for Lol {
fn eq(&self, other: &Lol) -> bool { **self!= **other }
fn ne(&self, other: &Lol) -> bool { **self == **other }
}
fn main() {
if Lol(2) == Lol(4) {
println!("2 == 4");
} else {
println!("2!= 4");
}
} | // 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 | random_line_split |
gate.rs | // ignore-arm
// ignore-aarch64
// ignore-wasm
// ignore-emscripten
// ignore-mips
// ignore-mips64
// ignore-powerpc
// ignore-powerpc64
// ignore-powerpc64le
// ignore-riscv64
// ignore-sparc
// ignore-sparc64
// ignore-s390x
// gate-test-sse4a_target_feature
// gate-test-powerpc_target_feature
// gate-test-avx512_target_feature
// gate-test-tbm_target_feature
// gate-test-arm_target_feature
// gate-test-aarch64_target_feature
// gate-test-hexagon_target_feature
// gate-test-mips_target_feature
// gate-test-wasm_target_feature
// gate-test-adx_target_feature
// gate-test-cmpxchg16b_target_feature
// gate-test-movbe_target_feature
// gate-test-rtm_target_feature
// gate-test-f16c_target_feature
// gate-test-riscv_target_feature
// gate-test-ermsb_target_feature
// gate-test-bpf_target_feature
#[target_feature(enable = "avx512bw")]
//~^ ERROR: currently unstable
unsafe fn foo() |
fn main() {}
| {} | identifier_body |
gate.rs | // ignore-arm
// ignore-aarch64
// ignore-wasm
// ignore-emscripten
// ignore-mips
// ignore-mips64
// ignore-powerpc
// ignore-powerpc64
// ignore-powerpc64le | // gate-test-powerpc_target_feature
// gate-test-avx512_target_feature
// gate-test-tbm_target_feature
// gate-test-arm_target_feature
// gate-test-aarch64_target_feature
// gate-test-hexagon_target_feature
// gate-test-mips_target_feature
// gate-test-wasm_target_feature
// gate-test-adx_target_feature
// gate-test-cmpxchg16b_target_feature
// gate-test-movbe_target_feature
// gate-test-rtm_target_feature
// gate-test-f16c_target_feature
// gate-test-riscv_target_feature
// gate-test-ermsb_target_feature
// gate-test-bpf_target_feature
#[target_feature(enable = "avx512bw")]
//~^ ERROR: currently unstable
unsafe fn foo() {}
fn main() {} | // ignore-riscv64
// ignore-sparc
// ignore-sparc64
// ignore-s390x
// gate-test-sse4a_target_feature | random_line_split |
gate.rs | // ignore-arm
// ignore-aarch64
// ignore-wasm
// ignore-emscripten
// ignore-mips
// ignore-mips64
// ignore-powerpc
// ignore-powerpc64
// ignore-powerpc64le
// ignore-riscv64
// ignore-sparc
// ignore-sparc64
// ignore-s390x
// gate-test-sse4a_target_feature
// gate-test-powerpc_target_feature
// gate-test-avx512_target_feature
// gate-test-tbm_target_feature
// gate-test-arm_target_feature
// gate-test-aarch64_target_feature
// gate-test-hexagon_target_feature
// gate-test-mips_target_feature
// gate-test-wasm_target_feature
// gate-test-adx_target_feature
// gate-test-cmpxchg16b_target_feature
// gate-test-movbe_target_feature
// gate-test-rtm_target_feature
// gate-test-f16c_target_feature
// gate-test-riscv_target_feature
// gate-test-ermsb_target_feature
// gate-test-bpf_target_feature
#[target_feature(enable = "avx512bw")]
//~^ ERROR: currently unstable
unsafe fn | () {}
fn main() {}
| foo | identifier_name |
values.rs | use num::FromPrimitive;
pub const FALSE: u8 = 0;
pub const TRUE: u8 = 1;
/// This gets added to the trainer class when setting CURRENT_OPPONENT
pub const TRAINER_TAG: u8 = 0xC8;
/// Any tile that has a value above this is a menu tile and therefore should be drawn on top of
/// sprites.
pub const MAX_MAP_TILE: u8 = 0x5F;
#[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
pub enum Direction {
Down = 0x0,
Up = 0x4,
Left = 0x8,
Right = 0xC
}
impl FromPrimitive for Direction {
fn from_i64(n: i64) -> Option<Direction> {
match n {
0x0 => Some(Direction::Down),
0x4 => Some(Direction::Up),
0x8 => Some(Direction::Left),
0xC => Some(Direction::Right),
_ => None,
}
}
fn from_u64(n: u64) -> Option<Direction> {
FromPrimitive::from_i64(n as i64)
}
}
pub enum BattleType {
Normal = 0,
OldMan = 1,
Safari = 2,
}
pub enum ActiveBattle {
None = 0,
Wild = 1,
Trainer = 2,
}
pub enum TrainerClass {
Unknown = 0x00,
ProfOak = 0x1A,
} | pub const RYHDON: u8 = 0x01;
pub const WEEDLE: u8 = 0x70;
}
pub mod status {
pub const NONE : u8 = 0;
pub const POISON : u8 = 3;
pub const BURN : u8 = 4;
pub const FREEZE : u8 = 5;
pub const PARALYZE: u8 = 6;
pub const SLEEP : u8 = 7;
}
pub mod types {
pub const NORMAL : u8 = 0x00;
pub const FIGHTING: u8 = 0x01;
pub const FLYING : u8 = 0x02;
pub const POISON : u8 = 0x03;
pub const GROUND : u8 = 0x04;
pub const ROCK : u8 = 0x05;
pub const BUG : u8 = 0x07;
pub const GHOST : u8 = 0x08;
pub const FIRE : u8 = 0x14;
pub const WATER : u8 = 0x15;
pub const GRASS : u8 = 0x16;
pub const ELECTRIC: u8 = 0x17;
pub const PSYCHIC : u8 = 0x18;
pub const ICE : u8 = 0x19;
pub const DRAGON : u8 = 0x1A;
}
pub mod moves {
// TODO: Add more moves
pub const NONE : u8 = 0x00;
pub const POUND : u8 = 0x01;
pub const KARATE_CHOP : u8 = 0x02;
pub const DOUBLESLAP : u8 = 0x03;
pub const COMET_PUNCH : u8 = 0x04;
pub const MEGA_PUNCH : u8 = 0x05;
pub const PAY_DAY : u8 = 0x06;
pub const FIRE_PUNCH : u8 = 0x07;
pub const ICE_PUNCH : u8 = 0x08;
pub const THUNDERPUNCH: u8 = 0x09;
pub const SCRATCH : u8 = 0x0a;
pub const VICEGRIP : u8 = 0x0b;
pub const GUILLOTINE : u8 = 0x0c;
pub const RAZOR_WIND : u8 = 0x0d;
pub const SWORDS_DANCE: u8 = 0x0e;
pub const CUT : u8 = 0x0f;
} |
pub mod pokeid {
// TODO: Add more pokemon | random_line_split |
values.rs | use num::FromPrimitive;
pub const FALSE: u8 = 0;
pub const TRUE: u8 = 1;
/// This gets added to the trainer class when setting CURRENT_OPPONENT
pub const TRAINER_TAG: u8 = 0xC8;
/// Any tile that has a value above this is a menu tile and therefore should be drawn on top of
/// sprites.
pub const MAX_MAP_TILE: u8 = 0x5F;
#[derive(Copy, Clone, Debug, PartialEq, Eq, RustcEncodable, RustcDecodable)]
pub enum Direction {
Down = 0x0,
Up = 0x4,
Left = 0x8,
Right = 0xC
}
impl FromPrimitive for Direction {
fn | (n: i64) -> Option<Direction> {
match n {
0x0 => Some(Direction::Down),
0x4 => Some(Direction::Up),
0x8 => Some(Direction::Left),
0xC => Some(Direction::Right),
_ => None,
}
}
fn from_u64(n: u64) -> Option<Direction> {
FromPrimitive::from_i64(n as i64)
}
}
pub enum BattleType {
Normal = 0,
OldMan = 1,
Safari = 2,
}
pub enum ActiveBattle {
None = 0,
Wild = 1,
Trainer = 2,
}
pub enum TrainerClass {
Unknown = 0x00,
ProfOak = 0x1A,
}
pub mod pokeid {
// TODO: Add more pokemon
pub const RYHDON: u8 = 0x01;
pub const WEEDLE: u8 = 0x70;
}
pub mod status {
pub const NONE : u8 = 0;
pub const POISON : u8 = 3;
pub const BURN : u8 = 4;
pub const FREEZE : u8 = 5;
pub const PARALYZE: u8 = 6;
pub const SLEEP : u8 = 7;
}
pub mod types {
pub const NORMAL : u8 = 0x00;
pub const FIGHTING: u8 = 0x01;
pub const FLYING : u8 = 0x02;
pub const POISON : u8 = 0x03;
pub const GROUND : u8 = 0x04;
pub const ROCK : u8 = 0x05;
pub const BUG : u8 = 0x07;
pub const GHOST : u8 = 0x08;
pub const FIRE : u8 = 0x14;
pub const WATER : u8 = 0x15;
pub const GRASS : u8 = 0x16;
pub const ELECTRIC: u8 = 0x17;
pub const PSYCHIC : u8 = 0x18;
pub const ICE : u8 = 0x19;
pub const DRAGON : u8 = 0x1A;
}
pub mod moves {
// TODO: Add more moves
pub const NONE : u8 = 0x00;
pub const POUND : u8 = 0x01;
pub const KARATE_CHOP : u8 = 0x02;
pub const DOUBLESLAP : u8 = 0x03;
pub const COMET_PUNCH : u8 = 0x04;
pub const MEGA_PUNCH : u8 = 0x05;
pub const PAY_DAY : u8 = 0x06;
pub const FIRE_PUNCH : u8 = 0x07;
pub const ICE_PUNCH : u8 = 0x08;
pub const THUNDERPUNCH: u8 = 0x09;
pub const SCRATCH : u8 = 0x0a;
pub const VICEGRIP : u8 = 0x0b;
pub const GUILLOTINE : u8 = 0x0c;
pub const RAZOR_WIND : u8 = 0x0d;
pub const SWORDS_DANCE: u8 = 0x0e;
pub const CUT : u8 = 0x0f;
}
| from_i64 | identifier_name |
htmlparagraphelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::HTMLParagraphElementBinding;
use crate::dom::bindings::root::DomRoot;
use crate::dom::document::Document;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::node::Node;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom_struct]
pub struct HTMLParagraphElement {
htmlelement: HTMLElement,
}
impl HTMLParagraphElement {
fn new_inherited(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> HTMLParagraphElement {
HTMLParagraphElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLParagraphElement> |
}
| {
Node::reflect_node(
Box::new(HTMLParagraphElement::new_inherited(
local_name, prefix, document,
)),
document,
HTMLParagraphElementBinding::Wrap,
)
} | identifier_body |
htmlparagraphelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::HTMLParagraphElementBinding;
use crate::dom::bindings::root::DomRoot;
use crate::dom::document::Document;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::node::Node;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom_struct]
pub struct HTMLParagraphElement {
htmlelement: HTMLElement,
}
impl HTMLParagraphElement {
fn new_inherited(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> HTMLParagraphElement {
HTMLParagraphElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn | (
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLParagraphElement> {
Node::reflect_node(
Box::new(HTMLParagraphElement::new_inherited(
local_name, prefix, document,
)),
document,
HTMLParagraphElementBinding::Wrap,
)
}
}
| new | identifier_name |
htmlparagraphelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::codegen::Bindings::HTMLParagraphElementBinding;
use crate::dom::bindings::root::DomRoot;
use crate::dom::document::Document;
use crate::dom::htmlelement::HTMLElement;
use crate::dom::node::Node;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
#[dom_struct]
pub struct HTMLParagraphElement {
htmlelement: HTMLElement,
} | document: &Document,
) -> HTMLParagraphElement {
HTMLParagraphElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(
local_name: LocalName,
prefix: Option<Prefix>,
document: &Document,
) -> DomRoot<HTMLParagraphElement> {
Node::reflect_node(
Box::new(HTMLParagraphElement::new_inherited(
local_name, prefix, document,
)),
document,
HTMLParagraphElementBinding::Wrap,
)
}
} |
impl HTMLParagraphElement {
fn new_inherited(
local_name: LocalName,
prefix: Option<Prefix>, | random_line_split |
lib.rs | //! `xxcalc` is a crate which provides an embeddable floating-point
//! polynomial calculator and linear solver.
//!
//! You can use `xxcalc` to embed mathematical expression evaluator
//! in your own programs. By default the calculator provides addition `+`,
//! subtraction `-`, multiplication `*`, division `/` and exponentation `^`
//! operators. Some functions such as `log` and `log10` are implemented,
//! as well as `pi` and `e` constants. This is a polynomial calculator, so
//! you can perform arithmetic operations on polynomials (using `x` symbol
//! by default) - a simple floating-point number is just a special case of
//! a polynomial (the constant polynomial, polynomial of degree zero).
//!
//! Furthermore the crate is well structurized and documented - you can use
//! pieces it provides to create your own custom solutions (you can use or change
//! a tokenizer, parser and evaluator however you want). Look at implementations
//! of `PolynomialParser`, `LinearSolverParser`, `PolynomialEvaluator` or
//! `LinearSolverEvaluator` to see how to extend default implementations.
//!
//! With the crate a `xxcalc` binary is provided which can be used as a
//! standalone CLI calculator (which can be replacement for `bc` command).
//! If the crate is installed with a feature "interactive" enabled, a history
//! of commands is enabled.
//!
//! Whole library is meticulously tested, use `cargo test` to run unit tests
//! (including doc examples), `cargo bench` will run simple benchmarks, while
//! `cargo bench -- --ignored` will run more computation-heavy benchmarks.
//!
//! # Examples
//!
//! You can easily take a `LinearSolver` or `PolynomialCalculator` to embed
//! mathematical engine inside your programs.
//!
//! ```
//! use xxcalc::linear_solver::LinearSolver;
//! use xxcalc::calculator::Calculator;
//! use xxcalc::polynomial::Polynomial;
//!
//! assert_eq!(LinearSolver.process("2x + 1 = 2(1-x)"), Ok(Polynomial::constant(0.25)));
//! assert_eq!(LinearSolver.process("0.1*-2+4"), Ok(Polynomial::constant(3.8)));
//! ```
//!
//! Please see documentation for [`PolynomialCalculator`] for more examples.
//!
//! [`PolynomialCalculator`]: polynomial_calculator/index.html
pub mod polynomial;
#[macro_use]
pub mod tokenizer;
pub mod parser;
pub mod evaluator;
pub mod calculator;
pub mod polynomial_calculator;
pub mod linear_solver;
use std::ops::Index;
use std::collections::BTreeMap;
/// `Token` is a basic unit returned after tokenization using
/// a `StringProcessor`.
///
/// `Token` can be than rearranged with a `TokensProcessor` and
/// interpreted (evaluated) to a `Polynomial` using a `TokensReducer`.
///
/// Tokens are used to conveniently store expressions in partially
/// parsed and computer readable form.
#[derive(Debug, PartialEq, Clone)]
pub enum Token {
/// Opening bracket `(` or beginning of subexpression
BracketOpening,
/// Closing bracket `)` or ending of subexpression
BracketClosing,
/// Argument separator
Separator,
/// Floating point number
Number(f64),
/// Single character operator
Operator(char),
/// Symbol identifier (represented by index in identifiers table)
Identifier(usize),
/// Unidentified character (with no meaning to a StringProcessor)
Unknown(char),
/// Skip marker
Skip
} | /// List of tokens with their position.
///
/// Tokens are represented as space-efficient continous vector
/// of tuples consisting of position in a input string and a
/// corresponding Token.
pub type TokenList = Vec<(usize, Token)>;
/// Vector of unique identifiers.
///
/// `Token::Identifier` stores just a location in this vector,
/// this keeps size of individual tokens minimal.
pub type Identifiers = Vec<String>;
/// `Tokens` is a compound storage for list of tokens with
/// their identifiers.
///
/// A `TokenList` is invalid without Identifiers, therefore
/// this struct keeps them always together. Furthermore
/// a lookup table is kept, so creating new identifier is
/// a relatively quick task.
#[derive(Debug)]
pub struct Tokens {
/// List of tokens
pub tokens: TokenList,
/// Identifier strings used in `Token::Identifier`
pub identifiers: Identifiers,
lookup: BTreeMap<String, usize>
}
/// Transforms text expression into list of tokens.
///
/// A `StringProcessor` can be implemented for a tokenizer (lexer)
/// which converts some text expression into a list of tokens.
pub trait StringProcessor {
fn process(self: &mut Self, line: &str) -> &Tokens;
}
/// Transforms list of tokens into another list of tokens.
///
/// A `TokensProcessor` can be implemented for a parser which
/// takes a list of tokens in some order and transform them
/// into list of tokens in the other form (like infix to
/// RPN notation). Furthermore a `TokensProcessor` can be used
/// to extend tokenizer with knowledge of new tokens, as it
/// can transform unknown tokens to known ones.
pub trait TokensProcessor {
fn process(&mut self, tokens: &Tokens) -> Result<&Tokens, ParsingError>;
}
/// Evaluates list of tokens into a single Polynomial value.
///
/// A `TokensReducer` takes a list of tokens in some expected
/// arrangement and evaluates them into a single Polynomial
/// value. It can be used for implementation of various
/// computational languages (such as the scientific calcualtor).
pub trait TokensReducer {
fn process(&self, tokens: &Tokens) -> Result<polynomial::Polynomial, EvaluationError>;
}
/// Returns position and token with given index.
///
/// One should note that token position is indepentent
/// from its index.
///
/// # Panics
///
/// It will panic when the index is greater than number of
/// tokens stored in the list.
///
/// # Examples
///
/// ```
/// # use xxcalc::{Tokens, Token};
/// let mut tokens = Tokens::new(None);
///
/// tokens.push(0, Token::Number(1.0));
/// tokens.push(8, Token::Number(2.0));
///
/// assert_eq!(tokens[0], (0, Token::Number(1.0)));
/// assert_eq!(tokens[1], (8, Token::Number(2.0)));
/// ```
impl Index<usize> for Tokens {
type Output = (usize, Token);
fn index(&self, idx: usize) -> &(usize, Token) {
&self.tokens[idx]
}
}
impl Tokens {
/// Creates a new token storage with optional capacity of
/// identifiers.
pub fn new(i_cap: Option<usize>) -> Tokens {
Tokens {
tokens: TokenList::with_capacity(10),
identifiers: Identifiers::with_capacity(i_cap.unwrap_or(0)),
lookup: BTreeMap::new()
}
}
/// Clears tokens list, however underlying identifiers vector and
/// its lookup cache is not cleared, as identifiers may be reused.
#[inline(always)]
pub fn clear(&mut self) {
self.tokens.clear()
}
/// Pushes a token (with its position) to the end of token list.
///
/// # Examples
///
/// ```
/// # use xxcalc::{Tokens, Token};
/// let mut tokens = Tokens::new(None);
///
/// tokens.push(0, Token::Number(1.0));
/// assert_eq!(tokens.tokens.len(), 1);
///
/// tokens.push(1, Token::Number(2.0));
/// assert_eq!(tokens.tokens.len(), 2);
/// ```
#[inline(always)]
pub fn push(&mut self, position: usize, token: Token) {
self.tokens.push((position, token))
}
/// Pushes a identifier (with its position) to the end of token list.
///
/// Using a lookup cache, an offset in identifier table is obtained.
/// If identifier does not yet exist, it is added both to the identifier
/// vector and to the lookup cache. Identifiers are case-agnostic.
/// A Token::Identifier with appropriate offset is pushed to the end
/// of the token list.
///
/// # Examples
///
/// ```
/// # use xxcalc::{Tokens, Token};
/// let mut tokens = Tokens::new(None);
///
/// tokens.push_identifier(0, &String::from("FOO"));
/// assert_eq!(tokens[0], (0, Token::Identifier(0)));
/// tokens.push_identifier(4, &String::from("foo"));
/// assert_eq!(tokens[1], (4, Token::Identifier(0)));
/// tokens.push_identifier(8, &String::from("bar"));
/// assert_eq!(tokens[2], (8, Token::Identifier(1)));
/// assert_eq!(tokens.identifiers, ["foo", "bar"]);
/// ```
#[inline]
pub fn push_identifier(&mut self, position: usize, value: &str) {
let idx = if let Some(&id) = self.lookup.get(value) {
id
} else
if let Some(&id) = self.lookup.get(&value.to_lowercase()) {
let _ = self.lookup.insert(value.to_owned(), id);
id
} else {
let _ = self.lookup.insert(value.to_lowercase(), self.identifiers.len());
self.identifiers.push(value.to_lowercase());
self.identifiers.len() - 1
};
self.push(position, Token::Identifier(idx));
}
}
/// An error that occurs during token processing,
/// usually by a parser.
#[derive(Debug, PartialEq)]
pub enum ParsingError {
/// Encountered an operator which is not recognized by a parser.
/// The operator is a first argument, while its position is the last one.
UnknownOperator(char, usize),
/// Encountered a Token with no meaning to the parser,
/// probably a Token::Unknown. This token is a first argument, while its
/// position is the last one.
UnexpectedToken(Token, usize),
/// Detected a missing opening or closing bracket at given position.
MissingBracket(usize),
/// Provided token list is empty, where expected it shouldn't be so.
EmptyExpression
}
/// An error that occurs during token reduction,
/// usually by an evaluator.
#[derive(Debug, PartialEq)]
pub enum EvaluationError {
/// Encountered an operator, a constant or a function with no meaning
/// to the evaluator. Most probably such symbol must be registered
/// beforehand. The identifier is a first argument, while its position
/// is the last one.
UnknownSymbol(String, usize),
/// Number of provided arguments for a function or an operator are not
/// enough (the function is registered with larger arity). The symbol
/// is a first argument, expected arity is a second argument, while the
/// position is the last one.
ArgumentMissing(String, usize, usize),
/// Multiple expressions where encountered, where not expected (as in
/// too many arguments or too many complete expressions).
MultipleExpressions,
/// A symbol with given name is conflicting with already registered
/// function or constant.
ConflictingName(String),
/// Wraps polynomial error which could be encountered during the evaluation
/// as result of some mathematical operation.
PolynomialError(polynomial::PolynomialError),
/// Wraps linear solver error which could be encountered when assumptions
/// needed for solving are not met.
SolvingError(linear_solver::SolvingError),
/// Used when exponent is of greater degree than zero. Result of such
/// exponentiation would not be a polynomial anylonger.
NonConstantExponent,
/// Used when exponent is not a natural number, while the base of
/// exponentiation is not a constant. Result of such operations would
/// not be a polynomial anylonger.
NonNaturalExponent
} | random_line_split | |
lib.rs | //! `xxcalc` is a crate which provides an embeddable floating-point
//! polynomial calculator and linear solver.
//!
//! You can use `xxcalc` to embed mathematical expression evaluator
//! in your own programs. By default the calculator provides addition `+`,
//! subtraction `-`, multiplication `*`, division `/` and exponentation `^`
//! operators. Some functions such as `log` and `log10` are implemented,
//! as well as `pi` and `e` constants. This is a polynomial calculator, so
//! you can perform arithmetic operations on polynomials (using `x` symbol
//! by default) - a simple floating-point number is just a special case of
//! a polynomial (the constant polynomial, polynomial of degree zero).
//!
//! Furthermore the crate is well structurized and documented - you can use
//! pieces it provides to create your own custom solutions (you can use or change
//! a tokenizer, parser and evaluator however you want). Look at implementations
//! of `PolynomialParser`, `LinearSolverParser`, `PolynomialEvaluator` or
//! `LinearSolverEvaluator` to see how to extend default implementations.
//!
//! With the crate a `xxcalc` binary is provided which can be used as a
//! standalone CLI calculator (which can be replacement for `bc` command).
//! If the crate is installed with a feature "interactive" enabled, a history
//! of commands is enabled.
//!
//! Whole library is meticulously tested, use `cargo test` to run unit tests
//! (including doc examples), `cargo bench` will run simple benchmarks, while
//! `cargo bench -- --ignored` will run more computation-heavy benchmarks.
//!
//! # Examples
//!
//! You can easily take a `LinearSolver` or `PolynomialCalculator` to embed
//! mathematical engine inside your programs.
//!
//! ```
//! use xxcalc::linear_solver::LinearSolver;
//! use xxcalc::calculator::Calculator;
//! use xxcalc::polynomial::Polynomial;
//!
//! assert_eq!(LinearSolver.process("2x + 1 = 2(1-x)"), Ok(Polynomial::constant(0.25)));
//! assert_eq!(LinearSolver.process("0.1*-2+4"), Ok(Polynomial::constant(3.8)));
//! ```
//!
//! Please see documentation for [`PolynomialCalculator`] for more examples.
//!
//! [`PolynomialCalculator`]: polynomial_calculator/index.html
pub mod polynomial;
#[macro_use]
pub mod tokenizer;
pub mod parser;
pub mod evaluator;
pub mod calculator;
pub mod polynomial_calculator;
pub mod linear_solver;
use std::ops::Index;
use std::collections::BTreeMap;
/// `Token` is a basic unit returned after tokenization using
/// a `StringProcessor`.
///
/// `Token` can be than rearranged with a `TokensProcessor` and
/// interpreted (evaluated) to a `Polynomial` using a `TokensReducer`.
///
/// Tokens are used to conveniently store expressions in partially
/// parsed and computer readable form.
#[derive(Debug, PartialEq, Clone)]
pub enum Token {
/// Opening bracket `(` or beginning of subexpression
BracketOpening,
/// Closing bracket `)` or ending of subexpression
BracketClosing,
/// Argument separator
Separator,
/// Floating point number
Number(f64),
/// Single character operator
Operator(char),
/// Symbol identifier (represented by index in identifiers table)
Identifier(usize),
/// Unidentified character (with no meaning to a StringProcessor)
Unknown(char),
/// Skip marker
Skip
}
/// List of tokens with their position.
///
/// Tokens are represented as space-efficient continous vector
/// of tuples consisting of position in a input string and a
/// corresponding Token.
pub type TokenList = Vec<(usize, Token)>;
/// Vector of unique identifiers.
///
/// `Token::Identifier` stores just a location in this vector,
/// this keeps size of individual tokens minimal.
pub type Identifiers = Vec<String>;
/// `Tokens` is a compound storage for list of tokens with
/// their identifiers.
///
/// A `TokenList` is invalid without Identifiers, therefore
/// this struct keeps them always together. Furthermore
/// a lookup table is kept, so creating new identifier is
/// a relatively quick task.
#[derive(Debug)]
pub struct Tokens {
/// List of tokens
pub tokens: TokenList,
/// Identifier strings used in `Token::Identifier`
pub identifiers: Identifiers,
lookup: BTreeMap<String, usize>
}
/// Transforms text expression into list of tokens.
///
/// A `StringProcessor` can be implemented for a tokenizer (lexer)
/// which converts some text expression into a list of tokens.
pub trait StringProcessor {
fn process(self: &mut Self, line: &str) -> &Tokens;
}
/// Transforms list of tokens into another list of tokens.
///
/// A `TokensProcessor` can be implemented for a parser which
/// takes a list of tokens in some order and transform them
/// into list of tokens in the other form (like infix to
/// RPN notation). Furthermore a `TokensProcessor` can be used
/// to extend tokenizer with knowledge of new tokens, as it
/// can transform unknown tokens to known ones.
pub trait TokensProcessor {
fn process(&mut self, tokens: &Tokens) -> Result<&Tokens, ParsingError>;
}
/// Evaluates list of tokens into a single Polynomial value.
///
/// A `TokensReducer` takes a list of tokens in some expected
/// arrangement and evaluates them into a single Polynomial
/// value. It can be used for implementation of various
/// computational languages (such as the scientific calcualtor).
pub trait TokensReducer {
fn process(&self, tokens: &Tokens) -> Result<polynomial::Polynomial, EvaluationError>;
}
/// Returns position and token with given index.
///
/// One should note that token position is indepentent
/// from its index.
///
/// # Panics
///
/// It will panic when the index is greater than number of
/// tokens stored in the list.
///
/// # Examples
///
/// ```
/// # use xxcalc::{Tokens, Token};
/// let mut tokens = Tokens::new(None);
///
/// tokens.push(0, Token::Number(1.0));
/// tokens.push(8, Token::Number(2.0));
///
/// assert_eq!(tokens[0], (0, Token::Number(1.0)));
/// assert_eq!(tokens[1], (8, Token::Number(2.0)));
/// ```
impl Index<usize> for Tokens {
type Output = (usize, Token);
fn index(&self, idx: usize) -> &(usize, Token) {
&self.tokens[idx]
}
}
impl Tokens {
/// Creates a new token storage with optional capacity of
/// identifiers.
pub fn new(i_cap: Option<usize>) -> Tokens {
Tokens {
tokens: TokenList::with_capacity(10),
identifiers: Identifiers::with_capacity(i_cap.unwrap_or(0)),
lookup: BTreeMap::new()
}
}
/// Clears tokens list, however underlying identifiers vector and
/// its lookup cache is not cleared, as identifiers may be reused.
#[inline(always)]
pub fn clear(&mut self) {
self.tokens.clear()
}
/// Pushes a token (with its position) to the end of token list.
///
/// # Examples
///
/// ```
/// # use xxcalc::{Tokens, Token};
/// let mut tokens = Tokens::new(None);
///
/// tokens.push(0, Token::Number(1.0));
/// assert_eq!(tokens.tokens.len(), 1);
///
/// tokens.push(1, Token::Number(2.0));
/// assert_eq!(tokens.tokens.len(), 2);
/// ```
#[inline(always)]
pub fn push(&mut self, position: usize, token: Token) {
self.tokens.push((position, token))
}
/// Pushes a identifier (with its position) to the end of token list.
///
/// Using a lookup cache, an offset in identifier table is obtained.
/// If identifier does not yet exist, it is added both to the identifier
/// vector and to the lookup cache. Identifiers are case-agnostic.
/// A Token::Identifier with appropriate offset is pushed to the end
/// of the token list.
///
/// # Examples
///
/// ```
/// # use xxcalc::{Tokens, Token};
/// let mut tokens = Tokens::new(None);
///
/// tokens.push_identifier(0, &String::from("FOO"));
/// assert_eq!(tokens[0], (0, Token::Identifier(0)));
/// tokens.push_identifier(4, &String::from("foo"));
/// assert_eq!(tokens[1], (4, Token::Identifier(0)));
/// tokens.push_identifier(8, &String::from("bar"));
/// assert_eq!(tokens[2], (8, Token::Identifier(1)));
/// assert_eq!(tokens.identifiers, ["foo", "bar"]);
/// ```
#[inline]
pub fn push_identifier(&mut self, position: usize, value: &str) {
let idx = if let Some(&id) = self.lookup.get(value) {
id
} else
if let Some(&id) = self.lookup.get(&value.to_lowercase()) {
let _ = self.lookup.insert(value.to_owned(), id);
id
} else {
let _ = self.lookup.insert(value.to_lowercase(), self.identifiers.len());
self.identifiers.push(value.to_lowercase());
self.identifiers.len() - 1
};
self.push(position, Token::Identifier(idx));
}
}
/// An error that occurs during token processing,
/// usually by a parser.
#[derive(Debug, PartialEq)]
pub enum ParsingError {
/// Encountered an operator which is not recognized by a parser.
/// The operator is a first argument, while its position is the last one.
UnknownOperator(char, usize),
/// Encountered a Token with no meaning to the parser,
/// probably a Token::Unknown. This token is a first argument, while its
/// position is the last one.
UnexpectedToken(Token, usize),
/// Detected a missing opening or closing bracket at given position.
MissingBracket(usize),
/// Provided token list is empty, where expected it shouldn't be so.
EmptyExpression
}
/// An error that occurs during token reduction,
/// usually by an evaluator.
#[derive(Debug, PartialEq)]
pub enum | {
/// Encountered an operator, a constant or a function with no meaning
/// to the evaluator. Most probably such symbol must be registered
/// beforehand. The identifier is a first argument, while its position
/// is the last one.
UnknownSymbol(String, usize),
/// Number of provided arguments for a function or an operator are not
/// enough (the function is registered with larger arity). The symbol
/// is a first argument, expected arity is a second argument, while the
/// position is the last one.
ArgumentMissing(String, usize, usize),
/// Multiple expressions where encountered, where not expected (as in
/// too many arguments or too many complete expressions).
MultipleExpressions,
/// A symbol with given name is conflicting with already registered
/// function or constant.
ConflictingName(String),
/// Wraps polynomial error which could be encountered during the evaluation
/// as result of some mathematical operation.
PolynomialError(polynomial::PolynomialError),
/// Wraps linear solver error which could be encountered when assumptions
/// needed for solving are not met.
SolvingError(linear_solver::SolvingError),
/// Used when exponent is of greater degree than zero. Result of such
/// exponentiation would not be a polynomial anylonger.
NonConstantExponent,
/// Used when exponent is not a natural number, while the base of
/// exponentiation is not a constant. Result of such operations would
/// not be a polynomial anylonger.
NonNaturalExponent
} | EvaluationError | identifier_name |
dependency_format.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.
//! Resolution of mixing rlibs and dylibs
//!
//! When producing a final artifact, such as a dynamic library, the compiler has
//! a choice between linking an rlib or linking a dylib of all upstream
//! dependencies. The linking phase must guarantee, however, that a library only
//! show up once in the object file. For example, it is illegal for library A to
//! be statically linked to B and C in separate dylibs, and then link B and C
//! into a crate D (because library A appears twice).
//!
//! The job of this module is to calculate what format each upstream crate
//! should be used when linking each output type requested in this session. This
//! generally follows this set of rules:
//!
//! 1. Each library must appear exactly once in the output.
//! 2. Each rlib contains only one library (it's just an object file)
//! 3. Each dylib can contain more than one library (due to static linking),
//! and can also bring in many dynamic dependencies.
//!
//! With these constraints in mind, it's generally a very difficult problem to
//! find a solution that's not "all rlibs" or "all dylibs". I have suspicions
//! that NP-ness may come into the picture here...
//!
//! The current selection algorithm below looks mostly similar to:
//!
//! 1. If static linking is required, then require all upstream dependencies
//! to be available as rlibs. If not, generate an error.
//! 2. If static linking is requested (generating an executable), then
//! attempt to use all upstream dependencies as rlibs. If any are not
//! found, bail out and continue to step 3.
//! 3. Static linking has failed, at least one library must be dynamically
//! linked. Apply a heuristic by greedily maximizing the number of
//! dynamically linked libraries.
//! 4. Each upstream dependency available as a dynamic library is
//! registered. The dependencies all propagate, adding to a map. It is
//! possible for a dylib to add a static library as a dependency, but it
//! is illegal for two dylibs to add the same static library as a
//! dependency. The same dylib can be added twice. Additionally, it is
//! illegal to add a static dependency when it was previously found as a
//! dylib (and vice versa)
//! 5. After all dynamic dependencies have been traversed, re-traverse the
//! remaining dependencies and add them statically (if they haven't been
//! added already).
//!
//! While not perfect, this algorithm should help support use-cases such as leaf
//! dependencies being static while the larger tree of inner dependencies are
//! all dynamic. This isn't currently very well battle tested, so it will likely
//! fall short in some use cases.
//!
//! Currently, there is no way to specify the preference of linkage with a
//! particular library (other than a global dynamic/static switch).
//! Additionally, the algorithm is geared towards finding *any* solution rather
//! than finding a number of solutions (there are normally quite a few).
use syntax::ast;
use session;
use session::config;
use metadata::cstore;
use metadata::csearch;
use middle::ty;
use util::nodemap::FnvHashMap;
/// A list of dependencies for a certain crate type.
///
/// The length of this vector is the same as the number of external crates used.
/// The value is None if the crate does not need to be linked (it was found
/// statically in another dylib), or Some(kind) if it needs to be linked as
/// `kind` (either static or dynamic).
pub type DependencyList = Vec<Option<cstore::LinkagePreference>>;
/// A mapping of all required dependencies for a particular flavor of output.
///
/// This is local to the tcx, and is generally relevant to one session.
pub type Dependencies = FnvHashMap<config::CrateType, DependencyList>;
pub fn calculate(tcx: &ty::ctxt) {
let mut fmts = tcx.dependency_formats.borrow_mut();
for &ty in &*tcx.sess.crate_types.borrow() {
fmts.insert(ty, calculate_type(&tcx.sess, ty));
}
tcx.sess.abort_if_errors();
}
fn calculate_type(sess: &session::Session,
ty: config::CrateType) -> DependencyList {
match ty {
// If the global prefer_dynamic switch is turned off, first attempt
// static linkage (this can fail).
config::CrateTypeExecutable if!sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
}
// No linkage happens with rlibs, we just needed the metadata (which we
// got long ago), so don't bother with anything.
config::CrateTypeRlib => return Vec::new(),
// Staticlibs must have all static dependencies. If any fail to be
// found, we generate some nice pretty errors.
config::CrateTypeStaticlib => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.rlib.is_some() { return }
sess.err(&format!("dependency `{}` not found in rlib format",
data.name));
});
return Vec::new();
}
// Generating a dylib without `-C prefer-dynamic` means that we're going
// to try to eagerly statically link all dependencies. This is normally
// done for end-product dylibs, not intermediate products.
config::CrateTypeDylib if!sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
}
// Everything else falls through below
config::CrateTypeExecutable | config::CrateTypeDylib => {},
}
let mut formats = FnvHashMap();
// Sweep all crates for found dylibs. Add all dylibs, as well as their
// dependencies, ensuring there are no conflicts. The only valid case for a
// dependency to be relied upon twice is for both cases to rely on a dylib.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_some() {
debug!("adding dylib: {}", data.name);
add_library(sess, cnum, cstore::RequireDynamic, &mut formats);
let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum);
for &(depnum, style) in &deps {
debug!("adding {:?}: {}", style,
sess.cstore.get_crate_data(depnum).name.clone());
add_library(sess, depnum, style, &mut formats);
}
}
});
// Collect what we've got so far in the return vector.
let mut ret = (1..sess.cstore.next_crate_num()).map(|i| {
match formats.get(&i).cloned() {
v @ Some(cstore::RequireDynamic) => v,
_ => None,
}
}).collect::<Vec<_>>();
// Run through the dependency list again, and add any missing libraries as
// static libraries.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_none() &&!formats.contains_key(&cnum) {
assert!(src.rlib.is_some());
debug!("adding staticlib: {}", data.name);
add_library(sess, cnum, cstore::RequireStatic, &mut formats);
ret[cnum as usize - 1] = Some(cstore::RequireStatic);
}
});
// When dylib B links to dylib A, then when using B we must also link to A.
// It could be the case, however, that the rlib for A is present (hence we
// found metadata), but the dylib for A has since been removed.
//
// For situations like this, we perform one last pass over the dependencies,
// making sure that everything is available in the requested format.
for (cnum, kind) in ret.iter().enumerate() {
let cnum = cnum as ast::CrateNum;
let src = sess.cstore.get_used_crate_source(cnum + 1).unwrap();
match *kind {
None => continue,
Some(cstore::RequireStatic) if src.rlib.is_some() => continue,
Some(cstore::RequireDynamic) if src.dylib.is_some() => continue,
Some(kind) => {
let data = sess.cstore.get_crate_data(cnum + 1);
sess.err(&format!("crate `{}` required to be available in {}, \
but it was not available in this form",
data.name,
match kind {
cstore::RequireStatic => "rlib",
cstore::RequireDynamic => "dylib",
}));
}
}
}
return ret;
}
fn | (sess: &session::Session,
cnum: ast::CrateNum,
link: cstore::LinkagePreference,
m: &mut FnvHashMap<ast::CrateNum, cstore::LinkagePreference>) {
match m.get(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are both static, then we
// would also have two copies of the library (static from two
// different locations).
//
// This error is probably a little obscure, but I imagine that it
// can be refined over time.
if link2!= link || link == cstore::RequireStatic {
let data = sess.cstore.get_crate_data(cnum);
sess.err(&format!("cannot satisfy dependencies so `{}` only \
shows up once",
data.name));
sess.help("having upstream crates all available in one format \
will likely make this go away");
}
}
None => { m.insert(cnum, link); }
}
}
fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
if crates.iter().by_ref().all(|&(_, ref p)| p.is_some()) {
Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())
} else {
None
}
}
| add_library | identifier_name |
dependency_format.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.
//! Resolution of mixing rlibs and dylibs
//!
//! When producing a final artifact, such as a dynamic library, the compiler has
//! a choice between linking an rlib or linking a dylib of all upstream
//! dependencies. The linking phase must guarantee, however, that a library only
//! show up once in the object file. For example, it is illegal for library A to
//! be statically linked to B and C in separate dylibs, and then link B and C
//! into a crate D (because library A appears twice).
//!
//! The job of this module is to calculate what format each upstream crate
//! should be used when linking each output type requested in this session. This
//! generally follows this set of rules:
//!
//! 1. Each library must appear exactly once in the output.
//! 2. Each rlib contains only one library (it's just an object file)
//! 3. Each dylib can contain more than one library (due to static linking),
//! and can also bring in many dynamic dependencies.
//!
//! With these constraints in mind, it's generally a very difficult problem to
//! find a solution that's not "all rlibs" or "all dylibs". I have suspicions
//! that NP-ness may come into the picture here...
//!
//! The current selection algorithm below looks mostly similar to:
//!
//! 1. If static linking is required, then require all upstream dependencies
//! to be available as rlibs. If not, generate an error.
//! 2. If static linking is requested (generating an executable), then
//! attempt to use all upstream dependencies as rlibs. If any are not
//! found, bail out and continue to step 3.
//! 3. Static linking has failed, at least one library must be dynamically
//! linked. Apply a heuristic by greedily maximizing the number of
//! dynamically linked libraries.
//! 4. Each upstream dependency available as a dynamic library is
//! registered. The dependencies all propagate, adding to a map. It is
//! possible for a dylib to add a static library as a dependency, but it
//! is illegal for two dylibs to add the same static library as a
//! dependency. The same dylib can be added twice. Additionally, it is
//! illegal to add a static dependency when it was previously found as a
//! dylib (and vice versa)
//! 5. After all dynamic dependencies have been traversed, re-traverse the
//! remaining dependencies and add them statically (if they haven't been
//! added already).
//!
//! While not perfect, this algorithm should help support use-cases such as leaf
//! dependencies being static while the larger tree of inner dependencies are
//! all dynamic. This isn't currently very well battle tested, so it will likely
//! fall short in some use cases.
//!
//! Currently, there is no way to specify the preference of linkage with a
//! particular library (other than a global dynamic/static switch).
//! Additionally, the algorithm is geared towards finding *any* solution rather
//! than finding a number of solutions (there are normally quite a few).
use syntax::ast;
use session;
use session::config;
use metadata::cstore;
use metadata::csearch;
use middle::ty;
use util::nodemap::FnvHashMap;
/// A list of dependencies for a certain crate type.
///
/// The length of this vector is the same as the number of external crates used.
/// The value is None if the crate does not need to be linked (it was found
/// statically in another dylib), or Some(kind) if it needs to be linked as
/// `kind` (either static or dynamic).
pub type DependencyList = Vec<Option<cstore::LinkagePreference>>;
/// A mapping of all required dependencies for a particular flavor of output.
///
/// This is local to the tcx, and is generally relevant to one session.
pub type Dependencies = FnvHashMap<config::CrateType, DependencyList>;
pub fn calculate(tcx: &ty::ctxt) {
let mut fmts = tcx.dependency_formats.borrow_mut();
for &ty in &*tcx.sess.crate_types.borrow() {
fmts.insert(ty, calculate_type(&tcx.sess, ty));
}
tcx.sess.abort_if_errors();
}
fn calculate_type(sess: &session::Session,
ty: config::CrateType) -> DependencyList {
match ty {
// If the global prefer_dynamic switch is turned off, first attempt
// static linkage (this can fail).
config::CrateTypeExecutable if!sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
}
// No linkage happens with rlibs, we just needed the metadata (which we
// got long ago), so don't bother with anything.
config::CrateTypeRlib => return Vec::new(),
// Staticlibs must have all static dependencies. If any fail to be
// found, we generate some nice pretty errors.
config::CrateTypeStaticlib => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.rlib.is_some() { return }
sess.err(&format!("dependency `{}` not found in rlib format",
data.name));
});
return Vec::new();
}
// Generating a dylib without `-C prefer-dynamic` means that we're going
// to try to eagerly statically link all dependencies. This is normally
// done for end-product dylibs, not intermediate products.
config::CrateTypeDylib if!sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
}
// Everything else falls through below
config::CrateTypeExecutable | config::CrateTypeDylib => {},
}
let mut formats = FnvHashMap();
// Sweep all crates for found dylibs. Add all dylibs, as well as their
// dependencies, ensuring there are no conflicts. The only valid case for a
// dependency to be relied upon twice is for both cases to rely on a dylib.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_some() {
debug!("adding dylib: {}", data.name);
add_library(sess, cnum, cstore::RequireDynamic, &mut formats);
let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum);
for &(depnum, style) in &deps {
debug!("adding {:?}: {}", style,
sess.cstore.get_crate_data(depnum).name.clone());
add_library(sess, depnum, style, &mut formats);
}
}
});
// Collect what we've got so far in the return vector.
let mut ret = (1..sess.cstore.next_crate_num()).map(|i| {
match formats.get(&i).cloned() {
v @ Some(cstore::RequireDynamic) => v,
_ => None,
}
}).collect::<Vec<_>>();
// Run through the dependency list again, and add any missing libraries as
// static libraries.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_none() &&!formats.contains_key(&cnum) {
assert!(src.rlib.is_some());
debug!("adding staticlib: {}", data.name);
add_library(sess, cnum, cstore::RequireStatic, &mut formats);
ret[cnum as usize - 1] = Some(cstore::RequireStatic);
}
});
// When dylib B links to dylib A, then when using B we must also link to A.
// It could be the case, however, that the rlib for A is present (hence we
// found metadata), but the dylib for A has since been removed.
//
// For situations like this, we perform one last pass over the dependencies,
// making sure that everything is available in the requested format.
for (cnum, kind) in ret.iter().enumerate() {
let cnum = cnum as ast::CrateNum;
let src = sess.cstore.get_used_crate_source(cnum + 1).unwrap();
match *kind {
None => continue,
Some(cstore::RequireStatic) if src.rlib.is_some() => continue,
Some(cstore::RequireDynamic) if src.dylib.is_some() => continue,
Some(kind) => {
let data = sess.cstore.get_crate_data(cnum + 1);
sess.err(&format!("crate `{}` required to be available in {}, \
but it was not available in this form",
data.name,
match kind {
cstore::RequireStatic => "rlib",
cstore::RequireDynamic => "dylib",
}));
}
}
}
return ret;
}
fn add_library(sess: &session::Session,
cnum: ast::CrateNum,
link: cstore::LinkagePreference,
m: &mut FnvHashMap<ast::CrateNum, cstore::LinkagePreference>) {
match m.get(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are both static, then we
// would also have two copies of the library (static from two
// different locations).
//
// This error is probably a little obscure, but I imagine that it
// can be refined over time.
if link2!= link || link == cstore::RequireStatic {
let data = sess.cstore.get_crate_data(cnum);
sess.err(&format!("cannot satisfy dependencies so `{}` only \
shows up once",
data.name));
sess.help("having upstream crates all available in one format \
will likely make this go away"); | }
None => { m.insert(cnum, link); }
}
}
fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
if crates.iter().by_ref().all(|&(_, ref p)| p.is_some()) {
Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())
} else {
None
}
} | } | random_line_split |
dependency_format.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.
//! Resolution of mixing rlibs and dylibs
//!
//! When producing a final artifact, such as a dynamic library, the compiler has
//! a choice between linking an rlib or linking a dylib of all upstream
//! dependencies. The linking phase must guarantee, however, that a library only
//! show up once in the object file. For example, it is illegal for library A to
//! be statically linked to B and C in separate dylibs, and then link B and C
//! into a crate D (because library A appears twice).
//!
//! The job of this module is to calculate what format each upstream crate
//! should be used when linking each output type requested in this session. This
//! generally follows this set of rules:
//!
//! 1. Each library must appear exactly once in the output.
//! 2. Each rlib contains only one library (it's just an object file)
//! 3. Each dylib can contain more than one library (due to static linking),
//! and can also bring in many dynamic dependencies.
//!
//! With these constraints in mind, it's generally a very difficult problem to
//! find a solution that's not "all rlibs" or "all dylibs". I have suspicions
//! that NP-ness may come into the picture here...
//!
//! The current selection algorithm below looks mostly similar to:
//!
//! 1. If static linking is required, then require all upstream dependencies
//! to be available as rlibs. If not, generate an error.
//! 2. If static linking is requested (generating an executable), then
//! attempt to use all upstream dependencies as rlibs. If any are not
//! found, bail out and continue to step 3.
//! 3. Static linking has failed, at least one library must be dynamically
//! linked. Apply a heuristic by greedily maximizing the number of
//! dynamically linked libraries.
//! 4. Each upstream dependency available as a dynamic library is
//! registered. The dependencies all propagate, adding to a map. It is
//! possible for a dylib to add a static library as a dependency, but it
//! is illegal for two dylibs to add the same static library as a
//! dependency. The same dylib can be added twice. Additionally, it is
//! illegal to add a static dependency when it was previously found as a
//! dylib (and vice versa)
//! 5. After all dynamic dependencies have been traversed, re-traverse the
//! remaining dependencies and add them statically (if they haven't been
//! added already).
//!
//! While not perfect, this algorithm should help support use-cases such as leaf
//! dependencies being static while the larger tree of inner dependencies are
//! all dynamic. This isn't currently very well battle tested, so it will likely
//! fall short in some use cases.
//!
//! Currently, there is no way to specify the preference of linkage with a
//! particular library (other than a global dynamic/static switch).
//! Additionally, the algorithm is geared towards finding *any* solution rather
//! than finding a number of solutions (there are normally quite a few).
use syntax::ast;
use session;
use session::config;
use metadata::cstore;
use metadata::csearch;
use middle::ty;
use util::nodemap::FnvHashMap;
/// A list of dependencies for a certain crate type.
///
/// The length of this vector is the same as the number of external crates used.
/// The value is None if the crate does not need to be linked (it was found
/// statically in another dylib), or Some(kind) if it needs to be linked as
/// `kind` (either static or dynamic).
pub type DependencyList = Vec<Option<cstore::LinkagePreference>>;
/// A mapping of all required dependencies for a particular flavor of output.
///
/// This is local to the tcx, and is generally relevant to one session.
pub type Dependencies = FnvHashMap<config::CrateType, DependencyList>;
pub fn calculate(tcx: &ty::ctxt) {
let mut fmts = tcx.dependency_formats.borrow_mut();
for &ty in &*tcx.sess.crate_types.borrow() {
fmts.insert(ty, calculate_type(&tcx.sess, ty));
}
tcx.sess.abort_if_errors();
}
fn calculate_type(sess: &session::Session,
ty: config::CrateType) -> DependencyList | None => {}
}
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.rlib.is_some() { return }
sess.err(&format!("dependency `{}` not found in rlib format",
data.name));
});
return Vec::new();
}
// Generating a dylib without `-C prefer-dynamic` means that we're going
// to try to eagerly statically link all dependencies. This is normally
// done for end-product dylibs, not intermediate products.
config::CrateTypeDylib if!sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
}
// Everything else falls through below
config::CrateTypeExecutable | config::CrateTypeDylib => {},
}
let mut formats = FnvHashMap();
// Sweep all crates for found dylibs. Add all dylibs, as well as their
// dependencies, ensuring there are no conflicts. The only valid case for a
// dependency to be relied upon twice is for both cases to rely on a dylib.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_some() {
debug!("adding dylib: {}", data.name);
add_library(sess, cnum, cstore::RequireDynamic, &mut formats);
let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum);
for &(depnum, style) in &deps {
debug!("adding {:?}: {}", style,
sess.cstore.get_crate_data(depnum).name.clone());
add_library(sess, depnum, style, &mut formats);
}
}
});
// Collect what we've got so far in the return vector.
let mut ret = (1..sess.cstore.next_crate_num()).map(|i| {
match formats.get(&i).cloned() {
v @ Some(cstore::RequireDynamic) => v,
_ => None,
}
}).collect::<Vec<_>>();
// Run through the dependency list again, and add any missing libraries as
// static libraries.
sess.cstore.iter_crate_data(|cnum, data| {
let src = sess.cstore.get_used_crate_source(cnum).unwrap();
if src.dylib.is_none() &&!formats.contains_key(&cnum) {
assert!(src.rlib.is_some());
debug!("adding staticlib: {}", data.name);
add_library(sess, cnum, cstore::RequireStatic, &mut formats);
ret[cnum as usize - 1] = Some(cstore::RequireStatic);
}
});
// When dylib B links to dylib A, then when using B we must also link to A.
// It could be the case, however, that the rlib for A is present (hence we
// found metadata), but the dylib for A has since been removed.
//
// For situations like this, we perform one last pass over the dependencies,
// making sure that everything is available in the requested format.
for (cnum, kind) in ret.iter().enumerate() {
let cnum = cnum as ast::CrateNum;
let src = sess.cstore.get_used_crate_source(cnum + 1).unwrap();
match *kind {
None => continue,
Some(cstore::RequireStatic) if src.rlib.is_some() => continue,
Some(cstore::RequireDynamic) if src.dylib.is_some() => continue,
Some(kind) => {
let data = sess.cstore.get_crate_data(cnum + 1);
sess.err(&format!("crate `{}` required to be available in {}, \
but it was not available in this form",
data.name,
match kind {
cstore::RequireStatic => "rlib",
cstore::RequireDynamic => "dylib",
}));
}
}
}
return ret;
}
fn add_library(sess: &session::Session,
cnum: ast::CrateNum,
link: cstore::LinkagePreference,
m: &mut FnvHashMap<ast::CrateNum, cstore::LinkagePreference>) {
match m.get(&cnum) {
Some(&link2) => {
// If the linkages differ, then we'd have two copies of the library
// if we continued linking. If the linkages are both static, then we
// would also have two copies of the library (static from two
// different locations).
//
// This error is probably a little obscure, but I imagine that it
// can be refined over time.
if link2!= link || link == cstore::RequireStatic {
let data = sess.cstore.get_crate_data(cnum);
sess.err(&format!("cannot satisfy dependencies so `{}` only \
shows up once",
data.name));
sess.help("having upstream crates all available in one format \
will likely make this go away");
}
}
None => { m.insert(cnum, link); }
}
}
fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
if crates.iter().by_ref().all(|&(_, ref p)| p.is_some()) {
Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())
} else {
None
}
}
| {
match ty {
// If the global prefer_dynamic switch is turned off, first attempt
// static linkage (this can fail).
config::CrateTypeExecutable if !sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
}
}
// No linkage happens with rlibs, we just needed the metadata (which we
// got long ago), so don't bother with anything.
config::CrateTypeRlib => return Vec::new(),
// Staticlibs must have all static dependencies. If any fail to be
// found, we generate some nice pretty errors.
config::CrateTypeStaticlib => {
match attempt_static(sess) {
Some(v) => return v, | identifier_body |
simple.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.
//! A small module implementing a simple "runtime" used for bootstrapping a rust
//! scheduler pool and then interacting with it.
use std::any::Any;
use std::mem;
use std::rt::Runtime;
use std::rt::local::Local;
use std::rt::mutex::NativeMutex;
use std::rt::rtio;
use std::rt::task::{Task, BlockedTask, TaskOpts};
struct SimpleTask {
lock: NativeMutex,
awoken: bool,
}
impl Runtime for SimpleTask {
// Implement the simple tasks of descheduling and rescheduling, but only in
// a simple number of cases.
fn deschedule(mut self: Box<SimpleTask>,
times: uint,
mut cur_task: Box<Task>,
f: |BlockedTask| -> Result<(), BlockedTask>) {
assert!(times == 1);
let me = &mut *self as *mut SimpleTask;
let cur_dupe = &mut *cur_task as *mut Task;
cur_task.put_runtime(self);
let task = BlockedTask::block(cur_task);
// See libnative/task.rs for what's going on here with the `awoken`
// field and the while loop around wait()
unsafe {
let guard = (*me).lock.lock();
(*me).awoken = false;
match f(task) {
Ok(()) => {
while!(*me).awoken {
guard.wait();
}
}
Err(task) => { mem::forget(task.wake()); }
}
drop(guard);
cur_task = mem::transmute(cur_dupe);
}
Local::put(cur_task);
}
fn reawaken(mut self: Box<SimpleTask>, mut to_wake: Box<Task>) {
let me = &mut *self as *mut SimpleTask;
to_wake.put_runtime(self);
unsafe {
mem::forget(to_wake);
let guard = (*me).lock.lock();
(*me).awoken = true;
guard.signal();
}
}
// These functions are all unimplemented and fail as a result. This is on
// purpose. A "simple task" is just that, a very simple task that can't
// really do a whole lot. The only purpose of the task is to get us off our
// feet and running.
fn yield_now(self: Box<SimpleTask>, _cur_task: Box<Task>) |
fn maybe_yield(self: Box<SimpleTask>, _cur_task: Box<Task>) { fail!() }
fn spawn_sibling(self: Box<SimpleTask>,
_cur_task: Box<Task>,
_opts: TaskOpts,
_f: proc():Send) {
fail!()
}
fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> { None }
fn stack_bounds(&self) -> (uint, uint) { fail!() }
fn can_block(&self) -> bool { true }
fn wrap(self: Box<SimpleTask>) -> Box<Any> { fail!() }
}
pub fn task() -> Box<Task> {
let mut task = box Task::new();
task.put_runtime(box SimpleTask {
lock: unsafe {NativeMutex::new()},
awoken: false,
});
return task;
}
| { fail!() } | identifier_body |
simple.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.
//! A small module implementing a simple "runtime" used for bootstrapping a rust
//! scheduler pool and then interacting with it.
use std::any::Any;
use std::mem;
use std::rt::Runtime;
use std::rt::local::Local;
use std::rt::mutex::NativeMutex; |
struct SimpleTask {
lock: NativeMutex,
awoken: bool,
}
impl Runtime for SimpleTask {
// Implement the simple tasks of descheduling and rescheduling, but only in
// a simple number of cases.
fn deschedule(mut self: Box<SimpleTask>,
times: uint,
mut cur_task: Box<Task>,
f: |BlockedTask| -> Result<(), BlockedTask>) {
assert!(times == 1);
let me = &mut *self as *mut SimpleTask;
let cur_dupe = &mut *cur_task as *mut Task;
cur_task.put_runtime(self);
let task = BlockedTask::block(cur_task);
// See libnative/task.rs for what's going on here with the `awoken`
// field and the while loop around wait()
unsafe {
let guard = (*me).lock.lock();
(*me).awoken = false;
match f(task) {
Ok(()) => {
while!(*me).awoken {
guard.wait();
}
}
Err(task) => { mem::forget(task.wake()); }
}
drop(guard);
cur_task = mem::transmute(cur_dupe);
}
Local::put(cur_task);
}
fn reawaken(mut self: Box<SimpleTask>, mut to_wake: Box<Task>) {
let me = &mut *self as *mut SimpleTask;
to_wake.put_runtime(self);
unsafe {
mem::forget(to_wake);
let guard = (*me).lock.lock();
(*me).awoken = true;
guard.signal();
}
}
// These functions are all unimplemented and fail as a result. This is on
// purpose. A "simple task" is just that, a very simple task that can't
// really do a whole lot. The only purpose of the task is to get us off our
// feet and running.
fn yield_now(self: Box<SimpleTask>, _cur_task: Box<Task>) { fail!() }
fn maybe_yield(self: Box<SimpleTask>, _cur_task: Box<Task>) { fail!() }
fn spawn_sibling(self: Box<SimpleTask>,
_cur_task: Box<Task>,
_opts: TaskOpts,
_f: proc():Send) {
fail!()
}
fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> { None }
fn stack_bounds(&self) -> (uint, uint) { fail!() }
fn can_block(&self) -> bool { true }
fn wrap(self: Box<SimpleTask>) -> Box<Any> { fail!() }
}
pub fn task() -> Box<Task> {
let mut task = box Task::new();
task.put_runtime(box SimpleTask {
lock: unsafe {NativeMutex::new()},
awoken: false,
});
return task;
} | use std::rt::rtio;
use std::rt::task::{Task, BlockedTask, TaskOpts}; | random_line_split |
simple.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.
//! A small module implementing a simple "runtime" used for bootstrapping a rust
//! scheduler pool and then interacting with it.
use std::any::Any;
use std::mem;
use std::rt::Runtime;
use std::rt::local::Local;
use std::rt::mutex::NativeMutex;
use std::rt::rtio;
use std::rt::task::{Task, BlockedTask, TaskOpts};
struct SimpleTask {
lock: NativeMutex,
awoken: bool,
}
impl Runtime for SimpleTask {
// Implement the simple tasks of descheduling and rescheduling, but only in
// a simple number of cases.
fn deschedule(mut self: Box<SimpleTask>,
times: uint,
mut cur_task: Box<Task>,
f: |BlockedTask| -> Result<(), BlockedTask>) {
assert!(times == 1);
let me = &mut *self as *mut SimpleTask;
let cur_dupe = &mut *cur_task as *mut Task;
cur_task.put_runtime(self);
let task = BlockedTask::block(cur_task);
// See libnative/task.rs for what's going on here with the `awoken`
// field and the while loop around wait()
unsafe {
let guard = (*me).lock.lock();
(*me).awoken = false;
match f(task) {
Ok(()) => {
while!(*me).awoken {
guard.wait();
}
}
Err(task) => { mem::forget(task.wake()); }
}
drop(guard);
cur_task = mem::transmute(cur_dupe);
}
Local::put(cur_task);
}
fn reawaken(mut self: Box<SimpleTask>, mut to_wake: Box<Task>) {
let me = &mut *self as *mut SimpleTask;
to_wake.put_runtime(self);
unsafe {
mem::forget(to_wake);
let guard = (*me).lock.lock();
(*me).awoken = true;
guard.signal();
}
}
// These functions are all unimplemented and fail as a result. This is on
// purpose. A "simple task" is just that, a very simple task that can't
// really do a whole lot. The only purpose of the task is to get us off our
// feet and running.
fn yield_now(self: Box<SimpleTask>, _cur_task: Box<Task>) { fail!() }
fn maybe_yield(self: Box<SimpleTask>, _cur_task: Box<Task>) { fail!() }
fn spawn_sibling(self: Box<SimpleTask>,
_cur_task: Box<Task>,
_opts: TaskOpts,
_f: proc():Send) {
fail!()
}
fn local_io<'a>(&'a mut self) -> Option<rtio::LocalIo<'a>> { None }
fn stack_bounds(&self) -> (uint, uint) { fail!() }
fn can_block(&self) -> bool { true }
fn | (self: Box<SimpleTask>) -> Box<Any> { fail!() }
}
pub fn task() -> Box<Task> {
let mut task = box Task::new();
task.put_runtime(box SimpleTask {
lock: unsafe {NativeMutex::new()},
awoken: false,
});
return task;
}
| wrap | identifier_name |
circle_queue.rs | #[derive(Debug)]
struct CircleQueue {
queue: Vec<i32>,
head: i32,
tail: i32,
n: i32,
}
impl CircleQueue {
fn new(n: i32) -> Self {
CircleQueue {
queue: vec![-1; n as usize],
head: 0,
tail: 0,
n: n,
}
}
fn enqueue(&mut self, num: i32) -> bool {
if (self.tail + 1) % self.n == self.head { return false; }
self.queue[self.tail as usize] = num;
self.tail = (self.tail + 1) % self.n;
true
}
fn dequeue(&mut self) -> i32 {
if self.head == self.tail |
let shift = self.queue[self.head as usize];
self.head = (self.head + 1) % self.n;
shift
}
fn print_all(&self) {
let mut s = String::from("");
for i in self.head..self.tail {
s.push(self.queue[i as usize] as u8 as char);
s.push_str("->");
}
println!("{:?}", s);
}
}
fn main() {
let mut queue = CircleQueue::new(10);
queue.enqueue(2);
queue.enqueue(2);
queue.enqueue(2);
queue.enqueue(2);
queue.dequeue();
queue.dequeue();
queue.enqueue(4);
queue.dequeue();
queue.print_all();
}
| { return -1; } | conditional_block |
circle_queue.rs | #[derive(Debug)]
struct CircleQueue {
queue: Vec<i32>,
head: i32,
tail: i32,
n: i32,
}
impl CircleQueue {
fn new(n: i32) -> Self {
CircleQueue {
queue: vec![-1; n as usize],
head: 0,
tail: 0,
n: n,
}
}
fn enqueue(&mut self, num: i32) -> bool {
if (self.tail + 1) % self.n == self.head { return false; }
self.queue[self.tail as usize] = num;
self.tail = (self.tail + 1) % self.n;
true
}
fn dequeue(&mut self) -> i32 {
if self.head == self.tail { return -1; }
let shift = self.queue[self.head as usize];
self.head = (self.head + 1) % self.n;
shift
}
fn print_all(&self) {
let mut s = String::from("");
for i in self.head..self.tail {
s.push(self.queue[i as usize] as u8 as char); | s.push_str("->");
}
println!("{:?}", s);
}
}
fn main() {
let mut queue = CircleQueue::new(10);
queue.enqueue(2);
queue.enqueue(2);
queue.enqueue(2);
queue.enqueue(2);
queue.dequeue();
queue.dequeue();
queue.enqueue(4);
queue.dequeue();
queue.print_all();
} | random_line_split | |
circle_queue.rs | #[derive(Debug)]
struct CircleQueue {
queue: Vec<i32>,
head: i32,
tail: i32,
n: i32,
}
impl CircleQueue {
fn new(n: i32) -> Self {
CircleQueue {
queue: vec![-1; n as usize],
head: 0,
tail: 0,
n: n,
}
}
fn enqueue(&mut self, num: i32) -> bool {
if (self.tail + 1) % self.n == self.head { return false; }
self.queue[self.tail as usize] = num;
self.tail = (self.tail + 1) % self.n;
true
}
fn dequeue(&mut self) -> i32 |
fn print_all(&self) {
let mut s = String::from("");
for i in self.head..self.tail {
s.push(self.queue[i as usize] as u8 as char);
s.push_str("->");
}
println!("{:?}", s);
}
}
fn main() {
let mut queue = CircleQueue::new(10);
queue.enqueue(2);
queue.enqueue(2);
queue.enqueue(2);
queue.enqueue(2);
queue.dequeue();
queue.dequeue();
queue.enqueue(4);
queue.dequeue();
queue.print_all();
}
| {
if self.head == self.tail { return -1; }
let shift = self.queue[self.head as usize];
self.head = (self.head + 1) % self.n;
shift
} | identifier_body |
circle_queue.rs | #[derive(Debug)]
struct CircleQueue {
queue: Vec<i32>,
head: i32,
tail: i32,
n: i32,
}
impl CircleQueue {
fn new(n: i32) -> Self {
CircleQueue {
queue: vec![-1; n as usize],
head: 0,
tail: 0,
n: n,
}
}
fn enqueue(&mut self, num: i32) -> bool {
if (self.tail + 1) % self.n == self.head { return false; }
self.queue[self.tail as usize] = num;
self.tail = (self.tail + 1) % self.n;
true
}
fn dequeue(&mut self) -> i32 {
if self.head == self.tail { return -1; }
let shift = self.queue[self.head as usize];
self.head = (self.head + 1) % self.n;
shift
}
fn print_all(&self) {
let mut s = String::from("");
for i in self.head..self.tail {
s.push(self.queue[i as usize] as u8 as char);
s.push_str("->");
}
println!("{:?}", s);
}
}
fn | () {
let mut queue = CircleQueue::new(10);
queue.enqueue(2);
queue.enqueue(2);
queue.enqueue(2);
queue.enqueue(2);
queue.dequeue();
queue.dequeue();
queue.enqueue(4);
queue.dequeue();
queue.print_all();
}
| main | identifier_name |
op.rs | #[derive(Debug, PartialEq)]
pub enum InfixOp {
// A + B
Add,
// A - B
Sub,
// A / B
Div,
// A * B
Mul,
// A % B
Mod,
// A ^ B
Pow,
// A equals B (traditionally A == B)
Equ,
// A < B
Lt,
// A <= B
Lte,
// A > B
Gt,
// A >= B
Gte,
}
impl InfixOp {
pub fn get_precedence(&self) -> u8 {
// Precedence(High -> Low):
// 9. () | [].
// 8. not | negate
// 7. * / %
// 6. + -
// 5. < | <= | > | >=
// 4. ==!=
// 3. bitwise and | bitwise or | bitwise xor | ^ (pow - not sure where this goes)
// 2. logical and | logical or
// 1.,
match *self {
InfixOp::Mul => 7,
InfixOp::Div => 7,
InfixOp::Mod => 7,
InfixOp::Add => 6,
InfixOp::Sub => 6,
InfixOp::Lt => 5,
InfixOp::Lte => 5,
InfixOp::Gt => 5,
InfixOp::Gte => 5,
InfixOp::Equ => 4,
InfixOp::Pow => 3 // Not sure about this one
}
}
}
#[derive(Debug, PartialEq)]
pub enum | {
// -A
Negate,
// not A (traditionally!A)
Not
}
| UnaryOp | identifier_name |
op.rs | #[derive(Debug, PartialEq)]
pub enum InfixOp {
// A + B
Add,
// A - B
Sub,
// A / B
Div,
// A * B
Mul,
// A % B
Mod, | // A ^ B
Pow,
// A equals B (traditionally A == B)
Equ,
// A < B
Lt,
// A <= B
Lte,
// A > B
Gt,
// A >= B
Gte,
}
impl InfixOp {
pub fn get_precedence(&self) -> u8 {
// Precedence(High -> Low):
// 9. () | [].
// 8. not | negate
// 7. * / %
// 6. + -
// 5. < | <= | > | >=
// 4. ==!=
// 3. bitwise and | bitwise or | bitwise xor | ^ (pow - not sure where this goes)
// 2. logical and | logical or
// 1.,
match *self {
InfixOp::Mul => 7,
InfixOp::Div => 7,
InfixOp::Mod => 7,
InfixOp::Add => 6,
InfixOp::Sub => 6,
InfixOp::Lt => 5,
InfixOp::Lte => 5,
InfixOp::Gt => 5,
InfixOp::Gte => 5,
InfixOp::Equ => 4,
InfixOp::Pow => 3 // Not sure about this one
}
}
}
#[derive(Debug, PartialEq)]
pub enum UnaryOp {
// -A
Negate,
// not A (traditionally!A)
Not
} | random_line_split | |
union_find.rs | pub struct UnionFind {
parents: Vec<usize>,
ranks: Vec<u64>
}
impl UnionFind {
pub fn new(size: usize) -> UnionFind {
UnionFind {
parents: (0..size).map(|i| i).collect(),
ranks: (0..size).map(|_| 0).collect()
}
}
pub fn find(&mut self, x: usize) -> usize {
let parent = self.parents[x];
if parent!= x {
self.parents[x] = self.find(parent);
}
self.parents[x]
}
pub fn union(&mut self, x: usize, y: usize) {
let xr = self.find(x);
let yr = self.find(y);
if xr == yr {
return;
}
if self.ranks[xr] < self.ranks[yr] {
self.parents[xr] = yr;
} else if self.ranks[xr] > self.ranks[yr] {
self.parents[yr] = xr;
} else {
self.parents[yr] = xr;
self.ranks[xr] += 1;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let mut uf = UnionFind::new(10);
uf.union(3, 5);
uf.union(7, 8);
uf.union(7, 9);
uf.union(5, 9);
| assert!(uf.find(2)!= uf.find(6));
}
} | assert!(uf.find(3) == uf.find(8));
assert!(uf.find(3) != uf.find(6)); | random_line_split |
union_find.rs | pub struct UnionFind {
parents: Vec<usize>,
ranks: Vec<u64>
}
impl UnionFind {
pub fn new(size: usize) -> UnionFind {
UnionFind {
parents: (0..size).map(|i| i).collect(),
ranks: (0..size).map(|_| 0).collect()
}
}
pub fn find(&mut self, x: usize) -> usize {
let parent = self.parents[x];
if parent!= x {
self.parents[x] = self.find(parent);
}
self.parents[x]
}
pub fn union(&mut self, x: usize, y: usize) {
let xr = self.find(x);
let yr = self.find(y);
if xr == yr {
return;
}
if self.ranks[xr] < self.ranks[yr] {
self.parents[xr] = yr;
} else if self.ranks[xr] > self.ranks[yr] {
self.parents[yr] = xr;
} else {
self.parents[yr] = xr;
self.ranks[xr] += 1;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() |
}
| {
let mut uf = UnionFind::new(10);
uf.union(3, 5);
uf.union(7, 8);
uf.union(7, 9);
uf.union(5, 9);
assert!(uf.find(3) == uf.find(8));
assert!(uf.find(3) != uf.find(6));
assert!(uf.find(2) != uf.find(6));
} | identifier_body |
union_find.rs | pub struct UnionFind {
parents: Vec<usize>,
ranks: Vec<u64>
}
impl UnionFind {
pub fn | (size: usize) -> UnionFind {
UnionFind {
parents: (0..size).map(|i| i).collect(),
ranks: (0..size).map(|_| 0).collect()
}
}
pub fn find(&mut self, x: usize) -> usize {
let parent = self.parents[x];
if parent!= x {
self.parents[x] = self.find(parent);
}
self.parents[x]
}
pub fn union(&mut self, x: usize, y: usize) {
let xr = self.find(x);
let yr = self.find(y);
if xr == yr {
return;
}
if self.ranks[xr] < self.ranks[yr] {
self.parents[xr] = yr;
} else if self.ranks[xr] > self.ranks[yr] {
self.parents[yr] = xr;
} else {
self.parents[yr] = xr;
self.ranks[xr] += 1;
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let mut uf = UnionFind::new(10);
uf.union(3, 5);
uf.union(7, 8);
uf.union(7, 9);
uf.union(5, 9);
assert!(uf.find(3) == uf.find(8));
assert!(uf.find(3)!= uf.find(6));
assert!(uf.find(2)!= uf.find(6));
}
}
| new | identifier_name |
detect.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use std::ptr;
use crate::core::*;
use crate::smb::smb::*;
use crate::dcerpc::detect::{DCEIfaceData, DCEOpnumData, DETECT_DCE_OPNUM_RANGE_UNINITIALIZED};
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_share(tx: &mut SMBTransaction,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
match tx.type_data {
Some(SMBTransactionTypeData::TREECONNECT(ref x)) => {
SCLogDebug!("is_pipe {}", x.is_pipe);
if!x.is_pipe {
unsafe {
*buffer = x.share_name.as_ptr();
*buffer_len = x.share_name.len() as u32;
return 1;
}
}
}
_ => {
}
}
unsafe {
*buffer = ptr::null();
*buffer_len = 0;
}
return 0;
}
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_named_pipe(tx: &mut SMBTransaction,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
match tx.type_data {
Some(SMBTransactionTypeData::TREECONNECT(ref x)) => {
SCLogDebug!("is_pipe {}", x.is_pipe);
if x.is_pipe {
unsafe {
*buffer = x.share_name.as_ptr();
*buffer_len = x.share_name.len() as u32;
return 1;
}
}
}
_ => {
}
}
unsafe {
*buffer = ptr::null();
*buffer_len = 0;
}
return 0;
}
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_stub_data(tx: &mut SMBTransaction,
direction: u8,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
| unsafe {
*buffer = ptr::null();
*buffer_len = 0;
}
return 0;
}
#[no_mangle]
pub extern "C" fn rs_smb_tx_match_dce_opnum(tx: &mut SMBTransaction,
dce_data: &mut DCEOpnumData)
-> u8
{
SCLogDebug!("rs_smb_tx_get_dce_opnum: start");
match tx.type_data {
Some(SMBTransactionTypeData::DCERPC(ref x)) => {
if x.req_cmd == 1 { // REQUEST
for range in dce_data.data.iter() {
if range.range2 == DETECT_DCE_OPNUM_RANGE_UNINITIALIZED {
if range.range1 == x.opnum as u32 {
return 1;
} else if range.range1 <= x.opnum as u32 && range.range2 >= x.opnum as u32 {
return 1;
}
}
}
}
}
_ => {
}
}
return 0;
}
/* based on:
* typedef enum DetectDceIfaceOperators_ {
* DETECT_DCE_IFACE_OP_NONE = 0,
* DETECT_DCE_IFACE_OP_LT,
* DETECT_DCE_IFACE_OP_GT,
* DETECT_DCE_IFACE_OP_EQ,
* DETECT_DCE_IFACE_OP_NE,
* } DetectDceIfaceOperators;
*/
#[inline]
fn match_version(op: u8, them: u16, us: u16) -> bool {
let result = match op {
0 => { // NONE
true
},
1 => { // LT
them < us
},
2 => { // GT
them > us
},
3 => { // EQ
them == us
},
4 => { // NE
them!= us
},
_ => {
panic!("called with invalid op {}", op);
},
};
result
}
/* mimic logic that is/was in the C code:
* - match on REQUEST (so not on BIND/BINDACK (probably for mixing with
* dce_opnum and dce_stub_data)
* - only match on approved ifaces (so ack_result == 0) */
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_dce_iface(state: &mut SMBState,
tx: &mut SMBTransaction,
dce_data: &mut DCEIfaceData)
-> u8
{
let if_uuid = dce_data.if_uuid.as_slice();
let if_op = dce_data.op;
let if_version = dce_data.version;
let is_dcerpc_request = match tx.type_data {
Some(SMBTransactionTypeData::DCERPC(ref x)) => { x.req_cmd == 1 },
_ => { false },
};
if!is_dcerpc_request {
return 0;
}
let ifaces = match state.dcerpc_ifaces {
Some(ref x) => x,
_ => {
return 0;
},
};
SCLogDebug!("looking for UUID {:?}", if_uuid);
for i in ifaces {
SCLogDebug!("stored UUID {:?} acked {} ack_result {}", i, i.acked, i.ack_result);
if i.acked && i.ack_result == 0 && i.uuid == if_uuid {
if match_version(if_op as u8, if_version as u16, i.ver) {
return 1;
}
}
}
return 0;
}
| {
match tx.type_data {
Some(SMBTransactionTypeData::DCERPC(ref x)) => {
let vref = if direction == STREAM_TOSERVER {
&x.stub_data_ts
} else {
&x.stub_data_tc
};
if vref.len() > 0 {
unsafe {
*buffer = vref.as_ptr();
*buffer_len = vref.len() as u32;
return 1;
}
}
}
_ => {
}
}
| identifier_body |
detect.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use std::ptr;
use crate::core::*;
use crate::smb::smb::*;
use crate::dcerpc::detect::{DCEIfaceData, DCEOpnumData, DETECT_DCE_OPNUM_RANGE_UNINITIALIZED};
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_share(tx: &mut SMBTransaction,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
match tx.type_data {
Some(SMBTransactionTypeData::TREECONNECT(ref x)) => {
SCLogDebug!("is_pipe {}", x.is_pipe);
if!x.is_pipe {
unsafe {
*buffer = x.share_name.as_ptr();
*buffer_len = x.share_name.len() as u32;
return 1;
}
}
}
_ => {
}
}
unsafe {
*buffer = ptr::null();
*buffer_len = 0;
}
return 0;
}
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_named_pipe(tx: &mut SMBTransaction,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
match tx.type_data {
Some(SMBTransactionTypeData::TREECONNECT(ref x)) => {
SCLogDebug!("is_pipe {}", x.is_pipe);
if x.is_pipe {
unsafe {
*buffer = x.share_name.as_ptr();
*buffer_len = x.share_name.len() as u32;
return 1;
}
}
}
_ => {
}
}
unsafe {
*buffer = ptr::null();
*buffer_len = 0;
}
return 0;
}
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_stub_data(tx: &mut SMBTransaction,
direction: u8,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
match tx.type_data {
Some(SMBTransactionTypeData::DCERPC(ref x)) => {
let vref = if direction == STREAM_TOSERVER {
&x.stub_data_ts
} else {
&x.stub_data_tc
};
if vref.len() > 0 {
unsafe {
*buffer = vref.as_ptr();
*buffer_len = vref.len() as u32;
return 1;
}
}
}
_ => {
}
}
unsafe {
*buffer = ptr::null();
*buffer_len = 0;
}
return 0;
}
#[no_mangle]
pub extern "C" fn rs_smb_tx_match_dce_opnum(tx: &mut SMBTransaction,
dce_data: &mut DCEOpnumData)
-> u8
{
SCLogDebug!("rs_smb_tx_get_dce_opnum: start");
match tx.type_data {
Some(SMBTransactionTypeData::DCERPC(ref x)) => {
if x.req_cmd == 1 { // REQUEST
for range in dce_data.data.iter() { | if range.range1 == x.opnum as u32 {
return 1;
} else if range.range1 <= x.opnum as u32 && range.range2 >= x.opnum as u32 {
return 1;
}
}
}
}
}
_ => {
}
}
return 0;
}
/* based on:
* typedef enum DetectDceIfaceOperators_ {
* DETECT_DCE_IFACE_OP_NONE = 0,
* DETECT_DCE_IFACE_OP_LT,
* DETECT_DCE_IFACE_OP_GT,
* DETECT_DCE_IFACE_OP_EQ,
* DETECT_DCE_IFACE_OP_NE,
* } DetectDceIfaceOperators;
*/
#[inline]
fn match_version(op: u8, them: u16, us: u16) -> bool {
let result = match op {
0 => { // NONE
true
},
1 => { // LT
them < us
},
2 => { // GT
them > us
},
3 => { // EQ
them == us
},
4 => { // NE
them!= us
},
_ => {
panic!("called with invalid op {}", op);
},
};
result
}
/* mimic logic that is/was in the C code:
* - match on REQUEST (so not on BIND/BINDACK (probably for mixing with
* dce_opnum and dce_stub_data)
* - only match on approved ifaces (so ack_result == 0) */
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_dce_iface(state: &mut SMBState,
tx: &mut SMBTransaction,
dce_data: &mut DCEIfaceData)
-> u8
{
let if_uuid = dce_data.if_uuid.as_slice();
let if_op = dce_data.op;
let if_version = dce_data.version;
let is_dcerpc_request = match tx.type_data {
Some(SMBTransactionTypeData::DCERPC(ref x)) => { x.req_cmd == 1 },
_ => { false },
};
if!is_dcerpc_request {
return 0;
}
let ifaces = match state.dcerpc_ifaces {
Some(ref x) => x,
_ => {
return 0;
},
};
SCLogDebug!("looking for UUID {:?}", if_uuid);
for i in ifaces {
SCLogDebug!("stored UUID {:?} acked {} ack_result {}", i, i.acked, i.ack_result);
if i.acked && i.ack_result == 0 && i.uuid == if_uuid {
if match_version(if_op as u8, if_version as u16, i.ver) {
return 1;
}
}
}
return 0;
} | if range.range2 == DETECT_DCE_OPNUM_RANGE_UNINITIALIZED { | random_line_split |
detect.rs | /* Copyright (C) 2017 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
use std::ptr;
use crate::core::*;
use crate::smb::smb::*;
use crate::dcerpc::detect::{DCEIfaceData, DCEOpnumData, DETECT_DCE_OPNUM_RANGE_UNINITIALIZED};
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_share(tx: &mut SMBTransaction,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
match tx.type_data {
Some(SMBTransactionTypeData::TREECONNECT(ref x)) => {
SCLogDebug!("is_pipe {}", x.is_pipe);
if!x.is_pipe {
unsafe {
*buffer = x.share_name.as_ptr();
*buffer_len = x.share_name.len() as u32;
return 1;
}
}
}
_ => {
}
}
unsafe {
*buffer = ptr::null();
*buffer_len = 0;
}
return 0;
}
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_named_pipe(tx: &mut SMBTransaction,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
match tx.type_data {
Some(SMBTransactionTypeData::TREECONNECT(ref x)) => {
SCLogDebug!("is_pipe {}", x.is_pipe);
if x.is_pipe {
unsafe {
*buffer = x.share_name.as_ptr();
*buffer_len = x.share_name.len() as u32;
return 1;
}
}
}
_ => {
}
}
unsafe {
*buffer = ptr::null();
*buffer_len = 0;
}
return 0;
}
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_stub_data(tx: &mut SMBTransaction,
direction: u8,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
match tx.type_data {
Some(SMBTransactionTypeData::DCERPC(ref x)) => {
let vref = if direction == STREAM_TOSERVER {
&x.stub_data_ts
} else {
&x.stub_data_tc
};
if vref.len() > 0 {
unsafe {
*buffer = vref.as_ptr();
*buffer_len = vref.len() as u32;
return 1;
}
}
}
_ => {
}
}
unsafe {
*buffer = ptr::null();
*buffer_len = 0;
}
return 0;
}
#[no_mangle]
pub extern "C" fn | (tx: &mut SMBTransaction,
dce_data: &mut DCEOpnumData)
-> u8
{
SCLogDebug!("rs_smb_tx_get_dce_opnum: start");
match tx.type_data {
Some(SMBTransactionTypeData::DCERPC(ref x)) => {
if x.req_cmd == 1 { // REQUEST
for range in dce_data.data.iter() {
if range.range2 == DETECT_DCE_OPNUM_RANGE_UNINITIALIZED {
if range.range1 == x.opnum as u32 {
return 1;
} else if range.range1 <= x.opnum as u32 && range.range2 >= x.opnum as u32 {
return 1;
}
}
}
}
}
_ => {
}
}
return 0;
}
/* based on:
* typedef enum DetectDceIfaceOperators_ {
* DETECT_DCE_IFACE_OP_NONE = 0,
* DETECT_DCE_IFACE_OP_LT,
* DETECT_DCE_IFACE_OP_GT,
* DETECT_DCE_IFACE_OP_EQ,
* DETECT_DCE_IFACE_OP_NE,
* } DetectDceIfaceOperators;
*/
#[inline]
fn match_version(op: u8, them: u16, us: u16) -> bool {
let result = match op {
0 => { // NONE
true
},
1 => { // LT
them < us
},
2 => { // GT
them > us
},
3 => { // EQ
them == us
},
4 => { // NE
them!= us
},
_ => {
panic!("called with invalid op {}", op);
},
};
result
}
/* mimic logic that is/was in the C code:
* - match on REQUEST (so not on BIND/BINDACK (probably for mixing with
* dce_opnum and dce_stub_data)
* - only match on approved ifaces (so ack_result == 0) */
#[no_mangle]
pub extern "C" fn rs_smb_tx_get_dce_iface(state: &mut SMBState,
tx: &mut SMBTransaction,
dce_data: &mut DCEIfaceData)
-> u8
{
let if_uuid = dce_data.if_uuid.as_slice();
let if_op = dce_data.op;
let if_version = dce_data.version;
let is_dcerpc_request = match tx.type_data {
Some(SMBTransactionTypeData::DCERPC(ref x)) => { x.req_cmd == 1 },
_ => { false },
};
if!is_dcerpc_request {
return 0;
}
let ifaces = match state.dcerpc_ifaces {
Some(ref x) => x,
_ => {
return 0;
},
};
SCLogDebug!("looking for UUID {:?}", if_uuid);
for i in ifaces {
SCLogDebug!("stored UUID {:?} acked {} ack_result {}", i, i.acked, i.ack_result);
if i.acked && i.ack_result == 0 && i.uuid == if_uuid {
if match_version(if_op as u8, if_version as u16, i.ver) {
return 1;
}
}
}
return 0;
}
| rs_smb_tx_match_dce_opnum | identifier_name |
cht.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd. |
// 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.
//! Canonical hash trie definitions and helper functions.
//!
//! Each CHT is a trie mapping block numbers to canonical hashes and total difficulty.
//! One is generated for every `SIZE` blocks, allowing us to discard those blocks in
//! favor the the trie root. When the "ancient" blocks need to be accessed, we simply
//! request an inclusion proof of a specific block number against the trie with the
//! root has. A correct proof implies that the claimed block is identical to the one
//! we discarded.
use ethcore::ids::BlockId;
use util::{Bytes, H256, U256, HashDB, MemoryDB};
use util::trie::{self, TrieMut, TrieDBMut, Trie, TrieDB, Recorder};
use rlp::{Stream, RlpStream, UntrustedRlp, View};
// encode a key.
macro_rules! key {
($num: expr) => { ::rlp::encode(&$num) }
}
macro_rules! val {
($hash: expr, $td: expr) => {{
let mut stream = RlpStream::new_list(2);
stream.append(&$hash).append(&$td);
stream.drain()
}}
}
/// The size of each CHT.
pub const SIZE: u64 = 2048;
/// A canonical hash trie. This is generic over any database it can query.
/// See module docs for more details.
#[derive(Debug, Clone)]
pub struct CHT<DB: HashDB> {
db: DB,
root: H256, // the root of this CHT.
number: u64,
}
impl<DB: HashDB> CHT<DB> {
/// Query the root of the CHT.
pub fn root(&self) -> H256 { self.root }
/// Query the number of the CHT.
pub fn number(&self) -> u64 { self.number }
/// Generate an inclusion proof for the entry at a specific block.
/// Nodes before level `from_level` will be omitted.
/// Returns an error on an incomplete trie, and `Ok(None)` on an unprovable request.
pub fn prove(&self, num: u64, from_level: u32) -> trie::Result<Option<Vec<Bytes>>> {
if block_to_cht_number(num)!= Some(self.number) { return Ok(None) }
let mut recorder = Recorder::with_depth(from_level);
let t = TrieDB::new(&self.db, &self.root)?;
t.get_with(&key!(num), &mut recorder)?;
Ok(Some(recorder.drain().into_iter().map(|x| x.data).collect()))
}
}
/// Block information necessary to build a CHT.
pub struct BlockInfo {
/// The block's hash.
pub hash: H256,
/// The block's parent's hash.
pub parent_hash: H256,
/// The block's total difficulty.
pub total_difficulty: U256,
}
/// Build an in-memory CHT from a closure which provides necessary information
/// about blocks. If the fetcher ever fails to provide the info, the CHT
/// will not be generated.
pub fn build<F>(cht_num: u64, mut fetcher: F) -> Option<CHT<MemoryDB>>
where F: FnMut(BlockId) -> Option<BlockInfo>
{
let mut db = MemoryDB::new();
// start from the last block by number and work backwards.
let last_num = start_number(cht_num + 1) - 1;
let mut id = BlockId::Number(last_num);
let mut root = H256::default();
{
let mut t = TrieDBMut::new(&mut db, &mut root);
for blk_num in (0..SIZE).map(|n| last_num - n) {
let info = match fetcher(id) {
Some(info) => info,
None => return None,
};
id = BlockId::Hash(info.parent_hash);
t.insert(&key!(blk_num), &val!(info.hash, info.total_difficulty))
.expect("fresh in-memory database is infallible; qed");
}
}
Some(CHT {
db: db,
root: root,
number: cht_num,
})
}
/// Compute a CHT root from an iterator of (hash, td) pairs. Fails if shorter than
/// SIZE items. The items are assumed to proceed sequentially from `start_number(cht_num)`.
/// Discards the trie's nodes.
pub fn compute_root<I>(cht_num: u64, iterable: I) -> Option<H256>
where I: IntoIterator<Item=(H256, U256)>
{
let mut v = Vec::with_capacity(SIZE as usize);
let start_num = start_number(cht_num) as usize;
for (i, (h, td)) in iterable.into_iter().take(SIZE as usize).enumerate() {
v.push((key!(i + start_num).to_vec(), val!(h, td).to_vec()))
}
if v.len() == SIZE as usize {
Some(::util::triehash::trie_root(v))
} else {
None
}
}
/// Check a proof for a CHT.
/// Given a set of a trie nodes, a number to query, and a trie root,
/// verify the given trie branch and extract the canonical hash and total difficulty.
// TODO: better support for partially-checked queries.
pub fn check_proof(proof: &[Bytes], num: u64, root: H256) -> Option<(H256, U256)> {
let mut db = MemoryDB::new();
for node in proof { db.insert(&node[..]); }
let res = match TrieDB::new(&db, &root) {
Err(_) => return None,
Ok(trie) => trie.get_with(&key!(num), |val: &[u8]| {
let rlp = UntrustedRlp::new(val);
rlp.val_at::<H256>(0)
.and_then(|h| rlp.val_at::<U256>(1).map(|td| (h, td)))
.ok()
})
};
match res {
Ok(Some(Some((hash, td)))) => Some((hash, td)),
_ => None,
}
}
/// Convert a block number to a CHT number.
/// Returns `None` for `block_num` == 0, `Some` otherwise.
pub fn block_to_cht_number(block_num: u64) -> Option<u64> {
match block_num {
0 => None,
n => Some((n - 1) / SIZE),
}
}
/// Get the starting block of a given CHT.
/// CHT 0 includes block 1...SIZE,
/// CHT 1 includes block SIZE + 1... 2*SIZE
/// More generally: CHT N includes block (1 + N*SIZE)...((N+1)*SIZE).
/// This is because the genesis hash is assumed to be known
/// and including it would be redundant.
pub fn start_number(cht_num: u64) -> u64 {
(cht_num * SIZE) + 1
}
#[cfg(test)]
mod tests {
#[test]
fn size_is_lt_usize() {
// to ensure safe casting on the target platform.
assert!(::cht::SIZE < usize::max_value() as u64)
}
#[test]
fn block_to_cht_number() {
assert!(::cht::block_to_cht_number(0).is_none());
assert_eq!(::cht::block_to_cht_number(1).unwrap(), 0);
assert_eq!(::cht::block_to_cht_number(::cht::SIZE + 1).unwrap(), 1);
assert_eq!(::cht::block_to_cht_number(::cht::SIZE).unwrap(), 0);
}
#[test]
fn start_number() {
assert_eq!(::cht::start_number(0), 1);
assert_eq!(::cht::start_number(1), ::cht::SIZE + 1);
assert_eq!(::cht::start_number(2), ::cht::SIZE * 2 + 1);
}
} | // This file is part of Parity. | random_line_split |
cht.rs | // Copyright 2015-2017 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.
//! Canonical hash trie definitions and helper functions.
//!
//! Each CHT is a trie mapping block numbers to canonical hashes and total difficulty.
//! One is generated for every `SIZE` blocks, allowing us to discard those blocks in
//! favor the the trie root. When the "ancient" blocks need to be accessed, we simply
//! request an inclusion proof of a specific block number against the trie with the
//! root has. A correct proof implies that the claimed block is identical to the one
//! we discarded.
use ethcore::ids::BlockId;
use util::{Bytes, H256, U256, HashDB, MemoryDB};
use util::trie::{self, TrieMut, TrieDBMut, Trie, TrieDB, Recorder};
use rlp::{Stream, RlpStream, UntrustedRlp, View};
// encode a key.
macro_rules! key {
($num: expr) => { ::rlp::encode(&$num) }
}
macro_rules! val {
($hash: expr, $td: expr) => {{
let mut stream = RlpStream::new_list(2);
stream.append(&$hash).append(&$td);
stream.drain()
}}
}
/// The size of each CHT.
pub const SIZE: u64 = 2048;
/// A canonical hash trie. This is generic over any database it can query.
/// See module docs for more details.
#[derive(Debug, Clone)]
pub struct CHT<DB: HashDB> {
db: DB,
root: H256, // the root of this CHT.
number: u64,
}
impl<DB: HashDB> CHT<DB> {
/// Query the root of the CHT.
pub fn root(&self) -> H256 { self.root }
/// Query the number of the CHT.
pub fn number(&self) -> u64 { self.number }
/// Generate an inclusion proof for the entry at a specific block.
/// Nodes before level `from_level` will be omitted.
/// Returns an error on an incomplete trie, and `Ok(None)` on an unprovable request.
pub fn prove(&self, num: u64, from_level: u32) -> trie::Result<Option<Vec<Bytes>>> {
if block_to_cht_number(num)!= Some(self.number) { return Ok(None) }
let mut recorder = Recorder::with_depth(from_level);
let t = TrieDB::new(&self.db, &self.root)?;
t.get_with(&key!(num), &mut recorder)?;
Ok(Some(recorder.drain().into_iter().map(|x| x.data).collect()))
}
}
/// Block information necessary to build a CHT.
pub struct BlockInfo {
/// The block's hash.
pub hash: H256,
/// The block's parent's hash.
pub parent_hash: H256,
/// The block's total difficulty.
pub total_difficulty: U256,
}
/// Build an in-memory CHT from a closure which provides necessary information
/// about blocks. If the fetcher ever fails to provide the info, the CHT
/// will not be generated.
pub fn build<F>(cht_num: u64, mut fetcher: F) -> Option<CHT<MemoryDB>>
where F: FnMut(BlockId) -> Option<BlockInfo>
{
let mut db = MemoryDB::new();
// start from the last block by number and work backwards.
let last_num = start_number(cht_num + 1) - 1;
let mut id = BlockId::Number(last_num);
let mut root = H256::default();
{
let mut t = TrieDBMut::new(&mut db, &mut root);
for blk_num in (0..SIZE).map(|n| last_num - n) {
let info = match fetcher(id) {
Some(info) => info,
None => return None,
};
id = BlockId::Hash(info.parent_hash);
t.insert(&key!(blk_num), &val!(info.hash, info.total_difficulty))
.expect("fresh in-memory database is infallible; qed");
}
}
Some(CHT {
db: db,
root: root,
number: cht_num,
})
}
/// Compute a CHT root from an iterator of (hash, td) pairs. Fails if shorter than
/// SIZE items. The items are assumed to proceed sequentially from `start_number(cht_num)`.
/// Discards the trie's nodes.
pub fn compute_root<I>(cht_num: u64, iterable: I) -> Option<H256>
where I: IntoIterator<Item=(H256, U256)>
|
/// Check a proof for a CHT.
/// Given a set of a trie nodes, a number to query, and a trie root,
/// verify the given trie branch and extract the canonical hash and total difficulty.
// TODO: better support for partially-checked queries.
pub fn check_proof(proof: &[Bytes], num: u64, root: H256) -> Option<(H256, U256)> {
let mut db = MemoryDB::new();
for node in proof { db.insert(&node[..]); }
let res = match TrieDB::new(&db, &root) {
Err(_) => return None,
Ok(trie) => trie.get_with(&key!(num), |val: &[u8]| {
let rlp = UntrustedRlp::new(val);
rlp.val_at::<H256>(0)
.and_then(|h| rlp.val_at::<U256>(1).map(|td| (h, td)))
.ok()
})
};
match res {
Ok(Some(Some((hash, td)))) => Some((hash, td)),
_ => None,
}
}
/// Convert a block number to a CHT number.
/// Returns `None` for `block_num` == 0, `Some` otherwise.
pub fn block_to_cht_number(block_num: u64) -> Option<u64> {
match block_num {
0 => None,
n => Some((n - 1) / SIZE),
}
}
/// Get the starting block of a given CHT.
/// CHT 0 includes block 1...SIZE,
/// CHT 1 includes block SIZE + 1... 2*SIZE
/// More generally: CHT N includes block (1 + N*SIZE)...((N+1)*SIZE).
/// This is because the genesis hash is assumed to be known
/// and including it would be redundant.
pub fn start_number(cht_num: u64) -> u64 {
(cht_num * SIZE) + 1
}
#[cfg(test)]
mod tests {
#[test]
fn size_is_lt_usize() {
// to ensure safe casting on the target platform.
assert!(::cht::SIZE < usize::max_value() as u64)
}
#[test]
fn block_to_cht_number() {
assert!(::cht::block_to_cht_number(0).is_none());
assert_eq!(::cht::block_to_cht_number(1).unwrap(), 0);
assert_eq!(::cht::block_to_cht_number(::cht::SIZE + 1).unwrap(), 1);
assert_eq!(::cht::block_to_cht_number(::cht::SIZE).unwrap(), 0);
}
#[test]
fn start_number() {
assert_eq!(::cht::start_number(0), 1);
assert_eq!(::cht::start_number(1), ::cht::SIZE + 1);
assert_eq!(::cht::start_number(2), ::cht::SIZE * 2 + 1);
}
}
| {
let mut v = Vec::with_capacity(SIZE as usize);
let start_num = start_number(cht_num) as usize;
for (i, (h, td)) in iterable.into_iter().take(SIZE as usize).enumerate() {
v.push((key!(i + start_num).to_vec(), val!(h, td).to_vec()))
}
if v.len() == SIZE as usize {
Some(::util::triehash::trie_root(v))
} else {
None
}
} | identifier_body |
cht.rs | // Copyright 2015-2017 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.
//! Canonical hash trie definitions and helper functions.
//!
//! Each CHT is a trie mapping block numbers to canonical hashes and total difficulty.
//! One is generated for every `SIZE` blocks, allowing us to discard those blocks in
//! favor the the trie root. When the "ancient" blocks need to be accessed, we simply
//! request an inclusion proof of a specific block number against the trie with the
//! root has. A correct proof implies that the claimed block is identical to the one
//! we discarded.
use ethcore::ids::BlockId;
use util::{Bytes, H256, U256, HashDB, MemoryDB};
use util::trie::{self, TrieMut, TrieDBMut, Trie, TrieDB, Recorder};
use rlp::{Stream, RlpStream, UntrustedRlp, View};
// encode a key.
macro_rules! key {
($num: expr) => { ::rlp::encode(&$num) }
}
macro_rules! val {
($hash: expr, $td: expr) => {{
let mut stream = RlpStream::new_list(2);
stream.append(&$hash).append(&$td);
stream.drain()
}}
}
/// The size of each CHT.
pub const SIZE: u64 = 2048;
/// A canonical hash trie. This is generic over any database it can query.
/// See module docs for more details.
#[derive(Debug, Clone)]
pub struct CHT<DB: HashDB> {
db: DB,
root: H256, // the root of this CHT.
number: u64,
}
impl<DB: HashDB> CHT<DB> {
/// Query the root of the CHT.
pub fn root(&self) -> H256 { self.root }
/// Query the number of the CHT.
pub fn number(&self) -> u64 { self.number }
/// Generate an inclusion proof for the entry at a specific block.
/// Nodes before level `from_level` will be omitted.
/// Returns an error on an incomplete trie, and `Ok(None)` on an unprovable request.
pub fn prove(&self, num: u64, from_level: u32) -> trie::Result<Option<Vec<Bytes>>> {
if block_to_cht_number(num)!= Some(self.number) { return Ok(None) }
let mut recorder = Recorder::with_depth(from_level);
let t = TrieDB::new(&self.db, &self.root)?;
t.get_with(&key!(num), &mut recorder)?;
Ok(Some(recorder.drain().into_iter().map(|x| x.data).collect()))
}
}
/// Block information necessary to build a CHT.
pub struct BlockInfo {
/// The block's hash.
pub hash: H256,
/// The block's parent's hash.
pub parent_hash: H256,
/// The block's total difficulty.
pub total_difficulty: U256,
}
/// Build an in-memory CHT from a closure which provides necessary information
/// about blocks. If the fetcher ever fails to provide the info, the CHT
/// will not be generated.
pub fn build<F>(cht_num: u64, mut fetcher: F) -> Option<CHT<MemoryDB>>
where F: FnMut(BlockId) -> Option<BlockInfo>
{
let mut db = MemoryDB::new();
// start from the last block by number and work backwards.
let last_num = start_number(cht_num + 1) - 1;
let mut id = BlockId::Number(last_num);
let mut root = H256::default();
{
let mut t = TrieDBMut::new(&mut db, &mut root);
for blk_num in (0..SIZE).map(|n| last_num - n) {
let info = match fetcher(id) {
Some(info) => info,
None => return None,
};
id = BlockId::Hash(info.parent_hash);
t.insert(&key!(blk_num), &val!(info.hash, info.total_difficulty))
.expect("fresh in-memory database is infallible; qed");
}
}
Some(CHT {
db: db,
root: root,
number: cht_num,
})
}
/// Compute a CHT root from an iterator of (hash, td) pairs. Fails if shorter than
/// SIZE items. The items are assumed to proceed sequentially from `start_number(cht_num)`.
/// Discards the trie's nodes.
pub fn compute_root<I>(cht_num: u64, iterable: I) -> Option<H256>
where I: IntoIterator<Item=(H256, U256)>
{
let mut v = Vec::with_capacity(SIZE as usize);
let start_num = start_number(cht_num) as usize;
for (i, (h, td)) in iterable.into_iter().take(SIZE as usize).enumerate() {
v.push((key!(i + start_num).to_vec(), val!(h, td).to_vec()))
}
if v.len() == SIZE as usize {
Some(::util::triehash::trie_root(v))
} else {
None
}
}
/// Check a proof for a CHT.
/// Given a set of a trie nodes, a number to query, and a trie root,
/// verify the given trie branch and extract the canonical hash and total difficulty.
// TODO: better support for partially-checked queries.
pub fn check_proof(proof: &[Bytes], num: u64, root: H256) -> Option<(H256, U256)> {
let mut db = MemoryDB::new();
for node in proof { db.insert(&node[..]); }
let res = match TrieDB::new(&db, &root) {
Err(_) => return None,
Ok(trie) => trie.get_with(&key!(num), |val: &[u8]| {
let rlp = UntrustedRlp::new(val);
rlp.val_at::<H256>(0)
.and_then(|h| rlp.val_at::<U256>(1).map(|td| (h, td)))
.ok()
})
};
match res {
Ok(Some(Some((hash, td)))) => Some((hash, td)),
_ => None,
}
}
/// Convert a block number to a CHT number.
/// Returns `None` for `block_num` == 0, `Some` otherwise.
pub fn block_to_cht_number(block_num: u64) -> Option<u64> {
match block_num {
0 => None,
n => Some((n - 1) / SIZE),
}
}
/// Get the starting block of a given CHT.
/// CHT 0 includes block 1...SIZE,
/// CHT 1 includes block SIZE + 1... 2*SIZE
/// More generally: CHT N includes block (1 + N*SIZE)...((N+1)*SIZE).
/// This is because the genesis hash is assumed to be known
/// and including it would be redundant.
pub fn start_number(cht_num: u64) -> u64 {
(cht_num * SIZE) + 1
}
#[cfg(test)]
mod tests {
#[test]
fn size_is_lt_usize() {
// to ensure safe casting on the target platform.
assert!(::cht::SIZE < usize::max_value() as u64)
}
#[test]
fn | () {
assert!(::cht::block_to_cht_number(0).is_none());
assert_eq!(::cht::block_to_cht_number(1).unwrap(), 0);
assert_eq!(::cht::block_to_cht_number(::cht::SIZE + 1).unwrap(), 1);
assert_eq!(::cht::block_to_cht_number(::cht::SIZE).unwrap(), 0);
}
#[test]
fn start_number() {
assert_eq!(::cht::start_number(0), 1);
assert_eq!(::cht::start_number(1), ::cht::SIZE + 1);
assert_eq!(::cht::start_number(2), ::cht::SIZE * 2 + 1);
}
}
| block_to_cht_number | identifier_name |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::{build, Program};
use graphql_syntax::parse_executable;
use relay_codegen::{print_fragment, print_operation, JsModuleFormat};
use relay_test_schema::get_test_schema;
use relay_transforms::{sort_selections, transform_defer_stream};
use std::sync::Arc;
pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> | Ok(result.join("\n\n"))
}
| {
let ast = parse_executable(
fixture.content,
SourceLocationKey::standalone(fixture.file_name),
)
.unwrap();
let schema = get_test_schema();
let ir = build(&schema, &ast.definitions).unwrap();
let program = Program::from_definitions(Arc::clone(&schema), ir);
let next_program = sort_selections(&transform_defer_stream(&program).unwrap());
let mut result = next_program
.fragments()
.map(|def| print_fragment(&schema, &def, JsModuleFormat::Haste))
.chain(
next_program
.operations()
.map(|def| print_operation(&schema, &def, JsModuleFormat::Haste)),
)
.collect::<Vec<_>>();
result.sort_unstable(); | identifier_body |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::{build, Program};
use graphql_syntax::parse_executable;
use relay_codegen::{print_fragment, print_operation, JsModuleFormat};
use relay_test_schema::get_test_schema;
use relay_transforms::{sort_selections, transform_defer_stream};
use std::sync::Arc;
pub fn | (fixture: &Fixture<'_>) -> Result<String, String> {
let ast = parse_executable(
fixture.content,
SourceLocationKey::standalone(fixture.file_name),
)
.unwrap();
let schema = get_test_schema();
let ir = build(&schema, &ast.definitions).unwrap();
let program = Program::from_definitions(Arc::clone(&schema), ir);
let next_program = sort_selections(&transform_defer_stream(&program).unwrap());
let mut result = next_program
.fragments()
.map(|def| print_fragment(&schema, &def, JsModuleFormat::Haste))
.chain(
next_program
.operations()
.map(|def| print_operation(&schema, &def, JsModuleFormat::Haste)),
)
.collect::<Vec<_>>();
result.sort_unstable();
Ok(result.join("\n\n"))
}
| transform_fixture | identifier_name |
mod.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::{build, Program};
use graphql_syntax::parse_executable;
use relay_codegen::{print_fragment, print_operation, JsModuleFormat};
use relay_test_schema::get_test_schema;
use relay_transforms::{sort_selections, transform_defer_stream};
use std::sync::Arc;
pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> {
let ast = parse_executable(
fixture.content,
SourceLocationKey::standalone(fixture.file_name),
)
.unwrap();
let schema = get_test_schema();
let ir = build(&schema, &ast.definitions).unwrap();
let program = Program::from_definitions(Arc::clone(&schema), ir);
let next_program = sort_selections(&transform_defer_stream(&program).unwrap());
let mut result = next_program | .chain(
next_program
.operations()
.map(|def| print_operation(&schema, &def, JsModuleFormat::Haste)),
)
.collect::<Vec<_>>();
result.sort_unstable();
Ok(result.join("\n\n"))
} | .fragments()
.map(|def| print_fragment(&schema, &def, JsModuleFormat::Haste)) | random_line_split |
all.rs | use std::collections::HashMap;
use protobuf::descriptor::FileDescriptorProto;
use protobuf::reflect::FileDescriptor;
use protobuf_parse::ProtoPath;
use protobuf_parse::ProtoPathBuf;
use crate::compiler_plugin;
use crate::customize::ctx::CustomizeElemCtx;
use crate::customize::CustomizeCallback;
use crate::gen::file::gen_file;
use crate::gen::mod_rs::gen_mod_rs;
use crate::gen::scope::RootScope;
use crate::gen::well_known_types::gen_well_known_types_mod;
use crate::Customize;
pub(crate) fn | (
file_descriptors: &[FileDescriptorProto],
parser: &str,
files_to_generate: &[ProtoPathBuf],
customize: &Customize,
customize_callback: &dyn CustomizeCallback,
) -> anyhow::Result<Vec<compiler_plugin::GenResult>> {
let file_descriptors = FileDescriptor::new_dynamic_fds(file_descriptors.to_vec())?;
let root_scope = RootScope {
file_descriptors: &file_descriptors,
};
let mut results: Vec<compiler_plugin::GenResult> = Vec::new();
let files_map: HashMap<&ProtoPath, &FileDescriptor> = file_descriptors
.iter()
.map(|f| Ok((ProtoPath::new(f.proto().name())?, f)))
.collect::<Result<_, anyhow::Error>>()?;
let mut mods = Vec::new();
let customize = CustomizeElemCtx {
for_elem: customize.clone(),
for_children: customize.clone(),
callback: customize_callback,
};
for file_name in files_to_generate {
let file = files_map.get(file_name.as_path()).expect(&format!(
"file not found in file descriptors: {:?}, files: {:?}",
file_name,
files_map.keys()
));
let gen_file_result = gen_file(file, &files_map, &root_scope, &customize, parser)?;
results.push(gen_file_result.compiler_plugin_result);
mods.push(gen_file_result.mod_name);
}
if customize.for_elem.inside_protobuf.unwrap_or(false) {
results.push(gen_well_known_types_mod(&file_descriptors));
}
if customize.for_elem.gen_mod_rs.unwrap_or(true) {
results.push(gen_mod_rs(&mods));
}
Ok(results)
}
| gen_all | identifier_name |
all.rs | use std::collections::HashMap;
use protobuf::descriptor::FileDescriptorProto;
use protobuf::reflect::FileDescriptor;
use protobuf_parse::ProtoPath;
use protobuf_parse::ProtoPathBuf;
use crate::compiler_plugin;
use crate::customize::ctx::CustomizeElemCtx;
use crate::customize::CustomizeCallback;
use crate::gen::file::gen_file;
use crate::gen::mod_rs::gen_mod_rs;
use crate::gen::scope::RootScope;
use crate::gen::well_known_types::gen_well_known_types_mod;
use crate::Customize;
pub(crate) fn gen_all(
file_descriptors: &[FileDescriptorProto],
parser: &str,
files_to_generate: &[ProtoPathBuf],
customize: &Customize,
customize_callback: &dyn CustomizeCallback,
) -> anyhow::Result<Vec<compiler_plugin::GenResult>> {
let file_descriptors = FileDescriptor::new_dynamic_fds(file_descriptors.to_vec())?;
let root_scope = RootScope {
file_descriptors: &file_descriptors,
};
let mut results: Vec<compiler_plugin::GenResult> = Vec::new();
let files_map: HashMap<&ProtoPath, &FileDescriptor> = file_descriptors
.iter()
.map(|f| Ok((ProtoPath::new(f.proto().name())?, f)))
.collect::<Result<_, anyhow::Error>>()?;
let mut mods = Vec::new();
let customize = CustomizeElemCtx {
for_elem: customize.clone(),
for_children: customize.clone(),
callback: customize_callback,
};
for file_name in files_to_generate {
let file = files_map.get(file_name.as_path()).expect(&format!(
"file not found in file descriptors: {:?}, files: {:?}",
file_name,
files_map.keys()
));
let gen_file_result = gen_file(file, &files_map, &root_scope, &customize, parser)?;
results.push(gen_file_result.compiler_plugin_result);
mods.push(gen_file_result.mod_name);
}
if customize.for_elem.inside_protobuf.unwrap_or(false) {
results.push(gen_well_known_types_mod(&file_descriptors));
}
if customize.for_elem.gen_mod_rs.unwrap_or(true) |
Ok(results)
}
| {
results.push(gen_mod_rs(&mods));
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.