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 |
---|---|---|---|---|
task_resolvers.rs
|
use chrono::{prelude::*};
use async_graphql::{Context, FieldResult, ID};
use eyre::{
eyre,
// Result,
// Context as _,
};
use super::{Task, TaskStatus, task_status::TaskStatusGQL};
use crate::{MachineMap, machine::{
MachineData,
messages::GetData,
}};
/// A spooled set of gcodes to be executed by the machine
#[async_graphql::Object]
impl Task {
async fn id(&self) -> ID { (&self.id).into() }
#[graphql(name="partID")]
async fn part_id(&self) -> Option<ID> {
self.part_id.as_ref().map(Into::into)
}
// async fn name<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<String> {
// let ctx: &Arc<crate::Context> = ctx.data()?;
// if let Some(print) = self.print.as_ref() {
// let part = Part::get(&ctx.db, print.part_id)?;
// Ok(part.name.to_string())
// } else {
// Ok("[UNNAMED_TASK]".to_string())
// }
// }
#[graphql(name = "status")]
async fn _status(&self) -> TaskStatusGQL { (&self.status).into() }
#[graphql(name = "paused")]
async fn _paused(&self) -> bool { self.status.is_paused() }
#[graphql(name = "settled")]
async fn _settled(&self) -> bool { self.status.is_settled() }
async fn total_lines(&self) -> u64 { self.total_lines }
async fn despooled_line_number(&self) -> &Option<u64> { &self.despooled_line_number }
async fn percent_complete(
&self,
#[graphql(desc = r#"
The number of digits to the right of the decimal place to round to. eg.
* percent_complete(digits: 0) gives 3
* percent_complete(digits: 2) gives 3.14
"#)]
digits: Option<u8>,
) -> FieldResult<f32> {
let printed_lines = self.despooled_line_number
.map(|n| n + 1)
.unwrap_or(0) as f32;
let percent = if self.status.was_successful() {
// Empty tasks need to denote success somehow
100.0
} else {
// Empty tasks need to not divide by zero
let total_lines = std::cmp::max(self.total_lines, 1) as f32;
100.0 * printed_lines / total_lines
};
if let Some(digits) = digits {
let scale = 10f32.powi(digits as i32);
Ok((percent * scale).round() / scale)
} else {
Ok(percent)
}
}
async fn estimated_print_time_millis(&self) -> Option<u64> {
self.estimated_print_time.map(|print_time| {
let millis = print_time.as_millis();
// Saturating conversion to u64
std::cmp::min(millis, std::u64::MAX as u128) as u64
})
}
async fn eta<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<Option<DateTime<Utc>>> {
let machines: &MachineMap = ctx.data()?;
let machines = machines.load();
let machine_id = (&self.machine_id).into();
let addr = machines.get(&machine_id)
.ok_or_else(|| eyre!("Unable to get machine ({:?}) for task", machine_id))?;
let machine_data = addr.call(GetData).await??;
let print_time = if let Some(print_time) = self.estimated_print_time {
print_time
} else {
return Ok(None)
};
let mut duration = print_time + self.time_paused + self.time_blocked;
if let TaskStatus::Paused(paused_status) = &self.status {
duration += (Utc::now() - paused_status.paused_at).to_std()?;
} else if let Some(blocked_at) = machine_data.blocked_at {
if self.status.is_pending() {
duration += (Utc::now() - blocked_at).to_std()?;
}
}
let eta= self.created_at + ::chrono::Duration::from_std(duration)?;
Ok(Some(eta))
}
async fn estimated_filament_meters(&self) -> &Option<f64> {
&self.estimated_filament_meters
}
async fn started_at(&self) -> &DateTime<Utc> { &self.created_at }
async fn
|
(&self) -> Option<&DateTime<Utc>> {
use super::*;
match &self.status {
| TaskStatus::Finished(Finished { finished_at: t })
| TaskStatus::Paused(Paused { paused_at: t })
| TaskStatus::Cancelled(Cancelled { cancelled_at: t })
| TaskStatus::Errored(Errored { errored_at: t,.. })
=> Some(t),
_ => None,
}
}
async fn machine<'ctx>(&self, ctx: &'ctx Context<'_>) -> FieldResult<MachineData> {
let machines: &MachineMap = ctx.data()?;
let machines = machines.load();
let machine_id = (&self.machine_id).into();
let addr = machines.get(&machine_id)
.ok_or_else(|| eyre!("Unable to get machine ({:?}) for task", machine_id))?;
let machine_data = addr.call(GetData).await??;
Ok(machine_data)
}
}
|
stopped_at
|
identifier_name
|
event.rs
|
// Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use ffi as ffi;
use EventType;
use Window;
glib_wrapper! {
/// A generic GDK event.
pub struct Event(Boxed<ffi::GdkEvent>);
match fn {
copy => |ptr| ffi::gdk_event_copy(ptr),
free => |ptr| ffi::gdk_event_free(ptr),
}
}
impl Event {
/// Returns the event type.
pub fn get_event_type(&self) -> EventType {
self.as_ref().type_
}
/// Returns the associated `Window` if applicable.
pub fn get_window(&self) -> Option<Window> {
unsafe { from_glib_none(self.as_ref().window) }
}
/// Returns whether the event was sent explicitly.
pub fn get_send_event(&self) -> bool {
from_glib(self.as_ref().send_event as i32)
}
/// Returns `true` if the event type matches `T`.
pub fn is<T: FromEvent>(&self) -> bool {
T::is(self)
}
/// Tries to downcast to a specific event type.
pub fn downcast<T: FromEvent>(self) -> Result<T, Self> {
T::from(self)
}
}
/// A helper trait implemented by all event subtypes.
pub trait FromEvent: Sized {
fn is(ev: &Event) -> bool;
fn from(ev: Event) -> Result<Self, Event>;
}
macro_rules! event_wrapper {
($name:ident, $ffi_name:ident) => {
impl<'a> ToGlibPtr<'a, *const ::ffi::$ffi_name> for $name {
type Storage = &'a Self;
#[inline]
fn to_glib_none(&'a self) -> Stash<'a, *const ::ffi::$ffi_name, Self> {
let ptr = ToGlibPtr::<*const ::ffi::GdkEvent>::to_glib_none(&self.0).0;
Stash(ptr as *const ::ffi::$ffi_name, self)
}
}
impl<'a> ToGlibPtrMut<'a, *mut ::ffi::$ffi_name> for $name {
type Storage = &'a mut Self;
#[inline]
fn to_glib_none_mut(&'a mut self) -> StashMut<'a, *mut ::ffi::$ffi_name, Self> {
let ptr = ToGlibPtrMut::<*mut ::ffi::GdkEvent>::to_glib_none_mut(&mut self.0).0;
StashMut(ptr as *mut ::ffi::$ffi_name, self)
}
}
impl FromGlibPtr<*mut ::ffi::$ffi_name> for $name {
#[inline]
unsafe fn from_glib_none(ptr: *mut ::ffi::$ffi_name) -> Self {
$name(from_glib_none(ptr as *mut ::ffi::GdkEvent))
}
#[inline]
unsafe fn from_glib_full(ptr: *mut ::ffi::$ffi_name) -> Self {
|
}
impl AsRef<::ffi::$ffi_name> for $name {
#[inline]
fn as_ref(&self) -> &::ffi::$ffi_name {
unsafe {
let ptr: *const ::ffi::$ffi_name = self.to_glib_none().0;
&*ptr
}
}
}
impl AsMut<::ffi::$ffi_name> for $name {
#[inline]
fn as_mut(&mut self) -> &mut ::ffi::$ffi_name {
unsafe {
let ptr: *mut ::ffi::$ffi_name = self.to_glib_none_mut().0;
&mut *ptr
}
}
}
}
}
event_wrapper!(Event, GdkEventAny);
macro_rules! event_subtype {
($name:ident, $($ty:ident)|+) => {
impl ::event::FromEvent for $name {
#[inline]
fn is(ev: &::event::Event) -> bool {
skip_assert_initialized!();
use EventType::*;
match ev.as_ref().type_ {
$($ty)|+ => true,
_ => false,
}
}
#[inline]
fn from(ev: ::event::Event) -> Result<Self, ::event::Event> {
skip_assert_initialized!();
if Self::is(&ev) {
Ok($name(ev))
}
else {
Err(ev)
}
}
}
impl ::std::ops::Deref for $name {
type Target = ::event::Event;
fn deref(&self) -> &::event::Event {
&self.0
}
}
impl ::std::ops::DerefMut for $name {
fn deref_mut(&mut self) -> &mut ::event::Event {
&mut self.0
}
}
}
}
|
$name(from_glib_full(ptr as *mut ::ffi::GdkEvent))
}
|
random_line_split
|
event.rs
|
// Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use ffi as ffi;
use EventType;
use Window;
glib_wrapper! {
/// A generic GDK event.
pub struct Event(Boxed<ffi::GdkEvent>);
match fn {
copy => |ptr| ffi::gdk_event_copy(ptr),
free => |ptr| ffi::gdk_event_free(ptr),
}
}
impl Event {
/// Returns the event type.
pub fn get_event_type(&self) -> EventType {
self.as_ref().type_
}
/// Returns the associated `Window` if applicable.
pub fn get_window(&self) -> Option<Window> {
unsafe { from_glib_none(self.as_ref().window) }
}
/// Returns whether the event was sent explicitly.
pub fn
|
(&self) -> bool {
from_glib(self.as_ref().send_event as i32)
}
/// Returns `true` if the event type matches `T`.
pub fn is<T: FromEvent>(&self) -> bool {
T::is(self)
}
/// Tries to downcast to a specific event type.
pub fn downcast<T: FromEvent>(self) -> Result<T, Self> {
T::from(self)
}
}
/// A helper trait implemented by all event subtypes.
pub trait FromEvent: Sized {
fn is(ev: &Event) -> bool;
fn from(ev: Event) -> Result<Self, Event>;
}
macro_rules! event_wrapper {
($name:ident, $ffi_name:ident) => {
impl<'a> ToGlibPtr<'a, *const ::ffi::$ffi_name> for $name {
type Storage = &'a Self;
#[inline]
fn to_glib_none(&'a self) -> Stash<'a, *const ::ffi::$ffi_name, Self> {
let ptr = ToGlibPtr::<*const ::ffi::GdkEvent>::to_glib_none(&self.0).0;
Stash(ptr as *const ::ffi::$ffi_name, self)
}
}
impl<'a> ToGlibPtrMut<'a, *mut ::ffi::$ffi_name> for $name {
type Storage = &'a mut Self;
#[inline]
fn to_glib_none_mut(&'a mut self) -> StashMut<'a, *mut ::ffi::$ffi_name, Self> {
let ptr = ToGlibPtrMut::<*mut ::ffi::GdkEvent>::to_glib_none_mut(&mut self.0).0;
StashMut(ptr as *mut ::ffi::$ffi_name, self)
}
}
impl FromGlibPtr<*mut ::ffi::$ffi_name> for $name {
#[inline]
unsafe fn from_glib_none(ptr: *mut ::ffi::$ffi_name) -> Self {
$name(from_glib_none(ptr as *mut ::ffi::GdkEvent))
}
#[inline]
unsafe fn from_glib_full(ptr: *mut ::ffi::$ffi_name) -> Self {
$name(from_glib_full(ptr as *mut ::ffi::GdkEvent))
}
}
impl AsRef<::ffi::$ffi_name> for $name {
#[inline]
fn as_ref(&self) -> &::ffi::$ffi_name {
unsafe {
let ptr: *const ::ffi::$ffi_name = self.to_glib_none().0;
&*ptr
}
}
}
impl AsMut<::ffi::$ffi_name> for $name {
#[inline]
fn as_mut(&mut self) -> &mut ::ffi::$ffi_name {
unsafe {
let ptr: *mut ::ffi::$ffi_name = self.to_glib_none_mut().0;
&mut *ptr
}
}
}
}
}
event_wrapper!(Event, GdkEventAny);
macro_rules! event_subtype {
($name:ident, $($ty:ident)|+) => {
impl ::event::FromEvent for $name {
#[inline]
fn is(ev: &::event::Event) -> bool {
skip_assert_initialized!();
use EventType::*;
match ev.as_ref().type_ {
$($ty)|+ => true,
_ => false,
}
}
#[inline]
fn from(ev: ::event::Event) -> Result<Self, ::event::Event> {
skip_assert_initialized!();
if Self::is(&ev) {
Ok($name(ev))
}
else {
Err(ev)
}
}
}
impl ::std::ops::Deref for $name {
type Target = ::event::Event;
fn deref(&self) -> &::event::Event {
&self.0
}
}
impl ::std::ops::DerefMut for $name {
fn deref_mut(&mut self) -> &mut ::event::Event {
&mut self.0
}
}
}
}
|
get_send_event
|
identifier_name
|
event.rs
|
// Copyright 2015-2016, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
use glib::translate::*;
use ffi as ffi;
use EventType;
use Window;
glib_wrapper! {
/// A generic GDK event.
pub struct Event(Boxed<ffi::GdkEvent>);
match fn {
copy => |ptr| ffi::gdk_event_copy(ptr),
free => |ptr| ffi::gdk_event_free(ptr),
}
}
impl Event {
/// Returns the event type.
pub fn get_event_type(&self) -> EventType
|
/// Returns the associated `Window` if applicable.
pub fn get_window(&self) -> Option<Window> {
unsafe { from_glib_none(self.as_ref().window) }
}
/// Returns whether the event was sent explicitly.
pub fn get_send_event(&self) -> bool {
from_glib(self.as_ref().send_event as i32)
}
/// Returns `true` if the event type matches `T`.
pub fn is<T: FromEvent>(&self) -> bool {
T::is(self)
}
/// Tries to downcast to a specific event type.
pub fn downcast<T: FromEvent>(self) -> Result<T, Self> {
T::from(self)
}
}
/// A helper trait implemented by all event subtypes.
pub trait FromEvent: Sized {
fn is(ev: &Event) -> bool;
fn from(ev: Event) -> Result<Self, Event>;
}
macro_rules! event_wrapper {
($name:ident, $ffi_name:ident) => {
impl<'a> ToGlibPtr<'a, *const ::ffi::$ffi_name> for $name {
type Storage = &'a Self;
#[inline]
fn to_glib_none(&'a self) -> Stash<'a, *const ::ffi::$ffi_name, Self> {
let ptr = ToGlibPtr::<*const ::ffi::GdkEvent>::to_glib_none(&self.0).0;
Stash(ptr as *const ::ffi::$ffi_name, self)
}
}
impl<'a> ToGlibPtrMut<'a, *mut ::ffi::$ffi_name> for $name {
type Storage = &'a mut Self;
#[inline]
fn to_glib_none_mut(&'a mut self) -> StashMut<'a, *mut ::ffi::$ffi_name, Self> {
let ptr = ToGlibPtrMut::<*mut ::ffi::GdkEvent>::to_glib_none_mut(&mut self.0).0;
StashMut(ptr as *mut ::ffi::$ffi_name, self)
}
}
impl FromGlibPtr<*mut ::ffi::$ffi_name> for $name {
#[inline]
unsafe fn from_glib_none(ptr: *mut ::ffi::$ffi_name) -> Self {
$name(from_glib_none(ptr as *mut ::ffi::GdkEvent))
}
#[inline]
unsafe fn from_glib_full(ptr: *mut ::ffi::$ffi_name) -> Self {
$name(from_glib_full(ptr as *mut ::ffi::GdkEvent))
}
}
impl AsRef<::ffi::$ffi_name> for $name {
#[inline]
fn as_ref(&self) -> &::ffi::$ffi_name {
unsafe {
let ptr: *const ::ffi::$ffi_name = self.to_glib_none().0;
&*ptr
}
}
}
impl AsMut<::ffi::$ffi_name> for $name {
#[inline]
fn as_mut(&mut self) -> &mut ::ffi::$ffi_name {
unsafe {
let ptr: *mut ::ffi::$ffi_name = self.to_glib_none_mut().0;
&mut *ptr
}
}
}
}
}
event_wrapper!(Event, GdkEventAny);
macro_rules! event_subtype {
($name:ident, $($ty:ident)|+) => {
impl ::event::FromEvent for $name {
#[inline]
fn is(ev: &::event::Event) -> bool {
skip_assert_initialized!();
use EventType::*;
match ev.as_ref().type_ {
$($ty)|+ => true,
_ => false,
}
}
#[inline]
fn from(ev: ::event::Event) -> Result<Self, ::event::Event> {
skip_assert_initialized!();
if Self::is(&ev) {
Ok($name(ev))
}
else {
Err(ev)
}
}
}
impl ::std::ops::Deref for $name {
type Target = ::event::Event;
fn deref(&self) -> &::event::Event {
&self.0
}
}
impl ::std::ops::DerefMut for $name {
fn deref_mut(&mut self) -> &mut ::event::Event {
&mut self.0
}
}
}
}
|
{
self.as_ref().type_
}
|
identifier_body
|
lib.rs
|
//#[deny(missing_docs)]
#[macro_use]
extern crate log;
extern crate gfx_core as core;
extern crate d3d11;
extern crate d3dcompiler;
extern crate dxgi;
extern crate dxguid;
extern crate winapi;
extern crate wio;
pub use self::data::map_format;
pub use self::device::Device;
mod command;
pub mod data;
mod execute;
mod device;
mod mirror;
pub mod native;
mod pool;
mod state;
use core::{command as com, handle};
use wio::com::ComPtr;
use std::cell::RefCell;
use std::ptr;
use std::sync::Arc;
use core::{handle as h, texture as tex};
use core::{QueueType, SubmissionResult};
use core::command::{AccessInfo, AccessGuard};
use std::os::raw::c_void;
static FEATURE_LEVELS: [winapi::D3D_FEATURE_LEVEL; 3] = [
winapi::D3D_FEATURE_LEVEL_11_0,
winapi::D3D_FEATURE_LEVEL_10_1,
winapi::D3D_FEATURE_LEVEL_10_0,
];
#[doc(hidden)]
pub struct Instance(pub ComPtr<winapi::IDXGIFactory2>);
impl Instance {
#[doc(hidden)]
pub fn create() -> Self {
// Create DXGI factory
let mut dxgi_factory: *mut winapi::IDXGIFactory2 = ptr::null_mut();
let hr = unsafe {
dxgi::CreateDXGIFactory1(
&dxguid::IID_IDXGIFactory2,
&mut dxgi_factory as *mut *mut _ as *mut *mut c_void)
};
if!winapi::SUCCEEDED(hr) {
error!("Failed on dxgi factory creation: {:?}", hr);
}
Instance(unsafe { ComPtr::new(dxgi_factory) })
}
#[doc(hidden)]
pub fn enumerate_adapters(&mut self) -> Vec<Adapter> {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let mut cur_index = 0;
let mut adapters = Vec::new();
loop {
let mut adapter = {
let mut adapter: *mut winapi::IDXGIAdapter1 = ptr::null_mut();
let hr = unsafe {
self.0.EnumAdapters1(
cur_index,
&mut adapter as *mut *mut _)
};
if hr == winapi::DXGI_ERROR_NOT_FOUND {
break;
}
unsafe { ComPtr::new(adapter) }
};
// We have found a possible adapter
// acquire the device information
let mut desc: winapi::DXGI_ADAPTER_DESC1 = unsafe { std::mem::uninitialized() };
unsafe { adapter.GetDesc1(&mut desc); }
let device_name = {
let len = desc.Description.iter().take_while(|&&c| c!= 0).count();
let name = <OsString as OsStringExt>::from_wide(&desc.Description[..len]);
name.to_string_lossy().into_owned()
};
let info = core::AdapterInfo {
name: device_name,
vendor: desc.VendorId as usize,
device: desc.DeviceId as usize,
software_rendering: false, // TODO
};
adapters.push(
Adapter {
adapter: adapter,
info: info,
queue_family: [(QueueFamily, QueueType::General)],
}
);
cur_index += 1;
}
adapters
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Buffer(native::Buffer);
impl Buffer {
pub fn as_resource(&self) -> *mut winapi::ID3D11Resource {
type Res = *mut winapi::ID3D11Resource;
match self.0 {
native::Buffer(t) => t as Res,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Texture(native::Texture);
impl Texture {
#[doc(hidden)]
pub fn new(tex: native::Texture) -> Self {
Texture(tex)
}
pub fn as_resource(&self) -> *mut winapi::ID3D11Resource {
type Res = *mut winapi::ID3D11Resource;
match self.0 {
native::Texture::D1(t) => t as Res,
native::Texture::D2(t) => t as Res,
native::Texture::D3(t) => t as Res,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Shader {
object: *mut winapi::ID3D11DeviceChild,
reflection: *mut winapi::ID3D11ShaderReflection,
code_hash: u64,
}
unsafe impl Send for Shader {}
unsafe impl Sync for Shader {}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Program {
vs: *mut winapi::ID3D11VertexShader,
hs: *mut winapi::ID3D11HullShader,
ds: *mut winapi::ID3D11DomainShader,
gs: *mut winapi::ID3D11GeometryShader,
ps: *mut winapi::ID3D11PixelShader,
vs_hash: u64,
}
unsafe impl Send for Program {}
unsafe impl Sync for Program {}
pub type InputLayout = *mut winapi::ID3D11InputLayout;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Pipeline {
topology: winapi::D3D11_PRIMITIVE_TOPOLOGY,
layout: InputLayout,
vertex_buffers: [Option<core::pso::VertexBufferDesc>; core::pso::MAX_VERTEX_BUFFERS],
attributes: [Option<core::pso::AttributeDesc>; core::MAX_VERTEX_ATTRIBUTES],
program: Program,
rasterizer: *const winapi::ID3D11RasterizerState,
depth_stencil: *const winapi::ID3D11DepthStencilState,
blend: *const winapi::ID3D11BlendState,
}
unsafe impl Send for Pipeline {}
unsafe impl Sync for Pipeline {}
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Backend {}
impl core::Backend for Backend {
type Adapter = Adapter;
type Resources = Resources;
type CommandQueue = CommandQueue;
type RawCommandBuffer = command::RawCommandBuffer<CommandList>; // TODO: deferred?
type SubpassCommandBuffer = command::SubpassCommandBuffer<CommandList>;
type SubmitInfo = command::SubmitInfo<CommandList>;
type Device = Device;
type QueueFamily = QueueFamily;
type RawCommandPool = pool::RawCommandPool;
type SubpassCommandPool = pool::SubpassCommandPool;
}
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Resources {}
impl core::Resources for Resources {
type Buffer = Buffer;
type Shader = Shader;
type Program = Program;
type PipelineStateObject = Pipeline;
type Texture = Texture;
type RenderTargetView = native::Rtv;
type DepthStencilView = native::Dsv;
type ShaderResourceView = native::Srv;
type UnorderedAccessView = ();
type Sampler = native::Sampler;
type Fence = Fence;
type Semaphore = (); // TODO
type Mapping = device::MappingGate;
}
/// Internal struct of shared data between the device and its factories.
#[doc(hidden)]
pub struct Share {
capabilities: core::Capabilities,
handles: RefCell<h::Manager<Resources>>,
}
pub type ShaderModel = u16;
#[derive(Clone)]
pub struct CommandList(Vec<command::Command>, command::DataBuffer);
impl CommandList {
pub fn new() -> CommandList {
CommandList(Vec::new(), command::DataBuffer::new())
}
}
impl command::Parser for CommandList {
fn reset(&mut self) {
self.0.clear();
self.1.reset();
}
fn parse(&mut self, com: command::Command) {
self.0.push(com);
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset: usize) {
let ptr = self.1.add(data);
self.0.push(command::Command::UpdateBuffer(buf, ptr, offset));
}
fn update_texture(&mut self, tex: Texture, kind: tex::Kind, face: Option<tex::CubeFace>, data: &[u8], image: tex::RawImageInfo) {
let ptr = self.1.add(data);
self.0.push(command::Command::UpdateTexture(tex, kind, face, ptr, image));
}
}
pub struct DeferredContext(ComPtr<winapi::ID3D11DeviceContext>, Option<*mut winapi::ID3D11CommandList>);
unsafe impl Send for DeferredContext {}
impl DeferredContext {
pub fn new(dc: ComPtr<winapi::ID3D11DeviceContext>) -> DeferredContext {
DeferredContext(dc, None)
}
}
impl Drop for DeferredContext {
fn drop(&mut self) {
unsafe { self.0.Release() };
}
}
impl command::Parser for DeferredContext {
fn reset(&mut self) {
if let Some(cl) = self.1 {
unsafe { (*cl).Release() };
self.1 = None;
}
unsafe {
self.0.ClearState()
};
}
fn parse(&mut self, com: command::Command) {
let db = command::DataBuffer::new(); //not used
execute::process(&mut self.0, &com, &db);
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset: usize) {
execute::update_buffer(&mut self.0, &buf, data, offset);
}
fn update_texture(&mut self, tex: Texture, kind: tex::Kind, face: Option<tex::CubeFace>, data: &[u8], image: tex::RawImageInfo) {
execute::update_texture(&mut self.0, &tex, kind, face, data, &image);
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Fence;
pub struct Adapter {
adapter: ComPtr<winapi::IDXGIAdapter1>,
info: core::AdapterInfo,
queue_family: [(QueueFamily, QueueType); 1],
}
impl core::Adapter<Backend> for Adapter {
fn open(&self, queue_descs: &[(&QueueFamily, QueueType, u32)]) -> core::Gpu<Backend> {
// Only support a single queue
assert_eq!(queue_descs.len(), 1);
assert!(queue_descs[0].2 <= 1);
// Create D3D11 device
let mut feature_level = winapi::D3D_FEATURE_LEVEL_10_0;
let (mut dev, context) = {
let mut device: *mut winapi::ID3D11Device = ptr::null_mut();
let mut context: *mut winapi::ID3D11DeviceContext = ptr::null_mut();
let hr = unsafe {
d3d11::D3D11CreateDevice(
self.adapter.as_mut() as *mut _ as *mut winapi::IDXGIAdapter,
winapi::D3D_DRIVER_TYPE_UNKNOWN,
ptr::null_mut(),
0, // TODO
&FEATURE_LEVELS[0],
FEATURE_LEVELS.len() as winapi::UINT,
winapi::D3D11_SDK_VERSION,
&mut device as *mut *mut winapi::ID3D11Device,
&mut feature_level as *mut _,
&mut context as *mut *mut winapi::ID3D11DeviceContext,
)
};
if!winapi::SUCCEEDED(hr) {
error!("error on device creation: {:x}", hr);
}
unsafe { (ComPtr::new(device), ComPtr::new(context)) }
};
let share = Arc::new(Share {
capabilities: core::Capabilities {
max_texture_size: 0,
max_patch_size: 32, //hard-coded in D3D11
instance_base_supported: false,
instance_call_supported: false,
instance_rate_supported: false,
vertex_base_supported: false,
srgb_color_supported: false,
constant_buffer_supported: true,
unordered_access_view_supported: false,
separate_blending_slots_supported: false,
copy_buffer_supported: true,
},
handles: RefCell::new(h::Manager::new()),
});
let device = Device::new(dev.clone(), feature_level, share.clone());
let mut gpu = core::Gpu {
device,
general_queues: Vec::new(),
graphics_queues: Vec::new(),
compute_queues: Vec::new(),
transfer_queues: Vec::new(),
heap_types: Vec::new(),
memory_heaps: Vec::new(),
};
let raw_queue = || {
CommandQueue {
device: dev.clone(),
context: context.clone(),
share: share.clone(),
frame_handles: handle::Manager::new(),
max_resource_count: Some(999999),
}
};
let (_, queue_type, num_queues) = queue_descs[0];
for _ in 0..num_queues {
unsafe {
match queue_type {
QueueType::General => {
gpu.general_queues.push(core::GeneralQueue::new(raw_queue()));
}
QueueType::Graphics => {
gpu.graphics_queues.push(core::GraphicsQueue::new(raw_queue()));
}
QueueType::Compute => {
gpu.compute_queues.push(core::ComputeQueue::new(raw_queue()));
}
QueueType::Transfer => {
gpu.transfer_queues.push(core::TransferQueue::new(raw_queue()));
}
}
}
}
gpu
}
fn info(&self) -> &core::AdapterInfo {
&self.info
}
fn queue_families(&self) -> &[(QueueFamily, QueueType)] {
&self.queue_family
}
}
pub struct CommandQueue {
#[doc(hidden)]
pub device: ComPtr<winapi::ID3D11Device>,
context: ComPtr<winapi::ID3D11DeviceContext>,
share: Arc<Share>,
frame_handles: handle::Manager<Resources>,
max_resource_count: Option<usize>,
}
impl CommandQueue {
pub fn before_submit<'a>(&mut self, gpu_access: &'a AccessInfo<Resources>)
-> core::SubmissionResult<AccessGuard<'a, Resources>> {
let mut gpu_access = try!(gpu_access.take_accesses());
for (buffer, mut mapping) in gpu_access.access_mapped() {
device::ensure_unmapped(&mut mapping, buffer, &mut self.context);
}
Ok(gpu_access)
}
}
impl core::CommandQueue<Backend> for CommandQueue {
unsafe fn submit_raw<'a, I>(
&mut self,
submit_infos: I,
fence: Option<&h::Fence<Resources>>,
access: &com::AccessInfo<Resources>,
) where I: Iterator<Item=core::RawSubmission<'a, Backend>>
|
fn pin_submitted_resources(&mut self, man: &handle::Manager<Resources>) {
self.frame_handles.extend(man);
match self.max_resource_count {
Some(c) if self.frame_handles.count() > c => {
error!("Way too many resources in the current frame. Did you call Device::cleanup()?");
self.max_resource_count = None;
},
_ => (),
}
}
fn cleanup(&mut self) {
use core::handle::Producer;
self.frame_handles.clear();
self.share.handles.borrow_mut().clean_with(&mut self.context,
|ctx, buffer| {
buffer.mapping().map(|raw| {
// we have exclusive access because it's the last reference
let mut mapping = unsafe { raw.use_access() };
device::ensure_unmapped(&mut mapping, buffer, ctx);
});
unsafe { (*(buffer.resource().0).0).Release(); }
},
|_, s| unsafe { //shader
(*s.object).Release();
(*s.reflection).Release();
},
|_, program| unsafe {
let p = program.resource();
if p.vs!= ptr::null_mut() { (*p.vs).Release(); }
if p.hs!= ptr::null_mut() { (*p.hs).Release(); }
if p.ds!= ptr::null_mut() { (*p.ds).Release(); }
if p.gs!= ptr::null_mut() { (*p.gs).Release(); }
if p.ps!= ptr::null_mut() { (*p.ps).Release(); }
},
|_, v| unsafe { //PSO
type Child = *mut winapi::ID3D11DeviceChild;
(*v.layout).Release();
(*(v.rasterizer as Child)).Release();
(*(v.depth_stencil as Child)).Release();
(*(v.blend as Child)).Release();
},
|_, texture| unsafe { (*texture.resource().as_resource()).Release(); },
|_, v| unsafe { (*v.0).Release(); }, //SRV
|_, _| {}, //UAV
|_, v| unsafe { (*v.0).Release(); }, //RTV
|_, v| unsafe { (*v.0).Release(); }, //DSV
|_, v| unsafe { (*v.0).Release(); }, //sampler
|_, _fence| {},
|_, _| {}, // Semaphore
);
}
}
///
#[derive(Debug)]
pub struct QueueFamily;
impl core::QueueFamily for QueueFamily {
fn num_queues(&self) -> u32 { 1 }
}
|
{
let _guard = self.before_submit(access).unwrap();
for submit in submit_infos {
for cb in submit.cmd_buffers {
unsafe { self.context.ClearState(); }
for com in &cb.parser.0 {
execute::process(&mut self.context, com, &cb.parser.1);
}
}
}
// TODO: handle sync
}
|
identifier_body
|
lib.rs
|
//#[deny(missing_docs)]
#[macro_use]
extern crate log;
extern crate gfx_core as core;
extern crate d3d11;
extern crate d3dcompiler;
extern crate dxgi;
extern crate dxguid;
extern crate winapi;
extern crate wio;
pub use self::data::map_format;
pub use self::device::Device;
mod command;
pub mod data;
mod execute;
mod device;
mod mirror;
pub mod native;
mod pool;
mod state;
use core::{command as com, handle};
use wio::com::ComPtr;
use std::cell::RefCell;
use std::ptr;
use std::sync::Arc;
use core::{handle as h, texture as tex};
use core::{QueueType, SubmissionResult};
use core::command::{AccessInfo, AccessGuard};
use std::os::raw::c_void;
static FEATURE_LEVELS: [winapi::D3D_FEATURE_LEVEL; 3] = [
winapi::D3D_FEATURE_LEVEL_11_0,
winapi::D3D_FEATURE_LEVEL_10_1,
winapi::D3D_FEATURE_LEVEL_10_0,
];
#[doc(hidden)]
pub struct Instance(pub ComPtr<winapi::IDXGIFactory2>);
impl Instance {
#[doc(hidden)]
pub fn create() -> Self {
// Create DXGI factory
let mut dxgi_factory: *mut winapi::IDXGIFactory2 = ptr::null_mut();
let hr = unsafe {
dxgi::CreateDXGIFactory1(
&dxguid::IID_IDXGIFactory2,
&mut dxgi_factory as *mut *mut _ as *mut *mut c_void)
};
if!winapi::SUCCEEDED(hr) {
error!("Failed on dxgi factory creation: {:?}", hr);
}
Instance(unsafe { ComPtr::new(dxgi_factory) })
}
#[doc(hidden)]
pub fn enumerate_adapters(&mut self) -> Vec<Adapter> {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let mut cur_index = 0;
let mut adapters = Vec::new();
loop {
let mut adapter = {
let mut adapter: *mut winapi::IDXGIAdapter1 = ptr::null_mut();
let hr = unsafe {
self.0.EnumAdapters1(
cur_index,
&mut adapter as *mut *mut _)
};
if hr == winapi::DXGI_ERROR_NOT_FOUND {
break;
}
unsafe { ComPtr::new(adapter) }
};
// We have found a possible adapter
// acquire the device information
let mut desc: winapi::DXGI_ADAPTER_DESC1 = unsafe { std::mem::uninitialized() };
unsafe { adapter.GetDesc1(&mut desc); }
let device_name = {
let len = desc.Description.iter().take_while(|&&c| c!= 0).count();
let name = <OsString as OsStringExt>::from_wide(&desc.Description[..len]);
name.to_string_lossy().into_owned()
};
let info = core::AdapterInfo {
name: device_name,
vendor: desc.VendorId as usize,
device: desc.DeviceId as usize,
software_rendering: false, // TODO
};
adapters.push(
Adapter {
adapter: adapter,
info: info,
queue_family: [(QueueFamily, QueueType::General)],
}
);
cur_index += 1;
}
adapters
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Buffer(native::Buffer);
impl Buffer {
pub fn as_resource(&self) -> *mut winapi::ID3D11Resource {
type Res = *mut winapi::ID3D11Resource;
match self.0 {
native::Buffer(t) => t as Res,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Texture(native::Texture);
impl Texture {
#[doc(hidden)]
pub fn new(tex: native::Texture) -> Self {
Texture(tex)
}
pub fn as_resource(&self) -> *mut winapi::ID3D11Resource {
type Res = *mut winapi::ID3D11Resource;
match self.0 {
native::Texture::D1(t) => t as Res,
native::Texture::D2(t) => t as Res,
native::Texture::D3(t) => t as Res,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Shader {
object: *mut winapi::ID3D11DeviceChild,
reflection: *mut winapi::ID3D11ShaderReflection,
code_hash: u64,
}
unsafe impl Send for Shader {}
unsafe impl Sync for Shader {}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Program {
vs: *mut winapi::ID3D11VertexShader,
|
}
unsafe impl Send for Program {}
unsafe impl Sync for Program {}
pub type InputLayout = *mut winapi::ID3D11InputLayout;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Pipeline {
topology: winapi::D3D11_PRIMITIVE_TOPOLOGY,
layout: InputLayout,
vertex_buffers: [Option<core::pso::VertexBufferDesc>; core::pso::MAX_VERTEX_BUFFERS],
attributes: [Option<core::pso::AttributeDesc>; core::MAX_VERTEX_ATTRIBUTES],
program: Program,
rasterizer: *const winapi::ID3D11RasterizerState,
depth_stencil: *const winapi::ID3D11DepthStencilState,
blend: *const winapi::ID3D11BlendState,
}
unsafe impl Send for Pipeline {}
unsafe impl Sync for Pipeline {}
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Backend {}
impl core::Backend for Backend {
type Adapter = Adapter;
type Resources = Resources;
type CommandQueue = CommandQueue;
type RawCommandBuffer = command::RawCommandBuffer<CommandList>; // TODO: deferred?
type SubpassCommandBuffer = command::SubpassCommandBuffer<CommandList>;
type SubmitInfo = command::SubmitInfo<CommandList>;
type Device = Device;
type QueueFamily = QueueFamily;
type RawCommandPool = pool::RawCommandPool;
type SubpassCommandPool = pool::SubpassCommandPool;
}
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Resources {}
impl core::Resources for Resources {
type Buffer = Buffer;
type Shader = Shader;
type Program = Program;
type PipelineStateObject = Pipeline;
type Texture = Texture;
type RenderTargetView = native::Rtv;
type DepthStencilView = native::Dsv;
type ShaderResourceView = native::Srv;
type UnorderedAccessView = ();
type Sampler = native::Sampler;
type Fence = Fence;
type Semaphore = (); // TODO
type Mapping = device::MappingGate;
}
/// Internal struct of shared data between the device and its factories.
#[doc(hidden)]
pub struct Share {
capabilities: core::Capabilities,
handles: RefCell<h::Manager<Resources>>,
}
pub type ShaderModel = u16;
#[derive(Clone)]
pub struct CommandList(Vec<command::Command>, command::DataBuffer);
impl CommandList {
pub fn new() -> CommandList {
CommandList(Vec::new(), command::DataBuffer::new())
}
}
impl command::Parser for CommandList {
fn reset(&mut self) {
self.0.clear();
self.1.reset();
}
fn parse(&mut self, com: command::Command) {
self.0.push(com);
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset: usize) {
let ptr = self.1.add(data);
self.0.push(command::Command::UpdateBuffer(buf, ptr, offset));
}
fn update_texture(&mut self, tex: Texture, kind: tex::Kind, face: Option<tex::CubeFace>, data: &[u8], image: tex::RawImageInfo) {
let ptr = self.1.add(data);
self.0.push(command::Command::UpdateTexture(tex, kind, face, ptr, image));
}
}
pub struct DeferredContext(ComPtr<winapi::ID3D11DeviceContext>, Option<*mut winapi::ID3D11CommandList>);
unsafe impl Send for DeferredContext {}
impl DeferredContext {
pub fn new(dc: ComPtr<winapi::ID3D11DeviceContext>) -> DeferredContext {
DeferredContext(dc, None)
}
}
impl Drop for DeferredContext {
fn drop(&mut self) {
unsafe { self.0.Release() };
}
}
impl command::Parser for DeferredContext {
fn reset(&mut self) {
if let Some(cl) = self.1 {
unsafe { (*cl).Release() };
self.1 = None;
}
unsafe {
self.0.ClearState()
};
}
fn parse(&mut self, com: command::Command) {
let db = command::DataBuffer::new(); //not used
execute::process(&mut self.0, &com, &db);
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset: usize) {
execute::update_buffer(&mut self.0, &buf, data, offset);
}
fn update_texture(&mut self, tex: Texture, kind: tex::Kind, face: Option<tex::CubeFace>, data: &[u8], image: tex::RawImageInfo) {
execute::update_texture(&mut self.0, &tex, kind, face, data, &image);
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Fence;
pub struct Adapter {
adapter: ComPtr<winapi::IDXGIAdapter1>,
info: core::AdapterInfo,
queue_family: [(QueueFamily, QueueType); 1],
}
impl core::Adapter<Backend> for Adapter {
fn open(&self, queue_descs: &[(&QueueFamily, QueueType, u32)]) -> core::Gpu<Backend> {
// Only support a single queue
assert_eq!(queue_descs.len(), 1);
assert!(queue_descs[0].2 <= 1);
// Create D3D11 device
let mut feature_level = winapi::D3D_FEATURE_LEVEL_10_0;
let (mut dev, context) = {
let mut device: *mut winapi::ID3D11Device = ptr::null_mut();
let mut context: *mut winapi::ID3D11DeviceContext = ptr::null_mut();
let hr = unsafe {
d3d11::D3D11CreateDevice(
self.adapter.as_mut() as *mut _ as *mut winapi::IDXGIAdapter,
winapi::D3D_DRIVER_TYPE_UNKNOWN,
ptr::null_mut(),
0, // TODO
&FEATURE_LEVELS[0],
FEATURE_LEVELS.len() as winapi::UINT,
winapi::D3D11_SDK_VERSION,
&mut device as *mut *mut winapi::ID3D11Device,
&mut feature_level as *mut _,
&mut context as *mut *mut winapi::ID3D11DeviceContext,
)
};
if!winapi::SUCCEEDED(hr) {
error!("error on device creation: {:x}", hr);
}
unsafe { (ComPtr::new(device), ComPtr::new(context)) }
};
let share = Arc::new(Share {
capabilities: core::Capabilities {
max_texture_size: 0,
max_patch_size: 32, //hard-coded in D3D11
instance_base_supported: false,
instance_call_supported: false,
instance_rate_supported: false,
vertex_base_supported: false,
srgb_color_supported: false,
constant_buffer_supported: true,
unordered_access_view_supported: false,
separate_blending_slots_supported: false,
copy_buffer_supported: true,
},
handles: RefCell::new(h::Manager::new()),
});
let device = Device::new(dev.clone(), feature_level, share.clone());
let mut gpu = core::Gpu {
device,
general_queues: Vec::new(),
graphics_queues: Vec::new(),
compute_queues: Vec::new(),
transfer_queues: Vec::new(),
heap_types: Vec::new(),
memory_heaps: Vec::new(),
};
let raw_queue = || {
CommandQueue {
device: dev.clone(),
context: context.clone(),
share: share.clone(),
frame_handles: handle::Manager::new(),
max_resource_count: Some(999999),
}
};
let (_, queue_type, num_queues) = queue_descs[0];
for _ in 0..num_queues {
unsafe {
match queue_type {
QueueType::General => {
gpu.general_queues.push(core::GeneralQueue::new(raw_queue()));
}
QueueType::Graphics => {
gpu.graphics_queues.push(core::GraphicsQueue::new(raw_queue()));
}
QueueType::Compute => {
gpu.compute_queues.push(core::ComputeQueue::new(raw_queue()));
}
QueueType::Transfer => {
gpu.transfer_queues.push(core::TransferQueue::new(raw_queue()));
}
}
}
}
gpu
}
fn info(&self) -> &core::AdapterInfo {
&self.info
}
fn queue_families(&self) -> &[(QueueFamily, QueueType)] {
&self.queue_family
}
}
pub struct CommandQueue {
#[doc(hidden)]
pub device: ComPtr<winapi::ID3D11Device>,
context: ComPtr<winapi::ID3D11DeviceContext>,
share: Arc<Share>,
frame_handles: handle::Manager<Resources>,
max_resource_count: Option<usize>,
}
impl CommandQueue {
pub fn before_submit<'a>(&mut self, gpu_access: &'a AccessInfo<Resources>)
-> core::SubmissionResult<AccessGuard<'a, Resources>> {
let mut gpu_access = try!(gpu_access.take_accesses());
for (buffer, mut mapping) in gpu_access.access_mapped() {
device::ensure_unmapped(&mut mapping, buffer, &mut self.context);
}
Ok(gpu_access)
}
}
impl core::CommandQueue<Backend> for CommandQueue {
unsafe fn submit_raw<'a, I>(
&mut self,
submit_infos: I,
fence: Option<&h::Fence<Resources>>,
access: &com::AccessInfo<Resources>,
) where I: Iterator<Item=core::RawSubmission<'a, Backend>> {
let _guard = self.before_submit(access).unwrap();
for submit in submit_infos {
for cb in submit.cmd_buffers {
unsafe { self.context.ClearState(); }
for com in &cb.parser.0 {
execute::process(&mut self.context, com, &cb.parser.1);
}
}
}
// TODO: handle sync
}
fn pin_submitted_resources(&mut self, man: &handle::Manager<Resources>) {
self.frame_handles.extend(man);
match self.max_resource_count {
Some(c) if self.frame_handles.count() > c => {
error!("Way too many resources in the current frame. Did you call Device::cleanup()?");
self.max_resource_count = None;
},
_ => (),
}
}
fn cleanup(&mut self) {
use core::handle::Producer;
self.frame_handles.clear();
self.share.handles.borrow_mut().clean_with(&mut self.context,
|ctx, buffer| {
buffer.mapping().map(|raw| {
// we have exclusive access because it's the last reference
let mut mapping = unsafe { raw.use_access() };
device::ensure_unmapped(&mut mapping, buffer, ctx);
});
unsafe { (*(buffer.resource().0).0).Release(); }
},
|_, s| unsafe { //shader
(*s.object).Release();
(*s.reflection).Release();
},
|_, program| unsafe {
let p = program.resource();
if p.vs!= ptr::null_mut() { (*p.vs).Release(); }
if p.hs!= ptr::null_mut() { (*p.hs).Release(); }
if p.ds!= ptr::null_mut() { (*p.ds).Release(); }
if p.gs!= ptr::null_mut() { (*p.gs).Release(); }
if p.ps!= ptr::null_mut() { (*p.ps).Release(); }
},
|_, v| unsafe { //PSO
type Child = *mut winapi::ID3D11DeviceChild;
(*v.layout).Release();
(*(v.rasterizer as Child)).Release();
(*(v.depth_stencil as Child)).Release();
(*(v.blend as Child)).Release();
},
|_, texture| unsafe { (*texture.resource().as_resource()).Release(); },
|_, v| unsafe { (*v.0).Release(); }, //SRV
|_, _| {}, //UAV
|_, v| unsafe { (*v.0).Release(); }, //RTV
|_, v| unsafe { (*v.0).Release(); }, //DSV
|_, v| unsafe { (*v.0).Release(); }, //sampler
|_, _fence| {},
|_, _| {}, // Semaphore
);
}
}
///
#[derive(Debug)]
pub struct QueueFamily;
impl core::QueueFamily for QueueFamily {
fn num_queues(&self) -> u32 { 1 }
}
|
hs: *mut winapi::ID3D11HullShader,
ds: *mut winapi::ID3D11DomainShader,
gs: *mut winapi::ID3D11GeometryShader,
ps: *mut winapi::ID3D11PixelShader,
vs_hash: u64,
|
random_line_split
|
lib.rs
|
//#[deny(missing_docs)]
#[macro_use]
extern crate log;
extern crate gfx_core as core;
extern crate d3d11;
extern crate d3dcompiler;
extern crate dxgi;
extern crate dxguid;
extern crate winapi;
extern crate wio;
pub use self::data::map_format;
pub use self::device::Device;
mod command;
pub mod data;
mod execute;
mod device;
mod mirror;
pub mod native;
mod pool;
mod state;
use core::{command as com, handle};
use wio::com::ComPtr;
use std::cell::RefCell;
use std::ptr;
use std::sync::Arc;
use core::{handle as h, texture as tex};
use core::{QueueType, SubmissionResult};
use core::command::{AccessInfo, AccessGuard};
use std::os::raw::c_void;
static FEATURE_LEVELS: [winapi::D3D_FEATURE_LEVEL; 3] = [
winapi::D3D_FEATURE_LEVEL_11_0,
winapi::D3D_FEATURE_LEVEL_10_1,
winapi::D3D_FEATURE_LEVEL_10_0,
];
#[doc(hidden)]
pub struct Instance(pub ComPtr<winapi::IDXGIFactory2>);
impl Instance {
#[doc(hidden)]
pub fn create() -> Self {
// Create DXGI factory
let mut dxgi_factory: *mut winapi::IDXGIFactory2 = ptr::null_mut();
let hr = unsafe {
dxgi::CreateDXGIFactory1(
&dxguid::IID_IDXGIFactory2,
&mut dxgi_factory as *mut *mut _ as *mut *mut c_void)
};
if!winapi::SUCCEEDED(hr) {
error!("Failed on dxgi factory creation: {:?}", hr);
}
Instance(unsafe { ComPtr::new(dxgi_factory) })
}
#[doc(hidden)]
pub fn enumerate_adapters(&mut self) -> Vec<Adapter> {
use std::ffi::OsString;
use std::os::windows::ffi::OsStringExt;
let mut cur_index = 0;
let mut adapters = Vec::new();
loop {
let mut adapter = {
let mut adapter: *mut winapi::IDXGIAdapter1 = ptr::null_mut();
let hr = unsafe {
self.0.EnumAdapters1(
cur_index,
&mut adapter as *mut *mut _)
};
if hr == winapi::DXGI_ERROR_NOT_FOUND {
break;
}
unsafe { ComPtr::new(adapter) }
};
// We have found a possible adapter
// acquire the device information
let mut desc: winapi::DXGI_ADAPTER_DESC1 = unsafe { std::mem::uninitialized() };
unsafe { adapter.GetDesc1(&mut desc); }
let device_name = {
let len = desc.Description.iter().take_while(|&&c| c!= 0).count();
let name = <OsString as OsStringExt>::from_wide(&desc.Description[..len]);
name.to_string_lossy().into_owned()
};
let info = core::AdapterInfo {
name: device_name,
vendor: desc.VendorId as usize,
device: desc.DeviceId as usize,
software_rendering: false, // TODO
};
adapters.push(
Adapter {
adapter: adapter,
info: info,
queue_family: [(QueueFamily, QueueType::General)],
}
);
cur_index += 1;
}
adapters
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Buffer(native::Buffer);
impl Buffer {
pub fn as_resource(&self) -> *mut winapi::ID3D11Resource {
type Res = *mut winapi::ID3D11Resource;
match self.0 {
native::Buffer(t) => t as Res,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Texture(native::Texture);
impl Texture {
#[doc(hidden)]
pub fn new(tex: native::Texture) -> Self {
Texture(tex)
}
pub fn as_resource(&self) -> *mut winapi::ID3D11Resource {
type Res = *mut winapi::ID3D11Resource;
match self.0 {
native::Texture::D1(t) => t as Res,
native::Texture::D2(t) => t as Res,
native::Texture::D3(t) => t as Res,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
pub struct Shader {
object: *mut winapi::ID3D11DeviceChild,
reflection: *mut winapi::ID3D11ShaderReflection,
code_hash: u64,
}
unsafe impl Send for Shader {}
unsafe impl Sync for Shader {}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct Program {
vs: *mut winapi::ID3D11VertexShader,
hs: *mut winapi::ID3D11HullShader,
ds: *mut winapi::ID3D11DomainShader,
gs: *mut winapi::ID3D11GeometryShader,
ps: *mut winapi::ID3D11PixelShader,
vs_hash: u64,
}
unsafe impl Send for Program {}
unsafe impl Sync for Program {}
pub type InputLayout = *mut winapi::ID3D11InputLayout;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct Pipeline {
topology: winapi::D3D11_PRIMITIVE_TOPOLOGY,
layout: InputLayout,
vertex_buffers: [Option<core::pso::VertexBufferDesc>; core::pso::MAX_VERTEX_BUFFERS],
attributes: [Option<core::pso::AttributeDesc>; core::MAX_VERTEX_ATTRIBUTES],
program: Program,
rasterizer: *const winapi::ID3D11RasterizerState,
depth_stencil: *const winapi::ID3D11DepthStencilState,
blend: *const winapi::ID3D11BlendState,
}
unsafe impl Send for Pipeline {}
unsafe impl Sync for Pipeline {}
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Backend {}
impl core::Backend for Backend {
type Adapter = Adapter;
type Resources = Resources;
type CommandQueue = CommandQueue;
type RawCommandBuffer = command::RawCommandBuffer<CommandList>; // TODO: deferred?
type SubpassCommandBuffer = command::SubpassCommandBuffer<CommandList>;
type SubmitInfo = command::SubmitInfo<CommandList>;
type Device = Device;
type QueueFamily = QueueFamily;
type RawCommandPool = pool::RawCommandPool;
type SubpassCommandPool = pool::SubpassCommandPool;
}
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum Resources {}
impl core::Resources for Resources {
type Buffer = Buffer;
type Shader = Shader;
type Program = Program;
type PipelineStateObject = Pipeline;
type Texture = Texture;
type RenderTargetView = native::Rtv;
type DepthStencilView = native::Dsv;
type ShaderResourceView = native::Srv;
type UnorderedAccessView = ();
type Sampler = native::Sampler;
type Fence = Fence;
type Semaphore = (); // TODO
type Mapping = device::MappingGate;
}
/// Internal struct of shared data between the device and its factories.
#[doc(hidden)]
pub struct Share {
capabilities: core::Capabilities,
handles: RefCell<h::Manager<Resources>>,
}
pub type ShaderModel = u16;
#[derive(Clone)]
pub struct CommandList(Vec<command::Command>, command::DataBuffer);
impl CommandList {
pub fn new() -> CommandList {
CommandList(Vec::new(), command::DataBuffer::new())
}
}
impl command::Parser for CommandList {
fn reset(&mut self) {
self.0.clear();
self.1.reset();
}
fn parse(&mut self, com: command::Command) {
self.0.push(com);
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset: usize) {
let ptr = self.1.add(data);
self.0.push(command::Command::UpdateBuffer(buf, ptr, offset));
}
fn update_texture(&mut self, tex: Texture, kind: tex::Kind, face: Option<tex::CubeFace>, data: &[u8], image: tex::RawImageInfo) {
let ptr = self.1.add(data);
self.0.push(command::Command::UpdateTexture(tex, kind, face, ptr, image));
}
}
pub struct DeferredContext(ComPtr<winapi::ID3D11DeviceContext>, Option<*mut winapi::ID3D11CommandList>);
unsafe impl Send for DeferredContext {}
impl DeferredContext {
pub fn new(dc: ComPtr<winapi::ID3D11DeviceContext>) -> DeferredContext {
DeferredContext(dc, None)
}
}
impl Drop for DeferredContext {
fn drop(&mut self) {
unsafe { self.0.Release() };
}
}
impl command::Parser for DeferredContext {
fn reset(&mut self) {
if let Some(cl) = self.1 {
unsafe { (*cl).Release() };
self.1 = None;
}
unsafe {
self.0.ClearState()
};
}
fn parse(&mut self, com: command::Command) {
let db = command::DataBuffer::new(); //not used
execute::process(&mut self.0, &com, &db);
}
fn update_buffer(&mut self, buf: Buffer, data: &[u8], offset: usize) {
execute::update_buffer(&mut self.0, &buf, data, offset);
}
fn update_texture(&mut self, tex: Texture, kind: tex::Kind, face: Option<tex::CubeFace>, data: &[u8], image: tex::RawImageInfo) {
execute::update_texture(&mut self.0, &tex, kind, face, data, &image);
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct
|
;
pub struct Adapter {
adapter: ComPtr<winapi::IDXGIAdapter1>,
info: core::AdapterInfo,
queue_family: [(QueueFamily, QueueType); 1],
}
impl core::Adapter<Backend> for Adapter {
fn open(&self, queue_descs: &[(&QueueFamily, QueueType, u32)]) -> core::Gpu<Backend> {
// Only support a single queue
assert_eq!(queue_descs.len(), 1);
assert!(queue_descs[0].2 <= 1);
// Create D3D11 device
let mut feature_level = winapi::D3D_FEATURE_LEVEL_10_0;
let (mut dev, context) = {
let mut device: *mut winapi::ID3D11Device = ptr::null_mut();
let mut context: *mut winapi::ID3D11DeviceContext = ptr::null_mut();
let hr = unsafe {
d3d11::D3D11CreateDevice(
self.adapter.as_mut() as *mut _ as *mut winapi::IDXGIAdapter,
winapi::D3D_DRIVER_TYPE_UNKNOWN,
ptr::null_mut(),
0, // TODO
&FEATURE_LEVELS[0],
FEATURE_LEVELS.len() as winapi::UINT,
winapi::D3D11_SDK_VERSION,
&mut device as *mut *mut winapi::ID3D11Device,
&mut feature_level as *mut _,
&mut context as *mut *mut winapi::ID3D11DeviceContext,
)
};
if!winapi::SUCCEEDED(hr) {
error!("error on device creation: {:x}", hr);
}
unsafe { (ComPtr::new(device), ComPtr::new(context)) }
};
let share = Arc::new(Share {
capabilities: core::Capabilities {
max_texture_size: 0,
max_patch_size: 32, //hard-coded in D3D11
instance_base_supported: false,
instance_call_supported: false,
instance_rate_supported: false,
vertex_base_supported: false,
srgb_color_supported: false,
constant_buffer_supported: true,
unordered_access_view_supported: false,
separate_blending_slots_supported: false,
copy_buffer_supported: true,
},
handles: RefCell::new(h::Manager::new()),
});
let device = Device::new(dev.clone(), feature_level, share.clone());
let mut gpu = core::Gpu {
device,
general_queues: Vec::new(),
graphics_queues: Vec::new(),
compute_queues: Vec::new(),
transfer_queues: Vec::new(),
heap_types: Vec::new(),
memory_heaps: Vec::new(),
};
let raw_queue = || {
CommandQueue {
device: dev.clone(),
context: context.clone(),
share: share.clone(),
frame_handles: handle::Manager::new(),
max_resource_count: Some(999999),
}
};
let (_, queue_type, num_queues) = queue_descs[0];
for _ in 0..num_queues {
unsafe {
match queue_type {
QueueType::General => {
gpu.general_queues.push(core::GeneralQueue::new(raw_queue()));
}
QueueType::Graphics => {
gpu.graphics_queues.push(core::GraphicsQueue::new(raw_queue()));
}
QueueType::Compute => {
gpu.compute_queues.push(core::ComputeQueue::new(raw_queue()));
}
QueueType::Transfer => {
gpu.transfer_queues.push(core::TransferQueue::new(raw_queue()));
}
}
}
}
gpu
}
fn info(&self) -> &core::AdapterInfo {
&self.info
}
fn queue_families(&self) -> &[(QueueFamily, QueueType)] {
&self.queue_family
}
}
pub struct CommandQueue {
#[doc(hidden)]
pub device: ComPtr<winapi::ID3D11Device>,
context: ComPtr<winapi::ID3D11DeviceContext>,
share: Arc<Share>,
frame_handles: handle::Manager<Resources>,
max_resource_count: Option<usize>,
}
impl CommandQueue {
pub fn before_submit<'a>(&mut self, gpu_access: &'a AccessInfo<Resources>)
-> core::SubmissionResult<AccessGuard<'a, Resources>> {
let mut gpu_access = try!(gpu_access.take_accesses());
for (buffer, mut mapping) in gpu_access.access_mapped() {
device::ensure_unmapped(&mut mapping, buffer, &mut self.context);
}
Ok(gpu_access)
}
}
impl core::CommandQueue<Backend> for CommandQueue {
unsafe fn submit_raw<'a, I>(
&mut self,
submit_infos: I,
fence: Option<&h::Fence<Resources>>,
access: &com::AccessInfo<Resources>,
) where I: Iterator<Item=core::RawSubmission<'a, Backend>> {
let _guard = self.before_submit(access).unwrap();
for submit in submit_infos {
for cb in submit.cmd_buffers {
unsafe { self.context.ClearState(); }
for com in &cb.parser.0 {
execute::process(&mut self.context, com, &cb.parser.1);
}
}
}
// TODO: handle sync
}
fn pin_submitted_resources(&mut self, man: &handle::Manager<Resources>) {
self.frame_handles.extend(man);
match self.max_resource_count {
Some(c) if self.frame_handles.count() > c => {
error!("Way too many resources in the current frame. Did you call Device::cleanup()?");
self.max_resource_count = None;
},
_ => (),
}
}
fn cleanup(&mut self) {
use core::handle::Producer;
self.frame_handles.clear();
self.share.handles.borrow_mut().clean_with(&mut self.context,
|ctx, buffer| {
buffer.mapping().map(|raw| {
// we have exclusive access because it's the last reference
let mut mapping = unsafe { raw.use_access() };
device::ensure_unmapped(&mut mapping, buffer, ctx);
});
unsafe { (*(buffer.resource().0).0).Release(); }
},
|_, s| unsafe { //shader
(*s.object).Release();
(*s.reflection).Release();
},
|_, program| unsafe {
let p = program.resource();
if p.vs!= ptr::null_mut() { (*p.vs).Release(); }
if p.hs!= ptr::null_mut() { (*p.hs).Release(); }
if p.ds!= ptr::null_mut() { (*p.ds).Release(); }
if p.gs!= ptr::null_mut() { (*p.gs).Release(); }
if p.ps!= ptr::null_mut() { (*p.ps).Release(); }
},
|_, v| unsafe { //PSO
type Child = *mut winapi::ID3D11DeviceChild;
(*v.layout).Release();
(*(v.rasterizer as Child)).Release();
(*(v.depth_stencil as Child)).Release();
(*(v.blend as Child)).Release();
},
|_, texture| unsafe { (*texture.resource().as_resource()).Release(); },
|_, v| unsafe { (*v.0).Release(); }, //SRV
|_, _| {}, //UAV
|_, v| unsafe { (*v.0).Release(); }, //RTV
|_, v| unsafe { (*v.0).Release(); }, //DSV
|_, v| unsafe { (*v.0).Release(); }, //sampler
|_, _fence| {},
|_, _| {}, // Semaphore
);
}
}
///
#[derive(Debug)]
pub struct QueueFamily;
impl core::QueueFamily for QueueFamily {
fn num_queues(&self) -> u32 { 1 }
}
|
Fence
|
identifier_name
|
hello_world.rs
|
extern crate cocoa;
use cocoa::base::{selector, nil, YES, NO};
use cocoa::foundation::{NSUInteger, NSRect, NSPoint, NSSize,
NSAutoreleasePool, NSProcessInfo, NSString};
use cocoa::appkit::{NSApp,
NSApplication, NSApplicationActivationPolicyRegular,
NSWindow, NSTitledWindowMask, NSBackingStoreBuffered,
NSMenu, NSMenuItem};
fn main() {
unsafe {
|
let _pool = NSAutoreleasePool::new(nil);
let app = NSApp();
app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
// create Menu Bar
let menubar = NSMenu::new(nil).autorelease();
let app_menu_item = NSMenuItem::new(nil).autorelease();
menubar.addItem_(app_menu_item);
app.setMainMenu_(menubar);
// create Application menu
let app_menu = NSMenu::new(nil).autorelease();
let quit_prefix = NSString::alloc(nil).init_str("Quit");
let quit_title = quit_prefix.stringByAppendingString_(
NSProcessInfo::processInfo(nil).processName()
);
let quit_action = selector("terminate:");
let quit_key = NSString::alloc(nil).init_str("q");
let quit_item = NSMenuItem::alloc(nil).initWithTitle_action_keyEquivalent_(
quit_title,
quit_action,
quit_key
).autorelease();
app_menu.addItem_(quit_item);
app_menu_item.setSubmenu_(app_menu);
// create Window
let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_(
NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)),
NSTitledWindowMask as NSUInteger,
NSBackingStoreBuffered,
NO
).autorelease();
window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.));
window.center();
let title = NSString::alloc(nil).init_str("Hello World!");
window.setTitle_(title);
window.makeKeyAndOrderFront_(nil);
app.activateIgnoringOtherApps_(YES);
app.run();
}
}
|
random_line_split
|
|
hello_world.rs
|
extern crate cocoa;
use cocoa::base::{selector, nil, YES, NO};
use cocoa::foundation::{NSUInteger, NSRect, NSPoint, NSSize,
NSAutoreleasePool, NSProcessInfo, NSString};
use cocoa::appkit::{NSApp,
NSApplication, NSApplicationActivationPolicyRegular,
NSWindow, NSTitledWindowMask, NSBackingStoreBuffered,
NSMenu, NSMenuItem};
fn main()
|
let quit_key = NSString::alloc(nil).init_str("q");
let quit_item = NSMenuItem::alloc(nil).initWithTitle_action_keyEquivalent_(
quit_title,
quit_action,
quit_key
).autorelease();
app_menu.addItem_(quit_item);
app_menu_item.setSubmenu_(app_menu);
// create Window
let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_(
NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)),
NSTitledWindowMask as NSUInteger,
NSBackingStoreBuffered,
NO
).autorelease();
window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.));
window.center();
let title = NSString::alloc(nil).init_str("Hello World!");
window.setTitle_(title);
window.makeKeyAndOrderFront_(nil);
app.activateIgnoringOtherApps_(YES);
app.run();
}
}
|
{
unsafe {
let _pool = NSAutoreleasePool::new(nil);
let app = NSApp();
app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
// create Menu Bar
let menubar = NSMenu::new(nil).autorelease();
let app_menu_item = NSMenuItem::new(nil).autorelease();
menubar.addItem_(app_menu_item);
app.setMainMenu_(menubar);
// create Application menu
let app_menu = NSMenu::new(nil).autorelease();
let quit_prefix = NSString::alloc(nil).init_str("Quit");
let quit_title = quit_prefix.stringByAppendingString_(
NSProcessInfo::processInfo(nil).processName()
);
let quit_action = selector("terminate:");
|
identifier_body
|
hello_world.rs
|
extern crate cocoa;
use cocoa::base::{selector, nil, YES, NO};
use cocoa::foundation::{NSUInteger, NSRect, NSPoint, NSSize,
NSAutoreleasePool, NSProcessInfo, NSString};
use cocoa::appkit::{NSApp,
NSApplication, NSApplicationActivationPolicyRegular,
NSWindow, NSTitledWindowMask, NSBackingStoreBuffered,
NSMenu, NSMenuItem};
fn
|
() {
unsafe {
let _pool = NSAutoreleasePool::new(nil);
let app = NSApp();
app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
// create Menu Bar
let menubar = NSMenu::new(nil).autorelease();
let app_menu_item = NSMenuItem::new(nil).autorelease();
menubar.addItem_(app_menu_item);
app.setMainMenu_(menubar);
// create Application menu
let app_menu = NSMenu::new(nil).autorelease();
let quit_prefix = NSString::alloc(nil).init_str("Quit");
let quit_title = quit_prefix.stringByAppendingString_(
NSProcessInfo::processInfo(nil).processName()
);
let quit_action = selector("terminate:");
let quit_key = NSString::alloc(nil).init_str("q");
let quit_item = NSMenuItem::alloc(nil).initWithTitle_action_keyEquivalent_(
quit_title,
quit_action,
quit_key
).autorelease();
app_menu.addItem_(quit_item);
app_menu_item.setSubmenu_(app_menu);
// create Window
let window = NSWindow::alloc(nil).initWithContentRect_styleMask_backing_defer_(
NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)),
NSTitledWindowMask as NSUInteger,
NSBackingStoreBuffered,
NO
).autorelease();
window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.));
window.center();
let title = NSString::alloc(nil).init_str("Hello World!");
window.setTitle_(title);
window.makeKeyAndOrderFront_(nil);
app.activateIgnoringOtherApps_(YES);
app.run();
}
}
|
main
|
identifier_name
|
windowing.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/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use compositor_thread::EventLoopWaker;
use euclid::{Point2D, Size2D};
use euclid::{ScaleFactor, TypedPoint2D, TypedSize2D};
use gleam::gl;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::{Key, KeyModifiers, KeyState, TopLevelBrowsingContextId, TraversalDirection};
use net_traits::net_error_list::NetError;
use script_traits::{LoadData, MouseButton, TouchEventType, TouchId, TouchpadPressurePhase};
use servo_geometry::DeviceIndependentPixel;
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::rc::Rc;
use style_traits::DevicePixel;
use style_traits::cursor::Cursor;
use webrender_api::{DeviceUintSize, DeviceUintRect, ScrollLocation};
#[derive(Clone)]
pub enum MouseWindowEvent {
Click(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseDown(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseUp(MouseButton, TypedPoint2D<f32, DevicePixel>),
}
/// Events that the windowing system sends to Servo.
#[derive(Clone)]
pub enum WindowEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem).
///
/// FIXME(pcwalton): This is kind of ugly and may not work well with multiprocess Servo.
/// It's possible that this should be something like
/// `CompositorMessageWindowEvent(compositor_thread::Msg)` instead.
Idle,
/// Sent when part of the window is marked dirty and needs to be redrawn. Before sending this
/// message, the window must make the same GL context as in `PrepareRenderingEvent` current.
Refresh,
/// Sent when the window is resized.
Resize(DeviceUintSize),
/// Touchpad Pressure
TouchpadPressure(TypedPoint2D<f32, DevicePixel>, f32, TouchpadPressurePhase),
/// Sent when a new URL is to be loaded.
LoadUrl(TopLevelBrowsingContextId, ServoUrl),
/// Sent when a mouse hit test is to be performed.
MouseWindowEventClass(MouseWindowEvent),
/// Sent when a mouse move.
MouseWindowMoveEventClass(TypedPoint2D<f32, DevicePixel>),
/// Touch event: type, identifier, point
Touch(TouchEventType, TouchId, TypedPoint2D<f32, DevicePixel>),
/// Sent when the user scrolls. The first point is the delta and the second point is the
/// origin.
Scroll(ScrollLocation, TypedPoint2D<i32, DevicePixel>, TouchEventType),
/// Sent when the user zooms.
Zoom(f32),
/// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel).
PinchZoom(f32),
/// Sent when the user resets zoom to default.
ResetZoom,
/// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace).
Navigation(TopLevelBrowsingContextId, TraversalDirection),
/// Sent when the user quits the application
Quit,
/// Sent when a key input state changes
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Sent when Ctr+R/Apple+R is called to reload the current page.
/// Toggles the Web renderer profiler on and off
ToggleWebRenderProfiler,
Reload(TopLevelBrowsingContextId),
/// Create a new top level browsing context
NewBrowser(ServoUrl, IpcSender<TopLevelBrowsingContextId>),
/// Make a top level browsing context visible, hiding the previous
/// visible one.
SelectBrowser(TopLevelBrowsingContextId),
}
impl Debug for WindowEvent {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
WindowEvent::Idle => write!(f, "Idle"),
WindowEvent::Refresh => write!(f, "Refresh"),
WindowEvent::Resize(..) => write!(f, "Resize"),
WindowEvent::TouchpadPressure(..) => write!(f, "TouchpadPressure"),
WindowEvent::KeyEvent(..) => write!(f, "Key"),
WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"),
WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"),
WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"),
WindowEvent::Touch(..) => write!(f, "Touch"),
WindowEvent::Scroll(..) => write!(f, "Scroll"),
WindowEvent::Zoom(..) => write!(f, "Zoom"),
WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"),
WindowEvent::ResetZoom => write!(f, "ResetZoom"),
WindowEvent::Navigation(..) => write!(f, "Navigation"),
WindowEvent::Quit => write!(f, "Quit"),
WindowEvent::ToggleWebRenderProfiler => write!(f, "ToggleWebRenderProfiler"),
WindowEvent::Reload(..) => write!(f, "Reload"),
WindowEvent::NewBrowser(..) => write!(f, "NewBrowser"),
WindowEvent::SelectBrowser(..) => write!(f, "SelectBrowser"),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum AnimationState {
Idle,
Animating,
}
|
/// Returns the rendering area size in hardware pixels.
fn framebuffer_size(&self) -> DeviceUintSize;
/// Returns the position and size of the window within the rendering area.
fn window_rect(&self) -> DeviceUintRect;
/// Returns the size of the window in density-independent "px" units.
fn size(&self) -> TypedSize2D<f32, DeviceIndependentPixel>;
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self);
/// Return the size of the window with head and borders and position of the window values
fn client_window(&self, ctx: TopLevelBrowsingContextId) -> (Size2D<u32>, Point2D<i32>);
/// Set the size inside of borders and head
fn set_inner_size(&self, ctx: TopLevelBrowsingContextId, size: Size2D<u32>);
/// Set the window position
fn set_position(&self, ctx: TopLevelBrowsingContextId, point: Point2D<i32>);
/// Set fullscreen state
fn set_fullscreen_state(&self, ctx: TopLevelBrowsingContextId, state: bool);
/// Sets the page title for the current page.
fn set_page_title(&self, ctx: TopLevelBrowsingContextId, title: Option<String>);
/// Called when the browser chrome should display a status message.
fn status(&self, ctx: TopLevelBrowsingContextId, Option<String>);
/// Called when the browser has started loading a frame.
fn load_start(&self, ctx: TopLevelBrowsingContextId);
/// Called when the browser is done loading a frame.
fn load_end(&self, ctx: TopLevelBrowsingContextId);
/// Called when the browser encounters an error while loading a URL
fn load_error(&self, ctx: TopLevelBrowsingContextId, code: NetError, url: String);
/// Wether or not to follow a link
fn allow_navigation(&self, ctx: TopLevelBrowsingContextId, url: ServoUrl, IpcSender<bool>);
/// Called when the <head> tag has finished parsing
fn head_parsed(&self, ctx: TopLevelBrowsingContextId);
/// Called when the history state has changed.
fn history_changed(&self, ctx: TopLevelBrowsingContextId, Vec<LoadData>, usize);
/// Returns the scale factor of the system (device pixels / device independent pixels).
fn hidpi_factor(&self) -> ScaleFactor<f32, DeviceIndependentPixel, DevicePixel>;
/// Returns a thread-safe object to wake up the window's event loop.
fn create_event_loop_waker(&self) -> Box<EventLoopWaker>;
/// Requests that the window system prepare a composite. Typically this will involve making
/// some type of platform-specific graphics context current. Returns true if the composite may
/// proceed and false if it should not.
fn prepare_for_composite(&self, width: usize, height: usize) -> bool;
/// Sets the cursor to be used in the window.
fn set_cursor(&self, cursor: Cursor);
/// Process a key event.
fn handle_key(&self, ctx: Option<TopLevelBrowsingContextId>, ch: Option<char>, key: Key, mods: KeyModifiers);
/// Does this window support a clipboard
fn supports_clipboard(&self) -> bool;
/// Add a favicon
fn set_favicon(&self, ctx: TopLevelBrowsingContextId, url: ServoUrl);
/// Return the GL function pointer trait.
fn gl(&self) -> Rc<gl::Gl>;
/// Set whether the application is currently animating.
/// Typically, when animations are active, the window
/// will want to avoid blocking on UI events, and just
/// run the event loop at the vsync interval.
fn set_animation_state(&self, _state: AnimationState) {}
}
|
pub trait WindowMethods {
|
random_line_split
|
windowing.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/. */
//! Abstract windowing methods. The concrete implementations of these can be found in `platform/`.
use compositor_thread::EventLoopWaker;
use euclid::{Point2D, Size2D};
use euclid::{ScaleFactor, TypedPoint2D, TypedSize2D};
use gleam::gl;
use ipc_channel::ipc::IpcSender;
use msg::constellation_msg::{Key, KeyModifiers, KeyState, TopLevelBrowsingContextId, TraversalDirection};
use net_traits::net_error_list::NetError;
use script_traits::{LoadData, MouseButton, TouchEventType, TouchId, TouchpadPressurePhase};
use servo_geometry::DeviceIndependentPixel;
use servo_url::ServoUrl;
use std::fmt::{Debug, Error, Formatter};
use std::rc::Rc;
use style_traits::DevicePixel;
use style_traits::cursor::Cursor;
use webrender_api::{DeviceUintSize, DeviceUintRect, ScrollLocation};
#[derive(Clone)]
pub enum
|
{
Click(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseDown(MouseButton, TypedPoint2D<f32, DevicePixel>),
MouseUp(MouseButton, TypedPoint2D<f32, DevicePixel>),
}
/// Events that the windowing system sends to Servo.
#[derive(Clone)]
pub enum WindowEvent {
/// Sent when no message has arrived, but the event loop was kicked for some reason (perhaps
/// by another Servo subsystem).
///
/// FIXME(pcwalton): This is kind of ugly and may not work well with multiprocess Servo.
/// It's possible that this should be something like
/// `CompositorMessageWindowEvent(compositor_thread::Msg)` instead.
Idle,
/// Sent when part of the window is marked dirty and needs to be redrawn. Before sending this
/// message, the window must make the same GL context as in `PrepareRenderingEvent` current.
Refresh,
/// Sent when the window is resized.
Resize(DeviceUintSize),
/// Touchpad Pressure
TouchpadPressure(TypedPoint2D<f32, DevicePixel>, f32, TouchpadPressurePhase),
/// Sent when a new URL is to be loaded.
LoadUrl(TopLevelBrowsingContextId, ServoUrl),
/// Sent when a mouse hit test is to be performed.
MouseWindowEventClass(MouseWindowEvent),
/// Sent when a mouse move.
MouseWindowMoveEventClass(TypedPoint2D<f32, DevicePixel>),
/// Touch event: type, identifier, point
Touch(TouchEventType, TouchId, TypedPoint2D<f32, DevicePixel>),
/// Sent when the user scrolls. The first point is the delta and the second point is the
/// origin.
Scroll(ScrollLocation, TypedPoint2D<i32, DevicePixel>, TouchEventType),
/// Sent when the user zooms.
Zoom(f32),
/// Simulated "pinch zoom" gesture for non-touch platforms (e.g. ctrl-scrollwheel).
PinchZoom(f32),
/// Sent when the user resets zoom to default.
ResetZoom,
/// Sent when the user uses chrome navigation (i.e. backspace or shift-backspace).
Navigation(TopLevelBrowsingContextId, TraversalDirection),
/// Sent when the user quits the application
Quit,
/// Sent when a key input state changes
KeyEvent(Option<char>, Key, KeyState, KeyModifiers),
/// Sent when Ctr+R/Apple+R is called to reload the current page.
/// Toggles the Web renderer profiler on and off
ToggleWebRenderProfiler,
Reload(TopLevelBrowsingContextId),
/// Create a new top level browsing context
NewBrowser(ServoUrl, IpcSender<TopLevelBrowsingContextId>),
/// Make a top level browsing context visible, hiding the previous
/// visible one.
SelectBrowser(TopLevelBrowsingContextId),
}
impl Debug for WindowEvent {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
match *self {
WindowEvent::Idle => write!(f, "Idle"),
WindowEvent::Refresh => write!(f, "Refresh"),
WindowEvent::Resize(..) => write!(f, "Resize"),
WindowEvent::TouchpadPressure(..) => write!(f, "TouchpadPressure"),
WindowEvent::KeyEvent(..) => write!(f, "Key"),
WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"),
WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"),
WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"),
WindowEvent::Touch(..) => write!(f, "Touch"),
WindowEvent::Scroll(..) => write!(f, "Scroll"),
WindowEvent::Zoom(..) => write!(f, "Zoom"),
WindowEvent::PinchZoom(..) => write!(f, "PinchZoom"),
WindowEvent::ResetZoom => write!(f, "ResetZoom"),
WindowEvent::Navigation(..) => write!(f, "Navigation"),
WindowEvent::Quit => write!(f, "Quit"),
WindowEvent::ToggleWebRenderProfiler => write!(f, "ToggleWebRenderProfiler"),
WindowEvent::Reload(..) => write!(f, "Reload"),
WindowEvent::NewBrowser(..) => write!(f, "NewBrowser"),
WindowEvent::SelectBrowser(..) => write!(f, "SelectBrowser"),
}
}
}
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum AnimationState {
Idle,
Animating,
}
pub trait WindowMethods {
/// Returns the rendering area size in hardware pixels.
fn framebuffer_size(&self) -> DeviceUintSize;
/// Returns the position and size of the window within the rendering area.
fn window_rect(&self) -> DeviceUintRect;
/// Returns the size of the window in density-independent "px" units.
fn size(&self) -> TypedSize2D<f32, DeviceIndependentPixel>;
/// Presents the window to the screen (perhaps by page flipping).
fn present(&self);
/// Return the size of the window with head and borders and position of the window values
fn client_window(&self, ctx: TopLevelBrowsingContextId) -> (Size2D<u32>, Point2D<i32>);
/// Set the size inside of borders and head
fn set_inner_size(&self, ctx: TopLevelBrowsingContextId, size: Size2D<u32>);
/// Set the window position
fn set_position(&self, ctx: TopLevelBrowsingContextId, point: Point2D<i32>);
/// Set fullscreen state
fn set_fullscreen_state(&self, ctx: TopLevelBrowsingContextId, state: bool);
/// Sets the page title for the current page.
fn set_page_title(&self, ctx: TopLevelBrowsingContextId, title: Option<String>);
/// Called when the browser chrome should display a status message.
fn status(&self, ctx: TopLevelBrowsingContextId, Option<String>);
/// Called when the browser has started loading a frame.
fn load_start(&self, ctx: TopLevelBrowsingContextId);
/// Called when the browser is done loading a frame.
fn load_end(&self, ctx: TopLevelBrowsingContextId);
/// Called when the browser encounters an error while loading a URL
fn load_error(&self, ctx: TopLevelBrowsingContextId, code: NetError, url: String);
/// Wether or not to follow a link
fn allow_navigation(&self, ctx: TopLevelBrowsingContextId, url: ServoUrl, IpcSender<bool>);
/// Called when the <head> tag has finished parsing
fn head_parsed(&self, ctx: TopLevelBrowsingContextId);
/// Called when the history state has changed.
fn history_changed(&self, ctx: TopLevelBrowsingContextId, Vec<LoadData>, usize);
/// Returns the scale factor of the system (device pixels / device independent pixels).
fn hidpi_factor(&self) -> ScaleFactor<f32, DeviceIndependentPixel, DevicePixel>;
/// Returns a thread-safe object to wake up the window's event loop.
fn create_event_loop_waker(&self) -> Box<EventLoopWaker>;
/// Requests that the window system prepare a composite. Typically this will involve making
/// some type of platform-specific graphics context current. Returns true if the composite may
/// proceed and false if it should not.
fn prepare_for_composite(&self, width: usize, height: usize) -> bool;
/// Sets the cursor to be used in the window.
fn set_cursor(&self, cursor: Cursor);
/// Process a key event.
fn handle_key(&self, ctx: Option<TopLevelBrowsingContextId>, ch: Option<char>, key: Key, mods: KeyModifiers);
/// Does this window support a clipboard
fn supports_clipboard(&self) -> bool;
/// Add a favicon
fn set_favicon(&self, ctx: TopLevelBrowsingContextId, url: ServoUrl);
/// Return the GL function pointer trait.
fn gl(&self) -> Rc<gl::Gl>;
/// Set whether the application is currently animating.
/// Typically, when animations are active, the window
/// will want to avoid blocking on UI events, and just
/// run the event loop at the vsync interval.
fn set_animation_state(&self, _state: AnimationState) {}
}
|
MouseWindowEvent
|
identifier_name
|
internal_unstable.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
|
#![feature(staged_api, allow_internal_unstable)]
#![staged_api]
#![stable(feature = "stable", since = "1.0.0")]
#[unstable(feature = "function")]
pub fn unstable() {}
#[stable(feature = "stable", since = "1.0.0")]
pub struct Foo {
#[unstable(feature = "struct_field")]
pub x: u8
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! call_unstable_allow {
() => { $crate::unstable() }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! construct_unstable_allow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! pass_through_allow {
($e: expr) => { $e }
}
#[macro_export]
macro_rules! call_unstable_noallow {
() => { $crate::unstable() }
}
#[macro_export]
macro_rules! construct_unstable_noallow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[macro_export]
macro_rules! pass_through_noallow {
($e: expr) => { $e }
}
|
// 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.
|
random_line_split
|
internal_unstable.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.
#![feature(staged_api, allow_internal_unstable)]
#![staged_api]
#![stable(feature = "stable", since = "1.0.0")]
#[unstable(feature = "function")]
pub fn unstable() {}
#[stable(feature = "stable", since = "1.0.0")]
pub struct
|
{
#[unstable(feature = "struct_field")]
pub x: u8
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! call_unstable_allow {
() => { $crate::unstable() }
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! construct_unstable_allow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[allow_internal_unstable]
#[macro_export]
macro_rules! pass_through_allow {
($e: expr) => { $e }
}
#[macro_export]
macro_rules! call_unstable_noallow {
() => { $crate::unstable() }
}
#[macro_export]
macro_rules! construct_unstable_noallow {
($e: expr) => {
$crate::Foo { x: $e }
}
}
#[macro_export]
macro_rules! pass_through_noallow {
($e: expr) => { $e }
}
|
Foo
|
identifier_name
|
sync.rs
|
use core::ops::{Deref, DerefMut};
use kernel::sched::{task_locked, task_unlocked};
use arch::int::{disable_interrupts, enable_interrupts};
use spin::{Mutex as M, MutexGuard as MG};
pub struct Mutex<T> {
l: M<T>,
}
pub struct MutexGuard<'a, T:?Sized + 'a> {
g: Option<MG<'a, T>>,
irq: bool,
task_locked: bool
}
impl<T> Mutex<T> {
pub const fn new(user_data: T) -> Mutex<T> {
Mutex {
l: M::new(user_data),
}
}
pub fn lock(&self) -> MutexGuard<T>
|
pub fn lock_irq(&self) -> MutexGuard<T> {
disable_interrupts();
task_locked();
MutexGuard {
g: Some(self.l.lock()),
irq: true,
task_locked: true
}
}
}
impl<'a, T:?Sized> Deref for MutexGuard<'a, T> {
type Target = T;
fn deref<'b>(&'b self) -> &'b T {
self.g.as_ref().unwrap()
}
}
impl<'a, T:?Sized> DerefMut for MutexGuard<'a, T> {
fn deref_mut<'b>(&'b mut self) -> &'b mut T {
self.g.as_mut().unwrap()
}
}
impl<'a, T:?Sized> Drop for MutexGuard<'a, T> {
fn drop(&mut self) {
drop(self.g.take());
if self.task_locked {
task_unlocked();
}
if self.irq {
enable_interrupts();
}
}
}
|
{
task_locked();
MutexGuard {
g: Some(self.l.lock()),
irq: false,
task_locked: true
}
}
|
identifier_body
|
sync.rs
|
use core::ops::{Deref, DerefMut};
use kernel::sched::{task_locked, task_unlocked};
use arch::int::{disable_interrupts, enable_interrupts};
use spin::{Mutex as M, MutexGuard as MG};
pub struct Mutex<T> {
l: M<T>,
}
pub struct MutexGuard<'a, T:?Sized + 'a> {
g: Option<MG<'a, T>>,
irq: bool,
task_locked: bool
}
impl<T> Mutex<T> {
pub const fn new(user_data: T) -> Mutex<T> {
Mutex {
l: M::new(user_data),
}
}
pub fn lock(&self) -> MutexGuard<T> {
task_locked();
MutexGuard {
g: Some(self.l.lock()),
irq: false,
task_locked: true
}
}
pub fn
|
(&self) -> MutexGuard<T> {
disable_interrupts();
task_locked();
MutexGuard {
g: Some(self.l.lock()),
irq: true,
task_locked: true
}
}
}
impl<'a, T:?Sized> Deref for MutexGuard<'a, T> {
type Target = T;
fn deref<'b>(&'b self) -> &'b T {
self.g.as_ref().unwrap()
}
}
impl<'a, T:?Sized> DerefMut for MutexGuard<'a, T> {
fn deref_mut<'b>(&'b mut self) -> &'b mut T {
self.g.as_mut().unwrap()
}
}
impl<'a, T:?Sized> Drop for MutexGuard<'a, T> {
fn drop(&mut self) {
drop(self.g.take());
if self.task_locked {
task_unlocked();
}
if self.irq {
enable_interrupts();
}
}
}
|
lock_irq
|
identifier_name
|
sync.rs
|
use core::ops::{Deref, DerefMut};
use kernel::sched::{task_locked, task_unlocked};
use arch::int::{disable_interrupts, enable_interrupts};
use spin::{Mutex as M, MutexGuard as MG};
pub struct Mutex<T> {
l: M<T>,
}
pub struct MutexGuard<'a, T:?Sized + 'a> {
g: Option<MG<'a, T>>,
irq: bool,
task_locked: bool
}
impl<T> Mutex<T> {
pub const fn new(user_data: T) -> Mutex<T> {
Mutex {
l: M::new(user_data),
}
}
pub fn lock(&self) -> MutexGuard<T> {
task_locked();
MutexGuard {
g: Some(self.l.lock()),
irq: false,
task_locked: true
}
}
pub fn lock_irq(&self) -> MutexGuard<T> {
disable_interrupts();
task_locked();
MutexGuard {
g: Some(self.l.lock()),
irq: true,
task_locked: true
}
}
}
impl<'a, T:?Sized> Deref for MutexGuard<'a, T> {
type Target = T;
fn deref<'b>(&'b self) -> &'b T {
self.g.as_ref().unwrap()
}
}
impl<'a, T:?Sized> DerefMut for MutexGuard<'a, T> {
fn deref_mut<'b>(&'b mut self) -> &'b mut T {
self.g.as_mut().unwrap()
}
}
impl<'a, T:?Sized> Drop for MutexGuard<'a, T> {
fn drop(&mut self) {
drop(self.g.take());
if self.task_locked
|
if self.irq {
enable_interrupts();
}
}
}
|
{
task_unlocked();
}
|
conditional_block
|
sync.rs
|
use core::ops::{Deref, DerefMut};
use kernel::sched::{task_locked, task_unlocked};
use arch::int::{disable_interrupts, enable_interrupts};
use spin::{Mutex as M, MutexGuard as MG};
pub struct Mutex<T> {
l: M<T>,
}
pub struct MutexGuard<'a, T:?Sized + 'a> {
g: Option<MG<'a, T>>,
irq: bool,
|
}
impl<T> Mutex<T> {
pub const fn new(user_data: T) -> Mutex<T> {
Mutex {
l: M::new(user_data),
}
}
pub fn lock(&self) -> MutexGuard<T> {
task_locked();
MutexGuard {
g: Some(self.l.lock()),
irq: false,
task_locked: true
}
}
pub fn lock_irq(&self) -> MutexGuard<T> {
disable_interrupts();
task_locked();
MutexGuard {
g: Some(self.l.lock()),
irq: true,
task_locked: true
}
}
}
impl<'a, T:?Sized> Deref for MutexGuard<'a, T> {
type Target = T;
fn deref<'b>(&'b self) -> &'b T {
self.g.as_ref().unwrap()
}
}
impl<'a, T:?Sized> DerefMut for MutexGuard<'a, T> {
fn deref_mut<'b>(&'b mut self) -> &'b mut T {
self.g.as_mut().unwrap()
}
}
impl<'a, T:?Sized> Drop for MutexGuard<'a, T> {
fn drop(&mut self) {
drop(self.g.take());
if self.task_locked {
task_unlocked();
}
if self.irq {
enable_interrupts();
}
}
}
|
task_locked: bool
|
random_line_split
|
capture_nil.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.
// compile-flags:-Z no-opt
// This test has to be setup just so to trigger
// the condition which was causing us a crash.
// The situation is that we are capturing a
// () value by ref. We generally feel free,
// however, to substitute NULL pointers and
// undefined values for values of () type, and
// so this caused a segfault when we copied into
// the closure.
//
// The fix is just to not emit any actual loads
// or stores for copies of () type (which is of
// course preferable, as the value itself is
// irrelevant).
use std::task;
fn
|
(x: ()) -> Receiver<()> {
let (tx, rx) = channel::<()>();
task::spawn(proc() {
tx.send(x);
});
rx
}
pub fn main() {
foo(()).recv()
}
|
foo
|
identifier_name
|
capture_nil.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.
// compile-flags:-Z no-opt
// This test has to be setup just so to trigger
// the condition which was causing us a crash.
// The situation is that we are capturing a
// () value by ref. We generally feel free,
// however, to substitute NULL pointers and
// undefined values for values of () type, and
// so this caused a segfault when we copied into
// the closure.
//
// The fix is just to not emit any actual loads
// or stores for copies of () type (which is of
// course preferable, as the value itself is
// irrelevant).
use std::task;
fn foo(x: ()) -> Receiver<()>
|
pub fn main() {
foo(()).recv()
}
|
{
let (tx, rx) = channel::<()>();
task::spawn(proc() {
tx.send(x);
});
rx
}
|
identifier_body
|
capture_nil.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.
// compile-flags:-Z no-opt
// This test has to be setup just so to trigger
// the condition which was causing us a crash.
// The situation is that we are capturing a
// () value by ref. We generally feel free,
// however, to substitute NULL pointers and
// undefined values for values of () type, and
// so this caused a segfault when we copied into
// the closure.
//
// The fix is just to not emit any actual loads
// or stores for copies of () type (which is of
// course preferable, as the value itself is
// irrelevant).
use std::task;
fn foo(x: ()) -> Receiver<()> {
let (tx, rx) = channel::<()>();
task::spawn(proc() {
tx.send(x);
});
rx
}
|
}
|
pub fn main() {
foo(()).recv()
|
random_line_split
|
logger.rs
|
use colored::*;
use env_logger::LogBuilder;
use log::{LogRecord, LogLevel, LogLevelFilter};
use std::env;
pub fn init()
|
builder.init().unwrap();
}
|
{
let format = |record: &LogRecord| {
let level = format!("{: <5}", record.level());
let levelc = match record.level() {
LogLevel::Trace => level.dimmed().yellow(),
LogLevel::Debug => level.black().on_yellow(),
LogLevel::Info => level.green().bold(),
LogLevel::Warn => level.magenta().bold(),
LogLevel::Error => level.red().bold()
};
format!("{} {} {}", levelc, record.target().cyan(), record.args())
};
let mut builder = LogBuilder::new();
builder.format(format).filter(None, LogLevelFilter::Warn);
if env::var("RUST_LOG").is_ok() {
builder.parse(&env::var("RUST_LOG").unwrap());
}
|
identifier_body
|
logger.rs
|
use colored::*;
use env_logger::LogBuilder;
use log::{LogRecord, LogLevel, LogLevelFilter};
use std::env;
pub fn init() {
let format = |record: &LogRecord| {
let level = format!("{: <5}", record.level());
let levelc = match record.level() {
LogLevel::Trace => level.dimmed().yellow(),
LogLevel::Debug => level.black().on_yellow(),
LogLevel::Info => level.green().bold(),
LogLevel::Warn => level.magenta().bold(),
LogLevel::Error => level.red().bold()
};
format!("{} {} {}", levelc, record.target().cyan(), record.args())
|
let mut builder = LogBuilder::new();
builder.format(format).filter(None, LogLevelFilter::Warn);
if env::var("RUST_LOG").is_ok() {
builder.parse(&env::var("RUST_LOG").unwrap());
}
builder.init().unwrap();
}
|
};
|
random_line_split
|
logger.rs
|
use colored::*;
use env_logger::LogBuilder;
use log::{LogRecord, LogLevel, LogLevelFilter};
use std::env;
pub fn
|
() {
let format = |record: &LogRecord| {
let level = format!("{: <5}", record.level());
let levelc = match record.level() {
LogLevel::Trace => level.dimmed().yellow(),
LogLevel::Debug => level.black().on_yellow(),
LogLevel::Info => level.green().bold(),
LogLevel::Warn => level.magenta().bold(),
LogLevel::Error => level.red().bold()
};
format!("{} {} {}", levelc, record.target().cyan(), record.args())
};
let mut builder = LogBuilder::new();
builder.format(format).filter(None, LogLevelFilter::Warn);
if env::var("RUST_LOG").is_ok() {
builder.parse(&env::var("RUST_LOG").unwrap());
}
builder.init().unwrap();
}
|
init
|
identifier_name
|
issue-46576.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-cloudabi no std::fs support
#![allow(dead_code)]
#![deny(unused_imports)]
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
//~^ ERROR unused import: `BufRead`
pub fn read_from_file(path: &str) {
let file = File::open(&path).unwrap();
let mut reader = BufReader::new(file);
let mut s = String::new();
reader.read_to_string(&mut s).unwrap();
}
pub fn read_lines(s: &str)
|
fn main() {}
|
{
for _line in s.lines() {
}
}
|
identifier_body
|
issue-46576.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-cloudabi no std::fs support
#![allow(dead_code)]
#![deny(unused_imports)]
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
//~^ ERROR unused import: `BufRead`
pub fn read_from_file(path: &str) {
let file = File::open(&path).unwrap();
let mut reader = BufReader::new(file);
let mut s = String::new();
reader.read_to_string(&mut s).unwrap();
}
pub fn
|
(s: &str) {
for _line in s.lines() {
}
}
fn main() {}
|
read_lines
|
identifier_name
|
issue-46576.rs
|
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
|
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-cloudabi no std::fs support
#![allow(dead_code)]
#![deny(unused_imports)]
use std::fs::File;
use std::io::{BufRead, BufReader, Read};
//~^ ERROR unused import: `BufRead`
pub fn read_from_file(path: &str) {
let file = File::open(&path).unwrap();
let mut reader = BufReader::new(file);
let mut s = String::new();
reader.read_to_string(&mut s).unwrap();
}
pub fn read_lines(s: &str) {
for _line in s.lines() {
}
}
fn main() {}
|
random_line_split
|
|
dot.rs
|
// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Graph visualization traits and functions to emit dot code.
use std::cmp::Eq;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use petgraph::graph::NodeIndex;
#[allow(unused_macros)]
macro_rules! add_strings {
( $( $x: expr ),* ) => {
{
let mut s = String::new();
$(
s.push_str(&format!("{}", $x));
)*
s
}
};
}
/// Represents the contents of a `GraphViz` attribute block
pub enum DotAttrBlock {
/// The attribute block as string including the surrounding square brackets.
/// Values have to be escaped manually.
Raw(String),
/// List of key-value pairs.
/// Values will be escaped for you.
Attributes(Vec<(String, String)>),
/// Represents one line in a dot file
Hybrid(String, Vec<(String, String)>),
}
impl DotAttrBlock {
fn bake(&mut self) -> &String {
let mut r = String::new();
let attr = if let DotAttrBlock::Hybrid(ref s, ref attr) = *self {
r.push_str(s);
attr.clone()
} else {
Vec::new()
};
if!attr.is_empty() {
*self = DotAttrBlock::Attributes(attr);
}
let s: String = match *self {
DotAttrBlock::Raw(ref l) => return l,
DotAttrBlock::Attributes(ref attrs) => {
if attrs.is_empty()
|
else {
let mut t = " [".to_string();
for &(ref k, ref v) in attrs {
t.push_str(&*format!(" {}={}", k, v));
}
t.push_str(" ]");
t
}
}
_ => unreachable!(),
};
r.push_str(&s);
r.push_str(";\n");
*self = DotAttrBlock::Raw(r);
if let DotAttrBlock::Raw(ref r) = *self {
return r;
}
unreachable!();
}
}
pub trait Index {
fn to_index(&self) -> usize;
}
impl Index for NodeIndex {
fn to_index(&self) -> usize {
self.index()
}
}
/// This trait enables graphs to be generated from implementors.
pub trait GraphDot {
type NodeIndex: Hash + Clone + Eq + Index + Debug;
type EdgeIndex: Hash + Clone + Eq;
fn node_index_new(usize) -> Self::NodeIndex;
fn edge_index_new(usize) -> Self::EdgeIndex;
fn configure(&self) -> String;
fn node_count(&self) -> usize;
fn edge_count(&self) -> usize;
fn nodes(&self) -> Vec<Self::NodeIndex>;
fn edges(&self) -> Vec<Self::EdgeIndex>;
// fn get_node(&self, n: usize) -> Option<&Self::NodeType>;
/// Nodes with the same node_cluster return value will be put in the same
/// graphviz-cluster.
fn node_cluster(&self, _: &Self::NodeIndex) -> Option<usize> {
Some(0)
}
fn node_skip(&self, &Self::NodeIndex) -> bool {
false
}
fn node_attrs(&self, &Self::NodeIndex) -> DotAttrBlock;
fn edge_skip(&self, &Self::EdgeIndex) -> bool {
false
}
fn edge_attrs(&self, &Self::EdgeIndex) -> DotAttrBlock;
fn edge_source(&self, &Self::EdgeIndex) -> Self::NodeIndex;
fn edge_target(&self, &Self::EdgeIndex) -> Self::NodeIndex;
}
pub fn emit_dot<T: GraphDot>(g: &T) -> String {
let mut result = String::new();
result.push_str(&*g.configure());
// Node configurations
{
let nodes = g.nodes();
let mut clustermap = HashMap::<T::NodeIndex, Vec<T::NodeIndex>>::new();
for i in &nodes {
let block = g.node_cluster(i).unwrap_or_else(|| {
radeco_err!("Block not found");
0
});
clustermap
.entry(T::node_index_new(block))
.or_insert_with(Vec::new)
.push(i.clone());
}
for (k, v) in &clustermap {
result.push_str(&*format!("subgraph cluster_{} {{\n", k.to_index()));
result.push_str("style=filled;\n");
result.push_str("fillcolor=gray;\n");
result.push_str("rankdir=TB;\n");
for node in v.iter() {
result.push_str(&*g.node_attrs(node).bake());
}
result.push_str("}\n");
}
}
// Connect nodes by edges.
for edge_i in g.edges() {
if g.edge_skip(&edge_i) {
continue;
}
result.push_str(g.edge_attrs(&edge_i).bake());
}
result.push_str("\n}\n");
result
}
|
{
"".to_owned()
}
|
conditional_block
|
dot.rs
|
// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Graph visualization traits and functions to emit dot code.
use std::cmp::Eq;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use petgraph::graph::NodeIndex;
#[allow(unused_macros)]
macro_rules! add_strings {
( $( $x: expr ),* ) => {
{
let mut s = String::new();
$(
s.push_str(&format!("{}", $x));
)*
s
}
};
}
/// Represents the contents of a `GraphViz` attribute block
pub enum DotAttrBlock {
/// The attribute block as string including the surrounding square brackets.
/// Values have to be escaped manually.
Raw(String),
/// List of key-value pairs.
/// Values will be escaped for you.
Attributes(Vec<(String, String)>),
/// Represents one line in a dot file
Hybrid(String, Vec<(String, String)>),
}
impl DotAttrBlock {
fn
|
(&mut self) -> &String {
let mut r = String::new();
let attr = if let DotAttrBlock::Hybrid(ref s, ref attr) = *self {
r.push_str(s);
attr.clone()
} else {
Vec::new()
};
if!attr.is_empty() {
*self = DotAttrBlock::Attributes(attr);
}
let s: String = match *self {
DotAttrBlock::Raw(ref l) => return l,
DotAttrBlock::Attributes(ref attrs) => {
if attrs.is_empty() {
"".to_owned()
} else {
let mut t = " [".to_string();
for &(ref k, ref v) in attrs {
t.push_str(&*format!(" {}={}", k, v));
}
t.push_str(" ]");
t
}
}
_ => unreachable!(),
};
r.push_str(&s);
r.push_str(";\n");
*self = DotAttrBlock::Raw(r);
if let DotAttrBlock::Raw(ref r) = *self {
return r;
}
unreachable!();
}
}
pub trait Index {
fn to_index(&self) -> usize;
}
impl Index for NodeIndex {
fn to_index(&self) -> usize {
self.index()
}
}
/// This trait enables graphs to be generated from implementors.
pub trait GraphDot {
type NodeIndex: Hash + Clone + Eq + Index + Debug;
type EdgeIndex: Hash + Clone + Eq;
fn node_index_new(usize) -> Self::NodeIndex;
fn edge_index_new(usize) -> Self::EdgeIndex;
fn configure(&self) -> String;
fn node_count(&self) -> usize;
fn edge_count(&self) -> usize;
fn nodes(&self) -> Vec<Self::NodeIndex>;
fn edges(&self) -> Vec<Self::EdgeIndex>;
// fn get_node(&self, n: usize) -> Option<&Self::NodeType>;
/// Nodes with the same node_cluster return value will be put in the same
/// graphviz-cluster.
fn node_cluster(&self, _: &Self::NodeIndex) -> Option<usize> {
Some(0)
}
fn node_skip(&self, &Self::NodeIndex) -> bool {
false
}
fn node_attrs(&self, &Self::NodeIndex) -> DotAttrBlock;
fn edge_skip(&self, &Self::EdgeIndex) -> bool {
false
}
fn edge_attrs(&self, &Self::EdgeIndex) -> DotAttrBlock;
fn edge_source(&self, &Self::EdgeIndex) -> Self::NodeIndex;
fn edge_target(&self, &Self::EdgeIndex) -> Self::NodeIndex;
}
pub fn emit_dot<T: GraphDot>(g: &T) -> String {
let mut result = String::new();
result.push_str(&*g.configure());
// Node configurations
{
let nodes = g.nodes();
let mut clustermap = HashMap::<T::NodeIndex, Vec<T::NodeIndex>>::new();
for i in &nodes {
let block = g.node_cluster(i).unwrap_or_else(|| {
radeco_err!("Block not found");
0
});
clustermap
.entry(T::node_index_new(block))
.or_insert_with(Vec::new)
.push(i.clone());
}
for (k, v) in &clustermap {
result.push_str(&*format!("subgraph cluster_{} {{\n", k.to_index()));
result.push_str("style=filled;\n");
result.push_str("fillcolor=gray;\n");
result.push_str("rankdir=TB;\n");
for node in v.iter() {
result.push_str(&*g.node_attrs(node).bake());
}
result.push_str("}\n");
}
}
// Connect nodes by edges.
for edge_i in g.edges() {
if g.edge_skip(&edge_i) {
continue;
}
result.push_str(g.edge_attrs(&edge_i).bake());
}
result.push_str("\n}\n");
result
}
|
bake
|
identifier_name
|
dot.rs
|
// Copyright (c) 2015, The Radare Project. All rights reserved.
// See the COPYING file at the top-level directory of this distribution.
// Licensed under the BSD 3-Clause License:
// <http://opensource.org/licenses/BSD-3-Clause>
// This file may not be copied, modified, or distributed
// except according to those terms.
//! Graph visualization traits and functions to emit dot code.
|
use std::cmp::Eq;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;
use petgraph::graph::NodeIndex;
#[allow(unused_macros)]
macro_rules! add_strings {
( $( $x: expr ),* ) => {
{
let mut s = String::new();
$(
s.push_str(&format!("{}", $x));
)*
s
}
};
}
/// Represents the contents of a `GraphViz` attribute block
pub enum DotAttrBlock {
/// The attribute block as string including the surrounding square brackets.
/// Values have to be escaped manually.
Raw(String),
/// List of key-value pairs.
/// Values will be escaped for you.
Attributes(Vec<(String, String)>),
/// Represents one line in a dot file
Hybrid(String, Vec<(String, String)>),
}
impl DotAttrBlock {
fn bake(&mut self) -> &String {
let mut r = String::new();
let attr = if let DotAttrBlock::Hybrid(ref s, ref attr) = *self {
r.push_str(s);
attr.clone()
} else {
Vec::new()
};
if!attr.is_empty() {
*self = DotAttrBlock::Attributes(attr);
}
let s: String = match *self {
DotAttrBlock::Raw(ref l) => return l,
DotAttrBlock::Attributes(ref attrs) => {
if attrs.is_empty() {
"".to_owned()
} else {
let mut t = " [".to_string();
for &(ref k, ref v) in attrs {
t.push_str(&*format!(" {}={}", k, v));
}
t.push_str(" ]");
t
}
}
_ => unreachable!(),
};
r.push_str(&s);
r.push_str(";\n");
*self = DotAttrBlock::Raw(r);
if let DotAttrBlock::Raw(ref r) = *self {
return r;
}
unreachable!();
}
}
pub trait Index {
fn to_index(&self) -> usize;
}
impl Index for NodeIndex {
fn to_index(&self) -> usize {
self.index()
}
}
/// This trait enables graphs to be generated from implementors.
pub trait GraphDot {
type NodeIndex: Hash + Clone + Eq + Index + Debug;
type EdgeIndex: Hash + Clone + Eq;
fn node_index_new(usize) -> Self::NodeIndex;
fn edge_index_new(usize) -> Self::EdgeIndex;
fn configure(&self) -> String;
fn node_count(&self) -> usize;
fn edge_count(&self) -> usize;
fn nodes(&self) -> Vec<Self::NodeIndex>;
fn edges(&self) -> Vec<Self::EdgeIndex>;
// fn get_node(&self, n: usize) -> Option<&Self::NodeType>;
/// Nodes with the same node_cluster return value will be put in the same
/// graphviz-cluster.
fn node_cluster(&self, _: &Self::NodeIndex) -> Option<usize> {
Some(0)
}
fn node_skip(&self, &Self::NodeIndex) -> bool {
false
}
fn node_attrs(&self, &Self::NodeIndex) -> DotAttrBlock;
fn edge_skip(&self, &Self::EdgeIndex) -> bool {
false
}
fn edge_attrs(&self, &Self::EdgeIndex) -> DotAttrBlock;
fn edge_source(&self, &Self::EdgeIndex) -> Self::NodeIndex;
fn edge_target(&self, &Self::EdgeIndex) -> Self::NodeIndex;
}
pub fn emit_dot<T: GraphDot>(g: &T) -> String {
let mut result = String::new();
result.push_str(&*g.configure());
// Node configurations
{
let nodes = g.nodes();
let mut clustermap = HashMap::<T::NodeIndex, Vec<T::NodeIndex>>::new();
for i in &nodes {
let block = g.node_cluster(i).unwrap_or_else(|| {
radeco_err!("Block not found");
0
});
clustermap
.entry(T::node_index_new(block))
.or_insert_with(Vec::new)
.push(i.clone());
}
for (k, v) in &clustermap {
result.push_str(&*format!("subgraph cluster_{} {{\n", k.to_index()));
result.push_str("style=filled;\n");
result.push_str("fillcolor=gray;\n");
result.push_str("rankdir=TB;\n");
for node in v.iter() {
result.push_str(&*g.node_attrs(node).bake());
}
result.push_str("}\n");
}
}
// Connect nodes by edges.
for edge_i in g.edges() {
if g.edge_skip(&edge_i) {
continue;
}
result.push_str(g.edge_attrs(&edge_i).bake());
}
result.push_str("\n}\n");
result
}
|
random_line_split
|
|
keyboard.rs
|
use alloc::borrow::ToOwned;
use alloc::string::String;
use alloc::vec::Vec;
use hashbrown::HashSet;
use d7keymap::{KeyAction, KeyCodes, KeyMap, KeySymbol};
use libd7::ipc::{self, protocol::keyboard::KeyboardEvent};
pub struct Keyboard {
keycodes: KeyCodes,
keymap: KeyMap,
pub pressed_modifiers: HashSet<KeySymbol>,
}
impl Keyboard {
pub fn new() -> Self {
let keycodes_json: Vec<u8> =
ipc::request("initrd/read", "keycodes.json".to_owned()).unwrap();
let keymap_json: Vec<u8> = ipc::request("initrd/read", "keymap.json".to_owned()).unwrap();
Self {
keycodes: serde_json::from_slice(&keycodes_json).unwrap(),
keymap: serde_json::from_slice(&keymap_json).unwrap(),
pressed_modifiers: HashSet::new(),
}
}
pub fn process_event(&mut self, event: KeyboardEvent) -> EventAction {
if let Some(keysym) = self.keycodes.clone().get(&event.keycode) {
if self.keymap.modifiers.contains(&keysym) {
if event.release {
self.pressed_modifiers.remove(keysym);
} else {
self.pressed_modifiers.insert(keysym.clone());
}
EventAction::Ignore
} else if!event.release {
let result = self.process_keysym_press(&keysym);
if let Some(action) = result {
EventAction::KeyAction(action)
} else {
EventAction::Unmatched(keysym.clone(), self.pressed_modifiers.clone())
}
} else {
EventAction::Ignore
}
} else {
EventAction::NoSuchSymbol
}
}
pub fn process_keysym_press(&mut self, keysym: &KeySymbol) -> Option<KeyAction>
|
}
#[derive(Debug)]
#[must_use]
pub enum EventAction {
KeyAction(KeyAction),
Unmatched(KeySymbol, HashSet<KeySymbol>),
Ignore,
NoSuchSymbol,
}
|
{
for (k, v) in &self.keymap.mapping {
if k.matches(keysym, &self.pressed_modifiers) {
return Some(if let KeyAction::Remap(to) = v.clone() {
self.process_keysym_press(&to)?
} else {
v.clone()
});
}
}
None
}
|
identifier_body
|
keyboard.rs
|
use alloc::borrow::ToOwned;
use alloc::string::String;
use alloc::vec::Vec;
use hashbrown::HashSet;
use d7keymap::{KeyAction, KeyCodes, KeyMap, KeySymbol};
use libd7::ipc::{self, protocol::keyboard::KeyboardEvent};
pub struct Keyboard {
keycodes: KeyCodes,
keymap: KeyMap,
pub pressed_modifiers: HashSet<KeySymbol>,
}
impl Keyboard {
pub fn new() -> Self {
let keycodes_json: Vec<u8> =
ipc::request("initrd/read", "keycodes.json".to_owned()).unwrap();
let keymap_json: Vec<u8> = ipc::request("initrd/read", "keymap.json".to_owned()).unwrap();
Self {
keycodes: serde_json::from_slice(&keycodes_json).unwrap(),
keymap: serde_json::from_slice(&keymap_json).unwrap(),
pressed_modifiers: HashSet::new(),
}
}
pub fn process_event(&mut self, event: KeyboardEvent) -> EventAction {
if let Some(keysym) = self.keycodes.clone().get(&event.keycode) {
if self.keymap.modifiers.contains(&keysym) {
if event.release {
self.pressed_modifiers.remove(keysym);
} else {
self.pressed_modifiers.insert(keysym.clone());
}
EventAction::Ignore
} else if!event.release {
let result = self.process_keysym_press(&keysym);
if let Some(action) = result {
EventAction::KeyAction(action)
} else {
EventAction::Unmatched(keysym.clone(), self.pressed_modifiers.clone())
}
} else {
EventAction::Ignore
}
} else {
EventAction::NoSuchSymbol
}
}
pub fn
|
(&mut self, keysym: &KeySymbol) -> Option<KeyAction> {
for (k, v) in &self.keymap.mapping {
if k.matches(keysym, &self.pressed_modifiers) {
return Some(if let KeyAction::Remap(to) = v.clone() {
self.process_keysym_press(&to)?
} else {
v.clone()
});
}
}
None
}
}
#[derive(Debug)]
#[must_use]
pub enum EventAction {
KeyAction(KeyAction),
Unmatched(KeySymbol, HashSet<KeySymbol>),
Ignore,
NoSuchSymbol,
}
|
process_keysym_press
|
identifier_name
|
keyboard.rs
|
use alloc::borrow::ToOwned;
use alloc::string::String;
use alloc::vec::Vec;
use hashbrown::HashSet;
use d7keymap::{KeyAction, KeyCodes, KeyMap, KeySymbol};
use libd7::ipc::{self, protocol::keyboard::KeyboardEvent};
pub struct Keyboard {
keycodes: KeyCodes,
keymap: KeyMap,
pub pressed_modifiers: HashSet<KeySymbol>,
}
impl Keyboard {
pub fn new() -> Self {
let keycodes_json: Vec<u8> =
ipc::request("initrd/read", "keycodes.json".to_owned()).unwrap();
let keymap_json: Vec<u8> = ipc::request("initrd/read", "keymap.json".to_owned()).unwrap();
Self {
keycodes: serde_json::from_slice(&keycodes_json).unwrap(),
keymap: serde_json::from_slice(&keymap_json).unwrap(),
pressed_modifiers: HashSet::new(),
}
}
pub fn process_event(&mut self, event: KeyboardEvent) -> EventAction {
if let Some(keysym) = self.keycodes.clone().get(&event.keycode) {
if self.keymap.modifiers.contains(&keysym) {
if event.release {
self.pressed_modifiers.remove(keysym);
} else {
self.pressed_modifiers.insert(keysym.clone());
}
EventAction::Ignore
} else if!event.release {
let result = self.process_keysym_press(&keysym);
if let Some(action) = result {
EventAction::KeyAction(action)
} else {
EventAction::Unmatched(keysym.clone(), self.pressed_modifiers.clone())
}
} else {
EventAction::Ignore
}
} else {
EventAction::NoSuchSymbol
}
}
pub fn process_keysym_press(&mut self, keysym: &KeySymbol) -> Option<KeyAction> {
for (k, v) in &self.keymap.mapping {
if k.matches(keysym, &self.pressed_modifiers) {
return Some(if let KeyAction::Remap(to) = v.clone() {
self.process_keysym_press(&to)?
} else {
v.clone()
});
}
}
None
}
}
#[derive(Debug)]
#[must_use]
pub enum EventAction {
KeyAction(KeyAction),
|
Unmatched(KeySymbol, HashSet<KeySymbol>),
Ignore,
NoSuchSymbol,
}
|
random_line_split
|
|
keyboard.rs
|
use alloc::borrow::ToOwned;
use alloc::string::String;
use alloc::vec::Vec;
use hashbrown::HashSet;
use d7keymap::{KeyAction, KeyCodes, KeyMap, KeySymbol};
use libd7::ipc::{self, protocol::keyboard::KeyboardEvent};
pub struct Keyboard {
keycodes: KeyCodes,
keymap: KeyMap,
pub pressed_modifiers: HashSet<KeySymbol>,
}
impl Keyboard {
pub fn new() -> Self {
let keycodes_json: Vec<u8> =
ipc::request("initrd/read", "keycodes.json".to_owned()).unwrap();
let keymap_json: Vec<u8> = ipc::request("initrd/read", "keymap.json".to_owned()).unwrap();
Self {
keycodes: serde_json::from_slice(&keycodes_json).unwrap(),
keymap: serde_json::from_slice(&keymap_json).unwrap(),
pressed_modifiers: HashSet::new(),
}
}
pub fn process_event(&mut self, event: KeyboardEvent) -> EventAction {
if let Some(keysym) = self.keycodes.clone().get(&event.keycode) {
if self.keymap.modifiers.contains(&keysym) {
if event.release {
self.pressed_modifiers.remove(keysym);
} else {
self.pressed_modifiers.insert(keysym.clone());
}
EventAction::Ignore
} else if!event.release {
let result = self.process_keysym_press(&keysym);
if let Some(action) = result {
EventAction::KeyAction(action)
} else {
EventAction::Unmatched(keysym.clone(), self.pressed_modifiers.clone())
}
} else {
EventAction::Ignore
}
} else
|
}
pub fn process_keysym_press(&mut self, keysym: &KeySymbol) -> Option<KeyAction> {
for (k, v) in &self.keymap.mapping {
if k.matches(keysym, &self.pressed_modifiers) {
return Some(if let KeyAction::Remap(to) = v.clone() {
self.process_keysym_press(&to)?
} else {
v.clone()
});
}
}
None
}
}
#[derive(Debug)]
#[must_use]
pub enum EventAction {
KeyAction(KeyAction),
Unmatched(KeySymbol, HashSet<KeySymbol>),
Ignore,
NoSuchSymbol,
}
|
{
EventAction::NoSuchSymbol
}
|
conditional_block
|
thumbnail2.rs
|
//! Super Mario Maker 2 thumbnail file manipulation.
use crate::decrypt;
use crate::key_tables::*;
use image::jpeg::JPEGEncoder;
use image::{load_from_memory, DynamicImage, ImageError};
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Clone, Debug, PartialEq)]
pub struct Thumbnail2 {
encrypted: Vec<u8>,
jpeg: Option<Vec<u8>>,
jpeg_opt: Option<Vec<u8>>,
}
impl Thumbnail2 {
pub fn new(bytes: Vec<u8>) -> Thumbnail2 {
Thumbnail2 {
encrypted: bytes,
jpeg: None,
jpeg_opt: None,
}
}
pub fn get_encrypted(&self) -> &Vec<u8> {
&self.encrypted
}
pub fn move_jpeg(&mut self) -> Vec<u8> {
self.lazy_load_jpeg();
self.jpeg.clone().unwrap()
}
pub fn get_jpeg(&mut self) -> &[u8] {
self.lazy_load_jpeg();
if let Some(jpeg) = &self.jpeg_opt {
&jpeg[..]
} else {
self.jpeg.as_ref().unwrap()
}
}
pub fn get_jpeg_no_opt(&mut self) -> &[u8] {
self.lazy_load_jpeg();
self.jpeg.as_ref().unwrap()
}
pub fn optimize_jpeg(&mut self) -> Result<(), ImageError> {
let jpeg = self.get_jpeg();
let image = load_from_memory(jpeg)?;
let color = image.color();
match image {
DynamicImage::ImageRgb8(buffer) => {
let (width, height) = buffer.dimensions();
let mut opt = vec![];
let mut encoder = JPEGEncoder::new_with_quality(&mut opt, 80);
encoder
.encode(&buffer.into_raw()[..], width, height, color)
.map_err(ImageError::from)?;
self.jpeg_opt = if opt.len() < jpeg.len()
|
else {
Some(jpeg.to_vec())
};
Ok(())
}
_ => Ok(()),
}
}
fn lazy_load_jpeg(&mut self) {
let decrypted = if self.jpeg.is_none() {
Some(decrypt(self.encrypted.clone(), &THUMBNAIL_KEY_TABLE))
} else {
None
};
if decrypted.is_some() {
self.jpeg = decrypted;
}
}
}
|
{
Some(opt)
}
|
conditional_block
|
thumbnail2.rs
|
use crate::key_tables::*;
use image::jpeg::JPEGEncoder;
use image::{load_from_memory, DynamicImage, ImageError};
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Clone, Debug, PartialEq)]
pub struct Thumbnail2 {
encrypted: Vec<u8>,
jpeg: Option<Vec<u8>>,
jpeg_opt: Option<Vec<u8>>,
}
impl Thumbnail2 {
pub fn new(bytes: Vec<u8>) -> Thumbnail2 {
Thumbnail2 {
encrypted: bytes,
jpeg: None,
jpeg_opt: None,
}
}
pub fn get_encrypted(&self) -> &Vec<u8> {
&self.encrypted
}
pub fn move_jpeg(&mut self) -> Vec<u8> {
self.lazy_load_jpeg();
self.jpeg.clone().unwrap()
}
pub fn get_jpeg(&mut self) -> &[u8] {
self.lazy_load_jpeg();
if let Some(jpeg) = &self.jpeg_opt {
&jpeg[..]
} else {
self.jpeg.as_ref().unwrap()
}
}
pub fn get_jpeg_no_opt(&mut self) -> &[u8] {
self.lazy_load_jpeg();
self.jpeg.as_ref().unwrap()
}
pub fn optimize_jpeg(&mut self) -> Result<(), ImageError> {
let jpeg = self.get_jpeg();
let image = load_from_memory(jpeg)?;
let color = image.color();
match image {
DynamicImage::ImageRgb8(buffer) => {
let (width, height) = buffer.dimensions();
let mut opt = vec![];
let mut encoder = JPEGEncoder::new_with_quality(&mut opt, 80);
encoder
.encode(&buffer.into_raw()[..], width, height, color)
.map_err(ImageError::from)?;
self.jpeg_opt = if opt.len() < jpeg.len() {
Some(opt)
} else {
Some(jpeg.to_vec())
};
Ok(())
}
_ => Ok(()),
}
}
fn lazy_load_jpeg(&mut self) {
let decrypted = if self.jpeg.is_none() {
Some(decrypt(self.encrypted.clone(), &THUMBNAIL_KEY_TABLE))
} else {
None
};
if decrypted.is_some() {
self.jpeg = decrypted;
}
}
}
|
//! Super Mario Maker 2 thumbnail file manipulation.
use crate::decrypt;
|
random_line_split
|
|
thumbnail2.rs
|
//! Super Mario Maker 2 thumbnail file manipulation.
use crate::decrypt;
use crate::key_tables::*;
use image::jpeg::JPEGEncoder;
use image::{load_from_memory, DynamicImage, ImageError};
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Clone, Debug, PartialEq)]
pub struct Thumbnail2 {
encrypted: Vec<u8>,
jpeg: Option<Vec<u8>>,
jpeg_opt: Option<Vec<u8>>,
}
impl Thumbnail2 {
pub fn new(bytes: Vec<u8>) -> Thumbnail2 {
Thumbnail2 {
encrypted: bytes,
jpeg: None,
jpeg_opt: None,
}
}
pub fn
|
(&self) -> &Vec<u8> {
&self.encrypted
}
pub fn move_jpeg(&mut self) -> Vec<u8> {
self.lazy_load_jpeg();
self.jpeg.clone().unwrap()
}
pub fn get_jpeg(&mut self) -> &[u8] {
self.lazy_load_jpeg();
if let Some(jpeg) = &self.jpeg_opt {
&jpeg[..]
} else {
self.jpeg.as_ref().unwrap()
}
}
pub fn get_jpeg_no_opt(&mut self) -> &[u8] {
self.lazy_load_jpeg();
self.jpeg.as_ref().unwrap()
}
pub fn optimize_jpeg(&mut self) -> Result<(), ImageError> {
let jpeg = self.get_jpeg();
let image = load_from_memory(jpeg)?;
let color = image.color();
match image {
DynamicImage::ImageRgb8(buffer) => {
let (width, height) = buffer.dimensions();
let mut opt = vec![];
let mut encoder = JPEGEncoder::new_with_quality(&mut opt, 80);
encoder
.encode(&buffer.into_raw()[..], width, height, color)
.map_err(ImageError::from)?;
self.jpeg_opt = if opt.len() < jpeg.len() {
Some(opt)
} else {
Some(jpeg.to_vec())
};
Ok(())
}
_ => Ok(()),
}
}
fn lazy_load_jpeg(&mut self) {
let decrypted = if self.jpeg.is_none() {
Some(decrypt(self.encrypted.clone(), &THUMBNAIL_KEY_TABLE))
} else {
None
};
if decrypted.is_some() {
self.jpeg = decrypted;
}
}
}
|
get_encrypted
|
identifier_name
|
thumbnail2.rs
|
//! Super Mario Maker 2 thumbnail file manipulation.
use crate::decrypt;
use crate::key_tables::*;
use image::jpeg::JPEGEncoder;
use image::{load_from_memory, DynamicImage, ImageError};
#[cfg(feature = "wasm")]
use wasm_bindgen::prelude::*;
#[cfg_attr(feature = "wasm", wasm_bindgen)]
#[derive(Clone, Debug, PartialEq)]
pub struct Thumbnail2 {
encrypted: Vec<u8>,
jpeg: Option<Vec<u8>>,
jpeg_opt: Option<Vec<u8>>,
}
impl Thumbnail2 {
pub fn new(bytes: Vec<u8>) -> Thumbnail2 {
Thumbnail2 {
encrypted: bytes,
jpeg: None,
jpeg_opt: None,
}
}
pub fn get_encrypted(&self) -> &Vec<u8> {
&self.encrypted
}
pub fn move_jpeg(&mut self) -> Vec<u8>
|
pub fn get_jpeg(&mut self) -> &[u8] {
self.lazy_load_jpeg();
if let Some(jpeg) = &self.jpeg_opt {
&jpeg[..]
} else {
self.jpeg.as_ref().unwrap()
}
}
pub fn get_jpeg_no_opt(&mut self) -> &[u8] {
self.lazy_load_jpeg();
self.jpeg.as_ref().unwrap()
}
pub fn optimize_jpeg(&mut self) -> Result<(), ImageError> {
let jpeg = self.get_jpeg();
let image = load_from_memory(jpeg)?;
let color = image.color();
match image {
DynamicImage::ImageRgb8(buffer) => {
let (width, height) = buffer.dimensions();
let mut opt = vec![];
let mut encoder = JPEGEncoder::new_with_quality(&mut opt, 80);
encoder
.encode(&buffer.into_raw()[..], width, height, color)
.map_err(ImageError::from)?;
self.jpeg_opt = if opt.len() < jpeg.len() {
Some(opt)
} else {
Some(jpeg.to_vec())
};
Ok(())
}
_ => Ok(()),
}
}
fn lazy_load_jpeg(&mut self) {
let decrypted = if self.jpeg.is_none() {
Some(decrypt(self.encrypted.clone(), &THUMBNAIL_KEY_TABLE))
} else {
None
};
if decrypted.is_some() {
self.jpeg = decrypted;
}
}
}
|
{
self.lazy_load_jpeg();
self.jpeg.clone().unwrap()
}
|
identifier_body
|
time_decoder.rs
|
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* io/decoders/time_decoder.rs *
* *
* hprose time decoder for Rust. *
* *
* LastModified: Oct 8, 2016 *
* Author: Chen Fei <[email protected]> *
* *
\**********************************************************/
use io::{Reader, Decoder, DecoderError, ParserError};
use io::tags::*;
use io::reader::cast_error;
use std::result;
use time::*;
type Result = result::Result<Tm, DecoderError>;
pub fn time_decode(r: &mut Reader, tag: u8) -> Result {
match tag {
b @ b'0'... b'9' => Ok(at_utc(Timespec::new((b - b'0') as i64, 0))),
TAG_INTEGER | TAG_LONG => read_long_as_time(r),
TAG_DOUBLE => read_float_as_time(r),
TAG_STRING => read_string_as_time(r),
TAG_DATE => r.read_datetime_without_tag(),
TAG_TIME => r.read_time_without_tag(),
TAG_REF => r.read_ref(),
_ => Err(cast_error(tag, "string"))
}
}
fn read_long_as_time(r: &mut Reader) -> Result {
r.byte_reader.read_i64()
.map(|i| at_utc(Timespec::new(i, 0)))
.map_err(|e| DecoderError::ParserError(e))
}
fn read_float_as_time(r: &mut Reader) -> Result {
r.byte_reader.read_f64()
.map(|f| at_utc(Timespec::new(f as i64, 0)))
.map_err(|e| DecoderError::ParserError(e))
}
fn
|
(r: &mut Reader) -> Result {
r.read_string_without_tag()
.and_then(|s| strptime(&s, "%F %T.%f %z").map_err(|e| DecoderError::ParserError(ParserError::ParseTimeError(e))))
}
|
read_string_as_time
|
identifier_name
|
time_decoder.rs
|
/**********************************************************\
|
| |
\**********************************************************/
/**********************************************************\
* *
* io/decoders/time_decoder.rs *
* *
* hprose time decoder for Rust. *
* *
* LastModified: Oct 8, 2016 *
* Author: Chen Fei <[email protected]> *
* *
\**********************************************************/
use io::{Reader, Decoder, DecoderError, ParserError};
use io::tags::*;
use io::reader::cast_error;
use std::result;
use time::*;
type Result = result::Result<Tm, DecoderError>;
pub fn time_decode(r: &mut Reader, tag: u8) -> Result {
match tag {
b @ b'0'... b'9' => Ok(at_utc(Timespec::new((b - b'0') as i64, 0))),
TAG_INTEGER | TAG_LONG => read_long_as_time(r),
TAG_DOUBLE => read_float_as_time(r),
TAG_STRING => read_string_as_time(r),
TAG_DATE => r.read_datetime_without_tag(),
TAG_TIME => r.read_time_without_tag(),
TAG_REF => r.read_ref(),
_ => Err(cast_error(tag, "string"))
}
}
fn read_long_as_time(r: &mut Reader) -> Result {
r.byte_reader.read_i64()
.map(|i| at_utc(Timespec::new(i, 0)))
.map_err(|e| DecoderError::ParserError(e))
}
fn read_float_as_time(r: &mut Reader) -> Result {
r.byte_reader.read_f64()
.map(|f| at_utc(Timespec::new(f as i64, 0)))
.map_err(|e| DecoderError::ParserError(e))
}
fn read_string_as_time(r: &mut Reader) -> Result {
r.read_string_without_tag()
.and_then(|s| strptime(&s, "%F %T.%f %z").map_err(|e| DecoderError::ParserError(ParserError::ParseTimeError(e))))
}
|
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
|
random_line_split
|
time_decoder.rs
|
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* io/decoders/time_decoder.rs *
* *
* hprose time decoder for Rust. *
* *
* LastModified: Oct 8, 2016 *
* Author: Chen Fei <[email protected]> *
* *
\**********************************************************/
use io::{Reader, Decoder, DecoderError, ParserError};
use io::tags::*;
use io::reader::cast_error;
use std::result;
use time::*;
type Result = result::Result<Tm, DecoderError>;
pub fn time_decode(r: &mut Reader, tag: u8) -> Result
|
fn read_long_as_time(r: &mut Reader) -> Result {
r.byte_reader.read_i64()
.map(|i| at_utc(Timespec::new(i, 0)))
.map_err(|e| DecoderError::ParserError(e))
}
fn read_float_as_time(r: &mut Reader) -> Result {
r.byte_reader.read_f64()
.map(|f| at_utc(Timespec::new(f as i64, 0)))
.map_err(|e| DecoderError::ParserError(e))
}
fn read_string_as_time(r: &mut Reader) -> Result {
r.read_string_without_tag()
.and_then(|s| strptime(&s, "%F %T.%f %z").map_err(|e| DecoderError::ParserError(ParserError::ParseTimeError(e))))
}
|
{
match tag {
b @ b'0' ... b'9' => Ok(at_utc(Timespec::new((b - b'0') as i64, 0))),
TAG_INTEGER | TAG_LONG => read_long_as_time(r),
TAG_DOUBLE => read_float_as_time(r),
TAG_STRING => read_string_as_time(r),
TAG_DATE => r.read_datetime_without_tag(),
TAG_TIME => r.read_time_without_tag(),
TAG_REF => r.read_ref(),
_ => Err(cast_error(tag, "string"))
}
}
|
identifier_body
|
mem.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Basic functions for dealing with memory
//!
//! This module contains functions for querying the size and alignment of
//! types, initializing and manipulating memory.
#![stable(feature = "rust1", since = "1.0.0")]
use marker::Sized;
use intrinsics;
use ptr;
#[stable(feature = "rust1", since = "1.0.0")]
pub use intrinsics::transmute;
/// Leaks a value into the void, consuming ownership and never running its
/// destructor.
///
/// This function will take ownership of its argument, but is distinct from the
/// `mem::drop` function in that it **does not run the destructor**, leaking the
/// value and any resources that it owns.
///
/// # Safety
///
/// This function is not marked as `unsafe` as Rust does not guarantee that the
/// `Drop` implementation for a value will always run. Note, however, that
/// leaking resources such as memory or I/O objects is likely not desired, so
/// this function is only recommended for specialized use cases.
///
/// The safety of this function implies that when writing `unsafe` code
/// yourself care must be taken when leveraging a destructor that is required to
/// run to preserve memory safety. There are known situations where the
/// destructor may not run (such as if ownership of the object with the
/// destructor is returned) which must be taken into account.
///
/// # Other forms of Leakage
///
/// It's important to point out that this function is not the only method by
/// which a value can be leaked in safe Rust code. Other known sources of
/// leakage are:
///
/// * `Rc` and `Arc` cycles
/// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally)
/// * Panicking destructors are likely to leak local resources
///
/// # When To Use
///
/// There's only a few reasons to use this function. They mainly come
/// up in unsafe code or FFI code.
///
/// * You have an uninitialized value, perhaps for performance reasons, and
/// need to prevent the destructor from running on it.
/// * You have two copies of a value (like `std::mem::swap`), but need the
/// destructor to only run once to prevent a double free.
/// * Transferring resources across FFI boundries.
///
/// # Example
///
/// Leak some heap memory by never deallocating it.
///
/// ```rust
/// use std::mem;
///
/// let heap_memory = Box::new(3);
/// mem::forget(heap_memory);
/// ```
///
/// Leak an I/O object, never closing the file.
///
/// ```rust,no_run
/// use std::mem;
/// use std::fs::File;
///
/// let file = File::open("foo.txt").unwrap();
/// mem::forget(file);
/// ```
///
/// The swap function uses forget to good effect.
///
/// ```rust
/// use std::mem;
/// use std::ptr;
///
/// fn swap<T>(x: &mut T, y: &mut T) {
|
/// // Perform the swap, `&mut` pointers never alias
/// ptr::copy_nonoverlapping(&*x, &mut t, 1);
/// ptr::copy_nonoverlapping(&*y, x, 1);
/// ptr::copy_nonoverlapping(&t, y, 1);
///
/// // y and t now point to the same thing, but we need to completely
/// // forget `t` because we do not want to run the destructor for `T`
/// // on its value, which is still owned somewhere outside this function.
/// mem::forget(t);
/// }
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn forget<T>(t: T) {
unsafe { intrinsics::forget(t) }
}
/// Returns the size of a type in bytes.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::size_of::<i32>());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn size_of<T>() -> usize {
unsafe { intrinsics::size_of::<T>() }
}
/// Returns the size of the type that `val` points to in bytes.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::size_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn size_of_val<T:?Sized>(val: &T) -> usize {
unsafe { intrinsics::size_of_val(val) }
}
/// Returns the ABI-required minimum alignment of a type
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::min_align_of::<i32>());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[deprecated(reason = "use `align_of` instead", since = "1.2.0")]
pub fn min_align_of<T>() -> usize {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::min_align_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
pub fn min_align_of_val<T:?Sized>(val: &T) -> usize {
unsafe { intrinsics::min_align_of_val(val) }
}
/// Returns the alignment in memory for a type.
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::align_of::<i32>());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn align_of<T>() -> usize {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::align_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn align_of_val<T:?Sized>(val: &T) -> usize {
unsafe { intrinsics::min_align_of_val(val) }
}
/// Creates a value initialized to zero.
///
/// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
/// operation).
///
/// Care must be taken when using this function, if the type `T` has a destructor and the value
/// falls out of scope (due to unwinding or returning) before being initialized, then the
/// destructor will run on zeroed data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x: i32 = unsafe { mem::zeroed() };
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn zeroed<T>() -> T {
intrinsics::init()
}
/// Creates a value initialized to an unspecified series of bytes.
///
/// The byte sequence usually indicates that the value at the memory
/// in question has been dropped. Thus, *if* T carries a drop flag,
/// any associated destructor will not be run when the value falls out
/// of scope.
///
/// Some code at one time used the `zeroed` function above to
/// accomplish this goal.
///
/// This function is expected to be deprecated with the transition
/// to non-zeroing drop.
#[inline]
#[unstable(feature = "filling_drop")]
pub unsafe fn dropped<T>() -> T {
#[inline(always)]
unsafe fn dropped_impl<T>() -> T { intrinsics::init_dropped() }
dropped_impl()
}
/// Creates an uninitialized value.
///
/// Care must be taken when using this function, if the type `T` has a destructor and the value
/// falls out of scope (due to unwinding or returning) before being initialized, then the
/// destructor will run on uninitialized data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x: i32 = unsafe { mem::uninitialized() };
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn uninitialized<T>() -> T {
intrinsics::uninit()
}
/// Swap the values at two mutable locations of the same type, without deinitialising or copying
/// either one.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x = &mut 5;
/// let y = &mut 42;
///
/// mem::swap(x, y);
///
/// assert_eq!(42, *x);
/// assert_eq!(5, *y);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninitialized();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping(&*x, &mut t, 1);
ptr::copy_nonoverlapping(&*y, x, 1);
ptr::copy_nonoverlapping(&t, y, 1);
// y and t now point to the same thing, but we need to completely
// forget `t` because we do not want to run the destructor for `T`
// on its value, which is still owned somewhere outside this function.
forget(t);
}
}
/// Replaces the value at a mutable location with a new one, returning the old value, without
/// deinitialising or copying either one.
///
/// This is primarily used for transferring and swapping ownership of a value in a mutable
/// location.
///
/// # Examples
///
/// A simple example:
///
/// ```
/// use std::mem;
///
/// let mut v: Vec<i32> = Vec::new();
///
/// mem::replace(&mut v, Vec::new());
/// ```
///
/// This function allows consumption of one field of a struct by replacing it with another value.
/// The normal approach doesn't always work:
///
/// ```rust,ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// // error: cannot move out of dereference of `&mut`-pointer
/// let buf = self.buf;
/// self.buf = Vec::new();
/// buf
/// }
/// }
/// ```
///
/// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset
/// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
/// `self`, allowing it to be returned:
///
/// ```
/// use std::mem;
/// # struct Buffer<T> { buf: Vec<T> }
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// mem::replace(&mut self.buf, Vec::new())
/// }
/// }
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn replace<T>(dest: &mut T, mut src: T) -> T {
swap(dest, &mut src);
src
}
/// Disposes of a value.
///
/// While this does call the argument's implementation of `Drop`, it will not
/// release any borrows, as borrows are based on lexical scope.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let v = vec![1, 2, 3];
///
/// drop(v); // explicitly drop the vector
/// ```
///
/// Borrows are based on lexical scope, so this produces an error:
///
/// ```ignore
/// let mut v = vec![1, 2, 3];
/// let x = &v[0];
///
/// drop(x); // explicitly drop the reference, but the borrow still exists
///
/// v.push(4); // error: cannot borrow `v` as mutable because it is also
/// // borrowed as immutable
/// ```
///
/// An inner scope is needed to fix this:
///
/// ```
/// let mut v = vec![1, 2, 3];
///
/// {
/// let x = &v[0];
///
/// drop(x); // this is now redundant, as `x` is going out of scope anyway
/// }
///
/// v.push(4); // no problems
/// ```
///
/// Since `RefCell` enforces the borrow rules at runtime, `drop()` can
/// seemingly release a borrow of one:
///
/// ```
/// use std::cell::RefCell;
///
/// let x = RefCell::new(1);
///
/// let mut mutable_borrow = x.borrow_mut();
/// *mutable_borrow = 1;
///
/// drop(mutable_borrow); // relinquish the mutable borrow on this slot
///
/// let borrow = x.borrow();
/// println!("{}", *borrow);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn drop<T>(_x: T) { }
macro_rules! repeat_u8_as_u32 {
($name:expr) => { (($name as u32) << 24 |
($name as u32) << 16 |
($name as u32) << 8 |
($name as u32)) }
}
macro_rules! repeat_u8_as_u64 {
($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 |
(repeat_u8_as_u32!($name) as u64)) }
}
// NOTE: Keep synchronized with values used in librustc_trans::trans::adt.
//
// In particular, the POST_DROP_U8 marker must never equal the
// DTOR_NEEDED_U8 marker.
//
// For a while pnkfelix was using 0xc1 here.
// But having the sign bit set is a pain, so 0x1d is probably better.
//
// And of course, 0x00 brings back the old world of zero'ing on drop.
#[unstable(feature = "filling_drop")]
pub const POST_DROP_U8: u8 = 0x1d;
#[unstable(feature = "filling_drop")]
pub const POST_DROP_U32: u32 = repeat_u8_as_u32!(POST_DROP_U8);
#[unstable(feature = "filling_drop")]
pub const POST_DROP_U64: u64 = repeat_u8_as_u64!(POST_DROP_U8);
#[cfg(target_pointer_width = "32")]
#[unstable(feature = "filling_drop")]
pub const POST_DROP_USIZE: usize = POST_DROP_U32 as usize;
#[cfg(target_pointer_width = "64")]
#[unstable(feature = "filling_drop")]
pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize;
/// Interprets `src` as `&U`, and then reads `src` without moving the contained
/// value.
///
/// This function will unsafely assume the pointer `src` is valid for
/// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
/// will also unsafely create a copy of the contained value instead of moving
/// out of `src`.
///
/// It is not a compile-time error if `T` and `U` have different sizes, but it
/// is highly encouraged to only invoke this function where `T` and `U` have the
/// same size. This function triggers undefined behavior if `U` is larger than
/// `T`.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let one = unsafe { mem::transmute_copy(&1) };
///
/// assert_eq!(1, one);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
// FIXME(#23542) Replace with type ascription.
#![allow(trivial_casts)]
ptr::read(src as *const T as *const U)
}
/// Transforms lifetime of the second pointer to match the first.
#[inline]
#[unstable(feature = "copy_lifetime",
reason = "this function may be removed in the future due to its \
questionable utility")]
#[deprecated(since = "1.2.0",
reason = "unclear that this function buys more safety and \
lifetimes are generally not handled as such in unsafe \
code today")]
pub unsafe fn copy_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S,
ptr: &T) -> &'a T {
transmute(ptr)
}
/// Transforms lifetime of the second mutable pointer to match the first.
#[inline]
#[unstable(feature = "copy_lifetime",
reason = "this function may be removed in the future due to its \
questionable utility")]
#[deprecated(since = "1.2.0",
reason = "unclear that this function buys more safety and \
lifetimes are generally not handled as such in unsafe \
code today")]
pub unsafe fn copy_mut_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S,
ptr: &mut T)
-> &'a mut T
{
transmute(ptr)
}
|
/// unsafe {
/// // Give ourselves some scratch space to work with
/// let mut t: T = mem::uninitialized();
///
|
random_line_split
|
mem.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Basic functions for dealing with memory
//!
//! This module contains functions for querying the size and alignment of
//! types, initializing and manipulating memory.
#![stable(feature = "rust1", since = "1.0.0")]
use marker::Sized;
use intrinsics;
use ptr;
#[stable(feature = "rust1", since = "1.0.0")]
pub use intrinsics::transmute;
/// Leaks a value into the void, consuming ownership and never running its
/// destructor.
///
/// This function will take ownership of its argument, but is distinct from the
/// `mem::drop` function in that it **does not run the destructor**, leaking the
/// value and any resources that it owns.
///
/// # Safety
///
/// This function is not marked as `unsafe` as Rust does not guarantee that the
/// `Drop` implementation for a value will always run. Note, however, that
/// leaking resources such as memory or I/O objects is likely not desired, so
/// this function is only recommended for specialized use cases.
///
/// The safety of this function implies that when writing `unsafe` code
/// yourself care must be taken when leveraging a destructor that is required to
/// run to preserve memory safety. There are known situations where the
/// destructor may not run (such as if ownership of the object with the
/// destructor is returned) which must be taken into account.
///
/// # Other forms of Leakage
///
/// It's important to point out that this function is not the only method by
/// which a value can be leaked in safe Rust code. Other known sources of
/// leakage are:
///
/// * `Rc` and `Arc` cycles
/// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally)
/// * Panicking destructors are likely to leak local resources
///
/// # When To Use
///
/// There's only a few reasons to use this function. They mainly come
/// up in unsafe code or FFI code.
///
/// * You have an uninitialized value, perhaps for performance reasons, and
/// need to prevent the destructor from running on it.
/// * You have two copies of a value (like `std::mem::swap`), but need the
/// destructor to only run once to prevent a double free.
/// * Transferring resources across FFI boundries.
///
/// # Example
///
/// Leak some heap memory by never deallocating it.
///
/// ```rust
/// use std::mem;
///
/// let heap_memory = Box::new(3);
/// mem::forget(heap_memory);
/// ```
///
/// Leak an I/O object, never closing the file.
///
/// ```rust,no_run
/// use std::mem;
/// use std::fs::File;
///
/// let file = File::open("foo.txt").unwrap();
/// mem::forget(file);
/// ```
///
/// The swap function uses forget to good effect.
///
/// ```rust
/// use std::mem;
/// use std::ptr;
///
/// fn swap<T>(x: &mut T, y: &mut T) {
/// unsafe {
/// // Give ourselves some scratch space to work with
/// let mut t: T = mem::uninitialized();
///
/// // Perform the swap, `&mut` pointers never alias
/// ptr::copy_nonoverlapping(&*x, &mut t, 1);
/// ptr::copy_nonoverlapping(&*y, x, 1);
/// ptr::copy_nonoverlapping(&t, y, 1);
///
/// // y and t now point to the same thing, but we need to completely
/// // forget `t` because we do not want to run the destructor for `T`
/// // on its value, which is still owned somewhere outside this function.
/// mem::forget(t);
/// }
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn forget<T>(t: T) {
unsafe { intrinsics::forget(t) }
}
/// Returns the size of a type in bytes.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::size_of::<i32>());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn size_of<T>() -> usize {
unsafe { intrinsics::size_of::<T>() }
}
/// Returns the size of the type that `val` points to in bytes.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::size_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn size_of_val<T:?Sized>(val: &T) -> usize {
unsafe { intrinsics::size_of_val(val) }
}
/// Returns the ABI-required minimum alignment of a type
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::min_align_of::<i32>());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[deprecated(reason = "use `align_of` instead", since = "1.2.0")]
pub fn min_align_of<T>() -> usize {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::min_align_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
pub fn min_align_of_val<T:?Sized>(val: &T) -> usize {
unsafe { intrinsics::min_align_of_val(val) }
}
/// Returns the alignment in memory for a type.
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::align_of::<i32>());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn align_of<T>() -> usize {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::align_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn align_of_val<T:?Sized>(val: &T) -> usize {
unsafe { intrinsics::min_align_of_val(val) }
}
/// Creates a value initialized to zero.
///
/// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
/// operation).
///
/// Care must be taken when using this function, if the type `T` has a destructor and the value
/// falls out of scope (due to unwinding or returning) before being initialized, then the
/// destructor will run on zeroed data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x: i32 = unsafe { mem::zeroed() };
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn zeroed<T>() -> T {
intrinsics::init()
}
/// Creates a value initialized to an unspecified series of bytes.
///
/// The byte sequence usually indicates that the value at the memory
/// in question has been dropped. Thus, *if* T carries a drop flag,
/// any associated destructor will not be run when the value falls out
/// of scope.
///
/// Some code at one time used the `zeroed` function above to
/// accomplish this goal.
///
/// This function is expected to be deprecated with the transition
/// to non-zeroing drop.
#[inline]
#[unstable(feature = "filling_drop")]
pub unsafe fn dropped<T>() -> T {
#[inline(always)]
unsafe fn dropped_impl<T>() -> T { intrinsics::init_dropped() }
dropped_impl()
}
/// Creates an uninitialized value.
///
/// Care must be taken when using this function, if the type `T` has a destructor and the value
/// falls out of scope (due to unwinding or returning) before being initialized, then the
/// destructor will run on uninitialized data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x: i32 = unsafe { mem::uninitialized() };
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn uninitialized<T>() -> T {
intrinsics::uninit()
}
/// Swap the values at two mutable locations of the same type, without deinitialising or copying
/// either one.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x = &mut 5;
/// let y = &mut 42;
///
/// mem::swap(x, y);
///
/// assert_eq!(42, *x);
/// assert_eq!(5, *y);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninitialized();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping(&*x, &mut t, 1);
ptr::copy_nonoverlapping(&*y, x, 1);
ptr::copy_nonoverlapping(&t, y, 1);
// y and t now point to the same thing, but we need to completely
// forget `t` because we do not want to run the destructor for `T`
// on its value, which is still owned somewhere outside this function.
forget(t);
}
}
/// Replaces the value at a mutable location with a new one, returning the old value, without
/// deinitialising or copying either one.
///
/// This is primarily used for transferring and swapping ownership of a value in a mutable
/// location.
///
/// # Examples
///
/// A simple example:
///
/// ```
/// use std::mem;
///
/// let mut v: Vec<i32> = Vec::new();
///
/// mem::replace(&mut v, Vec::new());
/// ```
///
/// This function allows consumption of one field of a struct by replacing it with another value.
/// The normal approach doesn't always work:
///
/// ```rust,ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// // error: cannot move out of dereference of `&mut`-pointer
/// let buf = self.buf;
/// self.buf = Vec::new();
/// buf
/// }
/// }
/// ```
///
/// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset
/// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
/// `self`, allowing it to be returned:
///
/// ```
/// use std::mem;
/// # struct Buffer<T> { buf: Vec<T> }
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// mem::replace(&mut self.buf, Vec::new())
/// }
/// }
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn replace<T>(dest: &mut T, mut src: T) -> T {
swap(dest, &mut src);
src
}
/// Disposes of a value.
///
/// While this does call the argument's implementation of `Drop`, it will not
/// release any borrows, as borrows are based on lexical scope.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let v = vec![1, 2, 3];
///
/// drop(v); // explicitly drop the vector
/// ```
///
/// Borrows are based on lexical scope, so this produces an error:
///
/// ```ignore
/// let mut v = vec![1, 2, 3];
/// let x = &v[0];
///
/// drop(x); // explicitly drop the reference, but the borrow still exists
///
/// v.push(4); // error: cannot borrow `v` as mutable because it is also
/// // borrowed as immutable
/// ```
///
/// An inner scope is needed to fix this:
///
/// ```
/// let mut v = vec![1, 2, 3];
///
/// {
/// let x = &v[0];
///
/// drop(x); // this is now redundant, as `x` is going out of scope anyway
/// }
///
/// v.push(4); // no problems
/// ```
///
/// Since `RefCell` enforces the borrow rules at runtime, `drop()` can
/// seemingly release a borrow of one:
///
/// ```
/// use std::cell::RefCell;
///
/// let x = RefCell::new(1);
///
/// let mut mutable_borrow = x.borrow_mut();
/// *mutable_borrow = 1;
///
/// drop(mutable_borrow); // relinquish the mutable borrow on this slot
///
/// let borrow = x.borrow();
/// println!("{}", *borrow);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn
|
<T>(_x: T) { }
macro_rules! repeat_u8_as_u32 {
($name:expr) => { (($name as u32) << 24 |
($name as u32) << 16 |
($name as u32) << 8 |
($name as u32)) }
}
macro_rules! repeat_u8_as_u64 {
($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 |
(repeat_u8_as_u32!($name) as u64)) }
}
// NOTE: Keep synchronized with values used in librustc_trans::trans::adt.
//
// In particular, the POST_DROP_U8 marker must never equal the
// DTOR_NEEDED_U8 marker.
//
// For a while pnkfelix was using 0xc1 here.
// But having the sign bit set is a pain, so 0x1d is probably better.
//
// And of course, 0x00 brings back the old world of zero'ing on drop.
#[unstable(feature = "filling_drop")]
pub const POST_DROP_U8: u8 = 0x1d;
#[unstable(feature = "filling_drop")]
pub const POST_DROP_U32: u32 = repeat_u8_as_u32!(POST_DROP_U8);
#[unstable(feature = "filling_drop")]
pub const POST_DROP_U64: u64 = repeat_u8_as_u64!(POST_DROP_U8);
#[cfg(target_pointer_width = "32")]
#[unstable(feature = "filling_drop")]
pub const POST_DROP_USIZE: usize = POST_DROP_U32 as usize;
#[cfg(target_pointer_width = "64")]
#[unstable(feature = "filling_drop")]
pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize;
/// Interprets `src` as `&U`, and then reads `src` without moving the contained
/// value.
///
/// This function will unsafely assume the pointer `src` is valid for
/// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
/// will also unsafely create a copy of the contained value instead of moving
/// out of `src`.
///
/// It is not a compile-time error if `T` and `U` have different sizes, but it
/// is highly encouraged to only invoke this function where `T` and `U` have the
/// same size. This function triggers undefined behavior if `U` is larger than
/// `T`.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let one = unsafe { mem::transmute_copy(&1) };
///
/// assert_eq!(1, one);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
// FIXME(#23542) Replace with type ascription.
#![allow(trivial_casts)]
ptr::read(src as *const T as *const U)
}
/// Transforms lifetime of the second pointer to match the first.
#[inline]
#[unstable(feature = "copy_lifetime",
reason = "this function may be removed in the future due to its \
questionable utility")]
#[deprecated(since = "1.2.0",
reason = "unclear that this function buys more safety and \
lifetimes are generally not handled as such in unsafe \
code today")]
pub unsafe fn copy_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S,
ptr: &T) -> &'a T {
transmute(ptr)
}
/// Transforms lifetime of the second mutable pointer to match the first.
#[inline]
#[unstable(feature = "copy_lifetime",
reason = "this function may be removed in the future due to its \
questionable utility")]
#[deprecated(since = "1.2.0",
reason = "unclear that this function buys more safety and \
lifetimes are generally not handled as such in unsafe \
code today")]
pub unsafe fn copy_mut_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S,
ptr: &mut T)
-> &'a mut T
{
transmute(ptr)
}
|
drop
|
identifier_name
|
mem.rs
|
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Basic functions for dealing with memory
//!
//! This module contains functions for querying the size and alignment of
//! types, initializing and manipulating memory.
#![stable(feature = "rust1", since = "1.0.0")]
use marker::Sized;
use intrinsics;
use ptr;
#[stable(feature = "rust1", since = "1.0.0")]
pub use intrinsics::transmute;
/// Leaks a value into the void, consuming ownership and never running its
/// destructor.
///
/// This function will take ownership of its argument, but is distinct from the
/// `mem::drop` function in that it **does not run the destructor**, leaking the
/// value and any resources that it owns.
///
/// # Safety
///
/// This function is not marked as `unsafe` as Rust does not guarantee that the
/// `Drop` implementation for a value will always run. Note, however, that
/// leaking resources such as memory or I/O objects is likely not desired, so
/// this function is only recommended for specialized use cases.
///
/// The safety of this function implies that when writing `unsafe` code
/// yourself care must be taken when leveraging a destructor that is required to
/// run to preserve memory safety. There are known situations where the
/// destructor may not run (such as if ownership of the object with the
/// destructor is returned) which must be taken into account.
///
/// # Other forms of Leakage
///
/// It's important to point out that this function is not the only method by
/// which a value can be leaked in safe Rust code. Other known sources of
/// leakage are:
///
/// * `Rc` and `Arc` cycles
/// * `mpsc::{Sender, Receiver}` cycles (they use `Arc` internally)
/// * Panicking destructors are likely to leak local resources
///
/// # When To Use
///
/// There's only a few reasons to use this function. They mainly come
/// up in unsafe code or FFI code.
///
/// * You have an uninitialized value, perhaps for performance reasons, and
/// need to prevent the destructor from running on it.
/// * You have two copies of a value (like `std::mem::swap`), but need the
/// destructor to only run once to prevent a double free.
/// * Transferring resources across FFI boundries.
///
/// # Example
///
/// Leak some heap memory by never deallocating it.
///
/// ```rust
/// use std::mem;
///
/// let heap_memory = Box::new(3);
/// mem::forget(heap_memory);
/// ```
///
/// Leak an I/O object, never closing the file.
///
/// ```rust,no_run
/// use std::mem;
/// use std::fs::File;
///
/// let file = File::open("foo.txt").unwrap();
/// mem::forget(file);
/// ```
///
/// The swap function uses forget to good effect.
///
/// ```rust
/// use std::mem;
/// use std::ptr;
///
/// fn swap<T>(x: &mut T, y: &mut T) {
/// unsafe {
/// // Give ourselves some scratch space to work with
/// let mut t: T = mem::uninitialized();
///
/// // Perform the swap, `&mut` pointers never alias
/// ptr::copy_nonoverlapping(&*x, &mut t, 1);
/// ptr::copy_nonoverlapping(&*y, x, 1);
/// ptr::copy_nonoverlapping(&t, y, 1);
///
/// // y and t now point to the same thing, but we need to completely
/// // forget `t` because we do not want to run the destructor for `T`
/// // on its value, which is still owned somewhere outside this function.
/// mem::forget(t);
/// }
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
pub fn forget<T>(t: T) {
unsafe { intrinsics::forget(t) }
}
/// Returns the size of a type in bytes.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::size_of::<i32>());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn size_of<T>() -> usize {
unsafe { intrinsics::size_of::<T>() }
}
/// Returns the size of the type that `val` points to in bytes.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::size_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn size_of_val<T:?Sized>(val: &T) -> usize {
unsafe { intrinsics::size_of_val(val) }
}
/// Returns the ABI-required minimum alignment of a type
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::min_align_of::<i32>());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[deprecated(reason = "use `align_of` instead", since = "1.2.0")]
pub fn min_align_of<T>() -> usize {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::min_align_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[deprecated(reason = "use `align_of_val` instead", since = "1.2.0")]
pub fn min_align_of_val<T:?Sized>(val: &T) -> usize
|
/// Returns the alignment in memory for a type.
///
/// This is the alignment used for struct fields. It may be smaller than the preferred alignment.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::align_of::<i32>());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn align_of<T>() -> usize {
unsafe { intrinsics::min_align_of::<T>() }
}
/// Returns the ABI-required minimum alignment of the type of the value that `val` points to
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// assert_eq!(4, mem::align_of_val(&5i32));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn align_of_val<T:?Sized>(val: &T) -> usize {
unsafe { intrinsics::min_align_of_val(val) }
}
/// Creates a value initialized to zero.
///
/// This function is similar to allocating space for a local variable and zeroing it out (an unsafe
/// operation).
///
/// Care must be taken when using this function, if the type `T` has a destructor and the value
/// falls out of scope (due to unwinding or returning) before being initialized, then the
/// destructor will run on zeroed data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x: i32 = unsafe { mem::zeroed() };
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn zeroed<T>() -> T {
intrinsics::init()
}
/// Creates a value initialized to an unspecified series of bytes.
///
/// The byte sequence usually indicates that the value at the memory
/// in question has been dropped. Thus, *if* T carries a drop flag,
/// any associated destructor will not be run when the value falls out
/// of scope.
///
/// Some code at one time used the `zeroed` function above to
/// accomplish this goal.
///
/// This function is expected to be deprecated with the transition
/// to non-zeroing drop.
#[inline]
#[unstable(feature = "filling_drop")]
pub unsafe fn dropped<T>() -> T {
#[inline(always)]
unsafe fn dropped_impl<T>() -> T { intrinsics::init_dropped() }
dropped_impl()
}
/// Creates an uninitialized value.
///
/// Care must be taken when using this function, if the type `T` has a destructor and the value
/// falls out of scope (due to unwinding or returning) before being initialized, then the
/// destructor will run on uninitialized data, likely leading to crashes.
///
/// This is useful for FFI functions sometimes, but should generally be avoided.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x: i32 = unsafe { mem::uninitialized() };
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn uninitialized<T>() -> T {
intrinsics::uninit()
}
/// Swap the values at two mutable locations of the same type, without deinitialising or copying
/// either one.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let x = &mut 5;
/// let y = &mut 42;
///
/// mem::swap(x, y);
///
/// assert_eq!(42, *x);
/// assert_eq!(5, *y);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninitialized();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping(&*x, &mut t, 1);
ptr::copy_nonoverlapping(&*y, x, 1);
ptr::copy_nonoverlapping(&t, y, 1);
// y and t now point to the same thing, but we need to completely
// forget `t` because we do not want to run the destructor for `T`
// on its value, which is still owned somewhere outside this function.
forget(t);
}
}
/// Replaces the value at a mutable location with a new one, returning the old value, without
/// deinitialising or copying either one.
///
/// This is primarily used for transferring and swapping ownership of a value in a mutable
/// location.
///
/// # Examples
///
/// A simple example:
///
/// ```
/// use std::mem;
///
/// let mut v: Vec<i32> = Vec::new();
///
/// mem::replace(&mut v, Vec::new());
/// ```
///
/// This function allows consumption of one field of a struct by replacing it with another value.
/// The normal approach doesn't always work:
///
/// ```rust,ignore
/// struct Buffer<T> { buf: Vec<T> }
///
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// // error: cannot move out of dereference of `&mut`-pointer
/// let buf = self.buf;
/// self.buf = Vec::new();
/// buf
/// }
/// }
/// ```
///
/// Note that `T` does not necessarily implement `Clone`, so it can't even clone and reset
/// `self.buf`. But `replace` can be used to disassociate the original value of `self.buf` from
/// `self`, allowing it to be returned:
///
/// ```
/// use std::mem;
/// # struct Buffer<T> { buf: Vec<T> }
/// impl<T> Buffer<T> {
/// fn get_and_reset(&mut self) -> Vec<T> {
/// mem::replace(&mut self.buf, Vec::new())
/// }
/// }
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn replace<T>(dest: &mut T, mut src: T) -> T {
swap(dest, &mut src);
src
}
/// Disposes of a value.
///
/// While this does call the argument's implementation of `Drop`, it will not
/// release any borrows, as borrows are based on lexical scope.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let v = vec![1, 2, 3];
///
/// drop(v); // explicitly drop the vector
/// ```
///
/// Borrows are based on lexical scope, so this produces an error:
///
/// ```ignore
/// let mut v = vec![1, 2, 3];
/// let x = &v[0];
///
/// drop(x); // explicitly drop the reference, but the borrow still exists
///
/// v.push(4); // error: cannot borrow `v` as mutable because it is also
/// // borrowed as immutable
/// ```
///
/// An inner scope is needed to fix this:
///
/// ```
/// let mut v = vec![1, 2, 3];
///
/// {
/// let x = &v[0];
///
/// drop(x); // this is now redundant, as `x` is going out of scope anyway
/// }
///
/// v.push(4); // no problems
/// ```
///
/// Since `RefCell` enforces the borrow rules at runtime, `drop()` can
/// seemingly release a borrow of one:
///
/// ```
/// use std::cell::RefCell;
///
/// let x = RefCell::new(1);
///
/// let mut mutable_borrow = x.borrow_mut();
/// *mutable_borrow = 1;
///
/// drop(mutable_borrow); // relinquish the mutable borrow on this slot
///
/// let borrow = x.borrow();
/// println!("{}", *borrow);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub fn drop<T>(_x: T) { }
macro_rules! repeat_u8_as_u32 {
($name:expr) => { (($name as u32) << 24 |
($name as u32) << 16 |
($name as u32) << 8 |
($name as u32)) }
}
macro_rules! repeat_u8_as_u64 {
($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 |
(repeat_u8_as_u32!($name) as u64)) }
}
// NOTE: Keep synchronized with values used in librustc_trans::trans::adt.
//
// In particular, the POST_DROP_U8 marker must never equal the
// DTOR_NEEDED_U8 marker.
//
// For a while pnkfelix was using 0xc1 here.
// But having the sign bit set is a pain, so 0x1d is probably better.
//
// And of course, 0x00 brings back the old world of zero'ing on drop.
#[unstable(feature = "filling_drop")]
pub const POST_DROP_U8: u8 = 0x1d;
#[unstable(feature = "filling_drop")]
pub const POST_DROP_U32: u32 = repeat_u8_as_u32!(POST_DROP_U8);
#[unstable(feature = "filling_drop")]
pub const POST_DROP_U64: u64 = repeat_u8_as_u64!(POST_DROP_U8);
#[cfg(target_pointer_width = "32")]
#[unstable(feature = "filling_drop")]
pub const POST_DROP_USIZE: usize = POST_DROP_U32 as usize;
#[cfg(target_pointer_width = "64")]
#[unstable(feature = "filling_drop")]
pub const POST_DROP_USIZE: usize = POST_DROP_U64 as usize;
/// Interprets `src` as `&U`, and then reads `src` without moving the contained
/// value.
///
/// This function will unsafely assume the pointer `src` is valid for
/// `sizeof(U)` bytes by transmuting `&T` to `&U` and then reading the `&U`. It
/// will also unsafely create a copy of the contained value instead of moving
/// out of `src`.
///
/// It is not a compile-time error if `T` and `U` have different sizes, but it
/// is highly encouraged to only invoke this function where `T` and `U` have the
/// same size. This function triggers undefined behavior if `U` is larger than
/// `T`.
///
/// # Examples
///
/// ```
/// use std::mem;
///
/// let one = unsafe { mem::transmute_copy(&1) };
///
/// assert_eq!(1, one);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
pub unsafe fn transmute_copy<T, U>(src: &T) -> U {
// FIXME(#23542) Replace with type ascription.
#![allow(trivial_casts)]
ptr::read(src as *const T as *const U)
}
/// Transforms lifetime of the second pointer to match the first.
#[inline]
#[unstable(feature = "copy_lifetime",
reason = "this function may be removed in the future due to its \
questionable utility")]
#[deprecated(since = "1.2.0",
reason = "unclear that this function buys more safety and \
lifetimes are generally not handled as such in unsafe \
code today")]
pub unsafe fn copy_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S,
ptr: &T) -> &'a T {
transmute(ptr)
}
/// Transforms lifetime of the second mutable pointer to match the first.
#[inline]
#[unstable(feature = "copy_lifetime",
reason = "this function may be removed in the future due to its \
questionable utility")]
#[deprecated(since = "1.2.0",
reason = "unclear that this function buys more safety and \
lifetimes are generally not handled as such in unsafe \
code today")]
pub unsafe fn copy_mut_lifetime<'a, S:?Sized, T:?Sized + 'a>(_ptr: &'a S,
ptr: &mut T)
-> &'a mut T
{
transmute(ptr)
}
|
{
unsafe { intrinsics::min_align_of_val(val) }
}
|
identifier_body
|
player.rs
|
use graphics::{Context, Polygon, Transformed};
use opengl_graphics::GlGraphics;
use rand::Rng;
use drawing::{color, Point, Size};
use super::Vector;
use traits::{Advance, Collide, Position};
/// The `Player` is the rocket controlled by the user
#[derive(Default)]
pub struct Player {
pub vector: Vector
}
derive_position_direction!(Player);
/// The player is drawn as the triangle below
const POLYGON: &'static [[f64; 2]] = &[
[0.0, -8.0],
[20.0, 0.0],
[0.0, 8.0]
];
impl Player {
/// Create a new `Player` with a random position and direction
pub fn random<R: Rng>(rng: &mut R, bounds: Size) -> Player {
Player { vector: Vector::random(rng, bounds) }
}
/// Draw the player
pub fn draw(&self, c: &Context, gl: &mut GlGraphics) {
// Set the center of the player as the origin and rotate it
let transform = c.transform.trans(self.x(), self.y())
.rot_rad(self.direction());
// Draw a rectangle on the position of the player
Polygon::new(color::RED).draw(POLYGON, &c.draw_state, transform, gl);
}
/// Returns the nose of the rocket
pub fn nose(&self) -> Point {
Point::new(POLYGON[1][0], POLYGON[1][1])
.rotate(self.direction())
.translate(&self.position())
}
}
impl Collide for Player {
|
fn radius(&self) -> f64 { 6.0 }
}
|
random_line_split
|
|
player.rs
|
use graphics::{Context, Polygon, Transformed};
use opengl_graphics::GlGraphics;
use rand::Rng;
use drawing::{color, Point, Size};
use super::Vector;
use traits::{Advance, Collide, Position};
/// The `Player` is the rocket controlled by the user
#[derive(Default)]
pub struct Player {
pub vector: Vector
}
derive_position_direction!(Player);
/// The player is drawn as the triangle below
const POLYGON: &'static [[f64; 2]] = &[
[0.0, -8.0],
[20.0, 0.0],
[0.0, 8.0]
];
impl Player {
/// Create a new `Player` with a random position and direction
pub fn
|
<R: Rng>(rng: &mut R, bounds: Size) -> Player {
Player { vector: Vector::random(rng, bounds) }
}
/// Draw the player
pub fn draw(&self, c: &Context, gl: &mut GlGraphics) {
// Set the center of the player as the origin and rotate it
let transform = c.transform.trans(self.x(), self.y())
.rot_rad(self.direction());
// Draw a rectangle on the position of the player
Polygon::new(color::RED).draw(POLYGON, &c.draw_state, transform, gl);
}
/// Returns the nose of the rocket
pub fn nose(&self) -> Point {
Point::new(POLYGON[1][0], POLYGON[1][1])
.rotate(self.direction())
.translate(&self.position())
}
}
impl Collide for Player {
fn radius(&self) -> f64 { 6.0 }
}
|
random
|
identifier_name
|
parallel-letter-frequency.rs
|
use std::collections::HashMap;
extern crate parallel_letter_frequency as frequency;
// Poem by Friedrich Schiller. The corresponding music is the European Anthem.
const ODE_AN_DIE_FREUDE: [&'static str; 8] = [
"Freude schöner Götterfunken",
"Tochter aus Elysium,",
"Wir betreten feuertrunken,",
"Himmlische, dein Heiligtum!",
"Deine Zauber binden wieder",
"Was die Mode streng geteilt;",
"Alle Menschen werden Brüder,",
"Wo dein sanfter Flügel weilt."];
// Dutch national anthem
const WILHELMUS: [&'static str; 8] = [
"Wilhelmus van Nassouwe",
"ben ik, van Duitsen bloed,",
"den vaderland getrouwe",
"blijf ik tot in den dood.",
"Een Prinse van Oranje",
"ben ik, vrij, onverveerd,",
"den Koning van Hispanje",
"heb ik altijd geëerd."];
// American national anthem
const STAR_SPANGLED_BANNER: [&'static str; 8] = [
"O say can you see by the dawn's early light,",
"What so proudly we hailed at the twilight's last gleaming,",
"Whose broad stripes and bright stars through the perilous fight,",
"O'er the ramparts we watched, were so gallantly streaming?",
"And the rockets' red glare, the bombs bursting in air,",
"Gave proof through the night that our flag was still there;",
"O say does that star-spangled banner yet wave,",
"O'er the land of the free and the home of the brave?"];
#[test]
fn test_no_texts() {
assert_eq!(frequency::frequency(&[], 4), HashMap::new());
}
#[test]
#[ignore]
fn test_one_letter() {
let mut hm = HashMap::new();
hm.insert('a', 1);
assert_eq!(frequency::frequency(&["a"], 4), hm);
}
#[test]
#[ignore]
fn test_case_insensitivity() {
let mut hm = HashMap::new();
hm.insert('a', 2);
assert_eq!(frequency::frequency(&["aA"], 4), hm);
}
#[test]
#[ignore]
fn test_many_empty_lines() {
let mut v = Vec::with_capacity(1000);
for _ in 0..1000 {
v.push("");
}
assert_eq!(frequency::frequency(&v[..], 4), HashMap::new());
}
#[test]
#[ignore]
fn test_
|
let mut v = Vec::with_capacity(1000);
for _ in 0..1000 {
v.push("abc");
}
let mut hm = HashMap::new();
hm.insert('a', 1000);
hm.insert('b', 1000);
hm.insert('c', 1000);
assert_eq!(frequency::frequency(&v[..], 4), hm);
}
#[test]
#[ignore]
fn test_punctuation_doesnt_count() {
assert!(!frequency::frequency(&WILHELMUS, 4).contains_key(&','));
}
#[test]
#[ignore]
fn test_numbers_dont_count() {
assert!(!frequency::frequency(&["Testing, 1, 2, 3"], 4).contains_key(&'1'));
}
#[test]
#[ignore]
fn test_all_three_anthems_1_worker() {
let mut v = Vec::new();
for anthem in [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER].iter() {
for line in anthem.iter() {
v.push(*line);
}
}
let freqs = frequency::frequency(&v[..], 1);
assert_eq!(freqs.get(&'a'), Some(&49));
assert_eq!(freqs.get(&'t'), Some(&56));
assert_eq!(freqs.get(&'ü'), Some(&2));
}
#[test]
#[ignore]
fn test_all_three_anthems_3_workers() {
let mut v = Vec::new();
for anthem in [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER].iter() {
for line in anthem.iter() {
v.push(*line);
}
}
let freqs = frequency::frequency(&v[..], 3);
assert_eq!(freqs.get(&'a'), Some(&49));
assert_eq!(freqs.get(&'t'), Some(&56));
assert_eq!(freqs.get(&'ü'), Some(&2));
}
|
many_times_same_text() {
|
identifier_name
|
parallel-letter-frequency.rs
|
use std::collections::HashMap;
extern crate parallel_letter_frequency as frequency;
// Poem by Friedrich Schiller. The corresponding music is the European Anthem.
const ODE_AN_DIE_FREUDE: [&'static str; 8] = [
"Freude schöner Götterfunken",
"Tochter aus Elysium,",
"Wir betreten feuertrunken,",
"Himmlische, dein Heiligtum!",
"Deine Zauber binden wieder",
"Was die Mode streng geteilt;",
"Alle Menschen werden Brüder,",
"Wo dein sanfter Flügel weilt."];
// Dutch national anthem
const WILHELMUS: [&'static str; 8] = [
"Wilhelmus van Nassouwe",
"ben ik, van Duitsen bloed,",
"den vaderland getrouwe",
"blijf ik tot in den dood.",
"Een Prinse van Oranje",
"ben ik, vrij, onverveerd,",
"den Koning van Hispanje",
"heb ik altijd geëerd."];
// American national anthem
const STAR_SPANGLED_BANNER: [&'static str; 8] = [
"O say can you see by the dawn's early light,",
"What so proudly we hailed at the twilight's last gleaming,",
"Whose broad stripes and bright stars through the perilous fight,",
"O'er the ramparts we watched, were so gallantly streaming?",
"And the rockets' red glare, the bombs bursting in air,",
"Gave proof through the night that our flag was still there;",
"O say does that star-spangled banner yet wave,",
"O'er the land of the free and the home of the brave?"];
#[test]
fn test_no_texts() {
assert_eq!(frequency::frequency(&[], 4), HashMap::new());
}
#[test]
#[ignore]
fn test_one_letter() {
let mut hm = HashMap::new();
hm.insert('a', 1);
assert_eq!(frequency::frequency(&["a"], 4), hm);
}
#[test]
#[ignore]
fn test_case_insensitivity() {
let mut hm = HashMap::new();
hm.insert('a', 2);
assert_eq!(frequency::frequency(&["aA"], 4), hm);
}
#[test]
#[ignore]
fn test_many_empty_lines() {
let mut v = Vec::with_capacity(1000);
for _ in 0..1000 {
v.push("");
}
assert_eq!(frequency::frequency(&v[..], 4), HashMap::new());
}
#[test]
#[ignore]
fn test_many_times_same_text() {
let mut v = Vec::with_capacity(1000);
for _ in 0..1000 {
v.push("abc");
}
let mut hm = HashMap::new();
hm.insert('a', 1000);
hm.insert('b', 1000);
hm.insert('c', 1000);
assert_eq!(frequency::frequency(&v[..], 4), hm);
}
#[test]
#[ignore]
fn test_punctuation_doesnt_count() {
assert!(!frequency::frequency(&WILHELMUS, 4).contains_key(&','));
}
#[test]
#[ignore]
fn test_numbers_dont_count() {
|
est]
#[ignore]
fn test_all_three_anthems_1_worker() {
let mut v = Vec::new();
for anthem in [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER].iter() {
for line in anthem.iter() {
v.push(*line);
}
}
let freqs = frequency::frequency(&v[..], 1);
assert_eq!(freqs.get(&'a'), Some(&49));
assert_eq!(freqs.get(&'t'), Some(&56));
assert_eq!(freqs.get(&'ü'), Some(&2));
}
#[test]
#[ignore]
fn test_all_three_anthems_3_workers() {
let mut v = Vec::new();
for anthem in [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER].iter() {
for line in anthem.iter() {
v.push(*line);
}
}
let freqs = frequency::frequency(&v[..], 3);
assert_eq!(freqs.get(&'a'), Some(&49));
assert_eq!(freqs.get(&'t'), Some(&56));
assert_eq!(freqs.get(&'ü'), Some(&2));
}
|
assert!(!frequency::frequency(&["Testing, 1, 2, 3"], 4).contains_key(&'1'));
}
#[t
|
identifier_body
|
parallel-letter-frequency.rs
|
use std::collections::HashMap;
extern crate parallel_letter_frequency as frequency;
// Poem by Friedrich Schiller. The corresponding music is the European Anthem.
const ODE_AN_DIE_FREUDE: [&'static str; 8] = [
"Freude schöner Götterfunken",
"Tochter aus Elysium,",
"Wir betreten feuertrunken,",
"Himmlische, dein Heiligtum!",
"Deine Zauber binden wieder",
"Was die Mode streng geteilt;",
"Alle Menschen werden Brüder,",
"Wo dein sanfter Flügel weilt."];
// Dutch national anthem
const WILHELMUS: [&'static str; 8] = [
"Wilhelmus van Nassouwe",
"ben ik, van Duitsen bloed,",
"den vaderland getrouwe",
"blijf ik tot in den dood.",
"Een Prinse van Oranje",
"ben ik, vrij, onverveerd,",
"den Koning van Hispanje",
"heb ik altijd geëerd."];
// American national anthem
const STAR_SPANGLED_BANNER: [&'static str; 8] = [
"O say can you see by the dawn's early light,",
"What so proudly we hailed at the twilight's last gleaming,",
"Whose broad stripes and bright stars through the perilous fight,",
"O'er the ramparts we watched, were so gallantly streaming?",
"And the rockets' red glare, the bombs bursting in air,",
"Gave proof through the night that our flag was still there;",
"O say does that star-spangled banner yet wave,",
|
"O'er the land of the free and the home of the brave?"];
#[test]
fn test_no_texts() {
assert_eq!(frequency::frequency(&[], 4), HashMap::new());
}
#[test]
#[ignore]
fn test_one_letter() {
let mut hm = HashMap::new();
hm.insert('a', 1);
assert_eq!(frequency::frequency(&["a"], 4), hm);
}
#[test]
#[ignore]
fn test_case_insensitivity() {
let mut hm = HashMap::new();
hm.insert('a', 2);
assert_eq!(frequency::frequency(&["aA"], 4), hm);
}
#[test]
#[ignore]
fn test_many_empty_lines() {
let mut v = Vec::with_capacity(1000);
for _ in 0..1000 {
v.push("");
}
assert_eq!(frequency::frequency(&v[..], 4), HashMap::new());
}
#[test]
#[ignore]
fn test_many_times_same_text() {
let mut v = Vec::with_capacity(1000);
for _ in 0..1000 {
v.push("abc");
}
let mut hm = HashMap::new();
hm.insert('a', 1000);
hm.insert('b', 1000);
hm.insert('c', 1000);
assert_eq!(frequency::frequency(&v[..], 4), hm);
}
#[test]
#[ignore]
fn test_punctuation_doesnt_count() {
assert!(!frequency::frequency(&WILHELMUS, 4).contains_key(&','));
}
#[test]
#[ignore]
fn test_numbers_dont_count() {
assert!(!frequency::frequency(&["Testing, 1, 2, 3"], 4).contains_key(&'1'));
}
#[test]
#[ignore]
fn test_all_three_anthems_1_worker() {
let mut v = Vec::new();
for anthem in [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER].iter() {
for line in anthem.iter() {
v.push(*line);
}
}
let freqs = frequency::frequency(&v[..], 1);
assert_eq!(freqs.get(&'a'), Some(&49));
assert_eq!(freqs.get(&'t'), Some(&56));
assert_eq!(freqs.get(&'ü'), Some(&2));
}
#[test]
#[ignore]
fn test_all_three_anthems_3_workers() {
let mut v = Vec::new();
for anthem in [ODE_AN_DIE_FREUDE, WILHELMUS, STAR_SPANGLED_BANNER].iter() {
for line in anthem.iter() {
v.push(*line);
}
}
let freqs = frequency::frequency(&v[..], 3);
assert_eq!(freqs.get(&'a'), Some(&49));
assert_eq!(freqs.get(&'t'), Some(&56));
assert_eq!(freqs.get(&'ü'), Some(&2));
}
|
random_line_split
|
|
raw.rs
|
#![allow(non_camel_case_types)]
use std::os::raw::{c_int, c_char, c_uchar};
#[link(name = "git2")]
extern "C" {
pub fn git_libgit2_init() -> c_int;
pub fn git_libgit2_shutdown() -> c_int;
pub fn giterr_last() -> *const git_error;
pub fn git_repository_open(out: *mut *mut git_repository, path: *const c_char) -> c_int;
pub fn git_repository_free(repo: *mut git_repository);
pub fn git_reference_name_to_id(
out: *mut git_oid,
repo: *mut git_repository,
reference: *const c_char,
) -> c_int;
pub fn git_commit_lookup(
out: *mut *mut git_commit,
repo: *mut git_repository,
id: *const git_oid,
) -> c_int;
pub fn git_commit_author(commit: *const git_commit) -> *const git_signature;
pub fn git_commit_message(commit: *const git_commit) -> *const c_char;
pub fn git_commit_free(commit: *mut git_commit);
}
pub enum git_repository {}
pub enum git_commit {}
#[repr(C)]
|
pub message: *const c_char,
pub klass: c_int,
}
#[repr(C)]
pub struct git_oid {
pub id: [c_uchar; 20],
}
pub type git_time_t = i64;
#[repr(C)]
pub struct git_time {
pub time: git_time_t,
pub offset: c_int,
}
#[repr(C)]
pub struct git_signature {
pub name: *const c_char,
pub email: *const c_char,
pub when: git_time,
}
|
pub struct git_error {
|
random_line_split
|
raw.rs
|
#![allow(non_camel_case_types)]
use std::os::raw::{c_int, c_char, c_uchar};
#[link(name = "git2")]
extern "C" {
pub fn git_libgit2_init() -> c_int;
pub fn git_libgit2_shutdown() -> c_int;
pub fn giterr_last() -> *const git_error;
pub fn git_repository_open(out: *mut *mut git_repository, path: *const c_char) -> c_int;
pub fn git_repository_free(repo: *mut git_repository);
pub fn git_reference_name_to_id(
out: *mut git_oid,
repo: *mut git_repository,
reference: *const c_char,
) -> c_int;
pub fn git_commit_lookup(
out: *mut *mut git_commit,
repo: *mut git_repository,
id: *const git_oid,
) -> c_int;
pub fn git_commit_author(commit: *const git_commit) -> *const git_signature;
pub fn git_commit_message(commit: *const git_commit) -> *const c_char;
pub fn git_commit_free(commit: *mut git_commit);
}
pub enum git_repository {}
pub enum git_commit {}
#[repr(C)]
pub struct git_error {
pub message: *const c_char,
pub klass: c_int,
}
#[repr(C)]
pub struct git_oid {
pub id: [c_uchar; 20],
}
pub type git_time_t = i64;
#[repr(C)]
pub struct
|
{
pub time: git_time_t,
pub offset: c_int,
}
#[repr(C)]
pub struct git_signature {
pub name: *const c_char,
pub email: *const c_char,
pub when: git_time,
}
|
git_time
|
identifier_name
|
window.rs
|
use ::rendering::DrawBatch;
use ::resources::ResourceManager;
use super::BorderImage;
use super::{Widget, Rectangle, EventListener};
use glium;
use std::option::Option;
use std::rc::Rc;
use std::cell::RefCell;
const PADDING: i32 = 5;
pub struct Window<'a> {
rect: Rectangle,
draw_batch: DrawBatch<'a>,
window_background: BorderImage,
child: Option<Rc<RefCell<Widget>>>
}
impl<'a> Window<'a> {
pub fn new(
resource_manager: &mut ResourceManager,
display: &'a glium::backend::glutin_backend::GlutinFacade,
x: i32,
y: i32,
width: i32,
height: i32
) -> Window<'a> {
let texture = resource_manager.create_texture("example_images/window_sq.png").unwrap();
let mut window_background = BorderImage::new(texture, 21.0, 21.0, 20.0, 22.0);
window_background.set_position((x - 20) as f32, (y + 19) as f32);
window_background.set_size((width + 40) as f32, (height + 40) as f32);
Window {
rect: Rectangle::new_with_values(x, y, width, height),
draw_batch: DrawBatch::new(display),
window_background: window_background,
child: None,
}
}
pub fn set_child(&mut self, child: Rc<RefCell<Widget>>) {
self.child = Some(child);
}
pub fn create_buffers(&mut self) {
self.draw_batch.clear();
self.window_background.add_to_batch(&mut self.draw_batch);
if let Some(ref child) = self.child {
child.borrow_mut().set_dimensions(self.rect.dimensions.0 - 2 * PADDING, self.rect.dimensions.1 - 2 * PADDING);
child.borrow_mut().set_position(self.rect.position.0 + PADDING, self.rect.position.1 - PADDING);
child.borrow_mut().add_to_batch(&mut self.draw_batch);
}
self.draw_batch.create_buffers();
}
pub fn test(&self, x: i32, y: i32) {
if let Some(ref child) = self.child
|
}
pub fn create_event_listener(&self, x: i32, y: i32) -> Option<Box<EventListener>> {
if let Some(ref child) = self.child {
let (i, widget) = child.borrow().get_highest_priority_child(x, y);
if let Some(widget) = widget {
println!("{}", i);
return widget.borrow().create_event_listener(x, y);
}
}
None
}
pub fn draw(&self, frame: &mut glium::Frame) {
self.draw_batch.draw(frame);
}
}
|
{
let (i, _) = child.borrow().get_highest_priority_child(x, y);
println!("{}", i);
}
|
conditional_block
|
window.rs
|
use ::rendering::DrawBatch;
use ::resources::ResourceManager;
use super::BorderImage;
use super::{Widget, Rectangle, EventListener};
use glium;
use std::option::Option;
use std::rc::Rc;
use std::cell::RefCell;
const PADDING: i32 = 5;
pub struct Window<'a> {
rect: Rectangle,
draw_batch: DrawBatch<'a>,
window_background: BorderImage,
child: Option<Rc<RefCell<Widget>>>
}
impl<'a> Window<'a> {
pub fn new(
resource_manager: &mut ResourceManager,
display: &'a glium::backend::glutin_backend::GlutinFacade,
x: i32,
y: i32,
width: i32,
height: i32
) -> Window<'a> {
let texture = resource_manager.create_texture("example_images/window_sq.png").unwrap();
let mut window_background = BorderImage::new(texture, 21.0, 21.0, 20.0, 22.0);
window_background.set_position((x - 20) as f32, (y + 19) as f32);
window_background.set_size((width + 40) as f32, (height + 40) as f32);
Window {
rect: Rectangle::new_with_values(x, y, width, height),
draw_batch: DrawBatch::new(display),
window_background: window_background,
child: None,
}
|
self.child = Some(child);
}
pub fn create_buffers(&mut self) {
self.draw_batch.clear();
self.window_background.add_to_batch(&mut self.draw_batch);
if let Some(ref child) = self.child {
child.borrow_mut().set_dimensions(self.rect.dimensions.0 - 2 * PADDING, self.rect.dimensions.1 - 2 * PADDING);
child.borrow_mut().set_position(self.rect.position.0 + PADDING, self.rect.position.1 - PADDING);
child.borrow_mut().add_to_batch(&mut self.draw_batch);
}
self.draw_batch.create_buffers();
}
pub fn test(&self, x: i32, y: i32) {
if let Some(ref child) = self.child {
let (i, _) = child.borrow().get_highest_priority_child(x, y);
println!("{}", i);
}
}
pub fn create_event_listener(&self, x: i32, y: i32) -> Option<Box<EventListener>> {
if let Some(ref child) = self.child {
let (i, widget) = child.borrow().get_highest_priority_child(x, y);
if let Some(widget) = widget {
println!("{}", i);
return widget.borrow().create_event_listener(x, y);
}
}
None
}
pub fn draw(&self, frame: &mut glium::Frame) {
self.draw_batch.draw(frame);
}
}
|
}
pub fn set_child(&mut self, child: Rc<RefCell<Widget>>) {
|
random_line_split
|
window.rs
|
use ::rendering::DrawBatch;
use ::resources::ResourceManager;
use super::BorderImage;
use super::{Widget, Rectangle, EventListener};
use glium;
use std::option::Option;
use std::rc::Rc;
use std::cell::RefCell;
const PADDING: i32 = 5;
pub struct Window<'a> {
rect: Rectangle,
draw_batch: DrawBatch<'a>,
window_background: BorderImage,
child: Option<Rc<RefCell<Widget>>>
}
impl<'a> Window<'a> {
pub fn new(
resource_manager: &mut ResourceManager,
display: &'a glium::backend::glutin_backend::GlutinFacade,
x: i32,
y: i32,
width: i32,
height: i32
) -> Window<'a> {
let texture = resource_manager.create_texture("example_images/window_sq.png").unwrap();
let mut window_background = BorderImage::new(texture, 21.0, 21.0, 20.0, 22.0);
window_background.set_position((x - 20) as f32, (y + 19) as f32);
window_background.set_size((width + 40) as f32, (height + 40) as f32);
Window {
rect: Rectangle::new_with_values(x, y, width, height),
draw_batch: DrawBatch::new(display),
window_background: window_background,
child: None,
}
}
pub fn set_child(&mut self, child: Rc<RefCell<Widget>>) {
self.child = Some(child);
}
pub fn create_buffers(&mut self) {
self.draw_batch.clear();
self.window_background.add_to_batch(&mut self.draw_batch);
if let Some(ref child) = self.child {
child.borrow_mut().set_dimensions(self.rect.dimensions.0 - 2 * PADDING, self.rect.dimensions.1 - 2 * PADDING);
child.borrow_mut().set_position(self.rect.position.0 + PADDING, self.rect.position.1 - PADDING);
child.borrow_mut().add_to_batch(&mut self.draw_batch);
}
self.draw_batch.create_buffers();
}
pub fn test(&self, x: i32, y: i32) {
if let Some(ref child) = self.child {
let (i, _) = child.borrow().get_highest_priority_child(x, y);
println!("{}", i);
}
}
pub fn create_event_listener(&self, x: i32, y: i32) -> Option<Box<EventListener>> {
if let Some(ref child) = self.child {
let (i, widget) = child.borrow().get_highest_priority_child(x, y);
if let Some(widget) = widget {
println!("{}", i);
return widget.borrow().create_event_listener(x, y);
}
}
None
}
pub fn draw(&self, frame: &mut glium::Frame)
|
}
|
{
self.draw_batch.draw(frame);
}
|
identifier_body
|
window.rs
|
use ::rendering::DrawBatch;
use ::resources::ResourceManager;
use super::BorderImage;
use super::{Widget, Rectangle, EventListener};
use glium;
use std::option::Option;
use std::rc::Rc;
use std::cell::RefCell;
const PADDING: i32 = 5;
pub struct Window<'a> {
rect: Rectangle,
draw_batch: DrawBatch<'a>,
window_background: BorderImage,
child: Option<Rc<RefCell<Widget>>>
}
impl<'a> Window<'a> {
pub fn
|
(
resource_manager: &mut ResourceManager,
display: &'a glium::backend::glutin_backend::GlutinFacade,
x: i32,
y: i32,
width: i32,
height: i32
) -> Window<'a> {
let texture = resource_manager.create_texture("example_images/window_sq.png").unwrap();
let mut window_background = BorderImage::new(texture, 21.0, 21.0, 20.0, 22.0);
window_background.set_position((x - 20) as f32, (y + 19) as f32);
window_background.set_size((width + 40) as f32, (height + 40) as f32);
Window {
rect: Rectangle::new_with_values(x, y, width, height),
draw_batch: DrawBatch::new(display),
window_background: window_background,
child: None,
}
}
pub fn set_child(&mut self, child: Rc<RefCell<Widget>>) {
self.child = Some(child);
}
pub fn create_buffers(&mut self) {
self.draw_batch.clear();
self.window_background.add_to_batch(&mut self.draw_batch);
if let Some(ref child) = self.child {
child.borrow_mut().set_dimensions(self.rect.dimensions.0 - 2 * PADDING, self.rect.dimensions.1 - 2 * PADDING);
child.borrow_mut().set_position(self.rect.position.0 + PADDING, self.rect.position.1 - PADDING);
child.borrow_mut().add_to_batch(&mut self.draw_batch);
}
self.draw_batch.create_buffers();
}
pub fn test(&self, x: i32, y: i32) {
if let Some(ref child) = self.child {
let (i, _) = child.borrow().get_highest_priority_child(x, y);
println!("{}", i);
}
}
pub fn create_event_listener(&self, x: i32, y: i32) -> Option<Box<EventListener>> {
if let Some(ref child) = self.child {
let (i, widget) = child.borrow().get_highest_priority_child(x, y);
if let Some(widget) = widget {
println!("{}", i);
return widget.borrow().create_event_listener(x, y);
}
}
None
}
pub fn draw(&self, frame: &mut glium::Frame) {
self.draw_batch.draw(frame);
}
}
|
new
|
identifier_name
|
inpaint.rs
|
// Inpainting is applied to fill holes in the X-ray quadtree leaf tiles.
// As inpainting depends on sampling the neighborhood of pixels, if we
// directly took the original tiles as input, we would get visible color
// differences for the inpainted pixels along the tile borders. Because
// of this we enlarge all tiles, so they overlap each other by half of their
// dimension, apply inpainting on the enlarged tiles and bilinearly interpolate
// between tiles, before cutting out the original tile.
use crate::utils::{get_image_path, image_from_path, interpolate_subimages};
use fnv::FnvHashSet;
use image::{DynamicImage, GenericImage, GenericImageView, ImageResult, Luma, Rgba, RgbaImage};
use imageproc::distance_transform::Norm;
use imageproc::map::{map_colors, map_colors2};
use imageproc::morphology::close;
use point_viewer::color::TRANSPARENT;
use point_viewer::utils::create_syncable_progress_bar;
use quadtree::{Direction, NodeId, SpatialNodeId};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use std::fs;
use std::path::{Path, PathBuf};
use texture_synthesis::{Dims, Example, Session};
/// Inpaints only holes with radius <= distance_px in the image, but leaves big borders untouched.
fn inpaint(image: RgbaImage, distance_px: u8) -> RgbaImage {
let (width, height) = image.dimensions();
// extract the alpha channel as sampling mask
let mask = map_colors(&image, |p| Luma([p[3]]));
// fill holes in the alpha channel
let closed_mask = close(&mask, Norm::LInf, distance_px);
// mark pixels to be inpainted
let inpaint_mask = map_colors2(&closed_mask, &mask, |c, m| Luma([255 - (c[0] - m[0])]));
let texsynth = Session::builder()
// we perform multithreading outside, so one deterministic thread here is enough
.max_thread_count(1)
.inpaint_example(
DynamicImage::ImageLuma8(inpaint_mask),
Example::builder(DynamicImage::ImageRgba8(image))
.set_sample_method(DynamicImage::ImageLuma8(mask)),
Dims::new(width, height),
)
.build()
.expect("Inpaint failed.");
texsynth.run(None).into_image().into_rgba()
}
struct SpatialNodeInpainter<'a> {
spatial_node_id: SpatialNodeId,
output_directory: &'a Path,
}
impl<'a> SpatialNodeInpainter<'a> {
fn get_inpaint_image_path(&self) -> PathBuf {
get_image_path(self.output_directory, NodeId::from(self.spatial_node_id))
.with_extension("inpaint.png")
}
fn spatial_id_from(&self, neighbor: impl Into<Option<Direction>>) -> Option<SpatialNodeId> {
match neighbor.into() {
Some(n) => self.spatial_node_id.neighbor(n),
None => Some(self.spatial_node_id),
}
}
fn image_from(&self, neighbor: impl Into<Option<Direction>>) -> ImageResult<Option<RgbaImage>> {
self.spatial_id_from(neighbor)
.and_then(|id| {
image_from_path(&get_image_path(self.output_directory, NodeId::from(id)))
})
.transpose()
}
fn inpaint_image_and_path_from(
&self,
neighbor: impl Into<Option<Direction>>,
) -> ImageResult<Option<(RgbaImage, PathBuf)>> {
self.spatial_id_from(neighbor)
.and_then(|spatial_node_id| {
let inpainter = SpatialNodeInpainter {
spatial_node_id,
output_directory: self.output_directory,
};
let inpaint_image_path = inpainter.get_inpaint_image_path();
image_from_path(&inpaint_image_path).map(|inpaint_image_res| {
inpaint_image_res.map(|inpaint_image| (inpaint_image, inpaint_image_path))
})
})
.transpose()
}
fn stitched_image(&self) -> ImageResult<Option<RgbaImage>> {
if let Some(current) = self.image_from(None)? {
let w = current.width() / 2;
let h = current.height() / 2;
let mut image = RgbaImage::from_pixel(4 * w, 4 * h, Rgba::from(TRANSPARENT.to_u8()));
image.copy_from(¤t, w, h)?;
let mut copy_subimage = |direction: Direction,
from_x: u32,
from_y: u32,
width: u32,
height: u32,
to_x: u32,
to_y: u32|
-> ImageResult<()> {
if let Some(neighbor) = self.image_from(direction)? {
image.copy_from(&neighbor.view(from_x, from_y, width, height), to_x, to_y)?;
}
Ok(())
};
copy_subimage(Direction::TopLeft, w, h, w, h, 0, 0)?;
copy_subimage(Direction::Top, 0, h, 2 * w, h, w, 0)?;
copy_subimage(Direction::TopRight, 0, h, w, h, 3 * w, 0)?;
copy_subimage(Direction::Right, 0, 0, w, 2 * h, 3 * w, h)?;
copy_subimage(Direction::BottomRight, 0, 0, w, h, 3 * w, 3 * h)?;
copy_subimage(Direction::Bottom, 0, 0, 2 * w, h, w, 3 * h)?;
copy_subimage(Direction::BottomLeft, w, 0, w, h, 0, 3 * h)?;
copy_subimage(Direction::Left, w, 0, w, 2 * h, 0, h)?;
Ok(Some(image))
} else {
Ok(None)
}
}
fn create_inpaint_image(&self, inpaint_distance_px: u8) -> ImageResult<()> {
if let Some(mut inpaint_image) = self.stitched_image()? {
inpaint_image = inpaint(inpaint_image, inpaint_distance_px);
let inpaint_image_path = self.get_inpaint_image_path();
inpaint_image.save(inpaint_image_path)?;
}
Ok(())
}
fn interpolate_inpaint_image_with(&self, direction: Direction) -> ImageResult<()> {
if let (Some((mut current, current_path)), Some((mut neighbor, neighbor_path))) = (
self.inpaint_image_and_path_from(None)?,
self.inpaint_image_and_path_from(direction)?,
)
|
);
current.save(current_path)?;
neighbor.save(neighbor_path)?;
}
Ok(())
}
fn apply_inpainting(&self) -> ImageResult<()> {
if let Some((inpaint_image, inpaint_image_path)) = self.inpaint_image_and_path_from(None)? {
let (width, height) = inpaint_image.dimensions();
let image_view = inpaint_image.view(width / 4, height / 4, width / 2, height / 2);
let image_path =
get_image_path(self.output_directory, NodeId::from(self.spatial_node_id));
image_view.to_image().save(image_path)?;
fs::remove_file(inpaint_image_path)?;
}
Ok(())
}
}
struct Inpainting<'a> {
output_directory: &'a Path,
spatial_node_ids: Vec<SpatialNodeId>,
}
impl<'a> Inpainting<'a> {
fn step<P, F>(
&self,
message: &str,
partitioning_function: P,
inpainter_function: F,
) -> ImageResult<()>
where
P: FnMut(&&SpatialNodeId) -> bool,
F: Fn(&SpatialNodeInpainter<'a>) -> ImageResult<()> + Sync,
{
let progress_bar = create_syncable_progress_bar(self.spatial_node_ids.len(), message);
let run_partition = |spatial_node_ids: Vec<SpatialNodeId>| -> ImageResult<()> {
spatial_node_ids
.into_par_iter()
.try_for_each(|spatial_node_id| {
let inpainter = SpatialNodeInpainter {
spatial_node_id,
output_directory: self.output_directory,
};
let res = inpainter_function(&inpainter);
progress_bar.lock().unwrap().inc();
res
})
};
let (first, second): (Vec<SpatialNodeId>, Vec<SpatialNodeId>) = self
.spatial_node_ids
.iter()
.partition(partitioning_function);
run_partition(first)?;
run_partition(second)?;
progress_bar.lock().unwrap().finish_println("");
Ok(())
}
}
pub fn perform_inpainting(
output_directory: &Path,
inpaint_distance_px: u8,
leaf_node_ids: &FnvHashSet<NodeId>,
) -> ImageResult<()> {
if inpaint_distance_px == 0 {
return Ok(());
}
let spatial_node_ids: Vec<SpatialNodeId> = leaf_node_ids
.iter()
.cloned()
.map(SpatialNodeId::from)
.collect();
let inpainting = Inpainting {
output_directory,
spatial_node_ids,
};
inpainting.step(
"Creating inpaint images",
|_| false,
|inpainter| inpainter.create_inpaint_image(inpaint_distance_px),
)?;
inpainting.step(
"Horizontally interpolating inpaint images",
// Interleave interpolation to avoid race conditions when writing images
|spatial_node_id| spatial_node_id.x() % 2 == 0,
|inpainter| inpainter.interpolate_inpaint_image_with(Direction::Right),
)?;
inpainting.step(
"Vertically interpolating inpaint images",
// Interleave interpolation to avoid race conditions when writing images
|spatial_node_id| spatial_node_id.y() % 2 == 0,
|inpainter| inpainter.interpolate_inpaint_image_with(Direction::Bottom),
)?;
inpainting.step(
"Applying inpainting",
|_| false,
SpatialNodeInpainter::apply_inpainting,
)?;
Ok(())
}
|
{
let (width, height) = match direction {
Direction::Right => (current.width() / 2, current.height()),
Direction::Bottom => (current.width(), current.height() / 2),
_ => unimplemented!(),
};
let ((current_x, current_y), (neighbor_x, neighbor_y)) = match direction {
Direction::Right => ((width, 0), (0, 0)),
Direction::Bottom => ((0, height), (0, 0)),
_ => unimplemented!(),
};
let neighbor_weighting_function: Box<dyn Fn(u32, u32) -> f32> = match direction {
Direction::Right => Box::new(|i, _| i as f32 / (width - 1) as f32),
Direction::Bottom => Box::new(|_, j| j as f32 / (height - 1) as f32),
_ => unimplemented!(),
};
interpolate_subimages(
&mut neighbor.sub_image(neighbor_x, neighbor_y, width, height),
&mut current.sub_image(current_x, current_y, width, height),
neighbor_weighting_function,
|
conditional_block
|
inpaint.rs
|
// Inpainting is applied to fill holes in the X-ray quadtree leaf tiles.
// As inpainting depends on sampling the neighborhood of pixels, if we
// directly took the original tiles as input, we would get visible color
// differences for the inpainted pixels along the tile borders. Because
// of this we enlarge all tiles, so they overlap each other by half of their
// dimension, apply inpainting on the enlarged tiles and bilinearly interpolate
// between tiles, before cutting out the original tile.
use crate::utils::{get_image_path, image_from_path, interpolate_subimages};
use fnv::FnvHashSet;
use image::{DynamicImage, GenericImage, GenericImageView, ImageResult, Luma, Rgba, RgbaImage};
use imageproc::distance_transform::Norm;
use imageproc::map::{map_colors, map_colors2};
use imageproc::morphology::close;
use point_viewer::color::TRANSPARENT;
use point_viewer::utils::create_syncable_progress_bar;
use quadtree::{Direction, NodeId, SpatialNodeId};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use std::fs;
use std::path::{Path, PathBuf};
use texture_synthesis::{Dims, Example, Session};
/// Inpaints only holes with radius <= distance_px in the image, but leaves big borders untouched.
fn inpaint(image: RgbaImage, distance_px: u8) -> RgbaImage {
let (width, height) = image.dimensions();
// extract the alpha channel as sampling mask
let mask = map_colors(&image, |p| Luma([p[3]]));
// fill holes in the alpha channel
let closed_mask = close(&mask, Norm::LInf, distance_px);
// mark pixels to be inpainted
let inpaint_mask = map_colors2(&closed_mask, &mask, |c, m| Luma([255 - (c[0] - m[0])]));
let texsynth = Session::builder()
// we perform multithreading outside, so one deterministic thread here is enough
.max_thread_count(1)
.inpaint_example(
DynamicImage::ImageLuma8(inpaint_mask),
Example::builder(DynamicImage::ImageRgba8(image))
.set_sample_method(DynamicImage::ImageLuma8(mask)),
Dims::new(width, height),
)
.build()
.expect("Inpaint failed.");
texsynth.run(None).into_image().into_rgba()
}
struct SpatialNodeInpainter<'a> {
spatial_node_id: SpatialNodeId,
output_directory: &'a Path,
}
impl<'a> SpatialNodeInpainter<'a> {
fn get_inpaint_image_path(&self) -> PathBuf {
get_image_path(self.output_directory, NodeId::from(self.spatial_node_id))
.with_extension("inpaint.png")
}
fn spatial_id_from(&self, neighbor: impl Into<Option<Direction>>) -> Option<SpatialNodeId> {
match neighbor.into() {
Some(n) => self.spatial_node_id.neighbor(n),
None => Some(self.spatial_node_id),
}
}
fn image_from(&self, neighbor: impl Into<Option<Direction>>) -> ImageResult<Option<RgbaImage>> {
self.spatial_id_from(neighbor)
.and_then(|id| {
image_from_path(&get_image_path(self.output_directory, NodeId::from(id)))
})
.transpose()
}
fn inpaint_image_and_path_from(
&self,
neighbor: impl Into<Option<Direction>>,
) -> ImageResult<Option<(RgbaImage, PathBuf)>> {
self.spatial_id_from(neighbor)
.and_then(|spatial_node_id| {
let inpainter = SpatialNodeInpainter {
spatial_node_id,
output_directory: self.output_directory,
};
let inpaint_image_path = inpainter.get_inpaint_image_path();
image_from_path(&inpaint_image_path).map(|inpaint_image_res| {
inpaint_image_res.map(|inpaint_image| (inpaint_image, inpaint_image_path))
})
})
.transpose()
}
fn stitched_image(&self) -> ImageResult<Option<RgbaImage>> {
if let Some(current) = self.image_from(None)? {
let w = current.width() / 2;
let h = current.height() / 2;
let mut image = RgbaImage::from_pixel(4 * w, 4 * h, Rgba::from(TRANSPARENT.to_u8()));
image.copy_from(¤t, w, h)?;
let mut copy_subimage = |direction: Direction,
from_x: u32,
from_y: u32,
width: u32,
height: u32,
to_x: u32,
to_y: u32|
-> ImageResult<()> {
if let Some(neighbor) = self.image_from(direction)? {
image.copy_from(&neighbor.view(from_x, from_y, width, height), to_x, to_y)?;
}
Ok(())
};
copy_subimage(Direction::TopLeft, w, h, w, h, 0, 0)?;
copy_subimage(Direction::Top, 0, h, 2 * w, h, w, 0)?;
copy_subimage(Direction::TopRight, 0, h, w, h, 3 * w, 0)?;
copy_subimage(Direction::Right, 0, 0, w, 2 * h, 3 * w, h)?;
copy_subimage(Direction::BottomRight, 0, 0, w, h, 3 * w, 3 * h)?;
copy_subimage(Direction::Bottom, 0, 0, 2 * w, h, w, 3 * h)?;
copy_subimage(Direction::BottomLeft, w, 0, w, h, 0, 3 * h)?;
copy_subimage(Direction::Left, w, 0, w, 2 * h, 0, h)?;
Ok(Some(image))
} else {
Ok(None)
}
}
fn create_inpaint_image(&self, inpaint_distance_px: u8) -> ImageResult<()> {
if let Some(mut inpaint_image) = self.stitched_image()? {
inpaint_image = inpaint(inpaint_image, inpaint_distance_px);
let inpaint_image_path = self.get_inpaint_image_path();
inpaint_image.save(inpaint_image_path)?;
}
Ok(())
}
fn interpolate_inpaint_image_with(&self, direction: Direction) -> ImageResult<()> {
if let (Some((mut current, current_path)), Some((mut neighbor, neighbor_path))) = (
self.inpaint_image_and_path_from(None)?,
self.inpaint_image_and_path_from(direction)?,
) {
let (width, height) = match direction {
Direction::Right => (current.width() / 2, current.height()),
Direction::Bottom => (current.width(), current.height() / 2),
_ => unimplemented!(),
};
let ((current_x, current_y), (neighbor_x, neighbor_y)) = match direction {
Direction::Right => ((width, 0), (0, 0)),
Direction::Bottom => ((0, height), (0, 0)),
_ => unimplemented!(),
};
let neighbor_weighting_function: Box<dyn Fn(u32, u32) -> f32> = match direction {
Direction::Right => Box::new(|i, _| i as f32 / (width - 1) as f32),
Direction::Bottom => Box::new(|_, j| j as f32 / (height - 1) as f32),
_ => unimplemented!(),
};
interpolate_subimages(
&mut neighbor.sub_image(neighbor_x, neighbor_y, width, height),
&mut current.sub_image(current_x, current_y, width, height),
neighbor_weighting_function,
);
current.save(current_path)?;
neighbor.save(neighbor_path)?;
}
Ok(())
}
fn apply_inpainting(&self) -> ImageResult<()> {
if let Some((inpaint_image, inpaint_image_path)) = self.inpaint_image_and_path_from(None)? {
let (width, height) = inpaint_image.dimensions();
let image_view = inpaint_image.view(width / 4, height / 4, width / 2, height / 2);
let image_path =
get_image_path(self.output_directory, NodeId::from(self.spatial_node_id));
image_view.to_image().save(image_path)?;
fs::remove_file(inpaint_image_path)?;
}
Ok(())
}
}
struct Inpainting<'a> {
output_directory: &'a Path,
spatial_node_ids: Vec<SpatialNodeId>,
}
impl<'a> Inpainting<'a> {
fn step<P, F>(
&self,
message: &str,
partitioning_function: P,
inpainter_function: F,
) -> ImageResult<()>
where
P: FnMut(&&SpatialNodeId) -> bool,
F: Fn(&SpatialNodeInpainter<'a>) -> ImageResult<()> + Sync,
{
let progress_bar = create_syncable_progress_bar(self.spatial_node_ids.len(), message);
let run_partition = |spatial_node_ids: Vec<SpatialNodeId>| -> ImageResult<()> {
spatial_node_ids
.into_par_iter()
.try_for_each(|spatial_node_id| {
let inpainter = SpatialNodeInpainter {
spatial_node_id,
output_directory: self.output_directory,
};
let res = inpainter_function(&inpainter);
progress_bar.lock().unwrap().inc();
res
})
};
let (first, second): (Vec<SpatialNodeId>, Vec<SpatialNodeId>) = self
.spatial_node_ids
.iter()
.partition(partitioning_function);
run_partition(first)?;
run_partition(second)?;
progress_bar.lock().unwrap().finish_println("");
Ok(())
}
}
pub fn perform_inpainting(
output_directory: &Path,
inpaint_distance_px: u8,
leaf_node_ids: &FnvHashSet<NodeId>,
) -> ImageResult<()>
|
)?;
inpainting.step(
"Horizontally interpolating inpaint images",
// Interleave interpolation to avoid race conditions when writing images
|spatial_node_id| spatial_node_id.x() % 2 == 0,
|inpainter| inpainter.interpolate_inpaint_image_with(Direction::Right),
)?;
inpainting.step(
"Vertically interpolating inpaint images",
// Interleave interpolation to avoid race conditions when writing images
|spatial_node_id| spatial_node_id.y() % 2 == 0,
|inpainter| inpainter.interpolate_inpaint_image_with(Direction::Bottom),
)?;
inpainting.step(
"Applying inpainting",
|_| false,
SpatialNodeInpainter::apply_inpainting,
)?;
Ok(())
}
|
{
if inpaint_distance_px == 0 {
return Ok(());
}
let spatial_node_ids: Vec<SpatialNodeId> = leaf_node_ids
.iter()
.cloned()
.map(SpatialNodeId::from)
.collect();
let inpainting = Inpainting {
output_directory,
spatial_node_ids,
};
inpainting.step(
"Creating inpaint images",
|_| false,
|inpainter| inpainter.create_inpaint_image(inpaint_distance_px),
|
identifier_body
|
inpaint.rs
|
// Inpainting is applied to fill holes in the X-ray quadtree leaf tiles.
// As inpainting depends on sampling the neighborhood of pixels, if we
// directly took the original tiles as input, we would get visible color
// differences for the inpainted pixels along the tile borders. Because
// of this we enlarge all tiles, so they overlap each other by half of their
// dimension, apply inpainting on the enlarged tiles and bilinearly interpolate
// between tiles, before cutting out the original tile.
use crate::utils::{get_image_path, image_from_path, interpolate_subimages};
use fnv::FnvHashSet;
use image::{DynamicImage, GenericImage, GenericImageView, ImageResult, Luma, Rgba, RgbaImage};
use imageproc::distance_transform::Norm;
use imageproc::map::{map_colors, map_colors2};
use imageproc::morphology::close;
use point_viewer::color::TRANSPARENT;
use point_viewer::utils::create_syncable_progress_bar;
use quadtree::{Direction, NodeId, SpatialNodeId};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use std::fs;
use std::path::{Path, PathBuf};
use texture_synthesis::{Dims, Example, Session};
/// Inpaints only holes with radius <= distance_px in the image, but leaves big borders untouched.
fn inpaint(image: RgbaImage, distance_px: u8) -> RgbaImage {
let (width, height) = image.dimensions();
// extract the alpha channel as sampling mask
let mask = map_colors(&image, |p| Luma([p[3]]));
// fill holes in the alpha channel
let closed_mask = close(&mask, Norm::LInf, distance_px);
// mark pixels to be inpainted
let inpaint_mask = map_colors2(&closed_mask, &mask, |c, m| Luma([255 - (c[0] - m[0])]));
let texsynth = Session::builder()
// we perform multithreading outside, so one deterministic thread here is enough
.max_thread_count(1)
.inpaint_example(
DynamicImage::ImageLuma8(inpaint_mask),
Example::builder(DynamicImage::ImageRgba8(image))
.set_sample_method(DynamicImage::ImageLuma8(mask)),
Dims::new(width, height),
)
.build()
.expect("Inpaint failed.");
texsynth.run(None).into_image().into_rgba()
}
struct SpatialNodeInpainter<'a> {
spatial_node_id: SpatialNodeId,
output_directory: &'a Path,
}
impl<'a> SpatialNodeInpainter<'a> {
fn get_inpaint_image_path(&self) -> PathBuf {
get_image_path(self.output_directory, NodeId::from(self.spatial_node_id))
.with_extension("inpaint.png")
}
fn
|
(&self, neighbor: impl Into<Option<Direction>>) -> Option<SpatialNodeId> {
match neighbor.into() {
Some(n) => self.spatial_node_id.neighbor(n),
None => Some(self.spatial_node_id),
}
}
fn image_from(&self, neighbor: impl Into<Option<Direction>>) -> ImageResult<Option<RgbaImage>> {
self.spatial_id_from(neighbor)
.and_then(|id| {
image_from_path(&get_image_path(self.output_directory, NodeId::from(id)))
})
.transpose()
}
fn inpaint_image_and_path_from(
&self,
neighbor: impl Into<Option<Direction>>,
) -> ImageResult<Option<(RgbaImage, PathBuf)>> {
self.spatial_id_from(neighbor)
.and_then(|spatial_node_id| {
let inpainter = SpatialNodeInpainter {
spatial_node_id,
output_directory: self.output_directory,
};
let inpaint_image_path = inpainter.get_inpaint_image_path();
image_from_path(&inpaint_image_path).map(|inpaint_image_res| {
inpaint_image_res.map(|inpaint_image| (inpaint_image, inpaint_image_path))
})
})
.transpose()
}
fn stitched_image(&self) -> ImageResult<Option<RgbaImage>> {
if let Some(current) = self.image_from(None)? {
let w = current.width() / 2;
let h = current.height() / 2;
let mut image = RgbaImage::from_pixel(4 * w, 4 * h, Rgba::from(TRANSPARENT.to_u8()));
image.copy_from(¤t, w, h)?;
let mut copy_subimage = |direction: Direction,
from_x: u32,
from_y: u32,
width: u32,
height: u32,
to_x: u32,
to_y: u32|
-> ImageResult<()> {
if let Some(neighbor) = self.image_from(direction)? {
image.copy_from(&neighbor.view(from_x, from_y, width, height), to_x, to_y)?;
}
Ok(())
};
copy_subimage(Direction::TopLeft, w, h, w, h, 0, 0)?;
copy_subimage(Direction::Top, 0, h, 2 * w, h, w, 0)?;
copy_subimage(Direction::TopRight, 0, h, w, h, 3 * w, 0)?;
copy_subimage(Direction::Right, 0, 0, w, 2 * h, 3 * w, h)?;
copy_subimage(Direction::BottomRight, 0, 0, w, h, 3 * w, 3 * h)?;
copy_subimage(Direction::Bottom, 0, 0, 2 * w, h, w, 3 * h)?;
copy_subimage(Direction::BottomLeft, w, 0, w, h, 0, 3 * h)?;
copy_subimage(Direction::Left, w, 0, w, 2 * h, 0, h)?;
Ok(Some(image))
} else {
Ok(None)
}
}
fn create_inpaint_image(&self, inpaint_distance_px: u8) -> ImageResult<()> {
if let Some(mut inpaint_image) = self.stitched_image()? {
inpaint_image = inpaint(inpaint_image, inpaint_distance_px);
let inpaint_image_path = self.get_inpaint_image_path();
inpaint_image.save(inpaint_image_path)?;
}
Ok(())
}
fn interpolate_inpaint_image_with(&self, direction: Direction) -> ImageResult<()> {
if let (Some((mut current, current_path)), Some((mut neighbor, neighbor_path))) = (
self.inpaint_image_and_path_from(None)?,
self.inpaint_image_and_path_from(direction)?,
) {
let (width, height) = match direction {
Direction::Right => (current.width() / 2, current.height()),
Direction::Bottom => (current.width(), current.height() / 2),
_ => unimplemented!(),
};
let ((current_x, current_y), (neighbor_x, neighbor_y)) = match direction {
Direction::Right => ((width, 0), (0, 0)),
Direction::Bottom => ((0, height), (0, 0)),
_ => unimplemented!(),
};
let neighbor_weighting_function: Box<dyn Fn(u32, u32) -> f32> = match direction {
Direction::Right => Box::new(|i, _| i as f32 / (width - 1) as f32),
Direction::Bottom => Box::new(|_, j| j as f32 / (height - 1) as f32),
_ => unimplemented!(),
};
interpolate_subimages(
&mut neighbor.sub_image(neighbor_x, neighbor_y, width, height),
&mut current.sub_image(current_x, current_y, width, height),
neighbor_weighting_function,
);
current.save(current_path)?;
neighbor.save(neighbor_path)?;
}
Ok(())
}
fn apply_inpainting(&self) -> ImageResult<()> {
if let Some((inpaint_image, inpaint_image_path)) = self.inpaint_image_and_path_from(None)? {
let (width, height) = inpaint_image.dimensions();
let image_view = inpaint_image.view(width / 4, height / 4, width / 2, height / 2);
let image_path =
get_image_path(self.output_directory, NodeId::from(self.spatial_node_id));
image_view.to_image().save(image_path)?;
fs::remove_file(inpaint_image_path)?;
}
Ok(())
}
}
struct Inpainting<'a> {
output_directory: &'a Path,
spatial_node_ids: Vec<SpatialNodeId>,
}
impl<'a> Inpainting<'a> {
fn step<P, F>(
&self,
message: &str,
partitioning_function: P,
inpainter_function: F,
) -> ImageResult<()>
where
P: FnMut(&&SpatialNodeId) -> bool,
F: Fn(&SpatialNodeInpainter<'a>) -> ImageResult<()> + Sync,
{
let progress_bar = create_syncable_progress_bar(self.spatial_node_ids.len(), message);
let run_partition = |spatial_node_ids: Vec<SpatialNodeId>| -> ImageResult<()> {
spatial_node_ids
.into_par_iter()
.try_for_each(|spatial_node_id| {
let inpainter = SpatialNodeInpainter {
spatial_node_id,
output_directory: self.output_directory,
};
let res = inpainter_function(&inpainter);
progress_bar.lock().unwrap().inc();
res
})
};
let (first, second): (Vec<SpatialNodeId>, Vec<SpatialNodeId>) = self
.spatial_node_ids
.iter()
.partition(partitioning_function);
run_partition(first)?;
run_partition(second)?;
progress_bar.lock().unwrap().finish_println("");
Ok(())
}
}
pub fn perform_inpainting(
output_directory: &Path,
inpaint_distance_px: u8,
leaf_node_ids: &FnvHashSet<NodeId>,
) -> ImageResult<()> {
if inpaint_distance_px == 0 {
return Ok(());
}
let spatial_node_ids: Vec<SpatialNodeId> = leaf_node_ids
.iter()
.cloned()
.map(SpatialNodeId::from)
.collect();
let inpainting = Inpainting {
output_directory,
spatial_node_ids,
};
inpainting.step(
"Creating inpaint images",
|_| false,
|inpainter| inpainter.create_inpaint_image(inpaint_distance_px),
)?;
inpainting.step(
"Horizontally interpolating inpaint images",
// Interleave interpolation to avoid race conditions when writing images
|spatial_node_id| spatial_node_id.x() % 2 == 0,
|inpainter| inpainter.interpolate_inpaint_image_with(Direction::Right),
)?;
inpainting.step(
"Vertically interpolating inpaint images",
// Interleave interpolation to avoid race conditions when writing images
|spatial_node_id| spatial_node_id.y() % 2 == 0,
|inpainter| inpainter.interpolate_inpaint_image_with(Direction::Bottom),
)?;
inpainting.step(
"Applying inpainting",
|_| false,
SpatialNodeInpainter::apply_inpainting,
)?;
Ok(())
}
|
spatial_id_from
|
identifier_name
|
inpaint.rs
|
// Inpainting is applied to fill holes in the X-ray quadtree leaf tiles.
// As inpainting depends on sampling the neighborhood of pixels, if we
// directly took the original tiles as input, we would get visible color
// differences for the inpainted pixels along the tile borders. Because
// of this we enlarge all tiles, so they overlap each other by half of their
// dimension, apply inpainting on the enlarged tiles and bilinearly interpolate
// between tiles, before cutting out the original tile.
use crate::utils::{get_image_path, image_from_path, interpolate_subimages};
use fnv::FnvHashSet;
use image::{DynamicImage, GenericImage, GenericImageView, ImageResult, Luma, Rgba, RgbaImage};
use imageproc::distance_transform::Norm;
use imageproc::map::{map_colors, map_colors2};
use imageproc::morphology::close;
use point_viewer::color::TRANSPARENT;
use point_viewer::utils::create_syncable_progress_bar;
use quadtree::{Direction, NodeId, SpatialNodeId};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use std::fs;
use std::path::{Path, PathBuf};
use texture_synthesis::{Dims, Example, Session};
/// Inpaints only holes with radius <= distance_px in the image, but leaves big borders untouched.
fn inpaint(image: RgbaImage, distance_px: u8) -> RgbaImage {
let (width, height) = image.dimensions();
// extract the alpha channel as sampling mask
let mask = map_colors(&image, |p| Luma([p[3]]));
// fill holes in the alpha channel
let closed_mask = close(&mask, Norm::LInf, distance_px);
// mark pixels to be inpainted
let inpaint_mask = map_colors2(&closed_mask, &mask, |c, m| Luma([255 - (c[0] - m[0])]));
let texsynth = Session::builder()
// we perform multithreading outside, so one deterministic thread here is enough
.max_thread_count(1)
.inpaint_example(
DynamicImage::ImageLuma8(inpaint_mask),
Example::builder(DynamicImage::ImageRgba8(image))
.set_sample_method(DynamicImage::ImageLuma8(mask)),
Dims::new(width, height),
)
.build()
.expect("Inpaint failed.");
texsynth.run(None).into_image().into_rgba()
}
struct SpatialNodeInpainter<'a> {
spatial_node_id: SpatialNodeId,
output_directory: &'a Path,
}
impl<'a> SpatialNodeInpainter<'a> {
fn get_inpaint_image_path(&self) -> PathBuf {
get_image_path(self.output_directory, NodeId::from(self.spatial_node_id))
.with_extension("inpaint.png")
}
fn spatial_id_from(&self, neighbor: impl Into<Option<Direction>>) -> Option<SpatialNodeId> {
match neighbor.into() {
Some(n) => self.spatial_node_id.neighbor(n),
None => Some(self.spatial_node_id),
}
}
fn image_from(&self, neighbor: impl Into<Option<Direction>>) -> ImageResult<Option<RgbaImage>> {
self.spatial_id_from(neighbor)
.and_then(|id| {
image_from_path(&get_image_path(self.output_directory, NodeId::from(id)))
})
.transpose()
}
fn inpaint_image_and_path_from(
&self,
neighbor: impl Into<Option<Direction>>,
) -> ImageResult<Option<(RgbaImage, PathBuf)>> {
self.spatial_id_from(neighbor)
.and_then(|spatial_node_id| {
let inpainter = SpatialNodeInpainter {
spatial_node_id,
output_directory: self.output_directory,
};
let inpaint_image_path = inpainter.get_inpaint_image_path();
image_from_path(&inpaint_image_path).map(|inpaint_image_res| {
inpaint_image_res.map(|inpaint_image| (inpaint_image, inpaint_image_path))
})
})
.transpose()
}
fn stitched_image(&self) -> ImageResult<Option<RgbaImage>> {
if let Some(current) = self.image_from(None)? {
let w = current.width() / 2;
let h = current.height() / 2;
let mut image = RgbaImage::from_pixel(4 * w, 4 * h, Rgba::from(TRANSPARENT.to_u8()));
image.copy_from(¤t, w, h)?;
let mut copy_subimage = |direction: Direction,
from_x: u32,
from_y: u32,
width: u32,
height: u32,
to_x: u32,
to_y: u32|
-> ImageResult<()> {
if let Some(neighbor) = self.image_from(direction)? {
image.copy_from(&neighbor.view(from_x, from_y, width, height), to_x, to_y)?;
}
Ok(())
};
copy_subimage(Direction::TopLeft, w, h, w, h, 0, 0)?;
copy_subimage(Direction::Top, 0, h, 2 * w, h, w, 0)?;
copy_subimage(Direction::TopRight, 0, h, w, h, 3 * w, 0)?;
copy_subimage(Direction::Right, 0, 0, w, 2 * h, 3 * w, h)?;
copy_subimage(Direction::BottomRight, 0, 0, w, h, 3 * w, 3 * h)?;
copy_subimage(Direction::Bottom, 0, 0, 2 * w, h, w, 3 * h)?;
copy_subimage(Direction::BottomLeft, w, 0, w, h, 0, 3 * h)?;
copy_subimage(Direction::Left, w, 0, w, 2 * h, 0, h)?;
Ok(Some(image))
} else {
Ok(None)
}
}
fn create_inpaint_image(&self, inpaint_distance_px: u8) -> ImageResult<()> {
if let Some(mut inpaint_image) = self.stitched_image()? {
inpaint_image = inpaint(inpaint_image, inpaint_distance_px);
let inpaint_image_path = self.get_inpaint_image_path();
inpaint_image.save(inpaint_image_path)?;
}
Ok(())
}
fn interpolate_inpaint_image_with(&self, direction: Direction) -> ImageResult<()> {
if let (Some((mut current, current_path)), Some((mut neighbor, neighbor_path))) = (
self.inpaint_image_and_path_from(None)?,
self.inpaint_image_and_path_from(direction)?,
) {
let (width, height) = match direction {
Direction::Right => (current.width() / 2, current.height()),
Direction::Bottom => (current.width(), current.height() / 2),
_ => unimplemented!(),
};
let ((current_x, current_y), (neighbor_x, neighbor_y)) = match direction {
Direction::Right => ((width, 0), (0, 0)),
Direction::Bottom => ((0, height), (0, 0)),
|
};
let neighbor_weighting_function: Box<dyn Fn(u32, u32) -> f32> = match direction {
Direction::Right => Box::new(|i, _| i as f32 / (width - 1) as f32),
Direction::Bottom => Box::new(|_, j| j as f32 / (height - 1) as f32),
_ => unimplemented!(),
};
interpolate_subimages(
&mut neighbor.sub_image(neighbor_x, neighbor_y, width, height),
&mut current.sub_image(current_x, current_y, width, height),
neighbor_weighting_function,
);
current.save(current_path)?;
neighbor.save(neighbor_path)?;
}
Ok(())
}
fn apply_inpainting(&self) -> ImageResult<()> {
if let Some((inpaint_image, inpaint_image_path)) = self.inpaint_image_and_path_from(None)? {
let (width, height) = inpaint_image.dimensions();
let image_view = inpaint_image.view(width / 4, height / 4, width / 2, height / 2);
let image_path =
get_image_path(self.output_directory, NodeId::from(self.spatial_node_id));
image_view.to_image().save(image_path)?;
fs::remove_file(inpaint_image_path)?;
}
Ok(())
}
}
struct Inpainting<'a> {
output_directory: &'a Path,
spatial_node_ids: Vec<SpatialNodeId>,
}
impl<'a> Inpainting<'a> {
fn step<P, F>(
&self,
message: &str,
partitioning_function: P,
inpainter_function: F,
) -> ImageResult<()>
where
P: FnMut(&&SpatialNodeId) -> bool,
F: Fn(&SpatialNodeInpainter<'a>) -> ImageResult<()> + Sync,
{
let progress_bar = create_syncable_progress_bar(self.spatial_node_ids.len(), message);
let run_partition = |spatial_node_ids: Vec<SpatialNodeId>| -> ImageResult<()> {
spatial_node_ids
.into_par_iter()
.try_for_each(|spatial_node_id| {
let inpainter = SpatialNodeInpainter {
spatial_node_id,
output_directory: self.output_directory,
};
let res = inpainter_function(&inpainter);
progress_bar.lock().unwrap().inc();
res
})
};
let (first, second): (Vec<SpatialNodeId>, Vec<SpatialNodeId>) = self
.spatial_node_ids
.iter()
.partition(partitioning_function);
run_partition(first)?;
run_partition(second)?;
progress_bar.lock().unwrap().finish_println("");
Ok(())
}
}
pub fn perform_inpainting(
output_directory: &Path,
inpaint_distance_px: u8,
leaf_node_ids: &FnvHashSet<NodeId>,
) -> ImageResult<()> {
if inpaint_distance_px == 0 {
return Ok(());
}
let spatial_node_ids: Vec<SpatialNodeId> = leaf_node_ids
.iter()
.cloned()
.map(SpatialNodeId::from)
.collect();
let inpainting = Inpainting {
output_directory,
spatial_node_ids,
};
inpainting.step(
"Creating inpaint images",
|_| false,
|inpainter| inpainter.create_inpaint_image(inpaint_distance_px),
)?;
inpainting.step(
"Horizontally interpolating inpaint images",
// Interleave interpolation to avoid race conditions when writing images
|spatial_node_id| spatial_node_id.x() % 2 == 0,
|inpainter| inpainter.interpolate_inpaint_image_with(Direction::Right),
)?;
inpainting.step(
"Vertically interpolating inpaint images",
// Interleave interpolation to avoid race conditions when writing images
|spatial_node_id| spatial_node_id.y() % 2 == 0,
|inpainter| inpainter.interpolate_inpaint_image_with(Direction::Bottom),
)?;
inpainting.step(
"Applying inpainting",
|_| false,
SpatialNodeInpainter::apply_inpainting,
)?;
Ok(())
}
|
_ => unimplemented!(),
|
random_line_split
|
markup.rs
|
use serde_derive::{Deserialize, Serialize};
use syntect::parsing::SyntaxSet;
pub const DEFAULT_HIGHLIGHT_THEME: &str = "base16-ocean-dark";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Markdown {
/// Whether to highlight all code blocks found in markdown files. Defaults to false
pub highlight_code: bool,
/// Which themes to use for code highlighting. See Readme for supported themes
/// Defaults to "base16-ocean-dark"
pub highlight_theme: String,
/// Whether to render emoji aliases (e.g.: :smile: => 😄) in the markdown files
pub render_emoji: bool,
/// Whether external links are to be opened in a new tab
/// If this is true, a `rel="noopener"` will always automatically be added for security reasons
pub external_links_target_blank: bool,
/// Whether to set rel="nofollow" for all external links
pub external_links_no_follow: bool,
/// Whether to set rel="noreferrer" for all external links
pub external_links_no_referrer: bool,
/// Whether smart punctuation is enabled (changing quotes, dashes, dots etc in their typographic form)
pub smart_punctuation: bool,
/// A list of directories to search for additional `.sublime-syntax` files in.
pub extra_syntaxes: Vec<String>,
/// The compiled extra syntaxes into a syntax set
#[serde(skip_serializing, skip_deserializing)] // not a typo, 2 are need
pub extra_syntax_set: Option<SyntaxSet>,
}
impl Markdown {
pub fn has_external_link_tweaks(&self) -> bool {
self.external_links_target_blank
|| self.external_links_no_follow
|| self.external_links_no_referrer
}
pub fn construct_external_link_tag(&self, url: &str, title: &str) -> String {
let mut rel_opts = Vec::new();
let mut target = "".to_owned();
let title = if title == "" { "".to_owned() } else { format!("title=\"{}\" ", title) };
if self.external_links_target_blank {
// Security risk otherwise
rel_opts.push("noopener");
target = "target=\"_blank\" ".to_owned();
}
if self.external_links_no_follow {
rel_opts.push("nofollow");
}
if self.external_links_no_referrer {
rel_opts.push("noreferrer");
}
let rel = if rel_opts.is_empty() {
|
se {
format!("rel=\"{}\" ", rel_opts.join(" "))
};
format!("<a {}{}{}href=\"{}\">", rel, target, title, url)
}
}
impl Default for Markdown {
fn default() -> Markdown {
Markdown {
highlight_code: false,
highlight_theme: DEFAULT_HIGHLIGHT_THEME.to_owned(),
render_emoji: false,
external_links_target_blank: false,
external_links_no_follow: false,
external_links_no_referrer: false,
smart_punctuation: false,
extra_syntaxes: vec![],
extra_syntax_set: None,
}
}
}
|
"".to_owned()
} el
|
conditional_block
|
markup.rs
|
use serde_derive::{Deserialize, Serialize};
use syntect::parsing::SyntaxSet;
pub const DEFAULT_HIGHLIGHT_THEME: &str = "base16-ocean-dark";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Markdown {
/// Whether to highlight all code blocks found in markdown files. Defaults to false
pub highlight_code: bool,
/// Which themes to use for code highlighting. See Readme for supported themes
/// Defaults to "base16-ocean-dark"
pub highlight_theme: String,
/// Whether to render emoji aliases (e.g.: :smile: => 😄) in the markdown files
pub render_emoji: bool,
/// Whether external links are to be opened in a new tab
/// If this is true, a `rel="noopener"` will always automatically be added for security reasons
pub external_links_target_blank: bool,
/// Whether to set rel="nofollow" for all external links
pub external_links_no_follow: bool,
/// Whether to set rel="noreferrer" for all external links
pub external_links_no_referrer: bool,
/// Whether smart punctuation is enabled (changing quotes, dashes, dots etc in their typographic form)
pub smart_punctuation: bool,
/// A list of directories to search for additional `.sublime-syntax` files in.
pub extra_syntaxes: Vec<String>,
/// The compiled extra syntaxes into a syntax set
#[serde(skip_serializing, skip_deserializing)] // not a typo, 2 are need
pub extra_syntax_set: Option<SyntaxSet>,
}
impl Markdown {
pub fn has_external_link_tweaks(&self) -> bool {
self.external_links_target_blank
|| self.external_links_no_follow
|| self.external_links_no_referrer
}
pub fn construct_external_link_tag(&self, url: &str, title: &str) -> String {
let mut rel_opts = Vec::new();
let mut target = "".to_owned();
let title = if title == "" { "".to_owned() } else { format!("title=\"{}\" ", title) };
if self.external_links_target_blank {
// Security risk otherwise
rel_opts.push("noopener");
target = "target=\"_blank\" ".to_owned();
}
if self.external_links_no_follow {
rel_opts.push("nofollow");
}
if self.external_links_no_referrer {
rel_opts.push("noreferrer");
}
let rel = if rel_opts.is_empty() {
"".to_owned()
} else {
format!("rel=\"{}\" ", rel_opts.join(" "))
};
format!("<a {}{}{}href=\"{}\">", rel, target, title, url)
}
}
impl Default for Markdown {
fn default() -> Markdown {
Markdown {
highlight_code: false,
highlight_theme: DEFAULT_HIGHLIGHT_THEME.to_owned(),
render_emoji: false,
external_links_target_blank: false,
external_links_no_follow: false,
external_links_no_referrer: false,
smart_punctuation: false,
extra_syntaxes: vec![],
extra_syntax_set: None,
}
}
|
}
|
random_line_split
|
|
markup.rs
|
use serde_derive::{Deserialize, Serialize};
use syntect::parsing::SyntaxSet;
pub const DEFAULT_HIGHLIGHT_THEME: &str = "base16-ocean-dark";
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Markdown {
/// Whether to highlight all code blocks found in markdown files. Defaults to false
pub highlight_code: bool,
/// Which themes to use for code highlighting. See Readme for supported themes
/// Defaults to "base16-ocean-dark"
pub highlight_theme: String,
/// Whether to render emoji aliases (e.g.: :smile: => 😄) in the markdown files
pub render_emoji: bool,
/// Whether external links are to be opened in a new tab
/// If this is true, a `rel="noopener"` will always automatically be added for security reasons
pub external_links_target_blank: bool,
/// Whether to set rel="nofollow" for all external links
pub external_links_no_follow: bool,
/// Whether to set rel="noreferrer" for all external links
pub external_links_no_referrer: bool,
/// Whether smart punctuation is enabled (changing quotes, dashes, dots etc in their typographic form)
pub smart_punctuation: bool,
/// A list of directories to search for additional `.sublime-syntax` files in.
pub extra_syntaxes: Vec<String>,
/// The compiled extra syntaxes into a syntax set
#[serde(skip_serializing, skip_deserializing)] // not a typo, 2 are need
pub extra_syntax_set: Option<SyntaxSet>,
}
impl Markdown {
pub fn has_external_link_tweaks(&self) -> bool {
self.external_links_target_blank
|| self.external_links_no_follow
|| self.external_links_no_referrer
}
pub fn con
|
elf, url: &str, title: &str) -> String {
let mut rel_opts = Vec::new();
let mut target = "".to_owned();
let title = if title == "" { "".to_owned() } else { format!("title=\"{}\" ", title) };
if self.external_links_target_blank {
// Security risk otherwise
rel_opts.push("noopener");
target = "target=\"_blank\" ".to_owned();
}
if self.external_links_no_follow {
rel_opts.push("nofollow");
}
if self.external_links_no_referrer {
rel_opts.push("noreferrer");
}
let rel = if rel_opts.is_empty() {
"".to_owned()
} else {
format!("rel=\"{}\" ", rel_opts.join(" "))
};
format!("<a {}{}{}href=\"{}\">", rel, target, title, url)
}
}
impl Default for Markdown {
fn default() -> Markdown {
Markdown {
highlight_code: false,
highlight_theme: DEFAULT_HIGHLIGHT_THEME.to_owned(),
render_emoji: false,
external_links_target_blank: false,
external_links_no_follow: false,
external_links_no_referrer: false,
smart_punctuation: false,
extra_syntaxes: vec![],
extra_syntax_set: None,
}
}
}
|
struct_external_link_tag(&s
|
identifier_name
|
screen.rs
|
use dom::bindings::codegen::Bindings::ScreenBinding;
use dom::bindings::codegen::Bindings::ScreenBinding::ScreenMethods;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::window::Window;
use dom_struct::dom_struct;
#[dom_struct]
pub struct Screen {
reflector_: Reflector,
}
impl Screen {
fn new_inherited() -> Screen {
Screen {
reflector_: Reflector::new(),
}
}
pub fn new(window: &Window) -> DomRoot<Screen> {
reflect_dom_object(Box::new(Screen::new_inherited()),
window,
ScreenBinding::Wrap)
}
}
impl ScreenMethods for Screen {
// https://drafts.csswg.org/cssom-view/#dom-screen-colordepth
fn ColorDepth(&self) -> u32 {
24
}
// https://drafts.csswg.org/cssom-view/#dom-screen-pixeldepth
fn PixelDepth(&self) -> u32 {
24
}
}
|
/* 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/. */
|
random_line_split
|
|
screen.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::ScreenBinding;
use dom::bindings::codegen::Bindings::ScreenBinding::ScreenMethods;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::window::Window;
use dom_struct::dom_struct;
#[dom_struct]
pub struct Screen {
reflector_: Reflector,
}
impl Screen {
fn new_inherited() -> Screen {
Screen {
reflector_: Reflector::new(),
}
}
pub fn new(window: &Window) -> DomRoot<Screen> {
reflect_dom_object(Box::new(Screen::new_inherited()),
window,
ScreenBinding::Wrap)
}
}
impl ScreenMethods for Screen {
// https://drafts.csswg.org/cssom-view/#dom-screen-colordepth
fn ColorDepth(&self) -> u32 {
24
}
// https://drafts.csswg.org/cssom-view/#dom-screen-pixeldepth
fn PixelDepth(&self) -> u32
|
}
|
{
24
}
|
identifier_body
|
screen.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::ScreenBinding;
use dom::bindings::codegen::Bindings::ScreenBinding::ScreenMethods;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::root::DomRoot;
use dom::window::Window;
use dom_struct::dom_struct;
#[dom_struct]
pub struct Screen {
reflector_: Reflector,
}
impl Screen {
fn new_inherited() -> Screen {
Screen {
reflector_: Reflector::new(),
}
}
pub fn new(window: &Window) -> DomRoot<Screen> {
reflect_dom_object(Box::new(Screen::new_inherited()),
window,
ScreenBinding::Wrap)
}
}
impl ScreenMethods for Screen {
// https://drafts.csswg.org/cssom-view/#dom-screen-colordepth
fn ColorDepth(&self) -> u32 {
24
}
// https://drafts.csswg.org/cssom-view/#dom-screen-pixeldepth
fn
|
(&self) -> u32 {
24
}
}
|
PixelDepth
|
identifier_name
|
service.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use {NetworkProtocolHandler, NetworkConfiguration, NonReservedPeerMode};
use error::NetworkError;
use host::{Host, NetworkContext, NetworkIoMessage, ProtocolId};
use stats::NetworkStats;
use io::*;
use parking_lot::RwLock;
use std::sync::Arc;
use ansi_term::Colour;
struct HostHandler {
public_url: RwLock<Option<String>>
}
impl IoHandler<NetworkIoMessage> for HostHandler {
fn message(&self, _io: &IoContext<NetworkIoMessage>, message: &NetworkIoMessage) {
if let NetworkIoMessage::NetworkStarted(ref public_url) = *message {
let mut url = self.public_url.write();
if url.as_ref().map_or(true, |uref| uref!= public_url) {
info!(target: "network", "Public node URL: {}", Colour::White.bold().paint(public_url.as_ref()));
}
|
}
}
}
/// IO Service with networking
/// `Message` defines a notification data type.
pub struct NetworkService {
io_service: IoService<NetworkIoMessage>,
host_info: String,
host: RwLock<Option<Arc<Host>>>,
stats: Arc<NetworkStats>,
panic_handler: Arc<PanicHandler>,
host_handler: Arc<HostHandler>,
config: NetworkConfiguration,
}
impl NetworkService {
/// Starts IO event loop
pub fn new(config: NetworkConfiguration) -> Result<NetworkService, NetworkError> {
let host_handler = Arc::new(HostHandler { public_url: RwLock::new(None) });
let panic_handler = PanicHandler::new_in_arc();
let io_service = try!(IoService::<NetworkIoMessage>::start());
panic_handler.forward_from(&io_service);
let stats = Arc::new(NetworkStats::new());
let host_info = Host::client_version();
Ok(NetworkService {
io_service: io_service,
host_info: host_info,
stats: stats,
panic_handler: panic_handler,
host: RwLock::new(None),
config: config,
host_handler: host_handler,
})
}
/// Regiter a new protocol handler with the event loop.
pub fn register_protocol(&self, handler: Arc<NetworkProtocolHandler + Send + Sync>, protocol: ProtocolId, packet_count: u8, versions: &[u8]) -> Result<(), NetworkError> {
try!(self.io_service.send_message(NetworkIoMessage::AddHandler {
handler: handler,
protocol: protocol,
versions: versions.to_vec(),
packet_count: packet_count,
}));
Ok(())
}
/// Returns host identifier string as advertised to other peers
pub fn host_info(&self) -> String {
self.host_info.clone()
}
/// Returns underlying io service.
pub fn io(&self) -> &IoService<NetworkIoMessage> {
&self.io_service
}
/// Returns network statistics.
pub fn stats(&self) -> &NetworkStats {
&self.stats
}
/// Returns network configuration.
pub fn config(&self) -> &NetworkConfiguration {
&self.config
}
/// Returns external url if available.
pub fn external_url(&self) -> Option<String> {
let host = self.host.read();
host.as_ref().and_then(|h| h.external_url())
}
/// Returns external url if available.
pub fn local_url(&self) -> Option<String> {
let host = self.host.read();
host.as_ref().map(|h| h.local_url())
}
/// Start network IO
pub fn start(&self) -> Result<(), NetworkError> {
let mut host = self.host.write();
if host.is_none() {
let h = Arc::new(try!(Host::new(self.config.clone(), self.stats.clone())));
try!(self.io_service.register_handler(h.clone()));
*host = Some(h);
}
if self.host_handler.public_url.read().is_none() {
try!(self.io_service.register_handler(self.host_handler.clone()));
}
Ok(())
}
/// Stop network IO
pub fn stop(&self) -> Result<(), NetworkError> {
let mut host = self.host.write();
if let Some(ref host) = *host {
let io = IoContext::new(self.io_service.channel(), 0); //TODO: take token id from host
try!(host.stop(&io));
}
*host = None;
Ok(())
}
/// Try to add a reserved peer.
pub fn add_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> {
let host = self.host.read();
if let Some(ref host) = *host {
host.add_reserved_node(peer)
} else {
Ok(())
}
}
/// Try to remove a reserved peer.
pub fn remove_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> {
let host = self.host.read();
if let Some(ref host) = *host {
host.remove_reserved_node(peer)
} else {
Ok(())
}
}
/// Set the non-reserved peer mode.
pub fn set_non_reserved_mode(&self, mode: NonReservedPeerMode) {
let host = self.host.read();
if let Some(ref host) = *host {
let io_ctxt = IoContext::new(self.io_service.channel(), 0);
host.set_non_reserved_mode(mode, &io_ctxt);
}
}
/// Executes action in the network context
pub fn with_context<F>(&self, protocol: ProtocolId, action: F) where F: Fn(&NetworkContext) {
let io = IoContext::new(self.io_service.channel(), 0);
let host = self.host.read();
if let Some(ref host) = host.as_ref() {
host.with_context(protocol, &io, action);
};
}
/// Evaluates function in the network context
pub fn with_context_eval<F, T>(&self, protocol: ProtocolId, action: F) -> Option<T> where F: Fn(&NetworkContext) -> T {
let io = IoContext::new(self.io_service.channel(), 0);
let host = self.host.read();
host.as_ref().map(|ref host| host.with_context_eval(protocol, &io, action))
}
}
impl MayPanic for NetworkService {
fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
self.panic_handler.on_panic(closure);
}
}
|
*url = Some(public_url.to_owned());
|
random_line_split
|
service.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use {NetworkProtocolHandler, NetworkConfiguration, NonReservedPeerMode};
use error::NetworkError;
use host::{Host, NetworkContext, NetworkIoMessage, ProtocolId};
use stats::NetworkStats;
use io::*;
use parking_lot::RwLock;
use std::sync::Arc;
use ansi_term::Colour;
struct HostHandler {
public_url: RwLock<Option<String>>
}
impl IoHandler<NetworkIoMessage> for HostHandler {
fn message(&self, _io: &IoContext<NetworkIoMessage>, message: &NetworkIoMessage) {
if let NetworkIoMessage::NetworkStarted(ref public_url) = *message {
let mut url = self.public_url.write();
if url.as_ref().map_or(true, |uref| uref!= public_url) {
info!(target: "network", "Public node URL: {}", Colour::White.bold().paint(public_url.as_ref()));
}
*url = Some(public_url.to_owned());
}
}
}
/// IO Service with networking
/// `Message` defines a notification data type.
pub struct NetworkService {
io_service: IoService<NetworkIoMessage>,
host_info: String,
host: RwLock<Option<Arc<Host>>>,
stats: Arc<NetworkStats>,
panic_handler: Arc<PanicHandler>,
host_handler: Arc<HostHandler>,
config: NetworkConfiguration,
}
impl NetworkService {
/// Starts IO event loop
pub fn new(config: NetworkConfiguration) -> Result<NetworkService, NetworkError> {
let host_handler = Arc::new(HostHandler { public_url: RwLock::new(None) });
let panic_handler = PanicHandler::new_in_arc();
let io_service = try!(IoService::<NetworkIoMessage>::start());
panic_handler.forward_from(&io_service);
let stats = Arc::new(NetworkStats::new());
let host_info = Host::client_version();
Ok(NetworkService {
io_service: io_service,
host_info: host_info,
stats: stats,
panic_handler: panic_handler,
host: RwLock::new(None),
config: config,
host_handler: host_handler,
})
}
/// Regiter a new protocol handler with the event loop.
pub fn register_protocol(&self, handler: Arc<NetworkProtocolHandler + Send + Sync>, protocol: ProtocolId, packet_count: u8, versions: &[u8]) -> Result<(), NetworkError>
|
/// Returns host identifier string as advertised to other peers
pub fn host_info(&self) -> String {
self.host_info.clone()
}
/// Returns underlying io service.
pub fn io(&self) -> &IoService<NetworkIoMessage> {
&self.io_service
}
/// Returns network statistics.
pub fn stats(&self) -> &NetworkStats {
&self.stats
}
/// Returns network configuration.
pub fn config(&self) -> &NetworkConfiguration {
&self.config
}
/// Returns external url if available.
pub fn external_url(&self) -> Option<String> {
let host = self.host.read();
host.as_ref().and_then(|h| h.external_url())
}
/// Returns external url if available.
pub fn local_url(&self) -> Option<String> {
let host = self.host.read();
host.as_ref().map(|h| h.local_url())
}
/// Start network IO
pub fn start(&self) -> Result<(), NetworkError> {
let mut host = self.host.write();
if host.is_none() {
let h = Arc::new(try!(Host::new(self.config.clone(), self.stats.clone())));
try!(self.io_service.register_handler(h.clone()));
*host = Some(h);
}
if self.host_handler.public_url.read().is_none() {
try!(self.io_service.register_handler(self.host_handler.clone()));
}
Ok(())
}
/// Stop network IO
pub fn stop(&self) -> Result<(), NetworkError> {
let mut host = self.host.write();
if let Some(ref host) = *host {
let io = IoContext::new(self.io_service.channel(), 0); //TODO: take token id from host
try!(host.stop(&io));
}
*host = None;
Ok(())
}
/// Try to add a reserved peer.
pub fn add_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> {
let host = self.host.read();
if let Some(ref host) = *host {
host.add_reserved_node(peer)
} else {
Ok(())
}
}
/// Try to remove a reserved peer.
pub fn remove_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> {
let host = self.host.read();
if let Some(ref host) = *host {
host.remove_reserved_node(peer)
} else {
Ok(())
}
}
/// Set the non-reserved peer mode.
pub fn set_non_reserved_mode(&self, mode: NonReservedPeerMode) {
let host = self.host.read();
if let Some(ref host) = *host {
let io_ctxt = IoContext::new(self.io_service.channel(), 0);
host.set_non_reserved_mode(mode, &io_ctxt);
}
}
/// Executes action in the network context
pub fn with_context<F>(&self, protocol: ProtocolId, action: F) where F: Fn(&NetworkContext) {
let io = IoContext::new(self.io_service.channel(), 0);
let host = self.host.read();
if let Some(ref host) = host.as_ref() {
host.with_context(protocol, &io, action);
};
}
/// Evaluates function in the network context
pub fn with_context_eval<F, T>(&self, protocol: ProtocolId, action: F) -> Option<T> where F: Fn(&NetworkContext) -> T {
let io = IoContext::new(self.io_service.channel(), 0);
let host = self.host.read();
host.as_ref().map(|ref host| host.with_context_eval(protocol, &io, action))
}
}
impl MayPanic for NetworkService {
fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
self.panic_handler.on_panic(closure);
}
}
|
{
try!(self.io_service.send_message(NetworkIoMessage::AddHandler {
handler: handler,
protocol: protocol,
versions: versions.to_vec(),
packet_count: packet_count,
}));
Ok(())
}
|
identifier_body
|
service.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use {NetworkProtocolHandler, NetworkConfiguration, NonReservedPeerMode};
use error::NetworkError;
use host::{Host, NetworkContext, NetworkIoMessage, ProtocolId};
use stats::NetworkStats;
use io::*;
use parking_lot::RwLock;
use std::sync::Arc;
use ansi_term::Colour;
struct HostHandler {
public_url: RwLock<Option<String>>
}
impl IoHandler<NetworkIoMessage> for HostHandler {
fn message(&self, _io: &IoContext<NetworkIoMessage>, message: &NetworkIoMessage) {
if let NetworkIoMessage::NetworkStarted(ref public_url) = *message {
let mut url = self.public_url.write();
if url.as_ref().map_or(true, |uref| uref!= public_url) {
info!(target: "network", "Public node URL: {}", Colour::White.bold().paint(public_url.as_ref()));
}
*url = Some(public_url.to_owned());
}
}
}
/// IO Service with networking
/// `Message` defines a notification data type.
pub struct NetworkService {
io_service: IoService<NetworkIoMessage>,
host_info: String,
host: RwLock<Option<Arc<Host>>>,
stats: Arc<NetworkStats>,
panic_handler: Arc<PanicHandler>,
host_handler: Arc<HostHandler>,
config: NetworkConfiguration,
}
impl NetworkService {
/// Starts IO event loop
pub fn new(config: NetworkConfiguration) -> Result<NetworkService, NetworkError> {
let host_handler = Arc::new(HostHandler { public_url: RwLock::new(None) });
let panic_handler = PanicHandler::new_in_arc();
let io_service = try!(IoService::<NetworkIoMessage>::start());
panic_handler.forward_from(&io_service);
let stats = Arc::new(NetworkStats::new());
let host_info = Host::client_version();
Ok(NetworkService {
io_service: io_service,
host_info: host_info,
stats: stats,
panic_handler: panic_handler,
host: RwLock::new(None),
config: config,
host_handler: host_handler,
})
}
/// Regiter a new protocol handler with the event loop.
pub fn register_protocol(&self, handler: Arc<NetworkProtocolHandler + Send + Sync>, protocol: ProtocolId, packet_count: u8, versions: &[u8]) -> Result<(), NetworkError> {
try!(self.io_service.send_message(NetworkIoMessage::AddHandler {
handler: handler,
protocol: protocol,
versions: versions.to_vec(),
packet_count: packet_count,
}));
Ok(())
}
/// Returns host identifier string as advertised to other peers
pub fn host_info(&self) -> String {
self.host_info.clone()
}
/// Returns underlying io service.
pub fn io(&self) -> &IoService<NetworkIoMessage> {
&self.io_service
}
/// Returns network statistics.
pub fn stats(&self) -> &NetworkStats {
&self.stats
}
/// Returns network configuration.
pub fn config(&self) -> &NetworkConfiguration {
&self.config
}
/// Returns external url if available.
pub fn
|
(&self) -> Option<String> {
let host = self.host.read();
host.as_ref().and_then(|h| h.external_url())
}
/// Returns external url if available.
pub fn local_url(&self) -> Option<String> {
let host = self.host.read();
host.as_ref().map(|h| h.local_url())
}
/// Start network IO
pub fn start(&self) -> Result<(), NetworkError> {
let mut host = self.host.write();
if host.is_none() {
let h = Arc::new(try!(Host::new(self.config.clone(), self.stats.clone())));
try!(self.io_service.register_handler(h.clone()));
*host = Some(h);
}
if self.host_handler.public_url.read().is_none() {
try!(self.io_service.register_handler(self.host_handler.clone()));
}
Ok(())
}
/// Stop network IO
pub fn stop(&self) -> Result<(), NetworkError> {
let mut host = self.host.write();
if let Some(ref host) = *host {
let io = IoContext::new(self.io_service.channel(), 0); //TODO: take token id from host
try!(host.stop(&io));
}
*host = None;
Ok(())
}
/// Try to add a reserved peer.
pub fn add_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> {
let host = self.host.read();
if let Some(ref host) = *host {
host.add_reserved_node(peer)
} else {
Ok(())
}
}
/// Try to remove a reserved peer.
pub fn remove_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> {
let host = self.host.read();
if let Some(ref host) = *host {
host.remove_reserved_node(peer)
} else {
Ok(())
}
}
/// Set the non-reserved peer mode.
pub fn set_non_reserved_mode(&self, mode: NonReservedPeerMode) {
let host = self.host.read();
if let Some(ref host) = *host {
let io_ctxt = IoContext::new(self.io_service.channel(), 0);
host.set_non_reserved_mode(mode, &io_ctxt);
}
}
/// Executes action in the network context
pub fn with_context<F>(&self, protocol: ProtocolId, action: F) where F: Fn(&NetworkContext) {
let io = IoContext::new(self.io_service.channel(), 0);
let host = self.host.read();
if let Some(ref host) = host.as_ref() {
host.with_context(protocol, &io, action);
};
}
/// Evaluates function in the network context
pub fn with_context_eval<F, T>(&self, protocol: ProtocolId, action: F) -> Option<T> where F: Fn(&NetworkContext) -> T {
let io = IoContext::new(self.io_service.channel(), 0);
let host = self.host.read();
host.as_ref().map(|ref host| host.with_context_eval(protocol, &io, action))
}
}
impl MayPanic for NetworkService {
fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
self.panic_handler.on_panic(closure);
}
}
|
external_url
|
identifier_name
|
service.rs
|
// Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
use {NetworkProtocolHandler, NetworkConfiguration, NonReservedPeerMode};
use error::NetworkError;
use host::{Host, NetworkContext, NetworkIoMessage, ProtocolId};
use stats::NetworkStats;
use io::*;
use parking_lot::RwLock;
use std::sync::Arc;
use ansi_term::Colour;
struct HostHandler {
public_url: RwLock<Option<String>>
}
impl IoHandler<NetworkIoMessage> for HostHandler {
fn message(&self, _io: &IoContext<NetworkIoMessage>, message: &NetworkIoMessage) {
if let NetworkIoMessage::NetworkStarted(ref public_url) = *message {
let mut url = self.public_url.write();
if url.as_ref().map_or(true, |uref| uref!= public_url) {
info!(target: "network", "Public node URL: {}", Colour::White.bold().paint(public_url.as_ref()));
}
*url = Some(public_url.to_owned());
}
}
}
/// IO Service with networking
/// `Message` defines a notification data type.
pub struct NetworkService {
io_service: IoService<NetworkIoMessage>,
host_info: String,
host: RwLock<Option<Arc<Host>>>,
stats: Arc<NetworkStats>,
panic_handler: Arc<PanicHandler>,
host_handler: Arc<HostHandler>,
config: NetworkConfiguration,
}
impl NetworkService {
/// Starts IO event loop
pub fn new(config: NetworkConfiguration) -> Result<NetworkService, NetworkError> {
let host_handler = Arc::new(HostHandler { public_url: RwLock::new(None) });
let panic_handler = PanicHandler::new_in_arc();
let io_service = try!(IoService::<NetworkIoMessage>::start());
panic_handler.forward_from(&io_service);
let stats = Arc::new(NetworkStats::new());
let host_info = Host::client_version();
Ok(NetworkService {
io_service: io_service,
host_info: host_info,
stats: stats,
panic_handler: panic_handler,
host: RwLock::new(None),
config: config,
host_handler: host_handler,
})
}
/// Regiter a new protocol handler with the event loop.
pub fn register_protocol(&self, handler: Arc<NetworkProtocolHandler + Send + Sync>, protocol: ProtocolId, packet_count: u8, versions: &[u8]) -> Result<(), NetworkError> {
try!(self.io_service.send_message(NetworkIoMessage::AddHandler {
handler: handler,
protocol: protocol,
versions: versions.to_vec(),
packet_count: packet_count,
}));
Ok(())
}
/// Returns host identifier string as advertised to other peers
pub fn host_info(&self) -> String {
self.host_info.clone()
}
/// Returns underlying io service.
pub fn io(&self) -> &IoService<NetworkIoMessage> {
&self.io_service
}
/// Returns network statistics.
pub fn stats(&self) -> &NetworkStats {
&self.stats
}
/// Returns network configuration.
pub fn config(&self) -> &NetworkConfiguration {
&self.config
}
/// Returns external url if available.
pub fn external_url(&self) -> Option<String> {
let host = self.host.read();
host.as_ref().and_then(|h| h.external_url())
}
/// Returns external url if available.
pub fn local_url(&self) -> Option<String> {
let host = self.host.read();
host.as_ref().map(|h| h.local_url())
}
/// Start network IO
pub fn start(&self) -> Result<(), NetworkError> {
let mut host = self.host.write();
if host.is_none() {
let h = Arc::new(try!(Host::new(self.config.clone(), self.stats.clone())));
try!(self.io_service.register_handler(h.clone()));
*host = Some(h);
}
if self.host_handler.public_url.read().is_none() {
try!(self.io_service.register_handler(self.host_handler.clone()));
}
Ok(())
}
/// Stop network IO
pub fn stop(&self) -> Result<(), NetworkError> {
let mut host = self.host.write();
if let Some(ref host) = *host {
let io = IoContext::new(self.io_service.channel(), 0); //TODO: take token id from host
try!(host.stop(&io));
}
*host = None;
Ok(())
}
/// Try to add a reserved peer.
pub fn add_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> {
let host = self.host.read();
if let Some(ref host) = *host
|
else {
Ok(())
}
}
/// Try to remove a reserved peer.
pub fn remove_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> {
let host = self.host.read();
if let Some(ref host) = *host {
host.remove_reserved_node(peer)
} else {
Ok(())
}
}
/// Set the non-reserved peer mode.
pub fn set_non_reserved_mode(&self, mode: NonReservedPeerMode) {
let host = self.host.read();
if let Some(ref host) = *host {
let io_ctxt = IoContext::new(self.io_service.channel(), 0);
host.set_non_reserved_mode(mode, &io_ctxt);
}
}
/// Executes action in the network context
pub fn with_context<F>(&self, protocol: ProtocolId, action: F) where F: Fn(&NetworkContext) {
let io = IoContext::new(self.io_service.channel(), 0);
let host = self.host.read();
if let Some(ref host) = host.as_ref() {
host.with_context(protocol, &io, action);
};
}
/// Evaluates function in the network context
pub fn with_context_eval<F, T>(&self, protocol: ProtocolId, action: F) -> Option<T> where F: Fn(&NetworkContext) -> T {
let io = IoContext::new(self.io_service.channel(), 0);
let host = self.host.read();
host.as_ref().map(|ref host| host.with_context_eval(protocol, &io, action))
}
}
impl MayPanic for NetworkService {
fn on_panic<F>(&self, closure: F) where F: OnPanicListener {
self.panic_handler.on_panic(closure);
}
}
|
{
host.add_reserved_node(peer)
}
|
conditional_block
|
htmllielement.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::HTMLLIElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::document::AbstractDocument;
use dom::element::HTMLLIElementTypeId;
use dom::htmlelement::HTMLElement;
use dom::node::{AbstractNode, Node};
pub struct HTMLLIElement {
htmlelement: HTMLElement,
}
impl HTMLLIElement {
pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLLIElement {
HTMLLIElement {
htmlelement: HTMLElement::new_inherited(HTMLLIElementTypeId, localName, document)
}
}
pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode {
let element = HTMLLIElement::new_inherited(localName, document);
Node::reflect_node(@mut element, document, HTMLLIElementBinding::Wrap)
}
}
impl HTMLLIElement {
pub fn Value(&self) -> i32 {
0
}
pub fn SetValue(&mut self, _value: i32) -> ErrorResult {
Ok(())
}
pub fn Type(&self) -> DOMString
|
pub fn SetType(&mut self, _type: DOMString) -> ErrorResult {
Ok(())
}
}
|
{
~""
}
|
identifier_body
|
htmllielement.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::HTMLLIElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::document::AbstractDocument;
use dom::element::HTMLLIElementTypeId;
use dom::htmlelement::HTMLElement;
use dom::node::{AbstractNode, Node};
pub struct HTMLLIElement {
htmlelement: HTMLElement,
}
impl HTMLLIElement {
pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLLIElement {
HTMLLIElement {
htmlelement: HTMLElement::new_inherited(HTMLLIElementTypeId, localName, document)
}
}
pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode {
let element = HTMLLIElement::new_inherited(localName, document);
Node::reflect_node(@mut element, document, HTMLLIElementBinding::Wrap)
}
}
impl HTMLLIElement {
pub fn Value(&self) -> i32 {
0
}
|
}
pub fn Type(&self) -> DOMString {
~""
}
pub fn SetType(&mut self, _type: DOMString) -> ErrorResult {
Ok(())
}
}
|
pub fn SetValue(&mut self, _value: i32) -> ErrorResult {
Ok(())
|
random_line_split
|
htmllielement.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::HTMLLIElementBinding;
use dom::bindings::utils::{DOMString, ErrorResult};
use dom::document::AbstractDocument;
use dom::element::HTMLLIElementTypeId;
use dom::htmlelement::HTMLElement;
use dom::node::{AbstractNode, Node};
pub struct HTMLLIElement {
htmlelement: HTMLElement,
}
impl HTMLLIElement {
pub fn new_inherited(localName: ~str, document: AbstractDocument) -> HTMLLIElement {
HTMLLIElement {
htmlelement: HTMLElement::new_inherited(HTMLLIElementTypeId, localName, document)
}
}
pub fn new(localName: ~str, document: AbstractDocument) -> AbstractNode {
let element = HTMLLIElement::new_inherited(localName, document);
Node::reflect_node(@mut element, document, HTMLLIElementBinding::Wrap)
}
}
impl HTMLLIElement {
pub fn Value(&self) -> i32 {
0
}
pub fn SetValue(&mut self, _value: i32) -> ErrorResult {
Ok(())
}
pub fn Type(&self) -> DOMString {
~""
}
pub fn
|
(&mut self, _type: DOMString) -> ErrorResult {
Ok(())
}
}
|
SetType
|
identifier_name
|
hello2.rs
|
//! # Basic Sample
//!
//! This sample demonstrates how to create a toplevel `window`, set its title, size and position, how to add a `button` to this `window` and how to connect signals with actions.
#![crate_type = "bin"]
extern crate gtk;
use gtk::prelude::*;
fn main()
|
window.add(&button);
window.show_all();
gtk::main();
}
|
{
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let window = gtk::Window::new(gtk::WindowType::Toplevel);
window.set_title("First GTK+ Program");
window.set_border_width(10);
window.set_position(gtk::WindowPosition::Center);
window.set_default_size(350, 70);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Click me!");
|
identifier_body
|
hello2.rs
|
//! # Basic Sample
//!
//! This sample demonstrates how to create a toplevel `window`, set its title, size and position, how to add a `button` to this `window` and how to connect signals with actions.
#![crate_type = "bin"]
extern crate gtk;
use gtk::prelude::*;
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let window = gtk::Window::new(gtk::WindowType::Toplevel);
window.set_title("First GTK+ Program");
window.set_border_width(10);
window.set_position(gtk::WindowPosition::Center);
window.set_default_size(350, 70);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Click me!");
window.add(&button);
window.show_all();
|
}
|
gtk::main();
|
random_line_split
|
hello2.rs
|
//! # Basic Sample
//!
//! This sample demonstrates how to create a toplevel `window`, set its title, size and position, how to add a `button` to this `window` and how to connect signals with actions.
#![crate_type = "bin"]
extern crate gtk;
use gtk::prelude::*;
fn
|
() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let window = gtk::Window::new(gtk::WindowType::Toplevel);
window.set_title("First GTK+ Program");
window.set_border_width(10);
window.set_position(gtk::WindowPosition::Center);
window.set_default_size(350, 70);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Click me!");
window.add(&button);
window.show_all();
gtk::main();
}
|
main
|
identifier_name
|
hello2.rs
|
//! # Basic Sample
//!
//! This sample demonstrates how to create a toplevel `window`, set its title, size and position, how to add a `button` to this `window` and how to connect signals with actions.
#![crate_type = "bin"]
extern crate gtk;
use gtk::prelude::*;
fn main() {
if gtk::init().is_err()
|
let window = gtk::Window::new(gtk::WindowType::Toplevel);
window.set_title("First GTK+ Program");
window.set_border_width(10);
window.set_position(gtk::WindowPosition::Center);
window.set_default_size(350, 70);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
let button = gtk::Button::new_with_label("Click me!");
window.add(&button);
window.show_all();
gtk::main();
}
|
{
println!("Failed to initialize GTK.");
return;
}
|
conditional_block
|
vic_memory.rs
|
// This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use zinc64_core::{Ram, Rom, Shared, SharedCell};
pub struct VicMemory {
base_address: SharedCell<u16>,
charset: Shared<Rom>,
ram: Shared<Ram>,
}
impl VicMemory {
pub fn new(base_address: SharedCell<u16>, charset: Shared<Rom>, ram: Shared<Ram>) -> VicMemory
|
pub fn read(&self, address: u16) -> u8 {
let full_address = self.base_address.get() | address;
let zone = full_address >> 12;
match zone {
0x01 => self.charset.borrow().read(full_address - 0x1000),
0x09 => self.charset.borrow().read(full_address - 0x9000),
_ => self.ram.borrow().read(full_address),
}
}
}
|
{
VicMemory {
base_address,
charset,
ram,
}
}
|
identifier_body
|
vic_memory.rs
|
// This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use zinc64_core::{Ram, Rom, Shared, SharedCell};
pub struct VicMemory {
base_address: SharedCell<u16>,
charset: Shared<Rom>,
ram: Shared<Ram>,
}
impl VicMemory {
pub fn new(base_address: SharedCell<u16>, charset: Shared<Rom>, ram: Shared<Ram>) -> VicMemory {
VicMemory {
base_address,
charset,
ram,
}
}
pub fn read(&self, address: u16) -> u8 {
let full_address = self.base_address.get() | address;
let zone = full_address >> 12;
match zone {
0x01 => self.charset.borrow().read(full_address - 0x1000),
0x09 => self.charset.borrow().read(full_address - 0x9000),
_ => self.ram.borrow().read(full_address),
|
}
}
}
|
random_line_split
|
|
vic_memory.rs
|
// This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
use zinc64_core::{Ram, Rom, Shared, SharedCell};
pub struct VicMemory {
base_address: SharedCell<u16>,
charset: Shared<Rom>,
ram: Shared<Ram>,
}
impl VicMemory {
pub fn
|
(base_address: SharedCell<u16>, charset: Shared<Rom>, ram: Shared<Ram>) -> VicMemory {
VicMemory {
base_address,
charset,
ram,
}
}
pub fn read(&self, address: u16) -> u8 {
let full_address = self.base_address.get() | address;
let zone = full_address >> 12;
match zone {
0x01 => self.charset.borrow().read(full_address - 0x1000),
0x09 => self.charset.borrow().read(full_address - 0x9000),
_ => self.ram.borrow().read(full_address),
}
}
}
|
new
|
identifier_name
|
universe.rs
|
extern crate rand;
use std::vec::Vec;
use celestial::bodies::{Star, Planet};
use celestial::starsystem::{OrbitData, StarSystem};
pub struct Universe {
systems: Vec<StarSystem>
}
impl Universe {
pub fn generate() -> Universe {
let mut u = Universe{
systems: vec![]
};
// generate x stars
for i in 1..100 {
let mut s = Star::new();
// generate random number of planets
let r = rand::random::<u16>() % 10;
let mut ps = vec![];
for j in 1..r {
let p = Planet::generate_for(&s);
let o = OrbitData::generate_for(&s, &p);
ps.push((p,o));
}
let mut sys = StarSystem::new(s);
for (p, o) in ps {
sys.getRootOrbit().addBody(p,o);
}
u.systems.push(sys);
}
// return Universe
u
}
pub fn numSystems(&self) -> usize {
self.systems.len()
}
pub fn getSystem(&mut self, i: usize) -> &mut StarSystem {
|
}
|
self.systems.get_mut(i).unwrap()
}
|
random_line_split
|
universe.rs
|
extern crate rand;
use std::vec::Vec;
use celestial::bodies::{Star, Planet};
use celestial::starsystem::{OrbitData, StarSystem};
pub struct Universe {
systems: Vec<StarSystem>
}
impl Universe {
pub fn generate() -> Universe {
let mut u = Universe{
systems: vec![]
};
// generate x stars
for i in 1..100 {
let mut s = Star::new();
// generate random number of planets
let r = rand::random::<u16>() % 10;
let mut ps = vec![];
for j in 1..r {
let p = Planet::generate_for(&s);
let o = OrbitData::generate_for(&s, &p);
ps.push((p,o));
}
let mut sys = StarSystem::new(s);
for (p, o) in ps {
sys.getRootOrbit().addBody(p,o);
}
u.systems.push(sys);
}
// return Universe
u
}
pub fn numSystems(&self) -> usize
|
pub fn getSystem(&mut self, i: usize) -> &mut StarSystem {
self.systems.get_mut(i).unwrap()
}
}
|
{
self.systems.len()
}
|
identifier_body
|
universe.rs
|
extern crate rand;
use std::vec::Vec;
use celestial::bodies::{Star, Planet};
use celestial::starsystem::{OrbitData, StarSystem};
pub struct Universe {
systems: Vec<StarSystem>
}
impl Universe {
pub fn generate() -> Universe {
let mut u = Universe{
systems: vec![]
};
// generate x stars
for i in 1..100 {
let mut s = Star::new();
// generate random number of planets
let r = rand::random::<u16>() % 10;
let mut ps = vec![];
for j in 1..r {
let p = Planet::generate_for(&s);
let o = OrbitData::generate_for(&s, &p);
ps.push((p,o));
}
let mut sys = StarSystem::new(s);
for (p, o) in ps {
sys.getRootOrbit().addBody(p,o);
}
u.systems.push(sys);
}
// return Universe
u
}
pub fn
|
(&self) -> usize {
self.systems.len()
}
pub fn getSystem(&mut self, i: usize) -> &mut StarSystem {
self.systems.get_mut(i).unwrap()
}
}
|
numSystems
|
identifier_name
|
p034.rs
|
//! [Problem 34](https://projecteuler.net/problem=34) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
fn compute() -> u32 {
let mut facts: [u32; 10] = [ 0; 10 ];
facts[0] = 1;
for i in (1.. facts.len()) {
facts[i] = facts[i - 1] * (i as u32);
}
let mut answer = 0;
for n in (0.. (facts[9].to_string().len() as u32) * facts[9]) {
let mut itr = n;
let mut sum = 0;
while itr > 0 {
sum += facts[(itr % 10) as usize];
itr /= 10;
}
if sum == n {
answer += sum;
}
}
answer - 1 - 2
}
fn solve() -> String
|
problem!("40730", solve);
|
{
compute().to_string()
}
|
identifier_body
|
p034.rs
|
//! [Problem 34](https://projecteuler.net/problem=34) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
fn compute() -> u32 {
let mut facts: [u32; 10] = [ 0; 10 ];
facts[0] = 1;
for i in (1.. facts.len()) {
facts[i] = facts[i - 1] * (i as u32);
}
let mut answer = 0;
for n in (0.. (facts[9].to_string().len() as u32) * facts[9]) {
let mut itr = n;
let mut sum = 0;
while itr > 0 {
sum += facts[(itr % 10) as usize];
itr /= 10;
}
if sum == n {
answer += sum;
}
}
answer - 1 - 2
}
fn
|
() -> String {
compute().to_string()
}
problem!("40730", solve);
|
solve
|
identifier_name
|
p034.rs
|
//! [Problem 34](https://projecteuler.net/problem=34) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
fn compute() -> u32 {
let mut facts: [u32; 10] = [ 0; 10 ];
facts[0] = 1;
for i in (1.. facts.len()) {
facts[i] = facts[i - 1] * (i as u32);
}
let mut answer = 0;
for n in (0.. (facts[9].to_string().len() as u32) * facts[9]) {
let mut itr = n;
let mut sum = 0;
while itr > 0 {
sum += facts[(itr % 10) as usize];
itr /= 10;
}
if sum == n {
answer += sum;
}
}
answer - 1 - 2
}
|
problem!("40730", solve);
|
fn solve() -> String {
compute().to_string()
}
|
random_line_split
|
p034.rs
|
//! [Problem 34](https://projecteuler.net/problem=34) solver.
#![warn(bad_style,
unused, unused_extern_crates, unused_import_braces,
unused_qualifications, unused_results)]
#[macro_use(problem)] extern crate common;
fn compute() -> u32 {
let mut facts: [u32; 10] = [ 0; 10 ];
facts[0] = 1;
for i in (1.. facts.len()) {
facts[i] = facts[i - 1] * (i as u32);
}
let mut answer = 0;
for n in (0.. (facts[9].to_string().len() as u32) * facts[9]) {
let mut itr = n;
let mut sum = 0;
while itr > 0 {
sum += facts[(itr % 10) as usize];
itr /= 10;
}
if sum == n
|
}
answer - 1 - 2
}
fn solve() -> String {
compute().to_string()
}
problem!("40730", solve);
|
{
answer += sum;
}
|
conditional_block
|
io.rs
|
use std::os::raw::{c_char, c_void};
#[repr(C)]
pub enum LoadState {
Ok,
Fail,
Converted,
Truncated,
OutOfData,
}
#[repr(C)]
pub struct
|
{
pub priv_data: *mut c_void,
pub write_int: fn(priv_data: *mut c_void, data: i64),
pub write_double: fn(priv_data: *mut c_void, data: f64),
pub write_string: fn(priv_data: *mut c_void, data: *const c_char),
}
pub struct CPDLoadState {
pub priv_data: *mut c_void,
pub read_int: fn(priv_data: *mut c_void, dest: *mut i64) -> LoadState,
pub read_double: fn(priv_data: *mut c_void, dest: *mut f64) -> LoadState,
pub read_string: fn(priv_data: *mut c_void, dest: *mut c_char, max_len: i32) -> LoadState,
}
|
CPDSaveState
|
identifier_name
|
io.rs
|
use std::os::raw::{c_char, c_void};
|
Converted,
Truncated,
OutOfData,
}
#[repr(C)]
pub struct CPDSaveState {
pub priv_data: *mut c_void,
pub write_int: fn(priv_data: *mut c_void, data: i64),
pub write_double: fn(priv_data: *mut c_void, data: f64),
pub write_string: fn(priv_data: *mut c_void, data: *const c_char),
}
pub struct CPDLoadState {
pub priv_data: *mut c_void,
pub read_int: fn(priv_data: *mut c_void, dest: *mut i64) -> LoadState,
pub read_double: fn(priv_data: *mut c_void, dest: *mut f64) -> LoadState,
pub read_string: fn(priv_data: *mut c_void, dest: *mut c_char, max_len: i32) -> LoadState,
}
|
#[repr(C)]
pub enum LoadState {
Ok,
Fail,
|
random_line_split
|
kernels.rs
|
/*
* Copyright (C) 2013 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.
*/
#pragma version(1)
#pragma rs java_package_name(com.android.rs.typecheck)
#pragma rs_fp_relaxed
// Test initialized and uninitialized variables
char c1;
char c1i = 1;
char2 c2;
char2 c2i = {1, 2};
char3 c3;
char3 c3i = {1, 2, 3};
char4 c4;
char4 c4i = {1, 2, 3, 4};
uchar uc1;
uchar uc1i = 1;
uchar2 uc2;
uchar2 uc2i = {1, 2};
uchar3 uc3;
uchar3 uc3i = {1, 2, 3};
uchar4 uc4;
uchar4 uc4i = {1, 2, 3, 4};
short s1;
short s1i = 1;
short2 s2;
short2 s2i = {1, 2};
short3 s3;
short3 s3i = {1, 2, 3};
short4 s4;
short4 s4i = {1, 2, 3, 4};
ushort us1;
ushort us1i = 1;
ushort2 us2;
ushort2 us2i = {1, 2};
|
ushort3 us3i = {1, 2, 3};
ushort4 us4;
ushort4 us4i = {1, 2, 3, 4};
int i1;
int i1i = 1;
int2 i2;
int2 i2i = {1, 2};
int3 i3;
int3 i3i = {1, 2, 3};
int4 i4;
int4 i4i = {1, 2, 3, 4};
uint ui1;
uint ui1i = 1;
uint2 ui2;
uint2 ui2i = {1, 2};
uint3 ui3;
uint3 ui3i = {1, 2, 3};
uint4 ui4;
uint4 ui4i = {1, 2, 3, 4};
long l1;
long l1i = 1;
long2 l2;
long2 l2i = {1, 2};
long3 l3;
long3 l3i = {1, 2, 3};
long4 l4;
long4 l4i = {1, 2, 3, 4};
ulong ul1;
ulong ul1i = 1;
ulong2 ul2;
ulong2 ul2i = {1, 2};
ulong3 ul3;
ulong3 ul3i = {1, 2, 3};
ulong4 ul4;
ulong4 ul4i = {1, 2, 3, 4};
float f1;
float f1i = 3.141592265358979f;
float2 f2;
float2 f2i = {1.f, 2.f};
float3 f3;
float3 f3i = {1.f, 2.f, 3.f};
float4 f4;
float4 f4i = {1.f, 2.f, 3.f, 4.f};
double d1;
double d1i = 3.141592265358979;
double2 d2;
double2 d2i = {1, 2};
double3 d3;
double3 d3i = {1, 2, 3};
double4 d4;
double4 d4i = {1, 2, 3, 4};
void __attribute__((kernel)) test_BOOLEAN(bool in) {
}
void __attribute__((kernel)) test_I8(char in) {
}
void __attribute__((kernel)) test_U8(uchar in) {
}
void __attribute__((kernel)) test_I16(short in) {
}
void __attribute__((kernel)) test_U16(ushort in) {
}
void __attribute__((kernel)) test_I32(int in) {
}
void __attribute__((kernel)) test_U32(uint in) {
}
void __attribute__((kernel)) test_I64(long in) {
}
void __attribute__((kernel)) test_U64(ulong in) {
}
void __attribute__((kernel)) test_F32(float in) {
}
void __attribute__((kernel)) test_F64(double in) {
}
|
ushort3 us3;
|
random_line_split
|
messages.rs
|
//! Protocol messages
//!
//! All protocol messages are serialized by serde according to the bincode data format. For
//! transmission on the wire, `tokio_io::codec::length_delimited` is used to prepend protocol
//! messages by an additional length header, thereby creating frames. It is crucial to
//!
//! The main type `Message` and the types in its fields are dump containers, which are not
//! responsible for any protocol logic (except for syntactic validation including validation of
//! `PublicKey` and `SecretKey` fields). Consequently, all fields of `Message` and all fields of
//! its contained types such as `Header` and `Payload` are public.
pub use secp256k1::key::{PublicKey, SecretKey};
use ::{SessionId, PeerIndex, SymmetricKey, SequenceNum, Commitment};
use dc::xor::XorVec;
use dc::fp::Fp;
/// A protocol message
///
/// Protocol messages consist of a header and a payload.
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Message {
pub header: Header,
pub payload: Payload,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Header {
pub session_id: SessionId, // just for consistency checks
pub peer_index: PeerIndex,
pub sequence_num: SequenceNum, // just for consistency checks
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum
|
{
KeyExchange(KeyExchange),
DcExponential(DcExponential),
DcMain(DcMain),
Blame(Blame),
Confirm(Confirm),
Reveal(Reveal),
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct KeyExchange {
pub ke_pk: PublicKey,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct DcExponential {
pub commitment: Commitment,
pub dc_exp: Vec<Fp>,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct DcMain {
pub ok: bool,
// TODO This is not an efficient serialization.
pub dc_xor: XorVec<XorVec<u8>>,
pub ke_pk: PublicKey,
pub extension: Extension,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum Extension {
None,
DcAddSecp256k1Scalar(/* TODO */),
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Blame {
pub ke_sk: SecretKey,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Confirm {
pub data: Vec<u8>,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Reveal {
pub keys: Vec<(PeerIndex, SymmetricKey)>,
}
#[cfg(test)]
mod tests {
use secp256k1::key::SecretKey;
use bincode;
use super::*;
#[test]
fn roundtrip_keyexchange() {
let slice: [u8; 32] = [0x4f; 32];
let sk = SecretKey::from_slice(&::SECP256K1, &slice).unwrap();
let ke_pk = PublicKey::from_secret_key(&::SECP256K1, &sk).unwrap();
assert!(ke_pk.is_valid());
let payload = Payload::KeyExchange(KeyExchange {
ke_pk: ke_pk,
});
roundtrip_serde_bincode(payload);
}
#[cfg(test)]
fn roundtrip_serde_bincode(payload1: Payload) {
let ser = bincode::serialize(&payload1, bincode::Infinite).unwrap();
let payload2 : Payload = bincode::deserialize(&ser).unwrap();
assert_eq!(payload1, payload2);
}
}
|
Payload
|
identifier_name
|
messages.rs
|
//! Protocol messages
//!
//! All protocol messages are serialized by serde according to the bincode data format. For
//! transmission on the wire, `tokio_io::codec::length_delimited` is used to prepend protocol
//! messages by an additional length header, thereby creating frames. It is crucial to
|
//! its contained types such as `Header` and `Payload` are public.
pub use secp256k1::key::{PublicKey, SecretKey};
use ::{SessionId, PeerIndex, SymmetricKey, SequenceNum, Commitment};
use dc::xor::XorVec;
use dc::fp::Fp;
/// A protocol message
///
/// Protocol messages consist of a header and a payload.
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Message {
pub header: Header,
pub payload: Payload,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Header {
pub session_id: SessionId, // just for consistency checks
pub peer_index: PeerIndex,
pub sequence_num: SequenceNum, // just for consistency checks
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum Payload {
KeyExchange(KeyExchange),
DcExponential(DcExponential),
DcMain(DcMain),
Blame(Blame),
Confirm(Confirm),
Reveal(Reveal),
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct KeyExchange {
pub ke_pk: PublicKey,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct DcExponential {
pub commitment: Commitment,
pub dc_exp: Vec<Fp>,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct DcMain {
pub ok: bool,
// TODO This is not an efficient serialization.
pub dc_xor: XorVec<XorVec<u8>>,
pub ke_pk: PublicKey,
pub extension: Extension,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub enum Extension {
None,
DcAddSecp256k1Scalar(/* TODO */),
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Blame {
pub ke_sk: SecretKey,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Confirm {
pub data: Vec<u8>,
}
#[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)]
pub struct Reveal {
pub keys: Vec<(PeerIndex, SymmetricKey)>,
}
#[cfg(test)]
mod tests {
use secp256k1::key::SecretKey;
use bincode;
use super::*;
#[test]
fn roundtrip_keyexchange() {
let slice: [u8; 32] = [0x4f; 32];
let sk = SecretKey::from_slice(&::SECP256K1, &slice).unwrap();
let ke_pk = PublicKey::from_secret_key(&::SECP256K1, &sk).unwrap();
assert!(ke_pk.is_valid());
let payload = Payload::KeyExchange(KeyExchange {
ke_pk: ke_pk,
});
roundtrip_serde_bincode(payload);
}
#[cfg(test)]
fn roundtrip_serde_bincode(payload1: Payload) {
let ser = bincode::serialize(&payload1, bincode::Infinite).unwrap();
let payload2 : Payload = bincode::deserialize(&ser).unwrap();
assert_eq!(payload1, payload2);
}
}
|
//!
//! The main type `Message` and the types in its fields are dump containers, which are not
//! responsible for any protocol logic (except for syntactic validation including validation of
//! `PublicKey` and `SecretKey` fields). Consequently, all fields of `Message` and all fields of
|
random_line_split
|
issue-5708.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.
/*
# ICE when returning struct with reference to trait
A function which takes a reference to a trait and returns a
struct with that reference results in an ICE.
This does not occur with concrete types, only with references
to traits.
*/
// original
trait Inner {
fn print(&self);
}
impl Inner for int {
fn print(&self) { print!("Inner: {}\n", *self); }
}
struct Outer<'a> {
inner: &'a Inner+'a
}
impl<'a> Outer<'a> {
fn new(inner: &Inner) -> Outer {
Outer {
inner: inner
}
}
}
pub fn main() {
let inner = 5i;
let outer = Outer::new(&inner as &Inner);
outer.inner.print();
}
// minimal
trait MyTrait<T> { }
pub struct MyContainer<'a, T> {
foos: Vec<&'a MyTrait<T>+'a>,
}
impl<'a, T> MyContainer<'a, T> {
|
}
|
pub fn add (&mut self, foo: &'a MyTrait<T>) {
self.foos.push(foo);
}
|
random_line_split
|
issue-5708.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.
/*
# ICE when returning struct with reference to trait
A function which takes a reference to a trait and returns a
struct with that reference results in an ICE.
This does not occur with concrete types, only with references
to traits.
*/
// original
trait Inner {
fn print(&self);
}
impl Inner for int {
fn print(&self) { print!("Inner: {}\n", *self); }
}
struct Outer<'a> {
inner: &'a Inner+'a
}
impl<'a> Outer<'a> {
fn new(inner: &Inner) -> Outer {
Outer {
inner: inner
}
}
}
pub fn
|
() {
let inner = 5i;
let outer = Outer::new(&inner as &Inner);
outer.inner.print();
}
// minimal
trait MyTrait<T> { }
pub struct MyContainer<'a, T> {
foos: Vec<&'a MyTrait<T>+'a>,
}
impl<'a, T> MyContainer<'a, T> {
pub fn add (&mut self, foo: &'a MyTrait<T>) {
self.foos.push(foo);
}
}
|
main
|
identifier_name
|
msub.rs
|
/*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::any::Any;
use super::super::{Mmultiscripts, Mmultiscript, Element, ElementType, InheritedProps, StyleProps,
Family, InstanceId, ScriptsAndLimits, Presentation, PresentationPrivate, Mempty,
SpecifiedPresentationProps};
use ::platform::Context;
use ::layout::{Layout};
pub struct Msub {
multiscript: Mmultiscripts
}
impl Msub {
pub fn new(base: Box<Element>, subscript: Box<Element>) -> Msub {
let mut multiscript = Mmultiscripts::new(base);
multiscript.with_postscript(Mmultiscript {
subscript,
superscript: Box::new(Mempty::new()),
});
Msub {
multiscript,
}
}
pub fn with_base<'a>(&'a mut self, base: Box<Element>) -> &'a mut Msub {
self.multiscript.with_base(base);
self
}
pub fn base(&self) -> &Box<Element> {
self.multiscript.base()
}
}
impl Element for Msub {
fn layout<'a>(&self, context: &Context, family: &Family<'a>, inherited: &InheritedProps,
style: &Option<&StyleProps>) -> Box<Layout>
|
fn type_info(&self) -> ElementType {
ElementType::ScriptsAndLimits(ScriptsAndLimits::Msub)
}
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
fn instance_id(&self) -> &InstanceId {
self.multiscript.instance_id()
}
}
impl PresentationPrivate<Mmultiscripts> for Msub {
fn get_specified_presentation_props(&self) -> &SpecifiedPresentationProps {
self.multiscript.get_specified_presentation_props()
}
fn get_specified_presentation_props_mut(&mut self) -> &mut SpecifiedPresentationProps {
self.multiscript.get_specified_presentation_props_mut()
}
}
impl Presentation<Mmultiscripts> for Msub {}
#[cfg(test)]
mod test {
use super::*;
use ::elements::*;
use ::test::skia::Snapshot;
#[test]
fn it_works() {
let snapshot = Snapshot::default();
let msub = Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Mi::new(String::from("i")))
);
snapshot.snap_element(&msub, "msub_simple");
let msub = Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Mi::new(String::from("i")))
))
))
))
);
snapshot.snap_element(&msub, "msub_nested");
}
}
|
{
self.multiscript.layout(context, family, inherited, style)
}
|
identifier_body
|
msub.rs
|
/*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::any::Any;
use super::super::{Mmultiscripts, Mmultiscript, Element, ElementType, InheritedProps, StyleProps,
Family, InstanceId, ScriptsAndLimits, Presentation, PresentationPrivate, Mempty,
SpecifiedPresentationProps};
use ::platform::Context;
use ::layout::{Layout};
pub struct Msub {
multiscript: Mmultiscripts
}
impl Msub {
pub fn new(base: Box<Element>, subscript: Box<Element>) -> Msub {
let mut multiscript = Mmultiscripts::new(base);
multiscript.with_postscript(Mmultiscript {
subscript,
superscript: Box::new(Mempty::new()),
});
Msub {
multiscript,
}
}
pub fn with_base<'a>(&'a mut self, base: Box<Element>) -> &'a mut Msub {
self.multiscript.with_base(base);
self
}
pub fn base(&self) -> &Box<Element> {
self.multiscript.base()
}
}
impl Element for Msub {
fn layout<'a>(&self, context: &Context, family: &Family<'a>, inherited: &InheritedProps,
style: &Option<&StyleProps>) -> Box<Layout> {
self.multiscript.layout(context, family, inherited, style)
}
fn type_info(&self) -> ElementType {
ElementType::ScriptsAndLimits(ScriptsAndLimits::Msub)
}
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
fn instance_id(&self) -> &InstanceId {
self.multiscript.instance_id()
}
}
impl PresentationPrivate<Mmultiscripts> for Msub {
fn get_specified_presentation_props(&self) -> &SpecifiedPresentationProps {
self.multiscript.get_specified_presentation_props()
}
fn get_specified_presentation_props_mut(&mut self) -> &mut SpecifiedPresentationProps {
self.multiscript.get_specified_presentation_props_mut()
}
}
impl Presentation<Mmultiscripts> for Msub {}
#[cfg(test)]
mod test {
use super::*;
use ::elements::*;
use ::test::skia::Snapshot;
#[test]
fn it_works() {
let snapshot = Snapshot::default();
let msub = Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Mi::new(String::from("i")))
);
snapshot.snap_element(&msub, "msub_simple");
let msub = Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Mi::new(String::from("i")))
))
))
))
|
);
snapshot.snap_element(&msub, "msub_nested");
}
}
|
random_line_split
|
|
msub.rs
|
/*
* Copyright 2017 Sreejith Krishnan R
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
use std::any::Any;
use super::super::{Mmultiscripts, Mmultiscript, Element, ElementType, InheritedProps, StyleProps,
Family, InstanceId, ScriptsAndLimits, Presentation, PresentationPrivate, Mempty,
SpecifiedPresentationProps};
use ::platform::Context;
use ::layout::{Layout};
pub struct Msub {
multiscript: Mmultiscripts
}
impl Msub {
pub fn
|
(base: Box<Element>, subscript: Box<Element>) -> Msub {
let mut multiscript = Mmultiscripts::new(base);
multiscript.with_postscript(Mmultiscript {
subscript,
superscript: Box::new(Mempty::new()),
});
Msub {
multiscript,
}
}
pub fn with_base<'a>(&'a mut self, base: Box<Element>) -> &'a mut Msub {
self.multiscript.with_base(base);
self
}
pub fn base(&self) -> &Box<Element> {
self.multiscript.base()
}
}
impl Element for Msub {
fn layout<'a>(&self, context: &Context, family: &Family<'a>, inherited: &InheritedProps,
style: &Option<&StyleProps>) -> Box<Layout> {
self.multiscript.layout(context, family, inherited, style)
}
fn type_info(&self) -> ElementType {
ElementType::ScriptsAndLimits(ScriptsAndLimits::Msub)
}
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
fn instance_id(&self) -> &InstanceId {
self.multiscript.instance_id()
}
}
impl PresentationPrivate<Mmultiscripts> for Msub {
fn get_specified_presentation_props(&self) -> &SpecifiedPresentationProps {
self.multiscript.get_specified_presentation_props()
}
fn get_specified_presentation_props_mut(&mut self) -> &mut SpecifiedPresentationProps {
self.multiscript.get_specified_presentation_props_mut()
}
}
impl Presentation<Mmultiscripts> for Msub {}
#[cfg(test)]
mod test {
use super::*;
use ::elements::*;
use ::test::skia::Snapshot;
#[test]
fn it_works() {
let snapshot = Snapshot::default();
let msub = Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Mi::new(String::from("i")))
);
snapshot.snap_element(&msub, "msub_simple");
let msub = Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Msub::new(
Box::new(Mi::new(String::from("a"))),
Box::new(Mi::new(String::from("i")))
))
))
))
);
snapshot.snap_element(&msub, "msub_nested");
}
}
|
new
|
identifier_name
|
user.rs
|
/*
* The user represents a structure that can receive data from or send data to a certain user that
* the program is currently connected to.
*/
use std::io::prelude::*;
use std::net::{TcpStream, SocketAddr};
use std::thread;
pub struct User {
stream: TcpStream,
}
impl User {
pub fn new(stream: TcpStream) -> User {
let user = User {
stream: stream,
};
let mut receive_stream = user.stream.try_clone().unwrap();
thread::spawn(move || {
User::receive_messages(&mut receive_stream);
});
user
}
fn receive_messages(stream: &mut TcpStream) {
loop {
let mut data = vec![0; 128];
let size = match stream.read(&mut data) {
Ok(size) => size,
Err(err) => {
println!("{:?} has been closed due to: {}", stream, err);
break
}
};
if size == 0 {
println!("{} disconnected.", stream.peer_addr().unwrap());
break
}
let message = String::from_utf8(data).unwrap();
println!("Message received from '{}':", stream.peer_addr().unwrap());
println!("{}", message);
}
drop(stream);
}
pub fn send_message(&mut self, msg: &str) -> Result<usize, String> {
let data = msg.as_bytes();
// TODO: This is a stupid workaround, because the io::error::Error type is private.
match self.stream.write(&data) {
Ok(size) => Ok(size),
Err(err) => Err(format!("{}", err))
}
}
pub fn remote_address(&self) -> SocketAddr {
self.stream.peer_addr().unwrap()
|
}
}
|
random_line_split
|
|
user.rs
|
/*
* The user represents a structure that can receive data from or send data to a certain user that
* the program is currently connected to.
*/
use std::io::prelude::*;
use std::net::{TcpStream, SocketAddr};
use std::thread;
pub struct User {
stream: TcpStream,
}
impl User {
pub fn new(stream: TcpStream) -> User
|
fn receive_messages(stream: &mut TcpStream) {
loop {
let mut data = vec![0; 128];
let size = match stream.read(&mut data) {
Ok(size) => size,
Err(err) => {
println!("{:?} has been closed due to: {}", stream, err);
break
}
};
if size == 0 {
println!("{} disconnected.", stream.peer_addr().unwrap());
break
}
let message = String::from_utf8(data).unwrap();
println!("Message received from '{}':", stream.peer_addr().unwrap());
println!("{}", message);
}
drop(stream);
}
pub fn send_message(&mut self, msg: &str) -> Result<usize, String> {
let data = msg.as_bytes();
// TODO: This is a stupid workaround, because the io::error::Error type is private.
match self.stream.write(&data) {
Ok(size) => Ok(size),
Err(err) => Err(format!("{}", err))
}
}
pub fn remote_address(&self) -> SocketAddr {
self.stream.peer_addr().unwrap()
}
}
|
{
let user = User {
stream: stream,
};
let mut receive_stream = user.stream.try_clone().unwrap();
thread::spawn(move || {
User::receive_messages(&mut receive_stream);
});
user
}
|
identifier_body
|
user.rs
|
/*
* The user represents a structure that can receive data from or send data to a certain user that
* the program is currently connected to.
*/
use std::io::prelude::*;
use std::net::{TcpStream, SocketAddr};
use std::thread;
pub struct User {
stream: TcpStream,
}
impl User {
pub fn new(stream: TcpStream) -> User {
let user = User {
stream: stream,
};
let mut receive_stream = user.stream.try_clone().unwrap();
thread::spawn(move || {
User::receive_messages(&mut receive_stream);
});
user
}
fn
|
(stream: &mut TcpStream) {
loop {
let mut data = vec![0; 128];
let size = match stream.read(&mut data) {
Ok(size) => size,
Err(err) => {
println!("{:?} has been closed due to: {}", stream, err);
break
}
};
if size == 0 {
println!("{} disconnected.", stream.peer_addr().unwrap());
break
}
let message = String::from_utf8(data).unwrap();
println!("Message received from '{}':", stream.peer_addr().unwrap());
println!("{}", message);
}
drop(stream);
}
pub fn send_message(&mut self, msg: &str) -> Result<usize, String> {
let data = msg.as_bytes();
// TODO: This is a stupid workaround, because the io::error::Error type is private.
match self.stream.write(&data) {
Ok(size) => Ok(size),
Err(err) => Err(format!("{}", err))
}
}
pub fn remote_address(&self) -> SocketAddr {
self.stream.peer_addr().unwrap()
}
}
|
receive_messages
|
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/. */
//! Servo's compiler plugin/macro crate
//!
//! Attributes this crate provides:
//!
//! - `#[derive(DenyPublicFields)]` : Forces all fields in a struct/enum to be private
//! - `#[derive(JSTraceable)]` : Auto-derives an implementation of `JSTraceable` for a struct in the script crate
//! - `#[must_root]` : Prevents data of the marked type from being used on the stack.
//! See the lints module for more details
//! - `#[dom_struct]` : Implies #[derive(JSTraceable, DenyPublicFields)]`, and `#[must_root]`.
//! Use this for structs that correspond to a DOM type
#![deny(unsafe_code)]
#![feature(plugin)]
#![feature(plugin_registrar)]
#![feature(rustc_private)]
#[macro_use]
extern crate rustc;
extern crate rustc_plugin;
extern crate syntax;
use rustc_plugin::Registry;
use syntax::feature_gate::AttributeType::Whitelisted;
mod unrooted_must_root;
/// Utilities for writing plugins
mod utils;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry)
|
{
reg.register_late_lint_pass(Box::new(unrooted_must_root::UnrootedPass::new()));
reg.register_attribute("allow_unrooted_interior".to_string(), Whitelisted);
reg.register_attribute("must_root".to_string(), Whitelisted);
}
|
identifier_body
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.