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 |
---|---|---|---|---|
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 canvas_traits::CanvasMsg;
use compositor_msg::Epoch;
use euclid::scale_factor::ScaleFactor;
use euclid::size::{Size2D, TypedSize2D};
use hyper::header::Headers;
use hyper::method::Method;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender, IpcSharedMemory};
use layers::geometry::DevicePixel;
use offscreen_gl_context::GLContextAttributes;
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::collections::HashMap;
use std::fmt;
use std::sync::mpsc::channel;
use style_traits::viewport::ViewportConstraints;
use url::Url;
use util::cursor::Cursor;
use util::geometry::{PagePx, ViewportPx};
use util::mem::HeapSizeOf;
use webdriver_msg::{LoadStatus, WebDriverScriptCommand};
#[derive(Deserialize, Serialize)]
pub struct | <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 type of focus event that is sent to a pipeline
#[derive(Copy, Clone, PartialEq)]
pub enum FocusType {
Element, // The first focus message - focus the element itself
Parent, // Focusing a parent element (an iframe)
}
/// Specifies the information required to load a URL in an iframe.
#[derive(Deserialize, Serialize)]
pub struct IframeLoadInfo {
/// Url to load
pub url: 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,
}
/// Messages from the compositor to the constellation.
#[derive(Deserialize, Serialize)]
pub enum CompositorMsg {
Exit,
FrameSize(PipelineId, Size2D<f32>),
/// Request that the constellation send the FrameId corresponding to the document
/// with the provided pipeline id
GetFrame(PipelineId, IpcSender<Option<FrameId>>),
/// Request that the constellation send the current pipeline id for the provided frame
/// id, or for the root frame if this is None, over a provided channel
GetPipeline(Option<FrameId>, IpcSender<Option<PipelineId>>),
/// Requests that the constellation inform the compositor of the title of the pipeline
/// immediately.
GetPipelineTitle(PipelineId),
InitLoadUrl(Url),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
KeyEvent(Key, KeyState, KeyModifiers),
LoadUrl(PipelineId, LoadData),
Navigate(Option<(PipelineId, SubpageId)>, NavigationDirection),
ResizedWindow(WindowSizeData),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
}
/// Messages from the script to the constellation.
#[derive(Deserialize, Serialize)]
pub enum ScriptMsg {
/// Indicates whether this pipeline is currently running animations.
ChangeRunningAnimationsState(PipelineId, AnimationState),
/// Requests that a new 2D canvas thread be created. (This is done in the constellation because
/// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.)
CreateCanvasPaintTask(Size2D<i32>, IpcSender<(IpcSender<CanvasMsg>, usize)>),
/// Requests that a new WebGL thread be created. (This is done in the constellation because
/// WebGL uses the GPU and we don't want to give untrusted content access to the GPU.)
CreateWebGLPaintTask(Size2D<i32>,
GLContextAttributes,
IpcSender<Result<(IpcSender<CanvasMsg>, usize), String>>),
/// Dispatched after the DOM load event has fired on a document
/// Causes a `load` event to be dispatched to any enclosing frame context element
/// for the given pipeline.
DOMLoad(PipelineId),
Failure(Failure),
/// Notifies the constellation that this frame has received focus.
Focus(PipelineId),
/// Requests that the constellation retrieve the current contents of the clipboard
GetClipboardContents(IpcSender<String>),
/// <head> tag finished parsing
HeadParsed,
LoadComplete(PipelineId),
LoadUrl(PipelineId, LoadData),
/// Dispatch a mozbrowser event to a given iframe. Only available in experimental mode.
MozBrowserEvent(PipelineId, SubpageId, MozBrowserEvent),
Navigate(Option<(PipelineId, SubpageId)>, NavigationDirection),
/// Favicon detected
NewFavicon(Url),
/// Status message to be displayed in the chrome, eg. a link URL on mouseover.
NodeStatus(Option<String>),
/// Notification that this iframe should be removed.
RemoveIFrame(PipelineId),
ScriptLoadedURLInIFrame(IframeLoadInfo),
/// Requests that the constellation set the contents of the clipboard
SetClipboardContents(String),
/// Requests that the constellation inform the compositor of the a cursor change.
SetCursor(Cursor),
/// Notifies the constellation that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
}
/// Messages from the paint task to the constellation.
#[derive(Deserialize, Serialize)]
pub enum PaintMsg {
Ready(PipelineId),
Failure(Failure),
}
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize, Debug)]
pub enum AnimationState {
AnimationsPresent,
AnimationCallbacksPresent,
NoAnimationsPresent,
NoAnimationCallbacksPresent,
}
// 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,
/// 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);
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct WorkerId(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);
| ConstellationChan | 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 canvas_traits::CanvasMsg;
use compositor_msg::Epoch;
use euclid::scale_factor::ScaleFactor;
use euclid::size::{Size2D, TypedSize2D};
use hyper::header::Headers;
use hyper::method::Method;
use ipc_channel::ipc::{self, IpcReceiver, IpcSender, IpcSharedMemory};
use layers::geometry::DevicePixel;
use offscreen_gl_context::GLContextAttributes;
use serde::{Deserialize, Serialize};
use std::cell::Cell;
use std::collections::HashMap;
use std::fmt;
use std::sync::mpsc::channel;
use style_traits::viewport::ViewportConstraints;
use url::Url;
use util::cursor::Cursor;
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 type of focus event that is sent to a pipeline
#[derive(Copy, Clone, PartialEq)]
pub enum FocusType {
Element, // The first focus message - focus the element itself
Parent, // Focusing a parent element (an iframe)
}
/// Specifies the information required to load a URL in an iframe.
#[derive(Deserialize, Serialize)]
pub struct IframeLoadInfo {
/// Url to load
pub url: 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,
}
/// Messages from the compositor to the constellation.
#[derive(Deserialize, Serialize)]
pub enum CompositorMsg {
Exit,
FrameSize(PipelineId, Size2D<f32>),
/// Request that the constellation send the FrameId corresponding to the document
/// with the provided pipeline id
GetFrame(PipelineId, IpcSender<Option<FrameId>>),
/// Request that the constellation send the current pipeline id for the provided frame
/// id, or for the root frame if this is None, over a provided channel
GetPipeline(Option<FrameId>, IpcSender<Option<PipelineId>>),
/// Requests that the constellation inform the compositor of the title of the pipeline
/// immediately.
GetPipelineTitle(PipelineId),
InitLoadUrl(Url),
/// Query the constellation to see if the current compositor output is stable
IsReadyToSaveImage(HashMap<PipelineId, Epoch>),
KeyEvent(Key, KeyState, KeyModifiers),
LoadUrl(PipelineId, LoadData),
Navigate(Option<(PipelineId, SubpageId)>, NavigationDirection),
ResizedWindow(WindowSizeData),
/// Requests that the constellation instruct layout to begin a new tick of the animation.
TickAnimation(PipelineId),
/// Dispatch a webdriver command
WebDriverCommand(WebDriverCommandMsg),
}
/// Messages from the script to the constellation.
#[derive(Deserialize, Serialize)]
pub enum ScriptMsg {
/// Indicates whether this pipeline is currently running animations.
ChangeRunningAnimationsState(PipelineId, AnimationState),
/// Requests that a new 2D canvas thread be created. (This is done in the constellation because
/// 2D canvases may use the GPU and we don't want to give untrusted content access to the GPU.)
CreateCanvasPaintTask(Size2D<i32>, IpcSender<(IpcSender<CanvasMsg>, usize)>),
/// Requests that a new WebGL thread be created. (This is done in the constellation because
/// WebGL uses the GPU and we don't want to give untrusted content access to the GPU.)
CreateWebGLPaintTask(Size2D<i32>,
GLContextAttributes,
IpcSender<Result<(IpcSender<CanvasMsg>, usize), String>>),
/// Dispatched after the DOM load event has fired on a document
/// Causes a `load` event to be dispatched to any enclosing frame context element
/// for the given pipeline.
DOMLoad(PipelineId),
Failure(Failure),
/// Notifies the constellation that this frame has received focus.
Focus(PipelineId),
/// Requests that the constellation retrieve the current contents of the clipboard
GetClipboardContents(IpcSender<String>),
/// <head> tag finished parsing
HeadParsed,
LoadComplete(PipelineId),
LoadUrl(PipelineId, LoadData),
/// Dispatch a mozbrowser event to a given iframe. Only available in experimental mode.
MozBrowserEvent(PipelineId, SubpageId, MozBrowserEvent),
Navigate(Option<(PipelineId, SubpageId)>, NavigationDirection),
/// Favicon detected
NewFavicon(Url),
/// Status message to be displayed in the chrome, eg. a link URL on mouseover.
NodeStatus(Option<String>),
/// Notification that this iframe should be removed.
RemoveIFrame(PipelineId),
ScriptLoadedURLInIFrame(IframeLoadInfo),
/// Requests that the constellation set the contents of the clipboard
SetClipboardContents(String),
/// Requests that the constellation inform the compositor of the a cursor change.
SetCursor(Cursor),
/// Notifies the constellation that the viewport has been constrained in some manner
ViewportConstrained(PipelineId, ViewportConstraints),
}
/// Messages from the paint task to the constellation.
#[derive(Deserialize, Serialize)]
pub enum PaintMsg {
Ready(PipelineId),
Failure(Failure),
}
#[derive(Clone, Eq, PartialEq, Deserialize, Serialize, Debug)]
pub enum AnimationState {
AnimationsPresent,
AnimationCallbacksPresent,
NoAnimationsPresent,
NoAnimationCallbacksPresent,
}
// 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,
/// 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);
#[derive(Clone, PartialEq, Eq, Copy, Hash, Debug, Deserialize, Serialize, HeapSizeOf)]
pub struct WorkerId(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
})
}
| // 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); | // 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 | random_line_split |
htmlparagraphelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLParagraphElement {
htmlelement: HTMLElement
} | HTMLParagraphElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLParagraphElement> {
let element = HTMLParagraphElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLParagraphElementBinding::Wrap)
}
} |
impl HTMLParagraphElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLParagraphElement { | random_line_split |
htmlparagraphelement.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding;
use dom::bindings::js::Root;
use dom::document::Document;
use dom::htmlelement::HTMLElement;
use dom::node::Node;
use string_cache::Atom;
use util::str::DOMString;
#[dom_struct]
pub struct | {
htmlelement: HTMLElement
}
impl HTMLParagraphElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLParagraphElement {
HTMLParagraphElement {
htmlelement:
HTMLElement::new_inherited(localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLParagraphElement> {
let element = HTMLParagraphElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLParagraphElementBinding::Wrap)
}
}
| HTMLParagraphElement | identifier_name |
identifiers.rs | extern crate memmap;
use self::memmap::{Mmap, Protection};
use std::collections::HashMap;
use std::io::BufRead;
use std::process::Command;
use std::str;
use rustc_serialize::json;
use crate::config;
fn uppercase(s: &[u8]) -> Vec<u8> {
let mut result = vec![];
for i in 0..s.len() {
result.push(if s[i] >= 'a' as u8 && s[i] <= 'z' as u8 {
s[i] - ('a' as u8) + ('A' as u8)
} else {
s[i]
});
}
result
}
pub struct IdentMap {
mmap: Option<Mmap>,
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct IdentResult {
pub id: String,
pub symbol: String,
}
fn demangle_name(name: &str) -> String {
let output = Command::new("c++filt")
.arg("--no-params")
.arg(name)
.output();
match output {
Err(_) => name.to_string(),
Ok(output) => {
if!output.status.success() {
return name.to_string();
}
String::from_utf8(output.stdout)
.unwrap_or(name.to_string())
.trim()
.to_string()
}
}
}
impl IdentMap {
fn new(filename: &str) -> IdentMap {
let mmap = match Mmap::open_path(filename, Protection::Read) {
Ok(mmap) => Some(mmap),
Err(e) => {
warn!("Failed to mmap {}: {:?}", filename, e);
None
}
};
IdentMap { mmap }
}
pub fn load(config: &config::Config) -> HashMap<String, IdentMap> {
let mut result = HashMap::new();
for (tree_name, tree_config) in &config.trees {
println!("Loading identifiers {}", tree_name);
let filename = format!("{}/identifiers", tree_config.paths.index_path);
let map = IdentMap::new(&filename);
result.insert(tree_name.clone(), map);
}
result
}
fn get_line(&self, pos: usize) -> &[u8] {
let mut pos = pos;
let mmap = match self.mmap {
Some(ref m) => m,
None => return &[],
};
let bytes: &[u8] = unsafe { mmap.as_slice() };
if bytes[pos] == '\n' as u8 {
pos -= 1;
}
let mut start = pos;
let mut end = pos;
while start > 0 && bytes[start - 1]!= '\n' as u8 {
start -= 1;
}
let size = mmap.len();
while end < size && bytes[end]!= '\n' as u8 {
end += 1;
}
&bytes[start..end]
}
fn bisect(&self, needle: &[u8], upper_bound: bool) -> usize {
let mut needle = uppercase(needle);
if upper_bound {
needle.push('~' as u8);
}
let mut first = 0;
let mut count = match self.mmap {
Some(ref m) => m.len(),
None => return 0,
};
while count > 0 {
let step = count / 2;
let pos = first + step;
let line = self.get_line(pos);
let line_upper = uppercase(line);
if line_upper < needle || (upper_bound && line_upper == needle) {
first = pos + 1;
count -= step + 1;
} else {
count = step;
}
}
first
}
// NEED A WAY TO LIMIT NUMBER OF RESULTS RETURNED TO 6
// Also need to apply c++filt to the ident as a better human-readable name
pub fn lookup(
&self,
needle: &str,
complete: bool,
fold_case: bool,
max_results: usize,
) -> Vec<IdentResult> {
let mmap = match self.mmap {
Some(ref m) => m,
None => return vec![],
};
let start = self.bisect(needle.as_bytes(), false);
let end = self.bisect(needle.as_bytes(), true);
let mut result = vec![];
let bytes: &[u8] = unsafe { mmap.as_slice() };
let slice = &bytes[start..end];
for line in slice.lines() {
let line = line.unwrap();
let mut pieces = line.split(' ');
let mut id = pieces.next().unwrap().to_string();
let symbol = pieces.next().unwrap();
{
let suffix = &id[needle.len()..];
if suffix.contains(':') || suffix.contains('.') || (complete && suffix.len() > 0) {
continue;
}
}
if!fold_case &&!id.starts_with(needle) {
continue;
}
let demangled = demangle_name(&symbol);
if demangled!= symbol |
result.push(IdentResult {
id: id,
symbol: symbol.to_string(),
});
if result.len() == max_results {
break;
}
}
result
}
pub fn lookup_json(
&self,
needle: &str,
complete: bool,
fold_case: bool,
max_results: usize,
) -> String {
let results = self.lookup(needle, complete, fold_case, max_results);
json::encode(&results).unwrap()
}
}
| {
id = demangled;
} | conditional_block |
identifiers.rs | extern crate memmap;
use self::memmap::{Mmap, Protection};
use std::collections::HashMap;
use std::io::BufRead;
use std::process::Command;
use std::str;
use rustc_serialize::json;
use crate::config;
fn uppercase(s: &[u8]) -> Vec<u8> {
let mut result = vec![];
for i in 0..s.len() {
result.push(if s[i] >= 'a' as u8 && s[i] <= 'z' as u8 {
s[i] - ('a' as u8) + ('A' as u8)
} else {
s[i]
});
}
result
}
pub struct IdentMap {
mmap: Option<Mmap>,
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct IdentResult {
pub id: String,
pub symbol: String,
}
fn demangle_name(name: &str) -> String {
let output = Command::new("c++filt")
.arg("--no-params")
.arg(name)
.output();
match output {
Err(_) => name.to_string(),
Ok(output) => {
if!output.status.success() {
return name.to_string();
}
String::from_utf8(output.stdout)
.unwrap_or(name.to_string())
.trim()
.to_string()
}
}
}
impl IdentMap {
fn new(filename: &str) -> IdentMap {
let mmap = match Mmap::open_path(filename, Protection::Read) {
Ok(mmap) => Some(mmap),
Err(e) => {
warn!("Failed to mmap {}: {:?}", filename, e);
None
}
};
IdentMap { mmap }
}
pub fn load(config: &config::Config) -> HashMap<String, IdentMap> {
let mut result = HashMap::new();
for (tree_name, tree_config) in &config.trees {
println!("Loading identifiers {}", tree_name);
let filename = format!("{}/identifiers", tree_config.paths.index_path);
let map = IdentMap::new(&filename);
result.insert(tree_name.clone(), map);
}
result
}
fn get_line(&self, pos: usize) -> &[u8] {
let mut pos = pos;
let mmap = match self.mmap {
Some(ref m) => m,
None => return &[],
};
let bytes: &[u8] = unsafe { mmap.as_slice() };
if bytes[pos] == '\n' as u8 {
pos -= 1;
}
let mut start = pos;
let mut end = pos;
while start > 0 && bytes[start - 1]!= '\n' as u8 {
start -= 1;
}
let size = mmap.len();
while end < size && bytes[end]!= '\n' as u8 {
end += 1;
}
&bytes[start..end]
}
fn bisect(&self, needle: &[u8], upper_bound: bool) -> usize {
let mut needle = uppercase(needle);
if upper_bound {
needle.push('~' as u8);
}
let mut first = 0;
let mut count = match self.mmap {
Some(ref m) => m.len(),
None => return 0,
};
while count > 0 {
let step = count / 2;
let pos = first + step;
let line = self.get_line(pos);
let line_upper = uppercase(line);
if line_upper < needle || (upper_bound && line_upper == needle) {
first = pos + 1;
count -= step + 1;
} else {
count = step;
}
}
first
}
// NEED A WAY TO LIMIT NUMBER OF RESULTS RETURNED TO 6
// Also need to apply c++filt to the ident as a better human-readable name
pub fn lookup(
&self,
needle: &str,
complete: bool,
fold_case: bool,
max_results: usize,
) -> Vec<IdentResult> { | None => return vec![],
};
let start = self.bisect(needle.as_bytes(), false);
let end = self.bisect(needle.as_bytes(), true);
let mut result = vec![];
let bytes: &[u8] = unsafe { mmap.as_slice() };
let slice = &bytes[start..end];
for line in slice.lines() {
let line = line.unwrap();
let mut pieces = line.split(' ');
let mut id = pieces.next().unwrap().to_string();
let symbol = pieces.next().unwrap();
{
let suffix = &id[needle.len()..];
if suffix.contains(':') || suffix.contains('.') || (complete && suffix.len() > 0) {
continue;
}
}
if!fold_case &&!id.starts_with(needle) {
continue;
}
let demangled = demangle_name(&symbol);
if demangled!= symbol {
id = demangled;
}
result.push(IdentResult {
id: id,
symbol: symbol.to_string(),
});
if result.len() == max_results {
break;
}
}
result
}
pub fn lookup_json(
&self,
needle: &str,
complete: bool,
fold_case: bool,
max_results: usize,
) -> String {
let results = self.lookup(needle, complete, fold_case, max_results);
json::encode(&results).unwrap()
}
} | let mmap = match self.mmap {
Some(ref m) => m, | random_line_split |
identifiers.rs | extern crate memmap;
use self::memmap::{Mmap, Protection};
use std::collections::HashMap;
use std::io::BufRead;
use std::process::Command;
use std::str;
use rustc_serialize::json;
use crate::config;
fn uppercase(s: &[u8]) -> Vec<u8> {
let mut result = vec![];
for i in 0..s.len() {
result.push(if s[i] >= 'a' as u8 && s[i] <= 'z' as u8 {
s[i] - ('a' as u8) + ('A' as u8)
} else {
s[i]
});
}
result
}
pub struct IdentMap {
mmap: Option<Mmap>,
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct IdentResult {
pub id: String,
pub symbol: String,
}
fn demangle_name(name: &str) -> String {
let output = Command::new("c++filt")
.arg("--no-params")
.arg(name)
.output();
match output {
Err(_) => name.to_string(),
Ok(output) => {
if!output.status.success() {
return name.to_string();
}
String::from_utf8(output.stdout)
.unwrap_or(name.to_string())
.trim()
.to_string()
}
}
}
impl IdentMap {
fn new(filename: &str) -> IdentMap {
let mmap = match Mmap::open_path(filename, Protection::Read) {
Ok(mmap) => Some(mmap),
Err(e) => {
warn!("Failed to mmap {}: {:?}", filename, e);
None
}
};
IdentMap { mmap }
}
pub fn load(config: &config::Config) -> HashMap<String, IdentMap> {
let mut result = HashMap::new();
for (tree_name, tree_config) in &config.trees {
println!("Loading identifiers {}", tree_name);
let filename = format!("{}/identifiers", tree_config.paths.index_path);
let map = IdentMap::new(&filename);
result.insert(tree_name.clone(), map);
}
result
}
fn get_line(&self, pos: usize) -> &[u8] {
let mut pos = pos;
let mmap = match self.mmap {
Some(ref m) => m,
None => return &[],
};
let bytes: &[u8] = unsafe { mmap.as_slice() };
if bytes[pos] == '\n' as u8 {
pos -= 1;
}
let mut start = pos;
let mut end = pos;
while start > 0 && bytes[start - 1]!= '\n' as u8 {
start -= 1;
}
let size = mmap.len();
while end < size && bytes[end]!= '\n' as u8 {
end += 1;
}
&bytes[start..end]
}
fn | (&self, needle: &[u8], upper_bound: bool) -> usize {
let mut needle = uppercase(needle);
if upper_bound {
needle.push('~' as u8);
}
let mut first = 0;
let mut count = match self.mmap {
Some(ref m) => m.len(),
None => return 0,
};
while count > 0 {
let step = count / 2;
let pos = first + step;
let line = self.get_line(pos);
let line_upper = uppercase(line);
if line_upper < needle || (upper_bound && line_upper == needle) {
first = pos + 1;
count -= step + 1;
} else {
count = step;
}
}
first
}
// NEED A WAY TO LIMIT NUMBER OF RESULTS RETURNED TO 6
// Also need to apply c++filt to the ident as a better human-readable name
pub fn lookup(
&self,
needle: &str,
complete: bool,
fold_case: bool,
max_results: usize,
) -> Vec<IdentResult> {
let mmap = match self.mmap {
Some(ref m) => m,
None => return vec![],
};
let start = self.bisect(needle.as_bytes(), false);
let end = self.bisect(needle.as_bytes(), true);
let mut result = vec![];
let bytes: &[u8] = unsafe { mmap.as_slice() };
let slice = &bytes[start..end];
for line in slice.lines() {
let line = line.unwrap();
let mut pieces = line.split(' ');
let mut id = pieces.next().unwrap().to_string();
let symbol = pieces.next().unwrap();
{
let suffix = &id[needle.len()..];
if suffix.contains(':') || suffix.contains('.') || (complete && suffix.len() > 0) {
continue;
}
}
if!fold_case &&!id.starts_with(needle) {
continue;
}
let demangled = demangle_name(&symbol);
if demangled!= symbol {
id = demangled;
}
result.push(IdentResult {
id: id,
symbol: symbol.to_string(),
});
if result.len() == max_results {
break;
}
}
result
}
pub fn lookup_json(
&self,
needle: &str,
complete: bool,
fold_case: bool,
max_results: usize,
) -> String {
let results = self.lookup(needle, complete, fold_case, max_results);
json::encode(&results).unwrap()
}
}
| bisect | identifier_name |
identifiers.rs | extern crate memmap;
use self::memmap::{Mmap, Protection};
use std::collections::HashMap;
use std::io::BufRead;
use std::process::Command;
use std::str;
use rustc_serialize::json;
use crate::config;
fn uppercase(s: &[u8]) -> Vec<u8> {
let mut result = vec![];
for i in 0..s.len() {
result.push(if s[i] >= 'a' as u8 && s[i] <= 'z' as u8 {
s[i] - ('a' as u8) + ('A' as u8)
} else {
s[i]
});
}
result
}
pub struct IdentMap {
mmap: Option<Mmap>,
}
#[derive(RustcDecodable, RustcEncodable)]
pub struct IdentResult {
pub id: String,
pub symbol: String,
}
fn demangle_name(name: &str) -> String {
let output = Command::new("c++filt")
.arg("--no-params")
.arg(name)
.output();
match output {
Err(_) => name.to_string(),
Ok(output) => {
if!output.status.success() {
return name.to_string();
}
String::from_utf8(output.stdout)
.unwrap_or(name.to_string())
.trim()
.to_string()
}
}
}
impl IdentMap {
fn new(filename: &str) -> IdentMap {
let mmap = match Mmap::open_path(filename, Protection::Read) {
Ok(mmap) => Some(mmap),
Err(e) => {
warn!("Failed to mmap {}: {:?}", filename, e);
None
}
};
IdentMap { mmap }
}
pub fn load(config: &config::Config) -> HashMap<String, IdentMap> {
let mut result = HashMap::new();
for (tree_name, tree_config) in &config.trees {
println!("Loading identifiers {}", tree_name);
let filename = format!("{}/identifiers", tree_config.paths.index_path);
let map = IdentMap::new(&filename);
result.insert(tree_name.clone(), map);
}
result
}
fn get_line(&self, pos: usize) -> &[u8] {
let mut pos = pos;
let mmap = match self.mmap {
Some(ref m) => m,
None => return &[],
};
let bytes: &[u8] = unsafe { mmap.as_slice() };
if bytes[pos] == '\n' as u8 {
pos -= 1;
}
let mut start = pos;
let mut end = pos;
while start > 0 && bytes[start - 1]!= '\n' as u8 {
start -= 1;
}
let size = mmap.len();
while end < size && bytes[end]!= '\n' as u8 {
end += 1;
}
&bytes[start..end]
}
fn bisect(&self, needle: &[u8], upper_bound: bool) -> usize {
let mut needle = uppercase(needle);
if upper_bound {
needle.push('~' as u8);
}
let mut first = 0;
let mut count = match self.mmap {
Some(ref m) => m.len(),
None => return 0,
};
while count > 0 {
let step = count / 2;
let pos = first + step;
let line = self.get_line(pos);
let line_upper = uppercase(line);
if line_upper < needle || (upper_bound && line_upper == needle) {
first = pos + 1;
count -= step + 1;
} else {
count = step;
}
}
first
}
// NEED A WAY TO LIMIT NUMBER OF RESULTS RETURNED TO 6
// Also need to apply c++filt to the ident as a better human-readable name
pub fn lookup(
&self,
needle: &str,
complete: bool,
fold_case: bool,
max_results: usize,
) -> Vec<IdentResult> | let suffix = &id[needle.len()..];
if suffix.contains(':') || suffix.contains('.') || (complete && suffix.len() > 0) {
continue;
}
}
if!fold_case &&!id.starts_with(needle) {
continue;
}
let demangled = demangle_name(&symbol);
if demangled!= symbol {
id = demangled;
}
result.push(IdentResult {
id: id,
symbol: symbol.to_string(),
});
if result.len() == max_results {
break;
}
}
result
}
pub fn lookup_json(
&self,
needle: &str,
complete: bool,
fold_case: bool,
max_results: usize,
) -> String {
let results = self.lookup(needle, complete, fold_case, max_results);
json::encode(&results).unwrap()
}
}
| {
let mmap = match self.mmap {
Some(ref m) => m,
None => return vec![],
};
let start = self.bisect(needle.as_bytes(), false);
let end = self.bisect(needle.as_bytes(), true);
let mut result = vec![];
let bytes: &[u8] = unsafe { mmap.as_slice() };
let slice = &bytes[start..end];
for line in slice.lines() {
let line = line.unwrap();
let mut pieces = line.split(' ');
let mut id = pieces.next().unwrap().to_string();
let symbol = pieces.next().unwrap();
{ | identifier_body |
image.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! CSS handling for the computed value of
//! [`image`][image]s
//!
//! [image]: https://drafts.csswg.org/css-images/#image-values
use crate::values::computed::position::Position;
use crate::values::computed::url::ComputedImageUrl;
#[cfg(feature = "gecko")]
use crate::values::computed::NumberOrPercentage;
use crate::values::computed::{Angle, Color, Context};
use crate::values::computed::{
LengthPercentage, NonNegativeLength, NonNegativeLengthPercentage, ToComputedValue,
};
use crate::values::generics::image::{self as generic, GradientCompatMode};
use crate::values::specified::image::LineDirection as SpecifiedLineDirection;
use crate::values::specified::position::{HorizontalPositionKeyword, VerticalPositionKeyword};
use std::f32::consts::PI;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
/// A computed image layer.
pub type ImageLayer = generic::GenericImageLayer<Image>;
/// Computed values for an image according to CSS-IMAGES.
/// <https://drafts.csswg.org/css-images/#image-values>
pub type Image = generic::GenericImage<Gradient, MozImageRect, ComputedImageUrl>;
/// Computed values for a CSS gradient.
/// <https://drafts.csswg.org/css-images/#gradients>
pub type Gradient = generic::GenericGradient<
LineDirection,
LengthPercentage,
NonNegativeLength,
NonNegativeLengthPercentage,
Position,
Color,
>;
/// A computed radial gradient ending shape.
pub type EndingShape = generic::GenericEndingShape<NonNegativeLength, NonNegativeLengthPercentage>;
/// A computed gradient line direction.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToResolvedValue)]
#[repr(C, u8)]
pub enum LineDirection {
/// An angle.
Angle(Angle),
/// A horizontal direction.
Horizontal(HorizontalPositionKeyword),
/// A vertical direction.
Vertical(VerticalPositionKeyword),
/// A corner.
Corner(HorizontalPositionKeyword, VerticalPositionKeyword),
}
/// A computed gradient item.
pub type GradientItem = generic::GenericGradientItem<Color, LengthPercentage>;
/// A computed color stop.
pub type ColorStop = generic::ColorStop<Color, LengthPercentage>;
/// Computed values for `-moz-image-rect(...)`.
#[cfg(feature = "gecko")]
pub type MozImageRect = generic::MozImageRect<NumberOrPercentage, ComputedImageUrl>;
/// Empty enum on non-gecko
#[cfg(not(feature = "gecko"))]
pub type MozImageRect = crate::values::specified::image::MozImageRect;
impl generic::LineDirection for LineDirection {
fn points_downwards(&self, compat_mode: GradientCompatMode) -> bool {
match *self {
LineDirection::Angle(angle) => angle.radians() == PI,
LineDirection::Vertical(VerticalPositionKeyword::Bottom) => {
compat_mode == GradientCompatMode::Modern
},
LineDirection::Vertical(VerticalPositionKeyword::Top) => {
compat_mode!= GradientCompatMode::Modern
},
_ => false,
}
}
fn to_css<W>(&self, dest: &mut CssWriter<W>, compat_mode: GradientCompatMode) -> fmt::Result
where
W: Write,
{
match *self {
LineDirection::Angle(ref angle) => angle.to_css(dest),
LineDirection::Horizontal(x) => {
if compat_mode == GradientCompatMode::Modern {
dest.write_str("to ")?;
}
x.to_css(dest)
},
LineDirection::Vertical(y) => {
if compat_mode == GradientCompatMode::Modern {
dest.write_str("to ")?;
}
y.to_css(dest)
},
LineDirection::Corner(x, y) => {
if compat_mode == GradientCompatMode::Modern {
dest.write_str("to ")?;
}
x.to_css(dest)?;
dest.write_str(" ")?;
y.to_css(dest)
},
}
}
}
impl ToComputedValue for SpecifiedLineDirection {
type ComputedValue = LineDirection;
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self {
SpecifiedLineDirection::Angle(ref angle) => {
LineDirection::Angle(angle.to_computed_value(context))
},
SpecifiedLineDirection::Horizontal(x) => LineDirection::Horizontal(x),
SpecifiedLineDirection::Vertical(y) => LineDirection::Vertical(y),
SpecifiedLineDirection::Corner(x, y) => LineDirection::Corner(x, y),
}
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
match *computed {
LineDirection::Angle(ref angle) => {
SpecifiedLineDirection::Angle(ToComputedValue::from_computed_value(angle))
},
LineDirection::Horizontal(x) => SpecifiedLineDirection::Horizontal(x), | LineDirection::Corner(x, y) => SpecifiedLineDirection::Corner(x, y),
}
}
} | LineDirection::Vertical(y) => SpecifiedLineDirection::Vertical(y), | random_line_split |
image.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! CSS handling for the computed value of
//! [`image`][image]s
//!
//! [image]: https://drafts.csswg.org/css-images/#image-values
use crate::values::computed::position::Position;
use crate::values::computed::url::ComputedImageUrl;
#[cfg(feature = "gecko")]
use crate::values::computed::NumberOrPercentage;
use crate::values::computed::{Angle, Color, Context};
use crate::values::computed::{
LengthPercentage, NonNegativeLength, NonNegativeLengthPercentage, ToComputedValue,
};
use crate::values::generics::image::{self as generic, GradientCompatMode};
use crate::values::specified::image::LineDirection as SpecifiedLineDirection;
use crate::values::specified::position::{HorizontalPositionKeyword, VerticalPositionKeyword};
use std::f32::consts::PI;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
/// A computed image layer.
pub type ImageLayer = generic::GenericImageLayer<Image>;
/// Computed values for an image according to CSS-IMAGES.
/// <https://drafts.csswg.org/css-images/#image-values>
pub type Image = generic::GenericImage<Gradient, MozImageRect, ComputedImageUrl>;
/// Computed values for a CSS gradient.
/// <https://drafts.csswg.org/css-images/#gradients>
pub type Gradient = generic::GenericGradient<
LineDirection,
LengthPercentage,
NonNegativeLength,
NonNegativeLengthPercentage,
Position,
Color,
>;
/// A computed radial gradient ending shape.
pub type EndingShape = generic::GenericEndingShape<NonNegativeLength, NonNegativeLengthPercentage>;
/// A computed gradient line direction.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToResolvedValue)]
#[repr(C, u8)]
pub enum LineDirection {
/// An angle.
Angle(Angle),
/// A horizontal direction.
Horizontal(HorizontalPositionKeyword),
/// A vertical direction.
Vertical(VerticalPositionKeyword),
/// A corner.
Corner(HorizontalPositionKeyword, VerticalPositionKeyword),
}
/// A computed gradient item.
pub type GradientItem = generic::GenericGradientItem<Color, LengthPercentage>;
/// A computed color stop.
pub type ColorStop = generic::ColorStop<Color, LengthPercentage>;
/// Computed values for `-moz-image-rect(...)`.
#[cfg(feature = "gecko")]
pub type MozImageRect = generic::MozImageRect<NumberOrPercentage, ComputedImageUrl>;
/// Empty enum on non-gecko
#[cfg(not(feature = "gecko"))]
pub type MozImageRect = crate::values::specified::image::MozImageRect;
impl generic::LineDirection for LineDirection {
fn points_downwards(&self, compat_mode: GradientCompatMode) -> bool {
match *self {
LineDirection::Angle(angle) => angle.radians() == PI,
LineDirection::Vertical(VerticalPositionKeyword::Bottom) => {
compat_mode == GradientCompatMode::Modern
},
LineDirection::Vertical(VerticalPositionKeyword::Top) => {
compat_mode!= GradientCompatMode::Modern
},
_ => false,
}
}
fn | <W>(&self, dest: &mut CssWriter<W>, compat_mode: GradientCompatMode) -> fmt::Result
where
W: Write,
{
match *self {
LineDirection::Angle(ref angle) => angle.to_css(dest),
LineDirection::Horizontal(x) => {
if compat_mode == GradientCompatMode::Modern {
dest.write_str("to ")?;
}
x.to_css(dest)
},
LineDirection::Vertical(y) => {
if compat_mode == GradientCompatMode::Modern {
dest.write_str("to ")?;
}
y.to_css(dest)
},
LineDirection::Corner(x, y) => {
if compat_mode == GradientCompatMode::Modern {
dest.write_str("to ")?;
}
x.to_css(dest)?;
dest.write_str(" ")?;
y.to_css(dest)
},
}
}
}
impl ToComputedValue for SpecifiedLineDirection {
type ComputedValue = LineDirection;
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self {
SpecifiedLineDirection::Angle(ref angle) => {
LineDirection::Angle(angle.to_computed_value(context))
},
SpecifiedLineDirection::Horizontal(x) => LineDirection::Horizontal(x),
SpecifiedLineDirection::Vertical(y) => LineDirection::Vertical(y),
SpecifiedLineDirection::Corner(x, y) => LineDirection::Corner(x, y),
}
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
match *computed {
LineDirection::Angle(ref angle) => {
SpecifiedLineDirection::Angle(ToComputedValue::from_computed_value(angle))
},
LineDirection::Horizontal(x) => SpecifiedLineDirection::Horizontal(x),
LineDirection::Vertical(y) => SpecifiedLineDirection::Vertical(y),
LineDirection::Corner(x, y) => SpecifiedLineDirection::Corner(x, y),
}
}
}
| to_css | identifier_name |
image.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! CSS handling for the computed value of
//! [`image`][image]s
//!
//! [image]: https://drafts.csswg.org/css-images/#image-values
use crate::values::computed::position::Position;
use crate::values::computed::url::ComputedImageUrl;
#[cfg(feature = "gecko")]
use crate::values::computed::NumberOrPercentage;
use crate::values::computed::{Angle, Color, Context};
use crate::values::computed::{
LengthPercentage, NonNegativeLength, NonNegativeLengthPercentage, ToComputedValue,
};
use crate::values::generics::image::{self as generic, GradientCompatMode};
use crate::values::specified::image::LineDirection as SpecifiedLineDirection;
use crate::values::specified::position::{HorizontalPositionKeyword, VerticalPositionKeyword};
use std::f32::consts::PI;
use std::fmt::{self, Write};
use style_traits::{CssWriter, ToCss};
/// A computed image layer.
pub type ImageLayer = generic::GenericImageLayer<Image>;
/// Computed values for an image according to CSS-IMAGES.
/// <https://drafts.csswg.org/css-images/#image-values>
pub type Image = generic::GenericImage<Gradient, MozImageRect, ComputedImageUrl>;
/// Computed values for a CSS gradient.
/// <https://drafts.csswg.org/css-images/#gradients>
pub type Gradient = generic::GenericGradient<
LineDirection,
LengthPercentage,
NonNegativeLength,
NonNegativeLengthPercentage,
Position,
Color,
>;
/// A computed radial gradient ending shape.
pub type EndingShape = generic::GenericEndingShape<NonNegativeLength, NonNegativeLengthPercentage>;
/// A computed gradient line direction.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToResolvedValue)]
#[repr(C, u8)]
pub enum LineDirection {
/// An angle.
Angle(Angle),
/// A horizontal direction.
Horizontal(HorizontalPositionKeyword),
/// A vertical direction.
Vertical(VerticalPositionKeyword),
/// A corner.
Corner(HorizontalPositionKeyword, VerticalPositionKeyword),
}
/// A computed gradient item.
pub type GradientItem = generic::GenericGradientItem<Color, LengthPercentage>;
/// A computed color stop.
pub type ColorStop = generic::ColorStop<Color, LengthPercentage>;
/// Computed values for `-moz-image-rect(...)`.
#[cfg(feature = "gecko")]
pub type MozImageRect = generic::MozImageRect<NumberOrPercentage, ComputedImageUrl>;
/// Empty enum on non-gecko
#[cfg(not(feature = "gecko"))]
pub type MozImageRect = crate::values::specified::image::MozImageRect;
impl generic::LineDirection for LineDirection {
fn points_downwards(&self, compat_mode: GradientCompatMode) -> bool {
match *self {
LineDirection::Angle(angle) => angle.radians() == PI,
LineDirection::Vertical(VerticalPositionKeyword::Bottom) => {
compat_mode == GradientCompatMode::Modern
},
LineDirection::Vertical(VerticalPositionKeyword::Top) => {
compat_mode!= GradientCompatMode::Modern
},
_ => false,
}
}
fn to_css<W>(&self, dest: &mut CssWriter<W>, compat_mode: GradientCompatMode) -> fmt::Result
where
W: Write,
{
match *self {
LineDirection::Angle(ref angle) => angle.to_css(dest),
LineDirection::Horizontal(x) => {
if compat_mode == GradientCompatMode::Modern {
dest.write_str("to ")?;
}
x.to_css(dest)
},
LineDirection::Vertical(y) => {
if compat_mode == GradientCompatMode::Modern {
dest.write_str("to ")?;
}
y.to_css(dest)
},
LineDirection::Corner(x, y) => {
if compat_mode == GradientCompatMode::Modern {
dest.write_str("to ")?;
}
x.to_css(dest)?;
dest.write_str(" ")?;
y.to_css(dest)
},
}
}
}
impl ToComputedValue for SpecifiedLineDirection {
type ComputedValue = LineDirection;
fn to_computed_value(&self, context: &Context) -> Self::ComputedValue {
match *self {
SpecifiedLineDirection::Angle(ref angle) => {
LineDirection::Angle(angle.to_computed_value(context))
},
SpecifiedLineDirection::Horizontal(x) => LineDirection::Horizontal(x),
SpecifiedLineDirection::Vertical(y) => LineDirection::Vertical(y),
SpecifiedLineDirection::Corner(x, y) => LineDirection::Corner(x, y),
}
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self |
}
| {
match *computed {
LineDirection::Angle(ref angle) => {
SpecifiedLineDirection::Angle(ToComputedValue::from_computed_value(angle))
},
LineDirection::Horizontal(x) => SpecifiedLineDirection::Horizontal(x),
LineDirection::Vertical(y) => SpecifiedLineDirection::Vertical(y),
LineDirection::Corner(x, y) => SpecifiedLineDirection::Corner(x, y),
}
} | identifier_body |
arithmetic_infix_ast_span.rs | extern crate peg;
peg::parser!( grammar arithmetic() for str {
rule ident() -> &'input str = $(['a'..='z']+)
pub rule expression() -> Node = precedence!{
start:position!() node:@ end:position!() { Node { start, node, end} }
--
x:(@) "+" y:@ { Op::Add(Box::new(x), Box::new(y)) }
--
x:(@) "*" y:@ { Op::Mul(Box::new(x), Box::new(y)) }
--
i:ident() [' '|'\n']* { Op::Ident(i.to_owned()) }
}
});
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Node {
node: Op,
start: usize,
end: usize,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Op {
Ident(String),
Add(Box<Node>, Box<Node>),
Mul(Box<Node>, Box<Node>),
}
fn main() | Box::new(Node {
start: 4,
end: 5,
node: Op::Ident("c".into())
})
)
})
)
}
);
} | {
assert_eq!(arithmetic::expression("a+b*c").unwrap(),
Node {
start: 0,
end: 5,
node: Op::Add(
Box::new(Node {
start: 0,
end: 1,
node: Op::Ident("a".into())
}),
Box::new(Node {
start: 2,
end: 5,
node: Op::Mul(
Box::new(Node {
start: 2,
end: 3,
node: Op::Ident("b".into())
}), | identifier_body |
arithmetic_infix_ast_span.rs | extern crate peg;
peg::parser!( grammar arithmetic() for str {
rule ident() -> &'input str = $(['a'..='z']+)
pub rule expression() -> Node = precedence!{
start:position!() node:@ end:position!() { Node { start, node, end} }
--
x:(@) "+" y:@ { Op::Add(Box::new(x), Box::new(y)) }
--
x:(@) "*" y:@ { Op::Mul(Box::new(x), Box::new(y)) }
--
i:ident() [' '|'\n']* { Op::Ident(i.to_owned()) }
}
});
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Node {
node: Op,
start: usize,
end: usize,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Op {
Ident(String),
Add(Box<Node>, Box<Node>),
Mul(Box<Node>, Box<Node>),
}
fn main(){
assert_eq!(arithmetic::expression("a+b*c").unwrap(),
Node {
start: 0,
end: 5,
node: Op::Add(
Box::new(Node {
start: 0,
end: 1,
node: Op::Ident("a".into())
}),
Box::new(Node {
start: 2, | Box::new(Node {
start: 2,
end: 3,
node: Op::Ident("b".into())
}),
Box::new(Node {
start: 4,
end: 5,
node: Op::Ident("c".into())
})
)
})
)
}
);
} | end: 5,
node: Op::Mul( | random_line_split |
arithmetic_infix_ast_span.rs | extern crate peg;
peg::parser!( grammar arithmetic() for str {
rule ident() -> &'input str = $(['a'..='z']+)
pub rule expression() -> Node = precedence!{
start:position!() node:@ end:position!() { Node { start, node, end} }
--
x:(@) "+" y:@ { Op::Add(Box::new(x), Box::new(y)) }
--
x:(@) "*" y:@ { Op::Mul(Box::new(x), Box::new(y)) }
--
i:ident() [' '|'\n']* { Op::Ident(i.to_owned()) }
}
});
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Node {
node: Op,
start: usize,
end: usize,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Op {
Ident(String),
Add(Box<Node>, Box<Node>),
Mul(Box<Node>, Box<Node>),
}
fn | (){
assert_eq!(arithmetic::expression("a+b*c").unwrap(),
Node {
start: 0,
end: 5,
node: Op::Add(
Box::new(Node {
start: 0,
end: 1,
node: Op::Ident("a".into())
}),
Box::new(Node {
start: 2,
end: 5,
node: Op::Mul(
Box::new(Node {
start: 2,
end: 3,
node: Op::Ident("b".into())
}),
Box::new(Node {
start: 4,
end: 5,
node: Op::Ident("c".into())
})
)
})
)
}
);
} | main | identifier_name |
derive.rs | use predicates::prelude::*;
use qualia::{object, ConversionError, Object, Result};
use qualia_derive::ObjectShape;
use std::convert::TryFrom;
#[derive(Debug, ObjectShape, PartialEq)]
struct Shape {
name: String,
width: i64,
height: i64,
}
fn result_is_err_matching<T, E: std::error::Error>(r: Result<T, E>, pattern: &str) -> bool {
predicate::str::is_match(pattern)
.unwrap()
.eval(&r.err().unwrap().to_string())
}
#[test]
fn can_convert_from_object() -> Result<(), ConversionError> {
assert_eq!(
Shape::try_from(object!("name" => "letter", "width" => 8, "height" => 11))?,
Shape {
name: "letter".to_string(),
width: 8,
height: 11
}
);
Ok(())
}
#[test]
fn converting_fails_when_fields_missing() -> Result<(), ConversionError> {
assert!(result_is_err_matching(
Shape::try_from(object!("name" => "letter", "height" => 11)),
"width.*missing",
));
Ok(()) | Shape::try_from(object!("name" => 4, "width" => 8, "height" => 11)),
"name.*string",
));
assert!(result_is_err_matching(
Shape::try_from(object!("name" => "letter", "width" => "potato", "height" => 11)),
"width.*number",
));
Ok(())
}
#[test]
fn can_convert_to_object() -> Result<(), ConversionError> {
let obj: Object = Shape {
name: "letter".to_string(),
width: 8,
height: 11,
}
.into();
assert_eq!(
obj,
object!("name" => "letter", "width" => 8, "height" => 11),
);
Ok(())
} | }
#[test]
fn converting_fails_when_fields_wrong_type() -> Result<(), ConversionError> {
assert!(result_is_err_matching( | random_line_split |
derive.rs | use predicates::prelude::*;
use qualia::{object, ConversionError, Object, Result};
use qualia_derive::ObjectShape;
use std::convert::TryFrom;
#[derive(Debug, ObjectShape, PartialEq)]
struct | {
name: String,
width: i64,
height: i64,
}
fn result_is_err_matching<T, E: std::error::Error>(r: Result<T, E>, pattern: &str) -> bool {
predicate::str::is_match(pattern)
.unwrap()
.eval(&r.err().unwrap().to_string())
}
#[test]
fn can_convert_from_object() -> Result<(), ConversionError> {
assert_eq!(
Shape::try_from(object!("name" => "letter", "width" => 8, "height" => 11))?,
Shape {
name: "letter".to_string(),
width: 8,
height: 11
}
);
Ok(())
}
#[test]
fn converting_fails_when_fields_missing() -> Result<(), ConversionError> {
assert!(result_is_err_matching(
Shape::try_from(object!("name" => "letter", "height" => 11)),
"width.*missing",
));
Ok(())
}
#[test]
fn converting_fails_when_fields_wrong_type() -> Result<(), ConversionError> {
assert!(result_is_err_matching(
Shape::try_from(object!("name" => 4, "width" => 8, "height" => 11)),
"name.*string",
));
assert!(result_is_err_matching(
Shape::try_from(object!("name" => "letter", "width" => "potato", "height" => 11)),
"width.*number",
));
Ok(())
}
#[test]
fn can_convert_to_object() -> Result<(), ConversionError> {
let obj: Object = Shape {
name: "letter".to_string(),
width: 8,
height: 11,
}
.into();
assert_eq!(
obj,
object!("name" => "letter", "width" => 8, "height" => 11),
);
Ok(())
}
| Shape | identifier_name |
derive.rs | use predicates::prelude::*;
use qualia::{object, ConversionError, Object, Result};
use qualia_derive::ObjectShape;
use std::convert::TryFrom;
#[derive(Debug, ObjectShape, PartialEq)]
struct Shape {
name: String,
width: i64,
height: i64,
}
fn result_is_err_matching<T, E: std::error::Error>(r: Result<T, E>, pattern: &str) -> bool |
#[test]
fn can_convert_from_object() -> Result<(), ConversionError> {
assert_eq!(
Shape::try_from(object!("name" => "letter", "width" => 8, "height" => 11))?,
Shape {
name: "letter".to_string(),
width: 8,
height: 11
}
);
Ok(())
}
#[test]
fn converting_fails_when_fields_missing() -> Result<(), ConversionError> {
assert!(result_is_err_matching(
Shape::try_from(object!("name" => "letter", "height" => 11)),
"width.*missing",
));
Ok(())
}
#[test]
fn converting_fails_when_fields_wrong_type() -> Result<(), ConversionError> {
assert!(result_is_err_matching(
Shape::try_from(object!("name" => 4, "width" => 8, "height" => 11)),
"name.*string",
));
assert!(result_is_err_matching(
Shape::try_from(object!("name" => "letter", "width" => "potato", "height" => 11)),
"width.*number",
));
Ok(())
}
#[test]
fn can_convert_to_object() -> Result<(), ConversionError> {
let obj: Object = Shape {
name: "letter".to_string(),
width: 8,
height: 11,
}
.into();
assert_eq!(
obj,
object!("name" => "letter", "width" => 8, "height" => 11),
);
Ok(())
}
| {
predicate::str::is_match(pattern)
.unwrap()
.eval(&r.err().unwrap().to_string())
} | identifier_body |
lib.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Interface to random number generators in Rust.
//!
//! This is an experimental library which lives underneath the standard library
//! in its dependency chain. This library is intended to define the interface
//! for random number generation and also provide utilities around doing so. It
//! is not recommended to use this library directly, but rather the official
//! interface through `std::rand`.
#![crate_name = "rand"]
#![license = "MIT/ASL2"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")]
#![feature(macro_rules, phase, globs)]
#![no_std]
#![experimental]
#[phase(plugin, link)]
extern crate core;
#[cfg(test)] #[phase(plugin, link)] extern crate std;
#[cfg(test)] #[phase(plugin, link)] extern crate log;
#[cfg(test)] extern crate native;
#[cfg(test)] extern crate debug;
use core::prelude::*;
pub use isaac::{IsaacRng, Isaac64Rng};
use distributions::{Range, IndependentSample};
use distributions::range::SampleRange;
#[cfg(test)]
static RAND_BENCH_N: u64 = 100;
pub mod distributions;
pub mod isaac;
pub mod reseeding;
mod rand_impls;
/// A type that can be randomly generated using an `Rng`.
pub trait Rand {
/// Generates a random instance of this type using the specified source of
/// randomness.
fn rand<R: Rng>(rng: &mut R) -> Self;
}
/// A random number generator.
pub trait Rng {
/// Return the next random u32.
///
/// This rarely needs to be called directly, prefer `r.gen()` to
/// `r.next_u32()`.
// FIXME #7771: Should be implemented in terms of next_u64
fn next_u32(&mut self) -> u32;
/// Return the next random u64.
///
/// By default this is implemented in terms of `next_u32`. An
/// implementation of this trait must provide at least one of
/// these two methods. Similarly to `next_u32`, this rarely needs
/// to be called directly, prefer `r.gen()` to `r.next_u64()`.
fn next_u64(&mut self) -> u64 {
(self.next_u32() as u64 << 32) | (self.next_u32() as u64)
}
/// Fill `dest` with random data.
///
/// This has a default implementation in terms of `next_u64` and
/// `next_u32`, but should be overridden by implementations that
/// offer a more efficient solution than just calling those
/// methods repeatedly.
///
/// This method does *not* have a requirement to bear any fixed
/// relationship to the other methods, for example, it does *not*
/// have to result in the same output as progressively filling
/// `dest` with `self.gen::<u8>()`, and any such behaviour should
/// not be relied upon.
///
/// This method should guarantee that `dest` is entirely filled
/// with new data, and may fail if this is impossible
/// (e.g. reading past the end of a file that is being used as the
/// source of randomness).
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut v = [0u8,.. 13579];
/// task_rng().fill_bytes(v);
/// println!("{}", v.as_slice());
/// ```
fn fill_bytes(&mut self, dest: &mut [u8]) {
// this could, in theory, be done by transmuting dest to a
// [u64], but this is (1) likely to be undefined behaviour for
// LLVM, (2) has to be very careful about alignment concerns,
// (3) adds more `unsafe` that needs to be checked, (4)
// probably doesn't give much performance gain if
// optimisations are on.
let mut count = 0i;
let mut num = 0;
for byte in dest.mut_iter() {
if count == 0 {
// we could micro-optimise here by generating a u32 if
// we only need a few more bytes to fill the vector
// (i.e. at most 4).
num = self.next_u64();
count = 8;
}
*byte = (num & 0xff) as u8;
num >>= 8;
count -= 1;
}
}
/// Return a random value of a `Rand` type.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let x: uint = rng.gen();
/// println!("{}", x);
/// println!("{}", rng.gen::<(f64, bool)>());
/// ```
#[inline(always)]
fn gen<T: Rand>(&mut self) -> T {
Rand::rand(self)
}
/// Return an iterator which will yield an infinite number of randomly
/// generated items.
///
/// # Example
///
/// ```
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
/// println!("{}", x);
/// println!("{}", rng.gen_iter::<(f64, bool)>().take(5)
/// .collect::<Vec<(f64, bool)>>());
/// ```
fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
Generator { rng: self }
}
/// Generate a random value in the range [`low`, `high`). Fails if
/// `low >= high`.
///
/// This is a convenience wrapper around
/// `distributions::Range`. If this function will be called
/// repeatedly with the same arguments, one should use `Range`, as
/// that will amortize the computations that allow for perfect
/// uniformity, as they only happen on initialization.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let n: uint = rng.gen_range(0u, 10);
/// println!("{}", n);
/// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
/// println!("{}", m);
/// ```
fn | <T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
assert!(low < high, "Rng.gen_range called with low >= high");
Range::new(low, high).ind_sample(self)
}
/// Return a bool with a 1 in n chance of true
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// println!("{:b}", rng.gen_weighted_bool(3));
/// ```
fn gen_weighted_bool(&mut self, n: uint) -> bool {
n == 0 || self.gen_range(0, n) == 0
}
/// Return an iterator of random characters from the set A-Z,a-z,0-9.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let s: String = task_rng().gen_ascii_chars().take(10).collect();
/// println!("{}", s);
/// ```
fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
AsciiGenerator { rng: self }
}
/// Return a random element from `values`.
///
/// Return `None` if `values` is empty.
///
/// # Example
///
/// ```
/// use std::rand::{task_rng, Rng};
///
/// let choices = [1i, 2, 4, 8, 16, 32];
/// let mut rng = task_rng();
/// println!("{}", rng.choose(choices));
/// assert_eq!(rng.choose(choices.slice_to(0)), None);
/// ```
fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() {
None
} else {
Some(&values[self.gen_range(0u, values.len())])
}
}
/// Deprecated name for `choose()`.
#[deprecated = "replaced by.choose()"]
fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
self.choose(values)
}
/// Shuffle a mutable slice in place.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let mut y = [1i, 2, 3];
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// ```
fn shuffle<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
while i >= 2u {
// invariant: elements with index >= i have been locked in place.
i -= 1u;
// lock element i in place.
values.swap(i, self.gen_range(0u, i + 1u));
}
}
}
/// Iterator which will generate a stream of random items.
///
/// This iterator is created via the `gen_iter` method on `Rng`.
pub struct Generator<'a, T, R:'a> {
rng: &'a mut R,
}
impl<'a, T: Rand, R: Rng> Iterator<T> for Generator<'a, T, R> {
fn next(&mut self) -> Option<T> {
Some(self.rng.gen())
}
}
/// Iterator which will continuously generate random ascii characters.
///
/// This iterator is created via the `gen_ascii_chars` method on `Rng`.
pub struct AsciiGenerator<'a, R:'a> {
rng: &'a mut R,
}
impl<'a, R: Rng> Iterator<char> for AsciiGenerator<'a, R> {
fn next(&mut self) -> Option<char> {
static GEN_ASCII_STR_CHARSET: &'static [u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789";
Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
}
}
/// A random number generator that can be explicitly seeded to produce
/// the same stream of randomness multiple times.
pub trait SeedableRng<Seed>: Rng {
/// Reseed an RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// let seed: &[_] = &[1, 2, 3, 4];
/// let mut rng: StdRng = SeedableRng::from_seed(seed);
/// println!("{}", rng.gen::<f64>());
/// rng.reseed([5, 6, 7, 8]);
/// println!("{}", rng.gen::<f64>());
/// ```
fn reseed(&mut self, Seed);
/// Create a new RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// let seed: &[_] = &[1, 2, 3, 4];
/// let mut rng: StdRng = SeedableRng::from_seed(seed);
/// println!("{}", rng.gen::<f64>());
/// ```
fn from_seed(seed: Seed) -> Self;
}
/// An Xorshift[1] random number
/// generator.
///
/// The Xorshift algorithm is not suitable for cryptographic purposes
/// but is very fast. If you do not know for sure that it fits your
/// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
///
/// [1]: Marsaglia, George (July 2003). ["Xorshift
/// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
/// Statistical Software*. Vol. 8 (Issue 14).
pub struct XorShiftRng {
x: u32,
y: u32,
z: u32,
w: u32,
}
impl XorShiftRng {
/// Creates a new XorShiftRng instance which is not seeded.
///
/// The initial values of this RNG are constants, so all generators created
/// by this function will yield the same stream of random numbers. It is
/// highly recommended that this is created through `SeedableRng` instead of
/// this function
pub fn new_unseeded() -> XorShiftRng {
XorShiftRng {
x: 0x193a6754,
y: 0xa8a7d469,
z: 0x97830e05,
w: 0x113ba7bb,
}
}
}
impl Rng for XorShiftRng {
#[inline]
fn next_u32(&mut self) -> u32 {
let x = self.x;
let t = x ^ (x << 11);
self.x = self.y;
self.y = self.z;
self.z = self.w;
let w = self.w;
self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
self.w
}
}
impl SeedableRng<[u32,.. 4]> for XorShiftRng {
/// Reseed an XorShiftRng. This will fail if `seed` is entirely 0.
fn reseed(&mut self, seed: [u32,.. 4]) {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng.reseed called with an all zero seed.");
self.x = seed[0];
self.y = seed[1];
self.z = seed[2];
self.w = seed[3];
}
/// Create a new XorShiftRng. This will fail if `seed` is entirely 0.
fn from_seed(seed: [u32,.. 4]) -> XorShiftRng {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng::from_seed called with an all zero seed.");
XorShiftRng {
x: seed[0],
y: seed[1],
z: seed[2],
w: seed[3]
}
}
}
impl Rand for XorShiftRng {
fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
let mut tuple: (u32, u32, u32, u32) = rng.gen();
while tuple == (0, 0, 0, 0) {
tuple = rng.gen();
}
let (x, y, z, w) = tuple;
XorShiftRng { x: x, y: y, z: z, w: w }
}
}
/// A wrapper for generating floating point numbers uniformly in the
/// open interval `(0,1)` (not including either endpoint).
///
/// Use `Closed01` for the closed interval `[0,1]`, and the default
/// `Rand` implementation for `f32` and `f64` for the half-open
/// `[0,1)`.
///
/// # Example
/// ```rust
/// use std::rand::{random, Open01};
///
/// let Open01(val) = random::<Open01<f32>>();
/// println!("f32 from (0,1): {}", val);
/// ```
pub struct Open01<F>(pub F);
/// A wrapper for generating floating point numbers uniformly in the
/// closed interval `[0,1]` (including both endpoints).
///
/// Use `Open01` for the closed interval `(0,1)`, and the default
/// `Rand` implementation of `f32` and `f64` for the half-open
/// `[0,1)`.
///
/// # Example
///
/// ```rust
/// use std::rand::{random, Closed01};
///
/// let Closed01(val) = random::<Closed01<f32>>();
/// println!("f32 from [0,1]: {}", val);
/// ```
pub struct Closed01<F>(pub F);
#[cfg(not(test))]
mod std {
pub use core::{option, fmt}; // fail!()
}
#[cfg(test)]
mod test {
use std::rand;
pub struct MyRng<R> { inner: R }
impl<R: rand::Rng> ::Rng for MyRng<R> {
fn next_u32(&mut self) -> u32 {
fn next<T: rand::Rng>(t: &mut T) -> u32 {
use std::rand::Rng;
t.next_u32()
}
next(&mut self.inner)
}
}
pub fn rng() -> MyRng<rand::TaskRng> {
MyRng { inner: rand::task_rng() }
}
pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
MyRng { inner: rand::weak_rng() }
}
}
| gen_range | identifier_name |
lib.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Interface to random number generators in Rust.
//!
//! This is an experimental library which lives underneath the standard library
//! in its dependency chain. This library is intended to define the interface
//! for random number generation and also provide utilities around doing so. It
//! is not recommended to use this library directly, but rather the official
//! interface through `std::rand`.
#![crate_name = "rand"]
#![license = "MIT/ASL2"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")]
#![feature(macro_rules, phase, globs)]
#![no_std]
#![experimental]
#[phase(plugin, link)]
extern crate core;
#[cfg(test)] #[phase(plugin, link)] extern crate std;
#[cfg(test)] #[phase(plugin, link)] extern crate log;
#[cfg(test)] extern crate native;
#[cfg(test)] extern crate debug;
use core::prelude::*;
pub use isaac::{IsaacRng, Isaac64Rng};
use distributions::{Range, IndependentSample};
use distributions::range::SampleRange;
#[cfg(test)]
static RAND_BENCH_N: u64 = 100;
pub mod distributions;
pub mod isaac;
pub mod reseeding;
mod rand_impls;
/// A type that can be randomly generated using an `Rng`.
pub trait Rand {
/// Generates a random instance of this type using the specified source of
/// randomness.
fn rand<R: Rng>(rng: &mut R) -> Self;
}
/// A random number generator.
pub trait Rng {
/// Return the next random u32.
///
/// This rarely needs to be called directly, prefer `r.gen()` to
/// `r.next_u32()`.
// FIXME #7771: Should be implemented in terms of next_u64
fn next_u32(&mut self) -> u32;
/// Return the next random u64.
///
/// By default this is implemented in terms of `next_u32`. An
/// implementation of this trait must provide at least one of
/// these two methods. Similarly to `next_u32`, this rarely needs
/// to be called directly, prefer `r.gen()` to `r.next_u64()`.
fn next_u64(&mut self) -> u64 {
(self.next_u32() as u64 << 32) | (self.next_u32() as u64)
}
/// Fill `dest` with random data.
///
/// This has a default implementation in terms of `next_u64` and
/// `next_u32`, but should be overridden by implementations that
/// offer a more efficient solution than just calling those
/// methods repeatedly.
///
/// This method does *not* have a requirement to bear any fixed
/// relationship to the other methods, for example, it does *not*
/// have to result in the same output as progressively filling
/// `dest` with `self.gen::<u8>()`, and any such behaviour should
/// not be relied upon.
///
/// This method should guarantee that `dest` is entirely filled
/// with new data, and may fail if this is impossible
/// (e.g. reading past the end of a file that is being used as the
/// source of randomness).
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut v = [0u8,.. 13579];
/// task_rng().fill_bytes(v);
/// println!("{}", v.as_slice());
/// ```
fn fill_bytes(&mut self, dest: &mut [u8]) {
// this could, in theory, be done by transmuting dest to a
// [u64], but this is (1) likely to be undefined behaviour for
// LLVM, (2) has to be very careful about alignment concerns,
// (3) adds more `unsafe` that needs to be checked, (4)
// probably doesn't give much performance gain if
// optimisations are on.
let mut count = 0i;
let mut num = 0;
for byte in dest.mut_iter() {
if count == 0 {
// we could micro-optimise here by generating a u32 if
// we only need a few more bytes to fill the vector
// (i.e. at most 4).
num = self.next_u64();
count = 8;
}
*byte = (num & 0xff) as u8;
num >>= 8;
count -= 1;
}
}
/// Return a random value of a `Rand` type.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let x: uint = rng.gen();
/// println!("{}", x);
/// println!("{}", rng.gen::<(f64, bool)>());
/// ```
#[inline(always)]
fn gen<T: Rand>(&mut self) -> T {
Rand::rand(self)
}
/// Return an iterator which will yield an infinite number of randomly
/// generated items.
///
/// # Example
///
/// ```
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
/// println!("{}", x);
/// println!("{}", rng.gen_iter::<(f64, bool)>().take(5)
/// .collect::<Vec<(f64, bool)>>());
/// ```
fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
Generator { rng: self }
}
/// Generate a random value in the range [`low`, `high`). Fails if
/// `low >= high`.
///
/// This is a convenience wrapper around
/// `distributions::Range`. If this function will be called
/// repeatedly with the same arguments, one should use `Range`, as
/// that will amortize the computations that allow for perfect
/// uniformity, as they only happen on initialization.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let n: uint = rng.gen_range(0u, 10);
/// println!("{}", n);
/// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
/// println!("{}", m);
/// ```
fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
assert!(low < high, "Rng.gen_range called with low >= high");
Range::new(low, high).ind_sample(self)
}
/// Return a bool with a 1 in n chance of true
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// println!("{:b}", rng.gen_weighted_bool(3));
/// ```
fn gen_weighted_bool(&mut self, n: uint) -> bool {
n == 0 || self.gen_range(0, n) == 0
}
/// Return an iterator of random characters from the set A-Z,a-z,0-9.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let s: String = task_rng().gen_ascii_chars().take(10).collect();
/// println!("{}", s);
/// ```
fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
AsciiGenerator { rng: self }
}
/// Return a random element from `values`.
///
/// Return `None` if `values` is empty.
///
/// # Example
///
/// ```
/// use std::rand::{task_rng, Rng};
///
/// let choices = [1i, 2, 4, 8, 16, 32];
/// let mut rng = task_rng();
/// println!("{}", rng.choose(choices));
/// assert_eq!(rng.choose(choices.slice_to(0)), None);
/// ```
fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> |
/// Deprecated name for `choose()`.
#[deprecated = "replaced by.choose()"]
fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
self.choose(values)
}
/// Shuffle a mutable slice in place.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let mut y = [1i, 2, 3];
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// ```
fn shuffle<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
while i >= 2u {
// invariant: elements with index >= i have been locked in place.
i -= 1u;
// lock element i in place.
values.swap(i, self.gen_range(0u, i + 1u));
}
}
}
/// Iterator which will generate a stream of random items.
///
/// This iterator is created via the `gen_iter` method on `Rng`.
pub struct Generator<'a, T, R:'a> {
rng: &'a mut R,
}
impl<'a, T: Rand, R: Rng> Iterator<T> for Generator<'a, T, R> {
fn next(&mut self) -> Option<T> {
Some(self.rng.gen())
}
}
/// Iterator which will continuously generate random ascii characters.
///
/// This iterator is created via the `gen_ascii_chars` method on `Rng`.
pub struct AsciiGenerator<'a, R:'a> {
rng: &'a mut R,
}
impl<'a, R: Rng> Iterator<char> for AsciiGenerator<'a, R> {
fn next(&mut self) -> Option<char> {
static GEN_ASCII_STR_CHARSET: &'static [u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789";
Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
}
}
/// A random number generator that can be explicitly seeded to produce
/// the same stream of randomness multiple times.
pub trait SeedableRng<Seed>: Rng {
/// Reseed an RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// let seed: &[_] = &[1, 2, 3, 4];
/// let mut rng: StdRng = SeedableRng::from_seed(seed);
/// println!("{}", rng.gen::<f64>());
/// rng.reseed([5, 6, 7, 8]);
/// println!("{}", rng.gen::<f64>());
/// ```
fn reseed(&mut self, Seed);
/// Create a new RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// let seed: &[_] = &[1, 2, 3, 4];
/// let mut rng: StdRng = SeedableRng::from_seed(seed);
/// println!("{}", rng.gen::<f64>());
/// ```
fn from_seed(seed: Seed) -> Self;
}
/// An Xorshift[1] random number
/// generator.
///
/// The Xorshift algorithm is not suitable for cryptographic purposes
/// but is very fast. If you do not know for sure that it fits your
/// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
///
/// [1]: Marsaglia, George (July 2003). ["Xorshift
/// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
/// Statistical Software*. Vol. 8 (Issue 14).
pub struct XorShiftRng {
x: u32,
y: u32,
z: u32,
w: u32,
}
impl XorShiftRng {
/// Creates a new XorShiftRng instance which is not seeded.
///
/// The initial values of this RNG are constants, so all generators created
/// by this function will yield the same stream of random numbers. It is
/// highly recommended that this is created through `SeedableRng` instead of
/// this function
pub fn new_unseeded() -> XorShiftRng {
XorShiftRng {
x: 0x193a6754,
y: 0xa8a7d469,
z: 0x97830e05,
w: 0x113ba7bb,
}
}
}
impl Rng for XorShiftRng {
#[inline]
fn next_u32(&mut self) -> u32 {
let x = self.x;
let t = x ^ (x << 11);
self.x = self.y;
self.y = self.z;
self.z = self.w;
let w = self.w;
self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
self.w
}
}
impl SeedableRng<[u32,.. 4]> for XorShiftRng {
/// Reseed an XorShiftRng. This will fail if `seed` is entirely 0.
fn reseed(&mut self, seed: [u32,.. 4]) {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng.reseed called with an all zero seed.");
self.x = seed[0];
self.y = seed[1];
self.z = seed[2];
self.w = seed[3];
}
/// Create a new XorShiftRng. This will fail if `seed` is entirely 0.
fn from_seed(seed: [u32,.. 4]) -> XorShiftRng {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng::from_seed called with an all zero seed.");
XorShiftRng {
x: seed[0],
y: seed[1],
z: seed[2],
w: seed[3]
}
}
}
impl Rand for XorShiftRng {
fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
let mut tuple: (u32, u32, u32, u32) = rng.gen();
while tuple == (0, 0, 0, 0) {
tuple = rng.gen();
}
let (x, y, z, w) = tuple;
XorShiftRng { x: x, y: y, z: z, w: w }
}
}
/// A wrapper for generating floating point numbers uniformly in the
/// open interval `(0,1)` (not including either endpoint).
///
/// Use `Closed01` for the closed interval `[0,1]`, and the default
/// `Rand` implementation for `f32` and `f64` for the half-open
/// `[0,1)`.
///
/// # Example
/// ```rust
/// use std::rand::{random, Open01};
///
/// let Open01(val) = random::<Open01<f32>>();
/// println!("f32 from (0,1): {}", val);
/// ```
pub struct Open01<F>(pub F);
/// A wrapper for generating floating point numbers uniformly in the
/// closed interval `[0,1]` (including both endpoints).
///
/// Use `Open01` for the closed interval `(0,1)`, and the default
/// `Rand` implementation of `f32` and `f64` for the half-open
/// `[0,1)`.
///
/// # Example
///
/// ```rust
/// use std::rand::{random, Closed01};
///
/// let Closed01(val) = random::<Closed01<f32>>();
/// println!("f32 from [0,1]: {}", val);
/// ```
pub struct Closed01<F>(pub F);
#[cfg(not(test))]
mod std {
pub use core::{option, fmt}; // fail!()
}
#[cfg(test)]
mod test {
use std::rand;
pub struct MyRng<R> { inner: R }
impl<R: rand::Rng> ::Rng for MyRng<R> {
fn next_u32(&mut self) -> u32 {
fn next<T: rand::Rng>(t: &mut T) -> u32 {
use std::rand::Rng;
t.next_u32()
}
next(&mut self.inner)
}
}
pub fn rng() -> MyRng<rand::TaskRng> {
MyRng { inner: rand::task_rng() }
}
pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
MyRng { inner: rand::weak_rng() }
}
}
| {
if values.is_empty() {
None
} else {
Some(&values[self.gen_range(0u, values.len())])
}
} | identifier_body |
lib.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Interface to random number generators in Rust.
//!
//! This is an experimental library which lives underneath the standard library
//! in its dependency chain. This library is intended to define the interface
//! for random number generation and also provide utilities around doing so. It
//! is not recommended to use this library directly, but rather the official
//! interface through `std::rand`.
#![crate_name = "rand"]
#![license = "MIT/ASL2"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")]
#![feature(macro_rules, phase, globs)]
#![no_std]
#![experimental]
#[phase(plugin, link)]
extern crate core;
#[cfg(test)] #[phase(plugin, link)] extern crate std;
#[cfg(test)] #[phase(plugin, link)] extern crate log;
#[cfg(test)] extern crate native;
#[cfg(test)] extern crate debug;
use core::prelude::*;
pub use isaac::{IsaacRng, Isaac64Rng};
use distributions::{Range, IndependentSample};
use distributions::range::SampleRange;
#[cfg(test)]
static RAND_BENCH_N: u64 = 100;
pub mod distributions;
pub mod isaac;
pub mod reseeding;
mod rand_impls;
/// A type that can be randomly generated using an `Rng`.
pub trait Rand {
/// Generates a random instance of this type using the specified source of
/// randomness.
fn rand<R: Rng>(rng: &mut R) -> Self;
}
/// A random number generator.
pub trait Rng {
/// Return the next random u32.
///
/// This rarely needs to be called directly, prefer `r.gen()` to
/// `r.next_u32()`.
// FIXME #7771: Should be implemented in terms of next_u64
fn next_u32(&mut self) -> u32;
/// Return the next random u64.
///
/// By default this is implemented in terms of `next_u32`. An
/// implementation of this trait must provide at least one of
/// these two methods. Similarly to `next_u32`, this rarely needs
/// to be called directly, prefer `r.gen()` to `r.next_u64()`.
fn next_u64(&mut self) -> u64 {
(self.next_u32() as u64 << 32) | (self.next_u32() as u64)
}
/// Fill `dest` with random data.
///
/// This has a default implementation in terms of `next_u64` and
/// `next_u32`, but should be overridden by implementations that
/// offer a more efficient solution than just calling those
/// methods repeatedly.
///
/// This method does *not* have a requirement to bear any fixed
/// relationship to the other methods, for example, it does *not*
/// have to result in the same output as progressively filling
/// `dest` with `self.gen::<u8>()`, and any such behaviour should
/// not be relied upon.
///
/// This method should guarantee that `dest` is entirely filled
/// with new data, and may fail if this is impossible
/// (e.g. reading past the end of a file that is being used as the
/// source of randomness).
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut v = [0u8,.. 13579];
/// task_rng().fill_bytes(v);
/// println!("{}", v.as_slice());
/// ```
fn fill_bytes(&mut self, dest: &mut [u8]) {
// this could, in theory, be done by transmuting dest to a
// [u64], but this is (1) likely to be undefined behaviour for
// LLVM, (2) has to be very careful about alignment concerns,
// (3) adds more `unsafe` that needs to be checked, (4)
// probably doesn't give much performance gain if
// optimisations are on.
let mut count = 0i;
let mut num = 0;
for byte in dest.mut_iter() {
if count == 0 {
// we could micro-optimise here by generating a u32 if
// we only need a few more bytes to fill the vector
// (i.e. at most 4).
num = self.next_u64();
count = 8;
}
*byte = (num & 0xff) as u8;
num >>= 8;
count -= 1;
}
}
/// Return a random value of a `Rand` type.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let x: uint = rng.gen();
/// println!("{}", x);
/// println!("{}", rng.gen::<(f64, bool)>());
/// ```
#[inline(always)]
fn gen<T: Rand>(&mut self) -> T {
Rand::rand(self)
}
/// Return an iterator which will yield an infinite number of randomly
/// generated items.
///
/// # Example
///
/// ```
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
/// println!("{}", x);
/// println!("{}", rng.gen_iter::<(f64, bool)>().take(5)
/// .collect::<Vec<(f64, bool)>>());
/// ```
fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
Generator { rng: self }
}
/// Generate a random value in the range [`low`, `high`). Fails if
/// `low >= high`.
///
/// This is a convenience wrapper around
/// `distributions::Range`. If this function will be called
/// repeatedly with the same arguments, one should use `Range`, as
/// that will amortize the computations that allow for perfect
/// uniformity, as they only happen on initialization.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let n: uint = rng.gen_range(0u, 10);
/// println!("{}", n);
/// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
/// println!("{}", m);
/// ```
fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
assert!(low < high, "Rng.gen_range called with low >= high");
Range::new(low, high).ind_sample(self)
}
/// Return a bool with a 1 in n chance of true
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// println!("{:b}", rng.gen_weighted_bool(3));
/// ```
fn gen_weighted_bool(&mut self, n: uint) -> bool {
n == 0 || self.gen_range(0, n) == 0
}
/// Return an iterator of random characters from the set A-Z,a-z,0-9.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let s: String = task_rng().gen_ascii_chars().take(10).collect();
/// println!("{}", s);
/// ```
fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
AsciiGenerator { rng: self }
}
/// Return a random element from `values`.
///
/// Return `None` if `values` is empty.
///
/// # Example
///
/// ```
/// use std::rand::{task_rng, Rng};
///
/// let choices = [1i, 2, 4, 8, 16, 32];
/// let mut rng = task_rng();
/// println!("{}", rng.choose(choices));
/// assert_eq!(rng.choose(choices.slice_to(0)), None);
/// ```
fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() {
None
} else {
Some(&values[self.gen_range(0u, values.len())])
}
}
/// Deprecated name for `choose()`.
#[deprecated = "replaced by.choose()"]
fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
self.choose(values)
}
/// Shuffle a mutable slice in place.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let mut y = [1i, 2, 3];
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// ```
fn shuffle<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
while i >= 2u {
// invariant: elements with index >= i have been locked in place.
i -= 1u;
// lock element i in place.
values.swap(i, self.gen_range(0u, i + 1u));
}
}
}
/// Iterator which will generate a stream of random items.
///
/// This iterator is created via the `gen_iter` method on `Rng`.
pub struct Generator<'a, T, R:'a> {
rng: &'a mut R,
}
impl<'a, T: Rand, R: Rng> Iterator<T> for Generator<'a, T, R> {
fn next(&mut self) -> Option<T> {
Some(self.rng.gen())
}
}
/// Iterator which will continuously generate random ascii characters.
///
/// This iterator is created via the `gen_ascii_chars` method on `Rng`.
pub struct AsciiGenerator<'a, R:'a> {
rng: &'a mut R,
}
impl<'a, R: Rng> Iterator<char> for AsciiGenerator<'a, R> {
fn next(&mut self) -> Option<char> {
static GEN_ASCII_STR_CHARSET: &'static [u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789";
Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
}
}
/// A random number generator that can be explicitly seeded to produce
/// the same stream of randomness multiple times.
pub trait SeedableRng<Seed>: Rng {
/// Reseed an RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// let seed: &[_] = &[1, 2, 3, 4];
/// let mut rng: StdRng = SeedableRng::from_seed(seed);
/// println!("{}", rng.gen::<f64>());
/// rng.reseed([5, 6, 7, 8]);
/// println!("{}", rng.gen::<f64>());
/// ```
fn reseed(&mut self, Seed);
/// Create a new RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// let seed: &[_] = &[1, 2, 3, 4];
/// let mut rng: StdRng = SeedableRng::from_seed(seed);
/// println!("{}", rng.gen::<f64>());
/// ```
fn from_seed(seed: Seed) -> Self;
}
/// An Xorshift[1] random number
/// generator.
///
/// The Xorshift algorithm is not suitable for cryptographic purposes
/// but is very fast. If you do not know for sure that it fits your
/// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
///
/// [1]: Marsaglia, George (July 2003). ["Xorshift
/// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
/// Statistical Software*. Vol. 8 (Issue 14).
pub struct XorShiftRng {
x: u32,
y: u32,
z: u32,
w: u32,
}
impl XorShiftRng {
/// Creates a new XorShiftRng instance which is not seeded.
///
/// The initial values of this RNG are constants, so all generators created
/// by this function will yield the same stream of random numbers. It is
/// highly recommended that this is created through `SeedableRng` instead of
/// this function
pub fn new_unseeded() -> XorShiftRng {
XorShiftRng {
x: 0x193a6754,
y: 0xa8a7d469,
z: 0x97830e05,
w: 0x113ba7bb,
}
}
}
impl Rng for XorShiftRng { | let t = x ^ (x << 11);
self.x = self.y;
self.y = self.z;
self.z = self.w;
let w = self.w;
self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
self.w
}
}
impl SeedableRng<[u32,.. 4]> for XorShiftRng {
/// Reseed an XorShiftRng. This will fail if `seed` is entirely 0.
fn reseed(&mut self, seed: [u32,.. 4]) {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng.reseed called with an all zero seed.");
self.x = seed[0];
self.y = seed[1];
self.z = seed[2];
self.w = seed[3];
}
/// Create a new XorShiftRng. This will fail if `seed` is entirely 0.
fn from_seed(seed: [u32,.. 4]) -> XorShiftRng {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng::from_seed called with an all zero seed.");
XorShiftRng {
x: seed[0],
y: seed[1],
z: seed[2],
w: seed[3]
}
}
}
impl Rand for XorShiftRng {
fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
let mut tuple: (u32, u32, u32, u32) = rng.gen();
while tuple == (0, 0, 0, 0) {
tuple = rng.gen();
}
let (x, y, z, w) = tuple;
XorShiftRng { x: x, y: y, z: z, w: w }
}
}
/// A wrapper for generating floating point numbers uniformly in the
/// open interval `(0,1)` (not including either endpoint).
///
/// Use `Closed01` for the closed interval `[0,1]`, and the default
/// `Rand` implementation for `f32` and `f64` for the half-open
/// `[0,1)`.
///
/// # Example
/// ```rust
/// use std::rand::{random, Open01};
///
/// let Open01(val) = random::<Open01<f32>>();
/// println!("f32 from (0,1): {}", val);
/// ```
pub struct Open01<F>(pub F);
/// A wrapper for generating floating point numbers uniformly in the
/// closed interval `[0,1]` (including both endpoints).
///
/// Use `Open01` for the closed interval `(0,1)`, and the default
/// `Rand` implementation of `f32` and `f64` for the half-open
/// `[0,1)`.
///
/// # Example
///
/// ```rust
/// use std::rand::{random, Closed01};
///
/// let Closed01(val) = random::<Closed01<f32>>();
/// println!("f32 from [0,1]: {}", val);
/// ```
pub struct Closed01<F>(pub F);
#[cfg(not(test))]
mod std {
pub use core::{option, fmt}; // fail!()
}
#[cfg(test)]
mod test {
use std::rand;
pub struct MyRng<R> { inner: R }
impl<R: rand::Rng> ::Rng for MyRng<R> {
fn next_u32(&mut self) -> u32 {
fn next<T: rand::Rng>(t: &mut T) -> u32 {
use std::rand::Rng;
t.next_u32()
}
next(&mut self.inner)
}
}
pub fn rng() -> MyRng<rand::TaskRng> {
MyRng { inner: rand::task_rng() }
}
pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
MyRng { inner: rand::weak_rng() }
}
} | #[inline]
fn next_u32(&mut self) -> u32 {
let x = self.x; | random_line_split |
lib.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Interface to random number generators in Rust.
//!
//! This is an experimental library which lives underneath the standard library
//! in its dependency chain. This library is intended to define the interface
//! for random number generation and also provide utilities around doing so. It
//! is not recommended to use this library directly, but rather the official
//! interface through `std::rand`.
#![crate_name = "rand"]
#![license = "MIT/ASL2"]
#![crate_type = "rlib"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/master/",
html_playground_url = "http://play.rust-lang.org/")]
#![feature(macro_rules, phase, globs)]
#![no_std]
#![experimental]
#[phase(plugin, link)]
extern crate core;
#[cfg(test)] #[phase(plugin, link)] extern crate std;
#[cfg(test)] #[phase(plugin, link)] extern crate log;
#[cfg(test)] extern crate native;
#[cfg(test)] extern crate debug;
use core::prelude::*;
pub use isaac::{IsaacRng, Isaac64Rng};
use distributions::{Range, IndependentSample};
use distributions::range::SampleRange;
#[cfg(test)]
static RAND_BENCH_N: u64 = 100;
pub mod distributions;
pub mod isaac;
pub mod reseeding;
mod rand_impls;
/// A type that can be randomly generated using an `Rng`.
pub trait Rand {
/// Generates a random instance of this type using the specified source of
/// randomness.
fn rand<R: Rng>(rng: &mut R) -> Self;
}
/// A random number generator.
pub trait Rng {
/// Return the next random u32.
///
/// This rarely needs to be called directly, prefer `r.gen()` to
/// `r.next_u32()`.
// FIXME #7771: Should be implemented in terms of next_u64
fn next_u32(&mut self) -> u32;
/// Return the next random u64.
///
/// By default this is implemented in terms of `next_u32`. An
/// implementation of this trait must provide at least one of
/// these two methods. Similarly to `next_u32`, this rarely needs
/// to be called directly, prefer `r.gen()` to `r.next_u64()`.
fn next_u64(&mut self) -> u64 {
(self.next_u32() as u64 << 32) | (self.next_u32() as u64)
}
/// Fill `dest` with random data.
///
/// This has a default implementation in terms of `next_u64` and
/// `next_u32`, but should be overridden by implementations that
/// offer a more efficient solution than just calling those
/// methods repeatedly.
///
/// This method does *not* have a requirement to bear any fixed
/// relationship to the other methods, for example, it does *not*
/// have to result in the same output as progressively filling
/// `dest` with `self.gen::<u8>()`, and any such behaviour should
/// not be relied upon.
///
/// This method should guarantee that `dest` is entirely filled
/// with new data, and may fail if this is impossible
/// (e.g. reading past the end of a file that is being used as the
/// source of randomness).
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut v = [0u8,.. 13579];
/// task_rng().fill_bytes(v);
/// println!("{}", v.as_slice());
/// ```
fn fill_bytes(&mut self, dest: &mut [u8]) {
// this could, in theory, be done by transmuting dest to a
// [u64], but this is (1) likely to be undefined behaviour for
// LLVM, (2) has to be very careful about alignment concerns,
// (3) adds more `unsafe` that needs to be checked, (4)
// probably doesn't give much performance gain if
// optimisations are on.
let mut count = 0i;
let mut num = 0;
for byte in dest.mut_iter() {
if count == 0 |
*byte = (num & 0xff) as u8;
num >>= 8;
count -= 1;
}
}
/// Return a random value of a `Rand` type.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let x: uint = rng.gen();
/// println!("{}", x);
/// println!("{}", rng.gen::<(f64, bool)>());
/// ```
#[inline(always)]
fn gen<T: Rand>(&mut self) -> T {
Rand::rand(self)
}
/// Return an iterator which will yield an infinite number of randomly
/// generated items.
///
/// # Example
///
/// ```
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
/// println!("{}", x);
/// println!("{}", rng.gen_iter::<(f64, bool)>().take(5)
/// .collect::<Vec<(f64, bool)>>());
/// ```
fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
Generator { rng: self }
}
/// Generate a random value in the range [`low`, `high`). Fails if
/// `low >= high`.
///
/// This is a convenience wrapper around
/// `distributions::Range`. If this function will be called
/// repeatedly with the same arguments, one should use `Range`, as
/// that will amortize the computations that allow for perfect
/// uniformity, as they only happen on initialization.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let n: uint = rng.gen_range(0u, 10);
/// println!("{}", n);
/// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
/// println!("{}", m);
/// ```
fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
assert!(low < high, "Rng.gen_range called with low >= high");
Range::new(low, high).ind_sample(self)
}
/// Return a bool with a 1 in n chance of true
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// println!("{:b}", rng.gen_weighted_bool(3));
/// ```
fn gen_weighted_bool(&mut self, n: uint) -> bool {
n == 0 || self.gen_range(0, n) == 0
}
/// Return an iterator of random characters from the set A-Z,a-z,0-9.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let s: String = task_rng().gen_ascii_chars().take(10).collect();
/// println!("{}", s);
/// ```
fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
AsciiGenerator { rng: self }
}
/// Return a random element from `values`.
///
/// Return `None` if `values` is empty.
///
/// # Example
///
/// ```
/// use std::rand::{task_rng, Rng};
///
/// let choices = [1i, 2, 4, 8, 16, 32];
/// let mut rng = task_rng();
/// println!("{}", rng.choose(choices));
/// assert_eq!(rng.choose(choices.slice_to(0)), None);
/// ```
fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
if values.is_empty() {
None
} else {
Some(&values[self.gen_range(0u, values.len())])
}
}
/// Deprecated name for `choose()`.
#[deprecated = "replaced by.choose()"]
fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
self.choose(values)
}
/// Shuffle a mutable slice in place.
///
/// # Example
///
/// ```rust
/// use std::rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let mut y = [1i, 2, 3];
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// ```
fn shuffle<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
while i >= 2u {
// invariant: elements with index >= i have been locked in place.
i -= 1u;
// lock element i in place.
values.swap(i, self.gen_range(0u, i + 1u));
}
}
}
/// Iterator which will generate a stream of random items.
///
/// This iterator is created via the `gen_iter` method on `Rng`.
pub struct Generator<'a, T, R:'a> {
rng: &'a mut R,
}
impl<'a, T: Rand, R: Rng> Iterator<T> for Generator<'a, T, R> {
fn next(&mut self) -> Option<T> {
Some(self.rng.gen())
}
}
/// Iterator which will continuously generate random ascii characters.
///
/// This iterator is created via the `gen_ascii_chars` method on `Rng`.
pub struct AsciiGenerator<'a, R:'a> {
rng: &'a mut R,
}
impl<'a, R: Rng> Iterator<char> for AsciiGenerator<'a, R> {
fn next(&mut self) -> Option<char> {
static GEN_ASCII_STR_CHARSET: &'static [u8] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
abcdefghijklmnopqrstuvwxyz\
0123456789";
Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
}
}
/// A random number generator that can be explicitly seeded to produce
/// the same stream of randomness multiple times.
pub trait SeedableRng<Seed>: Rng {
/// Reseed an RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// let seed: &[_] = &[1, 2, 3, 4];
/// let mut rng: StdRng = SeedableRng::from_seed(seed);
/// println!("{}", rng.gen::<f64>());
/// rng.reseed([5, 6, 7, 8]);
/// println!("{}", rng.gen::<f64>());
/// ```
fn reseed(&mut self, Seed);
/// Create a new RNG with the given seed.
///
/// # Example
///
/// ```rust
/// use std::rand::{Rng, SeedableRng, StdRng};
///
/// let seed: &[_] = &[1, 2, 3, 4];
/// let mut rng: StdRng = SeedableRng::from_seed(seed);
/// println!("{}", rng.gen::<f64>());
/// ```
fn from_seed(seed: Seed) -> Self;
}
/// An Xorshift[1] random number
/// generator.
///
/// The Xorshift algorithm is not suitable for cryptographic purposes
/// but is very fast. If you do not know for sure that it fits your
/// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
///
/// [1]: Marsaglia, George (July 2003). ["Xorshift
/// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
/// Statistical Software*. Vol. 8 (Issue 14).
pub struct XorShiftRng {
x: u32,
y: u32,
z: u32,
w: u32,
}
impl XorShiftRng {
/// Creates a new XorShiftRng instance which is not seeded.
///
/// The initial values of this RNG are constants, so all generators created
/// by this function will yield the same stream of random numbers. It is
/// highly recommended that this is created through `SeedableRng` instead of
/// this function
pub fn new_unseeded() -> XorShiftRng {
XorShiftRng {
x: 0x193a6754,
y: 0xa8a7d469,
z: 0x97830e05,
w: 0x113ba7bb,
}
}
}
impl Rng for XorShiftRng {
#[inline]
fn next_u32(&mut self) -> u32 {
let x = self.x;
let t = x ^ (x << 11);
self.x = self.y;
self.y = self.z;
self.z = self.w;
let w = self.w;
self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
self.w
}
}
impl SeedableRng<[u32,.. 4]> for XorShiftRng {
/// Reseed an XorShiftRng. This will fail if `seed` is entirely 0.
fn reseed(&mut self, seed: [u32,.. 4]) {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng.reseed called with an all zero seed.");
self.x = seed[0];
self.y = seed[1];
self.z = seed[2];
self.w = seed[3];
}
/// Create a new XorShiftRng. This will fail if `seed` is entirely 0.
fn from_seed(seed: [u32,.. 4]) -> XorShiftRng {
assert!(!seed.iter().all(|&x| x == 0),
"XorShiftRng::from_seed called with an all zero seed.");
XorShiftRng {
x: seed[0],
y: seed[1],
z: seed[2],
w: seed[3]
}
}
}
impl Rand for XorShiftRng {
fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
let mut tuple: (u32, u32, u32, u32) = rng.gen();
while tuple == (0, 0, 0, 0) {
tuple = rng.gen();
}
let (x, y, z, w) = tuple;
XorShiftRng { x: x, y: y, z: z, w: w }
}
}
/// A wrapper for generating floating point numbers uniformly in the
/// open interval `(0,1)` (not including either endpoint).
///
/// Use `Closed01` for the closed interval `[0,1]`, and the default
/// `Rand` implementation for `f32` and `f64` for the half-open
/// `[0,1)`.
///
/// # Example
/// ```rust
/// use std::rand::{random, Open01};
///
/// let Open01(val) = random::<Open01<f32>>();
/// println!("f32 from (0,1): {}", val);
/// ```
pub struct Open01<F>(pub F);
/// A wrapper for generating floating point numbers uniformly in the
/// closed interval `[0,1]` (including both endpoints).
///
/// Use `Open01` for the closed interval `(0,1)`, and the default
/// `Rand` implementation of `f32` and `f64` for the half-open
/// `[0,1)`.
///
/// # Example
///
/// ```rust
/// use std::rand::{random, Closed01};
///
/// let Closed01(val) = random::<Closed01<f32>>();
/// println!("f32 from [0,1]: {}", val);
/// ```
pub struct Closed01<F>(pub F);
#[cfg(not(test))]
mod std {
pub use core::{option, fmt}; // fail!()
}
#[cfg(test)]
mod test {
use std::rand;
pub struct MyRng<R> { inner: R }
impl<R: rand::Rng> ::Rng for MyRng<R> {
fn next_u32(&mut self) -> u32 {
fn next<T: rand::Rng>(t: &mut T) -> u32 {
use std::rand::Rng;
t.next_u32()
}
next(&mut self.inner)
}
}
pub fn rng() -> MyRng<rand::TaskRng> {
MyRng { inner: rand::task_rng() }
}
pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
MyRng { inner: rand::weak_rng() }
}
}
| {
// we could micro-optimise here by generating a u32 if
// we only need a few more bytes to fill the vector
// (i.e. at most 4).
num = self.next_u64();
count = 8;
} | conditional_block |
proptest_types.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::account::{xus_currency_code, Account, AccountData, AccountRoleSpecifier};
use proptest::prelude::*;
impl Arbitrary for Account {
type Parameters = ();
fn arbitrary_with(_params: ()) -> Self::Strategy {
// Provide Account::new as the canonical strategy. This means that no shrinking will happen,
// but that's fine as accounts have nothing to shrink inside them anyway.
Account::new as Self::Strategy
}
type Strategy = fn() -> Account;
}
impl AccountData {
/// Returns a [`Strategy`] that creates `AccountData` instances.
pub fn strategy(balance_strategy: impl Strategy<Value = u64>) -> impl Strategy<Value = Self> | sequence_number,
sent_events_count,
received_events_count,
AccountRoleSpecifier::default(), // TODO: Vary account type?
)
},
)
}
}
| {
// Pick sequence numbers and event counts in a smaller range so that valid transactions can
// be generated.
// XXX should we also test edge cases around large sequence numbers?
let sequence_strategy = 0u64..(1 << 32);
let event_count_strategy = 0u64..(1 << 32);
(
any::<Account>(),
balance_strategy,
sequence_strategy,
event_count_strategy.clone(),
event_count_strategy,
)
.prop_map(
|(account, balance, sequence_number, sent_events_count, received_events_count)| {
AccountData::with_account_and_event_counts(
account,
balance,
xus_currency_code(), // TODO: Vary account balance currency? | identifier_body |
proptest_types.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::account::{xus_currency_code, Account, AccountData, AccountRoleSpecifier};
use proptest::prelude::*;
impl Arbitrary for Account {
type Parameters = ();
fn arbitrary_with(_params: ()) -> Self::Strategy {
// Provide Account::new as the canonical strategy. This means that no shrinking will happen,
// but that's fine as accounts have nothing to shrink inside them anyway.
Account::new as Self::Strategy
}
type Strategy = fn() -> Account;
}
impl AccountData {
/// Returns a [`Strategy`] that creates `AccountData` instances.
pub fn | (balance_strategy: impl Strategy<Value = u64>) -> impl Strategy<Value = Self> {
// Pick sequence numbers and event counts in a smaller range so that valid transactions can
// be generated.
// XXX should we also test edge cases around large sequence numbers?
let sequence_strategy = 0u64..(1 << 32);
let event_count_strategy = 0u64..(1 << 32);
(
any::<Account>(),
balance_strategy,
sequence_strategy,
event_count_strategy.clone(),
event_count_strategy,
)
.prop_map(
|(account, balance, sequence_number, sent_events_count, received_events_count)| {
AccountData::with_account_and_event_counts(
account,
balance,
xus_currency_code(), // TODO: Vary account balance currency?
sequence_number,
sent_events_count,
received_events_count,
AccountRoleSpecifier::default(), // TODO: Vary account type?
)
},
)
}
}
| strategy | identifier_name |
proptest_types.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::account::{xus_currency_code, Account, AccountData, AccountRoleSpecifier};
use proptest::prelude::*;
impl Arbitrary for Account {
type Parameters = ();
fn arbitrary_with(_params: ()) -> Self::Strategy {
// Provide Account::new as the canonical strategy. This means that no shrinking will happen,
// but that's fine as accounts have nothing to shrink inside them anyway.
Account::new as Self::Strategy
}
type Strategy = fn() -> Account;
}
impl AccountData {
/// Returns a [`Strategy`] that creates `AccountData` instances.
pub fn strategy(balance_strategy: impl Strategy<Value = u64>) -> impl Strategy<Value = Self> {
// Pick sequence numbers and event counts in a smaller range so that valid transactions can
// be generated.
// XXX should we also test edge cases around large sequence numbers?
let sequence_strategy = 0u64..(1 << 32);
let event_count_strategy = 0u64..(1 << 32);
(
any::<Account>(), | event_count_strategy,
)
.prop_map(
|(account, balance, sequence_number, sent_events_count, received_events_count)| {
AccountData::with_account_and_event_counts(
account,
balance,
xus_currency_code(), // TODO: Vary account balance currency?
sequence_number,
sent_events_count,
received_events_count,
AccountRoleSpecifier::default(), // TODO: Vary account type?
)
},
)
}
} | balance_strategy,
sequence_strategy,
event_count_strategy.clone(), | random_line_split |
gainnode.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::audionode::AudioNode;
use crate::dom::audioparam::AudioParam;
use crate::dom::baseaudiocontext::BaseAudioContext;
use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
ChannelCountMode, ChannelInterpretation,
};
use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate;
use crate::dom::bindings::codegen::Bindings::GainNodeBinding::{GainNodeMethods, GainOptions};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_media::audio::gain_node::GainNodeOptions;
use servo_media::audio::node::AudioNodeInit;
use servo_media::audio::param::ParamType;
use std::f32;
#[dom_struct]
pub struct GainNode {
node: AudioNode,
gain: Dom<AudioParam>,
}
impl GainNode {
#[allow(unrooted_must_root)]
pub fn new_inherited(
window: &Window,
context: &BaseAudioContext,
options: &GainOptions,
) -> Fallible<GainNode> {
let node_options =
options
.parent
.unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers);
let node = AudioNode::new_inherited(
AudioNodeInit::GainNode(options.into()),
context,
node_options,
1, // inputs
1, // outputs
)?;
let gain = AudioParam::new(
window,
context,
node.node_id(),
ParamType::Gain,
AutomationRate::A_rate,
*options.gain, // default value
f32::MIN, // min value
f32::MAX, // max value
);
Ok(GainNode {
node,
gain: Dom::from_ref(&gain),
})
}
#[allow(unrooted_must_root)]
pub fn new(
window: &Window,
context: &BaseAudioContext,
options: &GainOptions,
) -> Fallible<DomRoot<GainNode>> {
let node = GainNode::new_inherited(window, context, options)?;
Ok(reflect_dom_object(Box::new(node), window))
}
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
context: &BaseAudioContext,
options: &GainOptions,
) -> Fallible<DomRoot<GainNode>> {
GainNode::new(window, context, options)
}
}
impl GainNodeMethods for GainNode {
// https://webaudio.github.io/web-audio-api/#dom-gainnode-gain
fn | (&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.gain)
}
}
impl<'a> From<&'a GainOptions> for GainNodeOptions {
fn from(options: &'a GainOptions) -> Self {
Self {
gain: *options.gain,
}
}
}
| Gain | identifier_name |
gainnode.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::audionode::AudioNode;
use crate::dom::audioparam::AudioParam;
use crate::dom::baseaudiocontext::BaseAudioContext;
use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
ChannelCountMode, ChannelInterpretation,
};
use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate;
use crate::dom::bindings::codegen::Bindings::GainNodeBinding::{GainNodeMethods, GainOptions};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_media::audio::gain_node::GainNodeOptions;
use servo_media::audio::node::AudioNodeInit;
use servo_media::audio::param::ParamType;
use std::f32;
#[dom_struct]
pub struct GainNode {
node: AudioNode,
gain: Dom<AudioParam>,
}
impl GainNode {
#[allow(unrooted_must_root)]
pub fn new_inherited(
window: &Window,
context: &BaseAudioContext,
options: &GainOptions,
) -> Fallible<GainNode> {
let node_options =
options
.parent
.unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers);
let node = AudioNode::new_inherited(
AudioNodeInit::GainNode(options.into()),
context,
node_options,
1, // inputs
1, // outputs
)?;
let gain = AudioParam::new(
window,
context,
node.node_id(),
ParamType::Gain,
AutomationRate::A_rate,
*options.gain, // default value
f32::MIN, // min value
f32::MAX, // max value
);
Ok(GainNode {
node,
gain: Dom::from_ref(&gain),
})
}
#[allow(unrooted_must_root)]
pub fn new(
window: &Window,
context: &BaseAudioContext,
options: &GainOptions,
) -> Fallible<DomRoot<GainNode>> |
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
context: &BaseAudioContext,
options: &GainOptions,
) -> Fallible<DomRoot<GainNode>> {
GainNode::new(window, context, options)
}
}
impl GainNodeMethods for GainNode {
// https://webaudio.github.io/web-audio-api/#dom-gainnode-gain
fn Gain(&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.gain)
}
}
impl<'a> From<&'a GainOptions> for GainNodeOptions {
fn from(options: &'a GainOptions) -> Self {
Self {
gain: *options.gain,
}
}
}
| {
let node = GainNode::new_inherited(window, context, options)?;
Ok(reflect_dom_object(Box::new(node), window))
} | identifier_body |
gainnode.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use crate::dom::audionode::AudioNode;
use crate::dom::audioparam::AudioParam;
use crate::dom::baseaudiocontext::BaseAudioContext;
use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{
ChannelCountMode, ChannelInterpretation,
};
use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate;
use crate::dom::bindings::codegen::Bindings::GainNodeBinding::{GainNodeMethods, GainOptions};
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::reflect_dom_object;
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::window::Window;
use dom_struct::dom_struct;
use servo_media::audio::gain_node::GainNodeOptions;
use servo_media::audio::node::AudioNodeInit;
use servo_media::audio::param::ParamType;
use std::f32;
#[dom_struct]
pub struct GainNode {
node: AudioNode,
gain: Dom<AudioParam>,
}
impl GainNode {
#[allow(unrooted_must_root)]
pub fn new_inherited(
window: &Window,
context: &BaseAudioContext,
options: &GainOptions,
) -> Fallible<GainNode> {
let node_options =
options
.parent
.unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers);
let node = AudioNode::new_inherited(
AudioNodeInit::GainNode(options.into()),
context,
node_options,
1, // inputs
1, // outputs
)?;
let gain = AudioParam::new(
window,
context,
node.node_id(),
ParamType::Gain,
AutomationRate::A_rate,
*options.gain, // default value
f32::MIN, // min value
f32::MAX, // max value
); | node,
gain: Dom::from_ref(&gain),
})
}
#[allow(unrooted_must_root)]
pub fn new(
window: &Window,
context: &BaseAudioContext,
options: &GainOptions,
) -> Fallible<DomRoot<GainNode>> {
let node = GainNode::new_inherited(window, context, options)?;
Ok(reflect_dom_object(Box::new(node), window))
}
#[allow(non_snake_case)]
pub fn Constructor(
window: &Window,
context: &BaseAudioContext,
options: &GainOptions,
) -> Fallible<DomRoot<GainNode>> {
GainNode::new(window, context, options)
}
}
impl GainNodeMethods for GainNode {
// https://webaudio.github.io/web-audio-api/#dom-gainnode-gain
fn Gain(&self) -> DomRoot<AudioParam> {
DomRoot::from_ref(&self.gain)
}
}
impl<'a> From<&'a GainOptions> for GainNodeOptions {
fn from(options: &'a GainOptions) -> Self {
Self {
gain: *options.gain,
}
}
} | Ok(GainNode { | random_line_split |
cipherstate.rs | use crypto_types::*;
pub trait CipherStateType {
fn name(&self, out: &mut [u8]) -> usize;
fn set(&mut self, key: &[u8], n: u64);
fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]);
fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool;
fn encrypt(&mut self, plaintext: &[u8], out: &mut[u8]);
fn decrypt(&mut self, ciphertext: &[u8], out: &mut[u8]) -> bool; | cipher : C,
n : u64,
has_key : bool,
overflow: bool
}
impl<C: CipherType + Default> CipherStateType for CipherState<C> {
fn name(&self, out: &mut [u8]) -> usize {
self.cipher.name(out)
}
fn set(&mut self, key: &[u8], n: u64) {
self.cipher.set(key);
self.n = n;
self.has_key = true;
self.overflow = false;
}
fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]) {
assert!(self.has_key &&!self.overflow);
self.cipher.encrypt(self.n, authtext, plaintext, out);
self.n += 1;
if self.n == 0 {
self.overflow = true;
}
}
fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool {
assert!(self.has_key &&!self.overflow);
let result = self.cipher.decrypt(self.n, authtext, ciphertext, out);
self.n += 1;
if self.n == 0 {
self.overflow = true;
}
result
}
fn encrypt(&mut self, plaintext: &[u8], out: &mut[u8]) {
self.encrypt_ad(&[0u8;0], plaintext, out)
}
fn decrypt(&mut self, ciphertext: &[u8], out: &mut[u8]) -> bool {
self.decrypt_ad(&[0u8;0], ciphertext, out)
}
} | }
#[derive(Default)]
pub struct CipherState<C: CipherType + Default> { | random_line_split |
cipherstate.rs |
use crypto_types::*;
pub trait CipherStateType {
fn name(&self, out: &mut [u8]) -> usize;
fn set(&mut self, key: &[u8], n: u64);
fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]);
fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool;
fn encrypt(&mut self, plaintext: &[u8], out: &mut[u8]);
fn decrypt(&mut self, ciphertext: &[u8], out: &mut[u8]) -> bool;
}
#[derive(Default)]
pub struct CipherState<C: CipherType + Default> {
cipher : C,
n : u64,
has_key : bool,
overflow: bool
}
impl<C: CipherType + Default> CipherStateType for CipherState<C> {
fn name(&self, out: &mut [u8]) -> usize {
self.cipher.name(out)
}
fn set(&mut self, key: &[u8], n: u64) {
self.cipher.set(key);
self.n = n;
self.has_key = true;
self.overflow = false;
}
fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]) {
assert!(self.has_key &&!self.overflow);
self.cipher.encrypt(self.n, authtext, plaintext, out);
self.n += 1;
if self.n == 0 |
}
fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool {
assert!(self.has_key &&!self.overflow);
let result = self.cipher.decrypt(self.n, authtext, ciphertext, out);
self.n += 1;
if self.n == 0 {
self.overflow = true;
}
result
}
fn encrypt(&mut self, plaintext: &[u8], out: &mut[u8]) {
self.encrypt_ad(&[0u8;0], plaintext, out)
}
fn decrypt(&mut self, ciphertext: &[u8], out: &mut[u8]) -> bool {
self.decrypt_ad(&[0u8;0], ciphertext, out)
}
}
| {
self.overflow = true;
} | conditional_block |
cipherstate.rs |
use crypto_types::*;
pub trait CipherStateType {
fn name(&self, out: &mut [u8]) -> usize;
fn set(&mut self, key: &[u8], n: u64);
fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]);
fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool;
fn encrypt(&mut self, plaintext: &[u8], out: &mut[u8]);
fn decrypt(&mut self, ciphertext: &[u8], out: &mut[u8]) -> bool;
}
#[derive(Default)]
pub struct CipherState<C: CipherType + Default> {
cipher : C,
n : u64,
has_key : bool,
overflow: bool
}
impl<C: CipherType + Default> CipherStateType for CipherState<C> {
fn name(&self, out: &mut [u8]) -> usize {
self.cipher.name(out)
}
fn set(&mut self, key: &[u8], n: u64) |
fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]) {
assert!(self.has_key &&!self.overflow);
self.cipher.encrypt(self.n, authtext, plaintext, out);
self.n += 1;
if self.n == 0 {
self.overflow = true;
}
}
fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool {
assert!(self.has_key &&!self.overflow);
let result = self.cipher.decrypt(self.n, authtext, ciphertext, out);
self.n += 1;
if self.n == 0 {
self.overflow = true;
}
result
}
fn encrypt(&mut self, plaintext: &[u8], out: &mut[u8]) {
self.encrypt_ad(&[0u8;0], plaintext, out)
}
fn decrypt(&mut self, ciphertext: &[u8], out: &mut[u8]) -> bool {
self.decrypt_ad(&[0u8;0], ciphertext, out)
}
}
| {
self.cipher.set(key);
self.n = n;
self.has_key = true;
self.overflow = false;
} | identifier_body |
cipherstate.rs |
use crypto_types::*;
pub trait CipherStateType {
fn name(&self, out: &mut [u8]) -> usize;
fn set(&mut self, key: &[u8], n: u64);
fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]);
fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool;
fn encrypt(&mut self, plaintext: &[u8], out: &mut[u8]);
fn decrypt(&mut self, ciphertext: &[u8], out: &mut[u8]) -> bool;
}
#[derive(Default)]
pub struct CipherState<C: CipherType + Default> {
cipher : C,
n : u64,
has_key : bool,
overflow: bool
}
impl<C: CipherType + Default> CipherStateType for CipherState<C> {
fn name(&self, out: &mut [u8]) -> usize {
self.cipher.name(out)
}
fn | (&mut self, key: &[u8], n: u64) {
self.cipher.set(key);
self.n = n;
self.has_key = true;
self.overflow = false;
}
fn encrypt_ad(&mut self, authtext: &[u8], plaintext: &[u8], out: &mut[u8]) {
assert!(self.has_key &&!self.overflow);
self.cipher.encrypt(self.n, authtext, plaintext, out);
self.n += 1;
if self.n == 0 {
self.overflow = true;
}
}
fn decrypt_ad(&mut self, authtext: &[u8], ciphertext: &[u8], out: &mut[u8]) -> bool {
assert!(self.has_key &&!self.overflow);
let result = self.cipher.decrypt(self.n, authtext, ciphertext, out);
self.n += 1;
if self.n == 0 {
self.overflow = true;
}
result
}
fn encrypt(&mut self, plaintext: &[u8], out: &mut[u8]) {
self.encrypt_ad(&[0u8;0], plaintext, out)
}
fn decrypt(&mut self, ciphertext: &[u8], out: &mut[u8]) -> bool {
self.decrypt_ad(&[0u8;0], ciphertext, out)
}
}
| set | identifier_name |
no_1207_unique_number_of_occurrences.rs | struct Solution;
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn unique_occurrences(arr: Vec<i32>) -> bool {
let mut cnts = HashMap::new();
for n in arr {
*cnts.entry(n).or_insert(0) += 1;
}
let mut times = HashSet::new();
for (_, cnt) in cnts.into_iter() {
// 如果 cnt 不在 times 中,insert 返回 true,否则返回 false
// 如果 cnt 已经存在于 times 中,则有两个值出现了同样的次数。
if!times.insert(cnt) { | true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_unique_occurrences() {
assert_eq!(Solution::unique_occurrences(vec![1, 2, 2, 1, 1, 3]), true);
assert_eq!(Solution::unique_occurrences(vec![1, 2]), false);
assert_eq!(
Solution::unique_occurrences(vec![-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]),
true
);
}
} | return false;
}
}
| random_line_split |
no_1207_unique_number_of_occurrences.rs | struct Solution;
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn unique_occurrences(arr: Vec<i32>) -> bool {
let mut cnts = HashMap::new();
for n in arr {
*cnts.entry(n).or_insert(0) += 1;
}
let mut times = HashSet::new();
for (_, cnt) in cnts.into_iter() {
// 如果 cnt 不在 times 中,insert 返回 true,否则返回 false
// 如果 cnt 已经存在于 times 中,则有两个值出现了同样的次数。
if!times.insert(cnt) {
return false;
}
}
true
| ::*;
#[test]
fn test_unique_occurrences() {
assert_eq!(Solution::unique_occurrences(vec![1, 2, 2, 1, 1, 3]), true);
assert_eq!(Solution::unique_occurrences(vec![1, 2]), false);
assert_eq!(
Solution::unique_occurrences(vec![-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]),
true
);
}
}
| }
}
#[cfg(test)]
mod tests {
use super | conditional_block |
no_1207_unique_number_of_occurrences.rs | struct Solution;
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn unique_occurrences(arr: Vec<i32>) -> bool {
let mut cnts = HashMap::new();
for n in arr {
*cnts.entry(n).or_insert(0) += 1;
}
let mut times = HashSet::new();
for (_, cnt) in cnts.into_iter() {
// 如果 cnt 不在 times 中,insert 返回 true,否则返回 false
// 如果 cnt 已经存在于 times 中,则有两个值出现了同样的次数。
if!times.insert(cnt) {
return false;
}
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_unique_occurrences() {
assert_eq!(Solution::unique_occurren | 3]), true);
assert_eq!(Solution::unique_occurrences(vec![1, 2]), false);
assert_eq!(
Solution::unique_occurrences(vec![-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]),
true
);
}
}
| ces(vec![1, 2, 2, 1, 1, | identifier_name |
no_1207_unique_number_of_occurrences.rs | struct Solution;
use std::collections::{HashMap, HashSet};
impl Solution {
pub fn unique_occurrences(arr: Vec<i32>) -> bool | use super::*;
#[test]
fn test_
unique_occurrences() {
assert_eq!(Solution::unique_occurrences(vec![1, 2, 2, 1, 1, 3]), true);
assert_eq!(Solution::unique_occurrences(vec![1, 2]), false);
assert_eq!(
Solution::unique_occurrences(vec![-3, 0, 1, -3, 1, 1, 1, -3, 10, 0]),
true
);
}
}
| {
let mut cnts = HashMap::new();
for n in arr {
*cnts.entry(n).or_insert(0) += 1;
}
let mut times = HashSet::new();
for (_, cnt) in cnts.into_iter() {
// 如果 cnt 不在 times 中,insert 返回 true,否则返回 false
// 如果 cnt 已经存在于 times 中,则有两个值出现了同样的次数。
if !times.insert(cnt) {
return false;
}
}
true
}
}
#[cfg(test)]
mod tests { | identifier_body |
class-cast-to-trait-multiple-types.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.
#![feature(managed_boxes)]
trait noisy {
fn speak(&mut self) -> int;
}
struct dog {
barks: uint,
volume: int,
}
impl dog {
fn bark(&mut self) -> int {
println!("Woof {} {}", self.barks, self.volume);
self.barks += 1u;
if self.barks % 3u == 0u {
self.volume += 1;
}
if self.barks % 10u == 0u {
self.volume -= 2;
}
println!("Grrr {} {}", self.barks, self.volume);
self.volume
}
}
impl noisy for dog {
fn speak(&mut self) -> int {
self.bark()
}
}
fn dog() -> dog {
dog {
volume: 0,
barks: 0u
}
}
#[deriving(Clone)]
struct | {
meows: uint,
how_hungry: int,
name: ~str,
}
impl noisy for cat {
fn speak(&mut self) -> int {
self.meow() as int
}
}
impl cat {
pub fn meow_count(&self) -> uint {
self.meows
}
}
impl cat {
fn meow(&mut self) -> uint {
println!("Meow");
self.meows += 1u;
if self.meows % 5u == 0u {
self.how_hungry += 1;
}
self.meows
}
}
fn cat(in_x: uint, in_y: int, in_name: ~str) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
fn annoy_neighbors(critter: &mut noisy) {
for _i in range(0u, 10) { critter.speak(); }
}
pub fn main() {
let mut nyan: cat = cat(0u, 2, "nyan".to_owned());
let mut whitefang: dog = dog();
annoy_neighbors(&mut nyan);
annoy_neighbors(&mut whitefang);
assert_eq!(nyan.meow_count(), 10u);
assert_eq!(whitefang.volume, 1);
}
| cat | identifier_name |
class-cast-to-trait-multiple-types.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.
#![feature(managed_boxes)]
trait noisy {
fn speak(&mut self) -> int;
}
struct dog {
barks: uint,
volume: int,
}
impl dog {
fn bark(&mut self) -> int {
println!("Woof {} {}", self.barks, self.volume);
self.barks += 1u;
if self.barks % 3u == 0u {
self.volume += 1;
}
if self.barks % 10u == 0u {
self.volume -= 2;
}
println!("Grrr {} {}", self.barks, self.volume);
self.volume
}
}
impl noisy for dog {
fn speak(&mut self) -> int {
self.bark()
}
}
fn dog() -> dog {
dog {
volume: 0,
barks: 0u
}
}
#[deriving(Clone)]
struct cat {
meows: uint,
how_hungry: int,
name: ~str,
}
impl noisy for cat {
fn speak(&mut self) -> int {
self.meow() as int
}
}
impl cat {
pub fn meow_count(&self) -> uint {
self.meows
}
}
impl cat {
fn meow(&mut self) -> uint {
println!("Meow");
self.meows += 1u;
if self.meows % 5u == 0u {
self.how_hungry += 1;
}
self.meows
}
}
fn cat(in_x: uint, in_y: int, in_name: ~str) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
fn annoy_neighbors(critter: &mut noisy) {
for _i in range(0u, 10) { critter.speak(); } | annoy_neighbors(&mut nyan);
annoy_neighbors(&mut whitefang);
assert_eq!(nyan.meow_count(), 10u);
assert_eq!(whitefang.volume, 1);
} | }
pub fn main() {
let mut nyan: cat = cat(0u, 2, "nyan".to_owned());
let mut whitefang: dog = dog(); | random_line_split |
class-cast-to-trait-multiple-types.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.
#![feature(managed_boxes)]
trait noisy {
fn speak(&mut self) -> int;
}
struct dog {
barks: uint,
volume: int,
}
impl dog {
fn bark(&mut self) -> int {
println!("Woof {} {}", self.barks, self.volume);
self.barks += 1u;
if self.barks % 3u == 0u |
if self.barks % 10u == 0u {
self.volume -= 2;
}
println!("Grrr {} {}", self.barks, self.volume);
self.volume
}
}
impl noisy for dog {
fn speak(&mut self) -> int {
self.bark()
}
}
fn dog() -> dog {
dog {
volume: 0,
barks: 0u
}
}
#[deriving(Clone)]
struct cat {
meows: uint,
how_hungry: int,
name: ~str,
}
impl noisy for cat {
fn speak(&mut self) -> int {
self.meow() as int
}
}
impl cat {
pub fn meow_count(&self) -> uint {
self.meows
}
}
impl cat {
fn meow(&mut self) -> uint {
println!("Meow");
self.meows += 1u;
if self.meows % 5u == 0u {
self.how_hungry += 1;
}
self.meows
}
}
fn cat(in_x: uint, in_y: int, in_name: ~str) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
fn annoy_neighbors(critter: &mut noisy) {
for _i in range(0u, 10) { critter.speak(); }
}
pub fn main() {
let mut nyan: cat = cat(0u, 2, "nyan".to_owned());
let mut whitefang: dog = dog();
annoy_neighbors(&mut nyan);
annoy_neighbors(&mut whitefang);
assert_eq!(nyan.meow_count(), 10u);
assert_eq!(whitefang.volume, 1);
}
| {
self.volume += 1;
} | conditional_block |
class-cast-to-trait-multiple-types.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.
#![feature(managed_boxes)]
trait noisy {
fn speak(&mut self) -> int;
}
struct dog {
barks: uint,
volume: int,
}
impl dog {
fn bark(&mut self) -> int |
}
impl noisy for dog {
fn speak(&mut self) -> int {
self.bark()
}
}
fn dog() -> dog {
dog {
volume: 0,
barks: 0u
}
}
#[deriving(Clone)]
struct cat {
meows: uint,
how_hungry: int,
name: ~str,
}
impl noisy for cat {
fn speak(&mut self) -> int {
self.meow() as int
}
}
impl cat {
pub fn meow_count(&self) -> uint {
self.meows
}
}
impl cat {
fn meow(&mut self) -> uint {
println!("Meow");
self.meows += 1u;
if self.meows % 5u == 0u {
self.how_hungry += 1;
}
self.meows
}
}
fn cat(in_x: uint, in_y: int, in_name: ~str) -> cat {
cat {
meows: in_x,
how_hungry: in_y,
name: in_name
}
}
fn annoy_neighbors(critter: &mut noisy) {
for _i in range(0u, 10) { critter.speak(); }
}
pub fn main() {
let mut nyan: cat = cat(0u, 2, "nyan".to_owned());
let mut whitefang: dog = dog();
annoy_neighbors(&mut nyan);
annoy_neighbors(&mut whitefang);
assert_eq!(nyan.meow_count(), 10u);
assert_eq!(whitefang.volume, 1);
}
| {
println!("Woof {} {}", self.barks, self.volume);
self.barks += 1u;
if self.barks % 3u == 0u {
self.volume += 1;
}
if self.barks % 10u == 0u {
self.volume -= 2;
}
println!("Grrr {} {}", self.barks, self.volume);
self.volume
} | identifier_body |
lib.rs | // Copyright (c) 2014, 2015 Robert Clipsham <[email protected]>
//
// 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.
//! # libpnet
//!
//! `libpnet` provides a cross-platform API for low level networking using Rust.
//!
//! There are four key components:
//!
//! * The packet module, allowing safe construction and manipulation of packets
//! * The pnet_packet crate, providing infrastructure for the packet module
//! * The transport module, which allows implementation of transport protocols
//! * The datalink module, which allows sending and receiving data link packets directly
//!
//! ## Terminology
//!
//! The documentation uses the following terms interchangably:
//!
//! * Layer 2, datalink layer
//! * Layer 3, network layer
//! * Layer 4, transport layer
//!
//! Unless otherwise stated, all interactions with libpnet are in host-byte order - any platform
//! specific variations are handled internally.
//!
//! ## Examples
//!
//! More examples, including a packet logger, and a version of the echo server written at the
//! transport layer, can be found in the examples/ directory.
//!
//! ### Ethernet echo server
//!
//! This (fairly useless) code implements an Ethernet echo server. Whenever a packet is received on
//! an interface, it echo's the packet back; reversing the source and destination addresses.
//!
//! ```no_run
//! extern crate pnet;
//!
//! use pnet::datalink::datalink_channel;
//! use pnet::datalink::DataLinkChannelType::Layer2;
//! use pnet::packet::{Packet, MutablePacket};
//! use pnet::util::{NetworkInterface, get_network_interfaces};
//!
//! use std::env;
//!
//! // Invoke as echo <interface name>
//! fn main() {
//! let interface_name = env::args().nth(1).unwrap();
//! let interface_names_match = |iface: &NetworkInterface| iface.name == interface_name;
//!
//! // Find the network interface with the provided name
//! let interfaces = get_network_interfaces();
//! let interface = interfaces.into_iter()
//! .filter(interface_names_match)
//! .next()
//! .unwrap();
//!
//! // Create a new channel, dealing with layer 2 packets
//! let (mut tx, mut rx) = match datalink_channel(&interface, 4096, 4096, Layer2) { | //! };
//!
//! let mut iter = rx.iter();
//! loop {
//! match iter.next() {
//! Ok(packet) => {
//! // Constructs a single packet, the same length as the the one received,
//! // using the provided closure. This allows the packet to be constructed
//! // directly in the write buffer, without copying. If copying is not a
//! // problem, you could also use send_to.
//! //
//! // The packet is sent once the closure has finished executing.
//! tx.build_and_send(1, packet.packet().len(), &mut |mut new_packet| {
//! // Create a clone of the original packet
//! new_packet.clone_from(&packet);
//!
//! // Switch the source and destination
//! new_packet.set_source(packet.get_destination());
//! new_packet.set_destination(packet.get_source());
//! });
//! },
//! Err(e) => {
//! // If an error occurs, we can handle it here
//! panic!("An error occurred while reading: {}", e);
//! }
//! }
//! }
//! }
//! ```
#![crate_name = "pnet"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![deny(missing_docs)]
#![allow(plugin_as_library)]
// FIXME Remove this once the std lib has stabilised
#![feature(convert, custom_attribute, ip_addr, libc, plugin, slice_bytes,
slice_patterns, vec_push_all)]
#![plugin(pnet_macros)]
#![cfg_attr(test, feature(str_char))]
#![cfg_attr(any(target_os = "freebsd", target_os = "macos"), feature(clone_from_slice))]
extern crate libc;
extern crate pnet_macros;
pub mod datalink;
pub mod packet;
pub mod transport;
pub mod util;
mod bindings;
mod internal;
// NOTE should probably have a cfg(pnet_test_network) here, but cargo doesn't allow custom --cfg
// flags
#[cfg(test)]
mod test;
// Required to make sure that imports from pnet_macros work
mod pnet {
pub use packet;
} | //! Ok((tx, rx)) => (tx, rx),
//! Err(e) => panic!("An error occurred when creating the datalink channel: {}", e) | random_line_split |
issue-43893.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-cross-compile
#![crate_name = "foo"]
pub trait SomeTrait {}
pub struct | ;
// @has foo/trait.SomeTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#19'
impl SomeTrait for usize {}
// @has foo/trait.SomeTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#22-24'
impl SomeTrait for SomeStruct {
// deliberately multi-line impl
}
pub trait AnotherTrait {}
// @has foo/trait.AnotherTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#29'
impl<T> AnotherTrait for T {}
| SomeStruct | identifier_name |
issue-43893.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-cross-compile
#![crate_name = "foo"]
pub trait SomeTrait {}
pub struct SomeStruct;
| impl SomeTrait for SomeStruct {
// deliberately multi-line impl
}
pub trait AnotherTrait {}
// @has foo/trait.AnotherTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#29'
impl<T> AnotherTrait for T {} | // @has foo/trait.SomeTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#19'
impl SomeTrait for usize {}
// @has foo/trait.SomeTrait.html '//a/@href' '../src/foo/issue-43893.rs.html#22-24' | random_line_split |
transaction.rs | //! Transaction parsing and verification
//!
//!
use std::fmt;
use std::time::{Instant,Duration};
use itertools::Itertools;
use buffer::*;
use hash::*;
use script::context;
use ffi;
use store;
use store::TxPtr;
use store::Record;
use store::HashIndexGuard;
use store::TxIndex;
const MAX_TRANSACTION_SIZE: usize = 1_000_000;
#[derive(Debug)]
pub enum TransactionError {
UnexpectedEndOfData,
TransactionTooLarge,
NoInputs,
NoOutputs,
DuplicateInputs,
OutputTransactionNotFound,
OutputIndexNotFound,
ScriptError(i32)
}
#[derive(Debug)]
pub enum TransactionOk {
AlreadyExists {
ptr: TxPtr
},
VerifiedAndStored {
ptr: TxPtr, |
}
type TransactionResult<T> = Result<T, TransactionError>;
impl From<EndOfBufferError> for TransactionError {
fn from(_: EndOfBufferError) -> TransactionError {
TransactionError::UnexpectedEndOfData
}
}
/// A transaction represents a parsed transaction
///
/// It always contains a reference to the buffer it was read from
#[derive(Debug)]
pub struct Transaction<'a> {
pub version: i32,
pub txs_in: Vec<TxInput<'a>>,
pub txs_out: Vec<TxOutput<'a>>,
pub lock_time: u32,
pub txs_out_idx: Vec<u32>,
raw: Buffer<'a>,
}
impl<'a> Parse<'a> for Transaction<'a> {
/// Parses the raw bytes into individual fields
/// and perform basic syntax checks
fn parse(buffer: &mut Buffer<'a>) -> Result<Transaction<'a>, EndOfBufferError> {
let org_buffer = *buffer;
let version = i32::parse(buffer)?;
let txs_in = Vec::parse(buffer)?;
let (txs_out,idxs) = buffer.parse_vec_with_indices(org_buffer)?;
let lock_time = u32::parse(buffer)?;
Ok(Transaction {
version: version,
txs_in: txs_in,
txs_out: txs_out,
txs_out_idx: idxs,
lock_time: lock_time,
raw: buffer.consumed_since(org_buffer)
})
}
}
impl<'a> ToRaw<'a> for Transaction<'a> {
fn to_raw(&self) -> &[u8] {
self.raw.inner
}
}
impl<'a> Transaction<'a> {
/// Performs basic syntax checks on the transaction
pub fn verify_syntax(&self) -> TransactionResult<()> {
if self.raw.len() > MAX_TRANSACTION_SIZE {
return Err(TransactionError::TransactionTooLarge);
}
if self.txs_in.is_empty() {
return Err(TransactionError::NoInputs);
}
if self.txs_out.is_empty() {
return Err(TransactionError::NoOutputs);
}
// No double inputs
if self.txs_in.iter().combinations(2).any(|pair|
pair[0].prev_tx_out_idx == pair[1].prev_tx_out_idx
&& pair[0].prev_tx_out == pair[1].prev_tx_out)
{
return Err(TransactionError::DuplicateInputs);
}
Ok(())
}
pub fn is_coinbase(&self) -> bool {
self.txs_in.len() == 1 && self.txs_in[0].prev_tx_out.is_null()
}
/// Reverse script validation
///
/// This checks the passed input-ptrs are valid against the corresponding output of self
///
pub fn verify_backtracking_outputs(&self, tx_store: &mut store::Transactions, inputs: &Vec<TxPtr>) {
for input_ptr in inputs.into_iter() {
debug_assert!(input_ptr.is_guard());
// read tx from disk
let tx_raw_vec = tx_store.read(*input_ptr);
let mut tx_raw = Buffer::new(tx_raw_vec.as_slice());
let tx = Transaction::parse(&mut tx_raw).
expect("Invalid tx data in database");
// find indixes
let input_index = input_ptr.get_input_index() as usize;
let ref input = tx.txs_in[input_index];
let output_index = input.prev_tx_out_idx as usize;
ffi::verify_script(self.txs_out[output_index].pk_script, tx.to_raw(), input_index as u32)
.expect("TODO: Handle script error without panic");
// TODO: verify_amount here
}
}
/// Gets the output records referenced by the inputs of this tx
///
/// Uses Record new_unmatched_input placeholder for outputs not found
pub fn get_output_records(&self, tx_index: &mut TxIndex) -> Vec<Record> {
self.txs_in.iter()
.filter(|tx_in|!tx_in.prev_tx_out.is_null())
.map(|input| {
tx_index
.get(input.prev_tx_out)
.iter()
.find(|ptr|!ptr.is_guard())
.map_or(Record::new_unmatched_input(), |ptr| Record::new_output(*ptr, input.prev_tx_out_idx))
})
.collect()
}
/// Verifies and stores the transaction in the transaction_store and index
pub fn verify_and_store(&self,
tx_index: &mut TxIndex,
tx_store: &mut store::Transactions,
initial_sync: bool,
hash: Hash32) -> TransactionResult<TransactionOk> {
let mut stats: TransactionStats = Default::default();
let p0 = Instant::now();
self.verify_syntax()?;
// store
let ptr = tx_store.write(self);
if initial_sync {
assert!(tx_index.set(hash, ptr, &[], true));
return Ok(TransactionOk::VerifiedAndStored {ptr: ptr, stats: stats })
}
let p1 = Instant::now();
stats.store_tx += p1 - p0;
self.verify_input_scripts(tx_index, tx_store, ptr, &mut stats)?;
let mut existing_ptrs = vec![];
loop {
let p2 = Instant::now();
// Store reference in the hash_index.
// This may fail if the tx is already in or if there are dependent transactions in
// that are "guarding" this one.
if tx_index.set(hash, ptr, &existing_ptrs, false) {
let p3 = Instant::now();
stats.store_tx_idx += p3 - p2;
return Ok(TransactionOk::VerifiedAndStored {ptr: ptr, stats: stats })
}
else {
let p3 = Instant::now();
stats.store_tx_idx += p3 - p2;
// First see if it already exists
existing_ptrs = tx_index.get(hash);
if existing_ptrs
.iter()
.any(|p|!p.is_guard()) {
assert_eq!(existing_ptrs.len(), 1);
return Ok(TransactionOk::AlreadyExists { ptr: existing_ptrs[0] })
}
// existing_ptrs (if any) are now inputs that are waiting for this transactions
// they need to be verified
self.verify_backtracking_outputs(tx_store, &existing_ptrs);
let p4 = Instant::now();
stats.backtracking += p4 - p3;
}
}
}
/// Finds the outputs corresponding to the inputs and verify the scripts
pub fn verify_input_scripts(&self,
tx_index: &mut TxIndex,
tx_store: &mut store::Transactions,
tx_ptr: TxPtr,
stats: &mut TransactionStats) -> TransactionResult<()> {
if self.is_coinbase() {
return Ok(())
}
for (index, input) in self.txs_in.iter().enumerate() {
let p0 = Instant::now();
let output = tx_index.get_or_set(input.prev_tx_out,
tx_ptr.to_input(index as u16 ));
let p1 = Instant::now();
stats.read_tx_idx += p1 - p0;
let output = match output {
None => {
// We can't find the transaction this input is pointing to
// Oddly, this is perfectly fine; we just postpone script validation
// until that transaction comes in.
// The spent-tree ensures that this transaction will never be connected
// before this happens
//
// ^^ get_or_set has placed appropriate guards in the hash_index
continue;
},
Some(o) => o
};
let previous_out_vec = tx_store.read_output(output, input.prev_tx_out_idx)
.ok_or(TransactionError::OutputIndexNotFound)?;
let previous_tx_out = TxOutput::parse(&mut Buffer::new(&previous_out_vec))
.expect("Corrupt output data in store");
let p2 = Instant::now();
stats.read_tx += p2 - p1;
ffi::verify_script(previous_tx_out.pk_script, self.to_raw(), index as u32)
.expect("TODO: Handle script error more gracefully");
let p3 = Instant::now();
stats.script += p3 - p2;
// TODO: verify_amount here
}
Ok(())
}
}
/// Transaction input
pub struct TxInput<'a> {
pub prev_tx_out: Hash32<'a>,
pub prev_tx_out_idx: u32,
script: &'a[u8],
sequence: u32,
}
impl<'a> Parse<'a> for TxInput<'a> {
fn parse(buffer: &mut Buffer<'a>) -> Result<TxInput<'a>, EndOfBufferError> {
Ok(TxInput {
prev_tx_out: try!(Hash32::parse(buffer)),
prev_tx_out_idx: try!(u32::parse(buffer)),
script: try!(buffer.parse_compact_size_bytes()),
sequence: try!(u32::parse(buffer))
})
}
}
#[derive(PartialEq)]
pub struct TxOutput<'a> {
value: i64,
pk_script: &'a[u8]
}
impl<'a> Parse<'a> for TxOutput<'a> {
fn parse(buffer: &mut Buffer<'a>) -> Result<TxOutput<'a>, EndOfBufferError> {
Ok(TxOutput {
value: i64::parse(buffer)?,
pk_script: buffer.parse_compact_size_bytes()?
})
}
}
impl<'a> fmt::Debug for TxInput<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(write!(fmt, "Prev-TX:{:?}, idx={:?}, seq={:?} script=",
self.prev_tx_out,
self.prev_tx_out_idx,
self.sequence));
let ctx = context::Context::new(&self.script);
write!(fmt, "{:?}", ctx)
}
}
impl<'a> fmt::Debug for TxOutput<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(write!(fmt, "v:{:?} ", self.value));
let ctx = context::Context::new(&self.pk_script);
write!(fmt, "{:?}", ctx)
}
}
#[derive(Default)]
pub struct TransactionStats {
pub merkle: Duration,
pub cloning: Duration,
pub hashing: Duration,
pub store_tx: Duration,
pub store_tx_idx: Duration,
pub backtracking: Duration,
pub read_tx: Duration,
pub read_tx_idx: Duration,
pub script: Duration
}
// Make stats additive (this could use a derive)
impl ::std::ops::Add for TransactionStats {
type Output = TransactionStats;
fn add(self, other: TransactionStats) -> TransactionStats {
TransactionStats {
merkle: self.merkle + other.merkle,
cloning: self.cloning + other.cloning,
hashing: self.hashing + other.hashing,
store_tx: self.store_tx + other.store_tx,
store_tx_idx: self.store_tx_idx + other.store_tx_idx,
backtracking: self.backtracking + other.backtracking,
read_tx: self.read_tx + other.read_tx,
read_tx_idx: self.read_tx_idx + other.read_tx_idx,
script: self.script + other.script,
}
}
}
impl ::std::iter::Sum for TransactionStats {
fn sum<I>(iter: I) -> TransactionStats
where I: Iterator<Item=TransactionStats> {
let mut r = Default::default();
for i in iter {
r = r + i;
}
r
}
}
impl ::std::fmt::Debug for TransactionStats {
fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
fn disp(d: Duration) -> u64 { d.as_secs() * 1_000_000 + d.subsec_nanos() as u64 / 1_000};
write!(fmt, "m,c,h: {},{},{} | wr:{},{} | rd:{},{} | s:{}, bt:{}",
disp(self.merkle), disp(self.cloning), disp(self.hashing),
disp(self.store_tx), disp(self.store_tx_idx),
disp(self.read_tx), disp(self.read_tx_idx),
disp(self.script), disp(self.backtracking))
}
}
/// tx-tests are external
#[cfg(test)]
mod tests {
use util::*;
use super::*;
use buffer;
use buffer::Parse;
#[test]
fn test_parse_tx() {
let tx_hex = "010000000236b01007488776b78a1e6cf59b72e2236ba378d42761eba901\
5d8bc243c7d9f0000000008a47304402206018582ef1405fbf9f08b71a2a\
b61b6a93caf713d50879573d42f87463c645b3022030e274e52bd107f604\
894d75968a47be340d633d3c38e5310fddf700ade244d501410475645fe0\
50491f9593348ba511bba43f91e02719cb604fc1f73ef57a5d8507d22b58\
20c9bf3065b1ac3543fc212b50218f7a4bf32aa664f84f336efa79660111\
ffffffff36b01007488776b78a1e6cf59b72e2236ba378d42761eba9015d\
8bc243c7d9f0010000008b4830450221009dd6581d23a64173cd5fd04c99\
dfc9b3581708c361433dfd340e7f5ea07e0eb1022042d08810307a92af6e\
f8c9ed748547f48e05b549f7bc004395b7c12879f94b2b014104607e781f\
9d685959b2009a4e35b7d2f240d8b515d59d2ddaa51b82f21ef56372f892\
39b836446bec96f5b66dee75425a38af3185610410e20655a9d333503f3b\
ffffffff0280f0fa02000000001976a914bb42487be1aae97292b5ecda5e\
66ba59d004d83088ac80f0fa02000000001976a914c3813e88eeddeba7de\
fe159bf9df3f210652571c88ac00000000";
let slice = &from_hex(tx_hex);
let mut buf = buffer::Buffer::new(slice);
let tx = Transaction::parse(&mut buf);
let _ = format!("{:?}", tx);
}
} | stats: TransactionStats
}, | random_line_split |
transaction.rs | //! Transaction parsing and verification
//!
//!
use std::fmt;
use std::time::{Instant,Duration};
use itertools::Itertools;
use buffer::*;
use hash::*;
use script::context;
use ffi;
use store;
use store::TxPtr;
use store::Record;
use store::HashIndexGuard;
use store::TxIndex;
const MAX_TRANSACTION_SIZE: usize = 1_000_000;
#[derive(Debug)]
pub enum TransactionError {
UnexpectedEndOfData,
TransactionTooLarge,
NoInputs,
NoOutputs,
DuplicateInputs,
OutputTransactionNotFound,
OutputIndexNotFound,
ScriptError(i32)
}
#[derive(Debug)]
pub enum TransactionOk {
AlreadyExists {
ptr: TxPtr
},
VerifiedAndStored {
ptr: TxPtr,
stats: TransactionStats
},
}
type TransactionResult<T> = Result<T, TransactionError>;
impl From<EndOfBufferError> for TransactionError {
fn from(_: EndOfBufferError) -> TransactionError {
TransactionError::UnexpectedEndOfData
}
}
/// A transaction represents a parsed transaction
///
/// It always contains a reference to the buffer it was read from
#[derive(Debug)]
pub struct Transaction<'a> {
pub version: i32,
pub txs_in: Vec<TxInput<'a>>,
pub txs_out: Vec<TxOutput<'a>>,
pub lock_time: u32,
pub txs_out_idx: Vec<u32>,
raw: Buffer<'a>,
}
impl<'a> Parse<'a> for Transaction<'a> {
/// Parses the raw bytes into individual fields
/// and perform basic syntax checks
fn parse(buffer: &mut Buffer<'a>) -> Result<Transaction<'a>, EndOfBufferError> {
let org_buffer = *buffer;
let version = i32::parse(buffer)?;
let txs_in = Vec::parse(buffer)?;
let (txs_out,idxs) = buffer.parse_vec_with_indices(org_buffer)?;
let lock_time = u32::parse(buffer)?;
Ok(Transaction {
version: version,
txs_in: txs_in,
txs_out: txs_out,
txs_out_idx: idxs,
lock_time: lock_time,
raw: buffer.consumed_since(org_buffer)
})
}
}
impl<'a> ToRaw<'a> for Transaction<'a> {
fn to_raw(&self) -> &[u8] {
self.raw.inner
}
}
impl<'a> Transaction<'a> {
/// Performs basic syntax checks on the transaction
pub fn verify_syntax(&self) -> TransactionResult<()> {
if self.raw.len() > MAX_TRANSACTION_SIZE {
return Err(TransactionError::TransactionTooLarge);
}
if self.txs_in.is_empty() {
return Err(TransactionError::NoInputs);
}
if self.txs_out.is_empty() {
return Err(TransactionError::NoOutputs);
}
// No double inputs
if self.txs_in.iter().combinations(2).any(|pair|
pair[0].prev_tx_out_idx == pair[1].prev_tx_out_idx
&& pair[0].prev_tx_out == pair[1].prev_tx_out)
{
return Err(TransactionError::DuplicateInputs);
}
Ok(())
}
pub fn is_coinbase(&self) -> bool {
self.txs_in.len() == 1 && self.txs_in[0].prev_tx_out.is_null()
}
/// Reverse script validation
///
/// This checks the passed input-ptrs are valid against the corresponding output of self
///
pub fn verify_backtracking_outputs(&self, tx_store: &mut store::Transactions, inputs: &Vec<TxPtr>) {
for input_ptr in inputs.into_iter() {
debug_assert!(input_ptr.is_guard());
// read tx from disk
let tx_raw_vec = tx_store.read(*input_ptr);
let mut tx_raw = Buffer::new(tx_raw_vec.as_slice());
let tx = Transaction::parse(&mut tx_raw).
expect("Invalid tx data in database");
// find indixes
let input_index = input_ptr.get_input_index() as usize;
let ref input = tx.txs_in[input_index];
let output_index = input.prev_tx_out_idx as usize;
ffi::verify_script(self.txs_out[output_index].pk_script, tx.to_raw(), input_index as u32)
.expect("TODO: Handle script error without panic");
// TODO: verify_amount here
}
}
/// Gets the output records referenced by the inputs of this tx
///
/// Uses Record new_unmatched_input placeholder for outputs not found
pub fn get_output_records(&self, tx_index: &mut TxIndex) -> Vec<Record> {
self.txs_in.iter()
.filter(|tx_in|!tx_in.prev_tx_out.is_null())
.map(|input| {
tx_index
.get(input.prev_tx_out)
.iter()
.find(|ptr|!ptr.is_guard())
.map_or(Record::new_unmatched_input(), |ptr| Record::new_output(*ptr, input.prev_tx_out_idx))
})
.collect()
}
/// Verifies and stores the transaction in the transaction_store and index
pub fn verify_and_store(&self,
tx_index: &mut TxIndex,
tx_store: &mut store::Transactions,
initial_sync: bool,
hash: Hash32) -> TransactionResult<TransactionOk> {
let mut stats: TransactionStats = Default::default();
let p0 = Instant::now();
self.verify_syntax()?;
// store
let ptr = tx_store.write(self);
if initial_sync {
assert!(tx_index.set(hash, ptr, &[], true));
return Ok(TransactionOk::VerifiedAndStored {ptr: ptr, stats: stats })
}
let p1 = Instant::now();
stats.store_tx += p1 - p0;
self.verify_input_scripts(tx_index, tx_store, ptr, &mut stats)?;
let mut existing_ptrs = vec![];
loop {
let p2 = Instant::now();
// Store reference in the hash_index.
// This may fail if the tx is already in or if there are dependent transactions in
// that are "guarding" this one.
if tx_index.set(hash, ptr, &existing_ptrs, false) {
let p3 = Instant::now();
stats.store_tx_idx += p3 - p2;
return Ok(TransactionOk::VerifiedAndStored {ptr: ptr, stats: stats })
}
else {
let p3 = Instant::now();
stats.store_tx_idx += p3 - p2;
// First see if it already exists
existing_ptrs = tx_index.get(hash);
if existing_ptrs
.iter()
.any(|p|!p.is_guard()) {
assert_eq!(existing_ptrs.len(), 1);
return Ok(TransactionOk::AlreadyExists { ptr: existing_ptrs[0] })
}
// existing_ptrs (if any) are now inputs that are waiting for this transactions
// they need to be verified
self.verify_backtracking_outputs(tx_store, &existing_ptrs);
let p4 = Instant::now();
stats.backtracking += p4 - p3;
}
}
}
/// Finds the outputs corresponding to the inputs and verify the scripts
pub fn verify_input_scripts(&self,
tx_index: &mut TxIndex,
tx_store: &mut store::Transactions,
tx_ptr: TxPtr,
stats: &mut TransactionStats) -> TransactionResult<()> {
if self.is_coinbase() {
return Ok(())
}
for (index, input) in self.txs_in.iter().enumerate() {
let p0 = Instant::now();
let output = tx_index.get_or_set(input.prev_tx_out,
tx_ptr.to_input(index as u16 ));
let p1 = Instant::now();
stats.read_tx_idx += p1 - p0;
let output = match output {
None => {
// We can't find the transaction this input is pointing to
// Oddly, this is perfectly fine; we just postpone script validation
// until that transaction comes in.
// The spent-tree ensures that this transaction will never be connected
// before this happens
//
// ^^ get_or_set has placed appropriate guards in the hash_index
continue;
},
Some(o) => o
};
let previous_out_vec = tx_store.read_output(output, input.prev_tx_out_idx)
.ok_or(TransactionError::OutputIndexNotFound)?;
let previous_tx_out = TxOutput::parse(&mut Buffer::new(&previous_out_vec))
.expect("Corrupt output data in store");
let p2 = Instant::now();
stats.read_tx += p2 - p1;
ffi::verify_script(previous_tx_out.pk_script, self.to_raw(), index as u32)
.expect("TODO: Handle script error more gracefully");
let p3 = Instant::now();
stats.script += p3 - p2;
// TODO: verify_amount here
}
Ok(())
}
}
/// Transaction input
pub struct TxInput<'a> {
pub prev_tx_out: Hash32<'a>,
pub prev_tx_out_idx: u32,
script: &'a[u8],
sequence: u32,
}
impl<'a> Parse<'a> for TxInput<'a> {
fn parse(buffer: &mut Buffer<'a>) -> Result<TxInput<'a>, EndOfBufferError> {
Ok(TxInput {
prev_tx_out: try!(Hash32::parse(buffer)),
prev_tx_out_idx: try!(u32::parse(buffer)),
script: try!(buffer.parse_compact_size_bytes()),
sequence: try!(u32::parse(buffer))
})
}
}
#[derive(PartialEq)]
pub struct TxOutput<'a> {
value: i64,
pk_script: &'a[u8]
}
impl<'a> Parse<'a> for TxOutput<'a> {
fn parse(buffer: &mut Buffer<'a>) -> Result<TxOutput<'a>, EndOfBufferError> {
Ok(TxOutput {
value: i64::parse(buffer)?,
pk_script: buffer.parse_compact_size_bytes()?
})
}
}
impl<'a> fmt::Debug for TxInput<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(write!(fmt, "Prev-TX:{:?}, idx={:?}, seq={:?} script=",
self.prev_tx_out,
self.prev_tx_out_idx,
self.sequence));
let ctx = context::Context::new(&self.script);
write!(fmt, "{:?}", ctx)
}
}
impl<'a> fmt::Debug for TxOutput<'a> {
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
try!(write!(fmt, "v:{:?} ", self.value));
let ctx = context::Context::new(&self.pk_script);
write!(fmt, "{:?}", ctx)
}
}
#[derive(Default)]
pub struct TransactionStats {
pub merkle: Duration,
pub cloning: Duration,
pub hashing: Duration,
pub store_tx: Duration,
pub store_tx_idx: Duration,
pub backtracking: Duration,
pub read_tx: Duration,
pub read_tx_idx: Duration,
pub script: Duration
}
// Make stats additive (this could use a derive)
impl ::std::ops::Add for TransactionStats {
type Output = TransactionStats;
fn add(self, other: TransactionStats) -> TransactionStats {
TransactionStats {
merkle: self.merkle + other.merkle,
cloning: self.cloning + other.cloning,
hashing: self.hashing + other.hashing,
store_tx: self.store_tx + other.store_tx,
store_tx_idx: self.store_tx_idx + other.store_tx_idx,
backtracking: self.backtracking + other.backtracking,
read_tx: self.read_tx + other.read_tx,
read_tx_idx: self.read_tx_idx + other.read_tx_idx,
script: self.script + other.script,
}
}
}
impl ::std::iter::Sum for TransactionStats {
fn sum<I>(iter: I) -> TransactionStats
where I: Iterator<Item=TransactionStats> {
let mut r = Default::default();
for i in iter {
r = r + i;
}
r
}
}
impl ::std::fmt::Debug for TransactionStats {
fn | (&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> {
fn disp(d: Duration) -> u64 { d.as_secs() * 1_000_000 + d.subsec_nanos() as u64 / 1_000};
write!(fmt, "m,c,h: {},{},{} | wr:{},{} | rd:{},{} | s:{}, bt:{}",
disp(self.merkle), disp(self.cloning), disp(self.hashing),
disp(self.store_tx), disp(self.store_tx_idx),
disp(self.read_tx), disp(self.read_tx_idx),
disp(self.script), disp(self.backtracking))
}
}
/// tx-tests are external
#[cfg(test)]
mod tests {
use util::*;
use super::*;
use buffer;
use buffer::Parse;
#[test]
fn test_parse_tx() {
let tx_hex = "010000000236b01007488776b78a1e6cf59b72e2236ba378d42761eba901\
5d8bc243c7d9f0000000008a47304402206018582ef1405fbf9f08b71a2a\
b61b6a93caf713d50879573d42f87463c645b3022030e274e52bd107f604\
894d75968a47be340d633d3c38e5310fddf700ade244d501410475645fe0\
50491f9593348ba511bba43f91e02719cb604fc1f73ef57a5d8507d22b58\
20c9bf3065b1ac3543fc212b50218f7a4bf32aa664f84f336efa79660111\
ffffffff36b01007488776b78a1e6cf59b72e2236ba378d42761eba9015d\
8bc243c7d9f0010000008b4830450221009dd6581d23a64173cd5fd04c99\
dfc9b3581708c361433dfd340e7f5ea07e0eb1022042d08810307a92af6e\
f8c9ed748547f48e05b549f7bc004395b7c12879f94b2b014104607e781f\
9d685959b2009a4e35b7d2f240d8b515d59d2ddaa51b82f21ef56372f892\
39b836446bec96f5b66dee75425a38af3185610410e20655a9d333503f3b\
ffffffff0280f0fa02000000001976a914bb42487be1aae97292b5ecda5e\
66ba59d004d83088ac80f0fa02000000001976a914c3813e88eeddeba7de\
fe159bf9df3f210652571c88ac00000000";
let slice = &from_hex(tx_hex);
let mut buf = buffer::Buffer::new(slice);
let tx = Transaction::parse(&mut buf);
let _ = format!("{:?}", tx);
}
}
| fmt | identifier_name |
lib.rs | //! # urlshortener
//!
//! An easy library for retrieving short urls.
//!
//! ## Usage
//!
//! Creating a short URL via a specified provider is very simple:
//!
//! ```rust,no_run
//! use urlshortener::{providers::Provider, client::UrlShortener};
//!
//! let us = UrlShortener::new().unwrap();
//! let short_url = us.generate("https://my-long-url.com", &Provider::IsGd);
//! assert!(short_url.is_ok());
//! ```
//!
//! Or attempting all URL shorteners until one is successfully generated:
//!
//! ```rust,no_run
//! use urlshortener::client::UrlShortener;
//!
//! let us = UrlShortener::new().unwrap();
//! let short_url = us.try_generate("https://my-long-url.com", None);
//! assert!(short_url.is_ok());
//! ```
//! In order to use service with authentication use the appropriate provider directly:
//!
//! ```rust,no_run
//! use urlshortener::{ client::UrlShortener, providers::Provider };
//! | //! assert!(short_url.is_ok());
//! ```
#![deny(missing_docs)]
#![deny(warnings)]
/// A urlshortener http client for performing requests.
#[cfg(feature = "client")]
pub mod client;
pub mod providers;
/// A request builders for sending via http client.
pub mod request;
/// A prelude module with main useful stuff.
pub mod prelude {
#[cfg(feature = "client")]
pub use crate::client::*;
pub use crate::providers::{Provider, PROVIDERS};
} | //! let us = UrlShortener::new().unwrap();
//! let key = "MY_API_KEY";
//! let short_url = us.generate("https://my-long-url.com", &Provider::GooGl { api_key:
//! key.to_owned() }); | random_line_split |
hash_index.rs |
//! Index that maps hashes to content pointers
//!
//! This is used for transactions & blockheaders; the values found for a hash can be:
//!
//! * a single fileptr pointing to a transaction
//! The transaction can be found at the ptr in block_content and is fully validated
//!
//! * a set of fileptr pointing to inputs
//! Transaction cannot be found, but these inputs need this transaction
//! and are already assumed to be valid. The transaction may not be inserted before these
//! scripts are checked
//!
//! * a single fileptr pointing to a pointer to blockheader
//! The block is found. The pointer points to a record in the spend-tree; _that_ pointer points to the blockheader
//! in block_content
//!
//! * a set of fileptr pointing to guard blocks
//! The block cannot be found, but the blocks pointed to by these ptrs are having the given hash as previous block;
//! they are "expecting" this block, and should be appended when this block comes in
//!
//! The implementation is a large root hash table, with colliding keys added to an unbalanced binary tree.
//!
//! TODO There is probably quite some gain to be made by moving to HAMT instead unbalanced binary trees
//! for the branches; especially for low-resource uses.
use std::{mem};
use std::sync::atomic;
use std::cmp::{Ord,Ordering};
use config;
use hash::*;
use store::FlatFilePtr;
use store::flatfileset::FlatFileSet;
const FILE_SIZE: u64 = 1 * 1024*1024*1024;
const MAX_CONTENT_SIZE: u64 = FILE_SIZE - 10 * 1024*1024;
const HASH_ROOT_COUNT: usize = 256*256*256;
/// Trait for objects that can be used as a guard
/// This is required for types that are stored in the hash-index
pub trait HashIndexGuard {
fn is_guard(self) -> bool;
}
/// Index to lookup fileptr's from hashes
///
/// Internally uses fileset
pub struct HashIndex<T : HashIndexGuard + Copy + Clone> {
fileset: FlatFileSet<IndexPtr>,
hash_index_root: &'static [IndexPtr; HASH_ROOT_COUNT],
phantom: ::std::marker::PhantomData<T>
}
impl<T : HashIndexGuard + Copy + Clone> Clone for HashIndex<T> {
// Explicit cloning can be used to allow concurrent access.
fn clone(&self) -> HashIndex<T> {
let mut fileset = self.fileset.clone();
let root = fileset.read_fixed(IndexPtr::new(0, super::flatfile::INITIAL_WRITEPOS));
HashIndex {
fileset: fileset,
hash_index_root: root,
phantom: ::std::marker::PhantomData
}
}
}
/// A persistent pointer into the hash-index
#[derive(Debug, Clone, Copy)]
pub struct IndexPtr {
file_offset: u32,
file_number: i16,
zero: u16
}
impl FlatFilePtr for IndexPtr {
fn new(file_number: i16, file_offset: u64) -> Self {
IndexPtr {
file_offset: file_offset as u32,
file_number: file_number,
zero: 0 // we must pad with zero to ensure atomic CAS works
}
}
fn get_file_offset(self) -> u64 { self.file_offset as u64 }
fn get_file_number(self) -> i16 { self.file_number }
}
impl IndexPtr {
pub fn null() -> Self { IndexPtr::new(0, 0) }
pub fn is_null(&self) -> bool { self.file_offset == 0 && self.file_number == 0 }
/// atomically replaces a hash indexptr value with a new_value,
/// fails if the current value is no longer the value supplied
pub fn atomic_replace(&self, current_value: IndexPtr, new_value: IndexPtr) -> bool {
let atomic_self: *mut atomic::AtomicU64 = unsafe { mem::transmute( self ) };
let prev = unsafe {
(*atomic_self).compare_and_swap(
mem::transmute(current_value),
mem::transmute(new_value),
atomic::Ordering::Relaxed)
};
prev == unsafe { mem::transmute(current_value) }
}
}
/// The result used internally when searched for hash
enum FindNodeResult {
/// Tha hash is found and the location is returned
Found(&'static Node),
/// The hash is not found; the location where the node should be inserted
/// is returned
NotFound(&'static IndexPtr)
}
/// Structures as stored in the fileset
#[derive(Debug)]
struct Node {
hash: Hash32Buf,
prev: IndexPtr, // to Node
next: IndexPtr, // to Node
leaf: IndexPtr, // to Leaf
}
/// Leaf of the binary tree
/// The supplied Type is the type of the elements that are stored in the tree
struct Leaf<T : HashIndexGuard> {
value: T, /// to Data file
next: IndexPtr, // to Leaf
}
impl<T : HashIndexGuard> Leaf<T> {
fn new(value: T) -> Self |
}
impl Node {
fn new(hash: Hash32, leaf_ptr: IndexPtr) -> Self {
Node {
hash: hash.as_buf(),
prev: IndexPtr::null(),
next: IndexPtr::null(),
leaf: leaf_ptr
}
}
}
// Returns the first 24-bits of the hash
//
// This is the index into the root-hash table
fn hash_to_index(hash: Hash32) -> usize {
(hash.0[0] as usize) |
(hash.0[1] as usize) << 8 |
(hash.0[2] as usize) << 16
}
impl<T :'static> HashIndex<T>
where T : HashIndexGuard + PartialEq + Copy + Clone
{
/// Opens the hash_index at the location given in the config
///
/// Creates a new fileset if needed
pub fn new(cfg: &config::Config, dir: &str) -> HashIndex<T> {
let dir = &cfg.root.clone().join(dir);
let is_new =!dir.exists();
let mut fileset = FlatFileSet::new(
dir, "hi-", FILE_SIZE, MAX_CONTENT_SIZE);
let hash_root_fileptr = if is_new {
// allocate space for root hash table
fileset.alloc_write_space(mem::size_of::<[IndexPtr; HASH_ROOT_COUNT]>() as u64)
}
else {
// hash root must have been the first thing written
IndexPtr::new(0, super::flatfile::INITIAL_WRITEPOS)
};
// and keep a reference to it
let hash_root_ref: &'static [IndexPtr; HASH_ROOT_COUNT]
= fileset.read_fixed(hash_root_fileptr);
HashIndex {
fileset: fileset,
hash_index_root: hash_root_ref,
phantom: ::std::marker::PhantomData
}
}
/// Collects all the values stored at the given node
fn collect_node_values(&mut self, node: &Node) -> Vec<T> {
let mut result : Vec<T> = Vec::new();
let mut leaf_ptr = node.leaf;
while!leaf_ptr.is_null() {
let v: &T = self.fileset.read_fixed(leaf_ptr);
let leaf: Leaf<T> = Leaf::new(*v);
result.push(leaf.value);
leaf_ptr = leaf.next;
}
result
}
// Finds the node containing the hash, or the location the hash should be inserted
fn find_node(&mut self, hash: Hash32) -> FindNodeResult {
// use the first 24-bit as index in the root hash table
let mut ptr = &self.hash_index_root[hash_to_index(hash)];
// from there, we follow the binary tree
while!ptr.is_null() {
let node: &Node = self.fileset.read_fixed(*ptr);
ptr = match hash.0.cmp(&node.hash.as_ref().0) {
Ordering::Less => &node.prev,
Ordering::Greater => &node.next,
Ordering::Equal => return FindNodeResult::Found(node)
};
}
FindNodeResult::NotFound(ptr)
}
/// Retrieves the fileptr'` of the given hash
pub fn get(&mut self, hash: Hash32) -> Vec<T> {
match self.find_node(hash) {
FindNodeResult::NotFound(_) => {
Vec::new()
},
FindNodeResult::Found(node) => {
self.collect_node_values(node)
}
}
}
/// Stores a T at the given hash
///
/// This will bail out atomically (do a noop) if there are existing Ts stored at the hash,
/// that are not among the passed `verified_ptrs`.
///
/// This way, inputs stores at a hash serve as guards that need to be verified before
/// the transaction can be stored.
///
/// The force_store flag can be used to overrule this behaviour and store anyway
///
/// Similarly, blockheader_guards need to be connected before a block can be stored
pub fn set(&mut self, hash: Hash32, store_ptr: T, verified_ptrs: &[T], force_store: bool) -> bool {
assert!(! store_ptr.is_guard());
assert!(verified_ptrs.iter().all(|p| p.is_guard()));
// this loops through retries when the CAS operation fails
loop {
match self.find_node(hash) {
FindNodeResult::NotFound(target) => {
// create and write a leaf;
let new_leaf = Leaf::new(store_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// create and write a node holding the leaf
let new_node = Node::new(hash, new_leaf_ptr);
let new_node_ptr = self.fileset.write_fixed(&new_node);
// then atomically update the pointer
if target.atomic_replace(IndexPtr::null(), new_node_ptr) {
return true;
}
},
FindNodeResult::Found(node) => {
let first_value_ptr = node.leaf;
// check if there is anything waiting that is not supplied in `verified_ptrs`
if!force_store &&
!self
.collect_node_values(node)
.into_iter()
.any(|val| verified_ptrs.contains(&val)) {
return false;
}
// We don't need to keep the verified-ptrs
// Replace all with a new leaf
let new_leaf = Leaf::new(store_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// then atomically update the pointer
if node.leaf.atomic_replace(first_value_ptr, new_leaf_ptr) {
return true;
}
}
};
}
}
/// Retrieves the fileptr
///
/// If there is no primary ptr (block/tx) for the given hash
/// the given guard_ptr is added atomically to block further adds
pub fn get_or_set(&mut self, hash: Hash32, guard_ptr: T) -> Option<T> {
debug_assert!(guard_ptr.is_guard());
// this loops through retries when the CAS operation fails
loop {
match self.find_node(hash) {
FindNodeResult::NotFound(ptr) => {
// The transaction doesn't exist; we insert guard_ptr instead
// create and write a leaf;
let new_leaf = Leaf::new(guard_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// create and write a node holding the leaf
let new_node = Node::new(hash, new_leaf_ptr);
let new_node_ptr = self.fileset.write_fixed(&new_node);
// then atomically update the pointer
if ptr.atomic_replace(IndexPtr::null(), new_node_ptr) {
return None;
}
},
FindNodeResult::Found(node) => {
// load first leaf
let first_value_ptr = node.leaf;
let val: &T = self.fileset.read_fixed(first_value_ptr);
let leaf: Leaf<T> = Leaf::new(*val);
if!leaf.value.is_guard() {
return Some(leaf.value);
}
// create a new leaf, pointing to the previous one
let new_leaf = Leaf { value: guard_ptr, next: node.leaf };
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// then atomically update the pointer
if node.leaf.atomic_replace(first_value_ptr, new_leaf_ptr) {
return None;
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::Node;
use std::mem;
extern crate tempdir;
extern crate rand;
use std::path::PathBuf;
use std::thread;
use super::*;
use self::rand::Rng;
use config;
use hash::Hash32Buf;
use store::TxPtr;
use store::flatfileset::FlatFilePtr;
#[test]
fn test_size_of_node() {
assert_eq!(mem::size_of::<Node>(), 56);
}
#[test]
fn test_seq() {
const DATA_SIZE: u32 = 100000;
const THREADS: usize = 100;
const LOOPS: usize = 500;
let dir = tempdir::TempDir::new("test1").unwrap();
let path = PathBuf::from(dir.path());
let cfg = config::Config { root: path.clone() };
let _idx: HashIndex<TxPtr> = HashIndex::new(& cfg, "test" );
// We create a little transaction world:
// The "transactions" are file pointers 1 to DATA_SIZE
// Function to hash them:
fn hash(n: usize) -> Hash32Buf {
let s = format!("{}",n);
Hash32Buf::double_sha256(s.into_bytes().as_ref())
}
let handles: Vec<_> = (0..THREADS).map(|_| {
let path = path.clone();
thread::spawn( move | | {
let mut rng = rand::thread_rng();
let cfg = config::Config { root: path };
let mut idx = HashIndex::new(&cfg, "test");
for _ in 0..LOOPS {
let tx = TxPtr::new(0, rng.gen_range(10, DATA_SIZE) as u64);
let tx_hash = hash(tx.get_file_offset() as usize);
let found_txs = idx.get(tx_hash.as_ref());
if!found_txs.is_empty() {
// check that x is either a tx or a set of inputs
if found_txs.clone().into_iter().all(|tx: TxPtr|!tx.is_guard() ) && found_txs.len() == 1 {
assert_eq!(found_txs[0].get_file_offset(), tx.get_file_offset());
continue;
}
if found_txs.clone().into_iter().all(|tx| tx.is_guard() ) {
continue;
}
panic!("Expected only 1 tx or 1..n inputs");
}
else {
if tx.get_file_offset() > 2 {
// some messy ops for messy tests
let output_tx1_ptr = TxPtr::new(0, tx.get_file_offset() -1);
let output_hash = hash(output_tx1_ptr.get_file_offset() as usize);
let input_ptr = TxPtr::new(0, tx.get_file_offset()).to_input(1);
let output_tx1 = idx.get_or_set(output_hash.as_ref(), input_ptr);
if let Some(x) = output_tx1 {
assert_eq!(!x.is_guard(), true);
// script validation goes here
}
idx.set(tx_hash.as_ref(), tx, &[input_ptr], false);
}
else {
idx.set(tx_hash.as_ref(), tx, &[], false);
}
}
}
})
}).collect();
for h in handles {
h.join().unwrap();
}
}
} | {
Leaf {
value: value,
next: IndexPtr::null()
}
} | identifier_body |
hash_index.rs |
//! Index that maps hashes to content pointers
//!
//! This is used for transactions & blockheaders; the values found for a hash can be:
//!
//! * a single fileptr pointing to a transaction
//! The transaction can be found at the ptr in block_content and is fully validated
//!
//! * a set of fileptr pointing to inputs
//! Transaction cannot be found, but these inputs need this transaction
//! and are already assumed to be valid. The transaction may not be inserted before these
//! scripts are checked
//!
//! * a single fileptr pointing to a pointer to blockheader
//! The block is found. The pointer points to a record in the spend-tree; _that_ pointer points to the blockheader
//! in block_content
//!
//! * a set of fileptr pointing to guard blocks
//! The block cannot be found, but the blocks pointed to by these ptrs are having the given hash as previous block;
//! they are "expecting" this block, and should be appended when this block comes in
//!
//! The implementation is a large root hash table, with colliding keys added to an unbalanced binary tree.
//!
//! TODO There is probably quite some gain to be made by moving to HAMT instead unbalanced binary trees
//! for the branches; especially for low-resource uses.
use std::{mem};
use std::sync::atomic;
use std::cmp::{Ord,Ordering};
use config;
use hash::*;
use store::FlatFilePtr;
use store::flatfileset::FlatFileSet;
const FILE_SIZE: u64 = 1 * 1024*1024*1024;
const MAX_CONTENT_SIZE: u64 = FILE_SIZE - 10 * 1024*1024;
const HASH_ROOT_COUNT: usize = 256*256*256;
/// Trait for objects that can be used as a guard
/// This is required for types that are stored in the hash-index
pub trait HashIndexGuard {
fn is_guard(self) -> bool;
}
/// Index to lookup fileptr's from hashes
///
/// Internally uses fileset
pub struct HashIndex<T : HashIndexGuard + Copy + Clone> {
fileset: FlatFileSet<IndexPtr>,
hash_index_root: &'static [IndexPtr; HASH_ROOT_COUNT],
phantom: ::std::marker::PhantomData<T>
}
impl<T : HashIndexGuard + Copy + Clone> Clone for HashIndex<T> {
// Explicit cloning can be used to allow concurrent access.
fn clone(&self) -> HashIndex<T> {
let mut fileset = self.fileset.clone();
let root = fileset.read_fixed(IndexPtr::new(0, super::flatfile::INITIAL_WRITEPOS));
HashIndex {
fileset: fileset,
hash_index_root: root,
phantom: ::std::marker::PhantomData
}
}
}
/// A persistent pointer into the hash-index
#[derive(Debug, Clone, Copy)]
pub struct IndexPtr {
file_offset: u32,
file_number: i16,
zero: u16
}
impl FlatFilePtr for IndexPtr {
fn new(file_number: i16, file_offset: u64) -> Self {
IndexPtr {
file_offset: file_offset as u32,
file_number: file_number,
zero: 0 // we must pad with zero to ensure atomic CAS works
}
}
fn get_file_offset(self) -> u64 { self.file_offset as u64 }
fn get_file_number(self) -> i16 { self.file_number }
}
impl IndexPtr {
pub fn null() -> Self { IndexPtr::new(0, 0) }
pub fn is_null(&self) -> bool { self.file_offset == 0 && self.file_number == 0 }
/// atomically replaces a hash indexptr value with a new_value,
/// fails if the current value is no longer the value supplied
pub fn atomic_replace(&self, current_value: IndexPtr, new_value: IndexPtr) -> bool {
let atomic_self: *mut atomic::AtomicU64 = unsafe { mem::transmute( self ) };
let prev = unsafe {
(*atomic_self).compare_and_swap(
mem::transmute(current_value),
mem::transmute(new_value),
atomic::Ordering::Relaxed)
};
prev == unsafe { mem::transmute(current_value) }
}
}
/// The result used internally when searched for hash
enum FindNodeResult {
/// Tha hash is found and the location is returned
Found(&'static Node),
/// The hash is not found; the location where the node should be inserted
/// is returned
NotFound(&'static IndexPtr)
}
/// Structures as stored in the fileset
#[derive(Debug)]
struct Node {
hash: Hash32Buf,
prev: IndexPtr, // to Node
next: IndexPtr, // to Node
leaf: IndexPtr, // to Leaf
}
/// Leaf of the binary tree
/// The supplied Type is the type of the elements that are stored in the tree
struct Leaf<T : HashIndexGuard> {
value: T, /// to Data file
next: IndexPtr, // to Leaf
}
impl<T : HashIndexGuard> Leaf<T> {
fn new(value: T) -> Self {
Leaf {
value: value,
next: IndexPtr::null()
}
}
}
impl Node {
fn new(hash: Hash32, leaf_ptr: IndexPtr) -> Self {
Node {
hash: hash.as_buf(),
prev: IndexPtr::null(),
next: IndexPtr::null(),
leaf: leaf_ptr
}
}
}
// Returns the first 24-bits of the hash
//
// This is the index into the root-hash table
fn hash_to_index(hash: Hash32) -> usize {
(hash.0[0] as usize) |
(hash.0[1] as usize) << 8 |
(hash.0[2] as usize) << 16
}
impl<T :'static> HashIndex<T>
where T : HashIndexGuard + PartialEq + Copy + Clone
{
/// Opens the hash_index at the location given in the config
///
/// Creates a new fileset if needed
pub fn new(cfg: &config::Config, dir: &str) -> HashIndex<T> {
let dir = &cfg.root.clone().join(dir);
let is_new =!dir.exists();
let mut fileset = FlatFileSet::new(
dir, "hi-", FILE_SIZE, MAX_CONTENT_SIZE);
let hash_root_fileptr = if is_new {
// allocate space for root hash table
fileset.alloc_write_space(mem::size_of::<[IndexPtr; HASH_ROOT_COUNT]>() as u64)
}
else {
// hash root must have been the first thing written
IndexPtr::new(0, super::flatfile::INITIAL_WRITEPOS)
};
// and keep a reference to it
let hash_root_ref: &'static [IndexPtr; HASH_ROOT_COUNT]
= fileset.read_fixed(hash_root_fileptr);
HashIndex {
fileset: fileset,
hash_index_root: hash_root_ref,
phantom: ::std::marker::PhantomData
}
}
/// Collects all the values stored at the given node
fn collect_node_values(&mut self, node: &Node) -> Vec<T> {
let mut result : Vec<T> = Vec::new();
let mut leaf_ptr = node.leaf;
while!leaf_ptr.is_null() {
let v: &T = self.fileset.read_fixed(leaf_ptr);
let leaf: Leaf<T> = Leaf::new(*v);
result.push(leaf.value);
leaf_ptr = leaf.next;
}
result
}
// Finds the node containing the hash, or the location the hash should be inserted
fn | (&mut self, hash: Hash32) -> FindNodeResult {
// use the first 24-bit as index in the root hash table
let mut ptr = &self.hash_index_root[hash_to_index(hash)];
// from there, we follow the binary tree
while!ptr.is_null() {
let node: &Node = self.fileset.read_fixed(*ptr);
ptr = match hash.0.cmp(&node.hash.as_ref().0) {
Ordering::Less => &node.prev,
Ordering::Greater => &node.next,
Ordering::Equal => return FindNodeResult::Found(node)
};
}
FindNodeResult::NotFound(ptr)
}
/// Retrieves the fileptr'` of the given hash
pub fn get(&mut self, hash: Hash32) -> Vec<T> {
match self.find_node(hash) {
FindNodeResult::NotFound(_) => {
Vec::new()
},
FindNodeResult::Found(node) => {
self.collect_node_values(node)
}
}
}
/// Stores a T at the given hash
///
/// This will bail out atomically (do a noop) if there are existing Ts stored at the hash,
/// that are not among the passed `verified_ptrs`.
///
/// This way, inputs stores at a hash serve as guards that need to be verified before
/// the transaction can be stored.
///
/// The force_store flag can be used to overrule this behaviour and store anyway
///
/// Similarly, blockheader_guards need to be connected before a block can be stored
pub fn set(&mut self, hash: Hash32, store_ptr: T, verified_ptrs: &[T], force_store: bool) -> bool {
assert!(! store_ptr.is_guard());
assert!(verified_ptrs.iter().all(|p| p.is_guard()));
// this loops through retries when the CAS operation fails
loop {
match self.find_node(hash) {
FindNodeResult::NotFound(target) => {
// create and write a leaf;
let new_leaf = Leaf::new(store_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// create and write a node holding the leaf
let new_node = Node::new(hash, new_leaf_ptr);
let new_node_ptr = self.fileset.write_fixed(&new_node);
// then atomically update the pointer
if target.atomic_replace(IndexPtr::null(), new_node_ptr) {
return true;
}
},
FindNodeResult::Found(node) => {
let first_value_ptr = node.leaf;
// check if there is anything waiting that is not supplied in `verified_ptrs`
if!force_store &&
!self
.collect_node_values(node)
.into_iter()
.any(|val| verified_ptrs.contains(&val)) {
return false;
}
// We don't need to keep the verified-ptrs
// Replace all with a new leaf
let new_leaf = Leaf::new(store_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// then atomically update the pointer
if node.leaf.atomic_replace(first_value_ptr, new_leaf_ptr) {
return true;
}
}
};
}
}
/// Retrieves the fileptr
///
/// If there is no primary ptr (block/tx) for the given hash
/// the given guard_ptr is added atomically to block further adds
pub fn get_or_set(&mut self, hash: Hash32, guard_ptr: T) -> Option<T> {
debug_assert!(guard_ptr.is_guard());
// this loops through retries when the CAS operation fails
loop {
match self.find_node(hash) {
FindNodeResult::NotFound(ptr) => {
// The transaction doesn't exist; we insert guard_ptr instead
// create and write a leaf;
let new_leaf = Leaf::new(guard_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// create and write a node holding the leaf
let new_node = Node::new(hash, new_leaf_ptr);
let new_node_ptr = self.fileset.write_fixed(&new_node);
// then atomically update the pointer
if ptr.atomic_replace(IndexPtr::null(), new_node_ptr) {
return None;
}
},
FindNodeResult::Found(node) => {
// load first leaf
let first_value_ptr = node.leaf;
let val: &T = self.fileset.read_fixed(first_value_ptr);
let leaf: Leaf<T> = Leaf::new(*val);
if!leaf.value.is_guard() {
return Some(leaf.value);
}
// create a new leaf, pointing to the previous one
let new_leaf = Leaf { value: guard_ptr, next: node.leaf };
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// then atomically update the pointer
if node.leaf.atomic_replace(first_value_ptr, new_leaf_ptr) {
return None;
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::Node;
use std::mem;
extern crate tempdir;
extern crate rand;
use std::path::PathBuf;
use std::thread;
use super::*;
use self::rand::Rng;
use config;
use hash::Hash32Buf;
use store::TxPtr;
use store::flatfileset::FlatFilePtr;
#[test]
fn test_size_of_node() {
assert_eq!(mem::size_of::<Node>(), 56);
}
#[test]
fn test_seq() {
const DATA_SIZE: u32 = 100000;
const THREADS: usize = 100;
const LOOPS: usize = 500;
let dir = tempdir::TempDir::new("test1").unwrap();
let path = PathBuf::from(dir.path());
let cfg = config::Config { root: path.clone() };
let _idx: HashIndex<TxPtr> = HashIndex::new(& cfg, "test" );
// We create a little transaction world:
// The "transactions" are file pointers 1 to DATA_SIZE
// Function to hash them:
fn hash(n: usize) -> Hash32Buf {
let s = format!("{}",n);
Hash32Buf::double_sha256(s.into_bytes().as_ref())
}
let handles: Vec<_> = (0..THREADS).map(|_| {
let path = path.clone();
thread::spawn( move | | {
let mut rng = rand::thread_rng();
let cfg = config::Config { root: path };
let mut idx = HashIndex::new(&cfg, "test");
for _ in 0..LOOPS {
let tx = TxPtr::new(0, rng.gen_range(10, DATA_SIZE) as u64);
let tx_hash = hash(tx.get_file_offset() as usize);
let found_txs = idx.get(tx_hash.as_ref());
if!found_txs.is_empty() {
// check that x is either a tx or a set of inputs
if found_txs.clone().into_iter().all(|tx: TxPtr|!tx.is_guard() ) && found_txs.len() == 1 {
assert_eq!(found_txs[0].get_file_offset(), tx.get_file_offset());
continue;
}
if found_txs.clone().into_iter().all(|tx| tx.is_guard() ) {
continue;
}
panic!("Expected only 1 tx or 1..n inputs");
}
else {
if tx.get_file_offset() > 2 {
// some messy ops for messy tests
let output_tx1_ptr = TxPtr::new(0, tx.get_file_offset() -1);
let output_hash = hash(output_tx1_ptr.get_file_offset() as usize);
let input_ptr = TxPtr::new(0, tx.get_file_offset()).to_input(1);
let output_tx1 = idx.get_or_set(output_hash.as_ref(), input_ptr);
if let Some(x) = output_tx1 {
assert_eq!(!x.is_guard(), true);
// script validation goes here
}
idx.set(tx_hash.as_ref(), tx, &[input_ptr], false);
}
else {
idx.set(tx_hash.as_ref(), tx, &[], false);
}
}
}
})
}).collect();
for h in handles {
h.join().unwrap();
}
}
} | find_node | identifier_name |
hash_index.rs |
//! Index that maps hashes to content pointers
//!
//! This is used for transactions & blockheaders; the values found for a hash can be:
//!
//! * a single fileptr pointing to a transaction
//! The transaction can be found at the ptr in block_content and is fully validated
//!
//! * a set of fileptr pointing to inputs
//! Transaction cannot be found, but these inputs need this transaction
//! and are already assumed to be valid. The transaction may not be inserted before these
//! scripts are checked
//!
//! * a single fileptr pointing to a pointer to blockheader
//! The block is found. The pointer points to a record in the spend-tree; _that_ pointer points to the blockheader
//! in block_content
//!
//! * a set of fileptr pointing to guard blocks
//! The block cannot be found, but the blocks pointed to by these ptrs are having the given hash as previous block;
//! they are "expecting" this block, and should be appended when this block comes in
//!
//! The implementation is a large root hash table, with colliding keys added to an unbalanced binary tree.
//!
//! TODO There is probably quite some gain to be made by moving to HAMT instead unbalanced binary trees
//! for the branches; especially for low-resource uses.
use std::{mem};
use std::sync::atomic;
use std::cmp::{Ord,Ordering};
use config;
use hash::*;
use store::FlatFilePtr;
use store::flatfileset::FlatFileSet;
const FILE_SIZE: u64 = 1 * 1024*1024*1024;
const MAX_CONTENT_SIZE: u64 = FILE_SIZE - 10 * 1024*1024;
const HASH_ROOT_COUNT: usize = 256*256*256;
/// Trait for objects that can be used as a guard
/// This is required for types that are stored in the hash-index
pub trait HashIndexGuard {
fn is_guard(self) -> bool;
}
/// Index to lookup fileptr's from hashes
///
/// Internally uses fileset
pub struct HashIndex<T : HashIndexGuard + Copy + Clone> {
fileset: FlatFileSet<IndexPtr>,
hash_index_root: &'static [IndexPtr; HASH_ROOT_COUNT],
phantom: ::std::marker::PhantomData<T>
}
impl<T : HashIndexGuard + Copy + Clone> Clone for HashIndex<T> {
// Explicit cloning can be used to allow concurrent access.
fn clone(&self) -> HashIndex<T> {
let mut fileset = self.fileset.clone();
let root = fileset.read_fixed(IndexPtr::new(0, super::flatfile::INITIAL_WRITEPOS));
HashIndex {
fileset: fileset,
hash_index_root: root,
phantom: ::std::marker::PhantomData
}
}
}
/// A persistent pointer into the hash-index
#[derive(Debug, Clone, Copy)]
pub struct IndexPtr {
file_offset: u32,
file_number: i16,
zero: u16
}
impl FlatFilePtr for IndexPtr {
fn new(file_number: i16, file_offset: u64) -> Self {
IndexPtr {
file_offset: file_offset as u32,
file_number: file_number,
zero: 0 // we must pad with zero to ensure atomic CAS works
}
}
fn get_file_offset(self) -> u64 { self.file_offset as u64 }
fn get_file_number(self) -> i16 { self.file_number }
}
impl IndexPtr {
pub fn null() -> Self { IndexPtr::new(0, 0) }
pub fn is_null(&self) -> bool { self.file_offset == 0 && self.file_number == 0 }
/// atomically replaces a hash indexptr value with a new_value,
/// fails if the current value is no longer the value supplied
pub fn atomic_replace(&self, current_value: IndexPtr, new_value: IndexPtr) -> bool {
let atomic_self: *mut atomic::AtomicU64 = unsafe { mem::transmute( self ) };
let prev = unsafe {
(*atomic_self).compare_and_swap(
mem::transmute(current_value),
mem::transmute(new_value),
atomic::Ordering::Relaxed)
};
prev == unsafe { mem::transmute(current_value) }
}
}
/// The result used internally when searched for hash
enum FindNodeResult {
/// Tha hash is found and the location is returned
Found(&'static Node),
/// The hash is not found; the location where the node should be inserted
/// is returned
NotFound(&'static IndexPtr)
}
/// Structures as stored in the fileset
#[derive(Debug)]
struct Node {
hash: Hash32Buf,
prev: IndexPtr, // to Node
next: IndexPtr, // to Node
leaf: IndexPtr, // to Leaf
}
/// Leaf of the binary tree
/// The supplied Type is the type of the elements that are stored in the tree
struct Leaf<T : HashIndexGuard> {
value: T, /// to Data file
next: IndexPtr, // to Leaf
}
impl<T : HashIndexGuard> Leaf<T> {
fn new(value: T) -> Self {
Leaf {
value: value,
next: IndexPtr::null()
}
}
}
impl Node {
fn new(hash: Hash32, leaf_ptr: IndexPtr) -> Self {
Node {
hash: hash.as_buf(),
prev: IndexPtr::null(),
next: IndexPtr::null(),
leaf: leaf_ptr
}
}
}
// Returns the first 24-bits of the hash
//
// This is the index into the root-hash table
fn hash_to_index(hash: Hash32) -> usize {
(hash.0[0] as usize) |
(hash.0[1] as usize) << 8 |
(hash.0[2] as usize) << 16
}
impl<T :'static> HashIndex<T>
where T : HashIndexGuard + PartialEq + Copy + Clone
{
/// Opens the hash_index at the location given in the config
///
/// Creates a new fileset if needed
pub fn new(cfg: &config::Config, dir: &str) -> HashIndex<T> {
let dir = &cfg.root.clone().join(dir);
let is_new =!dir.exists();
let mut fileset = FlatFileSet::new(
dir, "hi-", FILE_SIZE, MAX_CONTENT_SIZE);
let hash_root_fileptr = if is_new {
// allocate space for root hash table
fileset.alloc_write_space(mem::size_of::<[IndexPtr; HASH_ROOT_COUNT]>() as u64)
}
else {
// hash root must have been the first thing written
IndexPtr::new(0, super::flatfile::INITIAL_WRITEPOS)
};
// and keep a reference to it
let hash_root_ref: &'static [IndexPtr; HASH_ROOT_COUNT]
= fileset.read_fixed(hash_root_fileptr);
HashIndex {
fileset: fileset,
hash_index_root: hash_root_ref,
phantom: ::std::marker::PhantomData
}
}
/// Collects all the values stored at the given node
fn collect_node_values(&mut self, node: &Node) -> Vec<T> {
let mut result : Vec<T> = Vec::new();
let mut leaf_ptr = node.leaf;
while!leaf_ptr.is_null() {
let v: &T = self.fileset.read_fixed(leaf_ptr);
let leaf: Leaf<T> = Leaf::new(*v);
result.push(leaf.value);
leaf_ptr = leaf.next;
}
result
}
// Finds the node containing the hash, or the location the hash should be inserted
fn find_node(&mut self, hash: Hash32) -> FindNodeResult {
// use the first 24-bit as index in the root hash table
let mut ptr = &self.hash_index_root[hash_to_index(hash)];
// from there, we follow the binary tree
while!ptr.is_null() {
let node: &Node = self.fileset.read_fixed(*ptr);
ptr = match hash.0.cmp(&node.hash.as_ref().0) {
Ordering::Less => &node.prev,
Ordering::Greater => &node.next,
Ordering::Equal => return FindNodeResult::Found(node)
};
}
FindNodeResult::NotFound(ptr)
}
/// Retrieves the fileptr'` of the given hash
pub fn get(&mut self, hash: Hash32) -> Vec<T> {
match self.find_node(hash) {
FindNodeResult::NotFound(_) => {
Vec::new()
},
FindNodeResult::Found(node) => {
self.collect_node_values(node)
}
}
}
/// Stores a T at the given hash
///
/// This will bail out atomically (do a noop) if there are existing Ts stored at the hash,
/// that are not among the passed `verified_ptrs`.
///
/// This way, inputs stores at a hash serve as guards that need to be verified before
/// the transaction can be stored.
///
/// The force_store flag can be used to overrule this behaviour and store anyway
///
/// Similarly, blockheader_guards need to be connected before a block can be stored
pub fn set(&mut self, hash: Hash32, store_ptr: T, verified_ptrs: &[T], force_store: bool) -> bool {
assert!(! store_ptr.is_guard());
assert!(verified_ptrs.iter().all(|p| p.is_guard()));
// this loops through retries when the CAS operation fails
loop {
match self.find_node(hash) {
FindNodeResult::NotFound(target) => {
// create and write a leaf;
let new_leaf = Leaf::new(store_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// create and write a node holding the leaf
let new_node = Node::new(hash, new_leaf_ptr);
let new_node_ptr = self.fileset.write_fixed(&new_node);
// then atomically update the pointer
if target.atomic_replace(IndexPtr::null(), new_node_ptr) {
return true;
}
},
FindNodeResult::Found(node) => {
let first_value_ptr = node.leaf;
// check if there is anything waiting that is not supplied in `verified_ptrs`
if!force_store &&
!self
.collect_node_values(node)
.into_iter()
.any(|val| verified_ptrs.contains(&val)) {
return false;
}
// We don't need to keep the verified-ptrs
// Replace all with a new leaf
let new_leaf = Leaf::new(store_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// then atomically update the pointer
if node.leaf.atomic_replace(first_value_ptr, new_leaf_ptr) {
return true;
}
}
};
}
}
/// Retrieves the fileptr
///
/// If there is no primary ptr (block/tx) for the given hash
/// the given guard_ptr is added atomically to block further adds
pub fn get_or_set(&mut self, hash: Hash32, guard_ptr: T) -> Option<T> {
debug_assert!(guard_ptr.is_guard());
// this loops through retries when the CAS operation fails
loop {
match self.find_node(hash) {
FindNodeResult::NotFound(ptr) => {
// The transaction doesn't exist; we insert guard_ptr instead
// create and write a leaf;
let new_leaf = Leaf::new(guard_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// create and write a node holding the leaf
let new_node = Node::new(hash, new_leaf_ptr);
let new_node_ptr = self.fileset.write_fixed(&new_node);
// then atomically update the pointer
if ptr.atomic_replace(IndexPtr::null(), new_node_ptr) {
return None;
}
},
FindNodeResult::Found(node) => {
// load first leaf
let first_value_ptr = node.leaf;
let val: &T = self.fileset.read_fixed(first_value_ptr);
let leaf: Leaf<T> = Leaf::new(*val);
if!leaf.value.is_guard() {
return Some(leaf.value);
}
// create a new leaf, pointing to the previous one
let new_leaf = Leaf { value: guard_ptr, next: node.leaf };
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// then atomically update the pointer
if node.leaf.atomic_replace(first_value_ptr, new_leaf_ptr) |
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::Node;
use std::mem;
extern crate tempdir;
extern crate rand;
use std::path::PathBuf;
use std::thread;
use super::*;
use self::rand::Rng;
use config;
use hash::Hash32Buf;
use store::TxPtr;
use store::flatfileset::FlatFilePtr;
#[test]
fn test_size_of_node() {
assert_eq!(mem::size_of::<Node>(), 56);
}
#[test]
fn test_seq() {
const DATA_SIZE: u32 = 100000;
const THREADS: usize = 100;
const LOOPS: usize = 500;
let dir = tempdir::TempDir::new("test1").unwrap();
let path = PathBuf::from(dir.path());
let cfg = config::Config { root: path.clone() };
let _idx: HashIndex<TxPtr> = HashIndex::new(& cfg, "test" );
// We create a little transaction world:
// The "transactions" are file pointers 1 to DATA_SIZE
// Function to hash them:
fn hash(n: usize) -> Hash32Buf {
let s = format!("{}",n);
Hash32Buf::double_sha256(s.into_bytes().as_ref())
}
let handles: Vec<_> = (0..THREADS).map(|_| {
let path = path.clone();
thread::spawn( move | | {
let mut rng = rand::thread_rng();
let cfg = config::Config { root: path };
let mut idx = HashIndex::new(&cfg, "test");
for _ in 0..LOOPS {
let tx = TxPtr::new(0, rng.gen_range(10, DATA_SIZE) as u64);
let tx_hash = hash(tx.get_file_offset() as usize);
let found_txs = idx.get(tx_hash.as_ref());
if!found_txs.is_empty() {
// check that x is either a tx or a set of inputs
if found_txs.clone().into_iter().all(|tx: TxPtr|!tx.is_guard() ) && found_txs.len() == 1 {
assert_eq!(found_txs[0].get_file_offset(), tx.get_file_offset());
continue;
}
if found_txs.clone().into_iter().all(|tx| tx.is_guard() ) {
continue;
}
panic!("Expected only 1 tx or 1..n inputs");
}
else {
if tx.get_file_offset() > 2 {
// some messy ops for messy tests
let output_tx1_ptr = TxPtr::new(0, tx.get_file_offset() -1);
let output_hash = hash(output_tx1_ptr.get_file_offset() as usize);
let input_ptr = TxPtr::new(0, tx.get_file_offset()).to_input(1);
let output_tx1 = idx.get_or_set(output_hash.as_ref(), input_ptr);
if let Some(x) = output_tx1 {
assert_eq!(!x.is_guard(), true);
// script validation goes here
}
idx.set(tx_hash.as_ref(), tx, &[input_ptr], false);
}
else {
idx.set(tx_hash.as_ref(), tx, &[], false);
}
}
}
})
}).collect();
for h in handles {
h.join().unwrap();
}
}
} | {
return None;
} | conditional_block |
hash_index.rs | //! Index that maps hashes to content pointers
//!
//! This is used for transactions & blockheaders; the values found for a hash can be:
//!
//! * a single fileptr pointing to a transaction
//! The transaction can be found at the ptr in block_content and is fully validated
//!
//! * a set of fileptr pointing to inputs
//! Transaction cannot be found, but these inputs need this transaction
//! and are already assumed to be valid. The transaction may not be inserted before these
//! scripts are checked
//!
//! * a single fileptr pointing to a pointer to blockheader
//! The block is found. The pointer points to a record in the spend-tree; _that_ pointer points to the blockheader
//! in block_content
//!
//! * a set of fileptr pointing to guard blocks
//! The block cannot be found, but the blocks pointed to by these ptrs are having the given hash as previous block;
//! they are "expecting" this block, and should be appended when this block comes in
//!
//! The implementation is a large root hash table, with colliding keys added to an unbalanced binary tree.
//!
//! TODO There is probably quite some gain to be made by moving to HAMT instead unbalanced binary trees
//! for the branches; especially for low-resource uses.
use std::{mem};
use std::sync::atomic;
use std::cmp::{Ord,Ordering};
use config;
use hash::*;
use store::FlatFilePtr;
use store::flatfileset::FlatFileSet;
const FILE_SIZE: u64 = 1 * 1024*1024*1024;
const MAX_CONTENT_SIZE: u64 = FILE_SIZE - 10 * 1024*1024;
const HASH_ROOT_COUNT: usize = 256*256*256;
/// Trait for objects that can be used as a guard
/// This is required for types that are stored in the hash-index
pub trait HashIndexGuard {
fn is_guard(self) -> bool;
}
/// Index to lookup fileptr's from hashes
///
/// Internally uses fileset
pub struct HashIndex<T : HashIndexGuard + Copy + Clone> {
fileset: FlatFileSet<IndexPtr>,
hash_index_root: &'static [IndexPtr; HASH_ROOT_COUNT],
phantom: ::std::marker::PhantomData<T>
}
impl<T : HashIndexGuard + Copy + Clone> Clone for HashIndex<T> {
// Explicit cloning can be used to allow concurrent access.
fn clone(&self) -> HashIndex<T> {
let mut fileset = self.fileset.clone();
let root = fileset.read_fixed(IndexPtr::new(0, super::flatfile::INITIAL_WRITEPOS));
HashIndex {
fileset: fileset,
hash_index_root: root,
phantom: ::std::marker::PhantomData
}
}
}
/// A persistent pointer into the hash-index
#[derive(Debug, Clone, Copy)]
pub struct IndexPtr {
file_offset: u32,
file_number: i16,
zero: u16
}
impl FlatFilePtr for IndexPtr {
fn new(file_number: i16, file_offset: u64) -> Self {
IndexPtr {
file_offset: file_offset as u32,
file_number: file_number,
zero: 0 // we must pad with zero to ensure atomic CAS works
}
}
fn get_file_offset(self) -> u64 { self.file_offset as u64 }
fn get_file_number(self) -> i16 { self.file_number }
}
impl IndexPtr {
pub fn null() -> Self { IndexPtr::new(0, 0) }
pub fn is_null(&self) -> bool { self.file_offset == 0 && self.file_number == 0 }
/// atomically replaces a hash indexptr value with a new_value,
/// fails if the current value is no longer the value supplied
pub fn atomic_replace(&self, current_value: IndexPtr, new_value: IndexPtr) -> bool {
let atomic_self: *mut atomic::AtomicU64 = unsafe { mem::transmute( self ) };
let prev = unsafe {
(*atomic_self).compare_and_swap(
mem::transmute(current_value),
mem::transmute(new_value),
atomic::Ordering::Relaxed)
};
prev == unsafe { mem::transmute(current_value) }
}
}
/// The result used internally when searched for hash
enum FindNodeResult {
/// Tha hash is found and the location is returned
Found(&'static Node),
/// The hash is not found; the location where the node should be inserted
/// is returned
NotFound(&'static IndexPtr)
}
/// Structures as stored in the fileset
#[derive(Debug)]
struct Node {
hash: Hash32Buf,
prev: IndexPtr, // to Node
next: IndexPtr, // to Node
leaf: IndexPtr, // to Leaf
}
/// Leaf of the binary tree
/// The supplied Type is the type of the elements that are stored in the tree
struct Leaf<T : HashIndexGuard> {
value: T, /// to Data file
next: IndexPtr, // to Leaf
}
impl<T : HashIndexGuard> Leaf<T> {
fn new(value: T) -> Self {
Leaf {
value: value,
next: IndexPtr::null()
}
}
}
impl Node {
fn new(hash: Hash32, leaf_ptr: IndexPtr) -> Self {
Node {
hash: hash.as_buf(),
prev: IndexPtr::null(),
next: IndexPtr::null(),
leaf: leaf_ptr
}
}
}
// Returns the first 24-bits of the hash
//
// This is the index into the root-hash table
fn hash_to_index(hash: Hash32) -> usize {
(hash.0[0] as usize) |
(hash.0[1] as usize) << 8 |
(hash.0[2] as usize) << 16
}
impl<T :'static> HashIndex<T>
where T : HashIndexGuard + PartialEq + Copy + Clone
{
/// Opens the hash_index at the location given in the config
///
/// Creates a new fileset if needed
pub fn new(cfg: &config::Config, dir: &str) -> HashIndex<T> {
let dir = &cfg.root.clone().join(dir);
let is_new =!dir.exists();
let mut fileset = FlatFileSet::new(
dir, "hi-", FILE_SIZE, MAX_CONTENT_SIZE);
let hash_root_fileptr = if is_new {
// allocate space for root hash table
fileset.alloc_write_space(mem::size_of::<[IndexPtr; HASH_ROOT_COUNT]>() as u64)
}
else {
// hash root must have been the first thing written
IndexPtr::new(0, super::flatfile::INITIAL_WRITEPOS)
};
// and keep a reference to it
let hash_root_ref: &'static [IndexPtr; HASH_ROOT_COUNT]
= fileset.read_fixed(hash_root_fileptr);
HashIndex {
fileset: fileset,
hash_index_root: hash_root_ref,
phantom: ::std::marker::PhantomData
}
}
/// Collects all the values stored at the given node
fn collect_node_values(&mut self, node: &Node) -> Vec<T> {
let mut result : Vec<T> = Vec::new();
let mut leaf_ptr = node.leaf;
while!leaf_ptr.is_null() {
let v: &T = self.fileset.read_fixed(leaf_ptr);
let leaf: Leaf<T> = Leaf::new(*v);
result.push(leaf.value);
leaf_ptr = leaf.next;
}
result
}
// Finds the node containing the hash, or the location the hash should be inserted
fn find_node(&mut self, hash: Hash32) -> FindNodeResult {
// use the first 24-bit as index in the root hash table
let mut ptr = &self.hash_index_root[hash_to_index(hash)];
// from there, we follow the binary tree
while!ptr.is_null() {
let node: &Node = self.fileset.read_fixed(*ptr);
ptr = match hash.0.cmp(&node.hash.as_ref().0) {
Ordering::Less => &node.prev,
Ordering::Greater => &node.next,
Ordering::Equal => return FindNodeResult::Found(node)
};
}
FindNodeResult::NotFound(ptr)
}
/// Retrieves the fileptr'` of the given hash
pub fn get(&mut self, hash: Hash32) -> Vec<T> {
match self.find_node(hash) {
FindNodeResult::NotFound(_) => {
Vec::new()
},
FindNodeResult::Found(node) => {
self.collect_node_values(node)
}
}
}
/// Stores a T at the given hash
///
/// This will bail out atomically (do a noop) if there are existing Ts stored at the hash,
/// that are not among the passed `verified_ptrs`.
///
/// This way, inputs stores at a hash serve as guards that need to be verified before
/// the transaction can be stored.
///
/// The force_store flag can be used to overrule this behaviour and store anyway
///
/// Similarly, blockheader_guards need to be connected before a block can be stored
pub fn set(&mut self, hash: Hash32, store_ptr: T, verified_ptrs: &[T], force_store: bool) -> bool {
assert!(! store_ptr.is_guard());
assert!(verified_ptrs.iter().all(|p| p.is_guard()));
// this loops through retries when the CAS operation fails
loop {
match self.find_node(hash) {
FindNodeResult::NotFound(target) => {
// create and write a leaf;
let new_leaf = Leaf::new(store_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// create and write a node holding the leaf
let new_node = Node::new(hash, new_leaf_ptr);
let new_node_ptr = self.fileset.write_fixed(&new_node);
// then atomically update the pointer
if target.atomic_replace(IndexPtr::null(), new_node_ptr) {
return true;
}
},
FindNodeResult::Found(node) => {
let first_value_ptr = node.leaf;
// check if there is anything waiting that is not supplied in `verified_ptrs`
if!force_store &&
!self
.collect_node_values(node)
.into_iter()
.any(|val| verified_ptrs.contains(&val)) {
return false;
}
// We don't need to keep the verified-ptrs
// Replace all with a new leaf
let new_leaf = Leaf::new(store_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// then atomically update the pointer
if node.leaf.atomic_replace(first_value_ptr, new_leaf_ptr) {
return true;
}
}
};
}
}
/// Retrieves the fileptr
///
/// If there is no primary ptr (block/tx) for the given hash
/// the given guard_ptr is added atomically to block further adds
pub fn get_or_set(&mut self, hash: Hash32, guard_ptr: T) -> Option<T> {
debug_assert!(guard_ptr.is_guard());
// this loops through retries when the CAS operation fails
loop {
match self.find_node(hash) {
FindNodeResult::NotFound(ptr) => {
// The transaction doesn't exist; we insert guard_ptr instead
// create and write a leaf;
let new_leaf = Leaf::new(guard_ptr);
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// create and write a node holding the leaf
let new_node = Node::new(hash, new_leaf_ptr);
let new_node_ptr = self.fileset.write_fixed(&new_node);
// then atomically update the pointer
if ptr.atomic_replace(IndexPtr::null(), new_node_ptr) {
return None;
}
},
FindNodeResult::Found(node) => {
// load first leaf
let first_value_ptr = node.leaf;
let val: &T = self.fileset.read_fixed(first_value_ptr);
let leaf: Leaf<T> = Leaf::new(*val);
if!leaf.value.is_guard() {
return Some(leaf.value);
}
// create a new leaf, pointing to the previous one
let new_leaf = Leaf { value: guard_ptr, next: node.leaf };
let new_leaf_ptr = self.fileset.write_fixed(&new_leaf);
// then atomically update the pointer
if node.leaf.atomic_replace(first_value_ptr, new_leaf_ptr) {
return None;
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::Node;
use std::mem;
extern crate tempdir;
extern crate rand;
use std::path::PathBuf;
use std::thread;
use super::*;
use self::rand::Rng;
use config;
use hash::Hash32Buf;
use store::TxPtr;
use store::flatfileset::FlatFilePtr;
#[test]
fn test_size_of_node() {
assert_eq!(mem::size_of::<Node>(), 56);
}
#[test]
fn test_seq() {
const DATA_SIZE: u32 = 100000;
const THREADS: usize = 100;
const LOOPS: usize = 500;
let dir = tempdir::TempDir::new("test1").unwrap();
let path = PathBuf::from(dir.path());
let cfg = config::Config { root: path.clone() };
let _idx: HashIndex<TxPtr> = HashIndex::new(& cfg, "test" );
// We create a little transaction world:
// The "transactions" are file pointers 1 to DATA_SIZE
// Function to hash them:
fn hash(n: usize) -> Hash32Buf {
let s = format!("{}",n);
Hash32Buf::double_sha256(s.into_bytes().as_ref())
}
let handles: Vec<_> = (0..THREADS).map(|_| {
let path = path.clone();
thread::spawn( move | | {
let mut rng = rand::thread_rng();
let cfg = config::Config { root: path };
let mut idx = HashIndex::new(&cfg, "test");
for _ in 0..LOOPS {
let tx = TxPtr::new(0, rng.gen_range(10, DATA_SIZE) as u64);
let tx_hash = hash(tx.get_file_offset() as usize);
let found_txs = idx.get(tx_hash.as_ref());
if!found_txs.is_empty() {
// check that x is either a tx or a set of inputs
if found_txs.clone().into_iter().all(|tx: TxPtr|!tx.is_guard() ) && found_txs.len() == 1 {
assert_eq!(found_txs[0].get_file_offset(), tx.get_file_offset());
continue;
}
if found_txs.clone().into_iter().all(|tx| tx.is_guard() ) {
continue;
} |
// some messy ops for messy tests
let output_tx1_ptr = TxPtr::new(0, tx.get_file_offset() -1);
let output_hash = hash(output_tx1_ptr.get_file_offset() as usize);
let input_ptr = TxPtr::new(0, tx.get_file_offset()).to_input(1);
let output_tx1 = idx.get_or_set(output_hash.as_ref(), input_ptr);
if let Some(x) = output_tx1 {
assert_eq!(!x.is_guard(), true);
// script validation goes here
}
idx.set(tx_hash.as_ref(), tx, &[input_ptr], false);
}
else {
idx.set(tx_hash.as_ref(), tx, &[], false);
}
}
}
})
}).collect();
for h in handles {
h.join().unwrap();
}
}
} | panic!("Expected only 1 tx or 1..n inputs");
}
else {
if tx.get_file_offset() > 2 { | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of in script so that the devtools crate can be
//! modified independently of the rest of Servo.
#![crate_name = "devtools_traits"]
#![crate_type = "rlib"]
#![feature(int_uint)]
#![allow(non_snake_case)]
extern crate msg;
extern crate "rustc-serialize" as rustc_serialize;
extern crate url;
extern crate util;
use rustc_serialize::{Decodable, Decoder};
use msg::constellation_msg::PipelineId;
use util::str::DOMString;
use url::Url;
use std::sync::mpsc::{Sender, Receiver};
pub type DevtoolsControlChan = Sender<DevtoolsControlMsg>;
pub type DevtoolsControlPort = Receiver<DevtoolScriptControlMsg>;
// Information would be attached to NewGlobal to be received and show in devtools.
// Extend these fields if we need more information.
pub struct DevtoolsPageInfo {
pub title: DOMString,
pub url: Url
}
/// Messages to the instruct the devtools server to update its known actors/state
/// according to changes in the browser.
pub enum DevtoolsControlMsg {
NewGlobal(PipelineId, Sender<DevtoolScriptControlMsg>, DevtoolsPageInfo),
SendConsoleMessage(PipelineId, ConsoleMessage),
ServerExitMsg
}
/// Serialized JS return values
/// TODO: generalize this beyond the EvaluateJS message?
pub enum EvaluateJSReply {
VoidValue,
NullValue,
BooleanValue(bool),
NumberValue(f64),
StringValue(String),
ActorValue(String),
}
pub struct AttrInfo {
pub namespace: String,
pub name: String,
pub value: String,
}
pub struct NodeInfo {
pub uniqueId: String,
pub baseURI: String,
pub parent: String,
pub nodeType: uint,
pub namespaceURI: String,
pub nodeName: String,
pub numChildren: uint,
pub name: String,
pub publicId: String,
pub systemId: String,
pub attrs: Vec<AttrInfo>,
pub isDocumentElement: bool,
pub shortValue: String,
pub incompleteValue: bool,
}
/// Messages to process in a particular script task, as instructed by a devtools client.
pub enum DevtoolScriptControlMsg {
EvaluateJS(PipelineId, String, Sender<EvaluateJSReply>),
GetRootNode(PipelineId, Sender<NodeInfo>),
GetDocumentElement(PipelineId, Sender<NodeInfo>),
GetChildren(PipelineId, String, Sender<Vec<NodeInfo>>),
GetLayout(PipelineId, String, Sender<(f32, f32)>),
ModifyAttribute(PipelineId, String, Vec<Modification>),
WantsLiveNotifications(PipelineId, bool),
}
/// Messages to instruct devtools server to update its state relating to a particular
/// tab.
pub enum ScriptDevtoolControlMsg {
/// Report a new JS error message
ReportConsoleMsg(String),
}
#[derive(RustcEncodable)]
pub struct | {
pub attributeName: String,
pub newValue: Option<String>,
}
impl Decodable for Modification {
fn decode<D: Decoder>(d: &mut D) -> Result<Modification, D::Error> {
d.read_struct("Modification", 2u, |d|
Ok(Modification {
attributeName: try!(d.read_struct_field("attributeName", 0u, |d| Decodable::decode(d))),
newValue: match d.read_struct_field("newValue", 1u, |d| Decodable::decode(d)) {
Ok(opt) => opt,
Err(_) => None
}
})
)
}
}
//TODO: Include options for Warn, Debug, Info, Error messages from Console
#[derive(Clone)]
pub enum ConsoleMessage {
LogMessage(String),
//WarnMessage(String),
}
| Modification | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of in script so that the devtools crate can be
//! modified independently of the rest of Servo.
#![crate_name = "devtools_traits"]
#![crate_type = "rlib"]
#![feature(int_uint)]
#![allow(non_snake_case)]
extern crate msg;
extern crate "rustc-serialize" as rustc_serialize;
extern crate url;
extern crate util;
use rustc_serialize::{Decodable, Decoder};
use msg::constellation_msg::PipelineId;
use util::str::DOMString;
use url::Url;
use std::sync::mpsc::{Sender, Receiver};
pub type DevtoolsControlChan = Sender<DevtoolsControlMsg>;
pub type DevtoolsControlPort = Receiver<DevtoolScriptControlMsg>;
// Information would be attached to NewGlobal to be received and show in devtools.
// Extend these fields if we need more information.
pub struct DevtoolsPageInfo {
pub title: DOMString,
pub url: Url
}
/// Messages to the instruct the devtools server to update its known actors/state
/// according to changes in the browser.
pub enum DevtoolsControlMsg {
NewGlobal(PipelineId, Sender<DevtoolScriptControlMsg>, DevtoolsPageInfo),
SendConsoleMessage(PipelineId, ConsoleMessage),
ServerExitMsg
}
/// Serialized JS return values
/// TODO: generalize this beyond the EvaluateJS message?
pub enum EvaluateJSReply {
VoidValue,
NullValue,
BooleanValue(bool),
NumberValue(f64),
StringValue(String),
ActorValue(String),
}
pub struct AttrInfo {
pub namespace: String,
pub name: String,
pub value: String,
}
pub struct NodeInfo {
pub uniqueId: String,
pub baseURI: String,
pub parent: String,
pub nodeType: uint,
pub namespaceURI: String,
pub nodeName: String,
pub numChildren: uint,
pub name: String,
pub publicId: String,
pub systemId: String,
pub attrs: Vec<AttrInfo>,
pub isDocumentElement: bool,
pub shortValue: String,
pub incompleteValue: bool,
}
/// Messages to process in a particular script task, as instructed by a devtools client.
pub enum DevtoolScriptControlMsg {
EvaluateJS(PipelineId, String, Sender<EvaluateJSReply>),
GetRootNode(PipelineId, Sender<NodeInfo>),
GetDocumentElement(PipelineId, Sender<NodeInfo>),
GetChildren(PipelineId, String, Sender<Vec<NodeInfo>>),
GetLayout(PipelineId, String, Sender<(f32, f32)>),
ModifyAttribute(PipelineId, String, Vec<Modification>),
WantsLiveNotifications(PipelineId, bool),
}
/// Messages to instruct devtools server to update its state relating to a particular
/// tab.
pub enum ScriptDevtoolControlMsg {
/// Report a new JS error message
ReportConsoleMsg(String),
}
#[derive(RustcEncodable)]
pub struct Modification{
pub attributeName: String,
pub newValue: Option<String>,
}
impl Decodable for Modification {
fn decode<D: Decoder>(d: &mut D) -> Result<Modification, D::Error> |
}
//TODO: Include options for Warn, Debug, Info, Error messages from Console
#[derive(Clone)]
pub enum ConsoleMessage {
LogMessage(String),
//WarnMessage(String),
}
| {
d.read_struct("Modification", 2u, |d|
Ok(Modification {
attributeName: try!(d.read_struct_field("attributeName", 0u, |d| Decodable::decode(d))),
newValue: match d.read_struct_field("newValue", 1u, |d| Decodable::decode(d)) {
Ok(opt) => opt,
Err(_) => None
}
})
)
} | identifier_body |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module contains shared types and messages for use by devtools/script.
//! The traits are here instead of in script so that the devtools crate can be
//! modified independently of the rest of Servo.
#![crate_name = "devtools_traits"]
#![crate_type = "rlib"]
#![feature(int_uint)]
#![allow(non_snake_case)]
extern crate msg;
extern crate "rustc-serialize" as rustc_serialize;
extern crate url;
extern crate util;
use rustc_serialize::{Decodable, Decoder};
use msg::constellation_msg::PipelineId;
use util::str::DOMString;
use url::Url;
use std::sync::mpsc::{Sender, Receiver};
pub type DevtoolsControlChan = Sender<DevtoolsControlMsg>;
pub type DevtoolsControlPort = Receiver<DevtoolScriptControlMsg>;
// Information would be attached to NewGlobal to be received and show in devtools.
// Extend these fields if we need more information.
pub struct DevtoolsPageInfo {
pub title: DOMString,
pub url: Url
}
/// Messages to the instruct the devtools server to update its known actors/state
/// according to changes in the browser.
pub enum DevtoolsControlMsg {
NewGlobal(PipelineId, Sender<DevtoolScriptControlMsg>, DevtoolsPageInfo),
SendConsoleMessage(PipelineId, ConsoleMessage),
ServerExitMsg
}
/// Serialized JS return values
/// TODO: generalize this beyond the EvaluateJS message?
pub enum EvaluateJSReply {
VoidValue,
NullValue,
BooleanValue(bool),
NumberValue(f64),
StringValue(String),
ActorValue(String),
}
pub struct AttrInfo {
pub namespace: String,
pub name: String,
pub value: String,
}
pub struct NodeInfo {
pub uniqueId: String,
pub baseURI: String,
pub parent: String,
pub nodeType: uint,
pub namespaceURI: String,
pub nodeName: String,
pub numChildren: uint,
pub name: String,
pub publicId: String,
pub systemId: String,
pub attrs: Vec<AttrInfo>,
pub isDocumentElement: bool,
pub shortValue: String,
pub incompleteValue: bool,
}
/// Messages to process in a particular script task, as instructed by a devtools client.
pub enum DevtoolScriptControlMsg {
EvaluateJS(PipelineId, String, Sender<EvaluateJSReply>),
GetRootNode(PipelineId, Sender<NodeInfo>),
GetDocumentElement(PipelineId, Sender<NodeInfo>),
GetChildren(PipelineId, String, Sender<Vec<NodeInfo>>),
GetLayout(PipelineId, String, Sender<(f32, f32)>),
ModifyAttribute(PipelineId, String, Vec<Modification>),
WantsLiveNotifications(PipelineId, bool),
}
/// Messages to instruct devtools server to update its state relating to a particular
/// tab.
pub enum ScriptDevtoolControlMsg {
/// Report a new JS error message
ReportConsoleMsg(String),
}
#[derive(RustcEncodable)]
pub struct Modification{
pub attributeName: String,
pub newValue: Option<String>,
} | d.read_struct("Modification", 2u, |d|
Ok(Modification {
attributeName: try!(d.read_struct_field("attributeName", 0u, |d| Decodable::decode(d))),
newValue: match d.read_struct_field("newValue", 1u, |d| Decodable::decode(d)) {
Ok(opt) => opt,
Err(_) => None
}
})
)
}
}
//TODO: Include options for Warn, Debug, Info, Error messages from Console
#[derive(Clone)]
pub enum ConsoleMessage {
LogMessage(String),
//WarnMessage(String),
} |
impl Decodable for Modification {
fn decode<D: Decoder>(d: &mut D) -> Result<Modification, D::Error> { | random_line_split |
noise_image.rs | use crate::utils::color_gradient::Color;
#[cfg(feature = "image")]
use std::{self, path::Path};
const RASTER_MAX_WIDTH: u16 = 32_767;
const RASTER_MAX_HEIGHT: u16 = 32_767;
pub struct NoiseImage {
size: (usize, usize),
border_color: Color,
map: Vec<Color>,
}
impl NoiseImage {
pub fn new(width: usize, height: usize) -> Self {
Self::initialize().set_size(width, height)
}
pub fn set_size(self, width: usize, height: usize) -> Self {
// Check for invalid width or height.
assert!(width < RASTER_MAX_WIDTH as usize);
assert!(height < RASTER_MAX_HEIGHT as usize);
if width == 0 || height == 0 {
// An empty noise image was specified. Return a new blank, empty map.
Self::initialize()
} else {
// New noise map size specified. Allocate a new Vec unless the current Vec is large
// enough.
let map_size = width * height;
if self.map.capacity() < map_size {
// New size is too big for the current Vec. Create a new Vec with a large enough
// capacity now so we're not reallocating when filling the map.
Self {
map: vec![[0; 4]; map_size],
size: (width, height),
..self
}
} else {
// Vec capacity is already big enough, so leave it alone and just change the set size.
Self {
size: (width, height),
..self
}
}
}
}
pub fn set_border_color(self, color: Color) -> Self {
Self {
border_color: color,
..self
}
}
pub fn set_value(&mut self, x: usize, y: usize, value: Color) {
let (width, height) = self.size;
if x < width && y < height {
self.map[x + y * width] = value;
} else {
eprintln!("input point out of bounds")
}
}
pub fn size(&self) -> (usize, usize) {
self.size
}
pub fn border_color(&self) -> Color {
self.border_color
}
pub fn get_value(&self, x: usize, y: usize) -> Color {
let (width, height) = self.size;
if x < width && y < height {
self.map[x + y * width]
} else {
self.border_color
}
}
fn initialize() -> Self {
Self {
size: (0, 0),
border_color: [0; 4],
map: Vec::new(),
}
}
#[cfg(feature = "image")]
pub fn | (&self, filename: &str) {
// Create the output directory for the images, if it doesn't already exist
let target_dir = Path::new("example_images/");
if!target_dir.exists() {
std::fs::create_dir(target_dir).expect("failed to create example_images directory");
}
//concatenate the directory to the filename string
let directory: String = "example_images/".to_owned();
let file_path = directory + filename;
// collect the values from the map vector into an array
let (width, height) = self.size;
let mut result = Vec::with_capacity(width * height);
for i in &self.map {
for j in i.iter() {
result.push(*j);
}
}
let _ = image::save_buffer(
&Path::new(&file_path),
&*result,
self.size.0 as u32,
self.size.1 as u32,
image::ColorType::Rgba8,
);
println!("\nFinished generating {}", filename);
}
}
impl Default for NoiseImage {
fn default() -> Self {
Self::initialize()
}
}
| write_to_file | identifier_name |
noise_image.rs | use crate::utils::color_gradient::Color;
#[cfg(feature = "image")]
use std::{self, path::Path};
const RASTER_MAX_WIDTH: u16 = 32_767;
const RASTER_MAX_HEIGHT: u16 = 32_767;
pub struct NoiseImage {
size: (usize, usize),
border_color: Color,
map: Vec<Color>,
}
impl NoiseImage {
pub fn new(width: usize, height: usize) -> Self {
Self::initialize().set_size(width, height)
}
pub fn set_size(self, width: usize, height: usize) -> Self {
// Check for invalid width or height.
assert!(width < RASTER_MAX_WIDTH as usize);
assert!(height < RASTER_MAX_HEIGHT as usize);
if width == 0 || height == 0 {
// An empty noise image was specified. Return a new blank, empty map.
Self::initialize()
} else {
// New noise map size specified. Allocate a new Vec unless the current Vec is large
// enough.
let map_size = width * height;
if self.map.capacity() < map_size {
// New size is too big for the current Vec. Create a new Vec with a large enough
// capacity now so we're not reallocating when filling the map.
Self {
map: vec![[0; 4]; map_size],
size: (width, height),
..self
}
} else {
// Vec capacity is already big enough, so leave it alone and just change the set size.
Self {
size: (width, height),
..self
}
}
}
}
pub fn set_border_color(self, color: Color) -> Self {
Self {
border_color: color,
..self
}
}
pub fn set_value(&mut self, x: usize, y: usize, value: Color) {
let (width, height) = self.size;
if x < width && y < height {
self.map[x + y * width] = value;
} else {
eprintln!("input point out of bounds")
}
}
pub fn size(&self) -> (usize, usize) {
self.size
}
pub fn border_color(&self) -> Color {
self.border_color
}
pub fn get_value(&self, x: usize, y: usize) -> Color {
let (width, height) = self.size;
if x < width && y < height {
self.map[x + y * width]
} else {
self.border_color
}
}
fn initialize() -> Self {
Self {
size: (0, 0),
border_color: [0; 4],
map: Vec::new(),
}
}
#[cfg(feature = "image")]
pub fn write_to_file(&self, filename: &str) | }
let _ = image::save_buffer(
&Path::new(&file_path),
&*result,
self.size.0 as u32,
self.size.1 as u32,
image::ColorType::Rgba8,
);
println!("\nFinished generating {}", filename);
}
}
impl Default for NoiseImage {
fn default() -> Self {
Self::initialize()
}
}
| {
// Create the output directory for the images, if it doesn't already exist
let target_dir = Path::new("example_images/");
if !target_dir.exists() {
std::fs::create_dir(target_dir).expect("failed to create example_images directory");
}
//concatenate the directory to the filename string
let directory: String = "example_images/".to_owned();
let file_path = directory + filename;
// collect the values from the map vector into an array
let (width, height) = self.size;
let mut result = Vec::with_capacity(width * height);
for i in &self.map {
for j in i.iter() {
result.push(*j);
} | identifier_body |
noise_image.rs | use crate::utils::color_gradient::Color;
#[cfg(feature = "image")]
use std::{self, path::Path};
const RASTER_MAX_WIDTH: u16 = 32_767;
const RASTER_MAX_HEIGHT: u16 = 32_767;
pub struct NoiseImage {
size: (usize, usize),
border_color: Color,
map: Vec<Color>,
}
impl NoiseImage {
pub fn new(width: usize, height: usize) -> Self {
Self::initialize().set_size(width, height)
}
pub fn set_size(self, width: usize, height: usize) -> Self {
// Check for invalid width or height.
assert!(width < RASTER_MAX_WIDTH as usize);
assert!(height < RASTER_MAX_HEIGHT as usize);
if width == 0 || height == 0 {
// An empty noise image was specified. Return a new blank, empty map.
Self::initialize()
} else {
// New noise map size specified. Allocate a new Vec unless the current Vec is large
// enough.
let map_size = width * height;
if self.map.capacity() < map_size {
// New size is too big for the current Vec. Create a new Vec with a large enough
// capacity now so we're not reallocating when filling the map.
Self {
map: vec![[0; 4]; map_size],
size: (width, height),
..self
}
} else {
// Vec capacity is already big enough, so leave it alone and just change the set size.
Self {
size: (width, height),
..self
}
}
}
}
pub fn set_border_color(self, color: Color) -> Self {
Self {
border_color: color,
..self
}
}
pub fn set_value(&mut self, x: usize, y: usize, value: Color) {
let (width, height) = self.size;
if x < width && y < height {
self.map[x + y * width] = value;
} else |
}
pub fn size(&self) -> (usize, usize) {
self.size
}
pub fn border_color(&self) -> Color {
self.border_color
}
pub fn get_value(&self, x: usize, y: usize) -> Color {
let (width, height) = self.size;
if x < width && y < height {
self.map[x + y * width]
} else {
self.border_color
}
}
fn initialize() -> Self {
Self {
size: (0, 0),
border_color: [0; 4],
map: Vec::new(),
}
}
#[cfg(feature = "image")]
pub fn write_to_file(&self, filename: &str) {
// Create the output directory for the images, if it doesn't already exist
let target_dir = Path::new("example_images/");
if!target_dir.exists() {
std::fs::create_dir(target_dir).expect("failed to create example_images directory");
}
//concatenate the directory to the filename string
let directory: String = "example_images/".to_owned();
let file_path = directory + filename;
// collect the values from the map vector into an array
let (width, height) = self.size;
let mut result = Vec::with_capacity(width * height);
for i in &self.map {
for j in i.iter() {
result.push(*j);
}
}
let _ = image::save_buffer(
&Path::new(&file_path),
&*result,
self.size.0 as u32,
self.size.1 as u32,
image::ColorType::Rgba8,
);
println!("\nFinished generating {}", filename);
}
}
impl Default for NoiseImage {
fn default() -> Self {
Self::initialize()
}
}
| {
eprintln!("input point out of bounds")
} | conditional_block |
noise_image.rs | use crate::utils::color_gradient::Color;
#[cfg(feature = "image")]
use std::{self, path::Path};
const RASTER_MAX_WIDTH: u16 = 32_767;
const RASTER_MAX_HEIGHT: u16 = 32_767;
pub struct NoiseImage {
size: (usize, usize),
border_color: Color,
map: Vec<Color>,
}
impl NoiseImage {
pub fn new(width: usize, height: usize) -> Self {
Self::initialize().set_size(width, height)
}
pub fn set_size(self, width: usize, height: usize) -> Self {
// Check for invalid width or height. | // An empty noise image was specified. Return a new blank, empty map.
Self::initialize()
} else {
// New noise map size specified. Allocate a new Vec unless the current Vec is large
// enough.
let map_size = width * height;
if self.map.capacity() < map_size {
// New size is too big for the current Vec. Create a new Vec with a large enough
// capacity now so we're not reallocating when filling the map.
Self {
map: vec![[0; 4]; map_size],
size: (width, height),
..self
}
} else {
// Vec capacity is already big enough, so leave it alone and just change the set size.
Self {
size: (width, height),
..self
}
}
}
}
pub fn set_border_color(self, color: Color) -> Self {
Self {
border_color: color,
..self
}
}
pub fn set_value(&mut self, x: usize, y: usize, value: Color) {
let (width, height) = self.size;
if x < width && y < height {
self.map[x + y * width] = value;
} else {
eprintln!("input point out of bounds")
}
}
pub fn size(&self) -> (usize, usize) {
self.size
}
pub fn border_color(&self) -> Color {
self.border_color
}
pub fn get_value(&self, x: usize, y: usize) -> Color {
let (width, height) = self.size;
if x < width && y < height {
self.map[x + y * width]
} else {
self.border_color
}
}
fn initialize() -> Self {
Self {
size: (0, 0),
border_color: [0; 4],
map: Vec::new(),
}
}
#[cfg(feature = "image")]
pub fn write_to_file(&self, filename: &str) {
// Create the output directory for the images, if it doesn't already exist
let target_dir = Path::new("example_images/");
if!target_dir.exists() {
std::fs::create_dir(target_dir).expect("failed to create example_images directory");
}
//concatenate the directory to the filename string
let directory: String = "example_images/".to_owned();
let file_path = directory + filename;
// collect the values from the map vector into an array
let (width, height) = self.size;
let mut result = Vec::with_capacity(width * height);
for i in &self.map {
for j in i.iter() {
result.push(*j);
}
}
let _ = image::save_buffer(
&Path::new(&file_path),
&*result,
self.size.0 as u32,
self.size.1 as u32,
image::ColorType::Rgba8,
);
println!("\nFinished generating {}", filename);
}
}
impl Default for NoiseImage {
fn default() -> Self {
Self::initialize()
}
} | assert!(width < RASTER_MAX_WIDTH as usize);
assert!(height < RASTER_MAX_HEIGHT as usize);
if width == 0 || height == 0 { | random_line_split |
errors.rs | // Copyright 2016 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#![allow(dead_code)]
use std; // To refer to std::result::Result.
use std::collections::BTreeSet;
use rusqlite;
use edn;
use mentat_core::{
Attribute,
ValueType,
};
use mentat_db;
use mentat_query;
use mentat_query_algebrizer;
use mentat_query_projector;
use mentat_query_pull;
use mentat_sql;
#[cfg(feature = "syncable")]
use mentat_tolstoy;
pub type Result<T> = std::result::Result<T, MentatError>;
#[macro_export]
macro_rules! bail {
($e:expr) => (
return Err($e.into());
)
}
#[derive(Debug, Fail)]
pub enum MentatError {
#[fail(display = "bad uuid {}", _0)]
BadUuid(String),
#[fail(display = "path {} already exists", _0)]
PathAlreadyExists(String),
#[fail(display = "variables {:?} unbound at query execution time", _0)]
UnboundVariables(BTreeSet<String>),
#[fail(display = "invalid argument name: '{}'", _0)]
InvalidArgumentName(String),
#[fail(display = "unknown attribute: '{}'", _0)]
UnknownAttribute(String),
#[fail(display = "invalid vocabulary version")]
InvalidVocabularyVersion,
#[fail(display = "vocabulary {}/{} already has attribute {}, and the requested definition differs", _0, _1, _2)]
ConflictingAttributeDefinitions(String, ::vocabulary::Version, String, Attribute, Attribute),
#[fail(display = "existing vocabulary {} too new: wanted {}, got {}", _0, _1, _2)]
ExistingVocabularyTooNew(String, ::vocabulary::Version, ::vocabulary::Version),
#[fail(display = "core schema: wanted {}, got {:?}", _0, _1)]
UnexpectedCoreSchema(::vocabulary::Version, Option<::vocabulary::Version>),
#[fail(display = "Lost the transact() race!")]
UnexpectedLostTransactRace,
#[fail(display = "missing core attribute {}", _0)]
MissingCoreVocabulary(mentat_query::Keyword),
#[fail(display = "schema changed since query was prepared")]
PreparedQuerySchemaMismatch,
#[fail(display = "provided value of type {} doesn't match attribute value type {}", _0, _1)]
ValueTypeMismatch(ValueType, ValueType),
#[fail(display = "{}", _0)]
IoError(#[cause] std::io::Error),
// It would be better to capture the underlying `rusqlite::Error`, but that type doesn't
// implement many useful traits, including `Clone`, `Eq`, and `PartialEq`.
#[fail(display = "SQL error: {}", _0)]
RusqliteError(String),
#[fail(display = "{}", _0)]
EdnParseError(#[cause] edn::ParseError),
#[fail(display = "{}", _0)]
DbError(#[cause] mentat_db::DbError),
#[fail(display = "{}", _0)]
AlgebrizerError(#[cause] mentat_query_algebrizer::AlgebrizerError),
#[fail(display = "{}", _0)]
ProjectorError(#[cause] mentat_query_projector::ProjectorError),
#[fail(display = "{}", _0)]
PullError(#[cause] mentat_query_pull::PullError),
#[fail(display = "{}", _0)]
SQLError(#[cause] mentat_sql::SQLError),
#[cfg(feature = "syncable")]
#[fail(display = "{}", _0)]
TolstoyError(#[cause] mentat_tolstoy::TolstoyError),
}
impl From<std::io::Error> for MentatError {
fn from(error: std::io::Error) -> MentatError |
}
impl From<rusqlite::Error> for MentatError {
fn from(error: rusqlite::Error) -> MentatError {
MentatError::RusqliteError(error.to_string())
}
}
impl From<edn::ParseError> for MentatError {
fn from(error: edn::ParseError) -> MentatError {
MentatError::EdnParseError(error)
}
}
impl From<mentat_db::DbError> for MentatError {
fn from(error: mentat_db::DbError) -> MentatError {
MentatError::DbError(error)
}
}
impl From<mentat_query_algebrizer::AlgebrizerError> for MentatError {
fn from(error: mentat_query_algebrizer::AlgebrizerError) -> MentatError {
MentatError::AlgebrizerError(error)
}
}
impl From<mentat_query_projector::ProjectorError> for MentatError {
fn from(error: mentat_query_projector::ProjectorError) -> MentatError {
MentatError::ProjectorError(error)
}
}
impl From<mentat_query_pull::PullError> for MentatError {
fn from(error: mentat_query_pull::PullError) -> MentatError {
MentatError::PullError(error)
}
}
impl From<mentat_sql::SQLError> for MentatError {
fn from(error: mentat_sql::SQLError) -> MentatError {
MentatError::SQLError(error)
}
}
#[cfg(feature = "syncable")]
impl From<mentat_tolstoy::TolstoyError> for MentatError {
fn from(error: mentat_tolstoy::TolstoyError) -> MentatError {
MentatError::TolstoyError(error)
}
}
| {
MentatError::IoError(error)
} | identifier_body |
errors.rs | // Copyright 2016 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#![allow(dead_code)]
use std; // To refer to std::result::Result.
use std::collections::BTreeSet;
use rusqlite;
use edn;
use mentat_core::{
Attribute,
ValueType,
};
use mentat_db;
use mentat_query;
use mentat_query_algebrizer;
use mentat_query_projector;
use mentat_query_pull;
use mentat_sql;
#[cfg(feature = "syncable")]
use mentat_tolstoy;
pub type Result<T> = std::result::Result<T, MentatError>;
#[macro_export]
macro_rules! bail {
($e:expr) => (
return Err($e.into());
)
}
#[derive(Debug, Fail)]
pub enum | {
#[fail(display = "bad uuid {}", _0)]
BadUuid(String),
#[fail(display = "path {} already exists", _0)]
PathAlreadyExists(String),
#[fail(display = "variables {:?} unbound at query execution time", _0)]
UnboundVariables(BTreeSet<String>),
#[fail(display = "invalid argument name: '{}'", _0)]
InvalidArgumentName(String),
#[fail(display = "unknown attribute: '{}'", _0)]
UnknownAttribute(String),
#[fail(display = "invalid vocabulary version")]
InvalidVocabularyVersion,
#[fail(display = "vocabulary {}/{} already has attribute {}, and the requested definition differs", _0, _1, _2)]
ConflictingAttributeDefinitions(String, ::vocabulary::Version, String, Attribute, Attribute),
#[fail(display = "existing vocabulary {} too new: wanted {}, got {}", _0, _1, _2)]
ExistingVocabularyTooNew(String, ::vocabulary::Version, ::vocabulary::Version),
#[fail(display = "core schema: wanted {}, got {:?}", _0, _1)]
UnexpectedCoreSchema(::vocabulary::Version, Option<::vocabulary::Version>),
#[fail(display = "Lost the transact() race!")]
UnexpectedLostTransactRace,
#[fail(display = "missing core attribute {}", _0)]
MissingCoreVocabulary(mentat_query::Keyword),
#[fail(display = "schema changed since query was prepared")]
PreparedQuerySchemaMismatch,
#[fail(display = "provided value of type {} doesn't match attribute value type {}", _0, _1)]
ValueTypeMismatch(ValueType, ValueType),
#[fail(display = "{}", _0)]
IoError(#[cause] std::io::Error),
// It would be better to capture the underlying `rusqlite::Error`, but that type doesn't
// implement many useful traits, including `Clone`, `Eq`, and `PartialEq`.
#[fail(display = "SQL error: {}", _0)]
RusqliteError(String),
#[fail(display = "{}", _0)]
EdnParseError(#[cause] edn::ParseError),
#[fail(display = "{}", _0)]
DbError(#[cause] mentat_db::DbError),
#[fail(display = "{}", _0)]
AlgebrizerError(#[cause] mentat_query_algebrizer::AlgebrizerError),
#[fail(display = "{}", _0)]
ProjectorError(#[cause] mentat_query_projector::ProjectorError),
#[fail(display = "{}", _0)]
PullError(#[cause] mentat_query_pull::PullError),
#[fail(display = "{}", _0)]
SQLError(#[cause] mentat_sql::SQLError),
#[cfg(feature = "syncable")]
#[fail(display = "{}", _0)]
TolstoyError(#[cause] mentat_tolstoy::TolstoyError),
}
impl From<std::io::Error> for MentatError {
fn from(error: std::io::Error) -> MentatError {
MentatError::IoError(error)
}
}
impl From<rusqlite::Error> for MentatError {
fn from(error: rusqlite::Error) -> MentatError {
MentatError::RusqliteError(error.to_string())
}
}
impl From<edn::ParseError> for MentatError {
fn from(error: edn::ParseError) -> MentatError {
MentatError::EdnParseError(error)
}
}
impl From<mentat_db::DbError> for MentatError {
fn from(error: mentat_db::DbError) -> MentatError {
MentatError::DbError(error)
}
}
impl From<mentat_query_algebrizer::AlgebrizerError> for MentatError {
fn from(error: mentat_query_algebrizer::AlgebrizerError) -> MentatError {
MentatError::AlgebrizerError(error)
}
}
impl From<mentat_query_projector::ProjectorError> for MentatError {
fn from(error: mentat_query_projector::ProjectorError) -> MentatError {
MentatError::ProjectorError(error)
}
}
impl From<mentat_query_pull::PullError> for MentatError {
fn from(error: mentat_query_pull::PullError) -> MentatError {
MentatError::PullError(error)
}
}
impl From<mentat_sql::SQLError> for MentatError {
fn from(error: mentat_sql::SQLError) -> MentatError {
MentatError::SQLError(error)
}
}
#[cfg(feature = "syncable")]
impl From<mentat_tolstoy::TolstoyError> for MentatError {
fn from(error: mentat_tolstoy::TolstoyError) -> MentatError {
MentatError::TolstoyError(error)
}
}
| MentatError | identifier_name |
errors.rs | // Copyright 2016 Mozilla
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#![allow(dead_code)]
use std; // To refer to std::result::Result.
use std::collections::BTreeSet;
use rusqlite;
use edn;
use mentat_core::{
Attribute,
ValueType,
};
use mentat_db;
use mentat_query;
use mentat_query_algebrizer;
use mentat_query_projector;
use mentat_query_pull;
use mentat_sql;
#[cfg(feature = "syncable")]
use mentat_tolstoy;
pub type Result<T> = std::result::Result<T, MentatError>;
#[macro_export]
macro_rules! bail {
($e:expr) => (
return Err($e.into());
)
}
#[derive(Debug, Fail)]
pub enum MentatError {
#[fail(display = "bad uuid {}", _0)]
BadUuid(String),
#[fail(display = "path {} already exists", _0)]
PathAlreadyExists(String),
#[fail(display = "variables {:?} unbound at query execution time", _0)]
UnboundVariables(BTreeSet<String>),
#[fail(display = "invalid argument name: '{}'", _0)]
InvalidArgumentName(String),
#[fail(display = "unknown attribute: '{}'", _0)]
UnknownAttribute(String),
#[fail(display = "invalid vocabulary version")]
InvalidVocabularyVersion,
#[fail(display = "vocabulary {}/{} already has attribute {}, and the requested definition differs", _0, _1, _2)]
ConflictingAttributeDefinitions(String, ::vocabulary::Version, String, Attribute, Attribute),
#[fail(display = "existing vocabulary {} too new: wanted {}, got {}", _0, _1, _2)]
ExistingVocabularyTooNew(String, ::vocabulary::Version, ::vocabulary::Version),
#[fail(display = "core schema: wanted {}, got {:?}", _0, _1)]
UnexpectedCoreSchema(::vocabulary::Version, Option<::vocabulary::Version>),
#[fail(display = "Lost the transact() race!")]
UnexpectedLostTransactRace,
#[fail(display = "missing core attribute {}", _0)]
MissingCoreVocabulary(mentat_query::Keyword),
#[fail(display = "schema changed since query was prepared")]
PreparedQuerySchemaMismatch,
#[fail(display = "provided value of type {} doesn't match attribute value type {}", _0, _1)]
ValueTypeMismatch(ValueType, ValueType),
#[fail(display = "{}", _0)]
IoError(#[cause] std::io::Error),
// It would be better to capture the underlying `rusqlite::Error`, but that type doesn't
// implement many useful traits, including `Clone`, `Eq`, and `PartialEq`.
#[fail(display = "SQL error: {}", _0)]
RusqliteError(String),
#[fail(display = "{}", _0)]
EdnParseError(#[cause] edn::ParseError),
#[fail(display = "{}", _0)]
DbError(#[cause] mentat_db::DbError),
#[fail(display = "{}", _0)]
AlgebrizerError(#[cause] mentat_query_algebrizer::AlgebrizerError),
#[fail(display = "{}", _0)]
ProjectorError(#[cause] mentat_query_projector::ProjectorError),
#[fail(display = "{}", _0)]
PullError(#[cause] mentat_query_pull::PullError),
#[fail(display = "{}", _0)]
SQLError(#[cause] mentat_sql::SQLError),
#[cfg(feature = "syncable")]
#[fail(display = "{}", _0)]
TolstoyError(#[cause] mentat_tolstoy::TolstoyError),
}
impl From<std::io::Error> for MentatError {
fn from(error: std::io::Error) -> MentatError {
MentatError::IoError(error)
}
}
impl From<rusqlite::Error> for MentatError {
fn from(error: rusqlite::Error) -> MentatError {
MentatError::RusqliteError(error.to_string())
} | }
impl From<edn::ParseError> for MentatError {
fn from(error: edn::ParseError) -> MentatError {
MentatError::EdnParseError(error)
}
}
impl From<mentat_db::DbError> for MentatError {
fn from(error: mentat_db::DbError) -> MentatError {
MentatError::DbError(error)
}
}
impl From<mentat_query_algebrizer::AlgebrizerError> for MentatError {
fn from(error: mentat_query_algebrizer::AlgebrizerError) -> MentatError {
MentatError::AlgebrizerError(error)
}
}
impl From<mentat_query_projector::ProjectorError> for MentatError {
fn from(error: mentat_query_projector::ProjectorError) -> MentatError {
MentatError::ProjectorError(error)
}
}
impl From<mentat_query_pull::PullError> for MentatError {
fn from(error: mentat_query_pull::PullError) -> MentatError {
MentatError::PullError(error)
}
}
impl From<mentat_sql::SQLError> for MentatError {
fn from(error: mentat_sql::SQLError) -> MentatError {
MentatError::SQLError(error)
}
}
#[cfg(feature = "syncable")]
impl From<mentat_tolstoy::TolstoyError> for MentatError {
fn from(error: mentat_tolstoy::TolstoyError) -> MentatError {
MentatError::TolstoyError(error)
}
} | random_line_split |
|
error.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt::Display;
use std::io;
use std::num::ParseFloatError;
use std::str::Utf8Error;
use std::string::FromUtf8Error;
use std::{error, str};
use error_code::{self, ErrorCode, ErrorCodeExt};
use quick_error::quick_error;
use regex::Error as RegexpError;
use serde_json::error::Error as SerdeError;
use tidb_query_common::error::EvaluateError;
use tipb::{self, ScalarFuncSig};
pub const ERR_M_BIGGER_THAN_D: i32 = 1427;
pub const ERR_UNKNOWN: i32 = 1105;
pub const ERR_REGEXP: i32 = 1139;
pub const ZLIB_LENGTH_CORRUPTED: i32 = 1258;
pub const ZLIB_DATA_CORRUPTED: i32 = 1259;
pub const WARN_DATA_TRUNCATED: i32 = 1265;
pub const ERR_TRUNCATE_WRONG_VALUE: i32 = 1292;
pub const ERR_UNKNOWN_TIMEZONE: i32 = 1298;
pub const ERR_DIVISION_BY_ZERO: i32 = 1365;
pub const ERR_DATA_TOO_LONG: i32 = 1406;
pub const ERR_INCORRECT_PARAMETERS: i32 = 1583;
pub const ERR_DATA_OUT_OF_RANGE: i32 = 1690;
quick_error! {
#[derive(Debug)]
pub enum Error {
InvalidDataType(reason: String) {
display("invalid data type: {}", reason)
}
Encoding(err: Utf8Error) {
from()
cause(err)
display("encoding failed")
}
ColumnOffset(offset: usize) {
display("illegal column offset: {}", offset)
}
UnknownSignature(sig: ScalarFuncSig) {
display("Unknown signature: {:?}", sig)
}
Eval(s: String, code:i32) {
display("evaluation failed: {}", s)
}
Other(err: Box<dyn error::Error + Send + Sync>) {
from()
cause(err.as_ref())
display("{}", err)
}
}
}
impl Error {
pub fn overflow(data: impl Display, expr: impl Display) -> Error {
let msg = format!("{} value is out of range in '{}'", data, expr);
Error::Eval(msg, ERR_DATA_OUT_OF_RANGE)
}
pub fn truncated_wrong_val(data_type: impl Display, val: impl Display) -> Error {
let msg = format!("Truncated incorrect {} value: '{}'", data_type, val);
Error::Eval(msg, ERR_TRUNCATE_WRONG_VALUE)
}
pub fn truncated() -> Error {
Error::Eval("Data Truncated".into(), WARN_DATA_TRUNCATED)
}
pub fn m_bigger_than_d(column: impl Display) -> Error {
let msg = format!(
"For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column {}').",
column
);
Error::Eval(msg, ERR_M_BIGGER_THAN_D)
}
pub fn cast_neg_int_as_unsigned() -> Error {
let msg = "Cast to unsigned converted negative integer to it's positive complement";
Error::Eval(msg.into(), ERR_UNKNOWN)
}
pub fn cast_as_signed_overflow() -> Error {
let msg =
"Cast to signed converted positive out-of-range integer to it's negative complement";
Error::Eval(msg.into(), ERR_UNKNOWN)
}
pub fn invalid_timezone(given_time_zone: impl Display) -> Error {
let msg = format!("unknown or incorrect time zone: {}", given_time_zone);
Error::Eval(msg, ERR_UNKNOWN_TIMEZONE)
}
pub fn division_by_zero() -> Error {
let msg = "Division by 0";
Error::Eval(msg.into(), ERR_DIVISION_BY_ZERO)
}
pub fn data_too_long(msg: String) -> Error {
if msg.is_empty() {
Error::Eval("Data Too Long".into(), ERR_DATA_TOO_LONG)
} else {
Error::Eval(msg, ERR_DATA_TOO_LONG)
}
}
pub fn code(&self) -> i32 {
match *self {
Error::Eval(_, code) => code,
_ => ERR_UNKNOWN,
}
}
pub fn is_overflow(&self) -> bool {
self.code() == ERR_DATA_OUT_OF_RANGE
}
pub fn is_truncated(&self) -> bool {
self.code() == ERR_TRUNCATE_WRONG_VALUE
}
pub fn unexpected_eof() -> Error {
tikv_util::codec::Error::unexpected_eof().into()
}
pub fn invalid_time_format(val: impl Display) -> Error {
let msg = format!("invalid time format: '{}'", val);
Error::Eval(msg, ERR_TRUNCATE_WRONG_VALUE)
}
pub fn incorrect_datetime_value(val: impl Display) -> Error {
let msg = format!("Incorrect datetime value: '{}'", val);
Error::Eval(msg, ERR_TRUNCATE_WRONG_VALUE)
}
pub fn zlib_length_corrupted() -> Error {
let msg = "ZLIB: Not enough room in the output buffer (probably, length of uncompressed data was corrupted)";
Error::Eval(msg.into(), ZLIB_LENGTH_CORRUPTED)
}
pub fn zlib_data_corrupted() -> Error {
Error::Eval("ZLIB: Input data corrupted".into(), ZLIB_DATA_CORRUPTED)
}
pub fn incorrect_parameters(val: &str) -> Error {
let msg = format!(
"Incorrect parameters in the call to native function '{}'",
val
);
Error::Eval(msg, ERR_INCORRECT_PARAMETERS)
}
}
impl From<Error> for tipb::Error {
fn from(error: Error) -> tipb::Error {
let mut err = tipb::Error::default();
err.set_code(error.code());
err.set_msg(error.to_string());
err
}
}
impl From<FromUtf8Error> for Error {
fn from(err: FromUtf8Error) -> Error { | Error::Encoding(err.utf8_error())
}
}
impl From<SerdeError> for Error {
fn from(err: SerdeError) -> Error {
box_err!("serde:{:?}", err)
}
}
impl From<ParseFloatError> for Error {
fn from(err: ParseFloatError) -> Error {
box_err!("parse float: {:?}", err)
}
}
impl From<tikv_util::codec::Error> for Error {
fn from(err: tikv_util::codec::Error) -> Error {
box_err!("codec:{:?}", err)
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
let uerr: tikv_util::codec::Error = err.into();
uerr.into()
}
}
impl From<RegexpError> for Error {
fn from(err: RegexpError) -> Error {
let msg = format!("Got error '{:.64}' from regexp", err);
Error::Eval(msg, ERR_REGEXP)
}
}
impl From<codec::Error> for Error {
fn from(err: codec::Error) -> Error {
box_err!("Codec: {}", err)
}
}
impl From<crate::DataTypeError> for Error {
fn from(err: crate::DataTypeError) -> Self {
box_err!("invalid schema: {:?}", err)
}
}
// TODO: `codec::Error` should be substituted by EvaluateError.
impl From<Error> for EvaluateError {
#[inline]
fn from(err: Error) -> Self {
match err {
Error::Eval(msg, code) => EvaluateError::Custom { code, msg },
e => EvaluateError::Other(e.to_string()),
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
impl ErrorCodeExt for Error {
fn error_code(&self) -> ErrorCode {
match self {
Error::InvalidDataType(_) => error_code::coprocessor::INVALID_DATA_TYPE,
Error::Encoding(_) => error_code::coprocessor::ENCODING,
Error::ColumnOffset(_) => error_code::coprocessor::COLUMN_OFFSET,
Error::UnknownSignature(_) => error_code::coprocessor::UNKNOWN_SIGNATURE,
Error::Eval(_, _) => error_code::coprocessor::EVAL,
Error::Other(_) => error_code::UNKNOWN,
}
}
} | random_line_split |
|
error.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt::Display;
use std::io;
use std::num::ParseFloatError;
use std::str::Utf8Error;
use std::string::FromUtf8Error;
use std::{error, str};
use error_code::{self, ErrorCode, ErrorCodeExt};
use quick_error::quick_error;
use regex::Error as RegexpError;
use serde_json::error::Error as SerdeError;
use tidb_query_common::error::EvaluateError;
use tipb::{self, ScalarFuncSig};
pub const ERR_M_BIGGER_THAN_D: i32 = 1427;
pub const ERR_UNKNOWN: i32 = 1105;
pub const ERR_REGEXP: i32 = 1139;
pub const ZLIB_LENGTH_CORRUPTED: i32 = 1258;
pub const ZLIB_DATA_CORRUPTED: i32 = 1259;
pub const WARN_DATA_TRUNCATED: i32 = 1265;
pub const ERR_TRUNCATE_WRONG_VALUE: i32 = 1292;
pub const ERR_UNKNOWN_TIMEZONE: i32 = 1298;
pub const ERR_DIVISION_BY_ZERO: i32 = 1365;
pub const ERR_DATA_TOO_LONG: i32 = 1406;
pub const ERR_INCORRECT_PARAMETERS: i32 = 1583;
pub const ERR_DATA_OUT_OF_RANGE: i32 = 1690;
quick_error! {
#[derive(Debug)]
pub enum Error {
InvalidDataType(reason: String) {
display("invalid data type: {}", reason)
}
Encoding(err: Utf8Error) {
from()
cause(err)
display("encoding failed")
}
ColumnOffset(offset: usize) {
display("illegal column offset: {}", offset)
}
UnknownSignature(sig: ScalarFuncSig) {
display("Unknown signature: {:?}", sig)
}
Eval(s: String, code:i32) {
display("evaluation failed: {}", s)
}
Other(err: Box<dyn error::Error + Send + Sync>) {
from()
cause(err.as_ref())
display("{}", err)
}
}
}
impl Error {
pub fn overflow(data: impl Display, expr: impl Display) -> Error {
let msg = format!("{} value is out of range in '{}'", data, expr);
Error::Eval(msg, ERR_DATA_OUT_OF_RANGE)
}
pub fn truncated_wrong_val(data_type: impl Display, val: impl Display) -> Error {
let msg = format!("Truncated incorrect {} value: '{}'", data_type, val);
Error::Eval(msg, ERR_TRUNCATE_WRONG_VALUE)
}
pub fn truncated() -> Error {
Error::Eval("Data Truncated".into(), WARN_DATA_TRUNCATED)
}
pub fn m_bigger_than_d(column: impl Display) -> Error {
let msg = format!(
"For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column {}').",
column
);
Error::Eval(msg, ERR_M_BIGGER_THAN_D)
}
pub fn cast_neg_int_as_unsigned() -> Error {
let msg = "Cast to unsigned converted negative integer to it's positive complement";
Error::Eval(msg.into(), ERR_UNKNOWN)
}
pub fn cast_as_signed_overflow() -> Error |
pub fn invalid_timezone(given_time_zone: impl Display) -> Error {
let msg = format!("unknown or incorrect time zone: {}", given_time_zone);
Error::Eval(msg, ERR_UNKNOWN_TIMEZONE)
}
pub fn division_by_zero() -> Error {
let msg = "Division by 0";
Error::Eval(msg.into(), ERR_DIVISION_BY_ZERO)
}
pub fn data_too_long(msg: String) -> Error {
if msg.is_empty() {
Error::Eval("Data Too Long".into(), ERR_DATA_TOO_LONG)
} else {
Error::Eval(msg, ERR_DATA_TOO_LONG)
}
}
pub fn code(&self) -> i32 {
match *self {
Error::Eval(_, code) => code,
_ => ERR_UNKNOWN,
}
}
pub fn is_overflow(&self) -> bool {
self.code() == ERR_DATA_OUT_OF_RANGE
}
pub fn is_truncated(&self) -> bool {
self.code() == ERR_TRUNCATE_WRONG_VALUE
}
pub fn unexpected_eof() -> Error {
tikv_util::codec::Error::unexpected_eof().into()
}
pub fn invalid_time_format(val: impl Display) -> Error {
let msg = format!("invalid time format: '{}'", val);
Error::Eval(msg, ERR_TRUNCATE_WRONG_VALUE)
}
pub fn incorrect_datetime_value(val: impl Display) -> Error {
let msg = format!("Incorrect datetime value: '{}'", val);
Error::Eval(msg, ERR_TRUNCATE_WRONG_VALUE)
}
pub fn zlib_length_corrupted() -> Error {
let msg = "ZLIB: Not enough room in the output buffer (probably, length of uncompressed data was corrupted)";
Error::Eval(msg.into(), ZLIB_LENGTH_CORRUPTED)
}
pub fn zlib_data_corrupted() -> Error {
Error::Eval("ZLIB: Input data corrupted".into(), ZLIB_DATA_CORRUPTED)
}
pub fn incorrect_parameters(val: &str) -> Error {
let msg = format!(
"Incorrect parameters in the call to native function '{}'",
val
);
Error::Eval(msg, ERR_INCORRECT_PARAMETERS)
}
}
impl From<Error> for tipb::Error {
fn from(error: Error) -> tipb::Error {
let mut err = tipb::Error::default();
err.set_code(error.code());
err.set_msg(error.to_string());
err
}
}
impl From<FromUtf8Error> for Error {
fn from(err: FromUtf8Error) -> Error {
Error::Encoding(err.utf8_error())
}
}
impl From<SerdeError> for Error {
fn from(err: SerdeError) -> Error {
box_err!("serde:{:?}", err)
}
}
impl From<ParseFloatError> for Error {
fn from(err: ParseFloatError) -> Error {
box_err!("parse float: {:?}", err)
}
}
impl From<tikv_util::codec::Error> for Error {
fn from(err: tikv_util::codec::Error) -> Error {
box_err!("codec:{:?}", err)
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
let uerr: tikv_util::codec::Error = err.into();
uerr.into()
}
}
impl From<RegexpError> for Error {
fn from(err: RegexpError) -> Error {
let msg = format!("Got error '{:.64}' from regexp", err);
Error::Eval(msg, ERR_REGEXP)
}
}
impl From<codec::Error> for Error {
fn from(err: codec::Error) -> Error {
box_err!("Codec: {}", err)
}
}
impl From<crate::DataTypeError> for Error {
fn from(err: crate::DataTypeError) -> Self {
box_err!("invalid schema: {:?}", err)
}
}
// TODO: `codec::Error` should be substituted by EvaluateError.
impl From<Error> for EvaluateError {
#[inline]
fn from(err: Error) -> Self {
match err {
Error::Eval(msg, code) => EvaluateError::Custom { code, msg },
e => EvaluateError::Other(e.to_string()),
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
impl ErrorCodeExt for Error {
fn error_code(&self) -> ErrorCode {
match self {
Error::InvalidDataType(_) => error_code::coprocessor::INVALID_DATA_TYPE,
Error::Encoding(_) => error_code::coprocessor::ENCODING,
Error::ColumnOffset(_) => error_code::coprocessor::COLUMN_OFFSET,
Error::UnknownSignature(_) => error_code::coprocessor::UNKNOWN_SIGNATURE,
Error::Eval(_, _) => error_code::coprocessor::EVAL,
Error::Other(_) => error_code::UNKNOWN,
}
}
}
| {
let msg =
"Cast to signed converted positive out-of-range integer to it's negative complement";
Error::Eval(msg.into(), ERR_UNKNOWN)
} | identifier_body |
error.rs | // Copyright 2017 TiKV Project Authors. Licensed under Apache-2.0.
use std::fmt::Display;
use std::io;
use std::num::ParseFloatError;
use std::str::Utf8Error;
use std::string::FromUtf8Error;
use std::{error, str};
use error_code::{self, ErrorCode, ErrorCodeExt};
use quick_error::quick_error;
use regex::Error as RegexpError;
use serde_json::error::Error as SerdeError;
use tidb_query_common::error::EvaluateError;
use tipb::{self, ScalarFuncSig};
pub const ERR_M_BIGGER_THAN_D: i32 = 1427;
pub const ERR_UNKNOWN: i32 = 1105;
pub const ERR_REGEXP: i32 = 1139;
pub const ZLIB_LENGTH_CORRUPTED: i32 = 1258;
pub const ZLIB_DATA_CORRUPTED: i32 = 1259;
pub const WARN_DATA_TRUNCATED: i32 = 1265;
pub const ERR_TRUNCATE_WRONG_VALUE: i32 = 1292;
pub const ERR_UNKNOWN_TIMEZONE: i32 = 1298;
pub const ERR_DIVISION_BY_ZERO: i32 = 1365;
pub const ERR_DATA_TOO_LONG: i32 = 1406;
pub const ERR_INCORRECT_PARAMETERS: i32 = 1583;
pub const ERR_DATA_OUT_OF_RANGE: i32 = 1690;
quick_error! {
#[derive(Debug)]
pub enum Error {
InvalidDataType(reason: String) {
display("invalid data type: {}", reason)
}
Encoding(err: Utf8Error) {
from()
cause(err)
display("encoding failed")
}
ColumnOffset(offset: usize) {
display("illegal column offset: {}", offset)
}
UnknownSignature(sig: ScalarFuncSig) {
display("Unknown signature: {:?}", sig)
}
Eval(s: String, code:i32) {
display("evaluation failed: {}", s)
}
Other(err: Box<dyn error::Error + Send + Sync>) {
from()
cause(err.as_ref())
display("{}", err)
}
}
}
impl Error {
pub fn overflow(data: impl Display, expr: impl Display) -> Error {
let msg = format!("{} value is out of range in '{}'", data, expr);
Error::Eval(msg, ERR_DATA_OUT_OF_RANGE)
}
pub fn truncated_wrong_val(data_type: impl Display, val: impl Display) -> Error {
let msg = format!("Truncated incorrect {} value: '{}'", data_type, val);
Error::Eval(msg, ERR_TRUNCATE_WRONG_VALUE)
}
pub fn truncated() -> Error {
Error::Eval("Data Truncated".into(), WARN_DATA_TRUNCATED)
}
pub fn m_bigger_than_d(column: impl Display) -> Error {
let msg = format!(
"For float(M,D), double(M,D) or decimal(M,D), M must be >= D (column {}').",
column
);
Error::Eval(msg, ERR_M_BIGGER_THAN_D)
}
pub fn cast_neg_int_as_unsigned() -> Error {
let msg = "Cast to unsigned converted negative integer to it's positive complement";
Error::Eval(msg.into(), ERR_UNKNOWN)
}
pub fn cast_as_signed_overflow() -> Error {
let msg =
"Cast to signed converted positive out-of-range integer to it's negative complement";
Error::Eval(msg.into(), ERR_UNKNOWN)
}
pub fn invalid_timezone(given_time_zone: impl Display) -> Error {
let msg = format!("unknown or incorrect time zone: {}", given_time_zone);
Error::Eval(msg, ERR_UNKNOWN_TIMEZONE)
}
pub fn division_by_zero() -> Error {
let msg = "Division by 0";
Error::Eval(msg.into(), ERR_DIVISION_BY_ZERO)
}
pub fn data_too_long(msg: String) -> Error {
if msg.is_empty() {
Error::Eval("Data Too Long".into(), ERR_DATA_TOO_LONG)
} else {
Error::Eval(msg, ERR_DATA_TOO_LONG)
}
}
pub fn code(&self) -> i32 {
match *self {
Error::Eval(_, code) => code,
_ => ERR_UNKNOWN,
}
}
pub fn is_overflow(&self) -> bool {
self.code() == ERR_DATA_OUT_OF_RANGE
}
pub fn is_truncated(&self) -> bool {
self.code() == ERR_TRUNCATE_WRONG_VALUE
}
pub fn unexpected_eof() -> Error {
tikv_util::codec::Error::unexpected_eof().into()
}
pub fn invalid_time_format(val: impl Display) -> Error {
let msg = format!("invalid time format: '{}'", val);
Error::Eval(msg, ERR_TRUNCATE_WRONG_VALUE)
}
pub fn incorrect_datetime_value(val: impl Display) -> Error {
let msg = format!("Incorrect datetime value: '{}'", val);
Error::Eval(msg, ERR_TRUNCATE_WRONG_VALUE)
}
pub fn zlib_length_corrupted() -> Error {
let msg = "ZLIB: Not enough room in the output buffer (probably, length of uncompressed data was corrupted)";
Error::Eval(msg.into(), ZLIB_LENGTH_CORRUPTED)
}
pub fn zlib_data_corrupted() -> Error {
Error::Eval("ZLIB: Input data corrupted".into(), ZLIB_DATA_CORRUPTED)
}
pub fn incorrect_parameters(val: &str) -> Error {
let msg = format!(
"Incorrect parameters in the call to native function '{}'",
val
);
Error::Eval(msg, ERR_INCORRECT_PARAMETERS)
}
}
impl From<Error> for tipb::Error {
fn | (error: Error) -> tipb::Error {
let mut err = tipb::Error::default();
err.set_code(error.code());
err.set_msg(error.to_string());
err
}
}
impl From<FromUtf8Error> for Error {
fn from(err: FromUtf8Error) -> Error {
Error::Encoding(err.utf8_error())
}
}
impl From<SerdeError> for Error {
fn from(err: SerdeError) -> Error {
box_err!("serde:{:?}", err)
}
}
impl From<ParseFloatError> for Error {
fn from(err: ParseFloatError) -> Error {
box_err!("parse float: {:?}", err)
}
}
impl From<tikv_util::codec::Error> for Error {
fn from(err: tikv_util::codec::Error) -> Error {
box_err!("codec:{:?}", err)
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
let uerr: tikv_util::codec::Error = err.into();
uerr.into()
}
}
impl From<RegexpError> for Error {
fn from(err: RegexpError) -> Error {
let msg = format!("Got error '{:.64}' from regexp", err);
Error::Eval(msg, ERR_REGEXP)
}
}
impl From<codec::Error> for Error {
fn from(err: codec::Error) -> Error {
box_err!("Codec: {}", err)
}
}
impl From<crate::DataTypeError> for Error {
fn from(err: crate::DataTypeError) -> Self {
box_err!("invalid schema: {:?}", err)
}
}
// TODO: `codec::Error` should be substituted by EvaluateError.
impl From<Error> for EvaluateError {
#[inline]
fn from(err: Error) -> Self {
match err {
Error::Eval(msg, code) => EvaluateError::Custom { code, msg },
e => EvaluateError::Other(e.to_string()),
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
impl ErrorCodeExt for Error {
fn error_code(&self) -> ErrorCode {
match self {
Error::InvalidDataType(_) => error_code::coprocessor::INVALID_DATA_TYPE,
Error::Encoding(_) => error_code::coprocessor::ENCODING,
Error::ColumnOffset(_) => error_code::coprocessor::COLUMN_OFFSET,
Error::UnknownSignature(_) => error_code::coprocessor::UNKNOWN_SIGNATURE,
Error::Eval(_, _) => error_code::coprocessor::EVAL,
Error::Other(_) => error_code::UNKNOWN,
}
}
}
| from | identifier_name |
cycle-trait-type-trait.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.
// run-pass
#![allow(dead_code)]
// Test a case where a supertrait references a type that references
// the original trait. This poses no problem at the moment.
// pretty-expanded FIXME #23616
trait Chromosome: Get<Struct<i32>> {
}
trait Get<A> {
fn get(&self) -> A;
}
struct Struct<C:Chromosome> { c: C }
impl Chromosome for i32 { }
impl Get<Struct<i32>> for i32 {
fn get(&self) -> Struct<i32> {
Struct { c: *self }
}
}
fn main() | { } | identifier_body |
|
cycle-trait-type-trait.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.
// run-pass
#![allow(dead_code)]
// Test a case where a supertrait references a type that references
// the original trait. This poses no problem at the moment.
// pretty-expanded FIXME #23616
trait Chromosome: Get<Struct<i32>> {
}
trait Get<A> {
fn get(&self) -> A;
}
struct Struct<C:Chromosome> { c: C }
impl Chromosome for i32 { }
impl Get<Struct<i32>> for i32 {
fn | (&self) -> Struct<i32> {
Struct { c: *self }
}
}
fn main() { }
| get | identifier_name |
cycle-trait-type-trait.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.
// run-pass
#![allow(dead_code)]
// Test a case where a supertrait references a type that references
// the original trait. This poses no problem at the moment.
// pretty-expanded FIXME #23616
trait Chromosome: Get<Struct<i32>> {
}
trait Get<A> {
fn get(&self) -> A;
}
struct Struct<C:Chromosome> { c: C }
impl Chromosome for i32 { }
impl Get<Struct<i32>> for i32 {
fn get(&self) -> Struct<i32> {
Struct { c: *self }
}
}
fn main() { } | // 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.
// | random_line_split |
|
meg_csar_list.rs | extern crate megam_api;
extern crate term_painter;
extern crate toml;
extern crate rustc_serialize;
extern crate megam_rustyprint;
use self::megam_rustyprint::Printer;
use self::megam_api::api::Api;
use self::megam_api::util::csars::Csar;
use self::rustc_serialize::json;
use self::term_painter::ToStyle;
use self::term_painter::Color::*;
use util::header_hash as head;
pub struct | ;
impl Csaroptions {
pub fn list(&self) {
let opts = Csar::new();
let api_call = head::api_call().unwrap();
let out = opts.list(json::encode(&api_call).unwrap());
match out {
Ok(v) => {
println!("{}",
Green.bold().paint("CSARs\n"));
let mut a = Printer::new();
let mut header = Vec::new();
header.push("Id".to_string());
header.push("Description".to_string());
header.push("Created at".to_string());
a.set_header(header);
let mut parent = Vec::new();
for x in v.iter() {
let mut child = Vec::new();
child.push(x.link.to_string());
child.push(x.desc.to_string());
child.push(x.created_at.to_string());
parent.push(child);
}
a.set_body(parent);
println!("{:?}", a);
}
Err(e) => {
println!("{}",
Red.bold().paint("Not listing your CSARs You sure you created them?. Contact [email protected]"));
}
}}
}
| Csaroptions | identifier_name |
meg_csar_list.rs | extern crate megam_api;
extern crate term_painter;
extern crate toml;
extern crate rustc_serialize;
extern crate megam_rustyprint;
use self::megam_rustyprint::Printer;
use self::megam_api::api::Api;
use self::megam_api::util::csars::Csar;
use self::rustc_serialize::json;
use self::term_painter::ToStyle;
use self::term_painter::Color::*;
use util::header_hash as head;
pub struct Csaroptions;
impl Csaroptions {
pub fn list(&self) {
let opts = Csar::new();
let api_call = head::api_call().unwrap();
let out = opts.list(json::encode(&api_call).unwrap());
match out {
Ok(v) => {
println!("{}",
Green.bold().paint("CSARs\n"));
let mut a = Printer::new();
let mut header = Vec::new();
header.push("Id".to_string());
header.push("Description".to_string());
header.push("Created at".to_string());
a.set_header(header);
let mut parent = Vec::new();
|
let mut child = Vec::new();
child.push(x.link.to_string());
child.push(x.desc.to_string());
child.push(x.created_at.to_string());
parent.push(child);
}
a.set_body(parent);
println!("{:?}", a);
}
Err(e) => {
println!("{}",
Red.bold().paint("Not listing your CSARs You sure you created them?. Contact [email protected]"));
}
}}
} | for x in v.iter() { | random_line_split |
meg_csar_list.rs | extern crate megam_api;
extern crate term_painter;
extern crate toml;
extern crate rustc_serialize;
extern crate megam_rustyprint;
use self::megam_rustyprint::Printer;
use self::megam_api::api::Api;
use self::megam_api::util::csars::Csar;
use self::rustc_serialize::json;
use self::term_painter::ToStyle;
use self::term_painter::Color::*;
use util::header_hash as head;
pub struct Csaroptions;
impl Csaroptions {
pub fn list(&self) {
let opts = Csar::new();
let api_call = head::api_call().unwrap();
let out = opts.list(json::encode(&api_call).unwrap());
match out {
Ok(v) => {
println!("{}",
Green.bold().paint("CSARs\n"));
let mut a = Printer::new();
let mut header = Vec::new();
header.push("Id".to_string());
header.push("Description".to_string());
header.push("Created at".to_string());
a.set_header(header);
let mut parent = Vec::new();
for x in v.iter() {
let mut child = Vec::new();
child.push(x.link.to_string());
child.push(x.desc.to_string());
child.push(x.created_at.to_string());
parent.push(child);
}
a.set_body(parent);
println!("{:?}", a);
}
Err(e) => |
}}
}
| {
println!("{}",
Red.bold().paint("Not listing your CSARs You sure you created them? . Contact [email protected]"));
} | conditional_block |
main.rs | use std::collections::HashSet;
use std::env;
use std::error::Error;
use std::fs;
use std::iter::FromIterator;
fn main() {
run().unwrap();
}
fn get_lines() -> Vec<String> {
let args: Vec<String> = env::args().collect();
let default_fname = "input.txt".into();
let fname = args.get(1).unwrap_or(&default_fname);
let file_string = fs::read_to_string(fname).expect(&format!("Expected file named: {}", fname));
let lines: Vec<String> = file_string.trim().split("\n").map(|s| s.into()).collect();
lines
}
fn get_count<'a>(lines: impl Iterator<Item = &'a String>) -> [i32; 12] {
let mut positions = [0; 12];
for line in lines {
for (i, c) in line.chars().enumerate() {
positions[i] += if c == '1' { 1 } else { -1 }
}
}
positions
}
fn get_rate(lines: &Vec<String>, get_max: bool) -> Result<isize, Box<dyn Error>> {
let counts = get_count(lines.iter());
Ok(isize::from_str_radix(
&counts
.iter()
.map(|count| get_target(*count, get_max).to_string())
.collect::<Vec<_>>()
.join(""),
2,
)?)
}
fn get_rating(lines: &Vec<String>, get_max: bool) -> Result<isize, Box<dyn Error>> |
fn get_target(count: i32, is_max: bool) -> char {
if is_max {
if count >= 0 {
'1'
} else {
'0'
}
} else {
if count >= 0 {
'0'
} else {
'1'
}
}
}
fn run() -> Result<(), Box<dyn Error>> {
let lines = get_lines();
let gamma = get_rate(&lines, true)?;
let epsilon = get_rate(&lines, false)?;
println!("Part 1: {}*{}={}", gamma, epsilon, gamma * epsilon);
let oxygen = get_rating(&lines, true)?;
let c02 = get_rating(&lines, false)?;
println!("Part 2: {}*{}={}", oxygen, c02, oxygen * c02);
Ok(())
}
| {
let mut lines_set: HashSet<String> = HashSet::from_iter(lines.iter().cloned());
for i in 0..12 {
let count = get_count(lines_set.iter())[i];
for line in &lines_set.clone() {
let target = get_target(count, get_max);
if line.chars().nth(i).unwrap() != target {
lines_set.remove(line);
}
}
if lines_set.len() == 1 {
let result_string = &lines_set.iter().next().unwrap();
return Ok(isize::from_str_radix(result_string, 2)?);
}
}
return Ok(0);
} | identifier_body |
main.rs | use std::collections::HashSet;
use std::env;
use std::error::Error;
use std::fs;
use std::iter::FromIterator;
fn main() {
run().unwrap();
}
fn get_lines() -> Vec<String> {
let args: Vec<String> = env::args().collect();
let default_fname = "input.txt".into();
let fname = args.get(1).unwrap_or(&default_fname);
let file_string = fs::read_to_string(fname).expect(&format!("Expected file named: {}", fname));
let lines: Vec<String> = file_string.trim().split("\n").map(|s| s.into()).collect();
lines
}
fn get_count<'a>(lines: impl Iterator<Item = &'a String>) -> [i32; 12] {
let mut positions = [0; 12];
for line in lines {
for (i, c) in line.chars().enumerate() {
positions[i] += if c == '1' { 1 } else |
}
}
positions
}
fn get_rate(lines: &Vec<String>, get_max: bool) -> Result<isize, Box<dyn Error>> {
let counts = get_count(lines.iter());
Ok(isize::from_str_radix(
&counts
.iter()
.map(|count| get_target(*count, get_max).to_string())
.collect::<Vec<_>>()
.join(""),
2,
)?)
}
fn get_rating(lines: &Vec<String>, get_max: bool) -> Result<isize, Box<dyn Error>> {
let mut lines_set: HashSet<String> = HashSet::from_iter(lines.iter().cloned());
for i in 0..12 {
let count = get_count(lines_set.iter())[i];
for line in &lines_set.clone() {
let target = get_target(count, get_max);
if line.chars().nth(i).unwrap()!= target {
lines_set.remove(line);
}
}
if lines_set.len() == 1 {
let result_string = &lines_set.iter().next().unwrap();
return Ok(isize::from_str_radix(result_string, 2)?);
}
}
return Ok(0);
}
fn get_target(count: i32, is_max: bool) -> char {
if is_max {
if count >= 0 {
'1'
} else {
'0'
}
} else {
if count >= 0 {
'0'
} else {
'1'
}
}
}
fn run() -> Result<(), Box<dyn Error>> {
let lines = get_lines();
let gamma = get_rate(&lines, true)?;
let epsilon = get_rate(&lines, false)?;
println!("Part 1: {}*{}={}", gamma, epsilon, gamma * epsilon);
let oxygen = get_rating(&lines, true)?;
let c02 = get_rating(&lines, false)?;
println!("Part 2: {}*{}={}", oxygen, c02, oxygen * c02);
Ok(())
}
| { -1 } | conditional_block |
main.rs | use std::collections::HashSet;
use std::env;
use std::error::Error;
use std::fs;
use std::iter::FromIterator;
fn main() {
run().unwrap();
}
fn get_lines() -> Vec<String> {
let args: Vec<String> = env::args().collect();
let default_fname = "input.txt".into();
let fname = args.get(1).unwrap_or(&default_fname);
let file_string = fs::read_to_string(fname).expect(&format!("Expected file named: {}", fname));
let lines: Vec<String> = file_string.trim().split("\n").map(|s| s.into()).collect();
lines
}
fn get_count<'a>(lines: impl Iterator<Item = &'a String>) -> [i32; 12] {
let mut positions = [0; 12];
for line in lines {
for (i, c) in line.chars().enumerate() {
positions[i] += if c == '1' { 1 } else { -1 }
}
}
positions
}
fn | (lines: &Vec<String>, get_max: bool) -> Result<isize, Box<dyn Error>> {
let counts = get_count(lines.iter());
Ok(isize::from_str_radix(
&counts
.iter()
.map(|count| get_target(*count, get_max).to_string())
.collect::<Vec<_>>()
.join(""),
2,
)?)
}
fn get_rating(lines: &Vec<String>, get_max: bool) -> Result<isize, Box<dyn Error>> {
let mut lines_set: HashSet<String> = HashSet::from_iter(lines.iter().cloned());
for i in 0..12 {
let count = get_count(lines_set.iter())[i];
for line in &lines_set.clone() {
let target = get_target(count, get_max);
if line.chars().nth(i).unwrap()!= target {
lines_set.remove(line);
}
}
if lines_set.len() == 1 {
let result_string = &lines_set.iter().next().unwrap();
return Ok(isize::from_str_radix(result_string, 2)?);
}
}
return Ok(0);
}
fn get_target(count: i32, is_max: bool) -> char {
if is_max {
if count >= 0 {
'1'
} else {
'0'
}
} else {
if count >= 0 {
'0'
} else {
'1'
}
}
}
fn run() -> Result<(), Box<dyn Error>> {
let lines = get_lines();
let gamma = get_rate(&lines, true)?;
let epsilon = get_rate(&lines, false)?;
println!("Part 1: {}*{}={}", gamma, epsilon, gamma * epsilon);
let oxygen = get_rating(&lines, true)?;
let c02 = get_rating(&lines, false)?;
println!("Part 2: {}*{}={}", oxygen, c02, oxygen * c02);
Ok(())
}
| get_rate | identifier_name |
main.rs | use std::collections::HashSet;
use std::env;
use std::error::Error;
use std::fs;
use std::iter::FromIterator;
fn main() {
run().unwrap();
}
fn get_lines() -> Vec<String> {
let args: Vec<String> = env::args().collect();
let default_fname = "input.txt".into();
let fname = args.get(1).unwrap_or(&default_fname);
let file_string = fs::read_to_string(fname).expect(&format!("Expected file named: {}", fname));
let lines: Vec<String> = file_string.trim().split("\n").map(|s| s.into()).collect();
lines
}
fn get_count<'a>(lines: impl Iterator<Item = &'a String>) -> [i32; 12] {
let mut positions = [0; 12];
for line in lines {
for (i, c) in line.chars().enumerate() {
positions[i] += if c == '1' { 1 } else { -1 }
}
}
positions
}
fn get_rate(lines: &Vec<String>, get_max: bool) -> Result<isize, Box<dyn Error>> {
let counts = get_count(lines.iter());
Ok(isize::from_str_radix(
&counts
.iter()
.map(|count| get_target(*count, get_max).to_string())
.collect::<Vec<_>>()
.join(""),
2,
)?)
}
fn get_rating(lines: &Vec<String>, get_max: bool) -> Result<isize, Box<dyn Error>> {
let mut lines_set: HashSet<String> = HashSet::from_iter(lines.iter().cloned());
for i in 0..12 {
let count = get_count(lines_set.iter())[i];
for line in &lines_set.clone() {
let target = get_target(count, get_max);
if line.chars().nth(i).unwrap()!= target {
lines_set.remove(line);
}
}
if lines_set.len() == 1 {
let result_string = &lines_set.iter().next().unwrap();
return Ok(isize::from_str_radix(result_string, 2)?);
}
}
return Ok(0);
}
fn get_target(count: i32, is_max: bool) -> char { | if count >= 0 {
'1'
} else {
'0'
}
} else {
if count >= 0 {
'0'
} else {
'1'
}
}
}
fn run() -> Result<(), Box<dyn Error>> {
let lines = get_lines();
let gamma = get_rate(&lines, true)?;
let epsilon = get_rate(&lines, false)?;
println!("Part 1: {}*{}={}", gamma, epsilon, gamma * epsilon);
let oxygen = get_rating(&lines, true)?;
let c02 = get_rating(&lines, false)?;
println!("Part 2: {}*{}={}", oxygen, c02, oxygen * c02);
Ok(())
} | if is_max { | random_line_split |
TestNativeLog1p.rs | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh.
#pragma version(1) | }
float2 __attribute__((kernel)) testNativeLog1pFloat2Float2(float2 inV) {
return native_log1p(inV);
}
float3 __attribute__((kernel)) testNativeLog1pFloat3Float3(float3 inV) {
return native_log1p(inV);
}
float4 __attribute__((kernel)) testNativeLog1pFloat4Float4(float4 inV) {
return native_log1p(inV);
}
half __attribute__((kernel)) testNativeLog1pHalfHalf(half inV) {
return native_log1p(inV);
}
half2 __attribute__((kernel)) testNativeLog1pHalf2Half2(half2 inV) {
return native_log1p(inV);
}
half3 __attribute__((kernel)) testNativeLog1pHalf3Half3(half3 inV) {
return native_log1p(inV);
}
half4 __attribute__((kernel)) testNativeLog1pHalf4Half4(half4 inV) {
return native_log1p(inV);
} | #pragma rs java_package_name(android.renderscript.cts)
float __attribute__((kernel)) testNativeLog1pFloatFloat(float inV) {
return native_log1p(inV); | random_line_split |
issue-17302.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
static mut DROPPED: [bool,..2] = [false, false];
struct A(uint);
struct Foo { _a: A, _b: int }
impl Drop for A {
fn | (&mut self) {
let A(i) = *self;
unsafe { DROPPED[i] = true; }
}
}
fn main() {
{
Foo {
_a: A(0),
..Foo { _a: A(1), _b: 2 }
};
}
unsafe {
assert!(DROPPED[0]);
assert!(DROPPED[1]);
}
}
| drop | identifier_name |
issue-17302.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
static mut DROPPED: [bool,..2] = [false, false];
struct A(uint);
struct Foo { _a: A, _b: int }
impl Drop for A {
fn drop(&mut self) {
let A(i) = *self;
unsafe { DROPPED[i] = true; }
}
}
fn main() {
{
Foo {
_a: A(0),
..Foo { _a: A(1), _b: 2 }
};
}
unsafe {
assert!(DROPPED[0]);
assert!(DROPPED[1]);
} | } | random_line_split |
|
issue-17302.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
static mut DROPPED: [bool,..2] = [false, false];
struct A(uint);
struct Foo { _a: A, _b: int }
impl Drop for A {
fn drop(&mut self) {
let A(i) = *self;
unsafe { DROPPED[i] = true; }
}
}
fn main() | {
{
Foo {
_a: A(0),
..Foo { _a: A(1), _b: 2 }
};
}
unsafe {
assert!(DROPPED[0]);
assert!(DROPPED[1]);
}
} | identifier_body |
|
issue-10802.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct DroppableStruct;
enum DroppableEnum {
DroppableVariant1, DroppableVariant2
}
static mut DROPPED: bool = false;
impl Drop for DroppableStruct { | impl Drop for DroppableEnum {
fn drop(&mut self) {
unsafe { DROPPED = true; }
}
}
trait MyTrait { }
impl MyTrait for Box<DroppableStruct> {}
impl MyTrait for Box<DroppableEnum> {}
struct Whatever { w: Box<MyTrait+'static> }
impl Whatever {
fn new(w: Box<MyTrait+'static>) -> Whatever {
Whatever { w: w }
}
}
fn main() {
{
let f = box DroppableStruct;
let _a = Whatever::new(box f as Box<MyTrait>);
}
assert!(unsafe { DROPPED });
unsafe { DROPPED = false; }
{
let f = box DroppableEnum::DroppableVariant1;
let _a = Whatever::new(box f as Box<MyTrait>);
}
assert!(unsafe { DROPPED });
} | fn drop(&mut self) {
unsafe { DROPPED = true; }
}
} | random_line_split |
issue-10802.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct DroppableStruct;
enum DroppableEnum {
DroppableVariant1, DroppableVariant2
}
static mut DROPPED: bool = false;
impl Drop for DroppableStruct {
fn drop(&mut self) {
unsafe { DROPPED = true; }
}
}
impl Drop for DroppableEnum {
fn | (&mut self) {
unsafe { DROPPED = true; }
}
}
trait MyTrait { }
impl MyTrait for Box<DroppableStruct> {}
impl MyTrait for Box<DroppableEnum> {}
struct Whatever { w: Box<MyTrait+'static> }
impl Whatever {
fn new(w: Box<MyTrait+'static>) -> Whatever {
Whatever { w: w }
}
}
fn main() {
{
let f = box DroppableStruct;
let _a = Whatever::new(box f as Box<MyTrait>);
}
assert!(unsafe { DROPPED });
unsafe { DROPPED = false; }
{
let f = box DroppableEnum::DroppableVariant1;
let _a = Whatever::new(box f as Box<MyTrait>);
}
assert!(unsafe { DROPPED });
}
| drop | identifier_name |
issue-10802.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
struct DroppableStruct;
enum DroppableEnum {
DroppableVariant1, DroppableVariant2
}
static mut DROPPED: bool = false;
impl Drop for DroppableStruct {
fn drop(&mut self) {
unsafe { DROPPED = true; }
}
}
impl Drop for DroppableEnum {
fn drop(&mut self) |
}
trait MyTrait { }
impl MyTrait for Box<DroppableStruct> {}
impl MyTrait for Box<DroppableEnum> {}
struct Whatever { w: Box<MyTrait+'static> }
impl Whatever {
fn new(w: Box<MyTrait+'static>) -> Whatever {
Whatever { w: w }
}
}
fn main() {
{
let f = box DroppableStruct;
let _a = Whatever::new(box f as Box<MyTrait>);
}
assert!(unsafe { DROPPED });
unsafe { DROPPED = false; }
{
let f = box DroppableEnum::DroppableVariant1;
let _a = Whatever::new(box f as Box<MyTrait>);
}
assert!(unsafe { DROPPED });
}
| {
unsafe { DROPPED = true; }
} | identifier_body |
main.rs | extern crate rand;
use rand::{thread_rng, Rng};
use std::{thread, time};
use std::fmt;
#[derive(Clone)]
struct Memento {
money: u32,
fruits: Vec<String>,
}
impl Memento {
fn new(money: u32) -> Memento {
Memento {
money: money,
fruits: Vec::new(),
}
}
fn get_money(&self) -> u32 {
self.money
}
fn add_fruit(&mut self, fruit: String) {
self.fruits.push(fruit);
}
fn get_fruits(&self) -> Vec<String> {
self.fruits.clone()
}
}
struct Gamer {
money: u32,
fruits: Vec<String>,
rng: rand::ThreadRng,
}
impl Gamer {
fn new(money: u32) -> Gamer {
Gamer {
money: money,
fruits: Vec::new(),
rng: thread_rng(),
}
}
fn get_money(&self) -> u32 {
self.money
}
fn bet(&mut self) {
let dice = self.rng.gen_range(0, 7);
if dice == 1 {
self.money += 100;
println!("所持金が増えました。");
} else if dice == 2 {
self.money /= 2;
println!("所持金が半分になりました。");
} else if dice == 6 {
let f = self.get_fruit();
println!("フルーツ({})をもらいました。", f);
self.fruits.push(f);
} else {
println!("何も起こりませんでした。");
}
}
fn create_memento(&self) -> Memento {
let mut m = Memento::new(self.money);
| .fruits {
m.add_fruit(f.clone());
}
m
}
fn restore_memento(&mut self, memento: Memento) {
self.money = memento.get_money();
self.fruits = memento.get_fruits();
}
fn get_fruit(&mut self) -> String {
let mut prefix = "".to_string();
let coin = self.rng.gen_range(0, 1);
if coin == 0 {
prefix = "おいしい".to_string();
}
let fruits = ["リンゴ", "ぶどう", "バナナ", "みかん"];
let index = self.rng.gen_range(0, fruits.len());
format!("{}{}", prefix, fruits[index].to_string())
}
}
impl fmt::Display for Gamer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[money = {} + fruits = {:?}]", self.money, self.fruits)
}
}
fn main() {
let mut gamer = Gamer::new(100);
let mut memento = gamer.create_memento();
for i in 0..100 {
println!("===={}", i);
println!("現状:{}", gamer);
gamer.bet();
println!("所持金は{}円になりました。", gamer.get_money());
if gamer.get_money() > memento.get_money() {
println!(" (だいぶ増えたので、現在の状態を保存しておこう)");
memento = gamer.create_memento();
} else if gamer.get_money() < (memento.get_money() / 2) {
println!(" (だいぶ減ったので、以前の状態に復帰しよう)");
gamer.restore_memento(memento.clone());
}
thread::sleep(time::Duration::from_millis(1000));
println!();
}
}
| for f in &self | identifier_name |
main.rs | extern crate rand;
use rand::{thread_rng, Rng};
use std::{thread, time};
use std::fmt;
#[derive(Clone)]
struct Memento {
money: u32,
fruits: Vec<String>,
}
impl Memento {
fn new(money: u32) -> Memento {
Memento {
money: money,
fruits: Vec::new(),
}
}
fn get_money(&self) -> u32 {
self.money
}
fn add_fruit(&mut self, fruit: String) {
self.fruits.push(fruit);
}
fn get_fruits(&self) -> Vec<String> {
self.fruits.clone()
}
}
struct Gamer {
money: u32,
fruits: Vec<String>, |
impl Gamer {
fn new(money: u32) -> Gamer {
Gamer {
money: money,
fruits: Vec::new(),
rng: thread_rng(),
}
}
fn get_money(&self) -> u32 {
self.money
}
fn bet(&mut self) {
let dice = self.rng.gen_range(0, 7);
if dice == 1 {
self.money += 100;
println!("所持金が増えました。");
} else if dice == 2 {
self.money /= 2;
println!("所持金が半分になりました。");
} else if dice == 6 {
let f = self.get_fruit();
println!("フルーツ({})をもらいました。", f);
self.fruits.push(f);
} else {
println!("何も起こりませんでした。");
}
}
fn create_memento(&self) -> Memento {
let mut m = Memento::new(self.money);
for f in &self.fruits {
m.add_fruit(f.clone());
}
m
}
fn restore_memento(&mut self, memento: Memento) {
self.money = memento.get_money();
self.fruits = memento.get_fruits();
}
fn get_fruit(&mut self) -> String {
let mut prefix = "".to_string();
let coin = self.rng.gen_range(0, 1);
if coin == 0 {
prefix = "おいしい".to_string();
}
let fruits = ["リンゴ", "ぶどう", "バナナ", "みかん"];
let index = self.rng.gen_range(0, fruits.len());
format!("{}{}", prefix, fruits[index].to_string())
}
}
impl fmt::Display for Gamer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[money = {} + fruits = {:?}]", self.money, self.fruits)
}
}
fn main() {
let mut gamer = Gamer::new(100);
let mut memento = gamer.create_memento();
for i in 0..100 {
println!("===={}", i);
println!("現状:{}", gamer);
gamer.bet();
println!("所持金は{}円になりました。", gamer.get_money());
if gamer.get_money() > memento.get_money() {
println!(" (だいぶ増えたので、現在の状態を保存しておこう)");
memento = gamer.create_memento();
} else if gamer.get_money() < (memento.get_money() / 2) {
println!(" (だいぶ減ったので、以前の状態に復帰しよう)");
gamer.restore_memento(memento.clone());
}
thread::sleep(time::Duration::from_millis(1000));
println!();
}
} | rng: rand::ThreadRng,
} | random_line_split |
main.rs | extern crate rand;
use rand::{thread_rng, Rng};
use std::{thread, time};
use std::fmt;
#[derive(Clone)]
struct Memento {
money: u32,
fruits: Vec<String>,
}
impl Memento {
fn new(money: u32) -> Memento {
Memento {
money: money,
fruits: Vec::new(),
}
}
fn get_money(&self) -> u32 {
self.money
}
fn add_fruit(&mut self, fruit: String) {
self.fruits.push(fruit);
}
fn get_fruits(&self) -> Vec<String> {
self.fruits.clone()
}
}
struct Gamer {
money: u32,
fruits: Vec<String>,
rng: rand::ThreadRng,
}
impl Gamer {
fn new(money: u32) -> Gamer {
Gamer {
money: money,
fruits: Vec::new(),
rng: thread_rng(),
}
}
fn get_money(&self) -> u32 {
self.money
}
fn bet(&mut self) {
let dice = self.rng.gen_range(0, 7);
if dice == 1 {
self.money += 100;
println!("所持金が増えました。");
} else if dice == 2 {
self.money /= 2;
println!("所持金が半分になりました。");
} else if dice == 6 {
let f = self.get_fruit();
println!("フルーツ({})をもらいました。", f);
self.fruits.push(f);
} else {
println!("何も起こりませんでした。");
}
}
fn create_memento(&self) -> Memento {
let mut m = Memento::new(self.money);
for f in &self.fruits {
m.add_fruit(f.clone());
}
m
}
fn restore_memento(&mut self, memento: Memento) {
self.money = memento.get_money();
self.fruits = memento.get_fruits();
}
| n = self.rng.gen_range(0, 1);
if coin == 0 {
prefix = "おいしい".to_string();
}
let fruits = ["リンゴ", "ぶどう", "バナナ", "みかん"];
let index = self.rng.gen_range(0, fruits.len());
format!("{}{}", prefix, fruits[index].to_string())
}
}
impl fmt::Display for Gamer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[money = {} + fruits = {:?}]", self.money, self.fruits)
}
}
fn main() {
let mut gamer = Gamer::new(100);
let mut memento = gamer.create_memento();
for i in 0..100 {
println!("===={}", i);
println!("現状:{}", gamer);
gamer.bet();
println!("所持金は{}円になりました。", gamer.get_money());
if gamer.get_money() > memento.get_money() {
println!(" (だいぶ増えたので、現在の状態を保存しておこう)");
memento = gamer.create_memento();
} else if gamer.get_money() < (memento.get_money() / 2) {
println!(" (だいぶ減ったので、以前の状態に復帰しよう)");
gamer.restore_memento(memento.clone());
}
thread::sleep(time::Duration::from_millis(1000));
println!();
}
}
| fn get_fruit(&mut self) -> String {
let mut prefix = "".to_string();
let coi | identifier_body |
main.rs | extern crate rand;
use rand::{thread_rng, Rng};
use std::{thread, time};
use std::fmt;
#[derive(Clone)]
struct Memento {
money: u32,
fruits: Vec<String>,
}
impl Memento {
fn new(money: u32) -> Memento {
Memento {
money: money,
fruits: Vec::new(),
}
}
fn get_money(&self) -> u32 {
self.money
}
fn add_fruit(&mut self, fruit: String) {
self.fruits.push(fruit);
}
fn get_fruits(&self) -> Vec<String> {
self.fruits.clone()
}
}
struct Gamer {
money: u32,
fruits: Vec<String>,
rng: rand::ThreadRng,
}
impl Gamer {
fn new(money: u32) -> Gamer {
Gamer {
money: money,
fruits: Vec::new(),
rng: thread_rng(),
}
}
fn get_money(&self) -> u32 {
self.money
}
fn bet(&mut self) {
let dice = self.rng.gen_range(0, 7);
if dice == 1 {
self.money += 100;
println!("所持金が増えました。");
} else if dice == 2 {
self.m | get_fruit();
println!("フルーツ({})をもらいました。", f);
self.fruits.push(f);
} else {
println!("何も起こりませんでした。");
}
}
fn create_memento(&self) -> Memento {
let mut m = Memento::new(self.money);
for f in &self.fruits {
m.add_fruit(f.clone());
}
m
}
fn restore_memento(&mut self, memento: Memento) {
self.money = memento.get_money();
self.fruits = memento.get_fruits();
}
fn get_fruit(&mut self) -> String {
let mut prefix = "".to_string();
let coin = self.rng.gen_range(0, 1);
if coin == 0 {
prefix = "おいしい".to_string();
}
let fruits = ["リンゴ", "ぶどう", "バナナ", "みかん"];
let index = self.rng.gen_range(0, fruits.len());
format!("{}{}", prefix, fruits[index].to_string())
}
}
impl fmt::Display for Gamer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[money = {} + fruits = {:?}]", self.money, self.fruits)
}
}
fn main() {
let mut gamer = Gamer::new(100);
let mut memento = gamer.create_memento();
for i in 0..100 {
println!("===={}", i);
println!("現状:{}", gamer);
gamer.bet();
println!("所持金は{}円になりました。", gamer.get_money());
if gamer.get_money() > memento.get_money() {
println!(" (だいぶ増えたので、現在の状態を保存しておこう)");
memento = gamer.create_memento();
} else if gamer.get_money() < (memento.get_money() / 2) {
println!(" (だいぶ減ったので、以前の状態に復帰しよう)");
gamer.restore_memento(memento.clone());
}
thread::sleep(time::Duration::from_millis(1000));
println!();
}
}
| oney /= 2;
println!("所持金が半分になりました。");
} else if dice == 6 {
let f = self. | conditional_block |
errors.rs | use std::error;
use std::fmt;
#[derive(Debug)]
pub struct Error(ErrorKind);
#[derive(Debug)]
pub(crate) enum ErrorKind {
Raw(telegram_bot_raw::Error),
Hyper(hyper::Error),
Http(hyper::http::Error),
Io(std::io::Error),
InvalidMultipartFilename,
}
impl From<telegram_bot_raw::Error> for ErrorKind {
fn from(error: telegram_bot_raw::Error) -> Self {
ErrorKind::Raw(error)
}
}
impl From<hyper::Error> for ErrorKind {
fn from(error: hyper::Error) -> Self {
ErrorKind::Hyper(error)
}
} |
impl From<hyper::http::Error> for ErrorKind {
fn from(error: hyper::http::Error) -> Self {
ErrorKind::Http(error)
}
}
impl From<std::io::Error> for ErrorKind {
fn from(error: std::io::Error) -> Self {
ErrorKind::Io(error)
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
Error(kind)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
ErrorKind::Raw(error) => write!(f, "{}", error),
ErrorKind::Hyper(error) => write!(f, "{}", error),
ErrorKind::Http(error) => write!(f, "{}", error),
ErrorKind::Io(error) => write!(f, "{}", error),
ErrorKind::InvalidMultipartFilename => write!(f, "invalid multipart filename"),
}
}
}
impl error::Error for Error {} | random_line_split |
|
errors.rs | use std::error;
use std::fmt;
#[derive(Debug)]
pub struct Error(ErrorKind);
#[derive(Debug)]
pub(crate) enum ErrorKind {
Raw(telegram_bot_raw::Error),
Hyper(hyper::Error),
Http(hyper::http::Error),
Io(std::io::Error),
InvalidMultipartFilename,
}
impl From<telegram_bot_raw::Error> for ErrorKind {
fn | (error: telegram_bot_raw::Error) -> Self {
ErrorKind::Raw(error)
}
}
impl From<hyper::Error> for ErrorKind {
fn from(error: hyper::Error) -> Self {
ErrorKind::Hyper(error)
}
}
impl From<hyper::http::Error> for ErrorKind {
fn from(error: hyper::http::Error) -> Self {
ErrorKind::Http(error)
}
}
impl From<std::io::Error> for ErrorKind {
fn from(error: std::io::Error) -> Self {
ErrorKind::Io(error)
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
Error(kind)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
ErrorKind::Raw(error) => write!(f, "{}", error),
ErrorKind::Hyper(error) => write!(f, "{}", error),
ErrorKind::Http(error) => write!(f, "{}", error),
ErrorKind::Io(error) => write!(f, "{}", error),
ErrorKind::InvalidMultipartFilename => write!(f, "invalid multipart filename"),
}
}
}
impl error::Error for Error {}
| from | identifier_name |
mdbook.rs | use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::io::Write;
use std::error::Error;
use {BookConfig, BookItem, theme, parse, utils};
use book::BookItems;
use renderer::{Renderer, HtmlHandlebars};
use utils::{PathExt, create_path};
pub struct MDBook {
config: BookConfig,
pub content: Vec<BookItem>,
renderer: Box<Renderer>,
}
impl MDBook {
/// Create a new `MDBook` struct with root directory `root`
///
/// - The default source directory is set to `root/src`
/// - The default output directory is set to `root/book`
///
/// They can both be changed by using [`set_src()`](#method.set_src) and [`set_dest()`](#method.set_dest)
pub fn new(root: &Path) -> MDBook {
if!root.exists() ||!root.is_dir() {
output!("{:?} No directory with that name", root);
}
MDBook {
content: vec![],
config: BookConfig::new(root)
.set_src(&root.join("src"))
.set_dest(&root.join("book"))
.to_owned(),
renderer: Box::new(HtmlHandlebars::new()),
}
}
/// Returns a flat depth-first iterator over the elements of the book, it returns an [BookItem enum](bookitem.html):
/// `(section: String, bookitem: &BookItem)`
///
/// ```no_run
/// # extern crate mdbook;
/// # use mdbook::MDBook;
/// # use mdbook::BookItem;
/// # use std::path::Path;
/// # fn main() {
/// # let mut book = MDBook::new(Path::new("mybook"));
/// for item in book.iter() {
/// match item {
/// &BookItem::Chapter(ref section, ref chapter) => {},
/// &BookItem::Affix(ref chapter) => {},
/// &BookItem::Spacer => {},
/// }
/// }
///
/// // would print something like this:
/// // 1. Chapter 1
/// // 1.1 Sub Chapter
/// // 1.2 Sub Chapter
/// // 2. Chapter 2
/// //
/// // etc.
/// # }
/// ```
pub fn iter(&self) -> BookItems {
BookItems {
items: &self.content[..],
current_index: 0,
stack: Vec::new(),
}
}
/// `init()` creates some boilerplate files and directories to get you started with your book.
///
/// ```text
/// book-test/
/// ├── book
/// └── src
/// ├── chapter_1.md
/// └── SUMMARY.md
/// ```
///
/// It uses the paths given as source and output directories and adds a `SUMMARY.md` and a
/// `chapter_1.md` to the source directory.
pub fn init(&mut self) -> Result<(), Box<Error>> {
debug!("[fn]: init");
if!self.config.get_root().exists() {
create_path(self.config.get_root()).unwrap();
output!("{:?} created", self.config.get_root());
}
{
let dest = self.config.get_dest();
let src = self.config.get_src();
if!dest.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", dest);
try!(fs::create_dir(&dest));
}
if!src.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", src);
try!(fs::create_dir(&src));
}
let summary = src.join("SUMMARY.md");
if!summary.exists() {
// Summary does not exist, create it
debug!("[*]: {:?} does not exist, trying to create SUMMARY.md", src.join("SUMMARY.md"));
let mut f = try!(File::create(&src.join("SUMMARY.md")));
debug!("[*]: Writing to SUMMARY.md");
try!(writeln!(f, "# Summary"));
try!(writeln!(f, ""));
try!(writeln!(f, "- [Chapter 1](./chapter_1.md)"));
}
}
// parse SUMMARY.md, and create the missing item related file
try!(self.parse_summary());
debug!("[*]: constructing paths for missing files");
for item in self.iter() {
debug!("[*]: item: {:?}", item);
match *item {
BookItem::Spacer => continue,
BookItem::Chapter(_, ref ch) | BookItem::Affix(ref ch) => {
if ch.path!= PathBuf::new() {
let path = self.config.get_src().join(&ch.path);
if!path.exists() {
debug!("[*]: {:?} does not exist, trying to create file", path);
try!(::std::fs::create_dir_all(path.parent().unwrap()));
let mut f = try!(File::create(path));
//debug!("[*]: Writing to {:?}", path);
try!(writeln!(f, "# {}", ch.name));
}
}
}
}
}
debug!("[*]: init done");
Ok(())
}
/// The `build()` method is the one where everything happens. First it parses `SUMMARY.md` to
/// construct the book's structure in the form of a `Vec<BookItem>` and then calls `render()`
/// method of the current renderer.
///
/// It is the renderer who generates all the output files.
pub fn build(&mut self) -> Result<(), Box<Error>> {
debug!("[fn]: build");
try!(self.init());
// Clean output directory
try!(utils::remove_dir_content(&self.config.get_dest()));
try!(self.renderer.render(&self));
Ok(())
}
pub fn copy_theme(&self) -> Result<(), Box<Error>> {
debug!("[fn]: copy_theme");
let theme_dir = self.config.get_src().join("theme");
if!theme_dir.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", theme_dir);
try!(fs::create_dir(&theme_dir));
}
// index.hbs
let mut index = try!(File::create(&theme_dir.join("index.hbs")));
try!(index.write_all(theme::INDEX));
// book.css
let mut css = try!(File::create(&theme_dir.join("book.css")));
try!(css.write_all(theme::CSS));
// book.js
let mut js = try!(File::create(&theme_dir.join("book.js")));
try!(js.write_all(theme::JS));
// highlight.css
let mut highlight_css = try!(File::create(&theme_dir.join("highlight.css")));
try!(highlight_css.write_all(theme::HIGHLIGHT_CSS));
// highlight.js
let mut highlight_js = try!(File::create(&theme_dir.join("highlight.js")));
try!(highlight_js.write_all(theme::HIGHLIGHT_JS));
Ok(())
}
/// Parses the `book.json` file (if it exists) to extract the configuration parameters.
/// The `book.json` file should be in the root directory of the book.
/// The root directory is the one specified when creating a new `MDBook`
///
/// ```no_run
/// # extern crate mdbook;
/// # use mdbook::MDBook;
/// # use std::path::Path;
/// # fn main() {
/// let mut book = MDBook::new(Path::new("root_dir"));
/// # }
/// ```
///
/// In this example, `root_dir` will be the root directory of our book and is specified in function
/// of the current working directory by using a relative path instead of an absolute path.
pub fn read_config(mut self) -> Self {
let root = self.config.get_root().to_owned();
self.config.read_config(&root);
self
}
/// You can change the default renderer to another one by using this method. The only requirement
/// is for your renderer to implement the [Renderer trait](../../renderer/renderer/trait.Renderer.html)
///
/// ```no_run
/// extern crate mdbook;
/// use mdbook::MDBook;
/// use mdbook::renderer::HtmlHandlebars;
/// # use std::path::Path;
///
/// fn main() {
/// let mut book = MDBook::new(Path::new("mybook"))
/// .set_renderer(Box::new(HtmlHandlebars::new()));
///
/// // In this example we replace the default renderer by the default renderer...
/// // Don't forget to put your renderer in a Box
/// }
/// ```
///
/// **note:** Don't forget to put your renderer in a `Box` before passing it to `set_renderer()`
pub fn set_renderer(mut self, renderer: Box<Renderer>) -> Self {
self.renderer = renderer;
self
}
pub fn set_dest(mut self, dest: &Path) -> Self {
// Handle absolute and relative paths
match dest.is_absolute() {
true => { self.config.set_dest(dest); },
false => {
let dest = self.config.get_root().join(dest).to_owned();
self.config.set_dest(&dest);
}
}
self
}
pub fn get_dest(&self) -> &Path {
self.config.get_dest()
}
pub fn set_src(mut self, src: &Path) -> Self {
// Handle absolute and relative paths
match src.is_absolute() {
true => { self.config.set_src(src); },
false => {
let src = self.config.get_root().join(src).to_owned();
self.config.set_src(&src);
}
}
self
}
pub fn get_src(&self) -> &Path {
self.config.get_src()
}
pub fn set_title(mut self, title: &str) -> Self {
self.config.title = title.to_owned();
self
}
pub fn get_title(&self) -> &str | &self.config.title
}
pub fn set_author(mut self, author: &str) -> Self {
self.config.author = author.to_owned();
self
}
pub fn get_author(&self) -> &str {
&self.config.author
}
// Construct book
fn parse_summary(&mut self) -> Result<(), Box<Error>> {
// When append becomes stable, use self.content.append()...
self.content = try!(parse::construct_bookitems(&self.config.get_src().join("SUMMARY.md")));
Ok(())
}
}
| {
| identifier_name |
mdbook.rs | use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::io::Write;
use std::error::Error;
use {BookConfig, BookItem, theme, parse, utils};
use book::BookItems;
use renderer::{Renderer, HtmlHandlebars};
use utils::{PathExt, create_path};
pub struct MDBook {
config: BookConfig,
pub content: Vec<BookItem>,
renderer: Box<Renderer>,
}
impl MDBook {
/// Create a new `MDBook` struct with root directory `root`
///
/// - The default source directory is set to `root/src`
/// - The default output directory is set to `root/book`
///
/// They can both be changed by using [`set_src()`](#method.set_src) and [`set_dest()`](#method.set_dest)
pub fn new(root: &Path) -> MDBook {
if!root.exists() ||!root.is_dir() {
output!("{:?} No directory with that name", root);
}
MDBook {
content: vec![],
config: BookConfig::new(root)
.set_src(&root.join("src"))
.set_dest(&root.join("book"))
.to_owned(),
renderer: Box::new(HtmlHandlebars::new()),
}
}
/// Returns a flat depth-first iterator over the elements of the book, it returns an [BookItem enum](bookitem.html):
/// `(section: String, bookitem: &BookItem)`
///
/// ```no_run
/// # extern crate mdbook;
/// # use mdbook::MDBook;
/// # use mdbook::BookItem;
/// # use std::path::Path;
/// # fn main() {
/// # let mut book = MDBook::new(Path::new("mybook"));
/// for item in book.iter() {
/// match item {
/// &BookItem::Chapter(ref section, ref chapter) => {},
/// &BookItem::Affix(ref chapter) => {},
/// &BookItem::Spacer => {},
/// }
/// }
///
/// // would print something like this:
/// // 1. Chapter 1
/// // 1.1 Sub Chapter
/// // 1.2 Sub Chapter
/// // 2. Chapter 2
/// //
/// // etc.
/// # }
/// ```
pub fn iter(&self) -> BookItems {
BookItems {
items: &self.content[..],
current_index: 0,
stack: Vec::new(),
}
}
/// `init()` creates some boilerplate files and directories to get you started with your book.
///
/// ```text
/// book-test/
/// ├── book
/// └── src
/// ├── chapter_1.md
/// └── SUMMARY.md
/// ```
///
/// It uses the paths given as source and output directories and adds a `SUMMARY.md` and a
/// `chapter_1.md` to the source directory.
pub fn init(&mut self) -> Result<(), Box<Error>> {
debug!("[fn]: init");
if!self.config.get_root().exists() {
create_path(self.config.get_root()).unwrap();
output!("{:?} created", self.config.get_root());
}
{
let dest = self.config.get_dest();
let src = self.config.get_src();
if!dest.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", dest);
try!(fs::create_dir(&dest));
}
if!src.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", src);
try!(fs::create_dir(&src));
}
let summary = src.join("SUMMARY.md");
if!summary.exists() {
// Summary does not exist, create it
debug!("[*]: {:?} does not exist, trying to create SUMMARY.md", src.join("SUMMARY.md"));
let mut f = try!(File::create(&src.join("SUMMARY.md")));
debug!("[*]: Writing to SUMMARY.md");
try!(writeln!(f, "# Summary"));
try!(writeln!(f, ""));
try!(writeln!(f, "- [Chapter 1](./chapter_1.md)"));
}
}
// parse SUMMARY.md, and create the missing item related file
try!(self.parse_summary());
debug!("[*]: constructing paths for missing files");
for item in self.iter() {
debug!("[*]: item: {:?}", item);
match *item {
BookItem::Spacer => continue,
BookItem::Chapter(_, ref ch) | BookItem::Affix(ref ch) => {
if ch.path!= PathBuf::new() {
let path = self.config.get_src().join(&ch.path);
if!path.exists() {
debug!("[*]: {:?} does not exist, trying to create file", path);
try!(::std::fs::create_dir_all(path.parent().unwrap()));
let mut f = try!(File::create(path));
//debug!("[*]: Writing to {:?}", path);
try!(writeln!(f, "# {}", ch.name));
}
}
}
}
}
debug!("[*]: init done");
Ok(())
}
/// The `build()` method is the one where everything happens. First it parses `SUMMARY.md` to
/// construct the book's structure in the form of a `Vec<BookItem>` and then calls `render()`
/// method of the current renderer.
///
/// It is the renderer who generates all the output files.
pub fn build(&mut self) -> Result<(), Box<Error>> {
debug!("[fn]: build");
try!(self.init());
// Clean output directory
try!(utils::remove_dir_content(&self.config.get_dest()));
try!(self.renderer.render(&self));
Ok(())
}
pub fn copy_theme(&self) -> Result<(), Box<Error>> {
debug!("[fn]: copy_theme");
let theme_dir = self.config.get_src().join("theme");
if!theme_dir.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", theme_dir);
try!(fs::create_dir(&theme_dir));
}
// index.hbs
let mut index = try!(File::create(&theme_dir.join("index.hbs")));
try!(index.write_all(theme::INDEX));
// book.css
let mut css = try!(File::create(&theme_dir.join("book.css")));
try!(css.write_all(theme::CSS));
// book.js
let mut js = try!(File::create(&theme_dir.join("book.js")));
try!(js.write_all(theme::JS));
// highlight.css
let mut highlight_css = try!(File::create(&theme_dir.join("highlight.css")));
try!(highlight_css.write_all(theme::HIGHLIGHT_CSS));
// highlight.js
let mut highlight_js = try!(File::create(&theme_dir.join("highlight.js")));
try!(highlight_js.write_all(theme::HIGHLIGHT_JS));
Ok(())
}
/// Parses the `book.json` file (if it exists) to extract the configuration parameters.
/// The `book.json` file should be in the root directory of the book.
/// The root directory is the one specified when creating a new `MDBook`
///
/// ```no_run
/// # extern crate mdbook;
/// # use mdbook::MDBook;
/// # use std::path::Path;
/// # fn main() {
/// let mut book = MDBook::new(Path::new("root_dir"));
/// # }
/// ```
///
/// In this example, `root_dir` will be the root directory of our book and is specified in function
/// of the current working directory by using a relative path instead of an absolute path.
pub fn read_config(mut self) -> Self {
let root = self.config.get_root().to_owned();
self.config.read_config(&root);
self
}
/// You can change the default renderer to another one by using this method. The only requirement
/// is for your renderer to implement the [Renderer trait](../../renderer/renderer/trait.Renderer.html)
///
/// ```no_run
/// extern crate mdbook;
/// use mdbook::MDBook;
/// use mdbook::renderer::HtmlHandlebars;
/// # use std::path::Path;
///
/// fn main() {
/// let mut book = MDBook::new(Path::new("mybook"))
/// .set_renderer(Box::new(HtmlHandlebars::new()));
///
/// // In this example we replace the default renderer by the default renderer...
/// // Don't forget to put your renderer in a Box
/// }
/// ```
///
/// **note:** Don't forget to put your renderer in a `Box` before passing it to `set_renderer()`
pub fn set_renderer(mut self, renderer: Box<Renderer>) -> Self {
self.renderer = renderer;
self
}
pub fn set_dest(mut self, dest: &Path) -> Self {
// Handle absolute and relative paths
match dest.is_absolute() {
true => { self.config.set_dest(dest); },
false => {
let dest = self.config.get_root().join(dest).to_owned();
self.config.set_dest(&dest);
}
}
self
}
pub fn get_dest(&self) -> &Path {
self.config.get_dest()
}
pub fn set_src(mut self, src: &Path) -> Self {
// Handle absolute and relative paths
match src.is_absolute() {
true => { self.config.set_src(src); },
false => {
let src = self.config.get_root().join(src).to_owned();
self.config.set_src(&src);
}
}
self
}
pub fn get_src(&self) -> &Path {
self.config.get_src() | self
}
pub fn get_title(&self) -> &str {
&self.config.title
}
pub fn set_author(mut self, author: &str) -> Self {
self.config.author = author.to_owned();
self
}
pub fn get_author(&self) -> &str {
&self.config.author
}
// Construct book
fn parse_summary(&mut self) -> Result<(), Box<Error>> {
// When append becomes stable, use self.content.append()...
self.content = try!(parse::construct_bookitems(&self.config.get_src().join("SUMMARY.md")));
Ok(())
}
} | }
pub fn set_title(mut self, title: &str) -> Self {
self.config.title = title.to_owned(); | random_line_split |
mdbook.rs | use std::path::{Path, PathBuf};
use std::fs::{self, File};
use std::io::Write;
use std::error::Error;
use {BookConfig, BookItem, theme, parse, utils};
use book::BookItems;
use renderer::{Renderer, HtmlHandlebars};
use utils::{PathExt, create_path};
pub struct MDBook {
config: BookConfig,
pub content: Vec<BookItem>,
renderer: Box<Renderer>,
}
impl MDBook {
/// Create a new `MDBook` struct with root directory `root`
///
/// - The default source directory is set to `root/src`
/// - The default output directory is set to `root/book`
///
/// They can both be changed by using [`set_src()`](#method.set_src) and [`set_dest()`](#method.set_dest)
pub fn new(root: &Path) -> MDBook {
if!root.exists() ||!root.is_dir() {
output!("{:?} No directory with that name", root);
}
MDBook {
content: vec![],
config: BookConfig::new(root)
.set_src(&root.join("src"))
.set_dest(&root.join("book"))
.to_owned(),
renderer: Box::new(HtmlHandlebars::new()),
}
}
/// Returns a flat depth-first iterator over the elements of the book, it returns an [BookItem enum](bookitem.html):
/// `(section: String, bookitem: &BookItem)`
///
/// ```no_run
/// # extern crate mdbook;
/// # use mdbook::MDBook;
/// # use mdbook::BookItem;
/// # use std::path::Path;
/// # fn main() {
/// # let mut book = MDBook::new(Path::new("mybook"));
/// for item in book.iter() {
/// match item {
/// &BookItem::Chapter(ref section, ref chapter) => {},
/// &BookItem::Affix(ref chapter) => {},
/// &BookItem::Spacer => {},
/// }
/// }
///
/// // would print something like this:
/// // 1. Chapter 1
/// // 1.1 Sub Chapter
/// // 1.2 Sub Chapter
/// // 2. Chapter 2
/// //
/// // etc.
/// # }
/// ```
pub fn iter(&self) -> BookItems {
BookItems {
items: &self.content[..],
current_index: 0,
stack: Vec::new(),
}
}
/// `init()` creates some boilerplate files and directories to get you started with your book.
///
/// ```text
/// book-test/
/// ├── book
/// └── src
/// ├── chapter_1.md
/// └── SUMMARY.md
/// ```
///
/// It uses the paths given as source and output directories and adds a `SUMMARY.md` and a
/// `chapter_1.md` to the source directory.
pub fn init(&mut self) -> Result<(), Box<Error>> {
debug!("[fn]: init");
if!self.config.get_root().exists() {
create_path(self.config.get_root()).unwrap();
output!("{:?} created", self.config.get_root());
}
{
let dest = self.config.get_dest();
let src = self.config.get_src();
if!dest.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", dest);
try!(fs::create_dir(&dest));
}
if!src.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", src);
try!(fs::create_dir(&src));
}
let summary = src.join("SUMMARY.md");
if!summary.exists() {
// Summary does not exist, create it
debug!("[*]: {:?} does not exist, trying to create SUMMARY.md", src.join("SUMMARY.md"));
let mut f = try!(File::create(&src.join("SUMMARY.md")));
debug!("[*]: Writing to SUMMARY.md");
try!(writeln!(f, "# Summary"));
try!(writeln!(f, ""));
try!(writeln!(f, "- [Chapter 1](./chapter_1.md)"));
}
}
// parse SUMMARY.md, and create the missing item related file
try!(self.parse_summary());
debug!("[*]: constructing paths for missing files");
for item in self.iter() {
debug!("[*]: item: {:?}", item);
match *item {
BookItem::Spacer => continue,
BookItem::Chapter(_, ref ch) | BookItem::Affix(ref ch) => {
if |
debug!("[*]: init done");
Ok(())
}
/// The `build()` method is the one where everything happens. First it parses `SUMMARY.md` to
/// construct the book's structure in the form of a `Vec<BookItem>` and then calls `render()`
/// method of the current renderer.
///
/// It is the renderer who generates all the output files.
pub fn build(&mut self) -> Result<(), Box<Error>> {
debug!("[fn]: build");
try!(self.init());
// Clean output directory
try!(utils::remove_dir_content(&self.config.get_dest()));
try!(self.renderer.render(&self));
Ok(())
}
pub fn copy_theme(&self) -> Result<(), Box<Error>> {
debug!("[fn]: copy_theme");
let theme_dir = self.config.get_src().join("theme");
if!theme_dir.exists() {
debug!("[*]: {:?} does not exist, trying to create directory", theme_dir);
try!(fs::create_dir(&theme_dir));
}
// index.hbs
let mut index = try!(File::create(&theme_dir.join("index.hbs")));
try!(index.write_all(theme::INDEX));
// book.css
let mut css = try!(File::create(&theme_dir.join("book.css")));
try!(css.write_all(theme::CSS));
// book.js
let mut js = try!(File::create(&theme_dir.join("book.js")));
try!(js.write_all(theme::JS));
// highlight.css
let mut highlight_css = try!(File::create(&theme_dir.join("highlight.css")));
try!(highlight_css.write_all(theme::HIGHLIGHT_CSS));
// highlight.js
let mut highlight_js = try!(File::create(&theme_dir.join("highlight.js")));
try!(highlight_js.write_all(theme::HIGHLIGHT_JS));
Ok(())
}
/// Parses the `book.json` file (if it exists) to extract the configuration parameters.
/// The `book.json` file should be in the root directory of the book.
/// The root directory is the one specified when creating a new `MDBook`
///
/// ```no_run
/// # extern crate mdbook;
/// # use mdbook::MDBook;
/// # use std::path::Path;
/// # fn main() {
/// let mut book = MDBook::new(Path::new("root_dir"));
/// # }
/// ```
///
/// In this example, `root_dir` will be the root directory of our book and is specified in function
/// of the current working directory by using a relative path instead of an absolute path.
pub fn read_config(mut self) -> Self {
let root = self.config.get_root().to_owned();
self.config.read_config(&root);
self
}
/// You can change the default renderer to another one by using this method. The only requirement
/// is for your renderer to implement the [Renderer trait](../../renderer/renderer/trait.Renderer.html)
///
/// ```no_run
/// extern crate mdbook;
/// use mdbook::MDBook;
/// use mdbook::renderer::HtmlHandlebars;
/// # use std::path::Path;
///
/// fn main() {
/// let mut book = MDBook::new(Path::new("mybook"))
/// .set_renderer(Box::new(HtmlHandlebars::new()));
///
/// // In this example we replace the default renderer by the default renderer...
/// // Don't forget to put your renderer in a Box
/// }
/// ```
///
/// **note:** Don't forget to put your renderer in a `Box` before passing it to `set_renderer()`
pub fn set_renderer(mut self, renderer: Box<Renderer>) -> Self {
self.renderer = renderer;
self
}
pub fn set_dest(mut self, dest: &Path) -> Self {
// Handle absolute and relative paths
match dest.is_absolute() {
true => { self.config.set_dest(dest); },
false => {
let dest = self.config.get_root().join(dest).to_owned();
self.config.set_dest(&dest);
}
}
self
}
pub fn get_dest(&self) -> &Path {
self.config.get_dest()
}
pub fn set_src(mut self, src: &Path) -> Self {
// Handle absolute and relative paths
match src.is_absolute() {
true => { self.config.set_src(src); },
false => {
let src = self.config.get_root().join(src).to_owned();
self.config.set_src(&src);
}
}
self
}
pub fn get_src(&self) -> &Path {
self.config.get_src()
}
pub fn set_title(mut self, title: &str) -> Self {
self.config.title = title.to_owned();
self
}
pub fn get_title(&self) -> &str {
&self.config.title
}
pub fn set_author(mut self, author: &str) -> Self {
self.config.author = author.to_owned();
self
}
pub fn get_author(&self) -> &str {
&self.config.author
}
// Construct book
fn parse_summary(&mut self) -> Result<(), Box<Error>> {
// When append becomes stable, use self.content.append()...
self.content = try!(parse::construct_bookitems(&self.config.get_src().join("SUMMARY.md")));
Ok(())
}
}
| ch.path != PathBuf::new() {
let path = self.config.get_src().join(&ch.path);
if !path.exists() {
debug!("[*]: {:?} does not exist, trying to create file", path);
try!(::std::fs::create_dir_all(path.parent().unwrap()));
let mut f = try!(File::create(path));
//debug!("[*]: Writing to {:?}", path);
try!(writeln!(f, "# {}", ch.name));
}
}
}
}
} | conditional_block |
mockstream.rs | // https://github.com/lazy-bitfield/rust-mockstream/pull/2
use std::io::{Cursor, Read, Result, Error, ErrorKind};
use std::error::Error as errorError;
/// `FailingMockStream` mocks a stream which will fail upon read or write
///
/// # Examples
///
/// ```
/// use std::io::{Cursor, Read};
///
/// struct CountIo {}
///
/// impl CountIo {
/// fn read_data(&self, r: &mut Read) -> usize {
/// let mut count: usize = 0;
/// let mut retries = 3;
///
/// loop {
/// let mut buffer = [0; 5];
/// match r.read(&mut buffer) {
/// Err(_) => {
/// if retries == 0 { break; }
/// retries -= 1;
/// },
/// Ok(0) => break,
/// Ok(n) => count += n,
/// }
/// }
/// count
/// }
/// }
///
/// #[test]
/// fn test_io_retries() {
/// let mut c = Cursor::new(&b"1234"[..])
/// .chain(FailingMockStream::new(ErrorKind::Other, "Failing", 3))
/// .chain(Cursor::new(&b"5678"[..]));
///
/// let sut = CountIo {};
/// // this will fail unless read_data performs at least 3 retries on I/O errors
/// assert_eq!(8, sut.read_data(&mut c));
/// }
/// ```
#[derive(Clone)]
pub struct FailingMockStream {
kind: ErrorKind,
message: &'static str,
repeat_count: i32,
}
impl FailingMockStream {
/// Creates a FailingMockStream
///
/// When `read` or `write` is called, it will return an error `repeat_count` times.
/// `kind` and `message` can be specified to define the exact error.
pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> FailingMockStream {
FailingMockStream { kind: kind, message: message, repeat_count: repeat_count, }
}
fn error(&mut self) -> Result<usize> {
if self.repeat_count == 0 {
return Ok(0)
} else {
if self.repeat_count > 0 {
self.repeat_count -= 1;
}
Err(Error::new(self.kind, self.message))
}
}
}
impl Read for FailingMockStream {
fn | (&mut self, _: &mut [u8]) -> Result<usize> {
self.error()
}
}
#[test]
fn test_failing_mock_stream_read() {
let mut s = FailingMockStream::new(ErrorKind::BrokenPipe, "The dog ate the ethernet cable", 1);
let mut v = [0; 4];
let error = s.read(v.as_mut()).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BrokenPipe);
assert_eq!(error.description(), "The dog ate the ethernet cable");
// after a single error, it will return Ok(0)
assert_eq!(s.read(v.as_mut()).unwrap(), 0);
}
#[test]
fn test_failing_mock_stream_chain_interrupted() {
let mut c = Cursor::new(&b"abcd"[..])
.chain(FailingMockStream::new(ErrorKind::Interrupted, "Interrupted", 5))
.chain(Cursor::new(&b"ABCD"[..]));
let mut v = [0; 8];
c.read_exact(v.as_mut()).unwrap();
assert_eq!(v, [0x61, 0x62, 0x63, 0x64, 0x41, 0x42, 0x43, 0x44]);
assert_eq!(c.read(v.as_mut()).unwrap(), 0);
}
| read | identifier_name |
mockstream.rs | // https://github.com/lazy-bitfield/rust-mockstream/pull/2
use std::io::{Cursor, Read, Result, Error, ErrorKind};
use std::error::Error as errorError;
/// `FailingMockStream` mocks a stream which will fail upon read or write
///
/// # Examples
///
/// ```
/// use std::io::{Cursor, Read};
///
/// struct CountIo {}
///
/// impl CountIo {
/// fn read_data(&self, r: &mut Read) -> usize {
/// let mut count: usize = 0;
/// let mut retries = 3;
///
/// loop {
/// let mut buffer = [0; 5];
/// match r.read(&mut buffer) {
/// Err(_) => {
/// if retries == 0 { break; }
/// retries -= 1;
/// },
/// Ok(0) => break,
/// Ok(n) => count += n,
/// }
/// }
/// count
/// }
/// }
///
/// #[test]
/// fn test_io_retries() {
/// let mut c = Cursor::new(&b"1234"[..])
/// .chain(FailingMockStream::new(ErrorKind::Other, "Failing", 3))
/// .chain(Cursor::new(&b"5678"[..]));
///
/// let sut = CountIo {};
/// // this will fail unless read_data performs at least 3 retries on I/O errors
/// assert_eq!(8, sut.read_data(&mut c));
/// }
/// ```
#[derive(Clone)]
pub struct FailingMockStream {
kind: ErrorKind,
message: &'static str,
repeat_count: i32,
}
impl FailingMockStream {
/// Creates a FailingMockStream
///
/// When `read` or `write` is called, it will return an error `repeat_count` times.
/// `kind` and `message` can be specified to define the exact error.
pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> FailingMockStream {
FailingMockStream { kind: kind, message: message, repeat_count: repeat_count, }
}
fn error(&mut self) -> Result<usize> {
if self.repeat_count == 0 {
return Ok(0)
} else {
if self.repeat_count > 0 |
Err(Error::new(self.kind, self.message))
}
}
}
impl Read for FailingMockStream {
fn read(&mut self, _: &mut [u8]) -> Result<usize> {
self.error()
}
}
#[test]
fn test_failing_mock_stream_read() {
let mut s = FailingMockStream::new(ErrorKind::BrokenPipe, "The dog ate the ethernet cable", 1);
let mut v = [0; 4];
let error = s.read(v.as_mut()).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BrokenPipe);
assert_eq!(error.description(), "The dog ate the ethernet cable");
// after a single error, it will return Ok(0)
assert_eq!(s.read(v.as_mut()).unwrap(), 0);
}
#[test]
fn test_failing_mock_stream_chain_interrupted() {
let mut c = Cursor::new(&b"abcd"[..])
.chain(FailingMockStream::new(ErrorKind::Interrupted, "Interrupted", 5))
.chain(Cursor::new(&b"ABCD"[..]));
let mut v = [0; 8];
c.read_exact(v.as_mut()).unwrap();
assert_eq!(v, [0x61, 0x62, 0x63, 0x64, 0x41, 0x42, 0x43, 0x44]);
assert_eq!(c.read(v.as_mut()).unwrap(), 0);
}
| {
self.repeat_count -= 1;
} | conditional_block |
mockstream.rs | // https://github.com/lazy-bitfield/rust-mockstream/pull/2
use std::io::{Cursor, Read, Result, Error, ErrorKind};
use std::error::Error as errorError;
/// `FailingMockStream` mocks a stream which will fail upon read or write
///
/// # Examples
///
/// ```
/// use std::io::{Cursor, Read};
///
/// struct CountIo {}
///
/// impl CountIo {
/// fn read_data(&self, r: &mut Read) -> usize {
/// let mut count: usize = 0;
/// let mut retries = 3;
///
/// loop {
/// let mut buffer = [0; 5];
/// match r.read(&mut buffer) {
/// Err(_) => {
/// if retries == 0 { break; }
/// retries -= 1;
/// },
/// Ok(0) => break,
/// Ok(n) => count += n,
/// }
/// }
/// count
/// }
/// }
///
/// #[test]
/// fn test_io_retries() {
/// let mut c = Cursor::new(&b"1234"[..])
/// .chain(FailingMockStream::new(ErrorKind::Other, "Failing", 3))
/// .chain(Cursor::new(&b"5678"[..]));
///
/// let sut = CountIo {};
/// // this will fail unless read_data performs at least 3 retries on I/O errors
/// assert_eq!(8, sut.read_data(&mut c));
/// }
/// ```
#[derive(Clone)]
pub struct FailingMockStream {
kind: ErrorKind,
message: &'static str,
repeat_count: i32,
}
impl FailingMockStream {
/// Creates a FailingMockStream
///
/// When `read` or `write` is called, it will return an error `repeat_count` times.
/// `kind` and `message` can be specified to define the exact error.
pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> FailingMockStream {
FailingMockStream { kind: kind, message: message, repeat_count: repeat_count, }
}
fn error(&mut self) -> Result<usize> {
if self.repeat_count == 0 {
return Ok(0)
} else {
if self.repeat_count > 0 {
self.repeat_count -= 1;
}
Err(Error::new(self.kind, self.message))
}
}
}
impl Read for FailingMockStream {
fn read(&mut self, _: &mut [u8]) -> Result<usize> {
self.error()
}
}
#[test]
fn test_failing_mock_stream_read() {
let mut s = FailingMockStream::new(ErrorKind::BrokenPipe, "The dog ate the ethernet cable", 1);
let mut v = [0; 4];
let error = s.read(v.as_mut()).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BrokenPipe);
assert_eq!(error.description(), "The dog ate the ethernet cable");
// after a single error, it will return Ok(0)
assert_eq!(s.read(v.as_mut()).unwrap(), 0);
}
#[test]
fn test_failing_mock_stream_chain_interrupted() {
let mut c = Cursor::new(&b"abcd"[..])
.chain(FailingMockStream::new(ErrorKind::Interrupted, "Interrupted", 5))
.chain(Cursor::new(&b"ABCD"[..]));
let mut v = [0; 8];
c.read_exact(v.as_mut()).unwrap();
assert_eq!(v, [0x61, 0x62, 0x63, 0x64, 0x41, 0x42, 0x43, 0x44]);
assert_eq!(c.read(v.as_mut()).unwrap(), 0); | } | random_line_split |
|
mockstream.rs | // https://github.com/lazy-bitfield/rust-mockstream/pull/2
use std::io::{Cursor, Read, Result, Error, ErrorKind};
use std::error::Error as errorError;
/// `FailingMockStream` mocks a stream which will fail upon read or write
///
/// # Examples
///
/// ```
/// use std::io::{Cursor, Read};
///
/// struct CountIo {}
///
/// impl CountIo {
/// fn read_data(&self, r: &mut Read) -> usize {
/// let mut count: usize = 0;
/// let mut retries = 3;
///
/// loop {
/// let mut buffer = [0; 5];
/// match r.read(&mut buffer) {
/// Err(_) => {
/// if retries == 0 { break; }
/// retries -= 1;
/// },
/// Ok(0) => break,
/// Ok(n) => count += n,
/// }
/// }
/// count
/// }
/// }
///
/// #[test]
/// fn test_io_retries() {
/// let mut c = Cursor::new(&b"1234"[..])
/// .chain(FailingMockStream::new(ErrorKind::Other, "Failing", 3))
/// .chain(Cursor::new(&b"5678"[..]));
///
/// let sut = CountIo {};
/// // this will fail unless read_data performs at least 3 retries on I/O errors
/// assert_eq!(8, sut.read_data(&mut c));
/// }
/// ```
#[derive(Clone)]
pub struct FailingMockStream {
kind: ErrorKind,
message: &'static str,
repeat_count: i32,
}
impl FailingMockStream {
/// Creates a FailingMockStream
///
/// When `read` or `write` is called, it will return an error `repeat_count` times.
/// `kind` and `message` can be specified to define the exact error.
pub fn new(kind: ErrorKind, message: &'static str, repeat_count: i32) -> FailingMockStream {
FailingMockStream { kind: kind, message: message, repeat_count: repeat_count, }
}
fn error(&mut self) -> Result<usize> {
if self.repeat_count == 0 {
return Ok(0)
} else {
if self.repeat_count > 0 {
self.repeat_count -= 1;
}
Err(Error::new(self.kind, self.message))
}
}
}
impl Read for FailingMockStream {
fn read(&mut self, _: &mut [u8]) -> Result<usize> |
}
#[test]
fn test_failing_mock_stream_read() {
let mut s = FailingMockStream::new(ErrorKind::BrokenPipe, "The dog ate the ethernet cable", 1);
let mut v = [0; 4];
let error = s.read(v.as_mut()).unwrap_err();
assert_eq!(error.kind(), ErrorKind::BrokenPipe);
assert_eq!(error.description(), "The dog ate the ethernet cable");
// after a single error, it will return Ok(0)
assert_eq!(s.read(v.as_mut()).unwrap(), 0);
}
#[test]
fn test_failing_mock_stream_chain_interrupted() {
let mut c = Cursor::new(&b"abcd"[..])
.chain(FailingMockStream::new(ErrorKind::Interrupted, "Interrupted", 5))
.chain(Cursor::new(&b"ABCD"[..]));
let mut v = [0; 8];
c.read_exact(v.as_mut()).unwrap();
assert_eq!(v, [0x61, 0x62, 0x63, 0x64, 0x41, 0x42, 0x43, 0x44]);
assert_eq!(c.read(v.as_mut()).unwrap(), 0);
}
| {
self.error()
} | identifier_body |
no_std.rs | #![no_std]
use sdl2_sys::*;
use core::ptr::null_mut;
fn main() {
unsafe {
let mut _window: *mut SDL_Window = null_mut();
let mut _surface: *mut SDL_Surface = null_mut();
if SDL_Init(SDL_INIT_VIDEO) < 0 {
panic!("failed to initialize sdl2 with video");
};
_window = SDL_CreateWindow( | SDL_WindowFlags::SDL_WINDOW_SHOWN as u32
);
if _window == null_mut() {
panic!("failed to create window");
}
_surface = SDL_GetWindowSurface(_window);
SDL_FillRect(_surface, null_mut(), SDL_MapRGB((*_surface).format, 0xFF, 0xFF, 0x00));
SDL_UpdateWindowSurface(_window);
SDL_Delay(5000);
SDL_DestroyWindow(_window);
SDL_Quit();
}
} | b"hello_sdl2" as *const _ as *const i8,
SDL_WINDOWPOS_UNDEFINED_MASK as i32,
SDL_WINDOWPOS_UNDEFINED_MASK as i32,
640,
480, | random_line_split |
no_std.rs | #![no_std]
use sdl2_sys::*;
use core::ptr::null_mut;
fn main() {
unsafe {
let mut _window: *mut SDL_Window = null_mut();
let mut _surface: *mut SDL_Surface = null_mut();
if SDL_Init(SDL_INIT_VIDEO) < 0 {
panic!("failed to initialize sdl2 with video");
};
_window = SDL_CreateWindow(
b"hello_sdl2" as *const _ as *const i8,
SDL_WINDOWPOS_UNDEFINED_MASK as i32,
SDL_WINDOWPOS_UNDEFINED_MASK as i32,
640,
480,
SDL_WindowFlags::SDL_WINDOW_SHOWN as u32
);
if _window == null_mut() |
_surface = SDL_GetWindowSurface(_window);
SDL_FillRect(_surface, null_mut(), SDL_MapRGB((*_surface).format, 0xFF, 0xFF, 0x00));
SDL_UpdateWindowSurface(_window);
SDL_Delay(5000);
SDL_DestroyWindow(_window);
SDL_Quit();
}
}
| {
panic!("failed to create window");
} | conditional_block |
no_std.rs | #![no_std]
use sdl2_sys::*;
use core::ptr::null_mut;
fn main() | _surface = SDL_GetWindowSurface(_window);
SDL_FillRect(_surface, null_mut(), SDL_MapRGB((*_surface).format, 0xFF, 0xFF, 0x00));
SDL_UpdateWindowSurface(_window);
SDL_Delay(5000);
SDL_DestroyWindow(_window);
SDL_Quit();
}
}
| {
unsafe {
let mut _window: *mut SDL_Window = null_mut();
let mut _surface: *mut SDL_Surface = null_mut();
if SDL_Init(SDL_INIT_VIDEO) < 0 {
panic!("failed to initialize sdl2 with video");
};
_window = SDL_CreateWindow(
b"hello_sdl2" as *const _ as *const i8,
SDL_WINDOWPOS_UNDEFINED_MASK as i32,
SDL_WINDOWPOS_UNDEFINED_MASK as i32,
640,
480,
SDL_WindowFlags::SDL_WINDOW_SHOWN as u32
);
if _window == null_mut() {
panic!("failed to create window");
}
| identifier_body |
no_std.rs | #![no_std]
use sdl2_sys::*;
use core::ptr::null_mut;
fn | () {
unsafe {
let mut _window: *mut SDL_Window = null_mut();
let mut _surface: *mut SDL_Surface = null_mut();
if SDL_Init(SDL_INIT_VIDEO) < 0 {
panic!("failed to initialize sdl2 with video");
};
_window = SDL_CreateWindow(
b"hello_sdl2" as *const _ as *const i8,
SDL_WINDOWPOS_UNDEFINED_MASK as i32,
SDL_WINDOWPOS_UNDEFINED_MASK as i32,
640,
480,
SDL_WindowFlags::SDL_WINDOW_SHOWN as u32
);
if _window == null_mut() {
panic!("failed to create window");
}
_surface = SDL_GetWindowSurface(_window);
SDL_FillRect(_surface, null_mut(), SDL_MapRGB((*_surface).format, 0xFF, 0xFF, 0x00));
SDL_UpdateWindowSurface(_window);
SDL_Delay(5000);
SDL_DestroyWindow(_window);
SDL_Quit();
}
}
| main | identifier_name |
lib.rs | // Copyright (c) 2014 by SiegeLord
//
// All rights reserved. Distributed under ZLib. For full terms see the file LICENSE.
#![crate_name="allegro_font_sys"]
#![crate_type = "lib"]
#![allow(non_camel_case_types)]
#![allow(non_camel_case_types, raw_pointer_derive)]
extern crate libc;
extern crate allegro_sys as allegro;
#[macro_use]
extern crate allegro_util;
pub use self::allegro_font::*;
pub mod allegro_font
{
use libc::*;
use allegro_util::c_bool;
use allegro::{ALLEGRO_USTR, ALLEGRO_COLOR, ALLEGRO_BITMAP};
#[repr(C)]
#[derive(Copy, Clone)]
pub struct |
{
pub data: *mut c_void,
pub height: c_int,
pub vtable: *mut ALLEGRO_FONT_VTABLE,
}
#[repr(C)]
pub struct ALLEGRO_FONT_VTABLE
{
pub font_height: Option<extern "C" fn(arg1: *const ALLEGRO_FONT) -> c_int>,
pub font_ascent: Option<extern "C" fn(arg1: *const ALLEGRO_FONT) -> c_int>,
pub font_descent: Option<extern "C" fn(arg1: *const ALLEGRO_FONT) -> c_int>,
pub char_length: Option<extern "C" fn(arg1: *const ALLEGRO_FONT, arg2: c_int) -> c_int>,
pub text_length: Option<extern "C" fn(arg1: *const ALLEGRO_FONT, arg2: *const ALLEGRO_USTR) -> c_int>,
pub render_char: Option<extern "C" fn(arg1: *const ALLEGRO_FONT, arg2: ALLEGRO_COLOR, arg3: c_int, arg4: c_float, arg5: c_float) -> c_int>,
pub render: Option<extern "C" fn(arg1: *const ALLEGRO_FONT, arg2: ALLEGRO_COLOR, arg3: *const ALLEGRO_USTR, arg4: c_float, arg5: c_float) -> c_int>,
pub destroy: Option<extern "C" fn(arg1: *mut ALLEGRO_FONT)>,
pub get_text_dimensions: Option<extern "C" fn(arg1: *const ALLEGRO_FONT, arg2: *const ALLEGRO_USTR, arg3: *mut c_int, arg4: *mut c_int, arg5: *mut c_int, arg6: *mut c_int)>,
}
derive_copy_clone!(ALLEGRO_FONT_VTABLE);
pub const ALLEGRO_ALIGN_LEFT: c_int = 0;
pub const ALLEGRO_ALIGN_CENTRE: c_int = 1;
pub const ALLEGRO_ALIGN_CENTER: c_int = 1;
pub const ALLEGRO_ALIGN_RIGHT: c_int = 2;
pub const ALLEGRO_ALIGN_INTEGER: c_int = 4;
extern "C"
{
pub fn al_register_font_loader(ext: *const c_char, load: Option<extern "C" fn (arg1: *const c_char, arg2: c_int, arg3: c_int) -> *mut ALLEGRO_FONT>) -> c_bool;
pub fn al_load_bitmap_font(filename: *const c_char) -> *mut ALLEGRO_FONT;
pub fn al_load_font(filename: *const c_char, size: c_int, flags: c_int) -> *mut ALLEGRO_FONT;
pub fn al_grab_font_from_bitmap(bmp: *mut ALLEGRO_BITMAP, n: c_int, ranges: *const c_int) -> *mut ALLEGRO_FONT;
pub fn al_create_builtin_font() -> *mut ALLEGRO_FONT;
pub fn al_draw_ustr(font: *const ALLEGRO_FONT, color: ALLEGRO_COLOR, x: c_float, y: c_float, flags: c_int, ustr: *const ALLEGRO_USTR);
pub fn al_draw_text(font: *const ALLEGRO_FONT, color: ALLEGRO_COLOR, x: c_float, y: c_float, flags: c_int, text: *const c_char);
pub fn al_draw_justified_text(font: *const ALLEGRO_FONT, color: ALLEGRO_COLOR, x1: c_float, x2: c_float, y: c_float, diff: c_float, flags: c_int, text: *const c_char);
pub fn al_draw_justified_ustr(font: *const ALLEGRO_FONT, color: ALLEGRO_COLOR, x1: c_float, x2: c_float, y: c_float, diff: c_float, flags: c_int, text: *const ALLEGRO_USTR);
pub fn al_get_text_width(f: *const ALLEGRO_FONT, str: *const c_char) -> c_int;
pub fn al_get_ustr_width(f: *const ALLEGRO_FONT, ustr: *const ALLEGRO_USTR) -> c_int;
pub fn al_get_font_line_height(f: *const ALLEGRO_FONT) -> c_int;
pub fn al_get_font_ascent(f: *const ALLEGRO_FONT) -> c_int;
pub fn al_get_font_descent(f: *const ALLEGRO_FONT) -> c_int;
pub fn al_destroy_font(f: *mut ALLEGRO_FONT);
pub fn al_get_ustr_dimensions(f: *const ALLEGRO_FONT, text: *const ALLEGRO_USTR, bbx: *mut c_int, bby: *mut c_int, bbw: *mut c_int, bbh: *mut c_int);
pub fn al_get_text_dimensions(f: *const ALLEGRO_FONT, text: *const c_char, bbx: *mut c_int, bby: *mut c_int, bbw: *mut c_int, bbh: *mut c_int);
pub fn al_init_font_addon();
pub fn al_shutdown_font_addon();
pub fn al_get_allegro_font_version() -> uint32_t;
}
}
| ALLEGRO_FONT | identifier_name |
lib.rs | // Copyright (c) 2014 by SiegeLord
//
// All rights reserved. Distributed under ZLib. For full terms see the file LICENSE.
#![crate_name="allegro_font_sys"]
#![crate_type = "lib"]
#![allow(non_camel_case_types)]
#![allow(non_camel_case_types, raw_pointer_derive)]
extern crate libc;
extern crate allegro_sys as allegro;
#[macro_use]
extern crate allegro_util;
pub use self::allegro_font::*;
pub mod allegro_font
{
use libc::*;
use allegro_util::c_bool; | pub struct ALLEGRO_FONT
{
pub data: *mut c_void,
pub height: c_int,
pub vtable: *mut ALLEGRO_FONT_VTABLE,
}
#[repr(C)]
pub struct ALLEGRO_FONT_VTABLE
{
pub font_height: Option<extern "C" fn(arg1: *const ALLEGRO_FONT) -> c_int>,
pub font_ascent: Option<extern "C" fn(arg1: *const ALLEGRO_FONT) -> c_int>,
pub font_descent: Option<extern "C" fn(arg1: *const ALLEGRO_FONT) -> c_int>,
pub char_length: Option<extern "C" fn(arg1: *const ALLEGRO_FONT, arg2: c_int) -> c_int>,
pub text_length: Option<extern "C" fn(arg1: *const ALLEGRO_FONT, arg2: *const ALLEGRO_USTR) -> c_int>,
pub render_char: Option<extern "C" fn(arg1: *const ALLEGRO_FONT, arg2: ALLEGRO_COLOR, arg3: c_int, arg4: c_float, arg5: c_float) -> c_int>,
pub render: Option<extern "C" fn(arg1: *const ALLEGRO_FONT, arg2: ALLEGRO_COLOR, arg3: *const ALLEGRO_USTR, arg4: c_float, arg5: c_float) -> c_int>,
pub destroy: Option<extern "C" fn(arg1: *mut ALLEGRO_FONT)>,
pub get_text_dimensions: Option<extern "C" fn(arg1: *const ALLEGRO_FONT, arg2: *const ALLEGRO_USTR, arg3: *mut c_int, arg4: *mut c_int, arg5: *mut c_int, arg6: *mut c_int)>,
}
derive_copy_clone!(ALLEGRO_FONT_VTABLE);
pub const ALLEGRO_ALIGN_LEFT: c_int = 0;
pub const ALLEGRO_ALIGN_CENTRE: c_int = 1;
pub const ALLEGRO_ALIGN_CENTER: c_int = 1;
pub const ALLEGRO_ALIGN_RIGHT: c_int = 2;
pub const ALLEGRO_ALIGN_INTEGER: c_int = 4;
extern "C"
{
pub fn al_register_font_loader(ext: *const c_char, load: Option<extern "C" fn (arg1: *const c_char, arg2: c_int, arg3: c_int) -> *mut ALLEGRO_FONT>) -> c_bool;
pub fn al_load_bitmap_font(filename: *const c_char) -> *mut ALLEGRO_FONT;
pub fn al_load_font(filename: *const c_char, size: c_int, flags: c_int) -> *mut ALLEGRO_FONT;
pub fn al_grab_font_from_bitmap(bmp: *mut ALLEGRO_BITMAP, n: c_int, ranges: *const c_int) -> *mut ALLEGRO_FONT;
pub fn al_create_builtin_font() -> *mut ALLEGRO_FONT;
pub fn al_draw_ustr(font: *const ALLEGRO_FONT, color: ALLEGRO_COLOR, x: c_float, y: c_float, flags: c_int, ustr: *const ALLEGRO_USTR);
pub fn al_draw_text(font: *const ALLEGRO_FONT, color: ALLEGRO_COLOR, x: c_float, y: c_float, flags: c_int, text: *const c_char);
pub fn al_draw_justified_text(font: *const ALLEGRO_FONT, color: ALLEGRO_COLOR, x1: c_float, x2: c_float, y: c_float, diff: c_float, flags: c_int, text: *const c_char);
pub fn al_draw_justified_ustr(font: *const ALLEGRO_FONT, color: ALLEGRO_COLOR, x1: c_float, x2: c_float, y: c_float, diff: c_float, flags: c_int, text: *const ALLEGRO_USTR);
pub fn al_get_text_width(f: *const ALLEGRO_FONT, str: *const c_char) -> c_int;
pub fn al_get_ustr_width(f: *const ALLEGRO_FONT, ustr: *const ALLEGRO_USTR) -> c_int;
pub fn al_get_font_line_height(f: *const ALLEGRO_FONT) -> c_int;
pub fn al_get_font_ascent(f: *const ALLEGRO_FONT) -> c_int;
pub fn al_get_font_descent(f: *const ALLEGRO_FONT) -> c_int;
pub fn al_destroy_font(f: *mut ALLEGRO_FONT);
pub fn al_get_ustr_dimensions(f: *const ALLEGRO_FONT, text: *const ALLEGRO_USTR, bbx: *mut c_int, bby: *mut c_int, bbw: *mut c_int, bbh: *mut c_int);
pub fn al_get_text_dimensions(f: *const ALLEGRO_FONT, text: *const c_char, bbx: *mut c_int, bby: *mut c_int, bbw: *mut c_int, bbh: *mut c_int);
pub fn al_init_font_addon();
pub fn al_shutdown_font_addon();
pub fn al_get_allegro_font_version() -> uint32_t;
}
} | use allegro::{ALLEGRO_USTR, ALLEGRO_COLOR, ALLEGRO_BITMAP};
#[repr(C)]
#[derive(Copy, Clone)] | random_line_split |
publisher_to_multiple_subscribers.rs | use crossbeam::channel::unbounded;
use std::process::Command;
mod util;
mod msg {
rosrust::rosmsg_include!(std_msgs / String, rosgraph_msgs / Log);
}
#[test]
fn | () {
let _roscore = util::run_roscore_for(util::Language::Multi, util::Feature::Publisher);
let _subscriber_cpp = util::ChildProcessTerminator::spawn(
Command::new("rosrun")
.arg("roscpp_tutorials")
.arg("listener")
.arg("__name:=listener_cpp"),
);
let _subscriber_py = util::ChildProcessTerminator::spawn(
Command::new("rosrun")
.arg("rospy_tutorials")
.arg("listener"),
);
let _subscriber_rust = util::ChildProcessTerminator::spawn_example(
Command::new("cargo")
.arg("run")
.arg("--example")
.arg("subscriber"),
);
rosrust::init("hello_world_talker");
let (tx, rx) = unbounded();
let _log_subscriber =
rosrust::subscribe::<msg::rosgraph_msgs::Log, _>("/rosout_agg", 100, move |data| {
tx.send((data.level, data.msg)).unwrap();
})
.unwrap();
let publisher = rosrust::publish::<msg::std_msgs::String>("chatter", 100).unwrap();
let message = msg::std_msgs::String {
data: "hello world".into(),
};
println!("Checking roscpp subscriber");
util::test_publisher(&publisher, &message, &rx, r"^I heard: \[hello world\]$", 50);
println!("Checking rospy subscriber");
util::test_publisher(&publisher, &message, &rx, r"I heard hello world$", 50);
println!("Checking rosrust subscriber");
util::test_publisher(&publisher, &message, &rx, r"^Received: hello world$", 50);
assert_eq!(publisher.subscriber_count(), 3);
}
| publisher_to_multiple_subscribers | identifier_name |
publisher_to_multiple_subscribers.rs | use crossbeam::channel::unbounded;
use std::process::Command;
mod util;
mod msg {
rosrust::rosmsg_include!(std_msgs / String, rosgraph_msgs / Log);
}
#[test]
fn publisher_to_multiple_subscribers() | rosrust::init("hello_world_talker");
let (tx, rx) = unbounded();
let _log_subscriber =
rosrust::subscribe::<msg::rosgraph_msgs::Log, _>("/rosout_agg", 100, move |data| {
tx.send((data.level, data.msg)).unwrap();
})
.unwrap();
let publisher = rosrust::publish::<msg::std_msgs::String>("chatter", 100).unwrap();
let message = msg::std_msgs::String {
data: "hello world".into(),
};
println!("Checking roscpp subscriber");
util::test_publisher(&publisher, &message, &rx, r"^I heard: \[hello world\]$", 50);
println!("Checking rospy subscriber");
util::test_publisher(&publisher, &message, &rx, r"I heard hello world$", 50);
println!("Checking rosrust subscriber");
util::test_publisher(&publisher, &message, &rx, r"^Received: hello world$", 50);
assert_eq!(publisher.subscriber_count(), 3);
}
| {
let _roscore = util::run_roscore_for(util::Language::Multi, util::Feature::Publisher);
let _subscriber_cpp = util::ChildProcessTerminator::spawn(
Command::new("rosrun")
.arg("roscpp_tutorials")
.arg("listener")
.arg("__name:=listener_cpp"),
);
let _subscriber_py = util::ChildProcessTerminator::spawn(
Command::new("rosrun")
.arg("rospy_tutorials")
.arg("listener"),
);
let _subscriber_rust = util::ChildProcessTerminator::spawn_example(
Command::new("cargo")
.arg("run")
.arg("--example")
.arg("subscriber"),
);
| identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.