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 |
---|---|---|---|---|
render.rs | use syntax::ast::{Expr, Ident, Pat, Stmt, TokenTree};
use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use syntax::ptr::P;
use maud;
#[derive(Copy, Clone)]
pub enum Escape {
PassThru,
Escape,
}
pub struct Renderer<'cx> {
pub cx: &'cx ExtCtxt<'cx>,
w: Ident,
stmts: Vec<P<Stmt>>,
tail: String,
}
impl<'cx> Renderer<'cx> {
/// Creates a new `Renderer` using the given extension context.
pub fn new(cx: &'cx ExtCtxt<'cx>) -> Renderer<'cx> {
Renderer {
cx: cx,
w: Ident::new(token::intern("w")),
stmts: Vec::new(),
tail: String::new(),
}
}
/// Creates a new `Renderer` under the same context as `self`.
pub fn fork(&self) -> Renderer<'cx> {
Renderer {
cx: self.cx,
w: self.w,
stmts: Vec::new(),
tail: String::new(),
}
}
/// Flushes the tail buffer, emitting a single `.write_str()` call.
fn flush(&mut self) {
if!self.tail.is_empty() {
let expr = {
let w = self.w;
let s = &*self.tail;
quote_expr!(self.cx, $w.write_str($s))
};
let stmt = self.cx.stmt_expr(self.cx.expr_try(expr.span, expr));
self.stmts.push(stmt);
self.tail.clear();
}
}
/// Reifies the `Renderer` into a block of markup.
pub fn into_expr(mut self) -> P<Expr> {
let Renderer { cx, w, stmts,.. } = { self.flush(); self };
quote_expr!(cx,
::maud::rt::make_markup(|$w: &mut ::std::fmt::Write| -> Result<(), ::std::fmt::Error> {
use ::std::fmt::Write;
$stmts
Ok(())
}))
}
/// Reifies the `Renderer` into a raw list of statements.
pub fn into_stmts(mut self) -> Vec<P<Stmt>> {
let Renderer { stmts,.. } = { self.flush(); self };
stmts
}
/// Pushes a statement, flushing the tail buffer in the process.
fn push(&mut self, stmt: P<Stmt>) {
self.flush();
self.stmts.push(stmt);
}
/// Pushes a literal string to the tail buffer.
fn push_str(&mut self, s: &str) {
self.tail.push_str(s);
}
/// Appends a literal string, with the specified escaping method.
pub fn string(&mut self, s: &str, escape: Escape) {
let escaped;
let s = match escape {
Escape::PassThru => s,
Escape::Escape => { escaped = maud::escape(s); &*escaped },
};
self.push_str(s);
}
/// Appends the result of an expression, with the specified escaping method.
pub fn splice(&mut self, expr: P<Expr>, escape: Escape) {
let w = self.w;
let expr = match escape {
Escape::PassThru =>
quote_expr!(self.cx, write!($w, "{}", $expr)),
Escape::Escape =>
quote_expr!(self.cx,
write!(
::maud::rt::Escaper { inner: $w },
"{}",
$expr)),
};
let stmt = self.cx.stmt_expr(self.cx.expr_try(expr.span, expr));
self.push(stmt);
}
pub fn element_open_start(&mut self, name: &str) {
self.push_str("<");
self.push_str(name);
}
pub fn attribute_start(&mut self, name: &str) {
self.push_str(" ");
self.push_str(name);
self.push_str("=\"");
}
pub fn attribute_empty(&mut self, name: &str) {
self.push_str(" ");
self.push_str(name);
}
pub fn attribute_end(&mut self) {
self.push_str("\"");
}
pub fn element_open_end(&mut self) {
self.push_str(">");
}
pub fn element_close(&mut self, name: &str) {
self.push_str("</");
self.push_str(name);
self.push_str(">");
}
/// Emits an `if` expression.
///
/// The condition is a token tree (not an expression) so we don't
/// need to special-case `if let`.
pub fn emit_if(&mut self, if_cond: Vec<TokenTree>, if_body: Vec<P<Stmt>>,
else_body: Option<Vec<P<Stmt>>>) {
let stmt = match else_body {
None => quote_stmt!(self.cx, if $if_cond { $if_body }),
Some(else_body) =>
quote_stmt!(self.cx, if $if_cond { $if_body } else { $else_body }),
}.unwrap();
self.push(stmt);
}
pub fn emit_for(&mut self, pattern: P<Pat>, iterable: P<Expr>, body: Vec<P<Stmt>>) { | }
} | let stmt = quote_stmt!(self.cx, for $pattern in $iterable { $body }).unwrap();
self.push(stmt); | random_line_split |
render.rs | use syntax::ast::{Expr, Ident, Pat, Stmt, TokenTree};
use syntax::ext::base::ExtCtxt;
use syntax::ext::build::AstBuilder;
use syntax::parse::token;
use syntax::ptr::P;
use maud;
#[derive(Copy, Clone)]
pub enum Escape {
PassThru,
Escape,
}
pub struct Renderer<'cx> {
pub cx: &'cx ExtCtxt<'cx>,
w: Ident,
stmts: Vec<P<Stmt>>,
tail: String,
}
impl<'cx> Renderer<'cx> {
/// Creates a new `Renderer` using the given extension context.
pub fn new(cx: &'cx ExtCtxt<'cx>) -> Renderer<'cx> {
Renderer {
cx: cx,
w: Ident::new(token::intern("w")),
stmts: Vec::new(),
tail: String::new(),
}
}
/// Creates a new `Renderer` under the same context as `self`.
pub fn fork(&self) -> Renderer<'cx> {
Renderer {
cx: self.cx,
w: self.w,
stmts: Vec::new(),
tail: String::new(),
}
}
/// Flushes the tail buffer, emitting a single `.write_str()` call.
fn flush(&mut self) {
if!self.tail.is_empty() {
let expr = {
let w = self.w;
let s = &*self.tail;
quote_expr!(self.cx, $w.write_str($s))
};
let stmt = self.cx.stmt_expr(self.cx.expr_try(expr.span, expr));
self.stmts.push(stmt);
self.tail.clear();
}
}
/// Reifies the `Renderer` into a block of markup.
pub fn into_expr(mut self) -> P<Expr> {
let Renderer { cx, w, stmts,.. } = { self.flush(); self };
quote_expr!(cx,
::maud::rt::make_markup(|$w: &mut ::std::fmt::Write| -> Result<(), ::std::fmt::Error> {
use ::std::fmt::Write;
$stmts
Ok(())
}))
}
/// Reifies the `Renderer` into a raw list of statements.
pub fn into_stmts(mut self) -> Vec<P<Stmt>> {
let Renderer { stmts,.. } = { self.flush(); self };
stmts
}
/// Pushes a statement, flushing the tail buffer in the process.
fn push(&mut self, stmt: P<Stmt>) {
self.flush();
self.stmts.push(stmt);
}
/// Pushes a literal string to the tail buffer.
fn push_str(&mut self, s: &str) {
self.tail.push_str(s);
}
/// Appends a literal string, with the specified escaping method.
pub fn string(&mut self, s: &str, escape: Escape) {
let escaped;
let s = match escape {
Escape::PassThru => s,
Escape::Escape => { escaped = maud::escape(s); &*escaped },
};
self.push_str(s);
}
/// Appends the result of an expression, with the specified escaping method.
pub fn splice(&mut self, expr: P<Expr>, escape: Escape) {
let w = self.w;
let expr = match escape {
Escape::PassThru =>
quote_expr!(self.cx, write!($w, "{}", $expr)),
Escape::Escape =>
quote_expr!(self.cx,
write!(
::maud::rt::Escaper { inner: $w },
"{}",
$expr)),
};
let stmt = self.cx.stmt_expr(self.cx.expr_try(expr.span, expr));
self.push(stmt);
}
pub fn element_open_start(&mut self, name: &str) {
self.push_str("<");
self.push_str(name);
}
pub fn | (&mut self, name: &str) {
self.push_str(" ");
self.push_str(name);
self.push_str("=\"");
}
pub fn attribute_empty(&mut self, name: &str) {
self.push_str(" ");
self.push_str(name);
}
pub fn attribute_end(&mut self) {
self.push_str("\"");
}
pub fn element_open_end(&mut self) {
self.push_str(">");
}
pub fn element_close(&mut self, name: &str) {
self.push_str("</");
self.push_str(name);
self.push_str(">");
}
/// Emits an `if` expression.
///
/// The condition is a token tree (not an expression) so we don't
/// need to special-case `if let`.
pub fn emit_if(&mut self, if_cond: Vec<TokenTree>, if_body: Vec<P<Stmt>>,
else_body: Option<Vec<P<Stmt>>>) {
let stmt = match else_body {
None => quote_stmt!(self.cx, if $if_cond { $if_body }),
Some(else_body) =>
quote_stmt!(self.cx, if $if_cond { $if_body } else { $else_body }),
}.unwrap();
self.push(stmt);
}
pub fn emit_for(&mut self, pattern: P<Pat>, iterable: P<Expr>, body: Vec<P<Stmt>>) {
let stmt = quote_stmt!(self.cx, for $pattern in $iterable { $body }).unwrap();
self.push(stmt);
}
}
| attribute_start | identifier_name |
enum_explicit_type.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum Foo {
Bar = 0,
Qux = 1,
}
#[repr(i8)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum Neg {
MinusOne = -1,
One = 1,
}
#[repr(u16)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum Bigger {
Much = 255,
Larger = 256,
}
#[repr(i64)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum | {
MuchLow = -4294967296,
}
#[repr(i64)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum MuchLongLong {
I64_MIN = -9223372036854775808,
}
#[repr(u64)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum MuchULongLong {
MuchHigh = 4294967296,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum BoolEnumsAreFun {
Value = 1,
}
pub type MyType = bool;
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum BoolEnumsAreFun2 {
Value2 = 1,
}
pub const AnonymousVariantOne: _bindgen_ty_1 =
_bindgen_ty_1::AnonymousVariantOne;
pub const AnonymousVariantTwo: _bindgen_ty_1 =
_bindgen_ty_1::AnonymousVariantTwo;
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum _bindgen_ty_1 {
AnonymousVariantOne = 0,
AnonymousVariantTwo = 1,
}
| MuchLong | identifier_name |
enum_explicit_type.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum Foo {
Bar = 0,
Qux = 1,
} | pub enum Neg {
MinusOne = -1,
One = 1,
}
#[repr(u16)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum Bigger {
Much = 255,
Larger = 256,
}
#[repr(i64)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum MuchLong {
MuchLow = -4294967296,
}
#[repr(i64)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum MuchLongLong {
I64_MIN = -9223372036854775808,
}
#[repr(u64)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum MuchULongLong {
MuchHigh = 4294967296,
}
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum BoolEnumsAreFun {
Value = 1,
}
pub type MyType = bool;
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum BoolEnumsAreFun2 {
Value2 = 1,
}
pub const AnonymousVariantOne: _bindgen_ty_1 =
_bindgen_ty_1::AnonymousVariantOne;
pub const AnonymousVariantTwo: _bindgen_ty_1 =
_bindgen_ty_1::AnonymousVariantTwo;
#[repr(u8)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum _bindgen_ty_1 {
AnonymousVariantOne = 0,
AnonymousVariantTwo = 1,
} | #[repr(i8)]
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)] | random_line_split |
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling between these two components.
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use hyper::header::Headers;
use hyper::method::Method;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender, IpcSharedMemory};
use layers::geometry::DevicePixel;
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::fmt;
use std::sync::mpsc::channel;
use url::Url;
use util::geometry::{PagePx, ViewportPx};
use util::mem::HeapSizeOf;
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
#[derive(Deserialize, Serialize)]
pub struct ConstellationChan<T: Deserialize + Serialize>(pub IpcSender<T>);
impl<T: Deserialize + Serialize> ConstellationChan<T> {
pub fn new() -> (IpcReceiver<T>, ConstellationChan<T>) {
let (chan, port) = ipc::channel().unwrap();
(port, ConstellationChan(chan))
}
}
impl<T: Serialize + Deserialize> Clone for ConstellationChan<T> {
fn clone(&self) -> ConstellationChan<T> {
ConstellationChan(self.0.clone())
}
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum IFrameSandboxState {
IFrameSandboxed,
IFrameUnsandboxed
}
// We pass this info to various tasks, so it lives in a separate, cloneable struct.
#[derive(Clone, Copy, Deserialize, Serialize)]
pub struct Failure {
pub pipeline_id: PipelineId,
pub parent_info: Option<(PipelineId, SubpageId)>,
}
#[derive(Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct WindowSizeData {
/// The size of the initial layout viewport, before parsing an
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
pub initial_viewport: TypedSize2D<ViewportPx, f32>,
/// The "viewing area" in page px. See `PagePx` documentation for details.
pub visible_viewport: TypedSize2D<PagePx, f32>,
/// The resolution of the window in dppx, not including any "pinch zoom" factor.
pub device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>,
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum KeyState {
Pressed,
Released,
Repeated,
}
//N.B. Based on the glutin key enum
#[derive(Debug, PartialEq, Eq, Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LeftBracket,
Backslash,
RightBracket,
GraveAccent,
World1,
World2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Kp0,
Kp1,
Kp2,
Kp3,
Kp4,
Kp5,
Kp6,
Kp7,
Kp8,
Kp9,
KpDecimal,
KpDivide,
KpMultiply,
KpSubtract,
KpAdd,
KpEnter,
KpEqual,
LeftShift,
LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu,
}
bitflags! {
#[derive(Deserialize, Serialize)]
flags KeyModifiers: u8 {
const NONE = 0x00,
const SHIFT = 0x01,
const CONTROL = 0x02,
const ALT = 0x04,
const SUPER = 0x08,
}
}
/// Specifies the information required to load a URL in an iframe.
#[derive(Deserialize, Serialize)]
pub struct IframeLoadInfo {
/// Url to load
pub url: Option<Url>,
/// Pipeline ID of the parent of this iframe
pub containing_pipeline_id: PipelineId,
/// The new subpage ID for this load
pub new_subpage_id: SubpageId,
/// The old subpage ID for this iframe, if a page was previously loaded.
pub old_subpage_id: Option<SubpageId>,
/// The new pipeline ID that the iframe has generated.
pub new_pipeline_id: PipelineId,
/// Sandbox type of this iframe
pub sandbox: IFrameSandboxState,
}
#[derive(Deserialize, HeapSizeOf, Serialize)]
pub enum MouseEventType {
Click,
MouseDown,
MouseUp,
}
/// The mouse button involved in the event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum MouseButton {
/// The left mouse button.
Left,
/// The middle mouse button.
Middle,
/// The right mouse button.
Right,
}
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize, Debug)]
pub enum AnimationState {
AnimationsPresent,
AnimationCallbacksPresent,
NoAnimationsPresent,
NoAnimationCallbacksPresent,
}
/// Used to determine if a script has any pending asynchronous activity.
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize)]
pub enum DocumentState {
/// The document has been loaded and is idle.
Idle,
/// The document is either loading or waiting on an event.
Pending,
}
// https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API#Events
#[derive(Deserialize, Serialize)]
pub enum MozBrowserEvent {
/// Sent when the scroll position within a browser `<iframe>` changes.
AsyncScroll,
/// Sent when window.close() is called within a browser `<iframe>`.
Close,
/// Sent when a browser `<iframe>` tries to open a context menu. This allows
/// handling `<menuitem>` element available within the browser `<iframe>`'s content.
ContextMenu,
/// Sent when an error occurred while trying to load content within a browser `<iframe>`.
Error,
/// Sent when the favicon of a browser `<iframe>` changes.
IconChange(String, String, String),
/// Sent when the browser `<iframe>` has finished loading all its assets.
LoadEnd,
/// Sent when the browser `<iframe>` starts to load a new page.
LoadStart,
/// Sent when a browser `<iframe>`'s location changes.
LocationChange(String),
/// Sent when window.open() is called within a browser `<iframe>`.
OpenWindow,
/// Sent when the SSL state changes within a browser `<iframe>`.
SecurityChange,
/// Sent when alert(), confirm(), or prompt() is called within a browser `<iframe>`.
ShowModalPrompt(String, String, String, String), // TODO(simartin): Handle unblock()
/// Sent when the document.title changes within a browser `<iframe>`.
TitleChange(String),
/// Sent when an HTTP authentification is requested.
UsernameAndPasswordRequired,
/// Sent when a link to a search engine is found.
OpenSearch,
}
impl MozBrowserEvent {
pub fn name(&self) -> &'static str {
match *self {
MozBrowserEvent::AsyncScroll => "mozbrowserasyncscroll",
MozBrowserEvent::Close => "mozbrowserclose",
MozBrowserEvent::ContextMenu => "mozbrowsercontextmenu",
MozBrowserEvent::Error => "mozbrowsererror",
MozBrowserEvent::IconChange(_, _, _) => "mozbrowsericonchange",
MozBrowserEvent::LoadEnd => "mozbrowserloadend",
MozBrowserEvent::LoadStart => "mozbrowserloadstart",
MozBrowserEvent::LocationChange(_) => "mozbrowserlocationchange",
MozBrowserEvent::OpenWindow => "mozbrowseropenwindow",
MozBrowserEvent::SecurityChange => "mozbrowsersecuritychange",
MozBrowserEvent::ShowModalPrompt(_, _, _, _) => "mozbrowsershowmodalprompt",
MozBrowserEvent::TitleChange(_) => "mozbrowsertitlechange",
MozBrowserEvent::UsernameAndPasswordRequired => "mozbrowserusernameandpasswordrequired",
MozBrowserEvent::OpenSearch => "mozbrowseropensearch"
}
}
}
#[derive(Deserialize, Serialize)]
pub enum WebDriverCommandMsg {
LoadUrl(PipelineId, LoadData, IpcSender<LoadStatus>),
Refresh(PipelineId, IpcSender<LoadStatus>),
ScriptCommand(PipelineId, WebDriverScriptCommand),
SendKeys(PipelineId, Vec<(Key, KeyModifiers, KeyState)>),
TakeScreenshot(PipelineId, IpcSender<Option<Image>>),
}
#[derive(Deserialize, Eq, PartialEq, Serialize, HeapSizeOf)]
pub enum PixelFormat {
K8, // Luminance channel only
KA8, // Luminance + alpha
RGB8, // RGB, 8 bits per channel
RGBA8, // RGB + alpha, 8 bits per channel
}
#[derive(Deserialize, Serialize, HeapSizeOf)]
pub struct | {
pub width: u32,
pub height: u32,
pub format: PixelFormat,
#[ignore_heap_size_of = "Defined in ipc-channel"]
pub bytes: IpcSharedMemory,
}
/// Similar to net::resource_task::LoadData
/// can be passed to LoadUrl to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Deserialize, Serialize)]
pub struct LoadData {
pub url: Url,
pub method: Method,
pub headers: Headers,
pub data: Option<Vec<u8>>,
}
impl LoadData {
pub fn new(url: Url) -> LoadData {
LoadData {
url: url,
method: Method::Get,
headers: Headers::new(),
data: None,
}
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)]
pub enum NavigationDirection {
Forward,
Back,
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)]
pub struct FrameId(pub u32);
/// Each pipeline ID needs to be unique. However, it also needs to be possible to
/// generate the pipeline ID from an iframe element (this simplifies a lot of other
/// code that makes use of pipeline IDs).
///
/// To achieve this, each pipeline index belongs to a particular namespace. There is
/// a namespace for the constellation thread, and also one for every script thread.
/// This allows pipeline IDs to be generated by any of those threads without conflicting
/// with pipeline IDs created by other script threads or the constellation. The
/// constellation is the only code that is responsible for creating new *namespaces*.
/// This ensures that namespaces are always unique, even when using multi-process mode.
///
/// It may help conceptually to think of the namespace ID as an identifier for the
/// thread that created this pipeline ID - however this is really an implementation
/// detail so shouldn't be relied upon in code logic. It's best to think of the
/// pipeline ID as a simple unique identifier that doesn't convey any more information.
#[derive(Clone, Copy)]
pub struct PipelineNamespace {
id: PipelineNamespaceId,
next_index: PipelineIndex,
}
impl PipelineNamespace {
pub fn install(namespace_id: PipelineNamespaceId) {
PIPELINE_NAMESPACE.with(|tls| {
assert!(tls.get().is_none());
tls.set(Some(PipelineNamespace {
id: namespace_id,
next_index: PipelineIndex(0),
}));
});
}
fn next(&mut self) -> PipelineId {
let pipeline_id = PipelineId {
namespace_id: self.id,
index: self.next_index,
};
let PipelineIndex(current_index) = self.next_index;
self.next_index = PipelineIndex(current_index + 1);
pipeline_id
}
}
thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = Cell::new(None));
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineNamespaceId(pub u32);
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineIndex(pub u32);
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineId {
pub namespace_id: PipelineNamespaceId,
pub index: PipelineIndex
}
impl PipelineId {
pub fn new() -> PipelineId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_pipeline_id = namespace.next();
tls.set(Some(namespace));
new_pipeline_id
})
}
// TODO(gw): This should be removed. It's only required because of the code
// that uses it in the devtools lib.rs file (which itself is a TODO). Once
// that is fixed, this should be removed. It also relies on the first
// call to PipelineId::new() returning (0,0), which is checked with an
// assert in handle_init_load().
pub fn fake_root_pipeline_id() -> PipelineId {
PipelineId {
namespace_id: PipelineNamespaceId(0),
index: PipelineIndex(0),
}
}
}
impl fmt::Display for PipelineId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index)
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct SubpageId(pub u32);
| Image | identifier_name |
constellation_msg.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/. */
//! The high-level interface from script to constellation. Using this abstract interface helps
//! reduce coupling between these two components.
use euclid::scale_factor::ScaleFactor;
use euclid::size::TypedSize2D;
use hyper::header::Headers;
use hyper::method::Method;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender, IpcSharedMemory};
use layers::geometry::DevicePixel;
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::fmt;
use std::sync::mpsc::channel;
use url::Url;
use util::geometry::{PagePx, ViewportPx};
use util::mem::HeapSizeOf;
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
#[derive(Deserialize, Serialize)]
pub struct ConstellationChan<T: Deserialize + Serialize>(pub IpcSender<T>);
impl<T: Deserialize + Serialize> ConstellationChan<T> {
pub fn new() -> (IpcReceiver<T>, ConstellationChan<T>) {
let (chan, port) = ipc::channel().unwrap();
(port, ConstellationChan(chan))
}
}
impl<T: Serialize + Deserialize> Clone for ConstellationChan<T> {
fn clone(&self) -> ConstellationChan<T> {
ConstellationChan(self.0.clone())
}
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum IFrameSandboxState {
IFrameSandboxed,
IFrameUnsandboxed
}
// We pass this info to various tasks, so it lives in a separate, cloneable struct.
#[derive(Clone, Copy, Deserialize, Serialize)]
pub struct Failure {
pub pipeline_id: PipelineId,
pub parent_info: Option<(PipelineId, SubpageId)>,
}
#[derive(Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub struct WindowSizeData {
/// The size of the initial layout viewport, before parsing an
/// http://www.w3.org/TR/css-device-adapt/#initial-viewport
pub initial_viewport: TypedSize2D<ViewportPx, f32>,
/// The "viewing area" in page px. See `PagePx` documentation for details.
pub visible_viewport: TypedSize2D<PagePx, f32>,
/// The resolution of the window in dppx, not including any "pinch zoom" factor.
pub device_pixel_ratio: ScaleFactor<ViewportPx, DevicePixel, f32>,
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, Deserialize, Serialize)]
pub enum KeyState {
Pressed,
Released,
Repeated,
}
//N.B. Based on the glutin key enum
#[derive(Debug, PartialEq, Eq, Copy, Clone, Deserialize, Serialize, HeapSizeOf)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
LeftBracket,
Backslash,
RightBracket,
GraveAccent,
World1,
World2,
Escape,
Enter,
Tab,
Backspace,
Insert,
Delete,
Right,
Left,
Down,
Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23,
F24,
F25,
Kp0,
Kp1,
Kp2,
Kp3,
Kp4,
Kp5,
Kp6,
Kp7,
Kp8,
Kp9,
KpDecimal,
KpDivide,
KpMultiply,
KpSubtract,
KpAdd,
KpEnter,
KpEqual,
LeftShift,
LeftControl,
LeftAlt,
LeftSuper,
RightShift,
RightControl,
RightAlt,
RightSuper,
Menu,
}
bitflags! {
#[derive(Deserialize, Serialize)]
flags KeyModifiers: u8 {
const NONE = 0x00,
const SHIFT = 0x01,
const CONTROL = 0x02,
const ALT = 0x04,
const SUPER = 0x08,
}
}
/// Specifies the information required to load a URL in an iframe.
#[derive(Deserialize, Serialize)]
pub struct IframeLoadInfo {
/// Url to load
pub url: Option<Url>,
/// Pipeline ID of the parent of this iframe
pub containing_pipeline_id: PipelineId,
/// The new subpage ID for this load
pub new_subpage_id: SubpageId,
/// The old subpage ID for this iframe, if a page was previously loaded.
pub old_subpage_id: Option<SubpageId>,
/// The new pipeline ID that the iframe has generated.
pub new_pipeline_id: PipelineId,
/// Sandbox type of this iframe
pub sandbox: IFrameSandboxState,
}
#[derive(Deserialize, HeapSizeOf, Serialize)]
pub enum MouseEventType {
Click,
MouseDown,
MouseUp,
}
/// The mouse button involved in the event.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub enum MouseButton {
/// The left mouse button.
Left,
/// The middle mouse button.
Middle,
/// The right mouse button.
Right,
}
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize, Debug)]
pub enum AnimationState {
AnimationsPresent,
AnimationCallbacksPresent,
NoAnimationsPresent,
NoAnimationCallbacksPresent,
}
/// Used to determine if a script has any pending asynchronous activity.
#[derive(Copy, Clone, Debug, PartialEq, Deserialize, Serialize)]
pub enum DocumentState {
/// The document has been loaded and is idle.
Idle,
/// The document is either loading or waiting on an event.
Pending,
}
// https://developer.mozilla.org/en-US/docs/Web/API/Using_the_Browser_API#Events
#[derive(Deserialize, Serialize)]
pub enum MozBrowserEvent {
/// Sent when the scroll position within a browser `<iframe>` changes.
AsyncScroll,
/// Sent when window.close() is called within a browser `<iframe>`.
Close,
/// Sent when a browser `<iframe>` tries to open a context menu. This allows
/// handling `<menuitem>` element available within the browser `<iframe>`'s content.
ContextMenu,
/// Sent when an error occurred while trying to load content within a browser `<iframe>`.
Error,
/// Sent when the favicon of a browser `<iframe>` changes.
IconChange(String, String, String),
/// Sent when the browser `<iframe>` has finished loading all its assets.
LoadEnd,
/// Sent when the browser `<iframe>` starts to load a new page.
LoadStart,
/// Sent when a browser `<iframe>`'s location changes.
LocationChange(String),
/// Sent when window.open() is called within a browser `<iframe>`.
OpenWindow,
/// Sent when the SSL state changes within a browser `<iframe>`.
SecurityChange,
/// Sent when alert(), confirm(), or prompt() is called within a browser `<iframe>`.
ShowModalPrompt(String, String, String, String), // TODO(simartin): Handle unblock()
/// Sent when the document.title changes within a browser `<iframe>`.
TitleChange(String),
/// Sent when an HTTP authentification is requested.
UsernameAndPasswordRequired,
/// Sent when a link to a search engine is found.
OpenSearch,
}
impl MozBrowserEvent {
pub fn name(&self) -> &'static str {
match *self {
MozBrowserEvent::AsyncScroll => "mozbrowserasyncscroll",
MozBrowserEvent::Close => "mozbrowserclose",
MozBrowserEvent::ContextMenu => "mozbrowsercontextmenu",
MozBrowserEvent::Error => "mozbrowsererror",
MozBrowserEvent::IconChange(_, _, _) => "mozbrowsericonchange",
MozBrowserEvent::LoadEnd => "mozbrowserloadend",
MozBrowserEvent::LoadStart => "mozbrowserloadstart",
MozBrowserEvent::LocationChange(_) => "mozbrowserlocationchange",
MozBrowserEvent::OpenWindow => "mozbrowseropenwindow",
MozBrowserEvent::SecurityChange => "mozbrowsersecuritychange",
MozBrowserEvent::ShowModalPrompt(_, _, _, _) => "mozbrowsershowmodalprompt",
MozBrowserEvent::TitleChange(_) => "mozbrowsertitlechange",
MozBrowserEvent::UsernameAndPasswordRequired => "mozbrowserusernameandpasswordrequired",
MozBrowserEvent::OpenSearch => "mozbrowseropensearch"
}
}
}
#[derive(Deserialize, Serialize)]
pub enum WebDriverCommandMsg {
LoadUrl(PipelineId, LoadData, IpcSender<LoadStatus>),
Refresh(PipelineId, IpcSender<LoadStatus>),
ScriptCommand(PipelineId, WebDriverScriptCommand),
SendKeys(PipelineId, Vec<(Key, KeyModifiers, KeyState)>),
TakeScreenshot(PipelineId, IpcSender<Option<Image>>),
}
#[derive(Deserialize, Eq, PartialEq, Serialize, HeapSizeOf)]
pub enum PixelFormat {
K8, // Luminance channel only
KA8, // Luminance + alpha
RGB8, // RGB, 8 bits per channel
RGBA8, // RGB + alpha, 8 bits per channel
}
#[derive(Deserialize, Serialize, HeapSizeOf)]
pub struct Image {
pub width: u32,
pub height: u32,
pub format: PixelFormat,
#[ignore_heap_size_of = "Defined in ipc-channel"]
pub bytes: IpcSharedMemory,
}
/// Similar to net::resource_task::LoadData
/// can be passed to LoadUrl to load a page with GET/POST
/// parameters or headers
#[derive(Clone, Deserialize, Serialize)]
pub struct LoadData {
pub url: Url,
pub method: Method,
pub headers: Headers,
pub data: Option<Vec<u8>>,
}
impl LoadData {
pub fn new(url: Url) -> LoadData {
LoadData {
url: url,
method: Method::Get,
headers: Headers::new(),
data: None,
}
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)]
pub enum NavigationDirection {
Forward,
Back,
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize)]
pub struct FrameId(pub u32);
/// Each pipeline ID needs to be unique. However, it also needs to be possible to
/// generate the pipeline ID from an iframe element (this simplifies a lot of other
/// code that makes use of pipeline IDs).
///
/// To achieve this, each pipeline index belongs to a particular namespace. There is
/// a namespace for the constellation thread, and also one for every script thread.
/// This allows pipeline IDs to be generated by any of those threads without conflicting
/// with pipeline IDs created by other script threads or the constellation. The
/// constellation is the only code that is responsible for creating new *namespaces*.
/// This ensures that namespaces are always unique, even when using multi-process mode.
///
/// It may help conceptually to think of the namespace ID as an identifier for the
/// thread that created this pipeline ID - however this is really an implementation
/// detail so shouldn't be relied upon in code logic. It's best to think of the
/// pipeline ID as a simple unique identifier that doesn't convey any more information.
#[derive(Clone, Copy)]
pub struct PipelineNamespace { |
impl PipelineNamespace {
pub fn install(namespace_id: PipelineNamespaceId) {
PIPELINE_NAMESPACE.with(|tls| {
assert!(tls.get().is_none());
tls.set(Some(PipelineNamespace {
id: namespace_id,
next_index: PipelineIndex(0),
}));
});
}
fn next(&mut self) -> PipelineId {
let pipeline_id = PipelineId {
namespace_id: self.id,
index: self.next_index,
};
let PipelineIndex(current_index) = self.next_index;
self.next_index = PipelineIndex(current_index + 1);
pipeline_id
}
}
thread_local!(pub static PIPELINE_NAMESPACE: Cell<Option<PipelineNamespace>> = Cell::new(None));
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineNamespaceId(pub u32);
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineIndex(pub u32);
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct PipelineId {
pub namespace_id: PipelineNamespaceId,
pub index: PipelineIndex
}
impl PipelineId {
pub fn new() -> PipelineId {
PIPELINE_NAMESPACE.with(|tls| {
let mut namespace = tls.get().expect("No namespace set for this thread!");
let new_pipeline_id = namespace.next();
tls.set(Some(namespace));
new_pipeline_id
})
}
// TODO(gw): This should be removed. It's only required because of the code
// that uses it in the devtools lib.rs file (which itself is a TODO). Once
// that is fixed, this should be removed. It also relies on the first
// call to PipelineId::new() returning (0,0), which is checked with an
// assert in handle_init_load().
pub fn fake_root_pipeline_id() -> PipelineId {
PipelineId {
namespace_id: PipelineNamespaceId(0),
index: PipelineIndex(0),
}
}
}
impl fmt::Display for PipelineId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index)
}
}
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct SubpageId(pub u32); | id: PipelineNamespaceId,
next_index: PipelineIndex,
} | random_line_split |
build_schema.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 crate::compiler_state::CompilerState;
use crate::config::ProjectConfig;
use schema::Schema;
pub fn | (compiler_state: &CompilerState, project_config: &ProjectConfig) -> Schema {
let relay_extensions = String::from(schema::RELAY_EXTENSIONS);
let mut extensions = vec![&relay_extensions];
if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) {
extensions.extend(project_extensions);
}
if let Some(base_project_name) = project_config.base {
if let Some(base_project_extensions) = compiler_state.extensions.get(&base_project_name) {
extensions.extend(base_project_extensions);
}
}
let mut schema_sources = Vec::new();
schema_sources.extend(
compiler_state.schemas[&project_config.name]
.iter()
.map(String::as_str),
);
schema::build_schema_with_extensions(&schema_sources, &extensions).unwrap()
}
| build_schema | identifier_name |
build_schema.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 crate::compiler_state::CompilerState;
use crate::config::ProjectConfig;
use schema::Schema;
pub fn build_schema(compiler_state: &CompilerState, project_config: &ProjectConfig) -> Schema | {
let relay_extensions = String::from(schema::RELAY_EXTENSIONS);
let mut extensions = vec![&relay_extensions];
if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) {
extensions.extend(project_extensions);
}
if let Some(base_project_name) = project_config.base {
if let Some(base_project_extensions) = compiler_state.extensions.get(&base_project_name) {
extensions.extend(base_project_extensions);
}
}
let mut schema_sources = Vec::new();
schema_sources.extend(
compiler_state.schemas[&project_config.name]
.iter()
.map(String::as_str),
);
schema::build_schema_with_extensions(&schema_sources, &extensions).unwrap()
} | identifier_body |
|
build_schema.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 crate::compiler_state::CompilerState;
use crate::config::ProjectConfig;
use schema::Schema;
pub fn build_schema(compiler_state: &CompilerState, project_config: &ProjectConfig) -> Schema {
let relay_extensions = String::from(schema::RELAY_EXTENSIONS);
let mut extensions = vec![&relay_extensions];
if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) {
extensions.extend(project_extensions);
}
if let Some(base_project_name) = project_config.base {
if let Some(base_project_extensions) = compiler_state.extensions.get(&base_project_name) |
}
let mut schema_sources = Vec::new();
schema_sources.extend(
compiler_state.schemas[&project_config.name]
.iter()
.map(String::as_str),
);
schema::build_schema_with_extensions(&schema_sources, &extensions).unwrap()
}
| {
extensions.extend(base_project_extensions);
} | conditional_block |
build_schema.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 crate::compiler_state::CompilerState;
use crate::config::ProjectConfig;
use schema::Schema;
pub fn build_schema(compiler_state: &CompilerState, project_config: &ProjectConfig) -> Schema { | if let Some(base_project_name) = project_config.base {
if let Some(base_project_extensions) = compiler_state.extensions.get(&base_project_name) {
extensions.extend(base_project_extensions);
}
}
let mut schema_sources = Vec::new();
schema_sources.extend(
compiler_state.schemas[&project_config.name]
.iter()
.map(String::as_str),
);
schema::build_schema_with_extensions(&schema_sources, &extensions).unwrap()
} | let relay_extensions = String::from(schema::RELAY_EXTENSIONS);
let mut extensions = vec![&relay_extensions];
if let Some(project_extensions) = compiler_state.extensions.get(&project_config.name) {
extensions.extend(project_extensions);
} | random_line_split |
util.rs | use std::fmt::Debug;
#[macro_export]
macro_rules! unwrap_msg (
($e:expr) => (
($e).unwrap_log(file!(), line!(), module_path!(), stringify!($e))
)
);
pub trait UnwrapLog<T> {
fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T;
}
impl<T> UnwrapLog<T> for Option<T> {
fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T {
match self {
Some(t) => t,
None => panic!("{}:{} {} this should not have panicked:\ntried to unwrap `None` in:\nunwrap_msg!({})", file, line, module_path, expression)
}
}
}
impl<T,E:Debug> UnwrapLog<T> for Result<T,E> {
fn | (self, file: &str, line: u32, module_path: &str, expression: &str) -> T {
match self {
Ok(t) => t,
Err(e) => panic!("{}:{} {} this should not have panicked:\ntried to unwrap Err({:?}) in\nunwrap_msg!({})", file, line, module_path, e, expression)
}
}
}
#[macro_export]
macro_rules! assert_size (
($t:ty, $sz:expr) => (
assert_eq!(::std::mem::size_of::<$t>(), $sz);
);
);
| unwrap_log | identifier_name |
util.rs | use std::fmt::Debug;
#[macro_export]
macro_rules! unwrap_msg (
($e:expr) => (
($e).unwrap_log(file!(), line!(), module_path!(), stringify!($e))
)
);
pub trait UnwrapLog<T> {
fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T;
}
impl<T> UnwrapLog<T> for Option<T> {
fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T {
match self {
Some(t) => t,
None => panic!("{}:{} {} this should not have panicked:\ntried to unwrap `None` in:\nunwrap_msg!({})", file, line, module_path, expression)
}
}
}
impl<T,E:Debug> UnwrapLog<T> for Result<T,E> {
fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T {
match self {
Ok(t) => t,
Err(e) => panic!("{}:{} {} this should not have panicked:\ntried to unwrap Err({:?}) in\nunwrap_msg!({})", file, line, module_path, e, expression)
}
}
}
| ); | #[macro_export]
macro_rules! assert_size (
($t:ty, $sz:expr) => (
assert_eq!(::std::mem::size_of::<$t>(), $sz);
); | random_line_split |
util.rs | use std::fmt::Debug;
#[macro_export]
macro_rules! unwrap_msg (
($e:expr) => (
($e).unwrap_log(file!(), line!(), module_path!(), stringify!($e))
)
);
pub trait UnwrapLog<T> {
fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T;
}
impl<T> UnwrapLog<T> for Option<T> {
fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T |
}
impl<T,E:Debug> UnwrapLog<T> for Result<T,E> {
fn unwrap_log(self, file: &str, line: u32, module_path: &str, expression: &str) -> T {
match self {
Ok(t) => t,
Err(e) => panic!("{}:{} {} this should not have panicked:\ntried to unwrap Err({:?}) in\nunwrap_msg!({})", file, line, module_path, e, expression)
}
}
}
#[macro_export]
macro_rules! assert_size (
($t:ty, $sz:expr) => (
assert_eq!(::std::mem::size_of::<$t>(), $sz);
);
);
| {
match self {
Some(t) => t,
None => panic!("{}:{} {} this should not have panicked:\ntried to unwrap `None` in:\nunwrap_msg!({})", file, line, module_path, expression)
}
} | identifier_body |
text.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Text",
inherited=False,
gecko_name="TextReset",
additional_methods=[Method("has_underline", "bool"),
Method("has_overline", "bool"),
Method("has_line_through", "bool")]) %>
<%helpers:longhand name="text-overflow" animation_value_type="discrete" boxed="True"
flags="APPLIES_TO_PLACEHOLDER"
spec="https://drafts.csswg.org/css-ui/#propdef-text-overflow">
use std::fmt;
use style_traits::ToCss;
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
pub enum Side {
Clip,
Ellipsis,
String(Box<str>),
}
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
pub struct SpecifiedValue {
pub first: Side,
pub second: Option<Side>
}
pub mod computed_value {
pub use super::Side;
#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
pub struct T {
// When the specified value only has one side, that's the "second"
// side, and the sides are logical, so "second" means "end". The
// start side is Clip in that case.
//
// When the specified value has two sides, those are our "first"
// and "second" sides, and they are physical sides ("left" and
// "right").
pub first: Side,
pub second: Side,
pub sides_are_logical: bool
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.sides_are_logical {
assert!(self.first == Side::Clip);
self.second.to_css(dest)?;
} else {
self.first.to_css(dest)?;
dest.write_str(" ")?;
self.second.to_css(dest)?;
}
Ok(())
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
if let Some(ref second) = self.second {
Self::ComputedValue { first: self.first.clone(),
second: second.clone(),
sides_are_logical: false }
} else {
Self::ComputedValue { first: Side::Clip,
second: self.first.clone(),
sides_are_logical: true }
}
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
if computed.sides_are_logical {
assert!(computed.first == Side::Clip);
SpecifiedValue { first: computed.second.clone(),
second: None }
} else {
SpecifiedValue { first: computed.first.clone(),
second: Some(computed.second.clone()) }
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T {
first: Side::Clip,
second: Side::Clip,
sides_are_logical: true,
}
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let first = Side::parse(context, input)?;
let second = input.try(|input| Side::parse(context, input)).ok();
Ok(SpecifiedValue {
first: first,
second: second,
})
}
impl Parse for Side {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Side, ParseError<'i>> {
let location = input.current_source_location();
match *input.next()? {
Token::Ident(ref ident) => {
match_ignore_ascii_case! { ident,
"clip" => Ok(Side::Clip),
"ellipsis" => Ok(Side::Ellipsis),
_ => Err(location.new_custom_error(
SelectorParseErrorKind::UnexpectedIdent(ident.clone())
))
}
}
Token::QuotedString(ref v) => {
Ok(Side::String(v.as_ref().to_owned().into_boxed_str()))
}
ref t => Err(location.new_unexpected_token_error(t.clone())),
}
}
}
</%helpers:longhand>
${helpers.single_keyword("unicode-bidi",
"normal embed isolate bidi-override isolate-override plaintext",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-writing-modes/#propdef-unicode-bidi")}
<%helpers:longhand name="text-decoration-line"
custom_cascade="${product =='servo'}"
animation_value_type="discrete"
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-line">
use std::fmt;
use style_traits::ToCss;
bitflags! {
#[derive(MallocSizeOf, ToComputedValue)]
pub flags SpecifiedValue: u8 {
const NONE = 0,
const UNDERLINE = 0x01,
const OVERLINE = 0x02,
const LINE_THROUGH = 0x04,
const BLINK = 0x08,
% if product == "gecko":
/// Only set by presentation attributes
///
/// Setting this will mean that text-decorations use the color
/// specified by `color` in quirks mode.
///
/// For example, this gives <a href=foo><font color="red">text</font></a>
/// a red text decoration
const COLOR_OVERRIDE = 0x10,
% endif
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut has_any = false;
macro_rules! write_value {
($line:ident => $css:expr) => {
if self.contains($line) {
if has_any {
dest.write_str(" ")?;
}
dest.write_str($css)?;
has_any = true;
}
}
}
write_value!(UNDERLINE => "underline");
write_value!(OVERLINE => "overline");
write_value!(LINE_THROUGH => "line-through");
write_value!(BLINK => "blink");
if!has_any {
dest.write_str("none")?;
}
Ok(())
}
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
#[allow(non_upper_case_globals)]
pub const none: T = super::SpecifiedValue {
bits: 0
};
}
#[inline] pub fn get_initial_value() -> computed_value::T {
computed_value::none
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::empty()
}
/// none | [ underline || overline || line-through || blink ]
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let mut result = SpecifiedValue::empty();
if input.try(|input| input.expect_ident_matching("none")).is_ok() |
let mut empty = true;
loop {
let result: Result<_, ParseError> = input.try(|input| {
let location = input.current_source_location();
match input.expect_ident() {
Ok(ident) => {
(match_ignore_ascii_case! { &ident,
"underline" => if result.contains(UNDERLINE) { Err(()) }
else { empty = false; result.insert(UNDERLINE); Ok(()) },
"overline" => if result.contains(OVERLINE) { Err(()) }
else { empty = false; result.insert(OVERLINE); Ok(()) },
"line-through" => if result.contains(LINE_THROUGH) { Err(()) }
else { empty = false; result.insert(LINE_THROUGH); Ok(()) },
"blink" => if result.contains(BLINK) { Err(()) }
else { empty = false; result.insert(BLINK); Ok(()) },
_ => Err(())
}).map_err(|()| {
location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))
})
}
Err(e) => return Err(e.into())
}
});
if result.is_err() {
break;
}
}
if!empty { Ok(result) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) }
}
% if product == "servo":
fn cascade_property_custom(_declaration: &PropertyDeclaration,
context: &mut computed::Context) {
longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context);
}
% endif
#[cfg(feature = "gecko")]
impl_bitflags_conversions!(SpecifiedValue);
</%helpers:longhand>
${helpers.single_keyword("text-decoration-style",
"solid double dotted dashed wavy -moz-none",
products="gecko",
animation_value_type="discrete",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-style")}
${helpers.predefined_type(
"text-decoration-color",
"Color",
"computed_value::T::currentcolor()",
initial_specified_value="specified::Color::currentcolor()",
products="gecko",
animation_value_type="AnimatedColor",
ignored_when_colors_disabled=True,
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-color",
)}
${helpers.predefined_type(
"initial-letter",
"InitialLetter",
"computed::InitialLetter::normal()",
initial_specified_value="specified::InitialLetter::normal()",
animation_value_type="discrete",
products="gecko",
flags="APPLIES_TO_FIRST_LETTER",
spec="https://drafts.csswg.org/css-inline/#sizing-drop-initials")}
| {
return Ok(result)
} | conditional_block |
text.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Text",
inherited=False,
gecko_name="TextReset",
additional_methods=[Method("has_underline", "bool"),
Method("has_overline", "bool"),
Method("has_line_through", "bool")]) %>
<%helpers:longhand name="text-overflow" animation_value_type="discrete" boxed="True"
flags="APPLIES_TO_PLACEHOLDER"
spec="https://drafts.csswg.org/css-ui/#propdef-text-overflow">
use std::fmt;
use style_traits::ToCss;
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
pub enum Side {
Clip,
Ellipsis,
String(Box<str>),
}
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
pub struct SpecifiedValue {
pub first: Side,
pub second: Option<Side>
}
pub mod computed_value {
pub use super::Side;
#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
pub struct T {
// When the specified value only has one side, that's the "second"
// side, and the sides are logical, so "second" means "end". The
// start side is Clip in that case.
//
// When the specified value has two sides, those are our "first"
// and "second" sides, and they are physical sides ("left" and
// "right").
pub first: Side,
pub second: Side,
pub sides_are_logical: bool
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.sides_are_logical {
assert!(self.first == Side::Clip);
self.second.to_css(dest)?;
} else {
self.first.to_css(dest)?;
dest.write_str(" ")?;
self.second.to_css(dest)?;
}
Ok(())
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
if let Some(ref second) = self.second {
Self::ComputedValue { first: self.first.clone(),
second: second.clone(),
sides_are_logical: false }
} else {
Self::ComputedValue { first: Side::Clip,
second: self.first.clone(),
sides_are_logical: true }
}
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
if computed.sides_are_logical {
assert!(computed.first == Side::Clip);
SpecifiedValue { first: computed.second.clone(),
second: None }
} else {
SpecifiedValue { first: computed.first.clone(),
second: Some(computed.second.clone()) }
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T {
first: Side::Clip,
second: Side::Clip,
sides_are_logical: true,
}
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let first = Side::parse(context, input)?;
let second = input.try(|input| Side::parse(context, input)).ok();
Ok(SpecifiedValue {
first: first,
second: second,
})
}
impl Parse for Side {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Side, ParseError<'i>> {
let location = input.current_source_location();
match *input.next()? {
Token::Ident(ref ident) => {
match_ignore_ascii_case! { ident,
"clip" => Ok(Side::Clip),
"ellipsis" => Ok(Side::Ellipsis),
_ => Err(location.new_custom_error(
SelectorParseErrorKind::UnexpectedIdent(ident.clone())
))
}
}
Token::QuotedString(ref v) => {
Ok(Side::String(v.as_ref().to_owned().into_boxed_str()))
}
ref t => Err(location.new_unexpected_token_error(t.clone())),
}
}
}
</%helpers:longhand>
${helpers.single_keyword("unicode-bidi",
"normal embed isolate bidi-override isolate-override plaintext",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-writing-modes/#propdef-unicode-bidi")}
<%helpers:longhand name="text-decoration-line"
custom_cascade="${product =='servo'}"
animation_value_type="discrete"
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-line">
use std::fmt;
use style_traits::ToCss;
bitflags! {
#[derive(MallocSizeOf, ToComputedValue)]
pub flags SpecifiedValue: u8 {
const NONE = 0,
const UNDERLINE = 0x01,
const OVERLINE = 0x02,
const LINE_THROUGH = 0x04,
const BLINK = 0x08,
% if product == "gecko":
/// Only set by presentation attributes
///
/// Setting this will mean that text-decorations use the color
/// specified by `color` in quirks mode.
///
/// For example, this gives <a href=foo><font color="red">text</font></a>
/// a red text decoration
const COLOR_OVERRIDE = 0x10,
% endif
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut has_any = false;
macro_rules! write_value {
($line:ident => $css:expr) => {
if self.contains($line) {
if has_any {
dest.write_str(" ")?;
}
dest.write_str($css)?;
has_any = true;
}
}
}
write_value!(UNDERLINE => "underline");
write_value!(OVERLINE => "overline");
write_value!(LINE_THROUGH => "line-through");
write_value!(BLINK => "blink");
if!has_any {
dest.write_str("none")?;
}
Ok(())
}
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
#[allow(non_upper_case_globals)]
pub const none: T = super::SpecifiedValue {
bits: 0
};
}
#[inline] pub fn | () -> computed_value::T {
computed_value::none
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::empty()
}
/// none | [ underline || overline || line-through || blink ]
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let mut result = SpecifiedValue::empty();
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(result)
}
let mut empty = true;
loop {
let result: Result<_, ParseError> = input.try(|input| {
let location = input.current_source_location();
match input.expect_ident() {
Ok(ident) => {
(match_ignore_ascii_case! { &ident,
"underline" => if result.contains(UNDERLINE) { Err(()) }
else { empty = false; result.insert(UNDERLINE); Ok(()) },
"overline" => if result.contains(OVERLINE) { Err(()) }
else { empty = false; result.insert(OVERLINE); Ok(()) },
"line-through" => if result.contains(LINE_THROUGH) { Err(()) }
else { empty = false; result.insert(LINE_THROUGH); Ok(()) },
"blink" => if result.contains(BLINK) { Err(()) }
else { empty = false; result.insert(BLINK); Ok(()) },
_ => Err(())
}).map_err(|()| {
location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))
})
}
Err(e) => return Err(e.into())
}
});
if result.is_err() {
break;
}
}
if!empty { Ok(result) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) }
}
% if product == "servo":
fn cascade_property_custom(_declaration: &PropertyDeclaration,
context: &mut computed::Context) {
longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context);
}
% endif
#[cfg(feature = "gecko")]
impl_bitflags_conversions!(SpecifiedValue);
</%helpers:longhand>
${helpers.single_keyword("text-decoration-style",
"solid double dotted dashed wavy -moz-none",
products="gecko",
animation_value_type="discrete",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-style")}
${helpers.predefined_type(
"text-decoration-color",
"Color",
"computed_value::T::currentcolor()",
initial_specified_value="specified::Color::currentcolor()",
products="gecko",
animation_value_type="AnimatedColor",
ignored_when_colors_disabled=True,
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-color",
)}
${helpers.predefined_type(
"initial-letter",
"InitialLetter",
"computed::InitialLetter::normal()",
initial_specified_value="specified::InitialLetter::normal()",
animation_value_type="discrete",
products="gecko",
flags="APPLIES_TO_FIRST_LETTER",
spec="https://drafts.csswg.org/css-inline/#sizing-drop-initials")}
| get_initial_value | identifier_name |
text.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Text",
inherited=False,
gecko_name="TextReset",
additional_methods=[Method("has_underline", "bool"),
Method("has_overline", "bool"),
Method("has_line_through", "bool")]) %>
<%helpers:longhand name="text-overflow" animation_value_type="discrete" boxed="True"
flags="APPLIES_TO_PLACEHOLDER"
spec="https://drafts.csswg.org/css-ui/#propdef-text-overflow">
use std::fmt;
use style_traits::ToCss;
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
pub enum Side {
Clip,
Ellipsis,
String(Box<str>),
}
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
pub struct SpecifiedValue {
pub first: Side,
pub second: Option<Side>
}
pub mod computed_value {
pub use super::Side;
#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
pub struct T {
// When the specified value only has one side, that's the "second"
// side, and the sides are logical, so "second" means "end". The
// start side is Clip in that case.
//
// When the specified value has two sides, those are our "first"
// and "second" sides, and they are physical sides ("left" and
// "right").
pub first: Side,
pub second: Side,
pub sides_are_logical: bool
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.sides_are_logical {
assert!(self.first == Side::Clip);
self.second.to_css(dest)?;
} else {
self.first.to_css(dest)?;
dest.write_str(" ")?;
self.second.to_css(dest)?;
}
Ok(())
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
if let Some(ref second) = self.second {
Self::ComputedValue { first: self.first.clone(),
second: second.clone(),
sides_are_logical: false }
} else {
Self::ComputedValue { first: Side::Clip,
second: self.first.clone(),
sides_are_logical: true }
}
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
if computed.sides_are_logical {
assert!(computed.first == Side::Clip);
SpecifiedValue { first: computed.second.clone(),
second: None }
} else {
SpecifiedValue { first: computed.first.clone(),
second: Some(computed.second.clone()) }
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T {
first: Side::Clip,
second: Side::Clip,
sides_are_logical: true,
}
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let first = Side::parse(context, input)?;
let second = input.try(|input| Side::parse(context, input)).ok();
Ok(SpecifiedValue {
first: first,
second: second,
})
}
impl Parse for Side {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Side, ParseError<'i>> {
let location = input.current_source_location();
match *input.next()? {
Token::Ident(ref ident) => {
match_ignore_ascii_case! { ident,
"clip" => Ok(Side::Clip),
"ellipsis" => Ok(Side::Ellipsis),
_ => Err(location.new_custom_error(
SelectorParseErrorKind::UnexpectedIdent(ident.clone())
))
}
}
Token::QuotedString(ref v) => {
Ok(Side::String(v.as_ref().to_owned().into_boxed_str()))
}
ref t => Err(location.new_unexpected_token_error(t.clone())),
}
}
}
</%helpers:longhand>
${helpers.single_keyword("unicode-bidi",
"normal embed isolate bidi-override isolate-override plaintext",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-writing-modes/#propdef-unicode-bidi")}
<%helpers:longhand name="text-decoration-line"
custom_cascade="${product =='servo'}"
animation_value_type="discrete"
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-line">
use std::fmt;
use style_traits::ToCss;
bitflags! {
#[derive(MallocSizeOf, ToComputedValue)]
pub flags SpecifiedValue: u8 {
const NONE = 0,
const UNDERLINE = 0x01,
const OVERLINE = 0x02,
const LINE_THROUGH = 0x04,
const BLINK = 0x08,
% if product == "gecko":
/// Only set by presentation attributes
///
/// Setting this will mean that text-decorations use the color
/// specified by `color` in quirks mode.
///
/// For example, this gives <a href=foo><font color="red">text</font></a>
/// a red text decoration
const COLOR_OVERRIDE = 0x10,
% endif
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut has_any = false;
macro_rules! write_value {
($line:ident => $css:expr) => {
if self.contains($line) {
if has_any {
dest.write_str(" ")?;
}
dest.write_str($css)?;
has_any = true;
}
}
}
write_value!(UNDERLINE => "underline");
write_value!(OVERLINE => "overline");
write_value!(LINE_THROUGH => "line-through");
write_value!(BLINK => "blink");
if!has_any {
dest.write_str("none")?;
}
Ok(())
}
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
#[allow(non_upper_case_globals)]
pub const none: T = super::SpecifiedValue {
bits: 0
};
}
#[inline] pub fn get_initial_value() -> computed_value::T {
computed_value::none
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::empty()
}
/// none | [ underline || overline || line-through || blink ]
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> | else { empty = false; result.insert(BLINK); Ok(()) },
_ => Err(())
}).map_err(|()| {
location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))
})
}
Err(e) => return Err(e.into())
}
});
if result.is_err() {
break;
}
}
if!empty { Ok(result) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) }
}
% if product == "servo":
fn cascade_property_custom(_declaration: &PropertyDeclaration,
context: &mut computed::Context) {
longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context);
}
% endif
#[cfg(feature = "gecko")]
impl_bitflags_conversions!(SpecifiedValue);
</%helpers:longhand>
${helpers.single_keyword("text-decoration-style",
"solid double dotted dashed wavy -moz-none",
products="gecko",
animation_value_type="discrete",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-style")}
${helpers.predefined_type(
"text-decoration-color",
"Color",
"computed_value::T::currentcolor()",
initial_specified_value="specified::Color::currentcolor()",
products="gecko",
animation_value_type="AnimatedColor",
ignored_when_colors_disabled=True,
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-color",
)}
${helpers.predefined_type(
"initial-letter",
"InitialLetter",
"computed::InitialLetter::normal()",
initial_specified_value="specified::InitialLetter::normal()",
animation_value_type="discrete",
products="gecko",
flags="APPLIES_TO_FIRST_LETTER",
spec="https://drafts.csswg.org/css-inline/#sizing-drop-initials")}
| {
let mut result = SpecifiedValue::empty();
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(result)
}
let mut empty = true;
loop {
let result: Result<_, ParseError> = input.try(|input| {
let location = input.current_source_location();
match input.expect_ident() {
Ok(ident) => {
(match_ignore_ascii_case! { &ident,
"underline" => if result.contains(UNDERLINE) { Err(()) }
else { empty = false; result.insert(UNDERLINE); Ok(()) },
"overline" => if result.contains(OVERLINE) { Err(()) }
else { empty = false; result.insert(OVERLINE); Ok(()) },
"line-through" => if result.contains(LINE_THROUGH) { Err(()) }
else { empty = false; result.insert(LINE_THROUGH); Ok(()) },
"blink" => if result.contains(BLINK) { Err(()) } | identifier_body |
text.mako.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Text",
inherited=False,
gecko_name="TextReset",
additional_methods=[Method("has_underline", "bool"),
Method("has_overline", "bool"),
Method("has_line_through", "bool")]) %>
<%helpers:longhand name="text-overflow" animation_value_type="discrete" boxed="True"
flags="APPLIES_TO_PLACEHOLDER"
spec="https://drafts.csswg.org/css-ui/#propdef-text-overflow">
use std::fmt;
use style_traits::ToCss;
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
pub enum Side {
Clip,
Ellipsis,
String(Box<str>),
}
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
pub struct SpecifiedValue {
pub first: Side,
pub second: Option<Side>
}
pub mod computed_value {
pub use super::Side;
#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
pub struct T {
// When the specified value only has one side, that's the "second"
// side, and the sides are logical, so "second" means "end". The
// start side is Clip in that case.
//
// When the specified value has two sides, those are our "first"
// and "second" sides, and they are physical sides ("left" and
// "right").
pub first: Side,
pub second: Side,
pub sides_are_logical: bool
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.sides_are_logical {
assert!(self.first == Side::Clip);
self.second.to_css(dest)?;
} else {
self.first.to_css(dest)?;
dest.write_str(" ")?;
self.second.to_css(dest)?;
}
Ok(())
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
if let Some(ref second) = self.second {
Self::ComputedValue { first: self.first.clone(),
second: second.clone(),
sides_are_logical: false }
} else {
Self::ComputedValue { first: Side::Clip,
second: self.first.clone(),
sides_are_logical: true }
}
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
if computed.sides_are_logical {
assert!(computed.first == Side::Clip);
SpecifiedValue { first: computed.second.clone(),
second: None }
} else {
SpecifiedValue { first: computed.first.clone(),
second: Some(computed.second.clone()) }
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T {
first: Side::Clip,
second: Side::Clip,
sides_are_logical: true,
}
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let first = Side::parse(context, input)?;
let second = input.try(|input| Side::parse(context, input)).ok();
Ok(SpecifiedValue {
first: first,
second: second,
})
}
impl Parse for Side {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Side, ParseError<'i>> {
let location = input.current_source_location();
match *input.next()? {
Token::Ident(ref ident) => {
match_ignore_ascii_case! { ident,
"clip" => Ok(Side::Clip),
"ellipsis" => Ok(Side::Ellipsis),
_ => Err(location.new_custom_error(
SelectorParseErrorKind::UnexpectedIdent(ident.clone())
))
}
}
Token::QuotedString(ref v) => {
Ok(Side::String(v.as_ref().to_owned().into_boxed_str()))
}
ref t => Err(location.new_unexpected_token_error(t.clone())),
}
}
}
</%helpers:longhand>
${helpers.single_keyword("unicode-bidi",
"normal embed isolate bidi-override isolate-override plaintext",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-writing-modes/#propdef-unicode-bidi")}
<%helpers:longhand name="text-decoration-line"
custom_cascade="${product =='servo'}"
animation_value_type="discrete"
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-line">
use std::fmt;
use style_traits::ToCss;
bitflags! {
#[derive(MallocSizeOf, ToComputedValue)]
pub flags SpecifiedValue: u8 {
const NONE = 0,
const UNDERLINE = 0x01,
const OVERLINE = 0x02,
const LINE_THROUGH = 0x04,
const BLINK = 0x08,
% if product == "gecko":
/// Only set by presentation attributes
///
/// Setting this will mean that text-decorations use the color
/// specified by `color` in quirks mode.
///
/// For example, this gives <a href=foo><font color="red">text</font></a>
/// a red text decoration
const COLOR_OVERRIDE = 0x10,
% endif
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut has_any = false;
macro_rules! write_value {
($line:ident => $css:expr) => {
if self.contains($line) {
if has_any {
dest.write_str(" ")?;
}
dest.write_str($css)?;
has_any = true;
}
}
}
write_value!(UNDERLINE => "underline");
write_value!(OVERLINE => "overline");
write_value!(LINE_THROUGH => "line-through");
write_value!(BLINK => "blink");
if!has_any {
dest.write_str("none")?;
}
Ok(())
}
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
#[allow(non_upper_case_globals)]
pub const none: T = super::SpecifiedValue {
bits: 0
};
}
#[inline] pub fn get_initial_value() -> computed_value::T {
computed_value::none
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::empty()
}
/// none | [ underline || overline || line-through || blink ]
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let mut result = SpecifiedValue::empty();
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(result) | let location = input.current_source_location();
match input.expect_ident() {
Ok(ident) => {
(match_ignore_ascii_case! { &ident,
"underline" => if result.contains(UNDERLINE) { Err(()) }
else { empty = false; result.insert(UNDERLINE); Ok(()) },
"overline" => if result.contains(OVERLINE) { Err(()) }
else { empty = false; result.insert(OVERLINE); Ok(()) },
"line-through" => if result.contains(LINE_THROUGH) { Err(()) }
else { empty = false; result.insert(LINE_THROUGH); Ok(()) },
"blink" => if result.contains(BLINK) { Err(()) }
else { empty = false; result.insert(BLINK); Ok(()) },
_ => Err(())
}).map_err(|()| {
location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))
})
}
Err(e) => return Err(e.into())
}
});
if result.is_err() {
break;
}
}
if!empty { Ok(result) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) }
}
% if product == "servo":
fn cascade_property_custom(_declaration: &PropertyDeclaration,
context: &mut computed::Context) {
longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context);
}
% endif
#[cfg(feature = "gecko")]
impl_bitflags_conversions!(SpecifiedValue);
</%helpers:longhand>
${helpers.single_keyword("text-decoration-style",
"solid double dotted dashed wavy -moz-none",
products="gecko",
animation_value_type="discrete",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-style")}
${helpers.predefined_type(
"text-decoration-color",
"Color",
"computed_value::T::currentcolor()",
initial_specified_value="specified::Color::currentcolor()",
products="gecko",
animation_value_type="AnimatedColor",
ignored_when_colors_disabled=True,
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-color",
)}
${helpers.predefined_type(
"initial-letter",
"InitialLetter",
"computed::InitialLetter::normal()",
initial_specified_value="specified::InitialLetter::normal()",
animation_value_type="discrete",
products="gecko",
flags="APPLIES_TO_FIRST_LETTER",
spec="https://drafts.csswg.org/css-inline/#sizing-drop-initials")} | }
let mut empty = true;
loop {
let result: Result<_, ParseError> = input.try(|input| { | random_line_split |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::str::DOMString;
use dom::cssstylesheet::CSSStyleSheet;
use dom::document::Document;
use dom::element::Element;
use dom::htmlelement::HTMLElement;
use dom::node::{ChildrenMutation, Node, document_from_node, window_from_node};
use dom::stylesheet::StyleSheet as DOMStyleSheet;
use dom::virtualmethods::VirtualMethods;
use html5ever_atoms::LocalName;
use script_layout_interface::message::Msg;
use std::sync::Arc;
use style::media_queries::parse_media_query_list;
use style::parser::ParserContextExtraData;
use style::stylesheets::{Stylesheet, Origin};
#[dom_struct]
pub struct HTMLStyleElement {
htmlelement: HTMLElement,
#[ignore_heap_size_of = "Arc"]
stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>,
cssom_stylesheet: MutNullableHeap<JS<CSSStyleSheet>>,
}
impl HTMLStyleElement {
fn new_inherited(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
stylesheet: DOMRefCell::new(None),
cssom_stylesheet: MutNullableHeap::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLStyleElement> {
Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document),
document,
HTMLStyleElementBinding::Wrap)
}
pub fn parse_own_css(&self) {
let node = self.upcast::<Node>();
let element = self.upcast::<Element>();
assert!(node.is_in_doc());
let win = window_from_node(node);
let url = win.get_url();
let mq_attribute = element.get_attribute(&ns!(), &local_name!("media"));
let mq_str = match mq_attribute {
Some(a) => String::from(&**a.value()),
None => String::new(),
};
let data = node.GetTextContent().expect("Element.textContent must be a string");
let mq = parse_media_query_list(&mut CssParser::new(&mq_str));
let sheet = Stylesheet::from_str(&data, url, Origin::Author, mq, win.css_error_reporter(),
ParserContextExtraData::default());
let sheet = Arc::new(sheet);
win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap();
*self.stylesheet.borrow_mut() = Some(sheet);
let doc = document_from_node(self);
doc.invalidate_stylesheets();
}
pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
self.stylesheet.borrow().clone()
}
pub fn get_cssom_stylesheet(&self) -> Option<Root<CSSStyleSheet>> {
self.get_stylesheet().map(|sheet| {
self.cssom_stylesheet.or_init(|| {
CSSStyleSheet::new(&window_from_node(self),
"text/css".into(),
None, // todo handle location
None, // todo handle title
sheet)
})
})
}
}
impl VirtualMethods for HTMLStyleElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn children_changed(&self, mutation: &ChildrenMutation) {
if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
} |
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
self.parse_own_css();
}
}
}
impl HTMLStyleElementMethods for HTMLStyleElement {
// https://drafts.csswg.org/cssom/#dom-linkstyle-sheet
fn GetSheet(&self) -> Option<Root<DOMStyleSheet>> {
self.get_cssom_stylesheet().map(Root::upcast)
}
} | if self.upcast::<Node>().is_in_doc() {
self.parse_own_css();
}
} | random_line_split |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::str::DOMString;
use dom::cssstylesheet::CSSStyleSheet;
use dom::document::Document;
use dom::element::Element;
use dom::htmlelement::HTMLElement;
use dom::node::{ChildrenMutation, Node, document_from_node, window_from_node};
use dom::stylesheet::StyleSheet as DOMStyleSheet;
use dom::virtualmethods::VirtualMethods;
use html5ever_atoms::LocalName;
use script_layout_interface::message::Msg;
use std::sync::Arc;
use style::media_queries::parse_media_query_list;
use style::parser::ParserContextExtraData;
use style::stylesheets::{Stylesheet, Origin};
#[dom_struct]
pub struct HTMLStyleElement {
htmlelement: HTMLElement,
#[ignore_heap_size_of = "Arc"]
stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>,
cssom_stylesheet: MutNullableHeap<JS<CSSStyleSheet>>,
}
impl HTMLStyleElement {
fn new_inherited(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
stylesheet: DOMRefCell::new(None),
cssom_stylesheet: MutNullableHeap::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn | (local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLStyleElement> {
Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document),
document,
HTMLStyleElementBinding::Wrap)
}
pub fn parse_own_css(&self) {
let node = self.upcast::<Node>();
let element = self.upcast::<Element>();
assert!(node.is_in_doc());
let win = window_from_node(node);
let url = win.get_url();
let mq_attribute = element.get_attribute(&ns!(), &local_name!("media"));
let mq_str = match mq_attribute {
Some(a) => String::from(&**a.value()),
None => String::new(),
};
let data = node.GetTextContent().expect("Element.textContent must be a string");
let mq = parse_media_query_list(&mut CssParser::new(&mq_str));
let sheet = Stylesheet::from_str(&data, url, Origin::Author, mq, win.css_error_reporter(),
ParserContextExtraData::default());
let sheet = Arc::new(sheet);
win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap();
*self.stylesheet.borrow_mut() = Some(sheet);
let doc = document_from_node(self);
doc.invalidate_stylesheets();
}
pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
self.stylesheet.borrow().clone()
}
pub fn get_cssom_stylesheet(&self) -> Option<Root<CSSStyleSheet>> {
self.get_stylesheet().map(|sheet| {
self.cssom_stylesheet.or_init(|| {
CSSStyleSheet::new(&window_from_node(self),
"text/css".into(),
None, // todo handle location
None, // todo handle title
sheet)
})
})
}
}
impl VirtualMethods for HTMLStyleElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn children_changed(&self, mutation: &ChildrenMutation) {
if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
}
if self.upcast::<Node>().is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
self.parse_own_css();
}
}
}
impl HTMLStyleElementMethods for HTMLStyleElement {
// https://drafts.csswg.org/cssom/#dom-linkstyle-sheet
fn GetSheet(&self) -> Option<Root<DOMStyleSheet>> {
self.get_cssom_stylesheet().map(Root::upcast)
}
}
| new | identifier_name |
htmlstyleelement.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 cssparser::Parser as CssParser;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding;
use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{JS, MutNullableHeap, Root};
use dom::bindings::str::DOMString;
use dom::cssstylesheet::CSSStyleSheet;
use dom::document::Document;
use dom::element::Element;
use dom::htmlelement::HTMLElement;
use dom::node::{ChildrenMutation, Node, document_from_node, window_from_node};
use dom::stylesheet::StyleSheet as DOMStyleSheet;
use dom::virtualmethods::VirtualMethods;
use html5ever_atoms::LocalName;
use script_layout_interface::message::Msg;
use std::sync::Arc;
use style::media_queries::parse_media_query_list;
use style::parser::ParserContextExtraData;
use style::stylesheets::{Stylesheet, Origin};
#[dom_struct]
pub struct HTMLStyleElement {
htmlelement: HTMLElement,
#[ignore_heap_size_of = "Arc"]
stylesheet: DOMRefCell<Option<Arc<Stylesheet>>>,
cssom_stylesheet: MutNullableHeap<JS<CSSStyleSheet>>,
}
impl HTMLStyleElement {
fn new_inherited(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLStyleElement {
HTMLStyleElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
stylesheet: DOMRefCell::new(None),
cssom_stylesheet: MutNullableHeap::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLStyleElement> |
pub fn parse_own_css(&self) {
let node = self.upcast::<Node>();
let element = self.upcast::<Element>();
assert!(node.is_in_doc());
let win = window_from_node(node);
let url = win.get_url();
let mq_attribute = element.get_attribute(&ns!(), &local_name!("media"));
let mq_str = match mq_attribute {
Some(a) => String::from(&**a.value()),
None => String::new(),
};
let data = node.GetTextContent().expect("Element.textContent must be a string");
let mq = parse_media_query_list(&mut CssParser::new(&mq_str));
let sheet = Stylesheet::from_str(&data, url, Origin::Author, mq, win.css_error_reporter(),
ParserContextExtraData::default());
let sheet = Arc::new(sheet);
win.layout_chan().send(Msg::AddStylesheet(sheet.clone())).unwrap();
*self.stylesheet.borrow_mut() = Some(sheet);
let doc = document_from_node(self);
doc.invalidate_stylesheets();
}
pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> {
self.stylesheet.borrow().clone()
}
pub fn get_cssom_stylesheet(&self) -> Option<Root<CSSStyleSheet>> {
self.get_stylesheet().map(|sheet| {
self.cssom_stylesheet.or_init(|| {
CSSStyleSheet::new(&window_from_node(self),
"text/css".into(),
None, // todo handle location
None, // todo handle title
sheet)
})
})
}
}
impl VirtualMethods for HTMLStyleElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn children_changed(&self, mutation: &ChildrenMutation) {
if let Some(ref s) = self.super_type() {
s.children_changed(mutation);
}
if self.upcast::<Node>().is_in_doc() {
self.parse_own_css();
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
if tree_in_doc {
self.parse_own_css();
}
}
}
impl HTMLStyleElementMethods for HTMLStyleElement {
// https://drafts.csswg.org/cssom/#dom-linkstyle-sheet
fn GetSheet(&self) -> Option<Root<DOMStyleSheet>> {
self.get_cssom_stylesheet().map(Root::upcast)
}
}
| {
Node::reflect_node(box HTMLStyleElement::new_inherited(local_name, prefix, document),
document,
HTMLStyleElementBinding::Wrap)
} | identifier_body |
repl.rs | //! Helpers for replacing values in a message template.
//!
//! All properties in the template must be of the form: `"{label}"`.
//! Use either `MessageTempalte::new()` or `MessageTemplate::from_format()` to make sure
//! it's in the right format.
use std::collections::BTreeMap;
use std::str;
use events::Value;
use std::fmt::Write;
pub struct MessageTemplateRepl<'a> {
text: &'a str,
param_slices: Vec<ParamSlice>
}
impl <'a> MessageTemplateRepl<'a> {
pub fn new(text: &'a str) -> MessageTemplateRepl {
let slices = parse_slices(
text.as_bytes(),
State::Lit(0),
Vec::new()
);
MessageTemplateRepl {
text: text,
param_slices: slices
}
}
//TODO: DRY
pub fn replace(&self, values: &BTreeMap<&str, Value>) -> String {
let mut result = String::with_capacity(self.text.len());
let mut slice_iter = self.param_slices.iter();
let mut last_index = 0;
//The first slice
if let Some(slice) = slice_iter.next() {
let lit = &self.text[last_index..slice.start];
write!(result, "{}", lit).is_ok();
if let Some(ref val) = values.get(slice.label.as_str()) {
write!(result, "{}", val).is_ok();
}
last_index = slice.end;
}
//The middle slices
for slice in slice_iter {
let lit = &self.text[last_index..slice.start];
write!(result, "{}", lit).is_ok();
if let Some(ref val) = values.get(slice.label.as_str()) {
write!(result, "{}", val).is_ok();
}
last_index = slice.end;
}
//The last slice
if last_index < self.text.len() {
let lit = &self.text[last_index..];
write!(result, "{}", lit).is_ok();
}
result
}
pub fn text(&self) -> &str {
self.text
}
}
struct ParamSlice {
pub start: usize,
pub end: usize,
pub label: String
}
enum State {
Lit(usize),
Label(usize)
}
//TODO: Return Result<Vec<ParamSlice>, ParseResult> so malformed templates are rejected
fn parse_slices<'a>(i: &'a [u8], state: State, mut slices: Vec<ParamSlice>) -> Vec<ParamSlice> {
if i.len() == 0 {
slices
}
else {
match state {
State::Lit(c_start) => {
let (ci, rest) = parse_lit(i);
let c_end = c_start + ci;
parse_slices(rest, State::Label(c_end), slices)
},
State::Label(c_start) => {
let (ci, rest, label) = parse_label(i);
let c_end = c_start + ci;
if let Some(label) = label {
slices.push(ParamSlice {
start: c_start,
end: c_end,
label: label.to_string()
});
}
parse_slices(rest, State::Lit(c_end), slices)
}
}
}
}
//Parse the'myproperty:'in'myproperty: {somevalue} other'
fn parse_lit<'a>(i: &'a [u8]) -> (usize, &'a [u8]) {
shift_while(i, |c| c!= b'{')
}
//Parse the'somevalue' in '{somevalue} other'
fn parse_label<'a>(i: &'a [u8]) -> (usize, &'a [u8], Option<&'a str>) {
//Shift over the '{'
let (c_open, k_open) = shift(i, 1);
//Parse the label
let (c, k_label, s) = take_while(k_open, |c| c!= b'}');
//Shift over the '}'
let (c_close, k_close) = shift(k_label, 1);
let name = match s.len() {
0 => None,
_ => Some(s)
};
(c_open + c + c_close, k_close, name)
}
fn take_while<F>(i: &[u8], f: F) -> (usize, &[u8], &str) where F: Fn(u8) -> bool {
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
(ctr, &i[ctr..], str::from_utf8(&i[0..ctr]).unwrap())
}
fn shift(i: &[u8], c: usize) -> (usize, &[u8]) {
match c {
c if c >= i.len() => (i.len(), &[]),
_ => (c, &i[c..])
}
}
fn shift_while<F>(i: &[u8], f: F) -> (usize, &[u8]) where F: Fn(u8) -> bool {
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else |
}
(ctr, &i[ctr..])
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use ::templates::repl::MessageTemplateRepl;
#[test]
fn values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {Bert} E");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("Bert", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D value2 E", &replaced);
}
#[test]
fn missing_values_are_replaced_as_blank() {
let template_repl = MessageTemplateRepl::new("C {A} D {Bert} E");
let mut map = BTreeMap::new();
map.insert("Bert", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C D value2 E", &replaced);
}
#[test]
fn duplicate_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A}{B} D {A} {B} E");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1value2 D value1 value2 E", &replaced);
}
#[test]
fn leading_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("{A} DE {B} F");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("value1 DE value2 F", &replaced);
}
#[test]
fn trailing_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {B}");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D value2", &replaced);
}
//TODO: This should just return Err
#[test]
fn malformed_labels_are_not_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {{B}} {A");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D } value1", &replaced);
}
}
| {
break;
} | conditional_block |
repl.rs | //! Helpers for replacing values in a message template.
//!
//! All properties in the template must be of the form: `"{label}"`.
//! Use either `MessageTempalte::new()` or `MessageTemplate::from_format()` to make sure
//! it's in the right format. | use events::Value;
use std::fmt::Write;
pub struct MessageTemplateRepl<'a> {
text: &'a str,
param_slices: Vec<ParamSlice>
}
impl <'a> MessageTemplateRepl<'a> {
pub fn new(text: &'a str) -> MessageTemplateRepl {
let slices = parse_slices(
text.as_bytes(),
State::Lit(0),
Vec::new()
);
MessageTemplateRepl {
text: text,
param_slices: slices
}
}
//TODO: DRY
pub fn replace(&self, values: &BTreeMap<&str, Value>) -> String {
let mut result = String::with_capacity(self.text.len());
let mut slice_iter = self.param_slices.iter();
let mut last_index = 0;
//The first slice
if let Some(slice) = slice_iter.next() {
let lit = &self.text[last_index..slice.start];
write!(result, "{}", lit).is_ok();
if let Some(ref val) = values.get(slice.label.as_str()) {
write!(result, "{}", val).is_ok();
}
last_index = slice.end;
}
//The middle slices
for slice in slice_iter {
let lit = &self.text[last_index..slice.start];
write!(result, "{}", lit).is_ok();
if let Some(ref val) = values.get(slice.label.as_str()) {
write!(result, "{}", val).is_ok();
}
last_index = slice.end;
}
//The last slice
if last_index < self.text.len() {
let lit = &self.text[last_index..];
write!(result, "{}", lit).is_ok();
}
result
}
pub fn text(&self) -> &str {
self.text
}
}
struct ParamSlice {
pub start: usize,
pub end: usize,
pub label: String
}
enum State {
Lit(usize),
Label(usize)
}
//TODO: Return Result<Vec<ParamSlice>, ParseResult> so malformed templates are rejected
fn parse_slices<'a>(i: &'a [u8], state: State, mut slices: Vec<ParamSlice>) -> Vec<ParamSlice> {
if i.len() == 0 {
slices
}
else {
match state {
State::Lit(c_start) => {
let (ci, rest) = parse_lit(i);
let c_end = c_start + ci;
parse_slices(rest, State::Label(c_end), slices)
},
State::Label(c_start) => {
let (ci, rest, label) = parse_label(i);
let c_end = c_start + ci;
if let Some(label) = label {
slices.push(ParamSlice {
start: c_start,
end: c_end,
label: label.to_string()
});
}
parse_slices(rest, State::Lit(c_end), slices)
}
}
}
}
//Parse the'myproperty:'in'myproperty: {somevalue} other'
fn parse_lit<'a>(i: &'a [u8]) -> (usize, &'a [u8]) {
shift_while(i, |c| c!= b'{')
}
//Parse the'somevalue' in '{somevalue} other'
fn parse_label<'a>(i: &'a [u8]) -> (usize, &'a [u8], Option<&'a str>) {
//Shift over the '{'
let (c_open, k_open) = shift(i, 1);
//Parse the label
let (c, k_label, s) = take_while(k_open, |c| c!= b'}');
//Shift over the '}'
let (c_close, k_close) = shift(k_label, 1);
let name = match s.len() {
0 => None,
_ => Some(s)
};
(c_open + c + c_close, k_close, name)
}
fn take_while<F>(i: &[u8], f: F) -> (usize, &[u8], &str) where F: Fn(u8) -> bool {
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
(ctr, &i[ctr..], str::from_utf8(&i[0..ctr]).unwrap())
}
fn shift(i: &[u8], c: usize) -> (usize, &[u8]) {
match c {
c if c >= i.len() => (i.len(), &[]),
_ => (c, &i[c..])
}
}
fn shift_while<F>(i: &[u8], f: F) -> (usize, &[u8]) where F: Fn(u8) -> bool {
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
(ctr, &i[ctr..])
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use ::templates::repl::MessageTemplateRepl;
#[test]
fn values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {Bert} E");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("Bert", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D value2 E", &replaced);
}
#[test]
fn missing_values_are_replaced_as_blank() {
let template_repl = MessageTemplateRepl::new("C {A} D {Bert} E");
let mut map = BTreeMap::new();
map.insert("Bert", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C D value2 E", &replaced);
}
#[test]
fn duplicate_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A}{B} D {A} {B} E");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1value2 D value1 value2 E", &replaced);
}
#[test]
fn leading_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("{A} DE {B} F");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("value1 DE value2 F", &replaced);
}
#[test]
fn trailing_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {B}");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D value2", &replaced);
}
//TODO: This should just return Err
#[test]
fn malformed_labels_are_not_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {{B}} {A");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D } value1", &replaced);
}
} |
use std::collections::BTreeMap;
use std::str; | random_line_split |
repl.rs | //! Helpers for replacing values in a message template.
//!
//! All properties in the template must be of the form: `"{label}"`.
//! Use either `MessageTempalte::new()` or `MessageTemplate::from_format()` to make sure
//! it's in the right format.
use std::collections::BTreeMap;
use std::str;
use events::Value;
use std::fmt::Write;
pub struct MessageTemplateRepl<'a> {
text: &'a str,
param_slices: Vec<ParamSlice>
}
impl <'a> MessageTemplateRepl<'a> {
pub fn new(text: &'a str) -> MessageTemplateRepl {
let slices = parse_slices(
text.as_bytes(),
State::Lit(0),
Vec::new()
);
MessageTemplateRepl {
text: text,
param_slices: slices
}
}
//TODO: DRY
pub fn replace(&self, values: &BTreeMap<&str, Value>) -> String {
let mut result = String::with_capacity(self.text.len());
let mut slice_iter = self.param_slices.iter();
let mut last_index = 0;
//The first slice
if let Some(slice) = slice_iter.next() {
let lit = &self.text[last_index..slice.start];
write!(result, "{}", lit).is_ok();
if let Some(ref val) = values.get(slice.label.as_str()) {
write!(result, "{}", val).is_ok();
}
last_index = slice.end;
}
//The middle slices
for slice in slice_iter {
let lit = &self.text[last_index..slice.start];
write!(result, "{}", lit).is_ok();
if let Some(ref val) = values.get(slice.label.as_str()) {
write!(result, "{}", val).is_ok();
}
last_index = slice.end;
}
//The last slice
if last_index < self.text.len() {
let lit = &self.text[last_index..];
write!(result, "{}", lit).is_ok();
}
result
}
pub fn text(&self) -> &str {
self.text
}
}
struct ParamSlice {
pub start: usize,
pub end: usize,
pub label: String
}
enum State {
Lit(usize),
Label(usize)
}
//TODO: Return Result<Vec<ParamSlice>, ParseResult> so malformed templates are rejected
fn parse_slices<'a>(i: &'a [u8], state: State, mut slices: Vec<ParamSlice>) -> Vec<ParamSlice> {
if i.len() == 0 {
slices
}
else {
match state {
State::Lit(c_start) => {
let (ci, rest) = parse_lit(i);
let c_end = c_start + ci;
parse_slices(rest, State::Label(c_end), slices)
},
State::Label(c_start) => {
let (ci, rest, label) = parse_label(i);
let c_end = c_start + ci;
if let Some(label) = label {
slices.push(ParamSlice {
start: c_start,
end: c_end,
label: label.to_string()
});
}
parse_slices(rest, State::Lit(c_end), slices)
}
}
}
}
//Parse the'myproperty:'in'myproperty: {somevalue} other'
fn parse_lit<'a>(i: &'a [u8]) -> (usize, &'a [u8]) {
shift_while(i, |c| c!= b'{')
}
//Parse the'somevalue' in '{somevalue} other'
fn parse_label<'a>(i: &'a [u8]) -> (usize, &'a [u8], Option<&'a str>) {
//Shift over the '{'
let (c_open, k_open) = shift(i, 1);
//Parse the label
let (c, k_label, s) = take_while(k_open, |c| c!= b'}');
//Shift over the '}'
let (c_close, k_close) = shift(k_label, 1);
let name = match s.len() {
0 => None,
_ => Some(s)
};
(c_open + c + c_close, k_close, name)
}
fn take_while<F>(i: &[u8], f: F) -> (usize, &[u8], &str) where F: Fn(u8) -> bool {
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
(ctr, &i[ctr..], str::from_utf8(&i[0..ctr]).unwrap())
}
fn shift(i: &[u8], c: usize) -> (usize, &[u8]) {
match c {
c if c >= i.len() => (i.len(), &[]),
_ => (c, &i[c..])
}
}
fn | <F>(i: &[u8], f: F) -> (usize, &[u8]) where F: Fn(u8) -> bool {
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
(ctr, &i[ctr..])
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use ::templates::repl::MessageTemplateRepl;
#[test]
fn values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {Bert} E");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("Bert", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D value2 E", &replaced);
}
#[test]
fn missing_values_are_replaced_as_blank() {
let template_repl = MessageTemplateRepl::new("C {A} D {Bert} E");
let mut map = BTreeMap::new();
map.insert("Bert", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C D value2 E", &replaced);
}
#[test]
fn duplicate_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A}{B} D {A} {B} E");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1value2 D value1 value2 E", &replaced);
}
#[test]
fn leading_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("{A} DE {B} F");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("value1 DE value2 F", &replaced);
}
#[test]
fn trailing_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {B}");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D value2", &replaced);
}
//TODO: This should just return Err
#[test]
fn malformed_labels_are_not_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {{B}} {A");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D } value1", &replaced);
}
}
| shift_while | identifier_name |
repl.rs | //! Helpers for replacing values in a message template.
//!
//! All properties in the template must be of the form: `"{label}"`.
//! Use either `MessageTempalte::new()` or `MessageTemplate::from_format()` to make sure
//! it's in the right format.
use std::collections::BTreeMap;
use std::str;
use events::Value;
use std::fmt::Write;
pub struct MessageTemplateRepl<'a> {
text: &'a str,
param_slices: Vec<ParamSlice>
}
impl <'a> MessageTemplateRepl<'a> {
pub fn new(text: &'a str) -> MessageTemplateRepl {
let slices = parse_slices(
text.as_bytes(),
State::Lit(0),
Vec::new()
);
MessageTemplateRepl {
text: text,
param_slices: slices
}
}
//TODO: DRY
pub fn replace(&self, values: &BTreeMap<&str, Value>) -> String {
let mut result = String::with_capacity(self.text.len());
let mut slice_iter = self.param_slices.iter();
let mut last_index = 0;
//The first slice
if let Some(slice) = slice_iter.next() {
let lit = &self.text[last_index..slice.start];
write!(result, "{}", lit).is_ok();
if let Some(ref val) = values.get(slice.label.as_str()) {
write!(result, "{}", val).is_ok();
}
last_index = slice.end;
}
//The middle slices
for slice in slice_iter {
let lit = &self.text[last_index..slice.start];
write!(result, "{}", lit).is_ok();
if let Some(ref val) = values.get(slice.label.as_str()) {
write!(result, "{}", val).is_ok();
}
last_index = slice.end;
}
//The last slice
if last_index < self.text.len() {
let lit = &self.text[last_index..];
write!(result, "{}", lit).is_ok();
}
result
}
pub fn text(&self) -> &str {
self.text
}
}
struct ParamSlice {
pub start: usize,
pub end: usize,
pub label: String
}
enum State {
Lit(usize),
Label(usize)
}
//TODO: Return Result<Vec<ParamSlice>, ParseResult> so malformed templates are rejected
fn parse_slices<'a>(i: &'a [u8], state: State, mut slices: Vec<ParamSlice>) -> Vec<ParamSlice> {
if i.len() == 0 {
slices
}
else {
match state {
State::Lit(c_start) => {
let (ci, rest) = parse_lit(i);
let c_end = c_start + ci;
parse_slices(rest, State::Label(c_end), slices)
},
State::Label(c_start) => {
let (ci, rest, label) = parse_label(i);
let c_end = c_start + ci;
if let Some(label) = label {
slices.push(ParamSlice {
start: c_start,
end: c_end,
label: label.to_string()
});
}
parse_slices(rest, State::Lit(c_end), slices)
}
}
}
}
//Parse the'myproperty:'in'myproperty: {somevalue} other'
fn parse_lit<'a>(i: &'a [u8]) -> (usize, &'a [u8]) {
shift_while(i, |c| c!= b'{')
}
//Parse the'somevalue' in '{somevalue} other'
fn parse_label<'a>(i: &'a [u8]) -> (usize, &'a [u8], Option<&'a str>) {
//Shift over the '{'
let (c_open, k_open) = shift(i, 1);
//Parse the label
let (c, k_label, s) = take_while(k_open, |c| c!= b'}');
//Shift over the '}'
let (c_close, k_close) = shift(k_label, 1);
let name = match s.len() {
0 => None,
_ => Some(s)
};
(c_open + c + c_close, k_close, name)
}
fn take_while<F>(i: &[u8], f: F) -> (usize, &[u8], &str) where F: Fn(u8) -> bool |
fn shift(i: &[u8], c: usize) -> (usize, &[u8]) {
match c {
c if c >= i.len() => (i.len(), &[]),
_ => (c, &i[c..])
}
}
fn shift_while<F>(i: &[u8], f: F) -> (usize, &[u8]) where F: Fn(u8) -> bool {
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
(ctr, &i[ctr..])
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use ::templates::repl::MessageTemplateRepl;
#[test]
fn values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {Bert} E");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("Bert", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D value2 E", &replaced);
}
#[test]
fn missing_values_are_replaced_as_blank() {
let template_repl = MessageTemplateRepl::new("C {A} D {Bert} E");
let mut map = BTreeMap::new();
map.insert("Bert", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C D value2 E", &replaced);
}
#[test]
fn duplicate_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A}{B} D {A} {B} E");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1value2 D value1 value2 E", &replaced);
}
#[test]
fn leading_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("{A} DE {B} F");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("value1 DE value2 F", &replaced);
}
#[test]
fn trailing_values_are_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {B}");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D value2", &replaced);
}
//TODO: This should just return Err
#[test]
fn malformed_labels_are_not_replaced() {
let template_repl = MessageTemplateRepl::new("C {A} D {{B}} {A");
let mut map = BTreeMap::new();
map.insert("A", "value1".into());
map.insert("B", "value2".into());
let replaced = template_repl.replace(&map);
assert_eq!("C value1 D } value1", &replaced);
}
}
| {
let mut ctr = 0;
for c in i {
if f(*c) {
ctr += 1;
}
else {
break;
}
}
(ctr, &i[ctr..], str::from_utf8(&i[0..ctr]).unwrap())
} | identifier_body |
readcsv.rs | ///
/// This example parses, sorts and groups the iris dataset
/// and does some simple manipulations.
///
/// Iterators and itertools functionality are used throughout.
///
///
use ndarray::Array;
use dataframe::DataFrame;
use util::traits::UtahNum;
use util::error::*;
use util::traits::Constructor;
use rustc_serialize::Decodable;
use csv;
pub trait ReadCSV<T>
where T: UtahNum + Decodable
{
fn read_csv(file: &'static str) -> Result<DataFrame<T>>;
}
impl<T> ReadCSV<T> for DataFrame<T>
where T: UtahNum + Decodable
{
fn | (file: &'static str) -> Result<DataFrame<T>> {
let mut rdr = csv::Reader::from_file(file).unwrap();
let columns = rdr.headers().unwrap();
let (mut nrow, ncol) = (0, columns.len());
let mut v: Vec<T> = Vec::new();
for record in rdr.decode() {
nrow += 1;
let e: Vec<T> = record.unwrap();
v.extend(e.into_iter())
}
let matrix = Array::from_shape_vec((nrow, ncol), v).unwrap();
DataFrame::new(matrix).columns(&columns[..])
}
}
| read_csv | identifier_name |
readcsv.rs | ///
/// This example parses, sorts and groups the iris dataset
/// and does some simple manipulations.
///
/// Iterators and itertools functionality are used throughout.
///
///
use ndarray::Array;
use dataframe::DataFrame;
use util::traits::UtahNum;
use util::error::*;
use util::traits::Constructor;
use rustc_serialize::Decodable;
use csv;
pub trait ReadCSV<T>
where T: UtahNum + Decodable
{
fn read_csv(file: &'static str) -> Result<DataFrame<T>>;
}
impl<T> ReadCSV<T> for DataFrame<T>
where T: UtahNum + Decodable
{
fn read_csv(file: &'static str) -> Result<DataFrame<T>> |
}
| {
let mut rdr = csv::Reader::from_file(file).unwrap();
let columns = rdr.headers().unwrap();
let (mut nrow, ncol) = (0, columns.len());
let mut v: Vec<T> = Vec::new();
for record in rdr.decode() {
nrow += 1;
let e: Vec<T> = record.unwrap();
v.extend(e.into_iter())
}
let matrix = Array::from_shape_vec((nrow, ncol), v).unwrap();
DataFrame::new(matrix).columns(&columns[..])
} | identifier_body |
readcsv.rs | ///
/// This example parses, sorts and groups the iris dataset
/// and does some simple manipulations.
///
/// Iterators and itertools functionality are used throughout.
///
///
use ndarray::Array;
use dataframe::DataFrame;
use util::traits::UtahNum;
use util::error::*;
use util::traits::Constructor;
use rustc_serialize::Decodable;
use csv;
pub trait ReadCSV<T>
where T: UtahNum + Decodable
{
fn read_csv(file: &'static str) -> Result<DataFrame<T>>;
}
impl<T> ReadCSV<T> for DataFrame<T>
where T: UtahNum + Decodable
{
fn read_csv(file: &'static str) -> Result<DataFrame<T>> {
let mut rdr = csv::Reader::from_file(file).unwrap();
let columns = rdr.headers().unwrap();
let (mut nrow, ncol) = (0, columns.len());
let mut v: Vec<T> = Vec::new(); | let e: Vec<T> = record.unwrap();
v.extend(e.into_iter())
}
let matrix = Array::from_shape_vec((nrow, ncol), v).unwrap();
DataFrame::new(matrix).columns(&columns[..])
}
} | for record in rdr.decode() {
nrow += 1; | random_line_split |
error.rs | use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fmt::Result as FmtResult;
use std::io;
use fmt::Format;
pub type CliResult<T> = Result<T, CliError>;
#[derive(Debug)]
#[allow(dead_code)]
pub enum CliErrorKind {
UnknownBoolArg,
TomlTableRoot,
TomlNoName,
CurrentDir,
Unknown,
Io(io::Error),
Generic(String),
}
impl CliErrorKind {
fn description(&self) -> &str {
match *self {
CliErrorKind::Generic(ref e) => e,
CliErrorKind::TomlTableRoot => "No root table found for toml file",
CliErrorKind::TomlNoName => "No name for package in toml file",
CliErrorKind::CurrentDir => "Unable to determine the current working directory",
CliErrorKind::UnknownBoolArg => "The value supplied isn't valid, either use 'true/false', 'yes/no', or the first letter of either.",
CliErrorKind::Unknown => "An unknown fatal error has occurred, please consider filing a bug-report!",
CliErrorKind::Io(ref e) => e.description(),
}
}
}
impl From<CliErrorKind> for CliError {
fn from(kind: CliErrorKind) -> Self {
CliError {
error: format!("{} {}", Format::Error("error:"), kind.description()),
kind: kind,
}
}
}
#[derive(Debug)]
pub struct CliError {
/// The formatted error message
pub error: String,
/// The type of error
pub kind: CliErrorKind,
}
// Copies clog::error::Error;
impl CliError {
/// Return whether this was a fatal error or not.
pub fn use_stderr(&self) -> bool {
// For now all errors are fatal
true
}
/// Print this error and immediately exit the program.
///
/// If the error is non-fatal then the error is printed to stdout and the
/// exit status will be `0`. Otherwise, when the error is fatal, the error
/// is printed to stderr and the exit status will be `1`.
pub fn exit(&self) ->! {
if self.use_stderr() {
wlnerr!("{}", self);
::std::process::exit(1)
}
println!("{}", self);
::std::process::exit(0)
}
}
impl Display for CliError {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{}", self.error)
}
}
impl Error for CliError {
fn description(&self) -> &str {
self.kind.description()
}
fn cause(&self) -> Option<&Error> {
match self.kind {
CliErrorKind::Io(ref e) => Some(e),
_ => None
}
}
}
impl From<io::Error> for CliError {
fn | (ioe: io::Error) -> Self {
CliError {
error: format!("{} {}", Format::Error("error:"), ioe.description()),
kind: CliErrorKind::Io(ioe),
}
}
}
| from | identifier_name |
error.rs | use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fmt::Result as FmtResult;
use std::io;
use fmt::Format;
pub type CliResult<T> = Result<T, CliError>;
#[derive(Debug)]
#[allow(dead_code)]
pub enum CliErrorKind {
UnknownBoolArg,
TomlTableRoot,
TomlNoName,
CurrentDir, | Io(io::Error),
Generic(String),
}
impl CliErrorKind {
fn description(&self) -> &str {
match *self {
CliErrorKind::Generic(ref e) => e,
CliErrorKind::TomlTableRoot => "No root table found for toml file",
CliErrorKind::TomlNoName => "No name for package in toml file",
CliErrorKind::CurrentDir => "Unable to determine the current working directory",
CliErrorKind::UnknownBoolArg => "The value supplied isn't valid, either use 'true/false', 'yes/no', or the first letter of either.",
CliErrorKind::Unknown => "An unknown fatal error has occurred, please consider filing a bug-report!",
CliErrorKind::Io(ref e) => e.description(),
}
}
}
impl From<CliErrorKind> for CliError {
fn from(kind: CliErrorKind) -> Self {
CliError {
error: format!("{} {}", Format::Error("error:"), kind.description()),
kind: kind,
}
}
}
#[derive(Debug)]
pub struct CliError {
/// The formatted error message
pub error: String,
/// The type of error
pub kind: CliErrorKind,
}
// Copies clog::error::Error;
impl CliError {
/// Return whether this was a fatal error or not.
pub fn use_stderr(&self) -> bool {
// For now all errors are fatal
true
}
/// Print this error and immediately exit the program.
///
/// If the error is non-fatal then the error is printed to stdout and the
/// exit status will be `0`. Otherwise, when the error is fatal, the error
/// is printed to stderr and the exit status will be `1`.
pub fn exit(&self) ->! {
if self.use_stderr() {
wlnerr!("{}", self);
::std::process::exit(1)
}
println!("{}", self);
::std::process::exit(0)
}
}
impl Display for CliError {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{}", self.error)
}
}
impl Error for CliError {
fn description(&self) -> &str {
self.kind.description()
}
fn cause(&self) -> Option<&Error> {
match self.kind {
CliErrorKind::Io(ref e) => Some(e),
_ => None
}
}
}
impl From<io::Error> for CliError {
fn from(ioe: io::Error) -> Self {
CliError {
error: format!("{} {}", Format::Error("error:"), ioe.description()),
kind: CliErrorKind::Io(ioe),
}
}
} | Unknown, | random_line_split |
error.rs | use std::error::Error;
use std::fmt::{Display, Formatter};
use std::fmt::Result as FmtResult;
use std::io;
use fmt::Format;
pub type CliResult<T> = Result<T, CliError>;
#[derive(Debug)]
#[allow(dead_code)]
pub enum CliErrorKind {
UnknownBoolArg,
TomlTableRoot,
TomlNoName,
CurrentDir,
Unknown,
Io(io::Error),
Generic(String),
}
impl CliErrorKind {
fn description(&self) -> &str {
match *self {
CliErrorKind::Generic(ref e) => e,
CliErrorKind::TomlTableRoot => "No root table found for toml file",
CliErrorKind::TomlNoName => "No name for package in toml file",
CliErrorKind::CurrentDir => "Unable to determine the current working directory",
CliErrorKind::UnknownBoolArg => "The value supplied isn't valid, either use 'true/false', 'yes/no', or the first letter of either.",
CliErrorKind::Unknown => "An unknown fatal error has occurred, please consider filing a bug-report!",
CliErrorKind::Io(ref e) => e.description(),
}
}
}
impl From<CliErrorKind> for CliError {
fn from(kind: CliErrorKind) -> Self {
CliError {
error: format!("{} {}", Format::Error("error:"), kind.description()),
kind: kind,
}
}
}
#[derive(Debug)]
pub struct CliError {
/// The formatted error message
pub error: String,
/// The type of error
pub kind: CliErrorKind,
}
// Copies clog::error::Error;
impl CliError {
/// Return whether this was a fatal error or not.
pub fn use_stderr(&self) -> bool {
// For now all errors are fatal
true
}
/// Print this error and immediately exit the program.
///
/// If the error is non-fatal then the error is printed to stdout and the
/// exit status will be `0`. Otherwise, when the error is fatal, the error
/// is printed to stderr and the exit status will be `1`.
pub fn exit(&self) ->! {
if self.use_stderr() {
wlnerr!("{}", self);
::std::process::exit(1)
}
println!("{}", self);
::std::process::exit(0)
}
}
impl Display for CliError {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
write!(f, "{}", self.error)
}
}
impl Error for CliError {
fn description(&self) -> &str {
self.kind.description()
}
fn cause(&self) -> Option<&Error> {
match self.kind {
CliErrorKind::Io(ref e) => Some(e),
_ => None
}
}
}
impl From<io::Error> for CliError {
fn from(ioe: io::Error) -> Self |
}
| {
CliError {
error: format!("{} {}", Format::Error("error:"), ioe.description()),
kind: CliErrorKind::Io(ioe),
}
} | identifier_body |
quick.rs | #![cfg_attr(feature = "qc", feature(plugin, custom_attribute))]
#![cfg_attr(feature="qc", plugin(quickcheck_macros))]
#![allow(dead_code)]
//! The purpose of these tests is to cover corner cases of iterators
//! and adaptors.
//!
//! In particular we test the tedious size_hint and exact size correctness.
#[macro_use]
extern crate itertools;
#[cfg(feature = "qc")]
extern crate quickcheck;
#[cfg(feature = "qc")]
mod quicktests {
use std::default::Default;
use quickcheck as qc;
use std::ops::Range;
use itertools;
use itertools::Itertools;
use itertools::{
Zip,
Stride,
EitherOrBoth,
};
/// Our base iterator that we can impl Arbitrary for
///
/// NOTE: Iter is tricky and is not fused, to help catch bugs.
/// At the end it will return None once, then return Some(0),
/// then return None again.
#[derive(Clone, Debug)]
struct Iter<T>(Range<T>, i32); // with fuse/done flag
impl<T> Iter<T>
{
fn new(it: Range<T>) -> Self
{
Iter(it, 0)
}
}
impl<T> Iterator for Iter<T> where Range<T>: Iterator,
<Range<T> as Iterator>::Item: Default,
{
type Item = <Range<T> as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item>
{
let elt = self.0.next();
if elt.is_none() {
self.1 += 1;
// check fuse flag
if self.1 == 2 {
return Some(Default::default())
}
}
elt
}
fn size_hint(&self) -> (usize, Option<usize>)
{
self.0.size_hint()
}
}
impl<T> DoubleEndedIterator for Iter<T> where Range<T>: DoubleEndedIterator,
<Range<T> as Iterator>::Item: Default,
{
fn next_back(&mut self) -> Option<Self::Item> { self.0.next_back() }
}
impl<T> ExactSizeIterator for Iter<T> where Range<T>: ExactSizeIterator,
<Range<T> as Iterator>::Item: Default,
{ }
impl<T> qc::Arbitrary for Iter<T> where T: qc::Arbitrary
{
fn arbitrary<G: qc::Gen>(g: &mut G) -> Self
{
Iter::new(T::arbitrary(g)..T::arbitrary(g))
}
fn shrink(&self) -> Box<Iterator<Item=Iter<T>>>
{
let r = self.0.clone();
Box::new(
r.start.shrink().flat_map(move |x| {
r.end.shrink().map(move |y| (x.clone(), y))
})
.map(|(a, b)| Iter::new(a..b))
)
}
}
fn correct_size_hint_fast<I: Iterator>(it: I) -> bool {
let (low, hi) = it.size_hint();
let cnt = it.count();
cnt >= low &&
(hi.is_none() || hi.unwrap() >= cnt)
}
fn correct_size_hint<I: Iterator>(mut it: I) -> bool {
// record size hint at each iteration
let initial_hint = it.size_hint();
let mut hints = Vec::with_capacity(initial_hint.0 + 1);
hints.push(initial_hint);
while let Some(_) = it.next() {
hints.push(it.size_hint())
}
let mut true_count = hints.len(); // start off +1 too much
// check all the size hints
for &(low, hi) in &hints {
true_count -= 1;
if low > true_count ||
(hi.is_some() && hi.unwrap() < true_count)
{
println!("True size: {:?}, size hint: {:?}", true_count, (low, hi));
//println!("All hints: {:?}", hints);
return false
}
}
true
}
fn exact_size<I: ExactSizeIterator>(mut it: I) -> bool {
// check every iteration
let (mut low, mut hi) = it.size_hint();
if Some(low)!= hi { return false; }
while let Some(_) = it.next() {
let (xlow, xhi) = it.size_hint();
if low!= xlow + 1 { return false; }
low = xlow;
hi = xhi;
if Some(low)!= hi { return false; }
}
let (low, hi) = it.size_hint();
low == 0 && hi == Some(0)
}
/*
* NOTE: Range<i8> is broken!
* (all signed ranges are)
#[quickcheck]
fn size_range_i8(a: Iter<i8>) -> bool {
exact_size(a)
}
#[quickcheck]
fn size_range_i16(a: Iter<i16>) -> bool {
exact_size(a)
}
#[quickcheck]
fn size_range_u8(a: Iter<u8>) -> bool {
exact_size(a)
}
*/
#[quickcheck]
fn size_stride(data: Vec<u8>, mut stride: isize) -> bool {
if stride == 0 {
stride += 1; // never zero
}
exact_size(Stride::from_slice(&data, stride))
}
#[quickcheck] | if stride == 0 {
// never zero
stride += 1;
}
if stride > 0 {
itertools::equal(Stride::from_slice(&data, stride as isize),
data.iter().step(stride as usize))
} else {
itertools::equal(Stride::from_slice(&data, stride as isize),
data.iter().rev().step(-stride as usize))
}
}
#[quickcheck]
fn size_product(a: Iter<u16>, b: Iter<u16>) -> bool {
correct_size_hint(a.cartesian_product(b))
}
#[quickcheck]
fn size_product3(a: Iter<u16>, b: Iter<u16>, c: Iter<u16>) -> bool {
correct_size_hint(iproduct!(a, b, c))
}
#[quickcheck]
fn size_step(a: Iter<i16>, mut s: usize) -> bool {
if s == 0 {
s += 1; // never zero
}
let filt = a.clone().dedup();
correct_size_hint(filt.step(s)) &&
exact_size(a.step(s))
}
#[quickcheck]
fn size_multipeek(a: Iter<u16>, s: u8) -> bool {
let mut it = a.multipeek();
// peek a few times
for _ in 0..s {
it.peek();
}
exact_size(it)
}
#[quickcheck]
fn equal_merge(a: Vec<i16>, b: Vec<i16>) -> bool {
let mut sa = a.clone();
let mut sb = b.clone();
sa.sort();
sb.sort();
let mut merged = sa.clone();
merged.extend(sb.iter().cloned());
merged.sort();
itertools::equal(&merged, sa.iter().merge(&sb))
}
#[quickcheck]
fn size_merge(a: Iter<u16>, b: Iter<u16>) -> bool {
correct_size_hint(a.merge(b))
}
#[quickcheck]
fn size_zip(a: Iter<i16>, b: Iter<i16>, c: Iter<i16>) -> bool {
let filt = a.clone().dedup();
correct_size_hint(Zip::new((filt, b.clone(), c.clone()))) &&
exact_size(Zip::new((a, b, c)))
}
#[quickcheck]
fn size_zip_rc(a: Iter<i16>, b: Iter<i16>) -> bool {
let rc = a.clone().into_rc();
correct_size_hint(Zip::new((&rc, &rc, b)))
}
#[quickcheck]
fn size_zip_longest(a: Iter<i16>, b: Iter<i16>) -> bool {
let filt = a.clone().dedup();
let filt2 = b.clone().dedup();
correct_size_hint(filt.zip_longest(b.clone())) &&
correct_size_hint(a.clone().zip_longest(filt2)) &&
exact_size(a.zip_longest(b))
}
#[quickcheck]
fn size_2_zip_longest(a: Iter<i16>, b: Iter<i16>) -> bool {
let it = a.clone().zip_longest(b.clone());
let jt = a.clone().zip_longest(b.clone());
itertools::equal(a.clone(),
it.filter_map(|elt| match elt {
EitherOrBoth::Both(x, _) => Some(x),
EitherOrBoth::Left(x) => Some(x),
_ => None,
}
))
&&
itertools::equal(b.clone(),
jt.filter_map(|elt| match elt {
EitherOrBoth::Both(_, y) => Some(y),
EitherOrBoth::Right(y) => Some(y),
_ => None,
}
))
}
fn equal_islice(a: Vec<i16>, x: usize, y: usize) -> bool {
if x > y || y > a.len() { return true; }
let slc = &a[x..y];
itertools::equal(a.iter().slice(x..y), slc)
}
fn size_islice(a: Iter<i16>, x: usize, y: usize) -> bool {
correct_size_hint(a.clone().dedup().slice(x..y)) &&
exact_size(a.clone().slice(x..y))
}
#[quickcheck]
fn size_interleave(a: Iter<i16>, b: Iter<i16>) -> bool {
correct_size_hint(a.interleave(b))
}
#[quickcheck]
fn size_intersperse(a: Iter<i16>, x: i16) -> bool {
correct_size_hint(a.intersperse(x))
}
#[quickcheck]
fn equal_intersperse(a: Vec<i32>, x: i32) -> bool {
let mut inter = false;
let mut i = 0;
for elt in a.iter().cloned().intersperse(x) {
if inter {
if elt!= x { return false }
} else {
if elt!= a[i] { return false }
i += 1;
}
inter =!inter;
}
true
}
#[quickcheck]
fn equal_dedup(a: Vec<i32>) -> bool {
let mut b = a.clone();
b.dedup();
itertools::equal(&b, a.iter().dedup())
}
#[quickcheck]
fn size_dedup(a: Vec<i32>) -> bool {
correct_size_hint(a.iter().dedup())
}
#[quickcheck]
fn size_group_by(a: Vec<i8>) -> bool {
correct_size_hint(a.iter().group_by(|x| x.abs()))
}
#[quickcheck]
fn size_linspace(a: f32, b: f32, n: usize) -> bool {
let it = itertools::linspace(a, b, n);
it.len() == n &&
exact_size(it)
}
#[quickcheck]
fn equal_repeatn(n: usize, x: i32) -> bool {
let it = itertools::RepeatN::new(x, n);
exact_size(it)
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted(a: Vec<u8>, b: Vec<u8>) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter())))
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted3(a: Vec<u8>, b: Vec<u8>, c: Vec<u8>) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter(), c.iter())))
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn equal_ziptrusted_mix(a: Vec<u8>, b: Vec<()>, x: u8, y: u8) -> bool {
let it = itertools::ZipTrusted::new((a.iter(), b.iter(), x..y));
let jt = Zip::new((a.iter(), b.iter(), x..y));
itertools::equal(it, jt)
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted_mix(a: Vec<u8>, b: Vec<()>, x: u8, y: u8) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter(), x..y)))
}
#[quickcheck]
fn size_put_back(a: Vec<u8>, x: Option<u8>) -> bool {
let mut it = itertools::PutBack::new(a.into_iter());
match x {
Some(t) => it.put_back(t),
None => {}
}
correct_size_hint(it)
}
#[quickcheck]
fn size_put_backn(a: Vec<u8>, b: Vec<u8>) -> bool {
let mut it = itertools::PutBackN::new(a.into_iter());
for elt in b {
it.put_back(elt)
}
correct_size_hint(it)
}
#[quickcheck]
fn size_tee(a: Vec<u8>) -> bool {
let (mut t1, mut t2) = a.iter().tee();
t1.next();
t1.next();
t2.next();
exact_size(t1) && exact_size(t2)
}
#[quickcheck]
fn size_tee_2(a: Vec<u8>) -> bool {
let (mut t1, mut t2) = a.iter().dedup().tee();
t1.next();
t1.next();
t2.next();
correct_size_hint(t1) && correct_size_hint(t2)
}
#[quickcheck]
fn size_mend_slices(a: Vec<u8>, splits: Vec<usize>) -> bool {
let slice_iter = splits.into_iter().map(|ix|
if ix < a.len() {
&a[ix..(ix + 1)]
} else {
&a[0..0]
}
).mend_slices();
correct_size_hint(slice_iter)
}
#[quickcheck]
fn size_take_while_ref(a: Vec<u8>, stop: u8) -> bool {
correct_size_hint(a.iter().take_while_ref(|x| **x!= stop))
}
#[quickcheck]
fn equal_partition(mut a: Vec<i32>) -> bool {
let mut ap = a.clone();
let split_index = itertools::partition(&mut ap, |x| *x >= 0);
let parted = (0..split_index).all(|i| ap[i] >= 0) &&
(split_index..a.len()).all(|i| ap[i] < 0);
a.sort();
ap.sort();
parted && (a == ap)
}
#[quickcheck]
fn size_combinations(it: Iter<i16>) -> bool {
correct_size_hint(it.combinations())
}
#[quickcheck]
fn equal_combinations(mut it: Iter<i16>) -> bool {
let values = it.clone().collect_vec();
let mut cmb = it.combinations();
for i in 0..values.len() {
for j in i+1..values.len() {
let pair = (values[i], values[j]);
if pair!= cmb.next().unwrap() {
return false;
}
}
}
cmb.next() == None
}
#[quickcheck]
fn size_pad_tail(it: Iter<i8>, pad: u8) -> bool {
correct_size_hint(it.clone().pad_using(pad as usize, |_| 0)) &&
correct_size_hint(it.dropping(1).rev().pad_using(pad as usize, |_| 0))
}
#[quickcheck]
fn size_pad_tail2(it: Iter<i8>, pad: u8) -> bool {
exact_size(it.pad_using(pad as usize, |_| 0))
}
} | fn equal_stride(data: Vec<u8>, mut stride: i8) -> bool { | random_line_split |
quick.rs | #![cfg_attr(feature = "qc", feature(plugin, custom_attribute))]
#![cfg_attr(feature="qc", plugin(quickcheck_macros))]
#![allow(dead_code)]
//! The purpose of these tests is to cover corner cases of iterators
//! and adaptors.
//!
//! In particular we test the tedious size_hint and exact size correctness.
#[macro_use]
extern crate itertools;
#[cfg(feature = "qc")]
extern crate quickcheck;
#[cfg(feature = "qc")]
mod quicktests {
use std::default::Default;
use quickcheck as qc;
use std::ops::Range;
use itertools;
use itertools::Itertools;
use itertools::{
Zip,
Stride,
EitherOrBoth,
};
/// Our base iterator that we can impl Arbitrary for
///
/// NOTE: Iter is tricky and is not fused, to help catch bugs.
/// At the end it will return None once, then return Some(0),
/// then return None again.
#[derive(Clone, Debug)]
struct Iter<T>(Range<T>, i32); // with fuse/done flag
impl<T> Iter<T>
{
fn new(it: Range<T>) -> Self
{
Iter(it, 0)
}
}
impl<T> Iterator for Iter<T> where Range<T>: Iterator,
<Range<T> as Iterator>::Item: Default,
{
type Item = <Range<T> as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item>
{
let elt = self.0.next();
if elt.is_none() {
self.1 += 1;
// check fuse flag
if self.1 == 2 {
return Some(Default::default())
}
}
elt
}
fn size_hint(&self) -> (usize, Option<usize>)
{
self.0.size_hint()
}
}
impl<T> DoubleEndedIterator for Iter<T> where Range<T>: DoubleEndedIterator,
<Range<T> as Iterator>::Item: Default,
{
fn next_back(&mut self) -> Option<Self::Item> { self.0.next_back() }
}
impl<T> ExactSizeIterator for Iter<T> where Range<T>: ExactSizeIterator,
<Range<T> as Iterator>::Item: Default,
{ }
impl<T> qc::Arbitrary for Iter<T> where T: qc::Arbitrary
{
fn arbitrary<G: qc::Gen>(g: &mut G) -> Self
{
Iter::new(T::arbitrary(g)..T::arbitrary(g))
}
fn shrink(&self) -> Box<Iterator<Item=Iter<T>>>
{
let r = self.0.clone();
Box::new(
r.start.shrink().flat_map(move |x| {
r.end.shrink().map(move |y| (x.clone(), y))
})
.map(|(a, b)| Iter::new(a..b))
)
}
}
fn correct_size_hint_fast<I: Iterator>(it: I) -> bool {
let (low, hi) = it.size_hint();
let cnt = it.count();
cnt >= low &&
(hi.is_none() || hi.unwrap() >= cnt)
}
fn correct_size_hint<I: Iterator>(mut it: I) -> bool {
// record size hint at each iteration
let initial_hint = it.size_hint();
let mut hints = Vec::with_capacity(initial_hint.0 + 1);
hints.push(initial_hint);
while let Some(_) = it.next() {
hints.push(it.size_hint())
}
let mut true_count = hints.len(); // start off +1 too much
// check all the size hints
for &(low, hi) in &hints {
true_count -= 1;
if low > true_count ||
(hi.is_some() && hi.unwrap() < true_count)
{
println!("True size: {:?}, size hint: {:?}", true_count, (low, hi));
//println!("All hints: {:?}", hints);
return false
}
}
true
}
fn exact_size<I: ExactSizeIterator>(mut it: I) -> bool {
// check every iteration
let (mut low, mut hi) = it.size_hint();
if Some(low)!= hi { return false; }
while let Some(_) = it.next() {
let (xlow, xhi) = it.size_hint();
if low!= xlow + 1 { return false; }
low = xlow;
hi = xhi;
if Some(low)!= hi { return false; }
}
let (low, hi) = it.size_hint();
low == 0 && hi == Some(0)
}
/*
* NOTE: Range<i8> is broken!
* (all signed ranges are)
#[quickcheck]
fn size_range_i8(a: Iter<i8>) -> bool {
exact_size(a)
}
#[quickcheck]
fn size_range_i16(a: Iter<i16>) -> bool {
exact_size(a)
}
#[quickcheck]
fn size_range_u8(a: Iter<u8>) -> bool {
exact_size(a)
}
*/
#[quickcheck]
fn size_stride(data: Vec<u8>, mut stride: isize) -> bool {
if stride == 0 {
stride += 1; // never zero
}
exact_size(Stride::from_slice(&data, stride))
}
#[quickcheck]
fn equal_stride(data: Vec<u8>, mut stride: i8) -> bool {
if stride == 0 {
// never zero
stride += 1;
}
if stride > 0 {
itertools::equal(Stride::from_slice(&data, stride as isize),
data.iter().step(stride as usize))
} else {
itertools::equal(Stride::from_slice(&data, stride as isize),
data.iter().rev().step(-stride as usize))
}
}
#[quickcheck]
fn size_product(a: Iter<u16>, b: Iter<u16>) -> bool {
correct_size_hint(a.cartesian_product(b))
}
#[quickcheck]
fn size_product3(a: Iter<u16>, b: Iter<u16>, c: Iter<u16>) -> bool {
correct_size_hint(iproduct!(a, b, c))
}
#[quickcheck]
fn size_step(a: Iter<i16>, mut s: usize) -> bool {
if s == 0 {
s += 1; // never zero
}
let filt = a.clone().dedup();
correct_size_hint(filt.step(s)) &&
exact_size(a.step(s))
}
#[quickcheck]
fn size_multipeek(a: Iter<u16>, s: u8) -> bool {
let mut it = a.multipeek();
// peek a few times
for _ in 0..s {
it.peek();
}
exact_size(it)
}
#[quickcheck]
fn equal_merge(a: Vec<i16>, b: Vec<i16>) -> bool {
let mut sa = a.clone();
let mut sb = b.clone();
sa.sort();
sb.sort();
let mut merged = sa.clone();
merged.extend(sb.iter().cloned());
merged.sort();
itertools::equal(&merged, sa.iter().merge(&sb))
}
#[quickcheck]
fn size_merge(a: Iter<u16>, b: Iter<u16>) -> bool {
correct_size_hint(a.merge(b))
}
#[quickcheck]
fn size_zip(a: Iter<i16>, b: Iter<i16>, c: Iter<i16>) -> bool {
let filt = a.clone().dedup();
correct_size_hint(Zip::new((filt, b.clone(), c.clone()))) &&
exact_size(Zip::new((a, b, c)))
}
#[quickcheck]
fn size_zip_rc(a: Iter<i16>, b: Iter<i16>) -> bool {
let rc = a.clone().into_rc();
correct_size_hint(Zip::new((&rc, &rc, b)))
}
#[quickcheck]
fn size_zip_longest(a: Iter<i16>, b: Iter<i16>) -> bool |
#[quickcheck]
fn size_2_zip_longest(a: Iter<i16>, b: Iter<i16>) -> bool {
let it = a.clone().zip_longest(b.clone());
let jt = a.clone().zip_longest(b.clone());
itertools::equal(a.clone(),
it.filter_map(|elt| match elt {
EitherOrBoth::Both(x, _) => Some(x),
EitherOrBoth::Left(x) => Some(x),
_ => None,
}
))
&&
itertools::equal(b.clone(),
jt.filter_map(|elt| match elt {
EitherOrBoth::Both(_, y) => Some(y),
EitherOrBoth::Right(y) => Some(y),
_ => None,
}
))
}
fn equal_islice(a: Vec<i16>, x: usize, y: usize) -> bool {
if x > y || y > a.len() { return true; }
let slc = &a[x..y];
itertools::equal(a.iter().slice(x..y), slc)
}
fn size_islice(a: Iter<i16>, x: usize, y: usize) -> bool {
correct_size_hint(a.clone().dedup().slice(x..y)) &&
exact_size(a.clone().slice(x..y))
}
#[quickcheck]
fn size_interleave(a: Iter<i16>, b: Iter<i16>) -> bool {
correct_size_hint(a.interleave(b))
}
#[quickcheck]
fn size_intersperse(a: Iter<i16>, x: i16) -> bool {
correct_size_hint(a.intersperse(x))
}
#[quickcheck]
fn equal_intersperse(a: Vec<i32>, x: i32) -> bool {
let mut inter = false;
let mut i = 0;
for elt in a.iter().cloned().intersperse(x) {
if inter {
if elt!= x { return false }
} else {
if elt!= a[i] { return false }
i += 1;
}
inter =!inter;
}
true
}
#[quickcheck]
fn equal_dedup(a: Vec<i32>) -> bool {
let mut b = a.clone();
b.dedup();
itertools::equal(&b, a.iter().dedup())
}
#[quickcheck]
fn size_dedup(a: Vec<i32>) -> bool {
correct_size_hint(a.iter().dedup())
}
#[quickcheck]
fn size_group_by(a: Vec<i8>) -> bool {
correct_size_hint(a.iter().group_by(|x| x.abs()))
}
#[quickcheck]
fn size_linspace(a: f32, b: f32, n: usize) -> bool {
let it = itertools::linspace(a, b, n);
it.len() == n &&
exact_size(it)
}
#[quickcheck]
fn equal_repeatn(n: usize, x: i32) -> bool {
let it = itertools::RepeatN::new(x, n);
exact_size(it)
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted(a: Vec<u8>, b: Vec<u8>) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter())))
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted3(a: Vec<u8>, b: Vec<u8>, c: Vec<u8>) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter(), c.iter())))
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn equal_ziptrusted_mix(a: Vec<u8>, b: Vec<()>, x: u8, y: u8) -> bool {
let it = itertools::ZipTrusted::new((a.iter(), b.iter(), x..y));
let jt = Zip::new((a.iter(), b.iter(), x..y));
itertools::equal(it, jt)
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted_mix(a: Vec<u8>, b: Vec<()>, x: u8, y: u8) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter(), x..y)))
}
#[quickcheck]
fn size_put_back(a: Vec<u8>, x: Option<u8>) -> bool {
let mut it = itertools::PutBack::new(a.into_iter());
match x {
Some(t) => it.put_back(t),
None => {}
}
correct_size_hint(it)
}
#[quickcheck]
fn size_put_backn(a: Vec<u8>, b: Vec<u8>) -> bool {
let mut it = itertools::PutBackN::new(a.into_iter());
for elt in b {
it.put_back(elt)
}
correct_size_hint(it)
}
#[quickcheck]
fn size_tee(a: Vec<u8>) -> bool {
let (mut t1, mut t2) = a.iter().tee();
t1.next();
t1.next();
t2.next();
exact_size(t1) && exact_size(t2)
}
#[quickcheck]
fn size_tee_2(a: Vec<u8>) -> bool {
let (mut t1, mut t2) = a.iter().dedup().tee();
t1.next();
t1.next();
t2.next();
correct_size_hint(t1) && correct_size_hint(t2)
}
#[quickcheck]
fn size_mend_slices(a: Vec<u8>, splits: Vec<usize>) -> bool {
let slice_iter = splits.into_iter().map(|ix|
if ix < a.len() {
&a[ix..(ix + 1)]
} else {
&a[0..0]
}
).mend_slices();
correct_size_hint(slice_iter)
}
#[quickcheck]
fn size_take_while_ref(a: Vec<u8>, stop: u8) -> bool {
correct_size_hint(a.iter().take_while_ref(|x| **x!= stop))
}
#[quickcheck]
fn equal_partition(mut a: Vec<i32>) -> bool {
let mut ap = a.clone();
let split_index = itertools::partition(&mut ap, |x| *x >= 0);
let parted = (0..split_index).all(|i| ap[i] >= 0) &&
(split_index..a.len()).all(|i| ap[i] < 0);
a.sort();
ap.sort();
parted && (a == ap)
}
#[quickcheck]
fn size_combinations(it: Iter<i16>) -> bool {
correct_size_hint(it.combinations())
}
#[quickcheck]
fn equal_combinations(mut it: Iter<i16>) -> bool {
let values = it.clone().collect_vec();
let mut cmb = it.combinations();
for i in 0..values.len() {
for j in i+1..values.len() {
let pair = (values[i], values[j]);
if pair!= cmb.next().unwrap() {
return false;
}
}
}
cmb.next() == None
}
#[quickcheck]
fn size_pad_tail(it: Iter<i8>, pad: u8) -> bool {
correct_size_hint(it.clone().pad_using(pad as usize, |_| 0)) &&
correct_size_hint(it.dropping(1).rev().pad_using(pad as usize, |_| 0))
}
#[quickcheck]
fn size_pad_tail2(it: Iter<i8>, pad: u8) -> bool {
exact_size(it.pad_using(pad as usize, |_| 0))
}
}
| {
let filt = a.clone().dedup();
let filt2 = b.clone().dedup();
correct_size_hint(filt.zip_longest(b.clone())) &&
correct_size_hint(a.clone().zip_longest(filt2)) &&
exact_size(a.zip_longest(b))
} | identifier_body |
quick.rs | #![cfg_attr(feature = "qc", feature(plugin, custom_attribute))]
#![cfg_attr(feature="qc", plugin(quickcheck_macros))]
#![allow(dead_code)]
//! The purpose of these tests is to cover corner cases of iterators
//! and adaptors.
//!
//! In particular we test the tedious size_hint and exact size correctness.
#[macro_use]
extern crate itertools;
#[cfg(feature = "qc")]
extern crate quickcheck;
#[cfg(feature = "qc")]
mod quicktests {
use std::default::Default;
use quickcheck as qc;
use std::ops::Range;
use itertools;
use itertools::Itertools;
use itertools::{
Zip,
Stride,
EitherOrBoth,
};
/// Our base iterator that we can impl Arbitrary for
///
/// NOTE: Iter is tricky and is not fused, to help catch bugs.
/// At the end it will return None once, then return Some(0),
/// then return None again.
#[derive(Clone, Debug)]
struct Iter<T>(Range<T>, i32); // with fuse/done flag
impl<T> Iter<T>
{
fn new(it: Range<T>) -> Self
{
Iter(it, 0)
}
}
impl<T> Iterator for Iter<T> where Range<T>: Iterator,
<Range<T> as Iterator>::Item: Default,
{
type Item = <Range<T> as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item>
{
let elt = self.0.next();
if elt.is_none() {
self.1 += 1;
// check fuse flag
if self.1 == 2 {
return Some(Default::default())
}
}
elt
}
fn size_hint(&self) -> (usize, Option<usize>)
{
self.0.size_hint()
}
}
impl<T> DoubleEndedIterator for Iter<T> where Range<T>: DoubleEndedIterator,
<Range<T> as Iterator>::Item: Default,
{
fn next_back(&mut self) -> Option<Self::Item> { self.0.next_back() }
}
impl<T> ExactSizeIterator for Iter<T> where Range<T>: ExactSizeIterator,
<Range<T> as Iterator>::Item: Default,
{ }
impl<T> qc::Arbitrary for Iter<T> where T: qc::Arbitrary
{
fn arbitrary<G: qc::Gen>(g: &mut G) -> Self
{
Iter::new(T::arbitrary(g)..T::arbitrary(g))
}
fn shrink(&self) -> Box<Iterator<Item=Iter<T>>>
{
let r = self.0.clone();
Box::new(
r.start.shrink().flat_map(move |x| {
r.end.shrink().map(move |y| (x.clone(), y))
})
.map(|(a, b)| Iter::new(a..b))
)
}
}
fn correct_size_hint_fast<I: Iterator>(it: I) -> bool {
let (low, hi) = it.size_hint();
let cnt = it.count();
cnt >= low &&
(hi.is_none() || hi.unwrap() >= cnt)
}
fn correct_size_hint<I: Iterator>(mut it: I) -> bool {
// record size hint at each iteration
let initial_hint = it.size_hint();
let mut hints = Vec::with_capacity(initial_hint.0 + 1);
hints.push(initial_hint);
while let Some(_) = it.next() {
hints.push(it.size_hint())
}
let mut true_count = hints.len(); // start off +1 too much
// check all the size hints
for &(low, hi) in &hints {
true_count -= 1;
if low > true_count ||
(hi.is_some() && hi.unwrap() < true_count)
{
println!("True size: {:?}, size hint: {:?}", true_count, (low, hi));
//println!("All hints: {:?}", hints);
return false
}
}
true
}
fn exact_size<I: ExactSizeIterator>(mut it: I) -> bool {
// check every iteration
let (mut low, mut hi) = it.size_hint();
if Some(low)!= hi { return false; }
while let Some(_) = it.next() {
let (xlow, xhi) = it.size_hint();
if low!= xlow + 1 { return false; }
low = xlow;
hi = xhi;
if Some(low)!= hi { return false; }
}
let (low, hi) = it.size_hint();
low == 0 && hi == Some(0)
}
/*
* NOTE: Range<i8> is broken!
* (all signed ranges are)
#[quickcheck]
fn size_range_i8(a: Iter<i8>) -> bool {
exact_size(a)
}
#[quickcheck]
fn size_range_i16(a: Iter<i16>) -> bool {
exact_size(a)
}
#[quickcheck]
fn size_range_u8(a: Iter<u8>) -> bool {
exact_size(a)
}
*/
#[quickcheck]
fn size_stride(data: Vec<u8>, mut stride: isize) -> bool {
if stride == 0 {
stride += 1; // never zero
}
exact_size(Stride::from_slice(&data, stride))
}
#[quickcheck]
fn equal_stride(data: Vec<u8>, mut stride: i8) -> bool {
if stride == 0 {
// never zero
stride += 1;
}
if stride > 0 {
itertools::equal(Stride::from_slice(&data, stride as isize),
data.iter().step(stride as usize))
} else {
itertools::equal(Stride::from_slice(&data, stride as isize),
data.iter().rev().step(-stride as usize))
}
}
#[quickcheck]
fn size_product(a: Iter<u16>, b: Iter<u16>) -> bool {
correct_size_hint(a.cartesian_product(b))
}
#[quickcheck]
fn size_product3(a: Iter<u16>, b: Iter<u16>, c: Iter<u16>) -> bool {
correct_size_hint(iproduct!(a, b, c))
}
#[quickcheck]
fn size_step(a: Iter<i16>, mut s: usize) -> bool {
if s == 0 {
s += 1; // never zero
}
let filt = a.clone().dedup();
correct_size_hint(filt.step(s)) &&
exact_size(a.step(s))
}
#[quickcheck]
fn size_multipeek(a: Iter<u16>, s: u8) -> bool {
let mut it = a.multipeek();
// peek a few times
for _ in 0..s {
it.peek();
}
exact_size(it)
}
#[quickcheck]
fn equal_merge(a: Vec<i16>, b: Vec<i16>) -> bool {
let mut sa = a.clone();
let mut sb = b.clone();
sa.sort();
sb.sort();
let mut merged = sa.clone();
merged.extend(sb.iter().cloned());
merged.sort();
itertools::equal(&merged, sa.iter().merge(&sb))
}
#[quickcheck]
fn size_merge(a: Iter<u16>, b: Iter<u16>) -> bool {
correct_size_hint(a.merge(b))
}
#[quickcheck]
fn size_zip(a: Iter<i16>, b: Iter<i16>, c: Iter<i16>) -> bool {
let filt = a.clone().dedup();
correct_size_hint(Zip::new((filt, b.clone(), c.clone()))) &&
exact_size(Zip::new((a, b, c)))
}
#[quickcheck]
fn size_zip_rc(a: Iter<i16>, b: Iter<i16>) -> bool {
let rc = a.clone().into_rc();
correct_size_hint(Zip::new((&rc, &rc, b)))
}
#[quickcheck]
fn size_zip_longest(a: Iter<i16>, b: Iter<i16>) -> bool {
let filt = a.clone().dedup();
let filt2 = b.clone().dedup();
correct_size_hint(filt.zip_longest(b.clone())) &&
correct_size_hint(a.clone().zip_longest(filt2)) &&
exact_size(a.zip_longest(b))
}
#[quickcheck]
fn size_2_zip_longest(a: Iter<i16>, b: Iter<i16>) -> bool {
let it = a.clone().zip_longest(b.clone());
let jt = a.clone().zip_longest(b.clone());
itertools::equal(a.clone(),
it.filter_map(|elt| match elt {
EitherOrBoth::Both(x, _) => Some(x),
EitherOrBoth::Left(x) => Some(x),
_ => None,
}
))
&&
itertools::equal(b.clone(),
jt.filter_map(|elt| match elt {
EitherOrBoth::Both(_, y) => Some(y),
EitherOrBoth::Right(y) => Some(y),
_ => None,
}
))
}
fn equal_islice(a: Vec<i16>, x: usize, y: usize) -> bool {
if x > y || y > a.len() { return true; }
let slc = &a[x..y];
itertools::equal(a.iter().slice(x..y), slc)
}
fn size_islice(a: Iter<i16>, x: usize, y: usize) -> bool {
correct_size_hint(a.clone().dedup().slice(x..y)) &&
exact_size(a.clone().slice(x..y))
}
#[quickcheck]
fn size_interleave(a: Iter<i16>, b: Iter<i16>) -> bool {
correct_size_hint(a.interleave(b))
}
#[quickcheck]
fn size_intersperse(a: Iter<i16>, x: i16) -> bool {
correct_size_hint(a.intersperse(x))
}
#[quickcheck]
fn | (a: Vec<i32>, x: i32) -> bool {
let mut inter = false;
let mut i = 0;
for elt in a.iter().cloned().intersperse(x) {
if inter {
if elt!= x { return false }
} else {
if elt!= a[i] { return false }
i += 1;
}
inter =!inter;
}
true
}
#[quickcheck]
fn equal_dedup(a: Vec<i32>) -> bool {
let mut b = a.clone();
b.dedup();
itertools::equal(&b, a.iter().dedup())
}
#[quickcheck]
fn size_dedup(a: Vec<i32>) -> bool {
correct_size_hint(a.iter().dedup())
}
#[quickcheck]
fn size_group_by(a: Vec<i8>) -> bool {
correct_size_hint(a.iter().group_by(|x| x.abs()))
}
#[quickcheck]
fn size_linspace(a: f32, b: f32, n: usize) -> bool {
let it = itertools::linspace(a, b, n);
it.len() == n &&
exact_size(it)
}
#[quickcheck]
fn equal_repeatn(n: usize, x: i32) -> bool {
let it = itertools::RepeatN::new(x, n);
exact_size(it)
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted(a: Vec<u8>, b: Vec<u8>) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter())))
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted3(a: Vec<u8>, b: Vec<u8>, c: Vec<u8>) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter(), c.iter())))
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn equal_ziptrusted_mix(a: Vec<u8>, b: Vec<()>, x: u8, y: u8) -> bool {
let it = itertools::ZipTrusted::new((a.iter(), b.iter(), x..y));
let jt = Zip::new((a.iter(), b.iter(), x..y));
itertools::equal(it, jt)
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted_mix(a: Vec<u8>, b: Vec<()>, x: u8, y: u8) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter(), x..y)))
}
#[quickcheck]
fn size_put_back(a: Vec<u8>, x: Option<u8>) -> bool {
let mut it = itertools::PutBack::new(a.into_iter());
match x {
Some(t) => it.put_back(t),
None => {}
}
correct_size_hint(it)
}
#[quickcheck]
fn size_put_backn(a: Vec<u8>, b: Vec<u8>) -> bool {
let mut it = itertools::PutBackN::new(a.into_iter());
for elt in b {
it.put_back(elt)
}
correct_size_hint(it)
}
#[quickcheck]
fn size_tee(a: Vec<u8>) -> bool {
let (mut t1, mut t2) = a.iter().tee();
t1.next();
t1.next();
t2.next();
exact_size(t1) && exact_size(t2)
}
#[quickcheck]
fn size_tee_2(a: Vec<u8>) -> bool {
let (mut t1, mut t2) = a.iter().dedup().tee();
t1.next();
t1.next();
t2.next();
correct_size_hint(t1) && correct_size_hint(t2)
}
#[quickcheck]
fn size_mend_slices(a: Vec<u8>, splits: Vec<usize>) -> bool {
let slice_iter = splits.into_iter().map(|ix|
if ix < a.len() {
&a[ix..(ix + 1)]
} else {
&a[0..0]
}
).mend_slices();
correct_size_hint(slice_iter)
}
#[quickcheck]
fn size_take_while_ref(a: Vec<u8>, stop: u8) -> bool {
correct_size_hint(a.iter().take_while_ref(|x| **x!= stop))
}
#[quickcheck]
fn equal_partition(mut a: Vec<i32>) -> bool {
let mut ap = a.clone();
let split_index = itertools::partition(&mut ap, |x| *x >= 0);
let parted = (0..split_index).all(|i| ap[i] >= 0) &&
(split_index..a.len()).all(|i| ap[i] < 0);
a.sort();
ap.sort();
parted && (a == ap)
}
#[quickcheck]
fn size_combinations(it: Iter<i16>) -> bool {
correct_size_hint(it.combinations())
}
#[quickcheck]
fn equal_combinations(mut it: Iter<i16>) -> bool {
let values = it.clone().collect_vec();
let mut cmb = it.combinations();
for i in 0..values.len() {
for j in i+1..values.len() {
let pair = (values[i], values[j]);
if pair!= cmb.next().unwrap() {
return false;
}
}
}
cmb.next() == None
}
#[quickcheck]
fn size_pad_tail(it: Iter<i8>, pad: u8) -> bool {
correct_size_hint(it.clone().pad_using(pad as usize, |_| 0)) &&
correct_size_hint(it.dropping(1).rev().pad_using(pad as usize, |_| 0))
}
#[quickcheck]
fn size_pad_tail2(it: Iter<i8>, pad: u8) -> bool {
exact_size(it.pad_using(pad as usize, |_| 0))
}
}
| equal_intersperse | identifier_name |
quick.rs | #![cfg_attr(feature = "qc", feature(plugin, custom_attribute))]
#![cfg_attr(feature="qc", plugin(quickcheck_macros))]
#![allow(dead_code)]
//! The purpose of these tests is to cover corner cases of iterators
//! and adaptors.
//!
//! In particular we test the tedious size_hint and exact size correctness.
#[macro_use]
extern crate itertools;
#[cfg(feature = "qc")]
extern crate quickcheck;
#[cfg(feature = "qc")]
mod quicktests {
use std::default::Default;
use quickcheck as qc;
use std::ops::Range;
use itertools;
use itertools::Itertools;
use itertools::{
Zip,
Stride,
EitherOrBoth,
};
/// Our base iterator that we can impl Arbitrary for
///
/// NOTE: Iter is tricky and is not fused, to help catch bugs.
/// At the end it will return None once, then return Some(0),
/// then return None again.
#[derive(Clone, Debug)]
struct Iter<T>(Range<T>, i32); // with fuse/done flag
impl<T> Iter<T>
{
fn new(it: Range<T>) -> Self
{
Iter(it, 0)
}
}
impl<T> Iterator for Iter<T> where Range<T>: Iterator,
<Range<T> as Iterator>::Item: Default,
{
type Item = <Range<T> as Iterator>::Item;
fn next(&mut self) -> Option<Self::Item>
{
let elt = self.0.next();
if elt.is_none() {
self.1 += 1;
// check fuse flag
if self.1 == 2 {
return Some(Default::default())
}
}
elt
}
fn size_hint(&self) -> (usize, Option<usize>)
{
self.0.size_hint()
}
}
impl<T> DoubleEndedIterator for Iter<T> where Range<T>: DoubleEndedIterator,
<Range<T> as Iterator>::Item: Default,
{
fn next_back(&mut self) -> Option<Self::Item> { self.0.next_back() }
}
impl<T> ExactSizeIterator for Iter<T> where Range<T>: ExactSizeIterator,
<Range<T> as Iterator>::Item: Default,
{ }
impl<T> qc::Arbitrary for Iter<T> where T: qc::Arbitrary
{
fn arbitrary<G: qc::Gen>(g: &mut G) -> Self
{
Iter::new(T::arbitrary(g)..T::arbitrary(g))
}
fn shrink(&self) -> Box<Iterator<Item=Iter<T>>>
{
let r = self.0.clone();
Box::new(
r.start.shrink().flat_map(move |x| {
r.end.shrink().map(move |y| (x.clone(), y))
})
.map(|(a, b)| Iter::new(a..b))
)
}
}
fn correct_size_hint_fast<I: Iterator>(it: I) -> bool {
let (low, hi) = it.size_hint();
let cnt = it.count();
cnt >= low &&
(hi.is_none() || hi.unwrap() >= cnt)
}
fn correct_size_hint<I: Iterator>(mut it: I) -> bool {
// record size hint at each iteration
let initial_hint = it.size_hint();
let mut hints = Vec::with_capacity(initial_hint.0 + 1);
hints.push(initial_hint);
while let Some(_) = it.next() {
hints.push(it.size_hint())
}
let mut true_count = hints.len(); // start off +1 too much
// check all the size hints
for &(low, hi) in &hints {
true_count -= 1;
if low > true_count ||
(hi.is_some() && hi.unwrap() < true_count)
{
println!("True size: {:?}, size hint: {:?}", true_count, (low, hi));
//println!("All hints: {:?}", hints);
return false
}
}
true
}
fn exact_size<I: ExactSizeIterator>(mut it: I) -> bool {
// check every iteration
let (mut low, mut hi) = it.size_hint();
if Some(low)!= hi { return false; }
while let Some(_) = it.next() {
let (xlow, xhi) = it.size_hint();
if low!= xlow + 1 { return false; }
low = xlow;
hi = xhi;
if Some(low)!= hi { return false; }
}
let (low, hi) = it.size_hint();
low == 0 && hi == Some(0)
}
/*
* NOTE: Range<i8> is broken!
* (all signed ranges are)
#[quickcheck]
fn size_range_i8(a: Iter<i8>) -> bool {
exact_size(a)
}
#[quickcheck]
fn size_range_i16(a: Iter<i16>) -> bool {
exact_size(a)
}
#[quickcheck]
fn size_range_u8(a: Iter<u8>) -> bool {
exact_size(a)
}
*/
#[quickcheck]
fn size_stride(data: Vec<u8>, mut stride: isize) -> bool {
if stride == 0 {
stride += 1; // never zero
}
exact_size(Stride::from_slice(&data, stride))
}
#[quickcheck]
fn equal_stride(data: Vec<u8>, mut stride: i8) -> bool {
if stride == 0 {
// never zero
stride += 1;
}
if stride > 0 {
itertools::equal(Stride::from_slice(&data, stride as isize),
data.iter().step(stride as usize))
} else |
}
#[quickcheck]
fn size_product(a: Iter<u16>, b: Iter<u16>) -> bool {
correct_size_hint(a.cartesian_product(b))
}
#[quickcheck]
fn size_product3(a: Iter<u16>, b: Iter<u16>, c: Iter<u16>) -> bool {
correct_size_hint(iproduct!(a, b, c))
}
#[quickcheck]
fn size_step(a: Iter<i16>, mut s: usize) -> bool {
if s == 0 {
s += 1; // never zero
}
let filt = a.clone().dedup();
correct_size_hint(filt.step(s)) &&
exact_size(a.step(s))
}
#[quickcheck]
fn size_multipeek(a: Iter<u16>, s: u8) -> bool {
let mut it = a.multipeek();
// peek a few times
for _ in 0..s {
it.peek();
}
exact_size(it)
}
#[quickcheck]
fn equal_merge(a: Vec<i16>, b: Vec<i16>) -> bool {
let mut sa = a.clone();
let mut sb = b.clone();
sa.sort();
sb.sort();
let mut merged = sa.clone();
merged.extend(sb.iter().cloned());
merged.sort();
itertools::equal(&merged, sa.iter().merge(&sb))
}
#[quickcheck]
fn size_merge(a: Iter<u16>, b: Iter<u16>) -> bool {
correct_size_hint(a.merge(b))
}
#[quickcheck]
fn size_zip(a: Iter<i16>, b: Iter<i16>, c: Iter<i16>) -> bool {
let filt = a.clone().dedup();
correct_size_hint(Zip::new((filt, b.clone(), c.clone()))) &&
exact_size(Zip::new((a, b, c)))
}
#[quickcheck]
fn size_zip_rc(a: Iter<i16>, b: Iter<i16>) -> bool {
let rc = a.clone().into_rc();
correct_size_hint(Zip::new((&rc, &rc, b)))
}
#[quickcheck]
fn size_zip_longest(a: Iter<i16>, b: Iter<i16>) -> bool {
let filt = a.clone().dedup();
let filt2 = b.clone().dedup();
correct_size_hint(filt.zip_longest(b.clone())) &&
correct_size_hint(a.clone().zip_longest(filt2)) &&
exact_size(a.zip_longest(b))
}
#[quickcheck]
fn size_2_zip_longest(a: Iter<i16>, b: Iter<i16>) -> bool {
let it = a.clone().zip_longest(b.clone());
let jt = a.clone().zip_longest(b.clone());
itertools::equal(a.clone(),
it.filter_map(|elt| match elt {
EitherOrBoth::Both(x, _) => Some(x),
EitherOrBoth::Left(x) => Some(x),
_ => None,
}
))
&&
itertools::equal(b.clone(),
jt.filter_map(|elt| match elt {
EitherOrBoth::Both(_, y) => Some(y),
EitherOrBoth::Right(y) => Some(y),
_ => None,
}
))
}
fn equal_islice(a: Vec<i16>, x: usize, y: usize) -> bool {
if x > y || y > a.len() { return true; }
let slc = &a[x..y];
itertools::equal(a.iter().slice(x..y), slc)
}
fn size_islice(a: Iter<i16>, x: usize, y: usize) -> bool {
correct_size_hint(a.clone().dedup().slice(x..y)) &&
exact_size(a.clone().slice(x..y))
}
#[quickcheck]
fn size_interleave(a: Iter<i16>, b: Iter<i16>) -> bool {
correct_size_hint(a.interleave(b))
}
#[quickcheck]
fn size_intersperse(a: Iter<i16>, x: i16) -> bool {
correct_size_hint(a.intersperse(x))
}
#[quickcheck]
fn equal_intersperse(a: Vec<i32>, x: i32) -> bool {
let mut inter = false;
let mut i = 0;
for elt in a.iter().cloned().intersperse(x) {
if inter {
if elt!= x { return false }
} else {
if elt!= a[i] { return false }
i += 1;
}
inter =!inter;
}
true
}
#[quickcheck]
fn equal_dedup(a: Vec<i32>) -> bool {
let mut b = a.clone();
b.dedup();
itertools::equal(&b, a.iter().dedup())
}
#[quickcheck]
fn size_dedup(a: Vec<i32>) -> bool {
correct_size_hint(a.iter().dedup())
}
#[quickcheck]
fn size_group_by(a: Vec<i8>) -> bool {
correct_size_hint(a.iter().group_by(|x| x.abs()))
}
#[quickcheck]
fn size_linspace(a: f32, b: f32, n: usize) -> bool {
let it = itertools::linspace(a, b, n);
it.len() == n &&
exact_size(it)
}
#[quickcheck]
fn equal_repeatn(n: usize, x: i32) -> bool {
let it = itertools::RepeatN::new(x, n);
exact_size(it)
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted(a: Vec<u8>, b: Vec<u8>) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter())))
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted3(a: Vec<u8>, b: Vec<u8>, c: Vec<u8>) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter(), c.iter())))
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn equal_ziptrusted_mix(a: Vec<u8>, b: Vec<()>, x: u8, y: u8) -> bool {
let it = itertools::ZipTrusted::new((a.iter(), b.iter(), x..y));
let jt = Zip::new((a.iter(), b.iter(), x..y));
itertools::equal(it, jt)
}
#[cfg(feature = "unstable")]
#[quickcheck]
fn size_ziptrusted_mix(a: Vec<u8>, b: Vec<()>, x: u8, y: u8) -> bool {
exact_size(itertools::ZipTrusted::new((a.iter(), b.iter(), x..y)))
}
#[quickcheck]
fn size_put_back(a: Vec<u8>, x: Option<u8>) -> bool {
let mut it = itertools::PutBack::new(a.into_iter());
match x {
Some(t) => it.put_back(t),
None => {}
}
correct_size_hint(it)
}
#[quickcheck]
fn size_put_backn(a: Vec<u8>, b: Vec<u8>) -> bool {
let mut it = itertools::PutBackN::new(a.into_iter());
for elt in b {
it.put_back(elt)
}
correct_size_hint(it)
}
#[quickcheck]
fn size_tee(a: Vec<u8>) -> bool {
let (mut t1, mut t2) = a.iter().tee();
t1.next();
t1.next();
t2.next();
exact_size(t1) && exact_size(t2)
}
#[quickcheck]
fn size_tee_2(a: Vec<u8>) -> bool {
let (mut t1, mut t2) = a.iter().dedup().tee();
t1.next();
t1.next();
t2.next();
correct_size_hint(t1) && correct_size_hint(t2)
}
#[quickcheck]
fn size_mend_slices(a: Vec<u8>, splits: Vec<usize>) -> bool {
let slice_iter = splits.into_iter().map(|ix|
if ix < a.len() {
&a[ix..(ix + 1)]
} else {
&a[0..0]
}
).mend_slices();
correct_size_hint(slice_iter)
}
#[quickcheck]
fn size_take_while_ref(a: Vec<u8>, stop: u8) -> bool {
correct_size_hint(a.iter().take_while_ref(|x| **x!= stop))
}
#[quickcheck]
fn equal_partition(mut a: Vec<i32>) -> bool {
let mut ap = a.clone();
let split_index = itertools::partition(&mut ap, |x| *x >= 0);
let parted = (0..split_index).all(|i| ap[i] >= 0) &&
(split_index..a.len()).all(|i| ap[i] < 0);
a.sort();
ap.sort();
parted && (a == ap)
}
#[quickcheck]
fn size_combinations(it: Iter<i16>) -> bool {
correct_size_hint(it.combinations())
}
#[quickcheck]
fn equal_combinations(mut it: Iter<i16>) -> bool {
let values = it.clone().collect_vec();
let mut cmb = it.combinations();
for i in 0..values.len() {
for j in i+1..values.len() {
let pair = (values[i], values[j]);
if pair!= cmb.next().unwrap() {
return false;
}
}
}
cmb.next() == None
}
#[quickcheck]
fn size_pad_tail(it: Iter<i8>, pad: u8) -> bool {
correct_size_hint(it.clone().pad_using(pad as usize, |_| 0)) &&
correct_size_hint(it.dropping(1).rev().pad_using(pad as usize, |_| 0))
}
#[quickcheck]
fn size_pad_tail2(it: Iter<i8>, pad: u8) -> bool {
exact_size(it.pad_using(pad as usize, |_| 0))
}
}
| {
itertools::equal(Stride::from_slice(&data, stride as isize),
data.iter().rev().step(-stride as usize))
} | conditional_block |
http_test.rs | #[cfg(all(feature = "metrics", feature = "rt-tokio"))]
mod test {
use http::header::{HeaderValue, AUTHORIZATION, USER_AGENT};
use hyper::{
body,
service::{make_service_fn, service_fn},
Body, Method, Request, Response, Server,
};
use opentelemetry::{global, Key, KeyValue};
use std::net::SocketAddr;
use std::time::Duration;
#[tokio::test(flavor = "multi_thread")]
async fn integration_test() | Ok::<_, hyper::Error>(
Response::builder()
.status(http::StatusCode::METHOD_NOT_ALLOWED)
.body(Body::empty())
.unwrap(),
)
}
}
}))
}
});
let server = Server::bind(&addr).http1_only(true).serve(make_svc);
addr_tx.send(server.local_addr()).unwrap();
println!(
"Starting http server on port {}",
server.local_addr().port()
);
if let Err(err) = server
.with_graceful_shutdown(async move {
let _ = shutdown_rx.await;
})
.await
{
panic!("failed to start http server, {:?}", err);
}
});
let addr = addr_rx.await.unwrap();
let _meter = opentelemetry_dynatrace::new_pipeline()
.metrics(tokio::spawn, move |_: Duration| {
let mut tick_rx = tick_rx.clone();
futures::stream::once(async move {
let _ = tick_rx.changed().await.is_ok();
})
})
.with_exporter(opentelemetry_dynatrace::new_exporter().with_export_config(
opentelemetry_dynatrace::ExportConfig {
endpoint: Some(format!("http://{}/test/a/b/c", addr)),
token: Some("1234567890".to_string()),
},
))
.with_prefix("example".to_string())
.with_period(Duration::from_millis(100))
.with_timestamp(false)
.build()
.unwrap();
let (req, _) = tokio::join!(req_rx.recv(), async move {
let meter = global::meter("ex.com/basic");
let recorder = meter.u64_counter("test1").init();
recorder.add(
90,
&[
KeyValue::new("A", "test1"),
KeyValue::new("B", "test2"),
KeyValue::new("C", "test3"),
],
);
let recorder = meter.f64_counter("test2").init();
recorder.add(1e10 + 0.123, &[KeyValue::new("foo", "bar")]);
let recorder = meter.i64_histogram("test3").init();
recorder.record(-999, &[Key::new("foo").i64(-123)]);
let _ = tick_tx.send(1);
});
assert!(req.is_some());
let req = req.unwrap();
assert_eq!(req.method(), Method::POST);
assert_eq!(req.uri().path(), "/test/a/b/c");
assert_eq!(
req.headers().get(USER_AGENT),
Some(&HeaderValue::from_static("opentelemetry-metric-rust")),
);
assert_eq!(
req.headers().get(AUTHORIZATION),
Some(&HeaderValue::from_str("Api-Token 1234567890").unwrap()),
);
let bytes = body::to_bytes(req.into_body())
.await
.expect("http server body not readable");
let body = String::from_utf8(bytes.to_vec()).expect("response is not valid utf-8");
// We're done with this test request, so shut down the server.
shutdown_tx
.send(())
.expect("sender error while shutting down http server");
// Reap the task handle to ensure that the server did indeed shut down.
let _ = server_handle.await.expect("http server yielded an error");
let mut metric_lines: Vec<&str> = body.lines().collect();
metric_lines.sort_unstable();
let mut iter = metric_lines.iter();
assert_eq!(
Some(&"example.test1,a=test1,b=test2,c=test3,dt.metrics.source=opentelemetry gauge,90"),
iter.next(),
);
assert_eq!(
Some(&"example.test2,dt.metrics.source=opentelemetry,foo=bar gauge,10000000000.123"),
iter.next(),
);
assert_eq!(
Some(&"example.test3,dt.metrics.source=opentelemetry,foo=-123 gauge,-999"),
iter.next(),
);
assert_eq!(iter.next(), None);
}
}
| {
let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();
let (req_tx, mut req_rx) = tokio::sync::mpsc::channel(1);
let (tick_tx, tick_rx) = tokio::sync::watch::channel(0);
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
let addr: SocketAddr = "[::1]:0".parse().unwrap();
let server_handle = tokio::spawn(async move {
let make_svc = make_service_fn(move |_| {
let req_tx = req_tx.clone();
async move {
Ok::<_, hyper::Error>(service_fn(move |req: Request<Body>| {
let req_tx = req_tx.clone();
async move {
if req.method() == Method::POST && req.uri().path() == "/test/a/b/c" {
req_tx.send(req).await.unwrap();
Ok::<_, hyper::Error>(Response::new(Body::empty()))
} else {
req_tx.send(req).await.unwrap(); | identifier_body |
http_test.rs | #[cfg(all(feature = "metrics", feature = "rt-tokio"))]
mod test {
use http::header::{HeaderValue, AUTHORIZATION, USER_AGENT};
use hyper::{
body,
service::{make_service_fn, service_fn},
Body, Method, Request, Response, Server,
};
use opentelemetry::{global, Key, KeyValue};
use std::net::SocketAddr;
use std::time::Duration;
#[tokio::test(flavor = "multi_thread")]
async fn | () {
let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();
let (req_tx, mut req_rx) = tokio::sync::mpsc::channel(1);
let (tick_tx, tick_rx) = tokio::sync::watch::channel(0);
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
let addr: SocketAddr = "[::1]:0".parse().unwrap();
let server_handle = tokio::spawn(async move {
let make_svc = make_service_fn(move |_| {
let req_tx = req_tx.clone();
async move {
Ok::<_, hyper::Error>(service_fn(move |req: Request<Body>| {
let req_tx = req_tx.clone();
async move {
if req.method() == Method::POST && req.uri().path() == "/test/a/b/c" {
req_tx.send(req).await.unwrap();
Ok::<_, hyper::Error>(Response::new(Body::empty()))
} else {
req_tx.send(req).await.unwrap();
Ok::<_, hyper::Error>(
Response::builder()
.status(http::StatusCode::METHOD_NOT_ALLOWED)
.body(Body::empty())
.unwrap(),
)
}
}
}))
}
});
let server = Server::bind(&addr).http1_only(true).serve(make_svc);
addr_tx.send(server.local_addr()).unwrap();
println!(
"Starting http server on port {}",
server.local_addr().port()
);
if let Err(err) = server
.with_graceful_shutdown(async move {
let _ = shutdown_rx.await;
})
.await
{
panic!("failed to start http server, {:?}", err);
}
});
let addr = addr_rx.await.unwrap();
let _meter = opentelemetry_dynatrace::new_pipeline()
.metrics(tokio::spawn, move |_: Duration| {
let mut tick_rx = tick_rx.clone();
futures::stream::once(async move {
let _ = tick_rx.changed().await.is_ok();
})
})
.with_exporter(opentelemetry_dynatrace::new_exporter().with_export_config(
opentelemetry_dynatrace::ExportConfig {
endpoint: Some(format!("http://{}/test/a/b/c", addr)),
token: Some("1234567890".to_string()),
},
))
.with_prefix("example".to_string())
.with_period(Duration::from_millis(100))
.with_timestamp(false)
.build()
.unwrap();
let (req, _) = tokio::join!(req_rx.recv(), async move {
let meter = global::meter("ex.com/basic");
let recorder = meter.u64_counter("test1").init();
recorder.add(
90,
&[
KeyValue::new("A", "test1"),
KeyValue::new("B", "test2"),
KeyValue::new("C", "test3"),
],
);
let recorder = meter.f64_counter("test2").init();
recorder.add(1e10 + 0.123, &[KeyValue::new("foo", "bar")]);
let recorder = meter.i64_histogram("test3").init();
recorder.record(-999, &[Key::new("foo").i64(-123)]);
let _ = tick_tx.send(1);
});
assert!(req.is_some());
let req = req.unwrap();
assert_eq!(req.method(), Method::POST);
assert_eq!(req.uri().path(), "/test/a/b/c");
assert_eq!(
req.headers().get(USER_AGENT),
Some(&HeaderValue::from_static("opentelemetry-metric-rust")),
);
assert_eq!(
req.headers().get(AUTHORIZATION),
Some(&HeaderValue::from_str("Api-Token 1234567890").unwrap()),
);
let bytes = body::to_bytes(req.into_body())
.await
.expect("http server body not readable");
let body = String::from_utf8(bytes.to_vec()).expect("response is not valid utf-8");
// We're done with this test request, so shut down the server.
shutdown_tx
.send(())
.expect("sender error while shutting down http server");
// Reap the task handle to ensure that the server did indeed shut down.
let _ = server_handle.await.expect("http server yielded an error");
let mut metric_lines: Vec<&str> = body.lines().collect();
metric_lines.sort_unstable();
let mut iter = metric_lines.iter();
assert_eq!(
Some(&"example.test1,a=test1,b=test2,c=test3,dt.metrics.source=opentelemetry gauge,90"),
iter.next(),
);
assert_eq!(
Some(&"example.test2,dt.metrics.source=opentelemetry,foo=bar gauge,10000000000.123"),
iter.next(),
);
assert_eq!(
Some(&"example.test3,dt.metrics.source=opentelemetry,foo=-123 gauge,-999"),
iter.next(),
);
assert_eq!(iter.next(), None);
}
}
| integration_test | identifier_name |
http_test.rs | #[cfg(all(feature = "metrics", feature = "rt-tokio"))]
mod test {
use http::header::{HeaderValue, AUTHORIZATION, USER_AGENT};
use hyper::{
body,
service::{make_service_fn, service_fn},
Body, Method, Request, Response, Server,
};
use opentelemetry::{global, Key, KeyValue};
use std::net::SocketAddr;
use std::time::Duration;
#[tokio::test(flavor = "multi_thread")]
async fn integration_test() {
let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();
let (req_tx, mut req_rx) = tokio::sync::mpsc::channel(1);
let (tick_tx, tick_rx) = tokio::sync::watch::channel(0);
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
let addr: SocketAddr = "[::1]:0".parse().unwrap();
let server_handle = tokio::spawn(async move {
let make_svc = make_service_fn(move |_| {
let req_tx = req_tx.clone();
async move {
Ok::<_, hyper::Error>(service_fn(move |req: Request<Body>| {
let req_tx = req_tx.clone();
async move {
if req.method() == Method::POST && req.uri().path() == "/test/a/b/c" {
req_tx.send(req).await.unwrap();
Ok::<_, hyper::Error>(Response::new(Body::empty()))
} else |
}
}))
}
});
let server = Server::bind(&addr).http1_only(true).serve(make_svc);
addr_tx.send(server.local_addr()).unwrap();
println!(
"Starting http server on port {}",
server.local_addr().port()
);
if let Err(err) = server
.with_graceful_shutdown(async move {
let _ = shutdown_rx.await;
})
.await
{
panic!("failed to start http server, {:?}", err);
}
});
let addr = addr_rx.await.unwrap();
let _meter = opentelemetry_dynatrace::new_pipeline()
.metrics(tokio::spawn, move |_: Duration| {
let mut tick_rx = tick_rx.clone();
futures::stream::once(async move {
let _ = tick_rx.changed().await.is_ok();
})
})
.with_exporter(opentelemetry_dynatrace::new_exporter().with_export_config(
opentelemetry_dynatrace::ExportConfig {
endpoint: Some(format!("http://{}/test/a/b/c", addr)),
token: Some("1234567890".to_string()),
},
))
.with_prefix("example".to_string())
.with_period(Duration::from_millis(100))
.with_timestamp(false)
.build()
.unwrap();
let (req, _) = tokio::join!(req_rx.recv(), async move {
let meter = global::meter("ex.com/basic");
let recorder = meter.u64_counter("test1").init();
recorder.add(
90,
&[
KeyValue::new("A", "test1"),
KeyValue::new("B", "test2"),
KeyValue::new("C", "test3"),
],
);
let recorder = meter.f64_counter("test2").init();
recorder.add(1e10 + 0.123, &[KeyValue::new("foo", "bar")]);
let recorder = meter.i64_histogram("test3").init();
recorder.record(-999, &[Key::new("foo").i64(-123)]);
let _ = tick_tx.send(1);
});
assert!(req.is_some());
let req = req.unwrap();
assert_eq!(req.method(), Method::POST);
assert_eq!(req.uri().path(), "/test/a/b/c");
assert_eq!(
req.headers().get(USER_AGENT),
Some(&HeaderValue::from_static("opentelemetry-metric-rust")),
);
assert_eq!(
req.headers().get(AUTHORIZATION),
Some(&HeaderValue::from_str("Api-Token 1234567890").unwrap()),
);
let bytes = body::to_bytes(req.into_body())
.await
.expect("http server body not readable");
let body = String::from_utf8(bytes.to_vec()).expect("response is not valid utf-8");
// We're done with this test request, so shut down the server.
shutdown_tx
.send(())
.expect("sender error while shutting down http server");
// Reap the task handle to ensure that the server did indeed shut down.
let _ = server_handle.await.expect("http server yielded an error");
let mut metric_lines: Vec<&str> = body.lines().collect();
metric_lines.sort_unstable();
let mut iter = metric_lines.iter();
assert_eq!(
Some(&"example.test1,a=test1,b=test2,c=test3,dt.metrics.source=opentelemetry gauge,90"),
iter.next(),
);
assert_eq!(
Some(&"example.test2,dt.metrics.source=opentelemetry,foo=bar gauge,10000000000.123"),
iter.next(),
);
assert_eq!(
Some(&"example.test3,dt.metrics.source=opentelemetry,foo=-123 gauge,-999"),
iter.next(),
);
assert_eq!(iter.next(), None);
}
}
| {
req_tx.send(req).await.unwrap();
Ok::<_, hyper::Error>(
Response::builder()
.status(http::StatusCode::METHOD_NOT_ALLOWED)
.body(Body::empty())
.unwrap(),
)
} | conditional_block |
http_test.rs | #[cfg(all(feature = "metrics", feature = "rt-tokio"))]
mod test {
use http::header::{HeaderValue, AUTHORIZATION, USER_AGENT};
use hyper::{
body,
service::{make_service_fn, service_fn},
Body, Method, Request, Response, Server,
};
use opentelemetry::{global, Key, KeyValue};
use std::net::SocketAddr;
use std::time::Duration;
#[tokio::test(flavor = "multi_thread")]
async fn integration_test() {
let (addr_tx, addr_rx) = tokio::sync::oneshot::channel();
let (req_tx, mut req_rx) = tokio::sync::mpsc::channel(1);
let (tick_tx, tick_rx) = tokio::sync::watch::channel(0);
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
let addr: SocketAddr = "[::1]:0".parse().unwrap();
let server_handle = tokio::spawn(async move {
let make_svc = make_service_fn(move |_| {
let req_tx = req_tx.clone();
async move {
Ok::<_, hyper::Error>(service_fn(move |req: Request<Body>| {
let req_tx = req_tx.clone();
async move {
if req.method() == Method::POST && req.uri().path() == "/test/a/b/c" {
req_tx.send(req).await.unwrap();
Ok::<_, hyper::Error>(Response::new(Body::empty()))
} else {
req_tx.send(req).await.unwrap();
Ok::<_, hyper::Error>( | .status(http::StatusCode::METHOD_NOT_ALLOWED)
.body(Body::empty())
.unwrap(),
)
}
}
}))
}
});
let server = Server::bind(&addr).http1_only(true).serve(make_svc);
addr_tx.send(server.local_addr()).unwrap();
println!(
"Starting http server on port {}",
server.local_addr().port()
);
if let Err(err) = server
.with_graceful_shutdown(async move {
let _ = shutdown_rx.await;
})
.await
{
panic!("failed to start http server, {:?}", err);
}
});
let addr = addr_rx.await.unwrap();
let _meter = opentelemetry_dynatrace::new_pipeline()
.metrics(tokio::spawn, move |_: Duration| {
let mut tick_rx = tick_rx.clone();
futures::stream::once(async move {
let _ = tick_rx.changed().await.is_ok();
})
})
.with_exporter(opentelemetry_dynatrace::new_exporter().with_export_config(
opentelemetry_dynatrace::ExportConfig {
endpoint: Some(format!("http://{}/test/a/b/c", addr)),
token: Some("1234567890".to_string()),
},
))
.with_prefix("example".to_string())
.with_period(Duration::from_millis(100))
.with_timestamp(false)
.build()
.unwrap();
let (req, _) = tokio::join!(req_rx.recv(), async move {
let meter = global::meter("ex.com/basic");
let recorder = meter.u64_counter("test1").init();
recorder.add(
90,
&[
KeyValue::new("A", "test1"),
KeyValue::new("B", "test2"),
KeyValue::new("C", "test3"),
],
);
let recorder = meter.f64_counter("test2").init();
recorder.add(1e10 + 0.123, &[KeyValue::new("foo", "bar")]);
let recorder = meter.i64_histogram("test3").init();
recorder.record(-999, &[Key::new("foo").i64(-123)]);
let _ = tick_tx.send(1);
});
assert!(req.is_some());
let req = req.unwrap();
assert_eq!(req.method(), Method::POST);
assert_eq!(req.uri().path(), "/test/a/b/c");
assert_eq!(
req.headers().get(USER_AGENT),
Some(&HeaderValue::from_static("opentelemetry-metric-rust")),
);
assert_eq!(
req.headers().get(AUTHORIZATION),
Some(&HeaderValue::from_str("Api-Token 1234567890").unwrap()),
);
let bytes = body::to_bytes(req.into_body())
.await
.expect("http server body not readable");
let body = String::from_utf8(bytes.to_vec()).expect("response is not valid utf-8");
// We're done with this test request, so shut down the server.
shutdown_tx
.send(())
.expect("sender error while shutting down http server");
// Reap the task handle to ensure that the server did indeed shut down.
let _ = server_handle.await.expect("http server yielded an error");
let mut metric_lines: Vec<&str> = body.lines().collect();
metric_lines.sort_unstable();
let mut iter = metric_lines.iter();
assert_eq!(
Some(&"example.test1,a=test1,b=test2,c=test3,dt.metrics.source=opentelemetry gauge,90"),
iter.next(),
);
assert_eq!(
Some(&"example.test2,dt.metrics.source=opentelemetry,foo=bar gauge,10000000000.123"),
iter.next(),
);
assert_eq!(
Some(&"example.test3,dt.metrics.source=opentelemetry,foo=-123 gauge,-999"),
iter.next(),
);
assert_eq!(iter.next(), None);
}
} | Response::builder() | random_line_split |
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromScriptMsg};
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods;
use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding;
use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::HTMLCanvasElementMethods;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes;
use dom::bindings::codegen::UnionTypes::CanvasRenderingContext2DOrWebGLRenderingContext;
use dom::bindings::conversions::ConversionResult;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{HeapGCValue, JS, LayoutJS, Root};
use dom::bindings::num::Finite;
use dom::bindings::str::DOMString;
use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers};
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::globalscope::GlobalScope;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::webglrenderingcontext::{LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext};
use euclid::size::Size2D;
use html5ever_atoms::LocalName;
use image::ColorType;
use image::png::PNGEncoder;
use ipc_channel::ipc::{self, IpcSender};
use js::error::throw_type_error;
use js::jsapi::{HandleValue, JSContext};
use offscreen_gl_context::GLContextAttributes;
use rustc_serialize::base64::{STANDARD, ToBase64};
use script_layout_interface::HTMLCanvasData;
use std::iter::repeat;
use style::attr::AttrValue;
const DEFAULT_WIDTH: u32 = 300;
const DEFAULT_HEIGHT: u32 = 150;
#[must_root]
#[derive(JSTraceable, Clone, HeapSizeOf)]
pub enum CanvasContext {
Context2d(JS<CanvasRenderingContext2D>),
WebGL(JS<WebGLRenderingContext>),
}
impl HeapGCValue for CanvasContext {}
#[dom_struct]
pub struct HTMLCanvasElement {
htmlelement: HTMLElement,
context: DOMRefCell<Option<CanvasContext>>,
}
impl HTMLCanvasElement {
fn new_inherited(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLCanvasElement {
HTMLCanvasElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
context: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLCanvasElement> {
Node::reflect_node(box HTMLCanvasElement::new_inherited(local_name, prefix, document),
document,
HTMLCanvasElementBinding::Wrap)
}
fn recreate_contexts(&self) {
let size = self.get_size();
if let Some(ref context) = *self.context.borrow() {
match *context {
CanvasContext::Context2d(ref context) => context.set_bitmap_dimensions(size),
CanvasContext::WebGL(ref context) => context.recreate(size),
}
}
}
pub fn get_size(&self) -> Size2D<i32> {
Size2D::new(self.Width() as i32, self.Height() as i32)
}
pub fn origin_is_clean(&self) -> bool {
match *self.context.borrow() {
Some(CanvasContext::Context2d(ref context)) => context.origin_is_clean(),
_ => true,
}
}
}
pub trait LayoutHTMLCanvasElementHelpers {
fn data(&self) -> HTMLCanvasData;
}
impl LayoutHTMLCanvasElementHelpers for LayoutJS<HTMLCanvasElement> {
#[allow(unsafe_code)]
fn data(&self) -> HTMLCanvasData {
unsafe {
let canvas = &*self.unsafe_get();
let ipc_renderer = canvas.context.borrow_for_layout().as_ref().map(|context| {
match *context {
CanvasContext::Context2d(ref context) => {
context.to_layout().get_ipc_renderer()
},
CanvasContext::WebGL(ref context) => {
context.to_layout().get_ipc_renderer()
},
}
});
let width_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width"));
let height_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height"));
HTMLCanvasData {
ipc_renderer: ipc_renderer,
width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()),
height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()),
}
}
}
}
impl HTMLCanvasElement {
pub fn ipc_renderer(&self) -> Option<IpcSender<CanvasMsg>> {
self.context.borrow().as_ref().map(|context| {
match *context {
CanvasContext::Context2d(ref context) => context.ipc_renderer(),
CanvasContext::WebGL(ref context) => context.ipc_renderer(),
}
})
}
pub fn get_or_init_2d_context(&self) -> Option<Root<CanvasRenderingContext2D>> {
if self.context.borrow().is_none() {
let window = window_from_node(self);
let size = self.get_size();
let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size);
*self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref(&*context)));
}
match *self.context.borrow().as_ref().unwrap() { | _ => None,
}
}
#[allow(unsafe_code)]
pub fn get_or_init_webgl_context(&self,
cx: *mut JSContext,
attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> {
if self.context.borrow().is_none() {
let window = window_from_node(self);
let size = self.get_size();
let attrs = if let Some(webgl_attributes) = attrs {
match unsafe {
WebGLContextAttributes::new(cx, webgl_attributes) } {
Ok(ConversionResult::Success(ref attrs)) => From::from(attrs),
Ok(ConversionResult::Failure(ref error)) => {
unsafe { throw_type_error(cx, &error); }
return None;
}
_ => {
debug!("Unexpected error on conversion of WebGLContextAttributes");
return None;
}
}
} else {
GLContextAttributes::default()
};
let maybe_ctx = WebGLRenderingContext::new(window.upcast(), self, size, attrs);
*self.context.borrow_mut() = maybe_ctx.map( |ctx| CanvasContext::WebGL(JS::from_ref(&*ctx)));
}
if let Some(CanvasContext::WebGL(ref context)) = *self.context.borrow() {
Some(Root::from_ref(&*context))
} else {
None
}
}
pub fn is_valid(&self) -> bool {
self.Height()!= 0 && self.Width()!= 0
}
pub fn fetch_all_data(&self) -> Option<(Vec<u8>, Size2D<i32>)> {
let size = self.get_size();
if size.width == 0 || size.height == 0 {
return None
}
let data = if let Some(renderer) = self.ipc_renderer() {
let (sender, receiver) = ipc::channel().unwrap();
let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender));
renderer.send(msg).unwrap();
match receiver.recv().unwrap() {
Some(pixels) => pixels,
None => {
// TODO(emilio, #14109): Not sure if WebGL canvas is
// required for 2d spec, but I think it's not, if so, make
// this return a readback from the GL context.
return None;
}
}
} else {
repeat(0xffu8).take((size.height as usize) * (size.width as usize) * 4).collect()
};
Some((data, size))
}
}
impl HTMLCanvasElementMethods for HTMLCanvasElement {
// https://html.spec.whatwg.org/multipage/#dom-canvas-width
make_uint_getter!(Width, "width", DEFAULT_WIDTH);
// https://html.spec.whatwg.org/multipage/#dom-canvas-width
make_uint_setter!(SetWidth, "width", DEFAULT_WIDTH);
// https://html.spec.whatwg.org/multipage/#dom-canvas-height
make_uint_getter!(Height, "height", DEFAULT_HEIGHT);
// https://html.spec.whatwg.org/multipage/#dom-canvas-height
make_uint_setter!(SetHeight, "height", DEFAULT_HEIGHT);
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext
unsafe fn GetContext(&self,
cx: *mut JSContext,
id: DOMString,
attributes: Vec<HandleValue>)
-> Option<CanvasRenderingContext2DOrWebGLRenderingContext> {
match &*id {
"2d" => {
self.get_or_init_2d_context()
.map(CanvasRenderingContext2DOrWebGLRenderingContext::CanvasRenderingContext2D)
}
"webgl" | "experimental-webgl" => {
self.get_or_init_webgl_context(cx, attributes.get(0).cloned())
.map(CanvasRenderingContext2DOrWebGLRenderingContext::WebGLRenderingContext)
}
_ => None
}
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl
unsafe fn ToDataURL(&self,
_context: *mut JSContext,
_mime_type: Option<DOMString>,
_arguments: Vec<HandleValue>) -> Fallible<DOMString> {
// Step 1.
if let Some(CanvasContext::Context2d(ref context)) = *self.context.borrow() {
if!context.origin_is_clean() {
return Err(Error::Security);
}
}
// Step 2.
if self.Width() == 0 || self.Height() == 0 {
return Ok(DOMString::from("data:,"));
}
// Step 3.
let raw_data = match *self.context.borrow() {
Some(CanvasContext::Context2d(ref context)) => {
let image_data = try!(context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64),
Finite::wrap(self.Width() as f64),
Finite::wrap(self.Height() as f64)));
image_data.get_data_array()
}
None => {
// Each pixel is fully-transparent black.
vec![0; (self.Width() * self.Height() * 4) as usize]
}
_ => return Err(Error::NotSupported) // WebGL
};
// Only handle image/png for now.
let mime_type = "image/png";
let mut encoded = Vec::new();
{
let encoder: PNGEncoder<&mut Vec<u8>> = PNGEncoder::new(&mut encoded);
encoder.encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)).unwrap();
}
let encoded = encoded.to_base64(STANDARD);
Ok(DOMString::from(format!("data:{};base64,{}", mime_type, encoded)))
}
}
impl VirtualMethods for HTMLCanvasElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&local_name!("width") | &local_name!("height") => self.recreate_contexts(),
_ => (),
};
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
&local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes {
fn from(attrs: &'a WebGLContextAttributes) -> GLContextAttributes {
GLContextAttributes {
alpha: attrs.alpha,
depth: attrs.depth,
stencil: attrs.stencil,
antialias: attrs.antialias,
premultiplied_alpha: attrs.premultipliedAlpha,
preserve_drawing_buffer: attrs.preserveDrawingBuffer,
}
}
}
pub mod utils {
use dom::window::Window;
use ipc_channel::ipc;
use net_traits::image_cache_thread::{ImageCacheChan, ImageResponse};
use servo_url::ServoUrl;
pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse {
let image_cache = window.image_cache_thread();
let (response_chan, response_port) = ipc::channel().unwrap();
image_cache.request_image(url.into(), ImageCacheChan(response_chan), None);
let result = response_port.recv().unwrap();
result.image_response
}
} | CanvasContext::Context2d(ref context) => Some(Root::from_ref(&*context)), | random_line_split |
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromScriptMsg};
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods;
use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding;
use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::HTMLCanvasElementMethods;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes;
use dom::bindings::codegen::UnionTypes::CanvasRenderingContext2DOrWebGLRenderingContext;
use dom::bindings::conversions::ConversionResult;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{HeapGCValue, JS, LayoutJS, Root};
use dom::bindings::num::Finite;
use dom::bindings::str::DOMString;
use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers};
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::globalscope::GlobalScope;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::webglrenderingcontext::{LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext};
use euclid::size::Size2D;
use html5ever_atoms::LocalName;
use image::ColorType;
use image::png::PNGEncoder;
use ipc_channel::ipc::{self, IpcSender};
use js::error::throw_type_error;
use js::jsapi::{HandleValue, JSContext};
use offscreen_gl_context::GLContextAttributes;
use rustc_serialize::base64::{STANDARD, ToBase64};
use script_layout_interface::HTMLCanvasData;
use std::iter::repeat;
use style::attr::AttrValue;
const DEFAULT_WIDTH: u32 = 300;
const DEFAULT_HEIGHT: u32 = 150;
#[must_root]
#[derive(JSTraceable, Clone, HeapSizeOf)]
pub enum CanvasContext {
Context2d(JS<CanvasRenderingContext2D>),
WebGL(JS<WebGLRenderingContext>),
}
impl HeapGCValue for CanvasContext {}
#[dom_struct]
pub struct HTMLCanvasElement {
htmlelement: HTMLElement,
context: DOMRefCell<Option<CanvasContext>>,
}
impl HTMLCanvasElement {
fn new_inherited(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLCanvasElement {
HTMLCanvasElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
context: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLCanvasElement> {
Node::reflect_node(box HTMLCanvasElement::new_inherited(local_name, prefix, document),
document,
HTMLCanvasElementBinding::Wrap)
}
fn recreate_contexts(&self) {
let size = self.get_size();
if let Some(ref context) = *self.context.borrow() {
match *context {
CanvasContext::Context2d(ref context) => context.set_bitmap_dimensions(size),
CanvasContext::WebGL(ref context) => context.recreate(size),
}
}
}
pub fn get_size(&self) -> Size2D<i32> {
Size2D::new(self.Width() as i32, self.Height() as i32)
}
pub fn origin_is_clean(&self) -> bool {
match *self.context.borrow() {
Some(CanvasContext::Context2d(ref context)) => context.origin_is_clean(),
_ => true,
}
}
}
pub trait LayoutHTMLCanvasElementHelpers {
fn data(&self) -> HTMLCanvasData;
}
impl LayoutHTMLCanvasElementHelpers for LayoutJS<HTMLCanvasElement> {
#[allow(unsafe_code)]
fn data(&self) -> HTMLCanvasData {
unsafe {
let canvas = &*self.unsafe_get();
let ipc_renderer = canvas.context.borrow_for_layout().as_ref().map(|context| {
match *context {
CanvasContext::Context2d(ref context) => {
context.to_layout().get_ipc_renderer()
},
CanvasContext::WebGL(ref context) => | ,
}
});
let width_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width"));
let height_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height"));
HTMLCanvasData {
ipc_renderer: ipc_renderer,
width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()),
height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()),
}
}
}
}
impl HTMLCanvasElement {
pub fn ipc_renderer(&self) -> Option<IpcSender<CanvasMsg>> {
self.context.borrow().as_ref().map(|context| {
match *context {
CanvasContext::Context2d(ref context) => context.ipc_renderer(),
CanvasContext::WebGL(ref context) => context.ipc_renderer(),
}
})
}
pub fn get_or_init_2d_context(&self) -> Option<Root<CanvasRenderingContext2D>> {
if self.context.borrow().is_none() {
let window = window_from_node(self);
let size = self.get_size();
let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size);
*self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref(&*context)));
}
match *self.context.borrow().as_ref().unwrap() {
CanvasContext::Context2d(ref context) => Some(Root::from_ref(&*context)),
_ => None,
}
}
#[allow(unsafe_code)]
pub fn get_or_init_webgl_context(&self,
cx: *mut JSContext,
attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> {
if self.context.borrow().is_none() {
let window = window_from_node(self);
let size = self.get_size();
let attrs = if let Some(webgl_attributes) = attrs {
match unsafe {
WebGLContextAttributes::new(cx, webgl_attributes) } {
Ok(ConversionResult::Success(ref attrs)) => From::from(attrs),
Ok(ConversionResult::Failure(ref error)) => {
unsafe { throw_type_error(cx, &error); }
return None;
}
_ => {
debug!("Unexpected error on conversion of WebGLContextAttributes");
return None;
}
}
} else {
GLContextAttributes::default()
};
let maybe_ctx = WebGLRenderingContext::new(window.upcast(), self, size, attrs);
*self.context.borrow_mut() = maybe_ctx.map( |ctx| CanvasContext::WebGL(JS::from_ref(&*ctx)));
}
if let Some(CanvasContext::WebGL(ref context)) = *self.context.borrow() {
Some(Root::from_ref(&*context))
} else {
None
}
}
pub fn is_valid(&self) -> bool {
self.Height()!= 0 && self.Width()!= 0
}
pub fn fetch_all_data(&self) -> Option<(Vec<u8>, Size2D<i32>)> {
let size = self.get_size();
if size.width == 0 || size.height == 0 {
return None
}
let data = if let Some(renderer) = self.ipc_renderer() {
let (sender, receiver) = ipc::channel().unwrap();
let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender));
renderer.send(msg).unwrap();
match receiver.recv().unwrap() {
Some(pixels) => pixels,
None => {
// TODO(emilio, #14109): Not sure if WebGL canvas is
// required for 2d spec, but I think it's not, if so, make
// this return a readback from the GL context.
return None;
}
}
} else {
repeat(0xffu8).take((size.height as usize) * (size.width as usize) * 4).collect()
};
Some((data, size))
}
}
impl HTMLCanvasElementMethods for HTMLCanvasElement {
// https://html.spec.whatwg.org/multipage/#dom-canvas-width
make_uint_getter!(Width, "width", DEFAULT_WIDTH);
// https://html.spec.whatwg.org/multipage/#dom-canvas-width
make_uint_setter!(SetWidth, "width", DEFAULT_WIDTH);
// https://html.spec.whatwg.org/multipage/#dom-canvas-height
make_uint_getter!(Height, "height", DEFAULT_HEIGHT);
// https://html.spec.whatwg.org/multipage/#dom-canvas-height
make_uint_setter!(SetHeight, "height", DEFAULT_HEIGHT);
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext
unsafe fn GetContext(&self,
cx: *mut JSContext,
id: DOMString,
attributes: Vec<HandleValue>)
-> Option<CanvasRenderingContext2DOrWebGLRenderingContext> {
match &*id {
"2d" => {
self.get_or_init_2d_context()
.map(CanvasRenderingContext2DOrWebGLRenderingContext::CanvasRenderingContext2D)
}
"webgl" | "experimental-webgl" => {
self.get_or_init_webgl_context(cx, attributes.get(0).cloned())
.map(CanvasRenderingContext2DOrWebGLRenderingContext::WebGLRenderingContext)
}
_ => None
}
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl
unsafe fn ToDataURL(&self,
_context: *mut JSContext,
_mime_type: Option<DOMString>,
_arguments: Vec<HandleValue>) -> Fallible<DOMString> {
// Step 1.
if let Some(CanvasContext::Context2d(ref context)) = *self.context.borrow() {
if!context.origin_is_clean() {
return Err(Error::Security);
}
}
// Step 2.
if self.Width() == 0 || self.Height() == 0 {
return Ok(DOMString::from("data:,"));
}
// Step 3.
let raw_data = match *self.context.borrow() {
Some(CanvasContext::Context2d(ref context)) => {
let image_data = try!(context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64),
Finite::wrap(self.Width() as f64),
Finite::wrap(self.Height() as f64)));
image_data.get_data_array()
}
None => {
// Each pixel is fully-transparent black.
vec![0; (self.Width() * self.Height() * 4) as usize]
}
_ => return Err(Error::NotSupported) // WebGL
};
// Only handle image/png for now.
let mime_type = "image/png";
let mut encoded = Vec::new();
{
let encoder: PNGEncoder<&mut Vec<u8>> = PNGEncoder::new(&mut encoded);
encoder.encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)).unwrap();
}
let encoded = encoded.to_base64(STANDARD);
Ok(DOMString::from(format!("data:{};base64,{}", mime_type, encoded)))
}
}
impl VirtualMethods for HTMLCanvasElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&local_name!("width") | &local_name!("height") => self.recreate_contexts(),
_ => (),
};
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
&local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes {
fn from(attrs: &'a WebGLContextAttributes) -> GLContextAttributes {
GLContextAttributes {
alpha: attrs.alpha,
depth: attrs.depth,
stencil: attrs.stencil,
antialias: attrs.antialias,
premultiplied_alpha: attrs.premultipliedAlpha,
preserve_drawing_buffer: attrs.preserveDrawingBuffer,
}
}
}
pub mod utils {
use dom::window::Window;
use ipc_channel::ipc;
use net_traits::image_cache_thread::{ImageCacheChan, ImageResponse};
use servo_url::ServoUrl;
pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse {
let image_cache = window.image_cache_thread();
let (response_chan, response_port) = ipc::channel().unwrap();
image_cache.request_image(url.into(), ImageCacheChan(response_chan), None);
let result = response_port.recv().unwrap();
result.image_response
}
}
| {
context.to_layout().get_ipc_renderer()
} | conditional_block |
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromScriptMsg};
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods;
use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding;
use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::HTMLCanvasElementMethods;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes;
use dom::bindings::codegen::UnionTypes::CanvasRenderingContext2DOrWebGLRenderingContext;
use dom::bindings::conversions::ConversionResult;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{HeapGCValue, JS, LayoutJS, Root};
use dom::bindings::num::Finite;
use dom::bindings::str::DOMString;
use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers};
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::globalscope::GlobalScope;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::webglrenderingcontext::{LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext};
use euclid::size::Size2D;
use html5ever_atoms::LocalName;
use image::ColorType;
use image::png::PNGEncoder;
use ipc_channel::ipc::{self, IpcSender};
use js::error::throw_type_error;
use js::jsapi::{HandleValue, JSContext};
use offscreen_gl_context::GLContextAttributes;
use rustc_serialize::base64::{STANDARD, ToBase64};
use script_layout_interface::HTMLCanvasData;
use std::iter::repeat;
use style::attr::AttrValue;
const DEFAULT_WIDTH: u32 = 300;
const DEFAULT_HEIGHT: u32 = 150;
#[must_root]
#[derive(JSTraceable, Clone, HeapSizeOf)]
pub enum CanvasContext {
Context2d(JS<CanvasRenderingContext2D>),
WebGL(JS<WebGLRenderingContext>),
}
impl HeapGCValue for CanvasContext {}
#[dom_struct]
pub struct HTMLCanvasElement {
htmlelement: HTMLElement,
context: DOMRefCell<Option<CanvasContext>>,
}
impl HTMLCanvasElement {
fn new_inherited(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLCanvasElement {
HTMLCanvasElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
context: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLCanvasElement> {
Node::reflect_node(box HTMLCanvasElement::new_inherited(local_name, prefix, document),
document,
HTMLCanvasElementBinding::Wrap)
}
fn recreate_contexts(&self) {
let size = self.get_size();
if let Some(ref context) = *self.context.borrow() {
match *context {
CanvasContext::Context2d(ref context) => context.set_bitmap_dimensions(size),
CanvasContext::WebGL(ref context) => context.recreate(size),
}
}
}
pub fn get_size(&self) -> Size2D<i32> {
Size2D::new(self.Width() as i32, self.Height() as i32)
}
pub fn origin_is_clean(&self) -> bool {
match *self.context.borrow() {
Some(CanvasContext::Context2d(ref context)) => context.origin_is_clean(),
_ => true,
}
}
}
pub trait LayoutHTMLCanvasElementHelpers {
fn data(&self) -> HTMLCanvasData;
}
impl LayoutHTMLCanvasElementHelpers for LayoutJS<HTMLCanvasElement> {
#[allow(unsafe_code)]
fn data(&self) -> HTMLCanvasData {
unsafe {
let canvas = &*self.unsafe_get();
let ipc_renderer = canvas.context.borrow_for_layout().as_ref().map(|context| {
match *context {
CanvasContext::Context2d(ref context) => {
context.to_layout().get_ipc_renderer()
},
CanvasContext::WebGL(ref context) => {
context.to_layout().get_ipc_renderer()
},
}
});
let width_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width"));
let height_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height"));
HTMLCanvasData {
ipc_renderer: ipc_renderer,
width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()),
height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()),
}
}
}
}
impl HTMLCanvasElement {
pub fn ipc_renderer(&self) -> Option<IpcSender<CanvasMsg>> {
self.context.borrow().as_ref().map(|context| {
match *context {
CanvasContext::Context2d(ref context) => context.ipc_renderer(),
CanvasContext::WebGL(ref context) => context.ipc_renderer(),
}
})
}
pub fn get_or_init_2d_context(&self) -> Option<Root<CanvasRenderingContext2D>> {
if self.context.borrow().is_none() {
let window = window_from_node(self);
let size = self.get_size();
let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size);
*self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref(&*context)));
}
match *self.context.borrow().as_ref().unwrap() {
CanvasContext::Context2d(ref context) => Some(Root::from_ref(&*context)),
_ => None,
}
}
#[allow(unsafe_code)]
pub fn get_or_init_webgl_context(&self,
cx: *mut JSContext,
attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> {
if self.context.borrow().is_none() {
let window = window_from_node(self);
let size = self.get_size();
let attrs = if let Some(webgl_attributes) = attrs {
match unsafe {
WebGLContextAttributes::new(cx, webgl_attributes) } {
Ok(ConversionResult::Success(ref attrs)) => From::from(attrs),
Ok(ConversionResult::Failure(ref error)) => {
unsafe { throw_type_error(cx, &error); }
return None;
}
_ => {
debug!("Unexpected error on conversion of WebGLContextAttributes");
return None;
}
}
} else {
GLContextAttributes::default()
};
let maybe_ctx = WebGLRenderingContext::new(window.upcast(), self, size, attrs);
*self.context.borrow_mut() = maybe_ctx.map( |ctx| CanvasContext::WebGL(JS::from_ref(&*ctx)));
}
if let Some(CanvasContext::WebGL(ref context)) = *self.context.borrow() {
Some(Root::from_ref(&*context))
} else {
None
}
}
pub fn is_valid(&self) -> bool {
self.Height()!= 0 && self.Width()!= 0
}
pub fn fetch_all_data(&self) -> Option<(Vec<u8>, Size2D<i32>)> {
let size = self.get_size();
if size.width == 0 || size.height == 0 {
return None
}
let data = if let Some(renderer) = self.ipc_renderer() {
let (sender, receiver) = ipc::channel().unwrap();
let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender));
renderer.send(msg).unwrap();
match receiver.recv().unwrap() {
Some(pixels) => pixels,
None => {
// TODO(emilio, #14109): Not sure if WebGL canvas is
// required for 2d spec, but I think it's not, if so, make
// this return a readback from the GL context.
return None;
}
}
} else {
repeat(0xffu8).take((size.height as usize) * (size.width as usize) * 4).collect()
};
Some((data, size))
}
}
impl HTMLCanvasElementMethods for HTMLCanvasElement {
// https://html.spec.whatwg.org/multipage/#dom-canvas-width
make_uint_getter!(Width, "width", DEFAULT_WIDTH);
// https://html.spec.whatwg.org/multipage/#dom-canvas-width
make_uint_setter!(SetWidth, "width", DEFAULT_WIDTH);
// https://html.spec.whatwg.org/multipage/#dom-canvas-height
make_uint_getter!(Height, "height", DEFAULT_HEIGHT);
// https://html.spec.whatwg.org/multipage/#dom-canvas-height
make_uint_setter!(SetHeight, "height", DEFAULT_HEIGHT);
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext
unsafe fn GetContext(&self,
cx: *mut JSContext,
id: DOMString,
attributes: Vec<HandleValue>)
-> Option<CanvasRenderingContext2DOrWebGLRenderingContext> {
match &*id {
"2d" => {
self.get_or_init_2d_context()
.map(CanvasRenderingContext2DOrWebGLRenderingContext::CanvasRenderingContext2D)
}
"webgl" | "experimental-webgl" => {
self.get_or_init_webgl_context(cx, attributes.get(0).cloned())
.map(CanvasRenderingContext2DOrWebGLRenderingContext::WebGLRenderingContext)
}
_ => None
}
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl
unsafe fn ToDataURL(&self,
_context: *mut JSContext,
_mime_type: Option<DOMString>,
_arguments: Vec<HandleValue>) -> Fallible<DOMString> {
// Step 1.
if let Some(CanvasContext::Context2d(ref context)) = *self.context.borrow() {
if!context.origin_is_clean() {
return Err(Error::Security);
}
}
// Step 2.
if self.Width() == 0 || self.Height() == 0 {
return Ok(DOMString::from("data:,"));
}
// Step 3.
let raw_data = match *self.context.borrow() {
Some(CanvasContext::Context2d(ref context)) => {
let image_data = try!(context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64),
Finite::wrap(self.Width() as f64),
Finite::wrap(self.Height() as f64)));
image_data.get_data_array()
}
None => {
// Each pixel is fully-transparent black.
vec![0; (self.Width() * self.Height() * 4) as usize]
}
_ => return Err(Error::NotSupported) // WebGL
};
// Only handle image/png for now.
let mime_type = "image/png";
let mut encoded = Vec::new();
{
let encoder: PNGEncoder<&mut Vec<u8>> = PNGEncoder::new(&mut encoded);
encoder.encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)).unwrap();
}
let encoded = encoded.to_base64(STANDARD);
Ok(DOMString::from(format!("data:{};base64,{}", mime_type, encoded)))
}
}
impl VirtualMethods for HTMLCanvasElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&local_name!("width") | &local_name!("height") => self.recreate_contexts(),
_ => (),
};
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
&local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes {
fn from(attrs: &'a WebGLContextAttributes) -> GLContextAttributes {
GLContextAttributes {
alpha: attrs.alpha,
depth: attrs.depth,
stencil: attrs.stencil,
antialias: attrs.antialias,
premultiplied_alpha: attrs.premultipliedAlpha,
preserve_drawing_buffer: attrs.preserveDrawingBuffer,
}
}
}
pub mod utils {
use dom::window::Window;
use ipc_channel::ipc;
use net_traits::image_cache_thread::{ImageCacheChan, ImageResponse};
use servo_url::ServoUrl;
pub fn | (window: &Window, url: ServoUrl) -> ImageResponse {
let image_cache = window.image_cache_thread();
let (response_chan, response_port) = ipc::channel().unwrap();
image_cache.request_image(url.into(), ImageCacheChan(response_chan), None);
let result = response_port.recv().unwrap();
result.image_response
}
}
| request_image_from_cache | identifier_name |
htmlcanvaselement.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 canvas_traits::{CanvasMsg, FromScriptMsg};
use dom::attr::Attr;
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods;
use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding;
use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::HTMLCanvasElementMethods;
use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes;
use dom::bindings::codegen::UnionTypes::CanvasRenderingContext2DOrWebGLRenderingContext;
use dom::bindings::conversions::ConversionResult;
use dom::bindings::error::{Error, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{HeapGCValue, JS, LayoutJS, Root};
use dom::bindings::num::Finite;
use dom::bindings::str::DOMString;
use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers};
use dom::document::Document;
use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers};
use dom::globalscope::GlobalScope;
use dom::htmlelement::HTMLElement;
use dom::node::{Node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom::webglrenderingcontext::{LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext};
use euclid::size::Size2D;
use html5ever_atoms::LocalName;
use image::ColorType;
use image::png::PNGEncoder;
use ipc_channel::ipc::{self, IpcSender};
use js::error::throw_type_error;
use js::jsapi::{HandleValue, JSContext};
use offscreen_gl_context::GLContextAttributes;
use rustc_serialize::base64::{STANDARD, ToBase64};
use script_layout_interface::HTMLCanvasData;
use std::iter::repeat;
use style::attr::AttrValue;
const DEFAULT_WIDTH: u32 = 300;
const DEFAULT_HEIGHT: u32 = 150;
#[must_root]
#[derive(JSTraceable, Clone, HeapSizeOf)]
pub enum CanvasContext {
Context2d(JS<CanvasRenderingContext2D>),
WebGL(JS<WebGLRenderingContext>),
}
impl HeapGCValue for CanvasContext {}
#[dom_struct]
pub struct HTMLCanvasElement {
htmlelement: HTMLElement,
context: DOMRefCell<Option<CanvasContext>>,
}
impl HTMLCanvasElement {
fn new_inherited(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> HTMLCanvasElement {
HTMLCanvasElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
context: DOMRefCell::new(None),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLCanvasElement> {
Node::reflect_node(box HTMLCanvasElement::new_inherited(local_name, prefix, document),
document,
HTMLCanvasElementBinding::Wrap)
}
fn recreate_contexts(&self) {
let size = self.get_size();
if let Some(ref context) = *self.context.borrow() {
match *context {
CanvasContext::Context2d(ref context) => context.set_bitmap_dimensions(size),
CanvasContext::WebGL(ref context) => context.recreate(size),
}
}
}
pub fn get_size(&self) -> Size2D<i32> {
Size2D::new(self.Width() as i32, self.Height() as i32)
}
pub fn origin_is_clean(&self) -> bool {
match *self.context.borrow() {
Some(CanvasContext::Context2d(ref context)) => context.origin_is_clean(),
_ => true,
}
}
}
pub trait LayoutHTMLCanvasElementHelpers {
fn data(&self) -> HTMLCanvasData;
}
impl LayoutHTMLCanvasElementHelpers for LayoutJS<HTMLCanvasElement> {
#[allow(unsafe_code)]
fn data(&self) -> HTMLCanvasData {
unsafe {
let canvas = &*self.unsafe_get();
let ipc_renderer = canvas.context.borrow_for_layout().as_ref().map(|context| {
match *context {
CanvasContext::Context2d(ref context) => {
context.to_layout().get_ipc_renderer()
},
CanvasContext::WebGL(ref context) => {
context.to_layout().get_ipc_renderer()
},
}
});
let width_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width"));
let height_attr = canvas.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height"));
HTMLCanvasData {
ipc_renderer: ipc_renderer,
width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()),
height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()),
}
}
}
}
impl HTMLCanvasElement {
pub fn ipc_renderer(&self) -> Option<IpcSender<CanvasMsg>> {
self.context.borrow().as_ref().map(|context| {
match *context {
CanvasContext::Context2d(ref context) => context.ipc_renderer(),
CanvasContext::WebGL(ref context) => context.ipc_renderer(),
}
})
}
pub fn get_or_init_2d_context(&self) -> Option<Root<CanvasRenderingContext2D>> |
#[allow(unsafe_code)]
pub fn get_or_init_webgl_context(&self,
cx: *mut JSContext,
attrs: Option<HandleValue>) -> Option<Root<WebGLRenderingContext>> {
if self.context.borrow().is_none() {
let window = window_from_node(self);
let size = self.get_size();
let attrs = if let Some(webgl_attributes) = attrs {
match unsafe {
WebGLContextAttributes::new(cx, webgl_attributes) } {
Ok(ConversionResult::Success(ref attrs)) => From::from(attrs),
Ok(ConversionResult::Failure(ref error)) => {
unsafe { throw_type_error(cx, &error); }
return None;
}
_ => {
debug!("Unexpected error on conversion of WebGLContextAttributes");
return None;
}
}
} else {
GLContextAttributes::default()
};
let maybe_ctx = WebGLRenderingContext::new(window.upcast(), self, size, attrs);
*self.context.borrow_mut() = maybe_ctx.map( |ctx| CanvasContext::WebGL(JS::from_ref(&*ctx)));
}
if let Some(CanvasContext::WebGL(ref context)) = *self.context.borrow() {
Some(Root::from_ref(&*context))
} else {
None
}
}
pub fn is_valid(&self) -> bool {
self.Height()!= 0 && self.Width()!= 0
}
pub fn fetch_all_data(&self) -> Option<(Vec<u8>, Size2D<i32>)> {
let size = self.get_size();
if size.width == 0 || size.height == 0 {
return None
}
let data = if let Some(renderer) = self.ipc_renderer() {
let (sender, receiver) = ipc::channel().unwrap();
let msg = CanvasMsg::FromScript(FromScriptMsg::SendPixels(sender));
renderer.send(msg).unwrap();
match receiver.recv().unwrap() {
Some(pixels) => pixels,
None => {
// TODO(emilio, #14109): Not sure if WebGL canvas is
// required for 2d spec, but I think it's not, if so, make
// this return a readback from the GL context.
return None;
}
}
} else {
repeat(0xffu8).take((size.height as usize) * (size.width as usize) * 4).collect()
};
Some((data, size))
}
}
impl HTMLCanvasElementMethods for HTMLCanvasElement {
// https://html.spec.whatwg.org/multipage/#dom-canvas-width
make_uint_getter!(Width, "width", DEFAULT_WIDTH);
// https://html.spec.whatwg.org/multipage/#dom-canvas-width
make_uint_setter!(SetWidth, "width", DEFAULT_WIDTH);
// https://html.spec.whatwg.org/multipage/#dom-canvas-height
make_uint_getter!(Height, "height", DEFAULT_HEIGHT);
// https://html.spec.whatwg.org/multipage/#dom-canvas-height
make_uint_setter!(SetHeight, "height", DEFAULT_HEIGHT);
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-canvas-getcontext
unsafe fn GetContext(&self,
cx: *mut JSContext,
id: DOMString,
attributes: Vec<HandleValue>)
-> Option<CanvasRenderingContext2DOrWebGLRenderingContext> {
match &*id {
"2d" => {
self.get_or_init_2d_context()
.map(CanvasRenderingContext2DOrWebGLRenderingContext::CanvasRenderingContext2D)
}
"webgl" | "experimental-webgl" => {
self.get_or_init_webgl_context(cx, attributes.get(0).cloned())
.map(CanvasRenderingContext2DOrWebGLRenderingContext::WebGLRenderingContext)
}
_ => None
}
}
#[allow(unsafe_code)]
// https://html.spec.whatwg.org/multipage/#dom-canvas-todataurl
unsafe fn ToDataURL(&self,
_context: *mut JSContext,
_mime_type: Option<DOMString>,
_arguments: Vec<HandleValue>) -> Fallible<DOMString> {
// Step 1.
if let Some(CanvasContext::Context2d(ref context)) = *self.context.borrow() {
if!context.origin_is_clean() {
return Err(Error::Security);
}
}
// Step 2.
if self.Width() == 0 || self.Height() == 0 {
return Ok(DOMString::from("data:,"));
}
// Step 3.
let raw_data = match *self.context.borrow() {
Some(CanvasContext::Context2d(ref context)) => {
let image_data = try!(context.GetImageData(Finite::wrap(0f64), Finite::wrap(0f64),
Finite::wrap(self.Width() as f64),
Finite::wrap(self.Height() as f64)));
image_data.get_data_array()
}
None => {
// Each pixel is fully-transparent black.
vec![0; (self.Width() * self.Height() * 4) as usize]
}
_ => return Err(Error::NotSupported) // WebGL
};
// Only handle image/png for now.
let mime_type = "image/png";
let mut encoded = Vec::new();
{
let encoder: PNGEncoder<&mut Vec<u8>> = PNGEncoder::new(&mut encoded);
encoder.encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)).unwrap();
}
let encoded = encoded.to_base64(STANDARD);
Ok(DOMString::from(format!("data:{};base64,{}", mime_type, encoded)))
}
}
impl VirtualMethods for HTMLCanvasElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&local_name!("width") | &local_name!("height") => self.recreate_contexts(),
_ => (),
};
}
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
&local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
}
impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes {
fn from(attrs: &'a WebGLContextAttributes) -> GLContextAttributes {
GLContextAttributes {
alpha: attrs.alpha,
depth: attrs.depth,
stencil: attrs.stencil,
antialias: attrs.antialias,
premultiplied_alpha: attrs.premultipliedAlpha,
preserve_drawing_buffer: attrs.preserveDrawingBuffer,
}
}
}
pub mod utils {
use dom::window::Window;
use ipc_channel::ipc;
use net_traits::image_cache_thread::{ImageCacheChan, ImageResponse};
use servo_url::ServoUrl;
pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse {
let image_cache = window.image_cache_thread();
let (response_chan, response_port) = ipc::channel().unwrap();
image_cache.request_image(url.into(), ImageCacheChan(response_chan), None);
let result = response_port.recv().unwrap();
result.image_response
}
}
| {
if self.context.borrow().is_none() {
let window = window_from_node(self);
let size = self.get_size();
let context = CanvasRenderingContext2D::new(window.upcast::<GlobalScope>(), self, size);
*self.context.borrow_mut() = Some(CanvasContext::Context2d(JS::from_ref(&*context)));
}
match *self.context.borrow().as_ref().unwrap() {
CanvasContext::Context2d(ref context) => Some(Root::from_ref(&*context)),
_ => None,
}
} | identifier_body |
optimization-fuel-1.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.
#![crate_name="foo"]
use std::mem::size_of;
// (#55495: The --error-format is to sidestep an issue in our test harness)
// compile-flags: --error-format human -Z fuel=foo=1
struct S1(u8, u16, u8);
struct S2(u8, u16, u8);
fn | () {
let optimized = (size_of::<S1>() == 4) as usize
+(size_of::<S2>() == 4) as usize;
assert_eq!(optimized, 1);
}
| main | identifier_name |
optimization-fuel-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. |
use std::mem::size_of;
// (#55495: The --error-format is to sidestep an issue in our test harness)
// compile-flags: --error-format human -Z fuel=foo=1
struct S1(u8, u16, u8);
struct S2(u8, u16, u8);
fn main() {
let optimized = (size_of::<S1>() == 4) as usize
+(size_of::<S2>() == 4) as usize;
assert_eq!(optimized, 1);
} |
#![crate_name="foo"] | random_line_split |
install.rs | use serde::{Serialize, Serializer};
use std::str::FromStr;
use datatype::Error;
/// The installation outcome from a package manager.
pub struct InstallOutcome {
code: InstallCode,
stdout: String,
stderr: String,
}
impl InstallOutcome {
/// Create a new installation outcome.
pub fn new(code: InstallCode, stdout: String, stderr: String) -> InstallOutcome {
InstallOutcome { code, stdout, stderr }
}
/// Create a new installation outcome with empty stdout and stderr fields.
pub fn empty(code: InstallCode) -> InstallOutcome {
Self::new(code, "".into(), "".into())
}
/// Create a new installation outcome with a code of `OK`.
pub fn ok() -> InstallOutcome {
Self::empty(InstallCode::OK)
}
/// Create a new installation outcome with a code of `GENERAL_ERROR`.
pub fn error(stderr: String) -> InstallOutcome {
Self::new(InstallCode::GENERAL_ERROR, "".into(), stderr)
}
/// Convert an `InstallOutcome` into a `InstallResult
pub fn into_result(self, id: String) -> InstallResult {
InstallResult::new(id, self.code, format!("stdout: {}\nstderr: {}\n", self.stdout, self.stderr))
}
}
/// An encodable response of the installation outcome.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct InstallResult {
pub id: String,
pub result_code: InstallCode,
pub result_text: String,
}
impl InstallResult {
/// Create a new installation result.
pub fn new(id: String, result_code: InstallCode, result_text: String) -> InstallResult {
InstallResult { id, result_code, result_text }
}
/// Convert a single installation result to an `InstallReport`.
pub fn into_report(self) -> InstallReport {
InstallReport { update_id: self.id.clone(), operation_results: vec![self] }
}
}
/// A report of a list of installation results.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct | {
pub update_id: String,
pub operation_results: Vec<InstallResult>
}
impl InstallReport {
/// Create a new report from a list of installation results.
pub fn new(update_id: String, operation_results: Vec<InstallResult>) -> Self {
InstallReport { update_id, operation_results }
}
}
/// Enumerate the possible outcomes when trying to install a package.
#[allow(non_camel_case_types)]
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum InstallCode {
/// Operation executed successfully
OK = 0,
/// Operation has already been processed
ALREADY_PROCESSED,
/// Dependency failure during package install, upgrade, or removal
DEPENDENCY_FAILURE,
/// Update image integrity has been compromised
VALIDATION_FAILED,
/// Package installation failed
INSTALL_FAILED,
/// Package upgrade failed
UPGRADE_FAILED,
/// Package removal failed
REMOVAL_FAILED,
/// The module loader could not flash its managed module
FLASH_FAILED,
/// Partition creation failed
CREATE_PARTITION_FAILED,
/// Partition deletion failed
DELETE_PARTITION_FAILED,
/// Partition resize failed
RESIZE_PARTITION_FAILED,
/// Partition write failed
WRITE_PARTITION_FAILED,
/// Partition patching failed
PATCH_PARTITION_FAILED,
/// User declined the update
USER_DECLINED,
/// Software was blacklisted
SOFTWARE_BLACKLISTED,
/// Ran out of disk space
DISK_FULL,
/// Software package not found
NOT_FOUND,
/// Tried to downgrade to older version
OLD_VERSION,
/// SWM Internal integrity error
INTERNAL_ERROR,
/// Other error
GENERAL_ERROR,
}
impl InstallCode {
/// Was the installation successful?
pub fn is_success(&self) -> bool {
match *self {
InstallCode::OK | InstallCode::ALREADY_PROCESSED => true,
_ => false
}
}
}
impl Default for InstallCode {
fn default() -> Self {
InstallCode::OK
}
}
impl FromStr for InstallCode {
type Err = Error;
fn from_str(s: &str) -> Result<InstallCode, Error> {
match &*s.to_uppercase() {
"0" | "OK" => Ok(InstallCode::OK),
"1" | "ALREADY_PROCESSED" => Ok(InstallCode::ALREADY_PROCESSED),
"2" | "DEPENDENCY_FAILURE" => Ok(InstallCode::DEPENDENCY_FAILURE),
"3" | "VALIDATION_FAILED" => Ok(InstallCode::VALIDATION_FAILED),
"4" | "INSTALL_FAILED" => Ok(InstallCode::INSTALL_FAILED),
"5" | "UPGRADE_FAILED" => Ok(InstallCode::UPGRADE_FAILED),
"6" | "REMOVAL_FAILED" => Ok(InstallCode::REMOVAL_FAILED),
"7" | "FLASH_FAILED" => Ok(InstallCode::FLASH_FAILED),
"8" | "CREATE_PARTITION_FAILED" => Ok(InstallCode::CREATE_PARTITION_FAILED),
"9" | "DELETE_PARTITION_FAILED" => Ok(InstallCode::DELETE_PARTITION_FAILED),
"10" | "RESIZE_PARTITION_FAILED" => Ok(InstallCode::RESIZE_PARTITION_FAILED),
"11" | "WRITE_PARTITION_FAILED" => Ok(InstallCode::WRITE_PARTITION_FAILED),
"12" | "PATCH_PARTITION_FAILED" => Ok(InstallCode::PATCH_PARTITION_FAILED),
"13" | "USER_DECLINED" => Ok(InstallCode::USER_DECLINED),
"14" | "SOFTWARE_BLACKLISTED" => Ok(InstallCode::SOFTWARE_BLACKLISTED),
"15" | "DISK_FULL" => Ok(InstallCode::DISK_FULL),
"16" | "NOT_FOUND" => Ok(InstallCode::NOT_FOUND),
"17" | "OLD_VERSION" => Ok(InstallCode::OLD_VERSION),
"18" | "INTERNAL_ERROR" => Ok(InstallCode::INTERNAL_ERROR),
"19" | "GENERAL_ERROR" => Ok(InstallCode::GENERAL_ERROR),
_ => Err(Error::Parse(format!("unknown InstallCode: {}", s)))
}
}
}
impl Serialize for InstallCode {
fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
ser.serialize_u64(self.clone() as u64)
}
}
/// Encapsulates a single firmware installed on the device.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub struct InstalledFirmware {
pub module: String,
pub firmware_id: String,
pub last_modified: u64
}
/// Encapsulates a single package installed on the device.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub struct InstalledPackage {
pub package_id: String,
pub name: String,
pub description: String,
pub last_modified: u64
}
/// An encodable list of packages and firmwares to send to RVI.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct InstalledSoftware {
pub packages: Vec<InstalledPackage>,
pub firmwares: Vec<InstalledFirmware>
}
impl InstalledSoftware {
/// Instantiate a new list of the software installed on the device.
pub fn new(packages: Vec<InstalledPackage>, firmwares: Vec<InstalledFirmware>) -> InstalledSoftware {
InstalledSoftware { packages, firmwares }
}
}
| InstallReport | identifier_name |
install.rs | use serde::{Serialize, Serializer};
use std::str::FromStr;
use datatype::Error;
/// The installation outcome from a package manager.
pub struct InstallOutcome {
code: InstallCode,
stdout: String,
stderr: String,
}
impl InstallOutcome {
/// Create a new installation outcome.
pub fn new(code: InstallCode, stdout: String, stderr: String) -> InstallOutcome {
InstallOutcome { code, stdout, stderr }
}
/// Create a new installation outcome with empty stdout and stderr fields.
pub fn empty(code: InstallCode) -> InstallOutcome {
Self::new(code, "".into(), "".into())
}
/// Create a new installation outcome with a code of `OK`.
pub fn ok() -> InstallOutcome {
Self::empty(InstallCode::OK)
}
/// Create a new installation outcome with a code of `GENERAL_ERROR`.
pub fn error(stderr: String) -> InstallOutcome {
Self::new(InstallCode::GENERAL_ERROR, "".into(), stderr)
}
/// Convert an `InstallOutcome` into a `InstallResult
pub fn into_result(self, id: String) -> InstallResult {
InstallResult::new(id, self.code, format!("stdout: {}\nstderr: {}\n", self.stdout, self.stderr))
}
}
/// An encodable response of the installation outcome.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct InstallResult {
pub id: String,
pub result_code: InstallCode,
pub result_text: String,
}
impl InstallResult {
/// Create a new installation result.
pub fn new(id: String, result_code: InstallCode, result_text: String) -> InstallResult {
InstallResult { id, result_code, result_text }
}
/// Convert a single installation result to an `InstallReport`.
pub fn into_report(self) -> InstallReport {
InstallReport { update_id: self.id.clone(), operation_results: vec![self] }
}
}
/// A report of a list of installation results.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct InstallReport {
pub update_id: String,
pub operation_results: Vec<InstallResult>
}
impl InstallReport {
/// Create a new report from a list of installation results.
pub fn new(update_id: String, operation_results: Vec<InstallResult>) -> Self {
InstallReport { update_id, operation_results }
}
}
/// Enumerate the possible outcomes when trying to install a package.
#[allow(non_camel_case_types)]
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum InstallCode {
/// Operation executed successfully
OK = 0,
/// Operation has already been processed
ALREADY_PROCESSED,
/// Dependency failure during package install, upgrade, or removal
DEPENDENCY_FAILURE,
/// Update image integrity has been compromised
VALIDATION_FAILED,
/// Package installation failed
INSTALL_FAILED,
/// Package upgrade failed
UPGRADE_FAILED,
/// Package removal failed
REMOVAL_FAILED,
/// The module loader could not flash its managed module
FLASH_FAILED,
/// Partition creation failed
CREATE_PARTITION_FAILED,
/// Partition deletion failed
DELETE_PARTITION_FAILED,
/// Partition resize failed
RESIZE_PARTITION_FAILED,
/// Partition write failed
WRITE_PARTITION_FAILED,
/// Partition patching failed
PATCH_PARTITION_FAILED,
/// User declined the update
USER_DECLINED,
/// Software was blacklisted
SOFTWARE_BLACKLISTED,
/// Ran out of disk space
DISK_FULL,
/// Software package not found
NOT_FOUND,
/// Tried to downgrade to older version
OLD_VERSION,
/// SWM Internal integrity error
INTERNAL_ERROR,
/// Other error
GENERAL_ERROR,
}
impl InstallCode {
/// Was the installation successful?
pub fn is_success(&self) -> bool {
match *self {
InstallCode::OK | InstallCode::ALREADY_PROCESSED => true,
_ => false
}
}
}
impl Default for InstallCode {
fn default() -> Self {
InstallCode::OK
}
}
impl FromStr for InstallCode {
type Err = Error;
fn from_str(s: &str) -> Result<InstallCode, Error> {
match &*s.to_uppercase() {
"0" | "OK" => Ok(InstallCode::OK),
"1" | "ALREADY_PROCESSED" => Ok(InstallCode::ALREADY_PROCESSED),
"2" | "DEPENDENCY_FAILURE" => Ok(InstallCode::DEPENDENCY_FAILURE),
"3" | "VALIDATION_FAILED" => Ok(InstallCode::VALIDATION_FAILED),
"4" | "INSTALL_FAILED" => Ok(InstallCode::INSTALL_FAILED),
"5" | "UPGRADE_FAILED" => Ok(InstallCode::UPGRADE_FAILED),
"6" | "REMOVAL_FAILED" => Ok(InstallCode::REMOVAL_FAILED),
"7" | "FLASH_FAILED" => Ok(InstallCode::FLASH_FAILED),
"8" | "CREATE_PARTITION_FAILED" => Ok(InstallCode::CREATE_PARTITION_FAILED),
"9" | "DELETE_PARTITION_FAILED" => Ok(InstallCode::DELETE_PARTITION_FAILED),
"10" | "RESIZE_PARTITION_FAILED" => Ok(InstallCode::RESIZE_PARTITION_FAILED),
"11" | "WRITE_PARTITION_FAILED" => Ok(InstallCode::WRITE_PARTITION_FAILED),
"12" | "PATCH_PARTITION_FAILED" => Ok(InstallCode::PATCH_PARTITION_FAILED),
"13" | "USER_DECLINED" => Ok(InstallCode::USER_DECLINED),
"14" | "SOFTWARE_BLACKLISTED" => Ok(InstallCode::SOFTWARE_BLACKLISTED),
"15" | "DISK_FULL" => Ok(InstallCode::DISK_FULL),
"16" | "NOT_FOUND" => Ok(InstallCode::NOT_FOUND),
"17" | "OLD_VERSION" => Ok(InstallCode::OLD_VERSION),
"18" | "INTERNAL_ERROR" => Ok(InstallCode::INTERNAL_ERROR),
"19" | "GENERAL_ERROR" => Ok(InstallCode::GENERAL_ERROR),
_ => Err(Error::Parse(format!("unknown InstallCode: {}", s)))
}
}
}
impl Serialize for InstallCode {
fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
ser.serialize_u64(self.clone() as u64)
}
}
/// Encapsulates a single firmware installed on the device.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub struct InstalledFirmware {
pub module: String,
pub firmware_id: String,
pub last_modified: u64
} | pub package_id: String,
pub name: String,
pub description: String,
pub last_modified: u64
}
/// An encodable list of packages and firmwares to send to RVI.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct InstalledSoftware {
pub packages: Vec<InstalledPackage>,
pub firmwares: Vec<InstalledFirmware>
}
impl InstalledSoftware {
/// Instantiate a new list of the software installed on the device.
pub fn new(packages: Vec<InstalledPackage>, firmwares: Vec<InstalledFirmware>) -> InstalledSoftware {
InstalledSoftware { packages, firmwares }
}
} |
/// Encapsulates a single package installed on the device.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub struct InstalledPackage { | random_line_split |
install.rs | use serde::{Serialize, Serializer};
use std::str::FromStr;
use datatype::Error;
/// The installation outcome from a package manager.
pub struct InstallOutcome {
code: InstallCode,
stdout: String,
stderr: String,
}
impl InstallOutcome {
/// Create a new installation outcome.
pub fn new(code: InstallCode, stdout: String, stderr: String) -> InstallOutcome {
InstallOutcome { code, stdout, stderr }
}
/// Create a new installation outcome with empty stdout and stderr fields.
pub fn empty(code: InstallCode) -> InstallOutcome {
Self::new(code, "".into(), "".into())
}
/// Create a new installation outcome with a code of `OK`.
pub fn ok() -> InstallOutcome {
Self::empty(InstallCode::OK)
}
/// Create a new installation outcome with a code of `GENERAL_ERROR`.
pub fn error(stderr: String) -> InstallOutcome |
/// Convert an `InstallOutcome` into a `InstallResult
pub fn into_result(self, id: String) -> InstallResult {
InstallResult::new(id, self.code, format!("stdout: {}\nstderr: {}\n", self.stdout, self.stderr))
}
}
/// An encodable response of the installation outcome.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct InstallResult {
pub id: String,
pub result_code: InstallCode,
pub result_text: String,
}
impl InstallResult {
/// Create a new installation result.
pub fn new(id: String, result_code: InstallCode, result_text: String) -> InstallResult {
InstallResult { id, result_code, result_text }
}
/// Convert a single installation result to an `InstallReport`.
pub fn into_report(self) -> InstallReport {
InstallReport { update_id: self.id.clone(), operation_results: vec![self] }
}
}
/// A report of a list of installation results.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct InstallReport {
pub update_id: String,
pub operation_results: Vec<InstallResult>
}
impl InstallReport {
/// Create a new report from a list of installation results.
pub fn new(update_id: String, operation_results: Vec<InstallResult>) -> Self {
InstallReport { update_id, operation_results }
}
}
/// Enumerate the possible outcomes when trying to install a package.
#[allow(non_camel_case_types)]
#[derive(Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum InstallCode {
/// Operation executed successfully
OK = 0,
/// Operation has already been processed
ALREADY_PROCESSED,
/// Dependency failure during package install, upgrade, or removal
DEPENDENCY_FAILURE,
/// Update image integrity has been compromised
VALIDATION_FAILED,
/// Package installation failed
INSTALL_FAILED,
/// Package upgrade failed
UPGRADE_FAILED,
/// Package removal failed
REMOVAL_FAILED,
/// The module loader could not flash its managed module
FLASH_FAILED,
/// Partition creation failed
CREATE_PARTITION_FAILED,
/// Partition deletion failed
DELETE_PARTITION_FAILED,
/// Partition resize failed
RESIZE_PARTITION_FAILED,
/// Partition write failed
WRITE_PARTITION_FAILED,
/// Partition patching failed
PATCH_PARTITION_FAILED,
/// User declined the update
USER_DECLINED,
/// Software was blacklisted
SOFTWARE_BLACKLISTED,
/// Ran out of disk space
DISK_FULL,
/// Software package not found
NOT_FOUND,
/// Tried to downgrade to older version
OLD_VERSION,
/// SWM Internal integrity error
INTERNAL_ERROR,
/// Other error
GENERAL_ERROR,
}
impl InstallCode {
/// Was the installation successful?
pub fn is_success(&self) -> bool {
match *self {
InstallCode::OK | InstallCode::ALREADY_PROCESSED => true,
_ => false
}
}
}
impl Default for InstallCode {
fn default() -> Self {
InstallCode::OK
}
}
impl FromStr for InstallCode {
type Err = Error;
fn from_str(s: &str) -> Result<InstallCode, Error> {
match &*s.to_uppercase() {
"0" | "OK" => Ok(InstallCode::OK),
"1" | "ALREADY_PROCESSED" => Ok(InstallCode::ALREADY_PROCESSED),
"2" | "DEPENDENCY_FAILURE" => Ok(InstallCode::DEPENDENCY_FAILURE),
"3" | "VALIDATION_FAILED" => Ok(InstallCode::VALIDATION_FAILED),
"4" | "INSTALL_FAILED" => Ok(InstallCode::INSTALL_FAILED),
"5" | "UPGRADE_FAILED" => Ok(InstallCode::UPGRADE_FAILED),
"6" | "REMOVAL_FAILED" => Ok(InstallCode::REMOVAL_FAILED),
"7" | "FLASH_FAILED" => Ok(InstallCode::FLASH_FAILED),
"8" | "CREATE_PARTITION_FAILED" => Ok(InstallCode::CREATE_PARTITION_FAILED),
"9" | "DELETE_PARTITION_FAILED" => Ok(InstallCode::DELETE_PARTITION_FAILED),
"10" | "RESIZE_PARTITION_FAILED" => Ok(InstallCode::RESIZE_PARTITION_FAILED),
"11" | "WRITE_PARTITION_FAILED" => Ok(InstallCode::WRITE_PARTITION_FAILED),
"12" | "PATCH_PARTITION_FAILED" => Ok(InstallCode::PATCH_PARTITION_FAILED),
"13" | "USER_DECLINED" => Ok(InstallCode::USER_DECLINED),
"14" | "SOFTWARE_BLACKLISTED" => Ok(InstallCode::SOFTWARE_BLACKLISTED),
"15" | "DISK_FULL" => Ok(InstallCode::DISK_FULL),
"16" | "NOT_FOUND" => Ok(InstallCode::NOT_FOUND),
"17" | "OLD_VERSION" => Ok(InstallCode::OLD_VERSION),
"18" | "INTERNAL_ERROR" => Ok(InstallCode::INTERNAL_ERROR),
"19" | "GENERAL_ERROR" => Ok(InstallCode::GENERAL_ERROR),
_ => Err(Error::Parse(format!("unknown InstallCode: {}", s)))
}
}
}
impl Serialize for InstallCode {
fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
ser.serialize_u64(self.clone() as u64)
}
}
/// Encapsulates a single firmware installed on the device.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub struct InstalledFirmware {
pub module: String,
pub firmware_id: String,
pub last_modified: u64
}
/// Encapsulates a single package installed on the device.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub struct InstalledPackage {
pub package_id: String,
pub name: String,
pub description: String,
pub last_modified: u64
}
/// An encodable list of packages and firmwares to send to RVI.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq, Default)]
pub struct InstalledSoftware {
pub packages: Vec<InstalledPackage>,
pub firmwares: Vec<InstalledFirmware>
}
impl InstalledSoftware {
/// Instantiate a new list of the software installed on the device.
pub fn new(packages: Vec<InstalledPackage>, firmwares: Vec<InstalledFirmware>) -> InstalledSoftware {
InstalledSoftware { packages, firmwares }
}
}
| {
Self::new(InstallCode::GENERAL_ERROR, "".into(), stderr)
} | identifier_body |
download.rs | // Copyright (c) 2017 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::time;
use reqwest;
use serde::{Deserialize, Serialize};
use tempfile::NamedTempFile;
use crate::detect::Detected;
use crate::error::{Error, ResultExt};
use crate::res;
use crate::util::{progress_dummy, Retry, Sha256, ShaVerifyError};
use super::traits::Task;
/// A task to download a URL. This would normally be a task with no input
/// resources.
#[derive(
Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Hash, Clone,
)]
pub struct Download {
/// Process and arguments to spawn.
url: String,
/// Expected SHA256 hash.
sha256: Sha256,
/// Output path.
path: PathBuf,
/// How much time to give it to download. If `None`, there is no time
/// limit.
timeout: Option<time::Duration>,
/// Retry settings.
#[serde(default)]
retry: Retry,
}
impl fmt::Display for Download {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.url)
}
}
impl fmt::Debug for Download {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.url)
}
}
impl Task for Download {
fn execute(
&self,
root: &Path,
log: &mut dyn io::Write,
) -> Result<Detected, Error> {
let path = root.join(&self.path);
writeln!(log, "Downloading \"{}\" to {:?}", self.url, self.path)?;
// Retry the download if necessary.
let mut response = self.retry.call(
|| reqwest::get(&self.url)?.error_for_status(),
progress_dummy,
)?;
// Download to a temporary file that sits next to the desired path.
let dir = path.parent().unwrap_or_else(|| Path::new("."));
let mut temp = NamedTempFile::new_in(dir)?;
response.copy_to(&mut io::BufWriter::new(&mut temp))?;
let temp = temp.into_temp_path();
// Verify the SHA256
let sha256 = Sha256::from_path(&temp)?;
if self.sha256!= sha256 {
let result: Result<(), Error> =
Err(ShaVerifyError::new(self.sha256.clone(), sha256).into());
result.context(format!(
"Failed to verify SHA256 for URL {}",
self.url
))?;
}
temp.persist(&path)?;
Ok(Detected::new())
}
fn known_outputs(&self, resources: &mut res::Set) {
// TODO: Depend on output directory.
resources.insert(self.path.clone().into());
}
} | random_line_split |
|
download.rs | // Copyright (c) 2017 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::time;
use reqwest;
use serde::{Deserialize, Serialize};
use tempfile::NamedTempFile;
use crate::detect::Detected;
use crate::error::{Error, ResultExt};
use crate::res;
use crate::util::{progress_dummy, Retry, Sha256, ShaVerifyError};
use super::traits::Task;
/// A task to download a URL. This would normally be a task with no input
/// resources.
#[derive(
Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Hash, Clone,
)]
pub struct Download {
/// Process and arguments to spawn.
url: String,
/// Expected SHA256 hash.
sha256: Sha256,
/// Output path.
path: PathBuf,
/// How much time to give it to download. If `None`, there is no time
/// limit.
timeout: Option<time::Duration>,
/// Retry settings.
#[serde(default)]
retry: Retry,
}
impl fmt::Display for Download {
fn | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.url)
}
}
impl fmt::Debug for Download {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.url)
}
}
impl Task for Download {
fn execute(
&self,
root: &Path,
log: &mut dyn io::Write,
) -> Result<Detected, Error> {
let path = root.join(&self.path);
writeln!(log, "Downloading \"{}\" to {:?}", self.url, self.path)?;
// Retry the download if necessary.
let mut response = self.retry.call(
|| reqwest::get(&self.url)?.error_for_status(),
progress_dummy,
)?;
// Download to a temporary file that sits next to the desired path.
let dir = path.parent().unwrap_or_else(|| Path::new("."));
let mut temp = NamedTempFile::new_in(dir)?;
response.copy_to(&mut io::BufWriter::new(&mut temp))?;
let temp = temp.into_temp_path();
// Verify the SHA256
let sha256 = Sha256::from_path(&temp)?;
if self.sha256!= sha256 {
let result: Result<(), Error> =
Err(ShaVerifyError::new(self.sha256.clone(), sha256).into());
result.context(format!(
"Failed to verify SHA256 for URL {}",
self.url
))?;
}
temp.persist(&path)?;
Ok(Detected::new())
}
fn known_outputs(&self, resources: &mut res::Set) {
// TODO: Depend on output directory.
resources.insert(self.path.clone().into());
}
}
| fmt | identifier_name |
download.rs | // Copyright (c) 2017 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::time;
use reqwest;
use serde::{Deserialize, Serialize};
use tempfile::NamedTempFile;
use crate::detect::Detected;
use crate::error::{Error, ResultExt};
use crate::res;
use crate::util::{progress_dummy, Retry, Sha256, ShaVerifyError};
use super::traits::Task;
/// A task to download a URL. This would normally be a task with no input
/// resources.
#[derive(
Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Hash, Clone,
)]
pub struct Download {
/// Process and arguments to spawn.
url: String,
/// Expected SHA256 hash.
sha256: Sha256,
/// Output path.
path: PathBuf,
/// How much time to give it to download. If `None`, there is no time
/// limit.
timeout: Option<time::Duration>,
/// Retry settings.
#[serde(default)]
retry: Retry,
}
impl fmt::Display for Download {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.url)
}
}
impl fmt::Debug for Download {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.url)
}
}
impl Task for Download {
fn execute(
&self,
root: &Path,
log: &mut dyn io::Write,
) -> Result<Detected, Error> {
let path = root.join(&self.path);
writeln!(log, "Downloading \"{}\" to {:?}", self.url, self.path)?;
// Retry the download if necessary.
let mut response = self.retry.call(
|| reqwest::get(&self.url)?.error_for_status(),
progress_dummy,
)?;
// Download to a temporary file that sits next to the desired path.
let dir = path.parent().unwrap_or_else(|| Path::new("."));
let mut temp = NamedTempFile::new_in(dir)?;
response.copy_to(&mut io::BufWriter::new(&mut temp))?;
let temp = temp.into_temp_path();
// Verify the SHA256
let sha256 = Sha256::from_path(&temp)?;
if self.sha256!= sha256 |
temp.persist(&path)?;
Ok(Detected::new())
}
fn known_outputs(&self, resources: &mut res::Set) {
// TODO: Depend on output directory.
resources.insert(self.path.clone().into());
}
}
| {
let result: Result<(), Error> =
Err(ShaVerifyError::new(self.sha256.clone(), sha256).into());
result.context(format!(
"Failed to verify SHA256 for URL {}",
self.url
))?;
} | conditional_block |
download.rs | // Copyright (c) 2017 Jason White
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use std::time;
use reqwest;
use serde::{Deserialize, Serialize};
use tempfile::NamedTempFile;
use crate::detect::Detected;
use crate::error::{Error, ResultExt};
use crate::res;
use crate::util::{progress_dummy, Retry, Sha256, ShaVerifyError};
use super::traits::Task;
/// A task to download a URL. This would normally be a task with no input
/// resources.
#[derive(
Serialize, Deserialize, Ord, PartialOrd, Eq, PartialEq, Hash, Clone,
)]
pub struct Download {
/// Process and arguments to spawn.
url: String,
/// Expected SHA256 hash.
sha256: Sha256,
/// Output path.
path: PathBuf,
/// How much time to give it to download. If `None`, there is no time
/// limit.
timeout: Option<time::Duration>,
/// Retry settings.
#[serde(default)]
retry: Retry,
}
impl fmt::Display for Download {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.url)
}
}
impl fmt::Debug for Download {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.url)
}
}
impl Task for Download {
fn execute(
&self,
root: &Path,
log: &mut dyn io::Write,
) -> Result<Detected, Error> {
let path = root.join(&self.path);
writeln!(log, "Downloading \"{}\" to {:?}", self.url, self.path)?;
// Retry the download if necessary.
let mut response = self.retry.call(
|| reqwest::get(&self.url)?.error_for_status(),
progress_dummy,
)?;
// Download to a temporary file that sits next to the desired path.
let dir = path.parent().unwrap_or_else(|| Path::new("."));
let mut temp = NamedTempFile::new_in(dir)?;
response.copy_to(&mut io::BufWriter::new(&mut temp))?;
let temp = temp.into_temp_path();
// Verify the SHA256
let sha256 = Sha256::from_path(&temp)?;
if self.sha256!= sha256 {
let result: Result<(), Error> =
Err(ShaVerifyError::new(self.sha256.clone(), sha256).into());
result.context(format!(
"Failed to verify SHA256 for URL {}",
self.url
))?;
}
temp.persist(&path)?;
Ok(Detected::new())
}
fn known_outputs(&self, resources: &mut res::Set) |
}
| {
// TODO: Depend on output directory.
resources.insert(self.path.clone().into());
} | identifier_body |
io.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![stable(feature = "rust1", since = "1.0.0")]
use fs;
use os::windows::raw;
use net;
use sys_common::{self, AsInner, FromInner};
use sys;
/// Raw HANDLEs.
#[stable(feature = "rust1", since = "1.0.0")]
pub type RawHandle = raw::HANDLE;
/// Raw SOCKETs.
#[stable(feature = "rust1", since = "1.0.0")]
pub type RawSocket = raw::SOCKET;
/// Extract raw handles.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRawHandle {
/// Extracts the raw handle, without taking any ownership.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_raw_handle(&self) -> RawHandle;
}
/// Construct I/O objects from raw handles.
#[stable(feature = "from_raw_os", since = "1.1.0")]
pub trait FromRawHandle {
/// Constructs a new I/O object from the specified raw handle.
///
/// This function will **consume ownership** of the handle given,
/// passing responsibility for closing the handle to the returned
/// object.
///
/// This function is also unsafe as the primitives currently returned
/// have the contract that they are the sole owner of the file
/// descriptor they are wrapping. Usage of this function could
/// accidentally allow violating this contract which can cause memory
/// unsafety in code that relies on it being true.
#[stable(feature = "from_raw_os", since = "1.1.0")]
unsafe fn from_raw_handle(handle: RawHandle) -> Self;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawHandle for fs::File {
fn as_raw_handle(&self) -> RawHandle {
self.as_inner().handle().raw() as RawHandle
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawHandle for fs::File {
unsafe fn from_raw_handle(handle: RawHandle) -> fs::File {
let handle = handle as ::libc::HANDLE;
fs::File::from_inner(sys::fs::File::from_inner(handle))
}
}
/// Extract raw sockets.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRawSocket {
/// Extracts the underlying raw socket from this object.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_raw_socket(&self) -> RawSocket;
}
/// Create I/O objects from raw sockets.
#[stable(feature = "from_raw_os", since = "1.1.0")]
pub trait FromRawSocket {
/// Creates a new I/O object from the given raw socket.
///
/// This function will **consume ownership** of the socket provided and
/// it will be closed when the returned object goes out of scope.
///
/// This function is also unsafe as the primitives currently returned
/// have the contract that they are the sole owner of the file
/// descriptor they are wrapping. Usage of this function could
/// accidentally allow violating this contract which can cause memory
/// unsafety in code that relies on it being true.
#[stable(feature = "from_raw_os", since = "1.1.0")]
unsafe fn from_raw_socket(sock: RawSocket) -> Self;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawSocket for net::TcpStream {
fn | (&self) -> RawSocket {
*self.as_inner().socket().as_inner()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawSocket for net::TcpListener {
fn as_raw_socket(&self) -> RawSocket {
*self.as_inner().socket().as_inner()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawSocket for net::UdpSocket {
fn as_raw_socket(&self) -> RawSocket {
*self.as_inner().socket().as_inner()
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawSocket for net::TcpStream {
unsafe fn from_raw_socket(sock: RawSocket) -> net::TcpStream {
let sock = sys::net::Socket::from_inner(sock);
net::TcpStream::from_inner(sys_common::net::TcpStream::from_inner(sock))
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawSocket for net::TcpListener {
unsafe fn from_raw_socket(sock: RawSocket) -> net::TcpListener {
let sock = sys::net::Socket::from_inner(sock);
net::TcpListener::from_inner(sys_common::net::TcpListener::from_inner(sock))
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawSocket for net::UdpSocket {
unsafe fn from_raw_socket(sock: RawSocket) -> net::UdpSocket {
let sock = sys::net::Socket::from_inner(sock);
net::UdpSocket::from_inner(sys_common::net::UdpSocket::from_inner(sock))
}
}
| as_raw_socket | identifier_name |
io.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![stable(feature = "rust1", since = "1.0.0")]
use fs;
use os::windows::raw;
use net;
use sys_common::{self, AsInner, FromInner};
use sys;
/// Raw HANDLEs.
#[stable(feature = "rust1", since = "1.0.0")]
pub type RawHandle = raw::HANDLE;
/// Raw SOCKETs.
#[stable(feature = "rust1", since = "1.0.0")]
pub type RawSocket = raw::SOCKET;
/// Extract raw handles.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRawHandle {
/// Extracts the raw handle, without taking any ownership.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_raw_handle(&self) -> RawHandle;
}
/// Construct I/O objects from raw handles.
#[stable(feature = "from_raw_os", since = "1.1.0")]
pub trait FromRawHandle {
/// Constructs a new I/O object from the specified raw handle.
///
/// This function will **consume ownership** of the handle given,
/// passing responsibility for closing the handle to the returned
/// object.
///
/// This function is also unsafe as the primitives currently returned
/// have the contract that they are the sole owner of the file
/// descriptor they are wrapping. Usage of this function could
/// accidentally allow violating this contract which can cause memory
/// unsafety in code that relies on it being true.
#[stable(feature = "from_raw_os", since = "1.1.0")]
unsafe fn from_raw_handle(handle: RawHandle) -> Self;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawHandle for fs::File {
fn as_raw_handle(&self) -> RawHandle |
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawHandle for fs::File {
unsafe fn from_raw_handle(handle: RawHandle) -> fs::File {
let handle = handle as ::libc::HANDLE;
fs::File::from_inner(sys::fs::File::from_inner(handle))
}
}
/// Extract raw sockets.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRawSocket {
/// Extracts the underlying raw socket from this object.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_raw_socket(&self) -> RawSocket;
}
/// Create I/O objects from raw sockets.
#[stable(feature = "from_raw_os", since = "1.1.0")]
pub trait FromRawSocket {
/// Creates a new I/O object from the given raw socket.
///
/// This function will **consume ownership** of the socket provided and
/// it will be closed when the returned object goes out of scope.
///
/// This function is also unsafe as the primitives currently returned
/// have the contract that they are the sole owner of the file
/// descriptor they are wrapping. Usage of this function could
/// accidentally allow violating this contract which can cause memory
/// unsafety in code that relies on it being true.
#[stable(feature = "from_raw_os", since = "1.1.0")]
unsafe fn from_raw_socket(sock: RawSocket) -> Self;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawSocket for net::TcpStream {
fn as_raw_socket(&self) -> RawSocket {
*self.as_inner().socket().as_inner()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawSocket for net::TcpListener {
fn as_raw_socket(&self) -> RawSocket {
*self.as_inner().socket().as_inner()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawSocket for net::UdpSocket {
fn as_raw_socket(&self) -> RawSocket {
*self.as_inner().socket().as_inner()
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawSocket for net::TcpStream {
unsafe fn from_raw_socket(sock: RawSocket) -> net::TcpStream {
let sock = sys::net::Socket::from_inner(sock);
net::TcpStream::from_inner(sys_common::net::TcpStream::from_inner(sock))
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawSocket for net::TcpListener {
unsafe fn from_raw_socket(sock: RawSocket) -> net::TcpListener {
let sock = sys::net::Socket::from_inner(sock);
net::TcpListener::from_inner(sys_common::net::TcpListener::from_inner(sock))
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawSocket for net::UdpSocket {
unsafe fn from_raw_socket(sock: RawSocket) -> net::UdpSocket {
let sock = sys::net::Socket::from_inner(sock);
net::UdpSocket::from_inner(sys_common::net::UdpSocket::from_inner(sock))
}
}
| {
self.as_inner().handle().raw() as RawHandle
} | identifier_body |
io.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | // except according to those terms.
#![stable(feature = "rust1", since = "1.0.0")]
use fs;
use os::windows::raw;
use net;
use sys_common::{self, AsInner, FromInner};
use sys;
/// Raw HANDLEs.
#[stable(feature = "rust1", since = "1.0.0")]
pub type RawHandle = raw::HANDLE;
/// Raw SOCKETs.
#[stable(feature = "rust1", since = "1.0.0")]
pub type RawSocket = raw::SOCKET;
/// Extract raw handles.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRawHandle {
/// Extracts the raw handle, without taking any ownership.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_raw_handle(&self) -> RawHandle;
}
/// Construct I/O objects from raw handles.
#[stable(feature = "from_raw_os", since = "1.1.0")]
pub trait FromRawHandle {
/// Constructs a new I/O object from the specified raw handle.
///
/// This function will **consume ownership** of the handle given,
/// passing responsibility for closing the handle to the returned
/// object.
///
/// This function is also unsafe as the primitives currently returned
/// have the contract that they are the sole owner of the file
/// descriptor they are wrapping. Usage of this function could
/// accidentally allow violating this contract which can cause memory
/// unsafety in code that relies on it being true.
#[stable(feature = "from_raw_os", since = "1.1.0")]
unsafe fn from_raw_handle(handle: RawHandle) -> Self;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawHandle for fs::File {
fn as_raw_handle(&self) -> RawHandle {
self.as_inner().handle().raw() as RawHandle
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawHandle for fs::File {
unsafe fn from_raw_handle(handle: RawHandle) -> fs::File {
let handle = handle as ::libc::HANDLE;
fs::File::from_inner(sys::fs::File::from_inner(handle))
}
}
/// Extract raw sockets.
#[stable(feature = "rust1", since = "1.0.0")]
pub trait AsRawSocket {
/// Extracts the underlying raw socket from this object.
#[stable(feature = "rust1", since = "1.0.0")]
fn as_raw_socket(&self) -> RawSocket;
}
/// Create I/O objects from raw sockets.
#[stable(feature = "from_raw_os", since = "1.1.0")]
pub trait FromRawSocket {
/// Creates a new I/O object from the given raw socket.
///
/// This function will **consume ownership** of the socket provided and
/// it will be closed when the returned object goes out of scope.
///
/// This function is also unsafe as the primitives currently returned
/// have the contract that they are the sole owner of the file
/// descriptor they are wrapping. Usage of this function could
/// accidentally allow violating this contract which can cause memory
/// unsafety in code that relies on it being true.
#[stable(feature = "from_raw_os", since = "1.1.0")]
unsafe fn from_raw_socket(sock: RawSocket) -> Self;
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawSocket for net::TcpStream {
fn as_raw_socket(&self) -> RawSocket {
*self.as_inner().socket().as_inner()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawSocket for net::TcpListener {
fn as_raw_socket(&self) -> RawSocket {
*self.as_inner().socket().as_inner()
}
}
#[stable(feature = "rust1", since = "1.0.0")]
impl AsRawSocket for net::UdpSocket {
fn as_raw_socket(&self) -> RawSocket {
*self.as_inner().socket().as_inner()
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawSocket for net::TcpStream {
unsafe fn from_raw_socket(sock: RawSocket) -> net::TcpStream {
let sock = sys::net::Socket::from_inner(sock);
net::TcpStream::from_inner(sys_common::net::TcpStream::from_inner(sock))
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawSocket for net::TcpListener {
unsafe fn from_raw_socket(sock: RawSocket) -> net::TcpListener {
let sock = sys::net::Socket::from_inner(sock);
net::TcpListener::from_inner(sys_common::net::TcpListener::from_inner(sock))
}
}
#[stable(feature = "from_raw_os", since = "1.1.0")]
impl FromRawSocket for net::UdpSocket {
unsafe fn from_raw_socket(sock: RawSocket) -> net::UdpSocket {
let sock = sys::net::Socket::from_inner(sock);
net::UdpSocket::from_inner(sys_common::net::UdpSocket::from_inner(sock))
}
} | // 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 | random_line_split |
hud.rs | use std::result;
use toml;
use sdl2::rect::Rect;
#[derive(Debug)]
pub enum | {
SymbolNotFound,
InvalidSpec,
}
pub type HudResult<T> = result::Result<T, HudError>;
pub struct Hud {
pub health: Rect,
pub speed: Rect,
pub engine: Rect,
pub tyres: Rect,
pub armour: Rect,
pub letter: Rect,
pub money: Rect,
}
impl Hud {
fn get_rect(symbol_table: &toml::value::Table, name: &str, width: i32, height: i32) -> HudResult<Rect> {
let symbol = symbol_table.get(name).ok_or(HudError::SymbolNotFound)?
.as_table().ok_or(HudError::InvalidSpec)?;
let x = symbol.get("x").ok_or(HudError::InvalidSpec)?.
as_integer().ok_or(HudError::InvalidSpec)? as i32;
let y = symbol.get("y").ok_or(HudError::InvalidSpec)?.
as_integer().ok_or(HudError::InvalidSpec)? as i32;
Ok(Rect::new(x * width, y * height, width as u32, height as u32))
}
pub fn new(table: toml::value::Table) -> HudResult<Self> {
let symbol_width = table.get("symbol_width").ok_or(HudError::InvalidSpec)?
.as_integer().ok_or(HudError::InvalidSpec)? as i32;
let symbol_height = table.get("symbol_height").ok_or(HudError::InvalidSpec)?
.as_integer().ok_or(HudError::InvalidSpec)? as i32;
let symbol_table = table.get("symbols").ok_or(HudError::InvalidSpec)?
.as_table().ok_or(HudError::InvalidSpec)?;
Ok(Hud {
health: Self::get_rect(symbol_table, "Health", symbol_width, symbol_height)?,
speed: Self::get_rect(symbol_table, "Speed", symbol_width, symbol_height)?,
engine: Self::get_rect(symbol_table, "Engine", symbol_width, symbol_height)?,
tyres: Self::get_rect(symbol_table, "Tyres", symbol_width, symbol_height)?,
armour: Self::get_rect(symbol_table, "Armour", symbol_width, symbol_height)?,
letter: Self::get_rect(symbol_table, "Letter", symbol_width, symbol_height)?,
money: Self::get_rect(symbol_table, "Money", symbol_width, symbol_height)?,
})
}
}
| HudError | identifier_name |
hud.rs | use std::result;
use toml;
use sdl2::rect::Rect;
#[derive(Debug)]
pub enum HudError {
SymbolNotFound,
InvalidSpec,
}
pub type HudResult<T> = result::Result<T, HudError>;
pub struct Hud {
pub health: Rect,
pub speed: Rect,
pub engine: Rect,
pub tyres: Rect,
pub armour: Rect,
pub letter: Rect,
pub money: Rect,
}
impl Hud {
fn get_rect(symbol_table: &toml::value::Table, name: &str, width: i32, height: i32) -> HudResult<Rect> {
let symbol = symbol_table.get(name).ok_or(HudError::SymbolNotFound)?
.as_table().ok_or(HudError::InvalidSpec)?;
let x = symbol.get("x").ok_or(HudError::InvalidSpec)?.
as_integer().ok_or(HudError::InvalidSpec)? as i32;
let y = symbol.get("y").ok_or(HudError::InvalidSpec)?. | Ok(Rect::new(x * width, y * height, width as u32, height as u32))
}
pub fn new(table: toml::value::Table) -> HudResult<Self> {
let symbol_width = table.get("symbol_width").ok_or(HudError::InvalidSpec)?
.as_integer().ok_or(HudError::InvalidSpec)? as i32;
let symbol_height = table.get("symbol_height").ok_or(HudError::InvalidSpec)?
.as_integer().ok_or(HudError::InvalidSpec)? as i32;
let symbol_table = table.get("symbols").ok_or(HudError::InvalidSpec)?
.as_table().ok_or(HudError::InvalidSpec)?;
Ok(Hud {
health: Self::get_rect(symbol_table, "Health", symbol_width, symbol_height)?,
speed: Self::get_rect(symbol_table, "Speed", symbol_width, symbol_height)?,
engine: Self::get_rect(symbol_table, "Engine", symbol_width, symbol_height)?,
tyres: Self::get_rect(symbol_table, "Tyres", symbol_width, symbol_height)?,
armour: Self::get_rect(symbol_table, "Armour", symbol_width, symbol_height)?,
letter: Self::get_rect(symbol_table, "Letter", symbol_width, symbol_height)?,
money: Self::get_rect(symbol_table, "Money", symbol_width, symbol_height)?,
})
}
} | as_integer().ok_or(HudError::InvalidSpec)? as i32;
| random_line_split |
add_member.rs | use std::collections::HashMap;
use crate::internal::prelude::*;
use crate::model::id::RoleId;
/// A builder to add parameters when using [`GuildId::add_member`].
///
/// [`GuildId::add_member`]: crate::model::id::GuildId::add_member
#[derive(Clone, Debug, Default)]
pub struct AddMember(pub HashMap<&'static str, Value>);
impl AddMember {
/// Sets the OAuth2 access token for this request.
///
/// Requires the access token to have the `guilds.join` scope granted.
pub fn access_token(&mut self, access_token: impl ToString) -> &mut Self {
self.0.insert("access_token", Value::String(access_token.to_string()));
self
}
/// Sets the member's nickname.
///
/// Requires the [Manage Nicknames] permission.
///
/// [Manage Nicknames]: crate::model::permissions::Permissions::MANAGE_NICKNAMES
pub fn nickname(&mut self, nickname: impl ToString) -> &mut Self {
self.0.insert("nick", Value::String(nickname.to_string()));
self
}
/// Sets the list of roles that the member should have.
///
/// Requires the [Manage Roles] permission.
///
/// [Manage Roles]: crate::model::permissions::Permissions::MANAGE_ROLES
pub fn roles(&mut self, roles: impl IntoIterator<Item = impl AsRef<RoleId>>) -> &mut Self {
let roles = roles.into_iter().map(|x| Value::Number(Number::from(x.as_ref().0))).collect();
self.0.insert("roles", Value::Array(roles));
self
}
/// Whether to mute the member.
///
/// Requires the [Mute Members] permission.
///
/// [Mute Members]: crate::model::permissions::Permissions::MUTE_MEMBERS
pub fn mute(&mut self, mute: bool) -> &mut Self {
self.0.insert("mute", Value::Bool(mute));
self
}
/// Whether to deafen the member.
///
/// Requires the [Deafen Members] permission.
///
/// [Deafen Members]: crate::model::permissions::Permissions::DEAFEN_MEMBERS
pub fn | (&mut self, deafen: bool) -> &mut Self {
self.0.insert("deaf", Value::Bool(deafen));
self
}
}
| deafen | identifier_name |
add_member.rs | use std::collections::HashMap;
use crate::internal::prelude::*;
use crate::model::id::RoleId;
/// A builder to add parameters when using [`GuildId::add_member`].
///
/// [`GuildId::add_member`]: crate::model::id::GuildId::add_member
#[derive(Clone, Debug, Default)]
pub struct AddMember(pub HashMap<&'static str, Value>);
impl AddMember {
/// Sets the OAuth2 access token for this request.
///
/// Requires the access token to have the `guilds.join` scope granted.
pub fn access_token(&mut self, access_token: impl ToString) -> &mut Self {
self.0.insert("access_token", Value::String(access_token.to_string()));
self
}
/// Sets the member's nickname.
///
/// Requires the [Manage Nicknames] permission.
///
/// [Manage Nicknames]: crate::model::permissions::Permissions::MANAGE_NICKNAMES
pub fn nickname(&mut self, nickname: impl ToString) -> &mut Self {
self.0.insert("nick", Value::String(nickname.to_string()));
self
}
/// Sets the list of roles that the member should have.
///
/// Requires the [Manage Roles] permission.
///
/// [Manage Roles]: crate::model::permissions::Permissions::MANAGE_ROLES
pub fn roles(&mut self, roles: impl IntoIterator<Item = impl AsRef<RoleId>>) -> &mut Self {
let roles = roles.into_iter().map(|x| Value::Number(Number::from(x.as_ref().0))).collect();
self.0.insert("roles", Value::Array(roles));
self
}
/// Whether to mute the member.
/// | ///
/// [Mute Members]: crate::model::permissions::Permissions::MUTE_MEMBERS
pub fn mute(&mut self, mute: bool) -> &mut Self {
self.0.insert("mute", Value::Bool(mute));
self
}
/// Whether to deafen the member.
///
/// Requires the [Deafen Members] permission.
///
/// [Deafen Members]: crate::model::permissions::Permissions::DEAFEN_MEMBERS
pub fn deafen(&mut self, deafen: bool) -> &mut Self {
self.0.insert("deaf", Value::Bool(deafen));
self
}
} | /// Requires the [Mute Members] permission. | random_line_split |
pat-at-same-name-both.rs | // Test that `binding @ subpat` acts as a product context with respect to duplicate binding names.
// The code that is tested here lives in resolve (see `resolve_pattern_inner`).
fn main() {
fn | (a @ a @ a: ()) {}
//~^ ERROR identifier `a` is bound more than once in this parameter list
//~| ERROR identifier `a` is bound more than once in this parameter list
match Ok(0) {
Ok(a @ b @ a)
//~^ ERROR identifier `a` is bound more than once in the same pattern
| Err(a @ b @ a)
//~^ ERROR identifier `a` is bound more than once in the same pattern
=> {}
}
let a @ a @ a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
//~| ERROR identifier `a` is bound more than once in the same pattern
let ref a @ ref a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
let ref mut a @ ref mut a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
let a @ (Ok(a) | Err(a)) = Ok(());
//~^ ERROR identifier `a` is bound more than once in the same pattern
//~| ERROR identifier `a` is bound more than once in the same pattern
}
| f | identifier_name |
pat-at-same-name-both.rs | // Test that `binding @ subpat` acts as a product context with respect to duplicate binding names.
// The code that is tested here lives in resolve (see `resolve_pattern_inner`).
fn main() {
fn f(a @ a @ a: ()) {}
//~^ ERROR identifier `a` is bound more than once in this parameter list
//~| ERROR identifier `a` is bound more than once in this parameter list
match Ok(0) {
Ok(a @ b @ a)
//~^ ERROR identifier `a` is bound more than once in the same pattern
| Err(a @ b @ a)
//~^ ERROR identifier `a` is bound more than once in the same pattern
=> {}
}
let a @ a @ a = (); | //~| ERROR identifier `a` is bound more than once in the same pattern
let ref a @ ref a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
let ref mut a @ ref mut a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
let a @ (Ok(a) | Err(a)) = Ok(());
//~^ ERROR identifier `a` is bound more than once in the same pattern
//~| ERROR identifier `a` is bound more than once in the same pattern
} | //~^ ERROR identifier `a` is bound more than once in the same pattern | random_line_split |
pat-at-same-name-both.rs | // Test that `binding @ subpat` acts as a product context with respect to duplicate binding names.
// The code that is tested here lives in resolve (see `resolve_pattern_inner`).
fn main() {
fn f(a @ a @ a: ()) {}
//~^ ERROR identifier `a` is bound more than once in this parameter list
//~| ERROR identifier `a` is bound more than once in this parameter list
match Ok(0) {
Ok(a @ b @ a)
//~^ ERROR identifier `a` is bound more than once in the same pattern
| Err(a @ b @ a)
//~^ ERROR identifier `a` is bound more than once in the same pattern
=> |
}
let a @ a @ a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
//~| ERROR identifier `a` is bound more than once in the same pattern
let ref a @ ref a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
let ref mut a @ ref mut a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
let a @ (Ok(a) | Err(a)) = Ok(());
//~^ ERROR identifier `a` is bound more than once in the same pattern
//~| ERROR identifier `a` is bound more than once in the same pattern
}
| {} | conditional_block |
pat-at-same-name-both.rs | // Test that `binding @ subpat` acts as a product context with respect to duplicate binding names.
// The code that is tested here lives in resolve (see `resolve_pattern_inner`).
fn main() {
fn f(a @ a @ a: ()) |
//~^ ERROR identifier `a` is bound more than once in this parameter list
//~| ERROR identifier `a` is bound more than once in this parameter list
match Ok(0) {
Ok(a @ b @ a)
//~^ ERROR identifier `a` is bound more than once in the same pattern
| Err(a @ b @ a)
//~^ ERROR identifier `a` is bound more than once in the same pattern
=> {}
}
let a @ a @ a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
//~| ERROR identifier `a` is bound more than once in the same pattern
let ref a @ ref a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
let ref mut a @ ref mut a = ();
//~^ ERROR identifier `a` is bound more than once in the same pattern
let a @ (Ok(a) | Err(a)) = Ok(());
//~^ ERROR identifier `a` is bound more than once in the same pattern
//~| ERROR identifier `a` is bound more than once in the same pattern
}
| {} | identifier_body |
mod.rs | use super::i3::*;
use std::borrow::Cow;
mod clock;
mod shell;
mod florp_blarg;
pub use self::clock::*;
pub use self::shell::*;
pub use self::florp_blarg::*;
/// A type that produces blocks of data.
/// BlockProducer can respond to mouse-events.
pub trait Widget {
/// Updates the state of the producer and returns the new block data.
fn update<'a>(&'a mut self) -> Cow<'a, Block>;
/// Gets the name of the block, if available.
fn get_name(&self) -> Option<&str> {
None
}
/// Gets the instance name of the block, if available.
fn get_instance(&self) -> Option<&str> {
None
}
/// Handles a click event.
fn handle_event(&mut self, event: Button) {}
}
impl Widget for Block {
fn update<'a>(&'a mut self) -> Cow<'a, Block> |
}
impl<T: Into<String> + Clone + Send +'static> Widget for T {
fn update(&mut self) -> Cow<'static, Block> {
Cow::Owned(Block {
full_text: self.clone().into(),
..Block::default()
})
}
}
| {
Cow::Borrowed(self)
} | identifier_body |
mod.rs | use super::i3::*;
use std::borrow::Cow;
mod clock;
mod shell;
mod florp_blarg;
pub use self::clock::*;
pub use self::shell::*;
pub use self::florp_blarg::*;
/// A type that produces blocks of data.
/// BlockProducer can respond to mouse-events.
pub trait Widget {
/// Updates the state of the producer and returns the new block data.
fn update<'a>(&'a mut self) -> Cow<'a, Block>;
/// Gets the name of the block, if available.
fn get_name(&self) -> Option<&str> {
None
}
/// Gets the instance name of the block, if available.
fn get_instance(&self) -> Option<&str> {
None
}
/// Handles a click event.
fn handle_event(&mut self, event: Button) {}
}
impl Widget for Block {
fn | <'a>(&'a mut self) -> Cow<'a, Block> {
Cow::Borrowed(self)
}
}
impl<T: Into<String> + Clone + Send +'static> Widget for T {
fn update(&mut self) -> Cow<'static, Block> {
Cow::Owned(Block {
full_text: self.clone().into(),
..Block::default()
})
}
}
| update | identifier_name |
mod.rs | use super::i3::*;
use std::borrow::Cow;
mod clock;
mod shell;
mod florp_blarg;
|
/// A type that produces blocks of data.
/// BlockProducer can respond to mouse-events.
pub trait Widget {
/// Updates the state of the producer and returns the new block data.
fn update<'a>(&'a mut self) -> Cow<'a, Block>;
/// Gets the name of the block, if available.
fn get_name(&self) -> Option<&str> {
None
}
/// Gets the instance name of the block, if available.
fn get_instance(&self) -> Option<&str> {
None
}
/// Handles a click event.
fn handle_event(&mut self, event: Button) {}
}
impl Widget for Block {
fn update<'a>(&'a mut self) -> Cow<'a, Block> {
Cow::Borrowed(self)
}
}
impl<T: Into<String> + Clone + Send +'static> Widget for T {
fn update(&mut self) -> Cow<'static, Block> {
Cow::Owned(Block {
full_text: self.clone().into(),
..Block::default()
})
}
} | pub use self::clock::*;
pub use self::shell::*;
pub use self::florp_blarg::*; | random_line_split |
test_all_types.rs | #![no_main]
extern crate libfuzzer_sys;
extern crate capnp;
use capnp::{serialize, message};
use test_capnp::test_all_types;
pub mod test_capnp;
fn traverse(v: test_all_types::Reader) -> ::capnp::Result<()> {
v.get_int64_field();
v.get_float32_field();
v.get_float64_field();
v.get_text_field()?;
v.get_data_field()?;
v.get_struct_field()?;
v.get_enum_field()?;
let structs = v.get_struct_list()?;
for s in structs.iter() {
s.get_text_field()?;
s.get_data_field()?;
}
let bools = v.get_bool_list()?;
for idx in 0.. bools.len() {
bools.get(idx);
}
let enums = v.get_enum_list()?;
for idx in 0.. enums.len() {
enums.get(idx)?;
}
let int8s = v.get_int8_list()?;
for idx in 0.. int8s.len() {
int8s.get(idx);
}
Ok(())
}
fn try_go(mut data: &[u8]) -> ::capnp::Result<()> | list.set_with_caveats(0, root)?;
list.set_with_caveats(1, root)?;
}
traverse(root_builder.into_reader())?;
}
// init_root() will zero the previous value
let mut new_root = message.init_root::<test_all_types::Builder>();
new_root.set_struct_field(root)?;
Ok(())
}
#[export_name="rust_fuzzer_test_input"]
pub extern fn go(data: &[u8]) {
let _ = try_go(data);
}
| {
let orig_data = data;
let message_reader = serialize::read_message(
&mut data,
*message::ReaderOptions::new().traversal_limit_in_words(4 * 1024))?;
assert!(orig_data.len() > data.len());
let root: test_all_types::Reader = try!(message_reader.get_root());
root.total_size()?;
traverse(root)?;
let mut message = message::Builder::new_default();
message.set_root(root)?;
{
let mut root_builder = message.get_root::<test_all_types::Builder>()?;
root_builder.total_size()?;
root_builder.set_struct_field(root)?;
{
let list = root_builder.reborrow().init_struct_list(2); | identifier_body |
test_all_types.rs | #![no_main]
extern crate libfuzzer_sys;
extern crate capnp;
use capnp::{serialize, message};
use test_capnp::test_all_types;
pub mod test_capnp;
fn traverse(v: test_all_types::Reader) -> ::capnp::Result<()> {
v.get_int64_field();
v.get_float32_field();
v.get_float64_field();
v.get_text_field()?;
v.get_data_field()?;
v.get_struct_field()?;
v.get_enum_field()?;
let structs = v.get_struct_list()?;
for s in structs.iter() {
s.get_text_field()?;
s.get_data_field()?;
}
let bools = v.get_bool_list()?;
for idx in 0.. bools.len() {
bools.get(idx);
}
let enums = v.get_enum_list()?;
for idx in 0.. enums.len() {
enums.get(idx)?;
}
let int8s = v.get_int8_list()?;
for idx in 0.. int8s.len() {
int8s.get(idx);
}
Ok(())
}
fn try_go(mut data: &[u8]) -> ::capnp::Result<()> {
let orig_data = data;
let message_reader = serialize::read_message(
&mut data,
*message::ReaderOptions::new().traversal_limit_in_words(4 * 1024))?;
assert!(orig_data.len() > data.len());
let root: test_all_types::Reader = try!(message_reader.get_root());
root.total_size()?;
traverse(root)?;
let mut message = message::Builder::new_default();
message.set_root(root)?;
{
let mut root_builder = message.get_root::<test_all_types::Builder>()?;
root_builder.total_size()?;
root_builder.set_struct_field(root)?;
{
let list = root_builder.reborrow().init_struct_list(2);
list.set_with_caveats(0, root)?;
list.set_with_caveats(1, root)?;
} | traverse(root_builder.into_reader())?;
}
// init_root() will zero the previous value
let mut new_root = message.init_root::<test_all_types::Builder>();
new_root.set_struct_field(root)?;
Ok(())
}
#[export_name="rust_fuzzer_test_input"]
pub extern fn go(data: &[u8]) {
let _ = try_go(data);
} | random_line_split |
|
test_all_types.rs | #![no_main]
extern crate libfuzzer_sys;
extern crate capnp;
use capnp::{serialize, message};
use test_capnp::test_all_types;
pub mod test_capnp;
fn traverse(v: test_all_types::Reader) -> ::capnp::Result<()> {
v.get_int64_field();
v.get_float32_field();
v.get_float64_field();
v.get_text_field()?;
v.get_data_field()?;
v.get_struct_field()?;
v.get_enum_field()?;
let structs = v.get_struct_list()?;
for s in structs.iter() {
s.get_text_field()?;
s.get_data_field()?;
}
let bools = v.get_bool_list()?;
for idx in 0.. bools.len() {
bools.get(idx);
}
let enums = v.get_enum_list()?;
for idx in 0.. enums.len() {
enums.get(idx)?;
}
let int8s = v.get_int8_list()?;
for idx in 0.. int8s.len() {
int8s.get(idx);
}
Ok(())
}
fn try_go(mut data: &[u8]) -> ::capnp::Result<()> {
let orig_data = data;
let message_reader = serialize::read_message(
&mut data,
*message::ReaderOptions::new().traversal_limit_in_words(4 * 1024))?;
assert!(orig_data.len() > data.len());
let root: test_all_types::Reader = try!(message_reader.get_root());
root.total_size()?;
traverse(root)?;
let mut message = message::Builder::new_default();
message.set_root(root)?;
{
let mut root_builder = message.get_root::<test_all_types::Builder>()?;
root_builder.total_size()?;
root_builder.set_struct_field(root)?;
{
let list = root_builder.reborrow().init_struct_list(2);
list.set_with_caveats(0, root)?;
list.set_with_caveats(1, root)?;
}
traverse(root_builder.into_reader())?;
}
// init_root() will zero the previous value
let mut new_root = message.init_root::<test_all_types::Builder>();
new_root.set_struct_field(root)?;
Ok(())
}
#[export_name="rust_fuzzer_test_input"]
pub extern fn | (data: &[u8]) {
let _ = try_go(data);
}
| go | identifier_name |
mod.rs | // Copyright (c) 2013-2015 Sandstorm Development Group, Inc. and contributors
// Licensed under the MIT License:
// | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! Implementation details that should never be directly used by clients.
//!
//! We still need to make this module visible so that generated code can use it.
pub mod arena;
pub mod capability;
mod primitive;
pub mod layout;
mod mask;
pub mod units;
mod read_limiter;
mod zero;
#[cfg(test)]
mod layout_test; | // Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights | random_line_split |
htmltablesectionelement.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 cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::{self, HTMLTableSectionElementMethods};
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::error::{ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::root::{DomRoot, LayoutDom, RootedReference};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{Element, RawLayoutElementHelpers};
use dom::htmlcollection::{CollectionFilter, HTMLCollection};
use dom::htmlelement::HTMLElement;
use dom::htmltablerowelement::HTMLTableRowElement;
use dom::node::{Node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use style::attr::AttrValue;
#[dom_struct]
pub struct HTMLTableSectionElement {
htmlelement: HTMLElement,
}
impl HTMLTableSectionElement {
fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document)
-> HTMLTableSectionElement {
HTMLTableSectionElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn | (local_name: LocalName, prefix: Option<Prefix>, document: &Document)
-> DomRoot<HTMLTableSectionElement> {
Node::reflect_node(Box::new(HTMLTableSectionElement::new_inherited(local_name, prefix, document)),
document,
HTMLTableSectionElementBinding::Wrap)
}
}
#[derive(JSTraceable)]
struct RowsFilter;
impl CollectionFilter for RowsFilter {
fn filter(&self, elem: &Element, root: &Node) -> bool {
elem.is::<HTMLTableRowElement>() &&
elem.upcast::<Node>().GetParentNode().r() == Some(root)
}
}
impl HTMLTableSectionElementMethods for HTMLTableSectionElement {
// https://html.spec.whatwg.org/multipage/#dom-tbody-rows
fn Rows(&self) -> DomRoot<HTMLCollection> {
HTMLCollection::create(&window_from_node(self), self.upcast(), Box::new(RowsFilter))
}
// https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow
fn InsertRow(&self, index: i32) -> Fallible<DomRoot<HTMLElement>> {
let node = self.upcast::<Node>();
node.insert_cell_or_row(
index,
|| self.Rows(),
|| HTMLTableRowElement::new(local_name!("tr"), None, &node.owner_doc()))
}
// https://html.spec.whatwg.org/multipage/#dom-tbody-deleterow
fn DeleteRow(&self, index: i32) -> ErrorResult {
let node = self.upcast::<Node>();
node.delete_cell_or_row(
index,
|| self.Rows(),
|n| n.is::<HTMLTableRowElement>())
}
}
pub trait HTMLTableSectionElementLayoutHelpers {
fn get_background_color(&self) -> Option<RGBA>;
}
#[allow(unsafe_code)]
impl HTMLTableSectionElementLayoutHelpers for LayoutDom<HTMLTableSectionElement> {
fn get_background_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("bgcolor"))
.and_then(AttrValue::as_color)
.cloned()
}
}
}
impl VirtualMethods for HTMLTableSectionElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue {
match *local_name {
local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
| new | identifier_name |
htmltablesectionelement.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 |
use cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::{self, HTMLTableSectionElementMethods};
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::error::{ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::root::{DomRoot, LayoutDom, RootedReference};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{Element, RawLayoutElementHelpers};
use dom::htmlcollection::{CollectionFilter, HTMLCollection};
use dom::htmlelement::HTMLElement;
use dom::htmltablerowelement::HTMLTableRowElement;
use dom::node::{Node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use style::attr::AttrValue;
#[dom_struct]
pub struct HTMLTableSectionElement {
htmlelement: HTMLElement,
}
impl HTMLTableSectionElement {
fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document)
-> HTMLTableSectionElement {
HTMLTableSectionElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document)
-> DomRoot<HTMLTableSectionElement> {
Node::reflect_node(Box::new(HTMLTableSectionElement::new_inherited(local_name, prefix, document)),
document,
HTMLTableSectionElementBinding::Wrap)
}
}
#[derive(JSTraceable)]
struct RowsFilter;
impl CollectionFilter for RowsFilter {
fn filter(&self, elem: &Element, root: &Node) -> bool {
elem.is::<HTMLTableRowElement>() &&
elem.upcast::<Node>().GetParentNode().r() == Some(root)
}
}
impl HTMLTableSectionElementMethods for HTMLTableSectionElement {
// https://html.spec.whatwg.org/multipage/#dom-tbody-rows
fn Rows(&self) -> DomRoot<HTMLCollection> {
HTMLCollection::create(&window_from_node(self), self.upcast(), Box::new(RowsFilter))
}
// https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow
fn InsertRow(&self, index: i32) -> Fallible<DomRoot<HTMLElement>> {
let node = self.upcast::<Node>();
node.insert_cell_or_row(
index,
|| self.Rows(),
|| HTMLTableRowElement::new(local_name!("tr"), None, &node.owner_doc()))
}
// https://html.spec.whatwg.org/multipage/#dom-tbody-deleterow
fn DeleteRow(&self, index: i32) -> ErrorResult {
let node = self.upcast::<Node>();
node.delete_cell_or_row(
index,
|| self.Rows(),
|n| n.is::<HTMLTableRowElement>())
}
}
pub trait HTMLTableSectionElementLayoutHelpers {
fn get_background_color(&self) -> Option<RGBA>;
}
#[allow(unsafe_code)]
impl HTMLTableSectionElementLayoutHelpers for LayoutDom<HTMLTableSectionElement> {
fn get_background_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("bgcolor"))
.and_then(AttrValue::as_color)
.cloned()
}
}
}
impl VirtualMethods for HTMLTableSectionElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue {
match *local_name {
local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
} | * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | random_line_split |
htmltablesectionelement.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 cssparser::RGBA;
use dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding::{self, HTMLTableSectionElementMethods};
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::error::{ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::root::{DomRoot, LayoutDom, RootedReference};
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{Element, RawLayoutElementHelpers};
use dom::htmlcollection::{CollectionFilter, HTMLCollection};
use dom::htmlelement::HTMLElement;
use dom::htmltablerowelement::HTMLTableRowElement;
use dom::node::{Node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use dom_struct::dom_struct;
use html5ever::{LocalName, Prefix};
use style::attr::AttrValue;
#[dom_struct]
pub struct HTMLTableSectionElement {
htmlelement: HTMLElement,
}
impl HTMLTableSectionElement {
fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document)
-> HTMLTableSectionElement {
HTMLTableSectionElement {
htmlelement: HTMLElement::new_inherited(local_name, prefix, document),
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document)
-> DomRoot<HTMLTableSectionElement> {
Node::reflect_node(Box::new(HTMLTableSectionElement::new_inherited(local_name, prefix, document)),
document,
HTMLTableSectionElementBinding::Wrap)
}
}
#[derive(JSTraceable)]
struct RowsFilter;
impl CollectionFilter for RowsFilter {
fn filter(&self, elem: &Element, root: &Node) -> bool {
elem.is::<HTMLTableRowElement>() &&
elem.upcast::<Node>().GetParentNode().r() == Some(root)
}
}
impl HTMLTableSectionElementMethods for HTMLTableSectionElement {
// https://html.spec.whatwg.org/multipage/#dom-tbody-rows
fn Rows(&self) -> DomRoot<HTMLCollection> |
// https://html.spec.whatwg.org/multipage/#dom-tbody-insertrow
fn InsertRow(&self, index: i32) -> Fallible<DomRoot<HTMLElement>> {
let node = self.upcast::<Node>();
node.insert_cell_or_row(
index,
|| self.Rows(),
|| HTMLTableRowElement::new(local_name!("tr"), None, &node.owner_doc()))
}
// https://html.spec.whatwg.org/multipage/#dom-tbody-deleterow
fn DeleteRow(&self, index: i32) -> ErrorResult {
let node = self.upcast::<Node>();
node.delete_cell_or_row(
index,
|| self.Rows(),
|n| n.is::<HTMLTableRowElement>())
}
}
pub trait HTMLTableSectionElementLayoutHelpers {
fn get_background_color(&self) -> Option<RGBA>;
}
#[allow(unsafe_code)]
impl HTMLTableSectionElementLayoutHelpers for LayoutDom<HTMLTableSectionElement> {
fn get_background_color(&self) -> Option<RGBA> {
unsafe {
(&*self.upcast::<Element>().unsafe_get())
.get_attr_for_layout(&ns!(), &local_name!("bgcolor"))
.and_then(AttrValue::as_color)
.cloned()
}
}
}
impl VirtualMethods for HTMLTableSectionElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn parse_plain_attribute(&self, local_name: &LocalName, value: DOMString) -> AttrValue {
match *local_name {
local_name!("bgcolor") => AttrValue::from_legacy_color(value.into()),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
| {
HTMLCollection::create(&window_from_node(self), self.upcast(), Box::new(RowsFilter))
} | identifier_body |
test_interop_data.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use apache_avro::Reader;
use std::{
collections::HashMap,
ffi::OsStr,
io::{BufReader, Read},
};
fn main() -> anyhow::Result<()> {
let mut expected_user_metadata: HashMap<String, Vec<u8>> = HashMap::new();
expected_user_metadata.insert("user_metadata".to_string(), b"someByteArray".to_vec());
let data_dir = std::fs::read_dir("../../build/interop/data/")
.expect("Unable to list the interop data directory");
let mut errors = Vec::new();
for entry in data_dir {
let path = entry
.expect("Unable to read the interop data directory's files")
.path();
if path.is_file() {
let ext = path.extension().and_then(OsStr::to_str).unwrap();
if ext == "avro" {
println!("Checking {:?}", &path);
let content = std::fs::File::open(&path)?;
let reader = Reader::new(BufReader::new(&content))?;
test_user_metadata(&reader, &expected_user_metadata);
for value in reader {
if let Err(e) = value |
}
}
}
}
if errors.is_empty() {
Ok(())
} else {
panic!(
"There were errors reading some.avro files:\n{}",
errors.join(", ")
);
}
}
fn test_user_metadata<R: Read>(
reader: &Reader<BufReader<R>>,
expected_user_metadata: &HashMap<String, Vec<u8>>,
) {
let user_metadata = reader.user_metadata();
if!user_metadata.is_empty() {
assert_eq!(user_metadata, expected_user_metadata);
}
}
| {
errors.push(format!(
"There is a problem with reading of '{:?}', \n {:?}\n",
&path, e
));
} | conditional_block |
test_interop_data.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use apache_avro::Reader;
use std::{
collections::HashMap,
ffi::OsStr,
io::{BufReader, Read},
};
fn main() -> anyhow::Result<()> | let reader = Reader::new(BufReader::new(&content))?;
test_user_metadata(&reader, &expected_user_metadata);
for value in reader {
if let Err(e) = value {
errors.push(format!(
"There is a problem with reading of '{:?}', \n {:?}\n",
&path, e
));
}
}
}
}
}
if errors.is_empty() {
Ok(())
} else {
panic!(
"There were errors reading some.avro files:\n{}",
errors.join(", ")
);
}
}
fn test_user_metadata<R: Read>(
reader: &Reader<BufReader<R>>,
expected_user_metadata: &HashMap<String, Vec<u8>>,
) {
let user_metadata = reader.user_metadata();
if!user_metadata.is_empty() {
assert_eq!(user_metadata, expected_user_metadata);
}
}
| {
let mut expected_user_metadata: HashMap<String, Vec<u8>> = HashMap::new();
expected_user_metadata.insert("user_metadata".to_string(), b"someByteArray".to_vec());
let data_dir = std::fs::read_dir("../../build/interop/data/")
.expect("Unable to list the interop data directory");
let mut errors = Vec::new();
for entry in data_dir {
let path = entry
.expect("Unable to read the interop data directory's files")
.path();
if path.is_file() {
let ext = path.extension().and_then(OsStr::to_str).unwrap();
if ext == "avro" {
println!("Checking {:?}", &path);
let content = std::fs::File::open(&path)?; | identifier_body |
test_interop_data.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use apache_avro::Reader;
use std::{
collections::HashMap,
ffi::OsStr,
io::{BufReader, Read},
};
fn | () -> anyhow::Result<()> {
let mut expected_user_metadata: HashMap<String, Vec<u8>> = HashMap::new();
expected_user_metadata.insert("user_metadata".to_string(), b"someByteArray".to_vec());
let data_dir = std::fs::read_dir("../../build/interop/data/")
.expect("Unable to list the interop data directory");
let mut errors = Vec::new();
for entry in data_dir {
let path = entry
.expect("Unable to read the interop data directory's files")
.path();
if path.is_file() {
let ext = path.extension().and_then(OsStr::to_str).unwrap();
if ext == "avro" {
println!("Checking {:?}", &path);
let content = std::fs::File::open(&path)?;
let reader = Reader::new(BufReader::new(&content))?;
test_user_metadata(&reader, &expected_user_metadata);
for value in reader {
if let Err(e) = value {
errors.push(format!(
"There is a problem with reading of '{:?}', \n {:?}\n",
&path, e
));
}
}
}
}
}
if errors.is_empty() {
Ok(())
} else {
panic!(
"There were errors reading some.avro files:\n{}",
errors.join(", ")
);
}
}
fn test_user_metadata<R: Read>(
reader: &Reader<BufReader<R>>,
expected_user_metadata: &HashMap<String, Vec<u8>>,
) {
let user_metadata = reader.user_metadata();
if!user_metadata.is_empty() {
assert_eq!(user_metadata, expected_user_metadata);
}
}
| main | identifier_name |
test_interop_data.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the | // "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use apache_avro::Reader;
use std::{
collections::HashMap,
ffi::OsStr,
io::{BufReader, Read},
};
fn main() -> anyhow::Result<()> {
let mut expected_user_metadata: HashMap<String, Vec<u8>> = HashMap::new();
expected_user_metadata.insert("user_metadata".to_string(), b"someByteArray".to_vec());
let data_dir = std::fs::read_dir("../../build/interop/data/")
.expect("Unable to list the interop data directory");
let mut errors = Vec::new();
for entry in data_dir {
let path = entry
.expect("Unable to read the interop data directory's files")
.path();
if path.is_file() {
let ext = path.extension().and_then(OsStr::to_str).unwrap();
if ext == "avro" {
println!("Checking {:?}", &path);
let content = std::fs::File::open(&path)?;
let reader = Reader::new(BufReader::new(&content))?;
test_user_metadata(&reader, &expected_user_metadata);
for value in reader {
if let Err(e) = value {
errors.push(format!(
"There is a problem with reading of '{:?}', \n {:?}\n",
&path, e
));
}
}
}
}
}
if errors.is_empty() {
Ok(())
} else {
panic!(
"There were errors reading some.avro files:\n{}",
errors.join(", ")
);
}
}
fn test_user_metadata<R: Read>(
reader: &Reader<BufReader<R>>,
expected_user_metadata: &HashMap<String, Vec<u8>>,
) {
let user_metadata = reader.user_metadata();
if!user_metadata.is_empty() {
assert_eq!(user_metadata, expected_user_metadata);
}
} | random_line_split |
|
day24.rs | #[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashSet;
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let filename = matches.value_of("FILE").unwrap();
let mut file = match File::open(filename) {
Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)),
Ok(file) => file,
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)),
Ok(_) => println!("Read file {}", filename),
}
let packages = parse_input(s.trim().split('\n').collect());
let sum = packages.iter().fold(0, |sum, p| sum + p);
split_into_3(&packages, sum / 3);
split_into_4(&packages, sum / 4);
}
fn split_into_4(packages : &Vec<i32>, target : i32) {
let mut all : HashSet<Vec<i32>> = HashSet::new();
let mut min_length = std::usize::MAX;
let groupings = generate_sum(&packages, target, Vec::new());
for g in groupings {
if g.len() <= min_length {
let available_packages = packages.clone().into_iter().filter(|x|!g.contains(x)).collect();
let second_grouping = generate_sum(&available_packages, target, Vec::new());
for g2 in second_grouping {
let available_packages_3rd : Vec<i32> = packages.clone().into_iter().filter(|x|!g.contains(x) &&!g2.contains(x)).collect();
// Shouldn't generate all 2nd groups...just make sure 1 exists
let third_group_exists = sum_exists(&available_packages_3rd, target);
if third_group_exists {
all.insert(g.clone());
min_length = std::cmp::min(min_length, g.len());
}
}
}
}
let mut min_qe = std::usize::MAX;
for a in all {
if a.len() == min_length {
let qe : usize = a.iter().fold(1, |qe, x| qe * *x as usize);
min_qe = std::cmp::min(qe, min_qe);
}
}
println!("Part 2: Min QE = {}", min_qe);
}
fn split_into_3(packages : &Vec<i32>, target : i32) {
let mut all : HashSet<Vec<i32>> = HashSet::new();
let mut min_length = std::usize::MAX;
let groupings = generate_sum(&packages, target, Vec::new());
for g in groupings {
if g.len() <= min_length {
let available_packages = packages.clone().into_iter().filter(|x|!g.contains(x)).collect();
if sum_exists(&available_packages, target) {
all.insert(g.clone());
min_length = std::cmp::min(min_length, g.len());
}
}
}
let mut min_qe = std::usize::MAX;
for a in all {
if a.len() == min_length {
let qe : usize = a.iter().fold(1, |qe, x| qe * *x as usize);
min_qe = std::cmp::min(qe, min_qe);
}
}
println!("Part 1: Min QE = {}", min_qe);
}
fn sum_exists(packages : &Vec<i32>, target : i32) -> bool {
let mut exists = false;
for (i,p) in packages.iter().enumerate() {
if target - p == 0 {
exists = true;
} else if target - p > 0{
let new_vec = packages[i+1..packages.len()].to_vec();
exists = sum_exists(&new_vec, target - p);
}
if exists {
break;
}
}
exists
}
fn generate_sum(packages : &Vec<i32>, target : i32, potential : Vec<i32>) -> Vec<Vec<i32>> {
let mut groupings = Vec::new();
for (i,p) in packages.iter().enumerate() {
if target - p == 0 {
let mut group = potential.clone();
group.push(*p);
groupings.push(group.clone());
//println!("Found! {:?}", group);
} else if target - p > 0{
let new_vec = packages[i+1..packages.len()].to_vec();
let mut group = potential.clone();
group.push(*p);
groupings.append(&mut generate_sum(&new_vec, target - p, group));
}
}
groupings |
fn parse_input(input : Vec<&str>) -> Vec<i32> {
let mut v = Vec::new();
for s in input {
if s.trim().len() > 0 {
v.push(s.parse::<i32>().unwrap());
}
}
v.sort_by(|a,b| b.cmp(a));
v
} | }
| random_line_split |
day24.rs | #[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashSet;
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let filename = matches.value_of("FILE").unwrap();
let mut file = match File::open(filename) {
Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)),
Ok(file) => file,
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)),
Ok(_) => println!("Read file {}", filename),
}
let packages = parse_input(s.trim().split('\n').collect());
let sum = packages.iter().fold(0, |sum, p| sum + p);
split_into_3(&packages, sum / 3);
split_into_4(&packages, sum / 4);
}
fn split_into_4(packages : &Vec<i32>, target : i32) {
let mut all : HashSet<Vec<i32>> = HashSet::new();
let mut min_length = std::usize::MAX;
let groupings = generate_sum(&packages, target, Vec::new());
for g in groupings {
if g.len() <= min_length {
let available_packages = packages.clone().into_iter().filter(|x|!g.contains(x)).collect();
let second_grouping = generate_sum(&available_packages, target, Vec::new());
for g2 in second_grouping {
let available_packages_3rd : Vec<i32> = packages.clone().into_iter().filter(|x|!g.contains(x) &&!g2.contains(x)).collect();
// Shouldn't generate all 2nd groups...just make sure 1 exists
let third_group_exists = sum_exists(&available_packages_3rd, target);
if third_group_exists {
all.insert(g.clone());
min_length = std::cmp::min(min_length, g.len());
}
}
}
}
let mut min_qe = std::usize::MAX;
for a in all {
if a.len() == min_length {
let qe : usize = a.iter().fold(1, |qe, x| qe * *x as usize);
min_qe = std::cmp::min(qe, min_qe);
}
}
println!("Part 2: Min QE = {}", min_qe);
}
fn split_into_3(packages : &Vec<i32>, target : i32) | let qe : usize = a.iter().fold(1, |qe, x| qe * *x as usize);
min_qe = std::cmp::min(qe, min_qe);
}
}
println!("Part 1: Min QE = {}", min_qe);
}
fn sum_exists(packages : &Vec<i32>, target : i32) -> bool {
let mut exists = false;
for (i,p) in packages.iter().enumerate() {
if target - p == 0 {
exists = true;
} else if target - p > 0{
let new_vec = packages[i+1..packages.len()].to_vec();
exists = sum_exists(&new_vec, target - p);
}
if exists {
break;
}
}
exists
}
fn generate_sum(packages : &Vec<i32>, target : i32, potential : Vec<i32>) -> Vec<Vec<i32>> {
let mut groupings = Vec::new();
for (i,p) in packages.iter().enumerate() {
if target - p == 0 {
let mut group = potential.clone();
group.push(*p);
groupings.push(group.clone());
//println!("Found! {:?}", group);
} else if target - p > 0{
let new_vec = packages[i+1..packages.len()].to_vec();
let mut group = potential.clone();
group.push(*p);
groupings.append(&mut generate_sum(&new_vec, target - p, group));
}
}
groupings
}
fn parse_input(input : Vec<&str>) -> Vec<i32> {
let mut v = Vec::new();
for s in input {
if s.trim().len() > 0 {
v.push(s.parse::<i32>().unwrap());
}
}
v.sort_by(|a,b| b.cmp(a));
v
}
| {
let mut all : HashSet<Vec<i32>> = HashSet::new();
let mut min_length = std::usize::MAX;
let groupings = generate_sum(&packages, target, Vec::new());
for g in groupings {
if g.len() <= min_length {
let available_packages = packages.clone().into_iter().filter(|x| !g.contains(x)).collect();
if sum_exists(&available_packages, target) {
all.insert(g.clone());
min_length = std::cmp::min(min_length, g.len());
}
}
}
let mut min_qe = std::usize::MAX;
for a in all {
if a.len() == min_length { | identifier_body |
day24.rs | #[macro_use]
extern crate clap;
use clap::App;
extern crate regex;
use std::error::Error;
use std::fs::File;
use std::io::prelude::*;
use std::collections::HashSet;
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
let filename = matches.value_of("FILE").unwrap();
let mut file = match File::open(filename) {
Err(why) => panic!("Couldn't open {}: {}", filename, Error::description(&why)),
Ok(file) => file,
};
let mut s = String::new();
match file.read_to_string(&mut s) {
Err(why) => panic!("Couldn't read {}: {}", filename, Error::description(&why)),
Ok(_) => println!("Read file {}", filename),
}
let packages = parse_input(s.trim().split('\n').collect());
let sum = packages.iter().fold(0, |sum, p| sum + p);
split_into_3(&packages, sum / 3);
split_into_4(&packages, sum / 4);
}
fn split_into_4(packages : &Vec<i32>, target : i32) {
let mut all : HashSet<Vec<i32>> = HashSet::new();
let mut min_length = std::usize::MAX;
let groupings = generate_sum(&packages, target, Vec::new());
for g in groupings {
if g.len() <= min_length {
let available_packages = packages.clone().into_iter().filter(|x|!g.contains(x)).collect();
let second_grouping = generate_sum(&available_packages, target, Vec::new());
for g2 in second_grouping {
let available_packages_3rd : Vec<i32> = packages.clone().into_iter().filter(|x|!g.contains(x) &&!g2.contains(x)).collect();
// Shouldn't generate all 2nd groups...just make sure 1 exists
let third_group_exists = sum_exists(&available_packages_3rd, target);
if third_group_exists {
all.insert(g.clone());
min_length = std::cmp::min(min_length, g.len());
}
}
}
}
let mut min_qe = std::usize::MAX;
for a in all {
if a.len() == min_length {
let qe : usize = a.iter().fold(1, |qe, x| qe * *x as usize);
min_qe = std::cmp::min(qe, min_qe);
}
}
println!("Part 2: Min QE = {}", min_qe);
}
fn split_into_3(packages : &Vec<i32>, target : i32) {
let mut all : HashSet<Vec<i32>> = HashSet::new();
let mut min_length = std::usize::MAX;
let groupings = generate_sum(&packages, target, Vec::new());
for g in groupings {
if g.len() <= min_length {
let available_packages = packages.clone().into_iter().filter(|x|!g.contains(x)).collect();
if sum_exists(&available_packages, target) {
all.insert(g.clone());
min_length = std::cmp::min(min_length, g.len());
}
}
}
let mut min_qe = std::usize::MAX;
for a in all {
if a.len() == min_length {
let qe : usize = a.iter().fold(1, |qe, x| qe * *x as usize);
min_qe = std::cmp::min(qe, min_qe);
}
}
println!("Part 1: Min QE = {}", min_qe);
}
fn | (packages : &Vec<i32>, target : i32) -> bool {
let mut exists = false;
for (i,p) in packages.iter().enumerate() {
if target - p == 0 {
exists = true;
} else if target - p > 0{
let new_vec = packages[i+1..packages.len()].to_vec();
exists = sum_exists(&new_vec, target - p);
}
if exists {
break;
}
}
exists
}
fn generate_sum(packages : &Vec<i32>, target : i32, potential : Vec<i32>) -> Vec<Vec<i32>> {
let mut groupings = Vec::new();
for (i,p) in packages.iter().enumerate() {
if target - p == 0 {
let mut group = potential.clone();
group.push(*p);
groupings.push(group.clone());
//println!("Found! {:?}", group);
} else if target - p > 0{
let new_vec = packages[i+1..packages.len()].to_vec();
let mut group = potential.clone();
group.push(*p);
groupings.append(&mut generate_sum(&new_vec, target - p, group));
}
}
groupings
}
fn parse_input(input : Vec<&str>) -> Vec<i32> {
let mut v = Vec::new();
for s in input {
if s.trim().len() > 0 {
v.push(s.parse::<i32>().unwrap());
}
}
v.sort_by(|a,b| b.cmp(a));
v
}
| sum_exists | identifier_name |
ed25519.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module provides an API for the PureEdDSA signature scheme over the ed25519 twisted
//! Edwards curve as defined in [RFC8032](https://tools.ietf.org/html/rfc8032).
//!
//! Signature verification also checks and rejects non-canonical signatures.
//!
//! # Examples
//!
//! ```
//! use diem_crypto_derive::{CryptoHasher, BCSCryptoHash};
//! use diem_crypto::{
//! ed25519::*,
//! traits::{Signature, SigningKey, Uniform},
//! };
//! use rand::{rngs::StdRng, SeedableRng};
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, CryptoHasher, BCSCryptoHash)]
//! pub struct TestCryptoDocTest(String);
//! let message = TestCryptoDocTest("Test message".to_string());
//!
//! let mut rng: StdRng = SeedableRng::from_seed([0; 32]);
//! let private_key = Ed25519PrivateKey::generate(&mut rng);
//! let public_key: Ed25519PublicKey = (&private_key).into();
//! let signature = private_key.sign(&message);
//! assert!(signature.verify(&message, &public_key).is_ok());
//! ```
//! **Note**: The above example generates a private key using a private function intended only for
//! testing purposes. Production code should find an alternate means for secure key generation.
#![allow(clippy::integer_arithmetic)]
use crate::{
hash::{CryptoHash, CryptoHasher},
traits::*,
};
use anyhow::{anyhow, Result};
use core::convert::TryFrom;
use diem_crypto_derive::{DeserializeKey, SerializeKey, SilentDebug, SilentDisplay};
use mirai_annotations::*;
use serde::Serialize;
use std::{cmp::Ordering, fmt};
/// The length of the Ed25519PrivateKey
pub const ED25519_PRIVATE_KEY_LENGTH: usize = ed25519_dalek::SECRET_KEY_LENGTH;
/// The length of the Ed25519PublicKey
pub const ED25519_PUBLIC_KEY_LENGTH: usize = ed25519_dalek::PUBLIC_KEY_LENGTH;
/// The length of the Ed25519Signature
pub const ED25519_SIGNATURE_LENGTH: usize = ed25519_dalek::SIGNATURE_LENGTH;
/// The order of ed25519 as defined in [RFC8032](https://tools.ietf.org/html/rfc8032).
const L: [u8; 32] = [
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
];
/// An Ed25519 private key
#[derive(DeserializeKey, SerializeKey, SilentDebug, SilentDisplay)]
pub struct Ed25519PrivateKey(ed25519_dalek::SecretKey);
#[cfg(feature = "assert-private-keys-not-cloneable")]
static_assertions::assert_not_impl_any!(Ed25519PrivateKey: Clone);
#[cfg(any(test, feature = "cloneable-private-keys"))]
impl Clone for Ed25519PrivateKey {
fn clone(&self) -> Self {
let serialized: &[u8] = &(self.to_bytes());
Ed25519PrivateKey::try_from(serialized).unwrap()
}
}
/// An Ed25519 public key
#[derive(DeserializeKey, Clone, SerializeKey)]
pub struct Ed25519PublicKey(ed25519_dalek::PublicKey);
#[cfg(mirai)]
use crate::tags::ValidatedPublicKeyTag;
#[cfg(not(mirai))]
struct ValidatedPublicKeyTag {}
/// An Ed25519 signature
#[derive(DeserializeKey, Clone, SerializeKey)]
pub struct Ed25519Signature(ed25519_dalek::Signature);
impl Ed25519PrivateKey {
/// The length of the Ed25519PrivateKey
pub const LENGTH: usize = ed25519_dalek::SECRET_KEY_LENGTH;
/// Serialize an Ed25519PrivateKey.
pub fn to_bytes(&self) -> [u8; ED25519_PRIVATE_KEY_LENGTH] {
self.0.to_bytes()
}
/// Deserialize an Ed25519PrivateKey without any validation checks apart from expected key size.
fn from_bytes_unchecked(
bytes: &[u8],
) -> std::result::Result<Ed25519PrivateKey, CryptoMaterialError> {
match ed25519_dalek::SecretKey::from_bytes(bytes) {
Ok(dalek_secret_key) => Ok(Ed25519PrivateKey(dalek_secret_key)),
Err(_) => Err(CryptoMaterialError::DeserializationError),
}
}
/// Private function aimed at minimizing code duplication between sign
/// methods of the SigningKey implementation. This should remain private.
fn sign_arbitrary_message(&self, message: &[u8]) -> Ed25519Signature {
let secret_key: &ed25519_dalek::SecretKey = &self.0;
let public_key: Ed25519PublicKey = self.into();
let expanded_secret_key: ed25519_dalek::ExpandedSecretKey =
ed25519_dalek::ExpandedSecretKey::from(secret_key);
let sig = expanded_secret_key.sign(message.as_ref(), &public_key.0);
Ed25519Signature(sig)
}
}
impl Ed25519PublicKey {
/// Serialize an Ed25519PublicKey.
pub fn to_bytes(&self) -> [u8; ED25519_PUBLIC_KEY_LENGTH] {
self.0.to_bytes()
}
/// Deserialize an Ed25519PublicKey without any validation checks apart from expected key size.
pub(crate) fn from_bytes_unchecked(
bytes: &[u8],
) -> std::result::Result<Ed25519PublicKey, CryptoMaterialError> {
match ed25519_dalek::PublicKey::from_bytes(bytes) {
Ok(dalek_public_key) => Ok(Ed25519PublicKey(dalek_public_key)),
Err(_) => Err(CryptoMaterialError::DeserializationError),
}
}
/// Deserialize an Ed25519PublicKey from its representation as an x25519
/// public key, along with an indication of sign. This is meant to
/// compensate for the poor key storage capabilities of key management
/// solutions, and NOT to promote double usage of keys under several
/// schemes, which would lead to BAD vulnerabilities.
///
/// Arguments:
/// - `x25519_bytes`: bit representation of a public key in clamped
/// Montgomery form, a.k.a. the x25519 public key format.
/// - `negative`: whether to interpret the given point as a negative point,
/// as the Montgomery form erases the sign byte. By XEdDSA
/// convention, if you expect to ever convert this back to an
/// x25519 public key, you should pass `false` for this
/// argument.
#[cfg(test)]
pub(crate) fn from_x25519_public_bytes(
x25519_bytes: &[u8],
negative: bool,
) -> Result<Self, CryptoMaterialError> {
if x25519_bytes.len()!= 32 {
return Err(CryptoMaterialError::DeserializationError);
}
let key_bits = {
let mut bits = [0u8; 32];
bits.copy_from_slice(x25519_bytes);
bits
};
let mtg_point = curve25519_dalek::montgomery::MontgomeryPoint(key_bits);
let sign = if negative { 1u8 } else { 0u8 };
let ed_point = mtg_point
.to_edwards(sign)
.ok_or(CryptoMaterialError::DeserializationError)?;
Ed25519PublicKey::try_from(&ed_point.compress().as_bytes()[..])
}
}
impl Ed25519Signature {
/// The length of the Ed25519Signature
pub const LENGTH: usize = ed25519_dalek::SIGNATURE_LENGTH;
/// Serialize an Ed25519Signature.
pub fn to_bytes(&self) -> [u8; ED25519_SIGNATURE_LENGTH] {
self.0.to_bytes()
}
/// Deserialize an Ed25519Signature without any validation checks (malleability)
/// apart from expected key size.
pub(crate) fn from_bytes_unchecked(
bytes: &[u8],
) -> std::result::Result<Ed25519Signature, CryptoMaterialError> {
match ed25519_dalek::Signature::try_from(bytes) {
Ok(dalek_signature) => Ok(Ed25519Signature(dalek_signature)),
Err(_) => Err(CryptoMaterialError::DeserializationError),
}
}
/// return an all-zero signature (for test only)
#[cfg(any(test, feature = "fuzzing"))]
pub fn dummy_signature() -> Self {
Self::from_bytes_unchecked(&[0u8; Self::LENGTH]).unwrap()
}
/// Check for correct size and third-party based signature malleability issues.
/// This method is required to ensure that given a valid signature for some message under some
/// key, an attacker cannot produce another valid signature for the same message and key.
///
/// According to [RFC8032](https://tools.ietf.org/html/rfc8032), signatures comprise elements
/// {R, S} and we should enforce that S is of canonical form (smaller than L, where L is the
/// order of edwards25519 curve group) to prevent signature malleability. Without this check,
/// one could add a multiple of L into S and still pass signature verification, resulting in
/// a distinct yet valid signature.
///
/// This method does not check the R component of the signature, because R is hashed during
/// signing and verification to compute h = H(ENC(R) || ENC(A) || M), which means that a
/// third-party cannot modify R without being detected.
///
/// Note: It's true that malicious signers can already produce varying signatures by
/// choosing a different nonce, so this method protects against malleability attacks performed
/// by a non-signer.
pub fn check_malleability(bytes: &[u8]) -> std::result::Result<(), CryptoMaterialError> {
if bytes.len()!= ED25519_SIGNATURE_LENGTH {
return Err(CryptoMaterialError::WrongLengthError);
}
if!check_s_lt_l(&bytes[32..]) {
return Err(CryptoMaterialError::CanonicalRepresentationError);
}
Ok(())
}
}
///////////////////////
// PrivateKey Traits //
///////////////////////
impl PrivateKey for Ed25519PrivateKey {
type PublicKeyMaterial = Ed25519PublicKey;
}
impl SigningKey for Ed25519PrivateKey {
type VerifyingKeyMaterial = Ed25519PublicKey;
type SignatureMaterial = Ed25519Signature;
fn | <T: CryptoHash + Serialize>(&self, message: &T) -> Ed25519Signature {
let mut bytes = <T::Hasher as CryptoHasher>::seed().to_vec();
bcs::serialize_into(&mut bytes, &message)
.map_err(|_| CryptoMaterialError::SerializationError)
.expect("Serialization of signable material should not fail.");
Ed25519PrivateKey::sign_arbitrary_message(&self, bytes.as_ref())
}
#[cfg(any(test, feature = "fuzzing"))]
fn sign_arbitrary_message(&self, message: &[u8]) -> Ed25519Signature {
Ed25519PrivateKey::sign_arbitrary_message(self, message)
}
}
impl Uniform for Ed25519PrivateKey {
fn generate<R>(rng: &mut R) -> Self
where
R: ::rand::RngCore + ::rand::CryptoRng,
{
Ed25519PrivateKey(ed25519_dalek::SecretKey::generate(rng))
}
}
impl PartialEq<Self> for Ed25519PrivateKey {
fn eq(&self, other: &Self) -> bool {
self.to_bytes() == other.to_bytes()
}
}
impl Eq for Ed25519PrivateKey {}
// We could have a distinct kind of validation for the PrivateKey, for
// ex. checking the derived PublicKey is valid?
impl TryFrom<&[u8]> for Ed25519PrivateKey {
type Error = CryptoMaterialError;
/// Deserialize an Ed25519PrivateKey. This method will also check for key validity.
fn try_from(bytes: &[u8]) -> std::result::Result<Ed25519PrivateKey, CryptoMaterialError> {
// Note that the only requirement is that the size of the key is 32 bytes, something that
// is already checked during deserialization of ed25519_dalek::SecretKey
// Also, the underlying ed25519_dalek implementation ensures that the derived public key
// is safe and it will not lie in a small-order group, thus no extra check for PublicKey
// validation is required.
Ed25519PrivateKey::from_bytes_unchecked(bytes)
}
}
impl Length for Ed25519PrivateKey {
fn length(&self) -> usize {
Self::LENGTH
}
}
impl ValidCryptoMaterial for Ed25519PrivateKey {
fn to_bytes(&self) -> Vec<u8> {
self.to_bytes().to_vec()
}
}
impl Genesis for Ed25519PrivateKey {
fn genesis() -> Self {
let mut buf = [0u8; ED25519_PRIVATE_KEY_LENGTH];
buf[ED25519_PRIVATE_KEY_LENGTH - 1] = 1;
Self::try_from(buf.as_ref()).unwrap()
}
}
//////////////////////
// PublicKey Traits //
//////////////////////
// Implementing From<&PrivateKey<...>> allows to derive a public key in a more elegant fashion
impl From<&Ed25519PrivateKey> for Ed25519PublicKey {
fn from(private_key: &Ed25519PrivateKey) -> Self {
let secret: &ed25519_dalek::SecretKey = &private_key.0;
let public: ed25519_dalek::PublicKey = secret.into();
Ed25519PublicKey(public)
}
}
// We deduce PublicKey from this
impl PublicKey for Ed25519PublicKey {
type PrivateKeyMaterial = Ed25519PrivateKey;
}
impl std::hash::Hash for Ed25519PublicKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let encoded_pubkey = self.to_bytes();
state.write(&encoded_pubkey);
}
}
// Those are required by the implementation of hash above
impl PartialEq for Ed25519PublicKey {
fn eq(&self, other: &Ed25519PublicKey) -> bool {
self.to_bytes() == other.to_bytes()
}
}
impl Eq for Ed25519PublicKey {}
// We deduce VerifyingKey from pointing to the signature material
// we get the ability to do `pubkey.validate(msg, signature)`
impl VerifyingKey for Ed25519PublicKey {
type SigningKeyMaterial = Ed25519PrivateKey;
type SignatureMaterial = Ed25519Signature;
}
impl fmt::Display for Ed25519PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", hex::encode(&self.0.as_bytes()))
}
}
impl fmt::Debug for Ed25519PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Ed25519PublicKey({})", self)
}
}
impl TryFrom<&[u8]> for Ed25519PublicKey {
type Error = CryptoMaterialError;
/// Deserialize an Ed25519PublicKey. This method will also check for key validity, for instance
/// it will only deserialize keys that are safe against small subgroup attacks.
fn try_from(bytes: &[u8]) -> std::result::Result<Ed25519PublicKey, CryptoMaterialError> {
// We need to access the Edwards point which is not directly accessible from
// ed25519_dalek::PublicKey, so we need to do some custom deserialization.
if bytes.len()!= ED25519_PUBLIC_KEY_LENGTH {
return Err(CryptoMaterialError::WrongLengthError);
}
let mut bits = [0u8; ED25519_PUBLIC_KEY_LENGTH];
bits.copy_from_slice(&bytes[..ED25519_PUBLIC_KEY_LENGTH]);
let compressed = curve25519_dalek::edwards::CompressedEdwardsY(bits);
let point = compressed
.decompress()
.ok_or(CryptoMaterialError::DeserializationError)?;
// Check if the point lies on a small subgroup. This is required
// when using curves with a small cofactor (in ed25519, cofactor = 8).
if point.is_small_order() {
return Err(CryptoMaterialError::SmallSubgroupError);
}
// Unfortunately, tuple struct `PublicKey` is private so we cannot
// Ok(Ed25519PublicKey(ed25519_dalek::PublicKey(compressed, point)))
// and we have to again invoke deserialization.
let public_key = Ed25519PublicKey::from_bytes_unchecked(bytes)?;
add_tag!(&public_key, ValidatedPublicKeyTag); // This key has gone through validity checks.
Ok(public_key)
}
}
impl Length for Ed25519PublicKey {
fn length(&self) -> usize {
ED25519_PUBLIC_KEY_LENGTH
}
}
impl ValidCryptoMaterial for Ed25519PublicKey {
fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes().to_vec()
}
}
//////////////////////
// Signature Traits //
//////////////////////
impl Signature for Ed25519Signature {
type VerifyingKeyMaterial = Ed25519PublicKey;
type SigningKeyMaterial = Ed25519PrivateKey;
/// Verifies that the provided signature is valid for the provided
/// message, according to the RFC8032 algorithm. This strict verification performs the
/// recommended check of 5.1.7 §3, on top of the required RFC8032 verifications.
fn verify<T: CryptoHash + Serialize>(
&self,
message: &T,
public_key: &Ed25519PublicKey,
) -> Result<()> {
// Public keys should be validated to be safe against small subgroup attacks, etc.
precondition!(has_tag!(public_key, ValidatedPublicKeyTag));
let mut bytes = <T::Hasher as CryptoHasher>::seed().to_vec();
bcs::serialize_into(&mut bytes, &message)
.map_err(|_| CryptoMaterialError::SerializationError)?;
Self::verify_arbitrary_msg(self, &bytes, public_key)
}
/// Checks that `self` is valid for an arbitrary &[u8] `message` using `public_key`.
/// Outside of this crate, this particular function should only be used for native signature
/// verification in move
fn verify_arbitrary_msg(&self, message: &[u8], public_key: &Ed25519PublicKey) -> Result<()> {
// Public keys should be validated to be safe against small subgroup attacks, etc.
precondition!(has_tag!(public_key, ValidatedPublicKeyTag));
Ed25519Signature::check_malleability(&self.to_bytes())?;
public_key
.0
.verify_strict(message, &self.0)
.map_err(|e| anyhow!("{}", e))
.and(Ok(()))
}
fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes().to_vec()
}
/// Batch signature verification as described in the original EdDSA article
/// by Bernstein et al. "High-speed high-security signatures". Current implementation works for
/// signatures on the same message and it checks for malleability.
#[cfg(feature = "batch")]
fn batch_verify<T: CryptoHash + Serialize>(
message: &T,
keys_and_signatures: Vec<(Self::VerifyingKeyMaterial, Self)>,
) -> Result<()> {
for (_, sig) in keys_and_signatures.iter() {
Ed25519Signature::check_malleability(&sig.to_bytes())?
}
let mut message_bytes = <T::Hasher as CryptoHasher>::seed().to_vec();
bcs::serialize_into(&mut message_bytes, &message)
.map_err(|_| CryptoMaterialError::SerializationError)?;
let batch_argument = keys_and_signatures
.iter()
.map(|(key, signature)| (key.0, signature.0));
let (dalek_public_keys, dalek_signatures): (Vec<_>, Vec<_>) = batch_argument.unzip();
let message_ref = &(&message_bytes)[..];
// The original batching algorithm works for different messages and it expects as many
// messages as the number of signatures. In our case, we just populate the same
// message to meet dalek's api requirements.
let messages = vec![message_ref; dalek_signatures.len()];
ed25519_dalek::verify_batch(&messages[..], &dalek_signatures[..], &dalek_public_keys[..])
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
}
impl Length for Ed25519Signature {
fn length(&self) -> usize {
ED25519_SIGNATURE_LENGTH
}
}
impl ValidCryptoMaterial for Ed25519Signature {
fn to_bytes(&self) -> Vec<u8> {
self.to_bytes().to_vec()
}
}
impl std::hash::Hash for Ed25519Signature {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let encoded_signature = self.to_bytes();
state.write(&encoded_signature);
}
}
impl TryFrom<&[u8]> for Ed25519Signature {
type Error = CryptoMaterialError;
fn try_from(bytes: &[u8]) -> std::result::Result<Ed25519Signature, CryptoMaterialError> {
Ed25519Signature::check_malleability(bytes)?;
Ed25519Signature::from_bytes_unchecked(bytes)
}
}
// Those are required by the implementation of hash above
impl PartialEq for Ed25519Signature {
fn eq(&self, other: &Ed25519Signature) -> bool {
self.to_bytes()[..] == other.to_bytes()[..]
}
}
impl Eq for Ed25519Signature {}
impl fmt::Display for Ed25519Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", hex::encode(&self.0.to_bytes()[..]))
}
}
impl fmt::Debug for Ed25519Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Ed25519Signature({})", self)
}
}
/// Check if S < L to capture invalid signatures.
fn check_s_lt_l(s: &[u8]) -> bool {
for i in (0..32).rev() {
match s[i].cmp(&L[i]) {
Ordering::Less => return true,
Ordering::Greater => return false,
_ => {}
}
}
// As this stage S == L which implies a non canonical S.
false
}
#[cfg(any(test, feature = "fuzzing"))]
use crate::test_utils::{self, KeyPair};
/// Produces a uniformly random ed25519 keypair from a seed
#[cfg(any(test, feature = "fuzzing"))]
pub fn keypair_strategy() -> impl Strategy<Value = KeyPair<Ed25519PrivateKey, Ed25519PublicKey>> {
test_utils::uniform_keypair_strategy::<Ed25519PrivateKey, Ed25519PublicKey>()
}
#[cfg(any(test, feature = "fuzzing"))]
use proptest::prelude::*;
#[cfg(any(test, feature = "fuzzing"))]
impl proptest::arbitrary::Arbitrary for Ed25519PublicKey {
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
crate::test_utils::uniform_keypair_strategy::<Ed25519PrivateKey, Ed25519PublicKey>()
.prop_map(|v| v.public_key)
.boxed()
}
}
| sign | identifier_name |
ed25519.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module provides an API for the PureEdDSA signature scheme over the ed25519 twisted
//! Edwards curve as defined in [RFC8032](https://tools.ietf.org/html/rfc8032).
//!
//! Signature verification also checks and rejects non-canonical signatures.
//!
//! # Examples
//!
//! ```
//! use diem_crypto_derive::{CryptoHasher, BCSCryptoHash};
//! use diem_crypto::{
//! ed25519::*,
//! traits::{Signature, SigningKey, Uniform},
//! };
//! use rand::{rngs::StdRng, SeedableRng};
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, CryptoHasher, BCSCryptoHash)]
//! pub struct TestCryptoDocTest(String);
//! let message = TestCryptoDocTest("Test message".to_string());
//!
//! let mut rng: StdRng = SeedableRng::from_seed([0; 32]);
//! let private_key = Ed25519PrivateKey::generate(&mut rng);
//! let public_key: Ed25519PublicKey = (&private_key).into();
//! let signature = private_key.sign(&message);
//! assert!(signature.verify(&message, &public_key).is_ok());
//! ```
//! **Note**: The above example generates a private key using a private function intended only for
//! testing purposes. Production code should find an alternate means for secure key generation.
#![allow(clippy::integer_arithmetic)]
use crate::{
hash::{CryptoHash, CryptoHasher},
traits::*,
};
use anyhow::{anyhow, Result};
use core::convert::TryFrom;
use diem_crypto_derive::{DeserializeKey, SerializeKey, SilentDebug, SilentDisplay};
use mirai_annotations::*;
use serde::Serialize;
use std::{cmp::Ordering, fmt};
/// The length of the Ed25519PrivateKey
pub const ED25519_PRIVATE_KEY_LENGTH: usize = ed25519_dalek::SECRET_KEY_LENGTH;
/// The length of the Ed25519PublicKey
pub const ED25519_PUBLIC_KEY_LENGTH: usize = ed25519_dalek::PUBLIC_KEY_LENGTH;
/// The length of the Ed25519Signature
pub const ED25519_SIGNATURE_LENGTH: usize = ed25519_dalek::SIGNATURE_LENGTH;
/// The order of ed25519 as defined in [RFC8032](https://tools.ietf.org/html/rfc8032).
const L: [u8; 32] = [
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
];
/// An Ed25519 private key
#[derive(DeserializeKey, SerializeKey, SilentDebug, SilentDisplay)]
pub struct Ed25519PrivateKey(ed25519_dalek::SecretKey);
#[cfg(feature = "assert-private-keys-not-cloneable")]
static_assertions::assert_not_impl_any!(Ed25519PrivateKey: Clone);
#[cfg(any(test, feature = "cloneable-private-keys"))]
impl Clone for Ed25519PrivateKey {
fn clone(&self) -> Self {
let serialized: &[u8] = &(self.to_bytes());
Ed25519PrivateKey::try_from(serialized).unwrap()
}
}
/// An Ed25519 public key
#[derive(DeserializeKey, Clone, SerializeKey)]
pub struct Ed25519PublicKey(ed25519_dalek::PublicKey);
#[cfg(mirai)]
use crate::tags::ValidatedPublicKeyTag;
#[cfg(not(mirai))]
struct ValidatedPublicKeyTag {}
/// An Ed25519 signature
#[derive(DeserializeKey, Clone, SerializeKey)]
pub struct Ed25519Signature(ed25519_dalek::Signature);
impl Ed25519PrivateKey {
/// The length of the Ed25519PrivateKey
pub const LENGTH: usize = ed25519_dalek::SECRET_KEY_LENGTH;
/// Serialize an Ed25519PrivateKey.
pub fn to_bytes(&self) -> [u8; ED25519_PRIVATE_KEY_LENGTH] {
self.0.to_bytes()
}
/// Deserialize an Ed25519PrivateKey without any validation checks apart from expected key size.
fn from_bytes_unchecked(
bytes: &[u8],
) -> std::result::Result<Ed25519PrivateKey, CryptoMaterialError> {
match ed25519_dalek::SecretKey::from_bytes(bytes) {
Ok(dalek_secret_key) => Ok(Ed25519PrivateKey(dalek_secret_key)),
Err(_) => Err(CryptoMaterialError::DeserializationError),
}
}
/// Private function aimed at minimizing code duplication between sign
/// methods of the SigningKey implementation. This should remain private.
fn sign_arbitrary_message(&self, message: &[u8]) -> Ed25519Signature {
let secret_key: &ed25519_dalek::SecretKey = &self.0;
let public_key: Ed25519PublicKey = self.into();
let expanded_secret_key: ed25519_dalek::ExpandedSecretKey =
ed25519_dalek::ExpandedSecretKey::from(secret_key);
let sig = expanded_secret_key.sign(message.as_ref(), &public_key.0);
Ed25519Signature(sig)
}
}
impl Ed25519PublicKey {
/// Serialize an Ed25519PublicKey.
pub fn to_bytes(&self) -> [u8; ED25519_PUBLIC_KEY_LENGTH] {
self.0.to_bytes()
}
/// Deserialize an Ed25519PublicKey without any validation checks apart from expected key size.
pub(crate) fn from_bytes_unchecked(
bytes: &[u8],
) -> std::result::Result<Ed25519PublicKey, CryptoMaterialError> {
match ed25519_dalek::PublicKey::from_bytes(bytes) {
Ok(dalek_public_key) => Ok(Ed25519PublicKey(dalek_public_key)),
Err(_) => Err(CryptoMaterialError::DeserializationError),
}
}
/// Deserialize an Ed25519PublicKey from its representation as an x25519
/// public key, along with an indication of sign. This is meant to
/// compensate for the poor key storage capabilities of key management
/// solutions, and NOT to promote double usage of keys under several
/// schemes, which would lead to BAD vulnerabilities. | /// - `x25519_bytes`: bit representation of a public key in clamped
/// Montgomery form, a.k.a. the x25519 public key format.
/// - `negative`: whether to interpret the given point as a negative point,
/// as the Montgomery form erases the sign byte. By XEdDSA
/// convention, if you expect to ever convert this back to an
/// x25519 public key, you should pass `false` for this
/// argument.
#[cfg(test)]
pub(crate) fn from_x25519_public_bytes(
x25519_bytes: &[u8],
negative: bool,
) -> Result<Self, CryptoMaterialError> {
if x25519_bytes.len()!= 32 {
return Err(CryptoMaterialError::DeserializationError);
}
let key_bits = {
let mut bits = [0u8; 32];
bits.copy_from_slice(x25519_bytes);
bits
};
let mtg_point = curve25519_dalek::montgomery::MontgomeryPoint(key_bits);
let sign = if negative { 1u8 } else { 0u8 };
let ed_point = mtg_point
.to_edwards(sign)
.ok_or(CryptoMaterialError::DeserializationError)?;
Ed25519PublicKey::try_from(&ed_point.compress().as_bytes()[..])
}
}
impl Ed25519Signature {
/// The length of the Ed25519Signature
pub const LENGTH: usize = ed25519_dalek::SIGNATURE_LENGTH;
/// Serialize an Ed25519Signature.
pub fn to_bytes(&self) -> [u8; ED25519_SIGNATURE_LENGTH] {
self.0.to_bytes()
}
/// Deserialize an Ed25519Signature without any validation checks (malleability)
/// apart from expected key size.
pub(crate) fn from_bytes_unchecked(
bytes: &[u8],
) -> std::result::Result<Ed25519Signature, CryptoMaterialError> {
match ed25519_dalek::Signature::try_from(bytes) {
Ok(dalek_signature) => Ok(Ed25519Signature(dalek_signature)),
Err(_) => Err(CryptoMaterialError::DeserializationError),
}
}
/// return an all-zero signature (for test only)
#[cfg(any(test, feature = "fuzzing"))]
pub fn dummy_signature() -> Self {
Self::from_bytes_unchecked(&[0u8; Self::LENGTH]).unwrap()
}
/// Check for correct size and third-party based signature malleability issues.
/// This method is required to ensure that given a valid signature for some message under some
/// key, an attacker cannot produce another valid signature for the same message and key.
///
/// According to [RFC8032](https://tools.ietf.org/html/rfc8032), signatures comprise elements
/// {R, S} and we should enforce that S is of canonical form (smaller than L, where L is the
/// order of edwards25519 curve group) to prevent signature malleability. Without this check,
/// one could add a multiple of L into S and still pass signature verification, resulting in
/// a distinct yet valid signature.
///
/// This method does not check the R component of the signature, because R is hashed during
/// signing and verification to compute h = H(ENC(R) || ENC(A) || M), which means that a
/// third-party cannot modify R without being detected.
///
/// Note: It's true that malicious signers can already produce varying signatures by
/// choosing a different nonce, so this method protects against malleability attacks performed
/// by a non-signer.
pub fn check_malleability(bytes: &[u8]) -> std::result::Result<(), CryptoMaterialError> {
if bytes.len()!= ED25519_SIGNATURE_LENGTH {
return Err(CryptoMaterialError::WrongLengthError);
}
if!check_s_lt_l(&bytes[32..]) {
return Err(CryptoMaterialError::CanonicalRepresentationError);
}
Ok(())
}
}
///////////////////////
// PrivateKey Traits //
///////////////////////
impl PrivateKey for Ed25519PrivateKey {
type PublicKeyMaterial = Ed25519PublicKey;
}
impl SigningKey for Ed25519PrivateKey {
type VerifyingKeyMaterial = Ed25519PublicKey;
type SignatureMaterial = Ed25519Signature;
fn sign<T: CryptoHash + Serialize>(&self, message: &T) -> Ed25519Signature {
let mut bytes = <T::Hasher as CryptoHasher>::seed().to_vec();
bcs::serialize_into(&mut bytes, &message)
.map_err(|_| CryptoMaterialError::SerializationError)
.expect("Serialization of signable material should not fail.");
Ed25519PrivateKey::sign_arbitrary_message(&self, bytes.as_ref())
}
#[cfg(any(test, feature = "fuzzing"))]
fn sign_arbitrary_message(&self, message: &[u8]) -> Ed25519Signature {
Ed25519PrivateKey::sign_arbitrary_message(self, message)
}
}
impl Uniform for Ed25519PrivateKey {
fn generate<R>(rng: &mut R) -> Self
where
R: ::rand::RngCore + ::rand::CryptoRng,
{
Ed25519PrivateKey(ed25519_dalek::SecretKey::generate(rng))
}
}
impl PartialEq<Self> for Ed25519PrivateKey {
fn eq(&self, other: &Self) -> bool {
self.to_bytes() == other.to_bytes()
}
}
impl Eq for Ed25519PrivateKey {}
// We could have a distinct kind of validation for the PrivateKey, for
// ex. checking the derived PublicKey is valid?
impl TryFrom<&[u8]> for Ed25519PrivateKey {
type Error = CryptoMaterialError;
/// Deserialize an Ed25519PrivateKey. This method will also check for key validity.
fn try_from(bytes: &[u8]) -> std::result::Result<Ed25519PrivateKey, CryptoMaterialError> {
// Note that the only requirement is that the size of the key is 32 bytes, something that
// is already checked during deserialization of ed25519_dalek::SecretKey
// Also, the underlying ed25519_dalek implementation ensures that the derived public key
// is safe and it will not lie in a small-order group, thus no extra check for PublicKey
// validation is required.
Ed25519PrivateKey::from_bytes_unchecked(bytes)
}
}
impl Length for Ed25519PrivateKey {
fn length(&self) -> usize {
Self::LENGTH
}
}
impl ValidCryptoMaterial for Ed25519PrivateKey {
fn to_bytes(&self) -> Vec<u8> {
self.to_bytes().to_vec()
}
}
impl Genesis for Ed25519PrivateKey {
fn genesis() -> Self {
let mut buf = [0u8; ED25519_PRIVATE_KEY_LENGTH];
buf[ED25519_PRIVATE_KEY_LENGTH - 1] = 1;
Self::try_from(buf.as_ref()).unwrap()
}
}
//////////////////////
// PublicKey Traits //
//////////////////////
// Implementing From<&PrivateKey<...>> allows to derive a public key in a more elegant fashion
impl From<&Ed25519PrivateKey> for Ed25519PublicKey {
fn from(private_key: &Ed25519PrivateKey) -> Self {
let secret: &ed25519_dalek::SecretKey = &private_key.0;
let public: ed25519_dalek::PublicKey = secret.into();
Ed25519PublicKey(public)
}
}
// We deduce PublicKey from this
impl PublicKey for Ed25519PublicKey {
type PrivateKeyMaterial = Ed25519PrivateKey;
}
impl std::hash::Hash for Ed25519PublicKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let encoded_pubkey = self.to_bytes();
state.write(&encoded_pubkey);
}
}
// Those are required by the implementation of hash above
impl PartialEq for Ed25519PublicKey {
fn eq(&self, other: &Ed25519PublicKey) -> bool {
self.to_bytes() == other.to_bytes()
}
}
impl Eq for Ed25519PublicKey {}
// We deduce VerifyingKey from pointing to the signature material
// we get the ability to do `pubkey.validate(msg, signature)`
impl VerifyingKey for Ed25519PublicKey {
type SigningKeyMaterial = Ed25519PrivateKey;
type SignatureMaterial = Ed25519Signature;
}
impl fmt::Display for Ed25519PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", hex::encode(&self.0.as_bytes()))
}
}
impl fmt::Debug for Ed25519PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Ed25519PublicKey({})", self)
}
}
impl TryFrom<&[u8]> for Ed25519PublicKey {
type Error = CryptoMaterialError;
/// Deserialize an Ed25519PublicKey. This method will also check for key validity, for instance
/// it will only deserialize keys that are safe against small subgroup attacks.
fn try_from(bytes: &[u8]) -> std::result::Result<Ed25519PublicKey, CryptoMaterialError> {
// We need to access the Edwards point which is not directly accessible from
// ed25519_dalek::PublicKey, so we need to do some custom deserialization.
if bytes.len()!= ED25519_PUBLIC_KEY_LENGTH {
return Err(CryptoMaterialError::WrongLengthError);
}
let mut bits = [0u8; ED25519_PUBLIC_KEY_LENGTH];
bits.copy_from_slice(&bytes[..ED25519_PUBLIC_KEY_LENGTH]);
let compressed = curve25519_dalek::edwards::CompressedEdwardsY(bits);
let point = compressed
.decompress()
.ok_or(CryptoMaterialError::DeserializationError)?;
// Check if the point lies on a small subgroup. This is required
// when using curves with a small cofactor (in ed25519, cofactor = 8).
if point.is_small_order() {
return Err(CryptoMaterialError::SmallSubgroupError);
}
// Unfortunately, tuple struct `PublicKey` is private so we cannot
// Ok(Ed25519PublicKey(ed25519_dalek::PublicKey(compressed, point)))
// and we have to again invoke deserialization.
let public_key = Ed25519PublicKey::from_bytes_unchecked(bytes)?;
add_tag!(&public_key, ValidatedPublicKeyTag); // This key has gone through validity checks.
Ok(public_key)
}
}
impl Length for Ed25519PublicKey {
fn length(&self) -> usize {
ED25519_PUBLIC_KEY_LENGTH
}
}
impl ValidCryptoMaterial for Ed25519PublicKey {
fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes().to_vec()
}
}
//////////////////////
// Signature Traits //
//////////////////////
impl Signature for Ed25519Signature {
type VerifyingKeyMaterial = Ed25519PublicKey;
type SigningKeyMaterial = Ed25519PrivateKey;
/// Verifies that the provided signature is valid for the provided
/// message, according to the RFC8032 algorithm. This strict verification performs the
/// recommended check of 5.1.7 §3, on top of the required RFC8032 verifications.
fn verify<T: CryptoHash + Serialize>(
&self,
message: &T,
public_key: &Ed25519PublicKey,
) -> Result<()> {
// Public keys should be validated to be safe against small subgroup attacks, etc.
precondition!(has_tag!(public_key, ValidatedPublicKeyTag));
let mut bytes = <T::Hasher as CryptoHasher>::seed().to_vec();
bcs::serialize_into(&mut bytes, &message)
.map_err(|_| CryptoMaterialError::SerializationError)?;
Self::verify_arbitrary_msg(self, &bytes, public_key)
}
/// Checks that `self` is valid for an arbitrary &[u8] `message` using `public_key`.
/// Outside of this crate, this particular function should only be used for native signature
/// verification in move
fn verify_arbitrary_msg(&self, message: &[u8], public_key: &Ed25519PublicKey) -> Result<()> {
// Public keys should be validated to be safe against small subgroup attacks, etc.
precondition!(has_tag!(public_key, ValidatedPublicKeyTag));
Ed25519Signature::check_malleability(&self.to_bytes())?;
public_key
.0
.verify_strict(message, &self.0)
.map_err(|e| anyhow!("{}", e))
.and(Ok(()))
}
fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes().to_vec()
}
/// Batch signature verification as described in the original EdDSA article
/// by Bernstein et al. "High-speed high-security signatures". Current implementation works for
/// signatures on the same message and it checks for malleability.
#[cfg(feature = "batch")]
fn batch_verify<T: CryptoHash + Serialize>(
message: &T,
keys_and_signatures: Vec<(Self::VerifyingKeyMaterial, Self)>,
) -> Result<()> {
for (_, sig) in keys_and_signatures.iter() {
Ed25519Signature::check_malleability(&sig.to_bytes())?
}
let mut message_bytes = <T::Hasher as CryptoHasher>::seed().to_vec();
bcs::serialize_into(&mut message_bytes, &message)
.map_err(|_| CryptoMaterialError::SerializationError)?;
let batch_argument = keys_and_signatures
.iter()
.map(|(key, signature)| (key.0, signature.0));
let (dalek_public_keys, dalek_signatures): (Vec<_>, Vec<_>) = batch_argument.unzip();
let message_ref = &(&message_bytes)[..];
// The original batching algorithm works for different messages and it expects as many
// messages as the number of signatures. In our case, we just populate the same
// message to meet dalek's api requirements.
let messages = vec![message_ref; dalek_signatures.len()];
ed25519_dalek::verify_batch(&messages[..], &dalek_signatures[..], &dalek_public_keys[..])
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
}
impl Length for Ed25519Signature {
fn length(&self) -> usize {
ED25519_SIGNATURE_LENGTH
}
}
impl ValidCryptoMaterial for Ed25519Signature {
fn to_bytes(&self) -> Vec<u8> {
self.to_bytes().to_vec()
}
}
impl std::hash::Hash for Ed25519Signature {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let encoded_signature = self.to_bytes();
state.write(&encoded_signature);
}
}
impl TryFrom<&[u8]> for Ed25519Signature {
type Error = CryptoMaterialError;
fn try_from(bytes: &[u8]) -> std::result::Result<Ed25519Signature, CryptoMaterialError> {
Ed25519Signature::check_malleability(bytes)?;
Ed25519Signature::from_bytes_unchecked(bytes)
}
}
// Those are required by the implementation of hash above
impl PartialEq for Ed25519Signature {
fn eq(&self, other: &Ed25519Signature) -> bool {
self.to_bytes()[..] == other.to_bytes()[..]
}
}
impl Eq for Ed25519Signature {}
impl fmt::Display for Ed25519Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", hex::encode(&self.0.to_bytes()[..]))
}
}
impl fmt::Debug for Ed25519Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Ed25519Signature({})", self)
}
}
/// Check if S < L to capture invalid signatures.
fn check_s_lt_l(s: &[u8]) -> bool {
for i in (0..32).rev() {
match s[i].cmp(&L[i]) {
Ordering::Less => return true,
Ordering::Greater => return false,
_ => {}
}
}
// As this stage S == L which implies a non canonical S.
false
}
#[cfg(any(test, feature = "fuzzing"))]
use crate::test_utils::{self, KeyPair};
/// Produces a uniformly random ed25519 keypair from a seed
#[cfg(any(test, feature = "fuzzing"))]
pub fn keypair_strategy() -> impl Strategy<Value = KeyPair<Ed25519PrivateKey, Ed25519PublicKey>> {
test_utils::uniform_keypair_strategy::<Ed25519PrivateKey, Ed25519PublicKey>()
}
#[cfg(any(test, feature = "fuzzing"))]
use proptest::prelude::*;
#[cfg(any(test, feature = "fuzzing"))]
impl proptest::arbitrary::Arbitrary for Ed25519PublicKey {
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
crate::test_utils::uniform_keypair_strategy::<Ed25519PrivateKey, Ed25519PublicKey>()
.prop_map(|v| v.public_key)
.boxed()
}
} | ///
/// Arguments: | random_line_split |
ed25519.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module provides an API for the PureEdDSA signature scheme over the ed25519 twisted
//! Edwards curve as defined in [RFC8032](https://tools.ietf.org/html/rfc8032).
//!
//! Signature verification also checks and rejects non-canonical signatures.
//!
//! # Examples
//!
//! ```
//! use diem_crypto_derive::{CryptoHasher, BCSCryptoHash};
//! use diem_crypto::{
//! ed25519::*,
//! traits::{Signature, SigningKey, Uniform},
//! };
//! use rand::{rngs::StdRng, SeedableRng};
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize, CryptoHasher, BCSCryptoHash)]
//! pub struct TestCryptoDocTest(String);
//! let message = TestCryptoDocTest("Test message".to_string());
//!
//! let mut rng: StdRng = SeedableRng::from_seed([0; 32]);
//! let private_key = Ed25519PrivateKey::generate(&mut rng);
//! let public_key: Ed25519PublicKey = (&private_key).into();
//! let signature = private_key.sign(&message);
//! assert!(signature.verify(&message, &public_key).is_ok());
//! ```
//! **Note**: The above example generates a private key using a private function intended only for
//! testing purposes. Production code should find an alternate means for secure key generation.
#![allow(clippy::integer_arithmetic)]
use crate::{
hash::{CryptoHash, CryptoHasher},
traits::*,
};
use anyhow::{anyhow, Result};
use core::convert::TryFrom;
use diem_crypto_derive::{DeserializeKey, SerializeKey, SilentDebug, SilentDisplay};
use mirai_annotations::*;
use serde::Serialize;
use std::{cmp::Ordering, fmt};
/// The length of the Ed25519PrivateKey
pub const ED25519_PRIVATE_KEY_LENGTH: usize = ed25519_dalek::SECRET_KEY_LENGTH;
/// The length of the Ed25519PublicKey
pub const ED25519_PUBLIC_KEY_LENGTH: usize = ed25519_dalek::PUBLIC_KEY_LENGTH;
/// The length of the Ed25519Signature
pub const ED25519_SIGNATURE_LENGTH: usize = ed25519_dalek::SIGNATURE_LENGTH;
/// The order of ed25519 as defined in [RFC8032](https://tools.ietf.org/html/rfc8032).
const L: [u8; 32] = [
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,
];
/// An Ed25519 private key
#[derive(DeserializeKey, SerializeKey, SilentDebug, SilentDisplay)]
pub struct Ed25519PrivateKey(ed25519_dalek::SecretKey);
#[cfg(feature = "assert-private-keys-not-cloneable")]
static_assertions::assert_not_impl_any!(Ed25519PrivateKey: Clone);
#[cfg(any(test, feature = "cloneable-private-keys"))]
impl Clone for Ed25519PrivateKey {
fn clone(&self) -> Self {
let serialized: &[u8] = &(self.to_bytes());
Ed25519PrivateKey::try_from(serialized).unwrap()
}
}
/// An Ed25519 public key
#[derive(DeserializeKey, Clone, SerializeKey)]
pub struct Ed25519PublicKey(ed25519_dalek::PublicKey);
#[cfg(mirai)]
use crate::tags::ValidatedPublicKeyTag;
#[cfg(not(mirai))]
struct ValidatedPublicKeyTag {}
/// An Ed25519 signature
#[derive(DeserializeKey, Clone, SerializeKey)]
pub struct Ed25519Signature(ed25519_dalek::Signature);
impl Ed25519PrivateKey {
/// The length of the Ed25519PrivateKey
pub const LENGTH: usize = ed25519_dalek::SECRET_KEY_LENGTH;
/// Serialize an Ed25519PrivateKey.
pub fn to_bytes(&self) -> [u8; ED25519_PRIVATE_KEY_LENGTH] {
self.0.to_bytes()
}
/// Deserialize an Ed25519PrivateKey without any validation checks apart from expected key size.
fn from_bytes_unchecked(
bytes: &[u8],
) -> std::result::Result<Ed25519PrivateKey, CryptoMaterialError> {
match ed25519_dalek::SecretKey::from_bytes(bytes) {
Ok(dalek_secret_key) => Ok(Ed25519PrivateKey(dalek_secret_key)),
Err(_) => Err(CryptoMaterialError::DeserializationError),
}
}
/// Private function aimed at minimizing code duplication between sign
/// methods of the SigningKey implementation. This should remain private.
fn sign_arbitrary_message(&self, message: &[u8]) -> Ed25519Signature {
let secret_key: &ed25519_dalek::SecretKey = &self.0;
let public_key: Ed25519PublicKey = self.into();
let expanded_secret_key: ed25519_dalek::ExpandedSecretKey =
ed25519_dalek::ExpandedSecretKey::from(secret_key);
let sig = expanded_secret_key.sign(message.as_ref(), &public_key.0);
Ed25519Signature(sig)
}
}
impl Ed25519PublicKey {
/// Serialize an Ed25519PublicKey.
pub fn to_bytes(&self) -> [u8; ED25519_PUBLIC_KEY_LENGTH] {
self.0.to_bytes()
}
/// Deserialize an Ed25519PublicKey without any validation checks apart from expected key size.
pub(crate) fn from_bytes_unchecked(
bytes: &[u8],
) -> std::result::Result<Ed25519PublicKey, CryptoMaterialError> {
match ed25519_dalek::PublicKey::from_bytes(bytes) {
Ok(dalek_public_key) => Ok(Ed25519PublicKey(dalek_public_key)),
Err(_) => Err(CryptoMaterialError::DeserializationError),
}
}
/// Deserialize an Ed25519PublicKey from its representation as an x25519
/// public key, along with an indication of sign. This is meant to
/// compensate for the poor key storage capabilities of key management
/// solutions, and NOT to promote double usage of keys under several
/// schemes, which would lead to BAD vulnerabilities.
///
/// Arguments:
/// - `x25519_bytes`: bit representation of a public key in clamped
/// Montgomery form, a.k.a. the x25519 public key format.
/// - `negative`: whether to interpret the given point as a negative point,
/// as the Montgomery form erases the sign byte. By XEdDSA
/// convention, if you expect to ever convert this back to an
/// x25519 public key, you should pass `false` for this
/// argument.
#[cfg(test)]
pub(crate) fn from_x25519_public_bytes(
x25519_bytes: &[u8],
negative: bool,
) -> Result<Self, CryptoMaterialError> {
if x25519_bytes.len()!= 32 {
return Err(CryptoMaterialError::DeserializationError);
}
let key_bits = {
let mut bits = [0u8; 32];
bits.copy_from_slice(x25519_bytes);
bits
};
let mtg_point = curve25519_dalek::montgomery::MontgomeryPoint(key_bits);
let sign = if negative { 1u8 } else { 0u8 };
let ed_point = mtg_point
.to_edwards(sign)
.ok_or(CryptoMaterialError::DeserializationError)?;
Ed25519PublicKey::try_from(&ed_point.compress().as_bytes()[..])
}
}
impl Ed25519Signature {
/// The length of the Ed25519Signature
pub const LENGTH: usize = ed25519_dalek::SIGNATURE_LENGTH;
/// Serialize an Ed25519Signature.
pub fn to_bytes(&self) -> [u8; ED25519_SIGNATURE_LENGTH] {
self.0.to_bytes()
}
/// Deserialize an Ed25519Signature without any validation checks (malleability)
/// apart from expected key size.
pub(crate) fn from_bytes_unchecked(
bytes: &[u8],
) -> std::result::Result<Ed25519Signature, CryptoMaterialError> {
match ed25519_dalek::Signature::try_from(bytes) {
Ok(dalek_signature) => Ok(Ed25519Signature(dalek_signature)),
Err(_) => Err(CryptoMaterialError::DeserializationError),
}
}
/// return an all-zero signature (for test only)
#[cfg(any(test, feature = "fuzzing"))]
pub fn dummy_signature() -> Self {
Self::from_bytes_unchecked(&[0u8; Self::LENGTH]).unwrap()
}
/// Check for correct size and third-party based signature malleability issues.
/// This method is required to ensure that given a valid signature for some message under some
/// key, an attacker cannot produce another valid signature for the same message and key.
///
/// According to [RFC8032](https://tools.ietf.org/html/rfc8032), signatures comprise elements
/// {R, S} and we should enforce that S is of canonical form (smaller than L, where L is the
/// order of edwards25519 curve group) to prevent signature malleability. Without this check,
/// one could add a multiple of L into S and still pass signature verification, resulting in
/// a distinct yet valid signature.
///
/// This method does not check the R component of the signature, because R is hashed during
/// signing and verification to compute h = H(ENC(R) || ENC(A) || M), which means that a
/// third-party cannot modify R without being detected.
///
/// Note: It's true that malicious signers can already produce varying signatures by
/// choosing a different nonce, so this method protects against malleability attacks performed
/// by a non-signer.
pub fn check_malleability(bytes: &[u8]) -> std::result::Result<(), CryptoMaterialError> {
if bytes.len()!= ED25519_SIGNATURE_LENGTH {
return Err(CryptoMaterialError::WrongLengthError);
}
if!check_s_lt_l(&bytes[32..]) {
return Err(CryptoMaterialError::CanonicalRepresentationError);
}
Ok(())
}
}
///////////////////////
// PrivateKey Traits //
///////////////////////
impl PrivateKey for Ed25519PrivateKey {
type PublicKeyMaterial = Ed25519PublicKey;
}
impl SigningKey for Ed25519PrivateKey {
type VerifyingKeyMaterial = Ed25519PublicKey;
type SignatureMaterial = Ed25519Signature;
fn sign<T: CryptoHash + Serialize>(&self, message: &T) -> Ed25519Signature {
let mut bytes = <T::Hasher as CryptoHasher>::seed().to_vec();
bcs::serialize_into(&mut bytes, &message)
.map_err(|_| CryptoMaterialError::SerializationError)
.expect("Serialization of signable material should not fail.");
Ed25519PrivateKey::sign_arbitrary_message(&self, bytes.as_ref())
}
#[cfg(any(test, feature = "fuzzing"))]
fn sign_arbitrary_message(&self, message: &[u8]) -> Ed25519Signature {
Ed25519PrivateKey::sign_arbitrary_message(self, message)
}
}
impl Uniform for Ed25519PrivateKey {
fn generate<R>(rng: &mut R) -> Self
where
R: ::rand::RngCore + ::rand::CryptoRng,
{
Ed25519PrivateKey(ed25519_dalek::SecretKey::generate(rng))
}
}
impl PartialEq<Self> for Ed25519PrivateKey {
fn eq(&self, other: &Self) -> bool {
self.to_bytes() == other.to_bytes()
}
}
impl Eq for Ed25519PrivateKey {}
// We could have a distinct kind of validation for the PrivateKey, for
// ex. checking the derived PublicKey is valid?
impl TryFrom<&[u8]> for Ed25519PrivateKey {
type Error = CryptoMaterialError;
/// Deserialize an Ed25519PrivateKey. This method will also check for key validity.
fn try_from(bytes: &[u8]) -> std::result::Result<Ed25519PrivateKey, CryptoMaterialError> {
// Note that the only requirement is that the size of the key is 32 bytes, something that
// is already checked during deserialization of ed25519_dalek::SecretKey
// Also, the underlying ed25519_dalek implementation ensures that the derived public key
// is safe and it will not lie in a small-order group, thus no extra check for PublicKey
// validation is required.
Ed25519PrivateKey::from_bytes_unchecked(bytes)
}
}
impl Length for Ed25519PrivateKey {
fn length(&self) -> usize {
Self::LENGTH
}
}
impl ValidCryptoMaterial for Ed25519PrivateKey {
fn to_bytes(&self) -> Vec<u8> {
self.to_bytes().to_vec()
}
}
impl Genesis for Ed25519PrivateKey {
fn genesis() -> Self {
let mut buf = [0u8; ED25519_PRIVATE_KEY_LENGTH];
buf[ED25519_PRIVATE_KEY_LENGTH - 1] = 1;
Self::try_from(buf.as_ref()).unwrap()
}
}
//////////////////////
// PublicKey Traits //
//////////////////////
// Implementing From<&PrivateKey<...>> allows to derive a public key in a more elegant fashion
impl From<&Ed25519PrivateKey> for Ed25519PublicKey {
fn from(private_key: &Ed25519PrivateKey) -> Self {
let secret: &ed25519_dalek::SecretKey = &private_key.0;
let public: ed25519_dalek::PublicKey = secret.into();
Ed25519PublicKey(public)
}
}
// We deduce PublicKey from this
impl PublicKey for Ed25519PublicKey {
type PrivateKeyMaterial = Ed25519PrivateKey;
}
impl std::hash::Hash for Ed25519PublicKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let encoded_pubkey = self.to_bytes();
state.write(&encoded_pubkey);
}
}
// Those are required by the implementation of hash above
impl PartialEq for Ed25519PublicKey {
fn eq(&self, other: &Ed25519PublicKey) -> bool {
self.to_bytes() == other.to_bytes()
}
}
impl Eq for Ed25519PublicKey {}
// We deduce VerifyingKey from pointing to the signature material
// we get the ability to do `pubkey.validate(msg, signature)`
impl VerifyingKey for Ed25519PublicKey {
type SigningKeyMaterial = Ed25519PrivateKey;
type SignatureMaterial = Ed25519Signature;
}
impl fmt::Display for Ed25519PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", hex::encode(&self.0.as_bytes()))
}
}
impl fmt::Debug for Ed25519PublicKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Ed25519PublicKey({})", self)
}
}
impl TryFrom<&[u8]> for Ed25519PublicKey {
type Error = CryptoMaterialError;
/// Deserialize an Ed25519PublicKey. This method will also check for key validity, for instance
/// it will only deserialize keys that are safe against small subgroup attacks.
fn try_from(bytes: &[u8]) -> std::result::Result<Ed25519PublicKey, CryptoMaterialError> {
// We need to access the Edwards point which is not directly accessible from
// ed25519_dalek::PublicKey, so we need to do some custom deserialization.
if bytes.len()!= ED25519_PUBLIC_KEY_LENGTH {
return Err(CryptoMaterialError::WrongLengthError);
}
let mut bits = [0u8; ED25519_PUBLIC_KEY_LENGTH];
bits.copy_from_slice(&bytes[..ED25519_PUBLIC_KEY_LENGTH]);
let compressed = curve25519_dalek::edwards::CompressedEdwardsY(bits);
let point = compressed
.decompress()
.ok_or(CryptoMaterialError::DeserializationError)?;
// Check if the point lies on a small subgroup. This is required
// when using curves with a small cofactor (in ed25519, cofactor = 8).
if point.is_small_order() {
return Err(CryptoMaterialError::SmallSubgroupError);
}
// Unfortunately, tuple struct `PublicKey` is private so we cannot
// Ok(Ed25519PublicKey(ed25519_dalek::PublicKey(compressed, point)))
// and we have to again invoke deserialization.
let public_key = Ed25519PublicKey::from_bytes_unchecked(bytes)?;
add_tag!(&public_key, ValidatedPublicKeyTag); // This key has gone through validity checks.
Ok(public_key)
}
}
impl Length for Ed25519PublicKey {
fn length(&self) -> usize {
ED25519_PUBLIC_KEY_LENGTH
}
}
impl ValidCryptoMaterial for Ed25519PublicKey {
fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes().to_vec()
}
}
//////////////////////
// Signature Traits //
//////////////////////
impl Signature for Ed25519Signature {
type VerifyingKeyMaterial = Ed25519PublicKey;
type SigningKeyMaterial = Ed25519PrivateKey;
/// Verifies that the provided signature is valid for the provided
/// message, according to the RFC8032 algorithm. This strict verification performs the
/// recommended check of 5.1.7 §3, on top of the required RFC8032 verifications.
fn verify<T: CryptoHash + Serialize>(
&self,
message: &T,
public_key: &Ed25519PublicKey,
) -> Result<()> {
// Public keys should be validated to be safe against small subgroup attacks, etc.
precondition!(has_tag!(public_key, ValidatedPublicKeyTag));
let mut bytes = <T::Hasher as CryptoHasher>::seed().to_vec();
bcs::serialize_into(&mut bytes, &message)
.map_err(|_| CryptoMaterialError::SerializationError)?;
Self::verify_arbitrary_msg(self, &bytes, public_key)
}
/// Checks that `self` is valid for an arbitrary &[u8] `message` using `public_key`.
/// Outside of this crate, this particular function should only be used for native signature
/// verification in move
fn verify_arbitrary_msg(&self, message: &[u8], public_key: &Ed25519PublicKey) -> Result<()> {
// Public keys should be validated to be safe against small subgroup attacks, etc.
precondition!(has_tag!(public_key, ValidatedPublicKeyTag));
Ed25519Signature::check_malleability(&self.to_bytes())?;
public_key
.0
.verify_strict(message, &self.0)
.map_err(|e| anyhow!("{}", e))
.and(Ok(()))
}
fn to_bytes(&self) -> Vec<u8> {
self.0.to_bytes().to_vec()
}
/// Batch signature verification as described in the original EdDSA article
/// by Bernstein et al. "High-speed high-security signatures". Current implementation works for
/// signatures on the same message and it checks for malleability.
#[cfg(feature = "batch")]
fn batch_verify<T: CryptoHash + Serialize>(
message: &T,
keys_and_signatures: Vec<(Self::VerifyingKeyMaterial, Self)>,
) -> Result<()> {
for (_, sig) in keys_and_signatures.iter() {
Ed25519Signature::check_malleability(&sig.to_bytes())?
}
let mut message_bytes = <T::Hasher as CryptoHasher>::seed().to_vec();
bcs::serialize_into(&mut message_bytes, &message)
.map_err(|_| CryptoMaterialError::SerializationError)?;
let batch_argument = keys_and_signatures
.iter()
.map(|(key, signature)| (key.0, signature.0));
let (dalek_public_keys, dalek_signatures): (Vec<_>, Vec<_>) = batch_argument.unzip();
let message_ref = &(&message_bytes)[..];
// The original batching algorithm works for different messages and it expects as many
// messages as the number of signatures. In our case, we just populate the same
// message to meet dalek's api requirements.
let messages = vec![message_ref; dalek_signatures.len()];
ed25519_dalek::verify_batch(&messages[..], &dalek_signatures[..], &dalek_public_keys[..])
.map_err(|e| anyhow!("{}", e))?;
Ok(())
}
}
impl Length for Ed25519Signature {
fn length(&self) -> usize {
ED25519_SIGNATURE_LENGTH
}
}
impl ValidCryptoMaterial for Ed25519Signature {
fn to_bytes(&self) -> Vec<u8> {
self.to_bytes().to_vec()
}
}
impl std::hash::Hash for Ed25519Signature {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
let encoded_signature = self.to_bytes();
state.write(&encoded_signature);
}
}
impl TryFrom<&[u8]> for Ed25519Signature {
type Error = CryptoMaterialError;
fn try_from(bytes: &[u8]) -> std::result::Result<Ed25519Signature, CryptoMaterialError> {
Ed25519Signature::check_malleability(bytes)?;
Ed25519Signature::from_bytes_unchecked(bytes)
}
}
// Those are required by the implementation of hash above
impl PartialEq for Ed25519Signature {
fn eq(&self, other: &Ed25519Signature) -> bool {
self.to_bytes()[..] == other.to_bytes()[..]
}
}
impl Eq for Ed25519Signature {}
impl fmt::Display for Ed25519Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", hex::encode(&self.0.to_bytes()[..]))
}
}
impl fmt::Debug for Ed25519Signature {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | }
/// Check if S < L to capture invalid signatures.
fn check_s_lt_l(s: &[u8]) -> bool {
for i in (0..32).rev() {
match s[i].cmp(&L[i]) {
Ordering::Less => return true,
Ordering::Greater => return false,
_ => {}
}
}
// As this stage S == L which implies a non canonical S.
false
}
#[cfg(any(test, feature = "fuzzing"))]
use crate::test_utils::{self, KeyPair};
/// Produces a uniformly random ed25519 keypair from a seed
#[cfg(any(test, feature = "fuzzing"))]
pub fn keypair_strategy() -> impl Strategy<Value = KeyPair<Ed25519PrivateKey, Ed25519PublicKey>> {
test_utils::uniform_keypair_strategy::<Ed25519PrivateKey, Ed25519PublicKey>()
}
#[cfg(any(test, feature = "fuzzing"))]
use proptest::prelude::*;
#[cfg(any(test, feature = "fuzzing"))]
impl proptest::arbitrary::Arbitrary for Ed25519PublicKey {
type Parameters = ();
type Strategy = BoxedStrategy<Self>;
fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
crate::test_utils::uniform_keypair_strategy::<Ed25519PrivateKey, Ed25519PublicKey>()
.prop_map(|v| v.public_key)
.boxed()
}
}
|
write!(f, "Ed25519Signature({})", self)
}
| identifier_body |
of.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl TypeId {
// /// Returns the `TypeId` of the type this generic function has been
// /// instantiated with
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn of<T:?Sized + Reflect +'static>() -> TypeId {
// TypeId {
// t: unsafe { intrinsics::type_id::<T>() },
// }
// }
// }
type T = i32;
#[test]
fn of_test1() {
let x: T = 68;
let x_typeid: TypeId = x.get_type_id();
let typeid: TypeId = TypeId::of::<T>();
assert_eq!(x_typeid, typeid);
}
#[test]
#[should_panic]
fn of_test2() {
struct | ;
let x: T = 68;
let x_typeid: TypeId = x.get_type_id();
let typeid: TypeId = TypeId::of::<A>();
assert_eq!(x_typeid, typeid);
}
}
| A | identifier_name |
of.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl TypeId {
// /// Returns the `TypeId` of the type this generic function has been
// /// instantiated with
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn of<T:?Sized + Reflect +'static>() -> TypeId {
// TypeId {
// t: unsafe { intrinsics::type_id::<T>() },
// }
// }
// }
type T = i32;
#[test]
fn of_test1() {
let x: T = 68;
let x_typeid: TypeId = x.get_type_id();
let typeid: TypeId = TypeId::of::<T>();
assert_eq!(x_typeid, typeid); | struct A;
let x: T = 68;
let x_typeid: TypeId = x.get_type_id();
let typeid: TypeId = TypeId::of::<A>();
assert_eq!(x_typeid, typeid);
}
} | }
#[test]
#[should_panic]
fn of_test2() { | random_line_split |
of.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::any::Any;
use core::any::TypeId;
// #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
// #[stable(feature = "rust1", since = "1.0.0")]
// pub struct TypeId {
// t: u64,
// }
// impl TypeId {
// /// Returns the `TypeId` of the type this generic function has been
// /// instantiated with
// #[stable(feature = "rust1", since = "1.0.0")]
// pub fn of<T:?Sized + Reflect +'static>() -> TypeId {
// TypeId {
// t: unsafe { intrinsics::type_id::<T>() },
// }
// }
// }
type T = i32;
#[test]
fn of_test1() |
#[test]
#[should_panic]
fn of_test2() {
struct A;
let x: T = 68;
let x_typeid: TypeId = x.get_type_id();
let typeid: TypeId = TypeId::of::<A>();
assert_eq!(x_typeid, typeid);
}
}
| {
let x: T = 68;
let x_typeid: TypeId = x.get_type_id();
let typeid: TypeId = TypeId::of::<T>();
assert_eq!(x_typeid, typeid);
} | identifier_body |
core.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rustc;
use rustc::{driver, middle};
use rustc::metadata::creader::Loader;
use rustc::middle::privacy;
use rustc::middle::lint;
use syntax::ast;
use syntax::parse::token;
use syntax;
use std::cell::RefCell;
use std::os;
use collections::{HashSet, HashMap};
use visit_ast::RustdocVisitor;
use clean;
use clean::Clean;
pub enum MaybeTyped {
Typed(middle::ty::ctxt),
NotTyped(driver::session::Session)
}
pub type ExternalPaths = RefCell<Option<HashMap<ast::DefId,
(Vec<StrBuf>, clean::TypeKind)>>>;
pub struct DocContext {
pub krate: ast::Crate,
pub maybe_typed: MaybeTyped,
pub src: Path,
pub external_paths: ExternalPaths,
}
impl DocContext {
pub fn sess<'a>(&'a self) -> &'a driver::session::Session |
}
pub struct CrateAnalysis {
pub exported_items: privacy::ExportedItems,
pub public_items: privacy::PublicItems,
pub external_paths: ExternalPaths,
}
/// Parses, resolves, and typechecks the given crate
fn get_ast_and_resolve(cpath: &Path, libs: HashSet<Path>, cfgs: Vec<StrBuf>)
-> (DocContext, CrateAnalysis) {
use syntax::codemap::dummy_spanned;
use rustc::driver::driver::{FileInput,
phase_1_parse_input,
phase_2_configure_and_expand,
phase_3_run_analysis_passes};
use rustc::driver::config::build_configuration;
let input = FileInput(cpath.clone());
let sessopts = driver::config::Options {
maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
addl_lib_search_paths: RefCell::new(libs),
crate_types: vec!(driver::config::CrateTypeDylib),
lint_opts: vec!((lint::Warnings, lint::allow)),
..rustc::driver::config::basic_options().clone()
};
let codemap = syntax::codemap::CodeMap::new();
let diagnostic_handler = syntax::diagnostic::default_handler(syntax::diagnostic::Auto);
let span_diagnostic_handler =
syntax::diagnostic::mk_span_handler(diagnostic_handler, codemap);
let sess = driver::session::build_session_(sessopts,
Some(cpath.clone()),
span_diagnostic_handler);
let mut cfg = build_configuration(&sess);
for cfg_ in cfgs.move_iter() {
let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
cfg.push(@dummy_spanned(ast::MetaWord(cfg_)));
}
let krate = phase_1_parse_input(&sess, cfg, &input);
let (krate, ast_map) = phase_2_configure_and_expand(&sess, &mut Loader::new(&sess),
krate, &from_str("rustdoc").unwrap());
let driver::driver::CrateAnalysis {
exported_items, public_items, ty_cx,..
} = phase_3_run_analysis_passes(sess, &krate, ast_map);
debug!("crate: {:?}", krate);
(DocContext {
krate: krate,
maybe_typed: Typed(ty_cx),
src: cpath.clone(),
external_paths: RefCell::new(Some(HashMap::new())),
}, CrateAnalysis {
exported_items: exported_items,
public_items: public_items,
external_paths: RefCell::new(None),
})
}
pub fn run_core(libs: HashSet<Path>, cfgs: Vec<StrBuf>, path: &Path)
-> (clean::Crate, CrateAnalysis) {
let (ctxt, analysis) = get_ast_and_resolve(path, libs, cfgs);
let ctxt = @ctxt;
super::ctxtkey.replace(Some(ctxt));
let krate = {
let mut v = RustdocVisitor::new(ctxt, Some(&analysis));
v.visit(&ctxt.krate);
v.clean()
};
let external_paths = ctxt.external_paths.borrow_mut().take();
*analysis.external_paths.borrow_mut() = external_paths;
(krate, analysis)
}
| {
match self.maybe_typed {
Typed(ref tcx) => &tcx.sess,
NotTyped(ref sess) => sess
}
} | identifier_body |
core.rs | // 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;
use rustc::{driver, middle};
use rustc::metadata::creader::Loader;
use rustc::middle::privacy;
use rustc::middle::lint;
use syntax::ast;
use syntax::parse::token;
use syntax;
use std::cell::RefCell;
use std::os;
use collections::{HashSet, HashMap};
use visit_ast::RustdocVisitor;
use clean;
use clean::Clean;
pub enum MaybeTyped {
Typed(middle::ty::ctxt),
NotTyped(driver::session::Session)
}
pub type ExternalPaths = RefCell<Option<HashMap<ast::DefId,
(Vec<StrBuf>, clean::TypeKind)>>>;
pub struct DocContext {
pub krate: ast::Crate,
pub maybe_typed: MaybeTyped,
pub src: Path,
pub external_paths: ExternalPaths,
}
impl DocContext {
pub fn sess<'a>(&'a self) -> &'a driver::session::Session {
match self.maybe_typed {
Typed(ref tcx) => &tcx.sess,
NotTyped(ref sess) => sess
}
}
}
pub struct CrateAnalysis {
pub exported_items: privacy::ExportedItems,
pub public_items: privacy::PublicItems,
pub external_paths: ExternalPaths,
}
/// Parses, resolves, and typechecks the given crate
fn get_ast_and_resolve(cpath: &Path, libs: HashSet<Path>, cfgs: Vec<StrBuf>)
-> (DocContext, CrateAnalysis) {
use syntax::codemap::dummy_spanned;
use rustc::driver::driver::{FileInput,
phase_1_parse_input,
phase_2_configure_and_expand,
phase_3_run_analysis_passes};
use rustc::driver::config::build_configuration;
let input = FileInput(cpath.clone());
let sessopts = driver::config::Options {
maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
addl_lib_search_paths: RefCell::new(libs),
crate_types: vec!(driver::config::CrateTypeDylib),
lint_opts: vec!((lint::Warnings, lint::allow)),
..rustc::driver::config::basic_options().clone()
};
let codemap = syntax::codemap::CodeMap::new();
let diagnostic_handler = syntax::diagnostic::default_handler(syntax::diagnostic::Auto);
let span_diagnostic_handler =
syntax::diagnostic::mk_span_handler(diagnostic_handler, codemap);
let sess = driver::session::build_session_(sessopts,
Some(cpath.clone()),
span_diagnostic_handler);
let mut cfg = build_configuration(&sess);
for cfg_ in cfgs.move_iter() {
let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
cfg.push(@dummy_spanned(ast::MetaWord(cfg_)));
}
let krate = phase_1_parse_input(&sess, cfg, &input);
let (krate, ast_map) = phase_2_configure_and_expand(&sess, &mut Loader::new(&sess),
krate, &from_str("rustdoc").unwrap());
let driver::driver::CrateAnalysis {
exported_items, public_items, ty_cx,..
} = phase_3_run_analysis_passes(sess, &krate, ast_map);
debug!("crate: {:?}", krate);
(DocContext {
krate: krate,
maybe_typed: Typed(ty_cx),
src: cpath.clone(),
external_paths: RefCell::new(Some(HashMap::new())),
}, CrateAnalysis {
exported_items: exported_items,
public_items: public_items,
external_paths: RefCell::new(None),
})
}
pub fn run_core(libs: HashSet<Path>, cfgs: Vec<StrBuf>, path: &Path)
-> (clean::Crate, CrateAnalysis) {
let (ctxt, analysis) = get_ast_and_resolve(path, libs, cfgs);
let ctxt = @ctxt;
super::ctxtkey.replace(Some(ctxt));
let krate = {
let mut v = RustdocVisitor::new(ctxt, Some(&analysis));
v.visit(&ctxt.krate);
v.clean()
};
let external_paths = ctxt.external_paths.borrow_mut().take();
*analysis.external_paths.borrow_mut() = external_paths;
(krate, analysis)
} | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split |
|
core.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use rustc;
use rustc::{driver, middle};
use rustc::metadata::creader::Loader;
use rustc::middle::privacy;
use rustc::middle::lint;
use syntax::ast;
use syntax::parse::token;
use syntax;
use std::cell::RefCell;
use std::os;
use collections::{HashSet, HashMap};
use visit_ast::RustdocVisitor;
use clean;
use clean::Clean;
pub enum MaybeTyped {
Typed(middle::ty::ctxt),
NotTyped(driver::session::Session)
}
pub type ExternalPaths = RefCell<Option<HashMap<ast::DefId,
(Vec<StrBuf>, clean::TypeKind)>>>;
pub struct | {
pub krate: ast::Crate,
pub maybe_typed: MaybeTyped,
pub src: Path,
pub external_paths: ExternalPaths,
}
impl DocContext {
pub fn sess<'a>(&'a self) -> &'a driver::session::Session {
match self.maybe_typed {
Typed(ref tcx) => &tcx.sess,
NotTyped(ref sess) => sess
}
}
}
pub struct CrateAnalysis {
pub exported_items: privacy::ExportedItems,
pub public_items: privacy::PublicItems,
pub external_paths: ExternalPaths,
}
/// Parses, resolves, and typechecks the given crate
fn get_ast_and_resolve(cpath: &Path, libs: HashSet<Path>, cfgs: Vec<StrBuf>)
-> (DocContext, CrateAnalysis) {
use syntax::codemap::dummy_spanned;
use rustc::driver::driver::{FileInput,
phase_1_parse_input,
phase_2_configure_and_expand,
phase_3_run_analysis_passes};
use rustc::driver::config::build_configuration;
let input = FileInput(cpath.clone());
let sessopts = driver::config::Options {
maybe_sysroot: Some(os::self_exe_path().unwrap().dir_path()),
addl_lib_search_paths: RefCell::new(libs),
crate_types: vec!(driver::config::CrateTypeDylib),
lint_opts: vec!((lint::Warnings, lint::allow)),
..rustc::driver::config::basic_options().clone()
};
let codemap = syntax::codemap::CodeMap::new();
let diagnostic_handler = syntax::diagnostic::default_handler(syntax::diagnostic::Auto);
let span_diagnostic_handler =
syntax::diagnostic::mk_span_handler(diagnostic_handler, codemap);
let sess = driver::session::build_session_(sessopts,
Some(cpath.clone()),
span_diagnostic_handler);
let mut cfg = build_configuration(&sess);
for cfg_ in cfgs.move_iter() {
let cfg_ = token::intern_and_get_ident(cfg_.as_slice());
cfg.push(@dummy_spanned(ast::MetaWord(cfg_)));
}
let krate = phase_1_parse_input(&sess, cfg, &input);
let (krate, ast_map) = phase_2_configure_and_expand(&sess, &mut Loader::new(&sess),
krate, &from_str("rustdoc").unwrap());
let driver::driver::CrateAnalysis {
exported_items, public_items, ty_cx,..
} = phase_3_run_analysis_passes(sess, &krate, ast_map);
debug!("crate: {:?}", krate);
(DocContext {
krate: krate,
maybe_typed: Typed(ty_cx),
src: cpath.clone(),
external_paths: RefCell::new(Some(HashMap::new())),
}, CrateAnalysis {
exported_items: exported_items,
public_items: public_items,
external_paths: RefCell::new(None),
})
}
pub fn run_core(libs: HashSet<Path>, cfgs: Vec<StrBuf>, path: &Path)
-> (clean::Crate, CrateAnalysis) {
let (ctxt, analysis) = get_ast_and_resolve(path, libs, cfgs);
let ctxt = @ctxt;
super::ctxtkey.replace(Some(ctxt));
let krate = {
let mut v = RustdocVisitor::new(ctxt, Some(&analysis));
v.visit(&ctxt.krate);
v.clean()
};
let external_paths = ctxt.external_paths.borrow_mut().take();
*analysis.external_paths.borrow_mut() = external_paths;
(krate, analysis)
}
| DocContext | identifier_name |
unit.rs | type Health = f64;
type Attack = f64;
type Level = u8;
type Experience = f64;
pub trait Unit {
fn new(health: f64, attack: f64) -> Self;
fn realize_hp(&self) -> f64;
fn realize_atk(&self) -> f64;
fn change_current_hp(&mut self, amount: f64);
fn show(&self) -> String {
format!("{}hp {}atk",
self.realize_hp() as i32,
self.realize_atk() as i32)
}
}
#[derive(Clone)]
pub struct Hero {
hp: Health,
atk: Attack,
lvl: Level,
exp: Experience,
}
impl Unit for Hero {
fn new(health: f64, attack: f64) -> Hero {
Hero {
hp: health,
atk: attack,
lvl: 1,
exp: 0.0,
}
}
fn realize_hp(&self) -> f64 { self.hp }
fn realize_atk(&self) -> f64 { self.atk }
fn change_current_hp(&mut self, amount: f64) { self.hp += amount; }
}
impl Hero {
pub fn realize_lvl(&self) -> u8 { self.lvl }
pub fn realize_exp(&self) -> f64 { self.exp }
}
#[derive(Clone)]
pub struct NonHero {
hp: Health,
atk: Attack,
}
impl Unit for NonHero {
fn new(health: f64, attack: f64) -> NonHero {
NonHero {
hp: health,
atk: attack,
}
}
fn | (&self) -> f64 { self.hp }
fn realize_atk(&self) -> f64 { self.atk }
fn change_current_hp(&mut self, amount: f64) { self.hp += amount; }
}
| realize_hp | identifier_name |
unit.rs | type Health = f64;
type Attack = f64;
type Level = u8;
type Experience = f64;
pub trait Unit {
fn new(health: f64, attack: f64) -> Self;
fn realize_hp(&self) -> f64;
fn realize_atk(&self) -> f64;
fn change_current_hp(&mut self, amount: f64);
fn show(&self) -> String {
format!("{}hp {}atk",
self.realize_hp() as i32,
self.realize_atk() as i32)
}
}
#[derive(Clone)]
pub struct Hero {
hp: Health,
atk: Attack,
lvl: Level,
exp: Experience,
}
impl Unit for Hero {
fn new(health: f64, attack: f64) -> Hero {
Hero {
hp: health,
atk: attack,
lvl: 1,
exp: 0.0,
} | fn realize_hp(&self) -> f64 { self.hp }
fn realize_atk(&self) -> f64 { self.atk }
fn change_current_hp(&mut self, amount: f64) { self.hp += amount; }
}
impl Hero {
pub fn realize_lvl(&self) -> u8 { self.lvl }
pub fn realize_exp(&self) -> f64 { self.exp }
}
#[derive(Clone)]
pub struct NonHero {
hp: Health,
atk: Attack,
}
impl Unit for NonHero {
fn new(health: f64, attack: f64) -> NonHero {
NonHero {
hp: health,
atk: attack,
}
}
fn realize_hp(&self) -> f64 { self.hp }
fn realize_atk(&self) -> f64 { self.atk }
fn change_current_hp(&mut self, amount: f64) { self.hp += amount; }
} | } | random_line_split |
unit.rs | type Health = f64;
type Attack = f64;
type Level = u8;
type Experience = f64;
pub trait Unit {
fn new(health: f64, attack: f64) -> Self;
fn realize_hp(&self) -> f64;
fn realize_atk(&self) -> f64;
fn change_current_hp(&mut self, amount: f64);
fn show(&self) -> String {
format!("{}hp {}atk",
self.realize_hp() as i32,
self.realize_atk() as i32)
}
}
#[derive(Clone)]
pub struct Hero {
hp: Health,
atk: Attack,
lvl: Level,
exp: Experience,
}
impl Unit for Hero {
fn new(health: f64, attack: f64) -> Hero {
Hero {
hp: health,
atk: attack,
lvl: 1,
exp: 0.0,
}
}
fn realize_hp(&self) -> f64 { self.hp }
fn realize_atk(&self) -> f64 { self.atk }
fn change_current_hp(&mut self, amount: f64) { self.hp += amount; }
}
impl Hero {
pub fn realize_lvl(&self) -> u8 { self.lvl }
pub fn realize_exp(&self) -> f64 { self.exp }
}
#[derive(Clone)]
pub struct NonHero {
hp: Health,
atk: Attack,
}
impl Unit for NonHero {
fn new(health: f64, attack: f64) -> NonHero {
NonHero {
hp: health,
atk: attack,
}
}
fn realize_hp(&self) -> f64 { self.hp }
fn realize_atk(&self) -> f64 |
fn change_current_hp(&mut self, amount: f64) { self.hp += amount; }
}
| { self.atk } | identifier_body |
lib.rs | #![doc(html_root_url = "http://cpjreynolds.github.io/rustty/rustty/index.html")]
//! # Rustty
//!
//! Rustty is a terminal UI library that provides a simple, concise abstraction over an
//! underlying terminal device.
//!
//! Rustty is based on the concepts of cells and events. A terminal display is an array of cells,
//! each holding a character and a set of foreground and background styles. Events are how a
//! terminal communicates changes in its state; events are received from a terminal, processed, and
//! pushed onto an input stream to be read and responded to.
//!
//! Futher reading on the concepts behind Rustty can be found in the
//! [README](https://github.com/cpjreynolds/rustty/blob/master/README.md)
extern crate term;
extern crate libc;
extern crate gag;
mod core;
pub mod ui; |
pub use core::terminal::Terminal;
pub use core::cellbuffer::{Cell, Color, Attr, CellAccessor};
pub use core::position::{Pos, Size, HasSize, HasPosition};
pub use core::input::Event; | random_line_split |
|
gzip.rs | use byteorder::{LittleEndian, WriteBytesExt};
use std::io::{self, Write};
use crate::deflate::{deflate, BlockType};
use crate::Options;
const CRC_IEEE: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC);
static HEADER: &'static [u8] = &[
31, // ID1
139, // ID2 | 0, // FLG
0, // MTIME
0, 0, 0, 2, // XFL, 2 indicates best compression.
3, // OS follows Unix conventions.
];
/// Compresses the data according to the gzip specification, RFC 1952.
pub fn gzip_compress<W>(options: &Options, in_data: &[u8], mut out: W) -> io::Result<()>
where
W: Write,
{
out.by_ref().write_all(HEADER)?;
deflate(options, BlockType::Dynamic, in_data, out.by_ref())?;
out.by_ref()
.write_u32::<LittleEndian>(CRC_IEEE.checksum(in_data))?;
out.write_u32::<LittleEndian>(in_data.len() as u32)
} | 8, // CM | random_line_split |
gzip.rs | use byteorder::{LittleEndian, WriteBytesExt};
use std::io::{self, Write};
use crate::deflate::{deflate, BlockType};
use crate::Options;
const CRC_IEEE: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC);
static HEADER: &'static [u8] = &[
31, // ID1
139, // ID2
8, // CM
0, // FLG
0, // MTIME
0, 0, 0, 2, // XFL, 2 indicates best compression.
3, // OS follows Unix conventions.
];
/// Compresses the data according to the gzip specification, RFC 1952.
pub fn gzip_compress<W>(options: &Options, in_data: &[u8], mut out: W) -> io::Result<()>
where
W: Write,
| {
out.by_ref().write_all(HEADER)?;
deflate(options, BlockType::Dynamic, in_data, out.by_ref())?;
out.by_ref()
.write_u32::<LittleEndian>(CRC_IEEE.checksum(in_data))?;
out.write_u32::<LittleEndian>(in_data.len() as u32)
} | identifier_body |
|
gzip.rs | use byteorder::{LittleEndian, WriteBytesExt};
use std::io::{self, Write};
use crate::deflate::{deflate, BlockType};
use crate::Options;
const CRC_IEEE: crc::Crc<u32> = crc::Crc::<u32>::new(&crc::CRC_32_ISO_HDLC);
static HEADER: &'static [u8] = &[
31, // ID1
139, // ID2
8, // CM
0, // FLG
0, // MTIME
0, 0, 0, 2, // XFL, 2 indicates best compression.
3, // OS follows Unix conventions.
];
/// Compresses the data according to the gzip specification, RFC 1952.
pub fn | <W>(options: &Options, in_data: &[u8], mut out: W) -> io::Result<()>
where
W: Write,
{
out.by_ref().write_all(HEADER)?;
deflate(options, BlockType::Dynamic, in_data, out.by_ref())?;
out.by_ref()
.write_u32::<LittleEndian>(CRC_IEEE.checksum(in_data))?;
out.write_u32::<LittleEndian>(in_data.len() as u32)
}
| gzip_compress | identifier_name |
vga_buffer.rs | use core::ptr::Unique;
use core::fmt::Write;
use spin::Mutex;
macro_rules! print {
($($arg:tt)*) => ({
use core::fmt::Write;
$crate::vga_buffer::WRITER.lock().write_fmt(format_args!($($arg)*)).unwrap();
});
}
macro_rules! println {
($fmt:expr) => (print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
}
const BUFFER_HEIGHT: usize = 25;
const BUFFER_WIDTH: usize = 80;
pub fn clear_screen() {
for _ in 0..BUFFER_HEIGHT {
println!("");
}
}
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
LightMagenta = 13,
Yellow = 14,
White = 15,
}
#[derive(Copy, Clone)]
struct ColorCode(u8);
impl ColorCode {
const fn new(foreground: Color, background: Color) -> ColorCode {
ColorCode((background as u8) << 4 | (foreground as u8))
}
}
#[repr(C)]
#[derive(Copy, Clone)]
struct ScreenChar {
ascii_character: u8,
color_code: ColorCode,
}
struct Buffer {
chars: [[ScreenChar; BUFFER_WIDTH]; BUFFER_HEIGHT],
}
pub struct Writer {
column_position: usize,
color_code: ColorCode,
buffer: Unique<Buffer>,
}
impl Writer {
fn new(foreground: Color, background: Color) -> Writer {
Writer {
column_position: 0,
color_code: ColorCode::new(foreground, background),
buffer: unsafe { Unique::new(0xb8000 as *mut _) },
}
}
pub fn write_byte(&mut self, byte: u8) | }
pub fn write_str(&mut self, s: &str) {
for byte in s.bytes() {
self.write_byte(byte)
}
}
fn buffer(&mut self) -> &mut Buffer {
unsafe { self.buffer.get_mut() }
}
fn new_line(&mut self) {
for row in 0..(BUFFER_HEIGHT-1) {
let buffer = self.buffer();
buffer.chars[row] = buffer.chars[row + 1]
}
self.clear_row(BUFFER_HEIGHT-1);
self.column_position = 0;
}
fn clear_row(&mut self, row: usize) {
let blank = ScreenChar {
ascii_character: b' ',
color_code: self.color_code,
};
self.buffer().chars[row] = [blank; BUFFER_WIDTH];
}
}
impl ::core::fmt::Write for Writer {
fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
for byte in s.bytes() {
self.write_byte(byte)
}
Ok(())
}
}
pub static WRITER: Mutex<Writer> = Mutex::new(Writer {
column_position: 0,
color_code: ColorCode::new(Color::LightGreen, Color::Black),
buffer: unsafe { Unique::new(0xb8000 as *mut _) },
});
| {
match byte {
b'\n' => {
self.new_line();
},
byte => {
if self.column_position >= BUFFER_WIDTH {
self.new_line();
}
let row = BUFFER_HEIGHT -1;
let col = self.column_position;
self.buffer().chars[row][col] = ScreenChar {
ascii_character: byte,
color_code: self.color_code,
};
self.column_position += 1;
}
} | identifier_body |
vga_buffer.rs | use core::ptr::Unique;
use core::fmt::Write;
use spin::Mutex;
macro_rules! print {
($($arg:tt)*) => ({
use core::fmt::Write;
$crate::vga_buffer::WRITER.lock().write_fmt(format_args!($($arg)*)).unwrap();
});
}
macro_rules! println {
($fmt:expr) => (print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
}
const BUFFER_HEIGHT: usize = 25;
const BUFFER_WIDTH: usize = 80;
pub fn clear_screen() {
for _ in 0..BUFFER_HEIGHT {
println!("");
}
}
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
LightMagenta = 13,
Yellow = 14,
White = 15,
}
#[derive(Copy, Clone)]
struct ColorCode(u8);
impl ColorCode {
const fn new(foreground: Color, background: Color) -> ColorCode {
ColorCode((background as u8) << 4 | (foreground as u8))
}
}
#[repr(C)]
#[derive(Copy, Clone)]
struct ScreenChar {
ascii_character: u8,
color_code: ColorCode,
}
struct Buffer {
chars: [[ScreenChar; BUFFER_WIDTH]; BUFFER_HEIGHT],
}
pub struct Writer {
column_position: usize,
color_code: ColorCode,
buffer: Unique<Buffer>,
}
impl Writer {
fn new(foreground: Color, background: Color) -> Writer {
Writer {
column_position: 0,
color_code: ColorCode::new(foreground, background),
buffer: unsafe { Unique::new(0xb8000 as *mut _) },
}
}
pub fn write_byte(&mut self, byte: u8) {
match byte {
b'\n' => | ,
byte => {
if self.column_position >= BUFFER_WIDTH {
self.new_line();
}
let row = BUFFER_HEIGHT -1;
let col = self.column_position;
self.buffer().chars[row][col] = ScreenChar {
ascii_character: byte,
color_code: self.color_code,
};
self.column_position += 1;
}
}
}
pub fn write_str(&mut self, s: &str) {
for byte in s.bytes() {
self.write_byte(byte)
}
}
fn buffer(&mut self) -> &mut Buffer {
unsafe { self.buffer.get_mut() }
}
fn new_line(&mut self) {
for row in 0..(BUFFER_HEIGHT-1) {
let buffer = self.buffer();
buffer.chars[row] = buffer.chars[row + 1]
}
self.clear_row(BUFFER_HEIGHT-1);
self.column_position = 0;
}
fn clear_row(&mut self, row: usize) {
let blank = ScreenChar {
ascii_character: b' ',
color_code: self.color_code,
};
self.buffer().chars[row] = [blank; BUFFER_WIDTH];
}
}
impl ::core::fmt::Write for Writer {
fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
for byte in s.bytes() {
self.write_byte(byte)
}
Ok(())
}
}
pub static WRITER: Mutex<Writer> = Mutex::new(Writer {
column_position: 0,
color_code: ColorCode::new(Color::LightGreen, Color::Black),
buffer: unsafe { Unique::new(0xb8000 as *mut _) },
});
| {
self.new_line();
} | conditional_block |
vga_buffer.rs | use core::ptr::Unique;
use core::fmt::Write;
use spin::Mutex;
macro_rules! print {
($($arg:tt)*) => ({
use core::fmt::Write;
$crate::vga_buffer::WRITER.lock().write_fmt(format_args!($($arg)*)).unwrap();
});
}
macro_rules! println {
($fmt:expr) => (print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
}
const BUFFER_HEIGHT: usize = 25;
const BUFFER_WIDTH: usize = 80;
pub fn clear_screen() {
for _ in 0..BUFFER_HEIGHT {
println!("");
}
}
#[repr(u8)]
pub enum | {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
LightMagenta = 13,
Yellow = 14,
White = 15,
}
#[derive(Copy, Clone)]
struct ColorCode(u8);
impl ColorCode {
const fn new(foreground: Color, background: Color) -> ColorCode {
ColorCode((background as u8) << 4 | (foreground as u8))
}
}
#[repr(C)]
#[derive(Copy, Clone)]
struct ScreenChar {
ascii_character: u8,
color_code: ColorCode,
}
struct Buffer {
chars: [[ScreenChar; BUFFER_WIDTH]; BUFFER_HEIGHT],
}
pub struct Writer {
column_position: usize,
color_code: ColorCode,
buffer: Unique<Buffer>,
}
impl Writer {
fn new(foreground: Color, background: Color) -> Writer {
Writer {
column_position: 0,
color_code: ColorCode::new(foreground, background),
buffer: unsafe { Unique::new(0xb8000 as *mut _) },
}
}
pub fn write_byte(&mut self, byte: u8) {
match byte {
b'\n' => {
self.new_line();
},
byte => {
if self.column_position >= BUFFER_WIDTH {
self.new_line();
}
let row = BUFFER_HEIGHT -1;
let col = self.column_position;
self.buffer().chars[row][col] = ScreenChar {
ascii_character: byte,
color_code: self.color_code,
};
self.column_position += 1;
}
}
}
pub fn write_str(&mut self, s: &str) {
for byte in s.bytes() {
self.write_byte(byte)
}
}
fn buffer(&mut self) -> &mut Buffer {
unsafe { self.buffer.get_mut() }
}
fn new_line(&mut self) {
for row in 0..(BUFFER_HEIGHT-1) {
let buffer = self.buffer();
buffer.chars[row] = buffer.chars[row + 1]
}
self.clear_row(BUFFER_HEIGHT-1);
self.column_position = 0;
}
fn clear_row(&mut self, row: usize) {
let blank = ScreenChar {
ascii_character: b' ',
color_code: self.color_code,
};
self.buffer().chars[row] = [blank; BUFFER_WIDTH];
}
}
impl ::core::fmt::Write for Writer {
fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
for byte in s.bytes() {
self.write_byte(byte)
}
Ok(())
}
}
pub static WRITER: Mutex<Writer> = Mutex::new(Writer {
column_position: 0,
color_code: ColorCode::new(Color::LightGreen, Color::Black),
buffer: unsafe { Unique::new(0xb8000 as *mut _) },
});
| Color | identifier_name |
vga_buffer.rs | use core::ptr::Unique;
use core::fmt::Write;
use spin::Mutex;
macro_rules! print {
($($arg:tt)*) => ({
use core::fmt::Write;
$crate::vga_buffer::WRITER.lock().write_fmt(format_args!($($arg)*)).unwrap();
});
}
macro_rules! println {
($fmt:expr) => (print!(concat!($fmt, "\n")));
($fmt:expr, $($arg:tt)*) => (print!(concat!($fmt, "\n"), $($arg)*));
}
const BUFFER_HEIGHT: usize = 25;
const BUFFER_WIDTH: usize = 80;
pub fn clear_screen() {
for _ in 0..BUFFER_HEIGHT {
println!("");
}
}
#[repr(u8)]
pub enum Color {
Black = 0,
Blue = 1,
Green = 2,
Cyan = 3,
Red = 4,
Magenta = 5,
Brown = 6,
LightGray = 7,
DarkGray = 8,
LightBlue = 9,
LightGreen = 10,
LightCyan = 11,
LightRed = 12,
LightMagenta = 13,
Yellow = 14,
White = 15,
}
#[derive(Copy, Clone)]
struct ColorCode(u8);
impl ColorCode {
const fn new(foreground: Color, background: Color) -> ColorCode {
ColorCode((background as u8) << 4 | (foreground as u8))
}
}
#[repr(C)]
#[derive(Copy, Clone)]
struct ScreenChar {
ascii_character: u8,
color_code: ColorCode,
}
struct Buffer {
chars: [[ScreenChar; BUFFER_WIDTH]; BUFFER_HEIGHT],
}
pub struct Writer {
column_position: usize,
color_code: ColorCode,
buffer: Unique<Buffer>,
}
impl Writer {
fn new(foreground: Color, background: Color) -> Writer {
Writer {
column_position: 0,
color_code: ColorCode::new(foreground, background),
buffer: unsafe { Unique::new(0xb8000 as *mut _) },
}
}
pub fn write_byte(&mut self, byte: u8) {
match byte {
b'\n' => {
self.new_line();
},
byte => {
if self.column_position >= BUFFER_WIDTH {
self.new_line();
}
let row = BUFFER_HEIGHT -1;
let col = self.column_position;
self.buffer().chars[row][col] = ScreenChar {
ascii_character: byte,
color_code: self.color_code,
};
self.column_position += 1;
}
}
}
pub fn write_str(&mut self, s: &str) { | for byte in s.bytes() {
self.write_byte(byte)
}
}
fn buffer(&mut self) -> &mut Buffer {
unsafe { self.buffer.get_mut() }
}
fn new_line(&mut self) {
for row in 0..(BUFFER_HEIGHT-1) {
let buffer = self.buffer();
buffer.chars[row] = buffer.chars[row + 1]
}
self.clear_row(BUFFER_HEIGHT-1);
self.column_position = 0;
}
fn clear_row(&mut self, row: usize) {
let blank = ScreenChar {
ascii_character: b' ',
color_code: self.color_code,
};
self.buffer().chars[row] = [blank; BUFFER_WIDTH];
}
}
impl ::core::fmt::Write for Writer {
fn write_str(&mut self, s: &str) -> ::core::fmt::Result {
for byte in s.bytes() {
self.write_byte(byte)
}
Ok(())
}
}
pub static WRITER: Mutex<Writer> = Mutex::new(Writer {
column_position: 0,
color_code: ColorCode::new(Color::LightGreen, Color::Black),
buffer: unsafe { Unique::new(0xb8000 as *mut _) },
}); | random_line_split |
|
maildir.rs | use std::time::Duration;
use chan::Sender;
use block::{Block, ConfigBlock};
use config::Config;
use de::deserialize_duration;
use errors::*;
use widgets::text::TextWidget;
use widget::{I3BarWidget, State};
use input::I3BarEvent;
use scheduler::Task;
use maildir::Maildir as ExtMaildir;
use uuid::Uuid;
pub struct Maildir {
text: TextWidget,
id: String,
update_interval: Duration,
inboxes: Vec<String>,
threshold_warning: usize,
threshold_critical: usize,
}
#[derive(Deserialize, Debug, Default, Clone)]
#[serde(deny_unknown_fields)]
pub struct MaildirConfig {
/// Update interval in seconds
#[serde(default = "MaildirConfig::default_interval", deserialize_with = "deserialize_duration")]
pub interval: Duration,
pub inboxes: Vec<String>,
#[serde(default = "MaildirConfig::default_threshold_warning")]
pub threshold_warning: usize,
#[serde(default = "MaildirConfig::default_threshold_critical")]
pub threshold_critical: usize,
}
impl MaildirConfig {
fn default_interval() -> Duration {
Duration::from_secs(5)
}
fn default_threshold_warning() -> usize {
1 as usize
}
fn default_threshold_critical() -> usize {
10 as usize
}
}
impl ConfigBlock for Maildir {
type Config = MaildirConfig;
fn new(block_config: Self::Config, config: Config, _tx_update_request: Sender<Task>) -> Result<Self> {
Ok(Maildir {
id: Uuid::new_v4().simple().to_string(),
update_interval: block_config.interval,
text: TextWidget::new(config.clone())
.with_icon("mail")
.with_text(""),
inboxes: block_config.inboxes,
threshold_warning: block_config.threshold_warning,
threshold_critical: block_config.threshold_critical,
})
}
}
impl Block for Maildir {
fn update(&mut self) -> Result<Option<Duration>> {
let mut newmails = 0;
for inbox in &self.inboxes {
let isl: &str = &inbox[..];
let maildir = ExtMaildir::from(isl);
newmails += maildir.count_new();
}
let mut state = { State::Idle };
if newmails >= self.threshold_critical {
state = { State::Critical };
} else if newmails >= self.threshold_warning |
self.text.set_state(state);
self.text.set_text(format!("{}", newmails));
Ok(Some(self.update_interval))
}
fn view(&self) -> Vec<&I3BarWidget> {
vec![&self.text]
}
fn click(&mut self, _: &I3BarEvent) -> Result<()> {
Ok(())
}
fn id(&self) -> &str {
&self.id
}
}
| {
state = { State::Warning };
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.