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
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/. */ // Make |cargo bench| work. #![cfg_attr(feature = "unstable", feature(test))] #[macro_use] extern crate bitflags; #[macro_use] extern crate cssparser; #[macro_use] extern crate log; #[macro_use] extern crate matches; extern crate fnv;
extern crate smallvec; pub mod attr; pub mod bloom; mod builder; pub mod context; pub mod matching; pub mod parser; #[cfg(test)] mod size_of_tests; #[cfg(any(test, feature = "gecko_like_types"))] pub mod gecko_like_types; pub mod sink; mod tree; pub mod visitor; pub use parser::{SelectorImpl, Parser, SelectorList}; pub use tree::Element;
extern crate phf; extern crate precomputed_hash; #[cfg(test)] #[macro_use] extern crate size_of_test; extern crate servo_arc;
random_line_split
maschine.rs
// maschine.rs: user-space drivers for native instruments USB HIDs // Copyright (C) 2015 William Light <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. use std::os::unix::io::RawFd; #[derive(Copy,Clone,Debug)] pub enum MaschineButton { Restart, StepLeft, StepRight, Grid, Play, Rec, Erase, Shift, Group, Browse, Sampling, NoteRepeat, Encoder, F1, F2, F3, Control, Nav, NavLeft, NavRight, Main, Scene, Pattern, PadMode, View, Duplicate, Select, Solo, Mute } pub trait Maschine { fn get_fd(&self) -> RawFd; fn get_pad_pressure(&self, pad_idx: usize) -> Result<f32, ()>; fn get_midi_note_base(&self) -> u8; fn set_midi_note_base(&mut self, base: u8); fn set_pad_light(&mut self, pad_idx: usize, color: u32, brightness: f32); fn set_button_light(&mut self, btn: MaschineButton, color: u32, brightness: f32); fn readable(&mut self, &mut dyn MaschineHandler); fn clear_screen(&mut self); fn write_lights(&mut self); } #[allow(unused_variables)] pub trait MaschineHandler { fn pad_pressed(&mut self, &mut dyn Maschine, pad_idx: usize, pressure: f32) {} fn pad_aftertouch(&mut self, &mut dyn Maschine, pad_idx: usize, pressure: f32) {} fn pad_released(&mut self, &mut dyn Maschine, pad_idx: usize) {} fn
(&mut self, &mut dyn Maschine, encoder_idx: usize, delta: i32) {} fn button_down(&mut self, &mut dyn Maschine, button: MaschineButton) {} fn button_up(&mut self, &mut dyn Maschine, button: MaschineButton) {} }
encoder_step
identifier_name
maschine.rs
// maschine.rs: user-space drivers for native instruments USB HIDs // Copyright (C) 2015 William Light <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public
use std::os::unix::io::RawFd; #[derive(Copy,Clone,Debug)] pub enum MaschineButton { Restart, StepLeft, StepRight, Grid, Play, Rec, Erase, Shift, Group, Browse, Sampling, NoteRepeat, Encoder, F1, F2, F3, Control, Nav, NavLeft, NavRight, Main, Scene, Pattern, PadMode, View, Duplicate, Select, Solo, Mute } pub trait Maschine { fn get_fd(&self) -> RawFd; fn get_pad_pressure(&self, pad_idx: usize) -> Result<f32, ()>; fn get_midi_note_base(&self) -> u8; fn set_midi_note_base(&mut self, base: u8); fn set_pad_light(&mut self, pad_idx: usize, color: u32, brightness: f32); fn set_button_light(&mut self, btn: MaschineButton, color: u32, brightness: f32); fn readable(&mut self, &mut dyn MaschineHandler); fn clear_screen(&mut self); fn write_lights(&mut self); } #[allow(unused_variables)] pub trait MaschineHandler { fn pad_pressed(&mut self, &mut dyn Maschine, pad_idx: usize, pressure: f32) {} fn pad_aftertouch(&mut self, &mut dyn Maschine, pad_idx: usize, pressure: f32) {} fn pad_released(&mut self, &mut dyn Maschine, pad_idx: usize) {} fn encoder_step(&mut self, &mut dyn Maschine, encoder_idx: usize, delta: i32) {} fn button_down(&mut self, &mut dyn Maschine, button: MaschineButton) {} fn button_up(&mut self, &mut dyn Maschine, button: MaschineButton) {} }
// License along with this program. If not, see // <http://www.gnu.org/licenses/>.
random_line_split
maschine.rs
// maschine.rs: user-space drivers for native instruments USB HIDs // Copyright (C) 2015 William Light <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program. If not, see // <http://www.gnu.org/licenses/>. use std::os::unix::io::RawFd; #[derive(Copy,Clone,Debug)] pub enum MaschineButton { Restart, StepLeft, StepRight, Grid, Play, Rec, Erase, Shift, Group, Browse, Sampling, NoteRepeat, Encoder, F1, F2, F3, Control, Nav, NavLeft, NavRight, Main, Scene, Pattern, PadMode, View, Duplicate, Select, Solo, Mute } pub trait Maschine { fn get_fd(&self) -> RawFd; fn get_pad_pressure(&self, pad_idx: usize) -> Result<f32, ()>; fn get_midi_note_base(&self) -> u8; fn set_midi_note_base(&mut self, base: u8); fn set_pad_light(&mut self, pad_idx: usize, color: u32, brightness: f32); fn set_button_light(&mut self, btn: MaschineButton, color: u32, brightness: f32); fn readable(&mut self, &mut dyn MaschineHandler); fn clear_screen(&mut self); fn write_lights(&mut self); } #[allow(unused_variables)] pub trait MaschineHandler { fn pad_pressed(&mut self, &mut dyn Maschine, pad_idx: usize, pressure: f32) {} fn pad_aftertouch(&mut self, &mut dyn Maschine, pad_idx: usize, pressure: f32)
fn pad_released(&mut self, &mut dyn Maschine, pad_idx: usize) {} fn encoder_step(&mut self, &mut dyn Maschine, encoder_idx: usize, delta: i32) {} fn button_down(&mut self, &mut dyn Maschine, button: MaschineButton) {} fn button_up(&mut self, &mut dyn Maschine, button: MaschineButton) {} }
{}
identifier_body
fpcs.rs
#[doc = "Register `FPCS` reader"] pub struct R(crate::R<FPCS_SPEC>); impl core::ops::Deref for R { type Target = crate::R<FPCS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<FPCS_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<FPCS_SPEC>) -> Self { R(reader) } } #[doc = "Register `FPCS` writer"] pub struct W(crate::W<FPCS_SPEC>); impl core::ops::Deref for W { type Target = crate::W<FPCS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<FPCS_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<FPCS_SPEC>) -> Self { W(writer) } } #[doc = "Field `PCMP` reader - Floating Prescaler Shadow Compare Value"] pub struct PCMP_R(crate::FieldReader<u8, u8>); impl PCMP_R { pub(crate) fn new(bits: u8) -> Self { PCMP_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PCMP_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target {
w: &'a mut W, } impl<'a> PCMP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits &!0x0f) | (value as u32 & 0x0f); self.w } } impl R { #[doc = "Bits 0:3 - Floating Prescaler Shadow Compare Value"] #[inline(always)] pub fn pcmp(&self) -> PCMP_R { PCMP_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - Floating Prescaler Shadow Compare Value"] #[inline(always)] pub fn pcmp(&mut self) -> PCMP_W { PCMP_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "Floating Prescaler Shadow\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fpcs](index.html) module"] pub struct FPCS_SPEC; impl crate::RegisterSpec for FPCS_SPEC { type Ux = u32; } #[doc = "`read()` method returns [fpcs::R](R) reader structure"] impl crate::Readable for FPCS_SPEC { type Reader = R; } #[doc = "`write(|w|..)` method takes [fpcs::W](W) writer structure"] impl crate::Writable for FPCS_SPEC { type Writer = W; } #[doc = "`reset()` method sets FPCS to value 0"] impl crate::Resettable for FPCS_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
&self.0 } } #[doc = "Field `PCMP` writer - Floating Prescaler Shadow Compare Value"] pub struct PCMP_W<'a> {
random_line_split
fpcs.rs
#[doc = "Register `FPCS` reader"] pub struct R(crate::R<FPCS_SPEC>); impl core::ops::Deref for R { type Target = crate::R<FPCS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<FPCS_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<FPCS_SPEC>) -> Self { R(reader) } } #[doc = "Register `FPCS` writer"] pub struct W(crate::W<FPCS_SPEC>); impl core::ops::Deref for W { type Target = crate::W<FPCS_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<FPCS_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<FPCS_SPEC>) -> Self { W(writer) } } #[doc = "Field `PCMP` reader - Floating Prescaler Shadow Compare Value"] pub struct PCMP_R(crate::FieldReader<u8, u8>); impl PCMP_R { pub(crate) fn new(bits: u8) -> Self { PCMP_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for PCMP_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `PCMP` writer - Floating Prescaler Shadow Compare Value"] pub struct PCMP_W<'a> { w: &'a mut W, } impl<'a> PCMP_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits &!0x0f) | (value as u32 & 0x0f); self.w } } impl R { #[doc = "Bits 0:3 - Floating Prescaler Shadow Compare Value"] #[inline(always)] pub fn pcmp(&self) -> PCMP_R { PCMP_R::new((self.bits & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - Floating Prescaler Shadow Compare Value"] #[inline(always)] pub fn
(&mut self) -> PCMP_W { PCMP_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "Floating Prescaler Shadow\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fpcs](index.html) module"] pub struct FPCS_SPEC; impl crate::RegisterSpec for FPCS_SPEC { type Ux = u32; } #[doc = "`read()` method returns [fpcs::R](R) reader structure"] impl crate::Readable for FPCS_SPEC { type Reader = R; } #[doc = "`write(|w|..)` method takes [fpcs::W](W) writer structure"] impl crate::Writable for FPCS_SPEC { type Writer = W; } #[doc = "`reset()` method sets FPCS to value 0"] impl crate::Resettable for FPCS_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
pcmp
identifier_name
parser.rs
use std::io::{Read, Cursor}; use FromCursor; use compression::Compression; use frame::frame_response::ResponseBody; use super::*; use types::{from_bytes, UUID_LEN, CStringList}; use types::data_serialization_types::decode_timeuuid; use error; pub fn parse_frame(mut cursor: &mut Read, compressor: &Compression) -> error::Result<Frame> { // TODO: try to use slices instead let mut version_bytes = [0; VERSION_LEN]; let mut flag_bytes = [0; FLAG_LEN]; let mut opcode_bytes = [0; OPCODE_LEN]; let mut stream_bytes = [0; STREAM_LEN]; let mut length_bytes = [0; LENGTH_LEN]; // NOTE: order of reads matters try!(cursor.read(&mut version_bytes)); try!(cursor.read(&mut flag_bytes)); try!(cursor.read(&mut stream_bytes)); try!(cursor.read(&mut opcode_bytes)); try!(cursor.read(&mut length_bytes)); let version = Version::from(version_bytes.to_vec()); let flags = Flag::get_collection(flag_bytes[0]); let stream = from_bytes(stream_bytes.to_vec().as_slice()); let opcode = Opcode::from(opcode_bytes[0]); let length = from_bytes(length_bytes.to_vec().as_slice()) as usize; let mut body_bytes = Vec::with_capacity(length); unsafe { body_bytes.set_len(length); } try!(cursor.read_exact(&mut body_bytes)); let full_body = if flags.iter().any(|flag| flag == &Flag::Compression) { try!(compressor.decode(body_bytes)) } else { try!(Compression::None.decode(body_bytes)) }; // Use cursor to get tracing id, warnings and actual body let mut body_cursor = Cursor::new(full_body.as_slice()); let tracing_id = if flags.iter().any(|flag| flag == &Flag::Tracing) { let mut tracing_bytes = Vec::with_capacity(UUID_LEN); unsafe { tracing_bytes.set_len(UUID_LEN); } // TODO: try to use slice instead try!(body_cursor.read_exact(&mut tracing_bytes)); decode_timeuuid(tracing_bytes.as_slice()).ok() } else { None }; let warnings = if flags.iter().any(|flag| flag == &Flag::Warning) { CStringList::from_cursor(&mut body_cursor)?.into_plain() } else { vec![] }; let mut body = vec![]; try!(body_cursor.read_to_end(&mut body)); let frame = Frame { version: version, flags: flags, opcode: opcode, stream: stream, body: body, tracing_id: tracing_id, warnings: warnings, }; conver_frame_into_result(frame) } fn
(frame: Frame) -> error::Result<Frame> { match frame.opcode { Opcode::Error => { frame .get_body() .and_then(|err| match err { ResponseBody::Error(err) => Err(error::Error::Server(err)), _ => unreachable!(), }) } _ => Ok(frame), } }
conver_frame_into_result
identifier_name
parser.rs
use std::io::{Read, Cursor}; use FromCursor;
use types::data_serialization_types::decode_timeuuid; use error; pub fn parse_frame(mut cursor: &mut Read, compressor: &Compression) -> error::Result<Frame> { // TODO: try to use slices instead let mut version_bytes = [0; VERSION_LEN]; let mut flag_bytes = [0; FLAG_LEN]; let mut opcode_bytes = [0; OPCODE_LEN]; let mut stream_bytes = [0; STREAM_LEN]; let mut length_bytes = [0; LENGTH_LEN]; // NOTE: order of reads matters try!(cursor.read(&mut version_bytes)); try!(cursor.read(&mut flag_bytes)); try!(cursor.read(&mut stream_bytes)); try!(cursor.read(&mut opcode_bytes)); try!(cursor.read(&mut length_bytes)); let version = Version::from(version_bytes.to_vec()); let flags = Flag::get_collection(flag_bytes[0]); let stream = from_bytes(stream_bytes.to_vec().as_slice()); let opcode = Opcode::from(opcode_bytes[0]); let length = from_bytes(length_bytes.to_vec().as_slice()) as usize; let mut body_bytes = Vec::with_capacity(length); unsafe { body_bytes.set_len(length); } try!(cursor.read_exact(&mut body_bytes)); let full_body = if flags.iter().any(|flag| flag == &Flag::Compression) { try!(compressor.decode(body_bytes)) } else { try!(Compression::None.decode(body_bytes)) }; // Use cursor to get tracing id, warnings and actual body let mut body_cursor = Cursor::new(full_body.as_slice()); let tracing_id = if flags.iter().any(|flag| flag == &Flag::Tracing) { let mut tracing_bytes = Vec::with_capacity(UUID_LEN); unsafe { tracing_bytes.set_len(UUID_LEN); } // TODO: try to use slice instead try!(body_cursor.read_exact(&mut tracing_bytes)); decode_timeuuid(tracing_bytes.as_slice()).ok() } else { None }; let warnings = if flags.iter().any(|flag| flag == &Flag::Warning) { CStringList::from_cursor(&mut body_cursor)?.into_plain() } else { vec![] }; let mut body = vec![]; try!(body_cursor.read_to_end(&mut body)); let frame = Frame { version: version, flags: flags, opcode: opcode, stream: stream, body: body, tracing_id: tracing_id, warnings: warnings, }; conver_frame_into_result(frame) } fn conver_frame_into_result(frame: Frame) -> error::Result<Frame> { match frame.opcode { Opcode::Error => { frame .get_body() .and_then(|err| match err { ResponseBody::Error(err) => Err(error::Error::Server(err)), _ => unreachable!(), }) } _ => Ok(frame), } }
use compression::Compression; use frame::frame_response::ResponseBody; use super::*; use types::{from_bytes, UUID_LEN, CStringList};
random_line_split
parser.rs
use std::io::{Read, Cursor}; use FromCursor; use compression::Compression; use frame::frame_response::ResponseBody; use super::*; use types::{from_bytes, UUID_LEN, CStringList}; use types::data_serialization_types::decode_timeuuid; use error; pub fn parse_frame(mut cursor: &mut Read, compressor: &Compression) -> error::Result<Frame>
let mut body_bytes = Vec::with_capacity(length); unsafe { body_bytes.set_len(length); } try!(cursor.read_exact(&mut body_bytes)); let full_body = if flags.iter().any(|flag| flag == &Flag::Compression) { try!(compressor.decode(body_bytes)) } else { try!(Compression::None.decode(body_bytes)) }; // Use cursor to get tracing id, warnings and actual body let mut body_cursor = Cursor::new(full_body.as_slice()); let tracing_id = if flags.iter().any(|flag| flag == &Flag::Tracing) { let mut tracing_bytes = Vec::with_capacity(UUID_LEN); unsafe { tracing_bytes.set_len(UUID_LEN); } // TODO: try to use slice instead try!(body_cursor.read_exact(&mut tracing_bytes)); decode_timeuuid(tracing_bytes.as_slice()).ok() } else { None }; let warnings = if flags.iter().any(|flag| flag == &Flag::Warning) { CStringList::from_cursor(&mut body_cursor)?.into_plain() } else { vec![] }; let mut body = vec![]; try!(body_cursor.read_to_end(&mut body)); let frame = Frame { version: version, flags: flags, opcode: opcode, stream: stream, body: body, tracing_id: tracing_id, warnings: warnings, }; conver_frame_into_result(frame) } fn conver_frame_into_result(frame: Frame) -> error::Result<Frame> { match frame.opcode { Opcode::Error => { frame .get_body() .and_then(|err| match err { ResponseBody::Error(err) => Err(error::Error::Server(err)), _ => unreachable!(), }) } _ => Ok(frame), } }
{ // TODO: try to use slices instead let mut version_bytes = [0; VERSION_LEN]; let mut flag_bytes = [0; FLAG_LEN]; let mut opcode_bytes = [0; OPCODE_LEN]; let mut stream_bytes = [0; STREAM_LEN]; let mut length_bytes = [0; LENGTH_LEN]; // NOTE: order of reads matters try!(cursor.read(&mut version_bytes)); try!(cursor.read(&mut flag_bytes)); try!(cursor.read(&mut stream_bytes)); try!(cursor.read(&mut opcode_bytes)); try!(cursor.read(&mut length_bytes)); let version = Version::from(version_bytes.to_vec()); let flags = Flag::get_collection(flag_bytes[0]); let stream = from_bytes(stream_bytes.to_vec().as_slice()); let opcode = Opcode::from(opcode_bytes[0]); let length = from_bytes(length_bytes.to_vec().as_slice()) as usize;
identifier_body
parser.rs
use std::io::{Read, Cursor}; use FromCursor; use compression::Compression; use frame::frame_response::ResponseBody; use super::*; use types::{from_bytes, UUID_LEN, CStringList}; use types::data_serialization_types::decode_timeuuid; use error; pub fn parse_frame(mut cursor: &mut Read, compressor: &Compression) -> error::Result<Frame> { // TODO: try to use slices instead let mut version_bytes = [0; VERSION_LEN]; let mut flag_bytes = [0; FLAG_LEN]; let mut opcode_bytes = [0; OPCODE_LEN]; let mut stream_bytes = [0; STREAM_LEN]; let mut length_bytes = [0; LENGTH_LEN]; // NOTE: order of reads matters try!(cursor.read(&mut version_bytes)); try!(cursor.read(&mut flag_bytes)); try!(cursor.read(&mut stream_bytes)); try!(cursor.read(&mut opcode_bytes)); try!(cursor.read(&mut length_bytes)); let version = Version::from(version_bytes.to_vec()); let flags = Flag::get_collection(flag_bytes[0]); let stream = from_bytes(stream_bytes.to_vec().as_slice()); let opcode = Opcode::from(opcode_bytes[0]); let length = from_bytes(length_bytes.to_vec().as_slice()) as usize; let mut body_bytes = Vec::with_capacity(length); unsafe { body_bytes.set_len(length); } try!(cursor.read_exact(&mut body_bytes)); let full_body = if flags.iter().any(|flag| flag == &Flag::Compression) { try!(compressor.decode(body_bytes)) } else { try!(Compression::None.decode(body_bytes)) }; // Use cursor to get tracing id, warnings and actual body let mut body_cursor = Cursor::new(full_body.as_slice()); let tracing_id = if flags.iter().any(|flag| flag == &Flag::Tracing)
else { None }; let warnings = if flags.iter().any(|flag| flag == &Flag::Warning) { CStringList::from_cursor(&mut body_cursor)?.into_plain() } else { vec![] }; let mut body = vec![]; try!(body_cursor.read_to_end(&mut body)); let frame = Frame { version: version, flags: flags, opcode: opcode, stream: stream, body: body, tracing_id: tracing_id, warnings: warnings, }; conver_frame_into_result(frame) } fn conver_frame_into_result(frame: Frame) -> error::Result<Frame> { match frame.opcode { Opcode::Error => { frame .get_body() .and_then(|err| match err { ResponseBody::Error(err) => Err(error::Error::Server(err)), _ => unreachable!(), }) } _ => Ok(frame), } }
{ let mut tracing_bytes = Vec::with_capacity(UUID_LEN); unsafe { tracing_bytes.set_len(UUID_LEN); } // TODO: try to use slice instead try!(body_cursor.read_exact(&mut tracing_bytes)); decode_timeuuid(tracing_bytes.as_slice()).ok() }
conditional_block
issue-7573.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub struct CrateId { local_path: String, junk: String } impl CrateId { fn new(s: &str) -> CrateId { CrateId { local_path: s.to_string(), junk: "wutevs".to_string() } } } pub fn remove_package_from_database() { let mut lines_to_use: Vec<&CrateId> = Vec::new(); let push_id = |installed_id: &CrateId| { lines_to_use.push(installed_id); //~^ ERROR cannot infer an appropriate lifetime for automatic coercion due to // conflicting requirements }; list_database(push_id);
println!("{}", l.local_path); } } pub fn list_database<F>(mut f: F) where F: FnMut(&CrateId) { let stuff = ["foo", "bar"]; for l in &stuff { f(&CrateId::new(*l)); } } pub fn main() { remove_package_from_database(); }
for l in &lines_to_use {
random_line_split
issue-7573.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub struct CrateId { local_path: String, junk: String } impl CrateId { fn
(s: &str) -> CrateId { CrateId { local_path: s.to_string(), junk: "wutevs".to_string() } } } pub fn remove_package_from_database() { let mut lines_to_use: Vec<&CrateId> = Vec::new(); let push_id = |installed_id: &CrateId| { lines_to_use.push(installed_id); //~^ ERROR cannot infer an appropriate lifetime for automatic coercion due to // conflicting requirements }; list_database(push_id); for l in &lines_to_use { println!("{}", l.local_path); } } pub fn list_database<F>(mut f: F) where F: FnMut(&CrateId) { let stuff = ["foo", "bar"]; for l in &stuff { f(&CrateId::new(*l)); } } pub fn main() { remove_package_from_database(); }
new
identifier_name
issue-7573.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. pub struct CrateId { local_path: String, junk: String } impl CrateId { fn new(s: &str) -> CrateId { CrateId { local_path: s.to_string(), junk: "wutevs".to_string() } } } pub fn remove_package_from_database() { let mut lines_to_use: Vec<&CrateId> = Vec::new(); let push_id = |installed_id: &CrateId| { lines_to_use.push(installed_id); //~^ ERROR cannot infer an appropriate lifetime for automatic coercion due to // conflicting requirements }; list_database(push_id); for l in &lines_to_use { println!("{}", l.local_path); } } pub fn list_database<F>(mut f: F) where F: FnMut(&CrateId)
pub fn main() { remove_package_from_database(); }
{ let stuff = ["foo", "bar"]; for l in &stuff { f(&CrateId::new(*l)); } }
identifier_body
rewrite_reincarnation.rs
// Copyright 2018 Pierre Talbot // 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. // We rewrite `loop p end` into `loop p; p end` to avoid reincarnation problems. // See the thesis of (Tardieu, 2014), Chapter 7. // It is the simple rewriting of (Mignard, 1994) possibly exponential in the code size. use context::*; use session::*; pub fn rewrite_reincarnation(session: Session, context: Context) -> Env<Context> { let reincarnation = Reincarnation::new(session, context); reincarnation.rewrite() } struct Reincarnation { session: Session, context: Context, loops: usize, rename_mode: bool, renamings: Vec<(Ident, Ident)> } impl Reincarnation { pub fn new(session: Session, context: Context) -> Self { Reincarnation { session, context, loops: 0, rename_mode: false, renamings: vec![] } } fn rewrite(mut self) -> Env<Context> { let mut bcrate_clone = self.context.clone_ast(); self.visit_crate(&mut bcrate_clone); self.context.replace_ast(bcrate_clone); Env::value(self.session, self.context) } fn rename_decl(&mut self, mut name: Ident) -> Ident { let new_name = format!("__reincarn{}_{}", self.loops, name); name.value = new_name; name } fn rename(&mut self, var: &mut Variable) { for (old, new) in self.renamings.clone() { if var.len() == 1 && var.first() == old { var.path.fragments[0] = new; } } } } impl VisitorMut<JClass> for Reincarnation { fn
(&mut self, child: &mut Stmt) { self.loops += 1; self.visit_stmt(child); if!self.rename_mode { self.rename_mode = true; let child_copy = child.clone(); self.visit_stmt(child); let seq = StmtKind::Seq(vec![child.clone(), child_copy]); child.node = seq; self.rename_mode = false; } self.loops -= 1; } fn visit_let(&mut self, let_stmt: &mut LetStmt) { if self.rename_mode { let old = let_stmt.binding.name.clone(); let_stmt.binding.name = self.rename_decl(let_stmt.binding.name.clone()); self.renamings.push((old, let_stmt.binding.name.clone())); } self.visit_binding(&mut let_stmt.binding); self.visit_stmt(&mut *(let_stmt.body)); if self.rename_mode { self.renamings.pop(); } } fn visit_var(&mut self, var: &mut Variable) { self.rename(var); } }
visit_loop
identifier_name
rewrite_reincarnation.rs
// Copyright 2018 Pierre Talbot // 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. // We rewrite `loop p end` into `loop p; p end` to avoid reincarnation problems. // See the thesis of (Tardieu, 2014), Chapter 7. // It is the simple rewriting of (Mignard, 1994) possibly exponential in the code size. use context::*; use session::*; pub fn rewrite_reincarnation(session: Session, context: Context) -> Env<Context> { let reincarnation = Reincarnation::new(session, context); reincarnation.rewrite() } struct Reincarnation { session: Session, context: Context, loops: usize, rename_mode: bool, renamings: Vec<(Ident, Ident)> } impl Reincarnation { pub fn new(session: Session, context: Context) -> Self { Reincarnation { session, context, loops: 0, rename_mode: false, renamings: vec![] } } fn rewrite(mut self) -> Env<Context> { let mut bcrate_clone = self.context.clone_ast(); self.visit_crate(&mut bcrate_clone); self.context.replace_ast(bcrate_clone); Env::value(self.session, self.context) } fn rename_decl(&mut self, mut name: Ident) -> Ident { let new_name = format!("__reincarn{}_{}", self.loops, name); name.value = new_name; name } fn rename(&mut self, var: &mut Variable) { for (old, new) in self.renamings.clone() { if var.len() == 1 && var.first() == old { var.path.fragments[0] = new; } } } } impl VisitorMut<JClass> for Reincarnation { fn visit_loop(&mut self, child: &mut Stmt) { self.loops += 1; self.visit_stmt(child); if!self.rename_mode { self.rename_mode = true; let child_copy = child.clone(); self.visit_stmt(child); let seq = StmtKind::Seq(vec![child.clone(), child_copy]); child.node = seq; self.rename_mode = false; } self.loops -= 1; } fn visit_let(&mut self, let_stmt: &mut LetStmt) { if self.rename_mode
self.visit_binding(&mut let_stmt.binding); self.visit_stmt(&mut *(let_stmt.body)); if self.rename_mode { self.renamings.pop(); } } fn visit_var(&mut self, var: &mut Variable) { self.rename(var); } }
{ let old = let_stmt.binding.name.clone(); let_stmt.binding.name = self.rename_decl(let_stmt.binding.name.clone()); self.renamings.push((old, let_stmt.binding.name.clone())); }
conditional_block
rewrite_reincarnation.rs
// Copyright 2018 Pierre Talbot // 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. // We rewrite `loop p end` into `loop p; p end` to avoid reincarnation problems. // See the thesis of (Tardieu, 2014), Chapter 7. // It is the simple rewriting of (Mignard, 1994) possibly exponential in the code size. use context::*; use session::*; pub fn rewrite_reincarnation(session: Session, context: Context) -> Env<Context> { let reincarnation = Reincarnation::new(session, context); reincarnation.rewrite() }
context: Context, loops: usize, rename_mode: bool, renamings: Vec<(Ident, Ident)> } impl Reincarnation { pub fn new(session: Session, context: Context) -> Self { Reincarnation { session, context, loops: 0, rename_mode: false, renamings: vec![] } } fn rewrite(mut self) -> Env<Context> { let mut bcrate_clone = self.context.clone_ast(); self.visit_crate(&mut bcrate_clone); self.context.replace_ast(bcrate_clone); Env::value(self.session, self.context) } fn rename_decl(&mut self, mut name: Ident) -> Ident { let new_name = format!("__reincarn{}_{}", self.loops, name); name.value = new_name; name } fn rename(&mut self, var: &mut Variable) { for (old, new) in self.renamings.clone() { if var.len() == 1 && var.first() == old { var.path.fragments[0] = new; } } } } impl VisitorMut<JClass> for Reincarnation { fn visit_loop(&mut self, child: &mut Stmt) { self.loops += 1; self.visit_stmt(child); if!self.rename_mode { self.rename_mode = true; let child_copy = child.clone(); self.visit_stmt(child); let seq = StmtKind::Seq(vec![child.clone(), child_copy]); child.node = seq; self.rename_mode = false; } self.loops -= 1; } fn visit_let(&mut self, let_stmt: &mut LetStmt) { if self.rename_mode { let old = let_stmt.binding.name.clone(); let_stmt.binding.name = self.rename_decl(let_stmt.binding.name.clone()); self.renamings.push((old, let_stmt.binding.name.clone())); } self.visit_binding(&mut let_stmt.binding); self.visit_stmt(&mut *(let_stmt.body)); if self.rename_mode { self.renamings.pop(); } } fn visit_var(&mut self, var: &mut Variable) { self.rename(var); } }
struct Reincarnation { session: Session,
random_line_split
rewrite_reincarnation.rs
// Copyright 2018 Pierre Talbot // 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. // We rewrite `loop p end` into `loop p; p end` to avoid reincarnation problems. // See the thesis of (Tardieu, 2014), Chapter 7. // It is the simple rewriting of (Mignard, 1994) possibly exponential in the code size. use context::*; use session::*; pub fn rewrite_reincarnation(session: Session, context: Context) -> Env<Context> { let reincarnation = Reincarnation::new(session, context); reincarnation.rewrite() } struct Reincarnation { session: Session, context: Context, loops: usize, rename_mode: bool, renamings: Vec<(Ident, Ident)> } impl Reincarnation { pub fn new(session: Session, context: Context) -> Self { Reincarnation { session, context, loops: 0, rename_mode: false, renamings: vec![] } } fn rewrite(mut self) -> Env<Context> { let mut bcrate_clone = self.context.clone_ast(); self.visit_crate(&mut bcrate_clone); self.context.replace_ast(bcrate_clone); Env::value(self.session, self.context) } fn rename_decl(&mut self, mut name: Ident) -> Ident { let new_name = format!("__reincarn{}_{}", self.loops, name); name.value = new_name; name } fn rename(&mut self, var: &mut Variable)
} impl VisitorMut<JClass> for Reincarnation { fn visit_loop(&mut self, child: &mut Stmt) { self.loops += 1; self.visit_stmt(child); if!self.rename_mode { self.rename_mode = true; let child_copy = child.clone(); self.visit_stmt(child); let seq = StmtKind::Seq(vec![child.clone(), child_copy]); child.node = seq; self.rename_mode = false; } self.loops -= 1; } fn visit_let(&mut self, let_stmt: &mut LetStmt) { if self.rename_mode { let old = let_stmt.binding.name.clone(); let_stmt.binding.name = self.rename_decl(let_stmt.binding.name.clone()); self.renamings.push((old, let_stmt.binding.name.clone())); } self.visit_binding(&mut let_stmt.binding); self.visit_stmt(&mut *(let_stmt.body)); if self.rename_mode { self.renamings.pop(); } } fn visit_var(&mut self, var: &mut Variable) { self.rename(var); } }
{ for (old, new) in self.renamings.clone() { if var.len() == 1 && var.first() == old { var.path.fragments[0] = new; } } }
identifier_body
borrowck-uniq-via-lend.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. fn borrow(_v: &int) {} fn local() { let mut v = box 3i; borrow(v); } fn local_rec() { struct F { f: Box<int> } let mut v = F {f: box 3}; borrow(v.f); } fn
() { struct F { f: G } struct G { g: H } struct H { h: Box<int> } let mut v = F {f: G {g: H {h: box 3}}}; borrow(v.f.g.h); } fn aliased_imm() { let mut v = box 3i; let _w = &v; borrow(v); } fn aliased_mut() { let mut v = box 3i; let _w = &mut v; borrow(v); //~ ERROR cannot borrow `*v` } fn aliased_other() { let mut v = box 3i; let mut w = box 4i; let _x = &mut w; borrow(v); } fn aliased_other_reassign() { let mut v = box 3i; let mut w = box 4i; let mut _x = &mut w; _x = &mut v; borrow(v); //~ ERROR cannot borrow `*v` } fn main() { }
local_recs
identifier_name
borrowck-uniq-via-lend.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. fn borrow(_v: &int) {} fn local() { let mut v = box 3i; borrow(v); } fn local_rec() { struct F { f: Box<int> } let mut v = F {f: box 3}; borrow(v.f); } fn local_recs() { struct F { f: G } struct G { g: H } struct H { h: Box<int> } let mut v = F {f: G {g: H {h: box 3}}}; borrow(v.f.g.h); } fn aliased_imm() { let mut v = box 3i; let _w = &v; borrow(v); } fn aliased_mut() { let mut v = box 3i; let _w = &mut v; borrow(v); //~ ERROR cannot borrow `*v`
let _x = &mut w; borrow(v); } fn aliased_other_reassign() { let mut v = box 3i; let mut w = box 4i; let mut _x = &mut w; _x = &mut v; borrow(v); //~ ERROR cannot borrow `*v` } fn main() { }
} fn aliased_other() { let mut v = box 3i; let mut w = box 4i;
random_line_split
borrowck-uniq-via-lend.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. fn borrow(_v: &int) {} fn local() { let mut v = box 3i; borrow(v); } fn local_rec()
fn local_recs() { struct F { f: G } struct G { g: H } struct H { h: Box<int> } let mut v = F {f: G {g: H {h: box 3}}}; borrow(v.f.g.h); } fn aliased_imm() { let mut v = box 3i; let _w = &v; borrow(v); } fn aliased_mut() { let mut v = box 3i; let _w = &mut v; borrow(v); //~ ERROR cannot borrow `*v` } fn aliased_other() { let mut v = box 3i; let mut w = box 4i; let _x = &mut w; borrow(v); } fn aliased_other_reassign() { let mut v = box 3i; let mut w = box 4i; let mut _x = &mut w; _x = &mut v; borrow(v); //~ ERROR cannot borrow `*v` } fn main() { }
{ struct F { f: Box<int> } let mut v = F {f: box 3}; borrow(v.f); }
identifier_body
comparison_chain.rs
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::implements_trait; use clippy_utils::{get_trait_def_id, if_sequence, in_constant, is_else_clause, paths, SpanlessEq}; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Checks comparison chains written with `if` that can be /// rewritten with `match` and `cmp`. /// /// ### Why is this bad? /// `if` is not guaranteed to be exhaustive and conditionals can get /// repetitive /// /// ### Known problems /// The match statement may be slower due to the compiler /// not inlining the call to cmp. See issue [#5354](https://github.com/rust-lang/rust-clippy/issues/5354) /// /// ### Example /// ```rust,ignore /// # fn a() {} /// # fn b() {} /// # fn c() {} /// fn f(x: u8, y: u8) { /// if x > y { /// a() /// } else if x < y { /// b() /// } else { /// c() /// } /// } /// ``` /// /// Could be written: /// /// ```rust,ignore /// use std::cmp::Ordering; /// # fn a() {} /// # fn b() {} /// # fn c() {} /// fn f(x: u8, y: u8) { /// match x.cmp(&y) { /// Ordering::Greater => a(), /// Ordering::Less => b(), /// Ordering::Equal => c() /// } /// } /// ``` pub COMPARISON_CHAIN, style, "`if`s that can be rewritten with `match` and `cmp`" } declare_lint_pass!(ComparisonChain => [COMPARISON_CHAIN]); impl<'tcx> LateLintPass<'tcx> for ComparisonChain { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if expr.span.from_expansion()
// We only care about the top-most `if` in the chain if is_else_clause(cx.tcx, expr) { return; } if in_constant(cx, expr.hir_id) { return; } // Check that there exists at least one explicit else condition let (conds, _) = if_sequence(expr); if conds.len() < 2 { return; } for cond in conds.windows(2) { if let (&ExprKind::Binary(ref kind1, lhs1, rhs1), &ExprKind::Binary(ref kind2, lhs2, rhs2)) = (&cond[0].kind, &cond[1].kind) { if!kind_is_cmp(kind1.node) ||!kind_is_cmp(kind2.node) { return; } // Check that both sets of operands are equal let mut spanless_eq = SpanlessEq::new(cx); let same_fixed_operands = spanless_eq.eq_expr(lhs1, lhs2) && spanless_eq.eq_expr(rhs1, rhs2); let same_transposed_operands = spanless_eq.eq_expr(lhs1, rhs2) && spanless_eq.eq_expr(rhs1, lhs2); if!same_fixed_operands &&!same_transposed_operands { return; } // Check that if the operation is the same, either it's not `==` or the operands are transposed if kind1.node == kind2.node { if kind1.node == BinOpKind::Eq { return; } if!same_transposed_operands { return; } } // Check that the type being compared implements `core::cmp::Ord` let ty = cx.typeck_results().expr_ty(lhs1); let is_ord = get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[])); if!is_ord { return; } } else { // We only care about comparison chains return; } } span_lint_and_help( cx, COMPARISON_CHAIN, expr.span, "`if` chain can be rewritten with `match`", None, "consider rewriting the `if` chain to use `cmp` and `match`", ); } } fn kind_is_cmp(kind: BinOpKind) -> bool { matches!(kind, BinOpKind::Lt | BinOpKind::Gt | BinOpKind::Eq) }
{ return; }
conditional_block
comparison_chain.rs
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::implements_trait; use clippy_utils::{get_trait_def_id, if_sequence, in_constant, is_else_clause, paths, SpanlessEq}; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Checks comparison chains written with `if` that can be /// rewritten with `match` and `cmp`. /// /// ### Why is this bad? /// `if` is not guaranteed to be exhaustive and conditionals can get /// repetitive /// /// ### Known problems /// The match statement may be slower due to the compiler /// not inlining the call to cmp. See issue [#5354](https://github.com/rust-lang/rust-clippy/issues/5354) /// /// ### Example /// ```rust,ignore /// # fn a() {} /// # fn b() {} /// # fn c() {} /// fn f(x: u8, y: u8) { /// if x > y { /// a() /// } else if x < y { /// b() /// } else { /// c() /// } /// } /// ``` /// /// Could be written: /// /// ```rust,ignore /// use std::cmp::Ordering; /// # fn a() {} /// # fn b() {} /// # fn c() {} /// fn f(x: u8, y: u8) { /// match x.cmp(&y) { /// Ordering::Greater => a(), /// Ordering::Less => b(), /// Ordering::Equal => c() /// } /// } /// ``` pub COMPARISON_CHAIN, style, "`if`s that can be rewritten with `match` and `cmp`" } declare_lint_pass!(ComparisonChain => [COMPARISON_CHAIN]); impl<'tcx> LateLintPass<'tcx> for ComparisonChain { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if expr.span.from_expansion() { return; } // We only care about the top-most `if` in the chain if is_else_clause(cx.tcx, expr) { return; } if in_constant(cx, expr.hir_id) { return; } // Check that there exists at least one explicit else condition let (conds, _) = if_sequence(expr); if conds.len() < 2 { return; } for cond in conds.windows(2) { if let (&ExprKind::Binary(ref kind1, lhs1, rhs1), &ExprKind::Binary(ref kind2, lhs2, rhs2)) = (&cond[0].kind, &cond[1].kind) { if!kind_is_cmp(kind1.node) ||!kind_is_cmp(kind2.node) { return; } // Check that both sets of operands are equal let mut spanless_eq = SpanlessEq::new(cx); let same_fixed_operands = spanless_eq.eq_expr(lhs1, lhs2) && spanless_eq.eq_expr(rhs1, rhs2); let same_transposed_operands = spanless_eq.eq_expr(lhs1, rhs2) && spanless_eq.eq_expr(rhs1, lhs2); if!same_fixed_operands &&!same_transposed_operands { return; } // Check that if the operation is the same, either it's not `==` or the operands are transposed if kind1.node == kind2.node { if kind1.node == BinOpKind::Eq { return; } if!same_transposed_operands { return; } } // Check that the type being compared implements `core::cmp::Ord` let ty = cx.typeck_results().expr_ty(lhs1); let is_ord = get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[])); if!is_ord { return; } } else { // We only care about comparison chains return; } } span_lint_and_help( cx, COMPARISON_CHAIN, expr.span, "`if` chain can be rewritten with `match`", None, "consider rewriting the `if` chain to use `cmp` and `match`", ); } } fn
(kind: BinOpKind) -> bool { matches!(kind, BinOpKind::Lt | BinOpKind::Gt | BinOpKind::Eq) }
kind_is_cmp
identifier_name
comparison_chain.rs
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::implements_trait; use clippy_utils::{get_trait_def_id, if_sequence, in_constant, is_else_clause, paths, SpanlessEq}; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Checks comparison chains written with `if` that can be /// rewritten with `match` and `cmp`. /// /// ### Why is this bad? /// `if` is not guaranteed to be exhaustive and conditionals can get /// repetitive /// /// ### Known problems /// The match statement may be slower due to the compiler /// not inlining the call to cmp. See issue [#5354](https://github.com/rust-lang/rust-clippy/issues/5354) /// /// ### Example /// ```rust,ignore /// # fn a() {} /// # fn b() {} /// # fn c() {} /// fn f(x: u8, y: u8) { /// if x > y { /// a() /// } else if x < y { /// b() /// } else { /// c() /// } /// } /// ``` /// /// Could be written: /// /// ```rust,ignore /// use std::cmp::Ordering; /// # fn a() {} /// # fn b() {} /// # fn c() {} /// fn f(x: u8, y: u8) { /// match x.cmp(&y) { /// Ordering::Greater => a(), /// Ordering::Less => b(), /// Ordering::Equal => c() /// } /// } /// ``` pub COMPARISON_CHAIN, style, "`if`s that can be rewritten with `match` and `cmp`" } declare_lint_pass!(ComparisonChain => [COMPARISON_CHAIN]); impl<'tcx> LateLintPass<'tcx> for ComparisonChain { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if expr.span.from_expansion() { return; } // We only care about the top-most `if` in the chain if is_else_clause(cx.tcx, expr) { return; } if in_constant(cx, expr.hir_id) { return; } // Check that there exists at least one explicit else condition let (conds, _) = if_sequence(expr); if conds.len() < 2 { return; } for cond in conds.windows(2) { if let (&ExprKind::Binary(ref kind1, lhs1, rhs1), &ExprKind::Binary(ref kind2, lhs2, rhs2)) = (&cond[0].kind, &cond[1].kind) { if!kind_is_cmp(kind1.node) ||!kind_is_cmp(kind2.node) { return; } // Check that both sets of operands are equal let mut spanless_eq = SpanlessEq::new(cx); let same_fixed_operands = spanless_eq.eq_expr(lhs1, lhs2) && spanless_eq.eq_expr(rhs1, rhs2); let same_transposed_operands = spanless_eq.eq_expr(lhs1, rhs2) && spanless_eq.eq_expr(rhs1, lhs2); if!same_fixed_operands &&!same_transposed_operands { return; } // Check that if the operation is the same, either it's not `==` or the operands are transposed if kind1.node == kind2.node { if kind1.node == BinOpKind::Eq { return; } if!same_transposed_operands { return; } } // Check that the type being compared implements `core::cmp::Ord` let ty = cx.typeck_results().expr_ty(lhs1); let is_ord = get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[])); if!is_ord { return; } } else { // We only care about comparison chains return; } } span_lint_and_help( cx, COMPARISON_CHAIN, expr.span, "`if` chain can be rewritten with `match`", None, "consider rewriting the `if` chain to use `cmp` and `match`", ); } } fn kind_is_cmp(kind: BinOpKind) -> bool
{ matches!(kind, BinOpKind::Lt | BinOpKind::Gt | BinOpKind::Eq) }
identifier_body
comparison_chain.rs
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::implements_trait; use clippy_utils::{get_trait_def_id, if_sequence, in_constant, is_else_clause, paths, SpanlessEq}; use rustc_hir::{BinOpKind, Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; declare_clippy_lint! { /// ### What it does /// Checks comparison chains written with `if` that can be /// rewritten with `match` and `cmp`. /// /// ### Why is this bad? /// `if` is not guaranteed to be exhaustive and conditionals can get /// repetitive /// /// ### Known problems /// The match statement may be slower due to the compiler /// not inlining the call to cmp. See issue [#5354](https://github.com/rust-lang/rust-clippy/issues/5354) /// /// ### Example /// ```rust,ignore /// # fn a() {} /// # fn b() {} /// # fn c() {} /// fn f(x: u8, y: u8) { /// if x > y { /// a() /// } else if x < y { /// b() /// } else { /// c() /// } /// } /// ``` /// /// Could be written: /// /// ```rust,ignore /// use std::cmp::Ordering; /// # fn a() {} /// # fn b() {} /// # fn c() {} /// fn f(x: u8, y: u8) { /// match x.cmp(&y) { /// Ordering::Greater => a(), /// Ordering::Less => b(), /// Ordering::Equal => c() /// } /// } /// ``` pub COMPARISON_CHAIN, style, "`if`s that can be rewritten with `match` and `cmp`" } declare_lint_pass!(ComparisonChain => [COMPARISON_CHAIN]); impl<'tcx> LateLintPass<'tcx> for ComparisonChain { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { if expr.span.from_expansion() { return; }
// We only care about the top-most `if` in the chain if is_else_clause(cx.tcx, expr) { return; } if in_constant(cx, expr.hir_id) { return; } // Check that there exists at least one explicit else condition let (conds, _) = if_sequence(expr); if conds.len() < 2 { return; } for cond in conds.windows(2) { if let (&ExprKind::Binary(ref kind1, lhs1, rhs1), &ExprKind::Binary(ref kind2, lhs2, rhs2)) = (&cond[0].kind, &cond[1].kind) { if!kind_is_cmp(kind1.node) ||!kind_is_cmp(kind2.node) { return; } // Check that both sets of operands are equal let mut spanless_eq = SpanlessEq::new(cx); let same_fixed_operands = spanless_eq.eq_expr(lhs1, lhs2) && spanless_eq.eq_expr(rhs1, rhs2); let same_transposed_operands = spanless_eq.eq_expr(lhs1, rhs2) && spanless_eq.eq_expr(rhs1, lhs2); if!same_fixed_operands &&!same_transposed_operands { return; } // Check that if the operation is the same, either it's not `==` or the operands are transposed if kind1.node == kind2.node { if kind1.node == BinOpKind::Eq { return; } if!same_transposed_operands { return; } } // Check that the type being compared implements `core::cmp::Ord` let ty = cx.typeck_results().expr_ty(lhs1); let is_ord = get_trait_def_id(cx, &paths::ORD).map_or(false, |id| implements_trait(cx, ty, id, &[])); if!is_ord { return; } } else { // We only care about comparison chains return; } } span_lint_and_help( cx, COMPARISON_CHAIN, expr.span, "`if` chain can be rewritten with `match`", None, "consider rewriting the `if` chain to use `cmp` and `match`", ); } } fn kind_is_cmp(kind: BinOpKind) -> bool { matches!(kind, BinOpKind::Lt | BinOpKind::Gt | BinOpKind::Eq) }
random_line_split
cell.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Shareable mutable containers. //! //! Values of the `Cell` and `RefCell` types may be mutated through //! shared references (i.e. the common `&T` type), whereas most Rust //! types can only be mutated through unique (`&mut T`) references. We //! say that `Cell` and `RefCell` provide *interior mutability*, in //! contrast with typical Rust types that exhibit *inherited //! mutability*. //! //! Cell types come in two flavors: `Cell` and `RefCell`. `Cell` //! provides `get` and `set` methods that change the //! interior value with a single method call. `Cell` though is only //! compatible with types that implement `Copy`. For other types, //! one must use the `RefCell` type, acquiring a write lock before //! mutating. //! //! `RefCell` uses Rust's lifetimes to implement *dynamic borrowing*, //! a process whereby one can claim temporary, exclusive, mutable //! access to the inner value. Borrows for `RefCell`s are tracked *at //! runtime*, unlike Rust's native reference types which are entirely //! tracked statically, at compile time. Because `RefCell` borrows are //! dynamic it is possible to attempt to borrow a value that is //! already mutably borrowed; when this happens it results in task //! panic. //! //! # When to choose interior mutability //! //! The more common inherited mutability, where one must have unique //! access to mutate a value, is one of the key language elements that //! enables Rust to reason strongly about pointer aliasing, statically //! preventing crash bugs. Because of that, inherited mutability is //! preferred, and interior mutability is something of a last //! resort. Since cell types enable mutation where it would otherwise //! be disallowed though, there are occasions when interior //! mutability might be appropriate, or even *must* be used, e.g. //! //! * Introducing inherited mutability roots to shared types. //! * Implementation details of logically-immutable methods. //! * Mutating implementations of `clone`. //! //! ## Introducing inherited mutability roots to shared types //! //! Shared smart pointer types, including `Rc` and `Arc`, provide //! containers that can be cloned and shared between multiple parties. //! Because the contained values may be multiply-aliased, they can //! only be borrowed as shared references, not mutable references. //! Without cells it would be impossible to mutate data inside of //! shared boxes at all! //! //! It's very common then to put a `RefCell` inside shared pointer //! types to reintroduce mutability: //! //! ``` //! use std::collections::HashMap; //! use std::cell::RefCell; //! use std::rc::Rc; //! //! fn main() { //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); //! shared_map.borrow_mut().insert("africa", 92388i); //! shared_map.borrow_mut().insert("kyoto", 11837i); //! shared_map.borrow_mut().insert("piccadilly", 11826i); //! shared_map.borrow_mut().insert("marbles", 38i); //! } //! ``` //! //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that //! there is mutation happening "under the hood". This may be because //! logically the operation is immutable, but e.g. caching forces the //! implementation to perform mutation; or because you must employ //! mutation to implement a trait method that was originally defined //! to take `&self`. //! //! ``` //! use std::cell::RefCell; //! //! struct Graph { //! edges: Vec<(uint, uint)>, //! span_tree_cache: RefCell<Option<Vec<(uint, uint)>>> //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(uint, uint)> { //! // Create a new scope to contain the lifetime of the //! // dynamic borrow //! { //! // Take a reference to the inside of cache cell //! let mut cache = self.span_tree_cache.borrow_mut(); //! if cache.is_some() { //! return cache.as_ref().unwrap().clone(); //! } //! //! let span_tree = self.calc_span_tree(); //! *cache = Some(span_tree); //! } //! //! // Recursive call to return the just-cached value. //! // Note that if we had not let the previous borrow //! // of the cache fall out of scope then the subsequent //! // recursive borrow would cause a dynamic task panic. //! // This is the major hazard of using `RefCell`. //! self.minimum_spanning_tree() //! } //! # fn calc_span_tree(&self) -> Vec<(uint, uint)> { vec![] } //! } //! # fn main() { } //! ``` //! //! ## Mutating implementations of `clone` //! //! This is simply a special - but common - case of the previous: //! hiding mutability for operations that appear to be immutable. //! The `clone` method is expected to not change the source value, and //! is declared to take `&self`, not `&mut self`. Therefore any //! mutation that happens in the `clone` method must use cell //! types. For example, `Rc` maintains its reference counts within a //! `Cell`. //! //! ``` //! use std::cell::Cell; //! //! struct Rc<T> { //! ptr: *mut RcBox<T> //! } //! //! struct RcBox<T> { //! value: T, //! refcount: Cell<uint> //! } //! //! impl<T> Clone for Rc<T> { //! fn clone(&self) -> Rc<T> { //! unsafe { //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1); //! Rc { ptr: self.ptr } //! } //! } //! } //! ``` //! // FIXME: Explain difference between Cell and RefCell // FIXME: Downsides to interior mutability // FIXME: Can't be shared between threads. Dynamic borrows // FIXME: Relationship to Atomic types and RWLock use clone::Clone; use cmp::PartialEq; use default::Default; use kinds::{marker, Copy}; use ops::{Deref, DerefMut, Drop}; use option::{None, Option, Some}; /// A mutable memory location that admits only `Copy` data. #[unstable = "likely to be renamed; otherwise stable"] pub struct Cell<T> { value: UnsafeCell<T>, noshare: marker::NoSync, } impl<T:Copy> Cell<T> { /// Creates a new `Cell` containing the given value. #[stable] pub fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), noshare: marker::NoSync, } } /// Returns a copy of the contained value. #[inline] #[stable] pub fn get(&self) -> T { unsafe{ *self.value.get() } } /// Sets the contained value. #[inline] #[stable] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } /// Get a reference to the underlying `UnsafeCell`. /// /// This can be used to circumvent `Cell`'s safety checks. /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] #[experimental] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[unstable = "waiting for `Clone` trait to become stable"] impl<T:Copy> Clone for Cell<T> { fn clone(&self) -> Cell<T> { Cell::new(self.get()) } } #[unstable] impl<T:Default + Copy> Default for Cell<T> { fn default() -> Cell<T> { Cell::new(Default::default()) } } #[unstable = "waiting for `PartialEq` trait to become stable"] impl<T:PartialEq + Copy> PartialEq for Cell<T> { fn eq(&self, other: &Cell<T>) -> bool { self.get() == other.get() } } /// A mutable memory location with dynamically checked borrow rules #[unstable = "likely to be renamed; otherwise stable"] pub struct RefCell<T> { value: UnsafeCell<T>, borrow: Cell<BorrowFlag>, nocopy: marker::NoCopy, noshare: marker::NoSync, } // Values [1, MAX-1] represent the number of `Ref` active // (will not outgrow its range since `uint` is the size of the address space) type BorrowFlag = uint; const UNUSED: BorrowFlag = 0; const WRITING: BorrowFlag = -1; impl<T> RefCell<T> { /// Create a new `RefCell` containing `value` #[stable] pub fn new(value: T) -> RefCell<T> { RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED), nocopy: marker::NoCopy, noshare: marker::NoSync, } } /// Consumes the `RefCell`, returning the wrapped value. #[unstable = "may be renamed, depending on global conventions"] pub fn unwrap(self) -> T { debug_assert!(self.borrow.get() == UNUSED); unsafe{self.value.unwrap()} } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { match self.borrow.get() { WRITING => None, borrow => { self.borrow.set(borrow + 1); Some(Ref { _parent: self }) } } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Panics /// /// Panics if the value is currently mutably borrowed. #[unstable] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { Some(ptr) => ptr, None => panic!("RefCell<T> already mutably borrowed") } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { match self.borrow.get() { UNUSED => { self.borrow.set(WRITING); Some(RefMut { _parent: self }) }, _ => None } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Panics /// /// Panics if the value is currently borrowed. #[unstable] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { match self.try_borrow_mut() { Some(ptr) => ptr, None => panic!("RefCell<T> already borrowed") } } /// Get a reference to the underlying `UnsafeCell`. /// /// This can be used to circumvent `RefCell`'s safety checks. /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] #[experimental] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[unstable = "waiting for `Clone` to become stable"] impl<T: Clone> Clone for RefCell<T> { fn clone(&self) -> RefCell<T> { RefCell::new(self.borrow().clone()) } } #[unstable] impl<T:Default> Default for RefCell<T> { fn default() -> RefCell<T> { RefCell::new(Default::default()) } } #[unstable = "waiting for `PartialEq` to become stable"] impl<T: PartialEq> PartialEq for RefCell<T> { fn eq(&self, other: &RefCell<T>) -> bool { *self.borrow() == *other.borrow() } } /// Wraps a borrowed reference to a value in a `RefCell` box. #[unstable] pub struct
<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for Ref<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._parent.borrow.set(borrow - 1); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for Ref<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } /// Copy a `Ref`. /// /// The `RefCell` is already immutably borrowed, so this cannot fail. /// /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. #[experimental = "likely to be moved to a method, pending language changes"] pub fn clone_ref<'b, T>(orig: &Ref<'b, T>) -> Ref<'b, T> { // Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = orig._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); orig._parent.borrow.set(borrow + 1); Ref { _parent: orig._parent, } } /// Wraps a mutable borrowed reference to a value in a `RefCell` box. #[unstable] pub struct RefMut<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for RefMut<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow == WRITING); self._parent.borrow.set(UNUSED); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for RefMut<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } #[unstable = "waiting for `DerefMut` to become stable"] impl<'b, T> DerefMut<T> for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self._parent.value.get() } } } /// The core primitive for interior mutability in Rust. /// /// `UnsafeCell` type that wraps a type T and indicates unsafe interior /// operations on the wrapped type. Types with an `UnsafeCell<T>` field are /// considered to have an *unsafe interior*. The `UnsafeCell` type is the only /// legal way to obtain aliasable data that is considered mutable. In general, /// transmuting an &T type into an &mut T is considered undefined behavior. /// /// Although it is possible to put an `UnsafeCell<T>` into static item, it is /// not permitted to take the address of the static item if the item is not /// declared as mutable. This rule exists because immutable static items are /// stored in read-only memory, and thus any attempt to mutate their interior /// can cause segfaults. Immutable static items containing `UnsafeCell<T>` /// instances are still useful as read-only initializers, however, so we do not /// forbid them altogether. /// /// Types like `Cell` and `RefCell` use this type to wrap their internal data. /// /// `UnsafeCell` doesn't opt-out from any kind, instead, types with an /// `UnsafeCell` interior are expected to opt-out from kinds themselves. /// /// # Example: /// /// ```rust /// use std::cell::UnsafeCell; /// use std::kinds::marker; /// /// struct NotThreadSafe<T> { /// value: UnsafeCell<T>, /// marker: marker::NoSync /// } /// ``` /// /// **NOTE:** `UnsafeCell<T>` fields are public to allow static initializers. It /// is not recommended to access its fields directly, `get` should be used /// instead. #[lang="unsafe"] #[unstable = "this type may be renamed in the future"] pub struct UnsafeCell<T> { /// Wrapped value /// /// This field should not be accessed directly, it is made public for static /// initializers. #[unstable] pub value: T, } impl<T> UnsafeCell<T> { /// Construct a new instance of `UnsafeCell` which will wrap the specified /// value. /// /// All access to the inner value through methods is `unsafe`, and it is /// highly discouraged to access the fields directly. #[stable] pub fn new(value: T) -> UnsafeCell<T> { UnsafeCell { value: value } } /// Gets a mutable pointer to the wrapped value. /// /// This function is unsafe as the pointer returned is an unsafe pointer and /// no guarantees are made about the aliasing of the pointers being handed /// out in this or other tasks. #[inline] #[unstable = "conventions around acquiring an inner reference are still \ under development"] pub unsafe fn get(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value /// /// This function is unsafe because there is no guarantee that this or other /// tasks are currently inspecting the inner value. #[inline] #[unstable = "conventions around the name `unwrap` are still under \ development"] pub unsafe fn unwrap(self) -> T { self.value } }
Ref
identifier_name
cell.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Shareable mutable containers. //! //! Values of the `Cell` and `RefCell` types may be mutated through //! shared references (i.e. the common `&T` type), whereas most Rust //! types can only be mutated through unique (`&mut T`) references. We //! say that `Cell` and `RefCell` provide *interior mutability*, in //! contrast with typical Rust types that exhibit *inherited //! mutability*. //! //! Cell types come in two flavors: `Cell` and `RefCell`. `Cell` //! provides `get` and `set` methods that change the //! interior value with a single method call. `Cell` though is only //! compatible with types that implement `Copy`. For other types, //! one must use the `RefCell` type, acquiring a write lock before //! mutating. //! //! `RefCell` uses Rust's lifetimes to implement *dynamic borrowing*, //! a process whereby one can claim temporary, exclusive, mutable //! access to the inner value. Borrows for `RefCell`s are tracked *at //! runtime*, unlike Rust's native reference types which are entirely //! tracked statically, at compile time. Because `RefCell` borrows are //! dynamic it is possible to attempt to borrow a value that is //! already mutably borrowed; when this happens it results in task //! panic. //! //! # When to choose interior mutability //! //! The more common inherited mutability, where one must have unique //! access to mutate a value, is one of the key language elements that //! enables Rust to reason strongly about pointer aliasing, statically //! preventing crash bugs. Because of that, inherited mutability is //! preferred, and interior mutability is something of a last //! resort. Since cell types enable mutation where it would otherwise //! be disallowed though, there are occasions when interior //! mutability might be appropriate, or even *must* be used, e.g. //! //! * Introducing inherited mutability roots to shared types. //! * Implementation details of logically-immutable methods. //! * Mutating implementations of `clone`. //! //! ## Introducing inherited mutability roots to shared types //! //! Shared smart pointer types, including `Rc` and `Arc`, provide //! containers that can be cloned and shared between multiple parties. //! Because the contained values may be multiply-aliased, they can //! only be borrowed as shared references, not mutable references. //! Without cells it would be impossible to mutate data inside of //! shared boxes at all! //! //! It's very common then to put a `RefCell` inside shared pointer //! types to reintroduce mutability: //! //! ``` //! use std::collections::HashMap; //! use std::cell::RefCell; //! use std::rc::Rc; //! //! fn main() { //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); //! shared_map.borrow_mut().insert("africa", 92388i); //! shared_map.borrow_mut().insert("kyoto", 11837i); //! shared_map.borrow_mut().insert("piccadilly", 11826i); //! shared_map.borrow_mut().insert("marbles", 38i); //! } //! ``` //! //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that //! there is mutation happening "under the hood". This may be because //! logically the operation is immutable, but e.g. caching forces the //! implementation to perform mutation; or because you must employ //! mutation to implement a trait method that was originally defined //! to take `&self`. //! //! ``` //! use std::cell::RefCell; //! //! struct Graph { //! edges: Vec<(uint, uint)>, //! span_tree_cache: RefCell<Option<Vec<(uint, uint)>>> //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(uint, uint)> { //! // Create a new scope to contain the lifetime of the //! // dynamic borrow //! { //! // Take a reference to the inside of cache cell //! let mut cache = self.span_tree_cache.borrow_mut(); //! if cache.is_some() { //! return cache.as_ref().unwrap().clone(); //! } //! //! let span_tree = self.calc_span_tree(); //! *cache = Some(span_tree); //! } //!
//! // Recursive call to return the just-cached value. //! // Note that if we had not let the previous borrow //! // of the cache fall out of scope then the subsequent //! // recursive borrow would cause a dynamic task panic. //! // This is the major hazard of using `RefCell`. //! self.minimum_spanning_tree() //! } //! # fn calc_span_tree(&self) -> Vec<(uint, uint)> { vec![] } //! } //! # fn main() { } //! ``` //! //! ## Mutating implementations of `clone` //! //! This is simply a special - but common - case of the previous: //! hiding mutability for operations that appear to be immutable. //! The `clone` method is expected to not change the source value, and //! is declared to take `&self`, not `&mut self`. Therefore any //! mutation that happens in the `clone` method must use cell //! types. For example, `Rc` maintains its reference counts within a //! `Cell`. //! //! ``` //! use std::cell::Cell; //! //! struct Rc<T> { //! ptr: *mut RcBox<T> //! } //! //! struct RcBox<T> { //! value: T, //! refcount: Cell<uint> //! } //! //! impl<T> Clone for Rc<T> { //! fn clone(&self) -> Rc<T> { //! unsafe { //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1); //! Rc { ptr: self.ptr } //! } //! } //! } //! ``` //! // FIXME: Explain difference between Cell and RefCell // FIXME: Downsides to interior mutability // FIXME: Can't be shared between threads. Dynamic borrows // FIXME: Relationship to Atomic types and RWLock use clone::Clone; use cmp::PartialEq; use default::Default; use kinds::{marker, Copy}; use ops::{Deref, DerefMut, Drop}; use option::{None, Option, Some}; /// A mutable memory location that admits only `Copy` data. #[unstable = "likely to be renamed; otherwise stable"] pub struct Cell<T> { value: UnsafeCell<T>, noshare: marker::NoSync, } impl<T:Copy> Cell<T> { /// Creates a new `Cell` containing the given value. #[stable] pub fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), noshare: marker::NoSync, } } /// Returns a copy of the contained value. #[inline] #[stable] pub fn get(&self) -> T { unsafe{ *self.value.get() } } /// Sets the contained value. #[inline] #[stable] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } /// Get a reference to the underlying `UnsafeCell`. /// /// This can be used to circumvent `Cell`'s safety checks. /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] #[experimental] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[unstable = "waiting for `Clone` trait to become stable"] impl<T:Copy> Clone for Cell<T> { fn clone(&self) -> Cell<T> { Cell::new(self.get()) } } #[unstable] impl<T:Default + Copy> Default for Cell<T> { fn default() -> Cell<T> { Cell::new(Default::default()) } } #[unstable = "waiting for `PartialEq` trait to become stable"] impl<T:PartialEq + Copy> PartialEq for Cell<T> { fn eq(&self, other: &Cell<T>) -> bool { self.get() == other.get() } } /// A mutable memory location with dynamically checked borrow rules #[unstable = "likely to be renamed; otherwise stable"] pub struct RefCell<T> { value: UnsafeCell<T>, borrow: Cell<BorrowFlag>, nocopy: marker::NoCopy, noshare: marker::NoSync, } // Values [1, MAX-1] represent the number of `Ref` active // (will not outgrow its range since `uint` is the size of the address space) type BorrowFlag = uint; const UNUSED: BorrowFlag = 0; const WRITING: BorrowFlag = -1; impl<T> RefCell<T> { /// Create a new `RefCell` containing `value` #[stable] pub fn new(value: T) -> RefCell<T> { RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED), nocopy: marker::NoCopy, noshare: marker::NoSync, } } /// Consumes the `RefCell`, returning the wrapped value. #[unstable = "may be renamed, depending on global conventions"] pub fn unwrap(self) -> T { debug_assert!(self.borrow.get() == UNUSED); unsafe{self.value.unwrap()} } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { match self.borrow.get() { WRITING => None, borrow => { self.borrow.set(borrow + 1); Some(Ref { _parent: self }) } } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Panics /// /// Panics if the value is currently mutably borrowed. #[unstable] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { Some(ptr) => ptr, None => panic!("RefCell<T> already mutably borrowed") } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { match self.borrow.get() { UNUSED => { self.borrow.set(WRITING); Some(RefMut { _parent: self }) }, _ => None } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Panics /// /// Panics if the value is currently borrowed. #[unstable] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { match self.try_borrow_mut() { Some(ptr) => ptr, None => panic!("RefCell<T> already borrowed") } } /// Get a reference to the underlying `UnsafeCell`. /// /// This can be used to circumvent `RefCell`'s safety checks. /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] #[experimental] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[unstable = "waiting for `Clone` to become stable"] impl<T: Clone> Clone for RefCell<T> { fn clone(&self) -> RefCell<T> { RefCell::new(self.borrow().clone()) } } #[unstable] impl<T:Default> Default for RefCell<T> { fn default() -> RefCell<T> { RefCell::new(Default::default()) } } #[unstable = "waiting for `PartialEq` to become stable"] impl<T: PartialEq> PartialEq for RefCell<T> { fn eq(&self, other: &RefCell<T>) -> bool { *self.borrow() == *other.borrow() } } /// Wraps a borrowed reference to a value in a `RefCell` box. #[unstable] pub struct Ref<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for Ref<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._parent.borrow.set(borrow - 1); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for Ref<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } /// Copy a `Ref`. /// /// The `RefCell` is already immutably borrowed, so this cannot fail. /// /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. #[experimental = "likely to be moved to a method, pending language changes"] pub fn clone_ref<'b, T>(orig: &Ref<'b, T>) -> Ref<'b, T> { // Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = orig._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); orig._parent.borrow.set(borrow + 1); Ref { _parent: orig._parent, } } /// Wraps a mutable borrowed reference to a value in a `RefCell` box. #[unstable] pub struct RefMut<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for RefMut<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow == WRITING); self._parent.borrow.set(UNUSED); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for RefMut<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } #[unstable = "waiting for `DerefMut` to become stable"] impl<'b, T> DerefMut<T> for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self._parent.value.get() } } } /// The core primitive for interior mutability in Rust. /// /// `UnsafeCell` type that wraps a type T and indicates unsafe interior /// operations on the wrapped type. Types with an `UnsafeCell<T>` field are /// considered to have an *unsafe interior*. The `UnsafeCell` type is the only /// legal way to obtain aliasable data that is considered mutable. In general, /// transmuting an &T type into an &mut T is considered undefined behavior. /// /// Although it is possible to put an `UnsafeCell<T>` into static item, it is /// not permitted to take the address of the static item if the item is not /// declared as mutable. This rule exists because immutable static items are /// stored in read-only memory, and thus any attempt to mutate their interior /// can cause segfaults. Immutable static items containing `UnsafeCell<T>` /// instances are still useful as read-only initializers, however, so we do not /// forbid them altogether. /// /// Types like `Cell` and `RefCell` use this type to wrap their internal data. /// /// `UnsafeCell` doesn't opt-out from any kind, instead, types with an /// `UnsafeCell` interior are expected to opt-out from kinds themselves. /// /// # Example: /// /// ```rust /// use std::cell::UnsafeCell; /// use std::kinds::marker; /// /// struct NotThreadSafe<T> { /// value: UnsafeCell<T>, /// marker: marker::NoSync /// } /// ``` /// /// **NOTE:** `UnsafeCell<T>` fields are public to allow static initializers. It /// is not recommended to access its fields directly, `get` should be used /// instead. #[lang="unsafe"] #[unstable = "this type may be renamed in the future"] pub struct UnsafeCell<T> { /// Wrapped value /// /// This field should not be accessed directly, it is made public for static /// initializers. #[unstable] pub value: T, } impl<T> UnsafeCell<T> { /// Construct a new instance of `UnsafeCell` which will wrap the specified /// value. /// /// All access to the inner value through methods is `unsafe`, and it is /// highly discouraged to access the fields directly. #[stable] pub fn new(value: T) -> UnsafeCell<T> { UnsafeCell { value: value } } /// Gets a mutable pointer to the wrapped value. /// /// This function is unsafe as the pointer returned is an unsafe pointer and /// no guarantees are made about the aliasing of the pointers being handed /// out in this or other tasks. #[inline] #[unstable = "conventions around acquiring an inner reference are still \ under development"] pub unsafe fn get(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value /// /// This function is unsafe because there is no guarantee that this or other /// tasks are currently inspecting the inner value. #[inline] #[unstable = "conventions around the name `unwrap` are still under \ development"] pub unsafe fn unwrap(self) -> T { self.value } }
random_line_split
cell.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Shareable mutable containers. //! //! Values of the `Cell` and `RefCell` types may be mutated through //! shared references (i.e. the common `&T` type), whereas most Rust //! types can only be mutated through unique (`&mut T`) references. We //! say that `Cell` and `RefCell` provide *interior mutability*, in //! contrast with typical Rust types that exhibit *inherited //! mutability*. //! //! Cell types come in two flavors: `Cell` and `RefCell`. `Cell` //! provides `get` and `set` methods that change the //! interior value with a single method call. `Cell` though is only //! compatible with types that implement `Copy`. For other types, //! one must use the `RefCell` type, acquiring a write lock before //! mutating. //! //! `RefCell` uses Rust's lifetimes to implement *dynamic borrowing*, //! a process whereby one can claim temporary, exclusive, mutable //! access to the inner value. Borrows for `RefCell`s are tracked *at //! runtime*, unlike Rust's native reference types which are entirely //! tracked statically, at compile time. Because `RefCell` borrows are //! dynamic it is possible to attempt to borrow a value that is //! already mutably borrowed; when this happens it results in task //! panic. //! //! # When to choose interior mutability //! //! The more common inherited mutability, where one must have unique //! access to mutate a value, is one of the key language elements that //! enables Rust to reason strongly about pointer aliasing, statically //! preventing crash bugs. Because of that, inherited mutability is //! preferred, and interior mutability is something of a last //! resort. Since cell types enable mutation where it would otherwise //! be disallowed though, there are occasions when interior //! mutability might be appropriate, or even *must* be used, e.g. //! //! * Introducing inherited mutability roots to shared types. //! * Implementation details of logically-immutable methods. //! * Mutating implementations of `clone`. //! //! ## Introducing inherited mutability roots to shared types //! //! Shared smart pointer types, including `Rc` and `Arc`, provide //! containers that can be cloned and shared between multiple parties. //! Because the contained values may be multiply-aliased, they can //! only be borrowed as shared references, not mutable references. //! Without cells it would be impossible to mutate data inside of //! shared boxes at all! //! //! It's very common then to put a `RefCell` inside shared pointer //! types to reintroduce mutability: //! //! ``` //! use std::collections::HashMap; //! use std::cell::RefCell; //! use std::rc::Rc; //! //! fn main() { //! let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); //! shared_map.borrow_mut().insert("africa", 92388i); //! shared_map.borrow_mut().insert("kyoto", 11837i); //! shared_map.borrow_mut().insert("piccadilly", 11826i); //! shared_map.borrow_mut().insert("marbles", 38i); //! } //! ``` //! //! ## Implementation details of logically-immutable methods //! //! Occasionally it may be desirable not to expose in an API that //! there is mutation happening "under the hood". This may be because //! logically the operation is immutable, but e.g. caching forces the //! implementation to perform mutation; or because you must employ //! mutation to implement a trait method that was originally defined //! to take `&self`. //! //! ``` //! use std::cell::RefCell; //! //! struct Graph { //! edges: Vec<(uint, uint)>, //! span_tree_cache: RefCell<Option<Vec<(uint, uint)>>> //! } //! //! impl Graph { //! fn minimum_spanning_tree(&self) -> Vec<(uint, uint)> { //! // Create a new scope to contain the lifetime of the //! // dynamic borrow //! { //! // Take a reference to the inside of cache cell //! let mut cache = self.span_tree_cache.borrow_mut(); //! if cache.is_some() { //! return cache.as_ref().unwrap().clone(); //! } //! //! let span_tree = self.calc_span_tree(); //! *cache = Some(span_tree); //! } //! //! // Recursive call to return the just-cached value. //! // Note that if we had not let the previous borrow //! // of the cache fall out of scope then the subsequent //! // recursive borrow would cause a dynamic task panic. //! // This is the major hazard of using `RefCell`. //! self.minimum_spanning_tree() //! } //! # fn calc_span_tree(&self) -> Vec<(uint, uint)> { vec![] } //! } //! # fn main() { } //! ``` //! //! ## Mutating implementations of `clone` //! //! This is simply a special - but common - case of the previous: //! hiding mutability for operations that appear to be immutable. //! The `clone` method is expected to not change the source value, and //! is declared to take `&self`, not `&mut self`. Therefore any //! mutation that happens in the `clone` method must use cell //! types. For example, `Rc` maintains its reference counts within a //! `Cell`. //! //! ``` //! use std::cell::Cell; //! //! struct Rc<T> { //! ptr: *mut RcBox<T> //! } //! //! struct RcBox<T> { //! value: T, //! refcount: Cell<uint> //! } //! //! impl<T> Clone for Rc<T> { //! fn clone(&self) -> Rc<T> { //! unsafe { //! (*self.ptr).refcount.set((*self.ptr).refcount.get() + 1); //! Rc { ptr: self.ptr } //! } //! } //! } //! ``` //! // FIXME: Explain difference between Cell and RefCell // FIXME: Downsides to interior mutability // FIXME: Can't be shared between threads. Dynamic borrows // FIXME: Relationship to Atomic types and RWLock use clone::Clone; use cmp::PartialEq; use default::Default; use kinds::{marker, Copy}; use ops::{Deref, DerefMut, Drop}; use option::{None, Option, Some}; /// A mutable memory location that admits only `Copy` data. #[unstable = "likely to be renamed; otherwise stable"] pub struct Cell<T> { value: UnsafeCell<T>, noshare: marker::NoSync, } impl<T:Copy> Cell<T> { /// Creates a new `Cell` containing the given value. #[stable] pub fn new(value: T) -> Cell<T> { Cell { value: UnsafeCell::new(value), noshare: marker::NoSync, } } /// Returns a copy of the contained value. #[inline] #[stable] pub fn get(&self) -> T { unsafe{ *self.value.get() } } /// Sets the contained value. #[inline] #[stable] pub fn set(&self, value: T) { unsafe { *self.value.get() = value; } } /// Get a reference to the underlying `UnsafeCell`. /// /// This can be used to circumvent `Cell`'s safety checks. /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] #[experimental] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[unstable = "waiting for `Clone` trait to become stable"] impl<T:Copy> Clone for Cell<T> { fn clone(&self) -> Cell<T> { Cell::new(self.get()) } } #[unstable] impl<T:Default + Copy> Default for Cell<T> { fn default() -> Cell<T> { Cell::new(Default::default()) } } #[unstable = "waiting for `PartialEq` trait to become stable"] impl<T:PartialEq + Copy> PartialEq for Cell<T> { fn eq(&self, other: &Cell<T>) -> bool { self.get() == other.get() } } /// A mutable memory location with dynamically checked borrow rules #[unstable = "likely to be renamed; otherwise stable"] pub struct RefCell<T> { value: UnsafeCell<T>, borrow: Cell<BorrowFlag>, nocopy: marker::NoCopy, noshare: marker::NoSync, } // Values [1, MAX-1] represent the number of `Ref` active // (will not outgrow its range since `uint` is the size of the address space) type BorrowFlag = uint; const UNUSED: BorrowFlag = 0; const WRITING: BorrowFlag = -1; impl<T> RefCell<T> { /// Create a new `RefCell` containing `value` #[stable] pub fn new(value: T) -> RefCell<T> { RefCell { value: UnsafeCell::new(value), borrow: Cell::new(UNUSED), nocopy: marker::NoCopy, noshare: marker::NoSync, } } /// Consumes the `RefCell`, returning the wrapped value. #[unstable = "may be renamed, depending on global conventions"] pub fn unwrap(self) -> T { debug_assert!(self.borrow.get() == UNUSED); unsafe{self.value.unwrap()} } /// Attempts to immutably borrow the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// Returns `None` if the value is currently mutably borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow<'a>(&'a self) -> Option<Ref<'a, T>> { match self.borrow.get() { WRITING => None, borrow => { self.borrow.set(borrow + 1); Some(Ref { _parent: self }) } } } /// Immutably borrows the wrapped value. /// /// The borrow lasts until the returned `Ref` exits scope. Multiple /// immutable borrows can be taken out at the same time. /// /// # Panics /// /// Panics if the value is currently mutably borrowed. #[unstable] pub fn borrow<'a>(&'a self) -> Ref<'a, T> { match self.try_borrow() { Some(ptr) => ptr, None => panic!("RefCell<T> already mutably borrowed") } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// Returns `None` if the value is currently borrowed. #[unstable = "may be renamed, depending on global conventions"] pub fn try_borrow_mut<'a>(&'a self) -> Option<RefMut<'a, T>> { match self.borrow.get() { UNUSED => { self.borrow.set(WRITING); Some(RefMut { _parent: self }) }, _ => None } } /// Mutably borrows the wrapped value. /// /// The borrow lasts until the returned `RefMut` exits scope. The value /// cannot be borrowed while this borrow is active. /// /// # Panics /// /// Panics if the value is currently borrowed. #[unstable] pub fn borrow_mut<'a>(&'a self) -> RefMut<'a, T> { match self.try_borrow_mut() { Some(ptr) => ptr, None => panic!("RefCell<T> already borrowed") } } /// Get a reference to the underlying `UnsafeCell`. /// /// This can be used to circumvent `RefCell`'s safety checks. /// /// This function is `unsafe` because `UnsafeCell`'s field is public. #[inline] #[experimental] pub unsafe fn as_unsafe_cell<'a>(&'a self) -> &'a UnsafeCell<T> { &self.value } } #[unstable = "waiting for `Clone` to become stable"] impl<T: Clone> Clone for RefCell<T> { fn clone(&self) -> RefCell<T> { RefCell::new(self.borrow().clone()) } } #[unstable] impl<T:Default> Default for RefCell<T> { fn default() -> RefCell<T> { RefCell::new(Default::default()) } } #[unstable = "waiting for `PartialEq` to become stable"] impl<T: PartialEq> PartialEq for RefCell<T> { fn eq(&self, other: &RefCell<T>) -> bool { *self.borrow() == *other.borrow() } } /// Wraps a borrowed reference to a value in a `RefCell` box. #[unstable] pub struct Ref<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for Ref<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); self._parent.borrow.set(borrow - 1); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for Ref<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T
} /// Copy a `Ref`. /// /// The `RefCell` is already immutably borrowed, so this cannot fail. /// /// A `Clone` implementation would interfere with the widespread /// use of `r.borrow().clone()` to clone the contents of a `RefCell`. #[experimental = "likely to be moved to a method, pending language changes"] pub fn clone_ref<'b, T>(orig: &Ref<'b, T>) -> Ref<'b, T> { // Since this Ref exists, we know the borrow flag // is not set to WRITING. let borrow = orig._parent.borrow.get(); debug_assert!(borrow!= WRITING && borrow!= UNUSED); orig._parent.borrow.set(borrow + 1); Ref { _parent: orig._parent, } } /// Wraps a mutable borrowed reference to a value in a `RefCell` box. #[unstable] pub struct RefMut<'b, T:'b> { // FIXME #12808: strange name to try to avoid interfering with // field accesses of the contained type via Deref _parent: &'b RefCell<T> } #[unsafe_destructor] #[unstable] impl<'b, T> Drop for RefMut<'b, T> { fn drop(&mut self) { let borrow = self._parent.borrow.get(); debug_assert!(borrow == WRITING); self._parent.borrow.set(UNUSED); } } #[unstable = "waiting for `Deref` to become stable"] impl<'b, T> Deref<T> for RefMut<'b, T> { #[inline] fn deref<'a>(&'a self) -> &'a T { unsafe { &*self._parent.value.get() } } } #[unstable = "waiting for `DerefMut` to become stable"] impl<'b, T> DerefMut<T> for RefMut<'b, T> { #[inline] fn deref_mut<'a>(&'a mut self) -> &'a mut T { unsafe { &mut *self._parent.value.get() } } } /// The core primitive for interior mutability in Rust. /// /// `UnsafeCell` type that wraps a type T and indicates unsafe interior /// operations on the wrapped type. Types with an `UnsafeCell<T>` field are /// considered to have an *unsafe interior*. The `UnsafeCell` type is the only /// legal way to obtain aliasable data that is considered mutable. In general, /// transmuting an &T type into an &mut T is considered undefined behavior. /// /// Although it is possible to put an `UnsafeCell<T>` into static item, it is /// not permitted to take the address of the static item if the item is not /// declared as mutable. This rule exists because immutable static items are /// stored in read-only memory, and thus any attempt to mutate their interior /// can cause segfaults. Immutable static items containing `UnsafeCell<T>` /// instances are still useful as read-only initializers, however, so we do not /// forbid them altogether. /// /// Types like `Cell` and `RefCell` use this type to wrap their internal data. /// /// `UnsafeCell` doesn't opt-out from any kind, instead, types with an /// `UnsafeCell` interior are expected to opt-out from kinds themselves. /// /// # Example: /// /// ```rust /// use std::cell::UnsafeCell; /// use std::kinds::marker; /// /// struct NotThreadSafe<T> { /// value: UnsafeCell<T>, /// marker: marker::NoSync /// } /// ``` /// /// **NOTE:** `UnsafeCell<T>` fields are public to allow static initializers. It /// is not recommended to access its fields directly, `get` should be used /// instead. #[lang="unsafe"] #[unstable = "this type may be renamed in the future"] pub struct UnsafeCell<T> { /// Wrapped value /// /// This field should not be accessed directly, it is made public for static /// initializers. #[unstable] pub value: T, } impl<T> UnsafeCell<T> { /// Construct a new instance of `UnsafeCell` which will wrap the specified /// value. /// /// All access to the inner value through methods is `unsafe`, and it is /// highly discouraged to access the fields directly. #[stable] pub fn new(value: T) -> UnsafeCell<T> { UnsafeCell { value: value } } /// Gets a mutable pointer to the wrapped value. /// /// This function is unsafe as the pointer returned is an unsafe pointer and /// no guarantees are made about the aliasing of the pointers being handed /// out in this or other tasks. #[inline] #[unstable = "conventions around acquiring an inner reference are still \ under development"] pub unsafe fn get(&self) -> *mut T { &self.value as *const T as *mut T } /// Unwraps the value /// /// This function is unsafe because there is no guarantee that this or other /// tasks are currently inspecting the inner value. #[inline] #[unstable = "conventions around the name `unwrap` are still under \ development"] pub unsafe fn unwrap(self) -> T { self.value } }
{ unsafe { &*self._parent.value.get() } }
identifier_body
gradient_descent.rs
extern crate sensei_math; use sensei_math::math::Mat; use std::f32; fn dot(v1:&[f32], v2:&[f32]) -> f32 { assert!(v1.len() == v2.len()); //TODO: Do some performance comparisons between this form and a // for loop with an accumulator. v1.iter() .zip(v2.iter()) .map(|(&x,&y)| x*y) .fold(0f32, |sum, x| sum + x) // sum() cannot infer the type... } pub fn batch(alpha:f32, features:&Mat<f32>, labels:&[f32]) -> Vec<f32> { assert!(features.row_count > 0, "Expected at least one sample."); let m = labels.len(); let mut weights = vec! [0.0; features[0].len()]; let feature_count = weights.len(); let epsilon = 0.000_000_0001f32; let mut prev_error = f32::MAX; let mut cumulative_error = 0.0f32; // Continue descending until we are no longer making progress loop { for j in 0..m { let ref x:Vec<f32> = features[j]; let error = dot(&weights, &x) - labels[j]; for i in 0..feature_count { weights[i] = weights[i] - alpha * error * x[i]; } cumulative_error = cumulative_error + error*error; } if prev_error - cumulative_error < epsilon { break; } prev_error = cumulative_error; cumulative_error = 0.0f32; } weights } #[cfg(test)] mod tests { use super::*; use sensei_math::math::Mat; #[test] fn it_works()
}
{ let features = mat! [ [1.0], [2.0], [3.0], [4.0] ]; let labels = vec![1.0,2.0,3.0,4.0]; let expected_gradient = 1.0; let computed_gradient = batch(0.001f32, &features, &labels)[0]; assert!((expected_gradient - computed_gradient).abs() < 0.00001); }
identifier_body
gradient_descent.rs
extern crate sensei_math; use sensei_math::math::Mat; use std::f32; fn dot(v1:&[f32], v2:&[f32]) -> f32 { assert!(v1.len() == v2.len()); //TODO: Do some performance comparisons between this form and a // for loop with an accumulator. v1.iter() .zip(v2.iter()) .map(|(&x,&y)| x*y) .fold(0f32, |sum, x| sum + x) // sum() cannot infer the type... } pub fn batch(alpha:f32, features:&Mat<f32>, labels:&[f32]) -> Vec<f32> { assert!(features.row_count > 0, "Expected at least one sample."); let m = labels.len(); let mut weights = vec! [0.0; features[0].len()]; let feature_count = weights.len(); let epsilon = 0.000_000_0001f32; let mut prev_error = f32::MAX; let mut cumulative_error = 0.0f32; // Continue descending until we are no longer making progress loop { for j in 0..m { let ref x:Vec<f32> = features[j]; let error = dot(&weights, &x) - labels[j]; for i in 0..feature_count { weights[i] = weights[i] - alpha * error * x[i]; } cumulative_error = cumulative_error + error*error; } if prev_error - cumulative_error < epsilon { break; } prev_error = cumulative_error; cumulative_error = 0.0f32; } weights } #[cfg(test)] mod tests { use super::*; use sensei_math::math::Mat; #[test] fn
() { let features = mat! [ [1.0], [2.0], [3.0], [4.0] ]; let labels = vec![1.0,2.0,3.0,4.0]; let expected_gradient = 1.0; let computed_gradient = batch(0.001f32, &features, &labels)[0]; assert!((expected_gradient - computed_gradient).abs() < 0.00001); } }
it_works
identifier_name
gradient_descent.rs
extern crate sensei_math; use sensei_math::math::Mat; use std::f32; fn dot(v1:&[f32], v2:&[f32]) -> f32 { assert!(v1.len() == v2.len()); //TODO: Do some performance comparisons between this form and a // for loop with an accumulator. v1.iter() .zip(v2.iter()) .map(|(&x,&y)| x*y) .fold(0f32, |sum, x| sum + x) // sum() cannot infer the type... } pub fn batch(alpha:f32, features:&Mat<f32>, labels:&[f32]) -> Vec<f32> { assert!(features.row_count > 0, "Expected at least one sample."); let m = labels.len(); let mut weights = vec! [0.0; features[0].len()]; let feature_count = weights.len(); let epsilon = 0.000_000_0001f32; let mut prev_error = f32::MAX; let mut cumulative_error = 0.0f32; // Continue descending until we are no longer making progress loop { for j in 0..m { let ref x:Vec<f32> = features[j]; let error = dot(&weights, &x) - labels[j]; for i in 0..feature_count {
} if prev_error - cumulative_error < epsilon { break; } prev_error = cumulative_error; cumulative_error = 0.0f32; } weights } #[cfg(test)] mod tests { use super::*; use sensei_math::math::Mat; #[test] fn it_works() { let features = mat! [ [1.0], [2.0], [3.0], [4.0] ]; let labels = vec![1.0,2.0,3.0,4.0]; let expected_gradient = 1.0; let computed_gradient = batch(0.001f32, &features, &labels)[0]; assert!((expected_gradient - computed_gradient).abs() < 0.00001); } }
weights[i] = weights[i] - alpha * error * x[i]; } cumulative_error = cumulative_error + error*error;
random_line_split
gradient_descent.rs
extern crate sensei_math; use sensei_math::math::Mat; use std::f32; fn dot(v1:&[f32], v2:&[f32]) -> f32 { assert!(v1.len() == v2.len()); //TODO: Do some performance comparisons between this form and a // for loop with an accumulator. v1.iter() .zip(v2.iter()) .map(|(&x,&y)| x*y) .fold(0f32, |sum, x| sum + x) // sum() cannot infer the type... } pub fn batch(alpha:f32, features:&Mat<f32>, labels:&[f32]) -> Vec<f32> { assert!(features.row_count > 0, "Expected at least one sample."); let m = labels.len(); let mut weights = vec! [0.0; features[0].len()]; let feature_count = weights.len(); let epsilon = 0.000_000_0001f32; let mut prev_error = f32::MAX; let mut cumulative_error = 0.0f32; // Continue descending until we are no longer making progress loop { for j in 0..m { let ref x:Vec<f32> = features[j]; let error = dot(&weights, &x) - labels[j]; for i in 0..feature_count { weights[i] = weights[i] - alpha * error * x[i]; } cumulative_error = cumulative_error + error*error; } if prev_error - cumulative_error < epsilon
prev_error = cumulative_error; cumulative_error = 0.0f32; } weights } #[cfg(test)] mod tests { use super::*; use sensei_math::math::Mat; #[test] fn it_works() { let features = mat! [ [1.0], [2.0], [3.0], [4.0] ]; let labels = vec![1.0,2.0,3.0,4.0]; let expected_gradient = 1.0; let computed_gradient = batch(0.001f32, &features, &labels)[0]; assert!((expected_gradient - computed_gradient).abs() < 0.00001); } }
{ break; }
conditional_block
mod.rs
mod endpoint; mod model; use crate::database::settings::{PRIVACY_ADMIN_ONLY, PRIVACY_EVERYONE, PRIVACY_STAFF_ONLY}; use crate::discord::util::is_staff; use crate::server::endpoint::ban::{get_ban, get_bans, update_ban}; use crate::server::endpoint::captcha::{get_captcha_page, submit_captcha}; use crate::server::endpoint::hardban::{get_hardban, get_hardbans, update_hardban}; use crate::server::endpoint::kick::{get_kick, get_kicks, update_kick}; use crate::server::endpoint::login::login; use crate::server::endpoint::mute::{get_mute, get_mutes, update_mute}; use crate::server::endpoint::self_user::get_self; use crate::server::endpoint::settings::{get_setting, reset_setting, update_setting}; use crate::server::endpoint::softban::{get_softban, get_softbans, update_softban}; use crate::server::endpoint::warn::{get_warn, get_warns, update_warn}; use crate::service::guild::{CachedMember, GuildService}; use crate::service::invalid_uuid::InvalidUUIDService; use crate::service::setting::SettingService; use crate::util::now; use crate::Config; use actix_cors::Cors; use actix_web::http::header::{HeaderName, CONTENT_TYPE}; use actix_web::{get, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use jsonwebtoken::errors::ErrorKind; use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation}; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serenity::model::id::{GuildId, UserId}; use serenity::model::Permissions; use std::error::Error; use std::net::Ipv4Addr; use std::sync::Arc; use tracing::error; use typemap_rev::TypeMap; use uuid::Uuid; lazy_static! { static ref VALIDATION: Validation = Validation::new(Algorithm::HS512); static ref ENCODING_HEADER: Header = Header::new(Algorithm::HS512); } #[derive(Deserialize, Serialize)] struct JwtClaims { #[serde(rename = "userId")] user_id: String, uuid: Uuid, exp: u64, } fn verify_token(secret: &str, token: &str) -> Option<JwtClaims> { match decode::<JwtClaims>( token, &DecodingKey::from_secret(secret.as_bytes()), &VALIDATION, ) { Ok(data) => Some(data.claims), Err(error) => match error.kind() { ErrorKind::InvalidSignature | ErrorKind::ExpiredSignature => None, _ => { error!("failed to decode jwt token {:?}", error.kind()); None } }, } } fn generate_token(secret: &str, user_id: UserId) -> Option<String> { let user_id = user_id.to_string(); let expires_at = now() + 7 * 24 * 60 * 60; let uuid = Uuid::new_v4(); let claims = JwtClaims { user_id, uuid, exp: expires_at, }; match encode( &ENCODING_HEADER, &claims, &EncodingKey::from_secret(secret.as_bytes()), ) { Ok(token) => Some(token), Err(err) => { error!("failed to create jwt token {:?}", err); None } } } async fn is_authenticated( config: &Config, services: &TypeMap, req: &web::HttpRequest, ) -> Option<UserId>
None } } } } pub async fn check_authentication( config: &Config, services: &TypeMap, req: &web::HttpRequest, ) -> Result<UserId, HttpResponse> { is_authenticated(config, services, req) .await .ok_or_else(|| HttpResponse::Unauthorized().json("Invalid token!")) } pub enum PrivateEndpointKind { ModLog, Settings, } async fn is_authorized_to_view_private_endpoint( services: &TypeMap, guild_id: GuildId, permissions: Permissions, endpoint_kind: PrivateEndpointKind, ) -> bool { let setting_service = if let Some(service) = services.get::<SettingService>() { service } else { return false; }; let setting = setting_service.get_setting(guild_id).await; let privacy_setting = match endpoint_kind { PrivateEndpointKind::Settings => setting.privacy_settings, PrivateEndpointKind::ModLog => setting.privacy_mod_log, }; if privacy_setting == PRIVACY_EVERYONE { true } else if privacy_setting == PRIVACY_STAFF_ONLY { is_staff(permissions) } else if privacy_setting == PRIVACY_ADMIN_ONLY { permissions.administrator() } else { false } } pub async fn check_authorization_to_view_private_endpoint( services: &TypeMap, guild_id: GuildId, permissions: Permissions, endpoint_kind: PrivateEndpointKind, ) -> Option<HttpResponse> { if is_authorized_to_view_private_endpoint(services, guild_id, permissions, endpoint_kind).await { None } else { Some( HttpResponse::Forbidden() .json("Server settings prevent you from viewing private information!"), ) } } pub async fn is_guild_endpoint( services: &TypeMap, guild_id: GuildId, user_id: UserId, ) -> Option<(Arc<CachedMember>, Permissions)> { let guild_service = services.get::<GuildService>()?; let member = guild_service.get_member(guild_id, user_id).await.ok()?; let permissions = if let Ok(permissions) = guild_service .get_permissions(user_id, &member.roles, guild_id) .await { permissions } else { return None; }; Some((member, permissions)) } pub async fn check_guild_endpoint( services: &TypeMap, guild_id: GuildId, user_id: UserId, ) -> Result<(Arc<CachedMember>, Permissions), HttpResponse> { is_guild_endpoint(services, guild_id, user_id) .await .ok_or_else(|| { HttpResponse::Forbidden().json("This server either doesn't exist or you aren't in it!") }) } pub async fn apply_private_endpoint_fetch_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, endpoint_kind: PrivateEndpointKind, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if let Some(response) = check_authorization_to_view_private_endpoint(services, guild_id, permissions, endpoint_kind) .await { return Err(response); } Ok(()) } pub async fn apply_mod_log_update_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, required_permission: Permissions, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if permissions.contains(Permissions::ADMINISTRATOR) || permissions.contains(required_permission) { Ok(()) } else { Err(HttpResponse::Forbidden() .json("You don't have permissions to change moderator log history!")) } } pub async fn apply_setting_update_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if permissions.contains(Permissions::ADMINISTRATOR) { Ok(()) } else { Err(HttpResponse::Forbidden().json("You don't have permissions to change server settings!")) } } #[get("/")] async fn index() -> impl Responder { "Welcome to Safety Jim API." } pub async fn run_server(config: Arc<Config>, services: Arc<TypeMap>) -> Result<(), Box<dyn Error>> { let port = config.server_port; HttpServer::new(move || { App::new() .app_data(web::Data::from(config.clone())) .app_data(web::Data::from(services.clone())) .service(index) .service(get_self) .service(get_bans) .service(get_ban) .service(update_ban) .service(get_captcha_page) .service(submit_captcha) .service(get_hardbans) .service(get_hardban) .service(update_hardban) .service(get_kicks) .service(get_kick) .service(update_kick) .service(login) .service(get_mutes) .service(get_mute) .service(update_mute) .service(get_setting) .service(update_setting) .service(reset_setting) .service(get_softbans) .service(get_softban) .service(update_softban) .service(get_warns) .service(get_warn) .service(update_warn) .wrap( Cors::default() .allowed_origin(&config.cors_origin) // needed for captcha endpoint, actix-cors doesn't actually check if request is for CORS .allowed_origin(&config.self_url) .allowed_methods(vec!["GET", "POST", "DELETE"]) .allowed_headers(vec![CONTENT_TYPE, HeaderName::from_static("token")]) .max_age(None), ) }) .bind((Ipv4Addr::LOCALHOST, port))? .run() .await?; Ok(()) }
{ let token = req .headers() .get(HeaderName::from_static("token")) // optimize into constant? .map(|value| value.to_str()) .map(|result| result.ok()) .flatten()?; let claims = verify_token(&config.server_secret, token)?; let invalid_uuid_service = services.get::<InvalidUUIDService>()?; if invalid_uuid_service.is_uuid_invalid(claims.uuid).await { None } else { match claims.user_id.parse::<u64>() { Ok(id) => Some(UserId(id)), Err(_) => { // secret leaked or we have a problem with token generation error!("received a token with valid signature with invalid user id");
identifier_body
mod.rs
mod endpoint; mod model; use crate::database::settings::{PRIVACY_ADMIN_ONLY, PRIVACY_EVERYONE, PRIVACY_STAFF_ONLY}; use crate::discord::util::is_staff; use crate::server::endpoint::ban::{get_ban, get_bans, update_ban}; use crate::server::endpoint::captcha::{get_captcha_page, submit_captcha}; use crate::server::endpoint::hardban::{get_hardban, get_hardbans, update_hardban}; use crate::server::endpoint::kick::{get_kick, get_kicks, update_kick}; use crate::server::endpoint::login::login; use crate::server::endpoint::mute::{get_mute, get_mutes, update_mute}; use crate::server::endpoint::self_user::get_self; use crate::server::endpoint::settings::{get_setting, reset_setting, update_setting}; use crate::server::endpoint::softban::{get_softban, get_softbans, update_softban}; use crate::server::endpoint::warn::{get_warn, get_warns, update_warn}; use crate::service::guild::{CachedMember, GuildService}; use crate::service::invalid_uuid::InvalidUUIDService; use crate::service::setting::SettingService; use crate::util::now; use crate::Config; use actix_cors::Cors; use actix_web::http::header::{HeaderName, CONTENT_TYPE}; use actix_web::{get, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use jsonwebtoken::errors::ErrorKind; use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation}; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serenity::model::id::{GuildId, UserId}; use serenity::model::Permissions; use std::error::Error; use std::net::Ipv4Addr; use std::sync::Arc; use tracing::error; use typemap_rev::TypeMap; use uuid::Uuid; lazy_static! { static ref VALIDATION: Validation = Validation::new(Algorithm::HS512); static ref ENCODING_HEADER: Header = Header::new(Algorithm::HS512); } #[derive(Deserialize, Serialize)] struct JwtClaims { #[serde(rename = "userId")] user_id: String, uuid: Uuid, exp: u64, } fn verify_token(secret: &str, token: &str) -> Option<JwtClaims> { match decode::<JwtClaims>( token, &DecodingKey::from_secret(secret.as_bytes()), &VALIDATION, ) { Ok(data) => Some(data.claims), Err(error) => match error.kind() { ErrorKind::InvalidSignature | ErrorKind::ExpiredSignature => None, _ => { error!("failed to decode jwt token {:?}", error.kind()); None } }, } } fn generate_token(secret: &str, user_id: UserId) -> Option<String> { let user_id = user_id.to_string(); let expires_at = now() + 7 * 24 * 60 * 60; let uuid = Uuid::new_v4(); let claims = JwtClaims { user_id, uuid, exp: expires_at, }; match encode( &ENCODING_HEADER, &claims, &EncodingKey::from_secret(secret.as_bytes()), ) { Ok(token) => Some(token), Err(err) => { error!("failed to create jwt token {:?}", err); None } } } async fn is_authenticated( config: &Config, services: &TypeMap, req: &web::HttpRequest, ) -> Option<UserId> { let token = req .headers() .get(HeaderName::from_static("token")) // optimize into constant? .map(|value| value.to_str()) .map(|result| result.ok()) .flatten()?; let claims = verify_token(&config.server_secret, token)?; let invalid_uuid_service = services.get::<InvalidUUIDService>()?; if invalid_uuid_service.is_uuid_invalid(claims.uuid).await { None } else { match claims.user_id.parse::<u64>() { Ok(id) => Some(UserId(id)), Err(_) => { // secret leaked or we have a problem with token generation error!("received a token with valid signature with invalid user id"); None } } } } pub async fn check_authentication( config: &Config, services: &TypeMap, req: &web::HttpRequest, ) -> Result<UserId, HttpResponse> { is_authenticated(config, services, req) .await .ok_or_else(|| HttpResponse::Unauthorized().json("Invalid token!")) } pub enum PrivateEndpointKind { ModLog, Settings, } async fn is_authorized_to_view_private_endpoint( services: &TypeMap, guild_id: GuildId, permissions: Permissions, endpoint_kind: PrivateEndpointKind, ) -> bool { let setting_service = if let Some(service) = services.get::<SettingService>() { service } else { return false; }; let setting = setting_service.get_setting(guild_id).await; let privacy_setting = match endpoint_kind { PrivateEndpointKind::Settings => setting.privacy_settings, PrivateEndpointKind::ModLog => setting.privacy_mod_log, }; if privacy_setting == PRIVACY_EVERYONE { true } else if privacy_setting == PRIVACY_STAFF_ONLY { is_staff(permissions) } else if privacy_setting == PRIVACY_ADMIN_ONLY { permissions.administrator() } else { false } } pub async fn check_authorization_to_view_private_endpoint( services: &TypeMap, guild_id: GuildId, permissions: Permissions, endpoint_kind: PrivateEndpointKind, ) -> Option<HttpResponse> { if is_authorized_to_view_private_endpoint(services, guild_id, permissions, endpoint_kind).await { None } else { Some( HttpResponse::Forbidden() .json("Server settings prevent you from viewing private information!"), ) } } pub async fn is_guild_endpoint( services: &TypeMap, guild_id: GuildId, user_id: UserId, ) -> Option<(Arc<CachedMember>, Permissions)> { let guild_service = services.get::<GuildService>()?; let member = guild_service.get_member(guild_id, user_id).await.ok()?; let permissions = if let Ok(permissions) = guild_service .get_permissions(user_id, &member.roles, guild_id) .await { permissions } else { return None; }; Some((member, permissions)) } pub async fn check_guild_endpoint( services: &TypeMap, guild_id: GuildId, user_id: UserId, ) -> Result<(Arc<CachedMember>, Permissions), HttpResponse> { is_guild_endpoint(services, guild_id, user_id) .await .ok_or_else(|| { HttpResponse::Forbidden().json("This server either doesn't exist or you aren't in it!") }) } pub async fn apply_private_endpoint_fetch_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, endpoint_kind: PrivateEndpointKind, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if let Some(response) = check_authorization_to_view_private_endpoint(services, guild_id, permissions, endpoint_kind) .await { return Err(response); } Ok(()) } pub async fn apply_mod_log_update_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, required_permission: Permissions, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if permissions.contains(Permissions::ADMINISTRATOR) || permissions.contains(required_permission) { Ok(()) } else
} pub async fn apply_setting_update_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if permissions.contains(Permissions::ADMINISTRATOR) { Ok(()) } else { Err(HttpResponse::Forbidden().json("You don't have permissions to change server settings!")) } } #[get("/")] async fn index() -> impl Responder { "Welcome to Safety Jim API." } pub async fn run_server(config: Arc<Config>, services: Arc<TypeMap>) -> Result<(), Box<dyn Error>> { let port = config.server_port; HttpServer::new(move || { App::new() .app_data(web::Data::from(config.clone())) .app_data(web::Data::from(services.clone())) .service(index) .service(get_self) .service(get_bans) .service(get_ban) .service(update_ban) .service(get_captcha_page) .service(submit_captcha) .service(get_hardbans) .service(get_hardban) .service(update_hardban) .service(get_kicks) .service(get_kick) .service(update_kick) .service(login) .service(get_mutes) .service(get_mute) .service(update_mute) .service(get_setting) .service(update_setting) .service(reset_setting) .service(get_softbans) .service(get_softban) .service(update_softban) .service(get_warns) .service(get_warn) .service(update_warn) .wrap( Cors::default() .allowed_origin(&config.cors_origin) // needed for captcha endpoint, actix-cors doesn't actually check if request is for CORS .allowed_origin(&config.self_url) .allowed_methods(vec!["GET", "POST", "DELETE"]) .allowed_headers(vec![CONTENT_TYPE, HeaderName::from_static("token")]) .max_age(None), ) }) .bind((Ipv4Addr::LOCALHOST, port))? .run() .await?; Ok(()) }
{ Err(HttpResponse::Forbidden() .json("You don't have permissions to change moderator log history!")) }
conditional_block
mod.rs
mod endpoint; mod model; use crate::database::settings::{PRIVACY_ADMIN_ONLY, PRIVACY_EVERYONE, PRIVACY_STAFF_ONLY}; use crate::discord::util::is_staff; use crate::server::endpoint::ban::{get_ban, get_bans, update_ban}; use crate::server::endpoint::captcha::{get_captcha_page, submit_captcha}; use crate::server::endpoint::hardban::{get_hardban, get_hardbans, update_hardban}; use crate::server::endpoint::kick::{get_kick, get_kicks, update_kick}; use crate::server::endpoint::login::login; use crate::server::endpoint::mute::{get_mute, get_mutes, update_mute}; use crate::server::endpoint::self_user::get_self; use crate::server::endpoint::settings::{get_setting, reset_setting, update_setting}; use crate::server::endpoint::softban::{get_softban, get_softbans, update_softban}; use crate::server::endpoint::warn::{get_warn, get_warns, update_warn}; use crate::service::guild::{CachedMember, GuildService}; use crate::service::invalid_uuid::InvalidUUIDService; use crate::service::setting::SettingService; use crate::util::now; use crate::Config; use actix_cors::Cors; use actix_web::http::header::{HeaderName, CONTENT_TYPE}; use actix_web::{get, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use jsonwebtoken::errors::ErrorKind; use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation}; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serenity::model::id::{GuildId, UserId}; use serenity::model::Permissions; use std::error::Error; use std::net::Ipv4Addr; use std::sync::Arc; use tracing::error; use typemap_rev::TypeMap; use uuid::Uuid; lazy_static! { static ref VALIDATION: Validation = Validation::new(Algorithm::HS512); static ref ENCODING_HEADER: Header = Header::new(Algorithm::HS512); } #[derive(Deserialize, Serialize)] struct
{ #[serde(rename = "userId")] user_id: String, uuid: Uuid, exp: u64, } fn verify_token(secret: &str, token: &str) -> Option<JwtClaims> { match decode::<JwtClaims>( token, &DecodingKey::from_secret(secret.as_bytes()), &VALIDATION, ) { Ok(data) => Some(data.claims), Err(error) => match error.kind() { ErrorKind::InvalidSignature | ErrorKind::ExpiredSignature => None, _ => { error!("failed to decode jwt token {:?}", error.kind()); None } }, } } fn generate_token(secret: &str, user_id: UserId) -> Option<String> { let user_id = user_id.to_string(); let expires_at = now() + 7 * 24 * 60 * 60; let uuid = Uuid::new_v4(); let claims = JwtClaims { user_id, uuid, exp: expires_at, }; match encode( &ENCODING_HEADER, &claims, &EncodingKey::from_secret(secret.as_bytes()), ) { Ok(token) => Some(token), Err(err) => { error!("failed to create jwt token {:?}", err); None } } } async fn is_authenticated( config: &Config, services: &TypeMap, req: &web::HttpRequest, ) -> Option<UserId> { let token = req .headers() .get(HeaderName::from_static("token")) // optimize into constant? .map(|value| value.to_str()) .map(|result| result.ok()) .flatten()?; let claims = verify_token(&config.server_secret, token)?; let invalid_uuid_service = services.get::<InvalidUUIDService>()?; if invalid_uuid_service.is_uuid_invalid(claims.uuid).await { None } else { match claims.user_id.parse::<u64>() { Ok(id) => Some(UserId(id)), Err(_) => { // secret leaked or we have a problem with token generation error!("received a token with valid signature with invalid user id"); None } } } } pub async fn check_authentication( config: &Config, services: &TypeMap, req: &web::HttpRequest, ) -> Result<UserId, HttpResponse> { is_authenticated(config, services, req) .await .ok_or_else(|| HttpResponse::Unauthorized().json("Invalid token!")) } pub enum PrivateEndpointKind { ModLog, Settings, } async fn is_authorized_to_view_private_endpoint( services: &TypeMap, guild_id: GuildId, permissions: Permissions, endpoint_kind: PrivateEndpointKind, ) -> bool { let setting_service = if let Some(service) = services.get::<SettingService>() { service } else { return false; }; let setting = setting_service.get_setting(guild_id).await; let privacy_setting = match endpoint_kind { PrivateEndpointKind::Settings => setting.privacy_settings, PrivateEndpointKind::ModLog => setting.privacy_mod_log, }; if privacy_setting == PRIVACY_EVERYONE { true } else if privacy_setting == PRIVACY_STAFF_ONLY { is_staff(permissions) } else if privacy_setting == PRIVACY_ADMIN_ONLY { permissions.administrator() } else { false } } pub async fn check_authorization_to_view_private_endpoint( services: &TypeMap, guild_id: GuildId, permissions: Permissions, endpoint_kind: PrivateEndpointKind, ) -> Option<HttpResponse> { if is_authorized_to_view_private_endpoint(services, guild_id, permissions, endpoint_kind).await { None } else { Some( HttpResponse::Forbidden() .json("Server settings prevent you from viewing private information!"), ) } } pub async fn is_guild_endpoint( services: &TypeMap, guild_id: GuildId, user_id: UserId, ) -> Option<(Arc<CachedMember>, Permissions)> { let guild_service = services.get::<GuildService>()?; let member = guild_service.get_member(guild_id, user_id).await.ok()?; let permissions = if let Ok(permissions) = guild_service .get_permissions(user_id, &member.roles, guild_id) .await { permissions } else { return None; }; Some((member, permissions)) } pub async fn check_guild_endpoint( services: &TypeMap, guild_id: GuildId, user_id: UserId, ) -> Result<(Arc<CachedMember>, Permissions), HttpResponse> { is_guild_endpoint(services, guild_id, user_id) .await .ok_or_else(|| { HttpResponse::Forbidden().json("This server either doesn't exist or you aren't in it!") }) } pub async fn apply_private_endpoint_fetch_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, endpoint_kind: PrivateEndpointKind, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if let Some(response) = check_authorization_to_view_private_endpoint(services, guild_id, permissions, endpoint_kind) .await { return Err(response); } Ok(()) } pub async fn apply_mod_log_update_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, required_permission: Permissions, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if permissions.contains(Permissions::ADMINISTRATOR) || permissions.contains(required_permission) { Ok(()) } else { Err(HttpResponse::Forbidden() .json("You don't have permissions to change moderator log history!")) } } pub async fn apply_setting_update_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if permissions.contains(Permissions::ADMINISTRATOR) { Ok(()) } else { Err(HttpResponse::Forbidden().json("You don't have permissions to change server settings!")) } } #[get("/")] async fn index() -> impl Responder { "Welcome to Safety Jim API." } pub async fn run_server(config: Arc<Config>, services: Arc<TypeMap>) -> Result<(), Box<dyn Error>> { let port = config.server_port; HttpServer::new(move || { App::new() .app_data(web::Data::from(config.clone())) .app_data(web::Data::from(services.clone())) .service(index) .service(get_self) .service(get_bans) .service(get_ban) .service(update_ban) .service(get_captcha_page) .service(submit_captcha) .service(get_hardbans) .service(get_hardban) .service(update_hardban) .service(get_kicks) .service(get_kick) .service(update_kick) .service(login) .service(get_mutes) .service(get_mute) .service(update_mute) .service(get_setting) .service(update_setting) .service(reset_setting) .service(get_softbans) .service(get_softban) .service(update_softban) .service(get_warns) .service(get_warn) .service(update_warn) .wrap( Cors::default() .allowed_origin(&config.cors_origin) // needed for captcha endpoint, actix-cors doesn't actually check if request is for CORS .allowed_origin(&config.self_url) .allowed_methods(vec!["GET", "POST", "DELETE"]) .allowed_headers(vec![CONTENT_TYPE, HeaderName::from_static("token")]) .max_age(None), ) }) .bind((Ipv4Addr::LOCALHOST, port))? .run() .await?; Ok(()) }
JwtClaims
identifier_name
mod.rs
mod endpoint; mod model; use crate::database::settings::{PRIVACY_ADMIN_ONLY, PRIVACY_EVERYONE, PRIVACY_STAFF_ONLY}; use crate::discord::util::is_staff; use crate::server::endpoint::ban::{get_ban, get_bans, update_ban}; use crate::server::endpoint::captcha::{get_captcha_page, submit_captcha}; use crate::server::endpoint::hardban::{get_hardban, get_hardbans, update_hardban}; use crate::server::endpoint::kick::{get_kick, get_kicks, update_kick}; use crate::server::endpoint::login::login; use crate::server::endpoint::mute::{get_mute, get_mutes, update_mute}; use crate::server::endpoint::self_user::get_self; use crate::server::endpoint::settings::{get_setting, reset_setting, update_setting}; use crate::server::endpoint::softban::{get_softban, get_softbans, update_softban}; use crate::server::endpoint::warn::{get_warn, get_warns, update_warn}; use crate::service::guild::{CachedMember, GuildService}; use crate::service::invalid_uuid::InvalidUUIDService; use crate::service::setting::SettingService; use crate::util::now; use crate::Config; use actix_cors::Cors; use actix_web::http::header::{HeaderName, CONTENT_TYPE}; use actix_web::{get, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use jsonwebtoken::errors::ErrorKind; use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation}; use lazy_static::lazy_static; use serde::{Deserialize, Serialize}; use serenity::model::id::{GuildId, UserId}; use serenity::model::Permissions; use std::error::Error; use std::net::Ipv4Addr; use std::sync::Arc; use tracing::error; use typemap_rev::TypeMap; use uuid::Uuid; lazy_static! { static ref VALIDATION: Validation = Validation::new(Algorithm::HS512); static ref ENCODING_HEADER: Header = Header::new(Algorithm::HS512); } #[derive(Deserialize, Serialize)] struct JwtClaims { #[serde(rename = "userId")] user_id: String, uuid: Uuid, exp: u64, } fn verify_token(secret: &str, token: &str) -> Option<JwtClaims> { match decode::<JwtClaims>( token, &DecodingKey::from_secret(secret.as_bytes()), &VALIDATION, ) { Ok(data) => Some(data.claims), Err(error) => match error.kind() { ErrorKind::InvalidSignature | ErrorKind::ExpiredSignature => None, _ => { error!("failed to decode jwt token {:?}", error.kind()); None } }, } } fn generate_token(secret: &str, user_id: UserId) -> Option<String> { let user_id = user_id.to_string(); let expires_at = now() + 7 * 24 * 60 * 60; let uuid = Uuid::new_v4(); let claims = JwtClaims { user_id, uuid, exp: expires_at, }; match encode( &ENCODING_HEADER, &claims, &EncodingKey::from_secret(secret.as_bytes()), ) { Ok(token) => Some(token), Err(err) => { error!("failed to create jwt token {:?}", err); None } } } async fn is_authenticated( config: &Config, services: &TypeMap, req: &web::HttpRequest, ) -> Option<UserId> { let token = req .headers() .get(HeaderName::from_static("token")) // optimize into constant? .map(|value| value.to_str()) .map(|result| result.ok()) .flatten()?; let claims = verify_token(&config.server_secret, token)?; let invalid_uuid_service = services.get::<InvalidUUIDService>()?; if invalid_uuid_service.is_uuid_invalid(claims.uuid).await { None } else { match claims.user_id.parse::<u64>() { Ok(id) => Some(UserId(id)), Err(_) => { // secret leaked or we have a problem with token generation error!("received a token with valid signature with invalid user id"); None } } } } pub async fn check_authentication( config: &Config, services: &TypeMap, req: &web::HttpRequest, ) -> Result<UserId, HttpResponse> { is_authenticated(config, services, req) .await .ok_or_else(|| HttpResponse::Unauthorized().json("Invalid token!")) } pub enum PrivateEndpointKind { ModLog, Settings, } async fn is_authorized_to_view_private_endpoint( services: &TypeMap, guild_id: GuildId, permissions: Permissions, endpoint_kind: PrivateEndpointKind, ) -> bool { let setting_service = if let Some(service) = services.get::<SettingService>() { service } else { return false; }; let setting = setting_service.get_setting(guild_id).await; let privacy_setting = match endpoint_kind { PrivateEndpointKind::Settings => setting.privacy_settings, PrivateEndpointKind::ModLog => setting.privacy_mod_log, }; if privacy_setting == PRIVACY_EVERYONE { true } else if privacy_setting == PRIVACY_STAFF_ONLY { is_staff(permissions) } else if privacy_setting == PRIVACY_ADMIN_ONLY { permissions.administrator() } else { false } } pub async fn check_authorization_to_view_private_endpoint( services: &TypeMap, guild_id: GuildId, permissions: Permissions, endpoint_kind: PrivateEndpointKind, ) -> Option<HttpResponse> { if is_authorized_to_view_private_endpoint(services, guild_id, permissions, endpoint_kind).await { None } else { Some( HttpResponse::Forbidden() .json("Server settings prevent you from viewing private information!"), ) } } pub async fn is_guild_endpoint( services: &TypeMap, guild_id: GuildId, user_id: UserId, ) -> Option<(Arc<CachedMember>, Permissions)> { let guild_service = services.get::<GuildService>()?; let member = guild_service.get_member(guild_id, user_id).await.ok()?; let permissions = if let Ok(permissions) = guild_service .get_permissions(user_id, &member.roles, guild_id) .await { permissions } else { return None; }; Some((member, permissions)) } pub async fn check_guild_endpoint( services: &TypeMap, guild_id: GuildId, user_id: UserId, ) -> Result<(Arc<CachedMember>, Permissions), HttpResponse> { is_guild_endpoint(services, guild_id, user_id) .await .ok_or_else(|| { HttpResponse::Forbidden().json("This server either doesn't exist or you aren't in it!") }) } pub async fn apply_private_endpoint_fetch_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, endpoint_kind: PrivateEndpointKind, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response),
}; if let Some(response) = check_authorization_to_view_private_endpoint(services, guild_id, permissions, endpoint_kind) .await { return Err(response); } Ok(()) } pub async fn apply_mod_log_update_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, required_permission: Permissions, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if permissions.contains(Permissions::ADMINISTRATOR) || permissions.contains(required_permission) { Ok(()) } else { Err(HttpResponse::Forbidden() .json("You don't have permissions to change moderator log history!")) } } pub async fn apply_setting_update_checks( config: &Config, services: &TypeMap, req: &HttpRequest, guild_id: GuildId, ) -> Result<(), HttpResponse> { let user_id = match check_authentication(config, services, req).await { Ok(user_id) => user_id, Err(response) => return Err(response), }; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response), }; if permissions.contains(Permissions::ADMINISTRATOR) { Ok(()) } else { Err(HttpResponse::Forbidden().json("You don't have permissions to change server settings!")) } } #[get("/")] async fn index() -> impl Responder { "Welcome to Safety Jim API." } pub async fn run_server(config: Arc<Config>, services: Arc<TypeMap>) -> Result<(), Box<dyn Error>> { let port = config.server_port; HttpServer::new(move || { App::new() .app_data(web::Data::from(config.clone())) .app_data(web::Data::from(services.clone())) .service(index) .service(get_self) .service(get_bans) .service(get_ban) .service(update_ban) .service(get_captcha_page) .service(submit_captcha) .service(get_hardbans) .service(get_hardban) .service(update_hardban) .service(get_kicks) .service(get_kick) .service(update_kick) .service(login) .service(get_mutes) .service(get_mute) .service(update_mute) .service(get_setting) .service(update_setting) .service(reset_setting) .service(get_softbans) .service(get_softban) .service(update_softban) .service(get_warns) .service(get_warn) .service(update_warn) .wrap( Cors::default() .allowed_origin(&config.cors_origin) // needed for captcha endpoint, actix-cors doesn't actually check if request is for CORS .allowed_origin(&config.self_url) .allowed_methods(vec!["GET", "POST", "DELETE"]) .allowed_headers(vec![CONTENT_TYPE, HeaderName::from_static("token")]) .max_age(None), ) }) .bind((Ipv4Addr::LOCALHOST, port))? .run() .await?; Ok(()) }
}; let (_, permissions) = match check_guild_endpoint(services, guild_id, user_id).await { Ok((member, permissions)) => (member, permissions), Err(response) => return Err(response),
random_line_split
debug.rs
use alloc::boxed::Box; use collections::string::String; use scheduler::context::{context_switch, context_i, contexts_ptr}; use scheduler; use schemes::{KScheme, Resource, Url}; use syscall::handle; /// A debug resource pub struct DebugResource { pub scheme: *mut DebugScheme, pub command: String, pub line_toggle: bool, } impl Resource for DebugResource { fn dup(&self) -> Option<Box<Resource>> { Some(box DebugResource { scheme: self.scheme, command: self.command.clone(), line_toggle: self.line_toggle, }) } fn url(&self) -> Url { return Url::from_str("debug:"); } fn read(&mut self, buf: &mut [u8]) -> Option<usize> { if self.line_toggle { self.line_toggle = false; return Some(0); } if self.command.is_empty() { loop { unsafe { let reenable = scheduler::start_no_ints(); // Hack! if (*self.scheme).context >= (*contexts_ptr).len() || (*self.scheme).context < context_i { (*self.scheme).context = context_i; } if (*self.scheme).context == context_i && (*::console).command.is_some() { if let Some(ref command) = (*::console).command { self.command = command.clone(); } (*::console).command = None; break; } scheduler::end_no_ints(reenable); context_switch(false); } } } // TODO: Unicode let mut i = 0; while i < buf.len() &&! self.command.is_empty() { buf[i] = unsafe { self.command.as_mut_vec().remove(0) }; i += 1; } if i > 0 && self.command.is_empty() { self.line_toggle = true; } Some(i) } fn write(&mut self, buf: &[u8]) -> Option<usize>
fn sync(&mut self) -> bool { true } } pub struct DebugScheme { pub context: usize, } impl DebugScheme { pub fn new() -> Box<Self> { box DebugScheme { context: 0 } } } impl KScheme for DebugScheme { fn scheme(&self) -> &str { "debug" } fn open(&mut self, _: &Url, _: usize) -> Option<Box<Resource>> { Some(box DebugResource { scheme: self, command: String::new(), line_toggle: false, }) } }
{ for byte in buf { unsafe { handle::do_sys_debug(*byte); } } return Some(buf.len()); }
identifier_body
debug.rs
use alloc::boxed::Box; use collections::string::String; use scheduler::context::{context_switch, context_i, contexts_ptr}; use scheduler; use schemes::{KScheme, Resource, Url}; use syscall::handle; /// A debug resource pub struct DebugResource { pub scheme: *mut DebugScheme, pub command: String, pub line_toggle: bool, } impl Resource for DebugResource { fn dup(&self) -> Option<Box<Resource>> { Some(box DebugResource { scheme: self.scheme, command: self.command.clone(), line_toggle: self.line_toggle, }) } fn url(&self) -> Url { return Url::from_str("debug:"); } fn read(&mut self, buf: &mut [u8]) -> Option<usize> { if self.line_toggle { self.line_toggle = false; return Some(0); } if self.command.is_empty() { loop { unsafe { let reenable = scheduler::start_no_ints(); // Hack! if (*self.scheme).context >= (*contexts_ptr).len() || (*self.scheme).context < context_i { (*self.scheme).context = context_i; } if (*self.scheme).context == context_i && (*::console).command.is_some() { if let Some(ref command) = (*::console).command { self.command = command.clone(); } (*::console).command = None; break; } scheduler::end_no_ints(reenable); context_switch(false); } }
let mut i = 0; while i < buf.len() &&! self.command.is_empty() { buf[i] = unsafe { self.command.as_mut_vec().remove(0) }; i += 1; } if i > 0 && self.command.is_empty() { self.line_toggle = true; } Some(i) } fn write(&mut self, buf: &[u8]) -> Option<usize> { for byte in buf { unsafe { handle::do_sys_debug(*byte); } } return Some(buf.len()); } fn sync(&mut self) -> bool { true } } pub struct DebugScheme { pub context: usize, } impl DebugScheme { pub fn new() -> Box<Self> { box DebugScheme { context: 0 } } } impl KScheme for DebugScheme { fn scheme(&self) -> &str { "debug" } fn open(&mut self, _: &Url, _: usize) -> Option<Box<Resource>> { Some(box DebugResource { scheme: self, command: String::new(), line_toggle: false, }) } }
} // TODO: Unicode
random_line_split
debug.rs
use alloc::boxed::Box; use collections::string::String; use scheduler::context::{context_switch, context_i, contexts_ptr}; use scheduler; use schemes::{KScheme, Resource, Url}; use syscall::handle; /// A debug resource pub struct DebugResource { pub scheme: *mut DebugScheme, pub command: String, pub line_toggle: bool, } impl Resource for DebugResource { fn dup(&self) -> Option<Box<Resource>> { Some(box DebugResource { scheme: self.scheme, command: self.command.clone(), line_toggle: self.line_toggle, }) } fn url(&self) -> Url { return Url::from_str("debug:"); } fn read(&mut self, buf: &mut [u8]) -> Option<usize> { if self.line_toggle { self.line_toggle = false; return Some(0); } if self.command.is_empty() { loop { unsafe { let reenable = scheduler::start_no_ints(); // Hack! if (*self.scheme).context >= (*contexts_ptr).len() || (*self.scheme).context < context_i { (*self.scheme).context = context_i; } if (*self.scheme).context == context_i && (*::console).command.is_some() { if let Some(ref command) = (*::console).command { self.command = command.clone(); } (*::console).command = None; break; } scheduler::end_no_ints(reenable); context_switch(false); } } } // TODO: Unicode let mut i = 0; while i < buf.len() &&! self.command.is_empty() { buf[i] = unsafe { self.command.as_mut_vec().remove(0) }; i += 1; } if i > 0 && self.command.is_empty()
Some(i) } fn write(&mut self, buf: &[u8]) -> Option<usize> { for byte in buf { unsafe { handle::do_sys_debug(*byte); } } return Some(buf.len()); } fn sync(&mut self) -> bool { true } } pub struct DebugScheme { pub context: usize, } impl DebugScheme { pub fn new() -> Box<Self> { box DebugScheme { context: 0 } } } impl KScheme for DebugScheme { fn scheme(&self) -> &str { "debug" } fn open(&mut self, _: &Url, _: usize) -> Option<Box<Resource>> { Some(box DebugResource { scheme: self, command: String::new(), line_toggle: false, }) } }
{ self.line_toggle = true; }
conditional_block
debug.rs
use alloc::boxed::Box; use collections::string::String; use scheduler::context::{context_switch, context_i, contexts_ptr}; use scheduler; use schemes::{KScheme, Resource, Url}; use syscall::handle; /// A debug resource pub struct DebugResource { pub scheme: *mut DebugScheme, pub command: String, pub line_toggle: bool, } impl Resource for DebugResource { fn dup(&self) -> Option<Box<Resource>> { Some(box DebugResource { scheme: self.scheme, command: self.command.clone(), line_toggle: self.line_toggle, }) } fn url(&self) -> Url { return Url::from_str("debug:"); } fn read(&mut self, buf: &mut [u8]) -> Option<usize> { if self.line_toggle { self.line_toggle = false; return Some(0); } if self.command.is_empty() { loop { unsafe { let reenable = scheduler::start_no_ints(); // Hack! if (*self.scheme).context >= (*contexts_ptr).len() || (*self.scheme).context < context_i { (*self.scheme).context = context_i; } if (*self.scheme).context == context_i && (*::console).command.is_some() { if let Some(ref command) = (*::console).command { self.command = command.clone(); } (*::console).command = None; break; } scheduler::end_no_ints(reenable); context_switch(false); } } } // TODO: Unicode let mut i = 0; while i < buf.len() &&! self.command.is_empty() { buf[i] = unsafe { self.command.as_mut_vec().remove(0) }; i += 1; } if i > 0 && self.command.is_empty() { self.line_toggle = true; } Some(i) } fn write(&mut self, buf: &[u8]) -> Option<usize> { for byte in buf { unsafe { handle::do_sys_debug(*byte); } } return Some(buf.len()); } fn
(&mut self) -> bool { true } } pub struct DebugScheme { pub context: usize, } impl DebugScheme { pub fn new() -> Box<Self> { box DebugScheme { context: 0 } } } impl KScheme for DebugScheme { fn scheme(&self) -> &str { "debug" } fn open(&mut self, _: &Url, _: usize) -> Option<Box<Resource>> { Some(box DebugResource { scheme: self, command: String::new(), line_toggle: false, }) } }
sync
identifier_name
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_thread::FileManager; use net_traits::blob_url_store::BlobURLStoreError; use net_traits::filemanager_thread::{ FileManagerThreadError, FileManagerThreadMsg, ReadFileProgress, }; use servo_config::prefs::{PrefValue, PREFS}; use std::fs::File; use std::io::Read; use std::path::PathBuf; #[test] fn test_filemanager() { let filemanager = FileManager::new(create_embedder_proxy()); PREFS.set( "dom.testing.htmlinputelement.select_files.enabled", PrefValue::Boolean(true), ); // Try to open a dummy file "components/net/tests/test.jpeg" in tree let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen"); let mut test_file_content = vec![]; handler .read_to_end(&mut test_file_content) .expect("Read components/net/tests/test.jpeg error"); let patterns = vec![FilterPattern(".txt".to_string())]; let origin = "test.com".to_string(); { // Try to select a dummy file "components/net/tests/test.jpeg" let (tx, rx) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::SelectFile( patterns.clone(), tx, origin.clone(), Some("tests/test.jpeg".to_string()), )); let selected = rx .recv() .expect("Broken channel") .expect("The file manager failed to find test.jpeg"); // Expecting attributes conforming the spec assert_eq!(selected.filename, PathBuf::from("test.jpeg")); assert_eq!(selected.type_string, "image/jpeg".to_string()); // Test by reading, expecting same content { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), false, origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") { let mut bytes = blob_buf.bytes; loop { match rx2 .recv() .expect("Broken channel") .expect("File manager reading failure is unexpected") { ReadFileProgress::Meta(_) => { panic!("Invalid FileManager reply"); }, ReadFileProgress::Partial(mut bytes_in) => { bytes.append(&mut bytes_in); }, ReadFileProgress::EOF => { break; }, } } assert_eq!(test_file_content, bytes, "Read content differs"); } else { panic!("Invalid FileManager reply"); } } // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::DecRef( selected.id.clone(), origin.clone(), tx2, )); let ret = rx2.recv().expect("Broken channel"); assert!(ret.is_ok(), "DecRef is not okay"); } // Test by reading again, expecting read error because we invalidated the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), false, origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); match msg { Err(FileManagerThreadError::BlobURLStoreError( BlobURLStoreError::InvalidFileID, )) => {}, other =>
, } } } }
{ assert!( false, "Get unexpected response after deleting the id: {:?}", other ); }
conditional_block
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_thread::FileManager; use net_traits::blob_url_store::BlobURLStoreError; use net_traits::filemanager_thread::{ FileManagerThreadError, FileManagerThreadMsg, ReadFileProgress, }; use servo_config::prefs::{PrefValue, PREFS}; use std::fs::File; use std::io::Read; use std::path::PathBuf; #[test] fn
() { let filemanager = FileManager::new(create_embedder_proxy()); PREFS.set( "dom.testing.htmlinputelement.select_files.enabled", PrefValue::Boolean(true), ); // Try to open a dummy file "components/net/tests/test.jpeg" in tree let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen"); let mut test_file_content = vec![]; handler .read_to_end(&mut test_file_content) .expect("Read components/net/tests/test.jpeg error"); let patterns = vec![FilterPattern(".txt".to_string())]; let origin = "test.com".to_string(); { // Try to select a dummy file "components/net/tests/test.jpeg" let (tx, rx) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::SelectFile( patterns.clone(), tx, origin.clone(), Some("tests/test.jpeg".to_string()), )); let selected = rx .recv() .expect("Broken channel") .expect("The file manager failed to find test.jpeg"); // Expecting attributes conforming the spec assert_eq!(selected.filename, PathBuf::from("test.jpeg")); assert_eq!(selected.type_string, "image/jpeg".to_string()); // Test by reading, expecting same content { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), false, origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") { let mut bytes = blob_buf.bytes; loop { match rx2 .recv() .expect("Broken channel") .expect("File manager reading failure is unexpected") { ReadFileProgress::Meta(_) => { panic!("Invalid FileManager reply"); }, ReadFileProgress::Partial(mut bytes_in) => { bytes.append(&mut bytes_in); }, ReadFileProgress::EOF => { break; }, } } assert_eq!(test_file_content, bytes, "Read content differs"); } else { panic!("Invalid FileManager reply"); } } // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::DecRef( selected.id.clone(), origin.clone(), tx2, )); let ret = rx2.recv().expect("Broken channel"); assert!(ret.is_ok(), "DecRef is not okay"); } // Test by reading again, expecting read error because we invalidated the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), false, origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); match msg { Err(FileManagerThreadError::BlobURLStoreError( BlobURLStoreError::InvalidFileID, )) => {}, other => { assert!( false, "Get unexpected response after deleting the id: {:?}", other ); }, } } } }
test_filemanager
identifier_name
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_thread::FileManager; use net_traits::blob_url_store::BlobURLStoreError; use net_traits::filemanager_thread::{ FileManagerThreadError, FileManagerThreadMsg, ReadFileProgress, }; use servo_config::prefs::{PrefValue, PREFS}; use std::fs::File; use std::io::Read; use std::path::PathBuf; #[test] fn test_filemanager() { let filemanager = FileManager::new(create_embedder_proxy()); PREFS.set( "dom.testing.htmlinputelement.select_files.enabled", PrefValue::Boolean(true), ); // Try to open a dummy file "components/net/tests/test.jpeg" in tree let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen"); let mut test_file_content = vec![]; handler .read_to_end(&mut test_file_content) .expect("Read components/net/tests/test.jpeg error"); let patterns = vec![FilterPattern(".txt".to_string())]; let origin = "test.com".to_string(); { // Try to select a dummy file "components/net/tests/test.jpeg" let (tx, rx) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::SelectFile( patterns.clone(), tx, origin.clone(), Some("tests/test.jpeg".to_string()), )); let selected = rx .recv() .expect("Broken channel") .expect("The file manager failed to find test.jpeg"); // Expecting attributes conforming the spec assert_eq!(selected.filename, PathBuf::from("test.jpeg")); assert_eq!(selected.type_string, "image/jpeg".to_string()); // Test by reading, expecting same content { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), false, origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") { let mut bytes = blob_buf.bytes; loop { match rx2 .recv() .expect("Broken channel") .expect("File manager reading failure is unexpected") { ReadFileProgress::Meta(_) => { panic!("Invalid FileManager reply"); }, ReadFileProgress::Partial(mut bytes_in) => {
bytes.append(&mut bytes_in); }, ReadFileProgress::EOF => { break; }, } } assert_eq!(test_file_content, bytes, "Read content differs"); } else { panic!("Invalid FileManager reply"); } } // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::DecRef( selected.id.clone(), origin.clone(), tx2, )); let ret = rx2.recv().expect("Broken channel"); assert!(ret.is_ok(), "DecRef is not okay"); } // Test by reading again, expecting read error because we invalidated the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), false, origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); match msg { Err(FileManagerThreadError::BlobURLStoreError( BlobURLStoreError::InvalidFileID, )) => {}, other => { assert!( false, "Get unexpected response after deleting the id: {:?}", other ); }, } } } }
random_line_split
filemanager_thread.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_thread::FileManager; use net_traits::blob_url_store::BlobURLStoreError; use net_traits::filemanager_thread::{ FileManagerThreadError, FileManagerThreadMsg, ReadFileProgress, }; use servo_config::prefs::{PrefValue, PREFS}; use std::fs::File; use std::io::Read; use std::path::PathBuf; #[test] fn test_filemanager()
let (tx, rx) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::SelectFile( patterns.clone(), tx, origin.clone(), Some("tests/test.jpeg".to_string()), )); let selected = rx .recv() .expect("Broken channel") .expect("The file manager failed to find test.jpeg"); // Expecting attributes conforming the spec assert_eq!(selected.filename, PathBuf::from("test.jpeg")); assert_eq!(selected.type_string, "image/jpeg".to_string()); // Test by reading, expecting same content { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), false, origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") { let mut bytes = blob_buf.bytes; loop { match rx2 .recv() .expect("Broken channel") .expect("File manager reading failure is unexpected") { ReadFileProgress::Meta(_) => { panic!("Invalid FileManager reply"); }, ReadFileProgress::Partial(mut bytes_in) => { bytes.append(&mut bytes_in); }, ReadFileProgress::EOF => { break; }, } } assert_eq!(test_file_content, bytes, "Read content differs"); } else { panic!("Invalid FileManager reply"); } } // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::DecRef( selected.id.clone(), origin.clone(), tx2, )); let ret = rx2.recv().expect("Broken channel"); assert!(ret.is_ok(), "DecRef is not okay"); } // Test by reading again, expecting read error because we invalidated the id { let (tx2, rx2) = ipc::channel().unwrap(); filemanager.handle(FileManagerThreadMsg::ReadFile( tx2, selected.id.clone(), false, origin.clone(), )); let msg = rx2.recv().expect("Broken channel"); match msg { Err(FileManagerThreadError::BlobURLStoreError( BlobURLStoreError::InvalidFileID, )) => {}, other => { assert!( false, "Get unexpected response after deleting the id: {:?}", other ); }, } } } }
{ let filemanager = FileManager::new(create_embedder_proxy()); PREFS.set( "dom.testing.htmlinputelement.select_files.enabled", PrefValue::Boolean(true), ); // Try to open a dummy file "components/net/tests/test.jpeg" in tree let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen"); let mut test_file_content = vec![]; handler .read_to_end(&mut test_file_content) .expect("Read components/net/tests/test.jpeg error"); let patterns = vec![FilterPattern(".txt".to_string())]; let origin = "test.com".to_string(); { // Try to select a dummy file "components/net/tests/test.jpeg"
identifier_body
tree_iter.rs
// Copyright 2013-2015, The Rust-GNOME 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 ffi; use std; pub struct TreeIter { data: ffi::GtkTreeIter, pointer: *mut ffi::GtkTreeIter, is_owned: bool, is_true_pointer: bool } impl TreeIter { pub fn new() -> TreeIter { let mut t = TreeIter { data: ffi::GtkTreeIter { stamp: 0, user_data: std::ptr::null_mut(), user_data2: std::ptr::null_mut(), user_data3: std::ptr::null_mut() }, pointer: ::std::ptr::null_mut(), is_owned: false, is_true_pointer: false }; unsafe { t.pointer = std::mem::transmute(&mut t.data); } t } pub fn copy(&self) -> Option<TreeIter> { let tmp_pointer = unsafe { ffi::gtk_tree_iter_copy(self.pointer) }; if tmp_pointer.is_null() { None } else { unsafe { Some(TreeIter { data: std::mem::uninitialized(), pointer: tmp_pointer, is_owned: true, is_true_pointer: true }) } } } #[doc(hidden)] pub fn unwrap_pointer(&self) -> *mut ffi::GtkTreeIter { if self.is_true_pointer
else { unsafe { std::mem::transmute(&self.data) } } } #[doc(hidden)] pub fn wrap_pointer(c_treeiter: *mut ffi::GtkTreeIter) -> TreeIter { unsafe { TreeIter { data: std::mem::uninitialized(), pointer: c_treeiter, is_owned: false, is_true_pointer: true } } } } impl Drop for TreeIter { fn drop(&mut self) { if!self.pointer.is_null() && self.is_owned { unsafe { ffi::gtk_tree_iter_free(self.pointer) }; self.pointer = ::std::ptr::null_mut(); } } }
{ self.pointer }
conditional_block
tree_iter.rs
// Copyright 2013-2015, The Rust-GNOME 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 ffi; use std; pub struct TreeIter { data: ffi::GtkTreeIter, pointer: *mut ffi::GtkTreeIter, is_owned: bool, is_true_pointer: bool } impl TreeIter { pub fn new() -> TreeIter { let mut t = TreeIter { data: ffi::GtkTreeIter { stamp: 0, user_data: std::ptr::null_mut(), user_data2: std::ptr::null_mut(), user_data3: std::ptr::null_mut() }, pointer: ::std::ptr::null_mut(), is_owned: false, is_true_pointer: false }; unsafe { t.pointer = std::mem::transmute(&mut t.data); } t } pub fn copy(&self) -> Option<TreeIter> { let tmp_pointer = unsafe { ffi::gtk_tree_iter_copy(self.pointer) }; if tmp_pointer.is_null() { None } else { unsafe { Some(TreeIter { data: std::mem::uninitialized(), pointer: tmp_pointer, is_owned: true, is_true_pointer: true }) } } } #[doc(hidden)] pub fn unwrap_pointer(&self) -> *mut ffi::GtkTreeIter { if self.is_true_pointer { self.pointer } else { unsafe { std::mem::transmute(&self.data) } } } #[doc(hidden)] pub fn wrap_pointer(c_treeiter: *mut ffi::GtkTreeIter) -> TreeIter
} impl Drop for TreeIter { fn drop(&mut self) { if!self.pointer.is_null() && self.is_owned { unsafe { ffi::gtk_tree_iter_free(self.pointer) }; self.pointer = ::std::ptr::null_mut(); } } }
{ unsafe { TreeIter { data: std::mem::uninitialized(), pointer: c_treeiter, is_owned: false, is_true_pointer: true } } }
identifier_body
tree_iter.rs
// Copyright 2013-2015, The Rust-GNOME 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 ffi; use std; pub struct TreeIter { data: ffi::GtkTreeIter, pointer: *mut ffi::GtkTreeIter, is_owned: bool, is_true_pointer: bool } impl TreeIter { pub fn new() -> TreeIter { let mut t = TreeIter { data: ffi::GtkTreeIter { stamp: 0, user_data: std::ptr::null_mut(), user_data2: std::ptr::null_mut(), user_data3: std::ptr::null_mut() }, pointer: ::std::ptr::null_mut(), is_owned: false, is_true_pointer: false }; unsafe { t.pointer = std::mem::transmute(&mut t.data); } t } pub fn
(&self) -> Option<TreeIter> { let tmp_pointer = unsafe { ffi::gtk_tree_iter_copy(self.pointer) }; if tmp_pointer.is_null() { None } else { unsafe { Some(TreeIter { data: std::mem::uninitialized(), pointer: tmp_pointer, is_owned: true, is_true_pointer: true }) } } } #[doc(hidden)] pub fn unwrap_pointer(&self) -> *mut ffi::GtkTreeIter { if self.is_true_pointer { self.pointer } else { unsafe { std::mem::transmute(&self.data) } } } #[doc(hidden)] pub fn wrap_pointer(c_treeiter: *mut ffi::GtkTreeIter) -> TreeIter { unsafe { TreeIter { data: std::mem::uninitialized(), pointer: c_treeiter, is_owned: false, is_true_pointer: true } } } } impl Drop for TreeIter { fn drop(&mut self) { if!self.pointer.is_null() && self.is_owned { unsafe { ffi::gtk_tree_iter_free(self.pointer) }; self.pointer = ::std::ptr::null_mut(); } } }
copy
identifier_name
tree_iter.rs
// Copyright 2013-2015, The Rust-GNOME 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 ffi; use std; pub struct TreeIter { data: ffi::GtkTreeIter, pointer: *mut ffi::GtkTreeIter, is_owned: bool, is_true_pointer: bool } impl TreeIter { pub fn new() -> TreeIter { let mut t = TreeIter { data: ffi::GtkTreeIter { stamp: 0, user_data: std::ptr::null_mut(), user_data2: std::ptr::null_mut(), user_data3: std::ptr::null_mut() }, pointer: ::std::ptr::null_mut(), is_owned: false, is_true_pointer: false }; unsafe { t.pointer = std::mem::transmute(&mut t.data); }
if tmp_pointer.is_null() { None } else { unsafe { Some(TreeIter { data: std::mem::uninitialized(), pointer: tmp_pointer, is_owned: true, is_true_pointer: true }) } } } #[doc(hidden)] pub fn unwrap_pointer(&self) -> *mut ffi::GtkTreeIter { if self.is_true_pointer { self.pointer } else { unsafe { std::mem::transmute(&self.data) } } } #[doc(hidden)] pub fn wrap_pointer(c_treeiter: *mut ffi::GtkTreeIter) -> TreeIter { unsafe { TreeIter { data: std::mem::uninitialized(), pointer: c_treeiter, is_owned: false, is_true_pointer: true } } } } impl Drop for TreeIter { fn drop(&mut self) { if!self.pointer.is_null() && self.is_owned { unsafe { ffi::gtk_tree_iter_free(self.pointer) }; self.pointer = ::std::ptr::null_mut(); } } }
t } pub fn copy(&self) -> Option<TreeIter> { let tmp_pointer = unsafe { ffi::gtk_tree_iter_copy(self.pointer) };
random_line_split
objpools.rs
/* Copyright (c) 2016-2017, Robert Ou <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use std::collections::HashMap; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; use std::marker::PhantomData; use analyzer::util::*; // We need this because the Vec can be reallocated around, but we want to keep // around some kind of reference into the storage that can keep working after // the reallocation happens. We need the internal one specifically so that // we can ensure different types of strings don't get mixed up. #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] struct StringPoolIndexInternal { start: usize, end: usize, } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct StringPoolIndexLatin1 { start: usize, end: usize, } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct StringPoolIndexOsStr { start: usize, end: usize, } pub struct StringPool { storage: Vec<u8>, hashtable: HashMap<Vec<u8>, StringPoolIndexInternal>, } impl<'a> StringPool { pub fn new() -> StringPool { StringPool { storage: Vec::new(), hashtable: HashMap::new(), } } // TODO: Do we care about freeing things? fn add_internal_str(&mut self, inp: &[u8]) -> StringPoolIndexInternal { // We now need to intern the string because we need to ensure that // we always can compare string pool indices. This is needed so that // Identifiers can be compared without having to drag the string // pool around, which is in turn needed so that Identifiers can be // properly hashed. if let Some(existing_idx) = self.hashtable.get(inp)
let addition_begin = self.storage.len(); let addition_end = addition_begin + inp.len(); self.storage.extend(inp.iter().cloned()); let new_idx = StringPoolIndexInternal { start: addition_begin, end: addition_end }; self.hashtable.insert(inp.to_vec(), new_idx); new_idx } pub fn add_latin1_str(&mut self, inp: &[u8]) -> StringPoolIndexLatin1 { let int_idx = self.add_internal_str(inp); StringPoolIndexLatin1 { start: int_idx.start, end: int_idx.end, } } pub fn retrieve_latin1_str(&self, i: StringPoolIndexLatin1) -> Latin1Str { let the_slice = &self.storage[i.start..i.end]; Latin1Str::new(the_slice) } pub fn add_osstr(&mut self, inp: &OsStr) -> StringPoolIndexOsStr { let int_idx = self.add_internal_str(inp.as_bytes()); StringPoolIndexOsStr { start: int_idx.start, end: int_idx.end, } } pub fn retrieve_osstr(&self, i: StringPoolIndexOsStr) -> &OsStr { let the_slice = &self.storage[i.start..i.end]; OsStr::from_bytes(the_slice) } } #[derive(Hash, Debug)] pub struct ObjPoolIndex<T> { i: usize, type_marker: PhantomData<T> } impl<T> Copy for ObjPoolIndex<T> { } impl<T> Clone for ObjPoolIndex<T> { fn clone(&self) -> ObjPoolIndex<T> { *self } } impl<T> PartialEq for ObjPoolIndex<T> { fn eq(&self, other: &ObjPoolIndex<T>) -> bool { self.i == other.i } } impl<T> Eq for ObjPoolIndex<T> { } pub struct ObjPool<T> { storage: Vec<T> } impl<T: Default> ObjPool<T> { pub fn new() -> ObjPool<T> { ObjPool {storage: Vec::new()} } pub fn alloc(&mut self) -> ObjPoolIndex<T> { let i = self.storage.len(); let o = T::default(); self.storage.push(o); ObjPoolIndex::<T> {i: i, type_marker: PhantomData} } pub fn get(&self, i: ObjPoolIndex<T>) -> &T { &self.storage[i.i] } pub fn get_mut(&mut self, i: ObjPoolIndex<T>) -> &mut T { &mut self.storage[i.i] } } #[cfg(test)] mod tests { use super::*; #[test] fn stringpool_basic_works() { let mut sp = StringPool::new(); let x = sp.add_latin1_str(b"test1"); let y = sp.add_latin1_str(b"test2"); let sx = sp.retrieve_latin1_str(x); let sy = sp.retrieve_latin1_str(y); assert_eq!(sx.raw_name(), b"test1"); assert_eq!(sy.raw_name(), b"test2"); } #[test] fn stringpool_actually_pools() { let mut sp = StringPool::new(); sp.add_latin1_str(b"test1"); sp.add_latin1_str(b"test2"); assert_eq!(sp.storage, b"test1test2"); } #[test] fn stringpool_interns() { let mut sp = StringPool::new(); let x = sp.add_latin1_str(b"test1"); let y = sp.add_latin1_str(b"test1"); assert_eq!(x, y); assert_eq!(sp.storage, b"test1"); } #[derive(Default)] struct ObjPoolTestObject { foo: u32 } #[test] fn objpool_basic_works() { let mut pool = ObjPool::<ObjPoolTestObject>::new(); let x = pool.alloc(); let y = pool.alloc(); { let o = pool.get_mut(x); o.foo = 123; } { let o = pool.get_mut(y); o.foo = 456; } let ox = pool.get(x); let oy = pool.get(y); assert_eq!(ox.foo, 123); assert_eq!(oy.foo, 456); } }
{ return StringPoolIndexInternal { start: existing_idx.start, end: existing_idx.end, }; }
conditional_block
objpools.rs
/* Copyright (c) 2016-2017, Robert Ou <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use std::collections::HashMap; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; use std::marker::PhantomData; use analyzer::util::*; // We need this because the Vec can be reallocated around, but we want to keep // around some kind of reference into the storage that can keep working after // the reallocation happens. We need the internal one specifically so that // we can ensure different types of strings don't get mixed up. #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] struct StringPoolIndexInternal { start: usize, end: usize, } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct StringPoolIndexLatin1 { start: usize, end: usize, } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct StringPoolIndexOsStr { start: usize, end: usize, } pub struct StringPool { storage: Vec<u8>, hashtable: HashMap<Vec<u8>, StringPoolIndexInternal>, } impl<'a> StringPool { pub fn new() -> StringPool { StringPool { storage: Vec::new(), hashtable: HashMap::new(), } } // TODO: Do we care about freeing things? fn add_internal_str(&mut self, inp: &[u8]) -> StringPoolIndexInternal { // We now need to intern the string because we need to ensure that // we always can compare string pool indices. This is needed so that // Identifiers can be compared without having to drag the string // pool around, which is in turn needed so that Identifiers can be // properly hashed. if let Some(existing_idx) = self.hashtable.get(inp) { return StringPoolIndexInternal { start: existing_idx.start, end: existing_idx.end, }; } let addition_begin = self.storage.len(); let addition_end = addition_begin + inp.len(); self.storage.extend(inp.iter().cloned()); let new_idx = StringPoolIndexInternal { start: addition_begin, end: addition_end }; self.hashtable.insert(inp.to_vec(), new_idx); new_idx } pub fn add_latin1_str(&mut self, inp: &[u8]) -> StringPoolIndexLatin1 { let int_idx = self.add_internal_str(inp); StringPoolIndexLatin1 { start: int_idx.start, end: int_idx.end, } } pub fn retrieve_latin1_str(&self, i: StringPoolIndexLatin1) -> Latin1Str { let the_slice = &self.storage[i.start..i.end]; Latin1Str::new(the_slice) } pub fn add_osstr(&mut self, inp: &OsStr) -> StringPoolIndexOsStr { let int_idx = self.add_internal_str(inp.as_bytes()); StringPoolIndexOsStr { start: int_idx.start, end: int_idx.end, } } pub fn retrieve_osstr(&self, i: StringPoolIndexOsStr) -> &OsStr { let the_slice = &self.storage[i.start..i.end]; OsStr::from_bytes(the_slice) } } #[derive(Hash, Debug)] pub struct ObjPoolIndex<T> { i: usize, type_marker: PhantomData<T> } impl<T> Copy for ObjPoolIndex<T> { } impl<T> Clone for ObjPoolIndex<T> { fn clone(&self) -> ObjPoolIndex<T> { *self } } impl<T> PartialEq for ObjPoolIndex<T> { fn eq(&self, other: &ObjPoolIndex<T>) -> bool { self.i == other.i } } impl<T> Eq for ObjPoolIndex<T> { } pub struct ObjPool<T> { storage: Vec<T> } impl<T: Default> ObjPool<T> { pub fn new() -> ObjPool<T> { ObjPool {storage: Vec::new()} } pub fn alloc(&mut self) -> ObjPoolIndex<T> { let i = self.storage.len(); let o = T::default(); self.storage.push(o); ObjPoolIndex::<T> {i: i, type_marker: PhantomData} } pub fn get(&self, i: ObjPoolIndex<T>) -> &T { &self.storage[i.i] } pub fn get_mut(&mut self, i: ObjPoolIndex<T>) -> &mut T { &mut self.storage[i.i] } } #[cfg(test)] mod tests { use super::*; #[test] fn stringpool_basic_works() { let mut sp = StringPool::new(); let x = sp.add_latin1_str(b"test1"); let y = sp.add_latin1_str(b"test2"); let sx = sp.retrieve_latin1_str(x); let sy = sp.retrieve_latin1_str(y); assert_eq!(sx.raw_name(), b"test1"); assert_eq!(sy.raw_name(), b"test2"); } #[test] fn stringpool_actually_pools() { let mut sp = StringPool::new(); sp.add_latin1_str(b"test1"); sp.add_latin1_str(b"test2"); assert_eq!(sp.storage, b"test1test2"); } #[test] fn
() { let mut sp = StringPool::new(); let x = sp.add_latin1_str(b"test1"); let y = sp.add_latin1_str(b"test1"); assert_eq!(x, y); assert_eq!(sp.storage, b"test1"); } #[derive(Default)] struct ObjPoolTestObject { foo: u32 } #[test] fn objpool_basic_works() { let mut pool = ObjPool::<ObjPoolTestObject>::new(); let x = pool.alloc(); let y = pool.alloc(); { let o = pool.get_mut(x); o.foo = 123; } { let o = pool.get_mut(y); o.foo = 456; } let ox = pool.get(x); let oy = pool.get(y); assert_eq!(ox.foo, 123); assert_eq!(oy.foo, 456); } }
stringpool_interns
identifier_name
objpools.rs
/* Copyright (c) 2016-2017, Robert Ou <[email protected]> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ use std::collections::HashMap; use std::ffi::OsStr; use std::os::unix::ffi::OsStrExt; use std::marker::PhantomData; use analyzer::util::*; // We need this because the Vec can be reallocated around, but we want to keep // around some kind of reference into the storage that can keep working after // the reallocation happens. We need the internal one specifically so that // we can ensure different types of strings don't get mixed up. #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] struct StringPoolIndexInternal { start: usize, end: usize, } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct StringPoolIndexLatin1 { start: usize, end: usize, } #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug)] pub struct StringPoolIndexOsStr { start: usize, end: usize, } pub struct StringPool { storage: Vec<u8>, hashtable: HashMap<Vec<u8>, StringPoolIndexInternal>, } impl<'a> StringPool { pub fn new() -> StringPool { StringPool { storage: Vec::new(), hashtable: HashMap::new(), } } // TODO: Do we care about freeing things? fn add_internal_str(&mut self, inp: &[u8]) -> StringPoolIndexInternal { // We now need to intern the string because we need to ensure that // we always can compare string pool indices. This is needed so that // Identifiers can be compared without having to drag the string // pool around, which is in turn needed so that Identifiers can be // properly hashed. if let Some(existing_idx) = self.hashtable.get(inp) { return StringPoolIndexInternal { start: existing_idx.start, end: existing_idx.end, }; } let addition_begin = self.storage.len(); let addition_end = addition_begin + inp.len(); self.storage.extend(inp.iter().cloned()); let new_idx = StringPoolIndexInternal { start: addition_begin, end: addition_end }; self.hashtable.insert(inp.to_vec(), new_idx); new_idx } pub fn add_latin1_str(&mut self, inp: &[u8]) -> StringPoolIndexLatin1 { let int_idx = self.add_internal_str(inp); StringPoolIndexLatin1 { start: int_idx.start, end: int_idx.end, } } pub fn retrieve_latin1_str(&self, i: StringPoolIndexLatin1) -> Latin1Str { let the_slice = &self.storage[i.start..i.end]; Latin1Str::new(the_slice) } pub fn add_osstr(&mut self, inp: &OsStr) -> StringPoolIndexOsStr { let int_idx = self.add_internal_str(inp.as_bytes()); StringPoolIndexOsStr { start: int_idx.start, end: int_idx.end, } } pub fn retrieve_osstr(&self, i: StringPoolIndexOsStr) -> &OsStr { let the_slice = &self.storage[i.start..i.end]; OsStr::from_bytes(the_slice) } } #[derive(Hash, Debug)] pub struct ObjPoolIndex<T> { i: usize, type_marker: PhantomData<T> } impl<T> Copy for ObjPoolIndex<T> { } impl<T> Clone for ObjPoolIndex<T> { fn clone(&self) -> ObjPoolIndex<T> { *self }
} } impl<T> Eq for ObjPoolIndex<T> { } pub struct ObjPool<T> { storage: Vec<T> } impl<T: Default> ObjPool<T> { pub fn new() -> ObjPool<T> { ObjPool {storage: Vec::new()} } pub fn alloc(&mut self) -> ObjPoolIndex<T> { let i = self.storage.len(); let o = T::default(); self.storage.push(o); ObjPoolIndex::<T> {i: i, type_marker: PhantomData} } pub fn get(&self, i: ObjPoolIndex<T>) -> &T { &self.storage[i.i] } pub fn get_mut(&mut self, i: ObjPoolIndex<T>) -> &mut T { &mut self.storage[i.i] } } #[cfg(test)] mod tests { use super::*; #[test] fn stringpool_basic_works() { let mut sp = StringPool::new(); let x = sp.add_latin1_str(b"test1"); let y = sp.add_latin1_str(b"test2"); let sx = sp.retrieve_latin1_str(x); let sy = sp.retrieve_latin1_str(y); assert_eq!(sx.raw_name(), b"test1"); assert_eq!(sy.raw_name(), b"test2"); } #[test] fn stringpool_actually_pools() { let mut sp = StringPool::new(); sp.add_latin1_str(b"test1"); sp.add_latin1_str(b"test2"); assert_eq!(sp.storage, b"test1test2"); } #[test] fn stringpool_interns() { let mut sp = StringPool::new(); let x = sp.add_latin1_str(b"test1"); let y = sp.add_latin1_str(b"test1"); assert_eq!(x, y); assert_eq!(sp.storage, b"test1"); } #[derive(Default)] struct ObjPoolTestObject { foo: u32 } #[test] fn objpool_basic_works() { let mut pool = ObjPool::<ObjPoolTestObject>::new(); let x = pool.alloc(); let y = pool.alloc(); { let o = pool.get_mut(x); o.foo = 123; } { let o = pool.get_mut(y); o.foo = 456; } let ox = pool.get(x); let oy = pool.get(y); assert_eq!(ox.foo, 123); assert_eq!(oy.foo, 456); } }
} impl<T> PartialEq for ObjPoolIndex<T> { fn eq(&self, other: &ObjPoolIndex<T>) -> bool { self.i == other.i
random_line_split
decode.rs
//! Decodes a Bitterlemon-encoded byte stream into its original bit stream. use std::iter::Iterator; use std::result; /// Decodes a Bitterlemon byte stream into an iterator of `bool`s. /// `source` can be any iterator that yields `u8` values. /// /// # Errors /// /// Unlike encoding, decoding has a chance of failure. The exposed iterator /// will return a [`Result`] object to handle the possibility of an invalid /// input stream. The `Ok` value in this case is of type `bool`. /// /// [`Result`]: type.Result.html pub fn decode<S>(input: S) -> Decoder<S> where S : Iterator<Item=u8> { Decoder::<S> { source: input, state: DecodeState::Pending, } } /// Manages the state for decoding a Bitterlemon byte stream. /// /// To perform a decoding, see [`decode`](#fn.decode). pub struct Decoder<S> { state: DecodeState, source: S, } /// Describes errors that can occur when decoding a Bitterlemon byte stream. #[derive(Debug, PartialEq, Eq)] pub enum Error { /// Input had too few bytes to cleanly decode. The associated values are: /// /// * number of bits lost due to truncated input; /// * number of bytes still expected from the input. TruncatedInput(u8, u8), } /// Decode operations yield this on each iteration. pub type Result = result::Result<bool, Error>; impl<S> Iterator for Decoder<S> where S : Iterator<Item=u8> { type Item = Result; fn next(&mut self) -> Option<Self::Item> { // pull from source if needs be if self.must_pull() { let next = self.source.next(); self.next_with_pulled(next) } else { self.next_from_existing() } } } impl<S> Decoder<S> where S : Iterator<Item=u8> { fn must_pull(&self) -> bool { match self.state { DecodeState::Pending => true, DecodeState::Done => false, DecodeState::Run(remaining, _) => remaining == 0, DecodeState::Frame(remaining, _, stage_size) => remaining == 0 || stage_size == 0, } } fn next_with_pulled(&mut self, next: Option<u8>) -> Option<<Self as Iterator>::Item> { // handle None from source let next = match next { Some(x) => x, None => match self.state { DecodeState::Pending => { self.state = DecodeState::Done; return None; }, // source was empty DecodeState::Done => { return None; }, // always return None here DecodeState::Run(_, _) => { unreachable!("next_with_pulled called with more run bits to flush: {:?}", self.state); }, DecodeState::Frame(remaining, _, stage_size) => { debug_assert!(stage_size == 0); debug_assert!(remaining > 0); // missing bytes to complete the frame let error_specifics = Error::TruncatedInput(remaining, (remaining + 7) >> 3); return Some(Err(error_specifics)); } } }; // handle mid-frame if match self.state { DecodeState::Frame(ref mut remaining, ref mut stage, ref mut stage_size) if *remaining > 0 => { debug_assert!(*stage_size == 0); // shouldn't have pulled otherwise *stage = next; *stage_size = 8; // now fall through to real iteration logic true }, _ => false } { return self.next_from_existing(); } let got = match next { n if n < 0x80 => { // frame beginning let frame_size = byte_to_frame_size(n); self.state = DecodeState::Frame(frame_size, 0, 0); None }, n => { // new run let frame_size = byte_to_run_size(n); let mode = n >= 0xc0; self.state = if frame_size > 1 { // don't bother moving to run state if only one bit in this run // also, leaving this method in state Run(0, _) is a logic error DecodeState::Run(frame_size - 1, mode) } else { DecodeState::Pending }; Some(Ok(mode)) } }; got.or_else(|| { let next = self.source.next(); self.next_with_pulled(next) }) } fn next_from_existing(&mut self) -> Option<<Self as Iterator>::Item> { let (to_return, next_state) = match self.state { DecodeState::Pending => unreachable!(), DecodeState::Done => { return None; }, DecodeState::Run(ref mut remaining, ref run_mode) => { *remaining -= 1; (*run_mode, if *remaining == 0 {Some(DecodeState::Pending)} else {None}) }, DecodeState::Frame(ref mut remaining, ref mut stage, ref mut stage_size) => { let got_bit = (*stage & 0x80)!= 0; *stage = (*stage & 0x7f) << 1; *stage_size -= 1; *remaining -= 1; (got_bit, if *remaining == 0 {Some(DecodeState::Pending)} else {None}) } }; if let Some(next_state) = next_state { self.state = next_state; } Some(Ok(to_return)) } } fn byte_to_run_size(byte: u8) -> u8 { let byte = byte & 0x3f; if byte == 0 { 0x40 } else { byte } } fn byte_to_frame_size(byte: u8) -> u8 { if byte == 0
else { byte } } #[derive(Debug)] enum DecodeState { Pending, // should pull Run(u8, bool), // run count, is_set Frame(u8, u8, u8), // frame bit count, stage contents, stage size Done, // iteration complete } #[cfg(test)] mod test_decoder { macro_rules! decoder { ( $($e:expr),* ) => { { let v = vec![$( $e, )*]; super::decode(v.into_iter()) } } } #[test] fn empty_input() { let mut iter = decoder![]; assert_eq!(iter.next(), None); assert_eq!(iter.next(), None); } fn single_run_impl(top_bits: u8, mode: bool) { for i in 0..0x3fu8 { let run_size = super::byte_to_run_size(i); let mut iter = decoder![i+top_bits]; for _ in 0..run_size { assert_eq!(iter.next(), Some(Ok(mode))); } assert_eq!(iter.next(), None); } } #[test] fn single_run_clear() { single_run_impl(0x80, false) } #[test] fn single_run_set() { single_run_impl(0xc0, true) } #[test] fn single_byte_frame() { let case = |byte_in: u8, bool_out: bool| { let mut iter = decoder![0x01, byte_in]; assert_eq!(iter.next(), Some(Ok(bool_out))); }; case(0xff, true); case(0x00, false); case(0x80, true); case(0x7f, false); } #[test] fn full_byte_frame() { let mut iter = decoder![0x08, 0x55]; let mut expected = false; for _ in 0..8 { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); } #[test] fn two_byte_frame() { let mut iter = decoder![0x0f, 0x55, 0x55]; let mut expected = false; for _ in 0..15 { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); } #[test] fn alternate_runs_frames() { let case = |bytes: &[u8], count: usize, first_output: bool| { let mut iter = super::decode(bytes.iter().map(|&b| b)); let mut expected = first_output; for _ in 0..count { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); }; case(&[0xc1, 0x10, 0x55, 0x55, 0x81], 18, true); case(&[0x81, 0x10, 0xaa, 0xaa, 0xc1], 18, false); case(&[0x08, 0xaa, 0xc1, 0x08, 0x55], 17, true); case(&[0x08, 0x55, 0x81, 0x08, 0xaa], 17, false); } #[test] fn error_on_frame_cutoff() { let case = |bytes: &[u8], bits_lost: u8, bytes_missing: u8| { let mut iter = super::decode(bytes.iter().map(|&b| b)); let ok_count = (bytes.len() - 1) * 8; for _ in 0..ok_count { assert!(match iter.next() { Some(Ok(_)) => true, _ => false }); } let error = iter.next(); assert!(error.is_some()); let error = error.unwrap(); assert!(error.is_err()); match error.unwrap_err() { super::Error::TruncatedInput(pl, bm) => { assert_eq!(pl, bits_lost); assert_eq!(bm, bytes_missing); } }; }; case(&[0x01], 1, 1); case(&[0x02], 2, 1); case(&[0x00], 0x80, 0x10); case(&[0x09, 0xff], 1, 1); case(&[0x7f, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14], 7, 1); } #[test] fn next_none_idempotence() { let src = &[0xc1u8]; let mut iter = super::decode(src.iter().map(|&b| b)); assert!(iter.next().is_some()); for _ in 0..20 { assert_eq!(iter.next(), None); } } }
{ 0x80 }
conditional_block
decode.rs
//! Decodes a Bitterlemon-encoded byte stream into its original bit stream. use std::iter::Iterator; use std::result; /// Decodes a Bitterlemon byte stream into an iterator of `bool`s. /// `source` can be any iterator that yields `u8` values. /// /// # Errors /// /// Unlike encoding, decoding has a chance of failure. The exposed iterator /// will return a [`Result`] object to handle the possibility of an invalid /// input stream. The `Ok` value in this case is of type `bool`. /// /// [`Result`]: type.Result.html pub fn decode<S>(input: S) -> Decoder<S> where S : Iterator<Item=u8> { Decoder::<S> { source: input, state: DecodeState::Pending, } } /// Manages the state for decoding a Bitterlemon byte stream. /// /// To perform a decoding, see [`decode`](#fn.decode). pub struct Decoder<S> { state: DecodeState, source: S, } /// Describes errors that can occur when decoding a Bitterlemon byte stream. #[derive(Debug, PartialEq, Eq)] pub enum Error { /// Input had too few bytes to cleanly decode. The associated values are: /// /// * number of bits lost due to truncated input; /// * number of bytes still expected from the input. TruncatedInput(u8, u8), } /// Decode operations yield this on each iteration. pub type Result = result::Result<bool, Error>; impl<S> Iterator for Decoder<S> where S : Iterator<Item=u8> { type Item = Result; fn next(&mut self) -> Option<Self::Item> { // pull from source if needs be if self.must_pull() { let next = self.source.next(); self.next_with_pulled(next) } else { self.next_from_existing() } } } impl<S> Decoder<S> where S : Iterator<Item=u8> { fn must_pull(&self) -> bool { match self.state { DecodeState::Pending => true, DecodeState::Done => false, DecodeState::Run(remaining, _) => remaining == 0, DecodeState::Frame(remaining, _, stage_size) => remaining == 0 || stage_size == 0, } } fn next_with_pulled(&mut self, next: Option<u8>) -> Option<<Self as Iterator>::Item> { // handle None from source let next = match next { Some(x) => x, None => match self.state { DecodeState::Pending => { self.state = DecodeState::Done; return None; }, // source was empty DecodeState::Done => { return None; }, // always return None here DecodeState::Run(_, _) => { unreachable!("next_with_pulled called with more run bits to flush: {:?}", self.state); }, DecodeState::Frame(remaining, _, stage_size) => { debug_assert!(stage_size == 0); debug_assert!(remaining > 0); // missing bytes to complete the frame let error_specifics = Error::TruncatedInput(remaining, (remaining + 7) >> 3); return Some(Err(error_specifics)); } } }; // handle mid-frame if match self.state { DecodeState::Frame(ref mut remaining, ref mut stage, ref mut stage_size) if *remaining > 0 => { debug_assert!(*stage_size == 0); // shouldn't have pulled otherwise *stage = next; *stage_size = 8; // now fall through to real iteration logic true }, _ => false } { return self.next_from_existing(); } let got = match next { n if n < 0x80 => { // frame beginning let frame_size = byte_to_frame_size(n); self.state = DecodeState::Frame(frame_size, 0, 0); None }, n => { // new run let frame_size = byte_to_run_size(n); let mode = n >= 0xc0; self.state = if frame_size > 1 { // don't bother moving to run state if only one bit in this run // also, leaving this method in state Run(0, _) is a logic error DecodeState::Run(frame_size - 1, mode) } else { DecodeState::Pending }; Some(Ok(mode)) } }; got.or_else(|| { let next = self.source.next(); self.next_with_pulled(next) }) } fn next_from_existing(&mut self) -> Option<<Self as Iterator>::Item> { let (to_return, next_state) = match self.state { DecodeState::Pending => unreachable!(), DecodeState::Done => { return None; }, DecodeState::Run(ref mut remaining, ref run_mode) => { *remaining -= 1; (*run_mode, if *remaining == 0 {Some(DecodeState::Pending)} else {None}) }, DecodeState::Frame(ref mut remaining, ref mut stage, ref mut stage_size) => { let got_bit = (*stage & 0x80)!= 0; *stage = (*stage & 0x7f) << 1; *stage_size -= 1; *remaining -= 1; (got_bit, if *remaining == 0 {Some(DecodeState::Pending)} else {None}) } }; if let Some(next_state) = next_state { self.state = next_state; } Some(Ok(to_return)) }
fn byte_to_run_size(byte: u8) -> u8 { let byte = byte & 0x3f; if byte == 0 { 0x40 } else { byte } } fn byte_to_frame_size(byte: u8) -> u8 { if byte == 0 { 0x80 } else { byte } } #[derive(Debug)] enum DecodeState { Pending, // should pull Run(u8, bool), // run count, is_set Frame(u8, u8, u8), // frame bit count, stage contents, stage size Done, // iteration complete } #[cfg(test)] mod test_decoder { macro_rules! decoder { ( $($e:expr),* ) => { { let v = vec![$( $e, )*]; super::decode(v.into_iter()) } } } #[test] fn empty_input() { let mut iter = decoder![]; assert_eq!(iter.next(), None); assert_eq!(iter.next(), None); } fn single_run_impl(top_bits: u8, mode: bool) { for i in 0..0x3fu8 { let run_size = super::byte_to_run_size(i); let mut iter = decoder![i+top_bits]; for _ in 0..run_size { assert_eq!(iter.next(), Some(Ok(mode))); } assert_eq!(iter.next(), None); } } #[test] fn single_run_clear() { single_run_impl(0x80, false) } #[test] fn single_run_set() { single_run_impl(0xc0, true) } #[test] fn single_byte_frame() { let case = |byte_in: u8, bool_out: bool| { let mut iter = decoder![0x01, byte_in]; assert_eq!(iter.next(), Some(Ok(bool_out))); }; case(0xff, true); case(0x00, false); case(0x80, true); case(0x7f, false); } #[test] fn full_byte_frame() { let mut iter = decoder![0x08, 0x55]; let mut expected = false; for _ in 0..8 { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); } #[test] fn two_byte_frame() { let mut iter = decoder![0x0f, 0x55, 0x55]; let mut expected = false; for _ in 0..15 { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); } #[test] fn alternate_runs_frames() { let case = |bytes: &[u8], count: usize, first_output: bool| { let mut iter = super::decode(bytes.iter().map(|&b| b)); let mut expected = first_output; for _ in 0..count { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); }; case(&[0xc1, 0x10, 0x55, 0x55, 0x81], 18, true); case(&[0x81, 0x10, 0xaa, 0xaa, 0xc1], 18, false); case(&[0x08, 0xaa, 0xc1, 0x08, 0x55], 17, true); case(&[0x08, 0x55, 0x81, 0x08, 0xaa], 17, false); } #[test] fn error_on_frame_cutoff() { let case = |bytes: &[u8], bits_lost: u8, bytes_missing: u8| { let mut iter = super::decode(bytes.iter().map(|&b| b)); let ok_count = (bytes.len() - 1) * 8; for _ in 0..ok_count { assert!(match iter.next() { Some(Ok(_)) => true, _ => false }); } let error = iter.next(); assert!(error.is_some()); let error = error.unwrap(); assert!(error.is_err()); match error.unwrap_err() { super::Error::TruncatedInput(pl, bm) => { assert_eq!(pl, bits_lost); assert_eq!(bm, bytes_missing); } }; }; case(&[0x01], 1, 1); case(&[0x02], 2, 1); case(&[0x00], 0x80, 0x10); case(&[0x09, 0xff], 1, 1); case(&[0x7f, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14], 7, 1); } #[test] fn next_none_idempotence() { let src = &[0xc1u8]; let mut iter = super::decode(src.iter().map(|&b| b)); assert!(iter.next().is_some()); for _ in 0..20 { assert_eq!(iter.next(), None); } } }
}
random_line_split
decode.rs
//! Decodes a Bitterlemon-encoded byte stream into its original bit stream. use std::iter::Iterator; use std::result; /// Decodes a Bitterlemon byte stream into an iterator of `bool`s. /// `source` can be any iterator that yields `u8` values. /// /// # Errors /// /// Unlike encoding, decoding has a chance of failure. The exposed iterator /// will return a [`Result`] object to handle the possibility of an invalid /// input stream. The `Ok` value in this case is of type `bool`. /// /// [`Result`]: type.Result.html pub fn decode<S>(input: S) -> Decoder<S> where S : Iterator<Item=u8> { Decoder::<S> { source: input, state: DecodeState::Pending, } } /// Manages the state for decoding a Bitterlemon byte stream. /// /// To perform a decoding, see [`decode`](#fn.decode). pub struct Decoder<S> { state: DecodeState, source: S, } /// Describes errors that can occur when decoding a Bitterlemon byte stream. #[derive(Debug, PartialEq, Eq)] pub enum Error { /// Input had too few bytes to cleanly decode. The associated values are: /// /// * number of bits lost due to truncated input; /// * number of bytes still expected from the input. TruncatedInput(u8, u8), } /// Decode operations yield this on each iteration. pub type Result = result::Result<bool, Error>; impl<S> Iterator for Decoder<S> where S : Iterator<Item=u8> { type Item = Result; fn next(&mut self) -> Option<Self::Item> { // pull from source if needs be if self.must_pull() { let next = self.source.next(); self.next_with_pulled(next) } else { self.next_from_existing() } } } impl<S> Decoder<S> where S : Iterator<Item=u8> { fn must_pull(&self) -> bool { match self.state { DecodeState::Pending => true, DecodeState::Done => false, DecodeState::Run(remaining, _) => remaining == 0, DecodeState::Frame(remaining, _, stage_size) => remaining == 0 || stage_size == 0, } } fn next_with_pulled(&mut self, next: Option<u8>) -> Option<<Self as Iterator>::Item> { // handle None from source let next = match next { Some(x) => x, None => match self.state { DecodeState::Pending => { self.state = DecodeState::Done; return None; }, // source was empty DecodeState::Done => { return None; }, // always return None here DecodeState::Run(_, _) => { unreachable!("next_with_pulled called with more run bits to flush: {:?}", self.state); }, DecodeState::Frame(remaining, _, stage_size) => { debug_assert!(stage_size == 0); debug_assert!(remaining > 0); // missing bytes to complete the frame let error_specifics = Error::TruncatedInput(remaining, (remaining + 7) >> 3); return Some(Err(error_specifics)); } } }; // handle mid-frame if match self.state { DecodeState::Frame(ref mut remaining, ref mut stage, ref mut stage_size) if *remaining > 0 => { debug_assert!(*stage_size == 0); // shouldn't have pulled otherwise *stage = next; *stage_size = 8; // now fall through to real iteration logic true }, _ => false } { return self.next_from_existing(); } let got = match next { n if n < 0x80 => { // frame beginning let frame_size = byte_to_frame_size(n); self.state = DecodeState::Frame(frame_size, 0, 0); None }, n => { // new run let frame_size = byte_to_run_size(n); let mode = n >= 0xc0; self.state = if frame_size > 1 { // don't bother moving to run state if only one bit in this run // also, leaving this method in state Run(0, _) is a logic error DecodeState::Run(frame_size - 1, mode) } else { DecodeState::Pending }; Some(Ok(mode)) } }; got.or_else(|| { let next = self.source.next(); self.next_with_pulled(next) }) } fn
(&mut self) -> Option<<Self as Iterator>::Item> { let (to_return, next_state) = match self.state { DecodeState::Pending => unreachable!(), DecodeState::Done => { return None; }, DecodeState::Run(ref mut remaining, ref run_mode) => { *remaining -= 1; (*run_mode, if *remaining == 0 {Some(DecodeState::Pending)} else {None}) }, DecodeState::Frame(ref mut remaining, ref mut stage, ref mut stage_size) => { let got_bit = (*stage & 0x80)!= 0; *stage = (*stage & 0x7f) << 1; *stage_size -= 1; *remaining -= 1; (got_bit, if *remaining == 0 {Some(DecodeState::Pending)} else {None}) } }; if let Some(next_state) = next_state { self.state = next_state; } Some(Ok(to_return)) } } fn byte_to_run_size(byte: u8) -> u8 { let byte = byte & 0x3f; if byte == 0 { 0x40 } else { byte } } fn byte_to_frame_size(byte: u8) -> u8 { if byte == 0 { 0x80 } else { byte } } #[derive(Debug)] enum DecodeState { Pending, // should pull Run(u8, bool), // run count, is_set Frame(u8, u8, u8), // frame bit count, stage contents, stage size Done, // iteration complete } #[cfg(test)] mod test_decoder { macro_rules! decoder { ( $($e:expr),* ) => { { let v = vec![$( $e, )*]; super::decode(v.into_iter()) } } } #[test] fn empty_input() { let mut iter = decoder![]; assert_eq!(iter.next(), None); assert_eq!(iter.next(), None); } fn single_run_impl(top_bits: u8, mode: bool) { for i in 0..0x3fu8 { let run_size = super::byte_to_run_size(i); let mut iter = decoder![i+top_bits]; for _ in 0..run_size { assert_eq!(iter.next(), Some(Ok(mode))); } assert_eq!(iter.next(), None); } } #[test] fn single_run_clear() { single_run_impl(0x80, false) } #[test] fn single_run_set() { single_run_impl(0xc0, true) } #[test] fn single_byte_frame() { let case = |byte_in: u8, bool_out: bool| { let mut iter = decoder![0x01, byte_in]; assert_eq!(iter.next(), Some(Ok(bool_out))); }; case(0xff, true); case(0x00, false); case(0x80, true); case(0x7f, false); } #[test] fn full_byte_frame() { let mut iter = decoder![0x08, 0x55]; let mut expected = false; for _ in 0..8 { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); } #[test] fn two_byte_frame() { let mut iter = decoder![0x0f, 0x55, 0x55]; let mut expected = false; for _ in 0..15 { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); } #[test] fn alternate_runs_frames() { let case = |bytes: &[u8], count: usize, first_output: bool| { let mut iter = super::decode(bytes.iter().map(|&b| b)); let mut expected = first_output; for _ in 0..count { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); }; case(&[0xc1, 0x10, 0x55, 0x55, 0x81], 18, true); case(&[0x81, 0x10, 0xaa, 0xaa, 0xc1], 18, false); case(&[0x08, 0xaa, 0xc1, 0x08, 0x55], 17, true); case(&[0x08, 0x55, 0x81, 0x08, 0xaa], 17, false); } #[test] fn error_on_frame_cutoff() { let case = |bytes: &[u8], bits_lost: u8, bytes_missing: u8| { let mut iter = super::decode(bytes.iter().map(|&b| b)); let ok_count = (bytes.len() - 1) * 8; for _ in 0..ok_count { assert!(match iter.next() { Some(Ok(_)) => true, _ => false }); } let error = iter.next(); assert!(error.is_some()); let error = error.unwrap(); assert!(error.is_err()); match error.unwrap_err() { super::Error::TruncatedInput(pl, bm) => { assert_eq!(pl, bits_lost); assert_eq!(bm, bytes_missing); } }; }; case(&[0x01], 1, 1); case(&[0x02], 2, 1); case(&[0x00], 0x80, 0x10); case(&[0x09, 0xff], 1, 1); case(&[0x7f, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14], 7, 1); } #[test] fn next_none_idempotence() { let src = &[0xc1u8]; let mut iter = super::decode(src.iter().map(|&b| b)); assert!(iter.next().is_some()); for _ in 0..20 { assert_eq!(iter.next(), None); } } }
next_from_existing
identifier_name
decode.rs
//! Decodes a Bitterlemon-encoded byte stream into its original bit stream. use std::iter::Iterator; use std::result; /// Decodes a Bitterlemon byte stream into an iterator of `bool`s. /// `source` can be any iterator that yields `u8` values. /// /// # Errors /// /// Unlike encoding, decoding has a chance of failure. The exposed iterator /// will return a [`Result`] object to handle the possibility of an invalid /// input stream. The `Ok` value in this case is of type `bool`. /// /// [`Result`]: type.Result.html pub fn decode<S>(input: S) -> Decoder<S> where S : Iterator<Item=u8>
/// Manages the state for decoding a Bitterlemon byte stream. /// /// To perform a decoding, see [`decode`](#fn.decode). pub struct Decoder<S> { state: DecodeState, source: S, } /// Describes errors that can occur when decoding a Bitterlemon byte stream. #[derive(Debug, PartialEq, Eq)] pub enum Error { /// Input had too few bytes to cleanly decode. The associated values are: /// /// * number of bits lost due to truncated input; /// * number of bytes still expected from the input. TruncatedInput(u8, u8), } /// Decode operations yield this on each iteration. pub type Result = result::Result<bool, Error>; impl<S> Iterator for Decoder<S> where S : Iterator<Item=u8> { type Item = Result; fn next(&mut self) -> Option<Self::Item> { // pull from source if needs be if self.must_pull() { let next = self.source.next(); self.next_with_pulled(next) } else { self.next_from_existing() } } } impl<S> Decoder<S> where S : Iterator<Item=u8> { fn must_pull(&self) -> bool { match self.state { DecodeState::Pending => true, DecodeState::Done => false, DecodeState::Run(remaining, _) => remaining == 0, DecodeState::Frame(remaining, _, stage_size) => remaining == 0 || stage_size == 0, } } fn next_with_pulled(&mut self, next: Option<u8>) -> Option<<Self as Iterator>::Item> { // handle None from source let next = match next { Some(x) => x, None => match self.state { DecodeState::Pending => { self.state = DecodeState::Done; return None; }, // source was empty DecodeState::Done => { return None; }, // always return None here DecodeState::Run(_, _) => { unreachable!("next_with_pulled called with more run bits to flush: {:?}", self.state); }, DecodeState::Frame(remaining, _, stage_size) => { debug_assert!(stage_size == 0); debug_assert!(remaining > 0); // missing bytes to complete the frame let error_specifics = Error::TruncatedInput(remaining, (remaining + 7) >> 3); return Some(Err(error_specifics)); } } }; // handle mid-frame if match self.state { DecodeState::Frame(ref mut remaining, ref mut stage, ref mut stage_size) if *remaining > 0 => { debug_assert!(*stage_size == 0); // shouldn't have pulled otherwise *stage = next; *stage_size = 8; // now fall through to real iteration logic true }, _ => false } { return self.next_from_existing(); } let got = match next { n if n < 0x80 => { // frame beginning let frame_size = byte_to_frame_size(n); self.state = DecodeState::Frame(frame_size, 0, 0); None }, n => { // new run let frame_size = byte_to_run_size(n); let mode = n >= 0xc0; self.state = if frame_size > 1 { // don't bother moving to run state if only one bit in this run // also, leaving this method in state Run(0, _) is a logic error DecodeState::Run(frame_size - 1, mode) } else { DecodeState::Pending }; Some(Ok(mode)) } }; got.or_else(|| { let next = self.source.next(); self.next_with_pulled(next) }) } fn next_from_existing(&mut self) -> Option<<Self as Iterator>::Item> { let (to_return, next_state) = match self.state { DecodeState::Pending => unreachable!(), DecodeState::Done => { return None; }, DecodeState::Run(ref mut remaining, ref run_mode) => { *remaining -= 1; (*run_mode, if *remaining == 0 {Some(DecodeState::Pending)} else {None}) }, DecodeState::Frame(ref mut remaining, ref mut stage, ref mut stage_size) => { let got_bit = (*stage & 0x80)!= 0; *stage = (*stage & 0x7f) << 1; *stage_size -= 1; *remaining -= 1; (got_bit, if *remaining == 0 {Some(DecodeState::Pending)} else {None}) } }; if let Some(next_state) = next_state { self.state = next_state; } Some(Ok(to_return)) } } fn byte_to_run_size(byte: u8) -> u8 { let byte = byte & 0x3f; if byte == 0 { 0x40 } else { byte } } fn byte_to_frame_size(byte: u8) -> u8 { if byte == 0 { 0x80 } else { byte } } #[derive(Debug)] enum DecodeState { Pending, // should pull Run(u8, bool), // run count, is_set Frame(u8, u8, u8), // frame bit count, stage contents, stage size Done, // iteration complete } #[cfg(test)] mod test_decoder { macro_rules! decoder { ( $($e:expr),* ) => { { let v = vec![$( $e, )*]; super::decode(v.into_iter()) } } } #[test] fn empty_input() { let mut iter = decoder![]; assert_eq!(iter.next(), None); assert_eq!(iter.next(), None); } fn single_run_impl(top_bits: u8, mode: bool) { for i in 0..0x3fu8 { let run_size = super::byte_to_run_size(i); let mut iter = decoder![i+top_bits]; for _ in 0..run_size { assert_eq!(iter.next(), Some(Ok(mode))); } assert_eq!(iter.next(), None); } } #[test] fn single_run_clear() { single_run_impl(0x80, false) } #[test] fn single_run_set() { single_run_impl(0xc0, true) } #[test] fn single_byte_frame() { let case = |byte_in: u8, bool_out: bool| { let mut iter = decoder![0x01, byte_in]; assert_eq!(iter.next(), Some(Ok(bool_out))); }; case(0xff, true); case(0x00, false); case(0x80, true); case(0x7f, false); } #[test] fn full_byte_frame() { let mut iter = decoder![0x08, 0x55]; let mut expected = false; for _ in 0..8 { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); } #[test] fn two_byte_frame() { let mut iter = decoder![0x0f, 0x55, 0x55]; let mut expected = false; for _ in 0..15 { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); } #[test] fn alternate_runs_frames() { let case = |bytes: &[u8], count: usize, first_output: bool| { let mut iter = super::decode(bytes.iter().map(|&b| b)); let mut expected = first_output; for _ in 0..count { assert_eq!(iter.next(), Some(Ok(expected))); expected =!expected; } assert_eq!(iter.next(), None); }; case(&[0xc1, 0x10, 0x55, 0x55, 0x81], 18, true); case(&[0x81, 0x10, 0xaa, 0xaa, 0xc1], 18, false); case(&[0x08, 0xaa, 0xc1, 0x08, 0x55], 17, true); case(&[0x08, 0x55, 0x81, 0x08, 0xaa], 17, false); } #[test] fn error_on_frame_cutoff() { let case = |bytes: &[u8], bits_lost: u8, bytes_missing: u8| { let mut iter = super::decode(bytes.iter().map(|&b| b)); let ok_count = (bytes.len() - 1) * 8; for _ in 0..ok_count { assert!(match iter.next() { Some(Ok(_)) => true, _ => false }); } let error = iter.next(); assert!(error.is_some()); let error = error.unwrap(); assert!(error.is_err()); match error.unwrap_err() { super::Error::TruncatedInput(pl, bm) => { assert_eq!(pl, bits_lost); assert_eq!(bm, bytes_missing); } }; }; case(&[0x01], 1, 1); case(&[0x02], 2, 1); case(&[0x00], 0x80, 0x10); case(&[0x09, 0xff], 1, 1); case(&[0x7f, 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14], 7, 1); } #[test] fn next_none_idempotence() { let src = &[0xc1u8]; let mut iter = super::decode(src.iter().map(|&b| b)); assert!(iter.next().is_some()); for _ in 0..20 { assert_eq!(iter.next(), None); } } }
{ Decoder::<S> { source: input, state: DecodeState::Pending, } }
identifier_body
filter.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use serde::{Deserialize, Deserializer, Serialize, Serializer, Error}; use serde_json::value; use jsonrpc_core::Value; use ethcore::filter::Filter as EthFilter; use ethcore::client::BlockId; use v1::types::{BlockNumber, H160, H256, Log}; /// Variadic value #[derive(Debug, PartialEq, Clone)] pub enum VariadicValue<T> where T: Deserialize { /// Single Single(T), /// List Multiple(Vec<T>), /// None Null, } impl<T> Deserialize for VariadicValue<T> where T: Deserialize { fn deserialize<D>(deserializer: &mut D) -> Result<VariadicValue<T>, D::Error> where D: Deserializer { let v = try!(Value::deserialize(deserializer)); if v.is_null() { return Ok(VariadicValue::Null); } Deserialize::deserialize(&mut value::Deserializer::new(v.clone())).map(VariadicValue::Single) .or_else(|_| Deserialize::deserialize(&mut value::Deserializer::new(v.clone())).map(VariadicValue::Multiple)) .map_err(|_| Error::custom("")) // unreachable, but types must match } } /// Filter Address pub type FilterAddress = VariadicValue<H160>; /// Topic pub type Topic = VariadicValue<H256>; /// Filter #[derive(Debug, PartialEq, Clone, Deserialize)] #[serde(deny_unknown_fields)] pub struct Filter { /// From Block #[serde(rename="fromBlock")] pub from_block: Option<BlockNumber>, /// To Block #[serde(rename="toBlock")] pub to_block: Option<BlockNumber>, /// Address pub address: Option<FilterAddress>, /// Topics pub topics: Option<Vec<Topic>>, /// Limit pub limit: Option<usize>, } impl Into<EthFilter> for Filter { fn into(self) -> EthFilter { EthFilter { from_block: self.from_block.map_or_else(|| BlockId::Latest, Into::into), to_block: self.to_block.map_or_else(|| BlockId::Latest, Into::into), address: self.address.and_then(|address| match address { VariadicValue::Null => None, VariadicValue::Single(a) => Some(vec![a.into()]), VariadicValue::Multiple(a) => Some(a.into_iter().map(Into::into).collect()) }), topics: { let mut iter = self.topics.map_or_else(Vec::new, |topics| topics.into_iter().take(4).map(|topic| match topic { VariadicValue::Null => None, VariadicValue::Single(t) => Some(vec![t.into()]), VariadicValue::Multiple(t) => Some(t.into_iter().map(Into::into).collect()) }).collect()).into_iter(); vec![ iter.next().unwrap_or(None), iter.next().unwrap_or(None), iter.next().unwrap_or(None), iter.next().unwrap_or(None) ] }, limit: self.limit, } } } /// Results of the filter_changes RPC. #[derive(Debug, PartialEq)] pub enum FilterChanges { /// New logs. Logs(Vec<Log>), /// New hashes (block or transactions) Hashes(Vec<H256>), /// Empty result, Empty, } impl Serialize for FilterChanges { fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error> where S: Serializer { match *self { FilterChanges::Logs(ref logs) => logs.serialize(s), FilterChanges::Hashes(ref hashes) => hashes.serialize(s), FilterChanges::Empty => (&[] as &[Value]).serialize(s), } } } #[cfg(test)] mod tests { use serde_json; use std::str::FromStr; use util::hash::H256; use super::{VariadicValue, Topic, Filter}; use v1::types::BlockNumber; use ethcore::filter::Filter as EthFilter; use ethcore::client::BlockId;
let deserialized: Vec<Topic> = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, vec![ VariadicValue::Single(H256::from_str("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b").unwrap().into()), VariadicValue::Null, VariadicValue::Multiple(vec![ H256::from_str("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b").unwrap().into(), H256::from_str("0000000000000000000000000aff3454fce5edbc8cca8697c15331677e6ebccc").unwrap().into(), ]) ]); } #[test] fn filter_deserialization() { let s = r#"{"fromBlock":"earliest","toBlock":"latest"}"#; let deserialized: Filter = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, Filter { from_block: Some(BlockNumber::Earliest), to_block: Some(BlockNumber::Latest), address: None, topics: None, limit: None, }); } #[test] fn filter_conversion() { let filter = Filter { from_block: Some(BlockNumber::Earliest), to_block: Some(BlockNumber::Latest), address: Some(VariadicValue::Multiple(vec![])), topics: Some(vec![ VariadicValue::Null, VariadicValue::Single("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b".into()), VariadicValue::Null, ]), limit: None, }; let eth_filter: EthFilter = filter.into(); assert_eq!(eth_filter, EthFilter { from_block: BlockId::Earliest, to_block: BlockId::Latest, address: Some(vec![]), topics: vec![ None, Some(vec!["000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b".into()]), None, None, ], limit: None, }); } }
#[test] fn topic_deserialization() { let s = r#"["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b", null, ["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b", "0x0000000000000000000000000aff3454fce5edbc8cca8697c15331677e6ebccc"]]"#;
random_line_split
filter.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use serde::{Deserialize, Deserializer, Serialize, Serializer, Error}; use serde_json::value; use jsonrpc_core::Value; use ethcore::filter::Filter as EthFilter; use ethcore::client::BlockId; use v1::types::{BlockNumber, H160, H256, Log}; /// Variadic value #[derive(Debug, PartialEq, Clone)] pub enum VariadicValue<T> where T: Deserialize { /// Single Single(T), /// List Multiple(Vec<T>), /// None Null, } impl<T> Deserialize for VariadicValue<T> where T: Deserialize { fn deserialize<D>(deserializer: &mut D) -> Result<VariadicValue<T>, D::Error> where D: Deserializer { let v = try!(Value::deserialize(deserializer)); if v.is_null() { return Ok(VariadicValue::Null); } Deserialize::deserialize(&mut value::Deserializer::new(v.clone())).map(VariadicValue::Single) .or_else(|_| Deserialize::deserialize(&mut value::Deserializer::new(v.clone())).map(VariadicValue::Multiple)) .map_err(|_| Error::custom("")) // unreachable, but types must match } } /// Filter Address pub type FilterAddress = VariadicValue<H160>; /// Topic pub type Topic = VariadicValue<H256>; /// Filter #[derive(Debug, PartialEq, Clone, Deserialize)] #[serde(deny_unknown_fields)] pub struct Filter { /// From Block #[serde(rename="fromBlock")] pub from_block: Option<BlockNumber>, /// To Block #[serde(rename="toBlock")] pub to_block: Option<BlockNumber>, /// Address pub address: Option<FilterAddress>, /// Topics pub topics: Option<Vec<Topic>>, /// Limit pub limit: Option<usize>, } impl Into<EthFilter> for Filter { fn into(self) -> EthFilter { EthFilter { from_block: self.from_block.map_or_else(|| BlockId::Latest, Into::into), to_block: self.to_block.map_or_else(|| BlockId::Latest, Into::into), address: self.address.and_then(|address| match address { VariadicValue::Null => None, VariadicValue::Single(a) => Some(vec![a.into()]), VariadicValue::Multiple(a) => Some(a.into_iter().map(Into::into).collect()) }), topics: { let mut iter = self.topics.map_or_else(Vec::new, |topics| topics.into_iter().take(4).map(|topic| match topic { VariadicValue::Null => None, VariadicValue::Single(t) => Some(vec![t.into()]), VariadicValue::Multiple(t) => Some(t.into_iter().map(Into::into).collect()) }).collect()).into_iter(); vec![ iter.next().unwrap_or(None), iter.next().unwrap_or(None), iter.next().unwrap_or(None), iter.next().unwrap_or(None) ] }, limit: self.limit, } } } /// Results of the filter_changes RPC. #[derive(Debug, PartialEq)] pub enum FilterChanges { /// New logs. Logs(Vec<Log>), /// New hashes (block or transactions) Hashes(Vec<H256>), /// Empty result, Empty, } impl Serialize for FilterChanges { fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error> where S: Serializer { match *self { FilterChanges::Logs(ref logs) => logs.serialize(s), FilterChanges::Hashes(ref hashes) => hashes.serialize(s), FilterChanges::Empty => (&[] as &[Value]).serialize(s), } } } #[cfg(test)] mod tests { use serde_json; use std::str::FromStr; use util::hash::H256; use super::{VariadicValue, Topic, Filter}; use v1::types::BlockNumber; use ethcore::filter::Filter as EthFilter; use ethcore::client::BlockId; #[test] fn topic_deserialization() { let s = r#"["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b", null, ["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b", "0x0000000000000000000000000aff3454fce5edbc8cca8697c15331677e6ebccc"]]"#; let deserialized: Vec<Topic> = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, vec![ VariadicValue::Single(H256::from_str("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b").unwrap().into()), VariadicValue::Null, VariadicValue::Multiple(vec![ H256::from_str("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b").unwrap().into(), H256::from_str("0000000000000000000000000aff3454fce5edbc8cca8697c15331677e6ebccc").unwrap().into(), ]) ]); } #[test] fn filter_deserialization() { let s = r#"{"fromBlock":"earliest","toBlock":"latest"}"#; let deserialized: Filter = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, Filter { from_block: Some(BlockNumber::Earliest), to_block: Some(BlockNumber::Latest), address: None, topics: None, limit: None, }); } #[test] fn
() { let filter = Filter { from_block: Some(BlockNumber::Earliest), to_block: Some(BlockNumber::Latest), address: Some(VariadicValue::Multiple(vec![])), topics: Some(vec![ VariadicValue::Null, VariadicValue::Single("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b".into()), VariadicValue::Null, ]), limit: None, }; let eth_filter: EthFilter = filter.into(); assert_eq!(eth_filter, EthFilter { from_block: BlockId::Earliest, to_block: BlockId::Latest, address: Some(vec![]), topics: vec![ None, Some(vec!["000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b".into()]), None, None, ], limit: None, }); } }
filter_conversion
identifier_name
filter.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use serde::{Deserialize, Deserializer, Serialize, Serializer, Error}; use serde_json::value; use jsonrpc_core::Value; use ethcore::filter::Filter as EthFilter; use ethcore::client::BlockId; use v1::types::{BlockNumber, H160, H256, Log}; /// Variadic value #[derive(Debug, PartialEq, Clone)] pub enum VariadicValue<T> where T: Deserialize { /// Single Single(T), /// List Multiple(Vec<T>), /// None Null, } impl<T> Deserialize for VariadicValue<T> where T: Deserialize { fn deserialize<D>(deserializer: &mut D) -> Result<VariadicValue<T>, D::Error> where D: Deserializer { let v = try!(Value::deserialize(deserializer)); if v.is_null() { return Ok(VariadicValue::Null); } Deserialize::deserialize(&mut value::Deserializer::new(v.clone())).map(VariadicValue::Single) .or_else(|_| Deserialize::deserialize(&mut value::Deserializer::new(v.clone())).map(VariadicValue::Multiple)) .map_err(|_| Error::custom("")) // unreachable, but types must match } } /// Filter Address pub type FilterAddress = VariadicValue<H160>; /// Topic pub type Topic = VariadicValue<H256>; /// Filter #[derive(Debug, PartialEq, Clone, Deserialize)] #[serde(deny_unknown_fields)] pub struct Filter { /// From Block #[serde(rename="fromBlock")] pub from_block: Option<BlockNumber>, /// To Block #[serde(rename="toBlock")] pub to_block: Option<BlockNumber>, /// Address pub address: Option<FilterAddress>, /// Topics pub topics: Option<Vec<Topic>>, /// Limit pub limit: Option<usize>, } impl Into<EthFilter> for Filter { fn into(self) -> EthFilter { EthFilter { from_block: self.from_block.map_or_else(|| BlockId::Latest, Into::into), to_block: self.to_block.map_or_else(|| BlockId::Latest, Into::into), address: self.address.and_then(|address| match address { VariadicValue::Null => None, VariadicValue::Single(a) => Some(vec![a.into()]), VariadicValue::Multiple(a) => Some(a.into_iter().map(Into::into).collect()) }), topics: { let mut iter = self.topics.map_or_else(Vec::new, |topics| topics.into_iter().take(4).map(|topic| match topic { VariadicValue::Null => None, VariadicValue::Single(t) => Some(vec![t.into()]), VariadicValue::Multiple(t) => Some(t.into_iter().map(Into::into).collect()) }).collect()).into_iter(); vec![ iter.next().unwrap_or(None), iter.next().unwrap_or(None), iter.next().unwrap_or(None), iter.next().unwrap_or(None) ] }, limit: self.limit, } } } /// Results of the filter_changes RPC. #[derive(Debug, PartialEq)] pub enum FilterChanges { /// New logs. Logs(Vec<Log>), /// New hashes (block or transactions) Hashes(Vec<H256>), /// Empty result, Empty, } impl Serialize for FilterChanges { fn serialize<S>(&self, s: &mut S) -> Result<(), S::Error> where S: Serializer
} #[cfg(test)] mod tests { use serde_json; use std::str::FromStr; use util::hash::H256; use super::{VariadicValue, Topic, Filter}; use v1::types::BlockNumber; use ethcore::filter::Filter as EthFilter; use ethcore::client::BlockId; #[test] fn topic_deserialization() { let s = r#"["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b", null, ["0x000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b", "0x0000000000000000000000000aff3454fce5edbc8cca8697c15331677e6ebccc"]]"#; let deserialized: Vec<Topic> = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, vec![ VariadicValue::Single(H256::from_str("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b").unwrap().into()), VariadicValue::Null, VariadicValue::Multiple(vec![ H256::from_str("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b").unwrap().into(), H256::from_str("0000000000000000000000000aff3454fce5edbc8cca8697c15331677e6ebccc").unwrap().into(), ]) ]); } #[test] fn filter_deserialization() { let s = r#"{"fromBlock":"earliest","toBlock":"latest"}"#; let deserialized: Filter = serde_json::from_str(s).unwrap(); assert_eq!(deserialized, Filter { from_block: Some(BlockNumber::Earliest), to_block: Some(BlockNumber::Latest), address: None, topics: None, limit: None, }); } #[test] fn filter_conversion() { let filter = Filter { from_block: Some(BlockNumber::Earliest), to_block: Some(BlockNumber::Latest), address: Some(VariadicValue::Multiple(vec![])), topics: Some(vec![ VariadicValue::Null, VariadicValue::Single("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b".into()), VariadicValue::Null, ]), limit: None, }; let eth_filter: EthFilter = filter.into(); assert_eq!(eth_filter, EthFilter { from_block: BlockId::Earliest, to_block: BlockId::Latest, address: Some(vec![]), topics: vec![ None, Some(vec!["000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b".into()]), None, None, ], limit: None, }); } }
{ match *self { FilterChanges::Logs(ref logs) => logs.serialize(s), FilterChanges::Hashes(ref hashes) => hashes.serialize(s), FilterChanges::Empty => (&[] as &[Value]).serialize(s), } }
identifier_body
mmap.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::io::Error as IOError; use std::os::unix::io::RawFd; use std::result::Result; use vm_memory::{MmapRegion, MmapRegionError}; #[derive(Debug)] pub enum Error { Os(IOError), BuildMmapRegion(MmapRegionError), } pub(crate) fn mmap(size: usize, fd: RawFd, offset: i64) -> Result<MmapRegion, Error> { let prot = libc::PROT_READ | libc::PROT_WRITE; let flags = libc::MAP_SHARED | libc::MAP_POPULATE; // Safe because values are valid and we check the return value. let ptr = unsafe { libc::mmap(std::ptr::null_mut(), size, prot, flags, fd, offset) }; if (ptr as isize) < 0
// Safe because the mmap did not return error. unsafe { MmapRegion::build_raw(ptr as *mut u8, size, prot, flags).map_err(Error::BuildMmapRegion) } }
{ return Err(Error::Os(IOError::last_os_error())); }
conditional_block
mmap.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::io::Error as IOError; use std::os::unix::io::RawFd; use std::result::Result; use vm_memory::{MmapRegion, MmapRegionError}; #[derive(Debug)] pub enum Error { Os(IOError), BuildMmapRegion(MmapRegionError), } pub(crate) fn mmap(size: usize, fd: RawFd, offset: i64) -> Result<MmapRegion, Error> { let prot = libc::PROT_READ | libc::PROT_WRITE; let flags = libc::MAP_SHARED | libc::MAP_POPULATE; // Safe because values are valid and we check the return value. let ptr = unsafe { libc::mmap(std::ptr::null_mut(), size, prot, flags, fd, offset) }; if (ptr as isize) < 0 {
MmapRegion::build_raw(ptr as *mut u8, size, prot, flags).map_err(Error::BuildMmapRegion) } }
return Err(Error::Os(IOError::last_os_error())); } // Safe because the mmap did not return error. unsafe {
random_line_split
mmap.rs
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 use std::io::Error as IOError; use std::os::unix::io::RawFd; use std::result::Result; use vm_memory::{MmapRegion, MmapRegionError}; #[derive(Debug)] pub enum Error { Os(IOError), BuildMmapRegion(MmapRegionError), } pub(crate) fn
(size: usize, fd: RawFd, offset: i64) -> Result<MmapRegion, Error> { let prot = libc::PROT_READ | libc::PROT_WRITE; let flags = libc::MAP_SHARED | libc::MAP_POPULATE; // Safe because values are valid and we check the return value. let ptr = unsafe { libc::mmap(std::ptr::null_mut(), size, prot, flags, fd, offset) }; if (ptr as isize) < 0 { return Err(Error::Os(IOError::last_os_error())); } // Safe because the mmap did not return error. unsafe { MmapRegion::build_raw(ptr as *mut u8, size, prot, flags).map_err(Error::BuildMmapRegion) } }
mmap
identifier_name
paintworkletglobalscope.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use canvas_traits::CanvasData; use dom::bindings::callback::CallbackContainer; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::PaintWorkletGlobalScopeBinding; use dom::bindings::codegen::Bindings::PaintWorkletGlobalScopeBinding::PaintWorkletGlobalScopeMethods; use dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction; use dom::bindings::conversions::get_property; use dom::bindings::conversions::get_property_jsval; use dom::bindings::error::Error; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::JS; use dom::bindings::js::Root; use dom::bindings::reflector::DomObject; use dom::bindings::str::DOMString; use dom::paintrenderingcontext2d::PaintRenderingContext2D; use dom::paintsize::PaintSize; use dom::stylepropertymapreadonly::StylePropertyMapReadOnly; use dom::worklet::WorkletExecutor; use dom::workletglobalscope::WorkletGlobalScope; use dom::workletglobalscope::WorkletGlobalScopeInit; use dom::workletglobalscope::WorkletTask; use dom_struct::dom_struct; use euclid::ScaleFactor; use euclid::TypedSize2D; use ipc_channel::ipc; use js::jsapi::Call; use js::jsapi::Construct1; use js::jsapi::HandleValue; use js::jsapi::HandleValueArray; use js::jsapi::Heap; use js::jsapi::IsCallable; use js::jsapi::IsConstructor; use js::jsapi::JSAutoCompartment; use js::jsapi::JS_ClearPendingException; use js::jsapi::JS_IsExceptionPending; use js::jsval::JSVal; use js::jsval::ObjectValue; use js::jsval::UndefinedValue; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use net_traits::image::base::PixelFormat; use net_traits::image_cache::ImageCache; use script_layout_interface::message::Msg; use script_traits::DrawAPaintImageResult; use script_traits::Painter; use servo_atoms::Atom; use servo_url::ServoUrl; use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::ptr::null_mut; use std::rc::Rc; use std::sync::Arc; use std::sync::Mutex; use std::sync::mpsc; use std::sync::mpsc::Sender; use style_traits::CSSPixel; use style_traits::DevicePixel; /// https://drafts.css-houdini.org/css-paint-api/#paintworkletglobalscope #[dom_struct] pub struct PaintWorkletGlobalScope { /// The worklet global for this object worklet_global: WorkletGlobalScope, /// The image cache #[ignore_heap_size_of = "Arc"] image_cache: Arc<ImageCache>, /// https://drafts.css-houdini.org/css-paint-api/#paint-definitions paint_definitions: DOMRefCell<HashMap<Atom, Box<PaintDefinition>>>, /// https://drafts.css-houdini.org/css-paint-api/#paint-class-instances paint_class_instances: DOMRefCell<HashMap<Atom, Box<Heap<JSVal>>>>, } impl PaintWorkletGlobalScope { #[allow(unsafe_code)] pub fn new(runtime: &Runtime, pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit) -> Root<PaintWorkletGlobalScope> { debug!("Creating paint worklet global scope for pipeline {}.", pipeline_id); let global = box PaintWorkletGlobalScope { worklet_global: WorkletGlobalScope::new_inherited(pipeline_id, base_url, executor, init), image_cache: init.image_cache.clone(), paint_definitions: Default::default(), paint_class_instances: Default::default(), }; unsafe { PaintWorkletGlobalScopeBinding::Wrap(runtime.cx(), global) } } pub fn image_cache(&self) -> Arc<ImageCache> { self.image_cache.clone() } pub fn perform_a_worklet_task(&self, task: PaintWorkletTask) { match task { PaintWorkletTask::DrawAPaintImage(name, size_in_px, device_pixel_ratio, properties, sender) => { let properties = StylePropertyMapReadOnly::from_iter(self.upcast(), properties); let result = self.draw_a_paint_image(name, size_in_px, device_pixel_ratio, &*properties); let _ = sender.send(result); } } } /// https://drafts.css-houdini.org/css-paint-api/#draw-a-paint-image fn draw_a_paint_image(&self, name: Atom, size_in_px: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>, properties: &StylePropertyMapReadOnly) -> DrawAPaintImageResult { // TODO: document paint definitions. self.invoke_a_paint_callback(name, size_in_px, device_pixel_ratio, properties) } /// https://drafts.css-houdini.org/css-paint-api/#invoke-a-paint-callback #[allow(unsafe_code)] fn invoke_a_paint_callback(&self, name: Atom, size_in_px: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>, properties: &StylePropertyMapReadOnly) -> DrawAPaintImageResult { let size_in_dpx = size_in_px * device_pixel_ratio; let size_in_dpx = TypedSize2D::new(size_in_dpx.width.abs() as u32, size_in_dpx.height.abs() as u32); debug!("Invoking a paint callback {}({},{}) at {}.", name, size_in_px.width, size_in_px.height, device_pixel_ratio); let cx = self.worklet_global.get_cx(); let _ac = JSAutoCompartment::new(cx, self.worklet_global.reflector().get_jsobject().get()); // TODO: Steps 1-2.1. // Step 2.2-5.1. rooted!(in(cx) let mut class_constructor = UndefinedValue()); rooted!(in(cx) let mut paint_function = UndefinedValue()); let rendering_context = match self.paint_definitions.borrow().get(&name) { None => { // Step 2.2. warn!("Drawing un-registered paint definition {}.", name); return self.invalid_image(size_in_dpx, vec![]); } Some(definition) => { // Step 5.1 if!definition.constructor_valid_flag.get() { debug!("Drawing invalid paint definition {}.", name); return self.invalid_image(size_in_dpx, vec![]); } class_constructor.set(definition.class_constructor.get()); paint_function.set(definition.paint_function.get()); Root::from_ref(&*definition.context) } }; // Steps 5.2-5.4 // TODO: the spec requires calling the constructor now, but we might want to // prepopulate the paint instance in `RegisterPaint`, to avoid calling it in // the primary worklet thread. // https://github.com/servo/servo/issues/17377 rooted!(in(cx) let mut paint_instance = UndefinedValue()); match self.paint_class_instances.borrow_mut().entry(name.clone()) { Entry::Occupied(entry) => paint_instance.set(entry.get().get()), Entry::Vacant(entry) => { // Step 5.2-5.3 let args = HandleValueArray::new(); rooted!(in(cx) let mut result = null_mut()); unsafe { Construct1(cx, class_constructor.handle(), &args, result.handle_mut()); } paint_instance.set(ObjectValue(result.get())); if unsafe { JS_IsExceptionPending(cx) } { debug!("Paint constructor threw an exception {}.", name); unsafe { JS_ClearPendingException(cx); } self.paint_definitions.borrow_mut().get_mut(&name) .expect("Vanishing paint definition.") .constructor_valid_flag.set(false); return self.invalid_image(size_in_dpx, vec![]); } // Step 5.4 entry.insert(Box::new(Heap::default())).set(paint_instance.get()); } }; // TODO: Steps 6-7 // Step 8 // TODO: the spec requires creating a new paint rendering context each time, // this code recycles the same one. rendering_context.set_bitmap_dimensions(size_in_px, device_pixel_ratio); // Step 9 let paint_size = PaintSize::new(self, size_in_px); // TODO: Step 10 // Steps 11-12 debug!("Invoking paint function {}.", name); let args_slice = [ ObjectValue(rendering_context.reflector().get_jsobject().get()), ObjectValue(paint_size.reflector().get_jsobject().get()), ObjectValue(properties.reflector().get_jsobject().get()), ]; let args = unsafe { HandleValueArray::from_rooted_slice(&args_slice) }; rooted!(in(cx) let mut result = UndefinedValue()); unsafe { Call(cx, paint_instance.handle(), paint_function.handle(), &args, result.handle_mut()); } let missing_image_urls = rendering_context.take_missing_image_urls(); // Step 13. if unsafe { JS_IsExceptionPending(cx) } { debug!("Paint function threw an exception {}.", name); unsafe { JS_ClearPendingException(cx); } return self.invalid_image(size_in_dpx, missing_image_urls); } let (sender, receiver) = ipc::channel().expect("IPC channel creation."); rendering_context.send_data(sender); let image_key = match receiver.recv() { Ok(CanvasData::Image(data)) => Some(data.image_key), _ => None, }; DrawAPaintImageResult { width: size_in_dpx.width, height: size_in_dpx.height, format: PixelFormat::BGRA8, image_key: image_key, missing_image_urls: missing_image_urls, } } // https://drafts.csswg.org/css-images-4/#invalid-image fn invalid_image(&self, size: TypedSize2D<u32, DevicePixel>, missing_image_urls: Vec<ServoUrl>) -> DrawAPaintImageResult { debug!("Returning an invalid image."); DrawAPaintImageResult { width: size.width as u32, height: size.height as u32, format: PixelFormat::BGRA8, image_key: None, missing_image_urls: missing_image_urls, } } fn painter(&self, name: Atom) -> Arc<Painter> { // Rather annoyingly we have to use a mutex here to make the painter Sync. struct WorkletPainter(Atom, Mutex<WorkletExecutor>); impl Painter for WorkletPainter { fn draw_a_paint_image(&self, size: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>, properties: Vec<(Atom, String)>) -> DrawAPaintImageResult { let name = self.0.clone(); let (sender, receiver) = mpsc::channel(); let task = PaintWorkletTask::DrawAPaintImage(name, size, device_pixel_ratio, properties, sender); self.1.lock().expect("Locking a painter.") .schedule_a_worklet_task(WorkletTask::Paint(task)); receiver.recv().expect("Worklet thread died?") } } Arc::new(WorkletPainter(name, Mutex::new(self.worklet_global.executor()))) } } impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope { #[allow(unsafe_code)] #[allow(unrooted_must_root)] /// https://drafts.css-houdini.org/css-paint-api/#dom-paintworkletglobalscope-registerpaint fn
(&self, name: DOMString, paint_ctor: Rc<VoidFunction>) -> Fallible<()> { let name = Atom::from(name); let cx = self.worklet_global.get_cx(); rooted!(in(cx) let paint_obj = paint_ctor.callback_holder().get()); rooted!(in(cx) let paint_val = ObjectValue(paint_obj.get())); debug!("Registering paint image name {}.", name); // Step 1. if name.is_empty() { return Err(Error::Type(String::from("Empty paint name."))) ; } // Step 2-3. if self.paint_definitions.borrow().contains_key(&name) { return Err(Error::InvalidModification); } // Step 4-6. let mut property_names: Vec<String> = unsafe { get_property(cx, paint_obj.handle(), "inputProperties", ()) }? .unwrap_or_default(); let properties = property_names.drain(..).map(Atom::from).collect(); // Step 7-9. let _argument_names: Vec<String> = unsafe { get_property(cx, paint_obj.handle(), "inputArguments", ()) }? .unwrap_or_default(); // TODO: Steps 10-11. // Steps 12-13. let alpha: bool = unsafe { get_property(cx, paint_obj.handle(), "alpha", ()) }? .unwrap_or(true); // Step 14 if unsafe {!IsConstructor(paint_obj.get()) } { return Err(Error::Type(String::from("Not a constructor."))); } // Steps 15-16 rooted!(in(cx) let mut prototype = UndefinedValue()); unsafe { get_property_jsval(cx, paint_obj.handle(), "prototype", prototype.handle_mut())?; } if!prototype.is_object() { return Err(Error::Type(String::from("Prototype is not an object."))); } rooted!(in(cx) let prototype = prototype.to_object()); // Steps 17-18 rooted!(in(cx) let mut paint_function = UndefinedValue()); unsafe { get_property_jsval(cx, prototype.handle(), "paint", paint_function.handle_mut())?; } if!paint_function.is_object() || unsafe {!IsCallable(paint_function.to_object()) } { return Err(Error::Type(String::from("Paint function is not callable."))); } // Step 19. let context = PaintRenderingContext2D::new(self); let definition = PaintDefinition::new(paint_val.handle(), paint_function.handle(), alpha, &*context); // Step 20. debug!("Registering definition {}.", name); self.paint_definitions.borrow_mut().insert(name.clone(), definition); // TODO: Step 21. // Inform layout that there is a registered paint worklet. // TODO: layout will end up getting this message multiple times. let painter = self.painter(name.clone()); let msg = Msg::RegisterPaint(name, properties, painter); self.worklet_global.send_to_layout(msg); Ok(()) } } /// Tasks which can be peformed by a paint worklet pub enum PaintWorkletTask { DrawAPaintImage(Atom, TypedSize2D<f32, CSSPixel>, ScaleFactor<f32, CSSPixel, DevicePixel>, Vec<(Atom, String)>, Sender<DrawAPaintImageResult>) } /// A paint definition /// https://drafts.css-houdini.org/css-paint-api/#paint-definition /// This type is dangerous, because it contains uboxed `Heap<JSVal>` values, /// which can't be moved. #[derive(JSTraceable, HeapSizeOf)] #[must_root] struct PaintDefinition { class_constructor: Heap<JSVal>, paint_function: Heap<JSVal>, constructor_valid_flag: Cell<bool>, context_alpha_flag: bool, // TODO: the spec calls for fresh rendering contexts each time a paint image is drawn, // but to avoid having the primary worklet thread create a new renering context, // we recycle them. context: JS<PaintRenderingContext2D>, } impl PaintDefinition { fn new(class_constructor: HandleValue, paint_function: HandleValue, alpha: bool, context: &PaintRenderingContext2D) -> Box<PaintDefinition> { let result = Box::new(PaintDefinition { class_constructor: Heap::default(), paint_function: Heap::default(), constructor_valid_flag: Cell::new(true), context_alpha_flag: alpha, context: JS::from_ref(context), }); result.class_constructor.set(class_constructor.get()); result.paint_function.set(paint_function.get()); result } }
RegisterPaint
identifier_name
paintworkletglobalscope.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use canvas_traits::CanvasData; use dom::bindings::callback::CallbackContainer; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::PaintWorkletGlobalScopeBinding; use dom::bindings::codegen::Bindings::PaintWorkletGlobalScopeBinding::PaintWorkletGlobalScopeMethods; use dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction; use dom::bindings::conversions::get_property; use dom::bindings::conversions::get_property_jsval; use dom::bindings::error::Error; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::JS; use dom::bindings::js::Root; use dom::bindings::reflector::DomObject; use dom::bindings::str::DOMString; use dom::paintrenderingcontext2d::PaintRenderingContext2D; use dom::paintsize::PaintSize; use dom::stylepropertymapreadonly::StylePropertyMapReadOnly; use dom::worklet::WorkletExecutor; use dom::workletglobalscope::WorkletGlobalScope; use dom::workletglobalscope::WorkletGlobalScopeInit; use dom::workletglobalscope::WorkletTask; use dom_struct::dom_struct; use euclid::ScaleFactor; use euclid::TypedSize2D; use ipc_channel::ipc; use js::jsapi::Call; use js::jsapi::Construct1; use js::jsapi::HandleValue; use js::jsapi::HandleValueArray; use js::jsapi::Heap; use js::jsapi::IsCallable; use js::jsapi::IsConstructor; use js::jsapi::JSAutoCompartment; use js::jsapi::JS_ClearPendingException; use js::jsapi::JS_IsExceptionPending; use js::jsval::JSVal; use js::jsval::ObjectValue; use js::jsval::UndefinedValue; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use net_traits::image::base::PixelFormat; use net_traits::image_cache::ImageCache; use script_layout_interface::message::Msg; use script_traits::DrawAPaintImageResult; use script_traits::Painter; use servo_atoms::Atom; use servo_url::ServoUrl; use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::ptr::null_mut; use std::rc::Rc; use std::sync::Arc; use std::sync::Mutex; use std::sync::mpsc; use std::sync::mpsc::Sender; use style_traits::CSSPixel; use style_traits::DevicePixel; /// https://drafts.css-houdini.org/css-paint-api/#paintworkletglobalscope #[dom_struct] pub struct PaintWorkletGlobalScope { /// The worklet global for this object worklet_global: WorkletGlobalScope, /// The image cache #[ignore_heap_size_of = "Arc"] image_cache: Arc<ImageCache>, /// https://drafts.css-houdini.org/css-paint-api/#paint-definitions paint_definitions: DOMRefCell<HashMap<Atom, Box<PaintDefinition>>>, /// https://drafts.css-houdini.org/css-paint-api/#paint-class-instances paint_class_instances: DOMRefCell<HashMap<Atom, Box<Heap<JSVal>>>>, } impl PaintWorkletGlobalScope { #[allow(unsafe_code)] pub fn new(runtime: &Runtime, pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit) -> Root<PaintWorkletGlobalScope> { debug!("Creating paint worklet global scope for pipeline {}.", pipeline_id); let global = box PaintWorkletGlobalScope { worklet_global: WorkletGlobalScope::new_inherited(pipeline_id, base_url, executor, init), image_cache: init.image_cache.clone(), paint_definitions: Default::default(), paint_class_instances: Default::default(), }; unsafe { PaintWorkletGlobalScopeBinding::Wrap(runtime.cx(), global) } } pub fn image_cache(&self) -> Arc<ImageCache> { self.image_cache.clone() } pub fn perform_a_worklet_task(&self, task: PaintWorkletTask) { match task { PaintWorkletTask::DrawAPaintImage(name, size_in_px, device_pixel_ratio, properties, sender) => { let properties = StylePropertyMapReadOnly::from_iter(self.upcast(), properties); let result = self.draw_a_paint_image(name, size_in_px, device_pixel_ratio, &*properties); let _ = sender.send(result); } } } /// https://drafts.css-houdini.org/css-paint-api/#draw-a-paint-image fn draw_a_paint_image(&self, name: Atom, size_in_px: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>, properties: &StylePropertyMapReadOnly) -> DrawAPaintImageResult { // TODO: document paint definitions. self.invoke_a_paint_callback(name, size_in_px, device_pixel_ratio, properties) } /// https://drafts.css-houdini.org/css-paint-api/#invoke-a-paint-callback #[allow(unsafe_code)] fn invoke_a_paint_callback(&self, name: Atom, size_in_px: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>, properties: &StylePropertyMapReadOnly) -> DrawAPaintImageResult { let size_in_dpx = size_in_px * device_pixel_ratio; let size_in_dpx = TypedSize2D::new(size_in_dpx.width.abs() as u32, size_in_dpx.height.abs() as u32); debug!("Invoking a paint callback {}({},{}) at {}.", name, size_in_px.width, size_in_px.height, device_pixel_ratio); let cx = self.worklet_global.get_cx(); let _ac = JSAutoCompartment::new(cx, self.worklet_global.reflector().get_jsobject().get()); // TODO: Steps 1-2.1. // Step 2.2-5.1. rooted!(in(cx) let mut class_constructor = UndefinedValue()); rooted!(in(cx) let mut paint_function = UndefinedValue()); let rendering_context = match self.paint_definitions.borrow().get(&name) { None => { // Step 2.2. warn!("Drawing un-registered paint definition {}.", name); return self.invalid_image(size_in_dpx, vec![]); } Some(definition) =>
}; // Steps 5.2-5.4 // TODO: the spec requires calling the constructor now, but we might want to // prepopulate the paint instance in `RegisterPaint`, to avoid calling it in // the primary worklet thread. // https://github.com/servo/servo/issues/17377 rooted!(in(cx) let mut paint_instance = UndefinedValue()); match self.paint_class_instances.borrow_mut().entry(name.clone()) { Entry::Occupied(entry) => paint_instance.set(entry.get().get()), Entry::Vacant(entry) => { // Step 5.2-5.3 let args = HandleValueArray::new(); rooted!(in(cx) let mut result = null_mut()); unsafe { Construct1(cx, class_constructor.handle(), &args, result.handle_mut()); } paint_instance.set(ObjectValue(result.get())); if unsafe { JS_IsExceptionPending(cx) } { debug!("Paint constructor threw an exception {}.", name); unsafe { JS_ClearPendingException(cx); } self.paint_definitions.borrow_mut().get_mut(&name) .expect("Vanishing paint definition.") .constructor_valid_flag.set(false); return self.invalid_image(size_in_dpx, vec![]); } // Step 5.4 entry.insert(Box::new(Heap::default())).set(paint_instance.get()); } }; // TODO: Steps 6-7 // Step 8 // TODO: the spec requires creating a new paint rendering context each time, // this code recycles the same one. rendering_context.set_bitmap_dimensions(size_in_px, device_pixel_ratio); // Step 9 let paint_size = PaintSize::new(self, size_in_px); // TODO: Step 10 // Steps 11-12 debug!("Invoking paint function {}.", name); let args_slice = [ ObjectValue(rendering_context.reflector().get_jsobject().get()), ObjectValue(paint_size.reflector().get_jsobject().get()), ObjectValue(properties.reflector().get_jsobject().get()), ]; let args = unsafe { HandleValueArray::from_rooted_slice(&args_slice) }; rooted!(in(cx) let mut result = UndefinedValue()); unsafe { Call(cx, paint_instance.handle(), paint_function.handle(), &args, result.handle_mut()); } let missing_image_urls = rendering_context.take_missing_image_urls(); // Step 13. if unsafe { JS_IsExceptionPending(cx) } { debug!("Paint function threw an exception {}.", name); unsafe { JS_ClearPendingException(cx); } return self.invalid_image(size_in_dpx, missing_image_urls); } let (sender, receiver) = ipc::channel().expect("IPC channel creation."); rendering_context.send_data(sender); let image_key = match receiver.recv() { Ok(CanvasData::Image(data)) => Some(data.image_key), _ => None, }; DrawAPaintImageResult { width: size_in_dpx.width, height: size_in_dpx.height, format: PixelFormat::BGRA8, image_key: image_key, missing_image_urls: missing_image_urls, } } // https://drafts.csswg.org/css-images-4/#invalid-image fn invalid_image(&self, size: TypedSize2D<u32, DevicePixel>, missing_image_urls: Vec<ServoUrl>) -> DrawAPaintImageResult { debug!("Returning an invalid image."); DrawAPaintImageResult { width: size.width as u32, height: size.height as u32, format: PixelFormat::BGRA8, image_key: None, missing_image_urls: missing_image_urls, } } fn painter(&self, name: Atom) -> Arc<Painter> { // Rather annoyingly we have to use a mutex here to make the painter Sync. struct WorkletPainter(Atom, Mutex<WorkletExecutor>); impl Painter for WorkletPainter { fn draw_a_paint_image(&self, size: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>, properties: Vec<(Atom, String)>) -> DrawAPaintImageResult { let name = self.0.clone(); let (sender, receiver) = mpsc::channel(); let task = PaintWorkletTask::DrawAPaintImage(name, size, device_pixel_ratio, properties, sender); self.1.lock().expect("Locking a painter.") .schedule_a_worklet_task(WorkletTask::Paint(task)); receiver.recv().expect("Worklet thread died?") } } Arc::new(WorkletPainter(name, Mutex::new(self.worklet_global.executor()))) } } impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope { #[allow(unsafe_code)] #[allow(unrooted_must_root)] /// https://drafts.css-houdini.org/css-paint-api/#dom-paintworkletglobalscope-registerpaint fn RegisterPaint(&self, name: DOMString, paint_ctor: Rc<VoidFunction>) -> Fallible<()> { let name = Atom::from(name); let cx = self.worklet_global.get_cx(); rooted!(in(cx) let paint_obj = paint_ctor.callback_holder().get()); rooted!(in(cx) let paint_val = ObjectValue(paint_obj.get())); debug!("Registering paint image name {}.", name); // Step 1. if name.is_empty() { return Err(Error::Type(String::from("Empty paint name."))) ; } // Step 2-3. if self.paint_definitions.borrow().contains_key(&name) { return Err(Error::InvalidModification); } // Step 4-6. let mut property_names: Vec<String> = unsafe { get_property(cx, paint_obj.handle(), "inputProperties", ()) }? .unwrap_or_default(); let properties = property_names.drain(..).map(Atom::from).collect(); // Step 7-9. let _argument_names: Vec<String> = unsafe { get_property(cx, paint_obj.handle(), "inputArguments", ()) }? .unwrap_or_default(); // TODO: Steps 10-11. // Steps 12-13. let alpha: bool = unsafe { get_property(cx, paint_obj.handle(), "alpha", ()) }? .unwrap_or(true); // Step 14 if unsafe {!IsConstructor(paint_obj.get()) } { return Err(Error::Type(String::from("Not a constructor."))); } // Steps 15-16 rooted!(in(cx) let mut prototype = UndefinedValue()); unsafe { get_property_jsval(cx, paint_obj.handle(), "prototype", prototype.handle_mut())?; } if!prototype.is_object() { return Err(Error::Type(String::from("Prototype is not an object."))); } rooted!(in(cx) let prototype = prototype.to_object()); // Steps 17-18 rooted!(in(cx) let mut paint_function = UndefinedValue()); unsafe { get_property_jsval(cx, prototype.handle(), "paint", paint_function.handle_mut())?; } if!paint_function.is_object() || unsafe {!IsCallable(paint_function.to_object()) } { return Err(Error::Type(String::from("Paint function is not callable."))); } // Step 19. let context = PaintRenderingContext2D::new(self); let definition = PaintDefinition::new(paint_val.handle(), paint_function.handle(), alpha, &*context); // Step 20. debug!("Registering definition {}.", name); self.paint_definitions.borrow_mut().insert(name.clone(), definition); // TODO: Step 21. // Inform layout that there is a registered paint worklet. // TODO: layout will end up getting this message multiple times. let painter = self.painter(name.clone()); let msg = Msg::RegisterPaint(name, properties, painter); self.worklet_global.send_to_layout(msg); Ok(()) } } /// Tasks which can be peformed by a paint worklet pub enum PaintWorkletTask { DrawAPaintImage(Atom, TypedSize2D<f32, CSSPixel>, ScaleFactor<f32, CSSPixel, DevicePixel>, Vec<(Atom, String)>, Sender<DrawAPaintImageResult>) } /// A paint definition /// https://drafts.css-houdini.org/css-paint-api/#paint-definition /// This type is dangerous, because it contains uboxed `Heap<JSVal>` values, /// which can't be moved. #[derive(JSTraceable, HeapSizeOf)] #[must_root] struct PaintDefinition { class_constructor: Heap<JSVal>, paint_function: Heap<JSVal>, constructor_valid_flag: Cell<bool>, context_alpha_flag: bool, // TODO: the spec calls for fresh rendering contexts each time a paint image is drawn, // but to avoid having the primary worklet thread create a new renering context, // we recycle them. context: JS<PaintRenderingContext2D>, } impl PaintDefinition { fn new(class_constructor: HandleValue, paint_function: HandleValue, alpha: bool, context: &PaintRenderingContext2D) -> Box<PaintDefinition> { let result = Box::new(PaintDefinition { class_constructor: Heap::default(), paint_function: Heap::default(), constructor_valid_flag: Cell::new(true), context_alpha_flag: alpha, context: JS::from_ref(context), }); result.class_constructor.set(class_constructor.get()); result.paint_function.set(paint_function.get()); result } }
{ // Step 5.1 if !definition.constructor_valid_flag.get() { debug!("Drawing invalid paint definition {}.", name); return self.invalid_image(size_in_dpx, vec![]); } class_constructor.set(definition.class_constructor.get()); paint_function.set(definition.paint_function.get()); Root::from_ref(&*definition.context) }
conditional_block
paintworkletglobalscope.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use canvas_traits::CanvasData; use dom::bindings::callback::CallbackContainer; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::PaintWorkletGlobalScopeBinding; use dom::bindings::codegen::Bindings::PaintWorkletGlobalScopeBinding::PaintWorkletGlobalScopeMethods; use dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction; use dom::bindings::conversions::get_property; use dom::bindings::conversions::get_property_jsval; use dom::bindings::error::Error; use dom::bindings::error::Fallible; use dom::bindings::inheritance::Castable; use dom::bindings::js::JS; use dom::bindings::js::Root; use dom::bindings::reflector::DomObject; use dom::bindings::str::DOMString; use dom::paintrenderingcontext2d::PaintRenderingContext2D; use dom::paintsize::PaintSize; use dom::stylepropertymapreadonly::StylePropertyMapReadOnly; use dom::worklet::WorkletExecutor; use dom::workletglobalscope::WorkletGlobalScope; use dom::workletglobalscope::WorkletGlobalScopeInit; use dom::workletglobalscope::WorkletTask; use dom_struct::dom_struct; use euclid::ScaleFactor; use euclid::TypedSize2D; use ipc_channel::ipc; use js::jsapi::Call; use js::jsapi::Construct1; use js::jsapi::HandleValue; use js::jsapi::HandleValueArray; use js::jsapi::Heap; use js::jsapi::IsCallable; use js::jsapi::IsConstructor; use js::jsapi::JSAutoCompartment; use js::jsapi::JS_ClearPendingException; use js::jsapi::JS_IsExceptionPending; use js::jsval::JSVal; use js::jsval::ObjectValue; use js::jsval::UndefinedValue; use js::rust::Runtime; use msg::constellation_msg::PipelineId; use net_traits::image::base::PixelFormat; use net_traits::image_cache::ImageCache; use script_layout_interface::message::Msg; use script_traits::DrawAPaintImageResult; use script_traits::Painter; use servo_atoms::Atom; use servo_url::ServoUrl; use std::cell::Cell; use std::collections::HashMap; use std::collections::hash_map::Entry; use std::ptr::null_mut; use std::rc::Rc; use std::sync::Arc; use std::sync::Mutex; use std::sync::mpsc; use std::sync::mpsc::Sender; use style_traits::CSSPixel; use style_traits::DevicePixel; /// https://drafts.css-houdini.org/css-paint-api/#paintworkletglobalscope #[dom_struct] pub struct PaintWorkletGlobalScope { /// The worklet global for this object worklet_global: WorkletGlobalScope, /// The image cache #[ignore_heap_size_of = "Arc"] image_cache: Arc<ImageCache>, /// https://drafts.css-houdini.org/css-paint-api/#paint-definitions paint_definitions: DOMRefCell<HashMap<Atom, Box<PaintDefinition>>>, /// https://drafts.css-houdini.org/css-paint-api/#paint-class-instances paint_class_instances: DOMRefCell<HashMap<Atom, Box<Heap<JSVal>>>>, } impl PaintWorkletGlobalScope { #[allow(unsafe_code)] pub fn new(runtime: &Runtime, pipeline_id: PipelineId, base_url: ServoUrl, executor: WorkletExecutor, init: &WorkletGlobalScopeInit) -> Root<PaintWorkletGlobalScope> { debug!("Creating paint worklet global scope for pipeline {}.", pipeline_id); let global = box PaintWorkletGlobalScope { worklet_global: WorkletGlobalScope::new_inherited(pipeline_id, base_url, executor, init), image_cache: init.image_cache.clone(), paint_definitions: Default::default(), paint_class_instances: Default::default(), }; unsafe { PaintWorkletGlobalScopeBinding::Wrap(runtime.cx(), global) } } pub fn image_cache(&self) -> Arc<ImageCache> { self.image_cache.clone() } pub fn perform_a_worklet_task(&self, task: PaintWorkletTask) { match task { PaintWorkletTask::DrawAPaintImage(name, size_in_px, device_pixel_ratio, properties, sender) => { let properties = StylePropertyMapReadOnly::from_iter(self.upcast(), properties); let result = self.draw_a_paint_image(name, size_in_px, device_pixel_ratio, &*properties); let _ = sender.send(result); } } } /// https://drafts.css-houdini.org/css-paint-api/#draw-a-paint-image fn draw_a_paint_image(&self, name: Atom, size_in_px: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>, properties: &StylePropertyMapReadOnly) -> DrawAPaintImageResult { // TODO: document paint definitions. self.invoke_a_paint_callback(name, size_in_px, device_pixel_ratio, properties) } /// https://drafts.css-houdini.org/css-paint-api/#invoke-a-paint-callback #[allow(unsafe_code)] fn invoke_a_paint_callback(&self, name: Atom, size_in_px: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>, properties: &StylePropertyMapReadOnly) -> DrawAPaintImageResult { let size_in_dpx = size_in_px * device_pixel_ratio; let size_in_dpx = TypedSize2D::new(size_in_dpx.width.abs() as u32, size_in_dpx.height.abs() as u32); debug!("Invoking a paint callback {}({},{}) at {}.", name, size_in_px.width, size_in_px.height, device_pixel_ratio); let cx = self.worklet_global.get_cx(); let _ac = JSAutoCompartment::new(cx, self.worklet_global.reflector().get_jsobject().get()); // TODO: Steps 1-2.1. // Step 2.2-5.1. rooted!(in(cx) let mut class_constructor = UndefinedValue()); rooted!(in(cx) let mut paint_function = UndefinedValue()); let rendering_context = match self.paint_definitions.borrow().get(&name) { None => { // Step 2.2. warn!("Drawing un-registered paint definition {}.", name); return self.invalid_image(size_in_dpx, vec![]); } Some(definition) => { // Step 5.1 if!definition.constructor_valid_flag.get() { debug!("Drawing invalid paint definition {}.", name); return self.invalid_image(size_in_dpx, vec![]); } class_constructor.set(definition.class_constructor.get()); paint_function.set(definition.paint_function.get()); Root::from_ref(&*definition.context) } }; // Steps 5.2-5.4 // TODO: the spec requires calling the constructor now, but we might want to // prepopulate the paint instance in `RegisterPaint`, to avoid calling it in // the primary worklet thread. // https://github.com/servo/servo/issues/17377 rooted!(in(cx) let mut paint_instance = UndefinedValue()); match self.paint_class_instances.borrow_mut().entry(name.clone()) { Entry::Occupied(entry) => paint_instance.set(entry.get().get()), Entry::Vacant(entry) => { // Step 5.2-5.3 let args = HandleValueArray::new(); rooted!(in(cx) let mut result = null_mut()); unsafe { Construct1(cx, class_constructor.handle(), &args, result.handle_mut()); } paint_instance.set(ObjectValue(result.get())); if unsafe { JS_IsExceptionPending(cx) } { debug!("Paint constructor threw an exception {}.", name); unsafe { JS_ClearPendingException(cx); } self.paint_definitions.borrow_mut().get_mut(&name) .expect("Vanishing paint definition.") .constructor_valid_flag.set(false); return self.invalid_image(size_in_dpx, vec![]); } // Step 5.4 entry.insert(Box::new(Heap::default())).set(paint_instance.get()); } }; // TODO: Steps 6-7 // Step 8 // TODO: the spec requires creating a new paint rendering context each time, // this code recycles the same one. rendering_context.set_bitmap_dimensions(size_in_px, device_pixel_ratio); // Step 9 let paint_size = PaintSize::new(self, size_in_px); // TODO: Step 10 // Steps 11-12 debug!("Invoking paint function {}.", name); let args_slice = [ ObjectValue(rendering_context.reflector().get_jsobject().get()), ObjectValue(paint_size.reflector().get_jsobject().get()), ObjectValue(properties.reflector().get_jsobject().get()), ]; let args = unsafe { HandleValueArray::from_rooted_slice(&args_slice) }; rooted!(in(cx) let mut result = UndefinedValue()); unsafe { Call(cx, paint_instance.handle(), paint_function.handle(), &args, result.handle_mut()); } let missing_image_urls = rendering_context.take_missing_image_urls(); // Step 13. if unsafe { JS_IsExceptionPending(cx) } { debug!("Paint function threw an exception {}.", name); unsafe { JS_ClearPendingException(cx); } return self.invalid_image(size_in_dpx, missing_image_urls); } let (sender, receiver) = ipc::channel().expect("IPC channel creation."); rendering_context.send_data(sender); let image_key = match receiver.recv() { Ok(CanvasData::Image(data)) => Some(data.image_key), _ => None, }; DrawAPaintImageResult { width: size_in_dpx.width, height: size_in_dpx.height, format: PixelFormat::BGRA8, image_key: image_key, missing_image_urls: missing_image_urls, } } // https://drafts.csswg.org/css-images-4/#invalid-image fn invalid_image(&self, size: TypedSize2D<u32, DevicePixel>, missing_image_urls: Vec<ServoUrl>) -> DrawAPaintImageResult { debug!("Returning an invalid image."); DrawAPaintImageResult { width: size.width as u32, height: size.height as u32, format: PixelFormat::BGRA8, image_key: None, missing_image_urls: missing_image_urls, } } fn painter(&self, name: Atom) -> Arc<Painter> { // Rather annoyingly we have to use a mutex here to make the painter Sync. struct WorkletPainter(Atom, Mutex<WorkletExecutor>); impl Painter for WorkletPainter { fn draw_a_paint_image(&self, size: TypedSize2D<f32, CSSPixel>, device_pixel_ratio: ScaleFactor<f32, CSSPixel, DevicePixel>, properties: Vec<(Atom, String)>) -> DrawAPaintImageResult { let name = self.0.clone(); let (sender, receiver) = mpsc::channel(); let task = PaintWorkletTask::DrawAPaintImage(name, size, device_pixel_ratio, properties, sender); self.1.lock().expect("Locking a painter.") .schedule_a_worklet_task(WorkletTask::Paint(task)); receiver.recv().expect("Worklet thread died?") } } Arc::new(WorkletPainter(name, Mutex::new(self.worklet_global.executor()))) } } impl PaintWorkletGlobalScopeMethods for PaintWorkletGlobalScope { #[allow(unsafe_code)] #[allow(unrooted_must_root)] /// https://drafts.css-houdini.org/css-paint-api/#dom-paintworkletglobalscope-registerpaint fn RegisterPaint(&self, name: DOMString, paint_ctor: Rc<VoidFunction>) -> Fallible<()> { let name = Atom::from(name); let cx = self.worklet_global.get_cx(); rooted!(in(cx) let paint_obj = paint_ctor.callback_holder().get()); rooted!(in(cx) let paint_val = ObjectValue(paint_obj.get())); debug!("Registering paint image name {}.", name); // Step 1. if name.is_empty() { return Err(Error::Type(String::from("Empty paint name."))) ; } // Step 2-3. if self.paint_definitions.borrow().contains_key(&name) { return Err(Error::InvalidModification); } // Step 4-6. let mut property_names: Vec<String> = unsafe { get_property(cx, paint_obj.handle(), "inputProperties", ()) }? .unwrap_or_default(); let properties = property_names.drain(..).map(Atom::from).collect(); // Step 7-9. let _argument_names: Vec<String> = unsafe { get_property(cx, paint_obj.handle(), "inputArguments", ()) }? .unwrap_or_default(); // TODO: Steps 10-11. // Steps 12-13. let alpha: bool = unsafe { get_property(cx, paint_obj.handle(), "alpha", ()) }? .unwrap_or(true); // Step 14 if unsafe {!IsConstructor(paint_obj.get()) } { return Err(Error::Type(String::from("Not a constructor."))); } // Steps 15-16 rooted!(in(cx) let mut prototype = UndefinedValue()); unsafe { get_property_jsval(cx, paint_obj.handle(), "prototype", prototype.handle_mut())?; } if!prototype.is_object() { return Err(Error::Type(String::from("Prototype is not an object."))); } rooted!(in(cx) let prototype = prototype.to_object()); // Steps 17-18 rooted!(in(cx) let mut paint_function = UndefinedValue()); unsafe { get_property_jsval(cx, prototype.handle(), "paint", paint_function.handle_mut())?; } if!paint_function.is_object() || unsafe {!IsCallable(paint_function.to_object()) } { return Err(Error::Type(String::from("Paint function is not callable."))); } // Step 19. let context = PaintRenderingContext2D::new(self); let definition = PaintDefinition::new(paint_val.handle(), paint_function.handle(), alpha, &*context); // Step 20. debug!("Registering definition {}.", name); self.paint_definitions.borrow_mut().insert(name.clone(), definition); // TODO: Step 21. // Inform layout that there is a registered paint worklet. // TODO: layout will end up getting this message multiple times. let painter = self.painter(name.clone()); let msg = Msg::RegisterPaint(name, properties, painter); self.worklet_global.send_to_layout(msg); Ok(()) } } /// Tasks which can be peformed by a paint worklet pub enum PaintWorkletTask { DrawAPaintImage(Atom, TypedSize2D<f32, CSSPixel>, ScaleFactor<f32, CSSPixel, DevicePixel>, Vec<(Atom, String)>, Sender<DrawAPaintImageResult>) } /// A paint definition /// https://drafts.css-houdini.org/css-paint-api/#paint-definition /// This type is dangerous, because it contains uboxed `Heap<JSVal>` values, /// which can't be moved.
struct PaintDefinition { class_constructor: Heap<JSVal>, paint_function: Heap<JSVal>, constructor_valid_flag: Cell<bool>, context_alpha_flag: bool, // TODO: the spec calls for fresh rendering contexts each time a paint image is drawn, // but to avoid having the primary worklet thread create a new renering context, // we recycle them. context: JS<PaintRenderingContext2D>, } impl PaintDefinition { fn new(class_constructor: HandleValue, paint_function: HandleValue, alpha: bool, context: &PaintRenderingContext2D) -> Box<PaintDefinition> { let result = Box::new(PaintDefinition { class_constructor: Heap::default(), paint_function: Heap::default(), constructor_valid_flag: Cell::new(true), context_alpha_flag: alpha, context: JS::from_ref(context), }); result.class_constructor.set(class_constructor.get()); result.paint_function.set(paint_function.get()); result } }
#[derive(JSTraceable, HeapSizeOf)] #[must_root]
random_line_split
class-cast-to-trait.rs
// run-pass #![allow(dead_code)] #![allow(unused_mut)] #![allow(non_camel_case_types)] // ignore-freebsd FIXME fails on BSD trait noisy { fn speak(&mut self); } struct cat { meows: usize, how_hungry: isize, name: String, } impl noisy for cat { fn speak(&mut self) { self.meow(); } } impl cat { pub fn eat(&mut self) -> bool { if self.how_hungry > 0
else { println!("Not hungry!"); return false; } } } impl cat { fn meow(&mut self) { println!("Meow"); self.meows += 1; if self.meows % 5 == 0 { self.how_hungry += 1; } } } fn cat(in_x : usize, in_y : isize, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub fn main() { let mut nyan = cat(0, 2, "nyan".to_string()); let mut nyan: &mut dyn noisy = &mut nyan; nyan.speak(); }
{ println!("OM NOM NOM"); self.how_hungry -= 2; return true; }
conditional_block
class-cast-to-trait.rs
// run-pass #![allow(dead_code)] #![allow(unused_mut)] #![allow(non_camel_case_types)] // ignore-freebsd FIXME fails on BSD trait noisy { fn speak(&mut self); } struct cat { meows: usize, how_hungry: isize, name: String, } impl noisy for cat { fn speak(&mut self) { self.meow(); } } impl cat { pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl cat { fn
(&mut self) { println!("Meow"); self.meows += 1; if self.meows % 5 == 0 { self.how_hungry += 1; } } } fn cat(in_x : usize, in_y : isize, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub fn main() { let mut nyan = cat(0, 2, "nyan".to_string()); let mut nyan: &mut dyn noisy = &mut nyan; nyan.speak(); }
meow
identifier_name
class-cast-to-trait.rs
// run-pass #![allow(dead_code)] #![allow(unused_mut)] #![allow(non_camel_case_types)] // ignore-freebsd FIXME fails on BSD trait noisy { fn speak(&mut self); } struct cat { meows: usize, how_hungry: isize, name: String, } impl noisy for cat { fn speak(&mut self) { self.meow(); } } impl cat { pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl cat { fn meow(&mut self) { println!("Meow"); self.meows += 1; if self.meows % 5 == 0 { self.how_hungry += 1; } } } fn cat(in_x : usize, in_y : isize, in_name: String) -> cat
pub fn main() { let mut nyan = cat(0, 2, "nyan".to_string()); let mut nyan: &mut dyn noisy = &mut nyan; nyan.speak(); }
{ cat { meows: in_x, how_hungry: in_y, name: in_name } }
identifier_body
class-cast-to-trait.rs
// run-pass #![allow(dead_code)] #![allow(unused_mut)] #![allow(non_camel_case_types)] // ignore-freebsd FIXME fails on BSD trait noisy { fn speak(&mut self); } struct cat { meows: usize, how_hungry: isize, name: String, } impl noisy for cat { fn speak(&mut self) { self.meow(); } } impl cat { pub fn eat(&mut self) -> bool { if self.how_hungry > 0 { println!("OM NOM NOM"); self.how_hungry -= 2; return true; } else { println!("Not hungry!"); return false; } } } impl cat { fn meow(&mut self) { println!("Meow");
if self.meows % 5 == 0 { self.how_hungry += 1; } } } fn cat(in_x : usize, in_y : isize, in_name: String) -> cat { cat { meows: in_x, how_hungry: in_y, name: in_name } } pub fn main() { let mut nyan = cat(0, 2, "nyan".to_string()); let mut nyan: &mut dyn noisy = &mut nyan; nyan.speak(); }
self.meows += 1;
random_line_split
media_queries.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/. */ //! [Media queries][mq]. //! //! [mq]: https://drafts.csswg.org/mediaqueries/ use Atom; use app_units::Au; use cssparser::{Delimiter, Parser, Token}; use euclid::size::{Size2D, TypedSize2D}; use serialize_comma_separated_list; use std::ascii::AsciiExt; use std::fmt; use style_traits::{ToCss, ViewportPx}; use values::computed::{self, ToComputedValue}; use values::specified; #[derive(Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct MediaList { pub media_queries: Vec<MediaQuery> } impl ToCss for MediaList { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { serialize_comma_separated_list(dest, &self.media_queries) } } impl Default for MediaList { fn default() -> MediaList { MediaList { media_queries: vec![] } } } #[derive(PartialEq, Eq, Copy, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Range<T> { Min(T), Max(T), Eq(T), } impl Range<specified::Length> { fn to_computed_range(&self, viewport_size: Size2D<Au>) -> Range<Au> { // http://dev.w3.org/csswg/mediaqueries3/#units // em units are relative to the initial font-size. let context = computed::Context::initial(viewport_size, false); match *self { Range::Min(ref width) => Range::Min(width.to_computed_value(&context)), Range::Max(ref width) => Range::Max(width.to_computed_value(&context)), Range::Eq(ref width) => Range::Eq(width.to_computed_value(&context)) } } } impl<T: Ord> Range<T> { fn evaluate(&self, value: T) -> bool { match *self { Range::Min(ref width) => { value >= *width }, Range::Max(ref width) => { value <= *width }, Range::Eq(ref width) => { value == *width }, } } } /// http://dev.w3.org/csswg/mediaqueries-3/#media1 #[derive(PartialEq, Copy, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Expression { /// http://dev.w3.org/csswg/mediaqueries-3/#width Width(Range<specified::Length>), } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Copy, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Qualifier { Only, Not, } impl ToCss for Qualifier { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { Qualifier::Not => write!(dest, "not"), Qualifier::Only => write!(dest, "only"), } } } #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct MediaQuery { pub qualifier: Option<Qualifier>, pub media_type: MediaQueryType, pub expressions: Vec<Expression>, } impl MediaQuery { /// Return a media query that never matches, used for when we fail to parse /// a given media query. fn never_matching() -> Self { Self::new(Some(Qualifier::Not), MediaQueryType::All, vec![]) } pub fn new(qualifier: Option<Qualifier>, media_type: MediaQueryType, expressions: Vec<Expression>) -> MediaQuery { MediaQuery { qualifier: qualifier, media_type: media_type, expressions: expressions, } } } impl ToCss for MediaQuery { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { if let Some(qual) = self.qualifier { try!(qual.to_css(dest)); try!(write!(dest, " ")); } match self.media_type { MediaQueryType::All => { // We need to print "all" if there's a qualifier, or there's // just an empty list of expressions. // // Otherwise, we'd serialize media queries like "(min-width: // 40px)" in "all (min-width: 40px)", which is unexpected. if self.qualifier.is_some() || self.expressions.is_empty() { try!(write!(dest, "all")); } }, MediaQueryType::Known(MediaType::Screen) => try!(write!(dest, "screen")), MediaQueryType::Known(MediaType::Print) => try!(write!(dest, "print")), MediaQueryType::Unknown(ref desc) => try!(write!(dest, "{}", desc)), } if self.expressions.is_empty() { return Ok(()); } if self.media_type!= MediaQueryType::All || self.qualifier.is_some() { try!(write!(dest, " and ")); } for (i, &e) in self.expressions.iter().enumerate() { try!(write!(dest, "(")); let (mm, l) = match e { Expression::Width(Range::Min(ref l)) => ("min-", l), Expression::Width(Range::Max(ref l)) => ("max-", l), Expression::Width(Range::Eq(ref l)) => ("", l), }; try!(write!(dest, "{}width: ", mm)); try!(l.to_css(dest)); try!(write!(dest, ")")); if i!= self.expressions.len() - 1 { try!(write!(dest, " and ")); } } Ok(()) } } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum MediaQueryType { All, // Always true Known(MediaType), Unknown(Atom), } impl MediaQueryType { fn parse(ident: &str) -> Self { if ident.eq_ignore_ascii_case("all") { return MediaQueryType::All; } match MediaType::parse(ident) { Some(media_type) => MediaQueryType::Known(media_type), None => MediaQueryType::Unknown(Atom::from(ident)), } } fn matches(&self, other: &MediaType) -> bool { match *self { MediaQueryType::All => true, MediaQueryType::Known(ref known_type) => known_type == other, MediaQueryType::Unknown(..) => false, } } } #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum MediaType { Screen, Print, } impl MediaType { fn parse(name: &str) -> Option<Self> { Some(match_ignore_ascii_case! { name, "screen" => MediaType::Screen, "print" => MediaType::Print, _ => return None }) } } #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct Device { pub media_type: MediaType, pub viewport_size: TypedSize2D<f32, ViewportPx>, } impl Device { pub fn new(media_type: MediaType, viewport_size: TypedSize2D<f32, ViewportPx>) -> Device { Device { media_type: media_type, viewport_size: viewport_size, } } #[inline] pub fn au_viewport_size(&self) -> Size2D<Au> { Size2D::new(Au::from_f32_px(self.viewport_size.width), Au::from_f32_px(self.viewport_size.height)) } } impl Expression { fn parse(input: &mut Parser) -> Result<Expression, ()> { try!(input.expect_parenthesis_block()); input.parse_nested_block(|input| { let name = try!(input.expect_ident()); try!(input.expect_colon()); // TODO: Handle other media features match_ignore_ascii_case! { name, "min-width" => { Ok(Expression::Width(Range::Min(try!(specified::Length::parse_non_negative(input))))) }, "max-width" => { Ok(Expression::Width(Range::Max(try!(specified::Length::parse_non_negative(input))))) }, "width" => { Ok(Expression::Width(Range::Eq(try!(specified::Length::parse_non_negative(input))))) }, _ => Err(()) } }) } } impl MediaQuery { pub fn parse(input: &mut Parser) -> Result<MediaQuery, ()> { let mut expressions = vec![]; let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() { Some(Qualifier::Only) } else if input.try(|input| input.expect_ident_matching("not")).is_ok() { Some(Qualifier::Not) } else { None }; let media_type = match input.try(|input| input.expect_ident()) { Ok(ident) => MediaQueryType::parse(&*ident), Err(()) => { // Media type is only optional if qualifier is not specified. if qualifier.is_some() { return Err(()) } // Without a media type, require at least one expression. expressions.push(try!(Expression::parse(input))); MediaQueryType::All } }; // Parse any subsequent expressions loop { if input.try(|input| input.expect_ident_matching("and")).is_err() { return Ok(MediaQuery::new(qualifier, media_type, expressions)) } expressions.push(try!(Expression::parse(input))) } } } pub fn parse_media_query_list(input: &mut Parser) -> MediaList
impl MediaList { pub fn evaluate(&self, device: &Device) -> bool { let viewport_size = device.au_viewport_size(); // Check if it is an empty media query list or any queries match (OR condition) // https://drafts.csswg.org/mediaqueries-4/#mq-list self.media_queries.is_empty() || self.media_queries.iter().any(|mq| { let media_match = mq.media_type.matches(&device.media_type); // Check if all conditions match (AND condition) let query_match = media_match && mq.expressions.iter().all(|expression| { match *expression { Expression::Width(ref value) => value.to_computed_range(viewport_size).evaluate(viewport_size.width), } }); // Apply the logical NOT qualifier to the result match mq.qualifier { Some(Qualifier::Not) =>!query_match, _ => query_match, } }) } pub fn is_empty(&self) -> bool { self.media_queries.is_empty() } }
{ if input.is_exhausted() { return Default::default() } let mut media_queries = vec![]; loop { media_queries.push( input.parse_until_before(Delimiter::Comma, MediaQuery::parse).ok() .unwrap_or_else(MediaQuery::never_matching)); match input.next() { Ok(Token::Comma) => {}, Ok(_) => unreachable!(), Err(()) => break, } } MediaList { media_queries: media_queries, } }
identifier_body
media_queries.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/. */ //! [Media queries][mq]. //! //! [mq]: https://drafts.csswg.org/mediaqueries/ use Atom; use app_units::Au; use cssparser::{Delimiter, Parser, Token}; use euclid::size::{Size2D, TypedSize2D}; use serialize_comma_separated_list; use std::ascii::AsciiExt; use std::fmt; use style_traits::{ToCss, ViewportPx}; use values::computed::{self, ToComputedValue}; use values::specified; #[derive(Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct MediaList { pub media_queries: Vec<MediaQuery> } impl ToCss for MediaList { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { serialize_comma_separated_list(dest, &self.media_queries) } } impl Default for MediaList { fn default() -> MediaList { MediaList { media_queries: vec![] } } } #[derive(PartialEq, Eq, Copy, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Range<T> { Min(T), Max(T), Eq(T), } impl Range<specified::Length> { fn to_computed_range(&self, viewport_size: Size2D<Au>) -> Range<Au> { // http://dev.w3.org/csswg/mediaqueries3/#units // em units are relative to the initial font-size. let context = computed::Context::initial(viewport_size, false); match *self { Range::Min(ref width) => Range::Min(width.to_computed_value(&context)), Range::Max(ref width) => Range::Max(width.to_computed_value(&context)), Range::Eq(ref width) => Range::Eq(width.to_computed_value(&context)) } } } impl<T: Ord> Range<T> { fn evaluate(&self, value: T) -> bool { match *self { Range::Min(ref width) => { value >= *width }, Range::Max(ref width) => { value <= *width }, Range::Eq(ref width) => { value == *width }, } } } /// http://dev.w3.org/csswg/mediaqueries-3/#media1 #[derive(PartialEq, Copy, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Expression { /// http://dev.w3.org/csswg/mediaqueries-3/#width Width(Range<specified::Length>), } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Copy, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Qualifier { Only, Not, } impl ToCss for Qualifier { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { Qualifier::Not => write!(dest, "not"), Qualifier::Only => write!(dest, "only"), } } } #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct MediaQuery { pub qualifier: Option<Qualifier>, pub media_type: MediaQueryType, pub expressions: Vec<Expression>, } impl MediaQuery { /// Return a media query that never matches, used for when we fail to parse /// a given media query. fn never_matching() -> Self { Self::new(Some(Qualifier::Not), MediaQueryType::All, vec![]) } pub fn new(qualifier: Option<Qualifier>, media_type: MediaQueryType, expressions: Vec<Expression>) -> MediaQuery { MediaQuery { qualifier: qualifier, media_type: media_type, expressions: expressions, } } } impl ToCss for MediaQuery { fn
<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { if let Some(qual) = self.qualifier { try!(qual.to_css(dest)); try!(write!(dest, " ")); } match self.media_type { MediaQueryType::All => { // We need to print "all" if there's a qualifier, or there's // just an empty list of expressions. // // Otherwise, we'd serialize media queries like "(min-width: // 40px)" in "all (min-width: 40px)", which is unexpected. if self.qualifier.is_some() || self.expressions.is_empty() { try!(write!(dest, "all")); } }, MediaQueryType::Known(MediaType::Screen) => try!(write!(dest, "screen")), MediaQueryType::Known(MediaType::Print) => try!(write!(dest, "print")), MediaQueryType::Unknown(ref desc) => try!(write!(dest, "{}", desc)), } if self.expressions.is_empty() { return Ok(()); } if self.media_type!= MediaQueryType::All || self.qualifier.is_some() { try!(write!(dest, " and ")); } for (i, &e) in self.expressions.iter().enumerate() { try!(write!(dest, "(")); let (mm, l) = match e { Expression::Width(Range::Min(ref l)) => ("min-", l), Expression::Width(Range::Max(ref l)) => ("max-", l), Expression::Width(Range::Eq(ref l)) => ("", l), }; try!(write!(dest, "{}width: ", mm)); try!(l.to_css(dest)); try!(write!(dest, ")")); if i!= self.expressions.len() - 1 { try!(write!(dest, " and ")); } } Ok(()) } } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum MediaQueryType { All, // Always true Known(MediaType), Unknown(Atom), } impl MediaQueryType { fn parse(ident: &str) -> Self { if ident.eq_ignore_ascii_case("all") { return MediaQueryType::All; } match MediaType::parse(ident) { Some(media_type) => MediaQueryType::Known(media_type), None => MediaQueryType::Unknown(Atom::from(ident)), } } fn matches(&self, other: &MediaType) -> bool { match *self { MediaQueryType::All => true, MediaQueryType::Known(ref known_type) => known_type == other, MediaQueryType::Unknown(..) => false, } } } #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum MediaType { Screen, Print, } impl MediaType { fn parse(name: &str) -> Option<Self> { Some(match_ignore_ascii_case! { name, "screen" => MediaType::Screen, "print" => MediaType::Print, _ => return None }) } } #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct Device { pub media_type: MediaType, pub viewport_size: TypedSize2D<f32, ViewportPx>, } impl Device { pub fn new(media_type: MediaType, viewport_size: TypedSize2D<f32, ViewportPx>) -> Device { Device { media_type: media_type, viewport_size: viewport_size, } } #[inline] pub fn au_viewport_size(&self) -> Size2D<Au> { Size2D::new(Au::from_f32_px(self.viewport_size.width), Au::from_f32_px(self.viewport_size.height)) } } impl Expression { fn parse(input: &mut Parser) -> Result<Expression, ()> { try!(input.expect_parenthesis_block()); input.parse_nested_block(|input| { let name = try!(input.expect_ident()); try!(input.expect_colon()); // TODO: Handle other media features match_ignore_ascii_case! { name, "min-width" => { Ok(Expression::Width(Range::Min(try!(specified::Length::parse_non_negative(input))))) }, "max-width" => { Ok(Expression::Width(Range::Max(try!(specified::Length::parse_non_negative(input))))) }, "width" => { Ok(Expression::Width(Range::Eq(try!(specified::Length::parse_non_negative(input))))) }, _ => Err(()) } }) } } impl MediaQuery { pub fn parse(input: &mut Parser) -> Result<MediaQuery, ()> { let mut expressions = vec![]; let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() { Some(Qualifier::Only) } else if input.try(|input| input.expect_ident_matching("not")).is_ok() { Some(Qualifier::Not) } else { None }; let media_type = match input.try(|input| input.expect_ident()) { Ok(ident) => MediaQueryType::parse(&*ident), Err(()) => { // Media type is only optional if qualifier is not specified. if qualifier.is_some() { return Err(()) } // Without a media type, require at least one expression. expressions.push(try!(Expression::parse(input))); MediaQueryType::All } }; // Parse any subsequent expressions loop { if input.try(|input| input.expect_ident_matching("and")).is_err() { return Ok(MediaQuery::new(qualifier, media_type, expressions)) } expressions.push(try!(Expression::parse(input))) } } } pub fn parse_media_query_list(input: &mut Parser) -> MediaList { if input.is_exhausted() { return Default::default() } let mut media_queries = vec![]; loop { media_queries.push( input.parse_until_before(Delimiter::Comma, MediaQuery::parse).ok() .unwrap_or_else(MediaQuery::never_matching)); match input.next() { Ok(Token::Comma) => {}, Ok(_) => unreachable!(), Err(()) => break, } } MediaList { media_queries: media_queries, } } impl MediaList { pub fn evaluate(&self, device: &Device) -> bool { let viewport_size = device.au_viewport_size(); // Check if it is an empty media query list or any queries match (OR condition) // https://drafts.csswg.org/mediaqueries-4/#mq-list self.media_queries.is_empty() || self.media_queries.iter().any(|mq| { let media_match = mq.media_type.matches(&device.media_type); // Check if all conditions match (AND condition) let query_match = media_match && mq.expressions.iter().all(|expression| { match *expression { Expression::Width(ref value) => value.to_computed_range(viewport_size).evaluate(viewport_size.width), } }); // Apply the logical NOT qualifier to the result match mq.qualifier { Some(Qualifier::Not) =>!query_match, _ => query_match, } }) } pub fn is_empty(&self) -> bool { self.media_queries.is_empty() } }
to_css
identifier_name
media_queries.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/. */ //! [Media queries][mq]. //! //! [mq]: https://drafts.csswg.org/mediaqueries/ use Atom; use app_units::Au; use cssparser::{Delimiter, Parser, Token}; use euclid::size::{Size2D, TypedSize2D}; use serialize_comma_separated_list; use std::ascii::AsciiExt; use std::fmt; use style_traits::{ToCss, ViewportPx}; use values::computed::{self, ToComputedValue}; use values::specified; #[derive(Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct MediaList { pub media_queries: Vec<MediaQuery> } impl ToCss for MediaList { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { serialize_comma_separated_list(dest, &self.media_queries) } } impl Default for MediaList { fn default() -> MediaList { MediaList { media_queries: vec![] } } } #[derive(PartialEq, Eq, Copy, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Range<T> { Min(T), Max(T), Eq(T), } impl Range<specified::Length> { fn to_computed_range(&self, viewport_size: Size2D<Au>) -> Range<Au> { // http://dev.w3.org/csswg/mediaqueries3/#units // em units are relative to the initial font-size. let context = computed::Context::initial(viewport_size, false); match *self { Range::Min(ref width) => Range::Min(width.to_computed_value(&context)), Range::Max(ref width) => Range::Max(width.to_computed_value(&context)), Range::Eq(ref width) => Range::Eq(width.to_computed_value(&context)) } } } impl<T: Ord> Range<T> { fn evaluate(&self, value: T) -> bool { match *self { Range::Min(ref width) => { value >= *width }, Range::Max(ref width) => { value <= *width }, Range::Eq(ref width) => { value == *width }, } } } /// http://dev.w3.org/csswg/mediaqueries-3/#media1 #[derive(PartialEq, Copy, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Expression { /// http://dev.w3.org/csswg/mediaqueries-3/#width Width(Range<specified::Length>), } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Copy, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum Qualifier { Only, Not, } impl ToCss for Qualifier { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { match *self { Qualifier::Not => write!(dest, "not"), Qualifier::Only => write!(dest, "only"), } } } #[derive(Clone, Debug, PartialEq)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct MediaQuery { pub qualifier: Option<Qualifier>, pub media_type: MediaQueryType, pub expressions: Vec<Expression>, } impl MediaQuery { /// Return a media query that never matches, used for when we fail to parse /// a given media query. fn never_matching() -> Self { Self::new(Some(Qualifier::Not), MediaQueryType::All, vec![]) } pub fn new(qualifier: Option<Qualifier>, media_type: MediaQueryType, expressions: Vec<Expression>) -> MediaQuery { MediaQuery { qualifier: qualifier, media_type: media_type, expressions: expressions, } } } impl ToCss for MediaQuery { fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { if let Some(qual) = self.qualifier { try!(qual.to_css(dest)); try!(write!(dest, " ")); } match self.media_type { MediaQueryType::All => { // We need to print "all" if there's a qualifier, or there's // just an empty list of expressions. // // Otherwise, we'd serialize media queries like "(min-width: // 40px)" in "all (min-width: 40px)", which is unexpected. if self.qualifier.is_some() || self.expressions.is_empty() { try!(write!(dest, "all")); } }, MediaQueryType::Known(MediaType::Screen) => try!(write!(dest, "screen")), MediaQueryType::Known(MediaType::Print) => try!(write!(dest, "print")), MediaQueryType::Unknown(ref desc) => try!(write!(dest, "{}", desc)), } if self.expressions.is_empty() { return Ok(()); } if self.media_type!= MediaQueryType::All || self.qualifier.is_some() { try!(write!(dest, " and ")); } for (i, &e) in self.expressions.iter().enumerate() { try!(write!(dest, "(")); let (mm, l) = match e { Expression::Width(Range::Min(ref l)) => ("min-", l), Expression::Width(Range::Max(ref l)) => ("max-", l), Expression::Width(Range::Eq(ref l)) => ("", l), }; try!(write!(dest, "{}width: ", mm)); try!(l.to_css(dest)); try!(write!(dest, ")")); if i!= self.expressions.len() - 1 { try!(write!(dest, " and ")); } } Ok(()) } } /// http://dev.w3.org/csswg/mediaqueries-3/#media0 #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum MediaQueryType { All, // Always true Known(MediaType), Unknown(Atom), } impl MediaQueryType { fn parse(ident: &str) -> Self { if ident.eq_ignore_ascii_case("all") { return MediaQueryType::All; } match MediaType::parse(ident) { Some(media_type) => MediaQueryType::Known(media_type), None => MediaQueryType::Unknown(Atom::from(ident)), } } fn matches(&self, other: &MediaType) -> bool { match *self { MediaQueryType::All => true, MediaQueryType::Known(ref known_type) => known_type == other, MediaQueryType::Unknown(..) => false, } } } #[derive(PartialEq, Eq, Clone, Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub enum MediaType { Screen, Print, } impl MediaType { fn parse(name: &str) -> Option<Self> { Some(match_ignore_ascii_case! { name, "screen" => MediaType::Screen, "print" => MediaType::Print, _ => return None }) } } #[derive(Debug)] #[cfg_attr(feature = "servo", derive(HeapSizeOf))] pub struct Device { pub media_type: MediaType, pub viewport_size: TypedSize2D<f32, ViewportPx>, } impl Device { pub fn new(media_type: MediaType, viewport_size: TypedSize2D<f32, ViewportPx>) -> Device { Device { media_type: media_type, viewport_size: viewport_size, } } #[inline] pub fn au_viewport_size(&self) -> Size2D<Au> { Size2D::new(Au::from_f32_px(self.viewport_size.width), Au::from_f32_px(self.viewport_size.height)) } } impl Expression { fn parse(input: &mut Parser) -> Result<Expression, ()> { try!(input.expect_parenthesis_block()); input.parse_nested_block(|input| { let name = try!(input.expect_ident()); try!(input.expect_colon()); // TODO: Handle other media features match_ignore_ascii_case! { name, "min-width" => { Ok(Expression::Width(Range::Min(try!(specified::Length::parse_non_negative(input))))) }, "max-width" => { Ok(Expression::Width(Range::Max(try!(specified::Length::parse_non_negative(input))))) }, "width" => { Ok(Expression::Width(Range::Eq(try!(specified::Length::parse_non_negative(input))))) }, _ => Err(()) } }) } } impl MediaQuery { pub fn parse(input: &mut Parser) -> Result<MediaQuery, ()> { let mut expressions = vec![]; let qualifier = if input.try(|input| input.expect_ident_matching("only")).is_ok() { Some(Qualifier::Only) } else if input.try(|input| input.expect_ident_matching("not")).is_ok() { Some(Qualifier::Not) } else { None }; let media_type = match input.try(|input| input.expect_ident()) { Ok(ident) => MediaQueryType::parse(&*ident), Err(()) => { // Media type is only optional if qualifier is not specified. if qualifier.is_some() { return Err(()) } // Without a media type, require at least one expression. expressions.push(try!(Expression::parse(input))); MediaQueryType::All } }; // Parse any subsequent expressions loop { if input.try(|input| input.expect_ident_matching("and")).is_err() { return Ok(MediaQuery::new(qualifier, media_type, expressions)) } expressions.push(try!(Expression::parse(input))) }
if input.is_exhausted() { return Default::default() } let mut media_queries = vec![]; loop { media_queries.push( input.parse_until_before(Delimiter::Comma, MediaQuery::parse).ok() .unwrap_or_else(MediaQuery::never_matching)); match input.next() { Ok(Token::Comma) => {}, Ok(_) => unreachable!(), Err(()) => break, } } MediaList { media_queries: media_queries, } } impl MediaList { pub fn evaluate(&self, device: &Device) -> bool { let viewport_size = device.au_viewport_size(); // Check if it is an empty media query list or any queries match (OR condition) // https://drafts.csswg.org/mediaqueries-4/#mq-list self.media_queries.is_empty() || self.media_queries.iter().any(|mq| { let media_match = mq.media_type.matches(&device.media_type); // Check if all conditions match (AND condition) let query_match = media_match && mq.expressions.iter().all(|expression| { match *expression { Expression::Width(ref value) => value.to_computed_range(viewport_size).evaluate(viewport_size.width), } }); // Apply the logical NOT qualifier to the result match mq.qualifier { Some(Qualifier::Not) =>!query_match, _ => query_match, } }) } pub fn is_empty(&self) -> bool { self.media_queries.is_empty() } }
} } pub fn parse_media_query_list(input: &mut Parser) -> MediaList {
random_line_split
mod.rs
// // Copyright (c) 2016, Boris Popov <[email protected]> // // 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/. // extern crate libc; use self::libc::c_void; use self::libc::c_ulong; use self::libc::c_int; use std::ptr; use std::ffi::CString; use strerror::getStrError; ////////////////////////////////////////////////////////////////// pub fn mount(source: &str, target: &str, filesystem: &str) -> Result<(), String> { let c_source = CString::new(source).unwrap(); let source_raw = c_source.into_raw(); let c_target = CString::new(target).unwrap(); let target_raw = c_target.into_raw(); let c_filesystem = CString::new(filesystem).unwrap(); let filesystem_raw = c_filesystem.into_raw(); let flags: c_ulong = 0; let data: *const c_void = ptr::null(); let mut result: c_int = 0; unsafe { result = libc::mount(source_raw, target_raw, filesystem_raw, flags, data); } return get_result(result, "mount"); } pub fn umount(target: &str) -> Result<(), String> { let c_target = CString::new(target).unwrap(); let target_raw = c_target.into_raw(); let mut result: c_int = 0; unsafe { result = libc::umount(target_raw); } return get_result(result, "umount"); } fn get_result(result: c_int, s: &str) -> Result<(), String> { match result {
_ => { let mut mess = "Unexpected error in mount::".to_string(); mess += s; mess += "!"; Err(mess) } } } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// #[test] #[ignore] fn test_mount_01() { let mi = MountInfo{source: "/dev/sdb1", target: "/mnt/temp", filesystem: "ext4"}; println!("\n *** mount *** \n"); let res = mount(&mi); match res { Err(e) => println!("\nMOUNT ERROR: {}", e), _ => println!("\nMOUNT OK") } let res2 = umount(mi.target); match res2 { Err(e) => println!("\nUMOUNT ERROR: {}", e), _ => println!("\nUMOUNT OK") } } //////////////////////////////////////////////////////////////////
0 => Ok(()), -1 => Err(getStrError()),
random_line_split
mod.rs
// // Copyright (c) 2016, Boris Popov <[email protected]> // // 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/. // extern crate libc; use self::libc::c_void; use self::libc::c_ulong; use self::libc::c_int; use std::ptr; use std::ffi::CString; use strerror::getStrError; ////////////////////////////////////////////////////////////////// pub fn mount(source: &str, target: &str, filesystem: &str) -> Result<(), String> { let c_source = CString::new(source).unwrap(); let source_raw = c_source.into_raw(); let c_target = CString::new(target).unwrap(); let target_raw = c_target.into_raw(); let c_filesystem = CString::new(filesystem).unwrap(); let filesystem_raw = c_filesystem.into_raw(); let flags: c_ulong = 0; let data: *const c_void = ptr::null(); let mut result: c_int = 0; unsafe { result = libc::mount(source_raw, target_raw, filesystem_raw, flags, data); } return get_result(result, "mount"); } pub fn umount(target: &str) -> Result<(), String> { let c_target = CString::new(target).unwrap(); let target_raw = c_target.into_raw(); let mut result: c_int = 0; unsafe { result = libc::umount(target_raw); } return get_result(result, "umount"); } fn
(result: c_int, s: &str) -> Result<(), String> { match result { 0 => Ok(()), -1 => Err(getStrError()), _ => { let mut mess = "Unexpected error in mount::".to_string(); mess += s; mess += "!"; Err(mess) } } } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// #[test] #[ignore] fn test_mount_01() { let mi = MountInfo{source: "/dev/sdb1", target: "/mnt/temp", filesystem: "ext4"}; println!("\n *** mount *** \n"); let res = mount(&mi); match res { Err(e) => println!("\nMOUNT ERROR: {}", e), _ => println!("\nMOUNT OK") } let res2 = umount(mi.target); match res2 { Err(e) => println!("\nUMOUNT ERROR: {}", e), _ => println!("\nUMOUNT OK") } } //////////////////////////////////////////////////////////////////
get_result
identifier_name
mod.rs
// // Copyright (c) 2016, Boris Popov <[email protected]> // // 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/. // extern crate libc; use self::libc::c_void; use self::libc::c_ulong; use self::libc::c_int; use std::ptr; use std::ffi::CString; use strerror::getStrError; ////////////////////////////////////////////////////////////////// pub fn mount(source: &str, target: &str, filesystem: &str) -> Result<(), String> { let c_source = CString::new(source).unwrap(); let source_raw = c_source.into_raw(); let c_target = CString::new(target).unwrap(); let target_raw = c_target.into_raw(); let c_filesystem = CString::new(filesystem).unwrap(); let filesystem_raw = c_filesystem.into_raw(); let flags: c_ulong = 0; let data: *const c_void = ptr::null(); let mut result: c_int = 0; unsafe { result = libc::mount(source_raw, target_raw, filesystem_raw, flags, data); } return get_result(result, "mount"); } pub fn umount(target: &str) -> Result<(), String>
fn get_result(result: c_int, s: &str) -> Result<(), String> { match result { 0 => Ok(()), -1 => Err(getStrError()), _ => { let mut mess = "Unexpected error in mount::".to_string(); mess += s; mess += "!"; Err(mess) } } } ////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////// #[test] #[ignore] fn test_mount_01() { let mi = MountInfo{source: "/dev/sdb1", target: "/mnt/temp", filesystem: "ext4"}; println!("\n *** mount *** \n"); let res = mount(&mi); match res { Err(e) => println!("\nMOUNT ERROR: {}", e), _ => println!("\nMOUNT OK") } let res2 = umount(mi.target); match res2 { Err(e) => println!("\nUMOUNT ERROR: {}", e), _ => println!("\nUMOUNT OK") } } //////////////////////////////////////////////////////////////////
{ let c_target = CString::new(target).unwrap(); let target_raw = c_target.into_raw(); let mut result: c_int = 0; unsafe { result = libc::umount(target_raw); } return get_result(result, "umount"); }
identifier_body
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] // This is needed for the constants in atom_macro.rs, because we have some // atoms whose names differ only by case, e.g. datetime and dateTime. #![allow(non_upper_case_globals)] //! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s. use crate::gecko_bindings::bindings::Gecko_AddRefAtom; use crate::gecko_bindings::bindings::Gecko_Atomize; use crate::gecko_bindings::bindings::Gecko_Atomize16; use crate::gecko_bindings::bindings::Gecko_ReleaseAtom; use crate::gecko_bindings::structs::root::mozilla::detail::gGkAtoms; use crate::gecko_bindings::structs::root::mozilla::detail::kGkAtomsArrayOffset; use crate::gecko_bindings::structs::root::mozilla::detail::GkAtoms_Atoms_AtomsCount; use crate::gecko_bindings::structs::{nsAtom, nsDynamicAtom, nsStaticAtom}; use nsstring::{nsAString, nsStr}; use precomputed_hash::PrecomputedHash; use std::borrow::{Borrow, Cow}; use std::char::{self, DecodeUtf16}; use std::fmt::{self, Write}; use std::hash::{Hash, Hasher}; use std::iter::Cloned; use std::ops::Deref; use std::{mem, slice, str}; use style_traits::SpecifiedValueInfo; #[macro_use] #[allow(improper_ctypes, non_camel_case_types, missing_docs)] pub mod atom_macro { include!(concat!(env!("OUT_DIR"), "/gecko/atom_macro.rs")); } #[macro_use] pub mod namespace; pub use self::namespace::{Namespace, WeakNamespace}; macro_rules! local_name { ($s:tt) => { atom!($s) }; } /// A handle to a Gecko atom. /// /// This is either a strong reference to a dynamic atom (an nsAtom pointer), /// or an offset from gGkAtoms to the nsStaticAtom object. #[derive(Eq, PartialEq)] pub struct Atom(usize); /// An atom *without* a strong reference. /// /// Only usable as `&'a WeakAtom`, /// where `'a` is the lifetime of something that holds a strong reference to that atom. pub struct
(nsAtom); /// The number of static atoms we have. const STATIC_ATOM_COUNT: usize = GkAtoms_Atoms_AtomsCount as usize; /// Returns the Gecko static atom array. /// /// We have this rather than use rust-bindgen to generate /// mozilla::detail::gGkAtoms and then just reference gGkAtoms.mAtoms, so we /// avoid a problem with lld-link.exe on Windows. /// /// https://bugzilla.mozilla.org/show_bug.cgi?id=1517685 #[inline] fn static_atoms() -> &'static [nsStaticAtom; STATIC_ATOM_COUNT] { unsafe { let addr = &gGkAtoms as *const _ as usize + kGkAtomsArrayOffset as usize; &*(addr as *const _) } } /// Returns whether the specified address points to one of the nsStaticAtom /// objects in the Gecko static atom array. #[inline] fn valid_static_atom_addr(addr: usize) -> bool { unsafe { let atoms = static_atoms(); let start = atoms.get_unchecked(0) as *const _; let end = atoms.get_unchecked(STATIC_ATOM_COUNT) as *const _; let in_range = addr >= start as usize && addr < end as usize; let aligned = addr % mem::align_of::<nsStaticAtom>() == 0; in_range && aligned } } impl Deref for Atom { type Target = WeakAtom; #[inline] fn deref(&self) -> &WeakAtom { unsafe { let addr = if self.is_static() { (&gGkAtoms as *const _ as usize) + (self.0 >> 1) } else { self.0 }; debug_assert!(!self.is_static() || valid_static_atom_addr(addr)); WeakAtom::new(addr as *const nsAtom) } } } impl PrecomputedHash for Atom { #[inline] fn precomputed_hash(&self) -> u32 { self.get_hash() } } impl Borrow<WeakAtom> for Atom { #[inline] fn borrow(&self) -> &WeakAtom { self } } impl Eq for WeakAtom {} impl PartialEq for WeakAtom { #[inline] fn eq(&self, other: &Self) -> bool { let weak: *const WeakAtom = self; let other: *const WeakAtom = other; weak == other } } unsafe impl Send for Atom {} unsafe impl Sync for Atom {} unsafe impl Sync for WeakAtom {} impl WeakAtom { /// Construct a `WeakAtom` from a raw `nsAtom`. #[inline] pub unsafe fn new<'a>(atom: *const nsAtom) -> &'a mut Self { &mut *(atom as *mut WeakAtom) } /// Clone this atom, bumping the refcount if the atom is not static. #[inline] pub fn clone(&self) -> Atom { unsafe { Atom::from_raw(self.as_ptr()) } } /// Get the atom hash. #[inline] pub fn get_hash(&self) -> u32 { self.0.mHash } /// Get the atom as a slice of utf-16 chars. #[inline] pub fn as_slice(&self) -> &[u16] { let string = if self.is_static() { let atom_ptr = self.as_ptr() as *const nsStaticAtom; let string_offset = unsafe { (*atom_ptr).mStringOffset }; let string_offset = -(string_offset as isize); let u8_ptr = atom_ptr as *const u8; // It is safe to use offset() here because both addresses are within // the same struct, e.g. mozilla::detail::gGkAtoms. unsafe { u8_ptr.offset(string_offset) as *const u16 } } else { let atom_ptr = self.as_ptr() as *const nsDynamicAtom; // Dynamic atom chars are stored at the end of the object. unsafe { atom_ptr.offset(1) as *const u16 } }; unsafe { slice::from_raw_parts(string, self.len() as usize) } } // NOTE: don't expose this, since it's slow, and easy to be misused. fn chars(&self) -> DecodeUtf16<Cloned<slice::Iter<u16>>> { char::decode_utf16(self.as_slice().iter().cloned()) } /// Execute `cb` with the string that this atom represents. /// /// Find alternatives to this function when possible, please, since it's /// pretty slow. pub fn with_str<F, Output>(&self, cb: F) -> Output where F: FnOnce(&str) -> Output, { let mut buffer: [u8; 64] = unsafe { mem::uninitialized() }; // The total string length in utf16 is going to be less than or equal // the slice length (each utf16 character is going to take at least one // and at most 2 items in the utf16 slice). // // Each of those characters will take at most four bytes in the utf8 // one. Thus if the slice is less than 64 / 4 (16) we can guarantee that // we'll decode it in place. let owned_string; let len = self.len(); let utf8_slice = if len <= 16 { let mut total_len = 0; for c in self.chars() { let c = c.unwrap_or(char::REPLACEMENT_CHARACTER); let utf8_len = c.encode_utf8(&mut buffer[total_len..]).len(); total_len += utf8_len; } let slice = unsafe { str::from_utf8_unchecked(&buffer[..total_len]) }; debug_assert_eq!(slice, String::from_utf16_lossy(self.as_slice())); slice } else { owned_string = String::from_utf16_lossy(self.as_slice()); &*owned_string }; cb(utf8_slice) } /// Returns whether this atom is static. #[inline] pub fn is_static(&self) -> bool { self.0.mIsStatic()!= 0 } /// Returns whether this atom is ascii lowercase. #[inline] fn is_ascii_lowercase(&self) -> bool { self.0.mIsAsciiLowercase()!= 0 } /// Returns the length of the atom string. #[inline] pub fn len(&self) -> u32 { self.0.mLength() } /// Returns whether this atom is the empty string. #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the atom as a mutable pointer. #[inline] pub fn as_ptr(&self) -> *mut nsAtom { let const_ptr: *const nsAtom = &self.0; const_ptr as *mut nsAtom } /// Convert this atom to ASCII lower-case pub fn to_ascii_lowercase(&self) -> Atom { if self.is_ascii_lowercase() { return self.clone(); } let slice = self.as_slice(); let mut buffer: [u16; 64] = unsafe { mem::uninitialized() }; let mut vec; let mutable_slice = if let Some(buffer_prefix) = buffer.get_mut(..slice.len()) { buffer_prefix.copy_from_slice(slice); buffer_prefix } else { vec = slice.to_vec(); &mut vec }; for char16 in &mut *mutable_slice { if *char16 <= 0x7F { *char16 = (*char16 as u8).to_ascii_lowercase() as u16 } } Atom::from(&*mutable_slice) } /// Return whether two atoms are ASCII-case-insensitive matches #[inline] pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool { if self == other { return true; } // If we know both atoms are ascii-lowercase, then we can stick with // pointer equality. if self.is_ascii_lowercase() && other.is_ascii_lowercase() { debug_assert!(!self.eq_ignore_ascii_case_slow(other)); return false; } self.eq_ignore_ascii_case_slow(other) } fn eq_ignore_ascii_case_slow(&self, other: &Self) -> bool { let a = self.as_slice(); let b = other.as_slice(); if a.len()!= b.len() { return false; } a.iter().zip(b).all(|(&a16, &b16)| { if a16 <= 0x7F && b16 <= 0x7F { (a16 as u8).eq_ignore_ascii_case(&(b16 as u8)) } else { a16 == b16 } }) } } impl fmt::Debug for WeakAtom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { write!(w, "Gecko WeakAtom({:p}, {})", self, self) } } impl fmt::Display for WeakAtom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { for c in self.chars() { w.write_char(c.unwrap_or(char::REPLACEMENT_CHARACTER))? } Ok(()) } } #[inline] unsafe fn make_handle(ptr: *const nsAtom) -> usize { debug_assert!(!ptr.is_null()); if!WeakAtom::new(ptr).is_static() { ptr as usize } else { make_static_handle(ptr as *mut nsStaticAtom) } } #[inline] unsafe fn make_static_handle(ptr: *const nsStaticAtom) -> usize { // FIXME(heycam): Use offset_from once it's stabilized. // https://github.com/rust-lang/rust/issues/41079 debug_assert!(valid_static_atom_addr(ptr as usize)); let base = &gGkAtoms as *const _; let offset = ptr as usize - base as usize; (offset << 1) | 1 } impl Atom { #[inline] fn is_static(&self) -> bool { self.0 & 1 == 1 } /// Execute a callback with the atom represented by `ptr`. pub unsafe fn with<F, R>(ptr: *const nsAtom, callback: F) -> R where F: FnOnce(&Atom) -> R, { let atom = Atom(make_handle(ptr as *mut nsAtom)); let ret = callback(&atom); mem::forget(atom); ret } /// Creates a static atom from its index in the static atom table, without /// checking in release builds. #[inline] pub unsafe fn from_index(index: u16) -> Self { let ptr = static_atoms().get_unchecked(index as usize) as *const _; let handle = make_static_handle(ptr); let atom = Atom(handle); debug_assert!(valid_static_atom_addr(ptr as usize)); debug_assert!(atom.is_static()); debug_assert!((*atom).is_static()); debug_assert!(handle == make_handle(atom.as_ptr())); atom } /// Creates an atom from an atom pointer. #[inline(always)] pub unsafe fn from_raw(ptr: *mut nsAtom) -> Self { let atom = Atom(make_handle(ptr)); if!atom.is_static() { Gecko_AddRefAtom(ptr); } atom } /// Creates an atom from an atom pointer that has already had AddRef /// called on it. This may be a static or dynamic atom. #[inline] pub unsafe fn from_addrefed(ptr: *mut nsAtom) -> Self { assert!(!ptr.is_null()); Atom(make_handle(ptr)) } /// Convert this atom into an addrefed nsAtom pointer. #[inline] pub fn into_addrefed(self) -> *mut nsAtom { let ptr = self.as_ptr(); mem::forget(self); ptr } } impl Hash for Atom { fn hash<H>(&self, state: &mut H) where H: Hasher, { state.write_u32(self.get_hash()); } } impl Hash for WeakAtom { fn hash<H>(&self, state: &mut H) where H: Hasher, { state.write_u32(self.get_hash()); } } impl Clone for Atom { #[inline(always)] fn clone(&self) -> Atom { unsafe { let atom = Atom(self.0); if!atom.is_static() { Gecko_AddRefAtom(atom.as_ptr()); } atom } } } impl Drop for Atom { #[inline] fn drop(&mut self) { if!self.is_static() { unsafe { Gecko_ReleaseAtom(self.as_ptr()); } } } } impl Default for Atom { #[inline] fn default() -> Self { atom!("") } } impl fmt::Debug for Atom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { write!(w, "Atom(0x{:08x}, {})", self.0, self) } } impl fmt::Display for Atom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { self.deref().fmt(w) } } impl<'a> From<&'a str> for Atom { #[inline] fn from(string: &str) -> Atom { debug_assert!(string.len() <= u32::max_value() as usize); unsafe { Atom::from_addrefed(Gecko_Atomize( string.as_ptr() as *const _, string.len() as u32, )) } } } impl<'a> From<&'a [u16]> for Atom { #[inline] fn from(slice: &[u16]) -> Atom { Atom::from(&*nsStr::from(slice)) } } impl<'a> From<&'a nsAString> for Atom { #[inline] fn from(string: &nsAString) -> Atom { unsafe { Atom::from_addrefed(Gecko_Atomize16(string)) } } } impl<'a> From<Cow<'a, str>> for Atom { #[inline] fn from(string: Cow<'a, str>) -> Atom { Atom::from(&*string) } } impl From<String> for Atom { #[inline] fn from(string: String) -> Atom { Atom::from(&*string) } } malloc_size_of_is_0!(Atom); impl SpecifiedValueInfo for Atom {}
WeakAtom
identifier_name
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] // This is needed for the constants in atom_macro.rs, because we have some // atoms whose names differ only by case, e.g. datetime and dateTime. #![allow(non_upper_case_globals)] //! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s. use crate::gecko_bindings::bindings::Gecko_AddRefAtom; use crate::gecko_bindings::bindings::Gecko_Atomize; use crate::gecko_bindings::bindings::Gecko_Atomize16; use crate::gecko_bindings::bindings::Gecko_ReleaseAtom; use crate::gecko_bindings::structs::root::mozilla::detail::gGkAtoms; use crate::gecko_bindings::structs::root::mozilla::detail::kGkAtomsArrayOffset; use crate::gecko_bindings::structs::root::mozilla::detail::GkAtoms_Atoms_AtomsCount; use crate::gecko_bindings::structs::{nsAtom, nsDynamicAtom, nsStaticAtom}; use nsstring::{nsAString, nsStr}; use precomputed_hash::PrecomputedHash; use std::borrow::{Borrow, Cow}; use std::char::{self, DecodeUtf16}; use std::fmt::{self, Write}; use std::hash::{Hash, Hasher}; use std::iter::Cloned; use std::ops::Deref; use std::{mem, slice, str}; use style_traits::SpecifiedValueInfo; #[macro_use] #[allow(improper_ctypes, non_camel_case_types, missing_docs)] pub mod atom_macro { include!(concat!(env!("OUT_DIR"), "/gecko/atom_macro.rs")); } #[macro_use] pub mod namespace; pub use self::namespace::{Namespace, WeakNamespace}; macro_rules! local_name { ($s:tt) => { atom!($s) }; } /// A handle to a Gecko atom. /// /// This is either a strong reference to a dynamic atom (an nsAtom pointer), /// or an offset from gGkAtoms to the nsStaticAtom object. #[derive(Eq, PartialEq)] pub struct Atom(usize); /// An atom *without* a strong reference. /// /// Only usable as `&'a WeakAtom`, /// where `'a` is the lifetime of something that holds a strong reference to that atom. pub struct WeakAtom(nsAtom); /// The number of static atoms we have. const STATIC_ATOM_COUNT: usize = GkAtoms_Atoms_AtomsCount as usize; /// Returns the Gecko static atom array. /// /// We have this rather than use rust-bindgen to generate /// mozilla::detail::gGkAtoms and then just reference gGkAtoms.mAtoms, so we /// avoid a problem with lld-link.exe on Windows. /// /// https://bugzilla.mozilla.org/show_bug.cgi?id=1517685 #[inline] fn static_atoms() -> &'static [nsStaticAtom; STATIC_ATOM_COUNT] { unsafe { let addr = &gGkAtoms as *const _ as usize + kGkAtomsArrayOffset as usize; &*(addr as *const _) } } /// Returns whether the specified address points to one of the nsStaticAtom /// objects in the Gecko static atom array. #[inline] fn valid_static_atom_addr(addr: usize) -> bool { unsafe { let atoms = static_atoms(); let start = atoms.get_unchecked(0) as *const _; let end = atoms.get_unchecked(STATIC_ATOM_COUNT) as *const _; let in_range = addr >= start as usize && addr < end as usize; let aligned = addr % mem::align_of::<nsStaticAtom>() == 0; in_range && aligned } } impl Deref for Atom { type Target = WeakAtom; #[inline] fn deref(&self) -> &WeakAtom { unsafe { let addr = if self.is_static() { (&gGkAtoms as *const _ as usize) + (self.0 >> 1) } else { self.0 }; debug_assert!(!self.is_static() || valid_static_atom_addr(addr)); WeakAtom::new(addr as *const nsAtom) } } } impl PrecomputedHash for Atom { #[inline] fn precomputed_hash(&self) -> u32 { self.get_hash() } } impl Borrow<WeakAtom> for Atom { #[inline] fn borrow(&self) -> &WeakAtom { self } } impl Eq for WeakAtom {} impl PartialEq for WeakAtom { #[inline] fn eq(&self, other: &Self) -> bool { let weak: *const WeakAtom = self; let other: *const WeakAtom = other; weak == other } } unsafe impl Send for Atom {} unsafe impl Sync for Atom {} unsafe impl Sync for WeakAtom {} impl WeakAtom { /// Construct a `WeakAtom` from a raw `nsAtom`. #[inline] pub unsafe fn new<'a>(atom: *const nsAtom) -> &'a mut Self { &mut *(atom as *mut WeakAtom) } /// Clone this atom, bumping the refcount if the atom is not static. #[inline] pub fn clone(&self) -> Atom { unsafe { Atom::from_raw(self.as_ptr()) } } /// Get the atom hash. #[inline] pub fn get_hash(&self) -> u32 { self.0.mHash } /// Get the atom as a slice of utf-16 chars. #[inline] pub fn as_slice(&self) -> &[u16] { let string = if self.is_static() { let atom_ptr = self.as_ptr() as *const nsStaticAtom; let string_offset = unsafe { (*atom_ptr).mStringOffset }; let string_offset = -(string_offset as isize); let u8_ptr = atom_ptr as *const u8; // It is safe to use offset() here because both addresses are within // the same struct, e.g. mozilla::detail::gGkAtoms. unsafe { u8_ptr.offset(string_offset) as *const u16 } } else { let atom_ptr = self.as_ptr() as *const nsDynamicAtom; // Dynamic atom chars are stored at the end of the object. unsafe { atom_ptr.offset(1) as *const u16 } }; unsafe { slice::from_raw_parts(string, self.len() as usize) } } // NOTE: don't expose this, since it's slow, and easy to be misused. fn chars(&self) -> DecodeUtf16<Cloned<slice::Iter<u16>>> { char::decode_utf16(self.as_slice().iter().cloned()) } /// Execute `cb` with the string that this atom represents. /// /// Find alternatives to this function when possible, please, since it's /// pretty slow. pub fn with_str<F, Output>(&self, cb: F) -> Output where F: FnOnce(&str) -> Output, { let mut buffer: [u8; 64] = unsafe { mem::uninitialized() }; // The total string length in utf16 is going to be less than or equal // the slice length (each utf16 character is going to take at least one // and at most 2 items in the utf16 slice). // // Each of those characters will take at most four bytes in the utf8 // one. Thus if the slice is less than 64 / 4 (16) we can guarantee that // we'll decode it in place. let owned_string; let len = self.len(); let utf8_slice = if len <= 16 { let mut total_len = 0; for c in self.chars() { let c = c.unwrap_or(char::REPLACEMENT_CHARACTER); let utf8_len = c.encode_utf8(&mut buffer[total_len..]).len(); total_len += utf8_len; } let slice = unsafe { str::from_utf8_unchecked(&buffer[..total_len]) }; debug_assert_eq!(slice, String::from_utf16_lossy(self.as_slice())); slice } else { owned_string = String::from_utf16_lossy(self.as_slice()); &*owned_string }; cb(utf8_slice) } /// Returns whether this atom is static. #[inline] pub fn is_static(&self) -> bool { self.0.mIsStatic()!= 0 } /// Returns whether this atom is ascii lowercase. #[inline] fn is_ascii_lowercase(&self) -> bool { self.0.mIsAsciiLowercase()!= 0 } /// Returns the length of the atom string. #[inline] pub fn len(&self) -> u32 { self.0.mLength() } /// Returns whether this atom is the empty string. #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the atom as a mutable pointer. #[inline] pub fn as_ptr(&self) -> *mut nsAtom { let const_ptr: *const nsAtom = &self.0; const_ptr as *mut nsAtom } /// Convert this atom to ASCII lower-case pub fn to_ascii_lowercase(&self) -> Atom { if self.is_ascii_lowercase() { return self.clone(); } let slice = self.as_slice(); let mut buffer: [u16; 64] = unsafe { mem::uninitialized() }; let mut vec; let mutable_slice = if let Some(buffer_prefix) = buffer.get_mut(..slice.len()) { buffer_prefix.copy_from_slice(slice); buffer_prefix } else { vec = slice.to_vec(); &mut vec }; for char16 in &mut *mutable_slice { if *char16 <= 0x7F { *char16 = (*char16 as u8).to_ascii_lowercase() as u16 } } Atom::from(&*mutable_slice) } /// Return whether two atoms are ASCII-case-insensitive matches #[inline] pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool { if self == other { return true; } // If we know both atoms are ascii-lowercase, then we can stick with // pointer equality. if self.is_ascii_lowercase() && other.is_ascii_lowercase() { debug_assert!(!self.eq_ignore_ascii_case_slow(other)); return false; } self.eq_ignore_ascii_case_slow(other) } fn eq_ignore_ascii_case_slow(&self, other: &Self) -> bool { let a = self.as_slice(); let b = other.as_slice(); if a.len()!= b.len()
a.iter().zip(b).all(|(&a16, &b16)| { if a16 <= 0x7F && b16 <= 0x7F { (a16 as u8).eq_ignore_ascii_case(&(b16 as u8)) } else { a16 == b16 } }) } } impl fmt::Debug for WeakAtom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { write!(w, "Gecko WeakAtom({:p}, {})", self, self) } } impl fmt::Display for WeakAtom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { for c in self.chars() { w.write_char(c.unwrap_or(char::REPLACEMENT_CHARACTER))? } Ok(()) } } #[inline] unsafe fn make_handle(ptr: *const nsAtom) -> usize { debug_assert!(!ptr.is_null()); if!WeakAtom::new(ptr).is_static() { ptr as usize } else { make_static_handle(ptr as *mut nsStaticAtom) } } #[inline] unsafe fn make_static_handle(ptr: *const nsStaticAtom) -> usize { // FIXME(heycam): Use offset_from once it's stabilized. // https://github.com/rust-lang/rust/issues/41079 debug_assert!(valid_static_atom_addr(ptr as usize)); let base = &gGkAtoms as *const _; let offset = ptr as usize - base as usize; (offset << 1) | 1 } impl Atom { #[inline] fn is_static(&self) -> bool { self.0 & 1 == 1 } /// Execute a callback with the atom represented by `ptr`. pub unsafe fn with<F, R>(ptr: *const nsAtom, callback: F) -> R where F: FnOnce(&Atom) -> R, { let atom = Atom(make_handle(ptr as *mut nsAtom)); let ret = callback(&atom); mem::forget(atom); ret } /// Creates a static atom from its index in the static atom table, without /// checking in release builds. #[inline] pub unsafe fn from_index(index: u16) -> Self { let ptr = static_atoms().get_unchecked(index as usize) as *const _; let handle = make_static_handle(ptr); let atom = Atom(handle); debug_assert!(valid_static_atom_addr(ptr as usize)); debug_assert!(atom.is_static()); debug_assert!((*atom).is_static()); debug_assert!(handle == make_handle(atom.as_ptr())); atom } /// Creates an atom from an atom pointer. #[inline(always)] pub unsafe fn from_raw(ptr: *mut nsAtom) -> Self { let atom = Atom(make_handle(ptr)); if!atom.is_static() { Gecko_AddRefAtom(ptr); } atom } /// Creates an atom from an atom pointer that has already had AddRef /// called on it. This may be a static or dynamic atom. #[inline] pub unsafe fn from_addrefed(ptr: *mut nsAtom) -> Self { assert!(!ptr.is_null()); Atom(make_handle(ptr)) } /// Convert this atom into an addrefed nsAtom pointer. #[inline] pub fn into_addrefed(self) -> *mut nsAtom { let ptr = self.as_ptr(); mem::forget(self); ptr } } impl Hash for Atom { fn hash<H>(&self, state: &mut H) where H: Hasher, { state.write_u32(self.get_hash()); } } impl Hash for WeakAtom { fn hash<H>(&self, state: &mut H) where H: Hasher, { state.write_u32(self.get_hash()); } } impl Clone for Atom { #[inline(always)] fn clone(&self) -> Atom { unsafe { let atom = Atom(self.0); if!atom.is_static() { Gecko_AddRefAtom(atom.as_ptr()); } atom } } } impl Drop for Atom { #[inline] fn drop(&mut self) { if!self.is_static() { unsafe { Gecko_ReleaseAtom(self.as_ptr()); } } } } impl Default for Atom { #[inline] fn default() -> Self { atom!("") } } impl fmt::Debug for Atom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { write!(w, "Atom(0x{:08x}, {})", self.0, self) } } impl fmt::Display for Atom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { self.deref().fmt(w) } } impl<'a> From<&'a str> for Atom { #[inline] fn from(string: &str) -> Atom { debug_assert!(string.len() <= u32::max_value() as usize); unsafe { Atom::from_addrefed(Gecko_Atomize( string.as_ptr() as *const _, string.len() as u32, )) } } } impl<'a> From<&'a [u16]> for Atom { #[inline] fn from(slice: &[u16]) -> Atom { Atom::from(&*nsStr::from(slice)) } } impl<'a> From<&'a nsAString> for Atom { #[inline] fn from(string: &nsAString) -> Atom { unsafe { Atom::from_addrefed(Gecko_Atomize16(string)) } } } impl<'a> From<Cow<'a, str>> for Atom { #[inline] fn from(string: Cow<'a, str>) -> Atom { Atom::from(&*string) } } impl From<String> for Atom { #[inline] fn from(string: String) -> Atom { Atom::from(&*string) } } malloc_size_of_is_0!(Atom); impl SpecifiedValueInfo for Atom {}
{ return false; }
conditional_block
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] // This is needed for the constants in atom_macro.rs, because we have some // atoms whose names differ only by case, e.g. datetime and dateTime. #![allow(non_upper_case_globals)] //! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s. use crate::gecko_bindings::bindings::Gecko_AddRefAtom; use crate::gecko_bindings::bindings::Gecko_Atomize; use crate::gecko_bindings::bindings::Gecko_Atomize16; use crate::gecko_bindings::bindings::Gecko_ReleaseAtom; use crate::gecko_bindings::structs::root::mozilla::detail::gGkAtoms; use crate::gecko_bindings::structs::root::mozilla::detail::kGkAtomsArrayOffset; use crate::gecko_bindings::structs::root::mozilla::detail::GkAtoms_Atoms_AtomsCount; use crate::gecko_bindings::structs::{nsAtom, nsDynamicAtom, nsStaticAtom}; use nsstring::{nsAString, nsStr}; use precomputed_hash::PrecomputedHash; use std::borrow::{Borrow, Cow}; use std::char::{self, DecodeUtf16}; use std::fmt::{self, Write}; use std::hash::{Hash, Hasher}; use std::iter::Cloned; use std::ops::Deref; use std::{mem, slice, str}; use style_traits::SpecifiedValueInfo; #[macro_use] #[allow(improper_ctypes, non_camel_case_types, missing_docs)] pub mod atom_macro { include!(concat!(env!("OUT_DIR"), "/gecko/atom_macro.rs")); } #[macro_use] pub mod namespace; pub use self::namespace::{Namespace, WeakNamespace}; macro_rules! local_name { ($s:tt) => { atom!($s) }; } /// A handle to a Gecko atom. /// /// This is either a strong reference to a dynamic atom (an nsAtom pointer), /// or an offset from gGkAtoms to the nsStaticAtom object. #[derive(Eq, PartialEq)] pub struct Atom(usize); /// An atom *without* a strong reference. /// /// Only usable as `&'a WeakAtom`, /// where `'a` is the lifetime of something that holds a strong reference to that atom. pub struct WeakAtom(nsAtom); /// The number of static atoms we have. const STATIC_ATOM_COUNT: usize = GkAtoms_Atoms_AtomsCount as usize; /// Returns the Gecko static atom array. /// /// We have this rather than use rust-bindgen to generate /// mozilla::detail::gGkAtoms and then just reference gGkAtoms.mAtoms, so we /// avoid a problem with lld-link.exe on Windows. /// /// https://bugzilla.mozilla.org/show_bug.cgi?id=1517685 #[inline] fn static_atoms() -> &'static [nsStaticAtom; STATIC_ATOM_COUNT] { unsafe { let addr = &gGkAtoms as *const _ as usize + kGkAtomsArrayOffset as usize; &*(addr as *const _) } } /// Returns whether the specified address points to one of the nsStaticAtom /// objects in the Gecko static atom array. #[inline] fn valid_static_atom_addr(addr: usize) -> bool { unsafe { let atoms = static_atoms(); let start = atoms.get_unchecked(0) as *const _; let end = atoms.get_unchecked(STATIC_ATOM_COUNT) as *const _; let in_range = addr >= start as usize && addr < end as usize; let aligned = addr % mem::align_of::<nsStaticAtom>() == 0; in_range && aligned } } impl Deref for Atom { type Target = WeakAtom; #[inline] fn deref(&self) -> &WeakAtom { unsafe { let addr = if self.is_static() { (&gGkAtoms as *const _ as usize) + (self.0 >> 1) } else { self.0 }; debug_assert!(!self.is_static() || valid_static_atom_addr(addr)); WeakAtom::new(addr as *const nsAtom) } } } impl PrecomputedHash for Atom { #[inline] fn precomputed_hash(&self) -> u32 { self.get_hash() } } impl Borrow<WeakAtom> for Atom { #[inline] fn borrow(&self) -> &WeakAtom { self } } impl Eq for WeakAtom {} impl PartialEq for WeakAtom { #[inline] fn eq(&self, other: &Self) -> bool { let weak: *const WeakAtom = self; let other: *const WeakAtom = other; weak == other } } unsafe impl Send for Atom {} unsafe impl Sync for Atom {} unsafe impl Sync for WeakAtom {} impl WeakAtom { /// Construct a `WeakAtom` from a raw `nsAtom`. #[inline] pub unsafe fn new<'a>(atom: *const nsAtom) -> &'a mut Self { &mut *(atom as *mut WeakAtom) } /// Clone this atom, bumping the refcount if the atom is not static. #[inline] pub fn clone(&self) -> Atom { unsafe { Atom::from_raw(self.as_ptr()) } } /// Get the atom hash. #[inline] pub fn get_hash(&self) -> u32 { self.0.mHash } /// Get the atom as a slice of utf-16 chars. #[inline] pub fn as_slice(&self) -> &[u16] { let string = if self.is_static() { let atom_ptr = self.as_ptr() as *const nsStaticAtom; let string_offset = unsafe { (*atom_ptr).mStringOffset }; let string_offset = -(string_offset as isize); let u8_ptr = atom_ptr as *const u8; // It is safe to use offset() here because both addresses are within // the same struct, e.g. mozilla::detail::gGkAtoms. unsafe { u8_ptr.offset(string_offset) as *const u16 } } else { let atom_ptr = self.as_ptr() as *const nsDynamicAtom; // Dynamic atom chars are stored at the end of the object. unsafe { atom_ptr.offset(1) as *const u16 } }; unsafe { slice::from_raw_parts(string, self.len() as usize) } } // NOTE: don't expose this, since it's slow, and easy to be misused. fn chars(&self) -> DecodeUtf16<Cloned<slice::Iter<u16>>> { char::decode_utf16(self.as_slice().iter().cloned()) } /// Execute `cb` with the string that this atom represents. /// /// Find alternatives to this function when possible, please, since it's /// pretty slow. pub fn with_str<F, Output>(&self, cb: F) -> Output where F: FnOnce(&str) -> Output, { let mut buffer: [u8; 64] = unsafe { mem::uninitialized() }; // The total string length in utf16 is going to be less than or equal // the slice length (each utf16 character is going to take at least one // and at most 2 items in the utf16 slice). // // Each of those characters will take at most four bytes in the utf8 // one. Thus if the slice is less than 64 / 4 (16) we can guarantee that // we'll decode it in place. let owned_string; let len = self.len(); let utf8_slice = if len <= 16 { let mut total_len = 0; for c in self.chars() { let c = c.unwrap_or(char::REPLACEMENT_CHARACTER); let utf8_len = c.encode_utf8(&mut buffer[total_len..]).len(); total_len += utf8_len; } let slice = unsafe { str::from_utf8_unchecked(&buffer[..total_len]) }; debug_assert_eq!(slice, String::from_utf16_lossy(self.as_slice())); slice } else { owned_string = String::from_utf16_lossy(self.as_slice()); &*owned_string }; cb(utf8_slice) } /// Returns whether this atom is static. #[inline] pub fn is_static(&self) -> bool { self.0.mIsStatic()!= 0 } /// Returns whether this atom is ascii lowercase. #[inline] fn is_ascii_lowercase(&self) -> bool { self.0.mIsAsciiLowercase()!= 0 } /// Returns the length of the atom string. #[inline] pub fn len(&self) -> u32 { self.0.mLength() } /// Returns whether this atom is the empty string. #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the atom as a mutable pointer. #[inline] pub fn as_ptr(&self) -> *mut nsAtom { let const_ptr: *const nsAtom = &self.0; const_ptr as *mut nsAtom } /// Convert this atom to ASCII lower-case pub fn to_ascii_lowercase(&self) -> Atom { if self.is_ascii_lowercase() { return self.clone(); } let slice = self.as_slice(); let mut buffer: [u16; 64] = unsafe { mem::uninitialized() }; let mut vec; let mutable_slice = if let Some(buffer_prefix) = buffer.get_mut(..slice.len()) { buffer_prefix.copy_from_slice(slice); buffer_prefix } else { vec = slice.to_vec(); &mut vec }; for char16 in &mut *mutable_slice { if *char16 <= 0x7F { *char16 = (*char16 as u8).to_ascii_lowercase() as u16 } } Atom::from(&*mutable_slice) } /// Return whether two atoms are ASCII-case-insensitive matches #[inline] pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool { if self == other { return true; } // If we know both atoms are ascii-lowercase, then we can stick with // pointer equality. if self.is_ascii_lowercase() && other.is_ascii_lowercase() { debug_assert!(!self.eq_ignore_ascii_case_slow(other)); return false; } self.eq_ignore_ascii_case_slow(other) } fn eq_ignore_ascii_case_slow(&self, other: &Self) -> bool { let a = self.as_slice(); let b = other.as_slice(); if a.len()!= b.len() { return false; } a.iter().zip(b).all(|(&a16, &b16)| { if a16 <= 0x7F && b16 <= 0x7F { (a16 as u8).eq_ignore_ascii_case(&(b16 as u8)) } else { a16 == b16 } }) } } impl fmt::Debug for WeakAtom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { write!(w, "Gecko WeakAtom({:p}, {})", self, self) } } impl fmt::Display for WeakAtom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { for c in self.chars() { w.write_char(c.unwrap_or(char::REPLACEMENT_CHARACTER))? } Ok(()) } } #[inline] unsafe fn make_handle(ptr: *const nsAtom) -> usize { debug_assert!(!ptr.is_null()); if!WeakAtom::new(ptr).is_static() { ptr as usize } else { make_static_handle(ptr as *mut nsStaticAtom) } } #[inline] unsafe fn make_static_handle(ptr: *const nsStaticAtom) -> usize { // FIXME(heycam): Use offset_from once it's stabilized. // https://github.com/rust-lang/rust/issues/41079 debug_assert!(valid_static_atom_addr(ptr as usize)); let base = &gGkAtoms as *const _; let offset = ptr as usize - base as usize; (offset << 1) | 1 } impl Atom { #[inline] fn is_static(&self) -> bool { self.0 & 1 == 1 } /// Execute a callback with the atom represented by `ptr`. pub unsafe fn with<F, R>(ptr: *const nsAtom, callback: F) -> R where F: FnOnce(&Atom) -> R, { let atom = Atom(make_handle(ptr as *mut nsAtom)); let ret = callback(&atom); mem::forget(atom); ret } /// Creates a static atom from its index in the static atom table, without /// checking in release builds. #[inline] pub unsafe fn from_index(index: u16) -> Self { let ptr = static_atoms().get_unchecked(index as usize) as *const _; let handle = make_static_handle(ptr); let atom = Atom(handle); debug_assert!(valid_static_atom_addr(ptr as usize)); debug_assert!(atom.is_static()); debug_assert!((*atom).is_static()); debug_assert!(handle == make_handle(atom.as_ptr())); atom } /// Creates an atom from an atom pointer. #[inline(always)] pub unsafe fn from_raw(ptr: *mut nsAtom) -> Self { let atom = Atom(make_handle(ptr)); if!atom.is_static() { Gecko_AddRefAtom(ptr); } atom } /// Creates an atom from an atom pointer that has already had AddRef /// called on it. This may be a static or dynamic atom. #[inline] pub unsafe fn from_addrefed(ptr: *mut nsAtom) -> Self { assert!(!ptr.is_null()); Atom(make_handle(ptr)) } /// Convert this atom into an addrefed nsAtom pointer. #[inline] pub fn into_addrefed(self) -> *mut nsAtom { let ptr = self.as_ptr(); mem::forget(self); ptr } } impl Hash for Atom { fn hash<H>(&self, state: &mut H) where H: Hasher, { state.write_u32(self.get_hash()); } } impl Hash for WeakAtom { fn hash<H>(&self, state: &mut H) where H: Hasher, { state.write_u32(self.get_hash()); } } impl Clone for Atom { #[inline(always)] fn clone(&self) -> Atom { unsafe { let atom = Atom(self.0); if!atom.is_static() { Gecko_AddRefAtom(atom.as_ptr()); } atom } } } impl Drop for Atom { #[inline] fn drop(&mut self) { if!self.is_static() { unsafe { Gecko_ReleaseAtom(self.as_ptr()); } } } } impl Default for Atom { #[inline] fn default() -> Self { atom!("") } } impl fmt::Debug for Atom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { write!(w, "Atom(0x{:08x}, {})", self.0, self) } } impl fmt::Display for Atom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { self.deref().fmt(w) } }
#[inline] fn from(string: &str) -> Atom { debug_assert!(string.len() <= u32::max_value() as usize); unsafe { Atom::from_addrefed(Gecko_Atomize( string.as_ptr() as *const _, string.len() as u32, )) } } } impl<'a> From<&'a [u16]> for Atom { #[inline] fn from(slice: &[u16]) -> Atom { Atom::from(&*nsStr::from(slice)) } } impl<'a> From<&'a nsAString> for Atom { #[inline] fn from(string: &nsAString) -> Atom { unsafe { Atom::from_addrefed(Gecko_Atomize16(string)) } } } impl<'a> From<Cow<'a, str>> for Atom { #[inline] fn from(string: Cow<'a, str>) -> Atom { Atom::from(&*string) } } impl From<String> for Atom { #[inline] fn from(string: String) -> Atom { Atom::from(&*string) } } malloc_size_of_is_0!(Atom); impl SpecifiedValueInfo for Atom {}
impl<'a> From<&'a str> for Atom {
random_line_split
mod.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ #![allow(unsafe_code)] // This is needed for the constants in atom_macro.rs, because we have some // atoms whose names differ only by case, e.g. datetime and dateTime. #![allow(non_upper_case_globals)] //! A drop-in replacement for string_cache, but backed by Gecko `nsAtom`s. use crate::gecko_bindings::bindings::Gecko_AddRefAtom; use crate::gecko_bindings::bindings::Gecko_Atomize; use crate::gecko_bindings::bindings::Gecko_Atomize16; use crate::gecko_bindings::bindings::Gecko_ReleaseAtom; use crate::gecko_bindings::structs::root::mozilla::detail::gGkAtoms; use crate::gecko_bindings::structs::root::mozilla::detail::kGkAtomsArrayOffset; use crate::gecko_bindings::structs::root::mozilla::detail::GkAtoms_Atoms_AtomsCount; use crate::gecko_bindings::structs::{nsAtom, nsDynamicAtom, nsStaticAtom}; use nsstring::{nsAString, nsStr}; use precomputed_hash::PrecomputedHash; use std::borrow::{Borrow, Cow}; use std::char::{self, DecodeUtf16}; use std::fmt::{self, Write}; use std::hash::{Hash, Hasher}; use std::iter::Cloned; use std::ops::Deref; use std::{mem, slice, str}; use style_traits::SpecifiedValueInfo; #[macro_use] #[allow(improper_ctypes, non_camel_case_types, missing_docs)] pub mod atom_macro { include!(concat!(env!("OUT_DIR"), "/gecko/atom_macro.rs")); } #[macro_use] pub mod namespace; pub use self::namespace::{Namespace, WeakNamespace}; macro_rules! local_name { ($s:tt) => { atom!($s) }; } /// A handle to a Gecko atom. /// /// This is either a strong reference to a dynamic atom (an nsAtom pointer), /// or an offset from gGkAtoms to the nsStaticAtom object. #[derive(Eq, PartialEq)] pub struct Atom(usize); /// An atom *without* a strong reference. /// /// Only usable as `&'a WeakAtom`, /// where `'a` is the lifetime of something that holds a strong reference to that atom. pub struct WeakAtom(nsAtom); /// The number of static atoms we have. const STATIC_ATOM_COUNT: usize = GkAtoms_Atoms_AtomsCount as usize; /// Returns the Gecko static atom array. /// /// We have this rather than use rust-bindgen to generate /// mozilla::detail::gGkAtoms and then just reference gGkAtoms.mAtoms, so we /// avoid a problem with lld-link.exe on Windows. /// /// https://bugzilla.mozilla.org/show_bug.cgi?id=1517685 #[inline] fn static_atoms() -> &'static [nsStaticAtom; STATIC_ATOM_COUNT] { unsafe { let addr = &gGkAtoms as *const _ as usize + kGkAtomsArrayOffset as usize; &*(addr as *const _) } } /// Returns whether the specified address points to one of the nsStaticAtom /// objects in the Gecko static atom array. #[inline] fn valid_static_atom_addr(addr: usize) -> bool { unsafe { let atoms = static_atoms(); let start = atoms.get_unchecked(0) as *const _; let end = atoms.get_unchecked(STATIC_ATOM_COUNT) as *const _; let in_range = addr >= start as usize && addr < end as usize; let aligned = addr % mem::align_of::<nsStaticAtom>() == 0; in_range && aligned } } impl Deref for Atom { type Target = WeakAtom; #[inline] fn deref(&self) -> &WeakAtom { unsafe { let addr = if self.is_static() { (&gGkAtoms as *const _ as usize) + (self.0 >> 1) } else { self.0 }; debug_assert!(!self.is_static() || valid_static_atom_addr(addr)); WeakAtom::new(addr as *const nsAtom) } } } impl PrecomputedHash for Atom { #[inline] fn precomputed_hash(&self) -> u32 { self.get_hash() } } impl Borrow<WeakAtom> for Atom { #[inline] fn borrow(&self) -> &WeakAtom { self } } impl Eq for WeakAtom {} impl PartialEq for WeakAtom { #[inline] fn eq(&self, other: &Self) -> bool { let weak: *const WeakAtom = self; let other: *const WeakAtom = other; weak == other } } unsafe impl Send for Atom {} unsafe impl Sync for Atom {} unsafe impl Sync for WeakAtom {} impl WeakAtom { /// Construct a `WeakAtom` from a raw `nsAtom`. #[inline] pub unsafe fn new<'a>(atom: *const nsAtom) -> &'a mut Self { &mut *(atom as *mut WeakAtom) } /// Clone this atom, bumping the refcount if the atom is not static. #[inline] pub fn clone(&self) -> Atom { unsafe { Atom::from_raw(self.as_ptr()) } } /// Get the atom hash. #[inline] pub fn get_hash(&self) -> u32 { self.0.mHash } /// Get the atom as a slice of utf-16 chars. #[inline] pub fn as_slice(&self) -> &[u16]
// NOTE: don't expose this, since it's slow, and easy to be misused. fn chars(&self) -> DecodeUtf16<Cloned<slice::Iter<u16>>> { char::decode_utf16(self.as_slice().iter().cloned()) } /// Execute `cb` with the string that this atom represents. /// /// Find alternatives to this function when possible, please, since it's /// pretty slow. pub fn with_str<F, Output>(&self, cb: F) -> Output where F: FnOnce(&str) -> Output, { let mut buffer: [u8; 64] = unsafe { mem::uninitialized() }; // The total string length in utf16 is going to be less than or equal // the slice length (each utf16 character is going to take at least one // and at most 2 items in the utf16 slice). // // Each of those characters will take at most four bytes in the utf8 // one. Thus if the slice is less than 64 / 4 (16) we can guarantee that // we'll decode it in place. let owned_string; let len = self.len(); let utf8_slice = if len <= 16 { let mut total_len = 0; for c in self.chars() { let c = c.unwrap_or(char::REPLACEMENT_CHARACTER); let utf8_len = c.encode_utf8(&mut buffer[total_len..]).len(); total_len += utf8_len; } let slice = unsafe { str::from_utf8_unchecked(&buffer[..total_len]) }; debug_assert_eq!(slice, String::from_utf16_lossy(self.as_slice())); slice } else { owned_string = String::from_utf16_lossy(self.as_slice()); &*owned_string }; cb(utf8_slice) } /// Returns whether this atom is static. #[inline] pub fn is_static(&self) -> bool { self.0.mIsStatic()!= 0 } /// Returns whether this atom is ascii lowercase. #[inline] fn is_ascii_lowercase(&self) -> bool { self.0.mIsAsciiLowercase()!= 0 } /// Returns the length of the atom string. #[inline] pub fn len(&self) -> u32 { self.0.mLength() } /// Returns whether this atom is the empty string. #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Returns the atom as a mutable pointer. #[inline] pub fn as_ptr(&self) -> *mut nsAtom { let const_ptr: *const nsAtom = &self.0; const_ptr as *mut nsAtom } /// Convert this atom to ASCII lower-case pub fn to_ascii_lowercase(&self) -> Atom { if self.is_ascii_lowercase() { return self.clone(); } let slice = self.as_slice(); let mut buffer: [u16; 64] = unsafe { mem::uninitialized() }; let mut vec; let mutable_slice = if let Some(buffer_prefix) = buffer.get_mut(..slice.len()) { buffer_prefix.copy_from_slice(slice); buffer_prefix } else { vec = slice.to_vec(); &mut vec }; for char16 in &mut *mutable_slice { if *char16 <= 0x7F { *char16 = (*char16 as u8).to_ascii_lowercase() as u16 } } Atom::from(&*mutable_slice) } /// Return whether two atoms are ASCII-case-insensitive matches #[inline] pub fn eq_ignore_ascii_case(&self, other: &Self) -> bool { if self == other { return true; } // If we know both atoms are ascii-lowercase, then we can stick with // pointer equality. if self.is_ascii_lowercase() && other.is_ascii_lowercase() { debug_assert!(!self.eq_ignore_ascii_case_slow(other)); return false; } self.eq_ignore_ascii_case_slow(other) } fn eq_ignore_ascii_case_slow(&self, other: &Self) -> bool { let a = self.as_slice(); let b = other.as_slice(); if a.len()!= b.len() { return false; } a.iter().zip(b).all(|(&a16, &b16)| { if a16 <= 0x7F && b16 <= 0x7F { (a16 as u8).eq_ignore_ascii_case(&(b16 as u8)) } else { a16 == b16 } }) } } impl fmt::Debug for WeakAtom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { write!(w, "Gecko WeakAtom({:p}, {})", self, self) } } impl fmt::Display for WeakAtom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { for c in self.chars() { w.write_char(c.unwrap_or(char::REPLACEMENT_CHARACTER))? } Ok(()) } } #[inline] unsafe fn make_handle(ptr: *const nsAtom) -> usize { debug_assert!(!ptr.is_null()); if!WeakAtom::new(ptr).is_static() { ptr as usize } else { make_static_handle(ptr as *mut nsStaticAtom) } } #[inline] unsafe fn make_static_handle(ptr: *const nsStaticAtom) -> usize { // FIXME(heycam): Use offset_from once it's stabilized. // https://github.com/rust-lang/rust/issues/41079 debug_assert!(valid_static_atom_addr(ptr as usize)); let base = &gGkAtoms as *const _; let offset = ptr as usize - base as usize; (offset << 1) | 1 } impl Atom { #[inline] fn is_static(&self) -> bool { self.0 & 1 == 1 } /// Execute a callback with the atom represented by `ptr`. pub unsafe fn with<F, R>(ptr: *const nsAtom, callback: F) -> R where F: FnOnce(&Atom) -> R, { let atom = Atom(make_handle(ptr as *mut nsAtom)); let ret = callback(&atom); mem::forget(atom); ret } /// Creates a static atom from its index in the static atom table, without /// checking in release builds. #[inline] pub unsafe fn from_index(index: u16) -> Self { let ptr = static_atoms().get_unchecked(index as usize) as *const _; let handle = make_static_handle(ptr); let atom = Atom(handle); debug_assert!(valid_static_atom_addr(ptr as usize)); debug_assert!(atom.is_static()); debug_assert!((*atom).is_static()); debug_assert!(handle == make_handle(atom.as_ptr())); atom } /// Creates an atom from an atom pointer. #[inline(always)] pub unsafe fn from_raw(ptr: *mut nsAtom) -> Self { let atom = Atom(make_handle(ptr)); if!atom.is_static() { Gecko_AddRefAtom(ptr); } atom } /// Creates an atom from an atom pointer that has already had AddRef /// called on it. This may be a static or dynamic atom. #[inline] pub unsafe fn from_addrefed(ptr: *mut nsAtom) -> Self { assert!(!ptr.is_null()); Atom(make_handle(ptr)) } /// Convert this atom into an addrefed nsAtom pointer. #[inline] pub fn into_addrefed(self) -> *mut nsAtom { let ptr = self.as_ptr(); mem::forget(self); ptr } } impl Hash for Atom { fn hash<H>(&self, state: &mut H) where H: Hasher, { state.write_u32(self.get_hash()); } } impl Hash for WeakAtom { fn hash<H>(&self, state: &mut H) where H: Hasher, { state.write_u32(self.get_hash()); } } impl Clone for Atom { #[inline(always)] fn clone(&self) -> Atom { unsafe { let atom = Atom(self.0); if!atom.is_static() { Gecko_AddRefAtom(atom.as_ptr()); } atom } } } impl Drop for Atom { #[inline] fn drop(&mut self) { if!self.is_static() { unsafe { Gecko_ReleaseAtom(self.as_ptr()); } } } } impl Default for Atom { #[inline] fn default() -> Self { atom!("") } } impl fmt::Debug for Atom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { write!(w, "Atom(0x{:08x}, {})", self.0, self) } } impl fmt::Display for Atom { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { self.deref().fmt(w) } } impl<'a> From<&'a str> for Atom { #[inline] fn from(string: &str) -> Atom { debug_assert!(string.len() <= u32::max_value() as usize); unsafe { Atom::from_addrefed(Gecko_Atomize( string.as_ptr() as *const _, string.len() as u32, )) } } } impl<'a> From<&'a [u16]> for Atom { #[inline] fn from(slice: &[u16]) -> Atom { Atom::from(&*nsStr::from(slice)) } } impl<'a> From<&'a nsAString> for Atom { #[inline] fn from(string: &nsAString) -> Atom { unsafe { Atom::from_addrefed(Gecko_Atomize16(string)) } } } impl<'a> From<Cow<'a, str>> for Atom { #[inline] fn from(string: Cow<'a, str>) -> Atom { Atom::from(&*string) } } impl From<String> for Atom { #[inline] fn from(string: String) -> Atom { Atom::from(&*string) } } malloc_size_of_is_0!(Atom); impl SpecifiedValueInfo for Atom {}
{ let string = if self.is_static() { let atom_ptr = self.as_ptr() as *const nsStaticAtom; let string_offset = unsafe { (*atom_ptr).mStringOffset }; let string_offset = -(string_offset as isize); let u8_ptr = atom_ptr as *const u8; // It is safe to use offset() here because both addresses are within // the same struct, e.g. mozilla::detail::gGkAtoms. unsafe { u8_ptr.offset(string_offset) as *const u16 } } else { let atom_ptr = self.as_ptr() as *const nsDynamicAtom; // Dynamic atom chars are stored at the end of the object. unsafe { atom_ptr.offset(1) as *const u16 } }; unsafe { slice::from_raw_parts(string, self.len() as usize) } }
identifier_body
iobuf.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::ops::{Deref, DerefMut}; use data_model::IoBufMut; /// A trait for describing regions of memory to be used for IO. /// /// # Safety /// /// Types that implement this trait _must_ guarantee that the memory regions described by /// `as_iobufs()` are valid for the lifetime of the borrow. pub unsafe trait AsIoBufs { /// Returns a slice describing regions of memory on which to perform some IO. The returned /// memory region descriptions may be passed on to the OS kernel so implmentations must /// guarantee that the memory regions are valid for the lifetime of the borrow. fn as_iobufs(&mut self) -> &[IoBufMut]; } /// An owned buffer for IO. /// /// This type will be most commonly used to wrap a `Vec<u8>`. /// /// # Examples /// /// ``` /// # async fn do_it() -> anyhow::Result<()> { /// use cros_async::{Executor, File, OwnedIoBuf}; /// use std::{convert::TryFrom, fs::OpenOptions}; /// /// let urandom = File::open("/dev/urandom")?; /// let buf = OwnedIoBuf::new(vec![0; 256]); /// /// let (res, mut buf) = urandom.read_iobuf(buf, None).await; /// let count = res?; /// buf.truncate(count); /// /// let null = OpenOptions::new() /// .write(true) /// .open("/dev/null") /// .map_err(From::from) /// .and_then(File::try_from)?; /// while buf.len() > 0 { /// let (res, data) = null.write_iobuf(buf, None).await; /// let bytes_written = res?; /// buf = data; /// buf.advance(bytes_written); /// } /// # Ok(()) /// # } /// # cros_async::Executor::new().run_until(do_it()).unwrap().unwrap(); /// ``` pub struct OwnedIoBuf { buf: Box<[u8]>, // This IoBufMut has a static lifetime because it points to the data owned by `buf` so the // pointer is always valid for the lifetime of this struct. iobuf: [IoBufMut<'static>; 1], } impl OwnedIoBuf { /// Create a new owned IO buffer. pub fn new<B: Into<Box<[u8]>>>(buf: B) -> OwnedIoBuf { let mut buf = buf.into(); let iobuf = unsafe { IoBufMut::from_raw_parts(buf.as_mut_ptr(), buf.len()) }; OwnedIoBuf { buf, iobuf: [iobuf], } } /// Returns the length of the IO buffer. pub fn len(&self) -> usize { self.iobuf[0].len() } /// Returns true if the length of the buffer is 0. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Advances the beginning of the buffer by `count` bytes. /// /// Panics if `count > self.len()`. pub fn advance(&mut self, count: usize) { self.iobuf[0].advance(count) } /// Change the size of the buffer used for IO. /// /// Has no effect if `len > self.len()`. pub fn truncate(&mut self, len: usize) { self.iobuf[0].truncate(len) } /// Reset the buffer to its full length. pub fn reset(&mut self) { self.iobuf[0] = unsafe { IoBufMut::from_raw_parts(self.buf.as_mut_ptr(), self.buf.len()) }; } /// Convert this `OwnedIoBuf` back into the inner type. pub fn into_inner<C: From<Box<[u8]>>>(self) -> C { self.buf.into() } } impl Deref for OwnedIoBuf { type Target = [u8]; fn deref(&self) -> &Self::Target { &self.buf } } impl DerefMut for OwnedIoBuf { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.buf } } // Safe because the pointer and length in the returned `&[IoBufMut]` are valid for the lifetime of // the OwnedIoBuf. unsafe impl AsIoBufs for OwnedIoBuf { fn
(&mut self) -> &[IoBufMut] { &self.iobuf } } #[cfg(test)] mod test { use super::*; #[test] fn len() { let buf = OwnedIoBuf::new(vec![0xcc; 64]); assert_eq!(buf.len(), 64); } #[test] fn advance() { let mut buf = OwnedIoBuf::new(vec![0xcc; 64]); buf.advance(17); assert_eq!(buf.len(), 47); assert_eq!(buf.iobuf[0].as_ptr(), unsafe { buf.buf.as_ptr().add(17) }); buf.advance(9); assert_eq!(buf.len(), 38); assert_eq!(buf.iobuf[0].as_ptr(), unsafe { buf.buf.as_ptr().add(26) }); buf.advance(38); assert_eq!(buf.len(), 0); assert_eq!(buf.iobuf[0].as_ptr(), unsafe { buf.buf.as_ptr().add(64) }); } #[test] fn truncate() { let mut buf = OwnedIoBuf::new(vec![0xcc; 64]); buf.truncate(99); assert_eq!(buf.len(), 64); buf.truncate(64); assert_eq!(buf.len(), 64); buf.truncate(22); assert_eq!(buf.len(), 22); buf.truncate(0); assert_eq!(buf.len(), 0); } #[test] fn reset() { let mut buf = OwnedIoBuf::new(vec![0xcc; 64]); buf.truncate(22); assert_eq!(buf.len(), 22); assert_eq!(buf.iobuf[0].as_ptr(), buf.buf.as_ptr()); buf.advance(17); assert_eq!(buf.len(), 5); assert_eq!(buf.iobuf[0].as_ptr(), unsafe { buf.buf.as_ptr().add(17) }); buf.reset(); assert_eq!(buf.len(), 64); assert_eq!(buf.iobuf[0].as_ptr(), buf.buf.as_ptr()); } }
as_iobufs
identifier_name
iobuf.rs
// Copyright 2021 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use std::ops::{Deref, DerefMut}; use data_model::IoBufMut; /// A trait for describing regions of memory to be used for IO. /// /// # Safety /// /// Types that implement this trait _must_ guarantee that the memory regions described by /// `as_iobufs()` are valid for the lifetime of the borrow. pub unsafe trait AsIoBufs { /// Returns a slice describing regions of memory on which to perform some IO. The returned /// memory region descriptions may be passed on to the OS kernel so implmentations must /// guarantee that the memory regions are valid for the lifetime of the borrow. fn as_iobufs(&mut self) -> &[IoBufMut]; } /// An owned buffer for IO. /// /// This type will be most commonly used to wrap a `Vec<u8>`. /// /// # Examples /// /// ``` /// # async fn do_it() -> anyhow::Result<()> { /// use cros_async::{Executor, File, OwnedIoBuf}; /// use std::{convert::TryFrom, fs::OpenOptions}; /// /// let urandom = File::open("/dev/urandom")?; /// let buf = OwnedIoBuf::new(vec![0; 256]); /// /// let (res, mut buf) = urandom.read_iobuf(buf, None).await; /// let count = res?; /// buf.truncate(count); /// /// let null = OpenOptions::new() /// .write(true) /// .open("/dev/null") /// .map_err(From::from) /// .and_then(File::try_from)?; /// while buf.len() > 0 { /// let (res, data) = null.write_iobuf(buf, None).await; /// let bytes_written = res?; /// buf = data; /// buf.advance(bytes_written); /// } /// # Ok(())
/// # } /// # cros_async::Executor::new().run_until(do_it()).unwrap().unwrap(); /// ``` pub struct OwnedIoBuf { buf: Box<[u8]>, // This IoBufMut has a static lifetime because it points to the data owned by `buf` so the // pointer is always valid for the lifetime of this struct. iobuf: [IoBufMut<'static>; 1], } impl OwnedIoBuf { /// Create a new owned IO buffer. pub fn new<B: Into<Box<[u8]>>>(buf: B) -> OwnedIoBuf { let mut buf = buf.into(); let iobuf = unsafe { IoBufMut::from_raw_parts(buf.as_mut_ptr(), buf.len()) }; OwnedIoBuf { buf, iobuf: [iobuf], } } /// Returns the length of the IO buffer. pub fn len(&self) -> usize { self.iobuf[0].len() } /// Returns true if the length of the buffer is 0. pub fn is_empty(&self) -> bool { self.len() == 0 } /// Advances the beginning of the buffer by `count` bytes. /// /// Panics if `count > self.len()`. pub fn advance(&mut self, count: usize) { self.iobuf[0].advance(count) } /// Change the size of the buffer used for IO. /// /// Has no effect if `len > self.len()`. pub fn truncate(&mut self, len: usize) { self.iobuf[0].truncate(len) } /// Reset the buffer to its full length. pub fn reset(&mut self) { self.iobuf[0] = unsafe { IoBufMut::from_raw_parts(self.buf.as_mut_ptr(), self.buf.len()) }; } /// Convert this `OwnedIoBuf` back into the inner type. pub fn into_inner<C: From<Box<[u8]>>>(self) -> C { self.buf.into() } } impl Deref for OwnedIoBuf { type Target = [u8]; fn deref(&self) -> &Self::Target { &self.buf } } impl DerefMut for OwnedIoBuf { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.buf } } // Safe because the pointer and length in the returned `&[IoBufMut]` are valid for the lifetime of // the OwnedIoBuf. unsafe impl AsIoBufs for OwnedIoBuf { fn as_iobufs(&mut self) -> &[IoBufMut] { &self.iobuf } } #[cfg(test)] mod test { use super::*; #[test] fn len() { let buf = OwnedIoBuf::new(vec![0xcc; 64]); assert_eq!(buf.len(), 64); } #[test] fn advance() { let mut buf = OwnedIoBuf::new(vec![0xcc; 64]); buf.advance(17); assert_eq!(buf.len(), 47); assert_eq!(buf.iobuf[0].as_ptr(), unsafe { buf.buf.as_ptr().add(17) }); buf.advance(9); assert_eq!(buf.len(), 38); assert_eq!(buf.iobuf[0].as_ptr(), unsafe { buf.buf.as_ptr().add(26) }); buf.advance(38); assert_eq!(buf.len(), 0); assert_eq!(buf.iobuf[0].as_ptr(), unsafe { buf.buf.as_ptr().add(64) }); } #[test] fn truncate() { let mut buf = OwnedIoBuf::new(vec![0xcc; 64]); buf.truncate(99); assert_eq!(buf.len(), 64); buf.truncate(64); assert_eq!(buf.len(), 64); buf.truncate(22); assert_eq!(buf.len(), 22); buf.truncate(0); assert_eq!(buf.len(), 0); } #[test] fn reset() { let mut buf = OwnedIoBuf::new(vec![0xcc; 64]); buf.truncate(22); assert_eq!(buf.len(), 22); assert_eq!(buf.iobuf[0].as_ptr(), buf.buf.as_ptr()); buf.advance(17); assert_eq!(buf.len(), 5); assert_eq!(buf.iobuf[0].as_ptr(), unsafe { buf.buf.as_ptr().add(17) }); buf.reset(); assert_eq!(buf.len(), 64); assert_eq!(buf.iobuf[0].as_ptr(), buf.buf.as_ptr()); } }
random_line_split
issue-17121.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(dead_code)] // pretty-expanded FIXME #23616 // ignore-cloudabi no std::fs use std::fs::File; use std::io::{self, BufReader, Read}; struct Lexer<R: Read> { reader: BufReader<R>, } impl<R: Read> Lexer<R> { pub fn new_from_reader(r: R) -> Lexer<R> { Lexer{reader: BufReader::new(r)} } pub fn new_from_file(p: &str) -> io::Result<Lexer<File>>
pub fn new_from_str<'a>(s: &'a str) -> Lexer<&'a [u8]> { Lexer::new_from_reader(s.as_bytes()) } } fn main() {}
{ Ok(Lexer::new_from_reader(File::open(p)?)) }
identifier_body
issue-17121.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(dead_code)] // pretty-expanded FIXME #23616 // ignore-cloudabi no std::fs use std::fs::File; use std::io::{self, BufReader, Read}; struct Lexer<R: Read> { reader: BufReader<R>, } impl<R: Read> Lexer<R> { pub fn new_from_reader(r: R) -> Lexer<R> {
{ Ok(Lexer::new_from_reader(File::open(p)?)) } pub fn new_from_str<'a>(s: &'a str) -> Lexer<&'a [u8]> { Lexer::new_from_reader(s.as_bytes()) } } fn main() {}
Lexer{reader: BufReader::new(r)} } pub fn new_from_file(p: &str) -> io::Result<Lexer<File>>
random_line_split
issue-17121.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // compile-pass #![allow(dead_code)] // pretty-expanded FIXME #23616 // ignore-cloudabi no std::fs use std::fs::File; use std::io::{self, BufReader, Read}; struct Lexer<R: Read> { reader: BufReader<R>, } impl<R: Read> Lexer<R> { pub fn
(r: R) -> Lexer<R> { Lexer{reader: BufReader::new(r)} } pub fn new_from_file(p: &str) -> io::Result<Lexer<File>> { Ok(Lexer::new_from_reader(File::open(p)?)) } pub fn new_from_str<'a>(s: &'a str) -> Lexer<&'a [u8]> { Lexer::new_from_reader(s.as_bytes()) } } fn main() {}
new_from_reader
identifier_name
ufcs-explicit-self-bad.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::owned::Box; struct Foo { f: int, } impl Foo { fn foo(self: int, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` self.f + x } } struct Bar<T> { f: T, } impl<T> Bar<T> { fn foo(self: Bar<int>, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` x } fn bar(self: &Bar<uint>, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` x } } fn main() { let foo = box Foo { f: 1, }; println!("{}", foo.foo(2));
f: 1, }; println!("{} {}", bar.foo(2), bar.bar(2)); }
let bar = box Bar {
random_line_split
ufcs-explicit-self-bad.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::owned::Box; struct Foo { f: int, } impl Foo { fn foo(self: int, x: int) -> int
} struct Bar<T> { f: T, } impl<T> Bar<T> { fn foo(self: Bar<int>, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` x } fn bar(self: &Bar<uint>, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` x } } fn main() { let foo = box Foo { f: 1, }; println!("{}", foo.foo(2)); let bar = box Bar { f: 1, }; println!("{} {}", bar.foo(2), bar.bar(2)); }
{ //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` self.f + x }
identifier_body
ufcs-explicit-self-bad.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::owned::Box; struct Foo { f: int, } impl Foo { fn foo(self: int, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` self.f + x } } struct Bar<T> { f: T, } impl<T> Bar<T> { fn
(self: Bar<int>, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` x } fn bar(self: &Bar<uint>, x: int) -> int { //~ ERROR mismatched self type //~^ ERROR not a valid type for `self` x } } fn main() { let foo = box Foo { f: 1, }; println!("{}", foo.foo(2)); let bar = box Bar { f: 1, }; println!("{} {}", bar.foo(2), bar.bar(2)); }
foo
identifier_name
calc2.rs
// Copyright 2014 Pierre Talbot (IRCAM) // 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 oak::oak; use self::Expression::*; use self::BinOp::*; use std::str::FromStr; pub type PExpr = Box<Expression>; #[derive(Debug)] pub enum Expression { Variable(String), Number(u32), BinaryExpr(BinOp, PExpr, PExpr), LetIn(String, PExpr, PExpr) } #[derive(Debug)] pub enum BinOp { Add, Sub, Mul, Div, Exp } oak! { // Optional stream declaration. type Stream<'a> = StrStream<'a>; program = spacing expression expression = term (term_op term)* > fold_left term = exponent (factor_op exponent)* > fold_left exponent = (factor exponent_op)* factor > fold_right factor: PExpr = number > box Number / identifier > box Variable / let_expr > box LetIn / lparen expression rparen let_expr = let_kw let_binding in_kw expression let_binding = identifier bind_op expression term_op: BinOp = add_op > Add / sub_op > Sub factor_op: BinOp = mul_op > Mul / div_op > Div exponent_op: BinOp = exp_op > Exp identifier =!digit!keyword ident_char+ spacing > to_string ident_char = ["a-zA-Z0-9_"] digit = ["0-9"] number = digit+ spacing > to_number spacing = [" \n\r\t"]*:(^) kw_tail =!ident_char spacing keyword = let_kw / in_kw let_kw = "let" kw_tail in_kw = "in" kw_tail bind_op = "=" spacing add_op = "+" spacing sub_op = "-" spacing mul_op = "*" spacing div_op = "/" spacing exp_op = "^" spacing lparen = "(" spacing rparen = ")" spacing fn to_number(raw_text: Vec<char>) -> u32 { u32::from_str(&*to_string(raw_text)).unwrap() } fn to_string(raw_text: Vec<char>) -> String { raw_text.into_iter().collect() } fn fold_left(head: PExpr, rest: Vec<(BinOp, PExpr)>) -> PExpr { rest.into_iter().fold(head, |accu, (op, expr)| Box::new(BinaryExpr(op, accu, expr))) } fn fold_right(front: Vec<(PExpr, BinOp)>, last: PExpr) -> PExpr { front.into_iter().rev().fold(last, |accu, (expr, op)| Box::new(BinaryExpr(op, expr, accu)))
}
}
random_line_split
calc2.rs
// Copyright 2014 Pierre Talbot (IRCAM) // 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 oak::oak; use self::Expression::*; use self::BinOp::*; use std::str::FromStr; pub type PExpr = Box<Expression>; #[derive(Debug)] pub enum Expression { Variable(String), Number(u32), BinaryExpr(BinOp, PExpr, PExpr), LetIn(String, PExpr, PExpr) } #[derive(Debug)] pub enum
{ Add, Sub, Mul, Div, Exp } oak! { // Optional stream declaration. type Stream<'a> = StrStream<'a>; program = spacing expression expression = term (term_op term)* > fold_left term = exponent (factor_op exponent)* > fold_left exponent = (factor exponent_op)* factor > fold_right factor: PExpr = number > box Number / identifier > box Variable / let_expr > box LetIn / lparen expression rparen let_expr = let_kw let_binding in_kw expression let_binding = identifier bind_op expression term_op: BinOp = add_op > Add / sub_op > Sub factor_op: BinOp = mul_op > Mul / div_op > Div exponent_op: BinOp = exp_op > Exp identifier =!digit!keyword ident_char+ spacing > to_string ident_char = ["a-zA-Z0-9_"] digit = ["0-9"] number = digit+ spacing > to_number spacing = [" \n\r\t"]*:(^) kw_tail =!ident_char spacing keyword = let_kw / in_kw let_kw = "let" kw_tail in_kw = "in" kw_tail bind_op = "=" spacing add_op = "+" spacing sub_op = "-" spacing mul_op = "*" spacing div_op = "/" spacing exp_op = "^" spacing lparen = "(" spacing rparen = ")" spacing fn to_number(raw_text: Vec<char>) -> u32 { u32::from_str(&*to_string(raw_text)).unwrap() } fn to_string(raw_text: Vec<char>) -> String { raw_text.into_iter().collect() } fn fold_left(head: PExpr, rest: Vec<(BinOp, PExpr)>) -> PExpr { rest.into_iter().fold(head, |accu, (op, expr)| Box::new(BinaryExpr(op, accu, expr))) } fn fold_right(front: Vec<(PExpr, BinOp)>, last: PExpr) -> PExpr { front.into_iter().rev().fold(last, |accu, (expr, op)| Box::new(BinaryExpr(op, expr, accu))) } }
BinOp
identifier_name
eventlistener.rs
#![allow(non_snake_case)] #![allow(unused_variables)] use super::super::win::types::{WndProc,MSG,WPARAM,LPARAM}; use super::super::win::wnd::DWnd; use super::super::win::api::{CallWindowProcW}; use std::rc::Rc; use std::cell::{RefCell}; use std::collections::HashMap; /* 每一个窗口都有一个自有的事件处理器.它们通过哈希表关联在一起. */ pub struct EventProcesser{ pub defWindowProc:WndProc, //默认窗口过程. 当所有事件处理完毕,该过程将会被调用. //事件映射表,任意的. // pub events:HashMap<u32,RefCell<Box<Event +'static>>>, //事件对象表 //WM_NOTIFY // notifers:HashMap<u32,RefCell<Box<Event +'static>>>, //通知事件对象表. //WM_COMMAND // commands:HashMap<u32,RefCell<Box<Event +'static>>>, //菜单事件对象表. } pub trait TEventProcesser { // 消息进入队列之前.在这里处理. // 处理了 返回 false 返回 true 表示调用者需要自己处理消息. // 如果是窗体,且自己有快捷键表...... fn preTranslateMsg(&self,msg:&mut MSG)->bool{ true } fn setWndProc(&mut self,wproc:WndProc){} fn getWndProc(&self)->WndProc; fn setHwnd(&mut self, hWin:DWnd){} // 对象自有消息过程 fn msgProcedure(&self,hWin:DWnd, msg:u32,wparam:WPARAM,lparam:LPARAM)->int{ unsafe{ return CallWindowProcW(self.getWndProc(), hWin, msg, wparam, lparam) as int; } } } trait Event{ fn addEventEventListener(&self, evCallback:||->bool)->bool{ true } } /* trait Button for HWND{ fn Button(...)->HWND { let
indowEx(.....); unHookEventCreate(); hWin } } trait Window for HWND{ fn Window(title:&str, x:int,y:int, w:int,h:int)->HWND { let hWin; let mut event = WindowEventProcesser::new(); hookEventCreate(event) HWND = CreateWindowEx(.....); unHookEventCreate(); hWin } } let window = Window::Window("Hello Rust",style,0,0,400,560,|e|{ // onCreate }); let button = Button::new("Click Me", 0, 0, 100, 40); window.on(EventType::Created,|e|{ // you event code is here.... }); window.on(EventType::Size,|e|{ // you code is here.... }); window.onCommand(button.getId(), |e|{ // button clicked. }); */
hWin; let mut event = WindowWdgetsProcesser::new(); hookEventCreate(event) HWND = CreateW
identifier_body
eventlistener.rs
#![allow(non_snake_case)] #![allow(unused_variables)] use super::super::win::types::{WndProc,MSG,WPARAM,LPARAM}; use super::super::win::wnd::DWnd; use super::super::win::api::{CallWindowProcW}; use std::rc::Rc; use std::cell::{RefCell}; use std::collections::HashMap; /* 每一个窗口都有一个自有的事件处理器.它们通过哈希表关联在一起. */ pub struct EventProcesser{ pub defWindowProc:WndProc, //默认窗口过程. 当所有事件处理完毕,该过程将会被调用. //事件映射表,任意的. // pub events:HashMap<u32,RefCell<Box<Event +'static>>>, //事件对象表 //WM_NOTIFY // notifers:HashMap<u32,RefCell<Box<Event +'static>>>, //通知事件对象表. //WM_COMMAND // commands:HashMap<u32,RefCell<Box<Event +'static>>>, //菜单事件对象表. } pub trait TEventProcesser { // 消息进入队列之前.在这里处理. // 处理了 返回 false 返回 true 表示调用者需要自己处理消息. // 如果是窗体,且自己有快捷键表...... fn preTranslateMsg(&self,msg:&mut MSG)->bool{ true } fn setWndProc(&mut self,wproc:WndProc){} fn getWndProc(&self)->WndProc; fn setHwnd(&mut self, hWin:DWnd){} // 对象自有消息过程 fn msgProcedure(&self,hWin:DWnd, msg:u32,wparam:WPARAM,lparam:LPARAM)->int{ unsafe{ return CallWindowProcW(self.getWndProc(), hWin, msg, wparam, lparam) as int; } } } trait Event{ fn addEventEventListener(&self, evCallback:||->bool)->bool{ true } } /* trait Button for HWND{ fn Button(...)->HWND { let hWin; let mut event = WindowWdgetsProcesser::new(); hookEventCreate(event) HWND = CreateWindowEx(.....); unHookEventCreate(); hWin } } trait Window for HWND{ fn Window(title:&str, x:int,y:int, w:int,h:int)->HWND { let hWin; let mut event = WindowEventProcesser::new(); hookEventCreate(event) HWND = CreateWindowEx(.....); unHookEventCreate(); hWin } } let window = Window::Window("Hello Rust",style,0,0,400,560,|e|{ // onCreate }); let button = Button::new("Click Me", 0, 0, 100, 40); window.on(EventType::Created,|e|{ // you event code is here.... });
// button clicked. }); */
window.on(EventType::Size,|e|{ // you code is here.... }); window.onCommand(button.getId(), |e|{
random_line_split
eventlistener.rs
#![allow(non_snake_case)] #![allow(unused_variables)] use super::super::win::types::{WndProc,MSG,WPARAM,LPARAM}; use super::super::win::wnd::DWnd; use super::super::win::api::{CallWindowProcW}; use std::rc::Rc; use std::cell::{RefCell}; use std::collections::HashMap; /* 每一个窗口都有一个自有的事件处理器.它们通过哈希表关联在一起. */ pub struct EventProcesser{ pub defWindowProc:WndProc, //默认窗口过程. 当所有事件处理完毕,该过程将会被调用. //事件映射表,任意的. // pub events:HashMap<u32,RefCell<Box<Event +'static>>>, //事件对象表 //WM_NOTIFY // notifers:HashMap<u32,RefCell<Box<Event +'static>>>, //通知事件对象表. //WM_COMMAND // commands:HashMap<u32,RefCell<Box<Event +'static>>>, //菜单事件对象表. } pub trait TEventProcesser { // 消息进入队列之前.在这里处理. // 处理了 返回 false 返回 true 表示调用者需要自己处理消息. // 如果是窗体,且自己有快捷键表...... fn preTranslateMsg(&self,msg:&mut MSG)->bool{ true } fn setWndProc(&mut self,wproc:WndProc){} fn getWndProc(&self)->WndProc; fn setHwnd(&mut self, hWin:DWnd){} // 对象自有消息过程 fn msgProcedure(&self,hWin:DWnd, msg:u32,wparam:WPARAM,lparam:LPARAM)->int{ unsafe{ return CallWindowProcW(self.getWndProc(), hWin, msg, wparam, lparam) as int; } } } trait Event{ fn addEventEventListener(&self, evCallback:||->bool)->bool{ true }
trait Button for HWND{ fn Button(...)->HWND { let hWin; let mut event = WindowWdgetsProcesser::new(); hookEventCreate(event) HWND = CreateWindowEx(.....); unHookEventCreate(); hWin } } trait Window for HWND{ fn Window(title:&str, x:int,y:int, w:int,h:int)->HWND { let hWin; let mut event = WindowEventProcesser::new(); hookEventCreate(event) HWND = CreateWindowEx(.....); unHookEventCreate(); hWin } } let window = Window::Window("Hello Rust",style,0,0,400,560,|e|{ // onCreate }); let button = Button::new("Click Me", 0, 0, 100, 40); window.on(EventType::Created,|e|{ // you event code is here.... }); window.on(EventType::Size,|e|{ // you code is here.... }); window.onCommand(button.getId(), |e|{ // button clicked. }); */
} /*
identifier_name
builtin-superkinds-capabilities-transitive.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
// a Send. Basically this just makes sure rustc is using // each_bound_trait_and_supertraits in type_contents correctly. trait Bar : Send { } trait Foo : Bar { } impl <T: Send> Foo for T { } impl <T: Send> Bar for T { } fn foo<T: Foo>(val: T, chan: Sender<T>) { chan.send(val); } pub fn main() { let (tx, rx) = channel(); foo(31337, tx); assert!(rx.recv() == 31337); }
// Tests "transitivity" of super-builtin-kinds on traits. Here, if // we have a Foo, we know we have a Bar, and if we have a Bar, we // know we have a Send. So if we have a Foo we should know we have
random_line_split
builtin-superkinds-capabilities-transitive.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. // Tests "transitivity" of super-builtin-kinds on traits. Here, if // we have a Foo, we know we have a Bar, and if we have a Bar, we // know we have a Send. So if we have a Foo we should know we have // a Send. Basically this just makes sure rustc is using // each_bound_trait_and_supertraits in type_contents correctly. trait Bar : Send { } trait Foo : Bar { } impl <T: Send> Foo for T { } impl <T: Send> Bar for T { } fn foo<T: Foo>(val: T, chan: Sender<T>) { chan.send(val); } pub fn main()
{ let (tx, rx) = channel(); foo(31337, tx); assert!(rx.recv() == 31337); }
identifier_body
builtin-superkinds-capabilities-transitive.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. // Tests "transitivity" of super-builtin-kinds on traits. Here, if // we have a Foo, we know we have a Bar, and if we have a Bar, we // know we have a Send. So if we have a Foo we should know we have // a Send. Basically this just makes sure rustc is using // each_bound_trait_and_supertraits in type_contents correctly. trait Bar : Send { } trait Foo : Bar { } impl <T: Send> Foo for T { } impl <T: Send> Bar for T { } fn
<T: Foo>(val: T, chan: Sender<T>) { chan.send(val); } pub fn main() { let (tx, rx) = channel(); foo(31337, tx); assert!(rx.recv() == 31337); }
foo
identifier_name
parser.rs
use {Symbol, Rules, Text2Parse, Error, error}; use parser; use atom::parse_symbol; use ast; pub struct Config<'a> { pub text2parse: &'a Text2Parse, pub rules: &'a Rules, } pub trait Parse { fn parse(&self, conf: &Config, status: parser::Status) -> Result<(parser::Status, ast::Node), Error>; } pub fn parse(conf: &Config, symbol: &Symbol, status: parser::Status) -> Result<(parser::Status, ast::Node), Error> { let final_result = parse_symbol(conf, symbol, status)?; match final_result.0.pos.n == conf.text2parse.0.len() { true => Ok(final_result), false => { match final_result.0.deep_error { Some(error) => Err(error), None => { Err(error(&final_result.0.pos, &format!("unexpected >{}<", conf.text2parse .0 .chars() .skip(final_result.0.pos.n) .take(conf.text2parse.0.len() - final_result.0.pos.n) .collect::<String>()), conf.text2parse)) } } } } } #[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Ord)] pub struct Possition { pub n: usize, pub row: usize, pub col: usize, } #[derive(Debug, PartialEq, Clone, PartialOrd)] pub struct Depth(pub u32); #[derive(Debug, PartialEq, Clone)] pub struct Status { pub pos: Possition, pub depth: Depth, pub deep_error: Option<Error>, } impl Status { pub fn new() -> Self { Status { pos: Possition::new(), depth: Depth(0), deep_error: None, } } pub fn inc_depth(&self) -> Self { Status { depth: Depth(self.depth.0 + 1),..self.clone() } } pub fn update_deep_error(mut self, error: &Error) -> Self { self.deep_error = match self.deep_error { Some(ref derr) => { if error.pos.n > derr.pos.n { Some(error.clone()) } else { self.deep_error.clone() } } None => Some(error.clone()), }; self } } impl Possition { pub fn new() -> Self { Possition { n: 0, col: 1, row: 1, } } fn inc_ch(&mut self, ch: char) -> &Self { match ch { '\n' => { self.n += 1; self.col = 0; self.row += 1; } _ => { self.n += 1; self.col += 1; } }; self } pub fn inc_char(&mut self, text2parse: &Text2Parse) -> &Self
pub fn inc_chars(&mut self, s: &str) -> &Self { for ch in s.chars() { self.inc_ch(ch); } self } } pub mod tools { pub use atom::Atom; pub use expression::{Expression, MultiExpr, NRep}; pub fn lit(s: &str) -> Expression { Expression::Simple(Atom::Literal(s.to_owned())) } pub fn dot() -> Expression { Expression::Simple(Atom::Dot) } // fn nothing() -> Expression { // Expression::Simple(Atom::Nothing) // } pub fn or(exp_list: Vec<Expression>) -> Expression { Expression::Or(MultiExpr(exp_list)) } pub fn and(exp_list: Vec<Expression>) -> Expression { Expression::And(MultiExpr(exp_list)) } pub fn symref(s: &str) -> Expression { Expression::Simple(Atom::Symbol(s.to_owned())) } pub fn not(expr: Expression) -> Expression { Expression::Not(Box::new(expr)) } pub fn repeat(expr: Expression, min: NRep, max: Option<NRep>) -> Expression { Expression::Repeat(Box::new(expr), min, max) } pub fn match_ch(chars: &str, ranges: Vec<(char, char)>) -> Expression { Expression::Simple(Atom::Match(chars.to_owned(), ranges)) } }
{ let n = self.n; self.inc_ch(text2parse.0.chars().nth(n).unwrap_or('?')) }
identifier_body
parser.rs
use {Symbol, Rules, Text2Parse, Error, error}; use parser; use atom::parse_symbol; use ast; pub struct Config<'a> { pub text2parse: &'a Text2Parse, pub rules: &'a Rules, } pub trait Parse { fn parse(&self, conf: &Config, status: parser::Status) -> Result<(parser::Status, ast::Node), Error>; } pub fn parse(conf: &Config, symbol: &Symbol, status: parser::Status) -> Result<(parser::Status, ast::Node), Error> { let final_result = parse_symbol(conf, symbol, status)?; match final_result.0.pos.n == conf.text2parse.0.len() { true => Ok(final_result), false => { match final_result.0.deep_error { Some(error) => Err(error), None => { Err(error(&final_result.0.pos, &format!("unexpected >{}<", conf.text2parse .0 .chars() .skip(final_result.0.pos.n) .take(conf.text2parse.0.len() - final_result.0.pos.n) .collect::<String>()), conf.text2parse)) } } } } } #[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Ord)] pub struct Possition { pub n: usize, pub row: usize, pub col: usize, } #[derive(Debug, PartialEq, Clone, PartialOrd)] pub struct Depth(pub u32); #[derive(Debug, PartialEq, Clone)] pub struct Status { pub pos: Possition, pub depth: Depth, pub deep_error: Option<Error>, } impl Status { pub fn new() -> Self { Status { pos: Possition::new(), depth: Depth(0), deep_error: None, } } pub fn inc_depth(&self) -> Self { Status { depth: Depth(self.depth.0 + 1),..self.clone() } } pub fn update_deep_error(mut self, error: &Error) -> Self { self.deep_error = match self.deep_error { Some(ref derr) => { if error.pos.n > derr.pos.n { Some(error.clone()) } else { self.deep_error.clone() } } None => Some(error.clone()), }; self } } impl Possition { pub fn new() -> Self { Possition { n: 0, col: 1, row: 1, } } fn
(&mut self, ch: char) -> &Self { match ch { '\n' => { self.n += 1; self.col = 0; self.row += 1; } _ => { self.n += 1; self.col += 1; } }; self } pub fn inc_char(&mut self, text2parse: &Text2Parse) -> &Self { let n = self.n; self.inc_ch(text2parse.0.chars().nth(n).unwrap_or('?')) } pub fn inc_chars(&mut self, s: &str) -> &Self { for ch in s.chars() { self.inc_ch(ch); } self } } pub mod tools { pub use atom::Atom; pub use expression::{Expression, MultiExpr, NRep}; pub fn lit(s: &str) -> Expression { Expression::Simple(Atom::Literal(s.to_owned())) } pub fn dot() -> Expression { Expression::Simple(Atom::Dot) } // fn nothing() -> Expression { // Expression::Simple(Atom::Nothing) // } pub fn or(exp_list: Vec<Expression>) -> Expression { Expression::Or(MultiExpr(exp_list)) } pub fn and(exp_list: Vec<Expression>) -> Expression { Expression::And(MultiExpr(exp_list)) } pub fn symref(s: &str) -> Expression { Expression::Simple(Atom::Symbol(s.to_owned())) } pub fn not(expr: Expression) -> Expression { Expression::Not(Box::new(expr)) } pub fn repeat(expr: Expression, min: NRep, max: Option<NRep>) -> Expression { Expression::Repeat(Box::new(expr), min, max) } pub fn match_ch(chars: &str, ranges: Vec<(char, char)>) -> Expression { Expression::Simple(Atom::Match(chars.to_owned(), ranges)) } }
inc_ch
identifier_name
parser.rs
use {Symbol, Rules, Text2Parse, Error, error}; use parser; use atom::parse_symbol; use ast; pub struct Config<'a> { pub text2parse: &'a Text2Parse, pub rules: &'a Rules, } pub trait Parse { fn parse(&self, conf: &Config, status: parser::Status) -> Result<(parser::Status, ast::Node), Error>; } pub fn parse(conf: &Config, symbol: &Symbol, status: parser::Status) -> Result<(parser::Status, ast::Node), Error> { let final_result = parse_symbol(conf, symbol, status)?; match final_result.0.pos.n == conf.text2parse.0.len() { true => Ok(final_result), false => { match final_result.0.deep_error { Some(error) => Err(error), None => { Err(error(&final_result.0.pos, &format!("unexpected >{}<", conf.text2parse .0 .chars() .skip(final_result.0.pos.n) .take(conf.text2parse.0.len() - final_result.0.pos.n) .collect::<String>()), conf.text2parse)) } } } } } #[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Ord)] pub struct Possition { pub n: usize, pub row: usize, pub col: usize, } #[derive(Debug, PartialEq, Clone, PartialOrd)] pub struct Depth(pub u32); #[derive(Debug, PartialEq, Clone)] pub struct Status { pub pos: Possition, pub depth: Depth, pub deep_error: Option<Error>, } impl Status { pub fn new() -> Self { Status { pos: Possition::new(), depth: Depth(0), deep_error: None,
} pub fn update_deep_error(mut self, error: &Error) -> Self { self.deep_error = match self.deep_error { Some(ref derr) => { if error.pos.n > derr.pos.n { Some(error.clone()) } else { self.deep_error.clone() } } None => Some(error.clone()), }; self } } impl Possition { pub fn new() -> Self { Possition { n: 0, col: 1, row: 1, } } fn inc_ch(&mut self, ch: char) -> &Self { match ch { '\n' => { self.n += 1; self.col = 0; self.row += 1; } _ => { self.n += 1; self.col += 1; } }; self } pub fn inc_char(&mut self, text2parse: &Text2Parse) -> &Self { let n = self.n; self.inc_ch(text2parse.0.chars().nth(n).unwrap_or('?')) } pub fn inc_chars(&mut self, s: &str) -> &Self { for ch in s.chars() { self.inc_ch(ch); } self } } pub mod tools { pub use atom::Atom; pub use expression::{Expression, MultiExpr, NRep}; pub fn lit(s: &str) -> Expression { Expression::Simple(Atom::Literal(s.to_owned())) } pub fn dot() -> Expression { Expression::Simple(Atom::Dot) } // fn nothing() -> Expression { // Expression::Simple(Atom::Nothing) // } pub fn or(exp_list: Vec<Expression>) -> Expression { Expression::Or(MultiExpr(exp_list)) } pub fn and(exp_list: Vec<Expression>) -> Expression { Expression::And(MultiExpr(exp_list)) } pub fn symref(s: &str) -> Expression { Expression::Simple(Atom::Symbol(s.to_owned())) } pub fn not(expr: Expression) -> Expression { Expression::Not(Box::new(expr)) } pub fn repeat(expr: Expression, min: NRep, max: Option<NRep>) -> Expression { Expression::Repeat(Box::new(expr), min, max) } pub fn match_ch(chars: &str, ranges: Vec<(char, char)>) -> Expression { Expression::Simple(Atom::Match(chars.to_owned(), ranges)) } }
} } pub fn inc_depth(&self) -> Self { Status { depth: Depth(self.depth.0 + 1), ..self.clone() }
random_line_split
parser.rs
use {Symbol, Rules, Text2Parse, Error, error}; use parser; use atom::parse_symbol; use ast; pub struct Config<'a> { pub text2parse: &'a Text2Parse, pub rules: &'a Rules, } pub trait Parse { fn parse(&self, conf: &Config, status: parser::Status) -> Result<(parser::Status, ast::Node), Error>; } pub fn parse(conf: &Config, symbol: &Symbol, status: parser::Status) -> Result<(parser::Status, ast::Node), Error> { let final_result = parse_symbol(conf, symbol, status)?; match final_result.0.pos.n == conf.text2parse.0.len() { true => Ok(final_result), false => { match final_result.0.deep_error { Some(error) => Err(error), None => { Err(error(&final_result.0.pos, &format!("unexpected >{}<", conf.text2parse .0 .chars() .skip(final_result.0.pos.n) .take(conf.text2parse.0.len() - final_result.0.pos.n) .collect::<String>()), conf.text2parse)) } } } } } #[derive(Debug, PartialEq, Clone, Eq, PartialOrd, Ord)] pub struct Possition { pub n: usize, pub row: usize, pub col: usize, } #[derive(Debug, PartialEq, Clone, PartialOrd)] pub struct Depth(pub u32); #[derive(Debug, PartialEq, Clone)] pub struct Status { pub pos: Possition, pub depth: Depth, pub deep_error: Option<Error>, } impl Status { pub fn new() -> Self { Status { pos: Possition::new(), depth: Depth(0), deep_error: None, } } pub fn inc_depth(&self) -> Self { Status { depth: Depth(self.depth.0 + 1),..self.clone() } } pub fn update_deep_error(mut self, error: &Error) -> Self { self.deep_error = match self.deep_error { Some(ref derr) => { if error.pos.n > derr.pos.n { Some(error.clone()) } else
} None => Some(error.clone()), }; self } } impl Possition { pub fn new() -> Self { Possition { n: 0, col: 1, row: 1, } } fn inc_ch(&mut self, ch: char) -> &Self { match ch { '\n' => { self.n += 1; self.col = 0; self.row += 1; } _ => { self.n += 1; self.col += 1; } }; self } pub fn inc_char(&mut self, text2parse: &Text2Parse) -> &Self { let n = self.n; self.inc_ch(text2parse.0.chars().nth(n).unwrap_or('?')) } pub fn inc_chars(&mut self, s: &str) -> &Self { for ch in s.chars() { self.inc_ch(ch); } self } } pub mod tools { pub use atom::Atom; pub use expression::{Expression, MultiExpr, NRep}; pub fn lit(s: &str) -> Expression { Expression::Simple(Atom::Literal(s.to_owned())) } pub fn dot() -> Expression { Expression::Simple(Atom::Dot) } // fn nothing() -> Expression { // Expression::Simple(Atom::Nothing) // } pub fn or(exp_list: Vec<Expression>) -> Expression { Expression::Or(MultiExpr(exp_list)) } pub fn and(exp_list: Vec<Expression>) -> Expression { Expression::And(MultiExpr(exp_list)) } pub fn symref(s: &str) -> Expression { Expression::Simple(Atom::Symbol(s.to_owned())) } pub fn not(expr: Expression) -> Expression { Expression::Not(Box::new(expr)) } pub fn repeat(expr: Expression, min: NRep, max: Option<NRep>) -> Expression { Expression::Repeat(Box::new(expr), min, max) } pub fn match_ch(chars: &str, ranges: Vec<(char, char)>) -> Expression { Expression::Simple(Atom::Match(chars.to_owned(), ranges)) } }
{ self.deep_error.clone() }
conditional_block
penneys_game.rs
// http://rosettacode.org/wiki/Penney's_game // H = true, T = false extern crate rand; use std::io::{stdout, stdin, Read, Write}; use std::thread; use std::time::Duration; use rand::{Rng, thread_rng}; fn toss_coin(print:bool) -> char { let c : char; if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'} if print { print!("{}",c); stdout().flush().ok().expect("Could not flush stdout"); } c } fn gen_sequence(seed : Option<&str>) -> String { let mut seq = String::new(); match seed { Some(s) => { let c0 = s.chars().next().unwrap(); if c0 == 'H' {seq.push('T') } else {seq.push('H')} seq.push(c0); seq.push(s.chars().nth(1).unwrap()); }, None => { for _ in 0..3 { seq.push(toss_coin(false)) } } } seq } fn read_sequence(used_seq : Option<&str>) -> String { let mut seq = String::new(); loop { seq.clear(); println!("Please, enter sequence of 3 coins: H (heads) or T (tails): "); stdin().read_line(&mut seq).ok().expect("failed to read line"); seq = seq.trim().to_uppercase(); if!( seq.chars().all(|c| c == 'H' || c == 'T') && seq.len() == 3 && seq!= used_seq.unwrap_or("")
continue; } return seq; } } fn main() { println!("--Penney's game--"); loop { let useq : String; let aiseq : String; if thread_rng().gen::<bool>() { println!("You choose first!"); useq = read_sequence(None); println!("Your sequence: {}", useq); aiseq = gen_sequence( Some(&useq) ); println!("My sequence: {}", aiseq); } else { println!("I choose first!"); aiseq = gen_sequence(None); println!("My sequence: {}", aiseq); useq = read_sequence(Some(&aiseq)); println!("Your sequence: {}", useq); } println!("Tossing coins..."); let mut coins = String::new(); for _ in 0..2 { //toss first 2 coins coins.push(toss_coin(true)); thread::sleep(Duration::from_millis(500)); } loop { coins.push(toss_coin(true)); thread::sleep(Duration::from_millis(500)); if coins.contains(&useq) { println!("\nYou win!"); break; } if coins.contains(&aiseq) { println!("\nI win!"); break; } } println!(" Play again? Y to play, Q to exit."); let mut input = String::new(); stdin().read_line(&mut input).ok().expect("failed to read line"); match input.chars().next().unwrap() { 'Y' | 'y' => continue, _ => break } } }
) { println!("Please enter correct sequence!");
random_line_split
penneys_game.rs
// http://rosettacode.org/wiki/Penney's_game // H = true, T = false extern crate rand; use std::io::{stdout, stdin, Read, Write}; use std::thread; use std::time::Duration; use rand::{Rng, thread_rng}; fn toss_coin(print:bool) -> char { let c : char; if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'} if print { print!("{}",c); stdout().flush().ok().expect("Could not flush stdout"); } c } fn gen_sequence(seed : Option<&str>) -> String { let mut seq = String::new(); match seed { Some(s) => { let c0 = s.chars().next().unwrap(); if c0 == 'H' {seq.push('T') } else {seq.push('H')} seq.push(c0); seq.push(s.chars().nth(1).unwrap()); }, None => { for _ in 0..3 { seq.push(toss_coin(false)) } } } seq } fn
(used_seq : Option<&str>) -> String { let mut seq = String::new(); loop { seq.clear(); println!("Please, enter sequence of 3 coins: H (heads) or T (tails): "); stdin().read_line(&mut seq).ok().expect("failed to read line"); seq = seq.trim().to_uppercase(); if!( seq.chars().all(|c| c == 'H' || c == 'T') && seq.len() == 3 && seq!= used_seq.unwrap_or("") ) { println!("Please enter correct sequence!"); continue; } return seq; } } fn main() { println!("--Penney's game--"); loop { let useq : String; let aiseq : String; if thread_rng().gen::<bool>() { println!("You choose first!"); useq = read_sequence(None); println!("Your sequence: {}", useq); aiseq = gen_sequence( Some(&useq) ); println!("My sequence: {}", aiseq); } else { println!("I choose first!"); aiseq = gen_sequence(None); println!("My sequence: {}", aiseq); useq = read_sequence(Some(&aiseq)); println!("Your sequence: {}", useq); } println!("Tossing coins..."); let mut coins = String::new(); for _ in 0..2 { //toss first 2 coins coins.push(toss_coin(true)); thread::sleep(Duration::from_millis(500)); } loop { coins.push(toss_coin(true)); thread::sleep(Duration::from_millis(500)); if coins.contains(&useq) { println!("\nYou win!"); break; } if coins.contains(&aiseq) { println!("\nI win!"); break; } } println!(" Play again? Y to play, Q to exit."); let mut input = String::new(); stdin().read_line(&mut input).ok().expect("failed to read line"); match input.chars().next().unwrap() { 'Y' | 'y' => continue, _ => break } } }
read_sequence
identifier_name
penneys_game.rs
// http://rosettacode.org/wiki/Penney's_game // H = true, T = false extern crate rand; use std::io::{stdout, stdin, Read, Write}; use std::thread; use std::time::Duration; use rand::{Rng, thread_rng}; fn toss_coin(print:bool) -> char { let c : char; if thread_rng().gen::<bool>() {c = 'H'} else {c = 'T'} if print { print!("{}",c); stdout().flush().ok().expect("Could not flush stdout"); } c } fn gen_sequence(seed : Option<&str>) -> String { let mut seq = String::new(); match seed { Some(s) => { let c0 = s.chars().next().unwrap(); if c0 == 'H' {seq.push('T') } else {seq.push('H')} seq.push(c0); seq.push(s.chars().nth(1).unwrap()); }, None => { for _ in 0..3 { seq.push(toss_coin(false)) } } } seq } fn read_sequence(used_seq : Option<&str>) -> String { let mut seq = String::new(); loop { seq.clear(); println!("Please, enter sequence of 3 coins: H (heads) or T (tails): "); stdin().read_line(&mut seq).ok().expect("failed to read line"); seq = seq.trim().to_uppercase(); if!( seq.chars().all(|c| c == 'H' || c == 'T') && seq.len() == 3 && seq!= used_seq.unwrap_or("") ) { println!("Please enter correct sequence!"); continue; } return seq; } } fn main()
for _ in 0..2 { //toss first 2 coins coins.push(toss_coin(true)); thread::sleep(Duration::from_millis(500)); } loop { coins.push(toss_coin(true)); thread::sleep(Duration::from_millis(500)); if coins.contains(&useq) { println!("\nYou win!"); break; } if coins.contains(&aiseq) { println!("\nI win!"); break; } } println!(" Play again? Y to play, Q to exit."); let mut input = String::new(); stdin().read_line(&mut input).ok().expect("failed to read line"); match input.chars().next().unwrap() { 'Y' | 'y' => continue, _ => break } } }
{ println!("--Penney's game--"); loop { let useq : String; let aiseq : String; if thread_rng().gen::<bool>() { println!("You choose first!"); useq = read_sequence(None); println!("Your sequence: {}", useq); aiseq = gen_sequence( Some(&useq) ); println!("My sequence: {}", aiseq); } else { println!("I choose first!"); aiseq = gen_sequence(None); println!("My sequence: {}", aiseq); useq = read_sequence(Some(&aiseq)); println!("Your sequence: {}", useq); } println!("Tossing coins..."); let mut coins = String::new();
identifier_body